afxMagicMissile.cpp 65 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117
  1. //-----------------------------------------------------------------------------
  2. // Copyright (c) 2012 GarageGames, LLC
  3. //
  4. // Permission is hereby granted, free of charge, to any person obtaining a copy
  5. // of this software and associated documentation files (the "Software"), to
  6. // deal in the Software without restriction, including without limitation the
  7. // rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
  8. // sell copies of the Software, and to permit persons to whom the Software is
  9. // furnished to do so, subject to the following conditions:
  10. //
  11. // The above copyright notice and this permission notice shall be included in
  12. // all copies or substantial portions of the Software.
  13. //
  14. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  15. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  16. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  17. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  18. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
  19. // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
  20. // IN THE SOFTWARE.
  21. //-----------------------------------------------------------------------------
  22. //~~~~~~~~~~~~~~~~~~~~//~~~~~~~~~~~~~~~~~~~~//~~~~~~~~~~~~~~~~~~~~//~~~~~~~~~~~~~~~~~~~~~//
  23. // Arcane-FX for MIT Licensed Open Source version of Torque 3D from GarageGames
  24. // Copyright (C) 2015 Faust Logic, Inc.
  25. //
  26. // afxMagicMissile is a heavily modified variation of the stock Projectile class. In
  27. // addition to numerous AFX customizations, it also incorporates functionality based on
  28. // the following TGE resources:
  29. //
  30. // Guided or Seeker Projectiles by Derk Adams
  31. // http://www.garagegames.com/index.php?sec=mg&mod=resource&page=view&qid=6778
  32. //
  33. // Projectile Ballistic Coefficients (drag factors) by Mark Owen
  34. // http://www.garagegames.com/index.php?sec=mg&mod=resource&page=view&qid=5128
  35. //
  36. //~~~~~~~~~~~~~~~~~~~~//~~~~~~~~~~~~~~~~~~~~//~~~~~~~~~~~~~~~~~~~~//~~~~~~~~~~~~~~~~~~~~~//
  37. #include "afx/arcaneFX.h"
  38. #include "scene/sceneRenderState.h"
  39. #include "scene/sceneManager.h"
  40. #include "core/resourceManager.h"
  41. #include "ts/tsShapeInstance.h"
  42. #include "sfx/sfxTrack.h"
  43. #include "sfx/sfxSource.h"
  44. #include "sfx/sfxSystem.h"
  45. #include "sfx/sfxTypes.h"
  46. #include "math/mathUtils.h"
  47. #include "math/mathIO.h"
  48. #include "sim/netConnection.h"
  49. #include "T3D/fx/particleEmitter.h"
  50. #include "T3D/fx/splash.h"
  51. #include "T3D/physics/physicsPlugin.h"
  52. #include "T3D/physics/physicsWorld.h"
  53. #include "gfx/gfxTransformSaver.h"
  54. #include "T3D/containerQuery.h"
  55. #include "T3D/lightDescription.h"
  56. #include "console/engineAPI.h"
  57. #include "lighting/lightManager.h"
  58. #include "afx/util/afxEase.h"
  59. #include "afx/afxMagicMissile.h"
  60. #include "afx/afxMagicSpell.h"
  61. #include "afx/afxChoreographer.h"
  62. class ObjectDeleteEvent : public SimEvent
  63. {
  64. public:
  65. void process(SimObject *object)
  66. {
  67. object->deleteObject();
  68. }
  69. };
  70. IMPLEMENT_CO_DATABLOCK_V1(afxMagicMissileData);
  71. ConsoleDocClass( afxMagicMissileData,
  72. "@brief Defines a particular magic-missile type. (Use with afxMagicSpellData.)\n"
  73. "@tsexample\n"
  74. "datablock afxMagicMissileData(Fireball_MM)\n"
  75. "{\n"
  76. " muzzleVelocity = 50;\n"
  77. " velInheritFactor = 0;\n"
  78. " lifetime = 20000;\n"
  79. " isBallistic = true;\n"
  80. " ballisticCoefficient = 0.85;\n"
  81. " gravityMod = 0.05;\n"
  82. " isGuided = true;\n"
  83. " precision = 30;\n"
  84. " trackDelay = 7;\n"
  85. " launchOffset = \"0 0 43.7965\";\n"
  86. " launchOnServerSignal = true;\n"
  87. "};\n"
  88. "@endtsexample\n"
  89. "@ingroup AFX\n"
  90. );
  91. IMPLEMENT_CO_NETOBJECT_V1(afxMagicMissile);
  92. ConsoleDocClass( afxMagicMissile,
  93. "@brief Magic-missile class used internally by afxMagicSpell. Properties of individual missile types are defined using afxMagicMissileData.\n"
  94. "@ingroup AFX\n"
  95. );
  96. /* From stock Projectile code...
  97. IMPLEMENT_CALLBACK( ProjectileData, onExplode, void, ( Projectile* proj, Point3F pos, F32 fade ),
  98. ( proj, pos, fade ),
  99. "Called when a projectile explodes.\n"
  100. "@param proj The projectile exploding.\n"
  101. "@param pos The position of the explosion.\n"
  102. "@param fade The currently fadeValue of the projectile, affects its visibility.\n"
  103. "@see Projectile, ProjectileData\n"
  104. );
  105. IMPLEMENT_CALLBACK( ProjectileData, onCollision, void, ( Projectile* proj, SceneObject* col, F32 fade, Point3F pos, Point3F normal ),
  106. ( proj, col, fade, pos, normal ),
  107. "Called when a projectile collides with another object.\n"
  108. "@param proj The projectile colliding.\n"
  109. "@param col The object hit by the projectile.\n"
  110. "@param fade The current fadeValue of the projectile, affects its visibility.\n"
  111. "@param pos The collision position.\n"
  112. "@param normal The collision normal.\n"
  113. "@see Projectile, ProjectileData\n"
  114. );
  115. const U32 Projectile::csmStaticCollisionMask = TerrainObjectType |
  116. InteriorObjectType |
  117. StaticObjectType;
  118. const U32 Projectile::csmDynamicCollisionMask = PlayerObjectType |
  119. VehicleObjectType |
  120. DamagableItemObjectType;
  121. const U32 Projectile::csmDamageableMask = Projectile::csmDynamicCollisionMask;
  122. U32 Projectile::smProjectileWarpTicks = 5;
  123. */
  124. //--------------------------------------------------------------------------
  125. //
  126. afxMagicMissileData::afxMagicMissileData()
  127. {
  128. projectileShapeName = ST_NULLSTRING;
  129. sound = NULL;
  130. /* From stock Projectile code...
  131. explosion = NULL;
  132. explosionId = 0;
  133. waterExplosion = NULL;
  134. waterExplosionId = 0;
  135. */
  136. /* From stock Projectile code...
  137. faceViewer = false;
  138. */
  139. scale.set( 1.0f, 1.0f, 1.0f );
  140. isBallistic = false;
  141. /* From stock Projectile code...
  142. velInheritFactor = 1.0f;
  143. */
  144. muzzleVelocity = 50;
  145. /* From stock Projectile code...
  146. impactForce = 0.0f;
  147. armingDelay = 0;
  148. fadeDelay = 20000 / 32;
  149. lifetime = 20000 / 32;
  150. activateSeq = -1;
  151. maintainSeq = -1;
  152. */
  153. gravityMod = 1.0;
  154. /* From stock Projectile code...
  155. bounceElasticity = 0.999f;
  156. bounceFriction = 0.3f;
  157. */
  158. particleEmitter = NULL;
  159. particleEmitterId = 0;
  160. particleWaterEmitter = NULL;
  161. particleWaterEmitterId = 0;
  162. splash = NULL;
  163. splashId = 0;
  164. /* From stock Projectile code...
  165. decal = NULL;
  166. decalId = 0;
  167. */
  168. lightDesc = NULL;
  169. lightDescId = 0;
  170. starting_vel_vec.zero();
  171. isGuided = false;
  172. precision = 0;
  173. trackDelay = 0;
  174. ballisticCoefficient = 1.0f;
  175. followTerrain = false;
  176. followTerrainHeight = 0.1f;
  177. followTerrainAdjustRate = 20.0f;
  178. followTerrainAdjustDelay = 0;
  179. lifetime = MaxLifetimeTicks;
  180. collision_mask = arcaneFX::sMissileCollisionMask;
  181. acceleration = 0;
  182. accelDelay = 0;
  183. accelLifetime = 0;
  184. launch_node = ST_NULLSTRING;
  185. launch_offset.zero();
  186. launch_offset_server.zero();
  187. launch_offset_client.zero();
  188. launch_node_offset.zero();
  189. launch_pitch = 0;
  190. launch_pan = 0;
  191. launch_cons_s_spec = ST_NULLSTRING;
  192. launch_cons_c_spec = ST_NULLSTRING;
  193. echo_launch_offset = false;
  194. wiggle_axis_string = ST_NULLSTRING;
  195. wiggle_num_axis = 0;
  196. wiggle_axis = 0;
  197. hover_altitude = 0;
  198. hover_attack_distance = 0;
  199. hover_attack_gradient = 0;
  200. hover_time = 0;
  201. reverse_targeting = false;
  202. caster_safety_time = U32_MAX;
  203. }
  204. afxMagicMissileData::afxMagicMissileData(const afxMagicMissileData& other, bool temp_clone) : GameBaseData(other, temp_clone)
  205. {
  206. projectileShapeName = other.projectileShapeName;
  207. projectileShape = other.projectileShape; // -- TSShape loads using projectileShapeName
  208. sound = other.sound;
  209. splash = other.splash;
  210. splashId = other.splashId; // -- for pack/unpack of splash ptr
  211. lightDesc = other.lightDesc;
  212. lightDescId = other.lightDescId; // -- for pack/unpack of lightDesc ptr
  213. scale = other.scale;
  214. isBallistic = other.isBallistic;
  215. muzzleVelocity = other.muzzleVelocity;
  216. gravityMod = other.gravityMod;
  217. particleEmitter = other.particleEmitter;
  218. particleEmitterId = other.particleEmitterId; // -- for pack/unpack of particleEmitter ptr
  219. particleWaterEmitter = other.particleWaterEmitter;
  220. particleWaterEmitterId = other.particleWaterEmitterId; // -- for pack/unpack of particleWaterEmitter ptr
  221. collision_mask = other.collision_mask;
  222. starting_vel_vec = other.starting_vel_vec;
  223. isGuided = other.isGuided;
  224. precision = other.precision;
  225. trackDelay = other.trackDelay;
  226. ballisticCoefficient = other.ballisticCoefficient;
  227. followTerrain = other.followTerrain;
  228. followTerrainHeight = other.followTerrainHeight;
  229. followTerrainAdjustRate = other.followTerrainAdjustRate;
  230. followTerrainAdjustDelay = other.followTerrainAdjustDelay;
  231. lifetime = other.lifetime;
  232. fadeDelay = other.fadeDelay;
  233. acceleration = other.acceleration;
  234. accelDelay = other.accelDelay;
  235. accelLifetime = other.accelLifetime;
  236. launch_node = other.launch_node;
  237. launch_offset = other.launch_offset;
  238. launch_offset_server = other.launch_offset_server;
  239. launch_offset_client = other.launch_offset_client;
  240. launch_node_offset = other.launch_node_offset;
  241. launch_pitch = other.launch_pitch;
  242. launch_pan = other.launch_pan;
  243. launch_cons_s_spec = other.launch_cons_s_spec;
  244. launch_cons_c_spec = other.launch_cons_c_spec;
  245. launch_cons_s_def = other.launch_cons_s_def;
  246. launch_cons_c_def = other.launch_cons_c_def;
  247. echo_launch_offset = other.echo_launch_offset;
  248. wiggle_magnitudes = other.wiggle_magnitudes;
  249. wiggle_speeds = other.wiggle_speeds;
  250. wiggle_axis_string = other.wiggle_axis_string;
  251. wiggle_num_axis = other.wiggle_num_axis;
  252. wiggle_axis = other.wiggle_axis;
  253. hover_altitude = other.hover_altitude;
  254. hover_attack_distance = other.hover_attack_distance;
  255. hover_attack_gradient = other.hover_attack_gradient;
  256. hover_time = other.hover_time;
  257. reverse_targeting = other.reverse_targeting;
  258. caster_safety_time = other.caster_safety_time;
  259. }
  260. afxMagicMissileData::~afxMagicMissileData()
  261. {
  262. if (wiggle_axis)
  263. delete [] wiggle_axis;
  264. }
  265. afxMagicMissileData* afxMagicMissileData::cloneAndPerformSubstitutions(const SimObject* owner, S32 index)
  266. {
  267. if (!owner || getSubstitutionCount() == 0)
  268. return this;
  269. afxMagicMissileData* sub_missile_db = new afxMagicMissileData(*this, true);
  270. performSubstitutions(sub_missile_db, owner, index);
  271. return sub_missile_db;
  272. }
  273. //--------------------------------------------------------------------------
  274. #define myOffset(field) Offset(field, afxMagicMissileData)
  275. FRangeValidator muzzleVelocityValidator(0, 10000);
  276. FRangeValidator missilePrecisionValidator(0.f, 100.f);
  277. FRangeValidator missileTrackDelayValidator(0, 100000);
  278. FRangeValidator missileBallisticCoefficientValidator(0, 1);
  279. void afxMagicMissileData::initPersistFields()
  280. {
  281. static IRangeValidatorScaled ticksFromMS(TickMs, 0, MaxLifetimeTicks);
  282. addField("particleEmitter", TYPEID<ParticleEmitterData>(), Offset(particleEmitter, afxMagicMissileData));
  283. addField("particleWaterEmitter", TYPEID<ParticleEmitterData>(), Offset(particleWaterEmitter, afxMagicMissileData));
  284. addField("projectileShapeName", TypeFilename, Offset(projectileShapeName, afxMagicMissileData));
  285. addField("scale", TypePoint3F, Offset(scale, afxMagicMissileData));
  286. addField("sound", TypeSFXTrackName, Offset(sound, afxMagicMissileData));
  287. /* From stock Projectile code...
  288. addField("explosion", TYPEID< ExplosionData >(), Offset(explosion, ProjectileData));
  289. addField("waterExplosion", TYPEID< ExplosionData >(), Offset(waterExplosion, ProjectileData));
  290. */
  291. addField("splash", TYPEID<SplashData>(), Offset(splash, afxMagicMissileData));
  292. /* From stock Projectile code...
  293. addField("decal", TYPEID< DecalData >(), Offset(decal, ProjectileData));
  294. */
  295. addField("lightDesc", TYPEID< LightDescription >(), Offset(lightDesc, afxMagicMissileData));
  296. addField("isBallistic", TypeBool, Offset(isBallistic, afxMagicMissileData));
  297. /* From stock Projectile code...
  298. addField("velInheritFactor", TypeF32, Offset(velInheritFactor, ProjectileData));
  299. */
  300. addNamedFieldV(muzzleVelocity, TypeF32, afxMagicMissileData, &muzzleVelocityValidator);
  301. /* From stock Projectile code...
  302. addField("impactForce", TypeF32, Offset(impactForce, ProjectileData));
  303. */
  304. addNamedFieldV(lifetime, TypeS32, afxMagicMissileData, &ticksFromMS);
  305. /* From stock Projectile code...
  306. addProtectedField("armingDelay", TypeS32, Offset(armingDelay, ProjectileData), &setArmingDelay, &getScaledValue,
  307. "The time in milliseconds before the projectile is armed and will cause damage or explode on impact." );
  308. addProtectedField("fadeDelay", TypeS32, Offset(fadeDelay, ProjectileData), &setFadeDelay, &getScaledValue,
  309. "The time in milliseconds when the projectile begins to fade out. Must be less than the lifetime to have an effect." );
  310. addField("bounceElasticity", TypeF32, Offset(bounceElasticity, ProjectileData));
  311. addField("bounceFriction", TypeF32, Offset(bounceFriction, ProjectileData));
  312. */
  313. addField("gravityMod", TypeF32, Offset(gravityMod, afxMagicMissileData));
  314. // FIELDS ADDED BY MAGIC-MISSILE
  315. addField("missileShapeName", TypeFilename, myOffset(projectileShapeName));
  316. addField("missileShapeScale", TypePoint3F, myOffset(scale));
  317. addField("startingVelocityVector",TypePoint3F, myOffset(starting_vel_vec));
  318. addNamedField(isGuided, TypeBool, afxMagicMissileData);
  319. addNamedFieldV(precision, TypeF32, afxMagicMissileData, &missilePrecisionValidator);
  320. addNamedFieldV(trackDelay, TypeS32, afxMagicMissileData, &missileTrackDelayValidator);
  321. addNamedFieldV(ballisticCoefficient, TypeF32, afxMagicMissileData, &missileBallisticCoefficientValidator);
  322. addField("collisionMask", TypeS32, myOffset(collision_mask));
  323. addField("followTerrain", TypeBool, myOffset(followTerrain));
  324. addField("followTerrainHeight", TypeF32, myOffset(followTerrainHeight));
  325. addField("followTerrainAdjustRate", TypeF32, myOffset(followTerrainAdjustRate));
  326. addFieldV("followTerrainAdjustDelay", TypeS32, myOffset(followTerrainAdjustDelay), &ticksFromMS);
  327. addNamedField(acceleration, TypeF32, afxMagicMissileData);
  328. addNamedFieldV(accelDelay, TypeS32, afxMagicMissileData, &ticksFromMS);
  329. addNamedFieldV(accelLifetime, TypeS32, afxMagicMissileData, &ticksFromMS);
  330. addField("launchNode", TypeString, myOffset(launch_node));
  331. addField("launchOffset", TypePoint3F, myOffset(launch_offset));
  332. addField("launchOffsetServer",TypePoint3F, myOffset(launch_offset_server));
  333. addField("launchOffsetClient",TypePoint3F, myOffset(launch_offset_client));
  334. addField("launchNodeOffset", TypePoint3F, myOffset(launch_node_offset));
  335. addField("launchAimPitch", TypeF32, myOffset(launch_pitch));
  336. addField("launchAimPan", TypeF32, myOffset(launch_pan));
  337. addField("launchConstraintServer", TypeString, myOffset(launch_cons_s_spec));
  338. addField("launchConstraintClient", TypeString, myOffset(launch_cons_c_spec));
  339. //
  340. addField("echoLaunchOffset", TypeBool, myOffset(echo_launch_offset));
  341. addField("wiggleMagnitudes", TypeF32Vector, myOffset(wiggle_magnitudes));
  342. addField("wiggleSpeeds", TypeF32Vector, myOffset(wiggle_speeds));
  343. addField("wiggleAxis", TypeString, myOffset(wiggle_axis_string));
  344. addField("hoverAltitude", TypeF32, myOffset(hover_altitude));
  345. addField("hoverAttackDistance", TypeF32, myOffset(hover_attack_distance));
  346. addField("hoverAttackGradient", TypeF32, myOffset(hover_attack_gradient));
  347. addFieldV("hoverTime", TypeS32, myOffset(hover_time), &ticksFromMS);
  348. addField("reverseTargeting", TypeBool, myOffset(reverse_targeting));
  349. addFieldV("casterSafetyTime", TypeS32, myOffset(caster_safety_time), &ticksFromMS);
  350. Parent::initPersistFields();
  351. // disallow some field substitutions
  352. onlyKeepClearSubstitutions("particleEmitter"); // subs resolving to "~~", or "~0" are OK
  353. onlyKeepClearSubstitutions("particleWaterEmitter");
  354. onlyKeepClearSubstitutions("sound");
  355. onlyKeepClearSubstitutions("splash");
  356. }
  357. //--------------------------------------------------------------------------
  358. bool afxMagicMissileData::onAdd()
  359. {
  360. if(!Parent::onAdd())
  361. return false;
  362. // ADDED BY MAGIC-MISSILE
  363. // Wiggle axes ////////////////////////////////////////////////////////////
  364. if (wiggle_axis_string != ST_NULLSTRING && wiggle_num_axis == 0)
  365. {
  366. // Tokenize input string and convert to Point3F array
  367. //
  368. Vector<char*> dataBlocks(__FILE__, __LINE__);
  369. // make a copy of points_string
  370. dsize_t tokCopyLen = dStrlen(wiggle_axis_string) + 1;
  371. char* tokCopy = new char[tokCopyLen];
  372. dStrcpy(tokCopy, wiggle_axis_string, tokCopyLen);
  373. // extract tokens one by one, adding them to dataBlocks
  374. char* currTok = dStrtok(tokCopy, " \t");
  375. while (currTok != NULL)
  376. {
  377. dataBlocks.push_back(currTok);
  378. currTok = dStrtok(NULL, " \t");
  379. }
  380. // bail if there were no tokens in the string
  381. if (dataBlocks.size() == 0)
  382. {
  383. Con::warnf(ConsoleLogEntry::General, "afxMagicMissileData(%s) invalid wiggle axis string. No tokens found", getName());
  384. delete [] tokCopy;
  385. return false;
  386. }
  387. // Find wiggle_num_axis (round up to multiple of 3) // WARNING here if not multiple of 3?
  388. for (U32 i = 0; i < dataBlocks.size()%3; i++)
  389. {
  390. dataBlocks.push_back("0.0");
  391. }
  392. wiggle_num_axis = dataBlocks.size()/3;
  393. wiggle_axis = new Point3F[wiggle_num_axis];
  394. U32 p_i = 0;
  395. for (U32 i = 0; i < dataBlocks.size(); i+=3, p_i++)
  396. {
  397. F32 x,y,z;
  398. x = dAtof(dataBlocks[i]); // What about overflow?
  399. y = dAtof(dataBlocks[i+1]);
  400. z = dAtof(dataBlocks[i+2]);
  401. wiggle_axis[p_i].set(x,y,z);
  402. wiggle_axis[p_i].normalizeSafe(); // sufficient????
  403. }
  404. delete [] tokCopy;
  405. }
  406. launch_cons_s_def.parseSpec(launch_cons_s_spec, true, false);
  407. launch_cons_c_def.parseSpec(launch_cons_c_spec, false, true);
  408. return true;
  409. }
  410. bool afxMagicMissileData::preload(bool server, String &errorStr)
  411. {
  412. if (Parent::preload(server, errorStr) == false)
  413. return false;
  414. if( !server )
  415. {
  416. if (!particleEmitter && particleEmitterId != 0)
  417. if (Sim::findObject(particleEmitterId, particleEmitter) == false)
  418. Con::errorf(ConsoleLogEntry::General, "afxMagicMissileData::preload: Invalid packet, bad datablockId(particleEmitter): %d", particleEmitterId);
  419. if (!particleWaterEmitter && particleWaterEmitterId != 0)
  420. if (Sim::findObject(particleWaterEmitterId, particleWaterEmitter) == false)
  421. Con::errorf(ConsoleLogEntry::General, "afxMagicMissileData::preload: Invalid packet, bad datablockId(particleWaterEmitter): %d", particleWaterEmitterId);
  422. /* From stock Projectile code...
  423. if (!explosion && explosionId != 0)
  424. if (Sim::findObject(explosionId, explosion) == false)
  425. Con::errorf(ConsoleLogEntry::General, "ProjectileData::preload: Invalid packet, bad datablockId(explosion): %d", explosionId);
  426. if (!waterExplosion && waterExplosionId != 0)
  427. if (Sim::findObject(waterExplosionId, waterExplosion) == false)
  428. Con::errorf(ConsoleLogEntry::General, "ProjectileData::preload: Invalid packet, bad datablockId(waterExplosion): %d", waterExplosionId);
  429. */
  430. if (!splash && splashId != 0)
  431. if (Sim::findObject(splashId, splash) == false)
  432. Con::errorf(ConsoleLogEntry::General, "afxMagicMissileData::preload: Invalid packet, bad datablockId(splash): %d", splashId);
  433. /* From stock Projectile code...
  434. if (!decal && decalId != 0)
  435. if (Sim::findObject(decalId, decal) == false)
  436. Con::errorf(ConsoleLogEntry::General, "ProjectileData::preload: Invalid packet, bad datablockId(decal): %d", decalId);
  437. */
  438. String sfxErrorStr;
  439. if( !sfxResolve( &sound, sfxErrorStr) )
  440. Con::errorf(ConsoleLogEntry::General, "afxMagicMissileData::preload: Invalid packet: %s", sfxErrorStr.c_str());
  441. if (!lightDesc && lightDescId != 0)
  442. if (Sim::findObject(lightDescId, lightDesc) == false)
  443. Con::errorf(ConsoleLogEntry::General, "afxMagicMissileData::preload: Invalid packet, bad datablockid(lightDesc): %d", lightDescId);
  444. }
  445. if (projectileShapeName != ST_NULLSTRING)
  446. {
  447. projectileShape = ResourceManager::get().load(projectileShapeName);
  448. if (bool(projectileShape) == false)
  449. {
  450. errorStr = String::ToString("afxMagicMissileData::load: Couldn't load shape \"%s\"", projectileShapeName);
  451. return false;
  452. }
  453. /* From stock Projectile code...
  454. activateSeq = projectileShape->findSequence("activate");
  455. maintainSeq = projectileShape->findSequence("maintain");
  456. */
  457. }
  458. if (bool(projectileShape)) // create an instance to preload shape data
  459. {
  460. TSShapeInstance* pDummy = new TSShapeInstance(projectileShape, !server);
  461. delete pDummy;
  462. }
  463. return true;
  464. }
  465. //--------------------------------------------------------------------------
  466. // Modified from floorPlanRes.cc
  467. // Read a vector of items
  468. template <class T>
  469. bool readVector(Vector<T> & vec, Stream & stream, const char * msg)
  470. {
  471. U32 num, i;
  472. bool Ok = true;
  473. stream.read( & num );
  474. vec.setSize( num );
  475. for( i = 0; i < num && Ok; i++ ){
  476. Ok = stream.read(& vec[i]);
  477. AssertISV( Ok, avar("math vec read error (%s) on elem %d", msg, i) );
  478. }
  479. return Ok;
  480. }
  481. // Write a vector of items
  482. template <class T>
  483. bool writeVector(const Vector<T> & vec, Stream & stream, const char * msg)
  484. {
  485. bool Ok = true;
  486. stream.write( vec.size() );
  487. for( U32 i = 0; i < vec.size() && Ok; i++ ) {
  488. Ok = stream.write(vec[i]);
  489. AssertISV( Ok, avar("vec write error (%s) on elem %d", msg, i) );
  490. }
  491. return Ok;
  492. }
  493. //--------------------------------------------------------------------------
  494. void afxMagicMissileData::packData(BitStream* stream)
  495. {
  496. Parent::packData(stream);
  497. stream->writeString(projectileShapeName);
  498. /* From stock Projectile code...
  499. stream->writeFlag(faceViewer);
  500. */
  501. if(stream->writeFlag(scale.x != 1 || scale.y != 1 || scale.z != 1))
  502. {
  503. stream->write(scale.x);
  504. stream->write(scale.y);
  505. stream->write(scale.z);
  506. }
  507. stream->write(collision_mask);
  508. if (stream->writeFlag(particleEmitter != NULL))
  509. stream->writeRangedU32(particleEmitter->getId(), DataBlockObjectIdFirst,
  510. DataBlockObjectIdLast);
  511. if (stream->writeFlag(particleWaterEmitter != NULL))
  512. stream->writeRangedU32(particleWaterEmitter->getId(), DataBlockObjectIdFirst,
  513. DataBlockObjectIdLast);
  514. /* From stock Projectile code...
  515. if (stream->writeFlag(explosion != NULL))
  516. stream->writeRangedU32(explosion->getId(), DataBlockObjectIdFirst,
  517. DataBlockObjectIdLast);
  518. if (stream->writeFlag(waterExplosion != NULL))
  519. stream->writeRangedU32(waterExplosion->getId(), DataBlockObjectIdFirst,
  520. DataBlockObjectIdLast);
  521. */
  522. if (stream->writeFlag(splash != NULL))
  523. stream->writeRangedU32(splash->getId(), DataBlockObjectIdFirst,
  524. DataBlockObjectIdLast);
  525. /* From stock Projectile code...
  526. if (stream->writeFlag(decal != NULL))
  527. stream->writeRangedU32(decal->getId(), DataBlockObjectIdFirst,
  528. DataBlockObjectIdLast);
  529. */
  530. sfxWrite( stream, sound );
  531. if ( stream->writeFlag(lightDesc != NULL))
  532. stream->writeRangedU32(lightDesc->getId(), DataBlockObjectIdFirst,
  533. DataBlockObjectIdLast);
  534. /* From stock Projectile code...
  535. stream->write(impactForce);
  536. */
  537. stream->write(lifetime);
  538. /* From stock Projectile code...
  539. stream->write(armingDelay);
  540. stream->write(fadeDelay);
  541. */
  542. if(stream->writeFlag(isBallistic))
  543. {
  544. stream->write(gravityMod);
  545. /* From stock Projectile code...
  546. stream->write(bounceElasticity);
  547. stream->write(bounceFriction);
  548. */
  549. stream->write(ballisticCoefficient);
  550. }
  551. if(stream->writeFlag(isGuided))
  552. {
  553. stream->write(precision);
  554. stream->write(trackDelay);
  555. }
  556. stream->write(muzzleVelocity);
  557. mathWrite(*stream, starting_vel_vec);
  558. stream->write(acceleration);
  559. stream->write(accelDelay);
  560. stream->write(accelLifetime);
  561. stream->writeString(launch_node);
  562. mathWrite(*stream, launch_offset);
  563. mathWrite(*stream, launch_offset_server);
  564. mathWrite(*stream, launch_offset_client);
  565. mathWrite(*stream, launch_node_offset);
  566. stream->write(launch_pitch);
  567. stream->write(launch_pan);
  568. stream->writeString(launch_cons_c_spec);
  569. stream->writeFlag(echo_launch_offset);
  570. writeVector(wiggle_magnitudes, *stream, "afxMagicMissile: wiggle_magnitudes");
  571. writeVector(wiggle_speeds, *stream, "afxMagicMissile: wiggle_speeds");
  572. stream->write(wiggle_num_axis);
  573. for (U32 i = 0; i < wiggle_num_axis; i++)
  574. mathWrite(*stream, wiggle_axis[i]);
  575. stream->write(hover_altitude);
  576. stream->write(hover_attack_distance);
  577. stream->write(hover_attack_gradient);
  578. stream->writeRangedU32(hover_time, 0, MaxLifetimeTicks);
  579. stream->writeFlag(reverse_targeting);
  580. stream->write(caster_safety_time);
  581. }
  582. void afxMagicMissileData::unpackData(BitStream* stream)
  583. {
  584. Parent::unpackData(stream);
  585. projectileShapeName = stream->readSTString();
  586. /* From stock Projectile code...
  587. faceViewer = stream->readFlag();
  588. */
  589. if(stream->readFlag())
  590. {
  591. stream->read(&scale.x);
  592. stream->read(&scale.y);
  593. stream->read(&scale.z);
  594. }
  595. else
  596. scale.set(1,1,1);
  597. stream->read(&collision_mask);
  598. if (stream->readFlag())
  599. particleEmitterId = stream->readRangedU32(DataBlockObjectIdFirst, DataBlockObjectIdLast);
  600. if (stream->readFlag())
  601. particleWaterEmitterId = stream->readRangedU32(DataBlockObjectIdFirst, DataBlockObjectIdLast);
  602. /* From stock Projectile code...
  603. if (stream->readFlag())
  604. explosionId = stream->readRangedU32(DataBlockObjectIdFirst, DataBlockObjectIdLast);
  605. if (stream->readFlag())
  606. waterExplosionId = stream->readRangedU32(DataBlockObjectIdFirst, DataBlockObjectIdLast);
  607. */
  608. if (stream->readFlag())
  609. splashId = stream->readRangedU32(DataBlockObjectIdFirst, DataBlockObjectIdLast);
  610. /* From stock Projectile code...
  611. if (stream->readFlag())
  612. decalId = stream->readRangedU32(DataBlockObjectIdFirst, DataBlockObjectIdLast);
  613. */
  614. sfxRead( stream, &sound );
  615. if (stream->readFlag())
  616. lightDescId = stream->readRangedU32(DataBlockObjectIdFirst, DataBlockObjectIdLast);
  617. /* From stock Projectile code...
  618. stream->read(&impactForce);
  619. */
  620. stream->read(&lifetime);
  621. /* From stock Projectile code...
  622. stream->read(&armingDelay);
  623. stream->read(&fadeDelay);
  624. */
  625. isBallistic = stream->readFlag();
  626. if(isBallistic)
  627. {
  628. stream->read(&gravityMod);
  629. /* From stock Projectile code...
  630. stream->read(&bounceElasticity);
  631. stream->read(&bounceFriction);
  632. */
  633. stream->read(&ballisticCoefficient);
  634. }
  635. isGuided = stream->readFlag();
  636. if(isGuided)
  637. {
  638. stream->read(&precision);
  639. stream->read(&trackDelay);
  640. }
  641. stream->read(&muzzleVelocity);
  642. mathRead(*stream, &starting_vel_vec);
  643. stream->read(&acceleration);
  644. stream->read(&accelDelay);
  645. stream->read(&accelLifetime);
  646. launch_node = stream->readSTString();
  647. mathRead(*stream, &launch_offset);
  648. mathRead(*stream, &launch_offset_server);
  649. mathRead(*stream, &launch_offset_client);
  650. mathRead(*stream, &launch_node_offset);
  651. stream->read(&launch_pitch);
  652. stream->read(&launch_pan);
  653. launch_cons_c_spec = stream->readSTString();
  654. echo_launch_offset = stream->readFlag();
  655. readVector(wiggle_magnitudes, *stream, "afxMagicMissile: wiggle_magnitudes");
  656. readVector(wiggle_speeds, *stream, "afxMagicMissile: wiggle_speeds");
  657. if (wiggle_axis)
  658. delete [] wiggle_axis;
  659. wiggle_axis = 0;
  660. wiggle_num_axis = 0;
  661. stream->read(&wiggle_num_axis);
  662. if (wiggle_num_axis > 0)
  663. {
  664. wiggle_axis = new Point3F[wiggle_num_axis];
  665. for (U32 i = 0; i < wiggle_num_axis; i++)
  666. mathRead(*stream, &wiggle_axis[i]);
  667. }
  668. stream->read(&hover_altitude);
  669. stream->read(&hover_attack_distance);
  670. stream->read(&hover_attack_gradient);
  671. hover_time = stream->readRangedU32(0, MaxLifetimeTicks);
  672. reverse_targeting = stream->readFlag();
  673. stream->read(&caster_safety_time);
  674. }
  675. /* From stock Projectile code...
  676. bool ProjectileData::setLifetime( void *obj, const char *index, const char *data )
  677. {
  678. S32 value = dAtoi(data);
  679. value = scaleValue(value);
  680. ProjectileData *object = static_cast<ProjectileData*>(obj);
  681. object->lifetime = value;
  682. return false;
  683. }
  684. bool ProjectileData::setArmingDelay( void *obj, const char *index, const char *data )
  685. {
  686. S32 value = dAtoi(data);
  687. value = scaleValue(value);
  688. ProjectileData *object = static_cast<ProjectileData*>(obj);
  689. object->armingDelay = value;
  690. return false;
  691. }
  692. bool ProjectileData::setFadeDelay( void *obj, const char *index, const char *data )
  693. {
  694. S32 value = dAtoi(data);
  695. value = scaleValue(value);
  696. ProjectileData *object = static_cast<ProjectileData*>(obj);
  697. object->fadeDelay = value;
  698. return false;
  699. }
  700. const char *ProjectileData::getScaledValue( void *obj, const char *data)
  701. {
  702. S32 value = dAtoi(data);
  703. value = scaleValue(value, false);
  704. String stringData = String::ToString(value);
  705. char *strBuffer = Con::getReturnBuffer(stringData.size());
  706. dMemcpy( strBuffer, stringData, stringData.size() );
  707. return strBuffer;
  708. }
  709. S32 ProjectileData::scaleValue( S32 value, bool down )
  710. {
  711. S32 minV = 0;
  712. S32 maxV = Projectile::MaxLivingTicks;
  713. // scale down to ticks before we validate
  714. if( down )
  715. value /= TickMs;
  716. if(value < minV || value > maxV)
  717. {
  718. Con::errorf("ProjectileData::scaleValue(S32 value = %d, bool down = %b) - Scaled value must be between %d and %d", value, down, minV, maxV);
  719. if(value < minV)
  720. value = minV;
  721. else if(value > maxV)
  722. value = maxV;
  723. }
  724. // scale up from ticks after we validate
  725. if( !down )
  726. value *= TickMs;
  727. return value;
  728. }
  729. */
  730. void afxMagicMissileData::gather_cons_defs(Vector<afxConstraintDef>& defs)
  731. {
  732. if (launch_cons_s_def.isDefined())
  733. defs.push_back(launch_cons_s_def);
  734. if (launch_cons_c_def.isDefined())
  735. defs.push_back(launch_cons_c_def);
  736. };
  737. //~~~~~~~~~~~~~~~~~~~~//~~~~~~~~~~~~~~~~~~~~//~~~~~~~~~~~~~~~~~~~~//~~~~~~~~~~~~~~~~~~~~~//
  738. //~~~~~~~~~~~~~~~~~~~~//~~~~~~~~~~~~~~~~~~~~//~~~~~~~~~~~~~~~~~~~~//~~~~~~~~~~~~~~~~~~~~~//
  739. // afxMagicMissile
  740. afxMagicMissile::afxMagicMissile()
  741. {
  742. init(true, true);
  743. }
  744. afxMagicMissile::afxMagicMissile(bool on_server, bool on_client)
  745. {
  746. init(on_server, on_client);
  747. }
  748. //--------------------------------------------------------------------------
  749. //--------------------------------------
  750. //
  751. void afxMagicMissile::init(bool on_server, bool on_client)
  752. {
  753. mPhysicsWorld = NULL;
  754. mTypeMask |= ProjectileObjectType | LightObjectType;
  755. mLight = LightManager::createLightInfo();
  756. mLight->setType( LightInfo::Point );
  757. mLightState.clear();
  758. mLightState.setLightInfo( mLight );
  759. mCurrPosition.zero();
  760. mCurrVelocity.set(0, 0, 1);
  761. mCurrTick = 0;
  762. mParticleEmitter = NULL;
  763. mParticleWaterEmitter = NULL;
  764. mSound = 0;
  765. mProjectileShape = NULL;
  766. mDataBlock = NULL;
  767. choreographer = NULL;
  768. if (on_server != on_client)
  769. {
  770. client_only = on_client;
  771. server_only = on_server;
  772. mNetFlags.clear(Ghostable | ScopeAlways);
  773. if (client_only)
  774. mNetFlags.set(IsGhost);
  775. }
  776. else
  777. {
  778. // note -- setting neither server or client makes no sense so we
  779. // treat as if both are set.
  780. mNetFlags.set(Ghostable | ScopeAlways);
  781. client_only = server_only = false;
  782. }
  783. mCurrDeltaBase.zero();
  784. mCurrBackDelta.zero();
  785. collision_mask = 0;
  786. prec_inc = 0.0f;
  787. did_launch = false;
  788. did_impact = false;
  789. missile_target = NULL;
  790. collide_exempt = NULL;
  791. use_accel = false;
  792. hover_attack_go = false;
  793. hover_attack_tick = 0;
  794. starting_velocity = 0.0;
  795. starting_vel_vec.zero();
  796. ss_object = 0;
  797. ss_index = 0;
  798. }
  799. afxMagicMissile::~afxMagicMissile()
  800. {
  801. SAFE_DELETE(mLight);
  802. delete mProjectileShape;
  803. mProjectileShape = NULL;
  804. }
  805. //--------------------------------------------------------------------------
  806. void afxMagicMissile::initPersistFields()
  807. {
  808. addGroup("Physics");
  809. addField("initialPosition", TypePoint3F, Offset(mCurrPosition, afxMagicMissile) ,
  810. "Initial starting position for this missile.");
  811. addField("initialVelocity", TypePoint3F, Offset(mCurrVelocity, afxMagicMissile) ,
  812. "Initial starting velocity for this missile.");
  813. endGroup("Physics");
  814. /* From stock Projectile code...
  815. addGroup("Source");
  816. addField("sourceObject", TypeS32, Offset(mSourceObjectId, Projectile) ,"The object that fires this projectile. If this projectile was fired by a WeaponImage, it will be the object that owns the WeaponImage, usually the player.");
  817. addField("sourceSlot", TypeS32, Offset(mSourceObjectSlot, Projectile) ,"Which weapon slot on the sourceObject that this projectile originates from.");
  818. endGroup("Source");
  819. */
  820. Parent::initPersistFields();
  821. }
  822. /* From stock Projectile code...
  823. bool Projectile::calculateImpact(float,
  824. Point3F& pointOfImpact,
  825. float& impactTime)
  826. {
  827. Con::warnf(ConsoleLogEntry::General, "Projectile::calculateImpact: Should never be called");
  828. impactTime = 0;
  829. pointOfImpact.set(0, 0, 0);
  830. return false;
  831. }
  832. //--------------------------------------------------------------------------
  833. F32 Projectile::getUpdatePriority(CameraScopeQuery *camInfo, U32 updateMask, S32 updateSkips)
  834. {
  835. F32 ret = Parent::getUpdatePriority(camInfo, updateMask, updateSkips);
  836. // if the camera "owns" this object, it should have a slightly higher priority
  837. if(mSourceObject == camInfo->camera)
  838. return ret + 0.2;
  839. return ret;
  840. }
  841. */
  842. bool afxMagicMissile::onAdd()
  843. {
  844. if(!Parent::onAdd())
  845. return false;
  846. if (isServerObject())
  847. {
  848. /* From stock Projectile code...
  849. ShapeBase* ptr;
  850. if (Sim::findObject(mSourceObjectId, ptr))
  851. {
  852. mSourceObject = ptr;
  853. // Since we later do processAfter( mSourceObject ) we must clearProcessAfter
  854. // if it is deleted. SceneObject already handles this in onDeleteNotify so
  855. // all we need to do is register for the notification.
  856. deleteNotify( ptr );
  857. }
  858. else
  859. {
  860. if (mSourceObjectId != -1)
  861. Con::errorf(ConsoleLogEntry::General, "Projectile::onAdd: mSourceObjectId is invalid");
  862. mSourceObject = NULL;
  863. }
  864. // If we're on the server, we need to inherit some of our parent's velocity
  865. //
  866. mCurrTick = 0;
  867. */
  868. }
  869. else
  870. {
  871. if (bool(mDataBlock->projectileShape))
  872. {
  873. mProjectileShape = new TSShapeInstance(mDataBlock->projectileShape, true);
  874. /* From stock Projectile code...
  875. if (mDataBlock->activateSeq != -1)
  876. {
  877. mActivateThread = mProjectileShape->addThread();
  878. mProjectileShape->setTimeScale(mActivateThread, 1);
  879. mProjectileShape->setSequence(mActivateThread, mDataBlock->activateSeq, 0);
  880. }
  881. */
  882. }
  883. if (mDataBlock->particleEmitter != NULL)
  884. {
  885. ParticleEmitter* pEmitter = new ParticleEmitter;
  886. //pEmitter->setDataBlock(mDataBlock->particleEmitter->cloneAndPerformSubstitutions(ss_object, ss_index));
  887. pEmitter->onNewDataBlock(mDataBlock->particleEmitter->cloneAndPerformSubstitutions(ss_object, ss_index), false);
  888. if (pEmitter->registerObject() == false)
  889. {
  890. Con::warnf(ConsoleLogEntry::General, "Could not register particle emitter for particle of class: %s", mDataBlock->getName());
  891. delete pEmitter;
  892. pEmitter = NULL;
  893. }
  894. mParticleEmitter = pEmitter;
  895. }
  896. if (mDataBlock->particleWaterEmitter != NULL)
  897. {
  898. ParticleEmitter* pEmitter = new ParticleEmitter;
  899. pEmitter->onNewDataBlock(mDataBlock->particleWaterEmitter->cloneAndPerformSubstitutions(ss_object, ss_index), false);
  900. if (pEmitter->registerObject() == false)
  901. {
  902. Con::warnf(ConsoleLogEntry::General, "Could not register particle emitter for particle of class: %s", mDataBlock->getName());
  903. delete pEmitter;
  904. pEmitter = NULL;
  905. }
  906. mParticleWaterEmitter = pEmitter;
  907. }
  908. }
  909. /* From stock Projectile code...
  910. if (mSourceObject.isValid())
  911. processAfter(mSourceObject);
  912. */
  913. // detect for acceleration
  914. use_accel = (mDataBlock->acceleration != 0 && mDataBlock->accelLifetime > 0);
  915. // Setup our bounding box
  916. if (bool(mDataBlock->projectileShape) == true)
  917. mObjBox = mDataBlock->projectileShape->mBounds;
  918. else
  919. mObjBox = Box3F(Point3F(0, 0, 0), Point3F(0, 0, 0));
  920. resetWorldBox();
  921. addToScene();
  922. if ( PHYSICSMGR )
  923. mPhysicsWorld = PHYSICSMGR->getWorld( isServerObject() ? "server" : "client" );
  924. return true;
  925. }
  926. void afxMagicMissile::onRemove()
  927. {
  928. if(mParticleEmitter)
  929. {
  930. mParticleEmitter->deleteWhenEmpty();
  931. mParticleEmitter = NULL;
  932. }
  933. if(mParticleWaterEmitter)
  934. {
  935. mParticleWaterEmitter->deleteWhenEmpty();
  936. mParticleWaterEmitter = NULL;
  937. }
  938. SFX_DELETE( mSound );
  939. removeFromScene();
  940. Parent::onRemove();
  941. }
  942. bool afxMagicMissile::onNewDataBlock(GameBaseData* dptr, bool reload)
  943. {
  944. mDataBlock = dynamic_cast<afxMagicMissileData*>(dptr);
  945. if (!mDataBlock || !Parent::onNewDataBlock(dptr, reload))
  946. return false;
  947. starting_velocity = mDataBlock->muzzleVelocity;
  948. starting_vel_vec = mDataBlock->starting_vel_vec;
  949. collision_mask = mDataBlock->collision_mask;
  950. if ( isGhost() )
  951. {
  952. // Create the sound ahead of time. This reduces runtime
  953. // costs and makes the system easier to understand.
  954. SFX_DELETE( mSound );
  955. if ( mDataBlock->sound )
  956. mSound = SFX->createSource( mDataBlock->sound );
  957. }
  958. return true;
  959. }
  960. //--------------------------------------------------------------------------
  961. void afxMagicMissile::submitLights( LightManager *lm, bool staticLighting )
  962. {
  963. if ( staticLighting || isHidden() || !mDataBlock->lightDesc )
  964. return;
  965. mDataBlock->lightDesc->submitLight( &mLightState, getRenderTransform(), lm, this );
  966. }
  967. bool afxMagicMissile::pointInWater(const Point3F &point)
  968. {
  969. // This is pretty much a hack so we can use the existing ContainerQueryInfo
  970. // and findObject router.
  971. // We only care if we intersect with water at all
  972. // so build a box at the point that has only 1 z extent.
  973. // And test if water coverage is anything other than zero.
  974. Box3F boundsBox( point, point );
  975. boundsBox.maxExtents.z += 1.0f;
  976. ContainerQueryInfo info;
  977. info.box = boundsBox;
  978. info.mass = 0.0f;
  979. // Find and retreive physics info from intersecting WaterObject(s)
  980. if(mContainer != NULL)
  981. {
  982. mContainer->findObjects( boundsBox, WaterObjectType, findRouter, &info );
  983. }
  984. else
  985. {
  986. // Handle special case where the projectile has exploded prior to having
  987. // called onAdd() on the client. This occurs when the projectile on the
  988. // server is created and then explodes in the same network update tick.
  989. // On the client end in NetConnection::ghostReadPacket() the ghost is
  990. // created and then Projectile::unpackUpdate() is called prior to the
  991. // projectile being registered. Within unpackUpdate() the explosion
  992. // is triggered, but without being registered onAdd() isn't called and
  993. // the container is not set. As all we're doing is checking if the
  994. // given explosion point is within water, we should be able to use the
  995. // global container here. We could likely always get away with this,
  996. // but using the actual defined container when possible is the right
  997. // thing to do. DAW
  998. AssertFatal(isClientObject(), "Server projectile has not been properly added");
  999. gClientContainer.findObjects( boundsBox, WaterObjectType, findRouter, &info );
  1000. }
  1001. return ( info.waterCoverage > 0.0f );
  1002. }
  1003. //----------------------------------------------------------------------------
  1004. void afxMagicMissile::emitParticles(const Point3F& from, const Point3F& to, const Point3F& vel, const U32 ms)
  1005. {
  1006. /* From stock Projectile code...
  1007. if ( isHidden() )
  1008. return;
  1009. */
  1010. Point3F axis = -vel;
  1011. if( axis.isZero() )
  1012. axis.set( 0.0, 0.0, 1.0 );
  1013. else
  1014. axis.normalize();
  1015. bool fromWater = pointInWater(from);
  1016. bool toWater = pointInWater(to);
  1017. if (!fromWater && !toWater && bool(mParticleEmitter)) // not in water
  1018. mParticleEmitter->emitParticles(from, to, axis, vel, ms);
  1019. else if (fromWater && toWater && bool(mParticleWaterEmitter)) // in water
  1020. mParticleWaterEmitter->emitParticles(from, to, axis, vel, ms);
  1021. else if (!fromWater && toWater) // entering water
  1022. {
  1023. // cast the ray to get the surface point of the water
  1024. RayInfo rInfo;
  1025. if (gClientContainer.castRay(from, to, WaterObjectType, &rInfo))
  1026. {
  1027. create_splash(rInfo.point);
  1028. // create an emitter for the particles out of water and the particles in water
  1029. if (mParticleEmitter)
  1030. mParticleEmitter->emitParticles(from, rInfo.point, axis, vel, ms);
  1031. if (mParticleWaterEmitter)
  1032. mParticleWaterEmitter->emitParticles(rInfo.point, to, axis, vel, ms);
  1033. }
  1034. }
  1035. else if (fromWater && !toWater) // leaving water
  1036. {
  1037. // cast the ray in the opposite direction since that point is out of the water, otherwise
  1038. // we hit water immediately and wont get the appropriate surface point
  1039. RayInfo rInfo;
  1040. if (gClientContainer.castRay(to, from, WaterObjectType, &rInfo))
  1041. {
  1042. create_splash(rInfo.point);
  1043. // create an emitter for the particles out of water and the particles in water
  1044. if (mParticleEmitter)
  1045. mParticleEmitter->emitParticles(rInfo.point, to, axis, vel, ms);
  1046. if (mParticleWaterEmitter)
  1047. mParticleWaterEmitter->emitParticles(from, rInfo.point, axis, vel, ms);
  1048. }
  1049. }
  1050. }
  1051. void afxMagicMissile::processTick(const Move* move)
  1052. {
  1053. Parent::processTick( move );
  1054. // only active from launch to impact
  1055. if (!is_active())
  1056. return;
  1057. mCurrTick++;
  1058. // missile fizzles out by exceeding lifetime
  1059. if ((isServerObject() || client_only) && mCurrTick >= mDataBlock->lifetime)
  1060. {
  1061. did_impact = true;
  1062. setMaskBits(ImpactMask);
  1063. if (choreographer)
  1064. {
  1065. Point3F n = mCurrVelocity; n.normalizeSafe();
  1066. choreographer->impactNotify(mCurrPosition, n, 0);
  1067. }
  1068. Sim::postEvent(this, new ObjectDeleteEvent, Sim::getCurrentTime() + 500);
  1069. return;
  1070. }
  1071. static F32 dT = F32(TickMs)*0.001f;
  1072. Point3F old_pos = mCurrPosition;
  1073. // adjust missile velocity from gravity and drag influences
  1074. if (mDataBlock->isBallistic)
  1075. {
  1076. F32 dV = (1 - mDataBlock->ballisticCoefficient)*dT;
  1077. Point3F d(mCurrVelocity.x*dV, mCurrVelocity.y*dV, 9.81f*mDataBlock->gravityMod*dT);
  1078. mCurrVelocity -= d;
  1079. }
  1080. // adjust missile velocity from acceleration
  1081. if (use_accel)
  1082. {
  1083. if (mCurrTick > mDataBlock->accelDelay &&
  1084. mCurrTick <= mDataBlock->accelDelay + mDataBlock->accelLifetime)
  1085. {
  1086. Point3F d = mCurrVelocity; d.normalizeSafe();
  1087. mCurrVelocity += d*mDataBlock->acceleration*dT;
  1088. }
  1089. }
  1090. // adjust mCurrVelocity from guidance system influences
  1091. if (mDataBlock->isGuided && missile_target && mCurrTick > mDataBlock->trackDelay)
  1092. {
  1093. // get the position tracked by the guidance system
  1094. Point3F target_pos = missile_target->getBoxCenter();
  1095. Point3F target_vec = target_pos - mCurrPosition;
  1096. F32 target_dist_sq = target_vec.lenSquared();
  1097. if (target_dist_sq < 4.0f)
  1098. prec_inc += 1.0f;
  1099. // hover
  1100. if (mDataBlock->hover_altitude > 0.0f)
  1101. {
  1102. Point3F target_vec_xy(target_vec.x, target_vec.y, 0);
  1103. F32 xy_dist = target_vec_xy.len();
  1104. if (xy_dist > mDataBlock->hover_attack_distance)
  1105. {
  1106. hover_attack_go = false;
  1107. if (xy_dist > mDataBlock->hover_attack_distance + mDataBlock->hover_attack_gradient)
  1108. {
  1109. target_pos.z += mDataBlock->hover_altitude;
  1110. }
  1111. else
  1112. {
  1113. target_pos.z += afxEase::eq( (xy_dist-mDataBlock->hover_attack_distance)/mDataBlock->hover_attack_gradient,
  1114. 0.0f, mDataBlock->hover_altitude,
  1115. 0.25f, 0.75f);
  1116. }
  1117. target_vec = target_pos - mCurrPosition;
  1118. }
  1119. else
  1120. {
  1121. if (!hover_attack_go)
  1122. {
  1123. hover_attack_go = true;
  1124. hover_attack_tick = 0;
  1125. }
  1126. hover_attack_tick++;
  1127. if (hover_attack_tick < mDataBlock->hover_time)
  1128. {
  1129. target_pos.z += mDataBlock->hover_altitude;
  1130. target_vec = target_pos - mCurrPosition;
  1131. }
  1132. }
  1133. }
  1134. // apply precision
  1135. // extract speed
  1136. F32 speed = mCurrVelocity.len();
  1137. // normalize vectors
  1138. target_vec.normalizeSafe();
  1139. mCurrVelocity.normalize();
  1140. F32 prec = mDataBlock->precision;
  1141. // fade in precision gradually to avoid sudden turn
  1142. if (mCurrTick < mDataBlock->trackDelay + 16)
  1143. prec *= (mCurrTick - mDataBlock->trackDelay)/16.0f;
  1144. prec += prec_inc;
  1145. if (prec > 100)
  1146. prec = 100;
  1147. // apply precision weighting
  1148. target_vec *= prec;
  1149. mCurrVelocity *= (100 - prec);
  1150. mCurrVelocity += target_vec;
  1151. mCurrVelocity.normalize();
  1152. mCurrVelocity *= speed;
  1153. }
  1154. // wiggle
  1155. for (U32 i = 0; i < mDataBlock->wiggle_num_axis; i++)
  1156. {
  1157. if (i >= mDataBlock->wiggle_magnitudes.size() || i >= mDataBlock->wiggle_speeds.size())
  1158. break;
  1159. F32 wiggle_mag = mDataBlock->wiggle_magnitudes[i];
  1160. F32 wiggle_speed = mDataBlock->wiggle_speeds[i];
  1161. Point3F wiggle_axis = mDataBlock->wiggle_axis[i];
  1162. //wiggle_axis.normalizeSafe(); // sufficient????
  1163. F32 theta = wiggle_mag * mSin(wiggle_speed*(mCurrTick*TickSec));
  1164. //Con::printf( "theta: %f", theta );
  1165. AngAxisF thetaRot(wiggle_axis, theta);
  1166. MatrixF temp(true);
  1167. thetaRot.setMatrix(&temp);
  1168. temp.mulP(mCurrVelocity);
  1169. }
  1170. Point3F new_pos = old_pos + mCurrVelocity*dT;
  1171. // conform to terrain
  1172. if (mDataBlock->followTerrain && mCurrTick >= mDataBlock->followTerrainAdjustDelay)
  1173. {
  1174. U32 mask = TerrainObjectType | TerrainLikeObjectType; // | InteriorObjectType;
  1175. F32 ht = mDataBlock->followTerrainHeight;
  1176. F32 ht_rate = mDataBlock->followTerrainAdjustRate;
  1177. F32 ht_min = 0.05f;
  1178. if (ht < ht_min)
  1179. ht = ht_min;
  1180. SceneContainer* container = (isServerObject()) ? &gServerContainer : &gClientContainer;
  1181. Point3F above_pos = new_pos; above_pos.z += 10000;
  1182. Point3F below_pos = new_pos; below_pos.z -= 10000;
  1183. RayInfo rInfo;
  1184. if (container && container->castRay(above_pos, below_pos, mask, &rInfo))
  1185. {
  1186. F32 terrain_z = rInfo.point.z;
  1187. F32 seek_z = terrain_z + ht;
  1188. if (new_pos.z < seek_z)
  1189. {
  1190. new_pos.z += ht_rate*dT;
  1191. if (new_pos.z > seek_z)
  1192. new_pos.z = seek_z;
  1193. }
  1194. else if (new_pos.z > seek_z)
  1195. {
  1196. new_pos.z -= ht_rate*dT;
  1197. if (new_pos.z < seek_z)
  1198. new_pos.z = seek_z;
  1199. }
  1200. if (new_pos.z < terrain_z + ht_min)
  1201. new_pos.z = terrain_z + ht_min;
  1202. }
  1203. }
  1204. // only check for impacts on server
  1205. if (isServerObject())
  1206. {
  1207. // avoid collision with the spellcaster
  1208. if (collide_exempt && mCurrTick <= mDataBlock->caster_safety_time)
  1209. collide_exempt->disableCollision();
  1210. // check for collision along ray from old to new position
  1211. RayInfo rInfo;
  1212. bool did_hit = false;
  1213. if (mPhysicsWorld)
  1214. {
  1215. // did_hit = mPhysicsWorld->castRay(old_pos, new_pos, &rInfo, Point3F(new_pos - old_pos) * mDataBlock->impactForce );
  1216. // Impulse currently hardcoded for testing purposes
  1217. did_hit = mPhysicsWorld->castRay(old_pos, new_pos, &rInfo, Point3F(new_pos - old_pos) * 1000.0f );
  1218. }
  1219. else
  1220. {
  1221. did_hit = getContainer()->castRay(old_pos, new_pos, collision_mask, &rInfo);
  1222. }
  1223. // restore collisions on spellcaster
  1224. if (collide_exempt && mCurrTick <= mDataBlock->caster_safety_time)
  1225. collide_exempt->enableCollision();
  1226. // process impact
  1227. if (did_hit)
  1228. {
  1229. MatrixF xform(true);
  1230. xform.setColumn(3, rInfo.point);
  1231. setTransform(xform);
  1232. mCurrPosition = rInfo.point;
  1233. mCurrVelocity = Point3F(0, 0, 0);
  1234. did_impact = true;
  1235. setMaskBits(ImpactMask);
  1236. if (choreographer)
  1237. {
  1238. choreographer->impactNotify(rInfo.point, rInfo.normal, rInfo.object);
  1239. Sim::postEvent(this, new ObjectDeleteEvent, Sim::getCurrentTime() + 500);
  1240. }
  1241. }
  1242. }
  1243. else // if (isClientObject())
  1244. {
  1245. emitParticles(mCurrPosition, new_pos, mCurrVelocity, TickMs);
  1246. updateSound();
  1247. }
  1248. // interp values used in interpolateTick()
  1249. mCurrDeltaBase = new_pos;
  1250. mCurrBackDelta = mCurrPosition - new_pos;
  1251. mCurrPosition = new_pos;
  1252. MatrixF xform(true);
  1253. xform.setColumn(3, mCurrPosition);
  1254. setTransform(xform);
  1255. }
  1256. void afxMagicMissile::interpolateTick(F32 delta)
  1257. {
  1258. Parent::interpolateTick(delta);
  1259. // only active from launch to impact
  1260. if (!is_active())
  1261. return;
  1262. Point3F interpPos = mCurrDeltaBase + mCurrBackDelta * delta;
  1263. Point3F dir = mCurrVelocity;
  1264. if(dir.isZero())
  1265. dir.set(0,0,1);
  1266. else
  1267. dir.normalize();
  1268. MatrixF xform(true);
  1269. xform = MathUtils::createOrientFromDir(dir);
  1270. xform.setPosition(interpPos);
  1271. setRenderTransform(xform);
  1272. updateSound();
  1273. }
  1274. //--------------------------------------------------------------------------
  1275. U32 afxMagicMissile::packUpdate(NetConnection* con, U32 mask, BitStream* stream)
  1276. {
  1277. U32 retMask = Parent::packUpdate( con, mask, stream );
  1278. const bool isInitalUpdate = mask & GameBase::InitialUpdateMask;
  1279. // InitialUpdateMask
  1280. if ( stream->writeFlag( isInitalUpdate ) )
  1281. {
  1282. Point3F pos;
  1283. getTransform().getColumn( 3, &pos );
  1284. stream->writeCompressedPoint( pos );
  1285. F32 len = mCurrVelocity.len();
  1286. if ( stream->writeFlag( len > 0.02 ) )
  1287. {
  1288. Point3F outVel = mCurrVelocity;
  1289. outVel *= 1 / len;
  1290. stream->writeNormalVector( outVel, 10 );
  1291. len *= 32.0; // 5 bits for fraction
  1292. if ( len > 8191 )
  1293. len = 8191;
  1294. stream->writeInt( (S32)len, 13 );
  1295. }
  1296. stream->writeRangedU32( mCurrTick, 0, afxMagicMissileData::MaxLifetimeTicks );
  1297. if (choreographer)
  1298. {
  1299. S32 ghostIndex = con->getGhostIndex( choreographer );
  1300. if ( stream->writeFlag( ghostIndex != -1 ) )
  1301. {
  1302. stream->writeRangedU32( U32(ghostIndex),
  1303. 0,
  1304. NetConnection::MaxGhostCount );
  1305. }
  1306. else
  1307. // have not recieved the ghost for the source object yet, try again later
  1308. retMask |= GameBase::InitialUpdateMask;
  1309. }
  1310. else
  1311. stream->writeFlag( false );
  1312. }
  1313. // impact update
  1314. if (stream->writeFlag(mask & ImpactMask))
  1315. {
  1316. mathWrite(*stream, mCurrPosition);
  1317. mathWrite(*stream, mCurrVelocity);
  1318. stream->writeFlag(did_impact);
  1319. }
  1320. // guided update
  1321. if (stream->writeFlag(mask & GuideMask))
  1322. {
  1323. mathWrite(*stream, mCurrPosition);
  1324. mathWrite(*stream, mCurrVelocity);
  1325. }
  1326. return retMask;
  1327. }
  1328. void afxMagicMissile::unpackUpdate(NetConnection* con, BitStream* stream)
  1329. {
  1330. Parent::unpackUpdate(con, stream);
  1331. if ( stream->readFlag() ) // InitialUpdateMask
  1332. {
  1333. Point3F pos;
  1334. stream->readCompressedPoint( &pos );
  1335. if ( stream->readFlag() )
  1336. {
  1337. stream->readNormalVector( &mCurrVelocity, 10 );
  1338. mCurrVelocity *= stream->readInt( 13 ) / 32.0f;
  1339. }
  1340. else
  1341. mCurrVelocity.zero();
  1342. mCurrDeltaBase = pos;
  1343. mCurrBackDelta = mCurrPosition - pos;
  1344. mCurrPosition = pos;
  1345. setPosition( mCurrPosition );
  1346. mCurrTick = stream->readRangedU32(0, afxMagicMissileData::MaxLifetimeTicks);
  1347. if ( stream->readFlag() )
  1348. {
  1349. U32 id = stream->readRangedU32(0, NetConnection::MaxGhostCount);
  1350. choreographer = dynamic_cast<afxChoreographer*>(con->resolveGhost(id));
  1351. if (choreographer)
  1352. {
  1353. deleteNotify(choreographer);
  1354. }
  1355. }
  1356. else
  1357. {
  1358. if (choreographer)
  1359. clearNotify(choreographer);
  1360. choreographer = 0;
  1361. }
  1362. }
  1363. // impact update
  1364. if (stream->readFlag())
  1365. {
  1366. mathRead(*stream, &mCurrPosition);
  1367. mathRead(*stream, &mCurrVelocity);
  1368. did_impact = stream->readFlag();
  1369. }
  1370. if (stream->readFlag()) // guided update
  1371. {
  1372. mathRead( *stream, &mCurrPosition );
  1373. mathRead( *stream, &mCurrVelocity );
  1374. }
  1375. }
  1376. //--------------------------------------------------------------------------
  1377. void afxMagicMissile::prepRenderImage(SceneRenderState* state)
  1378. {
  1379. if (!is_active())
  1380. return;
  1381. /*
  1382. if (isHidden() || mFadeValue <= (1.0/255.0))
  1383. return;
  1384. */
  1385. if ( mDataBlock->lightDesc )
  1386. {
  1387. mDataBlock->lightDesc->prepRender( state, &mLightState, getRenderTransform() );
  1388. }
  1389. /*
  1390. if ( mFlareData )
  1391. {
  1392. mFlareState.fullBrightness = mDataBlock->lightDesc->mBrightness;
  1393. mFlareState.scale = mFlareScale;
  1394. mFlareState.lightInfo = mLight;
  1395. mFlareState.lightMat = getTransform();
  1396. mFlareData->prepRender( state, &mFlareState );
  1397. }
  1398. */
  1399. prepBatchRender( state );
  1400. }
  1401. void afxMagicMissile::prepBatchRender(SceneRenderState* state)
  1402. {
  1403. if ( !mProjectileShape )
  1404. return;
  1405. GFXTransformSaver saver;
  1406. // Set up our TS render state.
  1407. TSRenderState rdata;
  1408. rdata.setSceneState( state );
  1409. // We might have some forward lit materials
  1410. // so pass down a query to gather lights.
  1411. LightQuery query;
  1412. query.init( getWorldSphere() );
  1413. rdata.setLightQuery( &query );
  1414. MatrixF mat = getRenderTransform();
  1415. mat.scale( mObjScale );
  1416. mat.scale( mDataBlock->scale );
  1417. GFX->setWorldMatrix( mat );
  1418. mProjectileShape->setDetailFromPosAndScale( state, mat.getPosition(), mObjScale );
  1419. mProjectileShape->animate();
  1420. mProjectileShape->render( rdata );
  1421. }
  1422. void afxMagicMissile::onDeleteNotify(SimObject* obj)
  1423. {
  1424. ShapeBase* shape_test = dynamic_cast<ShapeBase*>(obj);
  1425. if (shape_test == collide_exempt)
  1426. {
  1427. collide_exempt = NULL;
  1428. Parent::onDeleteNotify(obj);
  1429. return;
  1430. }
  1431. SceneObject* target_test = dynamic_cast<SceneObject*>(obj);
  1432. if (target_test == missile_target)
  1433. {
  1434. missile_target = NULL;
  1435. Parent::onDeleteNotify(obj);
  1436. return;
  1437. }
  1438. afxChoreographer* ch = dynamic_cast<afxChoreographer*>(obj);
  1439. if (ch == choreographer)
  1440. {
  1441. choreographer = NULL;
  1442. Parent::onDeleteNotify(obj);
  1443. return;
  1444. }
  1445. Parent::onDeleteNotify(obj);
  1446. }
  1447. //~~~~~~~~~~~~~~~~~~~~//~~~~~~~~~~~~~~~~~~~~//~~~~~~~~~~~~~~~~~~~~//~~~~~~~~~~~~~~~~~~~~~//
  1448. // private:
  1449. void afxMagicMissile::create_splash(const Point3F& pos)
  1450. {
  1451. if (!mDataBlock || !mDataBlock->splash)
  1452. return;
  1453. MatrixF xfm = getTransform();
  1454. xfm.setPosition(pos);
  1455. Splash* splash = new Splash();
  1456. splash->onNewDataBlock(mDataBlock->splash, false);
  1457. splash->setTransform(xfm);
  1458. splash->setInitialState(xfm.getPosition(), Point3F(0.0, 0.0, 1.0));
  1459. if (!splash->registerObject())
  1460. {
  1461. delete splash;
  1462. splash = NULL;
  1463. }
  1464. }
  1465. void afxMagicMissile::get_launch_constraint_data(Point3F& pos, Point3F& vel)
  1466. {
  1467. // need a choreographer
  1468. if (!choreographer)
  1469. {
  1470. Con::errorf("afxMagicMissile::get_launch_constraint_data(): missing choreographer.");
  1471. return;
  1472. }
  1473. // need a constraint manager
  1474. afxConstraintMgr* cons_mgr = choreographer->getConstraintMgr();
  1475. if (!cons_mgr)
  1476. {
  1477. Con::errorf("afxMagicMissile::get_launch_constraint_data(): missing constriant manager.");
  1478. return;
  1479. }
  1480. // need a valid constraint
  1481. afxConstraintID launch_cons_id;
  1482. if (isServerObject())
  1483. launch_cons_id = cons_mgr->getConstraintId(mDataBlock->launch_cons_s_def);
  1484. else
  1485. launch_cons_id = cons_mgr->getConstraintId(mDataBlock->launch_cons_c_def);
  1486. afxConstraint* launch_cons = cons_mgr->getConstraint(launch_cons_id);
  1487. if (!launch_cons)
  1488. {
  1489. Con::errorf("afxMagicMissile::get_launch_constraint_data(): constraint undefined.");
  1490. return;
  1491. }
  1492. MatrixF launch_xfm;
  1493. launch_cons->getTransform(launch_xfm);
  1494. Point3F launch_pos;
  1495. launch_cons->getPosition(launch_pos);
  1496. pos = launch_pos;
  1497. // echo the actual launch position to the console
  1498. if (mDataBlock->echo_launch_offset)
  1499. {
  1500. SceneObject* default_launcher = get_default_launcher();
  1501. if (default_launcher)
  1502. {
  1503. MatrixF launcher_xfm_inv = default_launcher->getWorldTransform();
  1504. VectorF offset = pos - default_launcher->getRenderPosition();
  1505. launcher_xfm_inv.mulV(offset);
  1506. if (isServerObject())
  1507. Con::printf("launchOffsetServer = \"%g %g %g\";", offset.x, offset.y, offset.z);
  1508. else
  1509. Con::printf("launchOffsetClient = \"%g %g %g\";", offset.x, offset.y, offset.z);
  1510. }
  1511. }
  1512. // setup aiming matrix to straight forward and level
  1513. MatrixF aim_mtx;
  1514. AngAxisF aim_aa(Point3F(0,1,0),0);
  1515. aim_aa.setMatrix(&aim_mtx);
  1516. // calculate final aiming vector
  1517. MatrixF aim2_mtx;
  1518. aim2_mtx.mul(launch_xfm, aim_mtx);
  1519. VectorF aim_vec;
  1520. aim2_mtx.getColumn(1,&aim_vec);
  1521. aim_vec.normalizeSafe();
  1522. // give velocity vector a magnitude
  1523. vel = aim_vec*mDataBlock->muzzleVelocity;
  1524. }
  1525. // resolve the launch constraint object. normally it's the caster, but for
  1526. // reverse_targeting the target object us used.
  1527. SceneObject* afxMagicMissile::get_default_launcher() const
  1528. {
  1529. SceneObject* launch_cons_obj = 0;
  1530. if (mDataBlock->reverse_targeting)
  1531. {
  1532. if (dynamic_cast<afxMagicSpell*>(choreographer))
  1533. launch_cons_obj = ((afxMagicSpell*)choreographer)->mTarget;
  1534. if (!launch_cons_obj)
  1535. {
  1536. Con::errorf("afxMagicMissile::get_launch_data(): missing target constraint object for reverse targeted missile.");
  1537. return 0;
  1538. }
  1539. }
  1540. else
  1541. {
  1542. if (dynamic_cast<afxMagicSpell*>(choreographer))
  1543. launch_cons_obj = ((afxMagicSpell*)choreographer)->mCaster;
  1544. if (!launch_cons_obj)
  1545. {
  1546. Con::errorf("afxMagicMissile::get_launch_data(): missing launch constraint object missile.");
  1547. return 0;
  1548. }
  1549. }
  1550. return launch_cons_obj;
  1551. }
  1552. void afxMagicMissile::get_launch_data(Point3F& pos, Point3F& vel)
  1553. {
  1554. bool use_constraint = (isServerObject()) ? mDataBlock->launch_cons_s_def.isDefined() : mDataBlock->launch_cons_c_def.isDefined();
  1555. if (use_constraint)
  1556. {
  1557. get_launch_constraint_data(pos, vel);
  1558. return;
  1559. }
  1560. // a choreographer pointer is required
  1561. if (!choreographer)
  1562. {
  1563. Con::errorf("afxMagicMissile::get_launch_data(): missing choreographer.");
  1564. return;
  1565. }
  1566. SceneObject* launch_cons_obj = get_default_launcher();
  1567. if (!launch_cons_obj)
  1568. return;
  1569. MatrixF launch_xfm = launch_cons_obj->getRenderTransform();
  1570. // calculate launch position
  1571. Point3F offset_override = (isClientObject()) ? mDataBlock->launch_offset_client :
  1572. mDataBlock->launch_offset_server;
  1573. // override
  1574. if (!offset_override.isZero())
  1575. {
  1576. launch_xfm.mulV(offset_override);
  1577. pos = launch_cons_obj->getRenderPosition() + offset_override;
  1578. }
  1579. // no override
  1580. else
  1581. {
  1582. // get transformed launch offset
  1583. VectorF launch_offset = mDataBlock->launch_offset;
  1584. launch_xfm.mulV(launch_offset);
  1585. StringTableEntry launch_node = mDataBlock->launch_node;
  1586. // calculate position of missile at launch
  1587. if (launch_node != ST_NULLSTRING)
  1588. {
  1589. ShapeBase* launch_cons_shape = dynamic_cast<ShapeBase*>(launch_cons_obj);
  1590. TSShapeInstance* shape_inst = (launch_cons_shape) ? launch_cons_shape->getShapeInstance() : 0;
  1591. if (!shape_inst || !shape_inst->getShape())
  1592. launch_node = ST_NULLSTRING;
  1593. else
  1594. {
  1595. S32 node_ID = shape_inst->getShape()->findNode(launch_node);
  1596. MatrixF node_xfm = launch_cons_obj->getRenderTransform();
  1597. node_xfm.scale(launch_cons_obj->getScale());
  1598. if (node_ID >= 0)
  1599. node_xfm.mul(shape_inst->mNodeTransforms[node_ID]);
  1600. VectorF node_offset = mDataBlock->launch_node_offset;
  1601. node_xfm.mulV(node_offset);
  1602. pos = node_xfm.getPosition() + launch_offset + node_offset;
  1603. }
  1604. }
  1605. // calculate launch position without launch node
  1606. else
  1607. pos = launch_cons_obj->getRenderPosition() + launch_offset;
  1608. }
  1609. // echo the actual launch position to the console
  1610. if (mDataBlock->echo_launch_offset)
  1611. {
  1612. VectorF offset = pos - launch_cons_obj->getRenderPosition();
  1613. MatrixF caster_xfm_inv = launch_xfm;
  1614. caster_xfm_inv.affineInverse();
  1615. caster_xfm_inv.mulV(offset);
  1616. if (isServerObject())
  1617. Con::printf("launchOffsetServer = \"%g %g %g\";", offset.x, offset.y, offset.z);
  1618. else
  1619. Con::printf("launchOffsetClient = \"%g %g %g\";", offset.x, offset.y, offset.z);
  1620. }
  1621. // calculate launch velocity vector
  1622. if (starting_vel_vec.isZero())
  1623. {
  1624. // setup aiming matrix to straight forward and level
  1625. MatrixF aim_mtx;
  1626. AngAxisF aim_aa(Point3F(0,1,0),0);
  1627. aim_aa.setMatrix(&aim_mtx);
  1628. // setup pitch matrix
  1629. MatrixF pitch_mtx;
  1630. AngAxisF pitch_aa(Point3F(1,0,0),mDegToRad(mDataBlock->launch_pitch));
  1631. pitch_aa.setMatrix(&pitch_mtx);
  1632. // setup pan matrix
  1633. MatrixF pan_mtx;
  1634. AngAxisF pan_aa(Point3F(0,0,1),mDegToRad(mDataBlock->launch_pan));
  1635. pan_aa.setMatrix(&pan_mtx);
  1636. // calculate adjusted aiming matrix
  1637. aim_mtx.mul(pitch_mtx);
  1638. aim_mtx.mul(pan_mtx);
  1639. // calculate final aiming vector
  1640. MatrixF aim2_mtx;
  1641. aim2_mtx.mul(launch_xfm, aim_mtx);
  1642. VectorF aim_vec;
  1643. aim2_mtx.getColumn(1,&aim_vec);
  1644. aim_vec.normalizeSafe();
  1645. // give velocity vector a magnitude
  1646. vel = aim_vec*mDataBlock->muzzleVelocity;
  1647. }
  1648. else
  1649. {
  1650. vel = starting_vel_vec*starting_velocity;
  1651. }
  1652. }
  1653. void afxMagicMissile::updateSound()
  1654. {
  1655. if (!mDataBlock->sound)
  1656. return;
  1657. if ( mSound )
  1658. {
  1659. if ( !mSound->isPlaying() )
  1660. mSound->play();
  1661. mSound->setVelocity( getVelocity() );
  1662. mSound->setTransform( getRenderTransform() );
  1663. }
  1664. }
  1665. //~~~~~~~~~~~~~~~~~~~~//~~~~~~~~~~~~~~~~~~~~//~~~~~~~~~~~~~~~~~~~~//~~~~~~~~~~~~~~~~~~~~~//
  1666. // public:
  1667. void afxMagicMissile::launch()
  1668. {
  1669. get_launch_data(mCurrPosition, mCurrVelocity);
  1670. mCurrDeltaBase = mCurrPosition;
  1671. mCurrBackDelta.zero();
  1672. did_launch = true;
  1673. setPosition(mCurrPosition);
  1674. afxMagicSpell* spell = dynamic_cast<afxMagicSpell*>(choreographer);
  1675. if (spell)
  1676. {
  1677. if (mDataBlock->reverse_targeting)
  1678. {
  1679. missile_target = spell->mCaster;
  1680. collide_exempt = spell->mTarget;
  1681. }
  1682. else
  1683. {
  1684. missile_target = spell->mTarget;
  1685. collide_exempt = spell->mCaster;
  1686. }
  1687. if (spell->mCaster)
  1688. processAfter(spell->mCaster);
  1689. if (missile_target)
  1690. deleteNotify(missile_target);
  1691. if (collide_exempt)
  1692. deleteNotify(collide_exempt);
  1693. }
  1694. else
  1695. {
  1696. missile_target = 0;
  1697. collide_exempt = 0;
  1698. }
  1699. }
  1700. void afxMagicMissile::setChoreographer(afxChoreographer* chor)
  1701. {
  1702. if (choreographer)
  1703. clearNotify(choreographer);
  1704. choreographer = chor;
  1705. if (choreographer)
  1706. deleteNotify(choreographer);
  1707. }
  1708. void afxMagicMissile::setStartingVelocityVector(const Point3F& vel_vec)
  1709. {
  1710. starting_vel_vec = vel_vec;
  1711. }
  1712. void afxMagicMissile::setStartingVelocity(const F32 vel)
  1713. {
  1714. starting_velocity = vel;
  1715. }
  1716. void afxMagicMissile::getStartingVelocityValues(F32& vel, Point3F& vel_vec)
  1717. {
  1718. vel = starting_velocity;
  1719. vel_vec = starting_vel_vec;
  1720. }
  1721. //~~~~~~~~~~~~~~~~~~~~//~~~~~~~~~~~~~~~~~~~~//~~~~~~~~~~~~~~~~~~~~//~~~~~~~~~~~~~~~~~~~~~//
  1722. /* From stock Projectile code...
  1723. DefineEngineMethod(Projectile, presimulate, void, (F32 seconds), (1.0f), "Updates velocity and position, and performs collision testing.\n"
  1724. "@param seconds Amount of time, in seconds, since the simulation began, to start the simulation at.\n"
  1725. "@tsexample\n"
  1726. "// Tell the projectile object to process a simulation event, and provide the amount of time\n"
  1727. " in seconds that has passed since the simulation began.\n"
  1728. "%seconds = 2000;\n"
  1729. "%projectile.presimulate(%seconds);\n"
  1730. "@endtsexample\n")
  1731. {
  1732. object->simulate( seconds );
  1733. }
  1734. */
  1735. DefineEngineMethod(afxMagicMissile, setStartingVelocityVector, void, (Point3F velocityVec),,
  1736. "Set the starting velocity-vector for a magic-missile.\n\n"
  1737. "@ingroup AFX")
  1738. {
  1739. object->setStartingVelocityVector(velocityVec);
  1740. }
  1741. DefineEngineMethod(afxMagicMissile, setStartingVelocity, void, (float velocity),,
  1742. "Set the starting velocity for a magic-missile.\n\n"
  1743. "@ingroup AFX")
  1744. {
  1745. object->setStartingVelocity(velocity);
  1746. }
  1747. //~~~~~~~~~~~~~~~~~~~~//~~~~~~~~~~~~~~~~~~~~//~~~~~~~~~~~~~~~~~~~~//~~~~~~~~~~~~~~~~~~~~~//