Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- sreV product dayz ugc version 154 prefix JM\CF\Scripts 1_Core\CommunityFramework\CF_Byte.c £»dë 1_Core\CommunityFramework\CF_Cast.c ÖNb¿ 1_Core\CommunityFramework\CF_Encoding.c £»d 1_Core\CommunityFramework\CF_Operations.c ÖNb{ 1_Core\CommunityFramework\CF_PackedByte.c ÖNb± 1_Core\CommunityFramework\CF_SeekOrigin.c ÖNb3 1_Core\CommunityFramework\CF_String.c ÖNbâ 1_Core\CommunityFramework\CF_Uint.c ÖNb² 1_Core\CommunityFramework\EventArgs\CF_EventArgs.c ÖNbš 1_Core\CommunityFramework\EventArgs\CF_EventTimeArgs.c ÖNbw 1_Core\CommunityFramework\EventArgs\CF_EventUpdateArgs.c ÖNb– 1_Core\CommunityFramework\Files\CF_Directory.c ÖNbú 1_Core\CommunityFramework\Files\CF_File.c ÖNb 1_Core\CommunityFramework\Files\CF_Path.c £»d 1_Core\CommunityFramework\IO\CF_Base16Stream.c ÖNbæ 1_Core\CommunityFramework\IO\CF_Base64Stream.c ÖNbª 1_Core\CommunityFramework\IO\CF_BinaryReader.c 'åc 1_Core\CommunityFramework\IO\CF_BinaryWriter.c £»dŒ
- 1_Core\CommunityFramework\IO\CF_FileStream.c ÖNb‰
- 1_Core\CommunityFramework\IO\CF_IO.c 'åcÀ 1_Core\CommunityFramework\IO\CF_SerializerStream.c ÖNbË 1_Core\CommunityFramework\IO\CF_Stream.c ÖNb¯ 1_Core\CommunityFramework\IO\CF_StringStream.c £»dþ 1_Core\CommunityFramework\IO\CF_TextReader.c ÖNb- 1_Core\CommunityFramework\IO\CF_TextWriter.c £»d• 1_Core\CommunityFramework\Logging\CF_Log.c 'åc 1_Core\CommunityFramework\Logging\CF_LogLevel.c ÖNb_ 1_Core\CommunityFramework\Logging\CF_Trace.c 'åc- 1_Core\CommunityFramework\Module\CF_ModuleCore.c ÖNbf 1_Core\CommunityFramework\Module\CF_ModuleCoreEvent.c ÖNbÛ 1_Core\CommunityFramework\Module\CF_ModuleCoreManager.c .ÖNbØ 1_Core\CommunityFramework\Module\CF_Modules.c ÖNb= 1_Core\CommunityFramework\Module\CF_RegisterModule.c ÖNbw 1_Core\CommunityFramework\proto\EnMath.c ÖNbø 1_Core\CommunityFramework\TypeConverter\CF_RegisterTypeConverter.c ÖNb 1_Core\CommunityFramework\TypeConverter\CF_TypeConverter.c .ÖNb
- 1_Core\CommunityFramework\TypeConverter\CF_TypeConverterBase.c ÖNb1
- 1_Core\CommunityFramework\TypeConverter\CF_TypeConverterT.c ÖNbç 2_GameLib\CommunityFramework\Cryptography\CF_SHA256.c ÖNb 2_GameLib\CommunityFramework\EventHandler\Attributes\CF_EventSubscriber.c ¥DÒd¤ 2_GameLib\CommunityFramework\EventHandler\Attributes\CF_MultiEventSubscriber.c £»d 2_GameLib\CommunityFramework\EventHandler\CF_EventHandler.c ¼GÒd¼ 2_GameLib\CommunityFramework\LifecycleEvents\CF_LifecycleEvents.c Âp¿d 3_Game\CommunityFramework\Collections\Stack.c ÖNb) 3_Game\CommunityFramework\CommunityFramework.c .ÖNb¬ 3_Game\CommunityFramework\Config\ConfigArray.c ÖNb 3_Game\CommunityFramework\Config\ConfigArrayParam.c ÖNb¦ 3_Game\CommunityFramework\Config\ConfigArrayParamArray.c 'åc‹ 3_Game\CommunityFramework\Config\ConfigArrayParamFloat.c ÖNb= 3_Game\CommunityFramework\Config\ConfigArrayParamInt.c ÖNb- 3_Game\CommunityFramework\Config\ConfigArrayParamLong.c ÖNb2 3_Game\CommunityFramework\Config\ConfigArrayParamText.c ÖNb; 3_Game\CommunityFramework\Config\ConfigClass.c ÖNbv 3_Game\CommunityFramework\Config\ConfigEntry.c ÖNb¾ 3_Game\CommunityFramework\Config\ConfigFile.c ÖNbO 3_Game\CommunityFramework\Config\ConfigReader.c 'åc¨ 3_Game\CommunityFramework\Config\ConfigValue.c ÖNb‘ 3_Game\CommunityFramework\Config\ConfigValueFloat.c ÖNb- 3_Game\CommunityFramework\Config\ConfigValueInt.c ÖNb 3_Game\CommunityFramework\Config\ConfigValueLong.c ÖNb" 3_Game\CommunityFramework\Config\ConfigValueText.c ÖNb+ 3_Game\CommunityFramework\Config\ConfigValueTypes.c ÖNbW 3_Game\CommunityFramework\Credits\CreditsLoader.c 3ɾd 3_Game\CommunityFramework\EventArgs\CF_EventChatArgs.c ÖNb" 3_Game\CommunityFramework\EventArgs\CF_EventLoginArgs.c ÖNb² 3_Game\CommunityFramework\EventArgs\CF_EventRPCArgs.c ÖNbw 3_Game\CommunityFramework\ExpressionVM\CF_Expression.c £»d 3_Game\CommunityFramework\ExpressionVM\CF_ExpressionCompileToken.c ÖNbZ 3_Game\CommunityFramework\ExpressionVM\CF_ExpressionFunction.c £»dc 3_Game\CommunityFramework\ExpressionVM\CF_ExpressionInstruction.c ÖNbÏ 3_Game\CommunityFramework\ExpressionVM\CF_ExpressionStackDebug.c ÖNbg 3_Game\CommunityFramework\ExpressionVM\CF_ExpressionTests.c ÖNbK 3_Game\CommunityFramework\ExpressionVM\CF_ExpressionVM.c £»d 3_Game\CommunityFramework\ExpressionVM\CF_MathExpression.c ÖNbÖ 3_Game\CommunityFramework\ExpressionVM\CF_SQFExpression.c ÖNbx 3_Game\CommunityFramework\ExpressionVM\DayZGame.c ÖNb» 3_Game\CommunityFramework\Game\DayZGame.c “(åcÁ 3_Game\CommunityFramework\InputBindings\CF_InputBinding.c ÖNbD 3_Game\CommunityFramework\InputBindings\CF_InputBindings.c .ÖNb¯
- 3_Game\CommunityFramework\LifecycleEvents\DayZGame.c ×EÒdˆ 3_Game\CommunityFramework\Mods\ModInput.c ÖNbM 3_Game\CommunityFramework\Mods\ModLoader.c 'åc¨ 3_Game\CommunityFramework\Mods\ModStructure.c ÖNb 3_Game\CommunityFramework\ModStorage\CF_ModStorage.c .ÖNb’ 3_Game\CommunityFramework\ModStorage\CF_ModStorageMap.c ÖNbq 3_Game\CommunityFramework\ModStorage\CF_ModStorageModule.c .ÖNb
- 3_Game\CommunityFramework\ModStorage\CF_ModStorageTest.c ÖNbM 3_Game\CommunityFramework\Module\CF_ModuleConstructor.c £»dÏ 3_Game\CommunityFramework\Module\CF_ModuleGame.c .ÖNbF 3_Game\CommunityFramework\Module\CF_ModuleGameEvent.c .ÖNb' 3_Game\CommunityFramework\Module\CF_ModuleGameManager.c .ÖNb 3_Game\CommunityFramework\Module\Deprecated\JMModuleManagerBase.c £»d
- 3_Game\CommunityFramework\Network\CF_NetworkedVariables.c ÖNb 3_Game\CommunityFramework\Network\CF_NetworkVariable.c ÖNb 3_Game\CommunityFramework\Notification\NotificationRuntimeData.c ÖNbý 3_Game\CommunityFramework\Notification\NotificationSystem.c £»d` 3_Game\CommunityFramework\ObjectManager\ObjectManager.c 'åcÊ. 3_Game\CommunityFramework\RPC\RPCManager.c £»dw 3_Game\CommunityFramework\TypeConverter\CF_TypeConverterConstructor.c £»d 3_Game\CommunityFramework\TypeConverter\Converters\CF_TypeConverterBool.c ÖNbÒ 3_Game\CommunityFramework\TypeConverter\Converters\CF_TypeConverterClass.c ÖNb 3_Game\CommunityFramework\TypeConverter\Converters\CF_TypeConverterDate.c ÖNbF 3_Game\CommunityFramework\TypeConverter\Converters\CF_TypeConverterExpression.c ÖNbõ 3_Game\CommunityFramework\TypeConverter\Converters\CF_TypeConverterFile.c ÖNb 3_Game\CommunityFramework\TypeConverter\Converters\CF_TypeConverterFloat.c ÖNbÎ 3_Game\CommunityFramework\TypeConverter\Converters\CF_TypeConverterInt.c ÖNbÀ 3_Game\CommunityFramework\TypeConverter\Converters\CF_TypeConverterLocaliser.c ÖNbñ 3_Game\CommunityFramework\TypeConverter\Converters\CF_TypeConverterManaged.c ÖNbó 3_Game\CommunityFramework\TypeConverter\Converters\CF_TypeConverterString.c ÖNb 3_Game\CommunityFramework\TypeConverter\Converters\CF_TypeConverterVector.c ÖNbp 3_Game\CommunityFramework\Utils\CF_Date.c £»d½. 3_Game\CommunityFramework\Utils\CF_Localiser.c ÖNbY 3_Game\CommunityFramework\XML\CF_XML.c ÖNb³ 3_Game\CommunityFramework\XML\CF_XML_Attribute.c ÖNbñ 3_Game\CommunityFramework\XML\CF_XML_Callback.c ÖNbÔ 3_Game\CommunityFramework\XML\CF_XML_Document.c ÖNbd 3_Game\CommunityFramework\XML\CF_XML_Element.c 'åc´ 3_Game\CommunityFramework\XML\CF_XML_Reader.c £»dÍ 3_Game\CommunityFramework\XML\CF_XML_Tag.c 'åc* 4_World\CommunityFramework\Classes\JMAnimRegister.c ÖNb 4_World\CommunityFramework\Entities\AdvancedCommunication.c .ÖNb1 4_World\CommunityFramework\Entities\AnimalBase.c .ÖNb 4_World\CommunityFramework\Entities\BuildingBase.c .ÖNb 4_World\CommunityFramework\Entities\CarScript.c .ÖNb 4_World\CommunityFramework\Entities\DayZPlayerImplement.c .ÖNb- 4_World\CommunityFramework\Entities\HelicopterScript.c .ÖNb' 4_World\CommunityFramework\Entities\ItemBase.c .ÖNbÜ 4_World\CommunityFramework\Entities\ManBase\DayZPlayerCameras.c ÖNb˜ 4_World\CommunityFramework\Entities\ZombieBase.c .ÖNb 4_World\CommunityFramework\EventArgs\CF_EventPlayerArgs.c ÖNbJ 4_World\CommunityFramework\ModStorage\CF_ModStorageBase.c ÖNb¤ 4_World\CommunityFramework\ModStorage\CF_ModStorageObject.c 'åcƒ 4_World\CommunityFramework\ModStorage\modstorage_prepare.c .ÖNbÅ 4_World\CommunityFramework\Module\CF_ModuleWorld.c ÖNb´ 4_World\CommunityFramework\Module\CF_ModuleWorldEvent.c ÖNbÛ 4_World\CommunityFramework\Module\CF_ModuleWorldManager.c .ÖNbþ 4_World\CommunityFramework\Module\Deprecated\JMModuleBase.c £»d§ 4_World\CommunityFramework\Module\Deprecated\JMModuleBinding.c ÖNb 4_World\CommunityFramework\Module\Deprecated\JMModuleConstructorBase.c ÖNbŒ 4_World\CommunityFramework\Module\Deprecated\JMModuleManager.c £»d 4_World\CommunityFramework\Surfaces\CF_Surface.c ¤»d˜ 4_World\CommunityFramework\Surfaces\CF_VehicleSurface.c ¤»dá 4_World\CommunityFramework\Weapons\CF_WeaponStableState.c .ÖNbP 4_World\CommunityFramework\Weapons\Weapon_Base.c .ÖNbˆ 4_World\CommunityFramework\Weapons\WeaponFSM.c .ÖNb4 4_World\CommunityFramework\Weapons\WeaponStableState.c ÖNbà 5_Mission\CommunityFramework\GUI\Keybindings\KeybindingElement.c ÖNbÍ 5_Mission\CommunityFramework\GUI\Keybindings\KeybindingsGroup.c ÖNb‹ 5_Mission\CommunityFramework\LifecycleEvents\MissionBase.c kHÒd— 5_Mission\CommunityFramework\Mission\MissionBase.c ÖNb 5_Mission\CommunityFramework\Mission\MissionGameplay.c .ÖNb 5_Mission\CommunityFramework\Mission\MissionServer.c s;Þbh 5_Mission\CommunityFramework\Module\JMModuleConstructor.c ÖNbz config.bin òHÒd^ Editor\Plugins\CommunityFramework\BuildMod.c ÖNbh Editor\Plugins\CommunityFramework\DayZProjectManager.c ÖNbÄ Editor\Plugins\CommunityFramework\LaunchClient.c ÖNb, Editor\Plugins\CommunityFramework\LaunchLocalMP.c ÖNbR Editor\Plugins\CommunityFramework\LaunchOffline.c ÖNb? Editor\Plugins\CommunityFramework\LaunchServer.c ÖNb, Editor\Plugins\CommunityFramework\OpenLogs.c ÖNb Editor\Plugins\CommunityFramework\PluginErrorMessage.c ÖNbÓ /*
- Byte Type Definition
- -- This is a byte datatype definition for EnScript
- Author: Lystic, Jacob_Mango
- When working with bytes. It is necessary to use 'CF_Byte::Clamp()' to ensure the value remains 8 bit when modifying.
- */
- typedef int CF_Byte;
- class CF_Byte : CF_Uint
- {
- CF_Byte Clamp()
- {
- CF_Byte oldByte = value;
- value = value & 255;
- return value;
- }
- void Set(int index, int v)
- {
- // set and clamp
- value = v & 255;
- }
- int Get(int index)
- {
- return value;
- }
- static CF_Byte Set(int value)
- {
- // set and clamp
- CF_Byte byte = value & 255;
- return byte;
- }
- static CF_Byte Set(string char)
- {
- CF_Byte byte = char.Get(0).ToAscii() & 255;
- return byte;
- }
- string ToHex()
- {
- int ascii = value & 255;
- int n0 = Math.Floor(ascii / 16);
- int n1 = ascii % 16;
- return CF_Encoding.BASE_16[n0] + CF_Encoding.BASE_16[n1];
- }
- override CF_Uint XOR(CF_Uint y)
- {
- CF_Byte b = super.XOR(y) & 255;
- return b;
- }
- };
- class CF_Cast<Class U, Class V>
- {
- static V Reinterpret(U src)
- {
- U src_arr[1];
- src_arr[0] = src;
- V dst_arr[1];
- copyarray(dst_arr, src_arr);
- return dst_arr[0];
- }
- };
- class CF_Encoding
- {
- static const string BASE_16[16] = {
- "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "A", "B", "C", "D", "E", "F"
- };
- static const string BASE_64[64] = {
- "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P",
- "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z", "a", "b", "c", "d", "e", "f",
- "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v",
- "w", "x", "y", "z", "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "+", "/",
- };
- static int Find(string[] data, int count, string match)
- {
- for (int i = 0; i < count; i++)
- {
- if (data[i] == match) return i;
- }
- return -1;
- }
- static string FindGet(string[] data, int count, string match)
- {
- for (int i = 0; i < count; i++)
- {
- if (data[i] == match) return data[i];
- }
- return data[0];
- }
- static CF_Byte GetByte(string char)
- {
- return CF_Byte.Set(char);
- }
- static array<CF_Byte> GetBytes(string str)
- {
- array<CF_Byte> bytes = new array<CF_Byte>();
- for (int i = 0; i < str.Length(); i++)
- {
- bytes.Insert(CF_Byte.Set(str[i]));
- }
- return bytes;
- }
- static string ToHex(array<CF_Byte> bytes)
- {
- string str = "";
- for (int i = 0; i < bytes.Count(); i++)
- {
- str += bytes[i].ToHex();
- }
- return str;
- }
- static array<CF_Byte> FromHex(string str)
- {
- if (str.Length() % 2 != 0)
- {
- Error("Invalid string length");
- return null;
- }
- array<CF_Byte> bytes = new array<CF_Byte>();
- for (int i = 0; i < str.Length() / 2; i++)
- {
- int n0 = Find(BASE_16, 16, str[i * 2 + 0]) * 16;
- int n1 = Find(BASE_16, 16, str[i * 2 + 1]);
- if (n0 < 0 || n1 < 0)
- {
- Error("Invalid character, expect valid base-16, got \"" + str[i * 2 + 0] + str[i * 2 + 1] + "\"");
- return null;
- }
- CF_Byte byte = n0 + n1;
- bytes.Insert(byte);
- }
- return bytes;
- }
- static string ToBase64(array<CF_Byte> bytes)
- {
- string str = "";
- for (int i = 0; i < bytes.Count(); i++)
- {
- str += bytes[i].ToHex();
- }
- return str;
- }
- static bool IsWhitespace(string char)
- {
- return IsWhitespace(CF_Byte.Set(char));
- }
- /**
- * @brief Returns true if the input byte as in any character below decimal 32.
- * Helpful table https://commons.wikimedia.org/wiki/File:ASCII-Table-wide.svg
- */
- static bool IsWhitespace(CF_Byte byte)
- {
- if (byte <= 32) return true;
- return false;
- }
- static bool IsAlphanumeric(string char)
- {
- return IsAlphanumeric(CF_Byte.Set(char));
- }
- static bool IsAlphanumeric(CF_Byte byte)
- {
- if (byte >= 48 && byte <= 57) return true;
- if (byte > 90) byte -= 32;
- if (byte >= 65 && byte <= 90) return true;
- return false;
- }
- static bool IsAlpha(string char)
- {
- return IsAlpha(CF_Byte.Set(char));
- }
- static bool IsAlpha(CF_Byte byte)
- {
- if (byte > 90) byte -= 32;
- if (byte >= 65 && byte <= 90) return true;
- return false;
- }
- static bool IsNumeric(string char)
- {
- return IsNumeric(CF_Byte.Set(char));
- }
- static bool IsNumeric(CF_Byte byte)
- {
- if (byte >= 48 && byte <= 57) return true;
- return false;
- }
- static bool IsLine(string char)
- {
- return IsNumeric(CF_Byte.Set(char));
- }
- static bool IsLine(CF_Byte byte)
- {
- if (byte >= 10 && byte <= 15) return true;
- return false;
- }
- static bool StringToBool(string str)
- {
- str.ToLower();
- str.Trim();
- if (str == "true") return true;
- if (str == "false") return false;
- return str.ToInt();
- }
- };
- static int CF_XOR(int x, int y)
- {
- int a = (x | y);
- int b = ~x;
- int c = ~y;
- int d = (b | c);
- return (a & d);
- }
- /**
- * Storing bytes in a forward doubly linked list.
- * This gives both fast reading and an unlimited size of bytes
- */
- class CF_PackedByte
- {
- ref CF_PackedByte m_Next;
- CF_PackedByte m_Prev;
- CF_Byte m_Value;
- CF_PackedByte SerializerWrite(Serializer ctx, int length, inout int index)
- {
- CF_PackedByte byte = this;
- int b0;
- int b1;
- int b2;
- int b3;
- if (byte)
- {
- b0 = byte.m_Value;
- byte = byte.m_Next;
- index++;
- }
- if (byte)
- {
- b1 = byte.m_Value;
- byte = byte.m_Next;
- index++;
- }
- if (byte)
- {
- b2 = byte.m_Value;
- byte = byte.m_Next;
- index++;
- }
- if (byte)
- {
- b3 = byte.m_Value;
- byte = byte.m_Next;
- index++;
- }
- ctx.Write(((b3 & 0x000000FF) << 24) + ((b2 & 0x000000FF) << 16) + ((b1 & 0x000000FF) << 8) + (b0 & 0x000000FF));
- return byte;
- }
- CF_PackedByte SerializerRead(Serializer ctx, int length, inout int index)
- {
- CF_PackedByte byte = this;
- int value;
- ctx.Read(value);
- int b3 = (value >> 24) & 0x000000FF;
- int b2 = (value >> 16) & 0x000000FF;
- int b1 = (value >> 8 ) & 0x000000FF;
- int b0 = (value ) & 0x000000FF;
- if (index < length)
- {
- index++;
- // set and clamp
- byte.m_Value = b0 & 255;
- byte.m_Next = new CF_PackedByte();
- byte.m_Next.m_Prev = byte;
- byte = byte.m_Next;
- }
- if (index < length)
- {
- index++;
- // set and clamp
- byte.m_Value = b1 & 255;
- byte.m_Next = new CF_PackedByte();
- byte.m_Next.m_Prev = byte;
- byte = byte.m_Next;
- }
- if (index < length)
- {
- index++;
- byte.m_Value = b2 & 255;
- byte.m_Next = new CF_PackedByte();
- byte.m_Next.m_Prev = byte;
- byte = byte.m_Next;
- }
- if (index < length)
- {
- index++;
- byte.m_Value = b3 & 255;
- byte.m_Next = new CF_PackedByte();
- byte.m_Next.m_Prev = byte;
- byte = byte.m_Next;
- }
- return byte;
- }
- };
- enum CF_SeekOrigin
- {
- SET,
- CURRENT,
- END
- };
- typedef string CF_String;
- class CF_String : string
- {
- /**
- * @brief Returns the number of times the specified character exists in the string
- *
- * @param char The character that will be matched
- *
- * @code
- * CF_String str = "Hello, World!";
- * int count = str.CountCharacter("l");
- * Print(count);
- * >> '3'
- * @endcode
- */
- int CountCharacter(CF_String char)
- {
- int count = 0;
- int length = value.Length();
- for (int index = 0; index < length; index++)
- {
- count += value.Substring(index, 1) == char;
- }
- return count;
- }
- /**
- * @brief Returns the number of times the specified character exists in the string
- *
- * @param char The character that will be matched
- * @param[out] firstOccurrence The index of the first character
- *
- * @code
- * CF_String str = "Hello, World!";
- * int index;
- * int count = str.CountCharacter("l", index);
- * Print(count);
- * Print(index);
- * >> '3'
- * >> '2'
- * @endcode
- */
- int CountCharacter(CF_String char, out int firstOccurrence )
- {
- int count = 0;
- firstOccurrence = -1;
- int length = value.Length();
- for (int index = 0; index < length; index++)
- {
- count += value.Substring(index, 1) == char;
- if (count == 1 && firstOccurrence == -1)
- {
- firstOccurrence = index;
- }
- }
- return count;
- }
- /**
- * @brief Finds last 'sample' in 'str'. Returns -1 when not found
- *
- * @param sample Finding string
- * @return Returns position where sample starts, or -1 when sample not found
- *
- * @code
- * CF_String str = "Hello, World!";
- * Print(str.CF_LastIndexOf("l"));
- * >> 10
- * @endcode
- */
- int CF_LastIndexOf(CF_String sample)
- {
- int sampleLength = sample.Length();
- int length = value.Length();
- int start = length - sampleLength;
- if (start <= 0)
- {
- return -1;
- }
- for (int index = start - 1; index >= 0; index--)
- {
- if (value.Substring(index, sampleLength) == sample)
- {
- return index;
- }
- }
- return -1;
- }
- /**
- * @brief Fills the string with the specified character at the start so the string matches the length.
- * Does nothing if string is equal to or exceeds the specifiying length.
- *
- * @param length The total string length
- * @param padChar The character that will be padded
- *
- * @code
- * CF_String str = "55";
- * Print(str.PadStringFront(4, "0"));
- * >> '0055'
- * @endcode
- */
- string PadStringFront(int length, CF_String padChar)
- {
- string newString = value;
- length = newString.Length() - length;
- if (length > 0)
- {
- for (int index = 0; index < length; index++)
- {
- newString = padChar + newString;
- }
- }
- return newString;
- }
- /**
- * @brief Fills the string with the specified character at the end so the string matches the length.
- * Does nothing if string is equal to or exceeds the specifiying length.
- *
- * @param length The total string length
- * @param padChar The character that will be padded
- *
- * @code
- * CF_String str = "55";
- * Print(str.PadStringBack(4, "0"));
- * >> '5500'
- * @endcode
- */
- string PadStringBack(int length, CF_String padChar)
- {
- string newString = value;
- length = newString.Length() - length;
- if (length > 0)
- {
- for (int index = 0; index < length; index++)
- {
- newString += padChar;
- }
- }
- return newString;
- }
- /**
- * @brief Replaces the string of length at the index with the splice.
- *
- * @param start The index at which to start changing the string
- * @param padChar The string the content will be replaced with
- *
- * @code
- * CF_String str = "How is you?";
- * Print(str.SpliceString(4, "be"));
- * >> 'How be you?'
- * @endcode
- */
- string SpliceString(int start, CF_String splice)
- {
- int middle = start + splice.Length();
- int end = value.Length();
- string a = value.Substring(0, start);
- string b = splice;
- if (middle >= end)
- {
- return a + b;
- }
- string c = value.Substring(middle, end - middle);
- return a + b + c;
- }
- /**
- * @brief Replaces the string of length at the index with the splice. New string does not have to match the length.
- *
- * @param start The index at which to start changing the string
- * @param length The length of characters to be removed
- * @param padChar The string the content will be replaced with
- *
- * @code
- * CF_String str = "How are you?";
- * Print(str.SpliceString(4, 3, "is"));
- * >> 'How is you?'
- * @endcode
- */
- string SpliceString(int start, int length, CF_String splice)
- {
- int middle = start + length;
- int end = value.Length();
- string a = value.Substring(0, start);
- string b = splice;
- if (middle >= end)
- {
- return a + b;
- }
- string c = value.Substring(middle, end - middle);
- return a + b + c;
- }
- /**
- * @brief Checks to see if the two string matches
- *
- * @param a The first string to be checked
- * @param b The second string to be checked
- *
- * @code
- * CF_String a = "How are you?";
- * CF_String b = "how are you?";
- *
- * Print(CF_String.Equals(a, b));
- * >> false
- *
- * b = "How are you?";
- * Print(CF_String.Equals(a, b));
- * >> true
- * @endcode
- */
- static bool Equals(string a, string b)
- {
- return a == b;
- }
- /**
- * @brief Checks to see if the two string matches, ignoring their case
- *
- * @param a The first string to be checked
- * @param b The second string to be checked
- *
- * @code
- * CF_String a = "How are you?";
- * CF_String b = "how are you?";
- *
- * Print(CF_String.EqualsIgnoreCase(a, b));
- * >> true
- *
- * b = "How are you?";
- * Print(CF_String.EqualsIgnoreCase(a, b));
- * >> true
- * @endcode
- */
- static bool EqualsIgnoreCase(string a, string b)
- {
- a.ToLower();
- b.ToLower();
- return a == b;
- }
- /**
- * @brief Reverses the string
- *
- * @code
- * CF_String a = "How are you?";
- * CF_String b = a.Reverse();
- *
- * Print(a);
- * >> "How are you?"
- * Print(b);
- * >> "?uoy era woH"
- *
- * @endcode
- */
- string Reverse()
- {
- string result;
- int index = value.Length() - 1;
- while (index >= 0)
- {
- result += value.Substring(index, 1);
- index--;
- }
- return result;
- }
- };
- /*
- Uint Type Definition
- -- This is a CF_Uint datatype definition for EnScript
- Author: Lystic, Jacob_Mango
- When working with uints, Right Shift operations need to be handled by the ShiftRight method.
- */
- typedef int CF_Uint;
- class CF_Uint : int
- {
- CF_Uint Add(CF_Uint b)
- {
- CF_Uint a = value;
- CF_Uint carry = a & b;
- CF_Uint result = a.XOR(b);
- while (carry)
- {
- CF_Uint shiftedcarry = carry << 1;
- carry = result & shiftedcarry;
- result = result.XOR(shiftedcarry);
- }
- return result;
- }
- bool IsGt(CF_Uint b)
- {
- CF_Uint a = value;
- CF_Uint ltb = ~a & b;
- CF_Uint gtb = a & ~b;
- ltb |= ltb.ShiftRight(1);
- ltb |= ltb.ShiftRight(2);
- ltb |= ltb.ShiftRight(4);
- ltb |= ltb.ShiftRight(8);
- ltb |= ltb.ShiftRight(16);
- CF_Uint isGt = gtb & ~ltb;
- return (isGt != 0); //non-zero if A > B
- }
- bool IsLt(CF_Uint b)
- {
- return !b.IsGt(value);
- }
- CF_Uint ShiftLeft(int amount)
- {
- return value << amount;
- }
- CF_Uint ShiftRight(int amount)
- {
- if (amount <= 0) return value;
- CF_Uint new_value = (value >> 1) & 0x7FFFFFFF; //strip the sign bit away (making it 0)
- CF_Uint extra_shifts = amount - 1;
- if (extra_shifts > 0) new_value = (new_value >> extra_shifts);
- return new_value;
- }
- //--- unsigned bitwise operations
- static CF_Uint RotateLeft(CF_Uint a, CF_Uint b)
- {
- CF_Uint y = (a << b);
- CF_Uint x = (32 - b);
- CF_Uint z = a.ShiftRight(x);
- return (y | z);
- }
- static CF_Uint RotateRight(CF_Uint a, CF_Uint b)
- {
- CF_Uint y = a.ShiftRight(b);
- CF_Uint x = (32 - b);
- CF_Uint z = (a << x);
- return (y | z);
- }
- static CF_Uint CH(CF_Uint x, CF_Uint y, CF_Uint z)
- {
- CF_Uint a = (x & y);
- CF_Uint b = ~x;
- CF_Uint c = (b & z);
- return a.XOR(c); // a XOR c
- }
- static CF_Uint MAJ(CF_Uint x, CF_Uint y, CF_Uint z)
- {
- CF_Uint a = x & y;
- CF_Uint b = x & z;
- CF_Uint c = y & z;
- return a.XOR(b.XOR(c))); //a XOR b XOR c (left-right associativity)
- }
- static CF_Uint EP0(CF_Uint x)
- {
- CF_Uint a = CF_Uint.RotateRight(x, 2);
- CF_Uint b = CF_Uint.RotateRight(x, 13);
- CF_Uint c = CF_Uint.RotateRight(x, 22);
- return a.XOR(b.XOR(c))); //a XOR b XOR c
- }
- static CF_Uint EP1(CF_Uint x)
- {
- CF_Uint a = CF_Uint.RotateRight(x, 6);
- CF_Uint b = CF_Uint.RotateRight(x, 11);
- CF_Uint c = CF_Uint.RotateRight(x, 25);
- return a.XOR(b.XOR(c))); //a XOR b XOR c
- }
- static CF_Uint SIG0(CF_Uint x)
- {
- CF_Uint a = CF_Uint.RotateRight(x, 7);
- CF_Uint b = CF_Uint.RotateRight(x, 18);
- CF_Uint c = x.ShiftRight(3);
- return a.XOR(b.XOR(c))); //a XOR b XOR c
- }
- static CF_Uint SIG1(CF_Uint x)
- {
- CF_Uint a = CF_Uint.RotateRight(x, 17);
- CF_Uint b = CF_Uint.RotateRight(x, 19);
- CF_Uint c = x.ShiftRight(10);
- return a.XOR(b.XOR(c))); //a XOR b XOR c
- }
- CF_Uint XOR(CF_Uint y)
- {
- CF_Uint x = value;
- int a = (x | y);
- int b = ~x;
- int c = ~y;
- int d = (b | c);
- return (a & d);
- }
- };
- class CF_EventArgs
- {
- static const CF_EventArgs Empty = NULL;
- override string GetDebugName()
- {
- return "[" + ClassName() + "]";
- }
- };
- class CF_EventTimeArgs : CF_EventArgs
- {
- int Time;
- void CF_EventTimeArgs(int time)
- {
- Time = time;
- }
- };
- class CF_EventUpdateArgs : CF_EventArgs
- {
- float DeltaTime;
- void CF_EventUpdateArgs(float deltaTime = 0)
- {
- DeltaTime = deltaTime;
- }
- };
- class CF_Directory
- {
- /**
- * @param pattern The search pattern
- * @param [inout] files An array where the list of files will be written to
- * @param flags If it should be looked in directories or .pak files, or both
- *
- * @return If any files were found that matched the pattern
- */
- static bool GetFiles(string pattern, inout array<ref CF_File> files, FindFileFlags flags = 2)
- {
- #ifdef CF_TRACE_ENABLED
- auto trace = CF_Trace_3("CF_Directory", "GetFiles").Add(pattern).Add(files).Add(flags);
- #endif
- if (!files)
- {
- files = new array<ref CF_File>();
- }
- pattern.Replace("\\", CF_Path.DIRECTORY_SEPARATOR);
- string fileName;
- FileAttr fileAttr;
- FindFileHandle handle = FindFile(pattern, fileName, fileAttr, flags);
- if (!handle)
- {
- return false;
- }
- string folder = CF_Path.GetDirectoryName(pattern);
- CF_File file;
- while (true)
- {
- file = new CF_File();
- file._SetFileName(fileName);
- file._SetFolder(folder);
- file._SetAttributes(fileAttr);
- files.Insert(file);
- if (!FindNextFile(handle, fileName, fileAttr))
- {
- break;
- }
- }
- CloseFindFile(handle);
- return true;
- }
- /**
- * @brief Creates all directories and subdirectories in the specified path unless they already exist.
- *
- * @param directory The directory to create.
- *
- * @return If the directories could be created
- */
- static bool CreateDirectory(string directory)
- {
- array<string> directories();
- string path = directory;
- string previousPath = "";
- while (true)
- {
- previousPath = path;
- if (FileExist(previousPath))
- {
- break;
- }
- path = CF_Path.GetDirectoryName(path);
- if (previousPath == path)
- {
- path = previousPath;
- break;
- }
- if (previousPath[previousPath.Length() - 1] == CF_Path.FILESYSTEM_IDENTIFIER)
- {
- return false;
- }
- directory = CF_Path.GetFileNameEx(previousPath, path);
- directory = directory.Substring(0, directory.Length() - 1);
- directories.Insert(directory);
- }
- for (int i = directories.Count() - 1; i >= 0; i--)
- {
- path = path + directories[i] + CF_Path.DIRECTORY_SEPARATOR;
- if (!MakeDirectory(path))
- {
- return false;
- }
- }
- return true;
- }
- };
- class CF_File : Managed
- {
- protected string m_Directory;
- protected string m_FileName;
- protected string m_Extension;
- protected bool m_IsDirectory;
- protected bool m_IsHidden;
- protected bool m_IsReadOnly;
- protected bool m_IsValid;
- /**
- * @brief Constructor
- *
- * @param path No operation perform if path is empty string
- */
- void CF_File(string path = "")
- {
- m_IsValid = true;
- // Default constructor
- if (path == string.Empty)
- {
- return;
- }
- string fileName;
- FileAttr fileAttr;
- FindFileHandle handle = FindFile(path, fileName, fileAttr, FindFileFlags.ALL);
- if (!handle)
- {
- return;
- }
- _SetFolder(CF_Path.GetDirectoryName(path));
- _SetFileName(fileName);
- _SetAttributes(fileAttr);
- CloseFindFile(handle);
- }
- bool IsDirectory()
- {
- return m_IsDirectory;
- }
- bool IsHidden()
- {
- return m_IsHidden;
- }
- bool IsReadOnly()
- {
- return m_IsReadOnly;
- }
- bool IsValid()
- {
- return m_IsValid;
- }
- /**
- * @brief Returns the path, including file name and extension if they exist
- */
- string GetFullPath()
- {
- return m_Directory + m_FileName + m_Extension;
- }
- /**
- * @brief Returns the file name and extension
- */
- string GetFileName()
- {
- return m_FileName + m_Extension;
- }
- /**
- * @brief Returns the file name without the extension
- */
- string GetFileNameWithoutExtension()
- {
- return m_FileName;
- }
- /**
- * @brief Returns the extension (including the period ".")
- */
- string GetExtension()
- {
- return m_Extension;
- }
- /**
- * @brief Returns the full path of the parent folder
- */
- string GetDirectory()
- {
- return m_Directory;
- }
- /**
- * @brief Creates and opens a new instance of a FileStream for the current file
- *
- * @param mode Sets the file mode the stream will be opened in
- *
- * @return new instance of CF_FileStream
- */
- CF_Stream CreateStream(FileMode mode)
- {
- #ifdef CF_TRACE_ENABLED
- auto trace = CF_Trace_1(this, "CreateStream").Add(mode);
- #endif
- if (!IsValid())
- {
- return null;
- }
- return new CF_FileStream(GetFullPath(), mode);
- }
- /**
- * @brief Deletes the current file
- *
- * @return true if the operation was successful
- */
- bool Delete()
- {
- #ifdef CF_TRACE_ENABLED
- auto trace = CF_Trace_0(this, "Delete");
- #endif
- if (!IsValid())
- {
- return false;
- }
- return DeleteFile(GetFullPath());
- }
- /**
- * @brief Renames the current file (copy to new name, then delete original)
- *
- * @param name The new name of the file
- *
- * @return true if the operation was successful
- */
- bool Rename(string name)
- {
- #ifdef CF_TRACE_ENABLED
- auto trace = CF_Trace_1(this, "Rename").Add(name);
- #endif
- if (!IsValid())
- {
- return false;
- }
- // Check if the file already exists at the destination
- if (FileExist(m_Directory + name))
- {
- return false;
- }
- // Copy file to new name
- if (!CopyFile(GetFullPath(), m_Directory + name))
- {
- return false;
- }
- // Delete old file
- bool success = DeleteFile(GetFullPath());
- if (!success)
- {
- CF_Log.Warn("Failed to delete original file in rename for file \"%1\"", GetFullPath());
- }
- _SetFileName(name);
- return true;
- }
- /**
- * @brief Moves the file to the new path (copy to folder, then delete original)
- *
- * @param path The new path
- *
- * @return true if the operation was successful
- */
- bool Move(string path)
- {
- #ifdef CF_TRACE_ENABLED
- auto trace = CF_Trace_1(this, "Move").Add(path);
- #endif
- if (!IsValid())
- {
- return false;
- }
- string folder = CF_Path.GetDirectoryName(path);
- string name = CF_Path.GetFileNameEx(path, folder);
- // File isn't being renamed in move
- if (name == string.Empty)
- {
- name = GetFileName();
- }
- // Check if the file already exists at the destination
- if (FileExist(folder + name))
- {
- return false;
- }
- if (!CopyFile(GetFullPath(), folder + name))
- {
- return false;
- }
- // Delete old file
- bool success = DeleteFile(GetFullPath());
- if (!success)
- {
- CF_Log.Warn("Failed to delete original file in move for file \"%1\"", GetFullPath());
- }
- _SetFolder(folder);
- _SetFileName(name);
- return true;
- }
- /**
- * @brief Copies the file to the new path
- *
- * @param path The new path
- *
- * @return true if the operation was successful
- */
- bool Copy(string path)
- {
- #ifdef CF_TRACE_ENABLED
- auto trace = CF_Trace_1(this, "Move").Add(path);
- #endif
- if (!IsValid())
- {
- return false;
- }
- string folder = CF_Path.GetDirectoryName(path);
- string name = CF_Path.GetFileNameEx(path, folder);
- // File isn't being renamed in move
- if (name == string.Empty)
- {
- name = GetFileName();
- }
- // Check if the file already exists at the destination
- if (FileExist(folder + name))
- {
- CF_Log.Warn("The file already exists at \"%1\".", folder + name);
- return false;
- }
- if (!CopyFile(GetFullPath(), folder + name))
- {
- CF_Log.Warn("Failed to copy file to \"%1\".", folder + name);
- return false;
- }
- return true;
- }
- /**
- * @brief Copies the file to the new path, returning the instance of the file
- *
- * @param path The new path
- * @param [out] newFile Outputs the new instance of the file
- *
- * @return true if the operation was successful
- */
- bool Copy(string path, out CF_File newFile)
- {
- #ifdef CF_TRACE_ENABLED
- auto trace = CF_Trace_1(this, "Copy").Add(path);
- #endif
- if (!IsValid())
- {
- return false;
- }
- string folder = CF_Path.GetDirectoryName(path);
- string name = CF_Path.GetFileNameEx(path, folder);
- // File isn't being renamed in move
- if (name == string.Empty)
- {
- name = GetFileName();
- }
- // Check if the file already exists at the destination
- if (FileExist(folder + name))
- {
- CF_Log.Warn("The file already exists at \"%1\".", folder + name);
- return false;
- }
- if (!CopyFile(GetFullPath(), folder + name))
- {
- CF_Log.Warn("Failed to copy file to \"%1\".", folder + name);
- return false;
- }
- newFile = new CF_File(path);
- return true;
- }
- override string GetDebugName()
- {
- return "{path=\"" + GetFullPath() + "\", filename=\"" + GetFileName() + "\", directory=" + m_IsDirectory.ToString() + ", hidden=" + m_IsHidden.ToString() + ", readonly=" + m_IsReadOnly.ToString() + ", valid=" + m_IsValid.ToString() + "}";
- }
- void _SetFolder(string folder)
- {
- m_Directory = folder;
- }
- void _SetFileName(CF_String fileName)
- {
- int index = fileName.CF_LastIndexOf(".");
- if (index == -1)
- {
- m_FileName = fileName;
- m_Extension = "";
- return;
- }
- m_Extension = fileName.Substring(index, fileName.Length() - index);
- m_FileName = fileName.Substring(0, fileName.Length() - m_Extension.Length());
- }
- void _SetAttributes(FileAttr fileAttr)
- {
- m_IsDirectory = (fileAttr & FileAttr.DIRECTORY) != 0;
- m_IsHidden = (fileAttr & FileAttr.HIDDEN) != 0;
- m_IsReadOnly = (fileAttr & FileAttr.READONLY) != 0;
- m_IsValid = (fileAttr & FileAttr.INVALID) != 0;
- }
- };
- class CF_Path
- {
- static string DIRECTORY_SEPARATOR = "/";
- static string ALT_DIRECTORY_SEPARATOR = "\\";
- static string FILESYSTEM_IDENTIFIER = ":";
- static autoptr array<string> DIRECTORY_CHECKS = { DIRECTORY_SEPARATOR, ALT_DIRECTORY_SEPARATOR, FILESYSTEM_IDENTIFIER };
- /**
- * @brief Returns the directory information for the specified path.
- *
- * @param path The path of a file or directory.
- *
- * @return Directory information for path. Returns an empty string if path does not contain directory information.
- */
- static string GetDirectoryName(CF_String path)
- {
- path.Replace(CF_Path.ALT_DIRECTORY_SEPARATOR, CF_Path.DIRECTORY_SEPARATOR);
- int index = path.CF_LastIndexOf(CF_Path.DIRECTORY_SEPARATOR);
- if (index != -1)
- {
- return path.Substring(0, index) + CF_Path.DIRECTORY_SEPARATOR;
- }
- index = path.CF_LastIndexOf(CF_Path.FILESYSTEM_IDENTIFIER);
- if (index != -1)
- {
- return path.Substring(0, index) + CF_Path.FILESYSTEM_IDENTIFIER;
- }
- return string.Empty;
- }
- /**
- * @brief Returns the file name and extension of the specified path string.
- *
- * @param path The path string from which to obtain the file name and extension.
- *
- * @return The characters after the last directory separator character in path. If the last character of path is a directory or volume separator character, this method returns an empty string.
- */
- static string GetFileName(string path)
- {
- return GetFileNameEx(path, GetDirectoryName(path));
- }
- /**
- * @brief Returns the file name and extension of the specified path string.
- *
- * @param path The path string from which to obtain the file name and extension.
- *
- * @return The characters after the last directory separator character in path. If the last character of path is a directory or volume separator character, this method returns an empty string.
- */
- static string GetFileNameEx(string path, string folder)
- {
- int start = folder.Length();
- int end = path.Length() - folder.Length();
- if (end <= 0)
- {
- return string.Empty;
- }
- if (DIRECTORY_CHECKS.Find(path[end]) != -1)
- {
- return string.Empty;
- }
- return path.Substring(start, end);
- }
- /**
- * @brief Returns the file name of the specified path string.
- *
- * @param path The path string from which to obtain the file name.
- *
- * @return The characters after the last directory separator character in path. If the last character of path is a directory or volume separator character, this method returns an empty string.
- */
- static string GetFileNameWithoutExtension(string path)
- {
- return GetFileNameWithoutExtensionEx(path, GetDirectoryName(path));
- }
- /**
- * @brief Returns the file name of the specified path string.
- *
- * @param path The path string from which to obtain the file name.
- *
- * @return The characters after the last directory separator character in path. If the last character of path is a directory or volume separator character, this method returns an empty string.
- */
- static string GetFileNameWithoutExtensionEx(string path, string folder)
- {
- int start = folder.Length();
- int end = path.Length() - folder.Length();
- if (end <= 0)
- {
- return string.Empty;
- }
- if (DIRECTORY_CHECKS.Find(path[end]) != -1)
- {
- return string.Empty;
- }
- CF_String fileName = path.Substring(start, end);
- int index = fileName.CF_LastIndexOf(".");
- if (index != -1)
- {
- fileName = fileName.Substring(0, index);
- }
- return fileName;
- }
- /**
- * @brief Returns the extension (including the period ".") of the specified path string.
- *
- * @param path The path string from which to get the extension.
- *
- * @return The path string from which to get the extension. If path does not have extension information, this method returns an empty string.
- */
- static string GetExtension(CF_String path)
- {
- int index = path.CF_LastIndexOf(".");
- if (index == -1)
- {
- return string.Empty;
- }
- return path.Substring(index, path.Length() - index);
- }
- };
- typedef CF_Base16Stream CF_HexStream;
- class CF_Base16Stream : CF_Stream
- {
- protected string m_String;
- protected bool m_Dirty;
- void CF_Base16Stream(string str = "")
- {
- Decode(str);
- }
- override void Append(CF_Byte byte = 0)
- {
- super.Append(byte);
- m_Dirty = true;
- }
- override void AppendCurrent(CF_Byte byte = 0)
- {
- super.AppendCurrent(byte);
- m_Dirty = true;
- }
- override void SetOrigin(int index, int value, CF_SeekOrigin origin)
- {
- super.SetOrigin(index, value, origin);
- m_Dirty = true;
- }
- override void Set(int index, int value)
- {
- super.Set(index, value);
- m_Dirty = true;
- }
- override void Resize(int size)
- {
- super.Resize(size);
- m_Dirty = true;
- }
- void Decode(string str)
- {
- if (m_String != str)
- {
- m_String = str;
- for (int i = 0; i < m_String.Length() / 2; i++)
- {
- int n0 = CF_Encoding.Find(CF_Encoding.BASE_16, 16, m_String[i * 2 + 0]) * 16;
- int n1 = CF_Encoding.Find(CF_Encoding.BASE_16, 16, m_String[i * 2 + 1]) * 16;
- if (n0 < 0 || n1 < 0)
- {
- Error("Invalid character, expect valid base-16, got \"" + m_String[i * 2 + 0] + m_String[i * 2 + 1] + "\"");
- return;
- }
- Append(n0 + n1);
- }
- }
- Seek(0, CF_SeekOrigin.SET);
- }
- string Encode()
- {
- UpdateDirty();
- return m_String;
- }
- protected void UpdateDirty()
- {
- if (!m_Dirty) return;
- m_String = "";
- int oldPosition = m_Position;
- CF_PackedByte oldCurrent = m_Current;
- m_Position = 0;
- m_Current = m_Head;
- while (m_Current)
- {
- m_String += m_Current.m_Value.ToHex();
- m_Current = m_Current.m_Next;
- }
- m_Position = oldPosition;
- m_Current = oldCurrent;
- m_Dirty = false;
- }
- };
- class CF_Base64Stream : CF_Stream
- {
- static const string s_Padding[3] = { "", "=", "==" };
- protected string m_String;
- protected bool m_Dirty;
- void CF_Base64Stream(string str = "")
- {
- Decode(str);
- }
- override void Append(CF_Byte byte = 0)
- {
- super.Append(byte);
- m_Dirty = true;
- }
- override void AppendCurrent(CF_Byte byte = 0)
- {
- super.AppendCurrent(byte);
- m_Dirty = true;
- }
- override void SetOrigin(int index, int value, CF_SeekOrigin origin)
- {
- super.SetOrigin(index, value, origin);
- m_Dirty = true;
- }
- override void Set(int index, int value)
- {
- super.Set(index, value);
- m_Dirty = true;
- }
- override void Resize(int size)
- {
- super.Resize(size);
- m_Dirty = true;
- }
- void Decode(string str)
- {
- if (m_String != str)
- {
- m_String = str;
- int padding = 0;
- int i = 0;
- while (i < m_String.Length())
- {
- int value;
- for (int j = 0; j < 4; j++)
- {
- int n = CF_Encoding.Find(CF_Encoding.BASE_64, 64, m_String.Substring(i, 1));
- i++;
- if (n == -1)
- {
- padding++;
- continue;
- }
- value += n << ((18 - j * 6));
- }
- Append((value >> 16 ) & 255);
- Append((value >> 8 ) & 255);
- Append((value ) & 255);
- }
- Resize(m_Size - padding);
- }
- Seek(0, CF_SeekOrigin.SET);
- }
- string Encode()
- {
- UpdateDirty();
- return m_String;
- }
- protected void UpdateDirty()
- {
- if (!m_Dirty) return;
- m_String = "";
- int oldPosition = m_Position;
- CF_PackedByte oldCurrent = m_Current;
- m_Position = 0;
- m_Current = m_Head;
- while (m_Current)
- {
- CF_Uint value = 0;
- value = value.Add(m_Current.m_Value << 16);
- m_Current = m_Current.m_Next;
- if (m_Current)
- {
- value = value.Add(m_Current.m_Value << 8);
- m_Current = m_Current.m_Next;
- }
- if (m_Current)
- {
- value = value.Add(m_Current.m_Value);
- m_Current = m_Current.m_Next;
- }
- m_String += CF_Encoding.BASE_64[value.ShiftRight(18) & 63];
- m_String += CF_Encoding.BASE_64[value.ShiftRight(12) & 63];
- m_String += CF_Encoding.BASE_64[value.ShiftRight(6) & 63];
- m_String += CF_Encoding.BASE_64[value & 63];
- }
- int pad = 3 - (m_Size % 3);
- m_String = m_String.Substring(0, m_String.Length() - pad) + s_Padding[pad];
- m_Position = oldPosition;
- m_Current = oldCurrent;
- m_Dirty = false;
- }
- };
- class CF_BinaryReader : CF_IO
- {
- override bool IsRead()
- {
- return true;
- }
- override bool IsWrite()
- {
- return false;
- }
- override CF_Byte ReadByte()
- {
- return m_Stream.Next();
- }
- override array<CF_Byte> ReadBytes(int count)
- {
- array<CF_Byte> bytes = {};
- ReadBytes(count, bytes);
- return bytes;
- }
- override void ReadBytes(int count, inout array<CF_Byte> bytes)
- {
- bytes.Reserve(count);
- for (int i = 0; i < count; i++)
- {
- CF_Byte byte = m_Stream.Next();
- bytes.Insert(byte);
- }
- }
- override string ReadChar()
- {
- int byte = m_Stream.Next();
- return byte.AsciiToString();
- }
- override bool ReadBool()
- {
- return m_Stream.Next() != 0;
- }
- override int ReadShort()
- {
- int b0 = m_Stream.Next();
- int b1 = m_Stream.Next();
- return ((b1 & 0x000000FF) << 8) + (b0);
- }
- override int ReadInt()
- {
- int b0 = m_Stream.Next();
- int b1 = m_Stream.Next();
- int b2 = m_Stream.Next();
- int b3 = m_Stream.Next();
- return ((b3 & 0x000000FF) << 24) + ((b2 & 0x000000FF) << 16) + ((b1 & 0x000000FF) << 8) + (b0);
- }
- override float ReadFloat()
- {
- int b0 = m_Stream.Next();
- int b1 = m_Stream.Next();
- int b2 = m_Stream.Next();
- int b3 = m_Stream.Next();
- int src[1];
- src[0] = ((b3 & 0x000000FF) << 24) + ((b2 & 0x000000FF) << 16) + ((b1 & 0x000000FF) << 8) + (b0);
- float dst[1];
- copyarray(dst, src);
- return dst[0];
- }
- override vector ReadVector()
- {
- int b3;
- int b2;
- int b1;
- int b0;
- int src[3];
- vector dst;
- b0 = m_Stream.Next();
- b1 = m_Stream.Next();
- b2 = m_Stream.Next();
- b3 = m_Stream.Next();
- src[0] = ((b3 & 0x000000FF) << 24) + ((b2 & 0x000000FF) << 16) + ((b1 & 0x000000FF) << 8) + (b0);
- b0 = m_Stream.Next();
- b1 = m_Stream.Next();
- b2 = m_Stream.Next();
- b3 = m_Stream.Next();
- src[1] = ((b3 & 0x000000FF) << 24) + ((b2 & 0x000000FF) << 16) + ((b1 & 0x000000FF) << 8) + (b0);
- b0 = m_Stream.Next();
- b1 = m_Stream.Next();
- b2 = m_Stream.Next();
- b3 = m_Stream.Next();
- src[2] = ((b3 & 0x000000FF) << 24) + ((b2 & 0x000000FF) << 16) + ((b1 & 0x000000FF) << 8) + (b0);
- copyarray(dst, src);
- return dst;
- }
- override string ReadString()
- {
- int b0 = m_Stream.Next();
- int b1 = m_Stream.Next();
- int b2 = m_Stream.Next();
- int b3 = m_Stream.Next();
- int length = ((b3 & 0x000000FF) << 24) + ((b2 & 0x000000FF) << 16) + ((b1 & 0x000000FF) << 8) + (b0);
- string str;
- for (int index = 0; index < length; index++)
- {
- str += m_Stream.Next().AsciiToString();
- }
- return str;
- }
- override string ReadCString()
- {
- string str;
- int c = m_Stream.Next();
- while (c != 0)
- {
- str += c.AsciiToString();
- c = m_Stream.Next();
- }
- return str;
- }
- };
- class CF_BinaryWriter : CF_IO
- {
- override bool IsRead()
- {
- return false;
- }
- override bool IsWrite()
- {
- return true;
- }
- override void WriteByte(CF_Byte value)
- {
- m_Stream.AppendCurrent(value);
- }
- override void WriteBytes(array<CF_Byte> bytes)
- {
- for (int i = 0; i < bytes.Count(); i++)
- {
- WriteByte(bytes[i]);
- }
- }
- override void WriteChar(string value)
- {
- m_Stream.AppendCurrent(value.ToAscii());
- }
- override void WriteBool(bool value)
- {
- m_Stream.AppendCurrent(value != 0);
- }
- override void WriteShort(int value)
- {
- m_Stream.AppendCurrent((value ) & 0x000000FF);
- m_Stream.AppendCurrent((value >> 8 ) & 0x000000FF);
- }
- override void WriteInt(int value)
- {
- m_Stream.AppendCurrent((value ) & 0x000000FF);
- m_Stream.AppendCurrent((value >> 8 ) & 0x000000FF);
- m_Stream.AppendCurrent((value >> 16) & 0x000000FF);
- m_Stream.AppendCurrent((value >> 24) & 0x000000FF);
- }
- override void WriteFloat(float value)
- {
- float src[1] = { value };
- int dst[1];
- copyarray(dst, src);
- m_Stream.AppendCurrent((dst[0] ) & 0x000000FF);
- m_Stream.AppendCurrent((dst[0] >> 8 ) & 0x000000FF);
- m_Stream.AppendCurrent((dst[0] >> 16) & 0x000000FF);
- m_Stream.AppendCurrent((dst[0] >> 24) & 0x000000FF);
- }
- override void WriteVector(vector value)
- {
- int dst[3];
- copyarray(dst, value);
- int a = dst[0];
- int b = dst[1];
- int c = dst[2];
- m_Stream.AppendCurrent((a ) & 0x000000FF);
- m_Stream.AppendCurrent((a >> 8 ) & 0x000000FF);
- m_Stream.AppendCurrent((a >> 16) & 0x000000FF);
- m_Stream.AppendCurrent((a >> 24) & 0x000000FF);
- m_Stream.AppendCurrent((b ) & 0x000000FF);
- m_Stream.AppendCurrent((b >> 8 ) & 0x000000FF);
- m_Stream.AppendCurrent((b >> 16) & 0x000000FF);
- m_Stream.AppendCurrent((b >> 24) & 0x000000FF);
- m_Stream.AppendCurrent((c ) & 0x000000FF);
- m_Stream.AppendCurrent((c >> 8 ) & 0x000000FF);
- m_Stream.AppendCurrent((c >> 16) & 0x000000FF);
- m_Stream.AppendCurrent((c >> 24) & 0x000000FF);
- }
- override void WriteString(string value)
- {
- int length = value.Length();
- m_Stream.AppendCurrent((length ) & 0x000000FF);
- m_Stream.AppendCurrent((length >> 8 ) & 0x000000FF);
- m_Stream.AppendCurrent((length >> 16) & 0x000000FF);
- m_Stream.AppendCurrent((length >> 24) & 0x000000FF);
- for (int i = 0; i < value.Length(); i++)
- {
- m_Stream.AppendCurrent(value.Get(i).ToAscii());
- }
- }
- override void WriteCString(string value)
- {
- for (int i = 0; i < value.Length(); i++)
- {
- m_Stream.AppendCurrent(value.Get(i).ToAscii());
- }
- m_Stream.AppendCurrent(0);
- }
- };
- class CF_FileStream : CF_Stream
- {
- string m_Path;
- FileMode m_Mode;
- FileHandle m_FileHandle;
- protected bool m_Dirty;
- protected int m_NonZeroCount;
- protected int m_NonZeroes[4];
- void CF_FileStream(string path, FileMode mode)
- {
- m_Path = path;
- m_Mode = mode;
- m_FileHandle = OpenFile(m_Path, m_Mode);
- m_IsOpen = m_FileHandle != 0;
- ReadData(false);
- }
- void MarkDirty()
- {
- m_Dirty = true;
- }
- override void Append(CF_Byte byte = 0)
- {
- super.Append(byte);
- m_Dirty = true;
- }
- override void AppendCurrent(CF_Byte byte = 0)
- {
- super.AppendCurrent(byte);
- m_Dirty = true;
- }
- override void SetOrigin(int index, int value, CF_SeekOrigin origin)
- {
- super.SetOrigin(index, value, origin);
- m_Dirty = true;
- }
- override void Set(int index, int value)
- {
- super.Set(index, value);
- m_Dirty = true;
- }
- override void Resize(int size)
- {
- super.Resize(size);
- m_Dirty = true;
- }
- override bool IsValid()
- {
- return m_FileHandle != 0;
- }
- void ReadData(bool reopen = true)
- {
- if (reopen)
- {
- if (m_FileHandle != 0) CloseFile(m_FileHandle);
- m_FileHandle = OpenFile(m_Path, m_Mode);
- }
- if (m_FileHandle == 0) return;
- if (m_Mode != FileMode.READ) return;
- Resize(0);
- bool readData[1];
- while (ReadFile(m_FileHandle, readData, 1) > 0)
- {
- Append(readData[0] & 0x000000FF);
- }
- Seek(0, CF_SeekOrigin.SET);
- }
- override void Flush()
- {
- if (m_Mode == FileMode.READ) return;
- UpdateDirty();
- FileSerializer serializer = new FileSerializer();
- if (m_FileHandle != 0)
- {
- CloseFile(m_FileHandle);
- }
- if (!serializer.Open(m_Path, FileMode.APPEND)) return;
- int oldPosition = m_Position;
- CF_PackedByte oldCurrent = m_Current;
- m_Position = 0;
- m_Current = m_Head;
- int zero = 0;
- while (m_Current)
- {
- if (zero < m_NonZeroCount && m_NonZeroes[zero] == m_Position)
- {
- zero++;
- serializer.Close();
- m_FileHandle = OpenFile(m_Path, FileMode.APPEND);
- FPrint(m_FileHandle, Next_AsInt().AsciiToString());
- CloseFile(m_FileHandle);
- serializer.Open(m_Path, FileMode.APPEND);
- continue;
- }
- m_Current = m_Current.SerializerWrite(serializer, m_Size, m_Position);
- }
- serializer.Close();
- m_FileHandle = OpenFile(m_Path, FileMode.APPEND);
- m_Position = oldPosition;
- m_Current = oldCurrent;
- }
- override void Close()
- {
- super.Close();
- if (!IsValid())
- return;
- CloseFile(m_FileHandle);
- }
- protected int Next_AsInt()
- {
- int value;
- if (m_Current)
- {
- value = m_Current.m_Value;
- m_Current = m_Current.m_Next;
- m_Position++;
- }
- return value;
- }
- protected void UpdateDirty()
- {
- if (!m_Dirty) return;
- int oldPosition = m_Position;
- CF_PackedByte oldCurrent = m_Current;
- m_Position = 0;
- m_Current = m_Head;
- int needed = m_Size % 4;
- int lastZero = 0;
- m_NonZeroCount = 0;
- for (int index = 0; index < m_Size; index++)
- {
- if (m_NonZeroCount >= needed) break;
- if (Next() == 0) continue;
- // The value is at the start of a block of 4 bytes
- if (((index - lastZero) % 4) == 0)
- {
- m_NonZeroes[m_NonZeroCount] = index;
- m_NonZeroCount++;
- lastZero = index + 1;
- }
- }
- m_Position = oldPosition;
- m_Current = oldCurrent;
- m_Dirty = false;
- }
- };
- class CF_IO : Managed
- {
- ref CF_Stream m_Stream;
- void CF_IO(CF_Stream stream = null)
- {
- m_Stream = stream;
- }
- void SetStream(CF_Stream stream)
- {
- m_Stream = stream;
- }
- bool IsValid()
- {
- if (!m_Stream) return false;
- return m_Stream.IsValid();
- }
- bool IsRead()
- {
- return false;
- }
- bool IsWrite()
- {
- return false;
- }
- /**
- * Write a byte
- */
- void WriteByte(CF_Byte value)
- {
- CF_Log.Error("Not implemented.");
- }
- /**
- * Write an array of bytes
- */
- void WriteBytes(array<CF_Byte> bytes)
- {
- CF_Log.Error("Not implemented.");
- }
- /**
- * Write an ascii character
- */
- void WriteChar(string value)
- {
- CF_Log.Error("Not implemented.");
- }
- /**
- * Write a bool
- */
- void WriteBool(bool value)
- {
- CF_Log.Error("Not implemented.");
- }
- /**
- * Write a short int
- */
- void WriteShort(int value)
- {
- CF_Log.Error("Not implemented.");
- }
- /**
- * Write an int
- */
- void WriteInt(int value)
- {
- CF_Log.Error("Not implemented.");
- }
- /**
- * Write a float
- */
- void WriteFloat(float value)
- {
- CF_Log.Error("Not implemented.");
- }
- /**
- * Write a vector
- */
- void WriteVector(vector value)
- {
- CF_Log.Error("Not implemented.");
- }
- /**
- * Write a string
- */
- void WriteString(string value)
- {
- CF_Log.Error("Not implemented.");
- }
- /**
- * Write a string line
- */
- void WriteLine(string value)
- {
- CF_Log.Error("Not implemented.");
- }
- /**
- * Write a null terminated string
- */
- void WriteCString(string value)
- {
- CF_Log.Error("Not implemented.");
- }
- /**
- * ReadByte a byte
- */
- CF_Byte ReadByte()
- {
- CF_Log.Error("Not implemented.");
- return 0;
- }
- /**
- * ReadByte an array of byte
- */
- array<CF_Byte> ReadBytes(int count)
- {
- CF_Log.Error("Not implemented.");
- return null;
- }
- /**
- * ReadByte an array of byte
- */
- void ReadBytes(int count, inout array<CF_Byte> bytes)
- {
- CF_Log.Error("Not implemented.");
- }
- /**
- * ReadChar an ascii character
- */
- string ReadChar()
- {
- CF_Log.Error("Not implemented.");
- return "";
- }
- /**
- * ReadBool a bool
- */
- bool ReadBool()
- {
- CF_Log.Error("Not implemented.");
- return false;
- }
- /**
- * Read a short int
- */
- int ReadShort()
- {
- CF_Log.Error("Not implemented.");
- return 0;
- }
- /**
- * ReadInt a int
- */
- int ReadInt()
- {
- CF_Log.Error("Not implemented.");
- return 0;
- }
- /**
- * ReadFloat a float
- */
- float ReadFloat()
- {
- CF_Log.Error("Not implemented.");
- return 0;
- }
- /**
- * ReadVector a vector
- */
- vector ReadVector()
- {
- CF_Log.Error("Not implemented.");
- return "0 0 0";
- }
- /**
- * ReadString a string
- */
- string ReadString()
- {
- CF_Log.Error("Not implemented.");
- return "";
- }
- /**
- * ReadLine a line ended with '\n'
- */
- string ReadLine()
- {
- CF_Log.Error("Not implemented.");
- return "";
- }
- /**
- * ReadByte a null terminated string
- */
- string ReadCString()
- {
- CF_Log.Error("Not implemented.");
- return "";
- }
- bool EOF()
- {
- if (!m_Stream) return true;
- return m_Stream.m_Position >= m_Stream.m_Size;
- }
- int Position()
- {
- if (!m_Stream) return 0;
- return m_Stream.m_Position;
- }
- int Length()
- {
- if (!m_Stream) return 0;
- return m_Stream.m_Size;
- }
- void Seek(int num, CF_SeekOrigin origin = CF_SeekOrigin.CURRENT)
- {
- if (!m_Stream) return;
- m_Stream.Seek(num, origin);
- }
- void Close()
- {
- m_Stream.Close();
- m_Stream = null;
- }
- override string GetDebugName()
- {
- string str = "[" + ClassName() + "] ";
- if (m_Stream) str += m_Stream.GetDebugName();
- else str += "NULL";
- return str;
- }
- };
- class CF_SerializerStream : CF_Stream
- {
- Serializer m_Serializer;
- void CF_SerializerStream(Serializer serializer)
- {
- m_Serializer = serializer;
- }
- override bool IsValid()
- {
- return m_Serializer != null;
- }
- };
- class CF_SerializerReadStream : CF_SerializerStream
- {
- void CF_SerializerReadStream(Serializer serializer)
- {
- m_Serializer.Read(m_Size);
- if (m_Size > 0)
- {
- m_Head = new CF_PackedByte();
- m_Tail = m_Head;
- m_Position = 0;
- m_Current = m_Head;
- while (m_Position < m_Size)
- {
- m_Current = m_Current.SerializerRead(m_Serializer, m_Size, m_Position);
- }
- m_Tail = m_Current;
- }
- m_Position = 0;
- m_Current = m_Head;
- }
- };
- class CF_SerializerWriteStream : CF_SerializerStream
- {
- bool m_Flushed;
- override void Flush()
- {
- if (m_Flushed) return;
- m_Flushed = true;
- m_Serializer.Write(m_Size);
- int oldPosition = m_Position;
- CF_PackedByte oldCurrent = m_Current;
- m_Position = 0;
- m_Current = m_Head;
- while (m_Position < m_Size)
- {
- m_Current = m_Current.SerializerWrite(m_Serializer, m_Size, m_Position);
- }
- m_Position = oldPosition;
- m_Current = oldCurrent;
- }
- };
- class CF_Stream
- {
- ref CF_PackedByte m_Head;
- CF_PackedByte m_Tail;
- CF_PackedByte m_Current;
- int m_Size;
- int m_Position;
- bool m_IsOpen;
- void ~CF_Stream()
- {
- #ifdef CF_TRACE_ENABLED
- auto trace = CF_Trace_0(this, "~CF_Stream");
- #endif
- Close();
- }
- bool IsValid()
- {
- return m_IsOpen;
- }
- void Append(CF_Byte byte = 0)
- {
- CF_PackedByte pByte = new CF_PackedByte();
- pByte.m_Value = byte;
- if (!m_Tail)
- {
- m_Head = pByte;
- m_Tail = pByte;
- m_Size = 1;
- }
- else
- {
- pByte.m_Prev = m_Tail;
- m_Tail.m_Next = pByte;
- m_Tail = pByte;
- m_Size++;
- }
- m_Position = m_Size - 1;
- m_Current = pByte;
- }
- void AppendCurrent(CF_Byte byte = 0)
- {
- if (!m_Tail || m_Tail == m_Head || (m_Tail && m_Tail == m_Current))
- {
- Append(byte);
- return;
- }
- CF_PackedByte pByte = new CF_PackedByte();
- pByte.m_Value = byte;
- if (m_Current)
- {
- pByte.m_Next = m_Current.m_Next;
- m_Current.m_Next = pByte;
- pByte.m_Prev = m_Current;
- if (pByte.m_Next != null) pByte.m_Next.m_Prev = pByte;
- m_Position++;
- }
- else
- {
- pByte.m_Next = m_Head;
- m_Head.m_Prev = pByte;
- m_Head = pByte;
- m_Position = 0;
- }
- m_Size++;
- m_Current = pByte;
- }
- void Resize(int size)
- {
- if (m_Size == size) return;
- CF_PackedByte byte = m_Head;
- for (int i = 0; i < size; i++)
- {
- byte = byte.m_Next;
- }
- if (m_Size < size)
- {
- for (i = m_Size; i < size; i++)
- {
- Append();
- }
- }
- else
- {
- byte.m_Next = null;
- m_Tail = byte;
- if (m_Position >= size - 1)
- {
- m_Current = m_Tail;
- m_Position = size - 1;
- }
- }
- m_Size = size;
- }
- int Length()
- {
- return m_Size;
- }
- CF_Byte Get(int index, CF_SeekOrigin origin)
- {
- Seek(index, origin);
- if (!m_Current) return 0;
- return m_Current.m_Value;
- }
- CF_Byte Get(int index)
- {
- Seek(index, CF_SeekOrigin.SET);
- if (!m_Current) return 0;
- return m_Current.m_Value;
- }
- void SetOrigin(int index, int value, CF_SeekOrigin origin)
- {
- Seek(index, origin);
- m_Current.m_Value = value;
- }
- void Set(int index, int value)
- {
- Seek(index, CF_SeekOrigin.SET);
- m_Current.m_Value = value;
- }
- CF_Byte Next()
- {
- if (!m_Current)
- {
- m_Position = 0;
- m_Current = m_Head;
- return 0;
- }
- CF_Byte value = m_Current.m_Value;
- m_Current = m_Current.m_Next;
- m_Position++;
- if (!m_Current)
- {
- m_Position = m_Size;
- m_Current = null;
- }
- return value;
- }
- CF_Byte Previous()
- {
- if (!m_Current)
- {
- m_Position = m_Size - 1;
- m_Current = m_Tail;
- return 0;
- }
- CF_Byte value = m_Current.m_Value;
- m_Current = m_Current.m_Prev;
- m_Position--;
- if (!m_Current)
- {
- m_Position = 0;
- m_Current = m_Head;
- }
- return value;
- }
- void Next(CF_Byte value)
- {
- AppendCurrent(value);
- }
- Param2<CF_PackedByte, int> GetCurrent()
- {
- return new Param2<CF_PackedByte, int>(m_Current, m_Position);
- }
- void GetCurrent(inout Param2<CF_PackedByte, int> tuple)
- {
- tuple = new Param2<CF_PackedByte, int>(m_Current, m_Position);
- }
- void SetCurrent(Param2<CF_PackedByte, int> tuple)
- {
- m_Current = tuple.param1;
- m_Position = tuple.param2;
- }
- void SetPositionAtStart()
- {
- m_Current = null;
- m_Position = -1;
- }
- void SetPositionAtEnd()
- {
- m_Current = m_Tail;
- m_Position = m_Size - 1;
- }
- void Seek(int num, CF_SeekOrigin origin = CF_SeekOrigin.CURRENT)
- {
- int newPosition;
- switch (origin)
- {
- case CF_SeekOrigin.SET:
- newPosition = num;
- m_Position = 0;
- m_Current = m_Head;
- break;
- case CF_SeekOrigin.CURRENT:
- newPosition = m_Position + num;
- break;
- case CF_SeekOrigin.END:
- newPosition = m_Size - num;
- m_Position = m_Size - 1;
- m_Current = m_Tail;
- break;
- }
- if (newPosition < 0)
- {
- m_Position = -1;
- m_Current = null;
- return;
- }
- else if (newPosition >= m_Size)
- {
- m_Position = m_Size - 1;
- m_Current = m_Tail;
- return;
- }
- int i;
- if (newPosition > m_Position)
- {
- i = m_Position;
- while (i < newPosition)
- {
- m_Current = m_Current.m_Next;
- i++;
- }
- }
- else if (newPosition < m_Position)
- {
- i = m_Position;
- while (i > newPosition)
- {
- m_Current = m_Current.m_Prev;
- i--;
- }
- }
- m_Position = newPosition;
- }
- void CopyTo(CF_Stream dest)
- {
- CF_PackedByte byte = m_Head;
- while (byte)
- {
- dest.Append(byte.m_Value);
- byte = byte.m_Next;
- }
- }
- void CopyTo(CF_Stream dest, int size)
- {
- CF_PackedByte byte = m_Head;
- int index = 0;
- while (byte && index < size)
- {
- dest.Append(byte.m_Value);
- byte = byte.m_Next;
- index++;
- }
- }
- void CopyCurrentTo(CF_Stream dest)
- {
- CF_PackedByte byte = m_Current;
- while (byte)
- {
- dest.Append(byte.m_Value);
- byte = byte.m_Next;
- }
- }
- void CopyCurrentTo(CF_Stream dest, int size)
- {
- CF_PackedByte byte = m_Current;
- int index = 0;
- while (byte && index < size)
- {
- dest.Append(byte.m_Value);
- byte = byte.m_Next;
- index++;
- }
- }
- void Flush()
- {
- }
- void Close()
- {
- if (!m_IsOpen)
- return;
- Flush();
- m_IsOpen = true;
- }
- override string GetDebugName()
- {
- string str = "[" + m_Size + "] 0x";
- int oldPosition = m_Position;
- CF_PackedByte oldCurrent = m_Current;
- m_Position = 0;
- m_Current = m_Head;
- while (m_Current)
- {
- str += m_Current.m_Value.ToHex();
- m_Current = m_Current.m_Next;
- }
- m_Position = oldPosition;
- m_Current = oldCurrent;
- return str;
- }
- };
- class CF_StringStream : CF_Stream
- {
- protected string m_String;
- protected bool m_Dirty;
- void CF_StringStream(string str = "")
- {
- m_String = str;
- for (int i = 0; i < str.Length(); i++)
- {
- Append(str.Get(i).ToAscii());
- }
- Seek(0, CF_SeekOrigin.SET);
- }
- override void Append(CF_Byte byte = 0)
- {
- if (byte == 0)
- {
- CF_Log.Error("Attempted writing null byte in CF_StringStream.");
- return;
- }
- super.Append(byte);
- m_Dirty = true;
- }
- override void AppendCurrent(CF_Byte byte = 0)
- {
- if (byte == 0)
- {
- CF_Log.Error("Attempted writing null byte in CF_StringStream.");
- return;
- }
- super.AppendCurrent(byte);
- m_Dirty = true;
- }
- override void SetOrigin(int index, int value, CF_SeekOrigin origin)
- {
- if (value == 0)
- {
- CF_Log.Error("Attempted writing null byte in CF_StringStream.");
- return;
- }
- super.SetOrigin(index, value, origin);
- m_Dirty = true;
- }
- override void Set(int index, int value)
- {
- if (value == 0)
- {
- CF_Log.Error("Attempted writing null byte in CF_StringStream.");
- return;
- }
- super.Set(index, value);
- m_Dirty = true;
- }
- override void Resize(int size)
- {
- super.Resize(size);
- m_Dirty = true;
- }
- override string GetDebugName()
- {
- UpdateDirty();
- return m_String;
- }
- protected void UpdateDirty()
- {
- if (!m_Dirty) return;
- m_String = "";
- int oldPosition = m_Position;
- CF_PackedByte oldCurrent = m_Current;
- m_Position = 0;
- m_Current = m_Head;
- while (m_Current)
- {
- int byte = m_Current.m_Value;
- m_String += byte.AsciiToString();
- m_Current = m_Current.m_Next;
- }
- m_Position = oldPosition;
- m_Current = oldCurrent;
- m_Dirty = false;
- }
- };
- class CF_TextReader : CF_IO
- {
- override bool IsRead()
- {
- return true;
- }
- override bool IsWrite()
- {
- return false;
- }
- override CF_Byte ReadByte()
- {
- return m_Stream.Next();
- }
- override string ReadChar()
- {
- int byte = m_Stream.Next();
- return byte.AsciiToString();
- }
- override bool ReadBool()
- {
- Param2<CF_PackedByte, int> position;
- m_Stream.GetCurrent(position);
- string str = ReadWord();
- if (str == "true")
- return true;
- if (str == "false")
- return false;
- m_Stream.SetCurrent(position);
- return false;
- }
- override int ReadInt()
- {
- string str;
- int byte = ReadByte();
- while (!CF_Encoding.IsWhitespace(byte) && CF_Encoding.IsNumeric(byte) && !EOF())
- {
- str += byte.AsciiToString();
- byte = ReadByte();
- }
- return str.ToInt();
- }
- override float ReadFloat()
- {
- string str;
- int byte = ReadByte();
- bool decimal = false;
- while (!CF_Encoding.IsWhitespace(byte) && (CF_Encoding.IsNumeric(byte) || (!decimal && byte == 46)) && !EOF())
- {
- str += byte.AsciiToString();
- byte = ReadByte();
- }
- return str.ToFloat();
- }
- override vector ReadVector()
- {
- Param2<CF_PackedByte, int> position;
- m_Stream.GetCurrent(position);
- vector vec;
- vec[0] = ReadFloat();
- if (ReadByte() != 44)
- {
- m_Stream.SetCurrent(position);
- return vector.Zero;
- }
- ReadWhitespace();
- vec[1] = ReadFloat();
- if (ReadByte() != 44)
- {
- m_Stream.SetCurrent(position);
- return vector.Zero;
- }
- ReadWhitespace();
- vec[2] = ReadFloat();
- return vec;
- }
- override string ReadLine()
- {
- string str;
- int byte = ReadByte();
- while (!CF_Encoding.IsLine(byte) && !EOF())
- {
- str += byte.AsciiToString();
- byte = ReadByte();
- }
- return str;
- }
- string ReadWord()
- {
- string str;
- int byte = m_Stream.Next();
- while (!CF_Encoding.IsWhitespace(byte) && CF_Encoding.IsAlphanumeric(byte) && !EOF())
- {
- str += byte.AsciiToString();
- byte = m_Stream.Next();
- }
- m_Stream.Previous();
- return str;
- }
- string ReadWhitespace()
- {
- string str;
- int byte = ReadByte();
- while (CF_Encoding.IsWhitespace(byte) && !EOF())
- {
- str += byte.AsciiToString();
- byte = ReadByte();
- }
- m_Stream.Previous();
- return str;
- }
- };
- class CF_TextWriter : CF_IO
- {
- override bool IsRead()
- {
- return false;
- }
- override bool IsWrite()
- {
- return true;
- }
- override void WriteByte(CF_Byte value)
- {
- m_Stream.AppendCurrent(value);
- }
- override void WriteChar(string value)
- {
- WriteByte(value.ToAscii());
- }
- override void WriteBool(bool value)
- {
- WriteString(value.ToString());
- }
- override void WriteInt(int value)
- {
- WriteString(value.ToString());
- }
- override void WriteFloat(float value)
- {
- WriteString(value.ToString());
- }
- override void WriteVector(vector value)
- {
- WriteString(value.ToString());
- }
- override void WriteLine(string value)
- {
- for (int i = 0; i < value.Length(); i++)
- {
- WriteChar(value[i]);
- }
- WriteChar("\n");
- }
- override void WriteString(string value)
- {
- for (int i = 0; i < value.Length(); i++)
- {
- WriteChar(value[i]);
- }
- }
- };
- class CF_Log
- {
- #ifdef CF_TRACE_ENABLED
- static int Level = CF_LogLevel.TRACE;
- #else
- static int Level = CF_LogLevel.ERROR;
- #endif
- static bool IsLogging(CF_LogLevel level)
- {
- return level >= Level;
- }
- /**
- * @brief Logs that contain the most detailed messages. These messages should never be enabled in a production environment.
- */
- static void Trace(string message, string param1 = "", string param2 = "", string param3 = "", string param4 = "", string param5 = "", string param6 = "", string param7 = "", string param8 = "", string param9 = "")
- {
- if (Level > CF_LogLevel.TRACE) return;
- PrintFormat("[TRACE]\t%1", string.Format(message, param1, param2, param3, param4, param5, param6, param7, param8, param9));
- }
- /**
- * @brief Logs that should primarily contain information useful for debugging.
- */
- static void Debug(string message, string param1 = "", string param2 = "", string param3 = "", string param4 = "", string param5 = "", string param6 = "", string param7 = "", string param8 = "", string param9 = "")
- {
- if (Level > CF_LogLevel.DEBUG) return;
- PrintFormat("[DEBUG]\t%1", string.Format(message, param1, param2, param3, param4, param5, param6, param7, param8, param9));
- }
- /**
- * @brief Logs that output information that may be relevant to the user.
- */
- static void Info(string message, string param1 = "", string param2 = "", string param3 = "", string param4 = "", string param5 = "", string param6 = "", string param7 = "", string param8 = "", string param9 = "")
- {
- if (Level > CF_LogLevel.INFO) return;
- PrintFormat("[INFO]\t%1", string.Format(message, param1, param2, param3, param4, param5, param6, param7, param8, param9));
- }
- /**
- * @brief Logs that highlight an abnormal action, but does not cause the user to notice anything different.
- */
- static void Warn(string message, string param1 = "", string param2 = "", string param3 = "", string param4 = "", string param5 = "", string param6 = "", string param7 = "", string param8 = "", string param9 = "")
- {
- if (Level > CF_LogLevel.WARNING) return;
- PrintFormat("[WARNING]\t%1", string.Format(message, param1, param2, param3, param4, param5, param6, param7, param8, param9));
- }
- /**
- * @brief Logs that highlight when the current flow of execution is stopped due to a failure. This should indicate if the current activity has a failure and will not result in the game shutting down. Produces a stack trace.
- */
- static void Error(string message, string param1 = "", string param2 = "", string param3 = "", string param4 = "", string param5 = "", string param6 = "", string param7 = "", string param8 = "", string param9 = "")
- {
- if (Level > CF_LogLevel.ERROR) return;
- PrintFormat("[ERROR]\t%1", string.Format(message, param1, param2, param3, param4, param5, param6, param7, param8, param9));
- string dump = "";
- DumpStackString(dump);
- array<string> outputs = new array<string>();
- dump.Split("\n", outputs);
- for (int i = 1; i < outputs.Count(); i++)
- {
- Print("\t" + outputs[i]);
- }
- }
- /**
- * @brief Logs that describe an unrecoverable event and will most likely lead to the shutdown of the game. Produces a stack trace.
- */
- static void Critical(string message, string param1 = "", string param2 = "", string param3 = "", string param4 = "", string param5 = "", string param6 = "", string param7 = "", string param8 = "", string param9 = "")
- {
- if (Level > CF_LogLevel.CRITICAL) return;
- PrintFormat("[CRITICAL]\t%1", string.Format(message, param1, param2, param3, param4, param5, param6, param7, param8, param9));
- string dump = "";
- DumpStackString(dump);
- array<string> outputs = new array<string>();
- dump.Split("\n", outputs);
- for (int i = 1; i < outputs.Count(); i++)
- {
- Print("\t" + outputs[i]);
- }
- }
- };
- enum CF_LogLevel
- {
- TRACE = 0,
- DEBUG,
- INFO,
- WARNING,
- ERROR,
- CRITICAL,
- NONE,
- };
- class CF_Trace : Managed
- {
- // Global counter for the trace depth
- static string s_TraceDepth;
- protected string m_InstanceName;
- protected string m_StackName;
- protected int m_Ticks;
- protected int m_Count;
- protected int m_Index;
- protected string m_Strings[10];
- protected bool m_Flushed;
- protected bool m_DoLog;
- static string Depth()
- {
- return s_TraceDepth;
- }
- static string FormatInstance(Class instance)
- {
- if (!instance)
- {
- return "null";
- }
- string instanceName;
- //g_Script.CallFunction(instance, "GetDebugNameNative", instanceName, null);
- //if (instanceName == string.Empty)
- //{
- instanceName = "" + instance;
- //}
- return instanceName;
- }
- static string FormatStack(string instance, string stack)
- {
- string res;
- res = instance;
- if (stack != string.Empty) res = instance + "::" + stack;
- return res;
- }
- void CF_Trace(string instanceName, string stackName, int count, bool doLog)
- {
- m_DoLog = doLog;
- m_InstanceName = instanceName;
- string dump = "";
- DumpStackString(dump);
- array<string> outputs = new array<string>();
- dump.Split("\n", outputs);
- m_StackName = outputs[2];
- m_StackName = m_StackName.Substring(0, m_StackName.IndexOf("("));
- if (stackName != string.Empty)
- {
- m_StackName = m_StackName + "_" + stackName;
- }
- m_Count = count;
- if (m_Count == 0) Output();
- }
- void ~CF_Trace()
- {
- if (!m_DoLog || !m_Flushed) return;
- s_TraceDepth = s_TraceDepth.Substring(0, s_TraceDepth.Length() - 1);
- m_Ticks = TickCount(m_Ticks);
- CF_Log.Trace("%1-%2 Time: %3ms", Depth(), FormatStack(m_InstanceName, m_StackName), (m_Ticks / 10000.0).ToString());
- }
- bool IsLogged()
- {
- return m_DoLog;
- }
- void Output()
- {
- if (!m_DoLog || m_Flushed) return;
- m_Flushed = true;
- string params;
- for (int i = 0; i < m_Count - 1; i++)
- {
- params += m_Strings[i] + ", ";
- }
- if (m_Count > 0) params += m_Strings[m_Count - 1];
- CF_Log.Trace("%1+%2 (%3)", Depth(), FormatStack(m_InstanceName, m_StackName), params);
- s_TraceDepth += " ";
- m_Ticks = TickCount(0);
- }
- CF_Trace Add(bool value)
- {
- m_Strings[m_Index] = value.ToString();
- m_Index++;
- if (m_Index < m_Count || m_Count == -1) return this;
- Output();
- return this;
- }
- CF_Trace Add(int value)
- {
- m_Strings[m_Index] = value.ToString();
- m_Index++;
- if (m_Index < m_Count || m_Count == -1) return this;
- Output();
- return this;
- }
- CF_Trace Add(float value)
- {
- m_Strings[m_Index] = value.ToString();
- m_Index++;
- if (m_Index < m_Count || m_Count == -1) return this;
- Output();
- return this;
- }
- CF_Trace Add(vector value)
- {
- m_Strings[m_Index] = value.ToString();
- m_Index++;
- if (m_Index < m_Count || m_Count == -1) return this;
- Output();
- return this;
- }
- CF_Trace Add(string value)
- {
- m_Strings[m_Index] = "\"" + value + "\"";
- m_Index++;
- if (m_Index < m_Count || m_Count == -1) return this;
- Output();
- return this;
- }
- CF_Trace Add(typename value)
- {
- m_Strings[m_Index] = value.ToString();
- m_Index++;
- if (m_Index < m_Count || m_Count == -1) return this;
- Output();
- return this;
- }
- CF_Trace Add(Class value)
- {
- string val = "" + value;
- if (value) val = "\"" + value.GetDebugName() + "\"";
- m_Strings[m_Index] = val;
- m_Index++;
- if (m_Index < m_Count || m_Count == -1) return this;
- Output();
- return this;
- }
- CF_Trace Add(int value, typename type)
- {
- return Add(typename.EnumToString(type, value));
- }
- CF_Trace Add(int value, array<string> values)
- {
- string vName = "INVALID";
- if (value >= 0 && value < values.Count())
- {
- vName = values[value];
- }
- return Add(vName);
- }
- };
- static CF_Trace CF_Trace_Instance(Class instance)
- {
- auto trace = new CF_Trace(CF_Trace.FormatInstance(instance), string.Empty, 0, true);
- return trace;
- }
- static CF_Trace CF_Trace_0(Class instance, string stackName = string.Empty)
- {
- auto trace = new CF_Trace(CF_Trace.FormatInstance(instance), stackName, 0, true);
- return trace;
- }
- static CF_Trace CF_Trace_1(Class instance, string stackName = string.Empty)
- {
- auto trace = new CF_Trace(CF_Trace.FormatInstance(instance), stackName, 1, true);
- return trace;
- }
- static CF_Trace CF_Trace_2(Class instance, string stackName = string.Empty)
- {
- auto trace = new CF_Trace(CF_Trace.FormatInstance(instance), stackName, 2, true);
- return trace;
- }
- static CF_Trace CF_Trace_3(Class instance, string stackName = string.Empty)
- {
- auto trace = new CF_Trace(CF_Trace.FormatInstance(instance), stackName, 3, true);
- return trace;
- }
- static CF_Trace CF_Trace_4(Class instance, string stackName = string.Empty)
- {
- auto trace = new CF_Trace(CF_Trace.FormatInstance(instance), stackName, 4, true);
- return trace;
- }
- static CF_Trace CF_Trace_5(Class instance, string stackName = string.Empty)
- {
- auto trace = new CF_Trace(CF_Trace.FormatInstance(instance), stackName, 5, true);
- return trace;
- }
- static CF_Trace CF_Trace_6(Class instance, string stackName = string.Empty)
- {
- auto trace = new CF_Trace(CF_Trace.FormatInstance(instance), stackName, 6, true);
- return trace;
- }
- static CF_Trace CF_Trace_7(Class instance, string stackName = string.Empty)
- {
- auto trace = new CF_Trace(CF_Trace.FormatInstance(instance), stackName, 7, true);
- return trace;
- }
- static CF_Trace CF_Trace_8(Class instance, string stackName = string.Empty)
- {
- auto trace = new CF_Trace(CF_Trace.FormatInstance(instance), stackName, 8, true);
- return trace;
- }
- static CF_Trace CF_Trace_9(Class instance, string stackName = string.Empty)
- {
- auto trace = new CF_Trace(CF_Trace.FormatInstance(instance), stackName, 9, true);
- return trace;
- }
- static CF_Trace CF_Trace_0(string instance = string.Empty, string stackName = string.Empty)
- {
- auto trace = new CF_Trace(instance, stackName, 0, true);
- return trace;
- }
- static CF_Trace CF_Trace_1(string instance = string.Empty, string stackName = string.Empty)
- {
- auto trace = new CF_Trace(instance, stackName, 1, true);
- return trace;
- }
- static CF_Trace CF_Trace_2(string instance = string.Empty, string stackName = string.Empty)
- {
- auto trace = new CF_Trace(instance, stackName, 2, true);
- return trace;
- }
- static CF_Trace CF_Trace_3(string instance = string.Empty, string stackName = string.Empty)
- {
- auto trace = new CF_Trace(instance, stackName, 3, true);
- return trace;
- }
- static CF_Trace CF_Trace_4(string instance = string.Empty, string stackName = string.Empty)
- {
- auto trace = new CF_Trace(instance, stackName, 4, true);
- return trace;
- }
- static CF_Trace CF_Trace_5(string instance = string.Empty, string stackName = string.Empty)
- {
- auto trace = new CF_Trace(instance, stackName, 5, true);
- return trace;
- }
- static CF_Trace CF_Trace_6(string instance = string.Empty, string stackName = string.Empty)
- {
- auto trace = new CF_Trace(instance, stackName, 6, true);
- return trace;
- }
- static CF_Trace CF_Trace_7(string instance = string.Empty, string stackName = string.Empty)
- {
- auto trace = new CF_Trace(instance, stackName, 7, true);
- return trace;
- }
- static CF_Trace CF_Trace_8(string instance = string.Empty, string stackName = string.Empty)
- {
- auto trace = new CF_Trace(instance, stackName, 8, true);
- return trace;
- }
- static CF_Trace CF_Trace_9(string instance = string.Empty, string stackName = string.Empty)
- {
- auto trace = new CF_Trace(instance, stackName, 9, true);
- return trace;
- }
- static CF_Trace CF_Trace_Instance(bool doLog, Class instance)
- {
- auto trace = new CF_Trace(CF_Trace.FormatInstance(instance), string.Empty, 0, doLog);
- return trace;
- }
- static CF_Trace CF_Trace_0(bool doLog, Class instance, string stackName = string.Empty)
- {
- auto trace = new CF_Trace(CF_Trace.FormatInstance(instance), stackName, 0, doLog);
- return trace;
- }
- static CF_Trace CF_Trace_1(bool doLog, Class instance, string stackName = string.Empty)
- {
- auto trace = new CF_Trace(CF_Trace.FormatInstance(instance), stackName, 1, doLog);
- return trace;
- }
- static CF_Trace CF_Trace_2(bool doLog, Class instance, string stackName = string.Empty)
- {
- auto trace = new CF_Trace(CF_Trace.FormatInstance(instance), stackName, 2, doLog);
- return trace;
- }
- static CF_Trace CF_Trace_3(bool doLog, Class instance, string stackName = string.Empty)
- {
- auto trace = new CF_Trace(CF_Trace.FormatInstance(instance), stackName, 3, doLog);
- return trace;
- }
- static CF_Trace CF_Trace_4(bool doLog, Class instance, string stackName = string.Empty)
- {
- auto trace = new CF_Trace(CF_Trace.FormatInstance(instance), stackName, 4, doLog);
- return trace;
- }
- static CF_Trace CF_Trace_5(bool doLog, Class instance, string stackName = string.Empty)
- {
- auto trace = new CF_Trace(CF_Trace.FormatInstance(instance), stackName, 5, doLog);
- return trace;
- }
- static CF_Trace CF_Trace_6(bool doLog, Class instance, string stackName = string.Empty)
- {
- auto trace = new CF_Trace(CF_Trace.FormatInstance(instance), stackName, 6, doLog);
- return trace;
- }
- static CF_Trace CF_Trace_7(bool doLog, Class instance, string stackName = string.Empty)
- {
- auto trace = new CF_Trace(CF_Trace.FormatInstance(instance), stackName, 7, doLog);
- return trace;
- }
- static CF_Trace CF_Trace_8(bool doLog, Class instance, string stackName = string.Empty)
- {
- auto trace = new CF_Trace(CF_Trace.FormatInstance(instance), stackName, 8, doLog);
- return trace;
- }
- static CF_Trace CF_Trace_9(bool doLog, Class instance, string stackName = string.Empty)
- {
- auto trace = new CF_Trace(CF_Trace.FormatInstance(instance), stackName, 9, doLog);
- return trace;
- }
- static CF_Trace CF_Trace_0(bool doLog, string instance = string.Empty, string stackName = string.Empty)
- {
- auto trace = new CF_Trace(instance, stackName, 0, doLog);
- return trace;
- }
- static CF_Trace CF_Trace_1(bool doLog, string instance = string.Empty, string stackName = string.Empty)
- {
- auto trace = new CF_Trace(instance, stackName, 1, doLog);
- return trace;
- }
- static CF_Trace CF_Trace_2(bool doLog, string instance = string.Empty, string stackName = string.Empty)
- {
- auto trace = new CF_Trace(instance, stackName, 2, doLog);
- return trace;
- }
- static CF_Trace CF_Trace_3(bool doLog, string instance = string.Empty, string stackName = string.Empty)
- {
- auto trace = new CF_Trace(instance, stackName, 3, doLog);
- return trace;
- }
- static CF_Trace CF_Trace_4(bool doLog, string instance = string.Empty, string stackName = string.Empty)
- {
- auto trace = new CF_Trace(instance, stackName, 4, doLog);
- return trace;
- }
- static CF_Trace CF_Trace_5(bool doLog, string instance = string.Empty, string stackName = string.Empty)
- {
- auto trace = new CF_Trace(instance, stackName, 5, doLog);
- return trace;
- }
- static CF_Trace CF_Trace_6(bool doLog, string instance = string.Empty, string stackName = string.Empty)
- {
- auto trace = new CF_Trace(instance, stackName, 6, doLog);
- return trace;
- }
- static CF_Trace CF_Trace_7(bool doLog, string instance = string.Empty, string stackName = string.Empty)
- {
- auto trace = new CF_Trace(instance, stackName, 7, doLog);
- return trace;
- }
- static CF_Trace CF_Trace_8(bool doLog, string instance = string.Empty, string stackName = string.Empty)
- {
- auto trace = new CF_Trace(instance, stackName, 8, doLog);
- return trace;
- }
- static CF_Trace CF_Trace_9(bool doLog, string instance = string.Empty, string stackName = string.Empty)
- {
- auto trace = new CF_Trace(instance, stackName, 9, doLog);
- return trace;
- }
- class CF_ModuleCore : Managed
- {
- static bool s_PreventInput = false;
- int m_CF_GameFlag;
- void CF_ModuleCore()
- {
- #ifdef CF_TRACE_ENABLED
- auto trace = CF_Trace_0(this, "CF_ModuleCore");
- #endif
- }
- void ~CF_ModuleCore()
- {
- #ifdef CF_TRACE_ENABLED
- auto trace = CF_Trace_0(this, "~CF_ModuleCore");
- #endif
- }
- bool IsServer()
- {
- return true;
- }
- bool IsClient()
- {
- return true;
- }
- typename GetType()
- {
- return Type();
- }
- // Permanent Event
- void Init()
- {
- OnInit();
- }
- void OnInit()
- {
- }
- // Event Registration
- void EnableUpdate()
- {
- CF_ModuleCoreManager.s_Update.Add(this);
- }
- void EnableMissionStart()
- {
- CF_ModuleCoreManager.s_MissionStart.Add(this);
- }
- void EnableMissionFinish()
- {
- CF_ModuleCoreManager.s_MissionFinish.Add(this);
- }
- void EnableMissionLoaded()
- {
- CF_ModuleCoreManager.s_MissionLoaded.Add(this);
- }
- void EnableSettingsChanged()
- {
- CF_ModuleCoreManager.s_SettingsChanged.Add(this);
- }
- void EnablePermissionsChanged()
- {
- CF_ModuleCoreManager.s_PermissionsChanged.Add(this);
- }
- void EnableWorldCleanup()
- {
- CF_ModuleCoreManager.s_WorldCleanup.Add(this);
- }
- void EnableMPSessionStart()
- {
- CF_ModuleCoreManager.s_MPSessionStart.Add(this);
- }
- void EnableMPSessionPlayerReady()
- {
- CF_ModuleCoreManager.s_MPSessionPlayerReady.Add(this);
- }
- void EnableMPSessionFail()
- {
- CF_ModuleCoreManager.s_MPSessionFail.Add(this);
- }
- void EnableMPSessionEnd()
- {
- CF_ModuleCoreManager.s_MPSessionEnd.Add(this);
- }
- void EnableMPConnectAbort()
- {
- CF_ModuleCoreManager.s_MPConnectAbort.Add(this);
- }
- void EnableMPConnectionLost()
- {
- CF_ModuleCoreManager.s_MPConnectionLost.Add(this);
- }
- void EnableRespawn()
- {
- CF_ModuleCoreManager.s_Respawn.Add(this);
- }
- void EnableLoginTime()
- {
- CF_ModuleCoreManager.s_LoginTime.Add(this);
- }
- void EnableLoginStatus()
- {
- CF_ModuleCoreManager.s_LoginStatus.Add(this);
- }
- void EnableLogout()
- {
- CF_ModuleCoreManager.s_Logout.Add(this);
- }
- void EnableChat()
- {
- CF_ModuleCoreManager.s_Chat.Add(this);
- }
- // Events
- void OnMissionStart(Class sender, CF_EventArgs args);
- void OnMissionFinish(Class sender, CF_EventArgs args);
- void OnMissionLoaded(Class sender, CF_EventArgs args);
- void OnUpdate(Class sender, CF_EventArgs args);
- void OnSettingsChanged(Class sender, CF_EventArgs args);
- void OnPermissionsChanged(Class sender, CF_EventArgs args);
- /**
- * @brief See: WorldCleaupEventTypeID
- */
- void OnWorldCleanup(Class sender, CF_EventArgs args);
- /**
- * @brief See: MPSessionStartEventTypeID
- */
- void OnMPSessionStart(Class sender, CF_EventArgs args);
- /**
- * @brief See: MPSessionPlayerReadyEventTypeID
- */
- void OnMPSessionPlayerReady(Class sender, CF_EventArgs args);
- /**
- * @brief See: MPSessionFailEventTypeID
- */
- void OnMPSessionFail(Class sender, CF_EventArgs args);
- /**
- * @brief See: MPSessionEndEventTypeID
- */
- void OnMPSessionEnd(Class sender, CF_EventArgs args);
- /**
- * @brief See: ConnectingAbortEventTypeID
- */
- void OnMPConnectAbort(Class sender, CF_EventArgs args);
- /**
- * @brief See: MPConnectionLostEventTypeID
- */
- void OnMPConnectionLost(Class sender, CF_EventArgs args);
- /**
- * @brief See: RespawnEventTypeID
- */
- void OnRespawn(Class sender, CF_EventArgs args);
- /**
- * @brief See: LoginTimeEventTypeID
- */
- void OnLoginTime(Class sender, CF_EventArgs args);
- /**
- * @brief See: LoginStatusEventTypeID
- */
- void OnLoginStatus(Class sender, CF_EventArgs args);
- /**
- * @brief See: LogoutEventTypeID
- */
- void OnLogout(Class sender, CF_EventArgs args);
- /**
- * @brief See: ChatMessageEventTypeID
- */
- void OnChat(Class sender, CF_EventArgs args);
- // FALLBACKS
- void Error_Deprecated(string oldFunc, string newFunc)
- {
- CF_Log.Info(ClassName() + "::" + oldFunc + " is deprecated. Use " + ClassName() + "::" + newFunc + " instead.");
- }
- void Error_Removed(string oldFunc)
- {
- CF_Log.Info(ClassName() + "::" + oldFunc + " is deprecated and has no replacement.");
- }
- };
- class CF_ModuleCoreEvent
- {
- ref CF_ModuleCore m_Value;
- ref CF_ModuleCoreEvent m_Next;
- void CF_ModuleCoreEvent(CF_ModuleCore module = null)
- {
- m_Value = module;
- }
- void Add(CF_ModuleCore module)
- {
- CF_ModuleCoreEvent newEvent = new CF_ModuleCoreEvent(module);
- CF_ModuleCoreEvent current = this;
- CF_ModuleCoreEvent next = m_Next;
- while (current && next)
- {
- if (current.m_Value == module || next.m_Value == module)
- {
- return;
- }
- current = next;
- next = next.m_Next;
- }
- current.m_Next = newEvent;
- }
- void OnMissionStart(Class sender, CF_EventArgs args)
- {
- CF_ModuleCoreEvent evt = this.m_Next;
- while (evt)
- {
- CF_ModuleCore module = evt.m_Value;
- if ((module.m_CF_GameFlag & CF_ModuleCoreManager.s_GameFlag) != 0)
- {
- module.OnMissionStart(sender, args);
- }
- evt = evt.m_Next;
- }
- }
- void OnMissionFinish(Class sender, CF_EventArgs args)
- {
- CF_ModuleCoreEvent evt = this.m_Next;
- while (evt)
- {
- CF_ModuleCore module = evt.m_Value;
- if ((module.m_CF_GameFlag & CF_ModuleCoreManager.s_GameFlag) != 0)
- {
- module.OnMissionFinish(sender, args);
- }
- evt = evt.m_Next;
- }
- }
- void OnMissionLoaded(Class sender, CF_EventArgs args)
- {
- CF_ModuleCoreEvent evt = this.m_Next;
- while (evt)
- {
- CF_ModuleCore module = evt.m_Value;
- if ((module.m_CF_GameFlag & CF_ModuleCoreManager.s_GameFlag) != 0)
- {
- module.OnMissionLoaded(sender, args);
- }
- evt = evt.m_Next;
- }
- }
- void OnUpdate(Class sender, CF_EventArgs args)
- {
- CF_ModuleCoreEvent evt = this.m_Next;
- while (evt)
- {
- CF_ModuleCore module = evt.m_Value;
- if ((module.m_CF_GameFlag & CF_ModuleCoreManager.s_GameFlag) != 0)
- {
- module.OnUpdate(sender, args);
- }
- evt = evt.m_Next;
- }
- }
- void OnSettingsChanged(Class sender, CF_EventArgs args)
- {
- CF_ModuleCoreEvent evt = this.m_Next;
- while (evt)
- {
- CF_ModuleCore module = evt.m_Value;
- if ((module.m_CF_GameFlag & CF_ModuleCoreManager.s_GameFlag) != 0)
- {
- module.OnSettingsChanged(sender, args);
- }
- evt = evt.m_Next;
- }
- }
- void OnPermissionsChanged(Class sender, CF_EventArgs args)
- {
- CF_ModuleCoreEvent evt = this.m_Next;
- while (evt)
- {
- CF_ModuleCore module = evt.m_Value;
- if ((module.m_CF_GameFlag & CF_ModuleCoreManager.s_GameFlag) != 0)
- {
- module.OnPermissionsChanged(sender, args);
- }
- evt = evt.m_Next;
- }
- }
- void OnWorldCleanup(Class sender, CF_EventArgs args)
- {
- CF_ModuleCoreEvent evt = this.m_Next;
- while (evt)
- {
- CF_ModuleCore module = evt.m_Value;
- if ((module.m_CF_GameFlag & CF_ModuleCoreManager.s_GameFlag) != 0)
- {
- module.OnWorldCleanup(sender, args);
- }
- evt = evt.m_Next;
- }
- }
- void OnMPSessionStart(Class sender, CF_EventArgs args)
- {
- CF_ModuleCoreEvent evt = this.m_Next;
- while (evt)
- {
- CF_ModuleCore module = evt.m_Value;
- if ((module.m_CF_GameFlag & CF_ModuleCoreManager.s_GameFlag) != 0)
- {
- module.OnMPSessionStart(sender, args);
- }
- evt = evt.m_Next;
- }
- }
- void OnMPSessionPlayerReady(Class sender, CF_EventArgs args)
- {
- CF_ModuleCoreEvent evt = this.m_Next;
- while (evt)
- {
- CF_ModuleCore module = evt.m_Value;
- if ((module.m_CF_GameFlag & CF_ModuleCoreManager.s_GameFlag) != 0)
- {
- module.OnMPSessionPlayerReady(sender, args);
- }
- evt = evt.m_Next;
- }
- }
- void OnMPSessionFail(Class sender, CF_EventArgs args)
- {
- CF_ModuleCoreEvent evt = this.m_Next;
- while (evt)
- {
- CF_ModuleCore module = evt.m_Value;
- if ((module.m_CF_GameFlag & CF_ModuleCoreManager.s_GameFlag) != 0)
- {
- module.OnMPSessionFail(sender, args);
- }
- evt = evt.m_Next;
- }
- }
- void OnMPSessionEnd(Class sender, CF_EventArgs args)
- {
- CF_ModuleCoreEvent evt = this.m_Next;
- while (evt)
- {
- CF_ModuleCore module = evt.m_Value;
- if ((module.m_CF_GameFlag & CF_ModuleCoreManager.s_GameFlag) != 0)
- {
- module.OnMPSessionEnd(sender, args);
- }
- evt = evt.m_Next;
- }
- }
- void OnMPConnectAbort(Class sender, CF_EventArgs args)
- {
- CF_ModuleCoreEvent evt = this.m_Next;
- while (evt)
- {
- CF_ModuleCore module = evt.m_Value;
- if ((module.m_CF_GameFlag & CF_ModuleCoreManager.s_GameFlag) != 0)
- {
- module.OnMPConnectAbort(sender, args);
- }
- evt = evt.m_Next;
- }
- }
- void OnMPConnectionLost(Class sender, CF_EventArgs args)
- {
- CF_ModuleCoreEvent evt = this.m_Next;
- while (evt)
- {
- CF_ModuleCore module = evt.m_Value;
- if ((module.m_CF_GameFlag & CF_ModuleCoreManager.s_GameFlag) != 0)
- {
- module.OnMPConnectionLost(sender, args);
- }
- evt = evt.m_Next;
- }
- }
- void OnRespawn(Class sender, CF_EventArgs args)
- {
- CF_ModuleCoreEvent evt = this.m_Next;
- while (evt)
- {
- CF_ModuleCore module = evt.m_Value;
- if ((module.m_CF_GameFlag & CF_ModuleCoreManager.s_GameFlag) != 0)
- {
- module.OnRespawn(sender, args);
- }
- evt = evt.m_Next;
- }
- }
- void OnLoginTime(Class sender, CF_EventArgs args)
- {
- CF_ModuleCoreEvent evt = this.m_Next;
- while (evt)
- {
- CF_ModuleCore module = evt.m_Value;
- if ((module.m_CF_GameFlag & CF_ModuleCoreManager.s_GameFlag) != 0)
- {
- module.OnLoginTime(sender, args);
- }
- evt = evt.m_Next;
- }
- }
- void OnLoginStatus(Class sender, CF_EventArgs args)
- {
- CF_ModuleCoreEvent evt = this.m_Next;
- while (evt)
- {
- CF_ModuleCore module = evt.m_Value;
- if ((module.m_CF_GameFlag & CF_ModuleCoreManager.s_GameFlag) != 0)
- {
- module.OnLoginStatus(sender, args);
- }
- evt = evt.m_Next;
- }
- }
- void OnLogout(Class sender, CF_EventArgs args)
- {
- CF_ModuleCoreEvent evt = this.m_Next;
- while (evt)
- {
- CF_ModuleCore module = evt.m_Value;
- if ((module.m_CF_GameFlag & CF_ModuleCoreManager.s_GameFlag) != 0)
- {
- module.OnLogout(sender, args);
- }
- evt = evt.m_Next;
- }
- }
- void OnChat(Class sender, CF_EventArgs args)
- {
- CF_ModuleCoreEvent evt = this.m_Next;
- while (evt)
- {
- CF_ModuleCore module = evt.m_Value;
- if ((module.m_CF_GameFlag & CF_ModuleCoreManager.s_GameFlag) != 0)
- {
- module.OnChat(sender, args);
- }
- evt = evt.m_Next;
- }
- }
- };
- static autoptr CF_ModuleCoreManager g_CF_Module_Manager;
- class CF_ModuleCoreManager
- {
- static autoptr array<string> s_ModuleNames = new array<string>();
- static autoptr map<typename, CF_ModuleCore> s_ModulesMap = new map<typename, CF_ModuleCore>();
- static autoptr array<autoptr CF_ModuleCore> s_Modules = new array<autoptr CF_ModuleCore>();
- static bool s_IsCreated;
- static autoptr CF_ModuleCoreEvent s_MissionStart = new CF_ModuleCoreEvent();
- static autoptr CF_ModuleCoreEvent s_MissionFinish = new CF_ModuleCoreEvent();
- static autoptr CF_ModuleCoreEvent s_MissionLoaded = new CF_ModuleCoreEvent();
- static autoptr CF_ModuleCoreEvent s_Update = new CF_ModuleCoreEvent();
- static autoptr CF_ModuleCoreEvent s_SettingsChanged = new CF_ModuleCoreEvent();
- static autoptr CF_ModuleCoreEvent s_PermissionsChanged = new CF_ModuleCoreEvent();
- static autoptr CF_ModuleCoreEvent s_WorldCleanup = new CF_ModuleCoreEvent();
- static autoptr CF_ModuleCoreEvent s_MPSessionStart = new CF_ModuleCoreEvent();
- static autoptr CF_ModuleCoreEvent s_MPSessionPlayerReady = new CF_ModuleCoreEvent();
- static autoptr CF_ModuleCoreEvent s_MPSessionFail = new CF_ModuleCoreEvent();
- static autoptr CF_ModuleCoreEvent s_MPSessionEnd = new CF_ModuleCoreEvent();
- static autoptr CF_ModuleCoreEvent s_MPConnectAbort = new CF_ModuleCoreEvent();
- static autoptr CF_ModuleCoreEvent s_MPConnectionLost = new CF_ModuleCoreEvent();
- static autoptr CF_ModuleCoreEvent s_Respawn = new CF_ModuleCoreEvent();
- static autoptr CF_ModuleCoreEvent s_LoginTime = new CF_ModuleCoreEvent();
- static autoptr CF_ModuleCoreEvent s_LoginStatus = new CF_ModuleCoreEvent();
- static autoptr CF_ModuleCoreEvent s_Logout = new CF_ModuleCoreEvent();
- static autoptr CF_ModuleCoreEvent s_Chat = new CF_ModuleCoreEvent();
- static int s_GameFlag;
- static void _OnCreate()
- {
- #ifdef CF_TRACE_ENABLED
- auto trace = CF_Trace_0("CF_ModuleCoreManager", "_OnCreate");
- #endif
- _OnDestroy();
- g_CF_Module_Manager = new CF_ModuleCoreManager();
- s_IsCreated = true;
- for (int i = 0; i < s_ModuleNames.Count(); i++)
- {
- _Create(s_ModuleNames[i]);
- }
- }
- static void _OnDestroy()
- {
- #ifdef CF_TRACE_ENABLED
- auto trace = CF_Trace_0("CF_ModuleCoreManager", "_OnDestroy");
- #endif
- for (int i = s_Modules.Count() - 1; i >= 0; i--)
- {
- delete s_Modules[i];
- }
- s_ModulesMap.Clear();
- s_Modules.Clear();
- s_IsCreated = false;
- }
- /**
- * @brief Inserts the module typename into the list of modules to create, creates if already instantiated
- */
- static void _Insert(typename type)
- {
- #ifdef CF_TRACE_ENABLED
- auto trace = CF_Trace_1("CF_ModuleCoreManager", "_Insert").Add(type);
- #endif
- string className = type.ToString();
- s_ModuleNames.Insert(className);
- if (s_IsCreated)
- {
- _Create(className);
- }
- }
- /**
- * @brief Creates the module from the name of the class
- */
- static void _Create(string className)
- {
- #ifdef CF_TRACE_ENABLED
- auto trace = CF_Trace_1("CF_ModuleCoreManager", "_Create").Add(className);
- #endif
- typename type = className.ToType();
- if (s_ModulesMap.Contains(type))
- {
- return;
- }
- CF_ModuleCore module;
- if (!Class.CastTo(module, type.Spawn()))
- {
- return;
- }
- s_ModulesMap.Insert(type, module);
- s_Modules.Insert(module);
- module.m_CF_GameFlag = 0;
- if (module.IsClient())
- {
- module.m_CF_GameFlag |= 0x0F;
- }
- if (module.IsServer())
- {
- module.m_CF_GameFlag |= 0xF0;
- }
- module.Init();
- }
- static CF_ModuleCore Get(typename type)
- {
- return s_ModulesMap[type];
- }
- /**
- * @brief Deprecated
- */
- static CF_ModuleCore GetModule(typename type)
- {
- return s_ModulesMap[type];
- }
- static CF_ModuleCore Get(string type)
- {
- return s_ModulesMap[type.ToType()];
- }
- static CF_ModuleCore Get(int index)
- {
- return s_Modules[index];
- }
- static int Count()
- {
- return s_Modules.Count();
- }
- // EVENTS
- static void OnMissionStart(Class sender, CF_EventArgs args)
- {
- s_MissionStart.OnMissionStart(sender, args);
- delete args;
- }
- static void OnMissionFinish(Class sender, CF_EventArgs args)
- {
- s_MissionFinish.OnMissionFinish(sender, args);
- delete args;
- }
- static void OnMissionLoaded(Class sender, CF_EventArgs args)
- {
- s_MissionLoaded.OnMissionLoaded(sender, args);
- delete args;
- }
- static void OnSettingsChanged(Class sender, CF_EventArgs args)
- {
- s_SettingsChanged.OnSettingsChanged(sender, args);
- delete args;
- }
- static void OnPermissionsChanged(Class sender, CF_EventArgs args)
- {
- s_PermissionsChanged.OnPermissionsChanged(sender, args);
- delete args;
- }
- static void OnWorldCleanup(Class sender, CF_EventArgs args)
- {
- s_WorldCleanup.OnWorldCleanup(sender, args);
- delete args;
- }
- static void OnMPSessionStart(Class sender, CF_EventArgs args)
- {
- s_MPSessionStart.OnMPSessionStart(sender, args);
- delete args;
- }
- static void OnMPSessionPlayerReady(Class sender, CF_EventArgs args)
- {
- s_MPSessionPlayerReady.OnMPSessionPlayerReady(sender, args);
- delete args;
- }
- static void OnMPSessionFail(Class sender, CF_EventArgs args)
- {
- s_MPSessionFail.OnMPSessionFail(sender, args);
- delete args;
- }
- static void OnMPSessionEnd(Class sender, CF_EventArgs args)
- {
- s_MPSessionEnd.OnMPSessionEnd(sender, args);
- delete args;
- }
- static void OnMPConnectAbort(Class sender, CF_EventArgs args)
- {
- s_MPConnectAbort.OnMPConnectAbort(sender, args);
- delete args;
- }
- static void OnMPConnectionLost(Class sender, CF_EventArgs args)
- {
- s_MPConnectionLost.OnMPConnectionLost(sender, args);
- delete args;
- }
- static void OnRespawn(Class sender, CF_EventArgs args)
- {
- s_Respawn.OnRespawn(sender, args);
- delete args;
- }
- static void OnLoginTime(Class sender, CF_EventArgs args)
- {
- s_LoginTime.OnLoginTime(sender, args);
- delete args;
- }
- static void OnLoginStatus(Class sender, CF_EventArgs args)
- {
- s_LoginStatus.OnLoginStatus(sender, args);
- delete args;
- }
- static void OnLogout(Class sender, CF_EventArgs args)
- {
- s_Logout.OnLogout(sender, args);
- delete args;
- }
- static void OnChat(Class sender, CF_EventArgs args)
- {
- s_Chat.OnChat(sender, args);
- delete args;
- }
- };
- class CF_Modules<Class T>
- {
- static T Get()
- {
- typename type = T;
- T module;
- Class.CastTo(module, CF_ModuleCoreManager.s_ModulesMap[type]);
- return module;
- }
- static bool Get(inout T module)
- {
- typename type = T;
- return Class.CastTo(module, CF_ModuleCoreManager.s_ModulesMap[type]);
- }
- };
- class CF_RegisterModule
- {
- void CF_RegisterModule(typename type)
- {
- CF_ModuleCoreManager._Insert(type);
- }
- };
- /**
- * EnMath.c
- *
- * DayZ Expansion Mod
- * www.dayzexpansion.com
- * © 2020 DayZ Expansion Mod Team
- *
- * This work is licensed under the Creative Commons Attribution-NonCommercial-NoDerivatives 4.0 International License.
- * To view a copy of this license, visit http://creativecommons.org/licenses/by-nc-nd/4.0/.
- *
- */
- modded class Math
- {
- /**
- * @brief Returns the direction the number is facing, 0 if zero
- *
- * @return float
- */
- static float Sign( float number )
- {
- if ( number > 0 )
- return 1;
- if ( number < 0 )
- return -1;
- return 1;
- }
- /**
- * @brief Returns the direction the number is facing
- *
- * @return float
- */
- static float SignNoNeg( float number )
- {
- if ( number < 0 )
- return -1;
- return 1;
- }
- /**
- * @brief Square the number but keeping the sign
- *
- * @return float
- */
- static float SquareSign( float number )
- {
- return number * number * Sign( number );
- }
- /**
- * @brief (n * (n + 1)) * Sign(n)
- *
- * @return float
- */
- static float SquareSignPercent( float number )
- {
- return number * ( 1 + number ) * Sign( number );
- }
- static float Interpolate( float value, float cMin, float cMax, float vMin, float vMax )
- {
- if ( value <= cMin )
- return vMin;
- if ( value >= cMax )
- return vMax;
- return ( value - cMin ) / ( cMax - cMin ) * ( vMax - vMin ) + vMin;
- }
- static bool AngleDir( float a, float b )
- {
- float fR1 = a - b;
- float fR2 = b - a;
- if ( fR1 < 0 )
- fR1 += 360;
- if ( fR2 < 0 )
- fR2 += 360;
- return fR2 < fR1;
- }
- static float AngleDiff( float a, float b )
- {
- float angle = 180 - Math.AbsFloat( Math.AbsFloat( a - b ) - 180 );
- if ( a + angle != b )
- return -angle;
- return angle;
- }
- };class CF_RegisterTypeConverter
- {
- void CF_RegisterTypeConverter(typename type)
- {
- CF_TypeConverter._Insert(type);
- }
- };
- class CF_TypeConverter
- {
- private static autoptr array<string> m_TypeConverterNames = new array<string>();
- private static autoptr map<typename, CF_TypeConverterBase> m_TypeConvertersMap = new map<typename, CF_TypeConverterBase>();
- private static autoptr array<autoptr CF_TypeConverterBase> m_TypeConverters = new array<autoptr CF_TypeConverterBase>();
- private static bool m_IsCreated;
- private void CF_TypeConverter()
- {
- #ifdef CF_TRACE_ENABLED
- auto trace = CF_Trace_0(this, "CF_TypeConverter");
- #endif
- }
- void ~CF_TypeConverter()
- {
- #ifdef CF_TRACE_ENABLED
- auto trace = CF_Trace_0(this, "~CF_TypeConverter");
- #endif
- }
- static void _OnCreate()
- {
- #ifdef CF_TRACE_ENABLED
- auto trace = CF_Trace_0("CF_TypeConverter", "_OnCreate");
- #endif
- _OnDestroy();
- m_IsCreated = true;
- for (int i = 0; i < m_TypeConverterNames.Count(); i++)
- {
- _Create(m_TypeConverterNames[i]);
- }
- }
- static void _OnDestroy()
- {
- #ifdef CF_TRACE_ENABLED
- auto trace = CF_Trace_0("CF_TypeConverter", "_OnDestroy");
- #endif
- m_TypeConvertersMap.Clear();
- m_TypeConverters.Clear();
- m_IsCreated = false;
- }
- /**
- * @brief Inserts the typeconverter typename into the list of typeconverters to create, creates if already instantiated
- */
- static void _Insert(typename type)
- {
- #ifdef CF_TRACE_ENABLED
- auto trace = CF_Trace_1("Insert").Add(type);
- #endif
- string className = type.ToString();
- m_TypeConverterNames.Insert(className);
- if (m_IsCreated)
- {
- _Create(className);
- }
- }
- /**
- * @brief Creates the typeconverter from the name of the class
- */
- static void _Create(string className)
- {
- #ifdef CF_TRACE_ENABLED
- auto trace = CF_Trace_1("Create").Add(className);
- #endif
- CF_TypeConverterBase converter;
- if (!Class.CastTo(converter, className.ToType().Spawn()))
- {
- return;
- }
- if (m_TypeConvertersMap.Contains(converter.GetType()))
- {
- return;
- }
- m_TypeConvertersMap.Insert(converter.GetType(), converter);
- m_TypeConverters.Insert(converter);
- }
- static CF_TypeConverterBase Get(typename type)
- {
- #ifdef CF_TRACE_ENABLED
- auto trace = CF_Trace_1("Get").Add(type);
- #endif
- CF_TypeConverterBase converter;
- if (!m_TypeConvertersMap.Find(type, converter))
- {
- // if the type converter wasn't found, iterate over the list to find the inherited type and add it
- typename inputType = type;
- for (int i = m_TypeConverters.Count() - 1; i >= 0; i--)
- {
- if (type.IsInherited(m_TypeConverters[i].GetType()))
- {
- type = m_TypeConverters[i].GetType();
- break;
- }
- }
- if (type == inputType)
- {
- CF_Log.Error("Type Converter not found for type=" + type);
- return null;
- }
- m_TypeConvertersMap.Find(type, converter);
- }
- return converter;
- }
- static CF_TypeConverterBase Get(Class instance, string variableName)
- {
- if (!instance)
- {
- return null;
- }
- typename instanceType = instance.Type();
- int count = instanceType.GetVariableCount();
- for (int index = 0; index < count; index++)
- {
- if (CF_String.EqualsIgnoreCase(variableName, instanceType.GetVariableName(index)))
- {
- typename variableType = instanceType.GetVariableType(index);
- return Get(variableType);
- }
- }
- return null;
- }
- };
- /**
- * @brief Super implementation to handle all possible conversions.
- */
- class CF_TypeConverterBase : Managed
- {
- void SetInt(int value)
- {
- }
- int GetInt()
- {
- return 0;
- }
- void SetBool(bool value)
- {
- }
- bool GetBool()
- {
- return false;
- }
- void SetFloat(float value)
- {
- }
- float GetFloat()
- {
- return 0;
- }
- void SetVector(vector value)
- {
- }
- vector GetVector()
- {
- return "0 0 0";
- }
- void SetString(string value)
- {
- }
- string GetString()
- {
- return "";
- }
- void SetClass(Class value)
- {
- }
- Class GetClass()
- {
- return null;
- }
- void SetManaged(Managed value)
- {
- }
- Managed GetManaged()
- {
- return null;
- }
- typename GetType()
- {
- typename type;
- return type;
- }
- override string GetDebugName()
- {
- return "[" + this + "] " + GetString();
- }
- bool IsIOSupported()
- {
- return false;
- }
- bool Read(Serializer ctx)
- {
- #ifdef CF_TRACE_ENABLED
- auto trace = CF_Trace_1(this, "Read").Add(ctx);
- #endif
- CF_Log.Error("" + ClassName() + "::Read(Serializer) not implemented");
- return false;
- }
- bool Write(Serializer ctx)
- {
- #ifdef CF_TRACE_ENABLED
- auto trace = CF_Trace_1(this, "Write").Add(ctx);
- #endif
- CF_Log.Error("" + ClassName() + "::Write(Serializer) not implemented");
- return false;
- }
- bool Read(CF_IO io)
- {
- #ifdef CF_TRACE_ENABLED
- auto trace = CF_Trace_1(this, "Read").Add(io);
- #endif
- CF_Log.Error("" + ClassName() + "::Read(CF_IO) not implemented");
- return false;
- }
- bool Write(CF_IO io)
- {
- #ifdef CF_TRACE_ENABLED
- auto trace = CF_Trace_1(this, "Write").Add(io);
- #endif
- CF_Log.Error("" + ClassName() + "::Write(CF_IO) not implemented");
- return false;
- }
- bool Read(Class instance, string variableName)
- {
- #ifdef CF_TRACE_ENABLED
- auto trace = CF_Trace_2(this, "Read").Add(instance).Add(variableName);
- #endif
- CF_Log.Error("" + ClassName() + "::Read(Class, string) not implemented");
- return false;
- }
- bool Write(Class instance, string variableName)
- {
- #ifdef CF_TRACE_ENABLED
- auto trace = CF_Trace_2(this, "Write").Add(instance).Add(variableName);
- #endif
- CF_Log.Error("" + ClassName() + "::Write(Class, string) not implemented");
- return false;
- }
- bool Read(Class instance, int variableIndex)
- {
- #ifdef CF_TRACE_ENABLED
- auto trace = CF_Trace_2(this, "Read").Add(instance).Add(variableIndex);
- #endif
- CF_Log.Error("" + ClassName() + "::Read(Class, int) not implemented");
- return false;
- }
- };
- /**
- * @brief Template
- */
- class CF_TypeConverterT<Class T> : CF_TypeConverterBase
- {
- protected T m_Value;
- void Set(T value)
- {
- m_Value = value;
- }
- T Get()
- {
- return m_Value;
- }
- override typename GetType()
- {
- typename type = T;
- return type;
- }
- override bool Read(Serializer ctx)
- {
- #ifdef CF_TRACE_ENABLED
- auto trace = CF_Trace_1(this, "Read").Add(ctx);
- #endif
- return ctx.Read(m_Value);
- }
- override bool Write(Serializer ctx)
- {
- #ifdef CF_TRACE_ENABLED
- auto trace = CF_Trace_1(this, "Write").Add(ctx);
- #endif
- return ctx.Write(m_Value);
- }
- override bool Read(Class instance, string variableName)
- {
- #ifdef CF_TRACE_ENABLED
- auto trace = CF_Trace_2(this, "Read").Add(instance).Add(variableName);
- #endif
- EnScript.GetClassVar(instance, variableName, 0, m_Value);
- return true;
- }
- override bool Write(Class instance, string variableName)
- {
- #ifdef CF_TRACE_ENABLED
- auto trace = CF_Trace_2(this, "Write").Add(instance).Add(variableName);
- #endif
- EnScript.SetClassVar(instance, variableName, 0, m_Value);
- return true;
- }
- override bool Read(Class instance, int variableIndex)
- {
- #ifdef CF_TRACE_ENABLED
- auto trace = CF_Trace_2(this, "Read").Add(instance).Add(variableIndex);
- #endif
- typename instanceType = instance.Type();
- typename variableType = instanceType.GetVariableType(variableIndex);
- string variableName = instanceType.GetVariableName(variableIndex);
- // Unfortunately 'Class' type variables results in a hard crash with no discernible pattern to lock them out
- if (variableType.IsInherited(Class)) return false;
- instanceType.GetVariableValue(instance, variableIndex, m_Value);
- return true;
- }
- };
- class CF_SHA256
- {
- static CF_Uint s_K[64] = {
- 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5,
- 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174,
- 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,
- 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967,
- 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85,
- 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,
- 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3,
- 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2
- };
- static CF_Uint s_DataLength;
- static CF_Byte s_Data[64];
- static CF_Byte s_M[64];
- static CF_Uint s_BitLen[2];
- static CF_Uint s_State[8];
- static CF_Byte s_Hash[64];
- static void Process(CF_IO input, CF_IO output)
- {
- Process(input, output.m_Stream);
- }
- static void Process(CF_IO input, CF_Stream output)
- {
- if (!input) return;
- if (!input.m_Stream) return;
- input.m_Stream.SetPositionAtStart();
- s_DataLength = 0;
- s_BitLen[0] = 0;
- s_BitLen[1] = 0;
- s_State[0] = 0x6a09e667;
- s_State[1] = 0xbb67ae85;
- s_State[2] = 0x3c6ef372;
- s_State[3] = 0xa54ff53a;
- s_State[4] = 0x510e527f;
- s_State[5] = 0x9b05688c;
- s_State[6] = 0x1f83d9ab;
- s_State[7] = 0x5be0cd19;
- while (!input.EOF())
- {
- s_Data[s_DataLength] = input.ReadByte();
- s_DataLength++;
- if (s_DataLength == 64)
- {
- _Transform();
- _AdjustBitLength(512);
- s_DataLength = 0;
- }
- }
- CF_Uint i = s_DataLength;
- if (s_DataLength < 56)
- {
- s_Data[i++] = 0x80;
- while (i < 56)
- s_Data[i++] = 0x00;
- }
- else
- {
- s_Data[i++] = 0x80;
- while (i < 64)
- s_Data[i++] = 0x00;
- _Transform();
- }
- _AdjustBitLength(s_DataLength * 8);
- s_Data[63] = s_BitLen[0];
- s_Data[62] = s_BitLen[0].ShiftRight(8);
- s_Data[61] = s_BitLen[0].ShiftRight(16);
- s_Data[60] = s_BitLen[0].ShiftRight(24);
- s_Data[59] = s_BitLen[1];
- s_Data[58] = s_BitLen[1].ShiftRight(8);
- s_Data[57] = s_BitLen[1].ShiftRight(16);
- s_Data[56] = s_BitLen[1].ShiftRight(24);
- _Transform();
- for (i = 0; i < 4; ++i)
- {
- int shift = 24 - (i * 8);
- s_Hash[i ] = s_State[0].ShiftRight(shift);
- s_Hash[i + 4 ] = s_State[1].ShiftRight(shift);
- s_Hash[i + 8 ] = s_State[2].ShiftRight(shift);
- s_Hash[i + 12] = s_State[3].ShiftRight(shift);
- s_Hash[i + 16] = s_State[4].ShiftRight(shift);
- s_Hash[i + 20] = s_State[5].ShiftRight(shift);
- s_Hash[i + 24] = s_State[6].ShiftRight(shift);
- s_Hash[i + 28] = s_State[7].ShiftRight(shift);
- }
- for (i = 0; i < 32; ++i)
- {
- output.Append(s_Hash[i] & 255);
- }
- }
- static void _Transform()
- {
- CF_Uint a, b, c, d, e, f, g, h, i, j, t1, t2;
- for (i = 0; i < 64; ++i) s_M[i] = 0;
- for (i = 0; i < 16; ++i)
- {
- CF_Uint l1_a = s_Data[j] << 24;
- CF_Uint l1_b = s_Data[j + 1] << 16;
- CF_Uint l1_c = s_Data[j + 2] << 8;
- CF_Uint l1_d = s_Data[j + 3];
- s_M[i] = (l1_a | l1_b | l1_c | l1_d);
- j += 4;
- }
- for (; i < 64; ++i)
- {
- CF_Uint l2_a = s_M[i - 2];
- CF_Uint l2_b = CF_Uint.SIG1(l2_a);
- CF_Uint l2_c = s_M[i - 7];
- CF_Uint l2_d = s_M[i - 15];
- CF_Uint l2_e = CF_Uint.SIG0(l2_d);
- CF_Uint l2_f = s_M[i - 16];
- s_M[i] = l2_b + l2_c + l2_e + l2_f;
- }
- a = s_State[0];
- b = s_State[1];
- c = s_State[2];
- d = s_State[3];
- e = s_State[4];
- f = s_State[5];
- g = s_State[6];
- h = s_State[7];
- for (i = 0; i < 64; ++i)
- {
- t1 = h.Add(CF_Uint.EP1(e)).Add(CF_Uint.CH(e, f, g)).Add(s_K[i]).Add(s_M[i]); //h + EP1(e) + CH(e, f, g) + s_K[i] + s_M[i];
- t2 = CF_Uint.EP0(a).Add(CF_Uint.MAJ(a, b, c)); //EP0(a) + MAJ(a, b, c);
- h = g;
- g = f;
- f = e;
- e = d.Add(t1); //d + t1;
- d = c;
- c = b;
- b = a;
- a = t1.Add(t2); //t1 + t2;
- }
- s_State[0] = s_State[0] + a;
- s_State[1] = s_State[1] + b;
- s_State[2] = s_State[2] + c;
- s_State[3] = s_State[3] + d;
- s_State[4] = s_State[4] + e;
- s_State[5] = s_State[5] + f;
- s_State[6] = s_State[6] + g;
- s_State[7] = s_State[7] + h;
- }
- static void _AdjustBitLength(CF_Uint c)
- {
- CF_Uint max_int = 0xffffffff;
- CF_Uint test = max_int - c;
- if (s_BitLen[0].IsGt(test)) //if a > test (unsigned comparison)
- {
- s_BitLen[1] = s_BitLen[1] + 1;
- }
- s_BitLen[0] = s_BitLen[0].Add(c); // A + C using unsigned math
- }
- };
- class CF_EventSubscriber
- {
- /**
- * @brief ATTRIBUTE Register a function as subscriber of up to 9 CF_EventHandler instances.
- * If you need more than 9, please use the CF_MultiEventSubscriber attribute instead.
- *
- * @code
- * [CF_EventSubscriber(ScriptCaller.Create(HandlerFunction), Event1, Event2, Event3 ... Event9)]
- * void HandlerFunction(Class sender, CF_EventArgs args) {}
- * @endcode
- *
- * @param subscriber Function to register as subscriber.
- * @param evt1...9 CF_EventHandler instances to subscribe to.
- * @return void.
- */
- void CF_EventSubscriber(ScriptCaller subscriber,
- CF_EventHandlerBase evt1 = NULL,
- CF_EventHandlerBase evt2 = NULL,
- CF_EventHandlerBase evt3 = NULL,
- CF_EventHandlerBase evt4 = NULL,
- CF_EventHandlerBase evt5 = NULL,
- CF_EventHandlerBase evt6 = NULL,
- CF_EventHandlerBase evt7 = NULL,
- CF_EventHandlerBase evt8 = NULL,
- CF_EventHandlerBase evt9 = NULL)
- {
- UpdateSubscriptions(subscriber, {evt1, evt2, evt3, evt4, evt5, evt6, evt7, evt8, evt9});
- }
- static void UpdateSubscriptions(ScriptCaller subscriber, array<CF_EventHandlerBase> events)
- {
- foreach (CF_EventHandlerBase addEvent : events)
- {
- if (addEvent)
- addEvent.AddSubscriber(subscriber);
- }
- }
- }
- class CF_MultiEventSubscriber
- {
- /**
- * @brief ATTRIBUTE Register a function as subscriber of multiple CF_EventHandler instances.
- * If you only need to subscribe to 9 or less instances, use the regular CF_EventSubscriber attribute instead.
- *
- * @code
- * [CF_MultiEventSubscriber(ScriptCaller.Create(HandlerFunction), {Event1, Event2, Event3 ... EventN})]
- * void HandlerFunction(Class sender, CF_EventArgs args) {}
- * @endcode
- *
- * @param subscriber Function to register as subscriber.
- * @param events Array of CF_EventHandler instances to subscribe to. Use the static array initializer syntax: {<data here>}.
- * @return void.
- */
- void CF_MultiEventSubscriber(ScriptCaller subscriber, array<CF_EventHandlerBase> events)
- {
- CF_EventSubscriber.UpdateSubscriptions(subscriber, events);
- }
- };
- // DO NOT REMOVE!!! For some reason without this there is a compile error cf_eventhandler.c(39): Too many parameters for 'Get' method ...
- typedef array<ref ScriptCaller> CF_ScriptInvoker;
- class CF_EventHandlerBase //Base class to be able to accept both CF_EventHandler and CF_EventHandlerT as function parameter
- {
- protected autoptr CF_ScriptInvoker m_aCallers = {};
- void AddSubscriber(ScriptCaller caller)
- {
- #ifdef CF_TRACE_ENABLED
- auto trace = CF_Trace_0(this, "AddSubscriber");
- #endif
- #ifndef DAYZ_1_21
- // Make sure we do not add the same caller twice
- foreach (ScriptCaller existingCaller : m_aCallers)
- {
- if (existingCaller && existingCaller.IsValid() && existingCaller.Equals(caller))
- return;
- }
- #endif
- m_aCallers.Insert(caller);
- }
- void RemoveSubscriber(ScriptCaller caller)
- {
- #ifdef CF_TRACE_ENABLED
- auto trace = CF_Trace_0(this, "RemoveSubscriber");
- #endif
- m_aCallers.RemoveItem(caller);
- }
- void CF_EventHandlerBase()
- {
- #ifdef CF_TRACE_ENABLED
- auto trace = CF_Trace_0(this, "CF_EventHandlerBase");
- #endif
- }
- void ~CF_EventHandlerBase()
- {
- #ifdef CF_TRACE_ENABLED
- auto trace = CF_Trace_0(this, "~CF_EventHandlerBase");
- #endif
- }
- }
- class CF_EventHandlerT<Class TEventArgs> extends CF_EventHandlerBase
- {
- void Invoke(Class sender = NULL, TEventArgs args = NULL)
- {
- #ifdef CF_TRACE_ENABLED
- auto trace = CF_Trace_2(this, "Invoke").Add(sender).Add(args);
- #endif
- foreach (auto caller : m_aCallers)
- {
- #ifndef DAYZ_1_21
- if (caller && caller.IsValid())
- #else
- if (caller)
- #endif
- caller.Invoke(sender, args);
- }
- }
- }
- class CF_EventHandler extends CF_EventHandlerT<CF_EventArgs>
- {
- }
- class CF_LifecycleEvents
- {
- static const autoptr CF_EventHandler OnGameCreate = new CF_EventHandler();
- static const autoptr CF_EventHandler OnGameDestroy = new CF_EventHandler();
- static const autoptr CF_EventHandler OnMissionCreate = new CF_EventHandler();
- static const autoptr CF_EventHandler OnMissionDestroy = new CF_EventHandler();
- //!Single static class. Do not create with new or spawn - use CF_LifecycleEvents.<something> for access instead.
- protected void CF_LifecycleEvents()
- {
- #ifdef CF_TRACE_ENABLED
- auto trace = CF_Trace_0(this, "CF_LifecycleEvents");
- #endif
- }
- protected void ~CF_LifecycleEvents()
- {
- #ifdef CF_TRACE_ENABLED
- auto trace = CF_Trace_0(this, "~CF_LifecycleEvents");
- #endif
- }
- }
- /* TODO: Move to Community Framework */
- class __Stack<Class T>
- {
- private T _data[256];
- private int _count;
- void __Stack()
- {
- }
- T Pop()
- {
- T value;
- if ( _count <= 0 )
- {
- _count = 0;
- } else
- {
- value = _data[ _count - 1 ];
- _count--;
- }
- return value;
- }
- T Peek()
- {
- return _data[ _count - 1 ];
- }
- T Push( T value )
- {
- _data[ _count ] = value;
- _count++;
- return value;
- }
- array<T> ToArray()
- {
- array<T> arr = new array<T>();
- for ( int i = 0; i < _count; i++ )
- arr.Insert(_data[i]);
- return arr;
- }
- void Clear()
- {
- _count = 0;
- }
- T Get( int idx )
- {
- return _data[idx];
- }
- void Set( int idx, T value )
- {
- _data[idx] = value;
- }
- int Count()
- {
- return _count;
- }
- };CGame CF_CreateGame()
- {
- // Already assigns 'g_Game'
- CreateGame();
- CF._GameInit();
- return g_Game;
- }
- typedef CommunityFramework CF;
- class CommunityFramework : ModStructure
- {
- static CF_ObjectManager ObjectManager;
- static CF_XML XML;
- /**
- * @brief [Internal] CommunityFramework initilization for 3_Game
- *
- * @return void
- */
- static void _GameInit()
- {
- }
- /**
- * @brief [Internal] CommunityFramework cleanup
- *
- * @return void
- */
- static void _Cleanup()
- {
- ObjectManager._Cleanup();
- XML._Cleanup();
- }
- /**
- * @brief Checks if the game is host
- */
- static bool IsMissionHost()
- {
- if (!g_Game) return false;
- return g_Game.IsServer() || !g_Game.IsMultiplayer();
- }
- /**
- * @brief Checks if the game is client
- */
- static bool IsMissionClient()
- {
- if (!g_Game) return false;
- return g_Game.IsClient() || !g_Game.IsMultiplayer();
- }
- /**
- * @brief Checks if the game is singleplayer
- */
- static bool IsMissionOffline()
- {
- if (!g_Game) return false;
- return g_Game.IsServer() && !g_Game.IsMultiplayer();
- }
- };
- class JM_CommunityFramework : CommunityFramework
- {
- };
- //--------------------------------------------------------
- const autoptr TStringArray _cf_characters = {
- // "",
- // "",
- // "",
- // "",
- // "",
- // "",
- // "",
- // "",
- // "",
- // "",
- // "",
- // "",
- // "",
- // "",
- // "",
- // "",
- // "",
- // "",
- // "",
- // "",
- // "",
- // "",
- // "",
- // "",
- // "",
- // "",
- // "",
- // "",
- // "",
- // "",
- // "",
- // "",
- " ",
- "!",
- "\"",
- "#",
- "$",
- "%",
- "&",
- "\'",
- "(",
- ")",
- "*",
- "+",
- ",",
- "-",
- ".",
- "/",
- "0",
- "1",
- "2",
- "3",
- "4",
- "5",
- "6",
- "7",
- "8",
- "9",
- ":",
- ";",
- "<",
- "=",
- ">",
- "?",
- "@",
- "A",
- "B",
- "C",
- "D",
- "E",
- "F",
- "G",
- "H",
- "I",
- "J",
- "K",
- "L",
- "M",
- "N",
- "O",
- "P",
- "Q",
- "R",
- "S",
- "T",
- "U",
- "V",
- "W",
- "X",
- "Y",
- "Z",
- "[",
- "\\",
- "]",
- "^",
- "_",
- "`",
- "a",
- "b",
- "c",
- "d",
- "e",
- "f",
- "g",
- "h",
- "i",
- "j",
- "k",
- "l",
- "m",
- "n",
- "o",
- "p",
- "q",
- "r",
- "s",
- "t",
- "u",
- "v",
- "w",
- "x",
- "y",
- "z",
- "{",
- "|",
- "}",
- "~",
- ""
- };
- //TODO: remove this when the CF refactor is completed
- static string CF_XML_Indent( int level )
- {
- string str = "";
- for ( int i = 0; i < level; ++i )
- str += "\t";
- return str;
- }
- static bool IsMissionHost()
- {
- if ( !GetGame() )
- return false;
- return GetGame().IsServer() || !GetGame().IsMultiplayer();
- }
- static bool IsMissionClient()
- {
- if ( !GetGame() )
- return false;
- return GetGame().IsClient() || !GetGame().IsMultiplayer();
- }
- static bool IsMissionOffline()
- {
- if ( !GetGame() )
- return false;
- return GetGame().IsServer() && !GetGame().IsMultiplayer();
- }
- static string CF_Indent( int level )
- {
- string str = "";
- for ( int i = 0; i < level; ++i )
- str += " ";
- return str;
- }
- static void CF_DumpWidgets( Widget root, int tabs = 0 )
- {
- if ( !root )
- {
- return;
- }
- string tmp;
- for ( int i = 0; i < tabs; i++ )
- {
- tmp += " ";
- }
- string invisible = "";
- if ( !root.IsVisibleHierarchy() )
- {
- invisible = "[invisible]";
- }
- Print( tmp + "- " + root.GetName() + " (" + root.GetTypeName() + ") " + invisible );
- bool collapse = false;
- if ( root.GetChildren() )
- {
- collapse = true;
- Print( tmp + "{" );
- }
- CF_DumpWidgets( root.GetChildren(), tabs + 1 );
- if ( collapse )
- {
- Print( tmp + "}" );
- }
- CF_DumpWidgets( root.GetSibling(), tabs );
- }
- static void Assert_Log( string str, int offset = 1 )
- {
- Print( "==============================================WARNING=======================================================" );
- string time = CF_Date.Now( false ).Format( CF_Date.DATETIME );
- Print( "[WARNING " + time + "] " + str );
- Print( "Do you see this message? Unless the time is within a second of the crash than this was not the cause." );
- string dump = "";
- DumpStackString(dump);
- array<string> outputs = new array<string>();
- dump.Split("\n", outputs);
- for (int i = offset; i < outputs.Count(); i++)
- {
- Print("\t" + outputs[i]);
- }
- Print( "============================================================================================================" );
- }
- static bool Assert_Empty( string str, string message = "" )
- {
- if ( str == "" )
- {
- if ( message != "" )
- message = ": " + message;
- Assert_Log( "ASSERTION STRING EMPTY" + message, 2 );
- return true;
- }
- return false;
- }
- static bool Assert_Null( Class cls, string message = "" )
- {
- if ( cls == NULL )
- {
- if ( message != "" )
- message = ": " + message;
- Assert_Log( "ASSERTION NULL" + message, 2 );
- return true;
- }
- return false;
- }
- static bool Assert_False( bool cls, string message = "" )
- {
- if ( cls == false )
- {
- if ( message != "" )
- message = ": " + message;
- Assert_Log( "ASSERTION FALSE" + message, 2 );
- return true;
- }
- return false;
- }
- static bool Assert_True( bool cls, string message = "" )
- {
- if ( cls == true )
- {
- if ( message != "" )
- message = ": " + message;
- Assert_Log( "ASSERTION TRUE" + message, 2 );
- return true;
- }
- return false;
- }class ConfigArray : ConfigEntry
- {
- override string GetType()
- {
- return "ARRAY";
- }
- override bool IsArray()
- {
- return true;
- }
- override ConfigArray GetArray()
- {
- return this;
- }
- override bool Parse( ConfigReader reader, ConfigFile file )
- {
- string c = reader.SkipWhitespace();
- if ( c != "{" )
- {
- reader.Error( "'" + c + "' encountered instead of '{'" );
- return false;
- }
- for ( int vpp = 0; vpp < 100; vpp++ )
- {
- c = reader.SkipWhitespace();
- reader.BackChar();
- ConfigArrayParam entry = NULL;
- if ( c == "{" )
- {
- entry = new ConfigArrayParamArray();
- entry._parent = this;
- if ( !entry.Parse( reader, file ) )
- return false;
- } else
- {
- bool quoted;
- string value = reader.GetQuotedWord( quoted );
- if ( value.Length() > 0 )
- {
- if ( quoted )
- {
- entry = new ConfigArrayParamText();
- entry._parent = this;
- entry.SetText( value );
- } else
- {
- if ( value.Contains( "." ) )
- {
- entry = new ConfigArrayParamFloat();
- entry.SetFloat( value.ToFloat() );
- entry._parent = this;
- } else
- {
- entry = new ConfigArrayParamInt();
- entry.SetInt( value.ToInt() );
- entry._parent = this;
- }
- }
- }
- }
- if ( entry )
- _entries.Insert( entry );
- c = reader.SkipWhitespace();
- if ( c == "}" )
- return true;
- if ( c != "," && c != ";" )
- {
- reader.Error( "'" + c + "' encounted instead of ','" );
- return false;
- }
- }
- reader.Error( "Prematurely ending the array reading, going for too long." );
- return false;
- }
- };class ConfigArrayParam : ConfigEntry
- {
- override string GetType()
- {
- return "ARRAY_PARAM_BASE";
- }
- override bool IsArrayParam()
- {
- return true;
- }
- };class ConfigArrayParamArray : ConfigArrayParam
- {
- private ref ConfigArray _value = new ConfigArray();
- void ~ConfigArrayParamArray()
- {
- #ifdef CF_TRACE_ENABLED
- auto trace = CF_Trace_0(this);
- #endif
- }
- override string GetType()
- {
- return "ARRAY_PARAM";
- }
- override ConfigArray GetArray()
- {
- return _value;
- }
- override bool IsArray()
- {
- return true;
- }
- };class ConfigArrayParamFloat : ConfigArrayParam
- {
- private float _value;
- override string GetType()
- {
- return "FLOAT_PARAM";
- }
- override bool IsFloat()
- {
- return true;
- }
- override float GetFloat()
- {
- return _value;
- }
- override void SetFloat( float value )
- {
- _value = value;
- }
- };class ConfigArrayParamInt : ConfigArrayParam
- {
- private int _value;
- override string GetType()
- {
- return "INT_PARAM";
- }
- override bool IsInt()
- {
- return true;
- }
- override int GetInt()
- {
- return _value;
- }
- override void SetInt( int value )
- {
- _value = value;
- }
- };class ConfigArrayParamLong : ConfigArrayParam
- {
- private int _value;
- override string GetType()
- {
- return "LONG_PARAM";
- }
- override bool IsLong()
- {
- return true;
- }
- override int GetLong()
- {
- return _value;
- }
- override void SetLong( int value )
- {
- _value = value;
- }
- };class ConfigArrayParamText : ConfigArrayParam
- {
- private string _value;
- override string GetType()
- {
- return "TEXT_PARAM";
- }
- override bool IsText()
- {
- return true;
- }
- override string GetText()
- {
- return _value;
- }
- override void SetText( string value )
- {
- _value = value;
- }
- };class ConfigClassDeclaration : ConfigClass
- {
- override bool IsClassDecl()
- {
- return true;
- }
- };
- class ConfigDelete : ConfigEntry
- {
- override bool IsDelete()
- {
- return true;
- }
- };
- class ConfigClass : ConfigEntry
- {
- private ConfigClass _base;
- void ConfigClass()
- {
- }
- override string GetType()
- {
- return "CLASS";
- }
- override ConfigClass GetClass()
- {
- return this;
- }
- ConfigClass GetBase()
- {
- return _base;
- }
- private ConfigClass SetBase( string name )
- {
- int baseIndex = _parent.FindIndex( name );
- int thisIndex = _parent.FindIndex( _name );
- if ( baseIndex >= 0 && ( baseIndex < thisIndex || thisIndex < 0 ) )
- {
- return _parent._entries[ baseIndex ].GetClass();
- }
- ConfigEntry possibleEntry = NULL;
- if ( _parent.GetClass()._base != NULL )
- {
- possibleEntry = _parent.GetClass()._base.Find( name, true, true );
- }
- if ( possibleEntry == NULL && _parent._parent != NULL )
- {
- possibleEntry = _parent._parent.GetClass().Find( name, true, true );
- }
- if ( possibleEntry != NULL && possibleEntry.IsClass() )
- {
- return possibleEntry.GetClass();
- }
- return NULL;
- }
- ConfigEntry Find( string name, bool checkParent, bool checkBase )
- {
- int idx = FindIndex( name, true );
- if ( idx >= 0 )
- return _entries[idx];
- ConfigEntry entry = NULL;
- if ( checkBase && _base != NULL )
- {
- entry = _base.Find( name, true, true );
- if ( entry != NULL )
- return entry;
- }
- if ( checkParent && _parent != NULL && _parent.GetClass() != NULL )
- {
- entry = _parent.GetClass().Find( name, true, checkBase );
- if ( entry != NULL )
- return entry;
- }
- return NULL;
- }
- override bool Parse( ConfigReader reader, ConfigFile file )
- {
- for ( int vpp = 0; vpp < 100; vpp++ )
- {
- string c = reader.SkipWhitespace();
- if ( reader.EOF() )
- {
- if ( this == file )
- return true;
- reader.Error( "Unexpected EOF reached." );
- return false;
- }
- if ( c == "#" )
- {
- reader.NextLine();
- } else if (c == "}" )
- {
- c = reader.GetCharacter();
- while ( reader.IsWhitespace( c ) || c == ";" )
- c = reader.GetCharacter();
- reader.BackChar();
- return true;
- }
- reader.BackChar();
- ConfigEntry entry = NULL;
- string name = "";
- string token = reader.GetWord();
- if ( token == "delete" )
- {
- name = reader.GetWord();
- c = reader.SkipWhitespace();
- if ( c == ";" )
- {
- entry = new ConfigDelete();
- entry._name = name;
- entry._parent = this;
- } else
- {
- reader.Error( "'" + c + "' encountered instead of ';'" );
- return false;
- }
- } else if ( token == "class" )
- {
- name = reader.GetWord();
- c = reader.SkipWhitespace();
- if ( c == ";" )
- {
- entry = new ConfigClassDeclaration();
- entry._name = name;
- entry._parent = this;
- } else
- {
- entry = new ConfigClass();
- entry._name = name;
- entry._parent = this;
- if ( c == ":" )
- {
- string baseName = reader.GetWord();
- ConfigEntry baseEntry = Find( baseName, true, true );
- if ( baseEntry == NULL )
- {
- reader.Error( "Undefined base class '" + baseName + "'" );
- return false;
- }
- if ( !baseEntry.IsClass() )
- {
- reader.Error( "'" + baseName + "' is not a class" );
- return false;
- }
- entry.GetClass()._base = baseEntry.GetClass();
- c = reader.GetCharacter();
- }
- while ( c != "{" )
- {
- if ( !reader.IsWhitespace(c) )
- {
- reader.Error( "'" + c + "' encountered instead of '{'");
- return false;
- }
- c = reader.GetCharacter();
- }
- if ( !entry.Parse( reader, file ) )
- return false;
- }
- } else if ( token == "enum" )
- {
- reader.Error( "Enum is not supported");
- return false;
- } else if ( token != "" )
- {
- c = reader.GetCharacter();
- name = token;
- if ( c == "[" )
- {
- c = reader.SkipWhitespace();
- if (c != "]")
- {
- reader.Error( "'" + c + "' encountered instead of ']'" );
- return false;
- }
- c = reader.SkipWhitespace();
- if (c != "=")
- {
- reader.Error( "'" + c + "' encountered instead of '='" );
- return false;
- }
- entry = new ConfigArray();
- entry._name = name;
- entry._parent = this;
- if ( !entry.Parse( reader, file ) )
- return false;
- c = reader.SkipWhitespace();
- if ( c != ";")
- {
- reader.Error( "'" + c + "' encountered instead of ';'" );
- return false;
- }
- } else
- {
- while ( reader.IsWhitespace( c ) )
- c = reader.GetCharacter();
- if ( c != "=" )
- {
- reader.Error( "'" + c + "' encountered instead of '='" );
- return false;
- }
- bool quoted;
- string value = reader.GetQuotedWord( quoted );
- c = reader.SkipWhitespace();
- if (c == "}" )
- {
- reader.Warning( "'" + c + "' encountered instead of ';'" );
- reader.BackChar();
- } else if (c != ";" )
- {
- reader.Error( "Missing ';' at the end of the line" );
- return false;
- // TODO: resolve
- /*
- if (c != '\n' && c != '\r')
- {
- if (!quoted)
- {
- ParseError(input, $"'{(char)c}' encountered instead of ';'");
- return false;
- }
- input.BackChar()
- }
- ParseWarning(input, $"Missing ';' at the end of the line");
- */
- }
- if ( quoted )
- {
- entry = new ConfigValueText();
- entry._name = name;
- entry.SetText( value );
- entry._parent = this;
- } else
- {
- if ( value.Contains( "." ) )
- {
- entry = new ConfigValueFloat();
- entry._name = name;
- entry.SetFloat( value.ToFloat() );
- entry._parent = this;
- } else
- {
- entry = new ConfigValueInt();
- entry._name = name;
- entry.SetInt( value.ToInt() );
- entry._parent = this;
- }
- }
- }
- }
- if ( entry != NULL )
- {
- int idx = FindIndex( entry._name );
- if ( idx < 0)
- {
- _entries.Insert( entry );
- } else
- {
- reader.Error( "'" + entry._name + "' already defined" );
- }
- }
- }
- reader.Error( "Prematurely ending the class reading, going for too long." );
- return false;
- }
- };class ConfigEntry : Managed
- {
- protected ref array< ref ConfigEntry > _entries;
- protected ref ConfigEntry _parent;
- protected string _name;
- void ConfigEntry()
- {
- _entries = new array< ref ConfigEntry >();
- _parent = NULL;
- _name = "";
- }
- string GetType()
- {
- return "ENTRY";
- }
- string GetName()
- {
- return _name;
- }
- ConfigEntry GetParent()
- {
- return _parent;
- }
- ConfigClass GetClass()
- {
- return NULL;
- }
- bool IsValue()
- {
- return false;
- }
- bool IsClass()
- {
- return true;
- }
- bool IsClassDecl()
- {
- return true;
- }
- bool IsDelete()
- {
- return true;
- }
- bool IsText()
- {
- return false;
- }
- string GetText()
- {
- return "";
- }
- void SetText( string value )
- {
- }
- bool IsFloat()
- {
- return false;
- }
- float GetFloat()
- {
- return 0;
- }
- void SetFloat( float value )
- {
- }
- bool IsInt()
- {
- return false;
- }
- int GetInt()
- {
- return 0;
- }
- void SetInt( int value )
- {
- }
- bool IsLong()
- {
- return false;
- }
- int GetLong()
- {
- return 0;
- }
- void SetLong( int value )
- {
- }
- ConfigArray GetArray()
- {
- return NULL;
- }
- bool IsArrayParam()
- {
- return false;
- }
- bool IsArray()
- {
- return false;
- }
- int Count()
- {
- return _entries.Count();
- }
- ConfigEntry Get( int i )
- {
- return _entries[i];
- }
- int FindIndex( string name, bool isClass = false )
- {
- for ( int i = 0; i < _entries.Count(); i++ )
- {
- if ( isClass && !_entries[i].IsClass() )
- continue;
- if ( _entries[i]._name == name )
- return i;
- }
- return -1;
- }
- bool Parse( ConfigReader reader, ConfigFile file )
- {
- CF_Log.Error( "Not implemented." );
- return false;
- }
- ConfigEntry Get( string path )
- {
- TStringArray tokens = new TStringArray;
- path.Split( " ", tokens );
- return Get( tokens, 0 );
- }
- ConfigEntry Get( TStringArray tokens, int index = 0 )
- {
- string lowerToken = "" + tokens[ index ];
- lowerToken.ToLower();
- for ( int k = 0; k < _entries.Count(); ++k )
- {
- string nameLower = "" + _entries[k]._name;
- nameLower.ToLower();
- if ( lowerToken == nameLower )
- {
- if ( index + 1 >= tokens.Count() )
- {
- return _entries[k];
- }
- return _entries[k].Get( tokens, index + 1 );
- }
- }
- if ( IsClass() && GetClass().GetBase() != NULL )
- {
- return GetClass().GetBase().Get( tokens, index );
- }
- return NULL;
- }
- };
- class ConfigFile : ConfigClass
- {
- private ref ConfigReader _reader;
- private void ConfigFile()
- {
- }
- override string GetType()
- {
- return "FILE";
- }
- static ConfigFile Parse( string fileName )
- {
- ConfigFile file = new ConfigFile();
- file.Parse( ConfigReader.Open( fileName ), file );
- return file;
- }
- };class ConfigReader : Managed
- {
- private int _arrIdx = 0;
- private int _bufIdx = -1;
- private ref array< string > _lines = new array< string >;
- private void ConfigReader()
- {
- #ifdef CF_TRACE_ENABLED
- auto trace = CF_Trace_0(this);
- #endif
- }
- void ~ConfigReader()
- {
- #ifdef CF_TRACE_ENABLED
- auto trace = CF_Trace_0(this);
- #endif
- }
- static ConfigReader Open( string path )
- {
- ConfigReader reader = new ConfigReader();
- FileHandle fileHandle = OpenFile( path, FileMode.READ );
- string lineContent;
- while ( FGets( fileHandle, lineContent ) >= 0 )
- {
- if ( lineContent.Length() != 0 )
- {
- reader._lines.Insert( lineContent );
- }
- }
- CloseFile( fileHandle );
- return reader;
- }
- string BackChar()
- {
- _bufIdx--;
- if ( _bufIdx < 0 )
- {
- if ( !PreviousLine() )
- {
- return "";
- }
- }
- return _lines[_arrIdx].Substring( _bufIdx, 1 );
- }
- private string ReadChar()
- {
- _bufIdx++;
- if ( _bufIdx >= _lines[_arrIdx].Length() )
- {
- if ( !NextLine() )
- {
- return "";
- }
- }
- return _lines[_arrIdx].Substring( _bufIdx, 1 );
- }
- bool NextLine()
- {
- _bufIdx = 0;
- _arrIdx++;
- while ( _arrIdx < _lines.Count() )
- {
- if ( _lines[_arrIdx].Length() <= 0 )
- _arrIdx++;
- else
- return true;
- }
- return false;
- }
- bool PreviousLine()
- {
- _arrIdx--;
- while ( _arrIdx >= 0 )
- {
- if ( _lines[_arrIdx].Length() <= 0 )
- _arrIdx--;
- else
- {
- _bufIdx = _lines[_arrIdx].Length() - 1;
- return true;
- }
- }
- return false;
- }
- bool EOF()
- {
- return _arrIdx >= _lines.Count() || ( _arrIdx == _lines.Count() - 1 && _bufIdx >= _lines[_arrIdx].Length() );
- }
- private void SkipComment()
- {
- string c = ReadChar();
- while ( true )
- {
- if ( EOF() )
- {
- CF_Log.Error( "Unexpected end of file while parsing XML comment!" );
- break;
- }
- if ( c != "*" )
- {
- c = ReadChar();
- continue;
- }
- BackChar();
- string check = ReadChar();
- if ( check == "/" )
- {
- return;
- } else
- {
- c = ReadChar();
- }
- }
- }
- string GetCharacter()
- {
- string c = ReadChar();
- while ( true )
- {
- if ( c == "/" )
- {
- c = ReadChar();
- if ( c == "/" )
- {
- NextLine();
- } else if ( c == "*" )
- {
- SkipComment();
- } else
- {
- BackChar();
- return c;
- }
- } else
- {
- return c;
- }
- c = ReadChar();
- }
- return c;
- }
- bool IsWhitespace( string c )
- {
- if ( c == " " )
- return true;
- if ( c == "\t" )
- return true;
- if ( c == "\n" )
- return true;
- if ( c == "\r" )
- return true;
- //if ( c == "" )
- // Error( "Unexpected end of string" );
- return false;
- }
- bool IsLetterOrDigit( string c )
- {
- return IsLetterOrDigit( c, false );
- }
- bool IsLetterOrDigit( string c, bool isQuoted )
- {
- int i = _cf_characters.Find( c );
- if ( i == -1 )
- {
- return false;
- }
- if ( isQuoted )
- {
- return i >= 32 && i <= 126;
- }
- if ( i >= 48 && i <= 57 )
- {
- return true;
- }
- if ( i > 90 )
- i -= 32;
- if ( i >= 65 && i <= 90 )
- {
- return true;
- }
- return false;
- }
- string SkipWhitespace()
- {
- string c = GetCharacter();
- while ( IsWhitespace( c ) )
- c = GetCharacter();
- return c;
- }
- string GetWord()
- {
- string word = "";
- string c = SkipWhitespace();
- while ( IsLetterOrDigit( c ) )
- {
- word = word + c;
- c = GetCharacter();
- }
- BackChar();
- return word;
- }
- string GetQuotedWord( out bool isQuoted )
- {
- string word = "";
- string c = SkipWhitespace();
- if ( c == "\"" )
- {
- c = "";
- isQuoted = true;
- } else
- {
- isQuoted = false;
- }
- while ( ( IsLetterOrDigit( c, isQuoted ) || c == "" ) && !EOF() )
- {
- word = word + c;
- c = GetCharacter();
- if ( isQuoted && c == "\"" )
- {
- return word;
- }
- }
- BackChar();
- return word;
- }
- void Error( string msg )
- {
- CF_Log.Error( "[" + ( _arrIdx + 1 ) + ":" + _bufIdx + "] " + msg );
- }
- void Warning( string msg )
- {
- CF_Log.Warn( "[" + ( _arrIdx + 1 ) + ":" + _bufIdx + "] " + msg );
- }
- };class ConfigValue : ConfigEntry
- {
- override string GetType()
- {
- return "VALUE";
- }
- override bool IsValue()
- {
- return true;
- }
- }class ConfigValueFloat : ConfigValue
- {
- private float _value;
- override string GetType()
- {
- return "FLOAT";
- }
- override bool IsFloat()
- {
- return true;
- }
- override float GetFloat()
- {
- return _value;
- }
- override void SetFloat( float value )
- {
- _value = value;
- }
- };class ConfigValueInt : ConfigValue
- {
- private int _value;
- override string GetType()
- {
- return "INT";
- }
- override bool IsInt()
- {
- return true;
- }
- override int GetInt()
- {
- return _value;
- }
- override void SetInt( int value )
- {
- _value = value;
- }
- };class ConfigValueLong : ConfigValue
- {
- private int _value;
- override string GetType()
- {
- return "LONG";
- }
- override bool IsLong()
- {
- return true;
- }
- override int GetLong()
- {
- return _value;
- }
- override void SetLong( int value )
- {
- _value = value;
- }
- };class ConfigValueText : ConfigValue
- {
- private string _value;
- override string GetType()
- {
- return "TEXT";
- }
- override bool IsText()
- {
- return true;
- }
- override string GetText()
- {
- return _value;
- }
- override void SetText( string value )
- {
- _value = value;
- }
- };enum ConfigValueTypes
- {
- Text,
- Float,
- Int,
- Array,
- UKN_1,
- UKN_2,
- Int64
- };/*
- Epoch Mod for DayZ Standalone
- FileName: CreditsLoader.c
- Authors: DayZ SA Epoch Dev Team and Community Contributors
- https://github.com/EpochModTeam/DayZ_SA_Epoch/blob/experimental/README.md
- Licensing:
- https://github.com/EpochModTeam/DayZ_SA_Epoch/blob/experimental/LICENSE.md
- Changelog:
- [1/16/2019] AWOL / DirtySanchez
- AWOL1 - DZSA Epoch Dev Team and Community Credits
- [1/20/2019] AWOL
- AWOL2 - Made credits dynamically support other mods via 'creditsJson' var in CfgMods. Also appended DayZ Game header and credits
- [14/03/2019] Jacob_Mango
- JM3 - Changed the formatting of the credits
- [NewDate] Author(s)
- Initials(Change#)-Description
- */
- modded class CreditsLoader
- {
- override static JsonDataCredits GetData()
- {
- #ifdef CF_TRACE_ENABLED
- auto trace = CF_Trace_0("JsonDataCredits");
- #endif
- JsonDataCredits data = new JsonDataCredits;
- data.Departments = {};
- // get all mods
- array<ref ModStructure> mods = ModLoader.GetMods();
- foreach (auto mod : mods)
- {
- auto credits = mod.GetCredits();
- if (!credits || !credits.Departments)
- continue;
- foreach (auto department : credits.Departments)
- {
- data.Departments.Insert(department);
- }
- }
- // Append DayZ Game Credits Header
- JsonDataCreditsDepartment dayzDepartmentHeader();
- dayzDepartmentHeader.Sections = {};
- dayzDepartmentHeader.DepartmentName = (" DayZ Standalone");
- data.Departments.Insert(dayzDepartmentHeader);
- // Append DayZ Game Credits
- JsonDataCredits dayzCreditsData;
- JsonFileLoader<ref JsonDataCredits>.JsonLoadFile(JSON_FILE_PATH, dayzCreditsData);
- foreach (auto dayzDepartment : dayzCreditsData.Departments)
- {
- data.Departments.Insert(dayzDepartment);
- };
- return data;
- }
- };
- class CF_EventChatArgs : CF_EventArgs
- {
- int Channel;
- string From;
- string Text;
- string ColorConfig;
- void CF_EventChatArgs(int channel, string from, string text, string colorConfig)
- {
- Channel = channel;
- From = from;
- Text = text;
- ColorConfig = colorConfig;
- }
- };
- class CF_EventLoginArgs : CF_EventArgs
- {
- string Line1;
- string Line2;
- void CF_EventLoginArgs(string line1, string line2)
- {
- Line1 = line1;
- Line2 = line2;
- }
- };
- class CF_EventRPCArgs : CF_EventArgs
- {
- PlayerIdentity Sender;
- Object Target;
- int ID;
- Serializer Context;
- };
- class CF_Expression
- {
- protected string m_Source;
- protected int m_Position = -1;
- protected ref CF_ExpressionInstruction m_RootInstruction;
- protected CF_ExpressionInstruction m_TailInstruction;
- void SetSource(string source)
- {
- m_Source = source;
- }
- string GetSource()
- {
- return m_Source;
- }
- protected string BackChar()
- {
- m_Position--;
- if ( m_Position < 0 )
- m_Position = 0;
- return m_Source[m_Position];
- }
- protected string GetChar()
- {
- m_Position++;
- if ( m_Position >= m_Source.Length() )
- m_Position = m_Source.Length();
- return m_Source[m_Position];
- }
- protected bool EOF()
- {
- return m_Position >= m_Source.Length() - 1;
- }
- protected bool IsWhitespace( string c )
- {
- if ( c == " " )
- return true;
- if ( c == "\t" )
- return true;
- if ( c == "\n" )
- return true;
- if ( c == "\r" )
- return true;
- //if ( c == "" )
- // CF_Log.Error( "Unexpected end of string" );
- return false;
- }
- protected bool IsAlphanumeric( string c )
- {
- int i = c.ToAscii();
- if (i >= 42 && i <= 57)
- return true;
- if ( i > 90 )
- i -= 32;
- if ( i >= 65 && i <= 90 )
- return true;
- return false;
- }
- protected bool IsLetterOrDigit( string c )
- {
- int i = c.ToAscii();
- if ( i >= 48 && i <= 57 )
- return true;
- if ( i == 46 )
- return true;
- if ( i > 90 )
- i -= 32;
- if ( i >= 65 && i <= 90 )
- return true;
- return false;
- }
- protected string SkipWhitespace()
- {
- if ( EOF() )
- return "\0";
- string c = GetChar();
- while ( IsWhitespace( c ) && !EOF() )
- c = GetChar();
- return c;
- }
- protected string GetToken()
- {
- string word = "";
- string c = SkipWhitespace();
- if ( c == "[" || c == "]" || c == "(" || c == ")" )
- return c;
- if ( IsAlphanumeric( c ) && !IsLetterOrDigit( c ) )
- return c;
- while ( IsLetterOrDigit( c ) )
- {
- word = word + c;
- if ( EOF() )
- return word;
- c = GetChar();
- if ( c == "[" || c == "]" || c == "(" || c == ")" || word == "/" || word == "*" )
- break;
- }
- m_Position--;
- return word;
- }
- protected bool IsNumber( string word )
- {
- bool decimal = false;
- for ( int i = 0; i < word.Length(); i++ )
- {
- int c = word.Get(i).ToAscii();
- if ( c == 46 )
- {
- if ( decimal )
- return false;
- decimal = true;
- }
- else if ( !( c >= 48 && c <= 57 ) )
- {
- return false;
- }
- }
- return true;
- }
- float CompileEvaluate( map< string, float > variables )
- {
- if ( Compile( variables.GetKeyArray() ) )
- return Evaluate( variables.GetValueArray() );
- return 0;
- }
- /**
- * @note Test function
- */
- float CompileEvaluateTest( map< string, float > variables, bool test )
- {
- if ( CompileTest( variables.GetKeyArray(), test ) )
- return EvaluateTest( variables.GetValueArray(), test );
- return 0;
- }
- bool Compile( array< string > variables )
- {
- _Compile( variables );
- return true;
- }
- /**
- * @note Test function
- */
- bool CompileTest( array< string > variables, bool test )
- {
- int start = TickCount( 0 );
- bool success = Compile( variables );
- int time = TickCount( start );
- if ( test )
- CF_Log.Info( "CF_Expression::Compile took " + time + " ticks to execute." );
- return success;
- }
- float Evaluate( array< float > variables )
- {
- //! Make sure the evaluation position is set at the start
- m_Position = -1;
- return _Evaluate( variables );
- }
- float Evaluate()
- {
- //! Make sure the evaluation position is set at the start
- m_Position = -1;
- return _Evaluate(new array<float>());
- }
- /**
- * @note Test function
- */
- float EvaluateTest( array< float > variables, bool test )
- {
- int start = TickCount( 0 );
- m_Position = -1;
- float num = _Evaluate( variables );
- int time = TickCount( start );
- if ( test )
- CF_Log.Info( "CF_Expression::Evaluate took " + time + " ticks to execute." );
- return num;
- }
- protected float _Evaluate( array< float > variables )
- {
- CF_ExpressionVM.StackPointer = 0;
- CF_ExpressionVM.Variables = variables;
- CF_ExpressionVM.CurrentInstruction = m_RootInstruction;
- while (CF_ExpressionVM.CurrentInstruction)
- {
- CF_ExpressionVM.CurrentInstruction.Call();
- CF_ExpressionVM.CurrentInstruction = CF_ExpressionVM.CurrentInstruction.next;
- }
- return CF_ExpressionVM.Stack[CF_ExpressionVM.StackPointer];
- }
- protected void ClearInstructions()
- {
- m_RootInstruction = null;
- }
- protected void AddInstruction(CF_ExpressionInstruction instruction)
- {
- if (!m_RootInstruction)
- {
- m_RootInstruction = instruction;
- m_TailInstruction = instruction;
- return;
- }
- m_TailInstruction.next = instruction;
- m_TailInstruction = instruction;
- }
- protected int _Compile( array< string > variables )
- {
- return 0;
- }
- string ToRPN()
- {
- return _ToRPN();
- }
- /**
- * @note Test function
- */
- string ToRPN( bool test )
- {
- int start = TickCount( 0 );
- string rpn = _ToRPN();
- int time = TickCount( start );
- CF_Log.Info( "CF_Expression::ToRPN took " + time + " ticks to execute." );
- return rpn;
- }
- /**
- * @brief Converts the compiled expression into Reverse Polish Notation
- *
- * @return string
- */
- private string _ToRPN()
- {
- string rpn = string.Empty;
- if (!m_RootInstruction)
- return "0"; //! edge case because I managed to accidentally optimize this out
- CF_ExpressionInstruction instruction = m_RootInstruction;
- bool first = true;
- while (instruction)
- {
- if (!first) rpn = rpn + " ";
- first = false;
- rpn = rpn + instruction.GetDebugName();
- CF_ExpressionFunctionDef function;
- if (CF_ExpressionVM.Find(instruction.GetDebugName(), function))
- {
- //! instruction doesn't store parameters in an array for memory reasons
- if ( function.params != 0 )
- {
- rpn = rpn + " [";
- if ( function.params >= 4 )
- {
- rpn = rpn + instruction.param1;
- rpn = rpn + ", ";
- rpn = rpn + instruction.param2;
- rpn = rpn + ", ";
- rpn = rpn + instruction.param3;
- rpn = rpn + ", ";
- rpn = rpn + instruction.param4;
- } else if ( function.params >= 3 )
- {
- rpn = rpn + instruction.param1;
- rpn = rpn + ", ";
- rpn = rpn + instruction.param2;
- rpn = rpn + ", ";
- rpn = rpn + instruction.param3;
- } else if ( function.params >= 2 )
- {
- rpn = rpn + instruction.param1;
- rpn = rpn + ", ";
- rpn = rpn + instruction.param2;
- } else if ( function.params >= 1 )
- {
- rpn = rpn + instruction.param1;
- }
- rpn = rpn + "]";
- }
- }
- instruction = instruction.next;
- }
- return rpn;
- }
- };
- /*
- * Private class
- */
- class CF_ExpressionCompileToken
- {
- string token;
- ref array< float > parameters;
- void CF_ExpressionCompileToken( string _token )
- {
- token = _token;
- parameters = new array< float >();
- }
- CF_ExpressionInstruction ToOperation(CF_ExpressionFunctionDef funcDef, int variableIdx = -1)
- {
- CF_ExpressionInstruction instruction;
- if (funcDef)
- {
- instruction = funcDef.SpawnFunction();
- }
- else
- {
- instruction = new CF_ExpressionInstruction();
- }
- instruction.SetFields(token, parameters, variableIdx);
- return instruction;
- }
- };
- class CF_ExpressionFunction : CF_ExpressionInstruction
- {
- };
- class CF_ExpressionFunctionDef
- {
- int params = 0;
- int precedence = 1;
- bool associative = true;
- typename type = CF_ExpressionFunction;
- void CF_ExpressionFunctionDef(typename _type, int _params = 0, int _precedence = 1, bool _associative = true)
- {
- params = _params;
- precedence = _precedence;
- associative = _associative;
- type = _type;
- }
- CF_ExpressionFunction SpawnFunction()
- {
- return CF_ExpressionFunction.Cast(type.Spawn());
- }
- };
- class CF_ExpressionFunctionValue : CF_ExpressionFunction
- {
- static string CF_NAME = "#INTERNAL_0";
- [CF_EventSubscriber(ScriptCaller.Create(CF_ExpressionFunctionValue.Init), CF_LifecycleEvents.OnGameCreate)]
- static void Init()
- {
- CF_ExpressionVM.AddFunction(CF_NAME, new CF_ExpressionFunctionDef(CF_ExpressionFunctionValue, -1));
- }
- override void Call()
- {
- CF_ExpressionVM.Stack[++CF_ExpressionVM.StackPointer] = value;
- }
- override string GetDebugName()
- {
- return "" + value;
- }
- };
- class CF_ExpressionFunctionVariable : CF_ExpressionFunction
- {
- static string CF_NAME = "#INTERNAL_1";
- [CF_EventSubscriber(ScriptCaller.Create(CF_ExpressionFunctionVariable.Init), CF_LifecycleEvents.OnGameCreate)]
- static void Init()
- {
- CF_ExpressionVM.AddFunction(CF_NAME, new CF_ExpressionFunctionDef(CF_ExpressionFunctionVariable, -1));
- }
- override void Call()
- {
- CF_ExpressionVM.Stack[++CF_ExpressionVM.StackPointer] = CF_ExpressionVM.Variables[variableIndex];
- }
- override string GetDebugName()
- {
- return token;
- }
- };
- class CF_ExpressionFunctionPow : CF_ExpressionFunction
- {
- static string CF_NAME = "^";
- [CF_EventSubscriber(ScriptCaller.Create(CF_ExpressionFunctionPow.Init), CF_LifecycleEvents.OnGameCreate)]
- static void Init()
- {
- CF_ExpressionVM.AddFunction(CF_NAME, new CF_ExpressionFunctionDef(CF_ExpressionFunctionPow, 0, 4, false));
- }
- override void Call()
- {
- CF_ExpressionVM.Stack[CF_ExpressionVM.StackPointer] = Math.Pow(CF_ExpressionVM.Stack[CF_ExpressionVM.StackPointer--], CF_ExpressionVM.Stack[CF_ExpressionVM.StackPointer]);
- }
- override string GetDebugName()
- {
- return CF_NAME;
- }
- };
- class CF_ExpressionFunctionMul : CF_ExpressionFunction
- {
- static string CF_NAME = "*";
- [CF_EventSubscriber(ScriptCaller.Create(CF_ExpressionFunctionMul.Init), CF_LifecycleEvents.OnGameCreate)]
- static void Init()
- {
- CF_ExpressionVM.AddFunction(CF_NAME, new CF_ExpressionFunctionDef(CF_ExpressionFunctionMul, 0, 3, true));
- }
- override void Call()
- {
- CF_ExpressionVM.Stack[CF_ExpressionVM.StackPointer] = CF_ExpressionVM.Stack[CF_ExpressionVM.StackPointer--] * CF_ExpressionVM.Stack[CF_ExpressionVM.StackPointer];
- }
- override string GetDebugName()
- {
- return CF_NAME;
- }
- };
- class CF_ExpressionFunctionDiv : CF_ExpressionFunction
- {
- static string CF_NAME = "/";
- [CF_EventSubscriber(ScriptCaller.Create(CF_ExpressionFunctionDiv.Init), CF_LifecycleEvents.OnGameCreate)]
- static void Init()
- {
- CF_ExpressionVM.AddFunction(CF_NAME, new CF_ExpressionFunctionDef(CF_ExpressionFunctionDiv, 0, 3, true));
- }
- override void Call()
- {
- CF_ExpressionVM.StackPointer--;
- CF_ExpressionVM.Stack[CF_ExpressionVM.StackPointer] = CF_ExpressionVM.Stack[CF_ExpressionVM.StackPointer] / CF_ExpressionVM.Stack[CF_ExpressionVM.StackPointer + 1];
- }
- override string GetDebugName()
- {
- return CF_NAME;
- }
- };
- class CF_ExpressionFunctionAdd : CF_ExpressionFunction
- {
- static string CF_NAME = "+";
- [CF_EventSubscriber(ScriptCaller.Create(CF_ExpressionFunctionAdd.Init), CF_LifecycleEvents.OnGameCreate)]
- static void Init()
- {
- CF_ExpressionVM.AddFunction(CF_NAME, new CF_ExpressionFunctionDef(CF_ExpressionFunctionAdd, 0, 2, true));
- }
- override void Call()
- {
- CF_ExpressionVM.Stack[CF_ExpressionVM.StackPointer] = CF_ExpressionVM.Stack[CF_ExpressionVM.StackPointer--] + CF_ExpressionVM.Stack[CF_ExpressionVM.StackPointer];
- }
- override string GetDebugName()
- {
- return CF_NAME;
- }
- };
- class CF_ExpressionFunctionSub : CF_ExpressionFunction
- {
- static string CF_NAME = "-";
- [CF_EventSubscriber(ScriptCaller.Create(CF_ExpressionFunctionSub.Init), CF_LifecycleEvents.OnGameCreate)]
- static void Init()
- {
- CF_ExpressionVM.AddFunction(CF_NAME, new CF_ExpressionFunctionDef(CF_ExpressionFunctionSub, 0, 2, true));
- }
- override void Call()
- {
- CF_ExpressionVM.StackPointer--;
- CF_ExpressionVM.Stack[CF_ExpressionVM.StackPointer] = CF_ExpressionVM.Stack[CF_ExpressionVM.StackPointer] - CF_ExpressionVM.Stack[CF_ExpressionVM.StackPointer + 1];
- }
- override string GetDebugName()
- {
- return CF_NAME;
- }
- };
- class CF_ExpressionFunctionFactor : CF_ExpressionFunction
- {
- static string CF_NAME = "factor";
- [CF_EventSubscriber(ScriptCaller.Create(CF_ExpressionFunctionFactor.Init), CF_LifecycleEvents.OnGameCreate)]
- static void Init()
- {
- CF_ExpressionVM.AddFunction(CF_NAME, new CF_ExpressionFunctionDef(CF_ExpressionFunctionFactor, 2));
- }
- override void Call()
- {
- CF_ExpressionVM.Stack[CF_ExpressionVM.StackPointer] = (Math.Clamp(CF_ExpressionVM.Stack[CF_ExpressionVM.StackPointer], param1, param2) - param1) / (param2 - param1);
- }
- override string GetDebugName()
- {
- return CF_NAME;
- }
- };
- class CF_ExpressionFunctionReverseFactor : CF_ExpressionFunction
- {
- static string CF_NAME = "#factor_reverse";
- [CF_EventSubscriber(ScriptCaller.Create(CF_ExpressionFunctionReverseFactor.Init), CF_LifecycleEvents.OnGameCreate)]
- static void Init()
- {
- CF_ExpressionVM.AddFunction(CF_NAME, new CF_ExpressionFunctionDef(CF_ExpressionFunctionReverseFactor, 2));
- }
- override void Call()
- {
- CF_ExpressionVM.Stack[CF_ExpressionVM.StackPointer] = 1.0 - (Math.Clamp(CF_ExpressionVM.Stack[CF_ExpressionVM.StackPointer], param2, param1) - param2) / (param1 - param2);
- }
- override string GetDebugName()
- {
- return CF_NAME;
- }
- };
- class CF_ExpressionFunctionCos : CF_ExpressionFunction
- {
- static string CF_NAME = "cos";
- [CF_EventSubscriber(ScriptCaller.Create(CF_ExpressionFunctionCos.Init), CF_LifecycleEvents.OnGameCreate)]
- static void Init()
- {
- CF_ExpressionVM.AddFunction(CF_NAME, new CF_ExpressionFunctionDef(CF_ExpressionFunctionCos));
- }
- override void Call()
- {
- CF_ExpressionVM.Stack[CF_ExpressionVM.StackPointer] = Math.Cos(CF_ExpressionVM.Stack[CF_ExpressionVM.StackPointer]);
- }
- override string GetDebugName()
- {
- return CF_NAME;
- }
- };
- class CF_ExpressionFunctionSin : CF_ExpressionFunction
- {
- static string CF_NAME = "sin";
- [CF_EventSubscriber(ScriptCaller.Create(CF_ExpressionFunctionSin.Init), CF_LifecycleEvents.OnGameCreate)]
- static void Init()
- {
- CF_ExpressionVM.AddFunction(CF_NAME, new CF_ExpressionFunctionDef(CF_ExpressionFunctionSin));
- }
- override void Call()
- {
- CF_ExpressionVM.Stack[CF_ExpressionVM.StackPointer] = Math.Sin(CF_ExpressionVM.Stack[CF_ExpressionVM.StackPointer]);
- }
- override string GetDebugName()
- {
- return CF_NAME;
- }
- };
- class CF_ExpressionFunctionMin : CF_ExpressionFunction
- {
- static string CF_NAME = "min";
- [CF_EventSubscriber(ScriptCaller.Create(CF_ExpressionFunctionMin.Init), CF_LifecycleEvents.OnGameCreate)]
- static void Init()
- {
- CF_ExpressionVM.AddFunction(CF_NAME, new CF_ExpressionFunctionDef(CF_ExpressionFunctionMin));
- }
- override void Call()
- {
- CF_ExpressionVM.Stack[CF_ExpressionVM.StackPointer] = Math.Min(CF_ExpressionVM.Stack[CF_ExpressionVM.StackPointer--], CF_ExpressionVM.Stack[CF_ExpressionVM.StackPointer]);
- }
- override string GetDebugName()
- {
- return CF_NAME;
- }
- };
- class CF_ExpressionFunctionMax : CF_ExpressionFunction
- {
- static string CF_NAME = "max";
- [CF_EventSubscriber(ScriptCaller.Create(CF_ExpressionFunctionMax.Init), CF_LifecycleEvents.OnGameCreate)]
- static void Init()
- {
- CF_ExpressionVM.AddFunction(CF_NAME, new CF_ExpressionFunctionDef(CF_ExpressionFunctionMax));
- }
- override void Call()
- {
- CF_ExpressionVM.Stack[CF_ExpressionVM.StackPointer] = Math.Max(CF_ExpressionVM.Stack[CF_ExpressionVM.StackPointer--], CF_ExpressionVM.Stack[CF_ExpressionVM.StackPointer]);
- }
- override string GetDebugName()
- {
- return CF_NAME;
- }
- };
- /*
- * Private class
- */
- class CF_ExpressionInstruction
- {
- string token;
- float value;
- int variableIndex;
- ref CF_ExpressionInstruction next;
- float param1;
- float param2;
- float param3;
- float param4;
- void SetFields(string _token, array< float > _parameters, int _variableIndex)
- {
- token = _token;
- if (_variableIndex == -2) value = _token.ToFloat();
- variableIndex = _variableIndex;
- //! Setting the variables
- //! This looks bad but the code runs a couple of CPU ticks faster with it like this
- //! For code that is expected to run 1000 times a frame this is important
- if ( _parameters )
- {
- if ( _parameters.Count() >= 4 )
- {
- param1 = _parameters[0];
- param2 = _parameters[1];
- param3 = _parameters[2];
- param4 = _parameters[3];
- } else if ( _parameters.Count() >= 3 )
- {
- param1 = _parameters[0];
- param2 = _parameters[1];
- param3 = _parameters[2];
- } else if ( _parameters.Count() >= 2 )
- {
- param1 = _parameters[0];
- param2 = _parameters[1];
- } else if ( _parameters.Count() >= 1 )
- {
- param1 = _parameters[0];
- }
- }
- }
- void Call();
- override string GetDebugName()
- {
- return ToString();
- }
- };
- class CF_ExpressionStackDebug
- {
- float Get(int index)
- {
- CF_Log.Info("[" + index + "]: " + CF_ExpressionVM.Stack[index] + "");
- return CF_ExpressionVM.Stack[index];
- }
- void Set(int index, float value)
- {
- CF_Log.Info("[" + index + "]: " + CF_ExpressionVM.Stack[index] + " -> " + value + "");
- CF_ExpressionVM.Stack[index] = value;
- }
- };
- #ifdef CF_EXPRESSION_TEST
- class CF_ExpressionTests
- {
- private string _current;
- private int _cpu;
- private int _failed;
- private void CF_ExpressionTests()
- {
- }
- static void Perform()
- {
- CF_ExpressionTests tests = new CF_ExpressionTests();
- tests._Perform();
- }
- static void PerformSingle( string test )
- {
- CF_ExpressionTests tests = new CF_ExpressionTests();
- tests.PerformTest( test );
- }
- protected void Setup( inout array< string > tests )
- {
- tests.Insert("TestMultiplication_SQF_1");
- tests.Insert("TestDivision_SQF_1");
- tests.Insert("TestAddition_SQF_1");
- tests.Insert("TestSubtraction_SQF_1");
- tests.Insert("TestMultiplication_Math_1");
- tests.Insert("TestDivision_Math_1");
- tests.Insert("TestAddition_Math_1");
- tests.Insert("TestSubtraction_Math_1");
- tests.Insert("TestVariable_SQF_1");
- tests.Insert("TestVariable_Math_1");
- tests.Insert("TestFunction_SQF_1");
- tests.Insert("TestFunction_SQF_2");
- tests.Insert("TestFunction_Math_1");
- tests.Insert("TestFunction_Math_1");
- tests.Insert("TestBrackets_SQF_1");
- tests.Insert("TestBrackets_Math_2");
- tests.Insert("TestOrderOfOperations_SQF_1");
- tests.Insert("TestOrderOfOperations_SQF_2");
- tests.Insert("TestOrderOfOperations_Math_1");
- tests.Insert("TestOrderOfOperations_Math_2");
- tests.Insert("TestSound_SQF_1");
- tests.Insert("TestSound_SQF_2");
- tests.Insert("TestSound_Math_1");
- tests.Insert("TestSound_Math_2");
- }
- private void _Perform()
- {
- Print( "Starting tests" );
- array< string > tests = new array< string >();
- Setup( tests );
- _failed = 0;
- int start = TickCount( 0 );
- for ( int i = 0; i < tests.Count(); i++ )
- PerformTest( tests[i] );
- int time = TickCount( start );
- Print("\n");
- if ( _failed == 0 )
- {
- Print( "Success. All " + tests.Count() + " passed!" );
- } else
- {
- Print( "Tests failed. " + ( tests.Count() - _failed ) + "/" + tests.Count() + " passed." );
- }
- }
- private void PerformTest( string method )
- {
- Print("\n");
- Print("Running test \"" + method + "\"");
- _current = method;
- _cpu = TickCount( 0 );
- GetGame().GameScript.CallFunction( this, _current, null, null );
- }
- private void _assert( float expectedNum, float actualNum, string expectedRPN, string actualRPN )
- {
- int time = TickCount( _cpu );
- string info = "Test \"" + _current + "\" took " + time + " ticks to execute.";
- if ( expectedNum != actualNum || expectedRPN != actualRPN )
- {
- Print( " Expected Result: " + expectedNum );
- Print( " Actual Result: " + actualNum );
- Print( " Expected RPN: " + expectedRPN );
- Print( " Actual RPN: " + actualRPN );
- info = "FAILED: " + info;
- _failed++;
- } else
- {
- Print( " Result: " + actualNum );
- Print( " RPN: " + actualRPN );
- info = "PASSED: " + info;
- }
- Print( "" + info );
- Print( "" );
- }
- void TestMultiplication_SQF_1()
- {
- map< string, float > variables = new map< string, float >();
- string expr = "5 * 5";
- CF_Expression test = CF_ExpressionVM.Create(expr, CF_SQFExpression);
- float expectedNum = 5 * 5;
- float actualNum = test.CompileEvaluateTest(variables, true);
- string expectedRPN = "5 5 *";
- string actualRPN = test.ToRPN(true);
- _assert( expectedNum, actualNum, expectedRPN, actualRPN );
- }
- void TestDivision_SQF_1()
- {
- map< string, float > variables = new map< string, float >();
- string expr = "5 / 2";
- CF_Expression test = CF_ExpressionVM.Create(expr, CF_SQFExpression);
- float expectedNum = 5 / 2;
- float actualNum = test.CompileEvaluateTest(variables, true);
- string expectedRPN = "5 2 /";
- string actualRPN = test.ToRPN(true);
- _assert( expectedNum, actualNum, expectedRPN, actualRPN );
- }
- void TestAddition_SQF_1()
- {
- map< string, float > variables = new map< string, float >();
- string expr = "5 + 2";
- CF_Expression test = CF_ExpressionVM.Create(expr, CF_SQFExpression);
- float expectedNum = 5 + 2;
- float actualNum = test.CompileEvaluateTest(variables, true);
- string expectedRPN = "5 2 +";
- string actualRPN = test.ToRPN(true);
- _assert( expectedNum, actualNum, expectedRPN, actualRPN );
- }
- void TestSubtraction_SQF_1()
- {
- map< string, float > variables = new map< string, float >();
- string expr = "5 - 2";
- CF_Expression test = CF_ExpressionVM.Create(expr, CF_SQFExpression);
- float expectedNum = 5 - 2;
- float actualNum = test.CompileEvaluateTest(variables, true);
- string expectedRPN = "5 2 -";
- string actualRPN = test.ToRPN(true);
- _assert( expectedNum, actualNum, expectedRPN, actualRPN );
- }
- void TestMultiplication_Math_1()
- {
- map< string, float > variables = new map< string, float >();
- string expr = "5 * 5";
- CF_Expression test = CF_ExpressionVM.Create(expr, CF_MathExpression);
- float expectedNum = 5 * 5;
- float actualNum = test.CompileEvaluateTest(variables, true);
- string expectedRPN = "5 5 *";
- string actualRPN = test.ToRPN(true);
- _assert( expectedNum, actualNum, expectedRPN, actualRPN );
- }
- void TestDivision_Math_1()
- {
- map< string, float > variables = new map< string, float >();
- string expr = "5 / 2";
- CF_Expression test = CF_ExpressionVM.Create(expr, CF_MathExpression);
- float expectedNum = 5 / 2;
- float actualNum = test.CompileEvaluateTest(variables, true);
- string expectedRPN = "5 2 /";
- string actualRPN = test.ToRPN(true);
- _assert( expectedNum, actualNum, expectedRPN, actualRPN );
- }
- void TestAddition_Math_1()
- {
- map< string, float > variables = new map< string, float >();
- string expr = "5 + 2";
- CF_Expression test = CF_ExpressionVM.Create(expr, CF_MathExpression);
- float expectedNum = 5 + 2;
- float actualNum = test.CompileEvaluateTest(variables, true);
- string expectedRPN = "5 2 +";
- string actualRPN = test.ToRPN(true);
- _assert( expectedNum, actualNum, expectedRPN, actualRPN );
- }
- void TestSubtraction_Math_1()
- {
- map< string, float > variables = new map< string, float >();
- string expr = "5 - 2";
- CF_Expression test = CF_ExpressionVM.Create(expr, CF_MathExpression);
- float expectedNum = 5 - 2;
- float actualNum = test.CompileEvaluateTest(variables, true);
- string expectedRPN = "5 2 -";
- string actualRPN = test.ToRPN(true);
- _assert( expectedNum, actualNum, expectedRPN, actualRPN );
- }
- void TestVariable_SQF_1()
- {
- map< string, float > variables = new map< string, float >();
- variables["speed"] = 45;
- string expr = "speed * 2";
- CF_Expression test = CF_ExpressionVM.Create(expr, CF_SQFExpression);
- float expectedNum = variables["speed"] * 2;
- float actualNum = test.CompileEvaluateTest(variables, true);
- string expectedRPN = "speed 2 *";
- string actualRPN = test.ToRPN(true);
- _assert( expectedNum, actualNum, expectedRPN, actualRPN );
- }
- void TestVariable_Math_1()
- {
- map< string, float > variables = new map< string, float >();
- variables["speed"] = 45;
- string expr = "speed * 2";
- CF_Expression test = CF_ExpressionVM.Create(expr, CF_MathExpression);
- float expectedNum = variables["speed"] * 2;
- float actualNum = test.CompileEvaluateTest(variables, true);
- string expectedRPN = "speed 2 *";
- string actualRPN = test.ToRPN(true);
- _assert( expectedNum, actualNum, expectedRPN, actualRPN );
- }
- void TestFunction_SQF_1()
- {
- map< string, float > variables = new map< string, float >();
- string expr = "4 factor [0, 5]";
- CF_Expression test = CF_ExpressionVM.Create(expr, CF_SQFExpression);
- float expectedNum = Math.Interpolate(4, 0, 5, 0, 1);
- float actualNum = test.CompileEvaluateTest(variables, true);
- string expectedRPN = "4 factor [0, 5]";
- string actualRPN = test.ToRPN(true);
- _assert( expectedNum, actualNum, expectedRPN, actualRPN );
- }
- void TestFunction_SQF_2()
- {
- map< string, float > variables = new map< string, float >();
- variables["angle"] = 45;
- variables["pi"] = Math.PI;
- variables["toRad"] = Math.DEG2RAD;
- variables["toDeg"] = Math.RAD2DEG;
- string expr = "(angle * toRad) cos";
- CF_Expression test = CF_ExpressionVM.Create(expr, CF_SQFExpression);
- float expectedNum = Math.Cos(variables["angle"] * Math.DEG2RAD);
- float actualNum = test.CompileEvaluateTest(variables, true);
- string expectedRPN = "angle toRad * cos";
- string actualRPN = test.ToRPN(true);
- _assert( expectedNum, actualNum, expectedRPN, actualRPN );
- }
- void TestFunction_Math_1()
- {
- map< string, float > variables = new map< string, float >();
- string expr = "factor(4, 0, 5)";
- CF_Expression test = CF_ExpressionVM.Create(expr, CF_MathExpression);
- float expectedNum = Math.Interpolate(4, 0, 5, 0, 1);
- float actualNum = test.CompileEvaluateTest(variables, true);
- string expectedRPN = "4 factor [0, 5]";
- string actualRPN = test.ToRPN(true);
- _assert( expectedNum, actualNum, expectedRPN, actualRPN );
- }
- void TestFunction_Math_2()
- {
- map< string, float > variables = new map< string, float >();
- variables["angle"] = 45;
- variables["pi"] = Math.PI;
- variables["toRad"] = Math.DEG2RAD;
- variables["toDeg"] = Math.RAD2DEG;
- string expr = "cos(angle * toRad)";
- CF_Expression test = CF_ExpressionVM.Create(expr, CF_MathExpression);
- float expectedNum = Math.Cos(variables["angle"] * Math.DEG2RAD);
- float actualNum = test.CompileEvaluateTest(variables, true);
- string expectedRPN = "angle toRad * cos";
- string actualRPN = test.ToRPN(true);
- _assert( expectedNum, actualNum, expectedRPN, actualRPN );
- }
- void TestBrackets_SQF_1()
- {
- map< string, float > variables = new map< string, float >();
- string expr = "3 * (4 - 2) * 2";
- CF_Expression test = CF_ExpressionVM.Create(expr, CF_SQFExpression);
- float expectedNum = 3 * (4 - 2) * 2;
- float actualNum = test.CompileEvaluateTest(variables, true);
- string expectedRPN = "3 4 2 - 2 * *";
- string actualRPN = test.ToRPN(true);
- _assert( expectedNum, actualNum, expectedRPN, actualRPN );
- }
- void TestBrackets_Math_1()
- {
- map< string, float > variables = new map< string, float >();
- string expr = "3 * (4 - 2) * 2";
- CF_Expression test = CF_ExpressionVM.Create(expr, CF_MathExpression);
- float expectedNum = 3 * (4 - 2) * 2;
- float actualNum = test.CompileEvaluateTest(variables, true);
- string expectedRPN = "3 4 2 - 2 * *";
- string actualRPN = test.ToRPN(true);
- _assert( expectedNum, actualNum, expectedRPN, actualRPN );
- }
- void TestOrderOfOperations_SQF_1()
- {
- map< string, float > variables = new map< string, float >();
- string expr = "2 + 5 * 5 + 2";
- CF_Expression test = CF_ExpressionVM.Create(expr, CF_SQFExpression);
- float expectedNum = 2 + 5 * 5 + 2;
- float actualNum = test.CompileEvaluateTest(variables, true);
- string expectedRPN = "2 5 5 * 2 + +";
- string actualRPN = test.ToRPN(true);
- _assert( expectedNum, actualNum, expectedRPN, actualRPN );
- }
- void TestOrderOfOperations_SQF_2()
- {
- map< string, float > variables = new map< string, float >();
- string expr = "5 * 5 - 8 * 8";
- CF_Expression test = CF_ExpressionVM.Create(expr, CF_SQFExpression);
- float expectedNum = 5 * 5 - 8 * 8;
- float actualNum = test.CompileEvaluateTest(variables, true);
- string expectedRPN = "5 5 * 8 8 * -";
- string actualRPN = test.ToRPN(true);
- _assert( expectedNum, actualNum, expectedRPN, actualRPN );
- }
- void TestOrderOfOperations_Math_1()
- {
- map< string, float > variables = new map< string, float >();
- string expr = "2 + 5 * 5 + 2";
- CF_Expression test = CF_ExpressionVM.Create(expr, CF_MathExpression);
- float expectedNum = 2 + 5 * 5 + 2;
- float actualNum = test.CompileEvaluateTest(variables, true);
- string expectedRPN = "2 5 5 * 2 + +";
- string actualRPN = test.ToRPN(true);
- _assert( expectedNum, actualNum, expectedRPN, actualRPN );
- }
- void TestOrderOfOperations_Math_2()
- {
- map< string, float > variables = new map< string, float >();
- string expr = "5 * 5 - 8 * 8";
- CF_Expression test = CF_ExpressionVM.Create(expr, CF_MathExpression);
- float expectedNum = 5 * 5 - 8 * 8;
- float actualNum = test.CompileEvaluateTest(variables, true);
- string expectedRPN = "5 5 * 8 8 * -";
- string actualRPN = test.ToRPN(true);
- _assert( expectedNum, actualNum, expectedRPN, actualRPN );
- }
- void TestSound_SQF_1()
- {
- map< string, float > variables = new map< string, float >();
- variables["rpm"] = 7000;
- variables["doors"] = 0;
- variables["campos"] = 0;
- variables["engineOn"] = 1;
- string expr = "0.75 * 1 * (0.7 + 0.3 * (speed factor [10,60])) * engineOn * 1 * ((850 + ((rpm - 850)/(8000/5600))) factor [(((3250+4400)/2) - 2.5*200),(((3250+4400)/2) + 200)]) * ((1 - 0.25*doors) max campos) * (rpm factor[4800,6200])";
- CF_Expression test = CF_ExpressionVM.Create(expr, CF_SQFExpression);
- float expectedNum = 0.75 * 1 * (0.7 + 0.3 * Math.Interpolate( variables["speed"], 10, 60, 0, 1 ) ) * variables["engineOn"] * 1 * Math.Interpolate(850 + ((variables["rpm"] - 850)/(8000/5600)), (((3250+4400)/2) - 2.5*200),(((3250+4400)/2) + 200), 0, 1) * (Math.Max(1 - 0.25*variables["doors"], variables["campos"]) * Math.Interpolate(variables["rpm"], 4800,6200, 0, 1));
- float actualNum = test.CompileEvaluateTest(variables, true);
- string expectedRPN = "0.75 1 0.7 0.3 speed factor [10, 60] * + engineOn 1 850 rpm 850 - 8000 5600 / / + factor [3325, 4025] 1 0.25 doors * - campos max rpm factor [4800, 6200] * * * * * * *";
- string actualRPN = test.ToRPN(true);
- _assert( expectedNum, actualNum, expectedRPN, actualRPN );
- }
- void TestSound_SQF_2()
- {
- map< string, float > variables = new map< string, float >();
- variables["rpm"] = 1100;
- variables["doors"] = 0;
- variables["campos"] = 0;
- variables["engineOn"] = 1;
- string expr = "0.75 * 1 * engineOn * 0.4 * ((850 + ((rpm - 850)/(8000/5600))) factor [(((850+1200)/2) + 2.5*50),(((850+1200)/2) - 50)]) * ((1 - 0.25*doors) max campos)";
- CF_Expression test = CF_ExpressionVM.Create(expr, CF_SQFExpression);
- float expectedNum = 0.75 * 1 * variables["engineOn"] * 0.4 * Math.Interpolate(850 +((variables["rpm"] - 850)/(8000/5600)),(((850+1200)/2) - 50), (((850+1200)/2) + 2.5*50),0, 1) * Math.Max((1 - 0.25 * variables["doors"]), variables["campos"]);
- float actualNum = test.CompileEvaluateTest(variables, true);
- string expectedRPN = "0.75 1 engineOn 0.4 850 rpm 850 - 8000 5600 / / + factor [975, 1150] 1 0.25 doors * - campos max * * * * *";
- string actualRPN = test.ToRPN(true);
- _assert( expectedNum, actualNum, expectedRPN, actualRPN );
- }
- void TestSound_Math_1()
- {
- map< string, float > variables = new map< string, float >();
- variables["rpm"] = 7000;
- variables["doors"] = 0;
- variables["campos"] = 0;
- variables["engineOn"] = 1;
- string expr = "0.75 * 1 * (0.7 + 0.3 * factor( speed, 10, 60 ) ) * engineOn * 1 * factor(850 + ((rpm - 850)/(8000/5600)), (((3250+4400)/2) - 2.5*200),(((3250+4400)/2) + 200)) * (1 - 0.25*doors max campos) * factor(rpm, 4800,6200)";
- CF_Expression test = CF_ExpressionVM.Create(expr, CF_MathExpression);
- float expectedNum = 0.75 * 1 * (0.7 + 0.3 * Math.Interpolate( variables["speed"], 10, 60, 0, 1 ) ) * variables["engineOn"] * 1 * Math.Interpolate(850 + ((variables["rpm"] - 850)/(8000/5600)), (((3250+4400)/2) - 2.5*200),(((3250+4400)/2) + 200), 0, 1) * (Math.Max(1 - 0.25*variables["doors"], variables["campos"]) * Math.Interpolate(variables["rpm"], 4800,6200, 0, 1));
- float actualNum = test.CompileEvaluateTest(variables, true);
- string expectedRPN = "0.75 1 0.7 0.3 speed factor [10, 60] * + engineOn 1 850 rpm 850 - 8000 5600 / / + 1 0.25 doors campos max * - rpm factor [4800, 6200] * * factor [3325, 4025] * * * * *";
- string actualRPN = test.ToRPN(true);
- _assert( expectedNum, actualNum, expectedRPN, actualRPN );
- }
- void TestSound_Math_2()
- {
- map< string, float > variables = new map< string, float >();
- variables["rpm"] = 1100;
- variables["doors"] = 0;
- variables["campos"] = 0;
- variables["engineOn"] = 1;
- string expr = "0.75 * 1 * engineOn * 0.4 * factor(850 + ((rpm - 850)/(8000/5600)),(((850+1200)/2) + 2.5*50),(((850+1200)/2) - 50)) * ((1 - 0.25*doors) max campos)";
- CF_Expression test = CF_ExpressionVM.Create(expr, CF_MathExpression);
- float expectedNum = 0.75 * 1 * variables["engineOn"] * 0.4 * Math.Interpolate(850 +((variables["rpm"] - 850)/(8000/5600)),(((850+1200)/2) - 50), (((850+1200)/2) + 2.5*50),0, 1) * Math.Max((1 - 0.25 * variables["doors"]), variables["campos"]);
- float actualNum = test.CompileEvaluateTest(variables, true);
- string expectedRPN = "0.75 1 engineOn 0.4 850 rpm 850 - 8000 5600 / / + 1 0.25 doors * - campos max * factor [975, 1150] * * * *";
- string actualRPN = test.ToRPN(true);
- _assert( expectedNum, actualNum, expectedRPN, actualRPN );
- }
- void TestPerformance()
- {
- map< string, float > variables = new map< string, float >();
- variables["rpm"] = 7000;
- variables["doors"] = 0;
- variables["campos"] = 0;
- variables["engineOn"] = 1;
- string expr = "0.75 * 1 * (0.7 + 0.3 * (speed factor [10,60])) * engineOn * 1 * ((850 + ((rpm - 850)/(8000/5600))) factor [(((3250+4400)/2) - 2.5*200),(((3250+4400)/2) + 200)]) * ((1 - 0.25*doors) max campos) * (rpm factor[4800,6200])";
- CF_Expression test = CF_ExpressionVM.Create(expr, CF_SQFExpression);
- float expectedNum = 0.75 * 1 * (0.7 + 0.3 * Math.Interpolate( variables["speed"], 10, 60, 0, 1 ) ) * variables["engineOn"] * 1 * Math.Interpolate(850 + ((variables["rpm"] - 850)/(8000/5600)), (((3250+4400)/2) - 2.5*200),(((3250+4400)/2) + 200), 0, 1) * (Math.Max(1 - 0.25*variables["doors"], variables["campos"]) * Math.Interpolate(variables["rpm"], 4800,6200, 0, 1));
- test.CompileTest(variables.GetKeyArray(), true);
- array<float> varFloats = variables.GetValueArray();
- float actualNum = test.EvaluateTest(varFloats, true);
- string expectedRPN = "0.75 1 0.7 0.3 speed factor [10, 60] * + engineOn 1 850 rpm 850 - 8000 5600 / / + factor [3325, 4025] 1 0.25 doors * - campos max rpm factor [4800, 6200] * * * * * * *";
- string actualRPN = test.ToRPN(true);
- int count = 100000;
- float s_start = GetGame().GetTickTime();
- int t_start = TickCount( 0 );
- for (int i = 0; i < count; i++)
- {
- test.Evaluate(varFloats);
- }
- int t_time = TickCount(t_start);
- float s_time = GetGame().GetTickTime() - s_start;
- Print( "TestPerformance took " + (t_time) + " ticks to execute for " + count + " iterations, an average of " + (t_time / count) + " ticks." );
- Print( "TestPerformance took " + (s_time) + " seconds to execute for " + count + " iterations, an average of " + (s_time / (count / 1000.0)) + " milliseconds." );
- _assert( expectedNum, actualNum, expectedRPN, actualRPN );
- }
- };
- #endif
- class CF_ExpressionVM
- {
- static CF_ExpressionInstruction CurrentInstruction;
- static float Stack[16];
- static ref CF_ExpressionStackDebug StackDebugger = new CF_ExpressionStackDebug();
- static int StackPointer;
- static array<float> Variables;
- private static autoptr map<string, autoptr CF_ExpressionFunctionDef> s_Functions;
- [CF_EventSubscriber(ScriptCaller.Create(CF_ExpressionVM.Destroy), CF_LifecycleEvents.OnGameDestroy)]
- static void Destroy()
- {
- s_Functions = null;
- }
- static void AddFunction(string name, notnull CF_ExpressionFunctionDef function)
- {
- //! Init map
- if (s_Functions == null)
- {
- s_Functions = new map<string, autoptr CF_ExpressionFunctionDef>();
- }
- //! Add the function
- s_Functions[name] = function;
- }
- static CF_Expression Create(string src)
- {
- return Create(src, CF_MathExpression);
- }
- static CF_Expression Create(string src, typename type)
- {
- CF_Expression expr = CF_Expression.Cast(type.Spawn());
- if (expr) expr.SetSource(src);
- return expr;
- }
- static CF_Expression Compile(string src)
- {
- return Compile(src, new array<string>(), CF_MathExpression);
- }
- static CF_Expression Compile(string src, array<string> variables)
- {
- return Compile(src, variables, CF_MathExpression);
- }
- static CF_Expression Compile(string src, typename type)
- {
- return Compile(src, new array<string>(), type);
- }
- static CF_Expression Compile(string src, array<string> variables, typename type)
- {
- CF_Expression expr = Create(src, type);
- expr.Compile(variables);
- return expr;
- }
- static bool Find(string name, inout CF_ExpressionFunctionDef function)
- {
- return s_Functions.Find(name, function);
- }
- static bool Contains(string name)
- {
- return s_Functions.Contains(name);
- }
- };
- class CF_MathExpression : CF_Expression
- {
- //! @Jacob-Mango: I want this to be protected or private but a compile error happens
- int __Compile(array<string> variables)
- {
- array<ref CF_ExpressionCompileToken> dataStackStore();
- __Stack<CF_ExpressionCompileToken> stack();
- CF_ExpressionFunctionDef funcDef;
- CF_ExpressionCompileToken compileToken;
- while (!EOF())
- {
- string token = GetToken();
- token = token.Trim();
- if (token == ",")
- break;
- CF_ExpressionFunctionDef op1;
- CF_ExpressionFunctionDef op2;
- if (CF_ExpressionVM.Find(token, op1))
- {
- compileToken = new CF_ExpressionCompileToken(token);
- dataStackStore.Insert(compileToken);
- int startPosition = m_Position;
- token = SkipWhitespace();
- if (token == "(")
- {
- token = SkipWhitespace();
- int paramidx = 0;
- int nPos;
- m_Position--;
- while (token != ")")
- {
- //! First param can be a variabled expression, i.e. behaves as if this was brackets
- if (paramidx == 0)
- {
- nPos = __Compile(variables);
- m_Position = nPos - 1;
- token = SkipWhitespace();
- }
- else
- {
- CF_Expression parameter = new CF_MathExpression();
- parameter.m_Source = m_Source + "";
- parameter.m_Position = m_Position + 0;
- //! there should be no variables/functions inside a parameter for a function call
- nPos = parameter._Compile(variables);
- float nVal = parameter._Evaluate(new array<float>());
- compileToken.parameters.Insert(nVal);
- m_Position = nPos - 1;
- token = SkipWhitespace();
- }
- paramidx++;
- }
- }
- else
- {
- m_Position = startPosition;
- }
- //! factor function optimization
- if (compileToken.token == CF_ExpressionFunctionFactor.CF_NAME)
- {
- if (compileToken.parameters[1] < compileToken.parameters[0])
- {
- compileToken.token = CF_ExpressionFunctionReverseFactor.CF_NAME;
- }
- }
- while (stack.Count() > 0)
- {
- string tok = stack.Peek().token;
- if (!CF_ExpressionVM.Find(tok, op2))
- break;
- int c = op1.precedence - op2.precedence;
- if (op1.precedence != 1 && (c < 0 || (!op1.associative && c <= 0)))
- AddInstruction(stack.Pop().ToOperation(op2));
- else
- break;
- }
- stack.Push(compileToken);
- }
- else if (token == "(")
- {
- dataStackStore.Insert(stack.Push(new CF_ExpressionCompileToken(token)));
- }
- else if (token == ")")
- {
- string topToken = "";
- while (stack.Count() > 0)
- {
- compileToken = stack.Pop();
- topToken = compileToken.token;
- if ( compileToken.token == "(" )
- break;
- if (CF_ExpressionVM.Find( topToken, funcDef ))
- AddInstruction( compileToken.ToOperation( funcDef ) );
- }
- if (topToken != "(")
- break;
- }
- else
- {
- if ( IsNumber( token ) )
- {
- compileToken = new CF_ExpressionCompileToken( token );
- if (CF_ExpressionVM.Find( CF_ExpressionFunctionValue.CF_NAME, funcDef ))
- {
- AddInstruction( compileToken.ToOperation( funcDef, -2 ) );
- }
- } else
- {
- compileToken = new CF_ExpressionCompileToken( token );
- if (CF_ExpressionVM.Find( CF_ExpressionFunctionVariable.CF_NAME, funcDef ))
- {
- AddInstruction( compileToken.ToOperation( funcDef, variables.Find( token ) ) );
- }
- }
- }
- }
- while (stack.Count() > 0)
- {
- compileToken = stack.Pop();
- if ( !CF_ExpressionVM.Contains( compileToken.token ) )
- CF_Log.Error( "No matching right parenthesis" );
- if (CF_ExpressionVM.Find( compileToken.token, funcDef ))
- {
- AddInstruction( compileToken.ToOperation( funcDef ) );
- }
- }
- while (dataStackStore.Count() > 0)
- {
- dataStackStore.Remove(0);
- }
- return m_Position;
- }
- protected override int _Compile(array<string> variables)
- {
- ClearInstructions();
- return __Compile(variables);
- }
- };
- class CF_SQFExpression : CF_Expression
- {
- protected override int _Compile(array<string> variables)
- {
- array<ref CF_ExpressionCompileToken> dataStackStore();
- __Stack<CF_ExpressionCompileToken> stack();
- ClearInstructions();
- CF_ExpressionFunctionDef funcDef;
- CF_ExpressionCompileToken compileToken;
- while (!EOF())
- {
- string token = GetToken();
- token = token.Trim();
- if (token == "]" || token == ",")
- break;
- CF_ExpressionFunctionDef op1;
- CF_ExpressionFunctionDef op2;
- if (CF_ExpressionVM.Find(token, op1))
- {
- while (stack.Count() > 0)
- {
- string tok = stack.Peek().token;
- if (!CF_ExpressionVM.Find(tok, op2))
- break;
- int c = op1.precedence - op2.precedence;
- if (c < 0 || (!op1.associative && c <= 0))
- AddInstruction(stack.Pop().ToOperation(op2));
- else
- break;
- }
- compileToken = stack.Push(new CF_ExpressionCompileToken(token));
- dataStackStore.Insert(compileToken);
- int startPosition = m_Position;
- token = SkipWhitespace();
- if (token == "[")
- {
- token = SkipWhitespace();
- m_Position--;
- while (token != "]")
- {
- CF_Expression parameter = new CF_SQFExpression();
- parameter.m_Source = m_Source + "";
- parameter.m_Position = m_Position + 0;
- //! there should be no variables/functions inside a parameter for a function call
- int nPos = parameter._Compile(variables);
- float nVal = parameter._Evaluate(new array<float>());
- compileToken.parameters.Insert(nVal);
- m_Position = nPos - 1;
- token = SkipWhitespace();
- }
- //! factor function optimization
- if (compileToken.token == CF_ExpressionFunctionFactor.CF_NAME)
- {
- if (compileToken.parameters[1] < compileToken.parameters[0])
- {
- compileToken.token = CF_ExpressionFunctionReverseFactor.CF_NAME;
- }
- }
- }
- else
- {
- m_Position = startPosition;
- }
- }
- else if (token == "(")
- {
- dataStackStore.Insert(stack.Push(new CF_ExpressionCompileToken(token)));
- }
- else if (token == ")")
- {
- string topToken = "";
- while (stack.Count() > 0)
- {
- compileToken = stack.Pop();
- topToken = compileToken.token;
- if (compileToken.token == "(")
- break;
- if (CF_ExpressionVM.Find(topToken, funcDef))
- AddInstruction(compileToken.ToOperation(funcDef));
- }
- if (topToken != "(")
- CF_Log.Error("No matching left parenthesis");
- }
- else
- {
- if (IsNumber(token))
- {
- compileToken = new CF_ExpressionCompileToken(token);
- if (CF_ExpressionVM.Find(CF_ExpressionFunctionValue.CF_NAME, funcDef))
- {
- AddInstruction(compileToken.ToOperation(funcDef, -2));
- }
- }
- else
- {
- compileToken = new CF_ExpressionCompileToken(token);
- if (CF_ExpressionVM.Find(CF_ExpressionFunctionVariable.CF_NAME, funcDef))
- {
- AddInstruction(compileToken.ToOperation(funcDef, variables.Find(token)));
- }
- }
- }
- }
- while (stack.Count() > 0)
- {
- compileToken = stack.Pop();
- if (!CF_ExpressionVM.Contains(compileToken.token))
- CF_Log.Error("No matching right parenthesis");
- if (CF_ExpressionVM.Find(compileToken.token, funcDef))
- {
- AddInstruction(compileToken.ToOperation(funcDef));
- }
- }
- while (dataStackStore.Count() > 0)
- {
- dataStackStore.Remove(0);
- }
- return m_Position;
- }
- };
- /**
- * Backwards compatibility
- */
- class Expression : CF_SQFExpression
- {
- // DEPRECATED
- string value;
- void Expression(string val = "")
- {
- SetSource(val);
- }
- };
- #ifdef CF_EXPRESSION_TEST
- modded class DayZGame
- {
- private float m_CF_UpdateTime;
- private int m_CF_Tests;
- override void OnUpdate(bool doSim, float timeslice)
- {
- super.OnUpdate(doSim, timeslice);
- if (!doSim) return;
- m_CF_UpdateTime += timeslice;
- if (m_CF_UpdateTime > 5.0 && m_CF_Tests < 3)
- {
- m_CF_UpdateTime = 0;
- m_CF_Tests++;
- CF_ExpressionTests.PerformSingle("TestPerformance");
- }
- }
- };
- #endif
- modded class DayZGame
- {
- ref CF_EventRPCArgs m_CF_EventRPCArgs = new CF_EventRPCArgs();
- void DayZGame()
- {
- CF_ModuleGameManager.UpdateGameFlag(this);
- }
- override void DeferredInit()
- {
- #ifdef CF_TRACE_ENABLED
- auto trace = CF_Trace_0(this);
- #endif
- super.DeferredInit();
- GetRPCManager();
- }
- override void OnUpdate(bool doSim, float timeslice)
- {
- super.OnUpdate(doSim, timeslice);
- if (!GetGame().IsDedicatedServer())
- {
- foreach (auto input : CF_InputBindings.s_All)
- {
- input.Update(timeslice);
- }
- }
- }
- override void OnRPC(PlayerIdentity sender, Object target, int rpc_type, ParamsReadContext ctx)
- {
- #ifdef CF_TRACE_ENABLED
- auto trace = CF_Trace_4(this).Add(sender).Add(target).Add(rpc_type).Add(ctx);
- #endif
- if (rpc_type == RPCManager.FRAMEWORK_RPC_ID)
- {
- GetRPCManager().OnRPC(sender, target, rpc_type, ctx);
- return;
- }
- if (rpc_type == NotificationSystemRPC.Create)
- {
- NotificationSystem.RPC_CreateNotification(sender, target, ctx);
- return;
- }
- if (rpc_type == CF_ModuleGame.NETWORKED_VARIABLES_RPC_ID)
- {
- // Only allow this RPC to be executed on the client, don't want to allow the client to edit server variables
- if (GetGame().IsServer())
- {
- return;
- }
- string moduleName;
- if (!ctx.Read(moduleName))
- {
- return;
- }
- // Check to see if the module can be found
- CF_ModuleGame module;
- if (!Class.CastTo(module, CF_ModuleCoreManager.Get(moduleName)))
- {
- return;
- }
- module.m_CF_NetworkedVariables.Read(ctx);
- module.OnVariablesSynchronized(this, CF_EventArgs.Empty);
- return;
- }
- m_CF_EventRPCArgs.Sender = sender;
- m_CF_EventRPCArgs.Target = target;
- m_CF_EventRPCArgs.ID = rpc_type;
- m_CF_EventRPCArgs.Context = ctx;
- if (CF_ModuleGameManager.OnRPC(this, m_CF_EventRPCArgs))
- {
- return;
- }
- super.OnRPC(sender, target, rpc_type, ctx);
- }
- override void OnEvent(EventType eventTypeId, Param params)
- {
- super.OnEvent(eventTypeId, params);
- switch (eventTypeId)
- {
- case MPSessionStartEventTypeID:
- {
- CF_ModuleCoreManager.OnMPSessionStart(this, CF_EventArgs.Empty);
- break;
- }
- case MPSessionEndEventTypeID:
- {
- CF_ModuleCoreManager.OnMPSessionEnd(this, CF_EventArgs.Empty);
- break;
- }
- case MPSessionFailEventTypeID:
- {
- CF_ModuleCoreManager.OnMPSessionFail(this, CF_EventArgs.Empty);
- break;
- }
- case MPSessionPlayerReadyEventTypeID:
- {
- CF_ModuleCoreManager.OnMPSessionPlayerReady(this, CF_EventArgs.Empty);
- break;
- }
- case MPConnectionLostEventTypeID:
- {
- MPConnectionLostEventParams conLost_params;
- if (Class.CastTo(conLost_params, params))
- {
- CF_ModuleCoreManager.OnMPConnectionLost(this, new CF_EventTimeArgs(conLost_params.param1));
- }
- break;
- }
- case WorldCleaupEventTypeID:
- {
- CF_ModuleCoreManager.OnWorldCleanup(this, CF_EventArgs.Empty);
- break;
- }
- case ChatMessageEventTypeID:
- {
- ChatMessageEventParams chat_params;
- if (Class.CastTo(chat_params, params))
- {
- CF_ModuleCoreManager.OnChat(this, new CF_EventChatArgs(chat_params.param1, chat_params.param2, chat_params.param3, chat_params.param4));
- }
- break;
- }
- case LoginTimeEventTypeID:
- {
- LoginTimeEventParams loginTimeParams;
- if (Class.CastTo(loginTimeParams, params))
- {
- CF_ModuleCoreManager.OnLoginTime(this, new CF_EventTimeArgs(loginTimeParams.param1));
- }
- break;
- }
- case RespawnEventTypeID:
- {
- RespawnEventParams respawnParams;
- if (Class.CastTo(respawnParams, params))
- {
- CF_ModuleCoreManager.OnRespawn(this, new CF_EventTimeArgs(respawnParams.param1));
- }
- break;
- }
- case LogoutEventTypeID:
- {
- LogoutEventParams logoutParams;
- if (Class.CastTo(logoutParams, params))
- {
- CF_ModuleCoreManager.OnLogout(this, new CF_EventTimeArgs(logoutParams.param1));
- }
- break;
- }
- case LoginStatusEventTypeID:
- {
- LoginStatusEventParams loginStatusParams;
- if (Class.CastTo(loginStatusParams, params))
- {
- CF_ModuleCoreManager.OnLoginStatus(this, new CF_EventLoginArgs(loginStatusParams.param1, loginStatusParams.param2));
- }
- break;
- }
- case ConnectingAbortEventTypeID:
- {
- CF_ModuleCoreManager.OnMPConnectAbort(this, CF_EventArgs.Empty);
- break;
- }
- }
- }
- /**
- * @brief An overrideable function that determines if the UI input of the player is being blocked by an editbox widget.
- */
- bool CF_UIInputBlocked()
- {
- if (GetGame().IsDedicatedServer())
- {
- return false;
- }
- Widget focusedWidget = GetFocus();
- if (!focusedWidget)
- {
- return false;
- }
- return focusedWidget.ClassName().Contains("EditBoxWidget");
- }
- };
- class CF_InputBinding
- {
- static int PRESS = 1;
- static int RELEASE = 2;
- static int HOLD = 4;
- static int CLICK = 8;
- static int DOUBLE_CLICK = 16;
- ref CF_InputBinding m_Next;
- string m_Function;
- UAInput m_Input;
- int m_InputLimits;
- bool m_LimitMenu;
- void UpdateLimits()
- {
- m_InputLimits = 0;
- m_InputLimits &= m_Input.IsPressLimit() << 1;
- m_InputLimits &= m_Input.IsReleaseLimit() << 2;
- m_InputLimits &= m_Input.IsHoldLimit() << 3;
- m_InputLimits &= m_Input.IsClickLimit() << 4;
- m_InputLimits &= m_Input.IsDoubleClickLimit() << 5;
- }
- };
- class CF_InputBindings
- {
- static ref array<CF_InputBindings> s_All = new array<CF_InputBindings>();
- ref CF_InputBinding m_Head;
- Class m_Instance;
- /**
- * @brief Constructor. Adds to the list of all input binding managers. Should be called on parent class construction
- *
- * @param instance The input binding parent
- */
- void CF_InputBindings(Class instance)
- {
- m_Instance = instance;
- s_All.Insert(this);
- }
- /**
- * @brief Removes from the list of all input binding managers. Should be called on parent class deletion
- */
- void ~CF_InputBindings()
- {
- s_All.RemoveItemUnOrdered(this);
- }
- /**
- * @brief Binds input to head, pushes other entries back
- *
- * @param callback The function the input binding parent to call
- * @param input The name of the input
- * @param preventCallInMenu If the binding can be called while a menu is open
- *
- * @code
- * bindings.Bind("Close", "UAUIBack", false);
- * @endcode
- */
- void Bind(string callback, string input, bool preventCallInMenu = false)
- {
- Bind(callback, GetUApi().GetInputByName(input), preventCallInMenu);
- }
- /**
- * @brief Binds input to head, pushes other entries back
- *
- * @param callback The function the input binding parent to call
- * @param input The ID of the input. All inputs found within modded inputs is generated as a global int variable of the same name
- * @param preventCallInMenu If the binding can be called while a menu is open
- *
- * @code
- * bindings.Bind("Close", UAUIBack, false);
- * @endcode
- */
- void Bind(string callback, int input, bool preventCallInMenu = false)
- {
- Bind(callback, GetUApi().GetInputByID(input), preventCallInMenu);
- }
- /**
- * @brief Binds input to head, pushes other entries back
- *
- * @param callback The function the input binding parent to call
- * @param input The instance of the input
- * @param preventCallInMenu If the binding can be called while a menu is open
- *
- * @code
- * bindings.Bind("Close", GetUApi().GetInputByID(UAUIBack), false);
- * @endcode
- */
- void Bind(string callback, UAInput input, bool preventCallInMenu = false)
- {
- CF_InputBinding binding = new CF_InputBinding();
- binding.m_Function = callback;
- binding.m_Input = input;
- binding.m_LimitMenu = preventCallInMenu;
- Bind(binding);
- }
- /**
- * @brief Binds input to head, pushes other entries back
- *
- * @param binding The instance of the binding to add to the list
- */
- void Bind(CF_InputBinding binding)
- {
- if (m_Head)
- {
- binding.m_Next = m_Head;
- }
- m_Head = binding;
- m_Head.UpdateLimits();
- }
- /**
- * @brief Checks for all input state changes and calls the necessary functions
- *
- * @param dt Unused.
- */
- void Update(float dt)
- {
- bool inMenu = GetGame().GetUIManager().GetMenu() || CF_ModuleGame.s_PreventInput;
- CF_InputBinding binding = m_Head;
- while (binding)
- {
- if (!inMenu || (inMenu && !binding.m_LimitMenu))
- {
- UAInput input = binding.m_Input;
- bool isModified = input.LocalValue() != 0.0 || input.LocalRelease();
- if (binding.m_InputLimits != 0)
- {
- if (isModified)
- {
- g_Script.CallFunctionParams(m_Instance, binding.m_Function, NULL, new Param1<UAInput>(input));
- }
- }
- else if (isModified)
- {
- g_Script.CallFunctionParams(m_Instance, binding.m_Function, NULL, new Param1<UAInput>(input));
- }
- }
- binding = binding.m_Next;
- }
- }
- };
- modded class DayZGame
- {
- void DayZGame()
- {
- #ifdef CF_TRACE_ENABLED
- auto trace = CF_Trace_0(this);
- #endif
- CF_LifecycleEvents.OnGameCreate.Invoke(this, CF_EventArgs.Empty);
- }
- void ~DayZGame()
- {
- #ifdef CF_TRACE_ENABLED
- auto trace = CF_Trace_0(this);
- #endif
- CF_LifecycleEvents.OnGameDestroy.Invoke(this, CF_EventArgs.Empty);
- }
- };
- class ModInput
- {
- string Name;
- string Localization;
- bool Visible;
- };
- modded class ModLoader
- {
- static ref array<ref ModStructure> s_CF_Mods = new array<ref ModStructure>();
- static ref map<string, ModStructure> s_CF_ModMap = new map<string, ModStructure>();
- static ref array<ref CF_ModStorage> s_CF_ModStorages = new array<ref CF_ModStorage>();
- static ref CF_ModStorageMap s_CF_ModStorageMap = new CF_ModStorageMap();
- static ref map<int, ref map<int, CF_ModStorage>> s_CF_ModStorageHashedMap = new map<int, ref map<int, CF_ModStorage>>();
- static CF_ModStorage CF_GetStorage(string name)
- {
- #ifdef CF_TRACE_ENABLED
- auto trace = CF_Trace_1("ModLoader").Add(name);
- #endif
- LoadMods();
- return s_CF_ModStorageMap[name];
- }
- static bool CF_IsModStorage(string name)
- {
- #ifdef CF_TRACE_ENABLED
- auto trace = CF_Trace_1("ModLoader").Add(name);
- #endif
- LoadMods();
- return s_CF_ModStorageMap.Contains(name);
- }
- static bool _CF_ReadModStorage(Serializer ctx, int version, inout array<ref CF_ModStorage> unloadedMods, inout int stackIndex, inout CF_ModStorageMap loadedMods)
- {
- #ifdef CF_TRACE_ENABLED
- auto trace = CF_Trace_2("ModLoader").Add(ctx).Add(version);
- #endif
- LoadMods();
- int hashA, hashB;
- bool exists = false;
- CF_ModStorage storage;
- if (version > 3)
- {
- if (!ctx.Read(hashA)) return false;
- if (!ctx.Read(hashB)) return false;
- }
- else
- {
- CF_String modName;
- if (!ctx.Read(modName)) return false;
- hashA = modName.Hash();
- hashB = modName.Reverse().Hash();
- }
- auto hash = s_CF_ModStorageHashedMap[hashA];
- if (hash)
- {
- storage = hash[hashB];
- exists = storage != null;
- }
- if (!exists)
- {
- storage = new CF_ModStorage(null);
- storage.m_HashA = hashA;
- storage.m_HashB = hashB;
- }
- if (!ctx.Read(storage.m_Version)) return false;
- if (!ctx.Read(storage.m_Data)) return false;
- if (exists)
- {
- loadedMods.Insert(storage.GetMod().GetName(), storage);
- }
- else
- {
- unloadedMods[stackIndex] = storage;
- stackIndex++;
- }
- return true;
- }
- static ModStructure Get(string name)
- {
- #ifdef CF_TRACE_ENABLED
- auto trace = CF_Trace_1("ModLoader").Add(name);
- #endif
- LoadMods();
- return s_CF_ModMap[name];
- }
- static bool Contains(string name)
- {
- #ifdef CF_TRACE_ENABLED
- auto trace = CF_Trace_1("ModLoader").Add(name);
- #endif
- LoadMods();
- return s_CF_ModMap.Contains(name);
- }
- static bool Find(string name, out ModStructure mod)
- {
- #ifdef CF_TRACE_ENABLED
- auto trace = CF_Trace_1("ModLoader").Add(name);
- #endif
- LoadMods();
- return s_CF_ModMap.Find(name, mod);
- }
- override static array<ref ModStructure> GetMods()
- {
- #ifdef CF_TRACE_ENABLED
- auto trace = CF_Trace_0("ModLoader");
- #endif
- LoadMods();
- return m_Mods;
- }
- override static void LoadMods()
- {
- if (m_Loaded)
- {
- return;
- }
- #ifdef CF_TRACE_ENABLED
- auto trace = CF_Trace_0("ModLoader");
- #endif
- m_Mods = new array<ref ModStructure>;
- m_Loaded = true;
- int modCount = GetGame().ConfigGetChildrenCount("CfgMods");
- for (int i = 2; i < modCount; i++)
- {
- string name;
- GetGame().ConfigGetChildName("CfgMods", i, name);
- ModStructure mod;
- typename type = name.ToType();
- if (!type.IsInherited(ModStructure))
- {
- type = ModStructure;
- }
- if (Class.CastTo(mod, type.Spawn()))
- {
- mod._CF_Init(i, name, "CfgMods " + name);
- m_Mods.Insert(mod);
- s_CF_Mods.Insert(mod);
- s_CF_ModMap.Insert(name, mod);
- if (mod.HasModStorage())
- {
- CF_ModStorage storage = new CF_ModStorage(mod);
- s_CF_ModStorages.Insert(storage);
- s_CF_ModStorageMap.Insert(mod, storage);
- int hashA = mod.m_CF_HashA;
- int hashB = mod.m_CF_HashB;
- map<int, CF_ModStorage> hashStructures = s_CF_ModStorageHashedMap[hashA];
- if (!hashStructures)
- {
- hashStructures = new map<int, CF_ModStorage>();
- s_CF_ModStorageHashedMap.Insert(hashA, hashStructures);
- }
- if (hashStructures.Contains(hashB))
- {
- CF_Log.Error("Mod exists with duplicate hashes! Name=%0 A=%1 B=%2", mod.GetName(), hashA.ToString(), hashB.ToString());
- }
- hashStructures[hashB] = storage;
- }
- }
- }
- }
- };
- modded class ModStructure
- {
- protected CF_String m_CF_Name;
- int m_CF_HashA;
- int m_CF_HashB;
- protected ref array<ref ModInput> m_CF_ModInputs;
- protected ref JsonDataCredits m_CF_Credits;
- protected string m_CF_ModVersion;
- protected int m_CF_StorageVersion;
- /**
- * Set the mod specific data in here
- *
- * @param modName The name of the loaded mod, retrieved from the CfgMods params array
- *
- * @code
- * override bool CF_OnLoad( string modName )
- * {
- * if ( modName != "JM_CommunityFramework" )
- * return super.CF_OnLoad( modName );
- *
- * //! Set the storage version for this mod
- * SetStorageVersion( 1 );
- *
- * return true;
- * }
- * @endcode
- */
- bool CF_OnLoad(CF_String modName)
- {
- return false;
- }
- /**
- * @brief Backwards compatibility
- *
- * @deprecated
- */
- bool OnLoad(string modName)
- {
- return false;
- }
- void _CF_Init(int index, string name, string path)
- {
- m_ModIndex = index;
- m_ModPath = path;
- m_CF_Name = name;
- m_CF_HashA = m_CF_Name.Hash();
- m_CF_HashB = m_CF_Name.Reverse().Hash();
- m_CF_ModInputs = new array<ref ModInput>;
- m_CF_StorageVersion = 0;
- if (GetGame().ConfigIsExisting(m_ModPath))
- {
- if (GetGame().ConfigIsExisting(m_ModPath + " storageVersion"))
- {
- SetStorageVersion(GetGame().ConfigGetInt(m_ModPath + " storageVersion"));
- }
- if (GetGame().ConfigIsExisting(m_ModPath + " creditsJson"))
- {
- string creditsPath;
- GetGame().ConfigGetText(m_ModPath + " creditsJson", creditsPath);
- JsonFileLoader<JsonDataCredits>.JsonLoadFile(creditsPath, m_CF_Credits);
- }
- else if (GetGame().ConfigIsExisting(m_ModPath + " credits"))
- {
- string credits = "";
- m_CF_Credits = new JsonDataCredits;
- m_CF_Credits.Departments = new array<ref JsonDataCreditsDepartment>;
- JsonDataCreditsDepartment mod_department_header = new JsonDataCreditsDepartment;
- mod_department_header.Sections = new array<ref JsonDataCreditsSection>;
- mod_department_header.DepartmentName = " " + m_ModName;
- string author = "";
- bool hasAuthor = GetGame().ConfigIsExisting(m_ModPath + " author");
- GetGame().ConfigGetText(m_ModPath + " author", author);
- if (hasAuthor && author != "")
- {
- JsonDataCreditsSection mod_section_modheader_author = new JsonDataCreditsSection;
- mod_section_modheader_author.SectionLines = new array<string>;
- mod_section_modheader_author.SectionName = ("Author");
- mod_section_modheader_author.SectionLines.Insert(author);
- mod_department_header.Sections.Insert(mod_section_modheader_author);
- }
- GetGame().ConfigGetText(m_ModPath + " credits", credits);
- if (credits != "")
- {
- JsonDataCreditsSection mod_section_modheader = new JsonDataCreditsSection;
- mod_section_modheader.SectionLines = new array<string>;
- mod_section_modheader.SectionName = ("Credits");
- array<string> creditsArray = new array<string>;
- credits.Split(", ", creditsArray);
- foreach (string credit : creditsArray)
- {
- mod_section_modheader.SectionLines.Insert(credit);
- }
- mod_department_header.Sections.Insert(mod_section_modheader);
- }
- m_CF_Credits.Departments.Insert(mod_department_header);
- }
- else
- {
- m_CF_Credits = new JsonDataCredits;
- }
- if (GetGame().ConfigIsExisting(m_ModPath + " versionPath"))
- {
- string versionPath;
- GetGame().ConfigGetText(m_ModPath + " versionPath", versionPath);
- FileHandle file_handle = OpenFile(versionPath, FileMode.READ);
- while (FGets(file_handle, m_CF_ModVersion) > 0)
- break;
- CloseFile(file_handle);
- }
- else if (GetGame().ConfigIsExisting(m_ModPath + " version"))
- {
- GetGame().ConfigGetText(m_ModPath + " version", m_CF_ModVersion);
- }
- if (GetGame().ConfigIsExisting(m_ModPath + " inputs"))
- {
- string inputPath;
- GetGame().ConfigGetText(m_ModPath + " inputs", inputPath);
- CF_XML_Document document;
- if (inputPath != "" && CF.XML.ReadDocument(inputPath, document))
- {
- auto parent_tag = document.Get("modded_inputs")[0];
- if (parent_tag)
- parent_tag = parent_tag.GetTag("inputs")[0];
- if (parent_tag)
- parent_tag = parent_tag.GetTag("actions")[0];
- array<CF_XML_Tag> inputs = null;
- if (!parent_tag)
- inputs = new array<CF_XML_Tag>();
- else
- inputs = parent_tag.GetTag("input");
- for (int i = 0; i < inputs.Count(); i++)
- {
- ModInput modInput = new ModInput;
- CF_XML_Attribute attrib = null;
- attrib = inputs[i].GetAttribute("name");
- if (attrib)
- modInput.Name = attrib.ValueAsString();
- attrib = inputs[i].GetAttribute("loc");
- if (attrib)
- modInput.Localization = attrib.ValueAsString();
- attrib = inputs[i].GetAttribute("visible");
- if (attrib)
- modInput.Visible = attrib.ValueAsBool();
- else
- modInput.Visible = true;
- m_CF_ModInputs.Insert(modInput);
- }
- }
- }
- LoadData();
- if (ClassName() == "ModStructure" && !CF_OnLoad(m_CF_Name))
- {
- OnLoad(m_CF_Name);
- }
- }
- }
- array<ref ModInput> GetModInputs()
- {
- return m_CF_ModInputs;
- }
- JsonDataCredits GetCredits()
- {
- return m_CF_Credits;
- }
- string GetName()
- {
- return m_CF_Name;
- }
- string GetModPath()
- {
- return m_ModPath;
- }
- override string GetModName()
- {
- return m_ModName;
- }
- override string GetModLogo()
- {
- return m_ModLogo;
- }
- override string GetModLogoSmall()
- {
- return m_ModLogoSmall;
- }
- override string GetModLogoOver()
- {
- return m_ModLogoOver;
- }
- override string GetModActionURL()
- {
- return m_ModActionURL;
- }
- override string GetModToltip()
- {
- return m_ModTooltip;
- }
- override string GetModOverview()
- {
- return m_ModOverview;
- }
- string GetModVersion()
- {
- return m_CF_ModVersion;
- }
- int GetStorageVersion()
- {
- return m_CF_StorageVersion;
- }
- protected void SetStorageVersion(int version)
- {
- m_CF_StorageVersion = version;
- }
- bool HasModStorage()
- {
- return m_CF_StorageVersion > 0;
- }
- override string GetDebugName()
- {
- string str = super.GetDebugName();
- str += ", GetName=" + GetName();
- str += ", GetModPath=" + GetModPath();
- str += ", GetModName=" + GetModName();
- str += ", GetModLogo=" + GetModLogo();
- str += ", GetModLogoSmall=" + GetModLogoSmall();
- str += ", GetModLogoOver=" + GetModLogoOver();
- str += ", GetModActionURL=" + GetModActionURL();
- str += ", GetModToltip=" + GetModToltip();
- str += ", GetModOverview=" + GetModOverview();
- str += ", GetModVersion=" + GetModVersion();
- str += ", GetStorageVersion=" + GetStorageVersion();
- str += ", HasModStorage=" + HasModStorage();
- return str;
- }
- };
- /**
- * @class CF_ModStorage
- *
- * @note Do not mod this class. Modding this class defeats the purpose of this being in Community Framework.
- * You will break persistence if you mod it. Make a pull request here https://github.com/Jacob-Mango/DayZ-Community-Framework/pulls
- */
- class CF_ModStorage
- {
- static const int VERSION = 4;
- static const int GAME_VERSION_FIRST_INSTALL = 116;
- static const int GAME_VERSION_WIPE_FILE = 127;
- static const int MODSTORAGE_INITIAL_IMPLEMENTATION = 2;
- ModStructure m_Mod;
- int m_Version;
- int m_HashA;
- int m_HashB;
- string m_Data;
- string m_Value;
- void CF_ModStorage(ModStructure mod)
- {
- m_Mod = mod;
- _ResetStream();
- }
- int GetVersion()
- {
- return m_Version;
- }
- ModStructure GetMod()
- {
- return m_Mod;
- }
- bool Read(out bool value)
- {
- m_Data.ParseStringEx(m_Value);
- value = m_Value == "1";
- return true;
- }
- bool Read(out int value)
- {
- m_Data.ParseStringEx(m_Value);
- value = m_Value.ToInt();
- return true;
- }
- bool Read(out float value)
- {
- m_Data.ParseStringEx(m_Value);
- value = m_Value.ToFloat();
- return true;
- }
- bool Read(out vector value)
- {
- m_Data.ParseStringEx(m_Value);
- value = m_Value.ToVector();
- return true;
- }
- bool Read(out string value)
- {
- m_Data.ParseStringEx(m_Value);
- value = m_Value;
- return true;
- }
- void Write(bool value)
- {
- if (value)
- {
- m_Data += " 1";
- }
- else
- {
- m_Data += " 0";
- }
- }
- void Write(int value)
- {
- m_Data += " " + value.ToString();
- }
- void Write(float value)
- {
- m_Data += " " + value.ToString();
- }
- void Write(vector value)
- {
- m_Data += " \"" + value.ToString(false) + "\"";
- }
- void Write(string value)
- {
- m_Data += " \"" + value + "\"";
- }
- void _CopyStreamTo(Serializer ctx)
- {
- string data;
- if (m_Data.Length() > 0)
- {
- data = m_Data.Substring(1, m_Data.Length() - 1);
- }
- // force resetting early so we can write the latest version
- _ResetStream();
- ctx.Write(m_HashA);
- ctx.Write(m_HashB);
- ctx.Write(m_Version);
- ctx.Write(data);
- }
- // Read and Write functions can't be called, so we can't reset the stream
- void _ResetStream()
- {
- if (!m_Mod)
- {
- return;
- }
- m_Data = string.Empty;
- m_HashA = m_Mod.m_CF_HashA;
- m_HashB = m_Mod.m_CF_HashB;
- m_Version = m_Mod.GetStorageVersion();
- }
- };
- class CF_ModStorageMap
- {
- autoptr map<string, CF_ModStorage> m_Map = new map<string, CF_ModStorage>();
- CF_ModStorage Get(string name)
- {
- return m_Map[name];
- }
- CF_ModStorage Get(typename type)
- {
- return m_Map[type.ToString()];
- }
- bool Contains(string name)
- {
- return m_Map.Contains(name);
- }
- bool Find(string name, out CF_ModStorage storage)
- {
- return m_Map.Find(name, storage);
- }
- void Insert(string name, CF_ModStorage storage)
- {
- m_Map.Insert(name, storage);
- }
- void Insert(ModStructure mod, CF_ModStorage storage)
- {
- m_Map.Insert(mod.ClassName(), storage);
- }
- };
- /**
- * @class CF_ModStorageModule
- *
- * @brief Does not support unloading CF from the mods. Once loaded it can't be removed
- */
- #ifndef CF_MODSTORAGE_MODULE_DISABLE
- [CF_RegisterModule(CF_ModStorageModule)]
- #endif
- class CF_ModStorageModule : CF_ModuleGame
- {
- static const string m_FileName = "modstorageids.bin";
- protected string m_FilePath;
- protected autoptr map<int, ref map<int, ref map<int, ref map<int, ref Param1<bool>>>>> m_IDs = new map<int, ref map<int, ref map<int, ref map<int, ref Param1<bool>>>>>();
- protected bool m_IsLoaded;
- protected autoptr FileSerializer m_Serializer;
- /**
- * @brief Checks if the persistent ID is in the map. If they aren't in the map then add and write to the file
- */
- void AddEntity(int b1, int b2, int b3, int b4)
- {
- Load();
- if (!_AddEntity(b1, b2, b3, b4, false))
- {
- return;
- }
- m_Serializer.Write(b1);
- m_Serializer.Write(b2);
- m_Serializer.Write(b3);
- m_Serializer.Write(b4);
- }
- /**
- * @brief Checks to see if the persistent ID is loaded
- */
- bool IsEntity(int b1, int b2, int b3, int b4)
- {
- Load();
- auto map_b1 = m_IDs[b1];
- if (!map_b1)
- {
- return false;
- }
- auto map_b2 = map_b1[b2];
- if (!map_b2)
- {
- return false;
- }
- auto map_b3 = map_b2[b3];
- if (!map_b3)
- {
- return false;
- }
- auto val_b4 = map_b3[b4];
- if (!val_b4)
- {
- return false;
- }
- return true;
- }
- /**
- * @brief Reads the modstorage file
- */
- void Load(bool reload = false)
- {
- if (m_IsLoaded && !reload)
- {
- return;
- }
- m_IsLoaded = true;
- int instanceId = g_Game.ServerConfigGetInt("instanceId");
- string folder = "$mission:storage_" + instanceId + "/";
- if (!FileExist(folder))
- {
- MakeDirectory(folder);
- }
- folder += "communityframework/";
- if (!FileExist(folder))
- {
- MakeDirectory(folder);
- }
- m_FilePath = folder + m_FileName;
- if (m_Serializer) m_Serializer.Close();
- // Clear existing ids
- m_IDs.Clear();
- if (FileExist(m_FilePath))
- {
- FileHandle handle = OpenFile(m_FilePath, FileMode.READ);
- if (handle != 0)
- {
- // Reads 4 ints (16 bytes) at a time
- int data[4];
- while (ReadFile(handle, data, 16) > 0)
- {
- _AddEntity(data[0], data[1], data[2], data[3], true);
- }
- CloseFile(handle);
- }
- m_Serializer = new FileSerializer();
- m_Serializer.Open(m_FilePath, FileMode.APPEND);
- }
- else
- {
- m_Serializer = new FileSerializer();
- m_Serializer.Open(m_FilePath, FileMode.WRITE);
- }
- }
- /**
- * @param loaded If the entity was added from the file
- *
- * @return True if newly added entity
- */
- private bool _AddEntity(int b1, int b2, int b3, int b4, bool loaded)
- {
- auto map_b1 = m_IDs[b1];
- if (!map_b1)
- {
- map_b1 = new map<int, ref map<int, ref map<int, ref Param1<bool>>>>();
- m_IDs[b1] = map_b1;
- }
- auto map_b2 = map_b1[b2];
- if (!map_b2)
- {
- map_b2 = new map<int, ref map<int, ref Param1<bool>>>();
- map_b1[b2] = map_b2;
- }
- auto map_b3 = map_b2[b3];
- if (!map_b3)
- {
- map_b3 = new map<int, ref Param1<bool>>();
- map_b2[b3] = map_b3;
- }
- auto val_b4 = map_b3[b4];
- if (!val_b4)
- {
- val_b4 = new Param1<bool>(loaded);
- map_b3[b4] = val_b4;
- return true;
- }
- return false;
- }
- };
- //TODO: Automate into a framework for other modders to use for their own testing
- #ifdef CF_MODSTORAGE_TEST
- class CF_ModStorageTest
- {
- private string _current;
- private int _cpu;
- private int _failed;
- private void CF_ModStorageTest()
- {
- }
- static void Perform()
- {
- CF_ModStorageTest tests = new CF_ModStorageTest();
- tests._Perform();
- }
- static void PerformSingle(string test)
- {
- CF_ModStorageTest tests = new CF_ModStorageTest();
- tests.PerformTest(test);
- }
- protected void Setup(inout array<string> tests)
- {
- tests.Insert("CreateEntity");
- tests.Insert("TestEntity");
- }
- private void _Perform()
- {
- Print("Starting tests");
- array<string> tests = new array<string>();
- Setup(tests);
- _failed = 0;
- int start = TickCount(0);
- for (int i = 0; i < tests.Count(); i++)
- PerformTest(tests[i]);
- int time = TickCount(start);
- Print("\n");
- if (_failed == 0)
- {
- Print("Success. All " + tests.Count() + " passed!");
- }
- else
- {
- Print("Tests failed. " + (tests.Count() - _failed) + "/" + tests.Count() + " passed.");
- }
- }
- private void PerformTest(string method)
- {
- Print("\n");
- Print("Running test \"" + method + "\"");
- _current = method;
- _cpu = TickCount(0);
- GetGame().GameScript.CallFunction(this, _current, null, null);
- }
- private void _assert(string expected, string actual)
- {
- int time = TickCount(_cpu);
- string info = "Test \"" + _current + "\" took " + time + " ticks to execute.";
- Print(" Expected Result: " + expected);
- Print(" Actual Result: " + actual);
- if (expected != actual)
- {
- //Print( " Expected Result: " + expected );
- //Print( " Actual Result: " + actual );
- info = "FAILED: " + info;
- _failed++;
- }
- else
- {
- info = "PASSED: " + info;
- }
- Print("" + info);
- Print("");
- }
- EntityAI object;
- void CreateEntity()
- {
- string objectType = "Apple";
- object = EntityAI.Cast(GetGame().CreateObject(objectType, "0 0 0"));
- }
- void TestEntity()
- {
- object.SetPosition("5 5 0");
- string prev = object.GetDebugName();
- ScriptReadWriteContext ctx = new ScriptReadWriteContext;
- object.OnStoreSave(ctx.GetWriteContext());
- object.OnStoreLoad(ctx.GetReadContext(), GetGame().SaveVersion());
- _assert(prev, object.GetDebugName());
- }
- };
- #endif
- static autoptr CF_ModuleConstructor g_CF_ModuleConstructor = null;
- class CF_ModuleConstructor
- {
- private void CF_ModuleConstructor()
- {
- #ifdef CF_TRACE_ENABLED
- auto trace = CF_Trace_0(this);
- #endif
- CF_ModuleCoreManager._OnCreate();
- }
- /**
- * @note We can safely guarantee the destructor is called on script reload,
- * we can't do the same for 'OnGameDestroy'.
- */
- void ~CF_ModuleConstructor()
- {
- #ifdef CF_TRACE_ENABLED
- auto trace = CF_Trace_0(this);
- #endif
- CF_ModuleCoreManager._OnDestroy();
- }
- [CF_EventSubscriber(ScriptCaller.Create(CF_ModuleConstructor._Init), CF_LifecycleEvents.OnGameCreate)]
- static void _Init()
- {
- if (g_CF_ModuleConstructor)
- {
- return;
- }
- g_CF_ModuleConstructor = new CF_ModuleConstructor();
- }
- [CF_EventSubscriber(ScriptCaller.Create(CF_ModuleConstructor._Cleanup), CF_LifecycleEvents.OnGameDestroy)]
- static void _Cleanup()
- {
- g_CF_ModuleConstructor = null;
- }
- };
- class CF_ModuleGame : CF_ModuleCore
- {
- const static int NETWORKED_VARIABLES_RPC_ID = 435022;
- autoptr CF_InputBindings m_CF_Bindings = new CF_InputBindings(this);
- autoptr CF_NetworkedVariables m_CF_NetworkedVariables = new CF_NetworkedVariables(this);
- int m_CF_RPC_Minimum;
- int m_CF_RPC_Maximum;
- /**
- * @brief Binds a module function to an input
- *
- * @param callback The function within 'm_Instance' to call
- * @param input The name of the input
- * @param preventCallInMenu If the binding can be called while a menu is open
- *
- * @code
- * override void OnInit()
- * {
- * super.OnInit();
- *
- * Bind("Close", "UAUIBack", false);
- * };
- * @endcode
- */
- void Bind(string function, string input, bool limitMenu = false)
- {
- m_CF_Bindings.Bind(function, input, limitMenu);
- }
- /**
- * @brief Binds a module function to an input
- *
- * @param callback The function within 'm_Instance' to call
- * @param input The ID of the input. All inputs found within modded inputs is generated as a global int variable of the same name.
- * @param preventCallInMenu If the binding can be called while a menu is open
- *
- * @code
- * override void OnInit()
- * {
- * super.OnInit();
- *
- * Bind("Close", UAUIBack, false);
- * };
- * @endcode
- */
- void Bind(string function, int input, bool limitMenu = false)
- {
- m_CF_Bindings.Bind(function, input, limitMenu);
- }
- /**
- * @brief Binds a module function to an input
- *
- * @param callback The function within 'm_Instance' to call
- * @param input The name of the input
- * @param preventCallInMenu If the binding can be called while a menu is open
- *
- * @code
- * override void OnInit()
- * {
- * super.OnInit();
- *
- * Bind("Close", "UAUIBack", false);
- * };
- * @endcode
- */
- void Bind(string function, UAInput input, bool limitMenu = false)
- {
- m_CF_Bindings.Bind(function, input, limitMenu);
- }
- /**
- * @brief Binds a module function to an input
- *
- * @param binding The instance of the binding to add to the list
- *
- * @code
- * override void OnInit()
- * {
- * super.OnInit();
- *
- * CF_InputBinding binding = new CF_InputBinding();
- * binding.m_Function = "Close";
- * binding.m_Input = GetUApi().GetInputByID(UAUIBack);
- * binding.m_LimitMenu = false;
- *
- * Bind(binding);
- * };
- * @endcode
- */
- void Bind(CF_InputBinding binding)
- {
- m_CF_Bindings.Bind(binding);
- }
- /**
- * @brief Registers functions into legacy RPCFramework
- */
- void AddLegacyRPC(string funcName, int singlePlayerExecType = SingleplayerExecutionType.Server)
- {
- GetRPCManager().AddRPC(ClassName(), funcName, this, singlePlayerExecType);
- }
- /**
- * @note Only call in 'OnInit'
- */
- bool RegisterNetSyncVariable(string name)
- {
- return m_CF_NetworkedVariables.Register(name);
- }
- void SetSynchDirty()
- {
- // Only the server can send data
- if (!GetGame().IsDedicatedServer())
- {
- // No need to serialize in offline mode, just directly call 'OnVariablesSynchronized'
- if (GetGame().IsServer())
- {
- OnVariablesSynchronized(this, CF_EventArgs.Empty);
- }
- return;
- }
- ScriptRPC rpc = new ScriptRPC();
- rpc.Write(ClassName());
- m_CF_NetworkedVariables.Write(rpc);
- rpc.Send(null, CF_ModuleGame.NETWORKED_VARIABLES_RPC_ID, true, null);
- }
- int GetRPCMin()
- {
- return -1;
- }
- int GetRPCMax()
- {
- return -1;
- }
- void EnableRPC()
- {
- m_CF_RPC_Minimum = GetRPCMin();
- m_CF_RPC_Maximum = GetRPCMax();
- if (m_CF_RPC_Minimum == -1 || m_CF_RPC_Maximum == -1)
- {
- return;
- }
- CF_ModuleGameManager.s_RPC.Add(this);
- }
- /**
- * @deprecated
- */
- void EnableUpdateInput();
- void OnRPC(Class sender, CF_EventArgs args);
- void OnVariablesSynchronized(Class sender, CF_EventArgs args);
- };
- typedef CF_ModuleGame CF_Module;
- class CF_ModuleGameEvent : CF_ModuleCoreEvent
- {
- bool OnRPC(Class sender, CF_EventArgs args)
- {
- CF_EventRPCArgs rpc;
- if (!Class.CastTo(rpc, args))
- {
- return false;
- }
- auto evt = this.m_Next;
- while (evt)
- {
- auto module = CF_ModuleGame.Cast(evt.m_Value);
- if ((module.m_CF_GameFlag & CF_ModuleCoreManager.s_GameFlag) != 0 && (module.m_CF_RPC_Minimum <= rpc.ID && rpc.ID < module.m_CF_RPC_Maximum))
- {
- module.OnRPC(sender, rpc);
- return true;
- }
- evt = evt.m_Next;
- }
- return false;
- }
- };
- class CF_ModuleGameManager
- {
- static ref CF_ModuleGameEvent s_RPC = new CF_ModuleGameEvent();
- /**
- * @brief Updates the flag for event calling. So server side modules don't get the event called on client and same for client side on server.
- *
- * @param game Passes in the CGame/DayZGame instance. If none provided, automatically obtains from global 'g_Game' variable
- */
- static void UpdateGameFlag(CGame game = null)
- {
- if (game == null)
- {
- game = g_Game;
- }
- // 0xFF = Single Player
- // 0x0F = Client
- // 0xF0 = Dedicated Server
- CF_ModuleCoreManager.s_GameFlag = 0xFF;
- if (game.IsMultiplayer())
- {
- CF_ModuleCoreManager.s_GameFlag = 0x0F;
- if (game.IsServer())
- {
- CF_ModuleCoreManager.s_GameFlag = 0xF0;
- }
- }
- }
- static bool OnRPC(Class sender, CF_EventArgs args)
- {
- return s_RPC.OnRPC(sender, args);
- }
- static void OnUpdate(Class sender, CF_EventArgs args)
- {
- UpdateGameFlag();
- CF_ModuleCoreManager.s_Update.OnUpdate(sender, args);
- delete args;
- }
- };
- /**
- * @class JMModuleManagerBase
- *
- * @deprecated
- */
- class JMModuleManagerBase
- {
- protected bool m_PreventModuleBindings;
- bool IsPreventingModuleBindings()
- {
- m_PreventModuleBindings = CF_ModuleGame.s_PreventInput;
- return CF_ModuleGame.s_PreventInput;
- }
- void SetPreventModuleBindings(bool prevent)
- {
- CF_ModuleGame.s_PreventInput = prevent;
- m_PreventModuleBindings = CF_ModuleGame.s_PreventInput;
- }
- void InitModules()
- {
- // does nothing
- }
- void Print_DumpModules()
- {
- // does nothing
- }
- void OnSettingsUpdated()
- {
- CF_ModuleCoreManager.OnSettingsChanged(this, CF_EventArgs.Empty);
- }
- void OnClientPermissionsUpdated()
- {
- CF_ModuleCoreManager.OnPermissionsChanged(this, CF_EventArgs.Empty);
- }
- void OnInit()
- {
- // does nothing
- }
- void OnMissionStart()
- {
- CF_ModuleCoreManager.OnMissionStart(this, CF_EventArgs.Empty);
- }
- void OnMissionFinish()
- {
- CF_ModuleCoreManager.OnMissionFinish(this, CF_EventArgs.Empty);
- }
- void OnMissionLoaded()
- {
- CF_ModuleCoreManager.OnMissionLoaded(this, CF_EventArgs.Empty);
- }
- void OnRPC(PlayerIdentity sender, Object target, int rpc_type, ParamsReadContext ctx)
- {
- auto args = new CF_EventRPCArgs();
- args.Sender = sender;
- args.Target = target;
- args.ID = rpc_type;
- args.Context = ctx;
- CF_ModuleGameManager.OnRPC(this, args);
- }
- void OnUpdate(float timeslice)
- {
- CF_ModuleGameManager.OnUpdate(this, new CF_EventUpdateArgs(timeslice));
- }
- void OnWorldCleanup()
- {
- CF_ModuleCoreManager.OnWorldCleanup(this, CF_EventArgs.Empty);
- }
- void OnMPSessionStart()
- {
- CF_ModuleCoreManager.OnMPSessionStart(this, CF_EventArgs.Empty);
- }
- void OnMPSessionPlayerReady()
- {
- CF_ModuleCoreManager.OnMPSessionPlayerReady(this, CF_EventArgs.Empty);
- }
- void OnMPSessionFail()
- {
- CF_ModuleCoreManager.OnMPSessionFail(this, CF_EventArgs.Empty);
- }
- void OnMPSessionEnd()
- {
- CF_ModuleCoreManager.OnMPSessionEnd(this, CF_EventArgs.Empty);
- }
- void OnMPConnectAbort()
- {
- CF_ModuleCoreManager.OnMPConnectAbort(this, CF_EventArgs.Empty);
- }
- void OnMPConnectionLost(int duration)
- {
- CF_ModuleCoreManager.OnMPConnectionLost(this, new CF_EventTimeArgs(duration));
- }
- void OnRespawn(int time)
- {
- CF_ModuleCoreManager.OnRespawn(this, new CF_EventTimeArgs(time));
- }
- }
- ref JMModuleManagerBase g_cf_ModuleManager = NULL;
- static void DestroyModuleManager()
- {
- delete g_cf_ModuleManager;
- }
- static bool ModuleManagerExists()
- {
- return g_cf_ModuleManager != NULL;
- }
- class CF_NetworkedVariables
- {
- const static int MAX_COUNT = 256;
- int m_Count;
- ref CF_NetworkVariable m_Head;
- CF_NetworkVariable m_Tail;
- Class m_Instance;
- void CF_NetworkedVariables(Class instance)
- {
- m_Instance = instance;
- }
- string ErrorPrefix()
- {
- return "(" + m_Instance + ") " + this + "::";
- }
- bool Register(string name)
- {
- // hard limit, no point attempting to sync more variables
- if (m_Count >= MAX_COUNT)
- {
- CF_Log.Error(ErrorPrefix() + "Register('" + name + "') -> More than " + MAX_COUNT + " variables registered, got '" + m_Count + "'");
- return false;
- }
- CF_NetworkVariable variable = new CF_NetworkVariable();
- typename type = m_Instance.Type();
- array<string> tokens();
- name.Split(".", tokens);
- variable.m_Name = name;
- if (tokens.Count() != 0)
- {
- if (tokens.Count() >= CF_NetworkVariable.MAX_DEPTH - 1)
- {
- CF_Log.Error(ErrorPrefix() + "RegisterNetSyncVariable('" + name + "') -> Variable depth more than " + (CF_NetworkVariable.MAX_DEPTH - 1) + ", got '" + tokens.Count() + "'");
- return false;
- }
- variable.m_Name = tokens[tokens.Count() - 1];
- int i, j;
- // iterate over all tokens to get the sub class for the variable
- for (i = 0; i < tokens.Count() - 1; i++)
- {
- bool success = false;
- for (j = 0; j < type.GetVariableCount(); j++)
- {
- if (type.GetVariableName(j) == tokens[i])
- {
- type = type.GetVariableType(j);
- variable.m_AccessorIndices[variable.m_Count] = j;
- variable.m_AccessorTypes[variable.m_Count] = type;
- variable.m_Count++;
- success = true;
- break;
- }
- }
- // couldn't find sub variable
- if (!success)
- {
- Error(ErrorPrefix() + "RegisterNetSyncVariable('" + name + "') -> Couldn't find sub variable '" + tokens[i] + "'");
- return false;
- }
- }
- }
- for (j = 0; j < type.GetVariableCount(); j++)
- {
- if (type.GetVariableName(j) == variable.m_Name)
- {
- type = type.GetVariableType(j);
- variable.m_AccessorIndices[variable.m_Count] = j;
- variable.m_AccessorTypes[variable.m_Count] = type;
- variable.m_Count++;
- variable.m_Converter = CF_TypeConverter.Get(type);
- if (!variable.m_Converter)
- {
- CF_Log.Error(ErrorPrefix() + "RegisterNetSyncVariable('" + name + "') -> TypeConverter not found for type '" + type + "'");
- return false;
- }
- if (!m_Tail)
- {
- m_Head = variable;
- m_Tail = variable;
- }
- else
- {
- m_Tail.m_Next = variable;
- m_Tail = variable;
- }
- m_Count++;
- return true;
- }
- }
- CF_Log.Error(ErrorPrefix() + "RegisterNetSyncVariable('" + name + "') -> Couldn't find variable '" + variable.m_Name + "'");
- return false;
- }
- void Write(ParamsWriteContext ctx)
- {
- CF_NetworkVariable variable = m_Head;
- while (variable)
- {
- Class instance = m_Instance;
- int index = variable.m_Count - 1;
- for (int j = 0; j < index; j++)
- {
- if (!instance)
- {
- break;
- }
- variable.m_AccessorTypes[j].GetVariableValue(instance, variable.m_AccessorIndices[j], instance);
- }
- if (instance)
- {
- variable.m_Converter.Read(instance, variable.m_AccessorIndices[index]);
- }
- // attempt writing even if instance is null so the count remains the same in sync
- variable.m_Converter.Write(ctx);
- variable = variable.m_Next;
- }
- }
- void Read(ParamsReadContext ctx)
- {
- CF_NetworkVariable variable = m_Head;
- while (variable)
- {
- Class instance = m_Instance;
- for (int j = 0; j < variable.m_Count - 1; j++)
- {
- if (!instance)
- {
- break;
- }
- variable.m_AccessorTypes[j].GetVariableValue(instance, variable.m_AccessorIndices[j], instance);
- }
- // attempt reading even if instance is null so the count remains the same in sync
- variable.m_Converter.Read(ctx);
- if (instance)
- {
- variable.m_Converter.Write(instance, variable.m_Name);
- }
- variable = variable.m_Next;
- }
- }
- };
- class CF_NetworkVariable
- {
- static const int MAX_DEPTH = 4;
- ref CF_NetworkVariable m_Next;
- string m_Name;
- int m_Count; // MAX_DEPTH
- int m_AccessorIndices[MAX_DEPTH];
- typename m_AccessorTypes[MAX_DEPTH];
- CF_TypeConverterBase m_Converter;
- };
- modded class NotificationRuntimeData
- {
- string m_Icon;
- string m_TitleText;
- int m_Color;
- bool m_HasShown;
- void NotificationRuntimeData( float time, NotificationData data, string detail_text )
- {
- m_StaticData = data;
- m_Icon = data.m_Icon;
- m_TitleText = data.m_TitleText;
- if ( detail_text != "" )
- {
- m_DetailText = detail_text;
- } else
- {
- m_DetailText = m_StaticData.m_DescriptionText;
- }
- m_Color = ARGB( 255, 221, 38, 38 );
- m_NotificationTime = time + NOTIFICATION_FADE_TIME;
- }
- void SetColor( int color )
- {
- m_Color = color;
- }
- int GetColor()
- {
- return m_Color;
- }
- override string GetIcon()
- {
- return m_Icon;
- }
- override string GetTitleText()
- {
- return m_TitleText;
- }
- }enum NotificationSystemRPC
- {
- INVALID = 9000,
- Create,
- COUNT
- };
- modded class NotificationSystem
- {
- /**
- * Sending of the notification
- *
- * If on the client it will create the notification, otherwise on the server it sends the notification to the specified client(s)
- *
- * @param title A localised supported way of creating a notification
- * @param text A localised supported way of creating a notification
- * @param icon The icon the notification will use
- * @param color The colour of the notification
- * @param time How long the notification will stay on the screen for (in seconds)
- * @param sendTo The player to send the notification to (everyone if NULL)
- */
- static void Create( StringLocaliser title, StringLocaliser text, string icon, int color, float time = 3, PlayerIdentity sendTo = NULL )
- {
- CreateNotification( title, text, icon, color, time, sendTo );
- }
- /**
- * Sending of the notification
- *
- * If on the client it will create the notification, otherwise on the server it sends the notification to the specified client(s)
- *
- * @param title A localised supported way of creating a notification
- * @param text A localised supported way of creating a notification
- * @param icon The icon the notification will use
- * @param color The colour of the notification
- * @param time How long the notification will stay on the screen for (in seconds)
- * @param sendTo The player to send the notification to (everyone if NULL)
- */
- static void CreateNotification( StringLocaliser title, StringLocaliser text, string icon, int color, float time = 3, PlayerIdentity sendTo = NULL )
- {
- if ( IsMissionHost() )
- {
- ScriptRPC rpc = new ScriptRPC();
- rpc.Write( title );
- rpc.Write( text );
- rpc.Write( icon );
- rpc.Write( color );
- rpc.Write( time );
- rpc.Send( NULL, NotificationSystemRPC.Create, true, sendTo );
- } else
- {
- Exec_CreateNotification( title, text, icon, color, time );
- }
- }
- /**
- * Creation of the notification
- *
- * @param title A localised supported way of creating a notification
- * @param text A localised supported way of creating a notification
- * @param icon The icon the notification will use
- * @param color The colour of the notification
- * @param time How long the notification will stay on the screen for (in seconds)
- */
- private static void Exec_CreateNotification( StringLocaliser title, StringLocaliser text, string icon, int color, float time )
- {
- NotificationRuntimeData data = new NotificationRuntimeData( time, new NotificationData( icon, title.Format() ), text.Format() );
- data.SetColor( color );
- m_Instance.AddNotif( data );
- }
- /**
- * An RPC handler for the data that is to be read from the notification.
- *
- * @param sender Always NULL
- * @param target Always NULL
- * @param ctx The data container for the rpc
- */
- static void RPC_CreateNotification( PlayerIdentity sender, Object target, ParamsReadContext ctx )
- {
- StringLocaliser title = new StringLocaliser( "" );
- if ( !ctx.Read( title ) )
- return;
- StringLocaliser text = new StringLocaliser( "" );
- if ( !ctx.Read( text ) )
- return;
- string icon;
- if ( !ctx.Read( icon ) )
- return;
- int color;
- if ( !ctx.Read( color ) )
- return;
- float time;
- if ( !ctx.Read( time ) )
- return;
- Exec_CreateNotification( title, text, icon, color, time );
- }
- /**
- * Adds the notification to the deferred array or displays it if
- * the maximum has not yet been reached.
- *
- * @param data The notification data to be displayed
- */
- protected void AddNotif( NotificationRuntimeData data )
- {
- if ( m_TimeArray.Count() < MAX_NOTIFICATIONS )
- {
- float time = GetGame().GetTickTime() + data.GetTime();
- data.SetTime( time + NOTIFICATION_FADE_TIME );
- m_TimeArray.Insert( data );
- m_OnNotificationAdded.Invoke( data );
- }
- else
- {
- m_DeferredArray.Insert( data );
- }
- }
- /**
- * Vanilla code to get the pre-created notification based on the type
- *
- * Required to create due to how Enforce Script modding works
- *
- * @param type The notification type
- */
- override NotificationData GetNotificationData( NotificationType type )
- {
- if ( m_DataArray.Contains( type ) )
- {
- return m_DataArray.Get( type );
- }
- return null;
- }
- /**
- * Vanilla code to get the pre-created notification based on the type
- *
- * Required to create due to how Enforce Script modding works
- *
- * @param type The notification type
- */
- override static void AddNotification( NotificationType type, float show_time, string detail_text = "" )
- {
- NotificationRuntimeData data = new NotificationRuntimeData( show_time, m_Instance.GetNotificationData( type ), detail_text );
- m_Instance.AddNotif( data );
- }
- override static void AddNotificationExtended( float show_time, string title_text, string detail_text = "", string icon = "" )
- {
- NotificationData temp_data = new NotificationData( icon, title_text );
- NotificationRuntimeData data = new NotificationRuntimeData( show_time, temp_data, detail_text );
- m_Instance.AddNotif( data );
- }
- };
- class CF_ObjectManager_ObjectLink extends OLinkT
- {
- int flags;
- int eventMask;
- }
- class CF_ObjectManager
- {
- //!Single static instance. Do not create with new or spawn - use CF.ObjectManager for access instead.
- protected void CF_ObjectManager()
- {
- #ifdef CF_TRACE_ENABLED
- auto trace = CF_Trace_0(this);
- #endif
- }
- protected void ~CF_ObjectManager()
- {
- #ifdef CF_TRACE_ENABLED
- auto trace = CF_Trace_0(this);
- #endif
- }
- protected static const int HIDE_OBJECT_AXIS_OFFSET = 10000;
- protected static const ref map<Object, ref CF_ObjectManager_ObjectLink> m_HiddenObjects = new map<Object, ref CF_ObjectManager_ObjectLink>();
- protected static const ref array<ref CF_ObjectManager_ObjectLink> m_HiddenObjectsArray = new array<ref CF_ObjectManager_ObjectLink>();
- /**
- * @brief Hides a static map object (Houses, Vegetation, etc.) visually and physically.
- * @code
- * Object hidden = CF.ObjectManager.HideMapObject(object);
- * @endcode
- *
- * @param object Object to be hidden
- * @param updatePathGraph Performs a path graph update after the object has been hidden. Enabled by default.
- * @return Object instance of the object that was hidden, NULL in case of failure or invalid params.
- */
- static Object HideMapObject(Object object, bool updatePathGraph = true)
- {
- if (!IsMapObject(object)) return NULL; //Object is not a map object
- if (IsMapObjectHidden(object)) return NULL; //Object already hidden
- //Remember the original position for path graph updates
- auto originalPosition = object.GetPosition();
- //Register object in it's current state
- auto link = new CF_ObjectManager_ObjectLink(object);
- link.flags = object.GetFlags();
- link.eventMask = object.GetEventMask();
- object.ClearFlags(link.flags, true);
- object.ClearEventMask(link.eventMask);
- m_HiddenObjects.Set(object, link);
- m_HiddenObjectsArray.Insert(link);
- vector tm[4];
- object.GetTransform(tm);
- tm[3] = tm[3] - Vector(HIDE_OBJECT_AXIS_OFFSET, HIDE_OBJECT_AXIS_OFFSET, HIDE_OBJECT_AXIS_OFFSET);
- object.SetTransform(tm);
- object.Update();
- if (updatePathGraph && object.CanAffectPathgraph())
- {
- vector minMax[2];
- auto objectRadius = object.ClippingInfo(minMax);
- auto radiusVector = Vector(objectRadius, objectRadius, objectRadius);
- g_Game.UpdatePathgraphRegion(originalPosition - radiusVector, originalPosition + radiusVector);
- }
- return object;
- }
- /**
- * @brief Unhides an array of map objects
- * @code
- * array<Object> hidden = CF.ObjectManager.HideMapObjects(objects);
- * @endcode
- *
- * @param objects Objects to be hidden
- * @param updatePathGraph Performs a path graph update after the objects were hidden. Enabled by default.
- * @return array<Object> Array of objects that were hidden.
- */
- static array<Object> HideMapObjects(array<Object> objects, bool updatePathGraph = true)
- {
- array<Object> hidden();
- foreach (auto object: objects)
- {
- /*
- Todo potential improvement:
- Determine if a single path graph update over the whole area is more effective that many small ones.
- Possible metrics:
- - Object count to area ratio
- - Max distance between objects
- - Fixed radius lookup table
- */
- if (HideMapObject(object, updatePathGraph))
- {
- hidden.Insert(object);
- }
- }
- return hidden;
- }
- /**
- * @brief Hides static map objects at certain position and within a given radius
- * @code
- * array<Object> hidden = CF.ObjectManager.HideMapObjectsInRadius(position, 1000);
- * @endcode
- *
- * @param centerPosition center coordinates for the hide area.
- * @param radius radius of the hide area.
- * @param limitHeight y-axis limit for the hide area (Sphere). Disabled by default.
- * @param updatePathGraph Performs a path graph update after the objects were hidden. Enabled by default.
- * @return array<Object> Array of objects that were hidden.
- */
- static array<Object> HideMapObjectsInRadius(vector centerPosition, float radius, bool limitHeight = false, bool updatePathGraph = true)
- {
- array<Object> objects();
- if (limitHeight)
- {
- GetGame().GetObjectsAtPosition3D(centerPosition, radius, objects, NULL);
- }
- else
- {
- GetGame().GetObjectsAtPosition(centerPosition, radius, objects, NULL);
- }
- array<Object> hidden();
- foreach (auto object: objects)
- {
- //Todo potential improvement -> s. HideMapObjects
- if (HideMapObject(object, updatePathGraph))
- {
- hidden.Insert(object);
- }
- }
- return hidden;
- }
- /**
- * @brief Unhides a hidden static map object (Houses, Vegetation, etc.).
- * @code
- * Object unhidden = CF.ObjectManager.UnhideMapObject(hiddenObject);
- * @endcode
- *
- * @param object Object to be unhidden
- * @param updatePathGraph Performs a path graph update after the object has been unhidden. Enabled by default.
- * @return Object instance of the object that was unhidden, NULL in case of failure or invalid params.
- */
- static Object UnhideMapObject(Object object, bool updatePathGraph = true)
- {
- //Remove object from hidden collection
- auto link = m_HiddenObjects[object];
- if (!link) return NULL; //Object not known as hidden
- m_HiddenObjects.Remove(object);
- auto arrayIdx = m_HiddenObjectsArray.Find(link);
- if(arrayIdx >= 0) m_HiddenObjectsArray.Remove(arrayIdx);
- vector tm[4];
- object.GetTransform(tm);
- tm[3] = tm[3] + Vector(HIDE_OBJECT_AXIS_OFFSET, HIDE_OBJECT_AXIS_OFFSET, HIDE_OBJECT_AXIS_OFFSET);
- object.SetTransform(tm);
- object.SetFlags(link.flags, true);
- object.SetEventMask(link.eventMask);
- object.Update();
- if (updatePathGraph && object.CanAffectPathgraph())
- {
- vector minMax[2];
- auto objectPosition = object.GetPosition();
- auto objectRadius = object.ClippingInfo(minMax);
- auto radiusVector = Vector(objectRadius, objectRadius, objectRadius);
- g_Game.UpdatePathgraphRegion(objectPosition - radiusVector, objectPosition + radiusVector);
- }
- return object;
- }
- /**
- * @brief Unhides an array of map objects
- * @code
- * array<Object> unhidden = CF.ObjectManager.UnhideMapObjects(hiddenObjects);
- * @endcode
- *
- * @param objects Objects to be unhidden
- * @param updatePathGraph Performs a path graph update after the objects were unhidden. Enabled by default.
- * @return array<Object> Array of objects that were unhidden.
- */
- static array<Object> UnhideMapObjects(array<Object> objects, bool updatePathGraph = true)
- {
- array<Object> unhidden();
- foreach (auto object: objects)
- {
- //Todo potential improvement -> s. HideMapObjects
- if (UnhideMapObject(object, updatePathGraph))
- {
- unhidden.Insert(object);
- }
- }
- return unhidden;
- }
- /**
- * @brief Unhides static map objects at certain position and within a given radius
- * @code
- * array<Object> unhidden = CF.ObjectManager.UnhideMapObjectsInRadius(position, 1000);
- * @endcode
- *
- * @param centerPosition center coordinates for the unhide area.
- * @param radius radius of the unhide area.
- * @param limitHeight y-axis limit for the unhide area (Sphere). Disabled by default.
- * @param updatePathGraph Performs a path graph update after the objects were unhidden. Enabled by default.
- * @return array<Object> Array of objects that were unhidden.
- */
- static array<Object> UnhideMapObjectsInRadius(vector centerPosition, float radius, bool limitHeight = false, bool updatePathGraph = true)
- {
- array<Object> objects();
- if (limitHeight)
- {
- GetGame().GetObjectsAtPosition3D(centerPosition, radius, objects, NULL);
- }
- else
- {
- GetGame().GetObjectsAtPosition(centerPosition, radius, objects, NULL);
- }
- return UnhideMapObjects(objects, updatePathGraph);
- }
- /**
- * @brief Unhides all hidden map objects
- * @code
- * array<Object> unhidden = CF.ObjectManager.UnhideAllMapObjects();
- * @endcode
- *
- * @param updatePathGraph Performs a path graph update after the objects were unhidden. Enabled by default.
- * @return array<Object> Array of objects that were unhidden.
- */
- static array<Object> UnhideAllMapObjects(bool updatePathGraph = true)
- {
- //Expected result would be all the hidden objects
- auto unhidden = GetHiddenMapObjects();
- for(int nObject = 0; nObject < unhidden.Count(); nObject++)
- {
- //Todo potential improvement -> s. HideMapObjects
- if (!UnhideMapObject(unhidden[nObject], updatePathGraph))
- {
- //If - for what ever reason - the object was not unhidden, remove it from the result collection.
- unhidden.RemoveOrdered(nObject--);
- }
- }
- return unhidden;
- }
- /**
- * @brief Returns all map objects that are currently hidden
- * @code
- * array<Object> objects = CF.ObjectManager.GetHiddenMapObjects();
- * @endcode
- *
- * @return array<Object> Array of hidden objects.
- */
- static array<Object> GetHiddenMapObjects()
- {
- array<Object> objects();
- foreach(auto link : m_HiddenObjectsArray)
- {
- objects.Insert(link.Ptr());
- }
- return objects;
- }
- /**
- * @brief Checks if a map object is currently hidden.
- * @code
- * bool isHiddenObject = CF.ObjectManager.IsMapObjectHidden(object);
- * @endcode
- *
- * @param object Object to check
- * @return bool true if currently hidden, false otherwise.
- */
- static bool IsMapObjectHidden(Object object)
- {
- return m_HiddenObjects.Contains(object);
- }
- /**
- * @brief Checks if the given object is part of the baked map objects.
- * @code
- * bool isMapObject = CF.ObjectManager.IsMapObject(object);
- * @endcode
- *
- * @param object Object pointer
- * @return bool true if it is a map object, false otherwise.
- */
- static bool IsMapObject(Object object)
- {
- if (!object) return false; //Null
- // Added via p3d in TB with no config.
- // Inherits from House in Cfg class -> Building, House, Wreck, Well, Tree, Bush, etc.
- return ((object.GetType() == string.Empty) && (object.Type() == Object)) || object.IsKindOf("House") || object.IsTree() || object.IsBush() || object.IsRock() || object.IsInherited(Static);
- }
- /**
- * @brief [Internal] CommunityFramework cleanup
- *
- * @return void
- */
- static void _Cleanup()
- {
- //Cleanup hidden object allocation
- m_HiddenObjects.Clear();
- delete m_HiddenObjects;
- m_HiddenObjectsArray.Clear();
- delete m_HiddenObjectsArray;
- }
- }
- enum SingeplayerExecutionType
- {
- Server = 0,
- Client,
- Both
- }
- enum SingleplayerExecutionType
- {
- Server = 0,
- Client,
- Both
- }
- enum CallType
- {
- Server = 0,
- Client
- }
- class RPCMetaWrapper
- {
- protected Class m_Instance;
- protected int m_SPExecType;
- void RPCMetaWrapper( Class instance, int spExecType )
- {
- m_Instance = instance;
- m_SPExecType = spExecType;
- }
- Class GetInstance()
- {
- return m_Instance;
- }
- // Determines if the server or client function is what is called in singleplayer mode
- int GetSPExecutionType()
- {
- return m_SPExecType;
- }
- };
- class RPCManager
- {
- static const int FRAMEWORK_RPC_ID = 10042;
- protected autoptr map< string, ref map< string, ref RPCMetaWrapper > > m_RPCActions = new map< string, ref map< string, ref RPCMetaWrapper > >;
- void OnRPC( PlayerIdentity sender, Object target, int rpc_type, ParamsReadContext ctx )
- {
- #ifdef CF_TRACE_ENABLED
- auto trace = CF_Trace_4(this).Add(sender).Add(target).Add(rpc_type).Add(ctx);
- #endif
- Param2< string, string > metaData;
- if ( !ctx.Read( metaData ) )
- {
- CF_Log.Warn( "Failed reading the RPC metadata!");
- return;
- }
- string modName = metaData.param1;
- string funcName = metaData.param2;
- string recievedFrom = "server";
- if ( GetGame().IsDedicatedServer() )
- {
- if ( sender == NULL )
- {
- CF_Log.Warn( "RPC sent from invalid sender!");
- return;
- }
- recievedFrom = sender.GetPlainId();
- }
- map< string, ref RPCMetaWrapper > functions;
- if ( m_RPCActions.Find( modName, functions ) )
- {
- RPCMetaWrapper wrapper;
- if ( functions.Find( funcName, wrapper ) )
- {
- if ( wrapper.GetInstance() )
- {
- auto functionCallData = new Param4< CallType, ParamsReadContext, PlayerIdentity, Object >( CallType.Server, ctx, sender, target );
- if ( ( GetGame().IsServer() && GetGame().IsMultiplayer() ) || ( GetGame().IsServer() && !GetGame().IsMultiplayer() && ( wrapper.GetSPExecutionType() == SingleplayerExecutionType.Server || wrapper.GetSPExecutionType() == SingleplayerExecutionType.Both ) ) )
- {
- GetGame().GameScript.CallFunctionParams( wrapper.GetInstance(), funcName, NULL, functionCallData );
- }
- if ( ( GetGame().IsClient() && GetGame().IsMultiplayer() ) || ( GetGame().IsServer() && !GetGame().IsMultiplayer() && ( wrapper.GetSPExecutionType() == SingleplayerExecutionType.Client || wrapper.GetSPExecutionType() == SingleplayerExecutionType.Both ) ) )
- {
- //Update call type
- functionCallData.param1 = CallType.Client;
- GetGame().GameScript.CallFunctionParams( wrapper.GetInstance(), funcName, NULL, functionCallData );
- }
- }
- } else
- {
- CF_Log.Warn( recievedFrom + " tried sending " + modName + "::<" + funcName + "> which does not seem to exist!");
- }
- } else
- {
- CF_Log.Warn( recievedFrom + " tried sending <" + modName + ">::" + funcName + " which does not seem to exist!");
- }
- }
- void SendRPC( string modName, string funcName, Param params = NULL, bool guaranteed = false, PlayerIdentity sendToIdentity = NULL, Object sendToTarget = NULL )
- {
- #ifdef CF_TRACE_ENABLED
- auto trace = CF_Trace_6(this).Add(modName).Add(funcName).Add(params).Add(guaranteed).Add(sendToIdentity).Add(sendToTarget);
- #endif
- auto sendData = new array< ref Param >;
- sendData.Insert( new Param2< string, string >( modName, funcName ) );
- sendData.Insert( params );
- //In case we are in the singleplayer and the data is consumed twice for both client and server, we need to add it twice. Better than making a deep copy with more complicated rules on receiving
- if ( !GetGame().IsMultiplayer() )
- {
- if ( m_RPCActions.Contains( modName ) )
- {
- if ( m_RPCActions[ modName ].Contains( funcName ) )
- {
- RPCMetaWrapper wrapper = m_RPCActions[ modName ][ funcName ];
- if ( ( wrapper.GetSPExecutionType() == SingleplayerExecutionType.Both ) )
- {
- sendData.Insert( params );
- }
- }
- }
- }
- GetGame().RPC( sendToTarget, FRAMEWORK_RPC_ID, sendData, guaranteed, sendToIdentity );
- }
- /**
- * Warning: Does not support "SingleplayerExecutionType.Both"
- */
- void SendRPCs( string modName, string funcName, array< ref Param > params, bool guaranteed = false, PlayerIdentity sendToIdentity = NULL, Object sendToTarget = NULL )
- {
- #ifdef CF_TRACE_ENABLED
- auto trace = CF_Trace_6(this).Add(modName).Add(funcName).Add(params).Add(guaranteed).Add(sendToIdentity).Add(sendToTarget);
- #endif
- params.InsertAt( new Param2< string, string >( modName, funcName ), 0 );
- GetGame().RPC( sendToTarget, FRAMEWORK_RPC_ID, params, guaranteed, sendToIdentity );
- if ( !GetGame().IsMultiplayer() )
- {
- if ( m_RPCActions.Contains( modName ) )
- {
- if ( m_RPCActions[ modName ].Contains( funcName ) )
- {
- RPCMetaWrapper wrapper = m_RPCActions[ modName ][ funcName ];
- if ( ( wrapper.GetSPExecutionType() == SingleplayerExecutionType.Both ) )
- {
- CF_Log.Warn( modName + "::" + funcName + " does not support \"SingleplayerExecutionType.Both\" when using RPCManager::SendRPCs, use RPCManager::SendRPC instead!");
- }
- }
- }
- }
- }
- bool AddRPC( string modName, string funcName, Class instance, int singlePlayerExecType = SingleplayerExecutionType.Server )
- {
- #ifdef CF_TRACE_ENABLED
- auto trace = CF_Trace_4(this).Add(modName).Add(funcName).Add(instance).Add(singlePlayerExecType);
- #endif
- if ( !m_RPCActions.Contains( modName ) )
- {
- m_RPCActions.Set( modName, new map< string, ref RPCMetaWrapper > );
- }
- auto wrapper = new RPCMetaWrapper( instance, singlePlayerExecType );
- m_RPCActions[ modName ].Set( funcName, wrapper );
- return true;
- }
- };
- static ref RPCManager g_RPCManager;
- static RPCManager GetRPCManager()
- {
- if ( !g_RPCManager )
- {
- g_RPCManager = new RPCManager();
- }
- return g_RPCManager;
- }
- static autoptr CF_TypeConverterConstructor g_CF_TypeConverterConstructor = null;
- class CF_TypeConverterConstructor
- {
- private void CF_TypeConverterConstructor()
- {
- #ifdef CF_TRACE_ENABLED
- auto trace = CF_Trace_0(this);
- #endif
- CF_TypeConverter._OnCreate();
- }
- /**
- * @note We can safely guarantee the destructor is called on script reload,
- * we can't do the same for 'OnGameDestroy'.
- */
- void ~CF_TypeConverterConstructor()
- {
- #ifdef CF_TRACE_ENABLED
- auto trace = CF_Trace_0(this);
- #endif
- CF_TypeConverter._OnDestroy();
- }
- [CF_EventSubscriber(ScriptCaller.Create(CF_TypeConverterConstructor._Init), CF_LifecycleEvents.OnGameCreate)]
- static void _Init()
- {
- if (g_CF_TypeConverterConstructor)
- {
- return;
- }
- g_CF_TypeConverterConstructor = new CF_TypeConverterConstructor();
- }
- [CF_EventSubscriber(ScriptCaller.Create(CF_TypeConverterConstructor._Cleanup), CF_LifecycleEvents.OnGameDestroy)]
- static void _Cleanup()
- {
- g_CF_TypeConverterConstructor = null;
- }
- };
- [CF_RegisterTypeConverter(CF_TypeConverterBool)]
- class CF_TypeConverterBool : CF_TypeConverterT<bool>
- {
- override void SetInt(int value)
- {
- m_Value = value;
- }
- override int GetInt()
- {
- return m_Value;
- }
- override void SetBool(bool value)
- {
- m_Value = value;
- }
- override bool GetBool()
- {
- return m_Value;
- }
- override void SetFloat(float value)
- {
- m_Value = value;
- }
- override float GetFloat()
- {
- return m_Value;
- }
- override void SetVector(vector value)
- {
- }
- override vector GetVector()
- {
- return vector.Zero;
- }
- override void SetString(string value)
- {
- m_Value = CF_Encoding.StringToBool(value);
- }
- override string GetString()
- {
- return "" + m_Value;
- }
- override bool IsIOSupported()
- {
- return true;
- }
- override bool Write(CF_IO io)
- {
- io.WriteBool(m_Value);
- return true;
- }
- override bool Read(CF_IO io)
- {
- m_Value = io.ReadBool();
- return true;
- }
- };
- [CF_RegisterTypeConverter(CF_TypeConverterClass)]
- class CF_TypeConverterClass : CF_TypeConverterT<Class>
- {
- override int GetInt()
- {
- return (int) m_Value;
- }
- override bool GetBool()
- {
- return m_Value != null;
- }
- override float GetFloat()
- {
- return GetInt();
- }
- override string GetString()
- {
- if (!m_Value) return "NULL";
- return m_Value.GetDebugName();
- }
- override void SetClass(Class value)
- {
- m_Value = value;
- }
- override Class GetClass()
- {
- return m_Value;
- }
- };
- [CF_RegisterTypeConverter(CF_TypeConverterDate)]
- class CF_TypeConverterDate : CF_TypeConverterManaged
- {
- private string m_Format = "YYYY-MM-DD hh:mm:ss";
- override void SetInt(int value)
- {
- CF_Date date = GetDate();
- if (!date) return;
- date.EpochToDate(value);
- }
- override int GetInt()
- {
- CF_Date date = GetDate();
- if (!date) return 0;
- return date.DateToEpoch();
- }
- override string GetString()
- {
- CF_Date date = GetDate();
- if (!date) return "1970-01-01 00:00:00";
- return date.ToString(m_Format);
- }
- override void SetString(string value)
- {
- CF_Date date = GetDate();
- if (!date) return;
- //date.StringToDate(value);
- }
- override typename GetType()
- {
- typename type = CF_Date;
- return type;
- }
- CF_Date GetDate()
- {
- return CF_Date.Cast(m_Value);
- }
- };
- [CF_RegisterTypeConverter(CF_TypeConverterExpression)]
- class CF_TypeConverterExpression : CF_TypeConverterClass
- {
- override void SetBool(bool value)
- {
- }
- override bool GetBool()
- {
- return GetFloat() != 0.0;
- }
- override void SetInt(int value)
- {
- }
- override int GetInt()
- {
- return GetFloat();
- }
- override void SetFloat(float value)
- {
- }
- override float GetFloat()
- {
- CF_Expression expr = GetExpression();
- if (!expr) return 0;
- return expr.Evaluate(new array<float>);
- }
- override string GetString()
- {
- CF_Expression expr = GetExpression();
- if (!expr) return "";
- return expr.GetSource();
- }
- override void SetString(string value)
- {
- CF_Expression expr = GetExpression();
- if (!expr) return;
- expr.SetSource(value);
- expr.Compile(new array<string>);
- }
- override typename GetType()
- {
- typename type = CF_Expression;
- return type;
- }
- CF_Expression GetExpression()
- {
- return CF_Expression.Cast(m_Value);
- }
- };
- [CF_RegisterTypeConverter(CF_TypeConverterFile)]
- class CF_TypeConverterFile : CF_TypeConverterClass
- {
- override string GetString()
- {
- CF_File file = GetFile();
- if (!file)
- {
- return "";
- }
- return file.GetFileName();
- }
- override void SetString(string value)
- {
- CF_File file = GetFile();
- if (!file)
- {
- return;
- }
- file.Rename(value);
- }
- override typename GetType()
- {
- typename type = CF_File;
- return type;
- }
- CF_File GetFile()
- {
- return CF_File.Cast(m_Value);
- }
- };
- [CF_RegisterTypeConverter(CF_TypeConverterFloat)]
- class CF_TypeConverterFloat : CF_TypeConverterT<float>
- {
- override void SetInt(int value)
- {
- m_Value = value;
- }
- override int GetInt()
- {
- return m_Value;
- }
- override void SetBool(bool value)
- {
- m_Value = value;
- }
- override bool GetBool()
- {
- return m_Value != 0.0;
- }
- override void SetFloat(float value)
- {
- m_Value = value;
- }
- override float GetFloat()
- {
- return m_Value;
- }
- override void SetVector(vector value)
- {
- }
- override vector GetVector()
- {
- return vector.Zero;
- }
- override void SetString(string value)
- {
- m_Value = value.ToFloat();
- }
- override string GetString()
- {
- return "" + m_Value;
- }
- override bool IsIOSupported()
- {
- return true;
- }
- override bool Write(CF_IO io)
- {
- io.WriteFloat(m_Value);
- return true;
- }
- override bool Read(CF_IO io)
- {
- m_Value = io.ReadFloat();
- return true;
- }
- };
- [CF_RegisterTypeConverter(CF_TypeConverterInt)]
- class CF_TypeConverterInt : CF_TypeConverterT<int>
- {
- override void SetInt(int value)
- {
- m_Value = value;
- }
- override int GetInt()
- {
- return m_Value;
- }
- override void SetBool(bool value)
- {
- m_Value = value;
- }
- override bool GetBool()
- {
- return m_Value != 0;
- }
- override void SetFloat(float value)
- {
- m_Value = value;
- }
- override float GetFloat()
- {
- return m_Value;
- }
- override void SetVector(vector value)
- {
- }
- override vector GetVector()
- {
- return vector.Zero;
- }
- override void SetString(string value)
- {
- m_Value = value.ToInt();
- }
- override string GetString()
- {
- return "" + m_Value;
- }
- override bool IsIOSupported()
- {
- return true;
- }
- override bool Read(CF_IO io)
- {
- m_Value = io.ReadInt();
- return true;
- }
- override bool Write(CF_IO io)
- {
- io.WriteInt(m_Value);
- return true;
- }
- };
- [CF_RegisterTypeConverter(CF_TypeConverterLocaliser)]
- class CF_TypeConverterLocaliser : CF_TypeConverterClass
- {
- override string GetString()
- {
- CF_Localiser localiser = GetLocaliser();
- if (!localiser)
- {
- return "";
- }
- return localiser.Format();
- }
- override void SetString(string value)
- {
- }
- override typename GetType()
- {
- typename type = CF_Localiser;
- return type;
- }
- CF_Localiser GetLocaliser()
- {
- return CF_Localiser.Cast(m_Value);
- }
- };
- [CF_RegisterTypeConverter(CF_TypeConverterManaged)]
- class CF_TypeConverterManaged : CF_TypeConverterT<Managed>
- {
- override string GetString()
- {
- if (!m_Value) return "NULL";
- return m_Value.GetDebugName();
- }
- override void SetClass(Class value)
- {
- Class.CastTo(m_Value, value);
- }
- override Class GetClass()
- {
- return m_Value;
- }
- override void SetManaged(Managed value)
- {
- m_Value = value;
- }
- override Managed GetManaged()
- {
- return m_Value;
- }
- };
- [CF_RegisterTypeConverter(CF_TypeConverterString)]
- class CF_TypeConverterString : CF_TypeConverterT<string>
- {
- override void SetInt(int value)
- {
- m_Value = "" + value;
- }
- override int GetInt()
- {
- return m_Value.ToInt();
- }
- override void SetBool(bool value)
- {
- m_Value = "" + value;
- }
- override bool GetBool()
- {
- return CF_Encoding.StringToBool(m_Value);
- }
- override void SetFloat(float value)
- {
- m_Value = "" + value;
- }
- override float GetFloat()
- {
- return m_Value.ToFloat();
- }
- override void SetVector(vector value)
- {
- m_Value = "" + value;
- }
- override vector GetVector()
- {
- return m_Value.ToVector();
- }
- override void SetString(string value)
- {
- m_Value = value;
- }
- override string GetString()
- {
- return m_Value;
- }
- override bool IsIOSupported()
- {
- return true;
- }
- override bool Write(CF_IO io)
- {
- io.WriteString(m_Value);
- return true;
- }
- override bool Read(CF_IO io)
- {
- m_Value = io.ReadString();
- return true;
- }
- };
- [CF_RegisterTypeConverter(CF_TypeConverterVector)]
- class CF_TypeConverterVector : CF_TypeConverterT<vector>
- {
- override void SetVector(vector value)
- {
- m_Value = value;
- }
- override vector GetVector()
- {
- return m_Value;
- }
- override void SetString(string value)
- {
- m_Value = value.ToVector();
- }
- override string GetString()
- {
- return "" + m_Value;
- }
- override bool IsIOSupported()
- {
- return true;
- }
- override bool Write(CF_IO io)
- {
- io.WriteVector(m_Value);
- return true;
- }
- override bool Read(CF_IO io)
- {
- m_Value = io.ReadVector();
- return true;
- }
- };
- typedef CF_Date JMDate; // Compatability with a variety of mods.
- class CF_Date : Managed
- {
- // TODO: Stringtable
- static const string MONTHS_FULL_NAME[12] = {"January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"};
- static const string MONTHS_SHORT_NAME[12] = {"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"};
- static const int DAYS_IN_MONTH[12] = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
- static const string TIME = "hh:mm:ss";
- static const string DATE = "YYYY-MM-DD";
- static const string DATETIME = "YYYY-MM-DD hh:mm:ss";
- protected bool m_UseUTC;
- protected int m_Year;
- protected int m_Month;
- protected int m_Day;
- protected int m_Hour;
- protected int m_Minute;
- protected int m_Second;
- //! Compile error if protected
- private void CF_Date()
- {
- }
- static CF_Date Now(bool useUTC = false)
- {
- CF_Date date = new CF_Date();
- date.m_UseUTC = useUTC;
- if (date.m_UseUTC)
- {
- GetYearMonthDayUTC(date.m_Year, date.m_Month, date.m_Day);
- GetHourMinuteSecondUTC(date.m_Hour, date.m_Minute, date.m_Second);
- }
- else
- {
- GetYearMonthDay(date.m_Year, date.m_Month, date.m_Day);
- GetHourMinuteSecond(date.m_Hour, date.m_Minute, date.m_Second);
- }
- return date;
- }
- static CF_Date Epoch(int timestamp)
- {
- CF_Date date = new CF_Date();
- date.m_UseUTC = false;
- date.EpochToDate(timestamp);
- return date;
- }
- static CF_Date CreateDate(int year, int month, int day)
- {
- CF_Date date = new CF_Date();
- date.m_UseUTC = false;
- date.m_Year = year;
- date.m_Month = month;
- date.m_Day = day;
- GetHourMinuteSecond(date.m_Hour, date.m_Minute, date.m_Second);
- return date;
- }
- static CF_Date CreateTime(int hour, int minute, int second)
- {
- CF_Date date = new CF_Date();
- date.m_UseUTC = false;
- GetYearMonthDay(date.m_Year, date.m_Month, date.m_Day);
- date.m_Hour = hour;
- date.m_Minute = minute;
- date.m_Second = second;
- return date;
- }
- static CF_Date CreateDateTime(int year, int month, int day, int hour, int minute, int second)
- {
- CF_Date date = new CF_Date();
- date.m_UseUTC = false;
- date.m_Year = year;
- date.m_Month = month;
- date.m_Day = day;
- date.m_Hour = hour;
- date.m_Minute = minute;
- date.m_Second = second;
- return date;
- }
- //! UTILS
- static bool IsLeapYear(int year)
- {
- if (year % 400 == 0)
- return true;
- if (year % 100 == 0)
- return false;
- if (year % 4 == 0)
- return true;
- return false;
- }
- /**
- * Based on: https://en.wikipedia.org/wiki/Unix_time
- *
- * MAJOR NOTE:
- * Timestamp start at Year 1970, if any functions / methods linked
- * to Timestamp, be aware of using any date at least starting at this
- * year.
- *
- * @param {int} year
- * @param {int} month
- * @param {int} day
- * @param {int} hour
- * @param {int} minute
- * @param {int} second
- *
- * @return Timestamp in m_Second
- */
- static int Timestamp(int year, int month, int day, int hours, int minutes, int seconds)
- {
- if (year < 1970)
- return 0;
- bool isLeapYear = IsLeapYear(year);
- int timestamp = 0;
- for (int iYear = 1970; iYear < year; ++iYear)
- {
- if (IsLeapYear(iYear))
- {
- timestamp += 31622400;
- }
- else
- {
- timestamp += 31536000;
- }
- }
- for (int iMonth = 1; iMonth < month; iMonth++)
- {
- if (isLeapYear && iMonth == 2)
- {
- timestamp += 86400;
- }
- timestamp += DAYS_IN_MONTH[iMonth - 1] * 86400;
- }
- for (int iDay = 1; iDay < day; iDay++)
- {
- timestamp += 86400;
- }
- timestamp += hours * 3600;
- timestamp += minutes * 60;
- timestamp += seconds;
- return timestamp;
- }
- static void TimestampToDate(int timestamp, out int year, out int month, out int day, out int hours, out int minutes, out int seconds)
- {
- if (timestamp < 0)
- return;
- int iTimestamp = 0;
- iTimestamp = TimestampCalculYear(timestamp, year);
- iTimestamp = TimestampCalculMonth(iTimestamp, timestamp, year, month);
- iTimestamp = TimestampCalculDays(iTimestamp, timestamp, day);
- iTimestamp = TimestampCalculHours(iTimestamp, timestamp, hours);
- iTimestamp = TimestampCalculMinutes(iTimestamp, timestamp, minutes);
- iTimestamp = TimestampCalculSeconds(iTimestamp, timestamp, seconds);
- }
- protected static int TimestampCalculYear(int timestamp, out int year)
- {
- int iTimestamp = 0;
- year = 1970;
- while (iTimestamp < timestamp)
- {
- int yearTimestamp;
- if (IsLeapYear(year))
- yearTimestamp = 31622400;
- else
- yearTimestamp = 31536000;
- if (iTimestamp + yearTimestamp > timestamp)
- break;
- iTimestamp += yearTimestamp;
- year++;
- }
- return iTimestamp;
- }
- protected static int TimestampCalculMonth(int iTimestamp, int timestamp, int year, out int month)
- {
- bool isLeapYear = IsLeapYear(year);
- month = 0;
- while (iTimestamp < timestamp)
- {
- int monthTimestamp;
- if (isLeapYear && month == 1)
- monthTimestamp = 2505600;
- else
- monthTimestamp = DAYS_IN_MONTH[month] * 86400;
- if (iTimestamp + monthTimestamp > timestamp)
- break;
- iTimestamp += monthTimestamp;
- month++;
- }
- month++;
- return iTimestamp;
- }
- protected static int TimestampCalculDays(int iTimestamp, int timestamp, out int days)
- {
- days = 1;
- while (iTimestamp < timestamp)
- {
- if (iTimestamp + 86400 > timestamp)
- break;
- iTimestamp += 86400;
- days++;
- }
- return iTimestamp;
- }
- protected static int TimestampCalculHours(int iTimestamp, int timestamp, out int hours)
- {
- hours = 0;
- while (iTimestamp < timestamp)
- {
- if (iTimestamp + 3600 > timestamp)
- break;
- iTimestamp += 3600;
- hours++;
- }
- return iTimestamp;
- }
- protected static int TimestampCalculMinutes(int iTimestamp, int timestamp, out int minutes)
- {
- minutes = 0;
- while (iTimestamp < timestamp)
- {
- if (iTimestamp + 60 > timestamp)
- break;
- iTimestamp += 60;
- minutes++;
- }
- return iTimestamp;
- }
- protected static int TimestampCalculSeconds(int iTimestamp, int timestamp, out int seconds)
- {
- seconds = 0;
- while (iTimestamp < timestamp)
- {
- iTimestamp++;
- seconds++;
- }
- return iTimestamp;
- }
- int Compare(CF_Date other)
- {
- int timestamp1 = this.GetTimestamp();
- int timestamp2 = other.GetTimestamp();
- if (timestamp1 < timestamp2) {
- return -1;
- } else if (timestamp1 > timestamp2) {
- return 1;
- } else {
- return 0;
- }
- }
- void CalculateDifference(CF_Date other, out int hoursDiff, out int minutesDiff)
- {
- int timestamp1 = this.GetTimestamp();
- int timestamp2 = other.GetTimestamp();
- int timestampDiff = timestamp2 - timestamp1;
- hoursDiff = timestampDiff / 3600;
- minutesDiff = (timestampDiff % 3600) / 60;
- }
- void EpochToDate(int value)
- {
- int iTimestamp;
- iTimestamp = TimestampCalculYear(value, m_Year);
- iTimestamp = TimestampCalculMonth(iTimestamp, value, m_Year, m_Month);
- iTimestamp = TimestampCalculDays(iTimestamp, value, m_Day);
- iTimestamp = TimestampCalculHours(iTimestamp, value, m_Hour);
- iTimestamp = TimestampCalculMinutes(iTimestamp, value, m_Minute);
- iTimestamp = TimestampCalculSeconds(iTimestamp, value, m_Second);
- }
- int DateToEpoch()
- {
- return Timestamp(m_Year, m_Month, m_Day, m_Hour, m_Minute, m_Second);
- }
- /**
- * @return string with format: "month day, year hours:minutes:seconds"
- */
- string DateToString()
- {
- string dateToString = GetFullMonthString();
- dateToString += " " + m_Day.ToStringLen(2);
- dateToString += ", " + m_Year;
- dateToString += " " + m_Hour.ToStringLen(2) + ":" + m_Minute.ToStringLen(2) + ":" + m_Second.ToStringLen(2);
- return dateToString;
- }
- override string GetDebugName()
- {
- return DateToString();
- }
- /**
- * @param format Supply a format such as "YYYY-MM-DD hh:mm:ss"
- */
- string Format(string format)
- {
- FormatField(format, m_Year.ToString(), "Y");
- FormatField(format, m_Month.ToString(), "M");
- FormatField(format, m_Day.ToString(), "D");
- FormatField(format, m_Hour.ToString(), "h");
- FormatField(format, m_Minute.ToString(), "m");
- FormatField(format, m_Second.ToString(), "s");
- return format;
- }
- string ToString(string format)
- {
- return Format(format);
- }
- protected void FormatField(inout CF_String format, CF_String field, CF_String char)
- {
- int index;
- int count = format.CountCharacter(char, index);
- int length = field.Length();
- if (length < count)
- {
- field = field.PadStringFront(count, "0");
- }
- if (field.Length() > count)
- {
- field = field.Substring(0, count);
- }
- format = format.SpliceString(index, field);
- }
- //! GETTERS
- bool IsUsingUTC()
- {
- return m_UseUTC;
- }
- int GetYear()
- {
- return m_Year;
- }
- int GetMonth()
- {
- return m_Month;
- }
- string GetFullMonthString()
- {
- if (0 < m_Month && m_Month < 13)
- {
- return MONTHS_FULL_NAME[m_Month - 1];
- }
- return "undefined";
- }
- string GetShortMonthString()
- {
- if (0 < m_Month && m_Month < 13)
- {
- return MONTHS_SHORT_NAME[m_Month - 1];
- }
- return "undefined";
- }
- //! @note 0 = sunday
- int GetDayOfWeek()
- {
- int y = m_Year;
- int d = m_Day;
- if (m_Month < 3)
- d += y--;
- else
- d += y - 2;
- return (23 * m_Month / 9 + d + 4 + y / 4 - y / 100 + y / 400) % 7;
- }
- int GetDay()
- {
- return m_Day;
- }
- int GetHours()
- {
- return m_Hour;
- }
- int GetMinutes()
- {
- return m_Minute;
- }
- int GetSeconds()
- {
- return m_Second;
- }
- int GetTimestamp()
- {
- return Timestamp(m_Year, m_Month, m_Day, m_Hour, m_Minute, m_Second);
- }
- //! SETTERS
- void SetDate(int year, int month, int day, int hours, int minutes, int seconds)
- {
- SetYear(year);
- SetMonth(month);
- SetDay(day);
- SetHours(hours);
- SetMinutes(minutes);
- SetSeconds(seconds);
- }
- void SetDate(int month, int day, int hours, int minutes, int seconds)
- {
- SetMonth(month);
- SetDay(day);
- SetHours(hours);
- SetMinutes(minutes);
- SetSeconds(seconds);
- }
- void SetDate(int day, int hours, int minutes, int seconds)
- {
- SetDay(day);
- SetHours(hours);
- SetMinutes(minutes);
- SetSeconds(seconds);
- }
- void SetDate(int hours, int minutes, int seconds)
- {
- SetHours(hours);
- SetMinutes(minutes);
- SetSeconds(seconds);
- }
- void SetDate(int minutes, int seconds)
- {
- SetMinutes(minutes);
- SetSeconds(seconds);
- }
- void SetYear(int year)
- {
- m_Year = year;
- }
- void SetMonth(int month)
- {
- if (0 < month && month < 13)
- {
- m_Month = month;
- if (m_Day > DAYS_IN_MONTH[m_Month - 1])
- {
- m_Day = DAYS_IN_MONTH[m_Month - 1];
- }
- }
- else
- {
- CF_Log.Error("Invalid SetMonth: " + month + ". Expected a value between 1 and 12!");
- }
- }
- void SetDay(int day)
- {
- int monthDays = DAYS_IN_MONTH[m_Month - 1] + 1;
- if (IsLeapYear(m_Year) && m_Month == 2)
- {
- monthDays++;
- }
- if (0 < day && day < monthDays)
- {
- m_Day = day;
- }
- else
- {
- CF_Log.Error("Invalid SetDay: " + day + ". Expected a value between 1 and " + DAYS_IN_MONTH[m_Month - 1] + "!");
- }
- }
- void SetHours(int hours)
- {
- if (-1 < hours && hours < 24)
- {
- m_Hour = hours;
- }
- else
- {
- CF_Log.Error("Invalid SetHours: " + hours + ". Expected a value between 0 and 23!");
- }
- }
- void SetMinutes(int minutes)
- {
- if (-1 < minutes && minutes < 60)
- {
- m_Minute = minutes;
- }
- else
- {
- CF_Log.Error("Invalid SetMinutes: " + minutes + ". Expected a value between 0 and 59!");
- }
- }
- void SetSeconds(int seconds)
- {
- if (-1 < seconds && seconds < 60)
- {
- m_Second = seconds;
- }
- else
- {
- CF_Log.Error("Invalid SetSeconds: " + seconds + ". Expected a value between 0 and 59!");
- }
- }
- };
- /**@class CF_Localiser
- * @brief This class handle string formatting over network
- **/
- class CF_Localiser
- {
- protected int m_Count;
- protected string m_Strings[10];
- protected bool m_Translates[10];
- void CF_Localiser(string text = "", string param1 = "", string param2 = "", string param3 = "", string param4 = "", string param5 = "", string param6 = "", string param7 = "", string param8 = "", string param9 = "")
- {
- Set(-1, text);
- Set(0, param1);
- Set(1, param2);
- Set(2, param3);
- Set(3, param4);
- Set(4, param5);
- Set(5, param6);
- Set(6, param7);
- Set(7, param8);
- Set(8, param9);
- }
- static void Write(ParamsWriteContext ctx, CF_Localiser localiser)
- {
- ctx.Write(localiser.m_Count);
- for (int i = 0; i < localiser.m_Count; i++)
- {
- ctx.Write(localiser.m_Strings[i]);
- ctx.Write(localiser.m_Translates[i]);
- }
- }
- static bool Read(ParamsReadContext ctx, inout CF_Localiser localiser)
- {
- if (!localiser) localiser = new CF_Localiser();
- if (!ctx.Read(localiser.m_Count)) return false;
- for (int i = 0; i < localiser.m_Count; i++)
- {
- string str;
- bool translates;
- if (!ctx.Read(str) || !ctx.Read(translates)) return false;
- localiser.m_Strings[i] = str;
- localiser.m_Translates[i] = translates;
- }
- return true;
- }
- void SetTranslates(bool translates)
- {
- m_Translates[0] = translates;
- }
- string Format()
- {
- return GetDebugName();
- }
- override string GetDebugName()
- {
- string text = GetTranslated(-1);
- string p1 = GetTranslated(0);
- string p2 = GetTranslated(1);
- string p3 = GetTranslated(2);
- string p4 = GetTranslated(3);
- string p5 = GetTranslated(4);
- string p6 = GetTranslated(5);
- string p7 = GetTranslated(6);
- string p8 = GetTranslated(7);
- string p9 = GetTranslated(8);
- return string.Format(text, p1, p2, p3, p4, p5, p6, p7, p8, p9);
- }
- string GetText()
- {
- return Get(-1);
- }
- CF_Localiser Add(bool value)
- {
- return Set(m_Count - 1, value.ToString(), false);
- }
- CF_Localiser Add(int value)
- {
- return Set(m_Count - 1, value.ToString(), false);
- }
- CF_Localiser Add(float value)
- {
- return Set(m_Count - 1, value.ToString(), false);
- }
- CF_Localiser Add(vector value)
- {
- return Set(m_Count - 1, value.ToString(false), false);
- }
- CF_Localiser Add(Class value)
- {
- //TODO: use CF_TypeConverter here instead afer the PR is merged.
- string toStr = "";
- if (value) toStr = value.GetDebugName();
- return Set(m_Count - 1, toStr, false);
- }
- CF_Localiser Add(string value, bool translates = true)
- {
- return Set(m_Count - 1, value, translates);
- }
- CF_Localiser Set(int index, bool value)
- {
- return Set(index, value.ToString(), false);
- }
- CF_Localiser Set(int index, int value)
- {
- return Set(index, value.ToString(), false);
- }
- CF_Localiser Set(int index, float value)
- {
- return Set(index, value.ToString(), false);
- }
- CF_Localiser Set(int index, vector value)
- {
- return Set(index, value.ToString(false), false);
- }
- CF_Localiser Set(int index, Class value)
- {
- string toStr = "";
- if (value) toStr = value.GetDebugName();
- return Set(index, toStr, false);
- }
- CF_Localiser Set(int index, string value)
- {
- return Set(index, value, true);
- }
- CF_Localiser Set(int index, string value, bool translates)
- {
- int realIndex = index + 1;
- if (realIndex < 0 || realIndex > 9)
- return this;
- if (realIndex >= m_Count)
- {
- if (value == "" && realIndex != 0)
- return this;
- m_Count = realIndex + 1;
- }
- m_Strings[realIndex] = value;
- m_Translates[realIndex] = translates;
- return this;
- }
- string Get(int index)
- {
- int realIndex = index + 1;
- if (realIndex < 0 || realIndex >= m_Count)
- return "";
- return m_Strings[realIndex];
- }
- string GetTranslated(int index)
- {
- int realIndex = index + 1;
- if (realIndex < 0 || realIndex >= m_Count)
- return "";
- string value = m_Strings[realIndex];
- if (m_Translates[realIndex])
- {
- value = Widget.TranslateString("#" + value);
- if (value == "" || value[0] == " ")
- return m_Strings[realIndex];
- }
- return value;
- }
- /* Backwards compatbility - to be removed after CF 1.4 */
- CF_Localiser SetParam1(string arg)
- {
- return Set(1, arg);
- }
- CF_Localiser SetParam2(string arg)
- {
- return Set(2, arg);
- }
- CF_Localiser SetParam3(string arg)
- {
- return Set(3, arg);
- }
- CF_Localiser SetParam4(string arg)
- {
- return Set(4, arg);
- }
- CF_Localiser SetParam5(string arg)
- {
- return Set(5, arg);
- }
- CF_Localiser SetParam6(string arg)
- {
- return Set(6, arg);
- }
- CF_Localiser SetParam7(string arg)
- {
- return Set(7, arg);
- }
- CF_Localiser SetParam8(string arg)
- {
- return Set(8, arg);
- }
- CF_Localiser SetParam9(string arg)
- {
- return Set(9, arg);
- }
- };
- class StringLocaliser : CF_Localiser
- {
- };
- class CF_XML
- {
- static void _Cleanup()
- {
- }
- static CF_XML_Reader Open(string path)
- {
- CF_XML_Reader reader = new CF_XML_Reader();
- FileHandle fileHandle = OpenFile(path, FileMode.READ);
- string lineContent;
- while (FGets(fileHandle, lineContent) >= 0)
- reader.AddLine(lineContent);
- CloseFile(fileHandle);
- return reader;
- }
- static bool ReadDocument(string file, out CF_XML_Document document)
- {
- if (!document)
- document = new CF_XML_Document();
- return document.Read(Open(file));
- }
- static void Read(string file, notnull CF_XML_Callback callback)
- {
- Process(Open(file), callback);
- }
- static void ReadAsync(string file, notnull CF_XML_Callback callback)
- {
- thread Process(Open(file), callback);
- }
- static void Process(CF_XML_Reader reader, CF_XML_Callback callback)
- {
- CF_XML_Document document = new CF_XML_Document();
- callback.OnStart(document);
- bool success = false;
- if (document && reader)
- {
- success = document.Read(reader);
- }
- if (success)
- {
- callback.OnSuccess(document);
- }
- else
- {
- callback.OnFailure(document);
- }
- }
- };
- static CF_XML GetXMLApi()
- {
- return CF.XML;
- }typedef CF_XML_Attribute XMLAttribute;
- class CF_XML_Attribute : Managed
- {
- private string _name;
- private string _value;
- private CF_XML_Tag _parentTag;
- void CF_XML_Attribute(CF_XML_Tag parent, string name)
- {
- _parentTag = parent;
- _name = name;
- _value = "";
- }
- CF_XML_Attribute Copy(CF_XML_Tag parent = NULL)
- {
- CF_XML_Attribute element = new CF_XML_Attribute(parent, _name);
- element._value = _value;
- return element;
- }
- string GetName()
- {
- return _name;
- }
- void SetValue(string value)
- {
- _value = value;
- }
- void SetValue(bool value)
- {
- if (value)
- {
- _value = "true";
- }
- else
- {
- _value = "false";
- }
- }
- void SetValue(int value)
- {
- _value = "" + value;
- }
- void SetValue(float value)
- {
- _value = "" + value;
- }
- void SetValue(vector value)
- {
- _value = "" + value[0] + " " + value[1] + " " + value[2];
- }
- string GetValue()
- {
- return _value;
- }
- string ValueAsString()
- {
- return _value;
- }
- bool ValueAsBool()
- {
- if (_value == "true")
- return true;
- return false;
- }
- int ValueAsInt()
- {
- return _value.ToInt();
- }
- float ValueAsFloat()
- {
- return _value.ToFloat();
- }
- vector ValueAsVector()
- {
- array<string> tokens = new array<string>;
- _value.Split(" ", tokens);
- return Vector(tokens[0].ToFloat(), tokens[1].ToFloat(), tokens[2].ToFloat());
- }
- CF_XML_Tag GetParent()
- {
- return _parentTag;
- }
- void Debug(int level = 0)
- {
- string indent = CF_Indent(level);
- CF_Log.Info(indent + " name=" + _name + " value=" + _value);
- }
- void OnWrite(FileHandle handle, int depth)
- {
- FPrint(handle, _name);
- FPrint(handle, "=\"");
- FPrint(handle, _value);
- FPrint(handle, "\" ");
- }
- };typedef CF_XML_Callback XMLCallback;
- class CF_XML_Callback : Managed
- {
- void OnStart(CF_XML_Document document);
- void OnSuccess(CF_XML_Document document);
- void OnFailure(CF_XML_Document document);
- };typedef CF_XML_Document XMLDocument;
- class CF_XML_Document : CF_XML_Element
- {
- private CF_XML_Tag _currentTag;
- private ref CF_XML_Reader _reader;
- private autoptr map<string, string> _entities = new map<string, string>();
- void CF_XML_Document(CF_XML_Tag parent = NULL)
- {
- _entities.Insert(""", "\"");
- _entities.Insert("&", "&");
- _entities.Insert("'", "\'");
- _entities.Insert("<", "<");
- _entities.Insert(">", ">");
- }
- override CF_XML_Tag CreateTag(string name)
- {
- if (_currentTag)
- {
- _currentTag = _currentTag.CreateTag(name);
- }
- else
- {
- _currentTag = super.CreateTag(name);
- }
- return _currentTag;
- }
- CF_XML_Document CopyDocument()
- {
- CF_XML_Document document = new CF_XML_Document(NULL);
- for (int i = 0; i < _tags.Count(); ++i)
- {
- document._tags.Insert(_tags[i].Copy(this));
- }
- return document;
- }
- private bool ReadAttribute()
- {
- if (!_currentTag)
- {
- _reader.Err("Attempting to read attribute when not in tag!");
- return false;
- }
- bool isQuoted;
- string name = _reader.GetWord();
- string eq = _reader.GetCharacter();
- string value = _reader.GetQuotedWord(isQuoted);
- if (eq != "=")
- {
- _reader.Err("Expected '=' for attribute, got: " + eq);
- return false;
- }
- CF_XML_Attribute attrib = _currentTag.CreateAttribute(name);
- attrib.SetValue(value);
- return true;
- }
- private bool PopTag()
- {
- if (!_currentTag)
- return true;
- if (_currentTag.GetParent())
- _currentTag = _currentTag.GetParent().GetParent();
- else
- _currentTag = NULL;
- return true;
- }
- private bool ReadTag()
- {
- string c = _reader.SkipWhitespace();
- string tagName = "";
- if (c == "<")
- {
- c = _reader.GetCharacter();
- if (c == "/")
- {
- tagName = _reader.GetWord();
- if (_currentTag == NULL)
- {
- _reader.Err("Unexpected closing tag: " + tagName);
- }
- c = _reader.GetCharacter();
- if (c != ">")
- {
- _reader.Err("Expected '>' for closing tag, got: " + c);
- }
- PopTag();
- return true;
- }
- if (c != "?")
- _reader.BackChar();
- tagName = _reader.GetWord();
- CreateTag(tagName);
- c = _reader.SkipWhitespace();
- while (c != "/" && c != "?" && c != ">")
- {
- c = _reader.BackChar();
- if (!ReadAttribute())
- return false;
- c = _reader.SkipWhitespace();
- }
- if (c == "/" || c == "?")
- {
- c = _reader.GetCharacter();
- if (c != ">")
- {
- _reader.Err("Expected '>' for inline closing tag, got: " + c);
- }
- PopTag();
- }
- else if (c == ">")
- {
- c = _reader.SkipWhitespace();
- if (c == "<")
- {
- c = _reader.BackChar();
- return true;
- }
- string content = c;
- while (true)
- {
- bool wasNewLine = _reader.WasNewLine();
- if (wasNewLine) c = _reader.SkipWhitespace();
- else c = _reader.GetCharacter();
- if (c != "<")
- {
- if (wasNewLine) content += "\n";
- content += c;
- continue;
- }
- c = _reader.GetCharacter();
- if (c != "/")
- {
- _reader.Err("Expected '/' for inline closing tag, got: " + c);
- }
- tagName = _reader.GetWord();
- if (tagName != _currentTag.GetName())
- {
- _reader.Err("Unexpected closing tag: " + tagName);
- }
- break;
- }
- foreach (string ent_key, string ent_val : _entities)
- content.Replace(ent_key, ent_val);
- _currentTag.GetContent().SetContent(content);
- c = _reader.GetCharacter();
- if (c != ">")
- {
- _reader.Err("Expected '>' for closing tag, got: " + c);
- }
- PopTag();
- return true;
- }
- else
- {
- _reader.Err("Expected '>' for opening element within tag, got: " + c);
- }
- return true;
- }
- // could just be non-tagged content.
- return true;
- }
- bool Read(CF_XML_Reader reader)
- {
- _reader = reader;
- while (!_reader.EOF())
- {
- if (!ReadTag())
- {
- delete _reader;
- return false;
- }
- }
- delete _reader;
- return true;
- }
- void Save(string path)
- {
- ThreadWrite(path);
- //GetGame().GameScript.Call( this, "ThreadWrite", path );
- }
- private void ThreadWrite(string path)
- {
- FileHandle handle = OpenFile(path, FileMode.WRITE);
- if (handle != 0)
- {
- OnWrite(handle, 0);
- CloseFile(handle);
- }
- }
- };typedef CF_XML_Element XMLElement;
- class CF_XML_Element : Managed
- {
- protected autoptr array<autoptr CF_XML_Tag> _tags = new array<autoptr CF_XML_Tag>;
- protected CF_XML_Tag _parentTag;
- protected string _data;
- void CF_XML_Element(CF_XML_Tag parent = NULL)
- {
- #ifdef CF_TRACE_ENABLED
- auto trace = CF_Trace_1(this).Add(parent);
- #endif
- _parentTag = parent;
- }
- void ~CF_XML_Element()
- {
- #ifdef CF_TRACE_ENABLED
- auto trace = CF_Trace_0(this);
- #endif
- }
- CF_XML_Element Copy(CF_XML_Tag parent = NULL)
- {
- CF_XML_Element element = new CF_XML_Element(parent);
- for (int i = 0; i < _tags.Count(); ++i)
- {
- element._tags.Insert(_tags[i].Copy(element));
- }
- element._data = "" + _data;
- return element;
- }
- CF_XML_Tag CreateTag(string name)
- {
- CF_XML_Tag tag = new CF_XML_Tag(this, name);
- _tags.Insert(tag);
- return tag;
- }
- int Count()
- {
- return _tags.Count();
- }
- CF_XML_Tag Get(int index)
- {
- return _tags[index];
- }
- void Remove(CF_XML_Tag tag)
- {
- int index = _tags.Find(tag);
- if (index >= 0)
- _tags.Remove(index);
- }
- array<CF_XML_Tag> Get(string type)
- {
- array<CF_XML_Tag> tags = new array<CF_XML_Tag>;
- for (int i = 0; i < _tags.Count(); ++i)
- {
- if (_tags[i].GetName() == type)
- {
- tags.Insert(_tags[i]);
- }
- }
- return tags;
- }
- void SetContent(string data)
- {
- _data = data;
- }
- string GetContent()
- {
- return _data;
- }
- CF_XML_Tag GetParent()
- {
- return _parentTag;
- }
- void Debug(int level = 0)
- {
- string indent = CF_Indent(level);
- CF_Log.Info(indent + "Tags: count=" + _tags.Count());
- for (int i = 0; i < _tags.Count(); ++i)
- {
- _tags[i].Debug(level + 1);
- }
- }
- void OnWrite(FileHandle handle, int depth)
- {
- string indent = CF_XML_Indent(depth);
- FPrint(handle, _data);
- for (int i = 0; i < _tags.Count(); ++i)
- {
- _tags[i].OnWrite(handle, depth);
- }
- }
- };typedef CF_XML_Reader XMLReader;
- class CF_XML_Reader : Managed
- {
- private int _arrIdx = 0;
- private int _bufIdx = -1;
- private bool _wasNewLine;
- private ref array<string> _lines = new array<string>;
- void CF_XML_Reader()
- {
- #ifdef CF_TRACE_ENABLED
- auto trace = CF_Trace_0(this);
- #endif
- }
- void ~CF_XML_Reader()
- {
- #ifdef CF_TRACE_ENABLED
- auto trace = CF_Trace_0(this);
- #endif
- }
- void GetPosition(out int arrIdx, out int bufIdx)
- {
- arrIdx = _arrIdx;
- bufIdx = _bufIdx;
- }
- void SetPosition(out int arrIdx, out int bufIdx)
- {
- _arrIdx = arrIdx;
- _bufIdx = bufIdx;
- }
- void Err(string message)
- {
- CF_Log.Error("[" + (_arrIdx + 1 ) + ":" + _bufIdx + "] " + message);
- }
- void AddLine(string line)
- {
- if (line.Length() != 0)
- _lines.Insert(line);
- }
- bool WasNewLine()
- {
- return _wasNewLine;
- }
- string BackChar()
- {
- _wasNewLine = false;
- _bufIdx--;
- if (_bufIdx < 0)
- {
- _arrIdx--;
- if (_arrIdx < 0)
- {
- return "";
- }
- _bufIdx = _lines[_arrIdx].Length() - 1;
- }
- if (_bufIdx == 0) _wasNewLine = true;
- return _lines[_arrIdx].SubstringUtf8(_bufIdx, 1);
- }
- private string ReadChar()
- {
- _wasNewLine = false;
- _bufIdx++;
- if (_bufIdx >= _lines[_arrIdx].Length())
- {
- _bufIdx = 0;
- _arrIdx++;
- _wasNewLine = true;
- if (_arrIdx >= _lines.Count())
- {
- return "";
- }
- }
- return _lines[_arrIdx].SubstringUtf8(_bufIdx, 1);
- }
- bool EOF()
- {
- return _arrIdx >= _lines.Count() || (_arrIdx == _lines.Count() - 1 && _bufIdx >= _lines[_arrIdx].Length());
- }
- private void SkipComment()
- {
- string c = ReadChar();
- while (true)
- {
- if (EOF())
- {
- CF_Log.Error("Unexpected end of file while parsing XML comment!");
- break;
- }
- if (c != ">")
- {
- c = ReadChar();
- continue;
- }
- BackChar();
- BackChar();
- BackChar();
- string check = ReadChar() + ReadChar() + ReadChar();
- if (check == "-->")
- {
- return;
- }
- else
- {
- c = ReadChar();
- }
- }
- }
- string GetCharacter()
- {
- string c = ReadChar();
- while (true)
- {
- if (c == "<")
- {
- c = ReadChar();
- if (c == "!")
- {
- c = ReadChar();
- if (c == "-")
- {
- c = ReadChar();
- if (c == "-")
- {
- SkipComment();
- }
- else
- {
- BackChar();
- BackChar();
- BackChar();
- return "<";
- }
- }
- else
- {
- BackChar();
- BackChar();
- return "<";
- }
- }
- else
- {
- BackChar();
- return "<";
- }
- }
- else
- {
- return c;
- }
- c = ReadChar();
- }
- return c;
- }
- bool IsWhitespace(string c)
- {
- if (c == " ")
- return true;
- if (c == "\t")
- return true;
- if (c == "\n")
- return true;
- if (c == "\r")
- return true;
- //if ( c == "" )
- // Error( "Unexpected end of string" );
- return false;
- }
- bool IsLetterOrDigit(string c)
- {
- return IsLetterOrDigit(c, false);
- }
- bool IsLetterOrDigit(string c, bool isQuoted)
- {
- int i = c.ToAscii();
- if (i >= 255 || i < 0) //! To my dear @DaOne, please don't use UTF-8 characters :)
- return true;
- if (i < 32)
- return false;
- if (isQuoted && i >= 32 && i <= 126)
- return true;
- if (i >= 48 && i <= 57)
- return true;
- if (i == 95)
- return true;
- if (i > 90)
- i -= 32;
- if (i >= 65 && i <= 90)
- return true;
- return false;
- }
- string SkipWhitespace()
- {
- string c = GetCharacter();
- while (IsWhitespace(c) && !EOF())
- c = GetCharacter();
- return c;
- }
- string GetWord()
- {
- string word = "";
- string c = SkipWhitespace();
- while (IsLetterOrDigit(c) && !EOF())
- {
- word = word + c;
- c = GetCharacter();
- }
- BackChar();
- return word;
- }
- string GetQuotedWord(out bool isQuoted)
- {
- string word = "";
- string c = SkipWhitespace();
- if (c == "\"")
- {
- c = "";
- isQuoted = true;
- }
- while ((IsLetterOrDigit(c, isQuoted) || c == "") && !EOF())
- {
- word = word + c;
- c = GetCharacter();
- if (isQuoted && c == "\"")
- {
- break;
- }
- }
- if (!isQuoted)
- BackChar();
- return word;
- }
- };
- typedef CF_XML_Tag XMLTag;
- class CF_XML_Tag : Managed
- {
- private string _name;
- private autoptr map<string, ref CF_XML_Attribute> _attributes;
- private ref CF_XML_Element _element;
- private CF_XML_Element _parentElement;
- void CF_XML_Tag(CF_XML_Element parent, string name, bool isCopy = false)
- {
- #ifdef CF_TRACE_ENABLED
- auto trace = CF_Trace_3(this).Add(parent).Add(name).Add(isCopy);
- #endif
- _attributes = new map<string, ref CF_XML_Attribute>;
- _parentElement = parent;
- _name = name;
- if (!isCopy)
- _element = new CF_XML_Element(this);
- }
- void ~CF_XML_Tag()
- {
- #ifdef CF_TRACE_ENABLED
- auto trace = CF_Trace_0(this);
- #endif
- for (int i = 0; i < _attributes.Count(); ++i)
- {
- delete _attributes.GetElement(i);
- }
- delete _attributes;
- delete _element;
- }
- CF_XML_Tag Copy(CF_XML_Element parent = NULL)
- {
- CF_XML_Tag tag = new CF_XML_Tag(parent, _name);
- for (int i = 0; i < _attributes.Count(); ++i)
- {
- CF_XML_Attribute attrib = _attributes.GetElement(i).Copy(tag);
- tag._attributes.Insert(attrib.GetName(), attrib);
- }
- tag._element = _element.Copy(tag);
- return tag;
- }
- string GetName()
- {
- return _name;
- }
- CF_XML_Tag CreateTag(string name)
- {
- return _element.CreateTag(name);
- }
- array<CF_XML_Tag> GetTag(string type)
- {
- return _element.Get(type);
- }
- CF_XML_Attribute CreateAttribute(string name)
- {
- CF_XML_Attribute attrb = new CF_XML_Attribute(this, name);
- _attributes.Insert(name, attrb);
- return attrb;
- }
- CF_XML_Attribute GetAttribute(string name)
- {
- return _attributes.Get(name);
- }
- CF_XML_Element GetContent()
- {
- return _element;
- }
- CF_XML_Element GetParent()
- {
- return _parentElement;
- }
- void Debug(int level = 0)
- {
- string indent = CF_Indent(level);
- CF_Log.Info(indent + "Tag:");
- CF_Log.Info(indent + " name=" + _name);
- CF_Log.Info(indent + "Attributes: count=" + _attributes.Count());
- for (int i = 0; i < _attributes.Count(); ++i)
- {
- _attributes.GetElement(i).Debug(level);
- }
- CF_Log.Info(indent + "Element:");
- _element.Debug(level + 1);
- }
- void OnWrite(FileHandle handle, int depth)
- {
- string indent = CF_XML_Indent(depth);
- FPrint(handle, indent);
- FPrint(handle, "<");
- FPrint(handle, _name);
- if (_attributes.Count() > 0)
- {
- FPrint(handle, " ");
- for (int i = 0; i < _attributes.Count(); ++i)
- {
- _attributes.GetElement(i).OnWrite(handle, depth);
- }
- }
- if (_element.Count() > 0)
- {
- FPrint(handle, ">\n");
- _element.OnWrite(handle, depth + 1);
- FPrint(handle, indent);
- FPrint(handle, "<");
- FPrint(handle, _name);
- FPrint(handle, " ");
- }
- else if (_attributes.Count() == 0)
- {
- FPrint(handle, " ");
- }
- FPrint(handle, "/>\n");
- }
- };/*
- modded class ModItemRegisterCallbacks
- {
- ref JMAnimRegister m_AnimRegister;
- void ModItemRegisterCallbacks()
- {
- m_AnimRegister = new JMAnimRegister();
- }
- void ~ModItemRegisterCallbacks()
- {
- delete m_AnimRegister;
- }
- override void RegisterEmptyHanded( DayZPlayerType pType, DayzPlayerItemBehaviorCfg pBehavior )
- {
- super.RegisterEmptyHanded( pType, pBehavior );
- m_AnimRegister.OnRegisterEmptyHanded( pType, pBehavior );
- m_AnimRegister.RegisterEmptyHanded( pType, pBehavior );
- }
- override void RegisterOneHanded( DayZPlayerType pType, DayzPlayerItemBehaviorCfg pBehavior )
- {
- super.RegisterOneHanded( pType, pBehavior );
- m_AnimRegister.OnRegisterOneHanded( pType, pBehavior );
- m_AnimRegister.RegisterOneHanded( pType, pBehavior );
- }
- override void RegisterTwoHanded( DayZPlayerType pType, DayzPlayerItemBehaviorCfg pBehavior )
- {
- super.RegisterTwoHanded( pType, pBehavior );
- m_AnimRegister.OnRegisterTwoHanded( pType, pBehavior );
- m_AnimRegister.RegisterTwoHanded( pType, pBehavior );
- }
- override void RegisterRestrained( DayZPlayerType pType, DayzPlayerItemBehaviorCfg pBehavior )
- {
- super.RegisterRestrained( pType, pBehavior );
- m_AnimRegister.OnRegisterRestrained( pType, pBehavior );
- m_AnimRegister.RegisterRestrained( pType, pBehavior );
- }
- override void RegisterSurrender( DayZPlayerType pType, DayzPlayerItemBehaviorCfg pBehavior )
- {
- super.RegisterSurrender( pType, pBehavior );
- m_AnimRegister.OnRegisterSurrender( pType, pBehavior );
- m_AnimRegister.RegisterSurrender( pType, pBehavior );
- }
- override void RegisterHeavy( DayZPlayerType pType, DayzPlayerItemBehaviorCfg pBehavior )
- {
- super.RegisterHeavy( pType, pBehavior );
- m_AnimRegister.OnRegisterHeavy( pType, pBehavior );
- m_AnimRegister.RegisterHeavy( pType, pBehavior );
- }
- override void RegisterPistol( DayZPlayerType pType, DayzPlayerItemBehaviorCfg pBehavior )
- {
- super.RegisterPistol( pType, pBehavior );
- m_AnimRegister.OnRegisterPistol( pType, pBehavior );
- m_AnimRegister.RegisterPistol( pType, pBehavior );
- }
- override void RegisterFireArms( DayZPlayerType pType, DayzPlayerItemBehaviorCfg pBehavior )
- {
- super.RegisterFireArms( pType, pBehavior );
- m_AnimRegister.OnRegisterFireArms( pType, pBehavior );
- m_AnimRegister.RegisterFireArms( pType, pBehavior );
- }
- override void RegisterArcheryItem( DayZPlayerType pType, DayzPlayerItemBehaviorCfg pBehavior )
- {
- super.RegisterArcheryItem( pType, pBehavior );
- m_AnimRegister.OnRegisterArcheryItem( pType, pBehavior );
- m_AnimRegister.RegisterArcheryItem( pType, pBehavior );
- }
- override void RegisterLauncher( DayZPlayerType pType, DayzPlayerItemBehaviorCfg pBehavior )
- {
- super.RegisterLauncher( pType, pBehavior );
- m_AnimRegister.OnRegisterLauncher( pType, pBehavior );
- m_AnimRegister.RegisterLauncher( pType, pBehavior );
- }
- override void RegisterCustom( DayZPlayerType pType )
- {
- super.RegisterCustom( pType );
- m_AnimRegister.OnRegisterCustom( pType, pBehavior );
- m_AnimRegister.RegisterCustom( pType, pBehavior );
- }
- override void CustomBoneRemapping( DayZPlayerType pType )
- {
- super.CustomBoneRemapping( pType );
- m_AnimRegister.OnBoneRemapping( pType );
- m_AnimRegister.BoneRemapping( pType );
- }
- };
- */
- // 107 compatibility
- class JMAnimRegister
- {
- static JMAnimRegister Register( DayZPlayerType pType )
- {
- JMAnimRegister animReg = new JMAnimRegister;
- DayzPlayerItemBehaviorCfg behaviour;
- behaviour = new DayzPlayerItemBehaviorCfg;
- behaviour.SetEmptyHanded();
- animReg.OnRegisterEmptyHanded( pType, behaviour );
- animReg.RegisterEmptyHanded( pType, behaviour );
- behaviour = new DayzPlayerItemBehaviorCfg;
- behaviour.SetTwoHanded();
- animReg.OnRegisterTwoHanded( pType, behaviour );
- animReg.RegisterTwoHanded( pType, behaviour );
- behaviour = new DayzPlayerItemBehaviorCfg;
- behaviour.SetToolsOneHanded();
- animReg.OnRegisterOneHanded( pType, behaviour );
- animReg.RegisterOneHanded( pType, behaviour );
- behaviour = new DayzPlayerItemBehaviorCfg;
- behaviour.SetRestrained();
- animReg.OnRegisterRestrained( pType, behaviour );
- animReg.RegisterRestrained( pType, behaviour );
- behaviour = new DayzPlayerItemBehaviorCfg;
- behaviour.SetSurrender();
- animReg.OnRegisterSurrender( pType, behaviour );
- animReg.RegisterSurrender( pType, behaviour );
- behaviour = new DayzPlayerItemBehaviorCfg;
- behaviour.SetHeavyItems();
- animReg.OnRegisterHeavy( pType, behaviour );
- animReg.RegisterHeavy( pType, behaviour );
- behaviour = new DayzPlayerItemBehaviorCfg;
- behaviour.SetPistols();
- animReg.OnRegisterPistol( pType, behaviour );
- animReg.RegisterPistol( pType, behaviour );
- behaviour = new DayzPlayerItemBehaviorCfg;
- behaviour.SetFirearms();
- animReg.OnRegisterFireArms( pType, behaviour );
- animReg.RegisterFireArms( pType, behaviour );
- behaviour = new DayzPlayerItemBehaviorCfg;
- animReg.OnRegisterArcheryItem( pType, behaviour );
- animReg.RegisterArcheryItem( pType, behaviour );
- behaviour = new DayzPlayerItemBehaviorCfg;
- animReg.OnRegisterLauncher( pType, behaviour );
- animReg.RegisterLauncher( pType, behaviour );
- animReg.OnRegisterCustom( pType );
- animReg.RegisterCustom( pType );
- animReg.OnBoneRemapping( pType );
- animReg.BoneRemapping( pType );
- return animReg;
- }
- void RegisterEmptyHanded( DayZPlayerType pType, DayzPlayerItemBehaviorCfg pBehavior );
- void OnRegisterEmptyHanded( DayZPlayerType pType, DayzPlayerItemBehaviorCfg pBehavior );
- void RegisterOneHanded( DayZPlayerType pType, DayzPlayerItemBehaviorCfg pBehavior );
- void OnRegisterOneHanded( DayZPlayerType pType, DayzPlayerItemBehaviorCfg pBehavior );
- void RegisterTwoHanded( DayZPlayerType pType, DayzPlayerItemBehaviorCfg pBehavior );
- void OnRegisterTwoHanded( DayZPlayerType pType, DayzPlayerItemBehaviorCfg pBehavior );
- void RegisterRestrained( DayZPlayerType pType, DayzPlayerItemBehaviorCfg pBehavior );
- void OnRegisterRestrained( DayZPlayerType pType, DayzPlayerItemBehaviorCfg pBehavior );
- void RegisterSurrender( DayZPlayerType pType, DayzPlayerItemBehaviorCfg pBehavior );
- void OnRegisterSurrender( DayZPlayerType pType, DayzPlayerItemBehaviorCfg pBehavior );
- void RegisterHeavy( DayZPlayerType pType, DayzPlayerItemBehaviorCfg pBehavior );
- void OnRegisterHeavy( DayZPlayerType pType, DayzPlayerItemBehaviorCfg pBehavior );
- void RegisterPistol( DayZPlayerType pType, DayzPlayerItemBehaviorCfg pBehavior );
- void OnRegisterPistol( DayZPlayerType pType, DayzPlayerItemBehaviorCfg pBehavior );
- void RegisterFireArms( DayZPlayerType pType, DayzPlayerItemBehaviorCfg pBehavior );
- void OnRegisterFireArms( DayZPlayerType pType, DayzPlayerItemBehaviorCfg pBehavior );
- void RegisterArcheryItem( DayZPlayerType pType, DayzPlayerItemBehaviorCfg pBehavior );
- void OnRegisterArcheryItem( DayZPlayerType pType, DayzPlayerItemBehaviorCfg pBehavior );
- void RegisterLauncher( DayZPlayerType pType, DayzPlayerItemBehaviorCfg pBehavior );
- void OnRegisterLauncher( DayZPlayerType pType, DayzPlayerItemBehaviorCfg pBehavior );
- void RegisterCustom( DayZPlayerType pType );
- void OnRegisterCustom( DayZPlayerType pType );
- void BoneRemapping( DayZPlayerType pType );
- void OnBoneRemapping( DayZPlayerType pType );
- };modded class AdvancedCommunication
- {
- // autoptr CF_ModStorageBase m_CF_ModStorage = new CF_ModStorageObject<AdvancedCommunication>(this);
- //
- // override void OnStoreSave(ParamsWriteContext ctx)
- // {
- // super.OnStoreSave(ctx);
- //
- // m_CF_ModStorage.OnStoreSave(ctx);
- // }
- //
- // override bool OnStoreLoad(ParamsReadContext ctx, int version)
- // {
- // if (!super.OnStoreLoad(ctx, version))
- // {
- // return false;
- // }
- //
- // return m_CF_ModStorage.OnStoreLoad(ctx, version);
- // }
- /**
- * @brief Refer to CF/ModStorage implementation of ItemBase::CF_OnStoreSave
- */
- void CF_OnStoreSave(CF_ModStorageMap storage)
- {
- }
- /**
- * @brief Refer to CF/ModStorage implementation of ItemBase::CF_OnStoreLoad
- */
- bool CF_OnStoreLoad(CF_ModStorageMap storage)
- {
- return true;
- }
- };
- modded class AnimalBase
- {
- // autoptr CF_ModStorageBase m_CF_ModStorage = new CF_ModStorageObject<AnimalBase>(this);
- //
- // override void OnStoreSave(ParamsWriteContext ctx)
- // {
- // super.OnStoreSave(ctx);
- //
- // m_CF_ModStorage.OnStoreSave(ctx);
- // }
- //
- // override bool OnStoreLoad(ParamsReadContext ctx, int version)
- // {
- // if (!super.OnStoreLoad(ctx, version))
- // {
- // return false;
- // }
- //
- // return m_CF_ModStorage.OnStoreLoad(ctx, version);
- // }
- /**
- * @brief Refer to CF/ModStorage implementation of ItemBase::CF_OnStoreSave
- */
- void CF_OnStoreSave(CF_ModStorageMap storage)
- {
- }
- /**
- * @brief Refer to CF/ModStorage implementation of ItemBase::CF_OnStoreLoad
- */
- bool CF_OnStoreLoad(CF_ModStorageMap storage)
- {
- return true;
- }
- };
- modded class BuildingBase
- {
- // autoptr CF_ModStorageBase m_CF_ModStorage = new CF_ModStorageObject<BuildingBase>(this);
- //
- // override void OnStoreSave(ParamsWriteContext ctx)
- // {
- // super.OnStoreSave(ctx);
- //
- // m_CF_ModStorage.OnStoreSave(ctx);
- // }
- //
- // override bool OnStoreLoad(ParamsReadContext ctx, int version)
- // {
- // if (!super.OnStoreLoad(ctx, version))
- // {
- // return false;
- // }
- //
- // return m_CF_ModStorage.OnStoreLoad(ctx, version);
- // }
- /**
- * @brief Refer to CF/ModStorage implementation of ItemBase::CF_OnStoreSave
- */
- void CF_OnStoreSave(CF_ModStorageMap storage)
- {
- }
- /**
- * @brief Refer to CF/ModStorage implementation of ItemBase::CF_OnStoreLoad
- */
- bool CF_OnStoreLoad(CF_ModStorageMap storage)
- {
- return true;
- }
- };
- modded class CarScript
- {
- // autoptr CF_ModStorageBase m_CF_ModStorage = new CF_ModStorageObject<CarScript>(this);
- //
- // override void OnStoreSave(ParamsWriteContext ctx)
- // {
- // super.OnStoreSave(ctx);
- //
- // m_CF_ModStorage.OnStoreSave(ctx);
- // }
- //
- // override bool OnStoreLoad(ParamsReadContext ctx, int version)
- // {
- // if (!super.OnStoreLoad(ctx, version))
- // {
- // return false;
- // }
- //
- // return m_CF_ModStorage.OnStoreLoad(ctx, version);
- // }
- /**
- * @brief Refer to CF/ModStorage implementation of ItemBase::CF_OnStoreSave
- */
- void CF_OnStoreSave(CF_ModStorageMap storage)
- {
- }
- /**
- * @brief Refer to CF/ModStorage implementation of ItemBase::CF_OnStoreLoad
- */
- bool CF_OnStoreLoad(CF_ModStorageMap storage)
- {
- return true;
- }
- };
- modded class DayZPlayerImplement
- {
- // autoptr CF_ModStorageBase m_CF_ModStorage = new CF_ModStorageObject<DayZPlayerImplement>(this);
- //
- // override void OnStoreSave(ParamsWriteContext ctx)
- // {
- // super.OnStoreSave(ctx);
- //
- // m_CF_ModStorage.OnStoreSave(ctx);
- // }
- //
- // override bool OnStoreLoad(ParamsReadContext ctx, int version)
- // {
- // if (!super.OnStoreLoad(ctx, version))
- // {
- // return false;
- // }
- //
- // return m_CF_ModStorage.OnStoreLoad(ctx, version);
- // }
- /**
- * @brief Refer to CF/ModStorage implementation of ItemBase::CF_OnStoreSave
- */
- void CF_OnStoreSave(CF_ModStorageMap storage)
- {
- }
- /**
- * @brief Refer to CF/ModStorage implementation of ItemBase::CF_OnStoreLoad
- */
- bool CF_OnStoreLoad(CF_ModStorageMap storage)
- {
- return true;
- }
- };
- modded class HelicopterScript
- {
- // autoptr CF_ModStorageBase m_CF_ModStorage = new CF_ModStorageObject<HelicopterScript>(this);
- //
- // override void OnStoreSave(ParamsWriteContext ctx)
- // {
- // super.OnStoreSave(ctx);
- //
- // m_CF_ModStorage.OnStoreSave(ctx);
- // }
- //
- // override bool OnStoreLoad(ParamsReadContext ctx, int version)
- // {
- // if (!super.OnStoreLoad(ctx, version))
- // {
- // return false;
- // }
- //
- // return m_CF_ModStorage.OnStoreLoad(ctx, version);
- // }
- /**
- * @brief Refer to CF/ModStorage implementation of ItemBase::CF_OnStoreSave
- */
- void CF_OnStoreSave(CF_ModStorageMap storage)
- {
- }
- /**
- * @brief Refer to CF/ModStorage implementation of ItemBase::CF_OnStoreLoad
- */
- bool CF_OnStoreLoad(CF_ModStorageMap storage)
- {
- return true;
- }
- };
- modded class ItemBase
- {
- // autoptr CF_ModStorageBase m_CF_ModStorage = new CF_ModStorageObject<ItemBase>(this);
- //
- // override void OnStoreSave(ParamsWriteContext ctx)
- // {
- // super.OnStoreSave(ctx);
- //
- // m_CF_ModStorage.OnStoreSave(ctx);
- // }
- //
- // override bool OnStoreLoad(ParamsReadContext ctx, int version)
- // {
- // if (!super.OnStoreLoad(ctx, version))
- // {
- // return false;
- // }
- //
- // return m_CF_ModStorage.OnStoreLoad(ctx, version);
- // }
- /**
- * @param storage Map of 'CF_ModStorage' classes
- *
- * @code
- * modded class KitBase // extends from ItemBase
- * {
- * override void CF_OnStoreSave(CF_ModStorageMap storage)
- * {
- * //! Always call super at the start.
- * super.CF_OnStoreSave(storage);
- *
- * auto ctx = storage["JM_CommunityFramework"];
- *
- * ctx.Write(GetOrientation());
- * ctx.Write(6);
- * ctx.Write("ThisVariableIsAddedWithVersion2");
- * }
- * }
- */
- void CF_OnStoreSave(CF_ModStorageMap storage)
- {
- }
- /**
- * @param storage Map of 'CF_ModStorage' classes
- *
- * @return True if loading was successful
- *
- * @code
- * modded class KitBase // extends from ItemBase
- * {
- * override bool CF_OnStoreLoad(CF_ModStorageMap storage)
- * {
- * if (!super.CF_OnStoreLoad(storage)) return false;
- *
- * auto ctx = storage["JM_CommunityFramework"];
- * if (!ctx) return true;
- *
- * vector orientation;
- * if (!ctx.Read(orientation)) return false;
- *
- * string intVar;
- * if (!ctx.Read(intVar)) return false;
- *
- * //! The version of the mod is set in config 'storageVersion' for 'CfgMods' class
- *
- * string strVar;
- * if (ctx.GetVersion() > 1)
- * {
- * if (!ctx.Read(strVar)) return false;
- * }
- * else
- * {
- * strVar = "Default Value";
- * }
- *
- * return true;
- * }
- * }
- * @endcode
- */
- bool CF_OnStoreLoad(CF_ModStorageMap storage)
- {
- return true;
- }
- };
- modded class DayZPlayerCameras
- {
- static override void RegisterCameras( DayZPlayerType pType )
- {
- JMAnimRegister.Register( pType );
- pType.ResetCameraCreators();
- //!
- //! this registers camera ids for camera script class implementation
- //! which camera is used at the time is specified by DayzPlayerImplement.CamraHandler which returns id
- //!
- pType.RegisterCameraCreator(DAYZCAMERA_1ST, DayZPlayerCamera1stPerson);
- pType.RegisterCameraCreator(DAYZCAMERA_3RD_ERC, DayZPlayerCamera3rdPersonErc);
- pType.RegisterCameraCreator(DAYZCAMERA_3RD_ERC_SPR, DayZPlayerCamera3rdPersonErcSpr);
- pType.RegisterCameraCreator(DAYZCAMERA_3RD_ERC_RAISED, DayZPlayerCamera3rdPersonErcRaised);
- pType.RegisterCameraCreator(DAYZCAMERA_3RD_CRO, DayZPlayerCamera3rdPersonCrouch);
- pType.RegisterCameraCreator(DAYZCAMERA_3RD_CRO_RAISED, DayZPlayerCamera3rdPersonCrouchRaised);
- pType.RegisterCameraCreator(DAYZCAMERA_3RD_PRO, DayZPlayerCamera3rdPersonProne);
- pType.RegisterCameraCreator(DAYZCAMERA_3RD_PRO_RAISED, DayZPlayerCamera3rdPersonProneRaised);
- pType.RegisterCameraCreator(DAYZCAMERA_IRONSIGHTS, DayZPlayerCameraIronsights);
- pType.RegisterCameraCreator(DAYZCAMERA_OPTICS, DayZPlayerCameraOptics);
- pType.RegisterCameraCreator(DAYZCAMERA_3RD_ERC_RAISED_MELEE, DayZPlayerCamera3rdPersonErcRaisedMelee);
- pType.RegisterCameraCreator(DAYZCAMERA_1ST_UNCONSCIOUS, DayZPlayerCamera1stPersonUnconscious);
- pType.RegisterCameraCreator(DAYZCAMERA_3RD_JUMP, DayZPlayerCamera3rdPersonJump);
- pType.RegisterCameraCreator(DAYZCAMERA_3RD_CLIMB, DayZPlayerCamera3rdPersonClimb);
- pType.RegisterCameraCreator(DAYZCAMERA_1ST_VEHICLE, DayZPlayerCamera1stPersonVehicle);
- pType.RegisterCameraCreator(DAYZCAMERA_3RD_VEHICLE, DayZPlayerCamera3rdPersonVehicle);
- //! Blend times when changing cameras
- //! 3rd person erected camera transition
- RegisterTransitionTime(DAYZCAMERA_3RD_ERC, DAYZCAMERA_3RD_CRO, 0.4, false);
- RegisterTransitionTime(DAYZCAMERA_3RD_ERC, DAYZCAMERA_3RD_PRO, 0.8, false);
- RegisterTransitionTime(DAYZCAMERA_3RD_ERC, DAYZCAMERA_3RD_PRO_RAISED, 0.8, false);
- RegisterTransitionTime(DAYZCAMERA_3RD_ERC, DAYZCAMERA_3RD_ERC_RAISED, 0.2, false);
- RegisterTransitionTime(DAYZCAMERA_3RD_ERC, DAYZCAMERA_3RD_ERC_RAISED_MELEE, 0.2, false);
- RegisterTransitionTime(DAYZCAMERA_3RD_ERC, DAYZCAMERA_3RD_ERC_SPR, 0.6, false);
- RegisterTransitionTime(DAYZCAMERA_3RD_ERC_RAISED, DAYZCAMERA_3RD_ERC_SPR, 0.7, false);
- RegisterTransitionTime(DAYZCAMERA_3RD_ERC_RAISED, DAYZCAMERA_3RD_PRO_RAISED, 0.8, false);
- RegisterTransitionTime(DAYZCAMERA_3RD_ERC_SPR, DAYZCAMERA_3RD_ERC, 0.3, false);
- RegisterTransitionTime(DAYZCAMERA_3RD_ERC_SPR, DAYZCAMERA_3RD_CRO, 0.3, false);
- RegisterTransitionTime(DAYZCAMERA_3RD_ERC_SPR, DAYZCAMERA_3RD_PRO, 0.5, false);
- RegisterTransitionTime(DAYZCAMERA_3RD_ERC_SPR, DAYZCAMERA_3RD_ERC_RAISED, 0.3, false);
- RegisterTransitionTime(DAYZCAMERA_3RD_ERC_SPR, DAYZCAMERA_3RD_JUMP, 0.1, false);
- RegisterTransitionTime(DAYZCAMERA_3RD_JUMP, DAYZCAMERA_3RD_ERC_SPR, 0.2, false);
- RegisterTransitionTime(DAYZCAMERA_3RD_ERC, DAYZCAMERA_3RD_JUMP, 0.05, false);
- RegisterTransitionTime(DAYZCAMERA_3RD_JUMP, DAYZCAMERA_3RD_ERC, 0.3, false);
- RegisterTransitionTime(DAYZCAMERA_3RD_ERC, DAYZCAMERA_3RD_CLIMB, 0.3, false);
- RegisterTransitionTime(DAYZCAMERA_3RD_CLIMB, DAYZCAMERA_3RD_ERC, 0.3, false);
- //! 3rd person crouch camera transitions
- RegisterTransitionTime(DAYZCAMERA_3RD_CRO, DAYZCAMERA_3RD_ERC, 0.4, false);
- RegisterTransitionTime(DAYZCAMERA_3RD_CRO, DAYZCAMERA_3RD_PRO, 0.6, true);
- RegisterTransitionTime(DAYZCAMERA_3RD_CRO, DAYZCAMERA_3RD_CRO_RAISED, 0.2, true);
- RegisterTransitionTime(DAYZCAMERA_3RD_CRO, DAYZCAMERA_3RD_ERC_SPR, 0.6, false);
- //! 3rd person prone camera transitions
- RegisterTransitionTime(DAYZCAMERA_3RD_PRO, DAYZCAMERA_3RD_ERC, 0.9, false);
- RegisterTransitionTime(DAYZCAMERA_3RD_PRO, DAYZCAMERA_3RD_CRO, 0.7, false);
- RegisterTransitionTime(DAYZCAMERA_3RD_PRO, DAYZCAMERA_3RD_PRO_RAISED, 0.2, false);
- RegisterTransitionTime(DAYZCAMERA_3RD_PRO, DAYZCAMERA_3RD_ERC_SPR, 0.6, false);
- RegisterTransitionTime(DAYZCAMERA_3RD_PRO_RAISED, DAYZCAMERA_3RD_CRO, 0.7, false);
- RegisterTransitionTime(DAYZCAMERA_3RD_PRO_RAISED, DAYZCAMERA_3RD_CRO_RAISED, 0.7, false);
- RegisterTransitionTime(DAYZCAMERA_3RD_PRO_RAISED, DAYZCAMERA_3RD_ERC, 0.9, false);
- RegisterTransitionTime(DAYZCAMERA_3RD_PRO_RAISED, DAYZCAMERA_3RD_ERC_RAISED, 0.9, false);
- //! ironsights camera transitions
- RegisterTransitionTime(DAYZCAMERA_3RD_ERC_RAISED, DAYZCAMERA_IRONSIGHTS, TIME_CAMERACHANGE_02, true);
- RegisterTransitionTime(DAYZCAMERA_3RD_CRO_RAISED, DAYZCAMERA_IRONSIGHTS, TIME_CAMERACHANGE_02, true);
- RegisterTransitionTime(DAYZCAMERA_3RD_PRO_RAISED, DAYZCAMERA_IRONSIGHTS, TIME_CAMERACHANGE_02, true);
- RegisterTransitionTime(DAYZCAMERA_1ST, DAYZCAMERA_IRONSIGHTS, TIME_CAMERACHANGE_01, true);
- RegisterTransitionTime(DAYZCAMERA_3RD_ERC, DAYZCAMERA_IRONSIGHTS, TIME_CAMERACHANGE_02, true);
- RegisterTransitionTime(DAYZCAMERA_3RD_CRO, DAYZCAMERA_IRONSIGHTS, TIME_CAMERACHANGE_02, true);
- RegisterTransitionTime(DAYZCAMERA_3RD_PRO, DAYZCAMERA_IRONSIGHTS, TIME_CAMERACHANGE_02, true);
- //! optics camera transitions
- RegisterTransitionTime(DAYZCAMERA_IRONSIGHTS, DAYZCAMERA_OPTICS, TIME_CAMERACHANGE_02, true);
- RegisterTransitionTime(DAYZCAMERA_3RD_ERC_RAISED, DAYZCAMERA_OPTICS, TIME_CAMERACHANGE_03, true);
- RegisterTransitionTime(DAYZCAMERA_3RD_CRO_RAISED, DAYZCAMERA_OPTICS, TIME_CAMERACHANGE_03, true);
- RegisterTransitionTime(DAYZCAMERA_3RD_PRO_RAISED, DAYZCAMERA_OPTICS, TIME_CAMERACHANGE_03, true);
- RegisterTransitionTime(DAYZCAMERA_1ST, DAYZCAMERA_OPTICS, TIME_CAMERACHANGE_02, true); //handheld optics only
- RegisterTransitionTime(DAYZCAMERA_3RD_ERC, DAYZCAMERA_OPTICS, TIME_CAMERACHANGE_02, true); //handheld optics only
- RegisterTransitionTime(DAYZCAMERA_3RD_CRO, DAYZCAMERA_OPTICS, TIME_CAMERACHANGE_02, true); //handheld optics only
- RegisterTransitionTime(DAYZCAMERA_3RD_PRO, DAYZCAMERA_OPTICS, TIME_CAMERACHANGE_02, true); //handheld optics only
- //! register function to handle camera changes
- pType.RegisterCameraOnChangeFnStatic(DayZPlayerCameras, "OnCameraChange");
- };
- };modded class ZombieBase
- {
- // autoptr CF_ModStorageBase m_CF_ModStorage = new CF_ModStorageObject<ZombieBase>(this);
- //
- // override void OnStoreSave(ParamsWriteContext ctx)
- // {
- // super.OnStoreSave(ctx);
- //
- // m_CF_ModStorage.OnStoreSave(ctx);
- // }
- //
- // override bool OnStoreLoad(ParamsReadContext ctx, int version)
- // {
- // if (!super.OnStoreLoad(ctx, version))
- // {
- // return false;
- // }
- //
- // return m_CF_ModStorage.OnStoreLoad(ctx, version);
- // }
- /**
- * @brief Refer to CF/ModStorage implementation of ItemBase::CF_OnStoreSave
- */
- void CF_OnStoreSave(CF_ModStorageMap storage)
- {
- }
- /**
- * @brief Refer to CF/ModStorage implementation of ItemBase::CF_OnStoreLoad
- */
- bool CF_OnStoreLoad(CF_ModStorageMap storage)
- {
- return true;
- }
- };
- class CF_EventPlayerArgs : CF_EventArgs
- {
- PlayerBase Player;
- PlayerIdentity Identity;
- void CF_EventPlayerArgs(PlayerBase player = null, PlayerIdentity identity = null)
- {
- Player = player;
- Identity = identity;
- }
- };
- class CF_EventPlayerDisconnectedArgs : CF_EventPlayerArgs
- {
- string UID;
- int LogoutTime = -1; // -1 for Disconnected
- bool AuthFailed;
- };
- class CF_EventNewPlayerArgs : CF_EventPlayerArgs
- {
- vector Position;
- ParamsReadContext Context;
- void CF_EventNewPlayerArgs(PlayerBase player = null, PlayerIdentity identity = null, vector position = "0 0 0", ParamsReadContext ctx = null)
- {
- Position = position;
- Context = ctx;
- }
- };
- class CF_EventPlayerPrepareArgs : CF_EventArgs
- {
- PlayerIdentity Identity;
- bool UseDatabase;
- vector Position;
- float Yaw;
- int PreloadTimeout;
- };
- class CF_ModStorageBase
- {
- void OnStoreSave(ParamsWriteContext ctx)
- {
- }
- bool OnStoreLoad(ParamsReadContext ctx, int version)
- {
- return true;
- }
- };
- #ifndef CF_MODSTORAGE_DISABLE
- class CF_ModStorageObject<Class T> : CF_ModStorageBase
- {
- T m_Entity;
- autoptr array<ref CF_ModStorage> m_UnloadedMods;
- CF_ModStorageModule m_Module;
- void CF_ModStorageObject(T entity)
- {
- m_Entity = entity;
- m_UnloadedMods = new array<ref CF_ModStorage>();
- ModLoader.LoadMods();
- // Reset the stream for 'OnStoreSave'
- foreach (auto mod : ModLoader.s_CF_ModStorages)
- {
- mod._ResetStream();
- }
- m_Module = CF_Modules<CF_ModStorageModule>.Get();
- }
- override void OnStoreSave(ParamsWriteContext ctx)
- {
- #ifdef CF_MODSTORAGE_TRACE
- auto trace = CF_Trace_1(this).Add(ctx);
- #endif
- if (GetGame().SaveVersion() < CF_ModStorage.GAME_VERSION_FIRST_INSTALL)
- {
- return;
- }
- #ifndef CF_MODSTORAGE_MODULE_DISABLE
- int b1, b2, b3, b4;
- m_Entity.GetPersistentID(b1, b2, b3, b4);
- // Add the entity to the file so on next load the game knows that it can read the modstorage for the entity
- m_Module.AddEntity(b1, b2, b3, b4);
- #endif
- // Write the CF modstorage version
- ctx.Write(CF_ModStorage.VERSION);
- // Reset the stream for 'OnStoreSave'
- foreach (auto mod : ModLoader.s_CF_ModStorages)
- {
- mod._ResetStream();
- }
- m_Entity.CF_OnStoreSave(ModLoader.s_CF_ModStorageMap);
- ctx.Write(ModLoader.s_CF_ModStorages.Count() + m_UnloadedMods.Count());
- foreach (auto mod2 : ModLoader.s_CF_ModStorages)
- {
- // also resets the stream for next 'OnStoreSave'
- mod2._CopyStreamTo(ctx);
- }
- foreach (auto unloadedMod : m_UnloadedMods)
- {
- // Since mod is unloaded, the stream is not reset
- unloadedMod._CopyStreamTo(ctx);
- }
- }
- override bool OnStoreLoad(ParamsReadContext ctx, int version)
- {
- #ifdef CF_MODSTORAGE_TRACE
- auto trace = CF_Trace_2(this).Add(ctx).Add(version);
- #endif
- // Clearing the unloaded mods data
- m_UnloadedMods.Clear();
- // Persistence version is prior to 1.10
- if (version < CF_ModStorage.GAME_VERSION_FIRST_INSTALL)
- {
- return true;
- }
- #ifndef CF_MODSTORAGE_MODULE_DISABLE
- int b1, b2, b3, b4;
- m_Entity.GetPersistentID(b1, b2, b3, b4);
- // If the version is less than the wipe file, the entity will be added automatically in 'OnStoreSave'
- if (version >= CF_ModStorage.GAME_VERSION_WIPE_FILE)
- {
- if (!m_Module.IsEntity(b1, b2, b3, b4))
- {
- // Since the entity wasn't found we can assume that CF is freshly loaded
- // Highly unlikely anything else happened that can cause this
- // * A new entity won't take the ID of an old entity if it is in circulation
- // * If this is a new entity, OnStoreSave would've been called at some point before 'OnStoreLoad'
- return true;
- }
- }
- #endif
- int cf_version;
- if (!ctx.Read(cf_version))
- {
- return false;
- }
- // CF version is prior to ModStorage implementation
- if (cf_version < CF_ModStorage.MODSTORAGE_INITIAL_IMPLEMENTATION)
- {
- return true;
- }
- int numMods;
- if (!ctx.Read(numMods))
- {
- return false;
- }
- m_UnloadedMods.Resize(numMods);
- CF_ModStorageMap loadedMods();
- int unloadedModsRead;
- for (int modsRead = 0; modsRead < numMods; modsRead++)
- {
- if (!ModLoader._CF_ReadModStorage(ctx, cf_version, m_UnloadedMods, unloadedModsRead, loadedMods))
- {
- CF_Log.Error("Failed to read modstorage for entity Type=%1, Position=%2", m_Entity.GetType(), m_Entity.GetPosition().ToString());
- return false;
- }
- }
- m_UnloadedMods.Resize(unloadedModsRead);
- m_Entity.CF_OnStoreLoad(loadedMods);
- // Reset the stream for 'OnStoreSave'
- foreach (auto mod : ModLoader.s_CF_ModStorages)
- {
- mod._ResetStream();
- }
- return true;
- }
- };
- #endif
- modded class BuildingBase
- {
- override void OnStoreSave(ParamsWriteContext ctx)
- {
- super.OnStoreSave(ctx);
- ctx.Write(1);
- }
- override bool OnStoreLoad(ParamsReadContext ctx, int version)
- {
- if (!super.OnStoreLoad(ctx,version))
- return false;
- // If the persistence file is before 1.10, cf data doesn't exist
- if (version < 116) return true;
- int cf_version;
- if (!ctx.Read( cf_version )) return false;
- return true;
- }
- }
- modded class AnimalBase
- {
- override void OnStoreSave(ParamsWriteContext ctx)
- {
- super.OnStoreSave(ctx);
- ctx.Write(1);
- }
- override bool OnStoreLoad(ParamsReadContext ctx, int version)
- {
- if (!super.OnStoreLoad(ctx,version))
- return false;
- // If the persistence file is before 1.10, cf data doesn't exist
- if (version < 116) return true;
- int cf_version;
- if (!ctx.Read( cf_version )) return false;
- return true;
- }
- }
- modded class ZombieBase
- {
- override void OnStoreSave(ParamsWriteContext ctx)
- {
- super.OnStoreSave(ctx);
- ctx.Write(1);
- }
- override bool OnStoreLoad(ParamsReadContext ctx, int version)
- {
- if (!super.OnStoreLoad(ctx,version))
- return false;
- // If the persistence file is before 1.10, cf data doesn't exist
- if (version < 116) return true;
- int cf_version;
- if (!ctx.Read( cf_version )) return false;
- return true;
- }
- }
- modded class ItemBase
- {
- override void OnStoreSave(ParamsWriteContext ctx)
- {
- super.OnStoreSave(ctx);
- ctx.Write(1);
- }
- override bool OnStoreLoad(ParamsReadContext ctx, int version)
- {
- if (!super.OnStoreLoad(ctx,version))
- return false;
- // If the persistence file is before 1.10, cf data doesn't exist
- if (version < 116) return true;
- int cf_version;
- if (!ctx.Read( cf_version )) return false;
- return true;
- }
- }
- modded class DayZPlayerImplement
- {
- override void OnStoreSave(ParamsWriteContext ctx)
- {
- super.OnStoreSave(ctx);
- ctx.Write(1);
- }
- override bool OnStoreLoad(ParamsReadContext ctx, int version)
- {
- if (!super.OnStoreLoad(ctx,version))
- return false;
- // If the persistence file is before 1.10, cf data doesn't exist
- if (version < 116) return true;
- int cf_version;
- if (!ctx.Read( cf_version )) return false;
- return true;
- }
- }
- modded class CarScript
- {
- override void OnStoreSave(ParamsWriteContext ctx)
- {
- super.OnStoreSave(ctx);
- ctx.Write(1);
- }
- override bool OnStoreLoad(ParamsReadContext ctx, int version)
- {
- if (!super.OnStoreLoad(ctx,version))
- return false;
- // If the persistence file is before 1.10, cf data doesn't exist
- if (version < 116) return true;
- int cf_version;
- if (!ctx.Read( cf_version )) return false;
- return true;
- }
- }
- modded class HelicopterScript
- {
- override void OnStoreSave(ParamsWriteContext ctx)
- {
- super.OnStoreSave(ctx);
- ctx.Write(1);
- }
- override bool OnStoreLoad(ParamsReadContext ctx, int version)
- {
- if (!super.OnStoreLoad(ctx,version))
- return false;
- // If the persistence file is before 1.10, cf data doesn't exist
- if (version < 116) return true;
- int cf_version;
- if (!ctx.Read( cf_version )) return false;
- return true;
- }
- }
- modded class AdvancedCommunication
- {
- override void OnStoreSave(ParamsWriteContext ctx)
- {
- super.OnStoreSave(ctx);
- ctx.Write(1);
- }
- override bool OnStoreLoad(ParamsReadContext ctx, int version)
- {
- if (!super.OnStoreLoad(ctx,version))
- return false;
- // If the persistence file is before 1.10, cf data doesn't exist
- if (version < 116) return true;
- int cf_version;
- if (!ctx.Read( cf_version )) return false;
- return true;
- }
- }class CF_ModuleWorld : CF_ModuleGame
- {
- void EnableInvokeConnect()
- {
- CF_ModuleWorldManager.s_InvokeConnect.Add(this);
- }
- void EnableInvokeDisconnect()
- {
- CF_ModuleWorldManager.s_InvokeDisconnect.Add(this);
- }
- void EnableClientNew()
- {
- CF_ModuleWorldManager.s_ClientNew.Add(this);
- }
- void EnableClientRespawn()
- {
- CF_ModuleWorldManager.s_ClientRespawn.Add(this);
- }
- void EnableClientReady()
- {
- CF_ModuleWorldManager.s_ClientReady.Add(this);
- }
- void EnableClientPrepare()
- {
- CF_ModuleWorldManager.s_ClientPrepare.Add(this);
- }
- void EnableClientLogoutReconnect()
- {
- CF_ModuleWorldManager.s_ClientReconnect.Add(this);
- }
- void EnableClientLogout()
- {
- CF_ModuleWorldManager.s_ClientLogout.Add(this);
- }
- void EnableClientDisconnect()
- {
- CF_ModuleWorldManager.s_ClientDisconnect.Add(this);
- }
- void EnableClientLogoutCancelled()
- {
- CF_ModuleWorldManager.s_ClientLogoutCancelled.Add(this);
- }
- /**
- * @brief See: MissionServer::InvokeOnConnect
- */
- void OnInvokeConnect(Class sender, CF_EventArgs args);
- /**
- * @brief See: MissionServer::InvokeOnDisconnect
- */
- void OnInvokeDisconnect(Class sender, CF_EventArgs args);
- /**
- * @brief See: ClientNewEventTypeID
- */
- void OnClientNew(Class sender, CF_EventArgs args);
- /**
- * @brief See: ClientRespawnEventTypeID
- */
- void OnClientRespawn(Class sender, CF_EventArgs args);
- /**
- * @brief See: ClientReadyEventTypeID
- */
- void OnClientReady(Class sender, CF_EventArgs args);
- /**
- * @brief See: ClientPrepareEventTypeID
- */
- void OnClientPrepare(Class sender, CF_EventArgs args);
- /**
- * @brief See: ClientReconnectEventTypeID
- */
- void OnClientReconnect(Class sender, CF_EventArgs args);
- /**
- * @brief See: ClientDisconnectedEventTypeID
- */
- void OnClientLogout(Class sender, CF_EventArgs args);
- /**
- * @brief See: MissionServer::PlayerDisconnected - Fires when the player has disconnected from the server (OnClientReconnect won't fire)
- */
- void OnClientDisconnect(Class sender, CF_EventArgs args);
- /**
- * @brief See: LogoutCancelEventTypeID
- */
- void OnClientLogoutCancelled(Class sender, CF_EventArgs args);
- };
- class CF_ModuleWorldEvent : CF_ModuleCoreEvent
- {
- void OnInvokeConnect(Class sender, CF_EventArgs args)
- {
- auto evt = this.m_Next;
- while (evt)
- {
- auto module = CF_ModuleWorld.Cast(evt.m_Value);
- if ((module.m_CF_GameFlag & CF_ModuleCoreManager.s_GameFlag) != 0)
- {
- module.OnInvokeConnect(sender, args);
- }
- evt = evt.m_Next;
- }
- }
- void OnInvokeDisconnect(Class sender, CF_EventArgs args)
- {
- auto evt = this.m_Next;
- while (evt)
- {
- auto module = CF_ModuleWorld.Cast(evt.m_Value);
- if ((module.m_CF_GameFlag & CF_ModuleCoreManager.s_GameFlag) != 0)
- {
- module.OnInvokeDisconnect(sender, args);
- }
- evt = evt.m_Next;
- }
- }
- void OnClientNew(Class sender, CF_EventArgs args)
- {
- auto evt = this.m_Next;
- while (evt)
- {
- auto module = CF_ModuleWorld.Cast(evt.m_Value);
- if ((module.m_CF_GameFlag & CF_ModuleCoreManager.s_GameFlag) != 0)
- {
- module.OnClientNew(sender, args);
- }
- evt = evt.m_Next;
- }
- }
- void OnClientRespawn(Class sender, CF_EventArgs args)
- {
- auto evt = this.m_Next;
- while (evt)
- {
- auto module = CF_ModuleWorld.Cast(evt.m_Value);
- if ((module.m_CF_GameFlag & CF_ModuleCoreManager.s_GameFlag) != 0)
- {
- module.OnClientRespawn(sender, args);
- }
- evt = evt.m_Next;
- }
- }
- void OnClientReady(Class sender, CF_EventArgs args)
- {
- auto evt = this.m_Next;
- while (evt)
- {
- auto module = CF_ModuleWorld.Cast(evt.m_Value);
- if ((module.m_CF_GameFlag & CF_ModuleCoreManager.s_GameFlag) != 0)
- {
- module.OnClientReady(sender, args);
- }
- evt = evt.m_Next;
- }
- }
- void OnClientPrepare(Class sender, CF_EventArgs args)
- {
- auto evt = this.m_Next;
- while (evt)
- {
- auto module = CF_ModuleWorld.Cast(evt.m_Value);
- if ((module.m_CF_GameFlag & CF_ModuleCoreManager.s_GameFlag) != 0)
- {
- module.OnClientPrepare(sender, args);
- }
- evt = evt.m_Next;
- }
- }
- void OnClientReconnect(Class sender, CF_EventArgs args)
- {
- auto evt = this.m_Next;
- while (evt)
- {
- auto module = CF_ModuleWorld.Cast(evt.m_Value);
- if ((module.m_CF_GameFlag & CF_ModuleCoreManager.s_GameFlag) != 0)
- {
- module.OnClientReconnect(sender, args);
- }
- evt = evt.m_Next;
- }
- }
- void OnClientLogout(Class sender, CF_EventArgs args)
- {
- auto evt = this.m_Next;
- while (evt)
- {
- auto module = CF_ModuleWorld.Cast(evt.m_Value);
- if ((module.m_CF_GameFlag & CF_ModuleCoreManager.s_GameFlag) != 0)
- {
- module.OnClientLogout(sender, args);
- }
- evt = evt.m_Next;
- }
- }
- void OnClientDisconnect(Class sender, CF_EventArgs args)
- {
- auto evt = this.m_Next;
- while (evt)
- {
- auto module = CF_ModuleWorld.Cast(evt.m_Value);
- if ((module.m_CF_GameFlag & CF_ModuleCoreManager.s_GameFlag) != 0)
- {
- module.OnClientDisconnect(sender, args);
- }
- evt = evt.m_Next;
- }
- }
- void OnClientLogoutCancelled(Class sender, CF_EventArgs args)
- {
- auto evt = this.m_Next;
- while (evt)
- {
- auto module = CF_ModuleWorld.Cast(evt.m_Value);
- if ((module.m_CF_GameFlag & CF_ModuleCoreManager.s_GameFlag) != 0)
- {
- module.OnClientLogoutCancelled(sender, args);
- }
- evt = evt.m_Next;
- }
- }
- };
- class CF_ModuleWorldManager
- {
- static autoptr CF_ModuleWorldEvent s_InvokeConnect = new CF_ModuleWorldEvent();
- static autoptr CF_ModuleWorldEvent s_InvokeDisconnect = new CF_ModuleWorldEvent();
- static autoptr CF_ModuleWorldEvent s_ClientNew = new CF_ModuleWorldEvent();
- static autoptr CF_ModuleWorldEvent s_ClientRespawn = new CF_ModuleWorldEvent();
- static autoptr CF_ModuleWorldEvent s_ClientReady = new CF_ModuleWorldEvent();
- static autoptr CF_ModuleWorldEvent s_ClientPrepare = new CF_ModuleWorldEvent();
- static autoptr CF_ModuleWorldEvent s_ClientReconnect = new CF_ModuleWorldEvent();
- static autoptr CF_ModuleWorldEvent s_ClientLogout = new CF_ModuleWorldEvent();
- static autoptr CF_ModuleWorldEvent s_ClientDisconnect = new CF_ModuleWorldEvent();
- static autoptr CF_ModuleWorldEvent s_ClientLogoutCancelled = new CF_ModuleWorldEvent();
- static void OnInvokeConnect(Class sender, CF_EventArgs args)
- {
- s_InvokeConnect.OnInvokeConnect(sender, args);
- delete args;
- }
- static void OnInvokeDisconnect(Class sender, CF_EventArgs args)
- {
- s_InvokeDisconnect.OnInvokeDisconnect(sender, args);
- delete args;
- }
- static void OnClientNew(Class sender, CF_EventArgs args)
- {
- s_ClientNew.OnClientNew(sender, args);
- delete args;
- }
- static void OnClientRespawn(Class sender, CF_EventArgs args)
- {
- s_ClientRespawn.OnClientRespawn(sender, args);
- delete args;
- }
- static void OnClientReady(Class sender, CF_EventArgs args)
- {
- s_ClientReady.OnClientReady(sender, args);
- delete args;
- }
- static void OnClientPrepare(Class sender, CF_EventArgs args)
- {
- s_ClientPrepare.OnClientPrepare(sender, args);
- delete args;
- }
- static void OnClientReconnect(Class sender, CF_EventArgs args)
- {
- s_ClientReconnect.OnClientReconnect(sender, args);
- delete args;
- }
- static void OnClientLogout(Class sender, CF_EventArgs args)
- {
- s_ClientLogout.OnClientLogout(sender, args);
- delete args;
- }
- static void OnClientDisconnect(Class sender, CF_EventArgs args)
- {
- s_ClientDisconnect.OnClientDisconnect(sender, args);
- delete args;
- }
- static void OnClientLogoutCancelled(Class sender, CF_EventArgs args)
- {
- s_ClientLogoutCancelled.OnClientLogoutCancelled(sender, args);
- delete args;
- }
- };
- /**
- * @class JMModuleBase
- *
- * @deprecated
- */
- class JMModuleBase : CF_ModuleWorld
- {
- /**
- * Any module that inherits from 'JMModuleBase' probably expects all events to be enabled
- */
- override void Init()
- {
- EnableUpdate();
- EnableMissionStart();
- EnableMissionFinish();
- EnableMissionLoaded();
- EnableSettingsChanged();
- EnablePermissionsChanged();
- EnableWorldCleanup();
- EnableMPSessionStart();
- EnableMPSessionPlayerReady();
- EnableMPSessionFail();
- EnableMPSessionEnd();
- EnableMPConnectAbort();
- EnableMPConnectionLost();
- EnableRespawn();
- EnableRPC();
- EnableInvokeConnect();
- EnableInvokeDisconnect();
- EnableClientNew();
- EnableClientRespawn();
- EnableClientReady();
- EnableClientPrepare();
- EnableClientLogoutReconnect();
- EnableClientLogout();
- EnableClientDisconnect();
- EnableClientLogoutCancelled();
- GetModuleManager().NP_InitModule(this);
- RegisterKeyMouseBindings();
- super.Init();
- }
- void Toggle()
- {
- }
- void PreventInput(bool prevent)
- {
- }
- string GetModuleName()
- {
- return ClassName();
- }
- typename GetModuleType()
- {
- return Type();
- }
- bool IsEnabled()
- {
- return true;
- }
- bool IsPreventingInput()
- {
- return false;
- }
- set<ref JMModuleBinding> GetBindings()
- {
- return new set<ref JMModuleBinding>();
- }
- override void OnRPC(Class sender, CF_EventArgs args)
- {
- super.OnRPC(sender, args);
- auto rpc = CF_EventRPCArgs.Cast(args);
- OnRPC(rpc.Sender, rpc.Target, rpc.ID, rpc.Context);
- }
- override void OnMissionStart(Class sender, CF_EventArgs args)
- {
- super.OnMissionStart(sender, args);
- OnMissionStart();
- }
- override void OnMissionFinish(Class sender, CF_EventArgs args)
- {
- super.OnMissionFinish(sender, args);
- OnMissionFinish();
- }
- override void OnMissionLoaded(Class sender, CF_EventArgs args)
- {
- super.OnMissionLoaded(sender, args);
- OnMissionLoaded();
- }
- override void OnUpdate(Class sender, CF_EventArgs args)
- {
- super.OnUpdate(sender, args);
- auto update = CF_EventUpdateArgs.Cast(args);
- OnUpdate(update.DeltaTime);
- }
- override void OnSettingsChanged(Class sender, CF_EventArgs args)
- {
- super.OnSettingsChanged(sender, args);
- OnSettingsUpdated();
- }
- override void OnPermissionsChanged(Class sender, CF_EventArgs args)
- {
- super.OnPermissionsChanged(sender, args);
- OnClientPermissionsUpdated();
- }
- override void OnWorldCleanup(Class sender, CF_EventArgs args)
- {
- super.OnWorldCleanup(sender, args);
- OnWorldCleanup();
- }
- override void OnMPSessionStart(Class sender, CF_EventArgs args)
- {
- super.OnMPSessionStart(sender, args);
- OnMPSessionStart();
- }
- override void OnMPSessionPlayerReady(Class sender, CF_EventArgs args)
- {
- super.OnMPSessionPlayerReady(sender, args);
- OnMPSessionPlayerReady();
- }
- override void OnMPSessionFail(Class sender, CF_EventArgs args)
- {
- super.OnMPSessionFail(sender, args);
- OnMPSessionFail();
- }
- override void OnMPSessionEnd(Class sender, CF_EventArgs args)
- {
- super.OnMPSessionEnd(sender, args);
- OnMPSessionEnd();
- }
- override void OnMPConnectAbort(Class sender, CF_EventArgs args)
- {
- super.OnMPConnectAbort(sender, args);
- OnMPConnectAbort();
- }
- override void OnMPConnectionLost(Class sender, CF_EventArgs args)
- {
- super.OnMPConnectionLost(sender, args);
- OnMPConnectionLost(CF_EventTimeArgs.Cast(args).Time);
- }
- override void OnRespawn(Class sender, CF_EventArgs args)
- {
- super.OnRespawn(sender, args);
- OnRespawn(CF_EventTimeArgs.Cast(args).Time);
- }
- override void OnInvokeConnect(Class sender, CF_EventArgs args)
- {
- super.OnInvokeConnect(sender, args);
- auto cArgs = CF_EventPlayerArgs.Cast(args);
- OnInvokeConnect(cArgs.Player, cArgs.Identity);
- }
- override void OnInvokeDisconnect(Class sender, CF_EventArgs args)
- {
- super.OnInvokeDisconnect(sender, args);
- auto cArgs = CF_EventPlayerArgs.Cast(args);
- OnInvokeDisconnect(cArgs.Player);
- }
- override void OnClientNew(Class sender, CF_EventArgs args)
- {
- super.OnClientNew(sender, args);
- auto cArgs = CF_EventNewPlayerArgs.Cast(args);
- OnClientNew(cArgs.Player, cArgs.Identity, cArgs.Position, cArgs.Context);
- }
- override void OnClientRespawn(Class sender, CF_EventArgs args)
- {
- super.OnClientRespawn(sender, args);
- auto cArgs = CF_EventPlayerArgs.Cast(args);
- OnClientRespawn(cArgs.Player, cArgs.Identity);
- }
- override void OnClientReady(Class sender, CF_EventArgs args)
- {
- super.OnClientReady(sender, args);
- auto cArgs = CF_EventPlayerArgs.Cast(args);
- OnClientReady(cArgs.Player, cArgs.Identity);
- }
- override void OnClientPrepare(Class sender, CF_EventArgs args)
- {
- super.OnClientPrepare(sender, args);
- auto cArgs = CF_EventPlayerPrepareArgs.Cast(args);
- OnClientPrepare(cArgs.Identity, cArgs.UseDatabase, cArgs.Position, cArgs.Yaw, cArgs.PreloadTimeout);
- }
- override void OnClientReconnect(Class sender, CF_EventArgs args)
- {
- super.OnClientReconnect(sender, args);
- auto cArgs = CF_EventPlayerArgs.Cast(args);
- OnClientReconnect(cArgs.Player, cArgs.Identity);
- }
- override void OnClientLogout(Class sender, CF_EventArgs args)
- {
- super.OnClientLogout(sender, args);
- auto cArgs = CF_EventPlayerDisconnectedArgs.Cast(args);
- OnClientLogout(cArgs.Player, cArgs.Identity, cArgs.LogoutTime, cArgs.AuthFailed);
- }
- override void OnClientDisconnect(Class sender, CF_EventArgs args)
- {
- super.OnClientDisconnect(sender, args);
- auto cArgs = CF_EventPlayerDisconnectedArgs.Cast(args);
- OnClientDisconnect(cArgs.Player, cArgs.Identity, cArgs.UID);
- }
- override void OnClientLogoutCancelled(Class sender, CF_EventArgs args)
- {
- super.OnClientLogoutCancelled(sender, args);
- auto cArgs = CF_EventPlayerArgs.Cast(args);
- OnClientLogoutCancelled(cArgs.Player);
- }
- // Old Events
- void OnRPC(PlayerIdentity sender, Object target, int rpc_type, ParamsReadContext ctx);
- void OnMissionStart();
- void OnMissionFinish();
- void OnMissionLoaded();
- void OnUpdate(float timeslice);
- void OnSettingsUpdated();
- void OnClientPermissionsUpdated();
- void OnPermissionsChanged();
- void OnWorldCleanup();
- void OnMPSessionStart();
- void OnMPSessionPlayerReady();
- void OnMPSessionFail();
- void OnMPSessionEnd();
- void OnMPConnectAbort();
- void OnMPConnectionLost(int duration);
- void OnRespawn(int time);
- void OnInvokeConnect(PlayerBase player, PlayerIdentity identity);
- void OnInvokeDisconnect(PlayerBase player);
- void OnClientNew(inout PlayerBase player, PlayerIdentity identity, vector pos, ParamsReadContext ctx);
- void OnClientRespawn(PlayerBase player, PlayerIdentity identity);
- void OnClientReady(PlayerBase player, PlayerIdentity identity);
- void OnClientPrepare(PlayerIdentity identity, inout bool useDB, inout vector pos, inout float yaw, inout int preloadTimeout);
- void OnClientReconnect(PlayerBase player, PlayerIdentity identity);
- void OnClientLogout(PlayerBase player, PlayerIdentity identity, int logoutTime, bool authFailed);
- void OnClientDisconnect(PlayerBase player, PlayerIdentity identity, string uid);
- void OnClientLogoutCancelled(PlayerBase player);
- void RegisterKeyMouseBindings()
- {
- }
- void RegisterKeyMouseBinding(JMModuleBinding binding)
- {
- Bind(binding);
- Error_Deprecated("RegisterKeyMouseBinding", "Bind");
- }
- void RegisterBinding(JMModuleBinding binding)
- {
- Bind(binding);
- Error_Deprecated("RegisterBinding", "Bind");
- }
- };
- /**
- * @class JMModuleBinding
- *
- * @deprecated
- */
- class JMModuleBinding : CF_InputBinding
- {
- void JMModuleBinding(string callback, string input, bool menu = false)
- {
- m_Function = callback;
- m_Input = GetUApi().GetInputByName(input);
- m_LimitMenu = !menu;
- }
- };
- /**
- * @class JMModuleConstructorBase
- *
- * @deprecated
- */
- class JMModuleConstructorBase
- {
- autoptr TTypenameArray m_Modules = new TTypenameArray();
- void JMModuleConstructorBase()
- {
- RegisterModules(m_Modules);
- for (int i = 0; i < m_Modules.Count(); i++)
- {
- CF_ModuleCoreManager._Insert(m_Modules[i]);
- }
- }
- void RegisterModules(out TTypenameArray modules);
- };
- /**
- * @class JMModuleManager
- *
- * @deprecated
- */
- class JMModuleManager : JMModuleManagerBase
- {
- protected autoptr array<JMModuleBase> m_ModuleList;
- void JMModuleManager()
- {
- m_ModuleList = new array<JMModuleBase>();
- }
- JMModuleBase GetModule(typename type)
- {
- return JMModuleBase.Cast(CF_ModuleCoreManager.Get(type));
- }
- protected void InitModule(JMModuleBase module)
- {
- #ifdef CF_TRACE_ENABLED
- auto trace = CF_Trace_1(this).Add(module);
- #endif
- m_ModuleList.Insert(module);
- }
- /**
- * @note Can't remove protected from 'InitModule'' without compile errors
- */
- void NP_InitModule(JMModuleBase module)
- {
- InitModule(module);
- }
- void OnInvokeConnect(PlayerBase player, PlayerIdentity identity)
- {
- CF_ModuleWorldManager.OnInvokeConnect(this, new CF_EventPlayerArgs(player, identity));
- }
- void OnInvokeDisconnect(PlayerBase player)
- {
- CF_ModuleWorldManager.OnInvokeDisconnect(this, new CF_EventPlayerArgs(player));
- }
- void OnClientNew(out PlayerBase player, PlayerIdentity identity, vector pos, ParamsReadContext ctx)
- {
- auto args = new CF_EventNewPlayerArgs(player, identity, pos, ctx);
- CF_ModuleWorldManager.OnClientNew(this, args);
- player = args.Player;
- }
- void OnClientReady(PlayerBase player, PlayerIdentity identity)
- {
- CF_ModuleWorldManager.OnClientReady(this, new CF_EventPlayerArgs(player, identity));
- }
- void OnClientPrepare(PlayerIdentity identity, out bool useDB, out vector pos, out float yaw, out int preloadTimeout)
- {
- auto args = new CF_EventPlayerPrepareArgs();
- args.Identity = identity;
- args.UseDatabase = useDB;
- args.Position = pos;
- args.Yaw = yaw;
- args.PreloadTimeout = preloadTimeout;
- CF_ModuleWorldManager.OnClientPrepare(this, args);
- }
- void OnClientReconnect(PlayerBase player, PlayerIdentity identity)
- {
- CF_ModuleWorldManager.OnClientReconnect(this, new CF_EventPlayerArgs(player, identity));
- }
- void OnClientRespawn(PlayerBase player, PlayerIdentity identity)
- {
- CF_ModuleWorldManager.OnClientRespawn(this, new CF_EventPlayerArgs(player, identity));
- }
- void OnClientLogout(PlayerBase player, PlayerIdentity identity, int logoutTime, bool authFailed)
- {
- auto args = new CF_EventPlayerDisconnectedArgs(player, identity);
- args.LogoutTime = logoutTime;
- args.AuthFailed = authFailed;
- CF_ModuleWorldManager.OnClientLogout(this, args);
- }
- void OnClientDisconnect(PlayerBase player, PlayerIdentity identity, string uid)
- {
- auto args = new CF_EventPlayerDisconnectedArgs(player, identity);
- args.UID = uid;
- CF_ModuleWorldManager.OnClientDisconnect(this, args);
- }
- void OnClientLogoutCancelled(PlayerBase player)
- {
- CF_ModuleWorldManager.OnClientLogoutCancelled(this, new CF_EventPlayerArgs(player));
- }
- }
- static JMModuleManager GetModuleManager()
- {
- if (!g_JMModuleManager)
- {
- g_JMModuleManager = new JMModuleManager();
- }
- return g_JMModuleManager;
- }
- static ref JMModuleManager g_JMModuleManager;
- static void CreateModuleManager(JMModuleConstructorBase construct)
- {
- }
- class CF_Surface
- {
- private static autoptr map<string, autoptr CF_Surface> s_Surfaces = new map<string, autoptr CF_Surface>();
- private static string s_LastSurface;
- string Name = s_LastSurface;
- float Interior = GetValueFloat("interior");
- float Deflection = GetValueFloat("deflection");
- float Friction = GetValueFloat("friction");
- float Restitution = GetValueFloat("restitution");
- string SoundEnvironment = GetValueString("soundEnviron");
- string SoundHit = GetValueString("soundHit");
- string Character = GetValueString("character");
- string Files = GetValueString("files");
- float FootDamage = GetValueFloat("footDamage");
- float Audibility = GetValueFloat("audibility");
- string Impact = GetValueString("impact");
- bool IsDigable = GetValueInt("isDigable");
- bool IsFertile = GetValueInt("isFertile");
- bool IsLiquid = GetValueInt("liquidType");
- bool IsStairs = GetValueInt("isStairs");
- int LiquidType = GetValueInt("liquidType");
- float ChanceForCatch = GetValueFloat("chanceForCatch");
- float WindModifier = GetValueFloat("windModifier");
- CF_VehicleSurface VehicleSurface = GetValueVehicleSurface("vpSurface");
- /**
- * @brief Private constructor to prevent outside creation of the class
- */
- private void CF_Surface()
- {
- #ifdef CF_TRACE_ENABLED
- auto trace = CF_Trace_0(this);
- #endif
- s_Surfaces[s_LastSurface] = this;
- }
- /**
- * @brief Private constructor to prevent from marking as ref
- */
- private void ~CF_Surface()
- {
- #ifdef CF_TRACE_ENABLED
- auto trace = CF_Trace_0(this);
- #endif
- }
- /**
- * @brief Get the surface by the name. From 'CfgSurfaces'
- *
- * @param name The class name of the surface
- *
- * @return Instance of the surface class, creates a new one if it doesn't exist
- */
- static CF_Surface Get(string name)
- {
- #ifdef CF_TRACE_ENABLED
- auto trace = CF_Trace_1("CF_Surface").Add(name);
- #endif
- auto surf = s_Surfaces[name];
- if (!surf)
- {
- s_LastSurface = name;
- return new CF_Surface();
- }
- return surf;
- }
- /**
- * @brief Get the surface at the position in the world
- *
- * @param position The position of the surface within the world
- *
- * @return Global instance of the surface class
- */
- static CF_Surface At(vector position)
- {
- string name;
- GetGame().SurfaceGetType3D(position[0], position[1], position[2], name);
- return CF_Surface.Get(name);
- }
- /**
- * @brief Get the surface at the position in the world at it's maximum height
- *
- * @param x The x position of the surface within the world
- * @param z The z position of the surface within the world
- *
- * @return Global instance of the surface class
- */
- static CF_Surface At(float x, float z)
- {
- string name;
- GetGame().SurfaceGetType(x, z, name);
- return CF_Surface.Get(name);
- }
- /**
- * @brief Get the surface at the position in the world at it's maximum height
- *
- * @param object The object above the surface of the object
- *
- * @return Global instance of the surface class
- */
- static CF_Surface At(Object object)
- {
- string name;
- int liquidType;
- GetGame().SurfaceUnderObject(object, name, liquidType);
- return CF_Surface.Get(name);
- }
- #ifdef CF_DebugUI
- bool CF_OnDebugUpdate(CF_Debug instance, CF_DebugUI_Type type)
- {
- instance.Add("Name", Name);
- instance.Add("Interior", Interior);
- instance.Add("Deflection", Deflection);
- instance.Add("Friction", Friction);
- instance.Add("Restitution", Restitution);
- instance.Add("Sound Environent", SoundEnvironment);
- instance.Add("Sound Hit", SoundHit);
- instance.Add("Character", Character);
- instance.Add("Files", Files);
- instance.Add("Foot Damage", FootDamage);
- instance.Add("Audibility", Audibility);
- instance.Add("Impact", Impact);
- instance.Add("Is Digable", IsDigable);
- instance.Add("Is Fertile", IsFertile);
- instance.Add("Is Liquid", IsLiquid);
- instance.Add("Is Stairs", IsStairs);
- instance.Add("LiquidType", LiquidType);
- instance.Add("Chance For Catch", ChanceForCatch);
- instance.Add("Wind Modifier", WindModifier);
- instance.Add(VehicleSurface);
- return true;
- }
- #endif
- override string GetDebugName()
- {
- string str = this.ToString();
- str += ",\n\tName=\"" + Name + "\"";
- str += ",\n\tInterior=\"" + Interior + "\"";
- str += ",\n\tDeflection=\"" + Deflection + "\"";
- str += ",\n\tFriction=\"" + Friction + "\"";
- str += ",\n\tRestitution=\"" + Restitution + "\"";
- str += ",\n\tSoundEnvironent=\"" + SoundEnvironment + "\"";
- str += ",\n\tSoundHit=\"" + SoundHit + "\"";
- str += ",\n\tCharacter=\"" + Character + "\"";
- str += ",\n\tFiles=\"" + Files + "\"";
- str += ",\n\tFootDamage=\"" + FootDamage + "\""; ;
- str += ",\n\tAudibility=\"" + Audibility + "\"";
- str += ",\n\tImpact=\"" + Impact + "\"";
- str += ",\n\tIsDigable=\"" + IsDigable + "\"";
- str += ",\n\tIsFertile=\"" + IsFertile + "\"";
- str += ",\n\tIsLiquid=\"" + IsLiquid + "\"";
- str += ",\n\tIsStairs=\"" + IsStairs + "\"";
- str += ",\n\tLiquidType=\"" + LiquidType + "\"";
- str += ",\n\tChanceForCatch=\"" + ChanceForCatch + "\"";
- str += ",\n\tWindModifier=\"" + WindModifier + "\"";
- str += ",\n\tVehicleSurface=\"" + VehicleSurface.GetDebugName() + "\"";
- return str;
- }
- [CF_EventSubscriber(ScriptCaller.Create(CF_Surface._GetAllSurfaces), CF_LifecycleEvents.OnMissionCreate)]
- static void _GetAllSurfaces()
- {
- string path = "cfgSurfaces";
- string name;
- int count = GetGame().ConfigGetChildrenCount(path);
- for (int index = 0; index < count; index++)
- {
- GetGame().ConfigGetChildName(path, index, name);
- CF_Surface.Get(name);
- }
- }
- private static int GetValueInt(string param)
- {
- string path = "CfgSurfaces" + " " + s_LastSurface + " " + param;
- if (GetGame().ConfigIsExisting(path)) return GetGame().ConfigGetInt(path);
- return 0;
- }
- private static float GetValueFloat(string param)
- {
- string path = "CfgSurfaces" + " " + s_LastSurface + " " + param;
- if (GetGame().ConfigIsExisting(path)) return GetGame().ConfigGetFloat(path);
- return 0;
- }
- private static string GetValueString(string param)
- {
- string path = "CfgSurfaces" + " " + s_LastSurface + " " + param;
- if (GetGame().ConfigIsExisting(path)) return GetGame().ConfigGetTextOut(path);
- return string.Empty;
- }
- private static CF_VehicleSurface GetValueVehicleSurface(string param)
- {
- return CF_VehicleSurface.Get(GetValueString(param));
- }
- };
- class CF_VehicleSurface
- {
- private static autoptr map<string, autoptr CF_VehicleSurface> s_VehicleSurfaces = new map<string, autoptr CF_VehicleSurface>();
- private static string s_LastSurface;
- string Name = s_LastSurface;
- float NoiseSteer = GetValueFloat("noiseSteer");
- float NoiseFrequency = GetValueFloat("noiseFrequency");
- float Roughness = GetValueFloat("roughness");
- float FrictionOffroad = GetValueFloat("frictionOffroad");
- float FrictionSlick = GetValueFloat("frictionSlick");
- float RollResistance = GetValueFloat("rollResistance");
- float RollDrag = GetValueFloat("rollDrag");
- /**
- * @brief Private constructor to prevent outside creation of the class
- */
- private void CF_VehicleSurface()
- {
- #ifdef CF_TRACE_ENABLED
- auto trace = CF_Trace_0(this);
- #endif
- s_VehicleSurfaces[s_LastSurface] = this;
- }
- /**
- * @brief Private constructor to prevent from marking as ref
- */
- private void ~CF_VehicleSurface()
- {
- #ifdef CF_TRACE_ENABLED
- auto trace = CF_Trace_0(this);
- #endif
- }
- /**
- * @brief Get the vehicle surface by the name. From 'CfgVehicleSurfaces'
- *
- * @param name The class name of the surface
- *
- * @return Instance of the vehicle surface class, creates a new one if it doesn't exist
- */
- static CF_VehicleSurface Get(string name)
- {
- #ifdef CF_TRACE_ENABLED
- auto trace = CF_Trace_1("CF_VehicleSurface").Add(name);
- #endif
- auto surf = s_VehicleSurfaces[name];
- if (!surf)
- {
- s_LastSurface = name;
- return new CF_VehicleSurface();
- }
- return surf;
- }
- /**
- * @brief Get the vehicle surface at the position in the world
- *
- * @param position The position of the surface within the world
- *
- * @return Global instance of the vehicle surface class
- */
- static CF_VehicleSurface At(vector position)
- {
- return CF_Surface.At(position).VehicleSurface;
- }
- /**
- * @brief Get the vehicle surface at the position in the world at it's maximum height
- *
- * @param x The x position of the surface within the world
- * @param z The z position of the surface within the world
- *
- * @return Global instance of the vehicle surface class
- */
- static CF_VehicleSurface At(float x, float z)
- {
- return CF_Surface.At(x, z).VehicleSurface;
- }
- /**
- * @brief Get the surface at the position in the world at it's maximum height
- *
- * @param object The object above the surface of the object
- *
- * @return Global instance of the surface class
- */
- static CF_VehicleSurface At(Object object)
- {
- string name;
- int liquidType;
- GetGame().SurfaceUnderObject(object, name, liquidType);
- return CF_Surface.Get(name).VehicleSurface;
- }
- #ifdef CF_DebugUI
- bool CF_OnDebugUpdate(CF_Debug instance, CF_DebugUI_Type type)
- {
- instance.Add("Name", Name);
- instance.Add("Noise Steer", NoiseSteer);
- instance.Add("Noise Frequency", NoiseFrequency);
- instance.Add("Roughness", Roughness);
- instance.Add("Friction Offroad", FrictionOffroad);
- instance.Add("Friction Slick", FrictionSlick);
- instance.Add("Roll Resistance", RollResistance);
- instance.Add("Roll Drag", RollDrag);
- return true;
- }
- #endif
- override string GetDebugName()
- {
- string str = this.ToString();
- str += ",\n\tName=\"" + Name + "\"";
- str += ",\n\tNoiseSteer=\"" + NoiseSteer + "\"";
- str += ",\n\tNoiseFrequency=\"" + NoiseFrequency + "\"";
- str += ",\n\tRoughness=\"" + Roughness + "\"";
- str += ",\n\tFrictionOffroad=\"" + FrictionOffroad + "\"";
- str += ",\n\tFrictionSlick=\"" + FrictionSlick + "\"";
- str += ",\n\tRollResistance=\"" + RollResistance + "\"";
- str += ",\n\tRollDrag=\"" + RollDrag + "\"";
- return str;
- }
- [CF_EventSubscriber(ScriptCaller.Create(CF_VehicleSurface._GetAllSurfaces), CF_LifecycleEvents.OnMissionCreate)]
- static void _GetAllSurfaces()
- {
- string path = "CfgVehicleSurfaces";
- string name;
- int count = GetGame().ConfigGetChildrenCount(path);
- for (int index = 0; index < count; index++)
- {
- GetGame().ConfigGetChildName(path, index, name);
- CF_VehicleSurface.Get(name);
- }
- }
- private static int GetValueInt(string param)
- {
- string path = "CfgVehicleSurfaces" + " " + s_LastSurface + " " + param;
- if (GetGame().ConfigIsExisting(path)) return GetGame().ConfigGetInt(path);
- return 0;
- }
- private static float GetValueFloat(string param)
- {
- string path = "CfgVehicleSurfaces" + " " + s_LastSurface + " " + param;
- if (GetGame().ConfigIsExisting(path)) return GetGame().ConfigGetFloat(path);
- return 0;
- }
- private static string GetValueString(string param)
- {
- string path = "CfgVehicleSurfaces" + " " + s_LastSurface + " " + param;
- if (GetGame().ConfigIsExisting(path)) return GetGame().ConfigGetTextOut(path);
- return string.Empty;
- }
- };
- class CF_WeaponStableState : WeaponStableState
- {
- bool m_CF_HasBullet;
- bool m_CF_HasMagazine;
- bool m_CF_IsJammed;
- override bool IsRepairEnabled()
- {
- return true;
- }
- override bool HasBullet()
- {
- return m_CF_HasBullet;
- }
- override bool HasMagazine()
- {
- return m_CF_HasMagazine;
- }
- override bool IsJammed()
- {
- return m_CF_IsJammed;
- }
- /**
- * @brief Prevents default validation. 'm_muzzleHasBullet' is setup in 'WeaponFSM::CF_FindBestStableState' only.
- */
- #ifndef DAYZ_1_15
- override void ValidateMuzzleArray()
- {
- return;
- }
- #endif
- };
- modded class Weapon_Base
- {
- /**
- * @brief Spawns a magazine into the weapon as an attachment or into the internal magazine. Calls 'CF_AttachMagazine' on the spawned magazine.
- *
- * @param magazineType The class type of the magazine, must inherit from Magazine_Base
- * @param quantity The amount of ammunition in the stack/magazine, -1 for max
- * @param health The normalized health value, 0 is ruined, 1 is max health
- *
- * @return True if the magazine was spawned succesfully
- */
- bool CF_SpawnMagazine(string magazineType, int quantity = -1, float health = 1)
- {
- if (!GetGame().IsKindOf(magazineType, "Magazine_Base"))
- {
- return false;
- }
- InventoryLocation location();
- Magazine_Base magazine;
- bool isMagazine = !GetGame().IsKindOf(magazineType, "Ammunition_Base");
- bool success;
- if (isMagazine)
- {
- location.SetAttachment(this, NULL, InventorySlots.MAGAZINE);
- success = Class.CastTo(magazine, SpawnEntity(magazineType, location, ECE_IN_INVENTORY, RF_DEFAULT));
- }
- else
- {
- InventoryLocation weaponLocation();
- success = GetInventory().GetCurrentInventoryLocation(weaponLocation);
- if (success)
- {
- EntityAI parent = weaponLocation.GetParent();
- if (parent && parent.GetInventory().FindFirstFreeLocationForNewEntity(magazineType, FindInventoryLocationType.CARGO, location))
- {
- success = Class.CastTo(magazine, SpawnEntity(magazineType, location, ECE_IN_INVENTORY, RF_DEFAULT));
- }
- else
- {
- success = Class.CastTo(magazine, GetGame().CreateObjectEx(magazineType, GetWorldPosition(), ECE_PLACE_ON_SURFACE));
- }
- }
- }
- if (!success)
- {
- return false;
- }
- if (quantity != -1)
- {
- magazine.ServerSetAmmoCount(quantity);
- }
- magazine.SetHealth01("", "", health);
- if (CF_AttachMagazine(magazine))
- {
- return false;
- }
- if (quantity == -1 && magazine)
- {
- if (isMagazine)
- {
- // make sure the magazine is full
- magazine.ServerSetAmmoMax();
- }
- else
- {
- // delete overfill
- GetGame().ObjectDelete(magazine);
- magazine = null; // may be delayed
- }
- }
- return true;
- }
- /**
- * @brief Attaches a magazine to the weapon, fills up the internal magazine and chamber for all muzzle points.
- *
- * @param magazine The magazine to be attached
- *
- * @return True if operation successful
- */
- bool CF_AttachMagazine(Magazine_Base magazine)
- {
- bool isMagazine = !magazine.IsInherited(Ammunition_Base);
- if (GetGame().IsDedicatedServer())
- {
- // Delete the entities from clients
- GetGame().RemoteObjectDelete(this);
- GetGame().RemoteObjectDelete(magazine);
- }
- // Magazine has to attach into the attachment slot
- if (isMagazine)
- {
- InventoryLocation srcLocation();
- magazine.GetInventory().GetCurrentInventoryLocation(srcLocation);
- InventoryLocation dstLocation();
- dstLocation.SetAttachment(this, magazine, InventorySlots.MAGAZINE);
- // If false, then the magazine is already properly attached to the desired slot
- if (!dstLocation.CompareLocationOnly(srcLocation) && !GameInventory.LocationMoveEntity(srcLocation, dstLocation))
- {
- return false;
- }
- }
- float damage;
- string ammoType;
- int ammoCount = magazine.GetAmmoCount();
- int muzzleCount = GetMuzzleCount();
- for (int muzzle = 0; muzzle < muzzleCount; muzzle++)
- {
- int internalMagazineMax = GetInternalMagazineMaxCartridgeCount(muzzle);
- while (GetInternalMagazineCartridgeCount(muzzle) < internalMagazineMax && ammoCount > 0)
- {
- ammoCount--;
- if (magazine.ServerAcquireCartridge(damage, ammoType))
- {
- PushCartridgeToInternalMagazine(muzzle, damage, ammoType);
- }
- }
- if (ammoCount > 0)
- {
- ammoCount--;
- if (magazine.ServerAcquireCartridge(damage, ammoType))
- {
- PushCartridgeToChamber(muzzle, damage, ammoType);
- ShowBullet(muzzle);
- }
- }
- }
- m_fsm.CF_FindBestStableState();
- if (GetGame().IsDedicatedServer())
- {
- GetGame().RemoteObjectCreate(this);
- // When ammoCount reaches zero the magazine is deleted
- if (magazine)
- {
- GetGame().RemoteObjectCreate(magazine);
- }
- }
- return true;
- }
- WeaponFSM CF_GetFSM()
- {
- return m_fsm;
- }
- void CF_SyncSelectionState(WeaponStableState state)
- {
- int muzzleCount = state.m_muzzleHasBullet.Count();
- for (int muzzle = 0; muzzle < muzzleCount; muzzle++)
- {
- if (state.m_muzzleHasBullet[muzzle] != MuzzleState.E)
- {
- ShowBullet(muzzle);
- }
- else
- {
- HideBullet(muzzle);
- }
- }
- if (state.HasMagazine())
- {
- ShowMagazine();
- }
- else
- {
- HideMagazine();
- }
- }
- };
- modded class WeaponFSM
- {
- /**
- * @brief Finds the best stable state that matches the weapon.
- *
- * @return True if the repair was successful
- */
- bool CF_FindBestStableState()
- {
- // Only repair stable states
- WeaponStableState state = WeaponStableState.Cast(m_State);
- if (!state || !state.IsRepairEnabled())
- {
- return false;
- }
- // Make sure a weapon is assigned
- Weapon_Base weapon = state.m_weapon;
- if (!weapon)
- {
- return false;
- }
- CF_WeaponStableState comparingState = new CF_WeaponStableState();
- comparingState.m_muzzleHasBullet.Clear();
- int muzzleCount = weapon.GetMuzzleCount();
- for (int muzzle = 0; muzzle < muzzleCount; muzzle++)
- {
- bool magazine = weapon.GetMagazine(muzzle) != null;
- bool jammed = weapon.IsChamberJammed(muzzle);
- bool empty = weapon.IsChamberEmpty(muzzle);
- bool firedOut = weapon.IsChamberFiredOut(muzzle);
- bool loaded = !empty && !firedOut;
- if (loaded)
- {
- comparingState.m_muzzleHasBullet.Insert(MuzzleState.L);
- }
- else if (empty)
- {
- comparingState.m_muzzleHasBullet.Insert(MuzzleState.E);
- }
- else if (firedOut)
- {
- comparingState.m_muzzleHasBullet.Insert(MuzzleState.F);
- }
- comparingState.m_CF_HasMagazine |= magazine;
- comparingState.m_CF_HasBullet |= !empty;
- comparingState.m_CF_IsJammed |= jammed;
- }
- int count = m_Transitions.Count();
- for (int i = 0; i < count; ++i)
- {
- WeaponStableState srcState;
- if (!Class.CastTo(srcState, m_Transitions[i].m_srcState))
- {
- continue;
- }
- if (!srcState.CF_Equals(comparingState))
- {
- continue;
- }
- Terminate();
- m_State = srcState;
- Start(null, true);
- weapon.CF_SyncSelectionState(srcState);
- srcState.SyncAnimState();
- return true;
- }
- return false;
- }
- };
- modded class WeaponStableState
- {
- bool CF_Equals(WeaponStableState other)
- {
- if (IsRepairEnabled() != other.IsRepairEnabled())
- {
- return false;
- }
- if (HasBullet() != other.HasBullet())
- {
- return false;
- }
- if (HasMagazine() != other.HasMagazine())
- {
- return false;
- }
- if (IsJammed() != other.IsJammed())
- {
- return false;
- }
- int muzzleCount = m_muzzleHasBullet.Count();
- if (muzzleCount != other.m_muzzleHasBullet.Count())
- {
- return false;
- }
- for (int muzzle = 0; muzzle < muzzleCount; muzzle++)
- {
- if (m_muzzleHasBullet[muzzle] != other.m_muzzleHasBullet[muzzle])
- {
- return false;
- }
- }
- return true;
- }
- };
- modded class KeybindingElement
- {
- bool R_WasSet
- string R_DisplayName;
- override void Reload()
- {
- super.Reload();
- if ( R_WasSet )
- {
- m_ElementName.SetText( R_DisplayName );
- }
- }
- }modded class KeybindingsGroup
- {
- void KeybindingsGroup( int index, Input input, Widget parent, KeybindingsMenu menu )
- {
- Widget subgroup = m_Root.FindAnyWidget( "group_content" );
- TIntArray actions = new TIntArray;
- GetUApi().GetActiveInputs( actions );
- for( int i = 0; i < ModLoader.GetMods().Count(); i++ )
- {
- ModStructure mod = ModLoader.GetMods().Get( i );
- bool display = GetGame().ConfigIsExisting( mod.GetModPath() + " inputs" );
- TIntArray tempActions = new TIntArray;
- AddCFSubgroup( subgroup, input, mod, display, actions, tempActions );
- actions.Clear();
- actions.Copy( tempActions );
- }
- AddDayZSubgroup( subgroup, input, actions );
- subgroup.Update();
- m_Root.SetHandler( this );
- }
- void AddCFAction( int index, Widget parent, Input input, string displayName )
- {
- KeybindingElement ele = new KeybindingElement( index, parent, this );
- ele.R_WasSet = true;
- ele.R_DisplayName = displayName;
- ele.Reload();
- m_KeyWidgets.Insert( index, ele );
- }
- override void AddSubgroup( /*int index, */Widget parent, Input input )
- {
- // does nothing
- }
- void AddCFSubgroup( Widget parent, Input input, ModStructure mod, bool display, TIntArray inActions, out TIntArray remainingActions )
- {
- Widget subgroup_content;
- if ( display )
- {
- Widget subgroup = GetGame().GetWorkspace().CreateWidgets( "JM/CF/GUI/layouts/keybinding_subgroup.layout", parent );
- TextWidget subgroup_name = TextWidget.Cast( subgroup.FindAnyWidget( "subgroup_text" ) );
- string modDisplayName = "";
- GetGame().ConfigGetText( mod.GetModPath() + " name", modDisplayName );
- subgroup_name.SetText( modDisplayName );
- subgroup_content = subgroup.FindAnyWidget( "subgroup_content" );
- }
- for ( int i = 0; i < inActions.Count(); i++ )
- {
- string displayName = "";
- bool found = false;
- for ( int j = 0; j < mod.GetModInputs().Count(); j++ )
- {
- int id = GetUApi().GetInputByName( mod.GetModInputs()[j].Name ).ID();
- if ( id == inActions[i] )
- {
- displayName = Widget.TranslateString( "#" + mod.GetModInputs()[j].Localization );
- int hashSymbol = displayName.IndexOf( " " );
- if ( hashSymbol < 1 )
- {
- displayName = mod.GetModInputs()[j].Localization;
- }
- found = true;
- }
- }
- if ( found )
- {
- if ( display )
- {
- AddCFAction( inActions.Get( i ), subgroup_content, input, displayName );
- }
- } else
- {
- remainingActions.Insert( inActions.Get( i ) );
- }
- }
- if ( display )
- {
- subgroup_content.Update();
- }
- }
- void AddDayZSubgroup( Widget parent, Input input, TIntArray inActions )
- {
- Widget subgroup = GetGame().GetWorkspace().CreateWidgets( "JM/CF/GUI/layouts/keybinding_subgroup.layout", parent );
- TextWidget subgroup_name = TextWidget.Cast( subgroup.FindAnyWidget( "subgroup_text" ) );
- subgroup_name.SetText( "DayZ Standalone" );
- Widget subgroup_content = subgroup.FindAnyWidget( "subgroup_content" );
- for( int i = 0; i < inActions.Count(); i++ )
- {
- AddAction( inActions.Get( i ), subgroup_content, input );
- }
- subgroup_content.Update();
- }
- }modded class MissionBase
- {
- void MissionBase()
- {
- #ifdef CF_TRACE_ENABLED
- auto trace = CF_Trace_0(this);
- #endif
- CF_LifecycleEvents.OnMissionCreate.Invoke(this, CF_EventArgs.Empty);
- }
- void ~MissionBase()
- {
- #ifdef CF_TRACE_ENABLED
- auto trace = CF_Trace_0(this);
- #endif
- CF_LifecycleEvents.OnMissionDestroy.Invoke(this, CF_EventArgs.Empty);
- }
- };
- modded class MissionBase
- {
- protected bool m_bLoaded = false;
- void MissionBase()
- {
- CF_ModuleGameManager.UpdateGameFlag();
- // Deprecated
- if (!ModuleManagerExists())
- {
- CreateModuleManager(new JMModuleConstructor());
- }
- }
- void OnMissionLoaded()
- {
- }
- void CF_OnUpdate(float timeslice)
- {
- if (g_Game.IsLoading())
- {
- return;
- }
- if (!m_bLoaded)
- {
- m_bLoaded = true;
- OnMissionLoaded();
- }
- CF_ModuleGameManager.OnUpdate(this, new CF_EventUpdateArgs(timeslice));
- }
- };
- modded class MissionGameplay
- {
- override void OnMissionStart()
- {
- super.OnMissionStart();
- CF_ModuleCoreManager.OnSettingsChanged(this, CF_EventArgs.Empty);
- CF_ModuleCoreManager.OnMissionStart(this, CF_EventArgs.Empty);
- }
- override void OnMissionFinish()
- {
- super.OnMissionFinish();
- CF_ModuleCoreManager.OnMissionFinish(this, CF_EventArgs.Empty);
- }
- override void OnMissionLoaded()
- {
- super.OnMissionLoaded();
- CF_ModuleCoreManager.OnMissionLoaded(this, CF_EventArgs.Empty);
- }
- override void OnUpdate( float timeslice )
- {
- CF_OnUpdate(timeslice);
- super.OnUpdate( timeslice );
- }
- };
- modded class MissionServer
- {
- void MissionServer()
- {
- GetRPCManager().AddRPC( "CF", "RecieveModList", this, SingeplayerExecutionType.Server );
- }
- override void OnEvent( EventType eventTypeId, Param params )
- {
- super.OnEvent( eventTypeId, params );
- switch( eventTypeId )
- {
- case LogoutCancelEventTypeID:
- LogoutCancelEventParams logoutCancelParams;
- Class.CastTo( logoutCancelParams, params );
- auto logoutCancelArgs = new CF_EventPlayerArgs();
- Class.CastTo(logoutCancelArgs.Player, logoutCancelParams.param1);
- CF_ModuleWorldManager.OnClientLogoutCancelled(this, logoutCancelArgs);
- break;
- }
- }
- override void OnInit()
- {
- super.OnInit();
- }
- override void OnMissionStart()
- {
- super.OnMissionStart();
- CF_ModuleCoreManager.OnSettingsChanged(this, CF_EventArgs.Empty);
- CF_ModuleCoreManager.OnMissionStart(this, CF_EventArgs.Empty);
- }
- override void OnMissionFinish()
- {
- super.OnMissionFinish();
- CF_ModuleCoreManager.OnMissionFinish(this, CF_EventArgs.Empty);
- }
- override void OnMissionLoaded()
- {
- super.OnMissionLoaded();
- CF_ModuleCoreManager.OnMissionLoaded(this, CF_EventArgs.Empty);
- }
- override void OnUpdate( float timeslice )
- {
- CF_OnUpdate(timeslice);
- super.OnUpdate( timeslice );
- }
- override void InvokeOnConnect(PlayerBase player, PlayerIdentity identity)
- {
- super.InvokeOnConnect( player, identity );
- CF_ModuleWorldManager.OnInvokeConnect(this, new CF_EventPlayerArgs(player, identity));
- }
- override void InvokeOnDisconnect( PlayerBase player )
- {
- super.InvokeOnDisconnect( player );
- CF_ModuleWorldManager.OnInvokeDisconnect(this, new CF_EventPlayerArgs(player));
- }
- override void OnClientReadyEvent( PlayerIdentity identity, PlayerBase player )
- {
- super.OnClientReadyEvent( identity, player );
- CF_ModuleWorldManager.OnClientReady(this, new CF_EventPlayerArgs(player, identity));
- }
- override void OnClientReconnectEvent( PlayerIdentity identity, PlayerBase player )
- {
- super.OnClientReconnectEvent( identity, player );
- CF_ModuleWorldManager.OnClientReconnect(this, new CF_EventPlayerArgs(player, identity));
- }
- override void OnClientRespawnEvent( PlayerIdentity identity, PlayerBase player )
- {
- super.OnClientRespawnEvent( identity, player );
- CF_ModuleWorldManager.OnClientRespawn(this, new CF_EventPlayerArgs(player, identity));
- }
- override void OnClientDisconnectedEvent( PlayerIdentity identity, PlayerBase player, int logoutTime, bool authFailed )
- {
- super.OnClientDisconnectedEvent( identity, player, logoutTime, authFailed );
- auto args = new CF_EventPlayerDisconnectedArgs(player, identity);
- args.LogoutTime = logoutTime;
- args.AuthFailed = authFailed;
- CF_ModuleWorldManager.OnClientLogout(this, args);
- }
- override void PlayerDisconnected( PlayerBase player, PlayerIdentity identity, string uid )
- {
- auto args = new CF_EventPlayerDisconnectedArgs(player, identity);
- args.UID = uid;
- // must call before vanilla
- CF_ModuleWorldManager.OnClientDisconnect(this, args);
- super.PlayerDisconnected( player, identity, uid );
- }
- override PlayerBase OnClientNewEvent( PlayerIdentity identity, vector pos, ParamsReadContext ctx )
- {
- PlayerBase player = super.OnClientNewEvent( identity, pos, ctx );
- auto args = new CF_EventNewPlayerArgs(player, identity, pos, ctx);
- CF_ModuleWorldManager.OnClientNew(this, args);
- //TODO: allow the args to override these 'out' variables again, 'CF_ModuleWorldManager.OnClientNew' deletes 'args' before this can be used
- //player = args.Player;
- return player;
- }
- override void OnClientPrepareEvent( PlayerIdentity identity, out bool useDB, out vector pos, out float yaw, out int preloadTimeout )
- {
- auto args = new CF_EventPlayerPrepareArgs();
- args.Identity = identity;
- args.UseDatabase = useDB;
- args.Position = pos;
- args.Yaw = yaw;
- args.PreloadTimeout = preloadTimeout;
- CF_ModuleWorldManager.OnClientPrepare(this, args);
- //TODO: allow the args to override these 'out' variables again, 'CF_ModuleWorldManager.OnClientPrepare' deletes 'args' before this can be used
- //useDB = args.UseDatabase;
- //pos = args.Position;
- //yaw = args.Yaw;
- //preloadTimeout = args.PreloadTimeout;
- // must call module code before vanilla
- super.OnClientPrepareEvent(identity, useDB, pos, yaw, preloadTimeout);
- }
- };
- /**
- * @class JMModuleConstructor
- *
- * @deprecated
- */
- class JMModuleConstructor : JMModuleConstructorBase
- {
- };
- raP Z CfgPatches 3 CfgMods ” Z JM_CF_Scripts L ” units weapons requiredVersion ÍÌÌ=requiredAddons DZ_Data ” JM_CommunityFramework µ Z dir JM/CF picture action hideName hidePicture name Community Framework credits Jacob_Mango, Arkensor creditsJson JM/CF/Scripts/Data/Credits.json version 0.0.0 versionPath JM/CF/scripts/Data/Version.hpp author Jacob_Mango authorID 76561198103677868 extra type mod defines
- CF_MODULE_CONFIG CF_EXPRESSION CF_TRACE_STACK_NAME_ASSUMPTION_FIX CF_GHOSTICONS CF_MODSTORAGE_DISABLE CF_MODSTORAGE_MODULE_DISABLE CF_SURFACES CF_MODULES CF_REF_FIX CF_BUGFIX_REF dependencies Core Game World Mission defs è Z engineScriptModule e gameLibScriptModule ’ gameScriptModule  worldScriptModule ü missionScriptModule * Z value files JM/CF/Scripts/1_Core ’ value files JM/CF/Scripts/2_GameLib  value CF_CreateGame files JM/CF/Scripts/3_Game ü value files JM/CF/Scripts/4_World * value files JM/CF/Scripts/5_Mission Z [WorkbenchPluginAttribute("Build Mod", "Builds current mod", "F3", "", {"ResourceManager", "ScriptEditor"})]
- class BuildMod: DayZProjectManager
- {
- override void Run()
- {
- RunDayZBatList({
- string.Format("P:\\%1\\Workbench\\Batchfiles\\Exit.bat", ModName),
- string.Format("P:\\%1\\Workbench\\Batchfiles\\ZBinarizeDeploy.bat", ModName)
- });
- }
- }
- [WorkbenchPluginAttribute("Edit Project", "Edit Project", "", "", {"ResourceManager", "ScriptEditor"})]
- class DayZProjectManager: DayZTool
- {
- [Attribute("", "editbox")]
- string ModName = "JM\\CF";
- override void Run()
- {
- Workbench.ScriptDialog("Edit Project Settings", "", this);
- }
- override void RunDayZBat(string filepath, bool wait = false)
- {
- if (filepath.Length() < 2) return;
- filepath.Replace("\\", "/");
- if (filepath[1] != ":")
- {
- string cwd;
- Workbench.GetCwd(cwd);
- filepath = cwd + "/" + filepath;
- }
- int index = filepath.IndexOf("/");
- int last_index = index;
- while(index != -1)
- {
- last_index = index;
- index = filepath.IndexOfFrom(last_index + 1, "/");
- }
- if (last_index == -1) return;
- string path = filepath.Substring(0, last_index);
- string bat = filepath.Substring(last_index + 1, filepath.Length() - last_index - 1);
- Print("cmd /c \"chdir /D " + path + " & call " + bat + "\"");
- Workbench.RunCmd("cmd /c \"chdir /D " + path + " & call " + bat + "\"", wait);
- }
- void RunDayZBatList(array<string> filepaths)
- {
- foreach (string file: filepaths) {
- RunDayZBat(file, true);
- }
- }
- }
- [WorkbenchPluginAttribute("Launch Client", "Launches the game", "F8", "", {"ResourceManager", "ScriptEditor"})]
- class LaunchClientModTool: DayZProjectManager
- {
- override void Run()
- {
- RunDayZBat(string.Format("P:\\%1\\Workbench\\Batchfiles\\LaunchClient.bat", ModName), true);
- }
- }
- [WorkbenchPluginAttribute("Launch Local MP", "Launches the server and client, automatically joins", "F6", "", {"ResourceManager", "ScriptEditor"})]
- class LaunchLocalMPModTool: DayZProjectManager
- {
- override void Run()
- {
- RunDayZBat(string.Format("P:\\%1\\Workbench\\Batchfiles\\LaunchLocalMP.bat", ModName), true);
- }
- }
- [WorkbenchPluginAttribute("Launch Offline", "Launches the game in offline mode", "F5", "", {"ResourceManager", "ScriptEditor"})]
- class LaunchOfflineModTool: DayZProjectManager
- {
- override void Run()
- {
- RunDayZBat(string.Format("P:\\%1\\Workbench\\Batchfiles\\LaunchOffline.bat", ModName), true);
- }
- }
- [WorkbenchPluginAttribute("Launch Client", "Launches the game", "F9", "", {"ResourceManager", "ScriptEditor"})]
- class LaunchServerModTool: DayZProjectManager
- {
- override void Run()
- {
- RunDayZBat(string.Format("P:\\%1\\Workbench\\Batchfiles\\LaunchServer.bat", ModName), true);
- }
- }
- [WorkbenchPluginAttribute("Open Log Files", "Opens logfiles in NPP", "F4", "", {"ResourceManager", "ScriptEditor"})]
- class OpenLogFiles: DayZProjectManager
- {
- override void Run()
- {
- RunDayZBat(string.Format("P:\\%1\\Workbench\\Batchfiles\\OpenLogs.bat", ModName), true);
- }
- }class PluginErrorMessage
- {
- static int Show(string message)
- {
- PluginErrorMessage msg();
- return Workbench.ScriptDialog("Error", message, msg);
- }
- [ButtonAttribute("Ok")]
- void Ok()
- {
- }
- }
- S¼Öâò¥aj@æ”du¢°F¹•‘
Add Comment
Please, Sign In to add comment