2
0

LightningStrike.js 33 KB

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