miscgameplayfunctions.c 59 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960
  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 randomPos;
  965. vector minmax[2];
  966. parent.GetCollisionBox(minmax);
  967. Math3D.YawPitchRollMatrix( orientation, rotation_matrix );
  968. Math3D.MatrixToQuat( rotation_matrix, direction );
  969. //gather entities first
  970. array<EntityAI> ents = new array<EntityAI>;
  971. int count, i;
  972. //atts
  973. count = parent.GetInventory().AttachmentCount();
  974. for (i = 0; i < count; ++i)
  975. {
  976. ents.Insert(parent.GetInventory().GetAttachmentFromIndex(i));
  977. }
  978. //cargo
  979. count = parent.GetInventory().GetCargo().GetItemCount();
  980. for (i = 0; i < count; ++i)
  981. {
  982. ents.Insert(parent.GetInventory().GetCargo().GetItem(i));
  983. }
  984. //now throw them all
  985. foreach (EntityAI ent : ents)
  986. {
  987. randomPos = Vector(position[0] + Math.RandomFloat(minmax[0][0], minmax[1][0]),
  988. position[1] + Math.RandomFloat(minmax[0][1], minmax[1][1]),
  989. position[2] + Math.RandomFloat(minmax[0][2], minmax[1][2]));
  990. ThrowEntityFromInventory(ent, randomPos, direction, -GetVelocity(parent), ThrowEntityFlags.NONE);
  991. }
  992. }
  993. static void ThrowEntityFromInventory(notnull EntityAI entity, vector position, float direction[4], vector force, int flags)
  994. {
  995. InventoryMode invMode = InventoryMode.SERVER;
  996. if ( !GetGame().IsMultiplayer() )
  997. invMode = InventoryMode.LOCAL;
  998. ItemBase entityIB;
  999. if (CastTo(entityIB, entity))
  1000. {
  1001. InventoryLocation dst = new InventoryLocation;
  1002. dst.SetGroundEx(entity, position, direction);
  1003. if ( (flags & ThrowEntityFlags.SPLIT) && entityIB.CanBeSplit() )
  1004. {
  1005. for (int l = 0; l < entityIB.GetQuantity(); ++l)
  1006. {
  1007. ItemBase new_item = ItemBase.Cast( GameInventory.LocationCreateEntity( dst, entityIB.GetType(), ECE_NONE, RF_DEFAULT ) );
  1008. if ( new_item )
  1009. {
  1010. MiscGameplayFunctions.TransferItemProperties(entityIB, new_item);
  1011. entityIB.AddQuantity( -1 );
  1012. new_item.SetQuantity( 1 );
  1013. new_item.ThrowPhysically(null, force, false);
  1014. }
  1015. }
  1016. }
  1017. else
  1018. {
  1019. float stackable = entityIB.GetTargetQuantityMax();
  1020. if ( !(stackable == 0 || stackable >= entityIB.GetQuantity()) )
  1021. {
  1022. while (entityIB.GetQuantity() > stackable)
  1023. {
  1024. InventoryLocation spltDst = new InventoryLocation;
  1025. position[1] = position[1] + 0.1;
  1026. spltDst.SetGroundEx(entity, position, direction);
  1027. ItemBase splitItem = entityIB.SplitIntoStackMaxToInventoryLocationEx( spltDst );
  1028. splitItem.ThrowPhysically(null, force, false);
  1029. }
  1030. }
  1031. InventoryLocation src = new InventoryLocation;
  1032. entity.GetInventory().GetCurrentInventoryLocation(src);
  1033. entity.GetInventory().TakeToDst(invMode, src, dst);
  1034. entityIB.ThrowPhysically(null, force, false);
  1035. }
  1036. }
  1037. else
  1038. {
  1039. entity.GetInventory().DropEntity(invMode, entity.GetHierarchyRoot(), entity);
  1040. dBodyApplyImpulse(entity, force);
  1041. }
  1042. }
  1043. static float GetCurrentItemHeatIsolation( ItemBase pItem )
  1044. {
  1045. float wetFactor;
  1046. float healthFactor;
  1047. float heatIsolation = pItem.GetHeatIsolation(); //! item heat isolation (from cfg)
  1048. float itemHealthLabel = pItem.GetHealthLevel(); //! item health (state)
  1049. float itemWetness = pItem.GetWet(); //! item wetness
  1050. //! wet factor selection
  1051. if ( itemWetness >= GameConstants.STATE_DRY && itemWetness < GameConstants.STATE_DAMP )
  1052. {
  1053. wetFactor = GameConstants.ENVIRO_ISOLATION_WETFACTOR_DRY;
  1054. }
  1055. else if ( itemWetness >= GameConstants.STATE_DAMP && itemWetness < GameConstants.STATE_WET )
  1056. {
  1057. wetFactor = GameConstants.ENVIRO_ISOLATION_WETFACTOR_DAMP;
  1058. }
  1059. else if ( itemWetness >= GameConstants.STATE_WET && itemWetness < GameConstants.STATE_SOAKING_WET )
  1060. {
  1061. wetFactor = GameConstants.ENVIRO_ISOLATION_WETFACTOR_WET;
  1062. }
  1063. else if ( itemWetness >= GameConstants.STATE_SOAKING_WET && itemWetness < GameConstants.STATE_DRENCHED )
  1064. {
  1065. wetFactor = GameConstants.ENVIRO_ISOLATION_WETFACTOR_SOAKED;
  1066. }
  1067. else if ( itemWetness >= GameConstants.STATE_DRENCHED )
  1068. {
  1069. return GameConstants.ENVIRO_ISOLATION_WETFACTOR_DRENCHED;
  1070. }
  1071. //! health factor selection
  1072. switch (itemHealthLabel)
  1073. {
  1074. case GameConstants.STATE_PRISTINE:
  1075. healthFactor = GameConstants.ENVIRO_ISOLATION_HEALTHFACTOR_PRISTINE;
  1076. break;
  1077. case GameConstants.STATE_WORN:
  1078. healthFactor = GameConstants.ENVIRO_ISOLATION_HEALTHFACTOR_WORN;
  1079. break;
  1080. case GameConstants.STATE_DAMAGED:
  1081. healthFactor = GameConstants.ENVIRO_ISOLATION_HEALTHFACTOR_DAMAGED;
  1082. break;
  1083. case GameConstants.STATE_BADLY_DAMAGED:
  1084. healthFactor = GameConstants.ENVIRO_ISOLATION_HEALTHFACTOR_B_DAMAGED;
  1085. break;
  1086. case GameConstants.STATE_RUINED:
  1087. healthFactor = GameConstants.ENVIRO_ISOLATION_HEALTHFACTOR_RUINED;
  1088. break;
  1089. }
  1090. //! apply factors
  1091. heatIsolation *= healthFactor;
  1092. heatIsolation *= wetFactor;
  1093. return heatIsolation;
  1094. }
  1095. static void FilterObstructingObjects(array<Object> potentiallyObstructingObjects, out array<Object> obstructingObjects)
  1096. {
  1097. if (!obstructingObjects)
  1098. obstructingObjects = new array<Object>;
  1099. for ( int i = 0; i < potentiallyObstructingObjects.Count(); ++i )
  1100. {
  1101. Object obj = potentiallyObstructingObjects[i];
  1102. if ( obj && ( obj.CanObstruct() || obj.CanProxyObstruct() ) )
  1103. obstructingObjects.Insert(obj);
  1104. }
  1105. }
  1106. static bool CanIgnoreDistanceCheck(Object obj)
  1107. {
  1108. return obj.IsTransport() || obj.CanUseConstruction();
  1109. }
  1110. //! group objects that are close to each other together
  1111. 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)
  1112. {
  1113. array<Object> vicinityObjects= new array<Object>;
  1114. vicinityObjects.Copy(objects);
  1115. int i = 0;
  1116. int j = 0;
  1117. int k = 0;
  1118. int mCount = vicinityObjects.Count();
  1119. if (!filteredObjects)
  1120. filteredObjects = new array<Object>;
  1121. // Remove objects that are too far from the player anyways
  1122. if ( doDistanceCheck )
  1123. {
  1124. for ( i = vicinityObjects.Count() - 1; i >= 0; --i )
  1125. {
  1126. Object obj = vicinityObjects[i];
  1127. if ( obj && !CanIgnoreDistanceCheck( obj ) && vector.DistanceSq(origin, obj.GetPosition()) > maxDist * maxDist )
  1128. vicinityObjects.Remove(i);
  1129. }
  1130. }
  1131. // Sort obstructingObjects to have the furthest one first
  1132. array<Object> sortedObstructingObjects = new array<Object>;
  1133. array<float> distanceHelper = new array<float>;
  1134. array<float> distanceHelperUnsorted = new array<float>;
  1135. float distance, dist1, dist2;
  1136. for ( i = 0; i < obstructingObjects.Count(); ++i )
  1137. {
  1138. distance = vector.DistanceSq(obstructingObjects[i].GetWorldPosition(), origin);
  1139. distanceHelper.Insert(distance);
  1140. }
  1141. distanceHelperUnsorted.Copy(distanceHelper);
  1142. distanceHelper.Sort();
  1143. for ( i = distanceHelper.Count() - 1; i >= 0; --i )
  1144. sortedObstructingObjects.Insert(obstructingObjects[distanceHelperUnsorted.Find(distanceHelper[i])]);
  1145. array<ref array<Object>> tempGroups = new array<ref array<Object>>;
  1146. array<ref array<Object>> objectGroups = new array<ref array<Object>>;
  1147. array<Object> group;
  1148. float cos = Math.Cos(90);
  1149. float sin = Math.Sin(90);
  1150. // Iterate through sorted obstructingObjects
  1151. for ( i = 0; i < sortedObstructingObjects.Count(); ++i )
  1152. {
  1153. Object obstrObj = sortedObstructingObjects[i];
  1154. vector worldPos = obstrObj.GetWorldPosition();
  1155. vector min, max;
  1156. vector minMax[2];
  1157. if ( obstrObj.GetCollisionBox(minMax) )
  1158. {
  1159. min = minMax[0];
  1160. max = minMax[1];
  1161. max = max * (obstrObj.GetOrientation() * range);
  1162. vector center, dx, dy, dz, half;
  1163. center = (min + max) * 0.5;
  1164. dz = obstrObj.GetOrientation();
  1165. dx = vector.RotateAroundZero(dz, vector.Up, cos, sin);
  1166. dy = vector.RotateAroundZero(dz, vector.Aside, cos, sin);
  1167. half = (max - min) * 0.5;
  1168. half = Vector(Math.AbsFloat(half[0]), Math.AbsFloat(half[1]), Math.AbsFloat(half[2]));
  1169. group = new array<Object>;
  1170. // Group objects within the above box
  1171. for ( j = vicinityObjects.Count() - 1; j >= 0; --j )
  1172. {
  1173. Object vicObj = vicinityObjects[j];
  1174. if ( vicObj )
  1175. {
  1176. vector d = vicObj.GetWorldPosition() - worldPos + center;
  1177. 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] )
  1178. {
  1179. group.Insert(vicObj);
  1180. vicinityObjects.Remove(j);
  1181. }
  1182. }
  1183. }
  1184. if ( group.Count() > 0 )
  1185. tempGroups.Insert(group);
  1186. }
  1187. }
  1188. // Go through the objects grouped by obstruction to split them by distance too
  1189. for ( i = 0; i < tempGroups.Count(); ++i )
  1190. SplitArrayIntoGroupsByDistance(tempGroups[i], objectGroups, distanceDelta);
  1191. // Split initial groups by distance
  1192. SplitArrayIntoGroupsByDistance(vicinityObjects, objectGroups, distanceDelta);
  1193. // Raycast accordingly to groups
  1194. IsObjectObstructedCache cache = new IsObjectObstructedCache(origin, mCount);
  1195. for ( i = 0; i < objectGroups.Count(); ++i )
  1196. {
  1197. array<Object> objectGroup = objectGroups[i];
  1198. Object sampleObject = objectGroup[0];
  1199. if ( !IsObjectObstructedEx(sampleObject, cache) )
  1200. filteredObjects.InsertAll(objectGroup);
  1201. cache.ClearCache();
  1202. }
  1203. }
  1204. static void SplitArrayIntoGroupsByDistance(array<Object> objects, array<ref array<Object>> objectGroups, float squaredDistanceDelta)
  1205. {
  1206. array<Object> group;
  1207. for ( int i = 0; i < objects.Count(); )
  1208. {
  1209. Object obj1 = objects[i];
  1210. if ( obj1 )
  1211. {
  1212. group = new array<Object>;
  1213. group.Insert(obj1);
  1214. for ( int j = objects.Count() - 1; j > i; --j )
  1215. {
  1216. Object obj2 = objects[j];
  1217. if ( obj1 && obj2 )
  1218. {
  1219. vector start = obj1.GetWorldPosition();
  1220. vector end = obj2.GetWorldPosition();
  1221. float distance = vector.DistanceSq(start, end);
  1222. if ( distance < squaredDistanceDelta )
  1223. {
  1224. group.Insert(obj2);
  1225. objects.Remove(j);
  1226. }
  1227. }
  1228. }
  1229. objectGroups.Insert(group);
  1230. objects.Remove(i);
  1231. continue;
  1232. }
  1233. ++i;
  1234. }
  1235. }
  1236. static bool IsObjectObstructed(Object object, bool doDistanceCheck = false, vector distanceCheckPos = "0 0 0", float maxDist = 0)
  1237. {
  1238. vector rayStart;
  1239. MiscGameplayFunctions.GetHeadBonePos(PlayerBase.Cast(GetGame().GetPlayer()), rayStart);
  1240. IsObjectObstructedCache cache = new IsObjectObstructedCache(rayStart, 1);
  1241. return IsObjectObstructedEx(object, cache, doDistanceCheck, distanceCheckPos, maxDist);
  1242. }
  1243. static bool IsObjectObstructedEx(Object object, IsObjectObstructedCache cache, bool doDistanceCheck = false, vector distanceCheckPos = "0 0 0", float maxDist = 0)
  1244. {
  1245. if (!object)
  1246. return true;
  1247. PlayerBase player = PlayerBase.Cast(g_Game.GetPlayer());
  1248. if (doDistanceCheck && vector.DistanceSq(player.GetPosition(), distanceCheckPos) > maxDist * maxDist)
  1249. return true;
  1250. cache.ObjectCenterPos = object.GetCenter();
  1251. return IsObjectObstructedFilterEx(object, cache, player);
  1252. }
  1253. static bool IsObjectObstructedProxy(Object object, IsObjectObstructedCache cache, PlayerBase player)
  1254. {
  1255. if (object.CanProxyObstruct())
  1256. {
  1257. RaycastRVParams rayInput = new RaycastRVParams(cache.RaycastStart, cache.ObjectCenterPos, player);
  1258. DayZPhysics.RaycastRVProxy(rayInput, cache.HitProxyObjects);
  1259. if (cache.HitProxyObjects)
  1260. {
  1261. if (cache.HitProxyObjects.Count() > 0)
  1262. {
  1263. if (cache.HitProxyObjects[0].hierLevel > 0)
  1264. {
  1265. // ignores attachments on player
  1266. if (!cache.HitProxyObjects[0].parent.IsMan())
  1267. {
  1268. if (cache.HitProxyObjects[0].parent)
  1269. {
  1270. EntityAI proxyParent = EntityAI.Cast(cache.HitProxyObjects[0].parent);
  1271. if (proxyParent.GetInventory() && proxyParent.GetInventory().GetCargo())
  1272. return true;
  1273. }
  1274. }
  1275. }
  1276. }
  1277. }
  1278. }
  1279. return false;
  1280. }
  1281. static bool IsObjectObstructedFilter(Object object, IsObjectObstructedCache cache, PlayerBase player)
  1282. {
  1283. for (int m = 0; m < cache.HitObjects.Count(); ++m)
  1284. {
  1285. Object hit_object = cache.HitObjects.Get(m);
  1286. if ( hit_object.CanObstruct() )
  1287. return true;
  1288. //4.3. ignore item if items are big and heavy >= OBJECT_OBSTRUCTION_WEIGHT
  1289. //EntityAI eai;
  1290. //if ( Class.CastTo( eai, hit_object ) )
  1291. //{
  1292. // if ( eai.GetWeight() >= OBJECT_OBSTRUCTION_WEIGHT )
  1293. // {
  1294. // if ( eai != filtered_object && eai.GetHierarchyRoot() != filtered_object )
  1295. // {
  1296. // //Print("!!!!!obstacle vaha: " + hit_object);
  1297. // is_obstructed = true;
  1298. // }
  1299. // }
  1300. //}
  1301. }
  1302. return false;
  1303. }
  1304. //! groups 'RaycastRVProxy' and 'RaycastRV' approaches into one method, allowes for comprehensive geometry override, if desired
  1305. static bool IsObjectObstructedFilterEx(Object object, IsObjectObstructedCache cache, PlayerBase player, int geometryTypeOverride = -1)
  1306. {
  1307. //first proxy geometries
  1308. RaycastRVParams rayInput = new RaycastRVParams(cache.RaycastStart, cache.ObjectCenterPos, player);
  1309. rayInput.flags = CollisionFlags.ALLOBJECTS;
  1310. if (geometryTypeOverride != -1)
  1311. rayInput.type = geometryTypeOverride; //default 'ObjIntersectView'
  1312. DayZPhysics.RaycastRVProxy(rayInput, cache.HitProxyObjects);
  1313. int count;
  1314. int i;
  1315. if (cache.HitProxyObjects)
  1316. {
  1317. count = cache.HitProxyObjects.Count();
  1318. Object parent;
  1319. for (i = 0; i < count; ++i)
  1320. {
  1321. if (cache.HitProxyObjects[i].hierLevel > 0) //parent has to exist, skipping nullcheck
  1322. {
  1323. parent = cache.HitProxyObjects[i].parent;
  1324. if (parent && !parent.IsMan() && parent.CanProxyObstruct())
  1325. {
  1326. if (parent != object || (parent == object && object.CanProxyObstructSelf()))
  1327. return true;
  1328. }
  1329. }
  1330. }
  1331. }
  1332. //second, regular raycast
  1333. int geometry = ObjIntersectFire; //default for the RV raycast
  1334. if (geometryTypeOverride != -1)
  1335. geometry = geometryTypeOverride;
  1336. DayZPhysics.RaycastRV(cache.RaycastStart, cache.ObjectCenterPos, cache.ObjectContactPos, cache.ObjectContactDir, cache.ContactComponent, cache.HitObjects, object, GetGame().GetPlayer(), false, false, geometry, 0.0, CollisionFlags.ALLOBJECTS);
  1337. count = cache.HitObjects.Count();
  1338. for (i = 0; i < count; ++i)
  1339. {
  1340. if (cache.HitObjects[i].CanObstruct())
  1341. return true;
  1342. }
  1343. return false;
  1344. }
  1345. //Inflict damage to item based on environmental temperature and surface type
  1346. static void DealEvinronmentAdjustedDmg(ItemBase item, PlayerBase player, float baseDamage)
  1347. {
  1348. string surfaceType;
  1349. int liquidType;
  1350. float adjustedDamage;
  1351. GetGame().SurfaceUnderObject(player, surfaceType, liquidType);
  1352. float modifierSurface = Surface.GetParamFloat(surfaceType, "toolDamage"); // toolDamage
  1353. if (modifierSurface == 0)
  1354. modifierSurface = 1;
  1355. if (player.GetInColdArea())
  1356. adjustedDamage = baseDamage * (modifierSurface + GetGame().GetMission().GetWorldData().GetColdAreaToolDamageModifier());
  1357. else
  1358. adjustedDamage = baseDamage * modifierSurface;
  1359. DealAbsoluteDmg(item, adjustedDamage);
  1360. }
  1361. //Inflict absolute damage to item (used on tools when completing actions)
  1362. static void DealAbsoluteDmg(ItemBase item, float dmg)
  1363. {
  1364. item.DecreaseHealth(dmg, false);
  1365. }
  1366. //Function used to normailze values, enter the used value and the max value (max will become 1)
  1367. static float Normalize(int val, int maxVal)
  1368. {
  1369. if (maxVal == 0)
  1370. {
  1371. Debug.LogError("Division by 0 is not allowed");
  1372. return 0;
  1373. }
  1374. return val / maxVal;
  1375. }
  1376. static float Bobbing(float period, float amplitude, float elapsedTime)
  1377. {
  1378. //Prevent division by 0
  1379. if ( period == 0 )
  1380. period = 1;
  1381. elapsedTime /= period;
  1382. float cycle;
  1383. cycle += elapsedTime;
  1384. cycle = FModulus(cycle, 360);
  1385. cycle = Math.Sin(cycle) * amplitude;
  1386. return cycle;
  1387. }
  1388. // DEPRECATED, use Math.ModFloat directly instead
  1389. static float FModulus(float x, float y)
  1390. {
  1391. return Math.ModFloat(x, y);
  1392. }
  1393. static void RemoveSplint( PlayerBase player )
  1394. {
  1395. EntityAI entity = player.GetInventory().CreateInInventory("Splint");
  1396. if (!entity)
  1397. entity = player.SpawnEntityOnGroundOnCursorDir("Splint", 0.5);
  1398. EntityAI attachment;
  1399. ItemBase new_item = ItemBase.Cast(entity);
  1400. Class.CastTo(attachment, player.GetItemOnSlot("Splint_Right"));
  1401. if ( attachment && attachment.GetType() == "Splint_Applied" )
  1402. {
  1403. if (new_item)
  1404. {
  1405. MiscGameplayFunctions.TransferItemProperties(attachment,new_item);
  1406. if (GetGame().IsServer())
  1407. {
  1408. //Lower health level of splint after use
  1409. if (new_item.GetHealthLevel() < 4)
  1410. {
  1411. int newDmgLevel = new_item.GetHealthLevel() + 1;
  1412. float max = new_item.GetMaxHealth("","");
  1413. switch ( newDmgLevel )
  1414. {
  1415. case GameConstants.STATE_BADLY_DAMAGED:
  1416. new_item.SetHealth( "", "", max * GameConstants.DAMAGE_BADLY_DAMAGED_VALUE );
  1417. break;
  1418. case GameConstants.STATE_DAMAGED:
  1419. new_item.SetHealth( "", "", max * GameConstants.DAMAGE_DAMAGED_VALUE );
  1420. break;
  1421. case GameConstants.STATE_WORN:
  1422. new_item.SetHealth( "", "", max * GameConstants.DAMAGE_WORN_VALUE );
  1423. break;
  1424. case GameConstants.STATE_RUINED:
  1425. new_item.SetHealth( "", "", max * GameConstants.DAMAGE_RUINED_VALUE );
  1426. break;
  1427. default:
  1428. break;
  1429. }
  1430. }
  1431. }
  1432. }
  1433. attachment.Delete();
  1434. }
  1435. }
  1436. //! checks if we should teleport the player to a safe location and if so, performs the teleportation
  1437. static void TeleportCheck(notnull PlayerBase player, notnull array<ref array<float>> safe_positions)
  1438. {
  1439. if( player.GetSimulationTimeStamp() < 20 && !player.IsPersistentFlag(PersistentFlag.AREA_PRESENCE) )
  1440. {
  1441. //simulation time is bellow a threshold, which means the player has recently connected,
  1442. //the player does not have the AREA_PRESENCE flag set, which means they were not inside the area when they disconnected,
  1443. //that means they just spawned into a contaminated area, lets move them somewhere safe
  1444. vector player_pos = player.GetPosition();
  1445. vector closest_safe_pos = MiscGameplayFunctions.GetClosestSafePos(player_pos, safe_positions);
  1446. if (player_pos!=closest_safe_pos)
  1447. {
  1448. closest_safe_pos[1] = GetGame().SurfaceY(closest_safe_pos[0], closest_safe_pos[2]);
  1449. player.SetPosition( closest_safe_pos );//...so lets teleport them somewhere safe
  1450. //DeveloperTeleport.SetPlayerPosition(player, closest_safe_pos);
  1451. GetGame().RPCSingleParam(player, ERPCs.RPC_WARNING_TELEPORT, null, true, player.GetIdentity());
  1452. PluginAdminLog adminLog = PluginAdminLog.Cast(GetPlugin(PluginAdminLog));
  1453. if (adminLog)
  1454. adminLog.PlayerTeleportedLog(player,player_pos,closest_safe_pos,"Unwillingly spawning in contaminated area.");
  1455. }
  1456. player.SetPersistentFlag(PersistentFlag.AREA_PRESENCE, false);
  1457. }
  1458. }
  1459. static vector GetClosestSafePos(vector to_pos, notnull array<ref array<float>> positions)
  1460. {
  1461. vector closest_pos = to_pos;
  1462. float smallest_dist = float.MAX;
  1463. foreach( array<float> pos:positions)
  1464. {
  1465. vector vpos = "0 0 0";
  1466. vpos[0] = pos[0];
  1467. vpos[2] = pos[1];
  1468. to_pos[1] = 0;
  1469. float dist = vector.DistanceSq(to_pos, vpos);//2d dist sq
  1470. if ( dist < smallest_dist)
  1471. {
  1472. smallest_dist = dist;
  1473. closest_pos = vpos;
  1474. }
  1475. }
  1476. return closest_pos;
  1477. }
  1478. //! 'stupider' teleport method, does not touch flag management. Applies Y from the position as well!
  1479. static bool TeleportPlayerToSafeLocation3D(notnull PlayerBase player, vector safePos)
  1480. {
  1481. vector playerPos = player.GetPosition();
  1482. if (playerPos != safePos)
  1483. {
  1484. player.SetPosition(safePos);
  1485. GetGame().RPCSingleParam(player, ERPCs.RPC_WARNING_TELEPORT, null, true, player.GetIdentity());
  1486. return true;
  1487. }
  1488. return false;
  1489. }
  1490. static void GenerateAINoiseAtPosition(vector position, float lifeTime, NoiseParams noiseParams)
  1491. {
  1492. if (GetGame().IsServer())
  1493. {
  1494. NoiseSystem noise = GetGame().GetNoiseSystem();
  1495. if (noise)
  1496. {
  1497. noise.AddNoiseTarget(position, lifeTime, noiseParams, NoiseAIEvaluate.GetNoiseReduction(GetGame().GetWeather()));
  1498. }
  1499. }
  1500. }
  1501. static float GetMinValue(array<float> pArray)
  1502. {
  1503. float minValue = 0.0;
  1504. for (int i = 0; i < pArray.Count(); ++i)
  1505. {
  1506. if (minValue == 0 || pArray.Get(i) < minValue)
  1507. {
  1508. minValue = pArray.Get(i);
  1509. }
  1510. }
  1511. return minValue;
  1512. }
  1513. static float GetMaxValue(array<float> pArray)
  1514. {
  1515. float maxValue = 0.0;
  1516. for (int i = 0; i < pArray.Count(); ++i)
  1517. {
  1518. if (maxValue == 0 || pArray.Get(i) > maxValue)
  1519. {
  1520. maxValue = pArray.Get(i);
  1521. }
  1522. }
  1523. return maxValue;
  1524. }
  1525. static string GetItemDisplayName(string type)
  1526. {
  1527. return GetGame().ConfigGetTextOut("CfgVehicles " + type + " displayName");
  1528. }
  1529. static bool IsComponentInSelection(array<Selection> pSelection, string pCompName)
  1530. {
  1531. if (pSelection.Count() == 0 || pCompName.Length() == 0)
  1532. {
  1533. return false;
  1534. }
  1535. for (int i = 0; i < pSelection.Count(); ++i)
  1536. {
  1537. pCompName.ToLower();
  1538. if (pSelection[i] && pSelection[i].GetName() == pCompName)
  1539. {
  1540. return true;
  1541. }
  1542. }
  1543. return false;
  1544. }
  1545. static int GetComponentIndex(array<Selection> pSelection, string pCompName)
  1546. {
  1547. if (!MiscGameplayFunctions.IsComponentInSelection(pSelection, pCompName))
  1548. {
  1549. return INDEX_NOT_FOUND;
  1550. }
  1551. for (int i = 0; i < pSelection.Count(); ++i)
  1552. {
  1553. pCompName.ToLower();
  1554. if (pSelection[i] && pSelection[i].GetName() == pCompName)
  1555. {
  1556. return i;
  1557. }
  1558. }
  1559. return INDEX_NOT_FOUND;
  1560. }
  1561. static void RemoveAllAttachedChildrenByTypename(notnull EntityAI parent, array<typename> listOfTypenames)
  1562. {
  1563. if (listOfTypenames.Count() > 0)
  1564. {
  1565. Object child = Object.Cast(parent.GetChildren());
  1566. while (child)
  1567. {
  1568. Object childToRemove = child;
  1569. child = Object.Cast(child.GetSibling());
  1570. if (childToRemove.IsAnyInherited(listOfTypenames))
  1571. {
  1572. vector pos = parent.GetPosition();
  1573. parent.RemoveChild(childToRemove, false);
  1574. vector m4[4];
  1575. Math3D.MatrixIdentity4(m4);
  1576. m4[3] = pos;
  1577. childToRemove.SetTransform(m4);
  1578. childToRemove.PlaceOnSurface();
  1579. }
  1580. }
  1581. }
  1582. }
  1583. static void DeleteAttachedChildrenByTypename(notnull EntityAI parent, array<typename> listOfTypenames)
  1584. {
  1585. if (listOfTypenames.Count() > 0)
  1586. {
  1587. Object child = Object.Cast(parent.GetChildren());
  1588. while (child)
  1589. {
  1590. Object childToRemove = child;
  1591. child = Object.Cast(child.GetSibling());
  1592. if (childToRemove.IsAnyInherited(listOfTypenames))
  1593. {
  1594. parent.RemoveChild(childToRemove, false);
  1595. childToRemove.Delete();
  1596. }
  1597. }
  1598. }
  1599. }
  1600. //! Fills the provided array with all children entities in hierarchy of this entity
  1601. static void GetAttachedChildren(IEntity parent, array<IEntity> outputObjects)
  1602. {
  1603. IEntity child = parent.GetChildren();
  1604. while (child)
  1605. {
  1606. outputObjects.Insert(child);
  1607. child = child.GetSibling();
  1608. }
  1609. }
  1610. static void SoakItemInsideParentContainingLiquidAboveThreshold(notnull ItemBase item, notnull ItemBase parent, float liquidQuantityThresholdPercentage = 0.05)
  1611. {
  1612. if (g_Game.IsServer())
  1613. {
  1614. if (parent.GetLiquidType() != 0 && parent.GetQuantityNormalized() > liquidQuantityThresholdPercentage && !parent.GetIsFrozen())
  1615. item.SetWetMax();
  1616. }
  1617. }
  1618. static float GetCombinedSnowfallWindValue()
  1619. {
  1620. float windMin;
  1621. float windMax;
  1622. g_Game.GetWeather().GetWindMagnitude().GetLimits(windMin, windMax);
  1623. float snowfall = g_Game.GetWeather().GetSnowfall().GetActual();
  1624. float value = snowfall + g_Game.GetWeather().GetWindMagnitude().GetActual() / windMax;
  1625. return value;
  1626. }
  1627. }
  1628. class DestroyItemInCorpsesHandsAndCreateNewOnGndLambda : ReplaceAndDestroyLambda
  1629. {
  1630. // @NOTE m_Player == target player - i.e. restrained one
  1631. void DestroyItemInCorpsesHandsAndCreateNewOnGndLambda(EntityAI old_item, string new_item_type, PlayerBase player, bool destroy = false)
  1632. {
  1633. InventoryLocation gnd = new InventoryLocation;
  1634. vector mtx[4];
  1635. if (old_item)
  1636. old_item.GetTransform(mtx);
  1637. else
  1638. player.GetTransform(mtx);
  1639. gnd.SetGround(NULL, mtx);
  1640. OverrideNewLocation(gnd);
  1641. }
  1642. protected override void RemoveOldItemFromLocation()
  1643. {
  1644. super.RemoveOldItemFromLocation();
  1645. m_Player.GetHumanInventory().OnEntityInHandsDestroyed(m_OldLocation);
  1646. }
  1647. }
  1648. // This was created since IsObjectObstructed is often called multiple times in one frame
  1649. // 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
  1650. class IsObjectObstructedCache // Pretending this is a struct
  1651. {
  1652. // Outside data
  1653. vector RaycastStart = "0 0 0";
  1654. int TotalObjects = 0;
  1655. // Inside data
  1656. vector ObjectCenterPos = "0 0 0";
  1657. vector ObjectContactPos = "0 0 0";
  1658. vector ObjectContactDir = "0 0 0";
  1659. int ContactComponent = -1;
  1660. ref array<ref RaycastRVResult> HitProxyObjects = new array<ref RaycastRVResult>;
  1661. ref set<Object> HitObjects = new set<Object>;
  1662. void IsObjectObstructedCache(vector rayCastStart, int totalObjects)
  1663. {
  1664. RaycastStart = rayCastStart;
  1665. TotalObjects = totalObjects;
  1666. }
  1667. // Only inside data
  1668. void ClearCache()
  1669. {
  1670. ObjectCenterPos = "0 0 0";
  1671. ObjectContactPos = "0 0 0";
  1672. ObjectContactDir = "0 0 0";
  1673. ContactComponent = -1;
  1674. HitProxyObjects.Clear();
  1675. HitObjects.Clear();
  1676. }
  1677. }