afxMagicMissile.cpp 65 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110
  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) override
  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. INIT_ASSET(ProjectileSound);
  129. /* From stock Projectile code...
  130. explosion = NULL;
  131. explosionId = 0;
  132. waterExplosion = NULL;
  133. waterExplosionId = 0;
  134. */
  135. /* From stock Projectile code...
  136. faceViewer = false;
  137. */
  138. scale.set( 1.0f, 1.0f, 1.0f );
  139. isBallistic = false;
  140. /* From stock Projectile code...
  141. velInheritFactor = 1.0f;
  142. */
  143. muzzleVelocity = 50;
  144. /* From stock Projectile code...
  145. impactForce = 0.0f;
  146. armingDelay = 0;
  147. activateSeq = -1;
  148. maintainSeq = -1;
  149. */
  150. lifetime = 20000 / 32;
  151. fadeDelay = 20000 / 32;
  152. gravityMod = 1.0;
  153. /* From stock Projectile code...
  154. bounceElasticity = 0.999f;
  155. bounceFriction = 0.3f;
  156. */
  157. particleEmitter = NULL;
  158. particleEmitterId = 0;
  159. particleWaterEmitter = NULL;
  160. particleWaterEmitterId = 0;
  161. splash = NULL;
  162. splashId = 0;
  163. /* From stock Projectile code...
  164. decal = NULL;
  165. decalId = 0;
  166. */
  167. lightDesc = NULL;
  168. lightDescId = 0;
  169. starting_vel_vec.zero();
  170. isGuided = false;
  171. precision = 0;
  172. trackDelay = 0;
  173. ballisticCoefficient = 1.0f;
  174. followTerrain = false;
  175. followTerrainHeight = 0.1f;
  176. followTerrainAdjustRate = 20.0f;
  177. followTerrainAdjustDelay = 0;
  178. lifetime = MaxLifetimeTicks;
  179. collision_mask = arcaneFX::sMissileCollisionMask;
  180. acceleration = 0;
  181. accelDelay = 0;
  182. accelLifetime = 0;
  183. launch_node = ST_NULLSTRING;
  184. launch_offset.zero();
  185. launch_offset_server.zero();
  186. launch_offset_client.zero();
  187. launch_node_offset.zero();
  188. launch_pitch = 0;
  189. launch_pan = 0;
  190. launch_cons_s_spec = ST_NULLSTRING;
  191. launch_cons_c_spec = ST_NULLSTRING;
  192. echo_launch_offset = false;
  193. wiggle_axis_string = ST_NULLSTRING;
  194. wiggle_num_axis = 0;
  195. wiggle_axis = 0;
  196. hover_altitude = 0;
  197. hover_attack_distance = 0;
  198. hover_attack_gradient = 0;
  199. hover_time = 0;
  200. reverse_targeting = false;
  201. caster_safety_time = U32_MAX;
  202. mProjectileShapeAsset.registerRefreshNotify(this);
  203. }
  204. afxMagicMissileData::afxMagicMissileData(const afxMagicMissileData& other, bool temp_clone) : GameBaseData(other, temp_clone)
  205. {
  206. mProjectileShapeAsset = other.mProjectileShapeAsset;
  207. projectileShape = other.projectileShape; // -- TSShape loads using projectileShapeName
  208. CLONE_ASSET(ProjectileSound);
  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. mProjectileShapeAsset.unregisterRefreshNotify();
  265. }
  266. afxMagicMissileData* afxMagicMissileData::cloneAndPerformSubstitutions(const SimObject* owner, S32 index)
  267. {
  268. if (!owner || getSubstitutionCount() == 0)
  269. return this;
  270. afxMagicMissileData* sub_missile_db = new afxMagicMissileData(*this, true);
  271. performSubstitutions(sub_missile_db, owner, index);
  272. return sub_missile_db;
  273. }
  274. //--------------------------------------------------------------------------
  275. #define myOffset(field) Offset(field, afxMagicMissileData)
  276. FRangeValidator muzzleVelocityValidator(0, 10000);
  277. FRangeValidator missilePrecisionValidator(0.f, 100.f);
  278. IRangeValidator missileTrackDelayValidator(0, 100000);
  279. FRangeValidator missileBallisticCoefficientValidator(0, 1);
  280. FRangeValidator missileFollowTerrainAdjustRateValidator(0.05f, FLT_MAX);
  281. void afxMagicMissileData::initPersistFields()
  282. {
  283. docsURL;
  284. static IRangeValidatorScaled ticksFromMS(TickMs, 0, MaxLifetimeTicks);
  285. addGroup("Shapes");
  286. INITPERSISTFIELD_SHAPEASSET_REFACTOR(ProjectileShape, afxMagicMissileData, "Shape for the projectile");
  287. addField("scale", TypePoint3F, Offset(scale, afxMagicMissileData));
  288. addField("missileShapeScale", TypePoint3F, myOffset(scale));
  289. endGroup("Shapes");
  290. addGroup("Particle Effects");
  291. addField("particleEmitter", TYPEID<ParticleEmitterData>(), Offset(particleEmitter, afxMagicMissileData));
  292. addField("particleWaterEmitter", TYPEID<ParticleEmitterData>(), Offset(particleWaterEmitter, afxMagicMissileData));
  293. addField("splash", TYPEID<SplashData>(), Offset(splash, afxMagicMissileData));
  294. endGroup("Particle Effects");
  295. addGroup("Sounds");
  296. INITPERSISTFIELD_SOUNDASSET(ProjectileSound, afxMagicMissileData, "sound for the projectile");
  297. endGroup("Sounds");
  298. addGroup("Light Emitter");
  299. addField("lightDesc", TYPEID< LightDescription >(), Offset(lightDesc, afxMagicMissileData));
  300. endGroup("Light Emitter");
  301. addGroup("Physics");
  302. addNamedFieldV(lifetime, TypeRangedS32, afxMagicMissileData, &ticksFromMS);
  303. addFieldV("casterSafetyTime", TypeRangedS32, myOffset(caster_safety_time), &ticksFromMS);
  304. addField("isBallistic", TypeBool, Offset(isBallistic, afxMagicMissileData));
  305. addNamedFieldV(muzzleVelocity, TypeRangedF32, afxMagicMissileData, &muzzleVelocityValidator);
  306. addNamedFieldV(ballisticCoefficient, TypeRangedF32, afxMagicMissileData, &missileBallisticCoefficientValidator);
  307. addFieldV("gravityMod", TypeRangedF32, Offset(gravityMod, afxMagicMissileData), &CommonValidators::F32Range);
  308. addField("collisionMask", TypeS32, myOffset(collision_mask));
  309. addField("startingVelocityVector",TypePoint3F, myOffset(starting_vel_vec));
  310. addNamedField(acceleration, TypeF32, afxMagicMissileData);
  311. addNamedFieldV(accelDelay, TypeRangedS32, afxMagicMissileData, &ticksFromMS);
  312. addNamedFieldV(accelLifetime, TypeRangedS32, afxMagicMissileData, &ticksFromMS);
  313. addField("reverseTargeting", TypeBool, myOffset(reverse_targeting));
  314. endGroup("Physics");
  315. addGroup("Physics-Tracking");
  316. addNamedField(isGuided, TypeBool, afxMagicMissileData);
  317. addNamedFieldV(precision, TypeRangedF32, afxMagicMissileData, &missilePrecisionValidator);
  318. addNamedFieldV(trackDelay, TypeRangedS32, afxMagicMissileData, &missileTrackDelayValidator);
  319. endGroup("Physics-Tracking");
  320. addGroup("Physics-Avoidance");
  321. addField("followTerrain", TypeBool, myOffset(followTerrain));
  322. addFieldV("followTerrainHeight", TypeRangedS32, myOffset(followTerrainHeight), &CommonValidators::PositiveFloat);
  323. addFieldV("followTerrainAdjustRate", TypeRangedS32, myOffset(followTerrainAdjustRate), &missileFollowTerrainAdjustRateValidator);
  324. addFieldV("followTerrainAdjustDelay", TypeRangedS32, myOffset(followTerrainAdjustDelay), &ticksFromMS);
  325. addFieldV("hoverAltitude", TypeRangedF32, myOffset(hover_altitude), &CommonValidators::PositiveFloat);
  326. addFieldV("hoverAttackDistance", TypeRangedF32, myOffset(hover_attack_distance), &CommonValidators::PositiveFloat);
  327. addFieldV("hoverAttackGradient", TypeRangedF32, myOffset(hover_attack_gradient), &CommonValidators::PositiveNonZeroFloat);
  328. addFieldV("hoverTime", TypeRangedS32, myOffset(hover_time), &ticksFromMS);
  329. endGroup("Physics-Avoidance");
  330. addGroup("Physics-Launch");
  331. addField("launchNode", TypeString, myOffset(launch_node));
  332. addField("launchOffset", TypePoint3F, myOffset(launch_offset));
  333. addField("launchOffsetServer",TypePoint3F, myOffset(launch_offset_server));
  334. addField("launchOffsetClient",TypePoint3F, myOffset(launch_offset_client));
  335. addField("launchNodeOffset", TypePoint3F, myOffset(launch_node_offset));
  336. addFieldV("launchAimPitch", TypeRangedF32, myOffset(launch_pitch), &CommonValidators::DegreeRange);
  337. addFieldV("launchAimPan", TypeRangedF32, myOffset(launch_pan), &CommonValidators::DegreeRange);
  338. addField("launchConstraintServer", TypeString, myOffset(launch_cons_s_spec));
  339. addField("launchConstraintClient", TypeString, myOffset(launch_cons_c_spec));
  340. addField("echoLaunchOffset", TypeBool, myOffset(echo_launch_offset));
  341. endGroup("Physics-Launch");
  342. addGroup("Physics-Wiggle");
  343. addField("wiggleMagnitudes", TypeF32Vector, myOffset(wiggle_magnitudes));
  344. addField("wiggleSpeeds", TypeF32Vector, myOffset(wiggle_speeds));
  345. addField("wiggleAxis", TypeString, myOffset(wiggle_axis_string));
  346. endGroup("Physics-Wiggle");
  347. Parent::initPersistFields();
  348. // disallow some field substitutions
  349. onlyKeepClearSubstitutions("particleEmitter"); // subs resolving to "~~", or "~0" are OK
  350. onlyKeepClearSubstitutions("particleWaterEmitter");
  351. onlyKeepClearSubstitutions("sound");
  352. onlyKeepClearSubstitutions("splash");
  353. }
  354. //--------------------------------------------------------------------------
  355. bool afxMagicMissileData::onAdd()
  356. {
  357. if(!Parent::onAdd())
  358. return false;
  359. // ADDED BY MAGIC-MISSILE
  360. // Wiggle axes ////////////////////////////////////////////////////////////
  361. if (wiggle_axis_string != ST_NULLSTRING && wiggle_num_axis == 0)
  362. {
  363. // Tokenize input string and convert to Point3F array
  364. //
  365. Vector<String> dataBlocks(__FILE__, __LINE__);
  366. // make a copy of points_string
  367. dsize_t tokCopyLen = dStrlen(wiggle_axis_string) + 1;
  368. char* tokCopy = new char[tokCopyLen];
  369. dStrcpy(tokCopy, wiggle_axis_string, tokCopyLen);
  370. // extract tokens one by one, adding them to dataBlocks
  371. char* currTok = dStrtok(tokCopy, " \t");
  372. while (currTok != NULL)
  373. {
  374. dataBlocks.push_back(currTok);
  375. currTok = dStrtok(NULL, " \t");
  376. }
  377. // bail if there were no tokens in the string
  378. if (dataBlocks.size() == 0)
  379. {
  380. Con::warnf(ConsoleLogEntry::General, "afxMagicMissileData(%s) invalid wiggle axis string. No tokens found", getName());
  381. delete [] tokCopy;
  382. return false;
  383. }
  384. // Find wiggle_num_axis (round up to multiple of 3) // WARNING here if not multiple of 3?
  385. for (U32 i = 0; i < dataBlocks.size()%3; i++)
  386. {
  387. dataBlocks.push_back("0.0");
  388. }
  389. wiggle_num_axis = dataBlocks.size()/3;
  390. wiggle_axis = new Point3F[wiggle_num_axis];
  391. U32 p_i = 0;
  392. for (U32 i = 0; i < dataBlocks.size(); i+=3, p_i++)
  393. {
  394. F32 x,y,z;
  395. x = dAtof(dataBlocks[i]); // What about overflow?
  396. y = dAtof(dataBlocks[i+1]);
  397. z = dAtof(dataBlocks[i+2]);
  398. wiggle_axis[p_i].set(x,y,z);
  399. wiggle_axis[p_i].normalizeSafe(); // sufficient????
  400. }
  401. delete [] tokCopy;
  402. }
  403. launch_cons_s_def.parseSpec(launch_cons_s_spec, true, false);
  404. launch_cons_c_def.parseSpec(launch_cons_c_spec, false, true);
  405. return true;
  406. }
  407. bool afxMagicMissileData::preload(bool server, String &errorStr)
  408. {
  409. if (Parent::preload(server, errorStr) == false)
  410. return false;
  411. if( !server )
  412. {
  413. if (!particleEmitter && particleEmitterId != 0)
  414. if (Sim::findObject(particleEmitterId, particleEmitter) == false)
  415. Con::errorf(ConsoleLogEntry::General, "afxMagicMissileData::preload: Invalid packet, bad datablockId(particleEmitter): %d", particleEmitterId);
  416. if (!particleWaterEmitter && particleWaterEmitterId != 0)
  417. if (Sim::findObject(particleWaterEmitterId, particleWaterEmitter) == false)
  418. Con::errorf(ConsoleLogEntry::General, "afxMagicMissileData::preload: Invalid packet, bad datablockId(particleWaterEmitter): %d", particleWaterEmitterId);
  419. /* From stock Projectile code...
  420. if (!explosion && explosionId != 0)
  421. if (Sim::findObject(explosionId, explosion) == false)
  422. Con::errorf(ConsoleLogEntry::General, "ProjectileData::preload: Invalid packet, bad datablockId(explosion): %d", explosionId);
  423. if (!waterExplosion && waterExplosionId != 0)
  424. if (Sim::findObject(waterExplosionId, waterExplosion) == false)
  425. Con::errorf(ConsoleLogEntry::General, "ProjectileData::preload: Invalid packet, bad datablockId(waterExplosion): %d", waterExplosionId);
  426. */
  427. if (!splash && splashId != 0)
  428. if (Sim::findObject(splashId, splash) == false)
  429. Con::errorf(ConsoleLogEntry::General, "afxMagicMissileData::preload: Invalid packet, bad datablockId(splash): %d", splashId);
  430. /* From stock Projectile code...
  431. if (!decal && decalId != 0)
  432. if (Sim::findObject(decalId, decal) == false)
  433. Con::errorf(ConsoleLogEntry::General, "ProjectileData::preload: Invalid packet, bad datablockId(decal): %d", decalId);
  434. */
  435. if (!isProjectileSoundValid())
  436. {
  437. //return false; -TODO: trigger asset download
  438. }
  439. if (!lightDesc && lightDescId != 0)
  440. if (Sim::findObject(lightDescId, lightDesc) == false)
  441. Con::errorf(ConsoleLogEntry::General, "afxMagicMissileData::preload: Invalid packet, bad datablockid(lightDesc): %d", lightDescId);
  442. }
  443. U32 assetStatus = ShapeAsset::getAssetErrCode(mProjectileShapeAsset);
  444. if (assetStatus == AssetBase::Ok || assetStatus == AssetBase::UsingFallback)
  445. {
  446. projectileShape = getProjectileShape();
  447. if (bool(projectileShape) == false)
  448. {
  449. errorStr = String::ToString("afxMagicMissileData::preload: Couldn't load shape \"%s\"", _getProjectileShapeAssetId());
  450. return false;
  451. }
  452. /* From stock Projectile code...
  453. activateSeq = projectileShape->findSequence("activate");
  454. maintainSeq = projectileShape->findSequence("maintain");
  455. */
  456. }
  457. if (bool(projectileShape)) // create an instance to preload shape data
  458. {
  459. TSShapeInstance* pDummy = new TSShapeInstance(projectileShape, !server);
  460. delete pDummy;
  461. }
  462. return true;
  463. }
  464. //--------------------------------------------------------------------------
  465. // Modified from floorPlanRes.cc
  466. // Read a vector of items
  467. template <class T>
  468. bool readVector(Vector<T> & vec, Stream & stream, const char * msg)
  469. {
  470. U32 num, i;
  471. bool Ok = true;
  472. stream.read( & num );
  473. vec.setSize( num );
  474. for( i = 0; i < num && Ok; i++ ){
  475. Ok = stream.read(& vec[i]);
  476. AssertISV( Ok, avar("math vec read error (%s) on elem %d", msg, i) );
  477. }
  478. return Ok;
  479. }
  480. // Write a vector of items
  481. template <class T>
  482. bool writeVector(const Vector<T> & vec, Stream & stream, const char * msg)
  483. {
  484. bool Ok = true;
  485. stream.write( vec.size() );
  486. for( U32 i = 0; i < vec.size() && Ok; i++ ) {
  487. Ok = stream.write(vec[i]);
  488. AssertISV( Ok, avar("vec write error (%s) on elem %d", msg, i) );
  489. }
  490. return Ok;
  491. }
  492. //--------------------------------------------------------------------------
  493. void afxMagicMissileData::packData(BitStream* stream)
  494. {
  495. Parent::packData(stream);
  496. PACKDATA_ASSET_REFACTOR(ProjectileShape);
  497. /* From stock Projectile code...
  498. stream->writeFlag(faceViewer);
  499. */
  500. if(stream->writeFlag(scale.x != 1 || scale.y != 1 || scale.z != 1))
  501. {
  502. stream->write(scale.x);
  503. stream->write(scale.y);
  504. stream->write(scale.z);
  505. }
  506. stream->write(collision_mask);
  507. if (stream->writeFlag(particleEmitter != NULL))
  508. stream->writeRangedU32(particleEmitter->getId(), DataBlockObjectIdFirst,
  509. DataBlockObjectIdLast);
  510. if (stream->writeFlag(particleWaterEmitter != NULL))
  511. stream->writeRangedU32(particleWaterEmitter->getId(), DataBlockObjectIdFirst,
  512. DataBlockObjectIdLast);
  513. /* From stock Projectile code...
  514. if (stream->writeFlag(explosion != NULL))
  515. stream->writeRangedU32(explosion->getId(), DataBlockObjectIdFirst,
  516. DataBlockObjectIdLast);
  517. if (stream->writeFlag(waterExplosion != NULL))
  518. stream->writeRangedU32(waterExplosion->getId(), DataBlockObjectIdFirst,
  519. DataBlockObjectIdLast);
  520. */
  521. if (stream->writeFlag(splash != NULL))
  522. stream->writeRangedU32(splash->getId(), DataBlockObjectIdFirst,
  523. DataBlockObjectIdLast);
  524. /* From stock Projectile code...
  525. if (stream->writeFlag(decal != NULL))
  526. stream->writeRangedU32(decal->getId(), DataBlockObjectIdFirst,
  527. DataBlockObjectIdLast);
  528. */
  529. PACKDATA_ASSET(ProjectileSound);
  530. if ( stream->writeFlag(lightDesc != NULL))
  531. stream->writeRangedU32(lightDesc->getId(), DataBlockObjectIdFirst,
  532. DataBlockObjectIdLast);
  533. /* From stock Projectile code...
  534. stream->write(impactForce);
  535. */
  536. stream->write(lifetime);
  537. /* From stock Projectile code...
  538. stream->write(armingDelay);
  539. stream->write(fadeDelay);
  540. */
  541. if(stream->writeFlag(isBallistic))
  542. {
  543. stream->write(gravityMod);
  544. /* From stock Projectile code...
  545. stream->write(bounceElasticity);
  546. stream->write(bounceFriction);
  547. */
  548. stream->write(ballisticCoefficient);
  549. }
  550. if(stream->writeFlag(isGuided))
  551. {
  552. stream->write(precision);
  553. stream->write(trackDelay);
  554. }
  555. stream->write(muzzleVelocity);
  556. mathWrite(*stream, starting_vel_vec);
  557. stream->write(acceleration);
  558. stream->write(accelDelay);
  559. stream->write(accelLifetime);
  560. stream->writeString(launch_node);
  561. mathWrite(*stream, launch_offset);
  562. mathWrite(*stream, launch_offset_server);
  563. mathWrite(*stream, launch_offset_client);
  564. mathWrite(*stream, launch_node_offset);
  565. stream->write(launch_pitch);
  566. stream->write(launch_pan);
  567. stream->writeString(launch_cons_c_spec);
  568. stream->writeFlag(echo_launch_offset);
  569. writeVector(wiggle_magnitudes, *stream, "afxMagicMissile: wiggle_magnitudes");
  570. writeVector(wiggle_speeds, *stream, "afxMagicMissile: wiggle_speeds");
  571. stream->write(wiggle_num_axis);
  572. for (U32 i = 0; i < wiggle_num_axis; i++)
  573. mathWrite(*stream, wiggle_axis[i]);
  574. stream->write(hover_altitude);
  575. stream->write(hover_attack_distance);
  576. stream->write(hover_attack_gradient);
  577. stream->writeRangedU32(hover_time, 0, MaxLifetimeTicks);
  578. stream->writeFlag(reverse_targeting);
  579. stream->write(caster_safety_time);
  580. }
  581. void afxMagicMissileData::unpackData(BitStream* stream)
  582. {
  583. Parent::unpackData(stream);
  584. UNPACKDATA_ASSET_REFACTOR(ProjectileShape);
  585. /* From stock Projectile code...
  586. faceViewer = stream->readFlag();
  587. */
  588. if(stream->readFlag())
  589. {
  590. stream->read(&scale.x);
  591. stream->read(&scale.y);
  592. stream->read(&scale.z);
  593. }
  594. else
  595. scale.set(1,1,1);
  596. stream->read(&collision_mask);
  597. if (stream->readFlag())
  598. particleEmitterId = stream->readRangedU32(DataBlockObjectIdFirst, DataBlockObjectIdLast);
  599. if (stream->readFlag())
  600. particleWaterEmitterId = stream->readRangedU32(DataBlockObjectIdFirst, DataBlockObjectIdLast);
  601. /* From stock Projectile code...
  602. if (stream->readFlag())
  603. explosionId = stream->readRangedU32(DataBlockObjectIdFirst, DataBlockObjectIdLast);
  604. if (stream->readFlag())
  605. waterExplosionId = stream->readRangedU32(DataBlockObjectIdFirst, DataBlockObjectIdLast);
  606. */
  607. if (stream->readFlag())
  608. splashId = stream->readRangedU32(DataBlockObjectIdFirst, DataBlockObjectIdLast);
  609. /* From stock Projectile code...
  610. if (stream->readFlag())
  611. decalId = stream->readRangedU32(DataBlockObjectIdFirst, DataBlockObjectIdLast);
  612. */
  613. UNPACKDATA_ASSET(ProjectileSound);
  614. if (stream->readFlag())
  615. lightDescId = stream->readRangedU32(DataBlockObjectIdFirst, DataBlockObjectIdLast);
  616. /* From stock Projectile code...
  617. stream->read(&impactForce);
  618. */
  619. stream->read(&lifetime);
  620. /* From stock Projectile code...
  621. stream->read(&armingDelay);
  622. stream->read(&fadeDelay);
  623. */
  624. isBallistic = stream->readFlag();
  625. if(isBallistic)
  626. {
  627. stream->read(&gravityMod);
  628. /* From stock Projectile code...
  629. stream->read(&bounceElasticity);
  630. stream->read(&bounceFriction);
  631. */
  632. stream->read(&ballisticCoefficient);
  633. }
  634. isGuided = stream->readFlag();
  635. if(isGuided)
  636. {
  637. stream->read(&precision);
  638. stream->read(&trackDelay);
  639. }
  640. stream->read(&muzzleVelocity);
  641. mathRead(*stream, &starting_vel_vec);
  642. stream->read(&acceleration);
  643. stream->read(&accelDelay);
  644. stream->read(&accelLifetime);
  645. launch_node = stream->readSTString();
  646. mathRead(*stream, &launch_offset);
  647. mathRead(*stream, &launch_offset_server);
  648. mathRead(*stream, &launch_offset_client);
  649. mathRead(*stream, &launch_node_offset);
  650. stream->read(&launch_pitch);
  651. stream->read(&launch_pan);
  652. launch_cons_c_spec = stream->readSTString();
  653. echo_launch_offset = stream->readFlag();
  654. readVector(wiggle_magnitudes, *stream, "afxMagicMissile: wiggle_magnitudes");
  655. readVector(wiggle_speeds, *stream, "afxMagicMissile: wiggle_speeds");
  656. if (wiggle_axis)
  657. delete [] wiggle_axis;
  658. wiggle_axis = 0;
  659. wiggle_num_axis = 0;
  660. stream->read(&wiggle_num_axis);
  661. if (wiggle_num_axis > 0)
  662. {
  663. wiggle_axis = new Point3F[wiggle_num_axis];
  664. for (U32 i = 0; i < wiggle_num_axis; i++)
  665. mathRead(*stream, &wiggle_axis[i]);
  666. }
  667. stream->read(&hover_altitude);
  668. stream->read(&hover_attack_distance);
  669. stream->read(&hover_attack_gradient);
  670. hover_time = stream->readRangedU32(0, MaxLifetimeTicks);
  671. reverse_targeting = stream->readFlag();
  672. stream->read(&caster_safety_time);
  673. }
  674. /* From stock Projectile code...
  675. bool ProjectileData::setLifetime( void *obj, const char *index, const char *data )
  676. {
  677. S32 value = dAtoi(data);
  678. value = scaleValue(value);
  679. ProjectileData *object = static_cast<ProjectileData*>(obj);
  680. object->lifetime = value;
  681. return false;
  682. }
  683. bool ProjectileData::setArmingDelay( void *obj, const char *index, const char *data )
  684. {
  685. S32 value = dAtoi(data);
  686. value = scaleValue(value);
  687. ProjectileData *object = static_cast<ProjectileData*>(obj);
  688. object->armingDelay = value;
  689. return false;
  690. }
  691. bool ProjectileData::setFadeDelay( void *obj, const char *index, const char *data )
  692. {
  693. S32 value = dAtoi(data);
  694. value = scaleValue(value);
  695. ProjectileData *object = static_cast<ProjectileData*>(obj);
  696. object->fadeDelay = value;
  697. return false;
  698. }
  699. const char *ProjectileData::getScaledValue( void *obj, const char *data)
  700. {
  701. S32 value = dAtoi(data);
  702. value = scaleValue(value, false);
  703. String stringData = String::ToString(value);
  704. char *strBuffer = Con::getReturnBuffer(stringData.size());
  705. dMemcpy( strBuffer, stringData, stringData.size() );
  706. return strBuffer;
  707. }
  708. S32 ProjectileData::scaleValue( S32 value, bool down )
  709. {
  710. S32 minV = 0;
  711. S32 maxV = Projectile::MaxLivingTicks;
  712. // scale down to ticks before we validate
  713. if( down )
  714. value /= TickMs;
  715. if(value < minV || value > maxV)
  716. {
  717. Con::errorf("ProjectileData::scaleValue(S32 value = %d, bool down = %b) - Scaled value must be between %d and %d", value, down, minV, maxV);
  718. if(value < minV)
  719. value = minV;
  720. else if(value > maxV)
  721. value = maxV;
  722. }
  723. // scale up from ticks after we validate
  724. if( !down )
  725. value *= TickMs;
  726. return value;
  727. }
  728. */
  729. void afxMagicMissileData::gather_cons_defs(Vector<afxConstraintDef>& defs)
  730. {
  731. if (launch_cons_s_def.isDefined())
  732. defs.push_back(launch_cons_s_def);
  733. if (launch_cons_c_def.isDefined())
  734. defs.push_back(launch_cons_c_def);
  735. };
  736. //~~~~~~~~~~~~~~~~~~~~//~~~~~~~~~~~~~~~~~~~~//~~~~~~~~~~~~~~~~~~~~//~~~~~~~~~~~~~~~~~~~~~//
  737. //~~~~~~~~~~~~~~~~~~~~//~~~~~~~~~~~~~~~~~~~~//~~~~~~~~~~~~~~~~~~~~//~~~~~~~~~~~~~~~~~~~~~//
  738. // afxMagicMissile
  739. afxMagicMissile::afxMagicMissile()
  740. {
  741. init(true, true);
  742. }
  743. afxMagicMissile::afxMagicMissile(bool on_server, bool on_client)
  744. {
  745. init(on_server, on_client);
  746. }
  747. //--------------------------------------------------------------------------
  748. //--------------------------------------
  749. //
  750. void afxMagicMissile::init(bool on_server, bool on_client)
  751. {
  752. mPhysicsWorld = NULL;
  753. mTypeMask |= ProjectileObjectType | LightObjectType;
  754. mLight = LightManager::createLightInfo();
  755. mLight->setType( LightInfo::Point );
  756. mLightState.clear();
  757. mLightState.setLightInfo( mLight );
  758. mCurrPosition.zero();
  759. mCurrVelocity.set(0, 0, 1);
  760. mCurrTick = 0;
  761. mParticleEmitter = NULL;
  762. mParticleWaterEmitter = NULL;
  763. mSound = 0;
  764. mProjectileShape = NULL;
  765. mDataBlock = NULL;
  766. choreographer = NULL;
  767. if (on_server != on_client)
  768. {
  769. client_only = on_client;
  770. server_only = on_server;
  771. mNetFlags.clear(Ghostable | ScopeAlways);
  772. if (client_only)
  773. mNetFlags.set(IsGhost);
  774. }
  775. else
  776. {
  777. // note -- setting neither server or client makes no sense so we
  778. // treat as if both are set.
  779. mNetFlags.set(Ghostable | ScopeAlways);
  780. client_only = server_only = false;
  781. }
  782. mCurrDeltaBase.zero();
  783. mCurrBackDelta.zero();
  784. collision_mask = 0;
  785. prec_inc = 0.0f;
  786. did_launch = false;
  787. did_impact = false;
  788. missile_target = NULL;
  789. collide_exempt = NULL;
  790. use_accel = false;
  791. hover_attack_go = false;
  792. hover_attack_tick = 0;
  793. starting_velocity = 0.0;
  794. starting_vel_vec.zero();
  795. ss_object = 0;
  796. ss_index = 0;
  797. }
  798. afxMagicMissile::~afxMagicMissile()
  799. {
  800. SAFE_DELETE(mLight);
  801. delete mProjectileShape;
  802. mProjectileShape = NULL;
  803. }
  804. //--------------------------------------------------------------------------
  805. void afxMagicMissile::initPersistFields()
  806. {
  807. docsURL;
  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->getProjectileSound())
  956. mSound = SFX->createSource(mDataBlock->getProjectileSoundProfile());
  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->isProjectileSoundValid())
  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. //~~~~~~~~~~~~~~~~~~~~//~~~~~~~~~~~~~~~~~~~~//~~~~~~~~~~~~~~~~~~~~//~~~~~~~~~~~~~~~~~~~~~//