LightningStrike.js 33 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006
  1. /**
  2. * @fileoverview LightningStrike object for creating lightning strikes and voltaic arcs.
  3. *
  4. *
  5. * Usage
  6. *
  7. * var myRay = new THREE.LightningStrike( paramsObject );
  8. * var myRayMesh = new THREE.Mesh( myRay, myMaterial );
  9. * scene.add( myRayMesh );
  10. * ...
  11. * myRay.update( currentTime );
  12. *
  13. * The "currentTime" can vary its rate, go forwards, backwards or even jump, but it cannot be negative.
  14. *
  15. * You should normally leave the ray position to (0, 0, 0). You should control it by changing the sourceOffset and destOffset parameters.
  16. *
  17. *
  18. * LightningStrike parameters
  19. *
  20. * The paramsObject can contain any of the following parameters.
  21. *
  22. * Legend:
  23. * 'LightningStrike' (also called 'ray'): An independent voltaic arc with its ramifications and defined with a set of parameters.
  24. * 'Subray': A ramification of the ray. It is not a LightningStrike object.
  25. * 'Segment': A linear segment piece of a subray.
  26. * 'Leaf segment': A ray segment which cannot be smaller.
  27. *
  28. *
  29. * The following parameters can be changed any time and if they vary smoothly, the ray form will also change smoothly:
  30. *
  31. * @param {Vector3} sourceOffset The point where the ray starts.
  32. *
  33. * @param {Vector3} destOffset The point where the ray ends.
  34. *
  35. * @param {double} timeScale The rate at wich the ray form changes in time. Default: 1
  36. *
  37. * @param {double} roughness From 0 to 1. The higher the value, the more wrinkled is the ray. Default: 0.9
  38. *
  39. * @param {double} straightness From 0 to 1. The higher the value, the more straight will be a subray path. Default: 0.7
  40. *
  41. * @param {Vector3} up0 Ray 'up' direction at the ray starting point. Must be normalized. It should be perpendicular to the ray forward direction but it doesn't matter much.
  42. *
  43. * @param {Vector3} up1 Like the up0 parameter but at the end of the ray. Must be normalized.
  44. *
  45. * @param {double} radius0 Radius of the main ray trunk at the start point. Default: 1
  46. *
  47. * @param {double} radius1 Radius of the main ray trunk at the end point. Default: 1
  48. *
  49. * @param {double} radius0Factor The radius0 of a subray is this factor times the radius0 of its parent subray. Default: 0.5
  50. *
  51. * @param {double} radius1Factor The radius1 of a subray is this factor times the radius1 of its parent subray. Default: 0.2
  52. *
  53. * @param {minRadius} Minimum value a subray radius0 or radius1 can get. Default: 0.1
  54. *
  55. *
  56. * The following parameters should not be changed after lightning creation. They can be changed but the ray will change its form abruptly:
  57. *
  58. * @param {boolean} isEternal If true the ray never extinguishes. Otherwise its life is controlled by the 'birthTime' and 'deathTime' parameters. Default: true if any of those two parameters is undefined.
  59. *
  60. * @param {double} birthTime The time at which the ray starts its life and begins propagating. Only if isEternal is false. Default: None.
  61. *
  62. * @param {double} deathTime The time at which the ray ends vanishing and its life. Only if isEternal is false. Default: None.
  63. *
  64. * @param {double} propagationTimeFactor From 0 to 1. Lifetime factor at which the ray ends propagating and enters the steady phase. For example, 0.1 means it is propagating 1/10 of its lifetime. Default: 0.1
  65. *
  66. * @param {double} vanishingTimeFactor From 0 to 1. Lifetime factor at which the ray ends the steady phase and begins vanishing. For example, 0.9 means it is vanishing 1/10 of its lifetime. Default: 0.9
  67. *
  68. * @param {double} subrayPeriod Subrays cycle periodically. This is their time period. Default: 4
  69. *
  70. * @param {double} subrayDutyCycle From 0 to 1. This is the fraction of time a subray is active. Default: 0.6
  71. *
  72. *
  73. * These parameters cannot change after lightning creation:
  74. *
  75. * @param {integer} maxIterations: Greater than 0. The number of ray's leaf segments is 2**maxIterations. Default: 9
  76. *
  77. * @param {boolean} isStatic Set to true only for rays which won't change over time and are not attached to moving objects (Rare case). It is used to set the vertex buffers non-dynamic. You can omit calling update() for these rays.
  78. *
  79. * @param {integer} ramification Greater than 0. Maximum number of child subrays a subray can have. Default: 5
  80. *
  81. * @param {integer} maxSubrayRecursion Greater than 0. Maximum level of recursion (subray descendant generations). Default: 3
  82. *
  83. * @param {double} recursionProbability From 0 to 1. The lower the value, the less chance each new generation of subrays has to generate new subrays. Default: 0.6
  84. *
  85. * @param {boolean} generateUVs If true, the ray geometry will have uv coordinates generated. u runs along the ray, and v across its perimeter. Default: false.
  86. *
  87. * @param {Object} randomGenerator Set here your random number generator which will seed the SimplexNoise and other decisions during ray tree creation.
  88. * It can be used to generate repeatable rays. For that, set also the noiseSeed parameter, and each ray created with that generator and seed pair will be identical in time.
  89. * The randomGenerator parameter should be an object with a random() function similar to Math.random, but seedable.
  90. * It must have also a getSeed() method, which returns the current seed, and a setSeed( seed ) method, which accepts as seed a fractional number from 0 to 1, as well as any other number.
  91. * The default value is an internal generator for some uses and Math.random for others (It is non-repeatable even if noiseSeed is supplied)
  92. *
  93. * @param {double} noiseSeed Seed used to make repeatable rays (see the randomGenerator)
  94. *
  95. * @param {function} onDecideSubrayCreation Set this to change the callback which decides subray creation. You can look at the default callback in the code (createDefaultSubrayCreationCallbacks)for more info.
  96. *
  97. * @param {function} onSubrayCreation This is another callback, more simple than the previous one. It can be used to adapt the form of subrays or other parameters once a subray has been created and initialized. It is used in the examples to adapt subrays to a sphere or to a plane.
  98. *
  99. *
  100. */
  101. THREE.LightningStrike = function ( rayParameters ) {
  102. THREE.BufferGeometry.call( this );
  103. this.type = 'LightningStrike';
  104. // Set parameters, and set undefined parameters to default values
  105. rayParameters = rayParameters || {};
  106. this.init( THREE.LightningStrike.copyParameters( rayParameters, rayParameters ) );
  107. // Creates and populates the mesh
  108. this.createMesh();
  109. };
  110. THREE.LightningStrike.prototype = Object.create( THREE.BufferGeometry.prototype );
  111. THREE.LightningStrike.prototype.constructor = THREE.LightningStrike;
  112. THREE.LightningStrike.prototype.isLightningStrike = true;
  113. // Ray states
  114. THREE.LightningStrike.RAY_INITIALIZED = 0;
  115. THREE.LightningStrike.RAY_UNBORN = 1;
  116. THREE.LightningStrike.RAY_PROPAGATING = 2;
  117. THREE.LightningStrike.RAY_STEADY = 3;
  118. THREE.LightningStrike.RAY_VANISHING = 4;
  119. THREE.LightningStrike.RAY_EXTINGUISHED = 5;
  120. THREE.LightningStrike.COS30DEG = Math.cos( 30 * Math.PI / 180 );
  121. THREE.LightningStrike.SIN30DEG = Math.sin( 30 * Math.PI / 180 );
  122. THREE.LightningStrike.createRandomGenerator = function () {
  123. var numSeeds = 2053;
  124. var seeds = [];
  125. for ( var i = 0; i < numSeeds; i ++ ) {
  126. seeds.push( Math.random() );
  127. }
  128. var generator = {
  129. currentSeed: 0,
  130. random: function () {
  131. var value = seeds[ generator.currentSeed ];
  132. generator.currentSeed = ( generator.currentSeed + 1 ) % numSeeds;
  133. return value;
  134. },
  135. getSeed: function () {
  136. return generator.currentSeed / numSeeds;
  137. },
  138. setSeed: function ( seed ) {
  139. generator.currentSeed = Math.floor( seed * numSeeds ) % numSeeds;
  140. }
  141. };
  142. return generator;
  143. };
  144. THREE.LightningStrike.copyParameters = function ( dest, source ) {
  145. source = source || {};
  146. dest = dest || {};
  147. var vecCopy = function ( v ) {
  148. if ( source === dest ) {
  149. return v;
  150. } else {
  151. return v.clone();
  152. }
  153. };
  154. dest.sourceOffset = source.sourceOffset !== undefined ? vecCopy( source.sourceOffset ) : new THREE.Vector3( 0, 100, 0 ),
  155. dest.destOffset = source.destOffset !== undefined ? vecCopy( source.destOffset ) : new THREE.Vector3( 0, 0, 0 ),
  156. dest.timeScale = source.timeScale !== undefined ? source.timeScale : 1,
  157. dest.roughness = source.roughness !== undefined ? source.roughness : 0.9,
  158. dest.straightness = source.straightness !== undefined ? source.straightness : 0.7,
  159. dest.up0 = source.up0 !== undefined ? vecCopy( source.up0 ) : new THREE.Vector3( 0, 0, 1 );
  160. dest.up1 = source.up1 !== undefined ? vecCopy( source.up1 ) : new THREE.Vector3( 0, 0, 1 ),
  161. dest.radius0 = source.radius0 !== undefined ? source.radius0 : 1,
  162. dest.radius1 = source.radius1 !== undefined ? source.radius1 : 1,
  163. dest.radius0Factor = source.radius0Factor !== undefined ? source.radius0Factor : 0.5,
  164. dest.radius1Factor = source.radius1Factor !== undefined ? source.radius1Factor : 0.2,
  165. dest.minRadius = source.minRadius !== undefined ? source.minRadius : 0.2,
  166. // These parameters should not be changed after lightning creation. They can be changed but the ray will change its form abruptly:
  167. dest.isEternal = source.isEternal !== undefined ? source.isEternal : ( source.birthTime === undefined || source.deathTime === undefined ),
  168. dest.birthTime = source.birthTime,
  169. dest.deathTime = source.deathTime,
  170. dest.propagationTimeFactor = source.propagationTimeFactor !== undefined ? source.propagationTimeFactor : 0.1,
  171. dest.vanishingTimeFactor = source.vanishingTimeFactor !== undefined ? source.vanishingTimeFactor : 0.9,
  172. dest.subrayPeriod = source.subrayPeriod !== undefined ? source.subrayPeriod : 4,
  173. dest.subrayDutyCycle = source.subrayDutyCycle !== undefined ? source.subrayDutyCycle : 0.6;
  174. // These parameters cannot change after lightning creation:
  175. dest.maxIterations = source.maxIterations !== undefined ? source.maxIterations : 9;
  176. dest.isStatic = source.isStatic !== undefined ? source.isStatic : false;
  177. dest.ramification = source.ramification !== undefined ? source.ramification : 5;
  178. dest.maxSubrayRecursion = source.maxSubrayRecursion !== undefined ? source.maxSubrayRecursion : 3;
  179. dest.recursionProbability = source.recursionProbability !== undefined ? source.recursionProbability : 0.6;
  180. dest.generateUVs = source.generateUVs !== undefined ? source.generateUVs : false;
  181. dest.randomGenerator = source.randomGenerator,
  182. dest.noiseSeed = source.noiseSeed,
  183. dest.onDecideSubrayCreation = source.onDecideSubrayCreation,
  184. dest.onSubrayCreation = source.onSubrayCreation;
  185. return dest;
  186. };
  187. THREE.LightningStrike.prototype.update = function ( time ) {
  188. if ( this.isStatic ) return;
  189. if ( this.rayParameters.isEternal || ( this.rayParameters.birthTime <= time && time <= this.rayParameters.deathTime ) ) {
  190. this.updateMesh( time );
  191. if ( time < this.subrays[ 0 ].endPropagationTime ) {
  192. this.state = THREE.LightningStrike.RAY_PROPAGATING;
  193. } else if ( time > this.subrays[ 0 ].beginVanishingTime ) {
  194. this.state = THREE.LightningStrike.RAY_VANISHING;
  195. } else {
  196. this.state = THREE.LightningStrike.RAY_STEADY;
  197. }
  198. this.visible = true;
  199. } else {
  200. this.visible = false;
  201. if ( time < this.rayParameters.birthTime ) {
  202. this.state = THREE.LightningStrike.RAY_UNBORN;
  203. } else {
  204. this.state = THREE.LightningStrike.RAY_EXTINGUISHED;
  205. }
  206. }
  207. };
  208. THREE.LightningStrike.prototype.init = function ( rayParameters ) {
  209. // Init all the state from the parameters
  210. this.rayParameters = rayParameters;
  211. // These parameters cannot change after lightning creation:
  212. this.maxIterations = rayParameters.maxIterations !== undefined ? Math.floor( rayParameters.maxIterations ) : 9;
  213. rayParameters.maxIterations = this.maxIterations;
  214. this.isStatic = rayParameters.isStatic !== undefined ? rayParameters.isStatic : false;
  215. rayParameters.isStatic = this.isStatic;
  216. this.ramification = rayParameters.ramification !== undefined ? Math.floor( rayParameters.ramification ) : 5;
  217. rayParameters.ramification = this.ramification;
  218. this.maxSubrayRecursion = rayParameters.maxSubrayRecursion !== undefined ? Math.floor( rayParameters.maxSubrayRecursion ) : 3;
  219. rayParameters.maxSubrayRecursion = this.maxSubrayRecursion;
  220. this.recursionProbability = rayParameters.recursionProbability !== undefined ? rayParameters.recursionProbability : 0.6;
  221. rayParameters.recursionProbability = this.recursionProbability;
  222. this.generateUVs = rayParameters.generateUVs !== undefined ? rayParameters.generateUVs : false;
  223. rayParameters.generateUVs = this.generateUVs;
  224. // Random generator
  225. if ( rayParameters.randomGenerator !== undefined ) {
  226. this.randomGenerator = rayParameters.randomGenerator;
  227. this.seedGenerator = rayParameters.randomGenerator;
  228. if ( rayParameters.noiseSeed !== undefined ) {
  229. this.seedGenerator.setSeed( rayParameters.noiseSeed );
  230. }
  231. } else {
  232. this.randomGenerator = THREE.LightningStrike.createRandomGenerator();
  233. this.seedGenerator = Math;
  234. }
  235. // Ray creation callbacks
  236. if ( rayParameters.onDecideSubrayCreation !== undefined ) {
  237. this.onDecideSubrayCreation = rayParameters.onDecideSubrayCreation;
  238. } else {
  239. this.createDefaultSubrayCreationCallbacks();
  240. if ( rayParameters.onSubrayCreation !== undefined ) {
  241. this.onSubrayCreation = rayParameters.onSubrayCreation;
  242. }
  243. }
  244. // Internal state
  245. this.state = THREE.LightningStrike.RAY_INITIALIZED;
  246. this.maxSubrays = Math.ceil( 1 + Math.pow( this.ramification, Math.max( 0, this.maxSubrayRecursion - 1 ) ) );
  247. rayParameters.maxSubrays = this.maxSubrays;
  248. this.maxRaySegments = 2 * ( 1 << this.maxIterations );
  249. this.subrays = [];
  250. for ( var i = 0; i < this.maxSubrays; i ++ ) {
  251. this.subrays.push( this.createSubray() );
  252. }
  253. this.raySegments = [];
  254. for ( var i = 0; i < this.maxRaySegments; i ++ ) {
  255. this.raySegments.push( this.createSegment() );
  256. }
  257. this.time = 0;
  258. this.timeFraction = 0;
  259. this.currentSegmentCallback = null;
  260. this.currentCreateTriangleVertices = this.generateUVs ? this.createTriangleVerticesWithUVs : this.createTriangleVerticesWithoutUVs;
  261. this.numSubrays = 0;
  262. this.currentSubray = null;
  263. this.currentSegmentIndex = 0;
  264. this.isInitialSegment = false;
  265. this.subrayProbability = 0;
  266. this.currentVertex = 0;
  267. this.currentIndex = 0;
  268. this.currentCoordinate = 0;
  269. this.currentUVCoordinate = 0;
  270. this.vertices = null;
  271. this.uvs = null;
  272. this.indices = null;
  273. this.positionAttribute = null;
  274. this.uvsAttribute = null;
  275. this.simplexX = new THREE.SimplexNoise( this.seedGenerator );
  276. this.simplexY = new THREE.SimplexNoise( this.seedGenerator );
  277. this.simplexZ = new THREE.SimplexNoise( this.seedGenerator );
  278. // Temp vectors
  279. this.forwards = new THREE.Vector3();
  280. this.forwardsFill = new THREE.Vector3();
  281. this.side = new THREE.Vector3();
  282. this.down = new THREE.Vector3();
  283. this.middlePos = new THREE.Vector3();
  284. this.middleLinPos = new THREE.Vector3();
  285. this.newPos = new THREE.Vector3();
  286. this.vPos = new THREE.Vector3();
  287. this.cross1 = new THREE.Vector3();
  288. };
  289. THREE.LightningStrike.prototype.createMesh = function () {
  290. var maxDrawableSegmentsPerSubRay = 1 << this.maxIterations;
  291. var maxVerts = 3 * ( maxDrawableSegmentsPerSubRay + 1 ) * this.maxSubrays;
  292. var maxIndices = 18 * maxDrawableSegmentsPerSubRay * this.maxSubrays;
  293. this.vertices = new Float32Array( maxVerts * 3 );
  294. this.indices = new Uint32Array( maxIndices );
  295. if ( this.generateUVs ) {
  296. this.uvs = new Float32Array( maxVerts * 2 );
  297. }
  298. // Populate the mesh
  299. this.fillMesh( 0 );
  300. this.setIndex( new THREE.Uint32BufferAttribute( this.indices, 1 ) );
  301. this.positionAttribute = new THREE.Float32BufferAttribute( this.vertices, 3 );
  302. this.setAttribute( 'position', this.positionAttribute );
  303. if ( this.generateUVs ) {
  304. this.uvsAttribute = new THREE.Float32BufferAttribute( new Float32Array( this.uvs ), 2 );
  305. this.setAttribute( 'uv', this.uvsAttribute );
  306. }
  307. if ( ! this.isStatic ) {
  308. this.index.usage = THREE.DynamicDrawUsage;
  309. this.positionAttribute.usage = THREE.DynamicDrawUsage;
  310. if ( this.generateUVs ) {
  311. this.uvsAttribute.usage = THREE.DynamicDrawUsage;
  312. }
  313. }
  314. // Store buffers for later modification
  315. this.vertices = this.positionAttribute.array;
  316. this.indices = this.index.array;
  317. if ( this.generateUVs ) {
  318. this.uvs = this.uvsAttribute.array;
  319. }
  320. };
  321. THREE.LightningStrike.prototype.updateMesh = function ( time ) {
  322. this.fillMesh( time );
  323. this.drawRange.count = this.currentIndex;
  324. this.index.needsUpdate = true;
  325. this.positionAttribute.needsUpdate = true;
  326. if ( this.generateUVs ) {
  327. this.uvsAttribute.needsUpdate = true;
  328. }
  329. };
  330. THREE.LightningStrike.prototype.fillMesh = function ( time ) {
  331. var scope = this;
  332. this.currentVertex = 0;
  333. this.currentIndex = 0;
  334. this.currentCoordinate = 0;
  335. this.currentUVCoordinate = 0;
  336. this.fractalRay( time, function fillVertices( segment ) {
  337. var subray = scope.currentSubray;
  338. if ( time < subray.birthTime ) { //&& ( ! this.rayParameters.isEternal || scope.currentSubray.recursion > 0 ) ) {
  339. return;
  340. } else if ( this.rayParameters.isEternal && scope.currentSubray.recursion == 0 ) {
  341. // Eternal rays don't propagate nor vanish, but its subrays do
  342. scope.createPrism( segment );
  343. scope.onDecideSubrayCreation( segment, scope );
  344. } else if ( time < subray.endPropagationTime ) {
  345. if ( scope.timeFraction >= segment.fraction0 * subray.propagationTimeFactor ) {
  346. // Ray propagation has arrived to this segment
  347. scope.createPrism( segment );
  348. scope.onDecideSubrayCreation( segment, scope );
  349. }
  350. } else if ( time < subray.beginVanishingTime ) {
  351. // Ray is steady (nor propagating nor vanishing)
  352. scope.createPrism( segment );
  353. scope.onDecideSubrayCreation( segment, scope );
  354. } else {
  355. if ( scope.timeFraction <= subray.vanishingTimeFactor + segment.fraction1 * ( 1 - subray.vanishingTimeFactor ) ) {
  356. // Segment has not yet vanished
  357. scope.createPrism( segment );
  358. }
  359. scope.onDecideSubrayCreation( segment, scope );
  360. }
  361. } );
  362. };
  363. THREE.LightningStrike.prototype.addNewSubray = function ( /*rayParameters*/ ) {
  364. return this.subrays[ this.numSubrays ++ ];
  365. };
  366. THREE.LightningStrike.prototype.initSubray = function ( subray, rayParameters ) {
  367. subray.pos0.copy( rayParameters.sourceOffset );
  368. subray.pos1.copy( rayParameters.destOffset );
  369. subray.up0.copy( rayParameters.up0 );
  370. subray.up1.copy( rayParameters.up1 );
  371. subray.radius0 = rayParameters.radius0;
  372. subray.radius1 = rayParameters.radius1;
  373. subray.birthTime = rayParameters.birthTime;
  374. subray.deathTime = rayParameters.deathTime;
  375. subray.timeScale = rayParameters.timeScale;
  376. subray.roughness = rayParameters.roughness;
  377. subray.straightness = rayParameters.straightness;
  378. subray.propagationTimeFactor = rayParameters.propagationTimeFactor;
  379. subray.vanishingTimeFactor = rayParameters.vanishingTimeFactor;
  380. subray.maxIterations = this.maxIterations;
  381. subray.seed = rayParameters.noiseSeed !== undefined ? rayParameters.noiseSeed : 0;
  382. subray.recursion = 0;
  383. };
  384. THREE.LightningStrike.prototype.fractalRay = function ( time, segmentCallback ) {
  385. this.time = time;
  386. this.currentSegmentCallback = segmentCallback;
  387. this.numSubrays = 0;
  388. // Add the top level subray
  389. this.initSubray( this.addNewSubray(), this.rayParameters );
  390. // Process all subrays that are being generated until consuming all of them
  391. for ( var subrayIndex = 0; subrayIndex < this.numSubrays; subrayIndex ++ ) {
  392. var subray = this.subrays[ subrayIndex ];
  393. this.currentSubray = subray;
  394. this.randomGenerator.setSeed( subray.seed );
  395. subray.endPropagationTime = THREE.MathUtils.lerp( subray.birthTime, subray.deathTime, subray.propagationTimeFactor );
  396. subray.beginVanishingTime = THREE.MathUtils.lerp( subray.deathTime, subray.birthTime, 1 - subray.vanishingTimeFactor );
  397. var random1 = this.randomGenerator.random;
  398. subray.linPos0.set( random1(), random1(), random1() ).multiplyScalar( 1000 );
  399. subray.linPos1.set( random1(), random1(), random1() ).multiplyScalar( 1000 );
  400. this.timeFraction = ( time - subray.birthTime ) / ( subray.deathTime - subray.birthTime );
  401. this.currentSegmentIndex = 0;
  402. this.isInitialSegment = true;
  403. var segment = this.getNewSegment();
  404. segment.iteration = 0;
  405. segment.pos0.copy( subray.pos0 );
  406. segment.pos1.copy( subray.pos1 );
  407. segment.linPos0.copy( subray.linPos0 );
  408. segment.linPos1.copy( subray.linPos1 );
  409. segment.up0.copy( subray.up0 );
  410. segment.up1.copy( subray.up1 );
  411. segment.radius0 = subray.radius0;
  412. segment.radius1 = subray.radius1;
  413. segment.fraction0 = 0;
  414. segment.fraction1 = 1;
  415. segment.positionVariationFactor = 1 - subray.straightness;
  416. this.subrayProbability = this.ramification * Math.pow( this.recursionProbability, subray.recursion ) / ( 1 << subray.maxIterations );
  417. this.fractalRayRecursive( segment );
  418. }
  419. this.currentSegmentCallback = null;
  420. this.currentSubray = null;
  421. };
  422. THREE.LightningStrike.prototype.fractalRayRecursive = function ( segment ) {
  423. // Leave recursion condition
  424. if ( segment.iteration >= this.currentSubray.maxIterations ) {
  425. this.currentSegmentCallback( segment );
  426. return;
  427. }
  428. // Interpolation
  429. this.forwards.subVectors( segment.pos1, segment.pos0 );
  430. var lForwards = this.forwards.length();
  431. if ( lForwards < 0.000001 ) {
  432. this.forwards.set( 0, 0, 0.01 );
  433. lForwards = this.forwards.length();
  434. }
  435. var middleRadius = ( segment.radius0 + segment.radius1 ) * 0.5;
  436. var middleFraction = ( segment.fraction0 + segment.fraction1 ) * 0.5;
  437. var timeDimension = this.time * this.currentSubray.timeScale * Math.pow( 2, segment.iteration );
  438. this.middlePos.lerpVectors( segment.pos0, segment.pos1, 0.5 );
  439. this.middleLinPos.lerpVectors( segment.linPos0, segment.linPos1, 0.5 );
  440. var p = this.middleLinPos;
  441. // Noise
  442. this.newPos.set( this.simplexX.noise4d( p.x, p.y, p.z, timeDimension ),
  443. this.simplexY.noise4d( p.x, p.y, p.z, timeDimension ),
  444. this.simplexZ.noise4d( p.x, p.y, p.z, timeDimension ) );
  445. this.newPos.multiplyScalar( segment.positionVariationFactor * lForwards );
  446. this.newPos.add( this.middlePos );
  447. // Recursion
  448. var newSegment1 = this.getNewSegment();
  449. newSegment1.pos0.copy( segment.pos0 );
  450. newSegment1.pos1.copy( this.newPos );
  451. newSegment1.linPos0.copy( segment.linPos0 );
  452. newSegment1.linPos1.copy( this.middleLinPos );
  453. newSegment1.up0.copy( segment.up0 );
  454. newSegment1.up1.copy( segment.up1 );
  455. newSegment1.radius0 = segment.radius0;
  456. newSegment1.radius1 = middleRadius;
  457. newSegment1.fraction0 = segment.fraction0;
  458. newSegment1.fraction1 = middleFraction;
  459. newSegment1.positionVariationFactor = segment.positionVariationFactor * this.currentSubray.roughness;
  460. newSegment1.iteration = segment.iteration + 1;
  461. var newSegment2 = this.getNewSegment();
  462. newSegment2.pos0.copy( this.newPos );
  463. newSegment2.pos1.copy( segment.pos1 );
  464. newSegment2.linPos0.copy( this.middleLinPos );
  465. newSegment2.linPos1.copy( segment.linPos1 );
  466. this.cross1.crossVectors( segment.up0, this.forwards.normalize() );
  467. newSegment2.up0.crossVectors( this.forwards, this.cross1 ).normalize();
  468. newSegment2.up1.copy( segment.up1 );
  469. newSegment2.radius0 = middleRadius;
  470. newSegment2.radius1 = segment.radius1;
  471. newSegment2.fraction0 = middleFraction;
  472. newSegment2.fraction1 = segment.fraction1;
  473. newSegment2.positionVariationFactor = segment.positionVariationFactor * this.currentSubray.roughness;
  474. newSegment2.iteration = segment.iteration + 1;
  475. this.fractalRayRecursive( newSegment1 );
  476. this.fractalRayRecursive( newSegment2 );
  477. };
  478. THREE.LightningStrike.prototype.createPrism = function ( segment ) {
  479. // Creates one triangular prism and its vertices at the segment
  480. this.forwardsFill.subVectors( segment.pos1, segment.pos0 ).normalize();
  481. if ( this.isInitialSegment ) {
  482. this.currentCreateTriangleVertices( segment.pos0, segment.up0, this.forwardsFill, segment.radius0, 0 );
  483. this.isInitialSegment = false;
  484. }
  485. this.currentCreateTriangleVertices( segment.pos1, segment.up0, this.forwardsFill, segment.radius1, segment.fraction1 );
  486. this.createPrismFaces();
  487. };
  488. THREE.LightningStrike.prototype.createTriangleVerticesWithoutUVs = function ( pos, up, forwards, radius ) {
  489. // Create an equilateral triangle (only vertices)
  490. this.side.crossVectors( up, forwards ).multiplyScalar( radius * THREE.LightningStrike.COS30DEG );
  491. this.down.copy( up ).multiplyScalar( - radius * THREE.LightningStrike.SIN30DEG );
  492. var p = this.vPos;
  493. var v = this.vertices;
  494. p.copy( pos ).sub( this.side ).add( this.down );
  495. v[ this.currentCoordinate ++ ] = p.x;
  496. v[ this.currentCoordinate ++ ] = p.y;
  497. v[ this.currentCoordinate ++ ] = p.z;
  498. p.copy( pos ).add( this.side ).add( this.down );
  499. v[ this.currentCoordinate ++ ] = p.x;
  500. v[ this.currentCoordinate ++ ] = p.y;
  501. v[ this.currentCoordinate ++ ] = p.z;
  502. p.copy( up ).multiplyScalar( radius ).add( pos );
  503. v[ this.currentCoordinate ++ ] = p.x;
  504. v[ this.currentCoordinate ++ ] = p.y;
  505. v[ this.currentCoordinate ++ ] = p.z;
  506. this.currentVertex += 3;
  507. };
  508. THREE.LightningStrike.prototype.createTriangleVerticesWithUVs = function ( pos, up, forwards, radius, u ) {
  509. // Create an equilateral triangle (only vertices)
  510. this.side.crossVectors( up, forwards ).multiplyScalar( radius * THREE.LightningStrike.COS30DEG );
  511. this.down.copy( up ).multiplyScalar( - radius * THREE.LightningStrike.SIN30DEG );
  512. var p = this.vPos;
  513. var v = this.vertices;
  514. var uv = this.uvs;
  515. p.copy( pos ).sub( this.side ).add( this.down );
  516. v[ this.currentCoordinate ++ ] = p.x;
  517. v[ this.currentCoordinate ++ ] = p.y;
  518. v[ this.currentCoordinate ++ ] = p.z;
  519. uv[ this.currentUVCoordinate ++ ] = u;
  520. uv[ this.currentUVCoordinate ++ ] = 0;
  521. p.copy( pos ).add( this.side ).add( this.down );
  522. v[ this.currentCoordinate ++ ] = p.x;
  523. v[ this.currentCoordinate ++ ] = p.y;
  524. v[ this.currentCoordinate ++ ] = p.z;
  525. uv[ this.currentUVCoordinate ++ ] = u;
  526. uv[ this.currentUVCoordinate ++ ] = 0.5;
  527. p.copy( up ).multiplyScalar( radius ).add( pos );
  528. v[ this.currentCoordinate ++ ] = p.x;
  529. v[ this.currentCoordinate ++ ] = p.y;
  530. v[ this.currentCoordinate ++ ] = p.z;
  531. uv[ this.currentUVCoordinate ++ ] = u;
  532. uv[ this.currentUVCoordinate ++ ] = 1;
  533. this.currentVertex += 3;
  534. };
  535. THREE.LightningStrike.prototype.createPrismFaces = function ( vertex/*, index*/ ) {
  536. var indices = this.indices;
  537. var vertex = this.currentVertex - 6;
  538. indices[ this.currentIndex ++ ] = vertex + 1;
  539. indices[ this.currentIndex ++ ] = vertex + 2;
  540. indices[ this.currentIndex ++ ] = vertex + 5;
  541. indices[ this.currentIndex ++ ] = vertex + 1;
  542. indices[ this.currentIndex ++ ] = vertex + 5;
  543. indices[ this.currentIndex ++ ] = vertex + 4;
  544. indices[ this.currentIndex ++ ] = vertex + 0;
  545. indices[ this.currentIndex ++ ] = vertex + 1;
  546. indices[ this.currentIndex ++ ] = vertex + 4;
  547. indices[ this.currentIndex ++ ] = vertex + 0;
  548. indices[ this.currentIndex ++ ] = vertex + 4;
  549. indices[ this.currentIndex ++ ] = vertex + 3;
  550. indices[ this.currentIndex ++ ] = vertex + 2;
  551. indices[ this.currentIndex ++ ] = vertex + 0;
  552. indices[ this.currentIndex ++ ] = vertex + 3;
  553. indices[ this.currentIndex ++ ] = vertex + 2;
  554. indices[ this.currentIndex ++ ] = vertex + 3;
  555. indices[ this.currentIndex ++ ] = vertex + 5;
  556. };
  557. THREE.LightningStrike.prototype.createDefaultSubrayCreationCallbacks = function () {
  558. var random1 = this.randomGenerator.random;
  559. this.onDecideSubrayCreation = function ( segment, lightningStrike ) {
  560. // Decide subrays creation at parent (sub)ray segment
  561. var subray = lightningStrike.currentSubray;
  562. var period = lightningStrike.rayParameters.subrayPeriod;
  563. var dutyCycle = lightningStrike.rayParameters.subrayDutyCycle;
  564. var phase0 = ( lightningStrike.rayParameters.isEternal && subray.recursion == 0 ) ? - random1() * period : THREE.MathUtils.lerp( subray.birthTime, subray.endPropagationTime, segment.fraction0 ) - random1() * period;
  565. var phase = lightningStrike.time - phase0;
  566. var currentCycle = Math.floor( phase / period );
  567. var childSubraySeed = random1() * ( currentCycle + 1 );
  568. var isActive = phase % period <= dutyCycle * period;
  569. var probability = 0;
  570. if ( isActive ) {
  571. probability = lightningStrike.subrayProbability;
  572. // Distribution test: probability *= segment.fraction0 > 0.5 && segment.fraction0 < 0.9 ? 1 / 0.4 : 0;
  573. }
  574. if ( subray.recursion < lightningStrike.maxSubrayRecursion && lightningStrike.numSubrays < lightningStrike.maxSubrays && random1() < probability ) {
  575. var childSubray = lightningStrike.addNewSubray();
  576. var parentSeed = lightningStrike.randomGenerator.getSeed();
  577. childSubray.seed = childSubraySeed;
  578. lightningStrike.randomGenerator.setSeed( childSubraySeed );
  579. childSubray.recursion = subray.recursion + 1;
  580. childSubray.maxIterations = Math.max( 1, subray.maxIterations - 1 );
  581. childSubray.linPos0.set( random1(), random1(), random1() ).multiplyScalar( 1000 );
  582. childSubray.linPos1.set( random1(), random1(), random1() ).multiplyScalar( 1000 );
  583. childSubray.up0.copy( subray.up0 );
  584. childSubray.up1.copy( subray.up1 );
  585. childSubray.radius0 = segment.radius0 * lightningStrike.rayParameters.radius0Factor;
  586. childSubray.radius1 = Math.min( lightningStrike.rayParameters.minRadius, segment.radius1 * lightningStrike.rayParameters.radius1Factor );
  587. childSubray.birthTime = phase0 + ( currentCycle ) * period;
  588. childSubray.deathTime = childSubray.birthTime + period * dutyCycle;
  589. if ( ! lightningStrike.rayParameters.isEternal && subray.recursion == 0 ) {
  590. childSubray.birthTime = Math.max( childSubray.birthTime, subray.birthTime );
  591. childSubray.deathTime = Math.min( childSubray.deathTime, subray.deathTime );
  592. }
  593. childSubray.timeScale = subray.timeScale * 2;
  594. childSubray.roughness = subray.roughness;
  595. childSubray.straightness = subray.straightness;
  596. childSubray.propagationTimeFactor = subray.propagationTimeFactor;
  597. childSubray.vanishingTimeFactor = subray.vanishingTimeFactor;
  598. lightningStrike.onSubrayCreation( segment, subray, childSubray, lightningStrike );
  599. lightningStrike.randomGenerator.setSeed( parentSeed );
  600. }
  601. };
  602. var vec1Pos = new THREE.Vector3();
  603. var vec2Forward = new THREE.Vector3();
  604. var vec3Side = new THREE.Vector3();
  605. var vec4Up = new THREE.Vector3();
  606. this.onSubrayCreation = function ( segment, parentSubray, childSubray, lightningStrike ) {
  607. // Decide childSubray origin and destination positions (pos0 and pos1) and possibly other properties of childSubray
  608. // Just use the default cone position generator
  609. lightningStrike.subrayCylinderPosition( segment, parentSubray, childSubray, 0.5, 0.6, 0.2 );
  610. };
  611. this.subrayConePosition = function ( segment, parentSubray, childSubray, heightFactor, sideWidthFactor, minSideWidthFactor ) {
  612. // Sets childSubray pos0 and pos1 in a cone
  613. childSubray.pos0.copy( segment.pos0 );
  614. vec1Pos.subVectors( parentSubray.pos1, parentSubray.pos0 );
  615. vec2Forward.copy( vec1Pos ).normalize();
  616. vec1Pos.multiplyScalar( segment.fraction0 + ( 1 - segment.fraction0 ) * ( random1() * heightFactor ) );
  617. var length = vec1Pos.length();
  618. vec3Side.crossVectors( parentSubray.up0, vec2Forward );
  619. var angle = 2 * Math.PI * random1();
  620. vec3Side.multiplyScalar( Math.cos( angle ) );
  621. vec4Up.copy( parentSubray.up0 ).multiplyScalar( Math.sin( angle ) );
  622. childSubray.pos1.copy( vec3Side ).add( vec4Up ).multiplyScalar( length * sideWidthFactor * ( minSideWidthFactor + random1() * ( 1 - minSideWidthFactor ) ) ).add( vec1Pos ).add( parentSubray.pos0 );
  623. };
  624. this.subrayCylinderPosition = function ( segment, parentSubray, childSubray, heightFactor, sideWidthFactor, minSideWidthFactor ) {
  625. // Sets childSubray pos0 and pos1 in a cylinder
  626. childSubray.pos0.copy( segment.pos0 );
  627. vec1Pos.subVectors( parentSubray.pos1, parentSubray.pos0 );
  628. vec2Forward.copy( vec1Pos ).normalize();
  629. vec1Pos.multiplyScalar( segment.fraction0 + ( 1 - segment.fraction0 ) * ( ( 2 * random1() - 1 ) * heightFactor ) );
  630. var length = vec1Pos.length();
  631. vec3Side.crossVectors( parentSubray.up0, vec2Forward );
  632. var angle = 2 * Math.PI * random1();
  633. vec3Side.multiplyScalar( Math.cos( angle ) );
  634. vec4Up.copy( parentSubray.up0 ).multiplyScalar( Math.sin( angle ) );
  635. childSubray.pos1.copy( vec3Side ).add( vec4Up ).multiplyScalar( length * sideWidthFactor * ( minSideWidthFactor + random1() * ( 1 - minSideWidthFactor ) ) ).add( vec1Pos ).add( parentSubray.pos0 );
  636. };
  637. };
  638. THREE.LightningStrike.prototype.createSubray = function () {
  639. return {
  640. seed: 0,
  641. maxIterations: 0,
  642. recursion: 0,
  643. pos0: new THREE.Vector3(),
  644. pos1: new THREE.Vector3(),
  645. linPos0: new THREE.Vector3(),
  646. linPos1: new THREE.Vector3(),
  647. up0: new THREE.Vector3(),
  648. up1: new THREE.Vector3(),
  649. radius0: 0,
  650. radius1: 0,
  651. birthTime: 0,
  652. deathTime: 0,
  653. timeScale: 0,
  654. roughness: 0,
  655. straightness: 0,
  656. propagationTimeFactor: 0,
  657. vanishingTimeFactor: 0,
  658. endPropagationTime: 0,
  659. beginVanishingTime: 0
  660. };
  661. };
  662. THREE.LightningStrike.prototype.createSegment = function () {
  663. return {
  664. iteration: 0,
  665. pos0: new THREE.Vector3(),
  666. pos1: new THREE.Vector3(),
  667. linPos0: new THREE.Vector3(),
  668. linPos1: new THREE.Vector3(),
  669. up0: new THREE.Vector3(),
  670. up1: new THREE.Vector3(),
  671. radius0: 0,
  672. radius1: 0,
  673. fraction0: 0,
  674. fraction1: 0,
  675. positionVariationFactor: 0
  676. };
  677. };
  678. THREE.LightningStrike.prototype.getNewSegment = function () {
  679. return this.raySegments[ this.currentSegmentIndex ++ ];
  680. };
  681. THREE.LightningStrike.prototype.copy = function ( source ) {
  682. THREE.BufferGeometry.prototype.copy.call( this, source );
  683. this.init( THREE.LightningStrike.copyParameters( {}, source.rayParameters ) );
  684. return this;
  685. };
  686. THREE.LightningStrike.prototype.clone = function () {
  687. return new this.constructor( THREE.LightningStrike.copyParameters( {}, this.rayParameters ) );
  688. };