miscgameplayfunctions.c 59 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953
  1. class TurnItemIntoItemLambda extends ReplaceItemWithNewLambda
  2. {
  3. bool m_TransferAgents;
  4. bool m_TransferVariables;
  5. bool m_TransferHealth;
  6. bool m_ExcludeQuantity;
  7. float m_quantity_override;
  8. void TurnItemIntoItemLambda (EntityAI old_item, string new_item_type, PlayerBase player)
  9. {
  10. SetTransferParams();
  11. }
  12. void SetTransferParams (bool transfer_agents = true, bool transfer_variables = true, bool transfer_health = true, bool exclude_quantity = false, float quantity_override = -1)
  13. {
  14. m_TransferAgents = transfer_agents;
  15. m_TransferVariables = transfer_variables;
  16. m_TransferHealth = transfer_health;
  17. m_ExcludeQuantity = exclude_quantity;
  18. m_quantity_override = quantity_override;
  19. }
  20. override void CopyOldPropertiesToNew (notnull EntityAI old_item, EntityAI new_item)
  21. {
  22. super.CopyOldPropertiesToNew(old_item, new_item);
  23. if (new_item)
  24. {
  25. MiscGameplayFunctions.TransferItemProperties(old_item, new_item, m_TransferAgents, m_TransferVariables, m_TransferHealth, m_ExcludeQuantity);
  26. MiscGameplayFunctions.TransferInventory(old_item, new_item, m_Player);
  27. //quantity override
  28. if (ItemBase.Cast(new_item) && m_quantity_override != -1)
  29. {
  30. m_quantity_override = Math.Max(m_quantity_override,0);
  31. ItemBase.Cast(new_item).SetQuantity(m_quantity_override);
  32. }
  33. }
  34. else
  35. {
  36. Debug.LogError("TurnItemIntoItemLambda: failed to create new item","static");
  37. }
  38. }
  39. //! if attaching from att.slot to att.slot, skips the change to "ground" version. Allows for correct property transfers.
  40. override void VerifyItemTypeBySlotType ()
  41. {
  42. if (m_NewLocation.GetType() == InventoryLocationType.ATTACHMENT && m_OldItem.ConfigIsExisting("ChangeIntoOnAttach"))
  43. {
  44. string str;
  45. int idx = -1;
  46. TStringArray inventory_slots = new TStringArray;
  47. TIntArray inventory_slots_idx = new TIntArray;
  48. TStringArray attach_types = new TStringArray;
  49. m_OldItem.ConfigGetTextArray("ChangeInventorySlot",inventory_slots);
  50. if (inventory_slots.Count() < 1) //is string
  51. {
  52. inventory_slots_idx.Insert(InventorySlots.GetSlotIdFromString(m_OldItem.ConfigGetString("ChangeInventorySlot")));
  53. attach_types.Insert(m_OldItem.ConfigGetString("ChangeIntoOnAttach"));
  54. }
  55. else //is array
  56. {
  57. inventory_slots_idx.Clear();
  58. for (int i = 0; i < inventory_slots.Count(); ++i)
  59. {
  60. inventory_slots_idx.Insert(InventorySlots.GetSlotIdFromString(inventory_slots.Get(i)));
  61. }
  62. m_OldItem.ConfigGetTextArray("ChangeIntoOnAttach",attach_types);
  63. }
  64. idx = m_NewLocation.GetSlot();
  65. str = attach_types.Get(inventory_slots_idx.Find(idx));
  66. if (str != "")
  67. {
  68. m_NewItemType = str;
  69. }
  70. }
  71. }
  72. override void OnSuccess (EntityAI new_item)
  73. {
  74. super.OnSuccess(new_item);
  75. if( m_Player )
  76. {
  77. m_Player.GetItemAccessor().OnItemInHandsChanged();
  78. }
  79. }
  80. };
  81. class TurnItemIntoItemLambdaAnimSysNotifyLambda extends TurnItemIntoItemLambda
  82. {
  83. override void OnSuccess (EntityAI new_item)
  84. {
  85. super.OnSuccess(new_item);
  86. if( m_Player )
  87. {
  88. m_Player.GetItemAccessor().OnItemInHandsChanged();
  89. }
  90. }
  91. }
  92. class TurnItemIntoItemLambdaRestrainLambda extends TurnItemIntoItemLambdaAnimSysNotifyLambda
  93. {
  94. override void OnSuccess (EntityAI new_item)
  95. {
  96. super.OnSuccess(new_item);
  97. m_Player.SetRestrained(true);
  98. }
  99. }
  100. /**@class DropEquipAndDestroyRootLambda
  101. * @brief this one is a bit special: it drops all items and destroys the ex-root of the hierarchy
  102. **/
  103. class DropEquipAndDestroyRootLambda : ReplaceItemWithNewLambdaBase
  104. {
  105. PlayerBase m_Player;
  106. void DropEquipAndDestroyRootLambda (EntityAI old_item, string new_item_type, PlayerBase player)
  107. {
  108. m_Player = player;
  109. }
  110. override void CopyOldPropertiesToNew (notnull EntityAI old_item, EntityAI new_item)
  111. {
  112. super.CopyOldPropertiesToNew(old_item, new_item);
  113. InventoryLocation understash_src = m_NewLocation; // m_NewLocation is a backup of original old_item's src before the operation started
  114. array<EntityAI> children = new array<EntityAI>;
  115. old_item.GetInventory().EnumerateInventory(InventoryTraversalType.LEVELORDER, children);
  116. int count = children.Count();
  117. for (int i = 0; i < count; ++i)
  118. {
  119. EntityAI child = children.Get(i);
  120. if (child)
  121. {
  122. InventoryLocation child_src = new InventoryLocation;
  123. child.GetInventory().GetCurrentInventoryLocation(child_src);
  124. InventoryLocation child_dst = new InventoryLocation;
  125. //@TODO: modify _dst with place on gnd?
  126. vector m4[4];
  127. Math3D.MatrixIdentity4(m4);
  128. //! We don't care if a valid transform couldn't be found, we just want to preferably use it instead of placing on the old item
  129. GameInventory.PrepareDropEntityPos(old_item, child, m4, false, -1);
  130. child_dst.SetGround(child,m4);
  131. m_Player.LocalTakeToDst(child_src, child_dst);
  132. GetGame().RemoteObjectTreeCreate(child); // this forces server to send CreateVehicle Message to client. This is needed for preserving the appearance of network operations on client (so that DeleteObject(old) arrives before CreateVehicle(new)). @NOTE: this does not delete the object on server, only it's network representation.
  133. }
  134. }
  135. }
  136. }
  137. /**@class MoveEquipToExistingItemAndDestroyOldRootLambda
  138. * @brief this one is a also bit special: it moves all items to already existing item and destroys the ex-root of the hierarchy
  139. **/
  140. class MoveEquipToExistingItemAndDestroyOldRootLambda : ReplaceItemWithNewLambdaBase
  141. {
  142. PlayerBase m_Player;
  143. EntityAI m_NewItem;
  144. void MoveEquipToExistingItemAndDestroyOldRootLambda (EntityAI old_item, string new_item_type, PlayerBase player, EntityAI new_item)
  145. {
  146. m_Player = player;
  147. m_NewItem = new_item;
  148. if (new_item_type != string.Empty)
  149. Error("MoveEquipAndDestroyRootLambda expects new_item_type to be empty");
  150. }
  151. override protected void RemoveNetworkObjectInfo ()
  152. {
  153. super.RemoveNetworkObjectInfo();
  154. GetGame().RemoteObjectTreeDelete(m_NewItem);
  155. }
  156. override protected void UndoRemoveNetworkObjectInfo ()
  157. {
  158. super.UndoRemoveNetworkObjectInfo();
  159. GetGame().RemoteObjectTreeCreate(m_NewItem);
  160. }
  161. override void CopyOldPropertiesToNew (notnull EntityAI old_item, EntityAI new_item)
  162. {
  163. // @NOTE: new_item is NULL, this lambda does not create new entity
  164. super.CopyOldPropertiesToNew(old_item, new_item);
  165. MiscGameplayFunctions.TransferInventory(old_item, m_NewItem, m_Player);
  166. }
  167. override protected void CreateNetworkObjectInfo (EntityAI new_item)
  168. {
  169. super.CreateNetworkObjectInfo(new_item);
  170. GetGame().RemoteObjectTreeCreate(m_NewItem);
  171. }
  172. };
  173. enum TransferInventoryResult
  174. {
  175. Ok, DroppedSome
  176. };
  177. enum ThrowEntityFlags
  178. {
  179. NONE = 0,
  180. SPLIT = 1, //< Splits the item when it has quantity, recommended to use when called on an attachment
  181. }
  182. class MiscGameplayFunctions
  183. {
  184. //! truncate float to specified precision
  185. static float Truncate(float value, int decimals = 2)
  186. {
  187. int multiplier = Math.Pow(10,decimals);
  188. return Math.Clamp(Math.Floor(value * multiplier),float.LOWEST, float.MAX) / multiplier;
  189. }
  190. //! truncate float to specified precision, output as string
  191. static string TruncateToS(float value, int decimals = 2)
  192. {
  193. return Truncate(value, decimals).ToString();
  194. }
  195. //! truncate float to specified precision
  196. static vector TruncateVec(vector value, int decimals = 2)
  197. {
  198. int multiplier = Math.Pow(10,decimals);
  199. float v1 = Math.Clamp(Math.Floor(value[0] * multiplier),float.LOWEST, float.MAX) / multiplier;
  200. float v2 = Math.Clamp(Math.Floor(value[1] * multiplier),float.LOWEST, float.MAX) / multiplier;
  201. float v3 = Math.Clamp(Math.Floor(value[2] * multiplier),float.LOWEST, float.MAX) / multiplier;
  202. return Vector(v1,v2,v3);
  203. }
  204. static string TruncateVecToS(vector value,int decimals = 2, string delimiter = " ")
  205. {
  206. return MiscGameplayFunctions.TruncateToS(value[0],decimals) + delimiter + MiscGameplayFunctions.TruncateToS(value[1],decimals) +delimiter + MiscGameplayFunctions.TruncateToS(value[2],decimals));
  207. }
  208. static string GetColorString(float r, float g, float b, float a)
  209. {
  210. return string.Format("#(argb,8,8,3)color(%1,CO)", string.Format("%1,%2,%3,%4", r, g, b, a));
  211. }
  212. //! Produces ACII "progress bar" based on an 0..1 'value' input
  213. static string ValueToBar(float value, string bar = "[----------]", string mark = "x")
  214. {
  215. int length = bar.Length() - 2;
  216. float index = Math.Lerp(0,length, value);
  217. index = Math.Round(index);
  218. index = Math.Clamp(index,0,length);
  219. return InsertAtPos(bar,mark,index);
  220. }
  221. //! Insert 'insert' behind index 'pos' of the 'base' string
  222. static string InsertAtPos(string base, string insert, int pos)
  223. {
  224. int length_first = pos+1;
  225. int length_base = base.Length();
  226. int length_second = length_base - length_first;
  227. string first = base.Substring(0,length_first);
  228. string second = base.Substring(pos+1,length_second);
  229. return first + insert + second;
  230. }
  231. //! will transform variables, agents and other local scripted properties as well as any relevant non-scripted properties like health
  232. static void TransferItemProperties(EntityAI source, notnull EntityAI target, bool transfer_agents = true, bool transfer_variables = true, bool transfer_health = true, bool exclude_quantity = false)
  233. {
  234. ItemBase target_ib = ItemBase.Cast(target);
  235. if (transfer_agents && target_ib)
  236. target_ib.TransferAgents(source.GetAgents());
  237. if (transfer_variables)
  238. MiscGameplayFunctions.TransferEntityVariables(source, target, exclude_quantity);
  239. if (GetGame().IsServer() || !GetGame().IsMultiplayer())
  240. {
  241. if (transfer_health)
  242. {
  243. TransferEntityHealth(source,target,{"Health"});
  244. }
  245. }
  246. }
  247. static void TransferEntityVariables(EntityAI source, EntityAI target, bool exclude_quantity = false)
  248. {
  249. if (exclude_quantity)
  250. {
  251. int maskOriginal = source.m_VariablesMask;
  252. source.RemoveItemVariable(VARIABLE_QUANTITY);
  253. target.TransferVariablesFloat(source.GetVariablesFloat());
  254. source.m_VariablesMask = maskOriginal;
  255. }
  256. else
  257. {
  258. target.TransferVariablesFloat(source.GetVariablesFloat());
  259. }
  260. if (source.IsMagazine() && target.IsMagazine())
  261. {
  262. Magazine source_mag = Magazine.Cast(source);
  263. Magazine target_mag = Magazine.Cast(target);
  264. target_mag.ServerSetAmmoCount(source_mag.GetAmmoCount());
  265. }
  266. if (source.IsWeapon() && target.IsWeapon())
  267. {
  268. Weapon_Base source_wpn = Weapon_Base.Cast(source);
  269. Weapon_Base target_wpn = Weapon_Base.Cast(target);
  270. target_wpn.CopyWeaponStateFrom(source_wpn);
  271. }
  272. if (source.HasEnergyManager() && target.HasEnergyManager())
  273. {
  274. ComponentEnergyManager ems = source.GetCompEM();
  275. ComponentEnergyManager emt = target.GetCompEM();
  276. emt.SetEnergy(ems.GetEnergy());
  277. if (ems.IsSwitchedOn())
  278. emt.SwitchOn();
  279. }
  280. Edible_Base source_edb = Edible_Base.Cast(source);
  281. Edible_Base target_edb = Edible_Base.Cast(target);
  282. if (Class.CastTo(source_edb,source) && Class.CastTo(target_edb,target))
  283. {
  284. if (source_edb.CanDecay() && target_edb.CanDecay())
  285. target_edb.TransferFoodStage(source_edb);
  286. }
  287. }
  288. //! DEPRECATED
  289. static void TransferItemVariables(ItemBase source, ItemBase target, bool exclude_quantity = false)
  290. {
  291. TransferEntityVariables(source,target,exclude_quantity);
  292. }
  293. static TransferInventoryResult TransferInventory( EntityAI sourceItem, EntityAI targetItem, PlayerBase player)
  294. {
  295. TransferInventoryResult result = TransferInventoryResult.Ok;
  296. array<EntityAI> children = new array<EntityAI>;
  297. sourceItem.GetInventory().EnumerateInventory(InventoryTraversalType.LEVELORDER, children);
  298. int count = children.Count();
  299. for (int i = 0; i < count; ++i)
  300. {
  301. EntityAI child = children.Get(i);
  302. if (child)
  303. {
  304. InventoryLocation child_src = new InventoryLocation;
  305. child.GetInventory().GetCurrentInventoryLocation( child_src );
  306. InventoryLocation child_dst = new InventoryLocation;
  307. child_dst.Copy( child_src );
  308. child_dst.SetParent( targetItem );
  309. bool drop = false;
  310. if (GameInventory.LocationCanAddEntity(child_dst))
  311. {
  312. // try to move it to the same exact place in dst
  313. targetItem.GetInventory().TakeToDst(InventoryMode.LOCAL, child_src, child_dst);
  314. }
  315. else
  316. {
  317. drop = true; // or drop otherwise
  318. }
  319. if (drop)
  320. {
  321. player.LocalDropEntity(child);
  322. GetGame().RemoteObjectTreeCreate(child);
  323. result = TransferInventoryResult.DroppedSome;
  324. }
  325. }
  326. }
  327. return result;
  328. }
  329. static void TransferEntityHealth(EntityAI source, EntityAI target, array<string> healthTypes = null, bool transferZoneDamage = true)
  330. {
  331. array<string> HPTypes = new array<string>;
  332. if (!healthTypes || healthTypes.Count() == 0)
  333. HPTypes.Insert("Health");
  334. else
  335. HPTypes.Copy(healthTypes);
  336. if (transferZoneDamage)
  337. {
  338. TStringArray zonesSrc = new TStringArray;
  339. TStringArray zonesTgt = new TStringArray;
  340. source.GetDamageZones(zonesSrc);
  341. target.GetDamageZones(zonesTgt);
  342. foreach (string zone : zonesSrc)
  343. {
  344. if (zonesTgt.Find(zone) == -1)
  345. continue;
  346. foreach (string health : HPTypes)
  347. {
  348. target.SetHealth01(zone,health,source.GetHealth01(zone,health));
  349. }
  350. }
  351. }
  352. foreach (string gHealth : HPTypes)
  353. {
  354. target.SetHealth01("",gHealth,source.GetHealth01("",gHealth)); //global health last
  355. }
  356. }
  357. static void UnlimitedAmmoDebugCheck(Weapon_Base weapon)
  358. {
  359. if ( ItemBase.GetDebugActionsMask() & DebugActionType.UNLIMITED_AMMO )
  360. {
  361. Magazine magazine;
  362. if ( GetGame().IsServer() )
  363. {
  364. magazine = weapon.GetMagazine(weapon.GetCurrentMuzzle());
  365. if (magazine)
  366. {
  367. if (magazine.GetAmmoCount() <= 5)
  368. {
  369. magazine.ServerSetAmmoMax();
  370. }
  371. }
  372. }
  373. else
  374. {
  375. magazine = weapon.GetMagazine(weapon.GetCurrentMuzzle());
  376. if (magazine)
  377. {
  378. if (magazine.GetAmmoCount() <= 5)
  379. {
  380. magazine.LocalSetAmmoMax();
  381. }
  382. }
  383. }
  384. }
  385. }
  386. static void TurnItemIntoItem (notnull ItemBase old_item, string new_item_type, notnull PlayerBase player)
  387. {
  388. TurnItemIntoItemEx(player, new TurnItemIntoItemLambda(old_item, new_item_type, player));
  389. }
  390. static void TurnItemIntoItemEx (notnull PlayerBase player, ReplaceItemWithNewLambdaBase lambda)
  391. {
  392. player.ServerReplaceItemWithNew(lambda);
  393. }
  394. static void TurnItemInHandsIntoItem (notnull ItemBase old_item, string new_item_type, notnull PlayerBase player)
  395. {
  396. TurnItemInHandsIntoItemEx(player, new TurnItemIntoItemLambda(old_item, new_item_type, player));
  397. }
  398. static void TurnItemInHandsIntoItemEx (notnull PlayerBase player, ReplaceItemWithNewLambdaBase lambda)
  399. {
  400. player.ServerReplaceItemInHandsWithNew(lambda);
  401. }
  402. //!Spawns multiple piles of stackable ItemBase objects on ground (intended for generic use)
  403. static array<ItemBase> CreateItemBasePiles(string item_name, vector ground_position, float quantity, float health, bool floaty_spawn = false)
  404. {
  405. array<ItemBase> item_piles;
  406. float max_stack_size;
  407. ItemBase pile;
  408. item_piles = new array<ItemBase>;
  409. max_stack_size = g_Game.ConfigGetInt("cfgVehicles " + item_name + " varStackMax");
  410. if( max_stack_size < 1)
  411. max_stack_size = g_Game.ConfigGetInt("cfgVehicles " + item_name + " varQuantityMax");
  412. if( max_stack_size < 1)
  413. max_stack_size = 1;
  414. int full_piles_count = Math.Floor(quantity/max_stack_size);
  415. int rest = quantity - (full_piles_count*max_stack_size);
  416. for (int i = 0; i < full_piles_count; ++i)
  417. {
  418. if (floaty_spawn)
  419. pile = ItemBase.Cast(GetGame().CreateObjectEx(item_name, ground_position, ECE_CREATEPHYSICS|ECE_UPDATEPATHGRAPH));
  420. else
  421. pile = ItemBase.Cast(GetGame().CreateObjectEx(item_name, ground_position, ECE_PLACE_ON_SURFACE));
  422. pile.SetQuantity(max_stack_size);
  423. pile.SetHealth(health);
  424. item_piles.Insert(pile);
  425. }
  426. if (rest > 0)
  427. {
  428. if (floaty_spawn)
  429. pile = ItemBase.Cast(GetGame().CreateObjectEx(item_name, ground_position, ECE_CREATEPHYSICS|ECE_UPDATEPATHGRAPH));
  430. else
  431. pile = ItemBase.Cast(GetGame().CreateObjectEx(item_name, ground_position, ECE_PLACE_ON_SURFACE));
  432. pile.SetQuantity(rest);
  433. pile.SetHealth(health);
  434. item_piles.Insert(pile);
  435. }
  436. return item_piles;
  437. }
  438. //! creation method using raycast-dispersed positioning; ECE_TRACE not used as a result
  439. static array<ItemBase> CreateItemBasePilesDispersed(string item_name, vector starPos, vector targetPos, float radius, float quantity, float health, Object ignoreObjectCollison)
  440. {
  441. array<ItemBase> item_piles;
  442. float max_stack_size;
  443. ItemBase pile;
  444. item_piles = new array<ItemBase>;
  445. max_stack_size = g_Game.ConfigGetInt("cfgVehicles " + item_name + " varStackMax");
  446. if( max_stack_size < 1)
  447. max_stack_size = g_Game.ConfigGetInt("cfgVehicles " + item_name + " varQuantityMax");
  448. if( max_stack_size < 1)
  449. max_stack_size = 1;
  450. int full_piles_count = Math.Floor(quantity/max_stack_size);
  451. int rest = quantity - (full_piles_count*max_stack_size);
  452. vector randomizedPos;
  453. for (int i = 0; i < full_piles_count; ++i)
  454. {
  455. randomizedPos = MiscGameplayFunctions.GetRandomizedPositionVerified(starPos,targetPos,radius,ignoreObjectCollison);
  456. pile = ItemBase.Cast(GetGame().CreateObjectEx(item_name, randomizedPos, ECE_PLACE_ON_SURFACE));
  457. pile.SetQuantity(max_stack_size);
  458. pile.SetHealth(health);
  459. item_piles.Insert(pile);
  460. }
  461. if (rest > 0)
  462. {
  463. randomizedPos = MiscGameplayFunctions.GetRandomizedPositionVerified(starPos,targetPos,radius,ignoreObjectCollison);
  464. pile = ItemBase.Cast(GetGame().CreateObjectEx(item_name, randomizedPos, ECE_PLACE_ON_SURFACE));
  465. pile.SetQuantity(rest);
  466. pile.SetHealth(health);
  467. item_piles.Insert(pile);
  468. }
  469. return item_piles;
  470. }
  471. static array<Magazine> CreateMagazinePiles(string item_name, vector ground_position, float quantity, float health )
  472. {
  473. array<Magazine> items;
  474. float stack_size;
  475. Magazine pile;
  476. items = new array<Magazine>;
  477. stack_size = g_Game.ConfigGetInt("cfgMagazines " + item_name + " count");
  478. int piles_count = Math.Floor(quantity/stack_size);
  479. int rest = quantity - (piles_count*stack_size);
  480. for (int i = 0; i < piles_count; ++i)
  481. {
  482. pile = Magazine.Cast(GetGame().CreateObjectEx(item_name, ground_position, ECE_PLACE_ON_SURFACE));
  483. pile.ServerSetAmmoCount(stack_size);
  484. items.Insert(pile);
  485. }
  486. if (rest > 0)
  487. {
  488. pile = Magazine.Cast(GetGame().CreateObjectEx(item_name, ground_position, ECE_PLACE_ON_SURFACE));
  489. pile.ServerSetAmmoCount(rest);
  490. items.Insert(pile);
  491. }
  492. return items;
  493. }
  494. //! creation method using raycast-dispersed positioning; ECE_TRACE not used as a result
  495. static array<Magazine> CreateMagazinePilesDispersed(string item_name, vector starPos, vector targetPos, float radius, float quantity, float health, Object ignoreObjectCollison)
  496. {
  497. array<Magazine> items;
  498. float stack_size;
  499. Magazine pile;
  500. items = new array<Magazine>;
  501. stack_size = g_Game.ConfigGetInt("cfgMagazines " + item_name + " count");
  502. int piles_count = Math.Floor(quantity/stack_size);
  503. int rest = quantity - (piles_count*stack_size);
  504. vector randomizedPos;
  505. for (int i = 0; i < piles_count; ++i)
  506. {
  507. randomizedPos = MiscGameplayFunctions.GetRandomizedPositionVerified(starPos,targetPos,radius,ignoreObjectCollison);
  508. pile = Magazine.Cast(GetGame().CreateObjectEx(item_name, randomizedPos, ECE_CREATEPHYSICS|ECE_UPDATEPATHGRAPH));
  509. pile.ServerSetAmmoCount(stack_size);
  510. items.Insert(pile);
  511. }
  512. if (rest > 0)
  513. {
  514. randomizedPos = MiscGameplayFunctions.GetRandomizedPositionVerified(starPos,targetPos,radius,ignoreObjectCollison);
  515. pile = Magazine.Cast(GetGame().CreateObjectEx(item_name, randomizedPos, ECE_CREATEPHYSICS|ECE_UPDATEPATHGRAPH));
  516. pile.ServerSetAmmoCount(rest);
  517. items.Insert(pile);
  518. }
  519. return items;
  520. }
  521. static array<Magazine> CreateMagazinePilesFromBullet(string bullet_type, vector ground_position, float quantity, float health )
  522. {
  523. array<Magazine> items;
  524. items = new array<Magazine>;
  525. float stack_size;
  526. Magazine pile;
  527. string item_name;
  528. if (!g_Game.ConfigGetText("cfgAmmo " + bullet_type + " spawnPileType", item_name))
  529. return items;
  530. stack_size = g_Game.ConfigGetInt("cfgMagazines " + item_name + " count");
  531. if (stack_size > 0)
  532. {
  533. int piles_count = Math.Floor(quantity/stack_size);
  534. int rest = quantity - (piles_count*stack_size);
  535. for (int i = 0; i < piles_count; ++i)
  536. {
  537. pile = Magazine.Cast(GetGame().CreateObjectEx(item_name, ground_position, ECE_PLACE_ON_SURFACE));
  538. pile.ServerSetAmmoCount(stack_size);
  539. items.Insert(pile);
  540. }
  541. if (rest > 0)
  542. {
  543. pile = Magazine.Cast(GetGame().CreateObjectEx(item_name, ground_position, ECE_PLACE_ON_SURFACE));
  544. pile.ServerSetAmmoCount(rest);
  545. items.Insert(pile);
  546. }
  547. }
  548. return items;
  549. }
  550. //CreateMagazinePilesDispersed(string item_name, vector starPos, vector targetPos, float radius, float quantity, float health, Object ignoreObjectCollison)
  551. static array<Magazine> CreateMagazinePilesFromBulletDispersed(string bullet_type, vector starPos, vector targetPos, float radius, float quantity, float health, Object ignoreObjectCollison)
  552. {
  553. array<Magazine> items = new array<Magazine>;
  554. Magazine pile;
  555. string item_name;
  556. if (!g_Game.ConfigGetText("cfgAmmo " + bullet_type + " spawnPileType", item_name))
  557. return items;
  558. items = CreateMagazinePilesDispersed(item_name,starPos,targetPos,radius,quantity,health,ignoreObjectCollison);
  559. return items;
  560. }
  561. static int GetHealthLevelForAmmo(string class_name, float health)
  562. {
  563. float health_normalized = health / 100;
  564. string config_path = CFG_WEAPONSPATH + " " + class_name + " DamageSystem" + " GlobalHealth" + " healthLabels";
  565. CachedObjectsArrays.ARRAY_FLOAT.Clear();
  566. GetGame().ConfigGetFloatArray(config_path, CachedObjectsArrays.ARRAY_FLOAT);
  567. for(int i = 0; i < CachedObjectsArrays.ARRAY_FLOAT.Count(); ++i)
  568. {
  569. if( health_normalized >= CachedObjectsArrays.ARRAY_FLOAT.Get(i) )
  570. {
  571. return i;
  572. }
  573. }
  574. return -1;
  575. }
  576. static float GetTypeMaxGlobalHealth(string class_name, string health_type = "Health")
  577. {
  578. float max_health;
  579. string cfg_path;
  580. if ( GetGame().ConfigIsExisting(CFG_VEHICLESPATH+" "+class_name) )
  581. {
  582. cfg_path = CFG_VEHICLESPATH;
  583. }
  584. else if ( GetGame().ConfigIsExisting(CFG_WEAPONSPATH+" "+class_name) )
  585. {
  586. cfg_path = CFG_WEAPONSPATH;
  587. }
  588. else if ( GetGame().ConfigIsExisting(CFG_MAGAZINESPATH+" "+class_name) )
  589. {
  590. cfg_path = CFG_MAGAZINESPATH;
  591. }
  592. cfg_path = cfg_path + " "+class_name+" DamageSystem GlobalHealth " + health_type + " hitpoints";
  593. max_health = GetGame().ConfigGetFloat(cfg_path);
  594. return max_health;
  595. }
  596. static bool GetProjectedCursorPos3d (out vector position, Weapon_Base weapon)
  597. {
  598. vector usti_hlavne_position = weapon.GetSelectionPositionMS( "usti hlavne" );
  599. vector konec_hlavne_position = weapon.GetSelectionPositionMS( "konec hlavne" );
  600. vector end_point = weapon.ModelToWorld(usti_hlavne_position);
  601. vector begin_point = weapon.ModelToWorld(konec_hlavne_position);
  602. vector contact_dir;
  603. int contact_component;
  604. vector aim_point = end_point - begin_point;
  605. aim_point = aim_point.Normalized() * PROJECTED_CURSOR_DISTANCE;
  606. aim_point = aim_point + end_point;
  607. if (DayZPhysics.RaycastRV(begin_point, aim_point, position, contact_dir, contact_component, null, null, null, false, false, ObjIntersectFire))
  608. return true;
  609. return false;
  610. }
  611. static void GetHeadBonePos(notnull PlayerBase player, out vector pos)
  612. {
  613. // Get position of head for starting trace pos, otherwise use sane default
  614. int headBoneIdx = player.GetBoneIndexByName("Head");
  615. if ( headBoneIdx == -1 )
  616. { pos = player.GetPosition()[1] + 1.6; }
  617. else
  618. { pos = player.GetBonePositionWS(headBoneIdx); }
  619. }
  620. static vector GetHeadingVector(notnull PlayerBase player)
  621. {
  622. vector dir = vector.Zero;
  623. float headingAngle = GetHeadingAngle(player);
  624. dir[0] = Math.Cos(headingAngle + Math.PI_HALF);
  625. dir[2] = Math.Sin(headingAngle + Math.PI_HALF);
  626. return dir.Normalized();
  627. }
  628. static float GetHeadingAngle(notnull DayZPlayerImplement player)
  629. {
  630. HumanInputController hic = player.GetInputController();
  631. float headingAngle = hic.GetHeadingAngle();
  632. return headingAngle;
  633. }
  634. static float GetEnergyMetabolicSpeed(int movement_speed)
  635. {
  636. float speed;
  637. switch (movement_speed)
  638. {
  639. case DayZPlayerConstants.MOVEMENTIDX_WALK:
  640. speed = PlayerConstants.METABOLIC_SPEED_ENERGY_WALK;
  641. break;
  642. case DayZPlayerConstants.MOVEMENTIDX_RUN:
  643. speed = PlayerConstants.METABOLIC_SPEED_ENERGY_JOG;
  644. break;
  645. case DayZPlayerConstants.MOVEMENTIDX_SPRINT:
  646. speed = PlayerConstants.METABOLIC_SPEED_ENERGY_SPRINT;
  647. break;
  648. default:
  649. speed = 0;
  650. break;
  651. }
  652. speed += PlayerConstants.METABOLIC_SPEED_ENERGY_BASAL;
  653. return speed;
  654. }
  655. static float GetWaterMetabolicSpeed(int movement_speed)
  656. {
  657. float speed;
  658. switch (movement_speed)
  659. {
  660. case DayZPlayerConstants.MOVEMENTIDX_WALK:
  661. speed = PlayerConstants.METABOLIC_SPEED_WATER_WALK;
  662. break;
  663. case DayZPlayerConstants.MOVEMENTIDX_RUN:
  664. speed = PlayerConstants.METABOLIC_SPEED_WATER_JOG;
  665. break;
  666. case DayZPlayerConstants.MOVEMENTIDX_SPRINT:
  667. speed = PlayerConstants.METABOLIC_SPEED_WATER_SPRINT;
  668. break;
  669. default:
  670. speed = 0;
  671. break;
  672. }
  673. speed += PlayerConstants.METABOLIC_SPEED_WATER_BASAL;
  674. return speed;
  675. }
  676. static string ObtainRestrainItemTargetClassname(notnull EntityAI entity)
  677. {
  678. return entity.ConfigGetString( "OnRestrainChange");
  679. }
  680. static void TransformRestrainItem(EntityAI current_item, EntityAI tool, PlayerBase player_source, PlayerBase player_target, bool destroy = false)
  681. {
  682. bool type;
  683. if ( tool )
  684. {
  685. //is unrestrain and not struggle
  686. type = tool.ConfigGetBool("RestrainUnlockType");
  687. }
  688. string new_item_name = current_item.ConfigGetString( "OnRestrainChange");
  689. if ( new_item_name != "" )
  690. {
  691. if ( player_target )
  692. {
  693. if (player_target.IsAlive())
  694. MiscGameplayFunctions.TurnItemIntoItemEx(player_target, new ReplaceAndDestroyLambdaEx(current_item, new_item_name, player_target, type));
  695. else
  696. MiscGameplayFunctions.TurnItemIntoItemEx(player_source, new DestroyItemInCorpsesHandsAndCreateNewOnGndLambda(current_item, new_item_name, player_target, type));
  697. }
  698. else
  699. {
  700. MiscGameplayFunctions.TurnItemIntoItemEx(player_target, new ReplaceAndDestroyLambdaEx(current_item, new_item_name, player_target, type));
  701. }
  702. }
  703. else
  704. {
  705. Error("current_item:" +current_item+ ", tool:" +tool +". No value for 'OnRestrainChange' config parameter");
  706. }
  707. }
  708. static bool IsValueInRange(float value, float from, float to)
  709. {
  710. return (value >= from) && (value <= to);
  711. }
  712. //! Check if player direction(based on cone of defined angle) is oriented to target position
  713. static bool IsPlayerOrientedTowardPos(notnull DayZPlayerImplement player, vector target_pos, float cone_angle)
  714. {
  715. if (player)
  716. {
  717. vector player_dir = player.GetDirection();
  718. vector to_target_dir = target_pos - player.GetPosition();
  719. player_dir[1] = 0;
  720. to_target_dir[1] = 0;
  721. player_dir.Normalize();
  722. to_target_dir.Normalize();
  723. float cos_fi = vector.Dot(player_dir, to_target_dir);
  724. vector cross = player_dir * to_target_dir;
  725. int dir = Math.Acos(cos_fi) * Math.RAD2DEG;
  726. if( cross[1] < 0 )
  727. dir = -dir;
  728. //! dir in cone or in a tip of cone
  729. if( (dir <= cone_angle && dir >= -cone_angle) || Math.AbsFloat(dir) == 90 )
  730. {
  731. return true;
  732. }
  733. }
  734. return false;
  735. }
  736. static string SanitizeString(string input)
  737. {
  738. int max_length = 512;
  739. string output = input;
  740. output = output.Substring(0,Math.Clamp(max_length,0,output.Length()));
  741. return output;
  742. }
  743. // deprecated - dont use
  744. static bool ComplexBuildCollideCheckClient( PlayerBase player, ActionTarget target, ItemBase item, string partName = "" )
  745. {
  746. return true;
  747. }
  748. static bool ComplexBuildCollideCheckClient( PlayerBase player, ActionTarget target, ItemBase item, int constraction_index )
  749. {
  750. BaseBuildingBase base_building = BaseBuildingBase.Cast( target.GetObject() );
  751. if (base_building)
  752. {
  753. Construction construction = base_building.GetConstruction();
  754. if (construction && BuildCondition( player, target, item, false, constraction_index ))
  755. {
  756. ConstructionActionData construction_action_data = player.GetConstructionActionData();
  757. string partName;
  758. if ( item )
  759. {
  760. partName = construction_action_data.GetBuildPartAtIndex(constraction_index).GetPartName();
  761. }
  762. else
  763. {
  764. partName = construction_action_data.GetBuildPartNoToolAtIndex(constraction_index).GetPartName();
  765. }
  766. bool boo;
  767. if (base_building.PerformRoofCheckForBase(partName,player,boo) && boo)
  768. return false;
  769. if ( player.IsPlacingLocal() || player.IsPlacingServer() )
  770. return false;
  771. /*float distance_root = vector.DistanceSq(target.GetCursorHitPos(), player.GetPosition());
  772. if (!CfgGameplayHandler.GetDisableDistanceCheck() && distance_root < UAMaxDistances.BASEBUILDING_SHORT)
  773. {
  774. return false;
  775. } */
  776. return !construction.IsColliding( partName );
  777. }
  778. }
  779. return false;
  780. }
  781. // deprecated - dont use
  782. static bool BuildCondition( PlayerBase player, ActionTarget target, ItemBase item, bool camera_check )
  783. {
  784. return true;
  785. }
  786. static bool BuildCondition( PlayerBase player, ActionTarget target, ItemBase item, bool camera_check, int constraction_index )
  787. {
  788. Object targetObject = target.GetObject();
  789. if ( targetObject && targetObject.CanUseConstruction() )
  790. {
  791. BaseBuildingBase base_building = BaseBuildingBase.Cast( targetObject );
  792. ConstructionActionData construction_action_data = player.GetConstructionActionData();
  793. construction_action_data.SetTarget( targetObject );
  794. ConstructionPart constrution_part;
  795. if ( item )
  796. {
  797. constrution_part = construction_action_data.GetBuildPartAtIndex(constraction_index);
  798. }
  799. else
  800. {
  801. constrution_part = construction_action_data.GetBuildPartNoToolAtIndex(constraction_index);
  802. }
  803. //Debug
  804. /*
  805. if ( constrution_part )
  806. {
  807. Construction construction = base_building.GetConstruction();
  808. construction.IsColliding( constrution_part.GetPartName() );
  809. }
  810. */
  811. if ( constrution_part )
  812. {
  813. //camera and position checks
  814. bool position_check = ( base_building.MustBeBuiltFromOutside() && !base_building.IsPlayerInside(player, constrution_part.GetMainPartName()) ) || ( !base_building.MustBeBuiltFromOutside() && base_building.IsPlayerInside(player, constrution_part.GetMainPartName()) );
  815. if ( position_check && !player.GetInputController().CameraIsFreeLook() )
  816. {
  817. //Camera check (client-only)
  818. if ( camera_check )
  819. {
  820. if ( GetGame() && ( !GetGame().IsDedicatedServer() ) )
  821. {
  822. return !base_building.IsFacingCamera( constrution_part.GetMainPartName() );
  823. }
  824. }
  825. return true;
  826. }
  827. }
  828. }
  829. return false;
  830. }
  831. static void IsUnderRoofFromToCalculation(EntityAI entity, out vector from, out vector to, float height = GameConstants.ROOF_CHECK_RAYCAST_DIST)
  832. {
  833. vector minMax[2];
  834. entity.GetCollisionBox(minMax);
  835. vector size = Vector(0,0,0);
  836. //size[1] = minMax[1][1] - minMax[0][1];
  837. float from_override = entity.HeightStartCheckOverride();
  838. if (from_override > 0.0)
  839. {
  840. size[1] = from_override;
  841. }
  842. else
  843. {
  844. size[1] = minMax[1][1] - minMax[0][1];
  845. }
  846. from = entity.GetPosition() + size;
  847. if ( entity.HeightCheckOverride() > 0 )
  848. {
  849. to = entity.GetPosition() + Vector(0, entity.HeightCheckOverride(), 0);
  850. }
  851. else
  852. {
  853. vector ceiling = "0 0 0";
  854. ceiling[1] = height;
  855. to = from + ceiling; //+size ??? offset to cast same distance
  856. }
  857. }
  858. static bool IsUnderRoof(EntityAI entity, float height = GameConstants.ROOF_CHECK_RAYCAST_DIST)
  859. {
  860. return IsUnderRoofEx(entity, height, ObjIntersectIFire);
  861. }
  862. static bool IsUnderRoofEx(EntityAI entity, float height = GameConstants.ROOF_CHECK_RAYCAST_DIST, int geometry = ObjIntersectView)
  863. {
  864. vector from;
  865. vector to;
  866. IsUnderRoofFromToCalculation(entity, from, to, height);
  867. vector contact_pos;
  868. vector contact_dir;
  869. int contact_component;
  870. return DayZPhysics.RaycastRV(from, to, contact_pos, contact_dir, contact_component, NULL, NULL, entity, false, false, geometry,0.25);
  871. }
  872. // cooking equipment effects (get position for steam particle)
  873. static vector GetSteamPosition( EntityAI parent )
  874. {
  875. vector particle_pos;
  876. float steam_offset = 0;
  877. if ( parent )
  878. {
  879. particle_pos = parent.GetPosition();
  880. if ( parent.IsInherited( PortableGasStove ) )
  881. {
  882. steam_offset = 0.2;
  883. }
  884. else if ( parent.IsInherited( FireplaceBase ) )
  885. {
  886. FireplaceBase fireplace = FireplaceBase.Cast( parent );
  887. if ( fireplace.IsBaseFireplace() )
  888. {
  889. steam_offset = 0.8;
  890. }
  891. else if ( fireplace.IsBarrelWithHoles() )
  892. {
  893. steam_offset = 1.1;
  894. }
  895. else if ( fireplace.IsFireplaceIndoor() )
  896. {
  897. steam_offset = 0.45;
  898. }
  899. else if ( fireplace.IsIndoorOven() )
  900. {
  901. steam_offset = 0.9;
  902. }
  903. }
  904. }
  905. particle_pos[1] = particle_pos[1] + steam_offset;
  906. return particle_pos;
  907. }
  908. static vector GetRandomizedPosition(vector targetPos, float radius)
  909. {
  910. int angle = Math.RandomIntInclusive(1,360);
  911. float usedRadius = Math.RandomFloat01() * radius;
  912. vector randomPos = Vector(targetPos[0] + (Math.Cos(angle) * usedRadius), targetPos[1], targetPos[2] + (Math.Sin(angle) * usedRadius));
  913. return randomPos;
  914. }
  915. static vector GetRandomizedPositionVerified(vector startPos, vector targetPos, float radius, Object ignore = null)
  916. {
  917. vector ret = GetRandomizedPosition(targetPos,radius);
  918. RaycastRVParams params = new RaycastRVParams(startPos,ret,ignore);
  919. params.type = ObjIntersectIFire;
  920. array<ref RaycastRVResult> results = new array<ref RaycastRVResult>;
  921. array<Object> excluded = new array<Object>;
  922. if (DayZPhysics.RaycastRVProxy(params,results,excluded))
  923. {
  924. ret = results[0].pos;
  925. ret[1] = targetPos[1];
  926. }
  927. return ret;
  928. }
  929. static vector GetRandomizedPositionVerifiedPlayer(Man player, float distance, float radius, Object ignore)
  930. {
  931. vector startPos;
  932. MiscGameplayFunctions.GetHeadBonePos(PlayerBase.Cast(player),startPos);
  933. vector targetPos = player.GetPosition() + (player.GetDirection() * distance);
  934. return GetRandomizedPositionVerified(startPos,targetPos,radius,ignore);
  935. }
  936. static void DropAllItemsInInventoryInBounds(ItemBase ib, vector halfExtents)
  937. {
  938. if (!GetGame().IsServer())
  939. return;
  940. array<EntityAI> items = new array<EntityAI>;
  941. ib.GetInventory().EnumerateInventory(InventoryTraversalType.LEVELORDER, items);
  942. vector direction = ib.GetDirection();
  943. float dot = vector.Dot(direction, vector.Forward);
  944. float angle = Math.Acos(dot);
  945. if (direction[0] < 0)
  946. angle = -angle;
  947. float cos = Math.Cos(angle);
  948. float sin = Math.Sin(angle);
  949. EntityAI item;
  950. int count = items.Count();
  951. for ( int i = 0; i < count; ++i )
  952. {
  953. item = items.Get(i);
  954. if ( item )
  955. ib.GetInventory().DropEntityInBounds(InventoryMode.SERVER, ib, item, halfExtents, angle, cos, sin);
  956. }
  957. }
  958. static void ThrowAllItemsInInventory(notnull EntityAI parent, int flags)
  959. {
  960. vector position = parent.GetPosition();
  961. vector orientation = parent.GetOrientation();
  962. vector rotation_matrix[3];
  963. float direction[4];
  964. vector minmax[2];
  965. parent.GetCollisionBox(minmax);
  966. Math3D.YawPitchRollMatrix( orientation, rotation_matrix );
  967. Math3D.MatrixToQuat( rotation_matrix, direction );
  968. vector randomPos;
  969. for ( int i = 0; i < parent.GetInventory().AttachmentCount(); ++i )
  970. {
  971. randomPos = Vector(position[0] + Math.RandomFloat(minmax[0][0], minmax[1][0]),
  972. position[1] + Math.RandomFloat(minmax[0][1], minmax[1][1]),
  973. position[2] + Math.RandomFloat(minmax[0][2], minmax[1][2]));
  974. ThrowEntityFromInventory(parent.GetInventory().GetAttachmentFromIndex( i ), randomPos, direction, -GetVelocity(parent), ThrowEntityFlags.NONE);
  975. }
  976. for ( int j = 0; j < parent.GetInventory().GetCargo().GetItemCount(); ++j )
  977. {
  978. randomPos = Vector(position[0] + Math.RandomFloat(minmax[0][0], minmax[1][0]),
  979. position[1] + Math.RandomFloat(minmax[0][1], minmax[1][1]),
  980. position[2] + Math.RandomFloat(minmax[0][2], minmax[1][2]));
  981. ThrowEntityFromInventory(parent.GetInventory().GetCargo().GetItem( j ), randomPos, direction, -GetVelocity(parent), ThrowEntityFlags.NONE);
  982. }
  983. }
  984. static void ThrowEntityFromInventory(notnull EntityAI entity, vector position, float direction[4], vector force, int flags)
  985. {
  986. InventoryMode invMode = InventoryMode.SERVER;
  987. if ( !GetGame().IsMultiplayer() )
  988. invMode = InventoryMode.LOCAL;
  989. ItemBase entityIB;
  990. if (CastTo(entityIB, entity))
  991. {
  992. InventoryLocation dst = new InventoryLocation;
  993. dst.SetGroundEx(entity, position, direction);
  994. if ( (flags & ThrowEntityFlags.SPLIT) && entityIB.CanBeSplit() )
  995. {
  996. for (int l = 0; l < entityIB.GetQuantity(); ++l)
  997. {
  998. ItemBase new_item = ItemBase.Cast( GameInventory.LocationCreateEntity( dst, entityIB.GetType(), ECE_NONE, RF_DEFAULT ) );
  999. if ( new_item )
  1000. {
  1001. MiscGameplayFunctions.TransferItemProperties(entityIB, new_item);
  1002. entityIB.AddQuantity( -1 );
  1003. new_item.SetQuantity( 1 );
  1004. new_item.ThrowPhysically(null, force, false);
  1005. }
  1006. }
  1007. }
  1008. else
  1009. {
  1010. float stackable = entityIB.GetTargetQuantityMax();
  1011. if ( !(stackable == 0 || stackable >= entityIB.GetQuantity()) )
  1012. {
  1013. while (entityIB.GetQuantity() > stackable)
  1014. {
  1015. InventoryLocation spltDst = new InventoryLocation;
  1016. position[1] = position[1] + 0.1;
  1017. spltDst.SetGroundEx(entity, position, direction);
  1018. ItemBase splitItem = entityIB.SplitIntoStackMaxToInventoryLocationEx( spltDst );
  1019. splitItem.ThrowPhysically(null, force, false);
  1020. }
  1021. }
  1022. InventoryLocation src = new InventoryLocation;
  1023. entity.GetInventory().GetCurrentInventoryLocation(src);
  1024. entity.GetInventory().TakeToDst(invMode, src, dst);
  1025. entityIB.ThrowPhysically(null, force, false);
  1026. }
  1027. }
  1028. else
  1029. {
  1030. entity.GetInventory().DropEntity(invMode, entity.GetHierarchyRoot(), entity);
  1031. dBodyApplyImpulse(entity, force);
  1032. }
  1033. }
  1034. static float GetCurrentItemHeatIsolation( ItemBase pItem )
  1035. {
  1036. float wetFactor;
  1037. float healthFactor;
  1038. float heatIsolation = pItem.GetHeatIsolation(); //! item heat isolation (from cfg)
  1039. float itemHealthLabel = pItem.GetHealthLevel(); //! item health (state)
  1040. float itemWetness = pItem.GetWet(); //! item wetness
  1041. //! wet factor selection
  1042. if ( itemWetness >= GameConstants.STATE_DRY && itemWetness < GameConstants.STATE_DAMP )
  1043. {
  1044. wetFactor = GameConstants.ENVIRO_ISOLATION_WETFACTOR_DRY;
  1045. }
  1046. else if ( itemWetness >= GameConstants.STATE_DAMP && itemWetness < GameConstants.STATE_WET )
  1047. {
  1048. wetFactor = GameConstants.ENVIRO_ISOLATION_WETFACTOR_DAMP;
  1049. }
  1050. else if ( itemWetness >= GameConstants.STATE_WET && itemWetness < GameConstants.STATE_SOAKING_WET )
  1051. {
  1052. wetFactor = GameConstants.ENVIRO_ISOLATION_WETFACTOR_WET;
  1053. }
  1054. else if ( itemWetness >= GameConstants.STATE_SOAKING_WET && itemWetness < GameConstants.STATE_DRENCHED )
  1055. {
  1056. wetFactor = GameConstants.ENVIRO_ISOLATION_WETFACTOR_SOAKED;
  1057. }
  1058. else if ( itemWetness >= GameConstants.STATE_DRENCHED )
  1059. {
  1060. return GameConstants.ENVIRO_ISOLATION_WETFACTOR_DRENCHED;
  1061. }
  1062. //! health factor selection
  1063. switch (itemHealthLabel)
  1064. {
  1065. case GameConstants.STATE_PRISTINE:
  1066. healthFactor = GameConstants.ENVIRO_ISOLATION_HEALTHFACTOR_PRISTINE;
  1067. break;
  1068. case GameConstants.STATE_WORN:
  1069. healthFactor = GameConstants.ENVIRO_ISOLATION_HEALTHFACTOR_WORN;
  1070. break;
  1071. case GameConstants.STATE_DAMAGED:
  1072. healthFactor = GameConstants.ENVIRO_ISOLATION_HEALTHFACTOR_DAMAGED;
  1073. break;
  1074. case GameConstants.STATE_BADLY_DAMAGED:
  1075. healthFactor = GameConstants.ENVIRO_ISOLATION_HEALTHFACTOR_B_DAMAGED;
  1076. break;
  1077. case GameConstants.STATE_RUINED:
  1078. healthFactor = GameConstants.ENVIRO_ISOLATION_HEALTHFACTOR_RUINED;
  1079. break;
  1080. }
  1081. //! apply factors
  1082. heatIsolation *= healthFactor;
  1083. heatIsolation *= wetFactor;
  1084. return heatIsolation;
  1085. }
  1086. static void FilterObstructingObjects(array<Object> potentiallyObstructingObjects, out array<Object> obstructingObjects)
  1087. {
  1088. if (!obstructingObjects)
  1089. obstructingObjects = new array<Object>;
  1090. for ( int i = 0; i < potentiallyObstructingObjects.Count(); ++i )
  1091. {
  1092. Object obj = potentiallyObstructingObjects[i];
  1093. if ( obj && ( obj.CanObstruct() || obj.CanProxyObstruct() ) )
  1094. obstructingObjects.Insert(obj);
  1095. }
  1096. }
  1097. static bool CanIgnoreDistanceCheck(Object obj)
  1098. {
  1099. return obj.IsTransport() || obj.CanUseConstruction();
  1100. }
  1101. //! group objects that are close to each other together
  1102. static void FilterObstructedObjectsByGrouping(vector origin, float range, float distanceDelta, array<Object> objects, array<Object> obstructingObjects, out array<Object> filteredObjects, bool doDistanceCheck = false, bool checkIfDistanceCanBeIgnored = false, float maxDist = 0)
  1103. {
  1104. array<Object> vicinityObjects= new array<Object>;
  1105. vicinityObjects.Copy(objects);
  1106. int i = 0;
  1107. int j = 0;
  1108. int k = 0;
  1109. int mCount = vicinityObjects.Count();
  1110. if (!filteredObjects)
  1111. filteredObjects = new array<Object>;
  1112. // Remove objects that are too far from the player anyways
  1113. if ( doDistanceCheck )
  1114. {
  1115. for ( i = vicinityObjects.Count() - 1; i >= 0; --i )
  1116. {
  1117. Object obj = vicinityObjects[i];
  1118. if ( obj && !CanIgnoreDistanceCheck( obj ) && vector.DistanceSq(origin, obj.GetPosition()) > maxDist * maxDist )
  1119. vicinityObjects.Remove(i);
  1120. }
  1121. }
  1122. // Sort obstructingObjects to have the furthest one first
  1123. array<Object> sortedObstructingObjects = new array<Object>;
  1124. array<float> distanceHelper = new array<float>;
  1125. array<float> distanceHelperUnsorted = new array<float>;
  1126. float distance, dist1, dist2;
  1127. for ( i = 0; i < obstructingObjects.Count(); ++i )
  1128. {
  1129. distance = vector.DistanceSq(obstructingObjects[i].GetWorldPosition(), origin);
  1130. distanceHelper.Insert(distance);
  1131. }
  1132. distanceHelperUnsorted.Copy(distanceHelper);
  1133. distanceHelper.Sort();
  1134. for ( i = distanceHelper.Count() - 1; i >= 0; --i )
  1135. sortedObstructingObjects.Insert(obstructingObjects[distanceHelperUnsorted.Find(distanceHelper[i])]);
  1136. array<ref array<Object>> tempGroups = new array<ref array<Object>>;
  1137. array<ref array<Object>> objectGroups = new array<ref array<Object>>;
  1138. array<Object> group;
  1139. float cos = Math.Cos(90);
  1140. float sin = Math.Sin(90);
  1141. // Iterate through sorted obstructingObjects
  1142. for ( i = 0; i < sortedObstructingObjects.Count(); ++i )
  1143. {
  1144. Object obstrObj = sortedObstructingObjects[i];
  1145. vector worldPos = obstrObj.GetWorldPosition();
  1146. vector min, max;
  1147. vector minMax[2];
  1148. if ( obstrObj.GetCollisionBox(minMax) )
  1149. {
  1150. min = minMax[0];
  1151. max = minMax[1];
  1152. max = max * (obstrObj.GetOrientation() * range);
  1153. vector center, dx, dy, dz, half;
  1154. center = (min + max) * 0.5;
  1155. dz = obstrObj.GetOrientation();
  1156. dx = vector.RotateAroundZero(dz, vector.Up, cos, sin);
  1157. dy = vector.RotateAroundZero(dz, vector.Aside, cos, sin);
  1158. half = (max - min) * 0.5;
  1159. half = Vector(Math.AbsFloat(half[0]), Math.AbsFloat(half[1]), Math.AbsFloat(half[2]));
  1160. group = new array<Object>;
  1161. // Group objects within the above box
  1162. for ( j = vicinityObjects.Count() - 1; j >= 0; --j )
  1163. {
  1164. Object vicObj = vicinityObjects[j];
  1165. if ( vicObj )
  1166. {
  1167. vector d = vicObj.GetWorldPosition() - worldPos + center;
  1168. if ( Math.AbsFloat(vector.Dot(d, dx)) <= half[0] && Math.AbsFloat(vector.Dot(d, dy)) <= half[1] && Math.AbsFloat(vector.Dot(d, dz)) <= half[2] )
  1169. {
  1170. group.Insert(vicObj);
  1171. vicinityObjects.Remove(j);
  1172. }
  1173. }
  1174. }
  1175. if ( group.Count() > 0 )
  1176. tempGroups.Insert(group);
  1177. }
  1178. }
  1179. // Go through the objects grouped by obstruction to split them by distance too
  1180. for ( i = 0; i < tempGroups.Count(); ++i )
  1181. SplitArrayIntoGroupsByDistance(tempGroups[i], objectGroups, distanceDelta);
  1182. // Split initial groups by distance
  1183. SplitArrayIntoGroupsByDistance(vicinityObjects, objectGroups, distanceDelta);
  1184. // Raycast accordingly to groups
  1185. IsObjectObstructedCache cache = new IsObjectObstructedCache(origin, mCount);
  1186. for ( i = 0; i < objectGroups.Count(); ++i )
  1187. {
  1188. array<Object> objectGroup = objectGroups[i];
  1189. Object sampleObject = objectGroup[0];
  1190. if ( !IsObjectObstructedEx(sampleObject, cache) )
  1191. filteredObjects.InsertAll(objectGroup);
  1192. cache.ClearCache();
  1193. }
  1194. }
  1195. static void SplitArrayIntoGroupsByDistance(array<Object> objects, array<ref array<Object>> objectGroups, float squaredDistanceDelta)
  1196. {
  1197. array<Object> group;
  1198. for ( int i = 0; i < objects.Count(); )
  1199. {
  1200. Object obj1 = objects[i];
  1201. if ( obj1 )
  1202. {
  1203. group = new array<Object>;
  1204. group.Insert(obj1);
  1205. for ( int j = objects.Count() - 1; j > i; --j )
  1206. {
  1207. Object obj2 = objects[j];
  1208. if ( obj1 && obj2 )
  1209. {
  1210. vector start = obj1.GetWorldPosition();
  1211. vector end = obj2.GetWorldPosition();
  1212. float distance = vector.DistanceSq(start, end);
  1213. if ( distance < squaredDistanceDelta )
  1214. {
  1215. group.Insert(obj2);
  1216. objects.Remove(j);
  1217. }
  1218. }
  1219. }
  1220. objectGroups.Insert(group);
  1221. objects.Remove(i);
  1222. continue;
  1223. }
  1224. ++i;
  1225. }
  1226. }
  1227. static bool IsObjectObstructed(Object object, bool doDistanceCheck = false, vector distanceCheckPos = "0 0 0", float maxDist = 0)
  1228. {
  1229. vector rayStart;
  1230. MiscGameplayFunctions.GetHeadBonePos(PlayerBase.Cast(GetGame().GetPlayer()), rayStart);
  1231. IsObjectObstructedCache cache = new IsObjectObstructedCache(rayStart, 1);
  1232. return IsObjectObstructedEx(object, cache, doDistanceCheck, distanceCheckPos, maxDist);
  1233. }
  1234. static bool IsObjectObstructedEx(Object object, IsObjectObstructedCache cache, bool doDistanceCheck = false, vector distanceCheckPos = "0 0 0", float maxDist = 0)
  1235. {
  1236. if (!object)
  1237. return true;
  1238. PlayerBase player = PlayerBase.Cast(g_Game.GetPlayer());
  1239. if (doDistanceCheck && vector.DistanceSq(player.GetPosition(), distanceCheckPos) > maxDist * maxDist)
  1240. return true;
  1241. cache.ObjectCenterPos = object.GetCenter();
  1242. return IsObjectObstructedFilterEx(object, cache, player);
  1243. }
  1244. static bool IsObjectObstructedProxy(Object object, IsObjectObstructedCache cache, PlayerBase player)
  1245. {
  1246. if (object.CanProxyObstruct())
  1247. {
  1248. RaycastRVParams rayInput = new RaycastRVParams(cache.RaycastStart, cache.ObjectCenterPos, player);
  1249. DayZPhysics.RaycastRVProxy(rayInput, cache.HitProxyObjects);
  1250. if (cache.HitProxyObjects)
  1251. {
  1252. if (cache.HitProxyObjects.Count() > 0)
  1253. {
  1254. if (cache.HitProxyObjects[0].hierLevel > 0)
  1255. {
  1256. // ignores attachments on player
  1257. if (!cache.HitProxyObjects[0].parent.IsMan())
  1258. {
  1259. if (cache.HitProxyObjects[0].parent)
  1260. {
  1261. EntityAI proxyParent = EntityAI.Cast(cache.HitProxyObjects[0].parent);
  1262. if (proxyParent.GetInventory() && proxyParent.GetInventory().GetCargo())
  1263. return true;
  1264. }
  1265. }
  1266. }
  1267. }
  1268. }
  1269. }
  1270. return false;
  1271. }
  1272. static bool IsObjectObstructedFilter(Object object, IsObjectObstructedCache cache, PlayerBase player)
  1273. {
  1274. for (int m = 0; m < cache.HitObjects.Count(); ++m)
  1275. {
  1276. Object hit_object = cache.HitObjects.Get(m);
  1277. if ( hit_object.CanObstruct() )
  1278. return true;
  1279. //4.3. ignore item if items are big and heavy >= OBJECT_OBSTRUCTION_WEIGHT
  1280. //EntityAI eai;
  1281. //if ( Class.CastTo( eai, hit_object ) )
  1282. //{
  1283. // if ( eai.GetWeight() >= OBJECT_OBSTRUCTION_WEIGHT )
  1284. // {
  1285. // if ( eai != filtered_object && eai.GetHierarchyRoot() != filtered_object )
  1286. // {
  1287. // //Print("!!!!!obstacle vaha: " + hit_object);
  1288. // is_obstructed = true;
  1289. // }
  1290. // }
  1291. //}
  1292. }
  1293. return false;
  1294. }
  1295. //! groups 'RaycastRVProxy' and 'RaycastRV' approaches into one method, allowes for comprehensive geometry override, if desired
  1296. static bool IsObjectObstructedFilterEx(Object object, IsObjectObstructedCache cache, PlayerBase player, int geometryTypeOverride = -1)
  1297. {
  1298. //first proxy geometries
  1299. RaycastRVParams rayInput = new RaycastRVParams(cache.RaycastStart, cache.ObjectCenterPos, player);
  1300. rayInput.flags = CollisionFlags.ALLOBJECTS;
  1301. if (geometryTypeOverride != -1)
  1302. rayInput.type = geometryTypeOverride; //default 'ObjIntersectView'
  1303. DayZPhysics.RaycastRVProxy(rayInput, cache.HitProxyObjects);
  1304. int count;
  1305. int i;
  1306. if (cache.HitProxyObjects)
  1307. {
  1308. count = cache.HitProxyObjects.Count();
  1309. Object parent;
  1310. for (i = 0; i < count; ++i)
  1311. {
  1312. if (cache.HitProxyObjects[i].hierLevel > 0) //parent has to exist, skipping nullcheck
  1313. {
  1314. parent = cache.HitProxyObjects[i].parent;
  1315. if (parent && !parent.IsMan() && parent.CanProxyObstruct())
  1316. {
  1317. if (parent != object || (parent == object && object.CanProxyObstructSelf()))
  1318. return true;
  1319. }
  1320. }
  1321. }
  1322. }
  1323. //second, regular raycast
  1324. int geometry = ObjIntersectFire; //default for the RV raycast
  1325. if (geometryTypeOverride != -1)
  1326. geometry = geometryTypeOverride;
  1327. DayZPhysics.RaycastRV(cache.RaycastStart, cache.ObjectCenterPos, cache.ObjectContactPos, cache.ObjectContactDir, cache.ContactComponent, cache.HitObjects, object, GetGame().GetPlayer(), false, false, geometry, 0.0, CollisionFlags.ALLOBJECTS);
  1328. count = cache.HitObjects.Count();
  1329. for (i = 0; i < count; ++i)
  1330. {
  1331. if (cache.HitObjects[i].CanObstruct())
  1332. return true;
  1333. }
  1334. return false;
  1335. }
  1336. //Inflict damage to item based on environmental temperature and surface type
  1337. static void DealEvinronmentAdjustedDmg(ItemBase item, PlayerBase player, float baseDamage)
  1338. {
  1339. string surfaceType;
  1340. int liquidType;
  1341. float adjustedDamage;
  1342. GetGame().SurfaceUnderObject(player, surfaceType, liquidType);
  1343. float modifierSurface = Surface.GetParamFloat(surfaceType, "toolDamage"); // toolDamage
  1344. if (modifierSurface == 0)
  1345. modifierSurface = 1;
  1346. if (player.GetInColdArea())
  1347. adjustedDamage = baseDamage * (modifierSurface + GetGame().GetMission().GetWorldData().GetColdAreaToolDamageModifier();
  1348. else
  1349. adjustedDamage = baseDamage * modifierSurface;
  1350. DealAbsoluteDmg(item, adjustedDamage);
  1351. }
  1352. //Inflict absolute damage to item (used on tools when completing actions)
  1353. static void DealAbsoluteDmg(ItemBase item, float dmg)
  1354. {
  1355. item.DecreaseHealth(dmg, false);
  1356. }
  1357. //Function used to normailze values, enter the used value and the max value (max will become 1)
  1358. static float Normalize(int val, int maxVal)
  1359. {
  1360. if (maxVal == 0)
  1361. {
  1362. Debug.LogError("Division by 0 is not allowed");
  1363. return 0;
  1364. }
  1365. return val / maxVal;
  1366. }
  1367. static float Bobbing(float period, float amplitude, float elapsedTime)
  1368. {
  1369. //Prevent division by 0
  1370. if ( period == 0 )
  1371. period = 1;
  1372. elapsedTime /= period;
  1373. float cycle;
  1374. cycle += elapsedTime;
  1375. cycle = FModulus(cycle, 360);
  1376. cycle = Math.Sin(cycle) * amplitude;
  1377. return cycle;
  1378. }
  1379. // DEPRECATED, use Math.ModFloat directly instead
  1380. static float FModulus(float x, float y)
  1381. {
  1382. return Math.ModFloat(x, y);
  1383. }
  1384. static void RemoveSplint( PlayerBase player )
  1385. {
  1386. EntityAI entity = player.GetInventory().CreateInInventory("Splint");
  1387. if (!entity)
  1388. entity = player.SpawnEntityOnGroundOnCursorDir("Splint", 0.5);
  1389. EntityAI attachment;
  1390. ItemBase new_item = ItemBase.Cast(entity);
  1391. Class.CastTo(attachment, player.GetItemOnSlot("Splint_Right"));
  1392. if ( attachment && attachment.GetType() == "Splint_Applied" )
  1393. {
  1394. if (new_item)
  1395. {
  1396. MiscGameplayFunctions.TransferItemProperties(attachment,new_item);
  1397. if (GetGame().IsServer())
  1398. {
  1399. //Lower health level of splint after use
  1400. if (new_item.GetHealthLevel() < 4)
  1401. {
  1402. int newDmgLevel = new_item.GetHealthLevel() + 1;
  1403. float max = new_item.GetMaxHealth("","");
  1404. switch ( newDmgLevel )
  1405. {
  1406. case GameConstants.STATE_BADLY_DAMAGED:
  1407. new_item.SetHealth( "", "", max * GameConstants.DAMAGE_BADLY_DAMAGED_VALUE );
  1408. break;
  1409. case GameConstants.STATE_DAMAGED:
  1410. new_item.SetHealth( "", "", max * GameConstants.DAMAGE_DAMAGED_VALUE );
  1411. break;
  1412. case GameConstants.STATE_WORN:
  1413. new_item.SetHealth( "", "", max * GameConstants.DAMAGE_WORN_VALUE );
  1414. break;
  1415. case GameConstants.STATE_RUINED:
  1416. new_item.SetHealth( "", "", max * GameConstants.DAMAGE_RUINED_VALUE );
  1417. break;
  1418. default:
  1419. break;
  1420. }
  1421. }
  1422. }
  1423. }
  1424. attachment.Delete();
  1425. }
  1426. }
  1427. //! checks if we should teleport the player to a safe location and if so, performs the teleportation
  1428. static void TeleportCheck(notnull PlayerBase player, notnull array<ref array<float>> safe_positions)
  1429. {
  1430. if( player.GetSimulationTimeStamp() < 20 && !player.IsPersistentFlag(PersistentFlag.AREA_PRESENCE) )
  1431. {
  1432. //simulation time is bellow a threshold, which means the player has recently connected,
  1433. //the player does not have the AREA_PRESENCE flag set, which means they were not inside the area when they disconnected,
  1434. //that means they just spawned into a contaminated area, lets move them somewhere safe
  1435. vector player_pos = player.GetPosition();
  1436. vector closest_safe_pos = MiscGameplayFunctions.GetClosestSafePos(player_pos, safe_positions);
  1437. if (player_pos!=closest_safe_pos)
  1438. {
  1439. closest_safe_pos[1] = GetGame().SurfaceY(closest_safe_pos[0], closest_safe_pos[2]);
  1440. player.SetPosition( closest_safe_pos );//...so lets teleport them somewhere safe
  1441. //DeveloperTeleport.SetPlayerPosition(player, closest_safe_pos);
  1442. GetGame().RPCSingleParam(player, ERPCs.RPC_WARNING_TELEPORT, null, true, player.GetIdentity());
  1443. PluginAdminLog adminLog = PluginAdminLog.Cast(GetPlugin(PluginAdminLog));
  1444. if (adminLog)
  1445. adminLog.PlayerTeleportedLog(player,player_pos,closest_safe_pos,"Unwillingly spawning in contaminated area.");
  1446. }
  1447. player.SetPersistentFlag(PersistentFlag.AREA_PRESENCE, false);
  1448. }
  1449. }
  1450. static vector GetClosestSafePos(vector to_pos, notnull array<ref array<float>> positions)
  1451. {
  1452. vector closest_pos = to_pos;
  1453. float smallest_dist = float.MAX;
  1454. foreach( array<float> pos:positions)
  1455. {
  1456. vector vpos = "0 0 0";
  1457. vpos[0] = pos[0];
  1458. vpos[2] = pos[1];
  1459. to_pos[1] = 0;
  1460. float dist = vector.DistanceSq(to_pos, vpos);//2d dist sq
  1461. if ( dist < smallest_dist)
  1462. {
  1463. smallest_dist = dist;
  1464. closest_pos = vpos;
  1465. }
  1466. }
  1467. return closest_pos;
  1468. }
  1469. //! 'stupider' teleport method, does not touch flag management. Applies Y from the position as well!
  1470. static bool TeleportPlayerToSafeLocation3D(notnull PlayerBase player, vector safePos)
  1471. {
  1472. vector playerPos = player.GetPosition();
  1473. if (playerPos != safePos)
  1474. {
  1475. player.SetPosition(safePos);
  1476. GetGame().RPCSingleParam(player, ERPCs.RPC_WARNING_TELEPORT, null, true, player.GetIdentity());
  1477. return true;
  1478. }
  1479. return false;
  1480. }
  1481. static void GenerateAINoiseAtPosition(vector position, float lifeTime, NoiseParams noiseParams)
  1482. {
  1483. if (GetGame().IsServer())
  1484. {
  1485. NoiseSystem noise = GetGame().GetNoiseSystem();
  1486. if (noise)
  1487. {
  1488. noise.AddNoiseTarget(position, lifeTime, noiseParams, NoiseAIEvaluate.GetNoiseReduction(GetGame().GetWeather()));
  1489. }
  1490. }
  1491. }
  1492. static float GetMinValue(array<float> pArray)
  1493. {
  1494. float minValue = 0.0;
  1495. for (int i = 0; i < pArray.Count(); ++i)
  1496. {
  1497. if (minValue == 0 || pArray.Get(i) < minValue)
  1498. {
  1499. minValue = pArray.Get(i);
  1500. }
  1501. }
  1502. return minValue;
  1503. }
  1504. static float GetMaxValue(array<float> pArray)
  1505. {
  1506. float maxValue = 0.0;
  1507. for (int i = 0; i < pArray.Count(); ++i)
  1508. {
  1509. if (maxValue == 0 || pArray.Get(i) > maxValue)
  1510. {
  1511. maxValue = pArray.Get(i);
  1512. }
  1513. }
  1514. return maxValue;
  1515. }
  1516. static string GetItemDisplayName(string type)
  1517. {
  1518. return GetGame().ConfigGetTextOut("CfgVehicles " + type + " displayName");
  1519. }
  1520. static bool IsComponentInSelection(array<Selection> pSelection, string pCompName)
  1521. {
  1522. if (pSelection.Count() == 0 || pCompName.Length() == 0)
  1523. {
  1524. return false;
  1525. }
  1526. for (int i = 0; i < pSelection.Count(); ++i)
  1527. {
  1528. pCompName.ToLower();
  1529. if (pSelection[i] && pSelection[i].GetName() == pCompName)
  1530. {
  1531. return true;
  1532. }
  1533. }
  1534. return false;
  1535. }
  1536. static int GetComponentIndex(array<Selection> pSelection, string pCompName)
  1537. {
  1538. if (!MiscGameplayFunctions.IsComponentInSelection(pSelection, pCompName))
  1539. {
  1540. return INDEX_NOT_FOUND;
  1541. }
  1542. for (int i = 0; i < pSelection.Count(); ++i)
  1543. {
  1544. pCompName.ToLower();
  1545. if (pSelection[i] && pSelection[i].GetName() == pCompName)
  1546. {
  1547. return i;
  1548. }
  1549. }
  1550. return INDEX_NOT_FOUND;
  1551. }
  1552. static void RemoveAllAttachedChildrenByTypename(notnull EntityAI parent, array<typename> listOfTypenames)
  1553. {
  1554. if (listOfTypenames.Count() > 0)
  1555. {
  1556. Object child = Object.Cast(parent.GetChildren());
  1557. while (child)
  1558. {
  1559. Object childToRemove = child;
  1560. child = Object.Cast(child.GetSibling());
  1561. if (childToRemove.IsAnyInherited(listOfTypenames))
  1562. {
  1563. vector pos = parent.GetPosition();
  1564. parent.RemoveChild(childToRemove, false);
  1565. vector m4[4];
  1566. Math3D.MatrixIdentity4(m4);
  1567. m4[3] = pos;
  1568. childToRemove.SetTransform(m4);
  1569. childToRemove.PlaceOnSurface();
  1570. }
  1571. }
  1572. }
  1573. }
  1574. static void DeleteAttachedChildrenByTypename(notnull EntityAI parent, array<typename> listOfTypenames)
  1575. {
  1576. if (listOfTypenames.Count() > 0)
  1577. {
  1578. Object child = Object.Cast(parent.GetChildren());
  1579. while (child)
  1580. {
  1581. Object childToRemove = child;
  1582. child = Object.Cast(child.GetSibling());
  1583. if (childToRemove.IsAnyInherited(listOfTypenames))
  1584. {
  1585. parent.RemoveChild(childToRemove, false);
  1586. childToRemove.Delete();
  1587. }
  1588. }
  1589. }
  1590. }
  1591. //! Fills the provided array with all children entities in hierarchy of this entity
  1592. static void GetAttachedChildren(IEntity parent, array<IEntity> outputObjects)
  1593. {
  1594. IEntity child = parent.GetChildren();
  1595. while (child)
  1596. {
  1597. outputObjects.Insert(child);
  1598. child = child.GetSibling();
  1599. }
  1600. }
  1601. static void SoakItemInsideParentContainingLiquidAboveThreshold(notnull ItemBase item, notnull ItemBase parent, float liquidQuantityThresholdPercentage = 0.05)
  1602. {
  1603. if (g_Game.IsServer())
  1604. {
  1605. if (parent.GetLiquidType() != 0 && parent.GetQuantityNormalized() > liquidQuantityThresholdPercentage && !parent.GetIsFrozen())
  1606. item.SetWetMax();
  1607. }
  1608. }
  1609. static float GetCombinedSnowfallWindValue()
  1610. {
  1611. float windMin;
  1612. float windMax;
  1613. g_Game.GetWeather().GetWindMagnitude().GetLimits(windMin, windMax);
  1614. float snowfall = g_Game.GetWeather().GetSnowfall().GetActual();
  1615. float value = snowfall + g_Game.GetWeather().GetWindMagnitude().GetActual() / windMax;
  1616. return value;
  1617. }
  1618. }
  1619. class DestroyItemInCorpsesHandsAndCreateNewOnGndLambda : ReplaceAndDestroyLambda
  1620. {
  1621. // @NOTE m_Player == target player - i.e. restrained one
  1622. void DestroyItemInCorpsesHandsAndCreateNewOnGndLambda(EntityAI old_item, string new_item_type, PlayerBase player, bool destroy = false)
  1623. {
  1624. InventoryLocation gnd = new InventoryLocation;
  1625. vector mtx[4];
  1626. if (old_item)
  1627. old_item.GetTransform(mtx);
  1628. else
  1629. player.GetTransform(mtx);
  1630. gnd.SetGround(NULL, mtx);
  1631. OverrideNewLocation(gnd);
  1632. }
  1633. protected override void RemoveOldItemFromLocation()
  1634. {
  1635. super.RemoveOldItemFromLocation();
  1636. m_Player.GetHumanInventory().OnEntityInHandsDestroyed(m_OldLocation);
  1637. }
  1638. }
  1639. // This was created since IsObjectObstructed is often called multiple times in one frame
  1640. // And apparently it seems that keeping this data in one struct seems to be more efficient than creating the variables dozens of times per frame
  1641. class IsObjectObstructedCache // Pretending this is a struct
  1642. {
  1643. // Outside data
  1644. vector RaycastStart = "0 0 0";
  1645. int TotalObjects = 0;
  1646. // Inside data
  1647. vector ObjectCenterPos = "0 0 0";
  1648. vector ObjectContactPos = "0 0 0";
  1649. vector ObjectContactDir = "0 0 0";
  1650. int ContactComponent = -1;
  1651. ref array<ref RaycastRVResult> HitProxyObjects = new array<ref RaycastRVResult>;
  1652. ref set<Object> HitObjects = new set<Object>;
  1653. void IsObjectObstructedCache(vector rayCastStart, int totalObjects)
  1654. {
  1655. RaycastStart = rayCastStart;
  1656. TotalObjects = totalObjects;
  1657. }
  1658. // Only inside data
  1659. void ClearCache()
  1660. {
  1661. ObjectCenterPos = "0 0 0";
  1662. ObjectContactPos = "0 0 0";
  1663. ObjectContactDir = "0 0 0";
  1664. ContactComponent = -1;
  1665. HitProxyObjects.Clear();
  1666. HitObjects.Clear();
  1667. }
  1668. }