miscgameplayfunctions.c 55 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859
  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. static array<Magazine> CreateMagazinePiles(string item_name, vector ground_position, float quantity, float health )
  439. {
  440. array<Magazine> items;
  441. float stack_size;
  442. Magazine pile;
  443. items = new array<Magazine>;
  444. stack_size = g_Game.ConfigGetInt("cfgMagazines " + item_name + " count");
  445. int piles_count = Math.Floor(quantity/stack_size);
  446. int rest = quantity - (piles_count*stack_size);
  447. for ( int i = 0; i < piles_count; i++ )
  448. {
  449. pile = Magazine.Cast(GetGame().CreateObjectEx(item_name, ground_position, ECE_PLACE_ON_SURFACE));
  450. pile.ServerSetAmmoCount(stack_size);
  451. items.Insert(pile);
  452. }
  453. if ( rest > 0)
  454. {
  455. pile = Magazine.Cast(GetGame().CreateObjectEx(item_name, ground_position, ECE_PLACE_ON_SURFACE));
  456. pile.ServerSetAmmoCount(rest);
  457. items.Insert(pile);
  458. }
  459. return items;
  460. }
  461. static array<Magazine> CreateMagazinePilesFromBullet(string bullet_type, vector ground_position, float quantity, float health )
  462. {
  463. array<Magazine> items;
  464. items = new array<Magazine>;
  465. float stack_size;
  466. Magazine pile;
  467. string item_name;
  468. if( !g_Game.ConfigGetText("cfgAmmo " + bullet_type + " spawnPileType", item_name) )
  469. return items;
  470. stack_size = g_Game.ConfigGetInt("cfgMagazines " + item_name + " count");
  471. if(stack_size > 0)
  472. {
  473. int piles_count = Math.Floor(quantity/stack_size);
  474. int rest = quantity - (piles_count*stack_size);
  475. for ( int i = 0; i < piles_count; i++ )
  476. {
  477. pile = Magazine.Cast(GetGame().CreateObjectEx(item_name, ground_position, ECE_PLACE_ON_SURFACE));
  478. pile.ServerSetAmmoCount(stack_size);
  479. items.Insert(pile);
  480. }
  481. if ( rest > 0)
  482. {
  483. pile = Magazine.Cast(GetGame().CreateObjectEx(item_name, ground_position, ECE_PLACE_ON_SURFACE));
  484. pile.ServerSetAmmoCount(rest);
  485. items.Insert(pile);
  486. }
  487. }
  488. return items;
  489. }
  490. static int GetHealthLevelForAmmo(string class_name, float health)
  491. {
  492. float health_normalized = health / 100;
  493. string config_path = CFG_WEAPONSPATH + " " + class_name + " DamageSystem" + " GlobalHealth" + " healthLabels";
  494. CachedObjectsArrays.ARRAY_FLOAT.Clear();
  495. GetGame().ConfigGetFloatArray(config_path, CachedObjectsArrays.ARRAY_FLOAT);
  496. for(int i = 0; i < CachedObjectsArrays.ARRAY_FLOAT.Count(); i++)
  497. {
  498. if( health_normalized >= CachedObjectsArrays.ARRAY_FLOAT.Get(i) )
  499. {
  500. return i;
  501. }
  502. }
  503. return -1;
  504. }
  505. static float GetTypeMaxGlobalHealth(string class_name, string health_type = "Health")
  506. {
  507. float max_health;
  508. string cfg_path;
  509. if ( GetGame().ConfigIsExisting(CFG_VEHICLESPATH+" "+class_name) )
  510. {
  511. cfg_path = CFG_VEHICLESPATH;
  512. }
  513. else if ( GetGame().ConfigIsExisting(CFG_WEAPONSPATH+" "+class_name) )
  514. {
  515. cfg_path = CFG_WEAPONSPATH;
  516. }
  517. else if ( GetGame().ConfigIsExisting(CFG_MAGAZINESPATH+" "+class_name) )
  518. {
  519. cfg_path = CFG_MAGAZINESPATH;
  520. }
  521. cfg_path = cfg_path + " "+class_name+" DamageSystem GlobalHealth " + health_type + " hitpoints";
  522. max_health = GetGame().ConfigGetFloat(cfg_path);
  523. return max_health;
  524. }
  525. static bool GetProjectedCursorPos3d (out vector position, Weapon_Base weapon)
  526. {
  527. vector usti_hlavne_position = weapon.GetSelectionPositionMS( "usti hlavne" );
  528. vector konec_hlavne_position = weapon.GetSelectionPositionMS( "konec hlavne" );
  529. vector end_point = weapon.ModelToWorld(usti_hlavne_position);
  530. vector begin_point = weapon.ModelToWorld(konec_hlavne_position);
  531. vector contact_dir;
  532. int contact_component;
  533. vector aim_point = end_point - begin_point;
  534. aim_point = aim_point.Normalized() * PROJECTED_CURSOR_DISTANCE;
  535. aim_point = aim_point + end_point;
  536. if (DayZPhysics.RaycastRV(begin_point, aim_point, position, contact_dir, contact_component, null, null, null, false, false, ObjIntersectFire))
  537. return true;
  538. return false;
  539. }
  540. static void GetHeadBonePos(notnull PlayerBase player, out vector pos)
  541. {
  542. // Get position of head for starting trace pos, otherwise use sane default
  543. int headBoneIdx = player.GetBoneIndexByName("Head");
  544. if ( headBoneIdx == -1 )
  545. { pos = player.GetPosition()[1] + 1.6; }
  546. else
  547. { pos = player.GetBonePositionWS(headBoneIdx); }
  548. }
  549. static vector GetHeadingVector(notnull PlayerBase player)
  550. {
  551. vector dir = vector.Zero;
  552. float headingAngle = GetHeadingAngle(player);
  553. dir[0] = Math.Cos(headingAngle + Math.PI_HALF);
  554. dir[2] = Math.Sin(headingAngle + Math.PI_HALF);
  555. return dir.Normalized();
  556. }
  557. static float GetHeadingAngle(notnull DayZPlayerImplement player)
  558. {
  559. HumanInputController hic = player.GetInputController();
  560. float headingAngle = hic.GetHeadingAngle();
  561. return headingAngle;
  562. }
  563. static float GetEnergyMetabolicSpeed(int movement_speed)
  564. {
  565. float speed;
  566. switch (movement_speed)
  567. {
  568. case DayZPlayerConstants.MOVEMENTIDX_WALK:
  569. speed = PlayerConstants.METABOLIC_SPEED_ENERGY_WALK;
  570. break;
  571. case DayZPlayerConstants.MOVEMENTIDX_RUN:
  572. speed = PlayerConstants.METABOLIC_SPEED_ENERGY_JOG;
  573. break;
  574. case DayZPlayerConstants.MOVEMENTIDX_SPRINT:
  575. speed = PlayerConstants.METABOLIC_SPEED_ENERGY_SPRINT;
  576. break;
  577. default:
  578. speed = 0;
  579. break;
  580. }
  581. speed += PlayerConstants.METABOLIC_SPEED_ENERGY_BASAL;
  582. return speed;
  583. }
  584. static float GetWaterMetabolicSpeed(int movement_speed)
  585. {
  586. float speed;
  587. switch (movement_speed)
  588. {
  589. case DayZPlayerConstants.MOVEMENTIDX_WALK:
  590. speed = PlayerConstants.METABOLIC_SPEED_WATER_WALK;
  591. break;
  592. case DayZPlayerConstants.MOVEMENTIDX_RUN:
  593. speed = PlayerConstants.METABOLIC_SPEED_WATER_JOG;
  594. break;
  595. case DayZPlayerConstants.MOVEMENTIDX_SPRINT:
  596. speed = PlayerConstants.METABOLIC_SPEED_WATER_SPRINT;
  597. break;
  598. default:
  599. speed = 0;
  600. break;
  601. }
  602. speed += PlayerConstants.METABOLIC_SPEED_WATER_BASAL;
  603. return speed;
  604. }
  605. static string ObtainRestrainItemTargetClassname(notnull EntityAI entity)
  606. {
  607. return entity.ConfigGetString( "OnRestrainChange");
  608. }
  609. static void TransformRestrainItem(EntityAI current_item, EntityAI tool, PlayerBase player_source, PlayerBase player_target, bool destroy = false)
  610. {
  611. bool type;
  612. if ( tool )
  613. {
  614. //is unrestrain and not struggle
  615. type = tool.ConfigGetBool("RestrainUnlockType");
  616. }
  617. string new_item_name = current_item.ConfigGetString( "OnRestrainChange");
  618. if ( new_item_name != "" )
  619. {
  620. if ( player_target )
  621. {
  622. if (player_target.IsAlive())
  623. MiscGameplayFunctions.TurnItemIntoItemEx(player_target, new ReplaceAndDestroyLambdaEx(current_item, new_item_name, player_target, type));
  624. else
  625. MiscGameplayFunctions.TurnItemIntoItemEx(player_source, new DestroyItemInCorpsesHandsAndCreateNewOnGndLambda(current_item, new_item_name, player_target, type));
  626. }
  627. else
  628. {
  629. MiscGameplayFunctions.TurnItemIntoItemEx(player_target, new ReplaceAndDestroyLambdaEx(current_item, new_item_name, player_target, type));
  630. }
  631. }
  632. else
  633. {
  634. Error("current_item:" +current_item+ ", tool:" +tool +". No value for 'OnRestrainChange' config parameter");
  635. }
  636. }
  637. static bool IsValueInRange(float value, float from, float to)
  638. {
  639. return (value >= from) && (value <= to);
  640. }
  641. //! Check if player direction(based on cone of defined angle) is oriented to target position
  642. static bool IsPlayerOrientedTowardPos(notnull DayZPlayerImplement player, vector target_pos, float cone_angle)
  643. {
  644. if (player)
  645. {
  646. vector player_dir = player.GetDirection();
  647. vector to_target_dir = target_pos - player.GetPosition();
  648. player_dir[1] = 0;
  649. to_target_dir[1] = 0;
  650. player_dir.Normalize();
  651. to_target_dir.Normalize();
  652. float cos_fi = vector.Dot(player_dir, to_target_dir);
  653. vector cross = player_dir * to_target_dir;
  654. int dir = Math.Acos(cos_fi) * Math.RAD2DEG;
  655. if( cross[1] < 0 )
  656. dir = -dir;
  657. //! dir in cone or in a tip of cone
  658. if( (dir <= cone_angle && dir >= -cone_angle) || Math.AbsFloat(dir) == 90 )
  659. {
  660. return true;
  661. }
  662. }
  663. return false;
  664. }
  665. static string SanitizeString(string input)
  666. {
  667. int max_length = 512;
  668. string output = input;
  669. output = output.Substring(0,Math.Clamp(max_length,0,output.Length()));
  670. return output;
  671. }
  672. // deprecated - dont use
  673. static bool ComplexBuildCollideCheckClient( PlayerBase player, ActionTarget target, ItemBase item, string partName = "" )
  674. {
  675. return true;
  676. }
  677. static bool ComplexBuildCollideCheckClient( PlayerBase player, ActionTarget target, ItemBase item, int constraction_index )
  678. {
  679. BaseBuildingBase base_building = BaseBuildingBase.Cast( target.GetObject() );
  680. if (base_building)
  681. {
  682. Construction construction = base_building.GetConstruction();
  683. if (construction && BuildCondition( player, target, item, false, constraction_index ))
  684. {
  685. ConstructionActionData construction_action_data = player.GetConstructionActionData();
  686. string partName;
  687. if ( item )
  688. {
  689. partName = construction_action_data.GetBuildPartAtIndex(constraction_index).GetPartName();
  690. }
  691. else
  692. {
  693. partName = construction_action_data.GetBuildPartNoToolAtIndex(constraction_index).GetPartName();
  694. }
  695. bool boo;
  696. if (base_building.PerformRoofCheckForBase(partName,player,boo) && boo)
  697. return false;
  698. if ( player.IsPlacingLocal() || player.IsPlacingServer() )
  699. return false;
  700. /*float distance_root = vector.DistanceSq(target.GetCursorHitPos(), player.GetPosition());
  701. if (!CfgGameplayHandler.GetDisableDistanceCheck() && distance_root < UAMaxDistances.BASEBUILDING_SHORT)
  702. {
  703. return false;
  704. } */
  705. return !construction.IsColliding( partName );
  706. }
  707. }
  708. return false;
  709. }
  710. // deprecated - dont use
  711. static bool BuildCondition( PlayerBase player, ActionTarget target, ItemBase item, bool camera_check )
  712. {
  713. return true;
  714. }
  715. static bool BuildCondition( PlayerBase player, ActionTarget target, ItemBase item, bool camera_check, int constraction_index )
  716. {
  717. Object targetObject = target.GetObject();
  718. if ( targetObject && targetObject.CanUseConstruction() )
  719. {
  720. BaseBuildingBase base_building = BaseBuildingBase.Cast( targetObject );
  721. ConstructionActionData construction_action_data = player.GetConstructionActionData();
  722. construction_action_data.SetTarget( targetObject );
  723. ConstructionPart constrution_part;
  724. if ( item )
  725. {
  726. constrution_part = construction_action_data.GetBuildPartAtIndex(constraction_index);
  727. }
  728. else
  729. {
  730. constrution_part = construction_action_data.GetBuildPartNoToolAtIndex(constraction_index);
  731. }
  732. //Debug
  733. /*
  734. if ( constrution_part )
  735. {
  736. Construction construction = base_building.GetConstruction();
  737. construction.IsColliding( constrution_part.GetPartName() );
  738. }
  739. */
  740. if ( constrution_part )
  741. {
  742. //camera and position checks
  743. bool position_check = ( base_building.MustBeBuiltFromOutside() && !base_building.IsPlayerInside(player, constrution_part.GetMainPartName()) ) || ( !base_building.MustBeBuiltFromOutside() && base_building.IsPlayerInside(player, constrution_part.GetMainPartName()) );
  744. if ( position_check && !player.GetInputController().CameraIsFreeLook() )
  745. {
  746. //Camera check (client-only)
  747. if ( camera_check )
  748. {
  749. if ( GetGame() && ( !GetGame().IsDedicatedServer() ) )
  750. {
  751. return !base_building.IsFacingCamera( constrution_part.GetMainPartName() );
  752. }
  753. }
  754. return true;
  755. }
  756. }
  757. }
  758. return false;
  759. }
  760. static void IsUnderRoofFromToCalculation(EntityAI entity, out vector from, out vector to, float height = GameConstants.ROOF_CHECK_RAYCAST_DIST)
  761. {
  762. vector minMax[2];
  763. entity.GetCollisionBox(minMax);
  764. vector size = Vector(0,0,0);
  765. //size[1] = minMax[1][1] - minMax[0][1];
  766. float from_override = entity.HeightStartCheckOverride();
  767. if (from_override > 0.0)
  768. {
  769. size[1] = from_override;
  770. }
  771. else
  772. {
  773. size[1] = minMax[1][1] - minMax[0][1];
  774. }
  775. from = entity.GetPosition() + size;
  776. if ( entity.HeightCheckOverride() > 0 )
  777. {
  778. to = entity.GetPosition() + Vector(0, entity.HeightCheckOverride(), 0);
  779. }
  780. else
  781. {
  782. vector ceiling = "0 0 0";
  783. ceiling[1] = height;
  784. to = from + ceiling; //+size ??? offset to cast same distance
  785. }
  786. }
  787. static bool IsUnderRoof(EntityAI entity, float height = GameConstants.ROOF_CHECK_RAYCAST_DIST)
  788. {
  789. return IsUnderRoofEx(entity, height, ObjIntersectIFire);
  790. }
  791. static bool IsUnderRoofEx(EntityAI entity, float height = GameConstants.ROOF_CHECK_RAYCAST_DIST, int geometry = ObjIntersectView)
  792. {
  793. vector from;
  794. vector to;
  795. IsUnderRoofFromToCalculation(entity, from, to, height);
  796. vector contact_pos;
  797. vector contact_dir;
  798. int contact_component;
  799. return DayZPhysics.RaycastRV(from, to, contact_pos, contact_dir, contact_component, NULL, NULL, entity, false, false, geometry,0.25);
  800. }
  801. // cooking equipment effects (get position for steam particle)
  802. static vector GetSteamPosition( EntityAI parent )
  803. {
  804. vector particle_pos;
  805. float steam_offset = 0;
  806. if ( parent )
  807. {
  808. particle_pos = parent.GetPosition();
  809. if ( parent.IsInherited( PortableGasStove ) )
  810. {
  811. steam_offset = 0.2;
  812. }
  813. else if ( parent.IsInherited( FireplaceBase ) )
  814. {
  815. FireplaceBase fireplace = FireplaceBase.Cast( parent );
  816. if ( fireplace.IsBaseFireplace() )
  817. {
  818. steam_offset = 0.8;
  819. }
  820. else if ( fireplace.IsBarrelWithHoles() )
  821. {
  822. steam_offset = 1.1;
  823. }
  824. else if ( fireplace.IsFireplaceIndoor() )
  825. {
  826. steam_offset = 0.45;
  827. }
  828. else if ( fireplace.IsIndoorOven() )
  829. {
  830. steam_offset = 0.9;
  831. }
  832. }
  833. }
  834. particle_pos[1] = particle_pos[1] + steam_offset;
  835. return particle_pos;
  836. }
  837. static vector GetRandomizedPosition(vector targetPos, float radius)
  838. {
  839. int angle = Math.RandomIntInclusive(1,360);
  840. float usedRadius = Math.RandomFloat01() * radius;
  841. vector randomPos = Vector(targetPos[0] + (Math.Cos(angle) * usedRadius), targetPos[1], targetPos[2] + (Math.Sin(angle) * usedRadius));
  842. return randomPos;
  843. }
  844. static vector GetRandomizedPositionVerified(vector startPos, vector targetPos, float radius, Object ignore = null)
  845. {
  846. vector ret = GetRandomizedPosition(targetPos,radius);
  847. RaycastRVParams params = new RaycastRVParams(startPos,ret,ignore);
  848. params.type = ObjIntersectIFire;
  849. array<ref RaycastRVResult> results = new array<ref RaycastRVResult>;
  850. array<Object> excluded = new array<Object>;
  851. if (DayZPhysics.RaycastRVProxy(params,results,excluded))
  852. {
  853. ret = results[0].pos;
  854. ret[1] = targetPos[1];
  855. }
  856. return ret;
  857. }
  858. static void DropAllItemsInInventoryInBounds(ItemBase ib, vector halfExtents)
  859. {
  860. if (!GetGame().IsServer())
  861. return;
  862. array<EntityAI> items = new array<EntityAI>;
  863. ib.GetInventory().EnumerateInventory(InventoryTraversalType.LEVELORDER, items);
  864. vector direction = ib.GetDirection();
  865. float dot = vector.Dot(direction, vector.Forward);
  866. float angle = Math.Acos(dot);
  867. if (direction[0] < 0)
  868. angle = -angle;
  869. float cos = Math.Cos(angle);
  870. float sin = Math.Sin(angle);
  871. EntityAI item;
  872. int count = items.Count();
  873. for ( int i = 0; i < count; ++i )
  874. {
  875. item = items.Get(i);
  876. if ( item )
  877. ib.GetInventory().DropEntityInBounds(InventoryMode.SERVER, ib, item, halfExtents, angle, cos, sin);
  878. }
  879. }
  880. static void ThrowAllItemsInInventory(notnull EntityAI parent, int flags)
  881. {
  882. vector position = parent.GetPosition();
  883. vector orientation = parent.GetOrientation();
  884. vector rotation_matrix[3];
  885. float direction[4];
  886. vector minmax[2];
  887. parent.GetCollisionBox(minmax);
  888. Math3D.YawPitchRollMatrix( orientation, rotation_matrix );
  889. Math3D.MatrixToQuat( rotation_matrix, direction );
  890. vector randomPos;
  891. for ( int i = 0; i < parent.GetInventory().AttachmentCount(); ++i )
  892. {
  893. randomPos = Vector(position[0] + Math.RandomFloat(minmax[0][0], minmax[1][0]),
  894. position[1] + Math.RandomFloat(minmax[0][1], minmax[1][1]),
  895. position[2] + Math.RandomFloat(minmax[0][2], minmax[1][2]));
  896. ThrowEntityFromInventory(parent.GetInventory().GetAttachmentFromIndex( i ), randomPos, direction, -GetVelocity(parent), ThrowEntityFlags.NONE);
  897. }
  898. for ( int j = 0; j < parent.GetInventory().GetCargo().GetItemCount(); ++j )
  899. {
  900. randomPos = Vector(position[0] + Math.RandomFloat(minmax[0][0], minmax[1][0]),
  901. position[1] + Math.RandomFloat(minmax[0][1], minmax[1][1]),
  902. position[2] + Math.RandomFloat(minmax[0][2], minmax[1][2]));
  903. ThrowEntityFromInventory(parent.GetInventory().GetCargo().GetItem( j ), randomPos, direction, -GetVelocity(parent), ThrowEntityFlags.NONE);
  904. }
  905. }
  906. static void ThrowEntityFromInventory(notnull EntityAI entity, vector position, float direction[4], vector force, int flags)
  907. {
  908. InventoryMode invMode = InventoryMode.SERVER;
  909. if ( !GetGame().IsMultiplayer() )
  910. invMode = InventoryMode.LOCAL;
  911. ItemBase entityIB;
  912. if (CastTo(entityIB, entity))
  913. {
  914. InventoryLocation dst = new InventoryLocation;
  915. dst.SetGroundEx(entity, position, direction);
  916. if ( (flags & ThrowEntityFlags.SPLIT) && entityIB.CanBeSplit() )
  917. {
  918. for (int l = 0; l < entityIB.GetQuantity(); ++l)
  919. {
  920. ItemBase new_item = ItemBase.Cast( GameInventory.LocationCreateEntity( dst, entityIB.GetType(), ECE_NONE, RF_DEFAULT ) );
  921. if ( new_item )
  922. {
  923. MiscGameplayFunctions.TransferItemProperties(entityIB, new_item);
  924. entityIB.AddQuantity( -1 );
  925. new_item.SetQuantity( 1 );
  926. new_item.ThrowPhysically(null, force, false);
  927. }
  928. }
  929. }
  930. else
  931. {
  932. float stackable = entityIB.GetTargetQuantityMax();
  933. if ( !(stackable == 0 || stackable >= entityIB.GetQuantity()) )
  934. {
  935. while (entityIB.GetQuantity() > stackable)
  936. {
  937. InventoryLocation spltDst = new InventoryLocation;
  938. position[1] = position[1] + 0.1;
  939. spltDst.SetGroundEx(entity, position, direction);
  940. ItemBase splitItem = entityIB.SplitIntoStackMaxToInventoryLocationEx( spltDst );
  941. splitItem.ThrowPhysically(null, force, false);
  942. }
  943. }
  944. InventoryLocation src = new InventoryLocation;
  945. entity.GetInventory().GetCurrentInventoryLocation(src);
  946. entity.GetInventory().TakeToDst(invMode, src, dst);
  947. entityIB.ThrowPhysically(null, force, false);
  948. }
  949. }
  950. else
  951. {
  952. entity.GetInventory().DropEntity(invMode, entity.GetHierarchyRoot(), entity);
  953. dBodyApplyImpulse(entity, force);
  954. }
  955. }
  956. static float GetCurrentItemHeatIsolation( ItemBase pItem )
  957. {
  958. float wetFactor;
  959. float healthFactor;
  960. float heatIsolation = pItem.GetHeatIsolation(); //! item heat isolation (from cfg)
  961. float itemHealthLabel = pItem.GetHealthLevel(); //! item health (state)
  962. float itemWetness = pItem.GetWet(); //! item wetness
  963. //! wet factor selection
  964. if ( itemWetness >= GameConstants.STATE_DRY && itemWetness < GameConstants.STATE_DAMP )
  965. {
  966. wetFactor = GameConstants.ENVIRO_ISOLATION_WETFACTOR_DRY;
  967. }
  968. else if ( itemWetness >= GameConstants.STATE_DAMP && itemWetness < GameConstants.STATE_WET )
  969. {
  970. wetFactor = GameConstants.ENVIRO_ISOLATION_WETFACTOR_DAMP;
  971. }
  972. else if ( itemWetness >= GameConstants.STATE_WET && itemWetness < GameConstants.STATE_SOAKING_WET )
  973. {
  974. wetFactor = GameConstants.ENVIRO_ISOLATION_WETFACTOR_WET;
  975. }
  976. else if ( itemWetness >= GameConstants.STATE_SOAKING_WET && itemWetness < GameConstants.STATE_DRENCHED )
  977. {
  978. wetFactor = GameConstants.ENVIRO_ISOLATION_WETFACTOR_SOAKED;
  979. }
  980. else if ( itemWetness >= GameConstants.STATE_DRENCHED )
  981. {
  982. return GameConstants.ENVIRO_ISOLATION_WETFACTOR_DRENCHED;
  983. }
  984. //! health factor selection
  985. switch (itemHealthLabel)
  986. {
  987. case GameConstants.STATE_PRISTINE:
  988. healthFactor = GameConstants.ENVIRO_ISOLATION_HEALTHFACTOR_PRISTINE;
  989. break;
  990. case GameConstants.STATE_WORN:
  991. healthFactor = GameConstants.ENVIRO_ISOLATION_HEALTHFACTOR_WORN;
  992. break;
  993. case GameConstants.STATE_DAMAGED:
  994. healthFactor = GameConstants.ENVIRO_ISOLATION_HEALTHFACTOR_DAMAGED;
  995. break;
  996. case GameConstants.STATE_BADLY_DAMAGED:
  997. healthFactor = GameConstants.ENVIRO_ISOLATION_HEALTHFACTOR_B_DAMAGED;
  998. break;
  999. case GameConstants.STATE_RUINED:
  1000. healthFactor = GameConstants.ENVIRO_ISOLATION_HEALTHFACTOR_RUINED;
  1001. break;
  1002. }
  1003. //! apply factors
  1004. heatIsolation *= healthFactor;
  1005. heatIsolation *= wetFactor;
  1006. return heatIsolation;
  1007. }
  1008. static void FilterObstructingObjects(array<Object> potentiallyObstructingObjects, out array<Object> obstructingObjects)
  1009. {
  1010. if (!obstructingObjects)
  1011. obstructingObjects = new array<Object>;
  1012. for ( int i = 0; i < potentiallyObstructingObjects.Count(); ++i )
  1013. {
  1014. Object obj = potentiallyObstructingObjects[i];
  1015. if ( obj && ( obj.CanObstruct() || obj.CanProxyObstruct() ) )
  1016. obstructingObjects.Insert(obj);
  1017. }
  1018. }
  1019. static bool CanIgnoreDistanceCheck(Object obj)
  1020. {
  1021. return obj.IsTransport() || obj.CanUseConstruction();
  1022. }
  1023. //! group objects that are close to each other together
  1024. 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)
  1025. {
  1026. array<Object> vicinityObjects= new array<Object>;
  1027. vicinityObjects.Copy(objects);
  1028. int i = 0;
  1029. int j = 0;
  1030. int k = 0;
  1031. int mCount = vicinityObjects.Count();
  1032. if (!filteredObjects)
  1033. filteredObjects = new array<Object>;
  1034. // Remove objects that are too far from the player anyways
  1035. if ( doDistanceCheck )
  1036. {
  1037. for ( i = vicinityObjects.Count() - 1; i >= 0; --i )
  1038. {
  1039. Object obj = vicinityObjects[i];
  1040. if ( obj && !CanIgnoreDistanceCheck( obj ) && vector.DistanceSq(origin, obj.GetPosition()) > maxDist * maxDist )
  1041. vicinityObjects.Remove(i);
  1042. }
  1043. }
  1044. // Sort obstructingObjects to have the furthest one first
  1045. array<Object> sortedObstructingObjects = new array<Object>;
  1046. array<float> distanceHelper = new array<float>;
  1047. array<float> distanceHelperUnsorted = new array<float>;
  1048. float distance, dist1, dist2;
  1049. for ( i = 0; i < obstructingObjects.Count(); ++i )
  1050. {
  1051. distance = vector.DistanceSq(obstructingObjects[i].GetWorldPosition(), origin);
  1052. distanceHelper.Insert(distance);
  1053. }
  1054. distanceHelperUnsorted.Copy(distanceHelper);
  1055. distanceHelper.Sort();
  1056. for ( i = distanceHelper.Count() - 1; i >= 0; --i )
  1057. sortedObstructingObjects.Insert(obstructingObjects[distanceHelperUnsorted.Find(distanceHelper[i])]);
  1058. array<ref array<Object>> tempGroups = new array<ref array<Object>>;
  1059. array<ref array<Object>> objectGroups = new array<ref array<Object>>;
  1060. array<Object> group;
  1061. float cos = Math.Cos(90);
  1062. float sin = Math.Sin(90);
  1063. // Iterate through sorted obstructingObjects
  1064. for ( i = 0; i < sortedObstructingObjects.Count(); ++i )
  1065. {
  1066. Object obstrObj = sortedObstructingObjects[i];
  1067. vector worldPos = obstrObj.GetWorldPosition();
  1068. vector min, max;
  1069. vector minMax[2];
  1070. if ( obstrObj.GetCollisionBox(minMax) )
  1071. {
  1072. min = minMax[0];
  1073. max = minMax[1];
  1074. max = max * (obstrObj.GetOrientation() * range);
  1075. vector center, dx, dy, dz, half;
  1076. center = (min + max) * 0.5;
  1077. dz = obstrObj.GetOrientation();
  1078. dx = vector.RotateAroundZero(dz, vector.Up, cos, sin);
  1079. dy = vector.RotateAroundZero(dz, vector.Aside, cos, sin);
  1080. half = (max - min) * 0.5;
  1081. half = Vector(Math.AbsFloat(half[0]), Math.AbsFloat(half[1]), Math.AbsFloat(half[2]));
  1082. group = new array<Object>;
  1083. // Group objects within the above box
  1084. for ( j = vicinityObjects.Count() - 1; j >= 0; --j )
  1085. {
  1086. Object vicObj = vicinityObjects[j];
  1087. if ( vicObj )
  1088. {
  1089. vector d = vicObj.GetWorldPosition() - worldPos + center;
  1090. 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] )
  1091. {
  1092. group.Insert(vicObj);
  1093. vicinityObjects.Remove(j);
  1094. }
  1095. }
  1096. }
  1097. if ( group.Count() > 0 )
  1098. tempGroups.Insert(group);
  1099. }
  1100. }
  1101. // Go through the objects grouped by obstruction to split them by distance too
  1102. for ( i = 0; i < tempGroups.Count(); ++i )
  1103. SplitArrayIntoGroupsByDistance(tempGroups[i], objectGroups, distanceDelta);
  1104. // Split initial groups by distance
  1105. SplitArrayIntoGroupsByDistance(vicinityObjects, objectGroups, distanceDelta);
  1106. // Raycast accordingly to groups
  1107. IsObjectObstructedCache cache = new IsObjectObstructedCache(origin, mCount);
  1108. for ( i = 0; i < objectGroups.Count(); ++i )
  1109. {
  1110. array<Object> objectGroup = objectGroups[i];
  1111. Object sampleObject = objectGroup[0];
  1112. if ( !IsObjectObstructedEx(sampleObject, cache) )
  1113. filteredObjects.InsertAll(objectGroup);
  1114. cache.ClearCache();
  1115. }
  1116. }
  1117. static void SplitArrayIntoGroupsByDistance(array<Object> objects, array<ref array<Object>> objectGroups, float squaredDistanceDelta)
  1118. {
  1119. array<Object> group;
  1120. for ( int i = 0; i < objects.Count(); )
  1121. {
  1122. Object obj1 = objects[i];
  1123. if ( obj1 )
  1124. {
  1125. group = new array<Object>;
  1126. group.Insert(obj1);
  1127. for ( int j = objects.Count() - 1; j > i; --j )
  1128. {
  1129. Object obj2 = objects[j];
  1130. if ( obj1 && obj2 )
  1131. {
  1132. vector start = obj1.GetWorldPosition();
  1133. vector end = obj2.GetWorldPosition();
  1134. float distance = vector.DistanceSq(start, end);
  1135. if ( distance < squaredDistanceDelta )
  1136. {
  1137. group.Insert(obj2);
  1138. objects.Remove(j);
  1139. }
  1140. }
  1141. }
  1142. objectGroups.Insert(group);
  1143. objects.Remove(i);
  1144. continue;
  1145. }
  1146. ++i;
  1147. }
  1148. }
  1149. static bool IsObjectObstructed(Object object, bool doDistanceCheck = false, vector distanceCheckPos = "0 0 0", float maxDist = 0)
  1150. {
  1151. vector rayStart;
  1152. MiscGameplayFunctions.GetHeadBonePos(PlayerBase.Cast(GetGame().GetPlayer()), rayStart);
  1153. IsObjectObstructedCache cache = new IsObjectObstructedCache(rayStart, 1);
  1154. return IsObjectObstructedEx(object, cache, doDistanceCheck, distanceCheckPos, maxDist);
  1155. }
  1156. static bool IsObjectObstructedEx(Object object, IsObjectObstructedCache cache, bool doDistanceCheck = false, vector distanceCheckPos = "0 0 0", float maxDist = 0)
  1157. {
  1158. if (!object)
  1159. return true;
  1160. PlayerBase player = PlayerBase.Cast(g_Game.GetPlayer());
  1161. if (doDistanceCheck && vector.DistanceSq(player.GetPosition(), distanceCheckPos) > maxDist * maxDist)
  1162. return true;
  1163. cache.ObjectCenterPos = object.GetCenter();
  1164. return IsObjectObstructedFilterEx(object, cache, player);
  1165. }
  1166. static bool IsObjectObstructedProxy(Object object, IsObjectObstructedCache cache, PlayerBase player)
  1167. {
  1168. if (object.CanProxyObstruct())
  1169. {
  1170. RaycastRVParams rayInput = new RaycastRVParams(cache.RaycastStart, cache.ObjectCenterPos, player);
  1171. DayZPhysics.RaycastRVProxy(rayInput, cache.HitProxyObjects);
  1172. if (cache.HitProxyObjects)
  1173. {
  1174. if (cache.HitProxyObjects.Count() > 0)
  1175. {
  1176. if (cache.HitProxyObjects[0].hierLevel > 0)
  1177. {
  1178. // ignores attachments on player
  1179. if (!cache.HitProxyObjects[0].parent.IsMan())
  1180. {
  1181. if (cache.HitProxyObjects[0].parent)
  1182. {
  1183. EntityAI proxyParent = EntityAI.Cast(cache.HitProxyObjects[0].parent);
  1184. if (proxyParent.GetInventory() && proxyParent.GetInventory().GetCargo())
  1185. return true;
  1186. }
  1187. }
  1188. }
  1189. }
  1190. }
  1191. }
  1192. return false;
  1193. }
  1194. static bool IsObjectObstructedFilter(Object object, IsObjectObstructedCache cache, PlayerBase player)
  1195. {
  1196. for ( int m = 0; m < cache.HitObjects.Count(); m++ )
  1197. {
  1198. Object hit_object = cache.HitObjects.Get(m);
  1199. if ( hit_object.CanObstruct() )
  1200. return true;
  1201. //4.3. ignore item if items are big and heavy >= OBJECT_OBSTRUCTION_WEIGHT
  1202. //EntityAI eai;
  1203. //if ( Class.CastTo( eai, hit_object ) )
  1204. //{
  1205. // if ( eai.GetWeight() >= OBJECT_OBSTRUCTION_WEIGHT )
  1206. // {
  1207. // if ( eai != filtered_object && eai.GetHierarchyRoot() != filtered_object )
  1208. // {
  1209. // //Print("!!!!!obstacle vaha: " + hit_object);
  1210. // is_obstructed = true;
  1211. // }
  1212. // }
  1213. //}
  1214. }
  1215. return false;
  1216. }
  1217. //! groups 'RaycastRVProxy' and 'RaycastRV' approaches into one method, allowes for comprehensive geometry override, if desired
  1218. static bool IsObjectObstructedFilterEx(Object object, IsObjectObstructedCache cache, PlayerBase player, int geometryTypeOverride = -1)
  1219. {
  1220. //first proxy geometries
  1221. RaycastRVParams rayInput = new RaycastRVParams(cache.RaycastStart, cache.ObjectCenterPos, player);
  1222. rayInput.flags = CollisionFlags.ALLOBJECTS;
  1223. if (geometryTypeOverride != -1)
  1224. rayInput.type = geometryTypeOverride; //default 'ObjIntersectView'
  1225. DayZPhysics.RaycastRVProxy(rayInput, cache.HitProxyObjects);
  1226. int count;
  1227. int i;
  1228. if (cache.HitProxyObjects)
  1229. {
  1230. count = cache.HitProxyObjects.Count();
  1231. Object parent;
  1232. for (i = 0; i < count; i++)
  1233. {
  1234. if (cache.HitProxyObjects[i].hierLevel > 0) //parent has to exist, skipping nullcheck
  1235. {
  1236. parent = cache.HitProxyObjects[i].parent;
  1237. if (parent && !parent.IsMan() && parent.CanProxyObstruct())
  1238. {
  1239. if (parent != object || (parent == object && object.CanProxyObstructSelf()))
  1240. return true;
  1241. }
  1242. }
  1243. }
  1244. }
  1245. //second, regular raycast
  1246. int geometry = ObjIntersectFire; //default for the RV raycast
  1247. if (geometryTypeOverride != -1)
  1248. geometry = geometryTypeOverride;
  1249. DayZPhysics.RaycastRV(cache.RaycastStart, cache.ObjectCenterPos, cache.ObjectContactPos, cache.ObjectContactDir, cache.ContactComponent, cache.HitObjects, object, GetGame().GetPlayer(), false, false, geometry, 0.0, CollisionFlags.ALLOBJECTS);
  1250. count = cache.HitObjects.Count();
  1251. for (i = 0; i < count; i++ )
  1252. {
  1253. if (cache.HitObjects[i].CanObstruct())
  1254. return true;
  1255. }
  1256. return false;
  1257. }
  1258. //Inflict damage to item based on environmental temperature and surface type
  1259. static void DealEvinronmentAdjustedDmg(ItemBase item, PlayerBase player, float baseDamage)
  1260. {
  1261. string surfaceType;
  1262. int liquidType;
  1263. float adjustedDamage;
  1264. GetGame().SurfaceUnderObject(player, surfaceType, liquidType);
  1265. float modifierSurface = Surface.GetParamFloat(surfaceType, "toolDamage"); // toolDamage
  1266. if (modifierSurface == 0)
  1267. modifierSurface = 1;
  1268. if (player.GetInColdArea())
  1269. adjustedDamage = baseDamage * (modifierSurface + GetGame().GetMission().GetWorldData().GetColdAreaToolDamageModifier();
  1270. else
  1271. adjustedDamage = baseDamage * modifierSurface;
  1272. DealAbsoluteDmg(item, adjustedDamage);
  1273. }
  1274. //Inflict absolute damage to item (used on tools when completing actions)
  1275. static void DealAbsoluteDmg(ItemBase item, float dmg)
  1276. {
  1277. item.DecreaseHealth(dmg, false);
  1278. }
  1279. //Function used to normailze values, enter the used value and the max value (max will become 1)
  1280. static float Normalize(int val, int maxVal)
  1281. {
  1282. if (maxVal == 0)
  1283. {
  1284. Debug.LogError("Division by 0 is not allowed");
  1285. return 0;
  1286. }
  1287. return val / maxVal;
  1288. }
  1289. static float Bobbing(float period, float amplitude, float elapsedTime)
  1290. {
  1291. //Prevent division by 0
  1292. if ( period == 0 )
  1293. period = 1;
  1294. elapsedTime /= period;
  1295. float cycle;
  1296. cycle += elapsedTime;
  1297. cycle = FModulus(cycle, 360);
  1298. cycle = Math.Sin(cycle) * amplitude;
  1299. return cycle;
  1300. }
  1301. // DEPRECATED, use Math.ModFloat directly instead
  1302. static float FModulus(float x, float y)
  1303. {
  1304. return Math.ModFloat(x, y);
  1305. }
  1306. static void RemoveSplint( PlayerBase player )
  1307. {
  1308. EntityAI entity = player.GetInventory().CreateInInventory("Splint");
  1309. if (!entity)
  1310. entity = player.SpawnEntityOnGroundOnCursorDir("Splint", 0.5);
  1311. EntityAI attachment;
  1312. ItemBase new_item = ItemBase.Cast(entity);
  1313. Class.CastTo(attachment, player.GetItemOnSlot("Splint_Right"));
  1314. if ( attachment && attachment.GetType() == "Splint_Applied" )
  1315. {
  1316. if (new_item)
  1317. {
  1318. MiscGameplayFunctions.TransferItemProperties(attachment,new_item);
  1319. if (GetGame().IsServer())
  1320. {
  1321. //Lower health level of splint after use
  1322. if (new_item.GetHealthLevel() < 4)
  1323. {
  1324. int newDmgLevel = new_item.GetHealthLevel() + 1;
  1325. float max = new_item.GetMaxHealth("","");
  1326. switch ( newDmgLevel )
  1327. {
  1328. case GameConstants.STATE_BADLY_DAMAGED:
  1329. new_item.SetHealth( "", "", max * GameConstants.DAMAGE_BADLY_DAMAGED_VALUE );
  1330. break;
  1331. case GameConstants.STATE_DAMAGED:
  1332. new_item.SetHealth( "", "", max * GameConstants.DAMAGE_DAMAGED_VALUE );
  1333. break;
  1334. case GameConstants.STATE_WORN:
  1335. new_item.SetHealth( "", "", max * GameConstants.DAMAGE_WORN_VALUE );
  1336. break;
  1337. case GameConstants.STATE_RUINED:
  1338. new_item.SetHealth( "", "", max * GameConstants.DAMAGE_RUINED_VALUE );
  1339. break;
  1340. default:
  1341. break;
  1342. }
  1343. }
  1344. }
  1345. }
  1346. attachment.Delete();
  1347. }
  1348. }
  1349. //! checks if we should teleport the player to a safe location and if so, performs the teleportation
  1350. static void TeleportCheck(notnull PlayerBase player, notnull array<ref array<float>> safe_positions)
  1351. {
  1352. if( player.GetSimulationTimeStamp() < 20 && !player.IsPersistentFlag(PersistentFlag.AREA_PRESENCE) )
  1353. {
  1354. //simulation time is bellow a threshold, which means the player has recently connected,
  1355. //the player does not have the AREA_PRESENCE flag set, which means they were not inside the area when they disconnected,
  1356. //that means they just spawned into a contaminated area, lets move them somewhere safe
  1357. vector player_pos = player.GetPosition();
  1358. vector closest_safe_pos = MiscGameplayFunctions.GetClosestSafePos(player_pos, safe_positions);
  1359. if (player_pos!=closest_safe_pos)
  1360. {
  1361. closest_safe_pos[1] = GetGame().SurfaceY(closest_safe_pos[0], closest_safe_pos[2]);
  1362. player.SetPosition( closest_safe_pos );//...so lets teleport them somewhere safe
  1363. //DeveloperTeleport.SetPlayerPosition(player, closest_safe_pos);
  1364. GetGame().RPCSingleParam(player, ERPCs.RPC_WARNING_TELEPORT, null, true, player.GetIdentity());
  1365. PluginAdminLog adminLog = PluginAdminLog.Cast(GetPlugin(PluginAdminLog));
  1366. if (adminLog)
  1367. adminLog.PlayerTeleportedLog(player,player_pos,closest_safe_pos,"Unwillingly spawning in contaminated area.");
  1368. }
  1369. player.SetPersistentFlag(PersistentFlag.AREA_PRESENCE, false);
  1370. }
  1371. }
  1372. static vector GetClosestSafePos(vector to_pos, notnull array<ref array<float>> positions)
  1373. {
  1374. vector closest_pos = to_pos;
  1375. float smallest_dist = float.MAX;
  1376. foreach( array<float> pos:positions)
  1377. {
  1378. vector vpos = "0 0 0";
  1379. vpos[0] = pos[0];
  1380. vpos[2] = pos[1];
  1381. to_pos[1] = 0;
  1382. float dist = vector.DistanceSq(to_pos, vpos);//2d dist sq
  1383. if ( dist < smallest_dist)
  1384. {
  1385. smallest_dist = dist;
  1386. closest_pos = vpos;
  1387. }
  1388. }
  1389. return closest_pos;
  1390. }
  1391. //! 'stupider' teleport method, does not touch flag management. Applies Y from the position as well!
  1392. static bool TeleportPlayerToSafeLocation3D(notnull PlayerBase player, vector safePos)
  1393. {
  1394. vector playerPos = player.GetPosition();
  1395. if (playerPos != safePos)
  1396. {
  1397. player.SetPosition(safePos);
  1398. GetGame().RPCSingleParam(player, ERPCs.RPC_WARNING_TELEPORT, null, true, player.GetIdentity());
  1399. return true;
  1400. }
  1401. return false;
  1402. }
  1403. static void GenerateAINoiseAtPosition(vector position, float lifeTime, NoiseParams noiseParams)
  1404. {
  1405. if (GetGame().IsServer())
  1406. {
  1407. NoiseSystem noise = GetGame().GetNoiseSystem();
  1408. if (noise)
  1409. {
  1410. noise.AddNoiseTarget(position, lifeTime, noiseParams, NoiseAIEvaluate.GetNoiseReduction(GetGame().GetWeather()));
  1411. }
  1412. }
  1413. }
  1414. static float GetMinValue(array<float> pArray)
  1415. {
  1416. float minValue = 0.0;
  1417. for (int i = 0; i < pArray.Count(); i++)
  1418. {
  1419. if (minValue == 0 || pArray.Get(i) < minValue)
  1420. {
  1421. minValue = pArray.Get(i);
  1422. }
  1423. }
  1424. return minValue;
  1425. }
  1426. static float GetMaxValue(array<float> pArray)
  1427. {
  1428. float maxValue = 0.0;
  1429. for (int i = 0; i < pArray.Count(); i++)
  1430. {
  1431. if (maxValue == 0 || pArray.Get(i) > maxValue)
  1432. {
  1433. maxValue = pArray.Get(i);
  1434. }
  1435. }
  1436. return maxValue;
  1437. }
  1438. static string GetItemDisplayName(string type)
  1439. {
  1440. return GetGame().ConfigGetTextOut("CfgVehicles " + type + " displayName");
  1441. }
  1442. static bool IsComponentInSelection(array<Selection> pSelection, string pCompName)
  1443. {
  1444. if (pSelection.Count() == 0 || pCompName.Length() == 0)
  1445. {
  1446. return false;
  1447. }
  1448. for (int i = 0; i < pSelection.Count(); ++i)
  1449. {
  1450. pCompName.ToLower();
  1451. if (pSelection[i] && pSelection[i].GetName() == pCompName)
  1452. {
  1453. return true;
  1454. }
  1455. }
  1456. return false;
  1457. }
  1458. static int GetComponentIndex(array<Selection> pSelection, string pCompName)
  1459. {
  1460. if (!MiscGameplayFunctions.IsComponentInSelection(pSelection, pCompName))
  1461. {
  1462. return INDEX_NOT_FOUND;
  1463. }
  1464. for (int i = 0; i < pSelection.Count(); ++i)
  1465. {
  1466. pCompName.ToLower();
  1467. if (pSelection[i] && pSelection[i].GetName() == pCompName)
  1468. {
  1469. return i;
  1470. }
  1471. }
  1472. return INDEX_NOT_FOUND;
  1473. }
  1474. static void RemoveAllAttachedChildrenByTypename(notnull EntityAI parent, array<typename> listOfTypenames)
  1475. {
  1476. if (listOfTypenames.Count() > 0)
  1477. {
  1478. Object child = Object.Cast(parent.GetChildren());
  1479. while (child)
  1480. {
  1481. Object childToRemove = child;
  1482. child = Object.Cast(child.GetSibling());
  1483. if (childToRemove.IsAnyInherited(listOfTypenames))
  1484. {
  1485. vector pos = childToRemove.GetPosition();
  1486. parent.RemoveChild(childToRemove, false);
  1487. vector m4[4];
  1488. Math3D.MatrixIdentity4(m4);
  1489. m4[3] = pos;
  1490. childToRemove.SetTransform(m4);
  1491. childToRemove.PlaceOnSurface();
  1492. }
  1493. }
  1494. }
  1495. }
  1496. static void DeleteAttachedChildrenByTypename(notnull EntityAI parent, array<typename> listOfTypenames)
  1497. {
  1498. if (listOfTypenames.Count() > 0)
  1499. {
  1500. Object child = Object.Cast(parent.GetChildren());
  1501. while (child)
  1502. {
  1503. Object childToRemove = child;
  1504. child = Object.Cast(child.GetSibling());
  1505. if (childToRemove.IsAnyInherited(listOfTypenames))
  1506. {
  1507. parent.RemoveChild(childToRemove, false);
  1508. childToRemove.Delete();
  1509. }
  1510. }
  1511. }
  1512. }
  1513. //! Fills the provided array with all children entities in hierarchy of this entity
  1514. static void GetAttachedChildren(IEntity parent, array<IEntity> outputObjects)
  1515. {
  1516. IEntity child = parent.GetChildren();
  1517. while (child)
  1518. {
  1519. outputObjects.Insert(child);
  1520. child = child.GetSibling();
  1521. }
  1522. }
  1523. static void SoakItemInsideParentContainingLiquidAboveThreshold(notnull ItemBase item, notnull ItemBase parent, float liquidQuantityThresholdPercentage = 0.05)
  1524. {
  1525. if (g_Game.IsServer())
  1526. {
  1527. if (parent.GetLiquidType() != 0 && parent.GetQuantityNormalized() > liquidQuantityThresholdPercentage)
  1528. item.SetWetMax();
  1529. }
  1530. }
  1531. static float GetCombinedSnowfallWindValue()
  1532. {
  1533. float windMax;
  1534. g_Game.GetWeather().GetWindMagnitude().GetLimits(null, windMax);
  1535. float snowfall = g_Game.GetWeather().GetSnowfall().GetActual();
  1536. float value = snowfall + g_Game.GetWeather().GetWindMagnitude().GetActual() / windMax;
  1537. return value;
  1538. }
  1539. }
  1540. class DestroyItemInCorpsesHandsAndCreateNewOnGndLambda : ReplaceAndDestroyLambda
  1541. {
  1542. // @NOTE m_Player == target player - i.e. restrained one
  1543. void DestroyItemInCorpsesHandsAndCreateNewOnGndLambda(EntityAI old_item, string new_item_type, PlayerBase player, bool destroy = false)
  1544. {
  1545. InventoryLocation gnd = new InventoryLocation;
  1546. vector mtx[4];
  1547. if (old_item)
  1548. old_item.GetTransform(mtx);
  1549. else
  1550. player.GetTransform(mtx);
  1551. gnd.SetGround(NULL, mtx);
  1552. OverrideNewLocation(gnd);
  1553. }
  1554. protected override void RemoveOldItemFromLocation()
  1555. {
  1556. super.RemoveOldItemFromLocation();
  1557. m_Player.GetHumanInventory().OnEntityInHandsDestroyed(m_OldLocation);
  1558. }
  1559. }
  1560. // This was created since IsObjectObstructed is often called multiple times in one frame
  1561. // 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
  1562. class IsObjectObstructedCache // Pretending this is a struct
  1563. {
  1564. // Outside data
  1565. vector RaycastStart = "0 0 0";
  1566. int TotalObjects = 0;
  1567. // Inside data
  1568. vector ObjectCenterPos = "0 0 0";
  1569. vector ObjectContactPos = "0 0 0";
  1570. vector ObjectContactDir = "0 0 0";
  1571. int ContactComponent = -1;
  1572. ref array<ref RaycastRVResult> HitProxyObjects = new array<ref RaycastRVResult>;
  1573. ref set<Object> HitObjects = new set<Object>;
  1574. void IsObjectObstructedCache(vector rayCastStart, int totalObjects)
  1575. {
  1576. RaycastStart = rayCastStart;
  1577. TotalObjects = totalObjects;
  1578. }
  1579. // Only inside data
  1580. void ClearCache()
  1581. {
  1582. ObjectCenterPos = "0 0 0";
  1583. ObjectContactPos = "0 0 0";
  1584. ObjectContactDir = "0 0 0";
  1585. ContactComponent = -1;
  1586. HitProxyObjects.Clear();
  1587. HitObjects.Clear();
  1588. }
  1589. }