UNPKG

@drum-n-bass/kinetics

Version:

Kinetics, attractive particles system

2 lines (1 loc) 28.9 kB
!function(t,e){"object"==typeof exports&&"undefined"!=typeof module?module.exports=e():"function"==typeof define&&define.amd?define(e):(t="undefined"!=typeof globalThis?globalThis:t||self).Kinetics=e()}(this,(function(){"use strict";"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self&&self;var t=function(t){return function(t){return!!t&&"object"==typeof t}(t)&&!function(t){var i=Object.prototype.toString.call(t);return"[object RegExp]"===i||"[object Date]"===i||function(t){return t.$$typeof===e}(t)}(t)};var e="function"==typeof Symbol&&Symbol.for?Symbol.for("react.element"):60103;function i(t,e){return!1!==e.clone&&e.isMergeableObject(t)?a((i=t,Array.isArray(i)?[]:{}),t,e):t;var i}function n(t,e,n){return t.concat(e).map((function(t){return i(t,n)}))}function s(t){return Object.keys(t).concat(function(t){return Object.getOwnPropertySymbols?Object.getOwnPropertySymbols(t).filter((function(e){return t.propertyIsEnumerable(e)})):[]}(t))}function r(t,e){try{return e in t}catch(t){return!1}}function o(t,e,n){var o={};return n.isMergeableObject(t)&&s(t).forEach((function(e){o[e]=i(t[e],n)})),s(e).forEach((function(s){(function(t,e){return r(t,e)&&!(Object.hasOwnProperty.call(t,e)&&Object.propertyIsEnumerable.call(t,e))})(t,s)||(r(t,s)&&n.isMergeableObject(e[s])?o[s]=function(t,e){if(!e.customMerge)return a;var i=e.customMerge(t);return"function"==typeof i?i:a}(s,n)(t[s],e[s],n):o[s]=i(e[s],n))})),o}function a(e,s,r){(r=r||{}).arrayMerge=r.arrayMerge||n,r.isMergeableObject=r.isMergeableObject||t,r.cloneUnlessOtherwiseSpecified=i;var a=Array.isArray(s);return a===Array.isArray(e)?a?r.arrayMerge(e,s,r):o(e,s,r):i(s,r)}a.all=function(t,e){if(!Array.isArray(t))throw new Error("first argument should be an array");return t.reduce((function(t,i){return a(t,i,e)}),{})};var c=a,h={exports:{}};!function(t,e){t.exports=function(){var t=window.requestAnimationFrame,e=window.cancelAnimationFrame;t||["ms","moz","webkit","o"].every((function(i){return t=window[i+"RequestAnimationFrame"],e=window[i+"CancelAnimationFrame"]||window[i+"CancelRequestAnimationFrame"],!t}));var i,n,s=!!t,r=!1,o=!1,a=!0,c=window.pageYOffset,h=window.pageXOffset,p=c,l=h,u=["x","horizontal"],d=["any"],f={x:[],y:[],any:[]};function g(){var t=!1;(f.x.length||f.any.length)&&(h=window.pageXOffset),(f.y.length||f.any.length)&&(c=window.pageYOffset),c!==p&&(f.y.forEach(y.y),p=c,t=!0),h!==l&&(f.x.forEach(y.x),l=h,t=!0),t&&(f.any.forEach(y.any),window.clearTimeout(i),i=null),o=!1,_()}function y(t,e){t(e)}function m(){if(!r&&!o)return a?(r=!0,window.addEventListener("scroll",S),void document.body.addEventListener("touchmove",S)):void _()}function v(){r&&(window.removeEventListener("scroll",S),document.body.removeEventListener("touchmove",S),r=!1)}function S(){a=!1,_(),v()}function _(){o||(i||(i=window.setTimeout(w,1500)),n=t(g),o=!0)}function b(){o&&(e(n),o=!1)}function w(){a=!0,b(),m()}function x(t,e){if(s){if(m(),"function"==typeof t)return e=t,void f.y.push(e);"function"==typeof e&&(~u.indexOf(t)?f.x.push(e):~d.indexOf(t)?f.any.push(e):f.y.push(e))}}return y.y=function(t){y(t,c)},y.x=function(t){y(t,h)},y.any=function(t){y(t,[h,c])},x.remove=function(t,e){var i,n,s="y";if("string"==typeof t){if("function"!=typeof e)return;~u.indexOf(t)?s=u[0]:~d.indexOf(t)&&(s=d[0])}else e=t;(n=(i=f[s]).indexOf(e))>-1&&i.splice(n,1),f.x.length||f.y.length||f.any.length||(b(),v())},x.off=x.remove,x}()}(h);var p=h.exports,l={debug:!1,spring:{tension:8,friction:10,randomTension:50,randomFriction:-4,extendedRestDelay:10},canvas:{handlePosition:!0},particles:{count:16,sides:{min:3,max:4},sizes:{min:5,max:50},rotate:{speed:1.5,direction:null},mode:{type:"linear",speed:2,boundery:"endless"},parallex:{layers:3,speed:.15},attract:{chance:.75,force:1,grow:"random(1,4)",size:null,type:"static",speed:1.5,direction:-1,radius:1},fill:{colors:["#FFD166","#EF476F","#06D6A0","#118AB2"],toColors:["#FFD166","#EF476F","#06D6A0","#118AB2"],opacity:1},stroke:{colors:[],toColors:[],opacity:0,width:[]}}},u=t=>{const e=new RegExp('"random\\(([0-9]*[.])?[0-9]+,([0-9]*[.])?[0-9]+\\)"',"ig"),i=t=>parseFloat(t.replace(/^\D+/g,""));let n=JSON.stringify(t);n=n.replaceAll(e,(t=>{const e=i(t.split(",")[0]),n=i(t.split(",")[1]);return Math.random()*(n-e)+e}));return JSON.parse(n)},d={exports:{}};!function(t,e){t.exports=function(){var t=void 0;"undefined"!=typeof window&&(t=window.requestAnimationFrame||window.webkitRequestAnimationFrame||window.mozRequestAnimationFrame||window.msRequestAnimationFrame||window.oRequestAnimationFrame),t||"undefined"==typeof process||"node"!==process.title||(t=setImmediate);var e=t=t||function(t){window.setTimeout(t,1e3/60)},i=Array.prototype.concat,n=Array.prototype.slice;function s(t,e){for(var s=arguments.length,r=Array(s>2?s-2:0),o=2;o<s;o++)r[o-2]=arguments[o];return function(){for(var s=arguments.length,o=Array(s),a=0;a<s;a++)o[a]=arguments[a];t.apply(e,i.call(r,n.call(o)))}}function r(t,e){for(var i in e)e.hasOwnProperty(i)&&(t[i]=e[i])}function o(t){return e(t)}function a(t,e){var i=t.indexOf(e);-1!==i&&t.splice(i,1)}var c={};function h(t){if(c[t])return c[t];var e=t.replace("#","");3===e.length&&(e=e[0]+e[0]+e[1]+e[1]+e[2]+e[2]);var i=e.match(/.{2}/g);if(!i||i.length<3)throw new Error("Expected a color string of format #rrggbb");var n={r:parseInt(i[0],16),g:parseInt(i[1],16),b:parseInt(i[2],16)};return c[t]=n,n}function p(t,e,i){var n=t.toString(16),s=e.toString(16),r=i.toString(16);return"#"+(n=n.length<2?"0"+n:n)+(s=s.length<2?"0"+s:s)+(r=r.length<2?"0"+r:r)}var l=Object.freeze({bind:s,extend:r,onFrame:o,removeFirst:a,hexToRGB:h,rgbToHex:p});function u(t,e,i,n,s){return n+(t-e)/(i-e)*(s-n)}function d(t,e,i){var n=arguments.length>3&&void 0!==arguments[3]?arguments[3]:0,s=arguments.length>4&&void 0!==arguments[4]?arguments[4]:1,r=arguments[5],o=h(e),a=h(i),c=Math.floor(u(t,n,s,o.r,a.r)),l=Math.floor(u(t,n,s,o.g,a.g)),d=Math.floor(u(t,n,s,o.b,a.b));return r?"rgb("+c+","+l+","+d+")":p(c,l,d)}function f(t){return t*Math.PI/180}function g(t){return 180*t/Math.PI}var y=Object.freeze({mapValueInRange:u,interpolateColor:d,degreesToRadians:f,radiansToDegrees:g});function m(t){return 3.62*(t-30)+194}function v(t){return(t-194)/3.62+30}function S(t){return 3*(t-8)+25}function _(t){return(t-25)/3+8}var b=Object.freeze({tensionFromOrigamiValue:m,origamiValueFromTension:v,frictionFromOrigamiValue:S,origamiFromFriction:_}),w=function(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")},x=Object.assign||function(t){for(var e=1;e<arguments.length;e++){var i=arguments[e];for(var n in i)Object.prototype.hasOwnProperty.call(i,n)&&(t[n]=i[n])}return t},E=function(){function t(){w(this,t),this.springSystem=null}return t.prototype.run=function(){var t=I.call(this);o((function(){t.loop(Date.now())}))},t}(),A=function(){function t(e){w(this,t),this.springSystem=null,this.time=0,this.running=!1,this.timestep=e||16.667}return t.prototype.run=function(){var t=I.call(this);if(!this.running){for(this.running=!0;!t.getIsIdle();)t.loop(this.time+=this.timestep);this.running=!1}},t}(),M=function(){function t(){w(this,t),this.springSystem=null,this.time=0,this.running=!1}return t.prototype.run=function(){},t.prototype.step=function(t){I.call(this).loop(this.time+=t)},t}();function I(){if(null==this.springSystem)throw new Error("cannot run looper without a springSystem");return this.springSystem}var T=Object.freeze({AnimationLooper:E,SimulationLooper:A,SteppingSimulationLooper:M}),C=function(){function t(e,i){w(this,t),this.bounciness=e,this.speed=i;var n=this.normalize(e/1.7,0,20);n=this.projectNormal(n,0,.8);var s=this.normalize(i/1.7,0,20);this.bouncyTension=this.projectNormal(s,.5,200),this.bouncyFriction=this.quadraticOutInterpolation(n,this.b3Nobounce(this.bouncyTension),.01)}return t.prototype.normalize=function(t,e,i){return(t-e)/(i-e)},t.prototype.projectNormal=function(t,e,i){return e+t*(i-e)},t.prototype.linearInterpolation=function(t,e,i){return t*i+(1-t)*e},t.prototype.quadraticOutInterpolation=function(t,e,i){return this.linearInterpolation(2*t-t*t,e,i)},t.prototype.b3Friction1=function(t){return 7e-4*Math.pow(t,3)-.031*Math.pow(t,2)+.64*t+1.28},t.prototype.b3Friction2=function(t){return 44e-6*Math.pow(t,3)-.006*Math.pow(t,2)+.36*t+2},t.prototype.b3Friction3=function(t){return 45e-8*Math.pow(t,3)-332e-6*Math.pow(t,2)+.1078*t+5.84},t.prototype.b3Nobounce=function(t){return t<=18?this.b3Friction1(t):t>18&&t<=44?this.b3Friction2(t):this.b3Friction3(t)},t}(),R=function(){function t(e,i){w(this,t),this.tension=e,this.friction=i}return t.fromOrigamiTensionAndFriction=function(e,i){return new t(m(e),S(i))},t.fromBouncinessAndSpeed=function(e,i){var n=new C(e,i);return t.fromOrigamiTensionAndFriction(n.bouncyTension,n.bouncyFriction)},t.coastingConfigWithOrigamiFriction=function(e){return new t(0,S(e))},t}();R.DEFAULT_ORIGAMI_SPRING_CONFIG=R.fromOrigamiTensionAndFriction(40,7);var O=function t(){w(this,t),this.position=0,this.velocity=0},P=function(){function t(e){w(this,t),this.listeners=[],this._startValue=0,this._currentState=new O,this._displacementFromRestThreshold=.001,this._endValue=0,this._overshootClampingEnabled=!1,this._previousState=new O,this._restSpeedThreshold=.001,this._tempState=new O,this._timeAccumulator=0,this._wasAtRest=!0,this._id="s"+t._ID++,this._springSystem=e}return t.prototype.destroy=function(){this.listeners=[],this._springSystem.deregisterSpring(this)},t.prototype.getId=function(){return this._id},t.prototype.setSpringConfig=function(t){return this._springConfig=t,this},t.prototype.getSpringConfig=function(){return this._springConfig},t.prototype.setCurrentValue=function(t,e){return this._startValue=t,this._currentState.position=t,e||this.setAtRest(),this.notifyPositionUpdated(!1,!1),this},t.prototype.getStartValue=function(){return this._startValue},t.prototype.getCurrentValue=function(){return this._currentState.position},t.prototype.getCurrentDisplacementDistance=function(){return this.getDisplacementDistanceForState(this._currentState)},t.prototype.getDisplacementDistanceForState=function(t){return Math.abs(this._endValue-t.position)},t.prototype.setEndValue=function(t){if(this._endValue===t&&this.isAtRest())return this;this._startValue=this.getCurrentValue(),this._endValue=t,this._springSystem.activateSpring(this.getId());for(var e=0,i=this.listeners.length;e<i;e++){var n=this.listeners[e].onSpringEndStateChange;n&&n(this)}return this},t.prototype.getEndValue=function(){return this._endValue},t.prototype.setVelocity=function(t){return t===this._currentState.velocity||(this._currentState.velocity=t,this._springSystem.activateSpring(this.getId())),this},t.prototype.getVelocity=function(){return this._currentState.velocity},t.prototype.setRestSpeedThreshold=function(t){return this._restSpeedThreshold=t,this},t.prototype.getRestSpeedThreshold=function(){return this._restSpeedThreshold},t.prototype.setRestDisplacementThreshold=function(t){this._displacementFromRestThreshold=t},t.prototype.getRestDisplacementThreshold=function(){return this._displacementFromRestThreshold},t.prototype.setOvershootClampingEnabled=function(t){return this._overshootClampingEnabled=t,this},t.prototype.isOvershootClampingEnabled=function(){return this._overshootClampingEnabled},t.prototype.isOvershooting=function(){var t=this._startValue,e=this._endValue;return this._springConfig.tension>0&&(t<e&&this.getCurrentValue()>e||t>e&&this.getCurrentValue()<e)},t.prototype.advance=function(e,i){var n=this.isAtRest();if(!n||!this._wasAtRest){var s=i;i>t.MAX_DELTA_TIME_SEC&&(s=t.MAX_DELTA_TIME_SEC),this._timeAccumulator+=s;for(var r=this._springConfig.tension,o=this._springConfig.friction,a=this._currentState.position,c=this._currentState.velocity,h=this._tempState.position,p=this._tempState.velocity,l=void 0,u=void 0,d=void 0,f=void 0,g=void 0,y=void 0,m=void 0,v=void 0;this._timeAccumulator>=t.SOLVER_TIMESTEP_SEC;)this._timeAccumulator-=t.SOLVER_TIMESTEP_SEC,this._timeAccumulator<t.SOLVER_TIMESTEP_SEC&&(this._previousState.position=a,this._previousState.velocity=c),l=c,u=r*(this._endValue-h)-o*c,h=a+l*t.SOLVER_TIMESTEP_SEC*.5,d=p=c+u*t.SOLVER_TIMESTEP_SEC*.5,f=r*(this._endValue-h)-o*p,h=a+d*t.SOLVER_TIMESTEP_SEC*.5,g=p=c+f*t.SOLVER_TIMESTEP_SEC*.5,y=r*(this._endValue-h)-o*p,h=a+g*t.SOLVER_TIMESTEP_SEC,m=p=c+y*t.SOLVER_TIMESTEP_SEC,v=1/6*(u+2*(f+y)+(r*(this._endValue-h)-o*p)),a+=1/6*(l+2*(d+g)+m)*t.SOLVER_TIMESTEP_SEC,c+=v*t.SOLVER_TIMESTEP_SEC;this._tempState.position=h,this._tempState.velocity=p,this._currentState.position=a,this._currentState.velocity=c,this._timeAccumulator>0&&this._interpolate(this._timeAccumulator/t.SOLVER_TIMESTEP_SEC),(this.isAtRest()||this._overshootClampingEnabled&&this.isOvershooting())&&(this._springConfig.tension>0?(this._startValue=this._endValue,this._currentState.position=this._endValue):(this._endValue=this._currentState.position,this._startValue=this._endValue),this.setVelocity(0),n=!0);var S=!1;this._wasAtRest&&(this._wasAtRest=!1,S=!0);var _=!1;n&&(this._wasAtRest=!0,_=!0),this.notifyPositionUpdated(S,_)}},t.prototype.notifyPositionUpdated=function(t,e){for(var i=0,n=this.listeners.length;i<n;i++){var s=this.listeners[i];t&&s.onSpringActivate&&s.onSpringActivate(this),s.onSpringUpdate&&s.onSpringUpdate(this),e&&s.onSpringAtRest&&s.onSpringAtRest(this)}},t.prototype.systemShouldAdvance=function(){return!this.isAtRest()||!this.wasAtRest()},t.prototype.wasAtRest=function(){return this._wasAtRest},t.prototype.isAtRest=function(){return Math.abs(this._currentState.velocity)<this._restSpeedThreshold&&(this.getDisplacementDistanceForState(this._currentState)<=this._displacementFromRestThreshold||0===this._springConfig.tension)},t.prototype.setAtRest=function(){return this._endValue=this._currentState.position,this._tempState.position=this._currentState.position,this._currentState.velocity=0,this},t.prototype._interpolate=function(t){this._currentState.position=this._currentState.position*t+this._previousState.position*(1-t),this._currentState.velocity=this._currentState.velocity*t+this._previousState.velocity*(1-t)},t.prototype.getListeners=function(){return this.listeners},t.prototype.addListener=function(t){return this.listeners.push(t),this},t.prototype.removeListener=function(t){return a(this.listeners,t),this},t.prototype.removeAllListeners=function(){return this.listeners=[],this},t.prototype.currentValueIsApproximately=function(t){return Math.abs(this.getCurrentValue()-t)<=this.getRestDisplacementThreshold()},t}();P._ID=0,P.MAX_DELTA_TIME_SEC=.064,P.SOLVER_TIMESTEP_SEC=.001;var V=function(){function t(e){w(this,t),this.listeners=[],this._activeSprings=[],this._idleSpringIndices=[],this._isIdle=!0,this._lastTimeMillis=-1,this._springRegistry={},this.looper=e||new E,this.looper.springSystem=this}return t.prototype.setLooper=function(t){this.looper=t,t.springSystem=this},t.prototype.createSpring=function(t,e){var i=void 0;return i=void 0===t||void 0===e?R.DEFAULT_ORIGAMI_SPRING_CONFIG:R.fromOrigamiTensionAndFriction(t,e),this.createSpringWithConfig(i)},t.prototype.createSpringWithBouncinessAndSpeed=function(t,e){var i=void 0;return i=void 0===t||void 0===e?R.DEFAULT_ORIGAMI_SPRING_CONFIG:R.fromBouncinessAndSpeed(t,e),this.createSpringWithConfig(i)},t.prototype.createSpringWithConfig=function(t){var e=new P(this);return this.registerSpring(e),e.setSpringConfig(t),e},t.prototype.getIsIdle=function(){return this._isIdle},t.prototype.getSpringById=function(t){return this._springRegistry[t]},t.prototype.getAllSprings=function(){var t=[];for(var e in this._springRegistry)this._springRegistry.hasOwnProperty(e)&&t.push(this._springRegistry[e]);return t},t.prototype.registerSpring=function(t){this._springRegistry[t.getId()]=t},t.prototype.deregisterSpring=function(t){a(this._activeSprings,t),delete this._springRegistry[t.getId()]},t.prototype.advance=function(t,e){for(;this._idleSpringIndices.length>0;)this._idleSpringIndices.pop();for(var i=0,n=this._activeSprings.length;i<n;i++){var s=this._activeSprings[i];s.systemShouldAdvance()?s.advance(t/1e3,e/1e3):this._idleSpringIndices.push(this._activeSprings.indexOf(s))}for(;this._idleSpringIndices.length>0;){var r=this._idleSpringIndices.pop();r>=0&&this._activeSprings.splice(r,1)}},t.prototype.loop=function(t){var e=void 0;-1===this._lastTimeMillis&&(this._lastTimeMillis=t-1);var i=t-this._lastTimeMillis;this._lastTimeMillis=t;var n=0,s=this.listeners.length;for(n=0;n<s;n++)(e=this.listeners[n]).onBeforeIntegrate&&e.onBeforeIntegrate(this);for(this.advance(t,i),0===this._activeSprings.length&&(this._isIdle=!0,this._lastTimeMillis=-1),n=0;n<s;n++)(e=this.listeners[n]).onAfterIntegrate&&e.onAfterIntegrate(this);this._isIdle||this.looper.run()},t.prototype.activateSpring=function(t){var e=this._springRegistry[t];-1===this._activeSprings.indexOf(e)&&this._activeSprings.push(e),this.getIsIdle()&&(this._isIdle=!1,this.looper.run())},t.prototype.addListener=function(t){this.listeners.push(t)},t.prototype.removeListener=function(t){a(this.listeners,t)},t.prototype.removeAllListeners=function(){this.listeners=[]},t}();return x({},T,{OrigamiValueConverter:b,MathUtil:y,Spring:P,SpringConfig:R,SpringSystem:V,util:x({},l,y)})}()}(d);var f=d.exports,g=(t,e)=>{e=e||Math.random();const{min:i,max:n}=t;return Math.round(e*(n-i))+i};class y{constructor(t,e,i){this.ctx=t,this.config=e;const{particles:{sides:n,fill:s,stroke:r}}=e;this.sides=g(n),this.sidesSeeds=Array.from(Array(this.sides)).map(((t,e)=>Math.random()));const o=t=>Math.floor(Math.random()*t.length);this.indexes={fill:o(s.colors),fillTo:o(s.toColors),stroke:o(r.colors),strokeTo:o(r.toColors),strokeWidth:o(r.width)},this.seeds={x:Math.random(),y:Math.random()},this.springPosition=0,this.position={x:0,y:0},this.attractPoint={x:0,y:0},this.attractCenter={x:0,y:0},this.attractConfig={chance:1,direction:1,force:1,grow:1,radius:1,size:null,speed:1,type:""},this.resetFlip();const{spring:{tension:a,friction:c,randomTension:h,randomFriction:p}}=e;this.spring=i.createSpring(a+this.seeds.x*h,c+this.seeds.y*p),this.onSpringUpdate=this.onSpringUpdate.bind(this),this.spring.addListener({onSpringUpdate:this.onSpringUpdate})}destroy(){this.spring&&this.spring.destroy()}set(t){this.config=t,this.resetFlip()}resetFlip(){this.flip={x:1,y:1}}onExtendedRest(){this.config.debug&&console.log("onExtendedRest")}onSpringUpdate(t){this.springPosition=t.getCurrentValue()}canvasResized(t,e){this.canvasWidth=t,this.canvasHeight=e,this.position={x:Math.floor(this.seeds.x*t),y:Math.floor(this.seeds.y*e)}}attract(t,e,i){this.attractPoint=t,this.attractCenter=e,this.attractConfig=i,this.spring.setEndValue(i.force),this.isAttracted=!0}unattract(){this.isAttracted&&(this.spring.setEndValue(0),this.isAttracted=!1)}attractPosition(){if(this.isAttracted||!this.spring.isAtRest()){const{type:t,speed:e,direction:i,radius:n}=this.attractConfig,s=this.getAngle(i,this.seeds.x*e+e);return((t,e,i,n,s)=>{let{x:r,y:o}=e;const{x:a,y:c}=i,h=(r-a)*s,p=(o-c)*s,l=Math.cos(n),u=Math.sin(n);switch(t){case"":case"static":break;case"drone":r=a+l*Math.abs(h)-u*p,o=c+u*Math.abs(p)+l*p;break;case"horz":r=l*h+a;break;case"vert":o=u*p+c;break;case"orbit":r=a+l*Math.abs(h)-u*Math.abs(p),o=c+u*Math.abs(h)+l*Math.abs(p);break;case"bee":r=a+Math.abs(h)/2*l*u,o=c+Math.abs(p)*l;break;case"swing":r=a+u*h,o=c+u*p;break;default:throw new Error("invalid type: "+t)}return{x:r,y:o}})(t,this.attractPoint,this.attractCenter,s,n)}return this.attractPoint}modulatePosition(t,e){const{type:i,speed:n,boundery:s}=e;t=((t,e,i,n,s)=>{let{x:r,y:o}=e;switch(t){case"wind-from-right":r-=(s.x*i+i)*n.x;break;case"wind-from-left":r+=(s.x*i+i)*n.x;break;case"linear":r+=Math.cos(Math.PI-Math.PI*s.x)*i*n.x,o+=Math.cos(Math.PI-Math.PI*s.y)*i*n.y;break;case"rain":const e=s.y*i+i;r-=e/2*n.x,o+=e*n.y;break;case"wind":r-=(s.x*i+i)*n.x,o+=s.y*i*n.y;break;case"party":r+=s.x*i*n.x,o-=s.y*i*n.y;break;case"space":break;default:throw new Error("invalid type: "+t)}return{x:r,y:o}})(i,t,n,this.flip,this.seeds);const{sizes:{max:r},stroke:{width:o}}=this.config.particles;return t=((t,e,i,n,s,r)=>{let{x:o,y:a}=e,c=i;"pong"===t&&(c/=2);let h="";if(o>s+c&&(h="right"),o<-c&&(h="left"),a>r+c&&(h="bottom"),a<-c&&(h="top"),h)switch(t){case"endless":switch(h){case"left":o=s+c;break;case"right":o=-c;break;case"bottom":a=-c;break;case"top":a=r+c}break;case"pong":switch(h){case"left":o=-c,n.x*=-1;break;case"right":o=s+c,n.x*=-1;break;case"bottom":a=r+c,n.y*=-1;break;case"top":a=-c,n.y*=-1}break;case"emitter":o=s/2,a=r/2;break;default:throw new Error("invalid mode: "+t)}return{x:o,y:a}})(s,t,r+this.idxValue(o,"strokeWidth"),this.flip,this.canvasWidth,this.canvasHeight)}generateVertices(t,e){const{grow:i,size:n}=this.attractConfig;let s=1;n||(s+=this.springPosition*(i>=1?i:i-1));const{sizes:r,rotate:{speed:o,direction:a}}=this.config.particles,c=this.getAngle(a,o);return Array.from(Array(this.sides)).map(((i,o)=>{const a=360/this.sides,h=(this.sidesSeeds[o]*a+o*a)*Math.PI/180;let p=g(r,this.sidesSeeds[o]);if(n){const t=n*this.sidesSeeds[o];p=(1-this.springPosition)*p+this.springPosition*t}const l=p*Math.cos(h)*s,u=p*Math.sin(h)*s;return{x:t+l*Math.cos(c)-u*Math.sin(c),y:e+l*Math.sin(c)+u*Math.cos(c)}}))}getAngle(t,e){return this.ctx.frameCount*e%360*(Number.isInteger(t)?t:this.seeds.x>.5?1:-1)*Math.PI/180}getPosition(){if(!this.isAttracted&&(this.position=this.modulatePosition(this.position,this.config.particles.mode),this.spring.isAtRest()))return this.position;let{x:t,y:e}=this.attractPosition();return t=f.MathUtil.mapValueInRange(this.springPosition,0,1,this.position.x,t),e=f.MathUtil.mapValueInRange(this.springPosition,0,1,this.position.y,e),{x:t,y:e}}update(){const{x:t,y:e}=this.getPosition();this.vertices=this.generateVertices(t,e)}draw(){this.ctx.beginPath(),this.vertices.forEach((t=>this.ctx.lineTo(t.x,t.y))),this.ctx.closePath();const{fill:t,stroke:e}=this.config.particles;if(t.colors.length){let e=this.idxValue(t.colors,"fill");t.toColors.length&&(e=f.MathUtil.interpolateColor(this.colorPosition(),e,this.idxValue(t.toColors,"fillTo"))),this.ctx.fillStyle=e+this.float2hex(t.opacity),this.ctx.fill()}if(e.colors.length){const t=this.idxValue(e.width,"strokeWidth");if(t>0){let i=this.idxValue(e.colors,"stroke");e.toColors.length&&(i=f.MathUtil.interpolateColor(this.colorPosition(),i,this.idxValue(e.toColors,"strokeTo"))),this.ctx.strokeStyle=i+this.float2hex(e.opacity),this.ctx.lineWidth=t,this.ctx.stroke()}}}colorPosition(){return Math.abs(Math.sin(this.ctx.frameCount*this.seeds.x*Math.PI/180))}float2hex(t){return Number.isNaN(t)||t<0||t>1?"":Math.floor(255*t).toString(16).padStart(2,0)}idxValue(t,e){return t.length?t[this.indexes[e]]:null}}class m{constructor(t,e,i,n){this.ctx=t,this.width=i,this.height=n;const{count:s,sides:r}=e.particles;this.count=s,this.sides=r,this.config=e,this.init()}init(){this.particles=[],this.springSystem=new f.SpringSystem;for(let t=0;t<this.count;t++){const t=new y(this.ctx,this.config,this.springSystem);this.particles.push(t)}}destory(){this.springSystem&&this.springSystem.destory(),this.particles.forEach((t=>t.destory()))}set(t){t&&(this.config=t,this.particles.forEach((e=>e.set(t))))}draw(){this.resetCanvas(),this.particles.forEach((t=>t.draw()))}update(){this.particles.forEach((t=>t.update()))}attract(t,e){const{chance:i}=e,n=this.particles.length;[].concat(this.particles).sort((()=>Math.random())).forEach(((s,r)=>{if(r/n<i){const i=s.position,n=((t,e,i,n,s,r,o)=>{if(o&&i<t&&t<s&&n<e&&e<r)throw"Point "+[t,e]+"cannot be inside the rectangle: "+[i,n]+" - "+[s,r]+".";var a=(i+s)/2,c=(n+r)/2,h=(c-e)/(a-t);if(t<=a){var p=h*(i-t)+e;if(n<=p&&p<=r)return{x:i,y:p}}if(t>=a){var l=h*(s-t)+e;if(n<=l&&l<=r)return{x:s,y:l}}if(e<=c){var u=(n-e)/h+t;if(i<=u&&u<=s)return{x:u,y:n}}if(e>=c){var d=(r-e)/h+t;if(i<=d&&d<=s)return{x:d,y:r}}return t===a&&e===c?{x:t,y:e}:{x:a,y:c}})(i.x,i.y,t.left,t.top,t.right,t.bottom,!1),r={x:t.left+(t.right-t.left)/2,y:t.top+(t.bottom-t.top)/2};s.attract(n,r,e)}}))}unattract(){this.particles.forEach((t=>t.unattract()))}bump(t,e){this.particles.forEach((i=>{if(i.isAttracted){const n=.1;i.attractPoint.x+=t*n,i.attractPoint.y+=e*n}}))}scroll(t){this.particles.forEach(((e,i)=>{if(e.isAttracted)e.attractPoint.y-=t;else{const{layers:n,speed:s}=this.config.particles.parallex;e.position.y-=t*(i%n*s)}}))}resetCanvas(){this.ctx.clearRect(0,0,this.width,this.height)}canvasResized(t,e){this.width=t,this.height=e,this.particles.forEach((i=>i.canvasResized(t,e)))}}function v(t,e,i){let n={};try{const s=e+i[0].toUpperCase()+i.substr(1);n=JSON.parse(t.dataset[s])}catch(s){Object.keys(t.dataset).forEach((s=>{let r=s.replace(/[A-Z]/g,(t=>"-"+t.toLowerCase()));if(r.startsWith(`${e}-`)&&(r=r.substr(e.length+1),r!==i)){let e=t.dataset[s];isNaN(parseFloat(e))||(e=parseFloat(e));const o=r.substr(i.length+1);n[o]=e}}))}return n}return function(){let t=null;const e={arrayMerge:(t,e,i)=>e};function i(i={},n){if(!document.querySelector||!window.requestAnimationFrame)return console.warn("KINETICS: FAILED FEATURE TEST");t=this,this.destroy(),this.config=u(c(l,i,e)),this.originalConfig=c({},this.config),this.container=n,this.construct()}i.prototype.VERSION="0.9.0",i.prototype.construct=function(){this.paths=[],"IntersectionObserver"in window&&(this.intersectionObserver=new IntersectionObserver(r)),this.init(),s()},i.prototype.destroy=function(){this.config&&(this.config.debug&&console.log("destroy"),this.spring&&this.spring.destroy(),this.canvas&&this.canvas.remove(),p.remove(n),this.intersectionObserver&&this.intersectionObserver.disconnect(),this.config.click.shuffle&&document.removeEventListener("click",onClick,!0),this.onRestTimeout&&clearTimeout(this.onRestTimeout),this.config=null)},i.prototype.init=function(){this.config.debug&&console.log("init",this.config),this.canvas=document.createElement("canvas"),this.config.canvas.handlePosition&&(this.canvas.style.position=this.container?"absolute":"fixed",this.canvas.style.top=0,this.canvas.style.left=0,this.canvas.style.zIndex=-1);const t=this.container||document.body;t.prepend(this.canvas),this.ctx=this.canvas.getContext("2d",{alpha:!0}),this.ctx.frameCount=0,this.particles=new m(this.ctx,this.config),this.loop(),window.addEventListener("resize",s),document.addEventListener("visibilitychange",o),this.intersectionObserver&&this.intersectionObserver.observe(t),p(n)},i.prototype.loop=function(){requestAnimationFrame(t.loop),t.paused||(t.particles.update(),t.particles.draw(),t.ctx.frameCount+=1)},i.prototype.setupCanvas=function(t,e){this.config.debug&&console.log("setupCanvas",t,e),this.width=t,this.height=e;const i=(()=>{let t=1;return"undefined"!=typeof screen&&"deviceXDPI"in screen?t=screen.deviceXDPI/screen.logicalXDPI:"undefined"!=typeof window&&"devicePixelRatio"in window&&(t=window.devicePixelRatio),t=Number(t.toFixed(3)),t})();this.canvas.width=t*i,this.canvas.height=e*i,this.canvas.style.width=t+"px",this.canvas.style.height=e+"px",1!==i&&this.ctx.setTransform(i,0,0,i,0,0)};const n=function(e){if(t.container)return;if(t.paused)return;const i=e-(t.prevScroll||0);t.prevScroll=e,t.particles.scroll(i)},s=function(e){const i=t.container?t.container.offsetWidth:window.innerWidth,n=t.container?t.container.offsetHeight:window.innerHeight;t.config.debug&&console.log("Resize observed: Width "+i+"px, Height "+n+"px"),t.setupCanvas(i,n),t.particles.canvasResized(i,n)},r=function(e){t.paused=0===e[0].intersectionRatio,t.config.debug&&console.log("Paused",t.paused)},o=function(){t.paused="hidden"===document.visibilityState,t.config.debug&&console.log("Paused",t.paused)};return i.prototype.set=function(t={}){this.config=u(c(this.originalConfig,t,e)),this.particles.set(this.config)},i.prototype.bump=function(t,e,i,n){this.particles.bump(i,n)},i.prototype.attract=function(t,e){this.config.debug&&console.log("attract",t,e),this.particles.attract(t,u(c(this.config.particles.attract,e)))},i.prototype.unattract=function(){this.config.debug&&console.log("unattract"),this.particles.unattract()},i.prototype.interactionHook=function(t,e){((t,e={},i=document)=>{const{prefix:n,attraction:s,intersection:r}=c({prefix:"kinetics",attraction:{keyword:"attraction"},intersection:{threshold:.2,keyword:"mode"}},e);if(i.querySelectorAll(`[data-${n}-${s.keyword}]`).forEach((e=>{const i=v(e,n,s.keyword);e.addEventListener("mouseenter",(e=>{const n=e.target.getBoundingClientRect().toJSON();t.container&&(n.top=e.target.offsetTop,n.left=e.target.offsetLeft),t.attract(n,i)}),!1),e.addEventListener("mouseleave",(e=>t.unattract()),!1),e.addEventListener("mousemove",(e=>t.bump(e.offsetX,e.offsetY,e.movementX,e.movementY)),!1)})),"IntersectionObserver"in window){const e=new IntersectionObserver((e=>{e.forEach((e=>{if(e.isIntersecting){const i=v(e.target,n,r.keyword);t.set({particles:{mode:i}})}}))}),{threshold:r.threshold});i.querySelectorAll(`[data-${n}-${r.keyword}]`).forEach((t=>{e.observe(t)}))}})(this,t,e)},i}()}));