2 (function (global, factory) {
3 typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) :
4 typeof define === 'function' && define.amd ? define(['exports'], factory) :
5 (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.THREE = {}));
6 }(this, (function (exports) { 'use strict';
9 if (Number.EPSILON === undefined) {
10 Number.EPSILON = Math.pow(2, -52);
13 if (Number.isInteger === undefined) {
15 // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isInteger
16 Number.isInteger = function (value) {
17 return typeof value === 'number' && isFinite(value) && Math.floor(value) === value;
22 if (Math.sign === undefined) {
23 // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/sign
24 Math.sign = function (x) {
25 return x < 0 ? -1 : x > 0 ? 1 : +x;
29 if ('name' in Function.prototype === false) {
31 // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/name
32 Object.defineProperty(Function.prototype, 'name', {
34 return this.toString().match(/^\s*function\s*([^\(\s]*)/)[1];
39 if (Object.assign === undefined) {
41 // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/assign
42 Object.assign = function (target) {
44 if (target === undefined || target === null) {
45 throw new TypeError('Cannot convert undefined or null to object');
48 var output = Object(target);
50 for (var index = 1; index < arguments.length; index++) {
51 var source = arguments[index];
53 if (source !== undefined && source !== null) {
54 for (var nextKey in source) {
55 if (Object.prototype.hasOwnProperty.call(source, nextKey)) {
56 output[nextKey] = source[nextKey];
67 * Copyright (c) 2014-present, Facebook, Inc.
69 * This source code is licensed under the MIT license found in the
70 * LICENSE file in the root directory of this source tree.
72 var runtime = function (exports) {
74 var Op = Object.prototype;
75 var hasOwn = Op.hasOwnProperty;
76 var undefined$1; // More compressible than void 0.
78 var $Symbol = typeof Symbol === "function" ? Symbol : {};
79 var iteratorSymbol = $Symbol.iterator || "@@iterator";
80 var asyncIteratorSymbol = $Symbol.asyncIterator || "@@asyncIterator";
81 var toStringTagSymbol = $Symbol.toStringTag || "@@toStringTag";
83 function define(obj, key, value) {
84 Object.defineProperty(obj, key, {
94 // IE 8 has a broken Object.defineProperty that only works on DOM objects.
97 define = function define(obj, key, value) {
98 return obj[key] = value;
102 function wrap(innerFn, outerFn, self, tryLocsList) {
103 // If outerFn provided and outerFn.prototype is a Generator, then outerFn.prototype instanceof Generator.
104 var protoGenerator = outerFn && outerFn.prototype instanceof Generator ? outerFn : Generator;
105 var generator = Object.create(protoGenerator.prototype);
106 var context = new Context(tryLocsList || []); // The ._invoke method unifies the implementations of the .next,
107 // .throw, and .return methods.
109 generator._invoke = makeInvokeMethod(innerFn, self, context);
113 exports.wrap = wrap; // Try/catch helper to minimize deoptimizations. Returns a completion
114 // record like context.tryEntries[i].completion. This interface could
115 // have been (and was previously) designed to take a closure to be
116 // invoked without arguments, but in all the cases we care about we
117 // already have an existing method we want to call, so there's no need
118 // to create a new function object. We can even get away with assuming
119 // the method takes exactly one argument, since that happens to be true
120 // in every case, so we don't have to touch the arguments object. The
121 // only additional allocation required is the completion record, which
122 // has a stable shape and so hopefully should be cheap to allocate.
124 function tryCatch(fn, obj, arg) {
128 arg: fn.call(obj, arg)
138 var GenStateSuspendedStart = "suspendedStart";
139 var GenStateSuspendedYield = "suspendedYield";
140 var GenStateExecuting = "executing";
141 var GenStateCompleted = "completed"; // Returning this object from the innerFn has the same effect as
142 // breaking out of the dispatch switch statement.
144 var ContinueSentinel = {}; // Dummy constructor functions that we use as the .constructor and
145 // .constructor.prototype properties for functions that return Generator
146 // objects. For full spec compliance, you may wish to configure your
147 // minifier not to mangle the names of these two functions.
149 function Generator() {}
151 function GeneratorFunction() {}
153 function GeneratorFunctionPrototype() {} // This is a polyfill for %IteratorPrototype% for environments that
154 // don't natively support it.
157 var IteratorPrototype = {};
159 IteratorPrototype[iteratorSymbol] = function () {
163 var getProto = Object.getPrototypeOf;
164 var NativeIteratorPrototype = getProto && getProto(getProto(values([])));
166 if (NativeIteratorPrototype && NativeIteratorPrototype !== Op && hasOwn.call(NativeIteratorPrototype, iteratorSymbol)) {
167 // This environment has a native %IteratorPrototype%; use it instead
169 IteratorPrototype = NativeIteratorPrototype;
172 var Gp = GeneratorFunctionPrototype.prototype = Generator.prototype = Object.create(IteratorPrototype);
173 GeneratorFunction.prototype = Gp.constructor = GeneratorFunctionPrototype;
174 GeneratorFunctionPrototype.constructor = GeneratorFunction;
175 GeneratorFunction.displayName = define(GeneratorFunctionPrototype, toStringTagSymbol, "GeneratorFunction"); // Helper for defining the .next, .throw, and .return methods of the
176 // Iterator interface in terms of a single ._invoke method.
178 function defineIteratorMethods(prototype) {
179 ["next", "throw", "return"].forEach(function (method) {
180 define(prototype, method, function (arg) {
181 return this._invoke(method, arg);
186 exports.isGeneratorFunction = function (genFun) {
187 var ctor = typeof genFun === "function" && genFun.constructor;
188 return ctor ? ctor === GeneratorFunction || // For the native GeneratorFunction constructor, the best we can
189 // do is to check its .name property.
190 (ctor.displayName || ctor.name) === "GeneratorFunction" : false;
193 exports.mark = function (genFun) {
194 if (Object.setPrototypeOf) {
195 Object.setPrototypeOf(genFun, GeneratorFunctionPrototype);
197 genFun.__proto__ = GeneratorFunctionPrototype;
198 define(genFun, toStringTagSymbol, "GeneratorFunction");
201 genFun.prototype = Object.create(Gp);
203 }; // Within the body of any async function, `await x` is transformed to
204 // `yield regeneratorRuntime.awrap(x)`, so that the runtime can test
205 // `hasOwn.call(value, "__await")` to determine if the yielded value is
206 // meant to be awaited.
209 exports.awrap = function (arg) {
215 function AsyncIterator(generator, PromiseImpl) {
216 function invoke(method, arg, resolve, reject) {
217 var record = tryCatch(generator[method], generator, arg);
219 if (record.type === "throw") {
222 var result = record.arg;
223 var value = result.value;
225 if (value && typeof value === "object" && hasOwn.call(value, "__await")) {
226 return PromiseImpl.resolve(value.__await).then(function (value) {
227 invoke("next", value, resolve, reject);
229 invoke("throw", err, resolve, reject);
233 return PromiseImpl.resolve(value).then(function (unwrapped) {
234 // When a yielded Promise is resolved, its final value becomes
235 // the .value of the Promise<{value,done}> result for the
236 // current iteration.
237 result.value = unwrapped;
239 }, function (error) {
240 // If a rejected Promise was yielded, throw the rejection back
241 // into the async generator function so it can be handled there.
242 return invoke("throw", error, resolve, reject);
249 function enqueue(method, arg) {
250 function callInvokeWithMethodAndArg() {
251 return new PromiseImpl(function (resolve, reject) {
252 invoke(method, arg, resolve, reject);
256 return previousPromise = // If enqueue has been called before, then we want to wait until
257 // all previous Promises have been resolved before calling invoke,
258 // so that results are always delivered in the correct order. If
259 // enqueue has not been called before, then it is important to
260 // call invoke immediately, without waiting on a callback to fire,
261 // so that the async generator function has the opportunity to do
262 // any necessary setup in a predictable way. This predictability
263 // is why the Promise constructor synchronously invokes its
264 // executor callback, and why async functions synchronously
265 // execute code before the first await. Since we implement simple
266 // async functions in terms of async generators, it is especially
267 // important to get this right, even though it requires care.
268 previousPromise ? previousPromise.then(callInvokeWithMethodAndArg, // Avoid propagating failures to Promises returned by later
269 // invocations of the iterator.
270 callInvokeWithMethodAndArg) : callInvokeWithMethodAndArg();
271 } // Define the unified helper method that is used to implement .next,
272 // .throw, and .return (see defineIteratorMethods).
275 this._invoke = enqueue;
278 defineIteratorMethods(AsyncIterator.prototype);
280 AsyncIterator.prototype[asyncIteratorSymbol] = function () {
284 exports.AsyncIterator = AsyncIterator; // Note that simple async functions are implemented on top of
285 // AsyncIterator objects; they just return a Promise for the value of
286 // the final result produced by the iterator.
288 exports.async = function (innerFn, outerFn, self, tryLocsList, PromiseImpl) {
289 if (PromiseImpl === void 0) PromiseImpl = Promise;
290 var iter = new AsyncIterator(wrap(innerFn, outerFn, self, tryLocsList), PromiseImpl);
291 return exports.isGeneratorFunction(outerFn) ? iter // If outerFn is a generator, return the full iterator.
292 : iter.next().then(function (result) {
293 return result.done ? result.value : iter.next();
297 function makeInvokeMethod(innerFn, self, context) {
298 var state = GenStateSuspendedStart;
299 return function invoke(method, arg) {
300 if (state === GenStateExecuting) {
301 throw new Error("Generator is already running");
304 if (state === GenStateCompleted) {
305 if (method === "throw") {
307 } // Be forgiving, per 25.3.3.3.3 of the spec:
308 // https://people.mozilla.org/~jorendorff/es6-draft.html#sec-generatorresume
314 context.method = method;
318 var delegate = context.delegate;
321 var delegateResult = maybeInvokeDelegate(delegate, context);
323 if (delegateResult) {
324 if (delegateResult === ContinueSentinel) continue;
325 return delegateResult;
329 if (context.method === "next") {
330 // Setting context._sent for legacy support of Babel's
331 // function.sent implementation.
332 context.sent = context._sent = context.arg;
333 } else if (context.method === "throw") {
334 if (state === GenStateSuspendedStart) {
335 state = GenStateCompleted;
339 context.dispatchException(context.arg);
340 } else if (context.method === "return") {
341 context.abrupt("return", context.arg);
344 state = GenStateExecuting;
345 var record = tryCatch(innerFn, self, context);
347 if (record.type === "normal") {
348 // If an exception is thrown from innerFn, we leave state ===
349 // GenStateExecuting and loop back for another invocation.
350 state = context.done ? GenStateCompleted : GenStateSuspendedYield;
352 if (record.arg === ContinueSentinel) {
360 } else if (record.type === "throw") {
361 state = GenStateCompleted; // Dispatch the exception by looping back around to the
362 // context.dispatchException(context.arg) call above.
364 context.method = "throw";
365 context.arg = record.arg;
369 } // Call delegate.iterator[context.method](context.arg) and handle the
370 // result, either by returning a { value, done } result from the
371 // delegate iterator, or by modifying context.method and context.arg,
372 // setting context.delegate to null, and returning the ContinueSentinel.
375 function maybeInvokeDelegate(delegate, context) {
376 var method = delegate.iterator[context.method];
378 if (method === undefined$1) {
379 // A .throw or .return when the delegate iterator has no .throw
380 // method always terminates the yield* loop.
381 context.delegate = null;
383 if (context.method === "throw") {
384 // Note: ["return"] must be used for ES3 parsing compatibility.
385 if (delegate.iterator["return"]) {
386 // If the delegate iterator has a return method, give it a
387 // chance to clean up.
388 context.method = "return";
389 context.arg = undefined$1;
390 maybeInvokeDelegate(delegate, context);
392 if (context.method === "throw") {
393 // If maybeInvokeDelegate(context) changed context.method from
394 // "return" to "throw", let that override the TypeError below.
395 return ContinueSentinel;
399 context.method = "throw";
400 context.arg = new TypeError("The iterator does not provide a 'throw' method");
403 return ContinueSentinel;
406 var record = tryCatch(method, delegate.iterator, context.arg);
408 if (record.type === "throw") {
409 context.method = "throw";
410 context.arg = record.arg;
411 context.delegate = null;
412 return ContinueSentinel;
415 var info = record.arg;
418 context.method = "throw";
419 context.arg = new TypeError("iterator result is not an object");
420 context.delegate = null;
421 return ContinueSentinel;
425 // Assign the result of the finished delegate to the temporary
426 // variable specified by delegate.resultName (see delegateYield).
427 context[delegate.resultName] = info.value; // Resume execution at the desired location (see delegateYield).
429 context.next = delegate.nextLoc; // If context.method was "throw" but the delegate handled the
430 // exception, let the outer generator proceed normally. If
431 // context.method was "next", forget context.arg since it has been
432 // "consumed" by the delegate iterator. If context.method was
433 // "return", allow the original .return call to continue in the
436 if (context.method !== "return") {
437 context.method = "next";
438 context.arg = undefined$1;
441 // Re-yield the result returned by the delegate method.
443 } // The delegate iterator is finished, so forget it and continue with
444 // the outer generator.
447 context.delegate = null;
448 return ContinueSentinel;
449 } // Define Generator.prototype.{next,throw,return} in terms of the
450 // unified ._invoke helper method.
453 defineIteratorMethods(Gp);
454 define(Gp, toStringTagSymbol, "Generator"); // A Generator should always return itself as the iterator object when the
455 // @@iterator function is called on it. Some browsers' implementations of the
456 // iterator prototype chain incorrectly implement this, causing the Generator
457 // object to not be returned from this call. This ensures that doesn't happen.
458 // See https://github.com/facebook/regenerator/issues/274 for more details.
460 Gp[iteratorSymbol] = function () {
464 Gp.toString = function () {
465 return "[object Generator]";
468 function pushTryEntry(locs) {
474 entry.catchLoc = locs[1];
478 entry.finallyLoc = locs[2];
479 entry.afterLoc = locs[3];
482 this.tryEntries.push(entry);
485 function resetTryEntry(entry) {
486 var record = entry.completion || {};
487 record.type = "normal";
489 entry.completion = record;
492 function Context(tryLocsList) {
493 // The root entry object (effectively a try statement without a catch
494 // or a finally block) gives us a place to store values thrown from
495 // locations where there is no enclosing try statement.
499 tryLocsList.forEach(pushTryEntry, this);
503 exports.keys = function (object) {
506 for (var key in object) {
510 keys.reverse(); // Rather than returning an object with a next method, we keep
511 // things simple and return the next function itself.
513 return function next() {
514 while (keys.length) {
515 var key = keys.pop();
522 } // To avoid creating an additional object, we just hang the .value
523 // and .done properties off the next function object itself. This
524 // also ensures that the minifier will not anonymize the function.
532 function values(iterable) {
534 var iteratorMethod = iterable[iteratorSymbol];
536 if (iteratorMethod) {
537 return iteratorMethod.call(iterable);
540 if (typeof iterable.next === "function") {
544 if (!isNaN(iterable.length)) {
546 next = function next() {
547 while (++i < iterable.length) {
548 if (hasOwn.call(iterable, i)) {
549 next.value = iterable[i];
555 next.value = undefined$1;
560 return next.next = next;
562 } // Return an iterator with no values.
570 exports.values = values;
572 function doneResult() {
579 Context.prototype = {
580 constructor: Context,
581 reset: function reset(skipTempReset) {
583 this.next = 0; // Resetting context._sent for legacy support of Babel's
584 // function.sent implementation.
586 this.sent = this._sent = undefined$1;
588 this.delegate = null;
589 this.method = "next";
590 this.arg = undefined$1;
591 this.tryEntries.forEach(resetTryEntry);
593 if (!skipTempReset) {
594 for (var name in this) {
595 // Not sure about the optimal order of these conditions:
596 if (name.charAt(0) === "t" && hasOwn.call(this, name) && !isNaN(+name.slice(1))) {
597 this[name] = undefined$1;
602 stop: function stop() {
604 var rootEntry = this.tryEntries[0];
605 var rootRecord = rootEntry.completion;
607 if (rootRecord.type === "throw") {
608 throw rootRecord.arg;
613 dispatchException: function dispatchException(exception) {
620 function handle(loc, caught) {
621 record.type = "throw";
622 record.arg = exception;
626 // If the dispatched exception was caught by a catch block,
627 // then let that catch block handle the exception normally.
628 context.method = "next";
629 context.arg = undefined$1;
635 for (var i = this.tryEntries.length - 1; i >= 0; --i) {
636 var entry = this.tryEntries[i];
637 var record = entry.completion;
639 if (entry.tryLoc === "root") {
640 // Exception thrown outside of any try block that could handle
641 // it, so set the completion value of the entire function to
642 // throw the exception.
643 return handle("end");
646 if (entry.tryLoc <= this.prev) {
647 var hasCatch = hasOwn.call(entry, "catchLoc");
648 var hasFinally = hasOwn.call(entry, "finallyLoc");
650 if (hasCatch && hasFinally) {
651 if (this.prev < entry.catchLoc) {
652 return handle(entry.catchLoc, true);
653 } else if (this.prev < entry.finallyLoc) {
654 return handle(entry.finallyLoc);
656 } else if (hasCatch) {
657 if (this.prev < entry.catchLoc) {
658 return handle(entry.catchLoc, true);
660 } else if (hasFinally) {
661 if (this.prev < entry.finallyLoc) {
662 return handle(entry.finallyLoc);
665 throw new Error("try statement without catch or finally");
670 abrupt: function abrupt(type, arg) {
671 for (var i = this.tryEntries.length - 1; i >= 0; --i) {
672 var entry = this.tryEntries[i];
674 if (entry.tryLoc <= this.prev && hasOwn.call(entry, "finallyLoc") && this.prev < entry.finallyLoc) {
675 var finallyEntry = entry;
680 if (finallyEntry && (type === "break" || type === "continue") && finallyEntry.tryLoc <= arg && arg <= finallyEntry.finallyLoc) {
681 // Ignore the finally entry if control is not jumping to a
682 // location outside the try/catch block.
686 var record = finallyEntry ? finallyEntry.completion : {};
691 this.method = "next";
692 this.next = finallyEntry.finallyLoc;
693 return ContinueSentinel;
696 return this.complete(record);
698 complete: function complete(record, afterLoc) {
699 if (record.type === "throw") {
703 if (record.type === "break" || record.type === "continue") {
704 this.next = record.arg;
705 } else if (record.type === "return") {
706 this.rval = this.arg = record.arg;
707 this.method = "return";
709 } else if (record.type === "normal" && afterLoc) {
710 this.next = afterLoc;
713 return ContinueSentinel;
715 finish: function finish(finallyLoc) {
716 for (var i = this.tryEntries.length - 1; i >= 0; --i) {
717 var entry = this.tryEntries[i];
719 if (entry.finallyLoc === finallyLoc) {
720 this.complete(entry.completion, entry.afterLoc);
721 resetTryEntry(entry);
722 return ContinueSentinel;
726 "catch": function _catch(tryLoc) {
727 for (var i = this.tryEntries.length - 1; i >= 0; --i) {
728 var entry = this.tryEntries[i];
730 if (entry.tryLoc === tryLoc) {
731 var record = entry.completion;
733 if (record.type === "throw") {
734 var thrown = record.arg;
735 resetTryEntry(entry);
740 } // The context.catch method must only be called with a location
741 // argument that corresponds to a known catch block.
744 throw new Error("illegal catch attempt");
746 delegateYield: function delegateYield(iterable, resultName, nextLoc) {
748 iterator: values(iterable),
749 resultName: resultName,
753 if (this.method === "next") {
754 // Deliberately forget the last sent value so that we don't
755 // accidentally pass it on to the delegate.
756 this.arg = undefined$1;
759 return ContinueSentinel;
761 }; // Regardless of whether this script is executing as a CommonJS module
762 // or not, return the runtime object so that we can declare the variable
763 // regeneratorRuntime in the outer scope, which allows this module to be
764 // injected easily by `bin/regenerator --include-runtime script.js`.
767 }( // If this script is executing as a CommonJS module, use module.exports
768 // as the regeneratorRuntime namespace. Otherwise create a new empty
769 // object. Either way, the resulting object will be used to initialize
770 // the regeneratorRuntime variable at the top of this file.
771 typeof module === "object" ? module.exports : {});
774 regeneratorRuntime = runtime;
775 } catch (accidentalStrictMode) {
776 // This module should not be running in strict mode, so the above
777 // assignment should always work unless something is misconfigured. Just
778 // in case runtime.js accidentally runs in strict mode, we can escape
779 // strict mode using a global Function call. This could conceivably fail
780 // if a Content Security Policy forbids using Function, but in that case
781 // the proper solution is to fix the accidental strict mode problem. If
782 // you've misconfigured your bundler to force strict mode and applied a
783 // CSP to forbid Function, and you're not willing to fix either of those
784 // problems, please detail your unique predicament in a GitHub issue.
785 Function("r", "regeneratorRuntime = r")(runtime);
788 var REVISION = '125';
803 var CullFaceNone = 0;
804 var CullFaceBack = 1;
805 var CullFaceFront = 2;
806 var CullFaceFrontBack = 3;
807 var BasicShadowMap = 0;
808 var PCFShadowMap = 1;
809 var PCFSoftShadowMap = 2;
810 var VSMShadowMap = 3;
815 var SmoothShading = 2;
817 var NormalBlending = 1;
818 var AdditiveBlending = 2;
819 var SubtractiveBlending = 3;
820 var MultiplyBlending = 4;
821 var CustomBlending = 5;
822 var AddEquation = 100;
823 var SubtractEquation = 101;
824 var ReverseSubtractEquation = 102;
825 var MinEquation = 103;
826 var MaxEquation = 104;
827 var ZeroFactor = 200;
829 var SrcColorFactor = 202;
830 var OneMinusSrcColorFactor = 203;
831 var SrcAlphaFactor = 204;
832 var OneMinusSrcAlphaFactor = 205;
833 var DstAlphaFactor = 206;
834 var OneMinusDstAlphaFactor = 207;
835 var DstColorFactor = 208;
836 var OneMinusDstColorFactor = 209;
837 var SrcAlphaSaturateFactor = 210;
841 var LessEqualDepth = 3;
843 var GreaterEqualDepth = 5;
844 var GreaterDepth = 6;
845 var NotEqualDepth = 7;
846 var MultiplyOperation = 0;
847 var MixOperation = 1;
848 var AddOperation = 2;
849 var NoToneMapping = 0;
850 var LinearToneMapping = 1;
851 var ReinhardToneMapping = 2;
852 var CineonToneMapping = 3;
853 var ACESFilmicToneMapping = 4;
854 var CustomToneMapping = 5;
856 var CubeReflectionMapping = 301;
857 var CubeRefractionMapping = 302;
858 var EquirectangularReflectionMapping = 303;
859 var EquirectangularRefractionMapping = 304;
860 var CubeUVReflectionMapping = 306;
861 var CubeUVRefractionMapping = 307;
862 var RepeatWrapping = 1000;
863 var ClampToEdgeWrapping = 1001;
864 var MirroredRepeatWrapping = 1002;
865 var NearestFilter = 1003;
866 var NearestMipmapNearestFilter = 1004;
867 var NearestMipMapNearestFilter = 1004;
868 var NearestMipmapLinearFilter = 1005;
869 var NearestMipMapLinearFilter = 1005;
870 var LinearFilter = 1006;
871 var LinearMipmapNearestFilter = 1007;
872 var LinearMipMapNearestFilter = 1007;
873 var LinearMipmapLinearFilter = 1008;
874 var LinearMipMapLinearFilter = 1008;
875 var UnsignedByteType = 1009;
877 var ShortType = 1011;
878 var UnsignedShortType = 1012;
880 var UnsignedIntType = 1014;
881 var FloatType = 1015;
882 var HalfFloatType = 1016;
883 var UnsignedShort4444Type = 1017;
884 var UnsignedShort5551Type = 1018;
885 var UnsignedShort565Type = 1019;
886 var UnsignedInt248Type = 1020;
887 var AlphaFormat = 1021;
888 var RGBFormat = 1022;
889 var RGBAFormat = 1023;
890 var LuminanceFormat = 1024;
891 var LuminanceAlphaFormat = 1025;
892 var RGBEFormat = RGBAFormat;
893 var DepthFormat = 1026;
894 var DepthStencilFormat = 1027;
895 var RedFormat = 1028;
896 var RedIntegerFormat = 1029;
898 var RGIntegerFormat = 1031;
899 var RGBIntegerFormat = 1032;
900 var RGBAIntegerFormat = 1033;
901 var RGB_S3TC_DXT1_Format = 33776;
902 var RGBA_S3TC_DXT1_Format = 33777;
903 var RGBA_S3TC_DXT3_Format = 33778;
904 var RGBA_S3TC_DXT5_Format = 33779;
905 var RGB_PVRTC_4BPPV1_Format = 35840;
906 var RGB_PVRTC_2BPPV1_Format = 35841;
907 var RGBA_PVRTC_4BPPV1_Format = 35842;
908 var RGBA_PVRTC_2BPPV1_Format = 35843;
909 var RGB_ETC1_Format = 36196;
910 var RGB_ETC2_Format = 37492;
911 var RGBA_ETC2_EAC_Format = 37496;
912 var RGBA_ASTC_4x4_Format = 37808;
913 var RGBA_ASTC_5x4_Format = 37809;
914 var RGBA_ASTC_5x5_Format = 37810;
915 var RGBA_ASTC_6x5_Format = 37811;
916 var RGBA_ASTC_6x6_Format = 37812;
917 var RGBA_ASTC_8x5_Format = 37813;
918 var RGBA_ASTC_8x6_Format = 37814;
919 var RGBA_ASTC_8x8_Format = 37815;
920 var RGBA_ASTC_10x5_Format = 37816;
921 var RGBA_ASTC_10x6_Format = 37817;
922 var RGBA_ASTC_10x8_Format = 37818;
923 var RGBA_ASTC_10x10_Format = 37819;
924 var RGBA_ASTC_12x10_Format = 37820;
925 var RGBA_ASTC_12x12_Format = 37821;
926 var RGBA_BPTC_Format = 36492;
927 var SRGB8_ALPHA8_ASTC_4x4_Format = 37840;
928 var SRGB8_ALPHA8_ASTC_5x4_Format = 37841;
929 var SRGB8_ALPHA8_ASTC_5x5_Format = 37842;
930 var SRGB8_ALPHA8_ASTC_6x5_Format = 37843;
931 var SRGB8_ALPHA8_ASTC_6x6_Format = 37844;
932 var SRGB8_ALPHA8_ASTC_8x5_Format = 37845;
933 var SRGB8_ALPHA8_ASTC_8x6_Format = 37846;
934 var SRGB8_ALPHA8_ASTC_8x8_Format = 37847;
935 var SRGB8_ALPHA8_ASTC_10x5_Format = 37848;
936 var SRGB8_ALPHA8_ASTC_10x6_Format = 37849;
937 var SRGB8_ALPHA8_ASTC_10x8_Format = 37850;
938 var SRGB8_ALPHA8_ASTC_10x10_Format = 37851;
939 var SRGB8_ALPHA8_ASTC_12x10_Format = 37852;
940 var SRGB8_ALPHA8_ASTC_12x12_Format = 37853;
942 var LoopRepeat = 2201;
943 var LoopPingPong = 2202;
944 var InterpolateDiscrete = 2300;
945 var InterpolateLinear = 2301;
946 var InterpolateSmooth = 2302;
947 var ZeroCurvatureEnding = 2400;
948 var ZeroSlopeEnding = 2401;
949 var WrapAroundEnding = 2402;
950 var NormalAnimationBlendMode = 2500;
951 var AdditiveAnimationBlendMode = 2501;
952 var TrianglesDrawMode = 0;
953 var TriangleStripDrawMode = 1;
954 var TriangleFanDrawMode = 2;
955 var LinearEncoding = 3000;
956 var sRGBEncoding = 3001;
957 var GammaEncoding = 3007;
958 var RGBEEncoding = 3002;
959 var LogLuvEncoding = 3003;
960 var RGBM7Encoding = 3004;
961 var RGBM16Encoding = 3005;
962 var RGBDEncoding = 3006;
963 var BasicDepthPacking = 3200;
964 var RGBADepthPacking = 3201;
965 var TangentSpaceNormalMap = 0;
966 var ObjectSpaceNormalMap = 1;
967 var ZeroStencilOp = 0;
968 var KeepStencilOp = 7680;
969 var ReplaceStencilOp = 7681;
970 var IncrementStencilOp = 7682;
971 var DecrementStencilOp = 7683;
972 var IncrementWrapStencilOp = 34055;
973 var DecrementWrapStencilOp = 34056;
974 var InvertStencilOp = 5386;
975 var NeverStencilFunc = 512;
976 var LessStencilFunc = 513;
977 var EqualStencilFunc = 514;
978 var LessEqualStencilFunc = 515;
979 var GreaterStencilFunc = 516;
980 var NotEqualStencilFunc = 517;
981 var GreaterEqualStencilFunc = 518;
982 var AlwaysStencilFunc = 519;
983 var StaticDrawUsage = 35044;
984 var DynamicDrawUsage = 35048;
985 var StreamDrawUsage = 35040;
986 var StaticReadUsage = 35045;
987 var DynamicReadUsage = 35049;
988 var StreamReadUsage = 35041;
989 var StaticCopyUsage = 35046;
990 var DynamicCopyUsage = 35050;
991 var StreamCopyUsage = 35042;
993 var GLSL3 = '300 es';
995 function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) {
997 var info = gen[key](arg);
998 var value = info.value;
1007 Promise.resolve(value).then(_next, _throw);
1011 function _asyncToGenerator(fn) {
1012 return function () {
1015 return new Promise(function (resolve, reject) {
1016 var gen = fn.apply(self, args);
1018 function _next(value) {
1019 asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value);
1022 function _throw(err) {
1023 asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err);
1031 function _defineProperties(target, props) {
1032 for (var i = 0; i < props.length; i++) {
1033 var descriptor = props[i];
1034 descriptor.enumerable = descriptor.enumerable || false;
1035 descriptor.configurable = true;
1036 if ("value" in descriptor) descriptor.writable = true;
1037 Object.defineProperty(target, descriptor.key, descriptor);
1041 function _createClass(Constructor, protoProps, staticProps) {
1042 if (protoProps) _defineProperties(Constructor.prototype, protoProps);
1043 if (staticProps) _defineProperties(Constructor, staticProps);
1047 function _inheritsLoose(subClass, superClass) {
1048 subClass.prototype = Object.create(superClass.prototype);
1049 subClass.prototype.constructor = subClass;
1050 subClass.__proto__ = superClass;
1053 function _assertThisInitialized(self) {
1054 if (self === void 0) {
1055 throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
1061 function _unsupportedIterableToArray(o, minLen) {
1063 if (typeof o === "string") return _arrayLikeToArray(o, minLen);
1064 var n = Object.prototype.toString.call(o).slice(8, -1);
1065 if (n === "Object" && o.constructor) n = o.constructor.name;
1066 if (n === "Map" || n === "Set") return Array.from(o);
1067 if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen);
1070 function _arrayLikeToArray(arr, len) {
1071 if (len == null || len > arr.length) len = arr.length;
1073 for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i];
1078 function _createForOfIteratorHelperLoose(o, allowArrayLike) {
1081 if (typeof Symbol === "undefined" || o[Symbol.iterator] == null) {
1082 if (Array.isArray(o) || (it = _unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === "number") {
1085 return function () {
1086 if (i >= o.length) return {
1096 throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
1099 it = o[Symbol.iterator]();
1100 return it.next.bind(it);
1104 * https://github.com/mrdoob/eventdispatcher.js/
1106 function EventDispatcher() {}
1108 Object.assign(EventDispatcher.prototype, {
1109 addEventListener: function addEventListener(type, listener) {
1110 if (this._listeners === undefined) this._listeners = {};
1111 var listeners = this._listeners;
1113 if (listeners[type] === undefined) {
1114 listeners[type] = [];
1117 if (listeners[type].indexOf(listener) === -1) {
1118 listeners[type].push(listener);
1121 hasEventListener: function hasEventListener(type, listener) {
1122 if (this._listeners === undefined) return false;
1123 var listeners = this._listeners;
1124 return listeners[type] !== undefined && listeners[type].indexOf(listener) !== -1;
1126 removeEventListener: function removeEventListener(type, listener) {
1127 if (this._listeners === undefined) return;
1128 var listeners = this._listeners;
1129 var listenerArray = listeners[type];
1131 if (listenerArray !== undefined) {
1132 var index = listenerArray.indexOf(listener);
1135 listenerArray.splice(index, 1);
1139 dispatchEvent: function dispatchEvent(event) {
1140 if (this._listeners === undefined) return;
1141 var listeners = this._listeners;
1142 var listenerArray = listeners[event.type];
1144 if (listenerArray !== undefined) {
1145 event.target = this; // Make a copy, in case listeners are removed while iterating.
1147 var array = listenerArray.slice(0);
1149 for (var i = 0, l = array.length; i < l; i++) {
1150 array[i].call(this, event);
1158 for (var i = 0; i < 256; i++) {
1159 _lut[i] = (i < 16 ? '0' : '') + i.toString(16);
1162 var _seed = 1234567;
1164 DEG2RAD: Math.PI / 180,
1165 RAD2DEG: 180 / Math.PI,
1166 generateUUID: function generateUUID() {
1167 // http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/21963136#21963136
1168 var d0 = Math.random() * 0xffffffff | 0;
1169 var d1 = Math.random() * 0xffffffff | 0;
1170 var d2 = Math.random() * 0xffffffff | 0;
1171 var d3 = Math.random() * 0xffffffff | 0;
1172 var uuid = _lut[d0 & 0xff] + _lut[d0 >> 8 & 0xff] + _lut[d0 >> 16 & 0xff] + _lut[d0 >> 24 & 0xff] + '-' + _lut[d1 & 0xff] + _lut[d1 >> 8 & 0xff] + '-' + _lut[d1 >> 16 & 0x0f | 0x40] + _lut[d1 >> 24 & 0xff] + '-' + _lut[d2 & 0x3f | 0x80] + _lut[d2 >> 8 & 0xff] + '-' + _lut[d2 >> 16 & 0xff] + _lut[d2 >> 24 & 0xff] + _lut[d3 & 0xff] + _lut[d3 >> 8 & 0xff] + _lut[d3 >> 16 & 0xff] + _lut[d3 >> 24 & 0xff]; // .toUpperCase() here flattens concatenated strings to save heap memory space.
1174 return uuid.toUpperCase();
1176 clamp: function clamp(value, min, max) {
1177 return Math.max(min, Math.min(max, value));
1179 // compute euclidian modulo of m % n
1180 // https://en.wikipedia.org/wiki/Modulo_operation
1181 euclideanModulo: function euclideanModulo(n, m) {
1182 return (n % m + m) % m;
1184 // Linear mapping from range <a1, a2> to range <b1, b2>
1185 mapLinear: function mapLinear(x, a1, a2, b1, b2) {
1186 return b1 + (x - a1) * (b2 - b1) / (a2 - a1);
1188 // https://en.wikipedia.org/wiki/Linear_interpolation
1189 lerp: function lerp(x, y, t) {
1190 return (1 - t) * x + t * y;
1192 // http://www.rorydriscoll.com/2016/03/07/frame-rate-independent-damping-using-lerp/
1193 damp: function damp(x, y, lambda, dt) {
1194 return MathUtils.lerp(x, y, 1 - Math.exp(-lambda * dt));
1196 // https://www.desmos.com/calculator/vcsjnyz7x4
1197 pingpong: function pingpong(x, length) {
1198 if (length === void 0) {
1202 return length - Math.abs(MathUtils.euclideanModulo(x, length * 2) - length);
1204 // http://en.wikipedia.org/wiki/Smoothstep
1205 smoothstep: function smoothstep(x, min, max) {
1206 if (x <= min) return 0;
1207 if (x >= max) return 1;
1208 x = (x - min) / (max - min);
1209 return x * x * (3 - 2 * x);
1211 smootherstep: function smootherstep(x, min, max) {
1212 if (x <= min) return 0;
1213 if (x >= max) return 1;
1214 x = (x - min) / (max - min);
1215 return x * x * x * (x * (x * 6 - 15) + 10);
1217 // Random integer from <low, high> interval
1218 randInt: function randInt(low, high) {
1219 return low + Math.floor(Math.random() * (high - low + 1));
1221 // Random float from <low, high> interval
1222 randFloat: function randFloat(low, high) {
1223 return low + Math.random() * (high - low);
1225 // Random float from <-range/2, range/2> interval
1226 randFloatSpread: function randFloatSpread(range) {
1227 return range * (0.5 - Math.random());
1229 // Deterministic pseudo-random float in the interval [ 0, 1 ]
1230 seededRandom: function seededRandom(s) {
1231 if (s !== undefined) _seed = s % 2147483647; // Park-Miller algorithm
1233 _seed = _seed * 16807 % 2147483647;
1234 return (_seed - 1) / 2147483646;
1236 degToRad: function degToRad(degrees) {
1237 return degrees * MathUtils.DEG2RAD;
1239 radToDeg: function radToDeg(radians) {
1240 return radians * MathUtils.RAD2DEG;
1242 isPowerOfTwo: function isPowerOfTwo(value) {
1243 return (value & value - 1) === 0 && value !== 0;
1245 ceilPowerOfTwo: function ceilPowerOfTwo(value) {
1246 return Math.pow(2, Math.ceil(Math.log(value) / Math.LN2));
1248 floorPowerOfTwo: function floorPowerOfTwo(value) {
1249 return Math.pow(2, Math.floor(Math.log(value) / Math.LN2));
1251 setQuaternionFromProperEuler: function setQuaternionFromProperEuler(q, a, b, c, order) {
1252 // Intrinsic Proper Euler Angles - see https://en.wikipedia.org/wiki/Euler_angles
1253 // rotations are applied to the axes in the order specified by 'order'
1254 // rotation by angle 'a' is applied first, then by angle 'b', then by angle 'c'
1255 // angles are in radians
1258 var c2 = cos(b / 2);
1259 var s2 = sin(b / 2);
1260 var c13 = cos((a + c) / 2);
1261 var s13 = sin((a + c) / 2);
1262 var c1_3 = cos((a - c) / 2);
1263 var s1_3 = sin((a - c) / 2);
1264 var c3_1 = cos((c - a) / 2);
1265 var s3_1 = sin((c - a) / 2);
1269 q.set(c2 * s13, s2 * c1_3, s2 * s1_3, c2 * c13);
1273 q.set(s2 * s1_3, c2 * s13, s2 * c1_3, c2 * c13);
1277 q.set(s2 * c1_3, s2 * s1_3, c2 * s13, c2 * c13);
1281 q.set(c2 * s13, s2 * s3_1, s2 * c3_1, c2 * c13);
1285 q.set(s2 * c3_1, c2 * s13, s2 * s3_1, c2 * c13);
1289 q.set(s2 * s3_1, s2 * c3_1, c2 * s13, c2 * c13);
1293 console.warn('THREE.MathUtils: .setQuaternionFromProperEuler() encountered an unknown order: ' + order);
1298 var Vector2 = /*#__PURE__*/function () {
1299 function Vector2(x, y) {
1308 Object.defineProperty(this, 'isVector2', {
1315 var _proto = Vector2.prototype;
1317 _proto.set = function set(x, y) {
1323 _proto.setScalar = function setScalar(scalar) {
1329 _proto.setX = function setX(x) {
1334 _proto.setY = function setY(y) {
1339 _proto.setComponent = function setComponent(index, value) {
1350 throw new Error('index is out of range: ' + index);
1356 _proto.getComponent = function getComponent(index) {
1365 throw new Error('index is out of range: ' + index);
1369 _proto.clone = function clone() {
1370 return new this.constructor(this.x, this.y);
1373 _proto.copy = function copy(v) {
1379 _proto.add = function add(v, w) {
1380 if (w !== undefined) {
1381 console.warn('THREE.Vector2: .add() now only accepts one argument. Use .addVectors( a, b ) instead.');
1382 return this.addVectors(v, w);
1390 _proto.addScalar = function addScalar(s) {
1396 _proto.addVectors = function addVectors(a, b) {
1402 _proto.addScaledVector = function addScaledVector(v, s) {
1408 _proto.sub = function sub(v, w) {
1409 if (w !== undefined) {
1410 console.warn('THREE.Vector2: .sub() now only accepts one argument. Use .subVectors( a, b ) instead.');
1411 return this.subVectors(v, w);
1419 _proto.subScalar = function subScalar(s) {
1425 _proto.subVectors = function subVectors(a, b) {
1431 _proto.multiply = function multiply(v) {
1437 _proto.multiplyScalar = function multiplyScalar(scalar) {
1443 _proto.divide = function divide(v) {
1449 _proto.divideScalar = function divideScalar(scalar) {
1450 return this.multiplyScalar(1 / scalar);
1453 _proto.applyMatrix3 = function applyMatrix3(m) {
1457 this.x = e[0] * x + e[3] * y + e[6];
1458 this.y = e[1] * x + e[4] * y + e[7];
1462 _proto.min = function min(v) {
1463 this.x = Math.min(this.x, v.x);
1464 this.y = Math.min(this.y, v.y);
1468 _proto.max = function max(v) {
1469 this.x = Math.max(this.x, v.x);
1470 this.y = Math.max(this.y, v.y);
1474 _proto.clamp = function clamp(min, max) {
1475 // assumes min < max, componentwise
1476 this.x = Math.max(min.x, Math.min(max.x, this.x));
1477 this.y = Math.max(min.y, Math.min(max.y, this.y));
1481 _proto.clampScalar = function clampScalar(minVal, maxVal) {
1482 this.x = Math.max(minVal, Math.min(maxVal, this.x));
1483 this.y = Math.max(minVal, Math.min(maxVal, this.y));
1487 _proto.clampLength = function clampLength(min, max) {
1488 var length = this.length();
1489 return this.divideScalar(length || 1).multiplyScalar(Math.max(min, Math.min(max, length)));
1492 _proto.floor = function floor() {
1493 this.x = Math.floor(this.x);
1494 this.y = Math.floor(this.y);
1498 _proto.ceil = function ceil() {
1499 this.x = Math.ceil(this.x);
1500 this.y = Math.ceil(this.y);
1504 _proto.round = function round() {
1505 this.x = Math.round(this.x);
1506 this.y = Math.round(this.y);
1510 _proto.roundToZero = function roundToZero() {
1511 this.x = this.x < 0 ? Math.ceil(this.x) : Math.floor(this.x);
1512 this.y = this.y < 0 ? Math.ceil(this.y) : Math.floor(this.y);
1516 _proto.negate = function negate() {
1522 _proto.dot = function dot(v) {
1523 return this.x * v.x + this.y * v.y;
1526 _proto.cross = function cross(v) {
1527 return this.x * v.y - this.y * v.x;
1530 _proto.lengthSq = function lengthSq() {
1531 return this.x * this.x + this.y * this.y;
1534 _proto.length = function length() {
1535 return Math.sqrt(this.x * this.x + this.y * this.y);
1538 _proto.manhattanLength = function manhattanLength() {
1539 return Math.abs(this.x) + Math.abs(this.y);
1542 _proto.normalize = function normalize() {
1543 return this.divideScalar(this.length() || 1);
1546 _proto.angle = function angle() {
1547 // computes the angle in radians with respect to the positive x-axis
1548 var angle = Math.atan2(-this.y, -this.x) + Math.PI;
1552 _proto.distanceTo = function distanceTo(v) {
1553 return Math.sqrt(this.distanceToSquared(v));
1556 _proto.distanceToSquared = function distanceToSquared(v) {
1557 var dx = this.x - v.x,
1559 return dx * dx + dy * dy;
1562 _proto.manhattanDistanceTo = function manhattanDistanceTo(v) {
1563 return Math.abs(this.x - v.x) + Math.abs(this.y - v.y);
1566 _proto.setLength = function setLength(length) {
1567 return this.normalize().multiplyScalar(length);
1570 _proto.lerp = function lerp(v, alpha) {
1571 this.x += (v.x - this.x) * alpha;
1572 this.y += (v.y - this.y) * alpha;
1576 _proto.lerpVectors = function lerpVectors(v1, v2, alpha) {
1577 this.x = v1.x + (v2.x - v1.x) * alpha;
1578 this.y = v1.y + (v2.y - v1.y) * alpha;
1582 _proto.equals = function equals(v) {
1583 return v.x === this.x && v.y === this.y;
1586 _proto.fromArray = function fromArray(array, offset) {
1587 if (offset === void 0) {
1591 this.x = array[offset];
1592 this.y = array[offset + 1];
1596 _proto.toArray = function toArray(array, offset) {
1597 if (array === void 0) {
1601 if (offset === void 0) {
1605 array[offset] = this.x;
1606 array[offset + 1] = this.y;
1610 _proto.fromBufferAttribute = function fromBufferAttribute(attribute, index, offset) {
1611 if (offset !== undefined) {
1612 console.warn('THREE.Vector2: offset has been removed from .fromBufferAttribute().');
1615 this.x = attribute.getX(index);
1616 this.y = attribute.getY(index);
1620 _proto.rotateAround = function rotateAround(center, angle) {
1621 var c = Math.cos(angle),
1622 s = Math.sin(angle);
1623 var x = this.x - center.x;
1624 var y = this.y - center.y;
1625 this.x = x * c - y * s + center.x;
1626 this.y = x * s + y * c + center.y;
1630 _proto.random = function random() {
1631 this.x = Math.random();
1632 this.y = Math.random();
1636 _createClass(Vector2, [{
1638 get: function get() {
1641 set: function set(value) {
1646 get: function get() {
1649 set: function set(value) {
1657 var Matrix3 = /*#__PURE__*/function () {
1658 function Matrix3() {
1659 Object.defineProperty(this, 'isMatrix3', {
1662 this.elements = [1, 0, 0, 0, 1, 0, 0, 0, 1];
1664 if (arguments.length > 0) {
1665 console.error('THREE.Matrix3: the constructor no longer reads arguments. use .set() instead.');
1669 var _proto = Matrix3.prototype;
1671 _proto.set = function set(n11, n12, n13, n21, n22, n23, n31, n32, n33) {
1672 var te = this.elements;
1685 _proto.identity = function identity() {
1686 this.set(1, 0, 0, 0, 1, 0, 0, 0, 1);
1690 _proto.clone = function clone() {
1691 return new this.constructor().fromArray(this.elements);
1694 _proto.copy = function copy(m) {
1695 var te = this.elements;
1696 var me = m.elements;
1709 _proto.extractBasis = function extractBasis(xAxis, yAxis, zAxis) {
1710 xAxis.setFromMatrix3Column(this, 0);
1711 yAxis.setFromMatrix3Column(this, 1);
1712 zAxis.setFromMatrix3Column(this, 2);
1716 _proto.setFromMatrix4 = function setFromMatrix4(m) {
1717 var me = m.elements;
1718 this.set(me[0], me[4], me[8], me[1], me[5], me[9], me[2], me[6], me[10]);
1722 _proto.multiply = function multiply(m) {
1723 return this.multiplyMatrices(this, m);
1726 _proto.premultiply = function premultiply(m) {
1727 return this.multiplyMatrices(m, this);
1730 _proto.multiplyMatrices = function multiplyMatrices(a, b) {
1731 var ae = a.elements;
1732 var be = b.elements;
1733 var te = this.elements;
1752 te[0] = a11 * b11 + a12 * b21 + a13 * b31;
1753 te[3] = a11 * b12 + a12 * b22 + a13 * b32;
1754 te[6] = a11 * b13 + a12 * b23 + a13 * b33;
1755 te[1] = a21 * b11 + a22 * b21 + a23 * b31;
1756 te[4] = a21 * b12 + a22 * b22 + a23 * b32;
1757 te[7] = a21 * b13 + a22 * b23 + a23 * b33;
1758 te[2] = a31 * b11 + a32 * b21 + a33 * b31;
1759 te[5] = a31 * b12 + a32 * b22 + a33 * b32;
1760 te[8] = a31 * b13 + a32 * b23 + a33 * b33;
1764 _proto.multiplyScalar = function multiplyScalar(s) {
1765 var te = this.elements;
1778 _proto.determinant = function determinant() {
1779 var te = this.elements;
1789 return a * e * i - a * f * h - b * d * i + b * f * g + c * d * h - c * e * g;
1792 _proto.invert = function invert() {
1793 var te = this.elements,
1803 t11 = n33 * n22 - n32 * n23,
1804 t12 = n32 * n13 - n33 * n12,
1805 t13 = n23 * n12 - n22 * n13,
1806 det = n11 * t11 + n21 * t12 + n31 * t13;
1807 if (det === 0) return this.set(0, 0, 0, 0, 0, 0, 0, 0, 0);
1808 var detInv = 1 / det;
1809 te[0] = t11 * detInv;
1810 te[1] = (n31 * n23 - n33 * n21) * detInv;
1811 te[2] = (n32 * n21 - n31 * n22) * detInv;
1812 te[3] = t12 * detInv;
1813 te[4] = (n33 * n11 - n31 * n13) * detInv;
1814 te[5] = (n31 * n12 - n32 * n11) * detInv;
1815 te[6] = t13 * detInv;
1816 te[7] = (n21 * n13 - n23 * n11) * detInv;
1817 te[8] = (n22 * n11 - n21 * n12) * detInv;
1821 _proto.transpose = function transpose() {
1823 var m = this.elements;
1836 _proto.getNormalMatrix = function getNormalMatrix(matrix4) {
1837 return this.setFromMatrix4(matrix4).copy(this).invert().transpose();
1840 _proto.transposeIntoArray = function transposeIntoArray(r) {
1841 var m = this.elements;
1854 _proto.setUvTransform = function setUvTransform(tx, ty, sx, sy, rotation, cx, cy) {
1855 var c = Math.cos(rotation);
1856 var s = Math.sin(rotation);
1857 this.set(sx * c, sx * s, -sx * (c * cx + s * cy) + cx + tx, -sy * s, sy * c, -sy * (-s * cx + c * cy) + cy + ty, 0, 0, 1);
1861 _proto.scale = function scale(sx, sy) {
1862 var te = this.elements;
1872 _proto.rotate = function rotate(theta) {
1873 var c = Math.cos(theta);
1874 var s = Math.sin(theta);
1875 var te = this.elements;
1882 te[0] = c * a11 + s * a21;
1883 te[3] = c * a12 + s * a22;
1884 te[6] = c * a13 + s * a23;
1885 te[1] = -s * a11 + c * a21;
1886 te[4] = -s * a12 + c * a22;
1887 te[7] = -s * a13 + c * a23;
1891 _proto.translate = function translate(tx, ty) {
1892 var te = this.elements;
1893 te[0] += tx * te[2];
1894 te[3] += tx * te[5];
1895 te[6] += tx * te[8];
1896 te[1] += ty * te[2];
1897 te[4] += ty * te[5];
1898 te[7] += ty * te[8];
1902 _proto.equals = function equals(matrix) {
1903 var te = this.elements;
1904 var me = matrix.elements;
1906 for (var i = 0; i < 9; i++) {
1907 if (te[i] !== me[i]) return false;
1913 _proto.fromArray = function fromArray(array, offset) {
1914 if (offset === void 0) {
1918 for (var i = 0; i < 9; i++) {
1919 this.elements[i] = array[i + offset];
1925 _proto.toArray = function toArray(array, offset) {
1926 if (array === void 0) {
1930 if (offset === void 0) {
1934 var te = this.elements;
1935 array[offset] = te[0];
1936 array[offset + 1] = te[1];
1937 array[offset + 2] = te[2];
1938 array[offset + 3] = te[3];
1939 array[offset + 4] = te[4];
1940 array[offset + 5] = te[5];
1941 array[offset + 6] = te[6];
1942 array[offset + 7] = te[7];
1943 array[offset + 8] = te[8];
1953 getDataURL: function getDataURL(image) {
1954 if (/^data:/i.test(image.src)) {
1958 if (typeof HTMLCanvasElement == 'undefined') {
1964 if (image instanceof HTMLCanvasElement) {
1967 if (_canvas === undefined) _canvas = document.createElementNS('http://www.w3.org/1999/xhtml', 'canvas');
1968 _canvas.width = image.width;
1969 _canvas.height = image.height;
1971 var context = _canvas.getContext('2d');
1973 if (image instanceof ImageData) {
1974 context.putImageData(image, 0, 0);
1976 context.drawImage(image, 0, 0, image.width, image.height);
1982 if (canvas.width > 2048 || canvas.height > 2048) {
1983 return canvas.toDataURL('image/jpeg', 0.6);
1985 return canvas.toDataURL('image/png');
1992 function Texture(image, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding) {
1993 if (image === void 0) {
1994 image = Texture.DEFAULT_IMAGE;
1997 if (mapping === void 0) {
1998 mapping = Texture.DEFAULT_MAPPING;
2001 if (wrapS === void 0) {
2002 wrapS = ClampToEdgeWrapping;
2005 if (wrapT === void 0) {
2006 wrapT = ClampToEdgeWrapping;
2009 if (magFilter === void 0) {
2010 magFilter = LinearFilter;
2013 if (minFilter === void 0) {
2014 minFilter = LinearMipmapLinearFilter;
2017 if (format === void 0) {
2018 format = RGBAFormat;
2021 if (type === void 0) {
2022 type = UnsignedByteType;
2025 if (anisotropy === void 0) {
2029 if (encoding === void 0) {
2030 encoding = LinearEncoding;
2033 Object.defineProperty(this, 'id', {
2036 this.uuid = MathUtils.generateUUID();
2040 this.mapping = mapping;
2043 this.magFilter = magFilter;
2044 this.minFilter = minFilter;
2045 this.anisotropy = anisotropy;
2046 this.format = format;
2047 this.internalFormat = null;
2049 this.offset = new Vector2(0, 0);
2050 this.repeat = new Vector2(1, 1);
2051 this.center = new Vector2(0, 0);
2053 this.matrixAutoUpdate = true;
2054 this.matrix = new Matrix3();
2055 this.generateMipmaps = true;
2056 this.premultiplyAlpha = false;
2058 this.unpackAlignment = 4; // valid values: 1, 2, 4, 8 (see http://www.khronos.org/opengles/sdk/docs/man/xhtml/glPixelStorei.xml)
2059 // Values of encoding !== THREE.LinearEncoding only supported on map, envMap and emissiveMap.
2061 // Also changing the encoding after already used by a Material will not automatically make the Material
2062 // update. You need to explicitly call Material.needsUpdate to trigger it to recompile.
2064 this.encoding = encoding;
2066 this.onUpdate = null;
2069 Texture.DEFAULT_IMAGE = undefined;
2070 Texture.DEFAULT_MAPPING = UVMapping;
2071 Texture.prototype = Object.assign(Object.create(EventDispatcher.prototype), {
2072 constructor: Texture,
2074 updateMatrix: function updateMatrix() {
2075 this.matrix.setUvTransform(this.offset.x, this.offset.y, this.repeat.x, this.repeat.y, this.rotation, this.center.x, this.center.y);
2077 clone: function clone() {
2078 return new this.constructor().copy(this);
2080 copy: function copy(source) {
2081 this.name = source.name;
2082 this.image = source.image;
2083 this.mipmaps = source.mipmaps.slice(0);
2084 this.mapping = source.mapping;
2085 this.wrapS = source.wrapS;
2086 this.wrapT = source.wrapT;
2087 this.magFilter = source.magFilter;
2088 this.minFilter = source.minFilter;
2089 this.anisotropy = source.anisotropy;
2090 this.format = source.format;
2091 this.internalFormat = source.internalFormat;
2092 this.type = source.type;
2093 this.offset.copy(source.offset);
2094 this.repeat.copy(source.repeat);
2095 this.center.copy(source.center);
2096 this.rotation = source.rotation;
2097 this.matrixAutoUpdate = source.matrixAutoUpdate;
2098 this.matrix.copy(source.matrix);
2099 this.generateMipmaps = source.generateMipmaps;
2100 this.premultiplyAlpha = source.premultiplyAlpha;
2101 this.flipY = source.flipY;
2102 this.unpackAlignment = source.unpackAlignment;
2103 this.encoding = source.encoding;
2106 toJSON: function toJSON(meta) {
2107 var isRootObject = meta === undefined || typeof meta === 'string';
2109 if (!isRootObject && meta.textures[this.uuid] !== undefined) {
2110 return meta.textures[this.uuid];
2117 generator: 'Texture.toJSON'
2121 mapping: this.mapping,
2122 repeat: [this.repeat.x, this.repeat.y],
2123 offset: [this.offset.x, this.offset.y],
2124 center: [this.center.x, this.center.y],
2125 rotation: this.rotation,
2126 wrap: [this.wrapS, this.wrapT],
2127 format: this.format,
2129 encoding: this.encoding,
2130 minFilter: this.minFilter,
2131 magFilter: this.magFilter,
2132 anisotropy: this.anisotropy,
2134 premultiplyAlpha: this.premultiplyAlpha,
2135 unpackAlignment: this.unpackAlignment
2138 if (this.image !== undefined) {
2139 // TODO: Move to THREE.Image
2140 var image = this.image;
2142 if (image.uuid === undefined) {
2143 image.uuid = MathUtils.generateUUID(); // UGH
2146 if (!isRootObject && meta.images[image.uuid] === undefined) {
2149 if (Array.isArray(image)) {
2150 // process array of images e.g. CubeTexture
2153 for (var i = 0, l = image.length; i < l; i++) {
2154 // check cube texture with data textures
2155 if (image[i].isDataTexture) {
2156 url.push(serializeImage(image[i].image));
2158 url.push(serializeImage(image[i]));
2162 // process single image
2163 url = serializeImage(image);
2166 meta.images[image.uuid] = {
2172 output.image = image.uuid;
2175 if (!isRootObject) {
2176 meta.textures[this.uuid] = output;
2181 dispose: function dispose() {
2182 this.dispatchEvent({
2186 transformUv: function transformUv(uv) {
2187 if (this.mapping !== UVMapping) return uv;
2188 uv.applyMatrix3(this.matrix);
2190 if (uv.x < 0 || uv.x > 1) {
2191 switch (this.wrapS) {
2192 case RepeatWrapping:
2193 uv.x = uv.x - Math.floor(uv.x);
2196 case ClampToEdgeWrapping:
2197 uv.x = uv.x < 0 ? 0 : 1;
2200 case MirroredRepeatWrapping:
2201 if (Math.abs(Math.floor(uv.x) % 2) === 1) {
2202 uv.x = Math.ceil(uv.x) - uv.x;
2204 uv.x = uv.x - Math.floor(uv.x);
2211 if (uv.y < 0 || uv.y > 1) {
2212 switch (this.wrapT) {
2213 case RepeatWrapping:
2214 uv.y = uv.y - Math.floor(uv.y);
2217 case ClampToEdgeWrapping:
2218 uv.y = uv.y < 0 ? 0 : 1;
2221 case MirroredRepeatWrapping:
2222 if (Math.abs(Math.floor(uv.y) % 2) === 1) {
2223 uv.y = Math.ceil(uv.y) - uv.y;
2225 uv.y = uv.y - Math.floor(uv.y);
2239 Object.defineProperty(Texture.prototype, 'needsUpdate', {
2240 set: function set(value) {
2241 if (value === true) this.version++;
2245 function serializeImage(image) {
2246 if (typeof HTMLImageElement !== 'undefined' && image instanceof HTMLImageElement || typeof HTMLCanvasElement !== 'undefined' && image instanceof HTMLCanvasElement || typeof ImageBitmap !== 'undefined' && image instanceof ImageBitmap) {
2248 return ImageUtils.getDataURL(image);
2251 // images of DataTexture
2253 data: Array.prototype.slice.call(image.data),
2255 height: image.height,
2256 type: image.data.constructor.name
2259 console.warn('THREE.Texture: Unable to serialize Texture.');
2265 var Vector4 = /*#__PURE__*/function () {
2266 function Vector4(x, y, z, w) {
2283 Object.defineProperty(this, 'isVector4', {
2292 var _proto = Vector4.prototype;
2294 _proto.set = function set(x, y, z, w) {
2302 _proto.setScalar = function setScalar(scalar) {
2310 _proto.setX = function setX(x) {
2315 _proto.setY = function setY(y) {
2320 _proto.setZ = function setZ(z) {
2325 _proto.setW = function setW(w) {
2330 _proto.setComponent = function setComponent(index, value) {
2349 throw new Error('index is out of range: ' + index);
2355 _proto.getComponent = function getComponent(index) {
2370 throw new Error('index is out of range: ' + index);
2374 _proto.clone = function clone() {
2375 return new this.constructor(this.x, this.y, this.z, this.w);
2378 _proto.copy = function copy(v) {
2382 this.w = v.w !== undefined ? v.w : 1;
2386 _proto.add = function add(v, w) {
2387 if (w !== undefined) {
2388 console.warn('THREE.Vector4: .add() now only accepts one argument. Use .addVectors( a, b ) instead.');
2389 return this.addVectors(v, w);
2399 _proto.addScalar = function addScalar(s) {
2407 _proto.addVectors = function addVectors(a, b) {
2415 _proto.addScaledVector = function addScaledVector(v, s) {
2423 _proto.sub = function sub(v, w) {
2424 if (w !== undefined) {
2425 console.warn('THREE.Vector4: .sub() now only accepts one argument. Use .subVectors( a, b ) instead.');
2426 return this.subVectors(v, w);
2436 _proto.subScalar = function subScalar(s) {
2444 _proto.subVectors = function subVectors(a, b) {
2452 _proto.multiply = function multiply(v) {
2460 _proto.multiplyScalar = function multiplyScalar(scalar) {
2468 _proto.applyMatrix4 = function applyMatrix4(m) {
2474 this.x = e[0] * x + e[4] * y + e[8] * z + e[12] * w;
2475 this.y = e[1] * x + e[5] * y + e[9] * z + e[13] * w;
2476 this.z = e[2] * x + e[6] * y + e[10] * z + e[14] * w;
2477 this.w = e[3] * x + e[7] * y + e[11] * z + e[15] * w;
2481 _proto.divideScalar = function divideScalar(scalar) {
2482 return this.multiplyScalar(1 / scalar);
2485 _proto.setAxisAngleFromQuaternion = function setAxisAngleFromQuaternion(q) {
2486 // http://www.euclideanspace.com/maths/geometry/rotations/conversions/quaternionToAngle/index.htm
2487 // q is assumed to be normalized
2488 this.w = 2 * Math.acos(q.w);
2489 var s = Math.sqrt(1 - q.w * q.w);
2504 _proto.setAxisAngleFromRotationMatrix = function setAxisAngleFromRotationMatrix(m) {
2505 // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToAngle/index.htm
2506 // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
2507 var angle, x, y, z; // variables for result
2510 // margin to allow for rounding errors
2512 // margin to distinguish between 0 and 180 degrees
2524 if (Math.abs(m12 - m21) < epsilon && Math.abs(m13 - m31) < epsilon && Math.abs(m23 - m32) < epsilon) {
2525 // singularity found
2526 // first check for identity matrix which must have +1 for all terms
2527 // in leading diagonal and zero in other terms
2528 if (Math.abs(m12 + m21) < epsilon2 && Math.abs(m13 + m31) < epsilon2 && Math.abs(m23 + m32) < epsilon2 && Math.abs(m11 + m22 + m33 - 3) < epsilon2) {
2529 // this singularity is identity matrix so angle = 0
2530 this.set(1, 0, 0, 0);
2531 return this; // zero angle, arbitrary axis
2532 } // otherwise this singularity is angle = 180
2536 var xx = (m11 + 1) / 2;
2537 var yy = (m22 + 1) / 2;
2538 var zz = (m33 + 1) / 2;
2539 var xy = (m12 + m21) / 4;
2540 var xz = (m13 + m31) / 4;
2541 var yz = (m23 + m32) / 4;
2543 if (xx > yy && xx > zz) {
2544 // m11 is the largest diagonal term
2554 } else if (yy > zz) {
2555 // m22 is the largest diagonal term
2566 // m33 is the largest diagonal term so base result on this
2578 this.set(x, y, z, angle);
2579 return this; // return 180 deg rotation
2580 } // as we have reached here there are no singularities so we can handle normally
2583 var s = Math.sqrt((m32 - m23) * (m32 - m23) + (m13 - m31) * (m13 - m31) + (m21 - m12) * (m21 - m12)); // used to normalize
2585 if (Math.abs(s) < 0.001) s = 1; // prevent divide by zero, should not happen if matrix is orthogonal and should be
2586 // caught by singularity test above, but I've left it in just in case
2588 this.x = (m32 - m23) / s;
2589 this.y = (m13 - m31) / s;
2590 this.z = (m21 - m12) / s;
2591 this.w = Math.acos((m11 + m22 + m33 - 1) / 2);
2595 _proto.min = function min(v) {
2596 this.x = Math.min(this.x, v.x);
2597 this.y = Math.min(this.y, v.y);
2598 this.z = Math.min(this.z, v.z);
2599 this.w = Math.min(this.w, v.w);
2603 _proto.max = function max(v) {
2604 this.x = Math.max(this.x, v.x);
2605 this.y = Math.max(this.y, v.y);
2606 this.z = Math.max(this.z, v.z);
2607 this.w = Math.max(this.w, v.w);
2611 _proto.clamp = function clamp(min, max) {
2612 // assumes min < max, componentwise
2613 this.x = Math.max(min.x, Math.min(max.x, this.x));
2614 this.y = Math.max(min.y, Math.min(max.y, this.y));
2615 this.z = Math.max(min.z, Math.min(max.z, this.z));
2616 this.w = Math.max(min.w, Math.min(max.w, this.w));
2620 _proto.clampScalar = function clampScalar(minVal, maxVal) {
2621 this.x = Math.max(minVal, Math.min(maxVal, this.x));
2622 this.y = Math.max(minVal, Math.min(maxVal, this.y));
2623 this.z = Math.max(minVal, Math.min(maxVal, this.z));
2624 this.w = Math.max(minVal, Math.min(maxVal, this.w));
2628 _proto.clampLength = function clampLength(min, max) {
2629 var length = this.length();
2630 return this.divideScalar(length || 1).multiplyScalar(Math.max(min, Math.min(max, length)));
2633 _proto.floor = function floor() {
2634 this.x = Math.floor(this.x);
2635 this.y = Math.floor(this.y);
2636 this.z = Math.floor(this.z);
2637 this.w = Math.floor(this.w);
2641 _proto.ceil = function ceil() {
2642 this.x = Math.ceil(this.x);
2643 this.y = Math.ceil(this.y);
2644 this.z = Math.ceil(this.z);
2645 this.w = Math.ceil(this.w);
2649 _proto.round = function round() {
2650 this.x = Math.round(this.x);
2651 this.y = Math.round(this.y);
2652 this.z = Math.round(this.z);
2653 this.w = Math.round(this.w);
2657 _proto.roundToZero = function roundToZero() {
2658 this.x = this.x < 0 ? Math.ceil(this.x) : Math.floor(this.x);
2659 this.y = this.y < 0 ? Math.ceil(this.y) : Math.floor(this.y);
2660 this.z = this.z < 0 ? Math.ceil(this.z) : Math.floor(this.z);
2661 this.w = this.w < 0 ? Math.ceil(this.w) : Math.floor(this.w);
2665 _proto.negate = function negate() {
2673 _proto.dot = function dot(v) {
2674 return this.x * v.x + this.y * v.y + this.z * v.z + this.w * v.w;
2677 _proto.lengthSq = function lengthSq() {
2678 return this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w;
2681 _proto.length = function length() {
2682 return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
2685 _proto.manhattanLength = function manhattanLength() {
2686 return Math.abs(this.x) + Math.abs(this.y) + Math.abs(this.z) + Math.abs(this.w);
2689 _proto.normalize = function normalize() {
2690 return this.divideScalar(this.length() || 1);
2693 _proto.setLength = function setLength(length) {
2694 return this.normalize().multiplyScalar(length);
2697 _proto.lerp = function lerp(v, alpha) {
2698 this.x += (v.x - this.x) * alpha;
2699 this.y += (v.y - this.y) * alpha;
2700 this.z += (v.z - this.z) * alpha;
2701 this.w += (v.w - this.w) * alpha;
2705 _proto.lerpVectors = function lerpVectors(v1, v2, alpha) {
2706 this.x = v1.x + (v2.x - v1.x) * alpha;
2707 this.y = v1.y + (v2.y - v1.y) * alpha;
2708 this.z = v1.z + (v2.z - v1.z) * alpha;
2709 this.w = v1.w + (v2.w - v1.w) * alpha;
2713 _proto.equals = function equals(v) {
2714 return v.x === this.x && v.y === this.y && v.z === this.z && v.w === this.w;
2717 _proto.fromArray = function fromArray(array, offset) {
2718 if (offset === void 0) {
2722 this.x = array[offset];
2723 this.y = array[offset + 1];
2724 this.z = array[offset + 2];
2725 this.w = array[offset + 3];
2729 _proto.toArray = function toArray(array, offset) {
2730 if (array === void 0) {
2734 if (offset === void 0) {
2738 array[offset] = this.x;
2739 array[offset + 1] = this.y;
2740 array[offset + 2] = this.z;
2741 array[offset + 3] = this.w;
2745 _proto.fromBufferAttribute = function fromBufferAttribute(attribute, index, offset) {
2746 if (offset !== undefined) {
2747 console.warn('THREE.Vector4: offset has been removed from .fromBufferAttribute().');
2750 this.x = attribute.getX(index);
2751 this.y = attribute.getY(index);
2752 this.z = attribute.getZ(index);
2753 this.w = attribute.getW(index);
2757 _proto.random = function random() {
2758 this.x = Math.random();
2759 this.y = Math.random();
2760 this.z = Math.random();
2761 this.w = Math.random();
2765 _createClass(Vector4, [{
2767 get: function get() {
2770 set: function set(value) {
2775 get: function get() {
2778 set: function set(value) {
2787 In options, we can specify:
2788 * Texture parameters for an auto-generated target texture
2789 * depthBuffer/stencilBuffer: Booleans to indicate if we should generate these buffers
2792 var WebGLRenderTarget = /*#__PURE__*/function (_EventDispatcher) {
2793 _inheritsLoose(WebGLRenderTarget, _EventDispatcher);
2795 function WebGLRenderTarget(width, height, options) {
2798 _this = _EventDispatcher.call(this) || this;
2799 Object.defineProperty(_assertThisInitialized(_this), 'isWebGLRenderTarget', {
2802 _this.width = width;
2803 _this.height = height;
2804 _this.scissor = new Vector4(0, 0, width, height);
2805 _this.scissorTest = false;
2806 _this.viewport = new Vector4(0, 0, width, height);
2807 options = options || {};
2808 _this.texture = new Texture(undefined, options.mapping, options.wrapS, options.wrapT, options.magFilter, options.minFilter, options.format, options.type, options.anisotropy, options.encoding);
2809 _this.texture.image = {};
2810 _this.texture.image.width = width;
2811 _this.texture.image.height = height;
2812 _this.texture.generateMipmaps = options.generateMipmaps !== undefined ? options.generateMipmaps : false;
2813 _this.texture.minFilter = options.minFilter !== undefined ? options.minFilter : LinearFilter;
2814 _this.depthBuffer = options.depthBuffer !== undefined ? options.depthBuffer : true;
2815 _this.stencilBuffer = options.stencilBuffer !== undefined ? options.stencilBuffer : false;
2816 _this.depthTexture = options.depthTexture !== undefined ? options.depthTexture : null;
2820 var _proto = WebGLRenderTarget.prototype;
2822 _proto.setSize = function setSize(width, height) {
2823 if (this.width !== width || this.height !== height) {
2825 this.height = height;
2826 this.texture.image.width = width;
2827 this.texture.image.height = height;
2831 this.viewport.set(0, 0, width, height);
2832 this.scissor.set(0, 0, width, height);
2835 _proto.clone = function clone() {
2836 return new this.constructor().copy(this);
2839 _proto.copy = function copy(source) {
2840 this.width = source.width;
2841 this.height = source.height;
2842 this.viewport.copy(source.viewport);
2843 this.texture = source.texture.clone();
2844 this.depthBuffer = source.depthBuffer;
2845 this.stencilBuffer = source.stencilBuffer;
2846 this.depthTexture = source.depthTexture;
2850 _proto.dispose = function dispose() {
2851 this.dispatchEvent({
2856 return WebGLRenderTarget;
2859 var WebGLMultisampleRenderTarget = /*#__PURE__*/function (_WebGLRenderTarget) {
2860 _inheritsLoose(WebGLMultisampleRenderTarget, _WebGLRenderTarget);
2862 function WebGLMultisampleRenderTarget(width, height, options) {
2865 _this = _WebGLRenderTarget.call(this, width, height, options) || this;
2866 Object.defineProperty(_assertThisInitialized(_this), 'isWebGLMultisampleRenderTarget', {
2873 var _proto = WebGLMultisampleRenderTarget.prototype;
2875 _proto.copy = function copy(source) {
2876 _WebGLRenderTarget.prototype.copy.call(this, source);
2878 this.samples = source.samples;
2882 return WebGLMultisampleRenderTarget;
2883 }(WebGLRenderTarget);
2885 var Quaternion = /*#__PURE__*/function () {
2886 function Quaternion(x, y, z, w) {
2903 Object.defineProperty(this, 'isQuaternion', {
2912 Quaternion.slerp = function slerp(qa, qb, qm, t) {
2913 return qm.copy(qa).slerp(qb, t);
2916 Quaternion.slerpFlat = function slerpFlat(dst, dstOffset, src0, srcOffset0, src1, srcOffset1, t) {
2917 // fuzz-free, array-based Quaternion SLERP operation
2918 var x0 = src0[srcOffset0 + 0],
2919 y0 = src0[srcOffset0 + 1],
2920 z0 = src0[srcOffset0 + 2],
2921 w0 = src0[srcOffset0 + 3];
2922 var x1 = src1[srcOffset1 + 0],
2923 y1 = src1[srcOffset1 + 1],
2924 z1 = src1[srcOffset1 + 2],
2925 w1 = src1[srcOffset1 + 3];
2927 if (w0 !== w1 || x0 !== x1 || y0 !== y1 || z0 !== z1) {
2929 var cos = x0 * x1 + y0 * y1 + z0 * z1 + w0 * w1,
2930 dir = cos >= 0 ? 1 : -1,
2931 sqrSin = 1 - cos * cos; // Skip the Slerp for tiny steps to avoid numeric problems:
2933 if (sqrSin > Number.EPSILON) {
2934 var sin = Math.sqrt(sqrSin),
2935 len = Math.atan2(sin, cos * dir);
2936 s = Math.sin(s * len) / sin;
2937 t = Math.sin(t * len) / sin;
2941 x0 = x0 * s + x1 * tDir;
2942 y0 = y0 * s + y1 * tDir;
2943 z0 = z0 * s + z1 * tDir;
2944 w0 = w0 * s + w1 * tDir; // Normalize in case we just did a lerp:
2947 var f = 1 / Math.sqrt(x0 * x0 + y0 * y0 + z0 * z0 + w0 * w0);
2955 dst[dstOffset] = x0;
2956 dst[dstOffset + 1] = y0;
2957 dst[dstOffset + 2] = z0;
2958 dst[dstOffset + 3] = w0;
2961 Quaternion.multiplyQuaternionsFlat = function multiplyQuaternionsFlat(dst, dstOffset, src0, srcOffset0, src1, srcOffset1) {
2962 var x0 = src0[srcOffset0];
2963 var y0 = src0[srcOffset0 + 1];
2964 var z0 = src0[srcOffset0 + 2];
2965 var w0 = src0[srcOffset0 + 3];
2966 var x1 = src1[srcOffset1];
2967 var y1 = src1[srcOffset1 + 1];
2968 var z1 = src1[srcOffset1 + 2];
2969 var w1 = src1[srcOffset1 + 3];
2970 dst[dstOffset] = x0 * w1 + w0 * x1 + y0 * z1 - z0 * y1;
2971 dst[dstOffset + 1] = y0 * w1 + w0 * y1 + z0 * x1 - x0 * z1;
2972 dst[dstOffset + 2] = z0 * w1 + w0 * z1 + x0 * y1 - y0 * x1;
2973 dst[dstOffset + 3] = w0 * w1 - x0 * x1 - y0 * y1 - z0 * z1;
2977 var _proto = Quaternion.prototype;
2979 _proto.set = function set(x, y, z, w) {
2985 this._onChangeCallback();
2990 _proto.clone = function clone() {
2991 return new this.constructor(this._x, this._y, this._z, this._w);
2994 _proto.copy = function copy(quaternion) {
2995 this._x = quaternion.x;
2996 this._y = quaternion.y;
2997 this._z = quaternion.z;
2998 this._w = quaternion.w;
3000 this._onChangeCallback();
3005 _proto.setFromEuler = function setFromEuler(euler, update) {
3006 if (!(euler && euler.isEuler)) {
3007 throw new Error('THREE.Quaternion: .setFromEuler() now expects an Euler rotation rather than a Vector3 and order.');
3013 order = euler._order; // http://www.mathworks.com/matlabcentral/fileexchange/
3014 // 20696-function-to-convert-between-dcm-euler-angles-quaternions-and-euler-vectors/
3015 // content/SpinCalc.m
3019 var c1 = cos(x / 2);
3020 var c2 = cos(y / 2);
3021 var c3 = cos(z / 2);
3022 var s1 = sin(x / 2);
3023 var s2 = sin(y / 2);
3024 var s3 = sin(z / 2);
3028 this._x = s1 * c2 * c3 + c1 * s2 * s3;
3029 this._y = c1 * s2 * c3 - s1 * c2 * s3;
3030 this._z = c1 * c2 * s3 + s1 * s2 * c3;
3031 this._w = c1 * c2 * c3 - s1 * s2 * s3;
3035 this._x = s1 * c2 * c3 + c1 * s2 * s3;
3036 this._y = c1 * s2 * c3 - s1 * c2 * s3;
3037 this._z = c1 * c2 * s3 - s1 * s2 * c3;
3038 this._w = c1 * c2 * c3 + s1 * s2 * s3;
3042 this._x = s1 * c2 * c3 - c1 * s2 * s3;
3043 this._y = c1 * s2 * c3 + s1 * c2 * s3;
3044 this._z = c1 * c2 * s3 + s1 * s2 * c3;
3045 this._w = c1 * c2 * c3 - s1 * s2 * s3;
3049 this._x = s1 * c2 * c3 - c1 * s2 * s3;
3050 this._y = c1 * s2 * c3 + s1 * c2 * s3;
3051 this._z = c1 * c2 * s3 - s1 * s2 * c3;
3052 this._w = c1 * c2 * c3 + s1 * s2 * s3;
3056 this._x = s1 * c2 * c3 + c1 * s2 * s3;
3057 this._y = c1 * s2 * c3 + s1 * c2 * s3;
3058 this._z = c1 * c2 * s3 - s1 * s2 * c3;
3059 this._w = c1 * c2 * c3 - s1 * s2 * s3;
3063 this._x = s1 * c2 * c3 - c1 * s2 * s3;
3064 this._y = c1 * s2 * c3 - s1 * c2 * s3;
3065 this._z = c1 * c2 * s3 + s1 * s2 * c3;
3066 this._w = c1 * c2 * c3 + s1 * s2 * s3;
3070 console.warn('THREE.Quaternion: .setFromEuler() encountered an unknown order: ' + order);
3073 if (update !== false) this._onChangeCallback();
3077 _proto.setFromAxisAngle = function setFromAxisAngle(axis, angle) {
3078 // http://www.euclideanspace.com/maths/geometry/rotations/conversions/angleToQuaternion/index.htm
3079 // assumes axis is normalized
3080 var halfAngle = angle / 2,
3081 s = Math.sin(halfAngle);
3082 this._x = axis.x * s;
3083 this._y = axis.y * s;
3084 this._z = axis.z * s;
3085 this._w = Math.cos(halfAngle);
3087 this._onChangeCallback();
3092 _proto.setFromRotationMatrix = function setFromRotationMatrix(m) {
3093 // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToQuaternion/index.htm
3094 // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
3095 var te = m.elements,
3105 trace = m11 + m22 + m33;
3108 var s = 0.5 / Math.sqrt(trace + 1.0);
3110 this._x = (m32 - m23) * s;
3111 this._y = (m13 - m31) * s;
3112 this._z = (m21 - m12) * s;
3113 } else if (m11 > m22 && m11 > m33) {
3114 var _s = 2.0 * Math.sqrt(1.0 + m11 - m22 - m33);
3116 this._w = (m32 - m23) / _s;
3117 this._x = 0.25 * _s;
3118 this._y = (m12 + m21) / _s;
3119 this._z = (m13 + m31) / _s;
3120 } else if (m22 > m33) {
3121 var _s2 = 2.0 * Math.sqrt(1.0 + m22 - m11 - m33);
3123 this._w = (m13 - m31) / _s2;
3124 this._x = (m12 + m21) / _s2;
3125 this._y = 0.25 * _s2;
3126 this._z = (m23 + m32) / _s2;
3128 var _s3 = 2.0 * Math.sqrt(1.0 + m33 - m11 - m22);
3130 this._w = (m21 - m12) / _s3;
3131 this._x = (m13 + m31) / _s3;
3132 this._y = (m23 + m32) / _s3;
3133 this._z = 0.25 * _s3;
3136 this._onChangeCallback();
3141 _proto.setFromUnitVectors = function setFromUnitVectors(vFrom, vTo) {
3142 // assumes direction vectors vFrom and vTo are normalized
3144 var r = vFrom.dot(vTo) + 1;
3149 if (Math.abs(vFrom.x) > Math.abs(vFrom.z)) {
3161 // crossVectors( vFrom, vTo ); // inlined to avoid cyclic dependency on Vector3
3162 this._x = vFrom.y * vTo.z - vFrom.z * vTo.y;
3163 this._y = vFrom.z * vTo.x - vFrom.x * vTo.z;
3164 this._z = vFrom.x * vTo.y - vFrom.y * vTo.x;
3168 return this.normalize();
3171 _proto.angleTo = function angleTo(q) {
3172 return 2 * Math.acos(Math.abs(MathUtils.clamp(this.dot(q), -1, 1)));
3175 _proto.rotateTowards = function rotateTowards(q, step) {
3176 var angle = this.angleTo(q);
3177 if (angle === 0) return this;
3178 var t = Math.min(1, step / angle);
3183 _proto.identity = function identity() {
3184 return this.set(0, 0, 0, 1);
3187 _proto.invert = function invert() {
3188 // quaternion is assumed to have unit length
3189 return this.conjugate();
3192 _proto.conjugate = function conjugate() {
3197 this._onChangeCallback();
3202 _proto.dot = function dot(v) {
3203 return this._x * v._x + this._y * v._y + this._z * v._z + this._w * v._w;
3206 _proto.lengthSq = function lengthSq() {
3207 return this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w;
3210 _proto.length = function length() {
3211 return Math.sqrt(this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w);
3214 _proto.normalize = function normalize() {
3215 var l = this.length();
3224 this._x = this._x * l;
3225 this._y = this._y * l;
3226 this._z = this._z * l;
3227 this._w = this._w * l;
3230 this._onChangeCallback();
3235 _proto.multiply = function multiply(q, p) {
3236 if (p !== undefined) {
3237 console.warn('THREE.Quaternion: .multiply() now only accepts one argument. Use .multiplyQuaternions( a, b ) instead.');
3238 return this.multiplyQuaternions(q, p);
3241 return this.multiplyQuaternions(this, q);
3244 _proto.premultiply = function premultiply(q) {
3245 return this.multiplyQuaternions(q, this);
3248 _proto.multiplyQuaternions = function multiplyQuaternions(a, b) {
3249 // from http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/code/index.htm
3258 this._x = qax * qbw + qaw * qbx + qay * qbz - qaz * qby;
3259 this._y = qay * qbw + qaw * qby + qaz * qbx - qax * qbz;
3260 this._z = qaz * qbw + qaw * qbz + qax * qby - qay * qbx;
3261 this._w = qaw * qbw - qax * qbx - qay * qby - qaz * qbz;
3263 this._onChangeCallback();
3268 _proto.slerp = function slerp(qb, t) {
3269 if (t === 0) return this;
3270 if (t === 1) return this.copy(qb);
3274 w = this._w; // http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/slerp/
3276 var cosHalfTheta = w * qb._w + x * qb._x + y * qb._y + z * qb._z;
3278 if (cosHalfTheta < 0) {
3283 cosHalfTheta = -cosHalfTheta;
3288 if (cosHalfTheta >= 1.0) {
3296 var sqrSinHalfTheta = 1.0 - cosHalfTheta * cosHalfTheta;
3298 if (sqrSinHalfTheta <= Number.EPSILON) {
3300 this._w = s * w + t * this._w;
3301 this._x = s * x + t * this._x;
3302 this._y = s * y + t * this._y;
3303 this._z = s * z + t * this._z;
3306 this._onChangeCallback();
3311 var sinHalfTheta = Math.sqrt(sqrSinHalfTheta);
3312 var halfTheta = Math.atan2(sinHalfTheta, cosHalfTheta);
3313 var ratioA = Math.sin((1 - t) * halfTheta) / sinHalfTheta,
3314 ratioB = Math.sin(t * halfTheta) / sinHalfTheta;
3315 this._w = w * ratioA + this._w * ratioB;
3316 this._x = x * ratioA + this._x * ratioB;
3317 this._y = y * ratioA + this._y * ratioB;
3318 this._z = z * ratioA + this._z * ratioB;
3320 this._onChangeCallback();
3325 _proto.equals = function equals(quaternion) {
3326 return quaternion._x === this._x && quaternion._y === this._y && quaternion._z === this._z && quaternion._w === this._w;
3329 _proto.fromArray = function fromArray(array, offset) {
3330 if (offset === void 0) {
3334 this._x = array[offset];
3335 this._y = array[offset + 1];
3336 this._z = array[offset + 2];
3337 this._w = array[offset + 3];
3339 this._onChangeCallback();
3344 _proto.toArray = function toArray(array, offset) {
3345 if (array === void 0) {
3349 if (offset === void 0) {
3353 array[offset] = this._x;
3354 array[offset + 1] = this._y;
3355 array[offset + 2] = this._z;
3356 array[offset + 3] = this._w;
3360 _proto.fromBufferAttribute = function fromBufferAttribute(attribute, index) {
3361 this._x = attribute.getX(index);
3362 this._y = attribute.getY(index);
3363 this._z = attribute.getZ(index);
3364 this._w = attribute.getW(index);
3368 _proto._onChange = function _onChange(callback) {
3369 this._onChangeCallback = callback;
3373 _proto._onChangeCallback = function _onChangeCallback() {};
3375 _createClass(Quaternion, [{
3377 get: function get() {
3380 set: function set(value) {
3383 this._onChangeCallback();
3387 get: function get() {
3390 set: function set(value) {
3393 this._onChangeCallback();
3397 get: function get() {
3400 set: function set(value) {
3403 this._onChangeCallback();
3407 get: function get() {
3410 set: function set(value) {
3413 this._onChangeCallback();
3420 var Vector3 = /*#__PURE__*/function () {
3421 function Vector3(x, y, z) {
3434 Object.defineProperty(this, 'isVector3', {
3442 var _proto = Vector3.prototype;
3444 _proto.set = function set(x, y, z) {
3445 if (z === undefined) z = this.z; // sprite.scale.set(x,y)
3453 _proto.setScalar = function setScalar(scalar) {
3460 _proto.setX = function setX(x) {
3465 _proto.setY = function setY(y) {
3470 _proto.setZ = function setZ(z) {
3475 _proto.setComponent = function setComponent(index, value) {
3490 throw new Error('index is out of range: ' + index);
3496 _proto.getComponent = function getComponent(index) {
3508 throw new Error('index is out of range: ' + index);
3512 _proto.clone = function clone() {
3513 return new this.constructor(this.x, this.y, this.z);
3516 _proto.copy = function copy(v) {
3523 _proto.add = function add(v, w) {
3524 if (w !== undefined) {
3525 console.warn('THREE.Vector3: .add() now only accepts one argument. Use .addVectors( a, b ) instead.');
3526 return this.addVectors(v, w);
3535 _proto.addScalar = function addScalar(s) {
3542 _proto.addVectors = function addVectors(a, b) {
3549 _proto.addScaledVector = function addScaledVector(v, s) {
3556 _proto.sub = function sub(v, w) {
3557 if (w !== undefined) {
3558 console.warn('THREE.Vector3: .sub() now only accepts one argument. Use .subVectors( a, b ) instead.');
3559 return this.subVectors(v, w);
3568 _proto.subScalar = function subScalar(s) {
3575 _proto.subVectors = function subVectors(a, b) {
3582 _proto.multiply = function multiply(v, w) {
3583 if (w !== undefined) {
3584 console.warn('THREE.Vector3: .multiply() now only accepts one argument. Use .multiplyVectors( a, b ) instead.');
3585 return this.multiplyVectors(v, w);
3594 _proto.multiplyScalar = function multiplyScalar(scalar) {
3601 _proto.multiplyVectors = function multiplyVectors(a, b) {
3608 _proto.applyEuler = function applyEuler(euler) {
3609 if (!(euler && euler.isEuler)) {
3610 console.error('THREE.Vector3: .applyEuler() now expects an Euler rotation rather than a Vector3 and order.');
3613 return this.applyQuaternion(_quaternion.setFromEuler(euler));
3616 _proto.applyAxisAngle = function applyAxisAngle(axis, angle) {
3617 return this.applyQuaternion(_quaternion.setFromAxisAngle(axis, angle));
3620 _proto.applyMatrix3 = function applyMatrix3(m) {
3625 this.x = e[0] * x + e[3] * y + e[6] * z;
3626 this.y = e[1] * x + e[4] * y + e[7] * z;
3627 this.z = e[2] * x + e[5] * y + e[8] * z;
3631 _proto.applyNormalMatrix = function applyNormalMatrix(m) {
3632 return this.applyMatrix3(m).normalize();
3635 _proto.applyMatrix4 = function applyMatrix4(m) {
3640 var w = 1 / (e[3] * x + e[7] * y + e[11] * z + e[15]);
3641 this.x = (e[0] * x + e[4] * y + e[8] * z + e[12]) * w;
3642 this.y = (e[1] * x + e[5] * y + e[9] * z + e[13]) * w;
3643 this.z = (e[2] * x + e[6] * y + e[10] * z + e[14]) * w;
3647 _proto.applyQuaternion = function applyQuaternion(q) {
3654 qw = q.w; // calculate quat * vector
3656 var ix = qw * x + qy * z - qz * y;
3657 var iy = qw * y + qz * x - qx * z;
3658 var iz = qw * z + qx * y - qy * x;
3659 var iw = -qx * x - qy * y - qz * z; // calculate result * inverse quat
3661 this.x = ix * qw + iw * -qx + iy * -qz - iz * -qy;
3662 this.y = iy * qw + iw * -qy + iz * -qx - ix * -qz;
3663 this.z = iz * qw + iw * -qz + ix * -qy - iy * -qx;
3667 _proto.project = function project(camera) {
3668 return this.applyMatrix4(camera.matrixWorldInverse).applyMatrix4(camera.projectionMatrix);
3671 _proto.unproject = function unproject(camera) {
3672 return this.applyMatrix4(camera.projectionMatrixInverse).applyMatrix4(camera.matrixWorld);
3675 _proto.transformDirection = function transformDirection(m) {
3676 // input: THREE.Matrix4 affine matrix
3677 // vector interpreted as a direction
3682 this.x = e[0] * x + e[4] * y + e[8] * z;
3683 this.y = e[1] * x + e[5] * y + e[9] * z;
3684 this.z = e[2] * x + e[6] * y + e[10] * z;
3685 return this.normalize();
3688 _proto.divide = function divide(v) {
3695 _proto.divideScalar = function divideScalar(scalar) {
3696 return this.multiplyScalar(1 / scalar);
3699 _proto.min = function min(v) {
3700 this.x = Math.min(this.x, v.x);
3701 this.y = Math.min(this.y, v.y);
3702 this.z = Math.min(this.z, v.z);
3706 _proto.max = function max(v) {
3707 this.x = Math.max(this.x, v.x);
3708 this.y = Math.max(this.y, v.y);
3709 this.z = Math.max(this.z, v.z);
3713 _proto.clamp = function clamp(min, max) {
3714 // assumes min < max, componentwise
3715 this.x = Math.max(min.x, Math.min(max.x, this.x));
3716 this.y = Math.max(min.y, Math.min(max.y, this.y));
3717 this.z = Math.max(min.z, Math.min(max.z, this.z));
3721 _proto.clampScalar = function clampScalar(minVal, maxVal) {
3722 this.x = Math.max(minVal, Math.min(maxVal, this.x));
3723 this.y = Math.max(minVal, Math.min(maxVal, this.y));
3724 this.z = Math.max(minVal, Math.min(maxVal, this.z));
3728 _proto.clampLength = function clampLength(min, max) {
3729 var length = this.length();
3730 return this.divideScalar(length || 1).multiplyScalar(Math.max(min, Math.min(max, length)));
3733 _proto.floor = function floor() {
3734 this.x = Math.floor(this.x);
3735 this.y = Math.floor(this.y);
3736 this.z = Math.floor(this.z);
3740 _proto.ceil = function ceil() {
3741 this.x = Math.ceil(this.x);
3742 this.y = Math.ceil(this.y);
3743 this.z = Math.ceil(this.z);
3747 _proto.round = function round() {
3748 this.x = Math.round(this.x);
3749 this.y = Math.round(this.y);
3750 this.z = Math.round(this.z);
3754 _proto.roundToZero = function roundToZero() {
3755 this.x = this.x < 0 ? Math.ceil(this.x) : Math.floor(this.x);
3756 this.y = this.y < 0 ? Math.ceil(this.y) : Math.floor(this.y);
3757 this.z = this.z < 0 ? Math.ceil(this.z) : Math.floor(this.z);
3761 _proto.negate = function negate() {
3768 _proto.dot = function dot(v) {
3769 return this.x * v.x + this.y * v.y + this.z * v.z;
3770 } // TODO lengthSquared?
3773 _proto.lengthSq = function lengthSq() {
3774 return this.x * this.x + this.y * this.y + this.z * this.z;
3777 _proto.length = function length() {
3778 return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z);
3781 _proto.manhattanLength = function manhattanLength() {
3782 return Math.abs(this.x) + Math.abs(this.y) + Math.abs(this.z);
3785 _proto.normalize = function normalize() {
3786 return this.divideScalar(this.length() || 1);
3789 _proto.setLength = function setLength(length) {
3790 return this.normalize().multiplyScalar(length);
3793 _proto.lerp = function lerp(v, alpha) {
3794 this.x += (v.x - this.x) * alpha;
3795 this.y += (v.y - this.y) * alpha;
3796 this.z += (v.z - this.z) * alpha;
3800 _proto.lerpVectors = function lerpVectors(v1, v2, alpha) {
3801 this.x = v1.x + (v2.x - v1.x) * alpha;
3802 this.y = v1.y + (v2.y - v1.y) * alpha;
3803 this.z = v1.z + (v2.z - v1.z) * alpha;
3807 _proto.cross = function cross(v, w) {
3808 if (w !== undefined) {
3809 console.warn('THREE.Vector3: .cross() now only accepts one argument. Use .crossVectors( a, b ) instead.');
3810 return this.crossVectors(v, w);
3813 return this.crossVectors(this, v);
3816 _proto.crossVectors = function crossVectors(a, b) {
3823 this.x = ay * bz - az * by;
3824 this.y = az * bx - ax * bz;
3825 this.z = ax * by - ay * bx;
3829 _proto.projectOnVector = function projectOnVector(v) {
3830 var denominator = v.lengthSq();
3831 if (denominator === 0) return this.set(0, 0, 0);
3832 var scalar = v.dot(this) / denominator;
3833 return this.copy(v).multiplyScalar(scalar);
3836 _proto.projectOnPlane = function projectOnPlane(planeNormal) {
3837 _vector.copy(this).projectOnVector(planeNormal);
3839 return this.sub(_vector);
3842 _proto.reflect = function reflect(normal) {
3843 // reflect incident vector off plane orthogonal to normal
3844 // normal is assumed to have unit length
3845 return this.sub(_vector.copy(normal).multiplyScalar(2 * this.dot(normal)));
3848 _proto.angleTo = function angleTo(v) {
3849 var denominator = Math.sqrt(this.lengthSq() * v.lengthSq());
3850 if (denominator === 0) return Math.PI / 2;
3851 var theta = this.dot(v) / denominator; // clamp, to handle numerical problems
3853 return Math.acos(MathUtils.clamp(theta, -1, 1));
3856 _proto.distanceTo = function distanceTo(v) {
3857 return Math.sqrt(this.distanceToSquared(v));
3860 _proto.distanceToSquared = function distanceToSquared(v) {
3861 var dx = this.x - v.x,
3864 return dx * dx + dy * dy + dz * dz;
3867 _proto.manhattanDistanceTo = function manhattanDistanceTo(v) {
3868 return Math.abs(this.x - v.x) + Math.abs(this.y - v.y) + Math.abs(this.z - v.z);
3871 _proto.setFromSpherical = function setFromSpherical(s) {
3872 return this.setFromSphericalCoords(s.radius, s.phi, s.theta);
3875 _proto.setFromSphericalCoords = function setFromSphericalCoords(radius, phi, theta) {
3876 var sinPhiRadius = Math.sin(phi) * radius;
3877 this.x = sinPhiRadius * Math.sin(theta);
3878 this.y = Math.cos(phi) * radius;
3879 this.z = sinPhiRadius * Math.cos(theta);
3883 _proto.setFromCylindrical = function setFromCylindrical(c) {
3884 return this.setFromCylindricalCoords(c.radius, c.theta, c.y);
3887 _proto.setFromCylindricalCoords = function setFromCylindricalCoords(radius, theta, y) {
3888 this.x = radius * Math.sin(theta);
3890 this.z = radius * Math.cos(theta);
3894 _proto.setFromMatrixPosition = function setFromMatrixPosition(m) {
3902 _proto.setFromMatrixScale = function setFromMatrixScale(m) {
3903 var sx = this.setFromMatrixColumn(m, 0).length();
3904 var sy = this.setFromMatrixColumn(m, 1).length();
3905 var sz = this.setFromMatrixColumn(m, 2).length();
3912 _proto.setFromMatrixColumn = function setFromMatrixColumn(m, index) {
3913 return this.fromArray(m.elements, index * 4);
3916 _proto.setFromMatrix3Column = function setFromMatrix3Column(m, index) {
3917 return this.fromArray(m.elements, index * 3);
3920 _proto.equals = function equals(v) {
3921 return v.x === this.x && v.y === this.y && v.z === this.z;
3924 _proto.fromArray = function fromArray(array, offset) {
3925 if (offset === void 0) {
3929 this.x = array[offset];
3930 this.y = array[offset + 1];
3931 this.z = array[offset + 2];
3935 _proto.toArray = function toArray(array, offset) {
3936 if (array === void 0) {
3940 if (offset === void 0) {
3944 array[offset] = this.x;
3945 array[offset + 1] = this.y;
3946 array[offset + 2] = this.z;
3950 _proto.fromBufferAttribute = function fromBufferAttribute(attribute, index, offset) {
3951 if (offset !== undefined) {
3952 console.warn('THREE.Vector3: offset has been removed from .fromBufferAttribute().');
3955 this.x = attribute.getX(index);
3956 this.y = attribute.getY(index);
3957 this.z = attribute.getZ(index);
3961 _proto.random = function random() {
3962 this.x = Math.random();
3963 this.y = Math.random();
3964 this.z = Math.random();
3971 var _vector = /*@__PURE__*/new Vector3();
3973 var _quaternion = /*@__PURE__*/new Quaternion();
3975 var Box3 = /*#__PURE__*/function () {
3976 function Box3(min, max) {
3977 Object.defineProperty(this, 'isBox3', {
3980 this.min = min !== undefined ? min : new Vector3(+Infinity, +Infinity, +Infinity);
3981 this.max = max !== undefined ? max : new Vector3(-Infinity, -Infinity, -Infinity);
3984 var _proto = Box3.prototype;
3986 _proto.set = function set(min, max) {
3992 _proto.setFromArray = function setFromArray(array) {
3993 var minX = +Infinity;
3994 var minY = +Infinity;
3995 var minZ = +Infinity;
3996 var maxX = -Infinity;
3997 var maxY = -Infinity;
3998 var maxZ = -Infinity;
4000 for (var i = 0, l = array.length; i < l; i += 3) {
4002 var y = array[i + 1];
4003 var z = array[i + 2];
4004 if (x < minX) minX = x;
4005 if (y < minY) minY = y;
4006 if (z < minZ) minZ = z;
4007 if (x > maxX) maxX = x;
4008 if (y > maxY) maxY = y;
4009 if (z > maxZ) maxZ = z;
4012 this.min.set(minX, minY, minZ);
4013 this.max.set(maxX, maxY, maxZ);
4017 _proto.setFromBufferAttribute = function setFromBufferAttribute(attribute) {
4018 var minX = +Infinity;
4019 var minY = +Infinity;
4020 var minZ = +Infinity;
4021 var maxX = -Infinity;
4022 var maxY = -Infinity;
4023 var maxZ = -Infinity;
4025 for (var i = 0, l = attribute.count; i < l; i++) {
4026 var x = attribute.getX(i);
4027 var y = attribute.getY(i);
4028 var z = attribute.getZ(i);
4029 if (x < minX) minX = x;
4030 if (y < minY) minY = y;
4031 if (z < minZ) minZ = z;
4032 if (x > maxX) maxX = x;
4033 if (y > maxY) maxY = y;
4034 if (z > maxZ) maxZ = z;
4037 this.min.set(minX, minY, minZ);
4038 this.max.set(maxX, maxY, maxZ);
4042 _proto.setFromPoints = function setFromPoints(points) {
4045 for (var i = 0, il = points.length; i < il; i++) {
4046 this.expandByPoint(points[i]);
4052 _proto.setFromCenterAndSize = function setFromCenterAndSize(center, size) {
4053 var halfSize = _vector$1.copy(size).multiplyScalar(0.5);
4055 this.min.copy(center).sub(halfSize);
4056 this.max.copy(center).add(halfSize);
4060 _proto.setFromObject = function setFromObject(object) {
4062 return this.expandByObject(object);
4065 _proto.clone = function clone() {
4066 return new this.constructor().copy(this);
4069 _proto.copy = function copy(box) {
4070 this.min.copy(box.min);
4071 this.max.copy(box.max);
4075 _proto.makeEmpty = function makeEmpty() {
4076 this.min.x = this.min.y = this.min.z = +Infinity;
4077 this.max.x = this.max.y = this.max.z = -Infinity;
4081 _proto.isEmpty = function isEmpty() {
4082 // this is a more robust check for empty than ( volume <= 0 ) because volume can get positive with two negative axes
4083 return this.max.x < this.min.x || this.max.y < this.min.y || this.max.z < this.min.z;
4086 _proto.getCenter = function getCenter(target) {
4087 if (target === undefined) {
4088 console.warn('THREE.Box3: .getCenter() target is now required');
4089 target = new Vector3();
4092 return this.isEmpty() ? target.set(0, 0, 0) : target.addVectors(this.min, this.max).multiplyScalar(0.5);
4095 _proto.getSize = function getSize(target) {
4096 if (target === undefined) {
4097 console.warn('THREE.Box3: .getSize() target is now required');
4098 target = new Vector3();
4101 return this.isEmpty() ? target.set(0, 0, 0) : target.subVectors(this.max, this.min);
4104 _proto.expandByPoint = function expandByPoint(point) {
4105 this.min.min(point);
4106 this.max.max(point);
4110 _proto.expandByVector = function expandByVector(vector) {
4111 this.min.sub(vector);
4112 this.max.add(vector);
4116 _proto.expandByScalar = function expandByScalar(scalar) {
4117 this.min.addScalar(-scalar);
4118 this.max.addScalar(scalar);
4122 _proto.expandByObject = function expandByObject(object) {
4123 // Computes the world-axis-aligned bounding box of an object (including its children),
4124 // accounting for both the object's, and children's, world transforms
4125 object.updateWorldMatrix(false, false);
4126 var geometry = object.geometry;
4128 if (geometry !== undefined) {
4129 if (geometry.boundingBox === null) {
4130 geometry.computeBoundingBox();
4133 _box.copy(geometry.boundingBox);
4135 _box.applyMatrix4(object.matrixWorld);
4140 var children = object.children;
4142 for (var i = 0, l = children.length; i < l; i++) {
4143 this.expandByObject(children[i]);
4149 _proto.containsPoint = function containsPoint(point) {
4150 return point.x < this.min.x || point.x > this.max.x || point.y < this.min.y || point.y > this.max.y || point.z < this.min.z || point.z > this.max.z ? false : true;
4153 _proto.containsBox = function containsBox(box) {
4154 return this.min.x <= box.min.x && box.max.x <= this.max.x && this.min.y <= box.min.y && box.max.y <= this.max.y && this.min.z <= box.min.z && box.max.z <= this.max.z;
4157 _proto.getParameter = function getParameter(point, target) {
4158 // This can potentially have a divide by zero if the box
4159 // has a size dimension of 0.
4160 if (target === undefined) {
4161 console.warn('THREE.Box3: .getParameter() target is now required');
4162 target = new Vector3();
4165 return target.set((point.x - this.min.x) / (this.max.x - this.min.x), (point.y - this.min.y) / (this.max.y - this.min.y), (point.z - this.min.z) / (this.max.z - this.min.z));
4168 _proto.intersectsBox = function intersectsBox(box) {
4169 // using 6 splitting planes to rule out intersections.
4170 return box.max.x < this.min.x || box.min.x > this.max.x || box.max.y < this.min.y || box.min.y > this.max.y || box.max.z < this.min.z || box.min.z > this.max.z ? false : true;
4173 _proto.intersectsSphere = function intersectsSphere(sphere) {
4174 // Find the point on the AABB closest to the sphere center.
4175 this.clampPoint(sphere.center, _vector$1); // If that point is inside the sphere, the AABB and sphere intersect.
4177 return _vector$1.distanceToSquared(sphere.center) <= sphere.radius * sphere.radius;
4180 _proto.intersectsPlane = function intersectsPlane(plane) {
4181 // We compute the minimum and maximum dot product values. If those values
4182 // are on the same side (back or front) of the plane, then there is no intersection.
4185 if (plane.normal.x > 0) {
4186 min = plane.normal.x * this.min.x;
4187 max = plane.normal.x * this.max.x;
4189 min = plane.normal.x * this.max.x;
4190 max = plane.normal.x * this.min.x;
4193 if (plane.normal.y > 0) {
4194 min += plane.normal.y * this.min.y;
4195 max += plane.normal.y * this.max.y;
4197 min += plane.normal.y * this.max.y;
4198 max += plane.normal.y * this.min.y;
4201 if (plane.normal.z > 0) {
4202 min += plane.normal.z * this.min.z;
4203 max += plane.normal.z * this.max.z;
4205 min += plane.normal.z * this.max.z;
4206 max += plane.normal.z * this.min.z;
4209 return min <= -plane.constant && max >= -plane.constant;
4212 _proto.intersectsTriangle = function intersectsTriangle(triangle) {
4213 if (this.isEmpty()) {
4215 } // compute box center and extents
4218 this.getCenter(_center);
4220 _extents.subVectors(this.max, _center); // translate triangle to aabb origin
4223 _v0.subVectors(triangle.a, _center);
4225 _v1.subVectors(triangle.b, _center);
4227 _v2.subVectors(triangle.c, _center); // compute edge vectors for triangle
4230 _f0.subVectors(_v1, _v0);
4232 _f1.subVectors(_v2, _v1);
4234 _f2.subVectors(_v0, _v2); // test against axes that are given by cross product combinations of the edges of the triangle and the edges of the aabb
4235 // make an axis testing of each of the 3 sides of the aabb against each of the 3 sides of the triangle = 9 axis of separation
4236 // axis_ij = u_i x f_j (u0, u1, u2 = face normals of aabb = x,y,z axes vectors since aabb is axis aligned)
4239 var axes = [0, -_f0.z, _f0.y, 0, -_f1.z, _f1.y, 0, -_f2.z, _f2.y, _f0.z, 0, -_f0.x, _f1.z, 0, -_f1.x, _f2.z, 0, -_f2.x, -_f0.y, _f0.x, 0, -_f1.y, _f1.x, 0, -_f2.y, _f2.x, 0];
4241 if (!satForAxes(axes, _v0, _v1, _v2, _extents)) {
4243 } // test 3 face normals from the aabb
4246 axes = [1, 0, 0, 0, 1, 0, 0, 0, 1];
4248 if (!satForAxes(axes, _v0, _v1, _v2, _extents)) {
4250 } // finally testing the face normal of the triangle
4251 // use already existing triangle edge vectors here
4254 _triangleNormal.crossVectors(_f0, _f1);
4256 axes = [_triangleNormal.x, _triangleNormal.y, _triangleNormal.z];
4257 return satForAxes(axes, _v0, _v1, _v2, _extents);
4260 _proto.clampPoint = function clampPoint(point, target) {
4261 if (target === undefined) {
4262 console.warn('THREE.Box3: .clampPoint() target is now required');
4263 target = new Vector3();
4266 return target.copy(point).clamp(this.min, this.max);
4269 _proto.distanceToPoint = function distanceToPoint(point) {
4270 var clampedPoint = _vector$1.copy(point).clamp(this.min, this.max);
4272 return clampedPoint.sub(point).length();
4275 _proto.getBoundingSphere = function getBoundingSphere(target) {
4276 if (target === undefined) {
4277 console.error('THREE.Box3: .getBoundingSphere() target is now required'); //target = new Sphere(); // removed to avoid cyclic dependency
4280 this.getCenter(target.center);
4281 target.radius = this.getSize(_vector$1).length() * 0.5;
4285 _proto.intersect = function intersect(box) {
4286 this.min.max(box.min);
4287 this.max.min(box.max); // ensure that if there is no overlap, the result is fully empty, not slightly empty with non-inf/+inf values that will cause subsequence intersects to erroneously return valid values.
4289 if (this.isEmpty()) this.makeEmpty();
4293 _proto.union = function union(box) {
4294 this.min.min(box.min);
4295 this.max.max(box.max);
4299 _proto.applyMatrix4 = function applyMatrix4(matrix) {
4300 // transform of empty box is an empty box.
4301 if (this.isEmpty()) return this; // NOTE: I am using a binary pattern to specify all 2^3 combinations below
4303 _points[0].set(this.min.x, this.min.y, this.min.z).applyMatrix4(matrix); // 000
4306 _points[1].set(this.min.x, this.min.y, this.max.z).applyMatrix4(matrix); // 001
4309 _points[2].set(this.min.x, this.max.y, this.min.z).applyMatrix4(matrix); // 010
4312 _points[3].set(this.min.x, this.max.y, this.max.z).applyMatrix4(matrix); // 011
4315 _points[4].set(this.max.x, this.min.y, this.min.z).applyMatrix4(matrix); // 100
4318 _points[5].set(this.max.x, this.min.y, this.max.z).applyMatrix4(matrix); // 101
4321 _points[6].set(this.max.x, this.max.y, this.min.z).applyMatrix4(matrix); // 110
4324 _points[7].set(this.max.x, this.max.y, this.max.z).applyMatrix4(matrix); // 111
4327 this.setFromPoints(_points);
4331 _proto.translate = function translate(offset) {
4332 this.min.add(offset);
4333 this.max.add(offset);
4337 _proto.equals = function equals(box) {
4338 return box.min.equals(this.min) && box.max.equals(this.max);
4344 function satForAxes(axes, v0, v1, v2, extents) {
4345 for (var i = 0, j = axes.length - 3; i <= j; i += 3) {
4346 _testAxis.fromArray(axes, i); // project the aabb onto the seperating axis
4349 var r = extents.x * Math.abs(_testAxis.x) + extents.y * Math.abs(_testAxis.y) + extents.z * Math.abs(_testAxis.z); // project all 3 vertices of the triangle onto the seperating axis
4351 var p0 = v0.dot(_testAxis);
4352 var p1 = v1.dot(_testAxis);
4353 var p2 = v2.dot(_testAxis); // actual test, basically see if either of the most extreme of the triangle points intersects r
4355 if (Math.max(-Math.max(p0, p1, p2), Math.min(p0, p1, p2)) > r) {
4356 // points of the projected triangle are outside the projected half-length of the aabb
4357 // the axis is seperating and we can exit
4365 var _points = [/*@__PURE__*/new Vector3(), /*@__PURE__*/new Vector3(), /*@__PURE__*/new Vector3(), /*@__PURE__*/new Vector3(), /*@__PURE__*/new Vector3(), /*@__PURE__*/new Vector3(), /*@__PURE__*/new Vector3(), /*@__PURE__*/new Vector3()];
4367 var _vector$1 = /*@__PURE__*/new Vector3();
4369 var _box = /*@__PURE__*/new Box3(); // triangle centered vertices
4372 var _v0 = /*@__PURE__*/new Vector3();
4374 var _v1 = /*@__PURE__*/new Vector3();
4376 var _v2 = /*@__PURE__*/new Vector3(); // triangle edge vectors
4379 var _f0 = /*@__PURE__*/new Vector3();
4381 var _f1 = /*@__PURE__*/new Vector3();
4383 var _f2 = /*@__PURE__*/new Vector3();
4385 var _center = /*@__PURE__*/new Vector3();
4387 var _extents = /*@__PURE__*/new Vector3();
4389 var _triangleNormal = /*@__PURE__*/new Vector3();
4391 var _testAxis = /*@__PURE__*/new Vector3();
4393 var _box$1 = /*@__PURE__*/new Box3();
4395 var Sphere = /*#__PURE__*/function () {
4396 function Sphere(center, radius) {
4397 this.center = center !== undefined ? center : new Vector3();
4398 this.radius = radius !== undefined ? radius : -1;
4401 var _proto = Sphere.prototype;
4403 _proto.set = function set(center, radius) {
4404 this.center.copy(center);
4405 this.radius = radius;
4409 _proto.setFromPoints = function setFromPoints(points, optionalCenter) {
4410 var center = this.center;
4412 if (optionalCenter !== undefined) {
4413 center.copy(optionalCenter);
4415 _box$1.setFromPoints(points).getCenter(center);
4418 var maxRadiusSq = 0;
4420 for (var i = 0, il = points.length; i < il; i++) {
4421 maxRadiusSq = Math.max(maxRadiusSq, center.distanceToSquared(points[i]));
4424 this.radius = Math.sqrt(maxRadiusSq);
4428 _proto.clone = function clone() {
4429 return new this.constructor().copy(this);
4432 _proto.copy = function copy(sphere) {
4433 this.center.copy(sphere.center);
4434 this.radius = sphere.radius;
4438 _proto.isEmpty = function isEmpty() {
4439 return this.radius < 0;
4442 _proto.makeEmpty = function makeEmpty() {
4443 this.center.set(0, 0, 0);
4448 _proto.containsPoint = function containsPoint(point) {
4449 return point.distanceToSquared(this.center) <= this.radius * this.radius;
4452 _proto.distanceToPoint = function distanceToPoint(point) {
4453 return point.distanceTo(this.center) - this.radius;
4456 _proto.intersectsSphere = function intersectsSphere(sphere) {
4457 var radiusSum = this.radius + sphere.radius;
4458 return sphere.center.distanceToSquared(this.center) <= radiusSum * radiusSum;
4461 _proto.intersectsBox = function intersectsBox(box) {
4462 return box.intersectsSphere(this);
4465 _proto.intersectsPlane = function intersectsPlane(plane) {
4466 return Math.abs(plane.distanceToPoint(this.center)) <= this.radius;
4469 _proto.clampPoint = function clampPoint(point, target) {
4470 var deltaLengthSq = this.center.distanceToSquared(point);
4472 if (target === undefined) {
4473 console.warn('THREE.Sphere: .clampPoint() target is now required');
4474 target = new Vector3();
4479 if (deltaLengthSq > this.radius * this.radius) {
4480 target.sub(this.center).normalize();
4481 target.multiplyScalar(this.radius).add(this.center);
4487 _proto.getBoundingBox = function getBoundingBox(target) {
4488 if (target === undefined) {
4489 console.warn('THREE.Sphere: .getBoundingBox() target is now required');
4490 target = new Box3();
4493 if (this.isEmpty()) {
4494 // Empty sphere produces empty bounding box
4499 target.set(this.center, this.center);
4500 target.expandByScalar(this.radius);
4504 _proto.applyMatrix4 = function applyMatrix4(matrix) {
4505 this.center.applyMatrix4(matrix);
4506 this.radius = this.radius * matrix.getMaxScaleOnAxis();
4510 _proto.translate = function translate(offset) {
4511 this.center.add(offset);
4515 _proto.equals = function equals(sphere) {
4516 return sphere.center.equals(this.center) && sphere.radius === this.radius;
4522 var _vector$2 = /*@__PURE__*/new Vector3();
4524 var _segCenter = /*@__PURE__*/new Vector3();
4526 var _segDir = /*@__PURE__*/new Vector3();
4528 var _diff = /*@__PURE__*/new Vector3();
4530 var _edge1 = /*@__PURE__*/new Vector3();
4532 var _edge2 = /*@__PURE__*/new Vector3();
4534 var _normal = /*@__PURE__*/new Vector3();
4536 var Ray = /*#__PURE__*/function () {
4537 function Ray(origin, direction) {
4538 this.origin = origin !== undefined ? origin : new Vector3();
4539 this.direction = direction !== undefined ? direction : new Vector3(0, 0, -1);
4542 var _proto = Ray.prototype;
4544 _proto.set = function set(origin, direction) {
4545 this.origin.copy(origin);
4546 this.direction.copy(direction);
4550 _proto.clone = function clone() {
4551 return new this.constructor().copy(this);
4554 _proto.copy = function copy(ray) {
4555 this.origin.copy(ray.origin);
4556 this.direction.copy(ray.direction);
4560 _proto.at = function at(t, target) {
4561 if (target === undefined) {
4562 console.warn('THREE.Ray: .at() target is now required');
4563 target = new Vector3();
4566 return target.copy(this.direction).multiplyScalar(t).add(this.origin);
4569 _proto.lookAt = function lookAt(v) {
4570 this.direction.copy(v).sub(this.origin).normalize();
4574 _proto.recast = function recast(t) {
4575 this.origin.copy(this.at(t, _vector$2));
4579 _proto.closestPointToPoint = function closestPointToPoint(point, target) {
4580 if (target === undefined) {
4581 console.warn('THREE.Ray: .closestPointToPoint() target is now required');
4582 target = new Vector3();
4585 target.subVectors(point, this.origin);
4586 var directionDistance = target.dot(this.direction);
4588 if (directionDistance < 0) {
4589 return target.copy(this.origin);
4592 return target.copy(this.direction).multiplyScalar(directionDistance).add(this.origin);
4595 _proto.distanceToPoint = function distanceToPoint(point) {
4596 return Math.sqrt(this.distanceSqToPoint(point));
4599 _proto.distanceSqToPoint = function distanceSqToPoint(point) {
4600 var directionDistance = _vector$2.subVectors(point, this.origin).dot(this.direction); // point behind the ray
4603 if (directionDistance < 0) {
4604 return this.origin.distanceToSquared(point);
4607 _vector$2.copy(this.direction).multiplyScalar(directionDistance).add(this.origin);
4609 return _vector$2.distanceToSquared(point);
4612 _proto.distanceSqToSegment = function distanceSqToSegment(v0, v1, optionalPointOnRay, optionalPointOnSegment) {
4613 // from http://www.geometrictools.com/GTEngine/Include/Mathematics/GteDistRaySegment.h
4614 // It returns the min distance between the ray and the segment
4615 // defined by v0 and v1
4616 // It can also set two optional targets :
4617 // - The closest point on the ray
4618 // - The closest point on the segment
4619 _segCenter.copy(v0).add(v1).multiplyScalar(0.5);
4621 _segDir.copy(v1).sub(v0).normalize();
4623 _diff.copy(this.origin).sub(_segCenter);
4625 var segExtent = v0.distanceTo(v1) * 0.5;
4626 var a01 = -this.direction.dot(_segDir);
4628 var b0 = _diff.dot(this.direction);
4630 var b1 = -_diff.dot(_segDir);
4632 var c = _diff.lengthSq();
4634 var det = Math.abs(1 - a01 * a01);
4635 var s0, s1, sqrDist, extDet;
4638 // The ray and segment are not parallel.
4641 extDet = segExtent * det;
4644 if (s1 >= -extDet) {
4647 // Minimum at interior points of ray and segment.
4648 var invDet = 1 / det;
4651 sqrDist = s0 * (s0 + a01 * s1 + 2 * b0) + s1 * (a01 * s0 + s1 + 2 * b1) + c;
4655 s0 = Math.max(0, -(a01 * s1 + b0));
4656 sqrDist = -s0 * s0 + s1 * (s1 + 2 * b1) + c;
4661 s0 = Math.max(0, -(a01 * s1 + b0));
4662 sqrDist = -s0 * s0 + s1 * (s1 + 2 * b1) + c;
4665 if (s1 <= -extDet) {
4667 s0 = Math.max(0, -(-a01 * segExtent + b0));
4668 s1 = s0 > 0 ? -segExtent : Math.min(Math.max(-segExtent, -b1), segExtent);
4669 sqrDist = -s0 * s0 + s1 * (s1 + 2 * b1) + c;
4670 } else if (s1 <= extDet) {
4673 s1 = Math.min(Math.max(-segExtent, -b1), segExtent);
4674 sqrDist = s1 * (s1 + 2 * b1) + c;
4677 s0 = Math.max(0, -(a01 * segExtent + b0));
4678 s1 = s0 > 0 ? segExtent : Math.min(Math.max(-segExtent, -b1), segExtent);
4679 sqrDist = -s0 * s0 + s1 * (s1 + 2 * b1) + c;
4683 // Ray and segment are parallel.
4684 s1 = a01 > 0 ? -segExtent : segExtent;
4685 s0 = Math.max(0, -(a01 * s1 + b0));
4686 sqrDist = -s0 * s0 + s1 * (s1 + 2 * b1) + c;
4689 if (optionalPointOnRay) {
4690 optionalPointOnRay.copy(this.direction).multiplyScalar(s0).add(this.origin);
4693 if (optionalPointOnSegment) {
4694 optionalPointOnSegment.copy(_segDir).multiplyScalar(s1).add(_segCenter);
4700 _proto.intersectSphere = function intersectSphere(sphere, target) {
4701 _vector$2.subVectors(sphere.center, this.origin);
4703 var tca = _vector$2.dot(this.direction);
4705 var d2 = _vector$2.dot(_vector$2) - tca * tca;
4706 var radius2 = sphere.radius * sphere.radius;
4707 if (d2 > radius2) return null;
4708 var thc = Math.sqrt(radius2 - d2); // t0 = first intersect point - entrance on front of sphere
4710 var t0 = tca - thc; // t1 = second intersect point - exit point on back of sphere
4712 var t1 = tca + thc; // test to see if both t0 and t1 are behind the ray - if so, return null
4714 if (t0 < 0 && t1 < 0) return null; // test to see if t0 is behind the ray:
4715 // if it is, the ray is inside the sphere, so return the second exit point scaled by t1,
4716 // in order to always return an intersect point that is in front of the ray.
4718 if (t0 < 0) return this.at(t1, target); // else t0 is in front of the ray, so return the first collision point scaled by t0
4720 return this.at(t0, target);
4723 _proto.intersectsSphere = function intersectsSphere(sphere) {
4724 return this.distanceSqToPoint(sphere.center) <= sphere.radius * sphere.radius;
4727 _proto.distanceToPlane = function distanceToPlane(plane) {
4728 var denominator = plane.normal.dot(this.direction);
4730 if (denominator === 0) {
4731 // line is coplanar, return origin
4732 if (plane.distanceToPoint(this.origin) === 0) {
4734 } // Null is preferable to undefined since undefined means.... it is undefined
4740 var t = -(this.origin.dot(plane.normal) + plane.constant) / denominator; // Return if the ray never intersects the plane
4742 return t >= 0 ? t : null;
4745 _proto.intersectPlane = function intersectPlane(plane, target) {
4746 var t = this.distanceToPlane(plane);
4752 return this.at(t, target);
4755 _proto.intersectsPlane = function intersectsPlane(plane) {
4756 // check if the ray lies on the plane first
4757 var distToPoint = plane.distanceToPoint(this.origin);
4759 if (distToPoint === 0) {
4763 var denominator = plane.normal.dot(this.direction);
4765 if (denominator * distToPoint < 0) {
4767 } // ray origin is behind the plane (and is pointing behind it)
4773 _proto.intersectBox = function intersectBox(box, target) {
4774 var tmin, tmax, tymin, tymax, tzmin, tzmax;
4775 var invdirx = 1 / this.direction.x,
4776 invdiry = 1 / this.direction.y,
4777 invdirz = 1 / this.direction.z;
4778 var origin = this.origin;
4781 tmin = (box.min.x - origin.x) * invdirx;
4782 tmax = (box.max.x - origin.x) * invdirx;
4784 tmin = (box.max.x - origin.x) * invdirx;
4785 tmax = (box.min.x - origin.x) * invdirx;
4789 tymin = (box.min.y - origin.y) * invdiry;
4790 tymax = (box.max.y - origin.y) * invdiry;
4792 tymin = (box.max.y - origin.y) * invdiry;
4793 tymax = (box.min.y - origin.y) * invdiry;
4796 if (tmin > tymax || tymin > tmax) return null; // These lines also handle the case where tmin or tmax is NaN
4797 // (result of 0 * Infinity). x !== x returns true if x is NaN
4799 if (tymin > tmin || tmin !== tmin) tmin = tymin;
4800 if (tymax < tmax || tmax !== tmax) tmax = tymax;
4803 tzmin = (box.min.z - origin.z) * invdirz;
4804 tzmax = (box.max.z - origin.z) * invdirz;
4806 tzmin = (box.max.z - origin.z) * invdirz;
4807 tzmax = (box.min.z - origin.z) * invdirz;
4810 if (tmin > tzmax || tzmin > tmax) return null;
4811 if (tzmin > tmin || tmin !== tmin) tmin = tzmin;
4812 if (tzmax < tmax || tmax !== tmax) tmax = tzmax; //return point closest to the ray (positive side)
4814 if (tmax < 0) return null;
4815 return this.at(tmin >= 0 ? tmin : tmax, target);
4818 _proto.intersectsBox = function intersectsBox(box) {
4819 return this.intersectBox(box, _vector$2) !== null;
4822 _proto.intersectTriangle = function intersectTriangle(a, b, c, backfaceCulling, target) {
4823 // Compute the offset origin, edges, and normal.
4824 // from http://www.geometrictools.com/GTEngine/Include/Mathematics/GteIntrRay3Triangle3.h
4825 _edge1.subVectors(b, a);
4827 _edge2.subVectors(c, a);
4829 _normal.crossVectors(_edge1, _edge2); // Solve Q + t*D = b1*E1 + b2*E2 (Q = kDiff, D = ray direction,
4830 // E1 = kEdge1, E2 = kEdge2, N = Cross(E1,E2)) by
4831 // |Dot(D,N)|*b1 = sign(Dot(D,N))*Dot(D,Cross(Q,E2))
4832 // |Dot(D,N)|*b2 = sign(Dot(D,N))*Dot(D,Cross(E1,Q))
4833 // |Dot(D,N)|*t = -sign(Dot(D,N))*Dot(Q,N)
4836 var DdN = this.direction.dot(_normal);
4840 if (backfaceCulling) return null;
4842 } else if (DdN < 0) {
4849 _diff.subVectors(this.origin, a);
4851 var DdQxE2 = sign * this.direction.dot(_edge2.crossVectors(_diff, _edge2)); // b1 < 0, no intersection
4857 var DdE1xQ = sign * this.direction.dot(_edge1.cross(_diff)); // b2 < 0, no intersection
4861 } // b1+b2 > 1, no intersection
4864 if (DdQxE2 + DdE1xQ > DdN) {
4866 } // Line intersects triangle, check if ray does.
4869 var QdN = -sign * _diff.dot(_normal); // t < 0, no intersection
4874 } // Ray intersects triangle.
4877 return this.at(QdN / DdN, target);
4880 _proto.applyMatrix4 = function applyMatrix4(matrix4) {
4881 this.origin.applyMatrix4(matrix4);
4882 this.direction.transformDirection(matrix4);
4886 _proto.equals = function equals(ray) {
4887 return ray.origin.equals(this.origin) && ray.direction.equals(this.direction);
4893 var Matrix4 = /*#__PURE__*/function () {
4894 function Matrix4() {
4895 Object.defineProperty(this, 'isMatrix4', {
4898 this.elements = [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1];
4900 if (arguments.length > 0) {
4901 console.error('THREE.Matrix4: the constructor no longer reads arguments. use .set() instead.');
4905 var _proto = Matrix4.prototype;
4907 _proto.set = function set(n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44) {
4908 var te = this.elements;
4928 _proto.identity = function identity() {
4929 this.set(1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1);
4933 _proto.clone = function clone() {
4934 return new Matrix4().fromArray(this.elements);
4937 _proto.copy = function copy(m) {
4938 var te = this.elements;
4939 var me = m.elements;
4959 _proto.copyPosition = function copyPosition(m) {
4960 var te = this.elements,
4968 _proto.setFromMatrix3 = function setFromMatrix3(m) {
4969 var me = m.elements;
4970 this.set(me[0], me[3], me[6], 0, me[1], me[4], me[7], 0, me[2], me[5], me[8], 0, 0, 0, 0, 1);
4974 _proto.extractBasis = function extractBasis(xAxis, yAxis, zAxis) {
4975 xAxis.setFromMatrixColumn(this, 0);
4976 yAxis.setFromMatrixColumn(this, 1);
4977 zAxis.setFromMatrixColumn(this, 2);
4981 _proto.makeBasis = function makeBasis(xAxis, yAxis, zAxis) {
4982 this.set(xAxis.x, yAxis.x, zAxis.x, 0, xAxis.y, yAxis.y, zAxis.y, 0, xAxis.z, yAxis.z, zAxis.z, 0, 0, 0, 0, 1);
4986 _proto.extractRotation = function extractRotation(m) {
4987 // this method does not support reflection matrices
4988 var te = this.elements;
4989 var me = m.elements;
4991 var scaleX = 1 / _v1$1.setFromMatrixColumn(m, 0).length();
4993 var scaleY = 1 / _v1$1.setFromMatrixColumn(m, 1).length();
4995 var scaleZ = 1 / _v1$1.setFromMatrixColumn(m, 2).length();
4997 te[0] = me[0] * scaleX;
4998 te[1] = me[1] * scaleX;
4999 te[2] = me[2] * scaleX;
5001 te[4] = me[4] * scaleY;
5002 te[5] = me[5] * scaleY;
5003 te[6] = me[6] * scaleY;
5005 te[8] = me[8] * scaleZ;
5006 te[9] = me[9] * scaleZ;
5007 te[10] = me[10] * scaleZ;
5016 _proto.makeRotationFromEuler = function makeRotationFromEuler(euler) {
5017 if (!(euler && euler.isEuler)) {
5018 console.error('THREE.Matrix4: .makeRotationFromEuler() now expects a Euler rotation rather than a Vector3 and order.');
5021 var te = this.elements;
5025 var a = Math.cos(x),
5027 var c = Math.cos(y),
5029 var e = Math.cos(z),
5032 if (euler.order === 'XYZ') {
5040 te[1] = af + be * d;
5041 te[5] = ae - bf * d;
5043 te[2] = bf - ae * d;
5044 te[6] = be + af * d;
5046 } else if (euler.order === 'YXZ') {
5051 te[0] = ce + df * b;
5052 te[4] = de * b - cf;
5057 te[2] = cf * b - de;
5058 te[6] = df + ce * b;
5060 } else if (euler.order === 'ZXY') {
5066 te[0] = _ce - _df * b;
5068 te[8] = _de + _cf * b;
5069 te[1] = _cf + _de * b;
5071 te[9] = _df - _ce * b;
5075 } else if (euler.order === 'ZYX') {
5082 te[4] = _be * d - _af;
5083 te[8] = _ae * d + _bf;
5085 te[5] = _bf * d + _ae;
5086 te[9] = _af * d - _be;
5090 } else if (euler.order === 'YZX') {
5096 te[4] = bd - ac * f;
5097 te[8] = bc * f + ad;
5102 te[6] = ad * f + bc;
5103 te[10] = ac - bd * f;
5104 } else if (euler.order === 'XZY') {
5113 te[1] = _ac * f + _bd;
5115 te[9] = _ad * f - _bc;
5116 te[2] = _bc * f - _ad;
5118 te[10] = _bd * f + _ac;
5124 te[11] = 0; // last column
5133 _proto.makeRotationFromQuaternion = function makeRotationFromQuaternion(q) {
5134 return this.compose(_zero, q, _one);
5137 _proto.lookAt = function lookAt(eye, target, up) {
5138 var te = this.elements;
5140 _z.subVectors(eye, target);
5142 if (_z.lengthSq() === 0) {
5143 // eye and target are in the same position
5149 _x.crossVectors(up, _z);
5151 if (_x.lengthSq() === 0) {
5152 // up and z are parallel
5153 if (Math.abs(up.z) === 1) {
5161 _x.crossVectors(up, _z);
5166 _y.crossVectors(_z, _x);
5180 _proto.multiply = function multiply(m, n) {
5181 if (n !== undefined) {
5182 console.warn('THREE.Matrix4: .multiply() now only accepts one argument. Use .multiplyMatrices( a, b ) instead.');
5183 return this.multiplyMatrices(m, n);
5186 return this.multiplyMatrices(this, m);
5189 _proto.premultiply = function premultiply(m) {
5190 return this.multiplyMatrices(m, this);
5193 _proto.multiplyMatrices = function multiplyMatrices(a, b) {
5194 var ae = a.elements;
5195 var be = b.elements;
5196 var te = this.elements;
5229 te[0] = a11 * b11 + a12 * b21 + a13 * b31 + a14 * b41;
5230 te[4] = a11 * b12 + a12 * b22 + a13 * b32 + a14 * b42;
5231 te[8] = a11 * b13 + a12 * b23 + a13 * b33 + a14 * b43;
5232 te[12] = a11 * b14 + a12 * b24 + a13 * b34 + a14 * b44;
5233 te[1] = a21 * b11 + a22 * b21 + a23 * b31 + a24 * b41;
5234 te[5] = a21 * b12 + a22 * b22 + a23 * b32 + a24 * b42;
5235 te[9] = a21 * b13 + a22 * b23 + a23 * b33 + a24 * b43;
5236 te[13] = a21 * b14 + a22 * b24 + a23 * b34 + a24 * b44;
5237 te[2] = a31 * b11 + a32 * b21 + a33 * b31 + a34 * b41;
5238 te[6] = a31 * b12 + a32 * b22 + a33 * b32 + a34 * b42;
5239 te[10] = a31 * b13 + a32 * b23 + a33 * b33 + a34 * b43;
5240 te[14] = a31 * b14 + a32 * b24 + a33 * b34 + a34 * b44;
5241 te[3] = a41 * b11 + a42 * b21 + a43 * b31 + a44 * b41;
5242 te[7] = a41 * b12 + a42 * b22 + a43 * b32 + a44 * b42;
5243 te[11] = a41 * b13 + a42 * b23 + a43 * b33 + a44 * b43;
5244 te[15] = a41 * b14 + a42 * b24 + a43 * b34 + a44 * b44;
5248 _proto.multiplyScalar = function multiplyScalar(s) {
5249 var te = this.elements;
5269 _proto.determinant = function determinant() {
5270 var te = this.elements;
5286 n44 = te[15]; //TODO: make this more efficient
5287 //( based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm )
5289 return n41 * (+n14 * n23 * n32 - n13 * n24 * n32 - n14 * n22 * n33 + n12 * n24 * n33 + n13 * n22 * n34 - n12 * n23 * n34) + n42 * (+n11 * n23 * n34 - n11 * n24 * n33 + n14 * n21 * n33 - n13 * n21 * n34 + n13 * n24 * n31 - n14 * n23 * n31) + n43 * (+n11 * n24 * n32 - n11 * n22 * n34 - n14 * n21 * n32 + n12 * n21 * n34 + n14 * n22 * n31 - n12 * n24 * n31) + n44 * (-n13 * n22 * n31 - n11 * n23 * n32 + n11 * n22 * n33 + n13 * n21 * n32 - n12 * n21 * n33 + n12 * n23 * n31);
5292 _proto.transpose = function transpose() {
5293 var te = this.elements;
5316 _proto.setPosition = function setPosition(x, y, z) {
5317 var te = this.elements;
5332 _proto.invert = function invert() {
5333 // based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm
5334 var te = this.elements,
5351 t11 = n23 * n34 * n42 - n24 * n33 * n42 + n24 * n32 * n43 - n22 * n34 * n43 - n23 * n32 * n44 + n22 * n33 * n44,
5352 t12 = n14 * n33 * n42 - n13 * n34 * n42 - n14 * n32 * n43 + n12 * n34 * n43 + n13 * n32 * n44 - n12 * n33 * n44,
5353 t13 = n13 * n24 * n42 - n14 * n23 * n42 + n14 * n22 * n43 - n12 * n24 * n43 - n13 * n22 * n44 + n12 * n23 * n44,
5354 t14 = n14 * n23 * n32 - n13 * n24 * n32 - n14 * n22 * n33 + n12 * n24 * n33 + n13 * n22 * n34 - n12 * n23 * n34;
5355 var det = n11 * t11 + n21 * t12 + n31 * t13 + n41 * t14;
5356 if (det === 0) return this.set(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
5357 var detInv = 1 / det;
5358 te[0] = t11 * detInv;
5359 te[1] = (n24 * n33 * n41 - n23 * n34 * n41 - n24 * n31 * n43 + n21 * n34 * n43 + n23 * n31 * n44 - n21 * n33 * n44) * detInv;
5360 te[2] = (n22 * n34 * n41 - n24 * n32 * n41 + n24 * n31 * n42 - n21 * n34 * n42 - n22 * n31 * n44 + n21 * n32 * n44) * detInv;
5361 te[3] = (n23 * n32 * n41 - n22 * n33 * n41 - n23 * n31 * n42 + n21 * n33 * n42 + n22 * n31 * n43 - n21 * n32 * n43) * detInv;
5362 te[4] = t12 * detInv;
5363 te[5] = (n13 * n34 * n41 - n14 * n33 * n41 + n14 * n31 * n43 - n11 * n34 * n43 - n13 * n31 * n44 + n11 * n33 * n44) * detInv;
5364 te[6] = (n14 * n32 * n41 - n12 * n34 * n41 - n14 * n31 * n42 + n11 * n34 * n42 + n12 * n31 * n44 - n11 * n32 * n44) * detInv;
5365 te[7] = (n12 * n33 * n41 - n13 * n32 * n41 + n13 * n31 * n42 - n11 * n33 * n42 - n12 * n31 * n43 + n11 * n32 * n43) * detInv;
5366 te[8] = t13 * detInv;
5367 te[9] = (n14 * n23 * n41 - n13 * n24 * n41 - n14 * n21 * n43 + n11 * n24 * n43 + n13 * n21 * n44 - n11 * n23 * n44) * detInv;
5368 te[10] = (n12 * n24 * n41 - n14 * n22 * n41 + n14 * n21 * n42 - n11 * n24 * n42 - n12 * n21 * n44 + n11 * n22 * n44) * detInv;
5369 te[11] = (n13 * n22 * n41 - n12 * n23 * n41 - n13 * n21 * n42 + n11 * n23 * n42 + n12 * n21 * n43 - n11 * n22 * n43) * detInv;
5370 te[12] = t14 * detInv;
5371 te[13] = (n13 * n24 * n31 - n14 * n23 * n31 + n14 * n21 * n33 - n11 * n24 * n33 - n13 * n21 * n34 + n11 * n23 * n34) * detInv;
5372 te[14] = (n14 * n22 * n31 - n12 * n24 * n31 - n14 * n21 * n32 + n11 * n24 * n32 + n12 * n21 * n34 - n11 * n22 * n34) * detInv;
5373 te[15] = (n12 * n23 * n31 - n13 * n22 * n31 + n13 * n21 * n32 - n11 * n23 * n32 - n12 * n21 * n33 + n11 * n22 * n33) * detInv;
5377 _proto.scale = function scale(v) {
5378 var te = this.elements;
5397 _proto.getMaxScaleOnAxis = function getMaxScaleOnAxis() {
5398 var te = this.elements;
5399 var scaleXSq = te[0] * te[0] + te[1] * te[1] + te[2] * te[2];
5400 var scaleYSq = te[4] * te[4] + te[5] * te[5] + te[6] * te[6];
5401 var scaleZSq = te[8] * te[8] + te[9] * te[9] + te[10] * te[10];
5402 return Math.sqrt(Math.max(scaleXSq, scaleYSq, scaleZSq));
5405 _proto.makeTranslation = function makeTranslation(x, y, z) {
5406 this.set(1, 0, 0, x, 0, 1, 0, y, 0, 0, 1, z, 0, 0, 0, 1);
5410 _proto.makeRotationX = function makeRotationX(theta) {
5411 var c = Math.cos(theta),
5412 s = Math.sin(theta);
5413 this.set(1, 0, 0, 0, 0, c, -s, 0, 0, s, c, 0, 0, 0, 0, 1);
5417 _proto.makeRotationY = function makeRotationY(theta) {
5418 var c = Math.cos(theta),
5419 s = Math.sin(theta);
5420 this.set(c, 0, s, 0, 0, 1, 0, 0, -s, 0, c, 0, 0, 0, 0, 1);
5424 _proto.makeRotationZ = function makeRotationZ(theta) {
5425 var c = Math.cos(theta),
5426 s = Math.sin(theta);
5427 this.set(c, -s, 0, 0, s, c, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1);
5431 _proto.makeRotationAxis = function makeRotationAxis(axis, angle) {
5432 // Based on http://www.gamedev.net/reference/articles/article1199.asp
5433 var c = Math.cos(angle);
5434 var s = Math.sin(angle);
5441 this.set(tx * x + c, tx * y - s * z, tx * z + s * y, 0, tx * y + s * z, ty * y + c, ty * z - s * x, 0, tx * z - s * y, ty * z + s * x, t * z * z + c, 0, 0, 0, 0, 1);
5445 _proto.makeScale = function makeScale(x, y, z) {
5446 this.set(x, 0, 0, 0, 0, y, 0, 0, 0, 0, z, 0, 0, 0, 0, 1);
5450 _proto.makeShear = function makeShear(x, y, z) {
5451 this.set(1, y, z, 0, x, 1, z, 0, x, y, 1, 0, 0, 0, 0, 1);
5455 _proto.compose = function compose(position, quaternion, scale) {
5456 var te = this.elements;
5457 var x = quaternion._x,
5476 te[0] = (1 - (yy + zz)) * sx;
5477 te[1] = (xy + wz) * sx;
5478 te[2] = (xz - wy) * sx;
5480 te[4] = (xy - wz) * sy;
5481 te[5] = (1 - (xx + zz)) * sy;
5482 te[6] = (yz + wx) * sy;
5484 te[8] = (xz + wy) * sz;
5485 te[9] = (yz - wx) * sz;
5486 te[10] = (1 - (xx + yy)) * sz;
5488 te[12] = position.x;
5489 te[13] = position.y;
5490 te[14] = position.z;
5495 _proto.decompose = function decompose(position, quaternion, scale) {
5496 var te = this.elements;
5498 var sx = _v1$1.set(te[0], te[1], te[2]).length();
5500 var sy = _v1$1.set(te[4], te[5], te[6]).length();
5502 var sz = _v1$1.set(te[8], te[9], te[10]).length(); // if determine is negative, we need to invert one scale
5505 var det = this.determinant();
5506 if (det < 0) sx = -sx;
5507 position.x = te[12];
5508 position.y = te[13];
5509 position.z = te[14]; // scale the rotation part
5516 _m1.elements[0] *= invSX;
5517 _m1.elements[1] *= invSX;
5518 _m1.elements[2] *= invSX;
5519 _m1.elements[4] *= invSY;
5520 _m1.elements[5] *= invSY;
5521 _m1.elements[6] *= invSY;
5522 _m1.elements[8] *= invSZ;
5523 _m1.elements[9] *= invSZ;
5524 _m1.elements[10] *= invSZ;
5525 quaternion.setFromRotationMatrix(_m1);
5532 _proto.makePerspective = function makePerspective(left, right, top, bottom, near, far) {
5533 if (far === undefined) {
5534 console.warn('THREE.Matrix4: .makePerspective() has been redefined and has a new signature. Please check the docs.');
5537 var te = this.elements;
5538 var x = 2 * near / (right - left);
5539 var y = 2 * near / (top - bottom);
5540 var a = (right + left) / (right - left);
5541 var b = (top + bottom) / (top - bottom);
5542 var c = -(far + near) / (far - near);
5543 var d = -2 * far * near / (far - near);
5563 _proto.makeOrthographic = function makeOrthographic(left, right, top, bottom, near, far) {
5564 var te = this.elements;
5565 var w = 1.0 / (right - left);
5566 var h = 1.0 / (top - bottom);
5567 var p = 1.0 / (far - near);
5568 var x = (right + left) * w;
5569 var y = (top + bottom) * h;
5570 var z = (far + near) * p;
5590 _proto.equals = function equals(matrix) {
5591 var te = this.elements;
5592 var me = matrix.elements;
5594 for (var i = 0; i < 16; i++) {
5595 if (te[i] !== me[i]) return false;
5601 _proto.fromArray = function fromArray(array, offset) {
5602 if (offset === void 0) {
5606 for (var i = 0; i < 16; i++) {
5607 this.elements[i] = array[i + offset];
5613 _proto.toArray = function toArray(array, offset) {
5614 if (array === void 0) {
5618 if (offset === void 0) {
5622 var te = this.elements;
5623 array[offset] = te[0];
5624 array[offset + 1] = te[1];
5625 array[offset + 2] = te[2];
5626 array[offset + 3] = te[3];
5627 array[offset + 4] = te[4];
5628 array[offset + 5] = te[5];
5629 array[offset + 6] = te[6];
5630 array[offset + 7] = te[7];
5631 array[offset + 8] = te[8];
5632 array[offset + 9] = te[9];
5633 array[offset + 10] = te[10];
5634 array[offset + 11] = te[11];
5635 array[offset + 12] = te[12];
5636 array[offset + 13] = te[13];
5637 array[offset + 14] = te[14];
5638 array[offset + 15] = te[15];
5645 var _v1$1 = /*@__PURE__*/new Vector3();
5647 var _m1 = /*@__PURE__*/new Matrix4();
5649 var _zero = /*@__PURE__*/new Vector3(0, 0, 0);
5651 var _one = /*@__PURE__*/new Vector3(1, 1, 1);
5653 var _x = /*@__PURE__*/new Vector3();
5655 var _y = /*@__PURE__*/new Vector3();
5657 var _z = /*@__PURE__*/new Vector3();
5659 var Euler = /*#__PURE__*/function () {
5660 function Euler(x, y, z, order) {
5673 if (order === void 0) {
5674 order = Euler.DefaultOrder;
5677 Object.defineProperty(this, 'isEuler', {
5683 this._order = order;
5686 var _proto = Euler.prototype;
5688 _proto.set = function set(x, y, z, order) {
5692 this._order = order || this._order;
5694 this._onChangeCallback();
5699 _proto.clone = function clone() {
5700 return new this.constructor(this._x, this._y, this._z, this._order);
5703 _proto.copy = function copy(euler) {
5707 this._order = euler._order;
5709 this._onChangeCallback();
5714 _proto.setFromRotationMatrix = function setFromRotationMatrix(m, order, update) {
5715 var clamp = MathUtils.clamp; // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
5717 var te = m.elements;
5727 order = order || this._order;
5731 this._y = Math.asin(clamp(m13, -1, 1));
5733 if (Math.abs(m13) < 0.9999999) {
5734 this._x = Math.atan2(-m23, m33);
5735 this._z = Math.atan2(-m12, m11);
5737 this._x = Math.atan2(m32, m22);
5744 this._x = Math.asin(-clamp(m23, -1, 1));
5746 if (Math.abs(m23) < 0.9999999) {
5747 this._y = Math.atan2(m13, m33);
5748 this._z = Math.atan2(m21, m22);
5750 this._y = Math.atan2(-m31, m11);
5757 this._x = Math.asin(clamp(m32, -1, 1));
5759 if (Math.abs(m32) < 0.9999999) {
5760 this._y = Math.atan2(-m31, m33);
5761 this._z = Math.atan2(-m12, m22);
5764 this._z = Math.atan2(m21, m11);
5770 this._y = Math.asin(-clamp(m31, -1, 1));
5772 if (Math.abs(m31) < 0.9999999) {
5773 this._x = Math.atan2(m32, m33);
5774 this._z = Math.atan2(m21, m11);
5777 this._z = Math.atan2(-m12, m22);
5783 this._z = Math.asin(clamp(m21, -1, 1));
5785 if (Math.abs(m21) < 0.9999999) {
5786 this._x = Math.atan2(-m23, m22);
5787 this._y = Math.atan2(-m31, m11);
5790 this._y = Math.atan2(m13, m33);
5796 this._z = Math.asin(-clamp(m12, -1, 1));
5798 if (Math.abs(m12) < 0.9999999) {
5799 this._x = Math.atan2(m32, m22);
5800 this._y = Math.atan2(m13, m11);
5802 this._x = Math.atan2(-m23, m33);
5809 console.warn('THREE.Euler: .setFromRotationMatrix() encountered an unknown order: ' + order);
5812 this._order = order;
5813 if (update !== false) this._onChangeCallback();
5817 _proto.setFromQuaternion = function setFromQuaternion(q, order, update) {
5818 _matrix.makeRotationFromQuaternion(q);
5820 return this.setFromRotationMatrix(_matrix, order, update);
5823 _proto.setFromVector3 = function setFromVector3(v, order) {
5824 return this.set(v.x, v.y, v.z, order || this._order);
5827 _proto.reorder = function reorder(newOrder) {
5828 // WARNING: this discards revolution information -bhouston
5829 _quaternion$1.setFromEuler(this);
5831 return this.setFromQuaternion(_quaternion$1, newOrder);
5834 _proto.equals = function equals(euler) {
5835 return euler._x === this._x && euler._y === this._y && euler._z === this._z && euler._order === this._order;
5838 _proto.fromArray = function fromArray(array) {
5842 if (array[3] !== undefined) this._order = array[3];
5844 this._onChangeCallback();
5849 _proto.toArray = function toArray(array, offset) {
5850 if (array === void 0) {
5854 if (offset === void 0) {
5858 array[offset] = this._x;
5859 array[offset + 1] = this._y;
5860 array[offset + 2] = this._z;
5861 array[offset + 3] = this._order;
5865 _proto.toVector3 = function toVector3(optionalResult) {
5866 if (optionalResult) {
5867 return optionalResult.set(this._x, this._y, this._z);
5869 return new Vector3(this._x, this._y, this._z);
5873 _proto._onChange = function _onChange(callback) {
5874 this._onChangeCallback = callback;
5878 _proto._onChangeCallback = function _onChangeCallback() {};
5880 _createClass(Euler, [{
5882 get: function get() {
5885 set: function set(value) {
5888 this._onChangeCallback();
5892 get: function get() {
5895 set: function set(value) {
5898 this._onChangeCallback();
5902 get: function get() {
5905 set: function set(value) {
5908 this._onChangeCallback();
5912 get: function get() {
5915 set: function set(value) {
5916 this._order = value;
5918 this._onChangeCallback();
5925 Euler.DefaultOrder = 'XYZ';
5926 Euler.RotationOrders = ['XYZ', 'YZX', 'ZXY', 'XZY', 'YXZ', 'ZYX'];
5928 var _matrix = /*@__PURE__*/new Matrix4();
5930 var _quaternion$1 = /*@__PURE__*/new Quaternion();
5932 var Layers = /*#__PURE__*/function () {
5937 var _proto = Layers.prototype;
5939 _proto.set = function set(channel) {
5940 this.mask = 1 << channel | 0;
5943 _proto.enable = function enable(channel) {
5944 this.mask |= 1 << channel | 0;
5947 _proto.enableAll = function enableAll() {
5948 this.mask = 0xffffffff | 0;
5951 _proto.toggle = function toggle(channel) {
5952 this.mask ^= 1 << channel | 0;
5955 _proto.disable = function disable(channel) {
5956 this.mask &= ~(1 << channel | 0);
5959 _proto.disableAll = function disableAll() {
5963 _proto.test = function test(layers) {
5964 return (this.mask & layers.mask) !== 0;
5970 var _object3DId = 0;
5972 var _v1$2 = new Vector3();
5974 var _q1 = new Quaternion();
5976 var _m1$1 = new Matrix4();
5978 var _target = new Vector3();
5980 var _position = new Vector3();
5982 var _scale = new Vector3();
5984 var _quaternion$2 = new Quaternion();
5986 var _xAxis = new Vector3(1, 0, 0);
5988 var _yAxis = new Vector3(0, 1, 0);
5990 var _zAxis = new Vector3(0, 0, 1);
5995 var _removedEvent = {
5999 function Object3D() {
6000 Object.defineProperty(this, 'id', {
6001 value: _object3DId++
6003 this.uuid = MathUtils.generateUUID();
6005 this.type = 'Object3D';
6008 this.up = Object3D.DefaultUp.clone();
6009 var position = new Vector3();
6010 var rotation = new Euler();
6011 var quaternion = new Quaternion();
6012 var scale = new Vector3(1, 1, 1);
6014 function onRotationChange() {
6015 quaternion.setFromEuler(rotation, false);
6018 function onQuaternionChange() {
6019 rotation.setFromQuaternion(quaternion, undefined, false);
6022 rotation._onChange(onRotationChange);
6024 quaternion._onChange(onQuaternionChange);
6026 Object.defineProperties(this, {
6048 value: new Matrix4()
6051 value: new Matrix3()
6054 this.matrix = new Matrix4();
6055 this.matrixWorld = new Matrix4();
6056 this.matrixAutoUpdate = Object3D.DefaultMatrixAutoUpdate;
6057 this.matrixWorldNeedsUpdate = false;
6058 this.layers = new Layers();
6059 this.visible = true;
6060 this.castShadow = false;
6061 this.receiveShadow = false;
6062 this.frustumCulled = true;
6063 this.renderOrder = 0;
6064 this.animations = [];
6068 Object3D.DefaultUp = new Vector3(0, 1, 0);
6069 Object3D.DefaultMatrixAutoUpdate = true;
6070 Object3D.prototype = Object.assign(Object.create(EventDispatcher.prototype), {
6071 constructor: Object3D,
6073 onBeforeRender: function onBeforeRender() {},
6074 onAfterRender: function onAfterRender() {},
6075 applyMatrix4: function applyMatrix4(matrix) {
6076 if (this.matrixAutoUpdate) this.updateMatrix();
6077 this.matrix.premultiply(matrix);
6078 this.matrix.decompose(this.position, this.quaternion, this.scale);
6080 applyQuaternion: function applyQuaternion(q) {
6081 this.quaternion.premultiply(q);
6084 setRotationFromAxisAngle: function setRotationFromAxisAngle(axis, angle) {
6085 // assumes axis is normalized
6086 this.quaternion.setFromAxisAngle(axis, angle);
6088 setRotationFromEuler: function setRotationFromEuler(euler) {
6089 this.quaternion.setFromEuler(euler, true);
6091 setRotationFromMatrix: function setRotationFromMatrix(m) {
6092 // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
6093 this.quaternion.setFromRotationMatrix(m);
6095 setRotationFromQuaternion: function setRotationFromQuaternion(q) {
6096 // assumes q is normalized
6097 this.quaternion.copy(q);
6099 rotateOnAxis: function rotateOnAxis(axis, angle) {
6100 // rotate object on axis in object space
6101 // axis is assumed to be normalized
6102 _q1.setFromAxisAngle(axis, angle);
6104 this.quaternion.multiply(_q1);
6107 rotateOnWorldAxis: function rotateOnWorldAxis(axis, angle) {
6108 // rotate object on axis in world space
6109 // axis is assumed to be normalized
6110 // method assumes no rotated parent
6111 _q1.setFromAxisAngle(axis, angle);
6113 this.quaternion.premultiply(_q1);
6116 rotateX: function rotateX(angle) {
6117 return this.rotateOnAxis(_xAxis, angle);
6119 rotateY: function rotateY(angle) {
6120 return this.rotateOnAxis(_yAxis, angle);
6122 rotateZ: function rotateZ(angle) {
6123 return this.rotateOnAxis(_zAxis, angle);
6125 translateOnAxis: function translateOnAxis(axis, distance) {
6126 // translate object by distance along axis in object space
6127 // axis is assumed to be normalized
6128 _v1$2.copy(axis).applyQuaternion(this.quaternion);
6130 this.position.add(_v1$2.multiplyScalar(distance));
6133 translateX: function translateX(distance) {
6134 return this.translateOnAxis(_xAxis, distance);
6136 translateY: function translateY(distance) {
6137 return this.translateOnAxis(_yAxis, distance);
6139 translateZ: function translateZ(distance) {
6140 return this.translateOnAxis(_zAxis, distance);
6142 localToWorld: function localToWorld(vector) {
6143 return vector.applyMatrix4(this.matrixWorld);
6145 worldToLocal: function worldToLocal(vector) {
6146 return vector.applyMatrix4(_m1$1.copy(this.matrixWorld).invert());
6148 lookAt: function lookAt(x, y, z) {
6149 // This method does not support objects having non-uniformly-scaled parent(s)
6153 _target.set(x, y, z);
6156 var parent = this.parent;
6157 this.updateWorldMatrix(true, false);
6159 _position.setFromMatrixPosition(this.matrixWorld);
6161 if (this.isCamera || this.isLight) {
6162 _m1$1.lookAt(_position, _target, this.up);
6164 _m1$1.lookAt(_target, _position, this.up);
6167 this.quaternion.setFromRotationMatrix(_m1$1);
6170 _m1$1.extractRotation(parent.matrixWorld);
6172 _q1.setFromRotationMatrix(_m1$1);
6174 this.quaternion.premultiply(_q1.invert());
6177 add: function add(object) {
6178 if (arguments.length > 1) {
6179 for (var i = 0; i < arguments.length; i++) {
6180 this.add(arguments[i]);
6186 if (object === this) {
6187 console.error('THREE.Object3D.add: object can\'t be added as a child of itself.', object);
6191 if (object && object.isObject3D) {
6192 if (object.parent !== null) {
6193 object.parent.remove(object);
6196 object.parent = this;
6197 this.children.push(object);
6198 object.dispatchEvent(_addedEvent);
6200 console.error('THREE.Object3D.add: object not an instance of THREE.Object3D.', object);
6205 remove: function remove(object) {
6206 if (arguments.length > 1) {
6207 for (var i = 0; i < arguments.length; i++) {
6208 this.remove(arguments[i]);
6214 var index = this.children.indexOf(object);
6217 object.parent = null;
6218 this.children.splice(index, 1);
6219 object.dispatchEvent(_removedEvent);
6224 clear: function clear() {
6225 for (var i = 0; i < this.children.length; i++) {
6226 var object = this.children[i];
6227 object.parent = null;
6228 object.dispatchEvent(_removedEvent);
6231 this.children.length = 0;
6234 attach: function attach(object) {
6235 // adds object as a child of this, while maintaining the object's world transform
6236 this.updateWorldMatrix(true, false);
6238 _m1$1.copy(this.matrixWorld).invert();
6240 if (object.parent !== null) {
6241 object.parent.updateWorldMatrix(true, false);
6243 _m1$1.multiply(object.parent.matrixWorld);
6246 object.applyMatrix4(_m1$1);
6247 object.updateWorldMatrix(false, false);
6251 getObjectById: function getObjectById(id) {
6252 return this.getObjectByProperty('id', id);
6254 getObjectByName: function getObjectByName(name) {
6255 return this.getObjectByProperty('name', name);
6257 getObjectByProperty: function getObjectByProperty(name, value) {
6258 if (this[name] === value) return this;
6260 for (var i = 0, l = this.children.length; i < l; i++) {
6261 var child = this.children[i];
6262 var object = child.getObjectByProperty(name, value);
6264 if (object !== undefined) {
6271 getWorldPosition: function getWorldPosition(target) {
6272 if (target === undefined) {
6273 console.warn('THREE.Object3D: .getWorldPosition() target is now required');
6274 target = new Vector3();
6277 this.updateWorldMatrix(true, false);
6278 return target.setFromMatrixPosition(this.matrixWorld);
6280 getWorldQuaternion: function getWorldQuaternion(target) {
6281 if (target === undefined) {
6282 console.warn('THREE.Object3D: .getWorldQuaternion() target is now required');
6283 target = new Quaternion();
6286 this.updateWorldMatrix(true, false);
6287 this.matrixWorld.decompose(_position, target, _scale);
6290 getWorldScale: function getWorldScale(target) {
6291 if (target === undefined) {
6292 console.warn('THREE.Object3D: .getWorldScale() target is now required');
6293 target = new Vector3();
6296 this.updateWorldMatrix(true, false);
6297 this.matrixWorld.decompose(_position, _quaternion$2, target);
6300 getWorldDirection: function getWorldDirection(target) {
6301 if (target === undefined) {
6302 console.warn('THREE.Object3D: .getWorldDirection() target is now required');
6303 target = new Vector3();
6306 this.updateWorldMatrix(true, false);
6307 var e = this.matrixWorld.elements;
6308 return target.set(e[8], e[9], e[10]).normalize();
6310 raycast: function raycast() {},
6311 traverse: function traverse(callback) {
6313 var children = this.children;
6315 for (var i = 0, l = children.length; i < l; i++) {
6316 children[i].traverse(callback);
6319 traverseVisible: function traverseVisible(callback) {
6320 if (this.visible === false) return;
6322 var children = this.children;
6324 for (var i = 0, l = children.length; i < l; i++) {
6325 children[i].traverseVisible(callback);
6328 traverseAncestors: function traverseAncestors(callback) {
6329 var parent = this.parent;
6331 if (parent !== null) {
6333 parent.traverseAncestors(callback);
6336 updateMatrix: function updateMatrix() {
6337 this.matrix.compose(this.position, this.quaternion, this.scale);
6338 this.matrixWorldNeedsUpdate = true;
6340 updateMatrixWorld: function updateMatrixWorld(force) {
6341 if (this.matrixAutoUpdate) this.updateMatrix();
6343 if (this.matrixWorldNeedsUpdate || force) {
6344 if (this.parent === null) {
6345 this.matrixWorld.copy(this.matrix);
6347 this.matrixWorld.multiplyMatrices(this.parent.matrixWorld, this.matrix);
6350 this.matrixWorldNeedsUpdate = false;
6352 } // update children
6355 var children = this.children;
6357 for (var i = 0, l = children.length; i < l; i++) {
6358 children[i].updateMatrixWorld(force);
6361 updateWorldMatrix: function updateWorldMatrix(updateParents, updateChildren) {
6362 var parent = this.parent;
6364 if (updateParents === true && parent !== null) {
6365 parent.updateWorldMatrix(true, false);
6368 if (this.matrixAutoUpdate) this.updateMatrix();
6370 if (this.parent === null) {
6371 this.matrixWorld.copy(this.matrix);
6373 this.matrixWorld.multiplyMatrices(this.parent.matrixWorld, this.matrix);
6374 } // update children
6377 if (updateChildren === true) {
6378 var children = this.children;
6380 for (var i = 0, l = children.length; i < l; i++) {
6381 children[i].updateWorldMatrix(false, true);
6385 toJSON: function toJSON(meta) {
6386 // meta is a string when called from JSON.stringify
6387 var isRootObject = meta === undefined || typeof meta === 'string';
6388 var output = {}; // meta is a hash used to collect geometries, materials.
6389 // not providing it implies that this is the root object
6390 // being serialized.
6393 // initialize meta obj
6406 generator: 'Object3D.toJSON'
6408 } // standard Object3D serialization
6412 object.uuid = this.uuid;
6413 object.type = this.type;
6414 if (this.name !== '') object.name = this.name;
6415 if (this.castShadow === true) object.castShadow = true;
6416 if (this.receiveShadow === true) object.receiveShadow = true;
6417 if (this.visible === false) object.visible = false;
6418 if (this.frustumCulled === false) object.frustumCulled = false;
6419 if (this.renderOrder !== 0) object.renderOrder = this.renderOrder;
6420 if (JSON.stringify(this.userData) !== '{}') object.userData = this.userData;
6421 object.layers = this.layers.mask;
6422 object.matrix = this.matrix.toArray();
6423 if (this.matrixAutoUpdate === false) object.matrixAutoUpdate = false; // object specific properties
6425 if (this.isInstancedMesh) {
6426 object.type = 'InstancedMesh';
6427 object.count = this.count;
6428 object.instanceMatrix = this.instanceMatrix.toJSON();
6432 function serialize(library, element) {
6433 if (library[element.uuid] === undefined) {
6434 library[element.uuid] = element.toJSON(meta);
6437 return element.uuid;
6440 if (this.isMesh || this.isLine || this.isPoints) {
6441 object.geometry = serialize(meta.geometries, this.geometry);
6442 var parameters = this.geometry.parameters;
6444 if (parameters !== undefined && parameters.shapes !== undefined) {
6445 var shapes = parameters.shapes;
6447 if (Array.isArray(shapes)) {
6448 for (var i = 0, l = shapes.length; i < l; i++) {
6449 var shape = shapes[i];
6450 serialize(meta.shapes, shape);
6453 serialize(meta.shapes, shapes);
6458 if (this.isSkinnedMesh) {
6459 object.bindMode = this.bindMode;
6460 object.bindMatrix = this.bindMatrix.toArray();
6462 if (this.skeleton !== undefined) {
6463 serialize(meta.skeletons, this.skeleton);
6464 object.skeleton = this.skeleton.uuid;
6468 if (this.material !== undefined) {
6469 if (Array.isArray(this.material)) {
6472 for (var _i = 0, _l = this.material.length; _i < _l; _i++) {
6473 uuids.push(serialize(meta.materials, this.material[_i]));
6476 object.material = uuids;
6478 object.material = serialize(meta.materials, this.material);
6483 if (this.children.length > 0) {
6484 object.children = [];
6486 for (var _i2 = 0; _i2 < this.children.length; _i2++) {
6487 object.children.push(this.children[_i2].toJSON(meta).object);
6492 if (this.animations.length > 0) {
6493 object.animations = [];
6495 for (var _i3 = 0; _i3 < this.animations.length; _i3++) {
6496 var animation = this.animations[_i3];
6497 object.animations.push(serialize(meta.animations, animation));
6502 var geometries = extractFromCache(meta.geometries);
6503 var materials = extractFromCache(meta.materials);
6504 var textures = extractFromCache(meta.textures);
6505 var images = extractFromCache(meta.images);
6507 var _shapes = extractFromCache(meta.shapes);
6509 var skeletons = extractFromCache(meta.skeletons);
6510 var animations = extractFromCache(meta.animations);
6511 if (geometries.length > 0) output.geometries = geometries;
6512 if (materials.length > 0) output.materials = materials;
6513 if (textures.length > 0) output.textures = textures;
6514 if (images.length > 0) output.images = images;
6515 if (_shapes.length > 0) output.shapes = _shapes;
6516 if (skeletons.length > 0) output.skeletons = skeletons;
6517 if (animations.length > 0) output.animations = animations;
6520 output.object = object;
6521 return output; // extract data from the cache hash
6522 // remove metadata on each item
6523 // and return as array
6525 function extractFromCache(cache) {
6528 for (var key in cache) {
6529 var data = cache[key];
6530 delete data.metadata;
6537 clone: function clone(recursive) {
6538 return new this.constructor().copy(this, recursive);
6540 copy: function copy(source, recursive) {
6541 if (recursive === void 0) {
6545 this.name = source.name;
6546 this.up.copy(source.up);
6547 this.position.copy(source.position);
6548 this.rotation.order = source.rotation.order;
6549 this.quaternion.copy(source.quaternion);
6550 this.scale.copy(source.scale);
6551 this.matrix.copy(source.matrix);
6552 this.matrixWorld.copy(source.matrixWorld);
6553 this.matrixAutoUpdate = source.matrixAutoUpdate;
6554 this.matrixWorldNeedsUpdate = source.matrixWorldNeedsUpdate;
6555 this.layers.mask = source.layers.mask;
6556 this.visible = source.visible;
6557 this.castShadow = source.castShadow;
6558 this.receiveShadow = source.receiveShadow;
6559 this.frustumCulled = source.frustumCulled;
6560 this.renderOrder = source.renderOrder;
6561 this.userData = JSON.parse(JSON.stringify(source.userData));
6563 if (recursive === true) {
6564 for (var i = 0; i < source.children.length; i++) {
6565 var child = source.children[i];
6566 this.add(child.clone());
6574 var _vector1 = /*@__PURE__*/new Vector3();
6576 var _vector2 = /*@__PURE__*/new Vector3();
6578 var _normalMatrix = /*@__PURE__*/new Matrix3();
6580 var Plane = /*#__PURE__*/function () {
6581 function Plane(normal, constant) {
6582 Object.defineProperty(this, 'isPlane', {
6584 }); // normal is assumed to be normalized
6586 this.normal = normal !== undefined ? normal : new Vector3(1, 0, 0);
6587 this.constant = constant !== undefined ? constant : 0;
6590 var _proto = Plane.prototype;
6592 _proto.set = function set(normal, constant) {
6593 this.normal.copy(normal);
6594 this.constant = constant;
6598 _proto.setComponents = function setComponents(x, y, z, w) {
6599 this.normal.set(x, y, z);
6604 _proto.setFromNormalAndCoplanarPoint = function setFromNormalAndCoplanarPoint(normal, point) {
6605 this.normal.copy(normal);
6606 this.constant = -point.dot(this.normal);
6610 _proto.setFromCoplanarPoints = function setFromCoplanarPoints(a, b, c) {
6611 var normal = _vector1.subVectors(c, b).cross(_vector2.subVectors(a, b)).normalize(); // Q: should an error be thrown if normal is zero (e.g. degenerate plane)?
6614 this.setFromNormalAndCoplanarPoint(normal, a);
6618 _proto.clone = function clone() {
6619 return new this.constructor().copy(this);
6622 _proto.copy = function copy(plane) {
6623 this.normal.copy(plane.normal);
6624 this.constant = plane.constant;
6628 _proto.normalize = function normalize() {
6629 // Note: will lead to a divide by zero if the plane is invalid.
6630 var inverseNormalLength = 1.0 / this.normal.length();
6631 this.normal.multiplyScalar(inverseNormalLength);
6632 this.constant *= inverseNormalLength;
6636 _proto.negate = function negate() {
6637 this.constant *= -1;
6638 this.normal.negate();
6642 _proto.distanceToPoint = function distanceToPoint(point) {
6643 return this.normal.dot(point) + this.constant;
6646 _proto.distanceToSphere = function distanceToSphere(sphere) {
6647 return this.distanceToPoint(sphere.center) - sphere.radius;
6650 _proto.projectPoint = function projectPoint(point, target) {
6651 if (target === undefined) {
6652 console.warn('THREE.Plane: .projectPoint() target is now required');
6653 target = new Vector3();
6656 return target.copy(this.normal).multiplyScalar(-this.distanceToPoint(point)).add(point);
6659 _proto.intersectLine = function intersectLine(line, target) {
6660 if (target === undefined) {
6661 console.warn('THREE.Plane: .intersectLine() target is now required');
6662 target = new Vector3();
6665 var direction = line.delta(_vector1);
6666 var denominator = this.normal.dot(direction);
6668 if (denominator === 0) {
6669 // line is coplanar, return origin
6670 if (this.distanceToPoint(line.start) === 0) {
6671 return target.copy(line.start);
6672 } // Unsure if this is the correct method to handle this case.
6678 var t = -(line.start.dot(this.normal) + this.constant) / denominator;
6680 if (t < 0 || t > 1) {
6684 return target.copy(direction).multiplyScalar(t).add(line.start);
6687 _proto.intersectsLine = function intersectsLine(line) {
6688 // Note: this tests if a line intersects the plane, not whether it (or its end-points) are coplanar with it.
6689 var startSign = this.distanceToPoint(line.start);
6690 var endSign = this.distanceToPoint(line.end);
6691 return startSign < 0 && endSign > 0 || endSign < 0 && startSign > 0;
6694 _proto.intersectsBox = function intersectsBox(box) {
6695 return box.intersectsPlane(this);
6698 _proto.intersectsSphere = function intersectsSphere(sphere) {
6699 return sphere.intersectsPlane(this);
6702 _proto.coplanarPoint = function coplanarPoint(target) {
6703 if (target === undefined) {
6704 console.warn('THREE.Plane: .coplanarPoint() target is now required');
6705 target = new Vector3();
6708 return target.copy(this.normal).multiplyScalar(-this.constant);
6711 _proto.applyMatrix4 = function applyMatrix4(matrix, optionalNormalMatrix) {
6712 var normalMatrix = optionalNormalMatrix || _normalMatrix.getNormalMatrix(matrix);
6714 var referencePoint = this.coplanarPoint(_vector1).applyMatrix4(matrix);
6715 var normal = this.normal.applyMatrix3(normalMatrix).normalize();
6716 this.constant = -referencePoint.dot(normal);
6720 _proto.translate = function translate(offset) {
6721 this.constant -= offset.dot(this.normal);
6725 _proto.equals = function equals(plane) {
6726 return plane.normal.equals(this.normal) && plane.constant === this.constant;
6732 var _v0$1 = /*@__PURE__*/new Vector3();
6734 var _v1$3 = /*@__PURE__*/new Vector3();
6736 var _v2$1 = /*@__PURE__*/new Vector3();
6738 var _v3 = /*@__PURE__*/new Vector3();
6740 var _vab = /*@__PURE__*/new Vector3();
6742 var _vac = /*@__PURE__*/new Vector3();
6744 var _vbc = /*@__PURE__*/new Vector3();
6746 var _vap = /*@__PURE__*/new Vector3();
6748 var _vbp = /*@__PURE__*/new Vector3();
6750 var _vcp = /*@__PURE__*/new Vector3();
6752 var Triangle = /*#__PURE__*/function () {
6753 function Triangle(a, b, c) {
6754 this.a = a !== undefined ? a : new Vector3();
6755 this.b = b !== undefined ? b : new Vector3();
6756 this.c = c !== undefined ? c : new Vector3();
6759 Triangle.getNormal = function getNormal(a, b, c, target) {
6760 if (target === undefined) {
6761 console.warn('THREE.Triangle: .getNormal() target is now required');
6762 target = new Vector3();
6765 target.subVectors(c, b);
6767 _v0$1.subVectors(a, b);
6769 target.cross(_v0$1);
6770 var targetLengthSq = target.lengthSq();
6772 if (targetLengthSq > 0) {
6773 return target.multiplyScalar(1 / Math.sqrt(targetLengthSq));
6776 return target.set(0, 0, 0);
6777 } // static/instance method to calculate barycentric coordinates
6778 // based on: http://www.blackpawn.com/texts/pointinpoly/default.html
6781 Triangle.getBarycoord = function getBarycoord(point, a, b, c, target) {
6782 _v0$1.subVectors(c, a);
6784 _v1$3.subVectors(b, a);
6786 _v2$1.subVectors(point, a);
6788 var dot00 = _v0$1.dot(_v0$1);
6790 var dot01 = _v0$1.dot(_v1$3);
6792 var dot02 = _v0$1.dot(_v2$1);
6794 var dot11 = _v1$3.dot(_v1$3);
6796 var dot12 = _v1$3.dot(_v2$1);
6798 var denom = dot00 * dot11 - dot01 * dot01;
6800 if (target === undefined) {
6801 console.warn('THREE.Triangle: .getBarycoord() target is now required');
6802 target = new Vector3();
6803 } // collinear or singular triangle
6807 // arbitrary location outside of triangle?
6808 // not sure if this is the best idea, maybe should be returning undefined
6809 return target.set(-2, -1, -1);
6812 var invDenom = 1 / denom;
6813 var u = (dot11 * dot02 - dot01 * dot12) * invDenom;
6814 var v = (dot00 * dot12 - dot01 * dot02) * invDenom; // barycentric coordinates must always sum to 1
6816 return target.set(1 - u - v, v, u);
6819 Triangle.containsPoint = function containsPoint(point, a, b, c) {
6820 this.getBarycoord(point, a, b, c, _v3);
6821 return _v3.x >= 0 && _v3.y >= 0 && _v3.x + _v3.y <= 1;
6824 Triangle.getUV = function getUV(point, p1, p2, p3, uv1, uv2, uv3, target) {
6825 this.getBarycoord(point, p1, p2, p3, _v3);
6827 target.addScaledVector(uv1, _v3.x);
6828 target.addScaledVector(uv2, _v3.y);
6829 target.addScaledVector(uv3, _v3.z);
6833 Triangle.isFrontFacing = function isFrontFacing(a, b, c, direction) {
6834 _v0$1.subVectors(c, b);
6836 _v1$3.subVectors(a, b); // strictly front facing
6839 return _v0$1.cross(_v1$3).dot(direction) < 0 ? true : false;
6842 var _proto = Triangle.prototype;
6844 _proto.set = function set(a, b, c) {
6851 _proto.setFromPointsAndIndices = function setFromPointsAndIndices(points, i0, i1, i2) {
6852 this.a.copy(points[i0]);
6853 this.b.copy(points[i1]);
6854 this.c.copy(points[i2]);
6858 _proto.clone = function clone() {
6859 return new this.constructor().copy(this);
6862 _proto.copy = function copy(triangle) {
6863 this.a.copy(triangle.a);
6864 this.b.copy(triangle.b);
6865 this.c.copy(triangle.c);
6869 _proto.getArea = function getArea() {
6870 _v0$1.subVectors(this.c, this.b);
6872 _v1$3.subVectors(this.a, this.b);
6874 return _v0$1.cross(_v1$3).length() * 0.5;
6877 _proto.getMidpoint = function getMidpoint(target) {
6878 if (target === undefined) {
6879 console.warn('THREE.Triangle: .getMidpoint() target is now required');
6880 target = new Vector3();
6883 return target.addVectors(this.a, this.b).add(this.c).multiplyScalar(1 / 3);
6886 _proto.getNormal = function getNormal(target) {
6887 return Triangle.getNormal(this.a, this.b, this.c, target);
6890 _proto.getPlane = function getPlane(target) {
6891 if (target === undefined) {
6892 console.warn('THREE.Triangle: .getPlane() target is now required');
6893 target = new Plane();
6896 return target.setFromCoplanarPoints(this.a, this.b, this.c);
6899 _proto.getBarycoord = function getBarycoord(point, target) {
6900 return Triangle.getBarycoord(point, this.a, this.b, this.c, target);
6903 _proto.getUV = function getUV(point, uv1, uv2, uv3, target) {
6904 return Triangle.getUV(point, this.a, this.b, this.c, uv1, uv2, uv3, target);
6907 _proto.containsPoint = function containsPoint(point) {
6908 return Triangle.containsPoint(point, this.a, this.b, this.c);
6911 _proto.isFrontFacing = function isFrontFacing(direction) {
6912 return Triangle.isFrontFacing(this.a, this.b, this.c, direction);
6915 _proto.intersectsBox = function intersectsBox(box) {
6916 return box.intersectsTriangle(this);
6919 _proto.closestPointToPoint = function closestPointToPoint(p, target) {
6920 if (target === undefined) {
6921 console.warn('THREE.Triangle: .closestPointToPoint() target is now required');
6922 target = new Vector3();
6928 var v, w; // algorithm thanks to Real-Time Collision Detection by Christer Ericson,
6929 // published by Morgan Kaufmann Publishers, (c) 2005 Elsevier Inc.,
6930 // under the accompanying license; see chapter 5.1.5 for detailed explanation.
6931 // basically, we're distinguishing which of the voronoi regions of the triangle
6932 // the point lies in with the minimum amount of redundant computation.
6934 _vab.subVectors(b, a);
6936 _vac.subVectors(c, a);
6938 _vap.subVectors(p, a);
6940 var d1 = _vab.dot(_vap);
6942 var d2 = _vac.dot(_vap);
6944 if (d1 <= 0 && d2 <= 0) {
6945 // vertex region of A; barycentric coords (1, 0, 0)
6946 return target.copy(a);
6949 _vbp.subVectors(p, b);
6951 var d3 = _vab.dot(_vbp);
6953 var d4 = _vac.dot(_vbp);
6955 if (d3 >= 0 && d4 <= d3) {
6956 // vertex region of B; barycentric coords (0, 1, 0)
6957 return target.copy(b);
6960 var vc = d1 * d4 - d3 * d2;
6962 if (vc <= 0 && d1 >= 0 && d3 <= 0) {
6963 v = d1 / (d1 - d3); // edge region of AB; barycentric coords (1-v, v, 0)
6965 return target.copy(a).addScaledVector(_vab, v);
6968 _vcp.subVectors(p, c);
6970 var d5 = _vab.dot(_vcp);
6972 var d6 = _vac.dot(_vcp);
6974 if (d6 >= 0 && d5 <= d6) {
6975 // vertex region of C; barycentric coords (0, 0, 1)
6976 return target.copy(c);
6979 var vb = d5 * d2 - d1 * d6;
6981 if (vb <= 0 && d2 >= 0 && d6 <= 0) {
6982 w = d2 / (d2 - d6); // edge region of AC; barycentric coords (1-w, 0, w)
6984 return target.copy(a).addScaledVector(_vac, w);
6987 var va = d3 * d6 - d5 * d4;
6989 if (va <= 0 && d4 - d3 >= 0 && d5 - d6 >= 0) {
6990 _vbc.subVectors(c, b);
6992 w = (d4 - d3) / (d4 - d3 + (d5 - d6)); // edge region of BC; barycentric coords (0, 1-w, w)
6994 return target.copy(b).addScaledVector(_vbc, w); // edge region of BC
6998 var denom = 1 / (va + vb + vc); // u = va * denom
7002 return target.copy(a).addScaledVector(_vab, v).addScaledVector(_vac, w);
7005 _proto.equals = function equals(triangle) {
7006 return triangle.a.equals(this.a) && triangle.b.equals(this.b) && triangle.c.equals(this.c);
7012 var _colorKeywords = {
7013 'aliceblue': 0xF0F8FF,
7014 'antiquewhite': 0xFAEBD7,
7016 'aquamarine': 0x7FFFD4,
7021 'blanchedalmond': 0xFFEBCD,
7023 'blueviolet': 0x8A2BE2,
7025 'burlywood': 0xDEB887,
7026 'cadetblue': 0x5F9EA0,
7027 'chartreuse': 0x7FFF00,
7028 'chocolate': 0xD2691E,
7030 'cornflowerblue': 0x6495ED,
7031 'cornsilk': 0xFFF8DC,
7032 'crimson': 0xDC143C,
7034 'darkblue': 0x00008B,
7035 'darkcyan': 0x008B8B,
7036 'darkgoldenrod': 0xB8860B,
7037 'darkgray': 0xA9A9A9,
7038 'darkgreen': 0x006400,
7039 'darkgrey': 0xA9A9A9,
7040 'darkkhaki': 0xBDB76B,
7041 'darkmagenta': 0x8B008B,
7042 'darkolivegreen': 0x556B2F,
7043 'darkorange': 0xFF8C00,
7044 'darkorchid': 0x9932CC,
7045 'darkred': 0x8B0000,
7046 'darksalmon': 0xE9967A,
7047 'darkseagreen': 0x8FBC8F,
7048 'darkslateblue': 0x483D8B,
7049 'darkslategray': 0x2F4F4F,
7050 'darkslategrey': 0x2F4F4F,
7051 'darkturquoise': 0x00CED1,
7052 'darkviolet': 0x9400D3,
7053 'deeppink': 0xFF1493,
7054 'deepskyblue': 0x00BFFF,
7055 'dimgray': 0x696969,
7056 'dimgrey': 0x696969,
7057 'dodgerblue': 0x1E90FF,
7058 'firebrick': 0xB22222,
7059 'floralwhite': 0xFFFAF0,
7060 'forestgreen': 0x228B22,
7061 'fuchsia': 0xFF00FF,
7062 'gainsboro': 0xDCDCDC,
7063 'ghostwhite': 0xF8F8FF,
7065 'goldenrod': 0xDAA520,
7068 'greenyellow': 0xADFF2F,
7070 'honeydew': 0xF0FFF0,
7071 'hotpink': 0xFF69B4,
7072 'indianred': 0xCD5C5C,
7076 'lavender': 0xE6E6FA,
7077 'lavenderblush': 0xFFF0F5,
7078 'lawngreen': 0x7CFC00,
7079 'lemonchiffon': 0xFFFACD,
7080 'lightblue': 0xADD8E6,
7081 'lightcoral': 0xF08080,
7082 'lightcyan': 0xE0FFFF,
7083 'lightgoldenrodyellow': 0xFAFAD2,
7084 'lightgray': 0xD3D3D3,
7085 'lightgreen': 0x90EE90,
7086 'lightgrey': 0xD3D3D3,
7087 'lightpink': 0xFFB6C1,
7088 'lightsalmon': 0xFFA07A,
7089 'lightseagreen': 0x20B2AA,
7090 'lightskyblue': 0x87CEFA,
7091 'lightslategray': 0x778899,
7092 'lightslategrey': 0x778899,
7093 'lightsteelblue': 0xB0C4DE,
7094 'lightyellow': 0xFFFFE0,
7096 'limegreen': 0x32CD32,
7098 'magenta': 0xFF00FF,
7100 'mediumaquamarine': 0x66CDAA,
7101 'mediumblue': 0x0000CD,
7102 'mediumorchid': 0xBA55D3,
7103 'mediumpurple': 0x9370DB,
7104 'mediumseagreen': 0x3CB371,
7105 'mediumslateblue': 0x7B68EE,
7106 'mediumspringgreen': 0x00FA9A,
7107 'mediumturquoise': 0x48D1CC,
7108 'mediumvioletred': 0xC71585,
7109 'midnightblue': 0x191970,
7110 'mintcream': 0xF5FFFA,
7111 'mistyrose': 0xFFE4E1,
7112 'moccasin': 0xFFE4B5,
7113 'navajowhite': 0xFFDEAD,
7115 'oldlace': 0xFDF5E6,
7117 'olivedrab': 0x6B8E23,
7119 'orangered': 0xFF4500,
7121 'palegoldenrod': 0xEEE8AA,
7122 'palegreen': 0x98FB98,
7123 'paleturquoise': 0xAFEEEE,
7124 'palevioletred': 0xDB7093,
7125 'papayawhip': 0xFFEFD5,
7126 'peachpuff': 0xFFDAB9,
7130 'powderblue': 0xB0E0E6,
7132 'rebeccapurple': 0x663399,
7134 'rosybrown': 0xBC8F8F,
7135 'royalblue': 0x4169E1,
7136 'saddlebrown': 0x8B4513,
7138 'sandybrown': 0xF4A460,
7139 'seagreen': 0x2E8B57,
7140 'seashell': 0xFFF5EE,
7143 'skyblue': 0x87CEEB,
7144 'slateblue': 0x6A5ACD,
7145 'slategray': 0x708090,
7146 'slategrey': 0x708090,
7148 'springgreen': 0x00FF7F,
7149 'steelblue': 0x4682B4,
7152 'thistle': 0xD8BFD8,
7154 'turquoise': 0x40E0D0,
7158 'whitesmoke': 0xF5F5F5,
7160 'yellowgreen': 0x9ACD32
7173 function hue2rgb(p, q, t) {
7176 if (t < 1 / 6) return p + (q - p) * 6 * t;
7177 if (t < 1 / 2) return q;
7178 if (t < 2 / 3) return p + (q - p) * 6 * (2 / 3 - t);
7182 function SRGBToLinear(c) {
7183 return c < 0.04045 ? c * 0.0773993808 : Math.pow(c * 0.9478672986 + 0.0521327014, 2.4);
7186 function LinearToSRGB(c) {
7187 return c < 0.0031308 ? c * 12.92 : 1.055 * Math.pow(c, 0.41666) - 0.055;
7190 var Color = /*#__PURE__*/function () {
7191 function Color(r, g, b) {
7192 Object.defineProperty(this, 'isColor', {
7196 if (g === undefined && b === undefined) {
7197 // r is THREE.Color, hex or string
7201 return this.setRGB(r, g, b);
7204 var _proto = Color.prototype;
7206 _proto.set = function set(value) {
7207 if (value && value.isColor) {
7209 } else if (typeof value === 'number') {
7211 } else if (typeof value === 'string') {
7212 this.setStyle(value);
7218 _proto.setScalar = function setScalar(scalar) {
7225 _proto.setHex = function setHex(hex) {
7226 hex = Math.floor(hex);
7227 this.r = (hex >> 16 & 255) / 255;
7228 this.g = (hex >> 8 & 255) / 255;
7229 this.b = (hex & 255) / 255;
7233 _proto.setRGB = function setRGB(r, g, b) {
7240 _proto.setHSL = function setHSL(h, s, l) {
7241 // h,s,l ranges are in 0.0 - 1.0
7242 h = MathUtils.euclideanModulo(h, 1);
7243 s = MathUtils.clamp(s, 0, 1);
7244 l = MathUtils.clamp(l, 0, 1);
7247 this.r = this.g = this.b = l;
7249 var p = l <= 0.5 ? l * (1 + s) : l + s - l * s;
7251 this.r = hue2rgb(q, p, h + 1 / 3);
7252 this.g = hue2rgb(q, p, h);
7253 this.b = hue2rgb(q, p, h - 1 / 3);
7259 _proto.setStyle = function setStyle(style) {
7260 function handleAlpha(string) {
7261 if (string === undefined) return;
7263 if (parseFloat(string) < 1) {
7264 console.warn('THREE.Color: Alpha component of ' + style + ' will be ignored.');
7270 if (m = /^((?:rgb|hsl)a?)\(([^\)]*)\)/.exec(style)) {
7274 var components = m[2];
7279 if (color = /^\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(components)) {
7280 // rgb(255,0,0) rgba(255,0,0,0.5)
7281 this.r = Math.min(255, parseInt(color[1], 10)) / 255;
7282 this.g = Math.min(255, parseInt(color[2], 10)) / 255;
7283 this.b = Math.min(255, parseInt(color[3], 10)) / 255;
7284 handleAlpha(color[4]);
7288 if (color = /^\s*(\d+)\%\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(components)) {
7289 // rgb(100%,0%,0%) rgba(100%,0%,0%,0.5)
7290 this.r = Math.min(100, parseInt(color[1], 10)) / 100;
7291 this.g = Math.min(100, parseInt(color[2], 10)) / 100;
7292 this.b = Math.min(100, parseInt(color[3], 10)) / 100;
7293 handleAlpha(color[4]);
7301 if (color = /^\s*(\d*\.?\d+)\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(components)) {
7302 // hsl(120,50%,50%) hsla(120,50%,50%,0.5)
7303 var h = parseFloat(color[1]) / 360;
7304 var s = parseInt(color[2], 10) / 100;
7305 var l = parseInt(color[3], 10) / 100;
7306 handleAlpha(color[4]);
7307 return this.setHSL(h, s, l);
7312 } else if (m = /^\#([A-Fa-f\d]+)$/.exec(style)) {
7315 var size = hex.length;
7319 this.r = parseInt(hex.charAt(0) + hex.charAt(0), 16) / 255;
7320 this.g = parseInt(hex.charAt(1) + hex.charAt(1), 16) / 255;
7321 this.b = parseInt(hex.charAt(2) + hex.charAt(2), 16) / 255;
7323 } else if (size === 6) {
7325 this.r = parseInt(hex.charAt(0) + hex.charAt(1), 16) / 255;
7326 this.g = parseInt(hex.charAt(2) + hex.charAt(3), 16) / 255;
7327 this.b = parseInt(hex.charAt(4) + hex.charAt(5), 16) / 255;
7332 if (style && style.length > 0) {
7333 return this.setColorName(style);
7339 _proto.setColorName = function setColorName(style) {
7341 var hex = _colorKeywords[style];
7343 if (hex !== undefined) {
7348 console.warn('THREE.Color: Unknown color ' + style);
7354 _proto.clone = function clone() {
7355 return new this.constructor(this.r, this.g, this.b);
7358 _proto.copy = function copy(color) {
7365 _proto.copyGammaToLinear = function copyGammaToLinear(color, gammaFactor) {
7366 if (gammaFactor === void 0) {
7370 this.r = Math.pow(color.r, gammaFactor);
7371 this.g = Math.pow(color.g, gammaFactor);
7372 this.b = Math.pow(color.b, gammaFactor);
7376 _proto.copyLinearToGamma = function copyLinearToGamma(color, gammaFactor) {
7377 if (gammaFactor === void 0) {
7381 var safeInverse = gammaFactor > 0 ? 1.0 / gammaFactor : 1.0;
7382 this.r = Math.pow(color.r, safeInverse);
7383 this.g = Math.pow(color.g, safeInverse);
7384 this.b = Math.pow(color.b, safeInverse);
7388 _proto.convertGammaToLinear = function convertGammaToLinear(gammaFactor) {
7389 this.copyGammaToLinear(this, gammaFactor);
7393 _proto.convertLinearToGamma = function convertLinearToGamma(gammaFactor) {
7394 this.copyLinearToGamma(this, gammaFactor);
7398 _proto.copySRGBToLinear = function copySRGBToLinear(color) {
7399 this.r = SRGBToLinear(color.r);
7400 this.g = SRGBToLinear(color.g);
7401 this.b = SRGBToLinear(color.b);
7405 _proto.copyLinearToSRGB = function copyLinearToSRGB(color) {
7406 this.r = LinearToSRGB(color.r);
7407 this.g = LinearToSRGB(color.g);
7408 this.b = LinearToSRGB(color.b);
7412 _proto.convertSRGBToLinear = function convertSRGBToLinear() {
7413 this.copySRGBToLinear(this);
7417 _proto.convertLinearToSRGB = function convertLinearToSRGB() {
7418 this.copyLinearToSRGB(this);
7422 _proto.getHex = function getHex() {
7423 return this.r * 255 << 16 ^ this.g * 255 << 8 ^ this.b * 255 << 0;
7426 _proto.getHexString = function getHexString() {
7427 return ('000000' + this.getHex().toString(16)).slice(-6);
7430 _proto.getHSL = function getHSL(target) {
7431 // h,s,l ranges are in 0.0 - 1.0
7432 if (target === undefined) {
7433 console.warn('THREE.Color: .getHSL() target is now required');
7444 var max = Math.max(r, g, b);
7445 var min = Math.min(r, g, b);
7446 var hue, saturation;
7447 var lightness = (min + max) / 2.0;
7453 var delta = max - min;
7454 saturation = lightness <= 0.5 ? delta / (max + min) : delta / (2 - max - min);
7458 hue = (g - b) / delta + (g < b ? 6 : 0);
7462 hue = (b - r) / delta + 2;
7466 hue = (r - g) / delta + 4;
7474 target.s = saturation;
7475 target.l = lightness;
7479 _proto.getStyle = function getStyle() {
7480 return 'rgb(' + (this.r * 255 | 0) + ',' + (this.g * 255 | 0) + ',' + (this.b * 255 | 0) + ')';
7483 _proto.offsetHSL = function offsetHSL(h, s, l) {
7488 this.setHSL(_hslA.h, _hslA.s, _hslA.l);
7492 _proto.add = function add(color) {
7499 _proto.addColors = function addColors(color1, color2) {
7500 this.r = color1.r + color2.r;
7501 this.g = color1.g + color2.g;
7502 this.b = color1.b + color2.b;
7506 _proto.addScalar = function addScalar(s) {
7513 _proto.sub = function sub(color) {
7514 this.r = Math.max(0, this.r - color.r);
7515 this.g = Math.max(0, this.g - color.g);
7516 this.b = Math.max(0, this.b - color.b);
7520 _proto.multiply = function multiply(color) {
7527 _proto.multiplyScalar = function multiplyScalar(s) {
7534 _proto.lerp = function lerp(color, alpha) {
7535 this.r += (color.r - this.r) * alpha;
7536 this.g += (color.g - this.g) * alpha;
7537 this.b += (color.b - this.b) * alpha;
7541 _proto.lerpColors = function lerpColors(color1, color2, alpha) {
7542 this.r = color1.r + (color2.r - color1.r) * alpha;
7543 this.g = color1.g + (color2.g - color1.g) * alpha;
7544 this.b = color1.b + (color2.b - color1.b) * alpha;
7548 _proto.lerpHSL = function lerpHSL(color, alpha) {
7550 color.getHSL(_hslB);
7551 var h = MathUtils.lerp(_hslA.h, _hslB.h, alpha);
7552 var s = MathUtils.lerp(_hslA.s, _hslB.s, alpha);
7553 var l = MathUtils.lerp(_hslA.l, _hslB.l, alpha);
7554 this.setHSL(h, s, l);
7558 _proto.equals = function equals(c) {
7559 return c.r === this.r && c.g === this.g && c.b === this.b;
7562 _proto.fromArray = function fromArray(array, offset) {
7563 if (offset === void 0) {
7567 this.r = array[offset];
7568 this.g = array[offset + 1];
7569 this.b = array[offset + 2];
7573 _proto.toArray = function toArray(array, offset) {
7574 if (array === void 0) {
7578 if (offset === void 0) {
7582 array[offset] = this.r;
7583 array[offset + 1] = this.g;
7584 array[offset + 2] = this.b;
7588 _proto.fromBufferAttribute = function fromBufferAttribute(attribute, index) {
7589 this.r = attribute.getX(index);
7590 this.g = attribute.getY(index);
7591 this.b = attribute.getZ(index);
7593 if (attribute.normalized === true) {
7594 // assuming Uint8Array
7603 _proto.toJSON = function toJSON() {
7604 return this.getHex();
7610 Color.NAMES = _colorKeywords;
7611 Color.prototype.r = 1;
7612 Color.prototype.g = 1;
7613 Color.prototype.b = 1;
7615 var Face3 = /*#__PURE__*/function () {
7616 function Face3(a, b, c, normal, color, materialIndex) {
7617 if (materialIndex === void 0) {
7624 this.normal = normal && normal.isVector3 ? normal : new Vector3();
7625 this.vertexNormals = Array.isArray(normal) ? normal : [];
7626 this.color = color && color.isColor ? color : new Color();
7627 this.vertexColors = Array.isArray(color) ? color : [];
7628 this.materialIndex = materialIndex;
7631 var _proto = Face3.prototype;
7633 _proto.clone = function clone() {
7634 return new this.constructor().copy(this);
7637 _proto.copy = function copy(source) {
7641 this.normal.copy(source.normal);
7642 this.color.copy(source.color);
7643 this.materialIndex = source.materialIndex;
7645 for (var i = 0, il = source.vertexNormals.length; i < il; i++) {
7646 this.vertexNormals[i] = source.vertexNormals[i].clone();
7649 for (var _i = 0, _il = source.vertexColors.length; _i < _il; _i++) {
7650 this.vertexColors[_i] = source.vertexColors[_i].clone();
7661 function Material() {
7662 Object.defineProperty(this, 'id', {
7665 this.uuid = MathUtils.generateUUID();
7667 this.type = 'Material';
7669 this.blending = NormalBlending;
7670 this.side = FrontSide;
7671 this.flatShading = false;
7672 this.vertexColors = false;
7674 this.transparent = false;
7675 this.blendSrc = SrcAlphaFactor;
7676 this.blendDst = OneMinusSrcAlphaFactor;
7677 this.blendEquation = AddEquation;
7678 this.blendSrcAlpha = null;
7679 this.blendDstAlpha = null;
7680 this.blendEquationAlpha = null;
7681 this.depthFunc = LessEqualDepth;
7682 this.depthTest = true;
7683 this.depthWrite = true;
7684 this.stencilWriteMask = 0xff;
7685 this.stencilFunc = AlwaysStencilFunc;
7686 this.stencilRef = 0;
7687 this.stencilFuncMask = 0xff;
7688 this.stencilFail = KeepStencilOp;
7689 this.stencilZFail = KeepStencilOp;
7690 this.stencilZPass = KeepStencilOp;
7691 this.stencilWrite = false;
7692 this.clippingPlanes = null;
7693 this.clipIntersection = false;
7694 this.clipShadows = false;
7695 this.shadowSide = null;
7696 this.colorWrite = true;
7697 this.precision = null; // override the renderer's default precision for this material
7699 this.polygonOffset = false;
7700 this.polygonOffsetFactor = 0;
7701 this.polygonOffsetUnits = 0;
7702 this.dithering = false;
7704 this.premultipliedAlpha = false;
7705 this.visible = true;
7706 this.toneMapped = true;
7711 Material.prototype = Object.assign(Object.create(EventDispatcher.prototype), {
7712 constructor: Material,
7714 onBeforeCompile: function onBeforeCompile()
7715 /* shaderobject, renderer */
7717 customProgramCacheKey: function customProgramCacheKey() {
7718 return this.onBeforeCompile.toString();
7720 setValues: function setValues(values) {
7721 if (values === undefined) return;
7723 for (var key in values) {
7724 var newValue = values[key];
7726 if (newValue === undefined) {
7727 console.warn('THREE.Material: \'' + key + '\' parameter is undefined.');
7729 } // for backward compatability if shading is set in the constructor
7732 if (key === 'shading') {
7733 console.warn('THREE.' + this.type + ': .shading has been removed. Use the boolean .flatShading instead.');
7734 this.flatShading = newValue === FlatShading ? true : false;
7738 var currentValue = this[key];
7740 if (currentValue === undefined) {
7741 console.warn('THREE.' + this.type + ': \'' + key + '\' is not a property of this material.');
7745 if (currentValue && currentValue.isColor) {
7746 currentValue.set(newValue);
7747 } else if (currentValue && currentValue.isVector3 && newValue && newValue.isVector3) {
7748 currentValue.copy(newValue);
7750 this[key] = newValue;
7754 toJSON: function toJSON(meta) {
7755 var isRoot = meta === undefined || typeof meta === 'string';
7768 generator: 'Material.toJSON'
7770 }; // standard Material serialization
7772 data.uuid = this.uuid;
7773 data.type = this.type;
7774 if (this.name !== '') data.name = this.name;
7775 if (this.color && this.color.isColor) data.color = this.color.getHex();
7776 if (this.roughness !== undefined) data.roughness = this.roughness;
7777 if (this.metalness !== undefined) data.metalness = this.metalness;
7778 if (this.sheen && this.sheen.isColor) data.sheen = this.sheen.getHex();
7779 if (this.emissive && this.emissive.isColor) data.emissive = this.emissive.getHex();
7780 if (this.emissiveIntensity && this.emissiveIntensity !== 1) data.emissiveIntensity = this.emissiveIntensity;
7781 if (this.specular && this.specular.isColor) data.specular = this.specular.getHex();
7782 if (this.shininess !== undefined) data.shininess = this.shininess;
7783 if (this.clearcoat !== undefined) data.clearcoat = this.clearcoat;
7784 if (this.clearcoatRoughness !== undefined) data.clearcoatRoughness = this.clearcoatRoughness;
7786 if (this.clearcoatMap && this.clearcoatMap.isTexture) {
7787 data.clearcoatMap = this.clearcoatMap.toJSON(meta).uuid;
7790 if (this.clearcoatRoughnessMap && this.clearcoatRoughnessMap.isTexture) {
7791 data.clearcoatRoughnessMap = this.clearcoatRoughnessMap.toJSON(meta).uuid;
7794 if (this.clearcoatNormalMap && this.clearcoatNormalMap.isTexture) {
7795 data.clearcoatNormalMap = this.clearcoatNormalMap.toJSON(meta).uuid;
7796 data.clearcoatNormalScale = this.clearcoatNormalScale.toArray();
7799 if (this.map && this.map.isTexture) data.map = this.map.toJSON(meta).uuid;
7800 if (this.matcap && this.matcap.isTexture) data.matcap = this.matcap.toJSON(meta).uuid;
7801 if (this.alphaMap && this.alphaMap.isTexture) data.alphaMap = this.alphaMap.toJSON(meta).uuid;
7802 if (this.lightMap && this.lightMap.isTexture) data.lightMap = this.lightMap.toJSON(meta).uuid;
7804 if (this.aoMap && this.aoMap.isTexture) {
7805 data.aoMap = this.aoMap.toJSON(meta).uuid;
7806 data.aoMapIntensity = this.aoMapIntensity;
7809 if (this.bumpMap && this.bumpMap.isTexture) {
7810 data.bumpMap = this.bumpMap.toJSON(meta).uuid;
7811 data.bumpScale = this.bumpScale;
7814 if (this.normalMap && this.normalMap.isTexture) {
7815 data.normalMap = this.normalMap.toJSON(meta).uuid;
7816 data.normalMapType = this.normalMapType;
7817 data.normalScale = this.normalScale.toArray();
7820 if (this.displacementMap && this.displacementMap.isTexture) {
7821 data.displacementMap = this.displacementMap.toJSON(meta).uuid;
7822 data.displacementScale = this.displacementScale;
7823 data.displacementBias = this.displacementBias;
7826 if (this.roughnessMap && this.roughnessMap.isTexture) data.roughnessMap = this.roughnessMap.toJSON(meta).uuid;
7827 if (this.metalnessMap && this.metalnessMap.isTexture) data.metalnessMap = this.metalnessMap.toJSON(meta).uuid;
7828 if (this.emissiveMap && this.emissiveMap.isTexture) data.emissiveMap = this.emissiveMap.toJSON(meta).uuid;
7829 if (this.specularMap && this.specularMap.isTexture) data.specularMap = this.specularMap.toJSON(meta).uuid;
7831 if (this.envMap && this.envMap.isTexture) {
7832 data.envMap = this.envMap.toJSON(meta).uuid;
7833 data.reflectivity = this.reflectivity; // Scale behind envMap
7835 data.refractionRatio = this.refractionRatio;
7836 if (this.combine !== undefined) data.combine = this.combine;
7837 if (this.envMapIntensity !== undefined) data.envMapIntensity = this.envMapIntensity;
7840 if (this.gradientMap && this.gradientMap.isTexture) {
7841 data.gradientMap = this.gradientMap.toJSON(meta).uuid;
7844 if (this.size !== undefined) data.size = this.size;
7845 if (this.sizeAttenuation !== undefined) data.sizeAttenuation = this.sizeAttenuation;
7846 if (this.blending !== NormalBlending) data.blending = this.blending;
7847 if (this.flatShading === true) data.flatShading = this.flatShading;
7848 if (this.side !== FrontSide) data.side = this.side;
7849 if (this.vertexColors) data.vertexColors = true;
7850 if (this.opacity < 1) data.opacity = this.opacity;
7851 if (this.transparent === true) data.transparent = this.transparent;
7852 data.depthFunc = this.depthFunc;
7853 data.depthTest = this.depthTest;
7854 data.depthWrite = this.depthWrite;
7855 data.stencilWrite = this.stencilWrite;
7856 data.stencilWriteMask = this.stencilWriteMask;
7857 data.stencilFunc = this.stencilFunc;
7858 data.stencilRef = this.stencilRef;
7859 data.stencilFuncMask = this.stencilFuncMask;
7860 data.stencilFail = this.stencilFail;
7861 data.stencilZFail = this.stencilZFail;
7862 data.stencilZPass = this.stencilZPass; // rotation (SpriteMaterial)
7864 if (this.rotation && this.rotation !== 0) data.rotation = this.rotation;
7865 if (this.polygonOffset === true) data.polygonOffset = true;
7866 if (this.polygonOffsetFactor !== 0) data.polygonOffsetFactor = this.polygonOffsetFactor;
7867 if (this.polygonOffsetUnits !== 0) data.polygonOffsetUnits = this.polygonOffsetUnits;
7868 if (this.linewidth && this.linewidth !== 1) data.linewidth = this.linewidth;
7869 if (this.dashSize !== undefined) data.dashSize = this.dashSize;
7870 if (this.gapSize !== undefined) data.gapSize = this.gapSize;
7871 if (this.scale !== undefined) data.scale = this.scale;
7872 if (this.dithering === true) data.dithering = true;
7873 if (this.alphaTest > 0) data.alphaTest = this.alphaTest;
7874 if (this.premultipliedAlpha === true) data.premultipliedAlpha = this.premultipliedAlpha;
7875 if (this.wireframe === true) data.wireframe = this.wireframe;
7876 if (this.wireframeLinewidth > 1) data.wireframeLinewidth = this.wireframeLinewidth;
7877 if (this.wireframeLinecap !== 'round') data.wireframeLinecap = this.wireframeLinecap;
7878 if (this.wireframeLinejoin !== 'round') data.wireframeLinejoin = this.wireframeLinejoin;
7879 if (this.morphTargets === true) data.morphTargets = true;
7880 if (this.morphNormals === true) data.morphNormals = true;
7881 if (this.skinning === true) data.skinning = true;
7882 if (this.visible === false) data.visible = false;
7883 if (this.toneMapped === false) data.toneMapped = false;
7884 if (JSON.stringify(this.userData) !== '{}') data.userData = this.userData; // TODO: Copied from Object3D.toJSON
7886 function extractFromCache(cache) {
7889 for (var key in cache) {
7890 var _data = cache[key];
7891 delete _data.metadata;
7899 var textures = extractFromCache(meta.textures);
7900 var images = extractFromCache(meta.images);
7901 if (textures.length > 0) data.textures = textures;
7902 if (images.length > 0) data.images = images;
7907 clone: function clone() {
7908 return new this.constructor().copy(this);
7910 copy: function copy(source) {
7911 this.name = source.name;
7912 this.fog = source.fog;
7913 this.blending = source.blending;
7914 this.side = source.side;
7915 this.flatShading = source.flatShading;
7916 this.vertexColors = source.vertexColors;
7917 this.opacity = source.opacity;
7918 this.transparent = source.transparent;
7919 this.blendSrc = source.blendSrc;
7920 this.blendDst = source.blendDst;
7921 this.blendEquation = source.blendEquation;
7922 this.blendSrcAlpha = source.blendSrcAlpha;
7923 this.blendDstAlpha = source.blendDstAlpha;
7924 this.blendEquationAlpha = source.blendEquationAlpha;
7925 this.depthFunc = source.depthFunc;
7926 this.depthTest = source.depthTest;
7927 this.depthWrite = source.depthWrite;
7928 this.stencilWriteMask = source.stencilWriteMask;
7929 this.stencilFunc = source.stencilFunc;
7930 this.stencilRef = source.stencilRef;
7931 this.stencilFuncMask = source.stencilFuncMask;
7932 this.stencilFail = source.stencilFail;
7933 this.stencilZFail = source.stencilZFail;
7934 this.stencilZPass = source.stencilZPass;
7935 this.stencilWrite = source.stencilWrite;
7936 var srcPlanes = source.clippingPlanes;
7937 var dstPlanes = null;
7939 if (srcPlanes !== null) {
7940 var n = srcPlanes.length;
7941 dstPlanes = new Array(n);
7943 for (var i = 0; i !== n; ++i) {
7944 dstPlanes[i] = srcPlanes[i].clone();
7948 this.clippingPlanes = dstPlanes;
7949 this.clipIntersection = source.clipIntersection;
7950 this.clipShadows = source.clipShadows;
7951 this.shadowSide = source.shadowSide;
7952 this.colorWrite = source.colorWrite;
7953 this.precision = source.precision;
7954 this.polygonOffset = source.polygonOffset;
7955 this.polygonOffsetFactor = source.polygonOffsetFactor;
7956 this.polygonOffsetUnits = source.polygonOffsetUnits;
7957 this.dithering = source.dithering;
7958 this.alphaTest = source.alphaTest;
7959 this.premultipliedAlpha = source.premultipliedAlpha;
7960 this.visible = source.visible;
7961 this.toneMapped = source.toneMapped;
7962 this.userData = JSON.parse(JSON.stringify(source.userData));
7965 dispose: function dispose() {
7966 this.dispatchEvent({
7971 Object.defineProperty(Material.prototype, 'needsUpdate', {
7972 set: function set(value) {
7973 if (value === true) this.version++;
7981 * map: new THREE.Texture( <Image> ),
7983 * lightMap: new THREE.Texture( <Image> ),
7984 * lightMapIntensity: <float>
7986 * aoMap: new THREE.Texture( <Image> ),
7987 * aoMapIntensity: <float>
7989 * specularMap: new THREE.Texture( <Image> ),
7991 * alphaMap: new THREE.Texture( <Image> ),
7993 * envMap: new THREE.CubeTexture( [posx, negx, posy, negy, posz, negz] ),
7994 * combine: THREE.Multiply,
7995 * reflectivity: <float>,
7996 * refractionRatio: <float>,
7998 * depthTest: <bool>,
7999 * depthWrite: <bool>,
8001 * wireframe: <boolean>,
8002 * wireframeLinewidth: <float>,
8005 * morphTargets: <bool>
8009 function MeshBasicMaterial(parameters) {
8010 Material.call(this);
8011 this.type = 'MeshBasicMaterial';
8012 this.color = new Color(0xffffff); // emissive
8015 this.lightMap = null;
8016 this.lightMapIntensity = 1.0;
8018 this.aoMapIntensity = 1.0;
8019 this.specularMap = null;
8020 this.alphaMap = null;
8022 this.combine = MultiplyOperation;
8023 this.reflectivity = 1;
8024 this.refractionRatio = 0.98;
8025 this.wireframe = false;
8026 this.wireframeLinewidth = 1;
8027 this.wireframeLinecap = 'round';
8028 this.wireframeLinejoin = 'round';
8029 this.skinning = false;
8030 this.morphTargets = false;
8031 this.setValues(parameters);
8034 MeshBasicMaterial.prototype = Object.create(Material.prototype);
8035 MeshBasicMaterial.prototype.constructor = MeshBasicMaterial;
8036 MeshBasicMaterial.prototype.isMeshBasicMaterial = true;
8038 MeshBasicMaterial.prototype.copy = function (source) {
8039 Material.prototype.copy.call(this, source);
8040 this.color.copy(source.color);
8041 this.map = source.map;
8042 this.lightMap = source.lightMap;
8043 this.lightMapIntensity = source.lightMapIntensity;
8044 this.aoMap = source.aoMap;
8045 this.aoMapIntensity = source.aoMapIntensity;
8046 this.specularMap = source.specularMap;
8047 this.alphaMap = source.alphaMap;
8048 this.envMap = source.envMap;
8049 this.combine = source.combine;
8050 this.reflectivity = source.reflectivity;
8051 this.refractionRatio = source.refractionRatio;
8052 this.wireframe = source.wireframe;
8053 this.wireframeLinewidth = source.wireframeLinewidth;
8054 this.wireframeLinecap = source.wireframeLinecap;
8055 this.wireframeLinejoin = source.wireframeLinejoin;
8056 this.skinning = source.skinning;
8057 this.morphTargets = source.morphTargets;
8061 var _vector$3 = new Vector3();
8063 var _vector2$1 = new Vector2();
8065 function BufferAttribute(array, itemSize, normalized) {
8066 if (Array.isArray(array)) {
8067 throw new TypeError('THREE.BufferAttribute: array should be a Typed Array.');
8072 this.itemSize = itemSize;
8073 this.count = array !== undefined ? array.length / itemSize : 0;
8074 this.normalized = normalized === true;
8075 this.usage = StaticDrawUsage;
8076 this.updateRange = {
8083 Object.defineProperty(BufferAttribute.prototype, 'needsUpdate', {
8084 set: function set(value) {
8085 if (value === true) this.version++;
8088 Object.assign(BufferAttribute.prototype, {
8089 isBufferAttribute: true,
8090 onUploadCallback: function onUploadCallback() {},
8091 setUsage: function setUsage(value) {
8095 copy: function copy(source) {
8096 this.name = source.name;
8097 this.array = new source.array.constructor(source.array);
8098 this.itemSize = source.itemSize;
8099 this.count = source.count;
8100 this.normalized = source.normalized;
8101 this.usage = source.usage;
8104 copyAt: function copyAt(index1, attribute, index2) {
8105 index1 *= this.itemSize;
8106 index2 *= attribute.itemSize;
8108 for (var i = 0, l = this.itemSize; i < l; i++) {
8109 this.array[index1 + i] = attribute.array[index2 + i];
8114 copyArray: function copyArray(array) {
8115 this.array.set(array);
8118 copyColorsArray: function copyColorsArray(colors) {
8119 var array = this.array;
8122 for (var i = 0, l = colors.length; i < l; i++) {
8123 var color = colors[i];
8125 if (color === undefined) {
8126 console.warn('THREE.BufferAttribute.copyColorsArray(): color is undefined', i);
8127 color = new Color();
8130 array[offset++] = color.r;
8131 array[offset++] = color.g;
8132 array[offset++] = color.b;
8137 copyVector2sArray: function copyVector2sArray(vectors) {
8138 var array = this.array;
8141 for (var i = 0, l = vectors.length; i < l; i++) {
8142 var vector = vectors[i];
8144 if (vector === undefined) {
8145 console.warn('THREE.BufferAttribute.copyVector2sArray(): vector is undefined', i);
8146 vector = new Vector2();
8149 array[offset++] = vector.x;
8150 array[offset++] = vector.y;
8155 copyVector3sArray: function copyVector3sArray(vectors) {
8156 var array = this.array;
8159 for (var i = 0, l = vectors.length; i < l; i++) {
8160 var vector = vectors[i];
8162 if (vector === undefined) {
8163 console.warn('THREE.BufferAttribute.copyVector3sArray(): vector is undefined', i);
8164 vector = new Vector3();
8167 array[offset++] = vector.x;
8168 array[offset++] = vector.y;
8169 array[offset++] = vector.z;
8174 copyVector4sArray: function copyVector4sArray(vectors) {
8175 var array = this.array;
8178 for (var i = 0, l = vectors.length; i < l; i++) {
8179 var vector = vectors[i];
8181 if (vector === undefined) {
8182 console.warn('THREE.BufferAttribute.copyVector4sArray(): vector is undefined', i);
8183 vector = new Vector4();
8186 array[offset++] = vector.x;
8187 array[offset++] = vector.y;
8188 array[offset++] = vector.z;
8189 array[offset++] = vector.w;
8194 applyMatrix3: function applyMatrix3(m) {
8195 if (this.itemSize === 2) {
8196 for (var i = 0, l = this.count; i < l; i++) {
8197 _vector2$1.fromBufferAttribute(this, i);
8199 _vector2$1.applyMatrix3(m);
8201 this.setXY(i, _vector2$1.x, _vector2$1.y);
8203 } else if (this.itemSize === 3) {
8204 for (var _i = 0, _l = this.count; _i < _l; _i++) {
8205 _vector$3.fromBufferAttribute(this, _i);
8207 _vector$3.applyMatrix3(m);
8209 this.setXYZ(_i, _vector$3.x, _vector$3.y, _vector$3.z);
8215 applyMatrix4: function applyMatrix4(m) {
8216 for (var i = 0, l = this.count; i < l; i++) {
8217 _vector$3.x = this.getX(i);
8218 _vector$3.y = this.getY(i);
8219 _vector$3.z = this.getZ(i);
8221 _vector$3.applyMatrix4(m);
8223 this.setXYZ(i, _vector$3.x, _vector$3.y, _vector$3.z);
8228 applyNormalMatrix: function applyNormalMatrix(m) {
8229 for (var i = 0, l = this.count; i < l; i++) {
8230 _vector$3.x = this.getX(i);
8231 _vector$3.y = this.getY(i);
8232 _vector$3.z = this.getZ(i);
8234 _vector$3.applyNormalMatrix(m);
8236 this.setXYZ(i, _vector$3.x, _vector$3.y, _vector$3.z);
8241 transformDirection: function transformDirection(m) {
8242 for (var i = 0, l = this.count; i < l; i++) {
8243 _vector$3.x = this.getX(i);
8244 _vector$3.y = this.getY(i);
8245 _vector$3.z = this.getZ(i);
8247 _vector$3.transformDirection(m);
8249 this.setXYZ(i, _vector$3.x, _vector$3.y, _vector$3.z);
8254 set: function set(value, offset) {
8255 if (offset === void 0) {
8259 this.array.set(value, offset);
8262 getX: function getX(index) {
8263 return this.array[index * this.itemSize];
8265 setX: function setX(index, x) {
8266 this.array[index * this.itemSize] = x;
8269 getY: function getY(index) {
8270 return this.array[index * this.itemSize + 1];
8272 setY: function setY(index, y) {
8273 this.array[index * this.itemSize + 1] = y;
8276 getZ: function getZ(index) {
8277 return this.array[index * this.itemSize + 2];
8279 setZ: function setZ(index, z) {
8280 this.array[index * this.itemSize + 2] = z;
8283 getW: function getW(index) {
8284 return this.array[index * this.itemSize + 3];
8286 setW: function setW(index, w) {
8287 this.array[index * this.itemSize + 3] = w;
8290 setXY: function setXY(index, x, y) {
8291 index *= this.itemSize;
8292 this.array[index + 0] = x;
8293 this.array[index + 1] = y;
8296 setXYZ: function setXYZ(index, x, y, z) {
8297 index *= this.itemSize;
8298 this.array[index + 0] = x;
8299 this.array[index + 1] = y;
8300 this.array[index + 2] = z;
8303 setXYZW: function setXYZW(index, x, y, z, w) {
8304 index *= this.itemSize;
8305 this.array[index + 0] = x;
8306 this.array[index + 1] = y;
8307 this.array[index + 2] = z;
8308 this.array[index + 3] = w;
8311 onUpload: function onUpload(callback) {
8312 this.onUploadCallback = callback;
8315 clone: function clone() {
8316 return new this.constructor(this.array, this.itemSize).copy(this);
8318 toJSON: function toJSON() {
8320 itemSize: this.itemSize,
8321 type: this.array.constructor.name,
8322 array: Array.prototype.slice.call(this.array),
8323 normalized: this.normalized
8328 function Int8BufferAttribute(array, itemSize, normalized) {
8329 BufferAttribute.call(this, new Int8Array(array), itemSize, normalized);
8332 Int8BufferAttribute.prototype = Object.create(BufferAttribute.prototype);
8333 Int8BufferAttribute.prototype.constructor = Int8BufferAttribute;
8335 function Uint8BufferAttribute(array, itemSize, normalized) {
8336 BufferAttribute.call(this, new Uint8Array(array), itemSize, normalized);
8339 Uint8BufferAttribute.prototype = Object.create(BufferAttribute.prototype);
8340 Uint8BufferAttribute.prototype.constructor = Uint8BufferAttribute;
8342 function Uint8ClampedBufferAttribute(array, itemSize, normalized) {
8343 BufferAttribute.call(this, new Uint8ClampedArray(array), itemSize, normalized);
8346 Uint8ClampedBufferAttribute.prototype = Object.create(BufferAttribute.prototype);
8347 Uint8ClampedBufferAttribute.prototype.constructor = Uint8ClampedBufferAttribute;
8349 function Int16BufferAttribute(array, itemSize, normalized) {
8350 BufferAttribute.call(this, new Int16Array(array), itemSize, normalized);
8353 Int16BufferAttribute.prototype = Object.create(BufferAttribute.prototype);
8354 Int16BufferAttribute.prototype.constructor = Int16BufferAttribute;
8356 function Uint16BufferAttribute(array, itemSize, normalized) {
8357 BufferAttribute.call(this, new Uint16Array(array), itemSize, normalized);
8360 Uint16BufferAttribute.prototype = Object.create(BufferAttribute.prototype);
8361 Uint16BufferAttribute.prototype.constructor = Uint16BufferAttribute;
8363 function Int32BufferAttribute(array, itemSize, normalized) {
8364 BufferAttribute.call(this, new Int32Array(array), itemSize, normalized);
8367 Int32BufferAttribute.prototype = Object.create(BufferAttribute.prototype);
8368 Int32BufferAttribute.prototype.constructor = Int32BufferAttribute;
8370 function Uint32BufferAttribute(array, itemSize, normalized) {
8371 BufferAttribute.call(this, new Uint32Array(array), itemSize, normalized);
8374 Uint32BufferAttribute.prototype = Object.create(BufferAttribute.prototype);
8375 Uint32BufferAttribute.prototype.constructor = Uint32BufferAttribute;
8377 function Float16BufferAttribute(array, itemSize, normalized) {
8378 BufferAttribute.call(this, new Uint16Array(array), itemSize, normalized);
8381 Float16BufferAttribute.prototype = Object.create(BufferAttribute.prototype);
8382 Float16BufferAttribute.prototype.constructor = Float16BufferAttribute;
8383 Float16BufferAttribute.prototype.isFloat16BufferAttribute = true;
8385 function Float32BufferAttribute(array, itemSize, normalized) {
8386 BufferAttribute.call(this, new Float32Array(array), itemSize, normalized);
8389 Float32BufferAttribute.prototype = Object.create(BufferAttribute.prototype);
8390 Float32BufferAttribute.prototype.constructor = Float32BufferAttribute;
8392 function Float64BufferAttribute(array, itemSize, normalized) {
8393 BufferAttribute.call(this, new Float64Array(array), itemSize, normalized);
8396 Float64BufferAttribute.prototype = Object.create(BufferAttribute.prototype);
8397 Float64BufferAttribute.prototype.constructor = Float64BufferAttribute; //
8399 function arrayMax(array) {
8400 if (array.length === 0) return -Infinity;
8403 for (var i = 1, l = array.length; i < l; ++i) {
8404 if (array[i] > max) max = array[i];
8410 var TYPED_ARRAYS = {
8411 Int8Array: Int8Array,
8412 Uint8Array: Uint8Array,
8413 // Workaround for IE11 pre KB2929437. See #11440
8414 Uint8ClampedArray: typeof Uint8ClampedArray !== 'undefined' ? Uint8ClampedArray : Uint8Array,
8415 Int16Array: Int16Array,
8416 Uint16Array: Uint16Array,
8417 Int32Array: Int32Array,
8418 Uint32Array: Uint32Array,
8419 Float32Array: Float32Array,
8420 Float64Array: Float64Array
8423 function getTypedArray(type, buffer) {
8424 return new TYPED_ARRAYS[type](buffer);
8429 var _m1$2 = new Matrix4();
8431 var _obj = new Object3D();
8433 var _offset = new Vector3();
8435 var _box$2 = new Box3();
8437 var _boxMorphTargets = new Box3();
8439 var _vector$4 = new Vector3();
8441 function BufferGeometry() {
8442 Object.defineProperty(this, 'id', {
8445 this.uuid = MathUtils.generateUUID();
8447 this.type = 'BufferGeometry';
8449 this.attributes = {};
8450 this.morphAttributes = {};
8451 this.morphTargetsRelative = false;
8453 this.boundingBox = null;
8454 this.boundingSphere = null;
8462 BufferGeometry.prototype = Object.assign(Object.create(EventDispatcher.prototype), {
8463 constructor: BufferGeometry,
8464 isBufferGeometry: true,
8465 getIndex: function getIndex() {
8468 setIndex: function setIndex(index) {
8469 if (Array.isArray(index)) {
8470 this.index = new (arrayMax(index) > 65535 ? Uint32BufferAttribute : Uint16BufferAttribute)(index, 1);
8477 getAttribute: function getAttribute(name) {
8478 return this.attributes[name];
8480 setAttribute: function setAttribute(name, attribute) {
8481 this.attributes[name] = attribute;
8484 deleteAttribute: function deleteAttribute(name) {
8485 delete this.attributes[name];
8488 hasAttribute: function hasAttribute(name) {
8489 return this.attributes[name] !== undefined;
8491 addGroup: function addGroup(start, count, materialIndex) {
8492 if (materialIndex === void 0) {
8499 materialIndex: materialIndex
8502 clearGroups: function clearGroups() {
8505 setDrawRange: function setDrawRange(start, count) {
8506 this.drawRange.start = start;
8507 this.drawRange.count = count;
8509 applyMatrix4: function applyMatrix4(matrix) {
8510 var position = this.attributes.position;
8512 if (position !== undefined) {
8513 position.applyMatrix4(matrix);
8514 position.needsUpdate = true;
8517 var normal = this.attributes.normal;
8519 if (normal !== undefined) {
8520 var normalMatrix = new Matrix3().getNormalMatrix(matrix);
8521 normal.applyNormalMatrix(normalMatrix);
8522 normal.needsUpdate = true;
8525 var tangent = this.attributes.tangent;
8527 if (tangent !== undefined) {
8528 tangent.transformDirection(matrix);
8529 tangent.needsUpdate = true;
8532 if (this.boundingBox !== null) {
8533 this.computeBoundingBox();
8536 if (this.boundingSphere !== null) {
8537 this.computeBoundingSphere();
8542 rotateX: function rotateX(angle) {
8543 // rotate geometry around world x-axis
8544 _m1$2.makeRotationX(angle);
8546 this.applyMatrix4(_m1$2);
8549 rotateY: function rotateY(angle) {
8550 // rotate geometry around world y-axis
8551 _m1$2.makeRotationY(angle);
8553 this.applyMatrix4(_m1$2);
8556 rotateZ: function rotateZ(angle) {
8557 // rotate geometry around world z-axis
8558 _m1$2.makeRotationZ(angle);
8560 this.applyMatrix4(_m1$2);
8563 translate: function translate(x, y, z) {
8564 // translate geometry
8565 _m1$2.makeTranslation(x, y, z);
8567 this.applyMatrix4(_m1$2);
8570 scale: function scale(x, y, z) {
8572 _m1$2.makeScale(x, y, z);
8574 this.applyMatrix4(_m1$2);
8577 lookAt: function lookAt(vector) {
8578 _obj.lookAt(vector);
8580 _obj.updateMatrix();
8582 this.applyMatrix4(_obj.matrix);
8585 center: function center() {
8586 this.computeBoundingBox();
8587 this.boundingBox.getCenter(_offset).negate();
8588 this.translate(_offset.x, _offset.y, _offset.z);
8591 setFromPoints: function setFromPoints(points) {
8594 for (var i = 0, l = points.length; i < l; i++) {
8595 var point = points[i];
8596 position.push(point.x, point.y, point.z || 0);
8599 this.setAttribute('position', new Float32BufferAttribute(position, 3));
8602 computeBoundingBox: function computeBoundingBox() {
8603 if (this.boundingBox === null) {
8604 this.boundingBox = new Box3();
8607 var position = this.attributes.position;
8608 var morphAttributesPosition = this.morphAttributes.position;
8610 if (position && position.isGLBufferAttribute) {
8611 console.error('THREE.BufferGeometry.computeBoundingBox(): GLBufferAttribute requires a manual bounding box. Alternatively set "mesh.frustumCulled" to "false".', this);
8612 this.boundingBox.set(new Vector3(-Infinity, -Infinity, -Infinity), new Vector3(+Infinity, +Infinity, +Infinity));
8616 if (position !== undefined) {
8617 this.boundingBox.setFromBufferAttribute(position); // process morph attributes if present
8619 if (morphAttributesPosition) {
8620 for (var i = 0, il = morphAttributesPosition.length; i < il; i++) {
8621 var morphAttribute = morphAttributesPosition[i];
8623 _box$2.setFromBufferAttribute(morphAttribute);
8625 if (this.morphTargetsRelative) {
8626 _vector$4.addVectors(this.boundingBox.min, _box$2.min);
8628 this.boundingBox.expandByPoint(_vector$4);
8630 _vector$4.addVectors(this.boundingBox.max, _box$2.max);
8632 this.boundingBox.expandByPoint(_vector$4);
8634 this.boundingBox.expandByPoint(_box$2.min);
8635 this.boundingBox.expandByPoint(_box$2.max);
8640 this.boundingBox.makeEmpty();
8643 if (isNaN(this.boundingBox.min.x) || isNaN(this.boundingBox.min.y) || isNaN(this.boundingBox.min.z)) {
8644 console.error('THREE.BufferGeometry.computeBoundingBox(): Computed min/max have NaN values. The "position" attribute is likely to have NaN values.', this);
8647 computeBoundingSphere: function computeBoundingSphere() {
8648 if (this.boundingSphere === null) {
8649 this.boundingSphere = new Sphere();
8652 var position = this.attributes.position;
8653 var morphAttributesPosition = this.morphAttributes.position;
8655 if (position && position.isGLBufferAttribute) {
8656 console.error('THREE.BufferGeometry.computeBoundingSphere(): GLBufferAttribute requires a manual bounding sphere. Alternatively set "mesh.frustumCulled" to "false".', this);
8657 this.boundingSphere.set(new Vector3(), Infinity);
8662 // first, find the center of the bounding sphere
8663 var center = this.boundingSphere.center;
8665 _box$2.setFromBufferAttribute(position); // process morph attributes if present
8668 if (morphAttributesPosition) {
8669 for (var i = 0, il = morphAttributesPosition.length; i < il; i++) {
8670 var morphAttribute = morphAttributesPosition[i];
8672 _boxMorphTargets.setFromBufferAttribute(morphAttribute);
8674 if (this.morphTargetsRelative) {
8675 _vector$4.addVectors(_box$2.min, _boxMorphTargets.min);
8677 _box$2.expandByPoint(_vector$4);
8679 _vector$4.addVectors(_box$2.max, _boxMorphTargets.max);
8681 _box$2.expandByPoint(_vector$4);
8683 _box$2.expandByPoint(_boxMorphTargets.min);
8685 _box$2.expandByPoint(_boxMorphTargets.max);
8690 _box$2.getCenter(center); // second, try to find a boundingSphere with a radius smaller than the
8691 // boundingSphere of the boundingBox: sqrt(3) smaller in the best case
8694 var maxRadiusSq = 0;
8696 for (var _i = 0, _il = position.count; _i < _il; _i++) {
8697 _vector$4.fromBufferAttribute(position, _i);
8699 maxRadiusSq = Math.max(maxRadiusSq, center.distanceToSquared(_vector$4));
8700 } // process morph attributes if present
8703 if (morphAttributesPosition) {
8704 for (var _i2 = 0, _il2 = morphAttributesPosition.length; _i2 < _il2; _i2++) {
8705 var _morphAttribute = morphAttributesPosition[_i2];
8706 var morphTargetsRelative = this.morphTargetsRelative;
8708 for (var j = 0, jl = _morphAttribute.count; j < jl; j++) {
8709 _vector$4.fromBufferAttribute(_morphAttribute, j);
8711 if (morphTargetsRelative) {
8712 _offset.fromBufferAttribute(position, j);
8714 _vector$4.add(_offset);
8717 maxRadiusSq = Math.max(maxRadiusSq, center.distanceToSquared(_vector$4));
8722 this.boundingSphere.radius = Math.sqrt(maxRadiusSq);
8724 if (isNaN(this.boundingSphere.radius)) {
8725 console.error('THREE.BufferGeometry.computeBoundingSphere(): Computed radius is NaN. The "position" attribute is likely to have NaN values.', this);
8729 computeFaceNormals: function computeFaceNormals() {// backwards compatibility
8731 computeTangents: function computeTangents() {
8732 var index = this.index;
8733 var attributes = this.attributes; // based on http://www.terathon.com/code/tangent.html
8734 // (per vertex tangents)
8736 if (index === null || attributes.position === undefined || attributes.normal === undefined || attributes.uv === undefined) {
8737 console.error('THREE.BufferGeometry: .computeTangents() failed. Missing required attributes (index, position, normal or uv)');
8741 var indices = index.array;
8742 var positions = attributes.position.array;
8743 var normals = attributes.normal.array;
8744 var uvs = attributes.uv.array;
8745 var nVertices = positions.length / 3;
8747 if (attributes.tangent === undefined) {
8748 this.setAttribute('tangent', new BufferAttribute(new Float32Array(4 * nVertices), 4));
8751 var tangents = attributes.tangent.array;
8755 for (var i = 0; i < nVertices; i++) {
8756 tan1[i] = new Vector3();
8757 tan2[i] = new Vector3();
8760 var vA = new Vector3(),
8763 uvA = new Vector2(),
8764 uvB = new Vector2(),
8765 uvC = new Vector2(),
8766 sdir = new Vector3(),
8767 tdir = new Vector3();
8769 function handleTriangle(a, b, c) {
8770 vA.fromArray(positions, a * 3);
8771 vB.fromArray(positions, b * 3);
8772 vC.fromArray(positions, c * 3);
8773 uvA.fromArray(uvs, a * 2);
8774 uvB.fromArray(uvs, b * 2);
8775 uvC.fromArray(uvs, c * 2);
8780 var r = 1.0 / (uvB.x * uvC.y - uvC.x * uvB.y); // silently ignore degenerate uv triangles having coincident or colinear vertices
8782 if (!isFinite(r)) return;
8783 sdir.copy(vB).multiplyScalar(uvC.y).addScaledVector(vC, -uvB.y).multiplyScalar(r);
8784 tdir.copy(vC).multiplyScalar(uvB.x).addScaledVector(vB, -uvC.x).multiplyScalar(r);
8793 var groups = this.groups;
8795 if (groups.length === 0) {
8798 count: indices.length
8802 for (var _i3 = 0, il = groups.length; _i3 < il; ++_i3) {
8803 var group = groups[_i3];
8804 var start = group.start;
8805 var count = group.count;
8807 for (var j = start, jl = start + count; j < jl; j += 3) {
8808 handleTriangle(indices[j + 0], indices[j + 1], indices[j + 2]);
8812 var tmp = new Vector3(),
8813 tmp2 = new Vector3();
8814 var n = new Vector3(),
8817 function handleVertex(v) {
8818 n.fromArray(normals, v * 3);
8820 var t = tan1[v]; // Gram-Schmidt orthogonalize
8823 tmp.sub(n.multiplyScalar(n.dot(t))).normalize(); // Calculate handedness
8825 tmp2.crossVectors(n2, t);
8826 var test = tmp2.dot(tan2[v]);
8827 var w = test < 0.0 ? -1.0 : 1.0;
8828 tangents[v * 4] = tmp.x;
8829 tangents[v * 4 + 1] = tmp.y;
8830 tangents[v * 4 + 2] = tmp.z;
8831 tangents[v * 4 + 3] = w;
8834 for (var _i4 = 0, _il3 = groups.length; _i4 < _il3; ++_i4) {
8835 var _group = groups[_i4];
8836 var _start = _group.start;
8837 var _count = _group.count;
8839 for (var _j = _start, _jl = _start + _count; _j < _jl; _j += 3) {
8840 handleVertex(indices[_j + 0]);
8841 handleVertex(indices[_j + 1]);
8842 handleVertex(indices[_j + 2]);
8846 computeVertexNormals: function computeVertexNormals() {
8847 var index = this.index;
8848 var positionAttribute = this.getAttribute('position');
8850 if (positionAttribute !== undefined) {
8851 var normalAttribute = this.getAttribute('normal');
8853 if (normalAttribute === undefined) {
8854 normalAttribute = new BufferAttribute(new Float32Array(positionAttribute.count * 3), 3);
8855 this.setAttribute('normal', normalAttribute);
8857 // reset existing normals to zero
8858 for (var i = 0, il = normalAttribute.count; i < il; i++) {
8859 normalAttribute.setXYZ(i, 0, 0, 0);
8863 var pA = new Vector3(),
8866 var nA = new Vector3(),
8869 var cb = new Vector3(),
8870 ab = new Vector3(); // indexed elements
8873 for (var _i5 = 0, _il4 = index.count; _i5 < _il4; _i5 += 3) {
8874 var vA = index.getX(_i5 + 0);
8875 var vB = index.getX(_i5 + 1);
8876 var vC = index.getX(_i5 + 2);
8877 pA.fromBufferAttribute(positionAttribute, vA);
8878 pB.fromBufferAttribute(positionAttribute, vB);
8879 pC.fromBufferAttribute(positionAttribute, vC);
8880 cb.subVectors(pC, pB);
8881 ab.subVectors(pA, pB);
8883 nA.fromBufferAttribute(normalAttribute, vA);
8884 nB.fromBufferAttribute(normalAttribute, vB);
8885 nC.fromBufferAttribute(normalAttribute, vC);
8889 normalAttribute.setXYZ(vA, nA.x, nA.y, nA.z);
8890 normalAttribute.setXYZ(vB, nB.x, nB.y, nB.z);
8891 normalAttribute.setXYZ(vC, nC.x, nC.y, nC.z);
8894 // non-indexed elements (unconnected triangle soup)
8895 for (var _i6 = 0, _il5 = positionAttribute.count; _i6 < _il5; _i6 += 3) {
8896 pA.fromBufferAttribute(positionAttribute, _i6 + 0);
8897 pB.fromBufferAttribute(positionAttribute, _i6 + 1);
8898 pC.fromBufferAttribute(positionAttribute, _i6 + 2);
8899 cb.subVectors(pC, pB);
8900 ab.subVectors(pA, pB);
8902 normalAttribute.setXYZ(_i6 + 0, cb.x, cb.y, cb.z);
8903 normalAttribute.setXYZ(_i6 + 1, cb.x, cb.y, cb.z);
8904 normalAttribute.setXYZ(_i6 + 2, cb.x, cb.y, cb.z);
8908 this.normalizeNormals();
8909 normalAttribute.needsUpdate = true;
8912 merge: function merge(geometry, offset) {
8913 if (!(geometry && geometry.isBufferGeometry)) {
8914 console.error('THREE.BufferGeometry.merge(): geometry not an instance of THREE.BufferGeometry.', geometry);
8918 if (offset === undefined) {
8920 console.warn('THREE.BufferGeometry.merge(): Overwriting original geometry, starting at offset=0. ' + 'Use BufferGeometryUtils.mergeBufferGeometries() for lossless merge.');
8923 var attributes = this.attributes;
8925 for (var key in attributes) {
8926 if (geometry.attributes[key] === undefined) continue;
8927 var attribute1 = attributes[key];
8928 var attributeArray1 = attribute1.array;
8929 var attribute2 = geometry.attributes[key];
8930 var attributeArray2 = attribute2.array;
8931 var attributeOffset = attribute2.itemSize * offset;
8932 var length = Math.min(attributeArray2.length, attributeArray1.length - attributeOffset);
8934 for (var i = 0, j = attributeOffset; i < length; i++, j++) {
8935 attributeArray1[j] = attributeArray2[i];
8941 normalizeNormals: function normalizeNormals() {
8942 var normals = this.attributes.normal;
8944 for (var i = 0, il = normals.count; i < il; i++) {
8945 _vector$4.fromBufferAttribute(normals, i);
8947 _vector$4.normalize();
8949 normals.setXYZ(i, _vector$4.x, _vector$4.y, _vector$4.z);
8952 toNonIndexed: function toNonIndexed() {
8953 function convertBufferAttribute(attribute, indices) {
8954 var array = attribute.array;
8955 var itemSize = attribute.itemSize;
8956 var normalized = attribute.normalized;
8957 var array2 = new array.constructor(indices.length * itemSize);
8961 for (var i = 0, l = indices.length; i < l; i++) {
8962 index = indices[i] * itemSize;
8964 for (var j = 0; j < itemSize; j++) {
8965 array2[index2++] = array[index++];
8969 return new BufferAttribute(array2, itemSize, normalized);
8973 if (this.index === null) {
8974 console.warn('THREE.BufferGeometry.toNonIndexed(): BufferGeometry is already non-indexed.');
8978 var geometry2 = new BufferGeometry();
8979 var indices = this.index.array;
8980 var attributes = this.attributes; // attributes
8982 for (var name in attributes) {
8983 var attribute = attributes[name];
8984 var newAttribute = convertBufferAttribute(attribute, indices);
8985 geometry2.setAttribute(name, newAttribute);
8986 } // morph attributes
8989 var morphAttributes = this.morphAttributes;
8991 for (var _name in morphAttributes) {
8992 var morphArray = [];
8993 var morphAttribute = morphAttributes[_name]; // morphAttribute: array of Float32BufferAttributes
8995 for (var i = 0, il = morphAttribute.length; i < il; i++) {
8996 var _attribute = morphAttribute[i];
8998 var _newAttribute = convertBufferAttribute(_attribute, indices);
9000 morphArray.push(_newAttribute);
9003 geometry2.morphAttributes[_name] = morphArray;
9006 geometry2.morphTargetsRelative = this.morphTargetsRelative; // groups
9008 var groups = this.groups;
9010 for (var _i7 = 0, l = groups.length; _i7 < l; _i7++) {
9011 var group = groups[_i7];
9012 geometry2.addGroup(group.start, group.count, group.materialIndex);
9017 toJSON: function toJSON() {
9021 type: 'BufferGeometry',
9022 generator: 'BufferGeometry.toJSON'
9024 }; // standard BufferGeometry serialization
9026 data.uuid = this.uuid;
9027 data.type = this.type;
9028 if (this.name !== '') data.name = this.name;
9029 if (Object.keys(this.userData).length > 0) data.userData = this.userData;
9031 if (this.parameters !== undefined) {
9032 var parameters = this.parameters;
9034 for (var key in parameters) {
9035 if (parameters[key] !== undefined) data[key] = parameters[key];
9044 var index = this.index;
9046 if (index !== null) {
9048 type: index.array.constructor.name,
9049 array: Array.prototype.slice.call(index.array)
9053 var attributes = this.attributes;
9055 for (var _key in attributes) {
9056 var attribute = attributes[_key];
9057 var attributeData = attribute.toJSON(data.data);
9058 if (attribute.name !== '') attributeData.name = attribute.name;
9059 data.data.attributes[_key] = attributeData;
9062 var morphAttributes = {};
9063 var hasMorphAttributes = false;
9065 for (var _key2 in this.morphAttributes) {
9066 var attributeArray = this.morphAttributes[_key2];
9069 for (var i = 0, il = attributeArray.length; i < il; i++) {
9070 var _attribute2 = attributeArray[i];
9072 var _attributeData = _attribute2.toJSON(data.data);
9074 if (_attribute2.name !== '') _attributeData.name = _attribute2.name;
9075 array.push(_attributeData);
9078 if (array.length > 0) {
9079 morphAttributes[_key2] = array;
9080 hasMorphAttributes = true;
9084 if (hasMorphAttributes) {
9085 data.data.morphAttributes = morphAttributes;
9086 data.data.morphTargetsRelative = this.morphTargetsRelative;
9089 var groups = this.groups;
9091 if (groups.length > 0) {
9092 data.data.groups = JSON.parse(JSON.stringify(groups));
9095 var boundingSphere = this.boundingSphere;
9097 if (boundingSphere !== null) {
9098 data.data.boundingSphere = {
9099 center: boundingSphere.center.toArray(),
9100 radius: boundingSphere.radius
9106 clone: function clone() {
9108 // Handle primitives
9109 const parameters = this.parameters;
9110 if ( parameters !== undefined ) {
9112 for ( const key in parameters ) {
9113 values.push( parameters[ key ] );
9115 const geometry = Object.create( this.constructor.prototype );
9116 this.constructor.apply( geometry, values );
9119 return new this.constructor().copy( this );
9121 return new BufferGeometry().copy(this);
9123 copy: function copy(source) {
9126 this.attributes = {};
9127 this.morphAttributes = {};
9129 this.boundingBox = null;
9130 this.boundingSphere = null; // used for storing cloned, shared data
9132 var data = {}; // name
9134 this.name = source.name; // index
9136 var index = source.index;
9138 if (index !== null) {
9139 this.setIndex(index.clone(data));
9143 var attributes = source.attributes;
9145 for (var name in attributes) {
9146 var attribute = attributes[name];
9147 this.setAttribute(name, attribute.clone(data));
9148 } // morph attributes
9151 var morphAttributes = source.morphAttributes;
9153 for (var _name2 in morphAttributes) {
9155 var morphAttribute = morphAttributes[_name2]; // morphAttribute: array of Float32BufferAttributes
9157 for (var i = 0, l = morphAttribute.length; i < l; i++) {
9158 array.push(morphAttribute[i].clone(data));
9161 this.morphAttributes[_name2] = array;
9164 this.morphTargetsRelative = source.morphTargetsRelative; // groups
9166 var groups = source.groups;
9168 for (var _i8 = 0, _l = groups.length; _i8 < _l; _i8++) {
9169 var group = groups[_i8];
9170 this.addGroup(group.start, group.count, group.materialIndex);
9174 var boundingBox = source.boundingBox;
9176 if (boundingBox !== null) {
9177 this.boundingBox = boundingBox.clone();
9178 } // bounding sphere
9181 var boundingSphere = source.boundingSphere;
9183 if (boundingSphere !== null) {
9184 this.boundingSphere = boundingSphere.clone();
9188 this.drawRange.start = source.drawRange.start;
9189 this.drawRange.count = source.drawRange.count; // user data
9191 this.userData = source.userData;
9194 dispose: function dispose() {
9195 this.dispatchEvent({
9201 var _inverseMatrix = new Matrix4();
9203 var _ray = new Ray();
9205 var _sphere = new Sphere();
9207 var _vA = new Vector3();
9209 var _vB = new Vector3();
9211 var _vC = new Vector3();
9213 var _tempA = new Vector3();
9215 var _tempB = new Vector3();
9217 var _tempC = new Vector3();
9219 var _morphA = new Vector3();
9221 var _morphB = new Vector3();
9223 var _morphC = new Vector3();
9225 var _uvA = new Vector2();
9227 var _uvB = new Vector2();
9229 var _uvC = new Vector2();
9231 var _intersectionPoint = new Vector3();
9233 var _intersectionPointWorld = new Vector3();
9235 function Mesh(geometry, material) {
9236 if (geometry === void 0) {
9237 geometry = new BufferGeometry();
9240 if (material === void 0) {
9241 material = new MeshBasicMaterial();
9244 Object3D.call(this);
9246 this.geometry = geometry;
9247 this.material = material;
9248 this.updateMorphTargets();
9251 Mesh.prototype = Object.assign(Object.create(Object3D.prototype), {
9254 copy: function copy(source) {
9255 Object3D.prototype.copy.call(this, source);
9257 if (source.morphTargetInfluences !== undefined) {
9258 this.morphTargetInfluences = source.morphTargetInfluences.slice();
9261 if (source.morphTargetDictionary !== undefined) {
9262 this.morphTargetDictionary = Object.assign({}, source.morphTargetDictionary);
9265 this.material = source.material;
9266 this.geometry = source.geometry;
9269 updateMorphTargets: function updateMorphTargets() {
9270 var geometry = this.geometry;
9272 if (geometry.isBufferGeometry) {
9273 var morphAttributes = geometry.morphAttributes;
9274 var keys = Object.keys(morphAttributes);
9276 if (keys.length > 0) {
9277 var morphAttribute = morphAttributes[keys[0]];
9279 if (morphAttribute !== undefined) {
9280 this.morphTargetInfluences = [];
9281 this.morphTargetDictionary = {};
9283 for (var m = 0, ml = morphAttribute.length; m < ml; m++) {
9284 var name = morphAttribute[m].name || String(m);
9285 this.morphTargetInfluences.push(0);
9286 this.morphTargetDictionary[name] = m;
9291 var morphTargets = geometry.morphTargets;
9293 if (morphTargets !== undefined && morphTargets.length > 0) {
9294 console.error('THREE.Mesh.updateMorphTargets() no longer supports THREE.Geometry. Use THREE.BufferGeometry instead.');
9298 raycast: function raycast(raycaster, intersects) {
9299 var geometry = this.geometry;
9300 var material = this.material;
9301 var matrixWorld = this.matrixWorld;
9302 if (material === undefined) return; // Checking boundingSphere distance to ray
9304 if (geometry.boundingSphere === null) geometry.computeBoundingSphere();
9306 _sphere.copy(geometry.boundingSphere);
9308 _sphere.applyMatrix4(matrixWorld);
9310 if (raycaster.ray.intersectsSphere(_sphere) === false) return; //
9312 _inverseMatrix.copy(matrixWorld).invert();
9314 _ray.copy(raycaster.ray).applyMatrix4(_inverseMatrix); // Check boundingBox before continuing
9317 if (geometry.boundingBox !== null) {
9318 if (_ray.intersectsBox(geometry.boundingBox) === false) return;
9323 if (geometry.isBufferGeometry) {
9324 var index = geometry.index;
9325 var position = geometry.attributes.position;
9326 var morphPosition = geometry.morphAttributes.position;
9327 var morphTargetsRelative = geometry.morphTargetsRelative;
9328 var uv = geometry.attributes.uv;
9329 var uv2 = geometry.attributes.uv2;
9330 var groups = geometry.groups;
9331 var drawRange = geometry.drawRange;
9333 if (index !== null) {
9334 // indexed buffer geometry
9335 if (Array.isArray(material)) {
9336 for (var i = 0, il = groups.length; i < il; i++) {
9337 var group = groups[i];
9338 var groupMaterial = material[group.materialIndex];
9339 var start = Math.max(group.start, drawRange.start);
9340 var end = Math.min(group.start + group.count, drawRange.start + drawRange.count);
9342 for (var j = start, jl = end; j < jl; j += 3) {
9343 var a = index.getX(j);
9344 var b = index.getX(j + 1);
9345 var c = index.getX(j + 2);
9346 intersection = checkBufferGeometryIntersection(this, groupMaterial, raycaster, _ray, position, morphPosition, morphTargetsRelative, uv, uv2, a, b, c);
9349 intersection.faceIndex = Math.floor(j / 3); // triangle number in indexed buffer semantics
9351 intersection.face.materialIndex = group.materialIndex;
9352 intersects.push(intersection);
9357 var _start = Math.max(0, drawRange.start);
9359 var _end = Math.min(index.count, drawRange.start + drawRange.count);
9361 for (var _i = _start, _il = _end; _i < _il; _i += 3) {
9362 var _a = index.getX(_i);
9364 var _b = index.getX(_i + 1);
9366 var _c = index.getX(_i + 2);
9368 intersection = checkBufferGeometryIntersection(this, material, raycaster, _ray, position, morphPosition, morphTargetsRelative, uv, uv2, _a, _b, _c);
9371 intersection.faceIndex = Math.floor(_i / 3); // triangle number in indexed buffer semantics
9373 intersects.push(intersection);
9377 } else if (position !== undefined) {
9378 // non-indexed buffer geometry
9379 if (Array.isArray(material)) {
9380 for (var _i2 = 0, _il2 = groups.length; _i2 < _il2; _i2++) {
9381 var _group = groups[_i2];
9382 var _groupMaterial = material[_group.materialIndex];
9384 var _start2 = Math.max(_group.start, drawRange.start);
9386 var _end2 = Math.min(_group.start + _group.count, drawRange.start + drawRange.count);
9388 for (var _j = _start2, _jl = _end2; _j < _jl; _j += 3) {
9395 intersection = checkBufferGeometryIntersection(this, _groupMaterial, raycaster, _ray, position, morphPosition, morphTargetsRelative, uv, uv2, _a2, _b2, _c2);
9398 intersection.faceIndex = Math.floor(_j / 3); // triangle number in non-indexed buffer semantics
9400 intersection.face.materialIndex = _group.materialIndex;
9401 intersects.push(intersection);
9406 var _start3 = Math.max(0, drawRange.start);
9408 var _end3 = Math.min(position.count, drawRange.start + drawRange.count);
9410 for (var _i3 = _start3, _il3 = _end3; _i3 < _il3; _i3 += 3) {
9417 intersection = checkBufferGeometryIntersection(this, material, raycaster, _ray, position, morphPosition, morphTargetsRelative, uv, uv2, _a3, _b3, _c3);
9420 intersection.faceIndex = Math.floor(_i3 / 3); // triangle number in non-indexed buffer semantics
9422 intersects.push(intersection);
9427 } else if (geometry.isGeometry) {
9428 console.error('THREE.Mesh.raycast() no longer supports THREE.Geometry. Use THREE.BufferGeometry instead.');
9433 function checkIntersection(object, material, raycaster, ray, pA, pB, pC, point) {
9436 if (material.side === BackSide) {
9437 intersect = ray.intersectTriangle(pC, pB, pA, true, point);
9439 intersect = ray.intersectTriangle(pA, pB, pC, material.side !== DoubleSide, point);
9442 if (intersect === null) return null;
9444 _intersectionPointWorld.copy(point);
9446 _intersectionPointWorld.applyMatrix4(object.matrixWorld);
9448 var distance = raycaster.ray.origin.distanceTo(_intersectionPointWorld);
9449 if (distance < raycaster.near || distance > raycaster.far) return null;
9452 point: _intersectionPointWorld.clone(),
9457 function checkBufferGeometryIntersection(object, material, raycaster, ray, position, morphPosition, morphTargetsRelative, uv, uv2, a, b, c) {
9458 _vA.fromBufferAttribute(position, a);
9460 _vB.fromBufferAttribute(position, b);
9462 _vC.fromBufferAttribute(position, c);
9464 var morphInfluences = object.morphTargetInfluences;
9466 if (material.morphTargets && morphPosition && morphInfluences) {
9467 _morphA.set(0, 0, 0);
9469 _morphB.set(0, 0, 0);
9471 _morphC.set(0, 0, 0);
9473 for (var i = 0, il = morphPosition.length; i < il; i++) {
9474 var influence = morphInfluences[i];
9475 var morphAttribute = morphPosition[i];
9476 if (influence === 0) continue;
9478 _tempA.fromBufferAttribute(morphAttribute, a);
9480 _tempB.fromBufferAttribute(morphAttribute, b);
9482 _tempC.fromBufferAttribute(morphAttribute, c);
9484 if (morphTargetsRelative) {
9485 _morphA.addScaledVector(_tempA, influence);
9487 _morphB.addScaledVector(_tempB, influence);
9489 _morphC.addScaledVector(_tempC, influence);
9491 _morphA.addScaledVector(_tempA.sub(_vA), influence);
9493 _morphB.addScaledVector(_tempB.sub(_vB), influence);
9495 _morphC.addScaledVector(_tempC.sub(_vC), influence);
9506 if (object.isSkinnedMesh) {
9507 object.boneTransform(a, _vA);
9508 object.boneTransform(b, _vB);
9509 object.boneTransform(c, _vC);
9512 var intersection = checkIntersection(object, material, raycaster, ray, _vA, _vB, _vC, _intersectionPoint);
9516 _uvA.fromBufferAttribute(uv, a);
9518 _uvB.fromBufferAttribute(uv, b);
9520 _uvC.fromBufferAttribute(uv, c);
9522 intersection.uv = Triangle.getUV(_intersectionPoint, _vA, _vB, _vC, _uvA, _uvB, _uvC, new Vector2());
9526 _uvA.fromBufferAttribute(uv2, a);
9528 _uvB.fromBufferAttribute(uv2, b);
9530 _uvC.fromBufferAttribute(uv2, c);
9532 intersection.uv2 = Triangle.getUV(_intersectionPoint, _vA, _vB, _vC, _uvA, _uvB, _uvC, new Vector2());
9535 var face = new Face3(a, b, c);
9536 Triangle.getNormal(_vA, _vB, _vC, face.normal);
9537 intersection.face = face;
9540 return intersection;
9543 var BoxGeometry = /*#__PURE__*/function (_BufferGeometry) {
9544 _inheritsLoose(BoxGeometry, _BufferGeometry);
9546 function BoxGeometry(width, height, depth, widthSegments, heightSegments, depthSegments) {
9549 if (width === void 0) {
9553 if (height === void 0) {
9557 if (depth === void 0) {
9561 if (widthSegments === void 0) {
9565 if (heightSegments === void 0) {
9569 if (depthSegments === void 0) {
9573 _this = _BufferGeometry.call(this) || this;
9574 _this.type = 'BoxGeometry';
9575 _this.parameters = {
9579 widthSegments: widthSegments,
9580 heightSegments: heightSegments,
9581 depthSegments: depthSegments
9584 var scope = _assertThisInitialized(_this); // segments
9587 widthSegments = Math.floor(widthSegments);
9588 heightSegments = Math.floor(heightSegments);
9589 depthSegments = Math.floor(depthSegments); // buffers
9594 var uvs = []; // helper variables
9596 var numberOfVertices = 0;
9597 var groupStart = 0; // build each side of the box geometry
9599 buildPlane('z', 'y', 'x', -1, -1, depth, height, width, depthSegments, heightSegments, 0); // px
9601 buildPlane('z', 'y', 'x', 1, -1, depth, height, -width, depthSegments, heightSegments, 1); // nx
9603 buildPlane('x', 'z', 'y', 1, 1, width, depth, height, widthSegments, depthSegments, 2); // py
9605 buildPlane('x', 'z', 'y', 1, -1, width, depth, -height, widthSegments, depthSegments, 3); // ny
9607 buildPlane('x', 'y', 'z', 1, -1, width, height, depth, widthSegments, heightSegments, 4); // pz
9609 buildPlane('x', 'y', 'z', -1, -1, width, height, -depth, widthSegments, heightSegments, 5); // nz
9612 _this.setIndex(indices);
9614 _this.setAttribute('position', new Float32BufferAttribute(vertices, 3));
9616 _this.setAttribute('normal', new Float32BufferAttribute(normals, 3));
9618 _this.setAttribute('uv', new Float32BufferAttribute(uvs, 2));
9620 function buildPlane(u, v, w, udir, vdir, width, height, depth, gridX, gridY, materialIndex) {
9621 var segmentWidth = width / gridX;
9622 var segmentHeight = height / gridY;
9623 var widthHalf = width / 2;
9624 var heightHalf = height / 2;
9625 var depthHalf = depth / 2;
9626 var gridX1 = gridX + 1;
9627 var gridY1 = gridY + 1;
9628 var vertexCounter = 0;
9630 var vector = new Vector3(); // generate vertices, normals and uvs
9632 for (var iy = 0; iy < gridY1; iy++) {
9633 var y = iy * segmentHeight - heightHalf;
9635 for (var ix = 0; ix < gridX1; ix++) {
9636 var x = ix * segmentWidth - widthHalf; // set values to correct vector component
9638 vector[u] = x * udir;
9639 vector[v] = y * vdir;
9640 vector[w] = depthHalf; // now apply vector to vertex buffer
9642 vertices.push(vector.x, vector.y, vector.z); // set values to correct vector component
9646 vector[w] = depth > 0 ? 1 : -1; // now apply vector to normal buffer
9648 normals.push(vector.x, vector.y, vector.z); // uvs
9650 uvs.push(ix / gridX);
9651 uvs.push(1 - iy / gridY); // counters
9656 // 1. you need three indices to draw a single face
9657 // 2. a single segment consists of two faces
9658 // 3. so we need to generate six (2*3) indices per segment
9661 for (var _iy = 0; _iy < gridY; _iy++) {
9662 for (var _ix = 0; _ix < gridX; _ix++) {
9663 var a = numberOfVertices + _ix + gridX1 * _iy;
9664 var b = numberOfVertices + _ix + gridX1 * (_iy + 1);
9665 var c = numberOfVertices + (_ix + 1) + gridX1 * (_iy + 1);
9666 var d = numberOfVertices + (_ix + 1) + gridX1 * _iy; // faces
9668 indices.push(a, b, d);
9669 indices.push(b, c, d); // increase counter
9673 } // add a group to the geometry. this will ensure multi material support
9676 scope.addGroup(groupStart, groupCount, materialIndex); // calculate new start value for groups
9678 groupStart += groupCount; // update total number of vertices
9680 numberOfVertices += vertexCounter;
9692 function cloneUniforms(src) {
9695 for (var u in src) {
9698 for (var p in src[u]) {
9699 var property = src[u][p];
9701 if (property && (property.isColor || property.isMatrix3 || property.isMatrix4 || property.isVector2 || property.isVector3 || property.isVector4 || property.isTexture)) {
9702 dst[u][p] = property.clone();
9703 } else if (Array.isArray(property)) {
9704 dst[u][p] = property.slice();
9706 dst[u][p] = property;
9713 function mergeUniforms(uniforms) {
9716 for (var u = 0; u < uniforms.length; u++) {
9717 var tmp = cloneUniforms(uniforms[u]);
9719 for (var p in tmp) {
9727 var UniformsUtils = {
9728 clone: cloneUniforms,
9729 merge: mergeUniforms
9732 var default_vertex = "void main() {\n\tgl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );\n}";
9734 var default_fragment = "void main() {\n\tgl_FragColor = vec4( 1.0, 0.0, 0.0, 1.0 );\n}";
9738 * defines: { "label" : "value" },
9739 * uniforms: { "parameter1": { value: 1.0 }, "parameter2": { value2: 2 } },
9741 * fragmentShader: <string>,
9742 * vertexShader: <string>,
9744 * wireframe: <boolean>,
9745 * wireframeLinewidth: <float>,
9750 * morphTargets: <bool>,
9751 * morphNormals: <bool>
9755 function ShaderMaterial(parameters) {
9756 Material.call(this);
9757 this.type = 'ShaderMaterial';
9760 this.vertexShader = default_vertex;
9761 this.fragmentShader = default_fragment;
9763 this.wireframe = false;
9764 this.wireframeLinewidth = 1;
9765 this.fog = false; // set to use scene fog
9767 this.lights = false; // set to use scene lights
9769 this.clipping = false; // set to use user-defined clipping planes
9771 this.skinning = false; // set to use skinning attribute streams
9773 this.morphTargets = false; // set to use morph targets
9775 this.morphNormals = false; // set to use morph normals
9779 // set to use derivatives
9781 // set to use fragment depth values
9783 // set to use draw buffers
9784 shaderTextureLOD: false // set to use shader texture LOD
9786 }; // When rendered geometry doesn't include these attributes but the material does,
9787 // use these default values in WebGL. This avoids errors when buffer data is missing.
9789 this.defaultAttributeValues = {
9794 this.index0AttributeName = undefined;
9795 this.uniformsNeedUpdate = false;
9796 this.glslVersion = null;
9798 if (parameters !== undefined) {
9799 if (parameters.attributes !== undefined) {
9800 console.error('THREE.ShaderMaterial: attributes should now be defined in THREE.BufferGeometry instead.');
9803 this.setValues(parameters);
9807 ShaderMaterial.prototype = Object.create(Material.prototype);
9808 ShaderMaterial.prototype.constructor = ShaderMaterial;
9809 ShaderMaterial.prototype.isShaderMaterial = true;
9811 ShaderMaterial.prototype.copy = function (source) {
9812 Material.prototype.copy.call(this, source);
9813 this.fragmentShader = source.fragmentShader;
9814 this.vertexShader = source.vertexShader;
9815 this.uniforms = cloneUniforms(source.uniforms);
9816 this.defines = Object.assign({}, source.defines);
9817 this.wireframe = source.wireframe;
9818 this.wireframeLinewidth = source.wireframeLinewidth;
9819 this.lights = source.lights;
9820 this.clipping = source.clipping;
9821 this.skinning = source.skinning;
9822 this.morphTargets = source.morphTargets;
9823 this.morphNormals = source.morphNormals;
9824 this.extensions = Object.assign({}, source.extensions);
9825 this.glslVersion = source.glslVersion;
9829 ShaderMaterial.prototype.toJSON = function (meta) {
9830 var data = Material.prototype.toJSON.call(this, meta);
9831 data.glslVersion = this.glslVersion;
9834 for (var name in this.uniforms) {
9835 var uniform = this.uniforms[name];
9836 var value = uniform.value;
9838 if (value && value.isTexture) {
9839 data.uniforms[name] = {
9841 value: value.toJSON(meta).uuid
9843 } else if (value && value.isColor) {
9844 data.uniforms[name] = {
9846 value: value.getHex()
9848 } else if (value && value.isVector2) {
9849 data.uniforms[name] = {
9851 value: value.toArray()
9853 } else if (value && value.isVector3) {
9854 data.uniforms[name] = {
9856 value: value.toArray()
9858 } else if (value && value.isVector4) {
9859 data.uniforms[name] = {
9861 value: value.toArray()
9863 } else if (value && value.isMatrix3) {
9864 data.uniforms[name] = {
9866 value: value.toArray()
9868 } else if (value && value.isMatrix4) {
9869 data.uniforms[name] = {
9871 value: value.toArray()
9874 data.uniforms[name] = {
9876 }; // note: the array variants v2v, v3v, v4v, m4v and tv are not supported so far
9880 if (Object.keys(this.defines).length > 0) data.defines = this.defines;
9881 data.vertexShader = this.vertexShader;
9882 data.fragmentShader = this.fragmentShader;
9883 var extensions = {};
9885 for (var key in this.extensions) {
9886 if (this.extensions[key] === true) extensions[key] = true;
9889 if (Object.keys(extensions).length > 0) data.extensions = extensions;
9894 Object3D.call(this);
9895 this.type = 'Camera';
9896 this.matrixWorldInverse = new Matrix4();
9897 this.projectionMatrix = new Matrix4();
9898 this.projectionMatrixInverse = new Matrix4();
9901 Camera.prototype = Object.assign(Object.create(Object3D.prototype), {
9902 constructor: Camera,
9904 copy: function copy(source, recursive) {
9905 Object3D.prototype.copy.call(this, source, recursive);
9906 this.matrixWorldInverse.copy(source.matrixWorldInverse);
9907 this.projectionMatrix.copy(source.projectionMatrix);
9908 this.projectionMatrixInverse.copy(source.projectionMatrixInverse);
9911 getWorldDirection: function getWorldDirection(target) {
9912 if (target === undefined) {
9913 console.warn('THREE.Camera: .getWorldDirection() target is now required');
9914 target = new Vector3();
9917 this.updateWorldMatrix(true, false);
9918 var e = this.matrixWorld.elements;
9919 return target.set(-e[8], -e[9], -e[10]).normalize();
9921 updateMatrixWorld: function updateMatrixWorld(force) {
9922 Object3D.prototype.updateMatrixWorld.call(this, force);
9923 this.matrixWorldInverse.copy(this.matrixWorld).invert();
9925 updateWorldMatrix: function updateWorldMatrix(updateParents, updateChildren) {
9926 Object3D.prototype.updateWorldMatrix.call(this, updateParents, updateChildren);
9927 this.matrixWorldInverse.copy(this.matrixWorld).invert();
9929 clone: function clone() {
9930 return new this.constructor().copy(this);
9934 function PerspectiveCamera(fov, aspect, near, far) {
9935 if (fov === void 0) {
9939 if (aspect === void 0) {
9943 if (near === void 0) {
9947 if (far === void 0) {
9952 this.type = 'PerspectiveCamera';
9958 this.aspect = aspect;
9960 this.filmGauge = 35; // width of the film (default in millimeters)
9962 this.filmOffset = 0; // horizontal film offset (same unit as gauge)
9964 this.updateProjectionMatrix();
9967 PerspectiveCamera.prototype = Object.assign(Object.create(Camera.prototype), {
9968 constructor: PerspectiveCamera,
9969 isPerspectiveCamera: true,
9970 copy: function copy(source, recursive) {
9971 Camera.prototype.copy.call(this, source, recursive);
9972 this.fov = source.fov;
9973 this.zoom = source.zoom;
9974 this.near = source.near;
9975 this.far = source.far;
9976 this.focus = source.focus;
9977 this.aspect = source.aspect;
9978 this.view = source.view === null ? null : Object.assign({}, source.view);
9979 this.filmGauge = source.filmGauge;
9980 this.filmOffset = source.filmOffset;
9985 * Sets the FOV by focal length in respect to the current .filmGauge.
9987 * The default film gauge is 35, so that the focal length can be specified for
9988 * a 35mm (full frame) camera.
9990 * Values for focal length and film gauge must have the same unit.
9992 setFocalLength: function setFocalLength(focalLength) {
9993 /** see {@link http://www.bobatkins.com/photography/technical/field_of_view.html} */
9994 var vExtentSlope = 0.5 * this.getFilmHeight() / focalLength;
9995 this.fov = MathUtils.RAD2DEG * 2 * Math.atan(vExtentSlope);
9996 this.updateProjectionMatrix();
10000 * Calculates the focal length from the current .fov and .filmGauge.
10002 getFocalLength: function getFocalLength() {
10003 var vExtentSlope = Math.tan(MathUtils.DEG2RAD * 0.5 * this.fov);
10004 return 0.5 * this.getFilmHeight() / vExtentSlope;
10006 getEffectiveFOV: function getEffectiveFOV() {
10007 return MathUtils.RAD2DEG * 2 * Math.atan(Math.tan(MathUtils.DEG2RAD * 0.5 * this.fov) / this.zoom);
10009 getFilmWidth: function getFilmWidth() {
10010 // film not completely covered in portrait format (aspect < 1)
10011 return this.filmGauge * Math.min(this.aspect, 1);
10013 getFilmHeight: function getFilmHeight() {
10014 // film not completely covered in landscape format (aspect > 1)
10015 return this.filmGauge / Math.max(this.aspect, 1);
10019 * Sets an offset in a larger frustum. This is useful for multi-window or
10020 * multi-monitor/multi-machine setups.
10022 * For example, if you have 3x2 monitors and each monitor is 1920x1080 and
10023 * the monitors are in grid like this
10031 * then for each monitor you would call it like this
10035 * const fullWidth = w * 3;
10036 * const fullHeight = h * 2;
10039 * camera.setViewOffset( fullWidth, fullHeight, w * 0, h * 0, w, h );
10041 * camera.setViewOffset( fullWidth, fullHeight, w * 1, h * 0, w, h );
10043 * camera.setViewOffset( fullWidth, fullHeight, w * 2, h * 0, w, h );
10045 * camera.setViewOffset( fullWidth, fullHeight, w * 0, h * 1, w, h );
10047 * camera.setViewOffset( fullWidth, fullHeight, w * 1, h * 1, w, h );
10049 * camera.setViewOffset( fullWidth, fullHeight, w * 2, h * 1, w, h );
10051 * Note there is no reason monitors have to be the same size or in a grid.
10053 setViewOffset: function setViewOffset(fullWidth, fullHeight, x, y, width, height) {
10054 this.aspect = fullWidth / fullHeight;
10056 if (this.view === null) {
10068 this.view.enabled = true;
10069 this.view.fullWidth = fullWidth;
10070 this.view.fullHeight = fullHeight;
10071 this.view.offsetX = x;
10072 this.view.offsetY = y;
10073 this.view.width = width;
10074 this.view.height = height;
10075 this.updateProjectionMatrix();
10077 clearViewOffset: function clearViewOffset() {
10078 if (this.view !== null) {
10079 this.view.enabled = false;
10082 this.updateProjectionMatrix();
10084 updateProjectionMatrix: function updateProjectionMatrix() {
10085 var near = this.near;
10086 var top = near * Math.tan(MathUtils.DEG2RAD * 0.5 * this.fov) / this.zoom;
10087 var height = 2 * top;
10088 var width = this.aspect * height;
10089 var left = -0.5 * width;
10090 var view = this.view;
10092 if (this.view !== null && this.view.enabled) {
10093 var fullWidth = view.fullWidth,
10094 fullHeight = view.fullHeight;
10095 left += view.offsetX * width / fullWidth;
10096 top -= view.offsetY * height / fullHeight;
10097 width *= view.width / fullWidth;
10098 height *= view.height / fullHeight;
10101 var skew = this.filmOffset;
10102 if (skew !== 0) left += near * skew / this.getFilmWidth();
10103 this.projectionMatrix.makePerspective(left, left + width, top, top - height, near, this.far);
10104 this.projectionMatrixInverse.copy(this.projectionMatrix).invert();
10106 toJSON: function toJSON(meta) {
10107 var data = Object3D.prototype.toJSON.call(this, meta);
10108 data.object.fov = this.fov;
10109 data.object.zoom = this.zoom;
10110 data.object.near = this.near;
10111 data.object.far = this.far;
10112 data.object.focus = this.focus;
10113 data.object.aspect = this.aspect;
10114 if (this.view !== null) data.object.view = Object.assign({}, this.view);
10115 data.object.filmGauge = this.filmGauge;
10116 data.object.filmOffset = this.filmOffset;
10124 function CubeCamera(near, far, renderTarget) {
10125 Object3D.call(this);
10126 this.type = 'CubeCamera';
10128 if (renderTarget.isWebGLCubeRenderTarget !== true) {
10129 console.error('THREE.CubeCamera: The constructor now expects an instance of WebGLCubeRenderTarget as third parameter.');
10133 this.renderTarget = renderTarget;
10134 var cameraPX = new PerspectiveCamera(fov, aspect, near, far);
10135 cameraPX.layers = this.layers;
10136 cameraPX.up.set(0, -1, 0);
10137 cameraPX.lookAt(new Vector3(1, 0, 0));
10138 this.add(cameraPX);
10139 var cameraNX = new PerspectiveCamera(fov, aspect, near, far);
10140 cameraNX.layers = this.layers;
10141 cameraNX.up.set(0, -1, 0);
10142 cameraNX.lookAt(new Vector3(-1, 0, 0));
10143 this.add(cameraNX);
10144 var cameraPY = new PerspectiveCamera(fov, aspect, near, far);
10145 cameraPY.layers = this.layers;
10146 cameraPY.up.set(0, 0, 1);
10147 cameraPY.lookAt(new Vector3(0, 1, 0));
10148 this.add(cameraPY);
10149 var cameraNY = new PerspectiveCamera(fov, aspect, near, far);
10150 cameraNY.layers = this.layers;
10151 cameraNY.up.set(0, 0, -1);
10152 cameraNY.lookAt(new Vector3(0, -1, 0));
10153 this.add(cameraNY);
10154 var cameraPZ = new PerspectiveCamera(fov, aspect, near, far);
10155 cameraPZ.layers = this.layers;
10156 cameraPZ.up.set(0, -1, 0);
10157 cameraPZ.lookAt(new Vector3(0, 0, 1));
10158 this.add(cameraPZ);
10159 var cameraNZ = new PerspectiveCamera(fov, aspect, near, far);
10160 cameraNZ.layers = this.layers;
10161 cameraNZ.up.set(0, -1, 0);
10162 cameraNZ.lookAt(new Vector3(0, 0, -1));
10163 this.add(cameraNZ);
10165 this.update = function (renderer, scene) {
10166 if (this.parent === null) this.updateMatrixWorld();
10167 var currentXrEnabled = renderer.xr.enabled;
10168 var currentRenderTarget = renderer.getRenderTarget();
10169 renderer.xr.enabled = false;
10170 var generateMipmaps = renderTarget.texture.generateMipmaps;
10171 renderTarget.texture.generateMipmaps = false;
10172 renderer.setRenderTarget(renderTarget, 0);
10173 renderer.render(scene, cameraPX);
10174 renderer.setRenderTarget(renderTarget, 1);
10175 renderer.render(scene, cameraNX);
10176 renderer.setRenderTarget(renderTarget, 2);
10177 renderer.render(scene, cameraPY);
10178 renderer.setRenderTarget(renderTarget, 3);
10179 renderer.render(scene, cameraNY);
10180 renderer.setRenderTarget(renderTarget, 4);
10181 renderer.render(scene, cameraPZ);
10182 renderTarget.texture.generateMipmaps = generateMipmaps;
10183 renderer.setRenderTarget(renderTarget, 5);
10184 renderer.render(scene, cameraNZ);
10185 renderer.setRenderTarget(currentRenderTarget);
10186 renderer.xr.enabled = currentXrEnabled;
10190 CubeCamera.prototype = Object.create(Object3D.prototype);
10191 CubeCamera.prototype.constructor = CubeCamera;
10193 function CubeTexture(images, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding) {
10194 images = images !== undefined ? images : [];
10195 mapping = mapping !== undefined ? mapping : CubeReflectionMapping;
10196 format = format !== undefined ? format : RGBFormat;
10197 Texture.call(this, images, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding);
10198 this.flipY = false; // Why CubeTexture._needsFlipEnvMap is necessary:
10200 // By convention -- likely based on the RenderMan spec from the 1990's -- cube maps are specified by WebGL (and three.js)
10201 // in a coordinate system in which positive-x is to the right when looking up the positive-z axis -- in other words,
10202 // in a left-handed coordinate system. By continuing this convention, preexisting cube maps continued to render correctly.
10203 // three.js uses a right-handed coordinate system. So environment maps used in three.js appear to have px and nx swapped
10204 // and the flag _needsFlipEnvMap controls this conversion. The flip is not required (and thus _needsFlipEnvMap is set to false)
10205 // when using WebGLCubeRenderTarget.texture as a cube texture.
10207 this._needsFlipEnvMap = true;
10210 CubeTexture.prototype = Object.create(Texture.prototype);
10211 CubeTexture.prototype.constructor = CubeTexture;
10212 CubeTexture.prototype.isCubeTexture = true;
10213 Object.defineProperty(CubeTexture.prototype, 'images', {
10214 get: function get() {
10217 set: function set(value) {
10218 this.image = value;
10222 var WebGLCubeRenderTarget = /*#__PURE__*/function (_WebGLRenderTarget) {
10223 _inheritsLoose(WebGLCubeRenderTarget, _WebGLRenderTarget);
10225 function WebGLCubeRenderTarget(size, options, dummy) {
10228 if (Number.isInteger(options)) {
10229 console.warn('THREE.WebGLCubeRenderTarget: constructor signature is now WebGLCubeRenderTarget( size, options )');
10233 _this = _WebGLRenderTarget.call(this, size, size, options) || this;
10234 Object.defineProperty(_assertThisInitialized(_this), 'isWebGLCubeRenderTarget', {
10237 options = options || {};
10238 _this.texture = new CubeTexture(undefined, options.mapping, options.wrapS, options.wrapT, options.magFilter, options.minFilter, options.format, options.type, options.anisotropy, options.encoding);
10239 _this.texture._needsFlipEnvMap = false;
10243 var _proto = WebGLCubeRenderTarget.prototype;
10245 _proto.fromEquirectangularTexture = function fromEquirectangularTexture(renderer, texture) {
10246 this.texture.type = texture.type;
10247 this.texture.format = RGBAFormat; // see #18859
10249 this.texture.encoding = texture.encoding;
10250 this.texture.generateMipmaps = texture.generateMipmaps;
10251 this.texture.minFilter = texture.minFilter;
10252 this.texture.magFilter = texture.magFilter;
10261 "\n\n\t\t\t\tvarying vec3 vWorldDirection;\n\n\t\t\t\tvec3 transformDirection( in vec3 dir, in mat4 matrix ) {\n\n\t\t\t\t\treturn normalize( ( matrix * vec4( dir, 0.0 ) ).xyz );\n\n\t\t\t\t}\n\n\t\t\t\tvoid main() {\n\n\t\t\t\t\tvWorldDirection = transformDirection( position, modelMatrix );\n\n\t\t\t\t\t#include <begin_vertex>\n\t\t\t\t\t#include <project_vertex>\n\n\t\t\t\t}\n\t\t\t",
10264 "\n\n\t\t\t\tuniform sampler2D tEquirect;\n\n\t\t\t\tvarying vec3 vWorldDirection;\n\n\t\t\t\t#include <common>\n\n\t\t\t\tvoid main() {\n\n\t\t\t\t\tvec3 direction = normalize( vWorldDirection );\n\n\t\t\t\t\tvec2 sampleUV = equirectUv( direction );\n\n\t\t\t\t\tgl_FragColor = texture2D( tEquirect, sampleUV );\n\n\t\t\t\t}\n\t\t\t"
10266 var geometry = new BoxGeometry(5, 5, 5);
10267 var material = new ShaderMaterial({
10268 name: 'CubemapFromEquirect',
10269 uniforms: cloneUniforms(shader.uniforms),
10270 vertexShader: shader.vertexShader,
10271 fragmentShader: shader.fragmentShader,
10273 blending: NoBlending
10275 material.uniforms.tEquirect.value = texture;
10276 var mesh = new Mesh(geometry, material);
10277 var currentMinFilter = texture.minFilter; // Avoid blurred poles
10279 if (texture.minFilter === LinearMipmapLinearFilter) texture.minFilter = LinearFilter;
10280 var camera = new CubeCamera(1, 10, this);
10281 camera.update(renderer, mesh);
10282 texture.minFilter = currentMinFilter;
10283 mesh.geometry.dispose();
10284 mesh.material.dispose();
10288 _proto.clear = function clear(renderer, color, depth, stencil) {
10289 var currentRenderTarget = renderer.getRenderTarget();
10291 for (var i = 0; i < 6; i++) {
10292 renderer.setRenderTarget(this, i);
10293 renderer.clear(color, depth, stencil);
10296 renderer.setRenderTarget(currentRenderTarget);
10299 return WebGLCubeRenderTarget;
10300 }(WebGLRenderTarget);
10302 function DataTexture(data, width, height, format, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy, encoding) {
10303 Texture.call(this, null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding);
10305 data: data || null,
10307 height: height || 1
10309 this.magFilter = magFilter !== undefined ? magFilter : NearestFilter;
10310 this.minFilter = minFilter !== undefined ? minFilter : NearestFilter;
10311 this.generateMipmaps = false;
10312 this.flipY = false;
10313 this.unpackAlignment = 1;
10314 this.needsUpdate = true;
10317 DataTexture.prototype = Object.create(Texture.prototype);
10318 DataTexture.prototype.constructor = DataTexture;
10319 DataTexture.prototype.isDataTexture = true;
10321 var _sphere$1 = /*@__PURE__*/new Sphere();
10323 var _vector$5 = /*@__PURE__*/new Vector3();
10325 var Frustum = /*#__PURE__*/function () {
10326 function Frustum(p0, p1, p2, p3, p4, p5) {
10327 this.planes = [p0 !== undefined ? p0 : new Plane(), p1 !== undefined ? p1 : new Plane(), p2 !== undefined ? p2 : new Plane(), p3 !== undefined ? p3 : new Plane(), p4 !== undefined ? p4 : new Plane(), p5 !== undefined ? p5 : new Plane()];
10330 var _proto = Frustum.prototype;
10332 _proto.set = function set(p0, p1, p2, p3, p4, p5) {
10333 var planes = this.planes;
10334 planes[0].copy(p0);
10335 planes[1].copy(p1);
10336 planes[2].copy(p2);
10337 planes[3].copy(p3);
10338 planes[4].copy(p4);
10339 planes[5].copy(p5);
10343 _proto.clone = function clone() {
10344 return new this.constructor().copy(this);
10347 _proto.copy = function copy(frustum) {
10348 var planes = this.planes;
10350 for (var i = 0; i < 6; i++) {
10351 planes[i].copy(frustum.planes[i]);
10357 _proto.setFromProjectionMatrix = function setFromProjectionMatrix(m) {
10358 var planes = this.planes;
10359 var me = m.elements;
10376 planes[0].setComponents(me3 - me0, me7 - me4, me11 - me8, me15 - me12).normalize();
10377 planes[1].setComponents(me3 + me0, me7 + me4, me11 + me8, me15 + me12).normalize();
10378 planes[2].setComponents(me3 + me1, me7 + me5, me11 + me9, me15 + me13).normalize();
10379 planes[3].setComponents(me3 - me1, me7 - me5, me11 - me9, me15 - me13).normalize();
10380 planes[4].setComponents(me3 - me2, me7 - me6, me11 - me10, me15 - me14).normalize();
10381 planes[5].setComponents(me3 + me2, me7 + me6, me11 + me10, me15 + me14).normalize();
10385 _proto.intersectsObject = function intersectsObject(object) {
10386 var geometry = object.geometry;
10387 if (geometry.boundingSphere === null) geometry.computeBoundingSphere();
10389 _sphere$1.copy(geometry.boundingSphere).applyMatrix4(object.matrixWorld);
10391 return this.intersectsSphere(_sphere$1);
10394 _proto.intersectsSprite = function intersectsSprite(sprite) {
10395 _sphere$1.center.set(0, 0, 0);
10397 _sphere$1.radius = 0.7071067811865476;
10399 _sphere$1.applyMatrix4(sprite.matrixWorld);
10401 return this.intersectsSphere(_sphere$1);
10404 _proto.intersectsSphere = function intersectsSphere(sphere) {
10405 var planes = this.planes;
10406 var center = sphere.center;
10407 var negRadius = -sphere.radius;
10409 for (var i = 0; i < 6; i++) {
10410 var distance = planes[i].distanceToPoint(center);
10412 if (distance < negRadius) {
10420 _proto.intersectsBox = function intersectsBox(box) {
10421 var planes = this.planes;
10423 for (var i = 0; i < 6; i++) {
10424 var plane = planes[i]; // corner at max distance
10426 _vector$5.x = plane.normal.x > 0 ? box.max.x : box.min.x;
10427 _vector$5.y = plane.normal.y > 0 ? box.max.y : box.min.y;
10428 _vector$5.z = plane.normal.z > 0 ? box.max.z : box.min.z;
10430 if (plane.distanceToPoint(_vector$5) < 0) {
10438 _proto.containsPoint = function containsPoint(point) {
10439 var planes = this.planes;
10441 for (var i = 0; i < 6; i++) {
10442 if (planes[i].distanceToPoint(point) < 0) {
10453 function WebGLAnimation() {
10454 var context = null;
10455 var isAnimating = false;
10456 var animationLoop = null;
10457 var requestId = null;
10459 function onAnimationFrame(time, frame) {
10460 animationLoop(time, frame);
10461 requestId = context.requestAnimationFrame(onAnimationFrame);
10465 start: function start() {
10466 if (isAnimating === true) return;
10467 if (animationLoop === null) return;
10468 requestId = context.requestAnimationFrame(onAnimationFrame);
10469 isAnimating = true;
10471 stop: function stop() {
10472 context.cancelAnimationFrame(requestId);
10473 isAnimating = false;
10475 setAnimationLoop: function setAnimationLoop(callback) {
10476 animationLoop = callback;
10478 setContext: function setContext(value) {
10484 function WebGLAttributes(gl, capabilities) {
10485 var isWebGL2 = capabilities.isWebGL2;
10486 var buffers = new WeakMap();
10488 function createBuffer(attribute, bufferType) {
10489 var array = attribute.array;
10490 var usage = attribute.usage;
10491 var buffer = gl.createBuffer();
10492 gl.bindBuffer(bufferType, buffer);
10493 gl.bufferData(bufferType, array, usage);
10494 attribute.onUploadCallback();
10497 if (array instanceof Float32Array) {
10499 } else if (array instanceof Float64Array) {
10500 console.warn('THREE.WebGLAttributes: Unsupported data buffer format: Float64Array.');
10501 } else if (array instanceof Uint16Array) {
10502 if (attribute.isFloat16BufferAttribute) {
10506 console.warn('THREE.WebGLAttributes: Usage of Float16BufferAttribute requires WebGL2.');
10511 } else if (array instanceof Int16Array) {
10513 } else if (array instanceof Uint32Array) {
10515 } else if (array instanceof Int32Array) {
10517 } else if (array instanceof Int8Array) {
10519 } else if (array instanceof Uint8Array) {
10526 bytesPerElement: array.BYTES_PER_ELEMENT,
10527 version: attribute.version
10531 function updateBuffer(buffer, attribute, bufferType) {
10532 var array = attribute.array;
10533 var updateRange = attribute.updateRange;
10534 gl.bindBuffer(bufferType, buffer);
10536 if (updateRange.count === -1) {
10537 // Not using update ranges
10538 gl.bufferSubData(bufferType, 0, array);
10541 gl.bufferSubData(bufferType, updateRange.offset * array.BYTES_PER_ELEMENT, array, updateRange.offset, updateRange.count);
10543 gl.bufferSubData(bufferType, updateRange.offset * array.BYTES_PER_ELEMENT, array.subarray(updateRange.offset, updateRange.offset + updateRange.count));
10546 updateRange.count = -1; // reset range
10551 function get(attribute) {
10552 if (attribute.isInterleavedBufferAttribute) attribute = attribute.data;
10553 return buffers.get(attribute);
10556 function remove(attribute) {
10557 if (attribute.isInterleavedBufferAttribute) attribute = attribute.data;
10558 var data = buffers.get(attribute);
10561 gl.deleteBuffer(data.buffer);
10562 buffers.delete(attribute);
10566 function update(attribute, bufferType) {
10567 if (attribute.isGLBufferAttribute) {
10568 var cached = buffers.get(attribute);
10570 if (!cached || cached.version < attribute.version) {
10571 buffers.set(attribute, {
10572 buffer: attribute.buffer,
10573 type: attribute.type,
10574 bytesPerElement: attribute.elementSize,
10575 version: attribute.version
10582 if (attribute.isInterleavedBufferAttribute) attribute = attribute.data;
10583 var data = buffers.get(attribute);
10585 if (data === undefined) {
10586 buffers.set(attribute, createBuffer(attribute, bufferType));
10587 } else if (data.version < attribute.version) {
10588 updateBuffer(data.buffer, attribute, bufferType);
10589 data.version = attribute.version;
10600 var PlaneGeometry = /*#__PURE__*/function (_BufferGeometry) {
10601 _inheritsLoose(PlaneGeometry, _BufferGeometry);
10603 function PlaneGeometry(width, height, widthSegments, heightSegments) {
10606 if (width === void 0) {
10610 if (height === void 0) {
10614 if (widthSegments === void 0) {
10618 if (heightSegments === void 0) {
10619 heightSegments = 1;
10622 _this = _BufferGeometry.call(this) || this;
10623 _this.type = 'PlaneGeometry';
10624 _this.parameters = {
10627 widthSegments: widthSegments,
10628 heightSegments: heightSegments
10630 var width_half = width / 2;
10631 var height_half = height / 2;
10632 var gridX = Math.floor(widthSegments);
10633 var gridY = Math.floor(heightSegments);
10634 var gridX1 = gridX + 1;
10635 var gridY1 = gridY + 1;
10636 var segment_width = width / gridX;
10637 var segment_height = height / gridY; //
10644 for (var iy = 0; iy < gridY1; iy++) {
10645 var y = iy * segment_height - height_half;
10647 for (var ix = 0; ix < gridX1; ix++) {
10648 var x = ix * segment_width - width_half;
10649 vertices.push(x, -y, 0);
10650 normals.push(0, 0, 1);
10651 uvs.push(ix / gridX);
10652 uvs.push(1 - iy / gridY);
10656 for (var _iy = 0; _iy < gridY; _iy++) {
10657 for (var _ix = 0; _ix < gridX; _ix++) {
10658 var a = _ix + gridX1 * _iy;
10659 var b = _ix + gridX1 * (_iy + 1);
10660 var c = _ix + 1 + gridX1 * (_iy + 1);
10661 var d = _ix + 1 + gridX1 * _iy;
10662 indices.push(a, b, d);
10663 indices.push(b, c, d);
10667 _this.setIndex(indices);
10669 _this.setAttribute('position', new Float32BufferAttribute(vertices, 3));
10671 _this.setAttribute('normal', new Float32BufferAttribute(normals, 3));
10673 _this.setAttribute('uv', new Float32BufferAttribute(uvs, 2));
10678 return PlaneGeometry;
10681 var alphamap_fragment = "#ifdef USE_ALPHAMAP\n\tdiffuseColor.a *= texture2D( alphaMap, vUv ).g;\n#endif";
10683 var alphamap_pars_fragment = "#ifdef USE_ALPHAMAP\n\tuniform sampler2D alphaMap;\n#endif";
10685 var alphatest_fragment = "#ifdef ALPHATEST\n\tif ( diffuseColor.a < ALPHATEST ) discard;\n#endif";
10687 var aomap_fragment = "#ifdef USE_AOMAP\n\tfloat ambientOcclusion = ( texture2D( aoMap, vUv2 ).r - 1.0 ) * aoMapIntensity + 1.0;\n\treflectedLight.indirectDiffuse *= ambientOcclusion;\n\t#if defined( USE_ENVMAP ) && defined( STANDARD )\n\t\tfloat dotNV = saturate( dot( geometry.normal, geometry.viewDir ) );\n\t\treflectedLight.indirectSpecular *= computeSpecularOcclusion( dotNV, ambientOcclusion, material.specularRoughness );\n\t#endif\n#endif";
10689 var aomap_pars_fragment = "#ifdef USE_AOMAP\n\tuniform sampler2D aoMap;\n\tuniform float aoMapIntensity;\n#endif";
10691 var begin_vertex = "vec3 transformed = vec3( position );";
10693 var beginnormal_vertex = "vec3 objectNormal = vec3( normal );\n#ifdef USE_TANGENT\n\tvec3 objectTangent = vec3( tangent.xyz );\n#endif";
10695 var bsdfs = "vec2 integrateSpecularBRDF( const in float dotNV, const in float roughness ) {\n\tconst vec4 c0 = vec4( - 1, - 0.0275, - 0.572, 0.022 );\n\tconst vec4 c1 = vec4( 1, 0.0425, 1.04, - 0.04 );\n\tvec4 r = roughness * c0 + c1;\n\tfloat a004 = min( r.x * r.x, exp2( - 9.28 * dotNV ) ) * r.x + r.y;\n\treturn vec2( -1.04, 1.04 ) * a004 + r.zw;\n}\nfloat punctualLightIntensityToIrradianceFactor( const in float lightDistance, const in float cutoffDistance, const in float decayExponent ) {\n#if defined ( PHYSICALLY_CORRECT_LIGHTS )\n\tfloat distanceFalloff = 1.0 / max( pow( lightDistance, decayExponent ), 0.01 );\n\tif( cutoffDistance > 0.0 ) {\n\t\tdistanceFalloff *= pow2( saturate( 1.0 - pow4( lightDistance / cutoffDistance ) ) );\n\t}\n\treturn distanceFalloff;\n#else\n\tif( cutoffDistance > 0.0 && decayExponent > 0.0 ) {\n\t\treturn pow( saturate( -lightDistance / cutoffDistance + 1.0 ), decayExponent );\n\t}\n\treturn 1.0;\n#endif\n}\nvec3 BRDF_Diffuse_Lambert( const in vec3 diffuseColor ) {\n\treturn RECIPROCAL_PI * diffuseColor;\n}\nvec3 F_Schlick( const in vec3 specularColor, const in float dotLH ) {\n\tfloat fresnel = exp2( ( -5.55473 * dotLH - 6.98316 ) * dotLH );\n\treturn ( 1.0 - specularColor ) * fresnel + specularColor;\n}\nvec3 F_Schlick_RoughnessDependent( const in vec3 F0, const in float dotNV, const in float roughness ) {\n\tfloat fresnel = exp2( ( -5.55473 * dotNV - 6.98316 ) * dotNV );\n\tvec3 Fr = max( vec3( 1.0 - roughness ), F0 ) - F0;\n\treturn Fr * fresnel + F0;\n}\nfloat G_GGX_Smith( const in float alpha, const in float dotNL, const in float dotNV ) {\n\tfloat a2 = pow2( alpha );\n\tfloat gl = dotNL + sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNL ) );\n\tfloat gv = dotNV + sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNV ) );\n\treturn 1.0 / ( gl * gv );\n}\nfloat G_GGX_SmithCorrelated( const in float alpha, const in float dotNL, const in float dotNV ) {\n\tfloat a2 = pow2( alpha );\n\tfloat gv = dotNL * sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNV ) );\n\tfloat gl = dotNV * sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNL ) );\n\treturn 0.5 / max( gv + gl, EPSILON );\n}\nfloat D_GGX( const in float alpha, const in float dotNH ) {\n\tfloat a2 = pow2( alpha );\n\tfloat denom = pow2( dotNH ) * ( a2 - 1.0 ) + 1.0;\n\treturn RECIPROCAL_PI * a2 / pow2( denom );\n}\nvec3 BRDF_Specular_GGX( const in IncidentLight incidentLight, const in vec3 viewDir, const in vec3 normal, const in vec3 specularColor, const in float roughness ) {\n\tfloat alpha = pow2( roughness );\n\tvec3 halfDir = normalize( incidentLight.direction + viewDir );\n\tfloat dotNL = saturate( dot( normal, incidentLight.direction ) );\n\tfloat dotNV = saturate( dot( normal, viewDir ) );\n\tfloat dotNH = saturate( dot( normal, halfDir ) );\n\tfloat dotLH = saturate( dot( incidentLight.direction, halfDir ) );\n\tvec3 F = F_Schlick( specularColor, dotLH );\n\tfloat G = G_GGX_SmithCorrelated( alpha, dotNL, dotNV );\n\tfloat D = D_GGX( alpha, dotNH );\n\treturn F * ( G * D );\n}\nvec2 LTC_Uv( const in vec3 N, const in vec3 V, const in float roughness ) {\n\tconst float LUT_SIZE = 64.0;\n\tconst float LUT_SCALE = ( LUT_SIZE - 1.0 ) / LUT_SIZE;\n\tconst float LUT_BIAS = 0.5 / LUT_SIZE;\n\tfloat dotNV = saturate( dot( N, V ) );\n\tvec2 uv = vec2( roughness, sqrt( 1.0 - dotNV ) );\n\tuv = uv * LUT_SCALE + LUT_BIAS;\n\treturn uv;\n}\nfloat LTC_ClippedSphereFormFactor( const in vec3 f ) {\n\tfloat l = length( f );\n\treturn max( ( l * l + f.z ) / ( l + 1.0 ), 0.0 );\n}\nvec3 LTC_EdgeVectorFormFactor( const in vec3 v1, const in vec3 v2 ) {\n\tfloat x = dot( v1, v2 );\n\tfloat y = abs( x );\n\tfloat a = 0.8543985 + ( 0.4965155 + 0.0145206 * y ) * y;\n\tfloat b = 3.4175940 + ( 4.1616724 + y ) * y;\n\tfloat v = a / b;\n\tfloat theta_sintheta = ( x > 0.0 ) ? v : 0.5 * inversesqrt( max( 1.0 - x * x, 1e-7 ) ) - v;\n\treturn cross( v1, v2 ) * theta_sintheta;\n}\nvec3 LTC_Evaluate( const in vec3 N, const in vec3 V, const in vec3 P, const in mat3 mInv, const in vec3 rectCoords[ 4 ] ) {\n\tvec3 v1 = rectCoords[ 1 ] - rectCoords[ 0 ];\n\tvec3 v2 = rectCoords[ 3 ] - rectCoords[ 0 ];\n\tvec3 lightNormal = cross( v1, v2 );\n\tif( dot( lightNormal, P - rectCoords[ 0 ] ) < 0.0 ) return vec3( 0.0 );\n\tvec3 T1, T2;\n\tT1 = normalize( V - N * dot( V, N ) );\n\tT2 = - cross( N, T1 );\n\tmat3 mat = mInv * transposeMat3( mat3( T1, T2, N ) );\n\tvec3 coords[ 4 ];\n\tcoords[ 0 ] = mat * ( rectCoords[ 0 ] - P );\n\tcoords[ 1 ] = mat * ( rectCoords[ 1 ] - P );\n\tcoords[ 2 ] = mat * ( rectCoords[ 2 ] - P );\n\tcoords[ 3 ] = mat * ( rectCoords[ 3 ] - P );\n\tcoords[ 0 ] = normalize( coords[ 0 ] );\n\tcoords[ 1 ] = normalize( coords[ 1 ] );\n\tcoords[ 2 ] = normalize( coords[ 2 ] );\n\tcoords[ 3 ] = normalize( coords[ 3 ] );\n\tvec3 vectorFormFactor = vec3( 0.0 );\n\tvectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 0 ], coords[ 1 ] );\n\tvectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 1 ], coords[ 2 ] );\n\tvectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 2 ], coords[ 3 ] );\n\tvectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 3 ], coords[ 0 ] );\n\tfloat result = LTC_ClippedSphereFormFactor( vectorFormFactor );\n\treturn vec3( result );\n}\nvec3 BRDF_Specular_GGX_Environment( const in vec3 viewDir, const in vec3 normal, const in vec3 specularColor, const in float roughness ) {\n\tfloat dotNV = saturate( dot( normal, viewDir ) );\n\tvec2 brdf = integrateSpecularBRDF( dotNV, roughness );\n\treturn specularColor * brdf.x + brdf.y;\n}\nvoid BRDF_Specular_Multiscattering_Environment( const in GeometricContext geometry, const in vec3 specularColor, const in float roughness, inout vec3 singleScatter, inout vec3 multiScatter ) {\n\tfloat dotNV = saturate( dot( geometry.normal, geometry.viewDir ) );\n\tvec3 F = F_Schlick_RoughnessDependent( specularColor, dotNV, roughness );\n\tvec2 brdf = integrateSpecularBRDF( dotNV, roughness );\n\tvec3 FssEss = F * brdf.x + brdf.y;\n\tfloat Ess = brdf.x + brdf.y;\n\tfloat Ems = 1.0 - Ess;\n\tvec3 Favg = specularColor + ( 1.0 - specularColor ) * 0.047619;\tvec3 Fms = FssEss * Favg / ( 1.0 - Ems * Favg );\n\tsingleScatter += FssEss;\n\tmultiScatter += Fms * Ems;\n}\nfloat G_BlinnPhong_Implicit( ) {\n\treturn 0.25;\n}\nfloat D_BlinnPhong( const in float shininess, const in float dotNH ) {\n\treturn RECIPROCAL_PI * ( shininess * 0.5 + 1.0 ) * pow( dotNH, shininess );\n}\nvec3 BRDF_Specular_BlinnPhong( const in IncidentLight incidentLight, const in GeometricContext geometry, const in vec3 specularColor, const in float shininess ) {\n\tvec3 halfDir = normalize( incidentLight.direction + geometry.viewDir );\n\tfloat dotNH = saturate( dot( geometry.normal, halfDir ) );\n\tfloat dotLH = saturate( dot( incidentLight.direction, halfDir ) );\n\tvec3 F = F_Schlick( specularColor, dotLH );\n\tfloat G = G_BlinnPhong_Implicit( );\n\tfloat D = D_BlinnPhong( shininess, dotNH );\n\treturn F * ( G * D );\n}\nfloat GGXRoughnessToBlinnExponent( const in float ggxRoughness ) {\n\treturn ( 2.0 / pow2( ggxRoughness + 0.0001 ) - 2.0 );\n}\nfloat BlinnExponentToGGXRoughness( const in float blinnExponent ) {\n\treturn sqrt( 2.0 / ( blinnExponent + 2.0 ) );\n}\n#if defined( USE_SHEEN )\nfloat D_Charlie(float roughness, float NoH) {\n\tfloat invAlpha = 1.0 / roughness;\n\tfloat cos2h = NoH * NoH;\n\tfloat sin2h = max(1.0 - cos2h, 0.0078125);\treturn (2.0 + invAlpha) * pow(sin2h, invAlpha * 0.5) / (2.0 * PI);\n}\nfloat V_Neubelt(float NoV, float NoL) {\n\treturn saturate(1.0 / (4.0 * (NoL + NoV - NoL * NoV)));\n}\nvec3 BRDF_Specular_Sheen( const in float roughness, const in vec3 L, const in GeometricContext geometry, vec3 specularColor ) {\n\tvec3 N = geometry.normal;\n\tvec3 V = geometry.viewDir;\n\tvec3 H = normalize( V + L );\n\tfloat dotNH = saturate( dot( N, H ) );\n\treturn specularColor * D_Charlie( roughness, dotNH ) * V_Neubelt( dot(N, V), dot(N, L) );\n}\n#endif";
10697 var bumpmap_pars_fragment = "#ifdef USE_BUMPMAP\n\tuniform sampler2D bumpMap;\n\tuniform float bumpScale;\n\tvec2 dHdxy_fwd() {\n\t\tvec2 dSTdx = dFdx( vUv );\n\t\tvec2 dSTdy = dFdy( vUv );\n\t\tfloat Hll = bumpScale * texture2D( bumpMap, vUv ).x;\n\t\tfloat dBx = bumpScale * texture2D( bumpMap, vUv + dSTdx ).x - Hll;\n\t\tfloat dBy = bumpScale * texture2D( bumpMap, vUv + dSTdy ).x - Hll;\n\t\treturn vec2( dBx, dBy );\n\t}\n\tvec3 perturbNormalArb( vec3 surf_pos, vec3 surf_norm, vec2 dHdxy ) {\n\t\tvec3 vSigmaX = vec3( dFdx( surf_pos.x ), dFdx( surf_pos.y ), dFdx( surf_pos.z ) );\n\t\tvec3 vSigmaY = vec3( dFdy( surf_pos.x ), dFdy( surf_pos.y ), dFdy( surf_pos.z ) );\n\t\tvec3 vN = surf_norm;\n\t\tvec3 R1 = cross( vSigmaY, vN );\n\t\tvec3 R2 = cross( vN, vSigmaX );\n\t\tfloat fDet = dot( vSigmaX, R1 );\n\t\tfDet *= ( float( gl_FrontFacing ) * 2.0 - 1.0 );\n\t\tvec3 vGrad = sign( fDet ) * ( dHdxy.x * R1 + dHdxy.y * R2 );\n\t\treturn normalize( abs( fDet ) * surf_norm - vGrad );\n\t}\n#endif";
10699 var clipping_planes_fragment = "#if NUM_CLIPPING_PLANES > 0\n\tvec4 plane;\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < UNION_CLIPPING_PLANES; i ++ ) {\n\t\tplane = clippingPlanes[ i ];\n\t\tif ( dot( vClipPosition, plane.xyz ) > plane.w ) discard;\n\t}\n\t#pragma unroll_loop_end\n\t#if UNION_CLIPPING_PLANES < NUM_CLIPPING_PLANES\n\t\tbool clipped = true;\n\t\t#pragma unroll_loop_start\n\t\tfor ( int i = UNION_CLIPPING_PLANES; i < NUM_CLIPPING_PLANES; i ++ ) {\n\t\t\tplane = clippingPlanes[ i ];\n\t\t\tclipped = ( dot( vClipPosition, plane.xyz ) > plane.w ) && clipped;\n\t\t}\n\t\t#pragma unroll_loop_end\n\t\tif ( clipped ) discard;\n\t#endif\n#endif";
10701 var clipping_planes_pars_fragment = "#if NUM_CLIPPING_PLANES > 0\n\tvarying vec3 vClipPosition;\n\tuniform vec4 clippingPlanes[ NUM_CLIPPING_PLANES ];\n#endif";
10703 var clipping_planes_pars_vertex = "#if NUM_CLIPPING_PLANES > 0\n\tvarying vec3 vClipPosition;\n#endif";
10705 var clipping_planes_vertex = "#if NUM_CLIPPING_PLANES > 0\n\tvClipPosition = - mvPosition.xyz;\n#endif";
10707 var color_fragment = "#ifdef USE_COLOR\n\tdiffuseColor.rgb *= vColor;\n#endif";
10709 var color_pars_fragment = "#ifdef USE_COLOR\n\tvarying vec3 vColor;\n#endif";
10711 var color_pars_vertex = "#if defined( USE_COLOR ) || defined( USE_INSTANCING_COLOR )\n\tvarying vec3 vColor;\n#endif";
10713 var color_vertex = "#if defined( USE_COLOR ) || defined( USE_INSTANCING_COLOR )\n\tvColor = vec3( 1.0 );\n#endif\n#ifdef USE_COLOR\n\tvColor.xyz *= color.xyz;\n#endif\n#ifdef USE_INSTANCING_COLOR\n\tvColor.xyz *= instanceColor.xyz;\n#endif";
10715 var common = "#define PI 3.141592653589793\n#define PI2 6.283185307179586\n#define PI_HALF 1.5707963267948966\n#define RECIPROCAL_PI 0.3183098861837907\n#define RECIPROCAL_PI2 0.15915494309189535\n#define EPSILON 1e-6\n#ifndef saturate\n#define saturate(a) clamp( a, 0.0, 1.0 )\n#endif\n#define whiteComplement(a) ( 1.0 - saturate( a ) )\nfloat pow2( const in float x ) { return x*x; }\nfloat pow3( const in float x ) { return x*x*x; }\nfloat pow4( const in float x ) { float x2 = x*x; return x2*x2; }\nfloat average( const in vec3 color ) { return dot( color, vec3( 0.3333 ) ); }\nhighp float rand( const in vec2 uv ) {\n\tconst highp float a = 12.9898, b = 78.233, c = 43758.5453;\n\thighp float dt = dot( uv.xy, vec2( a,b ) ), sn = mod( dt, PI );\n\treturn fract(sin(sn) * c);\n}\n#ifdef HIGH_PRECISION\n\tfloat precisionSafeLength( vec3 v ) { return length( v ); }\n#else\n\tfloat max3( vec3 v ) { return max( max( v.x, v.y ), v.z ); }\n\tfloat precisionSafeLength( vec3 v ) {\n\t\tfloat maxComponent = max3( abs( v ) );\n\t\treturn length( v / maxComponent ) * maxComponent;\n\t}\n#endif\nstruct IncidentLight {\n\tvec3 color;\n\tvec3 direction;\n\tbool visible;\n};\nstruct ReflectedLight {\n\tvec3 directDiffuse;\n\tvec3 directSpecular;\n\tvec3 indirectDiffuse;\n\tvec3 indirectSpecular;\n};\nstruct GeometricContext {\n\tvec3 position;\n\tvec3 normal;\n\tvec3 viewDir;\n#ifdef CLEARCOAT\n\tvec3 clearcoatNormal;\n#endif\n};\nvec3 transformDirection( in vec3 dir, in mat4 matrix ) {\n\treturn normalize( ( matrix * vec4( dir, 0.0 ) ).xyz );\n}\nvec3 inverseTransformDirection( in vec3 dir, in mat4 matrix ) {\n\treturn normalize( ( vec4( dir, 0.0 ) * matrix ).xyz );\n}\nvec3 projectOnPlane(in vec3 point, in vec3 pointOnPlane, in vec3 planeNormal ) {\n\tfloat distance = dot( planeNormal, point - pointOnPlane );\n\treturn - distance * planeNormal + point;\n}\nfloat sideOfPlane( in vec3 point, in vec3 pointOnPlane, in vec3 planeNormal ) {\n\treturn sign( dot( point - pointOnPlane, planeNormal ) );\n}\nvec3 linePlaneIntersect( in vec3 pointOnLine, in vec3 lineDirection, in vec3 pointOnPlane, in vec3 planeNormal ) {\n\treturn lineDirection * ( dot( planeNormal, pointOnPlane - pointOnLine ) / dot( planeNormal, lineDirection ) ) + pointOnLine;\n}\nmat3 transposeMat3( const in mat3 m ) {\n\tmat3 tmp;\n\ttmp[ 0 ] = vec3( m[ 0 ].x, m[ 1 ].x, m[ 2 ].x );\n\ttmp[ 1 ] = vec3( m[ 0 ].y, m[ 1 ].y, m[ 2 ].y );\n\ttmp[ 2 ] = vec3( m[ 0 ].z, m[ 1 ].z, m[ 2 ].z );\n\treturn tmp;\n}\nfloat linearToRelativeLuminance( const in vec3 color ) {\n\tvec3 weights = vec3( 0.2126, 0.7152, 0.0722 );\n\treturn dot( weights, color.rgb );\n}\nbool isPerspectiveMatrix( mat4 m ) {\n\treturn m[ 2 ][ 3 ] == - 1.0;\n}\nvec2 equirectUv( in vec3 dir ) {\n\tfloat u = atan( dir.z, dir.x ) * RECIPROCAL_PI2 + 0.5;\n\tfloat v = asin( clamp( dir.y, - 1.0, 1.0 ) ) * RECIPROCAL_PI + 0.5;\n\treturn vec2( u, v );\n}";
10717 var cube_uv_reflection_fragment = "#ifdef ENVMAP_TYPE_CUBE_UV\n\t#define cubeUV_maxMipLevel 8.0\n\t#define cubeUV_minMipLevel 4.0\n\t#define cubeUV_maxTileSize 256.0\n\t#define cubeUV_minTileSize 16.0\n\tfloat getFace( vec3 direction ) {\n\t\tvec3 absDirection = abs( direction );\n\t\tfloat face = - 1.0;\n\t\tif ( absDirection.x > absDirection.z ) {\n\t\t\tif ( absDirection.x > absDirection.y )\n\t\t\t\tface = direction.x > 0.0 ? 0.0 : 3.0;\n\t\t\telse\n\t\t\t\tface = direction.y > 0.0 ? 1.0 : 4.0;\n\t\t} else {\n\t\t\tif ( absDirection.z > absDirection.y )\n\t\t\t\tface = direction.z > 0.0 ? 2.0 : 5.0;\n\t\t\telse\n\t\t\t\tface = direction.y > 0.0 ? 1.0 : 4.0;\n\t\t}\n\t\treturn face;\n\t}\n\tvec2 getUV( vec3 direction, float face ) {\n\t\tvec2 uv;\n\t\tif ( face == 0.0 ) {\n\t\t\tuv = vec2( direction.z, direction.y ) / abs( direction.x );\n\t\t} else if ( face == 1.0 ) {\n\t\t\tuv = vec2( - direction.x, - direction.z ) / abs( direction.y );\n\t\t} else if ( face == 2.0 ) {\n\t\t\tuv = vec2( - direction.x, direction.y ) / abs( direction.z );\n\t\t} else if ( face == 3.0 ) {\n\t\t\tuv = vec2( - direction.z, direction.y ) / abs( direction.x );\n\t\t} else if ( face == 4.0 ) {\n\t\t\tuv = vec2( - direction.x, direction.z ) / abs( direction.y );\n\t\t} else {\n\t\t\tuv = vec2( direction.x, direction.y ) / abs( direction.z );\n\t\t}\n\t\treturn 0.5 * ( uv + 1.0 );\n\t}\n\tvec3 bilinearCubeUV( sampler2D envMap, vec3 direction, float mipInt ) {\n\t\tfloat face = getFace( direction );\n\t\tfloat filterInt = max( cubeUV_minMipLevel - mipInt, 0.0 );\n\t\tmipInt = max( mipInt, cubeUV_minMipLevel );\n\t\tfloat faceSize = exp2( mipInt );\n\t\tfloat texelSize = 1.0 / ( 3.0 * cubeUV_maxTileSize );\n\t\tvec2 uv = getUV( direction, face ) * ( faceSize - 1.0 );\n\t\tvec2 f = fract( uv );\n\t\tuv += 0.5 - f;\n\t\tif ( face > 2.0 ) {\n\t\t\tuv.y += faceSize;\n\t\t\tface -= 3.0;\n\t\t}\n\t\tuv.x += face * faceSize;\n\t\tif ( mipInt < cubeUV_maxMipLevel ) {\n\t\t\tuv.y += 2.0 * cubeUV_maxTileSize;\n\t\t}\n\t\tuv.y += filterInt * 2.0 * cubeUV_minTileSize;\n\t\tuv.x += 3.0 * max( 0.0, cubeUV_maxTileSize - 2.0 * faceSize );\n\t\tuv *= texelSize;\n\t\tvec3 tl = envMapTexelToLinear( texture2D( envMap, uv ) ).rgb;\n\t\tuv.x += texelSize;\n\t\tvec3 tr = envMapTexelToLinear( texture2D( envMap, uv ) ).rgb;\n\t\tuv.y += texelSize;\n\t\tvec3 br = envMapTexelToLinear( texture2D( envMap, uv ) ).rgb;\n\t\tuv.x -= texelSize;\n\t\tvec3 bl = envMapTexelToLinear( texture2D( envMap, uv ) ).rgb;\n\t\tvec3 tm = mix( tl, tr, f.x );\n\t\tvec3 bm = mix( bl, br, f.x );\n\t\treturn mix( tm, bm, f.y );\n\t}\n\t#define r0 1.0\n\t#define v0 0.339\n\t#define m0 - 2.0\n\t#define r1 0.8\n\t#define v1 0.276\n\t#define m1 - 1.0\n\t#define r4 0.4\n\t#define v4 0.046\n\t#define m4 2.0\n\t#define r5 0.305\n\t#define v5 0.016\n\t#define m5 3.0\n\t#define r6 0.21\n\t#define v6 0.0038\n\t#define m6 4.0\n\tfloat roughnessToMip( float roughness ) {\n\t\tfloat mip = 0.0;\n\t\tif ( roughness >= r1 ) {\n\t\t\tmip = ( r0 - roughness ) * ( m1 - m0 ) / ( r0 - r1 ) + m0;\n\t\t} else if ( roughness >= r4 ) {\n\t\t\tmip = ( r1 - roughness ) * ( m4 - m1 ) / ( r1 - r4 ) + m1;\n\t\t} else if ( roughness >= r5 ) {\n\t\t\tmip = ( r4 - roughness ) * ( m5 - m4 ) / ( r4 - r5 ) + m4;\n\t\t} else if ( roughness >= r6 ) {\n\t\t\tmip = ( r5 - roughness ) * ( m6 - m5 ) / ( r5 - r6 ) + m5;\n\t\t} else {\n\t\t\tmip = - 2.0 * log2( 1.16 * roughness );\t\t}\n\t\treturn mip;\n\t}\n\tvec4 textureCubeUV( sampler2D envMap, vec3 sampleDir, float roughness ) {\n\t\tfloat mip = clamp( roughnessToMip( roughness ), m0, cubeUV_maxMipLevel );\n\t\tfloat mipF = fract( mip );\n\t\tfloat mipInt = floor( mip );\n\t\tvec3 color0 = bilinearCubeUV( envMap, sampleDir, mipInt );\n\t\tif ( mipF == 0.0 ) {\n\t\t\treturn vec4( color0, 1.0 );\n\t\t} else {\n\t\t\tvec3 color1 = bilinearCubeUV( envMap, sampleDir, mipInt + 1.0 );\n\t\t\treturn vec4( mix( color0, color1, mipF ), 1.0 );\n\t\t}\n\t}\n#endif";
10719 var defaultnormal_vertex = "vec3 transformedNormal = objectNormal;\n#ifdef USE_INSTANCING\n\tmat3 m = mat3( instanceMatrix );\n\ttransformedNormal /= vec3( dot( m[ 0 ], m[ 0 ] ), dot( m[ 1 ], m[ 1 ] ), dot( m[ 2 ], m[ 2 ] ) );\n\ttransformedNormal = m * transformedNormal;\n#endif\ntransformedNormal = normalMatrix * transformedNormal;\n#ifdef FLIP_SIDED\n\ttransformedNormal = - transformedNormal;\n#endif\n#ifdef USE_TANGENT\n\tvec3 transformedTangent = ( modelViewMatrix * vec4( objectTangent, 0.0 ) ).xyz;\n\t#ifdef FLIP_SIDED\n\t\ttransformedTangent = - transformedTangent;\n\t#endif\n#endif";
10721 var displacementmap_pars_vertex = "#ifdef USE_DISPLACEMENTMAP\n\tuniform sampler2D displacementMap;\n\tuniform float displacementScale;\n\tuniform float displacementBias;\n#endif";
10723 var displacementmap_vertex = "#ifdef USE_DISPLACEMENTMAP\n\ttransformed += normalize( objectNormal ) * ( texture2D( displacementMap, vUv ).x * displacementScale + displacementBias );\n#endif";
10725 var emissivemap_fragment = "#ifdef USE_EMISSIVEMAP\n\tvec4 emissiveColor = texture2D( emissiveMap, vUv );\n\temissiveColor.rgb = emissiveMapTexelToLinear( emissiveColor ).rgb;\n\ttotalEmissiveRadiance *= emissiveColor.rgb;\n#endif";
10727 var emissivemap_pars_fragment = "#ifdef USE_EMISSIVEMAP\n\tuniform sampler2D emissiveMap;\n#endif";
10729 var encodings_fragment = "gl_FragColor = linearToOutputTexel( gl_FragColor );";
10731 var encodings_pars_fragment = "\nvec4 LinearToLinear( in vec4 value ) {\n\treturn value;\n}\nvec4 GammaToLinear( in vec4 value, in float gammaFactor ) {\n\treturn vec4( pow( value.rgb, vec3( gammaFactor ) ), value.a );\n}\nvec4 LinearToGamma( in vec4 value, in float gammaFactor ) {\n\treturn vec4( pow( value.rgb, vec3( 1.0 / gammaFactor ) ), value.a );\n}\nvec4 sRGBToLinear( in vec4 value ) {\n\treturn vec4( mix( pow( value.rgb * 0.9478672986 + vec3( 0.0521327014 ), vec3( 2.4 ) ), value.rgb * 0.0773993808, vec3( lessThanEqual( value.rgb, vec3( 0.04045 ) ) ) ), value.a );\n}\nvec4 LinearTosRGB( in vec4 value ) {\n\treturn 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 );\n}\nvec4 RGBEToLinear( in vec4 value ) {\n\treturn vec4( value.rgb * exp2( value.a * 255.0 - 128.0 ), 1.0 );\n}\nvec4 LinearToRGBE( in vec4 value ) {\n\tfloat maxComponent = max( max( value.r, value.g ), value.b );\n\tfloat fExp = clamp( ceil( log2( maxComponent ) ), -128.0, 127.0 );\n\treturn vec4( value.rgb / exp2( fExp ), ( fExp + 128.0 ) / 255.0 );\n}\nvec4 RGBMToLinear( in vec4 value, in float maxRange ) {\n\treturn vec4( value.rgb * value.a * maxRange, 1.0 );\n}\nvec4 LinearToRGBM( in vec4 value, in float maxRange ) {\n\tfloat maxRGB = max( value.r, max( value.g, value.b ) );\n\tfloat M = clamp( maxRGB / maxRange, 0.0, 1.0 );\n\tM = ceil( M * 255.0 ) / 255.0;\n\treturn vec4( value.rgb / ( M * maxRange ), M );\n}\nvec4 RGBDToLinear( in vec4 value, in float maxRange ) {\n\treturn vec4( value.rgb * ( ( maxRange / 255.0 ) / value.a ), 1.0 );\n}\nvec4 LinearToRGBD( in vec4 value, in float maxRange ) {\n\tfloat maxRGB = max( value.r, max( value.g, value.b ) );\n\tfloat D = max( maxRange / maxRGB, 1.0 );\n\tD = clamp( floor( D ) / 255.0, 0.0, 1.0 );\n\treturn vec4( value.rgb * ( D * ( 255.0 / maxRange ) ), D );\n}\nconst mat3 cLogLuvM = mat3( 0.2209, 0.3390, 0.4184, 0.1138, 0.6780, 0.7319, 0.0102, 0.1130, 0.2969 );\nvec4 LinearToLogLuv( in vec4 value ) {\n\tvec3 Xp_Y_XYZp = cLogLuvM * value.rgb;\n\tXp_Y_XYZp = max( Xp_Y_XYZp, vec3( 1e-6, 1e-6, 1e-6 ) );\n\tvec4 vResult;\n\tvResult.xy = Xp_Y_XYZp.xy / Xp_Y_XYZp.z;\n\tfloat Le = 2.0 * log2(Xp_Y_XYZp.y) + 127.0;\n\tvResult.w = fract( Le );\n\tvResult.z = ( Le - ( floor( vResult.w * 255.0 ) ) / 255.0 ) / 255.0;\n\treturn vResult;\n}\nconst mat3 cLogLuvInverseM = mat3( 6.0014, -2.7008, -1.7996, -1.3320, 3.1029, -5.7721, 0.3008, -1.0882, 5.6268 );\nvec4 LogLuvToLinear( in vec4 value ) {\n\tfloat Le = value.z * 255.0 + value.w;\n\tvec3 Xp_Y_XYZp;\n\tXp_Y_XYZp.y = exp2( ( Le - 127.0 ) / 2.0 );\n\tXp_Y_XYZp.z = Xp_Y_XYZp.y / value.y;\n\tXp_Y_XYZp.x = value.x * Xp_Y_XYZp.z;\n\tvec3 vRGB = cLogLuvInverseM * Xp_Y_XYZp.rgb;\n\treturn vec4( max( vRGB, 0.0 ), 1.0 );\n}";
10733 var envmap_fragment = "#ifdef USE_ENVMAP\n\t#ifdef ENV_WORLDPOS\n\t\tvec3 cameraToFrag;\n\t\tif ( isOrthographic ) {\n\t\t\tcameraToFrag = normalize( vec3( - viewMatrix[ 0 ][ 2 ], - viewMatrix[ 1 ][ 2 ], - viewMatrix[ 2 ][ 2 ] ) );\n\t\t} else {\n\t\t\tcameraToFrag = normalize( vWorldPosition - cameraPosition );\n\t\t}\n\t\tvec3 worldNormal = inverseTransformDirection( normal, viewMatrix );\n\t\t#ifdef ENVMAP_MODE_REFLECTION\n\t\t\tvec3 reflectVec = reflect( cameraToFrag, worldNormal );\n\t\t#else\n\t\t\tvec3 reflectVec = refract( cameraToFrag, worldNormal, refractionRatio );\n\t\t#endif\n\t#else\n\t\tvec3 reflectVec = vReflect;\n\t#endif\n\t#ifdef ENVMAP_TYPE_CUBE\n\t\tvec4 envColor = textureCube( envMap, vec3( flipEnvMap * reflectVec.x, reflectVec.yz ) );\n\t#elif defined( ENVMAP_TYPE_CUBE_UV )\n\t\tvec4 envColor = textureCubeUV( envMap, reflectVec, 0.0 );\n\t#else\n\t\tvec4 envColor = vec4( 0.0 );\n\t#endif\n\t#ifndef ENVMAP_TYPE_CUBE_UV\n\t\tenvColor = envMapTexelToLinear( envColor );\n\t#endif\n\t#ifdef ENVMAP_BLENDING_MULTIPLY\n\t\toutgoingLight = mix( outgoingLight, outgoingLight * envColor.xyz, specularStrength * reflectivity );\n\t#elif defined( ENVMAP_BLENDING_MIX )\n\t\toutgoingLight = mix( outgoingLight, envColor.xyz, specularStrength * reflectivity );\n\t#elif defined( ENVMAP_BLENDING_ADD )\n\t\toutgoingLight += envColor.xyz * specularStrength * reflectivity;\n\t#endif\n#endif";
10735 var envmap_common_pars_fragment = "#ifdef USE_ENVMAP\n\tuniform float envMapIntensity;\n\tuniform float flipEnvMap;\n\tuniform int maxMipLevel;\n\t#ifdef ENVMAP_TYPE_CUBE\n\t\tuniform samplerCube envMap;\n\t#else\n\t\tuniform sampler2D envMap;\n\t#endif\n\t\n#endif";
10737 var envmap_pars_fragment = "#ifdef USE_ENVMAP\n\tuniform float reflectivity;\n\t#if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( PHONG )\n\t\t#define ENV_WORLDPOS\n\t#endif\n\t#ifdef ENV_WORLDPOS\n\t\tvarying vec3 vWorldPosition;\n\t\tuniform float refractionRatio;\n\t#else\n\t\tvarying vec3 vReflect;\n\t#endif\n#endif";
10739 var envmap_pars_vertex = "#ifdef USE_ENVMAP\n\t#if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) ||defined( PHONG )\n\t\t#define ENV_WORLDPOS\n\t#endif\n\t#ifdef ENV_WORLDPOS\n\t\t\n\t\tvarying vec3 vWorldPosition;\n\t#else\n\t\tvarying vec3 vReflect;\n\t\tuniform float refractionRatio;\n\t#endif\n#endif";
10741 var envmap_vertex = "#ifdef USE_ENVMAP\n\t#ifdef ENV_WORLDPOS\n\t\tvWorldPosition = worldPosition.xyz;\n\t#else\n\t\tvec3 cameraToVertex;\n\t\tif ( isOrthographic ) {\n\t\t\tcameraToVertex = normalize( vec3( - viewMatrix[ 0 ][ 2 ], - viewMatrix[ 1 ][ 2 ], - viewMatrix[ 2 ][ 2 ] ) );\n\t\t} else {\n\t\t\tcameraToVertex = normalize( worldPosition.xyz - cameraPosition );\n\t\t}\n\t\tvec3 worldNormal = inverseTransformDirection( transformedNormal, viewMatrix );\n\t\t#ifdef ENVMAP_MODE_REFLECTION\n\t\t\tvReflect = reflect( cameraToVertex, worldNormal );\n\t\t#else\n\t\t\tvReflect = refract( cameraToVertex, worldNormal, refractionRatio );\n\t\t#endif\n\t#endif\n#endif";
10743 var fog_vertex = "#ifdef USE_FOG\n\tfogDepth = - mvPosition.z;\n#endif";
10745 var fog_pars_vertex = "#ifdef USE_FOG\n\tvarying float fogDepth;\n#endif";
10747 var fog_fragment = "#ifdef USE_FOG\n\t#ifdef FOG_EXP2\n\t\tfloat fogFactor = 1.0 - exp( - fogDensity * fogDensity * fogDepth * fogDepth );\n\t#else\n\t\tfloat fogFactor = smoothstep( fogNear, fogFar, fogDepth );\n\t#endif\n\tgl_FragColor.rgb = mix( gl_FragColor.rgb, fogColor, fogFactor );\n#endif";
10749 var fog_pars_fragment = "#ifdef USE_FOG\n\tuniform vec3 fogColor;\n\tvarying float fogDepth;\n\t#ifdef FOG_EXP2\n\t\tuniform float fogDensity;\n\t#else\n\t\tuniform float fogNear;\n\t\tuniform float fogFar;\n\t#endif\n#endif";
10751 var gradientmap_pars_fragment = "#ifdef USE_GRADIENTMAP\n\tuniform sampler2D gradientMap;\n#endif\nvec3 getGradientIrradiance( vec3 normal, vec3 lightDirection ) {\n\tfloat dotNL = dot( normal, lightDirection );\n\tvec2 coord = vec2( dotNL * 0.5 + 0.5, 0.0 );\n\t#ifdef USE_GRADIENTMAP\n\t\treturn texture2D( gradientMap, coord ).rgb;\n\t#else\n\t\treturn ( coord.x < 0.7 ) ? vec3( 0.7 ) : vec3( 1.0 );\n\t#endif\n}";
10753 var lightmap_fragment = "#ifdef USE_LIGHTMAP\n\tvec4 lightMapTexel= texture2D( lightMap, vUv2 );\n\treflectedLight.indirectDiffuse += PI * lightMapTexelToLinear( lightMapTexel ).rgb * lightMapIntensity;\n#endif";
10755 var lightmap_pars_fragment = "#ifdef USE_LIGHTMAP\n\tuniform sampler2D lightMap;\n\tuniform float lightMapIntensity;\n#endif";
10757 var lights_lambert_vertex = "vec3 diffuse = vec3( 1.0 );\nGeometricContext geometry;\ngeometry.position = mvPosition.xyz;\ngeometry.normal = normalize( transformedNormal );\ngeometry.viewDir = ( isOrthographic ) ? vec3( 0, 0, 1 ) : normalize( -mvPosition.xyz );\nGeometricContext backGeometry;\nbackGeometry.position = geometry.position;\nbackGeometry.normal = -geometry.normal;\nbackGeometry.viewDir = geometry.viewDir;\nvLightFront = vec3( 0.0 );\nvIndirectFront = vec3( 0.0 );\n#ifdef DOUBLE_SIDED\n\tvLightBack = vec3( 0.0 );\n\tvIndirectBack = vec3( 0.0 );\n#endif\nIncidentLight directLight;\nfloat dotNL;\nvec3 directLightColor_Diffuse;\nvIndirectFront += getAmbientLightIrradiance( ambientLightColor );\nvIndirectFront += getLightProbeIrradiance( lightProbe, geometry );\n#ifdef DOUBLE_SIDED\n\tvIndirectBack += getAmbientLightIrradiance( ambientLightColor );\n\tvIndirectBack += getLightProbeIrradiance( lightProbe, backGeometry );\n#endif\n#if NUM_POINT_LIGHTS > 0\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_POINT_LIGHTS; i ++ ) {\n\t\tgetPointDirectLightIrradiance( pointLights[ i ], geometry, directLight );\n\t\tdotNL = dot( geometry.normal, directLight.direction );\n\t\tdirectLightColor_Diffuse = PI * directLight.color;\n\t\tvLightFront += saturate( dotNL ) * directLightColor_Diffuse;\n\t\t#ifdef DOUBLE_SIDED\n\t\t\tvLightBack += saturate( -dotNL ) * directLightColor_Diffuse;\n\t\t#endif\n\t}\n\t#pragma unroll_loop_end\n#endif\n#if NUM_SPOT_LIGHTS > 0\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_SPOT_LIGHTS; i ++ ) {\n\t\tgetSpotDirectLightIrradiance( spotLights[ i ], geometry, directLight );\n\t\tdotNL = dot( geometry.normal, directLight.direction );\n\t\tdirectLightColor_Diffuse = PI * directLight.color;\n\t\tvLightFront += saturate( dotNL ) * directLightColor_Diffuse;\n\t\t#ifdef DOUBLE_SIDED\n\t\t\tvLightBack += saturate( -dotNL ) * directLightColor_Diffuse;\n\t\t#endif\n\t}\n\t#pragma unroll_loop_end\n#endif\n#if NUM_DIR_LIGHTS > 0\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_DIR_LIGHTS; i ++ ) {\n\t\tgetDirectionalDirectLightIrradiance( directionalLights[ i ], geometry, directLight );\n\t\tdotNL = dot( geometry.normal, directLight.direction );\n\t\tdirectLightColor_Diffuse = PI * directLight.color;\n\t\tvLightFront += saturate( dotNL ) * directLightColor_Diffuse;\n\t\t#ifdef DOUBLE_SIDED\n\t\t\tvLightBack += saturate( -dotNL ) * directLightColor_Diffuse;\n\t\t#endif\n\t}\n\t#pragma unroll_loop_end\n#endif\n#if NUM_HEMI_LIGHTS > 0\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_HEMI_LIGHTS; i ++ ) {\n\t\tvIndirectFront += getHemisphereLightIrradiance( hemisphereLights[ i ], geometry );\n\t\t#ifdef DOUBLE_SIDED\n\t\t\tvIndirectBack += getHemisphereLightIrradiance( hemisphereLights[ i ], backGeometry );\n\t\t#endif\n\t}\n\t#pragma unroll_loop_end\n#endif";
10759 var lights_pars_begin = "uniform bool receiveShadow;\nuniform vec3 ambientLightColor;\nuniform vec3 lightProbe[ 9 ];\nvec3 shGetIrradianceAt( in vec3 normal, in vec3 shCoefficients[ 9 ] ) {\n\tfloat x = normal.x, y = normal.y, z = normal.z;\n\tvec3 result = shCoefficients[ 0 ] * 0.886227;\n\tresult += shCoefficients[ 1 ] * 2.0 * 0.511664 * y;\n\tresult += shCoefficients[ 2 ] * 2.0 * 0.511664 * z;\n\tresult += shCoefficients[ 3 ] * 2.0 * 0.511664 * x;\n\tresult += shCoefficients[ 4 ] * 2.0 * 0.429043 * x * y;\n\tresult += shCoefficients[ 5 ] * 2.0 * 0.429043 * y * z;\n\tresult += shCoefficients[ 6 ] * ( 0.743125 * z * z - 0.247708 );\n\tresult += shCoefficients[ 7 ] * 2.0 * 0.429043 * x * z;\n\tresult += shCoefficients[ 8 ] * 0.429043 * ( x * x - y * y );\n\treturn result;\n}\nvec3 getLightProbeIrradiance( const in vec3 lightProbe[ 9 ], const in GeometricContext geometry ) {\n\tvec3 worldNormal = inverseTransformDirection( geometry.normal, viewMatrix );\n\tvec3 irradiance = shGetIrradianceAt( worldNormal, lightProbe );\n\treturn irradiance;\n}\nvec3 getAmbientLightIrradiance( const in vec3 ambientLightColor ) {\n\tvec3 irradiance = ambientLightColor;\n\t#ifndef PHYSICALLY_CORRECT_LIGHTS\n\t\tirradiance *= PI;\n\t#endif\n\treturn irradiance;\n}\n#if NUM_DIR_LIGHTS > 0\n\tstruct DirectionalLight {\n\t\tvec3 direction;\n\t\tvec3 color;\n\t};\n\tuniform DirectionalLight directionalLights[ NUM_DIR_LIGHTS ];\n\tvoid getDirectionalDirectLightIrradiance( const in DirectionalLight directionalLight, const in GeometricContext geometry, out IncidentLight directLight ) {\n\t\tdirectLight.color = directionalLight.color;\n\t\tdirectLight.direction = directionalLight.direction;\n\t\tdirectLight.visible = true;\n\t}\n#endif\n#if NUM_POINT_LIGHTS > 0\n\tstruct PointLight {\n\t\tvec3 position;\n\t\tvec3 color;\n\t\tfloat distance;\n\t\tfloat decay;\n\t};\n\tuniform PointLight pointLights[ NUM_POINT_LIGHTS ];\n\tvoid getPointDirectLightIrradiance( const in PointLight pointLight, const in GeometricContext geometry, out IncidentLight directLight ) {\n\t\tvec3 lVector = pointLight.position - geometry.position;\n\t\tdirectLight.direction = normalize( lVector );\n\t\tfloat lightDistance = length( lVector );\n\t\tdirectLight.color = pointLight.color;\n\t\tdirectLight.color *= punctualLightIntensityToIrradianceFactor( lightDistance, pointLight.distance, pointLight.decay );\n\t\tdirectLight.visible = ( directLight.color != vec3( 0.0 ) );\n\t}\n#endif\n#if NUM_SPOT_LIGHTS > 0\n\tstruct SpotLight {\n\t\tvec3 position;\n\t\tvec3 direction;\n\t\tvec3 color;\n\t\tfloat distance;\n\t\tfloat decay;\n\t\tfloat coneCos;\n\t\tfloat penumbraCos;\n\t};\n\tuniform SpotLight spotLights[ NUM_SPOT_LIGHTS ];\n\tvoid getSpotDirectLightIrradiance( const in SpotLight spotLight, const in GeometricContext geometry, out IncidentLight directLight ) {\n\t\tvec3 lVector = spotLight.position - geometry.position;\n\t\tdirectLight.direction = normalize( lVector );\n\t\tfloat lightDistance = length( lVector );\n\t\tfloat angleCos = dot( directLight.direction, spotLight.direction );\n\t\tif ( angleCos > spotLight.coneCos ) {\n\t\t\tfloat spotEffect = smoothstep( spotLight.coneCos, spotLight.penumbraCos, angleCos );\n\t\t\tdirectLight.color = spotLight.color;\n\t\t\tdirectLight.color *= spotEffect * punctualLightIntensityToIrradianceFactor( lightDistance, spotLight.distance, spotLight.decay );\n\t\t\tdirectLight.visible = true;\n\t\t} else {\n\t\t\tdirectLight.color = vec3( 0.0 );\n\t\t\tdirectLight.visible = false;\n\t\t}\n\t}\n#endif\n#if NUM_RECT_AREA_LIGHTS > 0\n\tstruct RectAreaLight {\n\t\tvec3 color;\n\t\tvec3 position;\n\t\tvec3 halfWidth;\n\t\tvec3 halfHeight;\n\t};\n\tuniform sampler2D ltc_1;\tuniform sampler2D ltc_2;\n\tuniform RectAreaLight rectAreaLights[ NUM_RECT_AREA_LIGHTS ];\n#endif\n#if NUM_HEMI_LIGHTS > 0\n\tstruct HemisphereLight {\n\t\tvec3 direction;\n\t\tvec3 skyColor;\n\t\tvec3 groundColor;\n\t};\n\tuniform HemisphereLight hemisphereLights[ NUM_HEMI_LIGHTS ];\n\tvec3 getHemisphereLightIrradiance( const in HemisphereLight hemiLight, const in GeometricContext geometry ) {\n\t\tfloat dotNL = dot( geometry.normal, hemiLight.direction );\n\t\tfloat hemiDiffuseWeight = 0.5 * dotNL + 0.5;\n\t\tvec3 irradiance = mix( hemiLight.groundColor, hemiLight.skyColor, hemiDiffuseWeight );\n\t\t#ifndef PHYSICALLY_CORRECT_LIGHTS\n\t\t\tirradiance *= PI;\n\t\t#endif\n\t\treturn irradiance;\n\t}\n#endif";
10761 var envmap_physical_pars_fragment = "#if defined( USE_ENVMAP )\n\t#ifdef ENVMAP_MODE_REFRACTION\n\t\tuniform float refractionRatio;\n\t#endif\n\tvec3 getLightProbeIndirectIrradiance( const in GeometricContext geometry, const in int maxMIPLevel ) {\n\t\tvec3 worldNormal = inverseTransformDirection( geometry.normal, viewMatrix );\n\t\t#ifdef ENVMAP_TYPE_CUBE\n\t\t\tvec3 queryVec = vec3( flipEnvMap * worldNormal.x, worldNormal.yz );\n\t\t\t#ifdef TEXTURE_LOD_EXT\n\t\t\t\tvec4 envMapColor = textureCubeLodEXT( envMap, queryVec, float( maxMIPLevel ) );\n\t\t\t#else\n\t\t\t\tvec4 envMapColor = textureCube( envMap, queryVec, float( maxMIPLevel ) );\n\t\t\t#endif\n\t\t\tenvMapColor.rgb = envMapTexelToLinear( envMapColor ).rgb;\n\t\t#elif defined( ENVMAP_TYPE_CUBE_UV )\n\t\t\tvec4 envMapColor = textureCubeUV( envMap, worldNormal, 1.0 );\n\t\t#else\n\t\t\tvec4 envMapColor = vec4( 0.0 );\n\t\t#endif\n\t\treturn PI * envMapColor.rgb * envMapIntensity;\n\t}\n\tfloat getSpecularMIPLevel( const in float roughness, const in int maxMIPLevel ) {\n\t\tfloat maxMIPLevelScalar = float( maxMIPLevel );\n\t\tfloat sigma = PI * roughness * roughness / ( 1.0 + roughness );\n\t\tfloat desiredMIPLevel = maxMIPLevelScalar + log2( sigma );\n\t\treturn clamp( desiredMIPLevel, 0.0, maxMIPLevelScalar );\n\t}\n\tvec3 getLightProbeIndirectRadiance( const in vec3 viewDir, const in vec3 normal, const in float roughness, const in int maxMIPLevel ) {\n\t\t#ifdef ENVMAP_MODE_REFLECTION\n\t\t\tvec3 reflectVec = reflect( -viewDir, normal );\n\t\t\treflectVec = normalize( mix( reflectVec, normal, roughness * roughness) );\n\t\t#else\n\t\t\tvec3 reflectVec = refract( -viewDir, normal, refractionRatio );\n\t\t#endif\n\t\treflectVec = inverseTransformDirection( reflectVec, viewMatrix );\n\t\tfloat specularMIPLevel = getSpecularMIPLevel( roughness, maxMIPLevel );\n\t\t#ifdef ENVMAP_TYPE_CUBE\n\t\t\tvec3 queryReflectVec = vec3( flipEnvMap * reflectVec.x, reflectVec.yz );\n\t\t\t#ifdef TEXTURE_LOD_EXT\n\t\t\t\tvec4 envMapColor = textureCubeLodEXT( envMap, queryReflectVec, specularMIPLevel );\n\t\t\t#else\n\t\t\t\tvec4 envMapColor = textureCube( envMap, queryReflectVec, specularMIPLevel );\n\t\t\t#endif\n\t\t\tenvMapColor.rgb = envMapTexelToLinear( envMapColor ).rgb;\n\t\t#elif defined( ENVMAP_TYPE_CUBE_UV )\n\t\t\tvec4 envMapColor = textureCubeUV( envMap, reflectVec, roughness );\n\t\t#endif\n\t\treturn envMapColor.rgb * envMapIntensity;\n\t}\n#endif";
10763 var lights_toon_fragment = "ToonMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb;";
10765 var lights_toon_pars_fragment = "varying vec3 vViewPosition;\n#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n#endif\nstruct ToonMaterial {\n\tvec3 diffuseColor;\n};\nvoid RE_Direct_Toon( const in IncidentLight directLight, const in GeometricContext geometry, const in ToonMaterial material, inout ReflectedLight reflectedLight ) {\n\tvec3 irradiance = getGradientIrradiance( geometry.normal, directLight.direction ) * directLight.color;\n\t#ifndef PHYSICALLY_CORRECT_LIGHTS\n\t\tirradiance *= PI;\n\t#endif\n\treflectedLight.directDiffuse += irradiance * BRDF_Diffuse_Lambert( material.diffuseColor );\n}\nvoid RE_IndirectDiffuse_Toon( const in vec3 irradiance, const in GeometricContext geometry, const in ToonMaterial material, inout ReflectedLight reflectedLight ) {\n\treflectedLight.indirectDiffuse += irradiance * BRDF_Diffuse_Lambert( material.diffuseColor );\n}\n#define RE_Direct\t\t\t\tRE_Direct_Toon\n#define RE_IndirectDiffuse\t\tRE_IndirectDiffuse_Toon\n#define Material_LightProbeLOD( material )\t(0)";
10767 var lights_phong_fragment = "BlinnPhongMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb;\nmaterial.specularColor = specular;\nmaterial.specularShininess = shininess;\nmaterial.specularStrength = specularStrength;";
10769 var lights_phong_pars_fragment = "varying vec3 vViewPosition;\n#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n#endif\nstruct BlinnPhongMaterial {\n\tvec3 diffuseColor;\n\tvec3 specularColor;\n\tfloat specularShininess;\n\tfloat specularStrength;\n};\nvoid RE_Direct_BlinnPhong( const in IncidentLight directLight, const in GeometricContext geometry, const in BlinnPhongMaterial material, inout ReflectedLight reflectedLight ) {\n\tfloat dotNL = saturate( dot( geometry.normal, directLight.direction ) );\n\tvec3 irradiance = dotNL * directLight.color;\n\t#ifndef PHYSICALLY_CORRECT_LIGHTS\n\t\tirradiance *= PI;\n\t#endif\n\treflectedLight.directDiffuse += irradiance * BRDF_Diffuse_Lambert( material.diffuseColor );\n\treflectedLight.directSpecular += irradiance * BRDF_Specular_BlinnPhong( directLight, geometry, material.specularColor, material.specularShininess ) * material.specularStrength;\n}\nvoid RE_IndirectDiffuse_BlinnPhong( const in vec3 irradiance, const in GeometricContext geometry, const in BlinnPhongMaterial material, inout ReflectedLight reflectedLight ) {\n\treflectedLight.indirectDiffuse += irradiance * BRDF_Diffuse_Lambert( material.diffuseColor );\n}\n#define RE_Direct\t\t\t\tRE_Direct_BlinnPhong\n#define RE_IndirectDiffuse\t\tRE_IndirectDiffuse_BlinnPhong\n#define Material_LightProbeLOD( material )\t(0)";
10771 var lights_physical_fragment = "PhysicalMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb * ( 1.0 - metalnessFactor );\nvec3 dxy = max( abs( dFdx( geometryNormal ) ), abs( dFdy( geometryNormal ) ) );\nfloat geometryRoughness = max( max( dxy.x, dxy.y ), dxy.z );\nmaterial.specularRoughness = max( roughnessFactor, 0.0525 );material.specularRoughness += geometryRoughness;\nmaterial.specularRoughness = min( material.specularRoughness, 1.0 );\n#ifdef REFLECTIVITY\n\tmaterial.specularColor = mix( vec3( MAXIMUM_SPECULAR_COEFFICIENT * pow2( reflectivity ) ), diffuseColor.rgb, metalnessFactor );\n#else\n\tmaterial.specularColor = mix( vec3( DEFAULT_SPECULAR_COEFFICIENT ), diffuseColor.rgb, metalnessFactor );\n#endif\n#ifdef CLEARCOAT\n\tmaterial.clearcoat = clearcoat;\n\tmaterial.clearcoatRoughness = clearcoatRoughness;\n\t#ifdef USE_CLEARCOATMAP\n\t\tmaterial.clearcoat *= texture2D( clearcoatMap, vUv ).x;\n\t#endif\n\t#ifdef USE_CLEARCOAT_ROUGHNESSMAP\n\t\tmaterial.clearcoatRoughness *= texture2D( clearcoatRoughnessMap, vUv ).y;\n\t#endif\n\tmaterial.clearcoat = saturate( material.clearcoat );\tmaterial.clearcoatRoughness = max( material.clearcoatRoughness, 0.0525 );\n\tmaterial.clearcoatRoughness += geometryRoughness;\n\tmaterial.clearcoatRoughness = min( material.clearcoatRoughness, 1.0 );\n#endif\n#ifdef USE_SHEEN\n\tmaterial.sheenColor = sheen;\n#endif";
10773 var lights_physical_pars_fragment = "struct PhysicalMaterial {\n\tvec3 diffuseColor;\n\tfloat specularRoughness;\n\tvec3 specularColor;\n#ifdef CLEARCOAT\n\tfloat clearcoat;\n\tfloat clearcoatRoughness;\n#endif\n#ifdef USE_SHEEN\n\tvec3 sheenColor;\n#endif\n};\n#define MAXIMUM_SPECULAR_COEFFICIENT 0.16\n#define DEFAULT_SPECULAR_COEFFICIENT 0.04\nfloat clearcoatDHRApprox( const in float roughness, const in float dotNL ) {\n\treturn DEFAULT_SPECULAR_COEFFICIENT + ( 1.0 - DEFAULT_SPECULAR_COEFFICIENT ) * ( pow( 1.0 - dotNL, 5.0 ) * pow( 1.0 - roughness, 2.0 ) );\n}\n#if NUM_RECT_AREA_LIGHTS > 0\n\tvoid RE_Direct_RectArea_Physical( const in RectAreaLight rectAreaLight, const in GeometricContext geometry, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) {\n\t\tvec3 normal = geometry.normal;\n\t\tvec3 viewDir = geometry.viewDir;\n\t\tvec3 position = geometry.position;\n\t\tvec3 lightPos = rectAreaLight.position;\n\t\tvec3 halfWidth = rectAreaLight.halfWidth;\n\t\tvec3 halfHeight = rectAreaLight.halfHeight;\n\t\tvec3 lightColor = rectAreaLight.color;\n\t\tfloat roughness = material.specularRoughness;\n\t\tvec3 rectCoords[ 4 ];\n\t\trectCoords[ 0 ] = lightPos + halfWidth - halfHeight;\t\trectCoords[ 1 ] = lightPos - halfWidth - halfHeight;\n\t\trectCoords[ 2 ] = lightPos - halfWidth + halfHeight;\n\t\trectCoords[ 3 ] = lightPos + halfWidth + halfHeight;\n\t\tvec2 uv = LTC_Uv( normal, viewDir, roughness );\n\t\tvec4 t1 = texture2D( ltc_1, uv );\n\t\tvec4 t2 = texture2D( ltc_2, uv );\n\t\tmat3 mInv = mat3(\n\t\t\tvec3( t1.x, 0, t1.y ),\n\t\t\tvec3( 0, 1, 0 ),\n\t\t\tvec3( t1.z, 0, t1.w )\n\t\t);\n\t\tvec3 fresnel = ( material.specularColor * t2.x + ( vec3( 1.0 ) - material.specularColor ) * t2.y );\n\t\treflectedLight.directSpecular += lightColor * fresnel * LTC_Evaluate( normal, viewDir, position, mInv, rectCoords );\n\t\treflectedLight.directDiffuse += lightColor * material.diffuseColor * LTC_Evaluate( normal, viewDir, position, mat3( 1.0 ), rectCoords );\n\t}\n#endif\nvoid RE_Direct_Physical( const in IncidentLight directLight, const in GeometricContext geometry, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) {\n\tfloat dotNL = saturate( dot( geometry.normal, directLight.direction ) );\n\tvec3 irradiance = dotNL * directLight.color;\n\t#ifndef PHYSICALLY_CORRECT_LIGHTS\n\t\tirradiance *= PI;\n\t#endif\n\t#ifdef CLEARCOAT\n\t\tfloat ccDotNL = saturate( dot( geometry.clearcoatNormal, directLight.direction ) );\n\t\tvec3 ccIrradiance = ccDotNL * directLight.color;\n\t\t#ifndef PHYSICALLY_CORRECT_LIGHTS\n\t\t\tccIrradiance *= PI;\n\t\t#endif\n\t\tfloat clearcoatDHR = material.clearcoat * clearcoatDHRApprox( material.clearcoatRoughness, ccDotNL );\n\t\treflectedLight.directSpecular += ccIrradiance * material.clearcoat * BRDF_Specular_GGX( directLight, geometry.viewDir, geometry.clearcoatNormal, vec3( DEFAULT_SPECULAR_COEFFICIENT ), material.clearcoatRoughness );\n\t#else\n\t\tfloat clearcoatDHR = 0.0;\n\t#endif\n\t#ifdef USE_SHEEN\n\t\treflectedLight.directSpecular += ( 1.0 - clearcoatDHR ) * irradiance * BRDF_Specular_Sheen(\n\t\t\tmaterial.specularRoughness,\n\t\t\tdirectLight.direction,\n\t\t\tgeometry,\n\t\t\tmaterial.sheenColor\n\t\t);\n\t#else\n\t\treflectedLight.directSpecular += ( 1.0 - clearcoatDHR ) * irradiance * BRDF_Specular_GGX( directLight, geometry.viewDir, geometry.normal, material.specularColor, material.specularRoughness);\n\t#endif\n\treflectedLight.directDiffuse += ( 1.0 - clearcoatDHR ) * irradiance * BRDF_Diffuse_Lambert( material.diffuseColor );\n}\nvoid RE_IndirectDiffuse_Physical( const in vec3 irradiance, const in GeometricContext geometry, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) {\n\treflectedLight.indirectDiffuse += irradiance * BRDF_Diffuse_Lambert( material.diffuseColor );\n}\nvoid 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) {\n\t#ifdef CLEARCOAT\n\t\tfloat ccDotNV = saturate( dot( geometry.clearcoatNormal, geometry.viewDir ) );\n\t\treflectedLight.indirectSpecular += clearcoatRadiance * material.clearcoat * BRDF_Specular_GGX_Environment( geometry.viewDir, geometry.clearcoatNormal, vec3( DEFAULT_SPECULAR_COEFFICIENT ), material.clearcoatRoughness );\n\t\tfloat ccDotNL = ccDotNV;\n\t\tfloat clearcoatDHR = material.clearcoat * clearcoatDHRApprox( material.clearcoatRoughness, ccDotNL );\n\t#else\n\t\tfloat clearcoatDHR = 0.0;\n\t#endif\n\tfloat clearcoatInv = 1.0 - clearcoatDHR;\n\tvec3 singleScattering = vec3( 0.0 );\n\tvec3 multiScattering = vec3( 0.0 );\n\tvec3 cosineWeightedIrradiance = irradiance * RECIPROCAL_PI;\n\tBRDF_Specular_Multiscattering_Environment( geometry, material.specularColor, material.specularRoughness, singleScattering, multiScattering );\n\tvec3 diffuse = material.diffuseColor * ( 1.0 - ( singleScattering + multiScattering ) );\n\treflectedLight.indirectSpecular += clearcoatInv * radiance * singleScattering;\n\treflectedLight.indirectSpecular += multiScattering * cosineWeightedIrradiance;\n\treflectedLight.indirectDiffuse += diffuse * cosineWeightedIrradiance;\n}\n#define RE_Direct\t\t\t\tRE_Direct_Physical\n#define RE_Direct_RectArea\t\tRE_Direct_RectArea_Physical\n#define RE_IndirectDiffuse\t\tRE_IndirectDiffuse_Physical\n#define RE_IndirectSpecular\t\tRE_IndirectSpecular_Physical\nfloat computeSpecularOcclusion( const in float dotNV, const in float ambientOcclusion, const in float roughness ) {\n\treturn saturate( pow( dotNV + ambientOcclusion, exp2( - 16.0 * roughness - 1.0 ) ) - 1.0 + ambientOcclusion );\n}";
10775 var lights_fragment_begin = "\nGeometricContext geometry;\ngeometry.position = - vViewPosition;\ngeometry.normal = normal;\ngeometry.viewDir = ( isOrthographic ) ? vec3( 0, 0, 1 ) : normalize( vViewPosition );\n#ifdef CLEARCOAT\n\tgeometry.clearcoatNormal = clearcoatNormal;\n#endif\nIncidentLight directLight;\n#if ( NUM_POINT_LIGHTS > 0 ) && defined( RE_Direct )\n\tPointLight pointLight;\n\t#if defined( USE_SHADOWMAP ) && NUM_POINT_LIGHT_SHADOWS > 0\n\tPointLightShadow pointLightShadow;\n\t#endif\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_POINT_LIGHTS; i ++ ) {\n\t\tpointLight = pointLights[ i ];\n\t\tgetPointDirectLightIrradiance( pointLight, geometry, directLight );\n\t\t#if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_POINT_LIGHT_SHADOWS )\n\t\tpointLightShadow = pointLightShadows[ i ];\n\t\tdirectLight.color *= all( bvec2( directLight.visible, receiveShadow ) ) ? getPointShadow( pointShadowMap[ i ], pointLightShadow.shadowMapSize, pointLightShadow.shadowBias, pointLightShadow.shadowRadius, vPointShadowCoord[ i ], pointLightShadow.shadowCameraNear, pointLightShadow.shadowCameraFar ) : 1.0;\n\t\t#endif\n\t\tRE_Direct( directLight, geometry, material, reflectedLight );\n\t}\n\t#pragma unroll_loop_end\n#endif\n#if ( NUM_SPOT_LIGHTS > 0 ) && defined( RE_Direct )\n\tSpotLight spotLight;\n\t#if defined( USE_SHADOWMAP ) && NUM_SPOT_LIGHT_SHADOWS > 0\n\tSpotLightShadow spotLightShadow;\n\t#endif\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_SPOT_LIGHTS; i ++ ) {\n\t\tspotLight = spotLights[ i ];\n\t\tgetSpotDirectLightIrradiance( spotLight, geometry, directLight );\n\t\t#if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS )\n\t\tspotLightShadow = spotLightShadows[ i ];\n\t\tdirectLight.color *= all( bvec2( directLight.visible, receiveShadow ) ) ? getShadow( spotShadowMap[ i ], spotLightShadow.shadowMapSize, spotLightShadow.shadowBias, spotLightShadow.shadowRadius, vSpotShadowCoord[ i ] ) : 1.0;\n\t\t#endif\n\t\tRE_Direct( directLight, geometry, material, reflectedLight );\n\t}\n\t#pragma unroll_loop_end\n#endif\n#if ( NUM_DIR_LIGHTS > 0 ) && defined( RE_Direct )\n\tDirectionalLight directionalLight;\n\t#if defined( USE_SHADOWMAP ) && NUM_DIR_LIGHT_SHADOWS > 0\n\tDirectionalLightShadow directionalLightShadow;\n\t#endif\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_DIR_LIGHTS; i ++ ) {\n\t\tdirectionalLight = directionalLights[ i ];\n\t\tgetDirectionalDirectLightIrradiance( directionalLight, geometry, directLight );\n\t\t#if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_DIR_LIGHT_SHADOWS )\n\t\tdirectionalLightShadow = directionalLightShadows[ i ];\n\t\tdirectLight.color *= all( bvec2( directLight.visible, receiveShadow ) ) ? getShadow( directionalShadowMap[ i ], directionalLightShadow.shadowMapSize, directionalLightShadow.shadowBias, directionalLightShadow.shadowRadius, vDirectionalShadowCoord[ i ] ) : 1.0;\n\t\t#endif\n\t\tRE_Direct( directLight, geometry, material, reflectedLight );\n\t}\n\t#pragma unroll_loop_end\n#endif\n#if ( NUM_RECT_AREA_LIGHTS > 0 ) && defined( RE_Direct_RectArea )\n\tRectAreaLight rectAreaLight;\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_RECT_AREA_LIGHTS; i ++ ) {\n\t\trectAreaLight = rectAreaLights[ i ];\n\t\tRE_Direct_RectArea( rectAreaLight, geometry, material, reflectedLight );\n\t}\n\t#pragma unroll_loop_end\n#endif\n#if defined( RE_IndirectDiffuse )\n\tvec3 iblIrradiance = vec3( 0.0 );\n\tvec3 irradiance = getAmbientLightIrradiance( ambientLightColor );\n\tirradiance += getLightProbeIrradiance( lightProbe, geometry );\n\t#if ( NUM_HEMI_LIGHTS > 0 )\n\t\t#pragma unroll_loop_start\n\t\tfor ( int i = 0; i < NUM_HEMI_LIGHTS; i ++ ) {\n\t\t\tirradiance += getHemisphereLightIrradiance( hemisphereLights[ i ], geometry );\n\t\t}\n\t\t#pragma unroll_loop_end\n\t#endif\n#endif\n#if defined( RE_IndirectSpecular )\n\tvec3 radiance = vec3( 0.0 );\n\tvec3 clearcoatRadiance = vec3( 0.0 );\n#endif";
10777 var lights_fragment_maps = "#if defined( RE_IndirectDiffuse )\n\t#ifdef USE_LIGHTMAP\n\t\tvec4 lightMapTexel= texture2D( lightMap, vUv2 );\n\t\tvec3 lightMapIrradiance = lightMapTexelToLinear( lightMapTexel ).rgb * lightMapIntensity;\n\t\t#ifndef PHYSICALLY_CORRECT_LIGHTS\n\t\t\tlightMapIrradiance *= PI;\n\t\t#endif\n\t\tirradiance += lightMapIrradiance;\n\t#endif\n\t#if defined( USE_ENVMAP ) && defined( STANDARD ) && defined( ENVMAP_TYPE_CUBE_UV )\n\t\tiblIrradiance += getLightProbeIndirectIrradiance( geometry, maxMipLevel );\n\t#endif\n#endif\n#if defined( USE_ENVMAP ) && defined( RE_IndirectSpecular )\n\tradiance += getLightProbeIndirectRadiance( geometry.viewDir, geometry.normal, material.specularRoughness, maxMipLevel );\n\t#ifdef CLEARCOAT\n\t\tclearcoatRadiance += getLightProbeIndirectRadiance( geometry.viewDir, geometry.clearcoatNormal, material.clearcoatRoughness, maxMipLevel );\n\t#endif\n#endif";
10779 var lights_fragment_end = "#if defined( RE_IndirectDiffuse )\n\tRE_IndirectDiffuse( irradiance, geometry, material, reflectedLight );\n#endif\n#if defined( RE_IndirectSpecular )\n\tRE_IndirectSpecular( radiance, iblIrradiance, clearcoatRadiance, geometry, material, reflectedLight );\n#endif";
10781 var logdepthbuf_fragment = "#if defined( USE_LOGDEPTHBUF ) && defined( USE_LOGDEPTHBUF_EXT )\n\tgl_FragDepthEXT = vIsPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;\n#endif";
10783 var logdepthbuf_pars_fragment = "#if defined( USE_LOGDEPTHBUF ) && defined( USE_LOGDEPTHBUF_EXT )\n\tuniform float logDepthBufFC;\n\tvarying float vFragDepth;\n\tvarying float vIsPerspective;\n#endif";
10785 var logdepthbuf_pars_vertex = "#ifdef USE_LOGDEPTHBUF\n\t#ifdef USE_LOGDEPTHBUF_EXT\n\t\tvarying float vFragDepth;\n\t\tvarying float vIsPerspective;\n\t#else\n\t\tuniform float logDepthBufFC;\n\t#endif\n#endif";
10787 var logdepthbuf_vertex = "#ifdef USE_LOGDEPTHBUF\n\t#ifdef USE_LOGDEPTHBUF_EXT\n\t\tvFragDepth = 1.0 + gl_Position.w;\n\t\tvIsPerspective = float( isPerspectiveMatrix( projectionMatrix ) );\n\t#else\n\t\tif ( isPerspectiveMatrix( projectionMatrix ) ) {\n\t\t\tgl_Position.z = log2( max( EPSILON, gl_Position.w + 1.0 ) ) * logDepthBufFC - 1.0;\n\t\t\tgl_Position.z *= gl_Position.w;\n\t\t}\n\t#endif\n#endif";
10789 var map_fragment = "#ifdef USE_MAP\n\tvec4 texelColor = texture2D( map, vUv );\n\ttexelColor = mapTexelToLinear( texelColor );\n\tdiffuseColor *= texelColor;\n#endif";
10791 var map_pars_fragment = "#ifdef USE_MAP\n\tuniform sampler2D map;\n#endif";
10793 var map_particle_fragment = "#if defined( USE_MAP ) || defined( USE_ALPHAMAP )\n\tvec2 uv = ( uvTransform * vec3( gl_PointCoord.x, 1.0 - gl_PointCoord.y, 1 ) ).xy;\n#endif\n#ifdef USE_MAP\n\tvec4 mapTexel = texture2D( map, uv );\n\tdiffuseColor *= mapTexelToLinear( mapTexel );\n#endif\n#ifdef USE_ALPHAMAP\n\tdiffuseColor.a *= texture2D( alphaMap, uv ).g;\n#endif";
10795 var map_particle_pars_fragment = "#if defined( USE_MAP ) || defined( USE_ALPHAMAP )\n\tuniform mat3 uvTransform;\n#endif\n#ifdef USE_MAP\n\tuniform sampler2D map;\n#endif\n#ifdef USE_ALPHAMAP\n\tuniform sampler2D alphaMap;\n#endif";
10797 var metalnessmap_fragment = "float metalnessFactor = metalness;\n#ifdef USE_METALNESSMAP\n\tvec4 texelMetalness = texture2D( metalnessMap, vUv );\n\tmetalnessFactor *= texelMetalness.b;\n#endif";
10799 var metalnessmap_pars_fragment = "#ifdef USE_METALNESSMAP\n\tuniform sampler2D metalnessMap;\n#endif";
10801 var morphnormal_vertex = "#ifdef USE_MORPHNORMALS\n\tobjectNormal *= morphTargetBaseInfluence;\n\tobjectNormal += morphNormal0 * morphTargetInfluences[ 0 ];\n\tobjectNormal += morphNormal1 * morphTargetInfluences[ 1 ];\n\tobjectNormal += morphNormal2 * morphTargetInfluences[ 2 ];\n\tobjectNormal += morphNormal3 * morphTargetInfluences[ 3 ];\n#endif";
10803 var morphtarget_pars_vertex = "#ifdef USE_MORPHTARGETS\n\tuniform float morphTargetBaseInfluence;\n\t#ifndef USE_MORPHNORMALS\n\t\tuniform float morphTargetInfluences[ 8 ];\n\t#else\n\t\tuniform float morphTargetInfluences[ 4 ];\n\t#endif\n#endif";
10805 var morphtarget_vertex = "#ifdef USE_MORPHTARGETS\n\ttransformed *= morphTargetBaseInfluence;\n\ttransformed += morphTarget0 * morphTargetInfluences[ 0 ];\n\ttransformed += morphTarget1 * morphTargetInfluences[ 1 ];\n\ttransformed += morphTarget2 * morphTargetInfluences[ 2 ];\n\ttransformed += morphTarget3 * morphTargetInfluences[ 3 ];\n\t#ifndef USE_MORPHNORMALS\n\t\ttransformed += morphTarget4 * morphTargetInfluences[ 4 ];\n\t\ttransformed += morphTarget5 * morphTargetInfluences[ 5 ];\n\t\ttransformed += morphTarget6 * morphTargetInfluences[ 6 ];\n\t\ttransformed += morphTarget7 * morphTargetInfluences[ 7 ];\n\t#endif\n#endif";
10807 var normal_fragment_begin = "#ifdef FLAT_SHADED\n\tvec3 fdx = vec3( dFdx( vViewPosition.x ), dFdx( vViewPosition.y ), dFdx( vViewPosition.z ) );\n\tvec3 fdy = vec3( dFdy( vViewPosition.x ), dFdy( vViewPosition.y ), dFdy( vViewPosition.z ) );\n\tvec3 normal = normalize( cross( fdx, fdy ) );\n#else\n\tvec3 normal = normalize( vNormal );\n\t#ifdef DOUBLE_SIDED\n\t\tnormal = normal * ( float( gl_FrontFacing ) * 2.0 - 1.0 );\n\t#endif\n\t#ifdef USE_TANGENT\n\t\tvec3 tangent = normalize( vTangent );\n\t\tvec3 bitangent = normalize( vBitangent );\n\t\t#ifdef DOUBLE_SIDED\n\t\t\ttangent = tangent * ( float( gl_FrontFacing ) * 2.0 - 1.0 );\n\t\t\tbitangent = bitangent * ( float( gl_FrontFacing ) * 2.0 - 1.0 );\n\t\t#endif\n\t\t#if defined( TANGENTSPACE_NORMALMAP ) || defined( USE_CLEARCOAT_NORMALMAP )\n\t\t\tmat3 vTBN = mat3( tangent, bitangent, normal );\n\t\t#endif\n\t#endif\n#endif\nvec3 geometryNormal = normal;";
10809 var normal_fragment_maps = "#ifdef OBJECTSPACE_NORMALMAP\n\tnormal = texture2D( normalMap, vUv ).xyz * 2.0 - 1.0;\n\t#ifdef FLIP_SIDED\n\t\tnormal = - normal;\n\t#endif\n\t#ifdef DOUBLE_SIDED\n\t\tnormal = normal * ( float( gl_FrontFacing ) * 2.0 - 1.0 );\n\t#endif\n\tnormal = normalize( normalMatrix * normal );\n#elif defined( TANGENTSPACE_NORMALMAP )\n\tvec3 mapN = texture2D( normalMap, vUv ).xyz * 2.0 - 1.0;\n\tmapN.xy *= normalScale;\n\t#ifdef USE_TANGENT\n\t\tnormal = normalize( vTBN * mapN );\n\t#else\n\t\tnormal = perturbNormal2Arb( -vViewPosition, normal, mapN );\n\t#endif\n#elif defined( USE_BUMPMAP )\n\tnormal = perturbNormalArb( -vViewPosition, normal, dHdxy_fwd() );\n#endif";
10811 var normalmap_pars_fragment = "#ifdef USE_NORMALMAP\n\tuniform sampler2D normalMap;\n\tuniform vec2 normalScale;\n#endif\n#ifdef OBJECTSPACE_NORMALMAP\n\tuniform mat3 normalMatrix;\n#endif\n#if ! defined ( USE_TANGENT ) && ( defined ( TANGENTSPACE_NORMALMAP ) || defined ( USE_CLEARCOAT_NORMALMAP ) )\n\tvec3 perturbNormal2Arb( vec3 eye_pos, vec3 surf_norm, vec3 mapN ) {\n\t\tvec3 q0 = vec3( dFdx( eye_pos.x ), dFdx( eye_pos.y ), dFdx( eye_pos.z ) );\n\t\tvec3 q1 = vec3( dFdy( eye_pos.x ), dFdy( eye_pos.y ), dFdy( eye_pos.z ) );\n\t\tvec2 st0 = dFdx( vUv.st );\n\t\tvec2 st1 = dFdy( vUv.st );\n\t\tfloat scale = sign( st1.t * st0.s - st0.t * st1.s );\n\t\tvec3 S = normalize( ( q0 * st1.t - q1 * st0.t ) * scale );\n\t\tvec3 T = normalize( ( - q0 * st1.s + q1 * st0.s ) * scale );\n\t\tvec3 N = normalize( surf_norm );\n\t\tmat3 tsn = mat3( S, T, N );\n\t\tmapN.xy *= ( float( gl_FrontFacing ) * 2.0 - 1.0 );\n\t\treturn normalize( tsn * mapN );\n\t}\n#endif";
10813 var clearcoat_normal_fragment_begin = "#ifdef CLEARCOAT\n\tvec3 clearcoatNormal = geometryNormal;\n#endif";
10815 var clearcoat_normal_fragment_maps = "#ifdef USE_CLEARCOAT_NORMALMAP\n\tvec3 clearcoatMapN = texture2D( clearcoatNormalMap, vUv ).xyz * 2.0 - 1.0;\n\tclearcoatMapN.xy *= clearcoatNormalScale;\n\t#ifdef USE_TANGENT\n\t\tclearcoatNormal = normalize( vTBN * clearcoatMapN );\n\t#else\n\t\tclearcoatNormal = perturbNormal2Arb( - vViewPosition, clearcoatNormal, clearcoatMapN );\n\t#endif\n#endif";
10817 var clearcoat_pars_fragment = "#ifdef USE_CLEARCOATMAP\n\tuniform sampler2D clearcoatMap;\n#endif\n#ifdef USE_CLEARCOAT_ROUGHNESSMAP\n\tuniform sampler2D clearcoatRoughnessMap;\n#endif\n#ifdef USE_CLEARCOAT_NORMALMAP\n\tuniform sampler2D clearcoatNormalMap;\n\tuniform vec2 clearcoatNormalScale;\n#endif";
10819 var packing = "vec3 packNormalToRGB( const in vec3 normal ) {\n\treturn normalize( normal ) * 0.5 + 0.5;\n}\nvec3 unpackRGBToNormal( const in vec3 rgb ) {\n\treturn 2.0 * rgb.xyz - 1.0;\n}\nconst float PackUpscale = 256. / 255.;const float UnpackDownscale = 255. / 256.;\nconst vec3 PackFactors = vec3( 256. * 256. * 256., 256. * 256., 256. );\nconst vec4 UnpackFactors = UnpackDownscale / vec4( PackFactors, 1. );\nconst float ShiftRight8 = 1. / 256.;\nvec4 packDepthToRGBA( const in float v ) {\n\tvec4 r = vec4( fract( v * PackFactors ), v );\n\tr.yzw -= r.xyz * ShiftRight8;\treturn r * PackUpscale;\n}\nfloat unpackRGBAToDepth( const in vec4 v ) {\n\treturn dot( v, UnpackFactors );\n}\nvec4 pack2HalfToRGBA( vec2 v ) {\n\tvec4 r = vec4( v.x, fract( v.x * 255.0 ), v.y, fract( v.y * 255.0 ));\n\treturn vec4( r.x - r.y / 255.0, r.y, r.z - r.w / 255.0, r.w);\n}\nvec2 unpackRGBATo2Half( vec4 v ) {\n\treturn vec2( v.x + ( v.y / 255.0 ), v.z + ( v.w / 255.0 ) );\n}\nfloat viewZToOrthographicDepth( const in float viewZ, const in float near, const in float far ) {\n\treturn ( viewZ + near ) / ( near - far );\n}\nfloat orthographicDepthToViewZ( const in float linearClipZ, const in float near, const in float far ) {\n\treturn linearClipZ * ( near - far ) - near;\n}\nfloat viewZToPerspectiveDepth( const in float viewZ, const in float near, const in float far ) {\n\treturn (( near + viewZ ) * far ) / (( far - near ) * viewZ );\n}\nfloat perspectiveDepthToViewZ( const in float invClipZ, const in float near, const in float far ) {\n\treturn ( near * far ) / ( ( far - near ) * invClipZ - far );\n}";
10821 var premultiplied_alpha_fragment = "#ifdef PREMULTIPLIED_ALPHA\n\tgl_FragColor.rgb *= gl_FragColor.a;\n#endif";
10823 var project_vertex = "vec4 mvPosition = vec4( transformed, 1.0 );\n#ifdef USE_INSTANCING\n\tmvPosition = instanceMatrix * mvPosition;\n#endif\nmvPosition = modelViewMatrix * mvPosition;\ngl_Position = projectionMatrix * mvPosition;";
10825 var dithering_fragment = "#ifdef DITHERING\n\tgl_FragColor.rgb = dithering( gl_FragColor.rgb );\n#endif";
10827 var dithering_pars_fragment = "#ifdef DITHERING\n\tvec3 dithering( vec3 color ) {\n\t\tfloat grid_position = rand( gl_FragCoord.xy );\n\t\tvec3 dither_shift_RGB = vec3( 0.25 / 255.0, -0.25 / 255.0, 0.25 / 255.0 );\n\t\tdither_shift_RGB = mix( 2.0 * dither_shift_RGB, -2.0 * dither_shift_RGB, grid_position );\n\t\treturn color + dither_shift_RGB;\n\t}\n#endif";
10829 var roughnessmap_fragment = "float roughnessFactor = roughness;\n#ifdef USE_ROUGHNESSMAP\n\tvec4 texelRoughness = texture2D( roughnessMap, vUv );\n\troughnessFactor *= texelRoughness.g;\n#endif";
10831 var roughnessmap_pars_fragment = "#ifdef USE_ROUGHNESSMAP\n\tuniform sampler2D roughnessMap;\n#endif";
10833 var shadowmap_pars_fragment = "#ifdef USE_SHADOWMAP\n\t#if NUM_DIR_LIGHT_SHADOWS > 0\n\t\tuniform sampler2D directionalShadowMap[ NUM_DIR_LIGHT_SHADOWS ];\n\t\tvarying vec4 vDirectionalShadowCoord[ NUM_DIR_LIGHT_SHADOWS ];\n\t\tstruct DirectionalLightShadow {\n\t\t\tfloat shadowBias;\n\t\t\tfloat shadowNormalBias;\n\t\t\tfloat shadowRadius;\n\t\t\tvec2 shadowMapSize;\n\t\t};\n\t\tuniform DirectionalLightShadow directionalLightShadows[ NUM_DIR_LIGHT_SHADOWS ];\n\t#endif\n\t#if NUM_SPOT_LIGHT_SHADOWS > 0\n\t\tuniform sampler2D spotShadowMap[ NUM_SPOT_LIGHT_SHADOWS ];\n\t\tvarying vec4 vSpotShadowCoord[ NUM_SPOT_LIGHT_SHADOWS ];\n\t\tstruct SpotLightShadow {\n\t\t\tfloat shadowBias;\n\t\t\tfloat shadowNormalBias;\n\t\t\tfloat shadowRadius;\n\t\t\tvec2 shadowMapSize;\n\t\t};\n\t\tuniform SpotLightShadow spotLightShadows[ NUM_SPOT_LIGHT_SHADOWS ];\n\t#endif\n\t#if NUM_POINT_LIGHT_SHADOWS > 0\n\t\tuniform sampler2D pointShadowMap[ NUM_POINT_LIGHT_SHADOWS ];\n\t\tvarying vec4 vPointShadowCoord[ NUM_POINT_LIGHT_SHADOWS ];\n\t\tstruct PointLightShadow {\n\t\t\tfloat shadowBias;\n\t\t\tfloat shadowNormalBias;\n\t\t\tfloat shadowRadius;\n\t\t\tvec2 shadowMapSize;\n\t\t\tfloat shadowCameraNear;\n\t\t\tfloat shadowCameraFar;\n\t\t};\n\t\tuniform PointLightShadow pointLightShadows[ NUM_POINT_LIGHT_SHADOWS ];\n\t#endif\n\tfloat texture2DCompare( sampler2D depths, vec2 uv, float compare ) {\n\t\treturn step( compare, unpackRGBAToDepth( texture2D( depths, uv ) ) );\n\t}\n\tvec2 texture2DDistribution( sampler2D shadow, vec2 uv ) {\n\t\treturn unpackRGBATo2Half( texture2D( shadow, uv ) );\n\t}\n\tfloat VSMShadow (sampler2D shadow, vec2 uv, float compare ){\n\t\tfloat occlusion = 1.0;\n\t\tvec2 distribution = texture2DDistribution( shadow, uv );\n\t\tfloat hard_shadow = step( compare , distribution.x );\n\t\tif (hard_shadow != 1.0 ) {\n\t\t\tfloat distance = compare - distribution.x ;\n\t\t\tfloat variance = max( 0.00000, distribution.y * distribution.y );\n\t\t\tfloat softness_probability = variance / (variance + distance * distance );\t\t\tsoftness_probability = clamp( ( softness_probability - 0.3 ) / ( 0.95 - 0.3 ), 0.0, 1.0 );\t\t\tocclusion = clamp( max( hard_shadow, softness_probability ), 0.0, 1.0 );\n\t\t}\n\t\treturn occlusion;\n\t}\n\tfloat getShadow( sampler2D shadowMap, vec2 shadowMapSize, float shadowBias, float shadowRadius, vec4 shadowCoord ) {\n\t\tfloat shadow = 1.0;\n\t\tshadowCoord.xyz /= shadowCoord.w;\n\t\tshadowCoord.z += shadowBias;\n\t\tbvec4 inFrustumVec = bvec4 ( shadowCoord.x >= 0.0, shadowCoord.x <= 1.0, shadowCoord.y >= 0.0, shadowCoord.y <= 1.0 );\n\t\tbool inFrustum = all( inFrustumVec );\n\t\tbvec2 frustumTestVec = bvec2( inFrustum, shadowCoord.z <= 1.0 );\n\t\tbool frustumTest = all( frustumTestVec );\n\t\tif ( frustumTest ) {\n\t\t#if defined( SHADOWMAP_TYPE_PCF )\n\t\t\tvec2 texelSize = vec2( 1.0 ) / shadowMapSize;\n\t\t\tfloat dx0 = - texelSize.x * shadowRadius;\n\t\t\tfloat dy0 = - texelSize.y * shadowRadius;\n\t\t\tfloat dx1 = + texelSize.x * shadowRadius;\n\t\t\tfloat dy1 = + texelSize.y * shadowRadius;\n\t\t\tfloat dx2 = dx0 / 2.0;\n\t\t\tfloat dy2 = dy0 / 2.0;\n\t\t\tfloat dx3 = dx1 / 2.0;\n\t\t\tfloat dy3 = dy1 / 2.0;\n\t\t\tshadow = (\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx0, dy0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx1, dy0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx2, dy2 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy2 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx3, dy2 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx0, 0.0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx2, 0.0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy, shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx3, 0.0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx1, 0.0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx2, dy3 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy3 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx3, dy3 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx0, dy1 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy1 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx1, dy1 ), shadowCoord.z )\n\t\t\t) * ( 1.0 / 17.0 );\n\t\t#elif defined( SHADOWMAP_TYPE_PCF_SOFT )\n\t\t\tvec2 texelSize = vec2( 1.0 ) / shadowMapSize;\n\t\t\tfloat dx = texelSize.x;\n\t\t\tfloat dy = texelSize.y;\n\t\t\tvec2 uv = shadowCoord.xy;\n\t\t\tvec2 f = fract( uv * shadowMapSize + 0.5 );\n\t\t\tuv -= f * texelSize;\n\t\t\tshadow = (\n\t\t\t\ttexture2DCompare( shadowMap, uv, shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, uv + vec2( dx, 0.0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, uv + vec2( 0.0, dy ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, uv + texelSize, shadowCoord.z ) +\n\t\t\t\tmix( texture2DCompare( shadowMap, uv + vec2( -dx, 0.0 ), shadowCoord.z ), \n\t\t\t\t\t texture2DCompare( shadowMap, uv + vec2( 2.0 * dx, 0.0 ), shadowCoord.z ),\n\t\t\t\t\t f.x ) +\n\t\t\t\tmix( texture2DCompare( shadowMap, uv + vec2( -dx, dy ), shadowCoord.z ), \n\t\t\t\t\t texture2DCompare( shadowMap, uv + vec2( 2.0 * dx, dy ), shadowCoord.z ),\n\t\t\t\t\t f.x ) +\n\t\t\t\tmix( texture2DCompare( shadowMap, uv + vec2( 0.0, -dy ), shadowCoord.z ), \n\t\t\t\t\t texture2DCompare( shadowMap, uv + vec2( 0.0, 2.0 * dy ), shadowCoord.z ),\n\t\t\t\t\t f.y ) +\n\t\t\t\tmix( texture2DCompare( shadowMap, uv + vec2( dx, -dy ), shadowCoord.z ), \n\t\t\t\t\t texture2DCompare( shadowMap, uv + vec2( dx, 2.0 * dy ), shadowCoord.z ),\n\t\t\t\t\t f.y ) +\n\t\t\t\tmix( mix( texture2DCompare( shadowMap, uv + vec2( -dx, -dy ), shadowCoord.z ), \n\t\t\t\t\t\t texture2DCompare( shadowMap, uv + vec2( 2.0 * dx, -dy ), shadowCoord.z ),\n\t\t\t\t\t\t f.x ),\n\t\t\t\t\t mix( texture2DCompare( shadowMap, uv + vec2( -dx, 2.0 * dy ), shadowCoord.z ), \n\t\t\t\t\t\t texture2DCompare( shadowMap, uv + vec2( 2.0 * dx, 2.0 * dy ), shadowCoord.z ),\n\t\t\t\t\t\t f.x ),\n\t\t\t\t\t f.y )\n\t\t\t) * ( 1.0 / 9.0 );\n\t\t#elif defined( SHADOWMAP_TYPE_VSM )\n\t\t\tshadow = VSMShadow( shadowMap, shadowCoord.xy, shadowCoord.z );\n\t\t#else\n\t\t\tshadow = texture2DCompare( shadowMap, shadowCoord.xy, shadowCoord.z );\n\t\t#endif\n\t\t}\n\t\treturn shadow;\n\t}\n\tvec2 cubeToUV( vec3 v, float texelSizeY ) {\n\t\tvec3 absV = abs( v );\n\t\tfloat scaleToCube = 1.0 / max( absV.x, max( absV.y, absV.z ) );\n\t\tabsV *= scaleToCube;\n\t\tv *= scaleToCube * ( 1.0 - 2.0 * texelSizeY );\n\t\tvec2 planar = v.xy;\n\t\tfloat almostATexel = 1.5 * texelSizeY;\n\t\tfloat almostOne = 1.0 - almostATexel;\n\t\tif ( absV.z >= almostOne ) {\n\t\t\tif ( v.z > 0.0 )\n\t\t\t\tplanar.x = 4.0 - v.x;\n\t\t} else if ( absV.x >= almostOne ) {\n\t\t\tfloat signX = sign( v.x );\n\t\t\tplanar.x = v.z * signX + 2.0 * signX;\n\t\t} else if ( absV.y >= almostOne ) {\n\t\t\tfloat signY = sign( v.y );\n\t\t\tplanar.x = v.x + 2.0 * signY + 2.0;\n\t\t\tplanar.y = v.z * signY - 2.0;\n\t\t}\n\t\treturn vec2( 0.125, 0.25 ) * planar + vec2( 0.375, 0.75 );\n\t}\n\tfloat getPointShadow( sampler2D shadowMap, vec2 shadowMapSize, float shadowBias, float shadowRadius, vec4 shadowCoord, float shadowCameraNear, float shadowCameraFar ) {\n\t\tvec2 texelSize = vec2( 1.0 ) / ( shadowMapSize * vec2( 4.0, 2.0 ) );\n\t\tvec3 lightToPosition = shadowCoord.xyz;\n\t\tfloat dp = ( length( lightToPosition ) - shadowCameraNear ) / ( shadowCameraFar - shadowCameraNear );\t\tdp += shadowBias;\n\t\tvec3 bd3D = normalize( lightToPosition );\n\t\t#if defined( SHADOWMAP_TYPE_PCF ) || defined( SHADOWMAP_TYPE_PCF_SOFT ) || defined( SHADOWMAP_TYPE_VSM )\n\t\t\tvec2 offset = vec2( - 1, 1 ) * shadowRadius * texelSize.y;\n\t\t\treturn (\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.xyy, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.yyy, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.xyx, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.yyx, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.xxy, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.yxy, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.xxx, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.yxx, texelSize.y ), dp )\n\t\t\t) * ( 1.0 / 9.0 );\n\t\t#else\n\t\t\treturn texture2DCompare( shadowMap, cubeToUV( bd3D, texelSize.y ), dp );\n\t\t#endif\n\t}\n#endif";
10835 var shadowmap_pars_vertex = "#ifdef USE_SHADOWMAP\n\t#if NUM_DIR_LIGHT_SHADOWS > 0\n\t\tuniform mat4 directionalShadowMatrix[ NUM_DIR_LIGHT_SHADOWS ];\n\t\tvarying vec4 vDirectionalShadowCoord[ NUM_DIR_LIGHT_SHADOWS ];\n\t\tstruct DirectionalLightShadow {\n\t\t\tfloat shadowBias;\n\t\t\tfloat shadowNormalBias;\n\t\t\tfloat shadowRadius;\n\t\t\tvec2 shadowMapSize;\n\t\t};\n\t\tuniform DirectionalLightShadow directionalLightShadows[ NUM_DIR_LIGHT_SHADOWS ];\n\t#endif\n\t#if NUM_SPOT_LIGHT_SHADOWS > 0\n\t\tuniform mat4 spotShadowMatrix[ NUM_SPOT_LIGHT_SHADOWS ];\n\t\tvarying vec4 vSpotShadowCoord[ NUM_SPOT_LIGHT_SHADOWS ];\n\t\tstruct SpotLightShadow {\n\t\t\tfloat shadowBias;\n\t\t\tfloat shadowNormalBias;\n\t\t\tfloat shadowRadius;\n\t\t\tvec2 shadowMapSize;\n\t\t};\n\t\tuniform SpotLightShadow spotLightShadows[ NUM_SPOT_LIGHT_SHADOWS ];\n\t#endif\n\t#if NUM_POINT_LIGHT_SHADOWS > 0\n\t\tuniform mat4 pointShadowMatrix[ NUM_POINT_LIGHT_SHADOWS ];\n\t\tvarying vec4 vPointShadowCoord[ NUM_POINT_LIGHT_SHADOWS ];\n\t\tstruct PointLightShadow {\n\t\t\tfloat shadowBias;\n\t\t\tfloat shadowNormalBias;\n\t\t\tfloat shadowRadius;\n\t\t\tvec2 shadowMapSize;\n\t\t\tfloat shadowCameraNear;\n\t\t\tfloat shadowCameraFar;\n\t\t};\n\t\tuniform PointLightShadow pointLightShadows[ NUM_POINT_LIGHT_SHADOWS ];\n\t#endif\n#endif";
10837 var shadowmap_vertex = "#ifdef USE_SHADOWMAP\n\t#if NUM_DIR_LIGHT_SHADOWS > 0 || NUM_SPOT_LIGHT_SHADOWS > 0 || NUM_POINT_LIGHT_SHADOWS > 0\n\t\tvec3 shadowWorldNormal = inverseTransformDirection( transformedNormal, viewMatrix );\n\t\tvec4 shadowWorldPosition;\n\t#endif\n\t#if NUM_DIR_LIGHT_SHADOWS > 0\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_DIR_LIGHT_SHADOWS; i ++ ) {\n\t\tshadowWorldPosition = worldPosition + vec4( shadowWorldNormal * directionalLightShadows[ i ].shadowNormalBias, 0 );\n\t\tvDirectionalShadowCoord[ i ] = directionalShadowMatrix[ i ] * shadowWorldPosition;\n\t}\n\t#pragma unroll_loop_end\n\t#endif\n\t#if NUM_SPOT_LIGHT_SHADOWS > 0\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_SPOT_LIGHT_SHADOWS; i ++ ) {\n\t\tshadowWorldPosition = worldPosition + vec4( shadowWorldNormal * spotLightShadows[ i ].shadowNormalBias, 0 );\n\t\tvSpotShadowCoord[ i ] = spotShadowMatrix[ i ] * shadowWorldPosition;\n\t}\n\t#pragma unroll_loop_end\n\t#endif\n\t#if NUM_POINT_LIGHT_SHADOWS > 0\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_POINT_LIGHT_SHADOWS; i ++ ) {\n\t\tshadowWorldPosition = worldPosition + vec4( shadowWorldNormal * pointLightShadows[ i ].shadowNormalBias, 0 );\n\t\tvPointShadowCoord[ i ] = pointShadowMatrix[ i ] * shadowWorldPosition;\n\t}\n\t#pragma unroll_loop_end\n\t#endif\n#endif";
10839 var shadowmask_pars_fragment = "float getShadowMask() {\n\tfloat shadow = 1.0;\n\t#ifdef USE_SHADOWMAP\n\t#if NUM_DIR_LIGHT_SHADOWS > 0\n\tDirectionalLightShadow directionalLight;\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_DIR_LIGHT_SHADOWS; i ++ ) {\n\t\tdirectionalLight = directionalLightShadows[ i ];\n\t\tshadow *= receiveShadow ? getShadow( directionalShadowMap[ i ], directionalLight.shadowMapSize, directionalLight.shadowBias, directionalLight.shadowRadius, vDirectionalShadowCoord[ i ] ) : 1.0;\n\t}\n\t#pragma unroll_loop_end\n\t#endif\n\t#if NUM_SPOT_LIGHT_SHADOWS > 0\n\tSpotLightShadow spotLight;\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_SPOT_LIGHT_SHADOWS; i ++ ) {\n\t\tspotLight = spotLightShadows[ i ];\n\t\tshadow *= receiveShadow ? getShadow( spotShadowMap[ i ], spotLight.shadowMapSize, spotLight.shadowBias, spotLight.shadowRadius, vSpotShadowCoord[ i ] ) : 1.0;\n\t}\n\t#pragma unroll_loop_end\n\t#endif\n\t#if NUM_POINT_LIGHT_SHADOWS > 0\n\tPointLightShadow pointLight;\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_POINT_LIGHT_SHADOWS; i ++ ) {\n\t\tpointLight = pointLightShadows[ i ];\n\t\tshadow *= receiveShadow ? getPointShadow( pointShadowMap[ i ], pointLight.shadowMapSize, pointLight.shadowBias, pointLight.shadowRadius, vPointShadowCoord[ i ], pointLight.shadowCameraNear, pointLight.shadowCameraFar ) : 1.0;\n\t}\n\t#pragma unroll_loop_end\n\t#endif\n\t#endif\n\treturn shadow;\n}";
10841 var skinbase_vertex = "#ifdef USE_SKINNING\n\tmat4 boneMatX = getBoneMatrix( skinIndex.x );\n\tmat4 boneMatY = getBoneMatrix( skinIndex.y );\n\tmat4 boneMatZ = getBoneMatrix( skinIndex.z );\n\tmat4 boneMatW = getBoneMatrix( skinIndex.w );\n#endif";
10843 var skinning_pars_vertex = "#ifdef USE_SKINNING\n\tuniform mat4 bindMatrix;\n\tuniform mat4 bindMatrixInverse;\n\t#ifdef BONE_TEXTURE\n\t\tuniform highp sampler2D boneTexture;\n\t\tuniform int boneTextureSize;\n\t\tmat4 getBoneMatrix( const in float i ) {\n\t\t\tfloat j = i * 4.0;\n\t\t\tfloat x = mod( j, float( boneTextureSize ) );\n\t\t\tfloat y = floor( j / float( boneTextureSize ) );\n\t\t\tfloat dx = 1.0 / float( boneTextureSize );\n\t\t\tfloat dy = 1.0 / float( boneTextureSize );\n\t\t\ty = dy * ( y + 0.5 );\n\t\t\tvec4 v1 = texture2D( boneTexture, vec2( dx * ( x + 0.5 ), y ) );\n\t\t\tvec4 v2 = texture2D( boneTexture, vec2( dx * ( x + 1.5 ), y ) );\n\t\t\tvec4 v3 = texture2D( boneTexture, vec2( dx * ( x + 2.5 ), y ) );\n\t\t\tvec4 v4 = texture2D( boneTexture, vec2( dx * ( x + 3.5 ), y ) );\n\t\t\tmat4 bone = mat4( v1, v2, v3, v4 );\n\t\t\treturn bone;\n\t\t}\n\t#else\n\t\tuniform mat4 boneMatrices[ MAX_BONES ];\n\t\tmat4 getBoneMatrix( const in float i ) {\n\t\t\tmat4 bone = boneMatrices[ int(i) ];\n\t\t\treturn bone;\n\t\t}\n\t#endif\n#endif";
10845 var skinning_vertex = "#ifdef USE_SKINNING\n\tvec4 skinVertex = bindMatrix * vec4( transformed, 1.0 );\n\tvec4 skinned = vec4( 0.0 );\n\tskinned += boneMatX * skinVertex * skinWeight.x;\n\tskinned += boneMatY * skinVertex * skinWeight.y;\n\tskinned += boneMatZ * skinVertex * skinWeight.z;\n\tskinned += boneMatW * skinVertex * skinWeight.w;\n\ttransformed = ( bindMatrixInverse * skinned ).xyz;\n#endif";
10847 var skinnormal_vertex = "#ifdef USE_SKINNING\n\tmat4 skinMatrix = mat4( 0.0 );\n\tskinMatrix += skinWeight.x * boneMatX;\n\tskinMatrix += skinWeight.y * boneMatY;\n\tskinMatrix += skinWeight.z * boneMatZ;\n\tskinMatrix += skinWeight.w * boneMatW;\n\tskinMatrix = bindMatrixInverse * skinMatrix * bindMatrix;\n\tobjectNormal = vec4( skinMatrix * vec4( objectNormal, 0.0 ) ).xyz;\n\t#ifdef USE_TANGENT\n\t\tobjectTangent = vec4( skinMatrix * vec4( objectTangent, 0.0 ) ).xyz;\n\t#endif\n#endif";
10849 var specularmap_fragment = "float specularStrength;\n#ifdef USE_SPECULARMAP\n\tvec4 texelSpecular = texture2D( specularMap, vUv );\n\tspecularStrength = texelSpecular.r;\n#else\n\tspecularStrength = 1.0;\n#endif";
10851 var specularmap_pars_fragment = "#ifdef USE_SPECULARMAP\n\tuniform sampler2D specularMap;\n#endif";
10853 var tonemapping_fragment = "#if defined( TONE_MAPPING )\n\tgl_FragColor.rgb = toneMapping( gl_FragColor.rgb );\n#endif";
10855 var tonemapping_pars_fragment = "#ifndef saturate\n#define saturate(a) clamp( a, 0.0, 1.0 )\n#endif\nuniform float toneMappingExposure;\nvec3 LinearToneMapping( vec3 color ) {\n\treturn toneMappingExposure * color;\n}\nvec3 ReinhardToneMapping( vec3 color ) {\n\tcolor *= toneMappingExposure;\n\treturn saturate( color / ( vec3( 1.0 ) + color ) );\n}\nvec3 OptimizedCineonToneMapping( vec3 color ) {\n\tcolor *= toneMappingExposure;\n\tcolor = max( vec3( 0.0 ), color - 0.004 );\n\treturn pow( ( color * ( 6.2 * color + 0.5 ) ) / ( color * ( 6.2 * color + 1.7 ) + 0.06 ), vec3( 2.2 ) );\n}\nvec3 RRTAndODTFit( vec3 v ) {\n\tvec3 a = v * ( v + 0.0245786 ) - 0.000090537;\n\tvec3 b = v * ( 0.983729 * v + 0.4329510 ) + 0.238081;\n\treturn a / b;\n}\nvec3 ACESFilmicToneMapping( vec3 color ) {\n\tconst mat3 ACESInputMat = mat3(\n\t\tvec3( 0.59719, 0.07600, 0.02840 ),\t\tvec3( 0.35458, 0.90834, 0.13383 ),\n\t\tvec3( 0.04823, 0.01566, 0.83777 )\n\t);\n\tconst mat3 ACESOutputMat = mat3(\n\t\tvec3( 1.60475, -0.10208, -0.00327 ),\t\tvec3( -0.53108, 1.10813, -0.07276 ),\n\t\tvec3( -0.07367, -0.00605, 1.07602 )\n\t);\n\tcolor *= toneMappingExposure / 0.6;\n\tcolor = ACESInputMat * color;\n\tcolor = RRTAndODTFit( color );\n\tcolor = ACESOutputMat * color;\n\treturn saturate( color );\n}\nvec3 CustomToneMapping( vec3 color ) { return color; }";
10857 var transmissionmap_fragment = "#ifdef USE_TRANSMISSIONMAP\n\ttotalTransmission *= texture2D( transmissionMap, vUv ).r;\n#endif";
10859 var transmissionmap_pars_fragment = "#ifdef USE_TRANSMISSIONMAP\n\tuniform sampler2D transmissionMap;\n#endif";
10861 var uv_pars_fragment = "#if ( defined( USE_UV ) && ! defined( UVS_VERTEX_ONLY ) )\n\tvarying vec2 vUv;\n#endif";
10863 var uv_pars_vertex = "#ifdef USE_UV\n\t#ifdef UVS_VERTEX_ONLY\n\t\tvec2 vUv;\n\t#else\n\t\tvarying vec2 vUv;\n\t#endif\n\tuniform mat3 uvTransform;\n#endif";
10865 var uv_vertex = "#ifdef USE_UV\n\tvUv = ( uvTransform * vec3( uv, 1 ) ).xy;\n#endif";
10867 var uv2_pars_fragment = "#if defined( USE_LIGHTMAP ) || defined( USE_AOMAP )\n\tvarying vec2 vUv2;\n#endif";
10869 var uv2_pars_vertex = "#if defined( USE_LIGHTMAP ) || defined( USE_AOMAP )\n\tattribute vec2 uv2;\n\tvarying vec2 vUv2;\n\tuniform mat3 uv2Transform;\n#endif";
10871 var uv2_vertex = "#if defined( USE_LIGHTMAP ) || defined( USE_AOMAP )\n\tvUv2 = ( uv2Transform * vec3( uv2, 1 ) ).xy;\n#endif";
10873 var worldpos_vertex = "#if defined( USE_ENVMAP ) || defined( DISTANCE ) || defined ( USE_SHADOWMAP )\n\tvec4 worldPosition = vec4( transformed, 1.0 );\n\t#ifdef USE_INSTANCING\n\t\tworldPosition = instanceMatrix * worldPosition;\n\t#endif\n\tworldPosition = modelMatrix * worldPosition;\n#endif";
10875 var background_frag = "uniform sampler2D t2D;\nvarying vec2 vUv;\nvoid main() {\n\tvec4 texColor = texture2D( t2D, vUv );\n\tgl_FragColor = mapTexelToLinear( texColor );\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n}";
10877 var background_vert = "varying vec2 vUv;\nuniform mat3 uvTransform;\nvoid main() {\n\tvUv = ( uvTransform * vec3( uv, 1 ) ).xy;\n\tgl_Position = vec4( position.xy, 1.0, 1.0 );\n}";
10879 var cube_frag = "#include <envmap_common_pars_fragment>\nuniform float opacity;\nvarying vec3 vWorldDirection;\n#include <cube_uv_reflection_fragment>\nvoid main() {\n\tvec3 vReflect = vWorldDirection;\n\t#include <envmap_fragment>\n\tgl_FragColor = envColor;\n\tgl_FragColor.a *= opacity;\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n}";
10881 var cube_vert = "varying vec3 vWorldDirection;\n#include <common>\nvoid main() {\n\tvWorldDirection = transformDirection( position, modelMatrix );\n\t#include <begin_vertex>\n\t#include <project_vertex>\n\tgl_Position.z = gl_Position.w;\n}";
10883 var depth_frag = "#if DEPTH_PACKING == 3200\n\tuniform float opacity;\n#endif\n#include <common>\n#include <packing>\n#include <uv_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvarying vec2 vHighPrecisionZW;\nvoid main() {\n\t#include <clipping_planes_fragment>\n\tvec4 diffuseColor = vec4( 1.0 );\n\t#if DEPTH_PACKING == 3200\n\t\tdiffuseColor.a = opacity;\n\t#endif\n\t#include <map_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\t#include <logdepthbuf_fragment>\n\tfloat fragCoordZ = 0.5 * vHighPrecisionZW[0] / vHighPrecisionZW[1] + 0.5;\n\t#if DEPTH_PACKING == 3200\n\t\tgl_FragColor = vec4( vec3( 1.0 - fragCoordZ ), opacity );\n\t#elif DEPTH_PACKING == 3201\n\t\tgl_FragColor = packDepthToRGBA( fragCoordZ );\n\t#endif\n}";
10885 var depth_vert = "#include <common>\n#include <uv_pars_vertex>\n#include <displacementmap_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvarying vec2 vHighPrecisionZW;\nvoid main() {\n\t#include <uv_vertex>\n\t#include <skinbase_vertex>\n\t#ifdef USE_DISPLACEMENTMAP\n\t\t#include <beginnormal_vertex>\n\t\t#include <morphnormal_vertex>\n\t\t#include <skinnormal_vertex>\n\t#endif\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <displacementmap_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\tvHighPrecisionZW = gl_Position.zw;\n}";
10887 var distanceRGBA_frag = "#define DISTANCE\nuniform vec3 referencePosition;\nuniform float nearDistance;\nuniform float farDistance;\nvarying vec3 vWorldPosition;\n#include <common>\n#include <packing>\n#include <uv_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main () {\n\t#include <clipping_planes_fragment>\n\tvec4 diffuseColor = vec4( 1.0 );\n\t#include <map_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\tfloat dist = length( vWorldPosition - referencePosition );\n\tdist = ( dist - nearDistance ) / ( farDistance - nearDistance );\n\tdist = saturate( dist );\n\tgl_FragColor = packDepthToRGBA( dist );\n}";
10889 var distanceRGBA_vert = "#define DISTANCE\nvarying vec3 vWorldPosition;\n#include <common>\n#include <uv_pars_vertex>\n#include <displacementmap_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\t#include <skinbase_vertex>\n\t#ifdef USE_DISPLACEMENTMAP\n\t\t#include <beginnormal_vertex>\n\t\t#include <morphnormal_vertex>\n\t\t#include <skinnormal_vertex>\n\t#endif\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <displacementmap_vertex>\n\t#include <project_vertex>\n\t#include <worldpos_vertex>\n\t#include <clipping_planes_vertex>\n\tvWorldPosition = worldPosition.xyz;\n}";
10891 var equirect_frag = "uniform sampler2D tEquirect;\nvarying vec3 vWorldDirection;\n#include <common>\nvoid main() {\n\tvec3 direction = normalize( vWorldDirection );\n\tvec2 sampleUV = equirectUv( direction );\n\tvec4 texColor = texture2D( tEquirect, sampleUV );\n\tgl_FragColor = mapTexelToLinear( texColor );\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n}";
10893 var equirect_vert = "varying vec3 vWorldDirection;\n#include <common>\nvoid main() {\n\tvWorldDirection = transformDirection( position, modelMatrix );\n\t#include <begin_vertex>\n\t#include <project_vertex>\n}";
10895 var linedashed_frag = "uniform vec3 diffuse;\nuniform float opacity;\nuniform float dashSize;\nuniform float totalSize;\nvarying float vLineDistance;\n#include <common>\n#include <color_pars_fragment>\n#include <fog_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\t#include <clipping_planes_fragment>\n\tif ( mod( vLineDistance, totalSize ) > dashSize ) {\n\t\tdiscard;\n\t}\n\tvec3 outgoingLight = vec3( 0.0 );\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include <logdepthbuf_fragment>\n\t#include <color_fragment>\n\toutgoingLight = diffuseColor.rgb;\n\tgl_FragColor = vec4( outgoingLight, diffuseColor.a );\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n}";
10897 var linedashed_vert = "uniform float scale;\nattribute float lineDistance;\nvarying float vLineDistance;\n#include <common>\n#include <color_pars_vertex>\n#include <fog_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\tvLineDistance = scale * lineDistance;\n\t#include <color_vertex>\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\t#include <fog_vertex>\n}";
10899 var meshbasic_frag = "uniform vec3 diffuse;\nuniform float opacity;\n#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n#endif\n#include <common>\n#include <dithering_pars_fragment>\n#include <color_pars_fragment>\n#include <uv_pars_fragment>\n#include <uv2_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <aomap_pars_fragment>\n#include <lightmap_pars_fragment>\n#include <envmap_common_pars_fragment>\n#include <envmap_pars_fragment>\n#include <cube_uv_reflection_fragment>\n#include <fog_pars_fragment>\n#include <specularmap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\t#include <clipping_planes_fragment>\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include <logdepthbuf_fragment>\n\t#include <map_fragment>\n\t#include <color_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\t#include <specularmap_fragment>\n\tReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n\t#ifdef USE_LIGHTMAP\n\t\n\t\tvec4 lightMapTexel= texture2D( lightMap, vUv2 );\n\t\treflectedLight.indirectDiffuse += lightMapTexelToLinear( lightMapTexel ).rgb * lightMapIntensity;\n\t#else\n\t\treflectedLight.indirectDiffuse += vec3( 1.0 );\n\t#endif\n\t#include <aomap_fragment>\n\treflectedLight.indirectDiffuse *= diffuseColor.rgb;\n\tvec3 outgoingLight = reflectedLight.indirectDiffuse;\n\t#include <envmap_fragment>\n\tgl_FragColor = vec4( outgoingLight, diffuseColor.a );\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n\t#include <dithering_fragment>\n}";
10901 var meshbasic_vert = "#include <common>\n#include <uv_pars_vertex>\n#include <uv2_pars_vertex>\n#include <envmap_pars_vertex>\n#include <color_pars_vertex>\n#include <fog_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\t#include <uv2_vertex>\n\t#include <color_vertex>\n\t#include <skinbase_vertex>\n\t#ifdef USE_ENVMAP\n\t#include <beginnormal_vertex>\n\t#include <morphnormal_vertex>\n\t#include <skinnormal_vertex>\n\t#include <defaultnormal_vertex>\n\t#endif\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <worldpos_vertex>\n\t#include <clipping_planes_vertex>\n\t#include <envmap_vertex>\n\t#include <fog_vertex>\n}";
10903 var meshlambert_frag = "uniform vec3 diffuse;\nuniform vec3 emissive;\nuniform float opacity;\nvarying vec3 vLightFront;\nvarying vec3 vIndirectFront;\n#ifdef DOUBLE_SIDED\n\tvarying vec3 vLightBack;\n\tvarying vec3 vIndirectBack;\n#endif\n#include <common>\n#include <packing>\n#include <dithering_pars_fragment>\n#include <color_pars_fragment>\n#include <uv_pars_fragment>\n#include <uv2_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <aomap_pars_fragment>\n#include <lightmap_pars_fragment>\n#include <emissivemap_pars_fragment>\n#include <envmap_common_pars_fragment>\n#include <envmap_pars_fragment>\n#include <cube_uv_reflection_fragment>\n#include <bsdfs>\n#include <lights_pars_begin>\n#include <fog_pars_fragment>\n#include <shadowmap_pars_fragment>\n#include <shadowmask_pars_fragment>\n#include <specularmap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\t#include <clipping_planes_fragment>\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\tReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n\tvec3 totalEmissiveRadiance = emissive;\n\t#include <logdepthbuf_fragment>\n\t#include <map_fragment>\n\t#include <color_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\t#include <specularmap_fragment>\n\t#include <emissivemap_fragment>\n\t#ifdef DOUBLE_SIDED\n\t\treflectedLight.indirectDiffuse += ( gl_FrontFacing ) ? vIndirectFront : vIndirectBack;\n\t#else\n\t\treflectedLight.indirectDiffuse += vIndirectFront;\n\t#endif\n\t#include <lightmap_fragment>\n\treflectedLight.indirectDiffuse *= BRDF_Diffuse_Lambert( diffuseColor.rgb );\n\t#ifdef DOUBLE_SIDED\n\t\treflectedLight.directDiffuse = ( gl_FrontFacing ) ? vLightFront : vLightBack;\n\t#else\n\t\treflectedLight.directDiffuse = vLightFront;\n\t#endif\n\treflectedLight.directDiffuse *= BRDF_Diffuse_Lambert( diffuseColor.rgb ) * getShadowMask();\n\t#include <aomap_fragment>\n\tvec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + totalEmissiveRadiance;\n\t#include <envmap_fragment>\n\tgl_FragColor = vec4( outgoingLight, diffuseColor.a );\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n\t#include <dithering_fragment>\n}";
10905 var meshlambert_vert = "#define LAMBERT\nvarying vec3 vLightFront;\nvarying vec3 vIndirectFront;\n#ifdef DOUBLE_SIDED\n\tvarying vec3 vLightBack;\n\tvarying vec3 vIndirectBack;\n#endif\n#include <common>\n#include <uv_pars_vertex>\n#include <uv2_pars_vertex>\n#include <envmap_pars_vertex>\n#include <bsdfs>\n#include <lights_pars_begin>\n#include <color_pars_vertex>\n#include <fog_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <shadowmap_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\t#include <uv2_vertex>\n\t#include <color_vertex>\n\t#include <beginnormal_vertex>\n\t#include <morphnormal_vertex>\n\t#include <skinbase_vertex>\n\t#include <skinnormal_vertex>\n\t#include <defaultnormal_vertex>\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\t#include <worldpos_vertex>\n\t#include <envmap_vertex>\n\t#include <lights_lambert_vertex>\n\t#include <shadowmap_vertex>\n\t#include <fog_vertex>\n}";
10907 var meshmatcap_frag = "#define MATCAP\nuniform vec3 diffuse;\nuniform float opacity;\nuniform sampler2D matcap;\nvarying vec3 vViewPosition;\n#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n#endif\n#include <common>\n#include <dithering_pars_fragment>\n#include <color_pars_fragment>\n#include <uv_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <fog_pars_fragment>\n#include <bumpmap_pars_fragment>\n#include <normalmap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\t#include <clipping_planes_fragment>\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include <logdepthbuf_fragment>\n\t#include <map_fragment>\n\t#include <color_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\t#include <normal_fragment_begin>\n\t#include <normal_fragment_maps>\n\tvec3 viewDir = normalize( vViewPosition );\n\tvec3 x = normalize( vec3( viewDir.z, 0.0, - viewDir.x ) );\n\tvec3 y = cross( viewDir, x );\n\tvec2 uv = vec2( dot( x, normal ), dot( y, normal ) ) * 0.495 + 0.5;\n\t#ifdef USE_MATCAP\n\t\tvec4 matcapColor = texture2D( matcap, uv );\n\t\tmatcapColor = matcapTexelToLinear( matcapColor );\n\t#else\n\t\tvec4 matcapColor = vec4( 1.0 );\n\t#endif\n\tvec3 outgoingLight = diffuseColor.rgb * matcapColor.rgb;\n\tgl_FragColor = vec4( outgoingLight, diffuseColor.a );\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n\t#include <dithering_fragment>\n}";
10909 var meshmatcap_vert = "#define MATCAP\nvarying vec3 vViewPosition;\n#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n#endif\n#include <common>\n#include <uv_pars_vertex>\n#include <color_pars_vertex>\n#include <displacementmap_pars_vertex>\n#include <fog_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\t#include <color_vertex>\n\t#include <beginnormal_vertex>\n\t#include <morphnormal_vertex>\n\t#include <skinbase_vertex>\n\t#include <skinnormal_vertex>\n\t#include <defaultnormal_vertex>\n\t#ifndef FLAT_SHADED\n\t\tvNormal = normalize( transformedNormal );\n\t#endif\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <displacementmap_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\t#include <fog_vertex>\n\tvViewPosition = - mvPosition.xyz;\n}";
10911 var meshtoon_frag = "#define TOON\nuniform vec3 diffuse;\nuniform vec3 emissive;\nuniform float opacity;\n#include <common>\n#include <packing>\n#include <dithering_pars_fragment>\n#include <color_pars_fragment>\n#include <uv_pars_fragment>\n#include <uv2_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <aomap_pars_fragment>\n#include <lightmap_pars_fragment>\n#include <emissivemap_pars_fragment>\n#include <gradientmap_pars_fragment>\n#include <fog_pars_fragment>\n#include <bsdfs>\n#include <lights_pars_begin>\n#include <lights_toon_pars_fragment>\n#include <shadowmap_pars_fragment>\n#include <bumpmap_pars_fragment>\n#include <normalmap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\t#include <clipping_planes_fragment>\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\tReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n\tvec3 totalEmissiveRadiance = emissive;\n\t#include <logdepthbuf_fragment>\n\t#include <map_fragment>\n\t#include <color_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\t#include <normal_fragment_begin>\n\t#include <normal_fragment_maps>\n\t#include <emissivemap_fragment>\n\t#include <lights_toon_fragment>\n\t#include <lights_fragment_begin>\n\t#include <lights_fragment_maps>\n\t#include <lights_fragment_end>\n\t#include <aomap_fragment>\n\tvec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + totalEmissiveRadiance;\n\tgl_FragColor = vec4( outgoingLight, diffuseColor.a );\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n\t#include <dithering_fragment>\n}";
10913 var meshtoon_vert = "#define TOON\nvarying vec3 vViewPosition;\n#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n#endif\n#include <common>\n#include <uv_pars_vertex>\n#include <uv2_pars_vertex>\n#include <displacementmap_pars_vertex>\n#include <color_pars_vertex>\n#include <fog_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <shadowmap_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\t#include <uv2_vertex>\n\t#include <color_vertex>\n\t#include <beginnormal_vertex>\n\t#include <morphnormal_vertex>\n\t#include <skinbase_vertex>\n\t#include <skinnormal_vertex>\n\t#include <defaultnormal_vertex>\n#ifndef FLAT_SHADED\n\tvNormal = normalize( transformedNormal );\n#endif\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <displacementmap_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\tvViewPosition = - mvPosition.xyz;\n\t#include <worldpos_vertex>\n\t#include <shadowmap_vertex>\n\t#include <fog_vertex>\n}";
10915 var meshphong_frag = "#define PHONG\nuniform vec3 diffuse;\nuniform vec3 emissive;\nuniform vec3 specular;\nuniform float shininess;\nuniform float opacity;\n#include <common>\n#include <packing>\n#include <dithering_pars_fragment>\n#include <color_pars_fragment>\n#include <uv_pars_fragment>\n#include <uv2_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <aomap_pars_fragment>\n#include <lightmap_pars_fragment>\n#include <emissivemap_pars_fragment>\n#include <envmap_common_pars_fragment>\n#include <envmap_pars_fragment>\n#include <cube_uv_reflection_fragment>\n#include <fog_pars_fragment>\n#include <bsdfs>\n#include <lights_pars_begin>\n#include <lights_phong_pars_fragment>\n#include <shadowmap_pars_fragment>\n#include <bumpmap_pars_fragment>\n#include <normalmap_pars_fragment>\n#include <specularmap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\t#include <clipping_planes_fragment>\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\tReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n\tvec3 totalEmissiveRadiance = emissive;\n\t#include <logdepthbuf_fragment>\n\t#include <map_fragment>\n\t#include <color_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\t#include <specularmap_fragment>\n\t#include <normal_fragment_begin>\n\t#include <normal_fragment_maps>\n\t#include <emissivemap_fragment>\n\t#include <lights_phong_fragment>\n\t#include <lights_fragment_begin>\n\t#include <lights_fragment_maps>\n\t#include <lights_fragment_end>\n\t#include <aomap_fragment>\n\tvec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + reflectedLight.directSpecular + reflectedLight.indirectSpecular + totalEmissiveRadiance;\n\t#include <envmap_fragment>\n\tgl_FragColor = vec4( outgoingLight, diffuseColor.a );\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n\t#include <dithering_fragment>\n}";
10917 var meshphong_vert = "#define PHONG\nvarying vec3 vViewPosition;\n#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n#endif\n#include <common>\n#include <uv_pars_vertex>\n#include <uv2_pars_vertex>\n#include <displacementmap_pars_vertex>\n#include <envmap_pars_vertex>\n#include <color_pars_vertex>\n#include <fog_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <shadowmap_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\t#include <uv2_vertex>\n\t#include <color_vertex>\n\t#include <beginnormal_vertex>\n\t#include <morphnormal_vertex>\n\t#include <skinbase_vertex>\n\t#include <skinnormal_vertex>\n\t#include <defaultnormal_vertex>\n#ifndef FLAT_SHADED\n\tvNormal = normalize( transformedNormal );\n#endif\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <displacementmap_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\tvViewPosition = - mvPosition.xyz;\n\t#include <worldpos_vertex>\n\t#include <envmap_vertex>\n\t#include <shadowmap_vertex>\n\t#include <fog_vertex>\n}";
10919 var meshphysical_frag = "#define STANDARD\n#ifdef PHYSICAL\n\t#define REFLECTIVITY\n\t#define CLEARCOAT\n\t#define TRANSMISSION\n#endif\nuniform vec3 diffuse;\nuniform vec3 emissive;\nuniform float roughness;\nuniform float metalness;\nuniform float opacity;\n#ifdef TRANSMISSION\n\tuniform float transmission;\n#endif\n#ifdef REFLECTIVITY\n\tuniform float reflectivity;\n#endif\n#ifdef CLEARCOAT\n\tuniform float clearcoat;\n\tuniform float clearcoatRoughness;\n#endif\n#ifdef USE_SHEEN\n\tuniform vec3 sheen;\n#endif\nvarying vec3 vViewPosition;\n#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n\t#ifdef USE_TANGENT\n\t\tvarying vec3 vTangent;\n\t\tvarying vec3 vBitangent;\n\t#endif\n#endif\n#include <common>\n#include <packing>\n#include <dithering_pars_fragment>\n#include <color_pars_fragment>\n#include <uv_pars_fragment>\n#include <uv2_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <aomap_pars_fragment>\n#include <lightmap_pars_fragment>\n#include <emissivemap_pars_fragment>\n#include <transmissionmap_pars_fragment>\n#include <bsdfs>\n#include <cube_uv_reflection_fragment>\n#include <envmap_common_pars_fragment>\n#include <envmap_physical_pars_fragment>\n#include <fog_pars_fragment>\n#include <lights_pars_begin>\n#include <lights_physical_pars_fragment>\n#include <shadowmap_pars_fragment>\n#include <bumpmap_pars_fragment>\n#include <normalmap_pars_fragment>\n#include <clearcoat_pars_fragment>\n#include <roughnessmap_pars_fragment>\n#include <metalnessmap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\t#include <clipping_planes_fragment>\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\tReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n\tvec3 totalEmissiveRadiance = emissive;\n\t#ifdef TRANSMISSION\n\t\tfloat totalTransmission = transmission;\n\t#endif\n\t#include <logdepthbuf_fragment>\n\t#include <map_fragment>\n\t#include <color_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\t#include <roughnessmap_fragment>\n\t#include <metalnessmap_fragment>\n\t#include <normal_fragment_begin>\n\t#include <normal_fragment_maps>\n\t#include <clearcoat_normal_fragment_begin>\n\t#include <clearcoat_normal_fragment_maps>\n\t#include <emissivemap_fragment>\n\t#include <transmissionmap_fragment>\n\t#include <lights_physical_fragment>\n\t#include <lights_fragment_begin>\n\t#include <lights_fragment_maps>\n\t#include <lights_fragment_end>\n\t#include <aomap_fragment>\n\tvec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + reflectedLight.directSpecular + reflectedLight.indirectSpecular + totalEmissiveRadiance;\n\t#ifdef TRANSMISSION\n\t\tdiffuseColor.a *= mix( saturate( 1. - totalTransmission + linearToRelativeLuminance( reflectedLight.directSpecular + reflectedLight.indirectSpecular ) ), 1.0, metalness );\n\t#endif\n\tgl_FragColor = vec4( outgoingLight, diffuseColor.a );\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n\t#include <dithering_fragment>\n}";
10921 var meshphysical_vert = "#define STANDARD\nvarying vec3 vViewPosition;\n#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n\t#ifdef USE_TANGENT\n\t\tvarying vec3 vTangent;\n\t\tvarying vec3 vBitangent;\n\t#endif\n#endif\n#include <common>\n#include <uv_pars_vertex>\n#include <uv2_pars_vertex>\n#include <displacementmap_pars_vertex>\n#include <color_pars_vertex>\n#include <fog_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <shadowmap_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\t#include <uv2_vertex>\n\t#include <color_vertex>\n\t#include <beginnormal_vertex>\n\t#include <morphnormal_vertex>\n\t#include <skinbase_vertex>\n\t#include <skinnormal_vertex>\n\t#include <defaultnormal_vertex>\n#ifndef FLAT_SHADED\n\tvNormal = normalize( transformedNormal );\n\t#ifdef USE_TANGENT\n\t\tvTangent = normalize( transformedTangent );\n\t\tvBitangent = normalize( cross( vNormal, vTangent ) * tangent.w );\n\t#endif\n#endif\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <displacementmap_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\tvViewPosition = - mvPosition.xyz;\n\t#include <worldpos_vertex>\n\t#include <shadowmap_vertex>\n\t#include <fog_vertex>\n}";
10923 var normal_frag = "#define NORMAL\nuniform float opacity;\n#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( TANGENTSPACE_NORMALMAP )\n\tvarying vec3 vViewPosition;\n#endif\n#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n\t#ifdef USE_TANGENT\n\t\tvarying vec3 vTangent;\n\t\tvarying vec3 vBitangent;\n\t#endif\n#endif\n#include <packing>\n#include <uv_pars_fragment>\n#include <bumpmap_pars_fragment>\n#include <normalmap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\t#include <clipping_planes_fragment>\n\t#include <logdepthbuf_fragment>\n\t#include <normal_fragment_begin>\n\t#include <normal_fragment_maps>\n\tgl_FragColor = vec4( packNormalToRGB( normal ), opacity );\n}";
10925 var normal_vert = "#define NORMAL\n#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( TANGENTSPACE_NORMALMAP )\n\tvarying vec3 vViewPosition;\n#endif\n#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n\t#ifdef USE_TANGENT\n\t\tvarying vec3 vTangent;\n\t\tvarying vec3 vBitangent;\n\t#endif\n#endif\n#include <common>\n#include <uv_pars_vertex>\n#include <displacementmap_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\t#include <beginnormal_vertex>\n\t#include <morphnormal_vertex>\n\t#include <skinbase_vertex>\n\t#include <skinnormal_vertex>\n\t#include <defaultnormal_vertex>\n#ifndef FLAT_SHADED\n\tvNormal = normalize( transformedNormal );\n\t#ifdef USE_TANGENT\n\t\tvTangent = normalize( transformedTangent );\n\t\tvBitangent = normalize( cross( vNormal, vTangent ) * tangent.w );\n\t#endif\n#endif\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <displacementmap_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( TANGENTSPACE_NORMALMAP )\n\tvViewPosition = - mvPosition.xyz;\n#endif\n}";
10927 var points_frag = "uniform vec3 diffuse;\nuniform float opacity;\n#include <common>\n#include <color_pars_fragment>\n#include <map_particle_pars_fragment>\n#include <fog_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\t#include <clipping_planes_fragment>\n\tvec3 outgoingLight = vec3( 0.0 );\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include <logdepthbuf_fragment>\n\t#include <map_particle_fragment>\n\t#include <color_fragment>\n\t#include <alphatest_fragment>\n\toutgoingLight = diffuseColor.rgb;\n\tgl_FragColor = vec4( outgoingLight, diffuseColor.a );\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n}";
10929 var points_vert = "uniform float size;\nuniform float scale;\n#include <common>\n#include <color_pars_vertex>\n#include <fog_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <color_vertex>\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <project_vertex>\n\tgl_PointSize = size;\n\t#ifdef USE_SIZEATTENUATION\n\t\tbool isPerspective = isPerspectiveMatrix( projectionMatrix );\n\t\tif ( isPerspective ) gl_PointSize *= ( scale / - mvPosition.z );\n\t#endif\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\t#include <worldpos_vertex>\n\t#include <fog_vertex>\n}";
10931 var shadow_frag = "uniform vec3 color;\nuniform float opacity;\n#include <common>\n#include <packing>\n#include <fog_pars_fragment>\n#include <bsdfs>\n#include <lights_pars_begin>\n#include <shadowmap_pars_fragment>\n#include <shadowmask_pars_fragment>\nvoid main() {\n\tgl_FragColor = vec4( color, opacity * ( 1.0 - getShadowMask() ) );\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n}";
10933 var shadow_vert = "#include <common>\n#include <fog_pars_vertex>\n#include <shadowmap_pars_vertex>\nvoid main() {\n\t#include <begin_vertex>\n\t#include <project_vertex>\n\t#include <worldpos_vertex>\n\t#include <beginnormal_vertex>\n\t#include <morphnormal_vertex>\n\t#include <skinbase_vertex>\n\t#include <skinnormal_vertex>\n\t#include <defaultnormal_vertex>\n\t#include <shadowmap_vertex>\n\t#include <fog_vertex>\n}";
10935 var sprite_frag = "uniform vec3 diffuse;\nuniform float opacity;\n#include <common>\n#include <uv_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <fog_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\t#include <clipping_planes_fragment>\n\tvec3 outgoingLight = vec3( 0.0 );\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include <logdepthbuf_fragment>\n\t#include <map_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\toutgoingLight = diffuseColor.rgb;\n\tgl_FragColor = vec4( outgoingLight, diffuseColor.a );\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n}";
10937 var sprite_vert = "uniform float rotation;\nuniform vec2 center;\n#include <common>\n#include <uv_pars_vertex>\n#include <fog_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\tvec4 mvPosition = modelViewMatrix * vec4( 0.0, 0.0, 0.0, 1.0 );\n\tvec2 scale;\n\tscale.x = length( vec3( modelMatrix[ 0 ].x, modelMatrix[ 0 ].y, modelMatrix[ 0 ].z ) );\n\tscale.y = length( vec3( modelMatrix[ 1 ].x, modelMatrix[ 1 ].y, modelMatrix[ 1 ].z ) );\n\t#ifndef USE_SIZEATTENUATION\n\t\tbool isPerspective = isPerspectiveMatrix( projectionMatrix );\n\t\tif ( isPerspective ) scale *= - mvPosition.z;\n\t#endif\n\tvec2 alignedPosition = ( position.xy - ( center - vec2( 0.5 ) ) ) * scale;\n\tvec2 rotatedPosition;\n\trotatedPosition.x = cos( rotation ) * alignedPosition.x - sin( rotation ) * alignedPosition.y;\n\trotatedPosition.y = sin( rotation ) * alignedPosition.x + cos( rotation ) * alignedPosition.y;\n\tmvPosition.xy += rotatedPosition;\n\tgl_Position = projectionMatrix * mvPosition;\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\t#include <fog_vertex>\n}";
10939 var ShaderChunk = {
10940 alphamap_fragment: alphamap_fragment,
10941 alphamap_pars_fragment: alphamap_pars_fragment,
10942 alphatest_fragment: alphatest_fragment,
10943 aomap_fragment: aomap_fragment,
10944 aomap_pars_fragment: aomap_pars_fragment,
10945 begin_vertex: begin_vertex,
10946 beginnormal_vertex: beginnormal_vertex,
10948 bumpmap_pars_fragment: bumpmap_pars_fragment,
10949 clipping_planes_fragment: clipping_planes_fragment,
10950 clipping_planes_pars_fragment: clipping_planes_pars_fragment,
10951 clipping_planes_pars_vertex: clipping_planes_pars_vertex,
10952 clipping_planes_vertex: clipping_planes_vertex,
10953 color_fragment: color_fragment,
10954 color_pars_fragment: color_pars_fragment,
10955 color_pars_vertex: color_pars_vertex,
10956 color_vertex: color_vertex,
10958 cube_uv_reflection_fragment: cube_uv_reflection_fragment,
10959 defaultnormal_vertex: defaultnormal_vertex,
10960 displacementmap_pars_vertex: displacementmap_pars_vertex,
10961 displacementmap_vertex: displacementmap_vertex,
10962 emissivemap_fragment: emissivemap_fragment,
10963 emissivemap_pars_fragment: emissivemap_pars_fragment,
10964 encodings_fragment: encodings_fragment,
10965 encodings_pars_fragment: encodings_pars_fragment,
10966 envmap_fragment: envmap_fragment,
10967 envmap_common_pars_fragment: envmap_common_pars_fragment,
10968 envmap_pars_fragment: envmap_pars_fragment,
10969 envmap_pars_vertex: envmap_pars_vertex,
10970 envmap_physical_pars_fragment: envmap_physical_pars_fragment,
10971 envmap_vertex: envmap_vertex,
10972 fog_vertex: fog_vertex,
10973 fog_pars_vertex: fog_pars_vertex,
10974 fog_fragment: fog_fragment,
10975 fog_pars_fragment: fog_pars_fragment,
10976 gradientmap_pars_fragment: gradientmap_pars_fragment,
10977 lightmap_fragment: lightmap_fragment,
10978 lightmap_pars_fragment: lightmap_pars_fragment,
10979 lights_lambert_vertex: lights_lambert_vertex,
10980 lights_pars_begin: lights_pars_begin,
10981 lights_toon_fragment: lights_toon_fragment,
10982 lights_toon_pars_fragment: lights_toon_pars_fragment,
10983 lights_phong_fragment: lights_phong_fragment,
10984 lights_phong_pars_fragment: lights_phong_pars_fragment,
10985 lights_physical_fragment: lights_physical_fragment,
10986 lights_physical_pars_fragment: lights_physical_pars_fragment,
10987 lights_fragment_begin: lights_fragment_begin,
10988 lights_fragment_maps: lights_fragment_maps,
10989 lights_fragment_end: lights_fragment_end,
10990 logdepthbuf_fragment: logdepthbuf_fragment,
10991 logdepthbuf_pars_fragment: logdepthbuf_pars_fragment,
10992 logdepthbuf_pars_vertex: logdepthbuf_pars_vertex,
10993 logdepthbuf_vertex: logdepthbuf_vertex,
10994 map_fragment: map_fragment,
10995 map_pars_fragment: map_pars_fragment,
10996 map_particle_fragment: map_particle_fragment,
10997 map_particle_pars_fragment: map_particle_pars_fragment,
10998 metalnessmap_fragment: metalnessmap_fragment,
10999 metalnessmap_pars_fragment: metalnessmap_pars_fragment,
11000 morphnormal_vertex: morphnormal_vertex,
11001 morphtarget_pars_vertex: morphtarget_pars_vertex,
11002 morphtarget_vertex: morphtarget_vertex,
11003 normal_fragment_begin: normal_fragment_begin,
11004 normal_fragment_maps: normal_fragment_maps,
11005 normalmap_pars_fragment: normalmap_pars_fragment,
11006 clearcoat_normal_fragment_begin: clearcoat_normal_fragment_begin,
11007 clearcoat_normal_fragment_maps: clearcoat_normal_fragment_maps,
11008 clearcoat_pars_fragment: clearcoat_pars_fragment,
11010 premultiplied_alpha_fragment: premultiplied_alpha_fragment,
11011 project_vertex: project_vertex,
11012 dithering_fragment: dithering_fragment,
11013 dithering_pars_fragment: dithering_pars_fragment,
11014 roughnessmap_fragment: roughnessmap_fragment,
11015 roughnessmap_pars_fragment: roughnessmap_pars_fragment,
11016 shadowmap_pars_fragment: shadowmap_pars_fragment,
11017 shadowmap_pars_vertex: shadowmap_pars_vertex,
11018 shadowmap_vertex: shadowmap_vertex,
11019 shadowmask_pars_fragment: shadowmask_pars_fragment,
11020 skinbase_vertex: skinbase_vertex,
11021 skinning_pars_vertex: skinning_pars_vertex,
11022 skinning_vertex: skinning_vertex,
11023 skinnormal_vertex: skinnormal_vertex,
11024 specularmap_fragment: specularmap_fragment,
11025 specularmap_pars_fragment: specularmap_pars_fragment,
11026 tonemapping_fragment: tonemapping_fragment,
11027 tonemapping_pars_fragment: tonemapping_pars_fragment,
11028 transmissionmap_fragment: transmissionmap_fragment,
11029 transmissionmap_pars_fragment: transmissionmap_pars_fragment,
11030 uv_pars_fragment: uv_pars_fragment,
11031 uv_pars_vertex: uv_pars_vertex,
11032 uv_vertex: uv_vertex,
11033 uv2_pars_fragment: uv2_pars_fragment,
11034 uv2_pars_vertex: uv2_pars_vertex,
11035 uv2_vertex: uv2_vertex,
11036 worldpos_vertex: worldpos_vertex,
11037 background_frag: background_frag,
11038 background_vert: background_vert,
11039 cube_frag: cube_frag,
11040 cube_vert: cube_vert,
11041 depth_frag: depth_frag,
11042 depth_vert: depth_vert,
11043 distanceRGBA_frag: distanceRGBA_frag,
11044 distanceRGBA_vert: distanceRGBA_vert,
11045 equirect_frag: equirect_frag,
11046 equirect_vert: equirect_vert,
11047 linedashed_frag: linedashed_frag,
11048 linedashed_vert: linedashed_vert,
11049 meshbasic_frag: meshbasic_frag,
11050 meshbasic_vert: meshbasic_vert,
11051 meshlambert_frag: meshlambert_frag,
11052 meshlambert_vert: meshlambert_vert,
11053 meshmatcap_frag: meshmatcap_frag,
11054 meshmatcap_vert: meshmatcap_vert,
11055 meshtoon_frag: meshtoon_frag,
11056 meshtoon_vert: meshtoon_vert,
11057 meshphong_frag: meshphong_frag,
11058 meshphong_vert: meshphong_vert,
11059 meshphysical_frag: meshphysical_frag,
11060 meshphysical_vert: meshphysical_vert,
11061 normal_frag: normal_frag,
11062 normal_vert: normal_vert,
11063 points_frag: points_frag,
11064 points_vert: points_vert,
11065 shadow_frag: shadow_frag,
11066 shadow_vert: shadow_vert,
11067 sprite_frag: sprite_frag,
11068 sprite_vert: sprite_vert
11072 * Uniforms library for shared webgl shaders
11075 var UniformsLib = {
11078 value: new Color(0xeeeeee)
11087 value: new Matrix3()
11090 value: new Matrix3()
11130 lightMapIntensity: {
11152 value: new Vector2(1, 1)
11159 displacementScale: {
11162 displacementBias: {
11192 value: new Color(0xffffff)
11196 ambientLightColor: {
11202 directionalLights: {
11209 directionalLightShadows: {
11213 shadowNormalBias: {},
11218 directionalShadowMap: {
11221 directionalShadowMatrix: {
11236 spotLightShadows: {
11240 shadowNormalBias: {},
11248 spotShadowMatrix: {
11260 pointLightShadows: {
11264 shadowNormalBias: {},
11267 shadowCameraNear: {},
11268 shadowCameraFar: {}
11274 pointShadowMatrix: {
11277 hemisphereLights: {
11285 // TODO (abelnation): RectAreaLight BRDF data needs to be moved from example to main src
11304 value: new Color(0xeeeeee)
11322 value: new Matrix3()
11327 value: new Color(0xeeeeee)
11333 value: new Vector2(0.5, 0.5)
11345 value: new Matrix3()
11352 uniforms: mergeUniforms([UniformsLib.common, UniformsLib.specularmap, UniformsLib.envmap, UniformsLib.aomap, UniformsLib.lightmap, UniformsLib.fog]),
11353 vertexShader: ShaderChunk.meshbasic_vert,
11354 fragmentShader: ShaderChunk.meshbasic_frag
11357 uniforms: mergeUniforms([UniformsLib.common, UniformsLib.specularmap, UniformsLib.envmap, UniformsLib.aomap, UniformsLib.lightmap, UniformsLib.emissivemap, UniformsLib.fog, UniformsLib.lights, {
11359 value: new Color(0x000000)
11362 vertexShader: ShaderChunk.meshlambert_vert,
11363 fragmentShader: ShaderChunk.meshlambert_frag
11366 uniforms: mergeUniforms([UniformsLib.common, UniformsLib.specularmap, UniformsLib.envmap, UniformsLib.aomap, UniformsLib.lightmap, UniformsLib.emissivemap, UniformsLib.bumpmap, UniformsLib.normalmap, UniformsLib.displacementmap, UniformsLib.fog, UniformsLib.lights, {
11368 value: new Color(0x000000)
11371 value: new Color(0x111111)
11377 vertexShader: ShaderChunk.meshphong_vert,
11378 fragmentShader: ShaderChunk.meshphong_frag
11381 uniforms: mergeUniforms([UniformsLib.common, UniformsLib.envmap, UniformsLib.aomap, UniformsLib.lightmap, UniformsLib.emissivemap, UniformsLib.bumpmap, UniformsLib.normalmap, UniformsLib.displacementmap, UniformsLib.roughnessmap, UniformsLib.metalnessmap, UniformsLib.fog, UniformsLib.lights, {
11383 value: new Color(0x000000)
11396 vertexShader: ShaderChunk.meshphysical_vert,
11397 fragmentShader: ShaderChunk.meshphysical_frag
11400 uniforms: mergeUniforms([UniformsLib.common, UniformsLib.aomap, UniformsLib.lightmap, UniformsLib.emissivemap, UniformsLib.bumpmap, UniformsLib.normalmap, UniformsLib.displacementmap, UniformsLib.gradientmap, UniformsLib.fog, UniformsLib.lights, {
11402 value: new Color(0x000000)
11405 vertexShader: ShaderChunk.meshtoon_vert,
11406 fragmentShader: ShaderChunk.meshtoon_frag
11409 uniforms: mergeUniforms([UniformsLib.common, UniformsLib.bumpmap, UniformsLib.normalmap, UniformsLib.displacementmap, UniformsLib.fog, {
11414 vertexShader: ShaderChunk.meshmatcap_vert,
11415 fragmentShader: ShaderChunk.meshmatcap_frag
11418 uniforms: mergeUniforms([UniformsLib.points, UniformsLib.fog]),
11419 vertexShader: ShaderChunk.points_vert,
11420 fragmentShader: ShaderChunk.points_frag
11423 uniforms: mergeUniforms([UniformsLib.common, UniformsLib.fog, {
11434 vertexShader: ShaderChunk.linedashed_vert,
11435 fragmentShader: ShaderChunk.linedashed_frag
11438 uniforms: mergeUniforms([UniformsLib.common, UniformsLib.displacementmap]),
11439 vertexShader: ShaderChunk.depth_vert,
11440 fragmentShader: ShaderChunk.depth_frag
11443 uniforms: mergeUniforms([UniformsLib.common, UniformsLib.bumpmap, UniformsLib.normalmap, UniformsLib.displacementmap, {
11448 vertexShader: ShaderChunk.normal_vert,
11449 fragmentShader: ShaderChunk.normal_frag
11452 uniforms: mergeUniforms([UniformsLib.sprite, UniformsLib.fog]),
11453 vertexShader: ShaderChunk.sprite_vert,
11454 fragmentShader: ShaderChunk.sprite_frag
11459 value: new Matrix3()
11465 vertexShader: ShaderChunk.background_vert,
11466 fragmentShader: ShaderChunk.background_frag
11469 /* -------------------------------------------------------------------------
11471 ------------------------------------------------------------------------- */
11473 uniforms: mergeUniforms([UniformsLib.envmap, {
11478 vertexShader: ShaderChunk.cube_vert,
11479 fragmentShader: ShaderChunk.cube_frag
11487 vertexShader: ShaderChunk.equirect_vert,
11488 fragmentShader: ShaderChunk.equirect_frag
11491 uniforms: mergeUniforms([UniformsLib.common, UniformsLib.displacementmap, {
11492 referencePosition: {
11493 value: new Vector3()
11502 vertexShader: ShaderChunk.distanceRGBA_vert,
11503 fragmentShader: ShaderChunk.distanceRGBA_frag
11506 uniforms: mergeUniforms([UniformsLib.lights, UniformsLib.fog, {
11508 value: new Color(0x00000)
11514 vertexShader: ShaderChunk.shadow_vert,
11515 fragmentShader: ShaderChunk.shadow_frag
11518 ShaderLib.physical = {
11519 uniforms: mergeUniforms([ShaderLib.standard.uniforms, {
11526 clearcoatRoughness: {
11529 clearcoatRoughnessMap: {
11532 clearcoatNormalScale: {
11533 value: new Vector2(1, 1)
11535 clearcoatNormalMap: {
11539 value: new Color(0x000000)
11548 vertexShader: ShaderChunk.meshphysical_vert,
11549 fragmentShader: ShaderChunk.meshphysical_frag
11552 function WebGLBackground(renderer, cubemaps, state, objects, premultipliedAlpha) {
11553 var clearColor = new Color(0x000000);
11554 var clearAlpha = 0;
11557 var currentBackground = null;
11558 var currentBackgroundVersion = 0;
11559 var currentTonemapping = null;
11561 function render(renderList, scene, camera, forceClear) {
11562 var background = scene.isScene === true ? scene.background : null;
11564 if (background && background.isTexture) {
11565 background = cubemaps.get(background);
11566 } // Ignore background in AR
11567 // TODO: Reconsider this.
11570 var xr = renderer.xr;
11571 var session = xr.getSession && xr.getSession();
11573 if (session && session.environmentBlendMode === 'additive') {
11577 if (background === null) {
11578 setClear(clearColor, clearAlpha);
11579 } else if (background && background.isColor) {
11580 setClear(background, 1);
11584 if (renderer.autoClear || forceClear) {
11585 renderer.clear(renderer.autoClearColor, renderer.autoClearDepth, renderer.autoClearStencil);
11588 if (background && (background.isCubeTexture || background.isWebGLCubeRenderTarget || background.mapping === CubeUVReflectionMapping)) {
11589 if (boxMesh === undefined) {
11590 boxMesh = new Mesh(new BoxGeometry(1, 1, 1), new ShaderMaterial({
11591 name: 'BackgroundCubeMaterial',
11592 uniforms: cloneUniforms(ShaderLib.cube.uniforms),
11593 vertexShader: ShaderLib.cube.vertexShader,
11594 fragmentShader: ShaderLib.cube.fragmentShader,
11600 boxMesh.geometry.deleteAttribute('normal');
11601 boxMesh.geometry.deleteAttribute('uv');
11603 boxMesh.onBeforeRender = function (renderer, scene, camera) {
11604 this.matrixWorld.copyPosition(camera.matrixWorld);
11605 }; // enable code injection for non-built-in material
11608 Object.defineProperty(boxMesh.material, 'envMap', {
11609 get: function get() {
11610 return this.uniforms.envMap.value;
11613 objects.update(boxMesh);
11616 if (background.isWebGLCubeRenderTarget) {
11618 background = background.texture;
11621 boxMesh.material.uniforms.envMap.value = background;
11622 boxMesh.material.uniforms.flipEnvMap.value = background.isCubeTexture && background._needsFlipEnvMap ? -1 : 1;
11624 if (currentBackground !== background || currentBackgroundVersion !== background.version || currentTonemapping !== renderer.toneMapping) {
11625 boxMesh.material.needsUpdate = true;
11626 currentBackground = background;
11627 currentBackgroundVersion = background.version;
11628 currentTonemapping = renderer.toneMapping;
11629 } // push to the pre-sorted opaque render list
11632 renderList.unshift(boxMesh, boxMesh.geometry, boxMesh.material, 0, 0, null);
11633 } else if (background && background.isTexture) {
11634 if (planeMesh === undefined) {
11635 planeMesh = new Mesh(new PlaneGeometry(2, 2), new ShaderMaterial({
11636 name: 'BackgroundMaterial',
11637 uniforms: cloneUniforms(ShaderLib.background.uniforms),
11638 vertexShader: ShaderLib.background.vertexShader,
11639 fragmentShader: ShaderLib.background.fragmentShader,
11645 planeMesh.geometry.deleteAttribute('normal'); // enable code injection for non-built-in material
11647 Object.defineProperty(planeMesh.material, 'map', {
11648 get: function get() {
11649 return this.uniforms.t2D.value;
11652 objects.update(planeMesh);
11655 planeMesh.material.uniforms.t2D.value = background;
11657 if (background.matrixAutoUpdate === true) {
11658 background.updateMatrix();
11661 planeMesh.material.uniforms.uvTransform.value.copy(background.matrix);
11663 if (currentBackground !== background || currentBackgroundVersion !== background.version || currentTonemapping !== renderer.toneMapping) {
11664 planeMesh.material.needsUpdate = true;
11665 currentBackground = background;
11666 currentBackgroundVersion = background.version;
11667 currentTonemapping = renderer.toneMapping;
11668 } // push to the pre-sorted opaque render list
11671 renderList.unshift(planeMesh, planeMesh.geometry, planeMesh.material, 0, 0, null);
11675 function setClear(color, alpha) {
11676 state.buffers.color.setClear(color.r, color.g, color.b, alpha, premultipliedAlpha);
11680 getClearColor: function getClearColor() {
11683 setClearColor: function setClearColor(color, alpha) {
11684 if (alpha === void 0) {
11688 clearColor.set(color);
11689 clearAlpha = alpha;
11690 setClear(clearColor, clearAlpha);
11692 getClearAlpha: function getClearAlpha() {
11695 setClearAlpha: function setClearAlpha(alpha) {
11696 clearAlpha = alpha;
11697 setClear(clearColor, clearAlpha);
11703 function WebGLBindingStates(gl, extensions, attributes, capabilities) {
11704 var maxVertexAttributes = gl.getParameter(34921);
11705 var extension = capabilities.isWebGL2 ? null : extensions.get('OES_vertex_array_object');
11706 var vaoAvailable = capabilities.isWebGL2 || extension !== null;
11707 var bindingStates = {};
11708 var defaultState = createBindingState(null);
11709 var currentState = defaultState;
11711 function setup(object, material, program, geometry, index) {
11712 var updateBuffers = false;
11714 if (vaoAvailable) {
11715 var state = getBindingState(geometry, program, material);
11717 if (currentState !== state) {
11718 currentState = state;
11719 bindVertexArrayObject(currentState.object);
11722 updateBuffers = needsUpdate(geometry, index);
11723 if (updateBuffers) saveCache(geometry, index);
11725 var wireframe = material.wireframe === true;
11727 if (currentState.geometry !== geometry.id || currentState.program !== program.id || currentState.wireframe !== wireframe) {
11728 currentState.geometry = geometry.id;
11729 currentState.program = program.id;
11730 currentState.wireframe = wireframe;
11731 updateBuffers = true;
11735 if (object.isInstancedMesh === true) {
11736 updateBuffers = true;
11739 if (index !== null) {
11740 attributes.update(index, 34963);
11743 if (updateBuffers) {
11744 setupVertexAttributes(object, material, program, geometry);
11746 if (index !== null) {
11747 gl.bindBuffer(34963, attributes.get(index).buffer);
11752 function createVertexArrayObject() {
11753 if (capabilities.isWebGL2) return gl.createVertexArray();
11754 return extension.createVertexArrayOES();
11757 function bindVertexArrayObject(vao) {
11758 if (capabilities.isWebGL2) return gl.bindVertexArray(vao);
11759 return extension.bindVertexArrayOES(vao);
11762 function deleteVertexArrayObject(vao) {
11763 if (capabilities.isWebGL2) return gl.deleteVertexArray(vao);
11764 return extension.deleteVertexArrayOES(vao);
11767 function getBindingState(geometry, program, material) {
11768 var wireframe = material.wireframe === true;
11769 var programMap = bindingStates[geometry.id];
11771 if (programMap === undefined) {
11773 bindingStates[geometry.id] = programMap;
11776 var stateMap = programMap[program.id];
11778 if (stateMap === undefined) {
11780 programMap[program.id] = stateMap;
11783 var state = stateMap[wireframe];
11785 if (state === undefined) {
11786 state = createBindingState(createVertexArrayObject());
11787 stateMap[wireframe] = state;
11793 function createBindingState(vao) {
11794 var newAttributes = [];
11795 var enabledAttributes = [];
11796 var attributeDivisors = [];
11798 for (var i = 0; i < maxVertexAttributes; i++) {
11799 newAttributes[i] = 0;
11800 enabledAttributes[i] = 0;
11801 attributeDivisors[i] = 0;
11805 // for backward compatibility on non-VAO support browser
11809 newAttributes: newAttributes,
11810 enabledAttributes: enabledAttributes,
11811 attributeDivisors: attributeDivisors,
11818 function needsUpdate(geometry, index) {
11819 var cachedAttributes = currentState.attributes;
11820 var geometryAttributes = geometry.attributes;
11821 var attributesNum = 0;
11823 for (var key in geometryAttributes) {
11824 var cachedAttribute = cachedAttributes[key];
11825 var geometryAttribute = geometryAttributes[key];
11826 if (cachedAttribute === undefined) return true;
11827 if (cachedAttribute.attribute !== geometryAttribute) return true;
11828 if (cachedAttribute.data !== geometryAttribute.data) return true;
11832 if (currentState.attributesNum !== attributesNum) return true;
11833 if (currentState.index !== index) return true;
11837 function saveCache(geometry, index) {
11839 var attributes = geometry.attributes;
11840 var attributesNum = 0;
11842 for (var key in attributes) {
11843 var attribute = attributes[key];
11845 data.attribute = attribute;
11847 if (attribute.data) {
11848 data.data = attribute.data;
11855 currentState.attributes = cache;
11856 currentState.attributesNum = attributesNum;
11857 currentState.index = index;
11860 function initAttributes() {
11861 var newAttributes = currentState.newAttributes;
11863 for (var i = 0, il = newAttributes.length; i < il; i++) {
11864 newAttributes[i] = 0;
11868 function enableAttribute(attribute) {
11869 enableAttributeAndDivisor(attribute, 0);
11872 function enableAttributeAndDivisor(attribute, meshPerAttribute) {
11873 var newAttributes = currentState.newAttributes;
11874 var enabledAttributes = currentState.enabledAttributes;
11875 var attributeDivisors = currentState.attributeDivisors;
11876 newAttributes[attribute] = 1;
11878 if (enabledAttributes[attribute] === 0) {
11879 gl.enableVertexAttribArray(attribute);
11880 enabledAttributes[attribute] = 1;
11883 if (attributeDivisors[attribute] !== meshPerAttribute) {
11884 var _extension = capabilities.isWebGL2 ? gl : extensions.get('ANGLE_instanced_arrays');
11886 _extension[capabilities.isWebGL2 ? 'vertexAttribDivisor' : 'vertexAttribDivisorANGLE'](attribute, meshPerAttribute);
11888 attributeDivisors[attribute] = meshPerAttribute;
11892 function disableUnusedAttributes() {
11893 var newAttributes = currentState.newAttributes;
11894 var enabledAttributes = currentState.enabledAttributes;
11896 for (var i = 0, il = enabledAttributes.length; i < il; i++) {
11897 if (enabledAttributes[i] !== newAttributes[i]) {
11898 gl.disableVertexAttribArray(i);
11899 enabledAttributes[i] = 0;
11904 function vertexAttribPointer(index, size, type, normalized, stride, offset) {
11905 if (capabilities.isWebGL2 === true && (type === 5124 || type === 5125)) {
11906 gl.vertexAttribIPointer(index, size, type, stride, offset);
11908 gl.vertexAttribPointer(index, size, type, normalized, stride, offset);
11912 function setupVertexAttributes(object, material, program, geometry) {
11913 if (capabilities.isWebGL2 === false && (object.isInstancedMesh || geometry.isInstancedBufferGeometry)) {
11914 if (extensions.get('ANGLE_instanced_arrays') === null) return;
11918 var geometryAttributes = geometry.attributes;
11919 var programAttributes = program.getAttributes();
11920 var materialDefaultAttributeValues = material.defaultAttributeValues;
11922 for (var name in programAttributes) {
11923 var programAttribute = programAttributes[name];
11925 if (programAttribute >= 0) {
11926 var geometryAttribute = geometryAttributes[name];
11928 if (geometryAttribute !== undefined) {
11929 var normalized = geometryAttribute.normalized;
11930 var size = geometryAttribute.itemSize;
11931 var attribute = attributes.get(geometryAttribute); // TODO Attribute may not be available on context restore
11933 if (attribute === undefined) continue;
11934 var buffer = attribute.buffer;
11935 var type = attribute.type;
11936 var bytesPerElement = attribute.bytesPerElement;
11938 if (geometryAttribute.isInterleavedBufferAttribute) {
11939 var data = geometryAttribute.data;
11940 var stride = data.stride;
11941 var offset = geometryAttribute.offset;
11943 if (data && data.isInstancedInterleavedBuffer) {
11944 enableAttributeAndDivisor(programAttribute, data.meshPerAttribute);
11946 if (geometry._maxInstanceCount === undefined) {
11947 geometry._maxInstanceCount = data.meshPerAttribute * data.count;
11950 enableAttribute(programAttribute);
11953 gl.bindBuffer(34962, buffer);
11954 vertexAttribPointer(programAttribute, size, type, normalized, stride * bytesPerElement, offset * bytesPerElement);
11956 if (geometryAttribute.isInstancedBufferAttribute) {
11957 enableAttributeAndDivisor(programAttribute, geometryAttribute.meshPerAttribute);
11959 if (geometry._maxInstanceCount === undefined) {
11960 geometry._maxInstanceCount = geometryAttribute.meshPerAttribute * geometryAttribute.count;
11963 enableAttribute(programAttribute);
11966 gl.bindBuffer(34962, buffer);
11967 vertexAttribPointer(programAttribute, size, type, normalized, 0, 0);
11969 } else if (name === 'instanceMatrix') {
11970 var _attribute = attributes.get(object.instanceMatrix); // TODO Attribute may not be available on context restore
11973 if (_attribute === undefined) continue;
11974 var _buffer = _attribute.buffer;
11975 var _type = _attribute.type;
11976 enableAttributeAndDivisor(programAttribute + 0, 1);
11977 enableAttributeAndDivisor(programAttribute + 1, 1);
11978 enableAttributeAndDivisor(programAttribute + 2, 1);
11979 enableAttributeAndDivisor(programAttribute + 3, 1);
11980 gl.bindBuffer(34962, _buffer);
11981 gl.vertexAttribPointer(programAttribute + 0, 4, _type, false, 64, 0);
11982 gl.vertexAttribPointer(programAttribute + 1, 4, _type, false, 64, 16);
11983 gl.vertexAttribPointer(programAttribute + 2, 4, _type, false, 64, 32);
11984 gl.vertexAttribPointer(programAttribute + 3, 4, _type, false, 64, 48);
11985 } else if (name === 'instanceColor') {
11986 var _attribute2 = attributes.get(object.instanceColor); // TODO Attribute may not be available on context restore
11989 if (_attribute2 === undefined) continue;
11990 var _buffer2 = _attribute2.buffer;
11991 var _type2 = _attribute2.type;
11992 enableAttributeAndDivisor(programAttribute, 1);
11993 gl.bindBuffer(34962, _buffer2);
11994 gl.vertexAttribPointer(programAttribute, 3, _type2, false, 12, 0);
11995 } else if (materialDefaultAttributeValues !== undefined) {
11996 var value = materialDefaultAttributeValues[name];
11998 if (value !== undefined) {
11999 switch (value.length) {
12001 gl.vertexAttrib2fv(programAttribute, value);
12005 gl.vertexAttrib3fv(programAttribute, value);
12009 gl.vertexAttrib4fv(programAttribute, value);
12013 gl.vertexAttrib1fv(programAttribute, value);
12020 disableUnusedAttributes();
12023 function dispose() {
12026 for (var geometryId in bindingStates) {
12027 var programMap = bindingStates[geometryId];
12029 for (var programId in programMap) {
12030 var stateMap = programMap[programId];
12032 for (var wireframe in stateMap) {
12033 deleteVertexArrayObject(stateMap[wireframe].object);
12034 delete stateMap[wireframe];
12037 delete programMap[programId];
12040 delete bindingStates[geometryId];
12044 function releaseStatesOfGeometry(geometry) {
12045 if (bindingStates[geometry.id] === undefined) return;
12046 var programMap = bindingStates[geometry.id];
12048 for (var programId in programMap) {
12049 var stateMap = programMap[programId];
12051 for (var wireframe in stateMap) {
12052 deleteVertexArrayObject(stateMap[wireframe].object);
12053 delete stateMap[wireframe];
12056 delete programMap[programId];
12059 delete bindingStates[geometry.id];
12062 function releaseStatesOfProgram(program) {
12063 for (var geometryId in bindingStates) {
12064 var programMap = bindingStates[geometryId];
12065 if (programMap[program.id] === undefined) continue;
12066 var stateMap = programMap[program.id];
12068 for (var wireframe in stateMap) {
12069 deleteVertexArrayObject(stateMap[wireframe].object);
12070 delete stateMap[wireframe];
12073 delete programMap[program.id];
12078 resetDefaultState();
12079 if (currentState === defaultState) return;
12080 currentState = defaultState;
12081 bindVertexArrayObject(currentState.object);
12082 } // for backward-compatilibity
12085 function resetDefaultState() {
12086 defaultState.geometry = null;
12087 defaultState.program = null;
12088 defaultState.wireframe = false;
12094 resetDefaultState: resetDefaultState,
12096 releaseStatesOfGeometry: releaseStatesOfGeometry,
12097 releaseStatesOfProgram: releaseStatesOfProgram,
12098 initAttributes: initAttributes,
12099 enableAttribute: enableAttribute,
12100 disableUnusedAttributes: disableUnusedAttributes
12104 function WebGLBufferRenderer(gl, extensions, info, capabilities) {
12105 var isWebGL2 = capabilities.isWebGL2;
12108 function setMode(value) {
12112 function render(start, count) {
12113 gl.drawArrays(mode, start, count);
12114 info.update(count, mode, 1);
12117 function renderInstances(start, count, primcount) {
12118 if (primcount === 0) return;
12119 var extension, methodName;
12123 methodName = 'drawArraysInstanced';
12125 extension = extensions.get('ANGLE_instanced_arrays');
12126 methodName = 'drawArraysInstancedANGLE';
12128 if (extension === null) {
12129 console.error('THREE.WebGLBufferRenderer: using THREE.InstancedBufferGeometry but hardware does not support extension ANGLE_instanced_arrays.');
12134 extension[methodName](mode, start, count, primcount);
12135 info.update(count, mode, primcount);
12139 this.setMode = setMode;
12140 this.render = render;
12141 this.renderInstances = renderInstances;
12144 function WebGLCapabilities(gl, extensions, parameters) {
12147 function getMaxAnisotropy() {
12148 if (maxAnisotropy !== undefined) return maxAnisotropy;
12149 var extension = extensions.get('EXT_texture_filter_anisotropic');
12151 if (extension !== null) {
12152 maxAnisotropy = gl.getParameter(extension.MAX_TEXTURE_MAX_ANISOTROPY_EXT);
12157 return maxAnisotropy;
12160 function getMaxPrecision(precision) {
12161 if (precision === 'highp') {
12162 if (gl.getShaderPrecisionFormat(35633, 36338).precision > 0 && gl.getShaderPrecisionFormat(35632, 36338).precision > 0) {
12166 precision = 'mediump';
12169 if (precision === 'mediump') {
12170 if (gl.getShaderPrecisionFormat(35633, 36337).precision > 0 && gl.getShaderPrecisionFormat(35632, 36337).precision > 0) {
12177 /* eslint-disable no-undef */
12180 var isWebGL2 = typeof WebGL2RenderingContext !== 'undefined' && gl instanceof WebGL2RenderingContext || typeof WebGL2ComputeRenderingContext !== 'undefined' && gl instanceof WebGL2ComputeRenderingContext;
12181 /* eslint-enable no-undef */
12183 var precision = parameters.precision !== undefined ? parameters.precision : 'highp';
12184 var maxPrecision = getMaxPrecision(precision);
12186 if (maxPrecision !== precision) {
12187 console.warn('THREE.WebGLRenderer:', precision, 'not supported, using', maxPrecision, 'instead.');
12188 precision = maxPrecision;
12191 var logarithmicDepthBuffer = parameters.logarithmicDepthBuffer === true;
12192 var maxTextures = gl.getParameter(34930);
12193 var maxVertexTextures = gl.getParameter(35660);
12194 var maxTextureSize = gl.getParameter(3379);
12195 var maxCubemapSize = gl.getParameter(34076);
12196 var maxAttributes = gl.getParameter(34921);
12197 var maxVertexUniforms = gl.getParameter(36347);
12198 var maxVaryings = gl.getParameter(36348);
12199 var maxFragmentUniforms = gl.getParameter(36349);
12200 var vertexTextures = maxVertexTextures > 0;
12201 var floatFragmentTextures = isWebGL2 || !!extensions.get('OES_texture_float');
12202 var floatVertexTextures = vertexTextures && floatFragmentTextures;
12203 var maxSamples = isWebGL2 ? gl.getParameter(36183) : 0;
12205 isWebGL2: isWebGL2,
12206 getMaxAnisotropy: getMaxAnisotropy,
12207 getMaxPrecision: getMaxPrecision,
12208 precision: precision,
12209 logarithmicDepthBuffer: logarithmicDepthBuffer,
12210 maxTextures: maxTextures,
12211 maxVertexTextures: maxVertexTextures,
12212 maxTextureSize: maxTextureSize,
12213 maxCubemapSize: maxCubemapSize,
12214 maxAttributes: maxAttributes,
12215 maxVertexUniforms: maxVertexUniforms,
12216 maxVaryings: maxVaryings,
12217 maxFragmentUniforms: maxFragmentUniforms,
12218 vertexTextures: vertexTextures,
12219 floatFragmentTextures: floatFragmentTextures,
12220 floatVertexTextures: floatVertexTextures,
12221 maxSamples: maxSamples
12225 function WebGLClipping(properties) {
12227 var globalState = null,
12228 numGlobalPlanes = 0,
12229 localClippingEnabled = false,
12230 renderingShadows = false;
12231 var plane = new Plane(),
12232 viewNormalMatrix = new Matrix3(),
12237 this.uniform = uniform;
12238 this.numPlanes = 0;
12239 this.numIntersection = 0;
12241 this.init = function (planes, enableLocalClipping, camera) {
12242 var enabled = planes.length !== 0 || enableLocalClipping || // enable state of previous frame - the clipping code has to
12243 // run another frame in order to reset the state:
12244 numGlobalPlanes !== 0 || localClippingEnabled;
12245 localClippingEnabled = enableLocalClipping;
12246 globalState = projectPlanes(planes, camera, 0);
12247 numGlobalPlanes = planes.length;
12251 this.beginShadows = function () {
12252 renderingShadows = true;
12253 projectPlanes(null);
12256 this.endShadows = function () {
12257 renderingShadows = false;
12258 resetGlobalState();
12261 this.setState = function (material, camera, useCache) {
12262 var planes = material.clippingPlanes,
12263 clipIntersection = material.clipIntersection,
12264 clipShadows = material.clipShadows;
12265 var materialProperties = properties.get(material);
12267 if (!localClippingEnabled || planes === null || planes.length === 0 || renderingShadows && !clipShadows) {
12268 // there's no local clipping
12269 if (renderingShadows) {
12270 // there's no global clipping
12271 projectPlanes(null);
12273 resetGlobalState();
12276 var nGlobal = renderingShadows ? 0 : numGlobalPlanes,
12277 lGlobal = nGlobal * 4;
12278 var dstArray = materialProperties.clippingState || null;
12279 uniform.value = dstArray; // ensure unique state
12281 dstArray = projectPlanes(planes, camera, lGlobal, useCache);
12283 for (var i = 0; i !== lGlobal; ++i) {
12284 dstArray[i] = globalState[i];
12287 materialProperties.clippingState = dstArray;
12288 this.numIntersection = clipIntersection ? this.numPlanes : 0;
12289 this.numPlanes += nGlobal;
12293 function resetGlobalState() {
12294 if (uniform.value !== globalState) {
12295 uniform.value = globalState;
12296 uniform.needsUpdate = numGlobalPlanes > 0;
12299 scope.numPlanes = numGlobalPlanes;
12300 scope.numIntersection = 0;
12303 function projectPlanes(planes, camera, dstOffset, skipTransform) {
12304 var nPlanes = planes !== null ? planes.length : 0;
12305 var dstArray = null;
12307 if (nPlanes !== 0) {
12308 dstArray = uniform.value;
12310 if (skipTransform !== true || dstArray === null) {
12311 var flatSize = dstOffset + nPlanes * 4,
12312 viewMatrix = camera.matrixWorldInverse;
12313 viewNormalMatrix.getNormalMatrix(viewMatrix);
12315 if (dstArray === null || dstArray.length < flatSize) {
12316 dstArray = new Float32Array(flatSize);
12319 for (var i = 0, i4 = dstOffset; i !== nPlanes; ++i, i4 += 4) {
12320 plane.copy(planes[i]).applyMatrix4(viewMatrix, viewNormalMatrix);
12321 plane.normal.toArray(dstArray, i4);
12322 dstArray[i4 + 3] = plane.constant;
12326 uniform.value = dstArray;
12327 uniform.needsUpdate = true;
12330 scope.numPlanes = nPlanes;
12331 scope.numIntersection = 0;
12336 function WebGLCubeMaps(renderer) {
12337 var cubemaps = new WeakMap();
12339 function mapTextureMapping(texture, mapping) {
12340 if (mapping === EquirectangularReflectionMapping) {
12341 texture.mapping = CubeReflectionMapping;
12342 } else if (mapping === EquirectangularRefractionMapping) {
12343 texture.mapping = CubeRefractionMapping;
12349 function get(texture) {
12350 if (texture && texture.isTexture) {
12351 var mapping = texture.mapping;
12353 if (mapping === EquirectangularReflectionMapping || mapping === EquirectangularRefractionMapping) {
12354 if (cubemaps.has(texture)) {
12355 var cubemap = cubemaps.get(texture).texture;
12356 return mapTextureMapping(cubemap, texture.mapping);
12358 var image = texture.image;
12360 if (image && image.height > 0) {
12361 var currentRenderList = renderer.getRenderList();
12362 var currentRenderTarget = renderer.getRenderTarget();
12363 var renderTarget = new WebGLCubeRenderTarget(image.height / 2);
12364 renderTarget.fromEquirectangularTexture(renderer, texture);
12365 cubemaps.set(texture, renderTarget);
12366 renderer.setRenderTarget(currentRenderTarget);
12367 renderer.setRenderList(currentRenderList);
12368 texture.addEventListener('dispose', onTextureDispose);
12369 return mapTextureMapping(renderTarget.texture, texture.mapping);
12371 // image not yet ready. try the conversion next frame
12381 function onTextureDispose(event) {
12382 var texture = event.target;
12383 texture.removeEventListener('dispose', onTextureDispose);
12384 var cubemap = cubemaps.get(texture);
12386 if (cubemap !== undefined) {
12387 cubemaps.delete(texture);
12392 function dispose() {
12393 cubemaps = new WeakMap();
12402 function WebGLExtensions(gl) {
12403 var extensions = {};
12405 function getExtension(name) {
12406 if (extensions[name] !== undefined) {
12407 return extensions[name];
12413 case 'WEBGL_depth_texture':
12414 extension = gl.getExtension('WEBGL_depth_texture') || gl.getExtension('MOZ_WEBGL_depth_texture') || gl.getExtension('WEBKIT_WEBGL_depth_texture');
12417 case 'EXT_texture_filter_anisotropic':
12418 extension = gl.getExtension('EXT_texture_filter_anisotropic') || gl.getExtension('MOZ_EXT_texture_filter_anisotropic') || gl.getExtension('WEBKIT_EXT_texture_filter_anisotropic');
12421 case 'WEBGL_compressed_texture_s3tc':
12422 extension = gl.getExtension('WEBGL_compressed_texture_s3tc') || gl.getExtension('MOZ_WEBGL_compressed_texture_s3tc') || gl.getExtension('WEBKIT_WEBGL_compressed_texture_s3tc');
12425 case 'WEBGL_compressed_texture_pvrtc':
12426 extension = gl.getExtension('WEBGL_compressed_texture_pvrtc') || gl.getExtension('WEBKIT_WEBGL_compressed_texture_pvrtc');
12430 extension = gl.getExtension(name);
12433 extensions[name] = extension;
12438 has: function has(name) {
12439 return getExtension(name) !== null;
12441 init: function init(capabilities) {
12442 if (capabilities.isWebGL2) {
12443 getExtension('EXT_color_buffer_float');
12445 getExtension('WEBGL_depth_texture');
12446 getExtension('OES_texture_float');
12447 getExtension('OES_texture_half_float');
12448 getExtension('OES_texture_half_float_linear');
12449 getExtension('OES_standard_derivatives');
12450 getExtension('OES_element_index_uint');
12451 getExtension('OES_vertex_array_object');
12452 getExtension('ANGLE_instanced_arrays');
12455 getExtension('OES_texture_float_linear');
12456 getExtension('EXT_color_buffer_half_float');
12458 get: function get(name) {
12459 var extension = getExtension(name);
12461 if (extension === null) {
12462 console.warn('THREE.WebGLRenderer: ' + name + ' extension not supported.');
12470 function WebGLGeometries(gl, attributes, info, bindingStates) {
12471 var geometries = {};
12472 var wireframeAttributes = new WeakMap();
12474 function onGeometryDispose(event) {
12475 var geometry = event.target;
12477 if (geometry.index !== null) {
12478 attributes.remove(geometry.index);
12481 for (var name in geometry.attributes) {
12482 attributes.remove(geometry.attributes[name]);
12485 geometry.removeEventListener('dispose', onGeometryDispose);
12486 delete geometries[geometry.id];
12487 var attribute = wireframeAttributes.get(geometry);
12490 attributes.remove(attribute);
12491 wireframeAttributes.delete(geometry);
12494 bindingStates.releaseStatesOfGeometry(geometry);
12496 if (geometry.isInstancedBufferGeometry === true) {
12497 delete geometry._maxInstanceCount;
12501 info.memory.geometries--;
12504 function get(object, geometry) {
12505 if (geometries[geometry.id] === true) return geometry;
12506 geometry.addEventListener('dispose', onGeometryDispose);
12507 geometries[geometry.id] = true;
12508 info.memory.geometries++;
12512 function update(geometry) {
12513 var geometryAttributes = geometry.attributes; // Updating index buffer in VAO now. See WebGLBindingStates.
12515 for (var name in geometryAttributes) {
12516 attributes.update(geometryAttributes[name], 34962);
12520 var morphAttributes = geometry.morphAttributes;
12522 for (var _name in morphAttributes) {
12523 var array = morphAttributes[_name];
12525 for (var i = 0, l = array.length; i < l; i++) {
12526 attributes.update(array[i], 34962);
12531 function updateWireframeAttribute(geometry) {
12533 var geometryIndex = geometry.index;
12534 var geometryPosition = geometry.attributes.position;
12537 if (geometryIndex !== null) {
12538 var array = geometryIndex.array;
12539 version = geometryIndex.version;
12541 for (var i = 0, l = array.length; i < l; i += 3) {
12542 var a = array[i + 0];
12543 var b = array[i + 1];
12544 var c = array[i + 2];
12545 indices.push(a, b, b, c, c, a);
12548 var _array = geometryPosition.array;
12549 version = geometryPosition.version;
12551 for (var _i = 0, _l = _array.length / 3 - 1; _i < _l; _i += 3) {
12558 indices.push(_a, _b, _b, _c, _c, _a);
12562 var attribute = new (arrayMax(indices) > 65535 ? Uint32BufferAttribute : Uint16BufferAttribute)(indices, 1);
12563 attribute.version = version; // Updating index buffer in VAO now. See WebGLBindingStates
12566 var previousAttribute = wireframeAttributes.get(geometry);
12567 if (previousAttribute) attributes.remove(previousAttribute); //
12569 wireframeAttributes.set(geometry, attribute);
12572 function getWireframeAttribute(geometry) {
12573 var currentAttribute = wireframeAttributes.get(geometry);
12575 if (currentAttribute) {
12576 var geometryIndex = geometry.index;
12578 if (geometryIndex !== null) {
12579 // if the attribute is obsolete, create a new one
12580 if (currentAttribute.version < geometryIndex.version) {
12581 updateWireframeAttribute(geometry);
12585 updateWireframeAttribute(geometry);
12588 return wireframeAttributes.get(geometry);
12594 getWireframeAttribute: getWireframeAttribute
12598 function WebGLIndexedBufferRenderer(gl, extensions, info, capabilities) {
12599 var isWebGL2 = capabilities.isWebGL2;
12602 function setMode(value) {
12606 var type, bytesPerElement;
12608 function setIndex(value) {
12610 bytesPerElement = value.bytesPerElement;
12613 function render(start, count) {
12614 gl.drawElements(mode, count, type, start * bytesPerElement);
12615 info.update(count, mode, 1);
12618 function renderInstances(start, count, primcount) {
12619 if (primcount === 0) return;
12620 var extension, methodName;
12624 methodName = 'drawElementsInstanced';
12626 extension = extensions.get('ANGLE_instanced_arrays');
12627 methodName = 'drawElementsInstancedANGLE';
12629 if (extension === null) {
12630 console.error('THREE.WebGLIndexedBufferRenderer: using THREE.InstancedBufferGeometry but hardware does not support extension ANGLE_instanced_arrays.');
12635 extension[methodName](mode, count, type, start * bytesPerElement, primcount);
12636 info.update(count, mode, primcount);
12640 this.setMode = setMode;
12641 this.setIndex = setIndex;
12642 this.render = render;
12643 this.renderInstances = renderInstances;
12646 function WebGLInfo(gl) {
12659 function update(count, mode, instanceCount) {
12664 render.triangles += instanceCount * (count / 3);
12668 render.lines += instanceCount * (count / 2);
12672 render.lines += instanceCount * (count - 1);
12676 render.lines += instanceCount * count;
12680 render.points += instanceCount * count;
12684 console.error('THREE.WebGLInfo: Unknown draw mode:', mode);
12692 render.triangles = 0;
12707 function numericalSort(a, b) {
12708 return a[0] - b[0];
12711 function absNumericalSort(a, b) {
12712 return Math.abs(b[1]) - Math.abs(a[1]);
12715 function WebGLMorphtargets(gl) {
12716 var influencesList = {};
12717 var morphInfluences = new Float32Array(8);
12718 var workInfluences = [];
12720 for (var i = 0; i < 8; i++) {
12721 workInfluences[i] = [i, 0];
12724 function update(object, geometry, material, program) {
12725 var objectInfluences = object.morphTargetInfluences; // When object doesn't have morph target influences defined, we treat it as a 0-length array
12726 // This is important to make sure we set up morphTargetBaseInfluence / morphTargetInfluences
12728 var length = objectInfluences === undefined ? 0 : objectInfluences.length;
12729 var influences = influencesList[geometry.id];
12731 if (influences === undefined) {
12735 for (var _i = 0; _i < length; _i++) {
12736 influences[_i] = [_i, 0];
12739 influencesList[geometry.id] = influences;
12740 } // Collect influences
12743 for (var _i2 = 0; _i2 < length; _i2++) {
12744 var influence = influences[_i2];
12745 influence[0] = _i2;
12746 influence[1] = objectInfluences[_i2];
12749 influences.sort(absNumericalSort);
12751 for (var _i3 = 0; _i3 < 8; _i3++) {
12752 if (_i3 < length && influences[_i3][1]) {
12753 workInfluences[_i3][0] = influences[_i3][0];
12754 workInfluences[_i3][1] = influences[_i3][1];
12756 workInfluences[_i3][0] = Number.MAX_SAFE_INTEGER;
12757 workInfluences[_i3][1] = 0;
12761 workInfluences.sort(numericalSort);
12762 var morphTargets = material.morphTargets && geometry.morphAttributes.position;
12763 var morphNormals = material.morphNormals && geometry.morphAttributes.normal;
12764 var morphInfluencesSum = 0;
12766 for (var _i4 = 0; _i4 < 8; _i4++) {
12767 var _influence = workInfluences[_i4];
12768 var index = _influence[0];
12769 var value = _influence[1];
12771 if (index !== Number.MAX_SAFE_INTEGER && value) {
12772 if (morphTargets && geometry.getAttribute('morphTarget' + _i4) !== morphTargets[index]) {
12773 geometry.setAttribute('morphTarget' + _i4, morphTargets[index]);
12776 if (morphNormals && geometry.getAttribute('morphNormal' + _i4) !== morphNormals[index]) {
12777 geometry.setAttribute('morphNormal' + _i4, morphNormals[index]);
12780 morphInfluences[_i4] = value;
12781 morphInfluencesSum += value;
12783 if (morphTargets && geometry.hasAttribute('morphTarget' + _i4) === true) {
12784 geometry.deleteAttribute('morphTarget' + _i4);
12787 if (morphNormals && geometry.hasAttribute('morphNormal' + _i4) === true) {
12788 geometry.deleteAttribute('morphNormal' + _i4);
12791 morphInfluences[_i4] = 0;
12793 } // GLSL shader uses formula baseinfluence * base + sum(target * influence)
12794 // This allows us to switch between absolute morphs and relative morphs without changing shader code
12795 // When baseinfluence = 1 - sum(influence), the above is equivalent to sum((target - base) * influence)
12798 var morphBaseInfluence = geometry.morphTargetsRelative ? 1 : 1 - morphInfluencesSum;
12799 program.getUniforms().setValue(gl, 'morphTargetBaseInfluence', morphBaseInfluence);
12800 program.getUniforms().setValue(gl, 'morphTargetInfluences', morphInfluences);
12808 function WebGLObjects(gl, geometries, attributes, info) {
12809 var updateMap = new WeakMap();
12811 function update(object) {
12812 var frame = info.render.frame;
12813 var geometry = object.geometry;
12814 var buffergeometry = geometries.get(object, geometry); // Update once per frame
12816 if (updateMap.get(buffergeometry) !== frame) {
12817 geometries.update(buffergeometry);
12818 updateMap.set(buffergeometry, frame);
12821 if (object.isInstancedMesh) {
12822 if (object.hasEventListener('dispose', onInstancedMeshDispose) === false) {
12823 object.addEventListener('dispose', onInstancedMeshDispose);
12826 attributes.update(object.instanceMatrix, 34962);
12828 if (object.instanceColor !== null) {
12829 attributes.update(object.instanceColor, 34962);
12833 return buffergeometry;
12836 function dispose() {
12837 updateMap = new WeakMap();
12840 function onInstancedMeshDispose(event) {
12841 var instancedMesh = event.target;
12842 instancedMesh.removeEventListener('dispose', onInstancedMeshDispose);
12843 attributes.remove(instancedMesh.instanceMatrix);
12844 if (instancedMesh.instanceColor !== null) attributes.remove(instancedMesh.instanceColor);
12853 function DataTexture2DArray(data, width, height, depth) {
12854 if (data === void 0) {
12858 if (width === void 0) {
12862 if (height === void 0) {
12866 if (depth === void 0) {
12870 Texture.call(this, null);
12877 this.magFilter = NearestFilter;
12878 this.minFilter = NearestFilter;
12879 this.wrapR = ClampToEdgeWrapping;
12880 this.generateMipmaps = false;
12881 this.flipY = false;
12882 this.needsUpdate = true;
12885 DataTexture2DArray.prototype = Object.create(Texture.prototype);
12886 DataTexture2DArray.prototype.constructor = DataTexture2DArray;
12887 DataTexture2DArray.prototype.isDataTexture2DArray = true;
12889 function DataTexture3D(data, width, height, depth) {
12890 if (data === void 0) {
12894 if (width === void 0) {
12898 if (height === void 0) {
12902 if (depth === void 0) {
12906 // We're going to add .setXXX() methods for setting properties later.
12907 // Users can still set in DataTexture3D directly.
12909 // const texture = new THREE.DataTexture3D( data, width, height, depth );
12910 // texture.anisotropy = 16;
12913 Texture.call(this, null);
12920 this.magFilter = NearestFilter;
12921 this.minFilter = NearestFilter;
12922 this.wrapR = ClampToEdgeWrapping;
12923 this.generateMipmaps = false;
12924 this.flipY = false;
12925 this.needsUpdate = true;
12928 DataTexture3D.prototype = Object.create(Texture.prototype);
12929 DataTexture3D.prototype.constructor = DataTexture3D;
12930 DataTexture3D.prototype.isDataTexture3D = true;
12933 * Uniforms of a program.
12934 * Those form a tree structure with a special top-level container for the root,
12935 * which you get by calling 'new WebGLUniforms( gl, program )'.
12938 * Properties of inner nodes including the top-level container:
12940 * .seq - array of nested uniforms
12941 * .map - nested uniforms by name
12944 * Methods of all nodes except the top-level container:
12946 * .setValue( gl, value, [textures] )
12948 * uploads a uniform value(s)
12949 * the 'textures' parameter is needed for sampler uniforms
12952 * Static methods of the top-level container (textures factorizations):
12954 * .upload( gl, seq, values, textures )
12956 * sets uniforms in 'seq' to 'values[id].value'
12958 * .seqWithValue( seq, values ) : filteredSeq
12960 * filters 'seq' entries with corresponding entry in values
12963 * Methods of the top-level container (textures factorizations):
12965 * .setValue( gl, name, value, textures )
12967 * sets uniform with name 'name' to 'value'
12969 * .setOptional( gl, obj, prop )
12971 * like .set for an optional property of the object
12974 var emptyTexture = new Texture();
12975 var emptyTexture2dArray = new DataTexture2DArray();
12976 var emptyTexture3d = new DataTexture3D();
12977 var emptyCubeTexture = new CubeTexture(); // --- Utilities ---
12978 // Array Caches (provide typed arrays for temporary by size)
12980 var arrayCacheF32 = [];
12981 var arrayCacheI32 = []; // Float32Array caches used for uploading Matrix uniforms
12983 var mat4array = new Float32Array(16);
12984 var mat3array = new Float32Array(9);
12985 var mat2array = new Float32Array(4); // Flattening for arrays of vectors and matrices
12987 function flatten(array, nBlocks, blockSize) {
12988 var firstElem = array[0];
12989 if (firstElem <= 0 || firstElem > 0) return array; // unoptimized: ! isNaN( firstElem )
12990 // see http://jacksondunstan.com/articles/983
12992 var n = nBlocks * blockSize;
12993 var r = arrayCacheF32[n];
12995 if (r === undefined) {
12996 r = new Float32Array(n);
12997 arrayCacheF32[n] = r;
13000 if (nBlocks !== 0) {
13001 firstElem.toArray(r, 0);
13003 for (var i = 1, offset = 0; i !== nBlocks; ++i) {
13004 offset += blockSize;
13005 array[i].toArray(r, offset);
13012 function arraysEqual(a, b) {
13013 if (a.length !== b.length) return false;
13015 for (var i = 0, l = a.length; i < l; i++) {
13016 if (a[i] !== b[i]) return false;
13022 function copyArray(a, b) {
13023 for (var i = 0, l = b.length; i < l; i++) {
13026 } // Texture unit allocation
13029 function allocTexUnits(textures, n) {
13030 var r = arrayCacheI32[n];
13032 if (r === undefined) {
13033 r = new Int32Array(n);
13034 arrayCacheI32[n] = r;
13037 for (var i = 0; i !== n; ++i) {
13038 r[i] = textures.allocateTextureUnit();
13042 } // --- Setters ---
13043 // Note: Defining these methods externally, because they come in a bunch
13044 // and this way their names minify.
13048 function setValueV1f(gl, v) {
13049 var cache = this.cache;
13050 if (cache[0] === v) return;
13051 gl.uniform1f(this.addr, v);
13053 } // Single float vector (from flat array or THREE.VectorN)
13056 function setValueV2f(gl, v) {
13057 var cache = this.cache;
13059 if (v.x !== undefined) {
13060 if (cache[0] !== v.x || cache[1] !== v.y) {
13061 gl.uniform2f(this.addr, v.x, v.y);
13066 if (arraysEqual(cache, v)) return;
13067 gl.uniform2fv(this.addr, v);
13068 copyArray(cache, v);
13072 function setValueV3f(gl, v) {
13073 var cache = this.cache;
13075 if (v.x !== undefined) {
13076 if (cache[0] !== v.x || cache[1] !== v.y || cache[2] !== v.z) {
13077 gl.uniform3f(this.addr, v.x, v.y, v.z);
13082 } else if (v.r !== undefined) {
13083 if (cache[0] !== v.r || cache[1] !== v.g || cache[2] !== v.b) {
13084 gl.uniform3f(this.addr, v.r, v.g, v.b);
13090 if (arraysEqual(cache, v)) return;
13091 gl.uniform3fv(this.addr, v);
13092 copyArray(cache, v);
13096 function setValueV4f(gl, v) {
13097 var cache = this.cache;
13099 if (v.x !== undefined) {
13100 if (cache[0] !== v.x || cache[1] !== v.y || cache[2] !== v.z || cache[3] !== v.w) {
13101 gl.uniform4f(this.addr, v.x, v.y, v.z, v.w);
13108 if (arraysEqual(cache, v)) return;
13109 gl.uniform4fv(this.addr, v);
13110 copyArray(cache, v);
13112 } // Single matrix (from flat array or MatrixN)
13115 function setValueM2(gl, v) {
13116 var cache = this.cache;
13117 var elements = v.elements;
13119 if (elements === undefined) {
13120 if (arraysEqual(cache, v)) return;
13121 gl.uniformMatrix2fv(this.addr, false, v);
13122 copyArray(cache, v);
13124 if (arraysEqual(cache, elements)) return;
13125 mat2array.set(elements);
13126 gl.uniformMatrix2fv(this.addr, false, mat2array);
13127 copyArray(cache, elements);
13131 function setValueM3(gl, v) {
13132 var cache = this.cache;
13133 var elements = v.elements;
13135 if (elements === undefined) {
13136 if (arraysEqual(cache, v)) return;
13137 gl.uniformMatrix3fv(this.addr, false, v);
13138 copyArray(cache, v);
13140 if (arraysEqual(cache, elements)) return;
13141 mat3array.set(elements);
13142 gl.uniformMatrix3fv(this.addr, false, mat3array);
13143 copyArray(cache, elements);
13147 function setValueM4(gl, v) {
13148 var cache = this.cache;
13149 var elements = v.elements;
13151 if (elements === undefined) {
13152 if (arraysEqual(cache, v)) return;
13153 gl.uniformMatrix4fv(this.addr, false, v);
13154 copyArray(cache, v);
13156 if (arraysEqual(cache, elements)) return;
13157 mat4array.set(elements);
13158 gl.uniformMatrix4fv(this.addr, false, mat4array);
13159 copyArray(cache, elements);
13161 } // Single texture (2D / Cube)
13164 function setValueT1(gl, v, textures) {
13165 var cache = this.cache;
13166 var unit = textures.allocateTextureUnit();
13168 if (cache[0] !== unit) {
13169 gl.uniform1i(this.addr, unit);
13173 textures.safeSetTexture2D(v || emptyTexture, unit);
13176 function setValueT2DArray1(gl, v, textures) {
13177 var cache = this.cache;
13178 var unit = textures.allocateTextureUnit();
13180 if (cache[0] !== unit) {
13181 gl.uniform1i(this.addr, unit);
13185 textures.setTexture2DArray(v || emptyTexture2dArray, unit);
13188 function setValueT3D1(gl, v, textures) {
13189 var cache = this.cache;
13190 var unit = textures.allocateTextureUnit();
13192 if (cache[0] !== unit) {
13193 gl.uniform1i(this.addr, unit);
13197 textures.setTexture3D(v || emptyTexture3d, unit);
13200 function setValueT6(gl, v, textures) {
13201 var cache = this.cache;
13202 var unit = textures.allocateTextureUnit();
13204 if (cache[0] !== unit) {
13205 gl.uniform1i(this.addr, unit);
13209 textures.safeSetTextureCube(v || emptyCubeTexture, unit);
13210 } // Integer / Boolean vectors or arrays thereof (always flat arrays)
13213 function setValueV1i(gl, v) {
13214 var cache = this.cache;
13215 if (cache[0] === v) return;
13216 gl.uniform1i(this.addr, v);
13220 function setValueV2i(gl, v) {
13221 var cache = this.cache;
13222 if (arraysEqual(cache, v)) return;
13223 gl.uniform2iv(this.addr, v);
13224 copyArray(cache, v);
13227 function setValueV3i(gl, v) {
13228 var cache = this.cache;
13229 if (arraysEqual(cache, v)) return;
13230 gl.uniform3iv(this.addr, v);
13231 copyArray(cache, v);
13234 function setValueV4i(gl, v) {
13235 var cache = this.cache;
13236 if (arraysEqual(cache, v)) return;
13237 gl.uniform4iv(this.addr, v);
13238 copyArray(cache, v);
13242 function setValueV1ui(gl, v) {
13243 var cache = this.cache;
13244 if (cache[0] === v) return;
13245 gl.uniform1ui(this.addr, v);
13247 } // Helper to pick the right setter for the singular case
13250 function getSingularSetter(type) {
13253 return setValueV1f;
13257 return setValueV2f;
13261 return setValueV3f;
13265 return setValueV4f;
13282 return setValueV1i;
13287 return setValueV2i;
13292 return setValueV3i;
13297 return setValueV4i;
13301 return setValueV1ui;
13304 case 0x8b5e: // SAMPLER_2D
13306 case 0x8d66: // SAMPLER_EXTERNAL_OES
13308 case 0x8dca: // INT_SAMPLER_2D
13310 case 0x8dd2: // UNSIGNED_INT_SAMPLER_2D
13313 // SAMPLER_2D_SHADOW
13316 case 0x8b5f: // SAMPLER_3D
13318 case 0x8dcb: // INT_SAMPLER_3D
13321 // UNSIGNED_INT_SAMPLER_3D
13322 return setValueT3D1;
13324 case 0x8b60: // SAMPLER_CUBE
13326 case 0x8dcc: // INT_SAMPLER_CUBE
13328 case 0x8dd4: // UNSIGNED_INT_SAMPLER_CUBE
13331 // SAMPLER_CUBE_SHADOW
13334 case 0x8dc1: // SAMPLER_2D_ARRAY
13336 case 0x8dcf: // INT_SAMPLER_2D_ARRAY
13338 case 0x8dd7: // UNSIGNED_INT_SAMPLER_2D_ARRAY
13341 // SAMPLER_2D_ARRAY_SHADOW
13342 return setValueT2DArray1;
13344 } // Array of scalars
13347 function setValueV1fArray(gl, v) {
13348 gl.uniform1fv(this.addr, v);
13349 } // Integer / Boolean vectors or arrays thereof (always flat arrays)
13352 function setValueV1iArray(gl, v) {
13353 gl.uniform1iv(this.addr, v);
13356 function setValueV2iArray(gl, v) {
13357 gl.uniform2iv(this.addr, v);
13360 function setValueV3iArray(gl, v) {
13361 gl.uniform3iv(this.addr, v);
13364 function setValueV4iArray(gl, v) {
13365 gl.uniform4iv(this.addr, v);
13366 } // Array of vectors (flat or from THREE classes)
13369 function setValueV2fArray(gl, v) {
13370 var data = flatten(v, this.size, 2);
13371 gl.uniform2fv(this.addr, data);
13374 function setValueV3fArray(gl, v) {
13375 var data = flatten(v, this.size, 3);
13376 gl.uniform3fv(this.addr, data);
13379 function setValueV4fArray(gl, v) {
13380 var data = flatten(v, this.size, 4);
13381 gl.uniform4fv(this.addr, data);
13382 } // Array of matrices (flat or from THREE clases)
13385 function setValueM2Array(gl, v) {
13386 var data = flatten(v, this.size, 4);
13387 gl.uniformMatrix2fv(this.addr, false, data);
13390 function setValueM3Array(gl, v) {
13391 var data = flatten(v, this.size, 9);
13392 gl.uniformMatrix3fv(this.addr, false, data);
13395 function setValueM4Array(gl, v) {
13396 var data = flatten(v, this.size, 16);
13397 gl.uniformMatrix4fv(this.addr, false, data);
13398 } // Array of textures (2D / Cube)
13401 function setValueT1Array(gl, v, textures) {
13403 var units = allocTexUnits(textures, n);
13404 gl.uniform1iv(this.addr, units);
13406 for (var i = 0; i !== n; ++i) {
13407 textures.safeSetTexture2D(v[i] || emptyTexture, units[i]);
13411 function setValueT6Array(gl, v, textures) {
13413 var units = allocTexUnits(textures, n);
13414 gl.uniform1iv(this.addr, units);
13416 for (var i = 0; i !== n; ++i) {
13417 textures.safeSetTextureCube(v[i] || emptyCubeTexture, units[i]);
13419 } // Helper to pick the right setter for a pure (bottom-level) array
13422 function getPureArraySetter(type) {
13425 return setValueV1fArray;
13429 return setValueV2fArray;
13433 return setValueV3fArray;
13437 return setValueV4fArray;
13441 return setValueM2Array;
13445 return setValueM3Array;
13449 return setValueM4Array;
13454 return setValueV1iArray;
13459 return setValueV2iArray;
13464 return setValueV3iArray;
13469 return setValueV4iArray;
13472 case 0x8b5e: // SAMPLER_2D
13474 case 0x8d66: // SAMPLER_EXTERNAL_OES
13476 case 0x8dca: // INT_SAMPLER_2D
13478 case 0x8dd2: // UNSIGNED_INT_SAMPLER_2D
13481 // SAMPLER_2D_SHADOW
13482 return setValueT1Array;
13484 case 0x8b60: // SAMPLER_CUBE
13486 case 0x8dcc: // INT_SAMPLER_CUBE
13488 case 0x8dd4: // UNSIGNED_INT_SAMPLER_CUBE
13491 // SAMPLER_CUBE_SHADOW
13492 return setValueT6Array;
13494 } // --- Uniform Classes ---
13497 function SingleUniform(id, activeInfo, addr) {
13501 this.setValue = getSingularSetter(activeInfo.type); // this.path = activeInfo.name; // DEBUG
13504 function PureArrayUniform(id, activeInfo, addr) {
13508 this.size = activeInfo.size;
13509 this.setValue = getPureArraySetter(activeInfo.type); // this.path = activeInfo.name; // DEBUG
13512 PureArrayUniform.prototype.updateCache = function (data) {
13513 var cache = this.cache;
13515 if (data instanceof Float32Array && cache.length !== data.length) {
13516 this.cache = new Float32Array(data.length);
13519 copyArray(cache, data);
13522 function StructuredUniform(id) {
13528 StructuredUniform.prototype.setValue = function (gl, value, textures) {
13529 var seq = this.seq;
13531 for (var i = 0, n = seq.length; i !== n; ++i) {
13533 u.setValue(gl, value[u.id], textures);
13535 }; // --- Top-level ---
13536 // Parser - builds up the property tree from the path strings
13539 var RePathPart = /(\w+)(\])?(\[|\.)?/g; // extracts
13540 // - the identifier (member name or array index)
13541 // - followed by an optional right bracket (found when array index)
13542 // - followed by an optional left bracket or dot (type of subscript)
13544 // Note: These portions can be read in a non-overlapping fashion and
13545 // allow straightforward parsing of the hierarchy that WebGL encodes
13546 // in the uniform names.
13548 function addUniform(container, uniformObject) {
13549 container.seq.push(uniformObject);
13550 container.map[uniformObject.id] = uniformObject;
13553 function parseUniform(activeInfo, addr, container) {
13554 var path = activeInfo.name,
13555 pathLength = path.length; // reset RegExp object, because of the early exit of a previous run
13557 RePathPart.lastIndex = 0;
13560 var match = RePathPart.exec(path),
13561 matchEnd = RePathPart.lastIndex;
13563 var idIsIndex = match[2] === ']',
13564 subscript = match[3];
13565 if (idIsIndex) id = id | 0; // convert to integer
13567 if (subscript === undefined || subscript === '[' && matchEnd + 2 === pathLength) {
13568 // bare name or "pure" bottom-level array "[0]" suffix
13569 addUniform(container, subscript === undefined ? new SingleUniform(id, activeInfo, addr) : new PureArrayUniform(id, activeInfo, addr));
13572 // step into inner node / create it in case it doesn't exist
13573 var map = container.map;
13574 var next = map[id];
13576 if (next === undefined) {
13577 next = new StructuredUniform(id);
13578 addUniform(container, next);
13584 } // Root Container
13587 function WebGLUniforms(gl, program) {
13590 var n = gl.getProgramParameter(program, 35718);
13592 for (var i = 0; i < n; ++i) {
13593 var info = gl.getActiveUniform(program, i),
13594 addr = gl.getUniformLocation(program, info.name);
13595 parseUniform(info, addr, this);
13599 WebGLUniforms.prototype.setValue = function (gl, name, value, textures) {
13600 var u = this.map[name];
13601 if (u !== undefined) u.setValue(gl, value, textures);
13604 WebGLUniforms.prototype.setOptional = function (gl, object, name) {
13605 var v = object[name];
13606 if (v !== undefined) this.setValue(gl, name, v);
13607 }; // Static interface
13610 WebGLUniforms.upload = function (gl, seq, values, textures) {
13611 for (var i = 0, n = seq.length; i !== n; ++i) {
13615 if (v.needsUpdate !== false) {
13616 // note: always updating when .needsUpdate is undefined
13617 u.setValue(gl, v.value, textures);
13622 WebGLUniforms.seqWithValue = function (seq, values) {
13625 for (var i = 0, n = seq.length; i !== n; ++i) {
13627 if (u.id in values) r.push(u);
13633 function WebGLShader(gl, type, string) {
13634 var shader = gl.createShader(type);
13635 gl.shaderSource(shader, string);
13636 gl.compileShader(shader);
13640 var programIdCount = 0;
13642 function addLineNumbers(string) {
13643 var lines = string.split('\n');
13645 for (var i = 0; i < lines.length; i++) {
13646 lines[i] = i + 1 + ': ' + lines[i];
13649 return lines.join('\n');
13652 function getEncodingComponents(encoding) {
13653 switch (encoding) {
13654 case LinearEncoding:
13655 return ['Linear', '( value )'];
13658 return ['sRGB', '( value )'];
13661 return ['RGBE', '( value )'];
13663 case RGBM7Encoding:
13664 return ['RGBM', '( value, 7.0 )'];
13666 case RGBM16Encoding:
13667 return ['RGBM', '( value, 16.0 )'];
13670 return ['RGBD', '( value, 256.0 )'];
13672 case GammaEncoding:
13673 return ['Gamma', '( value, float( GAMMA_FACTOR ) )'];
13675 case LogLuvEncoding:
13676 return ['LogLuv', '( value )'];
13679 console.warn('THREE.WebGLProgram: Unsupported encoding:', encoding);
13680 return ['Linear', '( value )'];
13684 function getShaderErrors(gl, shader, type) {
13685 var status = gl.getShaderParameter(shader, 35713);
13686 var log = gl.getShaderInfoLog(shader).trim();
13687 if (status && log === '') return ''; // --enable-privileged-webgl-extension
13688 // console.log( '**' + type + '**', gl.getExtension( 'WEBGL_debug_shaders' ).getTranslatedShaderSource( shader ) );
13690 var source = gl.getShaderSource(shader);
13691 return 'THREE.WebGLShader: gl.getShaderInfoLog() ' + type + '\n' + log + addLineNumbers(source);
13694 function getTexelDecodingFunction(functionName, encoding) {
13695 var components = getEncodingComponents(encoding);
13696 return 'vec4 ' + functionName + '( vec4 value ) { return ' + components[0] + 'ToLinear' + components[1] + '; }';
13699 function getTexelEncodingFunction(functionName, encoding) {
13700 var components = getEncodingComponents(encoding);
13701 return 'vec4 ' + functionName + '( vec4 value ) { return LinearTo' + components[0] + components[1] + '; }';
13704 function getToneMappingFunction(functionName, toneMapping) {
13705 var toneMappingName;
13707 switch (toneMapping) {
13708 case LinearToneMapping:
13709 toneMappingName = 'Linear';
13712 case ReinhardToneMapping:
13713 toneMappingName = 'Reinhard';
13716 case CineonToneMapping:
13717 toneMappingName = 'OptimizedCineon';
13720 case ACESFilmicToneMapping:
13721 toneMappingName = 'ACESFilmic';
13724 case CustomToneMapping:
13725 toneMappingName = 'Custom';
13729 console.warn('THREE.WebGLProgram: Unsupported toneMapping:', toneMapping);
13730 toneMappingName = 'Linear';
13733 return 'vec3 ' + functionName + '( vec3 color ) { return ' + toneMappingName + 'ToneMapping( color ); }';
13736 function generateExtensions(parameters) {
13737 var chunks = [parameters.extensionDerivatives || parameters.envMapCubeUV || parameters.bumpMap || parameters.tangentSpaceNormalMap || parameters.clearcoatNormalMap || parameters.flatShading || parameters.shaderID === 'physical' ? '#extension GL_OES_standard_derivatives : enable' : '', (parameters.extensionFragDepth || parameters.logarithmicDepthBuffer) && parameters.rendererExtensionFragDepth ? '#extension GL_EXT_frag_depth : enable' : '', parameters.extensionDrawBuffers && parameters.rendererExtensionDrawBuffers ? '#extension GL_EXT_draw_buffers : require' : '', (parameters.extensionShaderTextureLOD || parameters.envMap) && parameters.rendererExtensionShaderTextureLod ? '#extension GL_EXT_shader_texture_lod : enable' : ''];
13738 return chunks.filter(filterEmptyLine).join('\n');
13741 function generateDefines(defines) {
13744 for (var name in defines) {
13745 var value = defines[name];
13746 if (value === false) continue;
13747 chunks.push('#define ' + name + ' ' + value);
13750 return chunks.join('\n');
13753 function fetchAttributeLocations(gl, program) {
13754 var attributes = {};
13755 var n = gl.getProgramParameter(program, 35721);
13757 for (var i = 0; i < n; i++) {
13758 var info = gl.getActiveAttrib(program, i);
13759 var name = info.name; // console.log( 'THREE.WebGLProgram: ACTIVE VERTEX ATTRIBUTE:', name, i );
13761 attributes[name] = gl.getAttribLocation(program, name);
13767 function filterEmptyLine(string) {
13768 return string !== '';
13771 function replaceLightNums(string, parameters) {
13772 return string.replace(/NUM_DIR_LIGHTS/g, parameters.numDirLights).replace(/NUM_SPOT_LIGHTS/g, parameters.numSpotLights).replace(/NUM_RECT_AREA_LIGHTS/g, parameters.numRectAreaLights).replace(/NUM_POINT_LIGHTS/g, parameters.numPointLights).replace(/NUM_HEMI_LIGHTS/g, parameters.numHemiLights).replace(/NUM_DIR_LIGHT_SHADOWS/g, parameters.numDirLightShadows).replace(/NUM_SPOT_LIGHT_SHADOWS/g, parameters.numSpotLightShadows).replace(/NUM_POINT_LIGHT_SHADOWS/g, parameters.numPointLightShadows);
13775 function replaceClippingPlaneNums(string, parameters) {
13776 return string.replace(/NUM_CLIPPING_PLANES/g, parameters.numClippingPlanes).replace(/UNION_CLIPPING_PLANES/g, parameters.numClippingPlanes - parameters.numClipIntersection);
13777 } // Resolve Includes
13780 var includePattern = /^[ \t]*#include +<([\w\d./]+)>/gm;
13782 function resolveIncludes(string) {
13783 return string.replace(includePattern, includeReplacer);
13786 function includeReplacer(match, include) {
13787 var string = ShaderChunk[include];
13789 if (string === undefined) {
13790 throw new Error('Can not resolve #include <' + include + '>');
13793 return resolveIncludes(string);
13797 var deprecatedUnrollLoopPattern = /#pragma unroll_loop[\s]+?for \( int i \= (\d+)\; i < (\d+)\; i \+\+ \) \{([\s\S]+?)(?=\})\}/g;
13798 var unrollLoopPattern = /#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;
13800 function unrollLoops(string) {
13801 return string.replace(unrollLoopPattern, loopReplacer).replace(deprecatedUnrollLoopPattern, deprecatedLoopReplacer);
13804 function deprecatedLoopReplacer(match, start, end, snippet) {
13805 console.warn('WebGLProgram: #pragma unroll_loop shader syntax is deprecated. Please use #pragma unroll_loop_start syntax instead.');
13806 return loopReplacer(match, start, end, snippet);
13809 function loopReplacer(match, start, end, snippet) {
13812 for (var i = parseInt(start); i < parseInt(end); i++) {
13813 string += snippet.replace(/\[\s*i\s*\]/g, '[ ' + i + ' ]').replace(/UNROLLED_LOOP_INDEX/g, i);
13820 function generatePrecision(parameters) {
13821 var precisionstring = 'precision ' + parameters.precision + ' float;\nprecision ' + parameters.precision + ' int;';
13823 if (parameters.precision === 'highp') {
13824 precisionstring += '\n#define HIGH_PRECISION';
13825 } else if (parameters.precision === 'mediump') {
13826 precisionstring += '\n#define MEDIUM_PRECISION';
13827 } else if (parameters.precision === 'lowp') {
13828 precisionstring += '\n#define LOW_PRECISION';
13831 return precisionstring;
13834 function generateShadowMapTypeDefine(parameters) {
13835 var shadowMapTypeDefine = 'SHADOWMAP_TYPE_BASIC';
13837 if (parameters.shadowMapType === PCFShadowMap) {
13838 shadowMapTypeDefine = 'SHADOWMAP_TYPE_PCF';
13839 } else if (parameters.shadowMapType === PCFSoftShadowMap) {
13840 shadowMapTypeDefine = 'SHADOWMAP_TYPE_PCF_SOFT';
13841 } else if (parameters.shadowMapType === VSMShadowMap) {
13842 shadowMapTypeDefine = 'SHADOWMAP_TYPE_VSM';
13845 return shadowMapTypeDefine;
13848 function generateEnvMapTypeDefine(parameters) {
13849 var envMapTypeDefine = 'ENVMAP_TYPE_CUBE';
13851 if (parameters.envMap) {
13852 switch (parameters.envMapMode) {
13853 case CubeReflectionMapping:
13854 case CubeRefractionMapping:
13855 envMapTypeDefine = 'ENVMAP_TYPE_CUBE';
13858 case CubeUVReflectionMapping:
13859 case CubeUVRefractionMapping:
13860 envMapTypeDefine = 'ENVMAP_TYPE_CUBE_UV';
13865 return envMapTypeDefine;
13868 function generateEnvMapModeDefine(parameters) {
13869 var envMapModeDefine = 'ENVMAP_MODE_REFLECTION';
13871 if (parameters.envMap) {
13872 switch (parameters.envMapMode) {
13873 case CubeRefractionMapping:
13874 case CubeUVRefractionMapping:
13875 envMapModeDefine = 'ENVMAP_MODE_REFRACTION';
13880 return envMapModeDefine;
13883 function generateEnvMapBlendingDefine(parameters) {
13884 var envMapBlendingDefine = 'ENVMAP_BLENDING_NONE';
13886 if (parameters.envMap) {
13887 switch (parameters.combine) {
13888 case MultiplyOperation:
13889 envMapBlendingDefine = 'ENVMAP_BLENDING_MULTIPLY';
13893 envMapBlendingDefine = 'ENVMAP_BLENDING_MIX';
13897 envMapBlendingDefine = 'ENVMAP_BLENDING_ADD';
13902 return envMapBlendingDefine;
13905 function WebGLProgram(renderer, cacheKey, parameters, bindingStates) {
13906 var gl = renderer.getContext();
13907 var defines = parameters.defines;
13908 var vertexShader = parameters.vertexShader;
13909 var fragmentShader = parameters.fragmentShader;
13910 var shadowMapTypeDefine = generateShadowMapTypeDefine(parameters);
13911 var envMapTypeDefine = generateEnvMapTypeDefine(parameters);
13912 var envMapModeDefine = generateEnvMapModeDefine(parameters);
13913 var envMapBlendingDefine = generateEnvMapBlendingDefine(parameters);
13914 var gammaFactorDefine = renderer.gammaFactor > 0 ? renderer.gammaFactor : 1.0;
13915 var customExtensions = parameters.isWebGL2 ? '' : generateExtensions(parameters);
13916 var customDefines = generateDefines(defines);
13917 var program = gl.createProgram();
13918 var prefixVertex, prefixFragment;
13919 var versionString = parameters.glslVersion ? '#version ' + parameters.glslVersion + '\n' : '';
13921 if (parameters.isRawShaderMaterial) {
13922 prefixVertex = [customDefines].filter(filterEmptyLine).join('\n');
13924 if (prefixVertex.length > 0) {
13925 prefixVertex += '\n';
13928 prefixFragment = [customExtensions, customDefines].filter(filterEmptyLine).join('\n');
13930 if (prefixFragment.length > 0) {
13931 prefixFragment += '\n';
13934 prefixVertex = [generatePrecision(parameters), '#define SHADER_NAME ' + parameters.shaderName, customDefines, parameters.instancing ? '#define USE_INSTANCING' : '', parameters.instancingColor ? '#define USE_INSTANCING_COLOR' : '', parameters.supportsVertexTextures ? '#define VERTEX_TEXTURES' : '', '#define GAMMA_FACTOR ' + gammaFactorDefine, '#define MAX_BONES ' + parameters.maxBones, parameters.useFog && parameters.fog ? '#define USE_FOG' : '', parameters.useFog && parameters.fogExp2 ? '#define FOG_EXP2' : '', parameters.map ? '#define USE_MAP' : '', parameters.envMap ? '#define USE_ENVMAP' : '', parameters.envMap ? '#define ' + envMapModeDefine : '', parameters.lightMap ? '#define USE_LIGHTMAP' : '', parameters.aoMap ? '#define USE_AOMAP' : '', parameters.emissiveMap ? '#define USE_EMISSIVEMAP' : '', parameters.bumpMap ? '#define USE_BUMPMAP' : '', parameters.normalMap ? '#define USE_NORMALMAP' : '', parameters.normalMap && parameters.objectSpaceNormalMap ? '#define OBJECTSPACE_NORMALMAP' : '', parameters.normalMap && parameters.tangentSpaceNormalMap ? '#define TANGENTSPACE_NORMALMAP' : '', parameters.clearcoatMap ? '#define USE_CLEARCOATMAP' : '', parameters.clearcoatRoughnessMap ? '#define USE_CLEARCOAT_ROUGHNESSMAP' : '', parameters.clearcoatNormalMap ? '#define USE_CLEARCOAT_NORMALMAP' : '', parameters.displacementMap && parameters.supportsVertexTextures ? '#define USE_DISPLACEMENTMAP' : '', parameters.specularMap ? '#define USE_SPECULARMAP' : '', parameters.roughnessMap ? '#define USE_ROUGHNESSMAP' : '', parameters.metalnessMap ? '#define USE_METALNESSMAP' : '', parameters.alphaMap ? '#define USE_ALPHAMAP' : '', parameters.transmissionMap ? '#define USE_TRANSMISSIONMAP' : '', parameters.vertexTangents ? '#define USE_TANGENT' : '', parameters.vertexColors ? '#define USE_COLOR' : '', parameters.vertexUvs ? '#define USE_UV' : '', parameters.uvsVertexOnly ? '#define UVS_VERTEX_ONLY' : '', parameters.flatShading ? '#define FLAT_SHADED' : '', parameters.skinning ? '#define USE_SKINNING' : '', parameters.useVertexTexture ? '#define BONE_TEXTURE' : '', parameters.morphTargets ? '#define USE_MORPHTARGETS' : '', parameters.morphNormals && parameters.flatShading === false ? '#define USE_MORPHNORMALS' : '', parameters.doubleSided ? '#define DOUBLE_SIDED' : '', parameters.flipSided ? '#define FLIP_SIDED' : '', parameters.shadowMapEnabled ? '#define USE_SHADOWMAP' : '', parameters.shadowMapEnabled ? '#define ' + shadowMapTypeDefine : '', parameters.sizeAttenuation ? '#define USE_SIZEATTENUATION' : '', parameters.logarithmicDepthBuffer ? '#define USE_LOGDEPTHBUF' : '', parameters.logarithmicDepthBuffer && parameters.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_TANGENT', ' attribute vec4 tangent;', '#endif', '#ifdef USE_COLOR', ' attribute vec3 color;', '#endif', '#ifdef USE_MORPHTARGETS', ' 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', '\n'].filter(filterEmptyLine).join('\n');
13935 prefixFragment = [customExtensions, generatePrecision(parameters), '#define SHADER_NAME ' + parameters.shaderName, customDefines, parameters.alphaTest ? '#define ALPHATEST ' + parameters.alphaTest + (parameters.alphaTest % 1 ? '' : '.0') : '', // add '.0' if integer
13936 '#define GAMMA_FACTOR ' + gammaFactorDefine, parameters.useFog && parameters.fog ? '#define USE_FOG' : '', parameters.useFog && parameters.fogExp2 ? '#define FOG_EXP2' : '', parameters.map ? '#define USE_MAP' : '', parameters.matcap ? '#define USE_MATCAP' : '', parameters.envMap ? '#define USE_ENVMAP' : '', parameters.envMap ? '#define ' + envMapTypeDefine : '', parameters.envMap ? '#define ' + envMapModeDefine : '', parameters.envMap ? '#define ' + envMapBlendingDefine : '', parameters.lightMap ? '#define USE_LIGHTMAP' : '', parameters.aoMap ? '#define USE_AOMAP' : '', parameters.emissiveMap ? '#define USE_EMISSIVEMAP' : '', parameters.bumpMap ? '#define USE_BUMPMAP' : '', parameters.normalMap ? '#define USE_NORMALMAP' : '', parameters.normalMap && parameters.objectSpaceNormalMap ? '#define OBJECTSPACE_NORMALMAP' : '', parameters.normalMap && parameters.tangentSpaceNormalMap ? '#define TANGENTSPACE_NORMALMAP' : '', parameters.clearcoatMap ? '#define USE_CLEARCOATMAP' : '', parameters.clearcoatRoughnessMap ? '#define USE_CLEARCOAT_ROUGHNESSMAP' : '', parameters.clearcoatNormalMap ? '#define USE_CLEARCOAT_NORMALMAP' : '', parameters.specularMap ? '#define USE_SPECULARMAP' : '', parameters.roughnessMap ? '#define USE_ROUGHNESSMAP' : '', parameters.metalnessMap ? '#define USE_METALNESSMAP' : '', parameters.alphaMap ? '#define USE_ALPHAMAP' : '', parameters.sheen ? '#define USE_SHEEN' : '', parameters.transmissionMap ? '#define USE_TRANSMISSIONMAP' : '', parameters.vertexTangents ? '#define USE_TANGENT' : '', parameters.vertexColors || parameters.instancingColor ? '#define USE_COLOR' : '', parameters.vertexUvs ? '#define USE_UV' : '', parameters.uvsVertexOnly ? '#define UVS_VERTEX_ONLY' : '', parameters.gradientMap ? '#define USE_GRADIENTMAP' : '', parameters.flatShading ? '#define FLAT_SHADED' : '', parameters.doubleSided ? '#define DOUBLE_SIDED' : '', parameters.flipSided ? '#define FLIP_SIDED' : '', parameters.shadowMapEnabled ? '#define USE_SHADOWMAP' : '', parameters.shadowMapEnabled ? '#define ' + shadowMapTypeDefine : '', parameters.premultipliedAlpha ? '#define PREMULTIPLIED_ALPHA' : '', parameters.physicallyCorrectLights ? '#define PHYSICALLY_CORRECT_LIGHTS' : '', parameters.logarithmicDepthBuffer ? '#define USE_LOGDEPTHBUF' : '', parameters.logarithmicDepthBuffer && parameters.rendererExtensionFragDepth ? '#define USE_LOGDEPTHBUF_EXT' : '', (parameters.extensionShaderTextureLOD || parameters.envMap) && parameters.rendererExtensionShaderTextureLod ? '#define TEXTURE_LOD_EXT' : '', 'uniform mat4 viewMatrix;', 'uniform vec3 cameraPosition;', 'uniform bool isOrthographic;', parameters.toneMapping !== NoToneMapping ? '#define TONE_MAPPING' : '', parameters.toneMapping !== NoToneMapping ? ShaderChunk['tonemapping_pars_fragment'] : '', // this code is required here because it is used by the toneMapping() function defined below
13937 parameters.toneMapping !== NoToneMapping ? getToneMappingFunction('toneMapping', parameters.toneMapping) : '', parameters.dithering ? '#define DITHERING' : '', ShaderChunk['encodings_pars_fragment'], // this code is required here because it is used by the various encoding/decoding function defined below
13938 parameters.map ? getTexelDecodingFunction('mapTexelToLinear', parameters.mapEncoding) : '', parameters.matcap ? getTexelDecodingFunction('matcapTexelToLinear', parameters.matcapEncoding) : '', parameters.envMap ? getTexelDecodingFunction('envMapTexelToLinear', parameters.envMapEncoding) : '', parameters.emissiveMap ? getTexelDecodingFunction('emissiveMapTexelToLinear', parameters.emissiveMapEncoding) : '', parameters.lightMap ? getTexelDecodingFunction('lightMapTexelToLinear', parameters.lightMapEncoding) : '', getTexelEncodingFunction('linearToOutputTexel', parameters.outputEncoding), parameters.depthPacking ? '#define DEPTH_PACKING ' + parameters.depthPacking : '', '\n'].filter(filterEmptyLine).join('\n');
13941 vertexShader = resolveIncludes(vertexShader);
13942 vertexShader = replaceLightNums(vertexShader, parameters);
13943 vertexShader = replaceClippingPlaneNums(vertexShader, parameters);
13944 fragmentShader = resolveIncludes(fragmentShader);
13945 fragmentShader = replaceLightNums(fragmentShader, parameters);
13946 fragmentShader = replaceClippingPlaneNums(fragmentShader, parameters);
13947 vertexShader = unrollLoops(vertexShader);
13948 fragmentShader = unrollLoops(fragmentShader);
13950 if (parameters.isWebGL2 && parameters.isRawShaderMaterial !== true) {
13951 // GLSL 3.0 conversion for built-in materials and ShaderMaterial
13952 versionString = '#version 300 es\n';
13953 prefixVertex = ['#define attribute in', '#define varying out', '#define texture2D texture'].join('\n') + '\n' + prefixVertex;
13954 prefixFragment = ['#define varying in', parameters.glslVersion === GLSL3 ? '' : 'out highp vec4 pc_fragColor;', parameters.glslVersion === GLSL3 ? '' : '#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('\n') + '\n' + prefixFragment;
13957 var vertexGlsl = versionString + prefixVertex + vertexShader;
13958 var fragmentGlsl = versionString + prefixFragment + fragmentShader; // console.log( '*VERTEX*', vertexGlsl );
13959 // console.log( '*FRAGMENT*', fragmentGlsl );
13961 var glVertexShader = WebGLShader(gl, 35633, vertexGlsl);
13962 var glFragmentShader = WebGLShader(gl, 35632, fragmentGlsl);
13963 gl.attachShader(program, glVertexShader);
13964 gl.attachShader(program, glFragmentShader); // Force a particular attribute to index 0.
13966 if (parameters.index0AttributeName !== undefined) {
13967 gl.bindAttribLocation(program, 0, parameters.index0AttributeName);
13968 } else if (parameters.morphTargets === true) {
13969 // programs with morphTargets displace position out of attribute 0
13970 gl.bindAttribLocation(program, 0, 'position');
13973 gl.linkProgram(program); // check for link errors
13975 if (renderer.debug.checkShaderErrors) {
13976 var programLog = gl.getProgramInfoLog(program).trim();
13977 var vertexLog = gl.getShaderInfoLog(glVertexShader).trim();
13978 var fragmentLog = gl.getShaderInfoLog(glFragmentShader).trim();
13979 var runnable = true;
13980 var haveDiagnostics = true;
13982 if (gl.getProgramParameter(program, 35714) === false) {
13984 var vertexErrors = getShaderErrors(gl, glVertexShader, 'vertex');
13985 var fragmentErrors = getShaderErrors(gl, glFragmentShader, 'fragment');
13986 console.error('THREE.WebGLProgram: shader error: ', gl.getError(), '35715', gl.getProgramParameter(program, 35715), 'gl.getProgramInfoLog', programLog, vertexErrors, fragmentErrors);
13987 } else if (programLog !== '') {
13988 console.warn('THREE.WebGLProgram: gl.getProgramInfoLog()', programLog);
13989 } else if (vertexLog === '' || fragmentLog === '') {
13990 haveDiagnostics = false;
13993 if (haveDiagnostics) {
13994 this.diagnostics = {
13995 runnable: runnable,
13996 programLog: programLog,
13999 prefix: prefixVertex
14003 prefix: prefixFragment
14008 // Crashes in iOS9 and iOS10. #18402
14009 // gl.detachShader( program, glVertexShader );
14010 // gl.detachShader( program, glFragmentShader );
14013 gl.deleteShader(glVertexShader);
14014 gl.deleteShader(glFragmentShader); // set up caching for uniform locations
14016 var cachedUniforms;
14018 this.getUniforms = function () {
14019 if (cachedUniforms === undefined) {
14020 cachedUniforms = new WebGLUniforms(gl, program);
14023 return cachedUniforms;
14024 }; // set up caching for attribute locations
14027 var cachedAttributes;
14029 this.getAttributes = function () {
14030 if (cachedAttributes === undefined) {
14031 cachedAttributes = fetchAttributeLocations(gl, program);
14034 return cachedAttributes;
14035 }; // free resource
14038 this.destroy = function () {
14039 bindingStates.releaseStatesOfProgram(this);
14040 gl.deleteProgram(program);
14041 this.program = undefined;
14045 this.name = parameters.shaderName;
14046 this.id = programIdCount++;
14047 this.cacheKey = cacheKey;
14048 this.usedTimes = 1;
14049 this.program = program;
14050 this.vertexShader = glVertexShader;
14051 this.fragmentShader = glFragmentShader;
14055 function WebGLPrograms(renderer, cubemaps, extensions, capabilities, bindingStates, clipping) {
14057 var isWebGL2 = capabilities.isWebGL2;
14058 var logarithmicDepthBuffer = capabilities.logarithmicDepthBuffer;
14059 var floatVertexTextures = capabilities.floatVertexTextures;
14060 var maxVertexUniforms = capabilities.maxVertexUniforms;
14061 var vertexTextures = capabilities.vertexTextures;
14062 var precision = capabilities.precision;
14064 MeshDepthMaterial: 'depth',
14065 MeshDistanceMaterial: 'distanceRGBA',
14066 MeshNormalMaterial: 'normal',
14067 MeshBasicMaterial: 'basic',
14068 MeshLambertMaterial: 'lambert',
14069 MeshPhongMaterial: 'phong',
14070 MeshToonMaterial: 'toon',
14071 MeshStandardMaterial: 'physical',
14072 MeshPhysicalMaterial: 'physical',
14073 MeshMatcapMaterial: 'matcap',
14074 LineBasicMaterial: 'basic',
14075 LineDashedMaterial: 'dashed',
14076 PointsMaterial: 'points',
14077 ShadowMaterial: 'shadow',
14078 SpriteMaterial: 'sprite'
14080 var parameterNames = ['precision', 'isWebGL2', 'supportsVertexTextures', 'outputEncoding', 'instancing', 'instancingColor', 'map', 'mapEncoding', 'matcap', 'matcapEncoding', 'envMap', 'envMapMode', 'envMapEncoding', 'envMapCubeUV', 'lightMap', 'lightMapEncoding', 'aoMap', 'emissiveMap', 'emissiveMapEncoding', 'bumpMap', 'normalMap', 'objectSpaceNormalMap', 'tangentSpaceNormalMap', 'clearcoatMap', 'clearcoatRoughnessMap', 'clearcoatNormalMap', 'displacementMap', 'specularMap', 'roughnessMap', 'metalnessMap', 'gradientMap', 'alphaMap', 'combine', 'vertexColors', 'vertexTangents', 'vertexUvs', 'uvsVertexOnly', 'fog', 'useFog', 'fogExp2', 'flatShading', 'sizeAttenuation', 'logarithmicDepthBuffer', 'skinning', 'maxBones', 'useVertexTexture', 'morphTargets', 'morphNormals', 'maxMorphTargets', 'maxMorphNormals', 'premultipliedAlpha', 'numDirLights', 'numPointLights', 'numSpotLights', 'numHemiLights', 'numRectAreaLights', 'numDirLightShadows', 'numPointLightShadows', 'numSpotLightShadows', 'shadowMapEnabled', 'shadowMapType', 'toneMapping', 'physicallyCorrectLights', 'alphaTest', 'doubleSided', 'flipSided', 'numClippingPlanes', 'numClipIntersection', 'depthPacking', 'dithering', 'sheen', 'transmissionMap'];
14082 function getMaxBones(object) {
14083 var skeleton = object.skeleton;
14084 var bones = skeleton.bones;
14086 if (floatVertexTextures) {
14089 // default for when object is not specified
14090 // ( for example when prebuilding shader to be used with multiple objects )
14092 // - leave some extra space for other uniforms
14093 // - limit here is ANGLE's 254 max uniform vectors
14094 // (up to 54 should be safe)
14095 var nVertexUniforms = maxVertexUniforms;
14096 var nVertexMatrices = Math.floor((nVertexUniforms - 20) / 4);
14097 var maxBones = Math.min(nVertexMatrices, bones.length);
14099 if (maxBones < bones.length) {
14100 console.warn('THREE.WebGLRenderer: Skeleton has ' + bones.length + ' bones. This GPU supports ' + maxBones + '.');
14108 function getTextureEncodingFromMap(map) {
14111 if (map && map.isTexture) {
14112 encoding = map.encoding;
14113 } else if (map && map.isWebGLRenderTarget) {
14114 console.warn('THREE.WebGLPrograms.getTextureEncodingFromMap: don\'t use render targets as textures. Use their .texture property instead.');
14115 encoding = map.texture.encoding;
14117 encoding = LinearEncoding;
14123 function getParameters(material, lights, shadows, scene, object) {
14124 var fog = scene.fog;
14125 var environment = material.isMeshStandardMaterial ? scene.environment : null;
14126 var envMap = cubemaps.get(material.envMap || environment);
14127 var shaderID = shaderIDs[material.type]; // heuristics to create shader parameters according to lights in the scene
14128 // (not to blow over maxLights budget)
14130 var maxBones = object.isSkinnedMesh ? getMaxBones(object) : 0;
14132 if (material.precision !== null) {
14133 precision = capabilities.getMaxPrecision(material.precision);
14135 if (precision !== material.precision) {
14136 console.warn('THREE.WebGLProgram.getParameters:', material.precision, 'not supported, using', precision, 'instead.');
14140 var vertexShader, fragmentShader;
14143 var shader = ShaderLib[shaderID];
14144 vertexShader = shader.vertexShader;
14145 fragmentShader = shader.fragmentShader;
14147 vertexShader = material.vertexShader;
14148 fragmentShader = material.fragmentShader;
14151 var currentRenderTarget = renderer.getRenderTarget();
14153 isWebGL2: isWebGL2,
14154 shaderID: shaderID,
14155 shaderName: material.type,
14156 vertexShader: vertexShader,
14157 fragmentShader: fragmentShader,
14158 defines: material.defines,
14159 isRawShaderMaterial: material.isRawShaderMaterial === true,
14160 glslVersion: material.glslVersion,
14161 precision: precision,
14162 instancing: object.isInstancedMesh === true,
14163 instancingColor: object.isInstancedMesh === true && object.instanceColor !== null,
14164 supportsVertexTextures: vertexTextures,
14165 outputEncoding: currentRenderTarget !== null ? getTextureEncodingFromMap(currentRenderTarget.texture) : renderer.outputEncoding,
14166 map: !!material.map,
14167 mapEncoding: getTextureEncodingFromMap(material.map),
14168 matcap: !!material.matcap,
14169 matcapEncoding: getTextureEncodingFromMap(material.matcap),
14171 envMapMode: envMap && envMap.mapping,
14172 envMapEncoding: getTextureEncodingFromMap(envMap),
14173 envMapCubeUV: !!envMap && (envMap.mapping === CubeUVReflectionMapping || envMap.mapping === CubeUVRefractionMapping),
14174 lightMap: !!material.lightMap,
14175 lightMapEncoding: getTextureEncodingFromMap(material.lightMap),
14176 aoMap: !!material.aoMap,
14177 emissiveMap: !!material.emissiveMap,
14178 emissiveMapEncoding: getTextureEncodingFromMap(material.emissiveMap),
14179 bumpMap: !!material.bumpMap,
14180 normalMap: !!material.normalMap,
14181 objectSpaceNormalMap: material.normalMapType === ObjectSpaceNormalMap,
14182 tangentSpaceNormalMap: material.normalMapType === TangentSpaceNormalMap,
14183 clearcoatMap: !!material.clearcoatMap,
14184 clearcoatRoughnessMap: !!material.clearcoatRoughnessMap,
14185 clearcoatNormalMap: !!material.clearcoatNormalMap,
14186 displacementMap: !!material.displacementMap,
14187 roughnessMap: !!material.roughnessMap,
14188 metalnessMap: !!material.metalnessMap,
14189 specularMap: !!material.specularMap,
14190 alphaMap: !!material.alphaMap,
14191 gradientMap: !!material.gradientMap,
14192 sheen: !!material.sheen,
14193 transmissionMap: !!material.transmissionMap,
14194 combine: material.combine,
14195 vertexTangents: material.normalMap && material.vertexTangents,
14196 vertexColors: material.vertexColors,
14197 vertexUvs: !!material.map || !!material.bumpMap || !!material.normalMap || !!material.specularMap || !!material.alphaMap || !!material.emissiveMap || !!material.roughnessMap || !!material.metalnessMap || !!material.clearcoatMap || !!material.clearcoatRoughnessMap || !!material.clearcoatNormalMap || !!material.displacementMap || !!material.transmissionMap,
14198 uvsVertexOnly: !(!!material.map || !!material.bumpMap || !!material.normalMap || !!material.specularMap || !!material.alphaMap || !!material.emissiveMap || !!material.roughnessMap || !!material.metalnessMap || !!material.clearcoatNormalMap || !!material.transmissionMap) && !!material.displacementMap,
14200 useFog: material.fog,
14201 fogExp2: fog && fog.isFogExp2,
14202 flatShading: material.flatShading,
14203 sizeAttenuation: material.sizeAttenuation,
14204 logarithmicDepthBuffer: logarithmicDepthBuffer,
14205 skinning: material.skinning && maxBones > 0,
14206 maxBones: maxBones,
14207 useVertexTexture: floatVertexTextures,
14208 morphTargets: material.morphTargets,
14209 morphNormals: material.morphNormals,
14210 maxMorphTargets: renderer.maxMorphTargets,
14211 maxMorphNormals: renderer.maxMorphNormals,
14212 numDirLights: lights.directional.length,
14213 numPointLights: lights.point.length,
14214 numSpotLights: lights.spot.length,
14215 numRectAreaLights: lights.rectArea.length,
14216 numHemiLights: lights.hemi.length,
14217 numDirLightShadows: lights.directionalShadowMap.length,
14218 numPointLightShadows: lights.pointShadowMap.length,
14219 numSpotLightShadows: lights.spotShadowMap.length,
14220 numClippingPlanes: clipping.numPlanes,
14221 numClipIntersection: clipping.numIntersection,
14222 dithering: material.dithering,
14223 shadowMapEnabled: renderer.shadowMap.enabled && shadows.length > 0,
14224 shadowMapType: renderer.shadowMap.type,
14225 toneMapping: material.toneMapped ? renderer.toneMapping : NoToneMapping,
14226 physicallyCorrectLights: renderer.physicallyCorrectLights,
14227 premultipliedAlpha: material.premultipliedAlpha,
14228 alphaTest: material.alphaTest,
14229 doubleSided: material.side === DoubleSide,
14230 flipSided: material.side === BackSide,
14231 depthPacking: material.depthPacking !== undefined ? material.depthPacking : false,
14232 index0AttributeName: material.index0AttributeName,
14233 extensionDerivatives: material.extensions && material.extensions.derivatives,
14234 extensionFragDepth: material.extensions && material.extensions.fragDepth,
14235 extensionDrawBuffers: material.extensions && material.extensions.drawBuffers,
14236 extensionShaderTextureLOD: material.extensions && material.extensions.shaderTextureLOD,
14237 rendererExtensionFragDepth: isWebGL2 || extensions.has('EXT_frag_depth'),
14238 rendererExtensionDrawBuffers: isWebGL2 || extensions.has('WEBGL_draw_buffers'),
14239 rendererExtensionShaderTextureLod: isWebGL2 || extensions.has('EXT_shader_texture_lod'),
14240 customProgramCacheKey: material.customProgramCacheKey()
14245 function getProgramCacheKey(parameters) {
14248 if (parameters.shaderID) {
14249 array.push(parameters.shaderID);
14251 array.push(parameters.fragmentShader);
14252 array.push(parameters.vertexShader);
14255 if (parameters.defines !== undefined) {
14256 for (var name in parameters.defines) {
14258 array.push(parameters.defines[name]);
14262 if (parameters.isRawShaderMaterial === false) {
14263 for (var i = 0; i < parameterNames.length; i++) {
14264 array.push(parameters[parameterNames[i]]);
14267 array.push(renderer.outputEncoding);
14268 array.push(renderer.gammaFactor);
14271 array.push(parameters.customProgramCacheKey);
14272 return array.join();
14275 function getUniforms(material) {
14276 var shaderID = shaderIDs[material.type];
14280 var shader = ShaderLib[shaderID];
14281 uniforms = UniformsUtils.clone(shader.uniforms);
14283 uniforms = material.uniforms;
14289 function acquireProgram(parameters, cacheKey) {
14290 var program; // Check if code has been already compiled
14292 for (var p = 0, pl = programs.length; p < pl; p++) {
14293 var preexistingProgram = programs[p];
14295 if (preexistingProgram.cacheKey === cacheKey) {
14296 program = preexistingProgram;
14297 ++program.usedTimes;
14302 if (program === undefined) {
14303 program = new WebGLProgram(renderer, cacheKey, parameters, bindingStates);
14304 programs.push(program);
14310 function releaseProgram(program) {
14311 if (--program.usedTimes === 0) {
14312 // Remove from unordered set
14313 var i = programs.indexOf(program);
14314 programs[i] = programs[programs.length - 1];
14315 programs.pop(); // Free WebGL resources
14322 getParameters: getParameters,
14323 getProgramCacheKey: getProgramCacheKey,
14324 getUniforms: getUniforms,
14325 acquireProgram: acquireProgram,
14326 releaseProgram: releaseProgram,
14327 // Exposed for resource monitoring & error feedback via renderer.info:
14332 function WebGLProperties() {
14333 var properties = new WeakMap();
14335 function get(object) {
14336 var map = properties.get(object);
14338 if (map === undefined) {
14340 properties.set(object, map);
14346 function remove(object) {
14347 properties.delete(object);
14350 function update(object, key, value) {
14351 properties.get(object)[key] = value;
14354 function dispose() {
14355 properties = new WeakMap();
14366 function painterSortStable(a, b) {
14367 if (a.groupOrder !== b.groupOrder) {
14368 return a.groupOrder - b.groupOrder;
14369 } else if (a.renderOrder !== b.renderOrder) {
14370 return a.renderOrder - b.renderOrder;
14371 } else if (a.program !== b.program) {
14372 return a.program.id - b.program.id;
14373 } else if (a.material.id !== b.material.id) {
14374 return a.material.id - b.material.id;
14375 } else if (a.z !== b.z) {
14378 return a.id - b.id;
14382 function reversePainterSortStable(a, b) {
14383 if (a.groupOrder !== b.groupOrder) {
14384 return a.groupOrder - b.groupOrder;
14385 } else if (a.renderOrder !== b.renderOrder) {
14386 return a.renderOrder - b.renderOrder;
14387 } else if (a.z !== b.z) {
14390 return a.id - b.id;
14394 function WebGLRenderList(properties) {
14395 var renderItems = [];
14396 var renderItemsIndex = 0;
14398 var transparent = [];
14399 var defaultProgram = {
14404 renderItemsIndex = 0;
14406 transparent.length = 0;
14409 function getNextRenderItem(object, geometry, material, groupOrder, z, group) {
14410 var renderItem = renderItems[renderItemsIndex];
14411 var materialProperties = properties.get(material);
14413 if (renderItem === undefined) {
14417 geometry: geometry,
14418 material: material,
14419 program: materialProperties.program || defaultProgram,
14420 groupOrder: groupOrder,
14421 renderOrder: object.renderOrder,
14425 renderItems[renderItemsIndex] = renderItem;
14427 renderItem.id = object.id;
14428 renderItem.object = object;
14429 renderItem.geometry = geometry;
14430 renderItem.material = material;
14431 renderItem.program = materialProperties.program || defaultProgram;
14432 renderItem.groupOrder = groupOrder;
14433 renderItem.renderOrder = object.renderOrder;
14435 renderItem.group = group;
14438 renderItemsIndex++;
14442 function push(object, geometry, material, groupOrder, z, group) {
14443 var renderItem = getNextRenderItem(object, geometry, material, groupOrder, z, group);
14444 (material.transparent === true ? transparent : opaque).push(renderItem);
14447 function unshift(object, geometry, material, groupOrder, z, group) {
14448 var renderItem = getNextRenderItem(object, geometry, material, groupOrder, z, group);
14449 (material.transparent === true ? transparent : opaque).unshift(renderItem);
14452 function sort(customOpaqueSort, customTransparentSort) {
14453 if (opaque.length > 1) opaque.sort(customOpaqueSort || painterSortStable);
14454 if (transparent.length > 1) transparent.sort(customTransparentSort || reversePainterSortStable);
14457 function finish() {
14458 // Clear references from inactive renderItems in the list
14459 for (var i = renderItemsIndex, il = renderItems.length; i < il; i++) {
14460 var renderItem = renderItems[i];
14461 if (renderItem.id === null) break;
14462 renderItem.id = null;
14463 renderItem.object = null;
14464 renderItem.geometry = null;
14465 renderItem.material = null;
14466 renderItem.program = null;
14467 renderItem.group = null;
14473 transparent: transparent,
14482 function WebGLRenderLists(properties) {
14483 var lists = new WeakMap();
14485 function get(scene, camera) {
14486 var cameras = lists.get(scene);
14489 if (cameras === undefined) {
14490 list = new WebGLRenderList(properties);
14491 lists.set(scene, new WeakMap());
14492 lists.get(scene).set(camera, list);
14494 list = cameras.get(camera);
14496 if (list === undefined) {
14497 list = new WebGLRenderList(properties);
14498 cameras.set(camera, list);
14505 function dispose() {
14506 lists = new WeakMap();
14515 function UniformsCache() {
14518 get: function get(light) {
14519 if (lights[light.id] !== undefined) {
14520 return lights[light.id];
14525 switch (light.type) {
14526 case 'DirectionalLight':
14528 direction: new Vector3(),
14535 position: new Vector3(),
14536 direction: new Vector3(),
14537 color: new Color(),
14547 position: new Vector3(),
14548 color: new Color(),
14554 case 'HemisphereLight':
14556 direction: new Vector3(),
14557 skyColor: new Color(),
14558 groundColor: new Color()
14562 case 'RectAreaLight':
14564 color: new Color(),
14565 position: new Vector3(),
14566 halfWidth: new Vector3(),
14567 halfHeight: new Vector3()
14572 lights[light.id] = uniforms;
14578 function ShadowUniformsCache() {
14581 get: function get(light) {
14582 if (lights[light.id] !== undefined) {
14583 return lights[light.id];
14588 switch (light.type) {
14589 case 'DirectionalLight':
14592 shadowNormalBias: 0,
14594 shadowMapSize: new Vector2()
14601 shadowNormalBias: 0,
14603 shadowMapSize: new Vector2()
14610 shadowNormalBias: 0,
14612 shadowMapSize: new Vector2(),
14613 shadowCameraNear: 1,
14614 shadowCameraFar: 1000
14617 // TODO (abelnation): set RectAreaLight shadow uniforms
14620 lights[light.id] = uniforms;
14626 var nextVersion = 0;
14628 function shadowCastingLightsFirst(lightA, lightB) {
14629 return (lightB.castShadow ? 1 : 0) - (lightA.castShadow ? 1 : 0);
14632 function WebGLLights(extensions, capabilities) {
14633 var cache = new UniformsCache();
14634 var shadowCache = ShadowUniformsCache();
14638 directionalLength: -1,
14641 rectAreaLength: -1,
14643 numDirectionalShadows: -1,
14644 numPointShadows: -1,
14647 ambient: [0, 0, 0],
14650 directionalShadow: [],
14651 directionalShadowMap: [],
14652 directionalShadowMatrix: [],
14656 spotShadowMatrix: [],
14658 rectAreaLTC1: null,
14659 rectAreaLTC2: null,
14662 pointShadowMap: [],
14663 pointShadowMatrix: [],
14667 for (var i = 0; i < 9; i++) {
14668 state.probe.push(new Vector3());
14671 var vector3 = new Vector3();
14672 var matrix4 = new Matrix4();
14673 var matrix42 = new Matrix4();
14675 function setup(lights) {
14680 for (var _i = 0; _i < 9; _i++) {
14681 state.probe[_i].set(0, 0, 0);
14684 var directionalLength = 0;
14685 var pointLength = 0;
14686 var spotLength = 0;
14687 var rectAreaLength = 0;
14688 var hemiLength = 0;
14689 var numDirectionalShadows = 0;
14690 var numPointShadows = 0;
14691 var numSpotShadows = 0;
14692 lights.sort(shadowCastingLightsFirst);
14694 for (var _i2 = 0, l = lights.length; _i2 < l; _i2++) {
14695 var light = lights[_i2];
14696 var color = light.color;
14697 var intensity = light.intensity;
14698 var distance = light.distance;
14699 var shadowMap = light.shadow && light.shadow.map ? light.shadow.map.texture : null;
14701 if (light.isAmbientLight) {
14702 r += color.r * intensity;
14703 g += color.g * intensity;
14704 b += color.b * intensity;
14705 } else if (light.isLightProbe) {
14706 for (var j = 0; j < 9; j++) {
14707 state.probe[j].addScaledVector(light.sh.coefficients[j], intensity);
14709 } else if (light.isDirectionalLight) {
14710 var uniforms = cache.get(light);
14711 uniforms.color.copy(light.color).multiplyScalar(light.intensity);
14713 if (light.castShadow) {
14714 var shadow = light.shadow;
14715 var shadowUniforms = shadowCache.get(light);
14716 shadowUniforms.shadowBias = shadow.bias;
14717 shadowUniforms.shadowNormalBias = shadow.normalBias;
14718 shadowUniforms.shadowRadius = shadow.radius;
14719 shadowUniforms.shadowMapSize = shadow.mapSize;
14720 state.directionalShadow[directionalLength] = shadowUniforms;
14721 state.directionalShadowMap[directionalLength] = shadowMap;
14722 state.directionalShadowMatrix[directionalLength] = light.shadow.matrix;
14723 numDirectionalShadows++;
14726 state.directional[directionalLength] = uniforms;
14727 directionalLength++;
14728 } else if (light.isSpotLight) {
14729 var _uniforms = cache.get(light);
14731 _uniforms.position.setFromMatrixPosition(light.matrixWorld);
14733 _uniforms.color.copy(color).multiplyScalar(intensity);
14735 _uniforms.distance = distance;
14736 _uniforms.coneCos = Math.cos(light.angle);
14737 _uniforms.penumbraCos = Math.cos(light.angle * (1 - light.penumbra));
14738 _uniforms.decay = light.decay;
14740 if (light.castShadow) {
14741 var _shadow = light.shadow;
14743 var _shadowUniforms = shadowCache.get(light);
14745 _shadowUniforms.shadowBias = _shadow.bias;
14746 _shadowUniforms.shadowNormalBias = _shadow.normalBias;
14747 _shadowUniforms.shadowRadius = _shadow.radius;
14748 _shadowUniforms.shadowMapSize = _shadow.mapSize;
14749 state.spotShadow[spotLength] = _shadowUniforms;
14750 state.spotShadowMap[spotLength] = shadowMap;
14751 state.spotShadowMatrix[spotLength] = light.shadow.matrix;
14755 state.spot[spotLength] = _uniforms;
14757 } else if (light.isRectAreaLight) {
14758 var _uniforms2 = cache.get(light); // (a) intensity is the total visible light emitted
14759 //uniforms.color.copy( color ).multiplyScalar( intensity / ( light.width * light.height * Math.PI ) );
14760 // (b) intensity is the brightness of the light
14763 _uniforms2.color.copy(color).multiplyScalar(intensity);
14765 _uniforms2.halfWidth.set(light.width * 0.5, 0.0, 0.0);
14767 _uniforms2.halfHeight.set(0.0, light.height * 0.5, 0.0);
14769 state.rectArea[rectAreaLength] = _uniforms2;
14771 } else if (light.isPointLight) {
14772 var _uniforms3 = cache.get(light);
14774 _uniforms3.color.copy(light.color).multiplyScalar(light.intensity);
14776 _uniforms3.distance = light.distance;
14777 _uniforms3.decay = light.decay;
14779 if (light.castShadow) {
14780 var _shadow2 = light.shadow;
14782 var _shadowUniforms2 = shadowCache.get(light);
14784 _shadowUniforms2.shadowBias = _shadow2.bias;
14785 _shadowUniforms2.shadowNormalBias = _shadow2.normalBias;
14786 _shadowUniforms2.shadowRadius = _shadow2.radius;
14787 _shadowUniforms2.shadowMapSize = _shadow2.mapSize;
14788 _shadowUniforms2.shadowCameraNear = _shadow2.camera.near;
14789 _shadowUniforms2.shadowCameraFar = _shadow2.camera.far;
14790 state.pointShadow[pointLength] = _shadowUniforms2;
14791 state.pointShadowMap[pointLength] = shadowMap;
14792 state.pointShadowMatrix[pointLength] = light.shadow.matrix;
14796 state.point[pointLength] = _uniforms3;
14798 } else if (light.isHemisphereLight) {
14799 var _uniforms4 = cache.get(light);
14801 _uniforms4.skyColor.copy(light.color).multiplyScalar(intensity);
14803 _uniforms4.groundColor.copy(light.groundColor).multiplyScalar(intensity);
14805 state.hemi[hemiLength] = _uniforms4;
14810 if (rectAreaLength > 0) {
14811 if (capabilities.isWebGL2) {
14813 state.rectAreaLTC1 = UniformsLib.LTC_FLOAT_1;
14814 state.rectAreaLTC2 = UniformsLib.LTC_FLOAT_2;
14817 if (extensions.has('OES_texture_float_linear') === true) {
14818 state.rectAreaLTC1 = UniformsLib.LTC_FLOAT_1;
14819 state.rectAreaLTC2 = UniformsLib.LTC_FLOAT_2;
14820 } else if (extensions.has('OES_texture_half_float_linear') === true) {
14821 state.rectAreaLTC1 = UniformsLib.LTC_HALF_1;
14822 state.rectAreaLTC2 = UniformsLib.LTC_HALF_2;
14824 console.error('THREE.WebGLRenderer: Unable to use RectAreaLight. Missing WebGL extensions.');
14829 state.ambient[0] = r;
14830 state.ambient[1] = g;
14831 state.ambient[2] = b;
14832 var hash = state.hash;
14834 if (hash.directionalLength !== directionalLength || hash.pointLength !== pointLength || hash.spotLength !== spotLength || hash.rectAreaLength !== rectAreaLength || hash.hemiLength !== hemiLength || hash.numDirectionalShadows !== numDirectionalShadows || hash.numPointShadows !== numPointShadows || hash.numSpotShadows !== numSpotShadows) {
14835 state.directional.length = directionalLength;
14836 state.spot.length = spotLength;
14837 state.rectArea.length = rectAreaLength;
14838 state.point.length = pointLength;
14839 state.hemi.length = hemiLength;
14840 state.directionalShadow.length = numDirectionalShadows;
14841 state.directionalShadowMap.length = numDirectionalShadows;
14842 state.pointShadow.length = numPointShadows;
14843 state.pointShadowMap.length = numPointShadows;
14844 state.spotShadow.length = numSpotShadows;
14845 state.spotShadowMap.length = numSpotShadows;
14846 state.directionalShadowMatrix.length = numDirectionalShadows;
14847 state.pointShadowMatrix.length = numPointShadows;
14848 state.spotShadowMatrix.length = numSpotShadows;
14849 hash.directionalLength = directionalLength;
14850 hash.pointLength = pointLength;
14851 hash.spotLength = spotLength;
14852 hash.rectAreaLength = rectAreaLength;
14853 hash.hemiLength = hemiLength;
14854 hash.numDirectionalShadows = numDirectionalShadows;
14855 hash.numPointShadows = numPointShadows;
14856 hash.numSpotShadows = numSpotShadows;
14857 state.version = nextVersion++;
14861 function setupView(lights, camera) {
14862 var directionalLength = 0;
14863 var pointLength = 0;
14864 var spotLength = 0;
14865 var rectAreaLength = 0;
14866 var hemiLength = 0;
14867 var viewMatrix = camera.matrixWorldInverse;
14869 for (var _i3 = 0, l = lights.length; _i3 < l; _i3++) {
14870 var light = lights[_i3];
14872 if (light.isDirectionalLight) {
14873 var uniforms = state.directional[directionalLength];
14874 uniforms.direction.setFromMatrixPosition(light.matrixWorld);
14875 vector3.setFromMatrixPosition(light.target.matrixWorld);
14876 uniforms.direction.sub(vector3);
14877 uniforms.direction.transformDirection(viewMatrix);
14878 directionalLength++;
14879 } else if (light.isSpotLight) {
14880 var _uniforms5 = state.spot[spotLength];
14882 _uniforms5.position.setFromMatrixPosition(light.matrixWorld);
14884 _uniforms5.position.applyMatrix4(viewMatrix);
14886 _uniforms5.direction.setFromMatrixPosition(light.matrixWorld);
14888 vector3.setFromMatrixPosition(light.target.matrixWorld);
14890 _uniforms5.direction.sub(vector3);
14892 _uniforms5.direction.transformDirection(viewMatrix);
14895 } else if (light.isRectAreaLight) {
14896 var _uniforms6 = state.rectArea[rectAreaLength];
14898 _uniforms6.position.setFromMatrixPosition(light.matrixWorld);
14900 _uniforms6.position.applyMatrix4(viewMatrix); // extract local rotation of light to derive width/height half vectors
14903 matrix42.identity();
14904 matrix4.copy(light.matrixWorld);
14905 matrix4.premultiply(viewMatrix);
14906 matrix42.extractRotation(matrix4);
14908 _uniforms6.halfWidth.set(light.width * 0.5, 0.0, 0.0);
14910 _uniforms6.halfHeight.set(0.0, light.height * 0.5, 0.0);
14912 _uniforms6.halfWidth.applyMatrix4(matrix42);
14914 _uniforms6.halfHeight.applyMatrix4(matrix42);
14917 } else if (light.isPointLight) {
14918 var _uniforms7 = state.point[pointLength];
14920 _uniforms7.position.setFromMatrixPosition(light.matrixWorld);
14922 _uniforms7.position.applyMatrix4(viewMatrix);
14925 } else if (light.isHemisphereLight) {
14926 var _uniforms8 = state.hemi[hemiLength];
14928 _uniforms8.direction.setFromMatrixPosition(light.matrixWorld);
14930 _uniforms8.direction.transformDirection(viewMatrix);
14932 _uniforms8.direction.normalize();
14941 setupView: setupView,
14946 function WebGLRenderState(extensions, capabilities) {
14947 var lights = new WebGLLights(extensions, capabilities);
14948 var lightsArray = [];
14949 var shadowsArray = [];
14952 lightsArray.length = 0;
14953 shadowsArray.length = 0;
14956 function pushLight(light) {
14957 lightsArray.push(light);
14960 function pushShadow(shadowLight) {
14961 shadowsArray.push(shadowLight);
14964 function setupLights() {
14965 lights.setup(lightsArray);
14968 function setupLightsView(camera) {
14969 lights.setupView(lightsArray, camera);
14973 lightsArray: lightsArray,
14974 shadowsArray: shadowsArray,
14980 setupLights: setupLights,
14981 setupLightsView: setupLightsView,
14982 pushLight: pushLight,
14983 pushShadow: pushShadow
14987 function WebGLRenderStates(extensions, capabilities) {
14988 var renderStates = new WeakMap();
14990 function get(scene, renderCallDepth) {
14991 if (renderCallDepth === void 0) {
14992 renderCallDepth = 0;
14997 if (renderStates.has(scene) === false) {
14998 renderState = new WebGLRenderState(extensions, capabilities);
14999 renderStates.set(scene, []);
15000 renderStates.get(scene).push(renderState);
15002 if (renderCallDepth >= renderStates.get(scene).length) {
15003 renderState = new WebGLRenderState(extensions, capabilities);
15004 renderStates.get(scene).push(renderState);
15006 renderState = renderStates.get(scene)[renderCallDepth];
15010 return renderState;
15013 function dispose() {
15014 renderStates = new WeakMap();
15026 * opacity: <float>,
15028 * map: new THREE.Texture( <Image> ),
15030 * alphaMap: new THREE.Texture( <Image> ),
15032 * displacementMap: new THREE.Texture( <Image> ),
15033 * displacementScale: <float>,
15034 * displacementBias: <float>,
15036 * wireframe: <boolean>,
15037 * wireframeLinewidth: <float>
15041 function MeshDepthMaterial(parameters) {
15042 Material.call(this);
15043 this.type = 'MeshDepthMaterial';
15044 this.depthPacking = BasicDepthPacking;
15045 this.skinning = false;
15046 this.morphTargets = false;
15048 this.alphaMap = null;
15049 this.displacementMap = null;
15050 this.displacementScale = 1;
15051 this.displacementBias = 0;
15052 this.wireframe = false;
15053 this.wireframeLinewidth = 1;
15055 this.setValues(parameters);
15058 MeshDepthMaterial.prototype = Object.create(Material.prototype);
15059 MeshDepthMaterial.prototype.constructor = MeshDepthMaterial;
15060 MeshDepthMaterial.prototype.isMeshDepthMaterial = true;
15062 MeshDepthMaterial.prototype.copy = function (source) {
15063 Material.prototype.copy.call(this, source);
15064 this.depthPacking = source.depthPacking;
15065 this.skinning = source.skinning;
15066 this.morphTargets = source.morphTargets;
15067 this.map = source.map;
15068 this.alphaMap = source.alphaMap;
15069 this.displacementMap = source.displacementMap;
15070 this.displacementScale = source.displacementScale;
15071 this.displacementBias = source.displacementBias;
15072 this.wireframe = source.wireframe;
15073 this.wireframeLinewidth = source.wireframeLinewidth;
15080 * referencePosition: <float>,
15081 * nearDistance: <float>,
15082 * farDistance: <float>,
15084 * skinning: <bool>,
15085 * morphTargets: <bool>,
15087 * map: new THREE.Texture( <Image> ),
15089 * alphaMap: new THREE.Texture( <Image> ),
15091 * displacementMap: new THREE.Texture( <Image> ),
15092 * displacementScale: <float>,
15093 * displacementBias: <float>
15098 function MeshDistanceMaterial(parameters) {
15099 Material.call(this);
15100 this.type = 'MeshDistanceMaterial';
15101 this.referencePosition = new Vector3();
15102 this.nearDistance = 1;
15103 this.farDistance = 1000;
15104 this.skinning = false;
15105 this.morphTargets = false;
15107 this.alphaMap = null;
15108 this.displacementMap = null;
15109 this.displacementScale = 1;
15110 this.displacementBias = 0;
15112 this.setValues(parameters);
15115 MeshDistanceMaterial.prototype = Object.create(Material.prototype);
15116 MeshDistanceMaterial.prototype.constructor = MeshDistanceMaterial;
15117 MeshDistanceMaterial.prototype.isMeshDistanceMaterial = true;
15119 MeshDistanceMaterial.prototype.copy = function (source) {
15120 Material.prototype.copy.call(this, source);
15121 this.referencePosition.copy(source.referencePosition);
15122 this.nearDistance = source.nearDistance;
15123 this.farDistance = source.farDistance;
15124 this.skinning = source.skinning;
15125 this.morphTargets = source.morphTargets;
15126 this.map = source.map;
15127 this.alphaMap = source.alphaMap;
15128 this.displacementMap = source.displacementMap;
15129 this.displacementScale = source.displacementScale;
15130 this.displacementBias = source.displacementBias;
15134 var vsm_frag = "uniform sampler2D shadow_pass;\nuniform vec2 resolution;\nuniform float radius;\n#include <packing>\nvoid main() {\n\tfloat mean = 0.0;\n\tfloat squared_mean = 0.0;\n\tfloat depth = unpackRGBAToDepth( texture2D( shadow_pass, ( gl_FragCoord.xy ) / resolution ) );\n\tfor ( float i = -1.0; i < 1.0 ; i += SAMPLE_RATE) {\n\t\t#ifdef HORIZONTAL_PASS\n\t\t\tvec2 distribution = unpackRGBATo2Half( texture2D( shadow_pass, ( gl_FragCoord.xy + vec2( i, 0.0 ) * radius ) / resolution ) );\n\t\t\tmean += distribution.x;\n\t\t\tsquared_mean += distribution.y * distribution.y + distribution.x * distribution.x;\n\t\t#else\n\t\t\tfloat depth = unpackRGBAToDepth( texture2D( shadow_pass, ( gl_FragCoord.xy + vec2( 0.0, i ) * radius ) / resolution ) );\n\t\t\tmean += depth;\n\t\t\tsquared_mean += depth * depth;\n\t\t#endif\n\t}\n\tmean = mean * HALF_SAMPLE_RATE;\n\tsquared_mean = squared_mean * HALF_SAMPLE_RATE;\n\tfloat std_dev = sqrt( squared_mean - mean * mean );\n\tgl_FragColor = pack2HalfToRGBA( vec2( mean, std_dev ) );\n}";
15136 var vsm_vert = "void main() {\n\tgl_Position = vec4( position, 1.0 );\n}";
15138 function WebGLShadowMap(_renderer, _objects, maxTextureSize) {
15139 var _frustum = new Frustum();
15141 var _shadowMapSize = new Vector2(),
15142 _viewportSize = new Vector2(),
15143 _viewport = new Vector4(),
15144 _depthMaterials = [],
15145 _distanceMaterials = [],
15146 _materialCache = {};
15153 var shadowMaterialVertical = new ShaderMaterial({
15155 SAMPLE_RATE: 2.0 / 8.0,
15156 HALF_SAMPLE_RATE: 1.0 / 8.0
15163 value: new Vector2()
15169 vertexShader: vsm_vert,
15170 fragmentShader: vsm_frag
15172 var shadowMaterialHorizontal = shadowMaterialVertical.clone();
15173 shadowMaterialHorizontal.defines.HORIZONTAL_PASS = 1;
15174 var fullScreenTri = new BufferGeometry();
15175 fullScreenTri.setAttribute('position', new BufferAttribute(new Float32Array([-1, -1, 0.5, 3, -1, 0.5, -1, 3, 0.5]), 3));
15176 var fullScreenMesh = new Mesh(fullScreenTri, shadowMaterialVertical);
15178 this.enabled = false;
15179 this.autoUpdate = true;
15180 this.needsUpdate = false;
15181 this.type = PCFShadowMap;
15183 this.render = function (lights, scene, camera) {
15184 if (scope.enabled === false) return;
15185 if (scope.autoUpdate === false && scope.needsUpdate === false) return;
15186 if (lights.length === 0) return;
15188 var currentRenderTarget = _renderer.getRenderTarget();
15190 var activeCubeFace = _renderer.getActiveCubeFace();
15192 var activeMipmapLevel = _renderer.getActiveMipmapLevel();
15194 var _state = _renderer.state; // Set GL state for depth map.
15196 _state.setBlending(NoBlending);
15198 _state.buffers.color.setClear(1, 1, 1, 1);
15200 _state.buffers.depth.setTest(true);
15202 _state.setScissorTest(false); // render depth map
15205 for (var i = 0, il = lights.length; i < il; i++) {
15206 var light = lights[i];
15207 var shadow = light.shadow;
15209 if (shadow === undefined) {
15210 console.warn('THREE.WebGLShadowMap:', light, 'has no shadow.');
15214 if (shadow.autoUpdate === false && shadow.needsUpdate === false) continue;
15216 _shadowMapSize.copy(shadow.mapSize);
15218 var shadowFrameExtents = shadow.getFrameExtents();
15220 _shadowMapSize.multiply(shadowFrameExtents);
15222 _viewportSize.copy(shadow.mapSize);
15224 if (_shadowMapSize.x > maxTextureSize || _shadowMapSize.y > maxTextureSize) {
15225 if (_shadowMapSize.x > maxTextureSize) {
15226 _viewportSize.x = Math.floor(maxTextureSize / shadowFrameExtents.x);
15227 _shadowMapSize.x = _viewportSize.x * shadowFrameExtents.x;
15228 shadow.mapSize.x = _viewportSize.x;
15231 if (_shadowMapSize.y > maxTextureSize) {
15232 _viewportSize.y = Math.floor(maxTextureSize / shadowFrameExtents.y);
15233 _shadowMapSize.y = _viewportSize.y * shadowFrameExtents.y;
15234 shadow.mapSize.y = _viewportSize.y;
15238 if (shadow.map === null && !shadow.isPointLightShadow && this.type === VSMShadowMap) {
15240 minFilter: LinearFilter,
15241 magFilter: LinearFilter,
15244 shadow.map = new WebGLRenderTarget(_shadowMapSize.x, _shadowMapSize.y, pars);
15245 shadow.map.texture.name = light.name + '.shadowMap';
15246 shadow.mapPass = new WebGLRenderTarget(_shadowMapSize.x, _shadowMapSize.y, pars);
15247 shadow.camera.updateProjectionMatrix();
15250 if (shadow.map === null) {
15252 minFilter: NearestFilter,
15253 magFilter: NearestFilter,
15256 shadow.map = new WebGLRenderTarget(_shadowMapSize.x, _shadowMapSize.y, _pars);
15257 shadow.map.texture.name = light.name + '.shadowMap';
15258 shadow.camera.updateProjectionMatrix();
15261 _renderer.setRenderTarget(shadow.map);
15265 var viewportCount = shadow.getViewportCount();
15267 for (var vp = 0; vp < viewportCount; vp++) {
15268 var viewport = shadow.getViewport(vp);
15270 _viewport.set(_viewportSize.x * viewport.x, _viewportSize.y * viewport.y, _viewportSize.x * viewport.z, _viewportSize.y * viewport.w);
15272 _state.viewport(_viewport);
15274 shadow.updateMatrices(light, vp);
15275 _frustum = shadow.getFrustum();
15276 renderObject(scene, camera, shadow.camera, light, this.type);
15277 } // do blur pass for VSM
15280 if (!shadow.isPointLightShadow && this.type === VSMShadowMap) {
15281 VSMPass(shadow, camera);
15284 shadow.needsUpdate = false;
15287 scope.needsUpdate = false;
15289 _renderer.setRenderTarget(currentRenderTarget, activeCubeFace, activeMipmapLevel);
15292 function VSMPass(shadow, camera) {
15293 var geometry = _objects.update(fullScreenMesh); // vertical pass
15296 shadowMaterialVertical.uniforms.shadow_pass.value = shadow.map.texture;
15297 shadowMaterialVertical.uniforms.resolution.value = shadow.mapSize;
15298 shadowMaterialVertical.uniforms.radius.value = shadow.radius;
15300 _renderer.setRenderTarget(shadow.mapPass);
15304 _renderer.renderBufferDirect(camera, null, geometry, shadowMaterialVertical, fullScreenMesh, null); // horizontal pass
15307 shadowMaterialHorizontal.uniforms.shadow_pass.value = shadow.mapPass.texture;
15308 shadowMaterialHorizontal.uniforms.resolution.value = shadow.mapSize;
15309 shadowMaterialHorizontal.uniforms.radius.value = shadow.radius;
15311 _renderer.setRenderTarget(shadow.map);
15315 _renderer.renderBufferDirect(camera, null, geometry, shadowMaterialHorizontal, fullScreenMesh, null);
15318 function getDepthMaterialVariant(useMorphing, useSkinning, useInstancing) {
15319 var index = useMorphing << 0 | useSkinning << 1 | useInstancing << 2;
15320 var material = _depthMaterials[index];
15322 if (material === undefined) {
15323 material = new MeshDepthMaterial({
15324 depthPacking: RGBADepthPacking,
15325 morphTargets: useMorphing,
15326 skinning: useSkinning
15328 _depthMaterials[index] = material;
15334 function getDistanceMaterialVariant(useMorphing, useSkinning, useInstancing) {
15335 var index = useMorphing << 0 | useSkinning << 1 | useInstancing << 2;
15336 var material = _distanceMaterials[index];
15338 if (material === undefined) {
15339 material = new MeshDistanceMaterial({
15340 morphTargets: useMorphing,
15341 skinning: useSkinning
15343 _distanceMaterials[index] = material;
15349 function getDepthMaterial(object, geometry, material, light, shadowCameraNear, shadowCameraFar, type) {
15351 var getMaterialVariant = getDepthMaterialVariant;
15352 var customMaterial = object.customDepthMaterial;
15354 if (light.isPointLight === true) {
15355 getMaterialVariant = getDistanceMaterialVariant;
15356 customMaterial = object.customDistanceMaterial;
15359 if (customMaterial === undefined) {
15360 var useMorphing = false;
15362 if (material.morphTargets === true) {
15363 useMorphing = geometry.morphAttributes && geometry.morphAttributes.position && geometry.morphAttributes.position.length > 0;
15366 var useSkinning = false;
15368 if (object.isSkinnedMesh === true) {
15369 if (material.skinning === true) {
15370 useSkinning = true;
15372 console.warn('THREE.WebGLShadowMap: THREE.SkinnedMesh with material.skinning set to false:', object);
15376 var useInstancing = object.isInstancedMesh === true;
15377 result = getMaterialVariant(useMorphing, useSkinning, useInstancing);
15379 result = customMaterial;
15382 if (_renderer.localClippingEnabled && material.clipShadows === true && material.clippingPlanes.length !== 0) {
15383 // in this case we need a unique material instance reflecting the
15384 // appropriate state
15385 var keyA = result.uuid,
15386 keyB = material.uuid;
15387 var materialsForVariant = _materialCache[keyA];
15389 if (materialsForVariant === undefined) {
15390 materialsForVariant = {};
15391 _materialCache[keyA] = materialsForVariant;
15394 var cachedMaterial = materialsForVariant[keyB];
15396 if (cachedMaterial === undefined) {
15397 cachedMaterial = result.clone();
15398 materialsForVariant[keyB] = cachedMaterial;
15401 result = cachedMaterial;
15404 result.visible = material.visible;
15405 result.wireframe = material.wireframe;
15407 if (type === VSMShadowMap) {
15408 result.side = material.shadowSide !== null ? material.shadowSide : material.side;
15410 result.side = material.shadowSide !== null ? material.shadowSide : shadowSide[material.side];
15413 result.clipShadows = material.clipShadows;
15414 result.clippingPlanes = material.clippingPlanes;
15415 result.clipIntersection = material.clipIntersection;
15416 result.wireframeLinewidth = material.wireframeLinewidth;
15417 result.linewidth = material.linewidth;
15419 if (light.isPointLight === true && result.isMeshDistanceMaterial === true) {
15420 result.referencePosition.setFromMatrixPosition(light.matrixWorld);
15421 result.nearDistance = shadowCameraNear;
15422 result.farDistance = shadowCameraFar;
15428 function renderObject(object, camera, shadowCamera, light, type) {
15429 if (object.visible === false) return;
15430 var visible = object.layers.test(camera.layers);
15432 if (visible && (object.isMesh || object.isLine || object.isPoints)) {
15433 if ((object.castShadow || object.receiveShadow && type === VSMShadowMap) && (!object.frustumCulled || _frustum.intersectsObject(object))) {
15434 object.modelViewMatrix.multiplyMatrices(shadowCamera.matrixWorldInverse, object.matrixWorld);
15436 var geometry = _objects.update(object);
15438 var material = object.material;
15440 if (Array.isArray(material)) {
15441 var groups = geometry.groups;
15443 for (var k = 0, kl = groups.length; k < kl; k++) {
15444 var group = groups[k];
15445 var groupMaterial = material[group.materialIndex];
15447 if (groupMaterial && groupMaterial.visible) {
15448 var depthMaterial = getDepthMaterial(object, geometry, groupMaterial, light, shadowCamera.near, shadowCamera.far, type);
15450 _renderer.renderBufferDirect(shadowCamera, null, geometry, depthMaterial, object, group);
15453 } else if (material.visible) {
15454 var _depthMaterial = getDepthMaterial(object, geometry, material, light, shadowCamera.near, shadowCamera.far, type);
15456 _renderer.renderBufferDirect(shadowCamera, null, geometry, _depthMaterial, object, null);
15461 var children = object.children;
15463 for (var i = 0, l = children.length; i < l; i++) {
15464 renderObject(children[i], camera, shadowCamera, light, type);
15469 function WebGLState(gl, extensions, capabilities) {
15470 var _equationToGL, _factorToGL;
15472 var isWebGL2 = capabilities.isWebGL2;
15474 function ColorBuffer() {
15475 var locked = false;
15476 var color = new Vector4();
15477 var currentColorMask = null;
15478 var currentColorClear = new Vector4(0, 0, 0, 0);
15480 setMask: function setMask(colorMask) {
15481 if (currentColorMask !== colorMask && !locked) {
15482 gl.colorMask(colorMask, colorMask, colorMask, colorMask);
15483 currentColorMask = colorMask;
15486 setLocked: function setLocked(lock) {
15489 setClear: function setClear(r, g, b, a, premultipliedAlpha) {
15490 if (premultipliedAlpha === true) {
15496 color.set(r, g, b, a);
15498 if (currentColorClear.equals(color) === false) {
15499 gl.clearColor(r, g, b, a);
15500 currentColorClear.copy(color);
15503 reset: function reset() {
15505 currentColorMask = null;
15506 currentColorClear.set(-1, 0, 0, 0); // set to invalid state
15511 function DepthBuffer() {
15512 var locked = false;
15513 var currentDepthMask = null;
15514 var currentDepthFunc = null;
15515 var currentDepthClear = null;
15517 setTest: function setTest(depthTest) {
15524 setMask: function setMask(depthMask) {
15525 if (currentDepthMask !== depthMask && !locked) {
15526 gl.depthMask(depthMask);
15527 currentDepthMask = depthMask;
15530 setFunc: function setFunc(depthFunc) {
15531 if (currentDepthFunc !== depthFunc) {
15533 switch (depthFunc) {
15546 case LessEqualDepth:
15554 case GreaterEqualDepth:
15562 case NotEqualDepth:
15573 currentDepthFunc = depthFunc;
15576 setLocked: function setLocked(lock) {
15579 setClear: function setClear(depth) {
15580 if (currentDepthClear !== depth) {
15581 gl.clearDepth(depth);
15582 currentDepthClear = depth;
15585 reset: function reset() {
15587 currentDepthMask = null;
15588 currentDepthFunc = null;
15589 currentDepthClear = null;
15594 function StencilBuffer() {
15595 var locked = false;
15596 var currentStencilMask = null;
15597 var currentStencilFunc = null;
15598 var currentStencilRef = null;
15599 var currentStencilFuncMask = null;
15600 var currentStencilFail = null;
15601 var currentStencilZFail = null;
15602 var currentStencilZPass = null;
15603 var currentStencilClear = null;
15605 setTest: function setTest(stencilTest) {
15614 setMask: function setMask(stencilMask) {
15615 if (currentStencilMask !== stencilMask && !locked) {
15616 gl.stencilMask(stencilMask);
15617 currentStencilMask = stencilMask;
15620 setFunc: function setFunc(stencilFunc, stencilRef, stencilMask) {
15621 if (currentStencilFunc !== stencilFunc || currentStencilRef !== stencilRef || currentStencilFuncMask !== stencilMask) {
15622 gl.stencilFunc(stencilFunc, stencilRef, stencilMask);
15623 currentStencilFunc = stencilFunc;
15624 currentStencilRef = stencilRef;
15625 currentStencilFuncMask = stencilMask;
15628 setOp: function setOp(stencilFail, stencilZFail, stencilZPass) {
15629 if (currentStencilFail !== stencilFail || currentStencilZFail !== stencilZFail || currentStencilZPass !== stencilZPass) {
15630 gl.stencilOp(stencilFail, stencilZFail, stencilZPass);
15631 currentStencilFail = stencilFail;
15632 currentStencilZFail = stencilZFail;
15633 currentStencilZPass = stencilZPass;
15636 setLocked: function setLocked(lock) {
15639 setClear: function setClear(stencil) {
15640 if (currentStencilClear !== stencil) {
15641 gl.clearStencil(stencil);
15642 currentStencilClear = stencil;
15645 reset: function reset() {
15647 currentStencilMask = null;
15648 currentStencilFunc = null;
15649 currentStencilRef = null;
15650 currentStencilFuncMask = null;
15651 currentStencilFail = null;
15652 currentStencilZFail = null;
15653 currentStencilZPass = null;
15654 currentStencilClear = null;
15660 var colorBuffer = new ColorBuffer();
15661 var depthBuffer = new DepthBuffer();
15662 var stencilBuffer = new StencilBuffer();
15663 var enabledCapabilities = {};
15664 var currentProgram = null;
15665 var currentBlendingEnabled = null;
15666 var currentBlending = null;
15667 var currentBlendEquation = null;
15668 var currentBlendSrc = null;
15669 var currentBlendDst = null;
15670 var currentBlendEquationAlpha = null;
15671 var currentBlendSrcAlpha = null;
15672 var currentBlendDstAlpha = null;
15673 var currentPremultipledAlpha = false;
15674 var currentFlipSided = null;
15675 var currentCullFace = null;
15676 var currentLineWidth = null;
15677 var currentPolygonOffsetFactor = null;
15678 var currentPolygonOffsetUnits = null;
15679 var maxTextures = gl.getParameter(35661);
15680 var lineWidthAvailable = false;
15682 var glVersion = gl.getParameter(7938);
15684 if (glVersion.indexOf('WebGL') !== -1) {
15685 version = parseFloat(/^WebGL (\d)/.exec(glVersion)[1]);
15686 lineWidthAvailable = version >= 1.0;
15687 } else if (glVersion.indexOf('OpenGL ES') !== -1) {
15688 version = parseFloat(/^OpenGL ES (\d)/.exec(glVersion)[1]);
15689 lineWidthAvailable = version >= 2.0;
15692 var currentTextureSlot = null;
15693 var currentBoundTextures = {};
15694 var currentScissor = new Vector4();
15695 var currentViewport = new Vector4();
15697 function createTexture(type, target, count) {
15698 var data = new Uint8Array(4); // 4 is required to match default unpack alignment of 4.
15700 var texture = gl.createTexture();
15701 gl.bindTexture(type, texture);
15702 gl.texParameteri(type, 10241, 9728);
15703 gl.texParameteri(type, 10240, 9728);
15705 for (var i = 0; i < count; i++) {
15706 gl.texImage2D(target + i, 0, 6408, 1, 1, 0, 6408, 5121, data);
15712 var emptyTextures = {};
15713 emptyTextures[3553] = createTexture(3553, 3553, 1);
15714 emptyTextures[34067] = createTexture(34067, 34069, 6); // init
15716 colorBuffer.setClear(0, 0, 0, 1);
15717 depthBuffer.setClear(1);
15718 stencilBuffer.setClear(0);
15720 depthBuffer.setFunc(LessEqualDepth);
15721 setFlipSided(false);
15722 setCullFace(CullFaceBack);
15724 setBlending(NoBlending); //
15726 function enable(id) {
15727 if (enabledCapabilities[id] !== true) {
15729 enabledCapabilities[id] = true;
15733 function disable(id) {
15734 if (enabledCapabilities[id] !== false) {
15736 enabledCapabilities[id] = false;
15740 function useProgram(program) {
15741 if (currentProgram !== program) {
15742 gl.useProgram(program);
15743 currentProgram = program;
15750 var equationToGL = (_equationToGL = {}, _equationToGL[AddEquation] = 32774, _equationToGL[SubtractEquation] = 32778, _equationToGL[ReverseSubtractEquation] = 32779, _equationToGL);
15753 equationToGL[MinEquation] = 32775;
15754 equationToGL[MaxEquation] = 32776;
15756 var extension = extensions.get('EXT_blend_minmax');
15758 if (extension !== null) {
15759 equationToGL[MinEquation] = extension.MIN_EXT;
15760 equationToGL[MaxEquation] = extension.MAX_EXT;
15764 var factorToGL = (_factorToGL = {}, _factorToGL[ZeroFactor] = 0, _factorToGL[OneFactor] = 1, _factorToGL[SrcColorFactor] = 768, _factorToGL[SrcAlphaFactor] = 770, _factorToGL[SrcAlphaSaturateFactor] = 776, _factorToGL[DstColorFactor] = 774, _factorToGL[DstAlphaFactor] = 772, _factorToGL[OneMinusSrcColorFactor] = 769, _factorToGL[OneMinusSrcAlphaFactor] = 771, _factorToGL[OneMinusDstColorFactor] = 775, _factorToGL[OneMinusDstAlphaFactor] = 773, _factorToGL);
15766 function setBlending(blending, blendEquation, blendSrc, blendDst, blendEquationAlpha, blendSrcAlpha, blendDstAlpha, premultipliedAlpha) {
15767 if (blending === NoBlending) {
15768 if (currentBlendingEnabled) {
15770 currentBlendingEnabled = false;
15776 if (!currentBlendingEnabled) {
15778 currentBlendingEnabled = true;
15781 if (blending !== CustomBlending) {
15782 if (blending !== currentBlending || premultipliedAlpha !== currentPremultipledAlpha) {
15783 if (currentBlendEquation !== AddEquation || currentBlendEquationAlpha !== AddEquation) {
15784 gl.blendEquation(32774);
15785 currentBlendEquation = AddEquation;
15786 currentBlendEquationAlpha = AddEquation;
15789 if (premultipliedAlpha) {
15790 switch (blending) {
15791 case NormalBlending:
15792 gl.blendFuncSeparate(1, 771, 1, 771);
15795 case AdditiveBlending:
15796 gl.blendFunc(1, 1);
15799 case SubtractiveBlending:
15800 gl.blendFuncSeparate(0, 0, 769, 771);
15803 case MultiplyBlending:
15804 gl.blendFuncSeparate(0, 768, 0, 770);
15808 console.error('THREE.WebGLState: Invalid blending: ', blending);
15812 switch (blending) {
15813 case NormalBlending:
15814 gl.blendFuncSeparate(770, 771, 1, 771);
15817 case AdditiveBlending:
15818 gl.blendFunc(770, 1);
15821 case SubtractiveBlending:
15822 gl.blendFunc(0, 769);
15825 case MultiplyBlending:
15826 gl.blendFunc(0, 768);
15830 console.error('THREE.WebGLState: Invalid blending: ', blending);
15835 currentBlendSrc = null;
15836 currentBlendDst = null;
15837 currentBlendSrcAlpha = null;
15838 currentBlendDstAlpha = null;
15839 currentBlending = blending;
15840 currentPremultipledAlpha = premultipliedAlpha;
15844 } // custom blending
15847 blendEquationAlpha = blendEquationAlpha || blendEquation;
15848 blendSrcAlpha = blendSrcAlpha || blendSrc;
15849 blendDstAlpha = blendDstAlpha || blendDst;
15851 if (blendEquation !== currentBlendEquation || blendEquationAlpha !== currentBlendEquationAlpha) {
15852 gl.blendEquationSeparate(equationToGL[blendEquation], equationToGL[blendEquationAlpha]);
15853 currentBlendEquation = blendEquation;
15854 currentBlendEquationAlpha = blendEquationAlpha;
15857 if (blendSrc !== currentBlendSrc || blendDst !== currentBlendDst || blendSrcAlpha !== currentBlendSrcAlpha || blendDstAlpha !== currentBlendDstAlpha) {
15858 gl.blendFuncSeparate(factorToGL[blendSrc], factorToGL[blendDst], factorToGL[blendSrcAlpha], factorToGL[blendDstAlpha]);
15859 currentBlendSrc = blendSrc;
15860 currentBlendDst = blendDst;
15861 currentBlendSrcAlpha = blendSrcAlpha;
15862 currentBlendDstAlpha = blendDstAlpha;
15865 currentBlending = blending;
15866 currentPremultipledAlpha = null;
15869 function setMaterial(material, frontFaceCW) {
15870 material.side === DoubleSide ? disable(2884) : enable(2884);
15871 var flipSided = material.side === BackSide;
15872 if (frontFaceCW) flipSided = !flipSided;
15873 setFlipSided(flipSided);
15874 material.blending === NormalBlending && material.transparent === false ? setBlending(NoBlending) : setBlending(material.blending, material.blendEquation, material.blendSrc, material.blendDst, material.blendEquationAlpha, material.blendSrcAlpha, material.blendDstAlpha, material.premultipliedAlpha);
15875 depthBuffer.setFunc(material.depthFunc);
15876 depthBuffer.setTest(material.depthTest);
15877 depthBuffer.setMask(material.depthWrite);
15878 colorBuffer.setMask(material.colorWrite);
15879 var stencilWrite = material.stencilWrite;
15880 stencilBuffer.setTest(stencilWrite);
15882 if (stencilWrite) {
15883 stencilBuffer.setMask(material.stencilWriteMask);
15884 stencilBuffer.setFunc(material.stencilFunc, material.stencilRef, material.stencilFuncMask);
15885 stencilBuffer.setOp(material.stencilFail, material.stencilZFail, material.stencilZPass);
15888 setPolygonOffset(material.polygonOffset, material.polygonOffsetFactor, material.polygonOffsetUnits);
15892 function setFlipSided(flipSided) {
15893 if (currentFlipSided !== flipSided) {
15895 gl.frontFace(2304);
15897 gl.frontFace(2305);
15900 currentFlipSided = flipSided;
15904 function setCullFace(cullFace) {
15905 if (cullFace !== CullFaceNone) {
15908 if (cullFace !== currentCullFace) {
15909 if (cullFace === CullFaceBack) {
15911 } else if (cullFace === CullFaceFront) {
15921 currentCullFace = cullFace;
15924 function setLineWidth(width) {
15925 if (width !== currentLineWidth) {
15926 if (lineWidthAvailable) gl.lineWidth(width);
15927 currentLineWidth = width;
15931 function setPolygonOffset(polygonOffset, factor, units) {
15932 if (polygonOffset) {
15935 if (currentPolygonOffsetFactor !== factor || currentPolygonOffsetUnits !== units) {
15936 gl.polygonOffset(factor, units);
15937 currentPolygonOffsetFactor = factor;
15938 currentPolygonOffsetUnits = units;
15945 function setScissorTest(scissorTest) {
15954 function activeTexture(webglSlot) {
15955 if (webglSlot === undefined) webglSlot = 33984 + maxTextures - 1;
15957 if (currentTextureSlot !== webglSlot) {
15958 gl.activeTexture(webglSlot);
15959 currentTextureSlot = webglSlot;
15963 function bindTexture(webglType, webglTexture) {
15964 if (currentTextureSlot === null) {
15968 var boundTexture = currentBoundTextures[currentTextureSlot];
15970 if (boundTexture === undefined) {
15975 currentBoundTextures[currentTextureSlot] = boundTexture;
15978 if (boundTexture.type !== webglType || boundTexture.texture !== webglTexture) {
15979 gl.bindTexture(webglType, webglTexture || emptyTextures[webglType]);
15980 boundTexture.type = webglType;
15981 boundTexture.texture = webglTexture;
15985 function unbindTexture() {
15986 var boundTexture = currentBoundTextures[currentTextureSlot];
15988 if (boundTexture !== undefined && boundTexture.type !== undefined) {
15989 gl.bindTexture(boundTexture.type, null);
15990 boundTexture.type = undefined;
15991 boundTexture.texture = undefined;
15995 function compressedTexImage2D() {
15997 gl.compressedTexImage2D.apply(gl, arguments);
15999 console.error('THREE.WebGLState:', error);
16003 function texImage2D() {
16005 gl.texImage2D.apply(gl, arguments);
16007 console.error('THREE.WebGLState:', error);
16011 function texImage3D() {
16013 gl.texImage3D.apply(gl, arguments);
16015 console.error('THREE.WebGLState:', error);
16020 function scissor(scissor) {
16021 if (currentScissor.equals(scissor) === false) {
16022 gl.scissor(scissor.x, scissor.y, scissor.z, scissor.w);
16023 currentScissor.copy(scissor);
16027 function viewport(viewport) {
16028 if (currentViewport.equals(viewport) === false) {
16029 gl.viewport(viewport.x, viewport.y, viewport.z, viewport.w);
16030 currentViewport.copy(viewport);
16036 enabledCapabilities = {};
16037 currentTextureSlot = null;
16038 currentBoundTextures = {};
16039 currentProgram = null;
16040 currentBlendingEnabled = null;
16041 currentBlending = null;
16042 currentBlendEquation = null;
16043 currentBlendSrc = null;
16044 currentBlendDst = null;
16045 currentBlendEquationAlpha = null;
16046 currentBlendSrcAlpha = null;
16047 currentBlendDstAlpha = null;
16048 currentPremultipledAlpha = false;
16049 currentFlipSided = null;
16050 currentCullFace = null;
16051 currentLineWidth = null;
16052 currentPolygonOffsetFactor = null;
16053 currentPolygonOffsetUnits = null;
16054 colorBuffer.reset();
16055 depthBuffer.reset();
16056 stencilBuffer.reset();
16061 color: colorBuffer,
16062 depth: depthBuffer,
16063 stencil: stencilBuffer
16067 useProgram: useProgram,
16068 setBlending: setBlending,
16069 setMaterial: setMaterial,
16070 setFlipSided: setFlipSided,
16071 setCullFace: setCullFace,
16072 setLineWidth: setLineWidth,
16073 setPolygonOffset: setPolygonOffset,
16074 setScissorTest: setScissorTest,
16075 activeTexture: activeTexture,
16076 bindTexture: bindTexture,
16077 unbindTexture: unbindTexture,
16078 compressedTexImage2D: compressedTexImage2D,
16079 texImage2D: texImage2D,
16080 texImage3D: texImage3D,
16082 viewport: viewport,
16087 function WebGLTextures(_gl, extensions, state, properties, capabilities, utils, info) {
16088 var _wrappingToGL, _filterToGL;
16090 var isWebGL2 = capabilities.isWebGL2;
16091 var maxTextures = capabilities.maxTextures;
16092 var maxCubemapSize = capabilities.maxCubemapSize;
16093 var maxTextureSize = capabilities.maxTextureSize;
16094 var maxSamples = capabilities.maxSamples;
16096 var _videoTextures = new WeakMap();
16098 var _canvas; // cordova iOS (as of 5.0) still uses UIWebView, which provides OffscreenCanvas,
16099 // also OffscreenCanvas.getContext("webgl"), but not OffscreenCanvas.getContext("2d")!
16100 // Some implementations may only implement OffscreenCanvas partially (e.g. lacking 2d).
16103 var useOffscreenCanvas = false;
16106 useOffscreenCanvas = typeof OffscreenCanvas !== 'undefined' && new OffscreenCanvas(1, 1).getContext('2d') !== null;
16107 } catch (err) {// Ignore any errors
16110 function createCanvas(width, height) {
16111 // Use OffscreenCanvas when available. Specially needed in web workers
16112 return useOffscreenCanvas ? new OffscreenCanvas(width, height) : document.createElementNS('http://www.w3.org/1999/xhtml', 'canvas');
16115 function resizeImage(image, needsPowerOfTwo, needsNewCanvas, maxSize) {
16116 var scale = 1; // handle case if texture exceeds max size
16118 if (image.width > maxSize || image.height > maxSize) {
16119 scale = maxSize / Math.max(image.width, image.height);
16120 } // only perform resize if necessary
16123 if (scale < 1 || needsPowerOfTwo === true) {
16124 // only perform resize for certain image types
16125 if (typeof HTMLImageElement !== 'undefined' && image instanceof HTMLImageElement || typeof HTMLCanvasElement !== 'undefined' && image instanceof HTMLCanvasElement || typeof ImageBitmap !== 'undefined' && image instanceof ImageBitmap) {
16126 var floor = needsPowerOfTwo ? MathUtils.floorPowerOfTwo : Math.floor;
16127 var width = floor(scale * image.width);
16128 var height = floor(scale * image.height);
16129 if (_canvas === undefined) _canvas = createCanvas(width, height); // cube textures can't reuse the same canvas
16131 var canvas = needsNewCanvas ? createCanvas(width, height) : _canvas;
16132 canvas.width = width;
16133 canvas.height = height;
16134 var context = canvas.getContext('2d');
16135 context.drawImage(image, 0, 0, width, height);
16136 console.warn('THREE.WebGLRenderer: Texture has been resized from (' + image.width + 'x' + image.height + ') to (' + width + 'x' + height + ').');
16139 if ('data' in image) {
16140 console.warn('THREE.WebGLRenderer: Image in DataTexture is too big (' + image.width + 'x' + image.height + ').');
16150 function isPowerOfTwo(image) {
16151 return MathUtils.isPowerOfTwo(image.width) && MathUtils.isPowerOfTwo(image.height);
16154 function textureNeedsPowerOfTwo(texture) {
16155 if (isWebGL2) return false;
16156 return texture.wrapS !== ClampToEdgeWrapping || texture.wrapT !== ClampToEdgeWrapping || texture.minFilter !== NearestFilter && texture.minFilter !== LinearFilter;
16159 function textureNeedsGenerateMipmaps(texture, supportsMips) {
16160 return texture.generateMipmaps && supportsMips && texture.minFilter !== NearestFilter && texture.minFilter !== LinearFilter;
16163 function generateMipmap(target, texture, width, height) {
16164 _gl.generateMipmap(target);
16166 var textureProperties = properties.get(texture); // Note: Math.log( x ) * Math.LOG2E used instead of Math.log2( x ) which is not supported by IE11
16168 textureProperties.__maxMipLevel = Math.log(Math.max(width, height)) * Math.LOG2E;
16171 function getInternalFormat(internalFormatName, glFormat, glType) {
16172 if (isWebGL2 === false) return glFormat;
16174 if (internalFormatName !== null) {
16175 if (_gl[internalFormatName] !== undefined) return _gl[internalFormatName];
16176 console.warn('THREE.WebGLRenderer: Attempt to use non-existing WebGL internal format \'' + internalFormatName + '\'');
16179 var internalFormat = glFormat;
16181 if (glFormat === 6403) {
16182 if (glType === 5126) internalFormat = 33326;
16183 if (glType === 5131) internalFormat = 33325;
16184 if (glType === 5121) internalFormat = 33321;
16187 if (glFormat === 6407) {
16188 if (glType === 5126) internalFormat = 34837;
16189 if (glType === 5131) internalFormat = 34843;
16190 if (glType === 5121) internalFormat = 32849;
16193 if (glFormat === 6408) {
16194 if (glType === 5126) internalFormat = 34836;
16195 if (glType === 5131) internalFormat = 34842;
16196 if (glType === 5121) internalFormat = 32856;
16199 if (internalFormat === 33325 || internalFormat === 33326 || internalFormat === 34842 || internalFormat === 34836) {
16200 extensions.get('EXT_color_buffer_float');
16203 return internalFormat;
16204 } // Fallback filters for non-power-of-2 textures
16207 function filterFallback(f) {
16208 if (f === NearestFilter || f === NearestMipmapNearestFilter || f === NearestMipmapLinearFilter) {
16216 function onTextureDispose(event) {
16217 var texture = event.target;
16218 texture.removeEventListener('dispose', onTextureDispose);
16219 deallocateTexture(texture);
16221 if (texture.isVideoTexture) {
16222 _videoTextures.delete(texture);
16225 info.memory.textures--;
16228 function onRenderTargetDispose(event) {
16229 var renderTarget = event.target;
16230 renderTarget.removeEventListener('dispose', onRenderTargetDispose);
16231 deallocateRenderTarget(renderTarget);
16232 info.memory.textures--;
16236 function deallocateTexture(texture) {
16237 var textureProperties = properties.get(texture);
16238 if (textureProperties.__webglInit === undefined) return;
16240 _gl.deleteTexture(textureProperties.__webglTexture);
16242 properties.remove(texture);
16245 function deallocateRenderTarget(renderTarget) {
16246 var renderTargetProperties = properties.get(renderTarget);
16247 var textureProperties = properties.get(renderTarget.texture);
16248 if (!renderTarget) return;
16250 if (textureProperties.__webglTexture !== undefined) {
16251 _gl.deleteTexture(textureProperties.__webglTexture);
16254 if (renderTarget.depthTexture) {
16255 renderTarget.depthTexture.dispose();
16258 if (renderTarget.isWebGLCubeRenderTarget) {
16259 for (var i = 0; i < 6; i++) {
16260 _gl.deleteFramebuffer(renderTargetProperties.__webglFramebuffer[i]);
16262 if (renderTargetProperties.__webglDepthbuffer) _gl.deleteRenderbuffer(renderTargetProperties.__webglDepthbuffer[i]);
16265 _gl.deleteFramebuffer(renderTargetProperties.__webglFramebuffer);
16267 if (renderTargetProperties.__webglDepthbuffer) _gl.deleteRenderbuffer(renderTargetProperties.__webglDepthbuffer);
16268 if (renderTargetProperties.__webglMultisampledFramebuffer) _gl.deleteFramebuffer(renderTargetProperties.__webglMultisampledFramebuffer);
16269 if (renderTargetProperties.__webglColorRenderbuffer) _gl.deleteRenderbuffer(renderTargetProperties.__webglColorRenderbuffer);
16270 if (renderTargetProperties.__webglDepthRenderbuffer) _gl.deleteRenderbuffer(renderTargetProperties.__webglDepthRenderbuffer);
16273 properties.remove(renderTarget.texture);
16274 properties.remove(renderTarget);
16278 var textureUnits = 0;
16280 function resetTextureUnits() {
16284 function allocateTextureUnit() {
16285 var textureUnit = textureUnits;
16287 if (textureUnit >= maxTextures) {
16288 console.warn('THREE.WebGLTextures: Trying to use ' + textureUnit + ' texture units while this GPU supports only ' + maxTextures);
16292 return textureUnit;
16296 function setTexture2D(texture, slot) {
16297 var textureProperties = properties.get(texture);
16298 if (texture.isVideoTexture) updateVideoTexture(texture);
16300 if (texture.version > 0 && textureProperties.__version !== texture.version) {
16301 var image = texture.image;
16303 if (image === undefined) {
16304 console.warn('THREE.WebGLRenderer: Texture marked for update but image is undefined');
16305 } else if (image.complete === false) {
16306 console.warn('THREE.WebGLRenderer: Texture marked for update but image is incomplete');
16308 uploadTexture(textureProperties, texture, slot);
16313 state.activeTexture(33984 + slot);
16314 state.bindTexture(3553, textureProperties.__webglTexture);
16317 function setTexture2DArray(texture, slot) {
16318 var textureProperties = properties.get(texture);
16320 if (texture.version > 0 && textureProperties.__version !== texture.version) {
16321 uploadTexture(textureProperties, texture, slot);
16325 state.activeTexture(33984 + slot);
16326 state.bindTexture(35866, textureProperties.__webglTexture);
16329 function setTexture3D(texture, slot) {
16330 var textureProperties = properties.get(texture);
16332 if (texture.version > 0 && textureProperties.__version !== texture.version) {
16333 uploadTexture(textureProperties, texture, slot);
16337 state.activeTexture(33984 + slot);
16338 state.bindTexture(32879, textureProperties.__webglTexture);
16341 function setTextureCube(texture, slot) {
16342 var textureProperties = properties.get(texture);
16344 if (texture.version > 0 && textureProperties.__version !== texture.version) {
16345 uploadCubeTexture(textureProperties, texture, slot);
16349 state.activeTexture(33984 + slot);
16350 state.bindTexture(34067, textureProperties.__webglTexture);
16353 var wrappingToGL = (_wrappingToGL = {}, _wrappingToGL[RepeatWrapping] = 10497, _wrappingToGL[ClampToEdgeWrapping] = 33071, _wrappingToGL[MirroredRepeatWrapping] = 33648, _wrappingToGL);
16354 var filterToGL = (_filterToGL = {}, _filterToGL[NearestFilter] = 9728, _filterToGL[NearestMipmapNearestFilter] = 9984, _filterToGL[NearestMipmapLinearFilter] = 9986, _filterToGL[LinearFilter] = 9729, _filterToGL[LinearMipmapNearestFilter] = 9985, _filterToGL[LinearMipmapLinearFilter] = 9987, _filterToGL);
16356 function setTextureParameters(textureType, texture, supportsMips) {
16357 if (supportsMips) {
16358 _gl.texParameteri(textureType, 10242, wrappingToGL[texture.wrapS]);
16360 _gl.texParameteri(textureType, 10243, wrappingToGL[texture.wrapT]);
16362 if (textureType === 32879 || textureType === 35866) {
16363 _gl.texParameteri(textureType, 32882, wrappingToGL[texture.wrapR]);
16366 _gl.texParameteri(textureType, 10240, filterToGL[texture.magFilter]);
16368 _gl.texParameteri(textureType, 10241, filterToGL[texture.minFilter]);
16370 _gl.texParameteri(textureType, 10242, 33071);
16372 _gl.texParameteri(textureType, 10243, 33071);
16374 if (textureType === 32879 || textureType === 35866) {
16375 _gl.texParameteri(textureType, 32882, 33071);
16378 if (texture.wrapS !== ClampToEdgeWrapping || texture.wrapT !== ClampToEdgeWrapping) {
16379 console.warn('THREE.WebGLRenderer: Texture is not power of two. Texture.wrapS and Texture.wrapT should be set to THREE.ClampToEdgeWrapping.');
16382 _gl.texParameteri(textureType, 10240, filterFallback(texture.magFilter));
16384 _gl.texParameteri(textureType, 10241, filterFallback(texture.minFilter));
16386 if (texture.minFilter !== NearestFilter && texture.minFilter !== LinearFilter) {
16387 console.warn('THREE.WebGLRenderer: Texture is not power of two. Texture.minFilter should be set to THREE.NearestFilter or THREE.LinearFilter.');
16391 var extension = extensions.get('EXT_texture_filter_anisotropic');
16394 if (texture.type === FloatType && extensions.get('OES_texture_float_linear') === null) return;
16395 if (texture.type === HalfFloatType && (isWebGL2 || extensions.get('OES_texture_half_float_linear')) === null) return;
16397 if (texture.anisotropy > 1 || properties.get(texture).__currentAnisotropy) {
16398 _gl.texParameterf(textureType, extension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(texture.anisotropy, capabilities.getMaxAnisotropy()));
16400 properties.get(texture).__currentAnisotropy = texture.anisotropy;
16405 function initTexture(textureProperties, texture) {
16406 if (textureProperties.__webglInit === undefined) {
16407 textureProperties.__webglInit = true;
16408 texture.addEventListener('dispose', onTextureDispose);
16409 textureProperties.__webglTexture = _gl.createTexture();
16410 info.memory.textures++;
16414 function uploadTexture(textureProperties, texture, slot) {
16415 var textureType = 3553;
16416 if (texture.isDataTexture2DArray) textureType = 35866;
16417 if (texture.isDataTexture3D) textureType = 32879;
16418 initTexture(textureProperties, texture);
16419 state.activeTexture(33984 + slot);
16420 state.bindTexture(textureType, textureProperties.__webglTexture);
16422 _gl.pixelStorei(37440, texture.flipY);
16424 _gl.pixelStorei(37441, texture.premultiplyAlpha);
16426 _gl.pixelStorei(3317, texture.unpackAlignment);
16428 var needsPowerOfTwo = textureNeedsPowerOfTwo(texture) && isPowerOfTwo(texture.image) === false;
16429 var image = resizeImage(texture.image, needsPowerOfTwo, false, maxTextureSize);
16430 var supportsMips = isPowerOfTwo(image) || isWebGL2,
16431 glFormat = utils.convert(texture.format);
16432 var glType = utils.convert(texture.type),
16433 glInternalFormat = getInternalFormat(texture.internalFormat, glFormat, glType);
16434 setTextureParameters(textureType, texture, supportsMips);
16436 var mipmaps = texture.mipmaps;
16438 if (texture.isDepthTexture) {
16439 // populate depth texture with dummy data
16440 glInternalFormat = 6402;
16443 if (texture.type === FloatType) {
16444 glInternalFormat = 36012;
16445 } else if (texture.type === UnsignedIntType) {
16446 glInternalFormat = 33190;
16447 } else if (texture.type === UnsignedInt248Type) {
16448 glInternalFormat = 35056;
16450 glInternalFormat = 33189; // WebGL2 requires sized internalformat for glTexImage2D
16453 if (texture.type === FloatType) {
16454 console.error('WebGLRenderer: Floating point depth texture requires WebGL2.');
16456 } // validation checks for WebGL 1
16459 if (texture.format === DepthFormat && glInternalFormat === 6402) {
16460 // The error INVALID_OPERATION is generated by texImage2D if format and internalformat are
16461 // DEPTH_COMPONENT and type is not UNSIGNED_SHORT or UNSIGNED_INT
16462 // (https://www.khronos.org/registry/webgl/extensions/WEBGL_depth_texture/)
16463 if (texture.type !== UnsignedShortType && texture.type !== UnsignedIntType) {
16464 console.warn('THREE.WebGLRenderer: Use UnsignedShortType or UnsignedIntType for DepthFormat DepthTexture.');
16465 texture.type = UnsignedShortType;
16466 glType = utils.convert(texture.type);
16470 if (texture.format === DepthStencilFormat && glInternalFormat === 6402) {
16471 // Depth stencil textures need the DEPTH_STENCIL internal format
16472 // (https://www.khronos.org/registry/webgl/extensions/WEBGL_depth_texture/)
16473 glInternalFormat = 34041; // The error INVALID_OPERATION is generated by texImage2D if format and internalformat are
16474 // DEPTH_STENCIL and type is not UNSIGNED_INT_24_8_WEBGL.
16475 // (https://www.khronos.org/registry/webgl/extensions/WEBGL_depth_texture/)
16477 if (texture.type !== UnsignedInt248Type) {
16478 console.warn('THREE.WebGLRenderer: Use UnsignedInt248Type for DepthStencilFormat DepthTexture.');
16479 texture.type = UnsignedInt248Type;
16480 glType = utils.convert(texture.type);
16485 state.texImage2D(3553, 0, glInternalFormat, image.width, image.height, 0, glFormat, glType, null);
16486 } else if (texture.isDataTexture) {
16487 // use manually created mipmaps if available
16488 // if there are no manual mipmaps
16489 // set 0 level mipmap and then use GL to generate other mipmap levels
16490 if (mipmaps.length > 0 && supportsMips) {
16491 for (var i = 0, il = mipmaps.length; i < il; i++) {
16492 mipmap = mipmaps[i];
16493 state.texImage2D(3553, i, glInternalFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data);
16496 texture.generateMipmaps = false;
16497 textureProperties.__maxMipLevel = mipmaps.length - 1;
16499 state.texImage2D(3553, 0, glInternalFormat, image.width, image.height, 0, glFormat, glType, image.data);
16500 textureProperties.__maxMipLevel = 0;
16502 } else if (texture.isCompressedTexture) {
16503 for (var _i = 0, _il = mipmaps.length; _i < _il; _i++) {
16504 mipmap = mipmaps[_i];
16506 if (texture.format !== RGBAFormat && texture.format !== RGBFormat) {
16507 if (glFormat !== null) {
16508 state.compressedTexImage2D(3553, _i, glInternalFormat, mipmap.width, mipmap.height, 0, mipmap.data);
16510 console.warn('THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()');
16513 state.texImage2D(3553, _i, glInternalFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data);
16517 textureProperties.__maxMipLevel = mipmaps.length - 1;
16518 } else if (texture.isDataTexture2DArray) {
16519 state.texImage3D(35866, 0, glInternalFormat, image.width, image.height, image.depth, 0, glFormat, glType, image.data);
16520 textureProperties.__maxMipLevel = 0;
16521 } else if (texture.isDataTexture3D) {
16522 state.texImage3D(32879, 0, glInternalFormat, image.width, image.height, image.depth, 0, glFormat, glType, image.data);
16523 textureProperties.__maxMipLevel = 0;
16525 // regular Texture (image, video, canvas)
16526 // use manually created mipmaps if available
16527 // if there are no manual mipmaps
16528 // set 0 level mipmap and then use GL to generate other mipmap levels
16529 if (mipmaps.length > 0 && supportsMips) {
16530 for (var _i2 = 0, _il2 = mipmaps.length; _i2 < _il2; _i2++) {
16531 mipmap = mipmaps[_i2];
16532 state.texImage2D(3553, _i2, glInternalFormat, glFormat, glType, mipmap);
16535 texture.generateMipmaps = false;
16536 textureProperties.__maxMipLevel = mipmaps.length - 1;
16538 state.texImage2D(3553, 0, glInternalFormat, glFormat, glType, image);
16539 textureProperties.__maxMipLevel = 0;
16543 if (textureNeedsGenerateMipmaps(texture, supportsMips)) {
16544 generateMipmap(textureType, texture, image.width, image.height);
16547 textureProperties.__version = texture.version;
16548 if (texture.onUpdate) texture.onUpdate(texture);
16551 function uploadCubeTexture(textureProperties, texture, slot) {
16552 if (texture.image.length !== 6) return;
16553 initTexture(textureProperties, texture);
16554 state.activeTexture(33984 + slot);
16555 state.bindTexture(34067, textureProperties.__webglTexture);
16557 _gl.pixelStorei(37440, texture.flipY);
16559 _gl.pixelStorei(37441, texture.premultiplyAlpha);
16561 _gl.pixelStorei(3317, texture.unpackAlignment);
16563 var isCompressed = texture && (texture.isCompressedTexture || texture.image[0].isCompressedTexture);
16564 var isDataTexture = texture.image[0] && texture.image[0].isDataTexture;
16565 var cubeImage = [];
16567 for (var i = 0; i < 6; i++) {
16568 if (!isCompressed && !isDataTexture) {
16569 cubeImage[i] = resizeImage(texture.image[i], false, true, maxCubemapSize);
16571 cubeImage[i] = isDataTexture ? texture.image[i].image : texture.image[i];
16575 var image = cubeImage[0],
16576 supportsMips = isPowerOfTwo(image) || isWebGL2,
16577 glFormat = utils.convert(texture.format),
16578 glType = utils.convert(texture.type),
16579 glInternalFormat = getInternalFormat(texture.internalFormat, glFormat, glType);
16580 setTextureParameters(34067, texture, supportsMips);
16583 if (isCompressed) {
16584 for (var _i3 = 0; _i3 < 6; _i3++) {
16585 mipmaps = cubeImage[_i3].mipmaps;
16587 for (var j = 0; j < mipmaps.length; j++) {
16588 var mipmap = mipmaps[j];
16590 if (texture.format !== RGBAFormat && texture.format !== RGBFormat) {
16591 if (glFormat !== null) {
16592 state.compressedTexImage2D(34069 + _i3, j, glInternalFormat, mipmap.width, mipmap.height, 0, mipmap.data);
16594 console.warn('THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .setTextureCube()');
16597 state.texImage2D(34069 + _i3, j, glInternalFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data);
16602 textureProperties.__maxMipLevel = mipmaps.length - 1;
16604 mipmaps = texture.mipmaps;
16606 for (var _i4 = 0; _i4 < 6; _i4++) {
16607 if (isDataTexture) {
16608 state.texImage2D(34069 + _i4, 0, glInternalFormat, cubeImage[_i4].width, cubeImage[_i4].height, 0, glFormat, glType, cubeImage[_i4].data);
16610 for (var _j = 0; _j < mipmaps.length; _j++) {
16611 var _mipmap = mipmaps[_j];
16612 var mipmapImage = _mipmap.image[_i4].image;
16613 state.texImage2D(34069 + _i4, _j + 1, glInternalFormat, mipmapImage.width, mipmapImage.height, 0, glFormat, glType, mipmapImage.data);
16616 state.texImage2D(34069 + _i4, 0, glInternalFormat, glFormat, glType, cubeImage[_i4]);
16618 for (var _j2 = 0; _j2 < mipmaps.length; _j2++) {
16619 var _mipmap2 = mipmaps[_j2];
16620 state.texImage2D(34069 + _i4, _j2 + 1, glInternalFormat, glFormat, glType, _mipmap2.image[_i4]);
16625 textureProperties.__maxMipLevel = mipmaps.length;
16628 if (textureNeedsGenerateMipmaps(texture, supportsMips)) {
16629 // We assume images for cube map have the same size.
16630 generateMipmap(34067, texture, image.width, image.height);
16633 textureProperties.__version = texture.version;
16634 if (texture.onUpdate) texture.onUpdate(texture);
16635 } // Render targets
16636 // Setup storage for target texture and bind it to correct framebuffer
16639 function setupFrameBufferTexture(framebuffer, renderTarget, attachment, textureTarget) {
16640 var glFormat = utils.convert(renderTarget.texture.format);
16641 var glType = utils.convert(renderTarget.texture.type);
16642 var glInternalFormat = getInternalFormat(renderTarget.texture.internalFormat, glFormat, glType);
16643 state.texImage2D(textureTarget, 0, glInternalFormat, renderTarget.width, renderTarget.height, 0, glFormat, glType, null);
16645 _gl.bindFramebuffer(36160, framebuffer);
16647 _gl.framebufferTexture2D(36160, attachment, textureTarget, properties.get(renderTarget.texture).__webglTexture, 0);
16649 _gl.bindFramebuffer(36160, null);
16650 } // Setup storage for internal depth/stencil buffers and bind to correct framebuffer
16653 function setupRenderBufferStorage(renderbuffer, renderTarget, isMultisample) {
16654 _gl.bindRenderbuffer(36161, renderbuffer);
16656 if (renderTarget.depthBuffer && !renderTarget.stencilBuffer) {
16657 var glInternalFormat = 33189;
16659 if (isMultisample) {
16660 var depthTexture = renderTarget.depthTexture;
16662 if (depthTexture && depthTexture.isDepthTexture) {
16663 if (depthTexture.type === FloatType) {
16664 glInternalFormat = 36012;
16665 } else if (depthTexture.type === UnsignedIntType) {
16666 glInternalFormat = 33190;
16670 var samples = getRenderTargetSamples(renderTarget);
16672 _gl.renderbufferStorageMultisample(36161, samples, glInternalFormat, renderTarget.width, renderTarget.height);
16674 _gl.renderbufferStorage(36161, glInternalFormat, renderTarget.width, renderTarget.height);
16677 _gl.framebufferRenderbuffer(36160, 36096, 36161, renderbuffer);
16678 } else if (renderTarget.depthBuffer && renderTarget.stencilBuffer) {
16679 if (isMultisample) {
16680 var _samples = getRenderTargetSamples(renderTarget);
16682 _gl.renderbufferStorageMultisample(36161, _samples, 35056, renderTarget.width, renderTarget.height);
16684 _gl.renderbufferStorage(36161, 34041, renderTarget.width, renderTarget.height);
16687 _gl.framebufferRenderbuffer(36160, 33306, 36161, renderbuffer);
16689 var glFormat = utils.convert(renderTarget.texture.format);
16690 var glType = utils.convert(renderTarget.texture.type);
16692 var _glInternalFormat = getInternalFormat(renderTarget.texture.internalFormat, glFormat, glType);
16694 if (isMultisample) {
16695 var _samples2 = getRenderTargetSamples(renderTarget);
16697 _gl.renderbufferStorageMultisample(36161, _samples2, _glInternalFormat, renderTarget.width, renderTarget.height);
16699 _gl.renderbufferStorage(36161, _glInternalFormat, renderTarget.width, renderTarget.height);
16703 _gl.bindRenderbuffer(36161, null);
16704 } // Setup resources for a Depth Texture for a FBO (needs an extension)
16707 function setupDepthTexture(framebuffer, renderTarget) {
16708 var isCube = renderTarget && renderTarget.isWebGLCubeRenderTarget;
16709 if (isCube) throw new Error('Depth Texture with cube render targets is not supported');
16711 _gl.bindFramebuffer(36160, framebuffer);
16713 if (!(renderTarget.depthTexture && renderTarget.depthTexture.isDepthTexture)) {
16714 throw new Error('renderTarget.depthTexture must be an instance of THREE.DepthTexture');
16715 } // upload an empty depth texture with framebuffer size
16718 if (!properties.get(renderTarget.depthTexture).__webglTexture || renderTarget.depthTexture.image.width !== renderTarget.width || renderTarget.depthTexture.image.height !== renderTarget.height) {
16719 renderTarget.depthTexture.image.width = renderTarget.width;
16720 renderTarget.depthTexture.image.height = renderTarget.height;
16721 renderTarget.depthTexture.needsUpdate = true;
16724 setTexture2D(renderTarget.depthTexture, 0);
16726 var webglDepthTexture = properties.get(renderTarget.depthTexture).__webglTexture;
16728 if (renderTarget.depthTexture.format === DepthFormat) {
16729 _gl.framebufferTexture2D(36160, 36096, 3553, webglDepthTexture, 0);
16730 } else if (renderTarget.depthTexture.format === DepthStencilFormat) {
16731 _gl.framebufferTexture2D(36160, 33306, 3553, webglDepthTexture, 0);
16733 throw new Error('Unknown depthTexture format');
16735 } // Setup GL resources for a non-texture depth buffer
16738 function setupDepthRenderbuffer(renderTarget) {
16739 var renderTargetProperties = properties.get(renderTarget);
16740 var isCube = renderTarget.isWebGLCubeRenderTarget === true;
16742 if (renderTarget.depthTexture) {
16743 if (isCube) throw new Error('target.depthTexture not supported in Cube render targets');
16744 setupDepthTexture(renderTargetProperties.__webglFramebuffer, renderTarget);
16747 renderTargetProperties.__webglDepthbuffer = [];
16749 for (var i = 0; i < 6; i++) {
16750 _gl.bindFramebuffer(36160, renderTargetProperties.__webglFramebuffer[i]);
16752 renderTargetProperties.__webglDepthbuffer[i] = _gl.createRenderbuffer();
16753 setupRenderBufferStorage(renderTargetProperties.__webglDepthbuffer[i], renderTarget, false);
16756 _gl.bindFramebuffer(36160, renderTargetProperties.__webglFramebuffer);
16758 renderTargetProperties.__webglDepthbuffer = _gl.createRenderbuffer();
16759 setupRenderBufferStorage(renderTargetProperties.__webglDepthbuffer, renderTarget, false);
16763 _gl.bindFramebuffer(36160, null);
16764 } // Set up GL resources for the render target
16767 function setupRenderTarget(renderTarget) {
16768 var renderTargetProperties = properties.get(renderTarget);
16769 var textureProperties = properties.get(renderTarget.texture);
16770 renderTarget.addEventListener('dispose', onRenderTargetDispose);
16771 textureProperties.__webglTexture = _gl.createTexture();
16772 info.memory.textures++;
16773 var isCube = renderTarget.isWebGLCubeRenderTarget === true;
16774 var isMultisample = renderTarget.isWebGLMultisampleRenderTarget === true;
16775 var supportsMips = isPowerOfTwo(renderTarget) || isWebGL2; // Handles WebGL2 RGBFormat fallback - #18858
16777 if (isWebGL2 && renderTarget.texture.format === RGBFormat && (renderTarget.texture.type === FloatType || renderTarget.texture.type === HalfFloatType)) {
16778 renderTarget.texture.format = RGBAFormat;
16779 console.warn('THREE.WebGLRenderer: Rendering to textures with RGB format is not supported. Using RGBA format instead.');
16780 } // Setup framebuffer
16784 renderTargetProperties.__webglFramebuffer = [];
16786 for (var i = 0; i < 6; i++) {
16787 renderTargetProperties.__webglFramebuffer[i] = _gl.createFramebuffer();
16790 renderTargetProperties.__webglFramebuffer = _gl.createFramebuffer();
16792 if (isMultisample) {
16794 renderTargetProperties.__webglMultisampledFramebuffer = _gl.createFramebuffer();
16795 renderTargetProperties.__webglColorRenderbuffer = _gl.createRenderbuffer();
16797 _gl.bindRenderbuffer(36161, renderTargetProperties.__webglColorRenderbuffer);
16799 var glFormat = utils.convert(renderTarget.texture.format);
16800 var glType = utils.convert(renderTarget.texture.type);
16801 var glInternalFormat = getInternalFormat(renderTarget.texture.internalFormat, glFormat, glType);
16802 var samples = getRenderTargetSamples(renderTarget);
16804 _gl.renderbufferStorageMultisample(36161, samples, glInternalFormat, renderTarget.width, renderTarget.height);
16806 _gl.bindFramebuffer(36160, renderTargetProperties.__webglMultisampledFramebuffer);
16808 _gl.framebufferRenderbuffer(36160, 36064, 36161, renderTargetProperties.__webglColorRenderbuffer);
16810 _gl.bindRenderbuffer(36161, null);
16812 if (renderTarget.depthBuffer) {
16813 renderTargetProperties.__webglDepthRenderbuffer = _gl.createRenderbuffer();
16814 setupRenderBufferStorage(renderTargetProperties.__webglDepthRenderbuffer, renderTarget, true);
16817 _gl.bindFramebuffer(36160, null);
16819 console.warn('THREE.WebGLRenderer: WebGLMultisampleRenderTarget can only be used with WebGL2.');
16822 } // Setup color buffer
16826 state.bindTexture(34067, textureProperties.__webglTexture);
16827 setTextureParameters(34067, renderTarget.texture, supportsMips);
16829 for (var _i5 = 0; _i5 < 6; _i5++) {
16830 setupFrameBufferTexture(renderTargetProperties.__webglFramebuffer[_i5], renderTarget, 36064, 34069 + _i5);
16833 if (textureNeedsGenerateMipmaps(renderTarget.texture, supportsMips)) {
16834 generateMipmap(34067, renderTarget.texture, renderTarget.width, renderTarget.height);
16837 state.bindTexture(34067, null);
16839 state.bindTexture(3553, textureProperties.__webglTexture);
16840 setTextureParameters(3553, renderTarget.texture, supportsMips);
16841 setupFrameBufferTexture(renderTargetProperties.__webglFramebuffer, renderTarget, 36064, 3553);
16843 if (textureNeedsGenerateMipmaps(renderTarget.texture, supportsMips)) {
16844 generateMipmap(3553, renderTarget.texture, renderTarget.width, renderTarget.height);
16847 state.bindTexture(3553, null);
16848 } // Setup depth and stencil buffers
16851 if (renderTarget.depthBuffer) {
16852 setupDepthRenderbuffer(renderTarget);
16856 function updateRenderTargetMipmap(renderTarget) {
16857 var texture = renderTarget.texture;
16858 var supportsMips = isPowerOfTwo(renderTarget) || isWebGL2;
16860 if (textureNeedsGenerateMipmaps(texture, supportsMips)) {
16861 var target = renderTarget.isWebGLCubeRenderTarget ? 34067 : 3553;
16863 var webglTexture = properties.get(texture).__webglTexture;
16865 state.bindTexture(target, webglTexture);
16866 generateMipmap(target, texture, renderTarget.width, renderTarget.height);
16867 state.bindTexture(target, null);
16871 function updateMultisampleRenderTarget(renderTarget) {
16872 if (renderTarget.isWebGLMultisampleRenderTarget) {
16874 var renderTargetProperties = properties.get(renderTarget);
16876 _gl.bindFramebuffer(36008, renderTargetProperties.__webglMultisampledFramebuffer);
16878 _gl.bindFramebuffer(36009, renderTargetProperties.__webglFramebuffer);
16880 var width = renderTarget.width;
16881 var height = renderTarget.height;
16883 if (renderTarget.depthBuffer) mask |= 256;
16884 if (renderTarget.stencilBuffer) mask |= 1024;
16886 _gl.blitFramebuffer(0, 0, width, height, 0, 0, width, height, mask, 9728);
16888 _gl.bindFramebuffer(36160, renderTargetProperties.__webglMultisampledFramebuffer); // see #18905
16891 console.warn('THREE.WebGLRenderer: WebGLMultisampleRenderTarget can only be used with WebGL2.');
16896 function getRenderTargetSamples(renderTarget) {
16897 return isWebGL2 && renderTarget.isWebGLMultisampleRenderTarget ? Math.min(maxSamples, renderTarget.samples) : 0;
16900 function updateVideoTexture(texture) {
16901 var frame = info.render.frame; // Check the last frame we updated the VideoTexture
16903 if (_videoTextures.get(texture) !== frame) {
16904 _videoTextures.set(texture, frame);
16908 } // backwards compatibility
16911 var warnedTexture2D = false;
16912 var warnedTextureCube = false;
16914 function safeSetTexture2D(texture, slot) {
16915 if (texture && texture.isWebGLRenderTarget) {
16916 if (warnedTexture2D === false) {
16917 console.warn('THREE.WebGLTextures.safeSetTexture2D: don\'t use render targets as textures. Use their .texture property instead.');
16918 warnedTexture2D = true;
16921 texture = texture.texture;
16924 setTexture2D(texture, slot);
16927 function safeSetTextureCube(texture, slot) {
16928 if (texture && texture.isWebGLCubeRenderTarget) {
16929 if (warnedTextureCube === false) {
16930 console.warn('THREE.WebGLTextures.safeSetTextureCube: don\'t use cube render targets as textures. Use their .texture property instead.');
16931 warnedTextureCube = true;
16934 texture = texture.texture;
16937 setTextureCube(texture, slot);
16941 this.allocateTextureUnit = allocateTextureUnit;
16942 this.resetTextureUnits = resetTextureUnits;
16943 this.setTexture2D = setTexture2D;
16944 this.setTexture2DArray = setTexture2DArray;
16945 this.setTexture3D = setTexture3D;
16946 this.setTextureCube = setTextureCube;
16947 this.setupRenderTarget = setupRenderTarget;
16948 this.updateRenderTargetMipmap = updateRenderTargetMipmap;
16949 this.updateMultisampleRenderTarget = updateMultisampleRenderTarget;
16950 this.safeSetTexture2D = safeSetTexture2D;
16951 this.safeSetTextureCube = safeSetTextureCube;
16954 function WebGLUtils(gl, extensions, capabilities) {
16955 var isWebGL2 = capabilities.isWebGL2;
16957 function convert(p) {
16959 if (p === UnsignedByteType) return 5121;
16960 if (p === UnsignedShort4444Type) return 32819;
16961 if (p === UnsignedShort5551Type) return 32820;
16962 if (p === UnsignedShort565Type) return 33635;
16963 if (p === ByteType) return 5120;
16964 if (p === ShortType) return 5122;
16965 if (p === UnsignedShortType) return 5123;
16966 if (p === IntType) return 5124;
16967 if (p === UnsignedIntType) return 5125;
16968 if (p === FloatType) return 5126;
16970 if (p === HalfFloatType) {
16971 if (isWebGL2) return 5131;
16972 extension = extensions.get('OES_texture_half_float');
16974 if (extension !== null) {
16975 return extension.HALF_FLOAT_OES;
16981 if (p === AlphaFormat) return 6406;
16982 if (p === RGBFormat) return 6407;
16983 if (p === RGBAFormat) return 6408;
16984 if (p === LuminanceFormat) return 6409;
16985 if (p === LuminanceAlphaFormat) return 6410;
16986 if (p === DepthFormat) return 6402;
16987 if (p === DepthStencilFormat) return 34041;
16988 if (p === RedFormat) return 6403; // WebGL2 formats.
16990 if (p === RedIntegerFormat) return 36244;
16991 if (p === RGFormat) return 33319;
16992 if (p === RGIntegerFormat) return 33320;
16993 if (p === RGBIntegerFormat) return 36248;
16994 if (p === RGBAIntegerFormat) return 36249;
16996 if (p === RGB_S3TC_DXT1_Format || p === RGBA_S3TC_DXT1_Format || p === RGBA_S3TC_DXT3_Format || p === RGBA_S3TC_DXT5_Format) {
16997 extension = extensions.get('WEBGL_compressed_texture_s3tc');
16999 if (extension !== null) {
17000 if (p === RGB_S3TC_DXT1_Format) return extension.COMPRESSED_RGB_S3TC_DXT1_EXT;
17001 if (p === RGBA_S3TC_DXT1_Format) return extension.COMPRESSED_RGBA_S3TC_DXT1_EXT;
17002 if (p === RGBA_S3TC_DXT3_Format) return extension.COMPRESSED_RGBA_S3TC_DXT3_EXT;
17003 if (p === RGBA_S3TC_DXT5_Format) return extension.COMPRESSED_RGBA_S3TC_DXT5_EXT;
17009 if (p === RGB_PVRTC_4BPPV1_Format || p === RGB_PVRTC_2BPPV1_Format || p === RGBA_PVRTC_4BPPV1_Format || p === RGBA_PVRTC_2BPPV1_Format) {
17010 extension = extensions.get('WEBGL_compressed_texture_pvrtc');
17012 if (extension !== null) {
17013 if (p === RGB_PVRTC_4BPPV1_Format) return extension.COMPRESSED_RGB_PVRTC_4BPPV1_IMG;
17014 if (p === RGB_PVRTC_2BPPV1_Format) return extension.COMPRESSED_RGB_PVRTC_2BPPV1_IMG;
17015 if (p === RGBA_PVRTC_4BPPV1_Format) return extension.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG;
17016 if (p === RGBA_PVRTC_2BPPV1_Format) return extension.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG;
17022 if (p === RGB_ETC1_Format) {
17023 extension = extensions.get('WEBGL_compressed_texture_etc1');
17025 if (extension !== null) {
17026 return extension.COMPRESSED_RGB_ETC1_WEBGL;
17032 if (p === RGB_ETC2_Format || p === RGBA_ETC2_EAC_Format) {
17033 extension = extensions.get('WEBGL_compressed_texture_etc');
17035 if (extension !== null) {
17036 if (p === RGB_ETC2_Format) return extension.COMPRESSED_RGB8_ETC2;
17037 if (p === RGBA_ETC2_EAC_Format) return extension.COMPRESSED_RGBA8_ETC2_EAC;
17041 if (p === RGBA_ASTC_4x4_Format || p === RGBA_ASTC_5x4_Format || p === RGBA_ASTC_5x5_Format || p === RGBA_ASTC_6x5_Format || p === RGBA_ASTC_6x6_Format || p === RGBA_ASTC_8x5_Format || p === RGBA_ASTC_8x6_Format || p === RGBA_ASTC_8x8_Format || p === RGBA_ASTC_10x5_Format || p === RGBA_ASTC_10x6_Format || p === RGBA_ASTC_10x8_Format || p === RGBA_ASTC_10x10_Format || p === RGBA_ASTC_12x10_Format || p === RGBA_ASTC_12x12_Format || p === SRGB8_ALPHA8_ASTC_4x4_Format || p === SRGB8_ALPHA8_ASTC_5x4_Format || p === SRGB8_ALPHA8_ASTC_5x5_Format || p === SRGB8_ALPHA8_ASTC_6x5_Format || p === SRGB8_ALPHA8_ASTC_6x6_Format || p === SRGB8_ALPHA8_ASTC_8x5_Format || p === SRGB8_ALPHA8_ASTC_8x6_Format || p === SRGB8_ALPHA8_ASTC_8x8_Format || p === SRGB8_ALPHA8_ASTC_10x5_Format || p === SRGB8_ALPHA8_ASTC_10x6_Format || p === SRGB8_ALPHA8_ASTC_10x8_Format || p === SRGB8_ALPHA8_ASTC_10x10_Format || p === SRGB8_ALPHA8_ASTC_12x10_Format || p === SRGB8_ALPHA8_ASTC_12x12_Format) {
17042 extension = extensions.get('WEBGL_compressed_texture_astc');
17044 if (extension !== null) {
17052 if (p === RGBA_BPTC_Format) {
17053 extension = extensions.get('EXT_texture_compression_bptc');
17055 if (extension !== null) {
17063 if (p === UnsignedInt248Type) {
17064 if (isWebGL2) return 34042;
17065 extension = extensions.get('WEBGL_depth_texture');
17067 if (extension !== null) {
17068 return extension.UNSIGNED_INT_24_8_WEBGL;
17080 function ArrayCamera(array) {
17081 if (array === void 0) {
17085 PerspectiveCamera.call(this);
17086 this.cameras = array;
17089 ArrayCamera.prototype = Object.assign(Object.create(PerspectiveCamera.prototype), {
17090 constructor: ArrayCamera,
17091 isArrayCamera: true
17095 Object3D.call(this);
17096 this.type = 'Group';
17099 Group.prototype = Object.assign(Object.create(Object3D.prototype), {
17100 constructor: Group,
17104 function WebXRController() {
17105 this._targetRay = null;
17110 Object.assign(WebXRController.prototype, {
17111 constructor: WebXRController,
17112 getHandSpace: function getHandSpace() {
17113 if (this._hand === null) {
17114 this._hand = new Group();
17115 this._hand.matrixAutoUpdate = false;
17116 this._hand.visible = false;
17117 this._hand.joints = {};
17118 this._hand.inputState = {
17125 getTargetRaySpace: function getTargetRaySpace() {
17126 if (this._targetRay === null) {
17127 this._targetRay = new Group();
17128 this._targetRay.matrixAutoUpdate = false;
17129 this._targetRay.visible = false;
17132 return this._targetRay;
17134 getGripSpace: function getGripSpace() {
17135 if (this._grip === null) {
17136 this._grip = new Group();
17137 this._grip.matrixAutoUpdate = false;
17138 this._grip.visible = false;
17143 dispatchEvent: function dispatchEvent(event) {
17144 if (this._targetRay !== null) {
17145 this._targetRay.dispatchEvent(event);
17148 if (this._grip !== null) {
17149 this._grip.dispatchEvent(event);
17152 if (this._hand !== null) {
17153 this._hand.dispatchEvent(event);
17158 disconnect: function disconnect(inputSource) {
17159 this.dispatchEvent({
17160 type: 'disconnected',
17164 if (this._targetRay !== null) {
17165 this._targetRay.visible = false;
17168 if (this._grip !== null) {
17169 this._grip.visible = false;
17172 if (this._hand !== null) {
17173 this._hand.visible = false;
17178 update: function update(inputSource, frame, referenceSpace) {
17179 var inputPose = null;
17180 var gripPose = null;
17181 var handPose = null;
17182 var targetRay = this._targetRay;
17183 var grip = this._grip;
17184 var hand = this._hand;
17186 if (inputSource && frame.session.visibilityState !== 'visible-blurred') {
17187 if (hand && inputSource.hand) {
17190 for (var _iterator = _createForOfIteratorHelperLoose(inputSource.hand.values()), _step; !(_step = _iterator()).done;) {
17191 var inputjoint = _step.value;
17192 // Update the joints groups with the XRJoint poses
17193 var jointPose = frame.getJointPose(inputjoint, referenceSpace);
17195 if (hand.joints[inputjoint.jointName] === undefined) {
17196 // The transform of this joint will be updated with the joint pose on each frame
17197 var _joint = new Group();
17199 _joint.matrixAutoUpdate = false;
17200 _joint.visible = false;
17201 hand.joints[inputjoint.jointName] = _joint; // ??
17206 var joint = hand.joints[inputjoint.jointName];
17208 if (jointPose !== null) {
17209 joint.matrix.fromArray(jointPose.transform.matrix);
17210 joint.matrix.decompose(joint.position, joint.rotation, joint.scale);
17211 joint.jointRadius = jointPose.radius;
17214 joint.visible = jointPose !== null;
17219 var indexTip = hand.joints['index-finger-tip'];
17220 var thumbTip = hand.joints['thumb-tip'];
17221 var distance = indexTip.position.distanceTo(thumbTip.position);
17222 var distanceToPinch = 0.02;
17223 var threshold = 0.005;
17225 if (hand.inputState.pinching && distance > distanceToPinch + threshold) {
17226 hand.inputState.pinching = false;
17227 this.dispatchEvent({
17229 handedness: inputSource.handedness,
17232 } else if (!hand.inputState.pinching && distance <= distanceToPinch - threshold) {
17233 hand.inputState.pinching = true;
17234 this.dispatchEvent({
17235 type: 'pinchstart',
17236 handedness: inputSource.handedness,
17241 if (targetRay !== null) {
17242 inputPose = frame.getPose(inputSource.targetRaySpace, referenceSpace);
17244 if (inputPose !== null) {
17245 targetRay.matrix.fromArray(inputPose.transform.matrix);
17246 targetRay.matrix.decompose(targetRay.position, targetRay.rotation, targetRay.scale);
17250 if (grip !== null && inputSource.gripSpace) {
17251 gripPose = frame.getPose(inputSource.gripSpace, referenceSpace);
17253 if (gripPose !== null) {
17254 grip.matrix.fromArray(gripPose.transform.matrix);
17255 grip.matrix.decompose(grip.position, grip.rotation, grip.scale);
17261 if (targetRay !== null) {
17262 targetRay.visible = inputPose !== null;
17265 if (grip !== null) {
17266 grip.visible = gripPose !== null;
17269 if (hand !== null) {
17270 hand.visible = handPose !== null;
17277 function WebXRManager(renderer, gl) {
17279 var session = null;
17280 var framebufferScaleFactor = 1.0;
17281 var referenceSpace = null;
17282 var referenceSpaceType = 'local-floor';
17284 var controllers = [];
17285 var inputSourcesMap = new Map(); //
17287 var cameraL = new PerspectiveCamera();
17288 cameraL.layers.enable(1);
17289 cameraL.viewport = new Vector4();
17290 var cameraR = new PerspectiveCamera();
17291 cameraR.layers.enable(2);
17292 cameraR.viewport = new Vector4();
17293 var cameras = [cameraL, cameraR];
17294 var cameraVR = new ArrayCamera();
17295 cameraVR.layers.enable(1);
17296 cameraVR.layers.enable(2);
17297 var _currentDepthNear = null;
17298 var _currentDepthFar = null; //
17300 this.enabled = false;
17301 this.isPresenting = false;
17303 this.getController = function (index) {
17304 var controller = controllers[index];
17306 if (controller === undefined) {
17307 controller = new WebXRController();
17308 controllers[index] = controller;
17311 return controller.getTargetRaySpace();
17314 this.getControllerGrip = function (index) {
17315 var controller = controllers[index];
17317 if (controller === undefined) {
17318 controller = new WebXRController();
17319 controllers[index] = controller;
17322 return controller.getGripSpace();
17325 this.getHand = function (index) {
17326 var controller = controllers[index];
17328 if (controller === undefined) {
17329 controller = new WebXRController();
17330 controllers[index] = controller;
17333 return controller.getHandSpace();
17337 function onSessionEvent(event) {
17338 var controller = inputSourcesMap.get(event.inputSource);
17341 controller.dispatchEvent({
17343 data: event.inputSource
17348 function onSessionEnd() {
17349 inputSourcesMap.forEach(function (controller, inputSource) {
17350 controller.disconnect(inputSource);
17352 inputSourcesMap.clear();
17353 _currentDepthNear = null;
17354 _currentDepthFar = null; //
17356 renderer.setFramebuffer(null);
17357 renderer.setRenderTarget(renderer.getRenderTarget()); // Hack #15830
17360 scope.isPresenting = false;
17361 scope.dispatchEvent({
17366 this.setFramebufferScaleFactor = function (value) {
17367 framebufferScaleFactor = value;
17369 if (scope.isPresenting === true) {
17370 console.warn('THREE.WebXRManager: Cannot change framebuffer scale while presenting.');
17374 this.setReferenceSpaceType = function (value) {
17375 referenceSpaceType = value;
17377 if (scope.isPresenting === true) {
17378 console.warn('THREE.WebXRManager: Cannot change reference space type while presenting.');
17382 this.getReferenceSpace = function () {
17383 return referenceSpace;
17386 this.getSession = function () {
17390 this.setSession = /*#__PURE__*/function () {
17391 var _ref = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee(value) {
17392 var attributes, layerInit, baseLayer;
17393 return regeneratorRuntime.wrap(function _callee$(_context) {
17395 switch (_context.prev = _context.next) {
17399 if (!(session !== null)) {
17400 _context.next = 24;
17404 session.addEventListener('select', onSessionEvent);
17405 session.addEventListener('selectstart', onSessionEvent);
17406 session.addEventListener('selectend', onSessionEvent);
17407 session.addEventListener('squeeze', onSessionEvent);
17408 session.addEventListener('squeezestart', onSessionEvent);
17409 session.addEventListener('squeezeend', onSessionEvent);
17410 session.addEventListener('end', onSessionEnd);
17411 session.addEventListener('inputsourceschange', onInputSourcesChange);
17412 attributes = gl.getContextAttributes();
17414 if (!(attributes.xrCompatible !== true)) {
17415 _context.next = 14;
17419 _context.next = 14;
17420 return gl.makeXRCompatible();
17424 antialias: attributes.antialias,
17425 alpha: attributes.alpha,
17426 depth: attributes.depth,
17427 stencil: attributes.stencil,
17428 framebufferScaleFactor: framebufferScaleFactor
17429 }; // eslint-disable-next-line no-undef
17431 baseLayer = new XRWebGLLayer(session, gl, layerInit);
17432 session.updateRenderState({
17433 baseLayer: baseLayer
17435 _context.next = 19;
17436 return session.requestReferenceSpace(referenceSpaceType);
17439 referenceSpace = _context.sent;
17440 animation.setContext(session);
17442 scope.isPresenting = true;
17443 scope.dispatchEvent({
17444 type: 'sessionstart'
17449 return _context.stop();
17455 return function (_x) {
17456 return _ref.apply(this, arguments);
17460 function onInputSourcesChange(event) {
17461 var inputSources = session.inputSources; // Assign inputSources to available controllers
17463 for (var i = 0; i < controllers.length; i++) {
17464 inputSourcesMap.set(inputSources[i], controllers[i]);
17465 } // Notify disconnected
17468 for (var _i = 0; _i < event.removed.length; _i++) {
17469 var inputSource = event.removed[_i];
17470 var controller = inputSourcesMap.get(inputSource);
17473 controller.dispatchEvent({
17474 type: 'disconnected',
17477 inputSourcesMap.delete(inputSource);
17479 } // Notify connected
17482 for (var _i2 = 0; _i2 < event.added.length; _i2++) {
17483 var _inputSource = event.added[_i2];
17485 var _controller = inputSourcesMap.get(_inputSource);
17488 _controller.dispatchEvent({
17497 var cameraLPos = new Vector3();
17498 var cameraRPos = new Vector3();
17500 * Assumes 2 cameras that are parallel and share an X-axis, and that
17501 * the cameras' projection and world matrices have already been set.
17502 * And that near and far planes are identical for both cameras.
17503 * Visualization of this technique: https://computergraphics.stackexchange.com/a/4765
17506 function setProjectionFromUnion(camera, cameraL, cameraR) {
17507 cameraLPos.setFromMatrixPosition(cameraL.matrixWorld);
17508 cameraRPos.setFromMatrixPosition(cameraR.matrixWorld);
17509 var ipd = cameraLPos.distanceTo(cameraRPos);
17510 var projL = cameraL.projectionMatrix.elements;
17511 var projR = cameraR.projectionMatrix.elements; // VR systems will have identical far and near planes, and
17512 // most likely identical top and bottom frustum extents.
17513 // Use the left camera for these values.
17515 var near = projL[14] / (projL[10] - 1);
17516 var far = projL[14] / (projL[10] + 1);
17517 var topFov = (projL[9] + 1) / projL[5];
17518 var bottomFov = (projL[9] - 1) / projL[5];
17519 var leftFov = (projL[8] - 1) / projL[0];
17520 var rightFov = (projR[8] + 1) / projR[0];
17521 var left = near * leftFov;
17522 var right = near * rightFov; // Calculate the new camera's position offset from the
17523 // left camera. xOffset should be roughly half `ipd`.
17525 var zOffset = ipd / (-leftFov + rightFov);
17526 var xOffset = zOffset * -leftFov; // TODO: Better way to apply this offset?
17528 cameraL.matrixWorld.decompose(camera.position, camera.quaternion, camera.scale);
17529 camera.translateX(xOffset);
17530 camera.translateZ(zOffset);
17531 camera.matrixWorld.compose(camera.position, camera.quaternion, camera.scale);
17532 camera.matrixWorldInverse.copy(camera.matrixWorld).invert(); // Find the union of the frustum values of the cameras and scale
17533 // the values so that the near plane's position does not change in world space,
17534 // although must now be relative to the new union camera.
17536 var near2 = near + zOffset;
17537 var far2 = far + zOffset;
17538 var left2 = left - xOffset;
17539 var right2 = right + (ipd - xOffset);
17540 var top2 = topFov * far / far2 * near2;
17541 var bottom2 = bottomFov * far / far2 * near2;
17542 camera.projectionMatrix.makePerspective(left2, right2, top2, bottom2, near2, far2);
17545 function updateCamera(camera, parent) {
17546 if (parent === null) {
17547 camera.matrixWorld.copy(camera.matrix);
17549 camera.matrixWorld.multiplyMatrices(parent.matrixWorld, camera.matrix);
17552 camera.matrixWorldInverse.copy(camera.matrixWorld).invert();
17555 this.getCamera = function (camera) {
17556 cameraVR.near = cameraR.near = cameraL.near = camera.near;
17557 cameraVR.far = cameraR.far = cameraL.far = camera.far;
17559 if (_currentDepthNear !== cameraVR.near || _currentDepthFar !== cameraVR.far) {
17560 // Note that the new renderState won't apply until the next frame. See #18320
17561 session.updateRenderState({
17562 depthNear: cameraVR.near,
17563 depthFar: cameraVR.far
17565 _currentDepthNear = cameraVR.near;
17566 _currentDepthFar = cameraVR.far;
17569 var parent = camera.parent;
17570 var cameras = cameraVR.cameras;
17571 updateCamera(cameraVR, parent);
17573 for (var i = 0; i < cameras.length; i++) {
17574 updateCamera(cameras[i], parent);
17575 } // update camera and its children
17578 camera.matrixWorld.copy(cameraVR.matrixWorld);
17579 camera.matrix.copy(cameraVR.matrix);
17580 camera.matrix.decompose(camera.position, camera.quaternion, camera.scale);
17581 var children = camera.children;
17583 for (var _i3 = 0, l = children.length; _i3 < l; _i3++) {
17584 children[_i3].updateMatrixWorld(true);
17585 } // update projection matrix for proper view frustum culling
17588 if (cameras.length === 2) {
17589 setProjectionFromUnion(cameraVR, cameraL, cameraR);
17591 // assume single camera setup (AR)
17592 cameraVR.projectionMatrix.copy(cameraL.projectionMatrix);
17596 }; // Animation Loop
17599 var onAnimationFrameCallback = null;
17601 function onAnimationFrame(time, frame) {
17602 pose = frame.getViewerPose(referenceSpace);
17604 if (pose !== null) {
17605 var views = pose.views;
17606 var baseLayer = session.renderState.baseLayer;
17607 renderer.setFramebuffer(baseLayer.framebuffer);
17608 var cameraVRNeedsUpdate = false; // check if it's necessary to rebuild cameraVR's camera list
17610 if (views.length !== cameraVR.cameras.length) {
17611 cameraVR.cameras.length = 0;
17612 cameraVRNeedsUpdate = true;
17615 for (var i = 0; i < views.length; i++) {
17616 var view = views[i];
17617 var viewport = baseLayer.getViewport(view);
17618 var camera = cameras[i];
17619 camera.matrix.fromArray(view.transform.matrix);
17620 camera.projectionMatrix.fromArray(view.projectionMatrix);
17621 camera.viewport.set(viewport.x, viewport.y, viewport.width, viewport.height);
17624 cameraVR.matrix.copy(camera.matrix);
17627 if (cameraVRNeedsUpdate === true) {
17628 cameraVR.cameras.push(camera);
17634 var inputSources = session.inputSources;
17636 for (var _i4 = 0; _i4 < controllers.length; _i4++) {
17637 var controller = controllers[_i4];
17638 var inputSource = inputSources[_i4];
17639 controller.update(inputSource, frame, referenceSpace);
17642 if (onAnimationFrameCallback) onAnimationFrameCallback(time, frame);
17645 var animation = new WebGLAnimation();
17646 animation.setAnimationLoop(onAnimationFrame);
17648 this.setAnimationLoop = function (callback) {
17649 onAnimationFrameCallback = callback;
17652 this.dispose = function () {};
17655 Object.assign(WebXRManager.prototype, EventDispatcher.prototype);
17657 function WebGLMaterials(properties) {
17658 function refreshFogUniforms(uniforms, fog) {
17659 uniforms.fogColor.value.copy(fog.color);
17662 uniforms.fogNear.value = fog.near;
17663 uniforms.fogFar.value = fog.far;
17664 } else if (fog.isFogExp2) {
17665 uniforms.fogDensity.value = fog.density;
17669 function refreshMaterialUniforms(uniforms, material, pixelRatio, height) {
17670 if (material.isMeshBasicMaterial) {
17671 refreshUniformsCommon(uniforms, material);
17672 } else if (material.isMeshLambertMaterial) {
17673 refreshUniformsCommon(uniforms, material);
17674 refreshUniformsLambert(uniforms, material);
17675 } else if (material.isMeshToonMaterial) {
17676 refreshUniformsCommon(uniforms, material);
17677 refreshUniformsToon(uniforms, material);
17678 } else if (material.isMeshPhongMaterial) {
17679 refreshUniformsCommon(uniforms, material);
17680 refreshUniformsPhong(uniforms, material);
17681 } else if (material.isMeshStandardMaterial) {
17682 refreshUniformsCommon(uniforms, material);
17684 if (material.isMeshPhysicalMaterial) {
17685 refreshUniformsPhysical(uniforms, material);
17687 refreshUniformsStandard(uniforms, material);
17689 } else if (material.isMeshMatcapMaterial) {
17690 refreshUniformsCommon(uniforms, material);
17691 refreshUniformsMatcap(uniforms, material);
17692 } else if (material.isMeshDepthMaterial) {
17693 refreshUniformsCommon(uniforms, material);
17694 refreshUniformsDepth(uniforms, material);
17695 } else if (material.isMeshDistanceMaterial) {
17696 refreshUniformsCommon(uniforms, material);
17697 refreshUniformsDistance(uniforms, material);
17698 } else if (material.isMeshNormalMaterial) {
17699 refreshUniformsCommon(uniforms, material);
17700 refreshUniformsNormal(uniforms, material);
17701 } else if (material.isLineBasicMaterial) {
17702 refreshUniformsLine(uniforms, material);
17704 if (material.isLineDashedMaterial) {
17705 refreshUniformsDash(uniforms, material);
17707 } else if (material.isPointsMaterial) {
17708 refreshUniformsPoints(uniforms, material, pixelRatio, height);
17709 } else if (material.isSpriteMaterial) {
17710 refreshUniformsSprites(uniforms, material);
17711 } else if (material.isShadowMaterial) {
17712 uniforms.color.value.copy(material.color);
17713 uniforms.opacity.value = material.opacity;
17714 } else if (material.isShaderMaterial) {
17715 material.uniformsNeedUpdate = false; // #15581
17719 function refreshUniformsCommon(uniforms, material) {
17720 uniforms.opacity.value = material.opacity;
17722 if (material.color) {
17723 uniforms.diffuse.value.copy(material.color);
17726 if (material.emissive) {
17727 uniforms.emissive.value.copy(material.emissive).multiplyScalar(material.emissiveIntensity);
17730 if (material.map) {
17731 uniforms.map.value = material.map;
17734 if (material.alphaMap) {
17735 uniforms.alphaMap.value = material.alphaMap;
17738 if (material.specularMap) {
17739 uniforms.specularMap.value = material.specularMap;
17742 var envMap = properties.get(material).envMap;
17745 uniforms.envMap.value = envMap;
17746 uniforms.flipEnvMap.value = envMap.isCubeTexture && envMap._needsFlipEnvMap ? -1 : 1;
17747 uniforms.reflectivity.value = material.reflectivity;
17748 uniforms.refractionRatio.value = material.refractionRatio;
17750 var maxMipLevel = properties.get(envMap).__maxMipLevel;
17752 if (maxMipLevel !== undefined) {
17753 uniforms.maxMipLevel.value = maxMipLevel;
17757 if (material.lightMap) {
17758 uniforms.lightMap.value = material.lightMap;
17759 uniforms.lightMapIntensity.value = material.lightMapIntensity;
17762 if (material.aoMap) {
17763 uniforms.aoMap.value = material.aoMap;
17764 uniforms.aoMapIntensity.value = material.aoMapIntensity;
17765 } // uv repeat and offset setting priorities
17768 // 3. displacementMap map
17771 // 6. roughnessMap map
17772 // 7. metalnessMap map
17774 // 9. emissiveMap map
17775 // 10. clearcoat map
17776 // 11. clearcoat normal map
17777 // 12. clearcoat roughnessMap map
17782 if (material.map) {
17783 uvScaleMap = material.map;
17784 } else if (material.specularMap) {
17785 uvScaleMap = material.specularMap;
17786 } else if (material.displacementMap) {
17787 uvScaleMap = material.displacementMap;
17788 } else if (material.normalMap) {
17789 uvScaleMap = material.normalMap;
17790 } else if (material.bumpMap) {
17791 uvScaleMap = material.bumpMap;
17792 } else if (material.roughnessMap) {
17793 uvScaleMap = material.roughnessMap;
17794 } else if (material.metalnessMap) {
17795 uvScaleMap = material.metalnessMap;
17796 } else if (material.alphaMap) {
17797 uvScaleMap = material.alphaMap;
17798 } else if (material.emissiveMap) {
17799 uvScaleMap = material.emissiveMap;
17800 } else if (material.clearcoatMap) {
17801 uvScaleMap = material.clearcoatMap;
17802 } else if (material.clearcoatNormalMap) {
17803 uvScaleMap = material.clearcoatNormalMap;
17804 } else if (material.clearcoatRoughnessMap) {
17805 uvScaleMap = material.clearcoatRoughnessMap;
17808 if (uvScaleMap !== undefined) {
17809 // backwards compatibility
17810 if (uvScaleMap.isWebGLRenderTarget) {
17811 uvScaleMap = uvScaleMap.texture;
17814 if (uvScaleMap.matrixAutoUpdate === true) {
17815 uvScaleMap.updateMatrix();
17818 uniforms.uvTransform.value.copy(uvScaleMap.matrix);
17819 } // uv repeat and offset setting priorities for uv2
17826 if (material.aoMap) {
17827 uv2ScaleMap = material.aoMap;
17828 } else if (material.lightMap) {
17829 uv2ScaleMap = material.lightMap;
17832 if (uv2ScaleMap !== undefined) {
17833 // backwards compatibility
17834 if (uv2ScaleMap.isWebGLRenderTarget) {
17835 uv2ScaleMap = uv2ScaleMap.texture;
17838 if (uv2ScaleMap.matrixAutoUpdate === true) {
17839 uv2ScaleMap.updateMatrix();
17842 uniforms.uv2Transform.value.copy(uv2ScaleMap.matrix);
17846 function refreshUniformsLine(uniforms, material) {
17847 uniforms.diffuse.value.copy(material.color);
17848 uniforms.opacity.value = material.opacity;
17851 function refreshUniformsDash(uniforms, material) {
17852 uniforms.dashSize.value = material.dashSize;
17853 uniforms.totalSize.value = material.dashSize + material.gapSize;
17854 uniforms.scale.value = material.scale;
17857 function refreshUniformsPoints(uniforms, material, pixelRatio, height) {
17858 uniforms.diffuse.value.copy(material.color);
17859 uniforms.opacity.value = material.opacity;
17860 uniforms.size.value = material.size * pixelRatio;
17861 uniforms.scale.value = height * 0.5;
17863 if (material.map) {
17864 uniforms.map.value = material.map;
17867 if (material.alphaMap) {
17868 uniforms.alphaMap.value = material.alphaMap;
17869 } // uv repeat and offset setting priorities
17876 if (material.map) {
17877 uvScaleMap = material.map;
17878 } else if (material.alphaMap) {
17879 uvScaleMap = material.alphaMap;
17882 if (uvScaleMap !== undefined) {
17883 if (uvScaleMap.matrixAutoUpdate === true) {
17884 uvScaleMap.updateMatrix();
17887 uniforms.uvTransform.value.copy(uvScaleMap.matrix);
17891 function refreshUniformsSprites(uniforms, material) {
17892 uniforms.diffuse.value.copy(material.color);
17893 uniforms.opacity.value = material.opacity;
17894 uniforms.rotation.value = material.rotation;
17896 if (material.map) {
17897 uniforms.map.value = material.map;
17900 if (material.alphaMap) {
17901 uniforms.alphaMap.value = material.alphaMap;
17902 } // uv repeat and offset setting priorities
17909 if (material.map) {
17910 uvScaleMap = material.map;
17911 } else if (material.alphaMap) {
17912 uvScaleMap = material.alphaMap;
17915 if (uvScaleMap !== undefined) {
17916 if (uvScaleMap.matrixAutoUpdate === true) {
17917 uvScaleMap.updateMatrix();
17920 uniforms.uvTransform.value.copy(uvScaleMap.matrix);
17924 function refreshUniformsLambert(uniforms, material) {
17925 if (material.emissiveMap) {
17926 uniforms.emissiveMap.value = material.emissiveMap;
17930 function refreshUniformsPhong(uniforms, material) {
17931 uniforms.specular.value.copy(material.specular);
17932 uniforms.shininess.value = Math.max(material.shininess, 1e-4); // to prevent pow( 0.0, 0.0 )
17934 if (material.emissiveMap) {
17935 uniforms.emissiveMap.value = material.emissiveMap;
17938 if (material.bumpMap) {
17939 uniforms.bumpMap.value = material.bumpMap;
17940 uniforms.bumpScale.value = material.bumpScale;
17941 if (material.side === BackSide) uniforms.bumpScale.value *= -1;
17944 if (material.normalMap) {
17945 uniforms.normalMap.value = material.normalMap;
17946 uniforms.normalScale.value.copy(material.normalScale);
17947 if (material.side === BackSide) uniforms.normalScale.value.negate();
17950 if (material.displacementMap) {
17951 uniforms.displacementMap.value = material.displacementMap;
17952 uniforms.displacementScale.value = material.displacementScale;
17953 uniforms.displacementBias.value = material.displacementBias;
17957 function refreshUniformsToon(uniforms, material) {
17958 if (material.gradientMap) {
17959 uniforms.gradientMap.value = material.gradientMap;
17962 if (material.emissiveMap) {
17963 uniforms.emissiveMap.value = material.emissiveMap;
17966 if (material.bumpMap) {
17967 uniforms.bumpMap.value = material.bumpMap;
17968 uniforms.bumpScale.value = material.bumpScale;
17969 if (material.side === BackSide) uniforms.bumpScale.value *= -1;
17972 if (material.normalMap) {
17973 uniforms.normalMap.value = material.normalMap;
17974 uniforms.normalScale.value.copy(material.normalScale);
17975 if (material.side === BackSide) uniforms.normalScale.value.negate();
17978 if (material.displacementMap) {
17979 uniforms.displacementMap.value = material.displacementMap;
17980 uniforms.displacementScale.value = material.displacementScale;
17981 uniforms.displacementBias.value = material.displacementBias;
17985 function refreshUniformsStandard(uniforms, material) {
17986 uniforms.roughness.value = material.roughness;
17987 uniforms.metalness.value = material.metalness;
17989 if (material.roughnessMap) {
17990 uniforms.roughnessMap.value = material.roughnessMap;
17993 if (material.metalnessMap) {
17994 uniforms.metalnessMap.value = material.metalnessMap;
17997 if (material.emissiveMap) {
17998 uniforms.emissiveMap.value = material.emissiveMap;
18001 if (material.bumpMap) {
18002 uniforms.bumpMap.value = material.bumpMap;
18003 uniforms.bumpScale.value = material.bumpScale;
18004 if (material.side === BackSide) uniforms.bumpScale.value *= -1;
18007 if (material.normalMap) {
18008 uniforms.normalMap.value = material.normalMap;
18009 uniforms.normalScale.value.copy(material.normalScale);
18010 if (material.side === BackSide) uniforms.normalScale.value.negate();
18013 if (material.displacementMap) {
18014 uniforms.displacementMap.value = material.displacementMap;
18015 uniforms.displacementScale.value = material.displacementScale;
18016 uniforms.displacementBias.value = material.displacementBias;
18019 var envMap = properties.get(material).envMap;
18022 //uniforms.envMap.value = material.envMap; // part of uniforms common
18023 uniforms.envMapIntensity.value = material.envMapIntensity;
18027 function refreshUniformsPhysical(uniforms, material) {
18028 refreshUniformsStandard(uniforms, material);
18029 uniforms.reflectivity.value = material.reflectivity; // also part of uniforms common
18031 uniforms.clearcoat.value = material.clearcoat;
18032 uniforms.clearcoatRoughness.value = material.clearcoatRoughness;
18033 if (material.sheen) uniforms.sheen.value.copy(material.sheen);
18035 if (material.clearcoatMap) {
18036 uniforms.clearcoatMap.value = material.clearcoatMap;
18039 if (material.clearcoatRoughnessMap) {
18040 uniforms.clearcoatRoughnessMap.value = material.clearcoatRoughnessMap;
18043 if (material.clearcoatNormalMap) {
18044 uniforms.clearcoatNormalScale.value.copy(material.clearcoatNormalScale);
18045 uniforms.clearcoatNormalMap.value = material.clearcoatNormalMap;
18047 if (material.side === BackSide) {
18048 uniforms.clearcoatNormalScale.value.negate();
18052 uniforms.transmission.value = material.transmission;
18054 if (material.transmissionMap) {
18055 uniforms.transmissionMap.value = material.transmissionMap;
18059 function refreshUniformsMatcap(uniforms, material) {
18060 if (material.matcap) {
18061 uniforms.matcap.value = material.matcap;
18064 if (material.bumpMap) {
18065 uniforms.bumpMap.value = material.bumpMap;
18066 uniforms.bumpScale.value = material.bumpScale;
18067 if (material.side === BackSide) uniforms.bumpScale.value *= -1;
18070 if (material.normalMap) {
18071 uniforms.normalMap.value = material.normalMap;
18072 uniforms.normalScale.value.copy(material.normalScale);
18073 if (material.side === BackSide) uniforms.normalScale.value.negate();
18076 if (material.displacementMap) {
18077 uniforms.displacementMap.value = material.displacementMap;
18078 uniforms.displacementScale.value = material.displacementScale;
18079 uniforms.displacementBias.value = material.displacementBias;
18083 function refreshUniformsDepth(uniforms, material) {
18084 if (material.displacementMap) {
18085 uniforms.displacementMap.value = material.displacementMap;
18086 uniforms.displacementScale.value = material.displacementScale;
18087 uniforms.displacementBias.value = material.displacementBias;
18091 function refreshUniformsDistance(uniforms, material) {
18092 if (material.displacementMap) {
18093 uniforms.displacementMap.value = material.displacementMap;
18094 uniforms.displacementScale.value = material.displacementScale;
18095 uniforms.displacementBias.value = material.displacementBias;
18098 uniforms.referencePosition.value.copy(material.referencePosition);
18099 uniforms.nearDistance.value = material.nearDistance;
18100 uniforms.farDistance.value = material.farDistance;
18103 function refreshUniformsNormal(uniforms, material) {
18104 if (material.bumpMap) {
18105 uniforms.bumpMap.value = material.bumpMap;
18106 uniforms.bumpScale.value = material.bumpScale;
18107 if (material.side === BackSide) uniforms.bumpScale.value *= -1;
18110 if (material.normalMap) {
18111 uniforms.normalMap.value = material.normalMap;
18112 uniforms.normalScale.value.copy(material.normalScale);
18113 if (material.side === BackSide) uniforms.normalScale.value.negate();
18116 if (material.displacementMap) {
18117 uniforms.displacementMap.value = material.displacementMap;
18118 uniforms.displacementScale.value = material.displacementScale;
18119 uniforms.displacementBias.value = material.displacementBias;
18124 refreshFogUniforms: refreshFogUniforms,
18125 refreshMaterialUniforms: refreshMaterialUniforms
18129 function createCanvasElement() {
18130 var canvas = document.createElementNS('http://www.w3.org/1999/xhtml', 'canvas');
18131 canvas.style.display = 'block';
18135 function WebGLRenderer(parameters) {
18136 parameters = parameters || {};
18138 var _canvas = parameters.canvas !== undefined ? parameters.canvas : createCanvasElement(),
18139 _context = parameters.context !== undefined ? parameters.context : null,
18140 _alpha = parameters.alpha !== undefined ? parameters.alpha : false,
18141 _depth = parameters.depth !== undefined ? parameters.depth : true,
18142 _stencil = parameters.stencil !== undefined ? parameters.stencil : true,
18143 _antialias = parameters.antialias !== undefined ? parameters.antialias : false,
18144 _premultipliedAlpha = parameters.premultipliedAlpha !== undefined ? parameters.premultipliedAlpha : true,
18145 _preserveDrawingBuffer = parameters.preserveDrawingBuffer !== undefined ? parameters.preserveDrawingBuffer : false,
18146 _powerPreference = parameters.powerPreference !== undefined ? parameters.powerPreference : 'default',
18147 _failIfMajorPerformanceCaveat = parameters.failIfMajorPerformanceCaveat !== undefined ? parameters.failIfMajorPerformanceCaveat : false;
18149 var currentRenderList = null;
18150 var currentRenderState = null; // render() can be called from within a callback triggered by another render.
18151 // We track this so that the nested render call gets its state isolated from the parent render call.
18153 var renderStateStack = []; // public properties
18155 this.domElement = _canvas; // Debug configuration container
18159 * Enables error checking and reporting when shader programs are being compiled
18162 checkShaderErrors: true
18165 this.autoClear = true;
18166 this.autoClearColor = true;
18167 this.autoClearDepth = true;
18168 this.autoClearStencil = true; // scene graph
18170 this.sortObjects = true; // user-defined clipping
18172 this.clippingPlanes = [];
18173 this.localClippingEnabled = false; // physically based shading
18175 this.gammaFactor = 2.0; // for backwards compatibility
18177 this.outputEncoding = LinearEncoding; // physical lights
18179 this.physicallyCorrectLights = false; // tone mapping
18181 this.toneMapping = NoToneMapping;
18182 this.toneMappingExposure = 1.0; // morphs
18184 this.maxMorphTargets = 8;
18185 this.maxMorphNormals = 4; // internal properties
18189 var _isContextLost = false; // internal state cache
18191 var _framebuffer = null;
18192 var _currentActiveCubeFace = 0;
18193 var _currentActiveMipmapLevel = 0;
18194 var _currentRenderTarget = null;
18195 var _currentFramebuffer = null;
18197 var _currentMaterialId = -1;
18199 var _currentCamera = null;
18201 var _currentViewport = new Vector4();
18203 var _currentScissor = new Vector4();
18205 var _currentScissorTest = null; //
18207 var _width = _canvas.width;
18208 var _height = _canvas.height;
18209 var _pixelRatio = 1;
18210 var _opaqueSort = null;
18211 var _transparentSort = null;
18213 var _viewport = new Vector4(0, 0, _width, _height);
18215 var _scissor = new Vector4(0, 0, _width, _height);
18217 var _scissorTest = false; // frustum
18219 var _frustum = new Frustum(); // clipping
18222 var _clippingEnabled = false;
18223 var _localClippingEnabled = false; // camera matrices cache
18225 var _projScreenMatrix = new Matrix4();
18227 var _vector3 = new Vector3();
18229 var _emptyScene = {
18233 overrideMaterial: null,
18237 function getTargetPixelRatio() {
18238 return _currentRenderTarget === null ? _pixelRatio : 1;
18242 var _gl = _context;
18244 function getContext(contextNames, contextAttributes) {
18245 for (var i = 0; i < contextNames.length; i++) {
18246 var contextName = contextNames[i];
18248 var context = _canvas.getContext(contextName, contextAttributes);
18250 if (context !== null) return context;
18257 var contextAttributes = {
18261 antialias: _antialias,
18262 premultipliedAlpha: _premultipliedAlpha,
18263 preserveDrawingBuffer: _preserveDrawingBuffer,
18264 powerPreference: _powerPreference,
18265 failIfMajorPerformanceCaveat: _failIfMajorPerformanceCaveat
18266 }; // event listeners must be registered before WebGL context is created, see #12753
18268 _canvas.addEventListener('webglcontextlost', onContextLost, false);
18270 _canvas.addEventListener('webglcontextrestored', onContextRestore, false);
18272 if (_gl === null) {
18273 var contextNames = ['webgl2', 'webgl', 'experimental-webgl'];
18275 if (_this.isWebGL1Renderer === true) {
18276 contextNames.shift();
18279 _gl = getContext(contextNames, contextAttributes);
18281 if (_gl === null) {
18282 if (getContext(contextNames)) {
18283 throw new Error('Error creating WebGL context with your selected attributes.');
18285 throw new Error('Error creating WebGL context.');
18288 } // Some experimental-webgl implementations do not have getShaderPrecisionFormat
18291 if (_gl.getShaderPrecisionFormat === undefined) {
18292 _gl.getShaderPrecisionFormat = function () {
18301 console.error('THREE.WebGLRenderer: ' + error.message);
18305 var extensions, capabilities, state, info;
18306 var properties, textures, cubemaps, attributes, geometries, objects;
18307 var programCache, materials, renderLists, renderStates, clipping;
18308 var background, morphtargets, bufferRenderer, indexedBufferRenderer;
18309 var utils, bindingStates;
18311 function initGLContext() {
18312 extensions = new WebGLExtensions(_gl);
18313 capabilities = new WebGLCapabilities(_gl, extensions, parameters);
18314 extensions.init(capabilities);
18315 utils = new WebGLUtils(_gl, extensions, capabilities);
18316 state = new WebGLState(_gl, extensions, capabilities);
18317 state.scissor(_currentScissor.copy(_scissor).multiplyScalar(_pixelRatio).floor());
18318 state.viewport(_currentViewport.copy(_viewport).multiplyScalar(_pixelRatio).floor());
18319 info = new WebGLInfo(_gl);
18320 properties = new WebGLProperties();
18321 textures = new WebGLTextures(_gl, extensions, state, properties, capabilities, utils, info);
18322 cubemaps = new WebGLCubeMaps(_this);
18323 attributes = new WebGLAttributes(_gl, capabilities);
18324 bindingStates = new WebGLBindingStates(_gl, extensions, attributes, capabilities);
18325 geometries = new WebGLGeometries(_gl, attributes, info, bindingStates);
18326 objects = new WebGLObjects(_gl, geometries, attributes, info);
18327 morphtargets = new WebGLMorphtargets(_gl);
18328 clipping = new WebGLClipping(properties);
18329 programCache = new WebGLPrograms(_this, cubemaps, extensions, capabilities, bindingStates, clipping);
18330 materials = new WebGLMaterials(properties);
18331 renderLists = new WebGLRenderLists(properties);
18332 renderStates = new WebGLRenderStates(extensions, capabilities);
18333 background = new WebGLBackground(_this, cubemaps, state, objects, _premultipliedAlpha);
18334 bufferRenderer = new WebGLBufferRenderer(_gl, extensions, info, capabilities);
18335 indexedBufferRenderer = new WebGLIndexedBufferRenderer(_gl, extensions, info, capabilities);
18336 info.programs = programCache.programs;
18337 _this.capabilities = capabilities;
18338 _this.extensions = extensions;
18339 _this.properties = properties;
18340 _this.renderLists = renderLists;
18341 _this.state = state;
18345 initGLContext(); // xr
18347 var xr = new WebXRManager(_this, _gl);
18348 this.xr = xr; // shadow map
18350 var shadowMap = new WebGLShadowMap(_this, objects, capabilities.maxTextureSize);
18351 this.shadowMap = shadowMap; // API
18353 this.getContext = function () {
18357 this.getContextAttributes = function () {
18358 return _gl.getContextAttributes();
18361 this.forceContextLoss = function () {
18362 var extension = extensions.get('WEBGL_lose_context');
18363 if (extension) extension.loseContext();
18366 this.forceContextRestore = function () {
18367 var extension = extensions.get('WEBGL_lose_context');
18368 if (extension) extension.restoreContext();
18371 this.getPixelRatio = function () {
18372 return _pixelRatio;
18375 this.setPixelRatio = function (value) {
18376 if (value === undefined) return;
18377 _pixelRatio = value;
18378 this.setSize(_width, _height, false);
18381 this.getSize = function (target) {
18382 if (target === undefined) {
18383 console.warn('WebGLRenderer: .getsize() now requires a Vector2 as an argument');
18384 target = new Vector2();
18387 return target.set(_width, _height);
18390 this.setSize = function (width, height, updateStyle) {
18391 if (xr.isPresenting) {
18392 console.warn('THREE.WebGLRenderer: Can\'t change size while VR device is presenting.');
18398 _canvas.width = Math.floor(width * _pixelRatio);
18399 _canvas.height = Math.floor(height * _pixelRatio);
18401 if (updateStyle !== false) {
18402 _canvas.style.width = width + 'px';
18403 _canvas.style.height = height + 'px';
18406 this.setViewport(0, 0, width, height);
18409 this.getDrawingBufferSize = function (target) {
18410 if (target === undefined) {
18411 console.warn('WebGLRenderer: .getdrawingBufferSize() now requires a Vector2 as an argument');
18412 target = new Vector2();
18415 return target.set(_width * _pixelRatio, _height * _pixelRatio).floor();
18418 this.setDrawingBufferSize = function (width, height, pixelRatio) {
18421 _pixelRatio = pixelRatio;
18422 _canvas.width = Math.floor(width * pixelRatio);
18423 _canvas.height = Math.floor(height * pixelRatio);
18424 this.setViewport(0, 0, width, height);
18427 this.getCurrentViewport = function (target) {
18428 if (target === undefined) {
18429 console.warn('WebGLRenderer: .getCurrentViewport() now requires a Vector4 as an argument');
18430 target = new Vector4();
18433 return target.copy(_currentViewport);
18436 this.getViewport = function (target) {
18437 return target.copy(_viewport);
18440 this.setViewport = function (x, y, width, height) {
18442 _viewport.set(x.x, x.y, x.z, x.w);
18444 _viewport.set(x, y, width, height);
18447 state.viewport(_currentViewport.copy(_viewport).multiplyScalar(_pixelRatio).floor());
18450 this.getScissor = function (target) {
18451 return target.copy(_scissor);
18454 this.setScissor = function (x, y, width, height) {
18456 _scissor.set(x.x, x.y, x.z, x.w);
18458 _scissor.set(x, y, width, height);
18461 state.scissor(_currentScissor.copy(_scissor).multiplyScalar(_pixelRatio).floor());
18464 this.getScissorTest = function () {
18465 return _scissorTest;
18468 this.setScissorTest = function (boolean) {
18469 state.setScissorTest(_scissorTest = boolean);
18472 this.setOpaqueSort = function (method) {
18473 _opaqueSort = method;
18476 this.setTransparentSort = function (method) {
18477 _transparentSort = method;
18481 this.getClearColor = function (target) {
18482 if (target === undefined) {
18483 console.warn('WebGLRenderer: .getClearColor() now requires a Color as an argument');
18484 target = new Color();
18487 return target.copy(background.getClearColor());
18490 this.setClearColor = function () {
18491 background.setClearColor.apply(background, arguments);
18494 this.getClearAlpha = function () {
18495 return background.getClearAlpha();
18498 this.setClearAlpha = function () {
18499 background.setClearAlpha.apply(background, arguments);
18502 this.clear = function (color, depth, stencil) {
18504 if (color === undefined || color) bits |= 16384;
18505 if (depth === undefined || depth) bits |= 256;
18506 if (stencil === undefined || stencil) bits |= 1024;
18511 this.clearColor = function () {
18512 this.clear(true, false, false);
18515 this.clearDepth = function () {
18516 this.clear(false, true, false);
18519 this.clearStencil = function () {
18520 this.clear(false, false, true);
18524 this.dispose = function () {
18525 _canvas.removeEventListener('webglcontextlost', onContextLost, false);
18527 _canvas.removeEventListener('webglcontextrestored', onContextRestore, false);
18529 renderLists.dispose();
18530 renderStates.dispose();
18531 properties.dispose();
18532 cubemaps.dispose();
18534 bindingStates.dispose();
18540 function onContextLost(event) {
18541 event.preventDefault();
18542 console.log('THREE.WebGLRenderer: Context Lost.');
18543 _isContextLost = true;
18546 function onContextRestore()
18549 console.log('THREE.WebGLRenderer: Context Restored.');
18550 _isContextLost = false;
18554 function onMaterialDispose(event) {
18555 var material = event.target;
18556 material.removeEventListener('dispose', onMaterialDispose);
18557 deallocateMaterial(material);
18558 } // Buffer deallocation
18561 function deallocateMaterial(material) {
18562 releaseMaterialProgramReference(material);
18563 properties.remove(material);
18566 function releaseMaterialProgramReference(material) {
18567 var programInfo = properties.get(material).program;
18569 if (programInfo !== undefined) {
18570 programCache.releaseProgram(programInfo);
18572 } // Buffer rendering
18575 function renderObjectImmediate(object, program) {
18576 object.render(function (object) {
18577 _this.renderBufferImmediate(object, program);
18581 this.renderBufferImmediate = function (object, program) {
18582 bindingStates.initAttributes();
18583 var buffers = properties.get(object);
18584 if (object.hasPositions && !buffers.position) buffers.position = _gl.createBuffer();
18585 if (object.hasNormals && !buffers.normal) buffers.normal = _gl.createBuffer();
18586 if (object.hasUvs && !buffers.uv) buffers.uv = _gl.createBuffer();
18587 if (object.hasColors && !buffers.color) buffers.color = _gl.createBuffer();
18588 var programAttributes = program.getAttributes();
18590 if (object.hasPositions) {
18591 _gl.bindBuffer(34962, buffers.position);
18593 _gl.bufferData(34962, object.positionArray, 35048);
18595 bindingStates.enableAttribute(programAttributes.position);
18597 _gl.vertexAttribPointer(programAttributes.position, 3, 5126, false, 0, 0);
18600 if (object.hasNormals) {
18601 _gl.bindBuffer(34962, buffers.normal);
18603 _gl.bufferData(34962, object.normalArray, 35048);
18605 bindingStates.enableAttribute(programAttributes.normal);
18607 _gl.vertexAttribPointer(programAttributes.normal, 3, 5126, false, 0, 0);
18610 if (object.hasUvs) {
18611 _gl.bindBuffer(34962, buffers.uv);
18613 _gl.bufferData(34962, object.uvArray, 35048);
18615 bindingStates.enableAttribute(programAttributes.uv);
18617 _gl.vertexAttribPointer(programAttributes.uv, 2, 5126, false, 0, 0);
18620 if (object.hasColors) {
18621 _gl.bindBuffer(34962, buffers.color);
18623 _gl.bufferData(34962, object.colorArray, 35048);
18625 bindingStates.enableAttribute(programAttributes.color);
18627 _gl.vertexAttribPointer(programAttributes.color, 3, 5126, false, 0, 0);
18630 bindingStates.disableUnusedAttributes();
18632 _gl.drawArrays(4, 0, object.count);
18637 this.renderBufferDirect = function (camera, scene, geometry, material, object, group) {
18638 if (scene === null) scene = _emptyScene; // renderBufferDirect second parameter used to be fog (could be null)
18640 var frontFaceCW = object.isMesh && object.matrixWorld.determinant() < 0;
18641 var program = setProgram(camera, scene, material, object);
18642 state.setMaterial(material, frontFaceCW); //
18644 var index = geometry.index;
18645 var position = geometry.attributes.position; //
18647 if (index === null) {
18648 if (position === undefined || position.count === 0) return;
18649 } else if (index.count === 0) {
18654 var rangeFactor = 1;
18656 if (material.wireframe === true) {
18657 index = geometries.getWireframeAttribute(geometry);
18661 if (material.morphTargets || material.morphNormals) {
18662 morphtargets.update(object, geometry, material, program);
18665 bindingStates.setup(object, material, program, geometry, index);
18667 var renderer = bufferRenderer;
18669 if (index !== null) {
18670 attribute = attributes.get(index);
18671 renderer = indexedBufferRenderer;
18672 renderer.setIndex(attribute);
18676 var dataCount = index !== null ? index.count : position.count;
18677 var rangeStart = geometry.drawRange.start * rangeFactor;
18678 var rangeCount = geometry.drawRange.count * rangeFactor;
18679 var groupStart = group !== null ? group.start * rangeFactor : 0;
18680 var groupCount = group !== null ? group.count * rangeFactor : Infinity;
18681 var drawStart = Math.max(rangeStart, groupStart);
18682 var drawEnd = Math.min(dataCount, rangeStart + rangeCount, groupStart + groupCount) - 1;
18683 var drawCount = Math.max(0, drawEnd - drawStart + 1);
18684 if (drawCount === 0) return; //
18686 if (object.isMesh) {
18687 if (material.wireframe === true) {
18688 state.setLineWidth(material.wireframeLinewidth * getTargetPixelRatio());
18689 renderer.setMode(1);
18691 renderer.setMode(4);
18693 } else if (object.isLine) {
18694 var lineWidth = material.linewidth;
18695 if (lineWidth === undefined) lineWidth = 1; // Not using Line*Material
18697 state.setLineWidth(lineWidth * getTargetPixelRatio());
18699 if (object.isLineSegments) {
18700 renderer.setMode(1);
18701 } else if (object.isLineLoop) {
18702 renderer.setMode(2);
18704 renderer.setMode(3);
18706 } else if (object.isPoints) {
18707 renderer.setMode(0);
18708 } else if (object.isSprite) {
18709 renderer.setMode(4);
18712 if (object.isInstancedMesh) {
18713 renderer.renderInstances(drawStart, drawCount, object.count);
18714 } else if (geometry.isInstancedBufferGeometry) {
18715 var instanceCount = Math.min(geometry.instanceCount, geometry._maxInstanceCount);
18716 renderer.renderInstances(drawStart, drawCount, instanceCount);
18718 renderer.render(drawStart, drawCount);
18723 this.compile = function (scene, camera) {
18724 currentRenderState = renderStates.get(scene);
18725 currentRenderState.init();
18726 scene.traverseVisible(function (object) {
18727 if (object.isLight && object.layers.test(camera.layers)) {
18728 currentRenderState.pushLight(object);
18730 if (object.castShadow) {
18731 currentRenderState.pushShadow(object);
18735 currentRenderState.setupLights();
18736 var compiled = new WeakMap();
18737 scene.traverse(function (object) {
18738 var material = object.material;
18741 if (Array.isArray(material)) {
18742 for (var i = 0; i < material.length; i++) {
18743 var material2 = material[i];
18745 if (compiled.has(material2) === false) {
18746 initMaterial(material2, scene, object);
18747 compiled.set(material2);
18750 } else if (compiled.has(material) === false) {
18751 initMaterial(material, scene, object);
18752 compiled.set(material);
18756 }; // Animation Loop
18759 var onAnimationFrameCallback = null;
18761 function onAnimationFrame(time) {
18762 if (xr.isPresenting) return;
18763 if (onAnimationFrameCallback) onAnimationFrameCallback(time);
18766 var animation = new WebGLAnimation();
18767 animation.setAnimationLoop(onAnimationFrame);
18768 if (typeof window !== 'undefined') animation.setContext(window);
18770 this.setAnimationLoop = function (callback) {
18771 onAnimationFrameCallback = callback;
18772 xr.setAnimationLoop(callback);
18773 callback === null ? animation.stop() : animation.start();
18777 this.render = function (scene, camera) {
18778 var renderTarget, forceClear;
18780 if (arguments[2] !== undefined) {
18781 console.warn('THREE.WebGLRenderer.render(): the renderTarget argument has been removed. Use .setRenderTarget() instead.');
18782 renderTarget = arguments[2];
18785 if (arguments[3] !== undefined) {
18786 console.warn('THREE.WebGLRenderer.render(): the forceClear argument has been removed. Use .clear() instead.');
18787 forceClear = arguments[3];
18790 if (camera !== undefined && camera.isCamera !== true) {
18791 console.error('THREE.WebGLRenderer.render: camera is not an instance of THREE.Camera.');
18795 if (_isContextLost === true) return; // reset caching for this frame
18797 bindingStates.resetDefaultState();
18798 _currentMaterialId = -1;
18799 _currentCamera = null; // update scene graph
18801 if (scene.autoUpdate === true) scene.updateMatrixWorld(); // update camera matrices and frustum
18803 if (camera.parent === null) camera.updateMatrixWorld();
18805 if (xr.enabled === true && xr.isPresenting === true) {
18806 camera = xr.getCamera(camera);
18810 if (scene.isScene === true) scene.onBeforeRender(_this, scene, camera, renderTarget || _currentRenderTarget);
18811 currentRenderState = renderStates.get(scene, renderStateStack.length);
18812 currentRenderState.init();
18813 renderStateStack.push(currentRenderState);
18815 _projScreenMatrix.multiplyMatrices(camera.projectionMatrix, camera.matrixWorldInverse);
18817 _frustum.setFromProjectionMatrix(_projScreenMatrix);
18819 _localClippingEnabled = this.localClippingEnabled;
18820 _clippingEnabled = clipping.init(this.clippingPlanes, _localClippingEnabled, camera);
18821 currentRenderList = renderLists.get(scene, camera);
18822 currentRenderList.init();
18823 projectObject(scene, camera, 0, _this.sortObjects);
18824 currentRenderList.finish();
18826 if (_this.sortObjects === true) {
18827 currentRenderList.sort(_opaqueSort, _transparentSort);
18831 if (_clippingEnabled === true) clipping.beginShadows();
18832 var shadowsArray = currentRenderState.state.shadowsArray;
18833 shadowMap.render(shadowsArray, scene, camera);
18834 currentRenderState.setupLights();
18835 currentRenderState.setupLightsView(camera);
18836 if (_clippingEnabled === true) clipping.endShadows(); //
18838 if (this.info.autoReset === true) this.info.reset();
18840 if (renderTarget !== undefined) {
18841 this.setRenderTarget(renderTarget);
18845 background.render(currentRenderList, scene, camera, forceClear); // render scene
18847 var opaqueObjects = currentRenderList.opaque;
18848 var transparentObjects = currentRenderList.transparent;
18849 if (opaqueObjects.length > 0) renderObjects(opaqueObjects, scene, camera);
18850 if (transparentObjects.length > 0) renderObjects(transparentObjects, scene, camera); //
18852 if (scene.isScene === true) scene.onAfterRender(_this, scene, camera); //
18854 if (_currentRenderTarget !== null) {
18855 // Generate mipmap if we're using any kind of mipmap filtering
18856 textures.updateRenderTargetMipmap(_currentRenderTarget); // resolve multisample renderbuffers to a single-sample texture if necessary
18858 textures.updateMultisampleRenderTarget(_currentRenderTarget);
18859 } // Ensure depth buffer writing is enabled so it can be cleared on next render
18862 state.buffers.depth.setTest(true);
18863 state.buffers.depth.setMask(true);
18864 state.buffers.color.setMask(true);
18865 state.setPolygonOffset(false); // _gl.finish();
18867 renderStateStack.pop();
18869 if (renderStateStack.length > 0) {
18870 currentRenderState = renderStateStack[renderStateStack.length - 1];
18872 currentRenderState = null;
18875 currentRenderList = null;
18878 function projectObject(object, camera, groupOrder, sortObjects) {
18879 if (object.visible === false) return;
18880 var visible = object.layers.test(camera.layers);
18883 if (object.isGroup) {
18884 groupOrder = object.renderOrder;
18885 } else if (object.isLOD) {
18886 if (object.autoUpdate === true) object.update(camera);
18887 } else if (object.isLight) {
18888 currentRenderState.pushLight(object);
18890 if (object.castShadow) {
18891 currentRenderState.pushShadow(object);
18893 } else if (object.isSprite) {
18894 if (!object.frustumCulled || _frustum.intersectsSprite(object)) {
18896 _vector3.setFromMatrixPosition(object.matrixWorld).applyMatrix4(_projScreenMatrix);
18899 var geometry = objects.update(object);
18900 var material = object.material;
18902 if (material.visible) {
18903 currentRenderList.push(object, geometry, material, groupOrder, _vector3.z, null);
18906 } else if (object.isImmediateRenderObject) {
18908 _vector3.setFromMatrixPosition(object.matrixWorld).applyMatrix4(_projScreenMatrix);
18911 currentRenderList.push(object, null, object.material, groupOrder, _vector3.z, null);
18912 } else if (object.isMesh || object.isLine || object.isPoints) {
18913 if (object.isSkinnedMesh) {
18914 // update skeleton only once in a frame
18915 if (object.skeleton.frame !== info.render.frame) {
18916 object.skeleton.update();
18917 object.skeleton.frame = info.render.frame;
18921 if (!object.frustumCulled || _frustum.intersectsObject(object)) {
18923 _vector3.setFromMatrixPosition(object.matrixWorld).applyMatrix4(_projScreenMatrix);
18926 var _geometry = objects.update(object);
18928 var _material = object.material;
18930 if (Array.isArray(_material)) {
18931 var groups = _geometry.groups;
18933 for (var i = 0, l = groups.length; i < l; i++) {
18934 var group = groups[i];
18935 var groupMaterial = _material[group.materialIndex];
18937 if (groupMaterial && groupMaterial.visible) {
18938 currentRenderList.push(object, _geometry, groupMaterial, groupOrder, _vector3.z, group);
18941 } else if (_material.visible) {
18942 currentRenderList.push(object, _geometry, _material, groupOrder, _vector3.z, null);
18948 var children = object.children;
18950 for (var _i = 0, _l = children.length; _i < _l; _i++) {
18951 projectObject(children[_i], camera, groupOrder, sortObjects);
18955 function renderObjects(renderList, scene, camera) {
18956 var overrideMaterial = scene.isScene === true ? scene.overrideMaterial : null;
18958 for (var i = 0, l = renderList.length; i < l; i++) {
18959 var renderItem = renderList[i];
18960 var object = renderItem.object;
18961 var geometry = renderItem.geometry;
18962 var material = overrideMaterial === null ? renderItem.material : overrideMaterial;
18963 var group = renderItem.group;
18965 if (camera.isArrayCamera) {
18966 var cameras = camera.cameras;
18968 for (var j = 0, jl = cameras.length; j < jl; j++) {
18969 var camera2 = cameras[j];
18971 if (object.layers.test(camera2.layers)) {
18972 state.viewport(_currentViewport.copy(camera2.viewport));
18973 currentRenderState.setupLightsView(camera2);
18974 renderObject(object, scene, camera2, geometry, material, group);
18978 renderObject(object, scene, camera, geometry, material, group);
18983 function renderObject(object, scene, camera, geometry, material, group) {
18984 object.onBeforeRender(_this, scene, camera, geometry, material, group);
18985 object.modelViewMatrix.multiplyMatrices(camera.matrixWorldInverse, object.matrixWorld);
18986 object.normalMatrix.getNormalMatrix(object.modelViewMatrix);
18988 if (object.isImmediateRenderObject) {
18989 var program = setProgram(camera, scene, material, object);
18990 state.setMaterial(material);
18991 bindingStates.reset();
18992 renderObjectImmediate(object, program);
18994 _this.renderBufferDirect(camera, scene, geometry, material, object, group);
18997 object.onAfterRender(_this, scene, camera, geometry, material, group);
19000 function initMaterial(material, scene, object) {
19001 if (scene.isScene !== true) scene = _emptyScene; // scene could be a Mesh, Line, Points, ...
19003 var materialProperties = properties.get(material);
19004 var lights = currentRenderState.state.lights;
19005 var shadowsArray = currentRenderState.state.shadowsArray;
19006 var lightsStateVersion = lights.state.version;
19007 var parameters = programCache.getParameters(material, lights.state, shadowsArray, scene, object);
19008 var programCacheKey = programCache.getProgramCacheKey(parameters);
19009 var program = materialProperties.program;
19010 var programChange = true; // always update environment and fog - changing these trigger an initMaterial call, but it's possible that the program doesn't change
19012 materialProperties.environment = material.isMeshStandardMaterial ? scene.environment : null;
19013 materialProperties.fog = scene.fog;
19014 materialProperties.envMap = cubemaps.get(material.envMap || materialProperties.environment);
19016 if (program === undefined) {
19018 material.addEventListener('dispose', onMaterialDispose);
19019 } else if (program.cacheKey !== programCacheKey) {
19020 // changed glsl or parameters
19021 releaseMaterialProgramReference(material);
19022 } else if (materialProperties.lightsStateVersion !== lightsStateVersion) {
19023 programChange = false;
19024 } else if (parameters.shaderID !== undefined) {
19025 // same glsl and uniform list
19028 // only rebuild uniform list
19029 programChange = false;
19032 if (programChange) {
19033 parameters.uniforms = programCache.getUniforms(material);
19034 material.onBeforeCompile(parameters, _this);
19035 program = programCache.acquireProgram(parameters, programCacheKey);
19036 materialProperties.program = program;
19037 materialProperties.uniforms = parameters.uniforms;
19038 materialProperties.outputEncoding = parameters.outputEncoding;
19041 var uniforms = materialProperties.uniforms;
19043 if (!material.isShaderMaterial && !material.isRawShaderMaterial || material.clipping === true) {
19044 materialProperties.numClippingPlanes = clipping.numPlanes;
19045 materialProperties.numIntersection = clipping.numIntersection;
19046 uniforms.clippingPlanes = clipping.uniform;
19047 } // store the light setup it was created for
19050 materialProperties.needsLights = materialNeedsLights(material);
19051 materialProperties.lightsStateVersion = lightsStateVersion;
19053 if (materialProperties.needsLights) {
19054 // wire up the material to this renderer's lighting state
19055 uniforms.ambientLightColor.value = lights.state.ambient;
19056 uniforms.lightProbe.value = lights.state.probe;
19057 uniforms.directionalLights.value = lights.state.directional;
19058 uniforms.directionalLightShadows.value = lights.state.directionalShadow;
19059 uniforms.spotLights.value = lights.state.spot;
19060 uniforms.spotLightShadows.value = lights.state.spotShadow;
19061 uniforms.rectAreaLights.value = lights.state.rectArea;
19062 uniforms.ltc_1.value = lights.state.rectAreaLTC1;
19063 uniforms.ltc_2.value = lights.state.rectAreaLTC2;
19064 uniforms.pointLights.value = lights.state.point;
19065 uniforms.pointLightShadows.value = lights.state.pointShadow;
19066 uniforms.hemisphereLights.value = lights.state.hemi;
19067 uniforms.directionalShadowMap.value = lights.state.directionalShadowMap;
19068 uniforms.directionalShadowMatrix.value = lights.state.directionalShadowMatrix;
19069 uniforms.spotShadowMap.value = lights.state.spotShadowMap;
19070 uniforms.spotShadowMatrix.value = lights.state.spotShadowMatrix;
19071 uniforms.pointShadowMap.value = lights.state.pointShadowMap;
19072 uniforms.pointShadowMatrix.value = lights.state.pointShadowMatrix; // TODO (abelnation): add area lights shadow info to uniforms
19075 var progUniforms = materialProperties.program.getUniforms();
19076 var uniformsList = WebGLUniforms.seqWithValue(progUniforms.seq, uniforms);
19077 materialProperties.uniformsList = uniformsList;
19080 function setProgram(camera, scene, material, object) {
19081 if (scene.isScene !== true) scene = _emptyScene; // scene could be a Mesh, Line, Points, ...
19083 textures.resetTextureUnits();
19084 var fog = scene.fog;
19085 var environment = material.isMeshStandardMaterial ? scene.environment : null;
19086 var encoding = _currentRenderTarget === null ? _this.outputEncoding : _currentRenderTarget.texture.encoding;
19087 var envMap = cubemaps.get(material.envMap || environment);
19088 var materialProperties = properties.get(material);
19089 var lights = currentRenderState.state.lights;
19091 if (_clippingEnabled === true) {
19092 if (_localClippingEnabled === true || camera !== _currentCamera) {
19093 var useCache = camera === _currentCamera && material.id === _currentMaterialId; // we might want to call this function with some ClippingGroup
19094 // object instead of the material, once it becomes feasible
19097 clipping.setState(material, camera, useCache);
19101 if (material.version === materialProperties.__version) {
19102 if (material.fog && materialProperties.fog !== fog) {
19103 initMaterial(material, scene, object);
19104 } else if (materialProperties.environment !== environment) {
19105 initMaterial(material, scene, object);
19106 } else if (materialProperties.needsLights && materialProperties.lightsStateVersion !== lights.state.version) {
19107 initMaterial(material, scene, object);
19108 } else if (materialProperties.numClippingPlanes !== undefined && (materialProperties.numClippingPlanes !== clipping.numPlanes || materialProperties.numIntersection !== clipping.numIntersection)) {
19109 initMaterial(material, scene, object);
19110 } else if (materialProperties.outputEncoding !== encoding) {
19111 initMaterial(material, scene, object);
19112 } else if (materialProperties.envMap !== envMap) {
19113 initMaterial(material, scene, object);
19116 initMaterial(material, scene, object);
19117 materialProperties.__version = material.version;
19120 var refreshProgram = false;
19121 var refreshMaterial = false;
19122 var refreshLights = false;
19123 var program = materialProperties.program,
19124 p_uniforms = program.getUniforms(),
19125 m_uniforms = materialProperties.uniforms;
19127 if (state.useProgram(program.program)) {
19128 refreshProgram = true;
19129 refreshMaterial = true;
19130 refreshLights = true;
19133 if (material.id !== _currentMaterialId) {
19134 _currentMaterialId = material.id;
19135 refreshMaterial = true;
19138 if (refreshProgram || _currentCamera !== camera) {
19139 p_uniforms.setValue(_gl, 'projectionMatrix', camera.projectionMatrix);
19141 if (capabilities.logarithmicDepthBuffer) {
19142 p_uniforms.setValue(_gl, 'logDepthBufFC', 2.0 / (Math.log(camera.far + 1.0) / Math.LN2));
19145 if (_currentCamera !== camera) {
19146 _currentCamera = camera; // lighting uniforms depend on the camera so enforce an update
19147 // now, in case this material supports lights - or later, when
19148 // the next material that does gets activated:
19150 refreshMaterial = true; // set to true on material change
19152 refreshLights = true; // remains set until update done
19153 } // load material specific uniforms
19154 // (shader material also gets them for the sake of genericity)
19157 if (material.isShaderMaterial || material.isMeshPhongMaterial || material.isMeshToonMaterial || material.isMeshStandardMaterial || material.envMap) {
19158 var uCamPos = p_uniforms.map.cameraPosition;
19160 if (uCamPos !== undefined) {
19161 uCamPos.setValue(_gl, _vector3.setFromMatrixPosition(camera.matrixWorld));
19165 if (material.isMeshPhongMaterial || material.isMeshToonMaterial || material.isMeshLambertMaterial || material.isMeshBasicMaterial || material.isMeshStandardMaterial || material.isShaderMaterial) {
19166 p_uniforms.setValue(_gl, 'isOrthographic', camera.isOrthographicCamera === true);
19169 if (material.isMeshPhongMaterial || material.isMeshToonMaterial || material.isMeshLambertMaterial || material.isMeshBasicMaterial || material.isMeshStandardMaterial || material.isShaderMaterial || material.isShadowMaterial || material.skinning) {
19170 p_uniforms.setValue(_gl, 'viewMatrix', camera.matrixWorldInverse);
19172 } // skinning uniforms must be set even if material didn't change
19173 // auto-setting of texture unit for bone texture must go before other textures
19174 // otherwise textures used for skinning can take over texture units reserved for other material textures
19177 if (material.skinning) {
19178 p_uniforms.setOptional(_gl, object, 'bindMatrix');
19179 p_uniforms.setOptional(_gl, object, 'bindMatrixInverse');
19180 var skeleton = object.skeleton;
19183 var bones = skeleton.bones;
19185 if (capabilities.floatVertexTextures) {
19186 if (skeleton.boneTexture === null) {
19187 // layout (1 matrix = 4 pixels)
19188 // RGBA RGBA RGBA RGBA (=> column1, column2, column3, column4)
19189 // with 8x8 pixel texture max 16 bones * 4 pixels = (8 * 8)
19190 // 16x16 pixel texture max 64 bones * 4 pixels = (16 * 16)
19191 // 32x32 pixel texture max 256 bones * 4 pixels = (32 * 32)
19192 // 64x64 pixel texture max 1024 bones * 4 pixels = (64 * 64)
19193 var size = Math.sqrt(bones.length * 4); // 4 pixels needed for 1 matrix
19195 size = MathUtils.ceilPowerOfTwo(size);
19196 size = Math.max(size, 4);
19197 var boneMatrices = new Float32Array(size * size * 4); // 4 floats per RGBA pixel
19199 boneMatrices.set(skeleton.boneMatrices); // copy current values
19201 var boneTexture = new DataTexture(boneMatrices, size, size, RGBAFormat, FloatType);
19202 skeleton.boneMatrices = boneMatrices;
19203 skeleton.boneTexture = boneTexture;
19204 skeleton.boneTextureSize = size;
19207 p_uniforms.setValue(_gl, 'boneTexture', skeleton.boneTexture, textures);
19208 p_uniforms.setValue(_gl, 'boneTextureSize', skeleton.boneTextureSize);
19210 p_uniforms.setOptional(_gl, skeleton, 'boneMatrices');
19215 if (refreshMaterial || materialProperties.receiveShadow !== object.receiveShadow) {
19216 materialProperties.receiveShadow = object.receiveShadow;
19217 p_uniforms.setValue(_gl, 'receiveShadow', object.receiveShadow);
19220 if (refreshMaterial) {
19221 p_uniforms.setValue(_gl, 'toneMappingExposure', _this.toneMappingExposure);
19223 if (materialProperties.needsLights) {
19224 // the current material requires lighting info
19225 // note: all lighting uniforms are always set correctly
19226 // they simply reference the renderer's state for their
19229 // use the current material's .needsUpdate flags to set
19230 // the GL state when required
19231 markUniformsLightsNeedsUpdate(m_uniforms, refreshLights);
19232 } // refresh uniforms common to several materials
19235 if (fog && material.fog) {
19236 materials.refreshFogUniforms(m_uniforms, fog);
19239 materials.refreshMaterialUniforms(m_uniforms, material, _pixelRatio, _height);
19240 WebGLUniforms.upload(_gl, materialProperties.uniformsList, m_uniforms, textures);
19243 if (material.isShaderMaterial && material.uniformsNeedUpdate === true) {
19244 WebGLUniforms.upload(_gl, materialProperties.uniformsList, m_uniforms, textures);
19245 material.uniformsNeedUpdate = false;
19248 if (material.isSpriteMaterial) {
19249 p_uniforms.setValue(_gl, 'center', object.center);
19250 } // common matrices
19253 p_uniforms.setValue(_gl, 'modelViewMatrix', object.modelViewMatrix);
19254 p_uniforms.setValue(_gl, 'normalMatrix', object.normalMatrix);
19255 p_uniforms.setValue(_gl, 'modelMatrix', object.matrixWorld);
19257 } // If uniforms are marked as clean, they don't need to be loaded to the GPU.
19260 function markUniformsLightsNeedsUpdate(uniforms, value) {
19261 uniforms.ambientLightColor.needsUpdate = value;
19262 uniforms.lightProbe.needsUpdate = value;
19263 uniforms.directionalLights.needsUpdate = value;
19264 uniforms.directionalLightShadows.needsUpdate = value;
19265 uniforms.pointLights.needsUpdate = value;
19266 uniforms.pointLightShadows.needsUpdate = value;
19267 uniforms.spotLights.needsUpdate = value;
19268 uniforms.spotLightShadows.needsUpdate = value;
19269 uniforms.rectAreaLights.needsUpdate = value;
19270 uniforms.hemisphereLights.needsUpdate = value;
19273 function materialNeedsLights(material) {
19274 return material.isMeshLambertMaterial || material.isMeshToonMaterial || material.isMeshPhongMaterial || material.isMeshStandardMaterial || material.isShadowMaterial || material.isShaderMaterial && material.lights === true;
19278 this.setFramebuffer = function (value) {
19279 if (_framebuffer !== value && _currentRenderTarget === null) _gl.bindFramebuffer(36160, value);
19280 _framebuffer = value;
19283 this.getActiveCubeFace = function () {
19284 return _currentActiveCubeFace;
19287 this.getActiveMipmapLevel = function () {
19288 return _currentActiveMipmapLevel;
19291 this.getRenderList = function () {
19292 return currentRenderList;
19295 this.setRenderList = function (renderList) {
19296 currentRenderList = renderList;
19299 this.getRenderTarget = function () {
19300 return _currentRenderTarget;
19303 this.setRenderTarget = function (renderTarget, activeCubeFace, activeMipmapLevel) {
19304 if (activeCubeFace === void 0) {
19305 activeCubeFace = 0;
19308 if (activeMipmapLevel === void 0) {
19309 activeMipmapLevel = 0;
19312 _currentRenderTarget = renderTarget;
19313 _currentActiveCubeFace = activeCubeFace;
19314 _currentActiveMipmapLevel = activeMipmapLevel;
19316 if (renderTarget && properties.get(renderTarget).__webglFramebuffer === undefined) {
19317 textures.setupRenderTarget(renderTarget);
19320 var framebuffer = _framebuffer;
19321 var isCube = false;
19323 if (renderTarget) {
19324 var __webglFramebuffer = properties.get(renderTarget).__webglFramebuffer;
19326 if (renderTarget.isWebGLCubeRenderTarget) {
19327 framebuffer = __webglFramebuffer[activeCubeFace];
19329 } else if (renderTarget.isWebGLMultisampleRenderTarget) {
19330 framebuffer = properties.get(renderTarget).__webglMultisampledFramebuffer;
19332 framebuffer = __webglFramebuffer;
19335 _currentViewport.copy(renderTarget.viewport);
19337 _currentScissor.copy(renderTarget.scissor);
19339 _currentScissorTest = renderTarget.scissorTest;
19341 _currentViewport.copy(_viewport).multiplyScalar(_pixelRatio).floor();
19343 _currentScissor.copy(_scissor).multiplyScalar(_pixelRatio).floor();
19345 _currentScissorTest = _scissorTest;
19348 if (_currentFramebuffer !== framebuffer) {
19349 _gl.bindFramebuffer(36160, framebuffer);
19351 _currentFramebuffer = framebuffer;
19354 state.viewport(_currentViewport);
19355 state.scissor(_currentScissor);
19356 state.setScissorTest(_currentScissorTest);
19359 var textureProperties = properties.get(renderTarget.texture);
19361 _gl.framebufferTexture2D(36160, 36064, 34069 + activeCubeFace, textureProperties.__webglTexture, activeMipmapLevel);
19365 this.readRenderTargetPixels = function (renderTarget, x, y, width, height, buffer, activeCubeFaceIndex) {
19366 if (!(renderTarget && renderTarget.isWebGLRenderTarget)) {
19367 console.error('THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget.');
19371 var framebuffer = properties.get(renderTarget).__webglFramebuffer;
19373 if (renderTarget.isWebGLCubeRenderTarget && activeCubeFaceIndex !== undefined) {
19374 framebuffer = framebuffer[activeCubeFaceIndex];
19378 var restore = false;
19380 if (framebuffer !== _currentFramebuffer) {
19381 _gl.bindFramebuffer(36160, framebuffer);
19387 var texture = renderTarget.texture;
19388 var textureFormat = texture.format;
19389 var textureType = texture.type;
19391 if (textureFormat !== RGBAFormat && utils.convert(textureFormat) !== _gl.getParameter(35739)) {
19392 console.error('THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in RGBA or implementation defined format.');
19396 var halfFloatSupportedByExt = textureType === HalfFloatType && (extensions.has('EXT_color_buffer_half_float') || capabilities.isWebGL2 && extensions.has('EXT_color_buffer_float'));
19398 if (textureType !== UnsignedByteType && utils.convert(textureType) !== _gl.getParameter(35738) && // IE11, Edge and Chrome Mac < 52 (#9513)
19399 !(textureType === FloatType && (capabilities.isWebGL2 || extensions.has('OES_texture_float') || extensions.has('WEBGL_color_buffer_float'))) && // Chrome Mac >= 52 and Firefox
19400 !halfFloatSupportedByExt) {
19401 console.error('THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in UnsignedByteType or implementation defined type.');
19405 if (_gl.checkFramebufferStatus(36160) === 36053) {
19406 // the following if statement ensures valid read requests (no out-of-bounds pixels, see #8604)
19407 if (x >= 0 && x <= renderTarget.width - width && y >= 0 && y <= renderTarget.height - height) {
19408 _gl.readPixels(x, y, width, height, utils.convert(textureFormat), utils.convert(textureType), buffer);
19411 console.error('THREE.WebGLRenderer.readRenderTargetPixels: readPixels from renderTarget failed. Framebuffer not complete.');
19415 _gl.bindFramebuffer(36160, _currentFramebuffer);
19421 this.copyFramebufferToTexture = function (position, texture, level) {
19422 if (level === void 0) {
19426 var levelScale = Math.pow(2, -level);
19427 var width = Math.floor(texture.image.width * levelScale);
19428 var height = Math.floor(texture.image.height * levelScale);
19429 var glFormat = utils.convert(texture.format);
19430 textures.setTexture2D(texture, 0);
19432 _gl.copyTexImage2D(3553, level, glFormat, position.x, position.y, width, height, 0);
19434 state.unbindTexture();
19437 this.copyTextureToTexture = function (position, srcTexture, dstTexture, level) {
19438 if (level === void 0) {
19442 var width = srcTexture.image.width;
19443 var height = srcTexture.image.height;
19444 var glFormat = utils.convert(dstTexture.format);
19445 var glType = utils.convert(dstTexture.type);
19446 textures.setTexture2D(dstTexture, 0); // As another texture upload may have changed pixelStorei
19447 // parameters, make sure they are correct for the dstTexture
19449 _gl.pixelStorei(37440, dstTexture.flipY);
19451 _gl.pixelStorei(37441, dstTexture.premultiplyAlpha);
19453 _gl.pixelStorei(3317, dstTexture.unpackAlignment);
19455 if (srcTexture.isDataTexture) {
19456 _gl.texSubImage2D(3553, level, position.x, position.y, width, height, glFormat, glType, srcTexture.image.data);
19458 if (srcTexture.isCompressedTexture) {
19459 _gl.compressedTexSubImage2D(3553, level, position.x, position.y, srcTexture.mipmaps[0].width, srcTexture.mipmaps[0].height, glFormat, srcTexture.mipmaps[0].data);
19461 _gl.texSubImage2D(3553, level, position.x, position.y, glFormat, glType, srcTexture.image);
19463 } // Generate mipmaps only when copying level 0
19466 if (level === 0 && dstTexture.generateMipmaps) _gl.generateMipmap(3553);
19467 state.unbindTexture();
19470 this.initTexture = function (texture) {
19471 textures.setTexture2D(texture, 0);
19472 state.unbindTexture();
19475 this.resetState = function () {
19477 bindingStates.reset();
19480 if (typeof __THREE_DEVTOOLS__ !== 'undefined') {
19481 __THREE_DEVTOOLS__.dispatchEvent(new CustomEvent('observe', {
19483 })); // eslint-disable-line no-undef
19488 function WebGL1Renderer(parameters) {
19489 WebGLRenderer.call(this, parameters);
19492 WebGL1Renderer.prototype = Object.assign(Object.create(WebGLRenderer.prototype), {
19493 constructor: WebGL1Renderer,
19494 isWebGL1Renderer: true
19497 var FogExp2 = /*#__PURE__*/function () {
19498 function FogExp2(color, density) {
19499 Object.defineProperty(this, 'isFogExp2', {
19503 this.color = new Color(color);
19504 this.density = density !== undefined ? density : 0.00025;
19507 var _proto = FogExp2.prototype;
19509 _proto.clone = function clone() {
19510 return new FogExp2(this.color, this.density);
19513 _proto.toJSON = function toJSON()
19518 color: this.color.getHex(),
19519 density: this.density
19526 var Fog = /*#__PURE__*/function () {
19527 function Fog(color, near, far) {
19528 Object.defineProperty(this, 'isFog', {
19532 this.color = new Color(color);
19533 this.near = near !== undefined ? near : 1;
19534 this.far = far !== undefined ? far : 1000;
19537 var _proto = Fog.prototype;
19539 _proto.clone = function clone() {
19540 return new Fog(this.color, this.near, this.far);
19543 _proto.toJSON = function toJSON()
19548 color: this.color.getHex(),
19557 var Scene = /*#__PURE__*/function (_Object3D) {
19558 _inheritsLoose(Scene, _Object3D);
19563 _this = _Object3D.call(this) || this;
19564 Object.defineProperty(_assertThisInitialized(_this), 'isScene', {
19567 _this.type = 'Scene';
19568 _this.background = null;
19569 _this.environment = null;
19571 _this.overrideMaterial = null;
19572 _this.autoUpdate = true; // checked by the renderer
19574 if (typeof __THREE_DEVTOOLS__ !== 'undefined') {
19575 __THREE_DEVTOOLS__.dispatchEvent(new CustomEvent('observe', {
19576 detail: _assertThisInitialized(_this)
19577 })); // eslint-disable-line no-undef
19584 var _proto = Scene.prototype;
19586 _proto.copy = function copy(source, recursive) {
19587 _Object3D.prototype.copy.call(this, source, recursive);
19589 if (source.background !== null) this.background = source.background.clone();
19590 if (source.environment !== null) this.environment = source.environment.clone();
19591 if (source.fog !== null) this.fog = source.fog.clone();
19592 if (source.overrideMaterial !== null) this.overrideMaterial = source.overrideMaterial.clone();
19593 this.autoUpdate = source.autoUpdate;
19594 this.matrixAutoUpdate = source.matrixAutoUpdate;
19598 _proto.toJSON = function toJSON(meta) {
19599 var data = _Object3D.prototype.toJSON.call(this, meta);
19601 if (this.background !== null) data.object.background = this.background.toJSON(meta);
19602 if (this.environment !== null) data.object.environment = this.environment.toJSON(meta);
19603 if (this.fog !== null) data.object.fog = this.fog.toJSON();
19610 function InterleavedBuffer(array, stride) {
19611 this.array = array;
19612 this.stride = stride;
19613 this.count = array !== undefined ? array.length / stride : 0;
19614 this.usage = StaticDrawUsage;
19615 this.updateRange = {
19620 this.uuid = MathUtils.generateUUID();
19623 Object.defineProperty(InterleavedBuffer.prototype, 'needsUpdate', {
19624 set: function set(value) {
19625 if (value === true) this.version++;
19628 Object.assign(InterleavedBuffer.prototype, {
19629 isInterleavedBuffer: true,
19630 onUploadCallback: function onUploadCallback() {},
19631 setUsage: function setUsage(value) {
19632 this.usage = value;
19635 copy: function copy(source) {
19636 this.array = new source.array.constructor(source.array);
19637 this.count = source.count;
19638 this.stride = source.stride;
19639 this.usage = source.usage;
19642 copyAt: function copyAt(index1, attribute, index2) {
19643 index1 *= this.stride;
19644 index2 *= attribute.stride;
19646 for (var i = 0, l = this.stride; i < l; i++) {
19647 this.array[index1 + i] = attribute.array[index2 + i];
19652 set: function set(value, offset) {
19653 if (offset === void 0) {
19657 this.array.set(value, offset);
19660 clone: function clone(data) {
19661 if (data.arrayBuffers === undefined) {
19662 data.arrayBuffers = {};
19665 if (this.array.buffer._uuid === undefined) {
19666 this.array.buffer._uuid = MathUtils.generateUUID();
19669 if (data.arrayBuffers[this.array.buffer._uuid] === undefined) {
19670 data.arrayBuffers[this.array.buffer._uuid] = this.array.slice(0).buffer;
19673 var array = new this.array.constructor(data.arrayBuffers[this.array.buffer._uuid]);
19674 var ib = new InterleavedBuffer(array, this.stride);
19675 ib.setUsage(this.usage);
19678 onUpload: function onUpload(callback) {
19679 this.onUploadCallback = callback;
19682 toJSON: function toJSON(data) {
19683 if (data.arrayBuffers === undefined) {
19684 data.arrayBuffers = {};
19685 } // generate UUID for array buffer if necessary
19688 if (this.array.buffer._uuid === undefined) {
19689 this.array.buffer._uuid = MathUtils.generateUUID();
19692 if (data.arrayBuffers[this.array.buffer._uuid] === undefined) {
19693 data.arrayBuffers[this.array.buffer._uuid] = Array.prototype.slice.call(new Uint32Array(this.array.buffer));
19699 buffer: this.array.buffer._uuid,
19700 type: this.array.constructor.name,
19701 stride: this.stride
19706 var _vector$6 = new Vector3();
19708 function InterleavedBufferAttribute(interleavedBuffer, itemSize, offset, normalized) {
19710 this.data = interleavedBuffer;
19711 this.itemSize = itemSize;
19712 this.offset = offset;
19713 this.normalized = normalized === true;
19716 Object.defineProperties(InterleavedBufferAttribute.prototype, {
19718 get: function get() {
19719 return this.data.count;
19723 get: function get() {
19724 return this.data.array;
19728 set: function set(value) {
19729 this.data.needsUpdate = value;
19733 Object.assign(InterleavedBufferAttribute.prototype, {
19734 isInterleavedBufferAttribute: true,
19735 applyMatrix4: function applyMatrix4(m) {
19736 for (var i = 0, l = this.data.count; i < l; i++) {
19737 _vector$6.x = this.getX(i);
19738 _vector$6.y = this.getY(i);
19739 _vector$6.z = this.getZ(i);
19741 _vector$6.applyMatrix4(m);
19743 this.setXYZ(i, _vector$6.x, _vector$6.y, _vector$6.z);
19748 setX: function setX(index, x) {
19749 this.data.array[index * this.data.stride + this.offset] = x;
19752 setY: function setY(index, y) {
19753 this.data.array[index * this.data.stride + this.offset + 1] = y;
19756 setZ: function setZ(index, z) {
19757 this.data.array[index * this.data.stride + this.offset + 2] = z;
19760 setW: function setW(index, w) {
19761 this.data.array[index * this.data.stride + this.offset + 3] = w;
19764 getX: function getX(index) {
19765 return this.data.array[index * this.data.stride + this.offset];
19767 getY: function getY(index) {
19768 return this.data.array[index * this.data.stride + this.offset + 1];
19770 getZ: function getZ(index) {
19771 return this.data.array[index * this.data.stride + this.offset + 2];
19773 getW: function getW(index) {
19774 return this.data.array[index * this.data.stride + this.offset + 3];
19776 setXY: function setXY(index, x, y) {
19777 index = index * this.data.stride + this.offset;
19778 this.data.array[index + 0] = x;
19779 this.data.array[index + 1] = y;
19782 setXYZ: function setXYZ(index, x, y, z) {
19783 index = index * this.data.stride + this.offset;
19784 this.data.array[index + 0] = x;
19785 this.data.array[index + 1] = y;
19786 this.data.array[index + 2] = z;
19789 setXYZW: function setXYZW(index, x, y, z, w) {
19790 index = index * this.data.stride + this.offset;
19791 this.data.array[index + 0] = x;
19792 this.data.array[index + 1] = y;
19793 this.data.array[index + 2] = z;
19794 this.data.array[index + 3] = w;
19797 clone: function clone(data) {
19798 if (data === undefined) {
19799 console.log('THREE.InterleavedBufferAttribute.clone(): Cloning an interlaved buffer attribute will deinterleave buffer data.');
19802 for (var i = 0; i < this.count; i++) {
19803 var index = i * this.data.stride + this.offset;
19805 for (var j = 0; j < this.itemSize; j++) {
19806 array.push(this.data.array[index + j]);
19810 return new BufferAttribute(new this.array.constructor(array), this.itemSize, this.normalized);
19812 if (data.interleavedBuffers === undefined) {
19813 data.interleavedBuffers = {};
19816 if (data.interleavedBuffers[this.data.uuid] === undefined) {
19817 data.interleavedBuffers[this.data.uuid] = this.data.clone(data);
19820 return new InterleavedBufferAttribute(data.interleavedBuffers[this.data.uuid], this.itemSize, this.offset, this.normalized);
19823 toJSON: function toJSON(data) {
19824 if (data === undefined) {
19825 console.log('THREE.InterleavedBufferAttribute.toJSON(): Serializing an interlaved buffer attribute will deinterleave buffer data.');
19828 for (var i = 0; i < this.count; i++) {
19829 var index = i * this.data.stride + this.offset;
19831 for (var j = 0; j < this.itemSize; j++) {
19832 array.push(this.data.array[index + j]);
19834 } // deinterleave data and save it as an ordinary buffer attribute for now
19838 itemSize: this.itemSize,
19839 type: this.array.constructor.name,
19841 normalized: this.normalized
19844 // save as true interlaved attribtue
19845 if (data.interleavedBuffers === undefined) {
19846 data.interleavedBuffers = {};
19849 if (data.interleavedBuffers[this.data.uuid] === undefined) {
19850 data.interleavedBuffers[this.data.uuid] = this.data.toJSON(data);
19854 isInterleavedBufferAttribute: true,
19855 itemSize: this.itemSize,
19856 data: this.data.uuid,
19857 offset: this.offset,
19858 normalized: this.normalized
19867 * map: new THREE.Texture( <Image> ),
19868 * alphaMap: new THREE.Texture( <Image> ),
19869 * rotation: <float>,
19870 * sizeAttenuation: <bool>
19874 function SpriteMaterial(parameters) {
19875 Material.call(this);
19876 this.type = 'SpriteMaterial';
19877 this.color = new Color(0xffffff);
19879 this.alphaMap = null;
19881 this.sizeAttenuation = true;
19882 this.transparent = true;
19883 this.setValues(parameters);
19886 SpriteMaterial.prototype = Object.create(Material.prototype);
19887 SpriteMaterial.prototype.constructor = SpriteMaterial;
19888 SpriteMaterial.prototype.isSpriteMaterial = true;
19890 SpriteMaterial.prototype.copy = function (source) {
19891 Material.prototype.copy.call(this, source);
19892 this.color.copy(source.color);
19893 this.map = source.map;
19894 this.alphaMap = source.alphaMap;
19895 this.rotation = source.rotation;
19896 this.sizeAttenuation = source.sizeAttenuation;
19902 var _intersectPoint = new Vector3();
19904 var _worldScale = new Vector3();
19906 var _mvPosition = new Vector3();
19908 var _alignedPosition = new Vector2();
19910 var _rotatedPosition = new Vector2();
19912 var _viewWorldMatrix = new Matrix4();
19914 var _vA$1 = new Vector3();
19916 var _vB$1 = new Vector3();
19918 var _vC$1 = new Vector3();
19920 var _uvA$1 = new Vector2();
19922 var _uvB$1 = new Vector2();
19924 var _uvC$1 = new Vector2();
19926 function Sprite(material) {
19927 Object3D.call(this);
19928 this.type = 'Sprite';
19930 if (_geometry === undefined) {
19931 _geometry = new BufferGeometry();
19932 var float32Array = new Float32Array([-0.5, -0.5, 0, 0, 0, 0.5, -0.5, 0, 1, 0, 0.5, 0.5, 0, 1, 1, -0.5, 0.5, 0, 0, 1]);
19933 var interleavedBuffer = new InterleavedBuffer(float32Array, 5);
19935 _geometry.setIndex([0, 1, 2, 0, 2, 3]);
19937 _geometry.setAttribute('position', new InterleavedBufferAttribute(interleavedBuffer, 3, 0, false));
19939 _geometry.setAttribute('uv', new InterleavedBufferAttribute(interleavedBuffer, 2, 3, false));
19942 this.geometry = _geometry;
19943 this.material = material !== undefined ? material : new SpriteMaterial();
19944 this.center = new Vector2(0.5, 0.5);
19947 Sprite.prototype = Object.assign(Object.create(Object3D.prototype), {
19948 constructor: Sprite,
19950 raycast: function raycast(raycaster, intersects) {
19951 if (raycaster.camera === null) {
19952 console.error('THREE.Sprite: "Raycaster.camera" needs to be set in order to raycast against sprites.');
19955 _worldScale.setFromMatrixScale(this.matrixWorld);
19957 _viewWorldMatrix.copy(raycaster.camera.matrixWorld);
19959 this.modelViewMatrix.multiplyMatrices(raycaster.camera.matrixWorldInverse, this.matrixWorld);
19961 _mvPosition.setFromMatrixPosition(this.modelViewMatrix);
19963 if (raycaster.camera.isPerspectiveCamera && this.material.sizeAttenuation === false) {
19964 _worldScale.multiplyScalar(-_mvPosition.z);
19967 var rotation = this.material.rotation;
19970 if (rotation !== 0) {
19971 cos = Math.cos(rotation);
19972 sin = Math.sin(rotation);
19975 var center = this.center;
19976 transformVertex(_vA$1.set(-0.5, -0.5, 0), _mvPosition, center, _worldScale, sin, cos);
19977 transformVertex(_vB$1.set(0.5, -0.5, 0), _mvPosition, center, _worldScale, sin, cos);
19978 transformVertex(_vC$1.set(0.5, 0.5, 0), _mvPosition, center, _worldScale, sin, cos);
19984 _uvC$1.set(1, 1); // check first triangle
19987 var intersect = raycaster.ray.intersectTriangle(_vA$1, _vB$1, _vC$1, false, _intersectPoint);
19989 if (intersect === null) {
19990 // check second triangle
19991 transformVertex(_vB$1.set(-0.5, 0.5, 0), _mvPosition, center, _worldScale, sin, cos);
19995 intersect = raycaster.ray.intersectTriangle(_vA$1, _vC$1, _vB$1, false, _intersectPoint);
19997 if (intersect === null) {
20002 var distance = raycaster.ray.origin.distanceTo(_intersectPoint);
20003 if (distance < raycaster.near || distance > raycaster.far) return;
20005 distance: distance,
20006 point: _intersectPoint.clone(),
20007 uv: Triangle.getUV(_intersectPoint, _vA$1, _vB$1, _vC$1, _uvA$1, _uvB$1, _uvC$1, new Vector2()),
20012 copy: function copy(source) {
20013 Object3D.prototype.copy.call(this, source);
20014 if (source.center !== undefined) this.center.copy(source.center);
20015 this.material = source.material;
20020 function transformVertex(vertexPosition, mvPosition, center, scale, sin, cos) {
20021 // compute position in camera space
20022 _alignedPosition.subVectors(vertexPosition, center).addScalar(0.5).multiply(scale); // to check if rotation is not zero
20025 if (sin !== undefined) {
20026 _rotatedPosition.x = cos * _alignedPosition.x - sin * _alignedPosition.y;
20027 _rotatedPosition.y = sin * _alignedPosition.x + cos * _alignedPosition.y;
20029 _rotatedPosition.copy(_alignedPosition);
20032 vertexPosition.copy(mvPosition);
20033 vertexPosition.x += _rotatedPosition.x;
20034 vertexPosition.y += _rotatedPosition.y; // transform to world space
20036 vertexPosition.applyMatrix4(_viewWorldMatrix);
20039 var _v1$4 = new Vector3();
20041 var _v2$2 = new Vector3();
20044 Object3D.call(this);
20045 this._currentLevel = 0;
20047 Object.defineProperties(this, {
20053 this.autoUpdate = true;
20056 LOD.prototype = Object.assign(Object.create(Object3D.prototype), {
20059 copy: function copy(source) {
20060 Object3D.prototype.copy.call(this, source, false);
20061 var levels = source.levels;
20063 for (var i = 0, l = levels.length; i < l; i++) {
20064 var level = levels[i];
20065 this.addLevel(level.object.clone(), level.distance);
20068 this.autoUpdate = source.autoUpdate;
20071 addLevel: function addLevel(object, distance) {
20072 if (distance === void 0) {
20076 distance = Math.abs(distance);
20077 var levels = this.levels;
20080 for (l = 0; l < levels.length; l++) {
20081 if (distance < levels[l].distance) {
20086 levels.splice(l, 0, {
20087 distance: distance,
20093 getCurrentLevel: function getCurrentLevel() {
20094 return this._currentLevel;
20096 getObjectForDistance: function getObjectForDistance(distance) {
20097 var levels = this.levels;
20099 if (levels.length > 0) {
20102 for (i = 1, l = levels.length; i < l; i++) {
20103 if (distance < levels[i].distance) {
20108 return levels[i - 1].object;
20113 raycast: function raycast(raycaster, intersects) {
20114 var levels = this.levels;
20116 if (levels.length > 0) {
20117 _v1$4.setFromMatrixPosition(this.matrixWorld);
20119 var distance = raycaster.ray.origin.distanceTo(_v1$4);
20120 this.getObjectForDistance(distance).raycast(raycaster, intersects);
20123 update: function update(camera) {
20124 var levels = this.levels;
20126 if (levels.length > 1) {
20127 _v1$4.setFromMatrixPosition(camera.matrixWorld);
20129 _v2$2.setFromMatrixPosition(this.matrixWorld);
20131 var distance = _v1$4.distanceTo(_v2$2) / camera.zoom;
20132 levels[0].object.visible = true;
20135 for (i = 1, l = levels.length; i < l; i++) {
20136 if (distance >= levels[i].distance) {
20137 levels[i - 1].object.visible = false;
20138 levels[i].object.visible = true;
20144 this._currentLevel = i - 1;
20146 for (; i < l; i++) {
20147 levels[i].object.visible = false;
20151 toJSON: function toJSON(meta) {
20152 var data = Object3D.prototype.toJSON.call(this, meta);
20153 if (this.autoUpdate === false) data.object.autoUpdate = false;
20154 data.object.levels = [];
20155 var levels = this.levels;
20157 for (var i = 0, l = levels.length; i < l; i++) {
20158 var level = levels[i];
20159 data.object.levels.push({
20160 object: level.object.uuid,
20161 distance: level.distance
20169 var _basePosition = new Vector3();
20171 var _skinIndex = new Vector4();
20173 var _skinWeight = new Vector4();
20175 var _vector$7 = new Vector3();
20177 var _matrix$1 = new Matrix4();
20179 function SkinnedMesh(geometry, material) {
20180 if (geometry && geometry.isGeometry) {
20181 console.error('THREE.SkinnedMesh no longer supports THREE.Geometry. Use THREE.BufferGeometry instead.');
20184 Mesh.call(this, geometry, material);
20185 this.type = 'SkinnedMesh';
20186 this.bindMode = 'attached';
20187 this.bindMatrix = new Matrix4();
20188 this.bindMatrixInverse = new Matrix4();
20191 SkinnedMesh.prototype = Object.assign(Object.create(Mesh.prototype), {
20192 constructor: SkinnedMesh,
20193 isSkinnedMesh: true,
20194 copy: function copy(source) {
20195 Mesh.prototype.copy.call(this, source);
20196 this.bindMode = source.bindMode;
20197 this.bindMatrix.copy(source.bindMatrix);
20198 this.bindMatrixInverse.copy(source.bindMatrixInverse);
20199 this.skeleton = source.skeleton;
20202 bind: function bind(skeleton, bindMatrix) {
20203 this.skeleton = skeleton;
20205 if (bindMatrix === undefined) {
20206 this.updateMatrixWorld(true);
20207 this.skeleton.calculateInverses();
20208 bindMatrix = this.matrixWorld;
20211 this.bindMatrix.copy(bindMatrix);
20212 this.bindMatrixInverse.copy(bindMatrix).invert();
20214 pose: function pose() {
20215 this.skeleton.pose();
20217 normalizeSkinWeights: function normalizeSkinWeights() {
20218 var vector = new Vector4();
20219 var skinWeight = this.geometry.attributes.skinWeight;
20221 for (var i = 0, l = skinWeight.count; i < l; i++) {
20222 vector.x = skinWeight.getX(i);
20223 vector.y = skinWeight.getY(i);
20224 vector.z = skinWeight.getZ(i);
20225 vector.w = skinWeight.getW(i);
20226 var scale = 1.0 / vector.manhattanLength();
20228 if (scale !== Infinity) {
20229 vector.multiplyScalar(scale);
20231 vector.set(1, 0, 0, 0); // do something reasonable
20234 skinWeight.setXYZW(i, vector.x, vector.y, vector.z, vector.w);
20237 updateMatrixWorld: function updateMatrixWorld(force) {
20238 Mesh.prototype.updateMatrixWorld.call(this, force);
20240 if (this.bindMode === 'attached') {
20241 this.bindMatrixInverse.copy(this.matrixWorld).invert();
20242 } else if (this.bindMode === 'detached') {
20243 this.bindMatrixInverse.copy(this.bindMatrix).invert();
20245 console.warn('THREE.SkinnedMesh: Unrecognized bindMode: ' + this.bindMode);
20248 boneTransform: function boneTransform(index, target) {
20249 var skeleton = this.skeleton;
20250 var geometry = this.geometry;
20252 _skinIndex.fromBufferAttribute(geometry.attributes.skinIndex, index);
20254 _skinWeight.fromBufferAttribute(geometry.attributes.skinWeight, index);
20256 _basePosition.fromBufferAttribute(geometry.attributes.position, index).applyMatrix4(this.bindMatrix);
20258 target.set(0, 0, 0);
20260 for (var i = 0; i < 4; i++) {
20261 var weight = _skinWeight.getComponent(i);
20263 if (weight !== 0) {
20264 var boneIndex = _skinIndex.getComponent(i);
20266 _matrix$1.multiplyMatrices(skeleton.bones[boneIndex].matrixWorld, skeleton.boneInverses[boneIndex]);
20268 target.addScaledVector(_vector$7.copy(_basePosition).applyMatrix4(_matrix$1), weight);
20272 return target.applyMatrix4(this.bindMatrixInverse);
20277 Object3D.call(this);
20278 this.type = 'Bone';
20281 Bone.prototype = Object.assign(Object.create(Object3D.prototype), {
20286 var _offsetMatrix = new Matrix4();
20288 var _identityMatrix = new Matrix4();
20290 function Skeleton(bones, boneInverses) {
20291 if (bones === void 0) {
20295 if (boneInverses === void 0) {
20299 this.uuid = MathUtils.generateUUID();
20300 this.bones = bones.slice(0);
20301 this.boneInverses = boneInverses;
20302 this.boneMatrices = null;
20303 this.boneTexture = null;
20304 this.boneTextureSize = 0;
20309 Object.assign(Skeleton.prototype, {
20310 init: function init() {
20311 var bones = this.bones;
20312 var boneInverses = this.boneInverses;
20313 this.boneMatrices = new Float32Array(bones.length * 16); // calculate inverse bone matrices if necessary
20315 if (boneInverses.length === 0) {
20316 this.calculateInverses();
20318 // handle special case
20319 if (bones.length !== boneInverses.length) {
20320 console.warn('THREE.Skeleton: Number of inverse bone matrices does not match amount of bones.');
20321 this.boneInverses = [];
20323 for (var i = 0, il = this.bones.length; i < il; i++) {
20324 this.boneInverses.push(new Matrix4());
20329 calculateInverses: function calculateInverses() {
20330 this.boneInverses.length = 0;
20332 for (var i = 0, il = this.bones.length; i < il; i++) {
20333 var inverse = new Matrix4();
20335 if (this.bones[i]) {
20336 inverse.copy(this.bones[i].matrixWorld).invert();
20339 this.boneInverses.push(inverse);
20342 pose: function pose() {
20343 // recover the bind-time world matrices
20344 for (var i = 0, il = this.bones.length; i < il; i++) {
20345 var bone = this.bones[i];
20348 bone.matrixWorld.copy(this.boneInverses[i]).invert();
20350 } // compute the local matrices, positions, rotations and scales
20353 for (var _i = 0, _il = this.bones.length; _i < _il; _i++) {
20354 var _bone = this.bones[_i];
20357 if (_bone.parent && _bone.parent.isBone) {
20358 _bone.matrix.copy(_bone.parent.matrixWorld).invert();
20360 _bone.matrix.multiply(_bone.matrixWorld);
20362 _bone.matrix.copy(_bone.matrixWorld);
20365 _bone.matrix.decompose(_bone.position, _bone.quaternion, _bone.scale);
20369 update: function update() {
20370 var bones = this.bones;
20371 var boneInverses = this.boneInverses;
20372 var boneMatrices = this.boneMatrices;
20373 var boneTexture = this.boneTexture; // flatten bone matrices to array
20375 for (var i = 0, il = bones.length; i < il; i++) {
20376 // compute the offset between the current and the original transform
20377 var matrix = bones[i] ? bones[i].matrixWorld : _identityMatrix;
20379 _offsetMatrix.multiplyMatrices(matrix, boneInverses[i]);
20381 _offsetMatrix.toArray(boneMatrices, i * 16);
20384 if (boneTexture !== null) {
20385 boneTexture.needsUpdate = true;
20388 clone: function clone() {
20389 return new Skeleton(this.bones, this.boneInverses);
20391 getBoneByName: function getBoneByName(name) {
20392 for (var i = 0, il = this.bones.length; i < il; i++) {
20393 var bone = this.bones[i];
20395 if (bone.name === name) {
20402 dispose: function dispose() {
20403 if (this.boneTexture !== null) {
20404 this.boneTexture.dispose();
20405 this.boneTexture = null;
20408 fromJSON: function fromJSON(json, bones) {
20409 this.uuid = json.uuid;
20411 for (var i = 0, l = json.bones.length; i < l; i++) {
20412 var uuid = json.bones[i];
20413 var bone = bones[uuid];
20415 if (bone === undefined) {
20416 console.warn('THREE.Skeleton: No bone found with UUID:', uuid);
20420 this.bones.push(bone);
20421 this.boneInverses.push(new Matrix4().fromArray(json.boneInverses[i]));
20427 toJSON: function toJSON() {
20432 generator: 'Skeleton.toJSON'
20437 data.uuid = this.uuid;
20438 var bones = this.bones;
20439 var boneInverses = this.boneInverses;
20441 for (var i = 0, l = bones.length; i < l; i++) {
20442 var bone = bones[i];
20443 data.bones.push(bone.uuid);
20444 var boneInverse = boneInverses[i];
20445 data.boneInverses.push(boneInverse.toArray());
20452 var _instanceLocalMatrix = new Matrix4();
20454 var _instanceWorldMatrix = new Matrix4();
20456 var _instanceIntersects = [];
20458 var _mesh = new Mesh();
20460 function InstancedMesh(geometry, material, count) {
20461 Mesh.call(this, geometry, material);
20462 this.instanceMatrix = new BufferAttribute(new Float32Array(count * 16), 16);
20463 this.instanceColor = null;
20464 this.count = count;
20465 this.frustumCulled = false;
20468 InstancedMesh.prototype = Object.assign(Object.create(Mesh.prototype), {
20469 constructor: InstancedMesh,
20470 isInstancedMesh: true,
20471 copy: function copy(source) {
20472 Mesh.prototype.copy.call(this, source);
20473 this.instanceMatrix.copy(source.instanceMatrix);
20474 if (source.instanceColor !== null) this.instanceColor = source.instanceColor.clone();
20475 this.count = source.count;
20478 getColorAt: function getColorAt(index, color) {
20479 color.fromArray(this.instanceColor.array, index * 3);
20481 getMatrixAt: function getMatrixAt(index, matrix) {
20482 matrix.fromArray(this.instanceMatrix.array, index * 16);
20484 raycast: function raycast(raycaster, intersects) {
20485 var matrixWorld = this.matrixWorld;
20486 var raycastTimes = this.count;
20487 _mesh.geometry = this.geometry;
20488 _mesh.material = this.material;
20489 if (_mesh.material === undefined) return;
20491 for (var instanceId = 0; instanceId < raycastTimes; instanceId++) {
20492 // calculate the world matrix for each instance
20493 this.getMatrixAt(instanceId, _instanceLocalMatrix);
20495 _instanceWorldMatrix.multiplyMatrices(matrixWorld, _instanceLocalMatrix); // the mesh represents this single instance
20498 _mesh.matrixWorld = _instanceWorldMatrix;
20500 _mesh.raycast(raycaster, _instanceIntersects); // process the result of raycast
20503 for (var i = 0, l = _instanceIntersects.length; i < l; i++) {
20504 var intersect = _instanceIntersects[i];
20505 intersect.instanceId = instanceId;
20506 intersect.object = this;
20507 intersects.push(intersect);
20510 _instanceIntersects.length = 0;
20513 setColorAt: function setColorAt(index, color) {
20514 if (this.instanceColor === null) {
20515 this.instanceColor = new BufferAttribute(new Float32Array(this.count * 3), 3);
20518 color.toArray(this.instanceColor.array, index * 3);
20520 setMatrixAt: function setMatrixAt(index, matrix) {
20521 matrix.toArray(this.instanceMatrix.array, index * 16);
20523 updateMorphTargets: function updateMorphTargets() {},
20524 dispose: function dispose() {
20525 this.dispatchEvent({
20534 * opacity: <float>,
20536 * linewidth: <float>,
20537 * linecap: "round",
20538 * linejoin: "round"
20542 function LineBasicMaterial(parameters) {
20543 Material.call(this);
20544 this.type = 'LineBasicMaterial';
20545 this.color = new Color(0xffffff);
20546 this.linewidth = 1;
20547 this.linecap = 'round';
20548 this.linejoin = 'round';
20549 this.morphTargets = false;
20550 this.setValues(parameters);
20553 LineBasicMaterial.prototype = Object.create(Material.prototype);
20554 LineBasicMaterial.prototype.constructor = LineBasicMaterial;
20555 LineBasicMaterial.prototype.isLineBasicMaterial = true;
20557 LineBasicMaterial.prototype.copy = function (source) {
20558 Material.prototype.copy.call(this, source);
20559 this.color.copy(source.color);
20560 this.linewidth = source.linewidth;
20561 this.linecap = source.linecap;
20562 this.linejoin = source.linejoin;
20563 this.morphTargets = source.morphTargets;
20567 var _start = new Vector3();
20569 var _end = new Vector3();
20571 var _inverseMatrix$1 = new Matrix4();
20573 var _ray$1 = new Ray();
20575 var _sphere$2 = new Sphere();
20577 function Line(geometry, material) {
20578 if (geometry === void 0) {
20579 geometry = new BufferGeometry();
20582 if (material === void 0) {
20583 material = new LineBasicMaterial();
20586 Object3D.call(this);
20587 this.type = 'Line';
20588 this.geometry = geometry;
20589 this.material = material;
20590 this.updateMorphTargets();
20593 Line.prototype = Object.assign(Object.create(Object3D.prototype), {
20596 copy: function copy(source) {
20597 Object3D.prototype.copy.call(this, source);
20598 this.material = source.material;
20599 this.geometry = source.geometry;
20602 computeLineDistances: function computeLineDistances() {
20603 var geometry = this.geometry;
20605 if (geometry.isBufferGeometry) {
20606 // we assume non-indexed geometry
20607 if (geometry.index === null) {
20608 var positionAttribute = geometry.attributes.position;
20609 var lineDistances = [0];
20611 for (var i = 1, l = positionAttribute.count; i < l; i++) {
20612 _start.fromBufferAttribute(positionAttribute, i - 1);
20614 _end.fromBufferAttribute(positionAttribute, i);
20616 lineDistances[i] = lineDistances[i - 1];
20617 lineDistances[i] += _start.distanceTo(_end);
20620 geometry.setAttribute('lineDistance', new Float32BufferAttribute(lineDistances, 1));
20622 console.warn('THREE.Line.computeLineDistances(): Computation only possible with non-indexed BufferGeometry.');
20624 } else if (geometry.isGeometry) {
20625 console.error('THREE.Line.computeLineDistances() no longer supports THREE.Geometry. Use THREE.BufferGeometry instead.');
20630 raycast: function raycast(raycaster, intersects) {
20631 var geometry = this.geometry;
20632 var matrixWorld = this.matrixWorld;
20633 var threshold = raycaster.params.Line.threshold; // Checking boundingSphere distance to ray
20635 if (geometry.boundingSphere === null) geometry.computeBoundingSphere();
20637 _sphere$2.copy(geometry.boundingSphere);
20639 _sphere$2.applyMatrix4(matrixWorld);
20641 _sphere$2.radius += threshold;
20642 if (raycaster.ray.intersectsSphere(_sphere$2) === false) return; //
20644 _inverseMatrix$1.copy(matrixWorld).invert();
20646 _ray$1.copy(raycaster.ray).applyMatrix4(_inverseMatrix$1);
20648 var localThreshold = threshold / ((this.scale.x + this.scale.y + this.scale.z) / 3);
20649 var localThresholdSq = localThreshold * localThreshold;
20650 var vStart = new Vector3();
20651 var vEnd = new Vector3();
20652 var interSegment = new Vector3();
20653 var interRay = new Vector3();
20654 var step = this.isLineSegments ? 2 : 1;
20656 if (geometry.isBufferGeometry) {
20657 var index = geometry.index;
20658 var attributes = geometry.attributes;
20659 var positionAttribute = attributes.position;
20661 if (index !== null) {
20662 var indices = index.array;
20664 for (var i = 0, l = indices.length - 1; i < l; i += step) {
20665 var a = indices[i];
20666 var b = indices[i + 1];
20667 vStart.fromBufferAttribute(positionAttribute, a);
20668 vEnd.fromBufferAttribute(positionAttribute, b);
20670 var distSq = _ray$1.distanceSqToSegment(vStart, vEnd, interRay, interSegment);
20672 if (distSq > localThresholdSq) continue;
20673 interRay.applyMatrix4(this.matrixWorld); //Move back to world space for distance calculation
20675 var distance = raycaster.ray.origin.distanceTo(interRay);
20676 if (distance < raycaster.near || distance > raycaster.far) continue;
20678 distance: distance,
20679 // What do we want? intersection point on the ray or on the segment??
20680 // point: raycaster.ray.at( distance ),
20681 point: interSegment.clone().applyMatrix4(this.matrixWorld),
20689 for (var _i = 0, _l = positionAttribute.count - 1; _i < _l; _i += step) {
20690 vStart.fromBufferAttribute(positionAttribute, _i);
20691 vEnd.fromBufferAttribute(positionAttribute, _i + 1);
20693 var _distSq = _ray$1.distanceSqToSegment(vStart, vEnd, interRay, interSegment);
20695 if (_distSq > localThresholdSq) continue;
20696 interRay.applyMatrix4(this.matrixWorld); //Move back to world space for distance calculation
20698 var _distance = raycaster.ray.origin.distanceTo(interRay);
20700 if (_distance < raycaster.near || _distance > raycaster.far) continue;
20702 distance: _distance,
20703 // What do we want? intersection point on the ray or on the segment??
20704 // point: raycaster.ray.at( distance ),
20705 point: interSegment.clone().applyMatrix4(this.matrixWorld),
20713 } else if (geometry.isGeometry) {
20714 console.error('THREE.Line.raycast() no longer supports THREE.Geometry. Use THREE.BufferGeometry instead.');
20717 updateMorphTargets: function updateMorphTargets() {
20718 var geometry = this.geometry;
20720 if (geometry.isBufferGeometry) {
20721 var morphAttributes = geometry.morphAttributes;
20722 var keys = Object.keys(morphAttributes);
20724 if (keys.length > 0) {
20725 var morphAttribute = morphAttributes[keys[0]];
20727 if (morphAttribute !== undefined) {
20728 this.morphTargetInfluences = [];
20729 this.morphTargetDictionary = {};
20731 for (var m = 0, ml = morphAttribute.length; m < ml; m++) {
20732 var name = morphAttribute[m].name || String(m);
20733 this.morphTargetInfluences.push(0);
20734 this.morphTargetDictionary[name] = m;
20739 var morphTargets = geometry.morphTargets;
20741 if (morphTargets !== undefined && morphTargets.length > 0) {
20742 console.error('THREE.Line.updateMorphTargets() does not support THREE.Geometry. Use THREE.BufferGeometry instead.');
20748 var _start$1 = new Vector3();
20750 var _end$1 = new Vector3();
20752 function LineSegments(geometry, material) {
20753 Line.call(this, geometry, material);
20754 this.type = 'LineSegments';
20757 LineSegments.prototype = Object.assign(Object.create(Line.prototype), {
20758 constructor: LineSegments,
20759 isLineSegments: true,
20760 computeLineDistances: function computeLineDistances() {
20761 var geometry = this.geometry;
20763 if (geometry.isBufferGeometry) {
20764 // we assume non-indexed geometry
20765 if (geometry.index === null) {
20766 var positionAttribute = geometry.attributes.position;
20767 var lineDistances = [];
20769 for (var i = 0, l = positionAttribute.count; i < l; i += 2) {
20770 _start$1.fromBufferAttribute(positionAttribute, i);
20772 _end$1.fromBufferAttribute(positionAttribute, i + 1);
20774 lineDistances[i] = i === 0 ? 0 : lineDistances[i - 1];
20775 lineDistances[i + 1] = lineDistances[i] + _start$1.distanceTo(_end$1);
20778 geometry.setAttribute('lineDistance', new Float32BufferAttribute(lineDistances, 1));
20780 console.warn('THREE.LineSegments.computeLineDistances(): Computation only possible with non-indexed BufferGeometry.');
20782 } else if (geometry.isGeometry) {
20783 console.error('THREE.LineSegments.computeLineDistances() no longer supports THREE.Geometry. Use THREE.BufferGeometry instead.');
20790 function LineLoop(geometry, material) {
20791 Line.call(this, geometry, material);
20792 this.type = 'LineLoop';
20795 LineLoop.prototype = Object.assign(Object.create(Line.prototype), {
20796 constructor: LineLoop,
20803 * opacity: <float>,
20804 * map: new THREE.Texture( <Image> ),
20805 * alphaMap: new THREE.Texture( <Image> ),
20808 * sizeAttenuation: <bool>
20810 * morphTargets: <bool>
20814 function PointsMaterial(parameters) {
20815 Material.call(this);
20816 this.type = 'PointsMaterial';
20817 this.color = new Color(0xffffff);
20819 this.alphaMap = null;
20821 this.sizeAttenuation = true;
20822 this.morphTargets = false;
20823 this.setValues(parameters);
20826 PointsMaterial.prototype = Object.create(Material.prototype);
20827 PointsMaterial.prototype.constructor = PointsMaterial;
20828 PointsMaterial.prototype.isPointsMaterial = true;
20830 PointsMaterial.prototype.copy = function (source) {
20831 Material.prototype.copy.call(this, source);
20832 this.color.copy(source.color);
20833 this.map = source.map;
20834 this.alphaMap = source.alphaMap;
20835 this.size = source.size;
20836 this.sizeAttenuation = source.sizeAttenuation;
20837 this.morphTargets = source.morphTargets;
20841 var _inverseMatrix$2 = new Matrix4();
20843 var _ray$2 = new Ray();
20845 var _sphere$3 = new Sphere();
20847 var _position$1 = new Vector3();
20849 function Points(geometry, material) {
20850 if (geometry === void 0) {
20851 geometry = new BufferGeometry();
20854 if (material === void 0) {
20855 material = new PointsMaterial();
20858 Object3D.call(this);
20859 this.type = 'Points';
20860 this.geometry = geometry;
20861 this.material = material;
20862 this.updateMorphTargets();
20865 Points.prototype = Object.assign(Object.create(Object3D.prototype), {
20866 constructor: Points,
20868 copy: function copy(source) {
20869 Object3D.prototype.copy.call(this, source);
20870 this.material = source.material;
20871 this.geometry = source.geometry;
20874 raycast: function raycast(raycaster, intersects) {
20875 var geometry = this.geometry;
20876 var matrixWorld = this.matrixWorld;
20877 var threshold = raycaster.params.Points.threshold; // Checking boundingSphere distance to ray
20879 if (geometry.boundingSphere === null) geometry.computeBoundingSphere();
20881 _sphere$3.copy(geometry.boundingSphere);
20883 _sphere$3.applyMatrix4(matrixWorld);
20885 _sphere$3.radius += threshold;
20886 if (raycaster.ray.intersectsSphere(_sphere$3) === false) return; //
20888 _inverseMatrix$2.copy(matrixWorld).invert();
20890 _ray$2.copy(raycaster.ray).applyMatrix4(_inverseMatrix$2);
20892 var localThreshold = threshold / ((this.scale.x + this.scale.y + this.scale.z) / 3);
20893 var localThresholdSq = localThreshold * localThreshold;
20895 if (geometry.isBufferGeometry) {
20896 var index = geometry.index;
20897 var attributes = geometry.attributes;
20898 var positionAttribute = attributes.position;
20900 if (index !== null) {
20901 var indices = index.array;
20903 for (var i = 0, il = indices.length; i < il; i++) {
20904 var a = indices[i];
20906 _position$1.fromBufferAttribute(positionAttribute, a);
20908 testPoint(_position$1, a, localThresholdSq, matrixWorld, raycaster, intersects, this);
20911 for (var _i = 0, l = positionAttribute.count; _i < l; _i++) {
20912 _position$1.fromBufferAttribute(positionAttribute, _i);
20914 testPoint(_position$1, _i, localThresholdSq, matrixWorld, raycaster, intersects, this);
20918 console.error('THREE.Points.raycast() no longer supports THREE.Geometry. Use THREE.BufferGeometry instead.');
20921 updateMorphTargets: function updateMorphTargets() {
20922 var geometry = this.geometry;
20924 if (geometry.isBufferGeometry) {
20925 var morphAttributes = geometry.morphAttributes;
20926 var keys = Object.keys(morphAttributes);
20928 if (keys.length > 0) {
20929 var morphAttribute = morphAttributes[keys[0]];
20931 if (morphAttribute !== undefined) {
20932 this.morphTargetInfluences = [];
20933 this.morphTargetDictionary = {};
20935 for (var m = 0, ml = morphAttribute.length; m < ml; m++) {
20936 var name = morphAttribute[m].name || String(m);
20937 this.morphTargetInfluences.push(0);
20938 this.morphTargetDictionary[name] = m;
20943 var morphTargets = geometry.morphTargets;
20945 if (morphTargets !== undefined && morphTargets.length > 0) {
20946 console.error('THREE.Points.updateMorphTargets() does not support THREE.Geometry. Use THREE.BufferGeometry instead.');
20952 function testPoint(point, index, localThresholdSq, matrixWorld, raycaster, intersects, object) {
20953 var rayPointDistanceSq = _ray$2.distanceSqToPoint(point);
20955 if (rayPointDistanceSq < localThresholdSq) {
20956 var intersectPoint = new Vector3();
20958 _ray$2.closestPointToPoint(point, intersectPoint);
20960 intersectPoint.applyMatrix4(matrixWorld);
20961 var distance = raycaster.ray.origin.distanceTo(intersectPoint);
20962 if (distance < raycaster.near || distance > raycaster.far) return;
20964 distance: distance,
20965 distanceToRay: Math.sqrt(rayPointDistanceSq),
20966 point: intersectPoint,
20974 function VideoTexture(video, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy) {
20975 Texture.call(this, video, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy);
20976 this.format = format !== undefined ? format : RGBFormat;
20977 this.minFilter = minFilter !== undefined ? minFilter : LinearFilter;
20978 this.magFilter = magFilter !== undefined ? magFilter : LinearFilter;
20979 this.generateMipmaps = false;
20982 function updateVideo() {
20983 scope.needsUpdate = true;
20984 video.requestVideoFrameCallback(updateVideo);
20987 if ('requestVideoFrameCallback' in video) {
20988 video.requestVideoFrameCallback(updateVideo);
20992 VideoTexture.prototype = Object.assign(Object.create(Texture.prototype), {
20993 constructor: VideoTexture,
20994 clone: function clone() {
20995 return new this.constructor(this.image).copy(this);
20997 isVideoTexture: true,
20998 update: function update() {
20999 var video = this.image;
21000 var hasVideoFrameCallback = ('requestVideoFrameCallback' in video);
21002 if (hasVideoFrameCallback === false && video.readyState >= video.HAVE_CURRENT_DATA) {
21003 this.needsUpdate = true;
21008 function CompressedTexture(mipmaps, width, height, format, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy, encoding) {
21009 Texture.call(this, null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding);
21014 this.mipmaps = mipmaps; // no flipping for cube textures
21015 // (also flipping doesn't work for compressed textures )
21017 this.flipY = false; // can't generate mipmaps for compressed textures
21018 // mips must be embedded in DDS files
21020 this.generateMipmaps = false;
21023 CompressedTexture.prototype = Object.create(Texture.prototype);
21024 CompressedTexture.prototype.constructor = CompressedTexture;
21025 CompressedTexture.prototype.isCompressedTexture = true;
21027 function CanvasTexture(canvas, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy) {
21028 Texture.call(this, canvas, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy);
21029 this.needsUpdate = true;
21032 CanvasTexture.prototype = Object.create(Texture.prototype);
21033 CanvasTexture.prototype.constructor = CanvasTexture;
21034 CanvasTexture.prototype.isCanvasTexture = true;
21036 function DepthTexture(width, height, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy, format) {
21037 format = format !== undefined ? format : DepthFormat;
21039 if (format !== DepthFormat && format !== DepthStencilFormat) {
21040 throw new Error('DepthTexture format must be either THREE.DepthFormat or THREE.DepthStencilFormat');
21043 if (type === undefined && format === DepthFormat) type = UnsignedShortType;
21044 if (type === undefined && format === DepthStencilFormat) type = UnsignedInt248Type;
21045 Texture.call(this, null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy);
21050 this.magFilter = magFilter !== undefined ? magFilter : NearestFilter;
21051 this.minFilter = minFilter !== undefined ? minFilter : NearestFilter;
21052 this.flipY = false;
21053 this.generateMipmaps = false;
21056 DepthTexture.prototype = Object.create(Texture.prototype);
21057 DepthTexture.prototype.constructor = DepthTexture;
21058 DepthTexture.prototype.isDepthTexture = true;
21060 var CircleGeometry = /*#__PURE__*/function (_BufferGeometry) {
21061 _inheritsLoose(CircleGeometry, _BufferGeometry);
21063 function CircleGeometry(radius, segments, thetaStart, thetaLength) {
21066 if (radius === void 0) {
21070 if (segments === void 0) {
21074 if (thetaStart === void 0) {
21078 if (thetaLength === void 0) {
21079 thetaLength = Math.PI * 2;
21082 _this = _BufferGeometry.call(this) || this;
21083 _this.type = 'CircleGeometry';
21084 _this.parameters = {
21086 segments: segments,
21087 thetaStart: thetaStart,
21088 thetaLength: thetaLength
21090 segments = Math.max(3, segments); // buffers
21095 var uvs = []; // helper variables
21097 var vertex = new Vector3();
21098 var uv = new Vector2(); // center point
21100 vertices.push(0, 0, 0);
21101 normals.push(0, 0, 1);
21102 uvs.push(0.5, 0.5);
21104 for (var s = 0, i = 3; s <= segments; s++, i += 3) {
21105 var segment = thetaStart + s / segments * thetaLength; // vertex
21107 vertex.x = radius * Math.cos(segment);
21108 vertex.y = radius * Math.sin(segment);
21109 vertices.push(vertex.x, vertex.y, vertex.z); // normal
21111 normals.push(0, 0, 1); // uvs
21113 uv.x = (vertices[i] / radius + 1) / 2;
21114 uv.y = (vertices[i + 1] / radius + 1) / 2;
21115 uvs.push(uv.x, uv.y);
21119 for (var _i = 1; _i <= segments; _i++) {
21120 indices.push(_i, _i + 1, 0);
21121 } // build geometry
21124 _this.setIndex(indices);
21126 _this.setAttribute('position', new Float32BufferAttribute(vertices, 3));
21128 _this.setAttribute('normal', new Float32BufferAttribute(normals, 3));
21130 _this.setAttribute('uv', new Float32BufferAttribute(uvs, 2));
21135 return CircleGeometry;
21138 var CylinderGeometry = /*#__PURE__*/function (_BufferGeometry) {
21139 _inheritsLoose(CylinderGeometry, _BufferGeometry);
21141 function CylinderGeometry(radiusTop, radiusBottom, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength) {
21144 if (radiusTop === void 0) {
21148 if (radiusBottom === void 0) {
21152 if (height === void 0) {
21156 if (radialSegments === void 0) {
21157 radialSegments = 8;
21160 if (heightSegments === void 0) {
21161 heightSegments = 1;
21164 if (openEnded === void 0) {
21168 if (thetaStart === void 0) {
21172 if (thetaLength === void 0) {
21173 thetaLength = Math.PI * 2;
21176 _this = _BufferGeometry.call(this) || this;
21177 _this.type = 'CylinderGeometry';
21178 _this.parameters = {
21179 radiusTop: radiusTop,
21180 radiusBottom: radiusBottom,
21182 radialSegments: radialSegments,
21183 heightSegments: heightSegments,
21184 openEnded: openEnded,
21185 thetaStart: thetaStart,
21186 thetaLength: thetaLength
21189 var scope = _assertThisInitialized(_this);
21191 radialSegments = Math.floor(radialSegments);
21192 heightSegments = Math.floor(heightSegments); // buffers
21197 var uvs = []; // helper variables
21200 var indexArray = [];
21201 var halfHeight = height / 2;
21202 var groupStart = 0; // generate geometry
21206 if (openEnded === false) {
21207 if (radiusTop > 0) generateCap(true);
21208 if (radiusBottom > 0) generateCap(false);
21209 } // build geometry
21212 _this.setIndex(indices);
21214 _this.setAttribute('position', new Float32BufferAttribute(vertices, 3));
21216 _this.setAttribute('normal', new Float32BufferAttribute(normals, 3));
21218 _this.setAttribute('uv', new Float32BufferAttribute(uvs, 2));
21220 function generateTorso() {
21221 var normal = new Vector3();
21222 var vertex = new Vector3();
21223 var groupCount = 0; // this will be used to calculate the normal
21225 var slope = (radiusBottom - radiusTop) / height; // generate vertices, normals and uvs
21227 for (var y = 0; y <= heightSegments; y++) {
21229 var v = y / heightSegments; // calculate the radius of the current row
21231 var radius = v * (radiusBottom - radiusTop) + radiusTop;
21233 for (var x = 0; x <= radialSegments; x++) {
21234 var u = x / radialSegments;
21235 var theta = u * thetaLength + thetaStart;
21236 var sinTheta = Math.sin(theta);
21237 var cosTheta = Math.cos(theta); // vertex
21239 vertex.x = radius * sinTheta;
21240 vertex.y = -v * height + halfHeight;
21241 vertex.z = radius * cosTheta;
21242 vertices.push(vertex.x, vertex.y, vertex.z); // normal
21244 normal.set(sinTheta, slope, cosTheta).normalize();
21245 normals.push(normal.x, normal.y, normal.z); // uv
21247 uvs.push(u, 1 - v); // save index of vertex in respective row
21249 indexRow.push(index++);
21250 } // now save vertices of the row in our index array
21253 indexArray.push(indexRow);
21254 } // generate indices
21257 for (var _x = 0; _x < radialSegments; _x++) {
21258 for (var _y = 0; _y < heightSegments; _y++) {
21259 // we use the index array to access the correct indices
21260 var a = indexArray[_y][_x];
21261 var b = indexArray[_y + 1][_x];
21262 var c = indexArray[_y + 1][_x + 1];
21263 var d = indexArray[_y][_x + 1]; // faces
21265 indices.push(a, b, d);
21266 indices.push(b, c, d); // update group counter
21270 } // add a group to the geometry. this will ensure multi material support
21273 scope.addGroup(groupStart, groupCount, 0); // calculate new start value for groups
21275 groupStart += groupCount;
21278 function generateCap(top) {
21279 // save the index of the first center vertex
21280 var centerIndexStart = index;
21281 var uv = new Vector2();
21282 var vertex = new Vector3();
21283 var groupCount = 0;
21284 var radius = top === true ? radiusTop : radiusBottom;
21285 var sign = top === true ? 1 : -1; // first we generate the center vertex data of the cap.
21286 // because the geometry needs one set of uvs per face,
21287 // we must generate a center vertex per face/segment
21289 for (var x = 1; x <= radialSegments; x++) {
21291 vertices.push(0, halfHeight * sign, 0); // normal
21293 normals.push(0, sign, 0); // uv
21295 uvs.push(0.5, 0.5); // increase index
21298 } // save the index of the last center vertex
21301 var centerIndexEnd = index; // now we generate the surrounding vertices, normals and uvs
21303 for (var _x2 = 0; _x2 <= radialSegments; _x2++) {
21304 var u = _x2 / radialSegments;
21305 var theta = u * thetaLength + thetaStart;
21306 var cosTheta = Math.cos(theta);
21307 var sinTheta = Math.sin(theta); // vertex
21309 vertex.x = radius * sinTheta;
21310 vertex.y = halfHeight * sign;
21311 vertex.z = radius * cosTheta;
21312 vertices.push(vertex.x, vertex.y, vertex.z); // normal
21314 normals.push(0, sign, 0); // uv
21316 uv.x = cosTheta * 0.5 + 0.5;
21317 uv.y = sinTheta * 0.5 * sign + 0.5;
21318 uvs.push(uv.x, uv.y); // increase index
21321 } // generate indices
21324 for (var _x3 = 0; _x3 < radialSegments; _x3++) {
21325 var c = centerIndexStart + _x3;
21326 var i = centerIndexEnd + _x3;
21328 if (top === true) {
21330 indices.push(i, i + 1, c);
21333 indices.push(i + 1, i, c);
21337 } // add a group to the geometry. this will ensure multi material support
21340 scope.addGroup(groupStart, groupCount, top === true ? 1 : 2); // calculate new start value for groups
21342 groupStart += groupCount;
21348 return CylinderGeometry;
21351 var ConeGeometry = /*#__PURE__*/function (_CylinderGeometry) {
21352 _inheritsLoose(ConeGeometry, _CylinderGeometry);
21354 function ConeGeometry(radius, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength) {
21357 if (radius === void 0) {
21361 if (height === void 0) {
21365 if (radialSegments === void 0) {
21366 radialSegments = 8;
21369 if (heightSegments === void 0) {
21370 heightSegments = 1;
21373 if (openEnded === void 0) {
21377 if (thetaStart === void 0) {
21381 if (thetaLength === void 0) {
21382 thetaLength = Math.PI * 2;
21385 _this = _CylinderGeometry.call(this, 0, radius, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength) || this;
21386 _this.type = 'ConeGeometry';
21387 _this.parameters = {
21390 radialSegments: radialSegments,
21391 heightSegments: heightSegments,
21392 openEnded: openEnded,
21393 thetaStart: thetaStart,
21394 thetaLength: thetaLength
21399 return ConeGeometry;
21400 }(CylinderGeometry);
21402 var PolyhedronGeometry = /*#__PURE__*/function (_BufferGeometry) {
21403 _inheritsLoose(PolyhedronGeometry, _BufferGeometry);
21405 function PolyhedronGeometry(vertices, indices, radius, detail) {
21408 if (radius === void 0) {
21412 if (detail === void 0) {
21416 _this = _BufferGeometry.call(this) || this;
21417 _this.type = 'PolyhedronGeometry';
21418 _this.parameters = {
21419 vertices: vertices,
21423 }; // default buffer data
21425 var vertexBuffer = [];
21426 var uvBuffer = []; // the subdivision creates the vertex buffer data
21428 subdivide(detail); // all vertices should lie on a conceptual sphere with a given radius
21430 applyRadius(radius); // finally, create the uv data
21432 generateUVs(); // build non-indexed geometry
21434 _this.setAttribute('position', new Float32BufferAttribute(vertexBuffer, 3));
21436 _this.setAttribute('normal', new Float32BufferAttribute(vertexBuffer.slice(), 3));
21438 _this.setAttribute('uv', new Float32BufferAttribute(uvBuffer, 2));
21440 if (detail === 0) {
21441 _this.computeVertexNormals(); // flat normals
21444 _this.normalizeNormals(); // smooth normals
21446 } // helper functions
21449 function subdivide(detail) {
21450 var a = new Vector3();
21451 var b = new Vector3();
21452 var c = new Vector3(); // iterate over all faces and apply a subdivison with the given detail value
21454 for (var i = 0; i < indices.length; i += 3) {
21455 // get the vertices of the face
21456 getVertexByIndex(indices[i + 0], a);
21457 getVertexByIndex(indices[i + 1], b);
21458 getVertexByIndex(indices[i + 2], c); // perform subdivision
21460 subdivideFace(a, b, c, detail);
21464 function subdivideFace(a, b, c, detail) {
21465 var cols = detail + 1; // we use this multidimensional array as a data structure for creating the subdivision
21467 var v = []; // construct all of the vertices for this subdivision
21469 for (var i = 0; i <= cols; i++) {
21471 var aj = a.clone().lerp(c, i / cols);
21472 var bj = b.clone().lerp(c, i / cols);
21473 var rows = cols - i;
21475 for (var j = 0; j <= rows; j++) {
21476 if (j === 0 && i === cols) {
21479 v[i][j] = aj.clone().lerp(bj, j / rows);
21482 } // construct all of the faces
21485 for (var _i = 0; _i < cols; _i++) {
21486 for (var _j = 0; _j < 2 * (cols - _i) - 1; _j++) {
21487 var k = Math.floor(_j / 2);
21489 if (_j % 2 === 0) {
21490 pushVertex(v[_i][k + 1]);
21491 pushVertex(v[_i + 1][k]);
21492 pushVertex(v[_i][k]);
21494 pushVertex(v[_i][k + 1]);
21495 pushVertex(v[_i + 1][k + 1]);
21496 pushVertex(v[_i + 1][k]);
21502 function applyRadius(radius) {
21503 var vertex = new Vector3(); // iterate over the entire buffer and apply the radius to each vertex
21505 for (var i = 0; i < vertexBuffer.length; i += 3) {
21506 vertex.x = vertexBuffer[i + 0];
21507 vertex.y = vertexBuffer[i + 1];
21508 vertex.z = vertexBuffer[i + 2];
21509 vertex.normalize().multiplyScalar(radius);
21510 vertexBuffer[i + 0] = vertex.x;
21511 vertexBuffer[i + 1] = vertex.y;
21512 vertexBuffer[i + 2] = vertex.z;
21516 function generateUVs() {
21517 var vertex = new Vector3();
21519 for (var i = 0; i < vertexBuffer.length; i += 3) {
21520 vertex.x = vertexBuffer[i + 0];
21521 vertex.y = vertexBuffer[i + 1];
21522 vertex.z = vertexBuffer[i + 2];
21523 var u = azimuth(vertex) / 2 / Math.PI + 0.5;
21524 var v = inclination(vertex) / Math.PI + 0.5;
21525 uvBuffer.push(u, 1 - v);
21532 function correctSeam() {
21533 // handle case when face straddles the seam, see #3269
21534 for (var i = 0; i < uvBuffer.length; i += 6) {
21535 // uv data of a single face
21536 var x0 = uvBuffer[i + 0];
21537 var x1 = uvBuffer[i + 2];
21538 var x2 = uvBuffer[i + 4];
21539 var max = Math.max(x0, x1, x2);
21540 var min = Math.min(x0, x1, x2); // 0.9 is somewhat arbitrary
21542 if (max > 0.9 && min < 0.1) {
21543 if (x0 < 0.2) uvBuffer[i + 0] += 1;
21544 if (x1 < 0.2) uvBuffer[i + 2] += 1;
21545 if (x2 < 0.2) uvBuffer[i + 4] += 1;
21550 function pushVertex(vertex) {
21551 vertexBuffer.push(vertex.x, vertex.y, vertex.z);
21554 function getVertexByIndex(index, vertex) {
21555 var stride = index * 3;
21556 vertex.x = vertices[stride + 0];
21557 vertex.y = vertices[stride + 1];
21558 vertex.z = vertices[stride + 2];
21561 function correctUVs() {
21562 var a = new Vector3();
21563 var b = new Vector3();
21564 var c = new Vector3();
21565 var centroid = new Vector3();
21566 var uvA = new Vector2();
21567 var uvB = new Vector2();
21568 var uvC = new Vector2();
21570 for (var i = 0, j = 0; i < vertexBuffer.length; i += 9, j += 6) {
21571 a.set(vertexBuffer[i + 0], vertexBuffer[i + 1], vertexBuffer[i + 2]);
21572 b.set(vertexBuffer[i + 3], vertexBuffer[i + 4], vertexBuffer[i + 5]);
21573 c.set(vertexBuffer[i + 6], vertexBuffer[i + 7], vertexBuffer[i + 8]);
21574 uvA.set(uvBuffer[j + 0], uvBuffer[j + 1]);
21575 uvB.set(uvBuffer[j + 2], uvBuffer[j + 3]);
21576 uvC.set(uvBuffer[j + 4], uvBuffer[j + 5]);
21577 centroid.copy(a).add(b).add(c).divideScalar(3);
21578 var azi = azimuth(centroid);
21579 correctUV(uvA, j + 0, a, azi);
21580 correctUV(uvB, j + 2, b, azi);
21581 correctUV(uvC, j + 4, c, azi);
21585 function correctUV(uv, stride, vector, azimuth) {
21586 if (azimuth < 0 && uv.x === 1) {
21587 uvBuffer[stride] = uv.x - 1;
21590 if (vector.x === 0 && vector.z === 0) {
21591 uvBuffer[stride] = azimuth / 2 / Math.PI + 0.5;
21593 } // Angle around the Y axis, counter-clockwise when looking from above.
21596 function azimuth(vector) {
21597 return Math.atan2(vector.z, -vector.x);
21598 } // Angle above the XZ plane.
21601 function inclination(vector) {
21602 return Math.atan2(-vector.y, Math.sqrt(vector.x * vector.x + vector.z * vector.z));
21608 return PolyhedronGeometry;
21611 var DodecahedronGeometry = /*#__PURE__*/function (_PolyhedronGeometry) {
21612 _inheritsLoose(DodecahedronGeometry, _PolyhedronGeometry);
21614 function DodecahedronGeometry(radius, detail) {
21617 if (radius === void 0) {
21621 if (detail === void 0) {
21625 var t = (1 + Math.sqrt(5)) / 2;
21627 var vertices = [// (±1, ±1, ±1)
21628 -1, -1, -1, -1, -1, 1, -1, 1, -1, -1, 1, 1, 1, -1, -1, 1, -1, 1, 1, 1, -1, 1, 1, 1, // (0, ±1/φ, ±φ)
21629 0, -r, -t, 0, -r, t, 0, r, -t, 0, r, t, // (±1/φ, ±φ, 0)
21630 -r, -t, 0, -r, t, 0, r, -t, 0, r, t, 0, // (±φ, 0, ±1/φ)
21631 -t, 0, -r, t, 0, -r, -t, 0, r, t, 0, r];
21632 var indices = [3, 11, 7, 3, 7, 15, 3, 15, 13, 7, 19, 17, 7, 17, 6, 7, 6, 15, 17, 4, 8, 17, 8, 10, 17, 10, 6, 8, 0, 16, 8, 16, 2, 8, 2, 10, 0, 12, 1, 0, 1, 18, 0, 18, 16, 6, 10, 2, 6, 2, 13, 6, 13, 15, 2, 16, 18, 2, 18, 3, 2, 3, 13, 18, 1, 9, 18, 9, 11, 18, 11, 3, 4, 14, 12, 4, 12, 0, 4, 0, 8, 11, 9, 5, 11, 5, 19, 11, 19, 7, 19, 5, 14, 19, 14, 4, 19, 4, 17, 1, 12, 14, 1, 14, 5, 1, 5, 9];
21633 _this = _PolyhedronGeometry.call(this, vertices, indices, radius, detail) || this;
21634 _this.type = 'DodecahedronGeometry';
21635 _this.parameters = {
21642 return DodecahedronGeometry;
21643 }(PolyhedronGeometry);
21645 var _v0$2 = new Vector3();
21647 var _v1$5 = new Vector3();
21649 var _normal$1 = new Vector3();
21651 var _triangle = new Triangle();
21653 var EdgesGeometry = /*#__PURE__*/function (_BufferGeometry) {
21654 _inheritsLoose(EdgesGeometry, _BufferGeometry);
21656 function EdgesGeometry(geometry, thresholdAngle) {
21659 _this = _BufferGeometry.call(this) || this;
21660 _this.type = 'EdgesGeometry';
21661 _this.parameters = {
21662 thresholdAngle: thresholdAngle
21664 thresholdAngle = thresholdAngle !== undefined ? thresholdAngle : 1;
21666 if (geometry.isGeometry === true) {
21667 console.error('THREE.EdgesGeometry no longer supports THREE.Geometry. Use THREE.BufferGeometry instead.');
21668 return _assertThisInitialized(_this);
21671 var precisionPoints = 4;
21672 var precision = Math.pow(10, precisionPoints);
21673 var thresholdDot = Math.cos(MathUtils.DEG2RAD * thresholdAngle);
21674 var indexAttr = geometry.getIndex();
21675 var positionAttr = geometry.getAttribute('position');
21676 var indexCount = indexAttr ? indexAttr.count : positionAttr.count;
21677 var indexArr = [0, 0, 0];
21678 var vertKeys = ['a', 'b', 'c'];
21679 var hashes = new Array(3);
21683 for (var i = 0; i < indexCount; i += 3) {
21685 indexArr[0] = indexAttr.getX(i);
21686 indexArr[1] = indexAttr.getX(i + 1);
21687 indexArr[2] = indexAttr.getX(i + 2);
21690 indexArr[1] = i + 1;
21691 indexArr[2] = i + 2;
21694 var a = _triangle.a,
21697 a.fromBufferAttribute(positionAttr, indexArr[0]);
21698 b.fromBufferAttribute(positionAttr, indexArr[1]);
21699 c.fromBufferAttribute(positionAttr, indexArr[2]);
21701 _triangle.getNormal(_normal$1); // create hashes for the edge from the vertices
21704 hashes[0] = Math.round(a.x * precision) + "," + Math.round(a.y * precision) + "," + Math.round(a.z * precision);
21705 hashes[1] = Math.round(b.x * precision) + "," + Math.round(b.y * precision) + "," + Math.round(b.z * precision);
21706 hashes[2] = Math.round(c.x * precision) + "," + Math.round(c.y * precision) + "," + Math.round(c.z * precision); // skip degenerate triangles
21708 if (hashes[0] === hashes[1] || hashes[1] === hashes[2] || hashes[2] === hashes[0]) {
21710 } // iterate over every edge
21713 for (var j = 0; j < 3; j++) {
21714 // get the first and next vertex making up the edge
21715 var jNext = (j + 1) % 3;
21716 var vecHash0 = hashes[j];
21717 var vecHash1 = hashes[jNext];
21718 var v0 = _triangle[vertKeys[j]];
21719 var v1 = _triangle[vertKeys[jNext]];
21720 var hash = vecHash0 + "_" + vecHash1;
21721 var reverseHash = vecHash1 + "_" + vecHash0;
21723 if (reverseHash in edgeData && edgeData[reverseHash]) {
21724 // if we found a sibling edge add it into the vertex array if
21725 // it meets the angle threshold and delete the edge from the map.
21726 if (_normal$1.dot(edgeData[reverseHash].normal) <= thresholdDot) {
21727 vertices.push(v0.x, v0.y, v0.z);
21728 vertices.push(v1.x, v1.y, v1.z);
21731 edgeData[reverseHash] = null;
21732 } else if (!(hash in edgeData)) {
21733 // if we've already got an edge here then skip adding a new one
21735 index0: indexArr[j],
21736 index1: indexArr[jNext],
21737 normal: _normal$1.clone()
21741 } // iterate over all remaining, unmatched edges and add them to the vertex array
21744 for (var key in edgeData) {
21745 if (edgeData[key]) {
21746 var _edgeData$key = edgeData[key],
21747 index0 = _edgeData$key.index0,
21748 index1 = _edgeData$key.index1;
21750 _v0$2.fromBufferAttribute(positionAttr, index0);
21752 _v1$5.fromBufferAttribute(positionAttr, index1);
21754 vertices.push(_v0$2.x, _v0$2.y, _v0$2.z);
21755 vertices.push(_v1$5.x, _v1$5.y, _v1$5.z);
21759 _this.setAttribute('position', new Float32BufferAttribute(vertices, 3));
21764 return EdgesGeometry;
21768 * Port from https://github.com/mapbox/earcut (v2.2.2)
21771 triangulate: function triangulate(data, holeIndices, dim) {
21773 var hasHoles = holeIndices && holeIndices.length;
21774 var outerLen = hasHoles ? holeIndices[0] * dim : data.length;
21775 var outerNode = linkedList(data, 0, outerLen, dim, true);
21776 var triangles = [];
21777 if (!outerNode || outerNode.next === outerNode.prev) return triangles;
21778 var minX, minY, maxX, maxY, x, y, invSize;
21779 if (hasHoles) outerNode = eliminateHoles(data, holeIndices, outerNode, dim); // if the shape is not too simple, we'll use z-order curve hash later; calculate polygon bbox
21781 if (data.length > 80 * dim) {
21782 minX = maxX = data[0];
21783 minY = maxY = data[1];
21785 for (var i = dim; i < outerLen; i += dim) {
21788 if (x < minX) minX = x;
21789 if (y < minY) minY = y;
21790 if (x > maxX) maxX = x;
21791 if (y > maxY) maxY = y;
21792 } // minX, minY and invSize are later used to transform coords into integers for z-order calculation
21795 invSize = Math.max(maxX - minX, maxY - minY);
21796 invSize = invSize !== 0 ? 1 / invSize : 0;
21799 earcutLinked(outerNode, triangles, dim, minX, minY, invSize);
21802 }; // create a circular doubly linked list from polygon points in the specified winding order
21804 function linkedList(data, start, end, dim, clockwise) {
21807 if (clockwise === signedArea(data, start, end, dim) > 0) {
21808 for (i = start; i < end; i += dim) {
21809 last = insertNode(i, data[i], data[i + 1], last);
21812 for (i = end - dim; i >= start; i -= dim) {
21813 last = insertNode(i, data[i], data[i + 1], last);
21817 if (last && equals(last, last.next)) {
21823 } // eliminate colinear or duplicate points
21826 function filterPoints(start, end) {
21827 if (!start) return start;
21828 if (!end) end = start;
21835 if (!p.steiner && (equals(p, p.next) || area(p.prev, p, p.next) === 0)) {
21838 if (p === p.next) break;
21843 } while (again || p !== end);
21846 } // main ear slicing loop which triangulates a polygon (given as a linked list)
21849 function earcutLinked(ear, triangles, dim, minX, minY, invSize, pass) {
21850 if (!ear) return; // interlink polygon nodes in z-order
21852 if (!pass && invSize) indexCurve(ear, minX, minY, invSize);
21855 next; // iterate through ears, slicing them one by one
21857 while (ear.prev !== ear.next) {
21861 if (invSize ? isEarHashed(ear, minX, minY, invSize) : isEar(ear)) {
21862 // cut off the triangle
21863 triangles.push(prev.i / dim);
21864 triangles.push(ear.i / dim);
21865 triangles.push(next.i / dim);
21866 removeNode(ear); // skipping the next vertex leads to less sliver triangles
21873 ear = next; // if we looped through the whole remaining polygon and can't find any more ears
21875 if (ear === stop) {
21876 // try filtering points and slicing again
21878 earcutLinked(filterPoints(ear), triangles, dim, minX, minY, invSize, 1); // if this didn't work, try curing all small self-intersections locally
21879 } else if (pass === 1) {
21880 ear = cureLocalIntersections(filterPoints(ear), triangles, dim);
21881 earcutLinked(ear, triangles, dim, minX, minY, invSize, 2); // as a last resort, try splitting the remaining polygon into two
21882 } else if (pass === 2) {
21883 splitEarcut(ear, triangles, dim, minX, minY, invSize);
21889 } // check whether a polygon node forms a valid ear with adjacent nodes
21892 function isEar(ear) {
21896 if (area(a, b, c) >= 0) return false; // reflex, can't be an ear
21897 // now make sure we don't have other points inside the potential ear
21899 var p = ear.next.next;
21901 while (p !== ear.prev) {
21902 if (pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) && area(p.prev, p, p.next) >= 0) return false;
21909 function isEarHashed(ear, minX, minY, invSize) {
21913 if (area(a, b, c) >= 0) return false; // reflex, can't be an ear
21914 // triangle bbox; min & max are calculated like this for speed
21916 var minTX = a.x < b.x ? a.x < c.x ? a.x : c.x : b.x < c.x ? b.x : c.x,
21917 minTY = a.y < b.y ? a.y < c.y ? a.y : c.y : b.y < c.y ? b.y : c.y,
21918 maxTX = a.x > b.x ? a.x > c.x ? a.x : c.x : b.x > c.x ? b.x : c.x,
21919 maxTY = a.y > b.y ? a.y > c.y ? a.y : c.y : b.y > c.y ? b.y : c.y; // z-order range for the current triangle bbox;
21921 var minZ = zOrder(minTX, minTY, minX, minY, invSize),
21922 maxZ = zOrder(maxTX, maxTY, minX, minY, invSize);
21924 n = ear.nextZ; // look for points inside the triangle in both directions
21926 while (p && p.z >= minZ && n && n.z <= maxZ) {
21927 if (p !== ear.prev && p !== ear.next && pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) && area(p.prev, p, p.next) >= 0) return false;
21929 if (n !== ear.prev && n !== ear.next && pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, n.x, n.y) && area(n.prev, n, n.next) >= 0) return false;
21931 } // look for remaining points in decreasing z-order
21934 while (p && p.z >= minZ) {
21935 if (p !== ear.prev && p !== ear.next && pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) && area(p.prev, p, p.next) >= 0) return false;
21937 } // look for remaining points in increasing z-order
21940 while (n && n.z <= maxZ) {
21941 if (n !== ear.prev && n !== ear.next && pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, n.x, n.y) && area(n.prev, n, n.next) >= 0) return false;
21946 } // go through all polygon nodes and cure small local self-intersections
21949 function cureLocalIntersections(start, triangles, dim) {
21956 if (!equals(a, b) && intersects(a, p, p.next, b) && locallyInside(a, b) && locallyInside(b, a)) {
21957 triangles.push(a.i / dim);
21958 triangles.push(p.i / dim);
21959 triangles.push(b.i / dim); // remove two nodes involved
21962 removeNode(p.next);
21967 } while (p !== start);
21969 return filterPoints(p);
21970 } // try splitting polygon into two and triangulate them independently
21973 function splitEarcut(start, triangles, dim, minX, minY, invSize) {
21974 // look for a valid diagonal that divides the polygon into two
21978 var b = a.next.next;
21980 while (b !== a.prev) {
21981 if (a.i !== b.i && isValidDiagonal(a, b)) {
21982 // split the polygon in two by the diagonal
21983 var c = splitPolygon(a, b); // filter colinear points around the cuts
21985 a = filterPoints(a, a.next);
21986 c = filterPoints(c, c.next); // run earcut on each half
21988 earcutLinked(a, triangles, dim, minX, minY, invSize);
21989 earcutLinked(c, triangles, dim, minX, minY, invSize);
21997 } while (a !== start);
21998 } // link every hole into the outer loop, producing a single-ring polygon without holes
22001 function eliminateHoles(data, holeIndices, outerNode, dim) {
22003 var i, len, start, end, list;
22005 for (i = 0, len = holeIndices.length; i < len; i++) {
22006 start = holeIndices[i] * dim;
22007 end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
22008 list = linkedList(data, start, end, dim, false);
22009 if (list === list.next) list.steiner = true;
22010 queue.push(getLeftmost(list));
22013 queue.sort(compareX); // process holes from left to right
22015 for (i = 0; i < queue.length; i++) {
22016 eliminateHole(queue[i], outerNode);
22017 outerNode = filterPoints(outerNode, outerNode.next);
22023 function compareX(a, b) {
22025 } // find a bridge between vertices that connects hole with an outer ring and and link it
22028 function eliminateHole(hole, outerNode) {
22029 outerNode = findHoleBridge(hole, outerNode);
22032 var b = splitPolygon(outerNode, hole); // filter collinear points around the cuts
22034 filterPoints(outerNode, outerNode.next);
22035 filterPoints(b, b.next);
22037 } // David Eberly's algorithm for finding a bridge between hole and outer polygon
22040 function findHoleBridge(hole, outerNode) {
22044 var qx = -Infinity,
22045 m; // find a segment intersected by a ray from the hole's leftmost point to the left;
22046 // segment's endpoint with lesser x will be potential connection point
22049 if (hy <= p.y && hy >= p.next.y && p.next.y !== p.y) {
22050 var x = p.x + (hy - p.y) * (p.next.x - p.x) / (p.next.y - p.y);
22052 if (x <= hx && x > qx) {
22056 if (hy === p.y) return p;
22057 if (hy === p.next.y) return p.next;
22060 m = p.x < p.next.x ? p : p.next;
22065 } while (p !== outerNode);
22067 if (!m) return null;
22068 if (hx === qx) return m; // hole touches outer segment; pick leftmost endpoint
22069 // look for points inside the triangle of hole point, segment intersection and endpoint;
22070 // if there are no points found, we have a valid connection;
22071 // otherwise choose the point of the minimum angle with the ray as connection point
22076 var tanMin = Infinity,
22081 if (hx >= p.x && p.x >= mx && hx !== p.x && pointInTriangle(hy < my ? hx : qx, hy, mx, my, hy < my ? qx : hx, hy, p.x, p.y)) {
22082 tan = Math.abs(hy - p.y) / (hx - p.x); // tangential
22084 if (locallyInside(p, hole) && (tan < tanMin || tan === tanMin && (p.x > m.x || p.x === m.x && sectorContainsSector(m, p)))) {
22091 } while (p !== stop);
22094 } // whether sector in vertex m contains sector in vertex p in the same coordinates
22097 function sectorContainsSector(m, p) {
22098 return area(m.prev, m, p.prev) < 0 && area(p.next, m, m.next) < 0;
22099 } // interlink polygon nodes in z-order
22102 function indexCurve(start, minX, minY, invSize) {
22106 if (p.z === null) p.z = zOrder(p.x, p.y, minX, minY, invSize);
22110 } while (p !== start);
22112 p.prevZ.nextZ = null;
22115 } // Simon Tatham's linked list merge sort algorithm
22116 // http://www.chiark.greenend.org.uk/~sgtatham/algorithms/listsort.html
22119 function sortLinked(list) {
22141 for (i = 0; i < inSize; i++) {
22149 while (pSize > 0 || qSize > 0 && q) {
22150 if (pSize !== 0 && (qSize === 0 || !q || p.z <= q.z)) {
22160 if (tail) tail.nextZ = e;else list = e;
22170 } while (numMerges > 1);
22173 } // z-order of a point given coords and inverse of the longer side of data bbox
22176 function zOrder(x, y, minX, minY, invSize) {
22177 // coords are transformed into non-negative 15-bit integer range
22178 x = 32767 * (x - minX) * invSize;
22179 y = 32767 * (y - minY) * invSize;
22180 x = (x | x << 8) & 0x00FF00FF;
22181 x = (x | x << 4) & 0x0F0F0F0F;
22182 x = (x | x << 2) & 0x33333333;
22183 x = (x | x << 1) & 0x55555555;
22184 y = (y | y << 8) & 0x00FF00FF;
22185 y = (y | y << 4) & 0x0F0F0F0F;
22186 y = (y | y << 2) & 0x33333333;
22187 y = (y | y << 1) & 0x55555555;
22189 } // find the leftmost node of a polygon ring
22192 function getLeftmost(start) {
22197 if (p.x < leftmost.x || p.x === leftmost.x && p.y < leftmost.y) leftmost = p;
22199 } while (p !== start);
22202 } // check if a point lies within a convex triangle
22205 function pointInTriangle(ax, ay, bx, by, cx, cy, px, py) {
22206 return (cx - px) * (ay - py) - (ax - px) * (cy - py) >= 0 && (ax - px) * (by - py) - (bx - px) * (ay - py) >= 0 && (bx - px) * (cy - py) - (cx - px) * (by - py) >= 0;
22207 } // check if a diagonal between two polygon nodes is valid (lies in polygon interior)
22210 function isValidDiagonal(a, b) {
22211 return a.next.i !== b.i && a.prev.i !== b.i && !intersectsPolygon(a, b) && ( // dones't intersect other edges
22212 locallyInside(a, b) && locallyInside(b, a) && middleInside(a, b) && ( // locally visible
22213 area(a.prev, a, b.prev) || area(a, b.prev, b)) || // does not create opposite-facing sectors
22214 equals(a, b) && area(a.prev, a, a.next) > 0 && area(b.prev, b, b.next) > 0); // special zero-length case
22215 } // signed area of a triangle
22218 function area(p, q, r) {
22219 return (q.y - p.y) * (r.x - q.x) - (q.x - p.x) * (r.y - q.y);
22220 } // check if two points are equal
22223 function equals(p1, p2) {
22224 return p1.x === p2.x && p1.y === p2.y;
22225 } // check if two segments intersect
22228 function intersects(p1, q1, p2, q2) {
22229 var o1 = sign(area(p1, q1, p2));
22230 var o2 = sign(area(p1, q1, q2));
22231 var o3 = sign(area(p2, q2, p1));
22232 var o4 = sign(area(p2, q2, q1));
22233 if (o1 !== o2 && o3 !== o4) return true; // general case
22235 if (o1 === 0 && onSegment(p1, p2, q1)) return true; // p1, q1 and p2 are collinear and p2 lies on p1q1
22237 if (o2 === 0 && onSegment(p1, q2, q1)) return true; // p1, q1 and q2 are collinear and q2 lies on p1q1
22239 if (o3 === 0 && onSegment(p2, p1, q2)) return true; // p2, q2 and p1 are collinear and p1 lies on p2q2
22241 if (o4 === 0 && onSegment(p2, q1, q2)) return true; // p2, q2 and q1 are collinear and q1 lies on p2q2
22244 } // for collinear points p, q, r, check if point q lies on segment pr
22247 function onSegment(p, q, r) {
22248 return q.x <= Math.max(p.x, r.x) && q.x >= Math.min(p.x, r.x) && q.y <= Math.max(p.y, r.y) && q.y >= Math.min(p.y, r.y);
22251 function sign(num) {
22252 return num > 0 ? 1 : num < 0 ? -1 : 0;
22253 } // check if a polygon diagonal intersects any polygon segments
22256 function intersectsPolygon(a, b) {
22260 if (p.i !== a.i && p.next.i !== a.i && p.i !== b.i && p.next.i !== b.i && intersects(p, p.next, a, b)) return true;
22265 } // check if a polygon diagonal is locally inside the polygon
22268 function locallyInside(a, b) {
22269 return area(a.prev, a, a.next) < 0 ? area(a, b, a.next) >= 0 && area(a, a.prev, b) >= 0 : area(a, b, a.prev) < 0 || area(a, a.next, b) < 0;
22270 } // check if the middle point of a polygon diagonal is inside the polygon
22273 function middleInside(a, b) {
22276 var px = (a.x + b.x) / 2,
22277 py = (a.y + b.y) / 2;
22280 if (p.y > py !== p.next.y > py && p.next.y !== p.y && px < (p.next.x - p.x) * (py - p.y) / (p.next.y - p.y) + p.x) inside = !inside;
22285 } // link two polygon vertices with a bridge; if the vertices belong to the same ring, it splits polygon into two;
22286 // if one belongs to the outer ring and another to a hole, it merges it into a single ring
22289 function splitPolygon(a, b) {
22290 var a2 = new Node(a.i, a.x, a.y),
22291 b2 = new Node(b.i, b.x, b.y),
22303 } // create a node and optionally link it with previous one (in a circular doubly linked list)
22306 function insertNode(i, x, y, last) {
22307 var p = new Node(i, x, y);
22313 p.next = last.next;
22315 last.next.prev = p;
22322 function removeNode(p) {
22323 p.next.prev = p.prev;
22324 p.prev.next = p.next;
22325 if (p.prevZ) p.prevZ.nextZ = p.nextZ;
22326 if (p.nextZ) p.nextZ.prevZ = p.prevZ;
22329 function Node(i, x, y) {
22330 // vertex index in coordinates array
22331 this.i = i; // vertex coordinates
22334 this.y = y; // previous and next vertex nodes in a polygon ring
22337 this.next = null; // z-order curve value
22339 this.z = null; // previous and next nodes in z-order
22342 this.nextZ = null; // indicates whether this is a steiner point
22344 this.steiner = false;
22347 function signedArea(data, start, end, dim) {
22350 for (var i = start, j = end - dim; i < end; i += dim) {
22351 sum += (data[j] - data[i]) * (data[i + 1] + data[j + 1]);
22359 // calculate area of the contour polygon
22360 area: function area(contour) {
22361 var n = contour.length;
22364 for (var p = n - 1, q = 0; q < n; p = q++) {
22365 a += contour[p].x * contour[q].y - contour[q].x * contour[p].y;
22370 isClockWise: function isClockWise(pts) {
22371 return ShapeUtils.area(pts) < 0;
22373 triangulateShape: function triangulateShape(contour, holes) {
22374 var vertices = []; // flat array of vertices like [ x0,y0, x1,y1, x2,y2, ... ]
22376 var holeIndices = []; // array of hole indices
22378 var faces = []; // final array of vertex indices like [ [ a,b,d ], [ b,c,d ] ]
22380 removeDupEndPts(contour);
22381 addContour(vertices, contour); //
22383 var holeIndex = contour.length;
22384 holes.forEach(removeDupEndPts);
22386 for (var i = 0; i < holes.length; i++) {
22387 holeIndices.push(holeIndex);
22388 holeIndex += holes[i].length;
22389 addContour(vertices, holes[i]);
22393 var triangles = Earcut.triangulate(vertices, holeIndices); //
22395 for (var _i = 0; _i < triangles.length; _i += 3) {
22396 faces.push(triangles.slice(_i, _i + 3));
22403 function removeDupEndPts(points) {
22404 var l = points.length;
22406 if (l > 2 && points[l - 1].equals(points[0])) {
22411 function addContour(vertices, contour) {
22412 for (var i = 0; i < contour.length; i++) {
22413 vertices.push(contour[i].x);
22414 vertices.push(contour[i].y);
22418 var ExtrudeGeometry = /*#__PURE__*/function (_BufferGeometry) {
22419 _inheritsLoose(ExtrudeGeometry, _BufferGeometry);
22421 function ExtrudeGeometry(shapes, options) {
22424 _this = _BufferGeometry.call(this) || this;
22425 _this.type = 'ExtrudeGeometry';
22426 _this.parameters = {
22430 shapes = Array.isArray(shapes) ? shapes : [shapes];
22432 var scope = _assertThisInitialized(_this);
22434 var verticesArray = [];
22437 for (var i = 0, l = shapes.length; i < l; i++) {
22438 var shape = shapes[i];
22440 } // build geometry
22443 _this.setAttribute('position', new Float32BufferAttribute(verticesArray, 3));
22445 _this.setAttribute('uv', new Float32BufferAttribute(uvArray, 2));
22447 _this.computeVertexNormals(); // functions
22450 function addShape(shape) {
22451 var placeholder = []; // options
22453 var curveSegments = options.curveSegments !== undefined ? options.curveSegments : 12;
22454 var steps = options.steps !== undefined ? options.steps : 1;
22455 var depth = options.depth !== undefined ? options.depth : 100;
22456 var bevelEnabled = options.bevelEnabled !== undefined ? options.bevelEnabled : true;
22457 var bevelThickness = options.bevelThickness !== undefined ? options.bevelThickness : 6;
22458 var bevelSize = options.bevelSize !== undefined ? options.bevelSize : bevelThickness - 2;
22459 var bevelOffset = options.bevelOffset !== undefined ? options.bevelOffset : 0;
22460 var bevelSegments = options.bevelSegments !== undefined ? options.bevelSegments : 3;
22461 var extrudePath = options.extrudePath;
22462 var uvgen = options.UVGenerator !== undefined ? options.UVGenerator : WorldUVGenerator; // deprecated options
22464 if (options.amount !== undefined) {
22465 console.warn('THREE.ExtrudeBufferGeometry: amount has been renamed to depth.');
22466 depth = options.amount;
22471 extrudeByPath = false;
22472 var splineTube, binormal, normal, position2;
22475 extrudePts = extrudePath.getSpacedPoints(steps);
22476 extrudeByPath = true;
22477 bevelEnabled = false; // bevels not supported for path extrusion
22478 // SETUP TNB variables
22479 // TODO1 - have a .isClosed in spline?
22481 splineTube = extrudePath.computeFrenetFrames(steps, false); // console.log(splineTube, 'splineTube', splineTube.normals.length, 'steps', steps, 'extrudePts', extrudePts.length);
22483 binormal = new Vector3();
22484 normal = new Vector3();
22485 position2 = new Vector3();
22486 } // Safeguards if bevels are not enabled
22489 if (!bevelEnabled) {
22491 bevelThickness = 0;
22494 } // Variables initialization
22497 var shapePoints = shape.extractPoints(curveSegments);
22498 var vertices = shapePoints.shape;
22499 var holes = shapePoints.holes;
22500 var reverse = !ShapeUtils.isClockWise(vertices);
22503 vertices = vertices.reverse(); // Maybe we should also check if holes are in the opposite direction, just to be safe ...
22505 for (var h = 0, hl = holes.length; h < hl; h++) {
22506 var ahole = holes[h];
22508 if (ShapeUtils.isClockWise(ahole)) {
22509 holes[h] = ahole.reverse();
22514 var faces = ShapeUtils.triangulateShape(vertices, holes);
22517 var contour = vertices; // vertices has all points but contour has only points of circumference
22519 for (var _h = 0, _hl = holes.length; _h < _hl; _h++) {
22520 var _ahole = holes[_h];
22521 vertices = vertices.concat(_ahole);
22524 function scalePt2(pt, vec, size) {
22525 if (!vec) console.error('THREE.ExtrudeGeometry: vec does not exist');
22526 return vec.clone().multiplyScalar(size).add(pt);
22529 var vlen = vertices.length,
22530 flen = faces.length; // Find directions for point movement
22532 function getBevelVec(inPt, inPrev, inNext) {
22533 // computes for inPt the corresponding point inPt' on a new contour
22534 // shifted by 1 unit (length of normalized vector) to the left
22535 // if we walk along contour clockwise, this new contour is outside the old one
22537 // inPt' is the intersection of the two lines parallel to the two
22538 // adjacent edges of inPt at a distance of 1 unit on the left side.
22539 var v_trans_x, v_trans_y, shrink_by; // resulting translation vector for inPt
22540 // good reading for geometry algorithms (here: line-line intersection)
22541 // http://geomalgorithms.com/a05-_intersect-1.html
22543 var v_prev_x = inPt.x - inPrev.x,
22544 v_prev_y = inPt.y - inPrev.y;
22545 var v_next_x = inNext.x - inPt.x,
22546 v_next_y = inNext.y - inPt.y;
22547 var v_prev_lensq = v_prev_x * v_prev_x + v_prev_y * v_prev_y; // check for collinear edges
22549 var collinear0 = v_prev_x * v_next_y - v_prev_y * v_next_x;
22551 if (Math.abs(collinear0) > Number.EPSILON) {
22553 // length of vectors for normalizing
22554 var v_prev_len = Math.sqrt(v_prev_lensq);
22555 var v_next_len = Math.sqrt(v_next_x * v_next_x + v_next_y * v_next_y); // shift adjacent points by unit vectors to the left
22557 var ptPrevShift_x = inPrev.x - v_prev_y / v_prev_len;
22558 var ptPrevShift_y = inPrev.y + v_prev_x / v_prev_len;
22559 var ptNextShift_x = inNext.x - v_next_y / v_next_len;
22560 var ptNextShift_y = inNext.y + v_next_x / v_next_len; // scaling factor for v_prev to intersection point
22562 var sf = ((ptNextShift_x - ptPrevShift_x) * v_next_y - (ptNextShift_y - ptPrevShift_y) * v_next_x) / (v_prev_x * v_next_y - v_prev_y * v_next_x); // vector from inPt to intersection point
22564 v_trans_x = ptPrevShift_x + v_prev_x * sf - inPt.x;
22565 v_trans_y = ptPrevShift_y + v_prev_y * sf - inPt.y; // Don't normalize!, otherwise sharp corners become ugly
22566 // but prevent crazy spikes
22568 var v_trans_lensq = v_trans_x * v_trans_x + v_trans_y * v_trans_y;
22570 if (v_trans_lensq <= 2) {
22571 return new Vector2(v_trans_x, v_trans_y);
22573 shrink_by = Math.sqrt(v_trans_lensq / 2);
22576 // handle special case of collinear edges
22577 var direction_eq = false; // assumes: opposite
22579 if (v_prev_x > Number.EPSILON) {
22580 if (v_next_x > Number.EPSILON) {
22581 direction_eq = true;
22584 if (v_prev_x < -Number.EPSILON) {
22585 if (v_next_x < -Number.EPSILON) {
22586 direction_eq = true;
22589 if (Math.sign(v_prev_y) === Math.sign(v_next_y)) {
22590 direction_eq = true;
22595 if (direction_eq) {
22596 // console.log("Warning: lines are a straight sequence");
22597 v_trans_x = -v_prev_y;
22598 v_trans_y = v_prev_x;
22599 shrink_by = Math.sqrt(v_prev_lensq);
22601 // console.log("Warning: lines are a straight spike");
22602 v_trans_x = v_prev_x;
22603 v_trans_y = v_prev_y;
22604 shrink_by = Math.sqrt(v_prev_lensq / 2);
22608 return new Vector2(v_trans_x / shrink_by, v_trans_y / shrink_by);
22611 var contourMovements = [];
22613 for (var _i = 0, il = contour.length, j = il - 1, k = _i + 1; _i < il; _i++, j++, k++) {
22614 if (j === il) j = 0;
22615 if (k === il) k = 0; // (j)---(i)---(k)
22616 // console.log('i,j,k', i, j , k)
22618 contourMovements[_i] = getBevelVec(contour[_i], contour[j], contour[k]);
22621 var holesMovements = [];
22622 var oneHoleMovements,
22623 verticesMovements = contourMovements.concat();
22625 for (var _h2 = 0, _hl2 = holes.length; _h2 < _hl2; _h2++) {
22626 var _ahole2 = holes[_h2];
22627 oneHoleMovements = [];
22629 for (var _i2 = 0, _il = _ahole2.length, _j = _il - 1, _k = _i2 + 1; _i2 < _il; _i2++, _j++, _k++) {
22630 if (_j === _il) _j = 0;
22631 if (_k === _il) _k = 0; // (j)---(i)---(k)
22633 oneHoleMovements[_i2] = getBevelVec(_ahole2[_i2], _ahole2[_j], _ahole2[_k]);
22636 holesMovements.push(oneHoleMovements);
22637 verticesMovements = verticesMovements.concat(oneHoleMovements);
22638 } // Loop bevelSegments, 1 for the front, 1 for the back
22641 for (var b = 0; b < bevelSegments; b++) {
22642 //for ( b = bevelSegments; b > 0; b -- ) {
22643 var t = b / bevelSegments;
22644 var z = bevelThickness * Math.cos(t * Math.PI / 2);
22646 var _bs = bevelSize * Math.sin(t * Math.PI / 2) + bevelOffset; // contract shape
22649 for (var _i3 = 0, _il2 = contour.length; _i3 < _il2; _i3++) {
22650 var vert = scalePt2(contour[_i3], contourMovements[_i3], _bs);
22651 v(vert.x, vert.y, -z);
22655 for (var _h3 = 0, _hl3 = holes.length; _h3 < _hl3; _h3++) {
22656 var _ahole3 = holes[_h3];
22657 oneHoleMovements = holesMovements[_h3];
22659 for (var _i4 = 0, _il3 = _ahole3.length; _i4 < _il3; _i4++) {
22660 var _vert = scalePt2(_ahole3[_i4], oneHoleMovements[_i4], _bs);
22662 v(_vert.x, _vert.y, -z);
22667 var bs = bevelSize + bevelOffset; // Back facing vertices
22669 for (var _i5 = 0; _i5 < vlen; _i5++) {
22670 var _vert2 = bevelEnabled ? scalePt2(vertices[_i5], verticesMovements[_i5], bs) : vertices[_i5];
22672 if (!extrudeByPath) {
22673 v(_vert2.x, _vert2.y, 0);
22675 // v( vert.x, vert.y + extrudePts[ 0 ].y, extrudePts[ 0 ].x );
22676 normal.copy(splineTube.normals[0]).multiplyScalar(_vert2.x);
22677 binormal.copy(splineTube.binormals[0]).multiplyScalar(_vert2.y);
22678 position2.copy(extrudePts[0]).add(normal).add(binormal);
22679 v(position2.x, position2.y, position2.z);
22681 } // Add stepped vertices...
22682 // Including front facing vertices
22685 for (var s = 1; s <= steps; s++) {
22686 for (var _i6 = 0; _i6 < vlen; _i6++) {
22687 var _vert3 = bevelEnabled ? scalePt2(vertices[_i6], verticesMovements[_i6], bs) : vertices[_i6];
22689 if (!extrudeByPath) {
22690 v(_vert3.x, _vert3.y, depth / steps * s);
22692 // v( vert.x, vert.y + extrudePts[ s - 1 ].y, extrudePts[ s - 1 ].x );
22693 normal.copy(splineTube.normals[s]).multiplyScalar(_vert3.x);
22694 binormal.copy(splineTube.binormals[s]).multiplyScalar(_vert3.y);
22695 position2.copy(extrudePts[s]).add(normal).add(binormal);
22696 v(position2.x, position2.y, position2.z);
22699 } // Add bevel segments planes
22700 //for ( b = 1; b <= bevelSegments; b ++ ) {
22703 for (var _b = bevelSegments - 1; _b >= 0; _b--) {
22704 var _t = _b / bevelSegments;
22706 var _z = bevelThickness * Math.cos(_t * Math.PI / 2);
22708 var _bs2 = bevelSize * Math.sin(_t * Math.PI / 2) + bevelOffset; // contract shape
22711 for (var _i7 = 0, _il4 = contour.length; _i7 < _il4; _i7++) {
22712 var _vert4 = scalePt2(contour[_i7], contourMovements[_i7], _bs2);
22714 v(_vert4.x, _vert4.y, depth + _z);
22718 for (var _h4 = 0, _hl4 = holes.length; _h4 < _hl4; _h4++) {
22719 var _ahole4 = holes[_h4];
22720 oneHoleMovements = holesMovements[_h4];
22722 for (var _i8 = 0, _il5 = _ahole4.length; _i8 < _il5; _i8++) {
22723 var _vert5 = scalePt2(_ahole4[_i8], oneHoleMovements[_i8], _bs2);
22725 if (!extrudeByPath) {
22726 v(_vert5.x, _vert5.y, depth + _z);
22728 v(_vert5.x, _vert5.y + extrudePts[steps - 1].y, extrudePts[steps - 1].x + _z);
22734 // Top and bottom faces
22737 buildLidFaces(); // Sides faces
22739 buildSideFaces(); ///// Internal functions
22741 function buildLidFaces() {
22742 var start = verticesArray.length / 3;
22744 if (bevelEnabled) {
22745 var layer = 0; // steps + 1
22747 var offset = vlen * layer; // Bottom faces
22749 for (var _i9 = 0; _i9 < flen; _i9++) {
22750 var face = faces[_i9];
22751 f3(face[2] + offset, face[1] + offset, face[0] + offset);
22754 layer = steps + bevelSegments * 2;
22755 offset = vlen * layer; // Top faces
22757 for (var _i10 = 0; _i10 < flen; _i10++) {
22758 var _face = faces[_i10];
22759 f3(_face[0] + offset, _face[1] + offset, _face[2] + offset);
22763 for (var _i11 = 0; _i11 < flen; _i11++) {
22764 var _face2 = faces[_i11];
22765 f3(_face2[2], _face2[1], _face2[0]);
22769 for (var _i12 = 0; _i12 < flen; _i12++) {
22770 var _face3 = faces[_i12];
22771 f3(_face3[0] + vlen * steps, _face3[1] + vlen * steps, _face3[2] + vlen * steps);
22775 scope.addGroup(start, verticesArray.length / 3 - start, 0);
22776 } // Create faces for the z-sides of the shape
22779 function buildSideFaces() {
22780 var start = verticesArray.length / 3;
22781 var layeroffset = 0;
22782 sidewalls(contour, layeroffset);
22783 layeroffset += contour.length;
22785 for (var _h5 = 0, _hl5 = holes.length; _h5 < _hl5; _h5++) {
22786 var _ahole5 = holes[_h5];
22787 sidewalls(_ahole5, layeroffset); //, true
22789 layeroffset += _ahole5.length;
22792 scope.addGroup(start, verticesArray.length / 3 - start, 1);
22795 function sidewalls(contour, layeroffset) {
22796 var i = contour.length;
22803 if (_k2 < 0) _k2 = contour.length - 1; //console.log('b', i,j, i-1, k,vertices.length);
22805 for (var _s = 0, sl = steps + bevelSegments * 2; _s < sl; _s++) {
22806 var slen1 = vlen * _s;
22807 var slen2 = vlen * (_s + 1);
22809 var a = layeroffset + _j2 + slen1,
22810 _b2 = layeroffset + _k2 + slen1,
22811 c = layeroffset + _k2 + slen2,
22812 d = layeroffset + _j2 + slen2;
22819 function v(x, y, z) {
22820 placeholder.push(x);
22821 placeholder.push(y);
22822 placeholder.push(z);
22825 function f3(a, b, c) {
22829 var nextIndex = verticesArray.length / 3;
22830 var uvs = uvgen.generateTopUV(scope, verticesArray, nextIndex - 3, nextIndex - 2, nextIndex - 1);
22836 function f4(a, b, c, d) {
22843 var nextIndex = verticesArray.length / 3;
22844 var uvs = uvgen.generateSideWallUV(scope, verticesArray, nextIndex - 6, nextIndex - 3, nextIndex - 2, nextIndex - 1);
22853 function addVertex(index) {
22854 verticesArray.push(placeholder[index * 3 + 0]);
22855 verticesArray.push(placeholder[index * 3 + 1]);
22856 verticesArray.push(placeholder[index * 3 + 2]);
22859 function addUV(vector2) {
22860 uvArray.push(vector2.x);
22861 uvArray.push(vector2.y);
22868 var _proto = ExtrudeGeometry.prototype;
22870 _proto.toJSON = function toJSON() {
22871 var data = BufferGeometry.prototype.toJSON.call(this);
22872 var shapes = this.parameters.shapes;
22873 var options = this.parameters.options;
22874 return _toJSON(shapes, options, data);
22877 return ExtrudeGeometry;
22880 var WorldUVGenerator = {
22881 generateTopUV: function generateTopUV(geometry, vertices, indexA, indexB, indexC) {
22882 var a_x = vertices[indexA * 3];
22883 var a_y = vertices[indexA * 3 + 1];
22884 var b_x = vertices[indexB * 3];
22885 var b_y = vertices[indexB * 3 + 1];
22886 var c_x = vertices[indexC * 3];
22887 var c_y = vertices[indexC * 3 + 1];
22888 return [new Vector2(a_x, a_y), new Vector2(b_x, b_y), new Vector2(c_x, c_y)];
22890 generateSideWallUV: function generateSideWallUV(geometry, vertices, indexA, indexB, indexC, indexD) {
22891 var a_x = vertices[indexA * 3];
22892 var a_y = vertices[indexA * 3 + 1];
22893 var a_z = vertices[indexA * 3 + 2];
22894 var b_x = vertices[indexB * 3];
22895 var b_y = vertices[indexB * 3 + 1];
22896 var b_z = vertices[indexB * 3 + 2];
22897 var c_x = vertices[indexC * 3];
22898 var c_y = vertices[indexC * 3 + 1];
22899 var c_z = vertices[indexC * 3 + 2];
22900 var d_x = vertices[indexD * 3];
22901 var d_y = vertices[indexD * 3 + 1];
22902 var d_z = vertices[indexD * 3 + 2];
22904 if (Math.abs(a_y - b_y) < 0.01) {
22905 return [new Vector2(a_x, 1 - a_z), new Vector2(b_x, 1 - b_z), new Vector2(c_x, 1 - c_z), new Vector2(d_x, 1 - d_z)];
22907 return [new Vector2(a_y, 1 - a_z), new Vector2(b_y, 1 - b_z), new Vector2(c_y, 1 - c_z), new Vector2(d_y, 1 - d_z)];
22912 function _toJSON(shapes, options, data) {
22915 if (Array.isArray(shapes)) {
22916 for (var i = 0, l = shapes.length; i < l; i++) {
22917 var shape = shapes[i];
22918 data.shapes.push(shape.uuid);
22921 data.shapes.push(shapes.uuid);
22924 if (options.extrudePath !== undefined) data.options.extrudePath = options.extrudePath.toJSON();
22928 var IcosahedronGeometry = /*#__PURE__*/function (_PolyhedronGeometry) {
22929 _inheritsLoose(IcosahedronGeometry, _PolyhedronGeometry);
22931 function IcosahedronGeometry(radius, detail) {
22934 if (radius === void 0) {
22938 if (detail === void 0) {
22942 var t = (1 + Math.sqrt(5)) / 2;
22943 var vertices = [-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];
22944 var indices = [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];
22945 _this = _PolyhedronGeometry.call(this, vertices, indices, radius, detail) || this;
22946 _this.type = 'IcosahedronGeometry';
22947 _this.parameters = {
22954 return IcosahedronGeometry;
22955 }(PolyhedronGeometry);
22957 var LatheGeometry = /*#__PURE__*/function (_BufferGeometry) {
22958 _inheritsLoose(LatheGeometry, _BufferGeometry);
22960 function LatheGeometry(points, segments, phiStart, phiLength) {
22963 if (segments === void 0) {
22967 if (phiStart === void 0) {
22971 if (phiLength === void 0) {
22972 phiLength = Math.PI * 2;
22975 _this = _BufferGeometry.call(this) || this;
22976 _this.type = 'LatheGeometry';
22977 _this.parameters = {
22979 segments: segments,
22980 phiStart: phiStart,
22981 phiLength: phiLength
22983 segments = Math.floor(segments); // clamp phiLength so it's in range of [ 0, 2PI ]
22985 phiLength = MathUtils.clamp(phiLength, 0, Math.PI * 2); // buffers
22989 var uvs = []; // helper variables
22991 var inverseSegments = 1.0 / segments;
22992 var vertex = new Vector3();
22993 var uv = new Vector2(); // generate vertices and uvs
22995 for (var i = 0; i <= segments; i++) {
22996 var phi = phiStart + i * inverseSegments * phiLength;
22997 var sin = Math.sin(phi);
22998 var cos = Math.cos(phi);
23000 for (var j = 0; j <= points.length - 1; j++) {
23002 vertex.x = points[j].x * sin;
23003 vertex.y = points[j].y;
23004 vertex.z = points[j].x * cos;
23005 vertices.push(vertex.x, vertex.y, vertex.z); // uv
23007 uv.x = i / segments;
23008 uv.y = j / (points.length - 1);
23009 uvs.push(uv.x, uv.y);
23014 for (var _i = 0; _i < segments; _i++) {
23015 for (var _j = 0; _j < points.length - 1; _j++) {
23016 var base = _j + _i * points.length;
23018 var b = base + points.length;
23019 var c = base + points.length + 1;
23020 var d = base + 1; // faces
23022 indices.push(a, b, d);
23023 indices.push(b, c, d);
23025 } // build geometry
23028 _this.setIndex(indices);
23030 _this.setAttribute('position', new Float32BufferAttribute(vertices, 3));
23032 _this.setAttribute('uv', new Float32BufferAttribute(uvs, 2)); // generate normals
23035 _this.computeVertexNormals(); // if the geometry is closed, we need to average the normals along the seam.
23036 // because the corresponding vertices are identical (but still have different UVs).
23039 if (phiLength === Math.PI * 2) {
23040 var normals = _this.attributes.normal.array;
23041 var n1 = new Vector3();
23042 var n2 = new Vector3();
23043 var n = new Vector3(); // this is the buffer offset for the last line of vertices
23045 var _base = segments * points.length * 3;
23047 for (var _i2 = 0, _j2 = 0; _i2 < points.length; _i2++, _j2 += 3) {
23048 // select the normal of the vertex in the first line
23049 n1.x = normals[_j2 + 0];
23050 n1.y = normals[_j2 + 1];
23051 n1.z = normals[_j2 + 2]; // select the normal of the vertex in the last line
23053 n2.x = normals[_base + _j2 + 0];
23054 n2.y = normals[_base + _j2 + 1];
23055 n2.z = normals[_base + _j2 + 2]; // average normals
23057 n.addVectors(n1, n2).normalize(); // assign the new values to both normals
23059 normals[_j2 + 0] = normals[_base + _j2 + 0] = n.x;
23060 normals[_j2 + 1] = normals[_base + _j2 + 1] = n.y;
23061 normals[_j2 + 2] = normals[_base + _j2 + 2] = n.z;
23068 return LatheGeometry;
23071 var OctahedronGeometry = /*#__PURE__*/function (_PolyhedronGeometry) {
23072 _inheritsLoose(OctahedronGeometry, _PolyhedronGeometry);
23074 function OctahedronGeometry(radius, detail) {
23077 if (radius === void 0) {
23081 if (detail === void 0) {
23085 var vertices = [1, 0, 0, -1, 0, 0, 0, 1, 0, 0, -1, 0, 0, 0, 1, 0, 0, -1];
23086 var indices = [0, 2, 4, 0, 4, 3, 0, 3, 5, 0, 5, 2, 1, 2, 5, 1, 5, 3, 1, 3, 4, 1, 4, 2];
23087 _this = _PolyhedronGeometry.call(this, vertices, indices, radius, detail) || this;
23088 _this.type = 'OctahedronGeometry';
23089 _this.parameters = {
23096 return OctahedronGeometry;
23097 }(PolyhedronGeometry);
23100 * Parametric Surfaces Geometry
23101 * based on the brilliant article by @prideout https://prideout.net/blog/old/blog/index.html@p=44.html
23104 function ParametricGeometry(func, slices, stacks) {
23105 BufferGeometry.call(this);
23106 this.type = 'ParametricGeometry';
23107 this.parameters = {
23118 var normal = new Vector3();
23119 var p0 = new Vector3(),
23120 p1 = new Vector3();
23121 var pu = new Vector3(),
23122 pv = new Vector3();
23124 if (func.length < 3) {
23125 console.error('THREE.ParametricGeometry: Function must now modify a Vector3 as third parameter.');
23126 } // generate vertices, normals and uvs
23129 var sliceCount = slices + 1;
23131 for (var i = 0; i <= stacks; i++) {
23132 var v = i / stacks;
23134 for (var j = 0; j <= slices; j++) {
23135 var u = j / slices; // vertex
23138 vertices.push(p0.x, p0.y, p0.z); // normal
23139 // approximate tangent vectors via finite differences
23141 if (u - EPS >= 0) {
23142 func(u - EPS, v, p1);
23143 pu.subVectors(p0, p1);
23145 func(u + EPS, v, p1);
23146 pu.subVectors(p1, p0);
23149 if (v - EPS >= 0) {
23150 func(u, v - EPS, p1);
23151 pv.subVectors(p0, p1);
23153 func(u, v + EPS, p1);
23154 pv.subVectors(p1, p0);
23155 } // cross product of tangent vectors returns surface normal
23158 normal.crossVectors(pu, pv).normalize();
23159 normals.push(normal.x, normal.y, normal.z); // uv
23163 } // generate indices
23166 for (var _i = 0; _i < stacks; _i++) {
23167 for (var _j = 0; _j < slices; _j++) {
23168 var a = _i * sliceCount + _j;
23169 var b = _i * sliceCount + _j + 1;
23170 var c = (_i + 1) * sliceCount + _j + 1;
23171 var d = (_i + 1) * sliceCount + _j; // faces one and two
23173 indices.push(a, b, d);
23174 indices.push(b, c, d);
23176 } // build geometry
23179 this.setIndex(indices);
23180 this.setAttribute('position', new Float32BufferAttribute(vertices, 3));
23181 this.setAttribute('normal', new Float32BufferAttribute(normals, 3));
23182 this.setAttribute('uv', new Float32BufferAttribute(uvs, 2));
23185 ParametricGeometry.prototype = Object.create(BufferGeometry.prototype);
23186 ParametricGeometry.prototype.constructor = ParametricGeometry;
23188 var RingGeometry = /*#__PURE__*/function (_BufferGeometry) {
23189 _inheritsLoose(RingGeometry, _BufferGeometry);
23191 function RingGeometry(innerRadius, outerRadius, thetaSegments, phiSegments, thetaStart, thetaLength) {
23194 if (innerRadius === void 0) {
23198 if (outerRadius === void 0) {
23202 if (thetaSegments === void 0) {
23206 if (phiSegments === void 0) {
23210 if (thetaStart === void 0) {
23214 if (thetaLength === void 0) {
23215 thetaLength = Math.PI * 2;
23218 _this = _BufferGeometry.call(this) || this;
23219 _this.type = 'RingGeometry';
23220 _this.parameters = {
23221 innerRadius: innerRadius,
23222 outerRadius: outerRadius,
23223 thetaSegments: thetaSegments,
23224 phiSegments: phiSegments,
23225 thetaStart: thetaStart,
23226 thetaLength: thetaLength
23228 thetaSegments = Math.max(3, thetaSegments);
23229 phiSegments = Math.max(1, phiSegments); // buffers
23234 var uvs = []; // some helper variables
23236 var radius = innerRadius;
23237 var radiusStep = (outerRadius - innerRadius) / phiSegments;
23238 var vertex = new Vector3();
23239 var uv = new Vector2(); // generate vertices, normals and uvs
23241 for (var j = 0; j <= phiSegments; j++) {
23242 for (var i = 0; i <= thetaSegments; i++) {
23243 // values are generate from the inside of the ring to the outside
23244 var segment = thetaStart + i / thetaSegments * thetaLength; // vertex
23246 vertex.x = radius * Math.cos(segment);
23247 vertex.y = radius * Math.sin(segment);
23248 vertices.push(vertex.x, vertex.y, vertex.z); // normal
23250 normals.push(0, 0, 1); // uv
23252 uv.x = (vertex.x / outerRadius + 1) / 2;
23253 uv.y = (vertex.y / outerRadius + 1) / 2;
23254 uvs.push(uv.x, uv.y);
23255 } // increase the radius for next row of vertices
23258 radius += radiusStep;
23262 for (var _j = 0; _j < phiSegments; _j++) {
23263 var thetaSegmentLevel = _j * (thetaSegments + 1);
23265 for (var _i = 0; _i < thetaSegments; _i++) {
23266 var _segment = _i + thetaSegmentLevel;
23269 var b = _segment + thetaSegments + 1;
23270 var c = _segment + thetaSegments + 2;
23271 var d = _segment + 1; // faces
23273 indices.push(a, b, d);
23274 indices.push(b, c, d);
23276 } // build geometry
23279 _this.setIndex(indices);
23281 _this.setAttribute('position', new Float32BufferAttribute(vertices, 3));
23283 _this.setAttribute('normal', new Float32BufferAttribute(normals, 3));
23285 _this.setAttribute('uv', new Float32BufferAttribute(uvs, 2));
23290 return RingGeometry;
23293 var ShapeGeometry = /*#__PURE__*/function (_BufferGeometry) {
23294 _inheritsLoose(ShapeGeometry, _BufferGeometry);
23296 function ShapeGeometry(shapes, curveSegments) {
23299 if (curveSegments === void 0) {
23300 curveSegments = 12;
23303 _this = _BufferGeometry.call(this) || this;
23304 _this.type = 'ShapeGeometry';
23305 _this.parameters = {
23307 curveSegments: curveSegments
23313 var uvs = []; // helper variables
23315 var groupStart = 0;
23316 var groupCount = 0; // allow single and array values for "shapes" parameter
23318 if (Array.isArray(shapes) === false) {
23321 for (var i = 0; i < shapes.length; i++) {
23322 addShape(shapes[i]);
23324 _this.addGroup(groupStart, groupCount, i); // enables MultiMaterial support
23327 groupStart += groupCount;
23330 } // build geometry
23333 _this.setIndex(indices);
23335 _this.setAttribute('position', new Float32BufferAttribute(vertices, 3));
23337 _this.setAttribute('normal', new Float32BufferAttribute(normals, 3));
23339 _this.setAttribute('uv', new Float32BufferAttribute(uvs, 2)); // helper functions
23342 function addShape(shape) {
23343 var indexOffset = vertices.length / 3;
23344 var points = shape.extractPoints(curveSegments);
23345 var shapeVertices = points.shape;
23346 var shapeHoles = points.holes; // check direction of vertices
23348 if (ShapeUtils.isClockWise(shapeVertices) === false) {
23349 shapeVertices = shapeVertices.reverse();
23352 for (var _i = 0, l = shapeHoles.length; _i < l; _i++) {
23353 var shapeHole = shapeHoles[_i];
23355 if (ShapeUtils.isClockWise(shapeHole) === true) {
23356 shapeHoles[_i] = shapeHole.reverse();
23360 var faces = ShapeUtils.triangulateShape(shapeVertices, shapeHoles); // join vertices of inner and outer paths to a single array
23362 for (var _i2 = 0, _l = shapeHoles.length; _i2 < _l; _i2++) {
23363 var _shapeHole = shapeHoles[_i2];
23364 shapeVertices = shapeVertices.concat(_shapeHole);
23365 } // vertices, normals, uvs
23368 for (var _i3 = 0, _l2 = shapeVertices.length; _i3 < _l2; _i3++) {
23369 var vertex = shapeVertices[_i3];
23370 vertices.push(vertex.x, vertex.y, 0);
23371 normals.push(0, 0, 1);
23372 uvs.push(vertex.x, vertex.y); // world uvs
23376 for (var _i4 = 0, _l3 = faces.length; _i4 < _l3; _i4++) {
23377 var face = faces[_i4];
23378 var a = face[0] + indexOffset;
23379 var b = face[1] + indexOffset;
23380 var c = face[2] + indexOffset;
23381 indices.push(a, b, c);
23389 var _proto = ShapeGeometry.prototype;
23391 _proto.toJSON = function toJSON() {
23392 var data = BufferGeometry.prototype.toJSON.call(this);
23393 var shapes = this.parameters.shapes;
23394 return _toJSON$1(shapes, data);
23397 return ShapeGeometry;
23400 function _toJSON$1(shapes, data) {
23403 if (Array.isArray(shapes)) {
23404 for (var i = 0, l = shapes.length; i < l; i++) {
23405 var shape = shapes[i];
23406 data.shapes.push(shape.uuid);
23409 data.shapes.push(shapes.uuid);
23415 var SphereGeometry = /*#__PURE__*/function (_BufferGeometry) {
23416 _inheritsLoose(SphereGeometry, _BufferGeometry);
23418 function SphereGeometry(radius, widthSegments, heightSegments, phiStart, phiLength, thetaStart, thetaLength) {
23421 if (radius === void 0) {
23425 if (widthSegments === void 0) {
23429 if (heightSegments === void 0) {
23430 heightSegments = 6;
23433 if (phiStart === void 0) {
23437 if (phiLength === void 0) {
23438 phiLength = Math.PI * 2;
23441 if (thetaStart === void 0) {
23445 if (thetaLength === void 0) {
23446 thetaLength = Math.PI;
23449 _this = _BufferGeometry.call(this) || this;
23450 _this.type = 'SphereGeometry';
23451 _this.parameters = {
23453 widthSegments: widthSegments,
23454 heightSegments: heightSegments,
23455 phiStart: phiStart,
23456 phiLength: phiLength,
23457 thetaStart: thetaStart,
23458 thetaLength: thetaLength
23460 widthSegments = Math.max(3, Math.floor(widthSegments));
23461 heightSegments = Math.max(2, Math.floor(heightSegments));
23462 var thetaEnd = Math.min(thetaStart + thetaLength, Math.PI);
23465 var vertex = new Vector3();
23466 var normal = new Vector3(); // buffers
23471 var uvs = []; // generate vertices, normals and uvs
23473 for (var iy = 0; iy <= heightSegments; iy++) {
23474 var verticesRow = [];
23475 var v = iy / heightSegments; // special case for the poles
23479 if (iy == 0 && thetaStart == 0) {
23480 uOffset = 0.5 / widthSegments;
23481 } else if (iy == heightSegments && thetaEnd == Math.PI) {
23482 uOffset = -0.5 / widthSegments;
23485 for (var ix = 0; ix <= widthSegments; ix++) {
23486 var u = ix / widthSegments; // vertex
23488 vertex.x = -radius * Math.cos(phiStart + u * phiLength) * Math.sin(thetaStart + v * thetaLength);
23489 vertex.y = radius * Math.cos(thetaStart + v * thetaLength);
23490 vertex.z = radius * Math.sin(phiStart + u * phiLength) * Math.sin(thetaStart + v * thetaLength);
23491 vertices.push(vertex.x, vertex.y, vertex.z); // normal
23493 normal.copy(vertex).normalize();
23494 normals.push(normal.x, normal.y, normal.z); // uv
23496 uvs.push(u + uOffset, 1 - v);
23497 verticesRow.push(index++);
23500 grid.push(verticesRow);
23504 for (var _iy = 0; _iy < heightSegments; _iy++) {
23505 for (var _ix = 0; _ix < widthSegments; _ix++) {
23506 var a = grid[_iy][_ix + 1];
23507 var b = grid[_iy][_ix];
23508 var c = grid[_iy + 1][_ix];
23509 var d = grid[_iy + 1][_ix + 1];
23510 if (_iy !== 0 || thetaStart > 0) indices.push(a, b, d);
23511 if (_iy !== heightSegments - 1 || thetaEnd < Math.PI) indices.push(b, c, d);
23513 } // build geometry
23516 _this.setIndex(indices);
23518 _this.setAttribute('position', new Float32BufferAttribute(vertices, 3));
23520 _this.setAttribute('normal', new Float32BufferAttribute(normals, 3));
23522 _this.setAttribute('uv', new Float32BufferAttribute(uvs, 2));
23527 return SphereGeometry;
23530 var TetrahedronGeometry = /*#__PURE__*/function (_PolyhedronGeometry) {
23531 _inheritsLoose(TetrahedronGeometry, _PolyhedronGeometry);
23533 function TetrahedronGeometry(radius, detail) {
23536 if (radius === void 0) {
23540 if (detail === void 0) {
23544 var vertices = [1, 1, 1, -1, -1, 1, -1, 1, -1, 1, -1, -1];
23545 var indices = [2, 1, 0, 0, 3, 2, 1, 3, 0, 2, 3, 1];
23546 _this = _PolyhedronGeometry.call(this, vertices, indices, radius, detail) || this;
23547 _this.type = 'TetrahedronGeometry';
23548 _this.parameters = {
23555 return TetrahedronGeometry;
23556 }(PolyhedronGeometry);
23558 var TextGeometry = /*#__PURE__*/function (_ExtrudeGeometry) {
23559 _inheritsLoose(TextGeometry, _ExtrudeGeometry);
23561 function TextGeometry(text, parameters) {
23564 if (parameters === void 0) {
23568 var font = parameters.font;
23570 if (!(font && font.isFont)) {
23571 console.error('THREE.TextGeometry: font parameter is not an instance of THREE.Font.');
23572 return new BufferGeometry() || _assertThisInitialized(_this);
23575 var shapes = font.generateShapes(text, parameters.size); // translate parameters to ExtrudeGeometry API
23577 parameters.depth = parameters.height !== undefined ? parameters.height : 50; // defaults
23579 if (parameters.bevelThickness === undefined) parameters.bevelThickness = 10;
23580 if (parameters.bevelSize === undefined) parameters.bevelSize = 8;
23581 if (parameters.bevelEnabled === undefined) parameters.bevelEnabled = false;
23582 _this = _ExtrudeGeometry.call(this, shapes, parameters) || this;
23583 _this.type = 'TextGeometry';
23587 return TextGeometry;
23588 }(ExtrudeGeometry);
23590 var TorusGeometry = /*#__PURE__*/function (_BufferGeometry) {
23591 _inheritsLoose(TorusGeometry, _BufferGeometry);
23593 function TorusGeometry(radius, tube, radialSegments, tubularSegments, arc) {
23596 if (radius === void 0) {
23600 if (tube === void 0) {
23604 if (radialSegments === void 0) {
23605 radialSegments = 8;
23608 if (tubularSegments === void 0) {
23609 tubularSegments = 6;
23612 if (arc === void 0) {
23616 _this = _BufferGeometry.call(this) || this;
23617 _this.type = 'TorusGeometry';
23618 _this.parameters = {
23621 radialSegments: radialSegments,
23622 tubularSegments: tubularSegments,
23625 radialSegments = Math.floor(radialSegments);
23626 tubularSegments = Math.floor(tubularSegments); // buffers
23631 var uvs = []; // helper variables
23633 var center = new Vector3();
23634 var vertex = new Vector3();
23635 var normal = new Vector3(); // generate vertices, normals and uvs
23637 for (var j = 0; j <= radialSegments; j++) {
23638 for (var i = 0; i <= tubularSegments; i++) {
23639 var u = i / tubularSegments * arc;
23640 var v = j / radialSegments * Math.PI * 2; // vertex
23642 vertex.x = (radius + tube * Math.cos(v)) * Math.cos(u);
23643 vertex.y = (radius + tube * Math.cos(v)) * Math.sin(u);
23644 vertex.z = tube * Math.sin(v);
23645 vertices.push(vertex.x, vertex.y, vertex.z); // normal
23647 center.x = radius * Math.cos(u);
23648 center.y = radius * Math.sin(u);
23649 normal.subVectors(vertex, center).normalize();
23650 normals.push(normal.x, normal.y, normal.z); // uv
23652 uvs.push(i / tubularSegments);
23653 uvs.push(j / radialSegments);
23655 } // generate indices
23658 for (var _j = 1; _j <= radialSegments; _j++) {
23659 for (var _i = 1; _i <= tubularSegments; _i++) {
23661 var a = (tubularSegments + 1) * _j + _i - 1;
23662 var b = (tubularSegments + 1) * (_j - 1) + _i - 1;
23663 var c = (tubularSegments + 1) * (_j - 1) + _i;
23664 var d = (tubularSegments + 1) * _j + _i; // faces
23666 indices.push(a, b, d);
23667 indices.push(b, c, d);
23669 } // build geometry
23672 _this.setIndex(indices);
23674 _this.setAttribute('position', new Float32BufferAttribute(vertices, 3));
23676 _this.setAttribute('normal', new Float32BufferAttribute(normals, 3));
23678 _this.setAttribute('uv', new Float32BufferAttribute(uvs, 2));
23683 return TorusGeometry;
23686 var TorusKnotGeometry = /*#__PURE__*/function (_BufferGeometry) {
23687 _inheritsLoose(TorusKnotGeometry, _BufferGeometry);
23689 function TorusKnotGeometry(radius, tube, tubularSegments, radialSegments, p, q) {
23692 if (radius === void 0) {
23696 if (tube === void 0) {
23700 if (tubularSegments === void 0) {
23701 tubularSegments = 64;
23704 if (radialSegments === void 0) {
23705 radialSegments = 8;
23708 if (p === void 0) {
23712 if (q === void 0) {
23716 _this = _BufferGeometry.call(this) || this;
23717 _this.type = 'TorusKnotGeometry';
23718 _this.parameters = {
23721 tubularSegments: tubularSegments,
23722 radialSegments: radialSegments,
23726 tubularSegments = Math.floor(tubularSegments);
23727 radialSegments = Math.floor(radialSegments); // buffers
23732 var uvs = []; // helper variables
23734 var vertex = new Vector3();
23735 var normal = new Vector3();
23736 var P1 = new Vector3();
23737 var P2 = new Vector3();
23738 var B = new Vector3();
23739 var T = new Vector3();
23740 var N = new Vector3(); // generate vertices, normals and uvs
23742 for (var i = 0; i <= tubularSegments; ++i) {
23743 // the radian "u" is used to calculate the position on the torus curve of the current tubular segement
23744 var u = i / tubularSegments * p * Math.PI * 2; // now we calculate two points. P1 is our current position on the curve, P2 is a little farther ahead.
23745 // these points are used to create a special "coordinate space", which is necessary to calculate the correct vertex positions
23747 calculatePositionOnCurve(u, p, q, radius, P1);
23748 calculatePositionOnCurve(u + 0.01, p, q, radius, P2); // calculate orthonormal basis
23750 T.subVectors(P2, P1);
23751 N.addVectors(P2, P1);
23752 B.crossVectors(T, N);
23753 N.crossVectors(B, T); // normalize B, N. T can be ignored, we don't use it
23758 for (var j = 0; j <= radialSegments; ++j) {
23759 // now calculate the vertices. they are nothing more than an extrusion of the torus curve.
23760 // because we extrude a shape in the xy-plane, there is no need to calculate a z-value.
23761 var v = j / radialSegments * Math.PI * 2;
23762 var cx = -tube * Math.cos(v);
23763 var cy = tube * Math.sin(v); // now calculate the final vertex position.
23764 // first we orient the extrusion with our basis vectos, then we add it to the current position on the curve
23766 vertex.x = P1.x + (cx * N.x + cy * B.x);
23767 vertex.y = P1.y + (cx * N.y + cy * B.y);
23768 vertex.z = P1.z + (cx * N.z + cy * B.z);
23769 vertices.push(vertex.x, vertex.y, vertex.z); // normal (P1 is always the center/origin of the extrusion, thus we can use it to calculate the normal)
23771 normal.subVectors(vertex, P1).normalize();
23772 normals.push(normal.x, normal.y, normal.z); // uv
23774 uvs.push(i / tubularSegments);
23775 uvs.push(j / radialSegments);
23777 } // generate indices
23780 for (var _j = 1; _j <= tubularSegments; _j++) {
23781 for (var _i = 1; _i <= radialSegments; _i++) {
23783 var a = (radialSegments + 1) * (_j - 1) + (_i - 1);
23784 var b = (radialSegments + 1) * _j + (_i - 1);
23785 var c = (radialSegments + 1) * _j + _i;
23786 var d = (radialSegments + 1) * (_j - 1) + _i; // faces
23788 indices.push(a, b, d);
23789 indices.push(b, c, d);
23791 } // build geometry
23794 _this.setIndex(indices);
23796 _this.setAttribute('position', new Float32BufferAttribute(vertices, 3));
23798 _this.setAttribute('normal', new Float32BufferAttribute(normals, 3));
23800 _this.setAttribute('uv', new Float32BufferAttribute(uvs, 2)); // this function calculates the current position on the torus curve
23803 function calculatePositionOnCurve(u, p, q, radius, position) {
23804 var cu = Math.cos(u);
23805 var su = Math.sin(u);
23806 var quOverP = q / p * u;
23807 var cs = Math.cos(quOverP);
23808 position.x = radius * (2 + cs) * 0.5 * cu;
23809 position.y = radius * (2 + cs) * su * 0.5;
23810 position.z = radius * Math.sin(quOverP) * 0.5;
23816 return TorusKnotGeometry;
23819 var TubeGeometry = /*#__PURE__*/function (_BufferGeometry) {
23820 _inheritsLoose(TubeGeometry, _BufferGeometry);
23822 function TubeGeometry(path, tubularSegments, radius, radialSegments, closed) {
23825 if (tubularSegments === void 0) {
23826 tubularSegments = 64;
23829 if (radius === void 0) {
23833 if (radialSegments === void 0) {
23834 radialSegments = 8;
23837 if (closed === void 0) {
23841 _this = _BufferGeometry.call(this) || this;
23842 _this.type = 'TubeGeometry';
23843 _this.parameters = {
23845 tubularSegments: tubularSegments,
23847 radialSegments: radialSegments,
23850 var frames = path.computeFrenetFrames(tubularSegments, closed); // expose internals
23852 _this.tangents = frames.tangents;
23853 _this.normals = frames.normals;
23854 _this.binormals = frames.binormals; // helper variables
23856 var vertex = new Vector3();
23857 var normal = new Vector3();
23858 var uv = new Vector2();
23859 var P = new Vector3(); // buffer
23864 var indices = []; // create buffer data
23866 generateBufferData(); // build geometry
23868 _this.setIndex(indices);
23870 _this.setAttribute('position', new Float32BufferAttribute(vertices, 3));
23872 _this.setAttribute('normal', new Float32BufferAttribute(normals, 3));
23874 _this.setAttribute('uv', new Float32BufferAttribute(uvs, 2)); // functions
23877 function generateBufferData() {
23878 for (var i = 0; i < tubularSegments; i++) {
23879 generateSegment(i);
23880 } // if the geometry is not closed, generate the last row of vertices and normals
23881 // at the regular position on the given path
23883 // if the geometry is closed, duplicate the first row of vertices and normals (uvs will differ)
23886 generateSegment(closed === false ? tubularSegments : 0); // uvs are generated in a separate function.
23887 // this makes it easy compute correct values for closed geometries
23889 generateUVs(); // finally create faces
23894 function generateSegment(i) {
23895 // we use getPointAt to sample evenly distributed points from the given path
23896 P = path.getPointAt(i / tubularSegments, P); // retrieve corresponding normal and binormal
23898 var N = frames.normals[i];
23899 var B = frames.binormals[i]; // generate normals and vertices for the current segment
23901 for (var j = 0; j <= radialSegments; j++) {
23902 var v = j / radialSegments * Math.PI * 2;
23903 var sin = Math.sin(v);
23904 var cos = -Math.cos(v); // normal
23906 normal.x = cos * N.x + sin * B.x;
23907 normal.y = cos * N.y + sin * B.y;
23908 normal.z = cos * N.z + sin * B.z;
23909 normal.normalize();
23910 normals.push(normal.x, normal.y, normal.z); // vertex
23912 vertex.x = P.x + radius * normal.x;
23913 vertex.y = P.y + radius * normal.y;
23914 vertex.z = P.z + radius * normal.z;
23915 vertices.push(vertex.x, vertex.y, vertex.z);
23919 function generateIndices() {
23920 for (var j = 1; j <= tubularSegments; j++) {
23921 for (var i = 1; i <= radialSegments; i++) {
23922 var a = (radialSegments + 1) * (j - 1) + (i - 1);
23923 var b = (radialSegments + 1) * j + (i - 1);
23924 var c = (radialSegments + 1) * j + i;
23925 var d = (radialSegments + 1) * (j - 1) + i; // faces
23927 indices.push(a, b, d);
23928 indices.push(b, c, d);
23933 function generateUVs() {
23934 for (var i = 0; i <= tubularSegments; i++) {
23935 for (var j = 0; j <= radialSegments; j++) {
23936 uv.x = i / tubularSegments;
23937 uv.y = j / radialSegments;
23938 uvs.push(uv.x, uv.y);
23946 var _proto = TubeGeometry.prototype;
23948 _proto.toJSON = function toJSON() {
23949 var data = BufferGeometry.prototype.toJSON.call(this);
23950 data.path = this.parameters.path.toJSON();
23954 return TubeGeometry;
23957 var WireframeGeometry = /*#__PURE__*/function (_BufferGeometry) {
23958 _inheritsLoose(WireframeGeometry, _BufferGeometry);
23960 function WireframeGeometry(geometry) {
23963 _this = _BufferGeometry.call(this) || this;
23964 _this.type = 'WireframeGeometry';
23966 if (geometry.isGeometry === true) {
23967 console.error('THREE.WireframeGeometry no longer supports THREE.Geometry. Use THREE.BufferGeometry instead.');
23968 return _assertThisInitialized(_this);
23972 var vertices = []; // helper variables
23976 var vertex = new Vector3();
23978 if (geometry.index !== null) {
23979 // indexed BufferGeometry
23980 var position = geometry.attributes.position;
23981 var indices = geometry.index;
23982 var groups = geometry.groups;
23984 if (groups.length === 0) {
23987 count: indices.count,
23990 } // create a data structure that contains all eges without duplicates
23993 for (var o = 0, ol = groups.length; o < ol; ++o) {
23994 var group = groups[o];
23995 var start = group.start;
23996 var count = group.count;
23998 for (var i = start, l = start + count; i < l; i += 3) {
23999 for (var j = 0; j < 3; j++) {
24000 var edge1 = indices.getX(i + j);
24001 var edge2 = indices.getX(i + (j + 1) % 3);
24002 edge[0] = Math.min(edge1, edge2); // sorting prevents duplicates
24004 edge[1] = Math.max(edge1, edge2);
24005 var key = edge[0] + ',' + edge[1];
24007 if (edges[key] === undefined) {
24015 } // generate vertices
24018 for (var _key in edges) {
24019 var e = edges[_key];
24020 vertex.fromBufferAttribute(position, e.index1);
24021 vertices.push(vertex.x, vertex.y, vertex.z);
24022 vertex.fromBufferAttribute(position, e.index2);
24023 vertices.push(vertex.x, vertex.y, vertex.z);
24026 // non-indexed BufferGeometry
24027 var _position = geometry.attributes.position;
24029 for (var _i = 0, _l = _position.count / 3; _i < _l; _i++) {
24030 for (var _j = 0; _j < 3; _j++) {
24031 // three edges per triangle, an edge is represented as (index1, index2)
24032 // e.g. the first triangle has the following edges: (0,1),(1,2),(2,0)
24033 var index1 = 3 * _i + _j;
24034 vertex.fromBufferAttribute(_position, index1);
24035 vertices.push(vertex.x, vertex.y, vertex.z);
24036 var index2 = 3 * _i + (_j + 1) % 3;
24037 vertex.fromBufferAttribute(_position, index2);
24038 vertices.push(vertex.x, vertex.y, vertex.z);
24041 } // build geometry
24044 _this.setAttribute('position', new Float32BufferAttribute(vertices, 3));
24049 return WireframeGeometry;
24052 var Geometries = /*#__PURE__*/Object.freeze({
24054 BoxGeometry: BoxGeometry,
24055 BoxBufferGeometry: BoxGeometry,
24056 CircleGeometry: CircleGeometry,
24057 CircleBufferGeometry: CircleGeometry,
24058 ConeGeometry: ConeGeometry,
24059 ConeBufferGeometry: ConeGeometry,
24060 CylinderGeometry: CylinderGeometry,
24061 CylinderBufferGeometry: CylinderGeometry,
24062 DodecahedronGeometry: DodecahedronGeometry,
24063 DodecahedronBufferGeometry: DodecahedronGeometry,
24064 EdgesGeometry: EdgesGeometry,
24065 ExtrudeGeometry: ExtrudeGeometry,
24066 ExtrudeBufferGeometry: ExtrudeGeometry,
24067 IcosahedronGeometry: IcosahedronGeometry,
24068 IcosahedronBufferGeometry: IcosahedronGeometry,
24069 LatheGeometry: LatheGeometry,
24070 LatheBufferGeometry: LatheGeometry,
24071 OctahedronGeometry: OctahedronGeometry,
24072 OctahedronBufferGeometry: OctahedronGeometry,
24073 ParametricGeometry: ParametricGeometry,
24074 ParametricBufferGeometry: ParametricGeometry,
24075 PlaneGeometry: PlaneGeometry,
24076 PlaneBufferGeometry: PlaneGeometry,
24077 PolyhedronGeometry: PolyhedronGeometry,
24078 PolyhedronBufferGeometry: PolyhedronGeometry,
24079 RingGeometry: RingGeometry,
24080 RingBufferGeometry: RingGeometry,
24081 ShapeGeometry: ShapeGeometry,
24082 ShapeBufferGeometry: ShapeGeometry,
24083 SphereGeometry: SphereGeometry,
24084 SphereBufferGeometry: SphereGeometry,
24085 TetrahedronGeometry: TetrahedronGeometry,
24086 TetrahedronBufferGeometry: TetrahedronGeometry,
24087 TextGeometry: TextGeometry,
24088 TextBufferGeometry: TextGeometry,
24089 TorusGeometry: TorusGeometry,
24090 TorusBufferGeometry: TorusGeometry,
24091 TorusKnotGeometry: TorusKnotGeometry,
24092 TorusKnotBufferGeometry: TorusKnotGeometry,
24093 TubeGeometry: TubeGeometry,
24094 TubeBufferGeometry: TubeGeometry,
24095 WireframeGeometry: WireframeGeometry
24100 * color: <THREE.Color>
24104 function ShadowMaterial(parameters) {
24105 Material.call(this);
24106 this.type = 'ShadowMaterial';
24107 this.color = new Color(0x000000);
24108 this.transparent = true;
24109 this.setValues(parameters);
24112 ShadowMaterial.prototype = Object.create(Material.prototype);
24113 ShadowMaterial.prototype.constructor = ShadowMaterial;
24114 ShadowMaterial.prototype.isShadowMaterial = true;
24116 ShadowMaterial.prototype.copy = function (source) {
24117 Material.prototype.copy.call(this, source);
24118 this.color.copy(source.color);
24122 function RawShaderMaterial(parameters) {
24123 ShaderMaterial.call(this, parameters);
24124 this.type = 'RawShaderMaterial';
24127 RawShaderMaterial.prototype = Object.create(ShaderMaterial.prototype);
24128 RawShaderMaterial.prototype.constructor = RawShaderMaterial;
24129 RawShaderMaterial.prototype.isRawShaderMaterial = true;
24134 * roughness: <float>,
24135 * metalness: <float>,
24136 * opacity: <float>,
24138 * map: new THREE.Texture( <Image> ),
24140 * lightMap: new THREE.Texture( <Image> ),
24141 * lightMapIntensity: <float>
24143 * aoMap: new THREE.Texture( <Image> ),
24144 * aoMapIntensity: <float>
24147 * emissiveIntensity: <float>
24148 * emissiveMap: new THREE.Texture( <Image> ),
24150 * bumpMap: new THREE.Texture( <Image> ),
24151 * bumpScale: <float>,
24153 * normalMap: new THREE.Texture( <Image> ),
24154 * normalMapType: THREE.TangentSpaceNormalMap,
24155 * normalScale: <Vector2>,
24157 * displacementMap: new THREE.Texture( <Image> ),
24158 * displacementScale: <float>,
24159 * displacementBias: <float>,
24161 * roughnessMap: new THREE.Texture( <Image> ),
24163 * metalnessMap: new THREE.Texture( <Image> ),
24165 * alphaMap: new THREE.Texture( <Image> ),
24167 * envMap: new THREE.CubeTexture( [posx, negx, posy, negy, posz, negz] ),
24168 * envMapIntensity: <float>
24170 * refractionRatio: <float>,
24172 * wireframe: <boolean>,
24173 * wireframeLinewidth: <float>,
24175 * skinning: <bool>,
24176 * morphTargets: <bool>,
24177 * morphNormals: <bool>
24181 function MeshStandardMaterial(parameters) {
24182 Material.call(this);
24186 this.type = 'MeshStandardMaterial';
24187 this.color = new Color(0xffffff); // diffuse
24189 this.roughness = 1.0;
24190 this.metalness = 0.0;
24192 this.lightMap = null;
24193 this.lightMapIntensity = 1.0;
24195 this.aoMapIntensity = 1.0;
24196 this.emissive = new Color(0x000000);
24197 this.emissiveIntensity = 1.0;
24198 this.emissiveMap = null;
24199 this.bumpMap = null;
24200 this.bumpScale = 1;
24201 this.normalMap = null;
24202 this.normalMapType = TangentSpaceNormalMap;
24203 this.normalScale = new Vector2(1, 1);
24204 this.displacementMap = null;
24205 this.displacementScale = 1;
24206 this.displacementBias = 0;
24207 this.roughnessMap = null;
24208 this.metalnessMap = null;
24209 this.alphaMap = null;
24210 this.envMap = null;
24211 this.envMapIntensity = 1.0;
24212 this.refractionRatio = 0.98;
24213 this.wireframe = false;
24214 this.wireframeLinewidth = 1;
24215 this.wireframeLinecap = 'round';
24216 this.wireframeLinejoin = 'round';
24217 this.skinning = false;
24218 this.morphTargets = false;
24219 this.morphNormals = false;
24220 this.vertexTangents = false;
24221 this.setValues(parameters);
24224 MeshStandardMaterial.prototype = Object.create(Material.prototype);
24225 MeshStandardMaterial.prototype.constructor = MeshStandardMaterial;
24226 MeshStandardMaterial.prototype.isMeshStandardMaterial = true;
24228 MeshStandardMaterial.prototype.copy = function (source) {
24229 Material.prototype.copy.call(this, source);
24233 this.color.copy(source.color);
24234 this.roughness = source.roughness;
24235 this.metalness = source.metalness;
24236 this.map = source.map;
24237 this.lightMap = source.lightMap;
24238 this.lightMapIntensity = source.lightMapIntensity;
24239 this.aoMap = source.aoMap;
24240 this.aoMapIntensity = source.aoMapIntensity;
24241 this.emissive.copy(source.emissive);
24242 this.emissiveMap = source.emissiveMap;
24243 this.emissiveIntensity = source.emissiveIntensity;
24244 this.bumpMap = source.bumpMap;
24245 this.bumpScale = source.bumpScale;
24246 this.normalMap = source.normalMap;
24247 this.normalMapType = source.normalMapType;
24248 this.normalScale.copy(source.normalScale);
24249 this.displacementMap = source.displacementMap;
24250 this.displacementScale = source.displacementScale;
24251 this.displacementBias = source.displacementBias;
24252 this.roughnessMap = source.roughnessMap;
24253 this.metalnessMap = source.metalnessMap;
24254 this.alphaMap = source.alphaMap;
24255 this.envMap = source.envMap;
24256 this.envMapIntensity = source.envMapIntensity;
24257 this.refractionRatio = source.refractionRatio;
24258 this.wireframe = source.wireframe;
24259 this.wireframeLinewidth = source.wireframeLinewidth;
24260 this.wireframeLinecap = source.wireframeLinecap;
24261 this.wireframeLinejoin = source.wireframeLinejoin;
24262 this.skinning = source.skinning;
24263 this.morphTargets = source.morphTargets;
24264 this.morphNormals = source.morphNormals;
24265 this.vertexTangents = source.vertexTangents;
24271 * clearcoat: <float>,
24272 * clearcoatMap: new THREE.Texture( <Image> ),
24273 * clearcoatRoughness: <float>,
24274 * clearcoatRoughnessMap: new THREE.Texture( <Image> ),
24275 * clearcoatNormalScale: <Vector2>,
24276 * clearcoatNormalMap: new THREE.Texture( <Image> ),
24278 * reflectivity: <float>,
24283 * transmission: <float>,
24284 * transmissionMap: new THREE.Texture( <Image> )
24288 function MeshPhysicalMaterial(parameters) {
24289 MeshStandardMaterial.call(this);
24294 this.type = 'MeshPhysicalMaterial';
24295 this.clearcoat = 0.0;
24296 this.clearcoatMap = null;
24297 this.clearcoatRoughness = 0.0;
24298 this.clearcoatRoughnessMap = null;
24299 this.clearcoatNormalScale = new Vector2(1, 1);
24300 this.clearcoatNormalMap = null;
24301 this.reflectivity = 0.5; // maps to F0 = 0.04
24303 Object.defineProperty(this, 'ior', {
24304 get: function get() {
24305 return (1 + 0.4 * this.reflectivity) / (1 - 0.4 * this.reflectivity);
24307 set: function set(ior) {
24308 this.reflectivity = MathUtils.clamp(2.5 * (ior - 1) / (ior + 1), 0, 1);
24311 this.sheen = null; // null will disable sheen bsdf
24313 this.transmission = 0.0;
24314 this.transmissionMap = null;
24315 this.setValues(parameters);
24318 MeshPhysicalMaterial.prototype = Object.create(MeshStandardMaterial.prototype);
24319 MeshPhysicalMaterial.prototype.constructor = MeshPhysicalMaterial;
24320 MeshPhysicalMaterial.prototype.isMeshPhysicalMaterial = true;
24322 MeshPhysicalMaterial.prototype.copy = function (source) {
24323 MeshStandardMaterial.prototype.copy.call(this, source);
24328 this.clearcoat = source.clearcoat;
24329 this.clearcoatMap = source.clearcoatMap;
24330 this.clearcoatRoughness = source.clearcoatRoughness;
24331 this.clearcoatRoughnessMap = source.clearcoatRoughnessMap;
24332 this.clearcoatNormalMap = source.clearcoatNormalMap;
24333 this.clearcoatNormalScale.copy(source.clearcoatNormalScale);
24334 this.reflectivity = source.reflectivity;
24336 if (source.sheen) {
24337 this.sheen = (this.sheen || new Color()).copy(source.sheen);
24342 this.transmission = source.transmission;
24343 this.transmissionMap = source.transmissionMap;
24351 * shininess: <float>,
24352 * opacity: <float>,
24354 * map: new THREE.Texture( <Image> ),
24356 * lightMap: new THREE.Texture( <Image> ),
24357 * lightMapIntensity: <float>
24359 * aoMap: new THREE.Texture( <Image> ),
24360 * aoMapIntensity: <float>
24363 * emissiveIntensity: <float>
24364 * emissiveMap: new THREE.Texture( <Image> ),
24366 * bumpMap: new THREE.Texture( <Image> ),
24367 * bumpScale: <float>,
24369 * normalMap: new THREE.Texture( <Image> ),
24370 * normalMapType: THREE.TangentSpaceNormalMap,
24371 * normalScale: <Vector2>,
24373 * displacementMap: new THREE.Texture( <Image> ),
24374 * displacementScale: <float>,
24375 * displacementBias: <float>,
24377 * specularMap: new THREE.Texture( <Image> ),
24379 * alphaMap: new THREE.Texture( <Image> ),
24381 * envMap: new THREE.CubeTexture( [posx, negx, posy, negy, posz, negz] ),
24382 * combine: THREE.MultiplyOperation,
24383 * reflectivity: <float>,
24384 * refractionRatio: <float>,
24386 * wireframe: <boolean>,
24387 * wireframeLinewidth: <float>,
24389 * skinning: <bool>,
24390 * morphTargets: <bool>,
24391 * morphNormals: <bool>
24395 function MeshPhongMaterial(parameters) {
24396 Material.call(this);
24397 this.type = 'MeshPhongMaterial';
24398 this.color = new Color(0xffffff); // diffuse
24400 this.specular = new Color(0x111111);
24401 this.shininess = 30;
24403 this.lightMap = null;
24404 this.lightMapIntensity = 1.0;
24406 this.aoMapIntensity = 1.0;
24407 this.emissive = new Color(0x000000);
24408 this.emissiveIntensity = 1.0;
24409 this.emissiveMap = null;
24410 this.bumpMap = null;
24411 this.bumpScale = 1;
24412 this.normalMap = null;
24413 this.normalMapType = TangentSpaceNormalMap;
24414 this.normalScale = new Vector2(1, 1);
24415 this.displacementMap = null;
24416 this.displacementScale = 1;
24417 this.displacementBias = 0;
24418 this.specularMap = null;
24419 this.alphaMap = null;
24420 this.envMap = null;
24421 this.combine = MultiplyOperation;
24422 this.reflectivity = 1;
24423 this.refractionRatio = 0.98;
24424 this.wireframe = false;
24425 this.wireframeLinewidth = 1;
24426 this.wireframeLinecap = 'round';
24427 this.wireframeLinejoin = 'round';
24428 this.skinning = false;
24429 this.morphTargets = false;
24430 this.morphNormals = false;
24431 this.setValues(parameters);
24434 MeshPhongMaterial.prototype = Object.create(Material.prototype);
24435 MeshPhongMaterial.prototype.constructor = MeshPhongMaterial;
24436 MeshPhongMaterial.prototype.isMeshPhongMaterial = true;
24438 MeshPhongMaterial.prototype.copy = function (source) {
24439 Material.prototype.copy.call(this, source);
24440 this.color.copy(source.color);
24441 this.specular.copy(source.specular);
24442 this.shininess = source.shininess;
24443 this.map = source.map;
24444 this.lightMap = source.lightMap;
24445 this.lightMapIntensity = source.lightMapIntensity;
24446 this.aoMap = source.aoMap;
24447 this.aoMapIntensity = source.aoMapIntensity;
24448 this.emissive.copy(source.emissive);
24449 this.emissiveMap = source.emissiveMap;
24450 this.emissiveIntensity = source.emissiveIntensity;
24451 this.bumpMap = source.bumpMap;
24452 this.bumpScale = source.bumpScale;
24453 this.normalMap = source.normalMap;
24454 this.normalMapType = source.normalMapType;
24455 this.normalScale.copy(source.normalScale);
24456 this.displacementMap = source.displacementMap;
24457 this.displacementScale = source.displacementScale;
24458 this.displacementBias = source.displacementBias;
24459 this.specularMap = source.specularMap;
24460 this.alphaMap = source.alphaMap;
24461 this.envMap = source.envMap;
24462 this.combine = source.combine;
24463 this.reflectivity = source.reflectivity;
24464 this.refractionRatio = source.refractionRatio;
24465 this.wireframe = source.wireframe;
24466 this.wireframeLinewidth = source.wireframeLinewidth;
24467 this.wireframeLinecap = source.wireframeLinecap;
24468 this.wireframeLinejoin = source.wireframeLinejoin;
24469 this.skinning = source.skinning;
24470 this.morphTargets = source.morphTargets;
24471 this.morphNormals = source.morphNormals;
24479 * map: new THREE.Texture( <Image> ),
24480 * gradientMap: new THREE.Texture( <Image> ),
24482 * lightMap: new THREE.Texture( <Image> ),
24483 * lightMapIntensity: <float>
24485 * aoMap: new THREE.Texture( <Image> ),
24486 * aoMapIntensity: <float>
24489 * emissiveIntensity: <float>
24490 * emissiveMap: new THREE.Texture( <Image> ),
24492 * bumpMap: new THREE.Texture( <Image> ),
24493 * bumpScale: <float>,
24495 * normalMap: new THREE.Texture( <Image> ),
24496 * normalMapType: THREE.TangentSpaceNormalMap,
24497 * normalScale: <Vector2>,
24499 * displacementMap: new THREE.Texture( <Image> ),
24500 * displacementScale: <float>,
24501 * displacementBias: <float>,
24503 * alphaMap: new THREE.Texture( <Image> ),
24505 * wireframe: <boolean>,
24506 * wireframeLinewidth: <float>,
24508 * skinning: <bool>,
24509 * morphTargets: <bool>,
24510 * morphNormals: <bool>
24514 function MeshToonMaterial(parameters) {
24515 Material.call(this);
24519 this.type = 'MeshToonMaterial';
24520 this.color = new Color(0xffffff);
24522 this.gradientMap = null;
24523 this.lightMap = null;
24524 this.lightMapIntensity = 1.0;
24526 this.aoMapIntensity = 1.0;
24527 this.emissive = new Color(0x000000);
24528 this.emissiveIntensity = 1.0;
24529 this.emissiveMap = null;
24530 this.bumpMap = null;
24531 this.bumpScale = 1;
24532 this.normalMap = null;
24533 this.normalMapType = TangentSpaceNormalMap;
24534 this.normalScale = new Vector2(1, 1);
24535 this.displacementMap = null;
24536 this.displacementScale = 1;
24537 this.displacementBias = 0;
24538 this.alphaMap = null;
24539 this.wireframe = false;
24540 this.wireframeLinewidth = 1;
24541 this.wireframeLinecap = 'round';
24542 this.wireframeLinejoin = 'round';
24543 this.skinning = false;
24544 this.morphTargets = false;
24545 this.morphNormals = false;
24546 this.setValues(parameters);
24549 MeshToonMaterial.prototype = Object.create(Material.prototype);
24550 MeshToonMaterial.prototype.constructor = MeshToonMaterial;
24551 MeshToonMaterial.prototype.isMeshToonMaterial = true;
24553 MeshToonMaterial.prototype.copy = function (source) {
24554 Material.prototype.copy.call(this, source);
24555 this.color.copy(source.color);
24556 this.map = source.map;
24557 this.gradientMap = source.gradientMap;
24558 this.lightMap = source.lightMap;
24559 this.lightMapIntensity = source.lightMapIntensity;
24560 this.aoMap = source.aoMap;
24561 this.aoMapIntensity = source.aoMapIntensity;
24562 this.emissive.copy(source.emissive);
24563 this.emissiveMap = source.emissiveMap;
24564 this.emissiveIntensity = source.emissiveIntensity;
24565 this.bumpMap = source.bumpMap;
24566 this.bumpScale = source.bumpScale;
24567 this.normalMap = source.normalMap;
24568 this.normalMapType = source.normalMapType;
24569 this.normalScale.copy(source.normalScale);
24570 this.displacementMap = source.displacementMap;
24571 this.displacementScale = source.displacementScale;
24572 this.displacementBias = source.displacementBias;
24573 this.alphaMap = source.alphaMap;
24574 this.wireframe = source.wireframe;
24575 this.wireframeLinewidth = source.wireframeLinewidth;
24576 this.wireframeLinecap = source.wireframeLinecap;
24577 this.wireframeLinejoin = source.wireframeLinejoin;
24578 this.skinning = source.skinning;
24579 this.morphTargets = source.morphTargets;
24580 this.morphNormals = source.morphNormals;
24586 * opacity: <float>,
24588 * bumpMap: new THREE.Texture( <Image> ),
24589 * bumpScale: <float>,
24591 * normalMap: new THREE.Texture( <Image> ),
24592 * normalMapType: THREE.TangentSpaceNormalMap,
24593 * normalScale: <Vector2>,
24595 * displacementMap: new THREE.Texture( <Image> ),
24596 * displacementScale: <float>,
24597 * displacementBias: <float>,
24599 * wireframe: <boolean>,
24600 * wireframeLinewidth: <float>
24602 * skinning: <bool>,
24603 * morphTargets: <bool>,
24604 * morphNormals: <bool>
24608 function MeshNormalMaterial(parameters) {
24609 Material.call(this);
24610 this.type = 'MeshNormalMaterial';
24611 this.bumpMap = null;
24612 this.bumpScale = 1;
24613 this.normalMap = null;
24614 this.normalMapType = TangentSpaceNormalMap;
24615 this.normalScale = new Vector2(1, 1);
24616 this.displacementMap = null;
24617 this.displacementScale = 1;
24618 this.displacementBias = 0;
24619 this.wireframe = false;
24620 this.wireframeLinewidth = 1;
24622 this.skinning = false;
24623 this.morphTargets = false;
24624 this.morphNormals = false;
24625 this.setValues(parameters);
24628 MeshNormalMaterial.prototype = Object.create(Material.prototype);
24629 MeshNormalMaterial.prototype.constructor = MeshNormalMaterial;
24630 MeshNormalMaterial.prototype.isMeshNormalMaterial = true;
24632 MeshNormalMaterial.prototype.copy = function (source) {
24633 Material.prototype.copy.call(this, source);
24634 this.bumpMap = source.bumpMap;
24635 this.bumpScale = source.bumpScale;
24636 this.normalMap = source.normalMap;
24637 this.normalMapType = source.normalMapType;
24638 this.normalScale.copy(source.normalScale);
24639 this.displacementMap = source.displacementMap;
24640 this.displacementScale = source.displacementScale;
24641 this.displacementBias = source.displacementBias;
24642 this.wireframe = source.wireframe;
24643 this.wireframeLinewidth = source.wireframeLinewidth;
24644 this.skinning = source.skinning;
24645 this.morphTargets = source.morphTargets;
24646 this.morphNormals = source.morphNormals;
24653 * opacity: <float>,
24655 * map: new THREE.Texture( <Image> ),
24657 * lightMap: new THREE.Texture( <Image> ),
24658 * lightMapIntensity: <float>
24660 * aoMap: new THREE.Texture( <Image> ),
24661 * aoMapIntensity: <float>
24664 * emissiveIntensity: <float>
24665 * emissiveMap: new THREE.Texture( <Image> ),
24667 * specularMap: new THREE.Texture( <Image> ),
24669 * alphaMap: new THREE.Texture( <Image> ),
24671 * envMap: new THREE.CubeTexture( [posx, negx, posy, negy, posz, negz] ),
24672 * combine: THREE.Multiply,
24673 * reflectivity: <float>,
24674 * refractionRatio: <float>,
24676 * wireframe: <boolean>,
24677 * wireframeLinewidth: <float>,
24679 * skinning: <bool>,
24680 * morphTargets: <bool>,
24681 * morphNormals: <bool>
24685 function MeshLambertMaterial(parameters) {
24686 Material.call(this);
24687 this.type = 'MeshLambertMaterial';
24688 this.color = new Color(0xffffff); // diffuse
24691 this.lightMap = null;
24692 this.lightMapIntensity = 1.0;
24694 this.aoMapIntensity = 1.0;
24695 this.emissive = new Color(0x000000);
24696 this.emissiveIntensity = 1.0;
24697 this.emissiveMap = null;
24698 this.specularMap = null;
24699 this.alphaMap = null;
24700 this.envMap = null;
24701 this.combine = MultiplyOperation;
24702 this.reflectivity = 1;
24703 this.refractionRatio = 0.98;
24704 this.wireframe = false;
24705 this.wireframeLinewidth = 1;
24706 this.wireframeLinecap = 'round';
24707 this.wireframeLinejoin = 'round';
24708 this.skinning = false;
24709 this.morphTargets = false;
24710 this.morphNormals = false;
24711 this.setValues(parameters);
24714 MeshLambertMaterial.prototype = Object.create(Material.prototype);
24715 MeshLambertMaterial.prototype.constructor = MeshLambertMaterial;
24716 MeshLambertMaterial.prototype.isMeshLambertMaterial = true;
24718 MeshLambertMaterial.prototype.copy = function (source) {
24719 Material.prototype.copy.call(this, source);
24720 this.color.copy(source.color);
24721 this.map = source.map;
24722 this.lightMap = source.lightMap;
24723 this.lightMapIntensity = source.lightMapIntensity;
24724 this.aoMap = source.aoMap;
24725 this.aoMapIntensity = source.aoMapIntensity;
24726 this.emissive.copy(source.emissive);
24727 this.emissiveMap = source.emissiveMap;
24728 this.emissiveIntensity = source.emissiveIntensity;
24729 this.specularMap = source.specularMap;
24730 this.alphaMap = source.alphaMap;
24731 this.envMap = source.envMap;
24732 this.combine = source.combine;
24733 this.reflectivity = source.reflectivity;
24734 this.refractionRatio = source.refractionRatio;
24735 this.wireframe = source.wireframe;
24736 this.wireframeLinewidth = source.wireframeLinewidth;
24737 this.wireframeLinecap = source.wireframeLinecap;
24738 this.wireframeLinejoin = source.wireframeLinejoin;
24739 this.skinning = source.skinning;
24740 this.morphTargets = source.morphTargets;
24741 this.morphNormals = source.morphNormals;
24748 * opacity: <float>,
24750 * matcap: new THREE.Texture( <Image> ),
24752 * map: new THREE.Texture( <Image> ),
24754 * bumpMap: new THREE.Texture( <Image> ),
24755 * bumpScale: <float>,
24757 * normalMap: new THREE.Texture( <Image> ),
24758 * normalMapType: THREE.TangentSpaceNormalMap,
24759 * normalScale: <Vector2>,
24761 * displacementMap: new THREE.Texture( <Image> ),
24762 * displacementScale: <float>,
24763 * displacementBias: <float>,
24765 * alphaMap: new THREE.Texture( <Image> ),
24767 * skinning: <bool>,
24768 * morphTargets: <bool>,
24769 * morphNormals: <bool>
24773 function MeshMatcapMaterial(parameters) {
24774 Material.call(this);
24778 this.type = 'MeshMatcapMaterial';
24779 this.color = new Color(0xffffff); // diffuse
24781 this.matcap = null;
24783 this.bumpMap = null;
24784 this.bumpScale = 1;
24785 this.normalMap = null;
24786 this.normalMapType = TangentSpaceNormalMap;
24787 this.normalScale = new Vector2(1, 1);
24788 this.displacementMap = null;
24789 this.displacementScale = 1;
24790 this.displacementBias = 0;
24791 this.alphaMap = null;
24792 this.skinning = false;
24793 this.morphTargets = false;
24794 this.morphNormals = false;
24795 this.setValues(parameters);
24798 MeshMatcapMaterial.prototype = Object.create(Material.prototype);
24799 MeshMatcapMaterial.prototype.constructor = MeshMatcapMaterial;
24800 MeshMatcapMaterial.prototype.isMeshMatcapMaterial = true;
24802 MeshMatcapMaterial.prototype.copy = function (source) {
24803 Material.prototype.copy.call(this, source);
24807 this.color.copy(source.color);
24808 this.matcap = source.matcap;
24809 this.map = source.map;
24810 this.bumpMap = source.bumpMap;
24811 this.bumpScale = source.bumpScale;
24812 this.normalMap = source.normalMap;
24813 this.normalMapType = source.normalMapType;
24814 this.normalScale.copy(source.normalScale);
24815 this.displacementMap = source.displacementMap;
24816 this.displacementScale = source.displacementScale;
24817 this.displacementBias = source.displacementBias;
24818 this.alphaMap = source.alphaMap;
24819 this.skinning = source.skinning;
24820 this.morphTargets = source.morphTargets;
24821 this.morphNormals = source.morphNormals;
24828 * opacity: <float>,
24830 * linewidth: <float>,
24833 * dashSize: <float>,
24838 function LineDashedMaterial(parameters) {
24839 LineBasicMaterial.call(this);
24840 this.type = 'LineDashedMaterial';
24844 this.setValues(parameters);
24847 LineDashedMaterial.prototype = Object.create(LineBasicMaterial.prototype);
24848 LineDashedMaterial.prototype.constructor = LineDashedMaterial;
24849 LineDashedMaterial.prototype.isLineDashedMaterial = true;
24851 LineDashedMaterial.prototype.copy = function (source) {
24852 LineBasicMaterial.prototype.copy.call(this, source);
24853 this.scale = source.scale;
24854 this.dashSize = source.dashSize;
24855 this.gapSize = source.gapSize;
24859 var Materials = /*#__PURE__*/Object.freeze({
24861 ShadowMaterial: ShadowMaterial,
24862 SpriteMaterial: SpriteMaterial,
24863 RawShaderMaterial: RawShaderMaterial,
24864 ShaderMaterial: ShaderMaterial,
24865 PointsMaterial: PointsMaterial,
24866 MeshPhysicalMaterial: MeshPhysicalMaterial,
24867 MeshStandardMaterial: MeshStandardMaterial,
24868 MeshPhongMaterial: MeshPhongMaterial,
24869 MeshToonMaterial: MeshToonMaterial,
24870 MeshNormalMaterial: MeshNormalMaterial,
24871 MeshLambertMaterial: MeshLambertMaterial,
24872 MeshDepthMaterial: MeshDepthMaterial,
24873 MeshDistanceMaterial: MeshDistanceMaterial,
24874 MeshBasicMaterial: MeshBasicMaterial,
24875 MeshMatcapMaterial: MeshMatcapMaterial,
24876 LineDashedMaterial: LineDashedMaterial,
24877 LineBasicMaterial: LineBasicMaterial,
24881 var AnimationUtils = {
24882 // same as Array.prototype.slice, but also works on typed arrays
24883 arraySlice: function arraySlice(array, from, to) {
24884 if (AnimationUtils.isTypedArray(array)) {
24885 // in ios9 array.subarray(from, undefined) will return empty array
24886 // but array.subarray(from) or array.subarray(from, len) is correct
24887 return new array.constructor(array.subarray(from, to !== undefined ? to : array.length));
24890 return array.slice(from, to);
24892 // converts an array to a specific type
24893 convertArray: function convertArray(array, type, forceClone) {
24894 if (!array || // let 'undefined' and 'null' pass
24895 !forceClone && array.constructor === type) return array;
24897 if (typeof type.BYTES_PER_ELEMENT === 'number') {
24898 return new type(array); // create typed array
24901 return Array.prototype.slice.call(array); // create Array
24903 isTypedArray: function isTypedArray(object) {
24904 return ArrayBuffer.isView(object) && !(object instanceof DataView);
24906 // returns an array by which times and values can be sorted
24907 getKeyframeOrder: function getKeyframeOrder(times) {
24908 function compareTime(i, j) {
24909 return times[i] - times[j];
24912 var n = times.length;
24913 var result = new Array(n);
24915 for (var i = 0; i !== n; ++i) {
24919 result.sort(compareTime);
24922 // uses the array previously returned by 'getKeyframeOrder' to sort data
24923 sortedArray: function sortedArray(values, stride, order) {
24924 var nValues = values.length;
24925 var result = new values.constructor(nValues);
24927 for (var i = 0, dstOffset = 0; dstOffset !== nValues; ++i) {
24928 var srcOffset = order[i] * stride;
24930 for (var j = 0; j !== stride; ++j) {
24931 result[dstOffset++] = values[srcOffset + j];
24937 // function for parsing AOS keyframe formats
24938 flattenJSON: function flattenJSON(jsonKeys, times, values, valuePropertyName) {
24942 while (key !== undefined && key[valuePropertyName] === undefined) {
24943 key = jsonKeys[i++];
24946 if (key === undefined) return; // no data
24948 var value = key[valuePropertyName];
24949 if (value === undefined) return; // no data
24951 if (Array.isArray(value)) {
24953 value = key[valuePropertyName];
24955 if (value !== undefined) {
24956 times.push(key.time);
24957 values.push.apply(values, value); // push all elements
24960 key = jsonKeys[i++];
24961 } while (key !== undefined);
24962 } else if (value.toArray !== undefined) {
24963 // ...assume THREE.Math-ish
24965 value = key[valuePropertyName];
24967 if (value !== undefined) {
24968 times.push(key.time);
24969 value.toArray(values, values.length);
24972 key = jsonKeys[i++];
24973 } while (key !== undefined);
24975 // otherwise push as-is
24977 value = key[valuePropertyName];
24979 if (value !== undefined) {
24980 times.push(key.time);
24981 values.push(value);
24984 key = jsonKeys[i++];
24985 } while (key !== undefined);
24988 subclip: function subclip(sourceClip, name, startFrame, endFrame, fps) {
24989 if (fps === void 0) {
24993 var clip = sourceClip.clone();
24997 for (var i = 0; i < clip.tracks.length; ++i) {
24998 var track = clip.tracks[i];
24999 var valueSize = track.getValueSize();
25003 for (var j = 0; j < track.times.length; ++j) {
25004 var frame = track.times[j] * fps;
25005 if (frame < startFrame || frame >= endFrame) continue;
25006 times.push(track.times[j]);
25008 for (var k = 0; k < valueSize; ++k) {
25009 values.push(track.values[j * valueSize + k]);
25013 if (times.length === 0) continue;
25014 track.times = AnimationUtils.convertArray(times, track.times.constructor);
25015 track.values = AnimationUtils.convertArray(values, track.values.constructor);
25016 tracks.push(track);
25019 clip.tracks = tracks; // find minimum .times value across all tracks in the trimmed clip
25021 var minStartTime = Infinity;
25023 for (var _i = 0; _i < clip.tracks.length; ++_i) {
25024 if (minStartTime > clip.tracks[_i].times[0]) {
25025 minStartTime = clip.tracks[_i].times[0];
25027 } // shift all tracks such that clip begins at t=0
25030 for (var _i2 = 0; _i2 < clip.tracks.length; ++_i2) {
25031 clip.tracks[_i2].shift(-1 * minStartTime);
25034 clip.resetDuration();
25037 makeClipAdditive: function makeClipAdditive(targetClip, referenceFrame, referenceClip, fps) {
25038 if (referenceFrame === void 0) {
25039 referenceFrame = 0;
25042 if (referenceClip === void 0) {
25043 referenceClip = targetClip;
25046 if (fps === void 0) {
25050 if (fps <= 0) fps = 30;
25051 var numTracks = referenceClip.tracks.length;
25052 var referenceTime = referenceFrame / fps; // Make each track's values relative to the values at the reference frame
25054 var _loop = function _loop(i) {
25055 var referenceTrack = referenceClip.tracks[i];
25056 var referenceTrackType = referenceTrack.ValueTypeName; // Skip this track if it's non-numeric
25058 if (referenceTrackType === 'bool' || referenceTrackType === 'string') return "continue"; // Find the track in the target clip whose name and type matches the reference track
25060 var targetTrack = targetClip.tracks.find(function (track) {
25061 return track.name === referenceTrack.name && track.ValueTypeName === referenceTrackType;
25063 if (targetTrack === undefined) return "continue";
25064 var referenceOffset = 0;
25065 var referenceValueSize = referenceTrack.getValueSize();
25067 if (referenceTrack.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline) {
25068 referenceOffset = referenceValueSize / 3;
25071 var targetOffset = 0;
25072 var targetValueSize = targetTrack.getValueSize();
25074 if (targetTrack.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline) {
25075 targetOffset = targetValueSize / 3;
25078 var lastIndex = referenceTrack.times.length - 1;
25079 var referenceValue = void 0; // Find the value to subtract out of the track
25081 if (referenceTime <= referenceTrack.times[0]) {
25082 // Reference frame is earlier than the first keyframe, so just use the first keyframe
25083 var startIndex = referenceOffset;
25084 var endIndex = referenceValueSize - referenceOffset;
25085 referenceValue = AnimationUtils.arraySlice(referenceTrack.values, startIndex, endIndex);
25086 } else if (referenceTime >= referenceTrack.times[lastIndex]) {
25087 // Reference frame is after the last keyframe, so just use the last keyframe
25088 var _startIndex = lastIndex * referenceValueSize + referenceOffset;
25090 var _endIndex = _startIndex + referenceValueSize - referenceOffset;
25092 referenceValue = AnimationUtils.arraySlice(referenceTrack.values, _startIndex, _endIndex);
25094 // Interpolate to the reference value
25095 var interpolant = referenceTrack.createInterpolant();
25096 var _startIndex2 = referenceOffset;
25098 var _endIndex2 = referenceValueSize - referenceOffset;
25100 interpolant.evaluate(referenceTime);
25101 referenceValue = AnimationUtils.arraySlice(interpolant.resultBuffer, _startIndex2, _endIndex2);
25102 } // Conjugate the quaternion
25105 if (referenceTrackType === 'quaternion') {
25106 var referenceQuat = new Quaternion().fromArray(referenceValue).normalize().conjugate();
25107 referenceQuat.toArray(referenceValue);
25108 } // Subtract the reference value from all of the track values
25111 var numTimes = targetTrack.times.length;
25113 for (var j = 0; j < numTimes; ++j) {
25114 var valueStart = j * targetValueSize + targetOffset;
25116 if (referenceTrackType === 'quaternion') {
25117 // Multiply the conjugate for quaternion track types
25118 Quaternion.multiplyQuaternionsFlat(targetTrack.values, valueStart, referenceValue, 0, targetTrack.values, valueStart);
25120 var valueEnd = targetValueSize - targetOffset * 2; // Subtract each value for all other numeric track types
25122 for (var k = 0; k < valueEnd; ++k) {
25123 targetTrack.values[valueStart + k] -= referenceValue[k];
25129 for (var i = 0; i < numTracks; ++i) {
25130 var _ret = _loop(i);
25132 if (_ret === "continue") continue;
25135 targetClip.blendMode = AdditiveAnimationBlendMode;
25141 * Abstract base class of interpolants over parametric samples.
25143 * The parameter domain is one dimensional, typically the time or a path
25144 * along a curve defined by the data.
25146 * The sample values can have any dimensionality and derived classes may
25147 * apply special interpretations to the data.
25149 * This class provides the interval seek in a Template Method, deferring
25150 * the actual interpolation to derived classes.
25152 * Time complexity is O(1) for linear access crossing at most two points
25153 * and O(log N) for random access, where N is the number of positions.
25157 * http://www.oodesign.com/template-method-pattern.html
25160 function Interpolant(parameterPositions, sampleValues, sampleSize, resultBuffer) {
25161 this.parameterPositions = parameterPositions;
25162 this._cachedIndex = 0;
25163 this.resultBuffer = resultBuffer !== undefined ? resultBuffer : new sampleValues.constructor(sampleSize);
25164 this.sampleValues = sampleValues;
25165 this.valueSize = sampleSize;
25168 Object.assign(Interpolant.prototype, {
25169 evaluate: function evaluate(t) {
25170 var pp = this.parameterPositions;
25171 var i1 = this._cachedIndex,
25175 validate_interval: {
25180 //- See http://jsperf.com/comparison-to-undefined/3
25183 //- if ( t >= t1 || t1 === undefined ) {
25184 forward_scan: if (!(t < t1)) {
25185 for (var giveUpAt = i1 + 2;;) {
25186 if (t1 === undefined) {
25187 if (t < t0) break forward_scan; // after end
25190 this._cachedIndex = i1;
25191 return this.afterEnd_(i1 - 1, t, t0);
25194 if (i1 === giveUpAt) break; // this loop
25200 // we have arrived at the sought interval
25203 } // prepare binary search on the right side of the index
25209 //- if ( t < t0 || t0 === undefined ) {
25214 var t1global = pp[1];
25216 if (t < t1global) {
25217 i1 = 2; // + 1, using the scan for the details
25220 } // linear reverse scan
25223 for (var _giveUpAt = i1 - 2;;) {
25224 if (t0 === undefined) {
25226 this._cachedIndex = 0;
25227 return this.beforeStart_(0, t, t1);
25230 if (i1 === _giveUpAt) break; // this loop
25236 // we have arrived at the sought interval
25239 } // prepare binary search on the left side of the index
25245 } // the interval is valid
25248 break validate_interval;
25253 while (i1 < right) {
25254 var mid = i1 + right >>> 1;
25264 t0 = pp[i1 - 1]; // check boundary cases, again
25266 if (t0 === undefined) {
25267 this._cachedIndex = 0;
25268 return this.beforeStart_(0, t, t1);
25271 if (t1 === undefined) {
25273 this._cachedIndex = i1;
25274 return this.afterEnd_(i1 - 1, t0, t);
25279 this._cachedIndex = i1;
25280 this.intervalChanged_(i1, t0, t1);
25281 } // validate_interval
25284 return this.interpolate_(i1, t0, t, t1);
25287 // optional, subclass-specific settings structure
25288 // Note: The indirection allows central control of many interpolants.
25289 // --- Protected interface
25290 DefaultSettings_: {},
25291 getSettings_: function getSettings_() {
25292 return this.settings || this.DefaultSettings_;
25294 copySampleValue_: function copySampleValue_(index) {
25295 // copies a sample value to the result buffer
25296 var result = this.resultBuffer,
25297 values = this.sampleValues,
25298 stride = this.valueSize,
25299 offset = index * stride;
25301 for (var i = 0; i !== stride; ++i) {
25302 result[i] = values[offset + i];
25307 // Template methods for derived classes:
25308 interpolate_: function interpolate_()
25309 /* i1, t0, t, t1 */
25311 throw new Error('call to abstract method'); // implementations shall return this.resultBuffer
25313 intervalChanged_: function intervalChanged_()
25317 }); // DECLARE ALIAS AFTER assign prototype
25319 Object.assign(Interpolant.prototype, {
25320 //( 0, t, t0 ), returns this.resultBuffer
25321 beforeStart_: Interpolant.prototype.copySampleValue_,
25322 //( N-1, tN-1, t ), returns this.resultBuffer
25323 afterEnd_: Interpolant.prototype.copySampleValue_
25327 * Fast and simple cubic spline interpolant.
25329 * It was derived from a Hermitian construction setting the first derivative
25330 * at each sample position to the linear slope between neighboring positions
25331 * over their parameter interval.
25334 function CubicInterpolant(parameterPositions, sampleValues, sampleSize, resultBuffer) {
25335 Interpolant.call(this, parameterPositions, sampleValues, sampleSize, resultBuffer);
25336 this._weightPrev = -0;
25337 this._offsetPrev = -0;
25338 this._weightNext = -0;
25339 this._offsetNext = -0;
25342 CubicInterpolant.prototype = Object.assign(Object.create(Interpolant.prototype), {
25343 constructor: CubicInterpolant,
25344 DefaultSettings_: {
25345 endingStart: ZeroCurvatureEnding,
25346 endingEnd: ZeroCurvatureEnding
25348 intervalChanged_: function intervalChanged_(i1, t0, t1) {
25349 var pp = this.parameterPositions;
25350 var iPrev = i1 - 2,
25355 if (tPrev === undefined) {
25356 switch (this.getSettings_().endingStart) {
25357 case ZeroSlopeEnding:
25360 tPrev = 2 * t0 - t1;
25363 case WrapAroundEnding:
25364 // use the other end of the curve
25365 iPrev = pp.length - 2;
25366 tPrev = t0 + pp[iPrev] - pp[iPrev + 1];
25370 // ZeroCurvatureEnding
25371 // f''(t0) = 0 a.k.a. Natural Spline
25377 if (tNext === undefined) {
25378 switch (this.getSettings_().endingEnd) {
25379 case ZeroSlopeEnding:
25382 tNext = 2 * t1 - t0;
25385 case WrapAroundEnding:
25386 // use the other end of the curve
25388 tNext = t1 + pp[1] - pp[0];
25392 // ZeroCurvatureEnding
25393 // f''(tN) = 0, a.k.a. Natural Spline
25399 var halfDt = (t1 - t0) * 0.5,
25400 stride = this.valueSize;
25401 this._weightPrev = halfDt / (t0 - tPrev);
25402 this._weightNext = halfDt / (tNext - t1);
25403 this._offsetPrev = iPrev * stride;
25404 this._offsetNext = iNext * stride;
25406 interpolate_: function interpolate_(i1, t0, t, t1) {
25407 var result = this.resultBuffer,
25408 values = this.sampleValues,
25409 stride = this.valueSize,
25412 oP = this._offsetPrev,
25413 oN = this._offsetNext,
25414 wP = this._weightPrev,
25415 wN = this._weightNext,
25416 p = (t - t0) / (t1 - t0),
25418 ppp = pp * p; // evaluate polynomials
25420 var sP = -wP * ppp + 2 * wP * pp - wP * p;
25421 var s0 = (1 + wP) * ppp + (-1.5 - 2 * wP) * pp + (-0.5 + wP) * p + 1;
25422 var s1 = (-1 - wN) * ppp + (1.5 + wN) * pp + 0.5 * p;
25423 var sN = wN * ppp - wN * pp; // combine data linearly
25425 for (var i = 0; i !== stride; ++i) {
25426 result[i] = sP * values[oP + i] + s0 * values[o0 + i] + s1 * values[o1 + i] + sN * values[oN + i];
25433 function LinearInterpolant(parameterPositions, sampleValues, sampleSize, resultBuffer) {
25434 Interpolant.call(this, parameterPositions, sampleValues, sampleSize, resultBuffer);
25437 LinearInterpolant.prototype = Object.assign(Object.create(Interpolant.prototype), {
25438 constructor: LinearInterpolant,
25439 interpolate_: function interpolate_(i1, t0, t, t1) {
25440 var result = this.resultBuffer,
25441 values = this.sampleValues,
25442 stride = this.valueSize,
25443 offset1 = i1 * stride,
25444 offset0 = offset1 - stride,
25445 weight1 = (t - t0) / (t1 - t0),
25446 weight0 = 1 - weight1;
25448 for (var i = 0; i !== stride; ++i) {
25449 result[i] = values[offset0 + i] * weight0 + values[offset1 + i] * weight1;
25458 * Interpolant that evaluates to the sample value at the position preceeding
25462 function DiscreteInterpolant(parameterPositions, sampleValues, sampleSize, resultBuffer) {
25463 Interpolant.call(this, parameterPositions, sampleValues, sampleSize, resultBuffer);
25466 DiscreteInterpolant.prototype = Object.assign(Object.create(Interpolant.prototype), {
25467 constructor: DiscreteInterpolant,
25468 interpolate_: function interpolate_(i1
25471 return this.copySampleValue_(i1 - 1);
25475 function KeyframeTrack(name, times, values, interpolation) {
25476 if (name === undefined) throw new Error('THREE.KeyframeTrack: track name is undefined');
25477 if (times === undefined || times.length === 0) throw new Error('THREE.KeyframeTrack: no keyframes in track named ' + name);
25479 this.times = AnimationUtils.convertArray(times, this.TimeBufferType);
25480 this.values = AnimationUtils.convertArray(values, this.ValueBufferType);
25481 this.setInterpolation(interpolation || this.DefaultInterpolation);
25482 } // Static methods
25485 Object.assign(KeyframeTrack, {
25486 // Serialization (in static context, because of constructor invocation
25487 // and automatic invocation of .toJSON):
25488 toJSON: function toJSON(track) {
25489 var trackType = track.constructor;
25490 var json; // derived classes can define a static toJSON method
25492 if (trackType.toJSON !== undefined) {
25493 json = trackType.toJSON(track);
25495 // by default, we assume the data can be serialized as-is
25497 'name': track.name,
25498 'times': AnimationUtils.convertArray(track.times, Array),
25499 'values': AnimationUtils.convertArray(track.values, Array)
25501 var interpolation = track.getInterpolation();
25503 if (interpolation !== track.DefaultInterpolation) {
25504 json.interpolation = interpolation;
25508 json.type = track.ValueTypeName; // mandatory
25513 Object.assign(KeyframeTrack.prototype, {
25514 constructor: KeyframeTrack,
25515 TimeBufferType: Float32Array,
25516 ValueBufferType: Float32Array,
25517 DefaultInterpolation: InterpolateLinear,
25518 InterpolantFactoryMethodDiscrete: function InterpolantFactoryMethodDiscrete(result) {
25519 return new DiscreteInterpolant(this.times, this.values, this.getValueSize(), result);
25521 InterpolantFactoryMethodLinear: function InterpolantFactoryMethodLinear(result) {
25522 return new LinearInterpolant(this.times, this.values, this.getValueSize(), result);
25524 InterpolantFactoryMethodSmooth: function InterpolantFactoryMethodSmooth(result) {
25525 return new CubicInterpolant(this.times, this.values, this.getValueSize(), result);
25527 setInterpolation: function setInterpolation(interpolation) {
25530 switch (interpolation) {
25531 case InterpolateDiscrete:
25532 factoryMethod = this.InterpolantFactoryMethodDiscrete;
25535 case InterpolateLinear:
25536 factoryMethod = this.InterpolantFactoryMethodLinear;
25539 case InterpolateSmooth:
25540 factoryMethod = this.InterpolantFactoryMethodSmooth;
25544 if (factoryMethod === undefined) {
25545 var message = 'unsupported interpolation for ' + this.ValueTypeName + ' keyframe track named ' + this.name;
25547 if (this.createInterpolant === undefined) {
25548 // fall back to default, unless the default itself is messed up
25549 if (interpolation !== this.DefaultInterpolation) {
25550 this.setInterpolation(this.DefaultInterpolation);
25552 throw new Error(message); // fatal, in this case
25556 console.warn('THREE.KeyframeTrack:', message);
25560 this.createInterpolant = factoryMethod;
25563 getInterpolation: function getInterpolation() {
25564 switch (this.createInterpolant) {
25565 case this.InterpolantFactoryMethodDiscrete:
25566 return InterpolateDiscrete;
25568 case this.InterpolantFactoryMethodLinear:
25569 return InterpolateLinear;
25571 case this.InterpolantFactoryMethodSmooth:
25572 return InterpolateSmooth;
25575 getValueSize: function getValueSize() {
25576 return this.values.length / this.times.length;
25578 // move all keyframes either forwards or backwards in time
25579 shift: function shift(timeOffset) {
25580 if (timeOffset !== 0.0) {
25581 var times = this.times;
25583 for (var i = 0, n = times.length; i !== n; ++i) {
25584 times[i] += timeOffset;
25590 // scale all keyframe times by a factor (useful for frame <-> seconds conversions)
25591 scale: function scale(timeScale) {
25592 if (timeScale !== 1.0) {
25593 var times = this.times;
25595 for (var i = 0, n = times.length; i !== n; ++i) {
25596 times[i] *= timeScale;
25602 // removes keyframes before and after animation without changing any values within the range [startTime, endTime].
25603 // IMPORTANT: We do not shift around keys to the start of the track time, because for interpolated keys this will change their values
25604 trim: function trim(startTime, endTime) {
25605 var times = this.times,
25606 nKeys = times.length;
25610 while (from !== nKeys && times[from] < startTime) {
25614 while (to !== -1 && times[to] > endTime) {
25618 ++to; // inclusive -> exclusive bound
25620 if (from !== 0 || to !== nKeys) {
25621 // empty tracks are forbidden, so keep at least one keyframe
25623 to = Math.max(to, 1);
25627 var stride = this.getValueSize();
25628 this.times = AnimationUtils.arraySlice(times, from, to);
25629 this.values = AnimationUtils.arraySlice(this.values, from * stride, to * stride);
25634 // ensure we do not get a GarbageInGarbageOut situation, make sure tracks are at least minimally viable
25635 validate: function validate() {
25637 var valueSize = this.getValueSize();
25639 if (valueSize - Math.floor(valueSize) !== 0) {
25640 console.error('THREE.KeyframeTrack: Invalid value size in track.', this);
25644 var times = this.times,
25645 values = this.values,
25646 nKeys = times.length;
25649 console.error('THREE.KeyframeTrack: Track is empty.', this);
25653 var prevTime = null;
25655 for (var i = 0; i !== nKeys; i++) {
25656 var currTime = times[i];
25658 if (typeof currTime === 'number' && isNaN(currTime)) {
25659 console.error('THREE.KeyframeTrack: Time is not a valid number.', this, i, currTime);
25664 if (prevTime !== null && prevTime > currTime) {
25665 console.error('THREE.KeyframeTrack: Out of order keys.', this, i, currTime, prevTime);
25670 prevTime = currTime;
25673 if (values !== undefined) {
25674 if (AnimationUtils.isTypedArray(values)) {
25675 for (var _i = 0, n = values.length; _i !== n; ++_i) {
25676 var value = values[_i];
25678 if (isNaN(value)) {
25679 console.error('THREE.KeyframeTrack: Value is not a valid number.', this, _i, value);
25689 // removes equivalent sequential keys as common in morph target sequences
25690 // (0,0,0,0,1,1,1,0,0,0,0,0,0,0) --> (0,0,1,1,0,0)
25691 optimize: function optimize() {
25692 // times or values may be shared with other tracks, so overwriting is unsafe
25693 var times = AnimationUtils.arraySlice(this.times),
25694 values = AnimationUtils.arraySlice(this.values),
25695 stride = this.getValueSize(),
25696 smoothInterpolation = this.getInterpolation() === InterpolateSmooth,
25697 lastIndex = times.length - 1;
25698 var writeIndex = 1;
25700 for (var i = 1; i < lastIndex; ++i) {
25702 var time = times[i];
25703 var timeNext = times[i + 1]; // remove adjacent keyframes scheduled at the same time
25705 if (time !== timeNext && (i !== 1 || time !== times[0])) {
25706 if (!smoothInterpolation) {
25707 // remove unnecessary keyframes same as their neighbors
25708 var offset = i * stride,
25709 offsetP = offset - stride,
25710 offsetN = offset + stride;
25712 for (var j = 0; j !== stride; ++j) {
25713 var value = values[offset + j];
25715 if (value !== values[offsetP + j] || value !== values[offsetN + j]) {
25723 } // in-place compaction
25727 if (i !== writeIndex) {
25728 times[writeIndex] = times[i];
25729 var readOffset = i * stride,
25730 writeOffset = writeIndex * stride;
25732 for (var _j = 0; _j !== stride; ++_j) {
25733 values[writeOffset + _j] = values[readOffset + _j];
25739 } // flush last keyframe (compaction looks ahead)
25742 if (lastIndex > 0) {
25743 times[writeIndex] = times[lastIndex];
25745 for (var _readOffset = lastIndex * stride, _writeOffset = writeIndex * stride, _j2 = 0; _j2 !== stride; ++_j2) {
25746 values[_writeOffset + _j2] = values[_readOffset + _j2];
25752 if (writeIndex !== times.length) {
25753 this.times = AnimationUtils.arraySlice(times, 0, writeIndex);
25754 this.values = AnimationUtils.arraySlice(values, 0, writeIndex * stride);
25756 this.times = times;
25757 this.values = values;
25762 clone: function clone() {
25763 var times = AnimationUtils.arraySlice(this.times, 0);
25764 var values = AnimationUtils.arraySlice(this.values, 0);
25765 var TypedKeyframeTrack = this.constructor;
25766 var track = new TypedKeyframeTrack(this.name, times, values); // Interpolant argument to constructor is not saved, so copy the factory method directly.
25768 track.createInterpolant = this.createInterpolant;
25774 * A Track of Boolean keyframe values.
25777 function BooleanKeyframeTrack(name, times, values) {
25778 KeyframeTrack.call(this, name, times, values);
25781 BooleanKeyframeTrack.prototype = Object.assign(Object.create(KeyframeTrack.prototype), {
25782 constructor: BooleanKeyframeTrack,
25783 ValueTypeName: 'bool',
25784 ValueBufferType: Array,
25785 DefaultInterpolation: InterpolateDiscrete,
25786 InterpolantFactoryMethodLinear: undefined,
25787 InterpolantFactoryMethodSmooth: undefined // Note: Actually this track could have a optimized / compressed
25788 // representation of a single value and a custom interpolant that
25789 // computes "firstValue ^ isOdd( index )".
25794 * A Track of keyframe values that represent color.
25797 function ColorKeyframeTrack(name, times, values, interpolation) {
25798 KeyframeTrack.call(this, name, times, values, interpolation);
25801 ColorKeyframeTrack.prototype = Object.assign(Object.create(KeyframeTrack.prototype), {
25802 constructor: ColorKeyframeTrack,
25803 ValueTypeName: 'color' // ValueBufferType is inherited
25804 // DefaultInterpolation is inherited
25805 // Note: Very basic implementation and nothing special yet.
25806 // However, this is the place for color space parameterization.
25811 * A Track of numeric keyframe values.
25814 function NumberKeyframeTrack(name, times, values, interpolation) {
25815 KeyframeTrack.call(this, name, times, values, interpolation);
25818 NumberKeyframeTrack.prototype = Object.assign(Object.create(KeyframeTrack.prototype), {
25819 constructor: NumberKeyframeTrack,
25820 ValueTypeName: 'number' // ValueBufferType is inherited
25821 // DefaultInterpolation is inherited
25826 * Spherical linear unit quaternion interpolant.
25829 function QuaternionLinearInterpolant(parameterPositions, sampleValues, sampleSize, resultBuffer) {
25830 Interpolant.call(this, parameterPositions, sampleValues, sampleSize, resultBuffer);
25833 QuaternionLinearInterpolant.prototype = Object.assign(Object.create(Interpolant.prototype), {
25834 constructor: QuaternionLinearInterpolant,
25835 interpolate_: function interpolate_(i1, t0, t, t1) {
25836 var result = this.resultBuffer,
25837 values = this.sampleValues,
25838 stride = this.valueSize,
25839 alpha = (t - t0) / (t1 - t0);
25840 var offset = i1 * stride;
25842 for (var end = offset + stride; offset !== end; offset += 4) {
25843 Quaternion.slerpFlat(result, 0, values, offset - stride, values, offset, alpha);
25851 * A Track of quaternion keyframe values.
25854 function QuaternionKeyframeTrack(name, times, values, interpolation) {
25855 KeyframeTrack.call(this, name, times, values, interpolation);
25858 QuaternionKeyframeTrack.prototype = Object.assign(Object.create(KeyframeTrack.prototype), {
25859 constructor: QuaternionKeyframeTrack,
25860 ValueTypeName: 'quaternion',
25861 // ValueBufferType is inherited
25862 DefaultInterpolation: InterpolateLinear,
25863 InterpolantFactoryMethodLinear: function InterpolantFactoryMethodLinear(result) {
25864 return new QuaternionLinearInterpolant(this.times, this.values, this.getValueSize(), result);
25866 InterpolantFactoryMethodSmooth: undefined // not yet implemented
25871 * A Track that interpolates Strings
25874 function StringKeyframeTrack(name, times, values, interpolation) {
25875 KeyframeTrack.call(this, name, times, values, interpolation);
25878 StringKeyframeTrack.prototype = Object.assign(Object.create(KeyframeTrack.prototype), {
25879 constructor: StringKeyframeTrack,
25880 ValueTypeName: 'string',
25881 ValueBufferType: Array,
25882 DefaultInterpolation: InterpolateDiscrete,
25883 InterpolantFactoryMethodLinear: undefined,
25884 InterpolantFactoryMethodSmooth: undefined
25888 * A Track of vectored keyframe values.
25891 function VectorKeyframeTrack(name, times, values, interpolation) {
25892 KeyframeTrack.call(this, name, times, values, interpolation);
25895 VectorKeyframeTrack.prototype = Object.assign(Object.create(KeyframeTrack.prototype), {
25896 constructor: VectorKeyframeTrack,
25897 ValueTypeName: 'vector' // ValueBufferType is inherited
25898 // DefaultInterpolation is inherited
25902 function AnimationClip(name, duration, tracks, blendMode) {
25903 if (duration === void 0) {
25907 if (blendMode === void 0) {
25908 blendMode = NormalAnimationBlendMode;
25912 this.tracks = tracks;
25913 this.duration = duration;
25914 this.blendMode = blendMode;
25915 this.uuid = MathUtils.generateUUID(); // this means it should figure out its duration by scanning the tracks
25917 if (this.duration < 0) {
25918 this.resetDuration();
25922 function getTrackTypeForValueTypeName(typeName) {
25923 switch (typeName.toLowerCase()) {
25929 return NumberKeyframeTrack;
25935 return VectorKeyframeTrack;
25938 return ColorKeyframeTrack;
25941 return QuaternionKeyframeTrack;
25945 return BooleanKeyframeTrack;
25948 return StringKeyframeTrack;
25951 throw new Error('THREE.KeyframeTrack: Unsupported typeName: ' + typeName);
25954 function parseKeyframeTrack(json) {
25955 if (json.type === undefined) {
25956 throw new Error('THREE.KeyframeTrack: track type undefined, can not parse');
25959 var trackType = getTrackTypeForValueTypeName(json.type);
25961 if (json.times === undefined) {
25964 AnimationUtils.flattenJSON(json.keys, times, values, 'value');
25965 json.times = times;
25966 json.values = values;
25967 } // derived classes can define a static parse method
25970 if (trackType.parse !== undefined) {
25971 return trackType.parse(json);
25973 // by default, we assume a constructor compatible with the base
25974 return new trackType(json.name, json.times, json.values, json.interpolation);
25978 Object.assign(AnimationClip, {
25979 parse: function parse(json) {
25981 jsonTracks = json.tracks,
25982 frameTime = 1.0 / (json.fps || 1.0);
25984 for (var i = 0, n = jsonTracks.length; i !== n; ++i) {
25985 tracks.push(parseKeyframeTrack(jsonTracks[i]).scale(frameTime));
25988 var clip = new AnimationClip(json.name, json.duration, tracks, json.blendMode);
25989 clip.uuid = json.uuid;
25992 toJSON: function toJSON(clip) {
25994 clipTracks = clip.tracks;
25997 'duration': clip.duration,
26000 'blendMode': clip.blendMode
26003 for (var i = 0, n = clipTracks.length; i !== n; ++i) {
26004 tracks.push(KeyframeTrack.toJSON(clipTracks[i]));
26009 CreateFromMorphTargetSequence: function CreateFromMorphTargetSequence(name, morphTargetSequence, fps, noLoop) {
26010 var numMorphTargets = morphTargetSequence.length;
26013 for (var i = 0; i < numMorphTargets; i++) {
26016 times.push((i + numMorphTargets - 1) % numMorphTargets, i, (i + 1) % numMorphTargets);
26017 values.push(0, 1, 0);
26018 var order = AnimationUtils.getKeyframeOrder(times);
26019 times = AnimationUtils.sortedArray(times, 1, order);
26020 values = AnimationUtils.sortedArray(values, 1, order); // if there is a key at the first frame, duplicate it as the
26021 // last frame as well for perfect loop.
26023 if (!noLoop && times[0] === 0) {
26024 times.push(numMorphTargets);
26025 values.push(values[0]);
26028 tracks.push(new NumberKeyframeTrack('.morphTargetInfluences[' + morphTargetSequence[i].name + ']', times, values).scale(1.0 / fps));
26031 return new AnimationClip(name, -1, tracks);
26033 findByName: function findByName(objectOrClipArray, name) {
26034 var clipArray = objectOrClipArray;
26036 if (!Array.isArray(objectOrClipArray)) {
26037 var o = objectOrClipArray;
26038 clipArray = o.geometry && o.geometry.animations || o.animations;
26041 for (var i = 0; i < clipArray.length; i++) {
26042 if (clipArray[i].name === name) {
26043 return clipArray[i];
26049 CreateClipsFromMorphTargetSequences: function CreateClipsFromMorphTargetSequences(morphTargets, fps, noLoop) {
26050 var animationToMorphTargets = {}; // tested with https://regex101.com/ on trick sequences
26051 // such flamingo_flyA_003, flamingo_run1_003, crdeath0059
26053 var pattern = /^([\w-]*?)([\d]+)$/; // sort morph target names into animation groups based
26054 // patterns like Walk_001, Walk_002, Run_001, Run_002
26056 for (var i = 0, il = morphTargets.length; i < il; i++) {
26057 var morphTarget = morphTargets[i];
26058 var parts = morphTarget.name.match(pattern);
26060 if (parts && parts.length > 1) {
26061 var name = parts[1];
26062 var animationMorphTargets = animationToMorphTargets[name];
26064 if (!animationMorphTargets) {
26065 animationToMorphTargets[name] = animationMorphTargets = [];
26068 animationMorphTargets.push(morphTarget);
26074 for (var _name in animationToMorphTargets) {
26075 clips.push(AnimationClip.CreateFromMorphTargetSequence(_name, animationToMorphTargets[_name], fps, noLoop));
26080 // parse the animation.hierarchy format
26081 parseAnimation: function parseAnimation(animation, bones) {
26083 console.error('THREE.AnimationClip: No animation in JSONLoader data.');
26087 var addNonemptyTrack = function addNonemptyTrack(trackType, trackName, animationKeys, propertyName, destTracks) {
26088 // only return track if there are actually keys.
26089 if (animationKeys.length !== 0) {
26092 AnimationUtils.flattenJSON(animationKeys, times, values, propertyName); // empty keys are filtered out, so check again
26094 if (times.length !== 0) {
26095 destTracks.push(new trackType(trackName, times, values));
26101 var clipName = animation.name || 'default';
26102 var fps = animation.fps || 30;
26103 var blendMode = animation.blendMode; // automatic length determination in AnimationClip.
26105 var duration = animation.length || -1;
26106 var hierarchyTracks = animation.hierarchy || [];
26108 for (var h = 0; h < hierarchyTracks.length; h++) {
26109 var animationKeys = hierarchyTracks[h].keys; // skip empty tracks
26111 if (!animationKeys || animationKeys.length === 0) continue; // process morph targets
26113 if (animationKeys[0].morphTargets) {
26114 // figure out all morph targets used in this track
26115 var morphTargetNames = {};
26118 for (k = 0; k < animationKeys.length; k++) {
26119 if (animationKeys[k].morphTargets) {
26120 for (var m = 0; m < animationKeys[k].morphTargets.length; m++) {
26121 morphTargetNames[animationKeys[k].morphTargets[m]] = -1;
26124 } // create a track for each morph target with all zero
26125 // morphTargetInfluences except for the keys in which
26126 // the morphTarget is named.
26129 for (var morphTargetName in morphTargetNames) {
26133 for (var _m = 0; _m !== animationKeys[k].morphTargets.length; ++_m) {
26134 var animationKey = animationKeys[k];
26135 times.push(animationKey.time);
26136 values.push(animationKey.morphTarget === morphTargetName ? 1 : 0);
26139 tracks.push(new NumberKeyframeTrack('.morphTargetInfluence[' + morphTargetName + ']', times, values));
26142 duration = morphTargetNames.length * (fps || 1.0);
26144 // ...assume skeletal animation
26145 var boneName = '.bones[' + bones[h].name + ']';
26146 addNonemptyTrack(VectorKeyframeTrack, boneName + '.position', animationKeys, 'pos', tracks);
26147 addNonemptyTrack(QuaternionKeyframeTrack, boneName + '.quaternion', animationKeys, 'rot', tracks);
26148 addNonemptyTrack(VectorKeyframeTrack, boneName + '.scale', animationKeys, 'scl', tracks);
26152 if (tracks.length === 0) {
26156 var clip = new AnimationClip(clipName, duration, tracks, blendMode);
26160 Object.assign(AnimationClip.prototype, {
26161 resetDuration: function resetDuration() {
26162 var tracks = this.tracks;
26165 for (var i = 0, n = tracks.length; i !== n; ++i) {
26166 var track = this.tracks[i];
26167 duration = Math.max(duration, track.times[track.times.length - 1]);
26170 this.duration = duration;
26173 trim: function trim() {
26174 for (var i = 0; i < this.tracks.length; i++) {
26175 this.tracks[i].trim(0, this.duration);
26180 validate: function validate() {
26183 for (var i = 0; i < this.tracks.length; i++) {
26184 valid = valid && this.tracks[i].validate();
26189 optimize: function optimize() {
26190 for (var i = 0; i < this.tracks.length; i++) {
26191 this.tracks[i].optimize();
26196 clone: function clone() {
26199 for (var i = 0; i < this.tracks.length; i++) {
26200 tracks.push(this.tracks[i].clone());
26203 return new AnimationClip(this.name, this.duration, tracks, this.blendMode);
26205 toJSON: function toJSON() {
26206 return AnimationClip.toJSON(this);
26213 add: function add(key, file) {
26214 if (this.enabled === false) return; // console.log( 'THREE.Cache', 'Adding key:', key );
26216 this.files[key] = file;
26218 get: function get(key) {
26219 if (this.enabled === false) return; // console.log( 'THREE.Cache', 'Checking key:', key );
26221 return this.files[key];
26223 remove: function remove(key) {
26224 delete this.files[key];
26226 clear: function clear() {
26231 function LoadingManager(onLoad, onProgress, onError) {
26233 var isLoading = false;
26234 var itemsLoaded = 0;
26235 var itemsTotal = 0;
26236 var urlModifier = undefined;
26237 var handlers = []; // Refer to #5689 for the reason why we don't set .onStart
26238 // in the constructor
26240 this.onStart = undefined;
26241 this.onLoad = onLoad;
26242 this.onProgress = onProgress;
26243 this.onError = onError;
26245 this.itemStart = function (url) {
26248 if (isLoading === false) {
26249 if (scope.onStart !== undefined) {
26250 scope.onStart(url, itemsLoaded, itemsTotal);
26257 this.itemEnd = function (url) {
26260 if (scope.onProgress !== undefined) {
26261 scope.onProgress(url, itemsLoaded, itemsTotal);
26264 if (itemsLoaded === itemsTotal) {
26267 if (scope.onLoad !== undefined) {
26273 this.itemError = function (url) {
26274 if (scope.onError !== undefined) {
26275 scope.onError(url);
26279 this.resolveURL = function (url) {
26281 return urlModifier(url);
26287 this.setURLModifier = function (transform) {
26288 urlModifier = transform;
26292 this.addHandler = function (regex, loader) {
26293 handlers.push(regex, loader);
26297 this.removeHandler = function (regex) {
26298 var index = handlers.indexOf(regex);
26300 if (index !== -1) {
26301 handlers.splice(index, 2);
26307 this.getHandler = function (file) {
26308 for (var i = 0, l = handlers.length; i < l; i += 2) {
26309 var regex = handlers[i];
26310 var loader = handlers[i + 1];
26311 if (regex.global) regex.lastIndex = 0; // see #17920
26313 if (regex.test(file)) {
26322 var DefaultLoadingManager = new LoadingManager();
26324 function Loader(manager) {
26325 this.manager = manager !== undefined ? manager : DefaultLoadingManager;
26326 this.crossOrigin = 'anonymous';
26327 this.withCredentials = false;
26329 this.resourcePath = '';
26330 this.requestHeader = {};
26333 Object.assign(Loader.prototype, {
26334 load: function load()
26335 /* url, onLoad, onProgress, onError */
26337 loadAsync: function loadAsync(url, onProgress) {
26339 return new Promise(function (resolve, reject) {
26340 scope.load(url, resolve, onProgress, reject);
26343 parse: function parse()
26346 setCrossOrigin: function setCrossOrigin(crossOrigin) {
26347 this.crossOrigin = crossOrigin;
26350 setWithCredentials: function setWithCredentials(value) {
26351 this.withCredentials = value;
26354 setPath: function setPath(path) {
26358 setResourcePath: function setResourcePath(resourcePath) {
26359 this.resourcePath = resourcePath;
26362 setRequestHeader: function setRequestHeader(requestHeader) {
26363 this.requestHeader = requestHeader;
26370 function FileLoader(manager) {
26371 Loader.call(this, manager);
26374 FileLoader.prototype = Object.assign(Object.create(Loader.prototype), {
26375 constructor: FileLoader,
26376 load: function load(url, onLoad, onProgress, onError) {
26377 if (url === undefined) url = '';
26378 if (this.path !== undefined) url = this.path + url;
26379 url = this.manager.resolveURL(url);
26381 var cached = Cache.get(url);
26383 if (cached !== undefined) {
26384 scope.manager.itemStart(url);
26385 setTimeout(function () {
26386 if (onLoad) onLoad(cached);
26387 scope.manager.itemEnd(url);
26390 } // Check if request is duplicate
26393 if (loading[url] !== undefined) {
26394 loading[url].push({
26396 onProgress: onProgress,
26400 } // Check for data: URI
26403 var dataUriRegex = /^data:(.*?)(;base64)?,(.*)$/;
26404 var dataUriRegexResult = url.match(dataUriRegex);
26405 var request; // Safari can not handle Data URIs through XMLHttpRequest so process manually
26407 if (dataUriRegexResult) {
26408 var mimeType = dataUriRegexResult[1];
26409 var isBase64 = !!dataUriRegexResult[2];
26410 var data = dataUriRegexResult[3];
26411 data = decodeURIComponent(data);
26412 if (isBase64) data = atob(data);
26416 var responseType = (this.responseType || '').toLowerCase();
26418 switch (responseType) {
26419 case 'arraybuffer':
26421 var view = new Uint8Array(data.length);
26423 for (var i = 0; i < data.length; i++) {
26424 view[i] = data.charCodeAt(i);
26427 if (responseType === 'blob') {
26428 response = new Blob([view.buffer], {
26432 response = view.buffer;
26438 var parser = new DOMParser();
26439 response = parser.parseFromString(data, mimeType);
26443 response = JSON.parse(data);
26450 } // Wait for next browser tick like standard XMLHttpRequest event dispatching does
26453 setTimeout(function () {
26454 if (onLoad) onLoad(response);
26455 scope.manager.itemEnd(url);
26458 // Wait for next browser tick like standard XMLHttpRequest event dispatching does
26459 setTimeout(function () {
26460 if (onError) onError(error);
26461 scope.manager.itemError(url);
26462 scope.manager.itemEnd(url);
26466 // Initialise array for duplicate requests
26468 loading[url].push({
26470 onProgress: onProgress,
26473 request = new XMLHttpRequest();
26474 request.open('GET', url, true);
26475 request.addEventListener('load', function (event) {
26476 var response = this.response;
26477 var callbacks = loading[url];
26478 delete loading[url];
26480 if (this.status === 200 || this.status === 0) {
26481 // Some browsers return HTTP Status 0 when using non-http protocol
26482 // e.g. 'file://' or 'data://'. Handle as success.
26483 if (this.status === 0) console.warn('THREE.FileLoader: HTTP Status 0 received.'); // Add to cache only on HTTP success, so that we do not cache
26484 // error response bodies as proper responses to requests.
26486 Cache.add(url, response);
26488 for (var _i = 0, il = callbacks.length; _i < il; _i++) {
26489 var callback = callbacks[_i];
26490 if (callback.onLoad) callback.onLoad(response);
26493 scope.manager.itemEnd(url);
26495 for (var _i2 = 0, _il = callbacks.length; _i2 < _il; _i2++) {
26496 var _callback = callbacks[_i2];
26497 if (_callback.onError) _callback.onError(event);
26500 scope.manager.itemError(url);
26501 scope.manager.itemEnd(url);
26504 request.addEventListener('progress', function (event) {
26505 var callbacks = loading[url];
26507 for (var _i3 = 0, il = callbacks.length; _i3 < il; _i3++) {
26508 var callback = callbacks[_i3];
26509 if (callback.onProgress) callback.onProgress(event);
26512 request.addEventListener('error', function (event) {
26513 var callbacks = loading[url];
26514 delete loading[url];
26516 for (var _i4 = 0, il = callbacks.length; _i4 < il; _i4++) {
26517 var callback = callbacks[_i4];
26518 if (callback.onError) callback.onError(event);
26521 scope.manager.itemError(url);
26522 scope.manager.itemEnd(url);
26524 request.addEventListener('abort', function (event) {
26525 var callbacks = loading[url];
26526 delete loading[url];
26528 for (var _i5 = 0, il = callbacks.length; _i5 < il; _i5++) {
26529 var callback = callbacks[_i5];
26530 if (callback.onError) callback.onError(event);
26533 scope.manager.itemError(url);
26534 scope.manager.itemEnd(url);
26536 if (this.responseType !== undefined) request.responseType = this.responseType;
26537 if (this.withCredentials !== undefined) request.withCredentials = this.withCredentials;
26538 if (request.overrideMimeType) request.overrideMimeType(this.mimeType !== undefined ? this.mimeType : 'text/plain');
26540 for (var header in this.requestHeader) {
26541 request.setRequestHeader(header, this.requestHeader[header]);
26544 request.send(null);
26547 scope.manager.itemStart(url);
26550 setResponseType: function setResponseType(value) {
26551 this.responseType = value;
26554 setMimeType: function setMimeType(value) {
26555 this.mimeType = value;
26560 function AnimationLoader(manager) {
26561 Loader.call(this, manager);
26564 AnimationLoader.prototype = Object.assign(Object.create(Loader.prototype), {
26565 constructor: AnimationLoader,
26566 load: function load(url, onLoad, onProgress, onError) {
26568 var loader = new FileLoader(scope.manager);
26569 loader.setPath(scope.path);
26570 loader.setRequestHeader(scope.requestHeader);
26571 loader.setWithCredentials(scope.withCredentials);
26572 loader.load(url, function (text) {
26574 onLoad(scope.parse(JSON.parse(text)));
26582 scope.manager.itemError(url);
26584 }, onProgress, onError);
26586 parse: function parse(json) {
26587 var animations = [];
26589 for (var i = 0; i < json.length; i++) {
26590 var clip = AnimationClip.parse(json[i]);
26591 animations.push(clip);
26599 * Abstract Base class to block based textures loader (dds, pvr, ...)
26601 * Sub classes have to implement the parse() method which will be used in load().
26604 function CompressedTextureLoader(manager) {
26605 Loader.call(this, manager);
26608 CompressedTextureLoader.prototype = Object.assign(Object.create(Loader.prototype), {
26609 constructor: CompressedTextureLoader,
26610 load: function load(url, onLoad, onProgress, onError) {
26613 var texture = new CompressedTexture();
26614 var loader = new FileLoader(this.manager);
26615 loader.setPath(this.path);
26616 loader.setResponseType('arraybuffer');
26617 loader.setRequestHeader(this.requestHeader);
26618 loader.setWithCredentials(scope.withCredentials);
26621 function loadTexture(i) {
26622 loader.load(url[i], function (buffer) {
26623 var texDatas = scope.parse(buffer, true);
26625 width: texDatas.width,
26626 height: texDatas.height,
26627 format: texDatas.format,
26628 mipmaps: texDatas.mipmaps
26632 if (loaded === 6) {
26633 if (texDatas.mipmapCount === 1) texture.minFilter = LinearFilter;
26634 texture.image = images;
26635 texture.format = texDatas.format;
26636 texture.needsUpdate = true;
26637 if (onLoad) onLoad(texture);
26639 }, onProgress, onError);
26642 if (Array.isArray(url)) {
26643 for (var i = 0, il = url.length; i < il; ++i) {
26647 // compressed cubemap texture stored in a single DDS file
26648 loader.load(url, function (buffer) {
26649 var texDatas = scope.parse(buffer, true);
26651 if (texDatas.isCubemap) {
26652 var faces = texDatas.mipmaps.length / texDatas.mipmapCount;
26654 for (var f = 0; f < faces; f++) {
26659 for (var _i = 0; _i < texDatas.mipmapCount; _i++) {
26660 images[f].mipmaps.push(texDatas.mipmaps[f * texDatas.mipmapCount + _i]);
26661 images[f].format = texDatas.format;
26662 images[f].width = texDatas.width;
26663 images[f].height = texDatas.height;
26667 texture.image = images;
26669 texture.image.width = texDatas.width;
26670 texture.image.height = texDatas.height;
26671 texture.mipmaps = texDatas.mipmaps;
26674 if (texDatas.mipmapCount === 1) {
26675 texture.minFilter = LinearFilter;
26678 texture.format = texDatas.format;
26679 texture.needsUpdate = true;
26680 if (onLoad) onLoad(texture);
26681 }, onProgress, onError);
26688 function ImageLoader(manager) {
26689 Loader.call(this, manager);
26692 ImageLoader.prototype = Object.assign(Object.create(Loader.prototype), {
26693 constructor: ImageLoader,
26694 load: function load(url, onLoad, onProgress, onError) {
26695 if (this.path !== undefined) url = this.path + url;
26696 url = this.manager.resolveURL(url);
26698 var cached = Cache.get(url);
26700 if (cached !== undefined) {
26701 scope.manager.itemStart(url);
26702 setTimeout(function () {
26703 if (onLoad) onLoad(cached);
26704 scope.manager.itemEnd(url);
26709 var image = document.createElementNS('http://www.w3.org/1999/xhtml', 'img');
26711 function onImageLoad() {
26712 image.removeEventListener('load', onImageLoad, false);
26713 image.removeEventListener('error', onImageError, false);
26714 Cache.add(url, this);
26715 if (onLoad) onLoad(this);
26716 scope.manager.itemEnd(url);
26719 function onImageError(event) {
26720 image.removeEventListener('load', onImageLoad, false);
26721 image.removeEventListener('error', onImageError, false);
26722 if (onError) onError(event);
26723 scope.manager.itemError(url);
26724 scope.manager.itemEnd(url);
26727 image.addEventListener('load', onImageLoad, false);
26728 image.addEventListener('error', onImageError, false);
26730 if (url.substr(0, 5) !== 'data:') {
26731 if (this.crossOrigin !== undefined) image.crossOrigin = this.crossOrigin;
26734 scope.manager.itemStart(url);
26740 function CubeTextureLoader(manager) {
26741 Loader.call(this, manager);
26744 CubeTextureLoader.prototype = Object.assign(Object.create(Loader.prototype), {
26745 constructor: CubeTextureLoader,
26746 load: function load(urls, onLoad, onProgress, onError) {
26747 var texture = new CubeTexture();
26748 var loader = new ImageLoader(this.manager);
26749 loader.setCrossOrigin(this.crossOrigin);
26750 loader.setPath(this.path);
26753 function loadTexture(i) {
26754 loader.load(urls[i], function (image) {
26755 texture.images[i] = image;
26758 if (loaded === 6) {
26759 texture.needsUpdate = true;
26760 if (onLoad) onLoad(texture);
26762 }, undefined, onError);
26765 for (var i = 0; i < urls.length; ++i) {
26774 * Abstract Base class to load generic binary textures formats (rgbe, hdr, ...)
26776 * Sub classes have to implement the parse() method which will be used in load().
26779 function DataTextureLoader(manager) {
26780 Loader.call(this, manager);
26783 DataTextureLoader.prototype = Object.assign(Object.create(Loader.prototype), {
26784 constructor: DataTextureLoader,
26785 load: function load(url, onLoad, onProgress, onError) {
26787 var texture = new DataTexture();
26788 var loader = new FileLoader(this.manager);
26789 loader.setResponseType('arraybuffer');
26790 loader.setRequestHeader(this.requestHeader);
26791 loader.setPath(this.path);
26792 loader.setWithCredentials(scope.withCredentials);
26793 loader.load(url, function (buffer) {
26794 var texData = scope.parse(buffer);
26795 if (!texData) return;
26797 if (texData.image !== undefined) {
26798 texture.image = texData.image;
26799 } else if (texData.data !== undefined) {
26800 texture.image.width = texData.width;
26801 texture.image.height = texData.height;
26802 texture.image.data = texData.data;
26805 texture.wrapS = texData.wrapS !== undefined ? texData.wrapS : ClampToEdgeWrapping;
26806 texture.wrapT = texData.wrapT !== undefined ? texData.wrapT : ClampToEdgeWrapping;
26807 texture.magFilter = texData.magFilter !== undefined ? texData.magFilter : LinearFilter;
26808 texture.minFilter = texData.minFilter !== undefined ? texData.minFilter : LinearFilter;
26809 texture.anisotropy = texData.anisotropy !== undefined ? texData.anisotropy : 1;
26811 if (texData.encoding !== undefined) {
26812 texture.encoding = texData.encoding;
26815 if (texData.flipY !== undefined) {
26816 texture.flipY = texData.flipY;
26819 if (texData.format !== undefined) {
26820 texture.format = texData.format;
26823 if (texData.type !== undefined) {
26824 texture.type = texData.type;
26827 if (texData.mipmaps !== undefined) {
26828 texture.mipmaps = texData.mipmaps;
26829 texture.minFilter = LinearMipmapLinearFilter; // presumably...
26832 if (texData.mipmapCount === 1) {
26833 texture.minFilter = LinearFilter;
26836 texture.needsUpdate = true;
26837 if (onLoad) onLoad(texture, texData);
26838 }, onProgress, onError);
26843 function TextureLoader(manager) {
26844 Loader.call(this, manager);
26847 TextureLoader.prototype = Object.assign(Object.create(Loader.prototype), {
26848 constructor: TextureLoader,
26849 load: function load(url, onLoad, onProgress, onError) {
26850 var texture = new Texture();
26851 var loader = new ImageLoader(this.manager);
26852 loader.setCrossOrigin(this.crossOrigin);
26853 loader.setPath(this.path);
26854 loader.load(url, function (image) {
26855 texture.image = image; // JPEGs can't have an alpha channel, so memory can be saved by storing them as RGB.
26857 var isJPEG = url.search(/\.jpe?g($|\?)/i) > 0 || url.search(/^data\:image\/jpeg/) === 0;
26858 texture.format = isJPEG ? RGBFormat : RGBAFormat;
26859 texture.needsUpdate = true;
26861 if (onLoad !== undefined) {
26864 }, onProgress, onError);
26870 * Extensible curve object.
26872 * Some common of curve methods:
26873 * .getPoint( t, optionalTarget ), .getTangent( t, optionalTarget )
26874 * .getPointAt( u, optionalTarget ), .getTangentAt( u, optionalTarget )
26875 * .getPoints(), .getSpacedPoints()
26877 * .updateArcLengths()
26879 * This following curves inherit from THREE.Curve:
26883 * THREE.CubicBezierCurve
26884 * THREE.EllipseCurve
26886 * THREE.QuadraticBezierCurve
26887 * THREE.SplineCurve
26890 * THREE.CatmullRomCurve3
26891 * THREE.CubicBezierCurve3
26893 * THREE.QuadraticBezierCurve3
26895 * A series of curves can be represented as a THREE.CurvePath.
26900 this.type = 'Curve';
26901 this.arcLengthDivisions = 200;
26904 Object.assign(Curve.prototype, {
26905 // Virtual base class method to overwrite and implement in subclasses
26907 getPoint: function getPoint()
26908 /* t, optionalTarget */
26910 console.warn('THREE.Curve: .getPoint() not implemented.');
26913 // Get point at relative position in curve according to arc length
26915 getPointAt: function getPointAt(u, optionalTarget) {
26916 var t = this.getUtoTmapping(u);
26917 return this.getPoint(t, optionalTarget);
26919 // Get sequence of points using getPoint( t )
26920 getPoints: function getPoints(divisions) {
26921 if (divisions === void 0) {
26927 for (var d = 0; d <= divisions; d++) {
26928 points.push(this.getPoint(d / divisions));
26933 // Get sequence of points using getPointAt( u )
26934 getSpacedPoints: function getSpacedPoints(divisions) {
26935 if (divisions === void 0) {
26941 for (var d = 0; d <= divisions; d++) {
26942 points.push(this.getPointAt(d / divisions));
26947 // Get total curve arc length
26948 getLength: function getLength() {
26949 var lengths = this.getLengths();
26950 return lengths[lengths.length - 1];
26952 // Get list of cumulative segment lengths
26953 getLengths: function getLengths(divisions) {
26954 if (divisions === undefined) divisions = this.arcLengthDivisions;
26956 if (this.cacheArcLengths && this.cacheArcLengths.length === divisions + 1 && !this.needsUpdate) {
26957 return this.cacheArcLengths;
26960 this.needsUpdate = false;
26963 last = this.getPoint(0);
26967 for (var p = 1; p <= divisions; p++) {
26968 current = this.getPoint(p / divisions);
26969 sum += current.distanceTo(last);
26974 this.cacheArcLengths = cache;
26975 return cache; // { sums: cache, sum: sum }; Sum is in the last element.
26977 updateArcLengths: function updateArcLengths() {
26978 this.needsUpdate = true;
26981 // Given u ( 0 .. 1 ), get a t to find p. This gives you points which are equidistant
26982 getUtoTmapping: function getUtoTmapping(u, distance) {
26983 var arcLengths = this.getLengths();
26985 var il = arcLengths.length;
26986 var targetArcLength; // The targeted u distance value to get
26989 targetArcLength = distance;
26991 targetArcLength = u * arcLengths[il - 1];
26992 } // binary search for the index with largest value smaller than target u distance
26999 while (low <= high) {
27000 i = Math.floor(low + (high - low) / 2); // less likely to overflow, though probably not issue here, JS doesn't really have integers, all numbers are floats
27002 comparison = arcLengths[i] - targetArcLength;
27004 if (comparison < 0) {
27006 } else if (comparison > 0) {
27016 if (arcLengths[i] === targetArcLength) {
27017 return i / (il - 1);
27018 } // we could get finer grain at lengths, or use simple interpolation between two points
27021 var lengthBefore = arcLengths[i];
27022 var lengthAfter = arcLengths[i + 1];
27023 var segmentLength = lengthAfter - lengthBefore; // determine where we are between the 'before' and 'after' points
27025 var segmentFraction = (targetArcLength - lengthBefore) / segmentLength; // add that fractional amount to t
27027 var t = (i + segmentFraction) / (il - 1);
27030 // Returns a unit vector tangent at t
27031 // In case any sub curve does not implement its tangent derivation,
27032 // 2 points a small delta apart will be used to find its gradient
27033 // which seems to give a reasonable approximation
27034 getTangent: function getTangent(t, optionalTarget) {
27035 var delta = 0.0001;
27036 var t1 = t - delta;
27037 var t2 = t + delta; // Capping in case of danger
27039 if (t1 < 0) t1 = 0;
27040 if (t2 > 1) t2 = 1;
27041 var pt1 = this.getPoint(t1);
27042 var pt2 = this.getPoint(t2);
27043 var tangent = optionalTarget || (pt1.isVector2 ? new Vector2() : new Vector3());
27044 tangent.copy(pt2).sub(pt1).normalize();
27047 getTangentAt: function getTangentAt(u, optionalTarget) {
27048 var t = this.getUtoTmapping(u);
27049 return this.getTangent(t, optionalTarget);
27051 computeFrenetFrames: function computeFrenetFrames(segments, closed) {
27052 // see http://www.cs.indiana.edu/pub/techreports/TR425.pdf
27053 var normal = new Vector3();
27056 var binormals = [];
27057 var vec = new Vector3();
27058 var mat = new Matrix4(); // compute the tangent vectors for each segment on the curve
27060 for (var i = 0; i <= segments; i++) {
27061 var u = i / segments;
27062 tangents[i] = this.getTangentAt(u, new Vector3());
27063 tangents[i].normalize();
27064 } // select an initial normal vector perpendicular to the first tangent vector,
27065 // and in the direction of the minimum tangent xyz component
27068 normals[0] = new Vector3();
27069 binormals[0] = new Vector3();
27070 var min = Number.MAX_VALUE;
27071 var tx = Math.abs(tangents[0].x);
27072 var ty = Math.abs(tangents[0].y);
27073 var tz = Math.abs(tangents[0].z);
27077 normal.set(1, 0, 0);
27082 normal.set(0, 1, 0);
27086 normal.set(0, 0, 1);
27089 vec.crossVectors(tangents[0], normal).normalize();
27090 normals[0].crossVectors(tangents[0], vec);
27091 binormals[0].crossVectors(tangents[0], normals[0]); // compute the slowly-varying normal and binormal vectors for each segment on the curve
27093 for (var _i = 1; _i <= segments; _i++) {
27094 normals[_i] = normals[_i - 1].clone();
27095 binormals[_i] = binormals[_i - 1].clone();
27096 vec.crossVectors(tangents[_i - 1], tangents[_i]);
27098 if (vec.length() > Number.EPSILON) {
27100 var theta = Math.acos(MathUtils.clamp(tangents[_i - 1].dot(tangents[_i]), -1, 1)); // clamp for floating pt errors
27102 normals[_i].applyMatrix4(mat.makeRotationAxis(vec, theta));
27105 binormals[_i].crossVectors(tangents[_i], normals[_i]);
27106 } // if the curve is closed, postprocess the vectors so the first and last normal vectors are the same
27109 if (closed === true) {
27110 var _theta = Math.acos(MathUtils.clamp(normals[0].dot(normals[segments]), -1, 1));
27112 _theta /= segments;
27114 if (tangents[0].dot(vec.crossVectors(normals[0], normals[segments])) > 0) {
27118 for (var _i2 = 1; _i2 <= segments; _i2++) {
27119 // twist a little...
27120 normals[_i2].applyMatrix4(mat.makeRotationAxis(tangents[_i2], _theta * _i2));
27122 binormals[_i2].crossVectors(tangents[_i2], normals[_i2]);
27127 tangents: tangents,
27129 binormals: binormals
27132 clone: function clone() {
27133 return new this.constructor().copy(this);
27135 copy: function copy(source) {
27136 this.arcLengthDivisions = source.arcLengthDivisions;
27139 toJSON: function toJSON() {
27144 generator: 'Curve.toJSON'
27147 data.arcLengthDivisions = this.arcLengthDivisions;
27148 data.type = this.type;
27151 fromJSON: function fromJSON(json) {
27152 this.arcLengthDivisions = json.arcLengthDivisions;
27157 function EllipseCurve(aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation) {
27159 this.type = 'EllipseCurve';
27162 this.xRadius = xRadius || 1;
27163 this.yRadius = yRadius || 1;
27164 this.aStartAngle = aStartAngle || 0;
27165 this.aEndAngle = aEndAngle || 2 * Math.PI;
27166 this.aClockwise = aClockwise || false;
27167 this.aRotation = aRotation || 0;
27170 EllipseCurve.prototype = Object.create(Curve.prototype);
27171 EllipseCurve.prototype.constructor = EllipseCurve;
27172 EllipseCurve.prototype.isEllipseCurve = true;
27174 EllipseCurve.prototype.getPoint = function (t, optionalTarget) {
27175 var point = optionalTarget || new Vector2();
27176 var twoPi = Math.PI * 2;
27177 var deltaAngle = this.aEndAngle - this.aStartAngle;
27178 var samePoints = Math.abs(deltaAngle) < Number.EPSILON; // ensures that deltaAngle is 0 .. 2 PI
27180 while (deltaAngle < 0) {
27181 deltaAngle += twoPi;
27184 while (deltaAngle > twoPi) {
27185 deltaAngle -= twoPi;
27188 if (deltaAngle < Number.EPSILON) {
27192 deltaAngle = twoPi;
27196 if (this.aClockwise === true && !samePoints) {
27197 if (deltaAngle === twoPi) {
27198 deltaAngle = -twoPi;
27200 deltaAngle = deltaAngle - twoPi;
27204 var angle = this.aStartAngle + t * deltaAngle;
27205 var x = this.aX + this.xRadius * Math.cos(angle);
27206 var y = this.aY + this.yRadius * Math.sin(angle);
27208 if (this.aRotation !== 0) {
27209 var cos = Math.cos(this.aRotation);
27210 var sin = Math.sin(this.aRotation);
27211 var tx = x - this.aX;
27212 var ty = y - this.aY; // Rotate the point about the center of the ellipse.
27214 x = tx * cos - ty * sin + this.aX;
27215 y = tx * sin + ty * cos + this.aY;
27218 return point.set(x, y);
27221 EllipseCurve.prototype.copy = function (source) {
27222 Curve.prototype.copy.call(this, source);
27223 this.aX = source.aX;
27224 this.aY = source.aY;
27225 this.xRadius = source.xRadius;
27226 this.yRadius = source.yRadius;
27227 this.aStartAngle = source.aStartAngle;
27228 this.aEndAngle = source.aEndAngle;
27229 this.aClockwise = source.aClockwise;
27230 this.aRotation = source.aRotation;
27234 EllipseCurve.prototype.toJSON = function () {
27235 var data = Curve.prototype.toJSON.call(this);
27238 data.xRadius = this.xRadius;
27239 data.yRadius = this.yRadius;
27240 data.aStartAngle = this.aStartAngle;
27241 data.aEndAngle = this.aEndAngle;
27242 data.aClockwise = this.aClockwise;
27243 data.aRotation = this.aRotation;
27247 EllipseCurve.prototype.fromJSON = function (json) {
27248 Curve.prototype.fromJSON.call(this, json);
27251 this.xRadius = json.xRadius;
27252 this.yRadius = json.yRadius;
27253 this.aStartAngle = json.aStartAngle;
27254 this.aEndAngle = json.aEndAngle;
27255 this.aClockwise = json.aClockwise;
27256 this.aRotation = json.aRotation;
27260 function ArcCurve(aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise) {
27261 EllipseCurve.call(this, aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise);
27262 this.type = 'ArcCurve';
27265 ArcCurve.prototype = Object.create(EllipseCurve.prototype);
27266 ArcCurve.prototype.constructor = ArcCurve;
27267 ArcCurve.prototype.isArcCurve = true;
27270 * Centripetal CatmullRom Curve - which is useful for avoiding
27271 * cusps and self-intersections in non-uniform catmull rom curves.
27272 * http://www.cemyuksel.com/research/catmullrom_param/catmullrom.pdf
27274 * curve.type accepts centripetal(default), chordal and catmullrom
27275 * curve.tension is used for catmullrom which defaults to 0.5
27279 Based on an optimized c++ solution in
27280 - http://stackoverflow.com/questions/9489736/catmull-rom-curve-with-no-cusps-and-no-self-intersections/
27281 - http://ideone.com/NoEbVM
27283 This CubicPoly class could be used for reusing some variables and calculations,
27284 but for three.js curve use, it could be possible inlined and flatten into a single function call
27285 which can be placed in CurveUtils.
27288 function CubicPoly() {
27294 * Compute coefficients for a cubic polynomial
27295 * p(s) = c0 + c1*s + c2*s^2 + c3*s^3
27297 * p(0) = x0, p(1) = x1
27299 * p'(0) = t0, p'(1) = t1.
27302 function init(x0, x1, t0, t1) {
27305 c2 = -3 * x0 + 3 * x1 - 2 * t0 - t1;
27306 c3 = 2 * x0 - 2 * x1 + t0 + t1;
27310 initCatmullRom: function initCatmullRom(x0, x1, x2, x3, tension) {
27311 init(x1, x2, tension * (x2 - x0), tension * (x3 - x1));
27313 initNonuniformCatmullRom: function initNonuniformCatmullRom(x0, x1, x2, x3, dt0, dt1, dt2) {
27314 // compute tangents when parameterized in [t1,t2]
27315 var t1 = (x1 - x0) / dt0 - (x2 - x0) / (dt0 + dt1) + (x2 - x1) / dt1;
27316 var t2 = (x2 - x1) / dt1 - (x3 - x1) / (dt1 + dt2) + (x3 - x2) / dt2; // rescale tangents for parametrization in [0,1]
27320 init(x1, x2, t1, t2);
27322 calc: function calc(t) {
27325 return c0 + c1 * t + c2 * t2 + c3 * t3;
27331 var tmp = new Vector3();
27332 var px = new CubicPoly(),
27333 py = new CubicPoly(),
27334 pz = new CubicPoly();
27336 function CatmullRomCurve3(points, closed, curveType, tension) {
27337 if (points === void 0) {
27341 if (closed === void 0) {
27345 if (curveType === void 0) {
27346 curveType = 'centripetal';
27349 if (tension === void 0) {
27354 this.type = 'CatmullRomCurve3';
27355 this.points = points;
27356 this.closed = closed;
27357 this.curveType = curveType;
27358 this.tension = tension;
27361 CatmullRomCurve3.prototype = Object.create(Curve.prototype);
27362 CatmullRomCurve3.prototype.constructor = CatmullRomCurve3;
27363 CatmullRomCurve3.prototype.isCatmullRomCurve3 = true;
27365 CatmullRomCurve3.prototype.getPoint = function (t, optionalTarget) {
27366 if (optionalTarget === void 0) {
27367 optionalTarget = new Vector3();
27370 var point = optionalTarget;
27371 var points = this.points;
27372 var l = points.length;
27373 var p = (l - (this.closed ? 0 : 1)) * t;
27374 var intPoint = Math.floor(p);
27375 var weight = p - intPoint;
27378 intPoint += intPoint > 0 ? 0 : (Math.floor(Math.abs(intPoint) / l) + 1) * l;
27379 } else if (weight === 0 && intPoint === l - 1) {
27384 var p0, p3; // 4 points (p1 & p2 defined below)
27386 if (this.closed || intPoint > 0) {
27387 p0 = points[(intPoint - 1) % l];
27389 // extrapolate first point
27390 tmp.subVectors(points[0], points[1]).add(points[0]);
27394 var p1 = points[intPoint % l];
27395 var p2 = points[(intPoint + 1) % l];
27397 if (this.closed || intPoint + 2 < l) {
27398 p3 = points[(intPoint + 2) % l];
27400 // extrapolate last point
27401 tmp.subVectors(points[l - 1], points[l - 2]).add(points[l - 1]);
27405 if (this.curveType === 'centripetal' || this.curveType === 'chordal') {
27406 // init Centripetal / Chordal Catmull-Rom
27407 var pow = this.curveType === 'chordal' ? 0.5 : 0.25;
27408 var dt0 = Math.pow(p0.distanceToSquared(p1), pow);
27409 var dt1 = Math.pow(p1.distanceToSquared(p2), pow);
27410 var dt2 = Math.pow(p2.distanceToSquared(p3), pow); // safety check for repeated points
27412 if (dt1 < 1e-4) dt1 = 1.0;
27413 if (dt0 < 1e-4) dt0 = dt1;
27414 if (dt2 < 1e-4) dt2 = dt1;
27415 px.initNonuniformCatmullRom(p0.x, p1.x, p2.x, p3.x, dt0, dt1, dt2);
27416 py.initNonuniformCatmullRom(p0.y, p1.y, p2.y, p3.y, dt0, dt1, dt2);
27417 pz.initNonuniformCatmullRom(p0.z, p1.z, p2.z, p3.z, dt0, dt1, dt2);
27418 } else if (this.curveType === 'catmullrom') {
27419 px.initCatmullRom(p0.x, p1.x, p2.x, p3.x, this.tension);
27420 py.initCatmullRom(p0.y, p1.y, p2.y, p3.y, this.tension);
27421 pz.initCatmullRom(p0.z, p1.z, p2.z, p3.z, this.tension);
27424 point.set(px.calc(weight), py.calc(weight), pz.calc(weight));
27428 CatmullRomCurve3.prototype.copy = function (source) {
27429 Curve.prototype.copy.call(this, source);
27432 for (var i = 0, l = source.points.length; i < l; i++) {
27433 var point = source.points[i];
27434 this.points.push(point.clone());
27437 this.closed = source.closed;
27438 this.curveType = source.curveType;
27439 this.tension = source.tension;
27443 CatmullRomCurve3.prototype.toJSON = function () {
27444 var data = Curve.prototype.toJSON.call(this);
27447 for (var i = 0, l = this.points.length; i < l; i++) {
27448 var point = this.points[i];
27449 data.points.push(point.toArray());
27452 data.closed = this.closed;
27453 data.curveType = this.curveType;
27454 data.tension = this.tension;
27458 CatmullRomCurve3.prototype.fromJSON = function (json) {
27459 Curve.prototype.fromJSON.call(this, json);
27462 for (var i = 0, l = json.points.length; i < l; i++) {
27463 var point = json.points[i];
27464 this.points.push(new Vector3().fromArray(point));
27467 this.closed = json.closed;
27468 this.curveType = json.curveType;
27469 this.tension = json.tension;
27474 * Bezier Curves formulas obtained from
27475 * http://en.wikipedia.org/wiki/Bézier_curve
27477 function CatmullRom(t, p0, p1, p2, p3) {
27478 var v0 = (p2 - p0) * 0.5;
27479 var v1 = (p3 - p1) * 0.5;
27482 return (2 * p1 - 2 * p2 + v0 + v1) * t3 + (-3 * p1 + 3 * p2 - 2 * v0 - v1) * t2 + v0 * t + p1;
27486 function QuadraticBezierP0(t, p) {
27491 function QuadraticBezierP1(t, p) {
27492 return 2 * (1 - t) * t * p;
27495 function QuadraticBezierP2(t, p) {
27499 function QuadraticBezier(t, p0, p1, p2) {
27500 return QuadraticBezierP0(t, p0) + QuadraticBezierP1(t, p1) + QuadraticBezierP2(t, p2);
27504 function CubicBezierP0(t, p) {
27506 return k * k * k * p;
27509 function CubicBezierP1(t, p) {
27511 return 3 * k * k * t * p;
27514 function CubicBezierP2(t, p) {
27515 return 3 * (1 - t) * t * t * p;
27518 function CubicBezierP3(t, p) {
27519 return t * t * t * p;
27522 function CubicBezier(t, p0, p1, p2, p3) {
27523 return CubicBezierP0(t, p0) + CubicBezierP1(t, p1) + CubicBezierP2(t, p2) + CubicBezierP3(t, p3);
27526 function CubicBezierCurve(v0, v1, v2, v3) {
27527 if (v0 === void 0) {
27528 v0 = new Vector2();
27531 if (v1 === void 0) {
27532 v1 = new Vector2();
27535 if (v2 === void 0) {
27536 v2 = new Vector2();
27539 if (v3 === void 0) {
27540 v3 = new Vector2();
27544 this.type = 'CubicBezierCurve';
27551 CubicBezierCurve.prototype = Object.create(Curve.prototype);
27552 CubicBezierCurve.prototype.constructor = CubicBezierCurve;
27553 CubicBezierCurve.prototype.isCubicBezierCurve = true;
27555 CubicBezierCurve.prototype.getPoint = function (t, optionalTarget) {
27556 if (optionalTarget === void 0) {
27557 optionalTarget = new Vector2();
27560 var point = optionalTarget;
27565 point.set(CubicBezier(t, v0.x, v1.x, v2.x, v3.x), CubicBezier(t, v0.y, v1.y, v2.y, v3.y));
27569 CubicBezierCurve.prototype.copy = function (source) {
27570 Curve.prototype.copy.call(this, source);
27571 this.v0.copy(source.v0);
27572 this.v1.copy(source.v1);
27573 this.v2.copy(source.v2);
27574 this.v3.copy(source.v3);
27578 CubicBezierCurve.prototype.toJSON = function () {
27579 var data = Curve.prototype.toJSON.call(this);
27580 data.v0 = this.v0.toArray();
27581 data.v1 = this.v1.toArray();
27582 data.v2 = this.v2.toArray();
27583 data.v3 = this.v3.toArray();
27587 CubicBezierCurve.prototype.fromJSON = function (json) {
27588 Curve.prototype.fromJSON.call(this, json);
27589 this.v0.fromArray(json.v0);
27590 this.v1.fromArray(json.v1);
27591 this.v2.fromArray(json.v2);
27592 this.v3.fromArray(json.v3);
27596 function CubicBezierCurve3(v0, v1, v2, v3) {
27597 if (v0 === void 0) {
27598 v0 = new Vector3();
27601 if (v1 === void 0) {
27602 v1 = new Vector3();
27605 if (v2 === void 0) {
27606 v2 = new Vector3();
27609 if (v3 === void 0) {
27610 v3 = new Vector3();
27614 this.type = 'CubicBezierCurve3';
27621 CubicBezierCurve3.prototype = Object.create(Curve.prototype);
27622 CubicBezierCurve3.prototype.constructor = CubicBezierCurve3;
27623 CubicBezierCurve3.prototype.isCubicBezierCurve3 = true;
27625 CubicBezierCurve3.prototype.getPoint = function (t, optionalTarget) {
27626 if (optionalTarget === void 0) {
27627 optionalTarget = new Vector3();
27630 var point = optionalTarget;
27635 point.set(CubicBezier(t, v0.x, v1.x, v2.x, v3.x), CubicBezier(t, v0.y, v1.y, v2.y, v3.y), CubicBezier(t, v0.z, v1.z, v2.z, v3.z));
27639 CubicBezierCurve3.prototype.copy = function (source) {
27640 Curve.prototype.copy.call(this, source);
27641 this.v0.copy(source.v0);
27642 this.v1.copy(source.v1);
27643 this.v2.copy(source.v2);
27644 this.v3.copy(source.v3);
27648 CubicBezierCurve3.prototype.toJSON = function () {
27649 var data = Curve.prototype.toJSON.call(this);
27650 data.v0 = this.v0.toArray();
27651 data.v1 = this.v1.toArray();
27652 data.v2 = this.v2.toArray();
27653 data.v3 = this.v3.toArray();
27657 CubicBezierCurve3.prototype.fromJSON = function (json) {
27658 Curve.prototype.fromJSON.call(this, json);
27659 this.v0.fromArray(json.v0);
27660 this.v1.fromArray(json.v1);
27661 this.v2.fromArray(json.v2);
27662 this.v3.fromArray(json.v3);
27666 function LineCurve(v1, v2) {
27667 if (v1 === void 0) {
27668 v1 = new Vector2();
27671 if (v2 === void 0) {
27672 v2 = new Vector2();
27676 this.type = 'LineCurve';
27681 LineCurve.prototype = Object.create(Curve.prototype);
27682 LineCurve.prototype.constructor = LineCurve;
27683 LineCurve.prototype.isLineCurve = true;
27685 LineCurve.prototype.getPoint = function (t, optionalTarget) {
27686 if (optionalTarget === void 0) {
27687 optionalTarget = new Vector2();
27690 var point = optionalTarget;
27693 point.copy(this.v2);
27695 point.copy(this.v2).sub(this.v1);
27696 point.multiplyScalar(t).add(this.v1);
27700 }; // Line curve is linear, so we can overwrite default getPointAt
27703 LineCurve.prototype.getPointAt = function (u, optionalTarget) {
27704 return this.getPoint(u, optionalTarget);
27707 LineCurve.prototype.getTangent = function (t, optionalTarget) {
27708 var tangent = optionalTarget || new Vector2();
27709 tangent.copy(this.v2).sub(this.v1).normalize();
27713 LineCurve.prototype.copy = function (source) {
27714 Curve.prototype.copy.call(this, source);
27715 this.v1.copy(source.v1);
27716 this.v2.copy(source.v2);
27720 LineCurve.prototype.toJSON = function () {
27721 var data = Curve.prototype.toJSON.call(this);
27722 data.v1 = this.v1.toArray();
27723 data.v2 = this.v2.toArray();
27727 LineCurve.prototype.fromJSON = function (json) {
27728 Curve.prototype.fromJSON.call(this, json);
27729 this.v1.fromArray(json.v1);
27730 this.v2.fromArray(json.v2);
27734 function LineCurve3(v1, v2) {
27735 if (v1 === void 0) {
27736 v1 = new Vector3();
27739 if (v2 === void 0) {
27740 v2 = new Vector3();
27744 this.type = 'LineCurve3';
27749 LineCurve3.prototype = Object.create(Curve.prototype);
27750 LineCurve3.prototype.constructor = LineCurve3;
27751 LineCurve3.prototype.isLineCurve3 = true;
27753 LineCurve3.prototype.getPoint = function (t, optionalTarget) {
27754 if (optionalTarget === void 0) {
27755 optionalTarget = new Vector3();
27758 var point = optionalTarget;
27761 point.copy(this.v2);
27763 point.copy(this.v2).sub(this.v1);
27764 point.multiplyScalar(t).add(this.v1);
27768 }; // Line curve is linear, so we can overwrite default getPointAt
27771 LineCurve3.prototype.getPointAt = function (u, optionalTarget) {
27772 return this.getPoint(u, optionalTarget);
27775 LineCurve3.prototype.copy = function (source) {
27776 Curve.prototype.copy.call(this, source);
27777 this.v1.copy(source.v1);
27778 this.v2.copy(source.v2);
27782 LineCurve3.prototype.toJSON = function () {
27783 var data = Curve.prototype.toJSON.call(this);
27784 data.v1 = this.v1.toArray();
27785 data.v2 = this.v2.toArray();
27789 LineCurve3.prototype.fromJSON = function (json) {
27790 Curve.prototype.fromJSON.call(this, json);
27791 this.v1.fromArray(json.v1);
27792 this.v2.fromArray(json.v2);
27796 function QuadraticBezierCurve(v0, v1, v2) {
27797 if (v0 === void 0) {
27798 v0 = new Vector2();
27801 if (v1 === void 0) {
27802 v1 = new Vector2();
27805 if (v2 === void 0) {
27806 v2 = new Vector2();
27810 this.type = 'QuadraticBezierCurve';
27816 QuadraticBezierCurve.prototype = Object.create(Curve.prototype);
27817 QuadraticBezierCurve.prototype.constructor = QuadraticBezierCurve;
27818 QuadraticBezierCurve.prototype.isQuadraticBezierCurve = true;
27820 QuadraticBezierCurve.prototype.getPoint = function (t, optionalTarget) {
27821 if (optionalTarget === void 0) {
27822 optionalTarget = new Vector2();
27825 var point = optionalTarget;
27829 point.set(QuadraticBezier(t, v0.x, v1.x, v2.x), QuadraticBezier(t, v0.y, v1.y, v2.y));
27833 QuadraticBezierCurve.prototype.copy = function (source) {
27834 Curve.prototype.copy.call(this, source);
27835 this.v0.copy(source.v0);
27836 this.v1.copy(source.v1);
27837 this.v2.copy(source.v2);
27841 QuadraticBezierCurve.prototype.toJSON = function () {
27842 var data = Curve.prototype.toJSON.call(this);
27843 data.v0 = this.v0.toArray();
27844 data.v1 = this.v1.toArray();
27845 data.v2 = this.v2.toArray();
27849 QuadraticBezierCurve.prototype.fromJSON = function (json) {
27850 Curve.prototype.fromJSON.call(this, json);
27851 this.v0.fromArray(json.v0);
27852 this.v1.fromArray(json.v1);
27853 this.v2.fromArray(json.v2);
27857 function QuadraticBezierCurve3(v0, v1, v2) {
27858 if (v0 === void 0) {
27859 v0 = new Vector3();
27862 if (v1 === void 0) {
27863 v1 = new Vector3();
27866 if (v2 === void 0) {
27867 v2 = new Vector3();
27871 this.type = 'QuadraticBezierCurve3';
27877 QuadraticBezierCurve3.prototype = Object.create(Curve.prototype);
27878 QuadraticBezierCurve3.prototype.constructor = QuadraticBezierCurve3;
27879 QuadraticBezierCurve3.prototype.isQuadraticBezierCurve3 = true;
27881 QuadraticBezierCurve3.prototype.getPoint = function (t, optionalTarget) {
27882 if (optionalTarget === void 0) {
27883 optionalTarget = new Vector3();
27886 var point = optionalTarget;
27890 point.set(QuadraticBezier(t, v0.x, v1.x, v2.x), QuadraticBezier(t, v0.y, v1.y, v2.y), QuadraticBezier(t, v0.z, v1.z, v2.z));
27894 QuadraticBezierCurve3.prototype.copy = function (source) {
27895 Curve.prototype.copy.call(this, source);
27896 this.v0.copy(source.v0);
27897 this.v1.copy(source.v1);
27898 this.v2.copy(source.v2);
27902 QuadraticBezierCurve3.prototype.toJSON = function () {
27903 var data = Curve.prototype.toJSON.call(this);
27904 data.v0 = this.v0.toArray();
27905 data.v1 = this.v1.toArray();
27906 data.v2 = this.v2.toArray();
27910 QuadraticBezierCurve3.prototype.fromJSON = function (json) {
27911 Curve.prototype.fromJSON.call(this, json);
27912 this.v0.fromArray(json.v0);
27913 this.v1.fromArray(json.v1);
27914 this.v2.fromArray(json.v2);
27918 function SplineCurve(points) {
27919 if (points === void 0) {
27924 this.type = 'SplineCurve';
27925 this.points = points;
27928 SplineCurve.prototype = Object.create(Curve.prototype);
27929 SplineCurve.prototype.constructor = SplineCurve;
27930 SplineCurve.prototype.isSplineCurve = true;
27932 SplineCurve.prototype.getPoint = function (t, optionalTarget) {
27933 if (optionalTarget === void 0) {
27934 optionalTarget = new Vector2();
27937 var point = optionalTarget;
27938 var points = this.points;
27939 var p = (points.length - 1) * t;
27940 var intPoint = Math.floor(p);
27941 var weight = p - intPoint;
27942 var p0 = points[intPoint === 0 ? intPoint : intPoint - 1];
27943 var p1 = points[intPoint];
27944 var p2 = points[intPoint > points.length - 2 ? points.length - 1 : intPoint + 1];
27945 var p3 = points[intPoint > points.length - 3 ? points.length - 1 : intPoint + 2];
27946 point.set(CatmullRom(weight, p0.x, p1.x, p2.x, p3.x), CatmullRom(weight, p0.y, p1.y, p2.y, p3.y));
27950 SplineCurve.prototype.copy = function (source) {
27951 Curve.prototype.copy.call(this, source);
27954 for (var i = 0, l = source.points.length; i < l; i++) {
27955 var point = source.points[i];
27956 this.points.push(point.clone());
27962 SplineCurve.prototype.toJSON = function () {
27963 var data = Curve.prototype.toJSON.call(this);
27966 for (var i = 0, l = this.points.length; i < l; i++) {
27967 var point = this.points[i];
27968 data.points.push(point.toArray());
27974 SplineCurve.prototype.fromJSON = function (json) {
27975 Curve.prototype.fromJSON.call(this, json);
27978 for (var i = 0, l = json.points.length; i < l; i++) {
27979 var point = json.points[i];
27980 this.points.push(new Vector2().fromArray(point));
27986 var Curves = /*#__PURE__*/Object.freeze({
27988 ArcCurve: ArcCurve,
27989 CatmullRomCurve3: CatmullRomCurve3,
27990 CubicBezierCurve: CubicBezierCurve,
27991 CubicBezierCurve3: CubicBezierCurve3,
27992 EllipseCurve: EllipseCurve,
27993 LineCurve: LineCurve,
27994 LineCurve3: LineCurve3,
27995 QuadraticBezierCurve: QuadraticBezierCurve,
27996 QuadraticBezierCurve3: QuadraticBezierCurve3,
27997 SplineCurve: SplineCurve
28000 /**************************************************************
28001 * Curved Path - a curve path is simply a array of connected
28002 * curves, but retains the api of a curve
28003 **************************************************************/
28005 function CurvePath() {
28007 this.type = 'CurvePath';
28009 this.autoClose = false; // Automatically closes the path
28012 CurvePath.prototype = Object.assign(Object.create(Curve.prototype), {
28013 constructor: CurvePath,
28014 add: function add(curve) {
28015 this.curves.push(curve);
28017 closePath: function closePath() {
28018 // Add a line curve if start and end of lines are not connected
28019 var startPoint = this.curves[0].getPoint(0);
28020 var endPoint = this.curves[this.curves.length - 1].getPoint(1);
28022 if (!startPoint.equals(endPoint)) {
28023 this.curves.push(new LineCurve(endPoint, startPoint));
28026 // To get accurate point with reference to
28027 // entire path distance at time t,
28028 // following has to be done:
28029 // 1. Length of each sub path have to be known
28030 // 2. Locate and identify type of curve
28031 // 3. Get t for the curve
28032 // 4. Return curve.getPointAt(t')
28033 getPoint: function getPoint(t) {
28034 var d = t * this.getLength();
28035 var curveLengths = this.getCurveLengths();
28036 var i = 0; // To think about boundaries points.
28038 while (i < curveLengths.length) {
28039 if (curveLengths[i] >= d) {
28040 var diff = curveLengths[i] - d;
28041 var curve = this.curves[i];
28042 var segmentLength = curve.getLength();
28043 var u = segmentLength === 0 ? 0 : 1 - diff / segmentLength;
28044 return curve.getPointAt(u);
28050 return null; // loop where sum != 0, sum > d , sum+1 <d
28052 // We cannot use the default THREE.Curve getPoint() with getLength() because in
28053 // THREE.Curve, getLength() depends on getPoint() but in THREE.CurvePath
28054 // getPoint() depends on getLength
28055 getLength: function getLength() {
28056 var lens = this.getCurveLengths();
28057 return lens[lens.length - 1];
28059 // cacheLengths must be recalculated.
28060 updateArcLengths: function updateArcLengths() {
28061 this.needsUpdate = true;
28062 this.cacheLengths = null;
28063 this.getCurveLengths();
28065 // Compute lengths and cache them
28066 // We cannot overwrite getLengths() because UtoT mapping uses it.
28067 getCurveLengths: function getCurveLengths() {
28068 // We use cache values if curves and cache array are same length
28069 if (this.cacheLengths && this.cacheLengths.length === this.curves.length) {
28070 return this.cacheLengths;
28071 } // Get length of sub-curve
28072 // Push sums into cached array
28078 for (var i = 0, l = this.curves.length; i < l; i++) {
28079 sums += this.curves[i].getLength();
28080 lengths.push(sums);
28083 this.cacheLengths = lengths;
28086 getSpacedPoints: function getSpacedPoints(divisions) {
28087 if (divisions === void 0) {
28093 for (var i = 0; i <= divisions; i++) {
28094 points.push(this.getPoint(i / divisions));
28097 if (this.autoClose) {
28098 points.push(points[0]);
28103 getPoints: function getPoints(divisions) {
28104 if (divisions === void 0) {
28111 for (var i = 0, curves = this.curves; i < curves.length; i++) {
28112 var curve = curves[i];
28113 var resolution = curve && curve.isEllipseCurve ? divisions * 2 : curve && (curve.isLineCurve || curve.isLineCurve3) ? 1 : curve && curve.isSplineCurve ? divisions * curve.points.length : divisions;
28114 var pts = curve.getPoints(resolution);
28116 for (var j = 0; j < pts.length; j++) {
28117 var point = pts[j];
28118 if (last && last.equals(point)) continue; // ensures no consecutive points are duplicates
28120 points.push(point);
28125 if (this.autoClose && points.length > 1 && !points[points.length - 1].equals(points[0])) {
28126 points.push(points[0]);
28131 copy: function copy(source) {
28132 Curve.prototype.copy.call(this, source);
28135 for (var i = 0, l = source.curves.length; i < l; i++) {
28136 var curve = source.curves[i];
28137 this.curves.push(curve.clone());
28140 this.autoClose = source.autoClose;
28143 toJSON: function toJSON() {
28144 var data = Curve.prototype.toJSON.call(this);
28145 data.autoClose = this.autoClose;
28148 for (var i = 0, l = this.curves.length; i < l; i++) {
28149 var curve = this.curves[i];
28150 data.curves.push(curve.toJSON());
28155 fromJSON: function fromJSON(json) {
28156 Curve.prototype.fromJSON.call(this, json);
28157 this.autoClose = json.autoClose;
28160 for (var i = 0, l = json.curves.length; i < l; i++) {
28161 var curve = json.curves[i];
28162 this.curves.push(new Curves[curve.type]().fromJSON(curve));
28169 function Path(points) {
28170 CurvePath.call(this);
28171 this.type = 'Path';
28172 this.currentPoint = new Vector2();
28175 this.setFromPoints(points);
28179 Path.prototype = Object.assign(Object.create(CurvePath.prototype), {
28181 setFromPoints: function setFromPoints(points) {
28182 this.moveTo(points[0].x, points[0].y);
28184 for (var i = 1, l = points.length; i < l; i++) {
28185 this.lineTo(points[i].x, points[i].y);
28190 moveTo: function moveTo(x, y) {
28191 this.currentPoint.set(x, y); // TODO consider referencing vectors instead of copying?
28195 lineTo: function lineTo(x, y) {
28196 var curve = new LineCurve(this.currentPoint.clone(), new Vector2(x, y));
28197 this.curves.push(curve);
28198 this.currentPoint.set(x, y);
28201 quadraticCurveTo: function quadraticCurveTo(aCPx, aCPy, aX, aY) {
28202 var curve = new QuadraticBezierCurve(this.currentPoint.clone(), new Vector2(aCPx, aCPy), new Vector2(aX, aY));
28203 this.curves.push(curve);
28204 this.currentPoint.set(aX, aY);
28207 bezierCurveTo: function bezierCurveTo(aCP1x, aCP1y, aCP2x, aCP2y, aX, aY) {
28208 var curve = new CubicBezierCurve(this.currentPoint.clone(), new Vector2(aCP1x, aCP1y), new Vector2(aCP2x, aCP2y), new Vector2(aX, aY));
28209 this.curves.push(curve);
28210 this.currentPoint.set(aX, aY);
28213 splineThru: function splineThru(pts
28214 /*Array of Vector*/
28216 var npts = [this.currentPoint.clone()].concat(pts);
28217 var curve = new SplineCurve(npts);
28218 this.curves.push(curve);
28219 this.currentPoint.copy(pts[pts.length - 1]);
28222 arc: function arc(aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise) {
28223 var x0 = this.currentPoint.x;
28224 var y0 = this.currentPoint.y;
28225 this.absarc(aX + x0, aY + y0, aRadius, aStartAngle, aEndAngle, aClockwise);
28228 absarc: function absarc(aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise) {
28229 this.absellipse(aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise);
28232 ellipse: function ellipse(aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation) {
28233 var x0 = this.currentPoint.x;
28234 var y0 = this.currentPoint.y;
28235 this.absellipse(aX + x0, aY + y0, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation);
28238 absellipse: function absellipse(aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation) {
28239 var curve = new EllipseCurve(aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation);
28241 if (this.curves.length > 0) {
28242 // if a previous curve is present, attempt to join
28243 var firstPoint = curve.getPoint(0);
28245 if (!firstPoint.equals(this.currentPoint)) {
28246 this.lineTo(firstPoint.x, firstPoint.y);
28250 this.curves.push(curve);
28251 var lastPoint = curve.getPoint(1);
28252 this.currentPoint.copy(lastPoint);
28255 copy: function copy(source) {
28256 CurvePath.prototype.copy.call(this, source);
28257 this.currentPoint.copy(source.currentPoint);
28260 toJSON: function toJSON() {
28261 var data = CurvePath.prototype.toJSON.call(this);
28262 data.currentPoint = this.currentPoint.toArray();
28265 fromJSON: function fromJSON(json) {
28266 CurvePath.prototype.fromJSON.call(this, json);
28267 this.currentPoint.fromArray(json.currentPoint);
28272 function Shape(points) {
28273 Path.call(this, points);
28274 this.uuid = MathUtils.generateUUID();
28275 this.type = 'Shape';
28279 Shape.prototype = Object.assign(Object.create(Path.prototype), {
28280 constructor: Shape,
28281 getPointsHoles: function getPointsHoles(divisions) {
28284 for (var i = 0, l = this.holes.length; i < l; i++) {
28285 holesPts[i] = this.holes[i].getPoints(divisions);
28290 // get points of shape and holes (keypoints based on segments parameter)
28291 extractPoints: function extractPoints(divisions) {
28293 shape: this.getPoints(divisions),
28294 holes: this.getPointsHoles(divisions)
28297 copy: function copy(source) {
28298 Path.prototype.copy.call(this, source);
28301 for (var i = 0, l = source.holes.length; i < l; i++) {
28302 var hole = source.holes[i];
28303 this.holes.push(hole.clone());
28308 toJSON: function toJSON() {
28309 var data = Path.prototype.toJSON.call(this);
28310 data.uuid = this.uuid;
28313 for (var i = 0, l = this.holes.length; i < l; i++) {
28314 var hole = this.holes[i];
28315 data.holes.push(hole.toJSON());
28320 fromJSON: function fromJSON(json) {
28321 Path.prototype.fromJSON.call(this, json);
28322 this.uuid = json.uuid;
28325 for (var i = 0, l = json.holes.length; i < l; i++) {
28326 var hole = json.holes[i];
28327 this.holes.push(new Path().fromJSON(hole));
28334 function Light(color, intensity) {
28335 if (intensity === void 0) {
28339 Object3D.call(this);
28340 this.type = 'Light';
28341 this.color = new Color(color);
28342 this.intensity = intensity;
28345 Light.prototype = Object.assign(Object.create(Object3D.prototype), {
28346 constructor: Light,
28348 copy: function copy(source) {
28349 Object3D.prototype.copy.call(this, source);
28350 this.color.copy(source.color);
28351 this.intensity = source.intensity;
28354 toJSON: function toJSON(meta) {
28355 var data = Object3D.prototype.toJSON.call(this, meta);
28356 data.object.color = this.color.getHex();
28357 data.object.intensity = this.intensity;
28358 if (this.groundColor !== undefined) data.object.groundColor = this.groundColor.getHex();
28359 if (this.distance !== undefined) data.object.distance = this.distance;
28360 if (this.angle !== undefined) data.object.angle = this.angle;
28361 if (this.decay !== undefined) data.object.decay = this.decay;
28362 if (this.penumbra !== undefined) data.object.penumbra = this.penumbra;
28363 if (this.shadow !== undefined) data.object.shadow = this.shadow.toJSON();
28368 function HemisphereLight(skyColor, groundColor, intensity) {
28369 Light.call(this, skyColor, intensity);
28370 this.type = 'HemisphereLight';
28371 this.position.copy(Object3D.DefaultUp);
28372 this.updateMatrix();
28373 this.groundColor = new Color(groundColor);
28376 HemisphereLight.prototype = Object.assign(Object.create(Light.prototype), {
28377 constructor: HemisphereLight,
28378 isHemisphereLight: true,
28379 copy: function copy(source) {
28380 Light.prototype.copy.call(this, source);
28381 this.groundColor.copy(source.groundColor);
28386 function LightShadow(camera) {
28387 this.camera = camera;
28389 this.normalBias = 0;
28391 this.mapSize = new Vector2(512, 512);
28393 this.mapPass = null;
28394 this.matrix = new Matrix4();
28395 this.autoUpdate = true;
28396 this.needsUpdate = false;
28397 this._frustum = new Frustum();
28398 this._frameExtents = new Vector2(1, 1);
28399 this._viewportCount = 1;
28400 this._viewports = [new Vector4(0, 0, 1, 1)];
28403 Object.assign(LightShadow.prototype, {
28404 _projScreenMatrix: new Matrix4(),
28405 _lightPositionWorld: new Vector3(),
28406 _lookTarget: new Vector3(),
28407 getViewportCount: function getViewportCount() {
28408 return this._viewportCount;
28410 getFrustum: function getFrustum() {
28411 return this._frustum;
28413 updateMatrices: function updateMatrices(light) {
28414 var shadowCamera = this.camera,
28415 shadowMatrix = this.matrix,
28416 projScreenMatrix = this._projScreenMatrix,
28417 lookTarget = this._lookTarget,
28418 lightPositionWorld = this._lightPositionWorld;
28419 lightPositionWorld.setFromMatrixPosition(light.matrixWorld);
28420 shadowCamera.position.copy(lightPositionWorld);
28421 lookTarget.setFromMatrixPosition(light.target.matrixWorld);
28422 shadowCamera.lookAt(lookTarget);
28423 shadowCamera.updateMatrixWorld();
28424 projScreenMatrix.multiplyMatrices(shadowCamera.projectionMatrix, shadowCamera.matrixWorldInverse);
28426 this._frustum.setFromProjectionMatrix(projScreenMatrix);
28428 shadowMatrix.set(0.5, 0.0, 0.0, 0.5, 0.0, 0.5, 0.0, 0.5, 0.0, 0.0, 0.5, 0.5, 0.0, 0.0, 0.0, 1.0);
28429 shadowMatrix.multiply(shadowCamera.projectionMatrix);
28430 shadowMatrix.multiply(shadowCamera.matrixWorldInverse);
28432 getViewport: function getViewport(viewportIndex) {
28433 return this._viewports[viewportIndex];
28435 getFrameExtents: function getFrameExtents() {
28436 return this._frameExtents;
28438 copy: function copy(source) {
28439 this.camera = source.camera.clone();
28440 this.bias = source.bias;
28441 this.radius = source.radius;
28442 this.mapSize.copy(source.mapSize);
28445 clone: function clone() {
28446 return new this.constructor().copy(this);
28448 toJSON: function toJSON() {
28450 if (this.bias !== 0) object.bias = this.bias;
28451 if (this.normalBias !== 0) object.normalBias = this.normalBias;
28452 if (this.radius !== 1) object.radius = this.radius;
28453 if (this.mapSize.x !== 512 || this.mapSize.y !== 512) object.mapSize = this.mapSize.toArray();
28454 object.camera = this.camera.toJSON(false).object;
28455 delete object.camera.matrix;
28460 function SpotLightShadow() {
28461 LightShadow.call(this, new PerspectiveCamera(50, 1, 0.5, 500));
28465 SpotLightShadow.prototype = Object.assign(Object.create(LightShadow.prototype), {
28466 constructor: SpotLightShadow,
28467 isSpotLightShadow: true,
28468 updateMatrices: function updateMatrices(light) {
28469 var camera = this.camera;
28470 var fov = MathUtils.RAD2DEG * 2 * light.angle * this.focus;
28471 var aspect = this.mapSize.width / this.mapSize.height;
28472 var far = light.distance || camera.far;
28474 if (fov !== camera.fov || aspect !== camera.aspect || far !== camera.far) {
28476 camera.aspect = aspect;
28478 camera.updateProjectionMatrix();
28481 LightShadow.prototype.updateMatrices.call(this, light);
28485 function SpotLight(color, intensity, distance, angle, penumbra, decay) {
28486 Light.call(this, color, intensity);
28487 this.type = 'SpotLight';
28488 this.position.copy(Object3D.DefaultUp);
28489 this.updateMatrix();
28490 this.target = new Object3D();
28491 Object.defineProperty(this, 'power', {
28492 get: function get() {
28493 // intensity = power per solid angle.
28494 // ref: equation (17) from https://seblagarde.files.wordpress.com/2015/07/course_notes_moving_frostbite_to_pbr_v32.pdf
28495 return this.intensity * Math.PI;
28497 set: function set(power) {
28498 // intensity = power per solid angle.
28499 // ref: equation (17) from https://seblagarde.files.wordpress.com/2015/07/course_notes_moving_frostbite_to_pbr_v32.pdf
28500 this.intensity = power / Math.PI;
28503 this.distance = distance !== undefined ? distance : 0;
28504 this.angle = angle !== undefined ? angle : Math.PI / 3;
28505 this.penumbra = penumbra !== undefined ? penumbra : 0;
28506 this.decay = decay !== undefined ? decay : 1; // for physically correct lights, should be 2.
28508 this.shadow = new SpotLightShadow();
28511 SpotLight.prototype = Object.assign(Object.create(Light.prototype), {
28512 constructor: SpotLight,
28514 copy: function copy(source) {
28515 Light.prototype.copy.call(this, source);
28516 this.distance = source.distance;
28517 this.angle = source.angle;
28518 this.penumbra = source.penumbra;
28519 this.decay = source.decay;
28520 this.target = source.target.clone();
28521 this.shadow = source.shadow.clone();
28526 function PointLightShadow() {
28527 LightShadow.call(this, new PerspectiveCamera(90, 1, 0.5, 500));
28528 this._frameExtents = new Vector2(4, 2);
28529 this._viewportCount = 6;
28530 this._viewports = [// These viewports map a cube-map onto a 2D texture with the
28531 // following orientation:
28536 // X - Positive x direction
28537 // x - Negative x direction
28538 // Y - Positive y direction
28539 // y - Negative y direction
28540 // Z - Positive z direction
28541 // z - Negative z direction
28543 new Vector4(2, 1, 1, 1), // negative X
28544 new Vector4(0, 1, 1, 1), // positive Z
28545 new Vector4(3, 1, 1, 1), // negative Z
28546 new Vector4(1, 1, 1, 1), // positive Y
28547 new Vector4(3, 0, 1, 1), // negative Y
28548 new Vector4(1, 0, 1, 1)];
28549 this._cubeDirections = [new Vector3(1, 0, 0), new Vector3(-1, 0, 0), new Vector3(0, 0, 1), new Vector3(0, 0, -1), new Vector3(0, 1, 0), new Vector3(0, -1, 0)];
28550 this._cubeUps = [new Vector3(0, 1, 0), new Vector3(0, 1, 0), new Vector3(0, 1, 0), new Vector3(0, 1, 0), new Vector3(0, 0, 1), new Vector3(0, 0, -1)];
28553 PointLightShadow.prototype = Object.assign(Object.create(LightShadow.prototype), {
28554 constructor: PointLightShadow,
28555 isPointLightShadow: true,
28556 updateMatrices: function updateMatrices(light, viewportIndex) {
28557 if (viewportIndex === void 0) {
28561 var camera = this.camera,
28562 shadowMatrix = this.matrix,
28563 lightPositionWorld = this._lightPositionWorld,
28564 lookTarget = this._lookTarget,
28565 projScreenMatrix = this._projScreenMatrix;
28566 lightPositionWorld.setFromMatrixPosition(light.matrixWorld);
28567 camera.position.copy(lightPositionWorld);
28568 lookTarget.copy(camera.position);
28569 lookTarget.add(this._cubeDirections[viewportIndex]);
28570 camera.up.copy(this._cubeUps[viewportIndex]);
28571 camera.lookAt(lookTarget);
28572 camera.updateMatrixWorld();
28573 shadowMatrix.makeTranslation(-lightPositionWorld.x, -lightPositionWorld.y, -lightPositionWorld.z);
28574 projScreenMatrix.multiplyMatrices(camera.projectionMatrix, camera.matrixWorldInverse);
28576 this._frustum.setFromProjectionMatrix(projScreenMatrix);
28580 function PointLight(color, intensity, distance, decay) {
28581 Light.call(this, color, intensity);
28582 this.type = 'PointLight';
28583 Object.defineProperty(this, 'power', {
28584 get: function get() {
28585 // intensity = power per solid angle.
28586 // ref: equation (15) from https://seblagarde.files.wordpress.com/2015/07/course_notes_moving_frostbite_to_pbr_v32.pdf
28587 return this.intensity * 4 * Math.PI;
28589 set: function set(power) {
28590 // intensity = power per solid angle.
28591 // ref: equation (15) from https://seblagarde.files.wordpress.com/2015/07/course_notes_moving_frostbite_to_pbr_v32.pdf
28592 this.intensity = power / (4 * Math.PI);
28595 this.distance = distance !== undefined ? distance : 0;
28596 this.decay = decay !== undefined ? decay : 1; // for physically correct lights, should be 2.
28598 this.shadow = new PointLightShadow();
28601 PointLight.prototype = Object.assign(Object.create(Light.prototype), {
28602 constructor: PointLight,
28603 isPointLight: true,
28604 copy: function copy(source) {
28605 Light.prototype.copy.call(this, source);
28606 this.distance = source.distance;
28607 this.decay = source.decay;
28608 this.shadow = source.shadow.clone();
28613 function OrthographicCamera(left, right, top, bottom, near, far) {
28614 if (left === void 0) {
28618 if (right === void 0) {
28622 if (top === void 0) {
28626 if (bottom === void 0) {
28630 if (near === void 0) {
28634 if (far === void 0) {
28639 this.type = 'OrthographicCamera';
28643 this.right = right;
28645 this.bottom = bottom;
28648 this.updateProjectionMatrix();
28651 OrthographicCamera.prototype = Object.assign(Object.create(Camera.prototype), {
28652 constructor: OrthographicCamera,
28653 isOrthographicCamera: true,
28654 copy: function copy(source, recursive) {
28655 Camera.prototype.copy.call(this, source, recursive);
28656 this.left = source.left;
28657 this.right = source.right;
28658 this.top = source.top;
28659 this.bottom = source.bottom;
28660 this.near = source.near;
28661 this.far = source.far;
28662 this.zoom = source.zoom;
28663 this.view = source.view === null ? null : Object.assign({}, source.view);
28666 setViewOffset: function setViewOffset(fullWidth, fullHeight, x, y, width, height) {
28667 if (this.view === null) {
28679 this.view.enabled = true;
28680 this.view.fullWidth = fullWidth;
28681 this.view.fullHeight = fullHeight;
28682 this.view.offsetX = x;
28683 this.view.offsetY = y;
28684 this.view.width = width;
28685 this.view.height = height;
28686 this.updateProjectionMatrix();
28688 clearViewOffset: function clearViewOffset() {
28689 if (this.view !== null) {
28690 this.view.enabled = false;
28693 this.updateProjectionMatrix();
28695 updateProjectionMatrix: function updateProjectionMatrix() {
28696 var dx = (this.right - this.left) / (2 * this.zoom);
28697 var dy = (this.top - this.bottom) / (2 * this.zoom);
28698 var cx = (this.right + this.left) / 2;
28699 var cy = (this.top + this.bottom) / 2;
28700 var left = cx - dx;
28701 var right = cx + dx;
28703 var bottom = cy - dy;
28705 if (this.view !== null && this.view.enabled) {
28706 var scaleW = (this.right - this.left) / this.view.fullWidth / this.zoom;
28707 var scaleH = (this.top - this.bottom) / this.view.fullHeight / this.zoom;
28708 left += scaleW * this.view.offsetX;
28709 right = left + scaleW * this.view.width;
28710 top -= scaleH * this.view.offsetY;
28711 bottom = top - scaleH * this.view.height;
28714 this.projectionMatrix.makeOrthographic(left, right, top, bottom, this.near, this.far);
28715 this.projectionMatrixInverse.copy(this.projectionMatrix).invert();
28717 toJSON: function toJSON(meta) {
28718 var data = Object3D.prototype.toJSON.call(this, meta);
28719 data.object.zoom = this.zoom;
28720 data.object.left = this.left;
28721 data.object.right = this.right;
28722 data.object.top = this.top;
28723 data.object.bottom = this.bottom;
28724 data.object.near = this.near;
28725 data.object.far = this.far;
28726 if (this.view !== null) data.object.view = Object.assign({}, this.view);
28731 function DirectionalLightShadow() {
28732 LightShadow.call(this, new OrthographicCamera(-5, 5, 5, -5, 0.5, 500));
28735 DirectionalLightShadow.prototype = Object.assign(Object.create(LightShadow.prototype), {
28736 constructor: DirectionalLightShadow,
28737 isDirectionalLightShadow: true,
28738 updateMatrices: function updateMatrices(light) {
28739 LightShadow.prototype.updateMatrices.call(this, light);
28743 function DirectionalLight(color, intensity) {
28744 Light.call(this, color, intensity);
28745 this.type = 'DirectionalLight';
28746 this.position.copy(Object3D.DefaultUp);
28747 this.updateMatrix();
28748 this.target = new Object3D();
28749 this.shadow = new DirectionalLightShadow();
28752 DirectionalLight.prototype = Object.assign(Object.create(Light.prototype), {
28753 constructor: DirectionalLight,
28754 isDirectionalLight: true,
28755 copy: function copy(source) {
28756 Light.prototype.copy.call(this, source);
28757 this.target = source.target.clone();
28758 this.shadow = source.shadow.clone();
28763 function AmbientLight(color, intensity) {
28764 Light.call(this, color, intensity);
28765 this.type = 'AmbientLight';
28768 AmbientLight.prototype = Object.assign(Object.create(Light.prototype), {
28769 constructor: AmbientLight,
28770 isAmbientLight: true
28773 function RectAreaLight(color, intensity, width, height) {
28774 Light.call(this, color, intensity);
28775 this.type = 'RectAreaLight';
28776 this.width = width !== undefined ? width : 10;
28777 this.height = height !== undefined ? height : 10;
28780 RectAreaLight.prototype = Object.assign(Object.create(Light.prototype), {
28781 constructor: RectAreaLight,
28782 isRectAreaLight: true,
28783 copy: function copy(source) {
28784 Light.prototype.copy.call(this, source);
28785 this.width = source.width;
28786 this.height = source.height;
28789 toJSON: function toJSON(meta) {
28790 var data = Light.prototype.toJSON.call(this, meta);
28791 data.object.width = this.width;
28792 data.object.height = this.height;
28798 * Primary reference:
28799 * https://graphics.stanford.edu/papers/envmap/envmap.pdf
28801 * Secondary reference:
28802 * https://www.ppsloan.org/publications/StupidSH36.pdf
28804 // 3-band SH defined by 9 coefficients
28806 var SphericalHarmonics3 = /*#__PURE__*/function () {
28807 function SphericalHarmonics3() {
28808 Object.defineProperty(this, 'isSphericalHarmonics3', {
28811 this.coefficients = [];
28813 for (var i = 0; i < 9; i++) {
28814 this.coefficients.push(new Vector3());
28818 var _proto = SphericalHarmonics3.prototype;
28820 _proto.set = function set(coefficients) {
28821 for (var i = 0; i < 9; i++) {
28822 this.coefficients[i].copy(coefficients[i]);
28828 _proto.zero = function zero() {
28829 for (var i = 0; i < 9; i++) {
28830 this.coefficients[i].set(0, 0, 0);
28834 } // get the radiance in the direction of the normal
28835 // target is a Vector3
28838 _proto.getAt = function getAt(normal, target) {
28839 // normal is assumed to be unit length
28843 var coeff = this.coefficients; // band 0
28845 target.copy(coeff[0]).multiplyScalar(0.282095); // band 1
28847 target.addScaledVector(coeff[1], 0.488603 * y);
28848 target.addScaledVector(coeff[2], 0.488603 * z);
28849 target.addScaledVector(coeff[3], 0.488603 * x); // band 2
28851 target.addScaledVector(coeff[4], 1.092548 * (x * y));
28852 target.addScaledVector(coeff[5], 1.092548 * (y * z));
28853 target.addScaledVector(coeff[6], 0.315392 * (3.0 * z * z - 1.0));
28854 target.addScaledVector(coeff[7], 1.092548 * (x * z));
28855 target.addScaledVector(coeff[8], 0.546274 * (x * x - y * y));
28857 } // get the irradiance (radiance convolved with cosine lobe) in the direction of the normal
28858 // target is a Vector3
28859 // https://graphics.stanford.edu/papers/envmap/envmap.pdf
28862 _proto.getIrradianceAt = function getIrradianceAt(normal, target) {
28863 // normal is assumed to be unit length
28867 var coeff = this.coefficients; // band 0
28869 target.copy(coeff[0]).multiplyScalar(0.886227); // π * 0.282095
28872 target.addScaledVector(coeff[1], 2.0 * 0.511664 * y); // ( 2 * π / 3 ) * 0.488603
28874 target.addScaledVector(coeff[2], 2.0 * 0.511664 * z);
28875 target.addScaledVector(coeff[3], 2.0 * 0.511664 * x); // band 2
28877 target.addScaledVector(coeff[4], 2.0 * 0.429043 * x * y); // ( π / 4 ) * 1.092548
28879 target.addScaledVector(coeff[5], 2.0 * 0.429043 * y * z);
28880 target.addScaledVector(coeff[6], 0.743125 * z * z - 0.247708); // ( π / 4 ) * 0.315392 * 3
28882 target.addScaledVector(coeff[7], 2.0 * 0.429043 * x * z);
28883 target.addScaledVector(coeff[8], 0.429043 * (x * x - y * y)); // ( π / 4 ) * 0.546274
28888 _proto.add = function add(sh) {
28889 for (var i = 0; i < 9; i++) {
28890 this.coefficients[i].add(sh.coefficients[i]);
28896 _proto.addScaledSH = function addScaledSH(sh, s) {
28897 for (var i = 0; i < 9; i++) {
28898 this.coefficients[i].addScaledVector(sh.coefficients[i], s);
28904 _proto.scale = function scale(s) {
28905 for (var i = 0; i < 9; i++) {
28906 this.coefficients[i].multiplyScalar(s);
28912 _proto.lerp = function lerp(sh, alpha) {
28913 for (var i = 0; i < 9; i++) {
28914 this.coefficients[i].lerp(sh.coefficients[i], alpha);
28920 _proto.equals = function equals(sh) {
28921 for (var i = 0; i < 9; i++) {
28922 if (!this.coefficients[i].equals(sh.coefficients[i])) {
28930 _proto.copy = function copy(sh) {
28931 return this.set(sh.coefficients);
28934 _proto.clone = function clone() {
28935 return new this.constructor().copy(this);
28938 _proto.fromArray = function fromArray(array, offset) {
28939 if (offset === void 0) {
28943 var coefficients = this.coefficients;
28945 for (var i = 0; i < 9; i++) {
28946 coefficients[i].fromArray(array, offset + i * 3);
28952 _proto.toArray = function toArray(array, offset) {
28953 if (array === void 0) {
28957 if (offset === void 0) {
28961 var coefficients = this.coefficients;
28963 for (var i = 0; i < 9; i++) {
28964 coefficients[i].toArray(array, offset + i * 3);
28968 } // evaluate the basis functions
28969 // shBasis is an Array[ 9 ]
28972 SphericalHarmonics3.getBasisAt = function getBasisAt(normal, shBasis) {
28973 // normal is assumed to be unit length
28976 z = normal.z; // band 0
28978 shBasis[0] = 0.282095; // band 1
28980 shBasis[1] = 0.488603 * y;
28981 shBasis[2] = 0.488603 * z;
28982 shBasis[3] = 0.488603 * x; // band 2
28984 shBasis[4] = 1.092548 * x * y;
28985 shBasis[5] = 1.092548 * y * z;
28986 shBasis[6] = 0.315392 * (3 * z * z - 1);
28987 shBasis[7] = 1.092548 * x * z;
28988 shBasis[8] = 0.546274 * (x * x - y * y);
28991 return SphericalHarmonics3;
28994 function LightProbe(sh, intensity) {
28995 Light.call(this, undefined, intensity);
28996 this.type = 'LightProbe';
28997 this.sh = sh !== undefined ? sh : new SphericalHarmonics3();
29000 LightProbe.prototype = Object.assign(Object.create(Light.prototype), {
29001 constructor: LightProbe,
29002 isLightProbe: true,
29003 copy: function copy(source) {
29004 Light.prototype.copy.call(this, source);
29005 this.sh.copy(source.sh);
29008 fromJSON: function fromJSON(json) {
29009 this.intensity = json.intensity; // TODO: Move this bit to Light.fromJSON();
29011 this.sh.fromArray(json.sh);
29014 toJSON: function toJSON(meta) {
29015 var data = Light.prototype.toJSON.call(this, meta);
29016 data.object.sh = this.sh.toArray();
29021 function MaterialLoader(manager) {
29022 Loader.call(this, manager);
29023 this.textures = {};
29026 MaterialLoader.prototype = Object.assign(Object.create(Loader.prototype), {
29027 constructor: MaterialLoader,
29028 load: function load(url, onLoad, onProgress, onError) {
29030 var loader = new FileLoader(scope.manager);
29031 loader.setPath(scope.path);
29032 loader.setRequestHeader(scope.requestHeader);
29033 loader.setWithCredentials(scope.withCredentials);
29034 loader.load(url, function (text) {
29036 onLoad(scope.parse(JSON.parse(text)));
29044 scope.manager.itemError(url);
29046 }, onProgress, onError);
29048 parse: function parse(json) {
29049 var textures = this.textures;
29051 function getTexture(name) {
29052 if (textures[name] === undefined) {
29053 console.warn('THREE.MaterialLoader: Undefined texture', name);
29056 return textures[name];
29059 var material = new Materials[json.type]();
29060 if (json.uuid !== undefined) material.uuid = json.uuid;
29061 if (json.name !== undefined) material.name = json.name;
29062 if (json.color !== undefined && material.color !== undefined) material.color.setHex(json.color);
29063 if (json.roughness !== undefined) material.roughness = json.roughness;
29064 if (json.metalness !== undefined) material.metalness = json.metalness;
29065 if (json.sheen !== undefined) material.sheen = new Color().setHex(json.sheen);
29066 if (json.emissive !== undefined && material.emissive !== undefined) material.emissive.setHex(json.emissive);
29067 if (json.specular !== undefined && material.specular !== undefined) material.specular.setHex(json.specular);
29068 if (json.shininess !== undefined) material.shininess = json.shininess;
29069 if (json.clearcoat !== undefined) material.clearcoat = json.clearcoat;
29070 if (json.clearcoatRoughness !== undefined) material.clearcoatRoughness = json.clearcoatRoughness;
29071 if (json.fog !== undefined) material.fog = json.fog;
29072 if (json.flatShading !== undefined) material.flatShading = json.flatShading;
29073 if (json.blending !== undefined) material.blending = json.blending;
29074 if (json.combine !== undefined) material.combine = json.combine;
29075 if (json.side !== undefined) material.side = json.side;
29076 if (json.opacity !== undefined) material.opacity = json.opacity;
29077 if (json.transparent !== undefined) material.transparent = json.transparent;
29078 if (json.alphaTest !== undefined) material.alphaTest = json.alphaTest;
29079 if (json.depthTest !== undefined) material.depthTest = json.depthTest;
29080 if (json.depthWrite !== undefined) material.depthWrite = json.depthWrite;
29081 if (json.colorWrite !== undefined) material.colorWrite = json.colorWrite;
29082 if (json.stencilWrite !== undefined) material.stencilWrite = json.stencilWrite;
29083 if (json.stencilWriteMask !== undefined) material.stencilWriteMask = json.stencilWriteMask;
29084 if (json.stencilFunc !== undefined) material.stencilFunc = json.stencilFunc;
29085 if (json.stencilRef !== undefined) material.stencilRef = json.stencilRef;
29086 if (json.stencilFuncMask !== undefined) material.stencilFuncMask = json.stencilFuncMask;
29087 if (json.stencilFail !== undefined) material.stencilFail = json.stencilFail;
29088 if (json.stencilZFail !== undefined) material.stencilZFail = json.stencilZFail;
29089 if (json.stencilZPass !== undefined) material.stencilZPass = json.stencilZPass;
29090 if (json.wireframe !== undefined) material.wireframe = json.wireframe;
29091 if (json.wireframeLinewidth !== undefined) material.wireframeLinewidth = json.wireframeLinewidth;
29092 if (json.wireframeLinecap !== undefined) material.wireframeLinecap = json.wireframeLinecap;
29093 if (json.wireframeLinejoin !== undefined) material.wireframeLinejoin = json.wireframeLinejoin;
29094 if (json.rotation !== undefined) material.rotation = json.rotation;
29095 if (json.linewidth !== 1) material.linewidth = json.linewidth;
29096 if (json.dashSize !== undefined) material.dashSize = json.dashSize;
29097 if (json.gapSize !== undefined) material.gapSize = json.gapSize;
29098 if (json.scale !== undefined) material.scale = json.scale;
29099 if (json.polygonOffset !== undefined) material.polygonOffset = json.polygonOffset;
29100 if (json.polygonOffsetFactor !== undefined) material.polygonOffsetFactor = json.polygonOffsetFactor;
29101 if (json.polygonOffsetUnits !== undefined) material.polygonOffsetUnits = json.polygonOffsetUnits;
29102 if (json.skinning !== undefined) material.skinning = json.skinning;
29103 if (json.morphTargets !== undefined) material.morphTargets = json.morphTargets;
29104 if (json.morphNormals !== undefined) material.morphNormals = json.morphNormals;
29105 if (json.dithering !== undefined) material.dithering = json.dithering;
29106 if (json.vertexTangents !== undefined) material.vertexTangents = json.vertexTangents;
29107 if (json.visible !== undefined) material.visible = json.visible;
29108 if (json.toneMapped !== undefined) material.toneMapped = json.toneMapped;
29109 if (json.userData !== undefined) material.userData = json.userData;
29111 if (json.vertexColors !== undefined) {
29112 if (typeof json.vertexColors === 'number') {
29113 material.vertexColors = json.vertexColors > 0 ? true : false;
29115 material.vertexColors = json.vertexColors;
29117 } // Shader Material
29120 if (json.uniforms !== undefined) {
29121 for (var name in json.uniforms) {
29122 var uniform = json.uniforms[name];
29123 material.uniforms[name] = {};
29125 switch (uniform.type) {
29127 material.uniforms[name].value = getTexture(uniform.value);
29131 material.uniforms[name].value = new Color().setHex(uniform.value);
29135 material.uniforms[name].value = new Vector2().fromArray(uniform.value);
29139 material.uniforms[name].value = new Vector3().fromArray(uniform.value);
29143 material.uniforms[name].value = new Vector4().fromArray(uniform.value);
29147 material.uniforms[name].value = new Matrix3().fromArray(uniform.value);
29151 material.uniforms[name].value = new Matrix4().fromArray(uniform.value);
29155 material.uniforms[name].value = uniform.value;
29160 if (json.defines !== undefined) material.defines = json.defines;
29161 if (json.vertexShader !== undefined) material.vertexShader = json.vertexShader;
29162 if (json.fragmentShader !== undefined) material.fragmentShader = json.fragmentShader;
29164 if (json.extensions !== undefined) {
29165 for (var key in json.extensions) {
29166 material.extensions[key] = json.extensions[key];
29171 if (json.shading !== undefined) material.flatShading = json.shading === 1; // THREE.FlatShading
29172 // for PointsMaterial
29174 if (json.size !== undefined) material.size = json.size;
29175 if (json.sizeAttenuation !== undefined) material.sizeAttenuation = json.sizeAttenuation; // maps
29177 if (json.map !== undefined) material.map = getTexture(json.map);
29178 if (json.matcap !== undefined) material.matcap = getTexture(json.matcap);
29179 if (json.alphaMap !== undefined) material.alphaMap = getTexture(json.alphaMap);
29180 if (json.bumpMap !== undefined) material.bumpMap = getTexture(json.bumpMap);
29181 if (json.bumpScale !== undefined) material.bumpScale = json.bumpScale;
29182 if (json.normalMap !== undefined) material.normalMap = getTexture(json.normalMap);
29183 if (json.normalMapType !== undefined) material.normalMapType = json.normalMapType;
29185 if (json.normalScale !== undefined) {
29186 var normalScale = json.normalScale;
29188 if (Array.isArray(normalScale) === false) {
29189 // Blender exporter used to export a scalar. See #7459
29190 normalScale = [normalScale, normalScale];
29193 material.normalScale = new Vector2().fromArray(normalScale);
29196 if (json.displacementMap !== undefined) material.displacementMap = getTexture(json.displacementMap);
29197 if (json.displacementScale !== undefined) material.displacementScale = json.displacementScale;
29198 if (json.displacementBias !== undefined) material.displacementBias = json.displacementBias;
29199 if (json.roughnessMap !== undefined) material.roughnessMap = getTexture(json.roughnessMap);
29200 if (json.metalnessMap !== undefined) material.metalnessMap = getTexture(json.metalnessMap);
29201 if (json.emissiveMap !== undefined) material.emissiveMap = getTexture(json.emissiveMap);
29202 if (json.emissiveIntensity !== undefined) material.emissiveIntensity = json.emissiveIntensity;
29203 if (json.specularMap !== undefined) material.specularMap = getTexture(json.specularMap);
29204 if (json.envMap !== undefined) material.envMap = getTexture(json.envMap);
29205 if (json.envMapIntensity !== undefined) material.envMapIntensity = json.envMapIntensity;
29206 if (json.reflectivity !== undefined) material.reflectivity = json.reflectivity;
29207 if (json.refractionRatio !== undefined) material.refractionRatio = json.refractionRatio;
29208 if (json.lightMap !== undefined) material.lightMap = getTexture(json.lightMap);
29209 if (json.lightMapIntensity !== undefined) material.lightMapIntensity = json.lightMapIntensity;
29210 if (json.aoMap !== undefined) material.aoMap = getTexture(json.aoMap);
29211 if (json.aoMapIntensity !== undefined) material.aoMapIntensity = json.aoMapIntensity;
29212 if (json.gradientMap !== undefined) material.gradientMap = getTexture(json.gradientMap);
29213 if (json.clearcoatMap !== undefined) material.clearcoatMap = getTexture(json.clearcoatMap);
29214 if (json.clearcoatRoughnessMap !== undefined) material.clearcoatRoughnessMap = getTexture(json.clearcoatRoughnessMap);
29215 if (json.clearcoatNormalMap !== undefined) material.clearcoatNormalMap = getTexture(json.clearcoatNormalMap);
29216 if (json.clearcoatNormalScale !== undefined) material.clearcoatNormalScale = new Vector2().fromArray(json.clearcoatNormalScale);
29217 if (json.transmission !== undefined) material.transmission = json.transmission;
29218 if (json.transmissionMap !== undefined) material.transmissionMap = getTexture(json.transmissionMap);
29221 setTextures: function setTextures(value) {
29222 this.textures = value;
29227 var LoaderUtils = {
29228 decodeText: function decodeText(array) {
29229 if (typeof TextDecoder !== 'undefined') {
29230 return new TextDecoder().decode(array);
29231 } // Avoid the String.fromCharCode.apply(null, array) shortcut, which
29232 // throws a "maximum call stack size exceeded" error for large arrays.
29237 for (var i = 0, il = array.length; i < il; i++) {
29238 // Implicitly assumes little-endian.
29239 s += String.fromCharCode(array[i]);
29243 // merges multi-byte utf-8 characters.
29244 return decodeURIComponent(escape(s));
29250 extractUrlBase: function extractUrlBase(url) {
29251 var index = url.lastIndexOf('/');
29252 if (index === -1) return './';
29253 return url.substr(0, index + 1);
29257 function InstancedBufferGeometry() {
29258 BufferGeometry.call(this);
29259 this.type = 'InstancedBufferGeometry';
29260 this.instanceCount = Infinity;
29263 InstancedBufferGeometry.prototype = Object.assign(Object.create(BufferGeometry.prototype), {
29264 constructor: InstancedBufferGeometry,
29265 isInstancedBufferGeometry: true,
29266 copy: function copy(source) {
29267 BufferGeometry.prototype.copy.call(this, source);
29268 this.instanceCount = source.instanceCount;
29271 clone: function clone() {
29272 return new this.constructor().copy(this);
29274 toJSON: function toJSON() {
29275 var data = BufferGeometry.prototype.toJSON.call(this);
29276 data.instanceCount = this.instanceCount;
29277 data.isInstancedBufferGeometry = true;
29282 function InstancedBufferAttribute(array, itemSize, normalized, meshPerAttribute) {
29283 if (typeof normalized === 'number') {
29284 meshPerAttribute = normalized;
29285 normalized = false;
29286 console.error('THREE.InstancedBufferAttribute: The constructor now expects normalized as the third argument.');
29289 BufferAttribute.call(this, array, itemSize, normalized);
29290 this.meshPerAttribute = meshPerAttribute || 1;
29293 InstancedBufferAttribute.prototype = Object.assign(Object.create(BufferAttribute.prototype), {
29294 constructor: InstancedBufferAttribute,
29295 isInstancedBufferAttribute: true,
29296 copy: function copy(source) {
29297 BufferAttribute.prototype.copy.call(this, source);
29298 this.meshPerAttribute = source.meshPerAttribute;
29301 toJSON: function toJSON() {
29302 var data = BufferAttribute.prototype.toJSON.call(this);
29303 data.meshPerAttribute = this.meshPerAttribute;
29304 data.isInstancedBufferAttribute = true;
29309 function BufferGeometryLoader(manager) {
29310 Loader.call(this, manager);
29313 BufferGeometryLoader.prototype = Object.assign(Object.create(Loader.prototype), {
29314 constructor: BufferGeometryLoader,
29315 load: function load(url, onLoad, onProgress, onError) {
29317 var loader = new FileLoader(scope.manager);
29318 loader.setPath(scope.path);
29319 loader.setRequestHeader(scope.requestHeader);
29320 loader.setWithCredentials(scope.withCredentials);
29321 loader.load(url, function (text) {
29323 onLoad(scope.parse(JSON.parse(text)));
29331 scope.manager.itemError(url);
29333 }, onProgress, onError);
29335 parse: function parse(json) {
29336 var interleavedBufferMap = {};
29337 var arrayBufferMap = {};
29339 function getInterleavedBuffer(json, uuid) {
29340 if (interleavedBufferMap[uuid] !== undefined) return interleavedBufferMap[uuid];
29341 var interleavedBuffers = json.interleavedBuffers;
29342 var interleavedBuffer = interleavedBuffers[uuid];
29343 var buffer = getArrayBuffer(json, interleavedBuffer.buffer);
29344 var array = getTypedArray(interleavedBuffer.type, buffer);
29345 var ib = new InterleavedBuffer(array, interleavedBuffer.stride);
29346 ib.uuid = interleavedBuffer.uuid;
29347 interleavedBufferMap[uuid] = ib;
29351 function getArrayBuffer(json, uuid) {
29352 if (arrayBufferMap[uuid] !== undefined) return arrayBufferMap[uuid];
29353 var arrayBuffers = json.arrayBuffers;
29354 var arrayBuffer = arrayBuffers[uuid];
29355 var ab = new Uint32Array(arrayBuffer).buffer;
29356 arrayBufferMap[uuid] = ab;
29360 var geometry = json.isInstancedBufferGeometry ? new InstancedBufferGeometry() : new BufferGeometry();
29361 var index = json.data.index;
29363 if (index !== undefined) {
29364 var typedArray = getTypedArray(index.type, index.array);
29365 geometry.setIndex(new BufferAttribute(typedArray, 1));
29368 var attributes = json.data.attributes;
29370 for (var key in attributes) {
29371 var attribute = attributes[key];
29372 var bufferAttribute = void 0;
29374 if (attribute.isInterleavedBufferAttribute) {
29375 var interleavedBuffer = getInterleavedBuffer(json.data, attribute.data);
29376 bufferAttribute = new InterleavedBufferAttribute(interleavedBuffer, attribute.itemSize, attribute.offset, attribute.normalized);
29378 var _typedArray = getTypedArray(attribute.type, attribute.array);
29380 var bufferAttributeConstr = attribute.isInstancedBufferAttribute ? InstancedBufferAttribute : BufferAttribute;
29381 bufferAttribute = new bufferAttributeConstr(_typedArray, attribute.itemSize, attribute.normalized);
29384 if (attribute.name !== undefined) bufferAttribute.name = attribute.name;
29385 geometry.setAttribute(key, bufferAttribute);
29388 var morphAttributes = json.data.morphAttributes;
29390 if (morphAttributes) {
29391 for (var _key in morphAttributes) {
29392 var attributeArray = morphAttributes[_key];
29395 for (var i = 0, il = attributeArray.length; i < il; i++) {
29396 var _attribute = attributeArray[i];
29398 var _bufferAttribute = void 0;
29400 if (_attribute.isInterleavedBufferAttribute) {
29401 var _interleavedBuffer = getInterleavedBuffer(json.data, _attribute.data);
29403 _bufferAttribute = new InterleavedBufferAttribute(_interleavedBuffer, _attribute.itemSize, _attribute.offset, _attribute.normalized);
29405 var _typedArray2 = getTypedArray(_attribute.type, _attribute.array);
29407 _bufferAttribute = new BufferAttribute(_typedArray2, _attribute.itemSize, _attribute.normalized);
29410 if (_attribute.name !== undefined) _bufferAttribute.name = _attribute.name;
29411 array.push(_bufferAttribute);
29414 geometry.morphAttributes[_key] = array;
29418 var morphTargetsRelative = json.data.morphTargetsRelative;
29420 if (morphTargetsRelative) {
29421 geometry.morphTargetsRelative = true;
29424 var groups = json.data.groups || json.data.drawcalls || json.data.offsets;
29426 if (groups !== undefined) {
29427 for (var _i = 0, n = groups.length; _i !== n; ++_i) {
29428 var group = groups[_i];
29429 geometry.addGroup(group.start, group.count, group.materialIndex);
29433 var boundingSphere = json.data.boundingSphere;
29435 if (boundingSphere !== undefined) {
29436 var center = new Vector3();
29438 if (boundingSphere.center !== undefined) {
29439 center.fromArray(boundingSphere.center);
29442 geometry.boundingSphere = new Sphere(center, boundingSphere.radius);
29445 if (json.name) geometry.name = json.name;
29446 if (json.userData) geometry.userData = json.userData;
29451 var ObjectLoader = /*#__PURE__*/function (_Loader) {
29452 _inheritsLoose(ObjectLoader, _Loader);
29454 function ObjectLoader(manager) {
29455 return _Loader.call(this, manager) || this;
29458 var _proto = ObjectLoader.prototype;
29460 _proto.load = function load(url, onLoad, onProgress, onError) {
29462 var path = this.path === '' ? LoaderUtils.extractUrlBase(url) : this.path;
29463 this.resourcePath = this.resourcePath || path;
29464 var loader = new FileLoader(this.manager);
29465 loader.setPath(this.path);
29466 loader.setRequestHeader(this.requestHeader);
29467 loader.setWithCredentials(this.withCredentials);
29468 loader.load(url, function (text) {
29472 json = JSON.parse(text);
29474 if (onError !== undefined) onError(error);
29475 console.error('THREE:ObjectLoader: Can\'t parse ' + url + '.', error.message);
29479 var metadata = json.metadata;
29481 if (metadata === undefined || metadata.type === undefined || metadata.type.toLowerCase() === 'geometry') {
29482 console.error('THREE.ObjectLoader: Can\'t load ' + url);
29486 scope.parse(json, onLoad);
29487 }, onProgress, onError);
29490 _proto.parse = function parse(json, onLoad) {
29491 var animations = this.parseAnimations(json.animations);
29492 var shapes = this.parseShapes(json.shapes);
29493 var geometries = this.parseGeometries(json.geometries, shapes);
29494 var images = this.parseImages(json.images, function () {
29495 if (onLoad !== undefined) onLoad(object);
29497 var textures = this.parseTextures(json.textures, images);
29498 var materials = this.parseMaterials(json.materials, textures);
29499 var object = this.parseObject(json.object, geometries, materials, animations);
29500 var skeletons = this.parseSkeletons(json.skeletons, object);
29501 this.bindSkeletons(object, skeletons); //
29503 if (onLoad !== undefined) {
29504 var hasImages = false;
29506 for (var uuid in images) {
29507 if (images[uuid] instanceof HTMLImageElement) {
29513 if (hasImages === false) onLoad(object);
29519 _proto.parseShapes = function parseShapes(json) {
29522 if (json !== undefined) {
29523 for (var i = 0, l = json.length; i < l; i++) {
29524 var shape = new Shape().fromJSON(json[i]);
29525 shapes[shape.uuid] = shape;
29532 _proto.parseSkeletons = function parseSkeletons(json, object) {
29533 var skeletons = {};
29534 var bones = {}; // generate bone lookup table
29536 object.traverse(function (child) {
29537 if (child.isBone) bones[child.uuid] = child;
29538 }); // create skeletons
29540 if (json !== undefined) {
29541 for (var i = 0, l = json.length; i < l; i++) {
29542 var skeleton = new Skeleton().fromJSON(json[i], bones);
29543 skeletons[skeleton.uuid] = skeleton;
29550 _proto.parseGeometries = function parseGeometries(json, shapes) {
29551 var geometries = {};
29552 var geometryShapes;
29554 if (json !== undefined) {
29555 var bufferGeometryLoader = new BufferGeometryLoader();
29557 for (var i = 0, l = json.length; i < l; i++) {
29558 var geometry = void 0;
29559 var data = json[i];
29561 switch (data.type) {
29562 case 'PlaneGeometry':
29563 case 'PlaneBufferGeometry':
29564 geometry = new Geometries[data.type](data.width, data.height, data.widthSegments, data.heightSegments);
29567 case 'BoxGeometry':
29568 case 'BoxBufferGeometry':
29569 geometry = new Geometries[data.type](data.width, data.height, data.depth, data.widthSegments, data.heightSegments, data.depthSegments);
29572 case 'CircleGeometry':
29573 case 'CircleBufferGeometry':
29574 geometry = new Geometries[data.type](data.radius, data.segments, data.thetaStart, data.thetaLength);
29577 case 'CylinderGeometry':
29578 case 'CylinderBufferGeometry':
29579 geometry = new Geometries[data.type](data.radiusTop, data.radiusBottom, data.height, data.radialSegments, data.heightSegments, data.openEnded, data.thetaStart, data.thetaLength);
29582 case 'ConeGeometry':
29583 case 'ConeBufferGeometry':
29584 geometry = new Geometries[data.type](data.radius, data.height, data.radialSegments, data.heightSegments, data.openEnded, data.thetaStart, data.thetaLength);
29587 case 'SphereGeometry':
29588 case 'SphereBufferGeometry':
29589 geometry = new Geometries[data.type](data.radius, data.widthSegments, data.heightSegments, data.phiStart, data.phiLength, data.thetaStart, data.thetaLength);
29592 case 'DodecahedronGeometry':
29593 case 'DodecahedronBufferGeometry':
29594 case 'IcosahedronGeometry':
29595 case 'IcosahedronBufferGeometry':
29596 case 'OctahedronGeometry':
29597 case 'OctahedronBufferGeometry':
29598 case 'TetrahedronGeometry':
29599 case 'TetrahedronBufferGeometry':
29600 geometry = new Geometries[data.type](data.radius, data.detail);
29603 case 'RingGeometry':
29604 case 'RingBufferGeometry':
29605 geometry = new Geometries[data.type](data.innerRadius, data.outerRadius, data.thetaSegments, data.phiSegments, data.thetaStart, data.thetaLength);
29608 case 'TorusGeometry':
29609 case 'TorusBufferGeometry':
29610 geometry = new Geometries[data.type](data.radius, data.tube, data.radialSegments, data.tubularSegments, data.arc);
29613 case 'TorusKnotGeometry':
29614 case 'TorusKnotBufferGeometry':
29615 geometry = new Geometries[data.type](data.radius, data.tube, data.tubularSegments, data.radialSegments, data.p, data.q);
29618 case 'TubeGeometry':
29619 case 'TubeBufferGeometry':
29620 // This only works for built-in curves (e.g. CatmullRomCurve3).
29621 // User defined curves or instances of CurvePath will not be deserialized.
29622 geometry = new Geometries[data.type](new Curves[data.path.type]().fromJSON(data.path), data.tubularSegments, data.radius, data.radialSegments, data.closed);
29625 case 'LatheGeometry':
29626 case 'LatheBufferGeometry':
29627 geometry = new Geometries[data.type](data.points, data.segments, data.phiStart, data.phiLength);
29630 case 'PolyhedronGeometry':
29631 case 'PolyhedronBufferGeometry':
29632 geometry = new Geometries[data.type](data.vertices, data.indices, data.radius, data.details);
29635 case 'ShapeGeometry':
29636 case 'ShapeBufferGeometry':
29637 geometryShapes = [];
29639 for (var j = 0, jl = data.shapes.length; j < jl; j++) {
29640 var shape = shapes[data.shapes[j]];
29641 geometryShapes.push(shape);
29644 geometry = new Geometries[data.type](geometryShapes, data.curveSegments);
29647 case 'ExtrudeGeometry':
29648 case 'ExtrudeBufferGeometry':
29649 geometryShapes = [];
29651 for (var _j = 0, _jl = data.shapes.length; _j < _jl; _j++) {
29652 var _shape = shapes[data.shapes[_j]];
29653 geometryShapes.push(_shape);
29656 var extrudePath = data.options.extrudePath;
29658 if (extrudePath !== undefined) {
29659 data.options.extrudePath = new Curves[extrudePath.type]().fromJSON(extrudePath);
29662 geometry = new Geometries[data.type](geometryShapes, data.options);
29665 case 'BufferGeometry':
29666 case 'InstancedBufferGeometry':
29667 geometry = bufferGeometryLoader.parse(data);
29671 console.error('THREE.ObjectLoader: Loading "Geometry" is not supported anymore.');
29675 console.warn('THREE.ObjectLoader: Unsupported geometry type "' + data.type + '"');
29679 geometry.uuid = data.uuid;
29680 if (data.name !== undefined) geometry.name = data.name;
29681 if (geometry.isBufferGeometry === true && data.userData !== undefined) geometry.userData = data.userData;
29682 geometries[data.uuid] = geometry;
29689 _proto.parseMaterials = function parseMaterials(json, textures) {
29690 var cache = {}; // MultiMaterial
29692 var materials = {};
29694 if (json !== undefined) {
29695 var loader = new MaterialLoader();
29696 loader.setTextures(textures);
29698 for (var i = 0, l = json.length; i < l; i++) {
29699 var data = json[i];
29701 if (data.type === 'MultiMaterial') {
29705 for (var j = 0; j < data.materials.length; j++) {
29706 var material = data.materials[j];
29708 if (cache[material.uuid] === undefined) {
29709 cache[material.uuid] = loader.parse(material);
29712 array.push(cache[material.uuid]);
29715 materials[data.uuid] = array;
29717 if (cache[data.uuid] === undefined) {
29718 cache[data.uuid] = loader.parse(data);
29721 materials[data.uuid] = cache[data.uuid];
29729 _proto.parseAnimations = function parseAnimations(json) {
29730 var animations = {};
29732 if (json !== undefined) {
29733 for (var i = 0; i < json.length; i++) {
29734 var data = json[i];
29735 var clip = AnimationClip.parse(data);
29736 animations[clip.uuid] = clip;
29743 _proto.parseImages = function parseImages(json, onLoad) {
29748 function loadImage(url) {
29749 scope.manager.itemStart(url);
29750 return loader.load(url, function () {
29751 scope.manager.itemEnd(url);
29752 }, undefined, function () {
29753 scope.manager.itemError(url);
29754 scope.manager.itemEnd(url);
29758 function deserializeImage(image) {
29759 if (typeof image === 'string') {
29761 var path = /^(\/\/)|([a-z]+:(\/\/)?)/i.test(url) ? url : scope.resourcePath + url;
29762 return loadImage(path);
29766 data: getTypedArray(image.type, image.data),
29767 width: image.width,
29768 height: image.height
29776 if (json !== undefined && json.length > 0) {
29777 var manager = new LoadingManager(onLoad);
29778 loader = new ImageLoader(manager);
29779 loader.setCrossOrigin(this.crossOrigin);
29781 for (var i = 0, il = json.length; i < il; i++) {
29782 var image = json[i];
29783 var url = image.url;
29785 if (Array.isArray(url)) {
29786 // load array of images e.g CubeTexture
29787 images[image.uuid] = [];
29789 for (var j = 0, jl = url.length; j < jl; j++) {
29790 var currentUrl = url[j];
29791 var deserializedImage = deserializeImage(currentUrl);
29793 if (deserializedImage !== null) {
29794 if (deserializedImage instanceof HTMLImageElement) {
29795 images[image.uuid].push(deserializedImage);
29797 // special case: handle array of data textures for cube textures
29798 images[image.uuid].push(new DataTexture(deserializedImage.data, deserializedImage.width, deserializedImage.height));
29803 // load single image
29804 var _deserializedImage = deserializeImage(image.url);
29806 if (_deserializedImage !== null) {
29807 images[image.uuid] = _deserializedImage;
29816 _proto.parseTextures = function parseTextures(json, images) {
29817 function parseConstant(value, type) {
29818 if (typeof value === 'number') return value;
29819 console.warn('THREE.ObjectLoader.parseTexture: Constant should be in numeric form.', value);
29820 return type[value];
29825 if (json !== undefined) {
29826 for (var i = 0, l = json.length; i < l; i++) {
29827 var data = json[i];
29829 if (data.image === undefined) {
29830 console.warn('THREE.ObjectLoader: No "image" specified for', data.uuid);
29833 if (images[data.image] === undefined) {
29834 console.warn('THREE.ObjectLoader: Undefined image', data.image);
29837 var texture = void 0;
29838 var image = images[data.image];
29840 if (Array.isArray(image)) {
29841 texture = new CubeTexture(image);
29842 if (image.length === 6) texture.needsUpdate = true;
29844 if (image && image.data) {
29845 texture = new DataTexture(image.data, image.width, image.height);
29847 texture = new Texture(image);
29850 if (image) texture.needsUpdate = true; // textures can have undefined image data
29853 texture.uuid = data.uuid;
29854 if (data.name !== undefined) texture.name = data.name;
29855 if (data.mapping !== undefined) texture.mapping = parseConstant(data.mapping, TEXTURE_MAPPING);
29856 if (data.offset !== undefined) texture.offset.fromArray(data.offset);
29857 if (data.repeat !== undefined) texture.repeat.fromArray(data.repeat);
29858 if (data.center !== undefined) texture.center.fromArray(data.center);
29859 if (data.rotation !== undefined) texture.rotation = data.rotation;
29861 if (data.wrap !== undefined) {
29862 texture.wrapS = parseConstant(data.wrap[0], TEXTURE_WRAPPING);
29863 texture.wrapT = parseConstant(data.wrap[1], TEXTURE_WRAPPING);
29866 if (data.format !== undefined) texture.format = data.format;
29867 if (data.type !== undefined) texture.type = data.type;
29868 if (data.encoding !== undefined) texture.encoding = data.encoding;
29869 if (data.minFilter !== undefined) texture.minFilter = parseConstant(data.minFilter, TEXTURE_FILTER);
29870 if (data.magFilter !== undefined) texture.magFilter = parseConstant(data.magFilter, TEXTURE_FILTER);
29871 if (data.anisotropy !== undefined) texture.anisotropy = data.anisotropy;
29872 if (data.flipY !== undefined) texture.flipY = data.flipY;
29873 if (data.premultiplyAlpha !== undefined) texture.premultiplyAlpha = data.premultiplyAlpha;
29874 if (data.unpackAlignment !== undefined) texture.unpackAlignment = data.unpackAlignment;
29875 textures[data.uuid] = texture;
29882 _proto.parseObject = function parseObject(data, geometries, materials, animations) {
29885 function getGeometry(name) {
29886 if (geometries[name] === undefined) {
29887 console.warn('THREE.ObjectLoader: Undefined geometry', name);
29890 return geometries[name];
29893 function getMaterial(name) {
29894 if (name === undefined) return undefined;
29896 if (Array.isArray(name)) {
29899 for (var i = 0, l = name.length; i < l; i++) {
29900 var uuid = name[i];
29902 if (materials[uuid] === undefined) {
29903 console.warn('THREE.ObjectLoader: Undefined material', uuid);
29906 array.push(materials[uuid]);
29912 if (materials[name] === undefined) {
29913 console.warn('THREE.ObjectLoader: Undefined material', name);
29916 return materials[name];
29919 var geometry, material;
29921 switch (data.type) {
29923 object = new Scene();
29925 if (data.background !== undefined) {
29926 if (Number.isInteger(data.background)) {
29927 object.background = new Color(data.background);
29931 if (data.fog !== undefined) {
29932 if (data.fog.type === 'Fog') {
29933 object.fog = new Fog(data.fog.color, data.fog.near, data.fog.far);
29934 } else if (data.fog.type === 'FogExp2') {
29935 object.fog = new FogExp2(data.fog.color, data.fog.density);
29941 case 'PerspectiveCamera':
29942 object = new PerspectiveCamera(data.fov, data.aspect, data.near, data.far);
29943 if (data.focus !== undefined) object.focus = data.focus;
29944 if (data.zoom !== undefined) object.zoom = data.zoom;
29945 if (data.filmGauge !== undefined) object.filmGauge = data.filmGauge;
29946 if (data.filmOffset !== undefined) object.filmOffset = data.filmOffset;
29947 if (data.view !== undefined) object.view = Object.assign({}, data.view);
29950 case 'OrthographicCamera':
29951 object = new OrthographicCamera(data.left, data.right, data.top, data.bottom, data.near, data.far);
29952 if (data.zoom !== undefined) object.zoom = data.zoom;
29953 if (data.view !== undefined) object.view = Object.assign({}, data.view);
29956 case 'AmbientLight':
29957 object = new AmbientLight(data.color, data.intensity);
29960 case 'DirectionalLight':
29961 object = new DirectionalLight(data.color, data.intensity);
29965 object = new PointLight(data.color, data.intensity, data.distance, data.decay);
29968 case 'RectAreaLight':
29969 object = new RectAreaLight(data.color, data.intensity, data.width, data.height);
29973 object = new SpotLight(data.color, data.intensity, data.distance, data.angle, data.penumbra, data.decay);
29976 case 'HemisphereLight':
29977 object = new HemisphereLight(data.color, data.groundColor, data.intensity);
29981 object = new LightProbe().fromJSON(data);
29984 case 'SkinnedMesh':
29985 geometry = getGeometry(data.geometry);
29986 material = getMaterial(data.material);
29987 object = new SkinnedMesh(geometry, material);
29988 if (data.bindMode !== undefined) object.bindMode = data.bindMode;
29989 if (data.bindMatrix !== undefined) object.bindMatrix.fromArray(data.bindMatrix);
29990 if (data.skeleton !== undefined) object.skeleton = data.skeleton;
29994 geometry = getGeometry(data.geometry);
29995 material = getMaterial(data.material);
29996 object = new Mesh(geometry, material);
29999 case 'InstancedMesh':
30000 geometry = getGeometry(data.geometry);
30001 material = getMaterial(data.material);
30002 var count = data.count;
30003 var instanceMatrix = data.instanceMatrix;
30004 object = new InstancedMesh(geometry, material, count);
30005 object.instanceMatrix = new BufferAttribute(new Float32Array(instanceMatrix.array), 16);
30009 object = new LOD();
30013 object = new Line(getGeometry(data.geometry), getMaterial(data.material));
30017 object = new LineLoop(getGeometry(data.geometry), getMaterial(data.material));
30020 case 'LineSegments':
30021 object = new LineSegments(getGeometry(data.geometry), getMaterial(data.material));
30026 object = new Points(getGeometry(data.geometry), getMaterial(data.material));
30030 object = new Sprite(getMaterial(data.material));
30034 object = new Group();
30038 object = new Bone();
30042 object = new Object3D();
30045 object.uuid = data.uuid;
30046 if (data.name !== undefined) object.name = data.name;
30048 if (data.matrix !== undefined) {
30049 object.matrix.fromArray(data.matrix);
30050 if (data.matrixAutoUpdate !== undefined) object.matrixAutoUpdate = data.matrixAutoUpdate;
30051 if (object.matrixAutoUpdate) object.matrix.decompose(object.position, object.quaternion, object.scale);
30053 if (data.position !== undefined) object.position.fromArray(data.position);
30054 if (data.rotation !== undefined) object.rotation.fromArray(data.rotation);
30055 if (data.quaternion !== undefined) object.quaternion.fromArray(data.quaternion);
30056 if (data.scale !== undefined) object.scale.fromArray(data.scale);
30059 if (data.castShadow !== undefined) object.castShadow = data.castShadow;
30060 if (data.receiveShadow !== undefined) object.receiveShadow = data.receiveShadow;
30063 if (data.shadow.bias !== undefined) object.shadow.bias = data.shadow.bias;
30064 if (data.shadow.normalBias !== undefined) object.shadow.normalBias = data.shadow.normalBias;
30065 if (data.shadow.radius !== undefined) object.shadow.radius = data.shadow.radius;
30066 if (data.shadow.mapSize !== undefined) object.shadow.mapSize.fromArray(data.shadow.mapSize);
30067 if (data.shadow.camera !== undefined) object.shadow.camera = this.parseObject(data.shadow.camera);
30070 if (data.visible !== undefined) object.visible = data.visible;
30071 if (data.frustumCulled !== undefined) object.frustumCulled = data.frustumCulled;
30072 if (data.renderOrder !== undefined) object.renderOrder = data.renderOrder;
30073 if (data.userData !== undefined) object.userData = data.userData;
30074 if (data.layers !== undefined) object.layers.mask = data.layers;
30076 if (data.children !== undefined) {
30077 var children = data.children;
30079 for (var i = 0; i < children.length; i++) {
30080 object.add(this.parseObject(children[i], geometries, materials, animations));
30084 if (data.animations !== undefined) {
30085 var objectAnimations = data.animations;
30087 for (var _i = 0; _i < objectAnimations.length; _i++) {
30088 var uuid = objectAnimations[_i];
30089 object.animations.push(animations[uuid]);
30093 if (data.type === 'LOD') {
30094 if (data.autoUpdate !== undefined) object.autoUpdate = data.autoUpdate;
30095 var levels = data.levels;
30097 for (var l = 0; l < levels.length; l++) {
30098 var level = levels[l];
30099 var child = object.getObjectByProperty('uuid', level.object);
30101 if (child !== undefined) {
30102 object.addLevel(child, level.distance);
30110 _proto.bindSkeletons = function bindSkeletons(object, skeletons) {
30111 if (Object.keys(skeletons).length === 0) return;
30112 object.traverse(function (child) {
30113 if (child.isSkinnedMesh === true && child.skeleton !== undefined) {
30114 var skeleton = skeletons[child.skeleton];
30116 if (skeleton === undefined) {
30117 console.warn('THREE.ObjectLoader: No skeleton found with UUID:', child.skeleton);
30119 child.bind(skeleton, child.bindMatrix);
30127 _proto.setTexturePath = function setTexturePath(value) {
30128 console.warn('THREE.ObjectLoader: .setTexturePath() has been renamed to .setResourcePath().');
30129 return this.setResourcePath(value);
30132 return ObjectLoader;
30135 var TEXTURE_MAPPING = {
30136 UVMapping: UVMapping,
30137 CubeReflectionMapping: CubeReflectionMapping,
30138 CubeRefractionMapping: CubeRefractionMapping,
30139 EquirectangularReflectionMapping: EquirectangularReflectionMapping,
30140 EquirectangularRefractionMapping: EquirectangularRefractionMapping,
30141 CubeUVReflectionMapping: CubeUVReflectionMapping,
30142 CubeUVRefractionMapping: CubeUVRefractionMapping
30144 var TEXTURE_WRAPPING = {
30145 RepeatWrapping: RepeatWrapping,
30146 ClampToEdgeWrapping: ClampToEdgeWrapping,
30147 MirroredRepeatWrapping: MirroredRepeatWrapping
30149 var TEXTURE_FILTER = {
30150 NearestFilter: NearestFilter,
30151 NearestMipmapNearestFilter: NearestMipmapNearestFilter,
30152 NearestMipmapLinearFilter: NearestMipmapLinearFilter,
30153 LinearFilter: LinearFilter,
30154 LinearMipmapNearestFilter: LinearMipmapNearestFilter,
30155 LinearMipmapLinearFilter: LinearMipmapLinearFilter
30158 function ImageBitmapLoader(manager) {
30159 if (typeof createImageBitmap === 'undefined') {
30160 console.warn('THREE.ImageBitmapLoader: createImageBitmap() not supported.');
30163 if (typeof fetch === 'undefined') {
30164 console.warn('THREE.ImageBitmapLoader: fetch() not supported.');
30167 Loader.call(this, manager);
30169 premultiplyAlpha: 'none'
30173 ImageBitmapLoader.prototype = Object.assign(Object.create(Loader.prototype), {
30174 constructor: ImageBitmapLoader,
30175 isImageBitmapLoader: true,
30176 setOptions: function setOptions(options) {
30177 this.options = options;
30180 load: function load(url, onLoad, onProgress, onError) {
30181 if (url === undefined) url = '';
30182 if (this.path !== undefined) url = this.path + url;
30183 url = this.manager.resolveURL(url);
30185 var cached = Cache.get(url);
30187 if (cached !== undefined) {
30188 scope.manager.itemStart(url);
30189 setTimeout(function () {
30190 if (onLoad) onLoad(cached);
30191 scope.manager.itemEnd(url);
30196 var fetchOptions = {};
30197 fetchOptions.credentials = this.crossOrigin === 'anonymous' ? 'same-origin' : 'include';
30198 fetch(url, fetchOptions).then(function (res) {
30200 }).then(function (blob) {
30201 return createImageBitmap(blob, scope.options);
30202 }).then(function (imageBitmap) {
30203 Cache.add(url, imageBitmap);
30204 if (onLoad) onLoad(imageBitmap);
30205 scope.manager.itemEnd(url);
30206 }).catch(function (e) {
30207 if (onError) onError(e);
30208 scope.manager.itemError(url);
30209 scope.manager.itemEnd(url);
30211 scope.manager.itemStart(url);
30215 function ShapePath() {
30216 this.type = 'ShapePath';
30217 this.color = new Color();
30218 this.subPaths = [];
30219 this.currentPath = null;
30222 Object.assign(ShapePath.prototype, {
30223 moveTo: function moveTo(x, y) {
30224 this.currentPath = new Path();
30225 this.subPaths.push(this.currentPath);
30226 this.currentPath.moveTo(x, y);
30229 lineTo: function lineTo(x, y) {
30230 this.currentPath.lineTo(x, y);
30233 quadraticCurveTo: function quadraticCurveTo(aCPx, aCPy, aX, aY) {
30234 this.currentPath.quadraticCurveTo(aCPx, aCPy, aX, aY);
30237 bezierCurveTo: function bezierCurveTo(aCP1x, aCP1y, aCP2x, aCP2y, aX, aY) {
30238 this.currentPath.bezierCurveTo(aCP1x, aCP1y, aCP2x, aCP2y, aX, aY);
30241 splineThru: function splineThru(pts) {
30242 this.currentPath.splineThru(pts);
30245 toShapes: function toShapes(isCCW, noHoles) {
30246 function toShapesNoHoles(inSubpaths) {
30249 for (var i = 0, l = inSubpaths.length; i < l; i++) {
30250 var _tmpPath = inSubpaths[i];
30252 var _tmpShape = new Shape();
30254 _tmpShape.curves = _tmpPath.curves;
30255 shapes.push(_tmpShape);
30261 function isPointInsidePolygon(inPt, inPolygon) {
30262 var polyLen = inPolygon.length; // inPt on polygon contour => immediate success or
30263 // toggling of inside/outside at every single! intersection point of an edge
30264 // with the horizontal line through inPt, left of inPt
30265 // not counting lowerY endpoints of edges and whole edges on that line
30267 var inside = false;
30269 for (var p = polyLen - 1, q = 0; q < polyLen; p = q++) {
30270 var edgeLowPt = inPolygon[p];
30271 var edgeHighPt = inPolygon[q];
30272 var edgeDx = edgeHighPt.x - edgeLowPt.x;
30273 var edgeDy = edgeHighPt.y - edgeLowPt.y;
30275 if (Math.abs(edgeDy) > Number.EPSILON) {
30278 edgeLowPt = inPolygon[q];
30280 edgeHighPt = inPolygon[p];
30284 if (inPt.y < edgeLowPt.y || inPt.y > edgeHighPt.y) continue;
30286 if (inPt.y === edgeLowPt.y) {
30287 if (inPt.x === edgeLowPt.x) return true; // inPt is on contour ?
30288 // continue; // no intersection or edgeLowPt => doesn't count !!!
30290 var perpEdge = edgeDy * (inPt.x - edgeLowPt.x) - edgeDx * (inPt.y - edgeLowPt.y);
30291 if (perpEdge === 0) return true; // inPt is on contour ?
30293 if (perpEdge < 0) continue;
30294 inside = !inside; // true intersection left of inPt
30297 // parallel or collinear
30298 if (inPt.y !== edgeLowPt.y) continue; // parallel
30299 // edge lies on the same horizontal line as inPt
30301 if (edgeHighPt.x <= inPt.x && inPt.x <= edgeLowPt.x || edgeLowPt.x <= inPt.x && inPt.x <= edgeHighPt.x) return true; // inPt: Point on contour !
30309 var isClockWise = ShapeUtils.isClockWise;
30310 var subPaths = this.subPaths;
30311 if (subPaths.length === 0) return [];
30312 if (noHoles === true) return toShapesNoHoles(subPaths);
30313 var solid, tmpPath, tmpShape;
30316 if (subPaths.length === 1) {
30317 tmpPath = subPaths[0];
30318 tmpShape = new Shape();
30319 tmpShape.curves = tmpPath.curves;
30320 shapes.push(tmpShape);
30324 var holesFirst = !isClockWise(subPaths[0].getPoints());
30325 holesFirst = isCCW ? !holesFirst : holesFirst; // console.log("Holes first", holesFirst);
30327 var betterShapeHoles = [];
30328 var newShapes = [];
30329 var newShapeHoles = [];
30332 newShapes[mainIdx] = undefined;
30333 newShapeHoles[mainIdx] = [];
30335 for (var i = 0, l = subPaths.length; i < l; i++) {
30336 tmpPath = subPaths[i];
30337 tmpPoints = tmpPath.getPoints();
30338 solid = isClockWise(tmpPoints);
30339 solid = isCCW ? !solid : solid;
30342 if (!holesFirst && newShapes[mainIdx]) mainIdx++;
30343 newShapes[mainIdx] = {
30347 newShapes[mainIdx].s.curves = tmpPath.curves;
30348 if (holesFirst) mainIdx++;
30349 newShapeHoles[mainIdx] = []; //console.log('cw', i);
30351 newShapeHoles[mainIdx].push({
30354 }); //console.log('ccw', i);
30356 } // only Holes? -> probably all Shapes with wrong orientation
30359 if (!newShapes[0]) return toShapesNoHoles(subPaths);
30361 if (newShapes.length > 1) {
30362 var ambiguous = false;
30365 for (var sIdx = 0, sLen = newShapes.length; sIdx < sLen; sIdx++) {
30366 betterShapeHoles[sIdx] = [];
30369 for (var _sIdx = 0, _sLen = newShapes.length; _sIdx < _sLen; _sIdx++) {
30370 var sho = newShapeHoles[_sIdx];
30372 for (var hIdx = 0; hIdx < sho.length; hIdx++) {
30373 var ho = sho[hIdx];
30374 var hole_unassigned = true;
30376 for (var s2Idx = 0; s2Idx < newShapes.length; s2Idx++) {
30377 if (isPointInsidePolygon(ho.p, newShapes[s2Idx].p)) {
30378 if (_sIdx !== s2Idx) toChange.push({
30384 if (hole_unassigned) {
30385 hole_unassigned = false;
30386 betterShapeHoles[s2Idx].push(ho);
30393 if (hole_unassigned) {
30394 betterShapeHoles[_sIdx].push(ho);
30397 } // console.log("ambiguous: ", ambiguous);
30400 if (toChange.length > 0) {
30401 // console.log("to change: ", toChange);
30402 if (!ambiguous) newShapeHoles = betterShapeHoles;
30408 for (var _i = 0, il = newShapes.length; _i < il; _i++) {
30409 tmpShape = newShapes[_i].s;
30410 shapes.push(tmpShape);
30411 tmpHoles = newShapeHoles[_i];
30413 for (var j = 0, jl = tmpHoles.length; j < jl; j++) {
30414 tmpShape.holes.push(tmpHoles[j].h);
30416 } //console.log("shape", shapes);
30423 var Font = /*#__PURE__*/function () {
30424 function Font(data) {
30425 Object.defineProperty(this, 'isFont', {
30428 this.type = 'Font';
30432 var _proto = Font.prototype;
30434 _proto.generateShapes = function generateShapes(text, size) {
30435 if (size === void 0) {
30440 var paths = createPaths(text, size, this.data);
30442 for (var p = 0, pl = paths.length; p < pl; p++) {
30443 Array.prototype.push.apply(shapes, paths[p].toShapes());
30452 function createPaths(text, size, data) {
30453 var chars = Array.from ? Array.from(text) : String(text).split(''); // workaround for IE11, see #13988
30455 var scale = size / data.resolution;
30456 var line_height = (data.boundingBox.yMax - data.boundingBox.yMin + data.underlineThickness) * scale;
30461 for (var i = 0; i < chars.length; i++) {
30462 var char = chars[i];
30464 if (char === '\n') {
30466 offsetY -= line_height;
30468 var ret = createPath(char, scale, offsetX, offsetY, data);
30469 offsetX += ret.offsetX;
30470 paths.push(ret.path);
30477 function createPath(char, scale, offsetX, offsetY, data) {
30478 var glyph = data.glyphs[char] || data.glyphs['?'];
30481 console.error('THREE.Font: character "' + char + '" does not exists in font family ' + data.familyName + '.');
30485 var path = new ShapePath();
30486 var x, y, cpx, cpy, cpx1, cpy1, cpx2, cpy2;
30489 var outline = glyph._cachedOutline || (glyph._cachedOutline = glyph.o.split(' '));
30491 for (var i = 0, l = outline.length; i < l;) {
30492 var action = outline[i++];
30497 x = outline[i++] * scale + offsetX;
30498 y = outline[i++] * scale + offsetY;
30504 x = outline[i++] * scale + offsetX;
30505 y = outline[i++] * scale + offsetY;
30510 // quadraticCurveTo
30511 cpx = outline[i++] * scale + offsetX;
30512 cpy = outline[i++] * scale + offsetY;
30513 cpx1 = outline[i++] * scale + offsetX;
30514 cpy1 = outline[i++] * scale + offsetY;
30515 path.quadraticCurveTo(cpx1, cpy1, cpx, cpy);
30520 cpx = outline[i++] * scale + offsetX;
30521 cpy = outline[i++] * scale + offsetY;
30522 cpx1 = outline[i++] * scale + offsetX;
30523 cpy1 = outline[i++] * scale + offsetY;
30524 cpx2 = outline[i++] * scale + offsetX;
30525 cpy2 = outline[i++] * scale + offsetY;
30526 path.bezierCurveTo(cpx1, cpy1, cpx2, cpy2, cpx, cpy);
30533 offsetX: glyph.ha * scale,
30538 function FontLoader(manager) {
30539 Loader.call(this, manager);
30542 FontLoader.prototype = Object.assign(Object.create(Loader.prototype), {
30543 constructor: FontLoader,
30544 load: function load(url, onLoad, onProgress, onError) {
30546 var loader = new FileLoader(this.manager);
30547 loader.setPath(this.path);
30548 loader.setRequestHeader(this.requestHeader);
30549 loader.setWithCredentials(scope.withCredentials);
30550 loader.load(url, function (text) {
30554 json = JSON.parse(text);
30556 console.warn('THREE.FontLoader: typeface.js support is being deprecated. Use typeface.json instead.');
30557 json = JSON.parse(text.substring(65, text.length - 2));
30560 var font = scope.parse(json);
30561 if (onLoad) onLoad(font);
30562 }, onProgress, onError);
30564 parse: function parse(json) {
30565 return new Font(json);
30571 var AudioContext = {
30572 getContext: function getContext() {
30573 if (_context === undefined) {
30574 _context = new (window.AudioContext || window.webkitAudioContext)();
30579 setContext: function setContext(value) {
30584 function AudioLoader(manager) {
30585 Loader.call(this, manager);
30588 AudioLoader.prototype = Object.assign(Object.create(Loader.prototype), {
30589 constructor: AudioLoader,
30590 load: function load(url, onLoad, onProgress, onError) {
30592 var loader = new FileLoader(scope.manager);
30593 loader.setResponseType('arraybuffer');
30594 loader.setPath(scope.path);
30595 loader.setRequestHeader(scope.requestHeader);
30596 loader.setWithCredentials(scope.withCredentials);
30597 loader.load(url, function (buffer) {
30599 // Create a copy of the buffer. The `decodeAudioData` method
30600 // detaches the buffer when complete, preventing reuse.
30601 var bufferCopy = buffer.slice(0);
30602 var context = AudioContext.getContext();
30603 context.decodeAudioData(bufferCopy, function (audioBuffer) {
30604 onLoad(audioBuffer);
30613 scope.manager.itemError(url);
30615 }, onProgress, onError);
30619 function HemisphereLightProbe(skyColor, groundColor, intensity) {
30620 LightProbe.call(this, undefined, intensity);
30621 var color1 = new Color().set(skyColor);
30622 var color2 = new Color().set(groundColor);
30623 var sky = new Vector3(color1.r, color1.g, color1.b);
30624 var ground = new Vector3(color2.r, color2.g, color2.b); // without extra factor of PI in the shader, should = 1 / Math.sqrt( Math.PI );
30626 var c0 = Math.sqrt(Math.PI);
30627 var c1 = c0 * Math.sqrt(0.75);
30628 this.sh.coefficients[0].copy(sky).add(ground).multiplyScalar(c0);
30629 this.sh.coefficients[1].copy(sky).sub(ground).multiplyScalar(c1);
30632 HemisphereLightProbe.prototype = Object.assign(Object.create(LightProbe.prototype), {
30633 constructor: HemisphereLightProbe,
30634 isHemisphereLightProbe: true,
30635 copy: function copy(source) {
30636 // modifying colors not currently supported
30637 LightProbe.prototype.copy.call(this, source);
30640 toJSON: function toJSON(meta) {
30641 var data = LightProbe.prototype.toJSON.call(this, meta); // data.sh = this.sh.toArray(); // todo
30647 function AmbientLightProbe(color, intensity) {
30648 LightProbe.call(this, undefined, intensity);
30649 var color1 = new Color().set(color); // without extra factor of PI in the shader, would be 2 / Math.sqrt( Math.PI );
30651 this.sh.coefficients[0].set(color1.r, color1.g, color1.b).multiplyScalar(2 * Math.sqrt(Math.PI));
30654 AmbientLightProbe.prototype = Object.assign(Object.create(LightProbe.prototype), {
30655 constructor: AmbientLightProbe,
30656 isAmbientLightProbe: true,
30657 copy: function copy(source) {
30658 // modifying color not currently supported
30659 LightProbe.prototype.copy.call(this, source);
30662 toJSON: function toJSON(meta) {
30663 var data = LightProbe.prototype.toJSON.call(this, meta); // data.sh = this.sh.toArray(); // todo
30669 var _eyeRight = new Matrix4();
30671 var _eyeLeft = new Matrix4();
30673 function StereoCamera() {
30674 this.type = 'StereoCamera';
30676 this.eyeSep = 0.064;
30677 this.cameraL = new PerspectiveCamera();
30678 this.cameraL.layers.enable(1);
30679 this.cameraL.matrixAutoUpdate = false;
30680 this.cameraR = new PerspectiveCamera();
30681 this.cameraR.layers.enable(2);
30682 this.cameraR.matrixAutoUpdate = false;
30694 Object.assign(StereoCamera.prototype, {
30695 update: function update(camera) {
30696 var cache = this._cache;
30697 var needsUpdate = cache.focus !== camera.focus || cache.fov !== camera.fov || cache.aspect !== camera.aspect * this.aspect || cache.near !== camera.near || cache.far !== camera.far || cache.zoom !== camera.zoom || cache.eyeSep !== this.eyeSep;
30700 cache.focus = camera.focus;
30701 cache.fov = camera.fov;
30702 cache.aspect = camera.aspect * this.aspect;
30703 cache.near = camera.near;
30704 cache.far = camera.far;
30705 cache.zoom = camera.zoom;
30706 cache.eyeSep = this.eyeSep; // Off-axis stereoscopic effect based on
30707 // http://paulbourke.net/stereographics/stereorender/
30709 var projectionMatrix = camera.projectionMatrix.clone();
30710 var eyeSepHalf = cache.eyeSep / 2;
30711 var eyeSepOnProjection = eyeSepHalf * cache.near / cache.focus;
30712 var ymax = cache.near * Math.tan(MathUtils.DEG2RAD * cache.fov * 0.5) / cache.zoom;
30713 var xmin, xmax; // translate xOffset
30715 _eyeLeft.elements[12] = -eyeSepHalf;
30716 _eyeRight.elements[12] = eyeSepHalf; // for left eye
30718 xmin = -ymax * cache.aspect + eyeSepOnProjection;
30719 xmax = ymax * cache.aspect + eyeSepOnProjection;
30720 projectionMatrix.elements[0] = 2 * cache.near / (xmax - xmin);
30721 projectionMatrix.elements[8] = (xmax + xmin) / (xmax - xmin);
30722 this.cameraL.projectionMatrix.copy(projectionMatrix); // for right eye
30724 xmin = -ymax * cache.aspect - eyeSepOnProjection;
30725 xmax = ymax * cache.aspect - eyeSepOnProjection;
30726 projectionMatrix.elements[0] = 2 * cache.near / (xmax - xmin);
30727 projectionMatrix.elements[8] = (xmax + xmin) / (xmax - xmin);
30728 this.cameraR.projectionMatrix.copy(projectionMatrix);
30731 this.cameraL.matrixWorld.copy(camera.matrixWorld).multiply(_eyeLeft);
30732 this.cameraR.matrixWorld.copy(camera.matrixWorld).multiply(_eyeRight);
30736 var Clock = /*#__PURE__*/function () {
30737 function Clock(autoStart) {
30738 this.autoStart = autoStart !== undefined ? autoStart : true;
30739 this.startTime = 0;
30741 this.elapsedTime = 0;
30742 this.running = false;
30745 var _proto = Clock.prototype;
30747 _proto.start = function start() {
30748 this.startTime = now();
30749 this.oldTime = this.startTime;
30750 this.elapsedTime = 0;
30751 this.running = true;
30754 _proto.stop = function stop() {
30755 this.getElapsedTime();
30756 this.running = false;
30757 this.autoStart = false;
30760 _proto.getElapsedTime = function getElapsedTime() {
30762 return this.elapsedTime;
30765 _proto.getDelta = function getDelta() {
30768 if (this.autoStart && !this.running) {
30773 if (this.running) {
30774 var newTime = now();
30775 diff = (newTime - this.oldTime) / 1000;
30776 this.oldTime = newTime;
30777 this.elapsedTime += diff;
30787 return (typeof performance === 'undefined' ? Date : performance).now(); // see #10732
30790 var _position$2 = /*@__PURE__*/new Vector3();
30792 var _quaternion$3 = /*@__PURE__*/new Quaternion();
30794 var _scale$1 = /*@__PURE__*/new Vector3();
30796 var _orientation = /*@__PURE__*/new Vector3();
30798 var AudioListener = /*#__PURE__*/function (_Object3D) {
30799 _inheritsLoose(AudioListener, _Object3D);
30801 function AudioListener() {
30804 _this = _Object3D.call(this) || this;
30805 _this.type = 'AudioListener';
30806 _this.context = AudioContext.getContext();
30807 _this.gain = _this.context.createGain();
30809 _this.gain.connect(_this.context.destination);
30811 _this.filter = null;
30812 _this.timeDelta = 0; // private
30814 _this._clock = new Clock();
30818 var _proto = AudioListener.prototype;
30820 _proto.getInput = function getInput() {
30824 _proto.removeFilter = function removeFilter() {
30825 if (this.filter !== null) {
30826 this.gain.disconnect(this.filter);
30827 this.filter.disconnect(this.context.destination);
30828 this.gain.connect(this.context.destination);
30829 this.filter = null;
30835 _proto.getFilter = function getFilter() {
30836 return this.filter;
30839 _proto.setFilter = function setFilter(value) {
30840 if (this.filter !== null) {
30841 this.gain.disconnect(this.filter);
30842 this.filter.disconnect(this.context.destination);
30844 this.gain.disconnect(this.context.destination);
30847 this.filter = value;
30848 this.gain.connect(this.filter);
30849 this.filter.connect(this.context.destination);
30853 _proto.getMasterVolume = function getMasterVolume() {
30854 return this.gain.gain.value;
30857 _proto.setMasterVolume = function setMasterVolume(value) {
30858 this.gain.gain.setTargetAtTime(value, this.context.currentTime, 0.01);
30862 _proto.updateMatrixWorld = function updateMatrixWorld(force) {
30863 _Object3D.prototype.updateMatrixWorld.call(this, force);
30865 var listener = this.context.listener;
30867 this.timeDelta = this._clock.getDelta();
30868 this.matrixWorld.decompose(_position$2, _quaternion$3, _scale$1);
30870 _orientation.set(0, 0, -1).applyQuaternion(_quaternion$3);
30872 if (listener.positionX) {
30873 // code path for Chrome (see #14393)
30874 var endTime = this.context.currentTime + this.timeDelta;
30875 listener.positionX.linearRampToValueAtTime(_position$2.x, endTime);
30876 listener.positionY.linearRampToValueAtTime(_position$2.y, endTime);
30877 listener.positionZ.linearRampToValueAtTime(_position$2.z, endTime);
30878 listener.forwardX.linearRampToValueAtTime(_orientation.x, endTime);
30879 listener.forwardY.linearRampToValueAtTime(_orientation.y, endTime);
30880 listener.forwardZ.linearRampToValueAtTime(_orientation.z, endTime);
30881 listener.upX.linearRampToValueAtTime(up.x, endTime);
30882 listener.upY.linearRampToValueAtTime(up.y, endTime);
30883 listener.upZ.linearRampToValueAtTime(up.z, endTime);
30885 listener.setPosition(_position$2.x, _position$2.y, _position$2.z);
30886 listener.setOrientation(_orientation.x, _orientation.y, _orientation.z, up.x, up.y, up.z);
30890 return AudioListener;
30893 var Audio = /*#__PURE__*/function (_Object3D) {
30894 _inheritsLoose(Audio, _Object3D);
30896 function Audio(listener) {
30899 _this = _Object3D.call(this) || this;
30900 _this.type = 'Audio';
30901 _this.listener = listener;
30902 _this.context = listener.context;
30903 _this.gain = _this.context.createGain();
30905 _this.gain.connect(listener.getInput());
30907 _this.autoplay = false;
30908 _this.buffer = null;
30910 _this.loop = false;
30911 _this.loopStart = 0;
30914 _this.duration = undefined;
30915 _this.playbackRate = 1;
30916 _this.isPlaying = false;
30917 _this.hasPlaybackControl = true;
30918 _this.source = null;
30919 _this.sourceType = 'empty';
30920 _this._startedAt = 0;
30921 _this._progress = 0;
30922 _this._connected = false;
30923 _this.filters = [];
30927 var _proto = Audio.prototype;
30929 _proto.getOutput = function getOutput() {
30933 _proto.setNodeSource = function setNodeSource(audioNode) {
30934 this.hasPlaybackControl = false;
30935 this.sourceType = 'audioNode';
30936 this.source = audioNode;
30941 _proto.setMediaElementSource = function setMediaElementSource(mediaElement) {
30942 this.hasPlaybackControl = false;
30943 this.sourceType = 'mediaNode';
30944 this.source = this.context.createMediaElementSource(mediaElement);
30949 _proto.setMediaStreamSource = function setMediaStreamSource(mediaStream) {
30950 this.hasPlaybackControl = false;
30951 this.sourceType = 'mediaStreamNode';
30952 this.source = this.context.createMediaStreamSource(mediaStream);
30957 _proto.setBuffer = function setBuffer(audioBuffer) {
30958 this.buffer = audioBuffer;
30959 this.sourceType = 'buffer';
30960 if (this.autoplay) this.play();
30964 _proto.play = function play(delay) {
30965 if (delay === void 0) {
30969 if (this.isPlaying === true) {
30970 console.warn('THREE.Audio: Audio is already playing.');
30974 if (this.hasPlaybackControl === false) {
30975 console.warn('THREE.Audio: this Audio has no playback control.');
30979 this._startedAt = this.context.currentTime + delay;
30980 var source = this.context.createBufferSource();
30981 source.buffer = this.buffer;
30982 source.loop = this.loop;
30983 source.loopStart = this.loopStart;
30984 source.loopEnd = this.loopEnd;
30985 source.onended = this.onEnded.bind(this);
30986 source.start(this._startedAt, this._progress + this.offset, this.duration);
30987 this.isPlaying = true;
30988 this.source = source;
30989 this.setDetune(this.detune);
30990 this.setPlaybackRate(this.playbackRate);
30991 return this.connect();
30994 _proto.pause = function pause() {
30995 if (this.hasPlaybackControl === false) {
30996 console.warn('THREE.Audio: this Audio has no playback control.');
31000 if (this.isPlaying === true) {
31001 // update current progress
31002 this._progress += Math.max(this.context.currentTime - this._startedAt, 0) * this.playbackRate;
31004 if (this.loop === true) {
31005 // ensure _progress does not exceed duration with looped audios
31006 this._progress = this._progress % (this.duration || this.buffer.duration);
31009 this.source.stop();
31010 this.source.onended = null;
31011 this.isPlaying = false;
31017 _proto.stop = function stop() {
31018 if (this.hasPlaybackControl === false) {
31019 console.warn('THREE.Audio: this Audio has no playback control.');
31023 this._progress = 0;
31024 this.source.stop();
31025 this.source.onended = null;
31026 this.isPlaying = false;
31030 _proto.connect = function connect() {
31031 if (this.filters.length > 0) {
31032 this.source.connect(this.filters[0]);
31034 for (var i = 1, l = this.filters.length; i < l; i++) {
31035 this.filters[i - 1].connect(this.filters[i]);
31038 this.filters[this.filters.length - 1].connect(this.getOutput());
31040 this.source.connect(this.getOutput());
31043 this._connected = true;
31047 _proto.disconnect = function disconnect() {
31048 if (this.filters.length > 0) {
31049 this.source.disconnect(this.filters[0]);
31051 for (var i = 1, l = this.filters.length; i < l; i++) {
31052 this.filters[i - 1].disconnect(this.filters[i]);
31055 this.filters[this.filters.length - 1].disconnect(this.getOutput());
31057 this.source.disconnect(this.getOutput());
31060 this._connected = false;
31064 _proto.getFilters = function getFilters() {
31065 return this.filters;
31068 _proto.setFilters = function setFilters(value) {
31069 if (!value) value = [];
31071 if (this._connected === true) {
31073 this.filters = value.slice();
31076 this.filters = value.slice();
31082 _proto.setDetune = function setDetune(value) {
31083 this.detune = value;
31084 if (this.source.detune === undefined) return; // only set detune when available
31086 if (this.isPlaying === true) {
31087 this.source.detune.setTargetAtTime(this.detune, this.context.currentTime, 0.01);
31093 _proto.getDetune = function getDetune() {
31094 return this.detune;
31097 _proto.getFilter = function getFilter() {
31098 return this.getFilters()[0];
31101 _proto.setFilter = function setFilter(filter) {
31102 return this.setFilters(filter ? [filter] : []);
31105 _proto.setPlaybackRate = function setPlaybackRate(value) {
31106 if (this.hasPlaybackControl === false) {
31107 console.warn('THREE.Audio: this Audio has no playback control.');
31111 this.playbackRate = value;
31113 if (this.isPlaying === true) {
31114 this.source.playbackRate.setTargetAtTime(this.playbackRate, this.context.currentTime, 0.01);
31120 _proto.getPlaybackRate = function getPlaybackRate() {
31121 return this.playbackRate;
31124 _proto.onEnded = function onEnded() {
31125 this.isPlaying = false;
31128 _proto.getLoop = function getLoop() {
31129 if (this.hasPlaybackControl === false) {
31130 console.warn('THREE.Audio: this Audio has no playback control.');
31137 _proto.setLoop = function setLoop(value) {
31138 if (this.hasPlaybackControl === false) {
31139 console.warn('THREE.Audio: this Audio has no playback control.');
31145 if (this.isPlaying === true) {
31146 this.source.loop = this.loop;
31152 _proto.setLoopStart = function setLoopStart(value) {
31153 this.loopStart = value;
31157 _proto.setLoopEnd = function setLoopEnd(value) {
31158 this.loopEnd = value;
31162 _proto.getVolume = function getVolume() {
31163 return this.gain.gain.value;
31166 _proto.setVolume = function setVolume(value) {
31167 this.gain.gain.setTargetAtTime(value, this.context.currentTime, 0.01);
31174 var _position$3 = /*@__PURE__*/new Vector3();
31176 var _quaternion$4 = /*@__PURE__*/new Quaternion();
31178 var _scale$2 = /*@__PURE__*/new Vector3();
31180 var _orientation$1 = /*@__PURE__*/new Vector3();
31182 var PositionalAudio = /*#__PURE__*/function (_Audio) {
31183 _inheritsLoose(PositionalAudio, _Audio);
31185 function PositionalAudio(listener) {
31188 _this = _Audio.call(this, listener) || this;
31189 _this.panner = _this.context.createPanner();
31190 _this.panner.panningModel = 'HRTF';
31192 _this.panner.connect(_this.gain);
31197 var _proto = PositionalAudio.prototype;
31199 _proto.getOutput = function getOutput() {
31200 return this.panner;
31203 _proto.getRefDistance = function getRefDistance() {
31204 return this.panner.refDistance;
31207 _proto.setRefDistance = function setRefDistance(value) {
31208 this.panner.refDistance = value;
31212 _proto.getRolloffFactor = function getRolloffFactor() {
31213 return this.panner.rolloffFactor;
31216 _proto.setRolloffFactor = function setRolloffFactor(value) {
31217 this.panner.rolloffFactor = value;
31221 _proto.getDistanceModel = function getDistanceModel() {
31222 return this.panner.distanceModel;
31225 _proto.setDistanceModel = function setDistanceModel(value) {
31226 this.panner.distanceModel = value;
31230 _proto.getMaxDistance = function getMaxDistance() {
31231 return this.panner.maxDistance;
31234 _proto.setMaxDistance = function setMaxDistance(value) {
31235 this.panner.maxDistance = value;
31239 _proto.setDirectionalCone = function setDirectionalCone(coneInnerAngle, coneOuterAngle, coneOuterGain) {
31240 this.panner.coneInnerAngle = coneInnerAngle;
31241 this.panner.coneOuterAngle = coneOuterAngle;
31242 this.panner.coneOuterGain = coneOuterGain;
31246 _proto.updateMatrixWorld = function updateMatrixWorld(force) {
31247 _Audio.prototype.updateMatrixWorld.call(this, force);
31249 if (this.hasPlaybackControl === true && this.isPlaying === false) return;
31250 this.matrixWorld.decompose(_position$3, _quaternion$4, _scale$2);
31252 _orientation$1.set(0, 0, 1).applyQuaternion(_quaternion$4);
31254 var panner = this.panner;
31256 if (panner.positionX) {
31257 // code path for Chrome and Firefox (see #14393)
31258 var endTime = this.context.currentTime + this.listener.timeDelta;
31259 panner.positionX.linearRampToValueAtTime(_position$3.x, endTime);
31260 panner.positionY.linearRampToValueAtTime(_position$3.y, endTime);
31261 panner.positionZ.linearRampToValueAtTime(_position$3.z, endTime);
31262 panner.orientationX.linearRampToValueAtTime(_orientation$1.x, endTime);
31263 panner.orientationY.linearRampToValueAtTime(_orientation$1.y, endTime);
31264 panner.orientationZ.linearRampToValueAtTime(_orientation$1.z, endTime);
31266 panner.setPosition(_position$3.x, _position$3.y, _position$3.z);
31267 panner.setOrientation(_orientation$1.x, _orientation$1.y, _orientation$1.z);
31271 return PositionalAudio;
31274 var AudioAnalyser = /*#__PURE__*/function () {
31275 function AudioAnalyser(audio, fftSize) {
31276 if (fftSize === void 0) {
31280 this.analyser = audio.context.createAnalyser();
31281 this.analyser.fftSize = fftSize;
31282 this.data = new Uint8Array(this.analyser.frequencyBinCount);
31283 audio.getOutput().connect(this.analyser);
31286 var _proto = AudioAnalyser.prototype;
31288 _proto.getFrequencyData = function getFrequencyData() {
31289 this.analyser.getByteFrequencyData(this.data);
31293 _proto.getAverageFrequency = function getAverageFrequency() {
31295 var data = this.getFrequencyData();
31297 for (var i = 0; i < data.length; i++) {
31301 return value / data.length;
31304 return AudioAnalyser;
31307 function PropertyMixer(binding, typeName, valueSize) {
31308 this.binding = binding;
31309 this.valueSize = valueSize;
31310 var mixFunction, mixFunctionAdditive, setIdentity; // buffer layout: [ incoming | accu0 | accu1 | orig | addAccu | (optional work) ]
31312 // interpolators can use .buffer as their .result
31313 // the data then goes to 'incoming'
31315 // 'accu0' and 'accu1' are used frame-interleaved for
31316 // the cumulative result and are compared to detect
31319 // 'orig' stores the original state of the property
31321 // 'add' is used for additive cumulative results
31323 // 'work' is optional and is only present for quaternion types. It is used
31324 // to store intermediate quaternion multiplication results
31326 switch (typeName) {
31328 mixFunction = this._slerp;
31329 mixFunctionAdditive = this._slerpAdditive;
31330 setIdentity = this._setAdditiveIdentityQuaternion;
31331 this.buffer = new Float64Array(valueSize * 6);
31332 this._workIndex = 5;
31337 mixFunction = this._select; // Use the regular mix function and for additive on these types,
31338 // additive is not relevant for non-numeric types
31340 mixFunctionAdditive = this._select;
31341 setIdentity = this._setAdditiveIdentityOther;
31342 this.buffer = new Array(valueSize * 5);
31346 mixFunction = this._lerp;
31347 mixFunctionAdditive = this._lerpAdditive;
31348 setIdentity = this._setAdditiveIdentityNumeric;
31349 this.buffer = new Float64Array(valueSize * 5);
31352 this._mixBufferRegion = mixFunction;
31353 this._mixBufferRegionAdditive = mixFunctionAdditive;
31354 this._setIdentity = setIdentity;
31355 this._origIndex = 3;
31356 this._addIndex = 4;
31357 this.cumulativeWeight = 0;
31358 this.cumulativeWeightAdditive = 0;
31360 this.referenceCount = 0;
31363 Object.assign(PropertyMixer.prototype, {
31364 // accumulate data in the 'incoming' region into 'accu<i>'
31365 accumulate: function accumulate(accuIndex, weight) {
31366 // note: happily accumulating nothing when weight = 0, the caller knows
31367 // the weight and shouldn't have made the call in the first place
31368 var buffer = this.buffer,
31369 stride = this.valueSize,
31370 offset = accuIndex * stride + stride;
31371 var currentWeight = this.cumulativeWeight;
31373 if (currentWeight === 0) {
31374 // accuN := incoming * weight
31375 for (var i = 0; i !== stride; ++i) {
31376 buffer[offset + i] = buffer[i];
31379 currentWeight = weight;
31381 // accuN := accuN + incoming * weight
31382 currentWeight += weight;
31383 var mix = weight / currentWeight;
31385 this._mixBufferRegion(buffer, offset, 0, mix, stride);
31388 this.cumulativeWeight = currentWeight;
31390 // accumulate data in the 'incoming' region into 'add'
31391 accumulateAdditive: function accumulateAdditive(weight) {
31392 var buffer = this.buffer,
31393 stride = this.valueSize,
31394 offset = stride * this._addIndex;
31396 if (this.cumulativeWeightAdditive === 0) {
31398 this._setIdentity();
31399 } // add := add + incoming * weight
31402 this._mixBufferRegionAdditive(buffer, offset, 0, weight, stride);
31404 this.cumulativeWeightAdditive += weight;
31406 // apply the state of 'accu<i>' to the binding when accus differ
31407 apply: function apply(accuIndex) {
31408 var stride = this.valueSize,
31409 buffer = this.buffer,
31410 offset = accuIndex * stride + stride,
31411 weight = this.cumulativeWeight,
31412 weightAdditive = this.cumulativeWeightAdditive,
31413 binding = this.binding;
31414 this.cumulativeWeight = 0;
31415 this.cumulativeWeightAdditive = 0;
31418 // accuN := accuN + original * ( 1 - cumulativeWeight )
31419 var originalValueOffset = stride * this._origIndex;
31421 this._mixBufferRegion(buffer, offset, originalValueOffset, 1 - weight, stride);
31424 if (weightAdditive > 0) {
31425 // accuN := accuN + additive accuN
31426 this._mixBufferRegionAdditive(buffer, offset, this._addIndex * stride, 1, stride);
31429 for (var i = stride, e = stride + stride; i !== e; ++i) {
31430 if (buffer[i] !== buffer[i + stride]) {
31431 // value has changed -> update scene graph
31432 binding.setValue(buffer, offset);
31437 // remember the state of the bound property and copy it to both accus
31438 saveOriginalState: function saveOriginalState() {
31439 var binding = this.binding;
31440 var buffer = this.buffer,
31441 stride = this.valueSize,
31442 originalValueOffset = stride * this._origIndex;
31443 binding.getValue(buffer, originalValueOffset); // accu[0..1] := orig -- initially detect changes against the original
31445 for (var i = stride, e = originalValueOffset; i !== e; ++i) {
31446 buffer[i] = buffer[originalValueOffset + i % stride];
31447 } // Add to identity for additive
31450 this._setIdentity();
31452 this.cumulativeWeight = 0;
31453 this.cumulativeWeightAdditive = 0;
31455 // apply the state previously taken via 'saveOriginalState' to the binding
31456 restoreOriginalState: function restoreOriginalState() {
31457 var originalValueOffset = this.valueSize * 3;
31458 this.binding.setValue(this.buffer, originalValueOffset);
31460 _setAdditiveIdentityNumeric: function _setAdditiveIdentityNumeric() {
31461 var startIndex = this._addIndex * this.valueSize;
31462 var endIndex = startIndex + this.valueSize;
31464 for (var i = startIndex; i < endIndex; i++) {
31465 this.buffer[i] = 0;
31468 _setAdditiveIdentityQuaternion: function _setAdditiveIdentityQuaternion() {
31469 this._setAdditiveIdentityNumeric();
31471 this.buffer[this._addIndex * this.valueSize + 3] = 1;
31473 _setAdditiveIdentityOther: function _setAdditiveIdentityOther() {
31474 var startIndex = this._origIndex * this.valueSize;
31475 var targetIndex = this._addIndex * this.valueSize;
31477 for (var i = 0; i < this.valueSize; i++) {
31478 this.buffer[targetIndex + i] = this.buffer[startIndex + i];
31482 _select: function _select(buffer, dstOffset, srcOffset, t, stride) {
31484 for (var i = 0; i !== stride; ++i) {
31485 buffer[dstOffset + i] = buffer[srcOffset + i];
31489 _slerp: function _slerp(buffer, dstOffset, srcOffset, t) {
31490 Quaternion.slerpFlat(buffer, dstOffset, buffer, dstOffset, buffer, srcOffset, t);
31492 _slerpAdditive: function _slerpAdditive(buffer, dstOffset, srcOffset, t, stride) {
31493 var workOffset = this._workIndex * stride; // Store result in intermediate buffer offset
31495 Quaternion.multiplyQuaternionsFlat(buffer, workOffset, buffer, dstOffset, buffer, srcOffset); // Slerp to the intermediate result
31497 Quaternion.slerpFlat(buffer, dstOffset, buffer, dstOffset, buffer, workOffset, t);
31499 _lerp: function _lerp(buffer, dstOffset, srcOffset, t, stride) {
31502 for (var i = 0; i !== stride; ++i) {
31503 var j = dstOffset + i;
31504 buffer[j] = buffer[j] * s + buffer[srcOffset + i] * t;
31507 _lerpAdditive: function _lerpAdditive(buffer, dstOffset, srcOffset, t, stride) {
31508 for (var i = 0; i !== stride; ++i) {
31509 var j = dstOffset + i;
31510 buffer[j] = buffer[j] + buffer[srcOffset + i] * t;
31515 // Characters [].:/ are reserved for track binding syntax.
31516 var _RESERVED_CHARS_RE = '\\[\\]\\.:\\/';
31518 var _reservedRe = new RegExp('[' + _RESERVED_CHARS_RE + ']', 'g'); // Attempts to allow node names from any language. ES5's `\w` regexp matches
31519 // only latin characters, and the unicode \p{L} is not yet supported. So
31520 // instead, we exclude reserved characters and match everything else.
31523 var _wordChar = '[^' + _RESERVED_CHARS_RE + ']';
31525 var _wordCharOrDot = '[^' + _RESERVED_CHARS_RE.replace('\\.', '') + ']'; // Parent directories, delimited by '/' or ':'. Currently unused, but must
31526 // be matched to parse the rest of the track name.
31529 var _directoryRe = /((?:WC+[\/:])*)/.source.replace('WC', _wordChar); // Target node. May contain word characters (a-zA-Z0-9_) and '.' or '-'.
31532 var _nodeRe = /(WCOD+)?/.source.replace('WCOD', _wordCharOrDot); // Object on target node, and accessor. May not contain reserved
31533 // characters. Accessor may contain any character except closing bracket.
31536 var _objectRe = /(?:\.(WC+)(?:\[(.+)\])?)?/.source.replace('WC', _wordChar); // Property and accessor. May not contain reserved characters. Accessor may
31537 // contain any non-bracket characters.
31540 var _propertyRe = /\.(WC+)(?:\[(.+)\])?/.source.replace('WC', _wordChar);
31542 var _trackRe = new RegExp('' + '^' + _directoryRe + _nodeRe + _objectRe + _propertyRe + '$');
31544 var _supportedObjectNames = ['material', 'materials', 'bones'];
31546 function Composite(targetGroup, path, optionalParsedPath) {
31547 var parsedPath = optionalParsedPath || PropertyBinding.parseTrackName(path);
31548 this._targetGroup = targetGroup;
31549 this._bindings = targetGroup.subscribe_(path, parsedPath);
31552 Object.assign(Composite.prototype, {
31553 getValue: function getValue(array, offset) {
31554 this.bind(); // bind all binding
31556 var firstValidIndex = this._targetGroup.nCachedObjects_,
31557 binding = this._bindings[firstValidIndex]; // and only call .getValue on the first
31559 if (binding !== undefined) binding.getValue(array, offset);
31561 setValue: function setValue(array, offset) {
31562 var bindings = this._bindings;
31564 for (var i = this._targetGroup.nCachedObjects_, n = bindings.length; i !== n; ++i) {
31565 bindings[i].setValue(array, offset);
31568 bind: function bind() {
31569 var bindings = this._bindings;
31571 for (var i = this._targetGroup.nCachedObjects_, n = bindings.length; i !== n; ++i) {
31572 bindings[i].bind();
31575 unbind: function unbind() {
31576 var bindings = this._bindings;
31578 for (var i = this._targetGroup.nCachedObjects_, n = bindings.length; i !== n; ++i) {
31579 bindings[i].unbind();
31584 function PropertyBinding(rootNode, path, parsedPath) {
31586 this.parsedPath = parsedPath || PropertyBinding.parseTrackName(path);
31587 this.node = PropertyBinding.findNode(rootNode, this.parsedPath.nodeName) || rootNode;
31588 this.rootNode = rootNode;
31591 Object.assign(PropertyBinding, {
31592 Composite: Composite,
31593 create: function create(root, path, parsedPath) {
31594 if (!(root && root.isAnimationObjectGroup)) {
31595 return new PropertyBinding(root, path, parsedPath);
31597 return new PropertyBinding.Composite(root, path, parsedPath);
31602 * Replaces spaces with underscores and removes unsupported characters from
31603 * node names, to ensure compatibility with parseTrackName().
31605 * @param {string} name Node name to be sanitized.
31608 sanitizeNodeName: function sanitizeNodeName(name) {
31609 return name.replace(/\s/g, '_').replace(_reservedRe, '');
31611 parseTrackName: function parseTrackName(trackName) {
31612 var matches = _trackRe.exec(trackName);
31615 throw new Error('PropertyBinding: Cannot parse trackName: ' + trackName);
31619 // directoryName: matches[ 1 ], // (tschw) currently unused
31620 nodeName: matches[2],
31621 objectName: matches[3],
31622 objectIndex: matches[4],
31623 propertyName: matches[5],
31625 propertyIndex: matches[6]
31627 var lastDot = results.nodeName && results.nodeName.lastIndexOf('.');
31629 if (lastDot !== undefined && lastDot !== -1) {
31630 var objectName = results.nodeName.substring(lastDot + 1); // Object names must be checked against an allowlist. Otherwise, there
31631 // is no way to parse 'foo.bar.baz': 'baz' must be a property, but
31632 // 'bar' could be the objectName, or part of a nodeName (which can
31633 // include '.' characters).
31635 if (_supportedObjectNames.indexOf(objectName) !== -1) {
31636 results.nodeName = results.nodeName.substring(0, lastDot);
31637 results.objectName = objectName;
31641 if (results.propertyName === null || results.propertyName.length === 0) {
31642 throw new Error('PropertyBinding: can not parse propertyName from trackName: ' + trackName);
31647 findNode: function findNode(root, nodeName) {
31648 if (!nodeName || nodeName === '' || nodeName === '.' || nodeName === -1 || nodeName === root.name || nodeName === root.uuid) {
31650 } // search into skeleton bones.
31653 if (root.skeleton) {
31654 var bone = root.skeleton.getBoneByName(nodeName);
31656 if (bone !== undefined) {
31659 } // search into node subtree.
31662 if (root.children) {
31663 var searchNodeSubtree = function searchNodeSubtree(children) {
31664 for (var i = 0; i < children.length; i++) {
31665 var childNode = children[i];
31667 if (childNode.name === nodeName || childNode.uuid === nodeName) {
31671 var result = searchNodeSubtree(childNode.children);
31672 if (result) return result;
31678 var subTreeNode = searchNodeSubtree(root.children);
31681 return subTreeNode;
31688 Object.assign(PropertyBinding.prototype, {
31689 // prototype, continued
31690 // these are used to "bind" a nonexistent property
31691 _getValue_unavailable: function _getValue_unavailable() {},
31692 _setValue_unavailable: function _setValue_unavailable() {},
31702 MatrixWorldNeedsUpdate: 2
31704 GetterByBindingType: [function getValue_direct(buffer, offset) {
31705 buffer[offset] = this.node[this.propertyName];
31706 }, function getValue_array(buffer, offset) {
31707 var source = this.resolvedProperty;
31709 for (var i = 0, n = source.length; i !== n; ++i) {
31710 buffer[offset++] = source[i];
31712 }, function getValue_arrayElement(buffer, offset) {
31713 buffer[offset] = this.resolvedProperty[this.propertyIndex];
31714 }, function getValue_toArray(buffer, offset) {
31715 this.resolvedProperty.toArray(buffer, offset);
31717 SetterByBindingTypeAndVersioning: [[// Direct
31718 function setValue_direct(buffer, offset) {
31719 this.targetObject[this.propertyName] = buffer[offset];
31720 }, function setValue_direct_setNeedsUpdate(buffer, offset) {
31721 this.targetObject[this.propertyName] = buffer[offset];
31722 this.targetObject.needsUpdate = true;
31723 }, function setValue_direct_setMatrixWorldNeedsUpdate(buffer, offset) {
31724 this.targetObject[this.propertyName] = buffer[offset];
31725 this.targetObject.matrixWorldNeedsUpdate = true;
31726 }], [// EntireArray
31727 function setValue_array(buffer, offset) {
31728 var dest = this.resolvedProperty;
31730 for (var i = 0, n = dest.length; i !== n; ++i) {
31731 dest[i] = buffer[offset++];
31733 }, function setValue_array_setNeedsUpdate(buffer, offset) {
31734 var dest = this.resolvedProperty;
31736 for (var i = 0, n = dest.length; i !== n; ++i) {
31737 dest[i] = buffer[offset++];
31740 this.targetObject.needsUpdate = true;
31741 }, function setValue_array_setMatrixWorldNeedsUpdate(buffer, offset) {
31742 var dest = this.resolvedProperty;
31744 for (var i = 0, n = dest.length; i !== n; ++i) {
31745 dest[i] = buffer[offset++];
31748 this.targetObject.matrixWorldNeedsUpdate = true;
31749 }], [// ArrayElement
31750 function setValue_arrayElement(buffer, offset) {
31751 this.resolvedProperty[this.propertyIndex] = buffer[offset];
31752 }, function setValue_arrayElement_setNeedsUpdate(buffer, offset) {
31753 this.resolvedProperty[this.propertyIndex] = buffer[offset];
31754 this.targetObject.needsUpdate = true;
31755 }, function setValue_arrayElement_setMatrixWorldNeedsUpdate(buffer, offset) {
31756 this.resolvedProperty[this.propertyIndex] = buffer[offset];
31757 this.targetObject.matrixWorldNeedsUpdate = true;
31758 }], [// HasToFromArray
31759 function setValue_fromArray(buffer, offset) {
31760 this.resolvedProperty.fromArray(buffer, offset);
31761 }, function setValue_fromArray_setNeedsUpdate(buffer, offset) {
31762 this.resolvedProperty.fromArray(buffer, offset);
31763 this.targetObject.needsUpdate = true;
31764 }, function setValue_fromArray_setMatrixWorldNeedsUpdate(buffer, offset) {
31765 this.resolvedProperty.fromArray(buffer, offset);
31766 this.targetObject.matrixWorldNeedsUpdate = true;
31768 getValue: function getValue_unbound(targetArray, offset) {
31770 this.getValue(targetArray, offset); // Note: This class uses a State pattern on a per-method basis:
31771 // 'bind' sets 'this.getValue' / 'setValue' and shadows the
31772 // prototype version of these methods with one that represents
31773 // the bound state. When the property is not found, the methods
31776 setValue: function getValue_unbound(sourceArray, offset) {
31778 this.setValue(sourceArray, offset);
31780 // create getter / setter pair for a property in the scene graph
31781 bind: function bind() {
31782 var targetObject = this.node;
31783 var parsedPath = this.parsedPath;
31784 var objectName = parsedPath.objectName;
31785 var propertyName = parsedPath.propertyName;
31786 var propertyIndex = parsedPath.propertyIndex;
31788 if (!targetObject) {
31789 targetObject = PropertyBinding.findNode(this.rootNode, parsedPath.nodeName) || this.rootNode;
31790 this.node = targetObject;
31791 } // set fail state so we can just 'return' on error
31794 this.getValue = this._getValue_unavailable;
31795 this.setValue = this._setValue_unavailable; // ensure there is a value node
31797 if (!targetObject) {
31798 console.error('THREE.PropertyBinding: Trying to update node for track: ' + this.path + ' but it wasn\'t found.');
31803 var objectIndex = parsedPath.objectIndex; // special cases were we need to reach deeper into the hierarchy to get the face materials....
31805 switch (objectName) {
31807 if (!targetObject.material) {
31808 console.error('THREE.PropertyBinding: Can not bind to material as node does not have a material.', this);
31812 if (!targetObject.material.materials) {
31813 console.error('THREE.PropertyBinding: Can not bind to material.materials as node.material does not have a materials array.', this);
31817 targetObject = targetObject.material.materials;
31821 if (!targetObject.skeleton) {
31822 console.error('THREE.PropertyBinding: Can not bind to bones as node does not have a skeleton.', this);
31824 } // potential future optimization: skip this if propertyIndex is already an integer
31825 // and convert the integer string to a true integer.
31828 targetObject = targetObject.skeleton.bones; // support resolving morphTarget names into indices.
31830 for (var i = 0; i < targetObject.length; i++) {
31831 if (targetObject[i].name === objectIndex) {
31840 if (targetObject[objectName] === undefined) {
31841 console.error('THREE.PropertyBinding: Can not bind to objectName of node undefined.', this);
31845 targetObject = targetObject[objectName];
31848 if (objectIndex !== undefined) {
31849 if (targetObject[objectIndex] === undefined) {
31850 console.error('THREE.PropertyBinding: Trying to bind to objectIndex of objectName, but is undefined.', this, targetObject);
31854 targetObject = targetObject[objectIndex];
31856 } // resolve property
31859 var nodeProperty = targetObject[propertyName];
31861 if (nodeProperty === undefined) {
31862 var nodeName = parsedPath.nodeName;
31863 console.error('THREE.PropertyBinding: Trying to update property for track: ' + nodeName + '.' + propertyName + ' but it wasn\'t found.', targetObject);
31865 } // determine versioning scheme
31868 var versioning = this.Versioning.None;
31869 this.targetObject = targetObject;
31871 if (targetObject.needsUpdate !== undefined) {
31873 versioning = this.Versioning.NeedsUpdate;
31874 } else if (targetObject.matrixWorldNeedsUpdate !== undefined) {
31876 versioning = this.Versioning.MatrixWorldNeedsUpdate;
31877 } // determine how the property gets bound
31880 var bindingType = this.BindingType.Direct;
31882 if (propertyIndex !== undefined) {
31883 // access a sub element of the property array (only primitives are supported right now)
31884 if (propertyName === 'morphTargetInfluences') {
31885 // potential optimization, skip this if propertyIndex is already an integer, and convert the integer string to a true integer.
31886 // support resolving morphTarget names into indices.
31887 if (!targetObject.geometry) {
31888 console.error('THREE.PropertyBinding: Can not bind to morphTargetInfluences because node does not have a geometry.', this);
31892 if (targetObject.geometry.isBufferGeometry) {
31893 if (!targetObject.geometry.morphAttributes) {
31894 console.error('THREE.PropertyBinding: Can not bind to morphTargetInfluences because node does not have a geometry.morphAttributes.', this);
31898 if (targetObject.morphTargetDictionary[propertyIndex] !== undefined) {
31899 propertyIndex = targetObject.morphTargetDictionary[propertyIndex];
31902 console.error('THREE.PropertyBinding: Can not bind to morphTargetInfluences on THREE.Geometry. Use THREE.BufferGeometry instead.', this);
31907 bindingType = this.BindingType.ArrayElement;
31908 this.resolvedProperty = nodeProperty;
31909 this.propertyIndex = propertyIndex;
31910 } else if (nodeProperty.fromArray !== undefined && nodeProperty.toArray !== undefined) {
31911 // must use copy for Object3D.Euler/Quaternion
31912 bindingType = this.BindingType.HasFromToArray;
31913 this.resolvedProperty = nodeProperty;
31914 } else if (Array.isArray(nodeProperty)) {
31915 bindingType = this.BindingType.EntireArray;
31916 this.resolvedProperty = nodeProperty;
31918 this.propertyName = propertyName;
31919 } // select getter / setter
31922 this.getValue = this.GetterByBindingType[bindingType];
31923 this.setValue = this.SetterByBindingTypeAndVersioning[bindingType][versioning];
31925 unbind: function unbind() {
31926 this.node = null; // back to the prototype version of getValue / setValue
31927 // note: avoiding to mutate the shape of 'this' via 'delete'
31929 this.getValue = this._getValue_unbound;
31930 this.setValue = this._setValue_unbound;
31932 }); // DECLARE ALIAS AFTER assign prototype
31934 Object.assign(PropertyBinding.prototype, {
31935 // initial state of these methods that calls 'bind'
31936 _getValue_unbound: PropertyBinding.prototype.getValue,
31937 _setValue_unbound: PropertyBinding.prototype.setValue
31942 * A group of objects that receives a shared animation state.
31946 * - Add objects you would otherwise pass as 'root' to the
31947 * constructor or the .clipAction method of AnimationMixer.
31949 * - Instead pass this object as 'root'.
31951 * - You can also add and remove objects later when the mixer
31956 * Objects of this class appear as one object to the mixer,
31957 * so cache control of the individual objects must be done
31962 * - The animated properties must be compatible among the
31963 * all objects in the group.
31965 * - A single property can either be controlled through a
31966 * target group or directly, but not both.
31969 function AnimationObjectGroup() {
31970 this.uuid = MathUtils.generateUUID(); // cached objects followed by the active ones
31972 this._objects = Array.prototype.slice.call(arguments);
31973 this.nCachedObjects_ = 0; // threshold
31974 // note: read by PropertyBinding.Composite
31977 this._indicesByUUID = indices; // for bookkeeping
31979 for (var i = 0, n = arguments.length; i !== n; ++i) {
31980 indices[arguments[i].uuid] = i;
31983 this._paths = []; // inside: string
31985 this._parsedPaths = []; // inside: { we don't care, here }
31987 this._bindings = []; // inside: Array< PropertyBinding >
31989 this._bindingsIndicesByPath = {}; // inside: indices in these arrays
31995 return scope._objects.length;
31999 return this.total - scope.nCachedObjects_;
32004 get bindingsPerObject() {
32005 return scope._bindings.length;
32011 Object.assign(AnimationObjectGroup.prototype, {
32012 isAnimationObjectGroup: true,
32013 add: function add() {
32014 var objects = this._objects,
32015 indicesByUUID = this._indicesByUUID,
32016 paths = this._paths,
32017 parsedPaths = this._parsedPaths,
32018 bindings = this._bindings,
32019 nBindings = bindings.length;
32020 var knownObject = undefined,
32021 nObjects = objects.length,
32022 nCachedObjects = this.nCachedObjects_;
32024 for (var i = 0, n = arguments.length; i !== n; ++i) {
32025 var object = arguments[i],
32026 uuid = object.uuid;
32027 var index = indicesByUUID[uuid];
32029 if (index === undefined) {
32030 // unknown object -> add it to the ACTIVE region
32031 index = nObjects++;
32032 indicesByUUID[uuid] = index;
32033 objects.push(object); // accounting is done, now do the same for all bindings
32035 for (var j = 0, m = nBindings; j !== m; ++j) {
32036 bindings[j].push(new PropertyBinding(object, paths[j], parsedPaths[j]));
32038 } else if (index < nCachedObjects) {
32039 knownObject = objects[index]; // move existing object to the ACTIVE region
32041 var firstActiveIndex = --nCachedObjects,
32042 lastCachedObject = objects[firstActiveIndex];
32043 indicesByUUID[lastCachedObject.uuid] = index;
32044 objects[index] = lastCachedObject;
32045 indicesByUUID[uuid] = firstActiveIndex;
32046 objects[firstActiveIndex] = object; // accounting is done, now do the same for all bindings
32048 for (var _j = 0, _m = nBindings; _j !== _m; ++_j) {
32049 var bindingsForPath = bindings[_j],
32050 lastCached = bindingsForPath[firstActiveIndex];
32051 var binding = bindingsForPath[index];
32052 bindingsForPath[index] = lastCached;
32054 if (binding === undefined) {
32055 // since we do not bother to create new bindings
32056 // for objects that are cached, the binding may
32057 // or may not exist
32058 binding = new PropertyBinding(object, paths[_j], parsedPaths[_j]);
32061 bindingsForPath[firstActiveIndex] = binding;
32063 } else if (objects[index] !== knownObject) {
32064 console.error('THREE.AnimationObjectGroup: Different objects with the same UUID ' + 'detected. Clean the caches or recreate your infrastructure when reloading scenes.');
32065 } // else the object is already where we want it to be
32070 this.nCachedObjects_ = nCachedObjects;
32072 remove: function remove() {
32073 var objects = this._objects,
32074 indicesByUUID = this._indicesByUUID,
32075 bindings = this._bindings,
32076 nBindings = bindings.length;
32077 var nCachedObjects = this.nCachedObjects_;
32079 for (var i = 0, n = arguments.length; i !== n; ++i) {
32080 var object = arguments[i],
32081 uuid = object.uuid,
32082 index = indicesByUUID[uuid];
32084 if (index !== undefined && index >= nCachedObjects) {
32085 // move existing object into the CACHED region
32086 var lastCachedIndex = nCachedObjects++,
32087 firstActiveObject = objects[lastCachedIndex];
32088 indicesByUUID[firstActiveObject.uuid] = index;
32089 objects[index] = firstActiveObject;
32090 indicesByUUID[uuid] = lastCachedIndex;
32091 objects[lastCachedIndex] = object; // accounting is done, now do the same for all bindings
32093 for (var j = 0, m = nBindings; j !== m; ++j) {
32094 var bindingsForPath = bindings[j],
32095 firstActive = bindingsForPath[lastCachedIndex],
32096 binding = bindingsForPath[index];
32097 bindingsForPath[index] = firstActive;
32098 bindingsForPath[lastCachedIndex] = binding;
32104 this.nCachedObjects_ = nCachedObjects;
32107 uncache: function uncache() {
32108 var objects = this._objects,
32109 indicesByUUID = this._indicesByUUID,
32110 bindings = this._bindings,
32111 nBindings = bindings.length;
32112 var nCachedObjects = this.nCachedObjects_,
32113 nObjects = objects.length;
32115 for (var i = 0, n = arguments.length; i !== n; ++i) {
32116 var object = arguments[i],
32117 uuid = object.uuid,
32118 index = indicesByUUID[uuid];
32120 if (index !== undefined) {
32121 delete indicesByUUID[uuid];
32123 if (index < nCachedObjects) {
32124 // object is cached, shrink the CACHED region
32125 var firstActiveIndex = --nCachedObjects,
32126 lastCachedObject = objects[firstActiveIndex],
32127 lastIndex = --nObjects,
32128 lastObject = objects[lastIndex]; // last cached object takes this object's place
32130 indicesByUUID[lastCachedObject.uuid] = index;
32131 objects[index] = lastCachedObject; // last object goes to the activated slot and pop
32133 indicesByUUID[lastObject.uuid] = firstActiveIndex;
32134 objects[firstActiveIndex] = lastObject;
32135 objects.pop(); // accounting is done, now do the same for all bindings
32137 for (var j = 0, m = nBindings; j !== m; ++j) {
32138 var bindingsForPath = bindings[j],
32139 lastCached = bindingsForPath[firstActiveIndex],
32140 last = bindingsForPath[lastIndex];
32141 bindingsForPath[index] = lastCached;
32142 bindingsForPath[firstActiveIndex] = last;
32143 bindingsForPath.pop();
32146 // object is active, just swap with the last and pop
32147 var _lastIndex = --nObjects,
32148 _lastObject = objects[_lastIndex];
32150 if (_lastIndex > 0) {
32151 indicesByUUID[_lastObject.uuid] = index;
32154 objects[index] = _lastObject;
32155 objects.pop(); // accounting is done, now do the same for all bindings
32157 for (var _j2 = 0, _m2 = nBindings; _j2 !== _m2; ++_j2) {
32158 var _bindingsForPath = bindings[_j2];
32159 _bindingsForPath[index] = _bindingsForPath[_lastIndex];
32161 _bindingsForPath.pop();
32163 } // cached or active
32165 } // if object is known
32170 this.nCachedObjects_ = nCachedObjects;
32172 // Internal interface used by befriended PropertyBinding.Composite:
32173 subscribe_: function subscribe_(path, parsedPath) {
32174 // returns an array of bindings for the given path that is changed
32175 // according to the contained objects in the group
32176 var indicesByPath = this._bindingsIndicesByPath;
32177 var index = indicesByPath[path];
32178 var bindings = this._bindings;
32179 if (index !== undefined) return bindings[index];
32180 var paths = this._paths,
32181 parsedPaths = this._parsedPaths,
32182 objects = this._objects,
32183 nObjects = objects.length,
32184 nCachedObjects = this.nCachedObjects_,
32185 bindingsForPath = new Array(nObjects);
32186 index = bindings.length;
32187 indicesByPath[path] = index;
32189 parsedPaths.push(parsedPath);
32190 bindings.push(bindingsForPath);
32192 for (var i = nCachedObjects, n = objects.length; i !== n; ++i) {
32193 var object = objects[i];
32194 bindingsForPath[i] = new PropertyBinding(object, path, parsedPath);
32197 return bindingsForPath;
32199 unsubscribe_: function unsubscribe_(path) {
32200 // tells the group to forget about a property path and no longer
32201 // update the array previously obtained with 'subscribe_'
32202 var indicesByPath = this._bindingsIndicesByPath,
32203 index = indicesByPath[path];
32205 if (index !== undefined) {
32206 var paths = this._paths,
32207 parsedPaths = this._parsedPaths,
32208 bindings = this._bindings,
32209 lastBindingsIndex = bindings.length - 1,
32210 lastBindings = bindings[lastBindingsIndex],
32211 lastBindingsPath = path[lastBindingsIndex];
32212 indicesByPath[lastBindingsPath] = index;
32213 bindings[index] = lastBindings;
32215 parsedPaths[index] = parsedPaths[lastBindingsIndex];
32217 paths[index] = paths[lastBindingsIndex];
32223 var AnimationAction = /*#__PURE__*/function () {
32224 function AnimationAction(mixer, clip, localRoot, blendMode) {
32225 if (localRoot === void 0) {
32229 if (blendMode === void 0) {
32230 blendMode = clip.blendMode;
32233 this._mixer = mixer;
32235 this._localRoot = localRoot;
32236 this.blendMode = blendMode;
32237 var tracks = clip.tracks,
32238 nTracks = tracks.length,
32239 interpolants = new Array(nTracks);
32240 var interpolantSettings = {
32241 endingStart: ZeroCurvatureEnding,
32242 endingEnd: ZeroCurvatureEnding
32245 for (var i = 0; i !== nTracks; ++i) {
32246 var interpolant = tracks[i].createInterpolant(null);
32247 interpolants[i] = interpolant;
32248 interpolant.settings = interpolantSettings;
32251 this._interpolantSettings = interpolantSettings;
32252 this._interpolants = interpolants; // bound by the mixer
32253 // inside: PropertyMixer (managed by the mixer)
32255 this._propertyBindings = new Array(nTracks);
32256 this._cacheIndex = null; // for the memory manager
32258 this._byClipCacheIndex = null; // for the memory manager
32260 this._timeScaleInterpolant = null;
32261 this._weightInterpolant = null;
32262 this.loop = LoopRepeat;
32263 this._loopCount = -1; // global mixer time when the action is to be started
32264 // it's set back to 'null' upon start of the action
32266 this._startTime = null; // scaled local time of the action
32267 // gets clamped or wrapped to 0..clip.duration according to loop
32270 this.timeScale = 1;
32271 this._effectiveTimeScale = 1;
32273 this._effectiveWeight = 1;
32274 this.repetitions = Infinity; // no. of repetitions when looping
32276 this.paused = false; // true -> zero effective time scale
32278 this.enabled = true; // false -> zero effective weight
32280 this.clampWhenFinished = false; // keep feeding the last frame?
32282 this.zeroSlopeAtStart = true; // for smooth interpolation w/o separate
32284 this.zeroSlopeAtEnd = true; // clips for start, loop and end
32285 } // State & Scheduling
32288 var _proto = AnimationAction.prototype;
32290 _proto.play = function play() {
32291 this._mixer._activateAction(this);
32296 _proto.stop = function stop() {
32297 this._mixer._deactivateAction(this);
32299 return this.reset();
32302 _proto.reset = function reset() {
32303 this.paused = false;
32304 this.enabled = true;
32305 this.time = 0; // restart clip
32307 this._loopCount = -1; // forget previous loops
32309 this._startTime = null; // forget scheduling
32311 return this.stopFading().stopWarping();
32314 _proto.isRunning = function isRunning() {
32315 return this.enabled && !this.paused && this.timeScale !== 0 && this._startTime === null && this._mixer._isActiveAction(this);
32316 } // return true when play has been called
32319 _proto.isScheduled = function isScheduled() {
32320 return this._mixer._isActiveAction(this);
32323 _proto.startAt = function startAt(time) {
32324 this._startTime = time;
32328 _proto.setLoop = function setLoop(mode, repetitions) {
32330 this.repetitions = repetitions;
32333 // set the weight stopping any scheduled fading
32334 // although .enabled = false yields an effective weight of zero, this
32335 // method does *not* change .enabled, because it would be confusing
32338 _proto.setEffectiveWeight = function setEffectiveWeight(weight) {
32339 this.weight = weight; // note: same logic as when updated at runtime
32341 this._effectiveWeight = this.enabled ? weight : 0;
32342 return this.stopFading();
32343 } // return the weight considering fading and .enabled
32346 _proto.getEffectiveWeight = function getEffectiveWeight() {
32347 return this._effectiveWeight;
32350 _proto.fadeIn = function fadeIn(duration) {
32351 return this._scheduleFading(duration, 0, 1);
32354 _proto.fadeOut = function fadeOut(duration) {
32355 return this._scheduleFading(duration, 1, 0);
32358 _proto.crossFadeFrom = function crossFadeFrom(fadeOutAction, duration, warp) {
32359 fadeOutAction.fadeOut(duration);
32360 this.fadeIn(duration);
32363 var fadeInDuration = this._clip.duration,
32364 fadeOutDuration = fadeOutAction._clip.duration,
32365 startEndRatio = fadeOutDuration / fadeInDuration,
32366 endStartRatio = fadeInDuration / fadeOutDuration;
32367 fadeOutAction.warp(1.0, startEndRatio, duration);
32368 this.warp(endStartRatio, 1.0, duration);
32374 _proto.crossFadeTo = function crossFadeTo(fadeInAction, duration, warp) {
32375 return fadeInAction.crossFadeFrom(this, duration, warp);
32378 _proto.stopFading = function stopFading() {
32379 var weightInterpolant = this._weightInterpolant;
32381 if (weightInterpolant !== null) {
32382 this._weightInterpolant = null;
32384 this._mixer._takeBackControlInterpolant(weightInterpolant);
32388 } // Time Scale Control
32389 // set the time scale stopping any scheduled warping
32390 // although .paused = true yields an effective time scale of zero, this
32391 // method does *not* change .paused, because it would be confusing
32394 _proto.setEffectiveTimeScale = function setEffectiveTimeScale(timeScale) {
32395 this.timeScale = timeScale;
32396 this._effectiveTimeScale = this.paused ? 0 : timeScale;
32397 return this.stopWarping();
32398 } // return the time scale considering warping and .paused
32401 _proto.getEffectiveTimeScale = function getEffectiveTimeScale() {
32402 return this._effectiveTimeScale;
32405 _proto.setDuration = function setDuration(duration) {
32406 this.timeScale = this._clip.duration / duration;
32407 return this.stopWarping();
32410 _proto.syncWith = function syncWith(action) {
32411 this.time = action.time;
32412 this.timeScale = action.timeScale;
32413 return this.stopWarping();
32416 _proto.halt = function halt(duration) {
32417 return this.warp(this._effectiveTimeScale, 0, duration);
32420 _proto.warp = function warp(startTimeScale, endTimeScale, duration) {
32421 var mixer = this._mixer,
32423 timeScale = this.timeScale;
32424 var interpolant = this._timeScaleInterpolant;
32426 if (interpolant === null) {
32427 interpolant = mixer._lendControlInterpolant();
32428 this._timeScaleInterpolant = interpolant;
32431 var times = interpolant.parameterPositions,
32432 values = interpolant.sampleValues;
32434 times[1] = now + duration;
32435 values[0] = startTimeScale / timeScale;
32436 values[1] = endTimeScale / timeScale;
32440 _proto.stopWarping = function stopWarping() {
32441 var timeScaleInterpolant = this._timeScaleInterpolant;
32443 if (timeScaleInterpolant !== null) {
32444 this._timeScaleInterpolant = null;
32446 this._mixer._takeBackControlInterpolant(timeScaleInterpolant);
32450 } // Object Accessors
32453 _proto.getMixer = function getMixer() {
32454 return this._mixer;
32457 _proto.getClip = function getClip() {
32461 _proto.getRoot = function getRoot() {
32462 return this._localRoot || this._mixer._root;
32466 _proto._update = function _update(time, deltaTime, timeDirection, accuIndex) {
32467 // called by the mixer
32468 if (!this.enabled) {
32469 // call ._updateWeight() to update ._effectiveWeight
32470 this._updateWeight(time);
32475 var startTime = this._startTime;
32477 if (startTime !== null) {
32478 // check for scheduled start of action
32479 var timeRunning = (time - startTime) * timeDirection;
32481 if (timeRunning < 0 || timeDirection === 0) {
32482 return; // yet to come / don't decide when delta = 0
32486 this._startTime = null; // unschedule
32488 deltaTime = timeDirection * timeRunning;
32489 } // apply time scale and advance time
32492 deltaTime *= this._updateTimeScale(time);
32494 var clipTime = this._updateTime(deltaTime); // note: _updateTime may disable the action resulting in
32495 // an effective weight of 0
32498 var weight = this._updateWeight(time);
32501 var _interpolants = this._interpolants;
32502 var propertyMixers = this._propertyBindings;
32504 switch (this.blendMode) {
32505 case AdditiveAnimationBlendMode:
32506 for (var j = 0, m = _interpolants.length; j !== m; ++j) {
32507 _interpolants[j].evaluate(clipTime);
32509 propertyMixers[j].accumulateAdditive(weight);
32514 case NormalAnimationBlendMode:
32516 for (var _j = 0, _m = _interpolants.length; _j !== _m; ++_j) {
32517 _interpolants[_j].evaluate(clipTime);
32519 propertyMixers[_j].accumulate(accuIndex, weight);
32526 _proto._updateWeight = function _updateWeight(time) {
32529 if (this.enabled) {
32530 weight = this.weight;
32531 var interpolant = this._weightInterpolant;
32533 if (interpolant !== null) {
32534 var interpolantValue = interpolant.evaluate(time)[0];
32535 weight *= interpolantValue;
32537 if (time > interpolant.parameterPositions[1]) {
32540 if (interpolantValue === 0) {
32541 // faded out, disable
32542 this.enabled = false;
32548 this._effectiveWeight = weight;
32552 _proto._updateTimeScale = function _updateTimeScale(time) {
32555 if (!this.paused) {
32556 timeScale = this.timeScale;
32557 var interpolant = this._timeScaleInterpolant;
32559 if (interpolant !== null) {
32560 var interpolantValue = interpolant.evaluate(time)[0];
32561 timeScale *= interpolantValue;
32563 if (time > interpolant.parameterPositions[1]) {
32564 this.stopWarping();
32566 if (timeScale === 0) {
32567 // motion has halted, pause
32568 this.paused = true;
32570 // warp done - apply final time scale
32571 this.timeScale = timeScale;
32577 this._effectiveTimeScale = timeScale;
32581 _proto._updateTime = function _updateTime(deltaTime) {
32582 var duration = this._clip.duration;
32583 var loop = this.loop;
32584 var time = this.time + deltaTime;
32585 var loopCount = this._loopCount;
32586 var pingPong = loop === LoopPingPong;
32588 if (deltaTime === 0) {
32589 if (loopCount === -1) return time;
32590 return pingPong && (loopCount & 1) === 1 ? duration - time : time;
32593 if (loop === LoopOnce) {
32594 if (loopCount === -1) {
32596 this._loopCount = 0;
32598 this._setEndings(true, true, false);
32602 if (time >= duration) {
32604 } else if (time < 0) {
32611 if (this.clampWhenFinished) this.paused = true;else this.enabled = false;
32614 this._mixer.dispatchEvent({
32617 direction: deltaTime < 0 ? -1 : 1
32621 // repetitive Repeat or PingPong
32622 if (loopCount === -1) {
32624 if (deltaTime >= 0) {
32627 this._setEndings(true, this.repetitions === 0, pingPong);
32629 // when looping in reverse direction, the initial
32630 // transition through zero counts as a repetition,
32631 // so leave loopCount at -1
32632 this._setEndings(this.repetitions === 0, true, pingPong);
32636 if (time >= duration || time < 0) {
32638 var loopDelta = Math.floor(time / duration); // signed
32640 time -= duration * loopDelta;
32641 loopCount += Math.abs(loopDelta);
32642 var pending = this.repetitions - loopCount;
32644 if (pending <= 0) {
32645 // have to stop (switch state, clamp time, fire event)
32646 if (this.clampWhenFinished) this.paused = true;else this.enabled = false;
32647 time = deltaTime > 0 ? duration : 0;
32650 this._mixer.dispatchEvent({
32653 direction: deltaTime > 0 ? 1 : -1
32657 if (pending === 1) {
32658 // entering the last round
32659 var atStart = deltaTime < 0;
32661 this._setEndings(atStart, !atStart, pingPong);
32663 this._setEndings(false, false, pingPong);
32666 this._loopCount = loopCount;
32669 this._mixer.dispatchEvent({
32672 loopDelta: loopDelta
32679 if (pingPong && (loopCount & 1) === 1) {
32680 // invert time for the "pong round"
32681 return duration - time;
32688 _proto._setEndings = function _setEndings(atStart, atEnd, pingPong) {
32689 var settings = this._interpolantSettings;
32692 settings.endingStart = ZeroSlopeEnding;
32693 settings.endingEnd = ZeroSlopeEnding;
32695 // assuming for LoopOnce atStart == atEnd == true
32697 settings.endingStart = this.zeroSlopeAtStart ? ZeroSlopeEnding : ZeroCurvatureEnding;
32699 settings.endingStart = WrapAroundEnding;
32703 settings.endingEnd = this.zeroSlopeAtEnd ? ZeroSlopeEnding : ZeroCurvatureEnding;
32705 settings.endingEnd = WrapAroundEnding;
32710 _proto._scheduleFading = function _scheduleFading(duration, weightNow, weightThen) {
32711 var mixer = this._mixer,
32713 var interpolant = this._weightInterpolant;
32715 if (interpolant === null) {
32716 interpolant = mixer._lendControlInterpolant();
32717 this._weightInterpolant = interpolant;
32720 var times = interpolant.parameterPositions,
32721 values = interpolant.sampleValues;
32723 values[0] = weightNow;
32724 times[1] = now + duration;
32725 values[1] = weightThen;
32729 return AnimationAction;
32732 function AnimationMixer(root) {
32735 this._initMemoryManager();
32737 this._accuIndex = 0;
32739 this.timeScale = 1.0;
32742 AnimationMixer.prototype = Object.assign(Object.create(EventDispatcher.prototype), {
32743 constructor: AnimationMixer,
32744 _bindAction: function _bindAction(action, prototypeAction) {
32745 var root = action._localRoot || this._root,
32746 tracks = action._clip.tracks,
32747 nTracks = tracks.length,
32748 bindings = action._propertyBindings,
32749 interpolants = action._interpolants,
32750 rootUuid = root.uuid,
32751 bindingsByRoot = this._bindingsByRootAndName;
32752 var bindingsByName = bindingsByRoot[rootUuid];
32754 if (bindingsByName === undefined) {
32755 bindingsByName = {};
32756 bindingsByRoot[rootUuid] = bindingsByName;
32759 for (var i = 0; i !== nTracks; ++i) {
32760 var track = tracks[i],
32761 trackName = track.name;
32762 var binding = bindingsByName[trackName];
32764 if (binding !== undefined) {
32765 bindings[i] = binding;
32767 binding = bindings[i];
32769 if (binding !== undefined) {
32770 // existing binding, make sure the cache knows
32771 if (binding._cacheIndex === null) {
32772 ++binding.referenceCount;
32774 this._addInactiveBinding(binding, rootUuid, trackName);
32780 var path = prototypeAction && prototypeAction._propertyBindings[i].binding.parsedPath;
32781 binding = new PropertyMixer(PropertyBinding.create(root, trackName, path), track.ValueTypeName, track.getValueSize());
32782 ++binding.referenceCount;
32784 this._addInactiveBinding(binding, rootUuid, trackName);
32786 bindings[i] = binding;
32789 interpolants[i].resultBuffer = binding.buffer;
32792 _activateAction: function _activateAction(action) {
32793 if (!this._isActiveAction(action)) {
32794 if (action._cacheIndex === null) {
32795 // this action has been forgotten by the cache, but the user
32796 // appears to be still using it -> rebind
32797 var rootUuid = (action._localRoot || this._root).uuid,
32798 clipUuid = action._clip.uuid,
32799 actionsForClip = this._actionsByClip[clipUuid];
32801 this._bindAction(action, actionsForClip && actionsForClip.knownActions[0]);
32803 this._addInactiveAction(action, clipUuid, rootUuid);
32806 var bindings = action._propertyBindings; // increment reference counts / sort out state
32808 for (var i = 0, n = bindings.length; i !== n; ++i) {
32809 var binding = bindings[i];
32811 if (binding.useCount++ === 0) {
32812 this._lendBinding(binding);
32814 binding.saveOriginalState();
32818 this._lendAction(action);
32821 _deactivateAction: function _deactivateAction(action) {
32822 if (this._isActiveAction(action)) {
32823 var bindings = action._propertyBindings; // decrement reference counts / sort out state
32825 for (var i = 0, n = bindings.length; i !== n; ++i) {
32826 var binding = bindings[i];
32828 if (--binding.useCount === 0) {
32829 binding.restoreOriginalState();
32831 this._takeBackBinding(binding);
32835 this._takeBackAction(action);
32839 _initMemoryManager: function _initMemoryManager() {
32840 this._actions = []; // 'nActiveActions' followed by inactive ones
32842 this._nActiveActions = 0;
32843 this._actionsByClip = {}; // inside:
32845 // knownActions: Array< AnimationAction > - used as prototypes
32846 // actionByRoot: AnimationAction - lookup
32849 this._bindings = []; // 'nActiveBindings' followed by inactive ones
32851 this._nActiveBindings = 0;
32852 this._bindingsByRootAndName = {}; // inside: Map< name, PropertyMixer >
32854 this._controlInterpolants = []; // same game as above
32856 this._nActiveControlInterpolants = 0;
32861 return scope._actions.length;
32865 return scope._nActiveActions;
32871 return scope._bindings.length;
32875 return scope._nActiveBindings;
32879 controlInterpolants: {
32881 return scope._controlInterpolants.length;
32885 return scope._nActiveControlInterpolants;
32891 // Memory management for AnimationAction objects
32892 _isActiveAction: function _isActiveAction(action) {
32893 var index = action._cacheIndex;
32894 return index !== null && index < this._nActiveActions;
32896 _addInactiveAction: function _addInactiveAction(action, clipUuid, rootUuid) {
32897 var actions = this._actions,
32898 actionsByClip = this._actionsByClip;
32899 var actionsForClip = actionsByClip[clipUuid];
32901 if (actionsForClip === undefined) {
32903 knownActions: [action],
32906 action._byClipCacheIndex = 0;
32907 actionsByClip[clipUuid] = actionsForClip;
32909 var knownActions = actionsForClip.knownActions;
32910 action._byClipCacheIndex = knownActions.length;
32911 knownActions.push(action);
32914 action._cacheIndex = actions.length;
32915 actions.push(action);
32916 actionsForClip.actionByRoot[rootUuid] = action;
32918 _removeInactiveAction: function _removeInactiveAction(action) {
32919 var actions = this._actions,
32920 lastInactiveAction = actions[actions.length - 1],
32921 cacheIndex = action._cacheIndex;
32922 lastInactiveAction._cacheIndex = cacheIndex;
32923 actions[cacheIndex] = lastInactiveAction;
32925 action._cacheIndex = null;
32926 var clipUuid = action._clip.uuid,
32927 actionsByClip = this._actionsByClip,
32928 actionsForClip = actionsByClip[clipUuid],
32929 knownActionsForClip = actionsForClip.knownActions,
32930 lastKnownAction = knownActionsForClip[knownActionsForClip.length - 1],
32931 byClipCacheIndex = action._byClipCacheIndex;
32932 lastKnownAction._byClipCacheIndex = byClipCacheIndex;
32933 knownActionsForClip[byClipCacheIndex] = lastKnownAction;
32934 knownActionsForClip.pop();
32935 action._byClipCacheIndex = null;
32936 var actionByRoot = actionsForClip.actionByRoot,
32937 rootUuid = (action._localRoot || this._root).uuid;
32938 delete actionByRoot[rootUuid];
32940 if (knownActionsForClip.length === 0) {
32941 delete actionsByClip[clipUuid];
32944 this._removeInactiveBindingsForAction(action);
32946 _removeInactiveBindingsForAction: function _removeInactiveBindingsForAction(action) {
32947 var bindings = action._propertyBindings;
32949 for (var i = 0, n = bindings.length; i !== n; ++i) {
32950 var binding = bindings[i];
32952 if (--binding.referenceCount === 0) {
32953 this._removeInactiveBinding(binding);
32957 _lendAction: function _lendAction(action) {
32958 // [ active actions | inactive actions ]
32959 // [ active actions >| inactive actions ]
32963 var actions = this._actions,
32964 prevIndex = action._cacheIndex,
32965 lastActiveIndex = this._nActiveActions++,
32966 firstInactiveAction = actions[lastActiveIndex];
32967 action._cacheIndex = lastActiveIndex;
32968 actions[lastActiveIndex] = action;
32969 firstInactiveAction._cacheIndex = prevIndex;
32970 actions[prevIndex] = firstInactiveAction;
32972 _takeBackAction: function _takeBackAction(action) {
32973 // [ active actions | inactive actions ]
32974 // [ active actions |< inactive actions ]
32978 var actions = this._actions,
32979 prevIndex = action._cacheIndex,
32980 firstInactiveIndex = --this._nActiveActions,
32981 lastActiveAction = actions[firstInactiveIndex];
32982 action._cacheIndex = firstInactiveIndex;
32983 actions[firstInactiveIndex] = action;
32984 lastActiveAction._cacheIndex = prevIndex;
32985 actions[prevIndex] = lastActiveAction;
32987 // Memory management for PropertyMixer objects
32988 _addInactiveBinding: function _addInactiveBinding(binding, rootUuid, trackName) {
32989 var bindingsByRoot = this._bindingsByRootAndName,
32990 bindings = this._bindings;
32991 var bindingByName = bindingsByRoot[rootUuid];
32993 if (bindingByName === undefined) {
32994 bindingByName = {};
32995 bindingsByRoot[rootUuid] = bindingByName;
32998 bindingByName[trackName] = binding;
32999 binding._cacheIndex = bindings.length;
33000 bindings.push(binding);
33002 _removeInactiveBinding: function _removeInactiveBinding(binding) {
33003 var bindings = this._bindings,
33004 propBinding = binding.binding,
33005 rootUuid = propBinding.rootNode.uuid,
33006 trackName = propBinding.path,
33007 bindingsByRoot = this._bindingsByRootAndName,
33008 bindingByName = bindingsByRoot[rootUuid],
33009 lastInactiveBinding = bindings[bindings.length - 1],
33010 cacheIndex = binding._cacheIndex;
33011 lastInactiveBinding._cacheIndex = cacheIndex;
33012 bindings[cacheIndex] = lastInactiveBinding;
33014 delete bindingByName[trackName];
33016 if (Object.keys(bindingByName).length === 0) {
33017 delete bindingsByRoot[rootUuid];
33020 _lendBinding: function _lendBinding(binding) {
33021 var bindings = this._bindings,
33022 prevIndex = binding._cacheIndex,
33023 lastActiveIndex = this._nActiveBindings++,
33024 firstInactiveBinding = bindings[lastActiveIndex];
33025 binding._cacheIndex = lastActiveIndex;
33026 bindings[lastActiveIndex] = binding;
33027 firstInactiveBinding._cacheIndex = prevIndex;
33028 bindings[prevIndex] = firstInactiveBinding;
33030 _takeBackBinding: function _takeBackBinding(binding) {
33031 var bindings = this._bindings,
33032 prevIndex = binding._cacheIndex,
33033 firstInactiveIndex = --this._nActiveBindings,
33034 lastActiveBinding = bindings[firstInactiveIndex];
33035 binding._cacheIndex = firstInactiveIndex;
33036 bindings[firstInactiveIndex] = binding;
33037 lastActiveBinding._cacheIndex = prevIndex;
33038 bindings[prevIndex] = lastActiveBinding;
33040 // Memory management of Interpolants for weight and time scale
33041 _lendControlInterpolant: function _lendControlInterpolant() {
33042 var interpolants = this._controlInterpolants,
33043 lastActiveIndex = this._nActiveControlInterpolants++;
33044 var interpolant = interpolants[lastActiveIndex];
33046 if (interpolant === undefined) {
33047 interpolant = new LinearInterpolant(new Float32Array(2), new Float32Array(2), 1, this._controlInterpolantsResultBuffer);
33048 interpolant.__cacheIndex = lastActiveIndex;
33049 interpolants[lastActiveIndex] = interpolant;
33052 return interpolant;
33054 _takeBackControlInterpolant: function _takeBackControlInterpolant(interpolant) {
33055 var interpolants = this._controlInterpolants,
33056 prevIndex = interpolant.__cacheIndex,
33057 firstInactiveIndex = --this._nActiveControlInterpolants,
33058 lastActiveInterpolant = interpolants[firstInactiveIndex];
33059 interpolant.__cacheIndex = firstInactiveIndex;
33060 interpolants[firstInactiveIndex] = interpolant;
33061 lastActiveInterpolant.__cacheIndex = prevIndex;
33062 interpolants[prevIndex] = lastActiveInterpolant;
33064 _controlInterpolantsResultBuffer: new Float32Array(1),
33065 // return an action for a clip optionally using a custom root target
33066 // object (this method allocates a lot of dynamic memory in case a
33067 // previously unknown clip/root combination is specified)
33068 clipAction: function clipAction(clip, optionalRoot, blendMode) {
33069 var root = optionalRoot || this._root,
33070 rootUuid = root.uuid;
33071 var clipObject = typeof clip === 'string' ? AnimationClip.findByName(root, clip) : clip;
33072 var clipUuid = clipObject !== null ? clipObject.uuid : clip;
33073 var actionsForClip = this._actionsByClip[clipUuid];
33074 var prototypeAction = null;
33076 if (blendMode === undefined) {
33077 if (clipObject !== null) {
33078 blendMode = clipObject.blendMode;
33080 blendMode = NormalAnimationBlendMode;
33084 if (actionsForClip !== undefined) {
33085 var existingAction = actionsForClip.actionByRoot[rootUuid];
33087 if (existingAction !== undefined && existingAction.blendMode === blendMode) {
33088 return existingAction;
33089 } // we know the clip, so we don't have to parse all
33090 // the bindings again but can just copy
33093 prototypeAction = actionsForClip.knownActions[0]; // also, take the clip from the prototype action
33095 if (clipObject === null) clipObject = prototypeAction._clip;
33096 } // clip must be known when specified via string
33099 if (clipObject === null) return null; // allocate all resources required to run it
33101 var newAction = new AnimationAction(this, clipObject, optionalRoot, blendMode);
33103 this._bindAction(newAction, prototypeAction); // and make the action known to the memory manager
33106 this._addInactiveAction(newAction, clipUuid, rootUuid);
33110 // get an existing action
33111 existingAction: function existingAction(clip, optionalRoot) {
33112 var root = optionalRoot || this._root,
33113 rootUuid = root.uuid,
33114 clipObject = typeof clip === 'string' ? AnimationClip.findByName(root, clip) : clip,
33115 clipUuid = clipObject ? clipObject.uuid : clip,
33116 actionsForClip = this._actionsByClip[clipUuid];
33118 if (actionsForClip !== undefined) {
33119 return actionsForClip.actionByRoot[rootUuid] || null;
33124 // deactivates all previously scheduled actions
33125 stopAllAction: function stopAllAction() {
33126 var actions = this._actions,
33127 nActions = this._nActiveActions;
33129 for (var i = nActions - 1; i >= 0; --i) {
33135 // advance the time and update apply the animation
33136 update: function update(deltaTime) {
33137 deltaTime *= this.timeScale;
33138 var actions = this._actions,
33139 nActions = this._nActiveActions,
33140 time = this.time += deltaTime,
33141 timeDirection = Math.sign(deltaTime),
33142 accuIndex = this._accuIndex ^= 1; // run active actions
33144 for (var i = 0; i !== nActions; ++i) {
33145 var action = actions[i];
33147 action._update(time, deltaTime, timeDirection, accuIndex);
33148 } // update scene graph
33151 var bindings = this._bindings,
33152 nBindings = this._nActiveBindings;
33154 for (var _i = 0; _i !== nBindings; ++_i) {
33155 bindings[_i].apply(accuIndex);
33160 // Allows you to seek to a specific time in an animation.
33161 setTime: function setTime(timeInSeconds) {
33162 this.time = 0; // Zero out time attribute for AnimationMixer object;
33164 for (var i = 0; i < this._actions.length; i++) {
33165 this._actions[i].time = 0; // Zero out time attribute for all associated AnimationAction objects.
33168 return this.update(timeInSeconds); // Update used to set exact time. Returns "this" AnimationMixer object.
33170 // return this mixer's root target object
33171 getRoot: function getRoot() {
33174 // free all resources specific to a particular clip
33175 uncacheClip: function uncacheClip(clip) {
33176 var actions = this._actions,
33177 clipUuid = clip.uuid,
33178 actionsByClip = this._actionsByClip,
33179 actionsForClip = actionsByClip[clipUuid];
33181 if (actionsForClip !== undefined) {
33182 // note: just calling _removeInactiveAction would mess up the
33183 // iteration state and also require updating the state we can
33185 var actionsToRemove = actionsForClip.knownActions;
33187 for (var i = 0, n = actionsToRemove.length; i !== n; ++i) {
33188 var action = actionsToRemove[i];
33190 this._deactivateAction(action);
33192 var cacheIndex = action._cacheIndex,
33193 lastInactiveAction = actions[actions.length - 1];
33194 action._cacheIndex = null;
33195 action._byClipCacheIndex = null;
33196 lastInactiveAction._cacheIndex = cacheIndex;
33197 actions[cacheIndex] = lastInactiveAction;
33200 this._removeInactiveBindingsForAction(action);
33203 delete actionsByClip[clipUuid];
33206 // free all resources specific to a particular root target object
33207 uncacheRoot: function uncacheRoot(root) {
33208 var rootUuid = root.uuid,
33209 actionsByClip = this._actionsByClip;
33211 for (var clipUuid in actionsByClip) {
33212 var actionByRoot = actionsByClip[clipUuid].actionByRoot,
33213 action = actionByRoot[rootUuid];
33215 if (action !== undefined) {
33216 this._deactivateAction(action);
33218 this._removeInactiveAction(action);
33222 var bindingsByRoot = this._bindingsByRootAndName,
33223 bindingByName = bindingsByRoot[rootUuid];
33225 if (bindingByName !== undefined) {
33226 for (var trackName in bindingByName) {
33227 var binding = bindingByName[trackName];
33228 binding.restoreOriginalState();
33230 this._removeInactiveBinding(binding);
33234 // remove a targeted clip from the cache
33235 uncacheAction: function uncacheAction(clip, optionalRoot) {
33236 var action = this.existingAction(clip, optionalRoot);
33238 if (action !== null) {
33239 this._deactivateAction(action);
33241 this._removeInactiveAction(action);
33246 var Uniform = /*#__PURE__*/function () {
33247 function Uniform(value) {
33248 if (typeof value === 'string') {
33249 console.warn('THREE.Uniform: Type parameter is no longer needed.');
33250 value = arguments[1];
33253 this.value = value;
33256 var _proto = Uniform.prototype;
33258 _proto.clone = function clone() {
33259 return new Uniform(this.value.clone === undefined ? this.value : this.value.clone());
33265 function InstancedInterleavedBuffer(array, stride, meshPerAttribute) {
33266 InterleavedBuffer.call(this, array, stride);
33267 this.meshPerAttribute = meshPerAttribute || 1;
33270 InstancedInterleavedBuffer.prototype = Object.assign(Object.create(InterleavedBuffer.prototype), {
33271 constructor: InstancedInterleavedBuffer,
33272 isInstancedInterleavedBuffer: true,
33273 copy: function copy(source) {
33274 InterleavedBuffer.prototype.copy.call(this, source);
33275 this.meshPerAttribute = source.meshPerAttribute;
33278 clone: function clone(data) {
33279 var ib = InterleavedBuffer.prototype.clone.call(this, data);
33280 ib.meshPerAttribute = this.meshPerAttribute;
33283 toJSON: function toJSON(data) {
33284 var json = InterleavedBuffer.prototype.toJSON.call(this, data);
33285 json.isInstancedInterleavedBuffer = true;
33286 json.meshPerAttribute = this.meshPerAttribute;
33291 function GLBufferAttribute(buffer, type, itemSize, elementSize, count) {
33292 this.buffer = buffer;
33294 this.itemSize = itemSize;
33295 this.elementSize = elementSize;
33296 this.count = count;
33300 Object.defineProperty(GLBufferAttribute.prototype, 'needsUpdate', {
33301 set: function set(value) {
33302 if (value === true) this.version++;
33305 Object.assign(GLBufferAttribute.prototype, {
33306 isGLBufferAttribute: true,
33307 setBuffer: function setBuffer(buffer) {
33308 this.buffer = buffer;
33311 setType: function setType(type, elementSize) {
33313 this.elementSize = elementSize;
33316 setItemSize: function setItemSize(itemSize) {
33317 this.itemSize = itemSize;
33320 setCount: function setCount(count) {
33321 this.count = count;
33326 function Raycaster(origin, direction, near, far) {
33327 this.ray = new Ray(origin, direction); // direction is assumed to be normalized (for accurate distance calculations)
33329 this.near = near || 0;
33330 this.far = far || Infinity;
33331 this.camera = null;
33332 this.layers = new Layers();
33344 Object.defineProperties(this.params, {
33346 get: function get() {
33347 console.warn('THREE.Raycaster: params.PointCloud has been renamed to params.Points.');
33348 return this.Points;
33354 function ascSort(a, b) {
33355 return a.distance - b.distance;
33358 function _intersectObject(object, raycaster, intersects, recursive) {
33359 if (object.layers.test(raycaster.layers)) {
33360 object.raycast(raycaster, intersects);
33363 if (recursive === true) {
33364 var children = object.children;
33366 for (var i = 0, l = children.length; i < l; i++) {
33367 _intersectObject(children[i], raycaster, intersects, true);
33372 Object.assign(Raycaster.prototype, {
33373 set: function set(origin, direction) {
33374 // direction is assumed to be normalized (for accurate distance calculations)
33375 this.ray.set(origin, direction);
33377 setFromCamera: function setFromCamera(coords, camera) {
33378 if (camera && camera.isPerspectiveCamera) {
33379 this.ray.origin.setFromMatrixPosition(camera.matrixWorld);
33380 this.ray.direction.set(coords.x, coords.y, 0.5).unproject(camera).sub(this.ray.origin).normalize();
33381 this.camera = camera;
33382 } else if (camera && camera.isOrthographicCamera) {
33383 this.ray.origin.set(coords.x, coords.y, (camera.near + camera.far) / (camera.near - camera.far)).unproject(camera); // set origin in plane of camera
33385 this.ray.direction.set(0, 0, -1).transformDirection(camera.matrixWorld);
33386 this.camera = camera;
33388 console.error('THREE.Raycaster: Unsupported camera type: ' + camera.type);
33391 intersectObject: function intersectObject(object, recursive, optionalTarget) {
33392 var intersects = optionalTarget || [];
33394 _intersectObject(object, this, intersects, recursive);
33396 intersects.sort(ascSort);
33399 intersectObjects: function intersectObjects(objects, recursive, optionalTarget) {
33400 var intersects = optionalTarget || [];
33402 if (Array.isArray(objects) === false) {
33403 console.warn('THREE.Raycaster.intersectObjects: objects is not an Array.');
33407 for (var i = 0, l = objects.length; i < l; i++) {
33408 _intersectObject(objects[i], this, intersects, recursive);
33411 intersects.sort(ascSort);
33417 * Ref: https://en.wikipedia.org/wiki/Spherical_coordinate_system
33419 * The polar angle (phi) is measured from the positive y-axis. The positive y-axis is up.
33420 * The azimuthal angle (theta) is measured from the positive z-axis.
33423 var Spherical = /*#__PURE__*/function () {
33424 function Spherical(radius, phi, theta) {
33425 if (radius === void 0) {
33429 if (phi === void 0) {
33433 if (theta === void 0) {
33437 this.radius = radius;
33438 this.phi = phi; // polar angle
33440 this.theta = theta; // azimuthal angle
33445 var _proto = Spherical.prototype;
33447 _proto.set = function set(radius, phi, theta) {
33448 this.radius = radius;
33450 this.theta = theta;
33454 _proto.clone = function clone() {
33455 return new this.constructor().copy(this);
33458 _proto.copy = function copy(other) {
33459 this.radius = other.radius;
33460 this.phi = other.phi;
33461 this.theta = other.theta;
33463 } // restrict phi to be betwee EPS and PI-EPS
33466 _proto.makeSafe = function makeSafe() {
33467 var EPS = 0.000001;
33468 this.phi = Math.max(EPS, Math.min(Math.PI - EPS, this.phi));
33472 _proto.setFromVector3 = function setFromVector3(v) {
33473 return this.setFromCartesianCoords(v.x, v.y, v.z);
33476 _proto.setFromCartesianCoords = function setFromCartesianCoords(x, y, z) {
33477 this.radius = Math.sqrt(x * x + y * y + z * z);
33479 if (this.radius === 0) {
33483 this.theta = Math.atan2(x, z);
33484 this.phi = Math.acos(MathUtils.clamp(y / this.radius, -1, 1));
33494 * Ref: https://en.wikipedia.org/wiki/Cylindrical_coordinate_system
33496 var Cylindrical = /*#__PURE__*/function () {
33497 function Cylindrical(radius, theta, y) {
33498 this.radius = radius !== undefined ? radius : 1.0; // distance from the origin to a point in the x-z plane
33500 this.theta = theta !== undefined ? theta : 0; // counterclockwise angle in the x-z plane measured in radians from the positive z-axis
33502 this.y = y !== undefined ? y : 0; // height above the x-z plane
33507 var _proto = Cylindrical.prototype;
33509 _proto.set = function set(radius, theta, y) {
33510 this.radius = radius;
33511 this.theta = theta;
33516 _proto.clone = function clone() {
33517 return new this.constructor().copy(this);
33520 _proto.copy = function copy(other) {
33521 this.radius = other.radius;
33522 this.theta = other.theta;
33527 _proto.setFromVector3 = function setFromVector3(v) {
33528 return this.setFromCartesianCoords(v.x, v.y, v.z);
33531 _proto.setFromCartesianCoords = function setFromCartesianCoords(x, y, z) {
33532 this.radius = Math.sqrt(x * x + z * z);
33533 this.theta = Math.atan2(x, z);
33538 return Cylindrical;
33541 var _vector$8 = /*@__PURE__*/new Vector2();
33543 var Box2 = /*#__PURE__*/function () {
33544 function Box2(min, max) {
33545 Object.defineProperty(this, 'isBox2', {
33548 this.min = min !== undefined ? min : new Vector2(+Infinity, +Infinity);
33549 this.max = max !== undefined ? max : new Vector2(-Infinity, -Infinity);
33552 var _proto = Box2.prototype;
33554 _proto.set = function set(min, max) {
33555 this.min.copy(min);
33556 this.max.copy(max);
33560 _proto.setFromPoints = function setFromPoints(points) {
33563 for (var i = 0, il = points.length; i < il; i++) {
33564 this.expandByPoint(points[i]);
33570 _proto.setFromCenterAndSize = function setFromCenterAndSize(center, size) {
33571 var halfSize = _vector$8.copy(size).multiplyScalar(0.5);
33573 this.min.copy(center).sub(halfSize);
33574 this.max.copy(center).add(halfSize);
33578 _proto.clone = function clone() {
33579 return new this.constructor().copy(this);
33582 _proto.copy = function copy(box) {
33583 this.min.copy(box.min);
33584 this.max.copy(box.max);
33588 _proto.makeEmpty = function makeEmpty() {
33589 this.min.x = this.min.y = +Infinity;
33590 this.max.x = this.max.y = -Infinity;
33594 _proto.isEmpty = function isEmpty() {
33595 // this is a more robust check for empty than ( volume <= 0 ) because volume can get positive with two negative axes
33596 return this.max.x < this.min.x || this.max.y < this.min.y;
33599 _proto.getCenter = function getCenter(target) {
33600 if (target === undefined) {
33601 console.warn('THREE.Box2: .getCenter() target is now required');
33602 target = new Vector2();
33605 return this.isEmpty() ? target.set(0, 0) : target.addVectors(this.min, this.max).multiplyScalar(0.5);
33608 _proto.getSize = function getSize(target) {
33609 if (target === undefined) {
33610 console.warn('THREE.Box2: .getSize() target is now required');
33611 target = new Vector2();
33614 return this.isEmpty() ? target.set(0, 0) : target.subVectors(this.max, this.min);
33617 _proto.expandByPoint = function expandByPoint(point) {
33618 this.min.min(point);
33619 this.max.max(point);
33623 _proto.expandByVector = function expandByVector(vector) {
33624 this.min.sub(vector);
33625 this.max.add(vector);
33629 _proto.expandByScalar = function expandByScalar(scalar) {
33630 this.min.addScalar(-scalar);
33631 this.max.addScalar(scalar);
33635 _proto.containsPoint = function containsPoint(point) {
33636 return point.x < this.min.x || point.x > this.max.x || point.y < this.min.y || point.y > this.max.y ? false : true;
33639 _proto.containsBox = function containsBox(box) {
33640 return this.min.x <= box.min.x && box.max.x <= this.max.x && this.min.y <= box.min.y && box.max.y <= this.max.y;
33643 _proto.getParameter = function getParameter(point, target) {
33644 // This can potentially have a divide by zero if the box
33645 // has a size dimension of 0.
33646 if (target === undefined) {
33647 console.warn('THREE.Box2: .getParameter() target is now required');
33648 target = new Vector2();
33651 return target.set((point.x - this.min.x) / (this.max.x - this.min.x), (point.y - this.min.y) / (this.max.y - this.min.y));
33654 _proto.intersectsBox = function intersectsBox(box) {
33655 // using 4 splitting planes to rule out intersections
33656 return box.max.x < this.min.x || box.min.x > this.max.x || box.max.y < this.min.y || box.min.y > this.max.y ? false : true;
33659 _proto.clampPoint = function clampPoint(point, target) {
33660 if (target === undefined) {
33661 console.warn('THREE.Box2: .clampPoint() target is now required');
33662 target = new Vector2();
33665 return target.copy(point).clamp(this.min, this.max);
33668 _proto.distanceToPoint = function distanceToPoint(point) {
33669 var clampedPoint = _vector$8.copy(point).clamp(this.min, this.max);
33671 return clampedPoint.sub(point).length();
33674 _proto.intersect = function intersect(box) {
33675 this.min.max(box.min);
33676 this.max.min(box.max);
33680 _proto.union = function union(box) {
33681 this.min.min(box.min);
33682 this.max.max(box.max);
33686 _proto.translate = function translate(offset) {
33687 this.min.add(offset);
33688 this.max.add(offset);
33692 _proto.equals = function equals(box) {
33693 return box.min.equals(this.min) && box.max.equals(this.max);
33699 var _startP = /*@__PURE__*/new Vector3();
33701 var _startEnd = /*@__PURE__*/new Vector3();
33703 var Line3 = /*#__PURE__*/function () {
33704 function Line3(start, end) {
33705 this.start = start !== undefined ? start : new Vector3();
33706 this.end = end !== undefined ? end : new Vector3();
33709 var _proto = Line3.prototype;
33711 _proto.set = function set(start, end) {
33712 this.start.copy(start);
33713 this.end.copy(end);
33717 _proto.clone = function clone() {
33718 return new this.constructor().copy(this);
33721 _proto.copy = function copy(line) {
33722 this.start.copy(line.start);
33723 this.end.copy(line.end);
33727 _proto.getCenter = function getCenter(target) {
33728 if (target === undefined) {
33729 console.warn('THREE.Line3: .getCenter() target is now required');
33730 target = new Vector3();
33733 return target.addVectors(this.start, this.end).multiplyScalar(0.5);
33736 _proto.delta = function delta(target) {
33737 if (target === undefined) {
33738 console.warn('THREE.Line3: .delta() target is now required');
33739 target = new Vector3();
33742 return target.subVectors(this.end, this.start);
33745 _proto.distanceSq = function distanceSq() {
33746 return this.start.distanceToSquared(this.end);
33749 _proto.distance = function distance() {
33750 return this.start.distanceTo(this.end);
33753 _proto.at = function at(t, target) {
33754 if (target === undefined) {
33755 console.warn('THREE.Line3: .at() target is now required');
33756 target = new Vector3();
33759 return this.delta(target).multiplyScalar(t).add(this.start);
33762 _proto.closestPointToPointParameter = function closestPointToPointParameter(point, clampToLine) {
33763 _startP.subVectors(point, this.start);
33765 _startEnd.subVectors(this.end, this.start);
33767 var startEnd2 = _startEnd.dot(_startEnd);
33769 var startEnd_startP = _startEnd.dot(_startP);
33771 var t = startEnd_startP / startEnd2;
33774 t = MathUtils.clamp(t, 0, 1);
33780 _proto.closestPointToPoint = function closestPointToPoint(point, clampToLine, target) {
33781 var t = this.closestPointToPointParameter(point, clampToLine);
33783 if (target === undefined) {
33784 console.warn('THREE.Line3: .closestPointToPoint() target is now required');
33785 target = new Vector3();
33788 return this.delta(target).multiplyScalar(t).add(this.start);
33791 _proto.applyMatrix4 = function applyMatrix4(matrix) {
33792 this.start.applyMatrix4(matrix);
33793 this.end.applyMatrix4(matrix);
33797 _proto.equals = function equals(line) {
33798 return line.start.equals(this.start) && line.end.equals(this.end);
33804 function ImmediateRenderObject(material) {
33805 Object3D.call(this);
33806 this.material = material;
33808 this.render = function ()
33809 /* renderCallback */
33812 this.hasPositions = false;
33813 this.hasNormals = false;
33814 this.hasColors = false;
33815 this.hasUvs = false;
33816 this.positionArray = null;
33817 this.normalArray = null;
33818 this.colorArray = null;
33819 this.uvArray = null;
33823 ImmediateRenderObject.prototype = Object.create(Object3D.prototype);
33824 ImmediateRenderObject.prototype.constructor = ImmediateRenderObject;
33825 ImmediateRenderObject.prototype.isImmediateRenderObject = true;
33827 var _vector$9 = /*@__PURE__*/new Vector3();
33829 var SpotLightHelper = /*#__PURE__*/function (_Object3D) {
33830 _inheritsLoose(SpotLightHelper, _Object3D);
33832 function SpotLightHelper(light, color) {
33835 _this = _Object3D.call(this) || this;
33836 _this.light = light;
33838 _this.light.updateMatrixWorld();
33840 _this.matrix = light.matrixWorld;
33841 _this.matrixAutoUpdate = false;
33842 _this.color = color;
33843 var geometry = new BufferGeometry();
33844 var positions = [0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 1, 0, 0, 0, -1, 0, 1, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, -1, 1];
33846 for (var i = 0, j = 1, l = 32; i < l; i++, j++) {
33847 var p1 = i / l * Math.PI * 2;
33848 var p2 = j / l * Math.PI * 2;
33849 positions.push(Math.cos(p1), Math.sin(p1), 1, Math.cos(p2), Math.sin(p2), 1);
33852 geometry.setAttribute('position', new Float32BufferAttribute(positions, 3));
33853 var material = new LineBasicMaterial({
33857 _this.cone = new LineSegments(geometry, material);
33859 _this.add(_this.cone);
33866 var _proto = SpotLightHelper.prototype;
33868 _proto.dispose = function dispose() {
33869 this.cone.geometry.dispose();
33870 this.cone.material.dispose();
33873 _proto.update = function update() {
33874 this.light.updateMatrixWorld();
33875 var coneLength = this.light.distance ? this.light.distance : 1000;
33876 var coneWidth = coneLength * Math.tan(this.light.angle);
33877 this.cone.scale.set(coneWidth, coneWidth, coneLength);
33879 _vector$9.setFromMatrixPosition(this.light.target.matrixWorld);
33881 this.cone.lookAt(_vector$9);
33883 if (this.color !== undefined) {
33884 this.cone.material.color.set(this.color);
33886 this.cone.material.color.copy(this.light.color);
33890 return SpotLightHelper;
33893 var _vector$a = /*@__PURE__*/new Vector3();
33895 var _boneMatrix = /*@__PURE__*/new Matrix4();
33897 var _matrixWorldInv = /*@__PURE__*/new Matrix4();
33899 var SkeletonHelper = /*#__PURE__*/function (_LineSegments) {
33900 _inheritsLoose(SkeletonHelper, _LineSegments);
33902 function SkeletonHelper(object) {
33905 var bones = getBoneList(object);
33906 var geometry = new BufferGeometry();
33909 var color1 = new Color(0, 0, 1);
33910 var color2 = new Color(0, 1, 0);
33912 for (var i = 0; i < bones.length; i++) {
33913 var bone = bones[i];
33915 if (bone.parent && bone.parent.isBone) {
33916 vertices.push(0, 0, 0);
33917 vertices.push(0, 0, 0);
33918 colors.push(color1.r, color1.g, color1.b);
33919 colors.push(color2.r, color2.g, color2.b);
33923 geometry.setAttribute('position', new Float32BufferAttribute(vertices, 3));
33924 geometry.setAttribute('color', new Float32BufferAttribute(colors, 3));
33925 var material = new LineBasicMaterial({
33926 vertexColors: true,
33932 _this = _LineSegments.call(this, geometry, material) || this;
33933 _this.type = 'SkeletonHelper';
33934 _this.isSkeletonHelper = true;
33935 _this.root = object;
33936 _this.bones = bones;
33937 _this.matrix = object.matrixWorld;
33938 _this.matrixAutoUpdate = false;
33942 var _proto = SkeletonHelper.prototype;
33944 _proto.updateMatrixWorld = function updateMatrixWorld(force) {
33945 var bones = this.bones;
33946 var geometry = this.geometry;
33947 var position = geometry.getAttribute('position');
33949 _matrixWorldInv.copy(this.root.matrixWorld).invert();
33951 for (var i = 0, j = 0; i < bones.length; i++) {
33952 var bone = bones[i];
33954 if (bone.parent && bone.parent.isBone) {
33955 _boneMatrix.multiplyMatrices(_matrixWorldInv, bone.matrixWorld);
33957 _vector$a.setFromMatrixPosition(_boneMatrix);
33959 position.setXYZ(j, _vector$a.x, _vector$a.y, _vector$a.z);
33961 _boneMatrix.multiplyMatrices(_matrixWorldInv, bone.parent.matrixWorld);
33963 _vector$a.setFromMatrixPosition(_boneMatrix);
33965 position.setXYZ(j + 1, _vector$a.x, _vector$a.y, _vector$a.z);
33970 geometry.getAttribute('position').needsUpdate = true;
33972 _LineSegments.prototype.updateMatrixWorld.call(this, force);
33975 return SkeletonHelper;
33978 function getBoneList(object) {
33981 if (object && object.isBone) {
33982 boneList.push(object);
33985 for (var i = 0; i < object.children.length; i++) {
33986 boneList.push.apply(boneList, getBoneList(object.children[i]));
33992 var PointLightHelper = /*#__PURE__*/function (_Mesh) {
33993 _inheritsLoose(PointLightHelper, _Mesh);
33995 function PointLightHelper(light, sphereSize, color) {
33998 var geometry = new SphereGeometry(sphereSize, 4, 2);
33999 var material = new MeshBasicMaterial({
34004 _this = _Mesh.call(this, geometry, material) || this;
34005 _this.light = light;
34007 _this.light.updateMatrixWorld();
34009 _this.color = color;
34010 _this.type = 'PointLightHelper';
34011 _this.matrix = _this.light.matrixWorld;
34012 _this.matrixAutoUpdate = false;
34016 // TODO: delete this comment?
34017 const distanceGeometry = new THREE.IcosahedronBufferGeometry( 1, 2 );
34018 const distanceMaterial = new THREE.MeshBasicMaterial( { color: hexColor, fog: false, wireframe: true, opacity: 0.1, transparent: true } );
34019 this.lightSphere = new THREE.Mesh( bulbGeometry, bulbMaterial );
34020 this.lightDistance = new THREE.Mesh( distanceGeometry, distanceMaterial );
34021 const d = light.distance;
34023 this.lightDistance.visible = false;
34025 this.lightDistance.scale.set( d, d, d );
34027 this.add( this.lightDistance );
34034 var _proto = PointLightHelper.prototype;
34036 _proto.dispose = function dispose() {
34037 this.geometry.dispose();
34038 this.material.dispose();
34041 _proto.update = function update() {
34042 if (this.color !== undefined) {
34043 this.material.color.set(this.color);
34045 this.material.color.copy(this.light.color);
34048 const d = this.light.distance;
34050 this.lightDistance.visible = false;
34052 this.lightDistance.visible = true;
34053 this.lightDistance.scale.set( d, d, d );
34059 return PointLightHelper;
34062 var _vector$b = /*@__PURE__*/new Vector3();
34064 var _color1 = /*@__PURE__*/new Color();
34066 var _color2 = /*@__PURE__*/new Color();
34068 var HemisphereLightHelper = /*#__PURE__*/function (_Object3D) {
34069 _inheritsLoose(HemisphereLightHelper, _Object3D);
34071 function HemisphereLightHelper(light, size, color) {
34074 _this = _Object3D.call(this) || this;
34075 _this.light = light;
34077 _this.light.updateMatrixWorld();
34079 _this.matrix = light.matrixWorld;
34080 _this.matrixAutoUpdate = false;
34081 _this.color = color;
34082 var geometry = new OctahedronGeometry(size);
34083 geometry.rotateY(Math.PI * 0.5);
34084 _this.material = new MeshBasicMaterial({
34089 if (_this.color === undefined) _this.material.vertexColors = true;
34090 var position = geometry.getAttribute('position');
34091 var colors = new Float32Array(position.count * 3);
34092 geometry.setAttribute('color', new BufferAttribute(colors, 3));
34094 _this.add(new Mesh(geometry, _this.material));
34101 var _proto = HemisphereLightHelper.prototype;
34103 _proto.dispose = function dispose() {
34104 this.children[0].geometry.dispose();
34105 this.children[0].material.dispose();
34108 _proto.update = function update() {
34109 var mesh = this.children[0];
34111 if (this.color !== undefined) {
34112 this.material.color.set(this.color);
34114 var colors = mesh.geometry.getAttribute('color');
34116 _color1.copy(this.light.color);
34118 _color2.copy(this.light.groundColor);
34120 for (var i = 0, l = colors.count; i < l; i++) {
34121 var color = i < l / 2 ? _color1 : _color2;
34122 colors.setXYZ(i, color.r, color.g, color.b);
34125 colors.needsUpdate = true;
34128 mesh.lookAt(_vector$b.setFromMatrixPosition(this.light.matrixWorld).negate());
34131 return HemisphereLightHelper;
34134 var GridHelper = /*#__PURE__*/function (_LineSegments) {
34135 _inheritsLoose(GridHelper, _LineSegments);
34137 function GridHelper(size, divisions, color1, color2) {
34140 if (size === void 0) {
34144 if (divisions === void 0) {
34148 if (color1 === void 0) {
34152 if (color2 === void 0) {
34156 color1 = new Color(color1);
34157 color2 = new Color(color2);
34158 var center = divisions / 2;
34159 var step = size / divisions;
34160 var halfSize = size / 2;
34164 for (var i = 0, j = 0, k = -halfSize; i <= divisions; i++, k += step) {
34165 vertices.push(-halfSize, 0, k, halfSize, 0, k);
34166 vertices.push(k, 0, -halfSize, k, 0, halfSize);
34167 var color = i === center ? color1 : color2;
34168 color.toArray(colors, j);
34170 color.toArray(colors, j);
34172 color.toArray(colors, j);
34174 color.toArray(colors, j);
34178 var geometry = new BufferGeometry();
34179 geometry.setAttribute('position', new Float32BufferAttribute(vertices, 3));
34180 geometry.setAttribute('color', new Float32BufferAttribute(colors, 3));
34181 var material = new LineBasicMaterial({
34182 vertexColors: true,
34185 _this = _LineSegments.call(this, geometry, material) || this;
34186 _this.type = 'GridHelper';
34193 var PolarGridHelper = /*#__PURE__*/function (_LineSegments) {
34194 _inheritsLoose(PolarGridHelper, _LineSegments);
34196 function PolarGridHelper(radius, radials, circles, divisions, color1, color2) {
34199 if (radius === void 0) {
34203 if (radials === void 0) {
34207 if (circles === void 0) {
34211 if (divisions === void 0) {
34215 if (color1 === void 0) {
34219 if (color2 === void 0) {
34223 color1 = new Color(color1);
34224 color2 = new Color(color2);
34226 var colors = []; // create the radials
34228 for (var i = 0; i <= radials; i++) {
34229 var v = i / radials * (Math.PI * 2);
34230 var x = Math.sin(v) * radius;
34231 var z = Math.cos(v) * radius;
34232 vertices.push(0, 0, 0);
34233 vertices.push(x, 0, z);
34234 var color = i & 1 ? color1 : color2;
34235 colors.push(color.r, color.g, color.b);
34236 colors.push(color.r, color.g, color.b);
34237 } // create the circles
34240 for (var _i = 0; _i <= circles; _i++) {
34241 var _color = _i & 1 ? color1 : color2;
34243 var r = radius - radius / circles * _i;
34245 for (var j = 0; j < divisions; j++) {
34247 var _v = j / divisions * (Math.PI * 2);
34249 var _x = Math.sin(_v) * r;
34251 var _z = Math.cos(_v) * r;
34253 vertices.push(_x, 0, _z);
34254 colors.push(_color.r, _color.g, _color.b); // second vertex
34256 _v = (j + 1) / divisions * (Math.PI * 2);
34257 _x = Math.sin(_v) * r;
34258 _z = Math.cos(_v) * r;
34259 vertices.push(_x, 0, _z);
34260 colors.push(_color.r, _color.g, _color.b);
34264 var geometry = new BufferGeometry();
34265 geometry.setAttribute('position', new Float32BufferAttribute(vertices, 3));
34266 geometry.setAttribute('color', new Float32BufferAttribute(colors, 3));
34267 var material = new LineBasicMaterial({
34268 vertexColors: true,
34271 _this = _LineSegments.call(this, geometry, material) || this;
34272 _this.type = 'PolarGridHelper';
34276 return PolarGridHelper;
34279 var _v1$6 = /*@__PURE__*/new Vector3();
34281 var _v2$3 = /*@__PURE__*/new Vector3();
34283 var _v3$1 = /*@__PURE__*/new Vector3();
34285 var DirectionalLightHelper = /*#__PURE__*/function (_Object3D) {
34286 _inheritsLoose(DirectionalLightHelper, _Object3D);
34288 function DirectionalLightHelper(light, size, color) {
34291 _this = _Object3D.call(this) || this;
34292 _this.light = light;
34294 _this.light.updateMatrixWorld();
34296 _this.matrix = light.matrixWorld;
34297 _this.matrixAutoUpdate = false;
34298 _this.color = color;
34299 if (size === undefined) size = 1;
34300 var geometry = new BufferGeometry();
34301 geometry.setAttribute('position', new Float32BufferAttribute([-size, size, 0, size, size, 0, size, -size, 0, -size, -size, 0, -size, size, 0], 3));
34302 var material = new LineBasicMaterial({
34306 _this.lightPlane = new Line(geometry, material);
34308 _this.add(_this.lightPlane);
34310 geometry = new BufferGeometry();
34311 geometry.setAttribute('position', new Float32BufferAttribute([0, 0, 0, 0, 0, 1], 3));
34312 _this.targetLine = new Line(geometry, material);
34314 _this.add(_this.targetLine);
34321 var _proto = DirectionalLightHelper.prototype;
34323 _proto.dispose = function dispose() {
34324 this.lightPlane.geometry.dispose();
34325 this.lightPlane.material.dispose();
34326 this.targetLine.geometry.dispose();
34327 this.targetLine.material.dispose();
34330 _proto.update = function update() {
34331 _v1$6.setFromMatrixPosition(this.light.matrixWorld);
34333 _v2$3.setFromMatrixPosition(this.light.target.matrixWorld);
34335 _v3$1.subVectors(_v2$3, _v1$6);
34337 this.lightPlane.lookAt(_v2$3);
34339 if (this.color !== undefined) {
34340 this.lightPlane.material.color.set(this.color);
34341 this.targetLine.material.color.set(this.color);
34343 this.lightPlane.material.color.copy(this.light.color);
34344 this.targetLine.material.color.copy(this.light.color);
34347 this.targetLine.lookAt(_v2$3);
34348 this.targetLine.scale.z = _v3$1.length();
34351 return DirectionalLightHelper;
34354 var _vector$c = /*@__PURE__*/new Vector3();
34356 var _camera = /*@__PURE__*/new Camera();
34358 * - shows frustum, line of sight and up of the camera
34359 * - suitable for fast updates
34360 * - based on frustum visualization in lightgl.js shadowmap example
34361 * http://evanw.github.com/lightgl.js/tests/shadowmap.html
34365 var CameraHelper = /*#__PURE__*/function (_LineSegments) {
34366 _inheritsLoose(CameraHelper, _LineSegments);
34368 function CameraHelper(camera) {
34371 var geometry = new BufferGeometry();
34372 var material = new LineBasicMaterial({
34374 vertexColors: true,
34379 var pointMap = {}; // colors
34381 var colorFrustum = new Color(0xffaa00);
34382 var colorCone = new Color(0xff0000);
34383 var colorUp = new Color(0x00aaff);
34384 var colorTarget = new Color(0xffffff);
34385 var colorCross = new Color(0x333333); // near
34387 addLine('n1', 'n2', colorFrustum);
34388 addLine('n2', 'n4', colorFrustum);
34389 addLine('n4', 'n3', colorFrustum);
34390 addLine('n3', 'n1', colorFrustum); // far
34392 addLine('f1', 'f2', colorFrustum);
34393 addLine('f2', 'f4', colorFrustum);
34394 addLine('f4', 'f3', colorFrustum);
34395 addLine('f3', 'f1', colorFrustum); // sides
34397 addLine('n1', 'f1', colorFrustum);
34398 addLine('n2', 'f2', colorFrustum);
34399 addLine('n3', 'f3', colorFrustum);
34400 addLine('n4', 'f4', colorFrustum); // cone
34402 addLine('p', 'n1', colorCone);
34403 addLine('p', 'n2', colorCone);
34404 addLine('p', 'n3', colorCone);
34405 addLine('p', 'n4', colorCone); // up
34407 addLine('u1', 'u2', colorUp);
34408 addLine('u2', 'u3', colorUp);
34409 addLine('u3', 'u1', colorUp); // target
34411 addLine('c', 't', colorTarget);
34412 addLine('p', 'c', colorCross); // cross
34414 addLine('cn1', 'cn2', colorCross);
34415 addLine('cn3', 'cn4', colorCross);
34416 addLine('cf1', 'cf2', colorCross);
34417 addLine('cf3', 'cf4', colorCross);
34419 function addLine(a, b, color) {
34420 addPoint(a, color);
34421 addPoint(b, color);
34424 function addPoint(id, color) {
34425 vertices.push(0, 0, 0);
34426 colors.push(color.r, color.g, color.b);
34428 if (pointMap[id] === undefined) {
34432 pointMap[id].push(vertices.length / 3 - 1);
34435 geometry.setAttribute('position', new Float32BufferAttribute(vertices, 3));
34436 geometry.setAttribute('color', new Float32BufferAttribute(colors, 3));
34437 _this = _LineSegments.call(this, geometry, material) || this;
34438 _this.type = 'CameraHelper';
34439 _this.camera = camera;
34440 if (_this.camera.updateProjectionMatrix) _this.camera.updateProjectionMatrix();
34441 _this.matrix = camera.matrixWorld;
34442 _this.matrixAutoUpdate = false;
34443 _this.pointMap = pointMap;
34450 var _proto = CameraHelper.prototype;
34452 _proto.update = function update() {
34453 var geometry = this.geometry;
34454 var pointMap = this.pointMap;
34456 h = 1; // we need just camera projection matrix inverse
34457 // world matrix must be identity
34459 _camera.projectionMatrixInverse.copy(this.camera.projectionMatrixInverse); // center / target
34462 setPoint('c', pointMap, geometry, _camera, 0, 0, -1);
34463 setPoint('t', pointMap, geometry, _camera, 0, 0, 1); // near
34465 setPoint('n1', pointMap, geometry, _camera, -w, -h, -1);
34466 setPoint('n2', pointMap, geometry, _camera, w, -h, -1);
34467 setPoint('n3', pointMap, geometry, _camera, -w, h, -1);
34468 setPoint('n4', pointMap, geometry, _camera, w, h, -1); // far
34470 setPoint('f1', pointMap, geometry, _camera, -w, -h, 1);
34471 setPoint('f2', pointMap, geometry, _camera, w, -h, 1);
34472 setPoint('f3', pointMap, geometry, _camera, -w, h, 1);
34473 setPoint('f4', pointMap, geometry, _camera, w, h, 1); // up
34475 setPoint('u1', pointMap, geometry, _camera, w * 0.7, h * 1.1, -1);
34476 setPoint('u2', pointMap, geometry, _camera, -w * 0.7, h * 1.1, -1);
34477 setPoint('u3', pointMap, geometry, _camera, 0, h * 2, -1); // cross
34479 setPoint('cf1', pointMap, geometry, _camera, -w, 0, 1);
34480 setPoint('cf2', pointMap, geometry, _camera, w, 0, 1);
34481 setPoint('cf3', pointMap, geometry, _camera, 0, -h, 1);
34482 setPoint('cf4', pointMap, geometry, _camera, 0, h, 1);
34483 setPoint('cn1', pointMap, geometry, _camera, -w, 0, -1);
34484 setPoint('cn2', pointMap, geometry, _camera, w, 0, -1);
34485 setPoint('cn3', pointMap, geometry, _camera, 0, -h, -1);
34486 setPoint('cn4', pointMap, geometry, _camera, 0, h, -1);
34487 geometry.getAttribute('position').needsUpdate = true;
34490 return CameraHelper;
34493 function setPoint(point, pointMap, geometry, camera, x, y, z) {
34494 _vector$c.set(x, y, z).unproject(camera);
34496 var points = pointMap[point];
34498 if (points !== undefined) {
34499 var position = geometry.getAttribute('position');
34501 for (var i = 0, l = points.length; i < l; i++) {
34502 position.setXYZ(points[i], _vector$c.x, _vector$c.y, _vector$c.z);
34507 var _box$3 = /*@__PURE__*/new Box3();
34509 var BoxHelper = /*#__PURE__*/function (_LineSegments) {
34510 _inheritsLoose(BoxHelper, _LineSegments);
34512 function BoxHelper(object, color) {
34515 if (color === void 0) {
34519 var indices = new Uint16Array([0, 1, 1, 2, 2, 3, 3, 0, 4, 5, 5, 6, 6, 7, 7, 4, 0, 4, 1, 5, 2, 6, 3, 7]);
34520 var positions = new Float32Array(8 * 3);
34521 var geometry = new BufferGeometry();
34522 geometry.setIndex(new BufferAttribute(indices, 1));
34523 geometry.setAttribute('position', new BufferAttribute(positions, 3));
34524 _this = _LineSegments.call(this, geometry, new LineBasicMaterial({
34528 _this.object = object;
34529 _this.type = 'BoxHelper';
34530 _this.matrixAutoUpdate = false;
34537 var _proto = BoxHelper.prototype;
34539 _proto.update = function update(object) {
34540 if (object !== undefined) {
34541 console.warn('THREE.BoxHelper: .update() has no longer arguments.');
34544 if (this.object !== undefined) {
34545 _box$3.setFromObject(this.object);
34548 if (_box$3.isEmpty()) return;
34549 var min = _box$3.min;
34550 var max = _box$3.max;
34556 0: max.x, max.y, max.z
34557 1: min.x, max.y, max.z
34558 2: min.x, min.y, max.z
34559 3: max.x, min.y, max.z
34560 4: max.x, max.y, min.z
34561 5: min.x, max.y, min.z
34562 6: min.x, min.y, min.z
34563 7: max.x, min.y, min.z
34566 var position = this.geometry.attributes.position;
34567 var array = position.array;
34592 position.needsUpdate = true;
34593 this.geometry.computeBoundingSphere();
34596 _proto.setFromObject = function setFromObject(object) {
34597 this.object = object;
34602 _proto.copy = function copy(source) {
34603 LineSegments.prototype.copy.call(this, source);
34604 this.object = source.object;
34611 var Box3Helper = /*#__PURE__*/function (_LineSegments) {
34612 _inheritsLoose(Box3Helper, _LineSegments);
34614 function Box3Helper(box, color) {
34617 if (color === void 0) {
34621 var indices = new Uint16Array([0, 1, 1, 2, 2, 3, 3, 0, 4, 5, 5, 6, 6, 7, 7, 4, 0, 4, 1, 5, 2, 6, 3, 7]);
34622 var positions = [1, 1, 1, -1, 1, 1, -1, -1, 1, 1, -1, 1, 1, 1, -1, -1, 1, -1, -1, -1, -1, 1, -1, -1];
34623 var geometry = new BufferGeometry();
34624 geometry.setIndex(new BufferAttribute(indices, 1));
34625 geometry.setAttribute('position', new Float32BufferAttribute(positions, 3));
34626 _this = _LineSegments.call(this, geometry, new LineBasicMaterial({
34631 _this.type = 'Box3Helper';
34633 _this.geometry.computeBoundingSphere();
34638 var _proto = Box3Helper.prototype;
34640 _proto.updateMatrixWorld = function updateMatrixWorld(force) {
34641 var box = this.box;
34642 if (box.isEmpty()) return;
34643 box.getCenter(this.position);
34644 box.getSize(this.scale);
34645 this.scale.multiplyScalar(0.5);
34647 _LineSegments.prototype.updateMatrixWorld.call(this, force);
34653 var PlaneHelper = /*#__PURE__*/function (_Line) {
34654 _inheritsLoose(PlaneHelper, _Line);
34656 function PlaneHelper(plane, size, hex) {
34659 if (size === void 0) {
34663 if (hex === void 0) {
34668 var positions = [1, -1, 1, -1, 1, 1, -1, -1, 1, 1, 1, 1, -1, 1, 1, -1, -1, 1, 1, -1, 1, 1, 1, 1, 0, 0, 1, 0, 0, 0];
34669 var geometry = new BufferGeometry();
34670 geometry.setAttribute('position', new Float32BufferAttribute(positions, 3));
34671 geometry.computeBoundingSphere();
34672 _this = _Line.call(this, geometry, new LineBasicMaterial({
34676 _this.type = 'PlaneHelper';
34677 _this.plane = plane;
34679 var positions2 = [1, 1, 1, -1, 1, 1, -1, -1, 1, 1, 1, 1, -1, -1, 1, 1, -1, 1];
34680 var geometry2 = new BufferGeometry();
34681 geometry2.setAttribute('position', new Float32BufferAttribute(positions2, 3));
34682 geometry2.computeBoundingSphere();
34684 _this.add(new Mesh(geometry2, new MeshBasicMaterial({
34695 var _proto = PlaneHelper.prototype;
34697 _proto.updateMatrixWorld = function updateMatrixWorld(force) {
34698 var scale = -this.plane.constant;
34699 if (Math.abs(scale) < 1e-8) scale = 1e-8; // sign does not matter
34701 this.scale.set(0.5 * this.size, 0.5 * this.size, scale);
34702 this.children[0].material.side = scale < 0 ? BackSide : FrontSide; // renderer flips side when determinant < 0; flipping not wanted here
34704 this.lookAt(this.plane.normal);
34706 _Line.prototype.updateMatrixWorld.call(this, force);
34709 return PlaneHelper;
34712 var _axis = /*@__PURE__*/new Vector3();
34714 var _lineGeometry, _coneGeometry;
34716 var ArrowHelper = /*#__PURE__*/function (_Object3D) {
34717 _inheritsLoose(ArrowHelper, _Object3D);
34719 function ArrowHelper(dir, origin, length, color, headLength, headWidth) {
34722 _this = _Object3D.call(this) || this; // dir is assumed to be normalized
34724 _this.type = 'ArrowHelper';
34725 if (dir === undefined) dir = new Vector3(0, 0, 1);
34726 if (origin === undefined) origin = new Vector3(0, 0, 0);
34727 if (length === undefined) length = 1;
34728 if (color === undefined) color = 0xffff00;
34729 if (headLength === undefined) headLength = 0.2 * length;
34730 if (headWidth === undefined) headWidth = 0.2 * headLength;
34732 if (_lineGeometry === undefined) {
34733 _lineGeometry = new BufferGeometry();
34735 _lineGeometry.setAttribute('position', new Float32BufferAttribute([0, 0, 0, 0, 1, 0], 3));
34737 _coneGeometry = new CylinderGeometry(0, 0.5, 1, 5, 1);
34739 _coneGeometry.translate(0, -0.5, 0);
34742 _this.position.copy(origin);
34744 _this.line = new Line(_lineGeometry, new LineBasicMaterial({
34748 _this.line.matrixAutoUpdate = false;
34750 _this.add(_this.line);
34752 _this.cone = new Mesh(_coneGeometry, new MeshBasicMaterial({
34756 _this.cone.matrixAutoUpdate = false;
34758 _this.add(_this.cone);
34760 _this.setDirection(dir);
34762 _this.setLength(length, headLength, headWidth);
34767 var _proto = ArrowHelper.prototype;
34769 _proto.setDirection = function setDirection(dir) {
34770 // dir is assumed to be normalized
34771 if (dir.y > 0.99999) {
34772 this.quaternion.set(0, 0, 0, 1);
34773 } else if (dir.y < -0.99999) {
34774 this.quaternion.set(1, 0, 0, 0);
34776 _axis.set(dir.z, 0, -dir.x).normalize();
34778 var radians = Math.acos(dir.y);
34779 this.quaternion.setFromAxisAngle(_axis, radians);
34783 _proto.setLength = function setLength(length, headLength, headWidth) {
34784 if (headLength === undefined) headLength = 0.2 * length;
34785 if (headWidth === undefined) headWidth = 0.2 * headLength;
34786 this.line.scale.set(1, Math.max(0.0001, length - headLength), 1); // see #17458
34788 this.line.updateMatrix();
34789 this.cone.scale.set(headWidth, headLength, headWidth);
34790 this.cone.position.y = length;
34791 this.cone.updateMatrix();
34794 _proto.setColor = function setColor(color) {
34795 this.line.material.color.set(color);
34796 this.cone.material.color.set(color);
34799 _proto.copy = function copy(source) {
34800 _Object3D.prototype.copy.call(this, source, false);
34802 this.line.copy(source.line);
34803 this.cone.copy(source.cone);
34807 return ArrowHelper;
34810 var AxesHelper = /*#__PURE__*/function (_LineSegments) {
34811 _inheritsLoose(AxesHelper, _LineSegments);
34813 function AxesHelper(size) {
34816 if (size === void 0) {
34820 var vertices = [0, 0, 0, size, 0, 0, 0, 0, 0, 0, size, 0, 0, 0, 0, 0, 0, size];
34821 var colors = [1, 0, 0, 1, 0.6, 0, 0, 1, 0, 0.6, 1, 0, 0, 0, 1, 0, 0.6, 1];
34822 var geometry = new BufferGeometry();
34823 geometry.setAttribute('position', new Float32BufferAttribute(vertices, 3));
34824 geometry.setAttribute('color', new Float32BufferAttribute(colors, 3));
34825 var material = new LineBasicMaterial({
34826 vertexColors: true,
34829 _this = _LineSegments.call(this, geometry, material) || this;
34830 _this.type = 'AxesHelper';
34837 var _floatView = new Float32Array(1);
34839 var _int32View = new Int32Array(_floatView.buffer);
34842 // Converts float32 to float16 (stored as uint16 value).
34843 toHalfFloat: function toHalfFloat(val) {
34844 // Source: http://gamedev.stackexchange.com/questions/17326/conversion-of-a-number-from-single-precision-floating-point-representation-to-a/17410#17410
34846 /* This method is faster than the OpenEXR implementation (very often
34847 * used, eg. in Ogre), with the additional benefit of rounding, inspired
34848 * by James Tursa?s half-precision code. */
34849 _floatView[0] = val;
34850 var x = _int32View[0];
34851 var bits = x >> 16 & 0x8000;
34854 var m = x >> 12 & 0x07ff;
34855 /* Keep one extra bit for rounding */
34857 var e = x >> 23 & 0xff;
34858 /* Using int is faster here */
34860 /* If zero, or denormal, or exponent underflows too much for a denormal
34861 * half, return signed zero. */
34863 if (e < 103) return bits;
34864 /* If NaN, return NaN. If Inf or exponent overflow, return Inf. */
34868 /* If exponent was 0xff and one mantissa bit was set, it means NaN,
34869 * not Inf, so make sure we set one mantissa bit too. */
34871 bits |= (e == 255 ? 0 : 1) && x & 0x007fffff;
34874 /* If exponent underflows but not too much, return a denormal */
34879 /* Extra rounding may overflow and set mantissa to 0 and exponent
34880 * to 1, which is OK. */
34882 bits |= (m >> 114 - e) + (m >> 113 - e & 1);
34886 bits |= e - 112 << 10 | m >> 1;
34887 /* Extra rounding. An overflow will set mantissa to 0 and increment
34888 * the exponent, which is OK. */
34898 var SIZE_MAX = Math.pow(2, LOD_MAX); // The standard deviations (radians) associated with the extra mips. These are
34899 // chosen to approximate a Trowbridge-Reitz distribution function times the
34900 // geometric shadowing function. These sigma values squared must match the
34901 // variance #defines in cube_uv_reflection_fragment.glsl.js.
34903 var EXTRA_LOD_SIGMA = [0.125, 0.215, 0.35, 0.446, 0.526, 0.582];
34904 var TOTAL_LODS = LOD_MAX - LOD_MIN + 1 + EXTRA_LOD_SIGMA.length; // The maximum length of the blur for loop. Smaller sigmas will use fewer
34905 // samples and exit early, but not recompile the shader.
34907 var MAX_SAMPLES = 20;
34908 var ENCODINGS = (_ENCODINGS = {}, _ENCODINGS[LinearEncoding] = 0, _ENCODINGS[sRGBEncoding] = 1, _ENCODINGS[RGBEEncoding] = 2, _ENCODINGS[RGBM7Encoding] = 3, _ENCODINGS[RGBM16Encoding] = 4, _ENCODINGS[RGBDEncoding] = 5, _ENCODINGS[GammaEncoding] = 6, _ENCODINGS);
34909 var backgroundMaterial = new MeshBasicMaterial({
34914 var backgroundBox = new Mesh(new BoxGeometry(), backgroundMaterial);
34916 var _flatCamera = /*@__PURE__*/new OrthographicCamera();
34918 var _createPlanes2 = /*@__PURE__*/_createPlanes(),
34919 _lodPlanes = _createPlanes2._lodPlanes,
34920 _sizeLods = _createPlanes2._sizeLods,
34921 _sigmas = _createPlanes2._sigmas;
34923 var _clearColor = /*@__PURE__*/new Color();
34925 var _oldTarget = null; // Golden Ratio
34927 var PHI = (1 + Math.sqrt(5)) / 2;
34928 var INV_PHI = 1 / PHI; // Vertices of a dodecahedron (except the opposites, which represent the
34929 // same axis), used as axis directions evenly spread on a sphere.
34931 var _axisDirections = [/*@__PURE__*/new Vector3(1, 1, 1), /*@__PURE__*/new Vector3(-1, 1, 1), /*@__PURE__*/new Vector3(1, 1, -1), /*@__PURE__*/new Vector3(-1, 1, -1), /*@__PURE__*/new Vector3(0, PHI, INV_PHI), /*@__PURE__*/new Vector3(0, PHI, -INV_PHI), /*@__PURE__*/new Vector3(INV_PHI, 0, PHI), /*@__PURE__*/new Vector3(-INV_PHI, 0, PHI), /*@__PURE__*/new Vector3(PHI, INV_PHI, 0), /*@__PURE__*/new Vector3(-PHI, INV_PHI, 0)];
34933 * This class generates a Prefiltered, Mipmapped Radiance Environment Map
34934 * (PMREM) from a cubeMap environment texture. This allows different levels of
34935 * blur to be quickly accessed based on material roughness. It is packed into a
34936 * special CubeUV format that allows us to perform custom interpolation so that
34937 * we can support nonlinear formats such as RGBE. Unlike a traditional mipmap
34938 * chain, it only goes down to the LOD_MIN level (above), and then creates extra
34939 * even more filtered 'mips' at the same LOD_MIN resolution, associated with
34940 * higher roughness levels. In this way we maintain resolution to smoothly
34941 * interpolate diffuse lighting while limiting sampling computation.
34944 function convertLinearToRGBE(color) {
34945 var maxComponent = Math.max(color.r, color.g, color.b);
34946 var fExp = Math.min(Math.max(Math.ceil(Math.log2(maxComponent)), -128.0), 127.0);
34947 color.multiplyScalar(Math.pow(2.0, -fExp));
34948 var alpha = (fExp + 128.0) / 255.0;
34952 var PMREMGenerator = /*#__PURE__*/function () {
34953 function PMREMGenerator(renderer) {
34954 this._renderer = renderer;
34955 this._pingPongRenderTarget = null;
34956 this._blurMaterial = _getBlurShader(MAX_SAMPLES);
34957 this._equirectShader = null;
34958 this._cubemapShader = null;
34960 this._compileMaterial(this._blurMaterial);
34963 * Generates a PMREM from a supplied Scene, which can be faster than using an
34964 * image if networking bandwidth is low. Optional sigma specifies a blur radius
34965 * in radians to be applied to the scene before PMREM generation. Optional near
34966 * and far planes ensure the scene is rendered in its entirety (the cubeCamera
34967 * is placed at the origin).
34971 var _proto = PMREMGenerator.prototype;
34973 _proto.fromScene = function fromScene(scene, sigma, near, far) {
34974 if (sigma === void 0) {
34978 if (near === void 0) {
34982 if (far === void 0) {
34986 _oldTarget = this._renderer.getRenderTarget();
34988 var cubeUVRenderTarget = this._allocateTargets();
34990 this._sceneToCubeUV(scene, near, far, cubeUVRenderTarget);
34993 this._blur(cubeUVRenderTarget, 0, 0, sigma);
34996 this._applyPMREM(cubeUVRenderTarget);
34998 this._cleanup(cubeUVRenderTarget);
35000 return cubeUVRenderTarget;
35003 * Generates a PMREM from an equirectangular texture, which can be either LDR
35004 * (RGBFormat) or HDR (RGBEFormat). The ideal input image size is 1k (1024 x 512),
35005 * as this matches best with the 256 x 256 cubemap output.
35009 _proto.fromEquirectangular = function fromEquirectangular(equirectangular) {
35010 return this._fromTexture(equirectangular);
35013 * Generates a PMREM from an cubemap texture, which can be either LDR
35014 * (RGBFormat) or HDR (RGBEFormat). The ideal input cube size is 256 x 256,
35015 * as this matches best with the 256 x 256 cubemap output.
35019 _proto.fromCubemap = function fromCubemap(cubemap) {
35020 return this._fromTexture(cubemap);
35023 * Pre-compiles the cubemap shader. You can get faster start-up by invoking this method during
35024 * your texture's network fetch for increased concurrency.
35028 _proto.compileCubemapShader = function compileCubemapShader() {
35029 if (this._cubemapShader === null) {
35030 this._cubemapShader = _getCubemapShader();
35032 this._compileMaterial(this._cubemapShader);
35036 * Pre-compiles the equirectangular shader. You can get faster start-up by invoking this method during
35037 * your texture's network fetch for increased concurrency.
35041 _proto.compileEquirectangularShader = function compileEquirectangularShader() {
35042 if (this._equirectShader === null) {
35043 this._equirectShader = _getEquirectShader();
35045 this._compileMaterial(this._equirectShader);
35049 * Disposes of the PMREMGenerator's internal memory. Note that PMREMGenerator is a static class,
35050 * so you should not need more than one PMREMGenerator object. If you do, calling dispose() on
35051 * one of them will cause any others to also become unusable.
35055 _proto.dispose = function dispose() {
35056 this._blurMaterial.dispose();
35058 if (this._cubemapShader !== null) this._cubemapShader.dispose();
35059 if (this._equirectShader !== null) this._equirectShader.dispose();
35061 for (var i = 0; i < _lodPlanes.length; i++) {
35062 _lodPlanes[i].dispose();
35064 } // private interface
35067 _proto._cleanup = function _cleanup(outputTarget) {
35068 this._pingPongRenderTarget.dispose();
35070 this._renderer.setRenderTarget(_oldTarget);
35072 outputTarget.scissorTest = false;
35074 _setViewport(outputTarget, 0, 0, outputTarget.width, outputTarget.height);
35077 _proto._fromTexture = function _fromTexture(texture) {
35078 _oldTarget = this._renderer.getRenderTarget();
35080 var cubeUVRenderTarget = this._allocateTargets(texture);
35082 this._textureToCubeUV(texture, cubeUVRenderTarget);
35084 this._applyPMREM(cubeUVRenderTarget);
35086 this._cleanup(cubeUVRenderTarget);
35088 return cubeUVRenderTarget;
35091 _proto._allocateTargets = function _allocateTargets(texture) {
35092 // warning: null texture is valid
35094 magFilter: NearestFilter,
35095 minFilter: NearestFilter,
35096 generateMipmaps: false,
35097 type: UnsignedByteType,
35098 format: RGBEFormat,
35099 encoding: _isLDR(texture) ? texture.encoding : RGBEEncoding,
35103 var cubeUVRenderTarget = _createRenderTarget(params);
35105 cubeUVRenderTarget.depthBuffer = texture ? false : true;
35106 this._pingPongRenderTarget = _createRenderTarget(params);
35107 return cubeUVRenderTarget;
35110 _proto._compileMaterial = function _compileMaterial(material) {
35111 var tmpMesh = new Mesh(_lodPlanes[0], material);
35113 this._renderer.compile(tmpMesh, _flatCamera);
35116 _proto._sceneToCubeUV = function _sceneToCubeUV(scene, near, far, cubeUVRenderTarget) {
35119 var cubeCamera = new PerspectiveCamera(fov, aspect, near, far);
35120 var upSign = [1, -1, 1, 1, 1, 1];
35121 var forwardSign = [1, 1, 1, -1, -1, -1];
35122 var renderer = this._renderer;
35123 var originalAutoClear = renderer.autoClear;
35124 var outputEncoding = renderer.outputEncoding;
35125 var toneMapping = renderer.toneMapping;
35126 renderer.getClearColor(_clearColor);
35127 renderer.toneMapping = NoToneMapping;
35128 renderer.outputEncoding = LinearEncoding;
35129 renderer.autoClear = false;
35130 var useSolidColor = false;
35131 var background = scene.background;
35134 if (background.isColor) {
35135 backgroundMaterial.color.copy(background).convertSRGBToLinear();
35136 scene.background = null;
35137 var alpha = convertLinearToRGBE(backgroundMaterial.color);
35138 backgroundMaterial.opacity = alpha;
35139 useSolidColor = true;
35142 backgroundMaterial.color.copy(_clearColor).convertSRGBToLinear();
35144 var _alpha = convertLinearToRGBE(backgroundMaterial.color);
35146 backgroundMaterial.opacity = _alpha;
35147 useSolidColor = true;
35150 for (var i = 0; i < 6; i++) {
35154 cubeCamera.up.set(0, upSign[i], 0);
35155 cubeCamera.lookAt(forwardSign[i], 0, 0);
35156 } else if (col == 1) {
35157 cubeCamera.up.set(0, 0, upSign[i]);
35158 cubeCamera.lookAt(0, forwardSign[i], 0);
35160 cubeCamera.up.set(0, upSign[i], 0);
35161 cubeCamera.lookAt(0, 0, forwardSign[i]);
35164 _setViewport(cubeUVRenderTarget, col * SIZE_MAX, i > 2 ? SIZE_MAX : 0, SIZE_MAX, SIZE_MAX);
35166 renderer.setRenderTarget(cubeUVRenderTarget);
35168 if (useSolidColor) {
35169 renderer.render(backgroundBox, cubeCamera);
35172 renderer.render(scene, cubeCamera);
35175 renderer.toneMapping = toneMapping;
35176 renderer.outputEncoding = outputEncoding;
35177 renderer.autoClear = originalAutoClear;
35180 _proto._textureToCubeUV = function _textureToCubeUV(texture, cubeUVRenderTarget) {
35181 var renderer = this._renderer;
35183 if (texture.isCubeTexture) {
35184 if (this._cubemapShader == null) {
35185 this._cubemapShader = _getCubemapShader();
35188 if (this._equirectShader == null) {
35189 this._equirectShader = _getEquirectShader();
35193 var material = texture.isCubeTexture ? this._cubemapShader : this._equirectShader;
35194 var mesh = new Mesh(_lodPlanes[0], material);
35195 var uniforms = material.uniforms;
35196 uniforms['envMap'].value = texture;
35198 if (!texture.isCubeTexture) {
35199 uniforms['texelSize'].value.set(1.0 / texture.image.width, 1.0 / texture.image.height);
35202 uniforms['inputEncoding'].value = ENCODINGS[texture.encoding];
35203 uniforms['outputEncoding'].value = ENCODINGS[cubeUVRenderTarget.texture.encoding];
35205 _setViewport(cubeUVRenderTarget, 0, 0, 3 * SIZE_MAX, 2 * SIZE_MAX);
35207 renderer.setRenderTarget(cubeUVRenderTarget);
35208 renderer.render(mesh, _flatCamera);
35211 _proto._applyPMREM = function _applyPMREM(cubeUVRenderTarget) {
35212 var renderer = this._renderer;
35213 var autoClear = renderer.autoClear;
35214 renderer.autoClear = false;
35216 for (var i = 1; i < TOTAL_LODS; i++) {
35217 var sigma = Math.sqrt(_sigmas[i] * _sigmas[i] - _sigmas[i - 1] * _sigmas[i - 1]);
35218 var poleAxis = _axisDirections[(i - 1) % _axisDirections.length];
35220 this._blur(cubeUVRenderTarget, i - 1, i, sigma, poleAxis);
35223 renderer.autoClear = autoClear;
35226 * This is a two-pass Gaussian blur for a cubemap. Normally this is done
35227 * vertically and horizontally, but this breaks down on a cube. Here we apply
35228 * the blur latitudinally (around the poles), and then longitudinally (towards
35229 * the poles) to approximate the orthogonally-separable blur. It is least
35230 * accurate at the poles, but still does a decent job.
35234 _proto._blur = function _blur(cubeUVRenderTarget, lodIn, lodOut, sigma, poleAxis) {
35235 var pingPongRenderTarget = this._pingPongRenderTarget;
35237 this._halfBlur(cubeUVRenderTarget, pingPongRenderTarget, lodIn, lodOut, sigma, 'latitudinal', poleAxis);
35239 this._halfBlur(pingPongRenderTarget, cubeUVRenderTarget, lodOut, lodOut, sigma, 'longitudinal', poleAxis);
35242 _proto._halfBlur = function _halfBlur(targetIn, targetOut, lodIn, lodOut, sigmaRadians, direction, poleAxis) {
35243 var renderer = this._renderer;
35244 var blurMaterial = this._blurMaterial;
35246 if (direction !== 'latitudinal' && direction !== 'longitudinal') {
35247 console.error('blur direction must be either latitudinal or longitudinal!');
35248 } // Number of standard deviations at which to cut off the discrete approximation.
35251 var STANDARD_DEVIATIONS = 3;
35252 var blurMesh = new Mesh(_lodPlanes[lodOut], blurMaterial);
35253 var blurUniforms = blurMaterial.uniforms;
35254 var pixels = _sizeLods[lodIn] - 1;
35255 var radiansPerPixel = isFinite(sigmaRadians) ? Math.PI / (2 * pixels) : 2 * Math.PI / (2 * MAX_SAMPLES - 1);
35256 var sigmaPixels = sigmaRadians / radiansPerPixel;
35257 var samples = isFinite(sigmaRadians) ? 1 + Math.floor(STANDARD_DEVIATIONS * sigmaPixels) : MAX_SAMPLES;
35259 if (samples > MAX_SAMPLES) {
35260 console.warn("sigmaRadians, " + sigmaRadians + ", is too large and will clip, as it requested " + samples + " samples when the maximum is set to " + MAX_SAMPLES);
35266 for (var i = 0; i < MAX_SAMPLES; ++i) {
35267 var _x = i / sigmaPixels;
35269 var weight = Math.exp(-_x * _x / 2);
35270 weights.push(weight);
35274 } else if (i < samples) {
35279 for (var _i = 0; _i < weights.length; _i++) {
35280 weights[_i] = weights[_i] / sum;
35283 blurUniforms['envMap'].value = targetIn.texture;
35284 blurUniforms['samples'].value = samples;
35285 blurUniforms['weights'].value = weights;
35286 blurUniforms['latitudinal'].value = direction === 'latitudinal';
35289 blurUniforms['poleAxis'].value = poleAxis;
35292 blurUniforms['dTheta'].value = radiansPerPixel;
35293 blurUniforms['mipInt'].value = LOD_MAX - lodIn;
35294 blurUniforms['inputEncoding'].value = ENCODINGS[targetIn.texture.encoding];
35295 blurUniforms['outputEncoding'].value = ENCODINGS[targetIn.texture.encoding];
35296 var outputSize = _sizeLods[lodOut];
35297 var x = 3 * Math.max(0, SIZE_MAX - 2 * outputSize);
35298 var y = (lodOut === 0 ? 0 : 2 * SIZE_MAX) + 2 * outputSize * (lodOut > LOD_MAX - LOD_MIN ? lodOut - LOD_MAX + LOD_MIN : 0);
35300 _setViewport(targetOut, x, y, 3 * outputSize, 2 * outputSize);
35302 renderer.setRenderTarget(targetOut);
35303 renderer.render(blurMesh, _flatCamera);
35306 return PMREMGenerator;
35309 function _isLDR(texture) {
35310 if (texture === undefined || texture.type !== UnsignedByteType) return false;
35311 return texture.encoding === LinearEncoding || texture.encoding === sRGBEncoding || texture.encoding === GammaEncoding;
35314 function _createPlanes() {
35315 var _lodPlanes = [];
35316 var _sizeLods = [];
35320 for (var i = 0; i < TOTAL_LODS; i++) {
35321 var sizeLod = Math.pow(2, lod);
35323 _sizeLods.push(sizeLod);
35325 var sigma = 1.0 / sizeLod;
35327 if (i > LOD_MAX - LOD_MIN) {
35328 sigma = EXTRA_LOD_SIGMA[i - LOD_MAX + LOD_MIN - 1];
35329 } else if (i == 0) {
35333 _sigmas.push(sigma);
35335 var texelSize = 1.0 / (sizeLod - 1);
35336 var min = -texelSize / 2;
35337 var max = 1 + texelSize / 2;
35338 var uv1 = [min, min, max, min, max, max, min, min, max, max, min, max];
35341 var positionSize = 3;
35343 var faceIndexSize = 1;
35344 var position = new Float32Array(positionSize * vertices * cubeFaces);
35345 var uv = new Float32Array(uvSize * vertices * cubeFaces);
35346 var faceIndex = new Float32Array(faceIndexSize * vertices * cubeFaces);
35348 for (var face = 0; face < cubeFaces; face++) {
35349 var x = face % 3 * 2 / 3 - 1;
35350 var y = face > 2 ? 0 : -1;
35351 var coordinates = [x, y, 0, x + 2 / 3, y, 0, x + 2 / 3, y + 1, 0, x, y, 0, x + 2 / 3, y + 1, 0, x, y + 1, 0];
35352 position.set(coordinates, positionSize * vertices * face);
35353 uv.set(uv1, uvSize * vertices * face);
35354 var fill = [face, face, face, face, face, face];
35355 faceIndex.set(fill, faceIndexSize * vertices * face);
35358 var planes = new BufferGeometry();
35359 planes.setAttribute('position', new BufferAttribute(position, positionSize));
35360 planes.setAttribute('uv', new BufferAttribute(uv, uvSize));
35361 planes.setAttribute('faceIndex', new BufferAttribute(faceIndex, faceIndexSize));
35363 _lodPlanes.push(planes);
35365 if (lod > LOD_MIN) {
35371 _lodPlanes: _lodPlanes,
35372 _sizeLods: _sizeLods,
35377 function _createRenderTarget(params) {
35378 var cubeUVRenderTarget = new WebGLRenderTarget(3 * SIZE_MAX, 3 * SIZE_MAX, params);
35379 cubeUVRenderTarget.texture.mapping = CubeUVReflectionMapping;
35380 cubeUVRenderTarget.texture.name = 'PMREM.cubeUv';
35381 cubeUVRenderTarget.scissorTest = true;
35382 return cubeUVRenderTarget;
35385 function _setViewport(target, x, y, width, height) {
35386 target.viewport.set(x, y, width, height);
35387 target.scissor.set(x, y, width, height);
35390 function _getBlurShader(maxSamples) {
35391 var weights = new Float32Array(maxSamples);
35392 var poleAxis = new Vector3(0, 1, 0);
35393 var shaderMaterial = new RawShaderMaterial({
35394 name: 'SphericalGaussianBlur',
35421 value: ENCODINGS[LinearEncoding]
35423 'outputEncoding': {
35424 value: ENCODINGS[LinearEncoding]
35427 vertexShader: _getCommonVertexShader(),
35430 "\n\n\t\t\tprecision mediump float;\n\t\t\tprecision mediump int;\n\n\t\t\tvarying vec3 vOutputDirection;\n\n\t\t\tuniform sampler2D envMap;\n\t\t\tuniform int samples;\n\t\t\tuniform float weights[ n ];\n\t\t\tuniform bool latitudinal;\n\t\t\tuniform float dTheta;\n\t\t\tuniform float mipInt;\n\t\t\tuniform vec3 poleAxis;\n\n\t\t\t" + _getEncodings() + "\n\n\t\t\t#define ENVMAP_TYPE_CUBE_UV\n\t\t\t#include <cube_uv_reflection_fragment>\n\n\t\t\tvec3 getSample( float theta, vec3 axis ) {\n\n\t\t\t\tfloat cosTheta = cos( theta );\n\t\t\t\t// Rodrigues' axis-angle rotation\n\t\t\t\tvec3 sampleDirection = vOutputDirection * cosTheta\n\t\t\t\t\t+ cross( axis, vOutputDirection ) * sin( theta )\n\t\t\t\t\t+ axis * dot( axis, vOutputDirection ) * ( 1.0 - cosTheta );\n\n\t\t\t\treturn bilinearCubeUV( envMap, sampleDirection, mipInt );\n\n\t\t\t}\n\n\t\t\tvoid main() {\n\n\t\t\t\tvec3 axis = latitudinal ? poleAxis : cross( poleAxis, vOutputDirection );\n\n\t\t\t\tif ( all( equal( axis, vec3( 0.0 ) ) ) ) {\n\n\t\t\t\t\taxis = vec3( vOutputDirection.z, 0.0, - vOutputDirection.x );\n\n\t\t\t\t}\n\n\t\t\t\taxis = normalize( axis );\n\n\t\t\t\tgl_FragColor = vec4( 0.0, 0.0, 0.0, 1.0 );\n\t\t\t\tgl_FragColor.rgb += weights[ 0 ] * getSample( 0.0, axis );\n\n\t\t\t\tfor ( int i = 1; i < n; i++ ) {\n\n\t\t\t\t\tif ( i >= samples ) {\n\n\t\t\t\t\t\tbreak;\n\n\t\t\t\t\t}\n\n\t\t\t\t\tfloat theta = dTheta * float( i );\n\t\t\t\t\tgl_FragColor.rgb += weights[ i ] * getSample( -1.0 * theta, axis );\n\t\t\t\t\tgl_FragColor.rgb += weights[ i ] * getSample( theta, axis );\n\n\t\t\t\t}\n\n\t\t\t\tgl_FragColor = linearToOutputTexel( gl_FragColor );\n\n\t\t\t}\n\t\t",
35431 blending: NoBlending,
35435 return shaderMaterial;
35438 function _getEquirectShader() {
35439 var texelSize = new Vector2(1, 1);
35440 var shaderMaterial = new RawShaderMaterial({
35441 name: 'EquirectangularToCubeUV',
35450 value: ENCODINGS[LinearEncoding]
35452 'outputEncoding': {
35453 value: ENCODINGS[LinearEncoding]
35456 vertexShader: _getCommonVertexShader(),
35459 "\n\n\t\t\tprecision mediump float;\n\t\t\tprecision mediump int;\n\n\t\t\tvarying vec3 vOutputDirection;\n\n\t\t\tuniform sampler2D envMap;\n\t\t\tuniform vec2 texelSize;\n\n\t\t\t" + _getEncodings() + "\n\n\t\t\t#include <common>\n\n\t\t\tvoid main() {\n\n\t\t\t\tgl_FragColor = vec4( 0.0, 0.0, 0.0, 1.0 );\n\n\t\t\t\tvec3 outputDirection = normalize( vOutputDirection );\n\t\t\t\tvec2 uv = equirectUv( outputDirection );\n\n\t\t\t\tvec2 f = fract( uv / texelSize - 0.5 );\n\t\t\t\tuv -= f * texelSize;\n\t\t\t\tvec3 tl = envMapTexelToLinear( texture2D ( envMap, uv ) ).rgb;\n\t\t\t\tuv.x += texelSize.x;\n\t\t\t\tvec3 tr = envMapTexelToLinear( texture2D ( envMap, uv ) ).rgb;\n\t\t\t\tuv.y += texelSize.y;\n\t\t\t\tvec3 br = envMapTexelToLinear( texture2D ( envMap, uv ) ).rgb;\n\t\t\t\tuv.x -= texelSize.x;\n\t\t\t\tvec3 bl = envMapTexelToLinear( texture2D ( envMap, uv ) ).rgb;\n\n\t\t\t\tvec3 tm = mix( tl, tr, f.x );\n\t\t\t\tvec3 bm = mix( bl, br, f.x );\n\t\t\t\tgl_FragColor.rgb = mix( tm, bm, f.y );\n\n\t\t\t\tgl_FragColor = linearToOutputTexel( gl_FragColor );\n\n\t\t\t}\n\t\t",
35460 blending: NoBlending,
35464 return shaderMaterial;
35467 function _getCubemapShader() {
35468 var shaderMaterial = new RawShaderMaterial({
35469 name: 'CubemapToCubeUV',
35475 value: ENCODINGS[LinearEncoding]
35477 'outputEncoding': {
35478 value: ENCODINGS[LinearEncoding]
35481 vertexShader: _getCommonVertexShader(),
35484 "\n\n\t\t\tprecision mediump float;\n\t\t\tprecision mediump int;\n\n\t\t\tvarying vec3 vOutputDirection;\n\n\t\t\tuniform samplerCube envMap;\n\n\t\t\t" + _getEncodings() + "\n\n\t\t\tvoid main() {\n\n\t\t\t\tgl_FragColor = vec4( 0.0, 0.0, 0.0, 1.0 );\n\t\t\t\tgl_FragColor.rgb = envMapTexelToLinear( textureCube( envMap, vec3( - vOutputDirection.x, vOutputDirection.yz ) ) ).rgb;\n\t\t\t\tgl_FragColor = linearToOutputTexel( gl_FragColor );\n\n\t\t\t}\n\t\t",
35485 blending: NoBlending,
35489 return shaderMaterial;
35492 function _getCommonVertexShader() {
35495 "\n\n\t\tprecision mediump float;\n\t\tprecision mediump int;\n\n\t\tattribute vec3 position;\n\t\tattribute vec2 uv;\n\t\tattribute float faceIndex;\n\n\t\tvarying vec3 vOutputDirection;\n\n\t\t// RH coordinate system; PMREM face-indexing convention\n\t\tvec3 getDirection( vec2 uv, float face ) {\n\n\t\t\tuv = 2.0 * uv - 1.0;\n\n\t\t\tvec3 direction = vec3( uv, 1.0 );\n\n\t\t\tif ( face == 0.0 ) {\n\n\t\t\t\tdirection = direction.zyx; // ( 1, v, u ) pos x\n\n\t\t\t} else if ( face == 1.0 ) {\n\n\t\t\t\tdirection = direction.xzy;\n\t\t\t\tdirection.xz *= -1.0; // ( -u, 1, -v ) pos y\n\n\t\t\t} else if ( face == 2.0 ) {\n\n\t\t\t\tdirection.x *= -1.0; // ( -u, v, 1 ) pos z\n\n\t\t\t} else if ( face == 3.0 ) {\n\n\t\t\t\tdirection = direction.zyx;\n\t\t\t\tdirection.xz *= -1.0; // ( -1, v, -u ) neg x\n\n\t\t\t} else if ( face == 4.0 ) {\n\n\t\t\t\tdirection = direction.xzy;\n\t\t\t\tdirection.xy *= -1.0; // ( -u, -1, v ) neg y\n\n\t\t\t} else if ( face == 5.0 ) {\n\n\t\t\t\tdirection.z *= -1.0; // ( u, v, -1 ) neg z\n\n\t\t\t}\n\n\t\t\treturn direction;\n\n\t\t}\n\n\t\tvoid main() {\n\n\t\t\tvOutputDirection = getDirection( uv, faceIndex );\n\t\t\tgl_Position = vec4( position, 1.0 );\n\n\t\t}\n\t"
35499 function _getEncodings() {
35502 "\n\n\t\tuniform int inputEncoding;\n\t\tuniform int outputEncoding;\n\n\t\t#include <encodings_pars_fragment>\n\n\t\tvec4 inputTexelToLinear( vec4 value ) {\n\n\t\t\tif ( inputEncoding == 0 ) {\n\n\t\t\t\treturn value;\n\n\t\t\t} else if ( inputEncoding == 1 ) {\n\n\t\t\t\treturn sRGBToLinear( value );\n\n\t\t\t} else if ( inputEncoding == 2 ) {\n\n\t\t\t\treturn RGBEToLinear( value );\n\n\t\t\t} else if ( inputEncoding == 3 ) {\n\n\t\t\t\treturn RGBMToLinear( value, 7.0 );\n\n\t\t\t} else if ( inputEncoding == 4 ) {\n\n\t\t\t\treturn RGBMToLinear( value, 16.0 );\n\n\t\t\t} else if ( inputEncoding == 5 ) {\n\n\t\t\t\treturn RGBDToLinear( value, 256.0 );\n\n\t\t\t} else {\n\n\t\t\t\treturn GammaToLinear( value, 2.2 );\n\n\t\t\t}\n\n\t\t}\n\n\t\tvec4 linearToOutputTexel( vec4 value ) {\n\n\t\t\tif ( outputEncoding == 0 ) {\n\n\t\t\t\treturn value;\n\n\t\t\t} else if ( outputEncoding == 1 ) {\n\n\t\t\t\treturn LinearTosRGB( value );\n\n\t\t\t} else if ( outputEncoding == 2 ) {\n\n\t\t\t\treturn LinearToRGBE( value );\n\n\t\t\t} else if ( outputEncoding == 3 ) {\n\n\t\t\t\treturn LinearToRGBM( value, 7.0 );\n\n\t\t\t} else if ( outputEncoding == 4 ) {\n\n\t\t\t\treturn LinearToRGBM( value, 16.0 );\n\n\t\t\t} else if ( outputEncoding == 5 ) {\n\n\t\t\t\treturn LinearToRGBD( value, 256.0 );\n\n\t\t\t} else {\n\n\t\t\t\treturn LinearToGamma( value, 2.2 );\n\n\t\t\t}\n\n\t\t}\n\n\t\tvec4 envMapTexelToLinear( vec4 color ) {\n\n\t\t\treturn inputTexelToLinear( color );\n\n\t\t}\n\t"
35506 function Face4(a, b, c, d, normal, color, materialIndex) {
35507 console.warn('THREE.Face4 has been removed. A THREE.Face3 will be created instead.');
35508 return new Face3(a, b, c, normal, color, materialIndex);
35511 var LinePieces = 1;
35513 var FaceColors = 1;
35514 var VertexColors = 2;
35515 function MeshFaceMaterial(materials) {
35516 console.warn('THREE.MeshFaceMaterial has been removed. Use an Array instead.');
35519 function MultiMaterial(materials) {
35520 if (materials === void 0) {
35524 console.warn('THREE.MultiMaterial has been removed. Use an Array instead.');
35525 materials.isMultiMaterial = true;
35526 materials.materials = materials;
35528 materials.clone = function () {
35529 return materials.slice();
35534 function PointCloud(geometry, material) {
35535 console.warn('THREE.PointCloud has been renamed to THREE.Points.');
35536 return new Points(geometry, material);
35538 function Particle(material) {
35539 console.warn('THREE.Particle has been renamed to THREE.Sprite.');
35540 return new Sprite(material);
35542 function ParticleSystem(geometry, material) {
35543 console.warn('THREE.ParticleSystem has been renamed to THREE.Points.');
35544 return new Points(geometry, material);
35546 function PointCloudMaterial(parameters) {
35547 console.warn('THREE.PointCloudMaterial has been renamed to THREE.PointsMaterial.');
35548 return new PointsMaterial(parameters);
35550 function ParticleBasicMaterial(parameters) {
35551 console.warn('THREE.ParticleBasicMaterial has been renamed to THREE.PointsMaterial.');
35552 return new PointsMaterial(parameters);
35554 function ParticleSystemMaterial(parameters) {
35555 console.warn('THREE.ParticleSystemMaterial has been renamed to THREE.PointsMaterial.');
35556 return new PointsMaterial(parameters);
35558 function Vertex(x, y, z) {
35559 console.warn('THREE.Vertex has been removed. Use THREE.Vector3 instead.');
35560 return new Vector3(x, y, z);
35563 function DynamicBufferAttribute(array, itemSize) {
35564 console.warn('THREE.DynamicBufferAttribute has been removed. Use new THREE.BufferAttribute().setUsage( THREE.DynamicDrawUsage ) instead.');
35565 return new BufferAttribute(array, itemSize).setUsage(DynamicDrawUsage);
35567 function Int8Attribute(array, itemSize) {
35568 console.warn('THREE.Int8Attribute has been removed. Use new THREE.Int8BufferAttribute() instead.');
35569 return new Int8BufferAttribute(array, itemSize);
35571 function Uint8Attribute(array, itemSize) {
35572 console.warn('THREE.Uint8Attribute has been removed. Use new THREE.Uint8BufferAttribute() instead.');
35573 return new Uint8BufferAttribute(array, itemSize);
35575 function Uint8ClampedAttribute(array, itemSize) {
35576 console.warn('THREE.Uint8ClampedAttribute has been removed. Use new THREE.Uint8ClampedBufferAttribute() instead.');
35577 return new Uint8ClampedBufferAttribute(array, itemSize);
35579 function Int16Attribute(array, itemSize) {
35580 console.warn('THREE.Int16Attribute has been removed. Use new THREE.Int16BufferAttribute() instead.');
35581 return new Int16BufferAttribute(array, itemSize);
35583 function Uint16Attribute(array, itemSize) {
35584 console.warn('THREE.Uint16Attribute has been removed. Use new THREE.Uint16BufferAttribute() instead.');
35585 return new Uint16BufferAttribute(array, itemSize);
35587 function Int32Attribute(array, itemSize) {
35588 console.warn('THREE.Int32Attribute has been removed. Use new THREE.Int32BufferAttribute() instead.');
35589 return new Int32BufferAttribute(array, itemSize);
35591 function Uint32Attribute(array, itemSize) {
35592 console.warn('THREE.Uint32Attribute has been removed. Use new THREE.Uint32BufferAttribute() instead.');
35593 return new Uint32BufferAttribute(array, itemSize);
35595 function Float32Attribute(array, itemSize) {
35596 console.warn('THREE.Float32Attribute has been removed. Use new THREE.Float32BufferAttribute() instead.');
35597 return new Float32BufferAttribute(array, itemSize);
35599 function Float64Attribute(array, itemSize) {
35600 console.warn('THREE.Float64Attribute has been removed. Use new THREE.Float64BufferAttribute() instead.');
35601 return new Float64BufferAttribute(array, itemSize);
35604 Curve.create = function (construct, getPoint) {
35605 console.log('THREE.Curve.create() has been deprecated');
35606 construct.prototype = Object.create(Curve.prototype);
35607 construct.prototype.constructor = construct;
35608 construct.prototype.getPoint = getPoint;
35613 Object.assign(Path.prototype, {
35614 fromPoints: function fromPoints(points) {
35615 console.warn('THREE.Path: .fromPoints() has been renamed to .setFromPoints().');
35616 return this.setFromPoints(points);
35620 function ClosedSplineCurve3(points) {
35621 console.warn('THREE.ClosedSplineCurve3 has been deprecated. Use THREE.CatmullRomCurve3 instead.');
35622 CatmullRomCurve3.call(this, points);
35623 this.type = 'catmullrom';
35624 this.closed = true;
35626 ClosedSplineCurve3.prototype = Object.create(CatmullRomCurve3.prototype); //
35628 function SplineCurve3(points) {
35629 console.warn('THREE.SplineCurve3 has been deprecated. Use THREE.CatmullRomCurve3 instead.');
35630 CatmullRomCurve3.call(this, points);
35631 this.type = 'catmullrom';
35633 SplineCurve3.prototype = Object.create(CatmullRomCurve3.prototype); //
35635 function Spline(points) {
35636 console.warn('THREE.Spline has been removed. Use THREE.CatmullRomCurve3 instead.');
35637 CatmullRomCurve3.call(this, points);
35638 this.type = 'catmullrom';
35640 Spline.prototype = Object.create(CatmullRomCurve3.prototype);
35641 Object.assign(Spline.prototype, {
35642 initFromArray: function initFromArray()
35645 console.error('THREE.Spline: .initFromArray() has been removed.');
35647 getControlPointsArray: function getControlPointsArray()
35648 /* optionalTarget */
35650 console.error('THREE.Spline: .getControlPointsArray() has been removed.');
35652 reparametrizeByArcLength: function reparametrizeByArcLength()
35655 console.error('THREE.Spline: .reparametrizeByArcLength() has been removed.');
35659 function AxisHelper(size) {
35660 console.warn('THREE.AxisHelper has been renamed to THREE.AxesHelper.');
35661 return new AxesHelper(size);
35663 function BoundingBoxHelper(object, color) {
35664 console.warn('THREE.BoundingBoxHelper has been deprecated. Creating a THREE.BoxHelper instead.');
35665 return new BoxHelper(object, color);
35667 function EdgesHelper(object, hex) {
35668 console.warn('THREE.EdgesHelper has been removed. Use THREE.EdgesGeometry instead.');
35669 return new LineSegments(new EdgesGeometry(object.geometry), new LineBasicMaterial({
35670 color: hex !== undefined ? hex : 0xffffff
35674 GridHelper.prototype.setColors = function () {
35675 console.error('THREE.GridHelper: setColors() has been deprecated, pass them in the constructor instead.');
35678 SkeletonHelper.prototype.update = function () {
35679 console.error('THREE.SkeletonHelper: update() no longer needs to be called.');
35682 function WireframeHelper(object, hex) {
35683 console.warn('THREE.WireframeHelper has been removed. Use THREE.WireframeGeometry instead.');
35684 return new LineSegments(new WireframeGeometry(object.geometry), new LineBasicMaterial({
35685 color: hex !== undefined ? hex : 0xffffff
35689 Object.assign(Loader.prototype, {
35690 extractUrlBase: function extractUrlBase(url) {
35691 console.warn('THREE.Loader: .extractUrlBase() has been deprecated. Use THREE.LoaderUtils.extractUrlBase() instead.');
35692 return LoaderUtils.extractUrlBase(url);
35695 Loader.Handlers = {
35696 add: function add()
35697 /* regex, loader */
35699 console.error('THREE.Loader: Handlers.add() has been removed. Use LoadingManager.addHandler() instead.');
35701 get: function get()
35704 console.error('THREE.Loader: Handlers.get() has been removed. Use LoadingManager.getHandler() instead.');
35707 function XHRLoader(manager) {
35708 console.warn('THREE.XHRLoader has been renamed to THREE.FileLoader.');
35709 return new FileLoader(manager);
35711 function BinaryTextureLoader(manager) {
35712 console.warn('THREE.BinaryTextureLoader has been renamed to THREE.DataTextureLoader.');
35713 return new DataTextureLoader(manager);
35716 Object.assign(Box2.prototype, {
35717 center: function center(optionalTarget) {
35718 console.warn('THREE.Box2: .center() has been renamed to .getCenter().');
35719 return this.getCenter(optionalTarget);
35721 empty: function empty() {
35722 console.warn('THREE.Box2: .empty() has been renamed to .isEmpty().');
35723 return this.isEmpty();
35725 isIntersectionBox: function isIntersectionBox(box) {
35726 console.warn('THREE.Box2: .isIntersectionBox() has been renamed to .intersectsBox().');
35727 return this.intersectsBox(box);
35729 size: function size(optionalTarget) {
35730 console.warn('THREE.Box2: .size() has been renamed to .getSize().');
35731 return this.getSize(optionalTarget);
35734 Object.assign(Box3.prototype, {
35735 center: function center(optionalTarget) {
35736 console.warn('THREE.Box3: .center() has been renamed to .getCenter().');
35737 return this.getCenter(optionalTarget);
35739 empty: function empty() {
35740 console.warn('THREE.Box3: .empty() has been renamed to .isEmpty().');
35741 return this.isEmpty();
35743 isIntersectionBox: function isIntersectionBox(box) {
35744 console.warn('THREE.Box3: .isIntersectionBox() has been renamed to .intersectsBox().');
35745 return this.intersectsBox(box);
35747 isIntersectionSphere: function isIntersectionSphere(sphere) {
35748 console.warn('THREE.Box3: .isIntersectionSphere() has been renamed to .intersectsSphere().');
35749 return this.intersectsSphere(sphere);
35751 size: function size(optionalTarget) {
35752 console.warn('THREE.Box3: .size() has been renamed to .getSize().');
35753 return this.getSize(optionalTarget);
35756 Object.assign(Sphere.prototype, {
35757 empty: function empty() {
35758 console.warn('THREE.Sphere: .empty() has been renamed to .isEmpty().');
35759 return this.isEmpty();
35763 Frustum.prototype.setFromMatrix = function (m) {
35764 console.warn('THREE.Frustum: .setFromMatrix() has been renamed to .setFromProjectionMatrix().');
35765 return this.setFromProjectionMatrix(m);
35768 Line3.prototype.center = function (optionalTarget) {
35769 console.warn('THREE.Line3: .center() has been renamed to .getCenter().');
35770 return this.getCenter(optionalTarget);
35773 Object.assign(MathUtils, {
35774 random16: function random16() {
35775 console.warn('THREE.Math: .random16() has been deprecated. Use Math.random() instead.');
35776 return Math.random();
35778 nearestPowerOfTwo: function nearestPowerOfTwo(value) {
35779 console.warn('THREE.Math: .nearestPowerOfTwo() has been renamed to .floorPowerOfTwo().');
35780 return MathUtils.floorPowerOfTwo(value);
35782 nextPowerOfTwo: function nextPowerOfTwo(value) {
35783 console.warn('THREE.Math: .nextPowerOfTwo() has been renamed to .ceilPowerOfTwo().');
35784 return MathUtils.ceilPowerOfTwo(value);
35787 Object.assign(Matrix3.prototype, {
35788 flattenToArrayOffset: function flattenToArrayOffset(array, offset) {
35789 console.warn('THREE.Matrix3: .flattenToArrayOffset() has been deprecated. Use .toArray() instead.');
35790 return this.toArray(array, offset);
35792 multiplyVector3: function multiplyVector3(vector) {
35793 console.warn('THREE.Matrix3: .multiplyVector3() has been removed. Use vector.applyMatrix3( matrix ) instead.');
35794 return vector.applyMatrix3(this);
35796 multiplyVector3Array: function multiplyVector3Array()
35799 console.error('THREE.Matrix3: .multiplyVector3Array() has been removed.');
35801 applyToBufferAttribute: function applyToBufferAttribute(attribute) {
35802 console.warn('THREE.Matrix3: .applyToBufferAttribute() has been removed. Use attribute.applyMatrix3( matrix ) instead.');
35803 return attribute.applyMatrix3(this);
35805 applyToVector3Array: function applyToVector3Array()
35806 /* array, offset, length */
35808 console.error('THREE.Matrix3: .applyToVector3Array() has been removed.');
35810 getInverse: function getInverse(matrix) {
35811 console.warn('THREE.Matrix3: .getInverse() has been removed. Use matrixInv.copy( matrix ).invert(); instead.');
35812 return this.copy(matrix).invert();
35815 Object.assign(Matrix4.prototype, {
35816 extractPosition: function extractPosition(m) {
35817 console.warn('THREE.Matrix4: .extractPosition() has been renamed to .copyPosition().');
35818 return this.copyPosition(m);
35820 flattenToArrayOffset: function flattenToArrayOffset(array, offset) {
35821 console.warn('THREE.Matrix4: .flattenToArrayOffset() has been deprecated. Use .toArray() instead.');
35822 return this.toArray(array, offset);
35824 getPosition: function getPosition() {
35825 console.warn('THREE.Matrix4: .getPosition() has been removed. Use Vector3.setFromMatrixPosition( matrix ) instead.');
35826 return new Vector3().setFromMatrixColumn(this, 3);
35828 setRotationFromQuaternion: function setRotationFromQuaternion(q) {
35829 console.warn('THREE.Matrix4: .setRotationFromQuaternion() has been renamed to .makeRotationFromQuaternion().');
35830 return this.makeRotationFromQuaternion(q);
35832 multiplyToArray: function multiplyToArray() {
35833 console.warn('THREE.Matrix4: .multiplyToArray() has been removed.');
35835 multiplyVector3: function multiplyVector3(vector) {
35836 console.warn('THREE.Matrix4: .multiplyVector3() has been removed. Use vector.applyMatrix4( matrix ) instead.');
35837 return vector.applyMatrix4(this);
35839 multiplyVector4: function multiplyVector4(vector) {
35840 console.warn('THREE.Matrix4: .multiplyVector4() has been removed. Use vector.applyMatrix4( matrix ) instead.');
35841 return vector.applyMatrix4(this);
35843 multiplyVector3Array: function multiplyVector3Array()
35846 console.error('THREE.Matrix4: .multiplyVector3Array() has been removed.');
35848 rotateAxis: function rotateAxis(v) {
35849 console.warn('THREE.Matrix4: .rotateAxis() has been removed. Use Vector3.transformDirection( matrix ) instead.');
35850 v.transformDirection(this);
35852 crossVector: function crossVector(vector) {
35853 console.warn('THREE.Matrix4: .crossVector() has been removed. Use vector.applyMatrix4( matrix ) instead.');
35854 return vector.applyMatrix4(this);
35856 translate: function translate() {
35857 console.error('THREE.Matrix4: .translate() has been removed.');
35859 rotateX: function rotateX() {
35860 console.error('THREE.Matrix4: .rotateX() has been removed.');
35862 rotateY: function rotateY() {
35863 console.error('THREE.Matrix4: .rotateY() has been removed.');
35865 rotateZ: function rotateZ() {
35866 console.error('THREE.Matrix4: .rotateZ() has been removed.');
35868 rotateByAxis: function rotateByAxis() {
35869 console.error('THREE.Matrix4: .rotateByAxis() has been removed.');
35871 applyToBufferAttribute: function applyToBufferAttribute(attribute) {
35872 console.warn('THREE.Matrix4: .applyToBufferAttribute() has been removed. Use attribute.applyMatrix4( matrix ) instead.');
35873 return attribute.applyMatrix4(this);
35875 applyToVector3Array: function applyToVector3Array()
35876 /* array, offset, length */
35878 console.error('THREE.Matrix4: .applyToVector3Array() has been removed.');
35880 makeFrustum: function makeFrustum(left, right, bottom, top, near, far) {
35881 console.warn('THREE.Matrix4: .makeFrustum() has been removed. Use .makePerspective( left, right, top, bottom, near, far ) instead.');
35882 return this.makePerspective(left, right, top, bottom, near, far);
35884 getInverse: function getInverse(matrix) {
35885 console.warn('THREE.Matrix4: .getInverse() has been removed. Use matrixInv.copy( matrix ).invert(); instead.');
35886 return this.copy(matrix).invert();
35890 Plane.prototype.isIntersectionLine = function (line) {
35891 console.warn('THREE.Plane: .isIntersectionLine() has been renamed to .intersectsLine().');
35892 return this.intersectsLine(line);
35895 Object.assign(Quaternion.prototype, {
35896 multiplyVector3: function multiplyVector3(vector) {
35897 console.warn('THREE.Quaternion: .multiplyVector3() has been removed. Use is now vector.applyQuaternion( quaternion ) instead.');
35898 return vector.applyQuaternion(this);
35900 inverse: function inverse() {
35901 console.warn('THREE.Quaternion: .inverse() has been renamed to invert().');
35902 return this.invert();
35905 Object.assign(Ray.prototype, {
35906 isIntersectionBox: function isIntersectionBox(box) {
35907 console.warn('THREE.Ray: .isIntersectionBox() has been renamed to .intersectsBox().');
35908 return this.intersectsBox(box);
35910 isIntersectionPlane: function isIntersectionPlane(plane) {
35911 console.warn('THREE.Ray: .isIntersectionPlane() has been renamed to .intersectsPlane().');
35912 return this.intersectsPlane(plane);
35914 isIntersectionSphere: function isIntersectionSphere(sphere) {
35915 console.warn('THREE.Ray: .isIntersectionSphere() has been renamed to .intersectsSphere().');
35916 return this.intersectsSphere(sphere);
35919 Object.assign(Triangle.prototype, {
35920 area: function area() {
35921 console.warn('THREE.Triangle: .area() has been renamed to .getArea().');
35922 return this.getArea();
35924 barycoordFromPoint: function barycoordFromPoint(point, target) {
35925 console.warn('THREE.Triangle: .barycoordFromPoint() has been renamed to .getBarycoord().');
35926 return this.getBarycoord(point, target);
35928 midpoint: function midpoint(target) {
35929 console.warn('THREE.Triangle: .midpoint() has been renamed to .getMidpoint().');
35930 return this.getMidpoint(target);
35932 normal: function normal(target) {
35933 console.warn('THREE.Triangle: .normal() has been renamed to .getNormal().');
35934 return this.getNormal(target);
35936 plane: function plane(target) {
35937 console.warn('THREE.Triangle: .plane() has been renamed to .getPlane().');
35938 return this.getPlane(target);
35941 Object.assign(Triangle, {
35942 barycoordFromPoint: function barycoordFromPoint(point, a, b, c, target) {
35943 console.warn('THREE.Triangle: .barycoordFromPoint() has been renamed to .getBarycoord().');
35944 return Triangle.getBarycoord(point, a, b, c, target);
35946 normal: function normal(a, b, c, target) {
35947 console.warn('THREE.Triangle: .normal() has been renamed to .getNormal().');
35948 return Triangle.getNormal(a, b, c, target);
35951 Object.assign(Shape.prototype, {
35952 extractAllPoints: function extractAllPoints(divisions) {
35953 console.warn('THREE.Shape: .extractAllPoints() has been removed. Use .extractPoints() instead.');
35954 return this.extractPoints(divisions);
35956 extrude: function extrude(options) {
35957 console.warn('THREE.Shape: .extrude() has been removed. Use ExtrudeGeometry() instead.');
35958 return new ExtrudeGeometry(this, options);
35960 makeGeometry: function makeGeometry(options) {
35961 console.warn('THREE.Shape: .makeGeometry() has been removed. Use ShapeGeometry() instead.');
35962 return new ShapeGeometry(this, options);
35965 Object.assign(Vector2.prototype, {
35966 fromAttribute: function fromAttribute(attribute, index, offset) {
35967 console.warn('THREE.Vector2: .fromAttribute() has been renamed to .fromBufferAttribute().');
35968 return this.fromBufferAttribute(attribute, index, offset);
35970 distanceToManhattan: function distanceToManhattan(v) {
35971 console.warn('THREE.Vector2: .distanceToManhattan() has been renamed to .manhattanDistanceTo().');
35972 return this.manhattanDistanceTo(v);
35974 lengthManhattan: function lengthManhattan() {
35975 console.warn('THREE.Vector2: .lengthManhattan() has been renamed to .manhattanLength().');
35976 return this.manhattanLength();
35979 Object.assign(Vector3.prototype, {
35980 setEulerFromRotationMatrix: function setEulerFromRotationMatrix() {
35981 console.error('THREE.Vector3: .setEulerFromRotationMatrix() has been removed. Use Euler.setFromRotationMatrix() instead.');
35983 setEulerFromQuaternion: function setEulerFromQuaternion() {
35984 console.error('THREE.Vector3: .setEulerFromQuaternion() has been removed. Use Euler.setFromQuaternion() instead.');
35986 getPositionFromMatrix: function getPositionFromMatrix(m) {
35987 console.warn('THREE.Vector3: .getPositionFromMatrix() has been renamed to .setFromMatrixPosition().');
35988 return this.setFromMatrixPosition(m);
35990 getScaleFromMatrix: function getScaleFromMatrix(m) {
35991 console.warn('THREE.Vector3: .getScaleFromMatrix() has been renamed to .setFromMatrixScale().');
35992 return this.setFromMatrixScale(m);
35994 getColumnFromMatrix: function getColumnFromMatrix(index, matrix) {
35995 console.warn('THREE.Vector3: .getColumnFromMatrix() has been renamed to .setFromMatrixColumn().');
35996 return this.setFromMatrixColumn(matrix, index);
35998 applyProjection: function applyProjection(m) {
35999 console.warn('THREE.Vector3: .applyProjection() has been removed. Use .applyMatrix4( m ) instead.');
36000 return this.applyMatrix4(m);
36002 fromAttribute: function fromAttribute(attribute, index, offset) {
36003 console.warn('THREE.Vector3: .fromAttribute() has been renamed to .fromBufferAttribute().');
36004 return this.fromBufferAttribute(attribute, index, offset);
36006 distanceToManhattan: function distanceToManhattan(v) {
36007 console.warn('THREE.Vector3: .distanceToManhattan() has been renamed to .manhattanDistanceTo().');
36008 return this.manhattanDistanceTo(v);
36010 lengthManhattan: function lengthManhattan() {
36011 console.warn('THREE.Vector3: .lengthManhattan() has been renamed to .manhattanLength().');
36012 return this.manhattanLength();
36015 Object.assign(Vector4.prototype, {
36016 fromAttribute: function fromAttribute(attribute, index, offset) {
36017 console.warn('THREE.Vector4: .fromAttribute() has been renamed to .fromBufferAttribute().');
36018 return this.fromBufferAttribute(attribute, index, offset);
36020 lengthManhattan: function lengthManhattan() {
36021 console.warn('THREE.Vector4: .lengthManhattan() has been renamed to .manhattanLength().');
36022 return this.manhattanLength();
36026 Object.assign(Object3D.prototype, {
36027 getChildByName: function getChildByName(name) {
36028 console.warn('THREE.Object3D: .getChildByName() has been renamed to .getObjectByName().');
36029 return this.getObjectByName(name);
36031 renderDepth: function renderDepth() {
36032 console.warn('THREE.Object3D: .renderDepth has been removed. Use .renderOrder, instead.');
36034 translate: function translate(distance, axis) {
36035 console.warn('THREE.Object3D: .translate() has been removed. Use .translateOnAxis( axis, distance ) instead.');
36036 return this.translateOnAxis(axis, distance);
36038 getWorldRotation: function getWorldRotation() {
36039 console.error('THREE.Object3D: .getWorldRotation() has been removed. Use THREE.Object3D.getWorldQuaternion( target ) instead.');
36041 applyMatrix: function applyMatrix(matrix) {
36042 console.warn('THREE.Object3D: .applyMatrix() has been renamed to .applyMatrix4().');
36043 return this.applyMatrix4(matrix);
36046 Object.defineProperties(Object3D.prototype, {
36048 get: function get() {
36049 console.warn('THREE.Object3D: .eulerOrder is now .rotation.order.');
36050 return this.rotation.order;
36052 set: function set(value) {
36053 console.warn('THREE.Object3D: .eulerOrder is now .rotation.order.');
36054 this.rotation.order = value;
36058 get: function get() {
36059 console.warn('THREE.Object3D: .useQuaternion has been removed. The library now uses quaternions by default.');
36061 set: function set() {
36062 console.warn('THREE.Object3D: .useQuaternion has been removed. The library now uses quaternions by default.');
36066 Object.assign(Mesh.prototype, {
36067 setDrawMode: function setDrawMode() {
36068 console.error('THREE.Mesh: .setDrawMode() has been removed. The renderer now always assumes THREE.TrianglesDrawMode. Transform your geometry via BufferGeometryUtils.toTrianglesDrawMode() if necessary.');
36071 Object.defineProperties(Mesh.prototype, {
36073 get: function get() {
36074 console.error('THREE.Mesh: .drawMode has been removed. The renderer now always assumes THREE.TrianglesDrawMode.');
36075 return TrianglesDrawMode;
36077 set: function set() {
36078 console.error('THREE.Mesh: .drawMode has been removed. The renderer now always assumes THREE.TrianglesDrawMode. Transform your geometry via BufferGeometryUtils.toTrianglesDrawMode() if necessary.');
36082 Object.defineProperties(LOD.prototype, {
36084 get: function get() {
36085 console.warn('THREE.LOD: .objects has been renamed to .levels.');
36086 return this.levels;
36090 Object.defineProperty(Skeleton.prototype, 'useVertexTexture', {
36091 get: function get() {
36092 console.warn('THREE.Skeleton: useVertexTexture has been removed.');
36094 set: function set() {
36095 console.warn('THREE.Skeleton: useVertexTexture has been removed.');
36099 SkinnedMesh.prototype.initBones = function () {
36100 console.error('THREE.SkinnedMesh: initBones() has been removed.');
36103 Object.defineProperty(Curve.prototype, '__arcLengthDivisions', {
36104 get: function get() {
36105 console.warn('THREE.Curve: .__arcLengthDivisions is now .arcLengthDivisions.');
36106 return this.arcLengthDivisions;
36108 set: function set(value) {
36109 console.warn('THREE.Curve: .__arcLengthDivisions is now .arcLengthDivisions.');
36110 this.arcLengthDivisions = value;
36114 PerspectiveCamera.prototype.setLens = function (focalLength, filmGauge) {
36115 console.warn('THREE.PerspectiveCamera.setLens is deprecated. ' + 'Use .setFocalLength and .filmGauge for a photographic setup.');
36116 if (filmGauge !== undefined) this.filmGauge = filmGauge;
36117 this.setFocalLength(focalLength);
36121 Object.defineProperties(Light.prototype, {
36123 set: function set() {
36124 console.warn('THREE.Light: .onlyShadow has been removed.');
36128 set: function set(value) {
36129 console.warn('THREE.Light: .shadowCameraFov is now .shadow.camera.fov.');
36130 this.shadow.camera.fov = value;
36133 shadowCameraLeft: {
36134 set: function set(value) {
36135 console.warn('THREE.Light: .shadowCameraLeft is now .shadow.camera.left.');
36136 this.shadow.camera.left = value;
36139 shadowCameraRight: {
36140 set: function set(value) {
36141 console.warn('THREE.Light: .shadowCameraRight is now .shadow.camera.right.');
36142 this.shadow.camera.right = value;
36146 set: function set(value) {
36147 console.warn('THREE.Light: .shadowCameraTop is now .shadow.camera.top.');
36148 this.shadow.camera.top = value;
36151 shadowCameraBottom: {
36152 set: function set(value) {
36153 console.warn('THREE.Light: .shadowCameraBottom is now .shadow.camera.bottom.');
36154 this.shadow.camera.bottom = value;
36157 shadowCameraNear: {
36158 set: function set(value) {
36159 console.warn('THREE.Light: .shadowCameraNear is now .shadow.camera.near.');
36160 this.shadow.camera.near = value;
36164 set: function set(value) {
36165 console.warn('THREE.Light: .shadowCameraFar is now .shadow.camera.far.');
36166 this.shadow.camera.far = value;
36169 shadowCameraVisible: {
36170 set: function set() {
36171 console.warn('THREE.Light: .shadowCameraVisible has been removed. Use new THREE.CameraHelper( light.shadow.camera ) instead.');
36175 set: function set(value) {
36176 console.warn('THREE.Light: .shadowBias is now .shadow.bias.');
36177 this.shadow.bias = value;
36181 set: function set() {
36182 console.warn('THREE.Light: .shadowDarkness has been removed.');
36186 set: function set(value) {
36187 console.warn('THREE.Light: .shadowMapWidth is now .shadow.mapSize.width.');
36188 this.shadow.mapSize.width = value;
36192 set: function set(value) {
36193 console.warn('THREE.Light: .shadowMapHeight is now .shadow.mapSize.height.');
36194 this.shadow.mapSize.height = value;
36199 Object.defineProperties(BufferAttribute.prototype, {
36201 get: function get() {
36202 console.warn('THREE.BufferAttribute: .length has been deprecated. Use .count instead.');
36203 return this.array.length;
36207 get: function get() {
36208 console.warn('THREE.BufferAttribute: .dynamic has been deprecated. Use .usage instead.');
36209 return this.usage === DynamicDrawUsage;
36211 set: function set()
36214 console.warn('THREE.BufferAttribute: .dynamic has been deprecated. Use .usage instead.');
36215 this.setUsage(DynamicDrawUsage);
36219 Object.assign(BufferAttribute.prototype, {
36220 setDynamic: function setDynamic(value) {
36221 console.warn('THREE.BufferAttribute: .setDynamic() has been deprecated. Use .setUsage() instead.');
36222 this.setUsage(value === true ? DynamicDrawUsage : StaticDrawUsage);
36225 copyIndicesArray: function copyIndicesArray()
36228 console.error('THREE.BufferAttribute: .copyIndicesArray() has been removed.');
36230 setArray: function setArray()
36233 console.error('THREE.BufferAttribute: .setArray has been removed. Use BufferGeometry .setAttribute to replace/resize attribute buffers');
36236 Object.assign(BufferGeometry.prototype, {
36237 addIndex: function addIndex(index) {
36238 console.warn('THREE.BufferGeometry: .addIndex() has been renamed to .setIndex().');
36239 this.setIndex(index);
36241 addAttribute: function addAttribute(name, attribute) {
36242 console.warn('THREE.BufferGeometry: .addAttribute() has been renamed to .setAttribute().');
36244 if (!(attribute && attribute.isBufferAttribute) && !(attribute && attribute.isInterleavedBufferAttribute)) {
36245 console.warn('THREE.BufferGeometry: .addAttribute() now expects ( name, attribute ).');
36246 return this.setAttribute(name, new BufferAttribute(arguments[1], arguments[2]));
36249 if (name === 'index') {
36250 console.warn('THREE.BufferGeometry.addAttribute: Use .setIndex() for index attribute.');
36251 this.setIndex(attribute);
36255 return this.setAttribute(name, attribute);
36257 addDrawCall: function addDrawCall(start, count, indexOffset) {
36258 if (indexOffset !== undefined) {
36259 console.warn('THREE.BufferGeometry: .addDrawCall() no longer supports indexOffset.');
36262 console.warn('THREE.BufferGeometry: .addDrawCall() is now .addGroup().');
36263 this.addGroup(start, count);
36265 clearDrawCalls: function clearDrawCalls() {
36266 console.warn('THREE.BufferGeometry: .clearDrawCalls() is now .clearGroups().');
36267 this.clearGroups();
36269 computeOffsets: function computeOffsets() {
36270 console.warn('THREE.BufferGeometry: .computeOffsets() has been removed.');
36272 removeAttribute: function removeAttribute(name) {
36273 console.warn('THREE.BufferGeometry: .removeAttribute() has been renamed to .deleteAttribute().');
36274 return this.deleteAttribute(name);
36276 applyMatrix: function applyMatrix(matrix) {
36277 console.warn('THREE.BufferGeometry: .applyMatrix() has been renamed to .applyMatrix4().');
36278 return this.applyMatrix4(matrix);
36281 Object.defineProperties(BufferGeometry.prototype, {
36283 get: function get() {
36284 console.error('THREE.BufferGeometry: .drawcalls has been renamed to .groups.');
36285 return this.groups;
36289 get: function get() {
36290 console.warn('THREE.BufferGeometry: .offsets has been renamed to .groups.');
36291 return this.groups;
36295 Object.defineProperties(InstancedBufferGeometry.prototype, {
36296 maxInstancedCount: {
36297 get: function get() {
36298 console.warn('THREE.InstancedBufferGeometry: .maxInstancedCount has been renamed to .instanceCount.');
36299 return this.instanceCount;
36301 set: function set(value) {
36302 console.warn('THREE.InstancedBufferGeometry: .maxInstancedCount has been renamed to .instanceCount.');
36303 this.instanceCount = value;
36307 Object.defineProperties(Raycaster.prototype, {
36309 get: function get() {
36310 console.warn('THREE.Raycaster: .linePrecision has been deprecated. Use .params.Line.threshold instead.');
36311 return this.params.Line.threshold;
36313 set: function set(value) {
36314 console.warn('THREE.Raycaster: .linePrecision has been deprecated. Use .params.Line.threshold instead.');
36315 this.params.Line.threshold = value;
36319 Object.defineProperties(InterleavedBuffer.prototype, {
36321 get: function get() {
36322 console.warn('THREE.InterleavedBuffer: .length has been deprecated. Use .usage instead.');
36323 return this.usage === DynamicDrawUsage;
36325 set: function set(value) {
36326 console.warn('THREE.InterleavedBuffer: .length has been deprecated. Use .usage instead.');
36327 this.setUsage(value);
36331 Object.assign(InterleavedBuffer.prototype, {
36332 setDynamic: function setDynamic(value) {
36333 console.warn('THREE.InterleavedBuffer: .setDynamic() has been deprecated. Use .setUsage() instead.');
36334 this.setUsage(value === true ? DynamicDrawUsage : StaticDrawUsage);
36337 setArray: function setArray()
36340 console.error('THREE.InterleavedBuffer: .setArray has been removed. Use BufferGeometry .setAttribute to replace/resize attribute buffers');
36344 Object.assign(ExtrudeGeometry.prototype, {
36345 getArrays: function getArrays() {
36346 console.error('THREE.ExtrudeGeometry: .getArrays() has been removed.');
36348 addShapeList: function addShapeList() {
36349 console.error('THREE.ExtrudeGeometry: .addShapeList() has been removed.');
36351 addShape: function addShape() {
36352 console.error('THREE.ExtrudeGeometry: .addShape() has been removed.');
36356 Object.assign(Scene.prototype, {
36357 dispose: function dispose() {
36358 console.error('THREE.Scene: .dispose() has been removed.');
36362 Object.defineProperties(Uniform.prototype, {
36364 set: function set() {
36365 console.warn('THREE.Uniform: .dynamic has been removed. Use object.onBeforeRender() instead.');
36369 value: function value() {
36370 console.warn('THREE.Uniform: .onUpdate() has been removed. Use object.onBeforeRender() instead.');
36376 Object.defineProperties(Material.prototype, {
36378 get: function get() {
36379 console.warn('THREE.Material: .wrapAround has been removed.');
36381 set: function set() {
36382 console.warn('THREE.Material: .wrapAround has been removed.');
36386 get: function get() {
36387 console.warn('THREE.Material: .overdraw has been removed.');
36389 set: function set() {
36390 console.warn('THREE.Material: .overdraw has been removed.');
36394 get: function get() {
36395 console.warn('THREE.Material: .wrapRGB has been removed.');
36396 return new Color();
36400 get: function get() {
36401 console.error('THREE.' + this.type + ': .shading has been removed. Use the boolean .flatShading instead.');
36403 set: function set(value) {
36404 console.warn('THREE.' + this.type + ': .shading has been removed. Use the boolean .flatShading instead.');
36405 this.flatShading = value === FlatShading;
36409 get: function get() {
36410 console.warn('THREE.' + this.type + ': .stencilMask has been removed. Use .stencilFuncMask instead.');
36411 return this.stencilFuncMask;
36413 set: function set(value) {
36414 console.warn('THREE.' + this.type + ': .stencilMask has been removed. Use .stencilFuncMask instead.');
36415 this.stencilFuncMask = value;
36419 Object.defineProperties(MeshPhongMaterial.prototype, {
36421 get: function get() {
36422 console.warn('THREE.MeshPhongMaterial: .metal has been removed. Use THREE.MeshStandardMaterial instead.');
36425 set: function set() {
36426 console.warn('THREE.MeshPhongMaterial: .metal has been removed. Use THREE.MeshStandardMaterial instead');
36430 Object.defineProperties(MeshPhysicalMaterial.prototype, {
36432 get: function get() {
36433 console.warn('THREE.MeshPhysicalMaterial: .transparency has been renamed to .transmission.');
36434 return this.transmission;
36436 set: function set(value) {
36437 console.warn('THREE.MeshPhysicalMaterial: .transparency has been renamed to .transmission.');
36438 this.transmission = value;
36442 Object.defineProperties(ShaderMaterial.prototype, {
36444 get: function get() {
36445 console.warn('THREE.ShaderMaterial: .derivatives has been moved to .extensions.derivatives.');
36446 return this.extensions.derivatives;
36448 set: function set(value) {
36449 console.warn('THREE. ShaderMaterial: .derivatives has been moved to .extensions.derivatives.');
36450 this.extensions.derivatives = value;
36455 Object.assign(WebGLRenderer.prototype, {
36456 clearTarget: function clearTarget(renderTarget, color, depth, stencil) {
36457 console.warn('THREE.WebGLRenderer: .clearTarget() has been deprecated. Use .setRenderTarget() and .clear() instead.');
36458 this.setRenderTarget(renderTarget);
36459 this.clear(color, depth, stencil);
36461 animate: function animate(callback) {
36462 console.warn('THREE.WebGLRenderer: .animate() is now .setAnimationLoop().');
36463 this.setAnimationLoop(callback);
36465 getCurrentRenderTarget: function getCurrentRenderTarget() {
36466 console.warn('THREE.WebGLRenderer: .getCurrentRenderTarget() is now .getRenderTarget().');
36467 return this.getRenderTarget();
36469 getMaxAnisotropy: function getMaxAnisotropy() {
36470 console.warn('THREE.WebGLRenderer: .getMaxAnisotropy() is now .capabilities.getMaxAnisotropy().');
36471 return this.capabilities.getMaxAnisotropy();
36473 getPrecision: function getPrecision() {
36474 console.warn('THREE.WebGLRenderer: .getPrecision() is now .capabilities.precision.');
36475 return this.capabilities.precision;
36477 resetGLState: function resetGLState() {
36478 console.warn('THREE.WebGLRenderer: .resetGLState() is now .state.reset().');
36479 return this.state.reset();
36481 supportsFloatTextures: function supportsFloatTextures() {
36482 console.warn('THREE.WebGLRenderer: .supportsFloatTextures() is now .extensions.get( \'OES_texture_float\' ).');
36483 return this.extensions.get('OES_texture_float');
36485 supportsHalfFloatTextures: function supportsHalfFloatTextures() {
36486 console.warn('THREE.WebGLRenderer: .supportsHalfFloatTextures() is now .extensions.get( \'OES_texture_half_float\' ).');
36487 return this.extensions.get('OES_texture_half_float');
36489 supportsStandardDerivatives: function supportsStandardDerivatives() {
36490 console.warn('THREE.WebGLRenderer: .supportsStandardDerivatives() is now .extensions.get( \'OES_standard_derivatives\' ).');
36491 return this.extensions.get('OES_standard_derivatives');
36493 supportsCompressedTextureS3TC: function supportsCompressedTextureS3TC() {
36494 console.warn('THREE.WebGLRenderer: .supportsCompressedTextureS3TC() is now .extensions.get( \'WEBGL_compressed_texture_s3tc\' ).');
36495 return this.extensions.get('WEBGL_compressed_texture_s3tc');
36497 supportsCompressedTexturePVRTC: function supportsCompressedTexturePVRTC() {
36498 console.warn('THREE.WebGLRenderer: .supportsCompressedTexturePVRTC() is now .extensions.get( \'WEBGL_compressed_texture_pvrtc\' ).');
36499 return this.extensions.get('WEBGL_compressed_texture_pvrtc');
36501 supportsBlendMinMax: function supportsBlendMinMax() {
36502 console.warn('THREE.WebGLRenderer: .supportsBlendMinMax() is now .extensions.get( \'EXT_blend_minmax\' ).');
36503 return this.extensions.get('EXT_blend_minmax');
36505 supportsVertexTextures: function supportsVertexTextures() {
36506 console.warn('THREE.WebGLRenderer: .supportsVertexTextures() is now .capabilities.vertexTextures.');
36507 return this.capabilities.vertexTextures;
36509 supportsInstancedArrays: function supportsInstancedArrays() {
36510 console.warn('THREE.WebGLRenderer: .supportsInstancedArrays() is now .extensions.get( \'ANGLE_instanced_arrays\' ).');
36511 return this.extensions.get('ANGLE_instanced_arrays');
36513 enableScissorTest: function enableScissorTest(boolean) {
36514 console.warn('THREE.WebGLRenderer: .enableScissorTest() is now .setScissorTest().');
36515 this.setScissorTest(boolean);
36517 initMaterial: function initMaterial() {
36518 console.warn('THREE.WebGLRenderer: .initMaterial() has been removed.');
36520 addPrePlugin: function addPrePlugin() {
36521 console.warn('THREE.WebGLRenderer: .addPrePlugin() has been removed.');
36523 addPostPlugin: function addPostPlugin() {
36524 console.warn('THREE.WebGLRenderer: .addPostPlugin() has been removed.');
36526 updateShadowMap: function updateShadowMap() {
36527 console.warn('THREE.WebGLRenderer: .updateShadowMap() has been removed.');
36529 setFaceCulling: function setFaceCulling() {
36530 console.warn('THREE.WebGLRenderer: .setFaceCulling() has been removed.');
36532 allocTextureUnit: function allocTextureUnit() {
36533 console.warn('THREE.WebGLRenderer: .allocTextureUnit() has been removed.');
36535 setTexture: function setTexture() {
36536 console.warn('THREE.WebGLRenderer: .setTexture() has been removed.');
36538 setTexture2D: function setTexture2D() {
36539 console.warn('THREE.WebGLRenderer: .setTexture2D() has been removed.');
36541 setTextureCube: function setTextureCube() {
36542 console.warn('THREE.WebGLRenderer: .setTextureCube() has been removed.');
36544 getActiveMipMapLevel: function getActiveMipMapLevel() {
36545 console.warn('THREE.WebGLRenderer: .getActiveMipMapLevel() is now .getActiveMipmapLevel().');
36546 return this.getActiveMipmapLevel();
36549 Object.defineProperties(WebGLRenderer.prototype, {
36550 shadowMapEnabled: {
36551 get: function get() {
36552 return this.shadowMap.enabled;
36554 set: function set(value) {
36555 console.warn('THREE.WebGLRenderer: .shadowMapEnabled is now .shadowMap.enabled.');
36556 this.shadowMap.enabled = value;
36560 get: function get() {
36561 return this.shadowMap.type;
36563 set: function set(value) {
36564 console.warn('THREE.WebGLRenderer: .shadowMapType is now .shadowMap.type.');
36565 this.shadowMap.type = value;
36568 shadowMapCullFace: {
36569 get: function get() {
36570 console.warn('THREE.WebGLRenderer: .shadowMapCullFace has been removed. Set Material.shadowSide instead.');
36573 set: function set()
36576 console.warn('THREE.WebGLRenderer: .shadowMapCullFace has been removed. Set Material.shadowSide instead.');
36580 get: function get() {
36581 console.warn('THREE.WebGLRenderer: .context has been removed. Use .getContext() instead.');
36582 return this.getContext();
36586 get: function get() {
36587 console.warn('THREE.WebGLRenderer: .vr has been renamed to .xr');
36592 get: function get() {
36593 console.warn('THREE.WebGLRenderer: .gammaInput has been removed. Set the encoding for textures via Texture.encoding instead.');
36596 set: function set() {
36597 console.warn('THREE.WebGLRenderer: .gammaInput has been removed. Set the encoding for textures via Texture.encoding instead.');
36601 get: function get() {
36602 console.warn('THREE.WebGLRenderer: .gammaOutput has been removed. Set WebGLRenderer.outputEncoding instead.');
36605 set: function set(value) {
36606 console.warn('THREE.WebGLRenderer: .gammaOutput has been removed. Set WebGLRenderer.outputEncoding instead.');
36607 this.outputEncoding = value === true ? sRGBEncoding : LinearEncoding;
36610 toneMappingWhitePoint: {
36611 get: function get() {
36612 console.warn('THREE.WebGLRenderer: .toneMappingWhitePoint has been removed.');
36615 set: function set() {
36616 console.warn('THREE.WebGLRenderer: .toneMappingWhitePoint has been removed.');
36620 Object.defineProperties(WebGLShadowMap.prototype, {
36622 get: function get() {
36623 console.warn('THREE.WebGLRenderer: .shadowMap.cullFace has been removed. Set Material.shadowSide instead.');
36626 set: function set()
36629 console.warn('THREE.WebGLRenderer: .shadowMap.cullFace has been removed. Set Material.shadowSide instead.');
36632 renderReverseSided: {
36633 get: function get() {
36634 console.warn('THREE.WebGLRenderer: .shadowMap.renderReverseSided has been removed. Set Material.shadowSide instead.');
36637 set: function set() {
36638 console.warn('THREE.WebGLRenderer: .shadowMap.renderReverseSided has been removed. Set Material.shadowSide instead.');
36641 renderSingleSided: {
36642 get: function get() {
36643 console.warn('THREE.WebGLRenderer: .shadowMap.renderSingleSided has been removed. Set Material.shadowSide instead.');
36646 set: function set() {
36647 console.warn('THREE.WebGLRenderer: .shadowMap.renderSingleSided has been removed. Set Material.shadowSide instead.');
36651 function WebGLRenderTargetCube(width, height, options) {
36652 console.warn('THREE.WebGLRenderTargetCube( width, height, options ) is now WebGLCubeRenderTarget( size, options ).');
36653 return new WebGLCubeRenderTarget(width, options);
36656 Object.defineProperties(WebGLRenderTarget.prototype, {
36658 get: function get() {
36659 console.warn('THREE.WebGLRenderTarget: .wrapS is now .texture.wrapS.');
36660 return this.texture.wrapS;
36662 set: function set(value) {
36663 console.warn('THREE.WebGLRenderTarget: .wrapS is now .texture.wrapS.');
36664 this.texture.wrapS = value;
36668 get: function get() {
36669 console.warn('THREE.WebGLRenderTarget: .wrapT is now .texture.wrapT.');
36670 return this.texture.wrapT;
36672 set: function set(value) {
36673 console.warn('THREE.WebGLRenderTarget: .wrapT is now .texture.wrapT.');
36674 this.texture.wrapT = value;
36678 get: function get() {
36679 console.warn('THREE.WebGLRenderTarget: .magFilter is now .texture.magFilter.');
36680 return this.texture.magFilter;
36682 set: function set(value) {
36683 console.warn('THREE.WebGLRenderTarget: .magFilter is now .texture.magFilter.');
36684 this.texture.magFilter = value;
36688 get: function get() {
36689 console.warn('THREE.WebGLRenderTarget: .minFilter is now .texture.minFilter.');
36690 return this.texture.minFilter;
36692 set: function set(value) {
36693 console.warn('THREE.WebGLRenderTarget: .minFilter is now .texture.minFilter.');
36694 this.texture.minFilter = value;
36698 get: function get() {
36699 console.warn('THREE.WebGLRenderTarget: .anisotropy is now .texture.anisotropy.');
36700 return this.texture.anisotropy;
36702 set: function set(value) {
36703 console.warn('THREE.WebGLRenderTarget: .anisotropy is now .texture.anisotropy.');
36704 this.texture.anisotropy = value;
36708 get: function get() {
36709 console.warn('THREE.WebGLRenderTarget: .offset is now .texture.offset.');
36710 return this.texture.offset;
36712 set: function set(value) {
36713 console.warn('THREE.WebGLRenderTarget: .offset is now .texture.offset.');
36714 this.texture.offset = value;
36718 get: function get() {
36719 console.warn('THREE.WebGLRenderTarget: .repeat is now .texture.repeat.');
36720 return this.texture.repeat;
36722 set: function set(value) {
36723 console.warn('THREE.WebGLRenderTarget: .repeat is now .texture.repeat.');
36724 this.texture.repeat = value;
36728 get: function get() {
36729 console.warn('THREE.WebGLRenderTarget: .format is now .texture.format.');
36730 return this.texture.format;
36732 set: function set(value) {
36733 console.warn('THREE.WebGLRenderTarget: .format is now .texture.format.');
36734 this.texture.format = value;
36738 get: function get() {
36739 console.warn('THREE.WebGLRenderTarget: .type is now .texture.type.');
36740 return this.texture.type;
36742 set: function set(value) {
36743 console.warn('THREE.WebGLRenderTarget: .type is now .texture.type.');
36744 this.texture.type = value;
36748 get: function get() {
36749 console.warn('THREE.WebGLRenderTarget: .generateMipmaps is now .texture.generateMipmaps.');
36750 return this.texture.generateMipmaps;
36752 set: function set(value) {
36753 console.warn('THREE.WebGLRenderTarget: .generateMipmaps is now .texture.generateMipmaps.');
36754 this.texture.generateMipmaps = value;
36759 Object.defineProperties(Audio.prototype, {
36761 value: function value(file) {
36762 console.warn('THREE.Audio: .load has been deprecated. Use THREE.AudioLoader instead.');
36764 var audioLoader = new AudioLoader();
36765 audioLoader.load(file, function (buffer) {
36766 scope.setBuffer(buffer);
36772 set: function set() {
36773 console.warn('THREE.Audio: .startTime is now .play( delay ).');
36778 AudioAnalyser.prototype.getData = function () {
36779 console.warn('THREE.AudioAnalyser: .getData() is now .getFrequencyData().');
36780 return this.getFrequencyData();
36784 CubeCamera.prototype.updateCubeMap = function (renderer, scene) {
36785 console.warn('THREE.CubeCamera: .updateCubeMap() is now .update().');
36786 return this.update(renderer, scene);
36789 CubeCamera.prototype.clear = function (renderer, color, depth, stencil) {
36790 console.warn('THREE.CubeCamera: .clear() is now .renderTarget.clear().');
36791 return this.renderTarget.clear(renderer, color, depth, stencil);
36795 var GeometryUtils = {
36796 merge: function merge(geometry1, geometry2, materialIndexOffset) {
36797 console.warn('THREE.GeometryUtils: .merge() has been moved to Geometry. Use geometry.merge( geometry2, matrix, materialIndexOffset ) instead.');
36800 if (geometry2.isMesh) {
36801 geometry2.matrixAutoUpdate && geometry2.updateMatrix();
36802 matrix = geometry2.matrix;
36803 geometry2 = geometry2.geometry;
36806 geometry1.merge(geometry2, matrix, materialIndexOffset);
36808 center: function center(geometry) {
36809 console.warn('THREE.GeometryUtils: .center() has been moved to Geometry. Use geometry.center() instead.');
36810 return geometry.center();
36813 ImageUtils.crossOrigin = undefined;
36815 ImageUtils.loadTexture = function (url, mapping, onLoad, onError) {
36816 console.warn('THREE.ImageUtils.loadTexture has been deprecated. Use THREE.TextureLoader() instead.');
36817 var loader = new TextureLoader();
36818 loader.setCrossOrigin(this.crossOrigin);
36819 var texture = loader.load(url, onLoad, undefined, onError);
36820 if (mapping) texture.mapping = mapping;
36824 ImageUtils.loadTextureCube = function (urls, mapping, onLoad, onError) {
36825 console.warn('THREE.ImageUtils.loadTextureCube has been deprecated. Use THREE.CubeTextureLoader() instead.');
36826 var loader = new CubeTextureLoader();
36827 loader.setCrossOrigin(this.crossOrigin);
36828 var texture = loader.load(urls, onLoad, undefined, onError);
36829 if (mapping) texture.mapping = mapping;
36833 ImageUtils.loadCompressedTexture = function () {
36834 console.error('THREE.ImageUtils.loadCompressedTexture has been removed. Use THREE.DDSLoader instead.');
36837 ImageUtils.loadCompressedTextureCube = function () {
36838 console.error('THREE.ImageUtils.loadCompressedTextureCube has been removed. Use THREE.DDSLoader instead.');
36842 function CanvasRenderer() {
36843 console.error('THREE.CanvasRenderer has been removed');
36846 function JSONLoader() {
36847 console.error('THREE.JSONLoader has been removed.');
36851 createMultiMaterialObject: function createMultiMaterialObject()
36852 /* geometry, materials */
36854 console.error('THREE.SceneUtils has been moved to /examples/jsm/utils/SceneUtils.js');
36856 detach: function detach()
36857 /* child, parent, scene */
36859 console.error('THREE.SceneUtils has been moved to /examples/jsm/utils/SceneUtils.js');
36861 attach: function attach()
36862 /* child, scene, parent */
36864 console.error('THREE.SceneUtils has been moved to /examples/jsm/utils/SceneUtils.js');
36868 function LensFlare() {
36869 console.error('THREE.LensFlare has been moved to /examples/jsm/objects/Lensflare.js');
36872 if (typeof __THREE_DEVTOOLS__ !== 'undefined') {
36873 /* eslint-disable no-undef */
36874 __THREE_DEVTOOLS__.dispatchEvent(new CustomEvent('register', {
36879 /* eslint-enable no-undef */
36883 if (typeof window !== 'undefined') {
36884 if (window.__THREE__) {
36885 console.warn('WARNING: Multiple instances of Three.js being imported.');
36887 window.__THREE__ = REVISION;
36891 exports.ACESFilmicToneMapping = ACESFilmicToneMapping;
36892 exports.AddEquation = AddEquation;
36893 exports.AddOperation = AddOperation;
36894 exports.AdditiveAnimationBlendMode = AdditiveAnimationBlendMode;
36895 exports.AdditiveBlending = AdditiveBlending;
36896 exports.AlphaFormat = AlphaFormat;
36897 exports.AlwaysDepth = AlwaysDepth;
36898 exports.AlwaysStencilFunc = AlwaysStencilFunc;
36899 exports.AmbientLight = AmbientLight;
36900 exports.AmbientLightProbe = AmbientLightProbe;
36901 exports.AnimationClip = AnimationClip;
36902 exports.AnimationLoader = AnimationLoader;
36903 exports.AnimationMixer = AnimationMixer;
36904 exports.AnimationObjectGroup = AnimationObjectGroup;
36905 exports.AnimationUtils = AnimationUtils;
36906 exports.ArcCurve = ArcCurve;
36907 exports.ArrayCamera = ArrayCamera;
36908 exports.ArrowHelper = ArrowHelper;
36909 exports.Audio = Audio;
36910 exports.AudioAnalyser = AudioAnalyser;
36911 exports.AudioContext = AudioContext;
36912 exports.AudioListener = AudioListener;
36913 exports.AudioLoader = AudioLoader;
36914 exports.AxesHelper = AxesHelper;
36915 exports.AxisHelper = AxisHelper;
36916 exports.BackSide = BackSide;
36917 exports.BasicDepthPacking = BasicDepthPacking;
36918 exports.BasicShadowMap = BasicShadowMap;
36919 exports.BinaryTextureLoader = BinaryTextureLoader;
36920 exports.Bone = Bone;
36921 exports.BooleanKeyframeTrack = BooleanKeyframeTrack;
36922 exports.BoundingBoxHelper = BoundingBoxHelper;
36923 exports.Box2 = Box2;
36924 exports.Box3 = Box3;
36925 exports.Box3Helper = Box3Helper;
36926 exports.BoxBufferGeometry = BoxGeometry;
36927 exports.BoxGeometry = BoxGeometry;
36928 exports.BoxHelper = BoxHelper;
36929 exports.BufferAttribute = BufferAttribute;
36930 exports.BufferGeometry = BufferGeometry;
36931 exports.BufferGeometryLoader = BufferGeometryLoader;
36932 exports.ByteType = ByteType;
36933 exports.Cache = Cache;
36934 exports.Camera = Camera;
36935 exports.CameraHelper = CameraHelper;
36936 exports.CanvasRenderer = CanvasRenderer;
36937 exports.CanvasTexture = CanvasTexture;
36938 exports.CatmullRomCurve3 = CatmullRomCurve3;
36939 exports.CineonToneMapping = CineonToneMapping;
36940 exports.CircleBufferGeometry = CircleGeometry;
36941 exports.CircleGeometry = CircleGeometry;
36942 exports.ClampToEdgeWrapping = ClampToEdgeWrapping;
36943 exports.Clock = Clock;
36944 exports.ClosedSplineCurve3 = ClosedSplineCurve3;
36945 exports.Color = Color;
36946 exports.ColorKeyframeTrack = ColorKeyframeTrack;
36947 exports.CompressedTexture = CompressedTexture;
36948 exports.CompressedTextureLoader = CompressedTextureLoader;
36949 exports.ConeBufferGeometry = ConeGeometry;
36950 exports.ConeGeometry = ConeGeometry;
36951 exports.CubeCamera = CubeCamera;
36952 exports.CubeReflectionMapping = CubeReflectionMapping;
36953 exports.CubeRefractionMapping = CubeRefractionMapping;
36954 exports.CubeTexture = CubeTexture;
36955 exports.CubeTextureLoader = CubeTextureLoader;
36956 exports.CubeUVReflectionMapping = CubeUVReflectionMapping;
36957 exports.CubeUVRefractionMapping = CubeUVRefractionMapping;
36958 exports.CubicBezierCurve = CubicBezierCurve;
36959 exports.CubicBezierCurve3 = CubicBezierCurve3;
36960 exports.CubicInterpolant = CubicInterpolant;
36961 exports.CullFaceBack = CullFaceBack;
36962 exports.CullFaceFront = CullFaceFront;
36963 exports.CullFaceFrontBack = CullFaceFrontBack;
36964 exports.CullFaceNone = CullFaceNone;
36965 exports.Curve = Curve;
36966 exports.CurvePath = CurvePath;
36967 exports.CustomBlending = CustomBlending;
36968 exports.CustomToneMapping = CustomToneMapping;
36969 exports.CylinderBufferGeometry = CylinderGeometry;
36970 exports.CylinderGeometry = CylinderGeometry;
36971 exports.Cylindrical = Cylindrical;
36972 exports.DataTexture = DataTexture;
36973 exports.DataTexture2DArray = DataTexture2DArray;
36974 exports.DataTexture3D = DataTexture3D;
36975 exports.DataTextureLoader = DataTextureLoader;
36976 exports.DataUtils = DataUtils;
36977 exports.DecrementStencilOp = DecrementStencilOp;
36978 exports.DecrementWrapStencilOp = DecrementWrapStencilOp;
36979 exports.DefaultLoadingManager = DefaultLoadingManager;
36980 exports.DepthFormat = DepthFormat;
36981 exports.DepthStencilFormat = DepthStencilFormat;
36982 exports.DepthTexture = DepthTexture;
36983 exports.DirectionalLight = DirectionalLight;
36984 exports.DirectionalLightHelper = DirectionalLightHelper;
36985 exports.DiscreteInterpolant = DiscreteInterpolant;
36986 exports.DodecahedronBufferGeometry = DodecahedronGeometry;
36987 exports.DodecahedronGeometry = DodecahedronGeometry;
36988 exports.DoubleSide = DoubleSide;
36989 exports.DstAlphaFactor = DstAlphaFactor;
36990 exports.DstColorFactor = DstColorFactor;
36991 exports.DynamicBufferAttribute = DynamicBufferAttribute;
36992 exports.DynamicCopyUsage = DynamicCopyUsage;
36993 exports.DynamicDrawUsage = DynamicDrawUsage;
36994 exports.DynamicReadUsage = DynamicReadUsage;
36995 exports.EdgesGeometry = EdgesGeometry;
36996 exports.EdgesHelper = EdgesHelper;
36997 exports.EllipseCurve = EllipseCurve;
36998 exports.EqualDepth = EqualDepth;
36999 exports.EqualStencilFunc = EqualStencilFunc;
37000 exports.EquirectangularReflectionMapping = EquirectangularReflectionMapping;
37001 exports.EquirectangularRefractionMapping = EquirectangularRefractionMapping;
37002 exports.Euler = Euler;
37003 exports.EventDispatcher = EventDispatcher;
37004 exports.ExtrudeBufferGeometry = ExtrudeGeometry;
37005 exports.ExtrudeGeometry = ExtrudeGeometry;
37006 exports.Face3 = Face3;
37007 exports.Face4 = Face4;
37008 exports.FaceColors = FaceColors;
37009 exports.FileLoader = FileLoader;
37010 exports.FlatShading = FlatShading;
37011 exports.Float16BufferAttribute = Float16BufferAttribute;
37012 exports.Float32Attribute = Float32Attribute;
37013 exports.Float32BufferAttribute = Float32BufferAttribute;
37014 exports.Float64Attribute = Float64Attribute;
37015 exports.Float64BufferAttribute = Float64BufferAttribute;
37016 exports.FloatType = FloatType;
37018 exports.FogExp2 = FogExp2;
37019 exports.Font = Font;
37020 exports.FontLoader = FontLoader;
37021 exports.FrontSide = FrontSide;
37022 exports.Frustum = Frustum;
37023 exports.GLBufferAttribute = GLBufferAttribute;
37024 exports.GLSL1 = GLSL1;
37025 exports.GLSL3 = GLSL3;
37026 exports.GammaEncoding = GammaEncoding;
37027 exports.GeometryUtils = GeometryUtils;
37028 exports.GreaterDepth = GreaterDepth;
37029 exports.GreaterEqualDepth = GreaterEqualDepth;
37030 exports.GreaterEqualStencilFunc = GreaterEqualStencilFunc;
37031 exports.GreaterStencilFunc = GreaterStencilFunc;
37032 exports.GridHelper = GridHelper;
37033 exports.Group = Group;
37034 exports.HalfFloatType = HalfFloatType;
37035 exports.HemisphereLight = HemisphereLight;
37036 exports.HemisphereLightHelper = HemisphereLightHelper;
37037 exports.HemisphereLightProbe = HemisphereLightProbe;
37038 exports.IcosahedronBufferGeometry = IcosahedronGeometry;
37039 exports.IcosahedronGeometry = IcosahedronGeometry;
37040 exports.ImageBitmapLoader = ImageBitmapLoader;
37041 exports.ImageLoader = ImageLoader;
37042 exports.ImageUtils = ImageUtils;
37043 exports.ImmediateRenderObject = ImmediateRenderObject;
37044 exports.IncrementStencilOp = IncrementStencilOp;
37045 exports.IncrementWrapStencilOp = IncrementWrapStencilOp;
37046 exports.InstancedBufferAttribute = InstancedBufferAttribute;
37047 exports.InstancedBufferGeometry = InstancedBufferGeometry;
37048 exports.InstancedInterleavedBuffer = InstancedInterleavedBuffer;
37049 exports.InstancedMesh = InstancedMesh;
37050 exports.Int16Attribute = Int16Attribute;
37051 exports.Int16BufferAttribute = Int16BufferAttribute;
37052 exports.Int32Attribute = Int32Attribute;
37053 exports.Int32BufferAttribute = Int32BufferAttribute;
37054 exports.Int8Attribute = Int8Attribute;
37055 exports.Int8BufferAttribute = Int8BufferAttribute;
37056 exports.IntType = IntType;
37057 exports.InterleavedBuffer = InterleavedBuffer;
37058 exports.InterleavedBufferAttribute = InterleavedBufferAttribute;
37059 exports.Interpolant = Interpolant;
37060 exports.InterpolateDiscrete = InterpolateDiscrete;
37061 exports.InterpolateLinear = InterpolateLinear;
37062 exports.InterpolateSmooth = InterpolateSmooth;
37063 exports.InvertStencilOp = InvertStencilOp;
37064 exports.JSONLoader = JSONLoader;
37065 exports.KeepStencilOp = KeepStencilOp;
37066 exports.KeyframeTrack = KeyframeTrack;
37068 exports.LatheBufferGeometry = LatheGeometry;
37069 exports.LatheGeometry = LatheGeometry;
37070 exports.Layers = Layers;
37071 exports.LensFlare = LensFlare;
37072 exports.LessDepth = LessDepth;
37073 exports.LessEqualDepth = LessEqualDepth;
37074 exports.LessEqualStencilFunc = LessEqualStencilFunc;
37075 exports.LessStencilFunc = LessStencilFunc;
37076 exports.Light = Light;
37077 exports.LightProbe = LightProbe;
37078 exports.Line = Line;
37079 exports.Line3 = Line3;
37080 exports.LineBasicMaterial = LineBasicMaterial;
37081 exports.LineCurve = LineCurve;
37082 exports.LineCurve3 = LineCurve3;
37083 exports.LineDashedMaterial = LineDashedMaterial;
37084 exports.LineLoop = LineLoop;
37085 exports.LinePieces = LinePieces;
37086 exports.LineSegments = LineSegments;
37087 exports.LineStrip = LineStrip;
37088 exports.LinearEncoding = LinearEncoding;
37089 exports.LinearFilter = LinearFilter;
37090 exports.LinearInterpolant = LinearInterpolant;
37091 exports.LinearMipMapLinearFilter = LinearMipMapLinearFilter;
37092 exports.LinearMipMapNearestFilter = LinearMipMapNearestFilter;
37093 exports.LinearMipmapLinearFilter = LinearMipmapLinearFilter;
37094 exports.LinearMipmapNearestFilter = LinearMipmapNearestFilter;
37095 exports.LinearToneMapping = LinearToneMapping;
37096 exports.Loader = Loader;
37097 exports.LoaderUtils = LoaderUtils;
37098 exports.LoadingManager = LoadingManager;
37099 exports.LogLuvEncoding = LogLuvEncoding;
37100 exports.LoopOnce = LoopOnce;
37101 exports.LoopPingPong = LoopPingPong;
37102 exports.LoopRepeat = LoopRepeat;
37103 exports.LuminanceAlphaFormat = LuminanceAlphaFormat;
37104 exports.LuminanceFormat = LuminanceFormat;
37105 exports.MOUSE = MOUSE;
37106 exports.Material = Material;
37107 exports.MaterialLoader = MaterialLoader;
37108 exports.Math = MathUtils;
37109 exports.MathUtils = MathUtils;
37110 exports.Matrix3 = Matrix3;
37111 exports.Matrix4 = Matrix4;
37112 exports.MaxEquation = MaxEquation;
37113 exports.Mesh = Mesh;
37114 exports.MeshBasicMaterial = MeshBasicMaterial;
37115 exports.MeshDepthMaterial = MeshDepthMaterial;
37116 exports.MeshDistanceMaterial = MeshDistanceMaterial;
37117 exports.MeshFaceMaterial = MeshFaceMaterial;
37118 exports.MeshLambertMaterial = MeshLambertMaterial;
37119 exports.MeshMatcapMaterial = MeshMatcapMaterial;
37120 exports.MeshNormalMaterial = MeshNormalMaterial;
37121 exports.MeshPhongMaterial = MeshPhongMaterial;
37122 exports.MeshPhysicalMaterial = MeshPhysicalMaterial;
37123 exports.MeshStandardMaterial = MeshStandardMaterial;
37124 exports.MeshToonMaterial = MeshToonMaterial;
37125 exports.MinEquation = MinEquation;
37126 exports.MirroredRepeatWrapping = MirroredRepeatWrapping;
37127 exports.MixOperation = MixOperation;
37128 exports.MultiMaterial = MultiMaterial;
37129 exports.MultiplyBlending = MultiplyBlending;
37130 exports.MultiplyOperation = MultiplyOperation;
37131 exports.NearestFilter = NearestFilter;
37132 exports.NearestMipMapLinearFilter = NearestMipMapLinearFilter;
37133 exports.NearestMipMapNearestFilter = NearestMipMapNearestFilter;
37134 exports.NearestMipmapLinearFilter = NearestMipmapLinearFilter;
37135 exports.NearestMipmapNearestFilter = NearestMipmapNearestFilter;
37136 exports.NeverDepth = NeverDepth;
37137 exports.NeverStencilFunc = NeverStencilFunc;
37138 exports.NoBlending = NoBlending;
37139 exports.NoColors = NoColors;
37140 exports.NoToneMapping = NoToneMapping;
37141 exports.NormalAnimationBlendMode = NormalAnimationBlendMode;
37142 exports.NormalBlending = NormalBlending;
37143 exports.NotEqualDepth = NotEqualDepth;
37144 exports.NotEqualStencilFunc = NotEqualStencilFunc;
37145 exports.NumberKeyframeTrack = NumberKeyframeTrack;
37146 exports.Object3D = Object3D;
37147 exports.ObjectLoader = ObjectLoader;
37148 exports.ObjectSpaceNormalMap = ObjectSpaceNormalMap;
37149 exports.OctahedronBufferGeometry = OctahedronGeometry;
37150 exports.OctahedronGeometry = OctahedronGeometry;
37151 exports.OneFactor = OneFactor;
37152 exports.OneMinusDstAlphaFactor = OneMinusDstAlphaFactor;
37153 exports.OneMinusDstColorFactor = OneMinusDstColorFactor;
37154 exports.OneMinusSrcAlphaFactor = OneMinusSrcAlphaFactor;
37155 exports.OneMinusSrcColorFactor = OneMinusSrcColorFactor;
37156 exports.OrthographicCamera = OrthographicCamera;
37157 exports.PCFShadowMap = PCFShadowMap;
37158 exports.PCFSoftShadowMap = PCFSoftShadowMap;
37159 exports.PMREMGenerator = PMREMGenerator;
37160 exports.ParametricBufferGeometry = ParametricGeometry;
37161 exports.ParametricGeometry = ParametricGeometry;
37162 exports.Particle = Particle;
37163 exports.ParticleBasicMaterial = ParticleBasicMaterial;
37164 exports.ParticleSystem = ParticleSystem;
37165 exports.ParticleSystemMaterial = ParticleSystemMaterial;
37166 exports.Path = Path;
37167 exports.PerspectiveCamera = PerspectiveCamera;
37168 exports.Plane = Plane;
37169 exports.PlaneBufferGeometry = PlaneGeometry;
37170 exports.PlaneGeometry = PlaneGeometry;
37171 exports.PlaneHelper = PlaneHelper;
37172 exports.PointCloud = PointCloud;
37173 exports.PointCloudMaterial = PointCloudMaterial;
37174 exports.PointLight = PointLight;
37175 exports.PointLightHelper = PointLightHelper;
37176 exports.Points = Points;
37177 exports.PointsMaterial = PointsMaterial;
37178 exports.PolarGridHelper = PolarGridHelper;
37179 exports.PolyhedronBufferGeometry = PolyhedronGeometry;
37180 exports.PolyhedronGeometry = PolyhedronGeometry;
37181 exports.PositionalAudio = PositionalAudio;
37182 exports.PropertyBinding = PropertyBinding;
37183 exports.PropertyMixer = PropertyMixer;
37184 exports.QuadraticBezierCurve = QuadraticBezierCurve;
37185 exports.QuadraticBezierCurve3 = QuadraticBezierCurve3;
37186 exports.Quaternion = Quaternion;
37187 exports.QuaternionKeyframeTrack = QuaternionKeyframeTrack;
37188 exports.QuaternionLinearInterpolant = QuaternionLinearInterpolant;
37189 exports.REVISION = REVISION;
37190 exports.RGBADepthPacking = RGBADepthPacking;
37191 exports.RGBAFormat = RGBAFormat;
37192 exports.RGBAIntegerFormat = RGBAIntegerFormat;
37193 exports.RGBA_ASTC_10x10_Format = RGBA_ASTC_10x10_Format;
37194 exports.RGBA_ASTC_10x5_Format = RGBA_ASTC_10x5_Format;
37195 exports.RGBA_ASTC_10x6_Format = RGBA_ASTC_10x6_Format;
37196 exports.RGBA_ASTC_10x8_Format = RGBA_ASTC_10x8_Format;
37197 exports.RGBA_ASTC_12x10_Format = RGBA_ASTC_12x10_Format;
37198 exports.RGBA_ASTC_12x12_Format = RGBA_ASTC_12x12_Format;
37199 exports.RGBA_ASTC_4x4_Format = RGBA_ASTC_4x4_Format;
37200 exports.RGBA_ASTC_5x4_Format = RGBA_ASTC_5x4_Format;
37201 exports.RGBA_ASTC_5x5_Format = RGBA_ASTC_5x5_Format;
37202 exports.RGBA_ASTC_6x5_Format = RGBA_ASTC_6x5_Format;
37203 exports.RGBA_ASTC_6x6_Format = RGBA_ASTC_6x6_Format;
37204 exports.RGBA_ASTC_8x5_Format = RGBA_ASTC_8x5_Format;
37205 exports.RGBA_ASTC_8x6_Format = RGBA_ASTC_8x6_Format;
37206 exports.RGBA_ASTC_8x8_Format = RGBA_ASTC_8x8_Format;
37207 exports.RGBA_BPTC_Format = RGBA_BPTC_Format;
37208 exports.RGBA_ETC2_EAC_Format = RGBA_ETC2_EAC_Format;
37209 exports.RGBA_PVRTC_2BPPV1_Format = RGBA_PVRTC_2BPPV1_Format;
37210 exports.RGBA_PVRTC_4BPPV1_Format = RGBA_PVRTC_4BPPV1_Format;
37211 exports.RGBA_S3TC_DXT1_Format = RGBA_S3TC_DXT1_Format;
37212 exports.RGBA_S3TC_DXT3_Format = RGBA_S3TC_DXT3_Format;
37213 exports.RGBA_S3TC_DXT5_Format = RGBA_S3TC_DXT5_Format;
37214 exports.RGBDEncoding = RGBDEncoding;
37215 exports.RGBEEncoding = RGBEEncoding;
37216 exports.RGBEFormat = RGBEFormat;
37217 exports.RGBFormat = RGBFormat;
37218 exports.RGBIntegerFormat = RGBIntegerFormat;
37219 exports.RGBM16Encoding = RGBM16Encoding;
37220 exports.RGBM7Encoding = RGBM7Encoding;
37221 exports.RGB_ETC1_Format = RGB_ETC1_Format;
37222 exports.RGB_ETC2_Format = RGB_ETC2_Format;
37223 exports.RGB_PVRTC_2BPPV1_Format = RGB_PVRTC_2BPPV1_Format;
37224 exports.RGB_PVRTC_4BPPV1_Format = RGB_PVRTC_4BPPV1_Format;
37225 exports.RGB_S3TC_DXT1_Format = RGB_S3TC_DXT1_Format;
37226 exports.RGFormat = RGFormat;
37227 exports.RGIntegerFormat = RGIntegerFormat;
37228 exports.RawShaderMaterial = RawShaderMaterial;
37230 exports.Raycaster = Raycaster;
37231 exports.RectAreaLight = RectAreaLight;
37232 exports.RedFormat = RedFormat;
37233 exports.RedIntegerFormat = RedIntegerFormat;
37234 exports.ReinhardToneMapping = ReinhardToneMapping;
37235 exports.RepeatWrapping = RepeatWrapping;
37236 exports.ReplaceStencilOp = ReplaceStencilOp;
37237 exports.ReverseSubtractEquation = ReverseSubtractEquation;
37238 exports.RingBufferGeometry = RingGeometry;
37239 exports.RingGeometry = RingGeometry;
37240 exports.SRGB8_ALPHA8_ASTC_10x10_Format = SRGB8_ALPHA8_ASTC_10x10_Format;
37241 exports.SRGB8_ALPHA8_ASTC_10x5_Format = SRGB8_ALPHA8_ASTC_10x5_Format;
37242 exports.SRGB8_ALPHA8_ASTC_10x6_Format = SRGB8_ALPHA8_ASTC_10x6_Format;
37243 exports.SRGB8_ALPHA8_ASTC_10x8_Format = SRGB8_ALPHA8_ASTC_10x8_Format;
37244 exports.SRGB8_ALPHA8_ASTC_12x10_Format = SRGB8_ALPHA8_ASTC_12x10_Format;
37245 exports.SRGB8_ALPHA8_ASTC_12x12_Format = SRGB8_ALPHA8_ASTC_12x12_Format;
37246 exports.SRGB8_ALPHA8_ASTC_4x4_Format = SRGB8_ALPHA8_ASTC_4x4_Format;
37247 exports.SRGB8_ALPHA8_ASTC_5x4_Format = SRGB8_ALPHA8_ASTC_5x4_Format;
37248 exports.SRGB8_ALPHA8_ASTC_5x5_Format = SRGB8_ALPHA8_ASTC_5x5_Format;
37249 exports.SRGB8_ALPHA8_ASTC_6x5_Format = SRGB8_ALPHA8_ASTC_6x5_Format;
37250 exports.SRGB8_ALPHA8_ASTC_6x6_Format = SRGB8_ALPHA8_ASTC_6x6_Format;
37251 exports.SRGB8_ALPHA8_ASTC_8x5_Format = SRGB8_ALPHA8_ASTC_8x5_Format;
37252 exports.SRGB8_ALPHA8_ASTC_8x6_Format = SRGB8_ALPHA8_ASTC_8x6_Format;
37253 exports.SRGB8_ALPHA8_ASTC_8x8_Format = SRGB8_ALPHA8_ASTC_8x8_Format;
37254 exports.Scene = Scene;
37255 exports.SceneUtils = SceneUtils;
37256 exports.ShaderChunk = ShaderChunk;
37257 exports.ShaderLib = ShaderLib;
37258 exports.ShaderMaterial = ShaderMaterial;
37259 exports.ShadowMaterial = ShadowMaterial;
37260 exports.Shape = Shape;
37261 exports.ShapeBufferGeometry = ShapeGeometry;
37262 exports.ShapeGeometry = ShapeGeometry;
37263 exports.ShapePath = ShapePath;
37264 exports.ShapeUtils = ShapeUtils;
37265 exports.ShortType = ShortType;
37266 exports.Skeleton = Skeleton;
37267 exports.SkeletonHelper = SkeletonHelper;
37268 exports.SkinnedMesh = SkinnedMesh;
37269 exports.SmoothShading = SmoothShading;
37270 exports.Sphere = Sphere;
37271 exports.SphereBufferGeometry = SphereGeometry;
37272 exports.SphereGeometry = SphereGeometry;
37273 exports.Spherical = Spherical;
37274 exports.SphericalHarmonics3 = SphericalHarmonics3;
37275 exports.Spline = Spline;
37276 exports.SplineCurve = SplineCurve;
37277 exports.SplineCurve3 = SplineCurve3;
37278 exports.SpotLight = SpotLight;
37279 exports.SpotLightHelper = SpotLightHelper;
37280 exports.Sprite = Sprite;
37281 exports.SpriteMaterial = SpriteMaterial;
37282 exports.SrcAlphaFactor = SrcAlphaFactor;
37283 exports.SrcAlphaSaturateFactor = SrcAlphaSaturateFactor;
37284 exports.SrcColorFactor = SrcColorFactor;
37285 exports.StaticCopyUsage = StaticCopyUsage;
37286 exports.StaticDrawUsage = StaticDrawUsage;
37287 exports.StaticReadUsage = StaticReadUsage;
37288 exports.StereoCamera = StereoCamera;
37289 exports.StreamCopyUsage = StreamCopyUsage;
37290 exports.StreamDrawUsage = StreamDrawUsage;
37291 exports.StreamReadUsage = StreamReadUsage;
37292 exports.StringKeyframeTrack = StringKeyframeTrack;
37293 exports.SubtractEquation = SubtractEquation;
37294 exports.SubtractiveBlending = SubtractiveBlending;
37295 exports.TOUCH = TOUCH;
37296 exports.TangentSpaceNormalMap = TangentSpaceNormalMap;
37297 exports.TetrahedronBufferGeometry = TetrahedronGeometry;
37298 exports.TetrahedronGeometry = TetrahedronGeometry;
37299 exports.TextBufferGeometry = TextGeometry;
37300 exports.TextGeometry = TextGeometry;
37301 exports.Texture = Texture;
37302 exports.TextureLoader = TextureLoader;
37303 exports.TorusBufferGeometry = TorusGeometry;
37304 exports.TorusGeometry = TorusGeometry;
37305 exports.TorusKnotBufferGeometry = TorusKnotGeometry;
37306 exports.TorusKnotGeometry = TorusKnotGeometry;
37307 exports.Triangle = Triangle;
37308 exports.TriangleFanDrawMode = TriangleFanDrawMode;
37309 exports.TriangleStripDrawMode = TriangleStripDrawMode;
37310 exports.TrianglesDrawMode = TrianglesDrawMode;
37311 exports.TubeBufferGeometry = TubeGeometry;
37312 exports.TubeGeometry = TubeGeometry;
37313 exports.UVMapping = UVMapping;
37314 exports.Uint16Attribute = Uint16Attribute;
37315 exports.Uint16BufferAttribute = Uint16BufferAttribute;
37316 exports.Uint32Attribute = Uint32Attribute;
37317 exports.Uint32BufferAttribute = Uint32BufferAttribute;
37318 exports.Uint8Attribute = Uint8Attribute;
37319 exports.Uint8BufferAttribute = Uint8BufferAttribute;
37320 exports.Uint8ClampedAttribute = Uint8ClampedAttribute;
37321 exports.Uint8ClampedBufferAttribute = Uint8ClampedBufferAttribute;
37322 exports.Uniform = Uniform;
37323 exports.UniformsLib = UniformsLib;
37324 exports.UniformsUtils = UniformsUtils;
37325 exports.UnsignedByteType = UnsignedByteType;
37326 exports.UnsignedInt248Type = UnsignedInt248Type;
37327 exports.UnsignedIntType = UnsignedIntType;
37328 exports.UnsignedShort4444Type = UnsignedShort4444Type;
37329 exports.UnsignedShort5551Type = UnsignedShort5551Type;
37330 exports.UnsignedShort565Type = UnsignedShort565Type;
37331 exports.UnsignedShortType = UnsignedShortType;
37332 exports.VSMShadowMap = VSMShadowMap;
37333 exports.Vector2 = Vector2;
37334 exports.Vector3 = Vector3;
37335 exports.Vector4 = Vector4;
37336 exports.VectorKeyframeTrack = VectorKeyframeTrack;
37337 exports.Vertex = Vertex;
37338 exports.VertexColors = VertexColors;
37339 exports.VideoTexture = VideoTexture;
37340 exports.WebGL1Renderer = WebGL1Renderer;
37341 exports.WebGLCubeRenderTarget = WebGLCubeRenderTarget;
37342 exports.WebGLMultisampleRenderTarget = WebGLMultisampleRenderTarget;
37343 exports.WebGLRenderTarget = WebGLRenderTarget;
37344 exports.WebGLRenderTargetCube = WebGLRenderTargetCube;
37345 exports.WebGLRenderer = WebGLRenderer;
37346 exports.WebGLUtils = WebGLUtils;
37347 exports.WireframeGeometry = WireframeGeometry;
37348 exports.WireframeHelper = WireframeHelper;
37349 exports.WrapAroundEnding = WrapAroundEnding;
37350 exports.XHRLoader = XHRLoader;
37351 exports.ZeroCurvatureEnding = ZeroCurvatureEnding;
37352 exports.ZeroFactor = ZeroFactor;
37353 exports.ZeroSlopeEnding = ZeroSlopeEnding;
37354 exports.ZeroStencilOp = ZeroStencilOp;
37355 exports.sRGBEncoding = sRGBEncoding;
37357 Object.defineProperty(exports, '__esModule', { value: true });