From fab8a1e982c7617e3dd4469804f9fe55c0003d4a Mon Sep 17 00:00:00 2001 From: Jett <55758076+Jettford@users.noreply.github.com> Date: Sun, 17 Jul 2022 07:54:36 +0100 Subject: [PATCH 01/86] Implement new chat features --- CMakeLists.txt | 9 ++-- dChatFilter/dChatFilter.cpp | 65 +++++++++++++++++++---------- dChatFilter/dChatFilter.h | 15 +++---- dGame/dComponents/PetComponent.cpp | 2 +- dNet/ClientPackets.cpp | 15 ++++++- dNet/WorldPackets.cpp | 23 +++++----- resources/blacklist.dcf | Bin 0 -> 16160 bytes 7 files changed, 84 insertions(+), 45 deletions(-) create mode 100644 resources/blacklist.dcf diff --git a/CMakeLists.txt b/CMakeLists.txt index 0817412b..caa61e4e 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -84,13 +84,14 @@ make_directory(${CMAKE_BINARY_DIR}/locale) make_directory(${CMAKE_BINARY_DIR}/logs) # Copy ini files on first build -set(INI_FILES "authconfig.ini" "chatconfig.ini" "worldconfig.ini" "masterconfig.ini") -foreach(ini ${INI_FILES}) - if (NOT EXISTS ${PROJECT_BINARY_DIR}/${ini}) +set(RESOURCE_FILES "authconfig.ini" "chatconfig.ini" "worldconfig.ini" "masterconfig.ini" "blacklist.dcf") +foreach(resource_file ${RESOURCE_FILES}) + if (NOT EXISTS ${PROJECT_BINARY_DIR}/${resource_file}) configure_file( - ${CMAKE_SOURCE_DIR}/resources/${ini} ${PROJECT_BINARY_DIR}/${ini} + ${CMAKE_SOURCE_DIR}/resources/${resource_file} ${PROJECT_BINARY_DIR}/${resource_file} COPYONLY ) + message("Moved ${resource_file} to project binary directory") endif() endforeach() diff --git a/dChatFilter/dChatFilter.cpp b/dChatFilter/dChatFilter.cpp index 7f8187a5..fe8a0d10 100644 --- a/dChatFilter/dChatFilter.cpp +++ b/dChatFilter/dChatFilter.cpp @@ -8,8 +8,9 @@ #include #include "dCommonVars.h" -#include "Database.h" #include "dLogger.h" +#include "dConfig.h" +#include "Database.h" #include "Game.h" using namespace dChatFilterDCF; @@ -21,25 +22,30 @@ dChatFilter::dChatFilter(const std::string& filepath, bool dontGenerateDCF) { ReadWordlistPlaintext(filepath + ".txt"); if (!m_DontGenerateDCF) ExportWordlistToDCF(filepath + ".dcf"); } - else if (!ReadWordlistDCF(filepath + ".dcf")) { + else if (!ReadWordlistDCF(filepath + ".dcf", true)) { ReadWordlistPlaintext(filepath + ".txt"); ExportWordlistToDCF(filepath + ".dcf"); } + if (BinaryIO::DoesFileExist("blacklist.dcf")) { + ReadWordlistDCF("blacklist.dcf", false); + } + //Read player names that are ok as well: auto stmt = Database::CreatePreppedStmt("select name from charinfo;"); auto res = stmt->executeQuery(); while (res->next()) { std::string line = res->getString(1).c_str(); std::transform(line.begin(), line.end(), line.begin(), ::tolower); //Transform to lowercase - m_Words.push_back(CalculateHash(line)); + m_YesYesWords.push_back(CalculateHash(line)); } delete res; delete stmt; } dChatFilter::~dChatFilter() { - m_Words.clear(); + m_YesYesWords.clear(); + m_NoNoWords.clear(); } void dChatFilter::ReadWordlistPlaintext(const std::string& filepath) { @@ -49,12 +55,12 @@ void dChatFilter::ReadWordlistPlaintext(const std::string& filepath) { while (std::getline(file, line)) { line.erase(std::remove(line.begin(), line.end(), '\r'), line.end()); std::transform(line.begin(), line.end(), line.begin(), ::tolower); //Transform to lowercase - m_Words.push_back(CalculateHash(line)); + m_YesYesWords.push_back(CalculateHash(line)); } } } -bool dChatFilter::ReadWordlistDCF(const std::string& filepath) { +bool dChatFilter::ReadWordlistDCF(const std::string& filepath, bool whiteList) { std::ifstream file(filepath, std::ios::binary); if (file) { fileHeader hdr; @@ -67,12 +73,14 @@ bool dChatFilter::ReadWordlistDCF(const std::string& filepath) { if (hdr.formatVersion == formatVersion) { size_t wordsToRead = 0; BinaryIO::BinaryRead(file, wordsToRead); - m_Words.reserve(wordsToRead); + if (whiteList) m_YesYesWords.reserve(wordsToRead); + else m_NoNoWords.reserve(wordsToRead); size_t word = 0; for (size_t i = 0; i < wordsToRead; ++i) { BinaryIO::BinaryRead(file, word); - m_Words.push_back(word); + if (whiteList) m_YesYesWords.push_back(word); + else m_NoNoWords.push_back(word); } return true; @@ -91,9 +99,9 @@ void dChatFilter::ExportWordlistToDCF(const std::string& filepath) { if (file) { BinaryIO::BinaryWrite(file, uint32_t(dChatFilterDCF::header)); BinaryIO::BinaryWrite(file, uint32_t(dChatFilterDCF::formatVersion)); - BinaryIO::BinaryWrite(file, size_t(m_Words.size())); + BinaryIO::BinaryWrite(file, size_t(m_YesYesWords.size())); - for (size_t word : m_Words) { + for (size_t word : m_YesYesWords) { BinaryIO::BinaryWrite(file, word); } @@ -101,31 +109,44 @@ void dChatFilter::ExportWordlistToDCF(const std::string& filepath) { } } -bool dChatFilter::IsSentenceOkay(const std::string& message, int gmLevel) { - if (gmLevel > GAME_MASTER_LEVEL_FORUM_MODERATOR) return true; //If anything but a forum mod, return true. - if (message.empty()) return true; +std::vector dChatFilter::IsSentenceOkay(const std::string& message, int gmLevel, bool whiteList) { + if (gmLevel > GAME_MASTER_LEVEL_FORUM_MODERATOR) return { }; //If anything but a forum mod, return true. + if (message.empty()) return { }; + if (!whiteList && m_NoNoWords.empty()) return { "" }; std::stringstream sMessage(message); std::string segment; std::regex reg("(!*|\\?*|\\;*|\\.*|\\,*)"); + std::vector listOfBadSegments = std::vector(); + while (std::getline(sMessage, segment, ' ')) { + std::string originalSegment = segment; + std::transform(segment.begin(), segment.end(), segment.begin(), ::tolower); //Transform to lowercase segment = std::regex_replace(segment, reg, ""); size_t hash = CalculateHash(segment); if (std::find(m_UserUnapprovedWordCache.begin(), m_UserUnapprovedWordCache.end(), hash) != m_UserUnapprovedWordCache.end()) { - return false; + listOfBadSegments.push_back(originalSegment); // found word that isn't ok, just deny this code works for both white and black list } - if (!IsInWordlist(hash)) { - m_UserUnapprovedWordCache.push_back(hash); - return false; + if (!IsInWordlist(hash, whiteList)) { + if (whiteList) { + m_UserUnapprovedWordCache.push_back(hash); + listOfBadSegments.push_back(originalSegment); + } + } + else { + if (!whiteList) { + m_UserUnapprovedWordCache.push_back(hash); + listOfBadSegments.push_back(originalSegment); + } } } - return true; + return listOfBadSegments; } size_t dChatFilter::CalculateHash(const std::string& word) { @@ -136,6 +157,8 @@ size_t dChatFilter::CalculateHash(const std::string& word) { return value; } -bool dChatFilter::IsInWordlist(size_t word) { - return std::find(m_Words.begin(), m_Words.end(), word) != m_Words.end(); -} +bool dChatFilter::IsInWordlist(size_t word, bool whiteList) { + auto* list = whiteList ? &m_YesYesWords : &m_NoNoWords; + + return std::find(list->begin(), list->end(), word) != list->end(); +} \ No newline at end of file diff --git a/dChatFilter/dChatFilter.h b/dChatFilter/dChatFilter.h index e8ae67d0..5acd6063 100644 --- a/dChatFilter/dChatFilter.h +++ b/dChatFilter/dChatFilter.h @@ -20,17 +20,18 @@ public: dChatFilter(const std::string& filepath, bool dontGenerateDCF); ~dChatFilter(); - void ReadWordlistPlaintext(const std::string & filepath); - bool ReadWordlistDCF(const std::string & filepath); - void ExportWordlistToDCF(const std::string & filepath); - bool IsSentenceOkay(const std::string& message, int gmLevel); + void ReadWordlistPlaintext(const std::string& filepath); + bool ReadWordlistDCF(const std::string& filepath, bool whiteList); + void ExportWordlistToDCF(const std::string& filepath); + std::vector IsSentenceOkay(const std::string& message, int gmLevel, bool whiteList = true); private: bool m_DontGenerateDCF; - std::vector m_Words; + std::vector m_NoNoWords; + std::vector m_YesYesWords; std::vector m_UserUnapprovedWordCache; //Private functions: size_t CalculateHash(const std::string& word); - bool IsInWordlist(size_t word); -}; + bool IsInWordlist(size_t word, bool whiteList); +}; \ No newline at end of file diff --git a/dGame/dComponents/PetComponent.cpp b/dGame/dComponents/PetComponent.cpp index d54087aa..3cfb4e8d 100644 --- a/dGame/dComponents/PetComponent.cpp +++ b/dGame/dComponents/PetComponent.cpp @@ -1193,7 +1193,7 @@ void PetComponent::SetPetNameForModeration(const std::string& petName) { int approved = 1; //default, in mod //Make sure that the name isn't already auto-approved: - if (Game::chatFilter->IsSentenceOkay(petName, 0)) { + if (Game::chatFilter->IsSentenceOkay(petName, 0).empty()) { approved = 2; //approved } diff --git a/dNet/ClientPackets.cpp b/dNet/ClientPackets.cpp index ef5b68ef..187ee12f 100644 --- a/dNet/ClientPackets.cpp +++ b/dNet/ClientPackets.cpp @@ -276,6 +276,7 @@ void ClientPackets::HandleChatModerationRequest(const SystemAddress& sysAddr, Pa std::string message = ""; stream.Read(chatLevel); + printf("%d", chatLevel); stream.Read(requestID); for (uint32_t i = 0; i < 42; ++i) { @@ -292,9 +293,19 @@ void ClientPackets::HandleChatModerationRequest(const SystemAddress& sysAddr, Pa } std::unordered_map unacceptedItems; - bool bAllClean = Game::chatFilter->IsSentenceOkay(message, user->GetLastUsedChar()->GetGMLevel()); + std::vector segments = Game::chatFilter->IsSentenceOkay(message, entity->GetGMLevel()); + + bool bAllClean = segments.empty(); + if (!bAllClean) { - unacceptedItems.insert(std::make_pair((char)0, (char)message.length())); + for (const auto& item : segments) { + if (item == "") { + unacceptedItems.insert({ (char)0, (char)message.length()}); + break; + } + + unacceptedItems.insert({ message.find(item), item.length() }); + } } if (user->GetIsMuted()) { diff --git a/dNet/WorldPackets.cpp b/dNet/WorldPackets.cpp index ae8f71a4..94792c91 100644 --- a/dNet/WorldPackets.cpp +++ b/dNet/WorldPackets.cpp @@ -192,19 +192,22 @@ void WorldPackets::SendChatModerationResponse(const SystemAddress& sysAddr, bool CBITSTREAM PacketUtils::WriteHeader(bitStream, CLIENT, MSG_CLIENT_CHAT_MODERATION_STRING); - bitStream.Write(static_cast(requestAccepted)); - bitStream.Write(static_cast(0)); - bitStream.Write(static_cast(requestID)); - bitStream.Write(static_cast(0)); + bitStream.Write(unacceptedItems.empty()); // Is sentence ok? + bitStream.Write(0x16); // Source ID, unknown - for (uint32_t i = 0; i < 33; ++i) { - bitStream.Write(static_cast(receiver[i])); + bitStream.Write(static_cast(requestID)); // request ID + bitStream.Write(static_cast(0)); // chat mode + + PacketUtils::WritePacketWString(receiver, 42, &bitStream); // receiver name + + for (auto it : unacceptedItems) { + bitStream.Write(it.first); // start index + bitStream.Write(it.second); // length } - for (std::unordered_map::iterator it = unacceptedItems.begin(); it != unacceptedItems.end(); ++it) { - bitStream.Write(it->first); - bitStream.Write(it->second); - } + for (int i = unacceptedItems.size(); 64 > i; i++) { + bitStream.Write(0); + } SEND_PACKET } diff --git a/resources/blacklist.dcf b/resources/blacklist.dcf new file mode 100644 index 0000000000000000000000000000000000000000..cdc64c2f5b245f4526974ab9cb1770fd8355b783 GIT binary patch literal 16160 zcmb8WQ*@ng+^rqkwyh>jnxsL4#)`&)c}=08B7$HbARxQY|MT@fpElkFH(YVzllBzTzeX_kifo?`EU;^FVlctFCR;Gt zVO*!NUR^kIRvaVO41_6+xzcPAR zI#^)SH38|@5H3U9xz%`P$Lw}BTEL+2xWxKVrYHRKYWIzS>kmVV^A?N%XRcP^;!i`I zvsPEa#fs35lm0ncQoploec61(zBGPt$yy_BB+&IC53NPMzg^zTd}SO4EHZ zjF{6jaIFXqQCJ|64;|3G@eqBj1NdTyy{SD+djC`g>uWglue-&yBe?MAbC!+;#Cx|C z6?W>qUjJwn=fWzHQOfFe8a)v%>=nQ(tw{)gc`Y#$9{h&0c}UOEzuD^BSoY~djX>DV zD8nRb{1WNw=SQfdnKKN9qy@+4$OXFl2o=(d@$PtXKaNervM(D%U{gxq2#$Lfptdo+ z&So+wFDpxKfGu`glWF4S#J6Y{5O0V|C|vzkd~FPgT|BC4WMjsFND_k-U|_y3po8i$ z!?qXu;~Jd;VBL4$g7+W_u$zi;krq7SKWQELFf<70!Ve+l3oaC-HMQ&|5L3$Cvh;5E z@e(zO6_zeT8Fn+?yDXPKG?9Cmg<5Y8sK1g$A?>tX-}Orw zeJ~#uwltVL+4b$BMHE7 z3OgaWj*=3#-BP&JuD6mm{S}eryCe?7_ABpFD?(YyUs-tS65;p<h8} zuIy3W84<*hXyDkGp0_!=1k93-znu#{=~uKeYTlB*ctLMn9ga^r6cGk6&S^vfT61um zxqF+)yUXzv299U>tx{sFemWS}ziN%iKF(mx$sN*53taJR<2a@|XCcdk3_ckbZ73nm zYg(f$j={+a_jM^4aob%b$JcA1^8yN1qD}3jH~8nEd4#sPCLxU`FAZn>;SZ5;O>M=y z9PB4;-=P}#_7Uj}rgRr$e2e1Ue72UnJKtzIEo@K&wsz@Y<>iCb1P;)?AN-ot_E4E1 zW(a4wB;arQX(0vv!sZs)8xO^rTb|IZtsJFf8xs9Vc*cjo_T<50elP@O;un zkvDeDI5>j?tSK7h7H-2_Ioc*Ns0;kd7#m>-7gYjIZD{0}b8_sRk0ZWDe@wh*HH&el zWzPtoX=ceI3hKVxI3EU0gsf){9kma#rh7D~ua7YS+%lE1GhTDFJ{>-~ccv#H12c$T z$s`7(XWEytr8}R7f_4zPZDrgQ0P~TX2KXIcWXM^PMWWw{({|%@r?&-q`P`+V0#TZ? z$E(^fiWpQ-sfjBQf_%;_UbBOuvr(H0Yx#4mpNg8>XC<0wz}x2EVL`?o0`ut7vyPtm zZb-_}S{#43gQGAp8JG}xXatNCwi55d9MZeSxm}K@XTpZ_!71mv&e5w%iexFp{!~P+ zmm}Xf;C;T2Q`MQqLFZQISKxhaWoFr6V{KvF*b!}4Sytbud*y&3K?Il|%-C;E$(Ia} zN@IE8R$!%Lb*|AEGvYWYo9ILz5)bOHi^HX z@bcTwWRU@AY?O$bRZ6JQNHYU*S^d-v~_Dcmn-jD#9`;VJ*QOSp__;Vr_HCO~nH z!LR>Q{lI&nYR(z#s1`0LoBRj?I{~)ZC1MCx!z!EVApg+HGiQ6{z6KWF<%X(OY-=w| z4cQP;8kcvT7q@~gd7PT$`;*ifC9}pQx8VWV=WSoBsKRbIuV4H}qUQbrODx71A8zjN zAdNb5#<~Xbt-9&OkjyK&m}EB?$ib@>JPcuzM6TF_x%5<5fyyKk2(4u)m{>xOUFG$2 z-ek?aS??!EK3BG77%oUb*G-m?>ScOUCBk>k)0s^ltV_xMvi~!5W{~YBbVG6uXvOVI@bTEk&V>e~vpmpu zy0m2x-N%E!EB<*<)hjeS)Q=i<6SvLWV9<;EX zjh%=<>CmRjOM19|N-`WAtmrgRUKQI~nCM#z`A3@2`x9ms=<`C(0i14`mLk)+YR^af zO)VpN3bA|uYwQ!}lwodc2Cq2PeVbLXYhSb&9u2TZ0#W4>$;!OKedNHz?omGD5Pf(} zgs_{l=rRZrFF@Kxe^(7YWqOzydyCAw%LC3)YIKBLpdABXlvA}$N`Hb`7TATNCpDPy z?1b80Eyk)R-}KIic?Vs&%e~`35QLFNqtDUZQX60Iry}dg589a?fViMl6V87MrL_J| z`Un#25p#C4m25TUne%>Iw&+knhhD_7dQfJnHm((hy7NxyaJndxy74(q+kX!@z@<1Y z_@o`D5UV8bwN|OhpVV)+Ed=OETJfT37Ox5rJv*yEkIZ@9{~%(|_>2AOVzR zG_C)})&KC7o8?)lb9cliDM)5RuM>G&;5+o|@XJPJ!w(Z0YGR+R@nn%h3@X>1&Mp_D zuE&vth?=#X=ExTrX2Y(0Zyz@z&YxT7`5mn20f-$!O480EbTwEdCriU~#a3+%lo&EH zPS`RNKPKzssp3u&u76ul1y({TwJ6z-3QzfeO$LM5a+|YYy zFE>xF(Y{~4nzJKkPzo5HO?~Kp#c+o~c4gp+rx~f*S}l%pSU&a>VzUy-e_kYPX~A5y z0w|@reW5&_Cjl_I7an8ZL(J}c28hd1+D*%# z(_j{Vxr;6`eKG8F1(PiII1D=0(K3UGt~IIqu?Ck}3-FfDckNyyq_YN$u6o#AfJiqD zinSdz32GiKErqp*Cj(#}oNBf;%{>yXrE)nlL*Qc72dY!so%%C1)dTTQlNJ8VqXnWJV zDM}@j7Pfm7#12B_YlC*60VYBW9zE5k)&MN( zQx^C0u!;pJyBC8Ckrg=&FiH$YaYkR|ydt8N^|}6wF2LQSNs$aIiN@eSi>r{LF<8ZX z2%*gGM<)c@q&0n+TvGFm{@*030%0)jOXKOQpI&pD{fRg9@UJ(W{;0l+10SqIVLzHY z3zJypd-M$~MjND~YYxFE_MisPTSWpXyDtTjyvk>14?$O7tu=j4Fzymc)N{qILT7#j z99@)Ye9xL#7&1ZYD{?K?>YkKi;&XU>`B3@Nzm6+~$>MJPr~4dWe_E#LJ;-GjO8Stc z=%}qQKr?4XnqT<)e_0u>?TR~gsWQy(a?mt52V-P-1?!E+Bmg?Ok@OUa^Q!|C%onrz zK0R~;5G8iIK-+F@lroeIyki;dxDOY??4egW7NE+9CIb(xS)?uMueVV`7#Dz7$NO@R z)ZnNGer>M?Z2{N-Ctqp&c{<)1xDKlYHu_BL&bep36}fT01H5R1-(GeaVgQJsxX2~R z`qIl6SWeg-0lA$;h!}(gPJ#rmeDSMC7MczB6h-9zwC$P8^_1R<_gAZgGK)p!0G~$0 zzeW3EHAz=yI@dP_B-r!AGpx{)oPx zi4(71R3$@$dHA7Tbjc-ul|M3mP+@frrq$11!{mGpn~Xz2n~yj+#R*B-NwdS@kUNQ{MO5j*e$jz zm|JK{NBQ+Y1|u&2W;|@ABTVPbxx>d+k{j#W&Qc*PDt8+?gMC|dIXl53iPlMqakMT_ zkFI4I-$L^#NW1eiNG<7Vg;QNmU)lvPv-F4Jfx;8dbK?3 zx-}mlfb}N=<@@7mp_ErhOy zUx>4<1`W$>Cyg-3*L|o2o8v-;Ef$!YNTq^v1*W!fNkZD^4+i^$JX7+Ebd4VIW9(kL zd{COmOhS6FC2&5&FkI0f`8qUAgUu}p2R=bDb}Sf9H+VtQ%~Dlp!kuy_LHz0*b30E4 z5^t`YmAaCm%DyaBB@$2Y=rx-U6KcZS7Fk{sQkiFX2F9)!4ZpmO%k|k1(g={sa5DLP zkH{KgJ5_>ZP%7r z?;sMT4O5&n>U~mM6Frxzj;vAuAq!P(qaR+uvi(5Ow&6A4BheQ$IFBEXj5dRpOYy=| zDdBFfzfRx_?a==ctW~78c%l_7pGPbT1p_UTm8Anv#|I-(H|hiupuCps&x>DQ*bail z%fOCThlH0|zp@6hV5%2?Y9sPK>r^dQDDpfgJ^&2l8T|dEe@+9isdE*-Sb#o0sS*JPgWcn2UG+Xhdr#?UwJ2KuKZ z(98z6pJE*4hJ(_{caA)$hZ$m*eT@_#sV3$_cAsit>*|d6!4)4&fpPpoUjAIEwSSAB ziKG@?sWHz8gr-C|5S2b>5Yibal1959e>-L3Y*h^1v+HxZbbwv(<$XmLy01KLVtqwl zCo_uyft^N^p7D>pKGYjnO#S}G4{twH64KJ^BRS@jN}E-4r9O$4|9@Ni13B zT%2}VW-w3|`WVe1G0fy_O?vI}h2Uy=h6JBJ&3F5r&JS~?W2f1%I3)m0X{mFvn7iTT zXyX()7VH}2yHbdu$cBY@N^2G<>;(n2eAaa|Kawptb!mo9yFu>ZyEmyqD?F|g zCZwUIoH>)!!%pwzy%8kK%+~AUW--4FQ(_}Lx)5cfjHjE2<^(=*lVC9iA1aQmKiKG9 zg#?xB*f+Q*v3=5@k(Vjj4X5L+~gb)Wz}lDj^71(+yH9^nGsbw|H=bwG=x>Si3oKw z{N*!SM0Pq25CYRypIvHG`nz`92L^g#qh+%HyINs4GC&6LbIU7wenx+}0HKc8Bra>DF-2ZND0nW)p>mwXWSrIvH0-1+KS!`MSzC@Ibb! zuo1S>bNp4Dm&C|{T88GG&1CiuSpdK>yT&{$?1lc&Lu_Qx+kW?erY46+GsjbaQ|~V_ zKgJKN0`Gs&{f5fv1Zd@e4NanTIu9@cn>{KoPx&68%JWULfTnq80XrTIQP@2`#~X-s z?vqDsJ$pF)ivmqOK#T5I`l*_b@rr{#V(Bl_o&ebp&!u=Uay25cuxvC;3WSD=+9>GequgQ_HOm;JK{U)EfM5r zfz4VBZ48V@E`O|k5F+;uhoZ;O6_-DD7RRz8Q~}$XE!Q+YP=6U5Woj001;%zAt}uX(6>~^CEh}sCf(h!x9_LLpucjNHI zR9(piT{at!6CmEF*Z?XH{7yWP#xU6+@JOSk+#EumA$v-3=XY-Zny@wPOzP6$)1lM} zKF}tL2)oHvfGBtXVa<|RMuNf+Em1-!#yI4aLXUi>swl80vYK1>&NI*FBrjTrwudiv zD1c*$nWHk51uG-vR+@QoYnvNYBq}WaVA${}dzBUmUP#`In0y2;f4{@5G|A1IINsSa zaP%#cf>3$|y&!fcRFA8b;&MvkkE_pU!MO2RiRVeq`A)j?mlqlDioM5<=z@-&_o&UY zxgqu%=Fix*W)h8n(xZUD{vnFT!PCOU_@S^(ek@ghP$`tFHLDHVLPt|4L!pJt(B|%n zpXp$kZX(Nu*$}v|JPN;sr1X=R0iqGHDYkuJ8mPdiz|a-QC#PT_a~;872HDcRC=Z4q ztoRFK4ubMMy)Is@cO%joN~!GaGhOP0io5-3#(@JtKHRj-QH1YZgWMY?{oSLhx!~8- z!ku@-ZdY^nt}Yv4{%HRd$5I?vSp_Lb`X!HgpObrfQ;^$%nFrTTl@75?121GQ z$0Oc-zE&TFn{d5A=#5Btis;WXQMJl#LGA0T`&x?dE{ti|qVM`QgnjUgwn?QcQAM{1zpMDw3Hba}IzgFL$j9i$4yA zIc=5ok&CVhTB6Kzn+D+M3}$^=WVWqyW4Vj zyEt?@+3?WVuDz0rx`Ua6Uq^Td-YbT6bWj=nD?|bsP2FYPM1>%`1p&oWl}8p%fuo`r zg|lWX>em2MvK=+oS9si)HqAhbK;B_x^Mrp~>38qrseK<+;X{6-T;On5;w1T90Sd z692*#x6F#U>ruB3how%9L>JqkB@tl5;`=iNz^|qLxk@OHA>r4L= z!@-4I9MX?AGseXLjeFwQ-mr;b-pn&Kw$U`wM|OUS)Mg|31Spq^Ama!$Ne->bRo*As zEIkWHjQGcOzb;PWzuQb7v@?b&Mj_u_N}Q{WED@?e_I^yN_fvUYQiL|s{egpFe?T{d z5;1a)Nt@@~Y*-sXZou35Wr(L_>GI1 zzhgeS8S<pwdd%ooRlkBXmG*b~&7kCEnxU8uL6{Va>U2t=2J?uDJ6(fwt=j zyC(2_(ai+^kXlz*Jtxm4iG{mbve`j&r;xpRX@sXK1-W*_Zlug!^`PJp5@FU{7tH2(^RB zXd~ixD}B8uZFlH+!Yq2*Q$?D5;&Gjd;jMS5mmpUXfhq>RCzLMC#W7@@vVHv5eZm|U z)l7<6O8>8WR&I;*x8&2|V4PnGIk#fB>y!>ELoS~ep7CdhJt734Jh@s5l{&e zhdb+E;Ml5(WL@HEMRAQDwam8!cyXXk9F*>%x6xRy!CllvX-NI;mNFS>v+^VYV0+Xg zoS+4|Wa^q`*&gcwPS%y#3B6Uk1I$;fgRa9ISogfty=sI8;f~_54vqf0QzTAhV}%)043wHH}R+7>)&ue3(boV;BzVIK`;xmRMb}c!(mReAIA`T7`{dTPG-$>gWmN zl;Dfu%ls{jH%6ky=&;iP9DSMCcY{y1y)C0)BLe&*FxNGrL}Ks)+k zL~AAuD(B~#Ai~p^K5CuvvLcV|GfviQ%yZt_+I(E{!n7$S?YlC{NRTd$(3n$s^O=b7 zaf+!Mg$5JLsOnS^IB>tV1u|CJQ>F#lktW@5E-wUEg^7QYt6qpt(7euya~0K~3Z~x% zFUd4>fUF~=7Ipk(a)pGAc*<5!Q;fNA;_?LY#bD>9WYb{(^f+0f#WV9=;gpHcGYxcg)bu=D>EoPWl-_73HY-sZVbxwa+xs8%Bvi|#mmdy z;XUVZe-Uy*>%;saJJO9bua^zLti$offgRPJ})7gy>Ur`uftK+mxL*Z{t zmXmOY|D|kw^EY}ji-DQgfZ4Op&$tlozDy|pQtR4<-)*2H6&goh%idX@ZRgM3S6;oY za7YH?ixLn^j`Lr=37P_q6BnNuhlCZcVq$ACqmhr|M=S1w`{t%69^H&3P!UYhD)O6m zjup8}^G&_4&ru%MKj1MnPz7`O9gI^4A+sMlX zVQNnxG`%m^%cXfcO%$a8@!?|b=Qk{@S(x4ripE^h{06@=MU^QrY--~Ws+2`t0|bQK zbO+Q9Ki-jb6wje>wd!v(+F|R`U>7yhYaW&-ym#nbVx;sS*#YqzSKq{&6YaAa2}s_e zL_cuKI}I}T+NoA@f^cc_wbjLHXYSA%bdP6Ts;^Nl)U(Y$L4$P*a(Xt!AEQVkRlbiR z5)gmL+@o`{f@_-5N2Jeg1@`7npWcq5;8ov4+f~;zlqhSwC*|I1qG-Gug}rx4g0w91 z5DM}NDnaTxPK4)`m(T4%5(P~R%ieI(l(BC`$GZ2O;f?r0Fq!&0L>_k9eQ6`vmQX@C zGvi6oH&xD-WXh-Pb+(yU2Iv-HaQ>!0bB39qey1IHLpR&%D6AQBH>m8aH@YdZngWnd zkc*!*eSn(RVvCrK^mcBq=9^c_#9IcyrX;mOZ?-z;Gz&$UMrb<*p~MLFl^$PzVk{wR z#LJD%4>uh{Fjy)>K29)Qv}(BOm})p&e9248zwE)RXxkk|^m9bfmFsRh-|UL9$!*73 z_G|=PEMc4@h2L(xwod^pAVBCEZ( z`S$SsptLfl((oG^u9gfVE%9rKJmosi7i4R5f~~_C_~iY#kYlQjhzO{B!(-TVGF)Z8y&!fE$GJc zpX@A@3erKd3r&;8NxL9*6Vh*=fAo{i%b3|on30O=AviqCvn%8;fE;bjn4ii^^=53O46^5T_%rR3-$3A<=>a1ZVQ&V0f09!47|Iw ztbd1Ebxr)kqfSh^E-`i9*+fp&Loaice!QM6;G5K3dOR6uz(0zZxTn?PvO)!{?1Axa zqJ$s5x`j##JC3j&Z4!uq`_2Zcwm=AJpmiRyw+_)iqjs6LxaE9fh?T6wX-&qPn6_2n zip7$kgE31v;MW`sKx-9p*a|kvIlymBOV|@Y61Q3B?men1XP!0Mv}D92C?nq5-mQ_6 z4EqlEvO0`{af|x)$Pu^3(oRJaT z&W_q4y{MCgn!(P4UcT$Bf8&^BR!7FW7)+!bqtb6v{eF5+BnoNfAYE9v_HMK~Ykd9g zc#`9&0eFx{=`_0Y2til6zMNSJayv>%>Ou02mn?eG*IM7H0`J>5GxO7%UN-fxubs$> zh6#x6jTUOPnynJt!s{B-4OCeNN@5T`7n1&*?{)EmT89i#xI9!1q*@p;#0^p+5xWacP$N7of_4u)}cy5mlh8C2&DcSM}aR@@>?F z<1jw@q@*_19bU$w%k-=b&HYqq z?liigm5kxi!c>TE;_;{cVhvn0St=RGtTca*>xRAgPBg6i@c!<;`SqkSa)41O2m2Zg zE?hB+_Ile2{N{T#tt0mLJqGPzvm(|*iDXxXK?g~~$$ANid;vMQ*o25Q040J<-aQ`E zKI}U~D|O}h`y4K=cPztA#^KH8P~JO0BB#!OS2vThc8zGveHA79$J^idY;?cxtK(O#|6A%NHy0>9v-W zp!HY&p=q}C>Xl91dMGqkIK?T$Rq0e#TV$j`0k#HCfK|x9-3r#)^+iB zG@L)hU7d}r7IfEBudJld&0uobbX!^DRr!NDSB`Z(FZA@B)dm>0d$KPpK6}a4+R^j- z8y^Y#MH9=YB!PCPcbDuJ$n;Gv$YWw&;c!^XX)F0PVXwzA7TithaF-LEj_s&YKw zN|oD?e;!G8jyiF{$G5p>_6u(`MRwJW7zBI@&4I5bYDnJ!s%2&DaRN76eKElKUWd}8 zFa(NkaP5iMO*vx9xHRoNp(iv9S56oo5@wa)q=**#lj;jE?x1YcH<ZNfK zu<>6Ena+UMo|7PCM8O-JxiDQfQN92#uaT#=tjNIK++wbezUz zve#~Q@Fi|T?9gB*j0L}`Hv4?QW-Q6*;-s#Dy38yP33Pz)qRw!z{^DVVW9J!zN>yR} zgpePB_h8d%i1&Q54)-s$)p1_@eMFVw3vLw1GH#<{s~xG2`dX6Ik48A!kE}D^^bq{Z z-hbv#tB(e>n~pq&vnIF^HZ4tp(5qmF(;UETr|l31C`pZ`8yQ|OWls9J-En1+3$EKU zYRft0zfpRux;O5eu!E2-5YTrpF?|VXzbYyiL>TOwoGYal!nCLAHu(aI;Ga;H6#|Ob zuOGp6m59+YCtKPg@+^18kIY2RBII1#!u?`O)BK>@YC3otf_F(T*Hntag4WF$coHCC zQ4adm@Ho<&6Rl!RlpYLCcE|eK-R!o*6qnwta*U&`<9R&h8hzT=vFT7y>gvhxjkjy4 zrV)q{N`H@Is@y(WO>RE0rFK>(YMEY%8lYpP!8ui(>IwGni`k8$?NrjrRwqyGa(6kd zCX7JCJdzOr9KIQB;wqZ9dA;VJf)k|kM$bAnVLAKu=8lZ#JS#GiNlXO>$RDcHu6x$ytCg?rNQM9NcXAZXj1494ttXZ~xK0XQH>KlcHubZ|@qz^xtQr@DEIanYvO^Eigfw;fM-gpe)yTa2dS<7lbyF1BX<9 zSgHAuRLD}%pomY2!9InrOZaxuVt}XGBBjkgm8FC598&0MC%Q@2n7>^*`n$>Yy_*Q; zt#bdMqD;B^xcFU`uOGkJY&r8R?j-{cKNUB*>q1s(`v*ZQeXBR-D1hyA&u{a~-9Coe zZW9Z1q5D4Qno&Pr=gLgegFZtVCkb}S;r_LOtJ!WRG;hZApTJnR?n|?6#Xxg~HGKS6 z*aJAJ6VnOHv1z>0MXHc&awP_)uDkzglfPx>I<&jKUNEp!r6w+qX$3PeG?lJt zlBi90ySIYw1R z%9+v`-gSDDZzsEh!-u1&>zuw=CJYUM4@E}fM%DbX@b~iM_w#aS=Z?m@2Y*33 z8H+mmIm*>zp&J`a#&v|M%FYP}I~!7>A``f}aU%)qwrMopPoldeC;guA!k?&?5IJ=H zdo3{f7WQ8xO-`J9!AcTlFP*SA-hZ03<3o%{Cs^mfBSwkzw32o6Thf$HQ!`j~F!Ae| zchM)QvFo?pAm!(hv$r42@vT4Atcg;G;j%Wg$%7wOdLYzxjew`CtJO0jr+jEe9+W?l z&PSP_+GlC#R&J|S`W^M|f2}>5)LrYDBv9e7XE|6<0q?h@p+DpgdS(Hb`|}Q^-npd% zwYSh;PBj5WrlB5so^Of_)fH8MMCBFn9VHBkQ6BVTc0^p_Q`6mMuKbi0bnG-aa~RU7 zwC;{RJfn}c`Uck7^W(<4grh}vEYOw{mXN33D3S@UnVq!g}{oZBM9xCs$5 z17n>x8hAmAXejYau04ekNVylBY0W636@Xm|8oD7pP=a(Sxl3OcZz7UYop+9f$EWY+ z!qqGG-lHK$p~KO8w-2ZQrQB3NW9a_i=t~iri;}S}CZQJU=oW@=xw9%;wEMn#c}+(Z zmWV;G)$zpKNiL5vl`BUaMJOZOC#6Lp-Qjt^B#hO0(7skSGjix`Jj z?|iS^gpIfF6m$=%|vsK*1VQ@pZ& z#5E&|)%uWxH9du3^}EOY5h1|y)=kg#Mc2X&+bIdu_{puu#-(LXYwx=qCBcWvWGq_U zZ@9NX9|Fh5u4w3%l%0>%F39gUHsg{Z1{`7+B}vw*ww$~(v8K=<&LM6%d#U211=fGE zS<+|=qsJ-kCvvI+=bb2gb2*T1gg&ynjG`S|(ZQ1`&cdI}woV96^ye26ik= zy-o@TGDIv;hrL?X0%j`BG#|6B_+|0MC;8-MVw8DhHNc(bhh(urdm}m3H7vGuchFJg zq|lQ`AbE@cTF3yGl4Wn@Pl*d=+%*uW0}&Py|Dkm?Va;P`t>Y^!iikzr=lJyP=NS2W zXoxLNgc@P$7gS+&?9eO4^&tM(rW3x`dKvkwrYrBQ^k-K!lsK3G`dI`76@I79ZEumW z8{~?DRBe}jgul({Lkoq|gz&1UwwLxWs)vxK0r=;&ujw$CG9yT}hI0awBuVNYw2<4! zi_B=^IKlx!9e9EEM7v$1H(#^gMe+=Gaty_QUDCfhBVb?j?~VxA4gJ6Fh5p?M0lOez z4+QLhfc+1!`}wcE53uw3-*!F!+nxv5@c_FRVCMqtRe&7_u-gFk8UOAvfc*rpcK~({ zz^(z<1pr<@;OqbE%L5)c;Ew~|IN*f?UiZHqH|PKLumR8dUvC=lrT@#52K;Eii~iqy z=>PJd|Mj2$^_~H*8Ss<;%QFVNV!-zWd|kk|{V%^3@MQr{_Fpd+@L>V(^>K2l%(& z2YPs*Z~wPX2l{iMp9cD5pbrLmT%eBy`c|M%1^UZ>drP2)1bRoHUj%wWpdSQ!K%nOW zdMlup0{SDMzXAFhpoana7NBPVdJUk*0D6mm`w5_z0CN9-bMk+4Zy=ZcH;)E#Um)iN z^4ov&)&DI|1#(g#_XP4sAZPqHPXzKpAQ$}KazG$w1M)K~a|K=J0<`zIs@oygSUpd5o Date: Sun, 17 Jul 2022 09:40:34 +0100 Subject: [PATCH 02/86] Add best friend check and complete blacklist --- dChatFilter/dChatFilter.cpp | 46 ++++++++++++----------------- dChatFilter/dChatFilter.h | 5 ++-- dGame/User.cpp | 2 ++ dGame/User.h | 5 ++++ dNet/ClientPackets.cpp | 56 ++++++++++++++++++++++++++++++++++-- resources/blacklist.dcf | Bin 16160 -> 16160 bytes 6 files changed, 82 insertions(+), 32 deletions(-) diff --git a/dChatFilter/dChatFilter.cpp b/dChatFilter/dChatFilter.cpp index fe8a0d10..eb6674a4 100644 --- a/dChatFilter/dChatFilter.cpp +++ b/dChatFilter/dChatFilter.cpp @@ -19,12 +19,12 @@ dChatFilter::dChatFilter(const std::string& filepath, bool dontGenerateDCF) { m_DontGenerateDCF = dontGenerateDCF; if (!BinaryIO::DoesFileExist(filepath + ".dcf") || m_DontGenerateDCF) { - ReadWordlistPlaintext(filepath + ".txt"); - if (!m_DontGenerateDCF) ExportWordlistToDCF(filepath + ".dcf"); + ReadWordlistPlaintext(filepath + ".txt", true); + if (!m_DontGenerateDCF) ExportWordlistToDCF(filepath + ".dcf", true); } else if (!ReadWordlistDCF(filepath + ".dcf", true)) { - ReadWordlistPlaintext(filepath + ".txt"); - ExportWordlistToDCF(filepath + ".dcf"); + ReadWordlistPlaintext(filepath + ".txt", true); + ExportWordlistToDCF(filepath + ".dcf", true); } if (BinaryIO::DoesFileExist("blacklist.dcf")) { @@ -48,14 +48,15 @@ dChatFilter::~dChatFilter() { m_NoNoWords.clear(); } -void dChatFilter::ReadWordlistPlaintext(const std::string& filepath) { +void dChatFilter::ReadWordlistPlaintext(const std::string& filepath, bool whiteList) { std::ifstream file(filepath); if (file) { std::string line; while (std::getline(file, line)) { line.erase(std::remove(line.begin(), line.end(), '\r'), line.end()); std::transform(line.begin(), line.end(), line.begin(), ::tolower); //Transform to lowercase - m_YesYesWords.push_back(CalculateHash(line)); + if (whiteList) m_YesYesWords.push_back(CalculateHash(line)); + else m_NoNoWords.push_back(CalculateHash(line)); } } } @@ -94,14 +95,14 @@ bool dChatFilter::ReadWordlistDCF(const std::string& filepath, bool whiteList) { return false; } -void dChatFilter::ExportWordlistToDCF(const std::string& filepath) { +void dChatFilter::ExportWordlistToDCF(const std::string& filepath, bool whiteList) { std::ofstream file(filepath, std::ios::binary | std::ios_base::out); if (file) { BinaryIO::BinaryWrite(file, uint32_t(dChatFilterDCF::header)); BinaryIO::BinaryWrite(file, uint32_t(dChatFilterDCF::formatVersion)); - BinaryIO::BinaryWrite(file, size_t(m_YesYesWords.size())); + BinaryIO::BinaryWrite(file, size_t(whiteList ? m_YesYesWords.size() : m_NoNoWords.size())); - for (size_t word : m_YesYesWords) { + for (size_t word : whiteList ? m_YesYesWords : m_NoNoWords) { BinaryIO::BinaryWrite(file, word); } @@ -128,21 +129,18 @@ std::vector dChatFilter::IsSentenceOkay(const std::string& message, size_t hash = CalculateHash(segment); - if (std::find(m_UserUnapprovedWordCache.begin(), m_UserUnapprovedWordCache.end(), hash) != m_UserUnapprovedWordCache.end()) { - listOfBadSegments.push_back(originalSegment); // found word that isn't ok, just deny this code works for both white and black list + if (std::find(m_UserUnapprovedWordCache.begin(), m_UserUnapprovedWordCache.end(), hash) != m_UserUnapprovedWordCache.end() && whiteList) { + listOfBadSegments.push_back(originalSegment); } - if (!IsInWordlist(hash, whiteList)) { - if (whiteList) { - m_UserUnapprovedWordCache.push_back(hash); - listOfBadSegments.push_back(originalSegment); - } + if (std::find(m_YesYesWords.begin(), m_YesYesWords.end(), hash) == m_YesYesWords.end() && whiteList) { + m_UserUnapprovedWordCache.push_back(hash); + listOfBadSegments.push_back(originalSegment); } - else { - if (!whiteList) { - m_UserUnapprovedWordCache.push_back(hash); - listOfBadSegments.push_back(originalSegment); - } + + if (std::find(m_NoNoWords.begin(), m_NoNoWords.end(), hash) != m_NoNoWords.end() && !whiteList) { + m_UserUnapprovedWordCache.push_back(hash); + listOfBadSegments.push_back(originalSegment); } } @@ -155,10 +153,4 @@ size_t dChatFilter::CalculateHash(const std::string& word) { size_t value = hash(word); return value; -} - -bool dChatFilter::IsInWordlist(size_t word, bool whiteList) { - auto* list = whiteList ? &m_YesYesWords : &m_NoNoWords; - - return std::find(list->begin(), list->end(), word) != list->end(); } \ No newline at end of file diff --git a/dChatFilter/dChatFilter.h b/dChatFilter/dChatFilter.h index 5acd6063..62a47242 100644 --- a/dChatFilter/dChatFilter.h +++ b/dChatFilter/dChatFilter.h @@ -20,9 +20,9 @@ public: dChatFilter(const std::string& filepath, bool dontGenerateDCF); ~dChatFilter(); - void ReadWordlistPlaintext(const std::string& filepath); + void ReadWordlistPlaintext(const std::string& filepath, bool whiteList); bool ReadWordlistDCF(const std::string& filepath, bool whiteList); - void ExportWordlistToDCF(const std::string& filepath); + void ExportWordlistToDCF(const std::string& filepath, bool whiteList); std::vector IsSentenceOkay(const std::string& message, int gmLevel, bool whiteList = true); private: @@ -33,5 +33,4 @@ private: //Private functions: size_t CalculateHash(const std::string& word); - bool IsInWordlist(size_t word, bool whiteList); }; \ No newline at end of file diff --git a/dGame/User.cpp b/dGame/User.cpp index 3efc4d0a..98a37954 100644 --- a/dGame/User.cpp +++ b/dGame/User.cpp @@ -18,6 +18,8 @@ User::User(const SystemAddress& sysAddr, const std::string& username, const std: m_SystemAddress = sysAddr; m_Username = username; m_LoggedInCharID = 0; + + m_IsBestFriendMap = std::unordered_map(); //HACK HACK HACK //This needs to be re-enabled / updated whenever the mute stuff is moved to another table. diff --git a/dGame/User.h b/dGame/User.h index 3be9148e..78640b38 100644 --- a/dGame/User.h +++ b/dGame/User.h @@ -42,6 +42,9 @@ public: bool GetLastChatMessageApproved() { return m_LastChatMessageApproved; } void SetLastChatMessageApproved(bool approved) { m_LastChatMessageApproved = approved; } + std::unordered_map GetIsBestFriendMap() { return m_IsBestFriendMap; } + void SetIsBestFriendMap(std::unordered_map mapToSet) { m_IsBestFriendMap = mapToSet; } + bool GetIsMuted() const; time_t GetMuteExpire() const; @@ -63,6 +66,8 @@ private: std::vector m_Characters; LWOOBJID m_LoggedInCharID; + std::unordered_map m_IsBestFriendMap; + bool m_LastChatMessageApproved = false; int m_AmountOfTimesOutOfSync = 0; const int m_MaxDesyncAllowed = 12; diff --git a/dNet/ClientPackets.cpp b/dNet/ClientPackets.cpp index 187ee12f..abb08688 100644 --- a/dNet/ClientPackets.cpp +++ b/dNet/ClientPackets.cpp @@ -30,6 +30,9 @@ #include "VehiclePhysicsComponent.h" #include "dConfig.h" #include "CharacterComponent.h" +#include "Database.h" + + void ClientPackets::HandleChatMessage(const SystemAddress& sysAddr, Packet* packet) { User* user = UserManager::Instance()->GetUser(sysAddr); @@ -276,7 +279,6 @@ void ClientPackets::HandleChatModerationRequest(const SystemAddress& sysAddr, Pa std::string message = ""; stream.Read(chatLevel); - printf("%d", chatLevel); stream.Read(requestID); for (uint32_t i = 0; i < 42; ++i) { @@ -285,6 +287,12 @@ void ClientPackets::HandleChatModerationRequest(const SystemAddress& sysAddr, Pa receiver.push_back(static_cast(character)); } + if (!receiver.empty()) { + if (std::string(receiver.c_str(), 4) == "[GM]") { + receiver = std::string(receiver.c_str() + 4, receiver.size() - 4); + } + } + stream.Read(messageLength); for (uint32_t i = 0; i < messageLength; ++i) { uint16_t character; @@ -292,8 +300,52 @@ void ClientPackets::HandleChatModerationRequest(const SystemAddress& sysAddr, Pa message.push_back(static_cast(character)); } + bool isBestFriend = false; + + if (chatLevel == 1) { + // Private chat + LWOOBJID idOfReceiver = LWOOBJID_EMPTY; + + { + sql::PreparedStatement* stmt = Database::CreatePreppedStmt("SELECT name FROM charinfo WHERE name = ?"); + stmt->setString(1, receiver); + + sql::ResultSet* res = stmt->executeQuery(); + + if (res->next()) { + idOfReceiver = res->getInt("id"); + } + } + + if (user->GetIsBestFriendMap().find(receiver) == user->GetIsBestFriendMap().end() && idOfReceiver != LWOOBJID_EMPTY) { + sql::PreparedStatement* stmt = Database::CreatePreppedStmt("SELECT * FROM friends WHERE (player_id = ? AND friend_id = ?) OR (player_id = ? AND friend_id = ?) LIMIT 1;"); + stmt->setInt(1, entity->GetObjectID()); + stmt->setInt(2, idOfReceiver); + stmt->setInt(3, idOfReceiver); + stmt->setInt(4, entity->GetObjectID()); + + sql::ResultSet* res = stmt->executeQuery(); + + if (res->next()) { + isBestFriend = res->getInt("best_friend") == 3; + } + + if (isBestFriend) { + auto tmpBestFriendMap = user->GetIsBestFriendMap(); + tmpBestFriendMap[receiver] = true; + user->SetIsBestFriendMap(tmpBestFriendMap); + } + + delete res; + delete stmt; + } + else if (user->GetIsBestFriendMap().find(receiver) != user->GetIsBestFriendMap().end()) { + isBestFriend = true; + } + } + std::unordered_map unacceptedItems; - std::vector segments = Game::chatFilter->IsSentenceOkay(message, entity->GetGMLevel()); + std::vector segments = Game::chatFilter->IsSentenceOkay(message, entity->GetGMLevel(), !(isBestFriend && chatLevel == 1)); bool bAllClean = segments.empty(); diff --git a/resources/blacklist.dcf b/resources/blacklist.dcf index cdc64c2f5b245f4526974ab9cb1770fd8355b783..ca4db242aa20dbc20082100845e658ab7d958bb6 100644 GIT binary patch literal 16160 zcmb8WRaBJ?)UFNE(#=A;yFt2Jx;v#irMsl0yF;W)x*O?6I;2~=+3R3G-#><9yyN?~ z2V7&qa*1&A%=^BkxR|8qI|vAfZ8-1;@SkZ4keZ>b_c_~TRuxi_ab2-DmEvLwKAZ&h zcctkS!LNzn>{0Z49O-$x05+`i#zV*AM)$b6qifT zBO8CP+wbsVGM>|#MG6%d7wK)-wHks;T2kIV!)Qp?LMEDhV5jLE?1n+zk1xmi#msS7 zM)WqGv~kN+>e&$7zLgRx#bsh*Z0AhVup$s5D;yDH%5bOs5pk_Y4@`E%wV-7wtHuL{ z%IEZKjz$7|McMHn!4M{xufpmRW2>jV{VE|m1dZI%6gv0LFrZfL{RTOFqM%quZGi1e z;a}bG>(xSJpW-^C4qGV-Z@1`1tH&+hj&%qhQ^>XmkTzg5P#lH7euu! zqoJg$h_U_UDqlhq#xjN#mwCVS*!Um!^VAZ8G5B4^^yaG`d2u6RyifVvM+jN&&FS|h#1px)wriK<^prJP(l&AwT- z&EzC`x}19*^0&=6KOckOoW2ALUQGM2bwp}+xb11@Phq?#U|h}KLKu+m>M}^c5u2n$ z|BT?HvYqyTQp~Mk@Bt5v?N=MjVxU*syQRC>;pp|IU6JCpV!z+m$ z%l!23g+Pno(V4K9@@YSor)`?}!tX@Pbm4aIDU}Dt({JJ=*@e-BZ8Pws8M7`^;OR5t zlZv!$ET-hvlN93V8GiPwlx4p2%D8auRzX&m_hjsUmt9D)yq=x}Cj9dH0*o-q`}D@C zWSrUVW+}g>nSe{(pnlRu4KEQ)5UChMQwdCZrh$v^vqNw^_sB@~%Qp>CVn!IAo)iHh zKcnFJ1Ug0hPoui9y}>H;Mv%DdvH6qK+!`xauDWN0-0xhs&t|8h1k98Jve zoj(qdSo@gsRlJuKt}I`rJ*2~1vN8Fwz#zK;C%X`O%_WYbU9?Ov508`n zoIbkz2V{7)(y0C?Rf%*vZME~()xMNJW5K~J89W)s*gW*BrfHBM#n_pJ*= zHe43_{29UQZtd;ML3DUL@6&H=ukHa@gxoUb+qk1UL*yspeZl`a#SG>n|LenF>n&f= zasOae@chL8YE&N~<9#dhy2~Mb<-2T@_mF+PY$@mPNOZ0Cr;x?pW=tP9`^2hh`=M+q z0QoXa`DbX2Rxuv5!Qhcw>#3NR;b|#JOtDCbs+ocgd;o}l@HEOapRb`JtV`tQ~ znKysY5UN3@vRoRRxrIFhEj-&|Rmb{hBIHmRuF_rhW4DyzcZA|HNPzWGW6IUlm1h9Y zU}Z5uqVf>80rjfC>ZzXAFMhYw9hgPEyE$yd@gD3CeC#>qk-S^xvdYe|k))oZ@w>&0 z!1@%9ZV4vbr*MCCt;f-H_ztJSft0%6d-8C-U>@zs6WAcIxr>lfCM#A9W**XyUp-e3 zW)3os?}dITKQ}<;4?upOUH3?*wYAI#ck@#w9y$e$eT)eILP6M8yeYLvwS|jR|8abTFQq&E0YvoSQ zk?L$csCkdtKoU_Y53?QVG3Ct$Q_(D#i_kwz8I~_+m}wR1X9l2{-(UQ;Z=w&xdCh%R zMIOgCnVUhex;UenCw)CUfjv&NX59{Ea!*Swpqc!{Mp1CfJCq5L*zozyA)+2$v2TBW zOF6n^tHbAVs4^u1<9okUwhkufqcH@`XVxUCiLA590W*~*n+@4e)9YZ|o^0#VfIE4H zP6ZpXV*aCL=OFi?kf-g;^QpH{R~=LIrhA0H&LltaIFQ&lVYO{1V;={!E`A+2w{P75 zjJ!W&+Kz+i|8Z8cow@4q7Q9<~vZC-w0ANUnrww_-UTpn4=Hn{F#ki})qmLMQI0-mC zX;3$DFw`}mOak=^v3(3|v-1oWKbdUga+-m%6TL)|lHX9fkAw>7s98|^fr?mE1Ndgt zh4*;1gSfNlcVF{c4<0^kx}C-^Qx`jKnojdeCr`$|!;@$3ML5aACH5;d&PAJG*xmE{ zJ5^5WHS?*ygG=mp8+~XDo$NteD0PFf-u^jt6TS*-yx*qRDKF{x^d>V5>2t;GX&<(TdwNY`EDb(cO{Hxfr>UQPzk?6rTx=RF z^Tpp0buP4GGk%v5OgPgQ{1SNY`U%#IZ*cCtYmkA`aNJ*8<->)>ls;%mcL6#R;&r_J zZnel6rfKjjL1!}G$h_ZeP(0Hphz9E}XTk8bJ3~IYYakflM_;n<#5-P9(C_?8K?4R2 zQx!z8?lK+>4_d_L(eCKgnKp%t8MI9F0QWeaQR0)w9#(ujjf1Z(T>Q;3iQ-9lurj8< zMWCl&E9l$(RT0#G@-NYHCX8qG#-wkZq@p0ep#!-74gH;Z{X)2ws^_3u3nFnHil9au zZ)GlQHGxJPTWBu-g&aaMa#i#cWb3$~a+MZ=K?ZyCTl_1)XM~f1lP9YR0fN2nAC6N> zx4Bt$b6@gu2G&Zk<7cCw^`vVszSe7S8CRdvLK z0S;WpsoK!RJy&0yq@Fg6qv%GT^yZk;?zBsRSJeRQ-**>Kt8ELyUeGA_l~qv{EiyIk z0tJ=w*IRWz+w=Q!$JiMHQ;_wzHl!?s9DA+E?0FilxVUaA&6X4^rDK?7RBh`UX_OcsV`|3=}h~6H#T63*yA#HkI`_E+cR)RhKEa<$_V{t4zLIJH7({r zzg1GA_%5Tms2sz-`Hfjnb_% z)B#^c#@(E1Wxe0ffysQItu!HYgr#5D~k;Z=qeg3eM1%^lsTV} z6A1LG)?JYRl9<R1;{Gz_E%E7<9Ezg@b?J^a~rq()|Yc{9UnOU(wBo~8UL8~ zio_nQ&8Ko%z{u+THPEvyI66*M663ZXYH*N(D5tonm-NSZ0;6*QXTXt+w6aQ8z81W7 zbH21-05?)-DE;r2wl#rDv$!;u9wg9N%Z=0x3(iIvIWNF>$p@uYM`G~+ZM3Dn2a(%< z2Iyb^>CiKYEg4{A=lE7mz|?|YXa|RLA0sTl1TiSvKD7*g)XOoUQzZVqyN^b4r>%26 z{YIz9y&P*m#4D9tz;0&WXYX=J&!Gt z_6gjNoVSa}>Ei0Hh;z1+<9)MGe=uR^4z#w9Q}3ph0(fw#f~^TdG5QTw8C`SpYahVI zQOu>uWTHbJA##jPf4TS^4Si+^mgxf(;KTB*wPX+&08OI6zn|xp8^|wA zya?8rGytEm%!FNhksGDsweEA3&Y(PV{9b3sLSO+-_11|yGeG|WI8zIr$)JBF&K0)N z(Kd^R2kHgT8OyB##330Ywv<+9h>oIvBCxslN#O#M=iaA1BkzMH{a1=s$l&+;IXGMO zra|xbMR2yDOD0$>G-E?KzfqlQK81EI?I{m-B5)oMemiEd(5eaD8Q7fb^n-lYtg$fH z8G8-MPCEhrbZFsY-c-V3pCS3e_7i$3HLKS(YU`tk+I3HvV+^b3`k0Jne3 z<93d(egTMYtMRcfG<=~yaIrQx3YpW93-(W<=KKcbcLBY0$hTF$gHk8Fhix-cQaPyc;d)9jr!9AQJE7ni*7xvu+tpi(i+&5bv_Z z(uLJD4+3m07wot&Px_^f1jIl!!=0N7?${`po+`Ku89Ke`pA$ZMlS}rd zyLx>*^&YmNl>WRT@f826K)TBTFha}z8jttK$n4vhgN5bin`jgNfd}hKwAC1OGEVJF ztLddJ{%YJBe9sKrV#E&T)vQ$crzNp0{i}g{Y@hx;ls= zXrB=t)*wmZ_je#rF#9#PL7uz_ALe%>5VfRFs`TI%Vzi=!Qr?Me=~=**#9TANJ!hliE`_nS#pk2dtYx8wq~k_cuVwWF zr)#dv%&1>kP%#+D^3Uh^VyhwRv>c}s8|7hB&<--oJs#zJs*Sd>k9=U`J~M$?2$kPt zoEe_0s4Rkf!}1i(hxK^~>9{mv{-{!OOnl_`(}F}^$RJaMTmPLi^!iB-p+=C!?dOGh z1uNr$bvKe7%=j}2-L_l06cvb1rqyMr>cJmC_T{|=9u)^pR z(Sox8{SeTcyz@f8+adV$Xn#~HiLV0C?eE^^Dbpznz`Sng^mp^Mxjss(kxZ2kW@vbRlCs&AtQP!}oI+i*kU6#n-nQK_q?UcO@Q1TSd) z&A>adYpo-Mv|CWu7zxYKlX08{>LrS=u%@ZQ=0tEHR$aNvP<+Lx&2;m`9ml3*L)n}& zpXDp0ti@EISR?!i?V@2dm}GQx2Pl4@Csfqx$rgUkLydS6Tv2c&VuiZ=N(;4xBPJ!- zwi^2A-CPDoxrO|YetURSHJgItX-IzF0lE2#=i9QHK9W_@aci6?G2bj%Cf);SPg#iL zX~TMceuA3RA&q27h6Wu(7VFh)ngo^9!ToB1U5FJ#78u)1d3l-G!GB~y$(AOvJHpLO zHau-c7JU~gg~t7*r;P|pl7{q4&krapR25CTjvGVr_vqmFHDo;}xf)DPv!HVjYm_5iaa^`#CR9MhF9EH%1S|MoUNg7S{Pp?%D+TyF5{*huf;3 ziKZ9FQ%~bOyH}6AyN=bXSiEnF24Xshs7HX*Gu|1}YSKDQ*JftUSq$p1aIpSBNtan> z^CFB8KVXo?6A>3J2GkNwK<;06FQ#s`x&Ea1!L?Ry6E}*Yd9OZ7X$IFhyHkaFjdhte z>4j+qi-EV)F1nG@c)POQ0=v0@tk+5BIhEK|A_n%$A;cRRW{&09-^)fPTIvVMFiCV+ zj*n5RpL0+zJRob!TDiwA=!eD{t9EkdPNnh!WtKd^o>5=SZ<;!=W!y^H{^)Y?TpH`aC}QX*S*b^EC@W7haJ2+srL~i| z+6_PFu{2ybLZ(N%5iol&0IC`IW@Nqj5J?HZBYEOotp1?^6X{}={b+a6x}EUlz=G$_ zNhB#WiHH)(6B}bK*hC!PSp}i55v92Eh-hN{qJ5JRgY)?UHoEt0Z=(~1=P5-%d&0wORWx z)bs~>wo#{QK_qPx;AiT^4@3E@(0jpNsSByO!XJk%3DxXm`xxAjSPaHL@$hwdPK6T` z$4x|aE_|c-8zoQ$o-vB!BANOGhejAgSvrnDNTTTFVw^oE?iWsrMat@4S&Ma z(hzsuBneFE`8uyoel3KyA7g&%*7 z0|@gWjaXh}I0&Fp;c-eEE>B*z{S3koEdI{1TS5(|-4AOx=Mm%~fzo3>8Swvqs8q6U zQcSjq-Zp198Y zO&o29P%MO-{Ox}0DR=+18}RSnGj7#>F{ zy<>*?4XQDG0rvO=(Wtoi5SQxr^C%HL_&^YSW9*pU;1h(>fp+$JABC!z-G2Czvj%Xk z3jDqX7jrdGjhDWJ8Y9J|C+twHBBRx>x*wrzSZ2ltBLX|xM<+MX{7zLl8h*Pa&J;Eh z>FD(#M|4J1W=9MRSVKEU5k*NOrJTOIKvcqR+7s+_=9cIul398uoxvc?b+j8dv1iOX zYSuird0?|?TK0&iu|21YS^(znxqCQ%YUdw{!zU`z)Xp{f!(_D=E^EV~{N`+7Yd%*! zaxY|yVUk+puzc-jTSChxt zg#NIFagCO2pxW#R`&P)=X6Y*JdCF{DhWqz?(6rfj8u#yKp|6uK?XS=PF=4QfOk9+c z*m)17zKU zEFdZu_8%<<4RG46@E@AI{l;MVgz-nYPrMMJ^Ij=MF1#>GN;I2pm_gWv>>KQ1eq*mv z!lMy$VU2j?$1j8qeq&P%!q{gei(aZ?K914g8J$u1m1%!+IoYdb^*z1f(WpL4fs&v| zd-abm=|lS8dZ8Qw&HIH{yj)F!tN6cec~z9fte{1hjdMdpW-BL|jq{>J&PTd|{~dPW z`vz~9@p$Y)2*+rb@l4u6E6hU853CepwN~YRV^1!^Yb}Aaw{P4HnFW*r-bLChbVg}E z+Bamo4nh|)G`H$?q87GNv_2U1?NcW+u_NHF%F~01h`UNDoQ;63UT-vO zx{f|(zaEf4=ei&!s2WntBA^2xI7knI z`9|M$fI(9_%8BR?ikz~gN zEN(}1Rfadm1t^Gx~ZnYpRozr;=Z11U4gN2A%g zhha{)ZU(=`Xi`x9#|Qa&sl`7R?6mz_q>JfM=VwLpr7^vaCh32TNEd^W&-0c%MbGon zIf)AHJY>ZR(L59Vdt<&j#}@lKFfTs+f`^nHp;#REz9lj0Ypt8`ZIRN*@m+*cFg@f3 z-5;!zLE@c|Fa7XZRNrI1zdLAuhEUv9mxVJ$`*>ViO-JgdML$iG21UxtzjvB-O22qB z09o=gQ~SsdO^IJTNsP;YD=kuq2iY01@=CNf5OdxDjT=@wsaAL zb*n!xH+Qi{a1vm8rMdkgf}_WZs7I^~%g+h>+s#)iovc#HxI1huijO z_mYxDJ-C+66JFkxnR;w06o_I}DoV#y8Sf8l~m)aT`TWx#4I%nfdG zr~vaQxXD$ywjx2g&{Sx5w~MC}&0k)7e!ZYx4a ze*)vgFpDM%q%4TpzP4`1B|>vM8e*;#wP1ziJIk4yM(HcK%0=mNt8Ez?Qi3V4Wq4Q$ zX4ICU*4Jmx+AY^UfR9^3sGt02y*$hXP(Nu*dDVVa+l{QSJoQB2tMxKiZI5hWM-Z>e zv>U!-MiBp%YFCqQJ5iudMQob?zK2kFVuZ*gp9#;;Q}N^*GgRV>NZQBtL7de7>}#fb zD1u9I>QvP{rauMSBx1jpv%j66{32>p9MvT97_err!uk#nj$Bb$VshiJhD6G z1e;m-Lx(fL>J1Y(g88C5yiAN5&V*_8KlFG+0e{|dxOUUo4^_k{eHh^+ zj0r(_Sl<;(3{_@{1t6Vu&(oPoIkv}p@cT*!n^E2Dxl@`enFGw1mC%^bC_)j2?o7=R zj-+ZfK3&9qec{Cq2NUa+*9JHHfG|>wUKHFw^5hEzJ^MxqY#)^$NA#7Zxd|dD_i&xBG9C z#o2ftUTzMg^l*$2cE_&$!`p4*j!oVI@#=dE`qQa4JQCF>>0?`$y!++T-uPthH8xbg zb5XW+!@B`Y5G{!#YBDnX+x~WufU=0}MA1E@sGg@@U(lxP^piLdp-UYFb_m|f`UPwG)Va7)CjvtJ*FZmIt5=;cx zE+Muee|IAdqFQ?JEBZ& z0W>EUdWTX1#f0-J8zvz@*VkvtZ8}y)>OAFm2_oMlxnnB}mSrtLsBHDMO)v1h&(E5D zmPZ(Bcd?e6BL!t);{S2FD!tngDaiyNH^M;KlwYvJ( z-qf>!<-T>iaVL>oawR&R|*TFoIrlY$EcNHqRom z?ezv^hoPUbiUlOXh8?58%TeU#7jSLVsp`FZ$yI*gFKcT2!&(Cr*#1R*S;jp=@+POh zpt1*p@;Hm#HfgVzM%;w$5Hp8mfK}0)1rD2e_563-+bb6H-`(H80}4Y!;(noFy19>b6){Wi13|$BhFL)BM-1Tved#h!lU7JBy!?g>IU6xC&i1!@mjT`^@dxr>hG-ZCH)l@BzCN!!n#Knd(&iu)HQ(vrQV;=` zq6SDW^UKvshYzQI(L70MR5XPr9y3C-(lkDUP{JzgOq_hY?!e-K3@3_zcqsa74tuuX zCL~tpM^2P1=g{qXFjJgE-x($7KKnp7Sh>{ZQ1C%2eZ9A@{2qc*>k-pOheB)M;!?vx zjdCer3xU>_ilh)pzbdeviez3-UqJ?@Mm@bOgIf`VV+5Of38D*b$X^vNDexQ+!RGhe zl4(tj&%q6n(?ha6@1>SE(?g0t?jukzp+TyX$UdszN7aCb%!Ag>Lws-`Q9tgxF3+fb+{BXk}T?oACNij^Gr z{ow*^+1a$HQJ!6G)!j&Jv2vDc0B+&a+hSGi*Z9JMS+HN@`C)s@nP ziqePidas=R5g9PubNY$fwbfOb(i5ir9qQn8&Iq&MFlLBRHtkULB-|xMt4MN5W)vLF z{vu(DEKd_(=GbuxtR0@9ERAW&Ow+hx4sYF;^QLjp zZeG8l2>zDa!`%i#OjbyL8ZU*qb}lS=DCvbGZ@-)^fjaI}=rcEE6kKh4CwOt34(EOl zTX_%KZ^Bfq0V7aJ-Pcew4F}@Iqb@>%OY|d6NZbazSG_x}*dPx|!-5gpThx@4{Sryr zTX5`@mo?Kg182DnnRqyJco%exh}kisEK9<9;bhx-phUhPZY7a9yj6Wh-DvmLIxO^% z3^(w6sn5v9_OgZdflZRH3ru@9$x)vPFrOr_)VK|hcvG?cQX01L3=yU9ezn;3lBy$F zMy1*HGBP6h%5v};O)1K_$9^1i$7yAnZ}*Y6VGXdU*r9ux&p46~`3bq!D!595ZA{>CJ_*o9n=I};m`}=Tc!B9UDZ3F(v7CGOasv>vFaSGmBGBOZXZ%-aZ&ut7-!ifD z{^l7pSE@BZKOtEBgf?nquwpz~+X4R^Z7(EOYiC((U)Tm$za`vBe=fc?_k9ErX5|$W zICxGd?2IyHt_QB;X>baOkS5}Y@*5wH-U-r(uCyX3yU>zPIZ#FQ&ZFGnVMbZcsYahg z{5U``DnppC!MVoERwTtz_1;Xh(g4$cGtqMVvDQW@V-Mg;p7b3a#-z0kHVq3t0aP}? zW4vIa!S0N$Ybcy9xop}cQ72=X(FBCKLTPI<84Y2e$uK_xsLeO3 z&XK1s@={lf;>)MJNR^*tN7U*Fpz`!6c9Oc4NPdYZ6@2hqm>z{`p1Be!P8TIE$1y@v zLi6dDkn2%I_m){j-D7p9#Pr+EX-j*gy`TD9BH@5D3coCV0f|!N0cFaE(R4zPHe@x6 zH;GVn3lxveegs+%37WrT_T|X9Bt*VIo?>I8dgZL5T4SXZBwwJ6mxy*LdMc*+6P@qj6(zm%diJGs>#%iRC)W+7D(YEqOrUf#4U zn(&B4hflZO>r--C4LZLhf830YZI$MqThFF$2c2KAK6d-Q$V>kSB{uYL4_!^oh@njd zvp6G$g!}B*fGihht)x$Oy|X%L@ktX&~-%1UikE@?Ieq4oOQw2R|?^>F{n zorf*mpw=C&%Z=u<-JsQZKt`Ao>xk94bxv5CQhe`JyU|zZ@2dvqOiwOWd^3jU6a;Q1 z=s&mBqO#hEna!hI^t61L?09FoR*|Q5h?RIQ9bw!I{0b{M2rfRtkA?o|%36yMjj`fo z*pJqY3LrjfmC|9zgqlwL#wHlknuYm++BL;cIc49Wt2&XKZnes}PSFW9%tpa%r|AbB zyrj^uZ%Xs2Th;{pF`3tL@bYGd>T6!Y!d8@@g5Db5=m&Y(-aa88jiAtVf|swf&rufF z_L3aF;y1=#X69z)rv*$$;>F;`+8fmRmLb=r{cnUxZ1 z>r+}oRfd|kjDG{feRL1Fzcf;EPNlW`lZtXgs8)HJe-+FuFPopianrd72~Na0@0o|{ z{tAPpcsn|tDZQ0%60zQ~iF1QaGwz^|XpS~+5;1VGS#9x6e`w*#qsEi?-g-p4!<^lD zyXyxt>?FNaOVP#P&yy)MujU2ggOtr9yH%+lr`4+9ueUM7{`Jd)LTS6w=O)G(qoftA zqOr~EBV@}y&!Xo*NKBGX)xH#DMjR>_XFC7V5A(w zb-NSd7{3<;{<-}$=wZOG_qK_&C?&>9mPo@=+Kd&J2F;oqeEJ~pSH3c``k-f*|HUbc zdHf`%0Z!>J{I`#^0ie3OF2p_hXqnrXJj*{RP4HQ?if81MD%T~jhuW1zo**a72C~S5 zDcv01fHsD$R>rDf` z^nZEMfFBKb(f^wd{a+sRzy9;T-ZS7e1Ag*&Mc7SIG_;vr~mjNExzy28Dg#kX-zupz#69HZh z;L8Ah%zybXfCmHkFaPDe{Fm?Y|LUy(p31*I%D)~8;GY1V#{a9I@vn~o_zZx*0Qd)h zcK~<>fIk5E0RQ&;Ko1Y}?f>@aKz|PO(?FjL^ua)n3-qx--wO1pK!5pfZwd5}K<^0j zi$G5Z^n*YT2=rV)Zw2&HKz{`EH$Yzl^e{l*0`x3EuL1NJKyUGHKLPX-K<@u3xQnlf6D=ZoDIm&fV>OH zpMd-b$bo>o$0Q0DC{M-~YQ; z1A8>EHv@Ytutx%W9?!|u&-ix_0G``{=WXD57So|{{UYoH%$Nl literal 16160 zcmb8WQ*@ng+^rqkwyh>jnxsL4#)`&)c}=08B7$HbARxQY|MT@fpElkFH(YVzllBzTzeX_kifo?`EU;^FVlctFCR;Gt zVO*!NUR^kIRvaVO41_6+xzcPAR zI#^)SH38|@5H3U9xz%`P$Lw}BTEL+2xWxKVrYHRKYWIzS>kmVV^A?N%XRcP^;!i`I zvsPEa#fs35lm0ncQoploec61(zBGPt$yy_BB+&IC53NPMzg^zTd}SO4EHZ zjF{6jaIFXqQCJ|64;|3G@eqBj1NdTyy{SD+djC`g>uWglue-&yBe?MAbC!+;#Cx|C z6?W>qUjJwn=fWzHQOfFe8a)v%>=nQ(tw{)gc`Y#$9{h&0c}UOEzuD^BSoY~djX>DV zD8nRb{1WNw=SQfdnKKN9qy@+4$OXFl2o=(d@$PtXKaNervM(D%U{gxq2#$Lfptdo+ z&So+wFDpxKfGu`glWF4S#J6Y{5O0V|C|vzkd~FPgT|BC4WMjsFND_k-U|_y3po8i$ z!?qXu;~Jd;VBL4$g7+W_u$zi;krq7SKWQELFf<70!Ve+l3oaC-HMQ&|5L3$Cvh;5E z@e(zO6_zeT8Fn+?yDXPKG?9Cmg<5Y8sK1g$A?>tX-}Orw zeJ~#uwltVL+4b$BMHE7 z3OgaWj*=3#-BP&JuD6mm{S}eryCe?7_ABpFD?(YyUs-tS65;p<h8} zuIy3W84<*hXyDkGp0_!=1k93-znu#{=~uKeYTlB*ctLMn9ga^r6cGk6&S^vfT61um zxqF+)yUXzv299U>tx{sFemWS}ziN%iKF(mx$sN*53taJR<2a@|XCcdk3_ckbZ73nm zYg(f$j={+a_jM^4aob%b$JcA1^8yN1qD}3jH~8nEd4#sPCLxU`FAZn>;SZ5;O>M=y z9PB4;-=P}#_7Uj}rgRr$e2e1Ue72UnJKtzIEo@K&wsz@Y<>iCb1P;)?AN-ot_E4E1 zW(a4wB;arQX(0vv!sZs)8xO^rTb|IZtsJFf8xs9Vc*cjo_T<50elP@O;un zkvDeDI5>j?tSK7h7H-2_Ioc*Ns0;kd7#m>-7gYjIZD{0}b8_sRk0ZWDe@wh*HH&el zWzPtoX=ceI3hKVxI3EU0gsf){9kma#rh7D~ua7YS+%lE1GhTDFJ{>-~ccv#H12c$T z$s`7(XWEytr8}R7f_4zPZDrgQ0P~TX2KXIcWXM^PMWWw{({|%@r?&-q`P`+V0#TZ? z$E(^fiWpQ-sfjBQf_%;_UbBOuvr(H0Yx#4mpNg8>XC<0wz}x2EVL`?o0`ut7vyPtm zZb-_}S{#43gQGAp8JG}xXatNCwi55d9MZeSxm}K@XTpZ_!71mv&e5w%iexFp{!~P+ zmm}Xf;C;T2Q`MQqLFZQISKxhaWoFr6V{KvF*b!}4Sytbud*y&3K?Il|%-C;E$(Ia} zN@IE8R$!%Lb*|AEGvYWYo9ILz5)bOHi^HX z@bcTwWRU@AY?O$bRZ6JQNHYU*S^d-v~_Dcmn-jD#9`;VJ*QOSp__;Vr_HCO~nH z!LR>Q{lI&nYR(z#s1`0LoBRj?I{~)ZC1MCx!z!EVApg+HGiQ6{z6KWF<%X(OY-=w| z4cQP;8kcvT7q@~gd7PT$`;*ifC9}pQx8VWV=WSoBsKRbIuV4H}qUQbrODx71A8zjN zAdNb5#<~Xbt-9&OkjyK&m}EB?$ib@>JPcuzM6TF_x%5<5fyyKk2(4u)m{>xOUFG$2 z-ek?aS??!EK3BG77%oUb*G-m?>ScOUCBk>k)0s^ltV_xMvi~!5W{~YBbVG6uXvOVI@bTEk&V>e~vpmpu zy0m2x-N%E!EB<*<)hjeS)Q=i<6SvLWV9<;EX zjh%=<>CmRjOM19|N-`WAtmrgRUKQI~nCM#z`A3@2`x9ms=<`C(0i14`mLk)+YR^af zO)VpN3bA|uYwQ!}lwodc2Cq2PeVbLXYhSb&9u2TZ0#W4>$;!OKedNHz?omGD5Pf(} zgs_{l=rRZrFF@Kxe^(7YWqOzydyCAw%LC3)YIKBLpdABXlvA}$N`Hb`7TATNCpDPy z?1b80Eyk)R-}KIic?Vs&%e~`35QLFNqtDUZQX60Iry}dg589a?fViMl6V87MrL_J| z`Un#25p#C4m25TUne%>Iw&+knhhD_7dQfJnHm((hy7NxyaJndxy74(q+kX!@z@<1Y z_@o`D5UV8bwN|OhpVV)+Ed=OETJfT37Ox5rJv*yEkIZ@9{~%(|_>2AOVzR zG_C)})&KC7o8?)lb9cliDM)5RuM>G&;5+o|@XJPJ!w(Z0YGR+R@nn%h3@X>1&Mp_D zuE&vth?=#X=ExTrX2Y(0Zyz@z&YxT7`5mn20f-$!O480EbTwEdCriU~#a3+%lo&EH zPS`RNKPKzssp3u&u76ul1y({TwJ6z-3QzfeO$LM5a+|YYy zFE>xF(Y{~4nzJKkPzo5HO?~Kp#c+o~c4gp+rx~f*S}l%pSU&a>VzUy-e_kYPX~A5y z0w|@reW5&_Cjl_I7an8ZL(J}c28hd1+D*%# z(_j{Vxr;6`eKG8F1(PiII1D=0(K3UGt~IIqu?Ck}3-FfDckNyyq_YN$u6o#AfJiqD zinSdz32GiKErqp*Cj(#}oNBf;%{>yXrE)nlL*Qc72dY!so%%C1)dTTQlNJ8VqXnWJV zDM}@j7Pfm7#12B_YlC*60VYBW9zE5k)&MN( zQx^C0u!;pJyBC8Ckrg=&FiH$YaYkR|ydt8N^|}6wF2LQSNs$aIiN@eSi>r{LF<8ZX z2%*gGM<)c@q&0n+TvGFm{@*030%0)jOXKOQpI&pD{fRg9@UJ(W{;0l+10SqIVLzHY z3zJypd-M$~MjND~YYxFE_MisPTSWpXyDtTjyvk>14?$O7tu=j4Fzymc)N{qILT7#j z99@)Ye9xL#7&1ZYD{?K?>YkKi;&XU>`B3@Nzm6+~$>MJPr~4dWe_E#LJ;-GjO8Stc z=%}qQKr?4XnqT<)e_0u>?TR~gsWQy(a?mt52V-P-1?!E+Bmg?Ok@OUa^Q!|C%onrz zK0R~;5G8iIK-+F@lroeIyki;dxDOY??4egW7NE+9CIb(xS)?uMueVV`7#Dz7$NO@R z)ZnNGer>M?Z2{N-Ctqp&c{<)1xDKlYHu_BL&bep36}fT01H5R1-(GeaVgQJsxX2~R z`qIl6SWeg-0lA$;h!}(gPJ#rmeDSMC7MczB6h-9zwC$P8^_1R<_gAZgGK)p!0G~$0 zzeW3EHAz=yI@dP_B-r!AGpx{)oPx zi4(71R3$@$dHA7Tbjc-ul|M3mP+@frrq$11!{mGpn~Xz2n~yj+#R*B-NwdS@kUNQ{MO5j*e$jz zm|JK{NBQ+Y1|u&2W;|@ABTVPbxx>d+k{j#W&Qc*PDt8+?gMC|dIXl53iPlMqakMT_ zkFI4I-$L^#NW1eiNG<7Vg;QNmU)lvPv-F4Jfx;8dbK?3 zx-}mlfb}N=<@@7mp_ErhOy zUx>4<1`W$>Cyg-3*L|o2o8v-;Ef$!YNTq^v1*W!fNkZD^4+i^$JX7+Ebd4VIW9(kL zd{COmOhS6FC2&5&FkI0f`8qUAgUu}p2R=bDb}Sf9H+VtQ%~Dlp!kuy_LHz0*b30E4 z5^t`YmAaCm%DyaBB@$2Y=rx-U6KcZS7Fk{sQkiFX2F9)!4ZpmO%k|k1(g={sa5DLP zkH{KgJ5_>ZP%7r z?;sMT4O5&n>U~mM6Frxzj;vAuAq!P(qaR+uvi(5Ow&6A4BheQ$IFBEXj5dRpOYy=| zDdBFfzfRx_?a==ctW~78c%l_7pGPbT1p_UTm8Anv#|I-(H|hiupuCps&x>DQ*bail z%fOCThlH0|zp@6hV5%2?Y9sPK>r^dQDDpfgJ^&2l8T|dEe@+9isdE*-Sb#o0sS*JPgWcn2UG+Xhdr#?UwJ2KuKZ z(98z6pJE*4hJ(_{caA)$hZ$m*eT@_#sV3$_cAsit>*|d6!4)4&fpPpoUjAIEwSSAB ziKG@?sWHz8gr-C|5S2b>5Yibal1959e>-L3Y*h^1v+HxZbbwv(<$XmLy01KLVtqwl zCo_uyft^N^p7D>pKGYjnO#S}G4{twH64KJ^BRS@jN}E-4r9O$4|9@Ni13B zT%2}VW-w3|`WVe1G0fy_O?vI}h2Uy=h6JBJ&3F5r&JS~?W2f1%I3)m0X{mFvn7iTT zXyX()7VH}2yHbdu$cBY@N^2G<>;(n2eAaa|Kawptb!mo9yFu>ZyEmyqD?F|g zCZwUIoH>)!!%pwzy%8kK%+~AUW--4FQ(_}Lx)5cfjHjE2<^(=*lVC9iA1aQmKiKG9 zg#?xB*f+Q*v3=5@k(Vjj4X5L+~gb)Wz}lDj^71(+yH9^nGsbw|H=bwG=x>Si3oKw z{N*!SM0Pq25CYRypIvHG`nz`92L^g#qh+%HyINs4GC&6LbIU7wenx+}0HKc8Bra>DF-2ZND0nW)p>mwXWSrIvH0-1+KS!`MSzC@Ibb! zuo1S>bNp4Dm&C|{T88GG&1CiuSpdK>yT&{$?1lc&Lu_Qx+kW?erY46+GsjbaQ|~V_ zKgJKN0`Gs&{f5fv1Zd@e4NanTIu9@cn>{KoPx&68%JWULfTnq80XrTIQP@2`#~X-s z?vqDsJ$pF)ivmqOK#T5I`l*_b@rr{#V(Bl_o&ebp&!u=Uay25cuxvC;3WSD=+9>GequgQ_HOm;JK{U)EfM5r zfz4VBZ48V@E`O|k5F+;uhoZ;O6_-DD7RRz8Q~}$XE!Q+YP=6U5Woj001;%zAt}uX(6>~^CEh}sCf(h!x9_LLpucjNHI zR9(piT{at!6CmEF*Z?XH{7yWP#xU6+@JOSk+#EumA$v-3=XY-Zny@wPOzP6$)1lM} zKF}tL2)oHvfGBtXVa<|RMuNf+Em1-!#yI4aLXUi>swl80vYK1>&NI*FBrjTrwudiv zD1c*$nWHk51uG-vR+@QoYnvNYBq}WaVA${}dzBUmUP#`In0y2;f4{@5G|A1IINsSa zaP%#cf>3$|y&!fcRFA8b;&MvkkE_pU!MO2RiRVeq`A)j?mlqlDioM5<=z@-&_o&UY zxgqu%=Fix*W)h8n(xZUD{vnFT!PCOU_@S^(ek@ghP$`tFHLDHVLPt|4L!pJt(B|%n zpXp$kZX(Nu*$}v|JPN;sr1X=R0iqGHDYkuJ8mPdiz|a-QC#PT_a~;872HDcRC=Z4q ztoRFK4ubMMy)Is@cO%joN~!GaGhOP0io5-3#(@JtKHRj-QH1YZgWMY?{oSLhx!~8- z!ku@-ZdY^nt}Yv4{%HRd$5I?vSp_Lb`X!HgpObrfQ;^$%nFrTTl@75?121GQ z$0Oc-zE&TFn{d5A=#5Btis;WXQMJl#LGA0T`&x?dE{ti|qVM`QgnjUgwn?QcQAM{1zpMDw3Hba}IzgFL$j9i$4yA zIc=5ok&CVhTB6Kzn+D+M3}$^=WVWqyW4Vj zyEt?@+3?WVuDz0rx`Ua6Uq^Td-YbT6bWj=nD?|bsP2FYPM1>%`1p&oWl}8p%fuo`r zg|lWX>em2MvK=+oS9si)HqAhbK;B_x^Mrp~>38qrseK<+;X{6-T;On5;w1T90Sd z692*#x6F#U>ruB3how%9L>JqkB@tl5;`=iNz^|qLxk@OHA>r4L= z!@-4I9MX?AGseXLjeFwQ-mr;b-pn&Kw$U`wM|OUS)Mg|31Spq^Ama!$Ne->bRo*As zEIkWHjQGcOzb;PWzuQb7v@?b&Mj_u_N}Q{WED@?e_I^yN_fvUYQiL|s{egpFe?T{d z5;1a)Nt@@~Y*-sXZou35Wr(L_>GI1 zzhgeS8S<pwdd%ooRlkBXmG*b~&7kCEnxU8uL6{Va>U2t=2J?uDJ6(fwt=j zyC(2_(ai+^kXlz*Jtxm4iG{mbve`j&r;xpRX@sXK1-W*_Zlug!^`PJp5@FU{7tH2(^RB zXd~ixD}B8uZFlH+!Yq2*Q$?D5;&Gjd;jMS5mmpUXfhq>RCzLMC#W7@@vVHv5eZm|U z)l7<6O8>8WR&I;*x8&2|V4PnGIk#fB>y!>ELoS~ep7CdhJt734Jh@s5l{&e zhdb+E;Ml5(WL@HEMRAQDwam8!cyXXk9F*>%x6xRy!CllvX-NI;mNFS>v+^VYV0+Xg zoS+4|Wa^q`*&gcwPS%y#3B6Uk1I$;fgRa9ISogfty=sI8;f~_54vqf0QzTAhV}%)043wHH}R+7>)&ue3(boV;BzVIK`;xmRMb}c!(mReAIA`T7`{dTPG-$>gWmN zl;Dfu%ls{jH%6ky=&;iP9DSMCcY{y1y)C0)BLe&*FxNGrL}Ks)+k zL~AAuD(B~#Ai~p^K5CuvvLcV|GfviQ%yZt_+I(E{!n7$S?YlC{NRTd$(3n$s^O=b7 zaf+!Mg$5JLsOnS^IB>tV1u|CJQ>F#lktW@5E-wUEg^7QYt6qpt(7euya~0K~3Z~x% zFUd4>fUF~=7Ipk(a)pGAc*<5!Q;fNA;_?LY#bD>9WYb{(^f+0f#WV9=;gpHcGYxcg)bu=D>EoPWl-_73HY-sZVbxwa+xs8%Bvi|#mmdy z;XUVZe-Uy*>%;saJJO9bua^zLti$offgRPJ})7gy>Ur`uftK+mxL*Z{t zmXmOY|D|kw^EY}ji-DQgfZ4Op&$tlozDy|pQtR4<-)*2H6&goh%idX@ZRgM3S6;oY za7YH?ixLn^j`Lr=37P_q6BnNuhlCZcVq$ACqmhr|M=S1w`{t%69^H&3P!UYhD)O6m zjup8}^G&_4&ru%MKj1MnPz7`O9gI^4A+sMlX zVQNnxG`%m^%cXfcO%$a8@!?|b=Qk{@S(x4ripE^h{06@=MU^QrY--~Ws+2`t0|bQK zbO+Q9Ki-jb6wje>wd!v(+F|R`U>7yhYaW&-ym#nbVx;sS*#YqzSKq{&6YaAa2}s_e zL_cuKI}I}T+NoA@f^cc_wbjLHXYSA%bdP6Ts;^Nl)U(Y$L4$P*a(Xt!AEQVkRlbiR z5)gmL+@o`{f@_-5N2Jeg1@`7npWcq5;8ov4+f~;zlqhSwC*|I1qG-Gug}rx4g0w91 z5DM}NDnaTxPK4)`m(T4%5(P~R%ieI(l(BC`$GZ2O;f?r0Fq!&0L>_k9eQ6`vmQX@C zGvi6oH&xD-WXh-Pb+(yU2Iv-HaQ>!0bB39qey1IHLpR&%D6AQBH>m8aH@YdZngWnd zkc*!*eSn(RVvCrK^mcBq=9^c_#9IcyrX;mOZ?-z;Gz&$UMrb<*p~MLFl^$PzVk{wR z#LJD%4>uh{Fjy)>K29)Qv}(BOm})p&e9248zwE)RXxkk|^m9bfmFsRh-|UL9$!*73 z_G|=PEMc4@h2L(xwod^pAVBCEZ( z`S$SsptLfl((oG^u9gfVE%9rKJmosi7i4R5f~~_C_~iY#kYlQjhzO{B!(-TVGF)Z8y&!fE$GJc zpX@A@3erKd3r&;8NxL9*6Vh*=fAo{i%b3|on30O=AviqCvn%8;fE;bjn4ii^^=53O46^5T_%rR3-$3A<=>a1ZVQ&V0f09!47|Iw ztbd1Ebxr)kqfSh^E-`i9*+fp&Loaice!QM6;G5K3dOR6uz(0zZxTn?PvO)!{?1Axa zqJ$s5x`j##JC3j&Z4!uq`_2Zcwm=AJpmiRyw+_)iqjs6LxaE9fh?T6wX-&qPn6_2n zip7$kgE31v;MW`sKx-9p*a|kvIlymBOV|@Y61Q3B?men1XP!0Mv}D92C?nq5-mQ_6 z4EqlEvO0`{af|x)$Pu^3(oRJaT z&W_q4y{MCgn!(P4UcT$Bf8&^BR!7FW7)+!bqtb6v{eF5+BnoNfAYE9v_HMK~Ykd9g zc#`9&0eFx{=`_0Y2til6zMNSJayv>%>Ou02mn?eG*IM7H0`J>5GxO7%UN-fxubs$> zh6#x6jTUOPnynJt!s{B-4OCeNN@5T`7n1&*?{)EmT89i#xI9!1q*@p;#0^p+5xWacP$N7of_4u)}cy5mlh8C2&DcSM}aR@@>?F z<1jw@q@*_19bU$w%k-=b&HYqq z?liigm5kxi!c>TE;_;{cVhvn0St=RGtTca*>xRAgPBg6i@c!<;`SqkSa)41O2m2Zg zE?hB+_Ile2{N{T#tt0mLJqGPzvm(|*iDXxXK?g~~$$ANid;vMQ*o25Q040J<-aQ`E zKI}U~D|O}h`y4K=cPztA#^KH8P~JO0BB#!OS2vThc8zGveHA79$J^idY;?cxtK(O#|6A%NHy0>9v-W zp!HY&p=q}C>Xl91dMGqkIK?T$Rq0e#TV$j`0k#HCfK|x9-3r#)^+iB zG@L)hU7d}r7IfEBudJld&0uobbX!^DRr!NDSB`Z(FZA@B)dm>0d$KPpK6}a4+R^j- z8y^Y#MH9=YB!PCPcbDuJ$n;Gv$YWw&;c!^XX)F0PVXwzA7TithaF-LEj_s&YKw zN|oD?e;!G8jyiF{$G5p>_6u(`MRwJW7zBI@&4I5bYDnJ!s%2&DaRN76eKElKUWd}8 zFa(NkaP5iMO*vx9xHRoNp(iv9S56oo5@wa)q=**#lj;jE?x1YcH<ZNfK zu<>6Ena+UMo|7PCM8O-JxiDQfQN92#uaT#=tjNIK++wbezUz zve#~Q@Fi|T?9gB*j0L}`Hv4?QW-Q6*;-s#Dy38yP33Pz)qRw!z{^DVVW9J!zN>yR} zgpePB_h8d%i1&Q54)-s$)p1_@eMFVw3vLw1GH#<{s~xG2`dX6Ik48A!kE}D^^bq{Z z-hbv#tB(e>n~pq&vnIF^HZ4tp(5qmF(;UETr|l31C`pZ`8yQ|OWls9J-En1+3$EKU zYRft0zfpRux;O5eu!E2-5YTrpF?|VXzbYyiL>TOwoGYal!nCLAHu(aI;Ga;H6#|Ob zuOGp6m59+YCtKPg@+^18kIY2RBII1#!u?`O)BK>@YC3otf_F(T*Hntag4WF$coHCC zQ4adm@Ho<&6Rl!RlpYLCcE|eK-R!o*6qnwta*U&`<9R&h8hzT=vFT7y>gvhxjkjy4 zrV)q{N`H@Is@y(WO>RE0rFK>(YMEY%8lYpP!8ui(>IwGni`k8$?NrjrRwqyGa(6kd zCX7JCJdzOr9KIQB;wqZ9dA;VJf)k|kM$bAnVLAKu=8lZ#JS#GiNlXO>$RDcHu6x$ytCg?rNQM9NcXAZXj1494ttXZ~xK0XQH>KlcHubZ|@qz^xtQr@DEIanYvO^Eigfw;fM-gpe)yTa2dS<7lbyF1BX<9 zSgHAuRLD}%pomY2!9InrOZaxuVt}XGBBjkgm8FC598&0MC%Q@2n7>^*`n$>Yy_*Q; zt#bdMqD;B^xcFU`uOGkJY&r8R?j-{cKNUB*>q1s(`v*ZQeXBR-D1hyA&u{a~-9Coe zZW9Z1q5D4Qno&Pr=gLgegFZtVCkb}S;r_LOtJ!WRG;hZApTJnR?n|?6#Xxg~HGKS6 z*aJAJ6VnOHv1z>0MXHc&awP_)uDkzglfPx>I<&jKUNEp!r6w+qX$3PeG?lJt zlBi90ySIYw1R z%9+v`-gSDDZzsEh!-u1&>zuw=CJYUM4@E}fM%DbX@b~iM_w#aS=Z?m@2Y*33 z8H+mmIm*>zp&J`a#&v|M%FYP}I~!7>A``f}aU%)qwrMopPoldeC;guA!k?&?5IJ=H zdo3{f7WQ8xO-`J9!AcTlFP*SA-hZ03<3o%{Cs^mfBSwkzw32o6Thf$HQ!`j~F!Ae| zchM)QvFo?pAm!(hv$r42@vT4Atcg;G;j%Wg$%7wOdLYzxjew`CtJO0jr+jEe9+W?l z&PSP_+GlC#R&J|S`W^M|f2}>5)LrYDBv9e7XE|6<0q?h@p+DpgdS(Hb`|}Q^-npd% zwYSh;PBj5WrlB5so^Of_)fH8MMCBFn9VHBkQ6BVTc0^p_Q`6mMuKbi0bnG-aa~RU7 zwC;{RJfn}c`Uck7^W(<4grh}vEYOw{mXN33D3S@UnVq!g}{oZBM9xCs$5 z17n>x8hAmAXejYau04ekNVylBY0W636@Xm|8oD7pP=a(Sxl3OcZz7UYop+9f$EWY+ z!qqGG-lHK$p~KO8w-2ZQrQB3NW9a_i=t~iri;}S}CZQJU=oW@=xw9%;wEMn#c}+(Z zmWV;G)$zpKNiL5vl`BUaMJOZOC#6Lp-Qjt^B#hO0(7skSGjix`Jj z?|iS^gpIfF6m$=%|vsK*1VQ@pZ& z#5E&|)%uWxH9du3^}EOY5h1|y)=kg#Mc2X&+bIdu_{puu#-(LXYwx=qCBcWvWGq_U zZ@9NX9|Fh5u4w3%l%0>%F39gUHsg{Z1{`7+B}vw*ww$~(v8K=<&LM6%d#U211=fGE zS<+|=qsJ-kCvvI+=bb2gb2*T1gg&ynjG`S|(ZQ1`&cdI}woV96^ye26ik= zy-o@TGDIv;hrL?X0%j`BG#|6B_+|0MC;8-MVw8DhHNc(bhh(urdm}m3H7vGuchFJg zq|lQ`AbE@cTF3yGl4Wn@Pl*d=+%*uW0}&Py|Dkm?Va;P`t>Y^!iikzr=lJyP=NS2W zXoxLNgc@P$7gS+&?9eO4^&tM(rW3x`dKvkwrYrBQ^k-K!lsK3G`dI`76@I79ZEumW z8{~?DRBe}jgul({Lkoq|gz&1UwwLxWs)vxK0r=;&ujw$CG9yT}hI0awBuVNYw2<4! zi_B=^IKlx!9e9EEM7v$1H(#^gMe+=Gaty_QUDCfhBVb?j?~VxA4gJ6Fh5p?M0lOez z4+QLhfc+1!`}wcE53uw3-*!F!+nxv5@c_FRVCMqtRe&7_u-gFk8UOAvfc*rpcK~({ zz^(z<1pr<@;OqbE%L5)c;Ew~|IN*f?UiZHqH|PKLumR8dUvC=lrT@#52K;Eii~iqy z=>PJd|Mj2$^_~H*8Ss<;%QFVNV!-zWd|kk|{V%^3@MQr{_Fpd+@L>V(^>K2l%(& z2YPs*Z~wPX2l{iMp9cD5pbrLmT%eBy`c|M%1^UZ>drP2)1bRoHUj%wWpdSQ!K%nOW zdMlup0{SDMzXAFhpoana7NBPVdJUk*0D6mm`w5_z0CN9-bMk+4Zy=ZcH;)E#Um)iN z^4ov&)&DI|1#(g#_XP4sAZPqHPXzKpAQ$}KazG$w1M)K~a|K=J0<`zIs@oygSUpd5o Date: Mon, 18 Jul 2022 10:01:43 +0100 Subject: [PATCH 03/86] Efficiency and naming changes. --- CMakeLists.txt | 6 ++--- dChatFilter/dChatFilter.cpp | 44 ++++++++++++++++++++----------------- dChatFilter/dChatFilter.h | 8 +++---- dNet/ClientPackets.cpp | 21 +++++------------- dNet/WorldPackets.cpp | 18 +++++++-------- dNet/WorldPackets.h | 2 +- 6 files changed, 47 insertions(+), 52 deletions(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index caa61e4e..a9218bdf 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -15,10 +15,10 @@ foreach(variable ${variables}) # If the string contains a #, skip it if(NOT "${variable}" MATCHES "#") - # Split the variable into name and value + # Split the variable into name and value string(REPLACE "=" ";" variable ${variable}) - # Check that the length of the variable is 2 (name and value) + # Check that the length of the variable is 2 (name and value) list(LENGTH variable length) if(${length} EQUAL 2) @@ -83,7 +83,7 @@ make_directory(${CMAKE_BINARY_DIR}/locale) # Create a /logs directory make_directory(${CMAKE_BINARY_DIR}/logs) -# Copy ini files on first build +# Copy resource files on first build set(RESOURCE_FILES "authconfig.ini" "chatconfig.ini" "worldconfig.ini" "masterconfig.ini" "blacklist.dcf") foreach(resource_file ${RESOURCE_FILES}) if (NOT EXISTS ${PROJECT_BINARY_DIR}/${resource_file}) diff --git a/dChatFilter/dChatFilter.cpp b/dChatFilter/dChatFilter.cpp index eb6674a4..6389623e 100644 --- a/dChatFilter/dChatFilter.cpp +++ b/dChatFilter/dChatFilter.cpp @@ -37,15 +37,15 @@ dChatFilter::dChatFilter(const std::string& filepath, bool dontGenerateDCF) { while (res->next()) { std::string line = res->getString(1).c_str(); std::transform(line.begin(), line.end(), line.begin(), ::tolower); //Transform to lowercase - m_YesYesWords.push_back(CalculateHash(line)); + m_ApprovedWords.push_back(CalculateHash(line)); } delete res; delete stmt; } dChatFilter::~dChatFilter() { - m_YesYesWords.clear(); - m_NoNoWords.clear(); + m_ApprovedWords.clear(); + m_DeniedWords.clear(); } void dChatFilter::ReadWordlistPlaintext(const std::string& filepath, bool whiteList) { @@ -55,8 +55,8 @@ void dChatFilter::ReadWordlistPlaintext(const std::string& filepath, bool whiteL while (std::getline(file, line)) { line.erase(std::remove(line.begin(), line.end(), '\r'), line.end()); std::transform(line.begin(), line.end(), line.begin(), ::tolower); //Transform to lowercase - if (whiteList) m_YesYesWords.push_back(CalculateHash(line)); - else m_NoNoWords.push_back(CalculateHash(line)); + if (whiteList) m_ApprovedWords.push_back(CalculateHash(line)); + else m_DeniedWords.push_back(CalculateHash(line)); } } } @@ -74,14 +74,14 @@ bool dChatFilter::ReadWordlistDCF(const std::string& filepath, bool whiteList) { if (hdr.formatVersion == formatVersion) { size_t wordsToRead = 0; BinaryIO::BinaryRead(file, wordsToRead); - if (whiteList) m_YesYesWords.reserve(wordsToRead); - else m_NoNoWords.reserve(wordsToRead); + if (whiteList) m_ApprovedWords.reserve(wordsToRead); + else m_DeniedWords.reserve(wordsToRead); size_t word = 0; for (size_t i = 0; i < wordsToRead; ++i) { BinaryIO::BinaryRead(file, word); - if (whiteList) m_YesYesWords.push_back(word); - else m_NoNoWords.push_back(word); + if (whiteList) m_ApprovedWords.push_back(word); + else m_DeniedWords.push_back(word); } return true; @@ -100,9 +100,9 @@ void dChatFilter::ExportWordlistToDCF(const std::string& filepath, bool whiteLis if (file) { BinaryIO::BinaryWrite(file, uint32_t(dChatFilterDCF::header)); BinaryIO::BinaryWrite(file, uint32_t(dChatFilterDCF::formatVersion)); - BinaryIO::BinaryWrite(file, size_t(whiteList ? m_YesYesWords.size() : m_NoNoWords.size())); + BinaryIO::BinaryWrite(file, size_t(whiteList ? m_ApprovedWords.size() : m_DeniedWords.size())); - for (size_t word : whiteList ? m_YesYesWords : m_NoNoWords) { + for (size_t word : whiteList ? m_ApprovedWords : m_DeniedWords) { BinaryIO::BinaryWrite(file, word); } @@ -110,16 +110,18 @@ void dChatFilter::ExportWordlistToDCF(const std::string& filepath, bool whiteLis } } -std::vector dChatFilter::IsSentenceOkay(const std::string& message, int gmLevel, bool whiteList) { +std::vector> dChatFilter::IsSentenceOkay(const std::string& message, int gmLevel, bool whiteList) { if (gmLevel > GAME_MASTER_LEVEL_FORUM_MODERATOR) return { }; //If anything but a forum mod, return true. if (message.empty()) return { }; - if (!whiteList && m_NoNoWords.empty()) return { "" }; + if (!whiteList && m_DeniedWords.empty()) return { { 0, message.length() } }; std::stringstream sMessage(message); std::string segment; std::regex reg("(!*|\\?*|\\;*|\\.*|\\,*)"); - std::vector listOfBadSegments = std::vector(); + std::vector> listOfBadSegments = std::vector>(); + + uint32_t position = 0; while (std::getline(sMessage, segment, ' ')) { std::string originalSegment = segment; @@ -130,18 +132,20 @@ std::vector dChatFilter::IsSentenceOkay(const std::string& message, size_t hash = CalculateHash(segment); if (std::find(m_UserUnapprovedWordCache.begin(), m_UserUnapprovedWordCache.end(), hash) != m_UserUnapprovedWordCache.end() && whiteList) { - listOfBadSegments.push_back(originalSegment); + listOfBadSegments.emplace_back(position, originalSegment.length()); } - if (std::find(m_YesYesWords.begin(), m_YesYesWords.end(), hash) == m_YesYesWords.end() && whiteList) { + if (std::find(m_ApprovedWords.begin(), m_ApprovedWords.end(), hash) == m_ApprovedWords.end() && whiteList) { m_UserUnapprovedWordCache.push_back(hash); - listOfBadSegments.push_back(originalSegment); + listOfBadSegments.emplace_back(position, originalSegment.length()); } - if (std::find(m_NoNoWords.begin(), m_NoNoWords.end(), hash) != m_NoNoWords.end() && !whiteList) { + if (std::find(m_DeniedWords.begin(), m_DeniedWords.end(), hash) != m_DeniedWords.end() && !whiteList) { m_UserUnapprovedWordCache.push_back(hash); - listOfBadSegments.push_back(originalSegment); + listOfBadSegments.emplace_back(position, originalSegment.length()); } + + position += segment.length() + 1; } return listOfBadSegments; @@ -153,4 +157,4 @@ size_t dChatFilter::CalculateHash(const std::string& word) { size_t value = hash(word); return value; -} \ No newline at end of file +} diff --git a/dChatFilter/dChatFilter.h b/dChatFilter/dChatFilter.h index 62a47242..7e7dd859 100644 --- a/dChatFilter/dChatFilter.h +++ b/dChatFilter/dChatFilter.h @@ -23,14 +23,14 @@ public: void ReadWordlistPlaintext(const std::string& filepath, bool whiteList); bool ReadWordlistDCF(const std::string& filepath, bool whiteList); void ExportWordlistToDCF(const std::string& filepath, bool whiteList); - std::vector IsSentenceOkay(const std::string& message, int gmLevel, bool whiteList = true); + std::vector> IsSentenceOkay(const std::string& message, int gmLevel, bool whiteList = true); private: bool m_DontGenerateDCF; - std::vector m_NoNoWords; - std::vector m_YesYesWords; + std::vector m_DeniedWords; + std::vector m_ApprovedWords; std::vector m_UserUnapprovedWordCache; //Private functions: size_t CalculateHash(const std::string& word); -}; \ No newline at end of file +}; diff --git a/dNet/ClientPackets.cpp b/dNet/ClientPackets.cpp index abb08688..b9f715ad 100644 --- a/dNet/ClientPackets.cpp +++ b/dNet/ClientPackets.cpp @@ -288,7 +288,7 @@ void ClientPackets::HandleChatModerationRequest(const SystemAddress& sysAddr, Pa } if (!receiver.empty()) { - if (std::string(receiver.c_str(), 4) == "[GM]") { + if (std::string(receiver.c_str(), 4) == "[GM]") { // Shift the string forward if we are speaking to a GM as the client appends "[GM]" if they are receiver = std::string(receiver.c_str() + 4, receiver.size() - 4); } } @@ -315,6 +315,9 @@ void ClientPackets::HandleChatModerationRequest(const SystemAddress& sysAddr, Pa if (res->next()) { idOfReceiver = res->getInt("id"); } + + delete stmt; + delete res; } if (user->GetIsBestFriendMap().find(receiver) == user->GetIsBestFriendMap().end() && idOfReceiver != LWOOBJID_EMPTY) { @@ -344,26 +347,14 @@ void ClientPackets::HandleChatModerationRequest(const SystemAddress& sysAddr, Pa } } - std::unordered_map unacceptedItems; - std::vector segments = Game::chatFilter->IsSentenceOkay(message, entity->GetGMLevel(), !(isBestFriend && chatLevel == 1)); + std::vector> segments = Game::chatFilter->IsSentenceOkay(message, entity->GetGMLevel(), !(isBestFriend && chatLevel == 1)); bool bAllClean = segments.empty(); - if (!bAllClean) { - for (const auto& item : segments) { - if (item == "") { - unacceptedItems.insert({ (char)0, (char)message.length()}); - break; - } - - unacceptedItems.insert({ message.find(item), item.length() }); - } - } - if (user->GetIsMuted()) { bAllClean = false; } user->SetLastChatMessageApproved(bAllClean); - WorldPackets::SendChatModerationResponse(sysAddr, bAllClean, requestID, receiver, unacceptedItems); + WorldPackets::SendChatModerationResponse(sysAddr, bAllClean, requestID, receiver, segments); } diff --git a/dNet/WorldPackets.cpp b/dNet/WorldPackets.cpp index 94792c91..54c925d6 100644 --- a/dNet/WorldPackets.cpp +++ b/dNet/WorldPackets.cpp @@ -188,28 +188,28 @@ void WorldPackets::SendCreateCharacter(const SystemAddress& sysAddr, Entity* ent Game::logger->Log("WorldPackets", "Sent CreateCharacter for ID: %llu\n", entity->GetObjectID()); } -void WorldPackets::SendChatModerationResponse(const SystemAddress& sysAddr, bool requestAccepted, uint32_t requestID, const std::string& receiver, std::unordered_map unacceptedItems) { - CBITSTREAM - PacketUtils::WriteHeader(bitStream, CLIENT, MSG_CLIENT_CHAT_MODERATION_STRING); +void WorldPackets::SendChatModerationResponse(const SystemAddress& sysAddr, bool requestAccepted, uint32_t requestID, const std::string& receiver, std::vector> unacceptedItems) { + CBITSTREAM + PacketUtils::WriteHeader(bitStream, CLIENT, MSG_CLIENT_CHAT_MODERATION_STRING); bitStream.Write(unacceptedItems.empty()); // Is sentence ok? bitStream.Write(0x16); // Source ID, unknown bitStream.Write(static_cast(requestID)); // request ID - bitStream.Write(static_cast(0)); // chat mode + bitStream.Write(static_cast(0)); // chat mode PacketUtils::WritePacketWString(receiver, 42, &bitStream); // receiver name - for (auto it : unacceptedItems) { - bitStream.Write(it.first); // start index - bitStream.Write(it.second); // length - } + for (auto it : unacceptedItems) { + bitStream.Write(it.first); // start index + bitStream.Write(it.second); // length + } for (int i = unacceptedItems.size(); 64 > i; i++) { bitStream.Write(0); } - SEND_PACKET + SEND_PACKET } void WorldPackets::SendGMLevelChange(const SystemAddress& sysAddr, bool success, uint8_t highestLevel, uint8_t prevLevel, uint8_t newLevel) { diff --git a/dNet/WorldPackets.h b/dNet/WorldPackets.h index 3508d6f0..b88602a4 100644 --- a/dNet/WorldPackets.h +++ b/dNet/WorldPackets.h @@ -18,7 +18,7 @@ namespace WorldPackets { void SendTransferToWorld(const SystemAddress& sysAddr, const std::string& serverIP, uint32_t serverPort, bool mythranShift); void SendServerState(const SystemAddress& sysAddr); void SendCreateCharacter(const SystemAddress& sysAddr, Entity* entity, const std::string& xmlData, const std::u16string& username, int32_t gm); - void SendChatModerationResponse(const SystemAddress& sysAddr, bool requestAccepted, uint32_t requestID, const std::string& receiver, std::unordered_map unacceptedItems); + void SendChatModerationResponse(const SystemAddress& sysAddr, bool requestAccepted, uint32_t requestID, const std::string& receiver, std::vector> unacceptedItems); void SendGMLevelChange(const SystemAddress& sysAddr, bool success, uint8_t highestLevel, uint8_t prevLevel, uint8_t newLevel); } From b55606d41e562f635e202a84535082b56d059b44 Mon Sep 17 00:00:00 2001 From: David Markowitz <39972741+EmosewaMC@users.noreply.github.com> Date: Mon, 18 Jul 2022 16:08:33 -0700 Subject: [PATCH 04/86] Fix the issue where we would create new worlds on ports that were still being used (#625) * Wait for world to shutdown We need to wait for the message that the world has shutdown before shutting it down. * Dont sent people to dead instances * Added shutting down check Added check for isShuttingDown * Update when we remove from master --- dMasterServer/InstanceManager.cpp | 4 ++-- dMasterServer/InstanceManager.h | 4 ++++ dMasterServer/MasterServer.cpp | 7 ++++--- 3 files changed, 10 insertions(+), 5 deletions(-) diff --git a/dMasterServer/InstanceManager.cpp b/dMasterServer/InstanceManager.cpp index 41d34cfc..7df1449f 100644 --- a/dMasterServer/InstanceManager.cpp +++ b/dMasterServer/InstanceManager.cpp @@ -280,7 +280,7 @@ bool InstanceManager::IsInstanceFull(Instance* instance, bool isFriendTransfer) Instance * InstanceManager::FindInstance(LWOMAPID mapID, bool isFriendTransfer, LWOCLONEID cloneId) { for (Instance* i : m_Instances) { - if (i && i->GetMapID() == mapID && i->GetCloneID() == cloneId && !IsInstanceFull(i, isFriendTransfer) && !i->GetIsPrivate() && !i->GetShutdownComplete()) { + if (i && i->GetMapID() == mapID && i->GetCloneID() == cloneId && !IsInstanceFull(i, isFriendTransfer) && !i->GetIsPrivate() && !i->GetShutdownComplete() && !i->GetIsShuttingDown()) { return i; } } @@ -290,7 +290,7 @@ Instance * InstanceManager::FindInstance(LWOMAPID mapID, bool isFriendTransfer, Instance * InstanceManager::FindInstance(LWOMAPID mapID, LWOINSTANCEID instanceID) { for (Instance* i : m_Instances) { - if (i && i->GetMapID() == mapID && i->GetInstanceID() == instanceID && !i->GetIsPrivate()) { + if (i && i->GetMapID() == mapID && i->GetInstanceID() == instanceID && !i->GetIsPrivate() && !i->GetShutdownComplete() && !i->GetIsShuttingDown()) { return i; } } diff --git a/dMasterServer/InstanceManager.h b/dMasterServer/InstanceManager.h index 5dc93849..ea261343 100644 --- a/dMasterServer/InstanceManager.h +++ b/dMasterServer/InstanceManager.h @@ -31,6 +31,7 @@ public: m_PendingAffirmations = {}; m_PendingRequests = {}; m_Ready = false; + m_IsShuttingDown = false; } const std::string& GetIP() const { return m_IP; } @@ -46,6 +47,8 @@ public: bool GetIsReady() const { return m_Ready; } void SetIsReady(bool value) { m_Ready = value; } + bool GetIsShuttingDown() const { return m_IsShuttingDown; } + void SetIsShuttingDown(bool value) { m_IsShuttingDown = value; } std::vector& GetPendingRequests() { return m_PendingRequests; } std::vector& GetPendingAffirmations() { return m_PendingAffirmations; } @@ -82,6 +85,7 @@ private: std::vector m_Players; SystemAddress m_SysAddr; bool m_Ready; + bool m_IsShuttingDown; std::vector m_PendingRequests; std::vector m_PendingAffirmations; diff --git a/dMasterServer/MasterServer.cpp b/dMasterServer/MasterServer.cpp index 2e881934..634c98c4 100644 --- a/dMasterServer/MasterServer.cpp +++ b/dMasterServer/MasterServer.cpp @@ -311,7 +311,7 @@ int main(int argc, char** argv) { if (affirmTimeout == 1000) { instance->Shutdown(); - instance->SetShutdownComplete(true); + instance->SetIsShuttingDown(true); Game::im->RedirectPendingRequests(instance); } @@ -358,6 +358,7 @@ void HandlePacket(Packet* packet) { Instance* instance = Game::im->GetInstanceBySysAddr(packet->systemAddress); if (instance) { + Game::logger->Log("MasterServer", "Actually disconnected from zone %i clone %i instance %i port %i\n", instance->GetMapID(), instance->GetCloneID(), instance->GetInstanceID(), instance->GetPort()); Game::im->RemoveInstance(instance); //Delete the old } @@ -694,8 +695,8 @@ void HandlePacket(Packet* packet) { return; } - Game::logger->Log("MasterServer", "Got shutdown response\n"); - instance->SetShutdownComplete(true); + Game::logger->Log("MasterServer", "Got shutdown response from zone %i clone %i instance %i port %i\n", instance->GetMapID(), instance->GetCloneID(), instance->GetInstanceID(), instance->GetPort()); + instance->SetIsShuttingDown(true); break; } From ec4ed8fa7e37d1a9457a17580273e3db79e4e818 Mon Sep 17 00:00:00 2001 From: Demetri Van Sickle Date: Mon, 18 Jul 2022 16:44:21 -0700 Subject: [PATCH 05/86] Adding migration command to build script (updated) (#653) * Added checks for migration runner * Added migration command to build script --- build.sh | 5 +- dMasterServer/MasterServer.cpp | 107 +++++++++++++++++++-------------- 2 files changed, 66 insertions(+), 46 deletions(-) diff --git a/build.sh b/build.sh index 11562359..31eaa2c7 100755 --- a/build.sh +++ b/build.sh @@ -6,4 +6,7 @@ cd build cmake .. # Run make to build the project. To build utilizing multiple cores, append `-j` and the amount of cores to utilize, for example `make -j8` -make \ No newline at end of file +make + +# Run migrations +./MasterServer -m diff --git a/dMasterServer/MasterServer.cpp b/dMasterServer/MasterServer.cpp index 634c98c4..f71fd408 100644 --- a/dMasterServer/MasterServer.cpp +++ b/dMasterServer/MasterServer.cpp @@ -84,56 +84,73 @@ int main(int argc, char** argv) { Game::config = &config; Game::logger->SetLogToConsole(bool(std::stoi(config.GetValue("log_to_console")))); Game::logger->SetLogDebugStatements(config.GetValue("log_debug_statements") == "1"); - - //Check CDClient exists - const std::string cdclient_path = "./res/CDServer.sqlite"; - std::ifstream cdclient_fd(cdclient_path); - if (!cdclient_fd.good()) { - Game::logger->Log("WorldServer", "%s could not be opened\n", cdclient_path.c_str()); - return EXIT_FAILURE; - } - cdclient_fd.close(); - - //Connect to CDClient - try { - CDClientDatabase::Connect(cdclient_path); - } catch (CppSQLite3Exception& e) { - Game::logger->Log("WorldServer", "Unable to connect to CDServer SQLite Database\n"); - Game::logger->Log("WorldServer", "Error: %s\n", e.errorMessage()); - Game::logger->Log("WorldServer", "Error Code: %i\n", e.errorCode()); - return EXIT_FAILURE; - } - - //Get CDClient initial information - try { - CDClientManager::Instance()->Initialize(); - } catch (CppSQLite3Exception& e) { - Game::logger->Log("WorldServer", "Failed to initialize CDServer SQLite Database\n"); - Game::logger->Log("WorldServer", "May be caused by corrupted file: %s\n", cdclient_path.c_str()); - Game::logger->Log("WorldServer", "Error: %s\n", e.errorMessage()); - Game::logger->Log("WorldServer", "Error Code: %i\n", e.errorCode()); - return EXIT_FAILURE; - } - - //Connect to the MySQL Database - std::string mysql_host = config.GetValue("mysql_host"); - std::string mysql_database = config.GetValue("mysql_database"); - std::string mysql_username = config.GetValue("mysql_username"); - std::string mysql_password = config.GetValue("mysql_password"); - - try { - Database::Connect(mysql_host, mysql_database, mysql_username, mysql_password); - } catch (sql::SQLException& ex) { - Game::logger->Log("MasterServer", "Got an error while connecting to the database: %s\n", ex.what()); - return EXIT_FAILURE; - } - + if (argc > 1 && (strcmp(argv[1], "-m") == 0 || strcmp(argv[1], "--migrations") == 0)) { + //Connect to the MySQL Database + std::string mysql_host = config.GetValue("mysql_host"); + std::string mysql_database = config.GetValue("mysql_database"); + std::string mysql_username = config.GetValue("mysql_username"); + std::string mysql_password = config.GetValue("mysql_password"); + + try { + Database::Connect(mysql_host, mysql_database, mysql_username, mysql_password); + } catch (sql::SQLException& ex) { + Game::logger->Log("MasterServer", "Got an error while connecting to the database: %s\n", ex.what()); + Game::logger->Log("MigrationRunner", "Migrations not run\n"); + return EXIT_FAILURE; + } + MigrationRunner::RunMigrations(); Game::logger->Log("MigrationRunner", "Finished running migrations\n"); return EXIT_SUCCESS; } + else { + + //Check CDClient exists + const std::string cdclient_path = "./res/CDServer.sqlite"; + std::ifstream cdclient_fd(cdclient_path); + if (!cdclient_fd.good()) { + Game::logger->Log("WorldServer", "%s could not be opened\n", cdclient_path.c_str()); + return EXIT_FAILURE; + } + cdclient_fd.close(); + + //Connect to CDClient + try { + CDClientDatabase::Connect(cdclient_path); + } catch (CppSQLite3Exception& e) { + Game::logger->Log("WorldServer", "Unable to connect to CDServer SQLite Database\n"); + Game::logger->Log("WorldServer", "Error: %s\n", e.errorMessage()); + Game::logger->Log("WorldServer", "Error Code: %i\n", e.errorCode()); + return EXIT_FAILURE; + } + + //Get CDClient initial information + try { + CDClientManager::Instance()->Initialize(); + } catch (CppSQLite3Exception& e) { + Game::logger->Log("WorldServer", "Failed to initialize CDServer SQLite Database\n"); + Game::logger->Log("WorldServer", "May be caused by corrupted file: %s\n", cdclient_path.c_str()); + Game::logger->Log("WorldServer", "Error: %s\n", e.errorMessage()); + Game::logger->Log("WorldServer", "Error Code: %i\n", e.errorCode()); + return EXIT_FAILURE; + } + + //Connect to the MySQL Database + std::string mysql_host = config.GetValue("mysql_host"); + std::string mysql_database = config.GetValue("mysql_database"); + std::string mysql_username = config.GetValue("mysql_username"); + std::string mysql_password = config.GetValue("mysql_password"); + + try { + Database::Connect(mysql_host, mysql_database, mysql_username, mysql_password); + } catch (sql::SQLException& ex) { + Game::logger->Log("MasterServer", "Got an error while connecting to the database: %s\n", ex.what()); + return EXIT_FAILURE; + } + } + //If the first command line argument is -a or --account then make the user //input a username and password, with the password being hidden. @@ -824,4 +841,4 @@ int FinalizeShutdown() { exit(EXIT_SUCCESS); return EXIT_SUCCESS; -} \ No newline at end of file +} From 3dfe363a6b05b6b8245b299755e59aecc7634ee3 Mon Sep 17 00:00:00 2001 From: Aaron Kimbrell Date: Tue, 19 Jul 2022 09:29:26 -0500 Subject: [PATCH 06/86] Added Aronwk and Simon to the readme (#657) * Added myself and Simon to the readme Me, since I've started to work on implementing mounts again. Simon for his work in Reverse engineering the client which has been helping over the years. Venture Vision and moving platforms/simple movers being two recent things that his RE has helped fix. moved the special thanks out a header at the suggestion of Xipho and Max, since these people have not directly contributed to the DLU codebase. made a section under the DLU team recognizing Blaster for the Logo that DLU uses bumped up the credits header to make formatting make more sense * Update based on feedback Credit Blaster builder as they requested. Remove duplicate entries for under DLU Team as requested --- README.md | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/README.md b/README.md index 5781c7b8..9acd9abf 100644 --- a/README.md +++ b/README.md @@ -417,10 +417,11 @@ Here is a summary of the commands available in-game. All commands are prefixed b -## Credits +# Credits ## Active Contributors * [EmosewaMC](https://github.com/EmosewaMC) * [Jettford](https://github.com/Jettford) +* [Aaron K.](https://github.com/aronwk-aaron) ## DLU Team * [DarwinAnim8or](https://github.com/DarwinAnim8or) @@ -429,10 +430,6 @@ Here is a summary of the commands available in-game. All commands are prefixed b * [averysumner](https://github.com/codeshaunted) * [Jon002](https://github.com/jaller200) * [Jonny](https://github.com/cuzitsjonny) -* TheMachine -* Matthew -* [Raine](https://github.com/Rainebannister) -* Bricknave ### Research and tools * [lcdr](https://github.com/lcdr) @@ -444,11 +441,14 @@ Here is a summary of the commands available in-game. All commands are prefixed b ### Former contributors * TheMachine * Matthew -* Raine +* [Raine](https://github.com/Rainebannister) * Bricknave -### Special thanks +### Logo +* Cole Peterson (BlasterBuilder) + +## Special thanks * humanoid24 * pwjones1969 -* BlasterBuilder for the logo +* [Simon](https://github.com/SimonNitzsche) * ALL OF THE NETDEVIL AND LEGO TEAMS! From ed5ced0beda35910799aabb06d01d6830e1766eb Mon Sep 17 00:00:00 2001 From: David Markowitz <39972741+EmosewaMC@users.noreply.github.com> Date: Tue, 19 Jul 2022 14:51:35 -0700 Subject: [PATCH 07/86] Fix Model Component Serialization (#655) * Fix model component serialization * Update ModelComponent.h --- dCommon/dCommonVars.h | 3 +- dGame/Entity.cpp | 52 ++++++++----- dGame/dComponents/DestroyableComponent.cpp | 4 +- dGame/dComponents/DestroyableComponent.h | 2 +- dGame/dComponents/ModelComponent.cpp | 48 +++++------- dGame/dComponents/ModelComponent.h | 73 +++++++++---------- .../PropertyManagementComponent.cpp | 49 +++++++------ 7 files changed, 120 insertions(+), 111 deletions(-) diff --git a/dCommon/dCommonVars.h b/dCommon/dCommonVars.h index c458b9fb..77d51125 100644 --- a/dCommon/dCommonVars.h +++ b/dCommon/dCommonVars.h @@ -387,6 +387,7 @@ enum eReplicaComponentType : int32_t { COMPONENT_TYPE_PROPERTY = 36, //!< The Property Component COMPONENT_TYPE_SCRIPTED_ACTIVITY = 39, //!< The ScriptedActivity Component COMPONENT_TYPE_PHANTOM_PHYSICS = 40, //!< The PhantomPhysics Component + COMPONENT_TYPE_MODEL = 42, //!< The Model Component COMPONENT_TYPE_PROPERTY_ENTRANCE = 43, //!< The PhantomPhysics Component COMPONENT_TYPE_PROPERTY_MANAGEMENT = 45, //!< The PropertyManagement Component COMPONENT_TYPE_REBUILD = 48, //!< The Rebuild Component @@ -411,8 +412,6 @@ enum eReplicaComponentType : int32_t { COMPONENT_TYPE_POSSESSOR = 110, //!< The Possessor Component COMPONENT_TYPE_BUILD_BORDER = 114, //!< The Build Border Component COMPONENT_TYPE_DESTROYABLE = 1000, //!< The Destroyable Component - - COMPONENT_TYPE_MODEL = 5398484 //look man idk }; enum class UseItemResponse : uint32_t { diff --git a/dGame/Entity.cpp b/dGame/Entity.cpp index a063b3c6..c44db6f1 100644 --- a/dGame/Entity.cpp +++ b/dGame/Entity.cpp @@ -182,12 +182,18 @@ void Entity::Initialize() SimplePhysicsComponent* comp = new SimplePhysicsComponent(simplePhysicsComponentID, this); m_Components.insert(std::make_pair(COMPONENT_TYPE_SIMPLE_PHYSICS, comp)); - ModelComponent* modelcomp = new ModelComponent(0, this); + ModelComponent* modelcomp = new ModelComponent(this); m_Components.insert(std::make_pair(COMPONENT_TYPE_MODEL, modelcomp)); RenderComponent* render = new RenderComponent(this); m_Components.insert(std::make_pair(COMPONENT_TYPE_RENDER, render)); + auto destroyableComponent = new DestroyableComponent(this); + destroyableComponent->SetHealth(1); + destroyableComponent->SetMaxHealth(1.0f); + destroyableComponent->SetFaction(-1, true); + destroyableComponent->SetIsSmashable(true); + m_Components.insert(std::make_pair(COMPONENT_TYPE_DESTROYABLE, destroyableComponent)); // We have all our components. return; } @@ -226,11 +232,6 @@ void Entity::Initialize() m_Components.insert(std::make_pair(COMPONENT_TYPE_RACING_STATS, nullptr)); } - PetComponent* petComponent; - if (compRegistryTable->GetByIDAndType(m_TemplateID, COMPONENT_TYPE_ITEM) > 0 && !TryGetComponent(COMPONENT_TYPE_PET, petComponent)) { - m_Components.insert(std::make_pair(COMPONENT_TYPE_ITEM, nullptr)); - } - if (compRegistryTable->GetByIDAndType(m_TemplateID, COMPONENT_TYPE_EXHIBIT, -1) >= 0) { m_Components.insert(std::make_pair(COMPONENT_TYPE_EXHIBIT, new LUPExhibitComponent(this))); } @@ -628,6 +629,23 @@ void Entity::Initialize() m_Components.insert(std::make_pair(COMPONENT_TYPE_SCRIPTED_ACTIVITY, new ScriptedActivityComponent(this, scriptedActivityID))); } + if (compRegistryTable->GetByIDAndType(m_TemplateID, COMPONENT_TYPE_MODEL, -1) != -1 && !GetComponent()) { + m_Components.insert(std::make_pair(COMPONENT_TYPE_MODEL, new ModelComponent(this))); + if (m_Components.find(COMPONENT_TYPE_DESTROYABLE) == m_Components.end()) { + auto destroyableComponent = new DestroyableComponent(this); + destroyableComponent->SetHealth(1); + destroyableComponent->SetMaxHealth(1.0f); + destroyableComponent->SetFaction(-1, true); + destroyableComponent->SetIsSmashable(true); + m_Components.insert(std::make_pair(COMPONENT_TYPE_DESTROYABLE, destroyableComponent)); + } + } + + PetComponent* petComponent; + if (compRegistryTable->GetByIDAndType(m_TemplateID, COMPONENT_TYPE_ITEM) > 0 && !TryGetComponent(COMPONENT_TYPE_PET, petComponent) && !HasComponent(COMPONENT_TYPE_MODEL)) { + m_Components.insert(std::make_pair(COMPONENT_TYPE_ITEM, nullptr)); + } + // Shooting gallery component if (compRegistryTable->GetByIDAndType(m_TemplateID, COMPONENT_TYPE_SHOOTING_GALLERY) > 0) { m_Components.insert(std::make_pair(COMPONENT_TYPE_SHOOTING_GALLERY, new ShootingGalleryComponent(this))); @@ -876,8 +894,8 @@ void Entity::WriteBaseReplicaData(RakNet::BitStream* outBitStream, eReplicaPacke const auto& syncLDF = GetVar>(u"syncLDF"); - //limiting it to lot 14 right now - if (m_Settings.size() > 0 && m_TemplateID == 14) { + // Only sync for models. + if (m_Settings.size() > 0 && (GetComponent() && !GetComponent())) { outBitStream->Write1(); //ldf data RakNet::BitStream settingStream; @@ -1170,23 +1188,23 @@ void Entity::WriteComponents(RakNet::BitStream* outBitStream, eReplicaPacketType renderComponent->Serialize(outBitStream, bIsInitialUpdate, flags); } + if (modelComponent) { + DestroyableComponent* destroyableComponent; + if (TryGetComponent(COMPONENT_TYPE_DESTROYABLE, destroyableComponent) && !destroyableSerialized) { + destroyableComponent->Serialize(outBitStream, bIsInitialUpdate, flags); + destroyableSerialized = true; + } + } + if (HasComponent(COMPONENT_TYPE_ZONE_CONTROL)) { outBitStream->Write(0x40000000); } // BBB Component, unused currently - // Need to to write0 so that is serlaizese correctly + // Need to to write0 so that is serialized correctly // TODO: Implement BBB Component outBitStream->Write0(); - - /* - if (m_Trigger != nullptr) - { - outBitStream->Write1(); - outBitStream->Write(m_Trigger->id); - } - */ } void Entity::ResetFlags() { diff --git a/dGame/dComponents/DestroyableComponent.cpp b/dGame/dComponents/DestroyableComponent.cpp index 72194568..37d74a55 100644 --- a/dGame/dComponents/DestroyableComponent.cpp +++ b/dGame/dComponents/DestroyableComponent.cpp @@ -829,11 +829,11 @@ void DestroyableComponent::Smash(const LWOOBJID source, const eKillType killType m_Parent->Kill(owner); } -void DestroyableComponent::SetFaction(int32_t factionID) { +void DestroyableComponent::SetFaction(int32_t factionID, bool ignoreChecks) { m_FactionIDs.clear(); m_EnemyFactionIDs.clear(); - AddFaction(factionID); + AddFaction(factionID, ignoreChecks); } void DestroyableComponent::PushImmunity(int32_t stacks) diff --git a/dGame/dComponents/DestroyableComponent.h b/dGame/dComponents/DestroyableComponent.h index a1f57be4..ade3f4e8 100644 --- a/dGame/dComponents/DestroyableComponent.h +++ b/dGame/dComponents/DestroyableComponent.h @@ -282,7 +282,7 @@ public: * Sets the faction ID of this entity, overriding all previously set entries * @param factionID the faction ID to set */ - void SetFaction(int32_t factionID); + void SetFaction(int32_t factionID, bool ignoreChecks = false); /** * Returns whether or not the provided entity is an enemy of this entity diff --git a/dGame/dComponents/ModelComponent.cpp b/dGame/dComponents/ModelComponent.cpp index bb8bdfe4..65259912 100644 --- a/dGame/dComponents/ModelComponent.cpp +++ b/dGame/dComponents/ModelComponent.cpp @@ -1,42 +1,32 @@ #include "ModelComponent.h" #include "Entity.h" -ModelComponent::ModelComponent(uint32_t componentID, Entity* parent) : Component(parent) +ModelComponent::ModelComponent(Entity* parent) : Component(parent) { - m_Position = m_Parent->GetDefaultPosition(); - m_Rotation = m_Parent->GetDefaultRotation(); + m_OriginalPosition = m_Parent->GetDefaultPosition(); + m_OriginalRotation = m_Parent->GetDefaultRotation(); m_userModelID = m_Parent->GetVarAs(u"userModelID"); - - /* - for (auto set : m_Parent->GetInfo().settings) { - if (set && set->GetKey() == u"userModelID") { - m_userModelID = std::stoull(set->GetValueAsString()); - } - } - */ -} - -ModelComponent::~ModelComponent() { } void ModelComponent::Serialize(RakNet::BitStream* outBitStream, bool bIsInitialUpdate, unsigned int& flags) { - //item component: - outBitStream->Write1(); - outBitStream->Write(m_userModelID); - outBitStream->Write(0); - outBitStream->Write0(); + // ItemComponent Serialization. Pets do not get this serialization. + if (!m_Parent->HasComponent(COMPONENT_TYPE_PET)) { + outBitStream->Write1(); + outBitStream->Write(m_userModelID != LWOOBJID_EMPTY ? m_userModelID : m_Parent->GetObjectID()); + outBitStream->Write(0); + outBitStream->Write0(); + } //actual model component: - outBitStream->Write1(); //yes we are writing model info - outBitStream->Write0(); //?? - outBitStream->Write(2); //model type, always 2 for BBB + outBitStream->Write1(); // Yes we are writing model info + outBitStream->Write0(); // Is pickable + outBitStream->Write(2); // Physics type + outBitStream->Write(m_OriginalPosition); // Original position + outBitStream->Write(m_OriginalRotation); // Original rotation - outBitStream->Write(m_Position); - outBitStream->Write(m_Rotation); - - outBitStream->Write1(); //second data flag, all unknown. Maybe skip? - outBitStream->Write(0); - outBitStream->Write1(); - outBitStream->Write0(); + outBitStream->Write1(); // We are writing behavior info + outBitStream->Write(0); // Number of behaviors + outBitStream->Write1(); // Is this model paused + if (bIsInitialUpdate) outBitStream->Write0(); // We are not writing model editing info } diff --git a/dGame/dComponents/ModelComponent.h b/dGame/dComponents/ModelComponent.h index 3b13bab8..81342059 100644 --- a/dGame/dComponents/ModelComponent.h +++ b/dGame/dComponents/ModelComponent.h @@ -12,51 +12,50 @@ class Entity; */ class ModelComponent : public Component { public: - static const uint32_t ComponentType = COMPONENT_TYPE_MODEL; + static const uint32_t ComponentType = COMPONENT_TYPE_MODEL; - ModelComponent(uint32_t componentID, Entity* parent); - ~ModelComponent() override; + ModelComponent(Entity* parent); - void Serialize(RakNet::BitStream* outBitStream, bool bIsInitialUpdate, unsigned int& flags); + void Serialize(RakNet::BitStream* outBitStream, bool bIsInitialUpdate, unsigned int& flags); - /** - * Returns the position of the model - * @return the position of the model - */ - NiPoint3& GetPosition() { return m_Position; } + /** + * Returns the original position of the model + * @return the original position of the model + */ + const NiPoint3& GetPosition() { return m_OriginalPosition; } - /** - * Sets the position of the model - * @param pos the position to set - */ - void SetPosition(const NiPoint3& pos) { m_Position = pos; } + /** + * Sets the original position of the model + * @param pos the original position to set + */ + void SetPosition(const NiPoint3& pos) { m_OriginalPosition = pos; } - /** - * Returns the rotation of the model - * @return the rotation of the model - */ - NiQuaternion& GetRotation() { return m_Rotation; } + /** + * Returns the original rotation of the model + * @return the original rotation of the model + */ + const NiQuaternion& GetRotation() { return m_OriginalRotation; } - /** - * Sets the rotation of the model - * @param rot the rotation to set - */ - void SetRotation(const NiQuaternion& rot) { m_Rotation = rot; } + /** + * Sets the original rotation of the model + * @param rot the original rotation to set + */ + void SetRotation(const NiQuaternion& rot) { m_OriginalRotation = rot; } private: - /** - * The position of the model - */ - NiPoint3 m_Position; + /** + * The original position of the model + */ + NiPoint3 m_OriginalPosition; - /** - * The rotation of the model - */ - NiQuaternion m_Rotation; + /** + * The rotation original of the model + */ + NiQuaternion m_OriginalRotation; - /** - * The ID of the user that made the model - */ - LWOOBJID m_userModelID; -}; \ No newline at end of file + /** + * The ID of the user that made the model + */ + LWOOBJID m_userModelID; +}; diff --git a/dGame/dComponents/PropertyManagementComponent.cpp b/dGame/dComponents/PropertyManagementComponent.cpp index f27ea283..1168209c 100644 --- a/dGame/dComponents/PropertyManagementComponent.cpp +++ b/dGame/dComponents/PropertyManagementComponent.cpp @@ -360,20 +360,17 @@ void PropertyManagementComponent::UpdateModelPosition(const LWOOBJID id, const N if (newEntity != nullptr) { EntityManager::Instance()->ConstructEntity(newEntity); - //Make sure the propMgmt doesn't delete our model after the server dies - //Trying to do this after the entity is constructed. Shouldn't really change anything but - //There was an issue with builds not appearing since it was placed above ConstructEntity. + // Make sure the propMgmt doesn't delete our model after the server dies + // Trying to do this after the entity is constructed. Shouldn't really change anything but + // There was an issue with builds not appearing since it was placed above ConstructEntity. PropertyManagementComponent::Instance()->AddModel(newEntity->GetObjectID(), spawnerID); } item->SetCount(item->GetCount() - 1); - //item->UnEquip(); - return; } item->SetCount(item->GetCount() - 1); - //item->UnEquip(); auto* node = new SpawnerNode(); @@ -402,6 +399,17 @@ void PropertyManagementComponent::UpdateModelPosition(const LWOOBJID id, const N auto* spawner = dZoneManager::Instance()->GetSpawner(spawnerId); + auto ldfModelBehavior = new LDFData(u"modelBehaviors", 0); + auto userModelID = new LDFData(u"userModelID", id); + auto modelType = new LDFData(u"modelType", 2); + auto propertyObjectID = new LDFData(u"propertyObjectID", true); + auto componentWhitelist = new LDFData(u"componentWhitelist", 1); + info.nodes[0]->config.push_back(componentWhitelist); + info.nodes[0]->config.push_back(ldfModelBehavior); + info.nodes[0]->config.push_back(modelType); + info.nodes[0]->config.push_back(propertyObjectID); + info.nodes[0]->config.push_back(userModelID); + auto* model = spawner->Spawn(); models.insert_or_assign(model->GetObjectID(), spawnerId); @@ -412,8 +420,6 @@ void PropertyManagementComponent::UpdateModelPosition(const LWOOBJID id, const N GameMessages::SendGetModelsOnProperty(entity->GetObjectID(), GetModels(), UNASSIGNED_SYSTEM_ADDRESS); - //item->SetCount(item->GetCount() - 1); - EntityManager::Instance()->GetZoneControlEntity()->OnZonePropertyModelPlaced(entity); }); // Progress place model missions @@ -669,6 +675,18 @@ void PropertyManagementComponent::Load() settings.push_back(modelType); settings.push_back(propertyObjectID); settings.push_back(userModelID); + } else { + auto modelType = new LDFData(u"modelType", 2); + auto userModelID = new LDFData(u"userModelID", id); + auto ldfModelBehavior = new LDFData(u"modelBehaviors", 0); + auto propertyObjectID = new LDFData(u"propertyObjectID", true); + auto componentWhitelist = new LDFData(u"componentWhitelist", 1); + + settings.push_back(componentWhitelist); + settings.push_back(ldfModelBehavior); + settings.push_back(modelType); + settings.push_back(propertyObjectID); + settings.push_back(userModelID); } node->config = settings; @@ -680,21 +698,6 @@ void PropertyManagementComponent::Load() auto* model = spawner->Spawn(); models.insert_or_assign(model->GetObjectID(), spawnerId); - - /* - EntityInfo info; - info.lot = lot; - info.pos = position; - info.rot = rotation; - info.settings = settings; - info.spawnerID = id; - - auto* model = EntityManager::Instance()->CreateEntity(info); - - EntityManager::Instance()->ConstructEntity(model); - - models.insert_or_assign(model->GetObjectID(), id); - */ } delete lookup; From 74343be871d9948b3a226b5f8c5dfcef056c3da9 Mon Sep 17 00:00:00 2001 From: David Markowitz <39972741+EmosewaMC@users.noreply.github.com> Date: Tue, 19 Jul 2022 14:52:39 -0700 Subject: [PATCH 08/86] Enable _dynamic by default (#656) --- CMakeVariables.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/CMakeVariables.txt b/CMakeVariables.txt index db89fef7..fb59f455 100644 --- a/CMakeVariables.txt +++ b/CMakeVariables.txt @@ -8,7 +8,7 @@ LICENSE=AGPL-3.0 # 171022 - Unmodded client NET_VERSION=171022 # Debugging -# __dynamic=1 +__dynamic=1 # Set __dynamic to 1 to enable the -rdynamic flag for the linker, yielding some symbols in crashlogs. # __ggdb=1 # Set __ggdb to 1 to enable the -ggdb flag for the linker, including more debug info. From 835cf2b794d33827c99218a2a4191ffe4c62998e Mon Sep 17 00:00:00 2001 From: David Markowitz <39972741+EmosewaMC@users.noreply.github.com> Date: Tue, 19 Jul 2022 21:51:05 -0700 Subject: [PATCH 09/86] Add an AMF Deserializer as well as corresponding Unit Tests (#599) * Add AMFDeserializer Add an AMFDeserializer Reverted unrelated changes Add unit tests for AMFDeserializer Added unit tests for the AMFDeserializer Finish tests Finish the AMF deserializer tests. This commit finishes the positive test case and implements a load test case that is expected to take less than 1.5 seconds to process. Modularized tests Made tests a bit modular and split into more methods Specified binary read from file Specified that on the IO stream we are reading a binary file otherwise windows will terminate reading the binary file on seeing a 1A byte. Added more tests Added tests for unimplemented values and edited a test file to be more modular Updated test text Fix spacing Update AMFDeserializeTests.cpp * Update CMakeLists.txt * Update AMFDeserializeTests.cpp f Actually follow the AMF spec Update AMFDeserializeTests.cpp tabs Add in commented tests * Follow spec formatting Add Integer Tests Follow Spec more Follow spec * Use unique_ptr * Update AMFDeserialize.cpp Semantics Update AMFDeserialize.cpp Add new lines to EOF CMake fix * Add better std string read Co-authored-by: Daniel Seiler * make not static Co-authored-by: Daniel Seiler --- .gitignore | 4 +- dCommon/AMFDeserialize.cpp | 158 +++++++ dCommon/AMFDeserialize.h | 71 +++ dCommon/AMFFormat.h | 12 + dCommon/CMakeLists.txt | 1 + tests/AMFDeserializeTests.cpp | 404 ++++++++++++++++++ tests/CMakeLists.txt | 12 + tests/TestBitStreams/AMFBitStreamTest.bin | Bin 0 -> 329 bytes .../AMFBitStreamUnimplementedTest.bin | 1 + 9 files changed, 662 insertions(+), 1 deletion(-) create mode 100644 dCommon/AMFDeserialize.cpp create mode 100644 dCommon/AMFDeserialize.h create mode 100644 tests/AMFDeserializeTests.cpp create mode 100644 tests/TestBitStreams/AMFBitStreamTest.bin create mode 100644 tests/TestBitStreams/AMFBitStreamUnimplementedTest.bin diff --git a/.gitignore b/.gitignore index 28f8f297..3777608d 100644 --- a/.gitignore +++ b/.gitignore @@ -119,4 +119,6 @@ thirdparty/zlib-1.2.11/ .env docker/__pycache__ -docker-compose.override.yml \ No newline at end of file +docker-compose.override.yml + +!/tests/TestBitStreams/*.bin diff --git a/dCommon/AMFDeserialize.cpp b/dCommon/AMFDeserialize.cpp new file mode 100644 index 00000000..7f3f6d95 --- /dev/null +++ b/dCommon/AMFDeserialize.cpp @@ -0,0 +1,158 @@ +#include "AMFDeserialize.h" + +#include "AMFFormat.h" + +/** + * AMF3 Reference document https://rtmp.veriskope.com/pdf/amf3-file-format-spec.pdf + * AMF3 Deserializer written by EmosewaMC + */ + +AMFValue* AMFDeserialize::Read(RakNet::BitStream* inStream) { + if (!inStream) return nullptr; + AMFValue* returnValue = nullptr; + // Read in the value type from the bitStream + int8_t marker; + inStream->Read(marker); + // Based on the typing, create the value associated with that and return the base value class + switch (marker) { + case AMFValueType::AMFUndefined: { + returnValue = new AMFUndefinedValue(); + break; + } + + case AMFValueType::AMFNull: { + returnValue = new AMFNullValue(); + break; + } + + case AMFValueType::AMFFalse: { + returnValue = new AMFFalseValue(); + break; + } + + case AMFValueType::AMFTrue: { + returnValue = new AMFTrueValue(); + break; + } + + case AMFValueType::AMFInteger: { + returnValue = ReadAmfInteger(inStream); + break; + } + + case AMFValueType::AMFDouble: { + returnValue = ReadAmfDouble(inStream); + break; + } + + case AMFValueType::AMFString: { + returnValue = ReadAmfString(inStream); + break; + } + + case AMFValueType::AMFArray: { + returnValue = ReadAmfArray(inStream); + break; + } + + // TODO We do not need these values, but if someone wants to implement them + // then please do so and add the corresponding unit tests. + case AMFValueType::AMFXMLDoc: + case AMFValueType::AMFDate: + case AMFValueType::AMFObject: + case AMFValueType::AMFXML: + case AMFValueType::AMFByteArray: + case AMFValueType::AMFVectorInt: + case AMFValueType::AMFVectorUInt: + case AMFValueType::AMFVectorDouble: + case AMFValueType::AMFVectorObject: + case AMFValueType::AMFDictionary: { + throw static_cast(marker); + break; + } + default: + throw static_cast(marker); + break; + } + return returnValue; +} + +uint32_t AMFDeserialize::ReadU29(RakNet::BitStream* inStream) { + bool byteFlag = true; + uint32_t actualNumber{}; + uint8_t numberOfBytesRead{}; + while (byteFlag && numberOfBytesRead < 4) { + uint8_t byte{}; + inStream->Read(byte); + // Parse the byte + if (numberOfBytesRead < 3) { + byteFlag = byte & static_cast(1 << 7); + byte = byte << 1UL; + } + // Combine the read byte with our current read in number + actualNumber <<= 8UL; + actualNumber |= static_cast(byte); + // If we are not done reading in bytes, shift right 1 bit + if (numberOfBytesRead < 3) actualNumber = actualNumber >> 1UL; + numberOfBytesRead++; + } + return actualNumber; +} + +std::string AMFDeserialize::ReadString(RakNet::BitStream* inStream) { + auto length = ReadU29(inStream); + // Check if this is a reference + bool isReference = length % 2 == 1; + // Right shift by 1 bit to get index if reference or size of next string if value + length = length >> 1; + if (isReference) { + std::string value(length, 0); + inStream->Read(&value[0], length); + // Empty strings are never sent by reference + if (!value.empty()) accessedElements.push_back(value); + return value; + } else { + // Length is a reference to a previous index - use that as the read in value + return accessedElements[length]; + } +} + +AMFValue* AMFDeserialize::ReadAmfDouble(RakNet::BitStream* inStream) { + auto doubleValue = new AMFDoubleValue(); + double value; + inStream->Read(value); + doubleValue->SetDoubleValue(value); + return doubleValue; +} + +AMFValue* AMFDeserialize::ReadAmfArray(RakNet::BitStream* inStream) { + auto arrayValue = new AMFArrayValue(); + auto sizeOfDenseArray = (ReadU29(inStream) >> 1); + if (sizeOfDenseArray >= 1) { + char valueType; + inStream->Read(valueType); // Unused + for (uint32_t i = 0; i < sizeOfDenseArray; i++) { + arrayValue->PushBackValue(Read(inStream)); + } + } else { + while (true) { + auto key = ReadString(inStream); + // No more values when we encounter an empty string + if (key.size() == 0) break; + arrayValue->InsertValue(key, Read(inStream)); + } + } + return arrayValue; +} + +AMFValue* AMFDeserialize::ReadAmfString(RakNet::BitStream* inStream) { + auto stringValue = new AMFStringValue(); + stringValue->SetStringValue(ReadString(inStream)); + return stringValue; +} + +AMFValue* AMFDeserialize::ReadAmfInteger(RakNet::BitStream* inStream) { + auto integerValue = new AMFIntegerValue(); + integerValue->SetIntegerValue(ReadU29(inStream)); + return integerValue; +} diff --git a/dCommon/AMFDeserialize.h b/dCommon/AMFDeserialize.h new file mode 100644 index 00000000..d03c150f --- /dev/null +++ b/dCommon/AMFDeserialize.h @@ -0,0 +1,71 @@ +#pragma once + +#include "BitStream.h" + +#include +#include + +class AMFValue; +class AMFDeserialize { + public: + /** + * Read an AMF3 value from a bitstream. + * + * @param inStream inStream to read value from. + * @return Returns an AMFValue with all the information from the bitStream in it. + */ + AMFValue* Read(RakNet::BitStream* inStream); + private: + /** + * @brief Private method to read a U29 integer from a bitstream + * + * @param inStream bitstream to read data from + * @return The number as an unsigned 29 bit integer + */ + uint32_t ReadU29(RakNet::BitStream* inStream); + + /** + * @brief Reads a string from a bitstream + * + * @param inStream bitStream to read data from + * @return The read string + */ + std::string ReadString(RakNet::BitStream* inStream); + + /** + * @brief Read an AMFDouble value from a bitStream + * + * @param inStream bitStream to read data from + * @return Double value represented as an AMFValue + */ + AMFValue* ReadAmfDouble(RakNet::BitStream* inStream); + + /** + * @brief Read an AMFArray from a bitStream + * + * @param inStream bitStream to read data from + * @return Array value represented as an AMFValue + */ + AMFValue* ReadAmfArray(RakNet::BitStream* inStream); + + /** + * @brief Read an AMFString from a bitStream + * + * @param inStream bitStream to read data from + * @return String value represented as an AMFValue + */ + AMFValue* ReadAmfString(RakNet::BitStream* inStream); + + /** + * @brief Read an AMFInteger from a bitStream + * + * @param inStream bitStream to read data from + * @return Integer value represented as an AMFValue + */ + AMFValue* ReadAmfInteger(RakNet::BitStream* inStream); + + /** + * List of strings read so far saved to be read by reference. + */ + std::vector accessedElements; +}; diff --git a/dCommon/AMFFormat.h b/dCommon/AMFFormat.h index 95863594..c3d0936c 100644 --- a/dCommon/AMFFormat.h +++ b/dCommon/AMFFormat.h @@ -308,6 +308,18 @@ public: \return Where the iterator ends */ _AMFArrayList_::iterator GetDenseIteratorEnd(); + + //! Returns the associative map + /*! + \return The associative map + */ + _AMFArrayMap_ GetAssociativeMap() { return this->associative; }; + + //! Returns the dense array + /*! + \return The dense array + */ + _AMFArrayList_ GetDenseArray() { return this->dense; }; }; //! The anonymous object value AMF type diff --git a/dCommon/CMakeLists.txt b/dCommon/CMakeLists.txt index 7e047a9c..7262bfef 100644 --- a/dCommon/CMakeLists.txt +++ b/dCommon/CMakeLists.txt @@ -1,4 +1,5 @@ set(DCOMMON_SOURCES "AMFFormat.cpp" + "AMFDeserialize.cpp" "AMFFormat_BitStream.cpp" "BinaryIO.cpp" "dConfig.cpp" diff --git a/tests/AMFDeserializeTests.cpp b/tests/AMFDeserializeTests.cpp new file mode 100644 index 00000000..88405803 --- /dev/null +++ b/tests/AMFDeserializeTests.cpp @@ -0,0 +1,404 @@ +#include +#include +#include +#include + +#include "AMFDeserialize.h" +#include "AMFFormat.h" +#include "CommonCxxTests.h" + +std::unique_ptr ReadFromBitStream(RakNet::BitStream* bitStream) { + AMFDeserialize deserializer; + std::unique_ptr returnValue(deserializer.Read(bitStream)); + return returnValue; +} + +int ReadAMFUndefinedFromBitStream() { + CBITSTREAM + bitStream.Write(0x00); + std::unique_ptr res(ReadFromBitStream(&bitStream)); + ASSERT_EQ(res->GetValueType(), AMFValueType::AMFUndefined); + return 0; +} + +int ReadAMFNullFromBitStream() { + CBITSTREAM + bitStream.Write(0x01); + std::unique_ptr res(ReadFromBitStream(&bitStream)); + ASSERT_EQ(res->GetValueType(), AMFValueType::AMFNull); + return 0; +} + +int ReadAMFFalseFromBitStream() { + CBITSTREAM + bitStream.Write(0x02); + std::unique_ptr res(ReadFromBitStream(&bitStream)); + ASSERT_EQ(res->GetValueType(), AMFValueType::AMFFalse); + return 0; +} + +int ReadAMFTrueFromBitStream() { + CBITSTREAM + bitStream.Write(0x03); + std::unique_ptr res(ReadFromBitStream(&bitStream)); + ASSERT_EQ(res->GetValueType(), AMFValueType::AMFTrue); + return 0; +} + +int ReadAMFIntegerFromBitStream() { + CBITSTREAM + { + bitStream.Write(0x04); + // 127 == 01111111 + bitStream.Write(127); + std::unique_ptr res(ReadFromBitStream(&bitStream)); + ASSERT_EQ(res->GetValueType(), AMFValueType::AMFInteger); + // Check that the max value of a byte can be read correctly + ASSERT_EQ(static_cast(res.get())->GetIntegerValue(), 127); + } + bitStream.Reset(); + { + bitStream.Write(0x04); + bitStream.Write(UINT32_MAX); + std::unique_ptr res(ReadFromBitStream(&bitStream)); + ASSERT_EQ(res->GetValueType(), AMFValueType::AMFInteger); + // Check that we can read the maximum value correctly + ASSERT_EQ(static_cast(res.get())->GetIntegerValue(), 536870911); + } + bitStream.Reset(); + { + bitStream.Write(0x04); + // 131 == 10000011 + bitStream.Write(131); + // 255 == 11111111 + bitStream.Write(255); + // 127 == 01111111 + bitStream.Write(127); + std::unique_ptr res(ReadFromBitStream(&bitStream)); + ASSERT_EQ(res->GetValueType(), AMFValueType::AMFInteger); + // Check that short max can be read correctly + ASSERT_EQ(static_cast(res.get())->GetIntegerValue(), UINT16_MAX); + } + bitStream.Reset(); + { + bitStream.Write(0x04); + // 255 == 11111111 + bitStream.Write(255); + // 127 == 01111111 + bitStream.Write(127); + std::unique_ptr res(ReadFromBitStream(&bitStream)); + ASSERT_EQ(res->GetValueType(), AMFValueType::AMFInteger); + // Check that 2 byte max can be read correctly + ASSERT_EQ(static_cast(res.get())->GetIntegerValue(), 16383); + } + return 0; +} + +int ReadAMFDoubleFromBitStream() { + CBITSTREAM + bitStream.Write(0x05); + bitStream.Write(25346.4f); + std::unique_ptr res(ReadFromBitStream(&bitStream)); + ASSERT_EQ(res->GetValueType(), AMFValueType::AMFDouble); + ASSERT_EQ(static_cast(res.get())->GetDoubleValue(), 25346.4f); + return 0; +} + +int ReadAMFStringFromBitStream() { + CBITSTREAM + bitStream.Write(0x06); + bitStream.Write(0x0F); + std::string toWrite = "stateID"; + for (auto e : toWrite) bitStream.Write(e); + std::unique_ptr res(ReadFromBitStream(&bitStream)); + ASSERT_EQ(res->GetValueType(), AMFValueType::AMFString); + ASSERT_EQ(static_cast(res.get())->GetStringValue(), "stateID"); + return 0; +} + +int ReadAMFArrayFromBitStream() { + CBITSTREAM + // Test empty AMFArray + bitStream.Write(0x09); + bitStream.Write(0x01); + bitStream.Write(0x01); + { + std::unique_ptr res(ReadFromBitStream(&bitStream)); + ASSERT_EQ(res->GetValueType(), AMFValueType::AMFArray); + ASSERT_EQ(static_cast(res.get())->GetAssociativeMap().size(), 0); + ASSERT_EQ(static_cast(res.get())->GetDenseArray().size(), 0); + } + bitStream.Reset(); + // Test a key'd value + bitStream.Write(0x09); + bitStream.Write(0x01); + bitStream.Write(0x15); + for (auto e : "BehaviorID") if (e != '\0') bitStream.Write(e); + bitStream.Write(0x06); + bitStream.Write(0x0B); + for (auto e : "10447") if (e != '\0') bitStream.Write(e); + bitStream.Write(0x01); + { + std::unique_ptr res(ReadFromBitStream(&bitStream)); + ASSERT_EQ(res->GetValueType(), AMFValueType::AMFArray); + ASSERT_EQ(static_cast(res.get())->GetAssociativeMap().size(), 1); + ASSERT_EQ(static_cast(static_cast(res.get())->FindValue("BehaviorID"))->GetStringValue(), "10447"); + } + // Test a dense array + return 0; +} + +/** + * This test checks that if we recieve an unimplemented AMFValueType + * we correctly throw an error and can actch it. + */ +int TestUnimplementedAMFValues() { + std::vector unimplementedValues = { + AMFValueType::AMFXMLDoc, + AMFValueType::AMFDate, + AMFValueType::AMFObject, + AMFValueType::AMFXML, + AMFValueType::AMFByteArray, + AMFValueType::AMFVectorInt, + AMFValueType::AMFVectorUInt, + AMFValueType::AMFVectorDouble, + AMFValueType::AMFVectorObject, + AMFValueType::AMFDictionary + }; + // Run unimplemented tests to check that errors are thrown if + // unimplemented AMF values are attempted to be parsed. + std::ifstream fileStream; + fileStream.open("AMFBitStreamUnimplementedTest.bin", std::ios::binary); + + // Read a test BitStream from a file + std::vector baseBitStream; + char byte = 0; + while (fileStream.get(byte)) { + baseBitStream.push_back(byte); + } + + fileStream.close(); + + for (auto amfValueType : unimplementedValues) { + RakNet::BitStream testBitStream; + for (auto element : baseBitStream) { + testBitStream.Write(element); + } + testBitStream.Write(amfValueType); + bool caughtException = false; + try { + ReadFromBitStream(&testBitStream); + } catch (AMFValueType unimplementedValueType) { + caughtException = true; + } + std::cout << "Testing unimplemented value " << amfValueType << " Did we catch an exception: " << (caughtException ? "YES" : "NO") << std::endl; + ASSERT_EQ(caughtException, true); + } + return 0; +} + +int TestLiveCapture() { + std::ifstream testFileStream; + testFileStream.open("AMFBitStreamTest.bin", std::ios::binary); + + // Read a test BitStream from a file + RakNet::BitStream testBitStream; + char byte = 0; + while (testFileStream.get(byte)) { + testBitStream.Write(byte); + } + + testFileStream.close(); + + auto resultFromFn = ReadFromBitStream(&testBitStream); + auto result = static_cast(resultFromFn.get()); + // Test the outermost array + + ASSERT_EQ(dynamic_cast(result->FindValue("BehaviorID"))->GetStringValue(), "10447"); + ASSERT_EQ(dynamic_cast(result->FindValue("objectID"))->GetStringValue(), "288300744895913279") + + // Test the execution state array + auto executionState = dynamic_cast(result->FindValue("executionState")); + ASSERT_NE(executionState, nullptr); + + auto strips = dynamic_cast(executionState->FindValue("strips"))->GetDenseArray(); + + ASSERT_EQ(strips.size(), 1); + + auto stripsPosition0 = dynamic_cast(strips[0]); + + auto actionIndex = dynamic_cast(stripsPosition0->FindValue("actionIndex")); + + ASSERT_EQ(actionIndex->GetDoubleValue(), 0.0f); + + auto stripIDExecution = dynamic_cast(stripsPosition0->FindValue("id")); + + ASSERT_EQ(stripIDExecution->GetDoubleValue(), 0.0f); + + auto stateIDExecution = dynamic_cast(executionState->FindValue("stateID")); + + ASSERT_EQ(stateIDExecution->GetDoubleValue(), 0.0f); + + auto states = dynamic_cast(result->FindValue("states"))->GetDenseArray(); + + ASSERT_EQ(states.size(), 1); + + auto firstState = dynamic_cast(states[0]); + + auto stateID = dynamic_cast(firstState->FindValue("id")); + + ASSERT_EQ(stateID->GetDoubleValue(), 0.0f); + + auto stripsInState = dynamic_cast(firstState->FindValue("strips"))->GetDenseArray(); + + ASSERT_EQ(stripsInState.size(), 1); + + auto firstStrip = dynamic_cast(stripsInState[0]); + + auto actionsInFirstStrip = dynamic_cast(firstStrip->FindValue("actions"))->GetDenseArray(); + + ASSERT_EQ(actionsInFirstStrip.size(), 3); + + auto actionID = dynamic_cast(firstStrip->FindValue("id")); + + ASSERT_EQ(actionID->GetDoubleValue(), 0.0f) + + auto uiArray = dynamic_cast(firstStrip->FindValue("ui")); + + auto xPos = dynamic_cast(uiArray->FindValue("x")); + auto yPos = dynamic_cast(uiArray->FindValue("y")); + + ASSERT_EQ(xPos->GetDoubleValue(), 103.0f); + ASSERT_EQ(yPos->GetDoubleValue(), 82.0f); + + auto stripID = dynamic_cast(firstStrip->FindValue("id")); + + ASSERT_EQ(stripID->GetDoubleValue(), 0.0f) + + auto firstAction = dynamic_cast(actionsInFirstStrip[0]); + + auto firstType = dynamic_cast(firstAction->FindValue("Type")); + + ASSERT_EQ(firstType->GetStringValue(), "OnInteract"); + + auto firstCallback = dynamic_cast(firstAction->FindValue("__callbackID__")); + + ASSERT_EQ(firstCallback->GetStringValue(), ""); + + auto secondAction = dynamic_cast(actionsInFirstStrip[1]); + + auto secondType = dynamic_cast(secondAction->FindValue("Type")); + + ASSERT_EQ(secondType->GetStringValue(), "FlyUp"); + + auto secondCallback = dynamic_cast(secondAction->FindValue("__callbackID__")); + + ASSERT_EQ(secondCallback->GetStringValue(), ""); + + auto secondDistance = dynamic_cast(secondAction->FindValue("Distance")); + + ASSERT_EQ(secondDistance->GetDoubleValue(), 25.0f); + + auto thirdAction = dynamic_cast(actionsInFirstStrip[2]); + + auto thirdType = dynamic_cast(thirdAction->FindValue("Type")); + + ASSERT_EQ(thirdType->GetStringValue(), "FlyDown"); + + auto thirdCallback = dynamic_cast(thirdAction->FindValue("__callbackID__")); + + ASSERT_EQ(thirdCallback->GetStringValue(), ""); + + auto thirdDistance = dynamic_cast(thirdAction->FindValue("Distance")); + + ASSERT_EQ(thirdDistance->GetDoubleValue(), 25.0f); + + return 0; +} + +int TestNullStream() { + auto result = ReadFromBitStream(nullptr); + ASSERT_EQ(result.get(), nullptr); + return 0; +} + +int AMFDeserializeTests(int argc, char** const argv) { + std::cout << "Checking that using a null bitstream doesnt cause exception" << std::endl; + if (TestNullStream()) return 1; + std::cout << "passed nullptr test, checking basic tests" << std::endl; + if (ReadAMFUndefinedFromBitStream() != 0) return 1; + if (ReadAMFNullFromBitStream() != 0) return 1; + if (ReadAMFFalseFromBitStream() != 0) return 1; + if (ReadAMFTrueFromBitStream() != 0) return 1; + if (ReadAMFIntegerFromBitStream() != 0) return 1; + if (ReadAMFDoubleFromBitStream() != 0) return 1; + if (ReadAMFStringFromBitStream() != 0) return 1; + if (ReadAMFArrayFromBitStream() != 0) return 1; + std::cout << "Passed basic test, checking live capture" << std::endl; + if (TestLiveCapture() != 0) return 1; + std::cout << "Passed live capture, checking unimplemented amf values" << std::endl; + if (TestUnimplementedAMFValues() != 0) return 1; + std::cout << "Passed all tests." << std::endl; + return 0; +} + +/** + * Below is the AMF that is in the AMFBitStreamTest.bin file that we are reading in + * from a bitstream to test. +args: amf3! +{ + "objectID": "288300744895913279", + "BehaviorID": "10447", + "executionState": amf3! + { + "strips": amf3! + [ + amf3! + { + "actionIndex": 0.0, + "id": 0.0, + }, + ], + "stateID": 0.0, + }, + "states": amf3! + [ + amf3! + { + "id": 0.0, + "strips": amf3! + [ + amf3! + { + "actions": amf3! + [ + amf3! + { + "Type": "OnInteract", + "__callbackID__": "", + }, + amf3! + { + "Distance": 25.0, + "Type": "FlyUp", + "__callbackID__": "", + }, + amf3! + { + "Distance": 25.0, + "Type": "FlyDown", + "__callbackID__": "", + }, + ], + "id": 0.0, + "ui": amf3! + { + "x": 103.0, + "y": 82.0, + }, + }, + ], + }, + ], +} + */ diff --git a/tests/CMakeLists.txt b/tests/CMakeLists.txt index b0e2c28d..9c6e57d3 100644 --- a/tests/CMakeLists.txt +++ b/tests/CMakeLists.txt @@ -1,6 +1,7 @@ # create the testing file and list of tests create_test_sourcelist (Tests CommonCxxTests.cpp + AMFDeserializeTests.cpp TestNiPoint3.cpp TestLDFFormat.cpp ) @@ -13,6 +14,17 @@ target_link_libraries(CommonCxxTests ${COMMON_LIBRARIES}) set (TestsToRun ${Tests}) remove (TestsToRun CommonCxxTests.cpp) +# Copy test files to testing directory +configure_file( + ${CMAKE_SOURCE_DIR}/tests/TestBitStreams/AMFBitStreamTest.bin ${PROJECT_BINARY_DIR}/tests/AMFBitStreamTest.bin + COPYONLY +) + +configure_file( + ${CMAKE_SOURCE_DIR}/tests/TestBitStreams/AMFBitStreamUnimplementedTest.bin ${PROJECT_BINARY_DIR}/tests/AMFBitStreamUnimplementedTest.bin + COPYONLY +) + # Add all the ADD_TEST for each test foreach (test ${TestsToRun}) get_filename_component (TName ${test} NAME_WE) diff --git a/tests/TestBitStreams/AMFBitStreamTest.bin b/tests/TestBitStreams/AMFBitStreamTest.bin new file mode 100644 index 0000000000000000000000000000000000000000..05241f3517e805abc4e514b272b138709e6b1c49 GIT binary patch literal 329 zcmd;N6m?3?NG!|DFYESEy>K!3oc14N#$hZF9y+`F02etz*}5W zlvz;B$;`;fD4v)MQtFwPl3D>*z?zu?XEQPi<|k#PCYJy$P&Kl!Fg7qSH!-oWG_^D| zHZr#angui*Vipfv69?FAeu&w{oa{i0I72E6QrSfPfmW5I76D~s|Q^2_r;G6CLL>d49 literal 0 HcmV?d00001 diff --git a/tests/TestBitStreams/AMFBitStreamUnimplementedTest.bin b/tests/TestBitStreams/AMFBitStreamUnimplementedTest.bin new file mode 100644 index 00000000..624bc5c3 --- /dev/null +++ b/tests/TestBitStreams/AMFBitStreamUnimplementedTest.bin @@ -0,0 +1 @@ + BehaviorID \ No newline at end of file From 082a2a418f345c6c39ff6bca4f8ac60e39e0285f Mon Sep 17 00:00:00 2001 From: EmosewaMC <39972741+EmosewaMC@users.noreply.github.com> Date: Tue, 19 Jul 2022 23:25:50 -0700 Subject: [PATCH 10/86] Use radii from settings Override the DB aggro and tether radii from the settings if they are present. --- dGame/dComponents/BaseCombatAIComponent.cpp | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/dGame/dComponents/BaseCombatAIComponent.cpp b/dGame/dComponents/BaseCombatAIComponent.cpp index 0903e621..4623e4dd 100644 --- a/dGame/dComponents/BaseCombatAIComponent.cpp +++ b/dGame/dComponents/BaseCombatAIComponent.cpp @@ -61,6 +61,15 @@ BaseCombatAIComponent::BaseCombatAIComponent(Entity* parent, const uint32_t id) componentResult.finalize(); + // Get aggro and tether radius from settings and use this if it is present. Only overwrite the + // radii if it is greater than the one in the database. + if (m_Parent) { + auto aggroRadius = m_Parent->GetVar(u"aggroRadius"); + m_AggroRadius = std::max(aggroRadius, m_AggroRadius); + auto tetherRadius = m_Parent->GetVar(u"tetherRadius"); + m_HardTetherRadius = std::max(tetherRadius, m_HardTetherRadius); + } + /* * Find skills */ From 74bca382534ea4f898855b22271cbbc99ede3ee1 Mon Sep 17 00:00:00 2001 From: Daniel Seiler Date: Wed, 20 Jul 2022 10:23:53 +0200 Subject: [PATCH 11/86] MSVC: set source / target encoding (#659) --- CMakeLists.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index a9218bdf..65df9a35 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -63,7 +63,7 @@ if(UNIX) set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -std=c99 -O2 -fPIC") elseif(MSVC) # Skip warning for invalid conversion from size_t to uint32_t for all targets below for now - add_compile_options("/wd4267") + add_compile_options("/wd4267" "/utf-8") elseif(WIN32) add_compile_definitions(_CRT_SECURE_NO_WARNINGS) endif() From 45a7dbdadd1a30ef3b54fc0e0507f627efb251bb Mon Sep 17 00:00:00 2001 From: David Markowitz <39972741+EmosewaMC@users.noreply.github.com> Date: Wed, 20 Jul 2022 01:28:57 -0700 Subject: [PATCH 12/86] Add Unimplemented GameMessages (#662) --- dGame/dGameMessages/GameMessageHandler.cpp | 4 +++ dGame/dGameMessages/GameMessages.cpp | 36 ++++++++++++++++++++++ dGame/dGameMessages/GameMessages.h | 33 ++++++++++++++++++++ dNet/dMessageIdentifiers.h | 3 ++ 4 files changed, 76 insertions(+) diff --git a/dGame/dGameMessages/GameMessageHandler.cpp b/dGame/dGameMessages/GameMessageHandler.cpp index cdaae38c..261a3105 100644 --- a/dGame/dGameMessages/GameMessageHandler.cpp +++ b/dGame/dGameMessages/GameMessageHandler.cpp @@ -535,6 +535,10 @@ void GameMessageHandler::HandleMessage(RakNet::BitStream* inStream, const System GameMessages::HandleBBBSaveRequest(inStream, entity, sysAddr); break; + case GAME_MSG_CONTROL_BEHAVIOR: + GameMessages::HandleControlBehaviors(inStream, entity, sysAddr); + break; + case GAME_MSG_PROPERTY_ENTRANCE_SYNC: GameMessages::HandlePropertyEntranceSync(inStream, entity, sysAddr); break; diff --git a/dGame/dGameMessages/GameMessages.cpp b/dGame/dGameMessages/GameMessages.cpp index 292afc71..ba410b70 100644 --- a/dGame/dGameMessages/GameMessages.cpp +++ b/dGame/dGameMessages/GameMessages.cpp @@ -2420,6 +2420,42 @@ void GameMessages::HandleBBBLoadItemRequest(RakNet::BitStream* inStream, Entity* SEND_PACKET; } +void GameMessages::SendSmash(Entity* entity, float force, float ghostOpacity, LWOOBJID killerID, bool ignoreObjectVisibility) { + CBITSTREAM + CMSGHEADER + + bitStream.Write(entity->GetObjectID()); + bitStream.Write(GAME_MSG::GAME_MSG_SMASH); + + bitStream.Write(ignoreObjectVisibility); + bitStream.Write(force); + bitStream.Write(ghostOpacity); + bitStream.Write(killerID); + + SEND_PACKET_BROADCAST +} + +void GameMessages::SendUnSmash(Entity* entity, LWOOBJID builderID, float duration) { + CBITSTREAM + CMSGHEADER + + bitStream.Write(entity->GetObjectID()); + bitStream.Write(GAME_MSG::GAME_MSG_UNSMASH); + + bitStream.Write(builderID != LWOOBJID_EMPTY); + if (builderID != LWOOBJID_EMPTY) bitStream.Write(builderID); + + bitStream.Write(duration != 3.0f); + if (duration != 3.0f) bitStream.Write(duration); + + SEND_PACKET_BROADCAST +} + +void GameMessages::HandleControlBehaviors(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr) { + // TODO + Game::logger->Log("GameMessages", "Recieved Control Behavior GameMessage, but property behaviors are unimplemented.\n"); +} + void GameMessages::HandleBBBSaveRequest(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr) { /* ___ ___ diff --git a/dGame/dGameMessages/GameMessages.h b/dGame/dGameMessages/GameMessages.h index 18e1467e..fc49ad70 100644 --- a/dGame/dGameMessages/GameMessages.h +++ b/dGame/dGameMessages/GameMessages.h @@ -122,6 +122,39 @@ namespace GameMessages { void SendStartCelebrationEffect(Entity* entity, const SystemAddress& sysAddr, int celebrationID); + /** + * Sends a message to an Entity to smash itself, but not delete or destroy itself from the world + * + * @param entity The Entity that will smash itself into bricks + * @param force The force the Entity will be smashed with + * @param ghostOpacity The ghosting opacity of the smashed Entity + * @param killerID The Entity that invoked the smash, if none exists, this should be LWOOBJID_EMPTY + * @param ignoreObjectVisibility Whether or not to ignore the objects visibility + */ + void SendSmash(Entity* entity, float force, float ghostOpacity, LWOOBJID killerID, bool ignoreObjectVisibility = false); + + /** + * Sends a message to an Entity to UnSmash itself (aka rebuild itself over a duration) + * + * @param entity The Entity that will UnSmash itself + * @param builderID The Entity that invoked the build (LWOOBJID_EMPTY if none exists or invoked the rebuild) + * @param duration The duration for the Entity to rebuild over. 3 seconds by default + */ + void SendUnSmash(Entity* entity, LWOOBJID builderID = LWOOBJID_EMPTY, float duration = 3.0f); + + /** + * @brief This GameMessage is the one that handles all of the property behavior incoming messages from the client. + * + * The GameMessage struct can be located here https://lcdruniverse.org/lu_packets/lu_packets/world/gm/server/struct.ControlBehaviors.html + * For information on the AMF3 format can be found here https://rtmp.veriskope.com/pdf/amf3-file-format-spec.pdf + * For any questions regarding AMF3 you can contact EmosewaMC on GitHub + * + * @param inStream The incoming data sent from the client + * @param entity The Entity that sent the message + * @param sysAddr The SystemAddress that sent the message + */ + void HandleControlBehaviors(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr); + // Rails stuff void SendSetRailMovement(const LWOOBJID& objectID, bool pathGoForward, std::u16string pathName, uint32_t pathStart, const SystemAddress& sysAddr = UNASSIGNED_SYSTEM_ADDRESS, diff --git a/dNet/dMessageIdentifiers.h b/dNet/dMessageIdentifiers.h index 5ad3921c..cb46b5d1 100644 --- a/dNet/dMessageIdentifiers.h +++ b/dNet/dMessageIdentifiers.h @@ -274,6 +274,7 @@ enum GAME_MSG : unsigned short { GAME_MSG_REQUEST_DIE = 38, GAME_MSG_PLAY_EMOTE = 41, GAME_MSG_PLAY_ANIMATION = 43, + GAME_MSG_CONTROL_BEHAVIOR = 48, GAME_MSG_SET_NAME = 72, GAME_MSG_ECHO_START_SKILL = 118, GAME_MSG_START_SKILL = 119, @@ -345,6 +346,8 @@ enum GAME_MSG : unsigned short { GAME_MSG_DISPLAY_MESSAGE_BOX = 529, GAME_MSG_MESSAGE_BOX_RESPOND = 530, GAME_MSG_CHOICE_BOX_RESPOND = 531, + GAME_MSG_SMASH = 537, + GAME_MSG_UNSMASH = 538, GAME_MSG_SET_SHOOTING_GALLERY_RETICULE_EFFECT = 548, GAME_MSG_PLACE_MODEL_RESPONSE = 0x223, GAME_MSG_SET_JET_PACK_MODE = 561, From 40a9aefb5bacd2d5c5a6f357ec2d46fdc6c04718 Mon Sep 17 00:00:00 2001 From: David Markowitz <39972741+EmosewaMC@users.noreply.github.com> Date: Wed, 20 Jul 2022 20:26:52 -0700 Subject: [PATCH 13/86] Aggro radius (#665) --- dGame/dComponents/BaseCombatAIComponent.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/dGame/dComponents/BaseCombatAIComponent.cpp b/dGame/dComponents/BaseCombatAIComponent.cpp index 4623e4dd..bfa000f2 100644 --- a/dGame/dComponents/BaseCombatAIComponent.cpp +++ b/dGame/dComponents/BaseCombatAIComponent.cpp @@ -65,9 +65,9 @@ BaseCombatAIComponent::BaseCombatAIComponent(Entity* parent, const uint32_t id) // radii if it is greater than the one in the database. if (m_Parent) { auto aggroRadius = m_Parent->GetVar(u"aggroRadius"); - m_AggroRadius = std::max(aggroRadius, m_AggroRadius); + m_AggroRadius = aggroRadius != 0 ? aggroRadius : m_AggroRadius; auto tetherRadius = m_Parent->GetVar(u"tetherRadius"); - m_HardTetherRadius = std::max(tetherRadius, m_HardTetherRadius); + m_HardTetherRadius = tetherRadius != 0 ? tetherRadius : m_HardTetherRadius; } /* From 5523b6aafc346f1e368682badda9b4fe49279e84 Mon Sep 17 00:00:00 2001 From: Aaron Kimbrell Date: Thu, 21 Jul 2022 21:09:25 -0500 Subject: [PATCH 14/86] Refactor UpdateEntities to not lose items if we add them while processing (#664) * if we are deleting entities, and we add an entity to delete, dont throw it out * made it all uniform * change update back to how it was since it's an unordere map and wouldn't be guaranteed to update even in this secnario --- dGame/EntityManager.cpp | 125 +++++++++++++++------------------------- 1 file changed, 48 insertions(+), 77 deletions(-) diff --git a/dGame/EntityManager.cpp b/dGame/EntityManager.cpp index da0cf685..d6e6256f 100644 --- a/dGame/EntityManager.cpp +++ b/dGame/EntityManager.cpp @@ -74,7 +74,7 @@ Entity* EntityManager::CreateEntity(EntityInfo info, User* user, Entity* parentE // For non player entites, we'll generate a new ID or set the appropiate flags else if (user == nullptr || info.lot != 1) { - + // Entities with no ID already set, often spawned entities, we'll generate a new sequencial ID if (info.id == 0) { id = ObjectIDManager::Instance()->GenerateObjectID(); @@ -104,7 +104,7 @@ Entity* EntityManager::CreateEntity(EntityInfo info, User* user, Entity* parentE } info.id = id; - + Entity* entity; // Check if the entitty if a player, in case use the extended player entity class @@ -117,7 +117,7 @@ Entity* EntityManager::CreateEntity(EntityInfo info, User* user, Entity* parentE // Initialize the entity entity->Initialize(); - + // Add the entity to the entity map m_Entities.insert_or_assign(id, entity); @@ -162,110 +162,81 @@ void EntityManager::DestroyEntity(Entity* entity) { void EntityManager::UpdateEntities(const float deltaTime) { for (const auto& e : m_Entities) { - e.second->Update(deltaTime); + e.second->Update(deltaTime); } - for (const auto entityId : m_EntitiesToSerialize) - { - auto* entity = GetEntity(entityId); + for (auto entry = m_EntitiesToSerialize.begin(); entry != m_EntitiesToSerialize.end(); entry++) { + auto* entity = GetEntity(*entry); if (entity == nullptr) continue; m_SerializationCounter++; RakNet::BitStream stream; - stream.Write(static_cast(ID_REPLICA_MANAGER_SERIALIZE)); stream.Write(static_cast(entity->GetNetworkId())); entity->WriteBaseReplicaData(&stream, PACKET_TYPE_SERIALIZATION); entity->WriteComponents(&stream, PACKET_TYPE_SERIALIZATION); - if (entity->GetIsGhostingCandidate()) - { - for (auto* player : Player::GetAllPlayers()) - { - if (player->IsObserved(entityId)) - { + if (entity->GetIsGhostingCandidate()) { + for (auto* player : Player::GetAllPlayers()) { + if (player->IsObserved(*entry)) { Game::server->Send(&stream, player->GetSystemAddress(), false); } } - } - else - { + } else { Game::server->Send(&stream, UNASSIGNED_SYSTEM_ADDRESS, true); } } - m_EntitiesToSerialize.clear(); - for (const auto& entry : m_EntitiesToKill) - { - auto* entity = GetEntity(entry); + for (auto entry = m_EntitiesToKill.begin(); entry != m_EntitiesToKill.end(); entry++) { + auto* entity = GetEntity(*entry); if (!entity) continue; - if (entity->GetScheduledKiller()) - { + if (entity->GetScheduledKiller()) { entity->Smash(entity->GetScheduledKiller()->GetObjectID(), SILENT); - } - else - { - entity->Smash(LWOOBJID_EMPTY, SILENT); + } else { + entity->Smash(LWOOBJID_EMPTY, SILENT); } } - m_EntitiesToKill.clear(); - for (const auto entry : m_EntitiesToDelete) - { + for (auto entry = m_EntitiesToDelete.begin(); entry != m_EntitiesToDelete.end(); entry++) { + // Get all this info first before we delete the player. - auto entityToDelete = GetEntity(entry); - + auto entityToDelete = GetEntity(*entry); auto networkIdToErase = entityToDelete->GetNetworkId(); - const auto& ghostingToDelete = std::find(m_EntitiesToGhost.begin(), m_EntitiesToGhost.end(), entityToDelete); - if (entityToDelete) - { + if (entityToDelete) { // If we are a player run through the player destructor. - if (entityToDelete->IsPlayer()) - { + if (entityToDelete->IsPlayer()) { delete dynamic_cast(entityToDelete); - } - else - { + } else { delete entityToDelete; } - entityToDelete = nullptr; - - if (networkIdToErase != 0) - { - m_LostNetworkIds.push(networkIdToErase); - } + if (networkIdToErase != 0) m_LostNetworkIds.push(networkIdToErase); } - if (ghostingToDelete != m_EntitiesToGhost.end()) - { - m_EntitiesToGhost.erase(ghostingToDelete); - } + if (ghostingToDelete != m_EntitiesToGhost.end()) m_EntitiesToGhost.erase(ghostingToDelete); - m_Entities.erase(entry); - + m_Entities.erase(*entry); } - m_EntitiesToDelete.clear(); } Entity * EntityManager::GetEntity(const LWOOBJID& objectId) const { const auto& index = m_Entities.find(objectId); - + if (index == m_Entities.end()) { return nullptr; } - + return index->second; } @@ -286,7 +257,7 @@ std::vector EntityManager::GetEntitiesByComponent(const int componentTy std::vector withComp; for (const auto& entity : m_Entities) { if (componentType != -1 && !entity.second->HasComponent(componentType)) continue; - + withComp.push_back(entity.second); } return withComp; @@ -331,7 +302,7 @@ void EntityManager::ConstructEntity(Entity* entity, const SystemAddress& sysAddr if (entity->GetNetworkId() == 0) { uint16_t networkId; - + if (!m_LostNetworkIds.empty()) { networkId = m_LostNetworkIds.top(); @@ -344,7 +315,7 @@ void EntityManager::ConstructEntity(Entity* entity, const SystemAddress& sysAddr entity->SetNetworkId(networkId); } - + const auto checkGhosting = entity->GetIsGhostingCandidate(); if (checkGhosting) @@ -365,13 +336,13 @@ void EntityManager::ConstructEntity(Entity* entity, const SystemAddress& sysAddr } m_SerializationCounter++; - + RakNet::BitStream stream; stream.Write(static_cast(ID_REPLICA_MANAGER_CONSTRUCTION)); stream.Write(true); stream.Write(static_cast(entity->GetNetworkId())); - + entity->WriteBaseReplicaData(&stream, PACKET_TYPE_CONSTRUCTION); entity->WriteComponents(&stream, PACKET_TYPE_CONSTRUCTION); @@ -430,7 +401,7 @@ void EntityManager::DestructEntity(Entity* entity, const SystemAddress& sysAddr) { return; } - + RakNet::BitStream stream; stream.Write(static_cast(ID_REPLICA_MANAGER_DESTRUCTION)); @@ -467,7 +438,7 @@ void EntityManager::DestructAllEntities(const SystemAddress& sysAddr) { } } -void EntityManager::SetGhostDistanceMax(float value) +void EntityManager::SetGhostDistanceMax(float value) { m_GhostDistanceMaxSquared = value * value; } @@ -477,7 +448,7 @@ float EntityManager::GetGhostDistanceMax() const return std::sqrt(m_GhostDistanceMaxSquared); } -void EntityManager::SetGhostDistanceMin(float value) +void EntityManager::SetGhostDistanceMin(float value) { m_GhostDistanceMinSqaured = value * value; } @@ -487,7 +458,7 @@ float EntityManager::GetGhostDistanceMin() const return std::sqrt(m_GhostDistanceMinSqaured); } -void EntityManager::QueueGhostUpdate(LWOOBJID playerID) +void EntityManager::QueueGhostUpdate(LWOOBJID playerID) { const auto& iter = std::find(m_PlayersToUpdateGhosting.begin(), m_PlayersToUpdateGhosting.end(), playerID); @@ -497,7 +468,7 @@ void EntityManager::QueueGhostUpdate(LWOOBJID playerID) } } -void EntityManager::UpdateGhosting() +void EntityManager::UpdateGhosting() { for (const auto playerID : m_PlayersToUpdateGhosting) { @@ -514,7 +485,7 @@ void EntityManager::UpdateGhosting() m_PlayersToUpdateGhosting.clear(); } -void EntityManager::UpdateGhosting(Player* player) +void EntityManager::UpdateGhosting(Player* player) { if (player == nullptr) { @@ -575,15 +546,15 @@ void EntityManager::UpdateGhosting(Player* player) } player->ObserveEntity(id); - + ConstructEntity(entity, player->GetSystemAddress()); - + entity->SetObservers(entity->GetObservers() + 1); } } } -void EntityManager::CheckGhosting(Entity* entity) +void EntityManager::CheckGhosting(Entity* entity) { if (entity == nullptr) { @@ -591,7 +562,7 @@ void EntityManager::CheckGhosting(Entity* entity) } const auto& referencePoint = entity->GetPosition(); - + auto ghostingDistanceMax = m_GhostDistanceMaxSquared; auto ghostingDistanceMin = m_GhostDistanceMinSqaured; @@ -618,15 +589,15 @@ void EntityManager::CheckGhosting(Entity* entity) else if (!observed && ghostingDistanceMin > distance) { player->ObserveEntity(id); - + ConstructEntity(entity, player->GetSystemAddress()); - + entity->SetObservers(entity->GetObservers() + 1); } } } -Entity* EntityManager::GetGhostCandidate(int32_t id) +Entity* EntityManager::GetGhostCandidate(int32_t id) { for (auto* entity : m_EntitiesToGhost) { @@ -635,7 +606,7 @@ Entity* EntityManager::GetGhostCandidate(int32_t id) return entity; } } - + return nullptr; } @@ -654,7 +625,7 @@ void EntityManager::ScheduleForKill(Entity* entity) { // Deactivate switches if they die if (!entity) return; - + SwitchComponent* switchComp = entity->GetComponent(); if (switchComp) { entity->TriggerEvent("OnDectivated"); @@ -670,7 +641,7 @@ void EntityManager::ScheduleForKill(Entity* entity) { m_EntitiesToKill.push_back(objectId); } -void EntityManager::ScheduleForDeletion(LWOOBJID entity) +void EntityManager::ScheduleForDeletion(LWOOBJID entity) { if (std::count(m_EntitiesToDelete.begin(), m_EntitiesToDelete.end(), entity)) { @@ -689,7 +660,7 @@ void EntityManager::FireEventServerSide(Entity* origin, std::string args) { } } -bool EntityManager::IsExcludedFromGhosting(LOT lot) +bool EntityManager::IsExcludedFromGhosting(LOT lot) { return std::find(m_GhostingExcludedLOTs.begin(), m_GhostingExcludedLOTs.end(), lot) != m_GhostingExcludedLOTs.end(); } From 6a38b67ed5508ec7bffdb985baf278a8ee833e1d Mon Sep 17 00:00:00 2001 From: David Markowitz <39972741+EmosewaMC@users.noreply.github.com> Date: Thu, 21 Jul 2022 22:26:09 -0700 Subject: [PATCH 15/86] General AMF cleanup (#663) * General AMF cleanup Proper memory management as well as style cleanup * General optimizations Fix AMFArray so values are properly deleted when you leave the scope it was created in. Add bounds check for deletion so you don't double delete. Remove all AMFdeletions that are contained in an array since the array now manages its own memory and deletes it when it is no longer needed. * Better tests and fix de-serialize Fix de-serialize to be correct and implement a test to check this * Update AMFDeserializeTests.cpp * Update AMFFormat.cpp --- dCommon/AMFDeserialize.cpp | 28 +- dCommon/AMFFormat.cpp | 14 + dCommon/AMFFormat.h | 4 + dCommon/AMFFormat_BitStream.cpp | 373 +++++++++--------- dCommon/AMFFormat_BitStream.h | 158 ++++---- dGame/dComponents/DestroyableComponent.cpp | 11 +- .../dComponents/PropertyEntranceComponent.cpp | 2 - dGame/dGameMessages/GameMessages.cpp | 5 +- dGame/dUtilities/SlashCommandHandler.cpp | 22 +- dScripts/BankInteractServer.cpp | 7 +- dScripts/MailBoxServer.cpp | 1 - dScripts/NsLegoClubDoor.cpp | 39 -- dScripts/PropertyBankInteract.cpp | 6 +- dScripts/StoryBoxInteractServer.cpp | 8 +- dWorldServer/WorldServer.cpp | 5 - tests/AMFDeserializeTests.cpp | 9 +- 16 files changed, 303 insertions(+), 389 deletions(-) diff --git a/dCommon/AMFDeserialize.cpp b/dCommon/AMFDeserialize.cpp index 7f3f6d95..afe2b61b 100644 --- a/dCommon/AMFDeserialize.cpp +++ b/dCommon/AMFDeserialize.cpp @@ -127,21 +127,23 @@ AMFValue* AMFDeserialize::ReadAmfDouble(RakNet::BitStream* inStream) { AMFValue* AMFDeserialize::ReadAmfArray(RakNet::BitStream* inStream) { auto arrayValue = new AMFArrayValue(); + + // Read size of dense array auto sizeOfDenseArray = (ReadU29(inStream) >> 1); - if (sizeOfDenseArray >= 1) { - char valueType; - inStream->Read(valueType); // Unused - for (uint32_t i = 0; i < sizeOfDenseArray; i++) { - arrayValue->PushBackValue(Read(inStream)); - } - } else { - while (true) { - auto key = ReadString(inStream); - // No more values when we encounter an empty string - if (key.size() == 0) break; - arrayValue->InsertValue(key, Read(inStream)); - } + + // Then read Key'd portion + while (true) { + auto key = ReadString(inStream); + // No more values when we encounter an empty string + if (key.size() == 0) break; + arrayValue->InsertValue(key, Read(inStream)); } + + // Finally read dense portion + for (uint32_t i = 0; i < sizeOfDenseArray; i++) { + arrayValue->PushBackValue(Read(inStream)); + } + return arrayValue; } diff --git a/dCommon/AMFFormat.cpp b/dCommon/AMFFormat.cpp index d4cf6531..741a8bc4 100644 --- a/dCommon/AMFFormat.cpp +++ b/dCommon/AMFFormat.cpp @@ -108,6 +108,14 @@ _AMFArrayList_::iterator AMFArrayValue::GetDenseIteratorEnd() { return this->dense.end(); } +AMFArrayValue::~AMFArrayValue() { + for (auto valueToDelete : GetDenseArray()) { + if (valueToDelete) delete valueToDelete; + } + for (auto valueToDelete : GetAssociativeMap()) { + if (valueToDelete.second) delete valueToDelete.second; + } +} // AMFObject Constructor AMFObjectValue::AMFObjectValue(std::vector> traits) { @@ -155,3 +163,9 @@ _AMFObjectTraits_::iterator AMFObjectValue::GetTraitsIteratorEnd() { uint32_t AMFObjectValue::GetTraitArrayCount() { return (uint32_t)this->traits.size(); } + +AMFObjectValue::~AMFObjectValue() { + for (auto valueToDelete = GetTraitsIteratorBegin(); valueToDelete != GetTraitsIteratorEnd(); valueToDelete++) { + if (valueToDelete->second.second) delete valueToDelete->second.second; + } +} diff --git a/dCommon/AMFFormat.h b/dCommon/AMFFormat.h index c3d0936c..54a02944 100644 --- a/dCommon/AMFFormat.h +++ b/dCommon/AMFFormat.h @@ -59,6 +59,7 @@ public: \return The AMF value type */ virtual AMFValueType GetValueType() = 0; + virtual ~AMFValue() {}; }; //! A typedef for a pointer to an AMF value @@ -233,6 +234,7 @@ public: }; //! The array value AMF type +// This object will manage it's own memory map and list. Do not delete its values. class AMFArrayValue : public AMFValue { private: _AMFArrayMap_ associative; //!< The array map (associative part) @@ -245,6 +247,7 @@ private: AMFValueType GetValueType() { return AMFArray; } public: + ~AMFArrayValue() override; //! Inserts an item into the array map for a specific key /*! \param key The key to set @@ -332,6 +335,7 @@ private: \return The AMF value type */ AMFValueType GetValueType() { return AMFObject; } + ~AMFObjectValue() override; public: //! Constructor diff --git a/dCommon/AMFFormat_BitStream.cpp b/dCommon/AMFFormat_BitStream.cpp index 57497951..96ccdab3 100644 --- a/dCommon/AMFFormat_BitStream.cpp +++ b/dCommon/AMFFormat_BitStream.cpp @@ -3,269 +3,248 @@ // Writes an AMFValue pointer to a RakNet::BitStream template<> void RakNet::BitStream::Write(AMFValue* value) { - if (value != nullptr) { - AMFValueType type = value->GetValueType(); - - switch (type) { - case AMFUndefined: { - AMFUndefinedValue* v = (AMFUndefinedValue*)value; - this->Write(*v); - break; - } - - case AMFNull: { - AMFNullValue* v = (AMFNullValue*)value; - this->Write(*v); - break; - } - - case AMFFalse: { - AMFFalseValue* v = (AMFFalseValue*)value; - this->Write(*v); - break; - } - - case AMFTrue: { - AMFTrueValue* v = (AMFTrueValue*)value; - this->Write(*v); - break; - } - - case AMFInteger: { - AMFIntegerValue* v = (AMFIntegerValue*)value; - this->Write(*v); - break; - } - - case AMFString: { - AMFStringValue* v = (AMFStringValue*)value; - this->Write(*v); - break; - } - - case AMFXMLDoc: { - AMFXMLDocValue* v = (AMFXMLDocValue*)value; - this->Write(*v); - break; - } - - case AMFDate: { - AMFDateValue* v = (AMFDateValue*)value; - this->Write(*v); - break; - } - - case AMFArray: { - AMFArrayValue* v = (AMFArrayValue*)value; - this->Write(*v); - break; - } - } - } + if (value != nullptr) { + AMFValueType type = value->GetValueType(); + + switch (type) { + case AMFUndefined: { + AMFUndefinedValue* v = (AMFUndefinedValue*)value; + this->Write(*v); + break; + } + + case AMFNull: { + AMFNullValue* v = (AMFNullValue*)value; + this->Write(*v); + break; + } + + case AMFFalse: { + AMFFalseValue* v = (AMFFalseValue*)value; + this->Write(*v); + break; + } + + case AMFTrue: { + AMFTrueValue* v = (AMFTrueValue*)value; + this->Write(*v); + break; + } + + case AMFInteger: { + AMFIntegerValue* v = (AMFIntegerValue*)value; + this->Write(*v); + break; + } + + case AMFDouble: { + AMFDoubleValue* v = (AMFDoubleValue*)value; + this->Write(*v); + break; + } + + case AMFString: { + AMFStringValue* v = (AMFStringValue*)value; + this->Write(*v); + break; + } + + case AMFXMLDoc: { + AMFXMLDocValue* v = (AMFXMLDocValue*)value; + this->Write(*v); + break; + } + + case AMFDate: { + AMFDateValue* v = (AMFDateValue*)value; + this->Write(*v); + break; + } + + case AMFArray: { + this->Write((AMFArrayValue*)value); + break; + } + } + } } -// A private function to write an value to a RakNet::BitStream +/** + * A private function to write an value to a RakNet::BitStream + * RakNet writes in the correct byte order - do not reverse this. + */ void WriteUInt29(RakNet::BitStream* bs, uint32_t v) { - unsigned char b4 = (unsigned char)v; - if (v < 0x00200000) { - b4 = b4 & 0x7F; - if (v > 0x7F) { - unsigned char b3; - v = v >> 7; - b3 = ((unsigned char)(v)) | 0x80; - if (v > 0x7F) { - unsigned char b2; - v = v >> 7; - b2 = ((unsigned char)(v)) | 0x80; - bs->Write(b2); - } - - bs->Write(b3); - } - } else { - unsigned char b1; - unsigned char b2; - unsigned char b3; - - v = v >> 8; - b3 = ((unsigned char)(v)) | 0x80; - v = v >> 7; - b2 = ((unsigned char)(v)) | 0x80; - v = v >> 7; - b1 = ((unsigned char)(v)) | 0x80; - - bs->Write(b1); - bs->Write(b2); - bs->Write(b3); - } - - bs->Write(b4); + unsigned char b4 = (unsigned char)v; + if (v < 0x00200000) { + b4 = b4 & 0x7F; + if (v > 0x7F) { + unsigned char b3; + v = v >> 7; + b3 = ((unsigned char)(v)) | 0x80; + if (v > 0x7F) { + unsigned char b2; + v = v >> 7; + b2 = ((unsigned char)(v)) | 0x80; + bs->Write(b2); + } + + bs->Write(b3); + } + } else { + unsigned char b1; + unsigned char b2; + unsigned char b3; + + v = v >> 8; + b3 = ((unsigned char)(v)) | 0x80; + v = v >> 7; + b2 = ((unsigned char)(v)) | 0x80; + v = v >> 7; + b1 = ((unsigned char)(v)) | 0x80; + + bs->Write(b1); + bs->Write(b2); + bs->Write(b3); + } + + bs->Write(b4); } -// Writes a flag number to a RakNet::BitStream +/** + * Writes a flag number to a RakNet::BitStream + * RakNet writes in the correct byte order - do not reverse this. + */ void WriteFlagNumber(RakNet::BitStream* bs, uint32_t v) { - v = (v << 1) | 0x01; - WriteUInt29(bs, v); + v = (v << 1) | 0x01; + WriteUInt29(bs, v); } -// Writes an AMFString to a RakNet::BitStream +/** + * Writes an AMFString to a RakNet::BitStream + * + * RakNet writes in the correct byte order - do not reverse this. + */ void WriteAMFString(RakNet::BitStream* bs, const std::string& str) { - WriteFlagNumber(bs, (uint32_t)str.size()); - bs->Write(str.c_str(), (uint32_t)str.size()); + WriteFlagNumber(bs, (uint32_t)str.size()); + bs->Write(str.c_str(), (uint32_t)str.size()); } -// Writes an AMF U16 to a RakNet::BitStream +/** + * Writes an U16 to a bitstream + * + * RakNet writes in the correct byte order - do not reverse this. + */ void WriteAMFU16(RakNet::BitStream* bs, uint16_t value) { - unsigned char b2; - b2 = (unsigned char)value; - value = value >> 8; - bs->Write((unsigned char)value); - bs->Write(b2); + bs->Write(value); } -// Writes an AMF U32 to RakNet::BitStream +/** + * Writes an U32 to a bitstream + * + * RakNet writes in the correct byte order - do not reverse this. + */ void WriteAMFU32(RakNet::BitStream* bs, uint32_t value) { - unsigned char b2; - unsigned char b3; - unsigned char b4; - - b4 = (unsigned char)value; - value = value >> 8; - b3 = (unsigned char)value; - value = value >> 8; - b2 = (unsigned char)value; - value = value >> 8; - - bs->Write((unsigned char)value); - bs->Write(b2); - bs->Write(b3); - bs->Write(b4); + bs->Write(value); } -// Writes an AMF U64 to RakNet::BitStream +/** + * Writes an U64 to a bitstream + * + * RakNet writes in the correct byte order - do not reverse this. + */ void WriteAMFU64(RakNet::BitStream* bs, uint64_t value) { - unsigned char b2; - unsigned char b3; - unsigned char b4; - unsigned char b5; - unsigned char b6; - unsigned char b7; - unsigned char b8; - - b8 = (unsigned char)value; - value = value >> 8; - b7 = (unsigned char)value; - value = value >> 8; - b6 = (unsigned char)value; - value = value >> 8; - b5 = (unsigned char)value; - value = value >> 8; - b4 = (unsigned char)value; - value = value >> 8; - b3 = (unsigned char)value; - value = value >> 8; - b2 = (unsigned char)value; - value = value >> 8; - - bs->Write((unsigned char)value); - bs->Write(b2); - bs->Write(b3); - bs->Write(b4); - bs->Write(b5); - bs->Write(b6); - bs->Write(b7); - bs->Write(b8); + bs->Write(value); } // Writes an AMFUndefinedValue to BitStream template<> void RakNet::BitStream::Write(AMFUndefinedValue value) { - this->Write(AMFUndefined); + this->Write(AMFUndefined); } // Writes an AMFNullValue to BitStream template<> void RakNet::BitStream::Write(AMFNullValue value) { - this->Write(AMFNull); + this->Write(AMFNull); } // Writes an AMFFalseValue to BitStream template<> void RakNet::BitStream::Write(AMFFalseValue value) { - this->Write(AMFFalse); + this->Write(AMFFalse); } // Writes an AMFTrueValue to BitStream template<> void RakNet::BitStream::Write(AMFTrueValue value) { - this->Write(AMFTrue); + this->Write(AMFTrue); } // Writes an AMFIntegerValue to BitStream template<> void RakNet::BitStream::Write(AMFIntegerValue value) { - this->Write(AMFInteger); - WriteUInt29(this, value.GetIntegerValue()); + this->Write(AMFInteger); + WriteUInt29(this, value.GetIntegerValue()); } // Writes an AMFDoubleValue to BitStream template<> void RakNet::BitStream::Write(AMFDoubleValue value) { - this->Write(AMFDouble); - double d = value.GetDoubleValue(); - WriteAMFU64(this, *((unsigned long long*)&d)); + this->Write(AMFDouble); + double d = value.GetDoubleValue(); + WriteAMFU64(this, *((unsigned long long*)&d)); } // Writes an AMFStringValue to BitStream template<> void RakNet::BitStream::Write(AMFStringValue value) { - this->Write(AMFString); - std::string v = value.GetStringValue(); - WriteAMFString(this, v); + this->Write(AMFString); + std::string v = value.GetStringValue(); + WriteAMFString(this, v); } // Writes an AMFXMLDocValue to BitStream template<> void RakNet::BitStream::Write(AMFXMLDocValue value) { - this->Write(AMFXMLDoc); - std::string v = value.GetXMLDocValue(); - WriteAMFString(this, v); + this->Write(AMFXMLDoc); + std::string v = value.GetXMLDocValue(); + WriteAMFString(this, v); } // Writes an AMFDateValue to BitStream template<> void RakNet::BitStream::Write(AMFDateValue value) { - this->Write(AMFDate); - uint64_t date = value.GetDateValue(); - WriteAMFU64(this, date); + this->Write(AMFDate); + uint64_t date = value.GetDateValue(); + WriteAMFU64(this, date); } // Writes an AMFArrayValue to BitStream template<> -void RakNet::BitStream::Write(AMFArrayValue value) { - this->Write(AMFArray); - uint32_t denseSize = value.GetDenseValueSize(); - WriteFlagNumber(this, denseSize); - - _AMFArrayMap_::iterator it = value.GetAssociativeIteratorValueBegin(); - _AMFArrayMap_::iterator end = value.GetAssociativeIteratorValueEnd(); - - while (it != end) { - WriteAMFString(this, it->first); - this->Write(it->second); - it++; - } - - this->Write(AMFNull); - - if (denseSize > 0) { - _AMFArrayList_::iterator it2 = value.GetDenseIteratorBegin(); - _AMFArrayList_::iterator end2 = value.GetDenseIteratorEnd(); - - while (it2 != end2) { - this->Write(*it2); - it2++; - } - } +void RakNet::BitStream::Write(AMFArrayValue* value) { + this->Write(AMFArray); + uint32_t denseSize = value->GetDenseValueSize(); + WriteFlagNumber(this, denseSize); + + _AMFArrayMap_::iterator it = value->GetAssociativeIteratorValueBegin(); + _AMFArrayMap_::iterator end = value->GetAssociativeIteratorValueEnd(); + + while (it != end) { + WriteAMFString(this, it->first); + this->Write(it->second); + it++; + } + + this->Write(AMFNull); + + if (denseSize > 0) { + _AMFArrayList_::iterator it2 = value->GetDenseIteratorBegin(); + _AMFArrayList_::iterator end2 = value->GetDenseIteratorEnd(); + + while (it2 != end2) { + this->Write(*it2); + it2++; + } + } } diff --git a/dCommon/AMFFormat_BitStream.h b/dCommon/AMFFormat_BitStream.h index 69dd0896..ff72a180 100644 --- a/dCommon/AMFFormat_BitStream.h +++ b/dCommon/AMFFormat_BitStream.h @@ -7,86 +7,86 @@ #include /*! - \file AMFBitStream.hpp - \brief A class that implements native writing of AMF values to RakNet::BitStream + \file AMFFormat_BitStream.h + \brief A class that implements native writing of AMF values to RakNet::BitStream */ // We are using the RakNet namespace namespace RakNet { - //! Writes an AMFValue pointer to a RakNet::BitStream - /*! - \param value The value to write - */ - template<> - void RakNet::BitStream::Write(AMFValue* value); - - //! Writes an AMFUndefinedValue to a RakNet::BitStream - /*! - \param value The value to write - */ - template<> - void RakNet::BitStream::Write(AMFUndefinedValue value); - - //! Writes an AMFNullValue to a RakNet::BitStream - /*! - \param value The value to write - */ - template<> - void RakNet::BitStream::Write(AMFNullValue value); - - //! Writes an AMFFalseValue to a RakNet::BitStream - /*! - \param value The value to write - */ - template<> - void RakNet::BitStream::Write(AMFFalseValue value); - - //! Writes an AMFTrueValue to a RakNet::BitStream - /*! - \param value The value to write - */ - template<> - void RakNet::BitStream::Write(AMFTrueValue value); - - //! Writes an AMFIntegerValue to a RakNet::BitStream - /*! - \param value The value to write - */ - template<> - void RakNet::BitStream::Write(AMFIntegerValue value); - - //! Writes an AMFDoubleValue to a RakNet::BitStream - /*! - \param value The value to write - */ - template<> - void RakNet::BitStream::Write(AMFDoubleValue value); - - //! Writes an AMFStringValue to a RakNet::BitStream - /*! - \param value The value to write - */ - template<> - void RakNet::BitStream::Write(AMFStringValue value); - - //! Writes an AMFXMLDocValue to a RakNet::BitStream - /*! - \param value The value to write - */ - template<> - void RakNet::BitStream::Write(AMFXMLDocValue value); - - //! Writes an AMFDateValue to a RakNet::BitStream - /*! - \param value The value to write - */ - template<> - void RakNet::BitStream::Write(AMFDateValue value); - - //! Writes an AMFArrayValue to a RakNet::BitStream - /*! - \param value The value to write - */ - template<> - void RakNet::BitStream::Write(AMFArrayValue value); -} + //! Writes an AMFValue pointer to a RakNet::BitStream + /*! + \param value The value to write + */ + template <> + void RakNet::BitStream::Write(AMFValue* value); + + //! Writes an AMFUndefinedValue to a RakNet::BitStream + /*! + \param value The value to write + */ + template <> + void RakNet::BitStream::Write(AMFUndefinedValue value); + + //! Writes an AMFNullValue to a RakNet::BitStream + /*! + \param value The value to write + */ + template <> + void RakNet::BitStream::Write(AMFNullValue value); + + //! Writes an AMFFalseValue to a RakNet::BitStream + /*! + \param value The value to write + */ + template <> + void RakNet::BitStream::Write(AMFFalseValue value); + + //! Writes an AMFTrueValue to a RakNet::BitStream + /*! + \param value The value to write + */ + template <> + void RakNet::BitStream::Write(AMFTrueValue value); + + //! Writes an AMFIntegerValue to a RakNet::BitStream + /*! + \param value The value to write + */ + template <> + void RakNet::BitStream::Write(AMFIntegerValue value); + + //! Writes an AMFDoubleValue to a RakNet::BitStream + /*! + \param value The value to write + */ + template <> + void RakNet::BitStream::Write(AMFDoubleValue value); + + //! Writes an AMFStringValue to a RakNet::BitStream + /*! + \param value The value to write + */ + template <> + void RakNet::BitStream::Write(AMFStringValue value); + + //! Writes an AMFXMLDocValue to a RakNet::BitStream + /*! + \param value The value to write + */ + template <> + void RakNet::BitStream::Write(AMFXMLDocValue value); + + //! Writes an AMFDateValue to a RakNet::BitStream + /*! + \param value The value to write + */ + template <> + void RakNet::BitStream::Write(AMFDateValue value); + + //! Writes an AMFArrayValue to a RakNet::BitStream + /*! + \param value The value to write + */ + template <> + void RakNet::BitStream::Write(AMFArrayValue* value); +} // namespace RakNet diff --git a/dGame/dComponents/DestroyableComponent.cpp b/dGame/dComponents/DestroyableComponent.cpp index 37d74a55..efcfb5cb 100644 --- a/dGame/dComponents/DestroyableComponent.cpp +++ b/dGame/dComponents/DestroyableComponent.cpp @@ -234,10 +234,8 @@ void DestroyableComponent::SetMaxHealth(float value, bool playAnim) { AMFArrayValue args; args.InsertValue("amount", amount); args.InsertValue("type", type); - GameMessages::SendUIMessageServerToSingleClient(m_Parent, m_Parent->GetParentUser()->GetSystemAddress(), "MaxPlayerBarUpdate", &args); - delete amount; - delete type; + GameMessages::SendUIMessageServerToSingleClient(m_Parent, m_Parent->GetParentUser()->GetSystemAddress(), "MaxPlayerBarUpdate", &args); } EntityManager::Instance()->SerializeEntity(m_Parent); @@ -283,9 +281,6 @@ void DestroyableComponent::SetMaxArmor(float value, bool playAnim) { args.InsertValue("type", type); GameMessages::SendUIMessageServerToSingleClient(m_Parent, m_Parent->GetParentUser()->GetSystemAddress(), "MaxPlayerBarUpdate", &args); - - delete amount; - delete type; } EntityManager::Instance()->SerializeEntity(m_Parent); @@ -328,10 +323,8 @@ void DestroyableComponent::SetMaxImagination(float value, bool playAnim) { AMFArrayValue args; args.InsertValue("amount", amount); args.InsertValue("type", type); - GameMessages::SendUIMessageServerToSingleClient(m_Parent, m_Parent->GetParentUser()->GetSystemAddress(), "MaxPlayerBarUpdate", &args); - delete amount; - delete type; + GameMessages::SendUIMessageServerToSingleClient(m_Parent, m_Parent->GetParentUser()->GetSystemAddress(), "MaxPlayerBarUpdate", &args); } EntityManager::Instance()->SerializeEntity(m_Parent); } diff --git a/dGame/dComponents/PropertyEntranceComponent.cpp b/dGame/dComponents/PropertyEntranceComponent.cpp index 87e0c7ed..4be059ed 100644 --- a/dGame/dComponents/PropertyEntranceComponent.cpp +++ b/dGame/dComponents/PropertyEntranceComponent.cpp @@ -40,8 +40,6 @@ void PropertyEntranceComponent::OnUse(Entity* entity) { args.InsertValue("state", state); GameMessages::SendUIMessageServerToSingleClient(entity, entity->GetSystemAddress(), "pushGameState", &args); - - delete state; } void PropertyEntranceComponent::OnEnterProperty(Entity* entity, uint32_t index, bool returnToZone, const SystemAddress& sysAddr) diff --git a/dGame/dGameMessages/GameMessages.cpp b/dGame/dGameMessages/GameMessages.cpp index ba410b70..a971b723 100644 --- a/dGame/dGameMessages/GameMessages.cpp +++ b/dGame/dGameMessages/GameMessages.cpp @@ -4978,12 +4978,9 @@ void GameMessages::HandleFireEventServerSide(RakNet::BitStream* inStream, Entity } if (args == u"toggleMail") { - AMFFalseValue* value = new AMFFalseValue(); - AMFArrayValue args; - args.InsertValue("visible", value); + args.InsertValue("visible", new AMFFalseValue()); GameMessages::SendUIMessageServerToSingleClient(entity, sysAddr, "ToggleMail", &args); - delete value; } // This should probably get it's own "ServerEvents" system or something at some point diff --git a/dGame/dUtilities/SlashCommandHandler.cpp b/dGame/dUtilities/SlashCommandHandler.cpp index 74d44ce7..22fbb680 100644 --- a/dGame/dUtilities/SlashCommandHandler.cpp +++ b/dGame/dUtilities/SlashCommandHandler.cpp @@ -276,27 +276,21 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit args.InsertValue("state", state); GameMessages::SendUIMessageServerToSingleClient(entity, entity->GetSystemAddress(), "pushGameState", &args); - - delete state; } entity->AddCallbackTimer(0.5f, [customText, entity] () { AMFArrayValue args; - auto* visiable = new AMFTrueValue(); auto* text = new AMFStringValue(); text->SetStringValue(customText); - args.InsertValue("visible", visiable); + args.InsertValue("visible", new AMFTrueValue()); args.InsertValue("text", text); Game::logger->Log("SlashCommandHandler", "Sending \n%s\n", customText.c_str()); GameMessages::SendUIMessageServerToSingleClient(entity, entity->GetSystemAddress(), "ToggleStoryBox", &args); - - delete visiable; - delete text; }); return; @@ -556,8 +550,6 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit ChatPackets::SendSystemMessage(sysAddr, u"Switched UI state."); - delete value; - return; } @@ -570,8 +562,6 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit ChatPackets::SendSystemMessage(sysAddr, u"Toggled UI state."); - delete value; - return; } @@ -1578,11 +1568,8 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit if ((chatCommand == "debugui") && entity->GetGMLevel() >= GAME_MASTER_LEVEL_DEVELOPER) { ChatPackets::SendSystemMessage(sysAddr, u"Opening UIDebugger..."); - AMFStringValue* value = new AMFStringValue(); - value->SetStringValue("ToggleUIDebugger;"); AMFArrayValue args; - GameMessages::SendUIMessageServerToSingleClient(entity, sysAddr, value->GetStringValue(), &args); - delete value; + GameMessages::SendUIMessageServerToSingleClient(entity, sysAddr, "ToggleUIDebugger;", nullptr); } if ((chatCommand == "boost") && entity->GetGMLevel() >= GAME_MASTER_LEVEL_DEVELOPER) { @@ -2008,11 +1995,6 @@ void SlashCommandHandler::SendAnnouncement(const std::string& title, const std:: GameMessages::SendUIMessageServerToAllClients("ToggleAnnounce", &args); - delete titleValue; - delete messageValue; - titleValue = nullptr; - messageValue = nullptr; - //Notify chat about it CBITSTREAM; PacketUtils::WriteHeader(bitStream, CHAT_INTERNAL, MSG_CHAT_INTERNAL_ANNOUNCEMENT); diff --git a/dScripts/BankInteractServer.cpp b/dScripts/BankInteractServer.cpp index 9bea375a..dc119056 100644 --- a/dScripts/BankInteractServer.cpp +++ b/dScripts/BankInteractServer.cpp @@ -9,8 +9,6 @@ void BankInteractServer::OnUse(Entity* self, Entity* user) args.InsertValue("state", bank); GameMessages::SendUIMessageServerToSingleClient(user, user->GetSystemAddress(), "pushGameState", &args); - - delete bank; } void BankInteractServer::OnFireEventServerSide(Entity *self, Entity *sender, std::string args, int32_t param1, @@ -19,13 +17,10 @@ void BankInteractServer::OnFireEventServerSide(Entity *self, Entity *sender, std if (args == "ToggleBank") { AMFArrayValue args; - AMFFalseValue* amfFalse = new AMFFalseValue(); - args.InsertValue("visible", amfFalse); + args.InsertValue("visible", new AMFFalseValue()); GameMessages::SendUIMessageServerToSingleClient(sender, sender->GetSystemAddress(), "ToggleBank", &args); - delete amfFalse; - GameMessages::SendNotifyClientObject(self->GetObjectID(), u"CloseBank", 0, 0, LWOOBJID_EMPTY, "", sender->GetSystemAddress()); } } diff --git a/dScripts/MailBoxServer.cpp b/dScripts/MailBoxServer.cpp index 3e4e9687..56e7793e 100644 --- a/dScripts/MailBoxServer.cpp +++ b/dScripts/MailBoxServer.cpp @@ -8,5 +8,4 @@ void MailBoxServer::OnUse(Entity* self, Entity* user) { AMFArrayValue args; args.InsertValue("state", value); GameMessages::SendUIMessageServerToSingleClient(user, user->GetSystemAddress(), "pushGameState", &args); - delete value; } \ No newline at end of file diff --git a/dScripts/NsLegoClubDoor.cpp b/dScripts/NsLegoClubDoor.cpp index 0b773b09..0a73c6d0 100644 --- a/dScripts/NsLegoClubDoor.cpp +++ b/dScripts/NsLegoClubDoor.cpp @@ -13,21 +13,6 @@ void NsLegoClubDoor::OnStartup(Entity* self) args = {}; - /** - { {0,{ - {"image", "textures/ui/zone_thumnails/Nimbus_Station.dds"}, - {"caption", "%[UI_CHOICE_NS]"}, -- "%[LOC_STRING]" is the format for sending localization tokens to the choice box - {"identifier", "zoneID_1200"}, - {"tooltipText", "%[UI_CHOICE_NS_HOVER]"} - }}, - {1,{ - {"image", "textures/ui/zone_thumnails/Nexus_Tower.dds"}, - {"caption", "%[UI_CHOICE_NT]"}, - {"identifier", "zoneID_1900"}, - {"tooltipText", "%[UI_CHOICE_NT_HOVER]"} - } } } - */ - AMFStringValue* callbackClient = new AMFStringValue(); callbackClient->SetStringValue(std::to_string(self->GetObjectID())); args.InsertValue("callbackClient", callbackClient); @@ -97,12 +82,6 @@ void NsLegoClubDoor::OnUse(Entity* self, Entity* user) if (CheckChoice(self, player)) { - /** - { {"callbackClient", self}, - {"strIdentifier", "choiceDoor"}, - {"title", "%[UI_CHOICE_DESTINATION]"}, - {"options", choiceOptions} } - */ AMFArrayValue* multiArgs = new AMFArrayValue(); AMFStringValue* callbackClient = new AMFStringValue(); @@ -120,19 +99,9 @@ void NsLegoClubDoor::OnUse(Entity* self, Entity* user) multiArgs->InsertValue("options", options); GameMessages::SendUIMessageServerToSingleClient(player, player->GetSystemAddress(), "QueueChoiceBox", multiArgs); - - delete multiArgs; - delete callbackClient; - delete strIdentifier; - delete title; } else if (self->GetVar(u"currentZone") != m_ChoiceZoneID) { - /** - { {"state", "Lobby"}, - {"context", {{"user", msg.user}, {"callbackObj", self}, - {"HelpVisible", "show" }, {"type", "Lego_Club_Valid"}} }} - */ AMFArrayValue* multiArgs = new AMFArrayValue(); AMFStringValue* state = new AMFStringValue(); @@ -160,14 +129,6 @@ void NsLegoClubDoor::OnUse(Entity* self, Entity* user) multiArgs->InsertValue("context", context); GameMessages::SendUIMessageServerToSingleClient(player, player->GetSystemAddress(), "pushGameState", multiArgs); - - delete multiArgs; - delete state; - delete context; - delete user; - delete callbackObj; - delete helpVisible; - delete type; } else { diff --git a/dScripts/PropertyBankInteract.cpp b/dScripts/PropertyBankInteract.cpp index 974b33a6..d564c503 100644 --- a/dScripts/PropertyBankInteract.cpp +++ b/dScripts/PropertyBankInteract.cpp @@ -24,7 +24,6 @@ void PropertyBankInteract::OnUse(Entity *self, Entity *user) { args.InsertValue("state", value); GameMessages::SendUIMessageServerToSingleClient(user, user->GetSystemAddress(), "pushGameState", &args); - delete value; GameMessages::SendNotifyClientObject(self->GetObjectID(), u"OpenBank", 0, 0, LWOOBJID_EMPTY, "", user->GetSystemAddress()); @@ -34,13 +33,10 @@ void PropertyBankInteract::OnFireEventServerSide(Entity *self, Entity *sender, s int32_t param2, int32_t param3) { if (args == "ToggleBank") { AMFArrayValue amfArgs; - auto* amfFalse = new AMFFalseValue(); - amfArgs.InsertValue("visible", amfFalse); + amfArgs.InsertValue("visible", new AMFFalseValue()); GameMessages::SendUIMessageServerToSingleClient(sender, sender->GetSystemAddress(), "ToggleBank", &amfArgs); - delete amfFalse; - GameMessages::SendNotifyClientObject(self->GetObjectID(), u"CloseBank", 0, 0, LWOOBJID_EMPTY, "", sender->GetSystemAddress()); } diff --git a/dScripts/StoryBoxInteractServer.cpp b/dScripts/StoryBoxInteractServer.cpp index e5899f5d..187d05a2 100644 --- a/dScripts/StoryBoxInteractServer.cpp +++ b/dScripts/StoryBoxInteractServer.cpp @@ -18,24 +18,18 @@ void StoryBoxInteractServer::OnUse(Entity* self, Entity* user) { args.InsertValue("state", state); GameMessages::SendUIMessageServerToSingleClient(user, user->GetSystemAddress(), "pushGameState", &args); - - delete state; } user->AddCallbackTimer(0.1f, [user, customText] () { AMFArrayValue args; - auto* visiable = new AMFTrueValue(); auto* text = new AMFStringValue(); text->SetStringValue(customText); - args.InsertValue("visible", visiable); + args.InsertValue("visible", new AMFTrueValue()); args.InsertValue("text", text); GameMessages::SendUIMessageServerToSingleClient(user, user->GetSystemAddress(), "ToggleStoryBox", &args); - - delete visiable; - delete text; }); return; diff --git a/dWorldServer/WorldServer.cpp b/dWorldServer/WorldServer.cpp index d7a3b41e..96149ae4 100644 --- a/dWorldServer/WorldServer.cpp +++ b/dWorldServer/WorldServer.cpp @@ -577,11 +577,6 @@ void HandlePacketChat(Packet* packet) { GameMessages::SendUIMessageServerToAllClients("ToggleAnnounce", &args); - delete titleValue; - delete messageValue; - titleValue = nullptr; - messageValue = nullptr; - break; } diff --git a/tests/AMFDeserializeTests.cpp b/tests/AMFDeserializeTests.cpp index 88405803..58d7eea4 100644 --- a/tests/AMFDeserializeTests.cpp +++ b/tests/AMFDeserializeTests.cpp @@ -129,20 +129,25 @@ int ReadAMFArrayFromBitStream() { ASSERT_EQ(static_cast(res.get())->GetDenseArray().size(), 0); } bitStream.Reset(); - // Test a key'd value + // Test a key'd value and dense value bitStream.Write(0x09); - bitStream.Write(0x01); + bitStream.Write(0x03); bitStream.Write(0x15); for (auto e : "BehaviorID") if (e != '\0') bitStream.Write(e); bitStream.Write(0x06); bitStream.Write(0x0B); for (auto e : "10447") if (e != '\0') bitStream.Write(e); bitStream.Write(0x01); + bitStream.Write(0x06); + bitStream.Write(0x0B); + for (auto e : "10447") if (e != '\0') bitStream.Write(e); { std::unique_ptr res(ReadFromBitStream(&bitStream)); ASSERT_EQ(res->GetValueType(), AMFValueType::AMFArray); ASSERT_EQ(static_cast(res.get())->GetAssociativeMap().size(), 1); + ASSERT_EQ(static_cast(res.get())->GetDenseArray().size(), 1); ASSERT_EQ(static_cast(static_cast(res.get())->FindValue("BehaviorID"))->GetStringValue(), "10447"); + ASSERT_EQ(static_cast(static_cast(res.get())->GetDenseArray()[0])->GetStringValue(), "10447"); } // Test a dense array return 0; From ef0a3c6d0b153535659df4adeba51b266ea99228 Mon Sep 17 00:00:00 2001 From: David Markowitz <39972741+EmosewaMC@users.noreply.github.com> Date: Fri, 22 Jul 2022 19:58:20 -0700 Subject: [PATCH 16/86] Add Hot Properties struct and address some whitespace (no functionality change) (#667) * Add GameMessages * General AMF cleanup Proper memory management as well as style cleanup * General AMF cleanup Proper memory management as well as style cleanup * General optimizations Fix AMFArray so values are properly deleted when you leave the scope it was created in. Add bounds check for deletion so you don't double delete. Remove all AMFdeletions that are contained in an array since the array now manages its own memory and deletes it when it is no longer needed. * Better tests and fix de-serialize Fix de-serialize to be correct and implement a test to check this * Update AMFDeserializeTests.cpp * Update GameMessages.h * Add GM * Comment out function * Spacing * eof --- dGame/dGameMessages/GameMessageHandler.cpp | 236 ++++---- dGame/dGameMessages/GameMessages.cpp | 613 +++++++++++---------- dGame/dGameMessages/GameMessages.h | 137 +++-- dNet/dMessageIdentifiers.h | 28 +- 4 files changed, 547 insertions(+), 467 deletions(-) diff --git a/dGame/dGameMessages/GameMessageHandler.cpp b/dGame/dGameMessages/GameMessageHandler.cpp index 261a3105..53cce60e 100644 --- a/dGame/dGameMessages/GameMessageHandler.cpp +++ b/dGame/dGameMessages/GameMessageHandler.cpp @@ -30,7 +30,7 @@ using namespace std; void GameMessageHandler::HandleMessage(RakNet::BitStream* inStream, const SystemAddress& sysAddr, LWOOBJID objectID, GAME_MSG messageID) { - + CBITSTREAM // Get the entity @@ -38,19 +38,19 @@ void GameMessageHandler::HandleMessage(RakNet::BitStream* inStream, const System User * usr = UserManager::Instance()->GetUser(sysAddr); - if (!entity) - { + if (!entity) + { Game::logger->Log("GameMessageHandler", "Failed to find associated entity (%llu), aborting GM (%X)!\n", objectID, messageID); - return; - } + return; + } - switch (messageID) { + switch (messageID) { - case GAME_MSG_PLAY_EMOTE: { - GameMessages::HandlePlayEmote(inStream, entity); - break; - } + case GAME_MSG_PLAY_EMOTE: { + GameMessages::HandlePlayEmote(inStream, entity); + break; + } case GAME_MSG_MOVE_ITEM_IN_INVENTORY: { GameMessages::HandleMoveItemInInventory(inStream, entity); @@ -69,27 +69,27 @@ void GameMessageHandler::HandleMessage(RakNet::BitStream* inStream, const System case GAME_MSG_UN_EQUIP_ITEM: GameMessages::HandleUnequipItem(inStream, entity); break; - - case GAME_MSG_RESPOND_TO_MISSION: { - GameMessages::HandleRespondToMission(inStream, entity); - break; - } - - case GAME_MSG_REQUEST_USE: { - GameMessages::HandleRequestUse(inStream, entity, sysAddr); - break; - } - - case GAME_MSG_SET_FLAG: { - GameMessages::HandleSetFlag(inStream, entity); - break; - } - - case GAME_MSG_HAS_BEEN_COLLECTED: { - GameMessages::HandleHasBeenCollected(inStream, entity); - break; - } - + + case GAME_MSG_RESPOND_TO_MISSION: { + GameMessages::HandleRespondToMission(inStream, entity); + break; + } + + case GAME_MSG_REQUEST_USE: { + GameMessages::HandleRequestUse(inStream, entity, sysAddr); + break; + } + + case GAME_MSG_SET_FLAG: { + GameMessages::HandleSetFlag(inStream, entity); + break; + } + + case GAME_MSG_HAS_BEEN_COLLECTED: { + GameMessages::HandleHasBeenCollected(inStream, entity); + break; + } + case GAME_MSG_PLAYER_LOADED: { GameMessages::SendRestoreToPostLoadStats(entity, sysAddr); entity->SetPlayerReadyForUpdates(); @@ -160,57 +160,57 @@ void GameMessageHandler::HandleMessage(RakNet::BitStream* inStream, const System Game::logger->Log("GameMessageHandler", "Player %s (%llu) loaded.\n", entity->GetCharacter()->GetName().c_str(), entity->GetObjectID()); // After we've done our thing, tell the client they're ready - GameMessages::SendPlayerReady(dZoneManager::Instance()->GetZoneControlObject(), sysAddr); - GameMessages::SendPlayerReady(entity, sysAddr); + GameMessages::SendPlayerReady(dZoneManager::Instance()->GetZoneControlObject(), sysAddr); + GameMessages::SendPlayerReady(entity, sysAddr); - break; - } - - case GAME_MSG_REQUEST_LINKED_MISSION: { - GameMessages::HandleRequestLinkedMission(inStream, entity); - break; - } - - case GAME_MSG_MISSION_DIALOGUE_OK: { - GameMessages::HandleMissionDialogOK(inStream, entity); - break; - } + break; + } + + case GAME_MSG_REQUEST_LINKED_MISSION: { + GameMessages::HandleRequestLinkedMission(inStream, entity); + break; + } + + case GAME_MSG_MISSION_DIALOGUE_OK: { + GameMessages::HandleMissionDialogOK(inStream, entity); + break; + } case GAME_MSG_MISSION_DIALOGUE_CANCELLED: { //This message is pointless for our implementation, as the client just carries on after //rejecting a mission offer. We dont need to do anything. This is just here to remove a warning in our logs :) break; } - - case GAME_MSG_REQUEST_PLATFORM_RESYNC: { - GameMessages::HandleRequestPlatformResync(inStream, entity, sysAddr); - break; - } - - case GAME_MSG_FIRE_EVENT_SERVER_SIDE: { + + case GAME_MSG_REQUEST_PLATFORM_RESYNC: { + GameMessages::HandleRequestPlatformResync(inStream, entity, sysAddr); + break; + } + + case GAME_MSG_FIRE_EVENT_SERVER_SIDE: { GameMessages::HandleFireEventServerSide(inStream, entity, sysAddr); - break; - } + break; + } - case GAME_MSG_SEND_ACTIVITY_SUMMARY_LEADERBOARD_DATA: { - GameMessages::HandleActivitySummaryLeaderboardData(inStream, entity, sysAddr); - break; - } + case GAME_MSG_SEND_ACTIVITY_SUMMARY_LEADERBOARD_DATA: { + GameMessages::HandleActivitySummaryLeaderboardData(inStream, entity, sysAddr); + break; + } - case GAME_MSG_REQUEST_ACTIVITY_SUMMARY_LEADERBOARD_DATA: { - GameMessages::HandleRequestActivitySummaryLeaderboardData(inStream, entity, sysAddr); - break; - } + case GAME_MSG_REQUEST_ACTIVITY_SUMMARY_LEADERBOARD_DATA: { + GameMessages::HandleRequestActivitySummaryLeaderboardData(inStream, entity, sysAddr); + break; + } - case GAME_MSG_ACTIVITY_STATE_CHANGE_REQUEST: { - GameMessages::HandleActivityStateChangeRequest(inStream, entity); - break; - } - - case GAME_MSG_PARSE_CHAT_MESSAGE: { - GameMessages::HandleParseChatMessage(inStream, entity, sysAddr); - break; - } + case GAME_MSG_ACTIVITY_STATE_CHANGE_REQUEST: { + GameMessages::HandleActivityStateChangeRequest(inStream, entity); + break; + } + + case GAME_MSG_PARSE_CHAT_MESSAGE: { + GameMessages::HandleParseChatMessage(inStream, entity, sysAddr); + break; + } case GAME_MSG_NOTIFY_SERVER_LEVEL_PROCESSING_COMPLETE: { GameMessages::HandleNotifyServerLevelProcessingComplete(inStream, entity); @@ -228,8 +228,8 @@ void GameMessageHandler::HandleMessage(RakNet::BitStream* inStream, const System } case GAME_MSG_RESURRECT: { - GameMessages::HandleResurrect(inStream, entity); - break; + GameMessages::HandleResurrect(inStream, entity); + break; } case GAME_MSG_REQUEST_RESURRECT: { @@ -243,10 +243,14 @@ void GameMessageHandler::HandleMessage(RakNet::BitStream* inStream, const System }*/ break; } + case GAME_MSG_HANDLE_HOT_PROPERTY_DATA: { + GameMessages::HandleGetHotPropertyData(inStream, entity, sysAddr); + break; + } - case GAME_MSG_REQUEST_SERVER_PROJECTILE_IMPACT: - { - auto message = GameMessages::RequestServerProjectileImpact(); + case GAME_MSG_REQUEST_SERVER_PROJECTILE_IMPACT: + { + auto message = GameMessages::RequestServerProjectileImpact(); message.Deserialize(inStream); @@ -260,10 +264,10 @@ void GameMessageHandler::HandleMessage(RakNet::BitStream* inStream, const System delete bs; } - - break; - } - + + break; + } + case GAME_MSG_START_SKILL: { GameMessages::StartSkill startSkill = GameMessages::StartSkill(); startSkill.Deserialize(inStream); // inStream replaces &bitStream @@ -279,7 +283,7 @@ void GameMessageHandler::HandleMessage(RakNet::BitStream* inStream, const System unsigned int behaviorId = skillTable->GetSkillByID(startSkill.skillID).behaviorID; bool success = false; - + if (behaviorId > 0) { RakNet::BitStream * bs = new RakNet::BitStream((unsigned char *)startSkill.sBitStream.c_str(), startSkill.sBitStream.size(), false); @@ -374,7 +378,7 @@ void GameMessageHandler::HandleMessage(RakNet::BitStream* inStream, const System case GAME_MSG_MODULAR_BUILD_FINISH: GameMessages::HandleModularBuildFinish(inStream, entity, sysAddr); break; - + case GAME_MSG_PUSH_EQUIPPED_ITEMS_STATE: GameMessages::HandlePushEquippedItemsState(inStream, entity); break; @@ -486,7 +490,7 @@ void GameMessageHandler::HandleMessage(RakNet::BitStream* inStream, const System GameMessages::HandleChoiceBoxRespond(inStream, entity, sysAddr); break; - // Property + // Property case GAME_MSG_QUERY_PROPERTY_DATA: GameMessages::HandleQueryPropertyData(inStream, entity, sysAddr); break; @@ -531,7 +535,7 @@ void GameMessageHandler::HandleMessage(RakNet::BitStream* inStream, const System GameMessages::HandleBBBLoadItemRequest(inStream, entity, sysAddr); break; - case GAME_MSG_BBB_SAVE_REQUEST: + case GAME_MSG_BBB_SAVE_REQUEST: GameMessages::HandleBBBSaveRequest(inStream, entity, sysAddr); break; @@ -554,7 +558,7 @@ void GameMessageHandler::HandleMessage(RakNet::BitStream* inStream, const System case GAME_MSG_UPDATE_PROPERTY_OR_MODEL_FOR_FILTER_CHECK: GameMessages::HandleUpdatePropertyOrModelForFilterCheck(inStream, entity, sysAddr); break; - + case GAME_MSG_SET_PROPERTY_ACCESS: GameMessages::HandleSetPropertyAccess(inStream, entity, sysAddr); break; @@ -620,41 +624,41 @@ void GameMessageHandler::HandleMessage(RakNet::BitStream* inStream, const System GameMessages::HandleSetGhostReferencePosition(inStream, entity, sysAddr); break; - case GAME_MSG_READY_FOR_UPDATES: - //We don't really care about this message, as it's simply here to inform us that the client is done loading an object. - //In the event we _do_ send an update to an object that hasn't finished loading, the client will handle it anyway. - break; + case GAME_MSG_READY_FOR_UPDATES: + //We don't really care about this message, as it's simply here to inform us that the client is done loading an object. + //In the event we _do_ send an update to an object that hasn't finished loading, the client will handle it anyway. + break; case GAME_MSG_REPORT_BUG: GameMessages::HandleReportBug(inStream, entity); break; - case GAME_MSG_CLIENT_RAIL_MOVEMENT_READY: - GameMessages::HandleClientRailMovementReady(inStream, entity, sysAddr); - break; - - case GAME_MSG_CANCEL_RAIL_MOVEMENT: - GameMessages::HandleCancelRailMovement(inStream, entity, sysAddr); - break; - - case GAME_MSG_PLAYER_RAIL_ARRIVED_NOTIFICATION: - GameMessages::HandlePlayerRailArrivedNotification(inStream, entity, sysAddr); - break; - - case GAME_MSG_CINEMATIC_UPDATE: - GameMessages::HandleCinematicUpdate(inStream, entity, sysAddr); - break; - - case GAME_MSG_MODIFY_PLAYER_ZONE_STATISTIC: - GameMessages::HandleModifyPlayerZoneStatistic(inStream, entity); - break; - - case GAME_MSG_UPDATE_PLAYER_STATISTIC: - GameMessages::HandleUpdatePlayerStatistic(inStream, entity); - break; - - default: - //Game::logger->Log("GameMessageHandler", "Unknown game message ID: %X\n", messageID); + case GAME_MSG_CLIENT_RAIL_MOVEMENT_READY: + GameMessages::HandleClientRailMovementReady(inStream, entity, sysAddr); break; - } + + case GAME_MSG_CANCEL_RAIL_MOVEMENT: + GameMessages::HandleCancelRailMovement(inStream, entity, sysAddr); + break; + + case GAME_MSG_PLAYER_RAIL_ARRIVED_NOTIFICATION: + GameMessages::HandlePlayerRailArrivedNotification(inStream, entity, sysAddr); + break; + + case GAME_MSG_CINEMATIC_UPDATE: + GameMessages::HandleCinematicUpdate(inStream, entity, sysAddr); + break; + + case GAME_MSG_MODIFY_PLAYER_ZONE_STATISTIC: + GameMessages::HandleModifyPlayerZoneStatistic(inStream, entity); + break; + + case GAME_MSG_UPDATE_PLAYER_STATISTIC: + GameMessages::HandleUpdatePlayerStatistic(inStream, entity); + break; + + default: + //Game::logger->Log("GameMessageHandler", "Unknown game message ID: %X\n", messageID); + break; + } } diff --git a/dGame/dGameMessages/GameMessages.cpp b/dGame/dGameMessages/GameMessages.cpp index a971b723..2f193170 100644 --- a/dGame/dGameMessages/GameMessages.cpp +++ b/dGame/dGameMessages/GameMessages.cpp @@ -170,14 +170,14 @@ void GameMessages::SendPlayerReady(Entity* entity, const SystemAddress& sysAddr) } void GameMessages::SendPlayerAllowedRespawn(LWOOBJID entityID, bool doNotPromptRespawn, const SystemAddress &sysAddr) { - CBITSTREAM - CMSGHEADER; + CBITSTREAM + CMSGHEADER; - bitStream.Write(entityID); - bitStream.Write(GAME_MSG::GAME_MSG_SET_PLAYER_ALLOWED_RESPAWN); - bitStream.Write(doNotPromptRespawn); + bitStream.Write(entityID); + bitStream.Write(GAME_MSG::GAME_MSG_SET_PLAYER_ALLOWED_RESPAWN); + bitStream.Write(doNotPromptRespawn); - SEND_PACKET; + SEND_PACKET; } void GameMessages::SendInvalidZoneTransferList(Entity* entity, const SystemAddress& sysAddr, const std::u16string& feedbackURL, const std::u16string& invalidMapTransferList, bool feedbackOnExit, bool feedbackOnInvalidTransfer) { @@ -266,7 +266,7 @@ void GameMessages::SendStartArrangingWithItem( } void GameMessages::SendPlayerSetCameraCyclingMode(const LWOOBJID& objectID, const SystemAddress& sysAddr, - bool bAllowCyclingWhileDeadOnly, eCyclingMode cyclingMode) { + bool bAllowCyclingWhileDeadOnly, eCyclingMode cyclingMode) { CBITSTREAM CMSGHEADER @@ -277,7 +277,7 @@ void GameMessages::SendPlayerSetCameraCyclingMode(const LWOOBJID& objectID, cons bitStream.Write(cyclingMode != ALLOW_CYCLE_TEAMMATES); if (cyclingMode != ALLOW_CYCLE_TEAMMATES) { - bitStream.Write(cyclingMode); + bitStream.Write(cyclingMode); } SEND_PACKET @@ -672,7 +672,7 @@ void GameMessages::SendStopFXEffect(Entity* entity, bool killImmediate, std::str bitStream.Write(entity->GetObjectID()); bitStream.Write(GAME_MSG::GAME_MSG_STOP_FX_EFFECT); - bitStream.Write(killImmediate); + bitStream.Write(killImmediate); bitStream.Write(name.size()); bitStream.Write(name.c_str(), name.size()); @@ -1456,76 +1456,76 @@ void GameMessages::SendMatchUpdate(Entity* entity, const SystemAddress& sysAddr, } void GameMessages::SendRequestActivitySummaryLeaderboardData(const LWOOBJID& objectID, const LWOOBJID& targetID, - const SystemAddress& sysAddr, const int32_t& gameID, - const int32_t& queryType, const int32_t& resultsEnd, - const int32_t& resultsStart, bool weekly) { - CBITSTREAM - CMSGHEADER + const SystemAddress& sysAddr, const int32_t& gameID, + const int32_t& queryType, const int32_t& resultsEnd, + const int32_t& resultsStart, bool weekly) { + CBITSTREAM + CMSGHEADER - bitStream.Write(objectID); - bitStream.Write(GAME_MSG::GAME_MSG_REQUEST_ACTIVITY_SUMMARY_LEADERBOARD_DATA); + bitStream.Write(objectID); + bitStream.Write(GAME_MSG::GAME_MSG_REQUEST_ACTIVITY_SUMMARY_LEADERBOARD_DATA); - bitStream.Write(gameID != 0); - if (gameID != 0) { - bitStream.Write(gameID); - } + bitStream.Write(gameID != 0); + if (gameID != 0) { + bitStream.Write(gameID); + } - bitStream.Write(queryType != 1); - if (queryType != 1) { - bitStream.Write(queryType); - } + bitStream.Write(queryType != 1); + if (queryType != 1) { + bitStream.Write(queryType); + } - bitStream.Write(resultsEnd != 10); - if (resultsEnd != 10) { - bitStream.Write(resultsEnd); - } + bitStream.Write(resultsEnd != 10); + if (resultsEnd != 10) { + bitStream.Write(resultsEnd); + } - bitStream.Write(resultsStart != 0); - if (resultsStart != 0) { - bitStream.Write(resultsStart); - } + bitStream.Write(resultsStart != 0); + if (resultsStart != 0) { + bitStream.Write(resultsStart); + } - bitStream.Write(targetID); - bitStream.Write(weekly); + bitStream.Write(targetID); + bitStream.Write(weekly); - SEND_PACKET + SEND_PACKET } void GameMessages::SendActivityPause(LWOOBJID objectId, bool pause, const SystemAddress& sysAddr) { - CBITSTREAM - CMSGHEADER + CBITSTREAM + CMSGHEADER - bitStream.Write(objectId); - bitStream.Write(GAME_MSG::GAME_MSG_ACTIVITY_PAUSE); - bitStream.Write(pause); + bitStream.Write(objectId); + bitStream.Write(GAME_MSG::GAME_MSG_ACTIVITY_PAUSE); + bitStream.Write(pause); - if (sysAddr == UNASSIGNED_SYSTEM_ADDRESS) SEND_PACKET_BROADCAST; - SEND_PACKET + if (sysAddr == UNASSIGNED_SYSTEM_ADDRESS) SEND_PACKET_BROADCAST; + SEND_PACKET } void GameMessages::SendStartActivityTime(LWOOBJID objectId, float_t startTime, const SystemAddress& sysAddr) { - CBITSTREAM - CMSGHEADER + CBITSTREAM + CMSGHEADER - bitStream.Write(objectId); - bitStream.Write(GAME_MSG::GAME_MSG_START_ACTIVITY_TIME); - bitStream.Write(startTime); + bitStream.Write(objectId); + bitStream.Write(GAME_MSG::GAME_MSG_START_ACTIVITY_TIME); + bitStream.Write(startTime); - if (sysAddr == UNASSIGNED_SYSTEM_ADDRESS) SEND_PACKET_BROADCAST; - SEND_PACKET + if (sysAddr == UNASSIGNED_SYSTEM_ADDRESS) SEND_PACKET_BROADCAST; + SEND_PACKET } void GameMessages::SendRequestActivityEnter(LWOOBJID objectId, const SystemAddress& sysAddr, bool bStart, LWOOBJID userID) { - CBITSTREAM - CMSGHEADER + CBITSTREAM + CMSGHEADER - bitStream.Write(objectId); - bitStream.Write(GAME_MSG::GAME_MSG_REQUEST_ACTIVITY_ENTER); - bitStream.Write(bStart); + bitStream.Write(objectId); + bitStream.Write(GAME_MSG::GAME_MSG_REQUEST_ACTIVITY_ENTER); + bitStream.Write(bStart); bitStream.Write(userID); - if (sysAddr == UNASSIGNED_SYSTEM_ADDRESS) SEND_PACKET_BROADCAST; - SEND_PACKET + if (sysAddr == UNASSIGNED_SYSTEM_ADDRESS) SEND_PACKET_BROADCAST; + SEND_PACKET } void GameMessages::NotifyLevelRewards(LWOOBJID objectID, const SystemAddress& sysAddr, int level, bool sending_rewards) { @@ -1614,87 +1614,87 @@ void GameMessages::HandleUpdateShootingGalleryRotation(RakNet::BitStream* inStre void GameMessages::HandleActivitySummaryLeaderboardData(RakNet::BitStream* instream, Entity* entity, - const SystemAddress& sysAddr) { - Game::logger->Log("AGS", "We got mail!\n"); + const SystemAddress& sysAddr) { + Game::logger->Log("AGS", "We got mail!\n"); } void GameMessages::SendActivitySummaryLeaderboardData(const LWOOBJID& objectID, const Leaderboard* leaderboard, const SystemAddress& sysAddr) { - CBITSTREAM - CMSGHEADER + CBITSTREAM + CMSGHEADER - bitStream.Write(objectID); - bitStream.Write(GAME_MSG::GAME_MSG_SEND_ACTIVITY_SUMMARY_LEADERBOARD_DATA); + bitStream.Write(objectID); + bitStream.Write(GAME_MSG::GAME_MSG_SEND_ACTIVITY_SUMMARY_LEADERBOARD_DATA); - bitStream.Write(leaderboard->GetGameID()); - bitStream.Write(leaderboard->GetInfoType()); + bitStream.Write(leaderboard->GetGameID()); + bitStream.Write(leaderboard->GetInfoType()); - // Leaderboard is written back as LDF string - const auto leaderboardString = leaderboard->ToString(); - bitStream.Write(leaderboardString.size()); - for (const auto c : leaderboardString) { - bitStream.Write(c); - } - if (!leaderboardString.empty()) bitStream.Write(uint16_t(0)); + // Leaderboard is written back as LDF string + const auto leaderboardString = leaderboard->ToString(); + bitStream.Write(leaderboardString.size()); + for (const auto c : leaderboardString) { + bitStream.Write(c); + } + if (!leaderboardString.empty()) bitStream.Write(uint16_t(0)); - bitStream.Write0(); - bitStream.Write0(); + bitStream.Write0(); + bitStream.Write0(); - SEND_PACKET + SEND_PACKET } void GameMessages::HandleRequestActivitySummaryLeaderboardData(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr) { - int32_t gameID = 0; - if (inStream->ReadBit()) inStream->Read(gameID); + int32_t gameID = 0; + if (inStream->ReadBit()) inStream->Read(gameID); - int32_t queryType = 1; - if (inStream->ReadBit()) inStream->Read(queryType); + int32_t queryType = 1; + if (inStream->ReadBit()) inStream->Read(queryType); - int32_t resultsEnd = 10; - if (inStream->ReadBit()) inStream->Read(resultsEnd); + int32_t resultsEnd = 10; + if (inStream->ReadBit()) inStream->Read(resultsEnd); - int32_t resultsStart = 0; - if (inStream->ReadBit()) inStream->Read(resultsStart); + int32_t resultsStart = 0; + if (inStream->ReadBit()) inStream->Read(resultsStart); - LWOOBJID target {}; - inStream->Read(target); + LWOOBJID target {}; + inStream->Read(target); - bool weekly = inStream->ReadBit(); + bool weekly = inStream->ReadBit(); - const auto* leaderboard = LeaderboardManager::GetLeaderboard(gameID, (InfoType)queryType, weekly, entity->GetObjectID()); - SendActivitySummaryLeaderboardData(entity->GetObjectID(), leaderboard, sysAddr); - delete leaderboard; + const auto* leaderboard = LeaderboardManager::GetLeaderboard(gameID, (InfoType)queryType, weekly, entity->GetObjectID()); + SendActivitySummaryLeaderboardData(entity->GetObjectID(), leaderboard, sysAddr); + delete leaderboard; } void GameMessages::HandleActivityStateChangeRequest(RakNet::BitStream *inStream, Entity *entity) { - LWOOBJID objectID; - inStream->Read(objectID); + LWOOBJID objectID; + inStream->Read(objectID); - int32_t value1; - inStream->Read(value1); + int32_t value1; + inStream->Read(value1); - int32_t value2; - inStream->Read(value2); + int32_t value2; + inStream->Read(value2); - uint32_t stringValueLength; - inStream->Read(stringValueLength); + uint32_t stringValueLength; + inStream->Read(stringValueLength); - std::u16string stringValue; - for (uint32_t i = 0; i < stringValueLength; ++i) { - uint16_t character; - inStream->Read(character); - stringValue.push_back(character); - } + std::u16string stringValue; + for (uint32_t i = 0; i < stringValueLength; ++i) { + uint16_t character; + inStream->Read(character); + stringValue.push_back(character); + } auto* assosiate = EntityManager::Instance()->GetEntity(objectID); - Game::logger->Log("Activity State Change", "%s [%i, %i] from %i to %i\n", GeneralUtils::UTF16ToWTF8(stringValue).c_str(), value1, value2, entity->GetLOT(), assosiate != nullptr ? assosiate->GetLOT() : 0); + Game::logger->Log("Activity State Change", "%s [%i, %i] from %i to %i\n", GeneralUtils::UTF16ToWTF8(stringValue).c_str(), value1, value2, entity->GetLOT(), assosiate != nullptr ? assosiate->GetLOT() : 0); std::vector scriptedActs = EntityManager::Instance()->GetEntitiesByComponent(COMPONENT_TYPE_SHOOTING_GALLERY); for (Entity* scriptEntity : scriptedActs) { scriptEntity->OnActivityStateChangeRequest(objectID, value1, value2, stringValue); } - entity->OnActivityStateChangeRequest(objectID, value1, value2, stringValue); + entity->OnActivityStateChangeRequest(objectID, value1, value2, stringValue); } void GameMessages::SendStartCelebrationEffect(Entity* entity, const SystemAddress& sysAddr, int celebrationID) { @@ -1727,99 +1727,99 @@ void GameMessages::SendStartCelebrationEffect(Entity* entity, const SystemAddres void GameMessages::SendSetRailMovement(const LWOOBJID& objectID, bool pathGoForward, std::u16string pathName, - uint32_t pathStart, const SystemAddress& sysAddr, int32_t railActivatorComponentID, - LWOOBJID railActivatorObjectID) { - CBITSTREAM; - CMSGHEADER; + uint32_t pathStart, const SystemAddress& sysAddr, int32_t railActivatorComponentID, + LWOOBJID railActivatorObjectID) { + CBITSTREAM; + CMSGHEADER; - bitStream.Write(objectID); - bitStream.Write(GAME_MSG::GAME_MSG_SET_RAIL_MOVEMENT); + bitStream.Write(objectID); + bitStream.Write(GAME_MSG::GAME_MSG_SET_RAIL_MOVEMENT); - bitStream.Write(pathGoForward); + bitStream.Write(pathGoForward); - bitStream.Write(uint32_t(pathName.size())); - for (auto character : pathName) { - bitStream.Write(character); - } + bitStream.Write(uint32_t(pathName.size())); + for (auto character : pathName) { + bitStream.Write(character); + } - bitStream.Write(pathStart); + bitStream.Write(pathStart); - const auto componentIDIsDefault = railActivatorComponentID == -1; - bitStream.Write(!componentIDIsDefault); - if (!componentIDIsDefault) - bitStream.Write(railActivatorComponentID); + const auto componentIDIsDefault = railActivatorComponentID == -1; + bitStream.Write(!componentIDIsDefault); + if (!componentIDIsDefault) + bitStream.Write(railActivatorComponentID); - const auto activatorObjectIDIsDefault = railActivatorObjectID == LWOOBJID_EMPTY; - bitStream.Write(!activatorObjectIDIsDefault); - if (!activatorObjectIDIsDefault) - bitStream.Write(railActivatorObjectID); + const auto activatorObjectIDIsDefault = railActivatorObjectID == LWOOBJID_EMPTY; + bitStream.Write(!activatorObjectIDIsDefault); + if (!activatorObjectIDIsDefault) + bitStream.Write(railActivatorObjectID); - if (sysAddr == UNASSIGNED_SYSTEM_ADDRESS) SEND_PACKET_BROADCAST; - SEND_PACKET; + if (sysAddr == UNASSIGNED_SYSTEM_ADDRESS) SEND_PACKET_BROADCAST; + SEND_PACKET; } void GameMessages::SendStartRailMovement(const LWOOBJID &objectID, std::u16string pathName, std::u16string startSound, - std::u16string loopSound, std::u16string stopSound, const SystemAddress& sysAddr, - uint32_t pathStart, bool goForward, bool damageImmune, bool noAggro, bool notifyActor, - bool showNameBillboard, bool cameraLocked, bool collisionEnabled, bool useDB, - int32_t railComponentID, LWOOBJID railActivatorObjectID) { - CBITSTREAM; - CMSGHEADER; + std::u16string loopSound, std::u16string stopSound, const SystemAddress& sysAddr, + uint32_t pathStart, bool goForward, bool damageImmune, bool noAggro, bool notifyActor, + bool showNameBillboard, bool cameraLocked, bool collisionEnabled, bool useDB, + int32_t railComponentID, LWOOBJID railActivatorObjectID) { + CBITSTREAM; + CMSGHEADER; - bitStream.Write(objectID); - bitStream.Write(GAME_MSG::GAME_MSG_START_RAIL_MOVEMENT); + bitStream.Write(objectID); + bitStream.Write(GAME_MSG::GAME_MSG_START_RAIL_MOVEMENT); - bitStream.Write(damageImmune); - bitStream.Write(noAggro); - bitStream.Write(notifyActor); - bitStream.Write(showNameBillboard); - bitStream.Write(cameraLocked); - bitStream.Write(collisionEnabled); + bitStream.Write(damageImmune); + bitStream.Write(noAggro); + bitStream.Write(notifyActor); + bitStream.Write(showNameBillboard); + bitStream.Write(cameraLocked); + bitStream.Write(collisionEnabled); - bitStream.Write(uint32_t(loopSound.size())); - for (auto character : loopSound) { - bitStream.Write(character); - } + bitStream.Write(uint32_t(loopSound.size())); + for (auto character : loopSound) { + bitStream.Write(character); + } - bitStream.Write(goForward); + bitStream.Write(goForward); - bitStream.Write(uint32_t(pathName.size())); - for (auto character : pathName) { - bitStream.Write(character); - } + bitStream.Write(uint32_t(pathName.size())); + for (auto character : pathName) { + bitStream.Write(character); + } - const auto pathStartIsDefault = pathStart == 0; - bitStream.Write(!pathStartIsDefault); - if (!pathStartIsDefault) { - bitStream.Write(pathStart); - } + const auto pathStartIsDefault = pathStart == 0; + bitStream.Write(!pathStartIsDefault); + if (!pathStartIsDefault) { + bitStream.Write(pathStart); + } - const auto railComponentIDIsDefault = railComponentID == -1; - bitStream.Write(!railComponentIDIsDefault); - if (!railComponentIDIsDefault) { - bitStream.Write(railComponentID); - } + const auto railComponentIDIsDefault = railComponentID == -1; + bitStream.Write(!railComponentIDIsDefault); + if (!railComponentIDIsDefault) { + bitStream.Write(railComponentID); + } - const auto railObjectIDIsDefault = railActivatorObjectID == LWOOBJID_EMPTY; - bitStream.Write(!railObjectIDIsDefault); - if (!railObjectIDIsDefault) { - bitStream.Write(railActivatorObjectID); - } + const auto railObjectIDIsDefault = railActivatorObjectID == LWOOBJID_EMPTY; + bitStream.Write(!railObjectIDIsDefault); + if (!railObjectIDIsDefault) { + bitStream.Write(railActivatorObjectID); + } - bitStream.Write(uint32_t(startSound.size())); - for (auto character : startSound) { - bitStream.Write(character); - } + bitStream.Write(uint32_t(startSound.size())); + for (auto character : startSound) { + bitStream.Write(character); + } - bitStream.Write(uint32_t(stopSound.size())); - for (auto character : stopSound) { - bitStream.Write(character); - } + bitStream.Write(uint32_t(stopSound.size())); + for (auto character : stopSound) { + bitStream.Write(character); + } - bitStream.Write(useDB); + bitStream.Write(useDB); - if (sysAddr == UNASSIGNED_SYSTEM_ADDRESS) SEND_PACKET_BROADCAST; - SEND_PACKET; + if (sysAddr == UNASSIGNED_SYSTEM_ADDRESS) SEND_PACKET_BROADCAST; + SEND_PACKET; } void GameMessages::SendNotifyClientObject(const LWOOBJID& objectID, std::u16string name, int param1, int param2, const LWOOBJID& paramObj, std::string paramStr, const SystemAddress& sysAddr) { @@ -2865,48 +2865,48 @@ void GameMessages::SendEndCinematic(LWOOBJID objectId, std::u16string pathName, } void GameMessages::HandleCinematicUpdate(RakNet::BitStream *inStream, Entity *entity, const SystemAddress &sysAddr) { - eCinematicEvent event; - if (!inStream->ReadBit()) { - event = STARTED; - } else { - inStream->Read(event); - } + eCinematicEvent event; + if (!inStream->ReadBit()) { + event = STARTED; + } else { + inStream->Read(event); + } - float_t overallTime; - if (!inStream->ReadBit()) { - overallTime = -1.0f; - } else { - inStream->Read(overallTime); - } + float_t overallTime; + if (!inStream->ReadBit()) { + overallTime = -1.0f; + } else { + inStream->Read(overallTime); + } - uint32_t pathNameLength; - inStream->Read(pathNameLength); + uint32_t pathNameLength; + inStream->Read(pathNameLength); - std::u16string pathName; - for (size_t i = 0; i < pathNameLength; i++) { - char16_t character; - inStream->Read(character); - pathName.push_back(character); - } + std::u16string pathName; + for (size_t i = 0; i < pathNameLength; i++) { + char16_t character; + inStream->Read(character); + pathName.push_back(character); + } - float_t pathTime; - if (!inStream->ReadBit()) { - pathTime = -1.0f; - } else { - inStream->Read(pathTime); - } + float_t pathTime; + if (!inStream->ReadBit()) { + pathTime = -1.0f; + } else { + inStream->Read(pathTime); + } - int32_t waypoint; - if (!inStream->ReadBit()) { - waypoint = -1; - } else { - inStream->Read(waypoint); - } + int32_t waypoint; + if (!inStream->ReadBit()) { + waypoint = -1; + } else { + inStream->Read(waypoint); + } - std::vector scriptedActs = EntityManager::Instance()->GetEntitiesByComponent(COMPONENT_TYPE_SCRIPT); - for (Entity* scriptEntity : scriptedActs) { - scriptEntity->OnCinematicUpdate(scriptEntity, entity, event, pathName, pathTime, overallTime, waypoint); - } + std::vector scriptedActs = EntityManager::Instance()->GetEntitiesByComponent(COMPONENT_TYPE_SCRIPT); + for (Entity* scriptEntity : scriptedActs) { + scriptEntity->OnCinematicUpdate(scriptEntity, entity, event, pathName, pathTime, overallTime, waypoint); + } } void GameMessages::SendSetStunned(LWOOBJID objectId, eStunState stateChangeType, const SystemAddress& sysAddr, @@ -4290,10 +4290,10 @@ void GameMessages::HandleVehicleNotifyHitImaginationServer(RakNet::BitStream* in } } - auto* characterComponent = entity->GetComponent(); - if (characterComponent != nullptr) { - characterComponent->UpdatePlayerStatistic(RacingImaginationPowerUpsCollected); - } + auto* characterComponent = entity->GetComponent(); + if (characterComponent != nullptr) { + characterComponent->UpdatePlayerStatistic(RacingImaginationPowerUpsCollected); + } pickup->OnFireEventServerSide(entity, "powerup"); @@ -4541,9 +4541,9 @@ void GameMessages::SendVehicleNotifyFinishedRace(LWOOBJID objectId, const System } void GameMessages::SendAddBuff(LWOOBJID& objectID, const LWOOBJID& casterID, uint32_t buffID, uint32_t msDuration, - bool addImmunity, bool cancelOnDamaged, bool cancelOnDeath, bool cancelOnLogout, - bool cancelOnRemoveBuff, bool cancelOnUi, bool cancelOnUnequip, bool cancelOnZone, - const SystemAddress& sysAddr) { + bool addImmunity, bool cancelOnDamaged, bool cancelOnDeath, bool cancelOnLogout, + bool cancelOnRemoveBuff, bool cancelOnUi, bool cancelOnUnequip, bool cancelOnZone, + const SystemAddress& sysAddr) { CBITSTREAM; CMSGHEADER; @@ -4735,11 +4735,11 @@ void GameMessages::HandleBuyFromVendor(RakNet::BitStream* inStream, Entity* enti Character* character = player->GetCharacter(); if (!character) return; - // Extra currency that needs to be deducted in case of crafting - auto craftingCurrencies = CDItemComponentTable::ParseCraftingCurrencies(itemComp); - for (const auto& craftingCurrency : craftingCurrencies) { - inv->RemoveItem(craftingCurrency.first, craftingCurrency.second * count); - } + // Extra currency that needs to be deducted in case of crafting + auto craftingCurrencies = CDItemComponentTable::ParseCraftingCurrencies(itemComp); + for (const auto& craftingCurrency : craftingCurrencies) { + inv->RemoveItem(craftingCurrency.first, craftingCurrency.second * count); + } if (isCommendationVendor) { @@ -5035,7 +5035,7 @@ void GameMessages::HandleFireEventServerSide(RakNet::BitStream* inStream, Entity }); } - entity->OnFireEventServerSide(sender, GeneralUtils::UTF16ToWTF8(args), param1, param2, param3); + entity->OnFireEventServerSide(sender, GeneralUtils::UTF16ToWTF8(args), param1, param2, param3); } void GameMessages::HandleRequestPlatformResync(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr) { @@ -5867,21 +5867,21 @@ void GameMessages::HandlePickupItem(RakNet::BitStream* inStream, Entity* entity) } void GameMessages::HandleResurrect(RakNet::BitStream* inStream, Entity* entity) { - bool immediate = inStream->ReadBit(); + bool immediate = inStream->ReadBit(); - Entity* zoneControl = EntityManager::Instance()->GetZoneControlEntity(); - for (CppScripts::Script* script : CppScripts::GetEntityScripts(zoneControl)) { - script->OnPlayerResurrected(zoneControl, entity); - } + Entity* zoneControl = EntityManager::Instance()->GetZoneControlEntity(); + for (CppScripts::Script* script : CppScripts::GetEntityScripts(zoneControl)) { + script->OnPlayerResurrected(zoneControl, entity); + } - std::vector scriptedActs = EntityManager::Instance()->GetEntitiesByComponent(COMPONENT_TYPE_SCRIPTED_ACTIVITY); - for (Entity* scriptEntity : scriptedActs) { - if (scriptEntity->GetObjectID() != zoneControl->GetObjectID()) { // Don't want to trigger twice on instance worlds - for (CppScripts::Script* script : CppScripts::GetEntityScripts(scriptEntity)) { - script->OnPlayerResurrected(scriptEntity, entity); - } - } - } + std::vector scriptedActs = EntityManager::Instance()->GetEntitiesByComponent(COMPONENT_TYPE_SCRIPTED_ACTIVITY); + for (Entity* scriptEntity : scriptedActs) { + if (scriptEntity->GetObjectID() != zoneControl->GetObjectID()) { // Don't want to trigger twice on instance worlds + for (CppScripts::Script* script : CppScripts::GetEntityScripts(scriptEntity)) { + script->OnPlayerResurrected(scriptEntity, entity); + } + } + } } void GameMessages::HandlePushEquippedItemsState(RakNet::BitStream* inStream, Entity* entity) { @@ -5923,7 +5923,7 @@ void GameMessages::HandleClientItemConsumed(RakNet::BitStream* inStream, Entity* auto* missions = static_cast(entity->GetComponent(COMPONENT_TYPE_MISSION)); if (missions != nullptr) { - missions->Progress(MissionTaskType::MISSION_TASK_TYPE_FOOD, item->GetLot()); + missions->Progress(MissionTaskType::MISSION_TASK_TYPE_FOOD, item->GetLot()); } } @@ -5995,6 +5995,51 @@ void GameMessages::HandleMatchRequest(RakNet::BitStream* inStream, Entity* entit } } +void GameMessages::HandleGetHotPropertyData(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr) { + SendGetHotPropertyData(inStream, entity, sysAddr); +} + +void GameMessages::SendGetHotPropertyData(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr) { + CBITSTREAM + CMSGHEADER + /** + * [u32] - Number of properties + * [objid] - property id + * [objid] - property owner id + * [wstring] - property owner name + * [u64] - total reputation + * [i32] - property template id + * [wstring] - property name + * [wstring] - property description + * [float] - performance cost + * [timestamp] - time last published + * [cloneid] - clone id + * + */ + // TODO This needs to be implemented when reputation is implemented for getting hot properties. + /** + bitStream.Write(entity->GetObjectID()); + bitStream.Write(GAME_MSG::GAME_MSG_SEND_HOT_PROPERTY_DATA); + std::vector t = {25166, 25188, 25191, 25194}; + bitStream.Write(4); + for (uint8_t i = 0; i < 4; i++) { + bitStream.Write(entity->GetObjectID()); + bitStream.Write(entity->GetObjectID()); + bitStream.Write(1); + bitStream.Write('c'); + bitStream.Write(42069); + bitStream.Write(t[i]); + bitStream.Write(1); + bitStream.Write('c'); + bitStream.Write(1); + bitStream.Write('c'); + bitStream.Write(420.69f); + bitStream.Write(1658376385); + bitStream.Write(25166); + } + SEND_PACKET*/ +} + void GameMessages::HandleReportBug(RakNet::BitStream* inStream, Entity* entity) { //Definitely not stolen from autogenerated code, no sir: std::u16string body; @@ -6060,25 +6105,25 @@ void GameMessages::HandleReportBug(RakNet::BitStream* inStream, Entity* entity) void GameMessages::HandleClientRailMovementReady(RakNet::BitStream *inStream, Entity *entity, const SystemAddress &sysAddr) { - const auto possibleRails = EntityManager::Instance()->GetEntitiesByComponent(COMPONENT_TYPE_RAIL_ACTIVATOR); - for (const auto* possibleRail : possibleRails) { - const auto* rail = possibleRail->GetComponent(); - if (rail != nullptr) { - rail->OnRailMovementReady(entity); - } - } + const auto possibleRails = EntityManager::Instance()->GetEntitiesByComponent(COMPONENT_TYPE_RAIL_ACTIVATOR); + for (const auto* possibleRail : possibleRails) { + const auto* rail = possibleRail->GetComponent(); + if (rail != nullptr) { + rail->OnRailMovementReady(entity); + } + } } void GameMessages::HandleCancelRailMovement(RakNet::BitStream *inStream, Entity *entity, const SystemAddress &sysAddr) { - const auto immediate = inStream->ReadBit(); + const auto immediate = inStream->ReadBit(); - const auto possibleRails = EntityManager::Instance()->GetEntitiesByComponent(COMPONENT_TYPE_RAIL_ACTIVATOR); - for (const auto* possibleRail : possibleRails) { - auto* rail = possibleRail->GetComponent(); - if (rail != nullptr) { - rail->OnCancelRailMovement(entity); - } - } + const auto possibleRails = EntityManager::Instance()->GetEntitiesByComponent(COMPONENT_TYPE_RAIL_ACTIVATOR); + for (const auto* possibleRail : possibleRails) { + auto* rail = possibleRail->GetComponent(); + if (rail != nullptr) { + rail->OnCancelRailMovement(entity); + } + } } void GameMessages::HandlePlayerRailArrivedNotification(RakNet::BitStream *inStream, Entity *entity, @@ -6105,43 +6150,43 @@ void GameMessages::HandlePlayerRailArrivedNotification(RakNet::BitStream *inStre } void GameMessages::HandleModifyPlayerZoneStatistic(RakNet::BitStream *inStream, Entity *entity) { - const auto set = inStream->ReadBit(); - const auto statisticsName = GeneralUtils::ReadWString(inStream); + const auto set = inStream->ReadBit(); + const auto statisticsName = GeneralUtils::ReadWString(inStream); - int32_t value; - if (inStream->ReadBit()) { - inStream->Read(value); - } else { - value = 0; - } + int32_t value; + if (inStream->ReadBit()) { + inStream->Read(value); + } else { + value = 0; + } - LWOMAPID zone; - if (inStream->ReadBit()) { - inStream->Read(zone); - } else { - zone = LWOMAPID_INVALID; - } + LWOMAPID zone; + if (inStream->ReadBit()) { + inStream->Read(zone); + } else { + zone = LWOMAPID_INVALID; + } - // Notify the character component that something's changed - auto* characterComponent = entity->GetComponent(); - if (characterComponent != nullptr) { - characterComponent->HandleZoneStatisticsUpdate(zone, statisticsName, value); - } + // Notify the character component that something's changed + auto* characterComponent = entity->GetComponent(); + if (characterComponent != nullptr) { + characterComponent->HandleZoneStatisticsUpdate(zone, statisticsName, value); + } } void GameMessages::HandleUpdatePlayerStatistic(RakNet::BitStream* inStream, Entity* entity) { - int32_t updateID; - inStream->Read(updateID); + int32_t updateID; + inStream->Read(updateID); - int64_t updateValue; - if (inStream->ReadBit()) { - inStream->Read(updateValue); - } else { - updateValue = 1; - } + int64_t updateValue; + if (inStream->ReadBit()) { + inStream->Read(updateValue); + } else { + updateValue = 1; + } - auto* characterComponent = entity->GetComponent(); - if (characterComponent != nullptr) { - characterComponent->UpdatePlayerStatistic((StatisticID) updateID, (uint64_t) std::max(updateValue, int64_t(0))); - } + auto* characterComponent = entity->GetComponent(); + if (characterComponent != nullptr) { + characterComponent->UpdatePlayerStatistic((StatisticID) updateID, (uint64_t) std::max(updateValue, int64_t(0))); + } } diff --git a/dGame/dGameMessages/GameMessages.h b/dGame/dGameMessages/GameMessages.h index fc49ad70..c5b7888d 100644 --- a/dGame/dGameMessages/GameMessages.h +++ b/dGame/dGameMessages/GameMessages.h @@ -24,7 +24,7 @@ namespace GameMessages { class PropertyDataMessage; void SendFireEventClientSide(const LWOOBJID& objectID, const SystemAddress& sysAddr, std::u16string args, const LWOOBJID& object, int64_t param1, int param2, const LWOOBJID& sender); void SendTeleport(const LWOOBJID& objectID, const NiPoint3& pos, const NiQuaternion& rot, const SystemAddress& sysAddr, bool bSetRotation = false, bool noGravTeleport = true); - void SendPlayAnimation(Entity* entity, const std::u16string& animationName, float fPriority = 0.0f, float fScale = 1.0f); + void SendPlayAnimation(Entity* entity, const std::u16string& animationName, float fPriority = 0.0f, float fScale = 1.0f); void SendPlayerReady(Entity * entity, const SystemAddress& sysAddr); void SendPlayerAllowedRespawn(LWOOBJID entityID, bool doNotPromptRespawn, const SystemAddress& systemAddress); void SendInvalidZoneTransferList(Entity * entity, const SystemAddress& sysAddr, const std::u16string& feedbackURL, const std::u16string& invalidMapTransferList, bool feedbackOnExit, bool feedbackOnInvalidTransfer); @@ -47,27 +47,27 @@ namespace GameMessages { ); void SendPlayerSetCameraCyclingMode(const LWOOBJID& objectID, const SystemAddress& sysAddr, - bool bAllowCyclingWhileDeadOnly = true, eCyclingMode cyclingMode = ALLOW_CYCLE_TEAMMATES); + bool bAllowCyclingWhileDeadOnly = true, eCyclingMode cyclingMode = ALLOW_CYCLE_TEAMMATES); void SendPlayNDAudioEmitter(Entity* entity, const SystemAddress& sysAddr, std::string audioGUID); void SendStartPathing(Entity* entity); void SendPlatformResync(Entity* entity, const SystemAddress& sysAddr, bool bStopAtDesiredWaypoint = false, - int iIndex = 0, int iDesiredWaypointIndex = 1, int nextIndex = 1, - MovementPlatformState movementState = MovementPlatformState::Moving); - + int iIndex = 0, int iDesiredWaypointIndex = 1, int nextIndex = 1, + MovementPlatformState movementState = MovementPlatformState::Moving); + void SendRestoreToPostLoadStats(Entity * entity, const SystemAddress& sysAddr); void SendServerDoneLoadingAllObjects(Entity * entity, const SystemAddress& sysAddr); - void SendGMLevelBroadcast(const LWOOBJID& objectID, uint8_t level); - void SendChatModeUpdate(const LWOOBJID& objectID, uint8_t level); - + void SendGMLevelBroadcast(const LWOOBJID& objectID, uint8_t level); + void SendChatModeUpdate(const LWOOBJID& objectID, uint8_t level); + void SendAddItemToInventoryClientSync(Entity* entity, const SystemAddress& sysAddr, Item* item, const LWOOBJID& objectID, bool showFlyingLoot, int itemCount, LWOOBJID subKey = LWOOBJID_EMPTY, eLootSourceType lootSourceType = eLootSourceType::LOOT_SOURCE_NONE); - void SendNotifyClientFlagChange(const LWOOBJID& objectID, int iFlagID, bool bFlag, const SystemAddress& sysAddr); + void SendNotifyClientFlagChange(const LWOOBJID& objectID, int iFlagID, bool bFlag, const SystemAddress& sysAddr); void SendChangeObjectWorldState(const LWOOBJID& objectID, int state, const SystemAddress& sysAddr); - void SendOfferMission(const LWOOBJID& entity, const SystemAddress& sysAddr, int32_t missionID, const LWOOBJID& offererID); - void SendNotifyMission(Entity * entity, const SystemAddress& sysAddr, int missionID, int missionState, bool sendingRewards); - void SendNotifyMissionTask(Entity * entity, const SystemAddress& sysAddr, int missionID, int taskMask, std::vector updates); + void SendOfferMission(const LWOOBJID& entity, const SystemAddress& sysAddr, int32_t missionID, const LWOOBJID& offererID); + void SendNotifyMission(Entity * entity, const SystemAddress& sysAddr, int missionID, int missionState, bool sendingRewards); + void SendNotifyMissionTask(Entity * entity, const SystemAddress& sysAddr, int missionID, int taskMask, std::vector updates); void NotifyLevelRewards(LWOOBJID objectID, const SystemAddress& sysAddr, int level, bool sending_rewards); void SendModifyLEGOScore(Entity* entity, const SystemAddress& sysAddr, int64_t score, eLootSourceType sourceType); @@ -92,7 +92,7 @@ namespace GameMessages { void SendSetInventorySize(Entity* entity, int invType, int size); void SendSetEmoteLockState(Entity* entity, bool bLock, int emoteID); - void SendSetJetPackMode(Entity* entity, bool use, bool bypassChecks = false, bool doHover = false, int effectID = -1, float airspeed = 10, float maxAirspeed = 15, float verticalVelocity = 1, int warningEffectID = -1); + void SendSetJetPackMode(Entity* entity, bool use, bool bypassChecks = false, bool doHover = false, int effectID = -1, float airspeed = 10, float maxAirspeed = 15, float verticalVelocity = 1, int warningEffectID = -1); void SendResurrect(Entity* entity); void SendStop2DAmbientSound(Entity* entity, bool force, std::string audioGUID, bool result = false); void SendPlay2DAmbientSound(Entity* entity, std::string audioGUID, bool result = false); @@ -157,15 +157,15 @@ namespace GameMessages { // Rails stuff void SendSetRailMovement(const LWOOBJID& objectID, bool pathGoForward, std::u16string pathName, uint32_t pathStart, - const SystemAddress& sysAddr = UNASSIGNED_SYSTEM_ADDRESS, - int32_t railActivatorComponentID = -1, LWOOBJID railActivatorObjectID = LWOOBJID_EMPTY); + const SystemAddress& sysAddr = UNASSIGNED_SYSTEM_ADDRESS, + int32_t railActivatorComponentID = -1, LWOOBJID railActivatorObjectID = LWOOBJID_EMPTY); void SendStartRailMovement(const LWOOBJID& objectID, std::u16string pathName, std::u16string startSound, - std::u16string loopSound, std::u16string stopSound, const SystemAddress& sysAddr = UNASSIGNED_SYSTEM_ADDRESS, - uint32_t pathStart = 0, bool goForward = true, bool damageImmune = true, bool noAggro = true, - bool notifyActor = false, bool showNameBillboard = true, bool cameraLocked = true, - bool collisionEnabled = true, bool useDB = true, int32_t railComponentID = -1, - LWOOBJID railActivatorObjectID = LWOOBJID_EMPTY); + std::u16string loopSound, std::u16string stopSound, const SystemAddress& sysAddr = UNASSIGNED_SYSTEM_ADDRESS, + uint32_t pathStart = 0, bool goForward = true, bool damageImmune = true, bool noAggro = true, + bool notifyActor = false, bool showNameBillboard = true, bool cameraLocked = true, + bool collisionEnabled = true, bool useDB = true, int32_t railComponentID = -1, + LWOOBJID railActivatorObjectID = LWOOBJID_EMPTY); void HandleClientRailMovementReady(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr); void HandleCancelRailMovement(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr); @@ -180,9 +180,9 @@ namespace GameMessages { void SendBBBSaveResponse(const LWOOBJID& objectId, const LWOOBJID& localID, unsigned char* buffer, uint32_t bufferSize, const SystemAddress& sysAddr); void SendAddBuff(LWOOBJID& objectID, const LWOOBJID& casterID, uint32_t buffID, uint32_t msDuration, - bool addImmunity = false, bool cancelOnDamaged = false, bool cancelOnDeath = true, - bool cancelOnLogout = false, bool cancelOnRemoveBuff = true, bool cancelOnUi = false, - bool cancelOnUnequip = false, bool cancelOnZone = false, const SystemAddress& sysAddr = UNASSIGNED_SYSTEM_ADDRESS); + bool addImmunity = false, bool cancelOnDamaged = false, bool cancelOnDeath = true, + bool cancelOnLogout = false, bool cancelOnRemoveBuff = true, bool cancelOnUi = false, + bool cancelOnUnequip = false, bool cancelOnZone = false, const SystemAddress& sysAddr = UNASSIGNED_SYSTEM_ADDRESS); void SendToggleGMInvis(LWOOBJID objectId, bool enabled, const SystemAddress& sysAddr); @@ -252,7 +252,7 @@ namespace GameMessages { bool lockPlayer = true, bool result = false, bool skipIfSamePath = false, float startTimeAdvance = 0); void SendEndCinematic(LWOOBJID objectID, std::u16string pathName, const SystemAddress& sysAddr = UNASSIGNED_SYSTEM_ADDRESS, - float leadOut = -1.0f, bool leavePlayerLocked = false); + float leadOut = -1.0f, bool leavePlayerLocked = false); void HandleCinematicUpdate(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr); void SendSetStunned(LWOOBJID objectId, eStunState stateChangeType, const SystemAddress& sysAddr, @@ -389,6 +389,38 @@ namespace GameMessages { */ void HandleAcknowledgePossession(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr); + /** + * @brief A request from a client to get the hot properties that would appear on the news feed + * This incoming message has NO DATA and is simply a request that expects to send a reply to the sender. + * + * @param inStream packet of data + * @param entity The Entity that sent the request + * @param sysAddr The SystemAddress of the Entity that sent the request + */ + void HandleGetHotPropertyData(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr); + + /** + * @brief A request from a client to get the hot properties that would appear on the news feed + * The struct of data to send is as follows + * + * [u32] - Number of properties + * [objid] - property id + * [objid] - property owner id + * [wstring] - property owner name + * [u64] - total reputation + * [i32] - property template id + * [wstring] - property name + * [wstring] - property description + * [float] - performance cost + * [timestamp] - time last published + * [cloneid] - clone id + * + * @param inStream packet of data + * @param entity The Entity that sent the request + * @param sysAddr The SystemAddress of the Entity that sent the request + */ + void SendGetHotPropertyData(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr); + //Racing: void HandleModuleAssemblyQueryData(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr); @@ -459,16 +491,16 @@ namespace GameMessages { void SendUpdateReputation(const LWOOBJID objectId, const int64_t reputation, const SystemAddress& sysAddr); - // Leaderboards - void SendActivitySummaryLeaderboardData(const LWOOBJID& objectID, const Leaderboard* leaderboard, - const SystemAddress& sysAddr = UNASSIGNED_SYSTEM_ADDRESS); - void HandleActivitySummaryLeaderboardData(RakNet::BitStream* instream, Entity* entity, const SystemAddress& sysAddr); - void SendRequestActivitySummaryLeaderboardData(const LWOOBJID& objectID, const LWOOBJID& targetID, - const SystemAddress& sysAddr, const int32_t& gameID = 0, - const int32_t& queryType = 1, const int32_t& resultsEnd = 10, - const int32_t& resultsStart = 0, bool weekly = false); - void HandleRequestActivitySummaryLeaderboardData(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr); - void HandleActivityStateChangeRequest(RakNet::BitStream* inStream, Entity* entity); + // Leaderboards + void SendActivitySummaryLeaderboardData(const LWOOBJID& objectID, const Leaderboard* leaderboard, + const SystemAddress& sysAddr = UNASSIGNED_SYSTEM_ADDRESS); + void HandleActivitySummaryLeaderboardData(RakNet::BitStream* instream, Entity* entity, const SystemAddress& sysAddr); + void SendRequestActivitySummaryLeaderboardData(const LWOOBJID& objectID, const LWOOBJID& targetID, + const SystemAddress& sysAddr, const int32_t& gameID = 0, + const int32_t& queryType = 1, const int32_t& resultsEnd = 10, + const int32_t& resultsStart = 0, bool weekly = false); + void HandleRequestActivitySummaryLeaderboardData(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr); + void HandleActivityStateChangeRequest(RakNet::BitStream* inStream, Entity* entity); void SendVehicleAddPassiveBoostAction(LWOOBJID objectId, const SystemAddress& sysAddr); @@ -482,8 +514,8 @@ namespace GameMessages { void SendShowActivityCountdown(LWOOBJID objectId, bool bPlayAdditionalSound, bool bPlayCountdownSound, std::u16string sndName, int32_t stateToPlaySoundOn, const SystemAddress& sysAddr); - //Handlers: - + //Handlers: + void HandleToggleGhostReferenceOverride(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr); void HandleSetGhostReferencePosition(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr); @@ -491,19 +523,19 @@ namespace GameMessages { void HandleSellToVendor(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr); void HandleBuybackFromVendor(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr); void HandleParseChatMessage(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr); - void HandleToggleGhostReffrenceOverride(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr); - void HandleSetGhostReffrenceOverride(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr); - void HandleFireEventServerSide(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr); - void HandleRequestPlatformResync(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr); + void HandleToggleGhostReffrenceOverride(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr); + void HandleSetGhostReffrenceOverride(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr); + void HandleFireEventServerSide(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr); + void HandleRequestPlatformResync(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr); void HandleRebuildCancel(RakNet::BitStream* inStream, Entity* entity); - void HandleRequestUse(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr); - void HandlePlayEmote(RakNet::BitStream* inStream, Entity* entity); + void HandleRequestUse(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr); + void HandlePlayEmote(RakNet::BitStream* inStream, Entity* entity); void HandleModularBuildConvertModel(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr); - void HandleSetFlag(RakNet::BitStream* inStream, Entity* entity); - void HandleRespondToMission(RakNet::BitStream* inStream, Entity* entity); - void HandleMissionDialogOK(RakNet::BitStream* inStream, Entity* entity); - void HandleRequestLinkedMission(RakNet::BitStream* inStream, Entity* entity); - void HandleHasBeenCollected(RakNet::BitStream* inStream, Entity* entity); + void HandleSetFlag(RakNet::BitStream* inStream, Entity* entity); + void HandleRespondToMission(RakNet::BitStream* inStream, Entity* entity); + void HandleMissionDialogOK(RakNet::BitStream* inStream, Entity* entity); + void HandleRequestLinkedMission(RakNet::BitStream* inStream, Entity* entity); + void HandleHasBeenCollected(RakNet::BitStream* inStream, Entity* entity); void HandleNotifyServerLevelProcessingComplete(RakNet::BitStream* inStream, Entity* entity); void HandlePickupCurrency(RakNet::BitStream* inStream, Entity* entity); void HandleRequestDie(RakNet::BitStream* inStream, Entity* entity); @@ -537,7 +569,7 @@ namespace GameMessages { class EchoSyncSkill { static const GAME_MSG MsgID = GAME_MSG_ECHO_SYNC_SKILL; - public: + public: EchoSyncSkill() { bDone = false; } @@ -598,7 +630,7 @@ namespace GameMessages { class SyncSkill { static const GAME_MSG MsgID = GAME_MSG_SYNC_SKILL; - public: + public: SyncSkill() { bDone = false; } @@ -659,7 +691,7 @@ namespace GameMessages { class RequestServerProjectileImpact { static const GAME_MSG MsgID = GAME_MSG_REQUEST_SERVER_PROJECTILE_IMPACT; - public: + public: RequestServerProjectileImpact() { i64LocalID = LWOOBJID_EMPTY; i64TargetID = LWOOBJID_EMPTY; @@ -728,7 +760,7 @@ namespace GameMessages { class DoClientProjectileImpact { static const GAME_MSG MsgID = GAME_MSG_DO_CLIENT_PROJECTILE_IMPACT; - public: + public: DoClientProjectileImpact() { i64OrgID = LWOOBJID_EMPTY; i64OwnerID = LWOOBJID_EMPTY; @@ -1078,7 +1110,4 @@ namespace GameMessages { }; }; - - - #endif // GAMEMESSAGES_H diff --git a/dNet/dMessageIdentifiers.h b/dNet/dMessageIdentifiers.h index cb46b5d1..4e88a9af 100644 --- a/dNet/dMessageIdentifiers.h +++ b/dNet/dMessageIdentifiers.h @@ -354,8 +354,8 @@ enum GAME_MSG : unsigned short { GAME_MSG_REGISTER_PET_ID = 565, GAME_MSG_REGISTER_PET_DBID = 566, GAME_MSG_SHOW_ACTIVITY_COUNTDOWN = 568, - GAME_MSG_START_ACTIVITY_TIME = 576, - GAME_MSG_ACTIVITY_PAUSE = 602, + GAME_MSG_START_ACTIVITY_TIME = 576, + GAME_MSG_ACTIVITY_PAUSE = 602, GAME_MSG_USE_NON_EQUIPMENT_ITEM = 603, GAME_MSG_USE_ITEM_RESULT = 607, GAME_MSG_COMMAND_PET = 640, @@ -386,14 +386,14 @@ enum GAME_MSG : unsigned short { GAME_MSG_PROPERTY_EDITOR_BEGIN = 724, GAME_MSG_PROPERTY_EDITOR_END = 725, GAME_MSG_START_PATHING = 735, - GAME_MSG_NOTIFY_CLIENT_ZONE_OBJECT = 737, + GAME_MSG_NOTIFY_CLIENT_ZONE_OBJECT = 737, GAME_MSG_UPDATE_REPUTATION = 746, GAME_MSG_PROPERTY_RENTAL_RESPONSE = 750, GAME_MSG_REQUEST_PLATFORM_RESYNC = 760, GAME_MSG_PLATFORM_RESYNC = 761, GAME_MSG_PLAY_CINEMATIC = 762, GAME_MSG_END_CINEMATIC = 763, - GAME_MSG_CINEMATIC_UPDATE = 764, + GAME_MSG_CINEMATIC_UPDATE = 764, GAME_MSG_TOGGLE_GHOST_REFERENCE_OVERRIDE = 767, GAME_MSG_SET_GHOST_REFERENCE_POSITION = 768, GAME_MSG_FIRE_EVENT_SERVER_SIDE = 770, @@ -438,8 +438,8 @@ enum GAME_MSG : unsigned short { GAME_MSG_BBB_SAVE_RESPONSE = 1006, GAME_MSG_NOTIFY_CLIENT_OBJECT = 1042, GAME_MSG_DISPLAY_ZONE_SUMMARY = 1043, - GAME_MSG_ACTIVITY_STATE_CHANGE_REQUEST = 1053, - GAME_MSG_MODIFY_PLAYER_ZONE_STATISTIC = 1046, + GAME_MSG_ACTIVITY_STATE_CHANGE_REQUEST = 1053, + GAME_MSG_MODIFY_PLAYER_ZONE_STATISTIC = 1046, GAME_MSG_START_BUILDING_WITH_ITEM = 1057, GAME_MSG_START_ARRANGING_WITH_ITEM = 1061, GAME_MSG_FINISH_ARRANGING_WITH_ITEM = 1062, @@ -460,7 +460,7 @@ enum GAME_MSG : unsigned short { GAME_MSG_REQUEST_SERVER_PROJECTILE_IMPACT = 1148, GAME_MSG_DO_CLIENT_PROJECTILE_IMPACT = 1151, GAME_MSG_MODULAR_BUILD_CONVERT_MODEL = 1155, - GAME_MSG_SET_PLAYER_ALLOWED_RESPAWN = 1165, + GAME_MSG_SET_PLAYER_ALLOWED_RESPAWN = 1165, GAME_MSG_UI_MESSAGE_SERVER_TO_SINGLE_CLIENT = 1184, GAME_MSG_UI_MESSAGE_SERVER_TO_ALL_CLIENTS = 1185, GAME_MSG_PET_TAMING_TRY_BUILD = 1197, @@ -515,10 +515,10 @@ enum GAME_MSG : unsigned short { GAME_MSG_RESTORE_TO_POST_LOAD_STATS = 1468, GAME_MSG_SET_RAIL_MOVEMENT = 1471, GAME_MSG_START_RAIL_MOVEMENT = 1472, - GAME_MSG_CANCEL_RAIL_MOVEMENT = 1474, - GAME_MSG_CLIENT_RAIL_MOVEMENT_READY = 1476, - GAME_MSG_PLAYER_RAIL_ARRIVED_NOTIFICATION = 1477, - GAME_MSG_UPDATE_PLAYER_STATISTIC = 1481, + GAME_MSG_CANCEL_RAIL_MOVEMENT = 1474, + GAME_MSG_CLIENT_RAIL_MOVEMENT_READY = 1476, + GAME_MSG_PLAYER_RAIL_ARRIVED_NOTIFICATION = 1477, + GAME_MSG_UPDATE_PLAYER_STATISTIC = 1481, GAME_MSG_MODULAR_ASSEMBLY_NIF_COMPLETED = 1498, GAME_MSG_NOTIFY_NOT_ENOUGH_INV_SPACE = 1516, GAME_MSG_TEAM_SET_LEADER = 0x0615, @@ -527,11 +527,13 @@ enum GAME_MSG : unsigned short { GAME_MSG_TEAM_ADD_PLAYER = 0x061a, GAME_MSG_TEAM_REMOVE_PLAYER = 0x061b, GAME_MSG_START_CELEBRATION_EFFECT = 1618, - GAME_MSG_ADD_BUFF = 1647, + GAME_MSG_ADD_BUFF = 1647, GAME_MSG_SERVER_DONE_LOADING_ALL_OBJECTS = 1642, GAME_MSG_PLACE_PROPERTY_MODEL = 1170, GAME_MSG_VEHICLE_NOTIFY_HIT_IMAGINATION_SERVER = 1606, GAME_MSG_ADD_RUN_SPEED_MODIFIER = 1505, + GAME_MSG_HANDLE_HOT_PROPERTY_DATA = 1511, + GAME_MSG_SEND_HOT_PROPERTY_DATA = 1510, GAME_MSG_REMOVE_RUN_SPEED_MODIFIER = 1506, GAME_MSG_UPDATE_PROPERTY_PERFORMANCE_COST = 1547, GAME_MSG_PROPERTY_ENTRANCE_BEGIN = 1553, @@ -544,4 +546,4 @@ enum GAME_MSG : unsigned short { GAME_MSG_DISMOUNT_COMPLETE = 1756, GAME_MSG_MARK_INVENTORY_ITEM_AS_ACTIVE = 1767, END -}; \ No newline at end of file +}; From f2d1c5d26d16678d57be92b43844a3fc4da24092 Mon Sep 17 00:00:00 2001 From: Aaron Kimbrell Date: Sun, 24 Jul 2022 13:04:02 -0500 Subject: [PATCH 17/86] Split out Level progression component (#671) * Split out Level progression component from Character Component This is to get to the Player forced movement Comp in a sane way * move XML to component insted of abusing charComp * use overrides should probably make everything that calls that call it correctly * fix linking issue --- dCommon/dCommonVars.h | 3 +- dGame/Entity.cpp | 23 +++++- dGame/dComponents/CMakeLists.txt | 1 + dGame/dComponents/CharacterComponent.cpp | 70 ------------------ dGame/dComponents/CharacterComponent.h | 22 ------ .../dComponents/LevelProgressionComponent.cpp | 74 +++++++++++++++++++ dGame/dComponents/LevelProgressionComponent.h | 63 ++++++++++++++++ dGame/dGameMessages/GameMessages.cpp | 22 +++--- dGame/dMission/Mission.cpp | 6 +- dGame/dUtilities/Preconditions.cpp | 7 +- dGame/dUtilities/SlashCommandHandler.cpp | 11 ++- 11 files changed, 185 insertions(+), 117 deletions(-) create mode 100644 dGame/dComponents/LevelProgressionComponent.cpp create mode 100644 dGame/dComponents/LevelProgressionComponent.h diff --git a/dCommon/dCommonVars.h b/dCommon/dCommonVars.h index 77d51125..f6efdcf8 100644 --- a/dCommon/dCommonVars.h +++ b/dCommon/dCommonVars.h @@ -402,13 +402,14 @@ enum eReplicaComponentType : int32_t { COMPONENT_TYPE_RACING_CONTROL = 71, //!< The RacingControl Component COMPONENT_TYPE_MISSION_OFFER = 73, //!< The MissionOffer Component COMPONENT_TYPE_EXHIBIT = 75, //!< The Exhibit Component - COMPONENT_TYPE_RACING_STATS = 74, //!< The Exhibit Component + COMPONENT_TYPE_RACING_STATS = 74, //!< The Racing Stats Component COMPONENT_TYPE_SOUND_TRIGGER = 77, //!< The Sound Trigger Component COMPONENT_TYPE_PROXIMITY_MONITOR = 78, //!< The Proximity Monitor Component COMPONENT_TYPE_MISSION = 84, //!< The Mission Component COMPONENT_TYPE_ROCKET_LAUNCH_LUP = 97, //!< The LUP Launchpad Componen COMPONENT_TYPE_RAIL_ACTIVATOR = 104, COMPONENT_TYPE_POSSESSABLE = 108, //!< The Possessable Component + COMPONENT_TYPE_LEVEL_PROGRESSION = 109, //!< The Level Progression Component COMPONENT_TYPE_POSSESSOR = 110, //!< The Possessor Component COMPONENT_TYPE_BUILD_BORDER = 114, //!< The Build Border Component COMPONENT_TYPE_DESTROYABLE = 1000, //!< The Destroyable Component diff --git a/dGame/Entity.cpp b/dGame/Entity.cpp index c44db6f1..45287bd8 100644 --- a/dGame/Entity.cpp +++ b/dGame/Entity.cpp @@ -28,6 +28,7 @@ #include "BuffComponent.h" #include "BouncerComponent.h" #include "InventoryComponent.h" +#include "LevelProgressionComponent.h" #include "ScriptComponent.h" #include "SkillComponent.h" #include "SimplePhysicsComponent.h" @@ -442,8 +443,14 @@ void Entity::Initialize() }*/ if (compRegistryTable->GetByIDAndType(m_TemplateID, COMPONENT_TYPE_CHARACTER) > 0 || m_Character) { - // Character Component always has a possessor component + // Character Component always has a possessor and level components m_Components.insert(std::make_pair(COMPONENT_TYPE_POSSESSOR, new PossessorComponent(this))); + + // load in the xml for the level + auto* levelComp = new LevelProgressionComponent(this); + levelComp->LoadFromXml(m_Character->GetXMLDoc()); + m_Components.insert(std::make_pair(COMPONENT_TYPE_LEVEL_PROGRESSION, levelComp)); + CharacterComponent* comp = new CharacterComponent(this, m_Character); m_Components.insert(std::make_pair(COMPONENT_TYPE_CHARACTER, comp)); } @@ -770,10 +777,9 @@ void Entity::Initialize() if (m_Character) { auto* controllablePhysicsComponent = GetComponent(); - auto* characterComponent = GetComponent(); + auto* levelComponent = GetComponent(); - if (controllablePhysicsComponent != nullptr && characterComponent->GetLevel() >= 20) - { + if (controllablePhysicsComponent != nullptr && levelComponent->GetLevel() >= 20) { controllablePhysicsComponent->SetSpeedMultiplier(525.0f / 500.0f); } } @@ -1088,6 +1094,15 @@ void Entity::WriteComponents(RakNet::BitStream* outBitStream, eReplicaPacketType // Should never happen, but just to be safe outBitStream->Write0(); } + + LevelProgressionComponent* levelProgressionComponent; + if (TryGetComponent(COMPONENT_TYPE_LEVEL_PROGRESSION, levelProgressionComponent)) { + levelProgressionComponent->Serialize(outBitStream, bIsInitialUpdate, flags); + } else { + // Should never happen, but just to be safe + outBitStream->Write0(); + } + characterComponent->Serialize(outBitStream, bIsInitialUpdate, flags); } diff --git a/dGame/dComponents/CMakeLists.txt b/dGame/dComponents/CMakeLists.txt index 706395ea..ebf93dde 100644 --- a/dGame/dComponents/CMakeLists.txt +++ b/dGame/dComponents/CMakeLists.txt @@ -7,6 +7,7 @@ set(DGAME_DCOMPONENTS_SOURCES "BaseCombatAIComponent.cpp" "ControllablePhysicsComponent.cpp" "DestroyableComponent.cpp" "InventoryComponent.cpp" + "LevelProgressionComponent.cpp" "LUPExhibitComponent.cpp" "MissionComponent.cpp" "MissionOfferComponent.cpp" diff --git a/dGame/dComponents/CharacterComponent.cpp b/dGame/dComponents/CharacterComponent.cpp index dd2b69bb..a1eb3c62 100644 --- a/dGame/dComponents/CharacterComponent.cpp +++ b/dGame/dComponents/CharacterComponent.cpp @@ -21,7 +21,6 @@ CharacterComponent::CharacterComponent(Entity* parent, Character* character) : C m_IsGM = false; m_IsLanding = false; m_IsLEGOClubMember = true; - m_Level = 1; m_DirtyCurrentActivity = false; m_DirtyGMInfo = false; @@ -80,8 +79,6 @@ CharacterComponent::~CharacterComponent() { } void CharacterComponent::Serialize(RakNet::BitStream* outBitStream, bool bIsInitialUpdate, unsigned int& flags) { - outBitStream->Write1(); - outBitStream->Write(m_Level); outBitStream->Write0(); if (bIsInitialUpdate) { @@ -181,57 +178,6 @@ void CharacterComponent::SetPvpEnabled(const bool value) m_PvpEnabled = value; } -void CharacterComponent::HandleLevelUp() -{ - auto* rewardsTable = CDClientManager::Instance()->GetTable("Rewards"); - - const auto& rewards = rewardsTable->GetByLevelID(m_Level); - bool rewardingItem = rewards.size() > 0; - - auto* parent = m_Character->GetEntity(); - - if (parent == nullptr) - { - return; - } - - auto* inventoryComponent = parent->GetComponent(); - auto* controllablePhysicsComponent = parent->GetComponent(); - - if (inventoryComponent == nullptr || controllablePhysicsComponent == nullptr) - { - return; - } - // Tell the client we beginning to send level rewards. - if(rewardingItem) GameMessages::NotifyLevelRewards(parent->GetObjectID(), parent->GetSystemAddress(), m_Level, rewardingItem); - - for (auto* reward : rewards) - { - switch (reward->rewardType) - { - case 0: - inventoryComponent->AddItem(reward->value, reward->count, eLootSourceType::LOOT_SOURCE_LEVEL_REWARD); - break; - case 4: - { - auto* items = inventoryComponent->GetInventory(eInventoryType::ITEMS); - items->SetSize(items->GetSize() + reward->value); - } - break; - case 9: - controllablePhysicsComponent->SetSpeedMultiplier(static_cast(reward->value) / 500.0f); - break; - case 11: - case 12: - break; - default: - break; - } - } - // Tell the client we have finished sending level rewards. - if(rewardingItem) GameMessages::NotifyLevelRewards(parent->GetObjectID(), parent->GetSystemAddress(), m_Level, !rewardingItem); -} - void CharacterComponent::SetGMLevel(int gmlevel) { m_DirtyGMInfo = true; if (gmlevel > 0) m_IsGM = true; @@ -332,14 +278,6 @@ void CharacterComponent::LoadFromXML() { } } - tinyxml2::XMLElement* level = doc->FirstChildElement("obj")->FirstChildElement("lvl"); - if (!level) { - Game::logger->Log("CharacterComponent", "Failed to find lvl tag while loading XML!\n"); - return; - } - - level->QueryAttribute("l", &m_Level); - if (character->FindAttribute("time")) { character->QueryUnsigned64Attribute("time", &m_TotalTimePlayed); } else { @@ -419,14 +357,6 @@ void CharacterComponent::UpdateXml(tinyxml2::XMLDocument* doc) { // End custom attributes // - tinyxml2::XMLElement* level = doc->FirstChildElement("obj")->FirstChildElement("lvl"); - if (!level) { - Game::logger->Log("CharacterComponent", "Failed to find lvl tag while updating XML!\n"); - return; - } - - level->SetAttribute("l", m_Level); - auto newUpdateTimestamp = std::time(nullptr); Game::logger->Log("TotalTimePlayed", "Time since last save: %d\n", newUpdateTimestamp - m_LastUpdateTimestamp); diff --git a/dGame/dComponents/CharacterComponent.h b/dGame/dComponents/CharacterComponent.h index 009530c4..83b67a17 100644 --- a/dGame/dComponents/CharacterComponent.h +++ b/dGame/dComponents/CharacterComponent.h @@ -95,18 +95,6 @@ public: */ void RocketUnEquip(Entity* player); - /** - * Gets the current level of the entity - * @return the current level of the entity - */ - const uint32_t GetLevel() const { return m_Level; } - - /** - * Sets the level of the entity - * @param level the level to set - */ - void SetLevel(uint32_t level) { m_Level = level; } - /** * Gets the universe score of the entity * @return the universe score of the entity @@ -191,11 +179,6 @@ public: */ void SetMountItemID(LWOOBJID mountItemID) { m_MountItemID = mountItemID; } - /** - * Gives the player rewards for the last level that they leveled up from - */ - void HandleLevelUp(); - /** * Gets the name of this character * @return the name of this character @@ -323,11 +306,6 @@ private: */ uint8_t m_PossessableType = 1; - /** - * Level of the entity - */ - uint32_t m_Level; - /** * Universe score of the entity */ diff --git a/dGame/dComponents/LevelProgressionComponent.cpp b/dGame/dComponents/LevelProgressionComponent.cpp new file mode 100644 index 00000000..96d31970 --- /dev/null +++ b/dGame/dComponents/LevelProgressionComponent.cpp @@ -0,0 +1,74 @@ +#include "LevelProgressionComponent.h" +#include "ControllablePhysicsComponent.h" +#include "InventoryComponent.h" +#include "CharacterComponent.h" +#include "tinyxml2.h" + +LevelProgressionComponent::LevelProgressionComponent(Entity* parent) : Component(parent) { + m_Parent = parent; + m_Level = 1; +} + +void LevelProgressionComponent::UpdateXml(tinyxml2::XMLDocument* doc) { + tinyxml2::XMLElement* level = doc->FirstChildElement("obj")->FirstChildElement("lvl"); + if (!level) { + Game::logger->Log("LevelProgressionComponent", "Failed to find lvl tag while updating XML!\n"); + return; + } + level->SetAttribute("l", m_Level); + +} + +void LevelProgressionComponent::LoadFromXml(tinyxml2::XMLDocument* doc){ + tinyxml2::XMLElement* level = doc->FirstChildElement("obj")->FirstChildElement("lvl"); + if (!level) { + Game::logger->Log("LevelProgressionComponent", "Failed to find lvl tag while loading XML!\n"); + return; + } + level->QueryAttribute("l", &m_Level); + +} + +void LevelProgressionComponent::Serialize(RakNet::BitStream* outBitStream, bool bIsInitialUpdate, unsigned int& flags){ + outBitStream->Write(bIsInitialUpdate || m_DirtyLevelInfo); + if (bIsInitialUpdate || m_DirtyLevelInfo) outBitStream->Write(m_Level); + m_DirtyLevelInfo = false; +} + +void LevelProgressionComponent::HandleLevelUp() { + auto* rewardsTable = CDClientManager::Instance()->GetTable("Rewards"); + + const auto& rewards = rewardsTable->GetByLevelID(m_Level); + bool rewardingItem = rewards.size() > 0; + + auto* inventoryComponent = m_Parent->GetComponent(); + auto* controllablePhysicsComponent = m_Parent->GetComponent(); + + if (!inventoryComponent || !controllablePhysicsComponent) return; + // Tell the client we beginning to send level rewards. + if(rewardingItem) GameMessages::NotifyLevelRewards(m_Parent->GetObjectID(), m_Parent->GetSystemAddress(), m_Level, rewardingItem); + + for (auto* reward : rewards) { + switch (reward->rewardType) { + case 0: + inventoryComponent->AddItem(reward->value, reward->count, eLootSourceType::LOOT_SOURCE_LEVEL_REWARD); + break; + case 4: + { + auto* items = inventoryComponent->GetInventory(eInventoryType::ITEMS); + items->SetSize(items->GetSize() + reward->value); + } + break; + case 9: + controllablePhysicsComponent->SetSpeedMultiplier(static_cast(reward->value) / 500.0f); + break; + case 11: + case 12: + break; + default: + break; + } + } + // Tell the client we have finished sending level rewards. + if(rewardingItem) GameMessages::NotifyLevelRewards(m_Parent->GetObjectID(), m_Parent->GetSystemAddress(), m_Level, !rewardingItem); +} diff --git a/dGame/dComponents/LevelProgressionComponent.h b/dGame/dComponents/LevelProgressionComponent.h new file mode 100644 index 00000000..ead3edfb --- /dev/null +++ b/dGame/dComponents/LevelProgressionComponent.h @@ -0,0 +1,63 @@ +#pragma once + +#include "Entity.h" +#include "GameMessages.h" +#include "Component.h" + +/** + * Component that handles level progression and serilization. + * + */ +class LevelProgressionComponent : public Component { +public: + static const uint32_t ComponentType = eReplicaComponentType::COMPONENT_TYPE_LEVEL_PROGRESSION; + + /** + * Constructor for this component + * @param parent parent that contains this component + */ + LevelProgressionComponent(Entity* parent); + ~LevelProgressionComponent() override {}; + + void Serialize(RakNet::BitStream* outBitStream, bool bIsInitialUpdate, unsigned int& flags); + + /** + * Save data from this componennt to character XML + * @param doc the document to write data to + */ + void UpdateXml(tinyxml2::XMLDocument* doc) override; + + /** + * Load base data for this component from character XML + * @param doc the document to read data from + */ + void LoadFromXml(tinyxml2::XMLDocument* doc) override; + + /** + * Gets the current level of the entity + * @return the current level of the entity + */ + const uint32_t GetLevel() const { return m_Level; } + + /** + * Sets the level of the entity + * @param level the level to set + */ + void SetLevel(uint32_t level) { m_Level = level; m_DirtyLevelInfo = true; } + + /** + * Gives the player rewards for the last level that they leveled up from + */ + void HandleLevelUp(); + +private: + /** + * whether the level is dirty + */ + bool m_DirtyLevelInfo = false; + + /** + * Level of the entity + */ + uint32_t m_Level; +}; diff --git a/dGame/dGameMessages/GameMessages.cpp b/dGame/dGameMessages/GameMessages.cpp index 2f193170..935a7ccb 100644 --- a/dGame/dGameMessages/GameMessages.cpp +++ b/dGame/dGameMessages/GameMessages.cpp @@ -58,6 +58,7 @@ #include "PossessorComponent.h" #include "RacingControlComponent.h" #include "RailActivatorComponent.h" +#include "LevelProgressionComponent.h" // Message includes: #include "dZoneManager.h" @@ -912,14 +913,11 @@ void GameMessages::SendResurrect(Entity* entity) { DestroyableComponent* dest = static_cast(entity->GetComponent(COMPONENT_TYPE_DESTROYABLE)); if (dest != nullptr && entity->GetLOT() == 1) { - auto* characterComponent = entity->GetComponent(); - - if (characterComponent == nullptr) { - return; + auto* levelComponent = entity->GetComponent(); + if (levelComponent) { + dest->SetHealth(levelComponent->GetLevel() >= 45 ? 8 : 4); + dest->SetImagination(levelComponent->GetLevel() >= 45 ? 20 : 6); } - - dest->SetHealth(characterComponent->GetLevel() >= 45 ? 8 : 4); - dest->SetImagination(characterComponent->GetLevel() >= 45 ? 20 : 6); } auto cont = static_cast(entity->GetComponent(COMPONENT_TYPE_CONTROLLABLE_PHYSICS)); @@ -5309,13 +5307,15 @@ void GameMessages::HandleHasBeenCollected(RakNet::BitStream* inStream, Entity* e } void GameMessages::HandleNotifyServerLevelProcessingComplete(RakNet::BitStream* inStream, Entity* entity) { - auto* character = static_cast(entity->GetComponent(COMPONENT_TYPE_CHARACTER)); + auto* levelComp = entity->GetComponent(); + if (!levelComp) return; + auto* character = entity->GetComponent(); if (!character) return; //Update our character's level in memory: - character->SetLevel(character->GetLevel() + 1); + levelComp->SetLevel(levelComp->GetLevel() + 1); - character->HandleLevelUp(); + levelComp->HandleLevelUp(); auto* inventoryComponent = entity->GetComponent(); @@ -5333,7 +5333,7 @@ void GameMessages::HandleNotifyServerLevelProcessingComplete(RakNet::BitStream* //Send a notification in chat: std::stringstream wss; wss << "level=1:"; - wss << character->GetLevel(); + wss << levelComp->GetLevel(); wss << "\n"; wss << "name=0:"; wss << character->GetName(); diff --git a/dGame/dMission/Mission.cpp b/dGame/dMission/Mission.cpp index aeb26838..e51a6901 100644 --- a/dGame/dMission/Mission.cpp +++ b/dGame/dMission/Mission.cpp @@ -1,10 +1,11 @@ -#include "Mission.h" +#include "Mission.h" #include #include "CDClientManager.h" #include "Character.h" #include "CharacterComponent.h" +#include "LevelProgressionComponent.h" #include "DestroyableComponent.h" #include "EntityManager.h" #include "Game.h" @@ -406,6 +407,7 @@ void Mission::YieldRewards() { auto* character = GetUser()->GetLastUsedChar(); auto* inventoryComponent = entity->GetComponent(); + auto* levelComponent = entity->GetComponent(); auto* characterComponent = entity->GetComponent(); auto* destroyableComponent = entity->GetComponent(); auto* missionComponent = entity->GetComponent(); @@ -433,7 +435,7 @@ void Mission::YieldRewards() { int32_t coinsToSend = 0; if (info->LegoScore > 0) { eLootSourceType lootSource = info->isMission ? eLootSourceType::LOOT_SOURCE_MISSION : eLootSourceType::LOOT_SOURCE_ACHIEVEMENT; - if(characterComponent->GetLevel() >= dZoneManager::Instance()->GetMaxLevel()) { + if(levelComponent->GetLevel() >= dZoneManager::Instance()->GetMaxLevel()) { // Since the character is at the level cap we reward them with coins instead of UScore. coinsToSend += info->LegoScore * dZoneManager::Instance()->GetLevelCapCurrencyConversion(); } else { diff --git a/dGame/dUtilities/Preconditions.cpp b/dGame/dUtilities/Preconditions.cpp index bd10b814..2e006ec4 100644 --- a/dGame/dUtilities/Preconditions.cpp +++ b/dGame/dUtilities/Preconditions.cpp @@ -1,4 +1,4 @@ -#include "Preconditions.h" +#include "Preconditions.h" #include "Game.h" #include "dLogger.h" @@ -9,6 +9,7 @@ #include "MissionComponent.h" #include "Character.h" #include "CharacterComponent.h" +#include "LevelProgressionComponent.h" #include "DestroyableComponent.h" #include "GameMessages.h" @@ -128,7 +129,7 @@ bool Precondition::CheckValue(Entity* player, const uint32_t value, bool evaluat auto* missionComponent = player->GetComponent(); auto* inventoryComponent = player->GetComponent(); auto* destroyableComponent = player->GetComponent(); - auto* characterComponent = player->GetComponent(); + auto* levelComponent = player->GetComponent(); auto* character = player->GetCharacter(); Mission* mission; @@ -207,7 +208,7 @@ bool Precondition::CheckValue(Entity* player, const uint32_t value, bool evaluat case PreconditionType::NoInteraction: return false; // TODO case PreconditionType::HasLevel: - return characterComponent->GetLevel() >= value; + return levelComponent->GetLevel() >= value; default: return true; // There are a couple more unknown preconditions. Always return true in this case. } diff --git a/dGame/dUtilities/SlashCommandHandler.cpp b/dGame/dUtilities/SlashCommandHandler.cpp index 22fbb680..4172884f 100644 --- a/dGame/dUtilities/SlashCommandHandler.cpp +++ b/dGame/dUtilities/SlashCommandHandler.cpp @@ -62,6 +62,7 @@ #include "VanityUtilities.h" #include "GameConfig.h" #include "ScriptedActivityComponent.h" +#include "LevelProgressionComponent.h" void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entity* entity, const SystemAddress& sysAddr) { std::string chatCommand; @@ -1329,6 +1330,8 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit // query to set our uscore to the correct value for this level auto characterComponent = entity->GetComponent(); + if (!characterComponent) return; + auto levelComponent = entity->GetComponent(); auto query = CDClientDatabase::CreatePreppedStmt("SELECT requiredUScore from LevelProgressionLookup WHERE id = ?;"); query.bind(1, (int)requestedLevel); auto result = query.execQuery(); @@ -1336,18 +1339,18 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit if (result.eof()) return; // Set the UScore first - oldLevel = characterComponent->GetLevel(); + oldLevel = levelComponent->GetLevel(); characterComponent->SetUScore(result.getIntField(0, characterComponent->GetUScore())); // handle level up for each level we have passed if we set our level to be higher than the current one. if (oldLevel < requestedLevel) { while (oldLevel < requestedLevel) { oldLevel+=1; - characterComponent->SetLevel(oldLevel); - characterComponent->HandleLevelUp(); + levelComponent->SetLevel(oldLevel); + levelComponent->HandleLevelUp(); } } else { - characterComponent->SetLevel(requestedLevel); + levelComponent->SetLevel(requestedLevel); } if (requestedPlayerToSetLevelOf != "") { From b57cacc676dcdbf4fe6ec75bb0cf6d3dbd13abc3 Mon Sep 17 00:00:00 2001 From: Aaron Kimbrell Date: Sun, 24 Jul 2022 13:25:10 -0500 Subject: [PATCH 18/86] Player forced movement component (#672) * Split out Level progression component from Character Component This is to get to the Player forced movement Comp in a sane way * move XML to component insted of abusing charComp * use overrides should probably make everything that calls that call it correctly * fix linking issue * Add proper Player Force movement component Not used, yet --- dCommon/dCommonVars.h | 95 ++++++++++--------- dGame/Entity.cpp | 19 ++-- dGame/dComponents/CMakeLists.txt | 1 + .../PlayerForcedMovementComponent.cpp | 16 ++++ .../PlayerForcedMovementComponent.h | 70 ++++++++++++++ 5 files changed, 147 insertions(+), 54 deletions(-) create mode 100644 dGame/dComponents/PlayerForcedMovementComponent.cpp create mode 100644 dGame/dComponents/PlayerForcedMovementComponent.h diff --git a/dCommon/dCommonVars.h b/dCommon/dCommonVars.h index f6efdcf8..9f62eaa4 100644 --- a/dCommon/dCommonVars.h +++ b/dCommon/dCommonVars.h @@ -366,53 +366,54 @@ enum eNotifyType { }; enum eReplicaComponentType : int32_t { - COMPONENT_TYPE_CONTROLLABLE_PHYSICS = 1, //!< The ControllablePhysics Component - COMPONENT_TYPE_RENDER = 2, //!< The Render Component - COMPONENT_TYPE_SIMPLE_PHYSICS = 3, //!< The SimplePhysics Component - COMPONENT_TYPE_CHARACTER = 4, //!< The Character Component - COMPONENT_TYPE_SCRIPT = 5, //!< The Script Component - COMPONENT_TYPE_BOUNCER = 6, //!< The Bouncer Component - COMPONENT_TYPE_BUFF = 7, //!< The Buff Component - COMPONENT_TYPE_SKILL = 9, //!< The Skill Component - COMPONENT_TYPE_ITEM = 11, //!< The Item Component - COMPONENT_TYPE_VENDOR = 16, //!< The Vendor Component - COMPONENT_TYPE_INVENTORY = 17, //!< The Inventory Component - COMPONENT_TYPE_SHOOTING_GALLERY = 19, //!< The Shooting Gallery Component - COMPONENT_TYPE_RIGID_BODY_PHANTOM_PHYSICS = 20, //!< The RigidBodyPhantomPhysics Component - COMPONENT_TYPE_COLLECTIBLE = 23, //!< The Collectible Component - COMPONENT_TYPE_MOVING_PLATFORM = 25, //!< The MovingPlatform Component - COMPONENT_TYPE_PET = 26, //!< The Pet Component - COMPONENT_TYPE_VEHICLE_PHYSICS = 30, //!< The VehiclePhysics Component - COMPONENT_TYPE_MOVEMENT_AI = 31, //!< The MovementAI Component - COMPONENT_TYPE_PROPERTY = 36, //!< The Property Component - COMPONENT_TYPE_SCRIPTED_ACTIVITY = 39, //!< The ScriptedActivity Component - COMPONENT_TYPE_PHANTOM_PHYSICS = 40, //!< The PhantomPhysics Component - COMPONENT_TYPE_MODEL = 42, //!< The Model Component - COMPONENT_TYPE_PROPERTY_ENTRANCE = 43, //!< The PhantomPhysics Component - COMPONENT_TYPE_PROPERTY_MANAGEMENT = 45, //!< The PropertyManagement Component - COMPONENT_TYPE_REBUILD = 48, //!< The Rebuild Component - COMPONENT_TYPE_SWITCH = 49, //!< The Switch Component - COMPONENT_TYPE_ZONE_CONTROL = 50, //!< The ZoneControl Component - COMPONENT_TYPE_PACKAGE = 53, //!< The Package Component - COMPONENT_TYPE_PLAYER_FLAG = 58, //!< The PlayerFlag Component - COMPONENT_TYPE_BASE_COMBAT_AI = 60, //!< The BaseCombatAI Component - COMPONENT_TYPE_MODULE_ASSEMBLY = 61, //!< The ModuleAssembly Component - COMPONENT_TYPE_PROPERTY_VENDOR = 65, //!< The PropertyVendor Component - COMPONENT_TYPE_ROCKET_LAUNCH = 67, //!< The RocketLaunch Component - COMPONENT_TYPE_RACING_CONTROL = 71, //!< The RacingControl Component - COMPONENT_TYPE_MISSION_OFFER = 73, //!< The MissionOffer Component - COMPONENT_TYPE_EXHIBIT = 75, //!< The Exhibit Component - COMPONENT_TYPE_RACING_STATS = 74, //!< The Racing Stats Component - COMPONENT_TYPE_SOUND_TRIGGER = 77, //!< The Sound Trigger Component - COMPONENT_TYPE_PROXIMITY_MONITOR = 78, //!< The Proximity Monitor Component - COMPONENT_TYPE_MISSION = 84, //!< The Mission Component - COMPONENT_TYPE_ROCKET_LAUNCH_LUP = 97, //!< The LUP Launchpad Componen - COMPONENT_TYPE_RAIL_ACTIVATOR = 104, - COMPONENT_TYPE_POSSESSABLE = 108, //!< The Possessable Component - COMPONENT_TYPE_LEVEL_PROGRESSION = 109, //!< The Level Progression Component - COMPONENT_TYPE_POSSESSOR = 110, //!< The Possessor Component - COMPONENT_TYPE_BUILD_BORDER = 114, //!< The Build Border Component - COMPONENT_TYPE_DESTROYABLE = 1000, //!< The Destroyable Component + COMPONENT_TYPE_CONTROLLABLE_PHYSICS = 1, //!< The ControllablePhysics Component + COMPONENT_TYPE_RENDER = 2, //!< The Render Component + COMPONENT_TYPE_SIMPLE_PHYSICS = 3, //!< The SimplePhysics Component + COMPONENT_TYPE_CHARACTER = 4, //!< The Character Component + COMPONENT_TYPE_SCRIPT = 5, //!< The Script Component + COMPONENT_TYPE_BOUNCER = 6, //!< The Bouncer Component + COMPONENT_TYPE_BUFF = 7, //!< The Buff Component + COMPONENT_TYPE_SKILL = 9, //!< The Skill Component + COMPONENT_TYPE_ITEM = 11, //!< The Item Component + COMPONENT_TYPE_VENDOR = 16, //!< The Vendor Component + COMPONENT_TYPE_INVENTORY = 17, //!< The Inventory Component + COMPONENT_TYPE_SHOOTING_GALLERY = 19, //!< The Shooting Gallery Component + COMPONENT_TYPE_RIGID_BODY_PHANTOM_PHYSICS = 20, //!< The RigidBodyPhantomPhysics Component + COMPONENT_TYPE_COLLECTIBLE = 23, //!< The Collectible Component + COMPONENT_TYPE_MOVING_PLATFORM = 25, //!< The MovingPlatform Component + COMPONENT_TYPE_PET = 26, //!< The Pet Component + COMPONENT_TYPE_VEHICLE_PHYSICS = 30, //!< The VehiclePhysics Component + COMPONENT_TYPE_MOVEMENT_AI = 31, //!< The MovementAI Component + COMPONENT_TYPE_PROPERTY = 36, //!< The Property Component + COMPONENT_TYPE_SCRIPTED_ACTIVITY = 39, //!< The ScriptedActivity Component + COMPONENT_TYPE_PHANTOM_PHYSICS = 40, //!< The PhantomPhysics Component + COMPONENT_TYPE_MODEL = 42, //!< The Model Component + COMPONENT_TYPE_PROPERTY_ENTRANCE = 43, //!< The PhantomPhysics Component + COMPONENT_TYPE_PROPERTY_MANAGEMENT = 45, //!< The PropertyManagement Component + COMPONENT_TYPE_REBUILD = 48, //!< The Rebuild Component + COMPONENT_TYPE_SWITCH = 49, //!< The Switch Component + COMPONENT_TYPE_ZONE_CONTROL = 50, //!< The ZoneControl Component + COMPONENT_TYPE_PACKAGE = 53, //!< The Package Component + COMPONENT_TYPE_PLAYER_FLAG = 58, //!< The PlayerFlag Component + COMPONENT_TYPE_BASE_COMBAT_AI = 60, //!< The BaseCombatAI Component + COMPONENT_TYPE_MODULE_ASSEMBLY = 61, //!< The ModuleAssembly Component + COMPONENT_TYPE_PROPERTY_VENDOR = 65, //!< The PropertyVendor Component + COMPONENT_TYPE_ROCKET_LAUNCH = 67, //!< The RocketLaunch Component + COMPONENT_TYPE_RACING_CONTROL = 71, //!< The RacingControl Component + COMPONENT_TYPE_MISSION_OFFER = 73, //!< The MissionOffer Component + COMPONENT_TYPE_EXHIBIT = 75, //!< The Exhibit Component + COMPONENT_TYPE_RACING_STATS = 74, //!< The Racing Stats Component + COMPONENT_TYPE_SOUND_TRIGGER = 77, //!< The Sound Trigger Component + COMPONENT_TYPE_PROXIMITY_MONITOR = 78, //!< The Proximity Monitor Component + COMPONENT_TYPE_MISSION = 84, //!< The Mission Component + COMPONENT_TYPE_ROCKET_LAUNCH_LUP = 97, //!< The LUP Launchpad Componen + COMPONENT_TYPE_RAIL_ACTIVATOR = 104, //!< The Rail Activator Component + COMPONENT_TYPE_PLAYER_FORCED_MOVEMENT = 106, //!< The Player Forced Movement Component + COMPONENT_TYPE_POSSESSABLE = 108, //!< The Possessable Component + COMPONENT_TYPE_LEVEL_PROGRESSION = 109, //!< The Level Progression Component + COMPONENT_TYPE_POSSESSOR = 110, //!< The Possessor Component + COMPONENT_TYPE_BUILD_BORDER = 114, //!< The Build Border Component + COMPONENT_TYPE_DESTROYABLE = 1000, //!< The Destroyable Component }; enum class UseItemResponse : uint32_t { diff --git a/dGame/Entity.cpp b/dGame/Entity.cpp index 45287bd8..32fa7d5b 100644 --- a/dGame/Entity.cpp +++ b/dGame/Entity.cpp @@ -29,6 +29,7 @@ #include "BouncerComponent.h" #include "InventoryComponent.h" #include "LevelProgressionComponent.h" +#include "PlayerForcedMovementComponent.h" #include "ScriptComponent.h" #include "SkillComponent.h" #include "SimplePhysicsComponent.h" @@ -436,14 +437,8 @@ void Entity::Initialize() m_Components.insert(std::make_pair(COMPONENT_TYPE_DESTROYABLE, comp)); } - /*if (compRegistryTable->GetByIDAndType(m_TemplateID, COMPONENT_TYPE_DESTROYABLE) > 0 || m_Character) { - DestroyableComponent* comp = new DestroyableComponent(); - if (m_Character) comp->LoadFromXML(m_Character->GetXMLDoc()); - m_Components.push_back(std::make_pair(COMPONENT_TYPE_DESTROYABLE, comp)); - }*/ - if (compRegistryTable->GetByIDAndType(m_TemplateID, COMPONENT_TYPE_CHARACTER) > 0 || m_Character) { - // Character Component always has a possessor and level components + // Character Component always has a possessor, level, and forced movement components m_Components.insert(std::make_pair(COMPONENT_TYPE_POSSESSOR, new PossessorComponent(this))); // load in the xml for the level @@ -451,6 +446,8 @@ void Entity::Initialize() levelComp->LoadFromXml(m_Character->GetXMLDoc()); m_Components.insert(std::make_pair(COMPONENT_TYPE_LEVEL_PROGRESSION, levelComp)); + m_Components.insert(std::make_pair(COMPONENT_TYPE_PLAYER_FORCED_MOVEMENT, new PlayerForcedMovementComponent(this))); + CharacterComponent* comp = new CharacterComponent(this, m_Character); m_Components.insert(std::make_pair(COMPONENT_TYPE_CHARACTER, comp)); } @@ -1103,6 +1100,14 @@ void Entity::WriteComponents(RakNet::BitStream* outBitStream, eReplicaPacketType outBitStream->Write0(); } + PlayerForcedMovementComponent* playerForcedMovementComponent; + if (TryGetComponent(COMPONENT_TYPE_PLAYER_FORCED_MOVEMENT, playerForcedMovementComponent)) { + playerForcedMovementComponent->Serialize(outBitStream, bIsInitialUpdate, flags); + } else { + // Should never happen, but just to be safe + outBitStream->Write0(); + } + characterComponent->Serialize(outBitStream, bIsInitialUpdate, flags); } diff --git a/dGame/dComponents/CMakeLists.txt b/dGame/dComponents/CMakeLists.txt index ebf93dde..0995428b 100644 --- a/dGame/dComponents/CMakeLists.txt +++ b/dGame/dComponents/CMakeLists.txt @@ -17,6 +17,7 @@ set(DGAME_DCOMPONENTS_SOURCES "BaseCombatAIComponent.cpp" "MovingPlatformComponent.cpp" "PetComponent.cpp" "PhantomPhysicsComponent.cpp" + "PlayerForcedMovementComponent.cpp" "PossessableComponent.cpp" "PossessorComponent.cpp" "PropertyComponent.cpp" diff --git a/dGame/dComponents/PlayerForcedMovementComponent.cpp b/dGame/dComponents/PlayerForcedMovementComponent.cpp new file mode 100644 index 00000000..94b79188 --- /dev/null +++ b/dGame/dComponents/PlayerForcedMovementComponent.cpp @@ -0,0 +1,16 @@ +#include "PlayerForcedMovementComponent.h" + +PlayerForcedMovementComponent::PlayerForcedMovementComponent(Entity* parent) : Component(parent) { + m_Parent = parent; +} + +PlayerForcedMovementComponent::~PlayerForcedMovementComponent() {} + +void PlayerForcedMovementComponent::Serialize(RakNet::BitStream* outBitStream, bool bIsInitialUpdate, unsigned int& flags){ + outBitStream->Write(m_DirtyInfo); + if (m_DirtyInfo) { + outBitStream->Write(m_PlayerOnRail); + outBitStream->Write(m_ShowBillboard); + } + m_DirtyInfo = false; +} \ No newline at end of file diff --git a/dGame/dComponents/PlayerForcedMovementComponent.h b/dGame/dComponents/PlayerForcedMovementComponent.h new file mode 100644 index 00000000..5745a42f --- /dev/null +++ b/dGame/dComponents/PlayerForcedMovementComponent.h @@ -0,0 +1,70 @@ +#pragma once + +#include "Entity.h" +#include "GameMessages.h" +#include "Component.h" + +/** + * Component that handles player forced movement + * + */ +class PlayerForcedMovementComponent : public Component { +public: + static const uint32_t ComponentType = eReplicaComponentType::COMPONENT_TYPE_PLAYER_FORCED_MOVEMENT; + + /** + * Constructor for this component + * @param parent parent that contains this component + */ + PlayerForcedMovementComponent(Entity* parent); + ~PlayerForcedMovementComponent() override; + + void Serialize(RakNet::BitStream* outBitStream, bool bIsInitialUpdate, unsigned int& flags); + + /** + * @brief Set the Player On Rail object + * + * @param value if the player is on a rail + */ + void SetPlayerOnRail(bool value){ m_PlayerOnRail = value; m_DirtyInfo = true; } + + /** + * @brief Set the Show Billboard object + * + * @param value if the billboard should be shown + */ + void SetShowBillboard(bool value){ m_ShowBillboard = value; m_DirtyInfo = true; } + + /** + * @brief Get the Player On Rail object + * + * @return true + * @return false + */ + + /** + * @brief Get the Player On Rail object + * + * @return true + * @return false + */ + bool GetPlayerOnRail(){ return m_PlayerOnRail; } + bool GetShowBillboard(){ return m_ShowBillboard; } + +private: + /** + * whether the info is dirty + */ + bool m_DirtyInfo = false; + + /** + * whether the player is on a rail + */ + bool m_PlayerOnRail = false; + + /** + * whether the billboard should be showing + */ + bool m_ShowBillboard = false; + +}; From 9ed4a4f47fe45fe7b3aa2b80fd10be3d93c4765a Mon Sep 17 00:00:00 2001 From: Aaron Kimbrell Date: Sun, 24 Jul 2022 16:17:01 -0500 Subject: [PATCH 19/86] Remove uneeded include (#674) --- dGame/dComponents/CharacterComponent.cpp | 1 - dGame/dComponents/PlayerForcedMovementComponent.h | 1 - 2 files changed, 2 deletions(-) diff --git a/dGame/dComponents/CharacterComponent.cpp b/dGame/dComponents/CharacterComponent.cpp index a1eb3c62..c7078f42 100644 --- a/dGame/dComponents/CharacterComponent.cpp +++ b/dGame/dComponents/CharacterComponent.cpp @@ -79,7 +79,6 @@ CharacterComponent::~CharacterComponent() { } void CharacterComponent::Serialize(RakNet::BitStream* outBitStream, bool bIsInitialUpdate, unsigned int& flags) { - outBitStream->Write0(); if (bIsInitialUpdate) { outBitStream->Write0(); diff --git a/dGame/dComponents/PlayerForcedMovementComponent.h b/dGame/dComponents/PlayerForcedMovementComponent.h index 5745a42f..d023155c 100644 --- a/dGame/dComponents/PlayerForcedMovementComponent.h +++ b/dGame/dComponents/PlayerForcedMovementComponent.h @@ -1,7 +1,6 @@ #pragma once #include "Entity.h" -#include "GameMessages.h" #include "Component.h" /** From a7fb6eb3f3108f2cf64b0f2bacd64733e2c6c971 Mon Sep 17 00:00:00 2001 From: Aaron Kimbrell Date: Sun, 24 Jul 2022 21:03:22 -0500 Subject: [PATCH 20/86] make LoadFromXml usage consistent across comps (#673) --- dGame/Entity.cpp | 9 +++++---- dGame/dComponents/BuffComponent.cpp | 2 +- dGame/dComponents/BuffComponent.h | 2 +- dGame/dComponents/CharacterComponent.cpp | 9 +-------- dGame/dComponents/CharacterComponent.h | 2 +- dGame/dComponents/ControllablePhysicsComponent.cpp | 2 +- dGame/dComponents/ControllablePhysicsComponent.h | 2 +- dGame/dComponents/DestroyableComponent.cpp | 4 ++-- dGame/dComponents/DestroyableComponent.h | 2 +- dGame/dComponents/LevelProgressionComponent.h | 1 - 10 files changed, 14 insertions(+), 21 deletions(-) diff --git a/dGame/Entity.cpp b/dGame/Entity.cpp index 32fa7d5b..fbb61437 100644 --- a/dGame/Entity.cpp +++ b/dGame/Entity.cpp @@ -252,7 +252,7 @@ void Entity::Initialize() ControllablePhysicsComponent* controllablePhysics = new ControllablePhysicsComponent(this); if (m_Character) { - controllablePhysics->LoadFromXML(m_Character->GetXMLDoc()); + controllablePhysics->LoadFromXml(m_Character->GetXMLDoc()); const auto mapID = Game::server->GetZoneID(); @@ -362,7 +362,7 @@ void Entity::Initialize() if (buffComponentID > 0 || collectibleComponentID > 0) { DestroyableComponent* comp = new DestroyableComponent(this); if (m_Character) { - comp->LoadFromXML(m_Character->GetXMLDoc()); + comp->LoadFromXml(m_Character->GetXMLDoc()); } else { if (componentID > 0) { @@ -448,8 +448,9 @@ void Entity::Initialize() m_Components.insert(std::make_pair(COMPONENT_TYPE_PLAYER_FORCED_MOVEMENT, new PlayerForcedMovementComponent(this))); - CharacterComponent* comp = new CharacterComponent(this, m_Character); - m_Components.insert(std::make_pair(COMPONENT_TYPE_CHARACTER, comp)); + CharacterComponent* charComp = new CharacterComponent(this, m_Character); + charComp->LoadFromXml(m_Character->GetXMLDoc()); + m_Components.insert(std::make_pair(COMPONENT_TYPE_CHARACTER, charComp)); } if (compRegistryTable->GetByIDAndType(m_TemplateID, COMPONENT_TYPE_INVENTORY) > 0 || m_Character) { diff --git a/dGame/dComponents/BuffComponent.cpp b/dGame/dComponents/BuffComponent.cpp index 9c12e87d..dcc74214 100644 --- a/dGame/dComponents/BuffComponent.cpp +++ b/dGame/dComponents/BuffComponent.cpp @@ -289,7 +289,7 @@ Entity* BuffComponent::GetParent() const return m_Parent; } -void BuffComponent::LoadFromXML(tinyxml2::XMLDocument* doc) +void BuffComponent::LoadFromXml(tinyxml2::XMLDocument* doc) { // Load buffs auto* dest = doc->FirstChildElement("obj")->FirstChildElement("dest"); diff --git a/dGame/dComponents/BuffComponent.h b/dGame/dComponents/BuffComponent.h index ba22c08b..49d7fec4 100644 --- a/dGame/dComponents/BuffComponent.h +++ b/dGame/dComponents/BuffComponent.h @@ -49,7 +49,7 @@ public: Entity* GetParent() const; - void LoadFromXML(tinyxml2::XMLDocument* doc); + void LoadFromXml(tinyxml2::XMLDocument* doc) override; void UpdateXml(tinyxml2::XMLDocument* doc) override; diff --git a/dGame/dComponents/CharacterComponent.cpp b/dGame/dComponents/CharacterComponent.cpp index c7078f42..f854c2b8 100644 --- a/dGame/dComponents/CharacterComponent.cpp +++ b/dGame/dComponents/CharacterComponent.cpp @@ -37,8 +37,6 @@ CharacterComponent::CharacterComponent(Entity* parent, Character* character) : C m_CountryCode = 0; m_LastUpdateTimestamp = std::time(nullptr); - LoadFromXML(); - //Check to see if we're landing: if (character->GetZoneID() != Game::server->GetZoneID()) { m_IsLanding = true; @@ -184,12 +182,7 @@ void CharacterComponent::SetGMLevel(int gmlevel) { m_GMLevel = gmlevel; } -void CharacterComponent::LoadFromXML() { - if (!m_Character) return; - - tinyxml2::XMLDocument* doc = m_Character->GetXMLDoc(); - if (!doc) return; - +void CharacterComponent::LoadFromXml(tinyxml2::XMLDocument* doc) { tinyxml2::XMLElement* character = doc->FirstChildElement("obj")->FirstChildElement("char"); if (!character) { Game::logger->Log("CharacterComponent", "Failed to find char tag while loading XML!\n"); diff --git a/dGame/dComponents/CharacterComponent.h b/dGame/dComponents/CharacterComponent.h index 83b67a17..cd5809f0 100644 --- a/dGame/dComponents/CharacterComponent.h +++ b/dGame/dComponents/CharacterComponent.h @@ -64,7 +64,7 @@ public: CharacterComponent(Entity* parent, Character* character); ~CharacterComponent() override; - void LoadFromXML(); + void LoadFromXml(tinyxml2::XMLDocument* doc) override; void UpdateXml(tinyxml2::XMLDocument* doc) override; void Serialize(RakNet::BitStream* outBitStream, bool bIsInitialUpdate, unsigned int& flags); diff --git a/dGame/dComponents/ControllablePhysicsComponent.cpp b/dGame/dComponents/ControllablePhysicsComponent.cpp index 648b1471..5d9cdd40 100644 --- a/dGame/dComponents/ControllablePhysicsComponent.cpp +++ b/dGame/dComponents/ControllablePhysicsComponent.cpp @@ -130,7 +130,7 @@ void ControllablePhysicsComponent::Serialize(RakNet::BitStream* outBitStream, bo if (!bIsInitialUpdate) outBitStream->Write0(); } -void ControllablePhysicsComponent::LoadFromXML(tinyxml2::XMLDocument* doc) { +void ControllablePhysicsComponent::LoadFromXml(tinyxml2::XMLDocument* doc) { tinyxml2::XMLElement* character = doc->FirstChildElement("obj")->FirstChildElement("char"); if (!character) { Game::logger->Log("ControllablePhysicsComponent", "Failed to find char tag!\n"); diff --git a/dGame/dComponents/ControllablePhysicsComponent.h b/dGame/dComponents/ControllablePhysicsComponent.h index c7acec62..73b3bb69 100644 --- a/dGame/dComponents/ControllablePhysicsComponent.h +++ b/dGame/dComponents/ControllablePhysicsComponent.h @@ -25,7 +25,7 @@ public: void Update(float deltaTime) override; void Serialize(RakNet::BitStream* outBitStream, bool bIsInitialUpdate, unsigned int& flags); - void LoadFromXML(tinyxml2::XMLDocument* doc); + void LoadFromXml(tinyxml2::XMLDocument* doc) override; void ResetFlags(); void UpdateXml(tinyxml2::XMLDocument* doc) override; diff --git a/dGame/dComponents/DestroyableComponent.cpp b/dGame/dComponents/DestroyableComponent.cpp index efcfb5cb..e7a6d385 100644 --- a/dGame/dComponents/DestroyableComponent.cpp +++ b/dGame/dComponents/DestroyableComponent.cpp @@ -159,7 +159,7 @@ void DestroyableComponent::Serialize(RakNet::BitStream* outBitStream, bool bIsIn } } -void DestroyableComponent::LoadFromXML(tinyxml2::XMLDocument* doc) { +void DestroyableComponent::LoadFromXml(tinyxml2::XMLDocument* doc) { tinyxml2::XMLElement* dest = doc->FirstChildElement("obj")->FirstChildElement("dest"); if (!dest) { Game::logger->Log("DestroyableComponent", "Failed to find dest tag!\n"); @@ -169,7 +169,7 @@ void DestroyableComponent::LoadFromXML(tinyxml2::XMLDocument* doc) { auto* buffComponent = m_Parent->GetComponent(); if (buffComponent != nullptr) { - buffComponent->LoadFromXML(doc); + buffComponent->LoadFromXml(doc); } dest->QueryAttribute("hc", &m_iHealth); diff --git a/dGame/dComponents/DestroyableComponent.h b/dGame/dComponents/DestroyableComponent.h index ade3f4e8..9d2b228f 100644 --- a/dGame/dComponents/DestroyableComponent.h +++ b/dGame/dComponents/DestroyableComponent.h @@ -19,7 +19,7 @@ public: ~DestroyableComponent() override; void Serialize(RakNet::BitStream* outBitStream, bool bIsInitialUpdate, uint32_t& flags); - void LoadFromXML(tinyxml2::XMLDocument* doc); + void LoadFromXml(tinyxml2::XMLDocument* doc) override; void UpdateXml(tinyxml2::XMLDocument* doc) override; /** diff --git a/dGame/dComponents/LevelProgressionComponent.h b/dGame/dComponents/LevelProgressionComponent.h index ead3edfb..53f6693e 100644 --- a/dGame/dComponents/LevelProgressionComponent.h +++ b/dGame/dComponents/LevelProgressionComponent.h @@ -17,7 +17,6 @@ public: * @param parent parent that contains this component */ LevelProgressionComponent(Entity* parent); - ~LevelProgressionComponent() override {}; void Serialize(RakNet::BitStream* outBitStream, bool bIsInitialUpdate, unsigned int& flags); From e97ae92624c436f118a36c60c4a2b8bcc456617d Mon Sep 17 00:00:00 2001 From: Aaron Kimbrell Date: Sun, 24 Jul 2022 21:26:51 -0500 Subject: [PATCH 21/86] Make logger automatically put a newline (#675) at the end of the line remove all the newlines in log calls --- dAuthServer/AuthServer.cpp | 12 +- dChatServer/ChatPacketHandler.cpp | 66 ++++---- dChatServer/ChatServer.cpp | 24 +-- dChatServer/PlayerContainer.cpp | 56 +++---- dCommon/dLogger.cpp | 6 +- dDatabase/Database.cpp | 12 +- dDatabase/MigrationRunner.cpp | 8 +- dDatabase/Tables/CDSkillBehaviorTable.cpp | 6 +- dGame/Character.cpp | 136 ++++++++-------- dGame/Player.cpp | 30 ++-- dGame/TradingManager.cpp | 60 +++---- dGame/User.cpp | 24 +-- dGame/UserManager.cpp | 150 +++++++++--------- dGame/dBehaviors/AreaOfEffectBehavior.cpp | 14 +- dGame/dBehaviors/BasicAttackBehavior.cpp | 10 +- dGame/dBehaviors/Behavior.cpp | 10 +- dGame/dBehaviors/BehaviorContext.cpp | 40 ++--- dGame/dBehaviors/BlockBehavior.cpp | 4 +- dGame/dBehaviors/BuffBehavior.cpp | 14 +- dGame/dBehaviors/CarBoostBehavior.cpp | 8 +- dGame/dBehaviors/DamageAbsorptionBehavior.cpp | 10 +- dGame/dBehaviors/DamageReductionBehavior.cpp | 10 +- dGame/dBehaviors/HealBehavior.cpp | 6 +- dGame/dBehaviors/ImmunityBehavior.cpp | 8 +- dGame/dBehaviors/MovementSwitchBehavior.cpp | 8 +- dGame/dBehaviors/ProjectileAttackBehavior.cpp | 16 +- dGame/dBehaviors/RepairBehavior.cpp | 6 +- dGame/dBehaviors/SpawnBehavior.cpp | 14 +- dGame/dBehaviors/StunBehavior.cpp | 12 +- dGame/dBehaviors/SwitchBehavior.cpp | 12 +- dGame/dBehaviors/TacArcBehavior.cpp | 16 +- dGame/dBehaviors/TauntBehavior.cpp | 8 +- dGame/dBehaviors/VerifyBehavior.cpp | 4 +- dGame/dComponents/BaseCombatAIComponent.cpp | 48 +++--- dGame/dComponents/BouncerComponent.cpp | 18 +-- dGame/dComponents/BuffComponent.cpp | 40 ++--- dGame/dComponents/BuildBorderComponent.cpp | 6 +- dGame/dComponents/CharacterComponent.cpp | 31 ++-- .../ControllablePhysicsComponent.cpp | 10 +- dGame/dComponents/DestroyableComponent.cpp | 16 +- dGame/dComponents/InventoryComponent.cpp | 46 +++--- .../dComponents/LevelProgressionComponent.cpp | 4 +- dGame/dComponents/MissionComponent.cpp | 14 +- dGame/dComponents/MissionOfferComponent.cpp | 26 +-- dGame/dComponents/MovingPlatformComponent.cpp | 40 ++--- dGame/dComponents/PetComponent.cpp | 94 +++++------ dGame/dComponents/PhantomPhysicsComponent.cpp | 24 +-- .../dComponents/PropertyEntranceComponent.cpp | 8 +- .../PropertyManagementComponent.cpp | 74 ++++----- dGame/dComponents/PropertyVendorComponent.cpp | 10 +- dGame/dComponents/RacingControlComponent.cpp | 22 +-- dGame/dComponents/RebuildComponent.cpp | 26 +-- .../RocketLaunchpadControlComponent.cpp | 4 +- .../dComponents/ScriptedActivityComponent.cpp | 16 +- dGame/dComponents/SkillComponent.cpp | 10 +- dGame/dGameMessages/GameMessageHandler.cpp | 60 +++---- dGame/dGameMessages/GameMessages.cpp | 86 +++++----- dGame/dInventory/Inventory.cpp | 36 ++--- dGame/dInventory/Item.cpp | 50 +++--- dGame/dMission/Mission.cpp | 4 +- dGame/dMission/MissionTask.cpp | 44 ++--- dGame/dUtilities/Mail.cpp | 8 +- dGame/dUtilities/Preconditions.cpp | 2 +- dGame/dUtilities/SlashCommandHandler.cpp | 20 +-- dGame/dUtilities/VanityUtilities.cpp | 34 ++-- dMasterServer/InstanceManager.cpp | 52 +++--- dMasterServer/MasterServer.cpp | 88 +++++----- dMasterServer/ObjectIDManager.cpp | 4 +- dNet/AuthPackets.cpp | 74 ++++----- dNet/ClientPackets.cpp | 10 +- dNet/WorldPackets.cpp | 36 ++--- dNet/dServer.cpp | 14 +- dPhysics/dpWorld.cpp | 22 +-- dScripts/ActivityManager.cpp | 10 +- dScripts/AgJetEffectServer.cpp | 10 +- dScripts/BaseRandomServer.cpp | 28 ++-- dScripts/BossSpiderQueenEnemyServer.cpp | 138 ++++++++-------- dScripts/CppScripts.cpp | 2 +- dScripts/FlameJetServer.cpp | 8 +- dScripts/FvMaelstromDragon.cpp | 12 +- dScripts/NjMonastryBossInstance.cpp | 4 +- dScripts/SGCannon.cpp | 70 ++++---- dWorldServer/WorldServer.cpp | 94 ++++++----- dZoneManager/Level.cpp | 20 ++- dZoneManager/Zone.cpp | 36 ++--- dZoneManager/dZoneManager.cpp | 18 +-- 86 files changed, 1249 insertions(+), 1252 deletions(-) diff --git a/dAuthServer/AuthServer.cpp b/dAuthServer/AuthServer.cpp index fef3124b..f5c85c3f 100644 --- a/dAuthServer/AuthServer.cpp +++ b/dAuthServer/AuthServer.cpp @@ -37,9 +37,9 @@ int main(int argc, char** argv) { //Create all the objects we need to run our service: Game::logger = SetupLogger(); if (!Game::logger) return 0; - Game::logger->Log("AuthServer", "Starting Auth server...\n"); - Game::logger->Log("AuthServer", "Version: %i.%i\n", PROJECT_VERSION_MAJOR, PROJECT_VERSION_MINOR); - Game::logger->Log("AuthServer", "Compiled on: %s\n", __TIMESTAMP__); + Game::logger->Log("AuthServer", "Starting Auth server..."); + Game::logger->Log("AuthServer", "Version: %i.%i", PROJECT_VERSION_MAJOR, PROJECT_VERSION_MINOR); + Game::logger->Log("AuthServer", "Compiled on: %s", __TIMESTAMP__); //Read our config: dConfig config("authconfig.ini"); @@ -56,7 +56,7 @@ int main(int argc, char** argv) { try { Database::Connect(mysql_host, mysql_database, mysql_username, mysql_password); } catch (sql::SQLException& ex) { - Game::logger->Log("AuthServer", "Got an error while connecting to the database: %s\n", ex.what()); + Game::logger->Log("AuthServer", "Got an error while connecting to the database: %s", ex.what()); Database::Destroy("AuthServer"); delete Game::server; delete Game::logger; @@ -78,10 +78,10 @@ int main(int argc, char** argv) { //It's safe to pass 'localhost' here, as the IP is only used as the external IP. int maxClients = 50; - int ourPort = 1001; //LU client is hardcoded to use this for auth port, so I'm making it the default. + int ourPort = 1001; //LU client is hardcoded to use this for auth port, so I'm making it the default. if (config.GetValue("max_clients") != "") maxClients = std::stoi(config.GetValue("max_clients")); if (config.GetValue("port") != "") ourPort = std::atoi(config.GetValue("port").c_str()); - + Game::server = new dServer(config.GetValue("external_ip"), ourPort, 0, maxClients, false, true, Game::logger, masterIP, masterPort, ServerType::Auth); //Run it until server gets a kill message from Master: diff --git a/dChatServer/ChatPacketHandler.cpp b/dChatServer/ChatPacketHandler.cpp index 4f055121..213e1948 100644 --- a/dChatServer/ChatPacketHandler.cpp +++ b/dChatServer/ChatPacketHandler.cpp @@ -79,7 +79,7 @@ void ChatPacketHandler::HandleFriendlistRequest(Packet* packet) { bitStream.Write(0); bitStream.Write(1); //Length of packet -- just writing one as it doesn't matter, client skips it. bitStream.Write((uint16_t)friends.size()); - + for (auto& data : friends) { data.Serialize(bitStream); } @@ -139,7 +139,7 @@ void ChatPacketHandler::HandleFriendRequest(Packet* packet) { } } - // If at this point we dont have a target, then they arent online and we cant send the request. + // If at this point we dont have a target, then they arent online and we cant send the request. // Send the response code that corresponds to what the error is. if (!requestee) { std::unique_ptr nameQuery(Database::CreatePreppedStmt("SELECT name from charinfo where name = ?;")); @@ -232,7 +232,7 @@ void ChatPacketHandler::HandleFriendRequest(Packet* packet) { // Do not send this if we are requesting to be a best friend. SendFriendRequest(requestee.get(), requestor); } - + // If the player is actually a player and not a ghost one defined above, release it from being deleted. if (requestee->sysAddr != UNASSIGNED_SYSTEM_ADDRESS) requestee.release(); } @@ -301,7 +301,7 @@ void ChatPacketHandler::HandleFriendResponse(Packet* packet) { requesteeData.isFTP = false; requesteeData.isOnline = true; requestor->friends.push_back(requesteeData); - + std::unique_ptr statement(Database::CreatePreppedStmt("INSERT IGNORE INTO `friends` (`player_id`, `friend_id`, `best_friend`) VALUES (?,?,?);")); statement->setUInt(1, static_cast(requestor->playerID)); statement->setUInt(2, static_cast(requestee->playerID)); @@ -371,7 +371,7 @@ void ChatPacketHandler::HandleRemoveFriend(Packet* packet) { SendRemoveFriend(goonB, goonAName, true); } -void ChatPacketHandler::HandleChatMessage(Packet* packet) +void ChatPacketHandler::HandleChatMessage(Packet* packet) { CINSTREAM; LWOOBJID playerID = LWOOBJID_EMPTY; @@ -390,10 +390,10 @@ void ChatPacketHandler::HandleChatMessage(Packet* packet) uint8_t channel = 0; inStream.Read(channel); - + std::string message = PacketUtils::ReadString(0x66, packet, true); - Game::logger->Log("ChatPacketHandler", "Got a message from (%s) [%d]: %s\n", senderName.c_str(), channel, message.c_str()); + Game::logger->Log("ChatPacketHandler", "Got a message from (%s) [%d]: %s", senderName.c_str(), channel, message.c_str()); if (channel != 8) return; @@ -530,16 +530,16 @@ void ChatPacketHandler::HandleTeamInvite(Packet* packet) if (team->memberIDs.size() > 3) { // no more teams greater than 4 - Game::logger->Log("ChatPacketHandler", "Someone tried to invite a 5th player to a team\n"); + Game::logger->Log("ChatPacketHandler", "Someone tried to invite a 5th player to a team"); return; } SendTeamInvite(other, player); - Game::logger->Log("ChatPacketHandler", "Got team invite: %llu -> %s\n", playerID, invitedPlayer.c_str()); + Game::logger->Log("ChatPacketHandler", "Got team invite: %llu -> %s", playerID, invitedPlayer.c_str()); } -void ChatPacketHandler::HandleTeamInviteResponse(Packet* packet) +void ChatPacketHandler::HandleTeamInviteResponse(Packet* packet) { CINSTREAM; LWOOBJID playerID = LWOOBJID_EMPTY; @@ -552,7 +552,7 @@ void ChatPacketHandler::HandleTeamInviteResponse(Packet* packet) LWOOBJID leaderID = LWOOBJID_EMPTY; inStream.Read(leaderID); - Game::logger->Log("ChatPacketHandler", "Accepted invite: %llu -> %llu (%d)\n", playerID, leaderID, declined); + Game::logger->Log("ChatPacketHandler", "Accepted invite: %llu -> %llu (%d)", playerID, leaderID, declined); if (declined) { @@ -563,21 +563,21 @@ void ChatPacketHandler::HandleTeamInviteResponse(Packet* packet) if (team == nullptr) { - Game::logger->Log("ChatPacketHandler", "Failed to find team for leader (%llu)\n", leaderID); + Game::logger->Log("ChatPacketHandler", "Failed to find team for leader (%llu)", leaderID); team = playerContainer.GetTeam(playerID); } - + if (team == nullptr) { - Game::logger->Log("ChatPacketHandler", "Failed to find team for player (%llu)\n", playerID); + Game::logger->Log("ChatPacketHandler", "Failed to find team for player (%llu)", playerID); return; } playerContainer.AddMember(team, playerID); } -void ChatPacketHandler::HandleTeamLeave(Packet* packet) +void ChatPacketHandler::HandleTeamLeave(Packet* packet) { CINSTREAM; LWOOBJID playerID = LWOOBJID_EMPTY; @@ -588,7 +588,7 @@ void ChatPacketHandler::HandleTeamLeave(Packet* packet) auto* team = playerContainer.GetTeam(playerID); - Game::logger->Log("ChatPacketHandler", "(%llu) leaving team\n", playerID); + Game::logger->Log("ChatPacketHandler", "(%llu) leaving team", playerID); if (team != nullptr) { @@ -596,16 +596,16 @@ void ChatPacketHandler::HandleTeamLeave(Packet* packet) } } -void ChatPacketHandler::HandleTeamKick(Packet* packet) +void ChatPacketHandler::HandleTeamKick(Packet* packet) { CINSTREAM; LWOOBJID playerID = LWOOBJID_EMPTY; inStream.Read(playerID); inStream.Read(playerID); - + std::string kickedPlayer = PacketUtils::ReadString(0x14, packet, true); - Game::logger->Log("ChatPacketHandler", "(%llu) kicking (%s) from team\n", playerID, kickedPlayer.c_str()); + Game::logger->Log("ChatPacketHandler", "(%llu) kicking (%s) from team", playerID, kickedPlayer.c_str()); auto* kicked = playerContainer.GetPlayerData(kickedPlayer); @@ -632,16 +632,16 @@ void ChatPacketHandler::HandleTeamKick(Packet* packet) } } -void ChatPacketHandler::HandleTeamPromote(Packet* packet) +void ChatPacketHandler::HandleTeamPromote(Packet* packet) { CINSTREAM; LWOOBJID playerID = LWOOBJID_EMPTY; inStream.Read(playerID); inStream.Read(playerID); - + std::string promotedPlayer = PacketUtils::ReadString(0x14, packet, true); - Game::logger->Log("ChatPacketHandler", "(%llu) promoting (%s) to team leader\n", playerID, promotedPlayer.c_str()); + Game::logger->Log("ChatPacketHandler", "(%llu) promoting (%s) to team leader", playerID, promotedPlayer.c_str()); auto* promoted = playerContainer.GetPlayerData(promotedPlayer); @@ -657,7 +657,7 @@ void ChatPacketHandler::HandleTeamPromote(Packet* packet) } } -void ChatPacketHandler::HandleTeamLootOption(Packet* packet) +void ChatPacketHandler::HandleTeamLootOption(Packet* packet) { CINSTREAM; LWOOBJID playerID = LWOOBJID_EMPTY; @@ -665,7 +665,7 @@ void ChatPacketHandler::HandleTeamLootOption(Packet* packet) inStream.Read(playerID); uint32_t size = 0; inStream.Read(size); - + char option; inStream.Read(option); @@ -678,12 +678,12 @@ void ChatPacketHandler::HandleTeamLootOption(Packet* packet) team->lootFlag = option; playerContainer.TeamStatusUpdate(team); - + playerContainer.UpdateTeamsOnWorld(team, false); } } -void ChatPacketHandler::HandleTeamStatusRequest(Packet* packet) +void ChatPacketHandler::HandleTeamStatusRequest(Packet* packet) { CINSTREAM; LWOOBJID playerID = LWOOBJID_EMPTY; @@ -729,7 +729,7 @@ void ChatPacketHandler::HandleTeamStatusRequest(Packet* packet) if (memberId == playerID) continue; const auto memberName = playerContainer.GetName(memberId); - + if (otherMember != nullptr) { ChatPacketHandler::SendTeamSetOffWorldFlag(otherMember, data->playerID, data->zoneID); @@ -741,7 +741,7 @@ void ChatPacketHandler::HandleTeamStatusRequest(Packet* packet) } } -void ChatPacketHandler::SendTeamInvite(PlayerData* receiver, PlayerData* sender) +void ChatPacketHandler::SendTeamInvite(PlayerData* receiver, PlayerData* sender) { CBITSTREAM; PacketUtils::WriteHeader(bitStream, CHAT_INTERNAL, MSG_CHAT_INTERNAL_ROUTE_TO_PLAYER); @@ -757,7 +757,7 @@ void ChatPacketHandler::SendTeamInvite(PlayerData* receiver, PlayerData* sender) SEND_PACKET; } -void ChatPacketHandler::SendTeamInviteConfirm(PlayerData* receiver, bool bLeaderIsFreeTrial, LWOOBJID i64LeaderID, LWOZONEID i64LeaderZoneID, uint8_t ucLootFlag, uint8_t ucNumOfOtherPlayers, uint8_t ucResponseCode, std::u16string wsLeaderName) +void ChatPacketHandler::SendTeamInviteConfirm(PlayerData* receiver, bool bLeaderIsFreeTrial, LWOOBJID i64LeaderID, LWOZONEID i64LeaderZoneID, uint8_t ucLootFlag, uint8_t ucNumOfOtherPlayers, uint8_t ucResponseCode, std::u16string wsLeaderName) { CBITSTREAM; PacketUtils::WriteHeader(bitStream, CHAT_INTERNAL, MSG_CHAT_INTERNAL_ROUTE_TO_PLAYER); @@ -813,7 +813,7 @@ void ChatPacketHandler::SendTeamStatus(PlayerData* receiver, LWOOBJID i64LeaderI SEND_PACKET; } -void ChatPacketHandler::SendTeamSetLeader(PlayerData* receiver, LWOOBJID i64PlayerID) +void ChatPacketHandler::SendTeamSetLeader(PlayerData* receiver, LWOOBJID i64PlayerID) { CBITSTREAM; PacketUtils::WriteHeader(bitStream, CHAT_INTERNAL, MSG_CHAT_INTERNAL_ROUTE_TO_PLAYER); @@ -831,7 +831,7 @@ void ChatPacketHandler::SendTeamSetLeader(PlayerData* receiver, LWOOBJID i64Play SEND_PACKET; } -void ChatPacketHandler::SendTeamAddPlayer(PlayerData* receiver, bool bIsFreeTrial, bool bLocal, bool bNoLootOnDeath, LWOOBJID i64PlayerID, std::u16string wsPlayerName, LWOZONEID zoneID) +void ChatPacketHandler::SendTeamAddPlayer(PlayerData* receiver, bool bIsFreeTrial, bool bLocal, bool bNoLootOnDeath, LWOOBJID i64PlayerID, std::u16string wsPlayerName, LWOZONEID zoneID) { CBITSTREAM; PacketUtils::WriteHeader(bitStream, CHAT_INTERNAL, MSG_CHAT_INTERNAL_ROUTE_TO_PLAYER); @@ -863,7 +863,7 @@ void ChatPacketHandler::SendTeamAddPlayer(PlayerData* receiver, bool bIsFreeTria SEND_PACKET; } -void ChatPacketHandler::SendTeamRemovePlayer(PlayerData* receiver, bool bDisband, bool bIsKicked, bool bIsLeaving, bool bLocal, LWOOBJID i64LeaderID, LWOOBJID i64PlayerID, std::u16string wsPlayerName) +void ChatPacketHandler::SendTeamRemovePlayer(PlayerData* receiver, bool bDisband, bool bIsKicked, bool bIsLeaving, bool bLocal, LWOOBJID i64LeaderID, LWOOBJID i64PlayerID, std::u16string wsPlayerName) { CBITSTREAM; PacketUtils::WriteHeader(bitStream, CHAT_INTERNAL, MSG_CHAT_INTERNAL_ROUTE_TO_PLAYER); @@ -891,7 +891,7 @@ void ChatPacketHandler::SendTeamRemovePlayer(PlayerData* receiver, bool bDisband SEND_PACKET; } -void ChatPacketHandler::SendTeamSetOffWorldFlag(PlayerData* receiver, LWOOBJID i64PlayerID, LWOZONEID zoneID) +void ChatPacketHandler::SendTeamSetOffWorldFlag(PlayerData* receiver, LWOOBJID i64PlayerID, LWOZONEID zoneID) { CBITSTREAM; PacketUtils::WriteHeader(bitStream, CHAT_INTERNAL, MSG_CHAT_INTERNAL_ROUTE_TO_PLAYER); diff --git a/dChatServer/ChatServer.cpp b/dChatServer/ChatServer.cpp index 9ba3ba1b..639d7b70 100644 --- a/dChatServer/ChatServer.cpp +++ b/dChatServer/ChatServer.cpp @@ -40,9 +40,9 @@ int main(int argc, char** argv) { //Create all the objects we need to run our service: Game::logger = SetupLogger(); if (!Game::logger) return 0; - Game::logger->Log("ChatServer", "Starting Chat server...\n"); - Game::logger->Log("ChatServer", "Version: %i.%i\n", PROJECT_VERSION_MAJOR, PROJECT_VERSION_MINOR); - Game::logger->Log("ChatServer", "Compiled on: %s\n", __TIMESTAMP__); + Game::logger->Log("ChatServer", "Starting Chat server..."); + Game::logger->Log("ChatServer", "Version: %i.%i", PROJECT_VERSION_MAJOR, PROJECT_VERSION_MINOR); + Game::logger->Log("ChatServer", "Compiled on: %s", __TIMESTAMP__); //Read our config: dConfig config("chatconfig.ini"); @@ -60,7 +60,7 @@ int main(int argc, char** argv) { Database::Connect(mysql_host, mysql_database, mysql_username, mysql_password); } catch (sql::SQLException& ex) { - Game::logger->Log("ChatServer", "Got an error while connecting to the database: %s\n", ex.what()); + Game::logger->Log("ChatServer", "Got an error while connecting to the database: %s", ex.what()); Database::Destroy("ChatServer"); delete Game::server; delete Game::logger; @@ -172,11 +172,11 @@ dLogger * SetupLogger() { void HandlePacket(Packet* packet) { if (packet->data[0] == ID_DISCONNECTION_NOTIFICATION || packet->data[0] == ID_CONNECTION_LOST) { - Game::logger->Log("ChatServer", "A server has disconnected, erasing their connected players from the list.\n"); + Game::logger->Log("ChatServer", "A server has disconnected, erasing their connected players from the list."); } if (packet->data[0] == ID_NEW_INCOMING_CONNECTION) { - Game::logger->Log("ChatServer", "A server is connecting, awaiting user list.\n"); + Game::logger->Log("ChatServer", "A server is connecting, awaiting user list."); } if (packet->data[1] == CHAT_INTERNAL) { @@ -205,7 +205,7 @@ void HandlePacket(Packet* packet) { } default: - Game::logger->Log("ChatServer", "Unknown CHAT_INTERNAL id: %i\n", int(packet->data[3])); + Game::logger->Log("ChatServer", "Unknown CHAT_INTERNAL id: %i", int(packet->data[3])); } } @@ -216,7 +216,7 @@ void HandlePacket(Packet* packet) { break; case MSG_CHAT_GET_IGNORE_LIST: - Game::logger->Log("ChatServer", "Asked for ignore list, but is unimplemented right now.\n"); + Game::logger->Log("ChatServer", "Asked for ignore list, but is unimplemented right now."); break; case MSG_CHAT_TEAM_GET_STATUS: @@ -272,21 +272,21 @@ void HandlePacket(Packet* packet) { case MSG_CHAT_TEAM_SET_LOOT: ChatPacketHandler::HandleTeamLootOption(packet); break; - + default: - Game::logger->Log("ChatServer", "Unknown CHAT id: %i\n", int(packet->data[3])); + Game::logger->Log("ChatServer", "Unknown CHAT id: %i", int(packet->data[3])); } } if (packet->data[1] == WORLD) { switch (packet->data[3]) { case MSG_WORLD_CLIENT_ROUTE_PACKET: { - printf("routing packet from world\n"); + Game::logger->Log("ChatServer", "Routing packet from world"); break; } default: - Game::logger->Log("ChatServer", "Unknown World id: %i\n", int(packet->data[3])); + Game::logger->Log("ChatServer", "Unknown World id: %i", int(packet->data[3])); } } } diff --git a/dChatServer/PlayerContainer.cpp b/dChatServer/PlayerContainer.cpp index 1517153d..73a22ba9 100644 --- a/dChatServer/PlayerContainer.cpp +++ b/dChatServer/PlayerContainer.cpp @@ -28,7 +28,7 @@ void PlayerContainer::InsertPlayer(Packet* packet) { for (int i = 0; i < len; i++) { char character; inStream.Read(character); - data->playerName += character; + data->playerName += character; } inStream.Read(data->zoneID); @@ -38,7 +38,7 @@ void PlayerContainer::InsertPlayer(Packet* packet) { mNames[data->playerID] = GeneralUtils::ASCIIToUTF16(std::string(data->playerName.c_str())); mPlayers.insert(std::make_pair(data->playerID, data)); - Game::logger->Log("PlayerContainer", "Added user: %s (%llu), zone: %i\n", data->playerName.c_str(), data->playerID, data->zoneID.GetMapID()); + Game::logger->Log("PlayerContainer", "Added user: %s (%llu), zone: %i", data->playerName.c_str(), data->playerID, data->zoneID.GetMapID()); auto* insertLog = Database::CreatePreppedStmt("INSERT INTO activity_log (character_id, activity, time, map_id) VALUES (?, ?, ?, ?);"); @@ -73,7 +73,7 @@ void PlayerContainer::RemovePlayer(Packet* packet) { if (team != nullptr) { const auto memberName = GeneralUtils::ASCIIToUTF16(std::string(player->playerName.c_str())); - + for (const auto memberId : team->memberIDs) { auto* otherMember = GetPlayerData(memberId); @@ -84,7 +84,7 @@ void PlayerContainer::RemovePlayer(Packet* packet) { } } - Game::logger->Log("PlayerContainer", "Removed user: %llu\n", playerID); + Game::logger->Log("PlayerContainer", "Removed user: %llu", playerID); mPlayers.erase(playerID); auto* insertLog = Database::CreatePreppedStmt("INSERT INTO activity_log (character_id, activity, time, map_id) VALUES (?, ?, ?, ?);"); @@ -97,7 +97,7 @@ void PlayerContainer::RemovePlayer(Packet* packet) { insertLog->executeUpdate(); } -void PlayerContainer::MuteUpdate(Packet* packet) +void PlayerContainer::MuteUpdate(Packet* packet) { CINSTREAM; LWOOBJID playerID; @@ -110,7 +110,7 @@ void PlayerContainer::MuteUpdate(Packet* packet) if (player == nullptr) { - Game::logger->Log("PlayerContainer", "Failed to find user: %llu\n", playerID); + Game::logger->Log("PlayerContainer", "Failed to find user: %llu", playerID); return; } @@ -120,7 +120,7 @@ void PlayerContainer::MuteUpdate(Packet* packet) BroadcastMuteUpdate(playerID, expire); } -void PlayerContainer::CreateTeamServer(Packet* packet) +void PlayerContainer::CreateTeamServer(Packet* packet) { CINSTREAM; LWOOBJID playerID; @@ -143,7 +143,7 @@ void PlayerContainer::CreateTeamServer(Packet* packet) LWOZONEID zoneId; inStream.Read(zoneId); - + auto* team = CreateLocalTeam(members); if (team != nullptr) @@ -154,7 +154,7 @@ void PlayerContainer::CreateTeamServer(Packet* packet) UpdateTeamsOnWorld(team, false); } -void PlayerContainer::BroadcastMuteUpdate(LWOOBJID player, time_t time) +void PlayerContainer::BroadcastMuteUpdate(LWOOBJID player, time_t time) { CBITSTREAM; PacketUtils::WriteHeader(bitStream, CHAT_INTERNAL, MSG_CHAT_INTERNAL_MUTE_UPDATE); @@ -165,7 +165,7 @@ void PlayerContainer::BroadcastMuteUpdate(LWOOBJID player, time_t time) Game::server->Send(&bitStream, UNASSIGNED_SYSTEM_ADDRESS, true); } -TeamData* PlayerContainer::CreateLocalTeam(std::vector members) +TeamData* PlayerContainer::CreateLocalTeam(std::vector members) { if (members.empty()) { @@ -200,14 +200,14 @@ TeamData* PlayerContainer::CreateLocalTeam(std::vector members) return newTeam; } -TeamData* PlayerContainer::CreateTeam(LWOOBJID leader, bool local) +TeamData* PlayerContainer::CreateTeam(LWOOBJID leader, bool local) { auto* team = new TeamData(); - + team->teamID = ++mTeamIDCounter; team->leaderID = leader; team->local = local; - + mTeams.push_back(team); AddMember(team, leader); @@ -215,7 +215,7 @@ TeamData* PlayerContainer::CreateTeam(LWOOBJID leader, bool local) return team; } -TeamData* PlayerContainer::GetTeam(LWOOBJID playerID) +TeamData* PlayerContainer::GetTeam(LWOOBJID playerID) { for (auto* team : mTeams) { @@ -223,11 +223,11 @@ TeamData* PlayerContainer::GetTeam(LWOOBJID playerID) return team; } - + return nullptr; } -void PlayerContainer::AddMember(TeamData* team, LWOOBJID playerID) +void PlayerContainer::AddMember(TeamData* team, LWOOBJID playerID) { const auto index = std::find(team->memberIDs.begin(), team->memberIDs.end(), playerID); @@ -263,7 +263,7 @@ void PlayerContainer::AddMember(TeamData* team, LWOOBJID playerID) if (otherMember == member) continue; const auto otherMemberName = GetName(memberId); - + ChatPacketHandler::SendTeamAddPlayer(member, false, team->local, false, memberId, otherMemberName, otherMember != nullptr ? otherMember->zoneID : LWOZONEID(0, 0, 0)); if (otherMember != nullptr) @@ -273,14 +273,14 @@ void PlayerContainer::AddMember(TeamData* team, LWOOBJID playerID) } } -void PlayerContainer::RemoveMember(TeamData* team, LWOOBJID playerID, bool disband, bool kicked, bool leaving, bool silent) +void PlayerContainer::RemoveMember(TeamData* team, LWOOBJID playerID, bool disband, bool kicked, bool leaving, bool silent) { const auto index = std::find(team->memberIDs.begin(), team->memberIDs.end(), playerID); if (index == team->memberIDs.end()) return; auto* member = GetPlayerData(playerID); - + if (member != nullptr && !silent) { ChatPacketHandler::SendTeamSetLeader(member, LWOOBJID_EMPTY); @@ -319,7 +319,7 @@ void PlayerContainer::RemoveMember(TeamData* team, LWOOBJID playerID, bool disba } } -void PlayerContainer::PromoteMember(TeamData* team, LWOOBJID newLeader) +void PlayerContainer::PromoteMember(TeamData* team, LWOOBJID newLeader) { team->leaderID = newLeader; @@ -333,7 +333,7 @@ void PlayerContainer::PromoteMember(TeamData* team, LWOOBJID newLeader) } } -void PlayerContainer::DisbandTeam(TeamData* team) +void PlayerContainer::DisbandTeam(TeamData* team) { const auto index = std::find(mTeams.begin(), mTeams.end(), team); @@ -350,7 +350,7 @@ void PlayerContainer::DisbandTeam(TeamData* team) ChatPacketHandler::SendTeamSetLeader(otherMember, LWOOBJID_EMPTY); ChatPacketHandler::SendTeamRemovePlayer(otherMember, true, false, false, team->local, team->leaderID, otherMember->playerID, memberName); } - + UpdateTeamsOnWorld(team, true); mTeams.erase(index); @@ -358,7 +358,7 @@ void PlayerContainer::DisbandTeam(TeamData* team) delete team; } -void PlayerContainer::TeamStatusUpdate(TeamData* team) +void PlayerContainer::TeamStatusUpdate(TeamData* team) { const auto index = std::find(mTeams.begin(), mTeams.end(), team); @@ -385,7 +385,7 @@ void PlayerContainer::TeamStatusUpdate(TeamData* team) UpdateTeamsOnWorld(team, false); } -void PlayerContainer::UpdateTeamsOnWorld(TeamData* team, bool deleteTeam) +void PlayerContainer::UpdateTeamsOnWorld(TeamData* team, bool deleteTeam) { CBITSTREAM; PacketUtils::WriteHeader(bitStream, CHAT_INTERNAL, MSG_CHAT_INTERNAL_TEAM_UPDATE); @@ -406,7 +406,7 @@ void PlayerContainer::UpdateTeamsOnWorld(TeamData* team, bool deleteTeam) Game::server->Send(&bitStream, UNASSIGNED_SYSTEM_ADDRESS, true); } -std::u16string PlayerContainer::GetName(LWOOBJID playerID) +std::u16string PlayerContainer::GetName(LWOOBJID playerID) { const auto& pair = mNames.find(playerID); @@ -415,7 +415,7 @@ std::u16string PlayerContainer::GetName(LWOOBJID playerID) return pair->second; } -LWOOBJID PlayerContainer::GetId(const std::u16string& playerName) +LWOOBJID PlayerContainer::GetId(const std::u16string& playerName) { for (const auto& pair : mNames) { @@ -424,11 +424,11 @@ LWOOBJID PlayerContainer::GetId(const std::u16string& playerName) return pair.first; } } - + return LWOOBJID_EMPTY; } -bool PlayerContainer::GetIsMuted(PlayerData* data) +bool PlayerContainer::GetIsMuted(PlayerData* data) { return data->muteExpire == 1 || data->muteExpire > time(NULL); } diff --git a/dCommon/dLogger.cpp b/dCommon/dLogger.cpp index 825c10cb..532a0cee 100644 --- a/dCommon/dLogger.cpp +++ b/dCommon/dLogger.cpp @@ -44,14 +44,14 @@ void dLogger::vLog(const char* format, va_list args) { strftime(timeStr, sizeof(timeStr), "%d-%m-%y %H:%M:%S", time); char message[2048]; vsprintf(message, format, args); - + if (m_logToConsole) { fputs("[", stdout); fputs(timeStr, stdout); fputs("] ", stdout); fputs(message, stdout); } - + if (fp != nullptr) { fputs("[", fp); fputs(timeStr, fp); @@ -76,7 +76,7 @@ void dLogger::LogBasic(const std::string & message) { void dLogger::Log(const char * className, const char * format, ...) { va_list args; - std::string log = "[" + std::string(className) + "] " + std::string(format); + std::string log = "[" + std::string(className) + "] " + std::string(format) + "\n"; va_start(args, format); vLog(log.c_str(), args); va_end(args); diff --git a/dDatabase/Database.cpp b/dDatabase/Database.cpp index 26a45359..7ab7b752 100644 --- a/dDatabase/Database.cpp +++ b/dDatabase/Database.cpp @@ -41,10 +41,10 @@ void Database::Connect() { void Database::Destroy(std::string source, bool log) { if (!con) return; - + if (log) { - if (source != "") Game::logger->Log("Database", "Destroying MySQL connection from %s!\n", source.c_str()); - else Game::logger->Log("Database", "Destroying MySQL connection!\n"); + if (source != "") Game::logger->Log("Database", "Destroying MySQL connection from %s!", source.c_str()); + else Game::logger->Log("Database", "Destroying MySQL connection!"); } con->close(); @@ -63,7 +63,7 @@ sql::PreparedStatement* Database::CreatePreppedStmt(const std::string& query) { if (!con) { Connect(); - Game::logger->Log("Database", "Trying to reconnect to MySQL\n"); + Game::logger->Log("Database", "Trying to reconnect to MySQL"); } if (!con->isValid() || con->isClosed()) @@ -73,9 +73,9 @@ sql::PreparedStatement* Database::CreatePreppedStmt(const std::string& query) { con = nullptr; Connect(); - Game::logger->Log("Database", "Trying to reconnect to MySQL from invalid or closed connection\n"); + Game::logger->Log("Database", "Trying to reconnect to MySQL from invalid or closed connection"); } - + auto* stmt = con->prepareStatement(str); return stmt; diff --git a/dDatabase/MigrationRunner.cpp b/dDatabase/MigrationRunner.cpp index a058b85e..186368fd 100644 --- a/dDatabase/MigrationRunner.cpp +++ b/dDatabase/MigrationRunner.cpp @@ -31,7 +31,7 @@ void MigrationRunner::RunMigrations() { delete stmt; if (doExit) continue; - Game::logger->Log("MigrationRunner", "Running migration: " + migration.name + "\n"); + Game::logger->Log("MigrationRunner", "Running migration: " + migration.name + ""); finalSQL.append(migration.data); finalSQL.append('\n'); @@ -49,7 +49,7 @@ void MigrationRunner::RunMigrations() { delete simpleStatement; } catch (sql::SQLException e) { - Game::logger->Log("MigrationRunner", std::string("Encountered error running migration: ") + e.what() + "\n"); + Game::logger->Log("MigrationRunner", std::string("Encountered error running migration: ") + e.what() + ""); } } } @@ -60,7 +60,7 @@ Migration MigrationRunner::LoadMigration(std::string path) { if (file.is_open()) { std::hash hash; - + std::string line; std::string total = ""; @@ -73,6 +73,6 @@ Migration MigrationRunner::LoadMigration(std::string path) { migration.name = path; migration.data = total; } - + return migration; } diff --git a/dDatabase/Tables/CDSkillBehaviorTable.cpp b/dDatabase/Tables/CDSkillBehaviorTable.cpp index ad79997d..88124161 100644 --- a/dDatabase/Tables/CDSkillBehaviorTable.cpp +++ b/dDatabase/Tables/CDSkillBehaviorTable.cpp @@ -13,9 +13,9 @@ CDSkillBehaviorTable::CDSkillBehaviorTable(void) { tableSize.nextRow(); } - + tableSize.finalize(); - + // Reserve the size //this->entries.reserve(size); @@ -68,7 +68,7 @@ std::vector CDSkillBehaviorTable::Query(std::function data; //So MSVC shuts up return data; } diff --git a/dGame/Character.cpp b/dGame/Character.cpp index ce61ae70..d92f8345 100644 --- a/dGame/Character.cpp +++ b/dGame/Character.cpp @@ -25,9 +25,9 @@ Character::Character(uint32_t id, User* parentUser) { ); stmt->setInt64(1, id); - + sql::ResultSet* res = stmt->executeQuery(); - + while (res->next()) { m_Name = res->getString(1).c_str(); m_UnapprovedName = res->getString(2).c_str(); @@ -35,25 +35,25 @@ Character::Character(uint32_t id, User* parentUser) { m_PropertyCloneID = res->getUInt(4); m_PermissionMap = static_cast(res->getUInt64(5)); } - + delete res; delete stmt; - + //Load the xmlData now: sql::PreparedStatement* xmlStmt = Database::CreatePreppedStmt( "SELECT xml_data FROM charxml WHERE id=? LIMIT 1;" ); xmlStmt->setInt64(1, id); - + sql::ResultSet* xmlRes = xmlStmt->executeQuery(); while (xmlRes->next()) { m_XMLData = xmlRes->getString(1).c_str(); } - + delete xmlRes; delete xmlStmt; - + m_ZoneID = 0; //TEMP! Set back to 0 when done. This is so we can see loading screen progress for testing. m_ZoneInstanceID = 0; //These values don't really matter, these are only used on the char select screen and seem unused. m_ZoneCloneID = 0; @@ -62,12 +62,12 @@ Character::Character(uint32_t id, User* parentUser) { //Quickly and dirtly parse the xmlData to get the info we need: DoQuickXMLDataParse(); - + //Set our objectID: m_ObjectID = m_ID; m_ObjectID = GeneralUtils::SetBit(m_ObjectID, OBJECT_BIT_CHARACTER); m_ObjectID = GeneralUtils::SetBit(m_ObjectID, OBJECT_BIT_PERSISTENT); - + m_ParentUser = parentUser; m_OurEntity = nullptr; m_BuildMode = false; @@ -78,16 +78,16 @@ Character::~Character() { m_Doc = nullptr; } -void Character::UpdateFromDatabase() +void Character::UpdateFromDatabase() { sql::PreparedStatement* stmt = Database::CreatePreppedStmt( "SELECT name, pending_name, needs_rename, prop_clone_id, permission_map FROM charinfo WHERE id=? LIMIT 1;" ); stmt->setInt64(1, m_ID); - + sql::ResultSet* res = stmt->executeQuery(); - + while (res->next()) { m_Name = res->getString(1).c_str(); m_UnapprovedName = res->getString(2).c_str(); @@ -95,24 +95,24 @@ void Character::UpdateFromDatabase() m_PropertyCloneID = res->getUInt(4); m_PermissionMap = static_cast(res->getUInt64(5)); } - + delete res; delete stmt; - + //Load the xmlData now: sql::PreparedStatement* xmlStmt = Database::CreatePreppedStmt( "SELECT xml_data FROM charxml WHERE id=? LIMIT 1;" ); xmlStmt->setInt64(1, m_ID); - + sql::ResultSet* xmlRes = xmlStmt->executeQuery(); while (xmlRes->next()) { m_XMLData = xmlRes->getString(1).c_str(); } - + delete xmlRes; delete xmlStmt; - + m_ZoneID = 0; //TEMP! Set back to 0 when done. This is so we can see loading screen progress for testing. m_ZoneInstanceID = 0; //These values don't really matter, these are only used on the char select screen and seem unused. m_ZoneCloneID = 0; @@ -122,67 +122,67 @@ void Character::UpdateFromDatabase() //Quickly and dirtly parse the xmlData to get the info we need: DoQuickXMLDataParse(); - + //Set our objectID: m_ObjectID = m_ID; m_ObjectID = GeneralUtils::SetBit(m_ObjectID, OBJECT_BIT_CHARACTER); m_ObjectID = GeneralUtils::SetBit(m_ObjectID, OBJECT_BIT_PERSISTENT); - + m_OurEntity = nullptr; m_BuildMode = false; } void Character::DoQuickXMLDataParse() { if (m_XMLData.size() == 0) return; - + delete m_Doc; m_Doc = new tinyxml2::XMLDocument(); if (!m_Doc) return; - + if (m_Doc->Parse(m_XMLData.c_str(), m_XMLData.size()) == 0) { - Game::logger->Log("Character", "Loaded xmlData for character %s (%i)!\n", m_Name.c_str(), m_ID); + Game::logger->Log("Character", "Loaded xmlData for character %s (%i)!", m_Name.c_str(), m_ID); } else { - Game::logger->Log("Character", "Failed to load xmlData!\n"); + Game::logger->Log("Character", "Failed to load xmlData!"); //Server::rakServer->CloseConnection(m_ParentUser->GetSystemAddress(), true); return; } - + tinyxml2::XMLElement* mf = m_Doc->FirstChildElement("obj")->FirstChildElement("mf"); if (!mf) { - Game::logger->Log("Character", "Failed to find mf tag!\n"); + Game::logger->Log("Character", "Failed to find mf tag!"); return; } - + mf->QueryAttribute("hc", &m_HairColor); mf->QueryAttribute("hs", &m_HairStyle); - + mf->QueryAttribute("t", &m_ShirtColor); mf->QueryAttribute("l", &m_PantsColor); - + mf->QueryAttribute("lh", &m_LeftHand); mf->QueryAttribute("rh", &m_RightHand); - + mf->QueryAttribute("es", &m_Eyebrows); mf->QueryAttribute("ess", &m_Eyes); mf->QueryAttribute("ms", &m_Mouth); - + tinyxml2::XMLElement* inv = m_Doc->FirstChildElement("obj")->FirstChildElement("inv"); if (!inv) { - Game::logger->Log("Character", "Char has no inv!\n"); + Game::logger->Log("Character", "Char has no inv!"); return; } - + tinyxml2::XMLElement* bag = inv->FirstChildElement("items")->FirstChildElement("in"); if (!bag) { - Game::logger->Log("Character", "Couldn't find bag0!\n"); + Game::logger->Log("Character", "Couldn't find bag0!"); return; } - + while (bag != nullptr) { auto* sib = bag->FirstChildElement(); - + while (sib != nullptr) { bool eq = false; sib->QueryAttribute("eq", &eq); @@ -198,8 +198,8 @@ void Character::DoQuickXMLDataParse() { bag = bag->NextSiblingElement(); } - - + + tinyxml2::XMLElement* character = m_Doc->FirstChildElement("obj")->FirstChildElement("char"); if (character) { character->QueryAttribute("cc", &m_Coins); @@ -261,7 +261,7 @@ void Character::DoQuickXMLDataParse() { character->QueryAttribute("lzrz", &m_OriginalRotation.z); character->QueryAttribute("lzrw", &m_OriginalRotation.w); } - + auto* flags = m_Doc->FirstChildElement("obj")->FirstChildElement("flag"); if (flags) { auto* currentChild = flags->FirstChildElement(); @@ -269,10 +269,10 @@ void Character::DoQuickXMLDataParse() { uint32_t index = 0; uint64_t value = 0; const auto* temp = currentChild->Attribute("v"); - + index = std::stoul(currentChild->Attribute("id")); value = std::stoull(temp); - + m_PlayerFlags.insert(std::make_pair(index, value)); currentChild = currentChild->NextSiblingElement(); } @@ -296,10 +296,10 @@ void Character::SetBuildMode(bool buildMode) void Character::SaveXMLToDatabase() { if (!m_Doc) return; - + //For metrics, we'll record the time it took to save: auto start = std::chrono::system_clock::now(); - + tinyxml2::XMLElement* character = m_Doc->FirstChildElement("obj")->FirstChildElement("char"); if (character) { character->SetAttribute("gm", m_GMLevel); @@ -323,7 +323,7 @@ void Character::SaveXMLToDatabase() { auto emotes = character->FirstChildElement("ue"); if (!emotes) emotes = m_Doc->NewElement("ue"); - + emotes->DeleteChildren(); for (int emoteID : m_UnlockedEmotes) { auto emote = m_Doc->NewElement("e"); @@ -334,53 +334,53 @@ void Character::SaveXMLToDatabase() { character->LinkEndChild(emotes); } - + //Export our flags: auto* flags = m_Doc->FirstChildElement("obj")->FirstChildElement("flag"); if (!flags) { flags = m_Doc->NewElement("flag"); //Create a flags tag if we don't have one m_Doc->FirstChildElement("obj")->LinkEndChild(flags); //Link it to the obj tag so we can find next time } - + flags->DeleteChildren(); //Clear it if we have anything, so that we can fill it up again without dupes for (std::pair flag : m_PlayerFlags) { auto* f = m_Doc->NewElement("f"); f->SetAttribute("id", flag.first); - + //Because of the joy that is tinyxml2, it doesn't offer a function to set a uint64 as an attribute. //Only signed 64-bits ints would work. std::string v = std::to_string(flag.second); f->SetAttribute("v", v.c_str()); - + flags->LinkEndChild(f); } SaveXmlRespawnCheckpoints(); - //Call upon the entity to update our xmlDoc: + //Call upon the entity to update our xmlDoc: if (!m_OurEntity) { - Game::logger->Log("Character", "We didn't have an entity set while saving! CHARACTER WILL NOT BE SAVED!\n"); + Game::logger->Log("Character", "We didn't have an entity set while saving! CHARACTER WILL NOT BE SAVED!"); return; } - + m_OurEntity->UpdateXMLDoc(m_Doc); - + //Dump our xml into m_XMLData: auto* printer = new tinyxml2::XMLPrinter(0, true, 0); m_Doc->Print(printer); m_XMLData = printer->CStr(); - + //Finally, save to db: sql::PreparedStatement* stmt = Database::CreatePreppedStmt("UPDATE charxml SET xml_data=? WHERE id=?"); stmt->setString(1, m_XMLData.c_str()); stmt->setUInt(2, m_ID); stmt->execute(); delete stmt; - + //For metrics, log the time it took to save: auto end = std::chrono::system_clock::now(); std::chrono::duration elapsed = end - start; - Game::logger->Log("Character", "Saved character to Database in: %fs\n", elapsed.count()); + Game::logger->Log("Character", "Saved character to Database in: %fs", elapsed.count()); delete printer; } @@ -404,7 +404,7 @@ void Character::SetPlayerFlag(const uint32_t flagId, const bool value) { } } } - + // Calculate the index first auto flagIndex = uint32_t(std::floor(flagId / 64)); @@ -425,9 +425,9 @@ void Character::SetPlayerFlag(const uint32_t flagId, const bool value) { if (value) { // Otherwise, insert the value uint64_t flagValue = 0; - + flagValue |= shiftedValue; - + m_PlayerFlags.insert(std::make_pair(flagIndex, flagValue)); } } @@ -458,7 +458,7 @@ void Character::SetRetroactiveFlags() { } } -void Character::SaveXmlRespawnCheckpoints() +void Character::SaveXmlRespawnCheckpoints() { //Export our respawn points: auto* points = m_Doc->FirstChildElement("obj")->FirstChildElement("res"); @@ -466,21 +466,21 @@ void Character::SaveXmlRespawnCheckpoints() points = m_Doc->NewElement("res"); m_Doc->FirstChildElement("obj")->LinkEndChild(points); } - + points->DeleteChildren(); for (const auto& point : m_WorldRespawnCheckpoints) { auto* r = m_Doc->NewElement("r"); r->SetAttribute("w", point.first); - + r->SetAttribute("x", point.second.x); r->SetAttribute("y", point.second.y); r->SetAttribute("z", point.second.z); - + points->LinkEndChild(r); } } -void Character::LoadXmlRespawnCheckpoints() +void Character::LoadXmlRespawnCheckpoints() { m_WorldRespawnCheckpoints.clear(); @@ -504,10 +504,10 @@ void Character::LoadXmlRespawnCheckpoints() m_WorldRespawnCheckpoints[map] = point; } - + } -void Character::OnZoneLoad() +void Character::OnZoneLoad() { if (m_OurEntity == nullptr) { return; @@ -530,8 +530,8 @@ void Character::OnZoneLoad() } /** - * Restrict old character to 1 million coins - */ + * Restrict old character to 1 million coins + */ if (HasPermission(PermissionMap::Old)) { if (GetCoins() > 1000000) { SetCoins(1000000, eLootSourceType::LOOT_SOURCE_NONE); @@ -560,7 +560,7 @@ bool Character::HasPermission(PermissionMap permission) const return (static_cast(m_PermissionMap) & static_cast(permission)) != 0; } -void Character::SetRespawnPoint(LWOMAPID map, const NiPoint3& point) +void Character::SetRespawnPoint(LWOMAPID map, const NiPoint3& point) { m_WorldRespawnCheckpoints[map] = point; } @@ -604,7 +604,7 @@ void Character::SendMuteNotice() const // Format: Mo, 15.06.2009 20:20:00 std::strftime(buffer, 32, "%a, %d.%m.%Y %H:%M:%S", ptm); } - + const auto timeStr = GeneralUtils::ASCIIToUTF16(std::string(buffer)); ChatPackets::SendSystemMessage(GetEntity()->GetSystemAddress(), u"You are muted until " + timeStr); diff --git a/dGame/Player.cpp b/dGame/Player.cpp index 350ddca5..56ae5a70 100644 --- a/dGame/Player.cpp +++ b/dGame/Player.cpp @@ -26,7 +26,7 @@ Player::Player(const LWOOBJID& objectID, const EntityInfo info, User* user, Enti m_SystemAddress = m_ParentUser->GetSystemAddress(); m_DroppedLoot = {}; m_DroppedCoins = 0; - + m_GhostReferencePoint = NiPoint3::ZERO; m_GhostOverridePoint = NiPoint3::ZERO; m_GhostOverride = false; @@ -121,7 +121,7 @@ void Player::SendToZone(LWOMAPID zoneId, LWOCLONEID cloneId) }); } -void Player::AddLimboConstruction(LWOOBJID objectId) +void Player::AddLimboConstruction(LWOOBJID objectId) { const auto& iter = std::find(m_LimboConstructions.begin(), m_LimboConstructions.end(), objectId); @@ -133,7 +133,7 @@ void Player::AddLimboConstruction(LWOOBJID objectId) m_LimboConstructions.push_back(objectId); } -void Player::RemoveLimboConstruction(LWOOBJID objectId) +void Player::RemoveLimboConstruction(LWOOBJID objectId) { const auto& iter = std::find(m_LimboConstructions.begin(), m_LimboConstructions.end(), objectId); @@ -158,7 +158,7 @@ void Player::ConstructLimboEntities() EntityManager::Instance()->ConstructEntity(entity, m_SystemAddress); } - + m_LimboConstructions.clear(); } @@ -177,12 +177,12 @@ const NiPoint3& Player::GetOriginGhostReferencePoint() const return m_GhostReferencePoint; } -void Player::SetGhostReferencePoint(const NiPoint3& value) +void Player::SetGhostReferencePoint(const NiPoint3& value) { m_GhostReferencePoint = value; } -void Player::SetGhostOverridePoint(const NiPoint3& value) +void Player::SetGhostOverridePoint(const NiPoint3& value) { m_GhostOverridePoint = value; } @@ -192,7 +192,7 @@ const NiPoint3& Player::GetGhostOverridePoint() const return m_GhostOverridePoint; } -void Player::SetGhostOverride(bool value) +void Player::SetGhostOverride(bool value) { m_GhostOverride = value; } @@ -202,7 +202,7 @@ bool Player::GetGhostOverride() const return m_GhostOverride; } -void Player::ObserveEntity(int32_t id) +void Player::ObserveEntity(int32_t id) { for (int32_t i = 0; i < m_ObservedEntitiesUsed; i++) { @@ -226,7 +226,7 @@ void Player::ObserveEntity(int32_t id) m_ObservedEntities[index] = id; } -bool Player::IsObserved(int32_t id) +bool Player::IsObserved(int32_t id) { for (int32_t i = 0; i < m_ObservedEntitiesUsed; i++) { @@ -239,7 +239,7 @@ bool Player::IsObserved(int32_t id) return false; } -void Player::GhostEntity(int32_t id) +void Player::GhostEntity(int32_t id) { for (int32_t i = 0; i < m_ObservedEntitiesUsed; i++) { @@ -257,7 +257,7 @@ Player* Player::GetPlayer(const SystemAddress& sysAddr) return static_cast(entity); } -Player* Player::GetPlayer(const std::string& name) +Player* Player::GetPlayer(const std::string& name) { const auto characters = EntityManager::Instance()->GetEntitiesByComponent(COMPONENT_TYPE_CHARACTER); @@ -274,7 +274,7 @@ Player* Player::GetPlayer(const std::string& name) return nullptr; } -Player* Player::GetPlayer(LWOOBJID playerID) +Player* Player::GetPlayer(LWOOBJID playerID) { for (auto* player : m_Players) { @@ -283,11 +283,11 @@ Player* Player::GetPlayer(LWOOBJID playerID) return player; } } - + return nullptr; } -const std::vector& Player::GetAllPlayers() +const std::vector& Player::GetAllPlayers() { return m_Players; } @@ -302,7 +302,7 @@ void Player::SetDroppedCoins(uint64_t value) { Player::~Player() { - Game::logger->Log("Player", "Deleted player\n"); + Game::logger->Log("Player", "Deleted player"); for (int32_t i = 0; i < m_ObservedEntitiesUsed; i++) { diff --git a/dGame/TradingManager.cpp b/dGame/TradingManager.cpp index 04a0501d..1d23126a 100644 --- a/dGame/TradingManager.cpp +++ b/dGame/TradingManager.cpp @@ -12,16 +12,16 @@ TradingManager* TradingManager::m_Address = nullptr; -Trade::Trade(LWOOBJID tradeId, LWOOBJID participantA, LWOOBJID participantB) +Trade::Trade(LWOOBJID tradeId, LWOOBJID participantA, LWOOBJID participantB) { m_TradeId = tradeId; m_ParticipantA = participantA; m_ParticipantB = participantB; } -Trade::~Trade() +Trade::~Trade() { - + } LWOOBJID Trade::GetTradeId() const @@ -54,7 +54,7 @@ Entity* Trade::GetParticipantBEntity() const return EntityManager::Instance()->GetEntity(m_ParticipantB); } -void Trade::SetCoins(LWOOBJID participant, uint64_t coins) +void Trade::SetCoins(LWOOBJID participant, uint64_t coins) { if (participant == m_ParticipantA) { @@ -66,7 +66,7 @@ void Trade::SetCoins(LWOOBJID participant, uint64_t coins) } } -void Trade::SetItems(LWOOBJID participant, std::vector items) +void Trade::SetItems(LWOOBJID participant, std::vector items) { if (participant == m_ParticipantA) { @@ -78,13 +78,13 @@ void Trade::SetItems(LWOOBJID participant, std::vector items) } } -void Trade::SetAccepted(LWOOBJID participant, bool value) +void Trade::SetAccepted(LWOOBJID participant, bool value) { if (participant == m_ParticipantA) { m_AcceptedA = !value; - Game::logger->Log("Trade", "Accepted from A (%d), B: (%d)\n", value, m_AcceptedB); + Game::logger->Log("Trade", "Accepted from A (%d), B: (%d)", value, m_AcceptedB); auto* entityB = GetParticipantBEntity(); @@ -97,7 +97,7 @@ void Trade::SetAccepted(LWOOBJID participant, bool value) { m_AcceptedB = !value; - Game::logger->Log("Trade", "Accepted from B (%d), A: (%d)\n", value, m_AcceptedA); + Game::logger->Log("Trade", "Accepted from B (%d), A: (%d)", value, m_AcceptedA); auto* entityA = GetParticipantAEntity(); @@ -106,7 +106,7 @@ void Trade::SetAccepted(LWOOBJID participant, bool value) GameMessages::SendServerTradeAccept(m_ParticipantA, value, entityA->GetSystemAddress()); } } - + if (m_AcceptedA && m_AcceptedB) { auto* entityB = GetParticipantBEntity(); @@ -119,7 +119,7 @@ void Trade::SetAccepted(LWOOBJID participant, bool value) { return; } - + auto* entityA = GetParticipantAEntity(); if (entityA != nullptr) @@ -130,16 +130,16 @@ void Trade::SetAccepted(LWOOBJID participant, bool value) { return; } - + Complete(); } } -void Trade::Complete() +void Trade::Complete() { auto* entityA = GetParticipantAEntity(); auto* entityB = GetParticipantBEntity(); - + if (entityA == nullptr || entityB == nullptr) return; auto* inventoryA = entityA->GetComponent(); @@ -160,7 +160,7 @@ void Trade::Complete() missionsA->Progress(MissionTaskType::MISSION_TASK_TYPE_ITEM_COLLECTION, tradeItem.itemLot, LWOOBJID_EMPTY, "", -tradeItem.itemCount); } - + for (const auto& tradeItem : m_ItemsB) { inventoryB->RemoveItem(tradeItem.itemLot, tradeItem.itemCount, INVALID, true); @@ -184,26 +184,26 @@ void Trade::Complete() characterB->SaveXMLToDatabase(); } -void Trade::Cancel() +void Trade::Cancel() { auto* entityA = GetParticipantAEntity(); auto* entityB = GetParticipantBEntity(); - + if (entityA == nullptr || entityB == nullptr) return; GameMessages::SendServerTradeCancel(entityA->GetObjectID(), entityA->GetSystemAddress()); GameMessages::SendServerTradeCancel(entityB->GetObjectID(), entityB->GetSystemAddress()); } -void Trade::SendUpdateToOther(LWOOBJID participant) +void Trade::SendUpdateToOther(LWOOBJID participant) { Entity* other = nullptr; Entity* self = nullptr; uint64_t coins; std::vector itemIds; - Game::logger->Log("Trade", "Attempting to send trade update\n"); - + Game::logger->Log("Trade", "Attempting to send trade update"); + if (participant == m_ParticipantA) { other = GetParticipantBEntity(); @@ -222,11 +222,11 @@ void Trade::SendUpdateToOther(LWOOBJID participant) { return; } - + if (other == nullptr || self == nullptr) return; std::vector items {}; - + auto* inventoryComponent = self->GetComponent(); if (inventoryComponent == nullptr) return; @@ -242,8 +242,8 @@ void Trade::SendUpdateToOther(LWOOBJID participant) items.push_back(tradeItem); } - Game::logger->Log("Trade", "Sending trade update\n"); - + Game::logger->Log("Trade", "Sending trade update"); + GameMessages::SendServerTradeUpdate(other->GetObjectID(), coins, items, other->GetSystemAddress()); } @@ -257,7 +257,7 @@ TradingManager::~TradingManager() { delete pair.second; } - + trades.clear(); } @@ -279,30 +279,30 @@ Trade* TradingManager::GetPlayerTrade(LWOOBJID playerId) const return pair.second; } } - + return nullptr; } -void TradingManager::CancelTrade(LWOOBJID tradeId) +void TradingManager::CancelTrade(LWOOBJID tradeId) { auto* trade = GetTrade(tradeId); if (trade == nullptr) return; - + delete trade; trades.erase(tradeId); } -Trade* TradingManager::NewTrade(LWOOBJID participantA, LWOOBJID participantB) +Trade* TradingManager::NewTrade(LWOOBJID participantA, LWOOBJID participantB) { const LWOOBJID tradeId = ObjectIDManager::Instance()->GenerateObjectID(); auto* trade = new Trade(tradeId, participantA, participantB); - + trades[tradeId] = trade; - Game::logger->Log("TradingManager", "Created new trade between (%llu) <-> (%llu)\n", participantA, participantB); + Game::logger->Log("TradingManager", "Created new trade between (%llu) <-> (%llu)", participantA, participantB); return trade; } diff --git a/dGame/User.cpp b/dGame/User.cpp index 98a37954..33329199 100644 --- a/dGame/User.cpp +++ b/dGame/User.cpp @@ -20,40 +20,40 @@ User::User(const SystemAddress& sysAddr, const std::string& username, const std: m_LoggedInCharID = 0; m_IsBestFriendMap = std::unordered_map(); - + //HACK HACK HACK //This needs to be re-enabled / updated whenever the mute stuff is moved to another table. //This was only done because otherwise the website's account page dies and the website is waiting on a migration to wordpress. - + //sql::PreparedStatement* stmt = Database::CreatePreppedStmt("SELECT id, gmlevel, mute_expire FROM accounts WHERE name=? LIMIT 1;"); sql::PreparedStatement* stmt = Database::CreatePreppedStmt("SELECT id, gm_level FROM accounts WHERE name=? LIMIT 1;"); stmt->setString(1, username.c_str()); - + sql::ResultSet* res = stmt->executeQuery(); while (res->next()) { m_AccountID = res->getUInt(1); m_MaxGMLevel = res->getInt(2); m_MuteExpire = 0; //res->getUInt64(3); } - + delete res; delete stmt; - + //If we're loading a zone, we'll load the last used (aka current) character: if (Game::server->GetZoneID() != 0) { sql::PreparedStatement* stmt = Database::CreatePreppedStmt("SELECT id FROM charinfo WHERE account_id=? ORDER BY last_login DESC LIMIT 1;"); stmt->setUInt(1, m_AccountID); - + sql::ResultSet* res = stmt->executeQuery(); if (res->rowsCount() > 0) { while (res->next()) { LWOOBJID objID = res->getUInt64(1); Character* character = new Character(uint32_t(objID), this); m_Characters.push_back(character); - Game::logger->Log("User", "Loaded %llu as it is the last used char\n", objID); + Game::logger->Log("User", "Loaded %llu as it is the last used char", objID); } } - + delete res; delete stmt; } @@ -92,7 +92,7 @@ User& User::operator= ( const User& other ) { bool User::operator== ( const User& other ) const { if (m_Username == other.m_Username || m_SessionKey == other.m_SessionKey || m_SystemAddress == other.m_SystemAddress) return true; - + return false; } @@ -104,7 +104,7 @@ Character * User::GetLastUsedChar() { for (size_t i = 0; i < m_Characters.size(); ++i) { if (m_Characters[i]->GetLastLogin() > toReturn->GetLastLogin()) toReturn = m_Characters[i]; } - + return toReturn; } } @@ -119,7 +119,7 @@ time_t User::GetMuteExpire() const return m_MuteExpire; } -void User::SetMuteExpire(time_t value) +void User::SetMuteExpire(time_t value) { m_MuteExpire = value; } @@ -128,7 +128,7 @@ void User::UserOutOfSync() { m_AmountOfTimesOutOfSync++; if (m_AmountOfTimesOutOfSync > m_MaxDesyncAllowed) { //YEET - Game::logger->Log("User", "User %s was out of sync %i times out of %i, disconnecting for suspected speedhacking.\n", m_Username.c_str(), m_AmountOfTimesOutOfSync, m_MaxDesyncAllowed); + Game::logger->Log("User", "User %s was out of sync %i times out of %i, disconnecting for suspected speedhacking.", m_Username.c_str(), m_AmountOfTimesOutOfSync, m_MaxDesyncAllowed); Game::server->Disconnect(this->m_SystemAddress, SERVER_DISCON_KICK); } } diff --git a/dGame/UserManager.cpp b/dGame/UserManager.cpp index 3956942a..5a320b51 100644 --- a/dGame/UserManager.cpp +++ b/dGame/UserManager.cpp @@ -62,7 +62,7 @@ void UserManager::Initialize() { fnFile.close(); mnFile.close(); lnFile.close(); - + //Load our pre-approved names: std::fstream chatList("./res/chatplus_en_us.txt", std::ios::in); while (std::getline(chatList, line, '\n')) { @@ -72,7 +72,7 @@ void UserManager::Initialize() { } UserManager::~UserManager() { - + } User* UserManager::CreateUser ( const SystemAddress& sysAddr, const std::string& username, const std::string& sessionKey ) { @@ -114,20 +114,20 @@ bool UserManager::DeleteUser ( const SystemAddress& sysAddr ) { if (std::count(m_UsersToDelete.begin(), m_UsersToDelete.end(), it->second)) return false; m_UsersToDelete.push_back(it->second); - + m_Users.erase(it); return true; } - + return false; } -void UserManager::DeletePendingRemovals() +void UserManager::DeletePendingRemovals() { for (auto* user : m_UsersToDelete) { - Game::logger->Log("UserManager", "Deleted user %i\n", user->GetAccountID()); + Game::logger->Log("UserManager", "Deleted user %i", user->GetAccountID()); delete user; } @@ -140,10 +140,10 @@ bool UserManager::IsNameAvailable ( const std::string& requestedName ) { sql::PreparedStatement* stmt = Database::CreatePreppedStmt("SELECT id FROM charinfo WHERE name=? OR pending_name=? LIMIT 1;"); stmt->setString(1, requestedName.c_str()); stmt->setString(2, requestedName.c_str()); - + sql::ResultSet* res = stmt->executeQuery(); if (res->rowsCount() == 0) toReturn = true; - + delete stmt; delete res; return toReturn; @@ -158,33 +158,33 @@ bool UserManager::IsNamePreapproved ( const std::string& requestedName ) { for (std::string& s : m_PreapprovedNames) { if (s == requestedName) return true; } - + for (std::string& s : m_FirstNames) { if (s == requestedName) return true; } - + for (std::string& s : m_MiddleNames) { if (s == requestedName) return true; } - + for (std::string& s : m_LastNames) { if (s == requestedName) return true; } - + return false; } void UserManager::RequestCharacterList ( const SystemAddress& sysAddr ) { User* u = GetUser(sysAddr); if (!u) return; - + sql::PreparedStatement* stmt = Database::CreatePreppedStmt("SELECT id FROM charinfo WHERE account_id=? ORDER BY last_login DESC LIMIT 4;"); stmt->setUInt(1, u->GetAccountID()); - + sql::ResultSet* res = stmt->executeQuery(); if (res->rowsCount() > 0) { std::vector& chars = u->GetCharacters(); - + for (size_t i = 0; i < chars.size(); ++i) { if (chars[i]->GetEntity() == nullptr) // We don't have entity data to save @@ -209,9 +209,9 @@ void UserManager::RequestCharacterList ( const SystemAddress& sysAddr ) { delete chars[i]; } - + chars.clear(); - + while (res->next()) { LWOOBJID objID = res->getUInt64(1); Character* character = new Character(uint32_t(objID), u); @@ -221,14 +221,14 @@ void UserManager::RequestCharacterList ( const SystemAddress& sysAddr ) { delete res; delete stmt; - + WorldPackets::SendCharacterList(sysAddr, u); } void UserManager::CreateCharacter(const SystemAddress& sysAddr, Packet* packet) { User* u = GetUser(sysAddr); if (!u) return; - + std::string name = PacketUtils::ReadString(8, packet, true); uint32_t firstNameIndex = PacketUtils::ReadPacketU32(74, packet); @@ -246,29 +246,29 @@ void UserManager::CreateCharacter(const SystemAddress& sysAddr, Packet* packet) uint32_t eyebrows = PacketUtils::ReadPacketU32(123, packet); uint32_t eyes = PacketUtils::ReadPacketU32(127, packet); uint32_t mouth = PacketUtils::ReadPacketU32(131, packet); - + LOT shirtLOT = FindCharShirtID(shirtColor, shirtStyle); LOT pantsLOT = FindCharPantsID(pantsColor); - + if (name != "" && !UserManager::IsNameAvailable(name)) { - Game::logger->Log("UserManager", "AccountID: %i chose unavailable name: %s\n", u->GetAccountID(), name.c_str()); + Game::logger->Log("UserManager", "AccountID: %i chose unavailable name: %s", u->GetAccountID(), name.c_str()); WorldPackets::SendCharacterCreationResponse(sysAddr, CREATION_RESPONSE_CUSTOM_NAME_IN_USE); return; } - + if (!IsNameAvailable(predefinedName)) { - Game::logger->Log("UserManager", "AccountID: %i chose unavailable predefined name: %s\n", u->GetAccountID(), predefinedName.c_str()); + Game::logger->Log("UserManager", "AccountID: %i chose unavailable predefined name: %s", u->GetAccountID(), predefinedName.c_str()); WorldPackets::SendCharacterCreationResponse(sysAddr, CREATION_RESPONSE_PREDEFINED_NAME_IN_USE); return; } - + if (name == "") { - Game::logger->Log("UserManager", "AccountID: %i is creating a character with predefined name: %s\n", u->GetAccountID(), predefinedName.c_str()); + Game::logger->Log("UserManager", "AccountID: %i is creating a character with predefined name: %s", u->GetAccountID(), predefinedName.c_str()); } else { - Game::logger->Log("UserManager", "AccountID: %i is creating a character with name: %s (temporary: %s)\n", u->GetAccountID(), name.c_str(), predefinedName.c_str()); + Game::logger->Log("UserManager", "AccountID: %i is creating a character with name: %s (temporary: %s)", u->GetAccountID(), name.c_str(), predefinedName.c_str()); } - + //Now that the name is ok, we can get an objectID from Master: ObjectIDManager::Instance()->RequestPersistentID([=](uint32_t objectID) { sql::PreparedStatement* overlapStmt = Database::CreatePreppedStmt("SELECT id FROM charinfo WHERE id = ?"); @@ -277,47 +277,47 @@ void UserManager::CreateCharacter(const SystemAddress& sysAddr, Packet* packet) auto* overlapResult = overlapStmt->executeQuery(); if (overlapResult->next()) { - Game::logger->Log("UserManager", "Character object id unavailable, check objectidtracker!\n"); + Game::logger->Log("UserManager", "Character object id unavailable, check objectidtracker!"); WorldPackets::SendCharacterCreationResponse(sysAddr, CREATION_RESPONSE_OBJECT_ID_UNAVAILABLE); return; } - + std::stringstream xml; xml << ""; - + xml << "GetAccountID() << "\" cc=\"0\" gm=\"0\" ft=\"0\" llog=\"" << time(NULL) << "\" "; xml << "ls=\"0\" lzx=\"-626.5847\" lzy=\"613.3515\" lzz=\"-28.6374\" lzrx=\"0.0\" lzry=\"0.7015\" lzrz=\"0.0\" lzrw=\"0.7126\" "; xml << "stt=\"0;0;0;0;0;0;0;0;0;0;0;0;0;0;0;0;0;0;0;0;0;0;0;0;0;0;0;\">"; xml << ""; xml << ""; std::string xmlSave1 = xml.str(); - + ObjectIDManager::Instance()->RequestPersistentID([=](uint32_t idforshirt) { std::stringstream xml2; - + LWOOBJID lwoidforshirt = idforshirt; lwoidforshirt = GeneralUtils::SetBit(lwoidforshirt, OBJECT_BIT_CHARACTER); lwoidforshirt = GeneralUtils::SetBit(lwoidforshirt, OBJECT_BIT_PERSISTENT); xml2 << xmlSave1 << ""; - + std::string xmlSave2 = xml2.str(); - + ObjectIDManager::Instance()->RequestPersistentID([=](uint32_t idforpants) { LWOOBJID lwoidforpants = idforpants; lwoidforpants = GeneralUtils::SetBit(lwoidforpants, OBJECT_BIT_CHARACTER); lwoidforpants = GeneralUtils::SetBit(lwoidforpants, OBJECT_BIT_PERSISTENT); - + std::stringstream xml3; xml3 << xmlSave2 << ""; - + xml3 << ""; - + //Check to see if our name was pre-approved: bool nameOk = IsNamePreapproved(name); if (!nameOk && u->GetMaxGMLevel() > 1) nameOk = true; - + if (name != "") { sql::PreparedStatement* stmt = Database::CreatePreppedStmt("INSERT INTO `charinfo`(`id`, `account_id`, `name`, `pending_name`, `needs_rename`, `last_login`) VALUES (?,?,?,?,?,?)"); stmt->setUInt(1, objectID); @@ -326,12 +326,12 @@ void UserManager::CreateCharacter(const SystemAddress& sysAddr, Packet* packet) stmt->setString(4, name.c_str()); stmt->setBoolean(5, false); stmt->setUInt64(6, time(NULL)); - + if (nameOk) { stmt->setString(3, name.c_str()); stmt->setString(4, ""); } - + stmt->execute(); delete stmt; } else { @@ -342,18 +342,18 @@ void UserManager::CreateCharacter(const SystemAddress& sysAddr, Packet* packet) stmt->setString(4, ""); stmt->setBoolean(5, false); stmt->setUInt64(6, time(NULL)); - + stmt->execute(); delete stmt; } - + //Now finally insert our character xml: sql::PreparedStatement* stmt = Database::CreatePreppedStmt("INSERT INTO `charxml`(`id`, `xml_data`) VALUES (?,?)"); stmt->setUInt(1, objectID); stmt->setString(2, xml3.str().c_str()); stmt->execute(); delete stmt; - + WorldPackets::SendCharacterCreationResponse(sysAddr, CREATION_RESPONSE_SUCCESS); UserManager::RequestCharacterList(sysAddr); }); @@ -364,28 +364,28 @@ void UserManager::CreateCharacter(const SystemAddress& sysAddr, Packet* packet) void UserManager::DeleteCharacter(const SystemAddress& sysAddr, Packet* packet) { User* u = GetUser(sysAddr); if (!u) { - Game::logger->Log("UserManager", "Couldn't get user to delete character\n"); + Game::logger->Log("UserManager", "Couldn't get user to delete character"); return; } - + LWOOBJID objectID = PacketUtils::ReadPacketS64(8, packet); uint32_t charID = static_cast(objectID); - Game::logger->Log("UserManager", "Received char delete req for ID: %llu (%u)\n", objectID, charID); - + Game::logger->Log("UserManager", "Received char delete req for ID: %llu (%u)", objectID, charID); + //Check if this user has this character: bool hasCharacter = false; std::vector& characters = u->GetCharacters(); for (size_t i = 0; i < characters.size(); ++i) { if (characters[i]->GetID() == charID) { hasCharacter = true; } } - + if (!hasCharacter) { - Game::logger->Log("UserManager", "User %i tried to delete a character that it does not own!\n", u->GetAccountID()); + Game::logger->Log("UserManager", "User %i tried to delete a character that it does not own!", u->GetAccountID()); WorldPackets::SendCharacterDeleteResponse(sysAddr, false); } else { - Game::logger->Log("UserManager", "Deleting character %i\n", charID); + Game::logger->Log("UserManager", "Deleting character %i", charID); { sql::PreparedStatement* stmt = Database::CreatePreppedStmt("DELETE FROM charxml WHERE id=? LIMIT 1;"); stmt->setUInt64(1, charID); @@ -453,7 +453,7 @@ void UserManager::DeleteCharacter(const SystemAddress& sysAddr, Packet* packet) stmt->execute(); delete stmt; } - + WorldPackets::SendCharacterDeleteResponse(sysAddr, true); } } @@ -461,37 +461,37 @@ void UserManager::DeleteCharacter(const SystemAddress& sysAddr, Packet* packet) void UserManager::RenameCharacter(const SystemAddress& sysAddr, Packet* packet) { User* u = GetUser(sysAddr); if (!u) { - Game::logger->Log("UserManager", "Couldn't get user to delete character\n"); + Game::logger->Log("UserManager", "Couldn't get user to delete character"); return; } - + LWOOBJID objectID = PacketUtils::ReadPacketS64(8, packet); objectID = GeneralUtils::ClearBit(objectID, OBJECT_BIT_CHARACTER); objectID = GeneralUtils::ClearBit(objectID, OBJECT_BIT_PERSISTENT); - + uint32_t charID = static_cast(objectID); - Game::logger->Log("UserManager", "Received char rename request for ID: %llu (%u)\n", objectID, charID); - + Game::logger->Log("UserManager", "Received char rename request for ID: %llu (%u)", objectID, charID); + std::string newName = PacketUtils::ReadString(16, packet, true); - + Character* character = nullptr; - + //Check if this user has this character: bool hasCharacter = false; std::vector& characters = u->GetCharacters(); for (size_t i = 0; i < characters.size(); ++i) { if (characters[i]->GetID() == charID) { hasCharacter = true; character = characters[i]; } } - + if (!hasCharacter || !character) { - Game::logger->Log("UserManager", "User %i tried to rename a character that it does not own!\n", u->GetAccountID()); + Game::logger->Log("UserManager", "User %i tried to rename a character that it does not own!", u->GetAccountID()); WorldPackets::SendCharacterRenameResponse(sysAddr, RENAME_RESPONSE_UNKNOWN_ERROR); } else if (hasCharacter && character) { if (newName == character->GetName()) { WorldPackets::SendCharacterRenameResponse(sysAddr, RENAME_RESPONSE_NAME_UNAVAILABLE); return; } - + if (IsNameAvailable(newName)) { if (IsNamePreapproved(newName)) { sql::PreparedStatement* stmt = Database::CreatePreppedStmt("UPDATE charinfo SET name=?, pending_name='', needs_rename=0, last_login=? WHERE id=? LIMIT 1"); @@ -500,8 +500,8 @@ void UserManager::RenameCharacter(const SystemAddress& sysAddr, Packet* packet) stmt->setUInt(3, character->GetID()); stmt->execute(); delete stmt; - - Game::logger->Log("UserManager", "Character %s now known as %s\n", character->GetName().c_str(), newName.c_str()); + + Game::logger->Log("UserManager", "Character %s now known as %s", character->GetName().c_str(), newName.c_str()); WorldPackets::SendCharacterRenameResponse(sysAddr, RENAME_RESPONSE_SUCCESS); UserManager::RequestCharacterList(sysAddr); } else { @@ -511,8 +511,8 @@ void UserManager::RenameCharacter(const SystemAddress& sysAddr, Packet* packet) stmt->setUInt(3, character->GetID()); stmt->execute(); delete stmt; - - Game::logger->Log("UserManager", "Character %s has been renamed to %s and is pending approval by a moderator.\n", character->GetName().c_str(), newName.c_str()); + + Game::logger->Log("UserManager", "Character %s has been renamed to %s and is pending approval by a moderator.", character->GetName().c_str(), newName.c_str()); WorldPackets::SendCharacterRenameResponse(sysAddr, RENAME_RESPONSE_SUCCESS); UserManager::RequestCharacterList(sysAddr); } @@ -520,7 +520,7 @@ void UserManager::RenameCharacter(const SystemAddress& sysAddr, Packet* packet) WorldPackets::SendCharacterRenameResponse(sysAddr, RENAME_RESPONSE_NAME_IN_USE); } } else { - Game::logger->Log("UserManager", "Unknown error occurred when renaming character, either hasCharacter or character variable != true.\n"); + Game::logger->Log("UserManager", "Unknown error occurred when renaming character, either hasCharacter or character variable != true."); WorldPackets::SendCharacterRenameResponse(sysAddr, RENAME_RESPONSE_UNKNOWN_ERROR); } } @@ -528,30 +528,30 @@ void UserManager::RenameCharacter(const SystemAddress& sysAddr, Packet* packet) void UserManager::LoginCharacter(const SystemAddress& sysAddr, uint32_t playerID) { User* u = GetUser(sysAddr); if (!u) { - Game::logger->Log("UserManager", "Couldn't get user to log in character\n"); + Game::logger->Log("UserManager", "Couldn't get user to log in character"); return; } - + Character* character = nullptr; bool hasCharacter = false; std::vector& characters = u->GetCharacters(); - + for (size_t i = 0; i < characters.size(); ++i) { if (characters[i]->GetID() == playerID) { hasCharacter = true; character = characters[i]; } } - + if (hasCharacter && character) { sql::PreparedStatement* stmt = Database::CreatePreppedStmt("UPDATE charinfo SET last_login=? WHERE id=? LIMIT 1"); stmt->setUInt64(1, time(NULL)); stmt->setUInt(2, playerID); stmt->execute(); delete stmt; - + uint32_t zoneID = character->GetZoneID(); if (zoneID == LWOZONEID_INVALID) zoneID = 1000; //Send char to VE - + ZoneInstanceManager::Instance()->RequestZoneTransfer(Game::server, zoneID, character->GetZoneClone(), false, [=](bool mythranShift, uint32_t zoneID, uint32_t zoneInstance, uint32_t zoneClone, std::string serverIP, uint16_t serverPort) { - Game::logger->Log("UserManager", "Transferring %s to Zone %i (Instance %i | Clone %i | Mythran Shift: %s) with IP %s and Port %i\n", character->GetName().c_str(), zoneID, zoneInstance, zoneClone, mythranShift == true ? "true" : "false", serverIP.c_str(), serverPort); + Game::logger->Log("UserManager", "Transferring %s to Zone %i (Instance %i | Clone %i | Mythran Shift: %s) with IP %s and Port %i", character->GetName().c_str(), zoneID, zoneInstance, zoneClone, mythranShift == true ? "true" : "false", serverIP.c_str(), serverPort); if (character) { character->SetZoneID(zoneID); character->SetZoneInstance(zoneInstance); @@ -561,7 +561,7 @@ void UserManager::LoginCharacter(const SystemAddress& sysAddr, uint32_t playerID return; }); } else { - Game::logger->Log("UserManager", "Unknown error occurred when logging in a character, either hasCharacter or character variable != true.\n"); + Game::logger->Log("UserManager", "Unknown error occurred when logging in a character, either hasCharacter or character variable != true."); } } diff --git a/dGame/dBehaviors/AreaOfEffectBehavior.cpp b/dGame/dBehaviors/AreaOfEffectBehavior.cpp index 6568f9b8..e3f992e7 100644 --- a/dGame/dBehaviors/AreaOfEffectBehavior.cpp +++ b/dGame/dBehaviors/AreaOfEffectBehavior.cpp @@ -37,7 +37,7 @@ void AreaOfEffectBehavior::Handle(BehaviorContext* context, RakNet::BitStream* b for (auto target : targets) { branch.target = target; - + this->m_action->Handle(context, bitStream, branch); } } @@ -48,7 +48,7 @@ void AreaOfEffectBehavior::Calculate(BehaviorContext* context, RakNet::BitStream if (self == nullptr) { - Game::logger->Log("TacArcBehavior", "Invalid self for (%llu)!\n", context->originator); + Game::logger->Log("TacArcBehavior", "Invalid self for (%llu)!", context->originator); return; } @@ -81,7 +81,7 @@ void AreaOfEffectBehavior::Calculate(BehaviorContext* context, RakNet::BitStream if (entity == nullptr) { - Game::logger->Log("TacArcBehavior", "Invalid target (%llu) for (%llu)!\n", validTarget, context->originator); + Game::logger->Log("TacArcBehavior", "Invalid target (%llu) for (%llu)!", validTarget, context->originator); continue; } @@ -90,7 +90,7 @@ void AreaOfEffectBehavior::Calculate(BehaviorContext* context, RakNet::BitStream { continue; } - + auto* destroyableComponent = entity->GetComponent(); if (destroyableComponent == nullptr) @@ -120,7 +120,7 @@ void AreaOfEffectBehavior::Calculate(BehaviorContext* context, RakNet::BitStream }); const uint32_t size = targets.size(); - + bitStream->Write(size); if (size == 0) @@ -133,10 +133,10 @@ void AreaOfEffectBehavior::Calculate(BehaviorContext* context, RakNet::BitStream for (auto* target : targets) { bitStream->Write(target->GetObjectID()); - + PlayFx(u"cast", context->originator, target->GetObjectID()); } - + for (auto* target : targets) { branch.target = target->GetObjectID(); diff --git a/dGame/dBehaviors/BasicAttackBehavior.cpp b/dGame/dBehaviors/BasicAttackBehavior.cpp index a9a58245..8f0fd287 100644 --- a/dGame/dBehaviors/BasicAttackBehavior.cpp +++ b/dGame/dBehaviors/BasicAttackBehavior.cpp @@ -21,7 +21,7 @@ void BasicAttackBehavior::Handle(BehaviorContext* context, RakNet::BitStream* bi return; } - + bitStream->AlignReadToByteBoundary(); uint16_t allocatedBits; @@ -69,7 +69,7 @@ void BasicAttackBehavior::Handle(BehaviorContext* context, RakNet::BitStream* bi this->m_onSuccess->Handle(context, bitStream, branch); break; default: - Game::logger->Log("BasicAttackBehavior", "Unknown success state (%i)!\n", successState); + Game::logger->Log("BasicAttackBehavior", "Unknown success state (%i)!", successState); break; } @@ -79,10 +79,10 @@ void BasicAttackBehavior::Handle(BehaviorContext* context, RakNet::BitStream* bi void BasicAttackBehavior::Calculate(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) { auto* self = EntityManager::Instance()->GetEntity(context->originator); if (self == nullptr) { - Game::logger->Log("BasicAttackBehavior", "Invalid self entity (%llu)!\n", context->originator); + Game::logger->Log("BasicAttackBehavior", "Invalid self entity (%llu)!", context->originator); return; } - + bitStream->AlignWriteToByteBoundary(); const auto allocatedAddress = bitStream->GetWriteOffset(); @@ -127,7 +127,7 @@ void BasicAttackBehavior::Calculate(BehaviorContext* context, RakNet::BitStream* this->m_onSuccess->Calculate(context, bitStream, branch); break; default: - Game::logger->Log("BasicAttackBehavior", "Unknown success state (%i)!\n", successState); + Game::logger->Log("BasicAttackBehavior", "Unknown success state (%i)!", successState); break; } diff --git a/dGame/dBehaviors/Behavior.cpp b/dGame/dBehaviors/Behavior.cpp index 489bd1a7..a1b746cd 100644 --- a/dGame/dBehaviors/Behavior.cpp +++ b/dGame/dBehaviors/Behavior.cpp @@ -175,7 +175,7 @@ Behavior* Behavior::CreateBehavior(const uint32_t behaviorId) behavior = new SpeedBehavior(behaviorId); break; case BehaviorTemplates::BEHAVIOR_DARK_INSPIRATION: break; - case BehaviorTemplates::BEHAVIOR_LOOT_BUFF: + case BehaviorTemplates::BEHAVIOR_LOOT_BUFF: behavior = new LootBuffBehavior(behaviorId); break; case BehaviorTemplates::BEHAVIOR_VENTURE_VISION: @@ -269,13 +269,13 @@ Behavior* Behavior::CreateBehavior(const uint32_t behaviorId) case BehaviorTemplates::BEHAVIOR_MOUNT: break; case BehaviorTemplates::BEHAVIOR_SKILL_SET: break; default: - //Game::logger->Log("Behavior", "Failed to load behavior with invalid template id (%i)!\n", templateId); + //Game::logger->Log("Behavior", "Failed to load behavior with invalid template id (%i)!", templateId); break; } if (behavior == nullptr) { - //Game::logger->Log("Behavior", "Failed to load unimplemented template id (%i)!\n", templateId); + //Game::logger->Log("Behavior", "Failed to load unimplemented template id (%i)!", templateId); behavior = new EmptyBehavior(behaviorId); } @@ -298,7 +298,7 @@ BehaviorTemplates Behavior::GetBehaviorTemplate(const uint32_t behaviorId) { } if (templateID == BehaviorTemplates::BEHAVIOR_EMPTY && behaviorId != 0) { - Game::logger->Log("Behavior", "Failed to load behavior template with id (%i)!\n", behaviorId); + Game::logger->Log("Behavior", "Failed to load behavior template with id (%i)!", behaviorId); } return templateID; @@ -432,7 +432,7 @@ Behavior::Behavior(const uint32_t behaviorId) // Make sure we do not proceed if we are trying to load an invalid behavior if (templateInDatabase.behaviorID == 0) { - Game::logger->Log("Behavior", "Failed to load behavior with id (%i)!\n", behaviorId); + Game::logger->Log("Behavior", "Failed to load behavior with id (%i)!", behaviorId); this->m_effectId = 0; this->m_effectHandle = nullptr; diff --git a/dGame/dBehaviors/BehaviorContext.cpp b/dGame/dBehaviors/BehaviorContext.cpp index c7bf912f..87e63a59 100644 --- a/dGame/dBehaviors/BehaviorContext.cpp +++ b/dGame/dBehaviors/BehaviorContext.cpp @@ -33,7 +33,7 @@ uint32_t BehaviorContext::GetUniqueSkillId() const if (entity == nullptr) { - Game::logger->Log("BehaviorContext", "Invalid entity for (%llu)!\n", this->originator); + Game::logger->Log("BehaviorContext", "Invalid entity for (%llu)!", this->originator); return 0; } @@ -42,7 +42,7 @@ uint32_t BehaviorContext::GetUniqueSkillId() const if (component == nullptr) { - Game::logger->Log("BehaviorContext", "No skill component attached to (%llu)!\n", this->originator);; + Game::logger->Log("BehaviorContext", "No skill component attached to (%llu)!", this->originator);; return 0; } @@ -65,7 +65,7 @@ void BehaviorContext::RegisterSyncBehavior(const uint32_t syncId, Behavior* beha void BehaviorContext::RegisterTimerBehavior(Behavior* behavior, const BehaviorBranchContext& branchContext, const LWOOBJID second) { BehaviorTimerEntry entry; - + entry.time = branchContext.duration; entry.behavior = behavior; entry.branchContext = branchContext; @@ -103,7 +103,7 @@ void BehaviorContext::ExecuteUpdates() auto* entity = EntityManager::Instance()->GetEntity(id); if (entity == nullptr) continue; - + EntityManager::Instance()->SerializeEntity(entity); } @@ -111,7 +111,7 @@ void BehaviorContext::ExecuteUpdates() } void BehaviorContext::SyncBehavior(const uint32_t syncId, RakNet::BitStream* bitStream) -{ +{ BehaviorSyncEntry entry; auto found = false; @@ -121,7 +121,7 @@ void BehaviorContext::SyncBehavior(const uint32_t syncId, RakNet::BitStream* bit for (auto i = 0u; i < this->syncEntries.size(); ++i) { const auto syncEntry = this->syncEntries.at(i); - + if (syncEntry.handle == syncId) { found = true; @@ -135,7 +135,7 @@ void BehaviorContext::SyncBehavior(const uint32_t syncId, RakNet::BitStream* bit if (!found) { - Game::logger->Log("BehaviorContext", "Failed to find behavior sync entry with sync id (%i)!\n", syncId); + Game::logger->Log("BehaviorContext", "Failed to find behavior sync entry with sync id (%i)!", syncId); return; } @@ -145,8 +145,8 @@ void BehaviorContext::SyncBehavior(const uint32_t syncId, RakNet::BitStream* bit if (behavior == nullptr) { - Game::logger->Log("BehaviorContext", "Invalid behavior for sync id (%i)!\n", syncId); - + Game::logger->Log("BehaviorContext", "Invalid behavior for sync id (%i)!", syncId); + return; } @@ -166,7 +166,7 @@ void BehaviorContext::Update(const float deltaTime) this->timerEntries[i] = entry; } - + if (entry.time > 0) { continue; @@ -174,7 +174,7 @@ void BehaviorContext::Update(const float deltaTime) entry.behavior->Timer(this, entry.branchContext, entry.second); } - + std::vector valid; for (const auto& entry : this->timerEntries) @@ -226,7 +226,7 @@ void BehaviorContext::InvokeEnd(const uint32_t id) bool BehaviorContext::CalculateUpdate(const float deltaTime) { auto any = false; - + for (auto i = 0u; i < this->syncEntries.size(); ++i) { auto entry = this->syncEntries.at(i); @@ -241,7 +241,7 @@ bool BehaviorContext::CalculateUpdate(const float deltaTime) if (entry.time > 0) { any = true; - + continue; } @@ -267,7 +267,7 @@ bool BehaviorContext::CalculateUpdate(const float deltaTime) PacketUtils::WriteHeader(message, CLIENT, MSG_CLIENT_GAME_MSG); message.Write(this->originator); echo.Serialize(&message); - + Game::server->Send(&message, UNASSIGNED_SYSTEM_ADDRESS, true); } @@ -293,7 +293,7 @@ bool BehaviorContext::CalculateUpdate(const float deltaTime) return any; } -void BehaviorContext::Interrupt() +void BehaviorContext::Interrupt() { std::vector keptSync {}; @@ -303,7 +303,7 @@ void BehaviorContext::Interrupt() keptSync.push_back(entry); } - + this->syncEntries = keptSync; } @@ -330,10 +330,10 @@ std::vector BehaviorContext::GetValidTargets(int32_t ignoreFaction, in auto* entity = EntityManager::Instance()->GetEntity(this->caster); std::vector targets; - + if (entity == nullptr) { - Game::logger->Log("BehaviorContext", "Invalid entity for (%llu)!\n", this->originator); + Game::logger->Log("BehaviorContext", "Invalid entity for (%llu)!", this->originator); return targets; } @@ -360,12 +360,12 @@ std::vector BehaviorContext::GetValidTargets(int32_t ignoreFaction, in { return targets; } - + auto entities = EntityManager::Instance()->GetEntitiesByComponent(COMPONENT_TYPE_CONTROLLABLE_PHYSICS); for (auto* candidate : entities) { const auto id = candidate->GetObjectID(); - + if ((id != entity->GetObjectID() || targetSelf) && destroyableComponent->CheckValidity(id, ignoreFaction || includeFaction, targetEnemy, targetFriend)) { targets.push_back(id); diff --git a/dGame/dBehaviors/BlockBehavior.cpp b/dGame/dBehaviors/BlockBehavior.cpp index 8f66b182..13012f98 100644 --- a/dGame/dBehaviors/BlockBehavior.cpp +++ b/dGame/dBehaviors/BlockBehavior.cpp @@ -15,7 +15,7 @@ void BlockBehavior::Handle(BehaviorContext* context, RakNet::BitStream* bitStrea if (entity == nullptr) { - Game::logger->Log("DamageAbsorptionBehavior", "Failed to find target (%llu)!\n", branch.target); + Game::logger->Log("DamageAbsorptionBehavior", "Failed to find target (%llu)!", branch.target); return; } @@ -52,7 +52,7 @@ void BlockBehavior::UnCast(BehaviorContext* context, BehaviorBranchContext branc if (entity == nullptr) { - Game::logger->Log("DamageAbsorptionBehavior", "Failed to find target (%llu)!\n", branch.target); + Game::logger->Log("DamageAbsorptionBehavior", "Failed to find target (%llu)!", branch.target); return; } diff --git a/dGame/dBehaviors/BuffBehavior.cpp b/dGame/dBehaviors/BuffBehavior.cpp index e2490f16..09b70e03 100644 --- a/dGame/dBehaviors/BuffBehavior.cpp +++ b/dGame/dBehaviors/BuffBehavior.cpp @@ -10,12 +10,12 @@ void BuffBehavior::Handle(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) { const auto target = branch.target != LWOOBJID_EMPTY ? branch.target : context->originator; - + auto* entity = EntityManager::Instance()->GetEntity(target); if (entity == nullptr) { - Game::logger->Log("BuffBehavior", "Invalid target (%llu)!\n", target); + Game::logger->Log("BuffBehavior", "Invalid target (%llu)!", target); return; } @@ -24,7 +24,7 @@ void BuffBehavior::Handle(BehaviorContext* context, RakNet::BitStream* bitStream if (component == nullptr) { - Game::logger->Log("BuffBehavior", "Invalid target, no destroyable component (%llu)!\n", target); + Game::logger->Log("BuffBehavior", "Invalid target, no destroyable component (%llu)!", target); return; } @@ -51,12 +51,12 @@ void BuffBehavior::Handle(BehaviorContext* context, RakNet::BitStream* bitStream void BuffBehavior::UnCast(BehaviorContext* context, BehaviorBranchContext branch) { const auto target = branch.target != LWOOBJID_EMPTY ? branch.target : context->originator; - + auto* entity = EntityManager::Instance()->GetEntity(target); if (entity == nullptr) { - Game::logger->Log("BuffBehavior", "Invalid target (%llu)!\n", target); + Game::logger->Log("BuffBehavior", "Invalid target (%llu)!", target); return; } @@ -65,7 +65,7 @@ void BuffBehavior::UnCast(BehaviorContext* context, BehaviorBranchContext branch if (component == nullptr) { - Game::logger->Log("BuffBehavior", "Invalid target, no destroyable component (%llu)!\n", target); + Game::logger->Log("BuffBehavior", "Invalid target, no destroyable component (%llu)!", target); return; } @@ -73,7 +73,7 @@ void BuffBehavior::UnCast(BehaviorContext* context, BehaviorBranchContext branch component->SetMaxHealth(component->GetMaxHealth() - this->m_health); component->SetMaxArmor(component->GetMaxArmor() - this->m_armor); component->SetMaxImagination(component->GetMaxImagination() - this->m_imagination); - + EntityManager::Instance()->SerializeEntity(entity); } diff --git a/dGame/dBehaviors/CarBoostBehavior.cpp b/dGame/dBehaviors/CarBoostBehavior.cpp index 7c726030..adfae01b 100644 --- a/dGame/dBehaviors/CarBoostBehavior.cpp +++ b/dGame/dBehaviors/CarBoostBehavior.cpp @@ -8,7 +8,7 @@ #include "dLogger.h" #include "PossessableComponent.h" -void CarBoostBehavior::Handle(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) +void CarBoostBehavior::Handle(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) { GameMessages::SendVehicleAddPassiveBoostAction(branch.target, UNASSIGNED_SYSTEM_ADDRESS); @@ -19,7 +19,7 @@ void CarBoostBehavior::Handle(BehaviorContext* context, RakNet::BitStream* bitSt return; } - Game::logger->Log("Car boost", "Activating car boost!\n"); + Game::logger->Log("Car boost", "Activating car boost!"); auto* possessableComponent = entity->GetComponent(); if (possessableComponent != nullptr) { @@ -29,7 +29,7 @@ void CarBoostBehavior::Handle(BehaviorContext* context, RakNet::BitStream* bitSt auto* characterComponent = possessor->GetComponent(); if (characterComponent != nullptr) { - Game::logger->Log("Car boost", "Tracking car boost!\n"); + Game::logger->Log("Car boost", "Tracking car boost!"); characterComponent->UpdatePlayerStatistic(RacingCarBoostsActivated); } } @@ -43,7 +43,7 @@ void CarBoostBehavior::Handle(BehaviorContext* context, RakNet::BitStream* bitSt }); } -void CarBoostBehavior::Load() +void CarBoostBehavior::Load() { m_Action = GetAction("action"); diff --git a/dGame/dBehaviors/DamageAbsorptionBehavior.cpp b/dGame/dBehaviors/DamageAbsorptionBehavior.cpp index bb94f9b3..f02c4eea 100644 --- a/dGame/dBehaviors/DamageAbsorptionBehavior.cpp +++ b/dGame/dBehaviors/DamageAbsorptionBehavior.cpp @@ -13,7 +13,7 @@ void DamageAbsorptionBehavior::Handle(BehaviorContext* context, RakNet::BitStrea if (target == nullptr) { - Game::logger->Log("DamageAbsorptionBehavior", "Failed to find target (%llu)!\n", branch.target); + Game::logger->Log("DamageAbsorptionBehavior", "Failed to find target (%llu)!", branch.target); return; } @@ -32,7 +32,7 @@ void DamageAbsorptionBehavior::Handle(BehaviorContext* context, RakNet::BitStrea context->RegisterTimerBehavior(this, branch, target->GetObjectID()); } -void DamageAbsorptionBehavior::Calculate(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) +void DamageAbsorptionBehavior::Calculate(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) { Handle(context, bitStream, branch); } @@ -43,11 +43,11 @@ void DamageAbsorptionBehavior::Timer(BehaviorContext* context, BehaviorBranchCon if (target == nullptr) { - Game::logger->Log("DamageAbsorptionBehavior", "Failed to find target (%llu)!\n", second); + Game::logger->Log("DamageAbsorptionBehavior", "Failed to find target (%llu)!", second); return; } - + auto* destroyable = target->GetComponent(); if (destroyable == nullptr) @@ -56,7 +56,7 @@ void DamageAbsorptionBehavior::Timer(BehaviorContext* context, BehaviorBranchCon } const auto present = static_cast(destroyable->GetDamageToAbsorb()); - + const auto toRemove = std::min(present, this->m_absorbAmount); destroyable->SetDamageToAbsorb(present - toRemove); diff --git a/dGame/dBehaviors/DamageReductionBehavior.cpp b/dGame/dBehaviors/DamageReductionBehavior.cpp index 96c32a03..45a30975 100644 --- a/dGame/dBehaviors/DamageReductionBehavior.cpp +++ b/dGame/dBehaviors/DamageReductionBehavior.cpp @@ -13,7 +13,7 @@ void DamageReductionBehavior::Handle(BehaviorContext* context, RakNet::BitStream if (target == nullptr) { - Game::logger->Log("DamageReductionBehavior", "Failed to find target (%llu)!\n", branch.target); + Game::logger->Log("DamageReductionBehavior", "Failed to find target (%llu)!", branch.target); return; } @@ -26,11 +26,11 @@ void DamageReductionBehavior::Handle(BehaviorContext* context, RakNet::BitStream } destroyable->SetDamageReduction(m_ReductionAmount); - + context->RegisterTimerBehavior(this, branch, target->GetObjectID()); } -void DamageReductionBehavior::Calculate(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) +void DamageReductionBehavior::Calculate(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) { Handle(context, bitStream, branch); } @@ -41,11 +41,11 @@ void DamageReductionBehavior::Timer(BehaviorContext* context, BehaviorBranchCont if (target == nullptr) { - Game::logger->Log("DamageReductionBehavior", "Failed to find target (%llu)!\n", second); + Game::logger->Log("DamageReductionBehavior", "Failed to find target (%llu)!", second); return; } - + auto* destroyable = target->GetComponent(); if (destroyable == nullptr) diff --git a/dGame/dBehaviors/HealBehavior.cpp b/dGame/dBehaviors/HealBehavior.cpp index eebf24f8..41107203 100644 --- a/dGame/dBehaviors/HealBehavior.cpp +++ b/dGame/dBehaviors/HealBehavior.cpp @@ -12,7 +12,7 @@ void HealBehavior::Handle(BehaviorContext* context, RakNet::BitStream* bit_strea if (entity == nullptr) { - Game::logger->Log("HealBehavior", "Failed to find entity for (%llu)!\n", branch.target); + Game::logger->Log("HealBehavior", "Failed to find entity for (%llu)!", branch.target); return; } @@ -21,11 +21,11 @@ void HealBehavior::Handle(BehaviorContext* context, RakNet::BitStream* bit_strea if (destroyable == nullptr) { - Game::logger->Log("HealBehavior", "Failed to find destroyable component for %(llu)!\n", branch.target); + Game::logger->Log("HealBehavior", "Failed to find destroyable component for %(llu)!", branch.target); return; } - + destroyable->Heal(this->m_health); } diff --git a/dGame/dBehaviors/ImmunityBehavior.cpp b/dGame/dBehaviors/ImmunityBehavior.cpp index 73dde1fa..4e72ba36 100644 --- a/dGame/dBehaviors/ImmunityBehavior.cpp +++ b/dGame/dBehaviors/ImmunityBehavior.cpp @@ -13,7 +13,7 @@ void ImmunityBehavior::Handle(BehaviorContext* context, RakNet::BitStream* bitSt if (target == nullptr) { - Game::logger->Log("DamageAbsorptionBehavior", "Failed to find target (%llu)!\n", branch.target); + Game::logger->Log("DamageAbsorptionBehavior", "Failed to find target (%llu)!", branch.target); return; } @@ -31,11 +31,11 @@ void ImmunityBehavior::Handle(BehaviorContext* context, RakNet::BitStream* bitSt } destroyable->PushImmunity(); - + context->RegisterTimerBehavior(this, branch, target->GetObjectID()); } -void ImmunityBehavior::Calculate(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) +void ImmunityBehavior::Calculate(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) { Handle(context, bitStream, branch); } @@ -46,7 +46,7 @@ void ImmunityBehavior::Timer(BehaviorContext* context, BehaviorBranchContext bra if (target == nullptr) { - Game::logger->Log("DamageAbsorptionBehavior", "Failed to find target (%llu)!\n", second); + Game::logger->Log("DamageAbsorptionBehavior", "Failed to find target (%llu)!", second); return; } diff --git a/dGame/dBehaviors/MovementSwitchBehavior.cpp b/dGame/dBehaviors/MovementSwitchBehavior.cpp index a77b114e..066f6224 100644 --- a/dGame/dBehaviors/MovementSwitchBehavior.cpp +++ b/dGame/dBehaviors/MovementSwitchBehavior.cpp @@ -8,13 +8,13 @@ void MovementSwitchBehavior::Handle(BehaviorContext* context, RakNet::BitStream* if (this->m_groundAction->m_templateId == BehaviorTemplates::BEHAVIOR_EMPTY && this->m_jumpAction->m_templateId == BehaviorTemplates::BEHAVIOR_EMPTY && this->m_fallingAction->m_templateId == BehaviorTemplates::BEHAVIOR_EMPTY && - this->m_doubleJumpAction->m_templateId == BehaviorTemplates::BEHAVIOR_EMPTY && + this->m_doubleJumpAction->m_templateId == BehaviorTemplates::BEHAVIOR_EMPTY && this->m_airAction->m_templateId == BehaviorTemplates::BEHAVIOR_EMPTY && this->m_jetpackAction->m_templateId == BehaviorTemplates::BEHAVIOR_EMPTY) { return; } - + uint32_t movementType; bitStream->Read(movementType); @@ -40,13 +40,13 @@ void MovementSwitchBehavior::Handle(BehaviorContext* context, RakNet::BitStream* this->m_jetpackAction->Handle(context, bitStream, branch); break; default: - Game::logger->Log("MovementSwitchBehavior", "Invalid movement behavior type (%i)!\n", movementType); + Game::logger->Log("MovementSwitchBehavior", "Invalid movement behavior type (%i)!", movementType); break; } } void MovementSwitchBehavior::Load() -{ +{ this->m_airAction = GetAction("air_action"); this->m_doubleJumpAction = GetAction("double_jump_action"); diff --git a/dGame/dBehaviors/ProjectileAttackBehavior.cpp b/dGame/dBehaviors/ProjectileAttackBehavior.cpp index 905a630c..5bf8b6a1 100644 --- a/dGame/dBehaviors/ProjectileAttackBehavior.cpp +++ b/dGame/dBehaviors/ProjectileAttackBehavior.cpp @@ -12,12 +12,12 @@ void ProjectileAttackBehavior::Handle(BehaviorContext* context, RakNet::BitStrea LWOOBJID target; bitStream->Read(target); - + auto* entity = EntityManager::Instance()->GetEntity(context->originator); if (entity == nullptr) { - Game::logger->Log("ProjectileAttackBehavior", "Failed to find originator (%llu)!\n", context->originator); + Game::logger->Log("ProjectileAttackBehavior", "Failed to find originator (%llu)!", context->originator); return; } @@ -26,7 +26,7 @@ void ProjectileAttackBehavior::Handle(BehaviorContext* context, RakNet::BitStrea if (skillComponent == nullptr) { - Game::logger->Log("ProjectileAttackBehavior", "Failed to find skill component for (%llu)!\n", -context->originator); + Game::logger->Log("ProjectileAttackBehavior", "Failed to find skill component for (%llu)!", -context->originator); return; } @@ -44,7 +44,7 @@ void ProjectileAttackBehavior::Handle(BehaviorContext* context, RakNet::BitStrea LWOOBJID projectileId; bitStream->Read(projectileId); - + branch.target = target; branch.isProjectile = true; branch.referencePosition = targetEntity == nullptr ? entity->GetPosition() : targetEntity->GetPosition(); @@ -61,7 +61,7 @@ void ProjectileAttackBehavior::Calculate(BehaviorContext* context, RakNet::BitSt if (entity == nullptr) { - Game::logger->Log("ProjectileAttackBehavior", "Failed to find originator (%llu)!\n", context->originator); + Game::logger->Log("ProjectileAttackBehavior", "Failed to find originator (%llu)!", context->originator); return; } @@ -70,7 +70,7 @@ void ProjectileAttackBehavior::Calculate(BehaviorContext* context, RakNet::BitSt if (skillComponent == nullptr) { - Game::logger->Log("ProjectileAttackBehavior", "Failed to find skill component for (%llu)!\n", context->originator); + Game::logger->Log("ProjectileAttackBehavior", "Failed to find skill component for (%llu)!", context->originator); return; @@ -80,8 +80,8 @@ void ProjectileAttackBehavior::Calculate(BehaviorContext* context, RakNet::BitSt if (other == nullptr) { - Game::logger->Log("ProjectileAttackBehavior", "Invalid projectile target (%llu)!\n", branch.target); - + Game::logger->Log("ProjectileAttackBehavior", "Invalid projectile target (%llu)!", branch.target); + return; } diff --git a/dGame/dBehaviors/RepairBehavior.cpp b/dGame/dBehaviors/RepairBehavior.cpp index 1a418cae..c3e8a4d3 100644 --- a/dGame/dBehaviors/RepairBehavior.cpp +++ b/dGame/dBehaviors/RepairBehavior.cpp @@ -12,7 +12,7 @@ void RepairBehavior::Handle(BehaviorContext* context, RakNet::BitStream* bit_str if (entity == nullptr) { - Game::logger->Log("RepairBehavior", "Failed to find entity for (%llu)!\n", branch.target); + Game::logger->Log("RepairBehavior", "Failed to find entity for (%llu)!", branch.target); return; } @@ -21,11 +21,11 @@ void RepairBehavior::Handle(BehaviorContext* context, RakNet::BitStream* bit_str if (destroyable == nullptr) { - Game::logger->Log("RepairBehavior", "Failed to find destroyable component for %(llu)!\n", branch.target); + Game::logger->Log("RepairBehavior", "Failed to find destroyable component for %(llu)!", branch.target); return; } - + destroyable->Repair(this->m_armor); } diff --git a/dGame/dBehaviors/SpawnBehavior.cpp b/dGame/dBehaviors/SpawnBehavior.cpp index 800eb86d..6d0e7490 100644 --- a/dGame/dBehaviors/SpawnBehavior.cpp +++ b/dGame/dBehaviors/SpawnBehavior.cpp @@ -14,7 +14,7 @@ void SpawnBehavior::Handle(BehaviorContext* context, RakNet::BitStream* bitStrea if (origin == nullptr) { - Game::logger->Log("SpawnBehavior", "Failed to find self entity (%llu)!\n", context->originator); + Game::logger->Log("SpawnBehavior", "Failed to find self entity (%llu)!", context->originator); return; } @@ -28,7 +28,7 @@ void SpawnBehavior::Handle(BehaviorContext* context, RakNet::BitStream* bitStrea origin = target; } } - + EntityInfo info; info.lot = this->m_lot; info.pos = origin->GetPosition(); @@ -47,7 +47,7 @@ void SpawnBehavior::Handle(BehaviorContext* context, RakNet::BitStream* bitStrea if (entity == nullptr) { - Game::logger->Log("SpawnBehavior", "Failed to spawn entity (%i)!\n", this->m_lot); + Game::logger->Log("SpawnBehavior", "Failed to spawn entity (%i)!", this->m_lot); return; } @@ -61,7 +61,7 @@ void SpawnBehavior::Handle(BehaviorContext* context, RakNet::BitStream* bitStrea { rebuildComponent->SetRepositionPlayer(false); } - + EntityManager::Instance()->ConstructEntity(entity); if (branch.duration > 0) @@ -79,7 +79,7 @@ void SpawnBehavior::Handle(BehaviorContext* context, RakNet::BitStream* bitStrea }); } -void SpawnBehavior::Calculate(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) +void SpawnBehavior::Calculate(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) { Handle(context, bitStream, branch); } @@ -90,7 +90,7 @@ void SpawnBehavior::Timer(BehaviorContext* context, const BehaviorBranchContext if (entity == nullptr) { - Game::logger->Log("SpawnBehavior", "Failed to find spawned entity (%llu)!\n", second); + Game::logger->Log("SpawnBehavior", "Failed to find spawned entity (%llu)!", second); return; } @@ -100,7 +100,7 @@ void SpawnBehavior::Timer(BehaviorContext* context, const BehaviorBranchContext if (destroyable == nullptr) { entity->Smash(context->originator); - + return; } diff --git a/dGame/dBehaviors/StunBehavior.cpp b/dGame/dBehaviors/StunBehavior.cpp index 994295bd..5c0ea310 100644 --- a/dGame/dBehaviors/StunBehavior.cpp +++ b/dGame/dBehaviors/StunBehavior.cpp @@ -22,7 +22,7 @@ void StunBehavior::Handle(BehaviorContext* context, RakNet::BitStream* bitStream if (target == nullptr) { - Game::logger->Log("StunBehavior", "Failed to find target (%llu)!\n", branch.target); + Game::logger->Log("StunBehavior", "Failed to find target (%llu)!", branch.target); return; } @@ -30,7 +30,7 @@ void StunBehavior::Handle(BehaviorContext* context, RakNet::BitStream* bitStream /* * If our target is an enemy we can go ahead and stun it. */ - + auto* combatAiComponent = static_cast(target->GetComponent(COMPONENT_TYPE_BASE_COMBAT_AI)); if (combatAiComponent == nullptr) @@ -49,7 +49,7 @@ void StunBehavior::Calculate(BehaviorContext* context, RakNet::BitStream* bitStr if (self == nullptr) { - Game::logger->Log("StunBehavior", "Invalid self entity (%llu)!\n", context->originator); + Game::logger->Log("StunBehavior", "Invalid self entity (%llu)!", context->originator); return; } @@ -57,7 +57,7 @@ void StunBehavior::Calculate(BehaviorContext* context, RakNet::BitStream* bitStr /* * See if we can stun ourselves */ - + auto* combatAiComponent = static_cast(self->GetComponent(COMPONENT_TYPE_BASE_COMBAT_AI)); if (combatAiComponent == nullptr) @@ -66,7 +66,7 @@ void StunBehavior::Calculate(BehaviorContext* context, RakNet::BitStream* bitStr } combatAiComponent->Stun(branch.duration); - + return; } @@ -88,7 +88,7 @@ void StunBehavior::Calculate(BehaviorContext* context, RakNet::BitStream* bitStr if (target == nullptr) { - Game::logger->Log("StunBehavior", "Failed to find target (%llu)!\n", branch.target); + Game::logger->Log("StunBehavior", "Failed to find target (%llu)!", branch.target); return; } diff --git a/dGame/dBehaviors/SwitchBehavior.cpp b/dGame/dBehaviors/SwitchBehavior.cpp index d6cb1438..8af8a334 100644 --- a/dGame/dBehaviors/SwitchBehavior.cpp +++ b/dGame/dBehaviors/SwitchBehavior.cpp @@ -23,13 +23,13 @@ void SwitchBehavior::Handle(BehaviorContext* context, RakNet::BitStream* bitStre } auto* destroyableComponent = entity->GetComponent(); - + if (destroyableComponent == nullptr) { return; } - Game::logger->Log("SwitchBehavior", "[%i] State: (%d), imagination: (%i) / (%f)\n", entity->GetLOT(), state, destroyableComponent->GetImagination(), destroyableComponent->GetMaxImagination()); + Game::logger->Log("SwitchBehavior", "[%i] State: (%d), imagination: (%i) / (%f)", entity->GetLOT(), state, destroyableComponent->GetImagination(), destroyableComponent->GetMaxImagination()); if (state || (entity->GetLOT() == 8092 && destroyableComponent->GetImagination() >= m_imagination)) { @@ -44,7 +44,7 @@ void SwitchBehavior::Handle(BehaviorContext* context, RakNet::BitStream* bitStre void SwitchBehavior::Calculate(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) { auto state = true; - + if (this->m_imagination > 0 || !this->m_isEnemyFaction) { auto* entity = EntityManager::Instance()->GetEntity(branch.target); @@ -77,11 +77,11 @@ void SwitchBehavior::Calculate(BehaviorContext* context, RakNet::BitStream* bitS void SwitchBehavior::Load() { this->m_actionTrue = GetAction("action_true"); - + this->m_actionFalse = GetAction("action_false"); - + this->m_imagination = GetInt("imagination"); - + this->m_isEnemyFaction = GetBoolean("isEnemyFaction"); this->m_targetHasBuff = GetInt("target_has_buff"); diff --git a/dGame/dBehaviors/TacArcBehavior.cpp b/dGame/dBehaviors/TacArcBehavior.cpp index 46ec03b9..2d012305 100644 --- a/dGame/dBehaviors/TacArcBehavior.cpp +++ b/dGame/dBehaviors/TacArcBehavior.cpp @@ -27,7 +27,7 @@ void TacArcBehavior::Handle(BehaviorContext* context, RakNet::BitStream* bitStre if (this->m_checkEnv) { bool blocked = false; - + bitStream->Read(blocked); if (blocked) @@ -63,7 +63,7 @@ void TacArcBehavior::Handle(BehaviorContext* context, RakNet::BitStream* bitStre for (auto target : targets) { branch.target = target; - + this->m_action->Handle(context, bitStream, branch); } } @@ -77,7 +77,7 @@ void TacArcBehavior::Calculate(BehaviorContext* context, RakNet::BitStream* bitS { auto* self = EntityManager::Instance()->GetEntity(context->originator); if (self == nullptr) { - Game::logger->Log("TacArcBehavior", "Invalid self for (%llu)!\n", context->originator); + Game::logger->Log("TacArcBehavior", "Invalid self for (%llu)!", context->originator); return; } @@ -102,7 +102,7 @@ void TacArcBehavior::Calculate(BehaviorContext* context, RakNet::BitStream* bitS } auto* combatAi = self->GetComponent(); - + const auto casterPosition = self->GetPosition(); auto reference = self->GetPosition(); //+ m_offset; @@ -144,7 +144,7 @@ void TacArcBehavior::Calculate(BehaviorContext* context, RakNet::BitStream* bitS if (entity == nullptr) { - Game::logger->Log("TacArcBehavior", "Invalid target (%llu) for (%llu)!\n", validTarget, context->originator); + Game::logger->Log("TacArcBehavior", "Invalid target (%llu) for (%llu)!", validTarget, context->originator); continue; } @@ -171,7 +171,7 @@ void TacArcBehavior::Calculate(BehaviorContext* context, RakNet::BitStream* bitS // otherPosition is the position of the target. // reference is the position of the caster. // If we cast a ray forward from the caster, does it come within m_farWidth of the target? - + const auto distance = Vector3::Distance(reference, otherPosition); if (m_method == 2) @@ -185,7 +185,7 @@ void TacArcBehavior::Calculate(BehaviorContext* context, RakNet::BitStream* bitS } auto normalized = (reference - otherPosition) / distance; - + const float degreeAngle = std::abs(Vector3::Angle(forward, normalized) * (180 / 3.14) - 180); if (distance >= this->m_minDistance && this->m_maxDistance >= distance && degreeAngle <= 2 * this->m_angle) @@ -221,7 +221,7 @@ void TacArcBehavior::Calculate(BehaviorContext* context, RakNet::BitStream* bitS } context->foundTarget = true; // We want to continue with this behavior - + const auto count = static_cast(targets.size()); bitStream->Write(count); diff --git a/dGame/dBehaviors/TauntBehavior.cpp b/dGame/dBehaviors/TauntBehavior.cpp index 7240dc14..8ccc3abc 100644 --- a/dGame/dBehaviors/TauntBehavior.cpp +++ b/dGame/dBehaviors/TauntBehavior.cpp @@ -12,13 +12,13 @@ void TauntBehavior::Handle(BehaviorContext* context, RakNet::BitStream* bitStrea if (target == nullptr) { - Game::logger->Log("TauntBehavior", "Failed to find target (%llu)!\n", branch.target); + Game::logger->Log("TauntBehavior", "Failed to find target (%llu)!", branch.target); return; } auto* combatComponent = target->GetComponent(); - + if (combatComponent != nullptr) { combatComponent->Taunt(context->originator, m_threatToAdd); @@ -31,13 +31,13 @@ void TauntBehavior::Calculate(BehaviorContext* context, RakNet::BitStream* bitSt if (target == nullptr) { - Game::logger->Log("TauntBehavior", "Failed to find target (%llu)!\n", branch.target); + Game::logger->Log("TauntBehavior", "Failed to find target (%llu)!", branch.target); return; } auto* combatComponent = target->GetComponent(); - + if (combatComponent != nullptr) { combatComponent->Taunt(context->originator, m_threatToAdd); diff --git a/dGame/dBehaviors/VerifyBehavior.cpp b/dGame/dBehaviors/VerifyBehavior.cpp index f4edfece..17ba1001 100644 --- a/dGame/dBehaviors/VerifyBehavior.cpp +++ b/dGame/dBehaviors/VerifyBehavior.cpp @@ -23,11 +23,11 @@ void VerifyBehavior::Calculate(BehaviorContext* context, RakNet::BitStream* bitS if (self == nullptr) { - Game::logger->Log("VerifyBehavior", "Invalid self for (%llu)\n", context->originator); + Game::logger->Log("VerifyBehavior", "Invalid self for (%llu)", context->originator); return; } - + const auto distance = Vector3::DistanceSquared(self->GetPosition(), entity->GetPosition()); if (distance > this->m_range * this->m_range) diff --git a/dGame/dComponents/BaseCombatAIComponent.cpp b/dGame/dComponents/BaseCombatAIComponent.cpp index bfa000f2..022b3e6c 100644 --- a/dGame/dComponents/BaseCombatAIComponent.cpp +++ b/dGame/dComponents/BaseCombatAIComponent.cpp @@ -38,7 +38,7 @@ BaseCombatAIComponent::BaseCombatAIComponent(Entity* parent, const uint32_t id) auto componentQuery = CDClientDatabase::CreatePreppedStmt( "SELECT aggroRadius, tetherSpeed, pursuitSpeed, softTetherRadius, hardTetherRadius FROM BaseCombatAIComponent WHERE id = ?;"); componentQuery.bind(1, (int) id); - + auto componentResult = componentQuery.execQuery(); if (!componentResult.eof()) @@ -76,7 +76,7 @@ BaseCombatAIComponent::BaseCombatAIComponent(Entity* parent, const uint32_t id) auto skillQuery = CDClientDatabase::CreatePreppedStmt( "SELECT skillID, cooldown, behaviorID FROM SkillBehavior WHERE skillID IN (SELECT skillID FROM ObjectSkills WHERE objectTemplate = ?);"); skillQuery.bind(1, (int) parent->GetLOT()); - + auto result = skillQuery.execQuery(); while (!result.eof()) { @@ -254,7 +254,7 @@ void BaseCombatAIComponent::CalculateCombat(const float deltaTime) { } skillComponent->CalculateUpdate(deltaTime); - + if (m_Disabled) return; if (m_StunTime > 0.0f) @@ -362,19 +362,19 @@ void BaseCombatAIComponent::CalculateCombat(const float deltaTime) { if (m_Target == LWOOBJID_EMPTY) { m_State = AiState::idle; - + return; } m_Downtime = 0.5f; - + auto* target = GetTargetEntity(); if (target != nullptr) { LookAt(target->GetPosition()); } - + for (auto i = 0; i < m_SkillEntries.size(); ++i) { auto entry = m_SkillEntries.at(i); @@ -413,11 +413,11 @@ LWOOBJID BaseCombatAIComponent::FindTarget() { if (m_MovementAI) reference = m_MovementAI->ApproximateLocation(); auto* target = GetTargetEntity(); - + if (target != nullptr && !m_DirtyThreat) { const auto targetPosition = target->GetPosition(); - + if (Vector3::DistanceSquared(targetPosition, m_StartPosition) < m_HardTetherRadius * m_HardTetherRadius) { return m_Target; @@ -492,7 +492,7 @@ LWOOBJID BaseCombatAIComponent::FindTarget() { } std::vector deadThreats {}; - + for (const auto& threatTarget : m_ThreatEntries) { auto* entity = EntityManager::Instance()->GetEntity(threatTarget.first); @@ -526,7 +526,7 @@ LWOOBJID BaseCombatAIComponent::FindTarget() { } m_DirtyThreat = false; - + if (optimalTarget == nullptr) { return LWOOBJID_EMPTY; @@ -577,7 +577,7 @@ bool BaseCombatAIComponent::IsEnemy(LWOOBJID target) const { auto* entity = EntityManager::Instance()->GetEntity(target); if (entity == nullptr) { - Game::logger->Log("BaseCombatAIComponent", "Invalid entity for checking validity (%llu)!\n", target); + Game::logger->Log("BaseCombatAIComponent", "Invalid entity for checking validity (%llu)!", target); return false; } @@ -591,7 +591,7 @@ bool BaseCombatAIComponent::IsEnemy(LWOOBJID target) const { auto* referenceDestroyable = m_Parent->GetComponent(); if (referenceDestroyable == nullptr) { - Game::logger->Log("BaseCombatAIComponent", "Invalid reference destroyable component on (%llu)!\n", m_Parent->GetObjectID()); + Game::logger->Log("BaseCombatAIComponent", "Invalid reference destroyable component on (%llu)!", m_Parent->GetObjectID()); return false; } @@ -601,7 +601,7 @@ bool BaseCombatAIComponent::IsEnemy(LWOOBJID target) const { if (quickbuild != nullptr) { const auto state = quickbuild->GetState(); - + if (state != REBUILD_COMPLETED) { return false; @@ -662,7 +662,7 @@ const NiPoint3& BaseCombatAIComponent::GetStartPosition() const return m_StartPosition; } -void BaseCombatAIComponent::ClearThreat() +void BaseCombatAIComponent::ClearThreat() { m_ThreatEntries.clear(); @@ -675,12 +675,12 @@ void BaseCombatAIComponent::Wander() { } m_MovementAI->SetHaltDistance(0); - + const auto& info = m_MovementAI->GetInfo(); const auto div = static_cast(info.wanderDelayMax); m_Timer = (div == 0 ? 0 : GeneralUtils::GenerateRandomNumber(0, div)) + info.wanderDelayMin; //set a random timer to stay put. - + const float radius = info.wanderRadius * sqrt(static_cast(GeneralUtils::GenerateRandomNumber(0, 1))); //our wander radius + a bit of random range const float theta = ((static_cast(GeneralUtils::GenerateRandomNumber(0, 1)) * 2 * PI)); @@ -720,7 +720,7 @@ void BaseCombatAIComponent::OnAggro() { } m_MovementAI->SetHaltDistance(m_AttackRadius); - + NiPoint3 targetPos = target->GetPosition(); NiPoint3 currentPos = m_MovementAI->GetCurrentPosition(); @@ -731,7 +731,7 @@ void BaseCombatAIComponent::OnAggro() { else if (Vector3::DistanceSquared(m_StartPosition, targetPos) > m_HardTetherRadius * m_HardTetherRadius) //Return to spawn if we're too far { m_MovementAI->SetSpeed(m_PursuitSpeed); - + m_MovementAI->SetDestination(m_StartPosition); } else //Chase the player's new position @@ -768,7 +768,7 @@ void BaseCombatAIComponent::OnTether() { m_MovementAI->SetSpeed(m_PursuitSpeed); m_MovementAI->SetDestination(m_StartPosition); - + m_State = AiState::aggro; } else { @@ -795,7 +795,7 @@ bool BaseCombatAIComponent::GetStunImmune() const return m_StunImmune; } -void BaseCombatAIComponent::SetStunImmune(bool value) +void BaseCombatAIComponent::SetStunImmune(bool value) { m_StunImmune = value; } @@ -805,7 +805,7 @@ float BaseCombatAIComponent::GetTetherSpeed() const return m_TetherSpeed; } -void BaseCombatAIComponent::SetTetherSpeed(float value) +void BaseCombatAIComponent::SetTetherSpeed(float value) { m_TetherSpeed = value; } @@ -816,7 +816,7 @@ void BaseCombatAIComponent::Stun(const float time) { } m_StunTime = time; - + m_Stunned = true; } @@ -848,13 +848,13 @@ bool BaseCombatAIComponent::GetDistabled() const return m_Disabled; } -void BaseCombatAIComponent::Sleep() +void BaseCombatAIComponent::Sleep() { m_dpEntity->SetSleeping(true); m_dpEntityEnemy->SetSleeping(true); } -void BaseCombatAIComponent::Wake() +void BaseCombatAIComponent::Wake() { m_dpEntity->SetSleeping(false); m_dpEntityEnemy->SetSleeping(false); diff --git a/dGame/dComponents/BouncerComponent.cpp b/dGame/dComponents/BouncerComponent.cpp index 38370f39..2e24b1ed 100644 --- a/dGame/dComponents/BouncerComponent.cpp +++ b/dGame/dComponents/BouncerComponent.cpp @@ -12,7 +12,7 @@ BouncerComponent::BouncerComponent(Entity* parent) : Component(parent) { m_PetEnabled = false; m_PetBouncerEnabled = false; m_PetSwitchLoaded = false; - + if (parent->GetLOT() == 7625) { LookupPetSwitch(); @@ -34,14 +34,14 @@ Entity* BouncerComponent::GetParentEntity() const return m_Parent; } -void BouncerComponent::SetPetEnabled(bool value) +void BouncerComponent::SetPetEnabled(bool value) { m_PetEnabled = value; EntityManager::Instance()->SerializeEntity(m_Parent); } -void BouncerComponent::SetPetBouncerEnabled(bool value) +void BouncerComponent::SetPetBouncerEnabled(bool value) { m_PetBouncerEnabled = value; @@ -57,7 +57,7 @@ void BouncerComponent::SetPetBouncerEnabled(bool value) { GameMessages::SendStopFXEffect(m_Parent, true, "PetOnSwitch"); } - + } bool BouncerComponent::GetPetEnabled() const @@ -70,7 +70,7 @@ bool BouncerComponent::GetPetBouncerEnabled() const return m_PetBouncerEnabled; } -void BouncerComponent::LookupPetSwitch() +void BouncerComponent::LookupPetSwitch() { const auto& groups = m_Parent->GetGroups(); @@ -85,21 +85,21 @@ void BouncerComponent::LookupPetSwitch() if (switchComponent != nullptr) { switchComponent->SetPetBouncer(this); - + m_PetSwitchLoaded = true; m_PetEnabled = true; EntityManager::Instance()->SerializeEntity(m_Parent); - Game::logger->Log("BouncerComponent", "Loaded pet bouncer\n"); + Game::logger->Log("BouncerComponent", "Loaded pet bouncer"); } } } if (!m_PetSwitchLoaded) { - Game::logger->Log("BouncerComponent", "Failed to load pet bouncer\n"); - + Game::logger->Log("BouncerComponent", "Failed to load pet bouncer"); + m_Parent->AddCallbackTimer(0.5f, [this]() { LookupPetSwitch(); }); diff --git a/dGame/dComponents/BuffComponent.cpp b/dGame/dComponents/BuffComponent.cpp index dcc74214..5874f8a6 100644 --- a/dGame/dComponents/BuffComponent.cpp +++ b/dGame/dComponents/BuffComponent.cpp @@ -49,11 +49,11 @@ void BuffComponent::Serialize(RakNet::BitStream* outBitStream, bool bIsInitialUp outBitStream->Write(0); } } - + outBitStream->Write0(); } -void BuffComponent::Update(float deltaTime) +void BuffComponent::Update(float deltaTime) { /** * Loop through all buffs and apply deltaTime to ther time. @@ -138,7 +138,7 @@ void BuffComponent::ApplyBuff(const int32_t id, const float duration, const LWOO m_Buffs.emplace(id, buff); } -void BuffComponent::RemoveBuff(int32_t id) +void BuffComponent::RemoveBuff(int32_t id) { const auto& iter = m_Buffs.find(id); @@ -146,18 +146,18 @@ void BuffComponent::RemoveBuff(int32_t id) { return; } - + m_Buffs.erase(iter); RemoveBuffEffect(id); } -bool BuffComponent::HasBuff(int32_t id) +bool BuffComponent::HasBuff(int32_t id) { return m_Buffs.find(id) != m_Buffs.end(); } -void BuffComponent::ApplyBuffEffect(int32_t id) +void BuffComponent::ApplyBuffEffect(int32_t id) { const auto& parameters = GetBuffParameters(id); for (const auto& parameter : parameters) @@ -209,7 +209,7 @@ void BuffComponent::ApplyBuffEffect(int32_t id) } } -void BuffComponent::RemoveBuffEffect(int32_t id) +void BuffComponent::RemoveBuffEffect(int32_t id) { const auto& parameters = GetBuffParameters(id); for (const auto& parameter : parameters) @@ -261,7 +261,7 @@ void BuffComponent::RemoveBuffEffect(int32_t id) } } -void BuffComponent::RemoveAllBuffs() +void BuffComponent::RemoveAllBuffs() { for (const auto& buff : m_Buffs) { @@ -271,12 +271,12 @@ void BuffComponent::RemoveAllBuffs() m_Buffs.clear(); } -void BuffComponent::Reset() +void BuffComponent::Reset() { RemoveAllBuffs(); } -void BuffComponent::ReApplyBuffs() +void BuffComponent::ReApplyBuffs() { for (const auto& buff : m_Buffs) { @@ -293,10 +293,10 @@ void BuffComponent::LoadFromXml(tinyxml2::XMLDocument* doc) { // Load buffs auto* dest = doc->FirstChildElement("obj")->FirstChildElement("dest"); - + // Make sure we have a clean buff element. auto* buffElement = dest->FirstChildElement("buff"); - + // Old character, no buffs to load if (buffElement == nullptr) { @@ -328,14 +328,14 @@ void BuffComponent::LoadFromXml(tinyxml2::XMLDocument* doc) } } -void BuffComponent::UpdateXml(tinyxml2::XMLDocument* doc) +void BuffComponent::UpdateXml(tinyxml2::XMLDocument* doc) { // Save buffs auto* dest = doc->FirstChildElement("obj")->FirstChildElement("dest"); - + // Make sure we have a clean buff element. auto* buffElement = dest->FirstChildElement("buff"); - + if (buffElement == nullptr) { buffElement = doc->NewElement("buff"); @@ -357,12 +357,12 @@ void BuffComponent::UpdateXml(tinyxml2::XMLDocument* doc) buffEntry->SetAttribute("s", buff.second.stacks); buffEntry->SetAttribute("sr", buff.second.source); buffEntry->SetAttribute("b", buff.second.behaviorID); - + buffElement->LinkEndChild(buffEntry); } } -const std::vector& BuffComponent::GetBuffParameters(int32_t buffId) +const std::vector& BuffComponent::GetBuffParameters(int32_t buffId) { const auto& pair = m_Cache.find(buffId); @@ -376,7 +376,7 @@ const std::vector& BuffComponent::GetBuffParameters(int32_t buffI query.bind(1, (int) buffId); auto result = query.execQuery(); - + std::vector parameters {}; while (!result.eof()) @@ -402,7 +402,7 @@ const std::vector& BuffComponent::GetBuffParameters(int32_t buffI } catch (std::invalid_argument& exception) { - Game::logger->Log("BuffComponent", "Failed to parse value (%s): (%s)!\n", token.c_str(), exception.what()); + Game::logger->Log("BuffComponent", "Failed to parse value (%s): (%s)!", token.c_str(), exception.what()); } } } @@ -411,7 +411,7 @@ const std::vector& BuffComponent::GetBuffParameters(int32_t buffI result.nextRow(); } - + m_Cache.insert_or_assign(buffId, parameters); return m_Cache.find(buffId)->second; diff --git a/dGame/dComponents/BuildBorderComponent.cpp b/dGame/dComponents/BuildBorderComponent.cpp index 1747f0ed..c565af97 100644 --- a/dGame/dComponents/BuildBorderComponent.cpp +++ b/dGame/dComponents/BuildBorderComponent.cpp @@ -26,8 +26,8 @@ void BuildBorderComponent::OnUse(Entity* originator) { if (!entities.empty()) { buildArea = entities[0]->GetObjectID(); - - Game::logger->Log("BuildBorderComponent", "Using PropertyPlaque\n"); + + Game::logger->Log("BuildBorderComponent", "Using PropertyPlaque"); } auto* inventoryComponent = originator->GetComponent(); @@ -44,7 +44,7 @@ void BuildBorderComponent::OnUse(Entity* originator) { inventoryComponent->PushEquippedItems(); - Game::logger->Log("BuildBorderComponent", "Starting with %llu\n", buildArea); + Game::logger->Log("BuildBorderComponent", "Starting with %llu", buildArea); if (PropertyManagementComponent::Instance() != nullptr) { GameMessages::SendStartArrangingWithItem( diff --git a/dGame/dComponents/CharacterComponent.cpp b/dGame/dComponents/CharacterComponent.cpp index f854c2b8..1f726a79 100644 --- a/dGame/dComponents/CharacterComponent.cpp +++ b/dGame/dComponents/CharacterComponent.cpp @@ -41,7 +41,7 @@ CharacterComponent::CharacterComponent(Entity* parent, Character* character) : C if (character->GetZoneID() != Game::server->GetZoneID()) { m_IsLanding = true; } - + if (LandingAnimDisabled(character->GetZoneID()) || LandingAnimDisabled(Game::server->GetZoneID()) || m_LastRocketConfig.empty()) { m_IsLanding = false; //Don't make us land on VE/minigames lol } @@ -77,13 +77,13 @@ CharacterComponent::~CharacterComponent() { } void CharacterComponent::Serialize(RakNet::BitStream* outBitStream, bool bIsInitialUpdate, unsigned int& flags) { - + if (bIsInitialUpdate) { outBitStream->Write0(); outBitStream->Write0(); outBitStream->Write0(); outBitStream->Write0(); - + outBitStream->Write(m_Character->GetHairColor()); outBitStream->Write(m_Character->GetHairStyle()); outBitStream->Write(0); //Default "head" @@ -128,7 +128,7 @@ void CharacterComponent::Serialize(RakNet::BitStream* outBitStream, bool bIsInit outBitStream->Write(m_RacingSmashablesSmashed); outBitStream->Write(m_RacesFinished); outBitStream->Write(m_FirstPlaceRaceFinishes); - + outBitStream->Write0(); outBitStream->Write(m_IsLanding); if (m_IsLanding) { @@ -147,17 +147,17 @@ void CharacterComponent::Serialize(RakNet::BitStream* outBitStream, bool bIsInit outBitStream->Write(m_EditorEnabled); outBitStream->Write(m_EditorLevel); } - + outBitStream->Write(m_DirtyCurrentActivity); if (m_DirtyCurrentActivity) outBitStream->Write(m_CurrentActivity); - + outBitStream->Write(m_DirtySocialInfo); if (m_DirtySocialInfo) { outBitStream->Write(m_GuildID); outBitStream->Write(static_cast(m_GuildName.size())); if (!m_GuildName.empty()) outBitStream->WriteBits(reinterpret_cast(m_GuildName.c_str()), static_cast(m_GuildName.size()) * sizeof(wchar_t) * 8); - + outBitStream->Write(m_IsLEGOClubMember); outBitStream->Write(m_CountryCode); } @@ -171,7 +171,7 @@ bool CharacterComponent::GetPvpEnabled() const void CharacterComponent::SetPvpEnabled(const bool value) { m_DirtyGMInfo = true; - + m_PvpEnabled = value; } @@ -183,15 +183,16 @@ void CharacterComponent::SetGMLevel(int gmlevel) { } void CharacterComponent::LoadFromXml(tinyxml2::XMLDocument* doc) { + tinyxml2::XMLElement* character = doc->FirstChildElement("obj")->FirstChildElement("char"); if (!character) { - Game::logger->Log("CharacterComponent", "Failed to find char tag while loading XML!\n"); + Game::logger->Log("CharacterComponent", "Failed to find char tag while loading XML!"); return; } if (character->QueryAttribute("rpt", &m_Reputation) == tinyxml2::XML_NO_ATTRIBUTE) { SetReputation(0); } - + character->QueryInt64Attribute("ls", &m_Uscore); // Load the statistics @@ -280,11 +281,11 @@ void CharacterComponent::LoadFromXml(tinyxml2::XMLDocument* doc) { void CharacterComponent::UpdateXml(tinyxml2::XMLDocument* doc) { tinyxml2::XMLElement* minifig = doc->FirstChildElement("obj")->FirstChildElement("mf"); if (!minifig) { - Game::logger->Log("CharacterComponent", "Failed to find mf tag while updating XML!\n"); + Game::logger->Log("CharacterComponent", "Failed to find mf tag while updating XML!"); return; } - // write minifig information that might have been changed by commands + // write minifig information that might have been changed by commands minifig->SetAttribute("es", m_Character->GetEyebrows()); minifig->SetAttribute("ess", m_Character->GetEyes()); @@ -300,7 +301,7 @@ void CharacterComponent::UpdateXml(tinyxml2::XMLDocument* doc) { tinyxml2::XMLElement* character = doc->FirstChildElement("obj")->FirstChildElement("char"); if (!character) { - Game::logger->Log("CharacterComponent", "Failed to find char tag while updating XML!\n"); + Game::logger->Log("CharacterComponent", "Failed to find char tag while updating XML!"); return; } @@ -350,7 +351,7 @@ void CharacterComponent::UpdateXml(tinyxml2::XMLDocument* doc) { // auto newUpdateTimestamp = std::time(nullptr); - Game::logger->Log("TotalTimePlayed", "Time since last save: %d\n", newUpdateTimestamp - m_LastUpdateTimestamp); + Game::logger->Log("TotalTimePlayed", "Time since last save: %d", newUpdateTimestamp - m_LastUpdateTimestamp); m_TotalTimePlayed += newUpdateTimestamp - m_LastUpdateTimestamp; character->SetAttribute("time", m_TotalTimePlayed); @@ -380,7 +381,7 @@ Item* CharacterComponent::GetRocket(Entity* player) { } if (!rocket) { - Game::logger->Log("CharacterComponent", "Unable to find rocket to equip!\n"); + Game::logger->Log("CharacterComponent", "Unable to find rocket to equip!"); return rocket; } return rocket; diff --git a/dGame/dComponents/ControllablePhysicsComponent.cpp b/dGame/dComponents/ControllablePhysicsComponent.cpp index 5d9cdd40..19c17035 100644 --- a/dGame/dComponents/ControllablePhysicsComponent.cpp +++ b/dGame/dComponents/ControllablePhysicsComponent.cpp @@ -36,7 +36,7 @@ ControllablePhysicsComponent::ControllablePhysicsComponent(Entity* entity) : Com return; if (entity->GetLOT() == 1) { - Game::logger->Log("ControllablePhysicsComponent", "Using patch to load minifig physics\n"); + Game::logger->Log("ControllablePhysicsComponent", "Using patch to load minifig physics"); float radius = 1.5f; m_dpEntity = new dpEntity(m_Parent->GetObjectID(), radius, false); @@ -133,10 +133,10 @@ void ControllablePhysicsComponent::Serialize(RakNet::BitStream* outBitStream, bo void ControllablePhysicsComponent::LoadFromXml(tinyxml2::XMLDocument* doc) { tinyxml2::XMLElement* character = doc->FirstChildElement("obj")->FirstChildElement("char"); if (!character) { - Game::logger->Log("ControllablePhysicsComponent", "Failed to find char tag!\n"); + Game::logger->Log("ControllablePhysicsComponent", "Failed to find char tag!"); return; } - + m_Parent->GetCharacter()->LoadXmlRespawnCheckpoints(); character->QueryAttribute("lzx", &m_Position.x); @@ -159,7 +159,7 @@ void ControllablePhysicsComponent::ResetFlags() { void ControllablePhysicsComponent::UpdateXml(tinyxml2::XMLDocument* doc) { tinyxml2::XMLElement* character = doc->FirstChildElement("obj")->FirstChildElement("char"); if (!character) { - Game::logger->Log("ControllablePhysicsComponent", "Failed to find char tag while updating XML!\n"); + Game::logger->Log("ControllablePhysicsComponent", "Failed to find char tag while updating XML!"); return; } @@ -254,7 +254,7 @@ void ControllablePhysicsComponent::RemovePickupRadiusScale(float value) { if (pos != m_ActivePickupRadiusScales.end()) { m_ActivePickupRadiusScales.erase(pos); } else { - Game::logger->Log("ControllablePhysicsComponent", "Warning: Could not find pickup radius %f in list of active radii. List has %i active radii.\n", value, m_ActivePickupRadiusScales.size()); + Game::logger->Log("ControllablePhysicsComponent", "Warning: Could not find pickup radius %f in list of active radii. List has %i active radii.", value, m_ActivePickupRadiusScales.size()); return; } diff --git a/dGame/dComponents/DestroyableComponent.cpp b/dGame/dComponents/DestroyableComponent.cpp index e7a6d385..c2532f42 100644 --- a/dGame/dComponents/DestroyableComponent.cpp +++ b/dGame/dComponents/DestroyableComponent.cpp @@ -162,7 +162,7 @@ void DestroyableComponent::Serialize(RakNet::BitStream* outBitStream, bool bIsIn void DestroyableComponent::LoadFromXml(tinyxml2::XMLDocument* doc) { tinyxml2::XMLElement* dest = doc->FirstChildElement("obj")->FirstChildElement("dest"); if (!dest) { - Game::logger->Log("DestroyableComponent", "Failed to find dest tag!\n"); + Game::logger->Log("DestroyableComponent", "Failed to find dest tag!"); return; } @@ -184,7 +184,7 @@ void DestroyableComponent::LoadFromXml(tinyxml2::XMLDocument* doc) { void DestroyableComponent::UpdateXml(tinyxml2::XMLDocument* doc) { tinyxml2::XMLElement* dest = doc->FirstChildElement("obj")->FirstChildElement("dest"); if (!dest) { - Game::logger->Log("DestroyableComponent", "Failed to find dest tag!\n"); + Game::logger->Log("DestroyableComponent", "Failed to find dest tag!"); return; } @@ -246,7 +246,7 @@ void DestroyableComponent::SetArmor(int32_t value) { // If Destroyable Component already has zero armor do not trigger the passive ability again. bool hadArmor = m_iArmor > 0; - + auto* characterComponent = m_Parent->GetComponent(); if (characterComponent != nullptr) { characterComponent->TrackArmorDelta(value - m_iArmor); @@ -499,7 +499,7 @@ bool DestroyableComponent::CheckValidity(const LWOOBJID target, const bool ignor if (targetEntity == nullptr) { - Game::logger->Log("DestroyableComponent", "Invalid entity for checking validity (%llu)!\n", target); + Game::logger->Log("DestroyableComponent", "Invalid entity for checking validity (%llu)!", target); return false; } @@ -777,22 +777,22 @@ void DestroyableComponent::Smash(const LWOOBJID source, const eKillType killType else { //Check if this zone allows coin drops - if (dZoneManager::Instance()->GetPlayerLoseCoinOnDeath()) + if (dZoneManager::Instance()->GetPlayerLoseCoinOnDeath()) { auto* character = m_Parent->GetCharacter(); uint64_t coinsTotal = character->GetCoins(); - if (coinsTotal > 0) + if (coinsTotal > 0) { uint64_t coinsToLoose = 1; - if (coinsTotal >= 200) + if (coinsTotal >= 200) { float hundreth = (coinsTotal / 100.0f); coinsToLoose = static_cast(hundreth); } - if (coinsToLoose > 10000) + if (coinsToLoose > 10000) { coinsToLoose = 10000; } diff --git a/dGame/dComponents/InventoryComponent.cpp b/dGame/dComponents/InventoryComponent.cpp index 0772482c..ea6c8368 100644 --- a/dGame/dComponents/InventoryComponent.cpp +++ b/dGame/dComponents/InventoryComponent.cpp @@ -157,7 +157,7 @@ void InventoryComponent::AddItem( { if (count == 0) { - Game::logger->Log("InventoryComponent", "Attempted to add 0 of item (%i) to the inventory!\n", lot); + Game::logger->Log("InventoryComponent", "Attempted to add 0 of item (%i) to the inventory!", lot); return; } @@ -166,7 +166,7 @@ void InventoryComponent::AddItem( { if (lot > 0) { - Game::logger->Log("InventoryComponent", "Attempted to add invalid item (%i) to the inventory!\n", lot); + Game::logger->Log("InventoryComponent", "Attempted to add invalid item (%i) to the inventory!", lot); } return; @@ -187,7 +187,7 @@ void InventoryComponent::AddItem( if (slot == -1) { - Game::logger->Log("InventoryComponent", "Failed to find empty slot for inventory (%i)!\n", inventoryType); + Game::logger->Log("InventoryComponent", "Failed to find empty slot for inventory (%i)!", inventoryType); return; } @@ -303,7 +303,7 @@ void InventoryComponent::RemoveItem(const LOT lot, const uint32_t count, eInvent { if (count == 0) { - Game::logger->Log("InventoryComponent", "Attempted to remove 0 of item (%i) from the inventory!\n", lot); + Game::logger->Log("InventoryComponent", "Attempted to remove 0 of item (%i) from the inventory!", lot); return; } @@ -532,7 +532,7 @@ void InventoryComponent::LoadXml(tinyxml2::XMLDocument* document) if (inventoryElement == nullptr) { - Game::logger->Log("InventoryComponent", "Failed to find 'inv' xml element!\n"); + Game::logger->Log("InventoryComponent", "Failed to find 'inv' xml element!"); return; } @@ -541,7 +541,7 @@ void InventoryComponent::LoadXml(tinyxml2::XMLDocument* document) if (bags == nullptr) { - Game::logger->Log("InventoryComponent", "Failed to find 'bags' xml element!\n"); + Game::logger->Log("InventoryComponent", "Failed to find 'bags' xml element!"); return; } @@ -569,7 +569,7 @@ void InventoryComponent::LoadXml(tinyxml2::XMLDocument* document) if (items == nullptr) { - Game::logger->Log("InventoryComponent", "Failed to find 'items' xml element!\n"); + Game::logger->Log("InventoryComponent", "Failed to find 'items' xml element!"); return; } @@ -586,7 +586,7 @@ void InventoryComponent::LoadXml(tinyxml2::XMLDocument* document) if (inventory == nullptr) { - Game::logger->Log("InventoryComponent", "Failed to find inventory (%i)!\n", type); + Game::logger->Log("InventoryComponent", "Failed to find inventory (%i)!", type); return; } @@ -666,7 +666,7 @@ void InventoryComponent::UpdateXml(tinyxml2::XMLDocument* document) if (inventoryElement == nullptr) { - Game::logger->Log("InventoryComponent", "Failed to find 'inv' xml element!\n"); + Game::logger->Log("InventoryComponent", "Failed to find 'inv' xml element!"); return; } @@ -691,7 +691,7 @@ void InventoryComponent::UpdateXml(tinyxml2::XMLDocument* document) if (bags == nullptr) { - Game::logger->Log("InventoryComponent", "Failed to find 'bags' xml element!\n"); + Game::logger->Log("InventoryComponent", "Failed to find 'bags' xml element!"); return; } @@ -712,7 +712,7 @@ void InventoryComponent::UpdateXml(tinyxml2::XMLDocument* document) if (items == nullptr) { - Game::logger->Log("InventoryComponent", "Failed to find 'items' xml element!\n"); + Game::logger->Log("InventoryComponent", "Failed to find 'items' xml element!"); return; } @@ -819,7 +819,7 @@ void InventoryComponent::Serialize(RakNet::BitStream* outBitStream, const bool b outBitStream->Write(0); // Don't compress outBitStream->Write(ldfStream); } - + outBitStream->Write1(); } @@ -932,9 +932,9 @@ void InventoryComponent::EquipItem(Item* item, const bool skipChecks) const auto building = character->GetBuildMode(); const auto type = static_cast(item->GetInfo().itemType); - + if (item->GetLot() == 8092 && m_Parent->GetGMLevel() >= GAME_MASTER_LEVEL_OPERATOR && hasCarEquipped == false) - { + { auto startPosition = m_Parent->GetPosition(); auto startRotation = NiQuaternion::LookAt(startPosition, startPosition + NiPoint3::UNIT_X); @@ -1055,11 +1055,11 @@ void InventoryComponent::EquipItem(Item* item, const bool skipChecks) } GenerateProxies(item); - + UpdateSlot(item->GetInfo().equipLocation, { item->GetId(), item->GetLot(), item->GetCount(), item->GetSlot(), item->GetConfig() }); ApplyBuff(item); - + AddItemSkills(item->GetLot()); EntityManager::Instance()->SerializeEntity(m_Parent); @@ -1087,7 +1087,7 @@ void InventoryComponent::UnEquipItem(Item* item) } RemoveBuff(item); - + RemoveItemSkills(item->GetLot()); RemoveSlot(item->GetInfo().equipLocation); @@ -1162,7 +1162,7 @@ void InventoryComponent::PopEquippedItems() m_Pushed.clear(); auto destroyableComponent = m_Parent->GetComponent(); - + // Reset stats to full if (destroyableComponent) { destroyableComponent->SetHealth(static_cast(destroyableComponent->GetMaxHealth())); @@ -1265,10 +1265,10 @@ void InventoryComponent::AddItemSkills(const LOT lot) if (index != m_Skills.end()) { const auto old = index->second; - + GameMessages::SendRemoveSkill(m_Parent, old); } - + GameMessages::SendAddSkill(m_Parent, skill, static_cast(slot)); m_Skills.insert_or_assign(slot, skill); @@ -1474,7 +1474,7 @@ std::vector InventoryComponent::FindBuffs(Item* item, bool castOnEquip if (entry.skillID == 0) { - Game::logger->Log("InventoryComponent", "Failed to find buff behavior for skill (%i)!\n", result.skillID); + Game::logger->Log("InventoryComponent", "Failed to find buff behavior for skill (%i)!", result.skillID); continue; } @@ -1483,7 +1483,7 @@ std::vector InventoryComponent::FindBuffs(Item* item, bool castOnEquip { missions->Progress(MissionTaskType::MISSION_TASK_TYPE_SKILL, result.skillID); } - + // If item is not a proxy, add its buff to the added buffs. if (item->GetParent() == LWOOBJID_EMPTY) buffs.push_back(static_cast(entry.behaviorID)); } @@ -1553,7 +1553,7 @@ std::vector InventoryComponent::GenerateProxies(Item* parent) } catch (std::invalid_argument& exception) { - Game::logger->Log("InventoryComponent", "Failed to parse proxy (%s): (%s)!\n", segment.c_str(), exception.what()); + Game::logger->Log("InventoryComponent", "Failed to parse proxy (%s): (%s)!", segment.c_str(), exception.what()); } } diff --git a/dGame/dComponents/LevelProgressionComponent.cpp b/dGame/dComponents/LevelProgressionComponent.cpp index 96d31970..ff4f3f85 100644 --- a/dGame/dComponents/LevelProgressionComponent.cpp +++ b/dGame/dComponents/LevelProgressionComponent.cpp @@ -12,7 +12,7 @@ LevelProgressionComponent::LevelProgressionComponent(Entity* parent) : Component void LevelProgressionComponent::UpdateXml(tinyxml2::XMLDocument* doc) { tinyxml2::XMLElement* level = doc->FirstChildElement("obj")->FirstChildElement("lvl"); if (!level) { - Game::logger->Log("LevelProgressionComponent", "Failed to find lvl tag while updating XML!\n"); + Game::logger->Log("LevelProgressionComponent", "Failed to find lvl tag while updating XML!"); return; } level->SetAttribute("l", m_Level); @@ -22,7 +22,7 @@ void LevelProgressionComponent::UpdateXml(tinyxml2::XMLDocument* doc) { void LevelProgressionComponent::LoadFromXml(tinyxml2::XMLDocument* doc){ tinyxml2::XMLElement* level = doc->FirstChildElement("obj")->FirstChildElement("lvl"); if (!level) { - Game::logger->Log("LevelProgressionComponent", "Failed to find lvl tag while loading XML!\n"); + Game::logger->Log("LevelProgressionComponent", "Failed to find lvl tag while loading XML!"); return; } level->QueryAttribute("l", &m_Level); diff --git a/dGame/dComponents/MissionComponent.cpp b/dGame/dComponents/MissionComponent.cpp index 1b809f48..03cb65ea 100644 --- a/dGame/dComponents/MissionComponent.cpp +++ b/dGame/dComponents/MissionComponent.cpp @@ -220,7 +220,7 @@ void MissionComponent::ForceProgressTaskType(const uint32_t missionId, const uin } } -void MissionComponent::ForceProgressValue(uint32_t missionId, uint32_t taskType, int32_t value, bool acceptMission) +void MissionComponent::ForceProgressValue(uint32_t missionId, uint32_t taskType, int32_t value, bool acceptMission) { auto* mission = GetMission(missionId); @@ -357,7 +357,7 @@ bool MissionComponent::LookForAchievements(MissionTaskType type, int32_t value, } } catch (std::invalid_argument& exception) { - Game::logger->Log("MissionComponent", "Failed to parse target (%s): (%s)!\n", token.c_str(), exception.what()); + Game::logger->Log("MissionComponent", "Failed to parse target (%s): (%s)!", token.c_str(), exception.what()); } } @@ -383,7 +383,7 @@ bool MissionComponent::LookForAchievements(MissionTaskType type, int32_t value, #endif } -const std::vector& MissionComponent::QueryAchievements(MissionTaskType type, int32_t value, const std::string targets) { +const std::vector& MissionComponent::QueryAchievements(MissionTaskType type, int32_t value, const std::string targets) { // Create a hash which represent this query for achievements size_t hash = 0; GeneralUtils::hash_combine(hash, type); @@ -471,7 +471,7 @@ bool MissionComponent::RequiresItem(const LOT lot) { } result.finalize(); - + for (const auto& pair : m_Missions) { auto* mission = pair.second; @@ -594,7 +594,7 @@ void MissionComponent::UpdateXml(tinyxml2::XMLDocument* doc) { } } -void MissionComponent::AddCollectible(int32_t collectibleID) +void MissionComponent::AddCollectible(int32_t collectibleID) { // Check if this collectible is already in the list if (HasCollectible(collectibleID)) { @@ -604,12 +604,12 @@ void MissionComponent::AddCollectible(int32_t collectibleID) m_Collectibles.push_back(collectibleID); } -bool MissionComponent::HasCollectible(int32_t collectibleID) +bool MissionComponent::HasCollectible(int32_t collectibleID) { return std::find(m_Collectibles.begin(), m_Collectibles.end(), collectibleID) != m_Collectibles.end(); } -bool MissionComponent::HasMission(uint32_t missionId) +bool MissionComponent::HasMission(uint32_t missionId) { return GetMission(missionId) != nullptr; } \ No newline at end of file diff --git a/dGame/dComponents/MissionOfferComponent.cpp b/dGame/dComponents/MissionOfferComponent.cpp index 8a9abb57..6e44d2e3 100644 --- a/dGame/dComponents/MissionOfferComponent.cpp +++ b/dGame/dComponents/MissionOfferComponent.cpp @@ -50,7 +50,7 @@ MissionOfferComponent::MissionOfferComponent(Entity* parent, const LOT parentLot // Now lookup the missions in the MissionNPCComponent table auto* missionNpcComponentTable = CDClientManager::Instance()->GetTable("MissionNPCComponent"); - + auto missions = missionNpcComponentTable->Query([=](const CDMissionNPCComponent& entry) { return entry.id == static_cast(componentId); @@ -73,11 +73,11 @@ MissionOfferComponent::~MissionOfferComponent() mission = nullptr; } } - + offeredMissions.clear(); } -void MissionOfferComponent::OnUse(Entity* originator) +void MissionOfferComponent::OnUse(Entity* originator) { OfferMissions(originator); } @@ -86,9 +86,9 @@ void MissionOfferComponent::OfferMissions(Entity* entity, const uint32_t specifi { // First, get the entity's MissionComponent. If there is not one, then we cannot offer missions to this entity. auto* missionComponent = static_cast(entity->GetComponent(COMPONENT_TYPE_MISSION)); - + if (!missionComponent) { - Game::logger->Log("MissionOfferComponent", "Unable to get mission component for Entity %llu\n", entity->GetObjectID()); + Game::logger->Log("MissionOfferComponent", "Unable to get mission component for Entity %llu", entity->GetObjectID()); return; } @@ -137,7 +137,7 @@ void MissionOfferComponent::OfferMissions(Entity* entity, const uint32_t specifi continue; } } - + const auto canAccept = MissionPrerequisites::CanAccept(missionId, missionComponent->GetMissions()); // Mission has not yet been accepted - check the prereqs @@ -148,10 +148,10 @@ void MissionOfferComponent::OfferMissions(Entity* entity, const uint32_t specifi { continue; } - + const auto& randomPool = info.randomPool; const auto isRandom = info.isRandom; - + if (isRandom && randomPool.empty()) // This means the mission is part of a random pool of missions. { continue; @@ -163,7 +163,7 @@ void MissionOfferComponent::OfferMissions(Entity* entity, const uint32_t specifi std::string token; std::vector randomMissionPool; - + while (std::getline(stream, token, ',')) { try @@ -174,7 +174,7 @@ void MissionOfferComponent::OfferMissions(Entity* entity, const uint32_t specifi } catch (std::invalid_argument& exception) { - Game::logger->Log("MissionOfferComponent", "Failed to parse value (%s): (%s)!\n", token.c_str(), exception.what()); + Game::logger->Log("MissionOfferComponent", "Failed to parse value (%s): (%s)!", token.c_str(), exception.what()); } } @@ -195,7 +195,7 @@ void MissionOfferComponent::OfferMissions(Entity* entity, const uint32_t specifi for (const auto sample : randomMissionPool) { const auto state = missionComponent->GetMissionState(sample); - + if (state == MissionState::MISSION_STATE_ACTIVE || state == MissionState::MISSION_STATE_COMPLETE_ACTIVE || state == MissionState::MISSION_STATE_READY_TO_COMPLETE || @@ -212,10 +212,10 @@ void MissionOfferComponent::OfferMissions(Entity* entity, const uint32_t specifi GameMessages::SendOfferMission(entity->GetObjectID(), entity->GetSystemAddress(), sample, m_Parent->GetObjectID()); canAcceptPool.clear(); - + break; } - + if (std::find(offered.begin(), offered.end(), sample) == offered.end() && MissionPrerequisites::CanAccept(sample, missionComponent->GetMissions())) { canAcceptPool.push_back(sample); diff --git a/dGame/dComponents/MovingPlatformComponent.cpp b/dGame/dComponents/MovingPlatformComponent.cpp index bf3ea9d5..4e99e6d6 100644 --- a/dGame/dComponents/MovingPlatformComponent.cpp +++ b/dGame/dComponents/MovingPlatformComponent.cpp @@ -20,12 +20,12 @@ MoverSubComponent::MoverSubComponent(const NiPoint3& startPos) { mDesiredWaypointIndex = 0; // -1; mInReverse = false; mShouldStopAtDesiredWaypoint = false; - + mPercentBetweenPoints = 0.0f; - + mCurrentWaypointIndex = 0; mNextWaypointIndex = 0; //mCurrentWaypointIndex + 1; - + mIdleTimeElapsed = 0.0f; } @@ -38,16 +38,16 @@ void MoverSubComponent::Serialize(RakNet::BitStream* outBitStream, bool bIsIniti outBitStream->Write(mDesiredWaypointIndex); outBitStream->Write(mShouldStopAtDesiredWaypoint); outBitStream->Write(mInReverse); - + outBitStream->Write(mPercentBetweenPoints); outBitStream->Write(mPosition.x); outBitStream->Write(mPosition.y); outBitStream->Write(mPosition.z); - + outBitStream->Write(mCurrentWaypointIndex); outBitStream->Write(mNextWaypointIndex); - + outBitStream->Write(mIdleTimeElapsed); outBitStream->Write(0.0f); // Move time elapsed } @@ -62,7 +62,7 @@ MovingPlatformComponent::MovingPlatformComponent(Entity* parent, const std::stri m_NoAutoStart = false; if (m_Path == nullptr) { - Game::logger->Log("MovingPlatformComponent", "Path not found: %s\n", pathName.c_str()); + Game::logger->Log("MovingPlatformComponent", "Path not found: %s", pathName.c_str()); } } @@ -72,7 +72,7 @@ MovingPlatformComponent::~MovingPlatformComponent() { void MovingPlatformComponent::Serialize(RakNet::BitStream* outBitStream, bool bIsInitialUpdate, unsigned int& flags) { // Here we don't serialize the moving platform to let the client simulate the movement - + if (!m_Serialize) { outBitStream->Write(false); @@ -89,7 +89,7 @@ void MovingPlatformComponent::Serialize(RakNet::BitStream* outBitStream, bool bI if (hasPath) { // Is on rail outBitStream->Write1(); - + outBitStream->Write(static_cast(m_PathName.size())); for (const auto& c : m_PathName) { outBitStream->Write(static_cast(c)); @@ -128,7 +128,7 @@ void MovingPlatformComponent::OnCompleteRebuild() { StartPathing(); } -void MovingPlatformComponent::SetMovementState(MovementPlatformState value) +void MovingPlatformComponent::SetMovementState(MovementPlatformState value) { auto* subComponent = static_cast(m_MoverSubComponent); @@ -137,10 +137,10 @@ void MovingPlatformComponent::SetMovementState(MovementPlatformState value) EntityManager::Instance()->SerializeEntity(m_Parent); } -void MovingPlatformComponent::GotoWaypoint(uint32_t index, bool stopAtWaypoint) +void MovingPlatformComponent::GotoWaypoint(uint32_t index, bool stopAtWaypoint) { auto* subComponent = static_cast(m_MoverSubComponent); - + subComponent->mDesiredWaypointIndex = index; subComponent->mNextWaypointIndex = index; subComponent->mShouldStopAtDesiredWaypoint = stopAtWaypoint; @@ -148,13 +148,13 @@ void MovingPlatformComponent::GotoWaypoint(uint32_t index, bool stopAtWaypoint) StartPathing(); } -void MovingPlatformComponent::StartPathing() +void MovingPlatformComponent::StartPathing() { //GameMessages::SendStartPathing(m_Parent); m_PathingStopped = false; - + auto* subComponent = static_cast(m_MoverSubComponent); - + subComponent->mShouldStopAtDesiredWaypoint = true; subComponent->mState = MovementPlatformState::Stationary; @@ -206,7 +206,7 @@ void MovingPlatformComponent::StartPathing() void MovingPlatformComponent::ContinuePathing() { auto* subComponent = static_cast(m_MoverSubComponent); - + subComponent->mState = MovementPlatformState::Stationary; subComponent->mCurrentWaypointIndex = subComponent->mNextWaypointIndex; @@ -258,7 +258,7 @@ void MovingPlatformComponent::ContinuePathing() case PathBehavior::Once: EntityManager::Instance()->SerializeEntity(m_Parent); return; - + case PathBehavior::Bounce: subComponent->mInReverse = true; break; @@ -266,7 +266,7 @@ void MovingPlatformComponent::ContinuePathing() case PathBehavior::Loop: subComponent->mNextWaypointIndex = 0; break; - + default: break; } @@ -347,7 +347,7 @@ void MovingPlatformComponent::StopPathing() //GameMessages::SendPlatformResync(m_Parent, UNASSIGNED_SYSTEM_ADDRESS); } -void MovingPlatformComponent::SetSerialized(bool value) +void MovingPlatformComponent::SetSerialized(bool value) { m_Serialize = value; } @@ -357,7 +357,7 @@ bool MovingPlatformComponent::GetNoAutoStart() const return m_NoAutoStart; } -void MovingPlatformComponent::SetNoAutoStart(const bool value) +void MovingPlatformComponent::SetNoAutoStart(const bool value) { m_NoAutoStart = value; } diff --git a/dGame/dComponents/PetComponent.cpp b/dGame/dComponents/PetComponent.cpp index 3cfb4e8d..0151fbf4 100644 --- a/dGame/dComponents/PetComponent.cpp +++ b/dGame/dComponents/PetComponent.cpp @@ -98,7 +98,7 @@ PetComponent::PetComponent(Entity* parent, uint32_t componentId) : Component(par result.finalize(); } -void PetComponent::Serialize(RakNet::BitStream* outBitStream, bool bIsInitialUpdate, unsigned int& flags) +void PetComponent::Serialize(RakNet::BitStream* outBitStream, bool bIsInitialUpdate, unsigned int& flags) { const bool tamed = m_Owner != LWOOBJID_EMPTY; @@ -114,7 +114,7 @@ void PetComponent::Serialize(RakNet::BitStream* outBitStream, bool bIsInitialUpd { outBitStream->Write(m_Interaction); } - + outBitStream->Write(tamed); if (tamed) { @@ -143,7 +143,7 @@ void PetComponent::Serialize(RakNet::BitStream* outBitStream, bool bIsInitialUpd } } -void PetComponent::OnUse(Entity* originator) +void PetComponent::OnUse(Entity* originator) { if (m_Owner != LWOOBJID_EMPTY) { @@ -158,7 +158,7 @@ void PetComponent::OnUse(Entity* originator) { return; } - + m_Tamer = LWOOBJID_EMPTY; } @@ -179,7 +179,7 @@ void PetComponent::OnUse(Entity* originator) { movementAIComponent->Stop(); } - + inventoryComponent->DespawnPet(); const auto& cached = buildCache.find(m_Parent->GetLOT()); @@ -245,7 +245,7 @@ void PetComponent::OnUse(Entity* originator) } auto* destroyableComponent = originator->GetComponent(); - + if (destroyableComponent == nullptr) { return; @@ -263,7 +263,7 @@ void PetComponent::OnUse(Entity* originator) if (bricks.empty()) { ChatPackets::SendSystemMessage(originator->GetSystemAddress(), u"Failed to load the puzzle minigame for this pet."); - Game::logger->Log("PetComponent", "Couldn't find %s for minigame!\n", buildFile.c_str()); + Game::logger->Log("PetComponent", "Couldn't find %s for minigame!", buildFile.c_str()); return; } @@ -282,7 +282,7 @@ void PetComponent::OnUse(Entity* originator) } auto position = originatorPosition; - + NiPoint3 forward = NiQuaternion::LookAt(m_Parent->GetPosition(), originator->GetPosition()).GetForwardVector(); forward.y = 0; @@ -297,7 +297,7 @@ void PetComponent::OnUse(Entity* originator) const NiPoint3 forward = m_Parent->GetRotation().GetForwardVector(); attempt = originatorPosition + forward * interactionDistance; - + y = dpWorld::Instance().GetHeightAtPoint(attempt); interactionDistance -= 0.5f; @@ -309,10 +309,10 @@ void PetComponent::OnUse(Entity* originator) { position = petPosition + forward * interactionDistance; } - + auto rotation = NiQuaternion::LookAt(position, petPosition); - + GameMessages::SendNotifyPetTamingMinigame( originator->GetObjectID(), m_Parent->GetObjectID(), @@ -350,7 +350,7 @@ void PetComponent::OnUse(Entity* originator) } } -void PetComponent::Update(float deltaTime) +void PetComponent::Update(float deltaTime) { if (m_StartPosition == NiPoint3::ZERO) { @@ -422,7 +422,7 @@ void PetComponent::Update(float deltaTime) } m_TresureTime -= deltaTime; - + m_MovementAI->Stop(); if (m_TresureTime <= 0) @@ -466,7 +466,7 @@ void PetComponent::Update(float deltaTime) if (m_Timer > 0) { m_Timer -= deltaTime; - + return; } @@ -509,7 +509,7 @@ void PetComponent::Update(float deltaTime) if (distance < 3 * 3) { m_Interaction = closestTresure->GetObjectID(); - + Command(NiPoint3::ZERO, LWOOBJID_EMPTY, 1, 202, true); m_TresureTime = 2; @@ -525,7 +525,7 @@ void PetComponent::Update(float deltaTime) skipTresure: m_MovementAI->SetHaltDistance(haltDistance); - + m_MovementAI->SetSpeed(2.5f); m_MovementAI->SetDestination(destination); @@ -573,7 +573,7 @@ void PetComponent::TryBuild(uint32_t numBricks, bool clientFailed) { GameMessages::SendPetTamingTryBuildResult(m_Tamer, !clientFailed, numBricks, tamer->GetSystemAddress()); } -void PetComponent::NotifyTamingBuildSuccess(NiPoint3 position) +void PetComponent::NotifyTamingBuildSuccess(NiPoint3 position) { if (m_Tamer == LWOOBJID_EMPTY) return; @@ -603,7 +603,7 @@ void PetComponent::NotifyTamingBuildSuccess(NiPoint3 position) info.spawnerID = tamer->GetObjectID(); auto* modelEntity = EntityManager::Instance()->CreateEntity(info); - + m_ModelId = modelEntity->GetObjectID(); EntityManager::Instance()->ConstructEntity(modelEntity); @@ -625,26 +625,26 @@ void PetComponent::NotifyTamingBuildSuccess(NiPoint3 position) petSubKey = GeneralUtils::SetBit(petSubKey, OBJECT_BIT_PERSISTENT); m_DatabaseId = petSubKey; - + std::string petName = tamer->GetCharacter()->GetName(); petName += "'s Pet"; GameMessages::SendAddPetToPlayer(m_Tamer, 0, GeneralUtils::ASCIIToUTF16(petName), petSubKey, m_Parent->GetLOT(), tamer->GetSystemAddress()); - + GameMessages::SendRegisterPetID(m_Tamer, m_Parent->GetObjectID(), tamer->GetSystemAddress()); GameMessages::SendRegisterPetDBID(m_Tamer, petSubKey, tamer->GetSystemAddress()); - + inventoryComponent->AddItem(m_Parent->GetLOT(), 1, eLootSourceType::LOOT_SOURCE_ACTIVITY, eInventoryType::MODELS, {}, LWOOBJID_EMPTY, true, false, petSubKey); auto* item = inventoryComponent->FindItemBySubKey(petSubKey, MODELS); - + if (item == nullptr) { return; } DatabasePet databasePet {}; - + databasePet.lot = m_Parent->GetLOT(); databasePet.moderationState = 1; databasePet.name = petName; @@ -687,7 +687,7 @@ void PetComponent::NotifyTamingBuildSuccess(NiPoint3 position) } } -void PetComponent::RequestSetPetName(std::u16string name) +void PetComponent::RequestSetPetName(std::u16string name) { if (m_Tamer == LWOOBJID_EMPTY) { @@ -717,7 +717,7 @@ void PetComponent::RequestSetPetName(std::u16string name) return; } - Game::logger->Log("PetComponent", "Got set pet name (%s)\n", GeneralUtils::UTF16ToWTF8(name).c_str()); + Game::logger->Log("PetComponent", "Got set pet name (%s)", GeneralUtils::UTF16ToWTF8(name).c_str()); auto* inventoryComponent = tamer->GetComponent(); @@ -770,7 +770,7 @@ void PetComponent::RequestSetPetName(std::u16string name) } } -void PetComponent::ClientExitTamingMinigame(bool voluntaryExit) +void PetComponent::ClientExitTamingMinigame(bool voluntaryExit) { if (m_Tamer == LWOOBJID_EMPTY) return; @@ -804,7 +804,7 @@ void PetComponent::ClientExitTamingMinigame(bool voluntaryExit) SetStatus(67108866); m_Tamer = LWOOBJID_EMPTY; m_Timer = 0; - + EntityManager::Instance()->SerializeEntity(m_Parent); // Notify the end of a pet taming minigame @@ -813,7 +813,7 @@ void PetComponent::ClientExitTamingMinigame(bool voluntaryExit) } } -void PetComponent::StartTimer() +void PetComponent::StartTimer() { const auto& cached = buildCache.find(m_Parent->GetLOT()); @@ -825,8 +825,8 @@ void PetComponent::StartTimer() m_Timer = cached->second.timeLimit; } -void PetComponent::ClientFailTamingMinigame() -{ +void PetComponent::ClientFailTamingMinigame() +{ if (m_Tamer == LWOOBJID_EMPTY) return; auto* tamer = EntityManager::Instance()->GetEntity(m_Tamer); @@ -859,7 +859,7 @@ void PetComponent::ClientFailTamingMinigame() SetStatus(67108866); m_Tamer = LWOOBJID_EMPTY; m_Timer = 0; - + EntityManager::Instance()->SerializeEntity(m_Parent); // Notify the end of a pet taming minigame @@ -868,7 +868,7 @@ void PetComponent::ClientFailTamingMinigame() } } -void PetComponent::Wander() +void PetComponent::Wander() { m_MovementAI = m_Parent->GetComponent(); @@ -877,12 +877,12 @@ void PetComponent::Wander() } m_MovementAI->SetHaltDistance(0); - + const auto& info = m_MovementAI->GetInfo(); const auto div = static_cast(info.wanderDelayMax); m_Timer = (div == 0 ? 0 : GeneralUtils::GenerateRandomNumber(0, div)) + info.wanderDelayMin; //set a random timer to stay put. - + const float radius = info.wanderRadius * sqrt(static_cast(GeneralUtils::GenerateRandomNumber(0, 1))); //our wander radius + a bit of random range const float theta = ((static_cast(GeneralUtils::GenerateRandomNumber(0, 1)) * 2 * PI)); @@ -912,13 +912,13 @@ void PetComponent::Wander() m_Timer += (m_MovementAI->GetCurrentPosition().x - destination.x) / info.wanderSpeed; } -void PetComponent::Activate(Item* item, bool registerPet, bool fromTaming) +void PetComponent::Activate(Item* item, bool registerPet, bool fromTaming) { AddDrainImaginationTimer(item, fromTaming); m_ItemId = item->GetId(); m_DatabaseId = item->GetSubKey(); - + auto* inventoryComponent = item->GetInventory()->GetComponent(); if (inventoryComponent == nullptr) return; @@ -1006,10 +1006,10 @@ void PetComponent::AddDrainImaginationTimer(Item* item, bool fromTaming) { // Set this to a variable so when this is called back from the player the timer doesn't fire off. m_Parent->AddCallbackTimer(imaginationDrainRate, [playerDestroyableComponent, this, item](){ if (!playerDestroyableComponent) { - Game::logger->Log("PetComponent", "No petComponent and/or no playerDestroyableComponent\n"); + Game::logger->Log("PetComponent", "No petComponent and/or no playerDestroyableComponent"); return; } - + // If we are out of imagination despawn the pet. if (playerDestroyableComponent->GetImagination() == 0) { this->Deactivate(); @@ -1023,7 +1023,7 @@ void PetComponent::AddDrainImaginationTimer(Item* item, bool fromTaming) { }); } -void PetComponent::Deactivate() +void PetComponent::Deactivate() { GameMessages::SendPlayFXEffect(m_Parent->GetObjectID(), -1, u"despawn", "", LWOOBJID_EMPTY, 1, 1, true); @@ -1036,7 +1036,7 @@ void PetComponent::Deactivate() auto* owner = GetOwner(); if (owner == nullptr) return; - + GameMessages::SendAddPetToPlayer(m_Owner, 0, u"", LWOOBJID_EMPTY, LOT_NULL, owner->GetSystemAddress()); GameMessages::SendRegisterPetID(m_Owner, LWOOBJID_EMPTY, owner->GetSystemAddress()); @@ -1046,7 +1046,7 @@ void PetComponent::Deactivate() GameMessages::SendShowPetActionButton(m_Owner, 0, false, owner->GetSystemAddress()); } -void PetComponent::Release() +void PetComponent::Release() { auto* inventoryComponent = GetOwner()->GetComponent(); @@ -1054,7 +1054,7 @@ void PetComponent::Release() { return; } - + Deactivate(); inventoryComponent->RemoveDatabasePet(m_DatabaseId); @@ -1064,7 +1064,7 @@ void PetComponent::Release() item->SetCount(0, false, false); } -void PetComponent::Command(NiPoint3 position, LWOOBJID source, int32_t commandType, int32_t typeId, bool overrideObey) +void PetComponent::Command(NiPoint3 position, LWOOBJID source, int32_t commandType, int32_t typeId, bool overrideObey) { auto* owner = GetOwner(); @@ -1133,12 +1133,12 @@ void PetComponent::SetStatus(uint32_t value) m_Status = value; } -void PetComponent::SetAbility(PetAbilityType value) +void PetComponent::SetAbility(PetAbilityType value) { m_Ability = value; } -PetComponent* PetComponent::GetTamingPet(LWOOBJID tamer) +PetComponent* PetComponent::GetTamingPet(LWOOBJID tamer) { const auto& pair = currentActivities.find(tamer); @@ -1159,7 +1159,7 @@ PetComponent* PetComponent::GetTamingPet(LWOOBJID tamer) return entity->GetComponent(); } -PetComponent* PetComponent::GetActivePet(LWOOBJID owner) +PetComponent* PetComponent::GetActivePet(LWOOBJID owner) { const auto& pair = activePets.find(owner); @@ -1173,7 +1173,7 @@ PetComponent* PetComponent::GetActivePet(LWOOBJID owner) if (entity == nullptr) { activePets.erase(owner); - + return nullptr; } diff --git a/dGame/dComponents/PhantomPhysicsComponent.cpp b/dGame/dComponents/PhantomPhysicsComponent.cpp index e1c2e842..3c8394f6 100644 --- a/dGame/dComponents/PhantomPhysicsComponent.cpp +++ b/dGame/dComponents/PhantomPhysicsComponent.cpp @@ -30,18 +30,18 @@ PhantomPhysicsComponent::PhantomPhysicsComponent(Entity* parent) : Component(par m_Rotation = m_Parent->GetDefaultRotation(); m_Scale = m_Parent->GetDefaultScale(); m_dpEntity = nullptr; - + m_EffectInfoDirty = false; m_PositionInfoDirty = false; - + m_IsPhysicsEffectActive = false; m_EffectType = 0; m_DirectionalMultiplier = 0.0f; - + m_MinMax = false; m_Min = 0; m_Max = 1; - + m_IsDirectional = false; m_Direction = NiPoint3(); // * m_DirectionalMultiplier @@ -82,7 +82,7 @@ PhantomPhysicsComponent::PhantomPhysicsComponent(Entity* parent) : Component(par } // HF - RespawnPoints. Legacy respawn entity. - if (m_Parent->GetLOT() == 4945) + if (m_Parent->GetLOT() == 4945) { m_IsRespawnVolume = true; m_RespawnPos = m_Position; @@ -218,7 +218,7 @@ PhantomPhysicsComponent::PhantomPhysicsComponent(Entity* parent) : Component(par dpWorld::Instance().AddEntity(m_dpEntity); } else { - //Game::logger->Log("PhantomPhysicsComponent", "This one is supposed to have %s\n", info->physicsAsset.c_str()); + //Game::logger->Log("PhantomPhysicsComponent", "This one is supposed to have %s", info->physicsAsset.c_str()); //add fallback cube: m_dpEntity = new dpEntity(m_Parent->GetObjectID(), 2.0f, 2.0f, 2.0f); @@ -262,7 +262,7 @@ void PhantomPhysicsComponent::CreatePhysics() { CDPhysicsComponentTable* physComp = CDClientManager::Instance()->GetTable("PhysicsComponent"); if (physComp == nullptr) return; - + auto info = physComp->GetByID(componentID); if (info == nullptr) return; @@ -315,15 +315,15 @@ void PhantomPhysicsComponent::Serialize(RakNet::BitStream* outBitStream, bool bI m_PositionInfoDirty = false; } - + outBitStream->Write(m_EffectInfoDirty || bIsInitialUpdate); if (m_EffectInfoDirty || bIsInitialUpdate) { outBitStream->Write(m_IsPhysicsEffectActive); - + if (m_IsPhysicsEffectActive) { outBitStream->Write(m_EffectType); outBitStream->Write(m_DirectionalMultiplier); - + // forgive me father for i have sinned outBitStream->Write0(); //outBitStream->Write(m_MinMax); @@ -331,7 +331,7 @@ void PhantomPhysicsComponent::Serialize(RakNet::BitStream* outBitStream, bool bI //outBitStream->Write(m_Min); //outBitStream->Write(m_Max); //} - + outBitStream->Write(m_IsDirectional); if (m_IsDirectional) { outBitStream->Write(m_Direction.x); @@ -379,7 +379,7 @@ void PhantomPhysicsComponent::SetDirection(const NiPoint3& pos) { m_Direction.x *= m_DirectionalMultiplier; m_Direction.y *= m_DirectionalMultiplier; m_Direction.z *= m_DirectionalMultiplier; - + m_EffectInfoDirty = true; m_IsDirectional = true; } diff --git a/dGame/dComponents/PropertyEntranceComponent.cpp b/dGame/dComponents/PropertyEntranceComponent.cpp index 4be059ed..5bc24a9f 100644 --- a/dGame/dComponents/PropertyEntranceComponent.cpp +++ b/dGame/dComponents/PropertyEntranceComponent.cpp @@ -192,7 +192,7 @@ void PropertyEntranceComponent::OnPropertyEntranceSync(Entity* entity, bool incl const auto query = BuildQuery(entity, sortMethod, character); auto propertyLookup = Database::CreatePreppedStmt(query); - + const auto searchString = "%" + filterText + "%"; propertyLookup->setUInt(1, this->m_MapID); propertyLookup->setString(2, searchString.c_str()); @@ -230,7 +230,7 @@ void PropertyEntranceComponent::OnPropertyEntranceSync(Entity* entity, bool incl delete nameLookup; nameLookup = nullptr; - Game::logger->Log("PropertyEntranceComponent", "Failed to find property owner name for %llu!\n", cloneId); + Game::logger->Log("PropertyEntranceComponent", "Failed to find property owner name for %llu!", cloneId); continue; } else { @@ -318,7 +318,7 @@ void PropertyEntranceComponent::OnPropertyEntranceSync(Entity* entity, bool incl propertyLookup = nullptr; propertyQueries[entity->GetObjectID()] = entries; - + // Query here is to figure out whether or not to display the button to go to the next page or not. int32_t numberOfProperties = 0; @@ -337,7 +337,7 @@ void PropertyEntranceComponent::OnPropertyEntranceSync(Entity* entity, bool incl delete result; result = nullptr; - + delete propertiesLeft; propertiesLeft = nullptr; diff --git a/dGame/dComponents/PropertyManagementComponent.cpp b/dGame/dComponents/PropertyManagementComponent.cpp index 1168209c..fa9a7e52 100644 --- a/dGame/dComponents/PropertyManagementComponent.cpp +++ b/dGame/dComponents/PropertyManagementComponent.cpp @@ -37,7 +37,7 @@ PropertyManagementComponent::PropertyManagementComponent(Entity* parent) : Compo instance = this; const auto& worldId = dZoneManager::Instance()->GetZone()->GetZoneID(); - + const auto zoneId = worldId.GetMapID(); const auto cloneId = worldId.GetCloneID(); @@ -51,7 +51,7 @@ PropertyManagementComponent::PropertyManagementComponent(Entity* parent) : Compo { return; } - + templateId = result.getIntField(0); result.finalize(); @@ -80,7 +80,7 @@ PropertyManagementComponent::PropertyManagementComponent(Entity* parent) : Compo this->reputation = propertyEntry->getUInt(14); Load(); - } + } delete propertyLookup; } @@ -111,14 +111,14 @@ std::vector PropertyManagementComponent::GetPaths() const auto result = query.execQuery(); std::vector paths {}; - + if (result.eof()) { return paths; } std::vector points; - + std::istringstream stream(result.getStringField(0)); std::string token; @@ -132,7 +132,7 @@ std::vector PropertyManagementComponent::GetPaths() const } catch (std::invalid_argument& exception) { - Game::logger->Log("PropertyManagementComponent", "Failed to parse value (%s): (%s)!\n", token.c_str(), exception.what()); + Game::logger->Log("PropertyManagementComponent", "Failed to parse value (%s): (%s)!", token.c_str(), exception.what()); } } @@ -149,7 +149,7 @@ PropertyPrivacyOption PropertyManagementComponent::GetPrivacyOption() const return privacyOption; } -void PropertyManagementComponent::SetPrivacyOption(PropertyPrivacyOption value) +void PropertyManagementComponent::SetPrivacyOption(PropertyPrivacyOption value) { if (owner == LWOOBJID_EMPTY) return; @@ -241,7 +241,7 @@ bool PropertyManagementComponent::Claim(const LWOOBJID playerId) } catch (sql::SQLException& exception) { - Game::logger->Log("PropertyManagementComponent", "Failed to execute query: (%s)!\n", exception.what()); + Game::logger->Log("PropertyManagementComponent", "Failed to execute query: (%s)!", exception.what()); throw exception; return false; @@ -254,7 +254,7 @@ bool PropertyManagementComponent::Claim(const LWOOBJID playerId) return true; } -void PropertyManagementComponent::OnStartBuilding() +void PropertyManagementComponent::OnStartBuilding() { auto* ownerEntity = GetOwner(); @@ -307,7 +307,7 @@ void PropertyManagementComponent::OnFinishBuilding() void PropertyManagementComponent::UpdateModelPosition(const LWOOBJID id, const NiPoint3 position, NiQuaternion rotation) { - Game::logger->Log("PropertyManagementComponent", "Placing model <%f, %f, %f>\n", position.x, position.y, position.z); + Game::logger->Log("PropertyManagementComponent", "Placing model <%f, %f, %f>", position.x, position.y, position.z); auto* entity = GetOwner(); @@ -327,7 +327,7 @@ void PropertyManagementComponent::UpdateModelPosition(const LWOOBJID id, const N if (item == nullptr) { - Game::logger->Log("PropertyManagementComponent", "Failed to find item with id %d\n", id); + Game::logger->Log("PropertyManagementComponent", "Failed to find item with id %d", id); return; } @@ -369,7 +369,7 @@ void PropertyManagementComponent::UpdateModelPosition(const LWOOBJID id, const N item->SetCount(item->GetCount() - 1); return; } - + item->SetCount(item->GetCount() - 1); auto* node = new SpawnerNode(); @@ -394,7 +394,7 @@ void PropertyManagementComponent::UpdateModelPosition(const LWOOBJID id, const N LWOOBJID id = static_cast(persistentId) | 1ull << OBJECT_BIT_CLIENT; info.spawnerID = id; - + const auto spawnerId = dZoneManager::Instance()->MakeSpawner(info); auto* spawner = dZoneManager::Instance()->GetSpawner(spawnerId); @@ -429,7 +429,7 @@ void PropertyManagementComponent::UpdateModelPosition(const LWOOBJID id, const N void PropertyManagementComponent::DeleteModel(const LWOOBJID id, const int deleteReason) { - Game::logger->Log("PropertyManagementComponent", "Delete model: (%llu) (%i)\n", id, deleteReason); + Game::logger->Log("PropertyManagementComponent", "Delete model: (%llu) (%i)", id, deleteReason); auto* entity = GetOwner(); @@ -449,34 +449,34 @@ void PropertyManagementComponent::DeleteModel(const LWOOBJID id, const int delet if (index == models.end()) { - Game::logger->Log("PropertyManagementComponent", "Failed to find model\n"); + Game::logger->Log("PropertyManagementComponent", "Failed to find model"); return; } const auto spawnerId = index->second; - + auto* spawner = dZoneManager::Instance()->GetSpawner(spawnerId); models.erase(id); - + if (spawner == nullptr) { - Game::logger->Log("PropertyManagementComponent", "Failed to find spawner\n"); + Game::logger->Log("PropertyManagementComponent", "Failed to find spawner"); } auto* model = EntityManager::Instance()->GetEntity(id); if (model == nullptr) { - Game::logger->Log("PropertyManagementComponent", "Failed to find model entity\n"); + Game::logger->Log("PropertyManagementComponent", "Failed to find model entity"); return; } EntityManager::Instance()->DestructEntity(model); - Game::logger->Log("PropertyManagementComponent", "Deleting model LOT %i\n", model->GetLOT()); + Game::logger->Log("PropertyManagementComponent", "Deleting model LOT %i", model->GetLOT()); if (model->GetLOT() == 14) { @@ -536,7 +536,7 @@ void PropertyManagementComponent::DeleteModel(const LWOOBJID id, const int delet return; } - + inventoryComponent->AddItem(model->GetLOT(), 1, eLootSourceType::LOOT_SOURCE_DELETION, INVALID, {}, LWOOBJID_EMPTY, false); auto* item = inventoryComponent->FindItemByLot(model->GetLOT()); @@ -572,10 +572,10 @@ void PropertyManagementComponent::DeleteModel(const LWOOBJID id, const int delet } default: { - Game::logger->Log("PropertyManagementComponent", "Invalid delete reason\n"); + Game::logger->Log("PropertyManagementComponent", "Invalid delete reason"); } } - + GameMessages::SendGetModelsOnProperty(entity->GetObjectID(), GetModels(), UNASSIGNED_SYSTEM_ADDRESS); GameMessages::SendPlaceModelResponse(entity->GetObjectID(), entity->GetSystemAddress(), NiPoint3::ZERO, LWOOBJID_EMPTY, 16, NiQuaternion::IDENTITY); @@ -593,7 +593,7 @@ void PropertyManagementComponent::DeleteModel(const LWOOBJID id, const int delet void PropertyManagementComponent::UpdateApprovedStatus(const bool value) { if (owner == LWOOBJID_EMPTY) return; - + auto* update = Database::CreatePreppedStmt("UPDATE properties SET mod_approved = ? WHERE id = ?;"); update->setBoolean(1, value); @@ -610,11 +610,11 @@ void PropertyManagementComponent::Load() { return; } - + auto* lookup = Database::CreatePreppedStmt("SELECT id, lot, x, y, z, rx, ry, rz, rw, ugc_id FROM properties_contents WHERE property_id = ?;"); lookup->setUInt64(1, propertyId); - + auto* lookupResult = lookup->executeQuery(); while (lookupResult->next()) @@ -622,7 +622,7 @@ void PropertyManagementComponent::Load() const LWOOBJID id = lookupResult->getUInt64(1); const LOT lot = lookupResult->getInt(2); - const NiPoint3 position = + const NiPoint3 position = { static_cast(lookupResult->getDouble(3)), static_cast(lookupResult->getDouble(4)), @@ -641,7 +641,7 @@ void PropertyManagementComponent::Load() node->position = position; node->rotation = rotation; - + SpawnerInfo info{}; info.templateID = lot; @@ -720,7 +720,7 @@ void PropertyManagementComponent::Save() try { lookupResult = lookup->executeQuery(); } catch (sql::SQLException& ex) { - Game::logger->Log("PropertyManagementComponent", "lookup error %s\n", ex.what()); + Game::logger->Log("PropertyManagementComponent", "lookup error %s", ex.what()); } std::vector present; @@ -734,7 +734,7 @@ void PropertyManagementComponent::Save() delete lookupResult; std::vector modelIds; - + for (const auto& pair : models) { const auto id = pair.second; @@ -767,7 +767,7 @@ void PropertyManagementComponent::Save() try { insertion->execute(); } catch (sql::SQLException& ex) { - Game::logger->Log("PropertyManagementComponent", "Error inserting into properties_contents. Error %s\n", ex.what()); + Game::logger->Log("PropertyManagementComponent", "Error inserting into properties_contents. Error %s", ex.what()); } } else @@ -784,7 +784,7 @@ void PropertyManagementComponent::Save() try { update->executeUpdate(); } catch (sql::SQLException& ex) { - Game::logger->Log("PropertyManagementComponent", "Error updating properties_contents. Error: %s\n", ex.what()); + Game::logger->Log("PropertyManagementComponent", "Error updating properties_contents. Error: %s", ex.what()); } } } @@ -800,7 +800,7 @@ void PropertyManagementComponent::Save() try { remove->execute(); } catch (sql::SQLException& ex) { - Game::logger->Log("PropertyManagementComponent", "Error removing from properties_contents. Error %s\n", ex.what()); + Game::logger->Log("PropertyManagementComponent", "Error removing from properties_contents. Error %s", ex.what()); } } @@ -815,7 +815,7 @@ void PropertyManagementComponent::Save() delete remove; } -void PropertyManagementComponent::AddModel(LWOOBJID modelId, LWOOBJID spawnerId) +void PropertyManagementComponent::AddModel(LWOOBJID modelId, LWOOBJID spawnerId) { models[modelId] = spawnerId; } @@ -834,7 +834,7 @@ void PropertyManagementComponent::OnQueryPropertyData(Entity* originator, const const auto& worldId = dZoneManager::Instance()->GetZone()->GetZoneID(); const auto zoneId = worldId.GetMapID(); - Game::logger->Log("Properties", "Getting property info for %d\n", zoneId); + Game::logger->Log("Properties", "Getting property info for %d", zoneId); GameMessages::PropertyDataMessage message = GameMessages::PropertyDataMessage(zoneId); const auto isClaimed = GetOwnerId() != LWOOBJID_EMPTY; @@ -845,7 +845,7 @@ void PropertyManagementComponent::OnQueryPropertyData(Entity* originator, const std::string description = ""; uint64_t claimed = 0; char privacy = 0; - + if (isClaimed) { const auto cloneId = worldId.GetCloneID(); @@ -904,7 +904,7 @@ void PropertyManagementComponent::OnQueryPropertyData(Entity* originator, const // send rejection here? } -void PropertyManagementComponent::OnUse(Entity* originator) +void PropertyManagementComponent::OnUse(Entity* originator) { OnQueryPropertyData(originator, UNASSIGNED_SYSTEM_ADDRESS); GameMessages::SendOpenPropertyManagment(m_Parent->GetObjectID(), originator->GetSystemAddress()); diff --git a/dGame/dComponents/PropertyVendorComponent.cpp b/dGame/dComponents/PropertyVendorComponent.cpp index 72e8ad64..5ab8340b 100644 --- a/dGame/dComponents/PropertyVendorComponent.cpp +++ b/dGame/dComponents/PropertyVendorComponent.cpp @@ -22,7 +22,7 @@ void PropertyVendorComponent::OnUse(Entity* originator) if (PropertyManagementComponent::Instance()->GetOwnerId() == LWOOBJID_EMPTY) { - Game::logger->Log("PropertyVendorComponent", "Property vendor opening!\n"); + Game::logger->Log("PropertyVendorComponent", "Property vendor opening!"); GameMessages::SendOpenPropertyVendor(m_Parent->GetObjectID(), originator->GetSystemAddress()); @@ -42,7 +42,7 @@ void PropertyVendorComponent::OnBuyFromVendor(Entity* originator, const bool con if (PropertyManagementComponent::Instance() == nullptr) return; if (PropertyManagementComponent::Instance()->Claim(originator->GetObjectID()) == false) { - Game::logger->Log("PropertyVendorComponent", "FAILED TO CLAIM PROPERTY. PLAYER ID IS %llu\n", originator->GetObjectID()); + Game::logger->Log("PropertyVendorComponent", "FAILED TO CLAIM PROPERTY. PLAYER ID IS %llu", originator->GetObjectID()); return; } @@ -51,11 +51,11 @@ void PropertyVendorComponent::OnBuyFromVendor(Entity* originator, const bool con auto* controller = dZoneManager::Instance()->GetZoneControlObject(); controller->OnFireEventServerSide(m_Parent, "propertyRented"); - + PropertyManagementComponent::Instance()->SetOwner(originator); - + PropertyManagementComponent::Instance()->OnQueryPropertyData(originator, originator->GetSystemAddress()); - Game::logger->Log("PropertyVendorComponent", "Fired event; (%d) (%i) (%i)\n", confirmed, lot, count); + Game::logger->Log("PropertyVendorComponent", "Fired event; (%d) (%i) (%i)", confirmed, lot, count); } diff --git a/dGame/dComponents/RacingControlComponent.cpp b/dGame/dComponents/RacingControlComponent.cpp index 7bea03f6..e157ca5f 100644 --- a/dGame/dComponents/RacingControlComponent.cpp +++ b/dGame/dComponents/RacingControlComponent.cpp @@ -91,7 +91,7 @@ void RacingControlComponent::OnPlayerLoaded(Entity *player) { m_LoadedPlayers++; - Game::logger->Log("RacingControlComponent", "Loading player %i\n", + Game::logger->Log("RacingControlComponent", "Loading player %i", m_LoadedPlayers); m_LobbyPlayers.push_back(objectID); @@ -116,7 +116,7 @@ void RacingControlComponent::LoadPlayerVehicle(Entity *player, auto *item = inventoryComponent->FindItemByLot(8092); if (item == nullptr) { - Game::logger->Log("RacingControlComponent", "Failed to find item\n"); + Game::logger->Log("RacingControlComponent", "Failed to find item"); return; } @@ -149,7 +149,7 @@ void RacingControlComponent::LoadPlayerVehicle(Entity *player, startRotation = NiQuaternion::FromEulerAngles(angles); Game::logger->Log("RacingControlComponent", - "Start position <%f, %f, %f>, <%f, %f, %f>\n", + "Start position <%f, %f, %f>, <%f, %f, %f>", startPosition.x, startPosition.y, startPosition.z, angles.x * (180.0f / M_PI), angles.y * (180.0f / M_PI), angles.z * (180.0f / M_PI)); @@ -565,11 +565,11 @@ void RacingControlComponent::Update(float deltaTime) { // to load in, can raise this if it's too low if (m_LoadTimer >= 15) { Game::logger->Log("RacingControlComponent", - "Loading all players...\n"); + "Loading all players..."); for (size_t i = 0; i < m_LobbyPlayers.size(); i++) { Game::logger->Log("RacingControlComponent", - "Loading player now!\n"); + "Loading player now!"); auto *player = EntityManager::Instance()->GetEntity(m_LobbyPlayers[i]); @@ -579,7 +579,7 @@ void RacingControlComponent::Update(float deltaTime) { } Game::logger->Log("RacingControlComponent", - "Loading player now NOW!\n"); + "Loading player now NOW!"); LoadPlayerVehicle(player, true); @@ -729,7 +729,7 @@ void RacingControlComponent::Update(float deltaTime) { m_Started = true; - Game::logger->Log("RacingControlComponent", "Starting race\n"); + Game::logger->Log("RacingControlComponent", "Starting race"); EntityManager::Instance()->SerializeEntity(m_Parent); @@ -833,7 +833,7 @@ void RacingControlComponent::Update(float deltaTime) { player.bestLapTime = lapTime; Game::logger->Log("RacingControlComponent", - "Best lap time (%llu)\n", lapTime); + "Best lap time (%llu)", lapTime); } auto *missionComponent = @@ -854,7 +854,7 @@ void RacingControlComponent::Update(float deltaTime) { player.raceTime = raceTime; Game::logger->Log("RacingControlComponent", - "Completed time %llu, %llu\n", + "Completed time %llu, %llu", raceTime, raceTime * 1000); // Entire race time @@ -870,12 +870,12 @@ void RacingControlComponent::Update(float deltaTime) { } Game::logger->Log("RacingControlComponent", - "Lapped (%i) in (%llu)\n", player.lap, + "Lapped (%i) in (%llu)", player.lap, lapTime); } Game::logger->Log("RacingControlComponent", - "Reached point (%i)/(%i)\n", player.respawnIndex, + "Reached point (%i)/(%i)", player.respawnIndex, path->pathWaypoints.size()); break; diff --git a/dGame/dComponents/RebuildComponent.cpp b/dGame/dComponents/RebuildComponent.cpp index 603a18cc..f2c2707f 100644 --- a/dGame/dComponents/RebuildComponent.cpp +++ b/dGame/dComponents/RebuildComponent.cpp @@ -28,12 +28,12 @@ RebuildComponent::RebuildComponent(Entity* entity) : Component(entity) { // Should a setting that has the build activator position exist, fetch that setting here and parse it for position. // It is assumed that the user who sets this setting uses the correct character delimiter (character 31 or in hex 0x1F) auto positionAsVector = GeneralUtils::SplitString(m_Parent->GetVarAsString(u"rebuild_activators"), 0x1F); - if (positionAsVector.size() == 3 && + if (positionAsVector.size() == 3 && GeneralUtils::TryParse(positionAsVector[0], m_ActivatorPosition.x) && - GeneralUtils::TryParse(positionAsVector[1], m_ActivatorPosition.y) && + GeneralUtils::TryParse(positionAsVector[1], m_ActivatorPosition.y) && GeneralUtils::TryParse(positionAsVector[2], m_ActivatorPosition.z)) { } else { - Game::logger->Log("RebuildComponent", "Failed to find activator position for lot %i. Defaulting to parents position.\n", m_Parent->GetLOT()); + Game::logger->Log("RebuildComponent", "Failed to find activator position for lot %i. Defaulting to parents position.", m_Parent->GetLOT()); m_ActivatorPosition = m_Parent->GetPosition(); } @@ -47,7 +47,7 @@ RebuildComponent::~RebuildComponent() { if (builder) { CancelRebuild(builder, eFailReason::REASON_BUILD_ENDED, true); } - + DespawnActivator(); } @@ -61,7 +61,7 @@ void RebuildComponent::Serialize(RakNet::BitStream* outBitStream, bool bIsInitia outBitStream->Write(false); } - // If build state is completed and we've already serialized once in the completed state, + // If build state is completed and we've already serialized once in the completed state, // don't serializing this component anymore as this will cause the build to jump again. // If state changes, serialization will begin again. if (!m_StateDirty && m_State == REBUILD_COMPLETED) { @@ -93,7 +93,7 @@ void RebuildComponent::Serialize(RakNet::BitStream* outBitStream, bool bIsInitia outBitStream->Write(m_ShowResetEffect); outBitStream->Write(m_Activator != nullptr); - + outBitStream->Write(m_Timer); outBitStream->Write(m_TimerIncomplete); @@ -146,7 +146,7 @@ void RebuildComponent::Update(float deltaTime) { } } } - + break; } case REBUILD_COMPLETED: { @@ -272,7 +272,7 @@ void RebuildComponent::SpawnActivator() { void RebuildComponent::DespawnActivator() { if (m_Activator) { EntityManager::Instance()->DestructEntity(m_Activator); - + m_Activator->ScheduleKillAfterUpdate(); m_Activator = nullptr; @@ -281,7 +281,7 @@ void RebuildComponent::DespawnActivator() { } } -Entity* RebuildComponent::GetActivator() +Entity* RebuildComponent::GetActivator() { return EntityManager::Instance()->GetEntity(m_ActivatorId); } @@ -431,13 +431,13 @@ void RebuildComponent::CompleteRebuild(Entity* user) { if (user == nullptr) { return; } - + auto* characterComponent = user->GetComponent(); if (characterComponent != nullptr) { characterComponent->SetCurrentActivity(eGameActivities::ACTIVITY_NONE); characterComponent->TrackRebuildComplete(); } else { - Game::logger->Log("RebuildComponent", "Some user tried to finish the rebuild but they didn't have a character somehow.\n"); + Game::logger->Log("RebuildComponent", "Some user tried to finish the rebuild but they didn't have a character somehow."); return; } @@ -447,7 +447,7 @@ void RebuildComponent::CompleteRebuild(Entity* user) { GameMessages::SendPlayFXEffect(m_Parent, 507, u"create", "BrickFadeUpVisCompleteEffect", LWOOBJID_EMPTY, 0.4f, 1.0f, true); GameMessages::SendEnableRebuild(m_Parent, false, false, true, eFailReason::REASON_NOT_GIVEN, m_ResetTime, user->GetObjectID()); GameMessages::SendTerminateInteraction(user->GetObjectID(), eTerminateType::FROM_INTERACTION, m_Parent->GetObjectID()); - + m_State = eRebuildState::REBUILD_COMPLETED; m_StateDirty = true; @@ -528,7 +528,7 @@ void RebuildComponent::ResetRebuild(bool failed) { m_TimerIncomplete = 0.0f; m_ShowResetEffect = false; m_DrainedImagination = 0; - + EntityManager::Instance()->SerializeEntity(m_Parent); // Notify scripts and possible subscribers diff --git a/dGame/dComponents/RocketLaunchpadControlComponent.cpp b/dGame/dComponents/RocketLaunchpadControlComponent.cpp index 357fb2d0..108335ae 100644 --- a/dGame/dComponents/RocketLaunchpadControlComponent.cpp +++ b/dGame/dComponents/RocketLaunchpadControlComponent.cpp @@ -57,7 +57,7 @@ void RocketLaunchpadControlComponent::Launch(Entity* originator, LWOMAPID mapId, auto* rocket = characterComponent->GetRocket(originator); if (!rocket) { - Game::logger->Log("RocketLaunchpadControlComponent", "Unable to find rocket!\n"); + Game::logger->Log("RocketLaunchpadControlComponent", "Unable to find rocket!"); return; } @@ -79,7 +79,7 @@ void RocketLaunchpadControlComponent::Launch(Entity* originator, LWOMAPID mapId, SetSelectedMapId(originator->GetObjectID(), zone); GameMessages::SendFireEventClientSide(m_Parent->GetObjectID(), originator->GetSystemAddress(), u"RocketEquipped", rocket->GetId(), cloneId, -1, originator->GetObjectID()); - + GameMessages::SendChangeObjectWorldState(rocket->GetId(), WORLDSTATE_ATTACHED, UNASSIGNED_SYSTEM_ADDRESS); EntityManager::Instance()->SerializeEntity(originator); diff --git a/dGame/dComponents/ScriptedActivityComponent.cpp b/dGame/dComponents/ScriptedActivityComponent.cpp index 4d62fb0b..edc6b70d 100644 --- a/dGame/dComponents/ScriptedActivityComponent.cpp +++ b/dGame/dComponents/ScriptedActivityComponent.cpp @@ -185,7 +185,7 @@ void ScriptedActivityComponent::PlayerLeave(LWOOBJID playerID) { delete lobby->players[i]; lobby->players[i] = nullptr; lobby->players.erase(lobby->players.begin() + i); - + return; } } @@ -246,7 +246,7 @@ void ScriptedActivityComponent::Update(float deltaTime) { // The timer has elapsed, start the instance if (lobby->timer <= 0.0f) { - Game::logger->Log("ScriptedActivityComponent", "Setting up instance.\n"); + Game::logger->Log("ScriptedActivityComponent", "Setting up instance."); ActivityInstance* instance = NewInstance(); LoadPlayersIntoInstance(instance, lobby->players); @@ -397,7 +397,7 @@ void ScriptedActivityComponent::ClearInstances() { m_Instances.clear(); } -ActivityPlayer* ScriptedActivityComponent::GetActivityPlayerData(LWOOBJID playerID) +ActivityPlayer* ScriptedActivityComponent::GetActivityPlayerData(LWOOBJID playerID) { for (auto* activityData : m_ActivityPlayers) { @@ -410,7 +410,7 @@ ActivityPlayer* ScriptedActivityComponent::GetActivityPlayerData(LWOOBJID player return nullptr; } -void ScriptedActivityComponent::RemoveActivityPlayerData(LWOOBJID playerID) +void ScriptedActivityComponent::RemoveActivityPlayerData(LWOOBJID playerID) { for (size_t i = 0; i < m_ActivityPlayers.size(); i++) { @@ -427,7 +427,7 @@ void ScriptedActivityComponent::RemoveActivityPlayerData(LWOOBJID playerID) } } -ActivityPlayer* ScriptedActivityComponent::AddActivityPlayerData(LWOOBJID playerID) +ActivityPlayer* ScriptedActivityComponent::AddActivityPlayerData(LWOOBJID playerID) { auto* data = GetActivityPlayerData(playerID); if (data != nullptr) @@ -515,7 +515,7 @@ void ActivityInstance::StartZone() { if (player == nullptr) return; - Game::logger->Log("UserManager", "Transferring %s to Zone %i (Instance %i | Clone %i | Mythran Shift: %s) with IP %s and Port %i\n", player->GetCharacter()->GetName().c_str(), zoneID, zoneInstance, zoneClone, mythranShift == true ? "true" : "false", serverIP.c_str(), serverPort); + Game::logger->Log("UserManager", "Transferring %s to Zone %i (Instance %i | Clone %i | Mythran Shift: %s) with IP %s and Port %i", player->GetCharacter()->GetName().c_str(), zoneID, zoneInstance, zoneClone, mythranShift == true ? "true" : "false", serverIP.c_str(), serverPort); if (player->GetCharacter()) { player->GetCharacter()->SetZoneID(zoneID); player->GetCharacter()->SetZoneInstance(zoneInstance); @@ -526,7 +526,7 @@ void ActivityInstance::StartZone() { return; }); } - + m_NextZoneCloneID++; } @@ -565,7 +565,7 @@ std::vector ActivityInstance::GetParticipants() const { if (entity != nullptr) entities.push_back(entity); } - + return entities; } diff --git a/dGame/dComponents/SkillComponent.cpp b/dGame/dComponents/SkillComponent.cpp index 7aa29523..608eced6 100644 --- a/dGame/dComponents/SkillComponent.cpp +++ b/dGame/dComponents/SkillComponent.cpp @@ -52,7 +52,7 @@ void SkillComponent::SyncPlayerSkill(const uint32_t skillUid, const uint32_t syn if (index == this->m_managedBehaviors.end()) { - Game::logger->Log("SkillComponent", "Failed to find skill with uid (%i)!\n", skillUid, syncId); + Game::logger->Log("SkillComponent", "Failed to find skill with uid (%i)!", skillUid, syncId); return; } @@ -81,7 +81,7 @@ void SkillComponent::SyncPlayerProjectile(const LWOOBJID projectileId, RakNet::B if (index == -1) { - Game::logger->Log("SkillComponent", "Failed to find projectile id (%llu)!\n", projectileId); + Game::logger->Log("SkillComponent", "Failed to find projectile id (%llu)!", projectileId); return; } @@ -95,7 +95,7 @@ void SkillComponent::SyncPlayerProjectile(const LWOOBJID projectileId, RakNet::B auto result = query.execQuery(); if (result.eof()) { - Game::logger->Log("SkillComponent", "Failed to find skill id for (%i)!\n", sync_entry.lot); + Game::logger->Log("SkillComponent", "Failed to find skill id for (%i)!", sync_entry.lot); return; } @@ -432,7 +432,7 @@ void SkillComponent::SyncProjectileCalculation(const ProjectileSyncEntry& entry) if (other == nullptr) { if (entry.branchContext.target != LWOOBJID_EMPTY) { - Game::logger->Log("SkillComponent", "Invalid projectile target (%llu)!\n", entry.branchContext.target); + Game::logger->Log("SkillComponent", "Invalid projectile target (%llu)!", entry.branchContext.target); } return; @@ -444,7 +444,7 @@ void SkillComponent::SyncProjectileCalculation(const ProjectileSyncEntry& entry) auto result = query.execQuery(); if (result.eof()) { - Game::logger->Log("SkillComponent", "Failed to find skill id for (%i)!\n", entry.lot); + Game::logger->Log("SkillComponent", "Failed to find skill id for (%i)!", entry.lot); return; } diff --git a/dGame/dGameMessages/GameMessageHandler.cpp b/dGame/dGameMessages/GameMessageHandler.cpp index 53cce60e..9cd8995a 100644 --- a/dGame/dGameMessages/GameMessageHandler.cpp +++ b/dGame/dGameMessages/GameMessageHandler.cpp @@ -30,7 +30,7 @@ using namespace std; void GameMessageHandler::HandleMessage(RakNet::BitStream* inStream, const SystemAddress& sysAddr, LWOOBJID objectID, GAME_MSG messageID) { - + CBITSTREAM // Get the entity @@ -40,7 +40,7 @@ void GameMessageHandler::HandleMessage(RakNet::BitStream* inStream, const System if (!entity) { - Game::logger->Log("GameMessageHandler", "Failed to find associated entity (%llu), aborting GM (%X)!\n", objectID, messageID); + Game::logger->Log("GameMessageHandler", "Failed to find associated entity (%llu), aborting GM (%X)!", objectID, messageID); return; } @@ -69,31 +69,31 @@ void GameMessageHandler::HandleMessage(RakNet::BitStream* inStream, const System case GAME_MSG_UN_EQUIP_ITEM: GameMessages::HandleUnequipItem(inStream, entity); break; - + case GAME_MSG_RESPOND_TO_MISSION: { GameMessages::HandleRespondToMission(inStream, entity); break; } - + case GAME_MSG_REQUEST_USE: { GameMessages::HandleRequestUse(inStream, entity, sysAddr); break; } - + case GAME_MSG_SET_FLAG: { GameMessages::HandleSetFlag(inStream, entity); break; } - + case GAME_MSG_HAS_BEEN_COLLECTED: { GameMessages::HandleHasBeenCollected(inStream, entity); break; } - + case GAME_MSG_PLAYER_LOADED: { GameMessages::SendRestoreToPostLoadStats(entity, sysAddr); entity->SetPlayerReadyForUpdates(); - + auto* player = dynamic_cast(entity); if (player != nullptr) { @@ -157,20 +157,20 @@ void GameMessageHandler::HandleMessage(RakNet::BitStream* inStream, const System character->OnZoneLoad(); } - Game::logger->Log("GameMessageHandler", "Player %s (%llu) loaded.\n", entity->GetCharacter()->GetName().c_str(), entity->GetObjectID()); + Game::logger->Log("GameMessageHandler", "Player %s (%llu) loaded.", entity->GetCharacter()->GetName().c_str(), entity->GetObjectID()); // After we've done our thing, tell the client they're ready GameMessages::SendPlayerReady(dZoneManager::Instance()->GetZoneControlObject(), sysAddr); GameMessages::SendPlayerReady(entity, sysAddr); - + break; } - + case GAME_MSG_REQUEST_LINKED_MISSION: { GameMessages::HandleRequestLinkedMission(inStream, entity); break; } - + case GAME_MSG_MISSION_DIALOGUE_OK: { GameMessages::HandleMissionDialogOK(inStream, entity); break; @@ -181,12 +181,12 @@ void GameMessageHandler::HandleMessage(RakNet::BitStream* inStream, const System //rejecting a mission offer. We dont need to do anything. This is just here to remove a warning in our logs :) break; } - + case GAME_MSG_REQUEST_PLATFORM_RESYNC: { GameMessages::HandleRequestPlatformResync(inStream, entity, sysAddr); break; } - + case GAME_MSG_FIRE_EVENT_SERVER_SIDE: { GameMessages::HandleFireEventServerSide(inStream, entity, sysAddr); break; @@ -206,7 +206,7 @@ void GameMessageHandler::HandleMessage(RakNet::BitStream* inStream, const System GameMessages::HandleActivityStateChangeRequest(inStream, entity); break; } - + case GAME_MSG_PARSE_CHAT_MESSAGE: { GameMessages::HandleParseChatMessage(inStream, entity, sysAddr); break; @@ -259,31 +259,31 @@ void GameMessageHandler::HandleMessage(RakNet::BitStream* inStream, const System if (skill_component != nullptr) { auto* bs = new RakNet::BitStream((unsigned char*) message.sBitStream.c_str(), message.sBitStream.size(), false); - + skill_component->SyncPlayerProjectile(message.i64LocalID, bs, message.i64TargetID); delete bs; } - + break; } - + case GAME_MSG_START_SKILL: { GameMessages::StartSkill startSkill = GameMessages::StartSkill(); startSkill.Deserialize(inStream); // inStream replaces &bitStream - + if (startSkill.skillID == 1561 || startSkill.skillID == 1562 || startSkill.skillID == 1541) return; MissionComponent* comp = entity->GetComponent(); if (comp) { comp->Progress(MissionTaskType::MISSION_TASK_TYPE_SKILL, startSkill.skillID); } - + CDSkillBehaviorTable* skillTable = CDClientManager::Instance()->GetTable("SkillBehavior"); unsigned int behaviorId = skillTable->GetSkillByID(startSkill.skillID).behaviorID; bool success = false; - + if (behaviorId > 0) { RakNet::BitStream * bs = new RakNet::BitStream((unsigned char *)startSkill.sBitStream.c_str(), startSkill.sBitStream.size(), false); @@ -295,10 +295,10 @@ void GameMessageHandler::HandleMessage(RakNet::BitStream* inStream, const System DestroyableComponent* destComp = entity->GetComponent(); destComp->SetImagination(destComp->GetImagination() - skillTable->GetSkillByID(startSkill.skillID).imaginationcost); } - + delete bs; } - + if (Game::server->GetZoneID() == 1302) { break; } @@ -345,7 +345,7 @@ void GameMessageHandler::HandleMessage(RakNet::BitStream* inStream, const System } //cout << buffer.str() << endl; - + if(usr != nullptr) { RakNet::BitStream * bs = new RakNet::BitStream((unsigned char *)sync.sBitStream.c_str(), sync.sBitStream.size(), false); @@ -378,7 +378,7 @@ void GameMessageHandler::HandleMessage(RakNet::BitStream* inStream, const System case GAME_MSG_MODULAR_BUILD_FINISH: GameMessages::HandleModularBuildFinish(inStream, entity, sysAddr); break; - + case GAME_MSG_PUSH_EQUIPPED_ITEMS_STATE: GameMessages::HandlePushEquippedItemsState(inStream, entity); break; @@ -386,7 +386,7 @@ void GameMessageHandler::HandleMessage(RakNet::BitStream* inStream, const System case GAME_MSG_POP_EQUIPPED_ITEMS_STATE: GameMessages::HandlePopEquippedItemsState(inStream, entity); break; - + case GAME_MSG_BUY_FROM_VENDOR: GameMessages::HandleBuyFromVendor(inStream, entity, sysAddr); break; @@ -477,7 +477,7 @@ void GameMessageHandler::HandleMessage(RakNet::BitStream* inStream, const System case GAME_MSG_COMMAND_PET: GameMessages::HandleCommandPet(inStream, entity, sysAddr); break; - + case GAME_MSG_DESPAWN_PET: GameMessages::HandleDespawnPet(inStream, entity, sysAddr); break; @@ -558,7 +558,7 @@ void GameMessageHandler::HandleMessage(RakNet::BitStream* inStream, const System case GAME_MSG_UPDATE_PROPERTY_OR_MODEL_FOR_FILTER_CHECK: GameMessages::HandleUpdatePropertyOrModelForFilterCheck(inStream, entity, sysAddr); break; - + case GAME_MSG_SET_PROPERTY_ACCESS: GameMessages::HandleSetPropertyAccess(inStream, entity, sysAddr); break; @@ -657,8 +657,8 @@ void GameMessageHandler::HandleMessage(RakNet::BitStream* inStream, const System GameMessages::HandleUpdatePlayerStatistic(inStream, entity); break; - default: - //Game::logger->Log("GameMessageHandler", "Unknown game message ID: %X\n", messageID); + default: + //Game::logger->Log("GameMessageHandler", "Unknown game message ID: %X", messageID); break; } } diff --git a/dGame/dGameMessages/GameMessages.cpp b/dGame/dGameMessages/GameMessages.cpp index 935a7ccb..365485f2 100644 --- a/dGame/dGameMessages/GameMessages.cpp +++ b/dGame/dGameMessages/GameMessages.cpp @@ -126,7 +126,7 @@ void GameMessages::SendTeleport(const LWOOBJID& objectID, const NiPoint3& pos, c void GameMessages::SendPlayAnimation(Entity* entity, const std::u16string& animationName, float fPriority, float fScale) { if (!entity) { - Game::logger->Log("SendPlayAnimation", "Trying to play animation, but entity var is nullptr!\n"); + Game::logger->Log("SendPlayAnimation", "Trying to play animation, but entity var is nullptr!"); return; } @@ -1613,7 +1613,7 @@ void GameMessages::HandleUpdateShootingGalleryRotation(RakNet::BitStream* inStre void GameMessages::HandleActivitySummaryLeaderboardData(RakNet::BitStream* instream, Entity* entity, const SystemAddress& sysAddr) { - Game::logger->Log("AGS", "We got mail!\n"); + Game::logger->Log("AGS", "We got mail!"); } void GameMessages::SendActivitySummaryLeaderboardData(const LWOOBJID& objectID, const Leaderboard* leaderboard, const SystemAddress& sysAddr) { @@ -1685,7 +1685,7 @@ void GameMessages::HandleActivityStateChangeRequest(RakNet::BitStream *inStream, auto* assosiate = EntityManager::Instance()->GetEntity(objectID); - Game::logger->Log("Activity State Change", "%s [%i, %i] from %i to %i\n", GeneralUtils::UTF16ToWTF8(stringValue).c_str(), value1, value2, entity->GetLOT(), assosiate != nullptr ? assosiate->GetLOT() : 0); + Game::logger->Log("Activity State Change", "%s [%i, %i] from %i to %i", GeneralUtils::UTF16ToWTF8(stringValue).c_str(), value1, value2, entity->GetLOT(), assosiate != nullptr ? assosiate->GetLOT() : 0); std::vector scriptedActs = EntityManager::Instance()->GetEntitiesByComponent(COMPONENT_TYPE_SHOOTING_GALLERY); for (Entity* scriptEntity : scriptedActs) { @@ -1985,7 +1985,7 @@ void GameMessages::SendDownloadPropertyData(const LWOOBJID objectId, const Prope data.Serialize(bitStream); - Game::logger->Log("SendDownloadPropertyData", "(%llu) sending property data (%d)\n", objectId, sysAddr == UNASSIGNED_SYSTEM_ADDRESS); + Game::logger->Log("SendDownloadPropertyData", "(%llu) sending property data (%d)", objectId, sysAddr == UNASSIGNED_SYSTEM_ADDRESS); if (sysAddr == UNASSIGNED_SYSTEM_ADDRESS) SEND_PACKET_BROADCAST; SEND_PACKET; @@ -2060,7 +2060,7 @@ void GameMessages::SendGetModelsOnProperty(LWOOBJID objectId, std::mapLog("SendGetModelsOnProperty", "Sending property models to (%llu) (%d)\n", objectId, sysAddr == UNASSIGNED_SYSTEM_ADDRESS); + Game::logger->Log("SendGetModelsOnProperty", "Sending property models to (%llu) (%d)", objectId, sysAddr == UNASSIGNED_SYSTEM_ADDRESS); if (sysAddr == UNASSIGNED_SYSTEM_ADDRESS) SEND_PACKET_BROADCAST; SEND_PACKET; @@ -2167,7 +2167,7 @@ void GameMessages::HandleSetPropertyAccess(RakNet::BitStream* inStream, Entity* inStream->Read(renewIsDefault); if (renewIsDefault != 0) inStream->Read(renew); - Game::logger->Log("GameMessages", "Set privacy option to: %i\n", accessType); + Game::logger->Log("GameMessages", "Set privacy option to: %i", accessType); if (PropertyManagementComponent::Instance() == nullptr) return; @@ -2211,7 +2211,7 @@ void GameMessages::HandleUpdatePropertyOrModelForFilterCheck(RakNet::BitStream* void GameMessages::HandleQueryPropertyData(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr) { - Game::logger->Log("HandleQueryPropertyData", "Entity (%i) requesting data\n", entity->GetLOT()); + Game::logger->Log("HandleQueryPropertyData", "Entity (%i) requesting data", entity->GetLOT()); /* auto entites = EntityManager::Instance()->GetEntitiesByComponent(COMPONENT_TYPE_PROPERTY_VENDOR); @@ -2270,7 +2270,7 @@ void GameMessages::HandleSetBuildMode(RakNet::BitStream* inStream, Entity* entit player->GetCharacter()->SetBuildMode(start); - Game::logger->Log("GameMessages", "Sending build mode confirm (%i): (%d) (%i) (%d) (%i) (%llu)\n", entity->GetLOT(), start, distanceType, modePaused, modeValue, playerId); + Game::logger->Log("GameMessages", "Sending build mode confirm (%i): (%d) (%i) (%d) (%i) (%llu)", entity->GetLOT(), start, distanceType, modePaused, modeValue, playerId); SendSetBuildModeConfirmed(entity->GetObjectID(), UNASSIGNED_SYSTEM_ADDRESS, start, false, modePaused, modeValue, playerId, startPosition); } @@ -2308,7 +2308,7 @@ void GameMessages::HandleStartBuildingWithItem(RakNet::BitStream* inStream, Enti sourceType = 4; } - Game::logger->Log("GameMessages", "Handling start building with item (%i): (%d) (%d) (%i) (%llu) (%i) (%i) (%llu) (%i) (%i)\n", entity->GetLOT(), firstTime, success, sourceBag, sourceId, sourceLot, sourceType, targetId, targetLot, targetType); + Game::logger->Log("GameMessages", "Handling start building with item (%i): (%d) (%d) (%i) (%llu) (%i) (%i) (%llu) (%i) (%i)", entity->GetLOT(), firstTime, success, sourceBag, sourceId, sourceLot, sourceType, targetId, targetLot, targetType); auto* user = UserManager::Instance()->GetUser(sysAddr); @@ -2408,7 +2408,7 @@ void GameMessages::HandleBBBLoadItemRequest(RakNet::BitStream* inStream, Entity* LWOOBJID itemID = LWOOBJID_EMPTY; inStream->Read(itemID); - Game::logger->Log("BBB", "Load item request for: " + std::to_string(itemID) + "\n"); + Game::logger->Log("BBB", "Load item request for: " + std::to_string(itemID) + ""); CBITSTREAM; PacketUtils::WriteHeader(bitStream, CLIENT, MSG_CLIENT_BLUEPRINT_LOAD_RESPONSE_ITEMID); @@ -2451,7 +2451,7 @@ void GameMessages::SendUnSmash(Entity* entity, LWOOBJID builderID, float duratio void GameMessages::HandleControlBehaviors(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr) { // TODO - Game::logger->Log("GameMessages", "Recieved Control Behavior GameMessage, but property behaviors are unimplemented.\n"); + Game::logger->Log("GameMessages", "Recieved Control Behavior GameMessage, but property behaviors are unimplemented."); } void GameMessages::HandleBBBSaveRequest(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr) { @@ -2531,7 +2531,7 @@ void GameMessages::HandleBBBSaveRequest(RakNet::BitStream* inStream, Entity* ent //int32_t size = ZCompression::Decompress(inData, lxfmlSize, outData, 327680, error); //if (size == -1) { - // Game::logger->Log("GameMessages", "Failed to decompress LXFML: (%i)\n", error); + // Game::logger->Log("GameMessages", "Failed to decompress LXFML: (%i)", error); // return; //} // @@ -3259,7 +3259,7 @@ void GameMessages::HandleClientTradeRequest(RakNet::BitStream* inStream, Entity* return; } - Game::logger->Log("GameMessages", "Trade request to (%llu)\n", i64Invitee); + Game::logger->Log("GameMessages", "Trade request to (%llu)", i64Invitee); auto* trade = TradingManager::Instance()->GetPlayerTrade(entity->GetObjectID()); @@ -3293,7 +3293,7 @@ void GameMessages::HandleClientTradeCancel(RakNet::BitStream* inStream, Entity* if (trade == nullptr) return; - Game::logger->Log("GameMessages", "Trade canceled from (%llu)\n", entity->GetObjectID()); + Game::logger->Log("GameMessages", "Trade canceled from (%llu)", entity->GetObjectID()); TradingManager::Instance()->CancelTrade(trade->GetTradeId()); } @@ -3302,7 +3302,7 @@ void GameMessages::HandleClientTradeAccept(RakNet::BitStream* inStream, Entity* { bool bFirst = inStream->ReadBit(); - Game::logger->Log("GameMessages", "Trade accepted from (%llu) -> (%d)\n", entity->GetObjectID(), bFirst); + Game::logger->Log("GameMessages", "Trade accepted from (%llu) -> (%d)", entity->GetObjectID(), bFirst); auto* trade = TradingManager::Instance()->GetPlayerTrade(entity->GetObjectID()); @@ -3319,7 +3319,7 @@ void GameMessages::HandleClientTradeUpdate(RakNet::BitStream* inStream, Entity* inStream->Read(currency); inStream->Read(itemCount); - Game::logger->Log("GameMessages", "Trade update from (%llu) -> (%llu), (%i)\n", entity->GetObjectID(), currency, itemCount); + Game::logger->Log("GameMessages", "Trade update from (%llu) -> (%llu), (%i)", entity->GetObjectID(), currency, itemCount); std::vector items {}; @@ -3375,7 +3375,7 @@ void GameMessages::HandleClientTradeUpdate(RakNet::BitStream* inStream, Entity* items.push_back({itemId, lot, unknown2}); - Game::logger->Log("GameMessages", "Trade item from (%llu) -> (%llu)/(%llu), (%i), (%llu), (%i), (%i)\n", entity->GetObjectID(), itemId, itemId2, lot, unknown1, unknown2, unknown3); + Game::logger->Log("GameMessages", "Trade item from (%llu) -> (%llu)/(%llu), (%i), (%llu), (%i), (%i)", entity->GetObjectID(), itemId, itemId2, lot, unknown1, unknown2, unknown3); } auto* trade = TradingManager::Instance()->GetPlayerTrade(entity->GetObjectID()); @@ -3848,7 +3848,7 @@ void GameMessages::HandleMessageBoxResponse(RakNet::BitStream* inStream, Entity* userData.push_back(character); } - Game::logger->Log("HandleMessageBoxResponse", "Button: " + std::to_string(iButton) + "; LOT: " + std::to_string(entity->GetLOT()) + " identifier: " + GeneralUtils::UTF16ToWTF8(identifier) + "; userData: " + GeneralUtils::UTF16ToWTF8(userData) + "\n"); + Game::logger->Log("HandleMessageBoxResponse", "Button: " + std::to_string(iButton) + "; LOT: " + std::to_string(entity->GetLOT()) + " identifier: " + GeneralUtils::UTF16ToWTF8(identifier) + "; userData: " + GeneralUtils::UTF16ToWTF8(userData)); auto* user = UserManager::Instance()->GetUser(sysAddr); @@ -3912,7 +3912,7 @@ void GameMessages::HandleChoiceBoxRespond(RakNet::BitStream* inStream, Entity* e identifier.push_back(character); } - Game::logger->Log("HandleChoiceBoxRespond", "Button: " + std::to_string(iButton) + "; LOT: " + std::to_string(entity->GetLOT()) + " buttonIdentifier: " + GeneralUtils::UTF16ToWTF8(buttonIdentifier) + "; userData: " + GeneralUtils::UTF16ToWTF8(identifier) + "\n"); + Game::logger->Log("HandleChoiceBoxRespond", "Button: " + std::to_string(iButton) + "; LOT: " + std::to_string(entity->GetLOT()) + " buttonIdentifier: " + GeneralUtils::UTF16ToWTF8(buttonIdentifier) + "; userData: " + GeneralUtils::UTF16ToWTF8(identifier)); auto* user = UserManager::Instance()->GetUser(sysAddr); @@ -4057,7 +4057,7 @@ void GameMessages::HandleDismountComplete(RakNet::BitStream* inStream, Entity* e void GameMessages::HandleAcknowledgePossession(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr) { - Game::logger->Log("HandleAcknowledgePossession", "Got AcknowledgePossession from %i\n", entity->GetLOT()); + Game::logger->Log("HandleAcknowledgePossession", "Got AcknowledgePossession from %i", entity->GetLOT()); EntityManager::Instance()->SerializeEntity(entity); } @@ -4067,11 +4067,11 @@ void GameMessages::HandleModuleAssemblyQueryData(RakNet::BitStream* inStream, En { auto* moduleAssemblyComponent = entity->GetComponent(); - Game::logger->Log("HandleModuleAssemblyQueryData", "Got Query from %i\n", entity->GetLOT()); + Game::logger->Log("HandleModuleAssemblyQueryData", "Got Query from %i", entity->GetLOT()); if (moduleAssemblyComponent != nullptr) { - Game::logger->Log("HandleModuleAssemblyQueryData", "Returning assembly %s\n", GeneralUtils::UTF16ToWTF8(moduleAssemblyComponent->GetAssemblyPartsLOTs()).c_str()); + Game::logger->Log("HandleModuleAssemblyQueryData", "Returning assembly %s", GeneralUtils::UTF16ToWTF8(moduleAssemblyComponent->GetAssemblyPartsLOTs()).c_str()); SendModuleAssemblyDBDataForClient(entity->GetObjectID(), moduleAssemblyComponent->GetSubKey(), moduleAssemblyComponent->GetAssemblyPartsLOTs(), UNASSIGNED_SYSTEM_ADDRESS); } @@ -4163,7 +4163,7 @@ void GameMessages::HandleRequestDie(RakNet::BitStream* inStream, Entity* entity, auto* racingControlComponent = zoneController->GetComponent(); - Game::logger->Log("HandleRequestDie", "Got die request: %i\n", entity->GetLOT()); + Game::logger->Log("HandleRequestDie", "Got die request: %i", entity->GetLOT()); if (racingControlComponent != nullptr) { @@ -4213,7 +4213,7 @@ void GameMessages::HandleRacingPlayerInfoResetFinished(RakNet::BitStream* inStre auto* racingControlComponent = zoneController->GetComponent(); - Game::logger->Log("HandleRacingPlayerInfoResetFinished", "Got finished: %i\n", entity->GetLOT()); + Game::logger->Log("HandleRacingPlayerInfoResetFinished", "Got finished: %i", entity->GetLOT()); if (racingControlComponent != nullptr) { @@ -5011,7 +5011,7 @@ void GameMessages::HandleFireEventServerSide(RakNet::BitStream* inStream, Entity mapId = dZoneManager::Instance()->GetZoneID().GetMapID(); // Fallback to sending the player back to the same zone. } - Game::logger->Log("FireEventServerSide", "Player %llu has requested zone transfer to (%i, %i).\n", sender->GetObjectID(), (int) mapId, (int) cloneId); + Game::logger->Log("FireEventServerSide", "Player %llu has requested zone transfer to (%i, %i).", sender->GetObjectID(), (int) mapId, (int) cloneId); auto* character = player->GetCharacter(); @@ -5020,7 +5020,7 @@ void GameMessages::HandleFireEventServerSide(RakNet::BitStream* inStream, Entity } ZoneInstanceManager::Instance()->RequestZoneTransfer(Game::server, mapId, cloneId, false, [=](bool mythranShift, uint32_t zoneID, uint32_t zoneInstance, uint32_t zoneClone, std::string serverIP, uint16_t serverPort) { - Game::logger->Log("UserManager", "Transferring %s to Zone %i (Instance %i | Clone %i | Mythran Shift: %s) with IP %s and Port %i\n", character->GetName().c_str(), zoneID, zoneInstance, zoneClone, mythranShift == true ? "true" : "false", serverIP.c_str(), serverPort); + Game::logger->Log("UserManager", "Transferring %s to Zone %i (Instance %i | Clone %i | Mythran Shift: %s) with IP %s and Port %i", character->GetName().c_str(), zoneID, zoneInstance, zoneClone, mythranShift == true ? "true" : "false", serverIP.c_str(), serverPort); if (character) { character->SetZoneID(zoneID); @@ -5071,7 +5071,7 @@ void GameMessages::HandleRequestUse(RakNet::BitStream* inStream, Entity* entity, if (interactedObject == nullptr) { - Game::logger->Log("GameMessages", "Object %llu tried to interact, but doesn't exist!\n", objectID); + Game::logger->Log("GameMessages", "Object %llu tried to interact, but doesn't exist!", objectID); return; } @@ -5117,7 +5117,7 @@ void GameMessages::HandlePlayEmote(RakNet::BitStream* inStream, Entity* entity) inStream->Read(emoteID); inStream->Read(targetID); - Game::logger->Log("GameMessages", "Emote (%i) (%llu)\n", emoteID, targetID); + Game::logger->Log("GameMessages", "Emote (%i) (%llu)", emoteID, targetID); //TODO: If targetID != 0, and we have one of the "perform emote" missions, complete them. @@ -5133,7 +5133,7 @@ void GameMessages::HandlePlayEmote(RakNet::BitStream* inStream, Entity* entity) { auto* targetEntity = EntityManager::Instance()->GetEntity(targetID); - Game::logger->Log("GameMessages", "Emote target found (%d)\n", targetEntity != nullptr); + Game::logger->Log("GameMessages", "Emote target found (%d)", targetEntity != nullptr); if (targetEntity != nullptr) { @@ -5218,7 +5218,7 @@ void GameMessages::HandleRespondToMission(RakNet::BitStream* inStream, Entity* e MissionComponent* missionComponent = static_cast(entity->GetComponent(COMPONENT_TYPE_MISSION)); if (!missionComponent) { - Game::logger->Log("GameMessages", "Unable to get mission component for entity %llu to handle RespondToMission\n", playerID); + Game::logger->Log("GameMessages", "Unable to get mission component for entity %llu to handle RespondToMission", playerID); return; } @@ -5227,13 +5227,13 @@ void GameMessages::HandleRespondToMission(RakNet::BitStream* inStream, Entity* e mission->SetReward(reward); } else { - Game::logger->Log("GameMessages", "Unable to get mission %i for entity %llu to update reward in RespondToMission\n", missionID, playerID); + Game::logger->Log("GameMessages", "Unable to get mission %i for entity %llu to update reward in RespondToMission", missionID, playerID); } Entity* offerer = EntityManager::Instance()->GetEntity(receiverID); if (offerer == nullptr) { - Game::logger->Log("GameMessages", "Unable to get receiver entity %llu for RespondToMission\n", receiverID); + Game::logger->Log("GameMessages", "Unable to get receiver entity %llu for RespondToMission", receiverID); return; } @@ -5262,7 +5262,7 @@ void GameMessages::HandleMissionDialogOK(RakNet::BitStream* inStream, Entity* en // Get the player's mission component MissionComponent* missionComponent = static_cast(player->GetComponent(COMPONENT_TYPE_MISSION)); if (!missionComponent) { - Game::logger->Log("GameMessages", "Unable to get mission component for entity %llu to handle MissionDialogueOK\n", player->GetObjectID()); + Game::logger->Log("GameMessages", "Unable to get mission component for entity %llu to handle MissionDialogueOK", player->GetObjectID()); return; } @@ -5608,7 +5608,7 @@ void GameMessages::HandleBuildModeSet(RakNet::BitStream* inStream, Entity* entit inStream->Read(bStart); // there's more here but we don't need it (for now?) - Game::logger->Log("GameMessages", "Set build mode to (%d) for (%llu)\n", bStart, entity->GetObjectID()); + Game::logger->Log("GameMessages", "Set build mode to (%d) for (%llu)", bStart, entity->GetObjectID()); if (entity->GetCharacter()) { entity->GetCharacter()->SetBuildMode(bStart); @@ -5623,7 +5623,7 @@ void GameMessages::HandleModularBuildFinish(RakNet::BitStream* inStream, Entity* InventoryComponent* inv = static_cast(character->GetComponent(COMPONENT_TYPE_INVENTORY)); if (!inv) return; - Game::logger->Log("GameMessages", "Build finished\n"); + Game::logger->Log("GameMessages", "Build finished"); GameMessages::SendFinishArrangingWithItem(character, entity->GetObjectID()); // kick them from modular build GameMessages::SendModularBuildEnd(character); // i dont know if this does anything but DLUv2 did it @@ -5753,7 +5753,7 @@ void GameMessages::HandleDoneArrangingWithItem(RakNet::BitStream* inStream, Enti /* Game::logger->Log("GameMessages", - "\nnewSourceBAG: %d\nnewSourceID: %llu\nnewSourceLOT: %d\nnewSourceTYPE: %d\nnewTargetID: %llu\nnewTargetLOT: %d\nnewTargetTYPE: %d\nnewTargetPOS: %f, %f, %f\noldItemBAG: %d\noldItemID: %llu\noldItemLOT: %d\noldItemTYPE: %d\n", + "\nnewSourceBAG: %d\nnewSourceID: %llu\nnewSourceLOT: %d\nnewSourceTYPE: %d\nnewTargetID: %llu\nnewTargetLOT: %d\nnewTargetTYPE: %d\nnewTargetPOS: %f, %f, %f\noldItemBAG: %d\noldItemID: %llu\noldItemLOT: %d\noldItemTYPE: %d", newSourceBAG, newSourceID, newSourceLOT, newSourceTYPE, newTargetID, newTargetLOT, newTargetTYPE, newTargetPOS.x, newTargetPOS.y, newTargetPOS.z, oldItemBAG, oldItemID, oldItemLOT, oldItemTYPE ); */ @@ -5771,15 +5771,15 @@ void GameMessages::HandleDoneArrangingWithItem(RakNet::BitStream* inStream, Enti else if (!entities.empty()) { buildArea = entities[0]; - Game::logger->Log("BuildBorderComponent", "Using PropertyPlaque\n"); + Game::logger->Log("BuildBorderComponent", "Using PropertyPlaque"); } else { - Game::logger->Log("BuildBorderComponent", "No build area found\n"); + Game::logger->Log("BuildBorderComponent", "No build area found"); return; } - Game::logger->Log("GameMessages", "Build area found: %llu\n", buildArea->GetObjectID()); + Game::logger->Log("GameMessages", "Build area found: %llu", buildArea->GetObjectID()); GameMessages::SendStartArrangingWithItem( character, @@ -5798,7 +5798,7 @@ void GameMessages::HandleDoneArrangingWithItem(RakNet::BitStream* inStream, Enti ); } - Game::logger->Log("GameMessages", "Done Arranging\n"); + Game::logger->Log("GameMessages", "Done Arranging"); //GenericInventory* models = inv->GetGenericInventory(MODELS); //GenericInventory* tempModels = inv->GetGenericInventory(TEMP_MODELS); @@ -5824,7 +5824,7 @@ void GameMessages::HandleModularBuildMoveAndEquip(RakNet::BitStream* inStream, E Entity* character = EntityManager::Instance()->GetEntity(user->GetLoggedInChar()); if (!character) return; - Game::logger->Log("GameMessages", "Build and move\n"); + Game::logger->Log("GameMessages", "Build and move"); LOT templateID; @@ -6014,7 +6014,7 @@ void GameMessages::SendGetHotPropertyData(RakNet::BitStream* inStream, Entity* e * [float] - performance cost * [timestamp] - time last published * [cloneid] - clone id - * + * */ // TODO This needs to be implemented when reputation is implemented for getting hot properties. /** @@ -6099,7 +6099,7 @@ void GameMessages::HandleReportBug(RakNet::BitStream* inStream, Entity* entity) delete insertBug; } catch (sql::SQLException& e) { - Game::logger->Log("HandleReportBug", "Couldn't save bug report! (%s)\n", e.what()); + Game::logger->Log("HandleReportBug", "Couldn't save bug report! (%s)", e.what()); } } diff --git a/dGame/dInventory/Inventory.cpp b/dGame/dInventory/Inventory.cpp index 53ff37b4..012bcacf 100644 --- a/dGame/dInventory/Inventory.cpp +++ b/dGame/dInventory/Inventory.cpp @@ -81,7 +81,7 @@ uint32_t Inventory::GetLotCount(const LOT lot) const void Inventory::SetSize(const uint32_t value) { free += static_cast(value) - static_cast(size); - + size = value; GameMessages::SendSetInventorySize(component->GetParent(), type, static_cast(size)); @@ -107,7 +107,7 @@ int32_t Inventory::FindEmptySlot() { newSize += 10u; } - + if (newSize > GetSize()) { SetSize(newSize); @@ -121,7 +121,7 @@ int32_t Inventory::FindEmptySlot() } const auto slots = GetSlots(); - + for (auto i = 0u; i < size; ++i) { if (slots.find(i) == slots.end()) @@ -133,15 +133,15 @@ int32_t Inventory::FindEmptySlot() return -1; } -int32_t Inventory::GetEmptySlots() +int32_t Inventory::GetEmptySlots() { return free; } -bool Inventory::IsSlotEmpty(int32_t slot) +bool Inventory::IsSlotEmpty(int32_t slot) { const auto slots = GetSlots(); - + const auto& index = slots.find(slot); return index == slots.end(); @@ -201,7 +201,7 @@ Item* Inventory::FindItemByLot(const LOT lot, const bool ignoreEquipped, const b Item* Inventory::FindItemBySlot(const uint32_t slot) const { const auto slots = GetSlots(); - + const auto index = slots.find(slot); if (index == slots.end()) @@ -228,21 +228,21 @@ Item* Inventory::FindItemBySubKey(LWOOBJID id) const void Inventory::AddManagedItem(Item* item) { const auto id = item->GetId(); - + if (items.find(id) != items.end()) { - Game::logger->Log("Inventory", "Attempting to add an item with an already present id (%llu)!\n", id); + Game::logger->Log("Inventory", "Attempting to add an item with an already present id (%llu)!", id); return; } - + const auto slots = GetSlots(); const auto slot = item->GetSlot(); if (slots.find(slot) != slots.end()) { - Game::logger->Log("Inventory", "Attempting to add an item with an already present slot (%i)!\n", slot); + Game::logger->Log("Inventory", "Attempting to add an item with an already present slot (%i)!", slot); return; } @@ -258,7 +258,7 @@ void Inventory::RemoveManagedItem(Item* item) if (items.find(id) == items.end()) { - Game::logger->Log("Inventory", "Attempting to remove an item with an invalid id (%llu), lot (%i)!\n", id, item->GetLot()); + Game::logger->Log("Inventory", "Attempting to remove an item with an invalid id (%llu), lot (%i)!", id, item->GetLot()); return; } @@ -277,7 +277,7 @@ eInventoryType Inventory::FindInventoryTypeForLot(const LOT lot) switch (itemType) { case eItemType::ITEM_TYPE_BRICK: return BRICKS; - + case eItemType::ITEM_TYPE_BEHAVIOR: return BEHAVIORS; @@ -289,7 +289,7 @@ eInventoryType Inventory::FindInventoryTypeForLot(const LOT lot) case eItemType::ITEM_TYPE_LOOT_MODEL: case eItemType::ITEM_TYPE_MOUNT: return MODELS; - + case eItemType::ITEM_TYPE_HAT: case eItemType::ITEM_TYPE_HAIR: case eItemType::ITEM_TYPE_NECK: @@ -307,7 +307,7 @@ eInventoryType Inventory::FindInventoryTypeForLot(const LOT lot) case eItemType::ITEM_TYPE_PACKAGE: case eItemType::ITEM_TYPE_CURRENCY: return ITEMS; - + case eItemType::ITEM_TYPE_QUEST_OBJECT: case eItemType::ITEM_TYPE_UNKNOWN: default: @@ -325,11 +325,11 @@ const CDItemComponent& Inventory::FindItemComponent(const LOT lot) if (componentId == 0) { - Game::logger->Log("Inventory", "Failed to find item component for (%i)!\n", lot); + Game::logger->Log("Inventory", "Failed to find item component for (%i)!", lot); return CDItemComponentTable::Default; } - + const auto& itemComponent = itemComponents->GetItemComponentByID(componentId); return itemComponent; @@ -344,7 +344,7 @@ bool Inventory::IsValidItem(const LOT lot) return componentId != 0; } -const std::vector& Inventory::GetAllGMItems() +const std::vector& Inventory::GetAllGMItems() { return m_GameMasterRestrictedItems; } diff --git a/dGame/dInventory/Item.cpp b/dGame/dInventory/Item.cpp index 0d254e5b..71ded509 100644 --- a/dGame/dInventory/Item.cpp +++ b/dGame/dInventory/Item.cpp @@ -20,7 +20,7 @@ Item::Item(const LWOOBJID id, const LOT lot, Inventory* inventory, const uint32_ { return; } - + this->id = id; this->lot = lot; this->inventory = inventory; @@ -32,7 +32,7 @@ Item::Item(const LWOOBJID id, const LOT lot, Inventory* inventory, const uint32_ this->info = &Inventory::FindItemComponent(lot); this->preconditions = new PreconditionExpression(this->info->reqPrecondition); this->subKey = subKey; - + inventory->AddManagedItem(this); } @@ -48,7 +48,7 @@ Item::Item( LWOOBJID subKey, bool bound, eLootSourceType lootSourceType) -{ +{ if (!Inventory::IsValidItem(lot)) { return; @@ -87,7 +87,7 @@ Item::Item( { Equip(); - Game::logger->Log("Item", "Move and equipped (%i) from (%i)\n", this->lot, this->inventory->GetType()); + Game::logger->Log("Item", "Move and equipped (%i) from (%i)", this->lot, this->inventory->GetType()); EntityManager::Instance()->SerializeEntity(inventory->GetComponent()->GetParent()); } @@ -154,7 +154,7 @@ void Item::SetCount(const uint32_t value, const bool silent, const bool disassem { return; } - + const auto delta = std::abs(static_cast(value) - static_cast(count)); const auto type = static_cast(info->itemType); @@ -169,11 +169,11 @@ void Item::SetCount(const uint32_t value, const bool silent, const bool disassem } } } - + if (!silent) { auto* entity = inventory->GetComponent()->GetParent(); - + if (value > count) { GameMessages::SendAddItemToInventoryClientSync(entity, entity->GetSystemAddress(), this, id, showFlyingLoot, delta, LWOOBJID_EMPTY, lootSourceType); @@ -217,7 +217,7 @@ void Item::SetBound(const bool value) bound = value; } -void Item::SetSubKey(LWOOBJID value) +void Item::SetSubKey(LWOOBJID value) { subKey = value; } @@ -271,14 +271,14 @@ bool Item::IsEquipped() const bool Item::Consume() { auto* skillsTable = CDClientManager::Instance()->GetTable("ObjectSkills"); - + auto skills = skillsTable->Query([=](const CDObjectSkills entry) { return entry.objectTemplate == static_cast(lot); }); auto success = false; - + for (auto& skill : skills) { if (skill.castOnType == 3) // Consumable type @@ -287,7 +287,7 @@ bool Item::Consume() } } - Game::logger->Log("Item", "Consumed (%i) / (%llu) with (%d)\n", lot, id, success); + Game::logger->Log("Item", "Consumed (%i) / (%llu) with (%d)", lot, id, success); GameMessages::SendUseItemResult(inventory->GetComponent()->GetParent(), lot, success); @@ -343,7 +343,7 @@ bool Item::UseNonEquip() LootGenerator::Instance().GiveLoot(inventory->GetComponent()->GetParent(), result, eLootSourceType::LOOT_SOURCE_CONSUMPTION); } - Game::logger->Log("Item", "Used (%i)\n", lot); + Game::logger->Log("Item", "Used (%i)", lot); inventory->GetComponent()->RemoveItem(lot, 1); } @@ -357,11 +357,11 @@ void Item::Disassemble(const eInventoryType inventoryType) if (data->GetKey() == u"assemblyPartLOTs") { auto modStr = data->GetValueAsString(); - + std::vector modArray; std::stringstream ssData(modStr); - + std::string token; const auto deliminator = '+'; @@ -369,7 +369,7 @@ void Item::Disassemble(const eInventoryType inventoryType) while (std::getline(ssData, token, deliminator)) { const auto modLot = std::stoi(token.substr(2, token.size() - 1)); - + modArray.push_back(modLot); } @@ -397,7 +397,7 @@ void Item::DisassembleModel() { return; } - + std::string renderAsset = result.fieldIsNull(0) ? "" : std::string(result.getStringField(0)); std::vector renderAssetSplit = GeneralUtils::SplitString(renderAsset, '\\'); @@ -410,7 +410,7 @@ void Item::DisassembleModel() { return; } - + std::stringstream data; data << file.rdbuf(); @@ -420,7 +420,7 @@ void Item::DisassembleModel() } auto* doc = new tinyxml2::XMLDocument(); - + if (!doc) { return; @@ -436,26 +436,26 @@ void Item::DisassembleModel() auto* lxfml = doc->FirstChildElement("LXFML"); auto* bricks = lxfml->FirstChildElement("Bricks"); std::string searchTerm = "Brick"; - + if (!bricks) { searchTerm = "Part"; bricks = lxfml->FirstChildElement("Scene")->FirstChildElement("Model")->FirstChildElement("Group"); - + if (!bricks) { return; } } - + auto* currentBrick = bricks->FirstChildElement(searchTerm.c_str()); while (currentBrick) { - if (currentBrick->Attribute("designID") != nullptr) + if (currentBrick->Attribute("designID") != nullptr) { parts.push_back(std::stoi(currentBrick->Attribute("designID"))); } - + currentBrick = currentBrick->NextSiblingElement(searchTerm.c_str()); } @@ -472,7 +472,7 @@ void Item::DisassembleModel() { continue; } - + GetInventory()->GetComponent()->AddItem(brickID[0].NDObjectID, 1, eLootSourceType::LOOT_SOURCE_DELETION); } } @@ -480,7 +480,7 @@ void Item::DisassembleModel() void Item::RemoveFromInventory() { UnEquip(); - + count = 0; inventory->RemoveManagedItem(this); diff --git a/dGame/dMission/Mission.cpp b/dGame/dMission/Mission.cpp index e51a6901..4e7a5826 100644 --- a/dGame/dMission/Mission.cpp +++ b/dGame/dMission/Mission.cpp @@ -35,7 +35,7 @@ Mission::Mission(MissionComponent* missionComponent, const uint32_t missionId) { info = missionsTable->GetPtrByMissionID(missionId); if (info == &CDMissionsTable::Default) { - Game::logger->Log("Missions", "Failed to find mission (%i)!\n", missionId); + Game::logger->Log("Missions", "Failed to find mission (%i)!", missionId); return; } @@ -491,7 +491,7 @@ void Mission::YieldRewards() { if (pair.second < 0 || (m_Reward > 0 && pair.first != m_Reward)) { continue; } - + // If a mission rewards zero of an item, make it reward 1. auto count = pair.second > 0 ? pair.second : 1; diff --git a/dGame/dMission/MissionTask.cpp b/dGame/dMission/MissionTask.cpp index 2dd59887..36051305 100644 --- a/dGame/dMission/MissionTask.cpp +++ b/dGame/dMission/MissionTask.cpp @@ -31,7 +31,7 @@ MissionTask::MissionTask(Mission* mission, CDMissionTasks* info, uint32_t mask) parameters.push_back(parameter); } } - + stream = std::istringstream(info->targetGroup); while (std::getline(stream, token, ',')) { @@ -61,14 +61,14 @@ void MissionTask::SetProgress(const uint32_t value, const bool echo) { return; } - + progress = value; if (!echo) { return; } - + auto* entity = mission->GetAssociate(); if (entity == nullptr) @@ -101,7 +101,7 @@ void MissionTask::AddProgress(int32_t value) { value = 0; } - + SetProgress(value); } @@ -211,7 +211,7 @@ void MissionTask::CheckCompletion() const void MissionTask::Progress(int32_t value, LWOOBJID associate, const std::string& targets, int32_t count) { if (IsComplete() && count > 0) return; - + const auto type = GetType(); if (count < 0) @@ -250,11 +250,11 @@ void MissionTask::Progress(int32_t value, LWOOBJID associate, const std::string& uint32_t lot; uint32_t collectionId; std::vector settings; - + switch (type) { case MissionTaskType::MISSION_TASK_TYPE_UNKNOWN: break; - + case MissionTaskType::MISSION_TASK_TYPE_ACTIVITY: { if (InAllTargets(value)) { @@ -265,7 +265,7 @@ void MissionTask::Progress(int32_t value, LWOOBJID associate, const std::string& entity = EntityManager::Instance()->GetEntity(associate); if (entity == nullptr) { if (associate != LWOOBJID_EMPTY) { - Game::logger->Log("MissionTask", "Failed to find associated entity (%llu)!\n", associate); + Game::logger->Log("MissionTask", "Failed to find associated entity (%llu)!", associate); } break; } @@ -305,12 +305,12 @@ void MissionTask::Progress(int32_t value, LWOOBJID associate, const std::string& case MissionTaskType::MISSION_TASK_TYPE_EMOTE: { if (!InParameters(value)) break; - + entity = EntityManager::Instance()->GetEntity(associate); if (entity == nullptr) { - Game::logger->Log("MissionTask", "Failed to find associated entity (%llu)!\n", associate); + Game::logger->Log("MissionTask", "Failed to find associated entity (%llu)!", associate); break; } @@ -320,10 +320,10 @@ void MissionTask::Progress(int32_t value, LWOOBJID associate, const std::string& if (GetTarget() != lot) break; AddProgress(count); - + break; } - + case MissionTaskType::MISSION_TASK_TYPE_SKILL: { // This is a complicated check because for some missions we need to check for the associate being in the parameters instead of the value being in the parameters. @@ -331,7 +331,7 @@ void MissionTask::Progress(int32_t value, LWOOBJID associate, const std::string& if (InParameters(value)) AddProgress(count); } else { if (InParameters(associate) && InAllTargets(value)) AddProgress(count); - } + } break; } @@ -373,19 +373,19 @@ void MissionTask::Progress(int32_t value, LWOOBJID associate, const std::string& AddProgress(count); unique.push_back(associate); - + break; } case MissionTaskType::MISSION_TASK_TYPE_ENVIRONMENT: { if (!InAllTargets(value)) break; - + entity = EntityManager::Instance()->GetEntity(associate); if (entity == nullptr) { - Game::logger->Log("MissionTask", "Failed to find associated entity (%llu)!\n", associate); + Game::logger->Log("MissionTask", "Failed to find associated entity (%llu)!", associate); break; } @@ -397,7 +397,7 @@ void MissionTask::Progress(int32_t value, LWOOBJID associate, const std::string& if (std::find(unique.begin(), unique.end(), collectionId) != unique.end()) break; unique.push_back(collectionId); - + SetProgress(unique.size()); auto* entity = mission->GetAssociate(); @@ -409,7 +409,7 @@ void MissionTask::Progress(int32_t value, LWOOBJID associate, const std::string& if (missionComponent == nullptr) break; missionComponent->AddCollectible(collectionId); - + break; } @@ -418,10 +418,10 @@ void MissionTask::Progress(int32_t value, LWOOBJID associate, const std::string& if (info->targetGroup != targets) break; AddProgress(count); - + break; } - + case MissionTaskType::MISSION_TASK_TYPE_RACING: { // The meaning of associate can be found in RacingTaskParam.h @@ -452,7 +452,7 @@ void MissionTask::Progress(int32_t value, LWOOBJID associate, const std::string& { // If the player did not crash during the race, progress this task by count. if (value != 0) break; - + AddProgress(count); } else if (associate == 4 || associate == 5 || associate == 14) @@ -495,7 +495,7 @@ void MissionTask::Progress(int32_t value, LWOOBJID associate, const std::string& break; } default: - Game::logger->Log("MissionTask", "Invalid mission task type (%i)!\n", static_cast(type)); + Game::logger->Log("MissionTask", "Invalid mission task type (%i)!", static_cast(type)); return; } diff --git a/dGame/dUtilities/Mail.cpp b/dGame/dUtilities/Mail.cpp index 7e77cd77..b15d3bb6 100644 --- a/dGame/dUtilities/Mail.cpp +++ b/dGame/dUtilities/Mail.cpp @@ -93,7 +93,7 @@ void Mail::SendMail(const LWOOBJID sender, const std::string& senderName, LWOOBJ delete ins; if (sysAddr == UNASSIGNED_SYSTEM_ADDRESS) return; // TODO: Echo to chat server - + SendNotification(sysAddr, 1); //Show the "one new mail" message } @@ -152,7 +152,7 @@ void Mail::HandleMailStuff(RakNet::BitStream* packet, const SystemAddress& sysAd Mail::HandleSendMail(packet, sysAddr, entity); break; default: - Game::logger->Log("Mail", "Unhandled and possibly undefined MailStuffID: %i\n", int(stuffID)); + Game::logger->Log("Mail", "Unhandled and possibly undefined MailStuffID: %i", int(stuffID)); } }); } @@ -264,10 +264,10 @@ void Mail::HandleSendMail(RakNet::BitStream* packet, const SystemAddress& sysAdd Mail::SendSendResponse(sysAddr, Mail::MailSendResponse::Success); entity->GetCharacter()->SetCoins(entity->GetCharacter()->GetCoins() - mailCost, eLootSourceType::LOOT_SOURCE_MAIL); - Game::logger->Log("Mail", "Seeing if we need to remove item with ID/count/LOT: %i %i %i\n", itemID, attachmentCount, itemLOT); + Game::logger->Log("Mail", "Seeing if we need to remove item with ID/count/LOT: %i %i %i", itemID, attachmentCount, itemLOT); if (inv && itemLOT != 0 && attachmentCount > 0 && item) { - Game::logger->Log("Mail", "Trying to remove item with ID/count/LOT: %i %i %i\n", itemID, attachmentCount, itemLOT); + Game::logger->Log("Mail", "Trying to remove item with ID/count/LOT: %i %i %i", itemID, attachmentCount, itemLOT); inv->RemoveItem(itemLOT, attachmentCount, INVALID, true); auto* missionCompoent = entity->GetComponent(); diff --git a/dGame/dUtilities/Preconditions.cpp b/dGame/dUtilities/Preconditions.cpp index 2e006ec4..1b442f49 100644 --- a/dGame/dUtilities/Preconditions.cpp +++ b/dGame/dUtilities/Preconditions.cpp @@ -29,7 +29,7 @@ Precondition::Precondition(const uint32_t condition) { this->count = 1; this->values = { 0 }; - Game::logger->Log("Precondition", "Failed to find precondition of id (%i)!\n", condition); + Game::logger->Log("Precondition", "Failed to find precondition of id (%i)!", condition); return; } diff --git a/dGame/dUtilities/SlashCommandHandler.cpp b/dGame/dUtilities/SlashCommandHandler.cpp index 4172884f..ecb3bbda 100644 --- a/dGame/dUtilities/SlashCommandHandler.cpp +++ b/dGame/dUtilities/SlashCommandHandler.cpp @@ -102,7 +102,7 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit break; } - //Game::logger->Log("SlashCommandHandler", "Received chat command \"%s\"\n", GeneralUtils::UTF16ToWTF8(command).c_str()); + //Game::logger->Log("SlashCommandHandler", "Received chat command \"%s\"", GeneralUtils::UTF16ToWTF8(command).c_str()); User* user = UserManager::Instance()->GetUser(sysAddr); if ((chatCommand == "setgmlevel" || chatCommand == "makegm" || chatCommand == "gmlevel") && user->GetMaxGMLevel() > GAME_MASTER_LEVEL_CIVILIAN) { @@ -145,7 +145,7 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit WorldPackets::SendGMLevelChange(sysAddr, success, user->GetMaxGMLevel(), entity->GetGMLevel(), level); GameMessages::SendChatModeUpdate(entity->GetObjectID(), level); entity->SetGMLevel(level); - Game::logger->Log("SlashCommandHandler", "User %s (%i) has changed their GM level to %i for charID %llu\n", user->GetUsername().c_str(), user->GetAccountID(), level, entity->GetObjectID()); + Game::logger->Log("SlashCommandHandler", "User %s (%i) has changed their GM level to %i for charID %llu", user->GetUsername().c_str(), user->GetAccountID(), level, entity->GetObjectID()); } } @@ -170,7 +170,7 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit auto* character = entity->GetComponent(); if (character == nullptr) { - Game::logger->Log("SlashCommandHandler", "Failed to find character component!\n"); + Game::logger->Log("SlashCommandHandler", "Failed to find character component!"); return; } @@ -289,7 +289,7 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit args.InsertValue("visible", new AMFTrueValue()); args.InsertValue("text", text); - Game::logger->Log("SlashCommandHandler", "Sending \n%s\n", customText.c_str()); + Game::logger->Log("SlashCommandHandler", "Sending %s", customText.c_str()); GameMessages::SendUIMessageServerToSingleClient(entity, entity->GetSystemAddress(), "ToggleStoryBox", &args); }); @@ -324,7 +324,7 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit const auto sysAddr = entity->GetSystemAddress(); - Game::logger->Log("UserManager", "Transferring %s to Zone %i (Instance %i | Clone %i | Mythran Shift: %s) with IP %s and Port %i\n", entity->GetCharacter()->GetName().c_str(), zoneID, zoneInstance, zoneClone, mythranShift == true ? "true" : "false", serverIP.c_str(), serverPort); + Game::logger->Log("UserManager", "Transferring %s to Zone %i (Instance %i | Clone %i | Mythran Shift: %s) with IP %s and Port %i", entity->GetCharacter()->GetName().c_str(), zoneID, zoneInstance, zoneClone, mythranShift == true ? "true" : "false", serverIP.c_str(), serverPort); if (entity->GetCharacter()) { entity->GetCharacter()->SetZoneID(zoneID); @@ -344,7 +344,7 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit ZoneInstanceManager::Instance()->RequestPrivateZone(Game::server, false, password, [=](bool mythranShift, uint32_t zoneID, uint32_t zoneInstance, uint32_t zoneClone, std::string serverIP, uint16_t serverPort) { - Game::logger->Log("UserManager", "Transferring %s to Zone %i (Instance %i | Clone %i | Mythran Shift: %s) with IP %s and Port %i\n", sysAddr.ToString(), zoneID, zoneInstance, zoneClone, mythranShift == true ? "true" : "false", serverIP.c_str(), serverPort); + Game::logger->Log("UserManager", "Transferring %s to Zone %i (Instance %i | Clone %i | Mythran Shift: %s) with IP %s and Port %i", sysAddr.ToString(), zoneID, zoneInstance, zoneClone, mythranShift == true ? "true" : "false", serverIP.c_str(), serverPort); if (entity->GetCharacter()) { entity->GetCharacter()->SetZoneID(zoneID); @@ -920,7 +920,7 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit pos.SetY(y); pos.SetZ(z); - Game::logger->Log("SlashCommandHandler", "Teleporting objectID: %llu to %f, %f, %f\n", entity->GetObjectID(), pos.x, pos.y, pos.z); + Game::logger->Log("SlashCommandHandler", "Teleporting objectID: %llu to %f, %f, %f", entity->GetObjectID(), pos.x, pos.y, pos.z); GameMessages::SendTeleport(entity->GetObjectID(), pos, NiQuaternion(), sysAddr); } else if (args.size() == 2) { @@ -942,7 +942,7 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit pos.SetY(0.0f); pos.SetZ(z); - Game::logger->Log("SlashCommandHandler", "Teleporting objectID: %llu to X: %f, Z: %f\n", entity->GetObjectID(), pos.x, pos.z); + Game::logger->Log("SlashCommandHandler", "Teleporting objectID: %llu to X: %f, Z: %f", entity->GetObjectID(), pos.x, pos.z); GameMessages::SendTeleport(entity->GetObjectID(), pos, NiQuaternion(), sysAddr); } else { ChatPackets::SendSystemMessage(sysAddr, u"Correct usage: /teleport () - if no Y given, will teleport to the height of the terrain (or any physics object)."); @@ -964,7 +964,7 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit EntityManager::Instance()->SerializeEntity(possassableEntity); - Game::logger->Log("ClientPackets", "Forced updated vehicle position\n"); + Game::logger->Log("ClientPackets", "Forced updated vehicle position"); } } } @@ -1522,7 +1522,7 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit ChatPackets::SendSystemMessage(sysAddr, u"Transfering map..."); - Game::logger->Log("UserManager", "Transferring %s to Zone %i (Instance %i | Clone %i | Mythran Shift: %s) with IP %s and Port %i\n", sysAddr.ToString(), zoneID, zoneInstance, zoneClone, mythranShift == true ? "true" : "false", serverIP.c_str(), serverPort); + Game::logger->Log("UserManager", "Transferring %s to Zone %i (Instance %i | Clone %i | Mythran Shift: %s) with IP %s and Port %i", sysAddr.ToString(), zoneID, zoneInstance, zoneClone, mythranShift == true ? "true" : "false", serverIP.c_str(), serverPort); if (entity->GetCharacter()) { entity->GetCharacter()->SetZoneID(zoneID); entity->GetCharacter()->SetZoneInstance(zoneInstance); diff --git a/dGame/dUtilities/VanityUtilities.cpp b/dGame/dUtilities/VanityUtilities.cpp index c3f8f6b4..1b85077b 100644 --- a/dGame/dUtilities/VanityUtilities.cpp +++ b/dGame/dUtilities/VanityUtilities.cpp @@ -48,7 +48,7 @@ void VanityUtilities::SpawnVanity() std::vector npcList = m_NPCs; std::vector taken = {}; - Game::logger->Log("VanityUtilities", "Spawning party with %i locations\n", party.m_Locations.size()); + Game::logger->Log("VanityUtilities", "Spawning party with %i locations", party.m_Locations.size()); // Loop through all locations for (const auto& location : party.m_Locations) { @@ -187,7 +187,7 @@ void VanityUtilities::ParseXML(const std::string& file) auto* npcs = doc.FirstChildElement("npcs"); if (npcs == nullptr) { - Game::logger->Log("VanityUtilities", "Failed to parse NPCs\n"); + Game::logger->Log("VanityUtilities", "Failed to parse NPCs"); return; } @@ -211,7 +211,7 @@ void VanityUtilities::ParseXML(const std::string& file) auto* locations = party->FirstChildElement("locations"); if (locations == nullptr) { - Game::logger->Log("VanityUtilities", "Failed to parse party locations\n"); + Game::logger->Log("VanityUtilities", "Failed to parse party locations"); continue; } @@ -228,7 +228,7 @@ void VanityUtilities::ParseXML(const std::string& file) if (x == nullptr || y == nullptr || z == nullptr || rw == nullptr || rx == nullptr || ry == nullptr || rz == nullptr) { - Game::logger->Log("VanityUtilities", "Failed to parse party location data\n"); + Game::logger->Log("VanityUtilities", "Failed to parse party location data"); continue; } @@ -246,7 +246,7 @@ void VanityUtilities::ParseXML(const std::string& file) auto* partyPhrases = npcs->FirstChildElement("partyphrases"); if (partyPhrases == nullptr) { - Game::logger->Log("VanityUtilities", "Failed to parse party phrases\n"); + Game::logger->Log("VanityUtilities", "Failed to parse party phrases"); return; } @@ -256,7 +256,7 @@ void VanityUtilities::ParseXML(const std::string& file) auto* text = phrase->GetText(); if (text == nullptr) { - Game::logger->Log("VanityUtilities", "Failed to parse party phrase\n"); + Game::logger->Log("VanityUtilities", "Failed to parse party phrase"); continue; } @@ -268,7 +268,7 @@ void VanityUtilities::ParseXML(const std::string& file) auto* name = npc->Attribute("name"); if (name == nullptr) { - Game::logger->Log("VanityUtilities", "Failed to parse NPC name\n"); + Game::logger->Log("VanityUtilities", "Failed to parse NPC name"); continue; } @@ -276,7 +276,7 @@ void VanityUtilities::ParseXML(const std::string& file) auto* lot = npc->Attribute("lot"); if (lot == nullptr) { - Game::logger->Log("VanityUtilities", "Failed to parse NPC lot\n"); + Game::logger->Log("VanityUtilities", "Failed to parse NPC lot"); continue; } @@ -284,7 +284,7 @@ void VanityUtilities::ParseXML(const std::string& file) auto* equipment = npc->FirstChildElement("equipment"); if (equipment == nullptr) { - Game::logger->Log("VanityUtilities", "Failed to parse NPC equipment\n"); + Game::logger->Log("VanityUtilities", "Failed to parse NPC equipment"); continue; } @@ -306,7 +306,7 @@ void VanityUtilities::ParseXML(const std::string& file) auto* phrases = npc->FirstChildElement("phrases"); if (phrases == nullptr) { - Game::logger->Log("VanityUtilities", "Failed to parse NPC phrases\n"); + Game::logger->Log("VanityUtilities", "Failed to parse NPC phrases"); continue; } @@ -318,7 +318,7 @@ void VanityUtilities::ParseXML(const std::string& file) auto* text = phrase->GetText(); if (text == nullptr) { - Game::logger->Log("VanityUtilities", "Failed to parse NPC phrase\n"); + Game::logger->Log("VanityUtilities", "Failed to parse NPC phrase"); continue; } @@ -334,7 +334,7 @@ void VanityUtilities::ParseXML(const std::string& file) auto* scriptNameAttribute = scriptElement->Attribute("name"); if (scriptNameAttribute == nullptr) { - Game::logger->Log("VanityUtilities", "Failed to parse NPC script name\n"); + Game::logger->Log("VanityUtilities", "Failed to parse NPC script name"); continue; } @@ -358,7 +358,7 @@ void VanityUtilities::ParseXML(const std::string& file) auto* name = flag->Attribute("name"); if (name == nullptr) { - Game::logger->Log("VanityUtilities", "Failed to parse NPC flag name\n"); + Game::logger->Log("VanityUtilities", "Failed to parse NPC flag name"); continue; } @@ -366,7 +366,7 @@ void VanityUtilities::ParseXML(const std::string& file) auto* value = flag->Attribute("value"); if (value == nullptr) { - Game::logger->Log("VanityUtilities", "Failed to parse NPC flag value\n"); + Game::logger->Log("VanityUtilities", "Failed to parse NPC flag value"); continue; } @@ -380,7 +380,7 @@ void VanityUtilities::ParseXML(const std::string& file) auto* zoneID = zone->Attribute("id"); if (zoneID == nullptr) { - Game::logger->Log("VanityUtilities", "Failed to parse NPC zone ID\n"); + Game::logger->Log("VanityUtilities", "Failed to parse NPC zone ID"); continue; } @@ -388,7 +388,7 @@ void VanityUtilities::ParseXML(const std::string& file) auto* locations = zone->FirstChildElement("locations"); if (locations == nullptr) { - Game::logger->Log("VanityUtilities", "Failed to parse NPC locations\n"); + Game::logger->Log("VanityUtilities", "Failed to parse NPC locations"); continue; } @@ -405,7 +405,7 @@ void VanityUtilities::ParseXML(const std::string& file) if (x == nullptr || y == nullptr || z == nullptr || rw == nullptr || rx == nullptr || ry == nullptr || rz == nullptr) { - Game::logger->Log("VanityUtilities", "Failed to parse NPC location data\n"); + Game::logger->Log("VanityUtilities", "Failed to parse NPC location data"); continue; } diff --git a/dMasterServer/InstanceManager.cpp b/dMasterServer/InstanceManager.cpp index 7df1449f..2c4c3287 100644 --- a/dMasterServer/InstanceManager.cpp +++ b/dMasterServer/InstanceManager.cpp @@ -26,7 +26,7 @@ InstanceManager::~InstanceManager() { } Instance * InstanceManager::GetInstance(LWOMAPID mapID, bool isFriendTransfer, LWOCLONEID cloneID) { - mLogger->Log("InstanceManager", "Searching for an instance for mapID %i/%i\n", mapID, cloneID); + mLogger->Log("InstanceManager", "Searching for an instance for mapID %i/%i", mapID, cloneID); Instance* instance = FindInstance(mapID, isFriendTransfer, cloneID); if (instance) return instance; @@ -78,10 +78,10 @@ Instance * InstanceManager::GetInstance(LWOMAPID mapID, bool isFriendTransfer, L m_Instances.push_back(instance); if (instance) { - mLogger->Log("InstanceManager", "Created new instance: %i/%i/%i with min/max %i/%i\n", mapID, m_LastInstanceID, cloneID, softCap, maxPlayers); + mLogger->Log("InstanceManager", "Created new instance: %i/%i/%i with min/max %i/%i", mapID, m_LastInstanceID, cloneID, softCap, maxPlayers); return instance; } - else mLogger->Log("InstanceManager", "Failed to create a new instance!\n"); + else mLogger->Log("InstanceManager", "Failed to create a new instance!"); return nullptr; } @@ -92,7 +92,7 @@ bool InstanceManager::IsPortInUse(uint32_t port) { return true; } } - + return false; } @@ -102,7 +102,7 @@ uint32_t InstanceManager::GetFreePort() { for (Instance* i : m_Instances) { usedPorts.push_back(i->GetPort()); } - + std::sort(usedPorts.begin(), usedPorts.end()); int portIdx = 0; @@ -142,7 +142,7 @@ std::vector InstanceManager::GetInstances() const void InstanceManager::AddInstance(Instance* instance) { if (instance == nullptr) return; - + m_Instances.push_back(instance); } @@ -152,9 +152,9 @@ void InstanceManager::RemoveInstance(Instance* instance) { if (m_Instances[i] == instance) { instance->SetShutdownComplete(true); - + RedirectPendingRequests(instance); - + delete m_Instances[i]; m_Instances.erase(m_Instances.begin() + i); @@ -174,7 +174,7 @@ void InstanceManager::ReadyInstance(Instance* instance) { const auto& zoneId = instance->GetZoneID(); - Game::logger->Log("InstanceManager", "Responding to pending request %llu -> %i (%i)\n", request, zoneId.GetMapID(), zoneId.GetCloneID()); + Game::logger->Log("InstanceManager", "Responding to pending request %llu -> %i (%i)", request, zoneId.GetMapID(), zoneId.GetCloneID()); MasterPackets::SendZoneTransferResponse( Game::server, @@ -188,7 +188,7 @@ void InstanceManager::ReadyInstance(Instance* instance) instance->GetPort() ); } - + pending.clear(); } @@ -201,10 +201,10 @@ void InstanceManager::RequestAffirmation(Instance* instance, const PendingInstan PacketUtils::WriteHeader(bitStream, MASTER, MSG_MASTER_AFFIRM_TRANSFER_REQUEST); bitStream.Write(request.id); - + Game::server->Send(&bitStream, instance->GetSysAddr(), false); - - Game::logger->Log("MasterServer", "Sent affirmation request %llu to %i/%i\n", request.id, + + Game::logger->Log("MasterServer", "Sent affirmation request %llu to %i/%i", request.id, static_cast(instance->GetZoneID().GetMapID()), static_cast(instance->GetZoneID().GetCloneID()) ); @@ -217,7 +217,7 @@ void InstanceManager::AffirmTransfer(Instance* instance, const uint64_t transfer for (auto i = 0u; i < pending.size(); ++i) { const auto& request = pending[i]; - + if (request.id != transferID) continue; const auto& zoneId = instance->GetZoneID(); @@ -233,7 +233,7 @@ void InstanceManager::AffirmTransfer(Instance* instance, const uint64_t transfer instance->GetIP(), instance->GetPort() ); - + pending.erase(pending.begin() + i); break; @@ -243,7 +243,7 @@ void InstanceManager::AffirmTransfer(Instance* instance, const uint64_t transfer void InstanceManager::RedirectPendingRequests(Instance* instance) { const auto& zoneId = instance->GetZoneID(); - + for (const auto& request : instance->GetPendingAffirmations()) { auto* in = Game::im->GetInstance(zoneId.GetMapID(), false, zoneId.GetCloneID()); @@ -270,11 +270,11 @@ Instance* InstanceManager::GetInstanceBySysAddr(SystemAddress& sysAddr) { } bool InstanceManager::IsInstanceFull(Instance* instance, bool isFriendTransfer) { - if (!isFriendTransfer && instance->GetSoftCap() > instance->GetCurrentClientCount()) + if (!isFriendTransfer && instance->GetSoftCap() > instance->GetCurrentClientCount()) return false; - else if (isFriendTransfer && instance->GetHardCap() > instance->GetCurrentClientCount()) + else if (isFriendTransfer && instance->GetHardCap() > instance->GetCurrentClientCount()) return false; - + return true; } @@ -308,7 +308,7 @@ Instance* InstanceManager::CreatePrivateInstance(LWOMAPID mapID, LWOCLONEID clon } int maxPlayers = 999; - + uint32_t port = GetFreePort(); instance = new Instance(mExternalIP, port, mapID, ++m_LastInstanceID, cloneID, maxPlayers, maxPlayers, true, password); @@ -339,7 +339,7 @@ Instance* InstanceManager::CreatePrivateInstance(LWOMAPID mapID, LWOCLONEID clon m_Instances.push_back(instance); if (instance) return instance; - else mLogger->Log("InstanceManager", "Failed to create a new instance!\n"); + else mLogger->Log("InstanceManager", "Failed to create a new instance!"); return instance; } @@ -355,7 +355,7 @@ Instance* InstanceManager::FindPrivateInstance(const std::string& password) continue; } - mLogger->Log("InstanceManager", "Password: %s == %s => %d\n", password.c_str(), instance->GetPassword().c_str(), password == instance->GetPassword()); + mLogger->Log("InstanceManager", "Password: %s == %s => %d", password.c_str(), instance->GetPassword().c_str(), password == instance->GetPassword()); if (instance->GetPassword() == password) { @@ -375,7 +375,7 @@ int InstanceManager::GetSoftCap(LWOMAPID mapID) { return zone->population_soft_cap; } } - + return 8; } @@ -405,10 +405,10 @@ bool Instance::GetShutdownComplete() const void Instance::Shutdown() { CBITSTREAM; - + PacketUtils::WriteHeader(bitStream, MASTER, MSG_MASTER_SHUTDOWN); Game::server->Send(&bitStream, this->m_SysAddr, false); - - Game::logger->Log("Instance", "Triggered world shutdown\n"); + + Game::logger->Log("Instance", "Triggered world shutdown"); } diff --git a/dMasterServer/MasterServer.cpp b/dMasterServer/MasterServer.cpp index f71fd408..e679940b 100644 --- a/dMasterServer/MasterServer.cpp +++ b/dMasterServer/MasterServer.cpp @@ -75,16 +75,16 @@ int main(int argc, char** argv) { Game::logger = SetupLogger(); if (!Game::logger) return EXIT_FAILURE; - Game::logger->Log("MasterServer", "Starting Master server...\n"); - Game::logger->Log("MasterServer", "Version: %i.%i\n", PROJECT_VERSION_MAJOR, PROJECT_VERSION_MINOR); - Game::logger->Log("MasterServer", "Compiled on: %s\n", __TIMESTAMP__); + Game::logger->Log("MasterServer", "Starting Master server..."); + Game::logger->Log("MasterServer", "Version: %i.%i", PROJECT_VERSION_MAJOR, PROJECT_VERSION_MINOR); + Game::logger->Log("MasterServer", "Compiled on: %s", __TIMESTAMP__); //Read our config: dConfig config("masterconfig.ini"); Game::config = &config; Game::logger->SetLogToConsole(bool(std::stoi(config.GetValue("log_to_console")))); Game::logger->SetLogDebugStatements(config.GetValue("log_debug_statements") == "1"); - + if (argc > 1 && (strcmp(argv[1], "-m") == 0 || strcmp(argv[1], "--migrations") == 0)) { //Connect to the MySQL Database std::string mysql_host = config.GetValue("mysql_host"); @@ -95,23 +95,23 @@ int main(int argc, char** argv) { try { Database::Connect(mysql_host, mysql_database, mysql_username, mysql_password); } catch (sql::SQLException& ex) { - Game::logger->Log("MasterServer", "Got an error while connecting to the database: %s\n", ex.what()); - Game::logger->Log("MigrationRunner", "Migrations not run\n"); + Game::logger->Log("MasterServer", "Got an error while connecting to the database: %s", ex.what()); + Game::logger->Log("MigrationRunner", "Migrations not run"); return EXIT_FAILURE; } MigrationRunner::RunMigrations(); - Game::logger->Log("MigrationRunner", "Finished running migrations\n"); + Game::logger->Log("MigrationRunner", "Finished running migrations"); return EXIT_SUCCESS; - } + } else { //Check CDClient exists const std::string cdclient_path = "./res/CDServer.sqlite"; std::ifstream cdclient_fd(cdclient_path); if (!cdclient_fd.good()) { - Game::logger->Log("WorldServer", "%s could not be opened\n", cdclient_path.c_str()); + Game::logger->Log("WorldServer", "%s could not be opened", cdclient_path.c_str()); return EXIT_FAILURE; } cdclient_fd.close(); @@ -120,9 +120,9 @@ int main(int argc, char** argv) { try { CDClientDatabase::Connect(cdclient_path); } catch (CppSQLite3Exception& e) { - Game::logger->Log("WorldServer", "Unable to connect to CDServer SQLite Database\n"); - Game::logger->Log("WorldServer", "Error: %s\n", e.errorMessage()); - Game::logger->Log("WorldServer", "Error Code: %i\n", e.errorCode()); + Game::logger->Log("WorldServer", "Unable to connect to CDServer SQLite Database"); + Game::logger->Log("WorldServer", "Error: %s", e.errorMessage()); + Game::logger->Log("WorldServer", "Error Code: %i", e.errorCode()); return EXIT_FAILURE; } @@ -130,10 +130,10 @@ int main(int argc, char** argv) { try { CDClientManager::Instance()->Initialize(); } catch (CppSQLite3Exception& e) { - Game::logger->Log("WorldServer", "Failed to initialize CDServer SQLite Database\n"); - Game::logger->Log("WorldServer", "May be caused by corrupted file: %s\n", cdclient_path.c_str()); - Game::logger->Log("WorldServer", "Error: %s\n", e.errorMessage()); - Game::logger->Log("WorldServer", "Error Code: %i\n", e.errorCode()); + Game::logger->Log("WorldServer", "Failed to initialize CDServer SQLite Database"); + Game::logger->Log("WorldServer", "May be caused by corrupted file: %s", cdclient_path.c_str()); + Game::logger->Log("WorldServer", "Error: %s", e.errorMessage()); + Game::logger->Log("WorldServer", "Error Code: %i", e.errorCode()); return EXIT_FAILURE; } @@ -146,7 +146,7 @@ int main(int argc, char** argv) { try { Database::Connect(mysql_host, mysql_database, mysql_username, mysql_password); } catch (sql::SQLException& ex) { - Game::logger->Log("MasterServer", "Got an error while connecting to the database: %s\n", ex.what()); + Game::logger->Log("MasterServer", "Got an error while connecting to the database: %s", ex.what()); return EXIT_FAILURE; } } @@ -368,14 +368,14 @@ dLogger* SetupLogger() { void HandlePacket(Packet* packet) { if (packet->data[0] == ID_DISCONNECTION_NOTIFICATION) { - Game::logger->Log("MasterServer", "A server has disconnected\n"); + Game::logger->Log("MasterServer", "A server has disconnected"); //Since this disconnection is intentional, we'll just delete it as //we'll start a new one anyway if needed: Instance* instance = Game::im->GetInstanceBySysAddr(packet->systemAddress); if (instance) { - Game::logger->Log("MasterServer", "Actually disconnected from zone %i clone %i instance %i port %i\n", instance->GetMapID(), instance->GetCloneID(), instance->GetInstanceID(), instance->GetPort()); + Game::logger->Log("MasterServer", "Actually disconnected from zone %i clone %i instance %i port %i", instance->GetMapID(), instance->GetCloneID(), instance->GetInstanceID(), instance->GetPort()); Game::im->RemoveInstance(instance); //Delete the old } @@ -385,7 +385,7 @@ void HandlePacket(Packet* packet) { } if (packet->data[0] == ID_CONNECTION_LOST) { - Game::logger->Log("MasterServer", "A server has lost the connection\n"); + Game::logger->Log("MasterServer", "A server has lost the connection"); Instance* instance = Game::im->GetInstanceBySysAddr(packet->systemAddress); @@ -403,7 +403,7 @@ void HandlePacket(Packet* packet) { if (packet->data[1] == MASTER) { switch (packet->data[3]) { case MSG_MASTER_REQUEST_PERSISTENT_ID: { - Game::logger->Log("MasterServer", "A persistent ID req\n"); + Game::logger->Log("MasterServer", "A persistent ID req"); RakNet::BitStream inStream(packet->data, packet->length, false); uint64_t header = inStream.Read(header); uint64_t requestID = 0; @@ -415,7 +415,7 @@ void HandlePacket(Packet* packet) { } case MSG_MASTER_REQUEST_ZONE_TRANSFER: { - Game::logger->Log("MasterServer","Received zone transfer req\n"); + Game::logger->Log("MasterServer","Received zone transfer req"); RakNet::BitStream inStream(packet->data, packet->length, false); uint64_t header = inStream.Read(header); uint64_t requestID = 0; @@ -431,18 +431,18 @@ void HandlePacket(Packet* packet) { Instance* in = Game::im->GetInstance(zoneID, false, zoneClone); for (auto* instance : Game::im->GetInstances()) { - Game::logger->Log("MasterServer", "Instance: %i/%i/%i -> %i\n",instance->GetMapID(), instance->GetCloneID(),instance->GetInstanceID(), instance == in); + Game::logger->Log("MasterServer", "Instance: %i/%i/%i -> %i",instance->GetMapID(), instance->GetCloneID(),instance->GetInstanceID(), instance == in); } if (!in->GetIsReady()) //Instance not ready, make a pending request { in->GetPendingRequests().push_back({ requestID, static_cast(mythranShift), packet->systemAddress }); - Game::logger->Log("MasterServer", "Server not ready, adding pending request %llu %i %i\n", requestID, zoneID, zoneClone); + Game::logger->Log("MasterServer", "Server not ready, adding pending request %llu %i %i", requestID, zoneID, zoneClone); break; } //Instance is ready, transfer - Game::logger->Log("MasterServer", "Responding to transfer request %llu for zone %i %i\n", requestID, zoneID, zoneClone); + Game::logger->Log("MasterServer", "Responding to transfer request %llu for zone %i %i", requestID, zoneID, zoneClone); Game::im->RequestAffirmation(in, { requestID, static_cast(mythranShift), packet->systemAddress }); break; } @@ -494,7 +494,7 @@ void HandlePacket(Packet* packet) { chatServerMasterPeerSysAddr = copy; } - Game::logger->Log("MasterServer", "Received server info, instance: %i port: %i\n", theirInstanceID, theirPort); + Game::logger->Log("MasterServer", "Received server info, instance: %i port: %i", theirInstanceID, theirPort); break; } @@ -526,7 +526,7 @@ void HandlePacket(Packet* packet) { } activeSessions.insert(std::make_pair(sessionKey, username)); - Game::logger->Log("MasterServer", "Got sessionKey %i for user %s\n", sessionKey, username.c_str()); + Game::logger->Log("MasterServer", "Got sessionKey %i for user %s", sessionKey, username.c_str()); break; } @@ -564,7 +564,7 @@ void HandlePacket(Packet* packet) { instance->AddPlayer(Player()); } else { - printf("Instance missing? What?\n"); + printf("Instance missing? What?"); } break; } @@ -622,7 +622,7 @@ void HandlePacket(Packet* packet) { inStream.Read(requestID); inStream.Read(mythranShift); - + uint32_t len; inStream.Read(len); @@ -633,7 +633,7 @@ void HandlePacket(Packet* packet) { auto* instance = Game::im->FindPrivateInstance(password.c_str()); - Game::logger->Log( "MasterServer", "Join private zone: %llu %d %s %p\n", requestID, mythranShift, password.c_str(), instance); + Game::logger->Log( "MasterServer", "Join private zone: %llu %d %s %p", requestID, mythranShift, password.c_str(), instance); if (instance == nullptr) { return; @@ -656,16 +656,16 @@ void HandlePacket(Packet* packet) { inStream.Read(zoneID); inStream.Read(instanceID); - Game::logger->Log("MasterServer", "Got world ready %i %i\n",zoneID, instanceID); + Game::logger->Log("MasterServer", "Got world ready %i %i",zoneID, instanceID); auto* instance = Game::im->FindInstance(zoneID, instanceID); if (instance == nullptr) { - Game::logger->Log("MasterServer","Failed to find zone to ready\n"); + Game::logger->Log("MasterServer","Failed to find zone to ready"); return; } - Game::logger->Log("MasterServer", "Ready zone %i\n", zoneID); + Game::logger->Log("MasterServer", "Ready zone %i", zoneID); Game::im->ReadyInstance(instance); break; } @@ -677,7 +677,7 @@ void HandlePacket(Packet* packet) { int zoneID; inStream.Read(zoneID); - Game::logger->Log("MasterServer", "Prepping zone %i\n", zoneID); + Game::logger->Log("MasterServer", "Prepping zone %i", zoneID); Game::im->GetInstance(zoneID, false, 0); break; } @@ -690,7 +690,7 @@ void HandlePacket(Packet* packet) { inStream.Read(requestID); - Game::logger->Log("MasterServer","Got affirmation of transfer %llu\n",requestID); + Game::logger->Log("MasterServer","Got affirmation of transfer %llu",requestID); auto* instance =Game::im->GetInstanceBySysAddr(packet->systemAddress); @@ -698,7 +698,7 @@ void HandlePacket(Packet* packet) { return; Game::im->AffirmTransfer(instance, requestID); - Game::logger->Log("MasterServer", "Affirmation complete %llu\n",requestID); + Game::logger->Log("MasterServer", "Affirmation complete %llu",requestID); break; } @@ -712,19 +712,19 @@ void HandlePacket(Packet* packet) { return; } - Game::logger->Log("MasterServer", "Got shutdown response from zone %i clone %i instance %i port %i\n", instance->GetMapID(), instance->GetCloneID(), instance->GetInstanceID(), instance->GetPort()); + Game::logger->Log("MasterServer", "Got shutdown response from zone %i clone %i instance %i port %i", instance->GetMapID(), instance->GetCloneID(), instance->GetInstanceID(), instance->GetPort()); instance->SetIsShuttingDown(true); break; } case MSG_MASTER_SHUTDOWN_UNIVERSE: { - Game::logger->Log("MasterServer","Received shutdown universe command, shutting down in 10 minutes.\n"); + Game::logger->Log("MasterServer","Received shutdown universe command, shutting down in 10 minutes."); shouldShutdown = true; break; } default: - Game::logger->Log("MasterServer","Unknown master packet ID from server: %i\n",packet->data[3]); + Game::logger->Log("MasterServer","Unknown master packet ID from server: %i",packet->data[3]); } } } @@ -780,7 +780,7 @@ void ShutdownSequence() { auto* objIdManager = ObjectIDManager::TryInstance(); if (objIdManager != nullptr) { objIdManager->SaveToDatabase(); - Game::logger->Log("MasterServer", "Saved ObjectIDTracker to DB\n"); + Game::logger->Log("MasterServer", "Saved ObjectIDTracker to DB"); } auto t = std::chrono::high_resolution_clock::now(); @@ -790,7 +790,7 @@ void ShutdownSequence() { exit(EXIT_SUCCESS); } - Game::logger->Log("MasterServer", "Attempting to shutdown instances, max 60 seconds...\n"); + Game::logger->Log("MasterServer", "Attempting to shutdown instances, max 60 seconds..."); while (true) { @@ -800,7 +800,7 @@ void ShutdownSequence() { Game::server->DeallocatePacket(packet); packet = nullptr; } - + auto done = true; for (auto* instance : Game::im->GetInstances()) { @@ -814,7 +814,7 @@ void ShutdownSequence() { } if (done) { - Game::logger->Log("MasterServer", "Finished shutting down MasterServer!\n"); + Game::logger->Log("MasterServer", "Finished shutting down MasterServer!"); break; } @@ -824,7 +824,7 @@ void ShutdownSequence() { ticks++; if (ticks == 600 * 6) { - Game::logger->Log("MasterServer", "Finished shutting down by timeout!\n"); + Game::logger->Log("MasterServer", "Finished shutting down by timeout!"); break; } } diff --git a/dMasterServer/ObjectIDManager.cpp b/dMasterServer/ObjectIDManager.cpp index 28a8ea17..160a3859 100644 --- a/dMasterServer/ObjectIDManager.cpp +++ b/dMasterServer/ObjectIDManager.cpp @@ -40,8 +40,8 @@ void ObjectIDManager::Initialize(dLogger *logger) { delete stmt; } catch (sql::SQLException &e) { mLogger->Log("ObjectIDManager", "Unable to fetch max persistent object " - "ID in use. Defaulting to 1.\n"); - mLogger->Log("ObjectIDManager", "SQL error: %s\n", e.what()); + "ID in use. Defaulting to 1."); + mLogger->Log("ObjectIDManager", "SQL error: %s", e.what()); this->currentPersistentID = 1; } } diff --git a/dNet/AuthPackets.cpp b/dNet/AuthPackets.cpp index c2aca466..0efce260 100644 --- a/dNet/AuthPackets.cpp +++ b/dNet/AuthPackets.cpp @@ -27,23 +27,23 @@ void AuthPackets::HandleHandshake(dServer* server, Packet* packet) { uint64_t header = inStream.Read(header); uint32_t clientVersion = 0; inStream.Read(clientVersion); - - server->GetLogger()->Log("AuthPackets", "Received client version: %i\n", clientVersion); + + server->GetLogger()->Log("AuthPackets", "Received client version: %i", clientVersion); SendHandshake(server, packet->systemAddress, server->GetIP(), server->GetPort()); } void AuthPackets::SendHandshake(dServer* server, const SystemAddress& sysAddr, const std::string& nextServerIP, uint16_t nextServerPort) { RakNet::BitStream bitStream; PacketUtils::WriteHeader(bitStream, SERVER, MSG_SERVER_VERSION_CONFIRM); - bitStream.Write(NET_VERSION); + bitStream.Write(NET_VERSION); bitStream.Write(uint32_t(0x93)); - + if (nextServerPort == 1001) bitStream.Write(uint32_t(1)); //Conn: auth else bitStream.Write(uint32_t(4)); //Conn: world - + bitStream.Write(uint32_t(0)); //Server process ID bitStream.Write(nextServerPort); - + server->Send(&bitStream, sysAddr, false); } @@ -55,15 +55,15 @@ void AuthPackets::HandleLoginRequest(dServer* server, Packet* packet) { // Fetch account details sql::PreparedStatement* stmt = Database::CreatePreppedStmt("SELECT password, banned, locked, play_key_id, gm_level FROM accounts WHERE name=? LIMIT 1;"); stmt->setString(1, szUsername); - + sql::ResultSet* res = stmt->executeQuery(); - + if (res->rowsCount() == 0) { - server->GetLogger()->Log("AuthPackets", "No user found!\n"); + server->GetLogger()->Log("AuthPackets", "No user found!"); AuthPackets::SendLoginResponse(server, packet->systemAddress, LOGIN_RESPONSE_WRONG_PASS_OR_USER, "", "", 2001, username); return; } - + std::string sqlPass = ""; bool sqlBanned = false; bool sqlLocked = false; @@ -77,7 +77,7 @@ void AuthPackets::HandleLoginRequest(dServer* server, Packet* packet) { sqlPlayKey = res->getInt(4); sqlGmLevel = res->getInt(5); } - + delete stmt; delete res; @@ -92,7 +92,7 @@ void AuthPackets::HandleLoginRequest(dServer* server, Packet* packet) { //Check to see if we have a play key: if (sqlPlayKey == 0 && sqlGmLevel == 0) { AuthPackets::SendLoginResponse(server, packet->systemAddress, LOGIN_RESPONSE_PERMISSIONS_NOT_HIGH_ENOUGH, "Your account doesn't have a play key associated with it!", "", 2001, username); - server->GetLogger()->Log("AuthPackets", "User %s tried to log in, but they don't have a play key.\n", username.c_str()); + server->GetLogger()->Log("AuthPackets", "User %s tried to log in, but they don't have a play key.", username.c_str()); return; } @@ -101,7 +101,7 @@ void AuthPackets::HandleLoginRequest(dServer* server, Packet* packet) { keyCheckStmt->setInt(1, sqlPlayKey); auto keyRes = keyCheckStmt->executeQuery(); bool isKeyActive = false; - + if (keyRes->rowsCount() == 0 && sqlGmLevel == 0) { AuthPackets::SendLoginResponse(server, packet->systemAddress, LOGIN_RESPONSE_PERMISSIONS_NOT_HIGH_ENOUGH, "Your account doesn't have a play key associated with it!", "", 2001, username); return; @@ -113,13 +113,13 @@ void AuthPackets::HandleLoginRequest(dServer* server, Packet* packet) { if (!isKeyActive && sqlGmLevel == 0) { AuthPackets::SendLoginResponse(server, packet->systemAddress, LOGIN_RESPONSE_PERMISSIONS_NOT_HIGH_ENOUGH, "Your play key has been disabled.", "", 2001, username); - server->GetLogger()->Log("AuthPackets", "User %s tried to log in, but their play key was disabled\n", username.c_str()); + server->GetLogger()->Log("AuthPackets", "User %s tried to log in, but their play key was disabled", username.c_str()); return; } } - - if (sqlBanned) { - AuthPackets::SendLoginResponse(server, packet->systemAddress, LOGIN_RESPONSE_BANNED, "", "", 2001, username); return; + + if (sqlBanned) { + AuthPackets::SendLoginResponse(server, packet->systemAddress, LOGIN_RESPONSE_BANNED, "", "", 2001, username); return; } if (sqlLocked) { @@ -131,7 +131,7 @@ void AuthPackets::HandleLoginRequest(dServer* server, Packet* packet) { * First attempt bcrypt. * If that fails, fallback to old method and setup bcrypt for new login. */ - + bool loginSuccess = true; int32_t bcryptState = ::bcrypt_checkpw(password.c_str(), sqlPass.c_str()); @@ -162,7 +162,7 @@ void AuthPackets::HandleLoginRequest(dServer* server, Packet* packet) { assert(bcryptState == 0); sql::PreparedStatement* accountUpdate = Database::CreatePreppedStmt("UPDATE accounts SET password = ? WHERE name = ? LIMIT 1;"); - + accountUpdate->setString(1, std::string(hash, BCRYPT_HASHSIZE).c_str()); accountUpdate->setString(2, szUsername); @@ -176,7 +176,7 @@ void AuthPackets::HandleLoginRequest(dServer* server, Packet* packet) { if (!loginSuccess) { AuthPackets::SendLoginResponse(server, packet->systemAddress, LOGIN_RESPONSE_WRONG_PASS_OR_USER, "", "", 2001, username); - server->GetLogger()->Log("AuthPackets", "Wrong password used\n"); + server->GetLogger()->Log("AuthPackets", "Wrong password used"); } else { SystemAddress system = packet->systemAddress; //Copy the sysAddr before the Packet gets destroyed from main @@ -185,7 +185,7 @@ void AuthPackets::HandleLoginRequest(dServer* server, Packet* packet) { AuthPackets::SendLoginResponse(server, system, LOGIN_RESPONSE_GENERAL_FAILED, "", "", 0, username); return; } - + ZoneInstanceManager::Instance()->RequestZoneTransfer(server, 0, 0, false, [system, server, username](bool mythranShift, uint32_t zoneID, uint32_t zoneInstance, uint32_t zoneClone, std::string zoneIP, uint16_t zonePort) { AuthPackets::SendLoginResponse(server, system, LOGIN_RESPONSE_SUCCESS, "", zoneIP, zonePort, username); }); @@ -195,11 +195,11 @@ void AuthPackets::HandleLoginRequest(dServer* server, Packet* packet) { void AuthPackets::SendLoginResponse(dServer* server, const SystemAddress& sysAddr, eLoginResponse responseCode, const std::string& errorMsg, const std::string& wServerIP, uint16_t wServerPort, std::string username) { RakNet::BitStream packet; PacketUtils::WriteHeader(packet, CLIENT, MSG_CLIENT_LOGIN_RESPONSE); - + packet.Write(static_cast(responseCode)); - + PacketUtils::WritePacketString("Talk_Like_A_Pirate", 33, &packet); - + // 7 unknown strings - perhaps other IP addresses? PacketUtils::WritePacketString("", 33, &packet); PacketUtils::WritePacketString("", 33, &packet); @@ -208,44 +208,44 @@ void AuthPackets::SendLoginResponse(dServer* server, const SystemAddress& sysAdd PacketUtils::WritePacketString("", 33, &packet); PacketUtils::WritePacketString("", 33, &packet); PacketUtils::WritePacketString("", 33, &packet); - + packet.Write(static_cast(1)); // Version Major packet.Write(static_cast(10)); // Version Current packet.Write(static_cast(64)); // Version Minor - + // Writes the user key uint32_t sessionKey = rand(); // not mt but whatever std::string userHash = std::to_string(sessionKey); userHash = md5(userHash); PacketUtils::WritePacketWString(userHash, 33, &packet); - + // Write the Character and Chat IPs PacketUtils::WritePacketString(wServerIP, 33, &packet); PacketUtils::WritePacketString("", 33, &packet); - + // Write the Character and Chat Ports packet.Write(static_cast(wServerPort)); packet.Write(static_cast(0)); - + // Write another IP PacketUtils::WritePacketString("", 33, &packet); - + // Write a GUID or something... PacketUtils::WritePacketString("00000000-0000-0000-0000-000000000000", 37, &packet); - + packet.Write(static_cast(0)); // ??? - + // Write the localization PacketUtils::WritePacketString("US", 3, &packet); - + packet.Write(static_cast(false)); // User first logged in? packet.Write(static_cast(false)); // User is F2P? packet.Write(static_cast(0)); // ??? - + // Write custom error message packet.Write(static_cast(errorMsg.length())); PacketUtils::WritePacketWString(errorMsg, static_cast(errorMsg.length()), &packet); - + // Here write auth logs packet.Write(static_cast(20)); for (uint32_t i = 0; i < 20; ++i) { @@ -254,7 +254,7 @@ void AuthPackets::SendLoginResponse(dServer* server, const SystemAddress& sysAdd packet.Write(static_cast(14000)); packet.Write(static_cast(0)); } - + server->Send(&packet, sysAddr, false); //Inform the master server that we've created a session for this user: @@ -265,6 +265,6 @@ void AuthPackets::SendLoginResponse(dServer* server, const SystemAddress& sysAdd PacketUtils::WriteString(bitStream, username, 66); server->SendToMaster(&bitStream); - server->GetLogger()->Log("AuthPackets", "Set sessionKey: %i for user %s\n", sessionKey, username.c_str()); + server->GetLogger()->Log("AuthPackets", "Set sessionKey: %i for user %s", sessionKey, username.c_str()); } } diff --git a/dNet/ClientPackets.cpp b/dNet/ClientPackets.cpp index b9f715ad..00c16133 100644 --- a/dNet/ClientPackets.cpp +++ b/dNet/ClientPackets.cpp @@ -37,7 +37,7 @@ void ClientPackets::HandleChatMessage(const SystemAddress& sysAddr, Packet* packet) { User* user = UserManager::Instance()->GetUser(sysAddr); if (!user) { - Game::logger->Log("ClientPackets", "Unable to get user to parse chat message\n"); + Game::logger->Log("ClientPackets", "Unable to get user to parse chat message"); return; } @@ -71,14 +71,14 @@ void ClientPackets::HandleChatMessage(const SystemAddress& sysAddr, Packet* pack if (!user->GetLastChatMessageApproved() && !isMythran) return; std::string sMessage = GeneralUtils::UTF16ToWTF8(message); - Game::logger->Log("Chat", "%s: %s\n", playerName.c_str(), sMessage.c_str()); + Game::logger->Log("Chat", "%s: %s", playerName.c_str(), sMessage.c_str()); ChatPackets::SendChatMessage(sysAddr, chatChannel, playerName, user->GetLoggedInChar(), isMythran, message); } void ClientPackets::HandleClientPositionUpdate(const SystemAddress& sysAddr, Packet* packet) { User* user = UserManager::Instance()->GetUser(sysAddr); if (!user) { - Game::logger->Log("ClientPackets", "Unable to get user to parse position update\n"); + Game::logger->Log("ClientPackets", "Unable to get user to parse position update"); return; } @@ -240,14 +240,14 @@ void ClientPackets::HandleClientPositionUpdate(const SystemAddress& sysAddr, Pac void ClientPackets::HandleChatModerationRequest(const SystemAddress& sysAddr, Packet* packet) { User* user = UserManager::Instance()->GetUser(sysAddr); if (!user) { - Game::logger->Log("ClientPackets", "Unable to get user to parse chat moderation request\n"); + Game::logger->Log("ClientPackets", "Unable to get user to parse chat moderation request"); return; } auto* entity = Player::GetPlayer(sysAddr); if (entity == nullptr) { - Game::logger->Log("ClientPackets", "Unable to get player to parse chat moderation request\n"); + Game::logger->Log("ClientPackets", "Unable to get player to parse chat moderation request"); return; } diff --git a/dNet/WorldPackets.cpp b/dNet/WorldPackets.cpp index 54c925d6..f7a15c7f 100644 --- a/dNet/WorldPackets.cpp +++ b/dNet/WorldPackets.cpp @@ -18,7 +18,7 @@ void WorldPackets::SendLoadStaticZone(const SystemAddress& sysAddr, float x, float y, float z, uint32_t checksum) { RakNet::BitStream bitStream; PacketUtils::WriteHeader(bitStream, CLIENT, MSG_CLIENT_LOAD_STATIC_ZONE); - + auto zone = dZoneManager::Instance()->GetZone()->GetZoneID(); bitStream.Write(static_cast(zone.GetMapID())); bitStream.Write(static_cast(zone.GetInstanceID())); @@ -33,7 +33,7 @@ void WorldPackets::SendLoadStaticZone(const SystemAddress& sysAddr, float x, flo bitStream.Write(z); bitStream.Write(static_cast(0)); // Change this to eventually use 4 on activity worlds - + SEND_PACKET } @@ -42,23 +42,23 @@ void WorldPackets::SendCharacterList ( const SystemAddress& sysAddr, User* user RakNet::BitStream bitStream; PacketUtils::WriteHeader(bitStream, CLIENT, MSG_CLIENT_CHARACTER_LIST_RESPONSE); - + std::vector characters = user->GetCharacters(); bitStream.Write(static_cast(characters.size())); bitStream.Write(static_cast(0)); //character index in front, just picking 0 - + for (uint32_t i = 0; i < characters.size(); ++i) { bitStream.Write(characters[i]->GetObjectID()); bitStream.Write(static_cast(0)); - + PacketUtils::WriteWString(bitStream, characters[i]->GetName(), 33); PacketUtils::WriteWString(bitStream, characters[i]->GetUnapprovedName(), 33); - + bitStream.Write(static_cast(characters[i]->GetNameRejected())); bitStream.Write(static_cast(false)); - + PacketUtils::WriteString(bitStream, "", 10); - + bitStream.Write(characters[i]->GetShirtColor()); bitStream.Write(characters[i]->GetShirtStyle()); bitStream.Write(characters[i]->GetPantsColor()); @@ -79,12 +79,12 @@ void WorldPackets::SendCharacterList ( const SystemAddress& sysAddr, User* user const auto& equippedItems = characters[i]->GetEquippedItems(); bitStream.Write(static_cast(equippedItems.size())); - + for (uint32_t j = 0; j < equippedItems.size(); ++j) { bitStream.Write(equippedItems[j]); } } - + SEND_PACKET } @@ -112,11 +112,11 @@ void WorldPackets::SendCharacterDeleteResponse(const SystemAddress& sysAddr, boo void WorldPackets::SendTransferToWorld ( const SystemAddress& sysAddr, const std::string& serverIP, uint32_t serverPort, bool mythranShift ) { RakNet::BitStream bitStream; PacketUtils::WriteHeader(bitStream, CLIENT, MSG_CLIENT_TRANSFER_TO_WORLD); - + PacketUtils::WriteString(bitStream, serverIP, 33); bitStream.Write(static_cast(serverPort)); bitStream.Write(static_cast(mythranShift)); - + SEND_PACKET } @@ -130,7 +130,7 @@ void WorldPackets::SendServerState ( const SystemAddress& sysAddr ) { void WorldPackets::SendCreateCharacter(const SystemAddress& sysAddr, Entity* entity, const std::string& xmlData, const std::u16string& username, int32_t gm) { RakNet::BitStream bitStream; PacketUtils::WriteHeader(bitStream, CLIENT, MSG_CLIENT_CREATE_CHARACTER); - + RakNet::BitStream data; data.Write(7); //LDF key count @@ -155,7 +155,7 @@ void WorldPackets::SendCreateCharacter(const SystemAddress& sysAddr, Entity* ent chatmode->WriteToPacket(&data); xmlConfigData->WriteToPacket(&data); reputation->WriteToPacket(&data); - + delete objid; delete lot; delete xmlConfigData; @@ -168,7 +168,7 @@ void WorldPackets::SendCreateCharacter(const SystemAddress& sysAddr, Entity* ent bitStream.Write(data.GetNumberOfBytesUsed() + 1); bitStream.Write(0); bitStream.Write((char*)data.GetData(), data.GetNumberOfBytesUsed()); -#else +#else //Compress the data before sending: const int reservedSize = 5 * 1024 * 1024; uint8_t compressedData[reservedSize]; @@ -185,7 +185,7 @@ void WorldPackets::SendCreateCharacter(const SystemAddress& sysAddr, Entity* ent PacketUtils::SavePacket("chardata.bin", (const char *)bitStream.GetData(), static_cast(bitStream.GetNumberOfBytesUsed())); SEND_PACKET - Game::logger->Log("WorldPackets", "Sent CreateCharacter for ID: %llu\n", entity->GetObjectID()); + Game::logger->Log("WorldPackets", "Sent CreateCharacter for ID: %llu", entity->GetObjectID()); } void WorldPackets::SendChatModerationResponse(const SystemAddress& sysAddr, bool requestAccepted, uint32_t requestID, const std::string& receiver, std::vector> unacceptedItems) { @@ -215,11 +215,11 @@ void WorldPackets::SendChatModerationResponse(const SystemAddress& sysAddr, bool void WorldPackets::SendGMLevelChange(const SystemAddress& sysAddr, bool success, uint8_t highestLevel, uint8_t prevLevel, uint8_t newLevel) { CBITSTREAM PacketUtils::WriteHeader(bitStream, CLIENT, MSG_CLIENT_MAKE_GM_RESPONSE); - + bitStream.Write(success); bitStream.Write(highestLevel); bitStream.Write(prevLevel); bitStream.Write(newLevel); - + SEND_PACKET } diff --git a/dNet/dServer.cpp b/dNet/dServer.cpp index 27b6df7c..56a73c1f 100644 --- a/dNet/dServer.cpp +++ b/dNet/dServer.cpp @@ -13,7 +13,7 @@ //! Replica Constructor class class ReplicaConstructor : public ReceiveConstructionInterface { -public: +public: ReplicaReturnResult ReceiveConstruction(RakNet::BitStream *inBitStream, RakNetTime timestamp, NetworkID networkID, NetworkIDObject *existingObject, SystemAddress senderId, ReplicaManager *caller) { return REPLICA_PROCESSING_DONE; } @@ -60,11 +60,11 @@ dServer::dServer(const std::string& ip, int port, int instanceID, int maxConnect if (mIsOkay) { if (zoneID == 0) - mLogger->Log("dServer", "Server is listening on %s:%i with encryption: %i\n", ip.c_str(), port, int(useEncryption)); + mLogger->Log("dServer", "Server is listening on %s:%i with encryption: %i", ip.c_str(), port, int(useEncryption)); else - mLogger->Log("dServer", "Server is listening on %s:%i with encryption: %i, running zone %i / %i\n", ip.c_str(), port, int(useEncryption), zoneID, instanceID); + mLogger->Log("dServer", "Server is listening on %s:%i with encryption: %i, running zone %i / %i", ip.c_str(), port, int(useEncryption), zoneID, instanceID); } - else { mLogger->Log("dServer", "FAILED TO START SERVER ON IP/PORT: %s:%i\n", ip.c_str(), port); return; } + else { mLogger->Log("dServer", "FAILED TO START SERVER ON IP/PORT: %s:%i", ip.c_str(), port); return; } mLogger->SetLogToConsole(prevLogSetting); @@ -104,13 +104,13 @@ Packet* dServer::ReceiveFromMaster() { if (packet->length < 1) { mMasterPeer->DeallocatePacket(packet); return nullptr; } if (packet->data[0] == ID_DISCONNECTION_NOTIFICATION || packet->data[0] == ID_CONNECTION_LOST) { - mLogger->Log("dServer", "Lost our connection to master, shutting DOWN!\n"); + mLogger->Log("dServer", "Lost our connection to master, shutting DOWN!"); mMasterConnectionActive = false; //ConnectToMaster(); //We'll just shut down now } - + if (packet->data[0] == ID_CONNECTION_REQUEST_ACCEPTED) { - mLogger->Log("dServer", "Established connection to master, zone (%i), instance (%i)\n",this->GetZoneID(), this->GetInstanceID()); + mLogger->Log("dServer", "Established connection to master, zone (%i), instance (%i)",this->GetZoneID(), this->GetInstanceID()); mMasterConnectionActive = true; mMasterSystemAddress = packet->systemAddress; MasterPackets::SendServerInfo(this, packet); diff --git a/dPhysics/dpWorld.cpp b/dPhysics/dpWorld.cpp index bb918b23..4caaab40 100644 --- a/dPhysics/dpWorld.cpp +++ b/dPhysics/dpWorld.cpp @@ -13,7 +13,7 @@ void dpWorld::Initialize(unsigned int zoneID) { phys_sp_tilecount = std::atoi(Game::config->GetValue("phys_sp_tilecount").c_str()); phys_sp_tilesize = std::atoi(Game::config->GetValue("phys_sp_tilesize").c_str()); - //If spatial partitioning is enabled, then we need to create the m_Grid. + //If spatial partitioning is enabled, then we need to create the m_Grid. //if m_Grid exists, then the old method will be used. //SP will NOT be used unless it is added to ShouldUseSP(); if (std::atoi(Game::config->GetValue("phys_spatial_partitioning").c_str()) == 1 @@ -21,11 +21,11 @@ void dpWorld::Initialize(unsigned int zoneID) { m_Grid = new dpGrid(phys_sp_tilecount, phys_sp_tilesize); } - Game::logger->Log("dpWorld", "Physics world initialized!\n"); + Game::logger->Log("dpWorld", "Physics world initialized!"); if (ShouldLoadNavmesh(zoneID)) { - if (LoadNavmeshByZoneID(zoneID)) Game::logger->Log("dpWorld", "Loaded navmesh!\n"); - else Game::logger->Log("dpWorld", "Error(s) occurred during navmesh load.\n"); + if (LoadNavmeshByZoneID(zoneID)) Game::logger->Log("dpWorld", "Loaded navmesh!"); + else Game::logger->Log("dpWorld", "Error(s) occurred during navmesh load."); } } @@ -39,9 +39,9 @@ dpWorld::~dpWorld() { } void dpWorld::StepWorld(float deltaTime) { - if (m_Grid) { - m_Grid->Update(deltaTime); - return; + if (m_Grid) { + m_Grid->Update(deltaTime); + return; } //Pre update: @@ -53,7 +53,7 @@ void dpWorld::StepWorld(float deltaTime) { //Do actual update: for (auto entity : m_DynamicEntites) { if (!entity || entity->GetSleeping()) continue; - + entity->Update(deltaTime); for (auto other : m_StaticEntities) { @@ -135,7 +135,7 @@ bool dpWorld::LoadNavmeshByZoneID(unsigned int zoneID) { dtNavMesh* dpWorld::LoadNavmesh(const char* path) { FILE* fp; - + #ifdef _WIN32 fopen_s(&fp, path, "rb"); #elif __APPLE__ @@ -144,7 +144,7 @@ dtNavMesh* dpWorld::LoadNavmesh(const char* path) { #else fp = fopen64(path, "rb"); #endif - + if (!fp) { return 0; } @@ -272,7 +272,7 @@ std::vector dpWorld::GetPath(const NiPoint3& startPos, const NiPoint3& //how many points to generate between start/end? //note: not actually 100% accurate due to rounding, but worst case it causes them to go a tiny bit faster //than their speed value would normally allow at the end. - int numPoints = startPos.Distance(startPos, endPos) / speed; + int numPoints = startPos.Distance(startPos, endPos) / speed; path.push_back(startPos); //insert the start pos diff --git a/dScripts/ActivityManager.cpp b/dScripts/ActivityManager.cpp index e464b20d..56766482 100644 --- a/dScripts/ActivityManager.cpp +++ b/dScripts/ActivityManager.cpp @@ -51,7 +51,7 @@ float_t ActivityManager::GetActivityValue(Entity *self, const LWOOBJID playerID, void ActivityManager::StopActivity(Entity *self, const LWOOBJID playerID, const uint32_t score, const uint32_t value1, const uint32_t value2, bool quit) { int32_t gameID = 0; - + auto* sac = self->GetComponent(); if (sac == nullptr) { gameID = self->GetLOT(); @@ -125,7 +125,7 @@ void ActivityManager::ActivityTimerStart(Entity *self, const std::string& timerN auto* timer = new ActivityTimer { timerName, updateInterval, stopTime }; activeTimers.push_back(timer); - Game::logger->Log("ActivityManager", "Starting timer '%s', %f, %f\n", timerName.c_str(), updateInterval, stopTime); + Game::logger->Log("ActivityManager", "Starting timer '%s', %f, %f", timerName.c_str(), updateInterval, stopTime); self->AddTimer(GetPrefixedName(timer->name), timer->updateInterval); } @@ -147,7 +147,7 @@ float_t ActivityManager::ActivityTimerGetCurrentTime(Entity *self, const std::st int32_t ActivityManager::GetGameID(Entity *self) const { int32_t gameID = 0; - + auto* sac = self->GetComponent(); if (sac == nullptr) { gameID = self->GetLOT(); @@ -208,10 +208,10 @@ void ActivityManager::OnTimerDone(Entity *self, std::string timerName) { activeTimers.erase(std::remove(activeTimers.begin(), activeTimers.end(), timer), activeTimers.end()); delete timer; - Game::logger->Log("ActivityManager", "Executing timer '%s'\n", activityTimerName.c_str()); + Game::logger->Log("ActivityManager", "Executing timer '%s'", activityTimerName.c_str()); OnActivityTimerDone(self, activityTimerName); } else { - Game::logger->Log("ActivityManager", "Updating timer '%s'\n", activityTimerName.c_str()); + Game::logger->Log("ActivityManager", "Updating timer '%s'", activityTimerName.c_str()); OnActivityTimerUpdate(self, timer->name, timer->stopTime - timer->runTime, timer->runTime); self->AddTimer(GetPrefixedName(timer->name), timer->updateInterval); } diff --git a/dScripts/AgJetEffectServer.cpp b/dScripts/AgJetEffectServer.cpp index 599f4d01..7336c8b8 100644 --- a/dScripts/AgJetEffectServer.cpp +++ b/dScripts/AgJetEffectServer.cpp @@ -49,20 +49,20 @@ void AgJetEffectServer::OnRebuildComplete(Entity* self, Entity* target) auto* effect = entities[0]; auto groups = self->GetGroups(); - + if (groups.empty()) { return; } builder = target->GetObjectID(); - + const auto group = groups[0]; GameMessages::SendPlayAnimation(effect, u"jetFX"); self->AddTimer("PlayEffect", 2.5f); - + if (group == "Base_Radar") { self->AddTimer("CineDone", 5); @@ -88,7 +88,7 @@ void AgJetEffectServer::OnTimerDone(Entity* self, std::string timerName) } const auto size = entities.size(); - + if (size == 0) { return; @@ -98,7 +98,7 @@ void AgJetEffectServer::OnTimerDone(Entity* self, std::string timerName) auto* mortar = entities[selected]; - Game::logger->Log("AgJetEffectServer", "Mortar (%i) (&d)\n", mortar->GetLOT(), mortar->HasComponent(COMPONENT_TYPE_SKILL)); + Game::logger->Log("AgJetEffectServer", "Mortar (%i) (&d)", mortar->GetLOT(), mortar->HasComponent(COMPONENT_TYPE_SKILL)); mortar->SetOwnerOverride(builder); diff --git a/dScripts/BaseRandomServer.cpp b/dScripts/BaseRandomServer.cpp index 7026178c..c2d335c4 100644 --- a/dScripts/BaseRandomServer.cpp +++ b/dScripts/BaseRandomServer.cpp @@ -4,7 +4,7 @@ #include "dLogger.h" #include "Entity.h" -void BaseRandomServer::BaseStartup(Entity* self) +void BaseRandomServer::BaseStartup(Entity* self) { self->SetVar(u"SpawnState", "min"); self->SetVar(u"JustChanged", false); @@ -13,12 +13,12 @@ void BaseRandomServer::BaseStartup(Entity* self) SpawnMapZones(self); } -void BaseRandomServer::CheckEvents(Entity* self) +void BaseRandomServer::CheckEvents(Entity* self) { // TODO: Add events? } -void BaseRandomServer::SpawnMapZones(Entity* self) +void BaseRandomServer::SpawnMapZones(Entity* self) { for (const auto& pair : sectionMultipliers) { @@ -35,13 +35,13 @@ void BaseRandomServer::SpawnMapZones(Entity* self) self->SetVar(u"bInit", true); } -void BaseRandomServer::SpawnSection(Entity* self, const std::string& sectionName, float iMultiplier) +void BaseRandomServer::SpawnSection(Entity* self, const std::string& sectionName, float iMultiplier) { Zone* spawnLoad = GetRandomLoad(self, sectionName); if (spawnLoad == nullptr) { - Game::logger->Log("BaseRandomServer", "Failed to find section: %s\n", sectionName.c_str()); + Game::logger->Log("BaseRandomServer", "Failed to find section: %s", sectionName.c_str()); return; } @@ -60,7 +60,7 @@ void BaseRandomServer::SpawnSection(Entity* self, const std::string& sectionName } } -void BaseRandomServer::SetSpawnerNetwork(Entity* self, const std::string& spawnerName, int32_t spawnNum, LOT spawnLOT) +void BaseRandomServer::SetSpawnerNetwork(Entity* self, const std::string& spawnerName, int32_t spawnNum, LOT spawnLOT) { const auto& spawners = dZoneManager::Instance()->GetSpawnersByName(spawnerName); @@ -71,7 +71,7 @@ void BaseRandomServer::SetSpawnerNetwork(Entity* self, const std::string& spawne if (spawners.empty()) { - Game::logger->Log("BaseRandomServer", "Failed to find spawner: %s\n", spawnerName.c_str()); + Game::logger->Log("BaseRandomServer", "Failed to find spawner: %s", spawnerName.c_str()); return; } @@ -108,7 +108,7 @@ void BaseRandomServer::SetSpawnerNetwork(Entity* self, const std::string& spawne spawnersWatched.push_back(spawner); } -BaseRandomServer::Zone* BaseRandomServer::GetRandomLoad(Entity* self, const std::string& sectionName) +BaseRandomServer::Zone* BaseRandomServer::GetRandomLoad(Entity* self, const std::string& sectionName) { const auto zoneInfo = GeneralUtils::SplitString(sectionName, '_'); @@ -135,7 +135,7 @@ BaseRandomServer::Zone* BaseRandomServer::GetRandomLoad(Entity* self, const std: return nullptr; } -void BaseRandomServer::NotifySpawnerOfDeath(Entity* self, Spawner* spawner) +void BaseRandomServer::NotifySpawnerOfDeath(Entity* self, Spawner* spawner) { const auto& spawnerName = spawner->GetName(); @@ -164,29 +164,29 @@ void BaseRandomServer::NotifySpawnerOfDeath(Entity* self, Spawner* spawner) self->SetVar(variableName, mobDeathCount); } -void BaseRandomServer::NamedEnemyDeath(Entity* self, Spawner* spawner) +void BaseRandomServer::NamedEnemyDeath(Entity* self, Spawner* spawner) { const auto spawnDelay = GeneralUtils::GenerateRandomNumber(1, 2) * 450; self->AddTimer("SpawnNewEnemy", spawnDelay); } -void BaseRandomServer::SpawnersUp(Entity* self) +void BaseRandomServer::SpawnersUp(Entity* self) { } -void BaseRandomServer::SpawnersDown(Entity* self) +void BaseRandomServer::SpawnersDown(Entity* self) { } -void BaseRandomServer::BaseOnTimerDone(Entity* self, const std::string& timerName) +void BaseRandomServer::BaseOnTimerDone(Entity* self, const std::string& timerName) { NamedTimerDone(self, timerName); } -void BaseRandomServer::SpawnNamedEnemy(Entity* self) +void BaseRandomServer::SpawnNamedEnemy(Entity* self) { const auto enemy = namedMobs[GeneralUtils::GenerateRandomNumber(0, namedMobs.size() - 1)]; diff --git a/dScripts/BossSpiderQueenEnemyServer.cpp b/dScripts/BossSpiderQueenEnemyServer.cpp index dd0b80c8..88f05a4b 100644 --- a/dScripts/BossSpiderQueenEnemyServer.cpp +++ b/dScripts/BossSpiderQueenEnemyServer.cpp @@ -22,7 +22,7 @@ void BossSpiderQueenEnemyServer::OnStartup(Entity* self) { // Make immune to stuns //self:SetStunImmunity{ StateChangeType = "PUSH", bImmuneToStunAttack = true, bImmuneToStunMove = true, bImmuneToStunTurn = true, bImmuneToStunUseItem = true, bImmuneToStunEquip = true, bImmuneToStunInteract = true, bImmuneToStunJump = true } - + // Make immune to knockbacks and pulls //self:SetStatusImmunity{ StateChangeType = "PUSH", bImmuneToPullToPoint = true, bImmuneToKnockback = true, bImmuneToInterrupt = true } @@ -60,7 +60,7 @@ void BossSpiderQueenEnemyServer::OnDie(Entity* self, Entity* killer) { missionComponent->CompleteMission(instanceMissionID); } - Game::logger->Log("BossSpiderQueenEnemyServer", "Starting timer...\n"); + Game::logger->Log("BossSpiderQueenEnemyServer", "Starting timer..."); // There is suppose to be a 0.1 second delay here but that may be admitted? auto* controller = EntityManager::Instance()->GetZoneControlEntity(); @@ -88,15 +88,15 @@ void BossSpiderQueenEnemyServer::WithdrawSpider(Entity* self, const bool withdra //First rotate for anim NiQuaternion rot = NiQuaternion::IDENTITY; - + controllable->SetStatic(false); controllable->SetRotation(rot); - + controllable->SetStatic(true); - + controllable->SetDirtyPosition(true); - + rot = controllable->GetRotation(); EntityManager::Instance()->SerializeEntity(self); @@ -122,10 +122,10 @@ void BossSpiderQueenEnemyServer::WithdrawSpider(Entity* self, const bool withdra } else { controllable->SetStatic(false); - + //Cancel all remaining timers for say idle anims: self->CancelAllTimers(); - + auto* baseCombatAi = self->GetComponent(); baseCombatAi->SetDisabled(false); @@ -133,7 +133,7 @@ void BossSpiderQueenEnemyServer::WithdrawSpider(Entity* self, const bool withdra // Move the Spider to its ground location // preparing its stage attacks, and removing invulnerability //destroyable->SetIsImmune(false); - + // Run the advance animation and prepare a timer for resuming AI float animTime = PlayAnimAndReturnTime(self, spiderAdvanceAnim); animTime += 1.f; @@ -142,19 +142,19 @@ void BossSpiderQueenEnemyServer::WithdrawSpider(Entity* self, const bool withdra destroyable->SetFaction(4); destroyable->SetIsImmune(false); - + //Advance stage m_CurrentBossStage++; //Reset the current wave death counter m_DeathCounter = 0; - + EntityManager::Instance()->SerializeEntity(self); // Prepare a timer for post leap attack self->AddTimer("AdvanceAttack", attackPause); - // Prepare a timer for post leap + // Prepare a timer for post leap self->AddTimer("AdvanceComplete", animTime); } @@ -162,7 +162,7 @@ void BossSpiderQueenEnemyServer::WithdrawSpider(Entity* self, const bool withdra } void BossSpiderQueenEnemyServer::SpawnSpiderWave(Entity* self, int spiderCount) { - // The Spider Queen Boss is withdrawing and requesting the spawn + // The Spider Queen Boss is withdrawing and requesting the spawn // of a hatchling wave /*auto SpiderEggNetworkID = self->GetI64(u"SpiderEggNetworkID"); @@ -176,7 +176,7 @@ void BossSpiderQueenEnemyServer::SpawnSpiderWave(Entity* self, int spiderCount) hatchCounter = spiderCount; hatchList = {}; - Game::logger->Log("SpiderQueen", "Trying to spawn %i spiders\n", hatchCounter); + Game::logger->Log("SpiderQueen", "Trying to spawn %i spiders", hatchCounter); // Run the wave manager @@ -189,19 +189,19 @@ void BossSpiderQueenEnemyServer::SpiderWaveManager(Entity* self) { // Reset the spider egg spawner network to ensure a maximum number of eggs //SpiderEggNetworkID:SpawnerReset() - + // Obtain a list of all the eggs on the egg spawner network //auto spiderEggList = SpiderEggNetworkID:SpawnerGetAllObjectIDsSpawned().objects; - //if (table.maxn(spiderEggList) <= 0) { + //if (table.maxn(spiderEggList) <= 0) { // self->AddTimer("PollSpiderWaveManager", 1.0f); // return; //} // //// A check for (wave mangement across multiple spawn iterations //if(hatchCounter < spiderWaveCnt) { - // // We have already prepped some objects for (hatching, + // // We have already prepped some objects for (hatching, // // remove them from our list for (random egg pulls // for (i, sVal in ipairs(spiderEggList) { // if(hatchList[sVal:GetID()]) { @@ -220,8 +220,8 @@ void BossSpiderQueenEnemyServer::SpiderWaveManager(Entity* self) { for (auto spodder : spooders) { spiderEggs.push_back(spodder->GetObjectID()); } - - // Select a number of random spider eggs from the list equal to the + + // Select a number of random spider eggs from the list equal to the // current number needed to complete the current wave for (int i = 0; i < hatchCounter; i++) { // Select a random spider egg @@ -235,7 +235,7 @@ void BossSpiderQueenEnemyServer::SpiderWaveManager(Entity* self) { randomEgg = spiderEggs[randomEggLoc]; } } - + if (randomEgg) { auto* eggEntity = EntityManager::Instance()->GetEntity(randomEgg); @@ -246,24 +246,24 @@ void BossSpiderQueenEnemyServer::SpiderWaveManager(Entity* self) { // Prep the selected spider egg //randomEgg:FireEvent{s}erID=self, args="prepEgg"} eggEntity->OnFireEventServerSide(self, "prepEgg"); - Game::logger->Log("SpiderQueen", "Prepping egg %llu\n", eggEntity->GetObjectID()); - + Game::logger->Log("SpiderQueen", "Prepping egg %llu", eggEntity->GetObjectID()); + // Add the prepped egg to our hatchList hatchList.push_back(eggEntity->GetObjectID()); // Decrement the hatchCounter hatchCounter = hatchCounter - 1; } - + // Remove it from our spider egg list //table.remove(spiderEggList, randomEggLoc); spiderEggs[randomEggLoc] = LWOOBJID_EMPTY; - - if (spiderEggs.size() <= 0 || (hatchCounter <= 0)) { + + if (spiderEggs.size() <= 0 || (hatchCounter <= 0)) { break; } } - + if (hatchCounter > 0) { // We still have more eggs to hatch, poll the SpiderWaveManager again self->AddTimer("PollSpiderWaveManager", 1.0f); @@ -280,20 +280,20 @@ void BossSpiderQueenEnemyServer::SpiderWaveManager(Entity* self) { } eggEntity->OnFireEventServerSide(self, "hatchEgg"); - Game::logger->Log("SpiderQueen", "hatching egg %llu\n", eggEntity->GetObjectID()); + Game::logger->Log("SpiderQueen", "hatching egg %llu", eggEntity->GetObjectID()); auto time = PlayAnimAndReturnTime(self, spiderWithdrawIdle); combat->SetStunImmune(false); combat->Stun(time += 6.0f); combat->SetStunImmune(true); - + //self->AddTimer("disableWaitForIdle", defaultAnimPause); self->AddTimer("checkForSpiders", 6.0f); } hatchList.clear(); - + } } @@ -322,7 +322,7 @@ void BossSpiderQueenEnemyServer::RunRainOfFire(Entity* self) for (const auto& rofGroup : ROFTargetGroupIDTable) { const auto spawners = dZoneManager::Instance()->GetSpawnersInGroup(rofGroup); - + std::vector spawned; for (auto* spawner : spawners) @@ -352,7 +352,7 @@ void BossSpiderQueenEnemyServer::RunRainOfFire(Entity* self) self->AddTimer("StartROF", animTime); } -void BossSpiderQueenEnemyServer::RainOfFireManager(Entity* self) +void BossSpiderQueenEnemyServer::RainOfFireManager(Entity* self) { if (!impactList.empty()) { @@ -362,7 +362,7 @@ void BossSpiderQueenEnemyServer::RainOfFireManager(Entity* self) if (entity == nullptr) { - Game::logger->Log("BossSpiderQueenEnemyServer", "Failed to find impact!\n"); + Game::logger->Log("BossSpiderQueenEnemyServer", "Failed to find impact!"); return; } @@ -371,8 +371,8 @@ void BossSpiderQueenEnemyServer::RainOfFireManager(Entity* self) if (skillComponent == nullptr) { - Game::logger->Log("BossSpiderQueenEnemyServer", "Failed to find impact skill component!\n"); - + Game::logger->Log("BossSpiderQueenEnemyServer", "Failed to find impact skill component!"); + return; } @@ -384,7 +384,7 @@ void BossSpiderQueenEnemyServer::RainOfFireManager(Entity* self) } ToggleForSpecial(self, false); - + self->AddTimer("ROF", GeneralUtils::GenerateRandomNumber(20, 40)); } @@ -402,7 +402,7 @@ void BossSpiderQueenEnemyServer::RapidFireShooterManager(Entity* self) } const auto target = attackTargetTable[0]; - + auto* skillComponent = self->GetComponent(); skillComponent->CalculateBehavior(1394, 32612, target, true); @@ -412,7 +412,7 @@ void BossSpiderQueenEnemyServer::RapidFireShooterManager(Entity* self) self->AddTimer("PollRFSManager", 0.3f); } -void BossSpiderQueenEnemyServer::RunRapidFireShooter(Entity* self) +void BossSpiderQueenEnemyServer::RunRapidFireShooter(Entity* self) { /* const auto targets = EntityManager::Instance()->GetEntitiesByComponent(COMPONENT_TYPE_CHARACTER); @@ -429,7 +429,7 @@ void BossSpiderQueenEnemyServer::RunRapidFireShooter(Entity* self) if (targets.empty()) { - Game::logger->Log("BossSpiderQueenEnemyServer", "Failed to find RFS targets\n"); + Game::logger->Log("BossSpiderQueenEnemyServer", "Failed to find RFS targets"); self->AddTimer("RFS", GeneralUtils::GenerateRandomNumber(5, 10)); @@ -452,7 +452,7 @@ void BossSpiderQueenEnemyServer::RunRapidFireShooter(Entity* self) PlayAnimAndReturnTime(self, spiderSingleShot); - Game::logger->Log("BossSpiderQueenEnemyServer", "Ran RFS\n"); + Game::logger->Log("BossSpiderQueenEnemyServer", "Ran RFS"); self->AddTimer("RFS", GeneralUtils::GenerateRandomNumber(10, 15)); } @@ -487,7 +487,7 @@ void BossSpiderQueenEnemyServer::OnTimerDone(Entity* self, const std::string tim //If there are still baby spiders, don't do anyhting either const auto spiders = EntityManager::Instance()->GetEntitiesInGroup("BabySpider"); - if (spiders.size() > 0) + if (spiders.size() > 0) self->AddTimer("checkForSpiders", time); else WithdrawSpider(self, false); @@ -496,30 +496,30 @@ void BossSpiderQueenEnemyServer::OnTimerDone(Entity* self, const std::string tim //Call the manager again to attempt to initiate an impact on another random location //Run the ROF Manager RainOfFireManager(self); - + } else if ( timerName == "PollRFSManager") { //Call the manager again to attempt to initiate a rapid fire shot at the next sequential target //Run the ROF Manager RapidFireShooterManager(self); - + } else if ( timerName == "StartROF") { //Re-enable Spider Boss //ToggleForSpecial(self, false); - + RainOfFireManager(self); - + } else if ( timerName == "PollSpiderSkillManager") { //Call the skill manager again to attempt to run the current Spider Boss //stage's special attack again //SpiderSkillManager(self, true); PlayAnimAndReturnTime(self, spiderJeerAnim); - + } else if ( timerName == "RFS") { RunRapidFireShooter(self); } else if ( timerName == "ROF") { RunRainOfFire(self); - } else if ( timerName == "RFSTauntComplete") { - //Determine an appropriate random time to check our manager again + } else if ( timerName == "RFSTauntComplete") { + //Determine an appropriate random time to check our manager again // local spiderCooldownDelay = math.random(s1DelayMin, s1DelayMax) //Set a timer based on our random cooldown determination @@ -529,7 +529,7 @@ void BossSpiderQueenEnemyServer::OnTimerDone(Entity* self, const std::string tim //Re-enable Spider Boss //ToggleForSpecial(self, false); - + } else if ( timerName == "WithdrawComplete") { //Play the Spider Boss' mountain idle anim PlayAnimAndReturnTime(self, spiderWithdrawIdle); @@ -545,19 +545,19 @@ void BossSpiderQueenEnemyServer::OnTimerDone(Entity* self, const std::string tim if (currentStage > 1) hatchCounter++; SpawnSpiderWave(self, spiderWaveCntTable[currentStage - 1]); - - } else if ( timerName == "AdvanceAttack") { + + } else if ( timerName == "AdvanceAttack") { //TODO: Can we even do knockbacks yet? @Wincent01 // Yes ^ //Fire the melee smash skill to throw players back /*local landingTarget = self:GetVar("LandingTarget") or false - + if((landingTarget) and (landingTarget:Exists())) { local advSmashFlag = landingTarget:CastSkill{skillID = bossLandingSkill} landingTarget:PlayEmbeddedEffectOnAllClientsNearObject{radius = 100, fromObjectID = landingTarget, effectName = "camshake-bridge"} }*/ - + auto landingTarget = self->GetI64(u"LandingTarget"); auto landingEntity = EntityManager::Instance()->GetEntity(landingTarget); @@ -567,7 +567,7 @@ void BossSpiderQueenEnemyServer::OnTimerDone(Entity* self, const std::string tim { skillComponent->CalculateBehavior(bossLandingSkill, 37739, LWOOBJID_EMPTY); } - + if (landingEntity) { auto* landingSkill = landingEntity->GetComponent(); @@ -578,12 +578,12 @@ void BossSpiderQueenEnemyServer::OnTimerDone(Entity* self, const std::string tim } GameMessages::SendPlayEmbeddedEffectOnAllClientsNearObject(self, u"camshake-bridge", self->GetObjectID(), 100.0f); - - } else if ( timerName == "AdvanceComplete") { + + } else if ( timerName == "AdvanceComplete") { //Reset faction and collision /*local SBFactionList = self:GetVar("SBFactionList") local SBCollisionGroup = self:GetVar("SBCollisionGroup") - + for i, fVal in ipairs(SBFactionList) { if(i == 1) { //Our first faction - flush and add @@ -596,18 +596,18 @@ void BossSpiderQueenEnemyServer::OnTimerDone(Entity* self, const std::string tim /* auto SBCollisionGroup = self->GetI32(u"SBCollisionGroup"); - + GameMessages::SendNotifyClientObject(self->GetObjectID(), u"SetColGroup", SBCollisionGroup, 0, LWOOBJID_EMPTY, "", UNASSIGNED_SYSTEM_ADDRESS); */ - + GameMessages::SendNotifyClientObject(self->GetObjectID(), u"SetColGroup", 11, 0, 0, "", UNASSIGNED_SYSTEM_ADDRESS); //Wind up, telegraphing next round float animTime = PlayAnimAndReturnTime(self, spiderJeerAnim); self->AddTimer("AdvanceTauntComplete", animTime); - + } else if ( timerName == "AdvanceTauntComplete") { - + //Declare a default special Spider Boss skill cooldown int spiderCooldownDelay = 10; @@ -620,11 +620,11 @@ void BossSpiderQueenEnemyServer::OnTimerDone(Entity* self, const std::string tim //Set a timer based on our random cooldown determination //to pulse the SpiderSkillManager self->AddTimer("PollSpiderSkillManager", spiderCooldownDelay); - + //Remove current status immunity /*self:SetStatusImmunity{ StateChangeType = "POP", bImmuneToSpeed = true, bImmuneToBasicAttack = true, bImmuneToDOT = true} - - self:SetStunned{StateChangeType = "POP", + + self:SetStunned{StateChangeType = "POP", bCantMove = true, bCantJump = true, bCantTurn = true, @@ -638,14 +638,14 @@ void BossSpiderQueenEnemyServer::OnTimerDone(Entity* self, const std::string tim destroyable->SetFaction(4); EntityManager::Instance()->SerializeEntity(self); - + } else if ( timerName == "Clear") { EntityManager::Instance()->FireEventServerSide(self, "ClearProperty"); self->CancelAllTimers(); } else if ( timerName == "UnlockSpecials") { //We no longer need to lock specials self->SetBoolean(u"bSpecialLock", false); - + //Did we queue a spcial attack? if(self->GetBoolean(u"bSpecialQueued")) { self->SetBoolean(u"bSpecialQueued", false); @@ -723,17 +723,17 @@ float BossSpiderQueenEnemyServer::PlayAnimAndReturnTime(Entity* self, const std: //TODO: Get the actual animation time // Get the anim time - float animTimer = defaultAnimPause; //self:GetAnimationTime{animationID = animID}.time - + float animTimer = defaultAnimPause; //self:GetAnimationTime{animationID = animID}.time + // If we have an animation play it if (animTimer > 0) { GameMessages::SendPlayAnimation(self, animID); } - + // If the anim time is less than the the default time use default if (animTimer < defaultAnimPause) { animTimer = defaultAnimPause; } - + return animTimer; } diff --git a/dScripts/CppScripts.cpp b/dScripts/CppScripts.cpp index 420394bb..8feb8ae7 100644 --- a/dScripts/CppScripts.cpp +++ b/dScripts/CppScripts.cpp @@ -818,7 +818,7 @@ CppScripts::Script* CppScripts::GetScript(Entity* parent, const std::string& scr script = invalidToReturn; else if (script == invalidToReturn) { if (scriptName.length() > 0) - Game::logger->LogDebug("CppScripts", "Attempted to load CppScript for '" + scriptName + "', but returned InvalidScript.\n"); + Game::logger->LogDebug("CppScripts", "Attempted to load CppScript for '" + scriptName + "', but returned InvalidScript."); // information not really needed for sys admins but is for developers script = invalidToReturn; diff --git a/dScripts/FlameJetServer.cpp b/dScripts/FlameJetServer.cpp index 0e6d91cc..936f2a94 100644 --- a/dScripts/FlameJetServer.cpp +++ b/dScripts/FlameJetServer.cpp @@ -2,7 +2,7 @@ #include "SkillComponent.h" #include "GameMessages.h" -void FlameJetServer::OnStartup(Entity* self) +void FlameJetServer::OnStartup(Entity* self) { if (self->GetVar(u"NotActive")) { @@ -12,7 +12,7 @@ void FlameJetServer::OnStartup(Entity* self) self->SetNetworkVar(u"FlameOn", true); } -void FlameJetServer::OnCollisionPhantom(Entity* self, Entity* target) +void FlameJetServer::OnCollisionPhantom(Entity* self, Entity* target) { if (!target->IsPlayer()) { @@ -42,9 +42,9 @@ void FlameJetServer::OnCollisionPhantom(Entity* self, Entity* target) GameMessages::SendKnockback(target->GetObjectID(), self->GetObjectID(), self->GetObjectID(), 1000, dir); } -void FlameJetServer::OnFireEventServerSide(Entity *self, Entity *sender, std::string args, int32_t param1, int32_t param2, int32_t param3) +void FlameJetServer::OnFireEventServerSide(Entity *self, Entity *sender, std::string args, int32_t param1, int32_t param2, int32_t param3) { - Game::logger->Log("FlameJetServer::OnFireEventServerSide", "Event: %s\n", args.c_str()); + Game::logger->Log("FlameJetServer::OnFireEventServerSide", "Event: %s", args.c_str()); if (args == "OnActivated") { diff --git a/dScripts/FvMaelstromDragon.cpp b/dScripts/FvMaelstromDragon.cpp index afdfa4ae..66e7de85 100644 --- a/dScripts/FvMaelstromDragon.cpp +++ b/dScripts/FvMaelstromDragon.cpp @@ -4,7 +4,7 @@ #include "BaseCombatAIComponent.h" #include "DestroyableComponent.h" -void FvMaelstromDragon::OnStartup(Entity* self) +void FvMaelstromDragon::OnStartup(Entity* self) { self->SetVar(u"weakspot", 0); @@ -16,7 +16,7 @@ void FvMaelstromDragon::OnStartup(Entity* self) } } -void FvMaelstromDragon::OnDie(Entity* self, Entity* killer) +void FvMaelstromDragon::OnDie(Entity* self, Entity* killer) { if (self->GetVar(u"bDied")) { @@ -68,7 +68,7 @@ void FvMaelstromDragon::OnHitOrHealResult(Entity* self, Entity* attacker, int32_ if (destroyableComponent != nullptr) { - Game::logger->Log("FvMaelstromDragon", "Hit %i\n", destroyableComponent->GetArmor()); + Game::logger->Log("FvMaelstromDragon", "Hit %i", destroyableComponent->GetArmor()); if (destroyableComponent->GetArmor() > 0) return; @@ -76,7 +76,7 @@ void FvMaelstromDragon::OnHitOrHealResult(Entity* self, Entity* attacker, int32_ if (weakpoint == 0) { - Game::logger->Log("FvMaelstromDragon", "Activating weakpoint\n"); + Game::logger->Log("FvMaelstromDragon", "Activating weakpoint"); self->AddTimer("ReviveTimer", 12); @@ -141,7 +141,7 @@ void FvMaelstromDragon::OnHitOrHealResult(Entity* self, Entity* attacker, int32_ } } -void FvMaelstromDragon::OnTimerDone(Entity* self, std::string timerName) +void FvMaelstromDragon::OnTimerDone(Entity* self, std::string timerName) { if (timerName == "ReviveHeldTimer") { @@ -187,7 +187,7 @@ FvMaelstromDragon::OnFireEventServerSide(Entity *self, Entity *sender, std::stri int32_t param3) { if (args != "rebuildDone") return; - + self->AddTimer("ExposeWeakSpotTimer", 3.8f); self->CancelTimer("ReviveTimer"); diff --git a/dScripts/NjMonastryBossInstance.cpp b/dScripts/NjMonastryBossInstance.cpp index cd34ea2c..2aa7222e 100644 --- a/dScripts/NjMonastryBossInstance.cpp +++ b/dScripts/NjMonastryBossInstance.cpp @@ -92,7 +92,7 @@ void NjMonastryBossInstance::OnPlayerExit(Entity *self, Entity *player) { UpdatePlayer(self, player->GetObjectID(), true); // Fetch the total players loaded from the vars auto totalPlayersLoaded = self->GetVar >(TotalPlayersLoadedVariable); - + // Find the player to remove auto playerToRemove = std::find(totalPlayersLoaded.begin(), totalPlayersLoaded.end(), player->GetObjectID()); @@ -100,7 +100,7 @@ void NjMonastryBossInstance::OnPlayerExit(Entity *self, Entity *player) { if (playerToRemove != totalPlayersLoaded.end()) { totalPlayersLoaded.erase(playerToRemove); } else { - Game::logger->Log("NjMonastryBossInstance", "Failed to remove player at exit.\n"); + Game::logger->Log("NjMonastryBossInstance", "Failed to remove player at exit."); } // Set the players loaded var back diff --git a/dScripts/SGCannon.cpp b/dScripts/SGCannon.cpp index ab179226..9f270562 100644 --- a/dScripts/SGCannon.cpp +++ b/dScripts/SGCannon.cpp @@ -13,7 +13,7 @@ #include "MissionComponent.h" void SGCannon::OnStartup(Entity *self) { - Game::logger->Log("SGCannon", "OnStartup\n"); + Game::logger->Log("SGCannon", "OnStartup"); m_Waves = GetWaves(); constants = GetConstants(); @@ -59,7 +59,7 @@ void SGCannon::OnStartup(Entity *self) { } void SGCannon::OnPlayerLoaded(Entity *self, Entity *player) { - Game::logger->Log("SGCannon", "Player loaded\n"); + Game::logger->Log("SGCannon", "Player loaded"); self->SetVar(PlayerIDVariable, player->GetObjectID()); } @@ -70,15 +70,15 @@ void SGCannon::OnFireEventServerSide(Entity *self, Entity *sender, std::string a void SGCannon::OnActivityStateChangeRequest(Entity *self, LWOOBJID senderID, int32_t value1, int32_t value2, const std::u16string &stringValue) { - Game::logger->Log("SGCannon", "Got activity state change request: %s\n", GeneralUtils::UTF16ToWTF8(stringValue).c_str()); + Game::logger->Log("SGCannon", "Got activity state change request: %s", GeneralUtils::UTF16ToWTF8(stringValue).c_str()); if (stringValue == u"clientready") { auto* player = EntityManager::Instance()->GetEntity(self->GetVar(PlayerIDVariable)); if (player != nullptr) { - Game::logger->Log("SGCannon", "Player is ready\n"); + Game::logger->Log("SGCannon", "Player is ready"); /*GameMessages::SendSetStunned(player->GetObjectID(), PUSH, player->GetSystemAddress(), LWOOBJID_EMPTY, true, true, true, true, true, true, true);*/ - Game::logger->Log("SGCannon", "Sending ActivityEnter\n"); + Game::logger->Log("SGCannon", "Sending ActivityEnter"); GameMessages::SendActivityEnter(self->GetObjectID(), player->GetSystemAddress()); @@ -87,14 +87,14 @@ void SGCannon::OnActivityStateChangeRequest(Entity *self, LWOOBJID senderID, int if (shootingGalleryComponent != nullptr) { shootingGalleryComponent->SetCurrentPlayerID(player->GetObjectID()); - Game::logger->Log("SGCannon", "Setting player ID\n"); + Game::logger->Log("SGCannon", "Setting player ID"); EntityManager::Instance()->SerializeEntity(self); } else { - Game::logger->Log("SGCannon", "Shooting gallery component is null\n"); + Game::logger->Log("SGCannon", "Shooting gallery component is null"); } - + auto* characterComponent = player->GetComponent(); if (characterComponent != nullptr) { @@ -112,11 +112,11 @@ void SGCannon::OnActivityStateChangeRequest(Entity *self, LWOOBJID senderID, int self->SetNetworkVar(HideScoreBoardVariable, true); self->SetNetworkVar(ReSetSuperChargeVariable, true); self->SetNetworkVar(ShowLoadingUI, true); - + /* GameMessages::SendTeleport( - player->GetObjectID(), - {-292.6415710449219, 230.20237731933594, -3.9090466499328613}, + player->GetObjectID(), + {-292.6415710449219, 230.20237731933594, -3.9090466499328613}, {0.7067984342575073, -6.527870573336259e-05, 0.707414984703064, 0.00021762956748716533}, player->GetSystemAddress(), true ); @@ -125,7 +125,7 @@ void SGCannon::OnActivityStateChangeRequest(Entity *self, LWOOBJID senderID, int //GameMessages::SendRequestActivityEnter(self->GetObjectID(), player->GetSystemAddress(), false, player->GetObjectID()); } else { - Game::logger->Log("SGCannon", "Player not found\n"); + Game::logger->Log("SGCannon", "Player not found"); } } else if (value1 == 1200) { @@ -193,7 +193,7 @@ void SGCannon::OnActivityTimerDone(Entity *self, const std::string &name) { SpawnObject(self, enemyToSpawn, true); } - Game::logger->Log("SGCannon", "Current wave spawn: %i/%i\n", wave, m_Waves.size()); + Game::logger->Log("SGCannon", "Current wave spawn: %i/%i", wave, m_Waves.size()); // All waves completed const auto timeLimit = (float_t) self->GetVar(TimeLimitVariable); @@ -208,7 +208,7 @@ void SGCannon::OnActivityTimerDone(Entity *self, const std::string &name) { GameMessages::SendPlayFXEffect(player->GetObjectID(), -1, u"SG-start", ""); GameMessages::SendStartActivityTime(self->GetObjectID(), timeLimit, player->GetSystemAddress()); - Game::logger->Log("SGCannon", "Sending ActivityPause false\n"); + Game::logger->Log("SGCannon", "Sending ActivityPause false"); GameMessages::SendActivityPause(self->GetObjectID(), false, player->GetSystemAddress()); } @@ -229,7 +229,7 @@ void SGCannon::OnActivityTimerDone(Entity *self, const std::string &name) { self->SetNetworkVar(WaveNumVariable, self->GetVar(ThisWaveVariable) + 1); self->SetNetworkVar(WaveStrVariable, self->GetVar(TimeLimitVariable)); - Game::logger->Log("SGCannon", "Current wave: %i/%i\n", self->GetVar(ThisWaveVariable), m_Waves.size()); + Game::logger->Log("SGCannon", "Current wave: %i/%i", self->GetVar(ThisWaveVariable), m_Waves.size()); if (self->GetVar(ThisWaveVariable) >= m_Waves.size()) { ActivityTimerStart(self, GameOverTimer, 0.1, 0.1); @@ -237,7 +237,7 @@ void SGCannon::OnActivityTimerDone(Entity *self, const std::string &name) { ActivityTimerStart(self, SpawnWaveTimer, constants.inBetweenWavePause, constants.inBetweenWavePause); } - Game::logger->Log("SGCannon", "Sending ActivityPause true\n"); + Game::logger->Log("SGCannon", "Sending ActivityPause true"); GameMessages::SendActivityPause(self->GetObjectID(), true); if (self->GetVar(SuperChargeActiveVariable) && !self->GetVar(SuperChargePausedVariable)) { @@ -246,7 +246,7 @@ void SGCannon::OnActivityTimerDone(Entity *self, const std::string &name) { } else if (name == GameOverTimer) { auto* player = EntityManager::Instance()->GetEntity(self->GetVar(PlayerIDVariable)); if (player != nullptr) { - Game::logger->Log("SGCannon", "Sending ActivityPause true\n"); + Game::logger->Log("SGCannon", "Sending ActivityPause true"); GameMessages::SendActivityPause(self->GetObjectID(), true, player->GetSystemAddress()); @@ -288,7 +288,7 @@ void SGCannon::OnActivityTimerDone(Entity *self, const std::string &name) { new LDFData(u"groupID", u"SGEnemy") }; - Game::logger->Log("SGCannon", "Spawning enemy %i on path %s\n", toSpawn.lot, path->pathName.c_str()); + Game::logger->Log("SGCannon", "Spawning enemy %i on path %s", toSpawn.lot, path->pathName.c_str()); auto* enemy = EntityManager::Instance()->CreateEntity(info, nullptr, self); EntityManager::Instance()->ConstructEntity(enemy); @@ -297,7 +297,7 @@ void SGCannon::OnActivityTimerDone(Entity *self, const std::string &name) { auto* movementAI = new MovementAIComponent(enemy, {}); enemy->AddComponent(COMPONENT_TYPE_MOVEMENT_AI, movementAI); - + movementAI->SetSpeed(toSpawn.initialSpeed); movementAI->SetCurrentSpeed(toSpawn.initialSpeed); movementAI->SetHaltDistance(0.0f); @@ -349,7 +349,7 @@ void SGCannon::StartGame(Entity *self) { auto* player = EntityManager::Instance()->GetEntity(self->GetVar(PlayerIDVariable)); if (player != nullptr) { GetLeaderboardData(self, player->GetObjectID(), GetActivityID(self)); - Game::logger->Log("SGCannon", "Sending ActivityStart\n"); + Game::logger->Log("SGCannon", "Sending ActivityStart"); GameMessages::SendActivityStart(self->GetObjectID(), player->GetSystemAddress()); GameMessages::SendPlayFXEffect(self->GetObjectID(), -1, u"start", ""); @@ -554,7 +554,7 @@ void SGCannon::StopGame(Entity *self, bool cancel) { } auto* missionComponent = player->GetComponent(); - + if (missionComponent != nullptr) { missionComponent->Progress(MissionTaskType::MISSION_TASK_TYPE_MINIGAME, self->GetVar(TotalScoreVariable), self->GetObjectID(), "performact_score"); missionComponent->Progress(MissionTaskType::MISSION_TASK_TYPE_MINIGAME, self->GetVar(MaxStreakVariable), self->GetObjectID(), "performact_streak"); @@ -602,7 +602,7 @@ void SGCannon::StopGame(Entity *self, bool cancel) { ResetVars(self); } -void SGCannon::RegisterHit(Entity* self, Entity* target, const std::string& timerName) +void SGCannon::RegisterHit(Entity* self, Entity* target, const std::string& timerName) { const auto& spawnInfo = target->GetVar(u"SpawnData"); @@ -634,7 +634,7 @@ void SGCannon::RegisterHit(Entity* self, Entity* target, const std::string& time auto scScore = self->GetVar(TotalScoreVariable) - lastSuperTotal; - Game::logger->Log("SGCannon", "LastSuperTotal: %i, scScore: %i, constants.chargedPoints: %i\n", + Game::logger->Log("SGCannon", "LastSuperTotal: %i, scScore: %i, constants.chargedPoints: %i", lastSuperTotal, scScore, constants.chargedPoints ); @@ -674,7 +674,7 @@ void SGCannon::RegisterHit(Entity* self, Entity* target, const std::string& time missionComponent->Progress(MissionTaskType::MISSION_TASK_TYPE_SMASH, spawnInfo.lot, self->GetObjectID()); } -void SGCannon::UpdateStreak(Entity* self) +void SGCannon::UpdateStreak(Entity* self) { const auto streakBonus = GetCurrentBonus(self); @@ -705,7 +705,7 @@ void SGCannon::UpdateStreak(Entity* self) if (maxStreak < curStreak) self->SetVar(MaxStreakVariable, curStreak); } -float_t SGCannon::GetCurrentBonus(Entity* self) +float_t SGCannon::GetCurrentBonus(Entity* self) { auto streak = self->GetVar(u"m_curStreak"); @@ -723,7 +723,7 @@ void SGCannon::ToggleSuperCharge(Entity *self, bool enable) { auto* player = EntityManager::Instance()->GetEntity(self->GetVar(PlayerIDVariable)); if (player == nullptr) { - Game::logger->Log("SGCannon", "Player not found in toggle super charge\n"); + Game::logger->Log("SGCannon", "Player not found in toggle super charge"); return; } @@ -731,7 +731,7 @@ void SGCannon::ToggleSuperCharge(Entity *self, bool enable) { auto equippedItems = inventoryComponent->GetEquippedItems(); - Game::logger->Log("SGCannon", "Player has %d equipped items\n", equippedItems.size()); + Game::logger->Log("SGCannon", "Player has %d equipped items", equippedItems.size()); auto skillID = constants.cannonSkill; auto coolDown = constants.cannonRefireRate; @@ -739,12 +739,12 @@ void SGCannon::ToggleSuperCharge(Entity *self, bool enable) { auto* selfInventoryComponent = self->GetComponent(); if (inventoryComponent == nullptr) { - Game::logger->Log("SGCannon", "Inventory component not found\n"); + Game::logger->Log("SGCannon", "Inventory component not found"); return; } if (enable) { - Game::logger->Log("SGCannon", "Player is activating super charge\n"); + Game::logger->Log("SGCannon", "Player is activating super charge"); selfInventoryComponent->UpdateSlot("greeble_r", { ObjectIDManager::GenerateRandomObjectID(), 6505, 1, 0 }); selfInventoryComponent->UpdateSlot("greeble_l", { ObjectIDManager::GenerateRandomObjectID(), 6506, 1, 0 }); @@ -754,15 +754,15 @@ void SGCannon::ToggleSuperCharge(Entity *self, bool enable) { } else { selfInventoryComponent->UpdateSlot("greeble_r", { ObjectIDManager::GenerateRandomObjectID(), 0, 0, 0 }); selfInventoryComponent->UpdateSlot("greeble_l", { ObjectIDManager::GenerateRandomObjectID(), 0, 0, 0 }); - + self->SetNetworkVar(u"SuperChargeBar", 0); - Game::logger->Log("SGCannon", "Player disables super charge\n"); - + Game::logger->Log("SGCannon", "Player disables super charge"); + // TODO: Unequip items for (const auto& equipped : equippedItems) { if (equipped.first == "special_r" || equipped.first == "special_l") { - Game::logger->Log("SGCannon", "Trying to unequip a weapon, %i\n", equipped.second.lot); + Game::logger->Log("SGCannon", "Trying to unequip a weapon, %i", equipped.second.lot); auto* item = inventoryComponent->FindItemById(equipped.second.id); @@ -770,7 +770,7 @@ void SGCannon::ToggleSuperCharge(Entity *self, bool enable) { inventoryComponent->UnEquipItem(item); } else { - Game::logger->Log("SGCannon", "Item not found, %i\n", equipped.second.lot); + Game::logger->Log("SGCannon", "Item not found, %i", equipped.second.lot); } } } @@ -787,7 +787,7 @@ void SGCannon::ToggleSuperCharge(Entity *self, bool enable) { } DynamicShootingGalleryParams properties = shootingGalleryComponent->GetDynamicParams(); - + properties.cannonFOV = 58.6f; properties.cannonVelocity = 129.0; properties.cannonRefireRate = 800; diff --git a/dWorldServer/WorldServer.cpp b/dWorldServer/WorldServer.cpp index 96149ae4..084b465a 100644 --- a/dWorldServer/WorldServer.cpp +++ b/dWorldServer/WorldServer.cpp @@ -127,9 +127,9 @@ int main(int argc, char** argv) { if (!Game::logger) return 0; Game::logger->SetLogToConsole(true); //We want this info to always be logged. - Game::logger->Log("WorldServer", "Starting World server...\n"); - Game::logger->Log("WorldServer", "Version: %i.%i\n", PROJECT_VERSION_MAJOR, PROJECT_VERSION_MINOR); - Game::logger->Log("WorldServer", "Compiled on: %s\n", __TIMESTAMP__); + Game::logger->Log("WorldServer", "Starting World server..."); + Game::logger->Log("WorldServer", "Version: %i.%i", PROJECT_VERSION_MAJOR, PROJECT_VERSION_MINOR); + Game::logger->Log("WorldServer", "Compiled on: %s", __TIMESTAMP__); #ifndef _DEBUG Game::logger->SetLogToConsole(false); //By default, turn it back off if not in debug. @@ -146,9 +146,9 @@ int main(int argc, char** argv) { try { CDClientDatabase::Connect("./res/CDServer.sqlite"); } catch (CppSQLite3Exception& e) { - Game::logger->Log("WorldServer", "Unable to connect to CDServer SQLite Database\n"); - Game::logger->Log("WorldServer", "Error: %s\n", e.errorMessage()); - Game::logger->Log("WorldServer", "Error Code: %i\n", e.errorCode()); + Game::logger->Log("WorldServer", "Unable to connect to CDServer SQLite Database"); + Game::logger->Log("WorldServer", "Error: %s", e.errorMessage()); + Game::logger->Log("WorldServer", "Error Code: %i", e.errorCode()); return -1; } @@ -170,7 +170,7 @@ int main(int argc, char** argv) { try { Database::Connect(mysql_host, mysql_database, mysql_username, mysql_password); } catch (sql::SQLException& ex) { - Game::logger->Log("WorldServer", "Got an error while connecting to the database: %s\n", ex.what()); + Game::logger->Log("WorldServer", "Got an error while connecting to the database: %s", ex.what()); return 0; } @@ -277,7 +277,7 @@ int main(int argc, char** argv) { delete md5; - Game::logger->Log("WorldServer", "FDB Checksum calculated as: %s\n", databaseChecksum.c_str()); + Game::logger->Log("WorldServer", "FDB Checksum calculated as: %s", databaseChecksum.c_str()); } } @@ -304,7 +304,7 @@ int main(int argc, char** argv) { //Warning if we ran slow if (deltaTime > currentFramerate) { - Game::logger->Log("WorldServer", "We're running behind, dT: %f > %f (framerate)\n", deltaTime, currentFramerate); + Game::logger->Log("WorldServer", "We're running behind, dT: %f > %f (framerate)", deltaTime, currentFramerate); } //Check if we're still connected to master: @@ -313,7 +313,7 @@ int main(int argc, char** argv) { int framesToWaitForMaster = ready ? 10 : 200; if (framesSinceMasterDisconnect >= framesToWaitForMaster && !worldShutdownSequenceStarted) { - Game::logger->Log("WorldServer", "Game loop running but no connection to master for %d frames, shutting down\n", framesToWaitForMaster); + Game::logger->Log("WorldServer", "Game loop running but no connection to master for %d frames, shutting down", framesToWaitForMaster); worldShutdownSequenceStarted = true; } } @@ -470,7 +470,7 @@ int main(int argc, char** argv) { if (framesSinceMasterStatus >= 200) { - Game::logger->Log("WorldServer", "Finished loading world with zone (%i), ready up!\n", Game::server->GetZoneID()); + Game::logger->Log("WorldServer", "Finished loading world with zone (%i), ready up!", Game::server->GetZoneID()); MasterPackets::SendWorldReady(Game::server, Game::server->GetZoneID(), Game::server->GetInstanceID()); @@ -504,13 +504,13 @@ dLogger * SetupLogger(int zoneID, int instanceID) { void HandlePacketChat(Packet* packet) { if (packet->data[0] == ID_DISCONNECTION_NOTIFICATION || packet->data[0] == ID_CONNECTION_LOST) { - Game::logger->Log("WorldServer", "Lost our connection to chat, zone(%i), instance(%i)\n", Game::server->GetZoneID(), Game::server->GetInstanceID()); + Game::logger->Log("WorldServer", "Lost our connection to chat, zone(%i), instance(%i)", Game::server->GetZoneID(), Game::server->GetInstanceID()); chatConnected = false; } if (packet->data[0] == ID_CONNECTION_REQUEST_ACCEPTED) { - Game::logger->Log("WorldServer", "Established connection to chat, zone(%i), instance (%i)\n",Game::server -> GetZoneID(), Game::server -> GetInstanceID()); + Game::logger->Log("WorldServer", "Established connection to chat, zone(%i), instance (%i)",Game::server -> GetZoneID(), Game::server -> GetInstanceID()); Game::chatSysAddr = packet->systemAddress; chatConnected = true; @@ -556,7 +556,7 @@ void HandlePacketChat(Packet* packet) { inStream.Read(character); title += character; } - + len = 0; inStream.Read(len); for (int i = 0; len > i; i++) { @@ -617,21 +617,21 @@ void HandlePacketChat(Packet* packet) { { TeamManager::Instance()->DeleteTeam(teamID); - Game::logger->Log("WorldServer", "Deleting team (%llu)\n", teamID); + Game::logger->Log("WorldServer", "Deleting team (%llu)", teamID); break; } inStream.Read(lootOption); inStream.Read(memberCount); - Game::logger->Log("WorldServer", "Updating team (%llu), (%i), (%i)\n", teamID, lootOption, memberCount); + Game::logger->Log("WorldServer", "Updating team (%llu), (%i), (%i)", teamID, lootOption, memberCount); for (char i = 0; i < memberCount; i++) { LWOOBJID member = LWOOBJID_EMPTY; inStream.Read(member); members.push_back(member); - Game::logger->Log("WorldServer", "Updating team member (%llu)\n", member); + Game::logger->Log("WorldServer", "Updating team member (%llu)", member); } TeamManager::Instance()->UpdateTeam(teamID, lootOption, members); @@ -640,7 +640,7 @@ void HandlePacketChat(Packet* packet) { } default: - Game::logger->Log("WorldServer", "Received an unknown chat internal: %i\n", int(packet->data[3])); + Game::logger->Log("WorldServer", "Received an unknown chat internal: %i", int(packet->data[3])); } } } @@ -674,7 +674,7 @@ void HandlePacket(Packet* packet) { entity->GetCharacter()->SaveXMLToDatabase(); - Game::logger->Log("WorldServer", "Deleting player %llu\n", entity->GetObjectID()); + Game::logger->Log("WorldServer", "Deleting player %llu", entity->GetObjectID()); EntityManager::Instance()->DestroyEntity(entity); } @@ -741,12 +741,12 @@ void HandlePacket(Packet* packet) { //Verify it: if (userHash != it->second.hash) { - Game::logger->Log("WorldServer", "SOMEONE IS TRYING TO HACK? SESSION KEY MISMATCH: ours: %s != master: %s\n", userHash.c_str(), it->second.hash.c_str()); + Game::logger->Log("WorldServer", "SOMEONE IS TRYING TO HACK? SESSION KEY MISMATCH: ours: %s != master: %s", userHash.c_str(), it->second.hash.c_str()); Game::server->Disconnect(it->second.sysAddr, SERVER_DISCON_INVALID_SESSION_KEY); return; } else { - Game::logger->Log("WorldServer", "User %s authenticated with correct key.\n", username.c_str()); + Game::logger->Log("WorldServer", "User %s authenticated with correct key.", username.c_str()); UserManager::Instance()->DeleteUser(packet->systemAddress); @@ -791,7 +791,7 @@ void HandlePacket(Packet* packet) { case MSG_MASTER_AFFIRM_TRANSFER_REQUEST: { const uint64_t requestID = PacketUtils::ReadPacketU64(8, packet); - Game::logger->Log("MasterServer", "Got affirmation request of transfer %llu\n", requestID); + Game::logger->Log("MasterServer", "Got affirmation request of transfer %llu", requestID); CBITSTREAM @@ -804,7 +804,7 @@ void HandlePacket(Packet* packet) { case MSG_MASTER_SHUTDOWN: { worldShutdownSequenceStarted = true; - Game::logger->Log("WorldServer", "Got shutdown request from master, zone (%i), instance (%i)\n", Game::server->GetZoneID(), Game::server->GetInstanceID()); + Game::logger->Log("WorldServer", "Got shutdown request from master, zone (%i), instance (%i)", Game::server->GetZoneID(), Game::server->GetInstanceID()); break; } @@ -814,10 +814,10 @@ void HandlePacket(Packet* packet) { uint32_t sessionKey = inStream.Read(sessionKey); std::string username; - + uint32_t len; inStream.Read(len); - + for (int i = 0; i < len; i++) { char character; inStream.Read(character); username += character; @@ -826,13 +826,13 @@ void HandlePacket(Packet* packet) { //Find them: User* user = UserManager::Instance()->GetUser(username.c_str()); if (!user) { - Game::logger->Log("WorldServer", "Got new session alert for user %s, but they're not logged in.\n", username.c_str()); + Game::logger->Log("WorldServer", "Got new session alert for user %s, but they're not logged in.", username.c_str()); return; } //Check the key: if (sessionKey != std::atoi(user->GetSessionKey().c_str())) { - Game::logger->Log("WorldServer", "Got new session alert for user %s, but the session key is invalid.\n", username.c_str()); + Game::logger->Log("WorldServer", "Got new session alert for user %s, but the session key is invalid.", username.c_str()); Game::server->Disconnect(user->GetSystemAddress(), SERVER_DISCON_INVALID_SESSION_KEY); return; } @@ -840,7 +840,7 @@ void HandlePacket(Packet* packet) { } default: - Game::logger->Log("WorldServer", "Unknown packet ID from master %i\n", int(packet->data[3])); + Game::logger->Log("WorldServer", "Unknown packet ID from master %i", int(packet->data[3])); } return; @@ -873,7 +873,7 @@ void HandlePacket(Packet* packet) { // Developers may skip this check if (gmLevel < 8 && clientDatabaseChecksum != databaseChecksum) { - Game::logger->Log("WorldServer", "Client's database checksum does not match the server's, aborting connection.\n"); + Game::logger->Log("WorldServer", "Client's database checksum does not match the server's, aborting connection."); Game::server->Disconnect(packet->systemAddress, SERVER_DISCON_KICK); return; } @@ -949,7 +949,7 @@ void HandlePacket(Packet* packet) { playerID = GeneralUtils::ClearBit(playerID, OBJECT_BIT_PERSISTENT); auto user = UserManager::Instance()->GetUser(packet->systemAddress); - + if (user) { auto lastCharacter = user->GetLoggedInChar(); // This means we swapped characters and we need to remove the previous player from the container. @@ -977,7 +977,7 @@ void HandlePacket(Packet* packet) { } case MSG_WORLD_CLIENT_LEVEL_LOAD_COMPLETE: { - Game::logger->Log("WorldServer", "Received level load complete from user.\n"); + Game::logger->Log("WorldServer", "Received level load complete from user."); User* user = UserManager::Instance()->GetUser(packet->systemAddress); if (user) { Character* c = user->GetLastUsedChar(); @@ -1036,7 +1036,7 @@ void HandlePacket(Packet* packet) { auto result = query.execQuery(); if (result.eof() || result.fieldIsNull(0)) { - Game::logger->Log("WorldServer", "No property templates found for zone %d, not sending BBB\n", zoneId); + Game::logger->Log("WorldServer", "No property templates found for zone %d, not sending BBB", zoneId); goto noBBB; } @@ -1064,7 +1064,7 @@ void HandlePacket(Packet* packet) { stmt->setUInt64(1, propertyId); auto res = stmt->executeQuery(); while (res->next()) { - Game::logger->Log("UGC", "Getting lxfml ugcID: " + std::to_string(res->getUInt(1)) + "\n"); + Game::logger->Log("UGC", "Getting lxfml ugcID: " + std::to_string(res->getUInt(1))); //Get lxfml: auto stmtL = Database::CreatePreppedStmt("SELECT lxfml from ugc where id=?"); @@ -1154,11 +1154,11 @@ void HandlePacket(Packet* packet) { } } else { - Game::logger->Log("WorldServer", "Couldn't find character to log in with for user %s (%i)!\n", user->GetUsername().c_str(), user->GetAccountID()); + Game::logger->Log("WorldServer", "Couldn't find character to log in with for user %s (%i)!", user->GetUsername().c_str(), user->GetAccountID()); Game::server->Disconnect(packet->systemAddress, SERVER_DISCON_CHARACTER_NOT_FOUND); } } else { - Game::logger->Log("WorldServer", "Couldn't get user for level load complete!\n"); + Game::logger->Log("WorldServer", "Couldn't get user for level load complete!"); } break; } @@ -1185,7 +1185,7 @@ void HandlePacket(Packet* packet) { inStream.Read(size); if (size > 20000) { - Game::logger->Log("WorldServer", "Tried to route a packet with a read size > 20000, so likely a false packet.\n"); + Game::logger->Log("WorldServer", "Tried to route a packet with a read size > 20000, so likely a false packet."); return; } @@ -1248,38 +1248,36 @@ void HandlePacket(Packet* packet) { } default: - Game::server->GetLogger()->Log("HandlePacket", "Unknown world packet received: %i\n", int(packet->data[3])); + Game::server->GetLogger()->Log("HandlePacket", "Unknown world packet received: %i", int(packet->data[3])); } } void WorldShutdownProcess(uint32_t zoneId) { - Game::logger->Log("WorldServer", "Saving map %i instance %i\n", zoneId, instanceID); + Game::logger->Log("WorldServer", "Saving map %i instance %i", zoneId, instanceID); for (auto i = 0; i < Game::server->GetReplicaManager()->GetParticipantCount(); ++i) { const auto& player = Game::server->GetReplicaManager()->GetParticipantAtIndex(i); auto* entity = Player::GetPlayer(player); - Game::logger->Log("WorldServer", "Saving data!\n"); + Game::logger->Log("WorldServer", "Saving data!"); if (entity != nullptr && entity->GetCharacter() != nullptr) { auto* skillComponent = entity->GetComponent(); if (skillComponent != nullptr) { skillComponent->Reset(); } - std::string message = "Saving character " + entity->GetCharacter()->GetName() + "...\n"; - Game::logger->Log("WorldServer", message); + Game::logger->Log("WorldServer", "Saving character %s...", entity->GetCharacter()->GetName().c_str()); entity->GetCharacter()->SaveXMLToDatabase(); - message = "Character data for " + entity->GetCharacter()->GetName() + " was saved!\n"; - Game::logger->Log("WorldServer", message); + Game::logger->Log("WorldServer", "Character data for %s was saved!", entity->GetCharacter()->GetName().c_str()); } } if (PropertyManagementComponent::Instance() != nullptr) { - Game::logger->Log("WorldServer", "Saving ALL property data for zone %i clone %i!\n", zoneId, PropertyManagementComponent::Instance()->GetCloneId()); + Game::logger->Log("WorldServer", "Saving ALL property data for zone %i clone %i!", zoneId, PropertyManagementComponent::Instance()->GetCloneId()); PropertyManagementComponent::Instance()->Save(); - Game::logger->Log("WorldServer", "ALL property data saved for zone %i clone %i!\n", zoneId, PropertyManagementComponent::Instance()->GetCloneId()); + Game::logger->Log("WorldServer", "ALL property data saved for zone %i clone %i!", zoneId, PropertyManagementComponent::Instance()->GetCloneId()); } - Game::logger->Log("WorldServer", "ALL DATA HAS BEEN SAVED FOR ZONE %i INSTANCE %i!\n", zoneId, instanceID); + Game::logger->Log("WorldServer", "ALL DATA HAS BEEN SAVED FOR ZONE %i INSTANCE %i!", zoneId, instanceID); while (Game::server->GetReplicaManager()->GetParticipantCount() > 0) { const auto& player = Game::server->GetReplicaManager()->GetParticipantAtIndex(0); @@ -1296,7 +1294,7 @@ void WorldShutdownSequence() { worldShutdownSequenceStarted = true; - Game::logger->Log("WorldServer", "Zone (%i) instance (%i) shutting down outside of main loop!\n", Game::server->GetZoneID(), instanceID); + Game::logger->Log("WorldServer", "Zone (%i) instance (%i) shutting down outside of main loop!", Game::server->GetZoneID(), instanceID); WorldShutdownProcess(Game::server->GetZoneID()); FinalizeShutdown(); } @@ -1306,7 +1304,7 @@ void FinalizeShutdown() { if (Game::physicsWorld) Game::physicsWorld = nullptr; if (Game::zoneManager) delete Game::zoneManager; - Game::logger->Log("WorldServer", "Shutdown complete, zone (%i), instance (%i)\n", Game::server->GetZoneID(), instanceID); + Game::logger->Log("WorldServer", "Shutdown complete, zone (%i), instance (%i)", Game::server->GetZoneID(), instanceID); Metrics::Clear(); Database::Destroy("WorldServer"); diff --git a/dZoneManager/Level.cpp b/dZoneManager/Level.cpp index b678ed95..afd2413e 100644 --- a/dZoneManager/Level.cpp +++ b/dZoneManager/Level.cpp @@ -18,11 +18,10 @@ Level::Level(Zone* parentZone, const std::string& filepath) { m_ParentZone = parentZone; std::ifstream file(filepath, std::ios_base::in | std::ios_base::binary); if (file) { - //printf("Opened %s\n", filepath.c_str()); ReadChunks(file); } else { - Game::logger->Log("Level", "Failed to load %s\n", filepath.c_str()); + Game::logger->Log("Level", "Failed to load %s", filepath.c_str()); } file.close(); @@ -96,7 +95,7 @@ void Level::ReadChunks(std::ifstream & file) { for (uint32_t i = 0; i < s; ++i) { file.ignore(4); //a uint file.ignore(4); //two floats - file.ignore(4); + file.ignore(4); } } } @@ -110,7 +109,7 @@ void Level::ReadChunks(std::ifstream & file) { if (header.chunkVersion >= 36) { file.ignore(3 * 4); } - + if (header.chunkVersion < 42) { file.ignore(3 * 4); @@ -176,7 +175,7 @@ void Level::ReadSceneObjectDataChunk(std::ifstream & file, Header & header) { BinaryIO::BinaryRead(file, obj.rotation); BinaryIO::BinaryRead(file, obj.scale); - //This is a little bit of a bodge, but because the alpha client (HF) doesn't store the + //This is a little bit of a bodge, but because the alpha client (HF) doesn't store the //spawn position / rotation like the later versions do, we need to check the LOT for the spawn pos & set it. if (obj.lot == LOT_MARKER_PLAYER_START) { dZoneManager::Instance()->GetZone()->SetSpawnPos(obj.position); @@ -186,18 +185,18 @@ void Level::ReadSceneObjectDataChunk(std::ifstream & file, Header & header) { std::u16string ldfString = u""; uint32_t length = 0; BinaryIO::BinaryRead(file, length); - + for (uint32_t i = 0; i < length; ++i) { uint16_t data; BinaryIO::BinaryRead(file, data); ldfString.push_back(data); } - + std::string sData = GeneralUtils::UTF16ToWTF8(ldfString); std::stringstream ssData(sData); std::string token; char deliminator = '\n'; - + while (std::getline(ssData, token, deliminator)) { LDFBaseData * ldfData = LDFBaseData::DataFromString(token); obj.settings.push_back(ldfData); @@ -260,11 +259,11 @@ void Level::ReadSceneObjectDataChunk(std::ifstream & file, Header & header) { if (data->GetKey() == u"spawner_active_on_load") { spawnInfo.activeOnLoad = std::stoi(data->GetValueAsString()); } - + if (data->GetKey() == u"active_on_load") { spawnInfo.activeOnLoad = std::stoi(data->GetValueAsString()); } - + if (data->GetKey() == u"respawn") { if (data->GetValueType() == eLDFType::LDF_TYPE_FLOAT) // Floats are in seconds { @@ -350,6 +349,5 @@ void Level::ReadSceneObjectDataChunk(std::ifstream & file, Header & header) { } } - //printf("Loaded %u objects!\n", objectsCount); header.sceneObjects = chunk; } diff --git a/dZoneManager/Zone.cpp b/dZoneManager/Zone.cpp index 68adb943..36245df4 100644 --- a/dZoneManager/Zone.cpp +++ b/dZoneManager/Zone.cpp @@ -24,7 +24,7 @@ Zone::Zone(const LWOMAPID & mapID, const LWOINSTANCEID & instanceID, const LWOCL } Zone::~Zone() { - Game::logger->Log("Zone", "Destroying zone %i\n", m_ZoneID.GetMapID()); + Game::logger->Log("Zone", "Destroying zone %i", m_ZoneID.GetMapID()); for (std::map::iterator it = m_Scenes.begin(); it != m_Scenes.end(); ++it) { if (it->second.level != nullptr) delete it->second.level; } @@ -45,12 +45,12 @@ void Zone::LoadZoneIntoMemory() { std::ifstream file(m_ZoneFilePath, std::ios::binary); if (file) { BinaryIO::BinaryRead(file, m_ZoneFileFormatVersion); - + uint32_t mapRevision = 0; if (m_ZoneFileFormatVersion >= Zone::ZoneFileFormatVersion::Alpha) BinaryIO::BinaryRead(file, mapRevision); - + BinaryIO::BinaryRead(file, m_WorldID); - if ((uint16_t)m_WorldID != m_ZoneID.GetMapID()) Game::logger->Log("Zone", "WorldID: %i doesn't match MapID %i! Is this intended?\n", m_WorldID, m_ZoneID.GetMapID()); + if ((uint16_t)m_WorldID != m_ZoneID.GetMapID()) Game::logger->Log("Zone", "WorldID: %i doesn't match MapID %i! Is this intended?", m_WorldID, m_ZoneID.GetMapID()); AddRevision(LWOSCENEID_INVALID, mapRevision); @@ -58,7 +58,7 @@ void Zone::LoadZoneIntoMemory() { BinaryIO::BinaryRead(file, m_Spawnpoint); BinaryIO::BinaryRead(file, m_SpawnpointRotation); } - + if (m_ZoneFileFormatVersion <= Zone::ZoneFileFormatVersion::LateAlpha) { uint8_t sceneCount; BinaryIO::BinaryRead(file, sceneCount); @@ -102,7 +102,7 @@ void Zone::LoadZoneIntoMemory() { for (uint32_t i = 0; i < pathCount; ++i) { LoadPath(file); } - + for (Path path : m_Paths) { if (path.pathType == PathType::Spawner) { SpawnerInfo info = SpawnerInfo(); @@ -150,16 +150,16 @@ void Zone::LoadZoneIntoMemory() { Spawner* spawner = new Spawner(info); dZoneManager::Instance()->AddSpawner(info.spawnerID, spawner); } - + } - + //m_PathData.resize(m_PathDataLength); //file.read((char*)&m_PathData[0], m_PathDataLength); } } else { - Game::logger->Log("Zone", "Failed to open: %s\n", m_ZoneFilePath.c_str()); + Game::logger->Log("Zone", "Failed to open: %s", m_ZoneFilePath.c_str()); } m_ZonePath = m_ZoneFilePath.substr(0, m_ZoneFilePath.rfind('/') + 1); @@ -226,7 +226,7 @@ void Zone::AddRevision(LWOSCENEID sceneID, uint32_t revision) { const void Zone::PrintAllGameObjects() { for (std::pair scene : m_Scenes) { - Game::logger->Log("Zone", "\nIn sceneID: %i\n\n", scene.first.GetSceneID()); + Game::logger->Log("Zone", "In sceneID: %i", scene.first.GetSceneID()); scene.second.level->PrintAllObjects(); } } @@ -242,7 +242,7 @@ void Zone::LoadScene(std::ifstream & file) { std::string luTriggersPath = scene.filename.substr(0, scene.filename.size() - 4) + ".lutriggers"; std::vector triggers = LoadLUTriggers(luTriggersPath, scene.id); - + for (LUTriggers::Trigger* trigger : triggers) { scene.triggers.insert({ trigger->id, trigger }); } @@ -283,13 +283,13 @@ std::vector Zone::LoadLUTriggers(std::string triggerFile, if (!doc) return lvlTriggers; if (doc->Parse(data.str().c_str(), data.str().size()) == 0) { - //Game::logger->Log("Zone", "Loaded LUTriggers from file %s!\n", triggerFile.c_str()); + //Game::logger->Log("Zone", "Loaded LUTriggers from file %s!", triggerFile.c_str()); } else { - Game::logger->Log("Zone", "Failed to load LUTriggers from file %s\n", triggerFile.c_str()); + Game::logger->Log("Zone", "Failed to load LUTriggers from file %s", triggerFile.c_str()); return lvlTriggers; } - + tinyxml2::XMLElement* triggers = doc->FirstChildElement("triggers"); if (!triggers) return lvlTriggers; @@ -323,7 +323,7 @@ std::vector Zone::LoadLUTriggers(std::string triggerFile, currentTrigger = currentTrigger->NextSiblingElement("trigger"); lvlTriggers.push_back(newTrigger); } - + delete doc; return lvlTriggers; @@ -474,8 +474,8 @@ void Zone::LoadPath(std::ifstream & file) { BinaryIO::BinaryRead(file, waypoint.position.x); BinaryIO::BinaryRead(file, waypoint.position.y); BinaryIO::BinaryRead(file, waypoint.position.z); - - + + if (path.pathType == PathType::Spawner || path.pathType == PathType::MovingPlatform || path.pathType == PathType::Race) { BinaryIO::BinaryRead(file, waypoint.rotation.w); BinaryIO::BinaryRead(file, waypoint.rotation.x); @@ -565,7 +565,7 @@ void Zone::LoadPath(std::ifstream & file) { path.pathWaypoints.push_back(waypoint); } - + m_Paths.push_back(path); } diff --git a/dZoneManager/dZoneManager.cpp b/dZoneManager/dZoneManager.cpp index 12215378..89f4b6f8 100644 --- a/dZoneManager/dZoneManager.cpp +++ b/dZoneManager/dZoneManager.cpp @@ -15,7 +15,7 @@ dZoneManager* dZoneManager::m_Address = nullptr; void dZoneManager::Initialize(const LWOZONEID& zoneID) { - Game::logger->Log("dZoneManager", "Preparing zone: %i/%i/%i\n", zoneID.GetMapID(), zoneID.GetInstanceID(), zoneID.GetCloneID()); + Game::logger->Log("dZoneManager", "Preparing zone: %i/%i/%i", zoneID.GetMapID(), zoneID.GetInstanceID(), zoneID.GetCloneID()); int64_t startTime = 0; int64_t endTime = 0; @@ -40,7 +40,7 @@ void dZoneManager::Initialize(const LWOZONEID& zoneID) { } } - Game::logger->Log("dZoneManager", "Creating zone control object %i\n", zoneControlTemplate); + Game::logger->Log("dZoneManager", "Creating zone control object %i", zoneControlTemplate); // Create ZoneControl object EntityInfo info; @@ -53,7 +53,7 @@ void dZoneManager::Initialize(const LWOZONEID& zoneID) { endTime = std::chrono::duration_cast(std::chrono::steady_clock::now().time_since_epoch()).count(); - Game::logger->Log("dZoneManager", "Zone prepared in: %llu ms\n", (endTime - startTime)); + Game::logger->Log("dZoneManager", "Zone prepared in: %llu ms", (endTime - startTime)); VanityUtilities::SpawnVanity(); } @@ -89,7 +89,7 @@ void dZoneManager::NotifyZone(const dZoneNotifier & notifier, const LWOOBJID& ob case dZoneNotifier::SpawnedChildObjectDestroyed: break; case dZoneNotifier::ReloadZone: - Game::logger->Log("dZoneManager", "Forcing reload of zone %i\n", m_ZoneID.GetMapID()); + Game::logger->Log("dZoneManager", "Forcing reload of zone %i", m_ZoneID.GetMapID()); LoadZone(m_ZoneID); m_pZone->Initalize(); @@ -102,10 +102,10 @@ void dZoneManager::NotifyZone(const dZoneNotifier & notifier, const LWOOBJID& ob m_pZone->PrintAllGameObjects(); break; case dZoneNotifier::InvalidNotifier: - Game::logger->Log("dZoneManager", "Got an invalid zone notifier.\n"); + Game::logger->Log("dZoneManager", "Got an invalid zone notifier."); break; default: - Game::logger->Log("dZoneManager", "Unknown zone notifier: %i\n", int(notifier)); + Game::logger->Log("dZoneManager", "Unknown zone notifier: %i", int(notifier)); } } @@ -188,7 +188,7 @@ void dZoneManager::RemoveSpawner(const LWOOBJID id) auto* spawner = GetSpawner(id); if (spawner == nullptr) { - Game::logger->Log("dZoneManager", "Failed to find spawner (%llu)\n", id); + Game::logger->Log("dZoneManager", "Failed to find spawner (%llu)", id); return; } @@ -199,7 +199,7 @@ void dZoneManager::RemoveSpawner(const LWOOBJID id) } else { - Game::logger->Log("dZoneManager", "Failed to find spawner entity (%llu)\n", id); + Game::logger->Log("dZoneManager", "Failed to find spawner entity (%llu)", id); } for (auto* node : spawner->m_Info.nodes) @@ -218,7 +218,7 @@ void dZoneManager::RemoveSpawner(const LWOOBJID id) spawner->Deactivate(); - Game::logger->Log("dZoneManager", "Destroying spawner (%llu)\n", id); + Game::logger->Log("dZoneManager", "Destroying spawner (%llu)", id); m_Spawners.erase(id); From 9813c3ed2ca60145c5934c73379b8f41b9bb4e4d Mon Sep 17 00:00:00 2001 From: Daniel Seiler Date: Tue, 26 Jul 2022 06:11:30 +0200 Subject: [PATCH 22/86] Better Unicode support in GeneralUtils (#658) * ASCIIToUTF16: output replacement character instead of failing assert * Add GeneralUtils::_NextUTF8Char * Implement GeneralUtils::UTF8ToUTF16 * use string_view everywhere * use string_view::front instead of begin * Add PushUTF16CodePoint --- dCommon/GeneralUtils.cpp | 119 +++++++++++++++++++++++++++++++++++++-- dCommon/GeneralUtils.h | 15 ++++- tests/CMakeLists.txt | 1 + tests/TestEncoding.cpp | 52 +++++++++++++++++ 4 files changed, 179 insertions(+), 8 deletions(-) create mode 100644 tests/TestEncoding.cpp diff --git a/dCommon/GeneralUtils.cpp b/dCommon/GeneralUtils.cpp index 01306226..eafa6a3b 100644 --- a/dCommon/GeneralUtils.cpp +++ b/dCommon/GeneralUtils.cpp @@ -6,7 +6,7 @@ #include template -inline size_t MinSize(size_t size, const std::basic_string& string) { +inline size_t MinSize(size_t size, const std::basic_string_view& string) { if (size == size_t(-1) || size > string.size()) { return string.size(); } else { @@ -24,7 +24,7 @@ inline bool IsTrailSurrogate(char16_t c) { inline void PushUTF8CodePoint(std::string& ret, char32_t cp) { if (cp <= 0x007F) { - ret.push_back(cp); + ret.push_back(static_cast(cp)); } else if (cp <= 0x07FF) { ret.push_back(0xC0 | (cp >> 6)); ret.push_back(0x80 | (cp & 0x3F)); @@ -42,16 +42,123 @@ inline void PushUTF8CodePoint(std::string& ret, char32_t cp) { } } +constexpr const char16_t REPLACEMENT_CHARACTER = 0xFFFD; + +bool _IsSuffixChar(uint8_t c) { + return (c & 0xC0) == 0x80; +} + +bool GeneralUtils::_NextUTF8Char(std::string_view& slice, uint32_t& out) { + size_t rem = slice.length(); + const uint8_t* bytes = (const uint8_t*) &slice.front(); + if (rem > 0) { + uint8_t first = bytes[0]; + if (first < 0x80) { // 1 byte character + out = static_cast(first & 0x7F); + slice.remove_prefix(1); + return true; + } else if (first < 0xC0) { + // middle byte, not valid at start, fall through + } else if (first < 0xE0) { // two byte character + if (rem > 1) { + uint8_t second = bytes[1]; + if (_IsSuffixChar(second)) { + out = (static_cast(first & 0x1F) << 6) + + static_cast(second & 0x3F); + slice.remove_prefix(2); + return true; + } + } + } else if (first < 0xF0) { // three byte character + if (rem > 2) { + uint8_t second = bytes[1]; + uint8_t third = bytes[2]; + if (_IsSuffixChar(second) && _IsSuffixChar(third)) { + out = (static_cast(first & 0x0F) << 12) + + (static_cast(second & 0x3F) << 6) + + static_cast(third & 0x3F); + slice.remove_prefix(3); + return true; + } + } + } else if (first < 0xF8) { // four byte character + if (rem > 3) { + uint8_t second = bytes[1]; + uint8_t third = bytes[2]; + uint8_t fourth = bytes[3]; + if (_IsSuffixChar(second) && _IsSuffixChar(third) && _IsSuffixChar(fourth)) { + out = (static_cast(first & 0x07) << 18) + + (static_cast(second & 0x3F) << 12) + + (static_cast(third & 0x3F) << 6) + + static_cast(fourth & 0x3F); + slice.remove_prefix(4); + return true; + } + } + } + out = static_cast(REPLACEMENT_CHARACTER); + slice.remove_prefix(1); + return true; + } + return false; +} + +/// See +bool PushUTF16CodePoint(std::u16string& output, uint32_t U, size_t size) { + if (output.length() >= size) return false; + if (U < 0x10000) { + // If U < 0x10000, encode U as a 16-bit unsigned integer and terminate. + output.push_back(static_cast(U)); + return true; + } else if (U > 0x10FFFF) { + output.push_back(REPLACEMENT_CHARACTER); + return true; + } else if (output.length() + 1 < size) { + // Let U' = U - 0x10000. Because U is less than or equal to 0x10FFFF, + // U' must be less than or equal to 0xFFFFF. That is, U' can be + // represented in 20 bits. + uint32_t Ut = U - 0x10000; + + // Initialize two 16-bit unsigned integers, W1 and W2, to 0xD800 and + // 0xDC00, respectively. These integers each have 10 bits free to + // encode the character value, for a total of 20 bits. + uint16_t W1 = 0xD800; + uint16_t W2 = 0xDC00; + + // Assign the 10 high-order bits of the 20-bit U' to the 10 low-order + // bits of W1 and the 10 low-order bits of U' to the 10 low-order + // bits of W2. + W1 += static_cast((Ut & 0x3FC00) >> 10); + W2 += static_cast((Ut & 0x3FF) >> 0); + + // Terminate. + output.push_back(W1); // high surrogate + output.push_back(W2); // low surrogate + return true; + } else return false; +} + +std::u16string GeneralUtils::UTF8ToUTF16(const std::string_view& string, size_t size) { + size_t newSize = MinSize(size, string); + std::u16string output; + output.reserve(newSize); + std::string_view iterator = string; + + uint32_t c; + while (_NextUTF8Char(iterator, c) && PushUTF16CodePoint(output, c, size)) {} + return output; +} + //! Converts an std::string (ASCII) to UCS-2 / UTF-16 -std::u16string GeneralUtils::ASCIIToUTF16(const std::string& string, size_t size) { +std::u16string GeneralUtils::ASCIIToUTF16(const std::string_view& string, size_t size) { size_t newSize = MinSize(size, string); std::u16string ret; ret.reserve(newSize); for (size_t i = 0; i < newSize; i++) { char c = string[i]; - assert(c > 0 && c <= 127); - ret.push_back(static_cast(c)); + // Note: both 7-bit ascii characters and REPLACEMENT_CHARACTER fit in one char16_t + ret.push_back((c > 0 && c <= 127) ? static_cast(c) : REPLACEMENT_CHARACTER); } return ret; @@ -59,7 +166,7 @@ std::u16string GeneralUtils::ASCIIToUTF16(const std::string& string, size_t size //! Converts a (potentially-ill-formed) UTF-16 string to UTF-8 //! See: -std::string GeneralUtils::UTF16ToWTF8(const std::u16string& string, size_t size) { +std::string GeneralUtils::UTF16ToWTF8(const std::u16string_view& string, size_t size) { size_t newSize = MinSize(size, string); std::string ret; ret.reserve(newSize); diff --git a/dCommon/GeneralUtils.h b/dCommon/GeneralUtils.h index 4973201e..f796839c 100644 --- a/dCommon/GeneralUtils.h +++ b/dCommon/GeneralUtils.h @@ -26,7 +26,18 @@ namespace GeneralUtils { \param size A size to trim the string to. Default is -1 (No trimming) \return An UTF-16 representation of the string */ - std::u16string ASCIIToUTF16(const std::string& string, size_t size = -1); + std::u16string ASCIIToUTF16(const std::string_view& string, size_t size = -1); + + //! Converts a UTF-8 String to a UTF-16 string + /*! + \param string The string to convert + \param size A size to trim the string to. Default is -1 (No trimming) + \return An UTF-16 representation of the string + */ + std::u16string UTF8ToUTF16(const std::string_view& string, size_t size = -1); + + //! Internal, do not use + bool _NextUTF8Char(std::string_view& slice, uint32_t& out); //! Converts a UTF-16 string to a UTF-8 string /*! @@ -34,7 +45,7 @@ namespace GeneralUtils { \param size A size to trim the string to. Default is -1 (No trimming) \return An UTF-8 representation of the string */ - std::string UTF16ToWTF8(const std::u16string& string, size_t size = -1); + std::string UTF16ToWTF8(const std::u16string_view& string, size_t size = -1); /** * Compares two basic strings but does so ignoring case sensitivity diff --git a/tests/CMakeLists.txt b/tests/CMakeLists.txt index 9c6e57d3..fb1ed5ac 100644 --- a/tests/CMakeLists.txt +++ b/tests/CMakeLists.txt @@ -4,6 +4,7 @@ create_test_sourcelist (Tests AMFDeserializeTests.cpp TestNiPoint3.cpp TestLDFFormat.cpp + TestEncoding.cpp ) # add the executable diff --git a/tests/TestEncoding.cpp b/tests/TestEncoding.cpp new file mode 100644 index 00000000..1e676ec3 --- /dev/null +++ b/tests/TestEncoding.cpp @@ -0,0 +1,52 @@ +#include +#include + +#include "GeneralUtils.h" +#include "CommonCxxTests.h" + +int TestEncoding(int argc, char* *const argv) { + std::string x = "Hello World!"; + std::string_view v(x); + + uint32_t out; + GeneralUtils::_NextUTF8Char(v, out); ASSERT_EQ(out, 'H'); + GeneralUtils::_NextUTF8Char(v, out); ASSERT_EQ(out, 'e'); + GeneralUtils::_NextUTF8Char(v, out); ASSERT_EQ(out, 'l'); + GeneralUtils::_NextUTF8Char(v, out); ASSERT_EQ(out, 'l'); + GeneralUtils::_NextUTF8Char(v, out); ASSERT_EQ(out, 'o'); + ASSERT_EQ(GeneralUtils::_NextUTF8Char(v, out), true); + + x = u8"Frühling"; + v = x; + GeneralUtils::_NextUTF8Char(v, out); ASSERT_EQ(out, U'F'); + GeneralUtils::_NextUTF8Char(v, out); ASSERT_EQ(out, U'r'); + GeneralUtils::_NextUTF8Char(v, out); ASSERT_EQ(out, U'ü'); + GeneralUtils::_NextUTF8Char(v, out); ASSERT_EQ(out, U'h'); + GeneralUtils::_NextUTF8Char(v, out); ASSERT_EQ(out, U'l'); + GeneralUtils::_NextUTF8Char(v, out); ASSERT_EQ(out, U'i'); + GeneralUtils::_NextUTF8Char(v, out); ASSERT_EQ(out, U'n'); + GeneralUtils::_NextUTF8Char(v, out); ASSERT_EQ(out, U'g'); + ASSERT_EQ(GeneralUtils::_NextUTF8Char(v, out), false); + + x = "中文字"; + v = x; + GeneralUtils::_NextUTF8Char(v, out); ASSERT_EQ(out, U'中'); + GeneralUtils::_NextUTF8Char(v, out); ASSERT_EQ(out, U'文'); + GeneralUtils::_NextUTF8Char(v, out); ASSERT_EQ(out, U'字'); + ASSERT_EQ(GeneralUtils::_NextUTF8Char(v, out), false); + + x = "👨‍⚖️"; + v = x; + GeneralUtils::_NextUTF8Char(v, out); ASSERT_EQ(out, 0x1F468); + GeneralUtils::_NextUTF8Char(v, out); ASSERT_EQ(out, 0x200D); + GeneralUtils::_NextUTF8Char(v, out); ASSERT_EQ(out, 0x2696); + GeneralUtils::_NextUTF8Char(v, out); ASSERT_EQ(out, 0xFE0F); + ASSERT_EQ(GeneralUtils::_NextUTF8Char(v, out), false); + + ASSERT_EQ(GeneralUtils::UTF8ToUTF16("Hello World!"), u"Hello World!"); + ASSERT_EQ(GeneralUtils::UTF8ToUTF16("Frühling"), u"Frühling"); + ASSERT_EQ(GeneralUtils::UTF8ToUTF16("中文字"), u"中文字"); + ASSERT_EQ(GeneralUtils::UTF8ToUTF16("👨‍⚖️"), u"👨‍⚖️"); + + return 0; +} From 9e08bb20d2c122326194b21a83aaf741347cbc24 Mon Sep 17 00:00:00 2001 From: Jett <55758076+Jettford@users.noreply.github.com> Date: Wed, 27 Jul 2022 02:52:04 +0100 Subject: [PATCH 23/86] Implement proper bounds checks across the codebase (#681) * Implement proper bounds checks across the codebase * Implement strnlen_s for cross platform --- dCommon/dLogger.cpp | 7 +++++++ dNet/PacketUtils.cpp | 17 ++++++++++------- dNet/PacketUtils.h | 2 +- 3 files changed, 18 insertions(+), 8 deletions(-) diff --git a/dCommon/dLogger.cpp b/dCommon/dLogger.cpp index 532a0cee..0beb5a3c 100644 --- a/dCommon/dLogger.cpp +++ b/dCommon/dLogger.cpp @@ -26,6 +26,13 @@ dLogger::~dLogger() { } void dLogger::vLog(const char* format, va_list args) { + const char* tempPtr = format; // strlen_s implementation for Linux and Windows + for (; *tempPtr != '\0'; ++tempPtr) { + size_t size = tempPtr - format; + if (size > 600) { + return; + } + } #ifdef _WIN32 time_t t = time(NULL); struct tm time; diff --git a/dNet/PacketUtils.cpp b/dNet/PacketUtils.cpp index a5d9f0ea..352f54b9 100644 --- a/dNet/PacketUtils.cpp +++ b/dNet/PacketUtils.cpp @@ -46,22 +46,25 @@ int64_t PacketUtils::ReadPacketS64(uint32_t startLoc, Packet * packet) { return *(int64_t*)t.data(); } -std::string PacketUtils::ReadString(uint32_t startLoc, Packet* packet, bool wide) { - std::string readString = ""; - +std::string PacketUtils::ReadString(uint32_t startLoc, Packet* packet, bool wide, uint32_t maxLen) { + std::string readString = ""; + + if (wide) maxLen *= 2; + if (packet->length > startLoc) { uint32_t i = 0; - while (packet->data[startLoc + i] != '\0' && packet->length > (uint32_t)(startLoc + i)) { + while (packet->data[startLoc + i] != '\0' && packet->length > (uint32_t)(startLoc + i) && maxLen > i) { readString.push_back(packet->data[startLoc + i]); - + if (wide) { i += 2; // Wide-char string - } else { + } + else { i++; // Regular string } } } - + return readString; } diff --git a/dNet/PacketUtils.h b/dNet/PacketUtils.h index 3426c3ab..61517ccf 100644 --- a/dNet/PacketUtils.h +++ b/dNet/PacketUtils.h @@ -11,7 +11,7 @@ namespace PacketUtils { uint32_t ReadPacketU32(uint32_t startLoc, Packet * packet); uint64_t ReadPacketU64(uint32_t startLoc, Packet * packet); int64_t ReadPacketS64(uint32_t startLoc, Packet * packet); - std::string ReadString(uint32_t startLoc, Packet * packet, bool wide); + std::string ReadString(uint32_t startLoc, Packet * packet, bool wide, uint32_t maxLen = 33); void WritePacketString(const std::string& string, uint32_t maxSize, RakNet::BitStream * bitStream); void WriteString(RakNet::BitStream& bitStream, const std::string& s, uint32_t maxSize); From a632ef8ccdd87316b27b941da18d051ed0ea32bf Mon Sep 17 00:00:00 2001 From: avery Date: Tue, 26 Jul 2022 23:52:53 -0700 Subject: [PATCH 24/86] Clean up format logs (#682) --- dDatabase/MigrationRunner.cpp | 4 ++-- dGame/dGameMessages/GameMessages.cpp | 6 +++--- dScripts/CppScripts.cpp | 2 +- dWorldServer/WorldServer.cpp | 4 ++-- 4 files changed, 8 insertions(+), 8 deletions(-) diff --git a/dDatabase/MigrationRunner.cpp b/dDatabase/MigrationRunner.cpp index 186368fd..a988acac 100644 --- a/dDatabase/MigrationRunner.cpp +++ b/dDatabase/MigrationRunner.cpp @@ -31,7 +31,7 @@ void MigrationRunner::RunMigrations() { delete stmt; if (doExit) continue; - Game::logger->Log("MigrationRunner", "Running migration: " + migration.name + ""); + Game::logger->Log("MigrationRunner", "Running migration: %s", migration.name.c_str()); finalSQL.append(migration.data); finalSQL.append('\n'); @@ -49,7 +49,7 @@ void MigrationRunner::RunMigrations() { delete simpleStatement; } catch (sql::SQLException e) { - Game::logger->Log("MigrationRunner", std::string("Encountered error running migration: ") + e.what() + ""); + Game::logger->Log("MigrationRunner", "Encountered error running migration: %s", e.what()); } } } diff --git a/dGame/dGameMessages/GameMessages.cpp b/dGame/dGameMessages/GameMessages.cpp index 365485f2..66d71ca1 100644 --- a/dGame/dGameMessages/GameMessages.cpp +++ b/dGame/dGameMessages/GameMessages.cpp @@ -2408,7 +2408,7 @@ void GameMessages::HandleBBBLoadItemRequest(RakNet::BitStream* inStream, Entity* LWOOBJID itemID = LWOOBJID_EMPTY; inStream->Read(itemID); - Game::logger->Log("BBB", "Load item request for: " + std::to_string(itemID) + ""); + Game::logger->Log("BBB", "Load item request for: %lld", itemID); CBITSTREAM; PacketUtils::WriteHeader(bitStream, CLIENT, MSG_CLIENT_BLUEPRINT_LOAD_RESPONSE_ITEMID); @@ -3848,7 +3848,7 @@ void GameMessages::HandleMessageBoxResponse(RakNet::BitStream* inStream, Entity* userData.push_back(character); } - Game::logger->Log("HandleMessageBoxResponse", "Button: " + std::to_string(iButton) + "; LOT: " + std::to_string(entity->GetLOT()) + " identifier: " + GeneralUtils::UTF16ToWTF8(identifier) + "; userData: " + GeneralUtils::UTF16ToWTF8(userData)); + Game::logger->Log("HandleMessageBoxResponse", "Button: %d; LOT: %u identifier: %s; userData: %s", iButton, entity->GetLOT(), GeneralUtils::UTF16ToWTF8(identifier).c_str(), GeneralUtils::UTF16ToWTF8(userData).c_str()); auto* user = UserManager::Instance()->GetUser(sysAddr); @@ -3912,7 +3912,7 @@ void GameMessages::HandleChoiceBoxRespond(RakNet::BitStream* inStream, Entity* e identifier.push_back(character); } - Game::logger->Log("HandleChoiceBoxRespond", "Button: " + std::to_string(iButton) + "; LOT: " + std::to_string(entity->GetLOT()) + " buttonIdentifier: " + GeneralUtils::UTF16ToWTF8(buttonIdentifier) + "; userData: " + GeneralUtils::UTF16ToWTF8(identifier)); + Game::logger->Log("HandleChoiceBoxRespond", "Button: %d; LOT: %u buttonIdentifier: %s; userData: %s", iButton, entity->GetLOT(), GeneralUtils::UTF16ToWTF8(buttonIdentifier).c_str(), GeneralUtils::UTF16ToWTF8(identifier).c_str()); auto* user = UserManager::Instance()->GetUser(sysAddr); diff --git a/dScripts/CppScripts.cpp b/dScripts/CppScripts.cpp index 8feb8ae7..8569bf9e 100644 --- a/dScripts/CppScripts.cpp +++ b/dScripts/CppScripts.cpp @@ -818,7 +818,7 @@ CppScripts::Script* CppScripts::GetScript(Entity* parent, const std::string& scr script = invalidToReturn; else if (script == invalidToReturn) { if (scriptName.length() > 0) - Game::logger->LogDebug("CppScripts", "Attempted to load CppScript for '" + scriptName + "', but returned InvalidScript."); + Game::logger->LogDebug("CppScripts", "Attempted to load CppScript for '%s', but returned InvalidScript.", scriptName.c_str()); // information not really needed for sys admins but is for developers script = invalidToReturn; diff --git a/dWorldServer/WorldServer.cpp b/dWorldServer/WorldServer.cpp index 084b465a..6d85b2cd 100644 --- a/dWorldServer/WorldServer.cpp +++ b/dWorldServer/WorldServer.cpp @@ -1064,7 +1064,7 @@ void HandlePacket(Packet* packet) { stmt->setUInt64(1, propertyId); auto res = stmt->executeQuery(); while (res->next()) { - Game::logger->Log("UGC", "Getting lxfml ugcID: " + std::to_string(res->getUInt(1))); + Game::logger->Log("UGC", "Getting lxfml ugcID: %u", res->getUInt(1)); //Get lxfml: auto stmtL = Database::CreatePreppedStmt("SELECT lxfml from ugc where id=?"); @@ -1321,4 +1321,4 @@ void SendShutdownMessageToMaster() { CBITSTREAM; PacketUtils::WriteHeader(bitStream, MASTER, MSG_MASTER_SHUTDOWN_RESPONSE); Game::server->SendToMaster(&bitStream); -} \ No newline at end of file +} From ffd447708193b38fa35f794e5e54800f7d7413ce Mon Sep 17 00:00:00 2001 From: Jett <55758076+Jettford@users.noreply.github.com> Date: Wed, 27 Jul 2022 10:08:04 +0100 Subject: [PATCH 25/86] Increment DLU patch version --- CMakeVariables.txt | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/CMakeVariables.txt b/CMakeVariables.txt index fb59f455..7a8d6b71 100644 --- a/CMakeVariables.txt +++ b/CMakeVariables.txt @@ -1,6 +1,6 @@ PROJECT_VERSION_MAJOR=1 PROJECT_VERSION_MINOR=0 -PROJECT_VERSION_PATCH=3 +PROJECT_VERSION_PATCH=4 # LICENSE LICENSE=AGPL-3.0 # The network version. @@ -17,4 +17,4 @@ __dynamic=1 # __compile_backtrace__=1 # Set __compile_backtrace__ to 1 to compile the backtrace library instead of using system libraries. __maria_db_connector_compile_jobs__=1 -# Set to the number of jobs (make -j equivalent) to compile the mariadbconn files with. \ No newline at end of file +# Set to the number of jobs (make -j equivalent) to compile the mariadbconn files with. From 4f7aa11067861ef598fcb30797ca140dee6b7036 Mon Sep 17 00:00:00 2001 From: aronwk-aaron Date: Wed, 27 Jul 2022 22:33:36 -0500 Subject: [PATCH 26/86] add editorconfig --- .editorconfig | 76 +++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 76 insertions(+) create mode 100644 .editorconfig diff --git a/.editorconfig b/.editorconfig new file mode 100644 index 00000000..ebdfa7ac --- /dev/null +++ b/.editorconfig @@ -0,0 +1,76 @@ +# top-most EditorConfig file +root=true + +# Unix-style newlines with a newline ending every file +[*] +indent_style=tab +tab_width=4 +charset=utf-8 +trim_trailing_whitespace=true +end_of_line=lf +insert_final_newline=true + +[*.{c++,cc,cpp,cxx,h,h++,hh,hpp,hxx,inl,ipp,tlh,tli}] + +vc_generate_documentation_comments=doxygen_slash_star + +cpp_indent_braces=false +cpp_alignment_tab_fill_style=use_spaces +cpp_indent_multi_line_relative_to=innermost_parenthesis +cpp_indent_within_parentheses=indent +cpp_indent_preserve_within_parentheses=false +cpp_indent_case_labels=false +cpp_indent_case_contents=true +cpp_indent_case_contents_when_block=false +cpp_indent_lambda_braces_when_parameter=true +cpp_indent_goto_labels=one_left +cpp_indent_preprocessor=leftmost_column +cpp_indent_access_specifiers=false +cpp_indent_namespace_contents=true +cpp_indent_preserve_comments=false +cpp_new_line_before_open_brace_namespace=same_line +cpp_new_line_before_open_brace_type=same_line +cpp_new_line_before_open_brace_function=same_line +cpp_new_line_before_open_brace_block=same_line +cpp_new_line_before_open_brace_lambda=same_line +cpp_new_line_scope_braces_on_separate_lines=false +cpp_new_line_close_brace_same_line_empty_type=false +cpp_new_line_close_brace_same_line_empty_function=false +cpp_new_line_before_catch=false +cpp_new_line_before_else=false +cpp_new_line_before_while_in_do_while=false +cpp_space_before_function_open_parenthesis=remove +cpp_space_within_parameter_list_parentheses=false +cpp_space_between_empty_parameter_list_parentheses=false +cpp_space_after_keywords_in_control_flow_statements=true +cpp_space_within_control_flow_statement_parentheses=false +cpp_space_before_lambda_open_parenthesis=false +cpp_space_within_cast_parentheses=false +cpp_space_after_cast_close_parenthesis=false +cpp_space_within_expression_parentheses=false +cpp_space_before_block_open_brace=true +cpp_space_between_empty_braces=false +cpp_space_before_initializer_list_open_brace=false +cpp_space_within_initializer_list_braces=true +cpp_space_preserve_in_initializer_list=true +cpp_space_before_open_square_bracket=false +cpp_space_within_square_brackets=false +cpp_space_before_empty_square_brackets=false +cpp_space_between_empty_square_brackets=false +cpp_space_group_square_brackets=true +cpp_space_within_lambda_brackets=false +cpp_space_between_empty_lambda_brackets=false +cpp_space_before_comma=false +cpp_space_after_comma=true +cpp_space_remove_around_member_operators=true +cpp_space_before_inheritance_colon=true +cpp_space_before_constructor_colon=true +cpp_space_remove_before_semicolon=true +cpp_space_after_semicolon=false +cpp_space_remove_around_unary_operator=true +cpp_space_around_binary_operator=insert +cpp_space_around_assignment_operator=insert +cpp_space_pointer_reference_alignment=left +cpp_space_around_ternary_operator=insert +cpp_wrap_preserve_blocks=one_liners +cpp_indent_comment=fasle From adb6a2c60956bbe8e2f4c225ee943d2315375dba Mon Sep 17 00:00:00 2001 From: David Markowitz <39972741+EmosewaMC@users.noreply.github.com> Date: Wed, 27 Jul 2022 20:54:42 -0700 Subject: [PATCH 27/86] Fix racing lap times (#683) --- dGame/dComponents/RacingControlComponent.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/dGame/dComponents/RacingControlComponent.cpp b/dGame/dComponents/RacingControlComponent.cpp index e157ca5f..770679e5 100644 --- a/dGame/dComponents/RacingControlComponent.cpp +++ b/dGame/dComponents/RacingControlComponent.cpp @@ -818,7 +818,7 @@ void RacingControlComponent::Update(float deltaTime) { // Reached the start point, lapped if (respawnIndex == 0) { - time_t lapTime = std::time(nullptr) - (player.lap == 1 ? m_StartTime : player.lapTime); + time_t lapTime = std::time(nullptr) - (player.lap == 0 ? m_StartTime : player.lapTime); // Cheating check if (lapTime < 40) { From 19e77a38d837ce781ba0ca6ea8e78b67a6e3b5a5 Mon Sep 17 00:00:00 2001 From: aronwk-aaron Date: Thu, 28 Jul 2022 08:39:57 -0500 Subject: [PATCH 28/86] format codebase --- dAuthServer/AuthServer.cpp | 16 +- dChatFilter/dChatFilter.cpp | 8 +- dChatServer/ChatPacketHandler.cpp | 186 +- dChatServer/ChatServer.cpp | 14 +- dChatServer/PlayerContainer.cpp | 137 +- dChatServer/PlayerContainer.h | 2 +- dCommon/AMFDeserialize.cpp | 106 +- dCommon/AMFDeserialize.h | 112 +- dCommon/AMFFormat.cpp | 122 +- dCommon/AMFFormat.h | 556 +++--- dCommon/AMFFormat_BitStream.cpp | 166 +- dCommon/AMFFormat_BitStream.h | 22 +- dCommon/BinaryIO.cpp | 4 +- dCommon/BinaryIO.h | 6 +- dCommon/Diagnostics.cpp | 254 +-- dCommon/Diagnostics.h | 26 +- dCommon/Game.h | 2 +- dCommon/GeneralUtils.cpp | 450 +++-- dCommon/GeneralUtils.h | 321 ++-- dCommon/LDFFormat.cpp | 212 +-- dCommon/LDFFormat.h | 342 ++-- dCommon/MD5.cpp | 438 +++-- dCommon/MD5.h | 106 +- dCommon/Metrics.cpp | 345 ++-- dCommon/Metrics.hpp | 66 +- dCommon/NiPoint3.cpp | 209 +-- dCommon/NiPoint3.h | 264 +-- dCommon/NiQuaternion.cpp | 179 +- dCommon/NiQuaternion.h | 264 +-- dCommon/PermissionMap.h | 52 +- dCommon/SHA512.cpp | 271 ++- dCommon/SHA512.h | 34 +- dCommon/Type.cpp | 16 +- dCommon/Type.h | 2 +- dCommon/ZCompression.cpp | 124 +- dCommon/ZCompression.h | 3 +- dCommon/dCommonVars.h | 382 ++-- dCommon/dConfig.cpp | 8 +- dCommon/dConfig.h | 2 +- dCommon/dLogger.cpp | 34 +- dCommon/dLogger.h | 10 +- dCommon/dPlatforms.h | 48 +- dCommon/eAninmationFlags.h | 2 +- dCommon/eItemType.h | 2 +- dDatabase/CDClientDatabase.cpp | 8 +- dDatabase/CDClientDatabase.h | 48 +- dDatabase/CDClientManager.cpp | 2 +- dDatabase/CDClientManager.h | 76 +- dDatabase/Database.cpp | 9 +- dDatabase/Database.h | 4 +- dDatabase/MigrationRunner.cpp | 95 +- dDatabase/MigrationRunner.h | 2 +- dDatabase/Tables/CDActivitiesTable.cpp | 2 +- dDatabase/Tables/CDActivityRewardsTable.cpp | 74 +- dDatabase/Tables/CDActivityRewardsTable.h | 70 +- dDatabase/Tables/CDAnimationsTable.cpp | 86 +- dDatabase/Tables/CDAnimationsTable.h | 82 +- dDatabase/Tables/CDBehaviorParameterTable.cpp | 5 +- dDatabase/Tables/CDBehaviorParameterTable.h | 34 +- dDatabase/Tables/CDBehaviorTemplateTable.cpp | 104 +- dDatabase/Tables/CDBehaviorTemplateTable.h | 66 +- dDatabase/Tables/CDBrickIDTableTable.cpp | 6 +- .../Tables/CDComponentsRegistryTable.cpp | 91 +- dDatabase/Tables/CDComponentsRegistryTable.h | 42 +- dDatabase/Tables/CDCurrencyTableTable.cpp | 72 +- dDatabase/Tables/CDCurrencyTableTable.h | 66 +- .../Tables/CDDestructibleComponentTable.cpp | 90 +- .../Tables/CDDestructibleComponentTable.h | 84 +- dDatabase/Tables/CDEmoteTable.cpp | 52 +- dDatabase/Tables/CDEmoteTable.h | 44 +- dDatabase/Tables/CDFeatureGatingTable.cpp | 91 +- dDatabase/Tables/CDFeatureGatingTable.h | 70 +- .../Tables/CDInventoryComponentTable.cpp | 70 +- dDatabase/Tables/CDInventoryComponentTable.h | 64 +- dDatabase/Tables/CDItemComponentTable.cpp | 252 +-- dDatabase/Tables/CDItemComponentTable.h | 124 +- dDatabase/Tables/CDItemSetSkillsTable.cpp | 73 +- dDatabase/Tables/CDItemSetSkillsTable.h | 62 +- dDatabase/Tables/CDItemSetsTable.cpp | 92 +- dDatabase/Tables/CDItemSetsTable.h | 86 +- .../Tables/CDLevelProgressionLookupTable.cpp | 68 +- .../Tables/CDLevelProgressionLookupTable.h | 62 +- dDatabase/Tables/CDLootMatrixTable.cpp | 80 +- dDatabase/Tables/CDLootMatrixTable.h | 74 +- dDatabase/Tables/CDLootTableTable.cpp | 74 +- dDatabase/Tables/CDLootTableTable.h | 66 +- dDatabase/Tables/CDMissionEmailTable.cpp | 66 +- dDatabase/Tables/CDMissionEmailTable.h | 56 +- .../Tables/CDMissionNPCComponentTable.cpp | 72 +- dDatabase/Tables/CDMissionNPCComponentTable.h | 66 +- dDatabase/Tables/CDMissionTasksTable.cpp | 109 +- dDatabase/Tables/CDMissionTasksTable.h | 84 +- dDatabase/Tables/CDMissionsTable.cpp | 206 +- dDatabase/Tables/CDMissionsTable.h | 162 +- .../Tables/CDMovementAIComponentTable.cpp | 6 +- dDatabase/Tables/CDObjectSkillsTable.cpp | 70 +- dDatabase/Tables/CDObjectSkillsTable.h | 64 +- dDatabase/Tables/CDObjectsTable.cpp | 118 +- dDatabase/Tables/CDObjectsTable.h | 60 +- dDatabase/Tables/CDPackageComponentTable.cpp | 8 +- dDatabase/Tables/CDPhysicsComponentTable.cpp | 30 +- dDatabase/Tables/CDPhysicsComponentTable.h | 10 +- .../CDPropertyEntranceComponentTable.cpp | 56 +- .../Tables/CDPropertyEntranceComponentTable.h | 52 +- dDatabase/Tables/CDPropertyTemplateTable.cpp | 54 +- dDatabase/Tables/CDPropertyTemplateTable.h | 22 +- .../CDProximityMonitorComponentTable.cpp | 6 +- dDatabase/Tables/CDRailActivatorComponent.cpp | 90 +- dDatabase/Tables/CDRailActivatorComponent.h | 46 +- dDatabase/Tables/CDRarityTableTable.cpp | 58 +- dDatabase/Tables/CDRarityTableTable.h | 76 +- dDatabase/Tables/CDRebuildComponentTable.cpp | 82 +- dDatabase/Tables/CDRebuildComponentTable.h | 76 +- dDatabase/Tables/CDRewardsTable.cpp | 32 +- dDatabase/Tables/CDRewardsTable.h | 10 +- dDatabase/Tables/CDScriptComponentTable.cpp | 48 +- dDatabase/Tables/CDScriptComponentTable.h | 48 +- dDatabase/Tables/CDSkillBehaviorTable.cpp | 98 +- dDatabase/Tables/CDSkillBehaviorTable.h | 76 +- dDatabase/Tables/CDTable.h | 16 +- dDatabase/Tables/CDVendorComponentTable.cpp | 6 +- dDatabase/Tables/CDZoneTableTable.cpp | 105 +- dDatabase/Tables/CDZoneTableTable.h | 92 +- dGame/Character.cpp | 238 ++- dGame/Character.h | 772 ++++---- dGame/Entity.cpp | 676 +++---- dGame/Entity.h | 257 ++- dGame/EntityManager.cpp | 215 +-- dGame/EntityManager.h | 40 +- dGame/LeaderboardManager.cpp | 573 +++--- dGame/LeaderboardManager.h | 108 +- dGame/Player.cpp | 173 +- dGame/Player.h | 38 +- dGame/TeamManager.cpp | 88 +- dGame/TeamManager.h | 14 +- dGame/TradingManager.cpp | 361 ++-- dGame/TradingManager.h | 72 +- dGame/User.cpp | 81 +- dGame/User.h | 20 +- dGame/UserManager.cpp | 447 +++-- dGame/UserManager.h | 12 +- dGame/dBehaviors/AirMovementBehavior.cpp | 17 +- dGame/dBehaviors/AirMovementBehavior.h | 3 +- dGame/dBehaviors/AndBehavior.cpp | 21 +- dGame/dBehaviors/AndBehavior.h | 7 +- dGame/dBehaviors/ApplyBuffBehavior.cpp | 56 +- dGame/dBehaviors/ApplyBuffBehavior.h | 27 +- dGame/dBehaviors/AreaOfEffectBehavior.cpp | 61 +- dGame/dBehaviors/AreaOfEffectBehavior.h | 9 +- dGame/dBehaviors/AttackDelayBehavior.cpp | 26 +- dGame/dBehaviors/AttackDelayBehavior.h | 7 +- dGame/dBehaviors/BasicAttackBehavior.cpp | 6 +- dGame/dBehaviors/BasicAttackBehavior.h | 7 +- dGame/dBehaviors/Behavior.cpp | 115 +- dGame/dBehaviors/Behavior.h | 18 +- dGame/dBehaviors/BehaviorBranchContext.cpp | 6 +- dGame/dBehaviors/BehaviorBranchContext.h | 6 +- dGame/dBehaviors/BehaviorContext.cpp | 166 +- dGame/dBehaviors/BehaviorContext.h | 18 +- dGame/dBehaviors/BehaviorTemplates.h | 2 +- dGame/dBehaviors/BlockBehavior.cpp | 37 +- dGame/dBehaviors/BlockBehavior.h | 9 +- dGame/dBehaviors/BuffBehavior.cpp | 37 +- dGame/dBehaviors/BuffBehavior.h | 7 +- dGame/dBehaviors/CarBoostBehavior.cpp | 53 +- dGame/dBehaviors/CarBoostBehavior.h | 5 +- dGame/dBehaviors/ChainBehavior.cpp | 18 +- dGame/dBehaviors/ChainBehavior.h | 5 +- .../dBehaviors/ChangeOrientationBehavior.cpp | 58 +- dGame/dBehaviors/ChangeOrientationBehavior.h | 9 +- dGame/dBehaviors/ChargeUpBehavior.cpp | 12 +- dGame/dBehaviors/ChargeUpBehavior.h | 7 +- dGame/dBehaviors/ClearTargetBehavior.cpp | 11 +- dGame/dBehaviors/ClearTargetBehavior.h | 5 +- dGame/dBehaviors/DamageAbsorptionBehavior.cpp | 24 +- dGame/dBehaviors/DamageAbsorptionBehavior.h | 5 +- dGame/dBehaviors/DamageReductionBehavior.cpp | 24 +- dGame/dBehaviors/DamageReductionBehavior.h | 5 +- dGame/dBehaviors/DurationBehavior.cpp | 9 +- dGame/dBehaviors/DurationBehavior.h | 7 +- dGame/dBehaviors/EmptyBehavior.h | 3 +- dGame/dBehaviors/EndBehavior.cpp | 9 +- dGame/dBehaviors/EndBehavior.h | 9 +- dGame/dBehaviors/ForceMovementBehavior.cpp | 102 +- dGame/dBehaviors/ForceMovementBehavior.h | 21 +- dGame/dBehaviors/HealBehavior.cpp | 15 +- dGame/dBehaviors/HealBehavior.h | 5 +- dGame/dBehaviors/ImaginationBehavior.cpp | 15 +- dGame/dBehaviors/ImaginationBehavior.h | 3 +- dGame/dBehaviors/ImmunityBehavior.cpp | 27 +- dGame/dBehaviors/ImmunityBehavior.h | 5 +- dGame/dBehaviors/InterruptBehavior.cpp | 25 +- dGame/dBehaviors/InterruptBehavior.h | 11 +- dGame/dBehaviors/JetPackBehavior.cpp | 20 +- dGame/dBehaviors/JetPackBehavior.h | 2 +- dGame/dBehaviors/KnockbackBehavior.cpp | 15 +- dGame/dBehaviors/KnockbackBehavior.h | 5 +- dGame/dBehaviors/LootBuffBehavior.cpp | 36 +- dGame/dBehaviors/LootBuffBehavior.h | 6 +- dGame/dBehaviors/MovementSwitchBehavior.cpp | 12 +- dGame/dBehaviors/MovementSwitchBehavior.h | 9 +- dGame/dBehaviors/NpcCombatSkillBehavior.cpp | 19 +- dGame/dBehaviors/NpcCombatSkillBehavior.h | 5 +- dGame/dBehaviors/OverTimeBehavior.cpp | 48 +- dGame/dBehaviors/OverTimeBehavior.h | 11 +- dGame/dBehaviors/PlayEffectBehavior.cpp | 9 +- dGame/dBehaviors/PlayEffectBehavior.h | 5 +- dGame/dBehaviors/ProjectileAttackBehavior.cpp | 43 +- dGame/dBehaviors/ProjectileAttackBehavior.h | 3 +- dGame/dBehaviors/PullToPointBehavior.cpp | 19 +- dGame/dBehaviors/PullToPointBehavior.h | 3 +- dGame/dBehaviors/RepairBehavior.cpp | 15 +- dGame/dBehaviors/RepairBehavior.h | 3 +- dGame/dBehaviors/SkillCastFailedBehavior.cpp | 9 +- dGame/dBehaviors/SkillCastFailedBehavior.h | 5 +- dGame/dBehaviors/SkillEventBehavior.cpp | 32 +- dGame/dBehaviors/SkillEventBehavior.h | 8 +- dGame/dBehaviors/SpawnBehavior.cpp | 48 +- dGame/dBehaviors/SpawnBehavior.h | 11 +- dGame/dBehaviors/SpawnQuickbuildBehavior.cpp | 7 +- dGame/dBehaviors/SpawnQuickbuildBehavior.h | 3 +- dGame/dBehaviors/SpeedBehavior.cpp | 117 +- dGame/dBehaviors/SpeedBehavior.h | 13 +- dGame/dBehaviors/StartBehavior.cpp | 11 +- dGame/dBehaviors/StartBehavior.h | 5 +- dGame/dBehaviors/StunBehavior.cpp | 36 +- dGame/dBehaviors/StunBehavior.h | 5 +- dGame/dBehaviors/SwitchBehavior.cpp | 57 +- dGame/dBehaviors/SwitchBehavior.h | 5 +- dGame/dBehaviors/SwitchMultipleBehavior.cpp | 18 +- dGame/dBehaviors/SwitchMultipleBehavior.h | 5 +- dGame/dBehaviors/TacArcBehavior.cpp | 138 +- dGame/dBehaviors/TacArcBehavior.h | 7 +- dGame/dBehaviors/TargetCasterBehavior.cpp | 12 +- dGame/dBehaviors/TargetCasterBehavior.h | 7 +- dGame/dBehaviors/TauntBehavior.cpp | 21 +- dGame/dBehaviors/TauntBehavior.h | 5 +- dGame/dBehaviors/VentureVisionBehavior.cpp | 6 +- dGame/dBehaviors/VentureVisionBehavior.h | 5 +- dGame/dBehaviors/VerifyBehavior.cpp | 32 +- dGame/dBehaviors/VerifyBehavior.h | 5 +- dGame/dComponents/BaseCombatAIComponent.cpp | 178 +- dGame/dComponents/BaseCombatAIComponent.h | 402 ++-- dGame/dComponents/BouncerComponent.cpp | 44 +- dGame/dComponents/BouncerComponent.h | 60 +- dGame/dComponents/BuffComponent.cpp | 172 +- dGame/dComponents/BuffComponent.h | 172 +- dGame/dComponents/BuildBorderComponent.cpp | 12 +- dGame/dComponents/BuildBorderComponent.h | 16 +- dGame/dComponents/CharacterComponent.cpp | 688 ++++--- dGame/dComponents/CharacterComponent.h | 660 +++---- dGame/dComponents/Component.cpp | 52 +- dGame/dComponents/Component.h | 62 +- .../ControllablePhysicsComponent.h | 558 +++--- dGame/dComponents/DestroyableComponent.cpp | 453 ++--- dGame/dComponents/DestroyableComponent.h | 864 ++++----- dGame/dComponents/InventoryComponent.cpp | 715 +++---- dGame/dComponents/InventoryComponent.h | 546 +++--- dGame/dComponents/LUPExhibitComponent.cpp | 51 +- dGame/dComponents/LUPExhibitComponent.h | 50 +- .../dComponents/LevelProgressionComponent.cpp | 18 +- dGame/dComponents/MissionComponent.cpp | 728 ++++---- dGame/dComponents/MissionComponent.h | 296 +-- dGame/dComponents/MissionOfferComponent.cpp | 291 ++- dGame/dComponents/MissionOfferComponent.h | 96 +- dGame/dComponents/ModelComponent.cpp | 19 +- dGame/dComponents/ModuleAssemblyComponent.cpp | 96 +- dGame/dComponents/ModuleAssemblyComponent.h | 92 +- dGame/dComponents/MovementAIComponent.cpp | 258 +-- dGame/dComponents/MovementAIComponent.h | 372 ++-- dGame/dComponents/MovingPlatformComponent.cpp | 459 +++-- dGame/dComponents/MovingPlatformComponent.h | 310 +-- dGame/dComponents/PetComponent.cpp | 1532 +++++++-------- dGame/dComponents/PetComponent.h | 566 +++--- dGame/dComponents/PhantomPhysicsComponent.cpp | 128 +- dGame/dComponents/PhantomPhysicsComponent.h | 296 +-- .../PlayerForcedMovementComponent.cpp | 4 +- .../PlayerForcedMovementComponent.h | 20 +- dGame/dComponents/PossessableComponent.cpp | 6 +- dGame/dComponents/PossessableComponent.h | 162 +- dGame/dComponents/PossessorComponent.h | 100 +- dGame/dComponents/PropertyComponent.cpp | 2 +- .../dComponents/PropertyEntranceComponent.cpp | 443 +++-- dGame/dComponents/PropertyEntranceComponent.h | 126 +- .../PropertyManagementComponent.cpp | 278 ++- .../dComponents/PropertyManagementComponent.h | 294 +-- dGame/dComponents/PropertyVendorComponent.cpp | 15 +- dGame/dComponents/PropertyVendorComponent.h | 34 +- .../dComponents/ProximityMonitorComponent.cpp | 2 +- dGame/dComponents/ProximityMonitorComponent.h | 74 +- dGame/dComponents/RacingControlComponent.cpp | 1344 ++++++------- dGame/dComponents/RacingControlComponent.h | 360 ++-- dGame/dComponents/RailActivatorComponent.cpp | 237 ++- dGame/dComponents/RailActivatorComponent.h | 208 +-- dGame/dComponents/RebuildComponent.cpp | 93 +- dGame/dComponents/RebuildComponent.h | 454 ++--- dGame/dComponents/RenderComponent.cpp | 291 ++- dGame/dComponents/RenderComponent.h | 150 +- .../RigidbodyPhantomPhysicsComponent.cpp | 31 +- .../RigidbodyPhantomPhysicsComponent.h | 84 +- dGame/dComponents/RocketLaunchLupComponent.h | 2 +- .../RocketLaunchpadControlComponent.cpp | 27 +- .../RocketLaunchpadControlComponent.h | 138 +- .../dComponents/ScriptedActivityComponent.cpp | 333 ++-- dGame/dComponents/ScriptedActivityComponent.h | 424 ++--- .../dComponents/ShootingGalleryComponent.cpp | 90 +- dGame/dComponents/ShootingGalleryComponent.h | 180 +- dGame/dComponents/SimplePhysicsComponent.cpp | 95 +- dGame/dComponents/SimplePhysicsComponent.h | 170 +- dGame/dComponents/SkillComponent.cpp | 160 +- dGame/dComponents/SkillComponent.h | 270 +-- dGame/dComponents/SoundTriggerComponent.cpp | 132 +- dGame/dComponents/SoundTriggerComponent.h | 60 +- dGame/dComponents/SwitchComponent.cpp | 70 +- dGame/dComponents/SwitchComponent.h | 4 +- dGame/dComponents/VehiclePhysicsComponent.cpp | 129 +- dGame/dComponents/VehiclePhysicsComponent.h | 160 +- dGame/dComponents/VendorComponent.cpp | 42 +- dGame/dComponents/VendorComponent.h | 28 +- dGame/dEntity/EntityCallbackTimer.cpp | 2 +- dGame/dEntity/EntityCallbackTimer.h | 2 +- dGame/dEntity/EntityInfo.h | 26 +- dGame/dEntity/EntityTimer.cpp | 4 +- dGame/dGameMessages/GameMessageHandler.cpp | 1022 +++++----- dGame/dGameMessages/GameMessageHandler.h | 2 +- dGame/dGameMessages/GameMessages.cpp | 1255 +++++-------- dGame/dGameMessages/GameMessages.h | 1010 +++++----- dGame/dGameMessages/PropertyDataMessage.cpp | 26 +- dGame/dGameMessages/PropertyDataMessage.h | 7 +- .../PropertySelectQueryProperty.cpp | 10 +- .../PropertySelectQueryProperty.h | 28 +- dGame/dInventory/DatabasePet.h | 24 +- dGame/dInventory/EquippedItem.h | 24 +- dGame/dInventory/Inventory.cpp | 149 +- dGame/dInventory/Inventory.h | 220 +-- dGame/dInventory/Item.cpp | 222 +-- dGame/dInventory/Item.h | 325 ++-- dGame/dInventory/ItemSet.cpp | 95 +- dGame/dInventory/ItemSet.h | 126 +- dGame/dInventory/ItemSetPassiveAbility.cpp | 564 +++--- dGame/dInventory/ItemSetPassiveAbility.h | 84 +- dGame/dInventory/ItemSetPassiveAbilityID.h | 100 +- dGame/dMission/Mission.cpp | 712 +++---- dGame/dMission/Mission.h | 326 ++-- dGame/dMission/MissionPrerequisites.cpp | 55 +- dGame/dMission/MissionPrerequisites.h | 44 +- dGame/dMission/MissionState.h | 72 +- dGame/dMission/MissionTask.cpp | 144 +- dGame/dMission/MissionTask.h | 228 +-- dGame/dMission/MissionTaskType.h | 42 +- dGame/dMission/RacingTaskParam.h | 30 +- dGame/dUtilities/BrickDatabase.cpp | 67 +- dGame/dUtilities/BrickDatabase.h | 30 +- dGame/dUtilities/GUID.cpp | 20 +- dGame/dUtilities/GUID.h | 20 +- dGame/dUtilities/GameConfig.cpp | 12 +- dGame/dUtilities/GameConfig.h | 2 +- dGame/dUtilities/Loot.cpp | 514 ++--- dGame/dUtilities/Loot.h | 58 +- dGame/dUtilities/Mail.cpp | 30 +- dGame/dUtilities/Mail.h | 4 +- dGame/dUtilities/Preconditions.cpp | 110 +- dGame/dUtilities/Preconditions.h | 84 +- dGame/dUtilities/SlashCommandHandler.cpp | 662 +++---- dGame/dUtilities/SlashCommandHandler.h | 6 +- dGame/dUtilities/VanityUtilities.cpp | 759 ++++---- dGame/dUtilities/VanityUtilities.h | 68 +- dGame/dUtilities/dLocale.cpp | 86 +- dGame/dUtilities/dLocale.h | 18 +- dMasterServer/InstanceManager.cpp | 176 +- dMasterServer/InstanceManager.h | 12 +- dMasterServer/MasterServer.cpp | 78 +- dMasterServer/ObjectIDManager.cpp | 88 +- dMasterServer/ObjectIDManager.h | 56 +- dNet/AuthPackets.cpp | 117 +- dNet/AuthPackets.h | 4 +- dNet/ChatPackets.cpp | 80 +- dNet/ChatPackets.h | 6 +- dNet/ClientPackets.cpp | 8 +- dNet/ClientPackets.h | 6 +- dNet/MasterPackets.cpp | 61 +- dNet/MasterPackets.h | 12 +- dNet/PacketUtils.cpp | 197 +- dNet/PacketUtils.h | 22 +- dNet/WorldPackets.cpp | 218 +-- dNet/WorldPackets.h | 10 +- dNet/ZoneInstanceManager.cpp | 82 +- dNet/ZoneInstanceManager.h | 76 +- dNet/dMessageIdentifiers.h | 2 +- dNet/dNetCommon.h | 2 +- dNet/dServer.cpp | 54 +- dNet/dServer.h | 4 +- dPhysics/Singleton.h | 2 +- dPhysics/dpCollisionChecks.cpp | 9 +- dPhysics/dpCollisionChecks.h | 2 +- dPhysics/dpCollisionGroups.h | 10 +- dPhysics/dpCommon.h | 2 +- dPhysics/dpEntity.cpp | 3 +- dPhysics/dpEntity.h | 2 +- dPhysics/dpGrid.h | 28 +- dPhysics/dpShapeBase.cpp | 5 +- dPhysics/dpShapeBase.h | 2 +- dPhysics/dpShapeBox.cpp | 9 +- dPhysics/dpShapeBox.h | 2 +- dPhysics/dpShapeSphere.cpp | 3 +- dPhysics/dpShapeSphere.h | 2 +- dPhysics/dpWorld.cpp | 28 +- dPhysics/dpWorld.h | 2 +- dPhysics/main.cpp | 2 +- dScripts/ActMine.cpp | 7 +- dScripts/ActMine.h | 24 +- dScripts/ActNinjaTurret.cpp | 28 +- dScripts/ActNinjaTurret.h | 4 +- dScripts/ActParadoxPipeFix.cpp | 90 +- dScripts/ActParadoxPipeFix.h | 2 +- dScripts/ActPlayerDeathTrigger.cpp | 7 +- dScripts/ActSharkPlayerDeathTrigger.cpp | 4 +- dScripts/ActSharkPlayerDeathTrigger.h | 4 +- dScripts/ActVehicleDeathTrigger.cpp | 70 +- dScripts/ActivityManager.cpp | 295 ++- dScripts/ActivityManager.h | 60 +- dScripts/AgBugsprayer.cpp | 25 +- dScripts/AgBugsprayer.h | 2 +- dScripts/AgBusDoor.cpp | 16 +- dScripts/AgCagedBricksServer.cpp | 5 +- dScripts/AgCagedBricksServer.h | 2 +- dScripts/AgDarkSpiderling.cpp | 10 +- dScripts/AgDarkSpiderling.h | 2 +- dScripts/AgFans.cpp | 13 +- dScripts/AgFans.h | 4 +- dScripts/AgImagSmashable.h | 2 +- dScripts/AgJetEffectServer.cpp | 42 +- dScripts/AgLaserSensorServer.cpp | 11 +- dScripts/AgMonumentBirds.cpp | 2 +- dScripts/AgMonumentLaserServer.cpp | 2 +- dScripts/AgMonumentRaceCancel.cpp | 10 +- dScripts/AgMonumentRaceCancel.h | 2 +- dScripts/AgMonumentRaceGoal.cpp | 17 +- dScripts/AgPicnicBlanket.cpp | 20 +- dScripts/AgPicnicBlanket.h | 2 +- dScripts/AgPropGuard.cpp | 49 +- dScripts/AgPropguards.cpp | 82 +- dScripts/AgPropguards.h | 4 +- dScripts/AgQbElevator.cpp | 14 +- dScripts/AgQbElevator.h | 2 +- dScripts/AgSalutingNpcs.cpp | 6 +- dScripts/AgShipPlayerDeathTrigger.cpp | 2 +- dScripts/AgShipPlayerShockServer.cpp | 6 +- dScripts/AgSpaceStuff.cpp | 12 +- dScripts/AgStagePlatforms.cpp | 18 +- dScripts/AgStagePlatforms.h | 4 +- dScripts/AgStromlingProperty.cpp | 22 +- dScripts/AgStromlingProperty.h | 2 +- dScripts/AgSurvivalBuffStation.cpp | 96 +- dScripts/AgSurvivalBuffStation.h | 90 +- dScripts/AgSurvivalMech.cpp | 14 +- dScripts/AgSurvivalMech.h | 4 +- dScripts/AgSurvivalSpiderling.cpp | 14 +- dScripts/AgSurvivalSpiderling.h | 4 +- dScripts/AgSurvivalStromling.cpp | 2 +- dScripts/AgSurvivalStromling.h | 2 +- dScripts/AgTurret.h | 2 +- dScripts/AmBlueX.cpp | 78 +- dScripts/AmBlueX.h | 26 +- dScripts/AmBridge.cpp | 35 +- dScripts/AmBridge.h | 6 +- dScripts/AmConsoleTeleportServer.cpp | 36 +- dScripts/AmConsoleTeleportServer.h | 24 +- dScripts/AmDarklingDragon.cpp | 211 +-- dScripts/AmDarklingDragon.h | 82 +- dScripts/AmDarklingMech.cpp | 7 +- dScripts/AmDarklingMech.h | 2 +- dScripts/AmDrawBridge.cpp | 168 +- dScripts/AmDrawBridge.h | 14 +- dScripts/AmDropshipComputer.cpp | 118 +- dScripts/AmDropshipComputer.h | 10 +- dScripts/AmScrollReaderServer.cpp | 19 +- dScripts/AmScrollReaderServer.h | 2 +- dScripts/AmShieldGenerator.cpp | 218 +-- dScripts/AmShieldGenerator.h | 14 +- dScripts/AmShieldGeneratorQuickbuild.cpp | 304 ++- dScripts/AmShieldGeneratorQuickbuild.h | 16 +- dScripts/AmSkeletonEngineer.cpp | 31 +- dScripts/AmSkeletonEngineer.h | 2 +- dScripts/AmSkullkinDrill.cpp | 473 +++-- dScripts/AmSkullkinDrill.h | 26 +- dScripts/AmSkullkinDrillStand.cpp | 43 +- dScripts/AmSkullkinDrillStand.h | 6 +- dScripts/AmSkullkinTower.cpp | 365 ++-- dScripts/AmSkullkinTower.h | 12 +- dScripts/AmTeapotServer.cpp | 2 +- dScripts/AmTeapotServer.h | 10 +- dScripts/AmTemplateSkillVolume.cpp | 32 +- dScripts/AmTemplateSkillVolume.h | 2 +- dScripts/AnvilOfArmor.cpp | 18 +- dScripts/AnvilOfArmor.h | 2 +- dScripts/BankInteractServer.cpp | 29 +- dScripts/BankInteractServer.h | 6 +- dScripts/BaseConsoleTeleportServer.cpp | 143 +- dScripts/BaseConsoleTeleportServer.h | 16 +- dScripts/BaseEnemyApe.cpp | 194 +- dScripts/BaseEnemyApe.h | 16 +- dScripts/BaseEnemyMech.cpp | 10 +- dScripts/BaseEnemyMech.h | 2 +- dScripts/BaseFootRaceManager.cpp | 72 +- dScripts/BaseFootRaceManager.h | 6 +- dScripts/BaseInteractDropLootServer.cpp | 37 +- dScripts/BaseInteractDropLootServer.h | 4 +- dScripts/BasePropertyServer.cpp | 510 +++-- dScripts/BasePropertyServer.h | 162 +- dScripts/BaseRandomServer.cpp | 234 +-- dScripts/BaseRandomServer.h | 88 +- dScripts/BaseSurvivalServer.cpp | 844 +++++---- dScripts/BaseSurvivalServer.h | 201 +- dScripts/BaseWavesGenericEnemy.cpp | 14 +- dScripts/BaseWavesGenericEnemy.h | 6 +- dScripts/BaseWavesServer.cpp | 854 ++++----- dScripts/BaseWavesServer.h | 237 +-- dScripts/Binoculars.cpp | 2 +- dScripts/Binoculars.h | 2 +- dScripts/BootyDigServer.cpp | 70 +- dScripts/BootyDigServer.h | 6 +- dScripts/BossSpiderQueenEnemyServer.cpp | 243 ++- dScripts/BossSpiderQueenEnemyServer.h | 14 +- dScripts/BuccaneerValiantShip.cpp | 22 +- dScripts/BuccaneerValiantShip.h | 2 +- dScripts/BurningTile.cpp | 19 +- dScripts/BurningTile.h | 4 +- dScripts/CatapultBaseServer.cpp | 39 +- dScripts/CatapultBaseServer.h | 6 +- dScripts/CatapultBouncerServer.cpp | 16 +- dScripts/CatapultBouncerServer.h | 2 +- dScripts/CauldronOfLife.cpp | 18 +- dScripts/CauldronOfLife.h | 2 +- dScripts/CavePrisonCage.cpp | 322 ++-- dScripts/CavePrisonCage.h | 12 +- dScripts/ChooseYourDestinationNsToNt.cpp | 98 +- dScripts/ChooseYourDestinationNsToNt.h | 6 +- dScripts/ClRing.cpp | 3 +- dScripts/CppScripts.cpp | 236 +-- dScripts/CppScripts.h | 124 +- dScripts/CrabServer.cpp | 56 +- dScripts/CrabServer.h | 6 +- dScripts/DLUVanityNPC.cpp | 68 +- dScripts/DLUVanityNPC.h | 6 +- dScripts/DamagingPets.cpp | 218 +-- dScripts/DamagingPets.h | 22 +- dScripts/Darkitect.cpp | 5 +- dScripts/EnemyNjBuff.cpp | 14 +- dScripts/EnemyRoninSpawner.cpp | 96 +- dScripts/EnemyRoninSpawner.h | 6 +- dScripts/EnemySkeletonSpawner.cpp | 107 +- dScripts/EnemySkeletonSpawner.h | 6 +- dScripts/EnemySpiderSpawner.cpp | 16 +- dScripts/EnemySpiderSpawner.h | 4 +- dScripts/ExplodingAsset.cpp | 41 +- dScripts/ExplodingAsset.h | 2 +- dScripts/FallingTile.cpp | 79 +- dScripts/FallingTile.h | 8 +- dScripts/FireFirstSkillonStartup.cpp | 26 +- dScripts/FireFirstSkillonStartup.h | 4 +- dScripts/FlameJetServer.cpp | 68 +- dScripts/FlameJetServer.h | 6 +- dScripts/ForceVolumeServer.cpp | 27 +- dScripts/FountainOfImagination.cpp | 18 +- dScripts/FountainOfImagination.h | 2 +- dScripts/FvBounceOverWall.cpp | 10 +- dScripts/FvBounceOverWall.h | 32 +- dScripts/FvBrickPuzzleServer.cpp | 100 +- dScripts/FvBrickPuzzleServer.h | 4 +- dScripts/FvCandle.cpp | 12 +- dScripts/FvCandle.h | 4 +- dScripts/FvConsoleLeftQuickbuild.cpp | 75 +- dScripts/FvConsoleLeftQuickbuild.h | 4 +- dScripts/FvConsoleRightQuickbuild.cpp | 75 +- dScripts/FvConsoleRightQuickbuild.h | 4 +- dScripts/FvDragonSmashingGolemQb.cpp | 40 +- dScripts/FvDragonSmashingGolemQb.h | 6 +- dScripts/FvFacilityBrick.cpp | 164 +- dScripts/FvFacilityBrick.h | 10 +- dScripts/FvFlyingCreviceDragon.cpp | 169 +- dScripts/FvFlyingCreviceDragon.h | 6 +- dScripts/FvFong.cpp | 6 +- dScripts/FvFong.h | 4 +- dScripts/FvFreeGfNinjas.cpp | 63 +- dScripts/FvFreeGfNinjas.h | 4 +- dScripts/FvHorsemenTrigger.cpp | 78 +- dScripts/FvHorsemenTrigger.h | 10 +- dScripts/FvMaelstromCavalry.cpp | 45 +- dScripts/FvMaelstromCavalry.h | 2 +- dScripts/FvMaelstromDragon.cpp | 257 ++- dScripts/FvMaelstromDragon.h | 10 +- dScripts/FvNinjaGuard.cpp | 32 +- dScripts/FvPandaServer.cpp | 50 +- dScripts/FvPandaServer.h | 6 +- dScripts/FvPandaSpawnerServer.cpp | 70 +- dScripts/FvPandaSpawnerServer.h | 2 +- dScripts/FvPassThroughWall.cpp | 22 +- dScripts/FvPassThroughWall.h | 56 +- dScripts/FvRaceSmashEggImagineServer.cpp | 50 +- dScripts/FvRaceSmashEggImagineServer.h | 2 +- dScripts/GfApeSmashingQB.cpp | 26 +- dScripts/GfApeSmashingQB.h | 6 +- dScripts/GfBanana.cpp | 33 +- dScripts/GfBanana.h | 4 +- dScripts/GfBananaCluster.cpp | 9 +- dScripts/GfCampfire.cpp | 50 +- dScripts/GfCampfire.h | 10 +- dScripts/GfCaptainsCannon.cpp | 111 +- dScripts/GfCaptainsCannon.h | 6 +- dScripts/GfJailWalls.cpp | 44 +- dScripts/GfJailWalls.h | 6 +- dScripts/GfJailkeepMission.cpp | 58 +- dScripts/GfJailkeepMission.h | 4 +- dScripts/GfOrgan.h | 2 +- dScripts/GfTikiTorch.cpp | 43 +- dScripts/GfTikiTorch.h | 8 +- dScripts/GrowingFlower.cpp | 44 +- dScripts/GrowingFlower.h | 10 +- dScripts/HydrantBroken.cpp | 49 +- dScripts/HydrantBroken.h | 4 +- dScripts/HydrantSmashable.cpp | 23 +- dScripts/HydrantSmashable.h | 2 +- dScripts/ImaginationBackpackHealServer.cpp | 28 +- dScripts/ImaginationBackpackHealServer.h | 2 +- dScripts/ImaginationShrineServer.cpp | 23 +- dScripts/ImaginationShrineServer.h | 2 +- dScripts/ImgBrickConsoleQB.cpp | 385 ++-- dScripts/ImgBrickConsoleQB.h | 24 +- ...nceExitTransferPlayerToLastNonInstance.cpp | 83 +- ...tanceExitTransferPlayerToLastNonInstance.h | 2 +- dScripts/LegoDieRoll.cpp | 84 +- dScripts/LegoDieRoll.h | 2 +- dScripts/Lieutenant.cpp | 66 +- dScripts/Lieutenant.h | 2 +- dScripts/MaestromExtracticatorServer.cpp | 8 +- dScripts/MaestromExtracticatorServer.h | 6 +- dScripts/MailBoxServer.cpp | 4 +- dScripts/MailBoxServer.h | 18 +- dScripts/MastTeleport.cpp | 119 +- dScripts/MastTeleport.h | 4 +- dScripts/MinigameTreasureChestServer.cpp | 86 +- dScripts/MinigameTreasureChestServer.h | 8 +- dScripts/MonCoreNookDoors.cpp | 52 +- dScripts/MonCoreNookDoors.h | 8 +- dScripts/MonCoreSmashableDoors.cpp | 15 +- dScripts/MonCoreSmashableDoors.h | 2 +- dScripts/NPCAddRemoveItem.cpp | 40 +- dScripts/NPCAddRemoveItem.h | 14 +- dScripts/NjColeNPC.cpp | 73 +- dScripts/NjColeNPC.h | 4 +- dScripts/NjDragonEmblemChestServer.cpp | 18 +- dScripts/NjDragonEmblemChestServer.h | 2 +- dScripts/NjEarthDragonPetServer.cpp | 12 +- dScripts/NjEarthDragonPetServer.h | 2 +- dScripts/NjEarthPetServer.cpp | 14 +- dScripts/NjEarthPetServer.h | 4 +- dScripts/NjGarmadonCelebration.cpp | 18 +- dScripts/NjGarmadonCelebration.h | 4 +- dScripts/NjIceRailActivator.cpp | 32 +- dScripts/NjIceRailActivator.h | 10 +- dScripts/NjJayMissionItems.cpp | 14 +- dScripts/NjJayMissionItems.h | 4 +- dScripts/NjMonastryBossInstance.cpp | 802 ++++---- dScripts/NjMonastryBossInstance.h | 252 +-- dScripts/NjNPCMissionSpinjitzuServer.cpp | 32 +- dScripts/NjNPCMissionSpinjitzuServer.h | 20 +- dScripts/NjNyaMissionitems.cpp | 8 +- dScripts/NjNyaMissionitems.h | 2 +- dScripts/NjRailActivatorsServer.cpp | 20 +- dScripts/NjRailActivatorsServer.h | 2 +- dScripts/NjRailPostServer.cpp | 70 +- dScripts/NjRailPostServer.h | 14 +- dScripts/NjRailSwitch.cpp | 16 +- dScripts/NjRailSwitch.h | 2 +- dScripts/NjScrollChestServer.cpp | 20 +- dScripts/NjScrollChestServer.h | 2 +- dScripts/NjWuNPC.cpp | 96 +- dScripts/NjWuNPC.h | 14 +- dScripts/NjhubLavaPlayerDeathTrigger.cpp | 9 +- dScripts/NjhubLavaPlayerDeathTrigger.h | 2 +- dScripts/NpcAgCourseStarter.cpp | 60 +- dScripts/NpcAgCourseStarter.h | 6 +- dScripts/NpcCowboyServer.cpp | 43 +- dScripts/NpcNjAssistantServer.cpp | 7 +- dScripts/NpcNjAssistantServer.h | 2 +- dScripts/NpcNpSpacemanBob.cpp | 8 +- dScripts/NpcPirateServer.cpp | 24 +- dScripts/NpcPirateServer.h | 2 +- dScripts/NpcWispServer.cpp | 38 +- dScripts/NpcWispServer.h | 2 +- dScripts/NsConcertChoiceBuild.cpp | 2 +- dScripts/NsConcertChoiceBuild.h | 4 +- dScripts/NsConcertChoiceBuildManager.cpp | 96 +- dScripts/NsConcertChoiceBuildManager.h | 14 +- dScripts/NsConcertInstrument.cpp | 548 +++--- dScripts/NsConcertInstrument.h | 138 +- dScripts/NsConcertQuickBuild.cpp | 332 ++-- dScripts/NsConcertQuickBuild.h | 34 +- dScripts/NsGetFactionMissionServer.cpp | 12 +- dScripts/NsJohnnyMissionServer.cpp | 20 +- dScripts/NsJohnnyMissionServer.h | 2 +- dScripts/NsLegoClubDoor.cpp | 216 +-- dScripts/NsLegoClubDoor.h | 24 +- dScripts/NsLupTeleport.cpp | 139 +- dScripts/NsLupTeleport.h | 22 +- dScripts/NsQbImaginationStatue.cpp | 53 +- dScripts/NsQbImaginationStatue.h | 6 +- dScripts/NsTokenConsoleServer.cpp | 94 +- dScripts/NsTokenConsoleServer.h | 2 +- dScripts/NtAssemblyTubeServer.cpp | 160 +- dScripts/NtAssemblyTubeServer.h | 12 +- dScripts/NtBeamImaginationCollectors.cpp | 37 +- dScripts/NtBeamImaginationCollectors.h | 14 +- dScripts/NtCombatChallengeDummy.cpp | 38 +- dScripts/NtCombatChallengeDummy.h | 4 +- dScripts/NtCombatChallengeExplodingDummy.cpp | 47 +- dScripts/NtCombatChallengeExplodingDummy.h | 6 +- dScripts/NtCombatChallengeServer.cpp | 292 ++- dScripts/NtCombatChallengeServer.h | 68 +- dScripts/NtConsoleTeleportServer.cpp | 32 +- dScripts/NtConsoleTeleportServer.h | 20 +- dScripts/NtDarkitectRevealServer.cpp | 6 +- dScripts/NtDirtCloudServer.cpp | 65 +- dScripts/NtDirtCloudServer.h | 6 +- dScripts/NtDukeServer.cpp | 50 +- dScripts/NtDukeServer.h | 8 +- dScripts/NtFactionSpyServer.cpp | 136 +- dScripts/NtFactionSpyServer.h | 38 +- dScripts/NtHaelServer.cpp | 26 +- dScripts/NtHaelServer.h | 2 +- dScripts/NtImagBeamBuffer.cpp | 81 +- dScripts/NtImagBeamBuffer.h | 8 +- dScripts/NtOverbuildServer.cpp | 44 +- dScripts/NtOverbuildServer.h | 4 +- dScripts/NtParadoxPanelServer.cpp | 31 +- dScripts/NtParadoxPanelServer.h | 2 +- dScripts/NtParadoxTeleServer.cpp | 158 +- dScripts/NtParadoxTeleServer.h | 10 +- dScripts/NtSentinelWalkwayServer.cpp | 58 +- dScripts/NtSleepingGuard.cpp | 15 +- dScripts/NtVandaServer.cpp | 16 +- dScripts/NtVandaServer.h | 6 +- dScripts/NtVentureCannonServer.cpp | 168 +- dScripts/NtVentureCannonServer.h | 10 +- dScripts/NtVentureSpeedPadServer.cpp | 35 +- dScripts/NtXRayServer.cpp | 16 +- dScripts/PersonalFortress.cpp | 69 +- dScripts/PersonalFortress.h | 4 +- dScripts/PetDigBuild.cpp | 70 +- dScripts/PetDigBuild.h | 4 +- dScripts/PetDigServer.cpp | 319 ++-- dScripts/PetDigServer.h | 32 +- dScripts/PetFromDigServer.cpp | 56 +- dScripts/PetFromDigServer.h | 6 +- dScripts/PetFromObjectServer.cpp | 52 +- dScripts/PetFromObjectServer.h | 6 +- dScripts/PrSeagullFly.cpp | 21 +- dScripts/PrWhistle.cpp | 19 +- dScripts/PrWhistle.h | 4 +- dScripts/PropertyBankInteract.cpp | 52 +- dScripts/PropertyBankInteract.h | 10 +- dScripts/PropertyDeathPlane.cpp | 16 +- dScripts/PropertyDevice.cpp | 32 +- dScripts/PropertyDevice.h | 8 +- dScripts/PropertyFXDamage.cpp | 22 +- dScripts/PropertyFXDamage.h | 2 +- dScripts/PropertyPlatform.cpp | 48 +- dScripts/PropertyPlatform.h | 12 +- dScripts/QbEnemyStunner.cpp | 101 +- dScripts/QbEnemyStunner.h | 4 +- dScripts/RaceImagineCrateServer.cpp | 71 +- dScripts/RaceImagineCrateServer.h | 14 +- dScripts/RaceImaginePowerup.cpp | 45 +- dScripts/RaceImaginePowerup.h | 4 +- dScripts/RaceMaelstromGeiser.cpp | 125 +- dScripts/RaceMaelstromGeiser.h | 4 +- dScripts/RaceSmashServer.cpp | 36 +- dScripts/RaceSmashServer.h | 14 +- dScripts/RainOfArrows.cpp | 113 +- dScripts/RainOfArrows.h | 16 +- dScripts/RandomSpawnerFin.cpp | 40 +- dScripts/RandomSpawnerFin.h | 28 +- dScripts/RandomSpawnerPit.cpp | 30 +- dScripts/RandomSpawnerPit.h | 28 +- dScripts/RandomSpawnerStr.cpp | 28 +- dScripts/RandomSpawnerStr.h | 28 +- dScripts/RandomSpawnerZip.cpp | 26 +- dScripts/RandomSpawnerZip.h | 28 +- dScripts/RockHydrantBroken.cpp | 19 +- dScripts/RockHydrantSmashable.cpp | 7 +- dScripts/SGCannon.cpp | 1661 ++++++++--------- dScripts/SGCannon.h | 270 +-- dScripts/ScriptComponent.cpp | 36 +- dScripts/ScriptComponent.h | 50 +- dScripts/ScriptedPowerupSpawner.cpp | 64 +- dScripts/ScriptedPowerupSpawner.h | 12 +- dScripts/SpawnGryphonServer.cpp | 34 +- dScripts/SpawnGryphonServer.h | 4 +- dScripts/SpawnLionServer.cpp | 12 +- dScripts/SpawnLionServer.h | 2 +- dScripts/SpawnPetBaseServer.cpp | 114 +- dScripts/SpawnPetBaseServer.h | 8 +- dScripts/SpawnSaberCatServer.cpp | 12 +- dScripts/SpawnSaberCatServer.h | 2 +- dScripts/SpawnShrakeServer.cpp | 12 +- dScripts/SpawnShrakeServer.h | 2 +- dScripts/SpawnStegoServer.cpp | 12 +- dScripts/SpawnStegoServer.h | 2 +- dScripts/SpecialImaginePowerupSpawner.cpp | 25 +- dScripts/SsModularBuildServer.cpp | 2 +- dScripts/StinkyFishTarget.cpp | 58 +- dScripts/StinkyFishTarget.h | 6 +- dScripts/StoryBoxInteractServer.cpp | 18 +- dScripts/StoryBoxInteractServer.h | 2 +- dScripts/Sunflower.cpp | 18 +- dScripts/Sunflower.h | 2 +- dScripts/TokenConsoleServer.cpp | 4 +- dScripts/TokenConsoleServer.h | 2 +- dScripts/TouchMissionUpdateServer.cpp | 32 +- dScripts/TreasureChestDragonServer.cpp | 56 +- dScripts/TriggerAmbush.cpp | 17 +- dScripts/TriggerAmbush.h | 4 +- dScripts/VeBricksampleServer.cpp | 24 +- dScripts/VeBricksampleServer.h | 4 +- dScripts/VeEpsilonServer.cpp | 34 +- dScripts/VeEpsilonServer.h | 10 +- dScripts/VeMech.cpp | 6 +- dScripts/VeMech.h | 2 +- dScripts/VeMissionConsole.cpp | 30 +- dScripts/VeMissionConsole.h | 4 +- dScripts/WaveBossApe.cpp | 56 +- dScripts/WaveBossApe.h | 12 +- dScripts/WaveBossHammerling.cpp | 32 +- dScripts/WaveBossHammerling.h | 8 +- dScripts/WaveBossHorsemen.cpp | 32 +- dScripts/WaveBossHorsemen.h | 8 +- dScripts/WaveBossSpiderling.cpp | 34 +- dScripts/WaveBossSpiderling.h | 8 +- dScripts/WhFans.cpp | 7 +- dScripts/WhFans.h | 4 +- dScripts/WildAmbients.cpp | 3 +- dScripts/WishingWellServer.cpp | 57 +- dScripts/WishingWellServer.h | 2 +- dScripts/ZoneAgMedProperty.cpp | 70 +- dScripts/ZoneAgMedProperty.h | 2 +- dScripts/ZoneAgProperty.cpp | 383 ++-- dScripts/ZoneAgProperty.h | 72 +- dScripts/ZoneAgSpiderQueen.cpp | 114 +- dScripts/ZoneAgSpiderQueen.h | 18 +- dScripts/ZoneAgSurvival.cpp | 228 +-- dScripts/ZoneAgSurvival.h | 8 +- dScripts/ZoneFvProperty.cpp | 68 +- dScripts/ZoneFvProperty.h | 2 +- dScripts/ZoneGfProperty.cpp | 68 +- dScripts/ZoneGfProperty.h | 2 +- dScripts/ZoneNsMedProperty.cpp | 68 +- dScripts/ZoneNsMedProperty.h | 2 +- dScripts/ZoneNsProperty.cpp | 70 +- dScripts/ZoneNsProperty.h | 2 +- dScripts/ZoneNsWaves.cpp | 908 ++++----- dScripts/ZoneNsWaves.h | 114 +- dScripts/ZoneSGServer.cpp | 32 +- dScripts/ZoneSGServer.h | 12 +- dWorldServer/ObjectIDManager.cpp | 49 +- dWorldServer/ObjectIDManager.h | 76 +- dWorldServer/PerformanceManager.cpp | 2 +- dWorldServer/WorldServer.cpp | 1135 ++++++----- dZoneManager/Level.cpp | 75 +- dZoneManager/Level.h | 2 +- dZoneManager/Spawner.cpp | 65 +- dZoneManager/Spawner.h | 8 +- dZoneManager/Zone.cpp | 73 +- dZoneManager/Zone.h | 4 +- dZoneManager/dZMCommon.h | 4 +- dZoneManager/dZoneManager.cpp | 71 +- dZoneManager/dZoneManager.h | 14 +- tests/AMFDeserializeTests.cpp | 48 +- tests/TestEncoding.cpp | 78 +- tests/TestLDFFormat.cpp | 8 +- tests/TestNiPoint3.cpp | 4 +- 881 files changed, 34700 insertions(+), 38689 deletions(-) diff --git a/dAuthServer/AuthServer.cpp b/dAuthServer/AuthServer.cpp index f5c85c3f..73cb4212 100644 --- a/dAuthServer/AuthServer.cpp +++ b/dAuthServer/AuthServer.cpp @@ -53,15 +53,15 @@ int main(int argc, char** argv) { std::string mysql_username = config.GetValue("mysql_username"); std::string mysql_password = config.GetValue("mysql_password"); - try { - Database::Connect(mysql_host, mysql_database, mysql_username, mysql_password); - } catch (sql::SQLException& ex) { + try { + Database::Connect(mysql_host, mysql_database, mysql_username, mysql_password); + } catch (sql::SQLException& ex) { Game::logger->Log("AuthServer", "Got an error while connecting to the database: %s", ex.what()); Database::Destroy("AuthServer"); delete Game::server; delete Game::logger; return 0; - } + } //Find out the master's IP: std::string masterIP; @@ -98,8 +98,7 @@ int main(int argc, char** argv) { if (framesSinceMasterDisconnect >= 30) break; //Exit our loop, shut down. - } - else framesSinceMasterDisconnect = 0; + } else framesSinceMasterDisconnect = 0; //In world we'd update our other systems here. @@ -134,8 +133,7 @@ int main(int argc, char** argv) { delete stmt; framesSinceLastSQLPing = 0; - } - else framesSinceLastSQLPing++; + } else framesSinceLastSQLPing++; //Sleep our thread since auth can afford to. t += std::chrono::milliseconds(mediumFramerate); //Auth can run at a lower "fps" @@ -151,7 +149,7 @@ int main(int argc, char** argv) { return EXIT_SUCCESS; } -dLogger * SetupLogger() { +dLogger* SetupLogger() { std::string logPath = "./logs/AuthServer_" + std::to_string(time(nullptr)) + ".log"; bool logToConsole = false; bool logDebugStatements = false; diff --git a/dChatFilter/dChatFilter.cpp b/dChatFilter/dChatFilter.cpp index 6389623e..ea38f8cd 100644 --- a/dChatFilter/dChatFilter.cpp +++ b/dChatFilter/dChatFilter.cpp @@ -21,8 +21,7 @@ dChatFilter::dChatFilter(const std::string& filepath, bool dontGenerateDCF) { if (!BinaryIO::DoesFileExist(filepath + ".dcf") || m_DontGenerateDCF) { ReadWordlistPlaintext(filepath + ".txt", true); if (!m_DontGenerateDCF) ExportWordlistToDCF(filepath + ".dcf", true); - } - else if (!ReadWordlistDCF(filepath + ".dcf", true)) { + } else if (!ReadWordlistDCF(filepath + ".dcf", true)) { ReadWordlistPlaintext(filepath + ".txt", true); ExportWordlistToDCF(filepath + ".dcf", true); } @@ -85,8 +84,7 @@ bool dChatFilter::ReadWordlistDCF(const std::string& filepath, bool whiteList) { } return true; - } - else { + } else { file.close(); return false; } @@ -139,7 +137,7 @@ std::vector> dChatFilter::IsSentenceOkay(const std:: m_UserUnapprovedWordCache.push_back(hash); listOfBadSegments.emplace_back(position, originalSegment.length()); } - + if (std::find(m_DeniedWords.begin(), m_DeniedWords.end(), hash) != m_DeniedWords.end() && !whiteList) { m_UserUnapprovedWordCache.push_back(hash); listOfBadSegments.emplace_back(position, originalSegment.length()); diff --git a/dChatServer/ChatPacketHandler.cpp b/dChatServer/ChatPacketHandler.cpp index 213e1948..83678525 100644 --- a/dChatServer/ChatPacketHandler.cpp +++ b/dChatServer/ChatPacketHandler.cpp @@ -29,8 +29,8 @@ void ChatPacketHandler::HandleFriendlistRequest(Packet* packet) { std::unique_ptr stmt(Database::CreatePreppedStmt( "SELECT fr.requested_player, best_friend, ci.name FROM " "(SELECT CASE " - "WHEN player_id = ? THEN friend_id " - "WHEN friend_id = ? THEN player_id " + "WHEN player_id = ? THEN friend_id " + "WHEN friend_id = ? THEN player_id " "END AS requested_player, best_friend FROM friends) AS fr " "JOIN charinfo AS ci ON ci.id = fr.requested_player " "WHERE fr.requested_player IS NOT NULL;")); @@ -48,7 +48,7 @@ void ChatPacketHandler::HandleFriendlistRequest(Packet* packet) { GeneralUtils::SetBit(fd.friendID, static_cast(eObjectBits::OBJECT_BIT_CHARACTER)); fd.isBestFriend = res->getInt(2) == 3; //0 = friends, 1 = left_requested, 2 = right_requested, 3 = both_accepted - are now bffs - if (fd.isBestFriend) player->countOfBestFriends+=1; + if (fd.isBestFriend) player->countOfBestFriends += 1; fd.friendName = res->getString(3); //Now check if they're online: @@ -60,8 +60,7 @@ void ChatPacketHandler::HandleFriendlistRequest(Packet* packet) { //Since this friend is online, we need to update them on the fact that we've just logged in: SendFriendUpdate(fr, player, 1, fd.isBestFriend); - } - else { + } else { fd.isOnline = false; fd.zoneID = LWOZONEID(); } @@ -209,8 +208,8 @@ void ChatPacketHandler::HandleFriendRequest(Packet* packet) { updateQuery->executeUpdate(); // Sent the best friend update here if the value is 3 if (bestFriendStatus == 3U) { - requestee->countOfBestFriends+=1; - requestor->countOfBestFriends+=1; + requestee->countOfBestFriends += 1; + requestor->countOfBestFriends += 1; if (requestee->sysAddr != UNASSIGNED_SYSTEM_ADDRESS) SendFriendResponse(requestee.get(), requestor, AddFriendResponseType::ACCEPTED, false, true); if (requestor->sysAddr != UNASSIGNED_SYSTEM_ADDRESS) SendFriendResponse(requestor, requestee.get(), AddFriendResponseType::ACCEPTED, false, true); for (auto& friendData : requestor->friends) { @@ -255,18 +254,18 @@ void ChatPacketHandler::HandleFriendResponse(Packet* packet) { uint8_t isAlreadyBestFriends = 0U; // We need to convert this response code to one we can actually send back to the client. switch (clientResponseCode) { - case AddFriendResponseCode::ACCEPTED: - serverResponseCode = AddFriendResponseType::ACCEPTED; - break; - case AddFriendResponseCode::BUSY: - serverResponseCode = AddFriendResponseType::BUSY; - break; - case AddFriendResponseCode::CANCELLED: - serverResponseCode = AddFriendResponseType::CANCELLED; - break; - case AddFriendResponseCode::REJECTED: - serverResponseCode = AddFriendResponseType::DECLINED; - break; + case AddFriendResponseCode::ACCEPTED: + serverResponseCode = AddFriendResponseType::ACCEPTED; + break; + case AddFriendResponseCode::BUSY: + serverResponseCode = AddFriendResponseType::BUSY; + break; + case AddFriendResponseCode::CANCELLED: + serverResponseCode = AddFriendResponseType::CANCELLED; + break; + case AddFriendResponseCode::REJECTED: + serverResponseCode = AddFriendResponseType::DECLINED; + break; } // Now that we have handled the base cases, we need to check the other cases. @@ -371,8 +370,7 @@ void ChatPacketHandler::HandleRemoveFriend(Packet* packet) { SendRemoveFriend(goonB, goonAName, true); } -void ChatPacketHandler::HandleChatMessage(Packet* packet) -{ +void ChatPacketHandler::HandleChatMessage(Packet* packet) { CINSTREAM; LWOOBJID playerID = LWOOBJID_EMPTY; inStream.Read(playerID); @@ -401,8 +399,7 @@ void ChatPacketHandler::HandleChatMessage(Packet* packet) if (team == nullptr) return; - for (const auto memberId : team->memberIDs) - { + for (const auto memberId : team->memberIDs) { auto* otherMember = playerContainer.GetPlayerData(memberId); if (otherMember == nullptr) return; @@ -493,8 +490,7 @@ void ChatPacketHandler::HandlePrivateChatMessage(Packet* packet) { } } -void ChatPacketHandler::HandleTeamInvite(Packet* packet) -{ +void ChatPacketHandler::HandleTeamInvite(Packet* packet) { CINSTREAM; LWOOBJID playerID; inStream.Read(playerID); @@ -503,27 +499,23 @@ void ChatPacketHandler::HandleTeamInvite(Packet* packet) auto* player = playerContainer.GetPlayerData(playerID); - if (player == nullptr) - { + if (player == nullptr) { return; } auto* team = playerContainer.GetTeam(playerID); - if (team == nullptr) - { + if (team == nullptr) { team = playerContainer.CreateTeam(playerID); } auto* other = playerContainer.GetPlayerData(invitedPlayer); - if (other == nullptr) - { + if (other == nullptr) { return; } - if (playerContainer.GetTeam(other->playerID) != nullptr) - { + if (playerContainer.GetTeam(other->playerID) != nullptr) { return; } @@ -539,8 +531,7 @@ void ChatPacketHandler::HandleTeamInvite(Packet* packet) Game::logger->Log("ChatPacketHandler", "Got team invite: %llu -> %s", playerID, invitedPlayer.c_str()); } -void ChatPacketHandler::HandleTeamInviteResponse(Packet* packet) -{ +void ChatPacketHandler::HandleTeamInviteResponse(Packet* packet) { CINSTREAM; LWOOBJID playerID = LWOOBJID_EMPTY; inStream.Read(playerID); @@ -554,22 +545,19 @@ void ChatPacketHandler::HandleTeamInviteResponse(Packet* packet) Game::logger->Log("ChatPacketHandler", "Accepted invite: %llu -> %llu (%d)", playerID, leaderID, declined); - if (declined) - { + if (declined) { return; } auto* team = playerContainer.GetTeam(leaderID); - if (team == nullptr) - { + if (team == nullptr) { Game::logger->Log("ChatPacketHandler", "Failed to find team for leader (%llu)", leaderID); team = playerContainer.GetTeam(playerID); } - if (team == nullptr) - { + if (team == nullptr) { Game::logger->Log("ChatPacketHandler", "Failed to find team for player (%llu)", playerID); return; } @@ -577,8 +565,7 @@ void ChatPacketHandler::HandleTeamInviteResponse(Packet* packet) playerContainer.AddMember(team, playerID); } -void ChatPacketHandler::HandleTeamLeave(Packet* packet) -{ +void ChatPacketHandler::HandleTeamLeave(Packet* packet) { CINSTREAM; LWOOBJID playerID = LWOOBJID_EMPTY; inStream.Read(playerID); @@ -590,14 +577,12 @@ void ChatPacketHandler::HandleTeamLeave(Packet* packet) Game::logger->Log("ChatPacketHandler", "(%llu) leaving team", playerID); - if (team != nullptr) - { + if (team != nullptr) { playerContainer.RemoveMember(team, playerID, false, false, true); } } -void ChatPacketHandler::HandleTeamKick(Packet* packet) -{ +void ChatPacketHandler::HandleTeamKick(Packet* packet) { CINSTREAM; LWOOBJID playerID = LWOOBJID_EMPTY; inStream.Read(playerID); @@ -611,12 +596,9 @@ void ChatPacketHandler::HandleTeamKick(Packet* packet) LWOOBJID kickedId = LWOOBJID_EMPTY; - if (kicked != nullptr) - { + if (kicked != nullptr) { kickedId = kicked->playerID; - } - else - { + } else { kickedId = playerContainer.GetId(GeneralUtils::ASCIIToUTF16(kickedPlayer)); } @@ -624,16 +606,14 @@ void ChatPacketHandler::HandleTeamKick(Packet* packet) auto* team = playerContainer.GetTeam(playerID); - if (team != nullptr) - { + if (team != nullptr) { if (team->leaderID != playerID || team->leaderID == kickedId) return; playerContainer.RemoveMember(team, kickedId, false, true, false); } } -void ChatPacketHandler::HandleTeamPromote(Packet* packet) -{ +void ChatPacketHandler::HandleTeamPromote(Packet* packet) { CINSTREAM; LWOOBJID playerID = LWOOBJID_EMPTY; inStream.Read(playerID); @@ -649,16 +629,14 @@ void ChatPacketHandler::HandleTeamPromote(Packet* packet) auto* team = playerContainer.GetTeam(playerID); - if (team != nullptr) - { + if (team != nullptr) { if (team->leaderID != playerID) return; playerContainer.PromoteMember(team, promoted->playerID); } } -void ChatPacketHandler::HandleTeamLootOption(Packet* packet) -{ +void ChatPacketHandler::HandleTeamLootOption(Packet* packet) { CINSTREAM; LWOOBJID playerID = LWOOBJID_EMPTY; inStream.Read(playerID); @@ -671,8 +649,7 @@ void ChatPacketHandler::HandleTeamLootOption(Packet* packet) auto* team = playerContainer.GetTeam(playerID); - if (team != nullptr) - { + if (team != nullptr) { if (team->leaderID != playerID) return; team->lootFlag = option; @@ -683,8 +660,7 @@ void ChatPacketHandler::HandleTeamLootOption(Packet* packet) } } -void ChatPacketHandler::HandleTeamStatusRequest(Packet* packet) -{ +void ChatPacketHandler::HandleTeamStatusRequest(Packet* packet) { CINSTREAM; LWOOBJID playerID = LWOOBJID_EMPTY; inStream.Read(playerID); @@ -693,28 +669,22 @@ void ChatPacketHandler::HandleTeamStatusRequest(Packet* packet) auto* team = playerContainer.GetTeam(playerID); auto* data = playerContainer.GetPlayerData(playerID); - if (team != nullptr && data != nullptr) - { - if (team->local && data->zoneID.GetMapID() != team->zoneId.GetMapID() && data->zoneID.GetCloneID() != team->zoneId.GetCloneID()) - { + if (team != nullptr && data != nullptr) { + if (team->local && data->zoneID.GetMapID() != team->zoneId.GetMapID() && data->zoneID.GetCloneID() != team->zoneId.GetCloneID()) { playerContainer.RemoveMember(team, playerID, false, false, true, true); return; } - if (team->memberIDs.size() <= 1 && !team->local) - { + if (team->memberIDs.size() <= 1 && !team->local) { playerContainer.DisbandTeam(team); return; } - if (!team->local) - { + if (!team->local) { ChatPacketHandler::SendTeamSetLeader(data, team->leaderID); - } - else - { + } else { ChatPacketHandler::SendTeamSetLeader(data, LWOOBJID_EMPTY); } @@ -722,16 +692,14 @@ void ChatPacketHandler::HandleTeamStatusRequest(Packet* packet) const auto leaderName = GeneralUtils::ASCIIToUTF16(std::string(data->playerName.c_str())); - for (const auto memberId : team->memberIDs) - { + for (const auto memberId : team->memberIDs) { auto* otherMember = playerContainer.GetPlayerData(memberId); if (memberId == playerID) continue; const auto memberName = playerContainer.GetName(memberId); - if (otherMember != nullptr) - { + if (otherMember != nullptr) { ChatPacketHandler::SendTeamSetOffWorldFlag(otherMember, data->playerID, data->zoneID); } ChatPacketHandler::SendTeamAddPlayer(data, false, team->local, false, memberId, memberName, otherMember != nullptr ? otherMember->zoneID : LWOZONEID(0, 0, 0)); @@ -741,8 +709,7 @@ void ChatPacketHandler::HandleTeamStatusRequest(Packet* packet) } } -void ChatPacketHandler::SendTeamInvite(PlayerData* receiver, PlayerData* sender) -{ +void ChatPacketHandler::SendTeamInvite(PlayerData* receiver, PlayerData* sender) { CBITSTREAM; PacketUtils::WriteHeader(bitStream, CHAT_INTERNAL, MSG_CHAT_INTERNAL_ROUTE_TO_PLAYER); bitStream.Write(receiver->playerID); @@ -757,8 +724,7 @@ void ChatPacketHandler::SendTeamInvite(PlayerData* receiver, PlayerData* sender) SEND_PACKET; } -void ChatPacketHandler::SendTeamInviteConfirm(PlayerData* receiver, bool bLeaderIsFreeTrial, LWOOBJID i64LeaderID, LWOZONEID i64LeaderZoneID, uint8_t ucLootFlag, uint8_t ucNumOfOtherPlayers, uint8_t ucResponseCode, std::u16string wsLeaderName) -{ +void ChatPacketHandler::SendTeamInviteConfirm(PlayerData* receiver, bool bLeaderIsFreeTrial, LWOOBJID i64LeaderID, LWOZONEID i64LeaderZoneID, uint8_t ucLootFlag, uint8_t ucNumOfOtherPlayers, uint8_t ucResponseCode, std::u16string wsLeaderName) { CBITSTREAM; PacketUtils::WriteHeader(bitStream, CHAT_INTERNAL, MSG_CHAT_INTERNAL_ROUTE_TO_PLAYER); bitStream.Write(receiver->playerID); @@ -766,7 +732,7 @@ void ChatPacketHandler::SendTeamInviteConfirm(PlayerData* receiver, bool bLeader //portion that will get routed: CMSGHEADER - bitStream.Write(receiver->playerID); + bitStream.Write(receiver->playerID); bitStream.Write(GAME_MSG::GAME_MSG_TEAM_INVITE_CONFIRM); bitStream.Write(bLeaderIsFreeTrial); @@ -777,8 +743,7 @@ void ChatPacketHandler::SendTeamInviteConfirm(PlayerData* receiver, bool bLeader bitStream.Write(ucNumOfOtherPlayers); bitStream.Write(ucResponseCode); bitStream.Write(static_cast(wsLeaderName.size())); - for (const auto character : wsLeaderName) - { + for (const auto character : wsLeaderName) { bitStream.Write(character); } @@ -786,8 +751,7 @@ void ChatPacketHandler::SendTeamInviteConfirm(PlayerData* receiver, bool bLeader SEND_PACKET; } -void ChatPacketHandler::SendTeamStatus(PlayerData* receiver, LWOOBJID i64LeaderID, LWOZONEID i64LeaderZoneID, uint8_t ucLootFlag, uint8_t ucNumOfOtherPlayers, std::u16string wsLeaderName) -{ +void ChatPacketHandler::SendTeamStatus(PlayerData* receiver, LWOOBJID i64LeaderID, LWOZONEID i64LeaderZoneID, uint8_t ucLootFlag, uint8_t ucNumOfOtherPlayers, std::u16string wsLeaderName) { CBITSTREAM; PacketUtils::WriteHeader(bitStream, CHAT_INTERNAL, MSG_CHAT_INTERNAL_ROUTE_TO_PLAYER); bitStream.Write(receiver->playerID); @@ -795,7 +759,7 @@ void ChatPacketHandler::SendTeamStatus(PlayerData* receiver, LWOOBJID i64LeaderI //portion that will get routed: CMSGHEADER - bitStream.Write(receiver->playerID); + bitStream.Write(receiver->playerID); bitStream.Write(GAME_MSG::GAME_MSG_TEAM_GET_STATUS_RESPONSE); bitStream.Write(i64LeaderID); @@ -804,8 +768,7 @@ void ChatPacketHandler::SendTeamStatus(PlayerData* receiver, LWOOBJID i64LeaderI bitStream.Write(ucLootFlag); bitStream.Write(ucNumOfOtherPlayers); bitStream.Write(static_cast(wsLeaderName.size())); - for (const auto character : wsLeaderName) - { + for (const auto character : wsLeaderName) { bitStream.Write(character); } @@ -813,8 +776,7 @@ void ChatPacketHandler::SendTeamStatus(PlayerData* receiver, LWOOBJID i64LeaderI SEND_PACKET; } -void ChatPacketHandler::SendTeamSetLeader(PlayerData* receiver, LWOOBJID i64PlayerID) -{ +void ChatPacketHandler::SendTeamSetLeader(PlayerData* receiver, LWOOBJID i64PlayerID) { CBITSTREAM; PacketUtils::WriteHeader(bitStream, CHAT_INTERNAL, MSG_CHAT_INTERNAL_ROUTE_TO_PLAYER); bitStream.Write(receiver->playerID); @@ -822,7 +784,7 @@ void ChatPacketHandler::SendTeamSetLeader(PlayerData* receiver, LWOOBJID i64Play //portion that will get routed: CMSGHEADER - bitStream.Write(receiver->playerID); + bitStream.Write(receiver->playerID); bitStream.Write(GAME_MSG::GAME_MSG_TEAM_SET_LEADER); bitStream.Write(i64PlayerID); @@ -831,8 +793,7 @@ void ChatPacketHandler::SendTeamSetLeader(PlayerData* receiver, LWOOBJID i64Play SEND_PACKET; } -void ChatPacketHandler::SendTeamAddPlayer(PlayerData* receiver, bool bIsFreeTrial, bool bLocal, bool bNoLootOnDeath, LWOOBJID i64PlayerID, std::u16string wsPlayerName, LWOZONEID zoneID) -{ +void ChatPacketHandler::SendTeamAddPlayer(PlayerData* receiver, bool bIsFreeTrial, bool bLocal, bool bNoLootOnDeath, LWOOBJID i64PlayerID, std::u16string wsPlayerName, LWOZONEID zoneID) { CBITSTREAM; PacketUtils::WriteHeader(bitStream, CHAT_INTERNAL, MSG_CHAT_INTERNAL_ROUTE_TO_PLAYER); bitStream.Write(receiver->playerID); @@ -840,7 +801,7 @@ void ChatPacketHandler::SendTeamAddPlayer(PlayerData* receiver, bool bIsFreeTria //portion that will get routed: CMSGHEADER - bitStream.Write(receiver->playerID); + bitStream.Write(receiver->playerID); bitStream.Write(GAME_MSG::GAME_MSG_TEAM_ADD_PLAYER); bitStream.Write(bIsFreeTrial); @@ -848,13 +809,11 @@ void ChatPacketHandler::SendTeamAddPlayer(PlayerData* receiver, bool bIsFreeTria bitStream.Write(bNoLootOnDeath); bitStream.Write(i64PlayerID); bitStream.Write(static_cast(wsPlayerName.size())); - for (const auto character : wsPlayerName) - { + for (const auto character : wsPlayerName) { bitStream.Write(character); } bitStream.Write1(); - if (receiver->zoneID.GetCloneID() == zoneID.GetCloneID()) - { + if (receiver->zoneID.GetCloneID() == zoneID.GetCloneID()) { zoneID = LWOZONEID(zoneID.GetMapID(), zoneID.GetInstanceID(), 0); } bitStream.Write(zoneID); @@ -863,8 +822,7 @@ void ChatPacketHandler::SendTeamAddPlayer(PlayerData* receiver, bool bIsFreeTria SEND_PACKET; } -void ChatPacketHandler::SendTeamRemovePlayer(PlayerData* receiver, bool bDisband, bool bIsKicked, bool bIsLeaving, bool bLocal, LWOOBJID i64LeaderID, LWOOBJID i64PlayerID, std::u16string wsPlayerName) -{ +void ChatPacketHandler::SendTeamRemovePlayer(PlayerData* receiver, bool bDisband, bool bIsKicked, bool bIsLeaving, bool bLocal, LWOOBJID i64LeaderID, LWOOBJID i64PlayerID, std::u16string wsPlayerName) { CBITSTREAM; PacketUtils::WriteHeader(bitStream, CHAT_INTERNAL, MSG_CHAT_INTERNAL_ROUTE_TO_PLAYER); bitStream.Write(receiver->playerID); @@ -872,7 +830,7 @@ void ChatPacketHandler::SendTeamRemovePlayer(PlayerData* receiver, bool bDisband //portion that will get routed: CMSGHEADER - bitStream.Write(receiver->playerID); + bitStream.Write(receiver->playerID); bitStream.Write(GAME_MSG::GAME_MSG_TEAM_REMOVE_PLAYER); bitStream.Write(bDisband); @@ -882,8 +840,7 @@ void ChatPacketHandler::SendTeamRemovePlayer(PlayerData* receiver, bool bDisband bitStream.Write(i64LeaderID); bitStream.Write(i64PlayerID); bitStream.Write(static_cast(wsPlayerName.size())); - for (const auto character : wsPlayerName) - { + for (const auto character : wsPlayerName) { bitStream.Write(character); } @@ -891,8 +848,7 @@ void ChatPacketHandler::SendTeamRemovePlayer(PlayerData* receiver, bool bDisband SEND_PACKET; } -void ChatPacketHandler::SendTeamSetOffWorldFlag(PlayerData* receiver, LWOOBJID i64PlayerID, LWOZONEID zoneID) -{ +void ChatPacketHandler::SendTeamSetOffWorldFlag(PlayerData* receiver, LWOOBJID i64PlayerID, LWOZONEID zoneID) { CBITSTREAM; PacketUtils::WriteHeader(bitStream, CHAT_INTERNAL, MSG_CHAT_INTERNAL_ROUTE_TO_PLAYER); bitStream.Write(receiver->playerID); @@ -900,12 +856,11 @@ void ChatPacketHandler::SendTeamSetOffWorldFlag(PlayerData* receiver, LWOOBJID i //portion that will get routed: CMSGHEADER - bitStream.Write(receiver->playerID); + bitStream.Write(receiver->playerID); bitStream.Write(GAME_MSG::GAME_MSG_TEAM_SET_OFF_WORLD_FLAG); bitStream.Write(i64PlayerID); - if (receiver->zoneID.GetCloneID() == zoneID.GetCloneID()) - { + if (receiver->zoneID.GetCloneID() == zoneID.GetCloneID()) { zoneID = LWOZONEID(zoneID.GetMapID(), zoneID.GetInstanceID(), 0); } bitStream.Write(zoneID); @@ -943,12 +898,9 @@ void ChatPacketHandler::SendFriendUpdate(PlayerData* friendData, PlayerData* pla bitStream.Write(playerData->zoneID.GetMapID()); bitStream.Write(playerData->zoneID.GetInstanceID()); - if (playerData->zoneID.GetCloneID() == friendData->zoneID.GetCloneID()) - { + if (playerData->zoneID.GetCloneID() == friendData->zoneID.GetCloneID()) { bitStream.Write(0); - } - else - { + } else { bitStream.Write(playerData->zoneID.GetCloneID()); } @@ -998,7 +950,7 @@ void ChatPacketHandler::SendFriendResponse(PlayerData* receiver, PlayerData* sen // Then write the player name PacketUtils::WritePacketWString(sender->playerName.c_str(), 33, &bitStream); // Then if this is an acceptance code, write the following extra info. - if (responseCode == AddFriendResponseType::ACCEPTED) { + if (responseCode == AddFriendResponseType::ACCEPTED) { bitStream.Write(sender->playerID); bitStream.Write(sender->zoneID); bitStream.Write(isBestFriendRequest); //isBFF diff --git a/dChatServer/ChatServer.cpp b/dChatServer/ChatServer.cpp index 639d7b70..273921eb 100644 --- a/dChatServer/ChatServer.cpp +++ b/dChatServer/ChatServer.cpp @@ -58,8 +58,7 @@ int main(int argc, char** argv) { try { Database::Connect(mysql_host, mysql_database, mysql_username, mysql_password); - } - catch (sql::SQLException& ex) { + } catch (sql::SQLException& ex) { Game::logger->Log("ChatServer", "Got an error while connecting to the database: %s", ex.what()); Database::Destroy("ChatServer"); delete Game::server; @@ -104,8 +103,7 @@ int main(int argc, char** argv) { if (framesSinceMasterDisconnect >= 30) break; //Exit our loop, shut down. - } - else framesSinceMasterDisconnect = 0; + } else framesSinceMasterDisconnect = 0; //In world we'd update our other systems here. @@ -122,8 +120,7 @@ int main(int argc, char** argv) { if (framesSinceLastFlush >= 900) { Game::logger->Flush(); framesSinceLastFlush = 0; - } - else framesSinceLastFlush++; + } else framesSinceLastFlush++; //Every 10 min we ping our sql server to keep it alive hopefully: if (framesSinceLastSQLPing >= 40000) { @@ -141,8 +138,7 @@ int main(int argc, char** argv) { delete stmt; framesSinceLastSQLPing = 0; - } - else framesSinceLastSQLPing++; + } else framesSinceLastSQLPing++; //Sleep our thread since auth can afford to. t += std::chrono::milliseconds(mediumFramerate); //Chat can run at a lower "fps" @@ -158,7 +154,7 @@ int main(int argc, char** argv) { return EXIT_SUCCESS; } -dLogger * SetupLogger() { +dLogger* SetupLogger() { std::string logPath = "./logs/ChatServer_" + std::to_string(time(nullptr)) + ".log"; bool logToConsole = false; bool logDebugStatements = false; diff --git a/dChatServer/PlayerContainer.cpp b/dChatServer/PlayerContainer.cpp index 73a22ba9..d8c2e067 100644 --- a/dChatServer/PlayerContainer.cpp +++ b/dChatServer/PlayerContainer.cpp @@ -70,17 +70,15 @@ void PlayerContainer::RemovePlayer(Packet* packet) { auto* team = GetTeam(playerID); - if (team != nullptr) - { + if (team != nullptr) { const auto memberName = GeneralUtils::ASCIIToUTF16(std::string(player->playerName.c_str())); - for (const auto memberId : team->memberIDs) - { + for (const auto memberId : team->memberIDs) { auto* otherMember = GetPlayerData(memberId); if (otherMember == nullptr) continue; - ChatPacketHandler::SendTeamSetOffWorldFlag(otherMember, playerID, {0, 0, 0}); + ChatPacketHandler::SendTeamSetOffWorldFlag(otherMember, playerID, { 0, 0, 0 }); } } @@ -97,8 +95,7 @@ void PlayerContainer::RemovePlayer(Packet* packet) { insertLog->executeUpdate(); } -void PlayerContainer::MuteUpdate(Packet* packet) -{ +void PlayerContainer::MuteUpdate(Packet* packet) { CINSTREAM; LWOOBJID playerID; inStream.Read(playerID); //skip header @@ -108,8 +105,7 @@ void PlayerContainer::MuteUpdate(Packet* packet) auto* player = this->GetPlayerData(playerID); - if (player == nullptr) - { + if (player == nullptr) { Game::logger->Log("PlayerContainer", "Failed to find user: %llu", playerID); return; @@ -120,8 +116,7 @@ void PlayerContainer::MuteUpdate(Packet* packet) BroadcastMuteUpdate(playerID, expire); } -void PlayerContainer::CreateTeamServer(Packet* packet) -{ +void PlayerContainer::CreateTeamServer(Packet* packet) { CINSTREAM; LWOOBJID playerID; inStream.Read(playerID); //skip header @@ -133,8 +128,7 @@ void PlayerContainer::CreateTeamServer(Packet* packet) members.reserve(membersSize); - for (size_t i = 0; i < membersSize; i++) - { + for (size_t i = 0; i < membersSize; i++) { LWOOBJID member; inStream.Read(member); members.push_back(member); @@ -146,16 +140,14 @@ void PlayerContainer::CreateTeamServer(Packet* packet) auto* team = CreateLocalTeam(members); - if (team != nullptr) - { + if (team != nullptr) { team->zoneId = zoneId; } UpdateTeamsOnWorld(team, false); } -void PlayerContainer::BroadcastMuteUpdate(LWOOBJID player, time_t time) -{ +void PlayerContainer::BroadcastMuteUpdate(LWOOBJID player, time_t time) { CBITSTREAM; PacketUtils::WriteHeader(bitStream, CHAT_INTERNAL, MSG_CHAT_INTERNAL_MUTE_UPDATE); @@ -165,30 +157,23 @@ void PlayerContainer::BroadcastMuteUpdate(LWOOBJID player, time_t time) Game::server->Send(&bitStream, UNASSIGNED_SYSTEM_ADDRESS, true); } -TeamData* PlayerContainer::CreateLocalTeam(std::vector members) -{ - if (members.empty()) - { +TeamData* PlayerContainer::CreateLocalTeam(std::vector members) { + if (members.empty()) { return nullptr; } TeamData* newTeam = nullptr; - for (const auto member : members) - { + for (const auto member : members) { auto* team = GetTeam(member); - if (team != nullptr) - { + if (team != nullptr) { RemoveMember(team, member, false, false, true); } - if (newTeam == nullptr) - { + if (newTeam == nullptr) { newTeam = CreateTeam(member, true); - } - else - { + } else { AddMember(newTeam, member); } } @@ -200,8 +185,7 @@ TeamData* PlayerContainer::CreateLocalTeam(std::vector members) return newTeam; } -TeamData* PlayerContainer::CreateTeam(LWOOBJID leader, bool local) -{ +TeamData* PlayerContainer::CreateTeam(LWOOBJID leader, bool local) { auto* team = new TeamData(); team->teamID = ++mTeamIDCounter; @@ -215,10 +199,8 @@ TeamData* PlayerContainer::CreateTeam(LWOOBJID leader, bool local) return team; } -TeamData* PlayerContainer::GetTeam(LWOOBJID playerID) -{ - for (auto* team : mTeams) - { +TeamData* PlayerContainer::GetTeam(LWOOBJID playerID) { + for (auto* team : mTeams) { if (std::find(team->memberIDs.begin(), team->memberIDs.end(), playerID) == team->memberIDs.end()) continue; return team; @@ -227,8 +209,7 @@ TeamData* PlayerContainer::GetTeam(LWOOBJID playerID) return nullptr; } -void PlayerContainer::AddMember(TeamData* team, LWOOBJID playerID) -{ +void PlayerContainer::AddMember(TeamData* team, LWOOBJID playerID) { const auto index = std::find(team->memberIDs.begin(), team->memberIDs.end(), playerID); if (index != team->memberIDs.end()) return; @@ -245,19 +226,15 @@ void PlayerContainer::AddMember(TeamData* team, LWOOBJID playerID) ChatPacketHandler::SendTeamInviteConfirm(member, false, leader->playerID, leader->zoneID, team->lootFlag, 0, 0, leaderName); - if (!team->local) - { + if (!team->local) { ChatPacketHandler::SendTeamSetLeader(member, leader->playerID); - } - else - { + } else { ChatPacketHandler::SendTeamSetLeader(member, LWOOBJID_EMPTY); } UpdateTeamsOnWorld(team, false); - for (const auto memberId : team->memberIDs) - { + for (const auto memberId : team->memberIDs) { auto* otherMember = GetPlayerData(memberId); if (otherMember == member) continue; @@ -266,32 +243,27 @@ void PlayerContainer::AddMember(TeamData* team, LWOOBJID playerID) ChatPacketHandler::SendTeamAddPlayer(member, false, team->local, false, memberId, otherMemberName, otherMember != nullptr ? otherMember->zoneID : LWOZONEID(0, 0, 0)); - if (otherMember != nullptr) - { + if (otherMember != nullptr) { ChatPacketHandler::SendTeamAddPlayer(otherMember, false, team->local, false, member->playerID, memberName, member->zoneID); } } } -void PlayerContainer::RemoveMember(TeamData* team, LWOOBJID playerID, bool disband, bool kicked, bool leaving, bool silent) -{ +void PlayerContainer::RemoveMember(TeamData* team, LWOOBJID playerID, bool disband, bool kicked, bool leaving, bool silent) { const auto index = std::find(team->memberIDs.begin(), team->memberIDs.end(), playerID); if (index == team->memberIDs.end()) return; auto* member = GetPlayerData(playerID); - if (member != nullptr && !silent) - { + if (member != nullptr && !silent) { ChatPacketHandler::SendTeamSetLeader(member, LWOOBJID_EMPTY); } const auto memberName = GetName(playerID); - for (const auto memberId : team->memberIDs) - { - if (silent && memberId == playerID) - { + for (const auto memberId : team->memberIDs) { + if (silent && memberId == playerID) { continue; } @@ -306,25 +278,19 @@ void PlayerContainer::RemoveMember(TeamData* team, LWOOBJID playerID, bool disba UpdateTeamsOnWorld(team, false); - if (team->memberIDs.size() <= 1) - { + if (team->memberIDs.size() <= 1) { DisbandTeam(team); - } - else - { - if (playerID == team->leaderID) - { + } else { + if (playerID == team->leaderID) { PromoteMember(team, team->memberIDs[0]); } } } -void PlayerContainer::PromoteMember(TeamData* team, LWOOBJID newLeader) -{ +void PlayerContainer::PromoteMember(TeamData* team, LWOOBJID newLeader) { team->leaderID = newLeader; - for (const auto memberId : team->memberIDs) - { + for (const auto memberId : team->memberIDs) { auto* otherMember = GetPlayerData(memberId); if (otherMember == nullptr) continue; @@ -333,14 +299,12 @@ void PlayerContainer::PromoteMember(TeamData* team, LWOOBJID newLeader) } } -void PlayerContainer::DisbandTeam(TeamData* team) -{ +void PlayerContainer::DisbandTeam(TeamData* team) { const auto index = std::find(mTeams.begin(), mTeams.end(), team); if (index == mTeams.end()) return; - for (const auto memberId : team->memberIDs) - { + for (const auto memberId : team->memberIDs) { auto* otherMember = GetPlayerData(memberId); if (otherMember == nullptr) continue; @@ -358,8 +322,7 @@ void PlayerContainer::DisbandTeam(TeamData* team) delete team; } -void PlayerContainer::TeamStatusUpdate(TeamData* team) -{ +void PlayerContainer::TeamStatusUpdate(TeamData* team) { const auto index = std::find(mTeams.begin(), mTeams.end(), team); if (index == mTeams.end()) return; @@ -370,14 +333,12 @@ void PlayerContainer::TeamStatusUpdate(TeamData* team) const auto leaderName = GeneralUtils::ASCIIToUTF16(std::string(leader->playerName.c_str())); - for (const auto memberId : team->memberIDs) - { + for (const auto memberId : team->memberIDs) { auto* otherMember = GetPlayerData(memberId); if (otherMember == nullptr) continue; - if (!team->local) - { + if (!team->local) { ChatPacketHandler::SendTeamStatus(otherMember, team->leaderID, leader->zoneID, team->lootFlag, 0, leaderName); } } @@ -385,20 +346,17 @@ void PlayerContainer::TeamStatusUpdate(TeamData* team) UpdateTeamsOnWorld(team, false); } -void PlayerContainer::UpdateTeamsOnWorld(TeamData* team, bool deleteTeam) -{ +void PlayerContainer::UpdateTeamsOnWorld(TeamData* team, bool deleteTeam) { CBITSTREAM; PacketUtils::WriteHeader(bitStream, CHAT_INTERNAL, MSG_CHAT_INTERNAL_TEAM_UPDATE); bitStream.Write(team->teamID); bitStream.Write(deleteTeam); - if (!deleteTeam) - { + if (!deleteTeam) { bitStream.Write(team->lootFlag); bitStream.Write(static_cast(team->memberIDs.size())); - for (const auto memberID : team->memberIDs) - { + for (const auto memberID : team->memberIDs) { bitStream.Write(memberID); } } @@ -406,8 +364,7 @@ void PlayerContainer::UpdateTeamsOnWorld(TeamData* team, bool deleteTeam) Game::server->Send(&bitStream, UNASSIGNED_SYSTEM_ADDRESS, true); } -std::u16string PlayerContainer::GetName(LWOOBJID playerID) -{ +std::u16string PlayerContainer::GetName(LWOOBJID playerID) { const auto& pair = mNames.find(playerID); if (pair == mNames.end()) return u""; @@ -415,12 +372,9 @@ std::u16string PlayerContainer::GetName(LWOOBJID playerID) return pair->second; } -LWOOBJID PlayerContainer::GetId(const std::u16string& playerName) -{ - for (const auto& pair : mNames) - { - if (pair.second == playerName) - { +LWOOBJID PlayerContainer::GetId(const std::u16string& playerName) { + for (const auto& pair : mNames) { + if (pair.second == playerName) { return pair.first; } } @@ -428,7 +382,6 @@ LWOOBJID PlayerContainer::GetId(const std::u16string& playerName) return LWOOBJID_EMPTY; } -bool PlayerContainer::GetIsMuted(PlayerData* data) -{ +bool PlayerContainer::GetIsMuted(PlayerData* data) { return data->muteExpire == 1 || data->muteExpire > time(NULL); } diff --git a/dChatServer/PlayerContainer.h b/dChatServer/PlayerContainer.h index 9216a361..0836eb59 100644 --- a/dChatServer/PlayerContainer.h +++ b/dChatServer/PlayerContainer.h @@ -20,7 +20,7 @@ struct PlayerData { struct TeamData { LWOOBJID teamID = LWOOBJID_EMPTY; // Internal use LWOOBJID leaderID = LWOOBJID_EMPTY; - std::vector memberIDs {}; + std::vector memberIDs{}; uint8_t lootFlag = 0; bool local = false; LWOZONEID zoneId = {}; diff --git a/dCommon/AMFDeserialize.cpp b/dCommon/AMFDeserialize.cpp index afe2b61b..df4a7cb6 100644 --- a/dCommon/AMFDeserialize.cpp +++ b/dCommon/AMFDeserialize.cpp @@ -15,64 +15,64 @@ AMFValue* AMFDeserialize::Read(RakNet::BitStream* inStream) { inStream->Read(marker); // Based on the typing, create the value associated with that and return the base value class switch (marker) { - case AMFValueType::AMFUndefined: { - returnValue = new AMFUndefinedValue(); - break; - } + case AMFValueType::AMFUndefined: { + returnValue = new AMFUndefinedValue(); + break; + } - case AMFValueType::AMFNull: { - returnValue = new AMFNullValue(); - break; - } + case AMFValueType::AMFNull: { + returnValue = new AMFNullValue(); + break; + } - case AMFValueType::AMFFalse: { - returnValue = new AMFFalseValue(); - break; - } + case AMFValueType::AMFFalse: { + returnValue = new AMFFalseValue(); + break; + } - case AMFValueType::AMFTrue: { - returnValue = new AMFTrueValue(); - break; - } + case AMFValueType::AMFTrue: { + returnValue = new AMFTrueValue(); + break; + } - case AMFValueType::AMFInteger: { - returnValue = ReadAmfInteger(inStream); - break; - } + case AMFValueType::AMFInteger: { + returnValue = ReadAmfInteger(inStream); + break; + } - case AMFValueType::AMFDouble: { - returnValue = ReadAmfDouble(inStream); - break; - } + case AMFValueType::AMFDouble: { + returnValue = ReadAmfDouble(inStream); + break; + } - case AMFValueType::AMFString: { - returnValue = ReadAmfString(inStream); - break; - } + case AMFValueType::AMFString: { + returnValue = ReadAmfString(inStream); + break; + } - case AMFValueType::AMFArray: { - returnValue = ReadAmfArray(inStream); - break; - } + case AMFValueType::AMFArray: { + returnValue = ReadAmfArray(inStream); + break; + } - // TODO We do not need these values, but if someone wants to implement them - // then please do so and add the corresponding unit tests. - case AMFValueType::AMFXMLDoc: - case AMFValueType::AMFDate: - case AMFValueType::AMFObject: - case AMFValueType::AMFXML: - case AMFValueType::AMFByteArray: - case AMFValueType::AMFVectorInt: - case AMFValueType::AMFVectorUInt: - case AMFValueType::AMFVectorDouble: - case AMFValueType::AMFVectorObject: - case AMFValueType::AMFDictionary: { - throw static_cast(marker); - break; - } - default: - throw static_cast(marker); - break; + // TODO We do not need these values, but if someone wants to implement them + // then please do so and add the corresponding unit tests. + case AMFValueType::AMFXMLDoc: + case AMFValueType::AMFDate: + case AMFValueType::AMFObject: + case AMFValueType::AMFXML: + case AMFValueType::AMFByteArray: + case AMFValueType::AMFVectorInt: + case AMFValueType::AMFVectorUInt: + case AMFValueType::AMFVectorDouble: + case AMFValueType::AMFVectorObject: + case AMFValueType::AMFDictionary: { + throw static_cast(marker); + break; + } + default: + throw static_cast(marker); + break; } return returnValue; } @@ -128,10 +128,10 @@ AMFValue* AMFDeserialize::ReadAmfDouble(RakNet::BitStream* inStream) { AMFValue* AMFDeserialize::ReadAmfArray(RakNet::BitStream* inStream) { auto arrayValue = new AMFArrayValue(); - // Read size of dense array + // Read size of dense array auto sizeOfDenseArray = (ReadU29(inStream) >> 1); - // Then read Key'd portion + // Then read Key'd portion while (true) { auto key = ReadString(inStream); // No more values when we encounter an empty string @@ -139,7 +139,7 @@ AMFValue* AMFDeserialize::ReadAmfArray(RakNet::BitStream* inStream) { arrayValue->InsertValue(key, Read(inStream)); } - // Finally read dense portion + // Finally read dense portion for (uint32_t i = 0; i < sizeOfDenseArray; i++) { arrayValue->PushBackValue(Read(inStream)); } diff --git a/dCommon/AMFDeserialize.h b/dCommon/AMFDeserialize.h index d03c150f..a49cdcd2 100644 --- a/dCommon/AMFDeserialize.h +++ b/dCommon/AMFDeserialize.h @@ -7,65 +7,65 @@ class AMFValue; class AMFDeserialize { - public: - /** - * Read an AMF3 value from a bitstream. - * - * @param inStream inStream to read value from. - * @return Returns an AMFValue with all the information from the bitStream in it. - */ - AMFValue* Read(RakNet::BitStream* inStream); - private: - /** - * @brief Private method to read a U29 integer from a bitstream - * - * @param inStream bitstream to read data from - * @return The number as an unsigned 29 bit integer - */ - uint32_t ReadU29(RakNet::BitStream* inStream); +public: + /** + * Read an AMF3 value from a bitstream. + * + * @param inStream inStream to read value from. + * @return Returns an AMFValue with all the information from the bitStream in it. + */ + AMFValue* Read(RakNet::BitStream* inStream); +private: + /** + * @brief Private method to read a U29 integer from a bitstream + * + * @param inStream bitstream to read data from + * @return The number as an unsigned 29 bit integer + */ + uint32_t ReadU29(RakNet::BitStream* inStream); - /** - * @brief Reads a string from a bitstream - * - * @param inStream bitStream to read data from - * @return The read string - */ - std::string ReadString(RakNet::BitStream* inStream); - - /** - * @brief Read an AMFDouble value from a bitStream - * - * @param inStream bitStream to read data from - * @return Double value represented as an AMFValue - */ - AMFValue* ReadAmfDouble(RakNet::BitStream* inStream); + /** + * @brief Reads a string from a bitstream + * + * @param inStream bitStream to read data from + * @return The read string + */ + std::string ReadString(RakNet::BitStream* inStream); - /** - * @brief Read an AMFArray from a bitStream - * - * @param inStream bitStream to read data from - * @return Array value represented as an AMFValue - */ - AMFValue* ReadAmfArray(RakNet::BitStream* inStream); + /** + * @brief Read an AMFDouble value from a bitStream + * + * @param inStream bitStream to read data from + * @return Double value represented as an AMFValue + */ + AMFValue* ReadAmfDouble(RakNet::BitStream* inStream); - /** - * @brief Read an AMFString from a bitStream - * - * @param inStream bitStream to read data from - * @return String value represented as an AMFValue - */ - AMFValue* ReadAmfString(RakNet::BitStream* inStream); + /** + * @brief Read an AMFArray from a bitStream + * + * @param inStream bitStream to read data from + * @return Array value represented as an AMFValue + */ + AMFValue* ReadAmfArray(RakNet::BitStream* inStream); - /** - * @brief Read an AMFInteger from a bitStream - * - * @param inStream bitStream to read data from - * @return Integer value represented as an AMFValue - */ - AMFValue* ReadAmfInteger(RakNet::BitStream* inStream); + /** + * @brief Read an AMFString from a bitStream + * + * @param inStream bitStream to read data from + * @return String value represented as an AMFValue + */ + AMFValue* ReadAmfString(RakNet::BitStream* inStream); - /** - * List of strings read so far saved to be read by reference. - */ - std::vector accessedElements; + /** + * @brief Read an AMFInteger from a bitStream + * + * @param inStream bitStream to read data from + * @return Integer value represented as an AMFValue + */ + AMFValue* ReadAmfInteger(RakNet::BitStream* inStream); + + /** + * List of strings read so far saved to be read by reference. + */ + std::vector accessedElements; }; diff --git a/dCommon/AMFFormat.cpp b/dCommon/AMFFormat.cpp index 741a8bc4..822f994d 100644 --- a/dCommon/AMFFormat.cpp +++ b/dCommon/AMFFormat.cpp @@ -2,170 +2,170 @@ // AMFInteger void AMFIntegerValue::SetIntegerValue(uint32_t value) { - this->value = value; + this->value = value; } uint32_t AMFIntegerValue::GetIntegerValue() { - return this->value; + return this->value; } // AMFDouble void AMFDoubleValue::SetDoubleValue(double value) { - this->value = value; + this->value = value; } double AMFDoubleValue::GetDoubleValue() { - return this->value; + return this->value; } // AMFString void AMFStringValue::SetStringValue(const std::string& value) { - this->value = value; + this->value = value; } std::string AMFStringValue::GetStringValue() { - return this->value; + return this->value; } // AMFXMLDoc void AMFXMLDocValue::SetXMLDocValue(const std::string& value) { - this->xmlData = value; + this->xmlData = value; } std::string AMFXMLDocValue::GetXMLDocValue() { - return this->xmlData; + return this->xmlData; } // AMFDate void AMFDateValue::SetDateValue(uint64_t value) { - this->millisecondTimestamp = value; + this->millisecondTimestamp = value; } uint64_t AMFDateValue::GetDateValue() { - return this->millisecondTimestamp; + return this->millisecondTimestamp; } // AMFArray Insert Value void AMFArrayValue::InsertValue(const std::string& key, AMFValue* value) { - this->associative.insert(std::make_pair(key, value)); + this->associative.insert(std::make_pair(key, value)); } // AMFArray Remove Value void AMFArrayValue::RemoveValue(const std::string& key) { - _AMFArrayMap_::iterator it = this->associative.find(key); - if (it != this->associative.end()) { - this->associative.erase(it); - } + _AMFArrayMap_::iterator it = this->associative.find(key); + if (it != this->associative.end()) { + this->associative.erase(it); + } } // AMFArray Find Value AMFValue* AMFArrayValue::FindValue(const std::string& key) { - _AMFArrayMap_::iterator it = this->associative.find(key); - if (it != this->associative.end()) { - return it->second; - } - - return nullptr; + _AMFArrayMap_::iterator it = this->associative.find(key); + if (it != this->associative.end()) { + return it->second; + } + + return nullptr; } // AMFArray Get Associative Iterator Begin _AMFArrayMap_::iterator AMFArrayValue::GetAssociativeIteratorValueBegin() { - return this->associative.begin(); + return this->associative.begin(); } // AMFArray Get Associative Iterator End _AMFArrayMap_::iterator AMFArrayValue::GetAssociativeIteratorValueEnd() { - return this->associative.end(); + return this->associative.end(); } // AMFArray Push Back Value void AMFArrayValue::PushBackValue(AMFValue* value) { - this->dense.push_back(value); + this->dense.push_back(value); } // AMFArray Pop Back Value void AMFArrayValue::PopBackValue() { - this->dense.pop_back(); + this->dense.pop_back(); } // AMFArray Get Dense List Size uint32_t AMFArrayValue::GetDenseValueSize() { - return (uint32_t)this->dense.size(); + return (uint32_t)this->dense.size(); } // AMFArray Get value at index in Dense List AMFValue* AMFArrayValue::GetValueAt(uint32_t index) { - return this->dense.at(index); + return this->dense.at(index); } // AMFArray Get Dense Iterator Begin _AMFArrayList_::iterator AMFArrayValue::GetDenseIteratorBegin() { - return this->dense.begin(); + return this->dense.begin(); } // AMFArray Get Dense Iterator End _AMFArrayList_::iterator AMFArrayValue::GetDenseIteratorEnd() { - return this->dense.end(); + return this->dense.end(); } AMFArrayValue::~AMFArrayValue() { - for (auto valueToDelete : GetDenseArray()) { - if (valueToDelete) delete valueToDelete; - } - for (auto valueToDelete : GetAssociativeMap()) { - if (valueToDelete.second) delete valueToDelete.second; - } + for (auto valueToDelete : GetDenseArray()) { + if (valueToDelete) delete valueToDelete; + } + for (auto valueToDelete : GetAssociativeMap()) { + if (valueToDelete.second) delete valueToDelete.second; + } } // AMFObject Constructor AMFObjectValue::AMFObjectValue(std::vector> traits) { - this->traits.reserve(traits.size()); - std::vector>::iterator it = traits.begin(); - while (it != traits.end()) { - this->traits.insert(std::make_pair(it->first, std::make_pair(it->second, new AMFNullValue()))); - it++; - } + this->traits.reserve(traits.size()); + std::vector>::iterator it = traits.begin(); + while (it != traits.end()) { + this->traits.insert(std::make_pair(it->first, std::make_pair(it->second, new AMFNullValue()))); + it++; + } } // AMFObject Set Value void AMFObjectValue::SetTraitValue(const std::string& trait, AMFValue* value) { - if (value) { - _AMFObjectTraits_::iterator it = this->traits.find(trait); - if (it != this->traits.end()) { - if (it->second.first == value->GetValueType()) { - it->second.second = value; - } - } - } + if (value) { + _AMFObjectTraits_::iterator it = this->traits.find(trait); + if (it != this->traits.end()) { + if (it->second.first == value->GetValueType()) { + it->second.second = value; + } + } + } } // AMFObject Get Value AMFValue* AMFObjectValue::GetTraitValue(const std::string& trait) { - _AMFObjectTraits_::iterator it = this->traits.find(trait); - if (it != this->traits.end()) { - return it->second.second; - } - - return nullptr; + _AMFObjectTraits_::iterator it = this->traits.find(trait); + if (it != this->traits.end()) { + return it->second.second; + } + + return nullptr; } // AMFObject Get Trait Iterator Begin _AMFObjectTraits_::iterator AMFObjectValue::GetTraitsIteratorBegin() { - return this->traits.begin(); + return this->traits.begin(); } // AMFObject Get Trait Iterator End _AMFObjectTraits_::iterator AMFObjectValue::GetTraitsIteratorEnd() { - return this->traits.end(); + return this->traits.end(); } // AMFObject Get Trait Size uint32_t AMFObjectValue::GetTraitArrayCount() { - return (uint32_t)this->traits.size(); + return (uint32_t)this->traits.size(); } AMFObjectValue::~AMFObjectValue() { - for (auto valueToDelete = GetTraitsIteratorBegin(); valueToDelete != GetTraitsIteratorEnd(); valueToDelete++) { - if (valueToDelete->second.second) delete valueToDelete->second.second; - } + for (auto valueToDelete = GetTraitsIteratorBegin(); valueToDelete != GetTraitsIteratorEnd(); valueToDelete++) { + if (valueToDelete->second.second) delete valueToDelete->second.second; + } } diff --git a/dCommon/AMFFormat.h b/dCommon/AMFFormat.h index 54a02944..eaa342cd 100644 --- a/dCommon/AMFFormat.h +++ b/dCommon/AMFFormat.h @@ -23,43 +23,43 @@ class AMFValue; // Forward declaration //! An enum for each AMF value type enum AMFValueType : unsigned char { - AMFUndefined = 0x00, //!< An undefined AMF Value - AMFNull = 0x01, //!< A null AMF value - AMFFalse = 0x02, //!< A false AMF value - AMFTrue = 0x03, //!< A true AMF value - AMFInteger = 0x04, //!< An integer AMF value - AMFDouble = 0x05, //!< A double AMF value - AMFString = 0x06, //!< A string AMF value - AMFXMLDoc = 0x07, //!< An XML Doc AMF value - AMFDate = 0x08, //!< A date AMF value - AMFArray = 0x09, //!< An array AMF value - AMFObject = 0x0A, //!< An object AMF value - AMFXML = 0x0B, //!< An XML AMF value - AMFByteArray = 0x0C, //!< A byte array AMF value - AMFVectorInt = 0x0D, //!< An integer vector AMF value - AMFVectorUInt = 0x0E, //!< An unsigned integer AMF value - AMFVectorDouble = 0x0F, //!< A double vector AMF value - AMFVectorObject = 0x10, //!< An object vector AMF value - AMFDictionary = 0x11 //!< A dictionary AMF value + AMFUndefined = 0x00, //!< An undefined AMF Value + AMFNull = 0x01, //!< A null AMF value + AMFFalse = 0x02, //!< A false AMF value + AMFTrue = 0x03, //!< A true AMF value + AMFInteger = 0x04, //!< An integer AMF value + AMFDouble = 0x05, //!< A double AMF value + AMFString = 0x06, //!< A string AMF value + AMFXMLDoc = 0x07, //!< An XML Doc AMF value + AMFDate = 0x08, //!< A date AMF value + AMFArray = 0x09, //!< An array AMF value + AMFObject = 0x0A, //!< An object AMF value + AMFXML = 0x0B, //!< An XML AMF value + AMFByteArray = 0x0C, //!< A byte array AMF value + AMFVectorInt = 0x0D, //!< An integer vector AMF value + AMFVectorUInt = 0x0E, //!< An unsigned integer AMF value + AMFVectorDouble = 0x0F, //!< A double vector AMF value + AMFVectorObject = 0x10, //!< An object vector AMF value + AMFDictionary = 0x11 //!< A dictionary AMF value }; //! An enum for the object value types enum AMFObjectValueType : unsigned char { - AMFObjectAnonymous = 0x01, - AMFObjectTyped = 0x02, - AMFObjectDynamic = 0x03, - AMFObjectExternalizable = 0x04 + AMFObjectAnonymous = 0x01, + AMFObjectTyped = 0x02, + AMFObjectDynamic = 0x03, + AMFObjectExternalizable = 0x04 }; //! The base AMF value class class AMFValue { public: - //! Returns the AMF value type - /*! - \return The AMF value type - */ - virtual AMFValueType GetValueType() = 0; - virtual ~AMFValue() {}; + //! Returns the AMF value type + /*! + \return The AMF value type + */ + virtual AMFValueType GetValueType() = 0; + virtual ~AMFValue() {}; }; //! A typedef for a pointer to an AMF value @@ -71,314 +71,314 @@ typedef AMFValue* NDGFxValue; //! The undefined value AMF type class AMFUndefinedValue : public AMFValue { private: - //! Returns the AMF value type - /*! - \return The AMF value type - */ - AMFValueType GetValueType() { return AMFUndefined; } + //! Returns the AMF value type + /*! + \return The AMF value type + */ + AMFValueType GetValueType() { return AMFUndefined; } }; //! The null value AMF type class AMFNullValue : public AMFValue { private: - //! Returns the AMF value type - /*! - \return The AMF value type - */ - AMFValueType GetValueType() { return AMFNull; } + //! Returns the AMF value type + /*! + \return The AMF value type + */ + AMFValueType GetValueType() { return AMFNull; } }; //! The false value AMF type class AMFFalseValue : public AMFValue { private: - //! Returns the AMF value type - /*! - \return The AMF value type - */ - AMFValueType GetValueType() { return AMFFalse; } + //! Returns the AMF value type + /*! + \return The AMF value type + */ + AMFValueType GetValueType() { return AMFFalse; } }; //! The true value AMF type class AMFTrueValue : public AMFValue { private: - //! Returns the AMF value type - /*! - \return The AMF value type - */ - AMFValueType GetValueType() { return AMFTrue; } + //! Returns the AMF value type + /*! + \return The AMF value type + */ + AMFValueType GetValueType() { return AMFTrue; } }; //! The integer value AMF type class AMFIntegerValue : public AMFValue { private: - uint32_t value; //!< The value of the AMF type - - //! Returns the AMF value type - /*! - \return The AMF value type - */ - AMFValueType GetValueType() { return AMFInteger; } - + uint32_t value; //!< The value of the AMF type + + //! Returns the AMF value type + /*! + \return The AMF value type + */ + AMFValueType GetValueType() { return AMFInteger; } + public: - //! Sets the integer value - /*! - \param value The value to set - */ - void SetIntegerValue(uint32_t value); - - //! Gets the integer value - /*! - \return The integer value - */ - uint32_t GetIntegerValue(); + //! Sets the integer value + /*! + \param value The value to set + */ + void SetIntegerValue(uint32_t value); + + //! Gets the integer value + /*! + \return The integer value + */ + uint32_t GetIntegerValue(); }; //! The double value AMF type class AMFDoubleValue : public AMFValue { private: - double value; //!< The value of the AMF type - - //! Returns the AMF value type - /*! - \return The AMF value type - */ - AMFValueType GetValueType() { return AMFDouble; } - + double value; //!< The value of the AMF type + + //! Returns the AMF value type + /*! + \return The AMF value type + */ + AMFValueType GetValueType() { return AMFDouble; } + public: - //! Sets the double value - /*! - \param value The value to set to - */ - void SetDoubleValue(double value); - - //! Gets the double value - /*! - \return The double value - */ - double GetDoubleValue(); + //! Sets the double value + /*! + \param value The value to set to + */ + void SetDoubleValue(double value); + + //! Gets the double value + /*! + \return The double value + */ + double GetDoubleValue(); }; //! The string value AMF type class AMFStringValue : public AMFValue { private: - std::string value; //!< The value of the AMF type - - //! Returns the AMF value type - /*! - \return The AMF value type - */ - AMFValueType GetValueType() { return AMFString; } - + std::string value; //!< The value of the AMF type + + //! Returns the AMF value type + /*! + \return The AMF value type + */ + AMFValueType GetValueType() { return AMFString; } + public: - //! Sets the string value - /*! - \param value The string value to set to - */ - void SetStringValue(const std::string& value); - - //! Gets the string value - /*! - \return The string value - */ - std::string GetStringValue(); + //! Sets the string value + /*! + \param value The string value to set to + */ + void SetStringValue(const std::string& value); + + //! Gets the string value + /*! + \return The string value + */ + std::string GetStringValue(); }; //! The XML doc value AMF type class AMFXMLDocValue : public AMFValue { private: - std::string xmlData; //!< The value of the AMF type - - //! Returns the AMF value type - /*! - \return The AMF value type - */ - AMFValueType GetValueType() { return AMFXMLDoc; } - + std::string xmlData; //!< The value of the AMF type + + //! Returns the AMF value type + /*! + \return The AMF value type + */ + AMFValueType GetValueType() { return AMFXMLDoc; } + public: - //! Sets the XML Doc value - /*! - \param value The value to set to - */ - void SetXMLDocValue(const std::string& value); - - //! Gets the XML Doc value - /*! - \return The XML Doc value - */ - std::string GetXMLDocValue(); + //! Sets the XML Doc value + /*! + \param value The value to set to + */ + void SetXMLDocValue(const std::string& value); + + //! Gets the XML Doc value + /*! + \return The XML Doc value + */ + std::string GetXMLDocValue(); }; //! The date value AMF type class AMFDateValue : public AMFValue { private: - uint64_t millisecondTimestamp; //!< The time in milliseconds since the ephoch - - //! Returns the AMF value type - /*! - \return The AMF value type - */ - AMFValueType GetValueType() { return AMFDate; } - + uint64_t millisecondTimestamp; //!< The time in milliseconds since the ephoch + + //! Returns the AMF value type + /*! + \return The AMF value type + */ + AMFValueType GetValueType() { return AMFDate; } + public: - //! Sets the date time - /*! - \param value The value to set to - */ - void SetDateValue(uint64_t value); - - //! Gets the date value - /*! - \return The date value in milliseconds since the epoch - */ - uint64_t GetDateValue(); + //! Sets the date time + /*! + \param value The value to set to + */ + void SetDateValue(uint64_t value); + + //! Gets the date value + /*! + \return The date value in milliseconds since the epoch + */ + uint64_t GetDateValue(); }; //! The array value AMF type // This object will manage it's own memory map and list. Do not delete its values. class AMFArrayValue : public AMFValue { private: - _AMFArrayMap_ associative; //!< The array map (associative part) - _AMFArrayList_ dense; //!< The array list (dense part) - - //! Returns the AMF value type - /*! - \return The AMF value type - */ - AMFValueType GetValueType() { return AMFArray; } - + _AMFArrayMap_ associative; //!< The array map (associative part) + _AMFArrayList_ dense; //!< The array list (dense part) + + //! Returns the AMF value type + /*! + \return The AMF value type + */ + AMFValueType GetValueType() { return AMFArray; } + public: - ~AMFArrayValue() override; - //! Inserts an item into the array map for a specific key - /*! - \param key The key to set - \param value The value to add - */ - void InsertValue(const std::string& key, AMFValue* value); - - //! Removes an item for a specific key - /*! - \param key The key to remove - */ - void RemoveValue(const std::string& key); - - //! Finds an AMF value - /*! - \return The AMF value if found, nullptr otherwise - */ - AMFValue* FindValue(const std::string& key); - - //! Returns where the associative iterator begins - /*! - \return Where the array map iterator begins - */ - _AMFArrayMap_::iterator GetAssociativeIteratorValueBegin(); - - //! Returns where the associative iterator ends - /*! - \return Where the array map iterator ends - */ - _AMFArrayMap_::iterator GetAssociativeIteratorValueEnd(); - - //! Pushes back a value into the array list - /*! - \param value The value to push back - */ - void PushBackValue(AMFValue* value); - - //! Pops back the last value in the array list - void PopBackValue(); - - //! Gets the count of the dense list - /*! - \return The dense list size - */ - uint32_t GetDenseValueSize(); - - //! Gets a specific value from the list for the specified index - /*! - \param index The index to get - */ - AMFValue* GetValueAt(uint32_t index); - - //! Returns where the dense iterator begins - /*! - \return Where the iterator begins - */ - _AMFArrayList_::iterator GetDenseIteratorBegin(); - - //! Returns where the dense iterator ends - /*! - \return Where the iterator ends - */ - _AMFArrayList_::iterator GetDenseIteratorEnd(); + ~AMFArrayValue() override; + //! Inserts an item into the array map for a specific key + /*! + \param key The key to set + \param value The value to add + */ + void InsertValue(const std::string& key, AMFValue* value); - //! Returns the associative map - /*! - \return The associative map - */ - _AMFArrayMap_ GetAssociativeMap() { return this->associative; }; + //! Removes an item for a specific key + /*! + \param key The key to remove + */ + void RemoveValue(const std::string& key); - //! Returns the dense array - /*! - \return The dense array - */ - _AMFArrayList_ GetDenseArray() { return this->dense; }; + //! Finds an AMF value + /*! + \return The AMF value if found, nullptr otherwise + */ + AMFValue* FindValue(const std::string& key); + + //! Returns where the associative iterator begins + /*! + \return Where the array map iterator begins + */ + _AMFArrayMap_::iterator GetAssociativeIteratorValueBegin(); + + //! Returns where the associative iterator ends + /*! + \return Where the array map iterator ends + */ + _AMFArrayMap_::iterator GetAssociativeIteratorValueEnd(); + + //! Pushes back a value into the array list + /*! + \param value The value to push back + */ + void PushBackValue(AMFValue* value); + + //! Pops back the last value in the array list + void PopBackValue(); + + //! Gets the count of the dense list + /*! + \return The dense list size + */ + uint32_t GetDenseValueSize(); + + //! Gets a specific value from the list for the specified index + /*! + \param index The index to get + */ + AMFValue* GetValueAt(uint32_t index); + + //! Returns where the dense iterator begins + /*! + \return Where the iterator begins + */ + _AMFArrayList_::iterator GetDenseIteratorBegin(); + + //! Returns where the dense iterator ends + /*! + \return Where the iterator ends + */ + _AMFArrayList_::iterator GetDenseIteratorEnd(); + + //! Returns the associative map + /*! + \return The associative map + */ + _AMFArrayMap_ GetAssociativeMap() { return this->associative; }; + + //! Returns the dense array + /*! + \return The dense array + */ + _AMFArrayList_ GetDenseArray() { return this->dense; }; }; //! The anonymous object value AMF type class AMFObjectValue : public AMFValue { private: - _AMFObjectTraits_ traits; //!< The object traits - - //! Returns the AMF value type - /*! - \return The AMF value type - */ - AMFValueType GetValueType() { return AMFObject; } - ~AMFObjectValue() override; - + _AMFObjectTraits_ traits; //!< The object traits + + //! Returns the AMF value type + /*! + \return The AMF value type + */ + AMFValueType GetValueType() { return AMFObject; } + ~AMFObjectValue() override; + public: - //! Constructor - /*! - \param traits The traits to set - */ - AMFObjectValue(std::vector> traits); - - //! Gets the object value type - /*! - \return The object value type - */ - virtual AMFObjectValueType GetObjectValueType() { return AMFObjectAnonymous; } - - //! Sets the value of a trait - /*! - \param trait The trait to set the value for - \param value The AMF value to set - */ - void SetTraitValue(const std::string& trait, AMFValue* value); - - //! Gets a trait value - /*! - \param trait The trait to get the value for - \return The trait value - */ - AMFValue* GetTraitValue(const std::string& trait); - - //! Gets the beginning of the object traits iterator - /*! - \return The AMF trait array iterator begin - */ - _AMFObjectTraits_::iterator GetTraitsIteratorBegin(); - - //! Gets the end of the object traits iterator - /*! - \return The AMF trait array iterator begin - */ - _AMFObjectTraits_::iterator GetTraitsIteratorEnd(); - - //! Gets the amount of traits - /*! - \return The amount of traits - */ - uint32_t GetTraitArrayCount(); + //! Constructor + /*! + \param traits The traits to set + */ + AMFObjectValue(std::vector> traits); + + //! Gets the object value type + /*! + \return The object value type + */ + virtual AMFObjectValueType GetObjectValueType() { return AMFObjectAnonymous; } + + //! Sets the value of a trait + /*! + \param trait The trait to set the value for + \param value The AMF value to set + */ + void SetTraitValue(const std::string& trait, AMFValue* value); + + //! Gets a trait value + /*! + \param trait The trait to get the value for + \return The trait value + */ + AMFValue* GetTraitValue(const std::string& trait); + + //! Gets the beginning of the object traits iterator + /*! + \return The AMF trait array iterator begin + */ + _AMFObjectTraits_::iterator GetTraitsIteratorBegin(); + + //! Gets the end of the object traits iterator + /*! + \return The AMF trait array iterator begin + */ + _AMFObjectTraits_::iterator GetTraitsIteratorEnd(); + + //! Gets the amount of traits + /*! + \return The amount of traits + */ + uint32_t GetTraitArrayCount(); }; diff --git a/dCommon/AMFFormat_BitStream.cpp b/dCommon/AMFFormat_BitStream.cpp index 96ccdab3..b603ba31 100644 --- a/dCommon/AMFFormat_BitStream.cpp +++ b/dCommon/AMFFormat_BitStream.cpp @@ -5,73 +5,73 @@ template<> void RakNet::BitStream::Write(AMFValue* value) { if (value != nullptr) { AMFValueType type = value->GetValueType(); - + switch (type) { - case AMFUndefined: { - AMFUndefinedValue* v = (AMFUndefinedValue*)value; - this->Write(*v); - break; - } - - case AMFNull: { - AMFNullValue* v = (AMFNullValue*)value; - this->Write(*v); - break; - } - - case AMFFalse: { - AMFFalseValue* v = (AMFFalseValue*)value; - this->Write(*v); - break; - } - - case AMFTrue: { - AMFTrueValue* v = (AMFTrueValue*)value; - this->Write(*v); - break; - } - - case AMFInteger: { - AMFIntegerValue* v = (AMFIntegerValue*)value; - this->Write(*v); - break; - } + case AMFUndefined: { + AMFUndefinedValue* v = (AMFUndefinedValue*)value; + this->Write(*v); + break; + } - case AMFDouble: { - AMFDoubleValue* v = (AMFDoubleValue*)value; - this->Write(*v); - break; - } + case AMFNull: { + AMFNullValue* v = (AMFNullValue*)value; + this->Write(*v); + break; + } - case AMFString: { - AMFStringValue* v = (AMFStringValue*)value; - this->Write(*v); - break; - } - - case AMFXMLDoc: { - AMFXMLDocValue* v = (AMFXMLDocValue*)value; - this->Write(*v); - break; - } - - case AMFDate: { - AMFDateValue* v = (AMFDateValue*)value; - this->Write(*v); - break; - } - - case AMFArray: { - this->Write((AMFArrayValue*)value); - break; - } + case AMFFalse: { + AMFFalseValue* v = (AMFFalseValue*)value; + this->Write(*v); + break; + } + + case AMFTrue: { + AMFTrueValue* v = (AMFTrueValue*)value; + this->Write(*v); + break; + } + + case AMFInteger: { + AMFIntegerValue* v = (AMFIntegerValue*)value; + this->Write(*v); + break; + } + + case AMFDouble: { + AMFDoubleValue* v = (AMFDoubleValue*)value; + this->Write(*v); + break; + } + + case AMFString: { + AMFStringValue* v = (AMFStringValue*)value; + this->Write(*v); + break; + } + + case AMFXMLDoc: { + AMFXMLDocValue* v = (AMFXMLDocValue*)value; + this->Write(*v); + break; + } + + case AMFDate: { + AMFDateValue* v = (AMFDateValue*)value; + this->Write(*v); + break; + } + + case AMFArray: { + this->Write((AMFArrayValue*)value); + break; + } } } } -/** +/** * A private function to write an value to a RakNet::BitStream - * RakNet writes in the correct byte order - do not reverse this. + * RakNet writes in the correct byte order - do not reverse this. */ void WriteUInt29(RakNet::BitStream* bs, uint32_t v) { unsigned char b4 = (unsigned char)v; @@ -87,70 +87,70 @@ void WriteUInt29(RakNet::BitStream* bs, uint32_t v) { b2 = ((unsigned char)(v)) | 0x80; bs->Write(b2); } - + bs->Write(b3); } } else { unsigned char b1; unsigned char b2; unsigned char b3; - + v = v >> 8; b3 = ((unsigned char)(v)) | 0x80; v = v >> 7; b2 = ((unsigned char)(v)) | 0x80; v = v >> 7; b1 = ((unsigned char)(v)) | 0x80; - + bs->Write(b1); bs->Write(b2); bs->Write(b3); } - + bs->Write(b4); } -/** +/** * Writes a flag number to a RakNet::BitStream - * RakNet writes in the correct byte order - do not reverse this. + * RakNet writes in the correct byte order - do not reverse this. */ void WriteFlagNumber(RakNet::BitStream* bs, uint32_t v) { v = (v << 1) | 0x01; WriteUInt29(bs, v); } -/** +/** * Writes an AMFString to a RakNet::BitStream - * - * RakNet writes in the correct byte order - do not reverse this. + * + * RakNet writes in the correct byte order - do not reverse this. */ void WriteAMFString(RakNet::BitStream* bs, const std::string& str) { WriteFlagNumber(bs, (uint32_t)str.size()); bs->Write(str.c_str(), (uint32_t)str.size()); } -/** +/** * Writes an U16 to a bitstream - * - * RakNet writes in the correct byte order - do not reverse this. + * + * RakNet writes in the correct byte order - do not reverse this. */ void WriteAMFU16(RakNet::BitStream* bs, uint16_t value) { bs->Write(value); } -/** +/** * Writes an U32 to a bitstream - * - * RakNet writes in the correct byte order - do not reverse this. + * + * RakNet writes in the correct byte order - do not reverse this. */ void WriteAMFU32(RakNet::BitStream* bs, uint32_t value) { bs->Write(value); } -/** +/** * Writes an U64 to a bitstream - * - * RakNet writes in the correct byte order - do not reverse this. + * + * RakNet writes in the correct byte order - do not reverse this. */ void WriteAMFU64(RakNet::BitStream* bs, uint64_t value) { bs->Write(value); @@ -193,7 +193,7 @@ template<> void RakNet::BitStream::Write(AMFDoubleValue value) { this->Write(AMFDouble); double d = value.GetDoubleValue(); - WriteAMFU64(this, *((unsigned long long*)&d)); + WriteAMFU64(this, *((unsigned long long*) & d)); } // Writes an AMFStringValue to BitStream @@ -226,22 +226,22 @@ void RakNet::BitStream::Write(AMFArrayValue* value) { this->Write(AMFArray); uint32_t denseSize = value->GetDenseValueSize(); WriteFlagNumber(this, denseSize); - + _AMFArrayMap_::iterator it = value->GetAssociativeIteratorValueBegin(); _AMFArrayMap_::iterator end = value->GetAssociativeIteratorValueEnd(); - + while (it != end) { WriteAMFString(this, it->first); this->Write(it->second); it++; } - + this->Write(AMFNull); - + if (denseSize > 0) { _AMFArrayList_::iterator it2 = value->GetDenseIteratorBegin(); _AMFArrayList_::iterator end2 = value->GetDenseIteratorEnd(); - + while (it2 != end2) { this->Write(*it2); it2++; diff --git a/dCommon/AMFFormat_BitStream.h b/dCommon/AMFFormat_BitStream.h index ff72a180..caa49337 100644 --- a/dCommon/AMFFormat_BitStream.h +++ b/dCommon/AMFFormat_BitStream.h @@ -11,7 +11,7 @@ \brief A class that implements native writing of AMF values to RakNet::BitStream */ -// We are using the RakNet namespace + // We are using the RakNet namespace namespace RakNet { //! Writes an AMFValue pointer to a RakNet::BitStream /*! @@ -19,70 +19,70 @@ namespace RakNet { */ template <> void RakNet::BitStream::Write(AMFValue* value); - + //! Writes an AMFUndefinedValue to a RakNet::BitStream /*! \param value The value to write */ template <> void RakNet::BitStream::Write(AMFUndefinedValue value); - + //! Writes an AMFNullValue to a RakNet::BitStream /*! \param value The value to write */ template <> void RakNet::BitStream::Write(AMFNullValue value); - + //! Writes an AMFFalseValue to a RakNet::BitStream /*! \param value The value to write */ template <> void RakNet::BitStream::Write(AMFFalseValue value); - + //! Writes an AMFTrueValue to a RakNet::BitStream /*! \param value The value to write */ template <> void RakNet::BitStream::Write(AMFTrueValue value); - + //! Writes an AMFIntegerValue to a RakNet::BitStream /*! \param value The value to write */ template <> void RakNet::BitStream::Write(AMFIntegerValue value); - + //! Writes an AMFDoubleValue to a RakNet::BitStream /*! \param value The value to write */ template <> void RakNet::BitStream::Write(AMFDoubleValue value); - + //! Writes an AMFStringValue to a RakNet::BitStream /*! \param value The value to write */ template <> void RakNet::BitStream::Write(AMFStringValue value); - + //! Writes an AMFXMLDocValue to a RakNet::BitStream /*! \param value The value to write */ template <> void RakNet::BitStream::Write(AMFXMLDocValue value); - + //! Writes an AMFDateValue to a RakNet::BitStream /*! \param value The value to write */ template <> void RakNet::BitStream::Write(AMFDateValue value); - + //! Writes an AMFArrayValue to a RakNet::BitStream /*! \param value The value to write diff --git a/dCommon/BinaryIO.cpp b/dCommon/BinaryIO.cpp index 8cad23a6..7cb18331 100644 --- a/dCommon/BinaryIO.cpp +++ b/dCommon/BinaryIO.cpp @@ -10,7 +10,7 @@ void BinaryIO::WriteString(const std::string& stringToWrite, std::ofstream& outs } //For reading null-terminated strings -std::string BinaryIO::ReadString(std::ifstream & instream) { +std::string BinaryIO::ReadString(std::ifstream& instream) { std::string toReturn; char buffer; @@ -37,7 +37,7 @@ std::string BinaryIO::ReadString(std::ifstream& instream, size_t size) { return toReturn; } -std::string BinaryIO::ReadWString(std::ifstream & instream) { +std::string BinaryIO::ReadWString(std::ifstream& instream) { size_t size; BinaryRead(instream, size); //toReturn.resize(size); diff --git a/dCommon/BinaryIO.h b/dCommon/BinaryIO.h index 0c459f02..1f9aaefd 100644 --- a/dCommon/BinaryIO.h +++ b/dCommon/BinaryIO.h @@ -9,15 +9,15 @@ namespace BinaryIO { } template - std::istream & BinaryRead(std::istream& stream, T& value) { - if (!stream.good()) + std::istream& BinaryRead(std::istream& stream, T& value) { + if (!stream.good()) printf("bla"); return stream.read(reinterpret_cast(&value), sizeof(T)); } void WriteString(const std::string& stringToWrite, std::ofstream& outstream); - std::string ReadString(std::ifstream & instream); + std::string ReadString(std::ifstream& instream); std::string ReadString(std::ifstream& instream, size_t size); std::string ReadWString(std::ifstream& instream); diff --git a/dCommon/Diagnostics.cpp b/dCommon/Diagnostics.cpp index 5963400d..bfde2d9a 100644 --- a/dCommon/Diagnostics.cpp +++ b/dCommon/Diagnostics.cpp @@ -10,51 +10,51 @@ #include "dLogger.h" void make_minidump(EXCEPTION_POINTERS* e) { - auto hDbgHelp = LoadLibraryA("dbghelp"); - if (hDbgHelp == nullptr) - return; - auto pMiniDumpWriteDump = (decltype(&MiniDumpWriteDump))GetProcAddress(hDbgHelp, "MiniDumpWriteDump"); - if (pMiniDumpWriteDump == nullptr) - return; + auto hDbgHelp = LoadLibraryA("dbghelp"); + if (hDbgHelp == nullptr) + return; + auto pMiniDumpWriteDump = (decltype(&MiniDumpWriteDump))GetProcAddress(hDbgHelp, "MiniDumpWriteDump"); + if (pMiniDumpWriteDump == nullptr) + return; - char name[MAX_PATH]; - { - auto nameEnd = name + GetModuleFileNameA(GetModuleHandleA(0), name, MAX_PATH); - SYSTEMTIME t; - GetSystemTime(&t); - wsprintfA(nameEnd - strlen(".exe"), - "_%4d%02d%02d_%02d%02d%02d.dmp", - t.wYear, t.wMonth, t.wDay, t.wHour, t.wMinute, t.wSecond); - } + char name[MAX_PATH]; + { + auto nameEnd = name + GetModuleFileNameA(GetModuleHandleA(0), name, MAX_PATH); + SYSTEMTIME t; + GetSystemTime(&t); + wsprintfA(nameEnd - strlen(".exe"), + "_%4d%02d%02d_%02d%02d%02d.dmp", + t.wYear, t.wMonth, t.wDay, t.wHour, t.wMinute, t.wSecond); + } - auto hFile = CreateFileA(name, GENERIC_WRITE, FILE_SHARE_READ, 0, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, 0); - if (hFile == INVALID_HANDLE_VALUE) - return; + auto hFile = CreateFileA(name, GENERIC_WRITE, FILE_SHARE_READ, 0, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, 0); + if (hFile == INVALID_HANDLE_VALUE) + return; - MINIDUMP_EXCEPTION_INFORMATION exceptionInfo; - exceptionInfo.ThreadId = GetCurrentThreadId(); - exceptionInfo.ExceptionPointers = e; - exceptionInfo.ClientPointers = FALSE; + MINIDUMP_EXCEPTION_INFORMATION exceptionInfo; + exceptionInfo.ThreadId = GetCurrentThreadId(); + exceptionInfo.ExceptionPointers = e; + exceptionInfo.ClientPointers = FALSE; - auto dumped = pMiniDumpWriteDump( - GetCurrentProcess(), - GetCurrentProcessId(), - hFile, - MINIDUMP_TYPE(MiniDumpWithIndirectlyReferencedMemory | MiniDumpScanMemory), - e ? &exceptionInfo : nullptr, - nullptr, - nullptr); + auto dumped = pMiniDumpWriteDump( + GetCurrentProcess(), + GetCurrentProcessId(), + hFile, + MINIDUMP_TYPE(MiniDumpWithIndirectlyReferencedMemory | MiniDumpScanMemory), + e ? &exceptionInfo : nullptr, + nullptr, + nullptr); - CloseHandle(hFile); + CloseHandle(hFile); - return; + return; } LONG CALLBACK unhandled_handler(EXCEPTION_POINTERS* e) { - make_minidump(e); - if (Game::logger) - Game::logger->Flush(); // Flush our log if we have one, before exiting. - return EXCEPTION_CONTINUE_SEARCH; + make_minidump(e); + if (Game::logger) + Game::logger->Flush(); // Flush our log if we have one, before exiting. + return EXCEPTION_CONTINUE_SEARCH; } #endif @@ -75,146 +75,146 @@ LONG CALLBACK unhandled_handler(EXCEPTION_POINTERS* e) { #include struct bt_ctx { - struct backtrace_state* state; - int error; + struct backtrace_state* state; + int error; }; static inline void Bt(struct backtrace_state* state) { - std::string fileName = Diagnostics::GetOutDirectory() + "crash_" + Diagnostics::GetProcessName() + "_" + std::to_string(getpid()) + ".log"; - FILE* file = fopen(fileName.c_str(), "w+"); - if (file != nullptr) { - backtrace_print(state, 2, file); - fclose(file); - } + std::string fileName = Diagnostics::GetOutDirectory() + "crash_" + Diagnostics::GetProcessName() + "_" + std::to_string(getpid()) + ".log"; + FILE* file = fopen(fileName.c_str(), "w+"); + if (file != nullptr) { + backtrace_print(state, 2, file); + fclose(file); + } - backtrace_print(state, 2, stdout); + backtrace_print(state, 2, stdout); } static void ErrorCallback(void* data, const char* msg, int errnum) { - auto* ctx = (struct bt_ctx*)data; - fprintf(stderr, "ERROR: %s (%d)", msg, errnum); - ctx->error = 1; + auto* ctx = (struct bt_ctx*)data; + fprintf(stderr, "ERROR: %s (%d)", msg, errnum); + ctx->error = 1; - std::string fileName = Diagnostics::GetOutDirectory() + "crash_" + Diagnostics::GetProcessName() + "_" + std::to_string(getpid()) + ".log"; - FILE* file = fopen(fileName.c_str(), "w+"); - if (file != nullptr) { - fprintf(file, "ERROR: %s (%d)", msg, errnum); - fclose(file); - } + std::string fileName = Diagnostics::GetOutDirectory() + "crash_" + Diagnostics::GetProcessName() + "_" + std::to_string(getpid()) + ".log"; + FILE* file = fopen(fileName.c_str(), "w+"); + if (file != nullptr) { + fprintf(file, "ERROR: %s (%d)", msg, errnum); + fclose(file); + } } #endif #include "Type.h" void GenerateDump() { - std::string cmd = "sudo gcore " + std::to_string(getpid()); - system(cmd.c_str()); + std::string cmd = "sudo gcore " + std::to_string(getpid()); + system(cmd.c_str()); } void CatchUnhandled(int sig) { #ifndef __include_backtrace__ - if (Diagnostics::GetProduceMemoryDump()) { - GenerateDump(); - } + if (Diagnostics::GetProduceMemoryDump()) { + GenerateDump(); + } - void* array[10]; - size_t size; + void* array[10]; + size_t size; - // get void*'s for all entries on the stack - size = backtrace(array, 10); + // get void*'s for all entries on the stack + size = backtrace(array, 10); - printf("Fatal error %i\nStacktrace:\n", sig); + printf("Fatal error %i\nStacktrace:\n", sig); #if defined(__GNUG__) and defined(__dynamic) - // Loop through the returned addresses, and get the symbols to be demangled - char** strings = backtrace_symbols(array, size); + // Loop through the returned addresses, and get the symbols to be demangled + char** strings = backtrace_symbols(array, size); - // Print the stack trace - for (size_t i = 0; i < size; i++) { - // Take a string like './WorldServer(_ZN19SlashCommandHandler17HandleChatCommandERKSbIDsSt11char_traitsIDsESaIDsEEP6EntityRK13SystemAddress+0x6187) [0x55869c44ecf7]' and extract the function name - std::string functionName = strings[i]; - std::string::size_type start = functionName.find('('); - std::string::size_type end = functionName.find('+'); - if (start != std::string::npos && end != std::string::npos) { - std::string demangled = functionName.substr(start + 1, end - start - 1); + // Print the stack trace + for (size_t i = 0; i < size; i++) { + // Take a string like './WorldServer(_ZN19SlashCommandHandler17HandleChatCommandERKSbIDsSt11char_traitsIDsESaIDsEEP6EntityRK13SystemAddress+0x6187) [0x55869c44ecf7]' and extract the function name + std::string functionName = strings[i]; + std::string::size_type start = functionName.find('('); + std::string::size_type end = functionName.find('+'); + if (start != std::string::npos && end != std::string::npos) { + std::string demangled = functionName.substr(start + 1, end - start - 1); - demangled = demangle(functionName.c_str()); + demangled = demangle(functionName.c_str()); - if (demangled.empty()) { - printf("[%02d] %s\n", i, demangled.c_str()); - } else { - printf("[%02d] %s\n", i, functionName.c_str()); - } - } else { - printf("[%02d] %s\n", i, functionName.c_str()); - } - } + if (demangled.empty()) { + printf("[%02d] %s\n", i, demangled.c_str()); + } else { + printf("[%02d] %s\n", i, functionName.c_str()); + } + } else { + printf("[%02d] %s\n", i, functionName.c_str()); + } + } #else - backtrace_symbols_fd(array, size, STDOUT_FILENO); + backtrace_symbols_fd(array, size, STDOUT_FILENO); #endif - std::string fileName = Diagnostics::GetOutDirectory() + "crash_" + Diagnostics::GetProcessName() + "_" + std::to_string(getpid()) + ".log"; - FILE* file = fopen(fileName.c_str(), "w+"); - if (file != NULL) { - // print out all the frames to stderr - fprintf(file, "Error: signal %d:\n", sig); - backtrace_symbols_fd(array, size, fileno(file)); - fclose(file); - } + std::string fileName = Diagnostics::GetOutDirectory() + "crash_" + Diagnostics::GetProcessName() + "_" + std::to_string(getpid()) + ".log"; + FILE* file = fopen(fileName.c_str(), "w+"); + if (file != NULL) { + // print out all the frames to stderr + fprintf(file, "Error: signal %d:\n", sig); + backtrace_symbols_fd(array, size, fileno(file)); + fclose(file); + } #else - struct backtrace_state* state = backtrace_create_state( - Diagnostics::GetProcessFileName().c_str(), - BACKTRACE_SUPPORTS_THREADS, - ErrorCallback, - nullptr); + struct backtrace_state* state = backtrace_create_state( + Diagnostics::GetProcessFileName().c_str(), + BACKTRACE_SUPPORTS_THREADS, + ErrorCallback, + nullptr); - struct bt_ctx ctx = {state, 0}; - Bt(state); + struct bt_ctx ctx = { state, 0 }; + Bt(state); #endif - exit(EXIT_FAILURE); + exit(EXIT_FAILURE); } void CritErrHdlr(int sig_num, siginfo_t* info, void* ucontext) { - CatchUnhandled(sig_num); + CatchUnhandled(sig_num); } void OnTerminate() { - CatchUnhandled(-1); + CatchUnhandled(-1); } void MakeBacktrace() { - struct sigaction sigact; + struct sigaction sigact; - sigact.sa_sigaction = CritErrHdlr; - sigact.sa_flags = SA_RESTART | SA_SIGINFO; + sigact.sa_sigaction = CritErrHdlr; + sigact.sa_flags = SA_RESTART | SA_SIGINFO; - if (sigaction(SIGSEGV, &sigact, (struct sigaction*)nullptr) != 0 || - sigaction(SIGFPE, &sigact, (struct sigaction*)nullptr) != 0 || - sigaction(SIGABRT, &sigact, (struct sigaction*)nullptr) != 0 || - sigaction(SIGILL, &sigact, (struct sigaction*)nullptr) != 0) { - fprintf(stderr, "error setting signal handler for %d (%s)\n", - SIGSEGV, - strsignal(SIGSEGV)); + if (sigaction(SIGSEGV, &sigact, (struct sigaction*)nullptr) != 0 || + sigaction(SIGFPE, &sigact, (struct sigaction*)nullptr) != 0 || + sigaction(SIGABRT, &sigact, (struct sigaction*)nullptr) != 0 || + sigaction(SIGILL, &sigact, (struct sigaction*)nullptr) != 0) { + fprintf(stderr, "error setting signal handler for %d (%s)\n", + SIGSEGV, + strsignal(SIGSEGV)); - exit(EXIT_FAILURE); - } + exit(EXIT_FAILURE); + } - std::set_terminate(OnTerminate); + std::set_terminate(OnTerminate); } #endif void Diagnostics::Initialize() { #ifdef _WIN32 - SetUnhandledExceptionFilter(unhandled_handler); + SetUnhandledExceptionFilter(unhandled_handler); #elif defined(__linux__) //&& !defined(__clang__) - MakeBacktrace(); + MakeBacktrace(); #else - fprintf(stderr, "Diagnostics not supported on this platform.\n"); + fprintf(stderr, "Diagnostics not supported on this platform.\n"); #endif } @@ -224,33 +224,33 @@ std::string Diagnostics::m_OutDirectory{}; bool Diagnostics::m_ProduceMemoryDump{}; void Diagnostics::SetProcessName(const std::string& name) { - m_ProcessName = name; + m_ProcessName = name; } void Diagnostics::SetProcessFileName(const std::string& name) { - m_ProcessFileName = name; + m_ProcessFileName = name; } void Diagnostics::SetOutDirectory(const std::string& path) { - m_OutDirectory = path; + m_OutDirectory = path; } void Diagnostics::SetProduceMemoryDump(bool value) { - m_ProduceMemoryDump = value; + m_ProduceMemoryDump = value; } const std::string& Diagnostics::GetProcessName() { - return m_ProcessName; + return m_ProcessName; } const std::string& Diagnostics::GetProcessFileName() { - return m_ProcessFileName; + return m_ProcessFileName; } const std::string& Diagnostics::GetOutDirectory() { - return m_OutDirectory; + return m_OutDirectory; } bool Diagnostics::GetProduceMemoryDump() { - return m_ProduceMemoryDump; + return m_ProduceMemoryDump; } diff --git a/dCommon/Diagnostics.h b/dCommon/Diagnostics.h index 41b7d177..fb6cc1a0 100644 --- a/dCommon/Diagnostics.h +++ b/dCommon/Diagnostics.h @@ -5,27 +5,27 @@ class Diagnostics { public: - static void Initialize(); + static void Initialize(); - static void SetProcessName(const std::string& name); + static void SetProcessName(const std::string& name); - static void SetProcessFileName(const std::string& name); + static void SetProcessFileName(const std::string& name); - static void SetOutDirectory(const std::string& path); + static void SetOutDirectory(const std::string& path); - static void SetProduceMemoryDump(bool value); + static void SetProduceMemoryDump(bool value); - static const std::string& GetProcessName(); + static const std::string& GetProcessName(); - static const std::string& GetProcessFileName(); + static const std::string& GetProcessFileName(); - static const std::string& GetOutDirectory(); + static const std::string& GetOutDirectory(); - static bool GetProduceMemoryDump(); + static bool GetProduceMemoryDump(); private: - static std::string m_ProcessName; - static std::string m_ProcessFileName; - static std::string m_OutDirectory; - static bool m_ProduceMemoryDump; + static std::string m_ProcessName; + static std::string m_ProcessFileName; + static std::string m_OutDirectory; + static bool m_ProduceMemoryDump; }; diff --git a/dCommon/Game.h b/dCommon/Game.h index 912baeb7..f4862602 100644 --- a/dCommon/Game.h +++ b/dCommon/Game.h @@ -23,4 +23,4 @@ namespace Game { extern std::mt19937 randomEngine; extern RakPeerInterface* chatServer; extern SystemAddress chatSysAddr; -} \ No newline at end of file +} diff --git a/dCommon/GeneralUtils.cpp b/dCommon/GeneralUtils.cpp index eafa6a3b..4a6c4739 100644 --- a/dCommon/GeneralUtils.cpp +++ b/dCommon/GeneralUtils.cpp @@ -7,272 +7,265 @@ template inline size_t MinSize(size_t size, const std::basic_string_view& string) { - if (size == size_t(-1) || size > string.size()) { - return string.size(); - } else { - return size; - } + if (size == size_t(-1) || size > string.size()) { + return string.size(); + } else { + return size; + } } inline bool IsLeadSurrogate(char16_t c) { - return (0xD800 <= c) && (c <= 0xDBFF); + return (0xD800 <= c) && (c <= 0xDBFF); } inline bool IsTrailSurrogate(char16_t c) { - return (0xDC00 <= c) && (c <= 0xDFFF); + return (0xDC00 <= c) && (c <= 0xDFFF); } inline void PushUTF8CodePoint(std::string& ret, char32_t cp) { - if (cp <= 0x007F) { - ret.push_back(static_cast(cp)); - } else if (cp <= 0x07FF) { - ret.push_back(0xC0 | (cp >> 6)); - ret.push_back(0x80 | (cp & 0x3F)); - } else if (cp <= 0xFFFF) { - ret.push_back(0xE0 | (cp >> 12)); - ret.push_back(0x80 | ((cp >> 6) & 0x3F)); - ret.push_back(0x80 | (cp & 0x3F)); - } else if (cp <= 0x10FFFF) { - ret.push_back(0xF0 | (cp >> 18)); - ret.push_back(0x80 | ((cp >> 12) & 0x3F)); - ret.push_back(0x80 | ((cp >> 6) & 0x3F)); - ret.push_back(0x80 | (cp & 0x3F)); - } else { - assert(false); - } + if (cp <= 0x007F) { + ret.push_back(static_cast(cp)); + } else if (cp <= 0x07FF) { + ret.push_back(0xC0 | (cp >> 6)); + ret.push_back(0x80 | (cp & 0x3F)); + } else if (cp <= 0xFFFF) { + ret.push_back(0xE0 | (cp >> 12)); + ret.push_back(0x80 | ((cp >> 6) & 0x3F)); + ret.push_back(0x80 | (cp & 0x3F)); + } else if (cp <= 0x10FFFF) { + ret.push_back(0xF0 | (cp >> 18)); + ret.push_back(0x80 | ((cp >> 12) & 0x3F)); + ret.push_back(0x80 | ((cp >> 6) & 0x3F)); + ret.push_back(0x80 | (cp & 0x3F)); + } else { + assert(false); + } } constexpr const char16_t REPLACEMENT_CHARACTER = 0xFFFD; bool _IsSuffixChar(uint8_t c) { - return (c & 0xC0) == 0x80; + return (c & 0xC0) == 0x80; } bool GeneralUtils::_NextUTF8Char(std::string_view& slice, uint32_t& out) { - size_t rem = slice.length(); - const uint8_t* bytes = (const uint8_t*) &slice.front(); - if (rem > 0) { - uint8_t first = bytes[0]; - if (first < 0x80) { // 1 byte character - out = static_cast(first & 0x7F); - slice.remove_prefix(1); - return true; - } else if (first < 0xC0) { - // middle byte, not valid at start, fall through - } else if (first < 0xE0) { // two byte character - if (rem > 1) { - uint8_t second = bytes[1]; - if (_IsSuffixChar(second)) { - out = (static_cast(first & 0x1F) << 6) - + static_cast(second & 0x3F); - slice.remove_prefix(2); - return true; - } - } - } else if (first < 0xF0) { // three byte character - if (rem > 2) { - uint8_t second = bytes[1]; - uint8_t third = bytes[2]; - if (_IsSuffixChar(second) && _IsSuffixChar(third)) { - out = (static_cast(first & 0x0F) << 12) - + (static_cast(second & 0x3F) << 6) - + static_cast(third & 0x3F); - slice.remove_prefix(3); - return true; - } - } - } else if (first < 0xF8) { // four byte character - if (rem > 3) { - uint8_t second = bytes[1]; - uint8_t third = bytes[2]; - uint8_t fourth = bytes[3]; - if (_IsSuffixChar(second) && _IsSuffixChar(third) && _IsSuffixChar(fourth)) { - out = (static_cast(first & 0x07) << 18) - + (static_cast(second & 0x3F) << 12) - + (static_cast(third & 0x3F) << 6) - + static_cast(fourth & 0x3F); - slice.remove_prefix(4); - return true; - } - } - } - out = static_cast(REPLACEMENT_CHARACTER); - slice.remove_prefix(1); - return true; - } - return false; + size_t rem = slice.length(); + const uint8_t* bytes = (const uint8_t*)&slice.front(); + if (rem > 0) { + uint8_t first = bytes[0]; + if (first < 0x80) { // 1 byte character + out = static_cast(first & 0x7F); + slice.remove_prefix(1); + return true; + } else if (first < 0xC0) { + // middle byte, not valid at start, fall through + } else if (first < 0xE0) { // two byte character + if (rem > 1) { + uint8_t second = bytes[1]; + if (_IsSuffixChar(second)) { + out = (static_cast(first & 0x1F) << 6) + + static_cast(second & 0x3F); + slice.remove_prefix(2); + return true; + } + } + } else if (first < 0xF0) { // three byte character + if (rem > 2) { + uint8_t second = bytes[1]; + uint8_t third = bytes[2]; + if (_IsSuffixChar(second) && _IsSuffixChar(third)) { + out = (static_cast(first & 0x0F) << 12) + + (static_cast(second & 0x3F) << 6) + + static_cast(third & 0x3F); + slice.remove_prefix(3); + return true; + } + } + } else if (first < 0xF8) { // four byte character + if (rem > 3) { + uint8_t second = bytes[1]; + uint8_t third = bytes[2]; + uint8_t fourth = bytes[3]; + if (_IsSuffixChar(second) && _IsSuffixChar(third) && _IsSuffixChar(fourth)) { + out = (static_cast(first & 0x07) << 18) + + (static_cast(second & 0x3F) << 12) + + (static_cast(third & 0x3F) << 6) + + static_cast(fourth & 0x3F); + slice.remove_prefix(4); + return true; + } + } + } + out = static_cast(REPLACEMENT_CHARACTER); + slice.remove_prefix(1); + return true; + } + return false; } /// See bool PushUTF16CodePoint(std::u16string& output, uint32_t U, size_t size) { - if (output.length() >= size) return false; - if (U < 0x10000) { - // If U < 0x10000, encode U as a 16-bit unsigned integer and terminate. - output.push_back(static_cast(U)); - return true; - } else if (U > 0x10FFFF) { - output.push_back(REPLACEMENT_CHARACTER); - return true; - } else if (output.length() + 1 < size) { - // Let U' = U - 0x10000. Because U is less than or equal to 0x10FFFF, - // U' must be less than or equal to 0xFFFFF. That is, U' can be - // represented in 20 bits. - uint32_t Ut = U - 0x10000; + if (output.length() >= size) return false; + if (U < 0x10000) { + // If U < 0x10000, encode U as a 16-bit unsigned integer and terminate. + output.push_back(static_cast(U)); + return true; + } else if (U > 0x10FFFF) { + output.push_back(REPLACEMENT_CHARACTER); + return true; + } else if (output.length() + 1 < size) { + // Let U' = U - 0x10000. Because U is less than or equal to 0x10FFFF, + // U' must be less than or equal to 0xFFFFF. That is, U' can be + // represented in 20 bits. + uint32_t Ut = U - 0x10000; - // Initialize two 16-bit unsigned integers, W1 and W2, to 0xD800 and - // 0xDC00, respectively. These integers each have 10 bits free to - // encode the character value, for a total of 20 bits. - uint16_t W1 = 0xD800; - uint16_t W2 = 0xDC00; + // Initialize two 16-bit unsigned integers, W1 and W2, to 0xD800 and + // 0xDC00, respectively. These integers each have 10 bits free to + // encode the character value, for a total of 20 bits. + uint16_t W1 = 0xD800; + uint16_t W2 = 0xDC00; - // Assign the 10 high-order bits of the 20-bit U' to the 10 low-order - // bits of W1 and the 10 low-order bits of U' to the 10 low-order - // bits of W2. - W1 += static_cast((Ut & 0x3FC00) >> 10); - W2 += static_cast((Ut & 0x3FF) >> 0); + // Assign the 10 high-order bits of the 20-bit U' to the 10 low-order + // bits of W1 and the 10 low-order bits of U' to the 10 low-order + // bits of W2. + W1 += static_cast((Ut & 0x3FC00) >> 10); + W2 += static_cast((Ut & 0x3FF) >> 0); - // Terminate. - output.push_back(W1); // high surrogate - output.push_back(W2); // low surrogate - return true; - } else return false; + // Terminate. + output.push_back(W1); // high surrogate + output.push_back(W2); // low surrogate + return true; + } else return false; } std::u16string GeneralUtils::UTF8ToUTF16(const std::string_view& string, size_t size) { - size_t newSize = MinSize(size, string); - std::u16string output; - output.reserve(newSize); - std::string_view iterator = string; + size_t newSize = MinSize(size, string); + std::u16string output; + output.reserve(newSize); + std::string_view iterator = string; - uint32_t c; - while (_NextUTF8Char(iterator, c) && PushUTF16CodePoint(output, c, size)) {} - return output; + uint32_t c; + while (_NextUTF8Char(iterator, c) && PushUTF16CodePoint(output, c, size)) {} + return output; } //! Converts an std::string (ASCII) to UCS-2 / UTF-16 std::u16string GeneralUtils::ASCIIToUTF16(const std::string_view& string, size_t size) { - size_t newSize = MinSize(size, string); - std::u16string ret; - ret.reserve(newSize); + size_t newSize = MinSize(size, string); + std::u16string ret; + ret.reserve(newSize); - for (size_t i = 0; i < newSize; i++) { - char c = string[i]; - // Note: both 7-bit ascii characters and REPLACEMENT_CHARACTER fit in one char16_t - ret.push_back((c > 0 && c <= 127) ? static_cast(c) : REPLACEMENT_CHARACTER); - } + for (size_t i = 0; i < newSize; i++) { + char c = string[i]; + // Note: both 7-bit ascii characters and REPLACEMENT_CHARACTER fit in one char16_t + ret.push_back((c > 0 && c <= 127) ? static_cast(c) : REPLACEMENT_CHARACTER); + } - return ret; + return ret; } //! Converts a (potentially-ill-formed) UTF-16 string to UTF-8 //! See: std::string GeneralUtils::UTF16ToWTF8(const std::u16string_view& string, size_t size) { - size_t newSize = MinSize(size, string); - std::string ret; - ret.reserve(newSize); + size_t newSize = MinSize(size, string); + std::string ret; + ret.reserve(newSize); - for (size_t i = 0; i < newSize; i++) { - char16_t u = string[i]; - if (IsLeadSurrogate(u) && (i + 1) < newSize) { - char16_t next = string[i + 1]; - if (IsTrailSurrogate(next)) { - i += 1; - char32_t cp = 0x10000 - + ((static_cast(u) - 0xD800) << 10) - + (static_cast(next) - 0xDC00); - PushUTF8CodePoint(ret, cp); - } else { - PushUTF8CodePoint(ret, u); - } - } else { - PushUTF8CodePoint(ret, u); - } - } + for (size_t i = 0; i < newSize; i++) { + char16_t u = string[i]; + if (IsLeadSurrogate(u) && (i + 1) < newSize) { + char16_t next = string[i + 1]; + if (IsTrailSurrogate(next)) { + i += 1; + char32_t cp = 0x10000 + + ((static_cast(u) - 0xD800) << 10) + + (static_cast(next) - 0xDC00); + PushUTF8CodePoint(ret, cp); + } else { + PushUTF8CodePoint(ret, u); + } + } else { + PushUTF8CodePoint(ret, u); + } + } - return ret; + return ret; } bool GeneralUtils::CaseInsensitiveStringCompare(const std::string& a, const std::string& b) { - return std::equal(a.begin(), a.end (), b.begin(), b.end(),[](char a, char b) { return tolower(a) == tolower(b); }); + return std::equal(a.begin(), a.end(), b.begin(), b.end(), [](char a, char b) { return tolower(a) == tolower(b); }); } // MARK: Bits //! Sets a specific bit in a signed 64-bit integer int64_t GeneralUtils::SetBit(int64_t value, uint32_t index) { - return value |= 1ULL << index; + return value |= 1ULL << index; } //! Clears a specific bit in a signed 64-bit integer int64_t GeneralUtils::ClearBit(int64_t value, uint32_t index) { - return value &= ~(1ULL << index); + return value &= ~(1ULL << index); } //! Checks a specific bit in a signed 64-bit integer bool GeneralUtils::CheckBit(int64_t value, uint32_t index) { - return value & (1ULL << index); + return value & (1ULL << index); } bool GeneralUtils::ReplaceInString(std::string& str, const std::string& from, const std::string& to) { - size_t start_pos = str.find(from); - if(start_pos == std::string::npos) - return false; - str.replace(start_pos, from.length(), to); - return true; + size_t start_pos = str.find(from); + if (start_pos == std::string::npos) + return false; + str.replace(start_pos, from.length(), to); + return true; } -std::vector GeneralUtils::SplitString(std::wstring& str, wchar_t delimiter) -{ - std::vector vector = std::vector(); - std::wstring current; +std::vector GeneralUtils::SplitString(std::wstring& str, wchar_t delimiter) { + std::vector vector = std::vector(); + std::wstring current; - for (const auto& c : str) { - if (c == delimiter) { - vector.push_back(current); - current = L""; - } else { - current += c; - } - } + for (const auto& c : str) { + if (c == delimiter) { + vector.push_back(current); + current = L""; + } else { + current += c; + } + } - vector.push_back(current); - return vector; + vector.push_back(current); + return vector; } -std::vector GeneralUtils::SplitString(std::u16string& str, char16_t delimiter) -{ - std::vector vector = std::vector(); - std::u16string current; +std::vector GeneralUtils::SplitString(std::u16string& str, char16_t delimiter) { + std::vector vector = std::vector(); + std::u16string current; - for (const auto& c : str) { - if (c == delimiter) { - vector.push_back(current); - current = u""; - } else { - current += c; - } - } + for (const auto& c : str) { + if (c == delimiter) { + vector.push_back(current); + current = u""; + } else { + current += c; + } + } - vector.push_back(current); - return vector; + vector.push_back(current); + return vector; } -std::vector GeneralUtils::SplitString(const std::string& str, char delimiter) -{ +std::vector GeneralUtils::SplitString(const std::string& str, char delimiter) { std::vector vector = std::vector(); std::string current = ""; - for (size_t i = 0; i < str.length(); i++) - { + for (size_t i = 0; i < str.length(); i++) { char c = str[i]; - if (c == delimiter) - { + if (c == delimiter) { vector.push_back(current); current = ""; - } - else - { + } else { current += c; } } @@ -282,39 +275,38 @@ std::vector GeneralUtils::SplitString(const std::string& str, char return vector; } -std::u16string GeneralUtils::ReadWString(RakNet::BitStream *inStream) { - uint32_t length; - inStream->Read(length); +std::u16string GeneralUtils::ReadWString(RakNet::BitStream* inStream) { + uint32_t length; + inStream->Read(length); - std::u16string string; - for (auto i = 0; i < length; i++) { - uint16_t c; - inStream->Read(c); - string.push_back(c); - } + std::u16string string; + for (auto i = 0; i < length; i++) { + uint16_t c; + inStream->Read(c); + string.push_back(c); + } - return string; + return string; } #ifdef _WIN32 #define WIN32_LEAN_AND_MEAN #include -std::vector GeneralUtils::GetFileNamesFromFolder(const std::string& folder) -{ - std::vector names; - std::string search_path = folder + "/*.*"; - WIN32_FIND_DATA fd; - HANDLE hFind = ::FindFirstFile(search_path.c_str(), &fd); - if (hFind != INVALID_HANDLE_VALUE) { - do { - if (!(fd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)) { - names.push_back(fd.cFileName); - } - } while (::FindNextFile(hFind, &fd)); - ::FindClose(hFind); - } - return names; +std::vector GeneralUtils::GetFileNamesFromFolder(const std::string& folder) { + std::vector names; + std::string search_path = folder + "/*.*"; + WIN32_FIND_DATA fd; + HANDLE hFind = ::FindFirstFile(search_path.c_str(), &fd); + if (hFind != INVALID_HANDLE_VALUE) { + do { + if (!(fd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)) { + names.push_back(fd.cFileName); + } + } while (::FindNextFile(hFind, &fd)); + ::FindClose(hFind); + } + return names; } #else #include @@ -325,23 +317,23 @@ std::vector GeneralUtils::GetFileNamesFromFolder(const std::string& #include std::vector GeneralUtils::GetFileNamesFromFolder(const std::string& folder) { - std::vector names; - struct dirent* entry; - DIR* dir = opendir(folder.c_str()); - if (dir == NULL) { - return names; - } + std::vector names; + struct dirent* entry; + DIR* dir = opendir(folder.c_str()); + if (dir == NULL) { + return names; + } - while ((entry = readdir(dir)) != NULL) { - std::string value(entry->d_name, strlen(entry->d_name)); - if (value == "." || value == "..") { - continue; - } - names.push_back(value); - } + while ((entry = readdir(dir)) != NULL) { + std::string value(entry->d_name, strlen(entry->d_name)); + if (value == "." || value == "..") { + continue; + } + names.push_back(value); + } - closedir(dir); + closedir(dir); - return names; + return names; } -#endif \ No newline at end of file +#endif diff --git a/dCommon/GeneralUtils.h b/dCommon/GeneralUtils.h index f796839c..898616d2 100644 --- a/dCommon/GeneralUtils.h +++ b/dCommon/GeneralUtils.h @@ -18,120 +18,119 @@ \brief A namespace containing general utility functions */ -//! The general utils namespace + //! The general utils namespace namespace GeneralUtils { - //! Converts a plain ASCII string to a UTF-16 string - /*! - \param string The string to convert - \param size A size to trim the string to. Default is -1 (No trimming) - \return An UTF-16 representation of the string - */ - std::u16string ASCIIToUTF16(const std::string_view& string, size_t size = -1); + //! Converts a plain ASCII string to a UTF-16 string + /*! + \param string The string to convert + \param size A size to trim the string to. Default is -1 (No trimming) + \return An UTF-16 representation of the string + */ + std::u16string ASCIIToUTF16(const std::string_view& string, size_t size = -1); - //! Converts a UTF-8 String to a UTF-16 string - /*! - \param string The string to convert - \param size A size to trim the string to. Default is -1 (No trimming) - \return An UTF-16 representation of the string - */ - std::u16string UTF8ToUTF16(const std::string_view& string, size_t size = -1); + //! Converts a UTF-8 String to a UTF-16 string + /*! + \param string The string to convert + \param size A size to trim the string to. Default is -1 (No trimming) + \return An UTF-16 representation of the string + */ + std::u16string UTF8ToUTF16(const std::string_view& string, size_t size = -1); - //! Internal, do not use - bool _NextUTF8Char(std::string_view& slice, uint32_t& out); + //! Internal, do not use + bool _NextUTF8Char(std::string_view& slice, uint32_t& out); - //! Converts a UTF-16 string to a UTF-8 string - /*! - \param string The string to convert - \param size A size to trim the string to. Default is -1 (No trimming) - \return An UTF-8 representation of the string - */ - std::string UTF16ToWTF8(const std::u16string_view& string, size_t size = -1); + //! Converts a UTF-16 string to a UTF-8 string + /*! + \param string The string to convert + \param size A size to trim the string to. Default is -1 (No trimming) + \return An UTF-8 representation of the string + */ + std::string UTF16ToWTF8(const std::u16string_view& string, size_t size = -1); - /** - * Compares two basic strings but does so ignoring case sensitivity - * \param a the first string to compare against the second string - * \param b the second string to compare against the first string - * @return if the two strings are equal - */ - bool CaseInsensitiveStringCompare(const std::string& a, const std::string& b); + /** + * Compares two basic strings but does so ignoring case sensitivity + * \param a the first string to compare against the second string + * \param b the second string to compare against the first string + * @return if the two strings are equal + */ + bool CaseInsensitiveStringCompare(const std::string& a, const std::string& b); - // MARK: Bits + // MARK: Bits - // MARK: Bits + // MARK: Bits - //! Sets a bit on a numerical value - template - void SetBit(T& value, size_t index) { - static_assert(std::is_arithmetic::value, "Not an arithmetic type"); - - if (index > (sizeof(T) * 8) - 1) { - return; - } - - value |= static_cast(1) << index; - } - - //! Clears a bit on a numerical value - template - void ClearBit(T& value, size_t index) { - static_assert(std::is_arithmetic::value, "Not an arithmetic type"); - - if (index > (sizeof(T) * 8 - 1)) { - return; - } - - value &= ~(static_cast(1) << index); - } - - //! Sets a specific bit in a signed 64-bit integer - /*! - \param value The value to set the bit for - \param index The index of the bit - */ - int64_t SetBit(int64_t value, uint32_t index); - - //! Clears a specific bit in a signed 64-bit integer - /*! - \param value The value to clear the bit from - \param index The index of the bit - */ - int64_t ClearBit(int64_t value, uint32_t index); - - //! Checks a specific bit in a signed 64-bit integer - /*! - \parma value The value to check the bit in - \param index The index of the bit - \return Whether or not the bit is set - */ - bool CheckBit(int64_t value, uint32_t index); + //! Sets a bit on a numerical value + template + void SetBit(T& value, size_t index) { + static_assert(std::is_arithmetic::value, "Not an arithmetic type"); - // MARK: Random Number Generation + if (index > (sizeof(T) * 8) - 1) { + return; + } - //! Generates a random number - /*! - \param min The minimum the generate from - \param max The maximum to generate to - */ - template - inline T GenerateRandomNumber(std::size_t min, std::size_t max) { - // Make sure it is a numeric type - static_assert(std::is_arithmetic::value, "Not an arithmetic type"); + value |= static_cast(1) << index; + } - if constexpr (std::is_integral_v) { // constexpr only necessary on first statement - std::uniform_int_distribution distribution(min, max); - return distribution(Game::randomEngine); - } - else if (std::is_floating_point_v) { - std::uniform_real_distribution distribution(min, max); - return distribution(Game::randomEngine); - } + //! Clears a bit on a numerical value + template + void ClearBit(T& value, size_t index) { + static_assert(std::is_arithmetic::value, "Not an arithmetic type"); + + if (index > (sizeof(T) * 8 - 1)) { + return; + } + + value &= ~(static_cast(1) << index); + } + + //! Sets a specific bit in a signed 64-bit integer + /*! + \param value The value to set the bit for + \param index The index of the bit + */ + int64_t SetBit(int64_t value, uint32_t index); + + //! Clears a specific bit in a signed 64-bit integer + /*! + \param value The value to clear the bit from + \param index The index of the bit + */ + int64_t ClearBit(int64_t value, uint32_t index); + + //! Checks a specific bit in a signed 64-bit integer + /*! + \parma value The value to check the bit in + \param index The index of the bit + \return Whether or not the bit is set + */ + bool CheckBit(int64_t value, uint32_t index); + + // MARK: Random Number Generation + + //! Generates a random number + /*! + \param min The minimum the generate from + \param max The maximum to generate to + */ + template + inline T GenerateRandomNumber(std::size_t min, std::size_t max) { + // Make sure it is a numeric type + static_assert(std::is_arithmetic::value, "Not an arithmetic type"); + + if constexpr (std::is_integral_v) { // constexpr only necessary on first statement + std::uniform_int_distribution distribution(min, max); + return distribution(Game::randomEngine); + } else if (std::is_floating_point_v) { + std::uniform_real_distribution distribution(min, max); + return distribution(Game::randomEngine); + } + + return T(); + } - return T(); - } - bool ReplaceInString(std::string& str, const std::string& from, const std::string& to); - std::u16string ReadWString(RakNet::BitStream *inStream); + std::u16string ReadWString(RakNet::BitStream* inStream); std::vector SplitString(std::wstring& str, wchar_t delimiter); @@ -139,85 +138,71 @@ namespace GeneralUtils { std::vector SplitString(const std::string& str, char delimiter); - std::vector GetFileNamesFromFolder(const std::string& folder); + std::vector GetFileNamesFromFolder(const std::string& folder); - template - T Parse(const char* value); + template + T Parse(const char* value); template <> - inline int32_t Parse(const char* value) - { - return std::stoi(value); + inline int32_t Parse(const char* value) { + return std::stoi(value); } - template <> - inline int64_t Parse(const char* value) - { - return std::stoll(value); - } + template <> + inline int64_t Parse(const char* value) { + return std::stoll(value); + } - template <> - inline float Parse(const char* value) - { - return std::stof(value); - } + template <> + inline float Parse(const char* value) { + return std::stof(value); + } - template <> - inline double Parse(const char* value) - { - return std::stod(value); - } - - template <> - inline uint32_t Parse(const char* value) - { - return std::stoul(value); - } + template <> + inline double Parse(const char* value) { + return std::stod(value); + } - template <> - inline uint64_t Parse(const char* value) - { - return std::stoull(value); - } - - template - bool TryParse(const char* value, T& dst) - { - try - { - dst = Parse(value); + template <> + inline uint32_t Parse(const char* value) { + return std::stoul(value); + } - return true; - } - catch (...) - { - return false; - } - } + template <> + inline uint64_t Parse(const char* value) { + return std::stoull(value); + } - template - T Parse(const std::string& value) - { - return Parse(value.c_str()); - } + template + bool TryParse(const char* value, T& dst) { + try { + dst = Parse(value); - template - bool TryParse(const std::string& value, T& dst) - { - return TryParse(value.c_str(), dst); - } + return true; + } catch (...) { + return false; + } + } - template - std::u16string to_u16string(T value) - { - return GeneralUtils::ASCIIToUTF16(std::to_string(value)); - } + template + T Parse(const std::string& value) { + return Parse(value.c_str()); + } - // From boost::hash_combine - template - void hash_combine(std::size_t& s, const T& v) - { - std::hash h; - s ^= h(v) + 0x9e3779b9 + (s << 6) + (s >> 2); - } + template + bool TryParse(const std::string& value, T& dst) { + return TryParse(value.c_str(), dst); + } + + template + std::u16string to_u16string(T value) { + return GeneralUtils::ASCIIToUTF16(std::to_string(value)); + } + + // From boost::hash_combine + template + void hash_combine(std::size_t& s, const T& v) { + std::hash h; + s ^= h(v) + 0x9e3779b9 + (s << 6) + (s >> 2); + } } diff --git a/dCommon/LDFFormat.cpp b/dCommon/LDFFormat.cpp index 8290faec..b6ea21a4 100644 --- a/dCommon/LDFFormat.cpp +++ b/dCommon/LDFFormat.cpp @@ -8,25 +8,25 @@ #include //! Returns a pointer to a LDFData value based on string format -LDFBaseData * LDFBaseData::DataFromString(const std::string& format) { - - // First, check the format - std::istringstream ssFormat(format); - std::string token; - - std::vector keyValueArray; - while (std::getline(ssFormat, token, '=')) { - keyValueArray.push_back(token); - } - - if (keyValueArray.size() == 2) { - std::u16string key = GeneralUtils::ASCIIToUTF16(keyValueArray[0]); - - std::vector dataArray; - std::istringstream ssData(keyValueArray[1]); - while (std::getline(ssData, token, ':')) { - dataArray.push_back(token); - } +LDFBaseData* LDFBaseData::DataFromString(const std::string& format) { + + // First, check the format + std::istringstream ssFormat(format); + std::string token; + + std::vector keyValueArray; + while (std::getline(ssFormat, token, '=')) { + keyValueArray.push_back(token); + } + + if (keyValueArray.size() == 2) { + std::u16string key = GeneralUtils::ASCIIToUTF16(keyValueArray[0]); + + std::vector dataArray; + std::istringstream ssData(keyValueArray[1]); + while (std::getline(ssData, token, ':')) { + dataArray.push_back(token); + } if (dataArray.size() > 2) { // hacky fix for strings with colons in them std::vector newDataArray; @@ -39,96 +39,86 @@ LDFBaseData * LDFBaseData::DataFromString(const std::string& format) { newDataArray.push_back(value); dataArray = newDataArray; } - - if ((dataArray[0] == "0" || dataArray[0] == "13") && dataArray.size() == 1) { - dataArray.push_back(""); - } - - if (dataArray.size() == 2) { - eLDFType type = static_cast(stoi(dataArray[0])); - - switch (type) { - case LDF_TYPE_UTF_16: { - std::u16string data = GeneralUtils::ASCIIToUTF16(dataArray[1]); - return new LDFData(key, data); - } - - case LDF_TYPE_S32: { - int32_t data = static_cast(stoull(dataArray[1])); - return new LDFData(key, data); - } - - case LDF_TYPE_FLOAT: { - float data = static_cast(stof(dataArray[1])); - return new LDFData(key, data); - } - - case LDF_TYPE_DOUBLE: { - double data = static_cast(stod(dataArray[1])); - return new LDFData(key, data); - } - - case LDF_TYPE_U32: - { - uint32_t data; - - if (dataArray[1] == "true") - { - data = 1; - } - else if (dataArray[1] == "false") - { - data = 0; - } - else - { - data = static_cast(stoul(dataArray[1])); - } - - return new LDFData(key, data); - } - - case LDF_TYPE_BOOLEAN: { - bool data; - - if (dataArray[1] == "true") - { - data = true; - } - else if (dataArray[1] == "false") - { - data = false; - } - else - { - data = static_cast(stoi(dataArray[1])); - } - - return new LDFData(key, data); - } - - case LDF_TYPE_U64: { - uint64_t data = static_cast(stoull(dataArray[1])); - return new LDFData(key, data); - } - - case LDF_TYPE_OBJID: { - LWOOBJID data = static_cast(stoll(dataArray[1])); - return new LDFData(key, data); - } - - case LDF_TYPE_UTF_8: { - std::string data = dataArray[1]; - return new LDFData(key, data); - } - - case LDF_TYPE_UNKNOWN: { - return nullptr; - } - } - } - } - - return nullptr; - + + if ((dataArray[0] == "0" || dataArray[0] == "13") && dataArray.size() == 1) { + dataArray.push_back(""); + } + + if (dataArray.size() == 2) { + eLDFType type = static_cast(stoi(dataArray[0])); + + switch (type) { + case LDF_TYPE_UTF_16: { + std::u16string data = GeneralUtils::ASCIIToUTF16(dataArray[1]); + return new LDFData(key, data); + } + + case LDF_TYPE_S32: { + int32_t data = static_cast(stoull(dataArray[1])); + return new LDFData(key, data); + } + + case LDF_TYPE_FLOAT: { + float data = static_cast(stof(dataArray[1])); + return new LDFData(key, data); + } + + case LDF_TYPE_DOUBLE: { + double data = static_cast(stod(dataArray[1])); + return new LDFData(key, data); + } + + case LDF_TYPE_U32: + { + uint32_t data; + + if (dataArray[1] == "true") { + data = 1; + } else if (dataArray[1] == "false") { + data = 0; + } else { + data = static_cast(stoul(dataArray[1])); + } + + return new LDFData(key, data); + } + + case LDF_TYPE_BOOLEAN: { + bool data; + + if (dataArray[1] == "true") { + data = true; + } else if (dataArray[1] == "false") { + data = false; + } else { + data = static_cast(stoi(dataArray[1])); + } + + return new LDFData(key, data); + } + + case LDF_TYPE_U64: { + uint64_t data = static_cast(stoull(dataArray[1])); + return new LDFData(key, data); + } + + case LDF_TYPE_OBJID: { + LWOOBJID data = static_cast(stoll(dataArray[1])); + return new LDFData(key, data); + } + + case LDF_TYPE_UTF_8: { + std::string data = dataArray[1]; + return new LDFData(key, data); + } + + case LDF_TYPE_UNKNOWN: { + return nullptr; + } + } + } + } + + return nullptr; + } diff --git a/dCommon/LDFFormat.h b/dCommon/LDFFormat.h index 0a8a99f3..9b62efa7 100644 --- a/dCommon/LDFFormat.h +++ b/dCommon/LDFFormat.h @@ -17,64 +17,64 @@ \brief A collection of LDF format classes */ -//! An enum for LDF Data Types + //! An enum for LDF Data Types enum eLDFType { - LDF_TYPE_UNKNOWN = -1, //!< Unknown data type - LDF_TYPE_UTF_16 = 0, //!< UTF-16 wstring data type - LDF_TYPE_S32 = 1, //!< Signed 32-bit data type - LDF_TYPE_FLOAT = 3, //!< Float data type - LDF_TYPE_DOUBLE = 4, //!< Double data type - LDF_TYPE_U32 = 5, //!< Unsigned 32-bit data type - LDF_TYPE_BOOLEAN = 7, //!< Boolean data type - LDF_TYPE_U64 = 8, //!< Unsigned 64-bit data type (originally signed, templates won't work with both S64 & OBJID - LDF_TYPE_OBJID = 9, //!< Signed 64-bit data type (reserved for object IDs) - LDF_TYPE_UTF_8 = 13, //!< UTF-8 string data type + LDF_TYPE_UNKNOWN = -1, //!< Unknown data type + LDF_TYPE_UTF_16 = 0, //!< UTF-16 wstring data type + LDF_TYPE_S32 = 1, //!< Signed 32-bit data type + LDF_TYPE_FLOAT = 3, //!< Float data type + LDF_TYPE_DOUBLE = 4, //!< Double data type + LDF_TYPE_U32 = 5, //!< Unsigned 32-bit data type + LDF_TYPE_BOOLEAN = 7, //!< Boolean data type + LDF_TYPE_U64 = 8, //!< Unsigned 64-bit data type (originally signed, templates won't work with both S64 & OBJID + LDF_TYPE_OBJID = 9, //!< Signed 64-bit data type (reserved for object IDs) + LDF_TYPE_UTF_8 = 13, //!< UTF-8 string data type }; //! A base class for the LDF data class LDFBaseData { public: - - //! Destructor - virtual ~LDFBaseData(void) { } - - //! Writes the data to a packet - /*! - \param packet The packet - */ - virtual void WriteToPacket(RakNet::BitStream * packet) = 0; - - //! Gets the key - /*! - \return The key - */ - virtual const std::u16string& GetKey(void) = 0; - - //! Gets the value type - /*! - \return The value type - */ - virtual eLDFType GetValueType(void) = 0; - - //! Gets a string from the key/value pair - /*! - \param includeKey Whether or not to include the key in the data - \param includeTypeId Whether or not to include the type id in the data - \return The string representation of the data - */ - virtual std::string GetString(bool includeKey = true, bool includeTypeId = true) = 0; - - virtual std::string GetValueAsString() = 0; - virtual LDFBaseData * Copy() = 0; - - // MARK: Functions - - //! Returns a pointer to a LDFData value based on string format - /*! - \param format The format - */ - static LDFBaseData * DataFromString(const std::string& format); + //! Destructor + virtual ~LDFBaseData(void) {} + + //! Writes the data to a packet + /*! + \param packet The packet + */ + virtual void WriteToPacket(RakNet::BitStream* packet) = 0; + + //! Gets the key + /*! + \return The key + */ + virtual const std::u16string& GetKey(void) = 0; + + //! Gets the value type + /*! + \return The value type + */ + virtual eLDFType GetValueType(void) = 0; + + //! Gets a string from the key/value pair + /*! + \param includeKey Whether or not to include the key in the data + \param includeTypeId Whether or not to include the type id in the data + \return The string representation of the data + */ + virtual std::string GetString(bool includeKey = true, bool includeTypeId = true) = 0; + + virtual std::string GetValueAsString() = 0; + + virtual LDFBaseData* Copy() = 0; + + // MARK: Functions + + //! Returns a pointer to a LDFData value based on string format + /*! + \param format The format + */ + static LDFBaseData* DataFromString(const std::string& format); }; @@ -82,115 +82,115 @@ public: template class LDFData : public LDFBaseData { private: - std::u16string key; - T value; - - //! Writes the key to the packet - void WriteKey(RakNet::BitStream * packet) { - packet->Write(static_cast(this->key.length() * sizeof(uint16_t))); - for (uint32_t i = 0; i < this->key.length(); ++i) { - packet->Write(static_cast(this->key[i])); - } - } - - //! Writes the value to the packet - void WriteValue(RakNet::BitStream * packet) { - packet->Write(static_cast(this->GetValueType())); - packet->Write(this->value); - } + std::u16string key; + T value; + + //! Writes the key to the packet + void WriteKey(RakNet::BitStream* packet) { + packet->Write(static_cast(this->key.length() * sizeof(uint16_t))); + for (uint32_t i = 0; i < this->key.length(); ++i) { + packet->Write(static_cast(this->key[i])); + } + } + + //! Writes the value to the packet + void WriteValue(RakNet::BitStream* packet) { + packet->Write(static_cast(this->GetValueType())); + packet->Write(this->value); + } public: - - //! Initializer - LDFData(const std::u16string& key, const T& value) { - this->key = key; - this->value = value; - } - - //! Destructor - ~LDFData(void) override { } - - //! Gets the value - /*! - \return The value - */ - const T& GetValue(void) { return this->value; } - - //! Sets the value - /*! - \param value The value to set to - */ - void SetValue(T value) { this->value = value; }; - //! Gets the value string - /*! - \return The value string - */ - std::string GetValueString(void) { return ""; } - - //! Writes the data to a packet - /*! - \param packet The packet - */ - void WriteToPacket(RakNet::BitStream * packet) override { - this->WriteKey(packet); - this->WriteValue(packet); - } - - //! Gets the key - /*! - \return The key - */ - const std::u16string& GetKey(void) override { return this->key; } - - //! Gets the LDF Type - /*! - \return The LDF value type - */ - eLDFType GetValueType(void) override { return LDF_TYPE_UNKNOWN; } - - //! Gets the string data - /*! - \param includeKey Whether or not to include the key in the data - \param includeTypeId Whether or not to include the type id in the data - \return The string representation of the data - */ - std::string GetString(const bool includeKey = true, const bool includeTypeId = true) override { - if (GetValueType() == -1) { - return GeneralUtils::UTF16ToWTF8(this->key) + "=-1:"; - } + //! Initializer + LDFData(const std::u16string& key, const T& value) { + this->key = key; + this->value = value; + } - std::stringstream stream; + //! Destructor + ~LDFData(void) override {} - if (includeKey) { - const std::string& sKey = GeneralUtils::UTF16ToWTF8(this->key, this->key.size()); - - stream << sKey << "="; - } + //! Gets the value + /*! + \return The value + */ + const T& GetValue(void) { return this->value; } - if (includeTypeId) { - const std::string& sType = std::to_string(this->GetValueType()); + //! Sets the value + /*! + \param value The value to set to + */ + void SetValue(T value) { this->value = value; }; - - stream << sType << ":"; - } + //! Gets the value string + /*! + \return The value string + */ + std::string GetValueString(void) { return ""; } - const std::string& sData = this->GetValueString(); - - stream << sData; + //! Writes the data to a packet + /*! + \param packet The packet + */ + void WriteToPacket(RakNet::BitStream* packet) override { + this->WriteKey(packet); + this->WriteValue(packet); + } - return stream.str(); - } - - std::string GetValueAsString() override { - return this->GetValueString(); - } - - LDFBaseData * Copy() override { - return new LDFData(key, value); - } - - inline static T Default = {}; + //! Gets the key + /*! + \return The key + */ + const std::u16string& GetKey(void) override { return this->key; } + + //! Gets the LDF Type + /*! + \return The LDF value type + */ + eLDFType GetValueType(void) override { return LDF_TYPE_UNKNOWN; } + + //! Gets the string data + /*! + \param includeKey Whether or not to include the key in the data + \param includeTypeId Whether or not to include the type id in the data + \return The string representation of the data + */ + std::string GetString(const bool includeKey = true, const bool includeTypeId = true) override { + if (GetValueType() == -1) { + return GeneralUtils::UTF16ToWTF8(this->key) + "=-1:"; + } + + std::stringstream stream; + + if (includeKey) { + const std::string& sKey = GeneralUtils::UTF16ToWTF8(this->key, this->key.size()); + + stream << sKey << "="; + } + + if (includeTypeId) { + const std::string& sType = std::to_string(this->GetValueType()); + + + stream << sType << ":"; + } + + const std::string& sData = this->GetValueString(); + + stream << sData; + + return stream.str(); + } + + std::string GetValueAsString() override { + return this->GetValueString(); + } + + LDFBaseData* Copy() override { + return new LDFData(key, value); + } + + inline static T Default = {}; }; // LDF Types @@ -206,38 +206,38 @@ template<> inline eLDFType LDFData::GetValueType(void) { return LDF // The specialized version for std::u16string (UTF-16) template<> -inline void LDFData::WriteValue(RakNet::BitStream * packet) { - packet->Write(static_cast(this->GetValueType())); - - packet->Write(static_cast(this->value.length())); - for (uint32_t i = 0; i < this->value.length(); ++i) { - packet->Write(static_cast(this->value[i])); - } +inline void LDFData::WriteValue(RakNet::BitStream* packet) { + packet->Write(static_cast(this->GetValueType())); + + packet->Write(static_cast(this->value.length())); + for (uint32_t i = 0; i < this->value.length(); ++i) { + packet->Write(static_cast(this->value[i])); + } } // The specialized version for bool template<> -inline void LDFData::WriteValue(RakNet::BitStream * packet) { - packet->Write(static_cast(this->GetValueType())); - - packet->Write(static_cast(this->value)); +inline void LDFData::WriteValue(RakNet::BitStream* packet) { + packet->Write(static_cast(this->GetValueType())); + + packet->Write(static_cast(this->value)); } // The specialized version for std::string (UTF-8) template<> -inline void LDFData::WriteValue(RakNet::BitStream * packet) { - packet->Write(static_cast(this->GetValueType())); - - packet->Write(static_cast(this->value.length())); - for (uint32_t i = 0; i < this->value.length(); ++i) { - packet->Write(static_cast(this->value[i])); - } +inline void LDFData::WriteValue(RakNet::BitStream* packet) { + packet->Write(static_cast(this->GetValueType())); + + packet->Write(static_cast(this->value.length())); + for (uint32_t i = 0; i < this->value.length(); ++i) { + packet->Write(static_cast(this->value[i])); + } } // MARK: String Data template<> inline std::string LDFData::GetValueString(void) { - //std::string toReturn(this->value.begin(), this->value.end()); - //return toReturn; + //std::string toReturn(this->value.begin(), this->value.end()); + //return toReturn; return GeneralUtils::UTF16ToWTF8(this->value, this->value.size()); } diff --git a/dCommon/MD5.cpp b/dCommon/MD5.cpp index 36c0d2cf..d02b540d 100644 --- a/dCommon/MD5.cpp +++ b/dCommon/MD5.cpp @@ -1,36 +1,36 @@ /* MD5 converted to C++ class by Frank Thilo (thilo@unix-ag.org) for bzflag (http://www.bzflag.org) - + based on: - + md5.h and md5.c reference implemantion of RFC 1321 - + Copyright (C) 1991-2, RSA Data Security, Inc. Created 1991. All rights reserved. - + License to copy and use this software is granted provided that it is identified as the "RSA Data Security, Inc. MD5 Message-Digest Algorithm" in all material mentioning or referencing this software or this function. - + License is also granted to make and use derivative works provided that such works are identified as "derived from the RSA Data Security, Inc. MD5 Message-Digest Algorithm" in all material mentioning or referencing the derived work. - + RSA Data Security, Inc. makes no representations concerning either the merchantability of this software or the suitability of this software for any particular purpose. It is provided "as is" without express or implied warranty of any kind. - + These notices must be retained in any copies of any part of this documentation and/or software. - + */ -/* interface header */ + /* interface header */ #include "MD5.h" /* system implementation headers */ @@ -59,304 +59,290 @@ // F, G, H and I are basic MD5 functions. inline MD5::uint4 MD5::F(uint4 x, uint4 y, uint4 z) { - return x&y | ~x&z; + return x & y | ~x & z; } inline MD5::uint4 MD5::G(uint4 x, uint4 y, uint4 z) { - return x&z | y&~z; + return x & z | y & ~z; } inline MD5::uint4 MD5::H(uint4 x, uint4 y, uint4 z) { - return x^y^z; + return x ^ y ^ z; } inline MD5::uint4 MD5::I(uint4 x, uint4 y, uint4 z) { - return y ^ (x | ~z); + return y ^ (x | ~z); } // rotate_left rotates x left n bits. inline MD5::uint4 MD5::rotate_left(uint4 x, int n) { - return (x << n) | (x >> (32 - n)); + return (x << n) | (x >> (32 - n)); } // FF, GG, HH, and II transformations for rounds 1, 2, 3, and 4. // Rotation is separate from addition to prevent recomputation. -inline void MD5::FF(uint4 &a, uint4 b, uint4 c, uint4 d, uint4 x, uint4 s, uint4 ac) { - a = rotate_left(a + F(b, c, d) + x + ac, s) + b; +inline void MD5::FF(uint4& a, uint4 b, uint4 c, uint4 d, uint4 x, uint4 s, uint4 ac) { + a = rotate_left(a + F(b, c, d) + x + ac, s) + b; } -inline void MD5::GG(uint4 &a, uint4 b, uint4 c, uint4 d, uint4 x, uint4 s, uint4 ac) { - a = rotate_left(a + G(b, c, d) + x + ac, s) + b; +inline void MD5::GG(uint4& a, uint4 b, uint4 c, uint4 d, uint4 x, uint4 s, uint4 ac) { + a = rotate_left(a + G(b, c, d) + x + ac, s) + b; } -inline void MD5::HH(uint4 &a, uint4 b, uint4 c, uint4 d, uint4 x, uint4 s, uint4 ac) { - a = rotate_left(a + H(b, c, d) + x + ac, s) + b; +inline void MD5::HH(uint4& a, uint4 b, uint4 c, uint4 d, uint4 x, uint4 s, uint4 ac) { + a = rotate_left(a + H(b, c, d) + x + ac, s) + b; } -inline void MD5::II(uint4 &a, uint4 b, uint4 c, uint4 d, uint4 x, uint4 s, uint4 ac) { - a = rotate_left(a + I(b, c, d) + x + ac, s) + b; +inline void MD5::II(uint4& a, uint4 b, uint4 c, uint4 d, uint4 x, uint4 s, uint4 ac) { + a = rotate_left(a + I(b, c, d) + x + ac, s) + b; } ////////////////////////////////////////////// // default ctor, just initailize -MD5::MD5() -{ - init(); +MD5::MD5() { + init(); } ////////////////////////////////////////////// // nifty shortcut ctor, compute MD5 for string and finalize it right away -MD5::MD5(const std::string &text) -{ - init(); - update(text.c_str(), text.length()); - finalize(); +MD5::MD5(const std::string& text) { + init(); + update(text.c_str(), text.length()); + finalize(); } ////////////////////////////// -void MD5::init() -{ - finalized = false; - - count[0] = 0; - count[1] = 0; - - // load magic initialization constants. - state[0] = 0x67452301; - state[1] = 0xefcdab89; - state[2] = 0x98badcfe; - state[3] = 0x10325476; +void MD5::init() { + finalized = false; + + count[0] = 0; + count[1] = 0; + + // load magic initialization constants. + state[0] = 0x67452301; + state[1] = 0xefcdab89; + state[2] = 0x98badcfe; + state[3] = 0x10325476; } ////////////////////////////// // decodes input (unsigned char) into output (uint4). Assumes len is a multiple of 4. -void MD5::decode(uint4 output[], const uint1 input[], size_type len) -{ - for (unsigned int i = 0, j = 0; j < len; i++, j += 4) - output[i] = ((uint4)input[j]) | (((uint4)input[j + 1]) << 8) | - (((uint4)input[j + 2]) << 16) | (((uint4)input[j + 3]) << 24); +void MD5::decode(uint4 output[], const uint1 input[], size_type len) { + for (unsigned int i = 0, j = 0; j < len; i++, j += 4) + output[i] = ((uint4)input[j]) | (((uint4)input[j + 1]) << 8) | + (((uint4)input[j + 2]) << 16) | (((uint4)input[j + 3]) << 24); } ////////////////////////////// // encodes input (uint4) into output (unsigned char). Assumes len is // a multiple of 4. -void MD5::encode(uint1 output[], const uint4 input[], size_type len) -{ - for (size_type i = 0, j = 0; j < len; i++, j += 4) { - output[j] = input[i] & 0xff; - output[j + 1] = (input[i] >> 8) & 0xff; - output[j + 2] = (input[i] >> 16) & 0xff; - output[j + 3] = (input[i] >> 24) & 0xff; - } +void MD5::encode(uint1 output[], const uint4 input[], size_type len) { + for (size_type i = 0, j = 0; j < len; i++, j += 4) { + output[j] = input[i] & 0xff; + output[j + 1] = (input[i] >> 8) & 0xff; + output[j + 2] = (input[i] >> 16) & 0xff; + output[j + 3] = (input[i] >> 24) & 0xff; + } } ////////////////////////////// // apply MD5 algo on a block -void MD5::transform(const uint1 block[blocksize]) -{ - uint4 a = state[0], b = state[1], c = state[2], d = state[3], x[16]; - decode(x, block, blocksize); - - /* Round 1 */ - FF(a, b, c, d, x[0], S11, 0xd76aa478); /* 1 */ - FF(d, a, b, c, x[1], S12, 0xe8c7b756); /* 2 */ - FF(c, d, a, b, x[2], S13, 0x242070db); /* 3 */ - FF(b, c, d, a, x[3], S14, 0xc1bdceee); /* 4 */ - FF(a, b, c, d, x[4], S11, 0xf57c0faf); /* 5 */ - FF(d, a, b, c, x[5], S12, 0x4787c62a); /* 6 */ - FF(c, d, a, b, x[6], S13, 0xa8304613); /* 7 */ - FF(b, c, d, a, x[7], S14, 0xfd469501); /* 8 */ - FF(a, b, c, d, x[8], S11, 0x698098d8); /* 9 */ - FF(d, a, b, c, x[9], S12, 0x8b44f7af); /* 10 */ - FF(c, d, a, b, x[10], S13, 0xffff5bb1); /* 11 */ - FF(b, c, d, a, x[11], S14, 0x895cd7be); /* 12 */ - FF(a, b, c, d, x[12], S11, 0x6b901122); /* 13 */ - FF(d, a, b, c, x[13], S12, 0xfd987193); /* 14 */ - FF(c, d, a, b, x[14], S13, 0xa679438e); /* 15 */ - FF(b, c, d, a, x[15], S14, 0x49b40821); /* 16 */ - - /* Round 2 */ - GG(a, b, c, d, x[1], S21, 0xf61e2562); /* 17 */ - GG(d, a, b, c, x[6], S22, 0xc040b340); /* 18 */ - GG(c, d, a, b, x[11], S23, 0x265e5a51); /* 19 */ - GG(b, c, d, a, x[0], S24, 0xe9b6c7aa); /* 20 */ - GG(a, b, c, d, x[5], S21, 0xd62f105d); /* 21 */ - GG(d, a, b, c, x[10], S22, 0x2441453); /* 22 */ - GG(c, d, a, b, x[15], S23, 0xd8a1e681); /* 23 */ - GG(b, c, d, a, x[4], S24, 0xe7d3fbc8); /* 24 */ - GG(a, b, c, d, x[9], S21, 0x21e1cde6); /* 25 */ - GG(d, a, b, c, x[14], S22, 0xc33707d6); /* 26 */ - GG(c, d, a, b, x[3], S23, 0xf4d50d87); /* 27 */ - GG(b, c, d, a, x[8], S24, 0x455a14ed); /* 28 */ - GG(a, b, c, d, x[13], S21, 0xa9e3e905); /* 29 */ - GG(d, a, b, c, x[2], S22, 0xfcefa3f8); /* 30 */ - GG(c, d, a, b, x[7], S23, 0x676f02d9); /* 31 */ - GG(b, c, d, a, x[12], S24, 0x8d2a4c8a); /* 32 */ - - /* Round 3 */ - HH(a, b, c, d, x[5], S31, 0xfffa3942); /* 33 */ - HH(d, a, b, c, x[8], S32, 0x8771f681); /* 34 */ - HH(c, d, a, b, x[11], S33, 0x6d9d6122); /* 35 */ - HH(b, c, d, a, x[14], S34, 0xfde5380c); /* 36 */ - HH(a, b, c, d, x[1], S31, 0xa4beea44); /* 37 */ - HH(d, a, b, c, x[4], S32, 0x4bdecfa9); /* 38 */ - HH(c, d, a, b, x[7], S33, 0xf6bb4b60); /* 39 */ - HH(b, c, d, a, x[10], S34, 0xbebfbc70); /* 40 */ - HH(a, b, c, d, x[13], S31, 0x289b7ec6); /* 41 */ - HH(d, a, b, c, x[0], S32, 0xeaa127fa); /* 42 */ - HH(c, d, a, b, x[3], S33, 0xd4ef3085); /* 43 */ - HH(b, c, d, a, x[6], S34, 0x4881d05); /* 44 */ - HH(a, b, c, d, x[9], S31, 0xd9d4d039); /* 45 */ - HH(d, a, b, c, x[12], S32, 0xe6db99e5); /* 46 */ - HH(c, d, a, b, x[15], S33, 0x1fa27cf8); /* 47 */ - HH(b, c, d, a, x[2], S34, 0xc4ac5665); /* 48 */ - - /* Round 4 */ - II(a, b, c, d, x[0], S41, 0xf4292244); /* 49 */ - II(d, a, b, c, x[7], S42, 0x432aff97); /* 50 */ - II(c, d, a, b, x[14], S43, 0xab9423a7); /* 51 */ - II(b, c, d, a, x[5], S44, 0xfc93a039); /* 52 */ - II(a, b, c, d, x[12], S41, 0x655b59c3); /* 53 */ - II(d, a, b, c, x[3], S42, 0x8f0ccc92); /* 54 */ - II(c, d, a, b, x[10], S43, 0xffeff47d); /* 55 */ - II(b, c, d, a, x[1], S44, 0x85845dd1); /* 56 */ - II(a, b, c, d, x[8], S41, 0x6fa87e4f); /* 57 */ - II(d, a, b, c, x[15], S42, 0xfe2ce6e0); /* 58 */ - II(c, d, a, b, x[6], S43, 0xa3014314); /* 59 */ - II(b, c, d, a, x[13], S44, 0x4e0811a1); /* 60 */ - II(a, b, c, d, x[4], S41, 0xf7537e82); /* 61 */ - II(d, a, b, c, x[11], S42, 0xbd3af235); /* 62 */ - II(c, d, a, b, x[2], S43, 0x2ad7d2bb); /* 63 */ - II(b, c, d, a, x[9], S44, 0xeb86d391); /* 64 */ - - state[0] += a; - state[1] += b; - state[2] += c; - state[3] += d; - - // Zeroize sensitive information. - memset(x, 0, sizeof x); +void MD5::transform(const uint1 block[blocksize]) { + uint4 a = state[0], b = state[1], c = state[2], d = state[3], x[16]; + decode(x, block, blocksize); + + /* Round 1 */ + FF(a, b, c, d, x[0], S11, 0xd76aa478); /* 1 */ + FF(d, a, b, c, x[1], S12, 0xe8c7b756); /* 2 */ + FF(c, d, a, b, x[2], S13, 0x242070db); /* 3 */ + FF(b, c, d, a, x[3], S14, 0xc1bdceee); /* 4 */ + FF(a, b, c, d, x[4], S11, 0xf57c0faf); /* 5 */ + FF(d, a, b, c, x[5], S12, 0x4787c62a); /* 6 */ + FF(c, d, a, b, x[6], S13, 0xa8304613); /* 7 */ + FF(b, c, d, a, x[7], S14, 0xfd469501); /* 8 */ + FF(a, b, c, d, x[8], S11, 0x698098d8); /* 9 */ + FF(d, a, b, c, x[9], S12, 0x8b44f7af); /* 10 */ + FF(c, d, a, b, x[10], S13, 0xffff5bb1); /* 11 */ + FF(b, c, d, a, x[11], S14, 0x895cd7be); /* 12 */ + FF(a, b, c, d, x[12], S11, 0x6b901122); /* 13 */ + FF(d, a, b, c, x[13], S12, 0xfd987193); /* 14 */ + FF(c, d, a, b, x[14], S13, 0xa679438e); /* 15 */ + FF(b, c, d, a, x[15], S14, 0x49b40821); /* 16 */ + + /* Round 2 */ + GG(a, b, c, d, x[1], S21, 0xf61e2562); /* 17 */ + GG(d, a, b, c, x[6], S22, 0xc040b340); /* 18 */ + GG(c, d, a, b, x[11], S23, 0x265e5a51); /* 19 */ + GG(b, c, d, a, x[0], S24, 0xe9b6c7aa); /* 20 */ + GG(a, b, c, d, x[5], S21, 0xd62f105d); /* 21 */ + GG(d, a, b, c, x[10], S22, 0x2441453); /* 22 */ + GG(c, d, a, b, x[15], S23, 0xd8a1e681); /* 23 */ + GG(b, c, d, a, x[4], S24, 0xe7d3fbc8); /* 24 */ + GG(a, b, c, d, x[9], S21, 0x21e1cde6); /* 25 */ + GG(d, a, b, c, x[14], S22, 0xc33707d6); /* 26 */ + GG(c, d, a, b, x[3], S23, 0xf4d50d87); /* 27 */ + GG(b, c, d, a, x[8], S24, 0x455a14ed); /* 28 */ + GG(a, b, c, d, x[13], S21, 0xa9e3e905); /* 29 */ + GG(d, a, b, c, x[2], S22, 0xfcefa3f8); /* 30 */ + GG(c, d, a, b, x[7], S23, 0x676f02d9); /* 31 */ + GG(b, c, d, a, x[12], S24, 0x8d2a4c8a); /* 32 */ + + /* Round 3 */ + HH(a, b, c, d, x[5], S31, 0xfffa3942); /* 33 */ + HH(d, a, b, c, x[8], S32, 0x8771f681); /* 34 */ + HH(c, d, a, b, x[11], S33, 0x6d9d6122); /* 35 */ + HH(b, c, d, a, x[14], S34, 0xfde5380c); /* 36 */ + HH(a, b, c, d, x[1], S31, 0xa4beea44); /* 37 */ + HH(d, a, b, c, x[4], S32, 0x4bdecfa9); /* 38 */ + HH(c, d, a, b, x[7], S33, 0xf6bb4b60); /* 39 */ + HH(b, c, d, a, x[10], S34, 0xbebfbc70); /* 40 */ + HH(a, b, c, d, x[13], S31, 0x289b7ec6); /* 41 */ + HH(d, a, b, c, x[0], S32, 0xeaa127fa); /* 42 */ + HH(c, d, a, b, x[3], S33, 0xd4ef3085); /* 43 */ + HH(b, c, d, a, x[6], S34, 0x4881d05); /* 44 */ + HH(a, b, c, d, x[9], S31, 0xd9d4d039); /* 45 */ + HH(d, a, b, c, x[12], S32, 0xe6db99e5); /* 46 */ + HH(c, d, a, b, x[15], S33, 0x1fa27cf8); /* 47 */ + HH(b, c, d, a, x[2], S34, 0xc4ac5665); /* 48 */ + + /* Round 4 */ + II(a, b, c, d, x[0], S41, 0xf4292244); /* 49 */ + II(d, a, b, c, x[7], S42, 0x432aff97); /* 50 */ + II(c, d, a, b, x[14], S43, 0xab9423a7); /* 51 */ + II(b, c, d, a, x[5], S44, 0xfc93a039); /* 52 */ + II(a, b, c, d, x[12], S41, 0x655b59c3); /* 53 */ + II(d, a, b, c, x[3], S42, 0x8f0ccc92); /* 54 */ + II(c, d, a, b, x[10], S43, 0xffeff47d); /* 55 */ + II(b, c, d, a, x[1], S44, 0x85845dd1); /* 56 */ + II(a, b, c, d, x[8], S41, 0x6fa87e4f); /* 57 */ + II(d, a, b, c, x[15], S42, 0xfe2ce6e0); /* 58 */ + II(c, d, a, b, x[6], S43, 0xa3014314); /* 59 */ + II(b, c, d, a, x[13], S44, 0x4e0811a1); /* 60 */ + II(a, b, c, d, x[4], S41, 0xf7537e82); /* 61 */ + II(d, a, b, c, x[11], S42, 0xbd3af235); /* 62 */ + II(c, d, a, b, x[2], S43, 0x2ad7d2bb); /* 63 */ + II(b, c, d, a, x[9], S44, 0xeb86d391); /* 64 */ + + state[0] += a; + state[1] += b; + state[2] += c; + state[3] += d; + + // Zeroize sensitive information. + memset(x, 0, sizeof x); } ////////////////////////////// // MD5 block update operation. Continues an MD5 message-digest // operation, processing another message block -void MD5::update(const unsigned char input[], size_type length) -{ - // compute number of bytes mod 64 - size_type index = count[0] / 8 % blocksize; - - // Update number of bits - if ((count[0] += (length << 3)) < (length << 3)) - count[1]++; - count[1] += (length >> 29); - - // number of bytes we need to fill in buffer - size_type firstpart = 64 - index; - - size_type i; - - // transform as many times as possible. - if (length >= firstpart) - { - // fill buffer first, transform - memcpy(&buffer[index], input, firstpart); - transform(buffer); - - // transform chunks of blocksize (64 bytes) - for (i = firstpart; i + blocksize <= length; i += blocksize) - transform(&input[i]); - - index = 0; - } - else - i = 0; - - // buffer remaining input - memcpy(&buffer[index], &input[i], length - i); +void MD5::update(const unsigned char input[], size_type length) { + // compute number of bytes mod 64 + size_type index = count[0] / 8 % blocksize; + + // Update number of bits + if ((count[0] += (length << 3)) < (length << 3)) + count[1]++; + count[1] += (length >> 29); + + // number of bytes we need to fill in buffer + size_type firstpart = 64 - index; + + size_type i; + + // transform as many times as possible. + if (length >= firstpart) { + // fill buffer first, transform + memcpy(&buffer[index], input, firstpart); + transform(buffer); + + // transform chunks of blocksize (64 bytes) + for (i = firstpart; i + blocksize <= length; i += blocksize) + transform(&input[i]); + + index = 0; + } else + i = 0; + + // buffer remaining input + memcpy(&buffer[index], &input[i], length - i); } ////////////////////////////// // for convenience provide a verson with signed char -void MD5::update(const char input[], size_type length) -{ - update((const unsigned char*)input, length); +void MD5::update(const char input[], size_type length) { + update((const unsigned char*)input, length); } ////////////////////////////// // MD5 finalization. Ends an MD5 message-digest operation, writing the // the message digest and zeroizing the context. -MD5& MD5::finalize() -{ - static unsigned char padding[64] = { - 0x80, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 - }; - - if (!finalized) { - // Save number of bits - unsigned char bits[8]; - encode(bits, count, 8); - - // pad out to 56 mod 64. - size_type index = count[0] / 8 % 64; - size_type padLen = (index < 56) ? (56 - index) : (120 - index); - update(padding, padLen); - - // Append length (before padding) - update(bits, 8); - - // Store state in digest - encode(digest, state, 16); - - // Zeroize sensitive information. - memset(buffer, 0, sizeof buffer); - memset(count, 0, sizeof count); - - finalized = true; - } - - return *this; +MD5& MD5::finalize() { + static unsigned char padding[64] = { + 0x80, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 + }; + + if (!finalized) { + // Save number of bits + unsigned char bits[8]; + encode(bits, count, 8); + + // pad out to 56 mod 64. + size_type index = count[0] / 8 % 64; + size_type padLen = (index < 56) ? (56 - index) : (120 - index); + update(padding, padLen); + + // Append length (before padding) + update(bits, 8); + + // Store state in digest + encode(digest, state, 16); + + // Zeroize sensitive information. + memset(buffer, 0, sizeof buffer); + memset(count, 0, sizeof count); + + finalized = true; + } + + return *this; } ////////////////////////////// // return hex representation of digest as string -std::string MD5::hexdigest() const -{ - if (!finalized) - return ""; - - char buf[33]; - for (int i = 0; i<16; i++) - sprintf(buf + i * 2, "%02x", digest[i]); - buf[32] = 0; - - return std::string(buf); +std::string MD5::hexdigest() const { + if (!finalized) + return ""; + + char buf[33]; + for (int i = 0; i < 16; i++) + sprintf(buf + i * 2, "%02x", digest[i]); + buf[32] = 0; + + return std::string(buf); } ////////////////////////////// -std::ostream& operator<<(std::ostream& out, MD5 md5) -{ - return out << md5.hexdigest(); +std::ostream& operator<<(std::ostream& out, MD5 md5) { + return out << md5.hexdigest(); } ////////////////////////////// -std::string md5(const std::string str) -{ - MD5 md5 = MD5(str); - - return md5.hexdigest(); +std::string md5(const std::string str) { + MD5 md5 = MD5(str); + + return md5.hexdigest(); } diff --git a/dCommon/MD5.h b/dCommon/MD5.h index 1ada98a5..30d178e1 100644 --- a/dCommon/MD5.h +++ b/dCommon/MD5.h @@ -1,33 +1,33 @@ /* MD5 converted to C++ class by Frank Thilo (thilo@unix-ag.org) for bzflag (http://www.bzflag.org) - + based on: - + md5.h and md5.c reference implementation of RFC 1321 - + Copyright (C) 1991-2, RSA Data Security, Inc. Created 1991. All rights reserved. - + License to copy and use this software is granted provided that it is identified as the "RSA Data Security, Inc. MD5 Message-Digest Algorithm" in all material mentioning or referencing this software or this function. - + License is also granted to make and use derivative works provided that such works are identified as "derived from the RSA Data Security, Inc. MD5 Message-Digest Algorithm" in all material mentioning or referencing the derived work. - + RSA Data Security, Inc. makes no representations concerning either the merchantability of this software or the suitability of this software for any particular purpose. It is provided "as is" without express or implied warranty of any kind. - + These notices must be retained in any copies of any part of this documentation and/or software. - + */ #ifndef BZF_MD5_H @@ -37,55 +37,55 @@ #include -// a small class for calculating MD5 hashes of strings or byte arrays -// it is not meant to be fast or secure -// -// usage: 1) feed it blocks of uchars with update() -// 2) finalize() -// 3) get hexdigest() string -// or -// MD5(std::string).hexdigest() -// -// assumes that char is 8 bit and int is 32 bit + // a small class for calculating MD5 hashes of strings or byte arrays + // it is not meant to be fast or secure + // + // usage: 1) feed it blocks of uchars with update() + // 2) finalize() + // 3) get hexdigest() string + // or + // MD5(std::string).hexdigest() + // + // assumes that char is 8 bit and int is 32 bit class MD5 { public: - typedef unsigned int size_type; // must be 32bit - - MD5(); - MD5(const std::string& text); - void update(const unsigned char *buf, size_type length); - void update(const char *buf, size_type length); - MD5& finalize(); - std::string hexdigest() const; - friend std::ostream& operator<<(std::ostream&, MD5 md5); - + typedef unsigned int size_type; // must be 32bit + + MD5(); + MD5(const std::string& text); + void update(const unsigned char* buf, size_type length); + void update(const char* buf, size_type length); + MD5& finalize(); + std::string hexdigest() const; + friend std::ostream& operator<<(std::ostream&, MD5 md5); + private: - void init(); - typedef unsigned char uint1; // 8bit - typedef unsigned int uint4; // 32bit - enum { blocksize = 64 }; // VC6 won't eat a const static int here - - void transform(const uint1 block[blocksize]); - static void decode(uint4 output[], const uint1 input[], size_type len); - static void encode(uint1 output[], const uint4 input[], size_type len); - - bool finalized; - uint1 buffer[blocksize]; // bytes that didn't fit in last 64 byte chunk - uint4 count[2]; // 64bit counter for number of bits (lo, hi) - uint4 state[4]; // digest so far - uint1 digest[16]; // the result - - // low level logic operations - static inline uint4 F(uint4 x, uint4 y, uint4 z); - static inline uint4 G(uint4 x, uint4 y, uint4 z); - static inline uint4 H(uint4 x, uint4 y, uint4 z); - static inline uint4 I(uint4 x, uint4 y, uint4 z); - static inline uint4 rotate_left(uint4 x, int n); - static inline void FF(uint4 &a, uint4 b, uint4 c, uint4 d, uint4 x, uint4 s, uint4 ac); - static inline void GG(uint4 &a, uint4 b, uint4 c, uint4 d, uint4 x, uint4 s, uint4 ac); - static inline void HH(uint4 &a, uint4 b, uint4 c, uint4 d, uint4 x, uint4 s, uint4 ac); - static inline void II(uint4 &a, uint4 b, uint4 c, uint4 d, uint4 x, uint4 s, uint4 ac); + void init(); + typedef unsigned char uint1; // 8bit + typedef unsigned int uint4; // 32bit + enum { blocksize = 64 }; // VC6 won't eat a const static int here + + void transform(const uint1 block[blocksize]); + static void decode(uint4 output[], const uint1 input[], size_type len); + static void encode(uint1 output[], const uint4 input[], size_type len); + + bool finalized; + uint1 buffer[blocksize]; // bytes that didn't fit in last 64 byte chunk + uint4 count[2]; // 64bit counter for number of bits (lo, hi) + uint4 state[4]; // digest so far + uint1 digest[16]; // the result + + // low level logic operations + static inline uint4 F(uint4 x, uint4 y, uint4 z); + static inline uint4 G(uint4 x, uint4 y, uint4 z); + static inline uint4 H(uint4 x, uint4 y, uint4 z); + static inline uint4 I(uint4 x, uint4 y, uint4 z); + static inline uint4 rotate_left(uint4 x, int n); + static inline void FF(uint4& a, uint4 b, uint4 c, uint4 d, uint4 x, uint4 s, uint4 ac); + static inline void GG(uint4& a, uint4 b, uint4 c, uint4 d, uint4 x, uint4 s, uint4 ac); + static inline void HH(uint4& a, uint4 b, uint4 c, uint4 d, uint4 x, uint4 s, uint4 ac); + static inline void II(uint4& a, uint4 b, uint4 c, uint4 d, uint4 x, uint4 s, uint4 ac); }; std::string md5(const std::string str); diff --git a/dCommon/Metrics.cpp b/dCommon/Metrics.cpp index a7adb998..b97b5435 100644 --- a/dCommon/Metrics.cpp +++ b/dCommon/Metrics.cpp @@ -4,174 +4,150 @@ std::unordered_map Metrics::m_Metrics = {}; std::vector Metrics::m_Variables = { - MetricVariable::GameLoop, - MetricVariable::PacketHandling, - MetricVariable::UpdateEntities, - MetricVariable::UpdateSpawners, - MetricVariable::Physics, - MetricVariable::UpdateReplica, - MetricVariable::Ghosting, - MetricVariable::CPUTime, - MetricVariable::Sleep, - MetricVariable::Frame, + MetricVariable::GameLoop, + MetricVariable::PacketHandling, + MetricVariable::UpdateEntities, + MetricVariable::UpdateSpawners, + MetricVariable::Physics, + MetricVariable::UpdateReplica, + MetricVariable::Ghosting, + MetricVariable::CPUTime, + MetricVariable::Sleep, + MetricVariable::Frame, }; -void Metrics::AddMeasurement(MetricVariable variable, int64_t value) -{ - const auto& iter = m_Metrics.find(variable); +void Metrics::AddMeasurement(MetricVariable variable, int64_t value) { + const auto& iter = m_Metrics.find(variable); - Metric* metric; + Metric* metric; - if (iter == m_Metrics.end()) - { - metric = new Metric(); + if (iter == m_Metrics.end()) { + metric = new Metric(); - m_Metrics[variable] = metric; - } - else - { - metric = iter->second; - } + m_Metrics[variable] = metric; + } else { + metric = iter->second; + } - AddMeasurement(metric, value); + AddMeasurement(metric, value); } -void Metrics::AddMeasurement(Metric* metric, int64_t value) -{ - const auto index = metric->measurementIndex; +void Metrics::AddMeasurement(Metric* metric, int64_t value) { + const auto index = metric->measurementIndex; - metric->measurements[index] = value; + metric->measurements[index] = value; - if (metric->max == -1 || value > metric->max) - { - metric->max = value; - } - else if (metric->min == -1 || metric->min > value) - { - metric->min = value; - } + if (metric->max == -1 || value > metric->max) { + metric->max = value; + } else if (metric->min == -1 || metric->min > value) { + metric->min = value; + } - if (metric->measurementSize < MAX_MEASURMENT_POINTS) - { - metric->measurementSize++; - } + if (metric->measurementSize < MAX_MEASURMENT_POINTS) { + metric->measurementSize++; + } - metric->measurementIndex = (index + 1) % MAX_MEASURMENT_POINTS; + metric->measurementIndex = (index + 1) % MAX_MEASURMENT_POINTS; } -const Metric* Metrics::GetMetric(MetricVariable variable) -{ - const auto& iter = m_Metrics.find(variable); +const Metric* Metrics::GetMetric(MetricVariable variable) { + const auto& iter = m_Metrics.find(variable); - if (iter == m_Metrics.end()) - { - return nullptr; - } + if (iter == m_Metrics.end()) { + return nullptr; + } - Metric* metric = iter->second; + Metric* metric = iter->second; - int64_t average = 0; + int64_t average = 0; - for (size_t i = 0; i < metric->measurementSize; i++) - { - average += metric->measurements[i]; - } + for (size_t i = 0; i < metric->measurementSize; i++) { + average += metric->measurements[i]; + } - average /= metric->measurementSize; + average /= metric->measurementSize; - metric->average = average; - - return metric; + metric->average = average; + + return metric; } -void Metrics::StartMeasurement(MetricVariable variable) -{ - const auto& iter = m_Metrics.find(variable); +void Metrics::StartMeasurement(MetricVariable variable) { + const auto& iter = m_Metrics.find(variable); - Metric* metric; + Metric* metric; - if (iter == m_Metrics.end()) - { - metric = new Metric(); + if (iter == m_Metrics.end()) { + metric = new Metric(); - m_Metrics[variable] = metric; - } - else - { - metric = iter->second; - } + m_Metrics[variable] = metric; + } else { + metric = iter->second; + } - metric->activeMeasurement = std::chrono::high_resolution_clock::now(); + metric->activeMeasurement = std::chrono::high_resolution_clock::now(); } -void Metrics::EndMeasurement(MetricVariable variable) -{ - const auto end = std::chrono::high_resolution_clock::now(); +void Metrics::EndMeasurement(MetricVariable variable) { + const auto end = std::chrono::high_resolution_clock::now(); - const auto& iter = m_Metrics.find(variable); + const auto& iter = m_Metrics.find(variable); - if (iter == m_Metrics.end()) - { - return; - } + if (iter == m_Metrics.end()) { + return; + } - Metric* metric = iter->second; + Metric* metric = iter->second; - const auto elapsed = end - metric->activeMeasurement; + const auto elapsed = end - metric->activeMeasurement; - const auto nanoseconds = std::chrono::duration_cast(elapsed).count(); + const auto nanoseconds = std::chrono::duration_cast(elapsed).count(); - AddMeasurement(metric, nanoseconds); + AddMeasurement(metric, nanoseconds); } -float Metrics::ToMiliseconds(int64_t nanoseconds) -{ - return (float) nanoseconds / 1e6; +float Metrics::ToMiliseconds(int64_t nanoseconds) { + return (float)nanoseconds / 1e6; } -std::string Metrics::MetricVariableToString(MetricVariable variable) -{ - switch (variable) - { - case MetricVariable::GameLoop: - return "GameLoop"; - case MetricVariable::PacketHandling: - return "PacketHandling"; - case MetricVariable::UpdateEntities: - return "UpdateEntities"; - case MetricVariable::UpdateSpawners: - return "UpdateSpawners"; - case MetricVariable::Physics: - return "Physics"; - case MetricVariable::UpdateReplica: - return "UpdateReplica"; - case MetricVariable::Sleep: - return "Sleep"; - case MetricVariable::CPUTime: - return "CPUTime"; - case MetricVariable::Frame: - return "Frame"; - case MetricVariable::Ghosting: - return "Ghosting"; - - default: - return "Invalid"; - } +std::string Metrics::MetricVariableToString(MetricVariable variable) { + switch (variable) { + case MetricVariable::GameLoop: + return "GameLoop"; + case MetricVariable::PacketHandling: + return "PacketHandling"; + case MetricVariable::UpdateEntities: + return "UpdateEntities"; + case MetricVariable::UpdateSpawners: + return "UpdateSpawners"; + case MetricVariable::Physics: + return "Physics"; + case MetricVariable::UpdateReplica: + return "UpdateReplica"; + case MetricVariable::Sleep: + return "Sleep"; + case MetricVariable::CPUTime: + return "CPUTime"; + case MetricVariable::Frame: + return "Frame"; + case MetricVariable::Ghosting: + return "Ghosting"; + + default: + return "Invalid"; + } } -const std::vector& Metrics::GetAllMetrics() -{ - return m_Variables; +const std::vector& Metrics::GetAllMetrics() { + return m_Variables; } -void Metrics::Clear() -{ - for (const auto& pair : m_Metrics) - { - delete pair.second; - } - - m_Metrics.clear(); +void Metrics::Clear() { + for (const auto& pair : m_Metrics) { + delete pair.second; + } + + m_Metrics.clear(); } /* RSS Memory utilities @@ -207,46 +183,44 @@ void Metrics::Clear() #error "Cannot define getPeakRSS( ) or getCurrentRSS( ) for an unknown OS." #endif -/** - * Returns the peak (maximum so far) resident set size (physical - * memory use) measured in bytes, or zero if the value cannot be - * determined on this OS. - */ -size_t Metrics::GetPeakRSS() -{ + /** + * Returns the peak (maximum so far) resident set size (physical + * memory use) measured in bytes, or zero if the value cannot be + * determined on this OS. + */ +size_t Metrics::GetPeakRSS() { #if defined(_WIN32) - /* Windows -------------------------------------------------- */ - PROCESS_MEMORY_COUNTERS info; - GetProcessMemoryInfo( GetCurrentProcess( ), &info, sizeof(info) ); - return (size_t)info.PeakWorkingSetSize; + /* Windows -------------------------------------------------- */ + PROCESS_MEMORY_COUNTERS info; + GetProcessMemoryInfo(GetCurrentProcess(), &info, sizeof(info)); + return (size_t)info.PeakWorkingSetSize; #elif (defined(_AIX) || defined(__TOS__AIX__)) || (defined(__sun__) || defined(__sun) || defined(sun) && (defined(__SVR4) || defined(__svr4__))) - /* AIX and Solaris ------------------------------------------ */ - struct psinfo psinfo; - int fd = -1; - if ( (fd = open( "/proc/self/psinfo", O_RDONLY )) == -1 ) - return (size_t)0L; /* Can't open? */ - if ( read( fd, &psinfo, sizeof(psinfo) ) != sizeof(psinfo) ) - { - close( fd ); - return (size_t)0L; /* Can't read? */ - } - close( fd ); - return (size_t)(psinfo.pr_rssize * 1024L); + /* AIX and Solaris ------------------------------------------ */ + struct psinfo psinfo; + int fd = -1; + if ((fd = open("/proc/self/psinfo", O_RDONLY)) == -1) + return (size_t)0L; /* Can't open? */ + if (read(fd, &psinfo, sizeof(psinfo)) != sizeof(psinfo)) { + close(fd); + return (size_t)0L; /* Can't read? */ + } + close(fd); + return (size_t)(psinfo.pr_rssize * 1024L); #elif defined(__unix__) || defined(__unix) || defined(unix) || (defined(__APPLE__) && defined(__MACH__)) - /* BSD, Linux, and OSX -------------------------------------- */ - struct rusage rusage; - getrusage( RUSAGE_SELF, &rusage ); + /* BSD, Linux, and OSX -------------------------------------- */ + struct rusage rusage; + getrusage(RUSAGE_SELF, &rusage); #if defined(__APPLE__) && defined(__MACH__) - return (size_t)rusage.ru_maxrss; + return (size_t)rusage.ru_maxrss; #else - return (size_t)(rusage.ru_maxrss * 1024L); + return (size_t)(rusage.ru_maxrss * 1024L); #endif #else - /* Unknown OS ----------------------------------------------- */ - return (size_t)0L; /* Unsupported. */ + /* Unknown OS ----------------------------------------------- */ + return (size_t)0L; /* Unsupported. */ #endif } @@ -255,49 +229,46 @@ size_t Metrics::GetPeakRSS() * Returns the current resident set size (physical memory use) measured * in bytes, or zero if the value cannot be determined on this OS. */ -size_t Metrics::GetCurrentRSS() -{ +size_t Metrics::GetCurrentRSS() { #if defined(_WIN32) - /* Windows -------------------------------------------------- */ - PROCESS_MEMORY_COUNTERS info; - GetProcessMemoryInfo( GetCurrentProcess( ), &info, sizeof(info) ); - return (size_t)info.WorkingSetSize; + /* Windows -------------------------------------------------- */ + PROCESS_MEMORY_COUNTERS info; + GetProcessMemoryInfo(GetCurrentProcess(), &info, sizeof(info)); + return (size_t)info.WorkingSetSize; #elif defined(__APPLE__) && defined(__MACH__) - /* OSX ------------------------------------------------------ */ - struct mach_task_basic_info info; - mach_msg_type_number_t infoCount = MACH_TASK_BASIC_INFO_COUNT; - if ( task_info( mach_task_self( ), MACH_TASK_BASIC_INFO, - (task_info_t)&info, &infoCount ) != KERN_SUCCESS ) - return (size_t)0L; /* Can't access? */ - return (size_t)info.resident_size; + /* OSX ------------------------------------------------------ */ + struct mach_task_basic_info info; + mach_msg_type_number_t infoCount = MACH_TASK_BASIC_INFO_COUNT; + if (task_info(mach_task_self(), MACH_TASK_BASIC_INFO, + (task_info_t)&info, &infoCount) != KERN_SUCCESS) + return (size_t)0L; /* Can't access? */ + return (size_t)info.resident_size; #elif defined(__linux__) || defined(__linux) || defined(linux) || defined(__gnu_linux__) - /* Linux ---------------------------------------------------- */ - long rss = 0L; - FILE* fp = NULL; - if ( (fp = fopen( "/proc/self/statm", "r" )) == NULL ) - return (size_t)0L; /* Can't open? */ - if ( fscanf( fp, "%*s%ld", &rss ) != 1 ) - { - fclose( fp ); - return (size_t)0L; /* Can't read? */ - } - fclose( fp ); - return (size_t)rss * (size_t)sysconf( _SC_PAGESIZE); + /* Linux ---------------------------------------------------- */ + long rss = 0L; + FILE* fp = NULL; + if ((fp = fopen("/proc/self/statm", "r")) == NULL) + return (size_t)0L; /* Can't open? */ + if (fscanf(fp, "%*s%ld", &rss) != 1) { + fclose(fp); + return (size_t)0L; /* Can't read? */ + } + fclose(fp); + return (size_t)rss * (size_t)sysconf(_SC_PAGESIZE); #else - /* AIX, BSD, Solaris, and Unknown OS ------------------------ */ - return (size_t)0L; /* Unsupported. */ + /* AIX, BSD, Solaris, and Unknown OS ------------------------ */ + return (size_t)0L; /* Unsupported. */ #endif } -size_t Metrics::GetProcessID() -{ +size_t Metrics::GetProcessID() { #if defined(_WIN32) - return GetCurrentProcessId(); + return GetCurrentProcessId(); #else - return getpid(); + return getpid(); #endif } diff --git a/dCommon/Metrics.hpp b/dCommon/Metrics.hpp index b22632d2..c03c914f 100644 --- a/dCommon/Metrics.hpp +++ b/dCommon/Metrics.hpp @@ -10,52 +10,52 @@ enum class MetricVariable : int32_t { - GameLoop, - PacketHandling, - UpdateEntities, - UpdateSpawners, - Physics, - UpdateReplica, - Ghosting, - CPUTime, - Sleep, - Frame, + GameLoop, + PacketHandling, + UpdateEntities, + UpdateSpawners, + Physics, + UpdateReplica, + Ghosting, + CPUTime, + Sleep, + Frame, }; struct Metric { - int64_t measurements[MAX_MEASURMENT_POINTS] = {}; - size_t measurementIndex = 0; - size_t measurementSize = 0; - int64_t max = -1; - int64_t min = -1; - int64_t average = 0; - std::chrono::time_point activeMeasurement; + int64_t measurements[MAX_MEASURMENT_POINTS] = {}; + size_t measurementIndex = 0; + size_t measurementSize = 0; + int64_t max = -1; + int64_t min = -1; + int64_t average = 0; + std::chrono::time_point activeMeasurement; }; class Metrics { public: - ~Metrics(); + ~Metrics(); - static void AddMeasurement(MetricVariable variable, int64_t value); - static void AddMeasurement(Metric* metric, int64_t value); - static const Metric* GetMetric(MetricVariable variable); - static void StartMeasurement(MetricVariable variable); - static void EndMeasurement(MetricVariable variable); - static float ToMiliseconds(int64_t nanoseconds); - static std::string MetricVariableToString(MetricVariable variable); - static const std::vector& GetAllMetrics(); + static void AddMeasurement(MetricVariable variable, int64_t value); + static void AddMeasurement(Metric* metric, int64_t value); + static const Metric* GetMetric(MetricVariable variable); + static void StartMeasurement(MetricVariable variable); + static void EndMeasurement(MetricVariable variable); + static float ToMiliseconds(int64_t nanoseconds); + static std::string MetricVariableToString(MetricVariable variable); + static const std::vector& GetAllMetrics(); - static size_t GetPeakRSS(); - static size_t GetCurrentRSS(); - static size_t GetProcessID(); + static size_t GetPeakRSS(); + static size_t GetCurrentRSS(); + static size_t GetProcessID(); - static void Clear(); + static void Clear(); private: - Metrics(); + Metrics(); - static std::unordered_map m_Metrics; - static std::vector m_Variables; + static std::unordered_map m_Metrics; + static std::vector m_Variables; }; diff --git a/dCommon/NiPoint3.cpp b/dCommon/NiPoint3.cpp index 4baefa13..a539c4df 100644 --- a/dCommon/NiPoint3.cpp +++ b/dCommon/NiPoint3.cpp @@ -13,23 +13,23 @@ const NiPoint3 NiPoint3::UNIT_ALL(1.0f, 1.0f, 1.0f); //! Initializer NiPoint3::NiPoint3(void) { - this->x = 0; - this->y = 0; - this->z = 0; + this->x = 0; + this->y = 0; + this->z = 0; } //! Initializer NiPoint3::NiPoint3(float x, float y, float z) { - this->x = x; - this->y = y; - this->z = z; + this->x = x; + this->y = y; + this->z = z; } //! Copy Constructor NiPoint3::NiPoint3(const NiPoint3& point) { - this->x = point.x; - this->y = point.y; - this->z = point.z; + this->x = point.x; + this->y = point.y; + this->z = point.z; } //! Destructor @@ -39,63 +39,63 @@ NiPoint3::~NiPoint3(void) {} //! Gets the X coordinate float NiPoint3::GetX(void) const { - return this->x; + return this->x; } //! Sets the X coordinate void NiPoint3::SetX(float x) { - this->x = x; + this->x = x; } //! Gets the Y coordinate float NiPoint3::GetY(void) const { - return this->y; + return this->y; } //! Sets the Y coordinate void NiPoint3::SetY(float y) { - this->y = y; + this->y = y; } //! Gets the Z coordinate float NiPoint3::GetZ(void) const { - return this->z; + return this->z; } //! Sets the Z coordinate void NiPoint3::SetZ(float z) { - this->z = z; + this->z = z; } // MARK: Functions //! Gets the length of the vector float NiPoint3::Length(void) const { - return sqrt(x*x + y*y + z*z); + return sqrt(x * x + y * y + z * z); } //! Gets the squared length of a vector float NiPoint3::SquaredLength(void) const { - return (x*x + y*y + z*z); + return (x * x + y * y + z * z); } //! Returns the dot product of the vector dotted with another vector float NiPoint3::DotProduct(const Vector3& vec) const { - return ((this->x * vec.x) + (this->y * vec.y) + (this->z * vec.z)); + return ((this->x * vec.x) + (this->y * vec.y) + (this->z * vec.z)); } //! Returns the cross product of the vector crossed with another vector Vector3 NiPoint3::CrossProduct(const Vector3& vec) const { - return Vector3(((this->y * vec.z) - (this->z * vec.y)), - ((this->z * vec.x) - (this->x * vec.z)), - ((this->x * vec.y) - (this->y * vec.x))); + return Vector3(((this->y * vec.z) - (this->z * vec.y)), + ((this->z * vec.x) - (this->x * vec.z)), + ((this->x * vec.y) - (this->y * vec.x))); } //! Unitize the vector NiPoint3 NiPoint3::Unitize(void) const { - float length = this->Length(); - - return length != 0 ? *this / length : NiPoint3::ZERO; + float length = this->Length(); + + return length != 0 ? *this / length : NiPoint3::ZERO; } @@ -103,57 +103,57 @@ NiPoint3 NiPoint3::Unitize(void) const { //! Operator to check for equality bool NiPoint3::operator==(const NiPoint3& point) const { - return point.x == this->x && point.y == this->y && point.z == this->z; + return point.x == this->x && point.y == this->y && point.z == this->z; } //! Operator to check for inequality bool NiPoint3::operator!=(const NiPoint3& point) const { - return !(*this == point); + return !(*this == point); } //! Operator for subscripting float& NiPoint3::operator[](int i) { - float * base = &x; - return (float&)base[i]; + float* base = &x; + return (float&)base[i]; } //! Operator for subscripting const float& NiPoint3::operator[](int i) const { - const float * base = &x; - return (float&)base[i]; + const float* base = &x; + return (float&)base[i]; } //! Operator for addition of vectors NiPoint3 NiPoint3::operator+(const NiPoint3& point) const { - return NiPoint3(this->x + point.x, this->y + point.y, this->z + point.z); + return NiPoint3(this->x + point.x, this->y + point.y, this->z + point.z); } //! Operator for subtraction of vectors NiPoint3 NiPoint3::operator-(const NiPoint3& point) const { - return NiPoint3(this->x - point.x, this->y - point.y, this->z - point.z); + return NiPoint3(this->x - point.x, this->y - point.y, this->z - point.z); } //! Operator for addition of a scalar on all vector components NiPoint3 NiPoint3::operator+(float fScalar) const { - return NiPoint3(this->x + fScalar, this->y + fScalar, this->z + fScalar); + return NiPoint3(this->x + fScalar, this->y + fScalar, this->z + fScalar); } //! Operator for subtraction of a scalar on all vector components NiPoint3 NiPoint3::operator-(float fScalar) const { - return NiPoint3(this->x - fScalar, this->y - fScalar, this->z - fScalar); + return NiPoint3(this->x - fScalar, this->y - fScalar, this->z - fScalar); } //! Operator for scalar multiplication of a vector NiPoint3 NiPoint3::operator*(float fScalar) const { - return NiPoint3(this->x * fScalar, this->y * fScalar, this->z * fScalar); + return NiPoint3(this->x * fScalar, this->y * fScalar, this->z * fScalar); } //! Operator for scalar division of a vector NiPoint3 NiPoint3::operator/(float fScalar) const { - float retX = this->x != 0 ? this->x / fScalar : 0; - float retY = this->y != 0 ? this->y / fScalar : 0; - float retZ = this->z != 0 ? this->z / fScalar : 0; - return NiPoint3(retX, retY, retZ); + float retX = this->x != 0 ? this->x / fScalar : 0; + float retY = this->y != 0 ? this->y / fScalar : 0; + float retZ = this->z != 0 ? this->z / fScalar : 0; + return NiPoint3(retX, retY, retZ); } @@ -161,96 +161,91 @@ NiPoint3 NiPoint3::operator/(float fScalar) const { //! Checks to see if the point (or vector) is with an Axis-Aligned Bounding Box bool NiPoint3::IsWithinAxisAlignedBox(const NiPoint3& minPoint, const NiPoint3& maxPoint) { - if (this->x < minPoint.x) return false; - if (this->x > maxPoint.x) return false; - if (this->y < minPoint.y) return false; - if (this->y > maxPoint.y) return false; + if (this->x < minPoint.x) return false; + if (this->x > maxPoint.x) return false; + if (this->y < minPoint.y) return false; + if (this->y > maxPoint.y) return false; - return (this->z < maxPoint.z && this->z > minPoint.z); + return (this->z < maxPoint.z&& this->z > minPoint.z); } //! Checks to see if the point (or vector) is within a sphere bool NiPoint3::IsWithinSpehere(const NiPoint3& sphereCenter, float radius) { - Vector3 diffVec = Vector3(x - sphereCenter.GetX(), y - sphereCenter.GetY(), z - sphereCenter.GetZ()); - return (diffVec.SquaredLength() <= (radius * radius)); + Vector3 diffVec = Vector3(x - sphereCenter.GetX(), y - sphereCenter.GetY(), z - sphereCenter.GetZ()); + return (diffVec.SquaredLength() <= (radius * radius)); } -NiPoint3 NiPoint3::ClosestPointOnLine(const NiPoint3& a, const NiPoint3& b, const NiPoint3& p) -{ - if (a == b) return a; +NiPoint3 NiPoint3::ClosestPointOnLine(const NiPoint3& a, const NiPoint3& b, const NiPoint3& p) { + if (a == b) return a; - const auto pa = p - a; - const auto ab = b - a; + const auto pa = p - a; + const auto ab = b - a; - const auto t = pa.DotProduct(ab) / ab.SquaredLength(); + const auto t = pa.DotProduct(ab) / ab.SquaredLength(); - if (t <= 0.0f) return a; - - if (t >= 1.0f) return b; - - return a + ab * t; + if (t <= 0.0f) return a; + + if (t >= 1.0f) return b; + + return a + ab * t; } -float NiPoint3::Angle(const NiPoint3& a, const NiPoint3& b) -{ - const auto dot = a.DotProduct(b); - const auto lenA = a.SquaredLength(); - const auto lenB = a.SquaredLength(); - return acos(dot / sqrt(lenA * lenB)); +float NiPoint3::Angle(const NiPoint3& a, const NiPoint3& b) { + const auto dot = a.DotProduct(b); + const auto lenA = a.SquaredLength(); + const auto lenB = a.SquaredLength(); + return acos(dot / sqrt(lenA * lenB)); } -float NiPoint3::Distance(const NiPoint3& a, const NiPoint3& b) -{ - const auto dx = a.x - b.x; - const auto dy = a.y - b.y; - const auto dz = a.z - b.z; +float NiPoint3::Distance(const NiPoint3& a, const NiPoint3& b) { + const auto dx = a.x - b.x; + const auto dy = a.y - b.y; + const auto dz = a.z - b.z; - return std::sqrt(dx * dx + dy * dy + dz * dz); + return std::sqrt(dx * dx + dy * dy + dz * dz); } -float NiPoint3::DistanceSquared(const NiPoint3& a, const NiPoint3& b) -{ - const auto dx = a.x - b.x; - const auto dy = a.y - b.y; - const auto dz = a.z - b.z; +float NiPoint3::DistanceSquared(const NiPoint3& a, const NiPoint3& b) { + const auto dx = a.x - b.x; + const auto dy = a.y - b.y; + const auto dz = a.z - b.z; - return dx * dx + dy * dy + dz * dz; + return dx * dx + dy * dy + dz * dz; } -NiPoint3 NiPoint3::MoveTowards(const NiPoint3& current, const NiPoint3& target, float maxDistanceDelta) -{ - float dx = target.x - current.x; - float dy = target.y - current.y; - float dz = target.z - current.z; - float lengthSquared = (float) ((double) dx * (double) dx + (double) dy * (double) dy + (double) dz * (double) dz); - if ((double) lengthSquared == 0.0 || (double) maxDistanceDelta >= 0.0 && (double) lengthSquared <= (double) maxDistanceDelta * (double) maxDistanceDelta) - return target; - float length = (float) std::sqrt((double) lengthSquared); - return NiPoint3(current.x + dx / length * maxDistanceDelta, current.y + dy / length * maxDistanceDelta, current.z + dz / length * maxDistanceDelta); +NiPoint3 NiPoint3::MoveTowards(const NiPoint3& current, const NiPoint3& target, float maxDistanceDelta) { + float dx = target.x - current.x; + float dy = target.y - current.y; + float dz = target.z - current.z; + float lengthSquared = (float)((double)dx * (double)dx + (double)dy * (double)dy + (double)dz * (double)dz); + if ((double)lengthSquared == 0.0 || (double)maxDistanceDelta >= 0.0 && (double)lengthSquared <= (double)maxDistanceDelta * (double)maxDistanceDelta) + return target; + float length = (float)std::sqrt((double)lengthSquared); + return NiPoint3(current.x + dx / length * maxDistanceDelta, current.y + dy / length * maxDistanceDelta, current.z + dz / length * maxDistanceDelta); } //This code is yoinked from the MS XNA code, so it should be right, even if it's horrible. NiPoint3 NiPoint3::RotateByQuaternion(const NiQuaternion& rotation) { - Vector3 vector; - float num12 = rotation.x + rotation.x; - float num2 = rotation.y + rotation.y; - float num = rotation.z + rotation.z; - float num11 = rotation.w * num12; - float num10 = rotation.w * num2; - float num9 = rotation.w * num; - float num8 = rotation.x * num12; - float num7 = rotation.x * num2; - float num6 = rotation.x * num; - float num5 = rotation.y * num2; - float num4 = rotation.y * num; - float num3 = rotation.z * num; + Vector3 vector; + float num12 = rotation.x + rotation.x; + float num2 = rotation.y + rotation.y; + float num = rotation.z + rotation.z; + float num11 = rotation.w * num12; + float num10 = rotation.w * num2; + float num9 = rotation.w * num; + float num8 = rotation.x * num12; + float num7 = rotation.x * num2; + float num6 = rotation.x * num; + float num5 = rotation.y * num2; + float num4 = rotation.y * num; + float num3 = rotation.z * num; - NiPoint3 value = *this; - float num15 = ((value.x * ((1.0f - num5) - num3)) + (value.y * (num7 - num9))) + (value.z * (num6 + num10)); - float num14 = ((value.x * (num7 + num9)) + (value.y * ((1.0f - num8) - num3))) + (value.z * (num4 - num11)); - float num13 = ((value.x * (num6 - num10)) + (value.y * (num4 + num11))) + (value.z * ((1.0f - num8) - num5)); - vector.x = num15; - vector.y = num14; - vector.z = num13; - return vector; -} \ No newline at end of file + NiPoint3 value = *this; + float num15 = ((value.x * ((1.0f - num5) - num3)) + (value.y * (num7 - num9))) + (value.z * (num6 + num10)); + float num14 = ((value.x * (num7 + num9)) + (value.y * ((1.0f - num8) - num3))) + (value.z * (num4 - num11)); + float num13 = ((value.x * (num6 - num10)) + (value.y * (num4 + num11))) + (value.z * ((1.0f - num8) - num5)); + vector.x = num15; + vector.y = num14; + vector.z = num13; + return vector; +} diff --git a/dCommon/NiPoint3.h b/dCommon/NiPoint3.h index 24e4e617..6c0b9d3d 100644 --- a/dCommon/NiPoint3.h +++ b/dCommon/NiPoint3.h @@ -12,177 +12,177 @@ typedef NiPoint3 Vector3; //!< The Vector3 class is technically the NiPoin //! A custom class the defines a point in space class NiPoint3 { public: - float x; //!< The x position - float y; //!< The y position - float z; //!< The z position + float x; //!< The x position + float y; //!< The y position + float z; //!< The z position - //! Initializer - NiPoint3(void); + //! Initializer + NiPoint3(void); - //! Initializer - /*! - \param x The x coordinate - \param y The y coordinate - \param z The z coordinate - */ - NiPoint3(float x, float y, float z); + //! Initializer + /*! + \param x The x coordinate + \param y The y coordinate + \param z The z coordinate + */ + NiPoint3(float x, float y, float z); - //! Copy Constructor - /*! - \param point The point to copy - */ - NiPoint3(const NiPoint3& point); + //! Copy Constructor + /*! + \param point The point to copy + */ + NiPoint3(const NiPoint3& point); - //! Destructor - ~NiPoint3(void); + //! Destructor + ~NiPoint3(void); - // MARK: Constants - static const NiPoint3 ZERO; //!< Point(0, 0, 0) - static const NiPoint3 UNIT_X; //!< Point(1, 0, 0) - static const NiPoint3 UNIT_Y; //!< Point(0, 1, 0) - static const NiPoint3 UNIT_Z; //!< Point(0, 0, 1) - static const NiPoint3 UNIT_ALL; //!< Point(1, 1, 1) + // MARK: Constants + static const NiPoint3 ZERO; //!< Point(0, 0, 0) + static const NiPoint3 UNIT_X; //!< Point(1, 0, 0) + static const NiPoint3 UNIT_Y; //!< Point(0, 1, 0) + static const NiPoint3 UNIT_Z; //!< Point(0, 0, 1) + static const NiPoint3 UNIT_ALL; //!< Point(1, 1, 1) - // MARK: Getters / Setters + // MARK: Getters / Setters - //! Gets the X coordinate - /*! - \return The x coordinate - */ - float GetX(void) const; + //! Gets the X coordinate + /*! + \return The x coordinate + */ + float GetX(void) const; - //! Sets the X coordinate - /*! - \param x The x coordinate - */ - void SetX(float x); + //! Sets the X coordinate + /*! + \param x The x coordinate + */ + void SetX(float x); - //! Gets the Y coordinate - /*! - \return The y coordinate - */ - float GetY(void) const; + //! Gets the Y coordinate + /*! + \return The y coordinate + */ + float GetY(void) const; - //! Sets the Y coordinate - /*! - \param y The y coordinate - */ - void SetY(float y); + //! Sets the Y coordinate + /*! + \param y The y coordinate + */ + void SetY(float y); - //! Gets the Z coordinate - /*! - \return The z coordinate - */ - float GetZ(void) const; + //! Gets the Z coordinate + /*! + \return The z coordinate + */ + float GetZ(void) const; - //! Sets the Z coordinate - /*! - \param z The z coordinate - */ - void SetZ(float z); + //! Sets the Z coordinate + /*! + \param z The z coordinate + */ + void SetZ(float z); - // MARK: Member Functions + // MARK: Member Functions - //! Gets the length of the vector - /*! - \return The scalar length of the vector - */ - float Length(void) const; + //! Gets the length of the vector + /*! + \return The scalar length of the vector + */ + float Length(void) const; - //! Gets the squared length of a vector - /*! - \return The squared length of a vector - */ - float SquaredLength(void) const; + //! Gets the squared length of a vector + /*! + \return The squared length of a vector + */ + float SquaredLength(void) const; - //! Returns the dot product of the vector dotted with another vector - /*! - \param vec The second vector - \return The dot product of the two vectors - */ - float DotProduct(const Vector3& vec) const; + //! Returns the dot product of the vector dotted with another vector + /*! + \param vec The second vector + \return The dot product of the two vectors + */ + float DotProduct(const Vector3& vec) const; - //! Returns the cross product of the vector crossed with another vector - /*! - \param vec The second vector - \return The cross product of the two vectors - */ - Vector3 CrossProduct(const Vector3& vec) const; + //! Returns the cross product of the vector crossed with another vector + /*! + \param vec The second vector + \return The cross product of the two vectors + */ + Vector3 CrossProduct(const Vector3& vec) const; - //! Unitize the vector - /*! - \returns The current vector - */ - NiPoint3 Unitize(void) const; + //! Unitize the vector + /*! + \returns The current vector + */ + NiPoint3 Unitize(void) const; - // MARK: Operators + // MARK: Operators - //! Operator to check for equality - bool operator==(const NiPoint3& point) const; + //! Operator to check for equality + bool operator==(const NiPoint3& point) const; - //! Operator to check for inequality - bool operator!=(const NiPoint3& point) const; + //! Operator to check for inequality + bool operator!=(const NiPoint3& point) const; - //! Operator for subscripting - float& operator[](int i); + //! Operator for subscripting + float& operator[](int i); - //! Operator for subscripting - const float& operator[](int i) const; + //! Operator for subscripting + const float& operator[](int i) const; - //! Operator for addition of vectors - NiPoint3 operator+(const NiPoint3& point) const; + //! Operator for addition of vectors + NiPoint3 operator+(const NiPoint3& point) const; - //! Operator for subtraction of vectors - NiPoint3 operator-(const NiPoint3& point) const; + //! Operator for subtraction of vectors + NiPoint3 operator-(const NiPoint3& point) const; - //! Operator for addition of a scalar on all vector components - NiPoint3 operator+(float fScalar) const; + //! Operator for addition of a scalar on all vector components + NiPoint3 operator+(float fScalar) const; - //! Operator for subtraction of a scalar on all vector components - NiPoint3 operator-(float fScalar) const; + //! Operator for subtraction of a scalar on all vector components + NiPoint3 operator-(float fScalar) const; - //! Operator for scalar multiplication of a vector - NiPoint3 operator*(float fScalar) const; + //! Operator for scalar multiplication of a vector + NiPoint3 operator*(float fScalar) const; - //! Operator for scalar division of a vector - NiPoint3 operator/(float fScalar) const; + //! Operator for scalar division of a vector + NiPoint3 operator/(float fScalar) const; - // MARK: Helper Functions + // MARK: Helper Functions - //! Checks to see if the point (or vector) is with an Axis-Aligned Bounding Box - /*! - \param minPoint The minimum point of the bounding box - \param maxPoint The maximum point of the bounding box - \return Whether or not this point lies within the box - */ - bool IsWithinAxisAlignedBox(const NiPoint3& minPoint, const NiPoint3& maxPoint); + //! Checks to see if the point (or vector) is with an Axis-Aligned Bounding Box + /*! + \param minPoint The minimum point of the bounding box + \param maxPoint The maximum point of the bounding box + \return Whether or not this point lies within the box + */ + bool IsWithinAxisAlignedBox(const NiPoint3& minPoint, const NiPoint3& maxPoint); - //! Checks to see if the point (or vector) is within a sphere - /*! - \param sphereCenter The sphere center - \param radius The radius - */ - bool IsWithinSpehere(const NiPoint3& sphereCenter, float radius); + //! Checks to see if the point (or vector) is within a sphere + /*! + \param sphereCenter The sphere center + \param radius The radius + */ + bool IsWithinSpehere(const NiPoint3& sphereCenter, float radius); - /*! - \param a Start of line - \param b End of line - \param p Refrence point - \return The point of line AB which is closest to P - */ - static NiPoint3 ClosestPointOnLine(const NiPoint3& a, const NiPoint3& b, const NiPoint3& p); + /*! + \param a Start of line + \param b End of line + \param p Refrence point + \return The point of line AB which is closest to P + */ + static NiPoint3 ClosestPointOnLine(const NiPoint3& a, const NiPoint3& b, const NiPoint3& p); - static float Angle(const NiPoint3& a, const NiPoint3& b); + static float Angle(const NiPoint3& a, const NiPoint3& b); - static float Distance(const NiPoint3& a, const NiPoint3& b); - - static float DistanceSquared(const NiPoint3& a, const NiPoint3& b); + static float Distance(const NiPoint3& a, const NiPoint3& b); - static NiPoint3 MoveTowards(const NiPoint3& current, const NiPoint3& target, float maxDistanceDelta); + static float DistanceSquared(const NiPoint3& a, const NiPoint3& b); - NiPoint3 RotateByQuaternion(const NiQuaternion& rotation); + static NiPoint3 MoveTowards(const NiPoint3& current, const NiPoint3& target, float maxDistanceDelta); + + NiPoint3 RotateByQuaternion(const NiQuaternion& rotation); }; diff --git a/dCommon/NiQuaternion.cpp b/dCommon/NiQuaternion.cpp index a8aa1dc8..33c5c976 100644 --- a/dCommon/NiQuaternion.cpp +++ b/dCommon/NiQuaternion.cpp @@ -8,18 +8,18 @@ const NiQuaternion NiQuaternion::IDENTITY(1, 0, 0, 0); //! The initializer NiQuaternion::NiQuaternion(void) { - this->w = 1; - this->x = 0; - this->y = 0; - this->z = 0; + this->w = 1; + this->x = 0; + this->y = 0; + this->z = 0; } //! The initializer NiQuaternion::NiQuaternion(float w, float x, float y, float z) { - this->w = w; - this->x = x; - this->y = y; - this->z = z; + this->w = w; + this->x = x; + this->y = y; + this->z = z; } //! Destructor @@ -30,42 +30,42 @@ NiQuaternion::~NiQuaternion(void) {} //! Gets the W coordinate float NiQuaternion::GetW(void) const { - return this->w; + return this->w; } //! Sets the W coordinate void NiQuaternion::SetW(float w) { - this->w = w; + this->w = w; } //! Gets the X coordinate float NiQuaternion::GetX(void) const { - return this->x; + return this->x; } //! Sets the X coordinate void NiQuaternion::SetX(float x) { - this->x = x; + this->x = x; } //! Gets the Y coordinate float NiQuaternion::GetY(void) const { - return this->y; + return this->y; } //! Sets the Y coordinate void NiQuaternion::SetY(float y) { - this->y = y; + this->y = y; } //! Gets the Z coordinate float NiQuaternion::GetZ(void) const { - return this->z; + return this->z; } //! Sets the Z coordinate void NiQuaternion::SetZ(float z) { - this->z = z; + this->z = z; } @@ -73,55 +73,54 @@ void NiQuaternion::SetZ(float z) { //! Returns the forward vector from the quaternion Vector3 NiQuaternion::GetForwardVector(void) const { - return Vector3(2 * (x * z + w * y), 2 * (y * z - w * x), 1 - 2 * (x * x + y * y)); + return Vector3(2 * (x * z + w * y), 2 * (y * z - w * x), 1 - 2 * (x * x + y * y)); } //! Returns the up vector from the quaternion Vector3 NiQuaternion::GetUpVector(void) const { - return Vector3(2 * (x * y - w * z), 1 - 2 * (x * x + z * z), 2 * (y * z + w * x)); + return Vector3(2 * (x * y - w * z), 1 - 2 * (x * x + z * z), 2 * (y * z + w * x)); } //! Returns the right vector from the quaternion Vector3 NiQuaternion::GetRightVector(void) const { - return Vector3(1 - 2 * (y * y + z * z), 2 * (x * y + w * z), 2 * (x * z - w * y)); + return Vector3(1 - 2 * (y * y + z * z), 2 * (x * y + w * z), 2 * (x * z - w * y)); } Vector3 NiQuaternion::GetEulerAngles() const { - Vector3 angles; + Vector3 angles; - // roll (x-axis rotation) - const float sinr_cosp = 2 * (w * x + y * z); - const float cosr_cosp = 1 - 2 * (x * x + y * y); - angles.x = std::atan2(sinr_cosp, cosr_cosp); + // roll (x-axis rotation) + const float sinr_cosp = 2 * (w * x + y * z); + const float cosr_cosp = 1 - 2 * (x * x + y * y); + angles.x = std::atan2(sinr_cosp, cosr_cosp); - // pitch (y-axis rotation) - const float sinp = 2 * (w * y - z * x); - - if (std::abs(sinp) >= 1) { - angles.y = std::copysign(3.14 / 2, sinp); // use 90 degrees if out of range - } - else { - angles.y = std::asin(sinp); - } + // pitch (y-axis rotation) + const float sinp = 2 * (w * y - z * x); - // yaw (z-axis rotation) - const float siny_cosp = 2 * (w * z + x * y); - const float cosy_cosp = 1 - 2 * (y * y + z * z); - angles.z = std::atan2(siny_cosp, cosy_cosp); + if (std::abs(sinp) >= 1) { + angles.y = std::copysign(3.14 / 2, sinp); // use 90 degrees if out of range + } else { + angles.y = std::asin(sinp); + } - return angles; + // yaw (z-axis rotation) + const float siny_cosp = 2 * (w * z + x * y); + const float cosy_cosp = 1 - 2 * (y * y + z * z); + angles.z = std::atan2(siny_cosp, cosy_cosp); + + return angles; } // MARK: Operators //! Operator to check for equality bool NiQuaternion::operator==(const NiQuaternion& rot) const { - return rot.x == this->x && rot.y == this->y && rot.z == this->z && rot.w == this->w; + return rot.x == this->x && rot.y == this->y && rot.z == this->z && rot.w == this->w; } //! Operator to check for inequality bool NiQuaternion::operator!=(const NiQuaternion& rot) const { - return !(*this == rot); + return !(*this == rot); } @@ -135,65 +134,63 @@ NiQuaternion NiQuaternion::LookAt(const NiPoint3& sourcePoint, const NiPoint3& d source.y = 0.0f; dest.y = 0.0f; - NiPoint3 forwardVector = NiPoint3(dest - source).Unitize(); - - NiPoint3 posZ = NiPoint3::UNIT_Z; - NiPoint3 vecA = posZ.CrossProduct(forwardVector).Unitize(); - - float dot = posZ.DotProduct(forwardVector); - float rotAngle = static_cast(acos(dot)); - - NiPoint3 vecB = vecA.CrossProduct(posZ); - - if (vecB.DotProduct(forwardVector) < 0) rotAngle = -rotAngle; - return NiQuaternion::CreateFromAxisAngle(vecA, rotAngle); + NiPoint3 forwardVector = NiPoint3(dest - source).Unitize(); + + NiPoint3 posZ = NiPoint3::UNIT_Z; + NiPoint3 vecA = posZ.CrossProduct(forwardVector).Unitize(); + + float dot = posZ.DotProduct(forwardVector); + float rotAngle = static_cast(acos(dot)); + + NiPoint3 vecB = vecA.CrossProduct(posZ); + + if (vecB.DotProduct(forwardVector) < 0) rotAngle = -rotAngle; + return NiQuaternion::CreateFromAxisAngle(vecA, rotAngle); } -NiQuaternion NiQuaternion::LookAtUnlocked(const NiPoint3& sourcePoint, const NiPoint3& destPoint) -{ - NiPoint3 forwardVector = NiPoint3(destPoint - sourcePoint).Unitize(); - - NiPoint3 posZ = NiPoint3::UNIT_Z; - NiPoint3 vecA = posZ.CrossProduct(forwardVector).Unitize(); - - float dot = posZ.DotProduct(forwardVector); - float rotAngle = static_cast(acos(dot)); - - NiPoint3 vecB = vecA.CrossProduct(posZ); - - if (vecB.DotProduct(forwardVector) < 0) rotAngle = -rotAngle; - return NiQuaternion::CreateFromAxisAngle(vecA, rotAngle); +NiQuaternion NiQuaternion::LookAtUnlocked(const NiPoint3& sourcePoint, const NiPoint3& destPoint) { + NiPoint3 forwardVector = NiPoint3(destPoint - sourcePoint).Unitize(); + + NiPoint3 posZ = NiPoint3::UNIT_Z; + NiPoint3 vecA = posZ.CrossProduct(forwardVector).Unitize(); + + float dot = posZ.DotProduct(forwardVector); + float rotAngle = static_cast(acos(dot)); + + NiPoint3 vecB = vecA.CrossProduct(posZ); + + if (vecB.DotProduct(forwardVector) < 0) rotAngle = -rotAngle; + return NiQuaternion::CreateFromAxisAngle(vecA, rotAngle); } //! Creates a Quaternion from a specific axis and angle relative to that axis NiQuaternion NiQuaternion::CreateFromAxisAngle(const Vector3& axis, float angle) { - float halfAngle = angle * 0.5f; - float s = static_cast(sin(halfAngle)); - - NiQuaternion q; - q.x = axis.GetX() * s; - q.y = axis.GetY() * s; - q.z = axis.GetZ() * s; - q.w = static_cast(cos(halfAngle)); - - return q; + float halfAngle = angle * 0.5f; + float s = static_cast(sin(halfAngle)); + + NiQuaternion q; + q.x = axis.GetX() * s; + q.y = axis.GetY() * s; + q.z = axis.GetZ() * s; + q.w = static_cast(cos(halfAngle)); + + return q; } -NiQuaternion NiQuaternion::FromEulerAngles(const NiPoint3& eulerAngles) -{ - // Abbreviations for the various angular functions - float cy = cos(eulerAngles.z * 0.5); - float sy = sin(eulerAngles.z * 0.5); - float cp = cos(eulerAngles.y * 0.5); - float sp = sin(eulerAngles.y * 0.5); - float cr = cos(eulerAngles.x * 0.5); - float sr = sin(eulerAngles.x * 0.5); +NiQuaternion NiQuaternion::FromEulerAngles(const NiPoint3& eulerAngles) { + // Abbreviations for the various angular functions + float cy = cos(eulerAngles.z * 0.5); + float sy = sin(eulerAngles.z * 0.5); + float cp = cos(eulerAngles.y * 0.5); + float sp = sin(eulerAngles.y * 0.5); + float cr = cos(eulerAngles.x * 0.5); + float sr = sin(eulerAngles.x * 0.5); - NiQuaternion q; - q.w = cr * cp * cy + sr * sp * sy; - q.x = sr * cp * cy - cr * sp * sy; - q.y = cr * sp * cy + sr * cp * sy; - q.z = cr * cp * sy - sr * sp * cy; + NiQuaternion q; + q.w = cr * cp * cy + sr * sp * sy; + q.x = sr * cp * cy - cr * sp * sy; + q.y = cr * sp * cy + sr * cp * sy; + q.z = cr * cp * sy - sr * sp * cy; - return q; + return q; } diff --git a/dCommon/NiQuaternion.h b/dCommon/NiQuaternion.h index f479501a..b7d60f4e 100644 --- a/dCommon/NiQuaternion.h +++ b/dCommon/NiQuaternion.h @@ -14,138 +14,138 @@ typedef NiQuaternion Quaternion; //!< A typedef for a shorthand version o //! A class that defines a rotation in space class NiQuaternion { public: - float w; //!< The w coordinate - float x; //!< The x coordinate - float y; //!< The y coordinate - float z; //!< The z coordinate - - - //! The initializer - NiQuaternion(void); - - //! The initializer - /*! - \param w The w coordinate - \param x The x coordinate - \param y The y coordinate - \param z The z coordinate - */ - NiQuaternion(float w, float x, float y, float z); - - //! Destructor - ~NiQuaternion(void); - - // MARK: Constants - static const NiQuaternion IDENTITY; //!< Quaternion(1, 0, 0, 0) - - // MARK: Setters / Getters - - //! Gets the W coordinate - /*! - \return The w coordinate - */ - float GetW(void) const; - - //! Sets the W coordinate - /*! - \param w The w coordinate - */ - void SetW(float w); - - //! Gets the X coordinate - /*! - \return The x coordinate - */ - float GetX(void) const; - - //! Sets the X coordinate - /*! - \param x The x coordinate - */ - void SetX(float x); - - //! Gets the Y coordinate - /*! - \return The y coordinate - */ - float GetY(void) const; - - //! Sets the Y coordinate - /*! - \param y The y coordinate - */ - void SetY(float y); - - //! Gets the Z coordinate - /*! - \return The z coordinate - */ - float GetZ(void) const; - - //! Sets the Z coordinate - /*! - \param z The z coordinate - */ - void SetZ(float z); - - - // MARK: Member Functions - - //! Returns the forward vector from the quaternion - /*! - \return The forward vector of the quaternion - */ - Vector3 GetForwardVector(void) const; - - //! Returns the up vector from the quaternion - /*! - \return The up vector fo the quaternion - */ - Vector3 GetUpVector(void) const; - - //! Returns the right vector from the quaternion - /*! - \return The right vector of the quaternion - */ - Vector3 GetRightVector(void) const; + float w; //!< The w coordinate + float x; //!< The x coordinate + float y; //!< The y coordinate + float z; //!< The z coordinate - Vector3 GetEulerAngles() const; - - - // MARK: Operators - - //! Operator to check for equality - bool operator==(const NiQuaternion& rot) const; - - //! Operator to check for inequality - bool operator!=(const NiQuaternion& rot) const; - - - // MARK: Helper Functions - - //! Look from a specific point in space to another point in space (Y-locked) - /*! - \param sourcePoint The source location - \param destPoint The destination location - \return The Quaternion with the rotation towards the destination - */ - static NiQuaternion LookAt(const NiPoint3& sourcePoint, const NiPoint3& destPoint); - - //! Look from a specific point in space to another point in space - /*! - \param sourcePoint The source location - \param destPoint The destination location - \return The Quaternion with the rotation towards the destination - */ - static NiQuaternion LookAtUnlocked(const NiPoint3& sourcePoint, const NiPoint3& destPoint); - - //! Creates a Quaternion from a specific axis and angle relative to that axis - /*! - \param axis The axis that is used - \param angle The angle relative to this axis - \return A quaternion created from the axis and angle - */ - static NiQuaternion CreateFromAxisAngle(const Vector3& axis, float angle); - static NiQuaternion FromEulerAngles(const NiPoint3& eulerAngles); + //! The initializer + NiQuaternion(void); + + //! The initializer + /*! + \param w The w coordinate + \param x The x coordinate + \param y The y coordinate + \param z The z coordinate + */ + NiQuaternion(float w, float x, float y, float z); + + //! Destructor + ~NiQuaternion(void); + + // MARK: Constants + static const NiQuaternion IDENTITY; //!< Quaternion(1, 0, 0, 0) + + // MARK: Setters / Getters + + //! Gets the W coordinate + /*! + \return The w coordinate + */ + float GetW(void) const; + + //! Sets the W coordinate + /*! + \param w The w coordinate + */ + void SetW(float w); + + //! Gets the X coordinate + /*! + \return The x coordinate + */ + float GetX(void) const; + + //! Sets the X coordinate + /*! + \param x The x coordinate + */ + void SetX(float x); + + //! Gets the Y coordinate + /*! + \return The y coordinate + */ + float GetY(void) const; + + //! Sets the Y coordinate + /*! + \param y The y coordinate + */ + void SetY(float y); + + //! Gets the Z coordinate + /*! + \return The z coordinate + */ + float GetZ(void) const; + + //! Sets the Z coordinate + /*! + \param z The z coordinate + */ + void SetZ(float z); + + + // MARK: Member Functions + + //! Returns the forward vector from the quaternion + /*! + \return The forward vector of the quaternion + */ + Vector3 GetForwardVector(void) const; + + //! Returns the up vector from the quaternion + /*! + \return The up vector fo the quaternion + */ + Vector3 GetUpVector(void) const; + + //! Returns the right vector from the quaternion + /*! + \return The right vector of the quaternion + */ + Vector3 GetRightVector(void) const; + + Vector3 GetEulerAngles() const; + + + // MARK: Operators + + //! Operator to check for equality + bool operator==(const NiQuaternion& rot) const; + + //! Operator to check for inequality + bool operator!=(const NiQuaternion& rot) const; + + + // MARK: Helper Functions + + //! Look from a specific point in space to another point in space (Y-locked) + /*! + \param sourcePoint The source location + \param destPoint The destination location + \return The Quaternion with the rotation towards the destination + */ + static NiQuaternion LookAt(const NiPoint3& sourcePoint, const NiPoint3& destPoint); + + //! Look from a specific point in space to another point in space + /*! + \param sourcePoint The source location + \param destPoint The destination location + \return The Quaternion with the rotation towards the destination + */ + static NiQuaternion LookAtUnlocked(const NiPoint3& sourcePoint, const NiPoint3& destPoint); + + //! Creates a Quaternion from a specific axis and angle relative to that axis + /*! + \param axis The axis that is used + \param angle The angle relative to this axis + \return A quaternion created from the axis and angle + */ + static NiQuaternion CreateFromAxisAngle(const Vector3& axis, float angle); + + static NiQuaternion FromEulerAngles(const NiPoint3& eulerAngles); }; diff --git a/dCommon/PermissionMap.h b/dCommon/PermissionMap.h index 177f4884..8c271f17 100644 --- a/dCommon/PermissionMap.h +++ b/dCommon/PermissionMap.h @@ -7,36 +7,36 @@ */ enum class PermissionMap : uint64_t { - /** - * Reserved for future use, bit 0-3. - */ + /** + * Reserved for future use, bit 0-3. + */ - /** - * The character has restricted trade acccess, bit 4. - */ - RestrictedTradeAccess = 0x1 << 4, + /** + * The character has restricted trade acccess, bit 4. + */ + RestrictedTradeAccess = 0x1 << 4, - /** - * The character has restricted mail access, bit 5. - */ - RestrictedMailAccess = 0x1 << 5, + /** + * The character has restricted mail access, bit 5. + */ + RestrictedMailAccess = 0x1 << 5, - /** - * The character has restricted chat access, bit 6. - */ - RestrictedChatAccess = 0x1 << 6, + /** + * The character has restricted chat access, bit 6. + */ + RestrictedChatAccess = 0x1 << 6, - // - // Combined permissions - // + // + // Combined permissions + // - /** - * The character is marked as 'old', restricted from trade and mail. - */ - Old = RestrictedTradeAccess | RestrictedMailAccess, + /** + * The character is marked as 'old', restricted from trade and mail. + */ + Old = RestrictedTradeAccess | RestrictedMailAccess, - /** - * The character is soft banned, restricted from trade, mail, and chat. - */ - SoftBanned = RestrictedTradeAccess | RestrictedMailAccess | RestrictedChatAccess, + /** + * The character is soft banned, restricted from trade, mail, and chat. + */ + SoftBanned = RestrictedTradeAccess | RestrictedMailAccess | RestrictedChatAccess, }; diff --git a/dCommon/SHA512.cpp b/dCommon/SHA512.cpp index 6daf44f6..f5a71d99 100644 --- a/dCommon/SHA512.cpp +++ b/dCommon/SHA512.cpp @@ -5,153 +5,148 @@ const unsigned long long SHA512::sha512_k[80] = //ULL = uint64 { 0x428a2f98d728ae22ULL, 0x7137449123ef65cdULL, - 0xb5c0fbcfec4d3b2fULL, 0xe9b5dba58189dbbcULL, - 0x3956c25bf348b538ULL, 0x59f111f1b605d019ULL, - 0x923f82a4af194f9bULL, 0xab1c5ed5da6d8118ULL, - 0xd807aa98a3030242ULL, 0x12835b0145706fbeULL, - 0x243185be4ee4b28cULL, 0x550c7dc3d5ffb4e2ULL, - 0x72be5d74f27b896fULL, 0x80deb1fe3b1696b1ULL, - 0x9bdc06a725c71235ULL, 0xc19bf174cf692694ULL, - 0xe49b69c19ef14ad2ULL, 0xefbe4786384f25e3ULL, - 0x0fc19dc68b8cd5b5ULL, 0x240ca1cc77ac9c65ULL, - 0x2de92c6f592b0275ULL, 0x4a7484aa6ea6e483ULL, - 0x5cb0a9dcbd41fbd4ULL, 0x76f988da831153b5ULL, - 0x983e5152ee66dfabULL, 0xa831c66d2db43210ULL, - 0xb00327c898fb213fULL, 0xbf597fc7beef0ee4ULL, - 0xc6e00bf33da88fc2ULL, 0xd5a79147930aa725ULL, - 0x06ca6351e003826fULL, 0x142929670a0e6e70ULL, - 0x27b70a8546d22ffcULL, 0x2e1b21385c26c926ULL, - 0x4d2c6dfc5ac42aedULL, 0x53380d139d95b3dfULL, - 0x650a73548baf63deULL, 0x766a0abb3c77b2a8ULL, - 0x81c2c92e47edaee6ULL, 0x92722c851482353bULL, - 0xa2bfe8a14cf10364ULL, 0xa81a664bbc423001ULL, - 0xc24b8b70d0f89791ULL, 0xc76c51a30654be30ULL, - 0xd192e819d6ef5218ULL, 0xd69906245565a910ULL, - 0xf40e35855771202aULL, 0x106aa07032bbd1b8ULL, - 0x19a4c116b8d2d0c8ULL, 0x1e376c085141ab53ULL, - 0x2748774cdf8eeb99ULL, 0x34b0bcb5e19b48a8ULL, - 0x391c0cb3c5c95a63ULL, 0x4ed8aa4ae3418acbULL, - 0x5b9cca4f7763e373ULL, 0x682e6ff3d6b2b8a3ULL, - 0x748f82ee5defb2fcULL, 0x78a5636f43172f60ULL, - 0x84c87814a1f0ab72ULL, 0x8cc702081a6439ecULL, - 0x90befffa23631e28ULL, 0xa4506cebde82bde9ULL, - 0xbef9a3f7b2c67915ULL, 0xc67178f2e372532bULL, - 0xca273eceea26619cULL, 0xd186b8c721c0c207ULL, - 0xeada7dd6cde0eb1eULL, 0xf57d4f7fee6ed178ULL, - 0x06f067aa72176fbaULL, 0x0a637dc5a2c898a6ULL, - 0x113f9804bef90daeULL, 0x1b710b35131c471bULL, - 0x28db77f523047d84ULL, 0x32caab7b40c72493ULL, - 0x3c9ebe0a15c9bebcULL, 0x431d67c49c100d4cULL, - 0x4cc5d4becb3e42b6ULL, 0x597f299cfc657e2aULL, - 0x5fcb6fab3ad6faecULL, 0x6c44198c4a475817ULL }; + 0xb5c0fbcfec4d3b2fULL, 0xe9b5dba58189dbbcULL, + 0x3956c25bf348b538ULL, 0x59f111f1b605d019ULL, + 0x923f82a4af194f9bULL, 0xab1c5ed5da6d8118ULL, + 0xd807aa98a3030242ULL, 0x12835b0145706fbeULL, + 0x243185be4ee4b28cULL, 0x550c7dc3d5ffb4e2ULL, + 0x72be5d74f27b896fULL, 0x80deb1fe3b1696b1ULL, + 0x9bdc06a725c71235ULL, 0xc19bf174cf692694ULL, + 0xe49b69c19ef14ad2ULL, 0xefbe4786384f25e3ULL, + 0x0fc19dc68b8cd5b5ULL, 0x240ca1cc77ac9c65ULL, + 0x2de92c6f592b0275ULL, 0x4a7484aa6ea6e483ULL, + 0x5cb0a9dcbd41fbd4ULL, 0x76f988da831153b5ULL, + 0x983e5152ee66dfabULL, 0xa831c66d2db43210ULL, + 0xb00327c898fb213fULL, 0xbf597fc7beef0ee4ULL, + 0xc6e00bf33da88fc2ULL, 0xd5a79147930aa725ULL, + 0x06ca6351e003826fULL, 0x142929670a0e6e70ULL, + 0x27b70a8546d22ffcULL, 0x2e1b21385c26c926ULL, + 0x4d2c6dfc5ac42aedULL, 0x53380d139d95b3dfULL, + 0x650a73548baf63deULL, 0x766a0abb3c77b2a8ULL, + 0x81c2c92e47edaee6ULL, 0x92722c851482353bULL, + 0xa2bfe8a14cf10364ULL, 0xa81a664bbc423001ULL, + 0xc24b8b70d0f89791ULL, 0xc76c51a30654be30ULL, + 0xd192e819d6ef5218ULL, 0xd69906245565a910ULL, + 0xf40e35855771202aULL, 0x106aa07032bbd1b8ULL, + 0x19a4c116b8d2d0c8ULL, 0x1e376c085141ab53ULL, + 0x2748774cdf8eeb99ULL, 0x34b0bcb5e19b48a8ULL, + 0x391c0cb3c5c95a63ULL, 0x4ed8aa4ae3418acbULL, + 0x5b9cca4f7763e373ULL, 0x682e6ff3d6b2b8a3ULL, + 0x748f82ee5defb2fcULL, 0x78a5636f43172f60ULL, + 0x84c87814a1f0ab72ULL, 0x8cc702081a6439ecULL, + 0x90befffa23631e28ULL, 0xa4506cebde82bde9ULL, + 0xbef9a3f7b2c67915ULL, 0xc67178f2e372532bULL, + 0xca273eceea26619cULL, 0xd186b8c721c0c207ULL, + 0xeada7dd6cde0eb1eULL, 0xf57d4f7fee6ed178ULL, + 0x06f067aa72176fbaULL, 0x0a637dc5a2c898a6ULL, + 0x113f9804bef90daeULL, 0x1b710b35131c471bULL, + 0x28db77f523047d84ULL, 0x32caab7b40c72493ULL, + 0x3c9ebe0a15c9bebcULL, 0x431d67c49c100d4cULL, + 0x4cc5d4becb3e42b6ULL, 0x597f299cfc657e2aULL, + 0x5fcb6fab3ad6faecULL, 0x6c44198c4a475817ULL }; -void SHA512::transform(const unsigned char *message, unsigned int block_nb) -{ - uint64 w[80]; - uint64 wv[8]; - uint64 t1, t2; - const unsigned char *sub_block; - int i, j; - for (i = 0; i < (int)block_nb; i++) { - sub_block = message + (i << 7); - for (j = 0; j < 16; j++) { - SHA2_PACK64(&sub_block[j << 3], &w[j]); - } - for (j = 16; j < 80; j++) { - w[j] = SHA512_F4(w[j - 2]) + w[j - 7] + SHA512_F3(w[j - 15]) + w[j - 16]; - } - for (j = 0; j < 8; j++) { - wv[j] = m_h[j]; - } - for (j = 0; j < 80; j++) { - t1 = wv[7] + SHA512_F2(wv[4]) + SHA2_CH(wv[4], wv[5], wv[6]) - + sha512_k[j] + w[j]; - t2 = SHA512_F1(wv[0]) + SHA2_MAJ(wv[0], wv[1], wv[2]); - wv[7] = wv[6]; - wv[6] = wv[5]; - wv[5] = wv[4]; - wv[4] = wv[3] + t1; - wv[3] = wv[2]; - wv[2] = wv[1]; - wv[1] = wv[0]; - wv[0] = t1 + t2; - } - for (j = 0; j < 8; j++) { - m_h[j] += wv[j]; - } - - } +void SHA512::transform(const unsigned char* message, unsigned int block_nb) { + uint64 w[80]; + uint64 wv[8]; + uint64 t1, t2; + const unsigned char* sub_block; + int i, j; + for (i = 0; i < (int)block_nb; i++) { + sub_block = message + (i << 7); + for (j = 0; j < 16; j++) { + SHA2_PACK64(&sub_block[j << 3], &w[j]); + } + for (j = 16; j < 80; j++) { + w[j] = SHA512_F4(w[j - 2]) + w[j - 7] + SHA512_F3(w[j - 15]) + w[j - 16]; + } + for (j = 0; j < 8; j++) { + wv[j] = m_h[j]; + } + for (j = 0; j < 80; j++) { + t1 = wv[7] + SHA512_F2(wv[4]) + SHA2_CH(wv[4], wv[5], wv[6]) + + sha512_k[j] + w[j]; + t2 = SHA512_F1(wv[0]) + SHA2_MAJ(wv[0], wv[1], wv[2]); + wv[7] = wv[6]; + wv[6] = wv[5]; + wv[5] = wv[4]; + wv[4] = wv[3] + t1; + wv[3] = wv[2]; + wv[2] = wv[1]; + wv[1] = wv[0]; + wv[0] = t1 + t2; + } + for (j = 0; j < 8; j++) { + m_h[j] += wv[j]; + } + + } } -void SHA512::init() -{ - m_h[0] = 0x6a09e667f3bcc908ULL; - m_h[1] = 0xbb67ae8584caa73bULL; - m_h[2] = 0x3c6ef372fe94f82bULL; - m_h[3] = 0xa54ff53a5f1d36f1ULL; - m_h[4] = 0x510e527fade682d1ULL; - m_h[5] = 0x9b05688c2b3e6c1fULL; - m_h[6] = 0x1f83d9abfb41bd6bULL; - m_h[7] = 0x5be0cd19137e2179ULL; - m_len = 0; - m_tot_len = 0; +void SHA512::init() { + m_h[0] = 0x6a09e667f3bcc908ULL; + m_h[1] = 0xbb67ae8584caa73bULL; + m_h[2] = 0x3c6ef372fe94f82bULL; + m_h[3] = 0xa54ff53a5f1d36f1ULL; + m_h[4] = 0x510e527fade682d1ULL; + m_h[5] = 0x9b05688c2b3e6c1fULL; + m_h[6] = 0x1f83d9abfb41bd6bULL; + m_h[7] = 0x5be0cd19137e2179ULL; + m_len = 0; + m_tot_len = 0; } -void SHA512::update(const unsigned char *message, unsigned int len) -{ - unsigned int block_nb; - unsigned int new_len, rem_len, tmp_len; - const unsigned char *shifted_message; - tmp_len = SHA384_512_BLOCK_SIZE - m_len; - rem_len = len < tmp_len ? len : tmp_len; - memcpy(&m_block[m_len], message, rem_len); - if (m_len + len < SHA384_512_BLOCK_SIZE) { - m_len += len; - return; - } - new_len = len - rem_len; - block_nb = new_len / SHA384_512_BLOCK_SIZE; - shifted_message = message + rem_len; - transform(m_block, 1); - transform(shifted_message, block_nb); - rem_len = new_len % SHA384_512_BLOCK_SIZE; - memcpy(m_block, &shifted_message[block_nb << 7], rem_len); - m_len = rem_len; - m_tot_len += (block_nb + 1) << 7; +void SHA512::update(const unsigned char* message, unsigned int len) { + unsigned int block_nb; + unsigned int new_len, rem_len, tmp_len; + const unsigned char* shifted_message; + tmp_len = SHA384_512_BLOCK_SIZE - m_len; + rem_len = len < tmp_len ? len : tmp_len; + memcpy(&m_block[m_len], message, rem_len); + if (m_len + len < SHA384_512_BLOCK_SIZE) { + m_len += len; + return; + } + new_len = len - rem_len; + block_nb = new_len / SHA384_512_BLOCK_SIZE; + shifted_message = message + rem_len; + transform(m_block, 1); + transform(shifted_message, block_nb); + rem_len = new_len % SHA384_512_BLOCK_SIZE; + memcpy(m_block, &shifted_message[block_nb << 7], rem_len); + m_len = rem_len; + m_tot_len += (block_nb + 1) << 7; } -void SHA512::final(unsigned char *digest) -{ - unsigned int block_nb; - unsigned int pm_len; - unsigned int len_b; - int i; - block_nb = 1 + ((SHA384_512_BLOCK_SIZE - 17) - < (m_len % SHA384_512_BLOCK_SIZE)); - len_b = (m_tot_len + m_len) << 3; - pm_len = block_nb << 7; - memset(m_block + m_len, 0, pm_len - m_len); - m_block[m_len] = 0x80; - SHA2_UNPACK32(len_b, m_block + pm_len - 4); - transform(m_block, block_nb); - for (i = 0; i < 8; i++) { - SHA2_UNPACK64(m_h[i], &digest[i << 3]); - } +void SHA512::final(unsigned char* digest) { + unsigned int block_nb; + unsigned int pm_len; + unsigned int len_b; + int i; + block_nb = 1 + ((SHA384_512_BLOCK_SIZE - 17) + < (m_len % SHA384_512_BLOCK_SIZE)); + len_b = (m_tot_len + m_len) << 3; + pm_len = block_nb << 7; + memset(m_block + m_len, 0, pm_len - m_len); + m_block[m_len] = 0x80; + SHA2_UNPACK32(len_b, m_block + pm_len - 4); + transform(m_block, block_nb); + for (i = 0; i < 8; i++) { + SHA2_UNPACK64(m_h[i], &digest[i << 3]); + } } -std::string sha512(std::string input) -{ - unsigned char digest[SHA512::DIGEST_SIZE]; - memset(digest, 0, SHA512::DIGEST_SIZE); - class SHA512 ctx; - ctx.init(); - ctx.update((unsigned char*)input.c_str(), input.length()); - ctx.final(digest); +std::string sha512(std::string input) { + unsigned char digest[SHA512::DIGEST_SIZE]; + memset(digest, 0, SHA512::DIGEST_SIZE); + class SHA512 ctx; + ctx.init(); + ctx.update((unsigned char*)input.c_str(), input.length()); + ctx.final(digest); - char buf[2 * SHA512::DIGEST_SIZE + 1]; - buf[2 * SHA512::DIGEST_SIZE] = 0; - for (int i = 0; i < SHA512::DIGEST_SIZE; i++) - sprintf(buf + i * 2, "%02x", digest[i]); + char buf[2 * SHA512::DIGEST_SIZE + 1]; + buf[2 * SHA512::DIGEST_SIZE] = 0; + for (int i = 0; i < SHA512::DIGEST_SIZE; i++) + sprintf(buf + i * 2, "%02x", digest[i]); - return std::string(buf); + return std::string(buf); } diff --git a/dCommon/SHA512.h b/dCommon/SHA512.h index aba80432..512fa645 100644 --- a/dCommon/SHA512.h +++ b/dCommon/SHA512.h @@ -5,25 +5,25 @@ class SHA512 { protected: - typedef unsigned char uint8; - typedef unsigned int uint32; - typedef unsigned long long uint64; - - const static uint64 sha512_k[]; - static const unsigned int SHA384_512_BLOCK_SIZE = (1024 / 8); - + typedef unsigned char uint8; + typedef unsigned int uint32; + typedef unsigned long long uint64; + + const static uint64 sha512_k[]; + static const unsigned int SHA384_512_BLOCK_SIZE = (1024 / 8); + public: - void init(); - void update(const unsigned char *message, unsigned int len); - void final(unsigned char *digest); - static const unsigned int DIGEST_SIZE = (512 / 8); - + void init(); + void update(const unsigned char* message, unsigned int len); + void final(unsigned char* digest); + static const unsigned int DIGEST_SIZE = (512 / 8); + protected: - void transform(const unsigned char *message, unsigned int block_nb); - unsigned int m_tot_len; - unsigned int m_len; - unsigned char m_block[2 * SHA384_512_BLOCK_SIZE]; - uint64 m_h[8]; + void transform(const unsigned char* message, unsigned int block_nb); + unsigned int m_tot_len; + unsigned int m_len; + unsigned char m_block[2 * SHA384_512_BLOCK_SIZE]; + uint64 m_h[8]; }; std::string sha512(std::string input); diff --git a/dCommon/Type.cpp b/dCommon/Type.cpp index f89d090e..5cce9d66 100644 --- a/dCommon/Type.cpp +++ b/dCommon/Type.cpp @@ -6,22 +6,22 @@ std::string demangle(const char* name) { - int status = -4; // some arbitrary value to eliminate the compiler warning + int status = -4; // some arbitrary value to eliminate the compiler warning - // enable c++11 by passing the flag -std=c++11 to g++ - std::unique_ptr res { - abi::__cxa_demangle(name, NULL, NULL, &status), - std::free - }; + // enable c++11 by passing the flag -std=c++11 to g++ + std::unique_ptr res{ + abi::__cxa_demangle(name, NULL, NULL, &status), + std::free + }; - return (status==0) ? res.get() : name ; + return (status == 0) ? res.get() : name; } #else // does nothing if not g++ std::string demangle(const char* name) { - return name; + return name; } #endif diff --git a/dCommon/Type.h b/dCommon/Type.h index ea26d2ce..552bb09f 100644 --- a/dCommon/Type.h +++ b/dCommon/Type.h @@ -8,5 +8,5 @@ std::string demangle(const char* name); template std::string type(const T& t) { - return demangle(typeid(t).name()); + return demangle(typeid(t).name()); } diff --git a/dCommon/ZCompression.cpp b/dCommon/ZCompression.cpp index 28588bb8..a82dc3c9 100644 --- a/dCommon/ZCompression.cpp +++ b/dCommon/ZCompression.cpp @@ -1,77 +1,73 @@ #include "ZCompression.h" -#ifndef _WIN32 +#ifndef _WIN32 #include -namespace ZCompression -{ - int32_t GetMaxCompressedLength(int32_t nLenSrc) - { - int32_t n16kBlocks = (nLenSrc + 16383) / 16384; // round up any fraction of a block - return (nLenSrc + 6 + (n16kBlocks * 5)); - } +namespace ZCompression { + int32_t GetMaxCompressedLength(int32_t nLenSrc) { + int32_t n16kBlocks = (nLenSrc + 16383) / 16384; // round up any fraction of a block + return (nLenSrc + 6 + (n16kBlocks * 5)); + } - int32_t Compress(const uint8_t* abSrc, int32_t nLenSrc, uint8_t* abDst, int32_t nLenDst) - { - z_stream zInfo = { 0 }; - zInfo.total_in = zInfo.avail_in = nLenSrc; - zInfo.total_out = zInfo.avail_out = nLenDst; - zInfo.next_in = const_cast(abSrc); - zInfo.next_out = abDst; + int32_t Compress(const uint8_t* abSrc, int32_t nLenSrc, uint8_t* abDst, int32_t nLenDst) { + z_stream zInfo = { 0 }; + zInfo.total_in = zInfo.avail_in = nLenSrc; + zInfo.total_out = zInfo.avail_out = nLenDst; + zInfo.next_in = const_cast(abSrc); + zInfo.next_out = abDst; - int nErr, nRet = -1; - nErr = deflateInit(&zInfo, Z_DEFAULT_COMPRESSION); // zlib function - if (nErr == Z_OK) { - nErr = deflate(&zInfo, Z_FINISH); // zlib function - if (nErr == Z_STREAM_END) { - nRet = zInfo.total_out; - } - } - deflateEnd(&zInfo); // zlib function - return(nRet); + int nErr, nRet = -1; + nErr = deflateInit(&zInfo, Z_DEFAULT_COMPRESSION); // zlib function + if (nErr == Z_OK) { + nErr = deflate(&zInfo, Z_FINISH); // zlib function + if (nErr == Z_STREAM_END) { + nRet = zInfo.total_out; + } + } + deflateEnd(&zInfo); // zlib function + return(nRet); - } + } - int32_t Decompress(const uint8_t* abSrc, int32_t nLenSrc, uint8_t* abDst, int32_t nLenDst, int32_t& nErr) - { - // Get the size of the decompressed data - z_stream zInfo = { 0 }; - zInfo.total_in = zInfo.avail_in = nLenSrc; - zInfo.total_out = zInfo.avail_out = nLenDst; - zInfo.next_in = const_cast(abSrc); - zInfo.next_out = abDst; + int32_t Decompress(const uint8_t* abSrc, int32_t nLenSrc, uint8_t* abDst, int32_t nLenDst, int32_t& nErr) { + // Get the size of the decompressed data + z_stream zInfo = { 0 }; + zInfo.total_in = zInfo.avail_in = nLenSrc; + zInfo.total_out = zInfo.avail_out = nLenDst; + zInfo.next_in = const_cast(abSrc); + zInfo.next_out = abDst; - int nRet = -1; - nErr = inflateInit(&zInfo); // zlib function - if (nErr == Z_OK) { - nErr = inflate(&zInfo, Z_FINISH); // zlib function - if (nErr == Z_STREAM_END) { - nRet = zInfo.total_out; - } - } - inflateEnd(&zInfo); // zlib function - return(nRet); - - /* - z_stream zInfo = { 0 }; - zInfo.total_in = zInfo.avail_in = nLenSrc; - zInfo.total_out = zInfo.avail_out = nLenDst; - zInfo.next_in = const_cast(abSrc); - zInfo.next_out = const_cast(abDst); + int nRet = -1; + nErr = inflateInit(&zInfo); // zlib function + if (nErr == Z_OK) { + nErr = inflate(&zInfo, Z_FINISH); // zlib function + if (nErr == Z_STREAM_END) { + nRet = zInfo.total_out; + } + } + inflateEnd(&zInfo); // zlib function + return(nRet); - int nRet = -1; - nErr = inflateInit(&zInfo); // zlib function - if (nErr == Z_OK) { - nErr = inflate(&zInfo, Z_FINISH); // zlib function - if (nErr == Z_STREAM_END) { - nRet = zInfo.total_out; - } - } - inflateEnd(&zInfo); // zlib function - return(nRet); // -1 or len of output - */ - } + /* + z_stream zInfo = { 0 }; + zInfo.total_in = zInfo.avail_in = nLenSrc; + zInfo.total_out = zInfo.avail_out = nLenDst; + zInfo.next_in = const_cast(abSrc); + zInfo.next_out = const_cast(abDst); + + int nRet = -1; + nErr = inflateInit(&zInfo); // zlib function + if (nErr == Z_OK) { + nErr = inflate(&zInfo, Z_FINISH); // zlib function + if (nErr == Z_STREAM_END) { + nRet = zInfo.total_out; + } + } + inflateEnd(&zInfo); // zlib function + return(nRet); // -1 or len of output + */ + } } -#endif \ No newline at end of file +#endif diff --git a/dCommon/ZCompression.h b/dCommon/ZCompression.h index 6db2a600..a4ac9193 100644 --- a/dCommon/ZCompression.h +++ b/dCommon/ZCompression.h @@ -6,8 +6,7 @@ #ifndef DARKFLAME_PLATFORM_WIN32 -namespace ZCompression -{ +namespace ZCompression { int32_t GetMaxCompressedLength(int32_t nLenSrc); int32_t Compress(const uint8_t* abSrc, int32_t nLenSrc, uint8_t* abDst, int32_t nLenDst); diff --git a/dCommon/dCommonVars.h b/dCommon/dCommonVars.h index 9f62eaa4..986f1c18 100644 --- a/dCommon/dCommonVars.h +++ b/dCommon/dCommonVars.h @@ -103,61 +103,61 @@ private: const LWOSCENEID LWOSCENEID_INVALID = -1; struct LWONameValue { - uint32_t length = 0; //!< The length of the name - std::u16string name; //!< The name - - LWONameValue(void) {} - - LWONameValue(const std::u16string& name) { - this->name = name; - this->length = static_cast(name.length()); - } - - ~LWONameValue(void) {} + uint32_t length = 0; //!< The length of the name + std::u16string name; //!< The name + + LWONameValue(void) {} + + LWONameValue(const std::u16string& name) { + this->name = name; + this->length = static_cast(name.length()); + } + + ~LWONameValue(void) {} }; struct FriendData { public: - bool isOnline = false; - bool isBestFriend = false; - bool isFTP = false; - LWOZONEID zoneID; - LWOOBJID friendID; - std::string friendName; + bool isOnline = false; + bool isBestFriend = false; + bool isFTP = false; + LWOZONEID zoneID; + LWOOBJID friendID; + std::string friendName; - void Serialize(RakNet::BitStream& bitStream) { - bitStream.Write(isOnline); - bitStream.Write(isBestFriend); - bitStream.Write(isFTP); - bitStream.Write(0); //??? - bitStream.Write(0); //??? - bitStream.Write(zoneID.GetMapID()); - bitStream.Write(zoneID.GetInstanceID()); - bitStream.Write(zoneID.GetCloneID()); - bitStream.Write(friendID); - - uint32_t maxSize = 33; - uint32_t size = static_cast(friendName.length()); - uint32_t remSize = static_cast(maxSize - size); + void Serialize(RakNet::BitStream& bitStream) { + bitStream.Write(isOnline); + bitStream.Write(isBestFriend); + bitStream.Write(isFTP); + bitStream.Write(0); //??? + bitStream.Write(0); //??? + bitStream.Write(zoneID.GetMapID()); + bitStream.Write(zoneID.GetInstanceID()); + bitStream.Write(zoneID.GetCloneID()); + bitStream.Write(friendID); - if (size > maxSize) size = maxSize; + uint32_t maxSize = 33; + uint32_t size = static_cast(friendName.length()); + uint32_t remSize = static_cast(maxSize - size); - for (uint32_t i = 0; i < size; ++i) { - bitStream.Write(static_cast(friendName[i])); - } + if (size > maxSize) size = maxSize; - for (uint32_t j = 0; j < remSize; ++j) { - bitStream.Write(static_cast(0)); - } + for (uint32_t i = 0; i < size; ++i) { + bitStream.Write(static_cast(friendName[i])); + } - bitStream.Write(0); //??? - bitStream.Write(0); //??? - } + for (uint32_t j = 0; j < remSize; ++j) { + bitStream.Write(static_cast(0)); + } + + bitStream.Write(0); //??? + bitStream.Write(0); //??? + } }; struct Brick { - uint32_t designerID; - uint32_t materialID; + uint32_t designerID; + uint32_t materialID; }; //This union is used by the behavior system @@ -169,26 +169,26 @@ union suchar { //=========== DLU ENUMS ============ enum eGameMasterLevel : int32_t { - GAME_MASTER_LEVEL_CIVILIAN = 0, // Normal player. - GAME_MASTER_LEVEL_FORUM_MODERATOR = 1, // No permissions on live servers. - GAME_MASTER_LEVEL_JUNIOR_MODERATOR = 2, // Can kick/mute and pull chat logs. - GAME_MASTER_LEVEL_MODERATOR = 3, // Can return lost items. - GAME_MASTER_LEVEL_SENIOR_MODERATOR = 4, // Can ban. - GAME_MASTER_LEVEL_LEAD_MODERATOR = 5, // Can approve properties. - GAME_MASTER_LEVEL_JUNIOR_DEVELOPER = 6, // Junior developer & future content team. Civilan on live. - GAME_MASTER_LEVEL_INACTIVE_DEVELOPER = 7, // Inactive developer, limited permissions. - GAME_MASTER_LEVEL_DEVELOPER = 8, // Active developer, full permissions on live. - GAME_MASTER_LEVEL_OPERATOR = 9 // Can shutdown server for restarts & updates. + GAME_MASTER_LEVEL_CIVILIAN = 0, // Normal player. + GAME_MASTER_LEVEL_FORUM_MODERATOR = 1, // No permissions on live servers. + GAME_MASTER_LEVEL_JUNIOR_MODERATOR = 2, // Can kick/mute and pull chat logs. + GAME_MASTER_LEVEL_MODERATOR = 3, // Can return lost items. + GAME_MASTER_LEVEL_SENIOR_MODERATOR = 4, // Can ban. + GAME_MASTER_LEVEL_LEAD_MODERATOR = 5, // Can approve properties. + GAME_MASTER_LEVEL_JUNIOR_DEVELOPER = 6, // Junior developer & future content team. Civilan on live. + GAME_MASTER_LEVEL_INACTIVE_DEVELOPER = 7, // Inactive developer, limited permissions. + GAME_MASTER_LEVEL_DEVELOPER = 8, // Active developer, full permissions on live. + GAME_MASTER_LEVEL_OPERATOR = 9 // Can shutdown server for restarts & updates. }; //=========== LU ENUMS ============ //! An enum for object ID bits enum eObjectBits : int32_t { - OBJECT_BIT_PERSISTENT = 32, //!< The 32 bit index - OBJECT_BIT_CLIENT = 46, //!< The 46 bit index - OBJECT_BIT_SPAWNED = 58, //!< The 58 bit index - OBJECT_BIT_CHARACTER = 60 //!< The 60 bit index + OBJECT_BIT_PERSISTENT = 32, //!< The 32 bit index + OBJECT_BIT_CLIENT = 46, //!< The 46 bit index + OBJECT_BIT_SPAWNED = 58, //!< The 58 bit index + OBJECT_BIT_CHARACTER = 60 //!< The 60 bit index }; //! An enum for MatchUpdate types @@ -208,18 +208,18 @@ enum eCyclingMode : uint32_t { }; enum eCinematicEvent : uint32_t { - STARTED, - WAYPOINT, - ENDED, + STARTED, + WAYPOINT, + ENDED, }; //! An enum for character creation responses enum eCreationResponse : uint8_t { - CREATION_RESPONSE_SUCCESS = 0, //!< The creation was successful - CREATION_RESPONSE_OBJECT_ID_UNAVAILABLE, //!< The Object ID can't be used - CREATION_RESPONSE_NAME_NOT_ALLOWED, //!< The name is not allowed - CREATION_RESPONSE_PREDEFINED_NAME_IN_USE, //!< The predefined name is already in use - CREATION_RESPONSE_CUSTOM_NAME_IN_USE //!< The custom name is already in use + CREATION_RESPONSE_SUCCESS = 0, //!< The creation was successful + CREATION_RESPONSE_OBJECT_ID_UNAVAILABLE, //!< The Object ID can't be used + CREATION_RESPONSE_NAME_NOT_ALLOWED, //!< The name is not allowed + CREATION_RESPONSE_PREDEFINED_NAME_IN_USE, //!< The predefined name is already in use + CREATION_RESPONSE_CUSTOM_NAME_IN_USE //!< The custom name is already in use }; //! An enum for login responses @@ -234,21 +234,21 @@ enum eLoginResponse : uint8_t { //! An enum for character rename responses enum eRenameResponse : uint8_t { - RENAME_RESPONSE_SUCCESS = 0, //!< The renaming was successful - RENAME_RESPONSE_UNKNOWN_ERROR, //!< There was an unknown error - RENAME_RESPONSE_NAME_UNAVAILABLE, //!< The name is unavailable - RENAME_RESPONSE_NAME_IN_USE //!< The name is already in use + RENAME_RESPONSE_SUCCESS = 0, //!< The renaming was successful + RENAME_RESPONSE_UNKNOWN_ERROR, //!< There was an unknown error + RENAME_RESPONSE_NAME_UNAVAILABLE, //!< The name is unavailable + RENAME_RESPONSE_NAME_IN_USE //!< The name is already in use }; //! A replica packet type enum eReplicaPacketType { - PACKET_TYPE_CONSTRUCTION, //!< A construction packet - PACKET_TYPE_SERIALIZATION, //!< A serialization packet - PACKET_TYPE_DESTRUCTION //!< A destruction packet + PACKET_TYPE_CONSTRUCTION, //!< A construction packet + PACKET_TYPE_SERIALIZATION, //!< A serialization packet + PACKET_TYPE_DESTRUCTION //!< A destruction packet }; enum ServerDisconnectIdentifiers { - SERVER_DISCON_UNKNOWN_SERVER_ERROR = 0, //!< Unknown server error + SERVER_DISCON_UNKNOWN_SERVER_ERROR = 0, //!< Unknown server error SERVER_DISCON_DUPLICATE_LOGIN = 4, //!< Used when another user with the same username is logged in (duplicate login) SERVER_DISCON_SERVER_SHUTDOWN = 5, //!< Used when the server is shutdown SERVER_DISCON_SERVER_MAP_LOAD_FAILURE = 6, //!< Used when the server cannot load a map @@ -263,80 +263,80 @@ enum ServerDisconnectIdentifiers { //! The Behavior Types for use with the AI system enum eCombatBehaviorTypes : uint32_t { - PASSIVE = 0, //!< The object is passive - AGGRESSIVE = 1, //!< The object is aggressive - PASSIVE_TURRET = 2, //!< The object is a passive turret - AGGRESSIVE_TURRET = 3 //!< The object is an aggressive turret + PASSIVE = 0, //!< The object is passive + AGGRESSIVE = 1, //!< The object is aggressive + PASSIVE_TURRET = 2, //!< The object is a passive turret + AGGRESSIVE_TURRET = 3 //!< The object is an aggressive turret }; //! The Combat Role Type for use with the AI system enum eCombatRoleType : uint32_t { - MELEE = 0, //!< Used for melee attacks - RANGED = 1, //!< Used for range attacks - SUPPORT = 2 //!< Used for support + MELEE = 0, //!< Used for melee attacks + RANGED = 1, //!< Used for range attacks + SUPPORT = 2 //!< Used for support }; //! The kill types for the Die packet enum eKillType : uint32_t { - VIOLENT, - SILENT + VIOLENT, + SILENT }; //! The various world states used throughout the server enum eObjectWorldState { - WORLDSTATE_INWORLD, //!< Probably used when the object is in the world - WORLDSTATE_ATTACHED, //!< Probably used when the object is attached to another object - WORLDSTATE_INVENTORY //!< Probably used when the object is in an inventory + WORLDSTATE_INWORLD, //!< Probably used when the object is in the world + WORLDSTATE_ATTACHED, //!< Probably used when the object is attached to another object + WORLDSTATE_INVENTORY //!< Probably used when the object is in an inventory }; //! The trigger stats (???) enum eTriggerStat { - INVALID_STAT, //!< ??? - HEALTH, //!< Probably used for health - ARMOR, //!< Probably used for armor - IMAGINATION //!< Probably used for imagination + INVALID_STAT, //!< ??? + HEALTH, //!< Probably used for health + ARMOR, //!< Probably used for armor + IMAGINATION //!< Probably used for imagination }; //! The trigger operations (???) enum eTriggerOperator { - INVALID_OPER, //!< ??? - EQUAL, //!< ??? - NOT_EQUAL, //!< ??? - GREATER, //!< ??? - GREATER_EQUAL, //!< ??? - LESS, //!< ??? - LESS_EQUAL //!< ??? + INVALID_OPER, //!< ??? + EQUAL, //!< ??? + NOT_EQUAL, //!< ??? + GREATER, //!< ??? + GREATER_EQUAL, //!< ??? + LESS, //!< ??? + LESS_EQUAL //!< ??? }; //! The various build types enum eBuildType { - BUILD_NOWHERE, //!< Used if something can't be built anywhere - BUILD_IN_WORLD, //!< Used if something can be built in the world - BUILD_ON_PROPERTY //!< Used if something can be build on a property + BUILD_NOWHERE, //!< Used if something can't be built anywhere + BUILD_IN_WORLD, //!< Used if something can be built in the world + BUILD_ON_PROPERTY //!< Used if something can be build on a property }; //! Quickbuild fail reasons enum eFailReason : uint32_t { - REASON_NOT_GIVEN, - REASON_OUT_OF_IMAGINATION, - REASON_CANCELED_EARLY, - REASON_BUILD_ENDED + REASON_NOT_GIVEN, + REASON_OUT_OF_IMAGINATION, + REASON_CANCELED_EARLY, + REASON_BUILD_ENDED }; //! Terminate interaction type enum eTerminateType : uint32_t { - RANGE, - USER, - FROM_INTERACTION + RANGE, + USER, + FROM_INTERACTION }; //! The combat state enum eCombatState { - IDLE, //!< The AI is in an idle state - AGGRO, //!< The AI is in an aggressive state - TETHER, //!< The AI is being redrawn back to tether point - SPAWN, //!< The AI is spawning - DEAD //!< The AI is dead + IDLE, //!< The AI is in an idle state + AGGRO, //!< The AI is in an aggressive state + TETHER, //!< The AI is being redrawn back to tether point + SPAWN, //!< The AI is spawning + DEAD //!< The AI is dead }; enum eControlSceme { @@ -348,7 +348,7 @@ enum eControlSceme { SCHEME_DRIVING, SCHEME_TAMING, SCHEME_MODULAR_BUILD, - SCHEME_WEAR_A_ROBOT //== freecam? + SCHEME_WEAR_A_ROBOT //== freecam? }; enum eStunState { @@ -357,86 +357,86 @@ enum eStunState { }; enum eNotifyType { - NOTIFY_TYPE_SUCCESS, - NOTIFY_TYPE_QUIT, - NOTIFY_TYPE_FAILED, - NOTIFY_TYPE_BEGIN, - NOTIFY_TYPE_READY, - NOTIFY_TYPE_NAMINGPET + NOTIFY_TYPE_SUCCESS, + NOTIFY_TYPE_QUIT, + NOTIFY_TYPE_FAILED, + NOTIFY_TYPE_BEGIN, + NOTIFY_TYPE_READY, + NOTIFY_TYPE_NAMINGPET }; enum eReplicaComponentType : int32_t { - COMPONENT_TYPE_CONTROLLABLE_PHYSICS = 1, //!< The ControllablePhysics Component - COMPONENT_TYPE_RENDER = 2, //!< The Render Component - COMPONENT_TYPE_SIMPLE_PHYSICS = 3, //!< The SimplePhysics Component - COMPONENT_TYPE_CHARACTER = 4, //!< The Character Component - COMPONENT_TYPE_SCRIPT = 5, //!< The Script Component - COMPONENT_TYPE_BOUNCER = 6, //!< The Bouncer Component - COMPONENT_TYPE_BUFF = 7, //!< The Buff Component - COMPONENT_TYPE_SKILL = 9, //!< The Skill Component - COMPONENT_TYPE_ITEM = 11, //!< The Item Component - COMPONENT_TYPE_VENDOR = 16, //!< The Vendor Component - COMPONENT_TYPE_INVENTORY = 17, //!< The Inventory Component - COMPONENT_TYPE_SHOOTING_GALLERY = 19, //!< The Shooting Gallery Component - COMPONENT_TYPE_RIGID_BODY_PHANTOM_PHYSICS = 20, //!< The RigidBodyPhantomPhysics Component - COMPONENT_TYPE_COLLECTIBLE = 23, //!< The Collectible Component - COMPONENT_TYPE_MOVING_PLATFORM = 25, //!< The MovingPlatform Component - COMPONENT_TYPE_PET = 26, //!< The Pet Component - COMPONENT_TYPE_VEHICLE_PHYSICS = 30, //!< The VehiclePhysics Component - COMPONENT_TYPE_MOVEMENT_AI = 31, //!< The MovementAI Component - COMPONENT_TYPE_PROPERTY = 36, //!< The Property Component - COMPONENT_TYPE_SCRIPTED_ACTIVITY = 39, //!< The ScriptedActivity Component - COMPONENT_TYPE_PHANTOM_PHYSICS = 40, //!< The PhantomPhysics Component - COMPONENT_TYPE_MODEL = 42, //!< The Model Component - COMPONENT_TYPE_PROPERTY_ENTRANCE = 43, //!< The PhantomPhysics Component - COMPONENT_TYPE_PROPERTY_MANAGEMENT = 45, //!< The PropertyManagement Component - COMPONENT_TYPE_REBUILD = 48, //!< The Rebuild Component - COMPONENT_TYPE_SWITCH = 49, //!< The Switch Component - COMPONENT_TYPE_ZONE_CONTROL = 50, //!< The ZoneControl Component - COMPONENT_TYPE_PACKAGE = 53, //!< The Package Component - COMPONENT_TYPE_PLAYER_FLAG = 58, //!< The PlayerFlag Component - COMPONENT_TYPE_BASE_COMBAT_AI = 60, //!< The BaseCombatAI Component - COMPONENT_TYPE_MODULE_ASSEMBLY = 61, //!< The ModuleAssembly Component - COMPONENT_TYPE_PROPERTY_VENDOR = 65, //!< The PropertyVendor Component - COMPONENT_TYPE_ROCKET_LAUNCH = 67, //!< The RocketLaunch Component - COMPONENT_TYPE_RACING_CONTROL = 71, //!< The RacingControl Component - COMPONENT_TYPE_MISSION_OFFER = 73, //!< The MissionOffer Component - COMPONENT_TYPE_EXHIBIT = 75, //!< The Exhibit Component - COMPONENT_TYPE_RACING_STATS = 74, //!< The Racing Stats Component - COMPONENT_TYPE_SOUND_TRIGGER = 77, //!< The Sound Trigger Component - COMPONENT_TYPE_PROXIMITY_MONITOR = 78, //!< The Proximity Monitor Component - COMPONENT_TYPE_MISSION = 84, //!< The Mission Component - COMPONENT_TYPE_ROCKET_LAUNCH_LUP = 97, //!< The LUP Launchpad Componen - COMPONENT_TYPE_RAIL_ACTIVATOR = 104, //!< The Rail Activator Component - COMPONENT_TYPE_PLAYER_FORCED_MOVEMENT = 106, //!< The Player Forced Movement Component - COMPONENT_TYPE_POSSESSABLE = 108, //!< The Possessable Component - COMPONENT_TYPE_LEVEL_PROGRESSION = 109, //!< The Level Progression Component - COMPONENT_TYPE_POSSESSOR = 110, //!< The Possessor Component - COMPONENT_TYPE_BUILD_BORDER = 114, //!< The Build Border Component - COMPONENT_TYPE_DESTROYABLE = 1000, //!< The Destroyable Component + COMPONENT_TYPE_CONTROLLABLE_PHYSICS = 1, //!< The ControllablePhysics Component + COMPONENT_TYPE_RENDER = 2, //!< The Render Component + COMPONENT_TYPE_SIMPLE_PHYSICS = 3, //!< The SimplePhysics Component + COMPONENT_TYPE_CHARACTER = 4, //!< The Character Component + COMPONENT_TYPE_SCRIPT = 5, //!< The Script Component + COMPONENT_TYPE_BOUNCER = 6, //!< The Bouncer Component + COMPONENT_TYPE_BUFF = 7, //!< The Buff Component + COMPONENT_TYPE_SKILL = 9, //!< The Skill Component + COMPONENT_TYPE_ITEM = 11, //!< The Item Component + COMPONENT_TYPE_VENDOR = 16, //!< The Vendor Component + COMPONENT_TYPE_INVENTORY = 17, //!< The Inventory Component + COMPONENT_TYPE_SHOOTING_GALLERY = 19, //!< The Shooting Gallery Component + COMPONENT_TYPE_RIGID_BODY_PHANTOM_PHYSICS = 20, //!< The RigidBodyPhantomPhysics Component + COMPONENT_TYPE_COLLECTIBLE = 23, //!< The Collectible Component + COMPONENT_TYPE_MOVING_PLATFORM = 25, //!< The MovingPlatform Component + COMPONENT_TYPE_PET = 26, //!< The Pet Component + COMPONENT_TYPE_VEHICLE_PHYSICS = 30, //!< The VehiclePhysics Component + COMPONENT_TYPE_MOVEMENT_AI = 31, //!< The MovementAI Component + COMPONENT_TYPE_PROPERTY = 36, //!< The Property Component + COMPONENT_TYPE_SCRIPTED_ACTIVITY = 39, //!< The ScriptedActivity Component + COMPONENT_TYPE_PHANTOM_PHYSICS = 40, //!< The PhantomPhysics Component + COMPONENT_TYPE_MODEL = 42, //!< The Model Component + COMPONENT_TYPE_PROPERTY_ENTRANCE = 43, //!< The PhantomPhysics Component + COMPONENT_TYPE_PROPERTY_MANAGEMENT = 45, //!< The PropertyManagement Component + COMPONENT_TYPE_REBUILD = 48, //!< The Rebuild Component + COMPONENT_TYPE_SWITCH = 49, //!< The Switch Component + COMPONENT_TYPE_ZONE_CONTROL = 50, //!< The ZoneControl Component + COMPONENT_TYPE_PACKAGE = 53, //!< The Package Component + COMPONENT_TYPE_PLAYER_FLAG = 58, //!< The PlayerFlag Component + COMPONENT_TYPE_BASE_COMBAT_AI = 60, //!< The BaseCombatAI Component + COMPONENT_TYPE_MODULE_ASSEMBLY = 61, //!< The ModuleAssembly Component + COMPONENT_TYPE_PROPERTY_VENDOR = 65, //!< The PropertyVendor Component + COMPONENT_TYPE_ROCKET_LAUNCH = 67, //!< The RocketLaunch Component + COMPONENT_TYPE_RACING_CONTROL = 71, //!< The RacingControl Component + COMPONENT_TYPE_MISSION_OFFER = 73, //!< The MissionOffer Component + COMPONENT_TYPE_EXHIBIT = 75, //!< The Exhibit Component + COMPONENT_TYPE_RACING_STATS = 74, //!< The Racing Stats Component + COMPONENT_TYPE_SOUND_TRIGGER = 77, //!< The Sound Trigger Component + COMPONENT_TYPE_PROXIMITY_MONITOR = 78, //!< The Proximity Monitor Component + COMPONENT_TYPE_MISSION = 84, //!< The Mission Component + COMPONENT_TYPE_ROCKET_LAUNCH_LUP = 97, //!< The LUP Launchpad Componen + COMPONENT_TYPE_RAIL_ACTIVATOR = 104, //!< The Rail Activator Component + COMPONENT_TYPE_PLAYER_FORCED_MOVEMENT = 106, //!< The Player Forced Movement Component + COMPONENT_TYPE_POSSESSABLE = 108, //!< The Possessable Component + COMPONENT_TYPE_LEVEL_PROGRESSION = 109, //!< The Level Progression Component + COMPONENT_TYPE_POSSESSOR = 110, //!< The Possessor Component + COMPONENT_TYPE_BUILD_BORDER = 114, //!< The Build Border Component + COMPONENT_TYPE_DESTROYABLE = 1000, //!< The Destroyable Component }; enum class UseItemResponse : uint32_t { - NoImaginationForPet = 1, - FailedPrecondition, - MountsNotAllowed + NoImaginationForPet = 1, + FailedPrecondition, + MountsNotAllowed }; /** * Represents the different types of inventories an entity may have */ enum eInventoryType : uint32_t { - ITEMS = 0, - VAULT_ITEMS, - BRICKS, - TEMP_ITEMS = 4, - MODELS, - TEMP_MODELS, - BEHAVIORS, - PROPERTY_DEEDS, + ITEMS = 0, + VAULT_ITEMS, + BRICKS, + TEMP_ITEMS = 4, + MODELS, + TEMP_MODELS, + BEHAVIORS, + PROPERTY_DEEDS, VENDOR_BUYBACK = 11, - HIDDEN = 12, //Used for missional items - VAULT_MODELS = 14, + HIDDEN = 12, //Used for missional items + VAULT_MODELS = 14, ITEM_SETS, //internal INVALID // made up, for internal use!!! }; @@ -450,7 +450,7 @@ enum eRebuildState : uint32_t { }; /** - * The loot source's type. + * The loot source's type. */ enum eLootSourceType : int32_t { LOOT_SOURCE_NONE = 0, @@ -542,7 +542,7 @@ enum ePlayerFlags { TOOLTIP_TALK_TO_SKYLAND_TO_GET_HAT = 52, MODULAR_BUILD_PLAYER_PLACES_FIRST_MODEL_IN_SCRATCH = 53, MODULAR_BUILD_FIRST_ARROW_DISPLAY_FOR_MODULE = 54, - AG_BEACON_QB,_SO_THE_PLAYER_CAN_ALWAYS_BUILD_THEM = 55, + AG_BEACON_QB_SO_THE_PLAYER_CAN_ALWAYS_BUILD_THEM = 55, GF_PET_DIG_FLAG_1 = 56, GF_PET_DIG_FLAG_2 = 57, GF_PET_DIG_FLAG_3 = 58, @@ -554,7 +554,7 @@ enum ePlayerFlags { ENTER_BBB_FROM_PROPERTY_EDIT_CONFIRMATION_DIALOG = 64, AG_FIRST_COMBAT_COMPLETE = 65, AG_COMPLETE_BOB_MISSION = 66, - NJ_GARMADON_CINEMATIC_SEEN = 125, + NJ_GARMADON_CINEMATIC_SEEN = 125, ELEPHANT_PET_3050 = 801, CAT_PET_3054 = 802, TRICERATOPS_PET_3195 = 803, @@ -631,19 +631,19 @@ enum ePlayerFlags { NT_FACTION_SPY_DUKE = 1974, NT_FACTION_SPY_OVERBUILD = 1976, NT_FACTION_SPY_HAEL = 1977, - NJ_EARTH_SPINJITZU = 2030, - NJ_LIGHTNING_SPINJITZU = 2031, - NJ_ICE_SPINJITZU = 2032, - NJ_FIRE_SPINJITZU = 2033, - NJ_WU_SHOW_DAILY_CHEST = 2099 + NJ_EARTH_SPINJITZU = 2030, + NJ_LIGHTNING_SPINJITZU = 2031, + NJ_ICE_SPINJITZU = 2032, + NJ_FIRE_SPINJITZU = 2033, + NJ_WU_SHOW_DAILY_CHEST = 2099 }; //======== FUNC =========== template inline T const& clamp(const T& val, const T& low, const T& high) { - if (val < low) return low; - else if (val > high) return high; - - return val; + if (val < low) return low; + else if (val > high) return high; + + return val; } diff --git a/dCommon/dConfig.cpp b/dCommon/dConfig.cpp index b53b7166..9750238a 100644 --- a/dCommon/dConfig.cpp +++ b/dCommon/dConfig.cpp @@ -12,7 +12,7 @@ dConfig::dConfig(const std::string& filepath) { if (line[0] != '#') ProcessLine(line); } } -} +} dConfig::~dConfig(void) { } @@ -31,15 +31,15 @@ void dConfig::ProcessLine(const std::string& line) { std::vector seglist; while (std::getline(ss, segment, '=')) { - seglist.push_back(segment); + seglist.push_back(segment); } if (seglist.size() != 2) return; //Make sure that on Linux, we remove special characters: if (!seglist[1].empty() && seglist[1][seglist[1].size() - 1] == '\r') - seglist[1].erase(seglist[1].size() - 1); + seglist[1].erase(seglist[1].size() - 1); m_Keys.push_back(seglist[0]); m_Values.push_back(seglist[1]); -} \ No newline at end of file +} diff --git a/dCommon/dConfig.h b/dCommon/dConfig.h index 0e712499..7764fa54 100644 --- a/dCommon/dConfig.h +++ b/dCommon/dConfig.h @@ -17,4 +17,4 @@ private: std::vector m_Keys; std::vector m_Values; std::string m_EmptyString; -}; \ No newline at end of file +}; diff --git a/dCommon/dLogger.cpp b/dCommon/dLogger.cpp index 0beb5a3c..3a91e31d 100644 --- a/dCommon/dLogger.cpp +++ b/dCommon/dLogger.cpp @@ -10,7 +10,7 @@ dLogger::dLogger(const std::string& outpath, bool logToConsole, bool logDebugSta if (!mFile) { printf("Couldn't open %s for writing!\n", outpath.c_str()); } #else fp = fopen(outpath.c_str(), "wt"); - if (fp == NULL) { printf("Couldn't open %s for writing!\n", outpath.c_str()); } + if (fp == NULL) { printf("Couldn't open %s for writing!\n", outpath.c_str()); } #endif } @@ -46,42 +46,42 @@ void dLogger::vLog(const char* format, va_list args) { mFile << "[" << timeStr << "] " << message; #else time_t t = time(NULL); - struct tm * time = localtime(&t); - char timeStr[70]; - strftime(timeStr, sizeof(timeStr), "%d-%m-%y %H:%M:%S", time); + struct tm* time = localtime(&t); + char timeStr[70]; + strftime(timeStr, sizeof(timeStr), "%d-%m-%y %H:%M:%S", time); char message[2048]; - vsprintf(message, format, args); + vsprintf(message, format, args); - if (m_logToConsole) { + if (m_logToConsole) { fputs("[", stdout); fputs(timeStr, stdout); fputs("] ", stdout); fputs(message, stdout); - } + } - if (fp != nullptr) { + if (fp != nullptr) { fputs("[", fp); fputs(timeStr, fp); fputs("] ", fp); fputs(message, fp); - } else { - printf("Logger not initialized!\n"); - } + } else { + printf("Logger not initialized!\n"); + } #endif } -void dLogger::LogBasic(const char * format, ...) { +void dLogger::LogBasic(const char* format, ...) { va_list args; va_start(args, format); vLog(format, args); va_end(args); } -void dLogger::LogBasic(const std::string & message) { +void dLogger::LogBasic(const std::string& message) { LogBasic(message.c_str()); } -void dLogger::Log(const char * className, const char * format, ...) { +void dLogger::Log(const char* className, const char* format, ...) { va_list args; std::string log = "[" + std::string(className) + "] " + std::string(format) + "\n"; va_start(args, format); @@ -89,11 +89,11 @@ void dLogger::Log(const char * className, const char * format, ...) { va_end(args); } -void dLogger::Log(const std::string & className, const std::string & message) { +void dLogger::Log(const std::string& className, const std::string& message) { Log(className.c_str(), message.c_str()); } -void dLogger::LogDebug(const char * className, const char * format, ...) { +void dLogger::LogDebug(const char* className, const char* format, ...) { if (!m_logDebugStatements) return; va_list args; std::string log = "[" + std::string(className) + "] " + std::string(format); @@ -102,7 +102,7 @@ void dLogger::LogDebug(const char * className, const char * format, ...) { va_end(args); } -void dLogger::LogDebug(const std::string & className, const std::string & message) { +void dLogger::LogDebug(const std::string& className, const std::string& message) { LogDebug(className.c_str(), message.c_str()); } diff --git a/dCommon/dLogger.h b/dCommon/dLogger.h index 7448237e..6726c6f1 100644 --- a/dCommon/dLogger.h +++ b/dCommon/dLogger.h @@ -31,8 +31,8 @@ private: std::string m_outpath; std::ofstream mFile; - #ifndef _WIN32 - //Glorious linux can run with SPEED: - FILE* fp = nullptr; - #endif -}; \ No newline at end of file +#ifndef _WIN32 + //Glorious linux can run with SPEED: + FILE* fp = nullptr; +#endif +}; diff --git a/dCommon/dPlatforms.h b/dCommon/dPlatforms.h index d19e8121..bca7f9e0 100644 --- a/dCommon/dPlatforms.h +++ b/dCommon/dPlatforms.h @@ -1,29 +1,29 @@ #pragma once #if defined(_WIN32) - #define DARKFLAME_PLATFORM_WIN32 +#define DARKFLAME_PLATFORM_WIN32 #elif defined(__APPLE__) && defined(__MACH__) - #include - #if TARGET_OS_IPHONE || TARGET_IPHONE_SIMULATOR - #define DARKFLAME_PLATFORM_IOS - #elif TARGET_OS_MAC - #define DARKFLAME_PLATFORM_MACOS - #else - #error unknown Apple operating system - #endif -#elif defined(__unix__) - #define DARKFLAME_PLATFORM_UNIX - #if defined(__ANDROID__) - #define DARKFLAME_PLATFORM_ANDROID - #elif defined(__linux__) - #define DARKFLAME_PLATFORM_LINUX - #elif defined(__FreeBSD__) || defined(__FreeBSD_kernel__) - #define DARKFLAME_PLATFORM_FREEBSD - #elif defined(__CYGWIN__) - #define DARKFLAME_PLATFORM_CYGWIN - #else - #error unknown unix operating system - #endif +#include +#if TARGET_OS_IPHONE || TARGET_IPHONE_SIMULATOR +#define DARKFLAME_PLATFORM_IOS +#elif TARGET_OS_MAC +#define DARKFLAME_PLATFORM_MACOS #else - #error unknown operating system -#endif \ No newline at end of file +#error unknown Apple operating system +#endif +#elif defined(__unix__) +#define DARKFLAME_PLATFORM_UNIX +#if defined(__ANDROID__) +#define DARKFLAME_PLATFORM_ANDROID +#elif defined(__linux__) +#define DARKFLAME_PLATFORM_LINUX +#elif defined(__FreeBSD__) || defined(__FreeBSD_kernel__) +#define DARKFLAME_PLATFORM_FREEBSD +#elif defined(__CYGWIN__) +#define DARKFLAME_PLATFORM_CYGWIN +#else +#error unknown unix operating system +#endif +#else +#error unknown operating system +#endif diff --git a/dCommon/eAninmationFlags.h b/dCommon/eAninmationFlags.h index 09cfde22..9b2ea3fb 100644 --- a/dCommon/eAninmationFlags.h +++ b/dCommon/eAninmationFlags.h @@ -41,4 +41,4 @@ enum class eAnimationFlags : uint32_t { IDLE_MISC12 }; -#endif //!__EANINMATIONFLAGS__H__ \ No newline at end of file +#endif //!__EANINMATIONFLAGS__H__ diff --git a/dCommon/eItemType.h b/dCommon/eItemType.h index 453e8737..e68ce695 100644 --- a/dCommon/eItemType.h +++ b/dCommon/eItemType.h @@ -33,4 +33,4 @@ enum class eItemType : int32_t { ITEM_TYPE_MOUNT = 24 //!< A Mount }; -#endif //!__EITEMTYPE__H__ \ No newline at end of file +#endif //!__EITEMTYPE__H__ diff --git a/dDatabase/CDClientDatabase.cpp b/dDatabase/CDClientDatabase.cpp index d09b2daa..bf8485d6 100644 --- a/dDatabase/CDClientDatabase.cpp +++ b/dDatabase/CDClientDatabase.cpp @@ -2,19 +2,19 @@ #include "CDComponentsRegistryTable.h" // Static Variables -static CppSQLite3DB * conn = new CppSQLite3DB(); +static CppSQLite3DB* conn = new CppSQLite3DB(); //! Opens a connection with the CDClient void CDClientDatabase::Connect(const std::string& filename) { - conn->open(filename.c_str()); + conn->open(filename.c_str()); } //! Queries the CDClient CppSQLite3Query CDClientDatabase::ExecuteQuery(const std::string& query) { - return conn->execQuery(query.c_str()); + return conn->execQuery(query.c_str()); } //! Makes prepared statements CppSQLite3Statement CDClientDatabase::CreatePreppedStmt(const std::string& query) { - return conn->compileStatement(query.c_str()); + return conn->compileStatement(query.c_str()); } diff --git a/dDatabase/CDClientDatabase.h b/dDatabase/CDClientDatabase.h index 91e9ee10..6b254ebb 100644 --- a/dDatabase/CDClientDatabase.h +++ b/dDatabase/CDClientDatabase.h @@ -13,10 +13,10 @@ #include #include -// Enable this to cache all entries in each table for fast access, comes with more memory cost -//#define CDCLIENT_CACHE_ALL + // Enable this to cache all entries in each table for fast access, comes with more memory cost + //#define CDCLIENT_CACHE_ALL -// Enable this to skip some unused columns in some tables + // Enable this to skip some unused columns in some tables #define UNUSED(v) /*! @@ -24,26 +24,26 @@ \brief An interface between the CDClient.sqlite file and the server */ -//! The CDClient Database namespace + //! The CDClient Database namespace namespace CDClientDatabase { - - //! Opens a connection with the CDClient - /*! - \param filename The filename - */ - void Connect(const std::string& filename); - - //! Queries the CDClient - /*! - \param query The query - \return The results of the query - */ - CppSQLite3Query ExecuteQuery(const std::string& query); - - //! Queries the CDClient and parses arguments - /*! - \param query The query with formatted arguments - \return prepared SQLite Statement - */ - CppSQLite3Statement CreatePreppedStmt(const std::string& query); + + //! Opens a connection with the CDClient + /*! + \param filename The filename + */ + void Connect(const std::string& filename); + + //! Queries the CDClient + /*! + \param query The query + \return The results of the query + */ + CppSQLite3Query ExecuteQuery(const std::string& query); + + //! Queries the CDClient and parses arguments + /*! + \param query The query with formatted arguments + \return prepared SQLite Statement + */ + CppSQLite3Statement CreatePreppedStmt(const std::string& query); }; diff --git a/dDatabase/CDClientManager.cpp b/dDatabase/CDClientManager.cpp index 75ada1ea..4b32e749 100644 --- a/dDatabase/CDClientManager.cpp +++ b/dDatabase/CDClientManager.cpp @@ -1,7 +1,7 @@ #include "CDClientManager.h" // Static Variables -CDClientManager * CDClientManager::m_Address = nullptr; +CDClientManager* CDClientManager::m_Address = nullptr; //! Initializes the manager void CDClientManager::Initialize(void) { diff --git a/dDatabase/CDClientManager.h b/dDatabase/CDClientManager.h index f4530f90..ea24a373 100644 --- a/dDatabase/CDClientManager.h +++ b/dDatabase/CDClientManager.h @@ -52,45 +52,45 @@ \brief A manager for the CDClient tables */ -//! Manages all data from the CDClient + //! Manages all data from the CDClient class CDClientManager { private: - static CDClientManager * m_Address; //!< The singleton address - - std::unordered_map tables; //!< The tables - + static CDClientManager* m_Address; //!< The singleton address + + std::unordered_map tables; //!< The tables + public: - - //! The singleton method - static CDClientManager * Instance() { - if (m_Address == 0) { - m_Address = new CDClientManager; - } - - return m_Address; - } - - //! Initializes the manager - void Initialize(void); - - //! Fetches a CDClient table - /*! - This function uses typename T which must be a subclass of CDTable. - It returns the class that conforms to the class name - - \param tableName The table name - \return The class or nullptr - */ - template - T * GetTable(const std::string& tableName) { - static_assert(std::is_base_of::value, "T should inherit from CDTable!"); - - for (auto itr = this->tables.begin(); itr != this->tables.end(); ++itr) { - if (itr->first == tableName) { - return dynamic_cast(itr->second); - } - } - - return nullptr; - } + + //! The singleton method + static CDClientManager* Instance() { + if (m_Address == 0) { + m_Address = new CDClientManager; + } + + return m_Address; + } + + //! Initializes the manager + void Initialize(void); + + //! Fetches a CDClient table + /*! + This function uses typename T which must be a subclass of CDTable. + It returns the class that conforms to the class name + + \param tableName The table name + \return The class or nullptr + */ + template + T* GetTable(const std::string& tableName) { + static_assert(std::is_base_of::value, "T should inherit from CDTable!"); + + for (auto itr = this->tables.begin(); itr != this->tables.end(); ++itr) { + if (itr->first == tableName) { + return dynamic_cast(itr->second); + } + } + + return nullptr; + } }; diff --git a/dDatabase/Database.cpp b/dDatabase/Database.cpp index 7ab7b752..f955bd43 100644 --- a/dDatabase/Database.cpp +++ b/dDatabase/Database.cpp @@ -6,8 +6,8 @@ using namespace std; #pragma warning (disable:4251) //Disables SQL warnings -sql::Driver * Database::driver; -sql::Connection * Database::con; +sql::Driver* Database::driver; +sql::Connection* Database::con; sql::Properties Database::props; std::string Database::database; @@ -66,8 +66,7 @@ sql::PreparedStatement* Database::CreatePreppedStmt(const std::string& query) { Game::logger->Log("Database", "Trying to reconnect to MySQL"); } - if (!con->isValid() || con->isClosed()) - { + if (!con->isValid() || con->isClosed()) { delete con; con = nullptr; @@ -83,4 +82,4 @@ sql::PreparedStatement* Database::CreatePreppedStmt(const std::string& query) { void Database::Commit() { Database::con->commit(); -} \ No newline at end of file +} diff --git a/dDatabase/Database.h b/dDatabase/Database.h index ece62a95..a15ba856 100644 --- a/dDatabase/Database.h +++ b/dDatabase/Database.h @@ -11,8 +11,8 @@ public: class Database { private: - static sql::Driver *driver; - static sql::Connection *con; + static sql::Driver* driver; + static sql::Connection* con; static sql::Properties props; static std::string database; public: diff --git a/dDatabase/MigrationRunner.cpp b/dDatabase/MigrationRunner.cpp index a988acac..30a63896 100644 --- a/dDatabase/MigrationRunner.cpp +++ b/dDatabase/MigrationRunner.cpp @@ -9,70 +9,69 @@ void MigrationRunner::RunMigrations() { auto stmt = Database::CreatePreppedStmt("CREATE TABLE IF NOT EXISTS migration_history (name TEXT NOT NULL, date TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP());"); stmt->executeQuery(); - delete stmt; + delete stmt; - sql::SQLString finalSQL = ""; - Migration checkMigration{}; + sql::SQLString finalSQL = ""; + Migration checkMigration{}; - for (const auto& entry : GeneralUtils::GetFileNamesFromFolder("./migrations/")) { - auto migration = LoadMigration(entry); + for (const auto& entry : GeneralUtils::GetFileNamesFromFolder("./migrations/")) { + auto migration = LoadMigration(entry); - if (migration.data.empty()) { - continue; - } + if (migration.data.empty()) { + continue; + } - checkMigration = migration; + checkMigration = migration; - stmt = Database::CreatePreppedStmt("SELECT name FROM migration_history WHERE name = ?;"); - stmt->setString(1, migration.name); - auto res = stmt->executeQuery(); - bool doExit = res->next(); - delete res; - delete stmt; - if (doExit) continue; + stmt = Database::CreatePreppedStmt("SELECT name FROM migration_history WHERE name = ?;"); + stmt->setString(1, migration.name); + auto res = stmt->executeQuery(); + bool doExit = res->next(); + delete res; + delete stmt; + if (doExit) continue; - Game::logger->Log("MigrationRunner", "Running migration: %s", migration.name.c_str()); + Game::logger->Log("MigrationRunner", "Running migration: %s", migration.name.c_str()); - finalSQL.append(migration.data); - finalSQL.append('\n'); + finalSQL.append(migration.data); + finalSQL.append('\n'); - stmt = Database::CreatePreppedStmt("INSERT INTO migration_history (name) VALUES (?);"); - stmt->setString(1, entry); - stmt->execute(); - delete stmt; - } + stmt = Database::CreatePreppedStmt("INSERT INTO migration_history (name) VALUES (?);"); + stmt->setString(1, entry); + stmt->execute(); + delete stmt; + } - if (!finalSQL.empty()) { - try { - auto simpleStatement = Database::CreateStmt(); - simpleStatement->execute(finalSQL); - delete simpleStatement; - } - catch (sql::SQLException e) { - Game::logger->Log("MigrationRunner", "Encountered error running migration: %s", e.what()); - } - } + if (!finalSQL.empty()) { + try { + auto simpleStatement = Database::CreateStmt(); + simpleStatement->execute(finalSQL); + delete simpleStatement; + } catch (sql::SQLException e) { + Game::logger->Log("MigrationRunner", "Encountered error running migration: %s", e.what()); + } + } } Migration MigrationRunner::LoadMigration(std::string path) { - Migration migration{}; - std::ifstream file("./migrations/" + path); + Migration migration{}; + std::ifstream file("./migrations/" + path); - if (file.is_open()) { - std::hash hash; + if (file.is_open()) { + std::hash hash; - std::string line; - std::string total = ""; + std::string line; + std::string total = ""; - while (std::getline(file, line)) { - total += line; - } + while (std::getline(file, line)) { + total += line; + } - file.close(); + file.close(); - migration.name = path; - migration.data = total; - } + migration.name = path; + migration.data = total; + } - return migration; + return migration; } diff --git a/dDatabase/MigrationRunner.h b/dDatabase/MigrationRunner.h index 343b252d..f5d1325a 100644 --- a/dDatabase/MigrationRunner.h +++ b/dDatabase/MigrationRunner.h @@ -16,4 +16,4 @@ class MigrationRunner { public: static void RunMigrations(); static Migration LoadMigration(std::string path); -}; \ No newline at end of file +}; diff --git a/dDatabase/Tables/CDActivitiesTable.cpp b/dDatabase/Tables/CDActivitiesTable.cpp index daa07b52..835ca3d2 100644 --- a/dDatabase/Tables/CDActivitiesTable.cpp +++ b/dDatabase/Tables/CDActivitiesTable.cpp @@ -49,7 +49,7 @@ CDActivitiesTable::CDActivitiesTable(void) { } //! Destructor -CDActivitiesTable::~CDActivitiesTable(void) { } +CDActivitiesTable::~CDActivitiesTable(void) {} //! Returns the table's name std::string CDActivitiesTable::GetName(void) const { diff --git a/dDatabase/Tables/CDActivityRewardsTable.cpp b/dDatabase/Tables/CDActivityRewardsTable.cpp index 03424de3..f1719204 100644 --- a/dDatabase/Tables/CDActivityRewardsTable.cpp +++ b/dDatabase/Tables/CDActivityRewardsTable.cpp @@ -2,59 +2,59 @@ //! Constructor CDActivityRewardsTable::CDActivityRewardsTable(void) { - - // First, get the size of the table - unsigned int size = 0; - auto tableSize = CDClientDatabase::ExecuteQuery("SELECT COUNT(*) FROM ActivityRewards"); - while (!tableSize.eof()) { - size = tableSize.getIntField(0, 0); - - tableSize.nextRow(); - } + + // First, get the size of the table + unsigned int size = 0; + auto tableSize = CDClientDatabase::ExecuteQuery("SELECT COUNT(*) FROM ActivityRewards"); + while (!tableSize.eof()) { + size = tableSize.getIntField(0, 0); + + tableSize.nextRow(); + } tableSize.finalize(); - - // Reserve the size - this->entries.reserve(size); - - // Now get the data - auto tableData = CDClientDatabase::ExecuteQuery("SELECT * FROM ActivityRewards"); - while (!tableData.eof()) { - CDActivityRewards entry; - entry.objectTemplate = tableData.getIntField(0, -1); - entry.ActivityRewardIndex = tableData.getIntField(1, -1); - entry.activityRating = tableData.getIntField(2, -1); - entry.LootMatrixIndex = tableData.getIntField(3, -1); - entry.CurrencyIndex = tableData.getIntField(4, -1); - entry.ChallengeRating = tableData.getIntField(5, -1); - entry.description = tableData.getStringField(6, ""); - - this->entries.push_back(entry); - tableData.nextRow(); - } + + // Reserve the size + this->entries.reserve(size); + + // Now get the data + auto tableData = CDClientDatabase::ExecuteQuery("SELECT * FROM ActivityRewards"); + while (!tableData.eof()) { + CDActivityRewards entry; + entry.objectTemplate = tableData.getIntField(0, -1); + entry.ActivityRewardIndex = tableData.getIntField(1, -1); + entry.activityRating = tableData.getIntField(2, -1); + entry.LootMatrixIndex = tableData.getIntField(3, -1); + entry.CurrencyIndex = tableData.getIntField(4, -1); + entry.ChallengeRating = tableData.getIntField(5, -1); + entry.description = tableData.getStringField(6, ""); + + this->entries.push_back(entry); + tableData.nextRow(); + } tableData.finalize(); } //! Destructor -CDActivityRewardsTable::~CDActivityRewardsTable(void) { } +CDActivityRewardsTable::~CDActivityRewardsTable(void) {} //! Returns the table's name std::string CDActivityRewardsTable::GetName(void) const { - return "ActivityRewards"; + return "ActivityRewards"; } //! Queries the table with a custom "where" clause std::vector CDActivityRewardsTable::Query(std::function predicate) { - - std::vector data = cpplinq::from(this->entries) - >> cpplinq::where(predicate) - >> cpplinq::to_vector(); - - return data; + + std::vector data = cpplinq::from(this->entries) + >> cpplinq::where(predicate) + >> cpplinq::to_vector(); + + return data; } //! Gets all the entries in the table std::vector CDActivityRewardsTable::GetEntries(void) const { - return this->entries; + return this->entries; } diff --git a/dDatabase/Tables/CDActivityRewardsTable.h b/dDatabase/Tables/CDActivityRewardsTable.h index fb3a5b09..7f1e81a0 100644 --- a/dDatabase/Tables/CDActivityRewardsTable.h +++ b/dDatabase/Tables/CDActivityRewardsTable.h @@ -8,47 +8,47 @@ \brief Contains data for the ActivityRewards table */ -//! ActivityRewards Entry Struct + //! ActivityRewards Entry Struct struct CDActivityRewards { - unsigned int objectTemplate; //!< The object template (?) - unsigned int ActivityRewardIndex; //!< The activity reward index - int activityRating; //!< The activity rating - unsigned int LootMatrixIndex; //!< The loot matrix index - unsigned int CurrencyIndex; //!< The currency index - unsigned int ChallengeRating; //!< The challenge rating - std::string description; //!< The description + unsigned int objectTemplate; //!< The object template (?) + unsigned int ActivityRewardIndex; //!< The activity reward index + int activityRating; //!< The activity rating + unsigned int LootMatrixIndex; //!< The loot matrix index + unsigned int CurrencyIndex; //!< The currency index + unsigned int ChallengeRating; //!< The challenge rating + std::string description; //!< The description }; //! ActivityRewards table class CDActivityRewardsTable : public CDTable { private: - std::vector entries; - + std::vector entries; + public: - - //! Constructor - CDActivityRewardsTable(void); - - //! Destructor - ~CDActivityRewardsTable(void); - - //! Returns the table's name - /*! - \return The table name - */ - std::string GetName(void) const override; - - //! Queries the table with a custom "where" clause - /*! - \param predicate The predicate - */ - std::vector Query(std::function predicate); - - //! Gets all the entries in the table - /*! - \return The entries - */ - std::vector GetEntries(void) const; - + + //! Constructor + CDActivityRewardsTable(void); + + //! Destructor + ~CDActivityRewardsTable(void); + + //! Returns the table's name + /*! + \return The table name + */ + std::string GetName(void) const override; + + //! Queries the table with a custom "where" clause + /*! + \param predicate The predicate + */ + std::vector Query(std::function predicate); + + //! Gets all the entries in the table + /*! + \return The entries + */ + std::vector GetEntries(void) const; + }; diff --git a/dDatabase/Tables/CDAnimationsTable.cpp b/dDatabase/Tables/CDAnimationsTable.cpp index 7056f710..399804f8 100644 --- a/dDatabase/Tables/CDAnimationsTable.cpp +++ b/dDatabase/Tables/CDAnimationsTable.cpp @@ -2,65 +2,65 @@ //! Constructor CDAnimationsTable::CDAnimationsTable(void) { - - // First, get the size of the table - unsigned int size = 0; - auto tableSize = CDClientDatabase::ExecuteQuery("SELECT COUNT(*) FROM Animations"); - while (!tableSize.eof()) { - size = tableSize.getIntField(0, 0); - - tableSize.nextRow(); - } + + // First, get the size of the table + unsigned int size = 0; + auto tableSize = CDClientDatabase::ExecuteQuery("SELECT COUNT(*) FROM Animations"); + while (!tableSize.eof()) { + size = tableSize.getIntField(0, 0); + + tableSize.nextRow(); + } tableSize.finalize(); - - // Reserve the size - this->entries.reserve(size); - - // Now get the data - auto tableData = CDClientDatabase::ExecuteQuery("SELECT * FROM Animations"); - while (!tableData.eof()) { - CDAnimations entry; - entry.animationGroupID = tableData.getIntField(0, -1); - entry.animation_type = tableData.getStringField(1, ""); - entry.animation_name = tableData.getStringField(2, ""); - entry.chance_to_play = tableData.getFloatField(3, -1.0f); - entry.min_loops = tableData.getIntField(4, -1); - entry.max_loops = tableData.getIntField(5, -1); - entry.animation_length = tableData.getFloatField(6, -1.0f); - entry.hideEquip = tableData.getIntField(7, -1) == 1 ? true : false; - entry.ignoreUpperBody = tableData.getIntField(8, -1) == 1 ? true : false; - entry.restartable = tableData.getIntField(9, -1) == 1 ? true : false; - entry.face_animation_name = tableData.getStringField(10, ""); - entry.priority = tableData.getFloatField(11, -1.0f); - entry.blendTime = tableData.getFloatField(12, -1.0f); - - this->entries.push_back(entry); - tableData.nextRow(); - } + + // Reserve the size + this->entries.reserve(size); + + // Now get the data + auto tableData = CDClientDatabase::ExecuteQuery("SELECT * FROM Animations"); + while (!tableData.eof()) { + CDAnimations entry; + entry.animationGroupID = tableData.getIntField(0, -1); + entry.animation_type = tableData.getStringField(1, ""); + entry.animation_name = tableData.getStringField(2, ""); + entry.chance_to_play = tableData.getFloatField(3, -1.0f); + entry.min_loops = tableData.getIntField(4, -1); + entry.max_loops = tableData.getIntField(5, -1); + entry.animation_length = tableData.getFloatField(6, -1.0f); + entry.hideEquip = tableData.getIntField(7, -1) == 1 ? true : false; + entry.ignoreUpperBody = tableData.getIntField(8, -1) == 1 ? true : false; + entry.restartable = tableData.getIntField(9, -1) == 1 ? true : false; + entry.face_animation_name = tableData.getStringField(10, ""); + entry.priority = tableData.getFloatField(11, -1.0f); + entry.blendTime = tableData.getFloatField(12, -1.0f); + + this->entries.push_back(entry); + tableData.nextRow(); + } tableData.finalize(); } //! Destructor -CDAnimationsTable::~CDAnimationsTable(void) { } +CDAnimationsTable::~CDAnimationsTable(void) {} //! Returns the table's name std::string CDAnimationsTable::GetName(void) const { - return "Animations"; + return "Animations"; } //! Queries the table with a custom "where" clause std::vector CDAnimationsTable::Query(std::function predicate) { - - std::vector data = cpplinq::from(this->entries) - >> cpplinq::where(predicate) - >> cpplinq::to_vector(); - - return data; + + std::vector data = cpplinq::from(this->entries) + >> cpplinq::where(predicate) + >> cpplinq::to_vector(); + + return data; } //! Gets all the entries in the table std::vector CDAnimationsTable::GetEntries(void) const { - return this->entries; + return this->entries; } diff --git a/dDatabase/Tables/CDAnimationsTable.h b/dDatabase/Tables/CDAnimationsTable.h index 61638f74..24112985 100644 --- a/dDatabase/Tables/CDAnimationsTable.h +++ b/dDatabase/Tables/CDAnimationsTable.h @@ -8,53 +8,53 @@ \brief Contains data for the Animations table */ -//! Animations Entry Struct + //! Animations Entry Struct struct CDAnimations { - unsigned int animationGroupID; //!< The animation group ID - std::string animation_type; //!< The animation type - std::string animation_name; //!< The animation name - float chance_to_play; //!< The chance to play the animation - unsigned int min_loops; //!< The minimum number of loops - unsigned int max_loops; //!< The maximum number of loops - float animation_length; //!< The animation length - bool hideEquip; //!< Whether or not to hide the equip - bool ignoreUpperBody; //!< Whether or not to ignore the upper body - bool restartable; //!< Whether or not the animation is restartable - std::string face_animation_name; //!< The face animation name - float priority; //!< The priority - float blendTime; //!< The blend time + unsigned int animationGroupID; //!< The animation group ID + std::string animation_type; //!< The animation type + std::string animation_name; //!< The animation name + float chance_to_play; //!< The chance to play the animation + unsigned int min_loops; //!< The minimum number of loops + unsigned int max_loops; //!< The maximum number of loops + float animation_length; //!< The animation length + bool hideEquip; //!< Whether or not to hide the equip + bool ignoreUpperBody; //!< Whether or not to ignore the upper body + bool restartable; //!< Whether or not the animation is restartable + std::string face_animation_name; //!< The face animation name + float priority; //!< The priority + float blendTime; //!< The blend time }; //! Animations table class CDAnimationsTable : public CDTable { private: - std::vector entries; - + std::vector entries; + public: - - //! Constructor - CDAnimationsTable(void); - - //! Destructor - ~CDAnimationsTable(void); - - //! Returns the table's name - /*! - \return The table name - */ - std::string GetName(void) const override; - - //! Queries the table with a custom "where" clause - /*! - \param predicate The predicate - */ - std::vector Query(std::function predicate); - - //! Gets all the entries in the table - /*! - \return The entries - */ - std::vector GetEntries(void) const; - + + //! Constructor + CDAnimationsTable(void); + + //! Destructor + ~CDAnimationsTable(void); + + //! Returns the table's name + /*! + \return The table name + */ + std::string GetName(void) const override; + + //! Queries the table with a custom "where" clause + /*! + \param predicate The predicate + */ + std::vector Query(std::function predicate); + + //! Gets all the entries in the table + /*! + \return The entries + */ + std::vector GetEntries(void) const; + }; diff --git a/dDatabase/Tables/CDBehaviorParameterTable.cpp b/dDatabase/Tables/CDBehaviorParameterTable.cpp index 05f39016..96015896 100644 --- a/dDatabase/Tables/CDBehaviorParameterTable.cpp +++ b/dDatabase/Tables/CDBehaviorParameterTable.cpp @@ -31,15 +31,14 @@ CDBehaviorParameterTable::CDBehaviorParameterTable(void) { } //! Destructor -CDBehaviorParameterTable::~CDBehaviorParameterTable(void) { } +CDBehaviorParameterTable::~CDBehaviorParameterTable(void) {} //! Returns the table's name std::string CDBehaviorParameterTable::GetName(void) const { return "BehaviorParameter"; } -CDBehaviorParameter CDBehaviorParameterTable::GetEntry(const uint32_t behaviorID, const std::string& name, const float defaultValue) -{ +CDBehaviorParameter CDBehaviorParameterTable::GetEntry(const uint32_t behaviorID, const std::string& name, const float defaultValue) { CDBehaviorParameter returnValue; returnValue.behaviorID = 0; returnValue.parameterID = m_ParametersList.end(); diff --git a/dDatabase/Tables/CDBehaviorParameterTable.h b/dDatabase/Tables/CDBehaviorParameterTable.h index c45d287b..f067e7d2 100644 --- a/dDatabase/Tables/CDBehaviorParameterTable.h +++ b/dDatabase/Tables/CDBehaviorParameterTable.h @@ -10,11 +10,11 @@ \brief Contains data for the BehaviorParameter table */ -//! BehaviorParameter Entry Struct + //! BehaviorParameter Entry Struct struct CDBehaviorParameter { - unsigned int behaviorID; //!< The Behavior ID - std::unordered_set::iterator parameterID; //!< The Parameter ID - float value; //!< The value of the behavior template + unsigned int behaviorID; //!< The Behavior ID + std::unordered_set::iterator parameterID; //!< The Parameter ID + float value; //!< The value of the behavior template }; //! BehaviorParameter table @@ -23,19 +23,19 @@ private: std::unordered_map m_Entries; std::unordered_set m_ParametersList; public: - - //! Constructor - CDBehaviorParameterTable(void); - - //! Destructor - ~CDBehaviorParameterTable(void); - - //! Returns the table's name - /*! - \return The table name - */ - std::string GetName(void) const override; - + + //! Constructor + CDBehaviorParameterTable(void); + + //! Destructor + ~CDBehaviorParameterTable(void); + + //! Returns the table's name + /*! + \return The table name + */ + std::string GetName(void) const override; + CDBehaviorParameter GetEntry(const uint32_t behaviorID, const std::string& name, const float defaultValue = 0); std::map GetParametersByBehaviorID(uint32_t behaviorID); diff --git a/dDatabase/Tables/CDBehaviorTemplateTable.cpp b/dDatabase/Tables/CDBehaviorTemplateTable.cpp index b832400d..1628756f 100644 --- a/dDatabase/Tables/CDBehaviorTemplateTable.cpp +++ b/dDatabase/Tables/CDBehaviorTemplateTable.cpp @@ -2,76 +2,76 @@ //! Constructor CDBehaviorTemplateTable::CDBehaviorTemplateTable(void) { - - // First, get the size of the table - unsigned int size = 0; - auto tableSize = CDClientDatabase::ExecuteQuery("SELECT COUNT(*) FROM BehaviorTemplate"); - while (!tableSize.eof()) { - size = tableSize.getIntField(0, 0); - - tableSize.nextRow(); - } - - tableSize.finalize(); - - // Reserve the size - this->entries.reserve(size); - // Now get the data - auto tableData = CDClientDatabase::ExecuteQuery("SELECT * FROM BehaviorTemplate"); - while (!tableData.eof()) { - CDBehaviorTemplate entry; - entry.behaviorID = tableData.getIntField(0, -1); - entry.templateID = tableData.getIntField(1, -1); - entry.effectID = tableData.getIntField(2, -1); - auto candidateToAdd = tableData.getStringField(3, ""); - auto parameter = m_EffectHandles.find(candidateToAdd); - if (parameter != m_EffectHandles.end()) { - entry.effectHandle = parameter; - } else { - entry.effectHandle = m_EffectHandles.insert(candidateToAdd).first; - } - - this->entries.push_back(entry); - this->entriesMappedByBehaviorID.insert(std::make_pair(entry.behaviorID, entry)); - tableData.nextRow(); - } + // First, get the size of the table + unsigned int size = 0; + auto tableSize = CDClientDatabase::ExecuteQuery("SELECT COUNT(*) FROM BehaviorTemplate"); + while (!tableSize.eof()) { + size = tableSize.getIntField(0, 0); + + tableSize.nextRow(); + } + + tableSize.finalize(); + + // Reserve the size + this->entries.reserve(size); + + // Now get the data + auto tableData = CDClientDatabase::ExecuteQuery("SELECT * FROM BehaviorTemplate"); + while (!tableData.eof()) { + CDBehaviorTemplate entry; + entry.behaviorID = tableData.getIntField(0, -1); + entry.templateID = tableData.getIntField(1, -1); + entry.effectID = tableData.getIntField(2, -1); + auto candidateToAdd = tableData.getStringField(3, ""); + auto parameter = m_EffectHandles.find(candidateToAdd); + if (parameter != m_EffectHandles.end()) { + entry.effectHandle = parameter; + } else { + entry.effectHandle = m_EffectHandles.insert(candidateToAdd).first; + } + + this->entries.push_back(entry); + this->entriesMappedByBehaviorID.insert(std::make_pair(entry.behaviorID, entry)); + tableData.nextRow(); + } tableData.finalize(); } //! Destructor -CDBehaviorTemplateTable::~CDBehaviorTemplateTable(void) { } +CDBehaviorTemplateTable::~CDBehaviorTemplateTable(void) {} //! Returns the table's name std::string CDBehaviorTemplateTable::GetName(void) const { - return "BehaviorTemplate"; + return "BehaviorTemplate"; } //! Queries the table with a custom "where" clause std::vector CDBehaviorTemplateTable::Query(std::function predicate) { - - std::vector data = cpplinq::from(this->entries) - >> cpplinq::where(predicate) - >> cpplinq::to_vector(); - - return data; + + std::vector data = cpplinq::from(this->entries) + >> cpplinq::where(predicate) + >> cpplinq::to_vector(); + + return data; } //! Gets all the entries in the table std::vector CDBehaviorTemplateTable::GetEntries(void) const { - return this->entries; + return this->entries; } const CDBehaviorTemplate CDBehaviorTemplateTable::GetByBehaviorID(uint32_t behaviorID) { - auto entry = this->entriesMappedByBehaviorID.find(behaviorID); - if (entry == this->entriesMappedByBehaviorID.end()) { - CDBehaviorTemplate entryToReturn; - entryToReturn.behaviorID = 0; - entryToReturn.effectHandle = m_EffectHandles.end(); - entryToReturn.effectID = 0; - return entryToReturn; - } else { - return entry->second; - } + auto entry = this->entriesMappedByBehaviorID.find(behaviorID); + if (entry == this->entriesMappedByBehaviorID.end()) { + CDBehaviorTemplate entryToReturn; + entryToReturn.behaviorID = 0; + entryToReturn.effectHandle = m_EffectHandles.end(); + entryToReturn.effectID = 0; + return entryToReturn; + } else { + return entry->second; + } } diff --git a/dDatabase/Tables/CDBehaviorTemplateTable.h b/dDatabase/Tables/CDBehaviorTemplateTable.h index 170da854..b2bd2521 100644 --- a/dDatabase/Tables/CDBehaviorTemplateTable.h +++ b/dDatabase/Tables/CDBehaviorTemplateTable.h @@ -10,46 +10,46 @@ \brief Contains data for the BehaviorTemplate table */ -//! BehaviorTemplate Entry Struct + //! BehaviorTemplate Entry Struct struct CDBehaviorTemplate { - unsigned int behaviorID; //!< The Behavior ID - unsigned int templateID; //!< The Template ID (LOT) - unsigned int effectID; //!< The Effect ID attached - std::unordered_set::iterator effectHandle; //!< The effect handle + unsigned int behaviorID; //!< The Behavior ID + unsigned int templateID; //!< The Template ID (LOT) + unsigned int effectID; //!< The Effect ID attached + std::unordered_set::iterator effectHandle; //!< The effect handle }; //! BehaviorTemplate table class CDBehaviorTemplateTable : public CDTable { private: - std::vector entries; - std::unordered_map entriesMappedByBehaviorID; - std::unordered_set m_EffectHandles; + std::vector entries; + std::unordered_map entriesMappedByBehaviorID; + std::unordered_set m_EffectHandles; public: - - //! Constructor - CDBehaviorTemplateTable(void); - - //! Destructor - ~CDBehaviorTemplateTable(void); - - //! Returns the table's name - /*! - \return The table name - */ - std::string GetName(void) const override; - - //! Queries the table with a custom "where" clause - /*! - \param predicate The predicate - */ - std::vector Query(std::function predicate); - - //! Gets all the entries in the table - /*! - \return The entries - */ - std::vector GetEntries(void) const; - const CDBehaviorTemplate GetByBehaviorID(uint32_t behaviorID); + //! Constructor + CDBehaviorTemplateTable(void); + + //! Destructor + ~CDBehaviorTemplateTable(void); + + //! Returns the table's name + /*! + \return The table name + */ + std::string GetName(void) const override; + + //! Queries the table with a custom "where" clause + /*! + \param predicate The predicate + */ + std::vector Query(std::function predicate); + + //! Gets all the entries in the table + /*! + \return The entries + */ + std::vector GetEntries(void) const; + + const CDBehaviorTemplate GetByBehaviorID(uint32_t behaviorID); }; diff --git a/dDatabase/Tables/CDBrickIDTableTable.cpp b/dDatabase/Tables/CDBrickIDTableTable.cpp index a3fc860e..9dbdf2c0 100644 --- a/dDatabase/Tables/CDBrickIDTableTable.cpp +++ b/dDatabase/Tables/CDBrickIDTableTable.cpp @@ -11,9 +11,9 @@ CDBrickIDTableTable::CDBrickIDTableTable(void) { tableSize.nextRow(); } - + tableSize.finalize(); - + // Reserve the size this->entries.reserve(size); @@ -32,7 +32,7 @@ CDBrickIDTableTable::CDBrickIDTableTable(void) { } //! Destructor -CDBrickIDTableTable::~CDBrickIDTableTable(void) { } +CDBrickIDTableTable::~CDBrickIDTableTable(void) {} //! Returns the table's name std::string CDBrickIDTableTable::GetName(void) const { diff --git a/dDatabase/Tables/CDComponentsRegistryTable.cpp b/dDatabase/Tables/CDComponentsRegistryTable.cpp index 7e746fb0..8e5ae108 100644 --- a/dDatabase/Tables/CDComponentsRegistryTable.cpp +++ b/dDatabase/Tables/CDComponentsRegistryTable.cpp @@ -4,33 +4,33 @@ //! Constructor CDComponentsRegistryTable::CDComponentsRegistryTable(void) { - -#ifdef CDCLIENT_CACHE_ALL - // First, get the size of the table - unsigned int size = 0; - auto tableSize = CDClientDatabase::ExecuteQuery("SELECT COUNT(*) FROM ComponentsRegistry"); - while (!tableSize.eof()) { - size = tableSize.getIntField(0, 0); - - tableSize.nextRow(); - } - - tableSize.finalize(); - - // Reserve the size - //this->entries.reserve(size); - - // Now get the data - auto tableData = CDClientDatabase::ExecuteQuery("SELECT * FROM ComponentsRegistry"); - while (!tableData.eof()) { - CDComponentsRegistry entry; - entry.id = tableData.getIntField(0, -1); - entry.component_type = tableData.getIntField(1, -1); - entry.component_id = tableData.getIntField(2, -1); - this->mappedEntries.insert_or_assign(((uint64_t) entry.component_type) << 32 | ((uint64_t) entry.id), entry.component_id); - - //this->entries.push_back(entry); +#ifdef CDCLIENT_CACHE_ALL + // First, get the size of the table + unsigned int size = 0; + auto tableSize = CDClientDatabase::ExecuteQuery("SELECT COUNT(*) FROM ComponentsRegistry"); + while (!tableSize.eof()) { + size = tableSize.getIntField(0, 0); + + tableSize.nextRow(); + } + + tableSize.finalize(); + + // Reserve the size + //this->entries.reserve(size); + + // Now get the data + auto tableData = CDClientDatabase::ExecuteQuery("SELECT * FROM ComponentsRegistry"); + while (!tableData.eof()) { + CDComponentsRegistry entry; + entry.id = tableData.getIntField(0, -1); + entry.component_type = tableData.getIntField(1, -1); + entry.component_id = tableData.getIntField(2, -1); + + this->mappedEntries.insert_or_assign(((uint64_t)entry.component_type) << 32 | ((uint64_t)entry.id), entry.component_id); + + //this->entries.push_back(entry); /* //Darwin's stuff: @@ -48,27 +48,25 @@ CDComponentsRegistryTable::CDComponentsRegistryTable(void) { } */ - tableData.nextRow(); - } + tableData.nextRow(); + } tableData.finalize(); #endif } //! Destructor -CDComponentsRegistryTable::~CDComponentsRegistryTable(void) { } +CDComponentsRegistryTable::~CDComponentsRegistryTable(void) {} //! Returns the table's name std::string CDComponentsRegistryTable::GetName(void) const { - return "ComponentsRegistry"; + return "ComponentsRegistry"; } -int32_t CDComponentsRegistryTable::GetByIDAndType(uint32_t id, uint32_t componentType, int32_t defaultValue) -{ - const auto& iter = this->mappedEntries.find(((uint64_t) componentType) << 32 | ((uint64_t) id)); +int32_t CDComponentsRegistryTable::GetByIDAndType(uint32_t id, uint32_t componentType, int32_t defaultValue) { + const auto& iter = this->mappedEntries.find(((uint64_t)componentType) << 32 | ((uint64_t)id)); - if (iter == this->mappedEntries.end()) - { + if (iter == this->mappedEntries.end()) { return defaultValue; } @@ -85,19 +83,19 @@ int32_t CDComponentsRegistryTable::GetByIDAndType(uint32_t id, uint32_t componen */ #ifndef CDCLIENT_CACHE_ALL - // Now get the data + // Now get the data std::stringstream query; query << "SELECT * FROM ComponentsRegistry WHERE id = " << std::to_string(id); auto tableData = CDClientDatabase::ExecuteQuery(query.str()); - while (!tableData.eof()) { - CDComponentsRegistry entry; - entry.id = tableData.getIntField(0, -1); - entry.component_type = tableData.getIntField(1, -1); - entry.component_id = tableData.getIntField(2, -1); - - //this->entries.push_back(entry); + while (!tableData.eof()) { + CDComponentsRegistry entry; + entry.id = tableData.getIntField(0, -1); + entry.component_type = tableData.getIntField(1, -1); + entry.component_id = tableData.getIntField(2, -1); + + //this->entries.push_back(entry); //Darwin's stuff: const auto& it = this->mappedEntries.find(entry.id); @@ -106,15 +104,14 @@ int32_t CDComponentsRegistryTable::GetByIDAndType(uint32_t id, uint32_t componen if (iter == it->second.end()) { it->second.insert(std::make_pair(entry.component_type, entry.component_id)); } - } - else { + } else { std::map map; map.insert(std::make_pair(entry.component_type, entry.component_id)); this->mappedEntries.insert(std::make_pair(entry.id, map)); } - tableData.nextRow(); - } + tableData.nextRow(); + } tableData.finalize(); diff --git a/dDatabase/Tables/CDComponentsRegistryTable.h b/dDatabase/Tables/CDComponentsRegistryTable.h index 4a02bf94..c3eb0ed2 100644 --- a/dDatabase/Tables/CDComponentsRegistryTable.h +++ b/dDatabase/Tables/CDComponentsRegistryTable.h @@ -8,33 +8,33 @@ \brief Contains data for the ComponentsRegistry table */ -//! ComponentsRegistry Entry Struct + //! ComponentsRegistry Entry Struct struct CDComponentsRegistry { - unsigned int id; //!< The LOT is used as the ID - unsigned int component_type; //!< See ComponentTypes enum for values - unsigned int component_id; //!< The ID used within the component's table (0 may either mean it's non-networked, or that the ID is actually 0 + unsigned int id; //!< The LOT is used as the ID + unsigned int component_type; //!< See ComponentTypes enum for values + unsigned int component_id; //!< The ID used within the component's table (0 may either mean it's non-networked, or that the ID is actually 0 }; //! ComponentsRegistry table class CDComponentsRegistryTable : public CDTable { private: - //std::vector entries; - std::map mappedEntries; //id, component_type, component_id - -public: - - //! Constructor - CDComponentsRegistryTable(void); - - //! Destructor - ~CDComponentsRegistryTable(void); - - //! Returns the table's name - /*! - \return The table name - */ - std::string GetName(void) const override; + //std::vector entries; + std::map mappedEntries; //id, component_type, component_id - int32_t GetByIDAndType(uint32_t id, uint32_t componentType, int32_t defaultValue = 0); +public: + + //! Constructor + CDComponentsRegistryTable(void); + + //! Destructor + ~CDComponentsRegistryTable(void); + + //! Returns the table's name + /*! + \return The table name + */ + std::string GetName(void) const override; + + int32_t GetByIDAndType(uint32_t id, uint32_t componentType, int32_t defaultValue = 0); }; diff --git a/dDatabase/Tables/CDCurrencyTableTable.cpp b/dDatabase/Tables/CDCurrencyTableTable.cpp index cfe26e73..a1923a73 100644 --- a/dDatabase/Tables/CDCurrencyTableTable.cpp +++ b/dDatabase/Tables/CDCurrencyTableTable.cpp @@ -2,57 +2,57 @@ //! Constructor CDCurrencyTableTable::CDCurrencyTableTable(void) { - - // First, get the size of the table - unsigned int size = 0; - auto tableSize = CDClientDatabase::ExecuteQuery("SELECT COUNT(*) FROM CurrencyTable"); - while (!tableSize.eof()) { - size = tableSize.getIntField(0, 0); - - tableSize.nextRow(); - } - + + // First, get the size of the table + unsigned int size = 0; + auto tableSize = CDClientDatabase::ExecuteQuery("SELECT COUNT(*) FROM CurrencyTable"); + while (!tableSize.eof()) { + size = tableSize.getIntField(0, 0); + + tableSize.nextRow(); + } + tableSize.finalize(); - - // Reserve the size - this->entries.reserve(size); - - // Now get the data - auto tableData = CDClientDatabase::ExecuteQuery("SELECT * FROM CurrencyTable"); - while (!tableData.eof()) { - CDCurrencyTable entry; - entry.currencyIndex = tableData.getIntField(0, -1); - entry.npcminlevel = tableData.getIntField(1, -1); - entry.minvalue = tableData.getIntField(2, -1); - entry.maxvalue = tableData.getIntField(3, -1); - entry.id = tableData.getIntField(4, -1); - - this->entries.push_back(entry); - tableData.nextRow(); - } + + // Reserve the size + this->entries.reserve(size); + + // Now get the data + auto tableData = CDClientDatabase::ExecuteQuery("SELECT * FROM CurrencyTable"); + while (!tableData.eof()) { + CDCurrencyTable entry; + entry.currencyIndex = tableData.getIntField(0, -1); + entry.npcminlevel = tableData.getIntField(1, -1); + entry.minvalue = tableData.getIntField(2, -1); + entry.maxvalue = tableData.getIntField(3, -1); + entry.id = tableData.getIntField(4, -1); + + this->entries.push_back(entry); + tableData.nextRow(); + } tableData.finalize(); } //! Destructor -CDCurrencyTableTable::~CDCurrencyTableTable(void) { } +CDCurrencyTableTable::~CDCurrencyTableTable(void) {} //! Returns the table's name std::string CDCurrencyTableTable::GetName(void) const { - return "CurrencyTable"; + return "CurrencyTable"; } //! Queries the table with a custom "where" clause std::vector CDCurrencyTableTable::Query(std::function predicate) { - - std::vector data = cpplinq::from(this->entries) - >> cpplinq::where(predicate) - >> cpplinq::to_vector(); - - return data; + + std::vector data = cpplinq::from(this->entries) + >> cpplinq::where(predicate) + >> cpplinq::to_vector(); + + return data; } //! Gets all the entries in the table std::vector CDCurrencyTableTable::GetEntries(void) const { - return this->entries; + return this->entries; } diff --git a/dDatabase/Tables/CDCurrencyTableTable.h b/dDatabase/Tables/CDCurrencyTableTable.h index b980a18a..5a856395 100644 --- a/dDatabase/Tables/CDCurrencyTableTable.h +++ b/dDatabase/Tables/CDCurrencyTableTable.h @@ -8,44 +8,44 @@ \brief Contains data for the CurrencyTable table */ -//! CurrencyTable Struct + //! CurrencyTable Struct struct CDCurrencyTable { - unsigned int currencyIndex; //!< The Currency Index - unsigned int npcminlevel; //!< The minimum level of the npc - unsigned int minvalue; //!< The minimum currency - unsigned int maxvalue; //!< The maximum currency - unsigned int id; //!< The ID of the currency index + unsigned int currencyIndex; //!< The Currency Index + unsigned int npcminlevel; //!< The minimum level of the npc + unsigned int minvalue; //!< The minimum currency + unsigned int maxvalue; //!< The maximum currency + unsigned int id; //!< The ID of the currency index }; //! CurrencyTable table class CDCurrencyTableTable : public CDTable { private: - std::vector entries; - + std::vector entries; + public: - - //! Constructor - CDCurrencyTableTable(void); - - //! Destructor - ~CDCurrencyTableTable(void); - - //! Returns the table's name - /*! - \return The table name - */ - std::string GetName(void) const override; - - //! Queries the table with a custom "where" clause - /*! - \param predicate The predicate - */ - std::vector Query(std::function predicate); - - //! Gets all the entries in the table - /*! - \return The entries - */ - std::vector GetEntries(void) const; - + + //! Constructor + CDCurrencyTableTable(void); + + //! Destructor + ~CDCurrencyTableTable(void); + + //! Returns the table's name + /*! + \return The table name + */ + std::string GetName(void) const override; + + //! Queries the table with a custom "where" clause + /*! + \param predicate The predicate + */ + std::vector Query(std::function predicate); + + //! Gets all the entries in the table + /*! + \return The entries + */ + std::vector GetEntries(void) const; + }; diff --git a/dDatabase/Tables/CDDestructibleComponentTable.cpp b/dDatabase/Tables/CDDestructibleComponentTable.cpp index 6eb64e7f..d7438fc7 100644 --- a/dDatabase/Tables/CDDestructibleComponentTable.cpp +++ b/dDatabase/Tables/CDDestructibleComponentTable.cpp @@ -2,66 +2,66 @@ //! Constructor CDDestructibleComponentTable::CDDestructibleComponentTable(void) { - - // First, get the size of the table - unsigned int size = 0; - auto tableSize = CDClientDatabase::ExecuteQuery("SELECT COUNT(*) FROM DestructibleComponent"); - while (!tableSize.eof()) { - size = tableSize.getIntField(0, 0); - - tableSize.nextRow(); - } - + + // First, get the size of the table + unsigned int size = 0; + auto tableSize = CDClientDatabase::ExecuteQuery("SELECT COUNT(*) FROM DestructibleComponent"); + while (!tableSize.eof()) { + size = tableSize.getIntField(0, 0); + + tableSize.nextRow(); + } + tableSize.finalize(); - - // Reserve the size - this->entries.reserve(size); - - // Now get the data - auto tableData = CDClientDatabase::ExecuteQuery("SELECT * FROM DestructibleComponent"); - while (!tableData.eof()) { - CDDestructibleComponent entry; - entry.id = tableData.getIntField(0, -1); - entry.faction = tableData.getIntField(1, -1); - entry.factionList = tableData.getStringField(2, ""); - entry.life = tableData.getIntField(3, -1); - entry.imagination = tableData.getIntField(4, -1); - entry.LootMatrixIndex = tableData.getIntField(5, -1); - entry.CurrencyIndex = tableData.getIntField(6, -1); - entry.level = tableData.getIntField(7, -1); - entry.armor = tableData.getFloatField(8, -1.0f); - entry.death_behavior = tableData.getIntField(9, -1); - entry.isnpc = tableData.getIntField(10, -1) == 1 ? true : false; - entry.attack_priority = tableData.getIntField(11, -1); - entry.isSmashable = tableData.getIntField(12, -1) == 1 ? true : false; - entry.difficultyLevel = tableData.getIntField(13, -1); - - this->entries.push_back(entry); - tableData.nextRow(); - } + + // Reserve the size + this->entries.reserve(size); + + // Now get the data + auto tableData = CDClientDatabase::ExecuteQuery("SELECT * FROM DestructibleComponent"); + while (!tableData.eof()) { + CDDestructibleComponent entry; + entry.id = tableData.getIntField(0, -1); + entry.faction = tableData.getIntField(1, -1); + entry.factionList = tableData.getStringField(2, ""); + entry.life = tableData.getIntField(3, -1); + entry.imagination = tableData.getIntField(4, -1); + entry.LootMatrixIndex = tableData.getIntField(5, -1); + entry.CurrencyIndex = tableData.getIntField(6, -1); + entry.level = tableData.getIntField(7, -1); + entry.armor = tableData.getFloatField(8, -1.0f); + entry.death_behavior = tableData.getIntField(9, -1); + entry.isnpc = tableData.getIntField(10, -1) == 1 ? true : false; + entry.attack_priority = tableData.getIntField(11, -1); + entry.isSmashable = tableData.getIntField(12, -1) == 1 ? true : false; + entry.difficultyLevel = tableData.getIntField(13, -1); + + this->entries.push_back(entry); + tableData.nextRow(); + } tableData.finalize(); } //! Destructor -CDDestructibleComponentTable::~CDDestructibleComponentTable(void) { } +CDDestructibleComponentTable::~CDDestructibleComponentTable(void) {} //! Returns the table's name std::string CDDestructibleComponentTable::GetName(void) const { - return "DestructibleComponent"; + return "DestructibleComponent"; } //! Queries the table with a custom "where" clause std::vector CDDestructibleComponentTable::Query(std::function predicate) { - - std::vector data = cpplinq::from(this->entries) - >> cpplinq::where(predicate) - >> cpplinq::to_vector(); - - return data; + + std::vector data = cpplinq::from(this->entries) + >> cpplinq::where(predicate) + >> cpplinq::to_vector(); + + return data; } //! Gets all the entries in the table std::vector CDDestructibleComponentTable::GetEntries(void) const { - return this->entries; + return this->entries; } diff --git a/dDatabase/Tables/CDDestructibleComponentTable.h b/dDatabase/Tables/CDDestructibleComponentTable.h index 9768b6df..e89bbff8 100644 --- a/dDatabase/Tables/CDDestructibleComponentTable.h +++ b/dDatabase/Tables/CDDestructibleComponentTable.h @@ -8,53 +8,53 @@ \brief Contains data for the DestructibleComponent table */ -//! ItemComponent Struct + //! ItemComponent Struct struct CDDestructibleComponent { - unsigned int id; //!< The component ID from the ComponentsRegistry Table - int faction; //!< The Faction ID of the object - std::string factionList; //!< A list of the faction IDs - int life; //!< The amount of life of the object - unsigned int imagination; //!< The amount of imagination of the object - int LootMatrixIndex; //!< The Loot Matrix Index - int CurrencyIndex; //!< The Currency Index - unsigned int level; //!< ??? - float armor; //!< The amount of armor of the object - unsigned int death_behavior; //!< The behavior ID of the death behavior - bool isnpc; //!< Whether or not the object is an NPC - unsigned int attack_priority; //!< ??? - bool isSmashable; //!< Whether or not the object is smashable - int difficultyLevel; //!< ??? + unsigned int id; //!< The component ID from the ComponentsRegistry Table + int faction; //!< The Faction ID of the object + std::string factionList; //!< A list of the faction IDs + int life; //!< The amount of life of the object + unsigned int imagination; //!< The amount of imagination of the object + int LootMatrixIndex; //!< The Loot Matrix Index + int CurrencyIndex; //!< The Currency Index + unsigned int level; //!< ??? + float armor; //!< The amount of armor of the object + unsigned int death_behavior; //!< The behavior ID of the death behavior + bool isnpc; //!< Whether or not the object is an NPC + unsigned int attack_priority; //!< ??? + bool isSmashable; //!< Whether or not the object is smashable + int difficultyLevel; //!< ??? }; //! ItemComponent table class CDDestructibleComponentTable : public CDTable { private: - std::vector entries; - + std::vector entries; + public: - - //! Constructor - CDDestructibleComponentTable(void); - - //! Destructor - ~CDDestructibleComponentTable(void); - - //! Returns the table's name - /*! - \return The table name - */ - std::string GetName(void) const override; - - //! Queries the table with a custom "where" clause - /*! - \param predicate The predicate - */ - std::vector Query(std::function predicate); - - //! Gets all the entries in the table - /*! - \return The entries - */ - std::vector GetEntries(void) const; - + + //! Constructor + CDDestructibleComponentTable(void); + + //! Destructor + ~CDDestructibleComponentTable(void); + + //! Returns the table's name + /*! + \return The table name + */ + std::string GetName(void) const override; + + //! Queries the table with a custom "where" clause + /*! + \param predicate The predicate + */ + std::vector Query(std::function predicate); + + //! Gets all the entries in the table + /*! + \return The entries + */ + std::vector GetEntries(void) const; + }; diff --git a/dDatabase/Tables/CDEmoteTable.cpp b/dDatabase/Tables/CDEmoteTable.cpp index 63e985ee..e3898422 100644 --- a/dDatabase/Tables/CDEmoteTable.cpp +++ b/dDatabase/Tables/CDEmoteTable.cpp @@ -2,43 +2,43 @@ //! Constructor CDEmoteTableTable::CDEmoteTableTable(void) { - auto tableData = CDClientDatabase::ExecuteQuery("SELECT * FROM Emotes"); - while (!tableData.eof()) { - CDEmoteTable* entry = new CDEmoteTable(); - entry->ID = tableData.getIntField(0, -1); - entry->animationName = tableData.getStringField(1, ""); - entry->iconFilename = tableData.getStringField(2, ""); - entry->channel = tableData.getIntField(3, -1); - entry->locked = tableData.getIntField(5, -1) != 0; - entry->localize = tableData.getIntField(6, -1) != 0; - entry->locState = tableData.getIntField(7, -1); - entry->gateVersion = tableData.getIntField(8, -1); + auto tableData = CDClientDatabase::ExecuteQuery("SELECT * FROM Emotes"); + while (!tableData.eof()) { + CDEmoteTable* entry = new CDEmoteTable(); + entry->ID = tableData.getIntField(0, -1); + entry->animationName = tableData.getStringField(1, ""); + entry->iconFilename = tableData.getStringField(2, ""); + entry->channel = tableData.getIntField(3, -1); + entry->locked = tableData.getIntField(5, -1) != 0; + entry->localize = tableData.getIntField(6, -1) != 0; + entry->locState = tableData.getIntField(7, -1); + entry->gateVersion = tableData.getIntField(8, -1); - entries.insert(std::make_pair(entry->ID, entry)); - tableData.nextRow(); - } + entries.insert(std::make_pair(entry->ID, entry)); + tableData.nextRow(); + } tableData.finalize(); } //! Destructor CDEmoteTableTable::~CDEmoteTableTable(void) { - for (auto e : entries) { - if (e.second) delete e.second; - } - - entries.clear(); + for (auto e : entries) { + if (e.second) delete e.second; + } + + entries.clear(); } //! Returns the table's name std::string CDEmoteTableTable::GetName(void) const { - return "Emotes"; + return "Emotes"; } -CDEmoteTable * CDEmoteTableTable::GetEmote(int id) { - for (auto e : entries) { - if (e.first == id) return e.second; - } - - return nullptr; +CDEmoteTable* CDEmoteTableTable::GetEmote(int id) { + for (auto e : entries) { + if (e.first == id) return e.second; + } + + return nullptr; } diff --git a/dDatabase/Tables/CDEmoteTable.h b/dDatabase/Tables/CDEmoteTable.h index 9fd19991..a22ae23e 100644 --- a/dDatabase/Tables/CDEmoteTable.h +++ b/dDatabase/Tables/CDEmoteTable.h @@ -9,7 +9,7 @@ \brief Contains data for the CDEmoteTable table */ -//! CDEmoteEntry Struct + //! CDEmoteEntry Struct struct CDEmoteTable { CDEmoteTable() { ID = -1; @@ -22,35 +22,35 @@ struct CDEmoteTable { gateVersion = -1; } - int ID; - std::string animationName; - std::string iconFilename; - int locState; - int channel; - bool locked; - bool localize; - int gateVersion; + int ID; + std::string animationName; + std::string iconFilename; + int locState; + int channel; + bool locked; + bool localize; + int gateVersion; }; //! CDEmoteTable table class CDEmoteTableTable : public CDTable { private: - std::map entries; + std::map entries; public: - //! Constructor - CDEmoteTableTable(void); + //! Constructor + CDEmoteTableTable(void); - //! Destructor - ~CDEmoteTableTable(void); + //! Destructor + ~CDEmoteTableTable(void); - //! Returns the table's name - /*! - \return The table name - */ - std::string GetName(void) const override; - - //! Returns an emote by ID - CDEmoteTable* GetEmote(int id); + //! Returns the table's name + /*! + \return The table name + */ + std::string GetName(void) const override; + + //! Returns an emote by ID + CDEmoteTable* GetEmote(int id); }; diff --git a/dDatabase/Tables/CDFeatureGatingTable.cpp b/dDatabase/Tables/CDFeatureGatingTable.cpp index 6a370e8b..dfc65387 100644 --- a/dDatabase/Tables/CDFeatureGatingTable.cpp +++ b/dDatabase/Tables/CDFeatureGatingTable.cpp @@ -2,70 +2,67 @@ //! Constructor CDFeatureGatingTable::CDFeatureGatingTable(void) { - - // First, get the size of the table - unsigned int size = 0; - auto tableSize = CDClientDatabase::ExecuteQuery("SELECT COUNT(*) FROM FeatureGating"); - while (!tableSize.eof()) { - size = tableSize.getIntField(0, 0); - - tableSize.nextRow(); - } - + + // First, get the size of the table + unsigned int size = 0; + auto tableSize = CDClientDatabase::ExecuteQuery("SELECT COUNT(*) FROM FeatureGating"); + while (!tableSize.eof()) { + size = tableSize.getIntField(0, 0); + + tableSize.nextRow(); + } + tableSize.finalize(); - - // Reserve the size - this->entries.reserve(size); - - // Now get the data - auto tableData = CDClientDatabase::ExecuteQuery("SELECT * FROM FeatureGating"); - while (!tableData.eof()) { - CDFeatureGating entry; - entry.featureName = tableData.getStringField(0, ""); - entry.major = tableData.getIntField(1, -1); - entry.current = tableData.getIntField(2, -1); - entry.minor = tableData.getIntField(3, -1); - entry.description = tableData.getStringField(4, ""); - - this->entries.push_back(entry); - tableData.nextRow(); - } + + // Reserve the size + this->entries.reserve(size); + + // Now get the data + auto tableData = CDClientDatabase::ExecuteQuery("SELECT * FROM FeatureGating"); + while (!tableData.eof()) { + CDFeatureGating entry; + entry.featureName = tableData.getStringField(0, ""); + entry.major = tableData.getIntField(1, -1); + entry.current = tableData.getIntField(2, -1); + entry.minor = tableData.getIntField(3, -1); + entry.description = tableData.getStringField(4, ""); + + this->entries.push_back(entry); + tableData.nextRow(); + } tableData.finalize(); } //! Destructor -CDFeatureGatingTable::~CDFeatureGatingTable(void) { } +CDFeatureGatingTable::~CDFeatureGatingTable(void) {} //! Returns the table's name std::string CDFeatureGatingTable::GetName(void) const { - return "FeatureGating"; + return "FeatureGating"; } //! Queries the table with a custom "where" clause std::vector CDFeatureGatingTable::Query(std::function predicate) { - - std::vector data = cpplinq::from(this->entries) - >> cpplinq::where(predicate) - >> cpplinq::to_vector(); - - return data; + + std::vector data = cpplinq::from(this->entries) + >> cpplinq::where(predicate) + >> cpplinq::to_vector(); + + return data; } -bool CDFeatureGatingTable::FeatureUnlocked(const std::string& feature) const -{ - for (const auto& entry : entries) - { - if (entry.featureName == feature) - { - return true; - } - } - - return false; +bool CDFeatureGatingTable::FeatureUnlocked(const std::string& feature) const { + for (const auto& entry : entries) { + if (entry.featureName == feature) { + return true; + } + } + + return false; } //! Gets all the entries in the table std::vector CDFeatureGatingTable::GetEntries(void) const { - return this->entries; + return this->entries; } diff --git a/dDatabase/Tables/CDFeatureGatingTable.h b/dDatabase/Tables/CDFeatureGatingTable.h index 11c25e67..54e6d21b 100644 --- a/dDatabase/Tables/CDFeatureGatingTable.h +++ b/dDatabase/Tables/CDFeatureGatingTable.h @@ -7,46 +7,46 @@ \file CDFeatureGatingTable.hpp */ -//! ItemComponent Struct + //! ItemComponent Struct struct CDFeatureGating { - std::string featureName; - int32_t major; - int32_t current; - int32_t minor; - std::string description; + std::string featureName; + int32_t major; + int32_t current; + int32_t minor; + std::string description; }; //! ItemComponent table class CDFeatureGatingTable : public CDTable { private: - std::vector entries; - -public: - - //! Constructor - CDFeatureGatingTable(void); - - //! Destructor - ~CDFeatureGatingTable(void); - - //! Returns the table's name - /*! - \return The table name - */ - std::string GetName(void) const override; - - //! Queries the table with a custom "where" clause - /*! - \param predicate The predicate - */ - std::vector Query(std::function predicate); + std::vector entries; + +public: + + //! Constructor + CDFeatureGatingTable(void); + + //! Destructor + ~CDFeatureGatingTable(void); + + //! Returns the table's name + /*! + \return The table name + */ + std::string GetName(void) const override; + + //! Queries the table with a custom "where" clause + /*! + \param predicate The predicate + */ + std::vector Query(std::function predicate); + + bool FeatureUnlocked(const std::string& feature) const; + + //! Gets all the entries in the table + /*! + \return The entries + */ + std::vector GetEntries(void) const; - bool FeatureUnlocked(const std::string& feature) const; - - //! Gets all the entries in the table - /*! - \return The entries - */ - std::vector GetEntries(void) const; - }; diff --git a/dDatabase/Tables/CDInventoryComponentTable.cpp b/dDatabase/Tables/CDInventoryComponentTable.cpp index b0849a45..65f09c9b 100644 --- a/dDatabase/Tables/CDInventoryComponentTable.cpp +++ b/dDatabase/Tables/CDInventoryComponentTable.cpp @@ -2,56 +2,56 @@ //! Constructor CDInventoryComponentTable::CDInventoryComponentTable(void) { - - // First, get the size of the table - unsigned int size = 0; - auto tableSize = CDClientDatabase::ExecuteQuery("SELECT COUNT(*) FROM InventoryComponent"); - while (!tableSize.eof()) { - size = tableSize.getIntField(0, 0); - - tableSize.nextRow(); - } - + + // First, get the size of the table + unsigned int size = 0; + auto tableSize = CDClientDatabase::ExecuteQuery("SELECT COUNT(*) FROM InventoryComponent"); + while (!tableSize.eof()) { + size = tableSize.getIntField(0, 0); + + tableSize.nextRow(); + } + tableSize.finalize(); - - // Reserve the size - this->entries.reserve(size); - - // Now get the data - auto tableData = CDClientDatabase::ExecuteQuery("SELECT * FROM InventoryComponent"); - while (!tableData.eof()) { - CDInventoryComponent entry; - entry.id = tableData.getIntField(0, -1); - entry.itemid = tableData.getIntField(1, -1); - entry.count = tableData.getIntField(2, -1); - entry.equip = tableData.getIntField(3, -1) == 1 ? true : false; - - this->entries.push_back(entry); - tableData.nextRow(); - } + + // Reserve the size + this->entries.reserve(size); + + // Now get the data + auto tableData = CDClientDatabase::ExecuteQuery("SELECT * FROM InventoryComponent"); + while (!tableData.eof()) { + CDInventoryComponent entry; + entry.id = tableData.getIntField(0, -1); + entry.itemid = tableData.getIntField(1, -1); + entry.count = tableData.getIntField(2, -1); + entry.equip = tableData.getIntField(3, -1) == 1 ? true : false; + + this->entries.push_back(entry); + tableData.nextRow(); + } tableData.finalize(); } //! Destructor -CDInventoryComponentTable::~CDInventoryComponentTable(void) { } +CDInventoryComponentTable::~CDInventoryComponentTable(void) {} //! Returns the table's name std::string CDInventoryComponentTable::GetName(void) const { - return "InventoryComponent"; + return "InventoryComponent"; } //! Queries the table with a custom "where" clause std::vector CDInventoryComponentTable::Query(std::function predicate) { - - std::vector data = cpplinq::from(this->entries) - >> cpplinq::where(predicate) - >> cpplinq::to_vector(); - - return data; + + std::vector data = cpplinq::from(this->entries) + >> cpplinq::where(predicate) + >> cpplinq::to_vector(); + + return data; } //! Gets all the entries in the table std::vector CDInventoryComponentTable::GetEntries(void) const { - return this->entries; + return this->entries; } diff --git a/dDatabase/Tables/CDInventoryComponentTable.h b/dDatabase/Tables/CDInventoryComponentTable.h index 3bce41f9..c6117907 100644 --- a/dDatabase/Tables/CDInventoryComponentTable.h +++ b/dDatabase/Tables/CDInventoryComponentTable.h @@ -8,43 +8,43 @@ \brief Contains data for the InventoryComponent table */ -//! ItemComponent Struct + //! ItemComponent Struct struct CDInventoryComponent { - unsigned int id; //!< The component ID for this object - unsigned int itemid; //!< The LOT of the object - unsigned int count; //!< The count of the items the object has - bool equip; //!< Whether or not to equip the item + unsigned int id; //!< The component ID for this object + unsigned int itemid; //!< The LOT of the object + unsigned int count; //!< The count of the items the object has + bool equip; //!< Whether or not to equip the item }; //! ItemComponent table class CDInventoryComponentTable : public CDTable { private: - std::vector entries; - + std::vector entries; + public: - - //! Constructor - CDInventoryComponentTable(void); - - //! Destructor - ~CDInventoryComponentTable(void); - - //! Returns the table's name - /*! - \return The table name - */ - std::string GetName(void) const override; - - //! Queries the table with a custom "where" clause - /*! - \param predicate The predicate - */ - std::vector Query(std::function predicate); - - //! Gets all the entries in the table - /*! - \return The entries - */ - std::vector GetEntries(void) const; - + + //! Constructor + CDInventoryComponentTable(void); + + //! Destructor + ~CDInventoryComponentTable(void); + + //! Returns the table's name + /*! + \return The table name + */ + std::string GetName(void) const override; + + //! Queries the table with a custom "where" clause + /*! + \param predicate The predicate + */ + std::vector Query(std::function predicate); + + //! Gets all the entries in the table + /*! + \return The entries + */ + std::vector GetEntries(void) const; + }; diff --git a/dDatabase/Tables/CDItemComponentTable.cpp b/dDatabase/Tables/CDItemComponentTable.cpp index 698f72a4..703497ff 100644 --- a/dDatabase/Tables/CDItemComponentTable.cpp +++ b/dDatabase/Tables/CDItemComponentTable.cpp @@ -5,84 +5,84 @@ CDItemComponent CDItemComponentTable::Default = {}; //! Constructor CDItemComponentTable::CDItemComponentTable(void) { - Default = CDItemComponent(); - + Default = CDItemComponent(); + #ifdef CDCLIENT_CACHE_ALL - // First, get the size of the table - unsigned int size = 0; - auto tableSize = CDClientDatabase::ExecuteQuery("SELECT COUNT(*) FROM ItemComponent"); - while (!tableSize.eof()) { - size = tableSize.getIntField(0, 0); - - tableSize.nextRow(); - } - + // First, get the size of the table + unsigned int size = 0; + auto tableSize = CDClientDatabase::ExecuteQuery("SELECT COUNT(*) FROM ItemComponent"); + while (!tableSize.eof()) { + size = tableSize.getIntField(0, 0); + + tableSize.nextRow(); + } + tableSize.finalize(); - - // Now get the data - auto tableData = CDClientDatabase::ExecuteQuery("SELECT * FROM ItemComponent"); - while (!tableData.eof()) { - CDItemComponent entry; - entry.id = tableData.getIntField(0, -1); - entry.equipLocation = tableData.getStringField(1, ""); - entry.baseValue = tableData.getIntField(2, -1); - entry.isKitPiece = tableData.getIntField(3, -1) == 1 ? true : false; - entry.rarity = tableData.getIntField(4, 0); - entry.itemType = tableData.getIntField(5, -1); - entry.itemInfo = tableData.getInt64Field(6, -1); - entry.inLootTable = tableData.getIntField(7, -1) == 1 ? true : false; - entry.inVendor = tableData.getIntField(8, -1) == 1 ? true : false; - entry.isUnique = tableData.getIntField(9, -1) == 1 ? true : false; - entry.isBOP = tableData.getIntField(10, -1) == 1 ? true : false; - entry.isBOE = tableData.getIntField(11, -1) == 1 ? true : false; - entry.reqFlagID = tableData.getIntField(12, -1); - entry.reqSpecialtyID = tableData.getIntField(13, -1); - entry.reqSpecRank = tableData.getIntField(14, -1); - entry.reqAchievementID = tableData.getIntField(15, -1); - entry.stackSize = tableData.getIntField(16, -1); - entry.color1 = tableData.getIntField(17, -1); - entry.decal = tableData.getIntField(18, -1); - entry.offsetGroupID = tableData.getIntField(19, -1); - entry.buildTypes = tableData.getIntField(20, -1); - entry.reqPrecondition = tableData.getStringField(21, ""); - entry.animationFlag = tableData.getIntField(22, -1); - entry.equipEffects = tableData.getIntField(23, -1); - entry.readyForQA = tableData.getIntField(24, -1) == 1 ? true : false; - entry.itemRating = tableData.getIntField(25, -1); - entry.isTwoHanded = tableData.getIntField(26, -1) == 1 ? true : false; - entry.minNumRequired = tableData.getIntField(27, -1); - entry.delResIndex = tableData.getIntField(28, -1); - entry.currencyLOT = tableData.getIntField(29, -1); - entry.altCurrencyCost = tableData.getIntField(30, -1); - entry.subItems = tableData.getStringField(31, ""); - entry.audioEventUse = tableData.getStringField(32, ""); - entry.noEquipAnimation = tableData.getIntField(33, -1) == 1 ? true : false; - entry.commendationLOT = tableData.getIntField(34, -1); - entry.commendationCost = tableData.getIntField(35, -1); - entry.audioEquipMetaEventSet = tableData.getStringField(36, ""); - entry.currencyCosts = tableData.getStringField(37, ""); - entry.ingredientInfo = tableData.getStringField(38, ""); - entry.locStatus = tableData.getIntField(39, -1); - entry.forgeType = tableData.getIntField(40, -1); - entry.SellMultiplier = tableData.getFloatField(41, -1.0f); - + + // Now get the data + auto tableData = CDClientDatabase::ExecuteQuery("SELECT * FROM ItemComponent"); + while (!tableData.eof()) { + CDItemComponent entry; + entry.id = tableData.getIntField(0, -1); + entry.equipLocation = tableData.getStringField(1, ""); + entry.baseValue = tableData.getIntField(2, -1); + entry.isKitPiece = tableData.getIntField(3, -1) == 1 ? true : false; + entry.rarity = tableData.getIntField(4, 0); + entry.itemType = tableData.getIntField(5, -1); + entry.itemInfo = tableData.getInt64Field(6, -1); + entry.inLootTable = tableData.getIntField(7, -1) == 1 ? true : false; + entry.inVendor = tableData.getIntField(8, -1) == 1 ? true : false; + entry.isUnique = tableData.getIntField(9, -1) == 1 ? true : false; + entry.isBOP = tableData.getIntField(10, -1) == 1 ? true : false; + entry.isBOE = tableData.getIntField(11, -1) == 1 ? true : false; + entry.reqFlagID = tableData.getIntField(12, -1); + entry.reqSpecialtyID = tableData.getIntField(13, -1); + entry.reqSpecRank = tableData.getIntField(14, -1); + entry.reqAchievementID = tableData.getIntField(15, -1); + entry.stackSize = tableData.getIntField(16, -1); + entry.color1 = tableData.getIntField(17, -1); + entry.decal = tableData.getIntField(18, -1); + entry.offsetGroupID = tableData.getIntField(19, -1); + entry.buildTypes = tableData.getIntField(20, -1); + entry.reqPrecondition = tableData.getStringField(21, ""); + entry.animationFlag = tableData.getIntField(22, -1); + entry.equipEffects = tableData.getIntField(23, -1); + entry.readyForQA = tableData.getIntField(24, -1) == 1 ? true : false; + entry.itemRating = tableData.getIntField(25, -1); + entry.isTwoHanded = tableData.getIntField(26, -1) == 1 ? true : false; + entry.minNumRequired = tableData.getIntField(27, -1); + entry.delResIndex = tableData.getIntField(28, -1); + entry.currencyLOT = tableData.getIntField(29, -1); + entry.altCurrencyCost = tableData.getIntField(30, -1); + entry.subItems = tableData.getStringField(31, ""); + entry.audioEventUse = tableData.getStringField(32, ""); + entry.noEquipAnimation = tableData.getIntField(33, -1) == 1 ? true : false; + entry.commendationLOT = tableData.getIntField(34, -1); + entry.commendationCost = tableData.getIntField(35, -1); + entry.audioEquipMetaEventSet = tableData.getStringField(36, ""); + entry.currencyCosts = tableData.getStringField(37, ""); + entry.ingredientInfo = tableData.getStringField(38, ""); + entry.locStatus = tableData.getIntField(39, -1); + entry.forgeType = tableData.getIntField(40, -1); + entry.SellMultiplier = tableData.getFloatField(41, -1.0f); + this->entries.insert(std::make_pair(entry.id, entry)); tableData.nextRow(); - } + } tableData.finalize(); #endif } //! Destructor -CDItemComponentTable::~CDItemComponentTable(void) { } +CDItemComponentTable::~CDItemComponentTable(void) {} //! Returns the table's name std::string CDItemComponentTable::GetName(void) const { - return "ItemComponent"; + return "ItemComponent"; } -const CDItemComponent & CDItemComponentTable::GetItemComponentByID(unsigned int skillID) { +const CDItemComponent& CDItemComponentTable::GetItemComponentByID(unsigned int skillID) { const auto& it = this->entries.find(skillID); if (it != this->entries.end()) { return it->second; @@ -94,59 +94,59 @@ const CDItemComponent & CDItemComponentTable::GetItemComponentByID(unsigned int query << "SELECT * FROM ItemComponent WHERE id = " << std::to_string(skillID); auto tableData = CDClientDatabase::ExecuteQuery(query.str()); - if (tableData.eof()) { + if (tableData.eof()) { entries.insert(std::make_pair(skillID, Default)); return Default; } - while (!tableData.eof()) { - CDItemComponent entry; - entry.id = tableData.getIntField(0, -1); - entry.equipLocation = tableData.getStringField(1, ""); - entry.baseValue = tableData.getIntField(2, -1); - entry.isKitPiece = tableData.getIntField(3, -1) == 1 ? true : false; - entry.rarity = tableData.getIntField(4, 0); - entry.itemType = tableData.getIntField(5, -1); - entry.itemInfo = tableData.getInt64Field(6, -1); - entry.inLootTable = tableData.getIntField(7, -1) == 1 ? true : false; - entry.inVendor = tableData.getIntField(8, -1) == 1 ? true : false; - entry.isUnique = tableData.getIntField(9, -1) == 1 ? true : false; - entry.isBOP = tableData.getIntField(10, -1) == 1 ? true : false; - entry.isBOE = tableData.getIntField(11, -1) == 1 ? true : false; - entry.reqFlagID = tableData.getIntField(12, -1); - entry.reqSpecialtyID = tableData.getIntField(13, -1); - entry.reqSpecRank = tableData.getIntField(14, -1); - entry.reqAchievementID = tableData.getIntField(15, -1); - entry.stackSize = tableData.getIntField(16, -1); - entry.color1 = tableData.getIntField(17, -1); - entry.decal = tableData.getIntField(18, -1); - entry.offsetGroupID = tableData.getIntField(19, -1); - entry.buildTypes = tableData.getIntField(20, -1); - entry.reqPrecondition = tableData.getStringField(21, ""); - entry.animationFlag = tableData.getIntField(22, -1); - entry.equipEffects = tableData.getIntField(23, -1); - entry.readyForQA = tableData.getIntField(24, -1) == 1 ? true : false; - entry.itemRating = tableData.getIntField(25, -1); - entry.isTwoHanded = tableData.getIntField(26, -1) == 1 ? true : false; - entry.minNumRequired = tableData.getIntField(27, -1); - entry.delResIndex = tableData.getIntField(28, -1); - entry.currencyLOT = tableData.getIntField(29, -1); - entry.altCurrencyCost = tableData.getIntField(30, -1); - entry.subItems = tableData.getStringField(31, ""); - UNUSED(entry.audioEventUse = tableData.getStringField(32, "")); - entry.noEquipAnimation = tableData.getIntField(33, -1) == 1 ? true : false; - entry.commendationLOT = tableData.getIntField(34, -1); - entry.commendationCost = tableData.getIntField(35, -1); - UNUSED(entry.audioEquipMetaEventSet = tableData.getStringField(36, "")); - entry.currencyCosts = tableData.getStringField(37, ""); - UNUSED(entry.ingredientInfo = tableData.getStringField(38, "")); - entry.locStatus = tableData.getIntField(39, -1); - entry.forgeType = tableData.getIntField(40, -1); - entry.SellMultiplier = tableData.getFloatField(41, -1.0f); - + while (!tableData.eof()) { + CDItemComponent entry; + entry.id = tableData.getIntField(0, -1); + entry.equipLocation = tableData.getStringField(1, ""); + entry.baseValue = tableData.getIntField(2, -1); + entry.isKitPiece = tableData.getIntField(3, -1) == 1 ? true : false; + entry.rarity = tableData.getIntField(4, 0); + entry.itemType = tableData.getIntField(5, -1); + entry.itemInfo = tableData.getInt64Field(6, -1); + entry.inLootTable = tableData.getIntField(7, -1) == 1 ? true : false; + entry.inVendor = tableData.getIntField(8, -1) == 1 ? true : false; + entry.isUnique = tableData.getIntField(9, -1) == 1 ? true : false; + entry.isBOP = tableData.getIntField(10, -1) == 1 ? true : false; + entry.isBOE = tableData.getIntField(11, -1) == 1 ? true : false; + entry.reqFlagID = tableData.getIntField(12, -1); + entry.reqSpecialtyID = tableData.getIntField(13, -1); + entry.reqSpecRank = tableData.getIntField(14, -1); + entry.reqAchievementID = tableData.getIntField(15, -1); + entry.stackSize = tableData.getIntField(16, -1); + entry.color1 = tableData.getIntField(17, -1); + entry.decal = tableData.getIntField(18, -1); + entry.offsetGroupID = tableData.getIntField(19, -1); + entry.buildTypes = tableData.getIntField(20, -1); + entry.reqPrecondition = tableData.getStringField(21, ""); + entry.animationFlag = tableData.getIntField(22, -1); + entry.equipEffects = tableData.getIntField(23, -1); + entry.readyForQA = tableData.getIntField(24, -1) == 1 ? true : false; + entry.itemRating = tableData.getIntField(25, -1); + entry.isTwoHanded = tableData.getIntField(26, -1) == 1 ? true : false; + entry.minNumRequired = tableData.getIntField(27, -1); + entry.delResIndex = tableData.getIntField(28, -1); + entry.currencyLOT = tableData.getIntField(29, -1); + entry.altCurrencyCost = tableData.getIntField(30, -1); + entry.subItems = tableData.getStringField(31, ""); + UNUSED(entry.audioEventUse = tableData.getStringField(32, "")); + entry.noEquipAnimation = tableData.getIntField(33, -1) == 1 ? true : false; + entry.commendationLOT = tableData.getIntField(34, -1); + entry.commendationCost = tableData.getIntField(35, -1); + UNUSED(entry.audioEquipMetaEventSet = tableData.getStringField(36, "")); + entry.currencyCosts = tableData.getStringField(37, ""); + UNUSED(entry.ingredientInfo = tableData.getStringField(38, "")); + entry.locStatus = tableData.getIntField(39, -1); + entry.forgeType = tableData.getIntField(40, -1); + entry.SellMultiplier = tableData.getFloatField(41, -1.0f); + this->entries.insert(std::make_pair(entry.id, entry)); tableData.nextRow(); - } + } const auto& it2 = this->entries.find(skillID); if (it2 != this->entries.end()) { @@ -154,26 +154,26 @@ const CDItemComponent & CDItemComponentTable::GetItemComponentByID(unsigned int } #endif - return Default; + return Default; } std::map CDItemComponentTable::ParseCraftingCurrencies(const CDItemComponent& itemComponent) { - std::map currencies = {}; + std::map currencies = {}; - if (!itemComponent.currencyCosts.empty()) { - auto currencySplit = GeneralUtils::SplitString(itemComponent.currencyCosts, ','); - for (const auto& currencyAmount : currencySplit) { - auto amountSplit = GeneralUtils::SplitString(currencyAmount, ':'); + if (!itemComponent.currencyCosts.empty()) { + auto currencySplit = GeneralUtils::SplitString(itemComponent.currencyCosts, ','); + for (const auto& currencyAmount : currencySplit) { + auto amountSplit = GeneralUtils::SplitString(currencyAmount, ':'); - // Checking for 2 here, not sure what to do when there's more stuff than expected - if (amountSplit.size() == 2) { - currencies.insert({ - std::stoull(amountSplit[0]), - std::stoi(amountSplit[1]) - }); - } - } - } + // Checking for 2 here, not sure what to do when there's more stuff than expected + if (amountSplit.size() == 2) { + currencies.insert({ + std::stoull(amountSplit[0]), + std::stoi(amountSplit[1]) + }); + } + } + } - return currencies; + return currencies; } diff --git a/dDatabase/Tables/CDItemComponentTable.h b/dDatabase/Tables/CDItemComponentTable.h index 83b66f91..b3a2a5f4 100644 --- a/dDatabase/Tables/CDItemComponentTable.h +++ b/dDatabase/Tables/CDItemComponentTable.h @@ -9,75 +9,75 @@ \brief Contains data for the ItemComponent table */ -//! ItemComponent Struct + //! ItemComponent Struct struct CDItemComponent { - unsigned int id; //!< The Component ID - std::string equipLocation; //!< The equip location - unsigned int baseValue; //!< The monetary base value of the item - bool isKitPiece; //!< Whether or not the item belongs to a kit - unsigned int rarity; //!< The rarity of the item - unsigned int itemType; //!< The item type - int64_t itemInfo; //!< The item info - bool inLootTable; //!< Whether or not the item is in a loot table - bool inVendor; //!< Whether or not the item is in a vendor inventory - bool isUnique; //!< ??? - bool isBOP; //!< ??? - bool isBOE; //!< ??? - unsigned int reqFlagID; //!< User must have completed this flag to get the item - unsigned int reqSpecialtyID; //!< ??? - unsigned int reqSpecRank; //!< ??? - unsigned int reqAchievementID; //!< The required achievement must be completed - unsigned int stackSize; //!< The stack size of the item - unsigned int color1; //!< Something to do with item color... - unsigned int decal; //!< The decal of the item - unsigned int offsetGroupID; //!< Something to do with group IDs - unsigned int buildTypes; //!< Something to do with building - std::string reqPrecondition; //!< The required precondition - unsigned int animationFlag; //!< The Animation Flag - unsigned int equipEffects; //!< The effect played when the item is equipped - bool readyForQA; //!< ??? - unsigned int itemRating; //!< ??? - bool isTwoHanded; //!< Whether or not the item is double handed - unsigned int minNumRequired; //!< Maybe the minimum number required for a mission, or to own this object? - unsigned int delResIndex; //!< ??? - unsigned int currencyLOT; //!< ??? - unsigned int altCurrencyCost; //!< ??? - std::string subItems; //!< A comma seperate string of sub items (maybe for multi-itemed things like faction test gear set) - UNUSED(std::string audioEventUse); //!< ??? - bool noEquipAnimation; //!< Whether or not there is an equip animation - unsigned int commendationLOT; //!< The commendation LOT - unsigned int commendationCost; //!< The commendation cost - UNUSED(std::string audioEquipMetaEventSet); //!< ??? - std::string currencyCosts; //!< Used for crafting - UNUSED(std::string ingredientInfo); //!< Unused - unsigned int locStatus; //!< ??? - unsigned int forgeType; //!< Forge Type - float SellMultiplier; //!< Something to do with early vendors perhaps (but replaced) + unsigned int id; //!< The Component ID + std::string equipLocation; //!< The equip location + unsigned int baseValue; //!< The monetary base value of the item + bool isKitPiece; //!< Whether or not the item belongs to a kit + unsigned int rarity; //!< The rarity of the item + unsigned int itemType; //!< The item type + int64_t itemInfo; //!< The item info + bool inLootTable; //!< Whether or not the item is in a loot table + bool inVendor; //!< Whether or not the item is in a vendor inventory + bool isUnique; //!< ??? + bool isBOP; //!< ??? + bool isBOE; //!< ??? + unsigned int reqFlagID; //!< User must have completed this flag to get the item + unsigned int reqSpecialtyID; //!< ??? + unsigned int reqSpecRank; //!< ??? + unsigned int reqAchievementID; //!< The required achievement must be completed + unsigned int stackSize; //!< The stack size of the item + unsigned int color1; //!< Something to do with item color... + unsigned int decal; //!< The decal of the item + unsigned int offsetGroupID; //!< Something to do with group IDs + unsigned int buildTypes; //!< Something to do with building + std::string reqPrecondition; //!< The required precondition + unsigned int animationFlag; //!< The Animation Flag + unsigned int equipEffects; //!< The effect played when the item is equipped + bool readyForQA; //!< ??? + unsigned int itemRating; //!< ??? + bool isTwoHanded; //!< Whether or not the item is double handed + unsigned int minNumRequired; //!< Maybe the minimum number required for a mission, or to own this object? + unsigned int delResIndex; //!< ??? + unsigned int currencyLOT; //!< ??? + unsigned int altCurrencyCost; //!< ??? + std::string subItems; //!< A comma seperate string of sub items (maybe for multi-itemed things like faction test gear set) + UNUSED(std::string audioEventUse); //!< ??? + bool noEquipAnimation; //!< Whether or not there is an equip animation + unsigned int commendationLOT; //!< The commendation LOT + unsigned int commendationCost; //!< The commendation cost + UNUSED(std::string audioEquipMetaEventSet); //!< ??? + std::string currencyCosts; //!< Used for crafting + UNUSED(std::string ingredientInfo); //!< Unused + unsigned int locStatus; //!< ??? + unsigned int forgeType; //!< Forge Type + float SellMultiplier; //!< Something to do with early vendors perhaps (but replaced) }; //! ItemComponent table class CDItemComponentTable : public CDTable { private: - std::map entries; - -public: - - //! Constructor - CDItemComponentTable(void); - - //! Destructor - ~CDItemComponentTable(void); - - //! Returns the table's name - /*! - \return The table name - */ - std::string GetName(void) const override; + std::map entries; + +public: + + //! Constructor + CDItemComponentTable(void); + + //! Destructor + ~CDItemComponentTable(void); + + //! Returns the table's name + /*! + \return The table name + */ + std::string GetName(void) const override; + + static std::map ParseCraftingCurrencies(const CDItemComponent& itemComponent); - static std::map ParseCraftingCurrencies(const CDItemComponent& itemComponent); - //! Gets an entry by ID const CDItemComponent& GetItemComponentByID(unsigned int skillID); - - static CDItemComponent Default; + + static CDItemComponent Default; }; diff --git a/dDatabase/Tables/CDItemSetSkillsTable.cpp b/dDatabase/Tables/CDItemSetSkillsTable.cpp index b20fd1cb..e94cf527 100644 --- a/dDatabase/Tables/CDItemSetSkillsTable.cpp +++ b/dDatabase/Tables/CDItemSetSkillsTable.cpp @@ -2,63 +2,62 @@ //! Constructor CDItemSetSkillsTable::CDItemSetSkillsTable(void) { - - // First, get the size of the table - unsigned int size = 0; - auto tableSize = CDClientDatabase::ExecuteQuery("SELECT COUNT(*) FROM ItemSetSkills"); - while (!tableSize.eof()) { - size = tableSize.getIntField(0, 0); - - tableSize.nextRow(); - } - + + // First, get the size of the table + unsigned int size = 0; + auto tableSize = CDClientDatabase::ExecuteQuery("SELECT COUNT(*) FROM ItemSetSkills"); + while (!tableSize.eof()) { + size = tableSize.getIntField(0, 0); + + tableSize.nextRow(); + } + tableSize.finalize(); - - // Reserve the size - this->entries.reserve(size); - - // Now get the data - auto tableData = CDClientDatabase::ExecuteQuery("SELECT * FROM ItemSetSkills"); - while (!tableData.eof()) { - CDItemSetSkills entry; - entry.SkillSetID = tableData.getIntField(0, -1); - entry.SkillID = tableData.getIntField(1, -1); - entry.SkillCastType = tableData.getIntField(2, -1); - - this->entries.push_back(entry); - tableData.nextRow(); - } + + // Reserve the size + this->entries.reserve(size); + + // Now get the data + auto tableData = CDClientDatabase::ExecuteQuery("SELECT * FROM ItemSetSkills"); + while (!tableData.eof()) { + CDItemSetSkills entry; + entry.SkillSetID = tableData.getIntField(0, -1); + entry.SkillID = tableData.getIntField(1, -1); + entry.SkillCastType = tableData.getIntField(2, -1); + + this->entries.push_back(entry); + tableData.nextRow(); + } tableData.finalize(); } //! Destructor -CDItemSetSkillsTable::~CDItemSetSkillsTable(void) { } +CDItemSetSkillsTable::~CDItemSetSkillsTable(void) {} //! Returns the table's name std::string CDItemSetSkillsTable::GetName(void) const { - return "ItemSetSkills"; + return "ItemSetSkills"; } //! Queries the table with a custom "where" clause std::vector CDItemSetSkillsTable::Query(std::function predicate) { - - std::vector data = cpplinq::from(this->entries) - >> cpplinq::where(predicate) - >> cpplinq::to_vector(); - - return data; + + std::vector data = cpplinq::from(this->entries) + >> cpplinq::where(predicate) + >> cpplinq::to_vector(); + + return data; } //! Gets all the entries in the table std::vector CDItemSetSkillsTable::GetEntries(void) const { - return this->entries; + return this->entries; } -std::vector CDItemSetSkillsTable::GetBySkillID(unsigned int SkillSetID) -{ +std::vector CDItemSetSkillsTable::GetBySkillID(unsigned int SkillSetID) { std::vector toReturn; - + for (CDItemSetSkills entry : this->entries) { if (entry.SkillSetID == SkillSetID) toReturn.push_back(entry); if (entry.SkillSetID > SkillSetID) return toReturn; //stop seeking in the db if it's not needed. diff --git a/dDatabase/Tables/CDItemSetSkillsTable.h b/dDatabase/Tables/CDItemSetSkillsTable.h index 78ce83ab..bf05eea9 100644 --- a/dDatabase/Tables/CDItemSetSkillsTable.h +++ b/dDatabase/Tables/CDItemSetSkillsTable.h @@ -8,45 +8,45 @@ \brief Contains data for the ItemSetSkills table */ -//! ZoneTable Struct + //! ZoneTable Struct struct CDItemSetSkills { - unsigned int SkillSetID; //!< The skill set ID - unsigned int SkillID; //!< The skill ID - unsigned int SkillCastType; //!< The skill cast type + unsigned int SkillSetID; //!< The skill set ID + unsigned int SkillID; //!< The skill ID + unsigned int SkillCastType; //!< The skill cast type }; //! ItemSets table class CDItemSetSkillsTable : public CDTable { private: - std::vector entries; - + std::vector entries; + public: - - //! Constructor - CDItemSetSkillsTable(void); - - //! Destructor - ~CDItemSetSkillsTable(void); - - //! Returns the table's name - /*! - \return The table name - */ - std::string GetName(void) const override; - - //! Queries the table with a custom "where" clause - /*! - \param predicate The predicate - */ - std::vector Query(std::function predicate); - - //! Gets all the entries in the table - /*! - \return The entries - */ - std::vector GetEntries(void) const; + + //! Constructor + CDItemSetSkillsTable(void); + + //! Destructor + ~CDItemSetSkillsTable(void); + + //! Returns the table's name + /*! + \return The table name + */ + std::string GetName(void) const override; + + //! Queries the table with a custom "where" clause + /*! + \param predicate The predicate + */ + std::vector Query(std::function predicate); + + //! Gets all the entries in the table + /*! + \return The entries + */ + std::vector GetEntries(void) const; std::vector GetBySkillID(unsigned int SkillSetID); - + }; diff --git a/dDatabase/Tables/CDItemSetsTable.cpp b/dDatabase/Tables/CDItemSetsTable.cpp index ad78ee3b..606e0cf9 100644 --- a/dDatabase/Tables/CDItemSetsTable.cpp +++ b/dDatabase/Tables/CDItemSetsTable.cpp @@ -2,67 +2,67 @@ //! Constructor CDItemSetsTable::CDItemSetsTable(void) { - - // First, get the size of the table - unsigned int size = 0; - auto tableSize = CDClientDatabase::ExecuteQuery("SELECT COUNT(*) FROM ItemSets"); - while (!tableSize.eof()) { - size = tableSize.getIntField(0, 0); - - tableSize.nextRow(); - } - + + // First, get the size of the table + unsigned int size = 0; + auto tableSize = CDClientDatabase::ExecuteQuery("SELECT COUNT(*) FROM ItemSets"); + while (!tableSize.eof()) { + size = tableSize.getIntField(0, 0); + + tableSize.nextRow(); + } + tableSize.finalize(); - - // Reserve the size - this->entries.reserve(size); - - // Now get the data - auto tableData = CDClientDatabase::ExecuteQuery("SELECT * FROM ItemSets"); - while (!tableData.eof()) { - CDItemSets entry; - entry.setID = tableData.getIntField(0, -1); - entry.locStatus = tableData.getIntField(1, -1); - entry.itemIDs = tableData.getStringField(2, ""); - entry.kitType = tableData.getIntField(3, -1); - entry.kitRank = tableData.getIntField(4, -1); - entry.kitImage = tableData.getIntField(5, -1); - entry.skillSetWith2 = tableData.getIntField(6, -1); - entry.skillSetWith3 = tableData.getIntField(7, -1); - entry.skillSetWith4 = tableData.getIntField(8, -1); - entry.skillSetWith5 = tableData.getIntField(9, -1); - entry.skillSetWith6 = tableData.getIntField(10, -1); - entry.localize = tableData.getIntField(11, -1) == 1 ? true : false; - entry.gate_version = tableData.getStringField(12, ""); - entry.kitID = tableData.getIntField(13, -1); - entry.priority = tableData.getFloatField(14, -1.0f); - - this->entries.push_back(entry); - tableData.nextRow(); - } + + // Reserve the size + this->entries.reserve(size); + + // Now get the data + auto tableData = CDClientDatabase::ExecuteQuery("SELECT * FROM ItemSets"); + while (!tableData.eof()) { + CDItemSets entry; + entry.setID = tableData.getIntField(0, -1); + entry.locStatus = tableData.getIntField(1, -1); + entry.itemIDs = tableData.getStringField(2, ""); + entry.kitType = tableData.getIntField(3, -1); + entry.kitRank = tableData.getIntField(4, -1); + entry.kitImage = tableData.getIntField(5, -1); + entry.skillSetWith2 = tableData.getIntField(6, -1); + entry.skillSetWith3 = tableData.getIntField(7, -1); + entry.skillSetWith4 = tableData.getIntField(8, -1); + entry.skillSetWith5 = tableData.getIntField(9, -1); + entry.skillSetWith6 = tableData.getIntField(10, -1); + entry.localize = tableData.getIntField(11, -1) == 1 ? true : false; + entry.gate_version = tableData.getStringField(12, ""); + entry.kitID = tableData.getIntField(13, -1); + entry.priority = tableData.getFloatField(14, -1.0f); + + this->entries.push_back(entry); + tableData.nextRow(); + } tableData.finalize(); } //! Destructor -CDItemSetsTable::~CDItemSetsTable(void) { } +CDItemSetsTable::~CDItemSetsTable(void) {} //! Returns the table's name std::string CDItemSetsTable::GetName(void) const { - return "ItemSets"; + return "ItemSets"; } //! Queries the table with a custom "where" clause std::vector CDItemSetsTable::Query(std::function predicate) { - - std::vector data = cpplinq::from(this->entries) - >> cpplinq::where(predicate) - >> cpplinq::to_vector(); - - return data; + + std::vector data = cpplinq::from(this->entries) + >> cpplinq::where(predicate) + >> cpplinq::to_vector(); + + return data; } //! Gets all the entries in the table std::vector CDItemSetsTable::GetEntries(void) const { - return this->entries; + return this->entries; } diff --git a/dDatabase/Tables/CDItemSetsTable.h b/dDatabase/Tables/CDItemSetsTable.h index 9e8b85e8..ef12c7b4 100644 --- a/dDatabase/Tables/CDItemSetsTable.h +++ b/dDatabase/Tables/CDItemSetsTable.h @@ -8,55 +8,55 @@ \brief Contains data for the ItemSets table */ -//! ZoneTable Struct + //! ZoneTable Struct struct CDItemSets { - unsigned int setID; //!< The item set ID - unsigned int locStatus; //!< The loc status - std::string itemIDs; //!< THe item IDs - unsigned int kitType; //!< The item kit type - unsigned int kitRank; //!< The item kit rank - unsigned int kitImage; //!< The item kit image - unsigned int skillSetWith2; //!< The skill set with 2 - unsigned int skillSetWith3; //!< The skill set with 3 - unsigned int skillSetWith4; //!< The skill set with 4 - unsigned int skillSetWith5; //!< The skill set with 5 - unsigned int skillSetWith6; //!< The skill set with 6 - bool localize; //!< Whether or localize - std::string gate_version; //!< The gate version - unsigned int kitID; //!< The kit ID - float priority; //!< The priority + unsigned int setID; //!< The item set ID + unsigned int locStatus; //!< The loc status + std::string itemIDs; //!< THe item IDs + unsigned int kitType; //!< The item kit type + unsigned int kitRank; //!< The item kit rank + unsigned int kitImage; //!< The item kit image + unsigned int skillSetWith2; //!< The skill set with 2 + unsigned int skillSetWith3; //!< The skill set with 3 + unsigned int skillSetWith4; //!< The skill set with 4 + unsigned int skillSetWith5; //!< The skill set with 5 + unsigned int skillSetWith6; //!< The skill set with 6 + bool localize; //!< Whether or localize + std::string gate_version; //!< The gate version + unsigned int kitID; //!< The kit ID + float priority; //!< The priority }; //! ItemSets table class CDItemSetsTable : public CDTable { private: - std::vector entries; - + std::vector entries; + public: - - //! Constructor - CDItemSetsTable(void); - - //! Destructor - ~CDItemSetsTable(void); - - //! Returns the table's name - /*! - \return The table name - */ - std::string GetName(void) const override; - - //! Queries the table with a custom "where" clause - /*! - \param predicate The predicate - */ - std::vector Query(std::function predicate); - - //! Gets all the entries in the table - /*! - \return The entries - */ - std::vector GetEntries(void) const; - + + //! Constructor + CDItemSetsTable(void); + + //! Destructor + ~CDItemSetsTable(void); + + //! Returns the table's name + /*! + \return The table name + */ + std::string GetName(void) const override; + + //! Queries the table with a custom "where" clause + /*! + \param predicate The predicate + */ + std::vector Query(std::function predicate); + + //! Gets all the entries in the table + /*! + \return The entries + */ + std::vector GetEntries(void) const; + }; diff --git a/dDatabase/Tables/CDLevelProgressionLookupTable.cpp b/dDatabase/Tables/CDLevelProgressionLookupTable.cpp index 0070e787..121c9f62 100644 --- a/dDatabase/Tables/CDLevelProgressionLookupTable.cpp +++ b/dDatabase/Tables/CDLevelProgressionLookupTable.cpp @@ -2,55 +2,55 @@ //! Constructor CDLevelProgressionLookupTable::CDLevelProgressionLookupTable(void) { - - // First, get the size of the table - unsigned int size = 0; - auto tableSize = CDClientDatabase::ExecuteQuery("SELECT COUNT(*) FROM LevelProgressionLookup"); - while (!tableSize.eof()) { - size = tableSize.getIntField(0, 0); - - tableSize.nextRow(); - } - + + // First, get the size of the table + unsigned int size = 0; + auto tableSize = CDClientDatabase::ExecuteQuery("SELECT COUNT(*) FROM LevelProgressionLookup"); + while (!tableSize.eof()) { + size = tableSize.getIntField(0, 0); + + tableSize.nextRow(); + } + tableSize.finalize(); - - // Reserve the size - this->entries.reserve(size); - - // Now get the data - auto tableData = CDClientDatabase::ExecuteQuery("SELECT * FROM LevelProgressionLookup"); - while (!tableData.eof()) { - CDLevelProgressionLookup entry; - entry.id = tableData.getIntField(0, -1); - entry.requiredUScore = tableData.getIntField(1, -1); - entry.BehaviorEffect = tableData.getStringField(2, ""); - - this->entries.push_back(entry); - tableData.nextRow(); - } + + // Reserve the size + this->entries.reserve(size); + + // Now get the data + auto tableData = CDClientDatabase::ExecuteQuery("SELECT * FROM LevelProgressionLookup"); + while (!tableData.eof()) { + CDLevelProgressionLookup entry; + entry.id = tableData.getIntField(0, -1); + entry.requiredUScore = tableData.getIntField(1, -1); + entry.BehaviorEffect = tableData.getStringField(2, ""); + + this->entries.push_back(entry); + tableData.nextRow(); + } tableData.finalize(); } //! Destructor -CDLevelProgressionLookupTable::~CDLevelProgressionLookupTable(void) { } +CDLevelProgressionLookupTable::~CDLevelProgressionLookupTable(void) {} //! Returns the table's name std::string CDLevelProgressionLookupTable::GetName(void) const { - return "LevelProgressionLookup"; + return "LevelProgressionLookup"; } //! Queries the table with a custom "where" clause std::vector CDLevelProgressionLookupTable::Query(std::function predicate) { - - std::vector data = cpplinq::from(this->entries) - >> cpplinq::where(predicate) - >> cpplinq::to_vector(); - - return data; + + std::vector data = cpplinq::from(this->entries) + >> cpplinq::where(predicate) + >> cpplinq::to_vector(); + + return data; } //! Gets all the entries in the table std::vector CDLevelProgressionLookupTable::GetEntries(void) const { - return this->entries; + return this->entries; } diff --git a/dDatabase/Tables/CDLevelProgressionLookupTable.h b/dDatabase/Tables/CDLevelProgressionLookupTable.h index 4174cdff..391c9b37 100644 --- a/dDatabase/Tables/CDLevelProgressionLookupTable.h +++ b/dDatabase/Tables/CDLevelProgressionLookupTable.h @@ -8,42 +8,42 @@ \brief Contains data for the LevelProgressionLookup table */ -//! LevelProgressionLookup Entry Struct + //! LevelProgressionLookup Entry Struct struct CDLevelProgressionLookup { - unsigned int id; //!< The Level ID - unsigned int requiredUScore; //!< The required LEGO Score - std::string BehaviorEffect; //!< The behavior effect attached to this + unsigned int id; //!< The Level ID + unsigned int requiredUScore; //!< The required LEGO Score + std::string BehaviorEffect; //!< The behavior effect attached to this }; //! LevelProgressionLookup table class CDLevelProgressionLookupTable : public CDTable { private: - std::vector entries; - + std::vector entries; + public: - - //! Constructor - CDLevelProgressionLookupTable(void); - - //! Destructor - ~CDLevelProgressionLookupTable(void); - - //! Returns the table's name - /*! - \return The table name - */ - std::string GetName(void) const override; - - //! Queries the table with a custom "where" clause - /*! - \param predicate The predicate - */ - std::vector Query(std::function predicate); - - //! Gets all the entries in the table - /*! - \return The entries - */ - std::vector GetEntries(void) const; - + + //! Constructor + CDLevelProgressionLookupTable(void); + + //! Destructor + ~CDLevelProgressionLookupTable(void); + + //! Returns the table's name + /*! + \return The table name + */ + std::string GetName(void) const override; + + //! Queries the table with a custom "where" clause + /*! + \param predicate The predicate + */ + std::vector Query(std::function predicate); + + //! Gets all the entries in the table + /*! + \return The entries + */ + std::vector GetEntries(void) const; + }; diff --git a/dDatabase/Tables/CDLootMatrixTable.cpp b/dDatabase/Tables/CDLootMatrixTable.cpp index 17fd8313..d47c081b 100644 --- a/dDatabase/Tables/CDLootMatrixTable.cpp +++ b/dDatabase/Tables/CDLootMatrixTable.cpp @@ -2,61 +2,61 @@ //! Constructor CDLootMatrixTable::CDLootMatrixTable(void) { - - // First, get the size of the table - unsigned int size = 0; - auto tableSize = CDClientDatabase::ExecuteQuery("SELECT COUNT(*) FROM LootMatrix"); - while (!tableSize.eof()) { - size = tableSize.getIntField(0, 0); - - tableSize.nextRow(); - } - + + // First, get the size of the table + unsigned int size = 0; + auto tableSize = CDClientDatabase::ExecuteQuery("SELECT COUNT(*) FROM LootMatrix"); + while (!tableSize.eof()) { + size = tableSize.getIntField(0, 0); + + tableSize.nextRow(); + } + tableSize.finalize(); - - // Reserve the size - this->entries.reserve(size); - - // Now get the data - auto tableData = CDClientDatabase::ExecuteQuery("SELECT * FROM LootMatrix"); - while (!tableData.eof()) { - CDLootMatrix entry; - entry.LootMatrixIndex = tableData.getIntField(0, -1); - entry.LootTableIndex = tableData.getIntField(1, -1); - entry.RarityTableIndex = tableData.getIntField(2, -1); - entry.percent = tableData.getFloatField(3, -1.0f); - entry.minToDrop = tableData.getIntField(4, -1); - entry.maxToDrop = tableData.getIntField(5, -1); - entry.id = tableData.getIntField(6, -1); - entry.flagID = tableData.getIntField(7, -1); - UNUSED(entry.gate_version = tableData.getStringField(8, "")); - - this->entries.push_back(entry); - tableData.nextRow(); - } + + // Reserve the size + this->entries.reserve(size); + + // Now get the data + auto tableData = CDClientDatabase::ExecuteQuery("SELECT * FROM LootMatrix"); + while (!tableData.eof()) { + CDLootMatrix entry; + entry.LootMatrixIndex = tableData.getIntField(0, -1); + entry.LootTableIndex = tableData.getIntField(1, -1); + entry.RarityTableIndex = tableData.getIntField(2, -1); + entry.percent = tableData.getFloatField(3, -1.0f); + entry.minToDrop = tableData.getIntField(4, -1); + entry.maxToDrop = tableData.getIntField(5, -1); + entry.id = tableData.getIntField(6, -1); + entry.flagID = tableData.getIntField(7, -1); + UNUSED(entry.gate_version = tableData.getStringField(8, "")); + + this->entries.push_back(entry); + tableData.nextRow(); + } tableData.finalize(); } //! Destructor -CDLootMatrixTable::~CDLootMatrixTable(void) { } +CDLootMatrixTable::~CDLootMatrixTable(void) {} //! Returns the table's name std::string CDLootMatrixTable::GetName(void) const { - return "LootMatrix"; + return "LootMatrix"; } //! Queries the table with a custom "where" clause std::vector CDLootMatrixTable::Query(std::function predicate) { - - std::vector data = cpplinq::from(this->entries) - >> cpplinq::where(predicate) - >> cpplinq::to_vector(); - - return data; + + std::vector data = cpplinq::from(this->entries) + >> cpplinq::where(predicate) + >> cpplinq::to_vector(); + + return data; } //! Gets all the entries in the table const std::vector& CDLootMatrixTable::GetEntries(void) const { - return this->entries; + return this->entries; } diff --git a/dDatabase/Tables/CDLootMatrixTable.h b/dDatabase/Tables/CDLootMatrixTable.h index f306324f..7d311b3b 100644 --- a/dDatabase/Tables/CDLootMatrixTable.h +++ b/dDatabase/Tables/CDLootMatrixTable.h @@ -8,49 +8,49 @@ \brief Contains data for the ObjectSkills table */ -//! LootMatrix Struct + //! LootMatrix Struct struct CDLootMatrix { - unsigned int LootMatrixIndex; //!< The Loot Matrix Index - unsigned int LootTableIndex; //!< The Loot Table Index - unsigned int RarityTableIndex; //!< The Rarity Table Index - float percent; //!< The percent that this matrix is used? - unsigned int minToDrop; //!< The minimum amount of loot from this matrix to drop - unsigned int maxToDrop; //!< The maximum amount of loot from this matrix to drop - unsigned int id; //!< The ID of the Loot Matrix - unsigned int flagID; //!< ??? - UNUSED(std::string gate_version); //!< The Gate Version + unsigned int LootMatrixIndex; //!< The Loot Matrix Index + unsigned int LootTableIndex; //!< The Loot Table Index + unsigned int RarityTableIndex; //!< The Rarity Table Index + float percent; //!< The percent that this matrix is used? + unsigned int minToDrop; //!< The minimum amount of loot from this matrix to drop + unsigned int maxToDrop; //!< The maximum amount of loot from this matrix to drop + unsigned int id; //!< The ID of the Loot Matrix + unsigned int flagID; //!< ??? + UNUSED(std::string gate_version); //!< The Gate Version }; //! MissionNPCComponent table class CDLootMatrixTable : public CDTable { private: - std::vector entries; - + std::vector entries; + public: - - //! Constructor - CDLootMatrixTable(void); - - //! Destructor - ~CDLootMatrixTable(void); - - //! Returns the table's name - /*! - \return The table name - */ - std::string GetName(void) const override; - - //! Queries the table with a custom "where" clause - /*! - \param predicate The predicate - */ - std::vector Query(std::function predicate); - - //! Gets all the entries in the table - /*! - \return The entries - */ - const std::vector& GetEntries(void) const; - + + //! Constructor + CDLootMatrixTable(void); + + //! Destructor + ~CDLootMatrixTable(void); + + //! Returns the table's name + /*! + \return The table name + */ + std::string GetName(void) const override; + + //! Queries the table with a custom "where" clause + /*! + \param predicate The predicate + */ + std::vector Query(std::function predicate); + + //! Gets all the entries in the table + /*! + \return The entries + */ + const std::vector& GetEntries(void) const; + }; diff --git a/dDatabase/Tables/CDLootTableTable.cpp b/dDatabase/Tables/CDLootTableTable.cpp index 62727ade..da8c824b 100644 --- a/dDatabase/Tables/CDLootTableTable.cpp +++ b/dDatabase/Tables/CDLootTableTable.cpp @@ -2,58 +2,58 @@ //! Constructor CDLootTableTable::CDLootTableTable(void) { - - // First, get the size of the table - unsigned int size = 0; - auto tableSize = CDClientDatabase::ExecuteQuery("SELECT COUNT(*) FROM LootTable"); - while (!tableSize.eof()) { - size = tableSize.getIntField(0, 0); - - tableSize.nextRow(); - } - + + // First, get the size of the table + unsigned int size = 0; + auto tableSize = CDClientDatabase::ExecuteQuery("SELECT COUNT(*) FROM LootTable"); + while (!tableSize.eof()) { + size = tableSize.getIntField(0, 0); + + tableSize.nextRow(); + } + tableSize.finalize(); - - // Reserve the size - this->entries.reserve(size); - - // Now get the data - auto tableData = CDClientDatabase::ExecuteQuery("SELECT * FROM LootTable"); - while (!tableData.eof()) { - CDLootTable entry; - entry.id = tableData.getIntField(0, -1); - entry.itemid = tableData.getIntField(0, -1); - entry.LootTableIndex = tableData.getIntField(1, -1); - entry.id = tableData.getIntField(2, -1); - entry.MissionDrop = tableData.getIntField(3, -1) == 1 ? true : false; - entry.sortPriority = tableData.getIntField(4, -1); - - this->entries.push_back(entry); - tableData.nextRow(); - } + + // Reserve the size + this->entries.reserve(size); + + // Now get the data + auto tableData = CDClientDatabase::ExecuteQuery("SELECT * FROM LootTable"); + while (!tableData.eof()) { + CDLootTable entry; + entry.id = tableData.getIntField(0, -1); + entry.itemid = tableData.getIntField(0, -1); + entry.LootTableIndex = tableData.getIntField(1, -1); + entry.id = tableData.getIntField(2, -1); + entry.MissionDrop = tableData.getIntField(3, -1) == 1 ? true : false; + entry.sortPriority = tableData.getIntField(4, -1); + + this->entries.push_back(entry); + tableData.nextRow(); + } tableData.finalize(); } //! Destructor -CDLootTableTable::~CDLootTableTable(void) { } +CDLootTableTable::~CDLootTableTable(void) {} //! Returns the table's name std::string CDLootTableTable::GetName(void) const { - return "LootTable"; + return "LootTable"; } //! Queries the table with a custom "where" clause std::vector CDLootTableTable::Query(std::function predicate) { - - std::vector data = cpplinq::from(this->entries) - >> cpplinq::where(predicate) - >> cpplinq::to_vector(); - - return data; + + std::vector data = cpplinq::from(this->entries) + >> cpplinq::where(predicate) + >> cpplinq::to_vector(); + + return data; } //! Gets all the entries in the table const std::vector& CDLootTableTable::GetEntries(void) const { - return this->entries; + return this->entries; } diff --git a/dDatabase/Tables/CDLootTableTable.h b/dDatabase/Tables/CDLootTableTable.h index 750adcb4..3f1baf60 100644 --- a/dDatabase/Tables/CDLootTableTable.h +++ b/dDatabase/Tables/CDLootTableTable.h @@ -8,45 +8,45 @@ \brief Contains data for the LootTable table */ -//! LootTable Struct + //! LootTable Struct struct CDLootTable { - unsigned int itemid; //!< The LOT of the item - unsigned int LootTableIndex; //!< The Loot Table Index - unsigned int id; //!< The ID - bool MissionDrop; //!< Whether or not this loot table is a mission drop - unsigned int sortPriority; //!< The sorting priority + unsigned int itemid; //!< The LOT of the item + unsigned int LootTableIndex; //!< The Loot Table Index + unsigned int id; //!< The ID + bool MissionDrop; //!< Whether or not this loot table is a mission drop + unsigned int sortPriority; //!< The sorting priority }; //! LootTable table class CDLootTableTable : public CDTable { private: - std::vector entries; - + std::vector entries; + public: - - //! Constructor - CDLootTableTable(void); - - //! Destructor - ~CDLootTableTable(void); - - //! Returns the table's name - /*! - \return The table name - */ - std::string GetName(void) const override; - - //! Queries the table with a custom "where" clause - /*! - \param predicate The predicate - */ - std::vector Query(std::function predicate); - - //! Gets all the entries in the table - /*! - \return The entries - */ - const std::vector& GetEntries(void) const; - + + //! Constructor + CDLootTableTable(void); + + //! Destructor + ~CDLootTableTable(void); + + //! Returns the table's name + /*! + \return The table name + */ + std::string GetName(void) const override; + + //! Queries the table with a custom "where" clause + /*! + \param predicate The predicate + */ + std::vector Query(std::function predicate); + + //! Gets all the entries in the table + /*! + \return The entries + */ + const std::vector& GetEntries(void) const; + }; diff --git a/dDatabase/Tables/CDMissionEmailTable.cpp b/dDatabase/Tables/CDMissionEmailTable.cpp index 2c5fc56a..a8beb95b 100644 --- a/dDatabase/Tables/CDMissionEmailTable.cpp +++ b/dDatabase/Tables/CDMissionEmailTable.cpp @@ -3,59 +3,59 @@ //! Constructor CDMissionEmailTable::CDMissionEmailTable(void) { - // First, get the size of the table - unsigned int size = 0; - auto tableSize = CDClientDatabase::ExecuteQuery("SELECT COUNT(*) FROM MissionEmail"); - while (!tableSize.eof()) { - size = tableSize.getIntField(0, 0); + // First, get the size of the table + unsigned int size = 0; + auto tableSize = CDClientDatabase::ExecuteQuery("SELECT COUNT(*) FROM MissionEmail"); + while (!tableSize.eof()) { + size = tableSize.getIntField(0, 0); + + tableSize.nextRow(); + } - tableSize.nextRow(); - } - tableSize.finalize(); - - // Reserve the size - this->entries.reserve(size); - // Now get the data - auto tableData = CDClientDatabase::ExecuteQuery("SELECT * FROM MissionEmail"); - while (!tableData.eof()) { - CDMissionEmail entry; - entry.ID = tableData.getIntField(0, -1); - entry.messageType = tableData.getIntField(1, -1); - entry.notificationGroup = tableData.getIntField(2, -1); - entry.missionID = tableData.getIntField(3, -1); - entry.attachmentLOT = tableData.getIntField(4, 0); - entry.localize = (bool)tableData.getIntField(5, -1); - entry.locStatus = tableData.getIntField(6, -1); - entry.gate_version = tableData.getStringField(7, ""); + // Reserve the size + this->entries.reserve(size); - this->entries.push_back(entry); - tableData.nextRow(); - } + // Now get the data + auto tableData = CDClientDatabase::ExecuteQuery("SELECT * FROM MissionEmail"); + while (!tableData.eof()) { + CDMissionEmail entry; + entry.ID = tableData.getIntField(0, -1); + entry.messageType = tableData.getIntField(1, -1); + entry.notificationGroup = tableData.getIntField(2, -1); + entry.missionID = tableData.getIntField(3, -1); + entry.attachmentLOT = tableData.getIntField(4, 0); + entry.localize = (bool)tableData.getIntField(5, -1); + entry.locStatus = tableData.getIntField(6, -1); + entry.gate_version = tableData.getStringField(7, ""); + + this->entries.push_back(entry); + tableData.nextRow(); + } tableData.finalize(); } //! Destructor -CDMissionEmailTable::~CDMissionEmailTable(void) { } +CDMissionEmailTable::~CDMissionEmailTable(void) {} //! Returns the table's name std::string CDMissionEmailTable::GetName(void) const { - return "MissionEmail"; + return "MissionEmail"; } //! Queries the table with a custom "where" clause std::vector CDMissionEmailTable::Query(std::function predicate) { - std::vector data = cpplinq::from(this->entries) - >> cpplinq::where(predicate) - >> cpplinq::to_vector(); + std::vector data = cpplinq::from(this->entries) + >> cpplinq::where(predicate) + >> cpplinq::to_vector(); - return data; + return data; } //! Gets all the entries in the table std::vector CDMissionEmailTable::GetEntries(void) const { - return this->entries; + return this->entries; } diff --git a/dDatabase/Tables/CDMissionEmailTable.h b/dDatabase/Tables/CDMissionEmailTable.h index cd0a1285..81a7a793 100644 --- a/dDatabase/Tables/CDMissionEmailTable.h +++ b/dDatabase/Tables/CDMissionEmailTable.h @@ -10,46 +10,46 @@ //! MissionEmail Entry Struct struct CDMissionEmail { - unsigned int ID; - unsigned int messageType; - unsigned int notificationGroup; - unsigned int missionID; - unsigned int attachmentLOT; - bool localize; - unsigned int locStatus; - std::string gate_version; + unsigned int ID; + unsigned int messageType; + unsigned int notificationGroup; + unsigned int missionID; + unsigned int attachmentLOT; + bool localize; + unsigned int locStatus; + std::string gate_version; }; //! MissionEmail table class CDMissionEmailTable : public CDTable { private: - std::vector entries; + std::vector entries; public: - //! Constructor - CDMissionEmailTable(void); + //! Constructor + CDMissionEmailTable(void); - //! Destructor - ~CDMissionEmailTable(void); + //! Destructor + ~CDMissionEmailTable(void); - //! Returns the table's name - /*! - \return The table name - */ - std::string GetName(void) const override; + //! Returns the table's name + /*! + \return The table name + */ + std::string GetName(void) const override; - //! Queries the table with a custom "where" clause - /*! - \param predicate The predicate - */ - std::vector Query(std::function predicate); + //! Queries the table with a custom "where" clause + /*! + \param predicate The predicate + */ + std::vector Query(std::function predicate); - //! Gets all the entries in the table - /*! - \return The entries - */ - std::vector GetEntries(void) const; + //! Gets all the entries in the table + /*! + \return The entries + */ + std::vector GetEntries(void) const; }; diff --git a/dDatabase/Tables/CDMissionNPCComponentTable.cpp b/dDatabase/Tables/CDMissionNPCComponentTable.cpp index 9014585b..e2589890 100644 --- a/dDatabase/Tables/CDMissionNPCComponentTable.cpp +++ b/dDatabase/Tables/CDMissionNPCComponentTable.cpp @@ -2,57 +2,57 @@ //! Constructor CDMissionNPCComponentTable::CDMissionNPCComponentTable(void) { - - // First, get the size of the table - unsigned int size = 0; - auto tableSize = CDClientDatabase::ExecuteQuery("SELECT COUNT(*) FROM MissionNPCComponent"); - while (!tableSize.eof()) { - size = tableSize.getIntField(0, 0); - - tableSize.nextRow(); - } - + + // First, get the size of the table + unsigned int size = 0; + auto tableSize = CDClientDatabase::ExecuteQuery("SELECT COUNT(*) FROM MissionNPCComponent"); + while (!tableSize.eof()) { + size = tableSize.getIntField(0, 0); + + tableSize.nextRow(); + } + tableSize.finalize(); - - // Reserve the size - this->entries.reserve(size); - - // Now get the data - auto tableData = CDClientDatabase::ExecuteQuery("SELECT * FROM MissionNPCComponent"); - while (!tableData.eof()) { - CDMissionNPCComponent entry; - entry.id = tableData.getIntField(0, -1); - entry.missionID = tableData.getIntField(1, -1); - entry.offersMission = tableData.getIntField(2, -1) == 1 ? true : false; - entry.acceptsMission = tableData.getIntField(3, -1) == 1 ? true : false; - entry.gate_version = tableData.getStringField(4, ""); - - this->entries.push_back(entry); - tableData.nextRow(); - } + + // Reserve the size + this->entries.reserve(size); + + // Now get the data + auto tableData = CDClientDatabase::ExecuteQuery("SELECT * FROM MissionNPCComponent"); + while (!tableData.eof()) { + CDMissionNPCComponent entry; + entry.id = tableData.getIntField(0, -1); + entry.missionID = tableData.getIntField(1, -1); + entry.offersMission = tableData.getIntField(2, -1) == 1 ? true : false; + entry.acceptsMission = tableData.getIntField(3, -1) == 1 ? true : false; + entry.gate_version = tableData.getStringField(4, ""); + + this->entries.push_back(entry); + tableData.nextRow(); + } tableData.finalize(); } //! Destructor -CDMissionNPCComponentTable::~CDMissionNPCComponentTable(void) { } +CDMissionNPCComponentTable::~CDMissionNPCComponentTable(void) {} //! Returns the table's name std::string CDMissionNPCComponentTable::GetName(void) const { - return "MissionNPCComponent"; + return "MissionNPCComponent"; } //! Queries the table with a custom "where" clause std::vector CDMissionNPCComponentTable::Query(std::function predicate) { - - std::vector data = cpplinq::from(this->entries) - >> cpplinq::where(predicate) - >> cpplinq::to_vector(); - - return data; + + std::vector data = cpplinq::from(this->entries) + >> cpplinq::where(predicate) + >> cpplinq::to_vector(); + + return data; } //! Gets all the entries in the table std::vector CDMissionNPCComponentTable::GetEntries(void) const { - return this->entries; + return this->entries; } diff --git a/dDatabase/Tables/CDMissionNPCComponentTable.h b/dDatabase/Tables/CDMissionNPCComponentTable.h index a31ba170..68c94ef0 100644 --- a/dDatabase/Tables/CDMissionNPCComponentTable.h +++ b/dDatabase/Tables/CDMissionNPCComponentTable.h @@ -8,45 +8,45 @@ \brief Contains data for the ObjectSkills table */ -//! MissionNPCComponent Struct + //! MissionNPCComponent Struct struct CDMissionNPCComponent { - unsigned int id; //!< The ID - unsigned int missionID; //!< The Mission ID - bool offersMission; //!< Whether or not this NPC offers a mission - bool acceptsMission; //!< Whether or not this NPC accepts a mission - std::string gate_version; //!< The gate version + unsigned int id; //!< The ID + unsigned int missionID; //!< The Mission ID + bool offersMission; //!< Whether or not this NPC offers a mission + bool acceptsMission; //!< Whether or not this NPC accepts a mission + std::string gate_version; //!< The gate version }; //! MissionNPCComponent table class CDMissionNPCComponentTable : public CDTable { private: - std::vector entries; - + std::vector entries; + public: - - //! Constructor - CDMissionNPCComponentTable(void); - - //! Destructor - ~CDMissionNPCComponentTable(void); - - //! Returns the table's name - /*! - \return The table name - */ - std::string GetName(void) const override; - - //! Queries the table with a custom "where" clause - /*! - \param predicate The predicate - */ - std::vector Query(std::function predicate); - - //! Gets all the entries in the table - /*! - \return The entries - */ - std::vector GetEntries(void) const; - + + //! Constructor + CDMissionNPCComponentTable(void); + + //! Destructor + ~CDMissionNPCComponentTable(void); + + //! Returns the table's name + /*! + \return The table name + */ + std::string GetName(void) const override; + + //! Queries the table with a custom "where" clause + /*! + \param predicate The predicate + */ + std::vector Query(std::function predicate); + + //! Gets all the entries in the table + /*! + \return The entries + */ + std::vector GetEntries(void) const; + }; diff --git a/dDatabase/Tables/CDMissionTasksTable.cpp b/dDatabase/Tables/CDMissionTasksTable.cpp index e79e6d02..81de2088 100644 --- a/dDatabase/Tables/CDMissionTasksTable.cpp +++ b/dDatabase/Tables/CDMissionTasksTable.cpp @@ -2,82 +2,79 @@ //! Constructor CDMissionTasksTable::CDMissionTasksTable(void) { - - // First, get the size of the table - unsigned int size = 0; - auto tableSize = CDClientDatabase::ExecuteQuery("SELECT COUNT(*) FROM MissionTasks"); - while (!tableSize.eof()) { - size = tableSize.getIntField(0, 0); - - tableSize.nextRow(); - } - + + // First, get the size of the table + unsigned int size = 0; + auto tableSize = CDClientDatabase::ExecuteQuery("SELECT COUNT(*) FROM MissionTasks"); + while (!tableSize.eof()) { + size = tableSize.getIntField(0, 0); + + tableSize.nextRow(); + } + tableSize.finalize(); - - // Reserve the size - this->entries.reserve(size); - - // Now get the data - auto tableData = CDClientDatabase::ExecuteQuery("SELECT * FROM MissionTasks"); - while (!tableData.eof()) { - CDMissionTasks entry; - entry.id = tableData.getIntField(0, -1); - UNUSED(entry.locStatus = tableData.getIntField(1, -1)); - entry.taskType = tableData.getIntField(2, -1); - entry.target = tableData.getIntField(3, -1); - entry.targetGroup = tableData.getStringField(4, ""); - entry.targetValue = tableData.getIntField(5, -1); - entry.taskParam1 = tableData.getStringField(6, ""); - UNUSED(entry.largeTaskIcon = tableData.getStringField(7, "")); - UNUSED(entry.IconID = tableData.getIntField(8, -1)); - entry.uid = tableData.getIntField(9, -1); - UNUSED(entry.largeTaskIconID = tableData.getIntField(10, -1)); - UNUSED(entry.localize = tableData.getIntField(11, -1) == 1 ? true : false); - UNUSED(entry.gate_version = tableData.getStringField(12, "")); - - this->entries.push_back(entry); - tableData.nextRow(); - } + + // Reserve the size + this->entries.reserve(size); + + // Now get the data + auto tableData = CDClientDatabase::ExecuteQuery("SELECT * FROM MissionTasks"); + while (!tableData.eof()) { + CDMissionTasks entry; + entry.id = tableData.getIntField(0, -1); + UNUSED(entry.locStatus = tableData.getIntField(1, -1)); + entry.taskType = tableData.getIntField(2, -1); + entry.target = tableData.getIntField(3, -1); + entry.targetGroup = tableData.getStringField(4, ""); + entry.targetValue = tableData.getIntField(5, -1); + entry.taskParam1 = tableData.getStringField(6, ""); + UNUSED(entry.largeTaskIcon = tableData.getStringField(7, "")); + UNUSED(entry.IconID = tableData.getIntField(8, -1)); + entry.uid = tableData.getIntField(9, -1); + UNUSED(entry.largeTaskIconID = tableData.getIntField(10, -1)); + UNUSED(entry.localize = tableData.getIntField(11, -1) == 1 ? true : false); + UNUSED(entry.gate_version = tableData.getStringField(12, "")); + + this->entries.push_back(entry); + tableData.nextRow(); + } tableData.finalize(); } //! Destructor -CDMissionTasksTable::~CDMissionTasksTable(void) { } +CDMissionTasksTable::~CDMissionTasksTable(void) {} //! Returns the table's name std::string CDMissionTasksTable::GetName(void) const { - return "MissionTasks"; + return "MissionTasks"; } //! Queries the table with a custom "where" clause std::vector CDMissionTasksTable::Query(std::function predicate) { - - std::vector data = cpplinq::from(this->entries) - >> cpplinq::where(predicate) - >> cpplinq::to_vector(); - - return data; + + std::vector data = cpplinq::from(this->entries) + >> cpplinq::where(predicate) + >> cpplinq::to_vector(); + + return data; } -std::vector CDMissionTasksTable::GetByMissionID(uint32_t missionID) -{ - std::vector tasks; +std::vector CDMissionTasksTable::GetByMissionID(uint32_t missionID) { + std::vector tasks; - for (auto& entry : this->entries) - { - if (entry.id == missionID) - { - CDMissionTasks* task = const_cast(&entry); + for (auto& entry : this->entries) { + if (entry.id == missionID) { + CDMissionTasks* task = const_cast(&entry); - tasks.push_back(task); - } - } + tasks.push_back(task); + } + } - return tasks; + return tasks; } //! Gets all the entries in the table const std::vector& CDMissionTasksTable::GetEntries(void) const { - return this->entries; + return this->entries; } diff --git a/dDatabase/Tables/CDMissionTasksTable.h b/dDatabase/Tables/CDMissionTasksTable.h index af84663e..1a4bd361 100644 --- a/dDatabase/Tables/CDMissionTasksTable.h +++ b/dDatabase/Tables/CDMissionTasksTable.h @@ -8,54 +8,54 @@ \brief Contains data for the MissionTasks table */ -//! ObjectSkills Struct + //! ObjectSkills Struct struct CDMissionTasks { - unsigned int id; //!< The Mission ID that the task belongs to - UNUSED(unsigned int locStatus); //!< ??? - unsigned int taskType; //!< The task type - unsigned int target; //!< The mission target - std::string targetGroup; //!< The mission target group - int targetValue; //!< The target value - std::string taskParam1; //!< The task param 1 - UNUSED(std::string largeTaskIcon); //!< ??? - UNUSED(unsigned int IconID); //!< ??? - unsigned int uid; //!< ??? - UNUSED(unsigned int largeTaskIconID); //!< ??? - UNUSED(bool localize); //!< Whether or not the task should be localized - UNUSED(std::string gate_version); //!< ??? + unsigned int id; //!< The Mission ID that the task belongs to + UNUSED(unsigned int locStatus); //!< ??? + unsigned int taskType; //!< The task type + unsigned int target; //!< The mission target + std::string targetGroup; //!< The mission target group + int targetValue; //!< The target value + std::string taskParam1; //!< The task param 1 + UNUSED(std::string largeTaskIcon); //!< ??? + UNUSED(unsigned int IconID); //!< ??? + unsigned int uid; //!< ??? + UNUSED(unsigned int largeTaskIconID); //!< ??? + UNUSED(bool localize); //!< Whether or not the task should be localized + UNUSED(std::string gate_version); //!< ??? }; //! ObjectSkills table class CDMissionTasksTable : public CDTable { private: - std::vector entries; - -public: - - //! Constructor - CDMissionTasksTable(void); - - //! Destructor - ~CDMissionTasksTable(void); - - //! Returns the table's name - /*! - \return The table name - */ - std::string GetName(void) const override; - - //! Queries the table with a custom "where" clause - /*! - \param predicate The predicate - */ - std::vector Query(std::function predicate); + std::vector entries; - std::vector GetByMissionID(uint32_t missionID); - - //! Gets all the entries in the table - /*! - \return The entries - */ - const std::vector& GetEntries(void) const; +public: + + //! Constructor + CDMissionTasksTable(void); + + //! Destructor + ~CDMissionTasksTable(void); + + //! Returns the table's name + /*! + \return The table name + */ + std::string GetName(void) const override; + + //! Queries the table with a custom "where" clause + /*! + \param predicate The predicate + */ + std::vector Query(std::function predicate); + + std::vector GetByMissionID(uint32_t missionID); + + //! Gets all the entries in the table + /*! + \return The entries + */ + const std::vector& GetEntries(void) const; }; diff --git a/dDatabase/Tables/CDMissionsTable.cpp b/dDatabase/Tables/CDMissionsTable.cpp index 58243bd8..7e59657d 100644 --- a/dDatabase/Tables/CDMissionsTable.cpp +++ b/dDatabase/Tables/CDMissionsTable.cpp @@ -4,136 +4,130 @@ CDMissions CDMissionsTable::Default = {}; //! Constructor CDMissionsTable::CDMissionsTable(void) { - - // First, get the size of the table - unsigned int size = 0; - auto tableSize = CDClientDatabase::ExecuteQuery("SELECT COUNT(*) FROM Missions"); - while (!tableSize.eof()) { - size = tableSize.getIntField(0, 0); - - tableSize.nextRow(); - } - + + // First, get the size of the table + unsigned int size = 0; + auto tableSize = CDClientDatabase::ExecuteQuery("SELECT COUNT(*) FROM Missions"); + while (!tableSize.eof()) { + size = tableSize.getIntField(0, 0); + + tableSize.nextRow(); + } + tableSize.finalize(); - - // Reserve the size - this->entries.reserve(size); - - // Now get the data - auto tableData = CDClientDatabase::ExecuteQuery("SELECT * FROM Missions"); - while (!tableData.eof()) { - CDMissions entry; - entry.id = tableData.getIntField(0, -1); - entry.defined_type = tableData.getStringField(1, ""); - entry.defined_subtype = tableData.getStringField(2, ""); - entry.UISortOrder = tableData.getIntField(3, -1); - entry.offer_objectID = tableData.getIntField(4, -1); - entry.target_objectID = tableData.getIntField(5, -1); - entry.reward_currency = tableData.getInt64Field(6, -1); - entry.LegoScore = tableData.getIntField(7, -1); - entry.reward_reputation = tableData.getIntField(8, -1); - entry.isChoiceReward = tableData.getIntField(9, -1) == 1 ? true : false; - entry.reward_item1 = tableData.getIntField(10, 0); - entry.reward_item1_count = tableData.getIntField(11, 0); - entry.reward_item2 = tableData.getIntField(12, 0); - entry.reward_item2_count = tableData.getIntField(13, 0); - entry.reward_item3 = tableData.getIntField(14, 0); - entry.reward_item3_count = tableData.getIntField(15, 0); - entry.reward_item4 = tableData.getIntField(16, 0); - entry.reward_item4_count = tableData.getIntField(17, 0); - entry.reward_emote = tableData.getIntField(18, -1); - entry.reward_emote2 = tableData.getIntField(19, -1); - entry.reward_emote3 = tableData.getIntField(20, -1); - entry.reward_emote4 = tableData.getIntField(21, -1); - entry.reward_maximagination = tableData.getIntField(22, -1); - entry.reward_maxhealth = tableData.getIntField(23, -1); - entry.reward_maxinventory = tableData.getIntField(24, -1); - entry.reward_maxmodel = tableData.getIntField(25, -1); - entry.reward_maxwidget = tableData.getIntField(26, -1); - entry.reward_maxwallet = tableData.getIntField(27, -1); - entry.repeatable = tableData.getIntField(28, -1) == 1 ? true : false; - entry.reward_currency_repeatable = tableData.getIntField(29, -1); - entry.reward_item1_repeatable = tableData.getIntField(30, -1); - entry.reward_item1_repeat_count = tableData.getIntField(31, -1); - entry.reward_item2_repeatable = tableData.getIntField(32, -1); - entry.reward_item2_repeat_count = tableData.getIntField(33, -1); - entry.reward_item3_repeatable = tableData.getIntField(34, -1); - entry.reward_item3_repeat_count = tableData.getIntField(35, -1); - entry.reward_item4_repeatable = tableData.getIntField(36, -1); - entry.reward_item4_repeat_count = tableData.getIntField(37, -1); - entry.time_limit = tableData.getIntField(38, -1); - entry.isMission = tableData.getIntField(39, -1) ? true : false; - entry.missionIconID = tableData.getIntField(40, -1); - entry.prereqMissionID = tableData.getStringField(41, ""); - entry.localize = tableData.getIntField(42, -1) == 1 ? true : false; - entry.inMOTD = tableData.getIntField(43, -1) == 1 ? true : false; - entry.cooldownTime = tableData.getInt64Field(44, -1); - entry.isRandom = tableData.getIntField(45, -1) == 1 ? true : false; - entry.randomPool = tableData.getStringField(46, ""); - entry.UIPrereqID = tableData.getIntField(47, -1); - UNUSED(entry.gate_version = tableData.getStringField(48, "")); - UNUSED(entry.HUDStates = tableData.getStringField(49, "")); - UNUSED(entry.locStatus = tableData.getIntField(50, -1)); - entry.reward_bankinventory = tableData.getIntField(51, -1); - - this->entries.push_back(entry); - tableData.nextRow(); - } + + // Reserve the size + this->entries.reserve(size); + + // Now get the data + auto tableData = CDClientDatabase::ExecuteQuery("SELECT * FROM Missions"); + while (!tableData.eof()) { + CDMissions entry; + entry.id = tableData.getIntField(0, -1); + entry.defined_type = tableData.getStringField(1, ""); + entry.defined_subtype = tableData.getStringField(2, ""); + entry.UISortOrder = tableData.getIntField(3, -1); + entry.offer_objectID = tableData.getIntField(4, -1); + entry.target_objectID = tableData.getIntField(5, -1); + entry.reward_currency = tableData.getInt64Field(6, -1); + entry.LegoScore = tableData.getIntField(7, -1); + entry.reward_reputation = tableData.getIntField(8, -1); + entry.isChoiceReward = tableData.getIntField(9, -1) == 1 ? true : false; + entry.reward_item1 = tableData.getIntField(10, 0); + entry.reward_item1_count = tableData.getIntField(11, 0); + entry.reward_item2 = tableData.getIntField(12, 0); + entry.reward_item2_count = tableData.getIntField(13, 0); + entry.reward_item3 = tableData.getIntField(14, 0); + entry.reward_item3_count = tableData.getIntField(15, 0); + entry.reward_item4 = tableData.getIntField(16, 0); + entry.reward_item4_count = tableData.getIntField(17, 0); + entry.reward_emote = tableData.getIntField(18, -1); + entry.reward_emote2 = tableData.getIntField(19, -1); + entry.reward_emote3 = tableData.getIntField(20, -1); + entry.reward_emote4 = tableData.getIntField(21, -1); + entry.reward_maximagination = tableData.getIntField(22, -1); + entry.reward_maxhealth = tableData.getIntField(23, -1); + entry.reward_maxinventory = tableData.getIntField(24, -1); + entry.reward_maxmodel = tableData.getIntField(25, -1); + entry.reward_maxwidget = tableData.getIntField(26, -1); + entry.reward_maxwallet = tableData.getIntField(27, -1); + entry.repeatable = tableData.getIntField(28, -1) == 1 ? true : false; + entry.reward_currency_repeatable = tableData.getIntField(29, -1); + entry.reward_item1_repeatable = tableData.getIntField(30, -1); + entry.reward_item1_repeat_count = tableData.getIntField(31, -1); + entry.reward_item2_repeatable = tableData.getIntField(32, -1); + entry.reward_item2_repeat_count = tableData.getIntField(33, -1); + entry.reward_item3_repeatable = tableData.getIntField(34, -1); + entry.reward_item3_repeat_count = tableData.getIntField(35, -1); + entry.reward_item4_repeatable = tableData.getIntField(36, -1); + entry.reward_item4_repeat_count = tableData.getIntField(37, -1); + entry.time_limit = tableData.getIntField(38, -1); + entry.isMission = tableData.getIntField(39, -1) ? true : false; + entry.missionIconID = tableData.getIntField(40, -1); + entry.prereqMissionID = tableData.getStringField(41, ""); + entry.localize = tableData.getIntField(42, -1) == 1 ? true : false; + entry.inMOTD = tableData.getIntField(43, -1) == 1 ? true : false; + entry.cooldownTime = tableData.getInt64Field(44, -1); + entry.isRandom = tableData.getIntField(45, -1) == 1 ? true : false; + entry.randomPool = tableData.getStringField(46, ""); + entry.UIPrereqID = tableData.getIntField(47, -1); + UNUSED(entry.gate_version = tableData.getStringField(48, "")); + UNUSED(entry.HUDStates = tableData.getStringField(49, "")); + UNUSED(entry.locStatus = tableData.getIntField(50, -1)); + entry.reward_bankinventory = tableData.getIntField(51, -1); + + this->entries.push_back(entry); + tableData.nextRow(); + } tableData.finalize(); - Default.id = -1; + Default.id = -1; } //! Destructor -CDMissionsTable::~CDMissionsTable(void) { } +CDMissionsTable::~CDMissionsTable(void) {} //! Returns the table's name std::string CDMissionsTable::GetName(void) const { - return "Missions"; + return "Missions"; } //! Queries the table with a custom "where" clause std::vector CDMissionsTable::Query(std::function predicate) { - - std::vector data = cpplinq::from(this->entries) - >> cpplinq::where(predicate) - >> cpplinq::to_vector(); - - return data; + + std::vector data = cpplinq::from(this->entries) + >> cpplinq::where(predicate) + >> cpplinq::to_vector(); + + return data; } //! Gets all the entries in the table const std::vector& CDMissionsTable::GetEntries(void) const { - return this->entries; + return this->entries; } -const CDMissions* CDMissionsTable::GetPtrByMissionID(uint32_t missionID) const -{ - for (const auto& entry : entries) - { - if (entry.id == missionID) - { - return const_cast(&entry); - } - } +const CDMissions* CDMissionsTable::GetPtrByMissionID(uint32_t missionID) const { + for (const auto& entry : entries) { + if (entry.id == missionID) { + return const_cast(&entry); + } + } - return &Default; + return &Default; } -const CDMissions& CDMissionsTable::GetByMissionID(uint32_t missionID, bool& found) const -{ - for (const auto& entry : entries) - { - if (entry.id == missionID) - { - found = true; +const CDMissions& CDMissionsTable::GetByMissionID(uint32_t missionID, bool& found) const { + for (const auto& entry : entries) { + if (entry.id == missionID) { + found = true; - return entry; - } - } + return entry; + } + } - found = false; + found = false; - return Default; + return Default; } diff --git a/dDatabase/Tables/CDMissionsTable.h b/dDatabase/Tables/CDMissionsTable.h index c961bb80..6d1c4a8f 100644 --- a/dDatabase/Tables/CDMissionsTable.h +++ b/dDatabase/Tables/CDMissionsTable.h @@ -10,97 +10,97 @@ \brief Contains data for the Missions table */ -//! Missions Struct + //! Missions Struct struct CDMissions { - int id; //!< The Mission ID - std::string defined_type; //!< The type of mission - std::string defined_subtype; //!< The subtype of the mission - int UISortOrder; //!< The UI Sort Order for the mission - int offer_objectID; //!< The LOT of the mission giver - int target_objectID; //!< The LOT of the mission's target - int64_t reward_currency; //!< The amount of currency to reward the player - int LegoScore; //!< The amount of LEGO Score to reward the player - int64_t reward_reputation; //!< The reputation to award the player - bool isChoiceReward; //!< Whether or not the user has the option to choose their loot - int reward_item1; //!< The first rewarded item - int reward_item1_count; //!< The count of the first item to be rewarded - int reward_item2; //!< The second rewarded item - int reward_item2_count; //!< The count of the second item to be rewarded - int reward_item3; //!< The third rewarded item - int reward_item3_count; //!< The count of the third item to be rewarded - int reward_item4; //!< The fourth rewarded item - int reward_item4_count; //!< The count of the fourth item to be rewarded - int reward_emote; //!< The first emote to be rewarded - int reward_emote2; //!< The second emote to be rewarded - int reward_emote3; //!< The third emote to be rewarded - int reward_emote4; //!< The fourth emote to be rewarded - int reward_maximagination; //!< The amount of max imagination to reward - int reward_maxhealth; //!< The amount of max health to reward - int reward_maxinventory; //!< The amount of max inventory to reward - int reward_maxmodel; //!< ??? - int reward_maxwidget; //!< ??? - int reward_maxwallet; //!< ??? - bool repeatable; //!< Whether or not this mission can be repeated (for instance, is it a daily mission) - int64_t reward_currency_repeatable; //!< The repeatable reward - int reward_item1_repeatable; //!< The first rewarded item - int reward_item1_repeat_count; //!< The count of the first item to be rewarded - int reward_item2_repeatable; //!< The second rewarded item - int reward_item2_repeat_count; //!< The count of the second item to be rewarded - int reward_item3_repeatable; //!< The third rewarded item - int reward_item3_repeat_count; //!< The count of the third item to be rewarded - int reward_item4_repeatable; //!< The fourth rewarded item - int reward_item4_repeat_count; //!< The count of the fourth item to be rewarded - int time_limit; //!< The time limit of the mission - bool isMission; //!< Maybe to differentiate between missions and achievements? - int missionIconID; //!< The mission icon ID - std::string prereqMissionID; //!< A '|' seperated list of prerequisite missions - bool localize; //!< Whether or not to localize the mission - bool inMOTD; //!< In Match of the Day(?) - int64_t cooldownTime; //!< The mission cooldown time - bool isRandom; //!< ??? - std::string randomPool; //!< ??? - int UIPrereqID; //!< ??? - UNUSED(std::string gate_version); //!< The gate version - UNUSED(std::string HUDStates); //!< ??? - UNUSED(int locStatus); //!< ??? - int reward_bankinventory; //!< The amount of bank space this mission rewards + int id; //!< The Mission ID + std::string defined_type; //!< The type of mission + std::string defined_subtype; //!< The subtype of the mission + int UISortOrder; //!< The UI Sort Order for the mission + int offer_objectID; //!< The LOT of the mission giver + int target_objectID; //!< The LOT of the mission's target + int64_t reward_currency; //!< The amount of currency to reward the player + int LegoScore; //!< The amount of LEGO Score to reward the player + int64_t reward_reputation; //!< The reputation to award the player + bool isChoiceReward; //!< Whether or not the user has the option to choose their loot + int reward_item1; //!< The first rewarded item + int reward_item1_count; //!< The count of the first item to be rewarded + int reward_item2; //!< The second rewarded item + int reward_item2_count; //!< The count of the second item to be rewarded + int reward_item3; //!< The third rewarded item + int reward_item3_count; //!< The count of the third item to be rewarded + int reward_item4; //!< The fourth rewarded item + int reward_item4_count; //!< The count of the fourth item to be rewarded + int reward_emote; //!< The first emote to be rewarded + int reward_emote2; //!< The second emote to be rewarded + int reward_emote3; //!< The third emote to be rewarded + int reward_emote4; //!< The fourth emote to be rewarded + int reward_maximagination; //!< The amount of max imagination to reward + int reward_maxhealth; //!< The amount of max health to reward + int reward_maxinventory; //!< The amount of max inventory to reward + int reward_maxmodel; //!< ??? + int reward_maxwidget; //!< ??? + int reward_maxwallet; //!< ??? + bool repeatable; //!< Whether or not this mission can be repeated (for instance, is it a daily mission) + int64_t reward_currency_repeatable; //!< The repeatable reward + int reward_item1_repeatable; //!< The first rewarded item + int reward_item1_repeat_count; //!< The count of the first item to be rewarded + int reward_item2_repeatable; //!< The second rewarded item + int reward_item2_repeat_count; //!< The count of the second item to be rewarded + int reward_item3_repeatable; //!< The third rewarded item + int reward_item3_repeat_count; //!< The count of the third item to be rewarded + int reward_item4_repeatable; //!< The fourth rewarded item + int reward_item4_repeat_count; //!< The count of the fourth item to be rewarded + int time_limit; //!< The time limit of the mission + bool isMission; //!< Maybe to differentiate between missions and achievements? + int missionIconID; //!< The mission icon ID + std::string prereqMissionID; //!< A '|' seperated list of prerequisite missions + bool localize; //!< Whether or not to localize the mission + bool inMOTD; //!< In Match of the Day(?) + int64_t cooldownTime; //!< The mission cooldown time + bool isRandom; //!< ??? + std::string randomPool; //!< ??? + int UIPrereqID; //!< ??? + UNUSED(std::string gate_version); //!< The gate version + UNUSED(std::string HUDStates); //!< ??? + UNUSED(int locStatus); //!< ??? + int reward_bankinventory; //!< The amount of bank space this mission rewards }; //! Missions table class CDMissionsTable : public CDTable { private: - std::vector entries; - + std::vector entries; + public: - - //! Constructor - CDMissionsTable(void); - - //! Destructor - ~CDMissionsTable(void); - - //! Returns the table's name - /*! - \return The table name - */ - std::string GetName(void) const override; - - //! Queries the table with a custom "where" clause - /*! - \param predicate The predicate - */ - std::vector Query(std::function predicate); - //! Gets all the entries in the table - /*! - \return The entries - */ - const std::vector& GetEntries(void) const; + //! Constructor + CDMissionsTable(void); - const CDMissions* GetPtrByMissionID(uint32_t missionID) const; + //! Destructor + ~CDMissionsTable(void); - const CDMissions& GetByMissionID(uint32_t missionID, bool& found) const; + //! Returns the table's name + /*! + \return The table name + */ + std::string GetName(void) const override; - static CDMissions Default; + //! Queries the table with a custom "where" clause + /*! + \param predicate The predicate + */ + std::vector Query(std::function predicate); + + //! Gets all the entries in the table + /*! + \return The entries + */ + const std::vector& GetEntries(void) const; + + const CDMissions* GetPtrByMissionID(uint32_t missionID) const; + + const CDMissions& GetByMissionID(uint32_t missionID, bool& found) const; + + static CDMissions Default; }; diff --git a/dDatabase/Tables/CDMovementAIComponentTable.cpp b/dDatabase/Tables/CDMovementAIComponentTable.cpp index d4fe4881..a98be8ba 100644 --- a/dDatabase/Tables/CDMovementAIComponentTable.cpp +++ b/dDatabase/Tables/CDMovementAIComponentTable.cpp @@ -11,9 +11,9 @@ CDMovementAIComponentTable::CDMovementAIComponentTable(void) { tableSize.nextRow(); } - + tableSize.finalize(); - + // Reserve the size this->entries.reserve(size); @@ -38,7 +38,7 @@ CDMovementAIComponentTable::CDMovementAIComponentTable(void) { } //! Destructor -CDMovementAIComponentTable::~CDMovementAIComponentTable(void) { } +CDMovementAIComponentTable::~CDMovementAIComponentTable(void) {} //! Returns the table's name std::string CDMovementAIComponentTable::GetName(void) const { diff --git a/dDatabase/Tables/CDObjectSkillsTable.cpp b/dDatabase/Tables/CDObjectSkillsTable.cpp index 4b133df8..1a5c4790 100644 --- a/dDatabase/Tables/CDObjectSkillsTable.cpp +++ b/dDatabase/Tables/CDObjectSkillsTable.cpp @@ -2,56 +2,56 @@ //! Constructor CDObjectSkillsTable::CDObjectSkillsTable(void) { - - // First, get the size of the table - unsigned int size = 0; - auto tableSize = CDClientDatabase::ExecuteQuery("SELECT COUNT(*) FROM ObjectSkills"); - while (!tableSize.eof()) { - size = tableSize.getIntField(0, 0); - - tableSize.nextRow(); - } - + + // First, get the size of the table + unsigned int size = 0; + auto tableSize = CDClientDatabase::ExecuteQuery("SELECT COUNT(*) FROM ObjectSkills"); + while (!tableSize.eof()) { + size = tableSize.getIntField(0, 0); + + tableSize.nextRow(); + } + tableSize.finalize(); - - // Reserve the size - this->entries.reserve(size); - - // Now get the data - auto tableData = CDClientDatabase::ExecuteQuery("SELECT * FROM ObjectSkills"); - while (!tableData.eof()) { - CDObjectSkills entry; - entry.objectTemplate = tableData.getIntField(0, -1); - entry.skillID = tableData.getIntField(1, -1); - entry.castOnType = tableData.getIntField(2, -1); - entry.AICombatWeight = tableData.getIntField(3, -1); - - this->entries.push_back(entry); - tableData.nextRow(); - } + + // Reserve the size + this->entries.reserve(size); + + // Now get the data + auto tableData = CDClientDatabase::ExecuteQuery("SELECT * FROM ObjectSkills"); + while (!tableData.eof()) { + CDObjectSkills entry; + entry.objectTemplate = tableData.getIntField(0, -1); + entry.skillID = tableData.getIntField(1, -1); + entry.castOnType = tableData.getIntField(2, -1); + entry.AICombatWeight = tableData.getIntField(3, -1); + + this->entries.push_back(entry); + tableData.nextRow(); + } tableData.finalize(); } //! Destructor -CDObjectSkillsTable::~CDObjectSkillsTable(void) { } +CDObjectSkillsTable::~CDObjectSkillsTable(void) {} //! Returns the table's name std::string CDObjectSkillsTable::GetName(void) const { - return "ObjectSkills"; + return "ObjectSkills"; } //! Queries the table with a custom "where" clause std::vector CDObjectSkillsTable::Query(std::function predicate) { - - std::vector data = cpplinq::from(this->entries) - >> cpplinq::where(predicate) - >> cpplinq::to_vector(); - - return data; + + std::vector data = cpplinq::from(this->entries) + >> cpplinq::where(predicate) + >> cpplinq::to_vector(); + + return data; } //! Gets all the entries in the table std::vector CDObjectSkillsTable::GetEntries(void) const { - return this->entries; + return this->entries; } diff --git a/dDatabase/Tables/CDObjectSkillsTable.h b/dDatabase/Tables/CDObjectSkillsTable.h index 986d95d4..c2caf71b 100644 --- a/dDatabase/Tables/CDObjectSkillsTable.h +++ b/dDatabase/Tables/CDObjectSkillsTable.h @@ -8,44 +8,44 @@ \brief Contains data for the ObjectSkills table */ -//! ObjectSkills Struct + //! ObjectSkills Struct struct CDObjectSkills { - unsigned int objectTemplate; //!< The LOT of the item - unsigned int skillID; //!< The Skill ID of the object - unsigned int castOnType; //!< ??? - unsigned int AICombatWeight; //!< ??? + unsigned int objectTemplate; //!< The LOT of the item + unsigned int skillID; //!< The Skill ID of the object + unsigned int castOnType; //!< ??? + unsigned int AICombatWeight; //!< ??? }; //! ObjectSkills table class CDObjectSkillsTable : public CDTable { private: - std::vector entries; - + std::vector entries; + public: - - //! Constructor - CDObjectSkillsTable(void); - - //! Destructor - ~CDObjectSkillsTable(void); - - //! Returns the table's name - /*! - \return The table name - */ - std::string GetName(void) const override; - - //! Queries the table with a custom "where" clause - /*! - \param predicate The predicate - */ - std::vector Query(std::function predicate); - - //! Gets all the entries in the table - /*! - \return The entries - */ - std::vector GetEntries(void) const; - + + //! Constructor + CDObjectSkillsTable(void); + + //! Destructor + ~CDObjectSkillsTable(void); + + //! Returns the table's name + /*! + \return The table name + */ + std::string GetName(void) const override; + + //! Queries the table with a custom "where" clause + /*! + \param predicate The predicate + */ + std::vector Query(std::function predicate); + + //! Gets all the entries in the table + /*! + \return The entries + */ + std::vector GetEntries(void) const; + }; diff --git a/dDatabase/Tables/CDObjectsTable.cpp b/dDatabase/Tables/CDObjectsTable.cpp index 5106f96a..03979af2 100644 --- a/dDatabase/Tables/CDObjectsTable.cpp +++ b/dDatabase/Tables/CDObjectsTable.cpp @@ -3,39 +3,39 @@ //! Constructor CDObjectsTable::CDObjectsTable(void) { #ifdef CDCLIENT_CACHE_ALL - // First, get the size of the table - unsigned int size = 0; - auto tableSize = CDClientDatabase::ExecuteQuery("SELECT COUNT(*) FROM Objects"); - while (!tableSize.eof()) { - size = tableSize.getIntField(0, 0); - - tableSize.nextRow(); - } - + // First, get the size of the table + unsigned int size = 0; + auto tableSize = CDClientDatabase::ExecuteQuery("SELECT COUNT(*) FROM Objects"); + while (!tableSize.eof()) { + size = tableSize.getIntField(0, 0); + + tableSize.nextRow(); + } + tableSize.finalize(); - - // Now get the data - auto tableData = CDClientDatabase::ExecuteQuery("SELECT * FROM Objects"); - while (!tableData.eof()) { - CDObjects entry; - entry.id = tableData.getIntField(0, -1); - entry.name = tableData.getStringField(1, ""); - entry.placeable = tableData.getIntField(2, -1); - entry.type = tableData.getStringField(3, ""); - entry.description = tableData.getStringField(4, ""); - entry.localize = tableData.getIntField(5, -1); - entry.npcTemplateID = tableData.getIntField(6, -1); - entry.displayName = tableData.getStringField(7, ""); - entry.interactionDistance = tableData.getFloatField(8, -1.0f); - entry.nametag = tableData.getIntField(9, -1); - entry._internalNotes = tableData.getStringField(10, ""); - entry.locStatus = tableData.getIntField(11, -1); - entry.gate_version = tableData.getStringField(12, ""); - entry.HQ_valid = tableData.getIntField(13, -1); - - this->entries.insert(std::make_pair(entry.id, entry)); - tableData.nextRow(); - } + + // Now get the data + auto tableData = CDClientDatabase::ExecuteQuery("SELECT * FROM Objects"); + while (!tableData.eof()) { + CDObjects entry; + entry.id = tableData.getIntField(0, -1); + entry.name = tableData.getStringField(1, ""); + entry.placeable = tableData.getIntField(2, -1); + entry.type = tableData.getStringField(3, ""); + entry.description = tableData.getStringField(4, ""); + entry.localize = tableData.getIntField(5, -1); + entry.npcTemplateID = tableData.getIntField(6, -1); + entry.displayName = tableData.getStringField(7, ""); + entry.interactionDistance = tableData.getFloatField(8, -1.0f); + entry.nametag = tableData.getIntField(9, -1); + entry._internalNotes = tableData.getStringField(10, ""); + entry.locStatus = tableData.getIntField(11, -1); + entry.gate_version = tableData.getStringField(12, ""); + entry.HQ_valid = tableData.getIntField(13, -1); + + this->entries.insert(std::make_pair(entry.id, entry)); + tableData.nextRow(); + } tableData.finalize(); #endif @@ -44,14 +44,14 @@ CDObjectsTable::CDObjectsTable(void) { } //! Destructor -CDObjectsTable::~CDObjectsTable(void) { } +CDObjectsTable::~CDObjectsTable(void) {} //! Returns the table's name std::string CDObjectsTable::GetName(void) const { - return "Objects"; + return "Objects"; } -const CDObjects & CDObjectsTable::GetByID(unsigned int LOT) { +const CDObjects& CDObjectsTable::GetByID(unsigned int LOT) { const auto& it = this->entries.find(LOT); if (it != this->entries.end()) { return it->second; @@ -63,32 +63,32 @@ const CDObjects & CDObjectsTable::GetByID(unsigned int LOT) { query << "SELECT * FROM Objects WHERE id = " << std::to_string(LOT); auto tableData = CDClientDatabase::ExecuteQuery(query.str()); - if (tableData.eof()) { - this->entries.insert(std::make_pair(LOT, m_default)); + if (tableData.eof()) { + this->entries.insert(std::make_pair(LOT, m_default)); return m_default; } - // Now get the data - while (!tableData.eof()) { - CDObjects entry; - entry.id = tableData.getIntField(0, -1); - entry.name = tableData.getStringField(1, ""); - UNUSED(entry.placeable = tableData.getIntField(2, -1)); - entry.type = tableData.getStringField(3, ""); - UNUSED(ntry.description = tableData.getStringField(4, "")); - UNUSED(entry.localize = tableData.getIntField(5, -1)); - UNUSED(entry.npcTemplateID = tableData.getIntField(6, -1)); - UNUSED(entry.displayName = tableData.getStringField(7, "")); - entry.interactionDistance = tableData.getFloatField(8, -1.0f); - UNUSED(entry.nametag = tableData.getIntField(9, -1)); - UNUSED(entry._internalNotes = tableData.getStringField(10, "")); - UNUSED(entry.locStatus = tableData.getIntField(11, -1)); - UNUSED(entry.gate_version = tableData.getStringField(12, "")); - UNUSED(entry.HQ_valid = tableData.getIntField(13, -1)); - - this->entries.insert(std::make_pair(entry.id, entry)); - tableData.nextRow(); - } + // Now get the data + while (!tableData.eof()) { + CDObjects entry; + entry.id = tableData.getIntField(0, -1); + entry.name = tableData.getStringField(1, ""); + UNUSED(entry.placeable = tableData.getIntField(2, -1)); + entry.type = tableData.getStringField(3, ""); + UNUSED(ntry.description = tableData.getStringField(4, "")); + UNUSED(entry.localize = tableData.getIntField(5, -1)); + UNUSED(entry.npcTemplateID = tableData.getIntField(6, -1)); + UNUSED(entry.displayName = tableData.getStringField(7, "")); + entry.interactionDistance = tableData.getFloatField(8, -1.0f); + UNUSED(entry.nametag = tableData.getIntField(9, -1)); + UNUSED(entry._internalNotes = tableData.getStringField(10, "")); + UNUSED(entry.locStatus = tableData.getIntField(11, -1)); + UNUSED(entry.gate_version = tableData.getStringField(12, "")); + UNUSED(entry.HQ_valid = tableData.getIntField(13, -1)); + + this->entries.insert(std::make_pair(entry.id, entry)); + tableData.nextRow(); + } tableData.finalize(); @@ -99,4 +99,4 @@ const CDObjects & CDObjectsTable::GetByID(unsigned int LOT) { #endif return m_default; -} \ No newline at end of file +} diff --git a/dDatabase/Tables/CDObjectsTable.h b/dDatabase/Tables/CDObjectsTable.h index c6dbc662..333477bd 100644 --- a/dDatabase/Tables/CDObjectsTable.h +++ b/dDatabase/Tables/CDObjectsTable.h @@ -8,45 +8,45 @@ \brief Contains data for the Objects table */ -//! RebuildComponent Struct + //! RebuildComponent Struct struct CDObjects { - unsigned int id; //!< The LOT of the object - std::string name; //!< The internal name of the object - UNUSED(unsigned int placeable); //!< Whether or not the object is placable - std::string type; //!< The object type - UNUSED(std::string description); //!< An internal description of the object - UNUSED(unsigned int localize); //!< Whether or not the object should localize - UNUSED(unsigned int npcTemplateID); //!< Something related to NPCs... - UNUSED(std::string displayName); //!< The display name of the object - float interactionDistance; //!< The interaction distance of the object - UNUSED(unsigned int nametag); //!< ??? - UNUSED(std::string _internalNotes); //!< Some internal notes (rarely used) - UNUSED(unsigned int locStatus); //!< ??? - UNUSED(std::string gate_version); //!< The gate version for the object - UNUSED(unsigned int HQ_valid); //!< Probably used for the Nexus HQ database on LEGOUniverse.com + unsigned int id; //!< The LOT of the object + std::string name; //!< The internal name of the object + UNUSED(unsigned int placeable); //!< Whether or not the object is placable + std::string type; //!< The object type + UNUSED(std::string description); //!< An internal description of the object + UNUSED(unsigned int localize); //!< Whether or not the object should localize + UNUSED(unsigned int npcTemplateID); //!< Something related to NPCs... + UNUSED(std::string displayName); //!< The display name of the object + float interactionDistance; //!< The interaction distance of the object + UNUSED(unsigned int nametag); //!< ??? + UNUSED(std::string _internalNotes); //!< Some internal notes (rarely used) + UNUSED(unsigned int locStatus); //!< ??? + UNUSED(std::string gate_version); //!< The gate version for the object + UNUSED(unsigned int HQ_valid); //!< Probably used for the Nexus HQ database on LEGOUniverse.com }; //! ObjectSkills table class CDObjectsTable : public CDTable { private: - //std::vector entries; + //std::vector entries; std::map entries; CDObjects m_default; - + public: - - //! Constructor - CDObjectsTable(void); - - //! Destructor - ~CDObjectsTable(void); - - //! Returns the table's name - /*! - \return The table name - */ - std::string GetName(void) const override; - + + //! Constructor + CDObjectsTable(void); + + //! Destructor + ~CDObjectsTable(void); + + //! Returns the table's name + /*! + \return The table name + */ + std::string GetName(void) const override; + //! Gets an entry by ID const CDObjects& GetByID(unsigned int LOT); diff --git a/dDatabase/Tables/CDPackageComponentTable.cpp b/dDatabase/Tables/CDPackageComponentTable.cpp index 23af5e38..83673c6f 100644 --- a/dDatabase/Tables/CDPackageComponentTable.cpp +++ b/dDatabase/Tables/CDPackageComponentTable.cpp @@ -11,9 +11,9 @@ CDPackageComponentTable::CDPackageComponentTable(void) { tableSize.nextRow(); } - + tableSize.finalize(); - + // Reserve the size this->entries.reserve(size); @@ -33,7 +33,7 @@ CDPackageComponentTable::CDPackageComponentTable(void) { } //! Destructor -CDPackageComponentTable::~CDPackageComponentTable(void) { } +CDPackageComponentTable::~CDPackageComponentTable(void) {} //! Returns the table's name std::string CDPackageComponentTable::GetName(void) const { @@ -53,4 +53,4 @@ std::vector CDPackageComponentTable::Query(std::function CDPackageComponentTable::GetEntries(void) const { return this->entries; -} \ No newline at end of file +} diff --git a/dDatabase/Tables/CDPhysicsComponentTable.cpp b/dDatabase/Tables/CDPhysicsComponentTable.cpp index b4b836ae..8cb7a3b0 100644 --- a/dDatabase/Tables/CDPhysicsComponentTable.cpp +++ b/dDatabase/Tables/CDPhysicsComponentTable.cpp @@ -1,10 +1,10 @@ #include "CDPhysicsComponentTable.h" CDPhysicsComponentTable::CDPhysicsComponentTable(void) { - auto tableData = CDClientDatabase::ExecuteQuery("SELECT * FROM PhysicsComponent"); - while (!tableData.eof()) { + auto tableData = CDClientDatabase::ExecuteQuery("SELECT * FROM PhysicsComponent"); + while (!tableData.eof()) { CDPhysicsComponent* entry = new CDPhysicsComponent(); - entry->id = tableData.getIntField(0, -1); + entry->id = tableData.getIntField(0, -1); entry->bStatic = tableData.getIntField(1, -1) != 0; entry->physicsAsset = tableData.getStringField(2, ""); UNUSED(entry->jump = tableData.getIntField(3, -1) != 0); @@ -22,28 +22,28 @@ CDPhysicsComponentTable::CDPhysicsComponentTable(void) { UNUSED(entry->gravityVolumeAsset = tableData.getStringField(15)); m_entries.insert(std::make_pair(entry->id, entry)); - tableData.nextRow(); - } + tableData.nextRow(); + } tableData.finalize(); } CDPhysicsComponentTable::~CDPhysicsComponentTable(void) { - for (auto e : m_entries) { - if (e.second) delete e.second; - } - - m_entries.clear(); + for (auto e : m_entries) { + if (e.second) delete e.second; + } + + m_entries.clear(); } std::string CDPhysicsComponentTable::GetName(void) const { - return "PhysicsComponent"; + return "PhysicsComponent"; } CDPhysicsComponent* CDPhysicsComponentTable::GetByID(unsigned int componentID) { - for (auto e : m_entries) { + for (auto e : m_entries) { if (e.first == componentID) return e.second; - } - - return nullptr; + } + + return nullptr; } diff --git a/dDatabase/Tables/CDPhysicsComponentTable.h b/dDatabase/Tables/CDPhysicsComponentTable.h index aa19757f..c5805da3 100644 --- a/dDatabase/Tables/CDPhysicsComponentTable.h +++ b/dDatabase/Tables/CDPhysicsComponentTable.h @@ -23,12 +23,12 @@ struct CDPhysicsComponent { class CDPhysicsComponentTable : public CDTable { public: - CDPhysicsComponentTable(void); - ~CDPhysicsComponentTable(void); - - std::string GetName(void) const override; + CDPhysicsComponentTable(void); + ~CDPhysicsComponentTable(void); + + std::string GetName(void) const override; CDPhysicsComponent* GetByID(unsigned int componentID); private: std::map m_entries; -}; \ No newline at end of file +}; diff --git a/dDatabase/Tables/CDPropertyEntranceComponentTable.cpp b/dDatabase/Tables/CDPropertyEntranceComponentTable.cpp index 500ef659..01a2ae37 100644 --- a/dDatabase/Tables/CDPropertyEntranceComponentTable.cpp +++ b/dDatabase/Tables/CDPropertyEntranceComponentTable.cpp @@ -3,31 +3,31 @@ CDPropertyEntranceComponentTable::CDPropertyEntranceComponentTable() { - // First, get the size of the table - size_t size = 0; - auto tableSize = CDClientDatabase::ExecuteQuery("SELECT COUNT(*) FROM PropertyEntranceComponent"); - while (!tableSize.eof()) { - size = tableSize.getIntField(0, 0); - tableSize.nextRow(); - } - + // First, get the size of the table + size_t size = 0; + auto tableSize = CDClientDatabase::ExecuteQuery("SELECT COUNT(*) FROM PropertyEntranceComponent"); + while (!tableSize.eof()) { + size = tableSize.getIntField(0, 0); + tableSize.nextRow(); + } + tableSize.finalize(); - - this->entries.reserve(size); - auto tableData = CDClientDatabase::ExecuteQuery("SELECT * FROM PropertyEntranceComponent;"); - while (!tableData.eof()) { - auto entry = CDPropertyEntranceComponent { - static_cast(tableData.getIntField(0, -1)), - static_cast(tableData.getIntField(1, -1)), - tableData.getStringField(2, ""), - static_cast(tableData.getIntField(3, false)), - tableData.getStringField(4, "") - }; + this->entries.reserve(size); - this->entries.push_back(entry); - tableData.nextRow(); - } + auto tableData = CDClientDatabase::ExecuteQuery("SELECT * FROM PropertyEntranceComponent;"); + while (!tableData.eof()) { + auto entry = CDPropertyEntranceComponent{ + static_cast(tableData.getIntField(0, -1)), + static_cast(tableData.getIntField(1, -1)), + tableData.getStringField(2, ""), + static_cast(tableData.getIntField(3, false)), + tableData.getStringField(4, "") + }; + + this->entries.push_back(entry); + tableData.nextRow(); + } tableData.finalize(); } @@ -35,14 +35,14 @@ CDPropertyEntranceComponentTable::CDPropertyEntranceComponentTable() { CDPropertyEntranceComponentTable::~CDPropertyEntranceComponentTable(void) = default; std::string CDPropertyEntranceComponentTable::GetName() const { - return "PropertyEntranceComponent"; + return "PropertyEntranceComponent"; } CDPropertyEntranceComponent CDPropertyEntranceComponentTable::GetByID(uint32_t id) { - for (const auto& entry : entries) { - if (entry.id == id) - return entry; - } + for (const auto& entry : entries) { + if (entry.id == id) + return entry; + } - return defaultEntry; + return defaultEntry; } diff --git a/dDatabase/Tables/CDPropertyEntranceComponentTable.h b/dDatabase/Tables/CDPropertyEntranceComponentTable.h index 8cecd941..fa0603c0 100644 --- a/dDatabase/Tables/CDPropertyEntranceComponentTable.h +++ b/dDatabase/Tables/CDPropertyEntranceComponentTable.h @@ -2,40 +2,40 @@ #include "CDTable.h" struct CDPropertyEntranceComponent { - uint32_t id; - uint32_t mapID; - std::string propertyName; - bool isOnProperty; - std::string groupType; + uint32_t id; + uint32_t mapID; + std::string propertyName; + bool isOnProperty; + std::string groupType; }; class CDPropertyEntranceComponentTable : public CDTable { public: - //! Constructor - CDPropertyEntranceComponentTable(); + //! Constructor + CDPropertyEntranceComponentTable(); - //! Destructor - ~CDPropertyEntranceComponentTable(); + //! Destructor + ~CDPropertyEntranceComponentTable(); - //! Returns the table's name - /*! - \return The table name - */ - [[nodiscard]] std::string GetName() const override; + //! Returns the table's name + /*! + \return The table name + */ + [[nodiscard]] std::string GetName() const override; - //! Queries the table with a custom "where" clause - /*! - \param predicate The predicate - */ - CDPropertyEntranceComponent GetByID(uint32_t id); + //! Queries the table with a custom "where" clause + /*! + \param predicate The predicate + */ + CDPropertyEntranceComponent GetByID(uint32_t id); - //! Gets all the entries in the table - /*! - \return The entries - */ - [[nodiscard]] std::vector GetEntries() const { return entries; } + //! Gets all the entries in the table + /*! + \return The entries + */ + [[nodiscard]] std::vector GetEntries() const { return entries; } private: - std::vector entries {}; - CDPropertyEntranceComponent defaultEntry {}; + std::vector entries{}; + CDPropertyEntranceComponent defaultEntry{}; }; diff --git a/dDatabase/Tables/CDPropertyTemplateTable.cpp b/dDatabase/Tables/CDPropertyTemplateTable.cpp index 11ba9378..7dd118eb 100644 --- a/dDatabase/Tables/CDPropertyTemplateTable.cpp +++ b/dDatabase/Tables/CDPropertyTemplateTable.cpp @@ -2,30 +2,30 @@ CDPropertyTemplateTable::CDPropertyTemplateTable() { - // First, get the size of the table - size_t size = 0; - auto tableSize = CDClientDatabase::ExecuteQuery("SELECT COUNT(*) FROM PropertyTemplate;"); - while (!tableSize.eof()) { - size = tableSize.getIntField(0, 0); - tableSize.nextRow(); - } - + // First, get the size of the table + size_t size = 0; + auto tableSize = CDClientDatabase::ExecuteQuery("SELECT COUNT(*) FROM PropertyTemplate;"); + while (!tableSize.eof()) { + size = tableSize.getIntField(0, 0); + tableSize.nextRow(); + } + tableSize.finalize(); - - this->entries.reserve(size); - auto tableData = CDClientDatabase::ExecuteQuery("SELECT * FROM PropertyTemplate;"); - while (!tableData.eof()) { - auto entry = CDPropertyTemplate { - static_cast(tableData.getIntField(0, -1)), - static_cast(tableData.getIntField(1, -1)), - static_cast(tableData.getIntField(2, -1)), - tableData.getStringField(3, "") - }; + this->entries.reserve(size); - this->entries.push_back(entry); - tableData.nextRow(); - } + auto tableData = CDClientDatabase::ExecuteQuery("SELECT * FROM PropertyTemplate;"); + while (!tableData.eof()) { + auto entry = CDPropertyTemplate{ + static_cast(tableData.getIntField(0, -1)), + static_cast(tableData.getIntField(1, -1)), + static_cast(tableData.getIntField(2, -1)), + tableData.getStringField(3, "") + }; + + this->entries.push_back(entry); + tableData.nextRow(); + } tableData.finalize(); } @@ -33,14 +33,14 @@ CDPropertyTemplateTable::CDPropertyTemplateTable() { CDPropertyTemplateTable::~CDPropertyTemplateTable() = default; std::string CDPropertyTemplateTable::GetName() const { - return "PropertyTemplate"; + return "PropertyTemplate"; } CDPropertyTemplate CDPropertyTemplateTable::GetByMapID(uint32_t mapID) { - for (const auto& entry : entries) { - if (entry.mapID == mapID) - return entry; - } + for (const auto& entry : entries) { + if (entry.mapID == mapID) + return entry; + } - return defaultEntry; + return defaultEntry; } diff --git a/dDatabase/Tables/CDPropertyTemplateTable.h b/dDatabase/Tables/CDPropertyTemplateTable.h index 24e6a739..a266932b 100644 --- a/dDatabase/Tables/CDPropertyTemplateTable.h +++ b/dDatabase/Tables/CDPropertyTemplateTable.h @@ -2,20 +2,20 @@ #include "CDTable.h" struct CDPropertyTemplate { - uint32_t id; - uint32_t mapID; - uint32_t vendorMapID; - std::string spawnName; + uint32_t id; + uint32_t mapID; + uint32_t vendorMapID; + std::string spawnName; }; class CDPropertyTemplateTable : public CDTable { public: - CDPropertyTemplateTable(); - ~CDPropertyTemplateTable(); + CDPropertyTemplateTable(); + ~CDPropertyTemplateTable(); - [[nodiscard]] std::string GetName() const override; - CDPropertyTemplate GetByMapID(uint32_t mapID); + [[nodiscard]] std::string GetName() const override; + CDPropertyTemplate GetByMapID(uint32_t mapID); private: - std::vector entries {}; - CDPropertyTemplate defaultEntry {}; -}; \ No newline at end of file + std::vector entries{}; + CDPropertyTemplate defaultEntry{}; +}; diff --git a/dDatabase/Tables/CDProximityMonitorComponentTable.cpp b/dDatabase/Tables/CDProximityMonitorComponentTable.cpp index d4195f0c..092f3ca1 100644 --- a/dDatabase/Tables/CDProximityMonitorComponentTable.cpp +++ b/dDatabase/Tables/CDProximityMonitorComponentTable.cpp @@ -11,9 +11,9 @@ CDProximityMonitorComponentTable::CDProximityMonitorComponentTable(void) { tableSize.nextRow(); } - + tableSize.finalize(); - + // Reserve the size this->entries.reserve(size); @@ -34,7 +34,7 @@ CDProximityMonitorComponentTable::CDProximityMonitorComponentTable(void) { } //! Destructor -CDProximityMonitorComponentTable::~CDProximityMonitorComponentTable(void) { } +CDProximityMonitorComponentTable::~CDProximityMonitorComponentTable(void) {} //! Returns the table's name std::string CDProximityMonitorComponentTable::GetName(void) const { diff --git a/dDatabase/Tables/CDRailActivatorComponent.cpp b/dDatabase/Tables/CDRailActivatorComponent.cpp index e3a2f8b8..ef72859b 100644 --- a/dDatabase/Tables/CDRailActivatorComponent.cpp +++ b/dDatabase/Tables/CDRailActivatorComponent.cpp @@ -2,82 +2,82 @@ #include "GeneralUtils.h" CDRailActivatorComponentTable::CDRailActivatorComponentTable() { - auto tableData = CDClientDatabase::ExecuteQuery("SELECT * FROM RailActivatorComponent;"); - while (!tableData.eof()) { - CDRailActivatorComponent entry; + auto tableData = CDClientDatabase::ExecuteQuery("SELECT * FROM RailActivatorComponent;"); + while (!tableData.eof()) { + CDRailActivatorComponent entry; - entry.id = tableData.getIntField(0); + entry.id = tableData.getIntField(0); - std::string startAnimation(tableData.getStringField(1, "")); - entry.startAnimation = GeneralUtils::ASCIIToUTF16(startAnimation); + std::string startAnimation(tableData.getStringField(1, "")); + entry.startAnimation = GeneralUtils::ASCIIToUTF16(startAnimation); - std::string loopAnimation(tableData.getStringField(2, "")); - entry.loopAnimation = GeneralUtils::ASCIIToUTF16(loopAnimation); + std::string loopAnimation(tableData.getStringField(2, "")); + entry.loopAnimation = GeneralUtils::ASCIIToUTF16(loopAnimation); - std::string stopAnimation(tableData.getStringField(3, "")); - entry.stopAnimation = GeneralUtils::ASCIIToUTF16(stopAnimation); + std::string stopAnimation(tableData.getStringField(3, "")); + entry.stopAnimation = GeneralUtils::ASCIIToUTF16(stopAnimation); - std::string startSound(tableData.getStringField(4, "")); - entry.startSound = GeneralUtils::ASCIIToUTF16(startSound); + std::string startSound(tableData.getStringField(4, "")); + entry.startSound = GeneralUtils::ASCIIToUTF16(startSound); - std::string loopSound(tableData.getStringField(5, "")); - entry.loopSound = GeneralUtils::ASCIIToUTF16(loopSound); + std::string loopSound(tableData.getStringField(5, "")); + entry.loopSound = GeneralUtils::ASCIIToUTF16(loopSound); - std::string stopSound(tableData.getStringField(6, "")); - entry.stopSound = GeneralUtils::ASCIIToUTF16(stopSound); + std::string stopSound(tableData.getStringField(6, "")); + entry.stopSound = GeneralUtils::ASCIIToUTF16(stopSound); - std::string loopEffectString(tableData.getStringField(7, "")); - entry.loopEffectID = EffectPairFromString(loopEffectString); + std::string loopEffectString(tableData.getStringField(7, "")); + entry.loopEffectID = EffectPairFromString(loopEffectString); - entry.preconditions = tableData.getStringField(8, "-1"); + entry.preconditions = tableData.getStringField(8, "-1"); - entry.playerCollision = tableData.getIntField(9, 0); + entry.playerCollision = tableData.getIntField(9, 0); - entry.cameraLocked = tableData.getIntField(10, 0); + entry.cameraLocked = tableData.getIntField(10, 0); - std::string startEffectString(tableData.getStringField(11, "")); - entry.startEffectID = EffectPairFromString(startEffectString); + std::string startEffectString(tableData.getStringField(11, "")); + entry.startEffectID = EffectPairFromString(startEffectString); - std::string stopEffectString(tableData.getStringField(12, "")); - entry.stopEffectID = EffectPairFromString(stopEffectString); + std::string stopEffectString(tableData.getStringField(12, "")); + entry.stopEffectID = EffectPairFromString(stopEffectString); - entry.damageImmune = tableData.getIntField(13, 0); + entry.damageImmune = tableData.getIntField(13, 0); - entry.noAggro = tableData.getIntField(14, 0); + entry.noAggro = tableData.getIntField(14, 0); - entry.showNameBillboard = tableData.getIntField(15, 0); + entry.showNameBillboard = tableData.getIntField(15, 0); - m_Entries.push_back(entry); - tableData.nextRow(); - } + m_Entries.push_back(entry); + tableData.nextRow(); + } - tableData.finalize(); + tableData.finalize(); } CDRailActivatorComponentTable::~CDRailActivatorComponentTable() = default; std::string CDRailActivatorComponentTable::GetName() const { - return "RailActivatorComponent"; + return "RailActivatorComponent"; } CDRailActivatorComponent CDRailActivatorComponentTable::GetEntryByID(int32_t id) const { - for (const auto& entry : m_Entries) { - if (entry.id == id) - return entry; - } + for (const auto& entry : m_Entries) { + if (entry.id == id) + return entry; + } - return {}; + return {}; } std::vector CDRailActivatorComponentTable::GetEntries() const { - return m_Entries; + return m_Entries; } -std::pair CDRailActivatorComponentTable::EffectPairFromString(std::string &str) { - const auto split = GeneralUtils::SplitString(str, ':'); - if (split.size() == 2) { - return { std::stoi(split.at(0)), GeneralUtils::ASCIIToUTF16(split.at(1)) }; - } +std::pair CDRailActivatorComponentTable::EffectPairFromString(std::string& str) { + const auto split = GeneralUtils::SplitString(str, ':'); + if (split.size() == 2) { + return { std::stoi(split.at(0)), GeneralUtils::ASCIIToUTF16(split.at(1)) }; + } - return {}; + return {}; } diff --git a/dDatabase/Tables/CDRailActivatorComponent.h b/dDatabase/Tables/CDRailActivatorComponent.h index 4f06ff5f..b8313e96 100644 --- a/dDatabase/Tables/CDRailActivatorComponent.h +++ b/dDatabase/Tables/CDRailActivatorComponent.h @@ -2,33 +2,33 @@ #include "CDTable.h" struct CDRailActivatorComponent { - int32_t id; - std::u16string startAnimation; - std::u16string loopAnimation; - std::u16string stopAnimation; - std::u16string startSound; - std::u16string loopSound; - std::u16string stopSound; - std::pair startEffectID; - std::pair loopEffectID; - std::pair stopEffectID; - std::string preconditions; - bool playerCollision; - bool cameraLocked; - bool damageImmune; - bool noAggro; - bool showNameBillboard; + int32_t id; + std::u16string startAnimation; + std::u16string loopAnimation; + std::u16string stopAnimation; + std::u16string startSound; + std::u16string loopSound; + std::u16string stopSound; + std::pair startEffectID; + std::pair loopEffectID; + std::pair stopEffectID; + std::string preconditions; + bool playerCollision; + bool cameraLocked; + bool damageImmune; + bool noAggro; + bool showNameBillboard; }; class CDRailActivatorComponentTable : public CDTable { public: - CDRailActivatorComponentTable(); - ~CDRailActivatorComponentTable(); + CDRailActivatorComponentTable(); + ~CDRailActivatorComponentTable(); - std::string GetName() const override; - [[nodiscard]] CDRailActivatorComponent GetEntryByID(int32_t id) const; - [[nodiscard]] std::vector GetEntries() const; + std::string GetName() const override; + [[nodiscard]] CDRailActivatorComponent GetEntryByID(int32_t id) const; + [[nodiscard]] std::vector GetEntries() const; private: - static std::pair EffectPairFromString(std::string& str); - std::vector m_Entries {}; + static std::pair EffectPairFromString(std::string& str); + std::vector m_Entries{}; }; diff --git a/dDatabase/Tables/CDRarityTableTable.cpp b/dDatabase/Tables/CDRarityTableTable.cpp index da41e3f3..67878cd2 100644 --- a/dDatabase/Tables/CDRarityTableTable.cpp +++ b/dDatabase/Tables/CDRarityTableTable.cpp @@ -3,55 +3,55 @@ //! Constructor CDRarityTableTable::CDRarityTableTable(void) { - // First, get the size of the table - unsigned int size = 0; - auto tableSize = CDClientDatabase::ExecuteQuery("SELECT COUNT(*) FROM RarityTable"); - while (!tableSize.eof()) { - size = tableSize.getIntField(0, 0); + // First, get the size of the table + unsigned int size = 0; + auto tableSize = CDClientDatabase::ExecuteQuery("SELECT COUNT(*) FROM RarityTable"); + while (!tableSize.eof()) { + size = tableSize.getIntField(0, 0); + + tableSize.nextRow(); + } - tableSize.nextRow(); - } - tableSize.finalize(); - - // Reserve the size - this->entries.reserve(size); - // Now get the data - auto tableData = CDClientDatabase::ExecuteQuery("SELECT * FROM RarityTable"); - while (!tableData.eof()) { - CDRarityTable entry; - entry.id = tableData.getIntField(0, -1); - entry.randmax = tableData.getFloatField(1, -1); - entry.rarity = tableData.getIntField(2, -1); - entry.RarityTableIndex = tableData.getIntField(3, -1); + // Reserve the size + this->entries.reserve(size); - this->entries.push_back(entry); - tableData.nextRow(); - } + // Now get the data + auto tableData = CDClientDatabase::ExecuteQuery("SELECT * FROM RarityTable"); + while (!tableData.eof()) { + CDRarityTable entry; + entry.id = tableData.getIntField(0, -1); + entry.randmax = tableData.getFloatField(1, -1); + entry.rarity = tableData.getIntField(2, -1); + entry.RarityTableIndex = tableData.getIntField(3, -1); + + this->entries.push_back(entry); + tableData.nextRow(); + } tableData.finalize(); } //! Destructor -CDRarityTableTable::~CDRarityTableTable(void) { } +CDRarityTableTable::~CDRarityTableTable(void) {} //! Returns the table's name std::string CDRarityTableTable::GetName(void) const { - return "RarityTable"; + return "RarityTable"; } //! Queries the table with a custom "where" clause std::vector CDRarityTableTable::Query(std::function predicate) { - std::vector data = cpplinq::from(this->entries) - >> cpplinq::where(predicate) - >> cpplinq::to_vector(); + std::vector data = cpplinq::from(this->entries) + >> cpplinq::where(predicate) + >> cpplinq::to_vector(); - return data; + return data; } //! Gets all the entries in the table const std::vector& CDRarityTableTable::GetEntries(void) const { - return this->entries; + return this->entries; } diff --git a/dDatabase/Tables/CDRarityTableTable.h b/dDatabase/Tables/CDRarityTableTable.h index 0a57e903..55cfec4b 100644 --- a/dDatabase/Tables/CDRarityTableTable.h +++ b/dDatabase/Tables/CDRarityTableTable.h @@ -10,63 +10,59 @@ //! RarityTable Entry Struct struct CDRarityTable { - unsigned int id; - float randmax; - unsigned int rarity; - unsigned int RarityTableIndex; + unsigned int id; + float randmax; + unsigned int rarity; + unsigned int RarityTableIndex; - friend bool operator> (const CDRarityTable& c1, const CDRarityTable& c2) - { - return c1.rarity > c2.rarity; - } + friend bool operator> (const CDRarityTable& c1, const CDRarityTable& c2) { + return c1.rarity > c2.rarity; + } - friend bool operator>= (const CDRarityTable& c1, const CDRarityTable& c2) - { - return c1.rarity >= c2.rarity; - } + friend bool operator>= (const CDRarityTable& c1, const CDRarityTable& c2) { + return c1.rarity >= c2.rarity; + } - friend bool operator< (const CDRarityTable& c1, const CDRarityTable& c2) - { - return c1.rarity < c2.rarity; - } + friend bool operator< (const CDRarityTable& c1, const CDRarityTable& c2) { + return c1.rarity < c2.rarity; + } - friend bool operator<= (const CDRarityTable& c1, const CDRarityTable& c2) - { - return c1.rarity <= c2.rarity; - } + friend bool operator<= (const CDRarityTable& c1, const CDRarityTable& c2) { + return c1.rarity <= c2.rarity; + } }; //! RarityTable table class CDRarityTableTable : public CDTable { private: - std::vector entries; + std::vector entries; public: - //! Constructor - CDRarityTableTable(void); + //! Constructor + CDRarityTableTable(void); - //! Destructor - ~CDRarityTableTable(void); + //! Destructor + ~CDRarityTableTable(void); - //! Returns the table's name - /*! - \return The table name - */ - std::string GetName(void) const override; + //! Returns the table's name + /*! + \return The table name + */ + std::string GetName(void) const override; - //! Queries the table with a custom "where" clause - /*! - \param predicate The predicate - */ - std::vector Query(std::function predicate); + //! Queries the table with a custom "where" clause + /*! + \param predicate The predicate + */ + std::vector Query(std::function predicate); - //! Gets all the entries in the table - /*! - \return The entries - */ - const std::vector& GetEntries(void) const; + //! Gets all the entries in the table + /*! + \return The entries + */ + const std::vector& GetEntries(void) const; }; diff --git a/dDatabase/Tables/CDRebuildComponentTable.cpp b/dDatabase/Tables/CDRebuildComponentTable.cpp index a1b5646c..c4299b98 100644 --- a/dDatabase/Tables/CDRebuildComponentTable.cpp +++ b/dDatabase/Tables/CDRebuildComponentTable.cpp @@ -2,62 +2,62 @@ //! Constructor CDRebuildComponentTable::CDRebuildComponentTable(void) { - - // First, get the size of the table - unsigned int size = 0; - auto tableSize = CDClientDatabase::ExecuteQuery("SELECT COUNT(*) FROM RebuildComponent"); - while (!tableSize.eof()) { - size = tableSize.getIntField(0, 0); - - tableSize.nextRow(); - } - + + // First, get the size of the table + unsigned int size = 0; + auto tableSize = CDClientDatabase::ExecuteQuery("SELECT COUNT(*) FROM RebuildComponent"); + while (!tableSize.eof()) { + size = tableSize.getIntField(0, 0); + + tableSize.nextRow(); + } + tableSize.finalize(); - - // Reserve the size - this->entries.reserve(size); - - // Now get the data - auto tableData = CDClientDatabase::ExecuteQuery("SELECT * FROM RebuildComponent"); - while (!tableData.eof()) { - CDRebuildComponent entry; - entry.id = tableData.getIntField(0, -1); - entry.reset_time = tableData.getFloatField(1, -1.0f); - entry.complete_time = tableData.getFloatField(2, -1.0f); - entry.take_imagination = tableData.getIntField(3, -1); - entry.interruptible = tableData.getIntField(4, -1) == 1 ? true : false; - entry.self_activator = tableData.getIntField(5, -1) == 1 ? true : false; - entry.custom_modules = tableData.getStringField(6, ""); - entry.activityID = tableData.getIntField(7, -1); - entry.post_imagination_cost = tableData.getIntField(8, -1); - entry.time_before_smash = tableData.getFloatField(9, -1.0f); - - this->entries.push_back(entry); - tableData.nextRow(); - } + + // Reserve the size + this->entries.reserve(size); + + // Now get the data + auto tableData = CDClientDatabase::ExecuteQuery("SELECT * FROM RebuildComponent"); + while (!tableData.eof()) { + CDRebuildComponent entry; + entry.id = tableData.getIntField(0, -1); + entry.reset_time = tableData.getFloatField(1, -1.0f); + entry.complete_time = tableData.getFloatField(2, -1.0f); + entry.take_imagination = tableData.getIntField(3, -1); + entry.interruptible = tableData.getIntField(4, -1) == 1 ? true : false; + entry.self_activator = tableData.getIntField(5, -1) == 1 ? true : false; + entry.custom_modules = tableData.getStringField(6, ""); + entry.activityID = tableData.getIntField(7, -1); + entry.post_imagination_cost = tableData.getIntField(8, -1); + entry.time_before_smash = tableData.getFloatField(9, -1.0f); + + this->entries.push_back(entry); + tableData.nextRow(); + } tableData.finalize(); } //! Destructor -CDRebuildComponentTable::~CDRebuildComponentTable(void) { } +CDRebuildComponentTable::~CDRebuildComponentTable(void) {} //! Returns the table's name std::string CDRebuildComponentTable::GetName(void) const { - return "RebuildComponent"; + return "RebuildComponent"; } //! Queries the table with a custom "where" clause std::vector CDRebuildComponentTable::Query(std::function predicate) { - - std::vector data = cpplinq::from(this->entries) - >> cpplinq::where(predicate) - >> cpplinq::to_vector(); - - return data; + + std::vector data = cpplinq::from(this->entries) + >> cpplinq::where(predicate) + >> cpplinq::to_vector(); + + return data; } //! Gets all the entries in the table std::vector CDRebuildComponentTable::GetEntries(void) const { - return this->entries; + return this->entries; } diff --git a/dDatabase/Tables/CDRebuildComponentTable.h b/dDatabase/Tables/CDRebuildComponentTable.h index 49d2e44f..bdc2da8a 100644 --- a/dDatabase/Tables/CDRebuildComponentTable.h +++ b/dDatabase/Tables/CDRebuildComponentTable.h @@ -8,50 +8,50 @@ \brief Contains data for the RebuildComponent table */ -//! RebuildComponent Struct + //! RebuildComponent Struct struct CDRebuildComponent { - unsigned int id; //!< The component Id - float reset_time; //!< The reset time - float complete_time; //!< The complete time - unsigned int take_imagination; //!< The amount of imagination it costs - bool interruptible; //!< Whether or not the rebuild is interruptible - bool self_activator; //!< Whether or not the rebuild is a rebuild activator itself - std::string custom_modules; //!< The custom modules - unsigned int activityID; //!< The activity ID - unsigned int post_imagination_cost; //!< The post imagination cost - float time_before_smash; //!< The time before smash + unsigned int id; //!< The component Id + float reset_time; //!< The reset time + float complete_time; //!< The complete time + unsigned int take_imagination; //!< The amount of imagination it costs + bool interruptible; //!< Whether or not the rebuild is interruptible + bool self_activator; //!< Whether or not the rebuild is a rebuild activator itself + std::string custom_modules; //!< The custom modules + unsigned int activityID; //!< The activity ID + unsigned int post_imagination_cost; //!< The post imagination cost + float time_before_smash; //!< The time before smash }; //! ObjectSkills table class CDRebuildComponentTable : public CDTable { private: - std::vector entries; - + std::vector entries; + public: - - //! Constructor - CDRebuildComponentTable(void); - - //! Destructor - ~CDRebuildComponentTable(void); - - //! Returns the table's name - /*! - \return The table name - */ - std::string GetName(void) const override; - - //! Queries the table with a custom "where" clause - /*! - \param predicate The predicate - */ - std::vector Query(std::function predicate); - - //! Gets all the entries in the table - /*! - \return The entries - */ - std::vector GetEntries(void) const; - + + //! Constructor + CDRebuildComponentTable(void); + + //! Destructor + ~CDRebuildComponentTable(void); + + //! Returns the table's name + /*! + \return The table name + */ + std::string GetName(void) const override; + + //! Queries the table with a custom "where" clause + /*! + \param predicate The predicate + */ + std::vector Query(std::function predicate); + + //! Gets all the entries in the table + /*! + \return The entries + */ + std::vector GetEntries(void) const; + }; diff --git a/dDatabase/Tables/CDRewardsTable.cpp b/dDatabase/Tables/CDRewardsTable.cpp index 2f7d1778..99d56f26 100644 --- a/dDatabase/Tables/CDRewardsTable.cpp +++ b/dDatabase/Tables/CDRewardsTable.cpp @@ -1,10 +1,10 @@ #include "CDRewardsTable.h" CDRewardsTable::CDRewardsTable(void) { - auto tableData = CDClientDatabase::ExecuteQuery("SELECT * FROM Rewards"); - while (!tableData.eof()) { + auto tableData = CDClientDatabase::ExecuteQuery("SELECT * FROM Rewards"); + while (!tableData.eof()) { CDRewards* entry = new CDRewards(); - entry->id = tableData.getIntField(0, -1); + entry->id = tableData.getIntField(0, -1); entry->levelID = tableData.getIntField(1, -1); entry->missionID = tableData.getIntField(2, -1); entry->rewardType = tableData.getIntField(3, -1); @@ -12,29 +12,29 @@ CDRewardsTable::CDRewardsTable(void) { entry->count = tableData.getIntField(5, -1); m_entries.insert(std::make_pair(entry->id, entry)); - tableData.nextRow(); - } + tableData.nextRow(); + } tableData.finalize(); } CDRewardsTable::~CDRewardsTable(void) { - for (auto e : m_entries) { - if (e.second) delete e.second; - } - - m_entries.clear(); + for (auto e : m_entries) { + if (e.second) delete e.second; + } + + m_entries.clear(); } std::string CDRewardsTable::GetName(void) const { - return "Rewards"; + return "Rewards"; } std::vector CDRewardsTable::GetByLevelID(uint32_t levelID) { - std::vector result {}; - for (const auto& e : m_entries) { + std::vector result{}; + for (const auto& e : m_entries) { if (e.second->levelID == levelID) result.push_back(e.second); - } - - return result; + } + + return result; } diff --git a/dDatabase/Tables/CDRewardsTable.h b/dDatabase/Tables/CDRewardsTable.h index c4f9fb70..2edfd2b3 100644 --- a/dDatabase/Tables/CDRewardsTable.h +++ b/dDatabase/Tables/CDRewardsTable.h @@ -13,12 +13,12 @@ struct CDRewards { class CDRewardsTable : public CDTable { public: - CDRewardsTable(void); - ~CDRewardsTable(void); - - std::string GetName(void) const override; + CDRewardsTable(void); + ~CDRewardsTable(void); + + std::string GetName(void) const override; std::vector GetByLevelID(uint32_t levelID); private: std::map m_entries; -}; \ No newline at end of file +}; diff --git a/dDatabase/Tables/CDScriptComponentTable.cpp b/dDatabase/Tables/CDScriptComponentTable.cpp index 11ab75ee..b34f96f1 100644 --- a/dDatabase/Tables/CDScriptComponentTable.cpp +++ b/dDatabase/Tables/CDScriptComponentTable.cpp @@ -2,39 +2,39 @@ //! Constructor CDScriptComponentTable::CDScriptComponentTable(void) { - - // First, get the size of the table - unsigned int size = 0; - auto tableSize = CDClientDatabase::ExecuteQuery("SELECT COUNT(*) FROM ScriptComponent"); - while (!tableSize.eof()) { - size = tableSize.getIntField(0, 0); - - tableSize.nextRow(); - } - + + // First, get the size of the table + unsigned int size = 0; + auto tableSize = CDClientDatabase::ExecuteQuery("SELECT COUNT(*) FROM ScriptComponent"); + while (!tableSize.eof()) { + size = tableSize.getIntField(0, 0); + + tableSize.nextRow(); + } + tableSize.finalize(); - - // Now get the data - auto tableData = CDClientDatabase::ExecuteQuery("SELECT * FROM ScriptComponent"); - while (!tableData.eof()) { - CDScriptComponent entry; - entry.id = tableData.getIntField(0, -1); - entry.script_name = tableData.getStringField(1, ""); - entry.client_script_name = tableData.getStringField(2, ""); - + + // Now get the data + auto tableData = CDClientDatabase::ExecuteQuery("SELECT * FROM ScriptComponent"); + while (!tableData.eof()) { + CDScriptComponent entry; + entry.id = tableData.getIntField(0, -1); + entry.script_name = tableData.getStringField(1, ""); + entry.client_script_name = tableData.getStringField(2, ""); + this->entries.insert(std::make_pair(entry.id, entry)); - tableData.nextRow(); - } + tableData.nextRow(); + } tableData.finalize(); } //! Destructor -CDScriptComponentTable::~CDScriptComponentTable(void) { } +CDScriptComponentTable::~CDScriptComponentTable(void) {} //! Returns the table's name std::string CDScriptComponentTable::GetName(void) const { - return "ScriptComponent"; + return "ScriptComponent"; } const CDScriptComponent& CDScriptComponentTable::GetByID(unsigned int id) { @@ -44,4 +44,4 @@ const CDScriptComponent& CDScriptComponentTable::GetByID(unsigned int id) { } return m_ToReturnWhenNoneFound; -} \ No newline at end of file +} diff --git a/dDatabase/Tables/CDScriptComponentTable.h b/dDatabase/Tables/CDScriptComponentTable.h index 7fc802fa..92534cc0 100644 --- a/dDatabase/Tables/CDScriptComponentTable.h +++ b/dDatabase/Tables/CDScriptComponentTable.h @@ -8,39 +8,39 @@ \brief Contains data for the ScriptComponent table */ -//! ScriptComponent Struct + //! ScriptComponent Struct struct CDScriptComponent { - unsigned int id; //!< The component ID - std::string script_name; //!< The script name - std::string client_script_name; //!< The client script name + unsigned int id; //!< The component ID + std::string script_name; //!< The script name + std::string client_script_name; //!< The client script name }; //! ObjectSkills table class CDScriptComponentTable : public CDTable { private: - std::map entries; + std::map entries; CDScriptComponent m_ToReturnWhenNoneFound; - + public: //! Gets an entry by ID const CDScriptComponent& GetByID(unsigned int id); - - //! Constructor - CDScriptComponentTable(void); - - //! Destructor - ~CDScriptComponentTable(void); - - //! Returns the table's name - /*! - \return The table name - */ - std::string GetName(void) const override; - - //! Queries the table with a custom "where" clause - /*! - \param predicate The predicate - */ - + + //! Constructor + CDScriptComponentTable(void); + + //! Destructor + ~CDScriptComponentTable(void); + + //! Returns the table's name + /*! + \return The table name + */ + std::string GetName(void) const override; + + //! Queries the table with a custom "where" clause + /*! + \param predicate The predicate + */ + }; diff --git a/dDatabase/Tables/CDSkillBehaviorTable.cpp b/dDatabase/Tables/CDSkillBehaviorTable.cpp index 88124161..e3986578 100644 --- a/dDatabase/Tables/CDSkillBehaviorTable.cpp +++ b/dDatabase/Tables/CDSkillBehaviorTable.cpp @@ -3,82 +3,82 @@ //! Constructor CDSkillBehaviorTable::CDSkillBehaviorTable(void) { - m_empty = CDSkillBehavior(); + m_empty = CDSkillBehavior(); - // First, get the size of the table - unsigned int size = 0; - auto tableSize = CDClientDatabase::ExecuteQuery("SELECT COUNT(*) FROM SkillBehavior"); - while (!tableSize.eof()) { - size = tableSize.getIntField(0, 0); + // First, get the size of the table + unsigned int size = 0; + auto tableSize = CDClientDatabase::ExecuteQuery("SELECT COUNT(*) FROM SkillBehavior"); + while (!tableSize.eof()) { + size = tableSize.getIntField(0, 0); - tableSize.nextRow(); - } + tableSize.nextRow(); + } tableSize.finalize(); - // Reserve the size - //this->entries.reserve(size); + // Reserve the size + //this->entries.reserve(size); - // Now get the data - auto tableData = CDClientDatabase::ExecuteQuery("SELECT * FROM SkillBehavior"); - while (!tableData.eof()) { - CDSkillBehavior entry; - entry.skillID = tableData.getIntField(0, -1); - UNUSED(entry.locStatus = tableData.getIntField(1, -1)); - entry.behaviorID = tableData.getIntField(2, -1); - entry.imaginationcost = tableData.getIntField(3, -1); - entry.cooldowngroup = tableData.getIntField(4, -1); - entry.cooldown = tableData.getFloatField(5, -1.0f); - UNUSED(entry.isNpcEditor = tableData.getIntField(6, -1) == 1 ? true : false); - UNUSED(entry.skillIcon = tableData.getIntField(7, -1)); - UNUSED(entry.oomSkillID = tableData.getStringField(8, "")); - UNUSED(entry.oomBehaviorEffectID = tableData.getIntField(9, -1)); - UNUSED(entry.castTypeDesc = tableData.getIntField(10, -1)); - UNUSED(entry.imBonusUI = tableData.getIntField(11, -1)); - UNUSED(entry.lifeBonusUI = tableData.getIntField(12, -1)); - UNUSED(entry.armorBonusUI = tableData.getIntField(13, -1)); - UNUSED(entry.damageUI = tableData.getIntField(14, -1)); - UNUSED(entry.hideIcon = tableData.getIntField(15, -1) == 1 ? true : false); - UNUSED(entry.localize = tableData.getIntField(16, -1) == 1 ? true : false); - UNUSED(entry.gate_version = tableData.getStringField(17, "")); - UNUSED(entry.cancelType = tableData.getIntField(18, -1)); + // Now get the data + auto tableData = CDClientDatabase::ExecuteQuery("SELECT * FROM SkillBehavior"); + while (!tableData.eof()) { + CDSkillBehavior entry; + entry.skillID = tableData.getIntField(0, -1); + UNUSED(entry.locStatus = tableData.getIntField(1, -1)); + entry.behaviorID = tableData.getIntField(2, -1); + entry.imaginationcost = tableData.getIntField(3, -1); + entry.cooldowngroup = tableData.getIntField(4, -1); + entry.cooldown = tableData.getFloatField(5, -1.0f); + UNUSED(entry.isNpcEditor = tableData.getIntField(6, -1) == 1 ? true : false); + UNUSED(entry.skillIcon = tableData.getIntField(7, -1)); + UNUSED(entry.oomSkillID = tableData.getStringField(8, "")); + UNUSED(entry.oomBehaviorEffectID = tableData.getIntField(9, -1)); + UNUSED(entry.castTypeDesc = tableData.getIntField(10, -1)); + UNUSED(entry.imBonusUI = tableData.getIntField(11, -1)); + UNUSED(entry.lifeBonusUI = tableData.getIntField(12, -1)); + UNUSED(entry.armorBonusUI = tableData.getIntField(13, -1)); + UNUSED(entry.damageUI = tableData.getIntField(14, -1)); + UNUSED(entry.hideIcon = tableData.getIntField(15, -1) == 1 ? true : false); + UNUSED(entry.localize = tableData.getIntField(16, -1) == 1 ? true : false); + UNUSED(entry.gate_version = tableData.getStringField(17, "")); + UNUSED(entry.cancelType = tableData.getIntField(18, -1)); - this->entries.insert(std::make_pair(entry.skillID, entry)); - //this->entries.push_back(entry); - tableData.nextRow(); - } + this->entries.insert(std::make_pair(entry.skillID, entry)); + //this->entries.push_back(entry); + tableData.nextRow(); + } tableData.finalize(); } //! Destructor -CDSkillBehaviorTable::~CDSkillBehaviorTable(void) { } +CDSkillBehaviorTable::~CDSkillBehaviorTable(void) {} //! Returns the table's name std::string CDSkillBehaviorTable::GetName(void) const { - return "SkillBehavior"; + return "SkillBehavior"; } //! Queries the table with a custom "where" clause std::vector CDSkillBehaviorTable::Query(std::function predicate) { - /*std::vector data = cpplinq::from(this->entries) - >> cpplinq::where(predicate) - >> cpplinq::to_vector(); + /*std::vector data = cpplinq::from(this->entries) + >> cpplinq::where(predicate) + >> cpplinq::to_vector(); - return data;*/ + return data;*/ - //Logger::LogDebug("CDSkillBehaviorTable", "The 'Query' function is no longer working! Please use GetSkillByID instead!"); + //Logger::LogDebug("CDSkillBehaviorTable", "The 'Query' function is no longer working! Please use GetSkillByID instead!"); std::vector data; //So MSVC shuts up return data; } //! Gets an entry by ID const CDSkillBehavior& CDSkillBehaviorTable::GetSkillByID(unsigned int skillID) { - std::map::iterator it = this->entries.find(skillID); - if (it != this->entries.end()) { - return it->second; - } + std::map::iterator it = this->entries.find(skillID); + if (it != this->entries.end()) { + return it->second; + } - return m_empty; + return m_empty; } diff --git a/dDatabase/Tables/CDSkillBehaviorTable.h b/dDatabase/Tables/CDSkillBehaviorTable.h index d70dca56..da8676db 100644 --- a/dDatabase/Tables/CDSkillBehaviorTable.h +++ b/dDatabase/Tables/CDSkillBehaviorTable.h @@ -8,56 +8,56 @@ \brief Contains data for the SkillBehavior table */ -//! ZoneTable Struct + //! ZoneTable Struct struct CDSkillBehavior { - unsigned int skillID; //!< The Skill ID of the skill - UNUSED(unsigned int locStatus); //!< ?? - unsigned int behaviorID; //!< The Behavior ID of the skill - unsigned int imaginationcost; //!< The imagination cost of the skill - unsigned int cooldowngroup; //!< The cooldown group ID of the skill - float cooldown; //!< The cooldown time of the skill - UNUSED(bool isNpcEditor); //!< ??? - UNUSED(unsigned int skillIcon); //!< The Skill Icon ID - UNUSED(std::string oomSkillID); //!< ??? - UNUSED(unsigned int oomBehaviorEffectID); //!< ??? - UNUSED(unsigned int castTypeDesc); //!< The cast type description(?) - UNUSED(unsigned int imBonusUI); //!< The imagination bonus of the skill - UNUSED(nsigned int lifeBonusUI); //!< The life bonus of the skill - UNUSED(unsigned int armorBonusUI); //!< The armor bonus of the skill - UNUSED(unsigned int damageUI); //!< ??? - UNUSED(bool hideIcon); //!< Whether or not to show the icon - UNUSED(bool localize); //!< ??? - UNUSED(std::string gate_version); //!< ??? - UNUSED(unsigned int cancelType); //!< The cancel type (?) + unsigned int skillID; //!< The Skill ID of the skill + UNUSED(unsigned int locStatus); //!< ?? + unsigned int behaviorID; //!< The Behavior ID of the skill + unsigned int imaginationcost; //!< The imagination cost of the skill + unsigned int cooldowngroup; //!< The cooldown group ID of the skill + float cooldown; //!< The cooldown time of the skill + UNUSED(bool isNpcEditor); //!< ??? + UNUSED(unsigned int skillIcon); //!< The Skill Icon ID + UNUSED(std::string oomSkillID); //!< ??? + UNUSED(unsigned int oomBehaviorEffectID); //!< ??? + UNUSED(unsigned int castTypeDesc); //!< The cast type description(?) + UNUSED(unsigned int imBonusUI); //!< The imagination bonus of the skill + UNUSED(nsigned int lifeBonusUI); //!< The life bonus of the skill + UNUSED(unsigned int armorBonusUI); //!< The armor bonus of the skill + UNUSED(unsigned int damageUI); //!< ??? + UNUSED(bool hideIcon); //!< Whether or not to show the icon + UNUSED(bool localize); //!< ??? + UNUSED(std::string gate_version); //!< ??? + UNUSED(unsigned int cancelType); //!< The cancel type (?) }; //! SkillBehavior table class CDSkillBehaviorTable : public CDTable { private: - std::map entries; - CDSkillBehavior m_empty; + std::map entries; + CDSkillBehavior m_empty; public: - //! Constructor - CDSkillBehaviorTable(void); + //! Constructor + CDSkillBehaviorTable(void); - //! Destructor - ~CDSkillBehaviorTable(void); + //! Destructor + ~CDSkillBehaviorTable(void); - //! Returns the table's name - /*! - \return The table name - */ - std::string GetName(void) const override; + //! Returns the table's name + /*! + \return The table name + */ + std::string GetName(void) const override; - //! Queries the table with a custom "where" clause - /*! - \param predicate The predicate - */ - std::vector Query(std::function predicate); + //! Queries the table with a custom "where" clause + /*! + \param predicate The predicate + */ + std::vector Query(std::function predicate); - //! Gets an entry by ID - const CDSkillBehavior& GetSkillByID(unsigned int skillID); + //! Gets an entry by ID + const CDSkillBehavior& GetSkillByID(unsigned int skillID); }; diff --git a/dDatabase/Tables/CDTable.h b/dDatabase/Tables/CDTable.h index ec056e8e..cd05782d 100644 --- a/dDatabase/Tables/CDTable.h +++ b/dDatabase/Tables/CDTable.h @@ -13,7 +13,7 @@ #ifdef _WIN32 #define NOMINMAX // windows.h has min and max macros that breaks cpplinq -#endif +#endif #include "cpplinq.hpp" #pragma warning (disable : 4244) //Disable double to float conversion warnings @@ -29,13 +29,13 @@ typedef __int64_t __int64; \brief A virtual class for CDClient Tables */ -//! The base class for all CD tables + //! The base class for all CD tables class CDTable { public: - - //! Returns the table's name - /*! - \return The table name - */ - virtual std::string GetName() const = 0; + + //! Returns the table's name + /*! + \return The table name + */ + virtual std::string GetName() const = 0; }; diff --git a/dDatabase/Tables/CDVendorComponentTable.cpp b/dDatabase/Tables/CDVendorComponentTable.cpp index e096e85a..f1dd96db 100644 --- a/dDatabase/Tables/CDVendorComponentTable.cpp +++ b/dDatabase/Tables/CDVendorComponentTable.cpp @@ -11,9 +11,9 @@ CDVendorComponentTable::CDVendorComponentTable(void) { tableSize.nextRow(); } - + tableSize.finalize(); - + // Reserve the size this->entries.reserve(size); @@ -35,7 +35,7 @@ CDVendorComponentTable::CDVendorComponentTable(void) { } //! Destructor -CDVendorComponentTable::~CDVendorComponentTable(void) { } +CDVendorComponentTable::~CDVendorComponentTable(void) {} //! Returns the table's name std::string CDVendorComponentTable::GetName(void) const { diff --git a/dDatabase/Tables/CDZoneTableTable.cpp b/dDatabase/Tables/CDZoneTableTable.cpp index 7cd8d0d8..e172f79a 100644 --- a/dDatabase/Tables/CDZoneTableTable.cpp +++ b/dDatabase/Tables/CDZoneTableTable.cpp @@ -2,73 +2,72 @@ //! Constructor CDZoneTableTable::CDZoneTableTable(void) { - - // First, get the size of the table - unsigned int size = 0; - auto tableSize = CDClientDatabase::ExecuteQuery("SELECT COUNT(*) FROM ZoneTable"); - while (!tableSize.eof()) { - size = tableSize.getIntField(0, 0); - - tableSize.nextRow(); - } - + + // First, get the size of the table + unsigned int size = 0; + auto tableSize = CDClientDatabase::ExecuteQuery("SELECT COUNT(*) FROM ZoneTable"); + while (!tableSize.eof()) { + size = tableSize.getIntField(0, 0); + + tableSize.nextRow(); + } + tableSize.finalize(); - - // Now get the data - auto tableData = CDClientDatabase::ExecuteQuery("SELECT * FROM ZoneTable"); - while (!tableData.eof()) { - CDZoneTable entry; - entry.zoneID = tableData.getIntField(0, -1); - entry.locStatus = tableData.getIntField(1, -1); - entry.zoneName = tableData.getStringField(2, ""); - entry.scriptID = tableData.getIntField(3, -1); - entry.ghostdistance_min = tableData.getFloatField(4, -1.0f); - entry.ghostdistance = tableData.getFloatField(5, -1.0f); - entry.population_soft_cap = tableData.getIntField(6, -1); - entry.population_hard_cap = tableData.getIntField(7, -1); - UNUSED(entry.DisplayDescription = tableData.getStringField(8, "")); - UNUSED(entry.mapFolder = tableData.getStringField(9, "")); - entry.smashableMinDistance = tableData.getFloatField(10, -1.0f); - entry.smashableMaxDistance = tableData.getFloatField(11, -1.0f); - UNUSED(entry.mixerProgram = tableData.getStringField(12, "")); - UNUSED(entry.clientPhysicsFramerate = tableData.getStringField(13, "")); - UNUSED(entry.serverPhysicsFramerate = tableData.getStringField(14, "")); - entry.zoneControlTemplate = tableData.getIntField(15, -1); - entry.widthInChunks = tableData.getIntField(16, -1); - entry.heightInChunks = tableData.getIntField(17, -1); - entry.petsAllowed = tableData.getIntField(18, -1) == 1 ? true : false; - entry.localize = tableData.getIntField(19, -1) == 1 ? true : false; - entry.fZoneWeight = tableData.getFloatField(20, -1.0f); - UNUSED(entry.thumbnail = tableData.getStringField(21, "")); - entry.PlayerLoseCoinsOnDeath = tableData.getIntField(22, -1) == 1 ? true : false; - UNUSED(entry.disableSaveLoc = tableData.getIntField(23, -1) == 1 ? true : false); - entry.teamRadius = tableData.getFloatField(24, -1.0f); - UNUSED(entry.gate_version = tableData.getStringField(25, "")); - UNUSED(entry.mountsAllowed = tableData.getIntField(26, -1) == 1 ? true : false); - + + // Now get the data + auto tableData = CDClientDatabase::ExecuteQuery("SELECT * FROM ZoneTable"); + while (!tableData.eof()) { + CDZoneTable entry; + entry.zoneID = tableData.getIntField(0, -1); + entry.locStatus = tableData.getIntField(1, -1); + entry.zoneName = tableData.getStringField(2, ""); + entry.scriptID = tableData.getIntField(3, -1); + entry.ghostdistance_min = tableData.getFloatField(4, -1.0f); + entry.ghostdistance = tableData.getFloatField(5, -1.0f); + entry.population_soft_cap = tableData.getIntField(6, -1); + entry.population_hard_cap = tableData.getIntField(7, -1); + UNUSED(entry.DisplayDescription = tableData.getStringField(8, "")); + UNUSED(entry.mapFolder = tableData.getStringField(9, "")); + entry.smashableMinDistance = tableData.getFloatField(10, -1.0f); + entry.smashableMaxDistance = tableData.getFloatField(11, -1.0f); + UNUSED(entry.mixerProgram = tableData.getStringField(12, "")); + UNUSED(entry.clientPhysicsFramerate = tableData.getStringField(13, "")); + UNUSED(entry.serverPhysicsFramerate = tableData.getStringField(14, "")); + entry.zoneControlTemplate = tableData.getIntField(15, -1); + entry.widthInChunks = tableData.getIntField(16, -1); + entry.heightInChunks = tableData.getIntField(17, -1); + entry.petsAllowed = tableData.getIntField(18, -1) == 1 ? true : false; + entry.localize = tableData.getIntField(19, -1) == 1 ? true : false; + entry.fZoneWeight = tableData.getFloatField(20, -1.0f); + UNUSED(entry.thumbnail = tableData.getStringField(21, "")); + entry.PlayerLoseCoinsOnDeath = tableData.getIntField(22, -1) == 1 ? true : false; + UNUSED(entry.disableSaveLoc = tableData.getIntField(23, -1) == 1 ? true : false); + entry.teamRadius = tableData.getFloatField(24, -1.0f); + UNUSED(entry.gate_version = tableData.getStringField(25, "")); + UNUSED(entry.mountsAllowed = tableData.getIntField(26, -1) == 1 ? true : false); + this->m_Entries.insert(std::make_pair(entry.zoneID, entry)); - tableData.nextRow(); - } + tableData.nextRow(); + } tableData.finalize(); } //! Destructor -CDZoneTableTable::~CDZoneTableTable(void) { } +CDZoneTableTable::~CDZoneTableTable(void) {} //! Returns the table's name std::string CDZoneTableTable::GetName(void) const { - return "ZoneTable"; + return "ZoneTable"; } //! Queries the table with a zoneID to find. const CDZoneTable* CDZoneTableTable::Query(unsigned int zoneID) { - const auto& iter = m_Entries.find(zoneID); + const auto& iter = m_Entries.find(zoneID); - if (iter != m_Entries.end()) - { - return &iter->second; - } + if (iter != m_Entries.end()) { + return &iter->second; + } return nullptr; -} \ No newline at end of file +} diff --git a/dDatabase/Tables/CDZoneTableTable.h b/dDatabase/Tables/CDZoneTableTable.h index f99febc8..c115a38a 100644 --- a/dDatabase/Tables/CDZoneTableTable.h +++ b/dDatabase/Tables/CDZoneTableTable.h @@ -8,59 +8,59 @@ \brief Contains data for the ZoneTable table */ -//! ZoneTable Struct + //! ZoneTable Struct struct CDZoneTable { - unsigned int zoneID; //!< The Zone ID of the object - unsigned int locStatus; //!< The Locale Status(?) - std::string zoneName; //!< The name of the zone - unsigned int scriptID; //!< The Script ID of the zone (ScriptsTable) - float ghostdistance_min; //!< The minimum ghosting distance - float ghostdistance; //!< The ghosting distance - unsigned int population_soft_cap; //!< The "soft cap" on the world population - unsigned int population_hard_cap; //!< The "hard cap" on the world population - UNUSED(std::string DisplayDescription); //!< The display description of the world - UNUSED(std::string mapFolder); //!< ??? - float smashableMinDistance; //!< The minimum smashable distance? - float smashableMaxDistance; //!< The maximum smashable distance? - UNUSED(std::string mixerProgram); //!< ??? - UNUSED(std::string clientPhysicsFramerate); //!< The client physics framerate - UNUSED(std::string serverPhysicsFramerate); //!< The server physics framerate - unsigned int zoneControlTemplate; //!< The Zone Control template - unsigned int widthInChunks; //!< The width of the world in chunks - unsigned int heightInChunks; //!< The height of the world in chunks - bool petsAllowed; //!< Whether or not pets are allowed in the world + unsigned int zoneID; //!< The Zone ID of the object + unsigned int locStatus; //!< The Locale Status(?) + std::string zoneName; //!< The name of the zone + unsigned int scriptID; //!< The Script ID of the zone (ScriptsTable) + float ghostdistance_min; //!< The minimum ghosting distance + float ghostdistance; //!< The ghosting distance + unsigned int population_soft_cap; //!< The "soft cap" on the world population + unsigned int population_hard_cap; //!< The "hard cap" on the world population + UNUSED(std::string DisplayDescription); //!< The display description of the world + UNUSED(std::string mapFolder); //!< ??? + float smashableMinDistance; //!< The minimum smashable distance? + float smashableMaxDistance; //!< The maximum smashable distance? + UNUSED(std::string mixerProgram); //!< ??? + UNUSED(std::string clientPhysicsFramerate); //!< The client physics framerate + UNUSED(std::string serverPhysicsFramerate); //!< The server physics framerate + unsigned int zoneControlTemplate; //!< The Zone Control template + unsigned int widthInChunks; //!< The width of the world in chunks + unsigned int heightInChunks; //!< The height of the world in chunks + bool petsAllowed; //!< Whether or not pets are allowed in the world bool localize; //!< Whether or not the world should be localized - float fZoneWeight; //!< ??? - UNUSED(std::string thumbnail); //!< The thumbnail of the world - bool PlayerLoseCoinsOnDeath; //!< Whether or not the user loses coins on death - UNUSED(bool disableSaveLoc); //!< Disables the saving location? + float fZoneWeight; //!< ??? + UNUSED(std::string thumbnail); //!< The thumbnail of the world + bool PlayerLoseCoinsOnDeath; //!< Whether or not the user loses coins on death + UNUSED(bool disableSaveLoc); //!< Disables the saving location? float teamRadius; //!< ??? - UNUSED(std::string gate_version); //!< The gate version - UNUSED(bool mountsAllowed); //!< Whether or not mounts are allowed + UNUSED(std::string gate_version); //!< The gate version + UNUSED(bool mountsAllowed); //!< Whether or not mounts are allowed }; //! ZoneTable table class CDZoneTableTable : public CDTable { private: std::map m_Entries; - + public: - - //! Constructor - CDZoneTableTable(void); - - //! Destructor - ~CDZoneTableTable(void); - - //! Returns the table's name - /*! - \return The table name - */ - std::string GetName(void) const override; - - //! Queries the table with a zoneID to find. - /*! - \param id The zoneID - */ - const CDZoneTable* Query(unsigned int zoneID); -}; \ No newline at end of file + + //! Constructor + CDZoneTableTable(void); + + //! Destructor + ~CDZoneTableTable(void); + + //! Returns the table's name + /*! + \return The table name + */ + std::string GetName(void) const override; + + //! Queries the table with a zoneID to find. + /*! + \param id The zoneID + */ + const CDZoneTable* Query(unsigned int zoneID); +}; diff --git a/dGame/Character.cpp b/dGame/Character.cpp index d92f8345..0b92f0aa 100644 --- a/dGame/Character.cpp +++ b/dGame/Character.cpp @@ -18,7 +18,7 @@ Character::Character(uint32_t id, User* parentUser) { //First load the name, etc: - m_ID = id; + m_ID = id; sql::PreparedStatement* stmt = Database::CreatePreppedStmt( "SELECT name, pending_name, needs_rename, prop_clone_id, permission_map FROM charinfo WHERE id=? LIMIT 1;" @@ -65,21 +65,20 @@ Character::Character(uint32_t id, User* parentUser) { //Set our objectID: m_ObjectID = m_ID; - m_ObjectID = GeneralUtils::SetBit(m_ObjectID, OBJECT_BIT_CHARACTER); - m_ObjectID = GeneralUtils::SetBit(m_ObjectID, OBJECT_BIT_PERSISTENT); + m_ObjectID = GeneralUtils::SetBit(m_ObjectID, OBJECT_BIT_CHARACTER); + m_ObjectID = GeneralUtils::SetBit(m_ObjectID, OBJECT_BIT_PERSISTENT); - m_ParentUser = parentUser; + m_ParentUser = parentUser; m_OurEntity = nullptr; m_BuildMode = false; } Character::~Character() { delete m_Doc; - m_Doc = nullptr; + m_Doc = nullptr; } -void Character::UpdateFromDatabase() -{ +void Character::UpdateFromDatabase() { sql::PreparedStatement* stmt = Database::CreatePreppedStmt( "SELECT name, pending_name, needs_rename, prop_clone_id, permission_map FROM charinfo WHERE id=? LIMIT 1;" ); @@ -125,8 +124,8 @@ void Character::UpdateFromDatabase() //Set our objectID: m_ObjectID = m_ID; - m_ObjectID = GeneralUtils::SetBit(m_ObjectID, OBJECT_BIT_CHARACTER); - m_ObjectID = GeneralUtils::SetBit(m_ObjectID, OBJECT_BIT_PERSISTENT); + m_ObjectID = GeneralUtils::SetBit(m_ObjectID, OBJECT_BIT_CHARACTER); + m_ObjectID = GeneralUtils::SetBit(m_ObjectID, OBJECT_BIT_PERSISTENT); m_OurEntity = nullptr; m_BuildMode = false; @@ -136,14 +135,14 @@ void Character::DoQuickXMLDataParse() { if (m_XMLData.size() == 0) return; delete m_Doc; - m_Doc = new tinyxml2::XMLDocument(); - if (!m_Doc) return; + m_Doc = new tinyxml2::XMLDocument(); + if (!m_Doc) return; if (m_Doc->Parse(m_XMLData.c_str(), m_XMLData.size()) == 0) { Game::logger->Log("Character", "Loaded xmlData for character %s (%i)!", m_Name.c_str(), m_ID); } else { Game::logger->Log("Character", "Failed to load xmlData!"); - //Server::rakServer->CloseConnection(m_ParentUser->GetSystemAddress(), true); + //Server::rakServer->CloseConnection(m_ParentUser->GetSystemAddress(), true); return; } @@ -179,8 +178,7 @@ void Character::DoQuickXMLDataParse() { return; } - while (bag != nullptr) - { + while (bag != nullptr) { auto* sib = bag->FirstChildElement(); while (sib != nullptr) { @@ -201,9 +199,9 @@ void Character::DoQuickXMLDataParse() { tinyxml2::XMLElement* character = m_Doc->FirstChildElement("obj")->FirstChildElement("char"); - if (character) { + if (character) { character->QueryAttribute("cc", &m_Coins); - character->QueryAttribute("gm", &m_GMLevel); + character->QueryAttribute("gm", &m_GMLevel); uint64_t lzidConcat = 0; if (character->FindAttribute("lzid")) { @@ -221,9 +219,9 @@ void Character::DoQuickXMLDataParse() { } if (character->FindAttribute("lnzid")) { - uint32_t lastNonInstanceZoneID = 0; - character->QueryAttribute("lnzid", &lastNonInstanceZoneID); - m_LastNonInstanceZoneID = lastNonInstanceZoneID; + uint32_t lastNonInstanceZoneID = 0; + character->QueryAttribute("lnzid", &lastNonInstanceZoneID); + m_LastNonInstanceZoneID = lastNonInstanceZoneID; } if (character->FindAttribute("tscene")) { @@ -260,33 +258,31 @@ void Character::DoQuickXMLDataParse() { character->QueryAttribute("lzry", &m_OriginalRotation.y); character->QueryAttribute("lzrz", &m_OriginalRotation.z); character->QueryAttribute("lzrw", &m_OriginalRotation.w); - } + } - auto* flags = m_Doc->FirstChildElement("obj")->FirstChildElement("flag"); - if (flags) { - auto* currentChild = flags->FirstChildElement(); - while (currentChild) { - uint32_t index = 0; - uint64_t value = 0; - const auto* temp = currentChild->Attribute("v"); + auto* flags = m_Doc->FirstChildElement("obj")->FirstChildElement("flag"); + if (flags) { + auto* currentChild = flags->FirstChildElement(); + while (currentChild) { + uint32_t index = 0; + uint64_t value = 0; + const auto* temp = currentChild->Attribute("v"); index = std::stoul(currentChild->Attribute("id")); - value = std::stoull(temp); + value = std::stoull(temp); - m_PlayerFlags.insert(std::make_pair(index, value)); - currentChild = currentChild->NextSiblingElement(); - } - } + m_PlayerFlags.insert(std::make_pair(index, value)); + currentChild = currentChild->NextSiblingElement(); + } + } } -void Character::UnlockEmote(int emoteID) -{ +void Character::UnlockEmote(int emoteID) { m_UnlockedEmotes.push_back(emoteID); GameMessages::SendSetEmoteLockState(EntityManager::Instance()->GetEntity(m_ObjectID), false, emoteID); } -void Character::SetBuildMode(bool buildMode) -{ +void Character::SetBuildMode(bool buildMode) { m_BuildMode = buildMode; auto* controller = dZoneManager::Instance()->GetZoneControlObject(); @@ -295,14 +291,14 @@ void Character::SetBuildMode(bool buildMode) } void Character::SaveXMLToDatabase() { - if (!m_Doc) return; + if (!m_Doc) return; - //For metrics, we'll record the time it took to save: - auto start = std::chrono::system_clock::now(); + //For metrics, we'll record the time it took to save: + auto start = std::chrono::system_clock::now(); - tinyxml2::XMLElement* character = m_Doc->FirstChildElement("obj")->FirstChildElement("char"); - if (character) { - character->SetAttribute("gm", m_GMLevel); + tinyxml2::XMLElement* character = m_Doc->FirstChildElement("obj")->FirstChildElement("char"); + if (character) { + character->SetAttribute("gm", m_GMLevel); character->SetAttribute("cc", m_Coins); // lzid garbage, binary concat of zoneID, zoneInstance and zoneClone @@ -333,31 +329,31 @@ void Character::SaveXMLToDatabase() { } character->LinkEndChild(emotes); - } + } - //Export our flags: - auto* flags = m_Doc->FirstChildElement("obj")->FirstChildElement("flag"); + //Export our flags: + auto* flags = m_Doc->FirstChildElement("obj")->FirstChildElement("flag"); if (!flags) { flags = m_Doc->NewElement("flag"); //Create a flags tag if we don't have one m_Doc->FirstChildElement("obj")->LinkEndChild(flags); //Link it to the obj tag so we can find next time } - flags->DeleteChildren(); //Clear it if we have anything, so that we can fill it up again without dupes - for (std::pair flag : m_PlayerFlags) { - auto* f = m_Doc->NewElement("f"); - f->SetAttribute("id", flag.first); + flags->DeleteChildren(); //Clear it if we have anything, so that we can fill it up again without dupes + for (std::pair flag : m_PlayerFlags) { + auto* f = m_Doc->NewElement("f"); + f->SetAttribute("id", flag.first); - //Because of the joy that is tinyxml2, it doesn't offer a function to set a uint64 as an attribute. - //Only signed 64-bits ints would work. - std::string v = std::to_string(flag.second); - f->SetAttribute("v", v.c_str()); + //Because of the joy that is tinyxml2, it doesn't offer a function to set a uint64 as an attribute. + //Only signed 64-bits ints would work. + std::string v = std::to_string(flag.second); + f->SetAttribute("v", v.c_str()); flags->LinkEndChild(f); } SaveXmlRespawnCheckpoints(); - //Call upon the entity to update our xmlDoc: + //Call upon the entity to update our xmlDoc: if (!m_OurEntity) { Game::logger->Log("Character", "We didn't have an entity set while saving! CHARACTER WILL NOT BE SAVED!"); return; @@ -365,22 +361,22 @@ void Character::SaveXMLToDatabase() { m_OurEntity->UpdateXMLDoc(m_Doc); - //Dump our xml into m_XMLData: - auto* printer = new tinyxml2::XMLPrinter(0, true, 0); - m_Doc->Print(printer); - m_XMLData = printer->CStr(); + //Dump our xml into m_XMLData: + auto* printer = new tinyxml2::XMLPrinter(0, true, 0); + m_Doc->Print(printer); + m_XMLData = printer->CStr(); - //Finally, save to db: + //Finally, save to db: sql::PreparedStatement* stmt = Database::CreatePreppedStmt("UPDATE charxml SET xml_data=? WHERE id=?"); - stmt->setString(1, m_XMLData.c_str()); - stmt->setUInt(2, m_ID); - stmt->execute(); - delete stmt; + stmt->setString(1, m_XMLData.c_str()); + stmt->setUInt(2, m_ID); + stmt->execute(); + delete stmt; - //For metrics, log the time it took to save: - auto end = std::chrono::system_clock::now(); - std::chrono::duration elapsed = end - start; - Game::logger->Log("Character", "Saved character to Database in: %fs", elapsed.count()); + //For metrics, log the time it took to save: + auto end = std::chrono::system_clock::now(); + std::chrono::duration elapsed = end - start; + Game::logger->Log("Character", "Saved character to Database in: %fs", elapsed.count()); delete printer; } @@ -389,51 +385,47 @@ void Character::SetPlayerFlag(const uint32_t flagId, const bool value) { // If the flag is already set, we don't have to recalculate it if (GetPlayerFlag(flagId) == value) return; - if (value) - { + if (value) { // Update the mission component: auto* player = EntityManager::Instance()->GetEntity(m_ObjectID); - if (player != nullptr) - { + if (player != nullptr) { auto* missionComponent = player->GetComponent(); - if (missionComponent != nullptr) - { + if (missionComponent != nullptr) { missionComponent->Progress(MissionTaskType::MISSION_TASK_TYPE_PLAYER_FLAG, flagId); } } } - // Calculate the index first - auto flagIndex = uint32_t(std::floor(flagId / 64)); + // Calculate the index first + auto flagIndex = uint32_t(std::floor(flagId / 64)); - const auto shiftedValue = 1ULL << flagId % 64; + const auto shiftedValue = 1ULL << flagId % 64; - auto it = m_PlayerFlags.find(flagIndex); + auto it = m_PlayerFlags.find(flagIndex); // Check if flag index exists - if (it != m_PlayerFlags.end()) - { - // Update the value - if (value) { - it->second |= shiftedValue; - } else { - it->second &= ~shiftedValue; - } - } else { - if (value) { - // Otherwise, insert the value - uint64_t flagValue = 0; + if (it != m_PlayerFlags.end()) { + // Update the value + if (value) { + it->second |= shiftedValue; + } else { + it->second &= ~shiftedValue; + } + } else { + if (value) { + // Otherwise, insert the value + uint64_t flagValue = 0; flagValue |= shiftedValue; - m_PlayerFlags.insert(std::make_pair(flagIndex, flagValue)); - } - } + m_PlayerFlags.insert(std::make_pair(flagIndex, flagValue)); + } + } - // Notify the client that a flag has changed server-side - GameMessages::SendNotifyClientFlagChange(m_ObjectID, flagId, value, m_ParentUser->GetSystemAddress()); + // Notify the client that a flag has changed server-side + GameMessages::SendNotifyClientFlagChange(m_ObjectID, flagId, value, m_ParentUser->GetSystemAddress()); } bool Character::GetPlayerFlag(const uint32_t flagId) const { @@ -458,40 +450,37 @@ void Character::SetRetroactiveFlags() { } } -void Character::SaveXmlRespawnCheckpoints() -{ - //Export our respawn points: - auto* points = m_Doc->FirstChildElement("obj")->FirstChildElement("res"); +void Character::SaveXmlRespawnCheckpoints() { + //Export our respawn points: + auto* points = m_Doc->FirstChildElement("obj")->FirstChildElement("res"); if (!points) { points = m_Doc->NewElement("res"); m_Doc->FirstChildElement("obj")->LinkEndChild(points); } - points->DeleteChildren(); - for (const auto& point : m_WorldRespawnCheckpoints) { - auto* r = m_Doc->NewElement("r"); - r->SetAttribute("w", point.first); + points->DeleteChildren(); + for (const auto& point : m_WorldRespawnCheckpoints) { + auto* r = m_Doc->NewElement("r"); + r->SetAttribute("w", point.first); - r->SetAttribute("x", point.second.x); - r->SetAttribute("y", point.second.y); - r->SetAttribute("z", point.second.z); + r->SetAttribute("x", point.second.x); + r->SetAttribute("y", point.second.y); + r->SetAttribute("z", point.second.z); points->LinkEndChild(r); } } -void Character::LoadXmlRespawnCheckpoints() -{ +void Character::LoadXmlRespawnCheckpoints() { m_WorldRespawnCheckpoints.clear(); - auto* points = m_Doc->FirstChildElement("obj")->FirstChildElement("res"); + auto* points = m_Doc->FirstChildElement("obj")->FirstChildElement("res"); if (!points) { return; } auto* r = points->FirstChildElement("r"); - while (r != nullptr) - { + while (r != nullptr) { int32_t map = 0; NiPoint3 point = NiPoint3::ZERO; @@ -507,8 +496,7 @@ void Character::LoadXmlRespawnCheckpoints() } -void Character::OnZoneLoad() -{ +void Character::OnZoneLoad() { if (m_OurEntity == nullptr) { return; } @@ -550,23 +538,19 @@ void Character::OnZoneLoad() } } -PermissionMap Character::GetPermissionMap() const -{ +PermissionMap Character::GetPermissionMap() const { return m_PermissionMap; } -bool Character::HasPermission(PermissionMap permission) const -{ +bool Character::HasPermission(PermissionMap permission) const { return (static_cast(m_PermissionMap) & static_cast(permission)) != 0; } -void Character::SetRespawnPoint(LWOMAPID map, const NiPoint3& point) -{ +void Character::SetRespawnPoint(LWOMAPID map, const NiPoint3& point) { m_WorldRespawnCheckpoints[map] = point; } -const NiPoint3& Character::GetRespawnPoint(LWOMAPID map) const -{ +const NiPoint3& Character::GetRespawnPoint(LWOMAPID map) const { const auto& pair = m_WorldRespawnCheckpoints.find(map); if (pair == m_WorldRespawnCheckpoints.end()) return NiPoint3::ZERO; @@ -575,8 +559,7 @@ const NiPoint3& Character::GetRespawnPoint(LWOMAPID map) const } void Character::SetCoins(int64_t newCoins, eLootSourceType lootSource) { - if (newCoins < 0) - { + if (newCoins < 0) { newCoins = 0; } @@ -585,22 +568,19 @@ void Character::SetCoins(int64_t newCoins, eLootSourceType lootSource) { GameMessages::SendSetCurrency(EntityManager::Instance()->GetEntity(m_ObjectID), m_Coins, 0, 0, 0, 0, true, lootSource); } -bool Character::HasBeenToWorld(LWOMAPID mapID) const -{ +bool Character::HasBeenToWorld(LWOMAPID mapID) const { return m_WorldRespawnCheckpoints.find(mapID) != m_WorldRespawnCheckpoints.end(); } -void Character::SendMuteNotice() const -{ +void Character::SendMuteNotice() const { if (!m_ParentUser->GetIsMuted()) return; time_t expire = m_ParentUser->GetMuteExpire(); char buffer[32] = "brought up for review.\0"; - if (expire != 1) - { - std::tm * ptm = std::localtime(&expire); + if (expire != 1) { + std::tm* ptm = std::localtime(&expire); // Format: Mo, 15.06.2009 20:20:00 std::strftime(buffer, 32, "%a, %d.%m.%Y %H:%M:%S", ptm); } diff --git a/dGame/Character.h b/dGame/Character.h index 9678eb3d..1a1d4cd0 100644 --- a/dGame/Character.h +++ b/dGame/Character.h @@ -23,344 +23,344 @@ public: Character(uint32_t id, User* parentUser); ~Character(); - void SaveXMLToDatabase(); - void UpdateFromDatabase(); + void SaveXMLToDatabase(); + void UpdateFromDatabase(); - void SaveXmlRespawnCheckpoints(); - void LoadXmlRespawnCheckpoints(); + void SaveXmlRespawnCheckpoints(); + void LoadXmlRespawnCheckpoints(); - const std::string& GetXMLData() const { return m_XMLData; } - tinyxml2::XMLDocument* GetXMLDoc() const { return m_Doc; } + const std::string& GetXMLData() const { return m_XMLData; } + tinyxml2::XMLDocument* GetXMLDoc() const { return m_Doc; } - /** - * Gets the database ID of the character - * @return the database ID of the character - */ + /** + * Gets the database ID of the character + * @return the database ID of the character + */ uint32_t GetID() const { return m_ID; } - /** - * Gets the (custom) name of the character - * @return the name of the character - */ + /** + * Gets the (custom) name of the character + * @return the name of the character + */ const std::string& GetName() const { return m_Name; } - /** - * Gets the generated name of the character - * @return the generated name - */ + /** + * Gets the generated name of the character + * @return the generated name + */ const std::string& GetUnapprovedName() const { return m_UnapprovedName; } - /** - * Gets whether or not the custom name for this character was rejected - * @return whether the custom name for this character was rejected - */ + /** + * Gets whether or not the custom name for this character was rejected + * @return whether the custom name for this character was rejected + */ bool GetNameRejected() const { return m_NameRejected; } - /** - * Gets the object ID of the entity this character belongs to - * @return the object ID of the entity this character belongs to - */ + /** + * Gets the object ID of the entity this character belongs to + * @return the object ID of the entity this character belongs to + */ LWOOBJID GetObjectID() const { return m_ObjectID; } - /** - * Gets the identifier for the properties of this character - * @return The identifier for the properties of this character - */ + /** + * Gets the identifier for the properties of this character + * @return The identifier for the properties of this character + */ uint32_t GetPropertyCloneID() const { return m_PropertyCloneID; } - /** - * Gets the last login of this character in MS - * @return the last login of this character - */ + /** + * Gets the last login of this character in MS + * @return the last login of this character + */ uint64_t GetLastLogin() const { return m_LastLogin; } - - /** - * Gets the default shirt color for this character - * @return the default shirt color ID - */ - uint32_t GetShirtColor() const { return m_ShirtColor; } - /** - * Gets the default hair style for this character - * @return the default hair style ID - */ - uint32_t GetShirtStyle() const { return m_ShirtStyle; } + /** + * Gets the default shirt color for this character + * @return the default shirt color ID + */ + uint32_t GetShirtColor() const { return m_ShirtColor; } - /** - * Gets the default pants color for this character - * @return the default pants color ID - */ - uint32_t GetPantsColor() const { return m_PantsColor; } + /** + * Gets the default hair style for this character + * @return the default hair style ID + */ + uint32_t GetShirtStyle() const { return m_ShirtStyle; } - /** - * Gets the default hair color for this character - * @return the default hair color ID - */ - uint32_t GetHairColor() const { return m_HairColor; } + /** + * Gets the default pants color for this character + * @return the default pants color ID + */ + uint32_t GetPantsColor() const { return m_PantsColor; } - /** - * Gets the default hair style of this character - * @return the default hair style ID - */ - uint32_t GetHairStyle() const { return m_HairStyle; } + /** + * Gets the default hair color for this character + * @return the default hair color ID + */ + uint32_t GetHairColor() const { return m_HairColor; } - /** - * Gets the eyes config for this character - * @return the eyes config ID - */ - uint32_t GetEyes() const { return m_Eyes; } + /** + * Gets the default hair style of this character + * @return the default hair style ID + */ + uint32_t GetHairStyle() const { return m_HairStyle; } - /** - * Gets the eyebrows config for this character - * @return the eyebrow config ID - */ - uint32_t GetEyebrows() const { return m_Eyebrows; } + /** + * Gets the eyes config for this character + * @return the eyes config ID + */ + uint32_t GetEyes() const { return m_Eyes; } - /** - * Get the mouth of this character - * @return the mouth ID - */ - uint32_t GetMouth() const { return m_Mouth; } + /** + * Gets the eyebrows config for this character + * @return the eyebrow config ID + */ + uint32_t GetEyebrows() const { return m_Eyebrows; } - /** - * Gets the left hand color of this character - * @return the left hand color ID - */ - uint32_t GetLeftHand() const { return m_LeftHand; } + /** + * Get the mouth of this character + * @return the mouth ID + */ + uint32_t GetMouth() const { return m_Mouth; } - /** - * Gets the right hand color of this character - * @return the right hand color ID - */ - uint32_t GetRightHand() const { return m_RightHand; } + /** + * Gets the left hand color of this character + * @return the left hand color ID + */ + uint32_t GetLeftHand() const { return m_LeftHand; } - /** - * Sets the default shirt color for this character - * @param color the shirt color ID to set - */ - void SetShirtColor(uint32_t color) { m_ShirtColor = color; } + /** + * Gets the right hand color of this character + * @return the right hand color ID + */ + uint32_t GetRightHand() const { return m_RightHand; } - /** - * Sets the default shirt style for this character - * @param style the shirt style ID to set - */ - void SetShirtStyle(uint32_t style) { m_ShirtStyle = style; } + /** + * Sets the default shirt color for this character + * @param color the shirt color ID to set + */ + void SetShirtColor(uint32_t color) { m_ShirtColor = color; } - /** - * Sets the default pants color for this character - * @param color the pants color ID to set - */ - void SetPantsColor(uint32_t color) { m_PantsColor = color; } + /** + * Sets the default shirt style for this character + * @param style the shirt style ID to set + */ + void SetShirtStyle(uint32_t style) { m_ShirtStyle = style; } - /** - * Sets the default hair color for this character - * @param color the hair color ID to set - */ - void SetHairColor(uint32_t color) { m_HairColor = color; } + /** + * Sets the default pants color for this character + * @param color the pants color ID to set + */ + void SetPantsColor(uint32_t color) { m_PantsColor = color; } - /** - * Sets the default hair style for this character - * @param style the hair style ID to set - */ - void SetHairStyle(uint32_t style) { m_HairStyle = style; } + /** + * Sets the default hair color for this character + * @param color the hair color ID to set + */ + void SetHairColor(uint32_t color) { m_HairColor = color; } - /** - * Sets the eyes config for this character - * @param eyes the eyes config ID to set - */ - void SetEyes(uint32_t eyes) { m_Eyes = eyes; } + /** + * Sets the default hair style for this character + * @param style the hair style ID to set + */ + void SetHairStyle(uint32_t style) { m_HairStyle = style; } - /** - * Sets the eyebrows config for this character - * @param eyebrows the eyebrows config ID to set - */ - void SetEyebrows(uint32_t eyebrows) { m_Eyebrows = eyebrows; } + /** + * Sets the eyes config for this character + * @param eyes the eyes config ID to set + */ + void SetEyes(uint32_t eyes) { m_Eyes = eyes; } - /** - * Sets the mouth config for this character - * @param mouth the mouth config ID to set - */ - void SetMouth(uint32_t mouth) { m_Mouth = mouth; } + /** + * Sets the eyebrows config for this character + * @param eyebrows the eyebrows config ID to set + */ + void SetEyebrows(uint32_t eyebrows) { m_Eyebrows = eyebrows; } - /** - * Sets the left hand color for this character - * @param color the left hand color ID to set - */ - void SetLeftHand(uint32_t leftHand) { m_LeftHand = leftHand; } + /** + * Sets the mouth config for this character + * @param mouth the mouth config ID to set + */ + void SetMouth(uint32_t mouth) { m_Mouth = mouth; } - /** - * Sets the right hand color for this character - * @param color the right hand color ID to set - */ - void SetRightHand(uint32_t rightHand) { m_RightHand = rightHand; } + /** + * Sets the left hand color for this character + * @param color the left hand color ID to set + */ + void SetLeftHand(uint32_t leftHand) { m_LeftHand = leftHand; } + + /** + * Sets the right hand color for this character + * @param color the right hand color ID to set + */ + void SetRightHand(uint32_t rightHand) { m_RightHand = rightHand; } - /** - * Whether this character has visited a certain zone - * @param mapID the ID of the zone to check for - * @return Whether the character has visited the provided zone - */ + /** + * Whether this character has visited a certain zone + * @param mapID the ID of the zone to check for + * @return Whether the character has visited the provided zone + */ bool HasBeenToWorld(LWOMAPID mapID) const; - /** - * Gets the zone ID the character is currently in - * @return the zone ID the character is currently in - */ + /** + * Gets the zone ID the character is currently in + * @return the zone ID the character is currently in + */ uint32_t GetZoneID() const { return m_ZoneID; } - /** - * Sets the zone ID the character is currently in - * @param id the zone ID to set - */ - void SetZoneID(uint32_t id) { m_ZoneID = id; } + /** + * Sets the zone ID the character is currently in + * @param id the zone ID to set + */ + void SetZoneID(uint32_t id) { m_ZoneID = id; } - /** - * Gets the instance ID of the zone the character is currently in, for boss battles - * @return the instance ID of the zone the character is in - */ + /** + * Gets the instance ID of the zone the character is currently in, for boss battles + * @return the instance ID of the zone the character is in + */ uint32_t GetZoneInstance() const { return m_ZoneInstanceID; } - /** - * Sets the zone instance ID the character is currently in - * @param instance the instance ID of the zone - */ - void SetZoneInstance(uint32_t instance) { m_ZoneInstanceID = instance; } + /** + * Sets the zone instance ID the character is currently in + * @param instance the instance ID of the zone + */ + void SetZoneInstance(uint32_t instance) { m_ZoneInstanceID = instance; } - /** - * Gets the clone ID of the zone the character is currently in, for properties - * @return the clone ID of the zone the character is in - */ + /** + * Gets the clone ID of the zone the character is currently in, for properties + * @return the clone ID of the zone the character is in + */ uint32_t GetZoneClone() const { return m_ZoneCloneID; } - /** - * Sets the clone ID of the zone the character is currently in - * @param clone the clone ID of the zone - */ - void SetZoneClone(uint32_t clone) { m_ZoneCloneID = clone; } + /** + * Sets the clone ID of the zone the character is currently in + * @param clone the clone ID of the zone + */ + void SetZoneClone(uint32_t clone) { m_ZoneCloneID = clone; } - /** - * Gets the last zone the character was in, that was not an instance (=boss battle), to be able to send them back - * @return the zone ID of the last non-instance zone this character was in - */ + /** + * Gets the last zone the character was in, that was not an instance (=boss battle), to be able to send them back + * @return the zone ID of the last non-instance zone this character was in + */ uint32_t GetLastNonInstanceZoneID() const { return m_LastNonInstanceZoneID; } - /** - * Sets the last non instance zone ID for the character - * @param id the zone ID - */ - void SetLastNonInstanceZoneID(uint32_t id) { m_LastNonInstanceZoneID = id; } + /** + * Sets the last non instance zone ID for the character + * @param id the zone ID + */ + void SetLastNonInstanceZoneID(uint32_t id) { m_LastNonInstanceZoneID = id; } - /** - * Gets the name of the scene that will play when the character lands in the next zone - * @return the name of the landing scene - */ + /** + * Gets the name of the scene that will play when the character lands in the next zone + * @return the name of the landing scene + */ const std::string& GetTargetScene() const { return m_TargetScene; } - /** - * Sets the name of the landing scene that will play when the player lands in the new zone - * NOTE: Generally set by launch pads before heading off to the next zone - * @param value the name of the landing scene to set - */ - void SetTargetScene(const std::string& value) { m_TargetScene = value; } + /** + * Sets the name of the landing scene that will play when the player lands in the new zone + * NOTE: Generally set by launch pads before heading off to the next zone + * @param value the name of the landing scene to set + */ + void SetTargetScene(const std::string& value) { m_TargetScene = value; } - /** - * Gets the starting position of the character (at spawn) - * @return the starting position of the character - */ + /** + * Gets the starting position of the character (at spawn) + * @return the starting position of the character + */ const NiPoint3& GetOriginalPos() const { return m_OriginalPosition; } - /** - * Gets the starting rotation of the character (at spawn) - * @return the starting rotation of the character - */ + /** + * Gets the starting rotation of the character (at spawn) + * @return the starting rotation of the character + */ const NiQuaternion& GetOriginalRot() const { return m_OriginalRotation; } - /** - * Gets the respawn point of the the character for a certain map - * @param map the map ID to get the respawn point for - * @return the respawn point of the character on the given map - */ - const NiPoint3& GetRespawnPoint(LWOMAPID map) const; + /** + * Gets the respawn point of the the character for a certain map + * @param map the map ID to get the respawn point for + * @return the respawn point of the character on the given map + */ + const NiPoint3& GetRespawnPoint(LWOMAPID map) const; - /** - * Sets the respawn point of this character for a given map - * @param map the map to set the respawn point for - * @param point the point to set as respawn point on the given map - */ + /** + * Sets the respawn point of this character for a given map + * @param map the map to set the respawn point for + * @param point the point to set as respawn point on the given map + */ void SetRespawnPoint(LWOMAPID map, const NiPoint3& point); - /** - * Gets the GM level of the character - * @return the GM level - */ + /** + * Gets the GM level of the character + * @return the GM level + */ int32_t GetGMLevel() const { return m_GMLevel; } - /** - * Sets the GM level of the character - * @param value the GM level to set - */ - void SetGMLevel(uint8_t value) { m_GMLevel = value; } + /** + * Sets the GM level of the character + * @param value the GM level to set + */ + void SetGMLevel(uint8_t value) { m_GMLevel = value; } - /** - * Gets the current amount of coins of the character - * @return the current amount of coins - */ + /** + * Gets the current amount of coins of the character + * @return the current amount of coins + */ const int64_t GetCoins() const { return m_Coins; } - /** - * Updates the current amount of coins of the character by a specified amount - * @param newCoins the amount of coins to update by - * @param coinSource The source of the loot - */ - void SetCoins(int64_t newCoins, eLootSourceType coinSource); + /** + * Updates the current amount of coins of the character by a specified amount + * @param newCoins the amount of coins to update by + * @param coinSource The source of the loot + */ + void SetCoins(int64_t newCoins, eLootSourceType coinSource); - /** - * Get the entity this character belongs to - * @return the entity this character belongs to - */ + /** + * Get the entity this character belongs to + * @return the entity this character belongs to + */ Entity* GetEntity() const { return m_OurEntity; } - /** - * Sets the entity this character belongs to - * @param entity the entity this character belongs to - */ + /** + * Sets the entity this character belongs to + * @param entity the entity this character belongs to + */ void SetEntity(Entity* entity) { m_OurEntity = entity; } - /** - * Gets the current build mode of the character (on or off) - * @return the current build mode of the character - */ + /** + * Gets the current build mode of the character (on or off) + * @return the current build mode of the character + */ bool GetBuildMode() const { return m_BuildMode; } - /** - * Sets the current build mode for the character (either on or off) - * @param buildMode the build mode to set - */ + /** + * Sets the current build mode for the character (either on or off) + * @param buildMode the build mode to set + */ void SetBuildMode(bool buildMode); - /** - * Gets the title of an announcement that a character made (reserved for GMs) - * @return the title of the announcement a character made - */ + /** + * Gets the title of an announcement that a character made (reserved for GMs) + * @return the title of the announcement a character made + */ const std::string& GetAnnouncementTitle() const { return m_AnnouncementTitle; } - /** - * Sets the title of an announcement a character will make (reserved for GMs) - * @param value the title to set - */ + /** + * Sets the title of an announcement a character will make (reserved for GMs) + * @param value the title to set + */ void SetAnnouncementTitle(const std::string& value) { m_AnnouncementTitle = value; } - /** - * Gets the body of an announcement a character made (reserved for GMs) - * @return the body of the announcement - */ + /** + * Gets the body of an announcement a character made (reserved for GMs) + * @return the body of the announcement + */ const std::string& GetAnnouncementMessage() const { return m_AnnouncementMessage; } - /** - * Sets the body of an annoucement to make (reserved for GMs) - * @param value the body of the announcement - */ + /** + * Sets the body of an annoucement to make (reserved for GMs) + * @param value the body of the announcement + */ void SetAnnouncementMessage(const std::string& value) { m_AnnouncementMessage = value; } /** @@ -368,29 +368,29 @@ public: */ void OnZoneLoad(); - /** - * Gets the permissions of the character, determining what actions a character may do - * @return the permissions for this character - */ + /** + * Gets the permissions of the character, determining what actions a character may do + * @return the permissions for this character + */ PermissionMap GetPermissionMap() const; - /** - * Check if this character has a certain permission - * @param permission the ID of the permission to check for - * @return whether the character has the specified permission - */ + /** + * Check if this character has a certain permission + * @param permission the ID of the permission to check for + * @return whether the character has the specified permission + */ bool HasPermission(PermissionMap permission) const; - /** - * Gets all the emotes this character has unlocked so far - * @return the emotes this character has unlocked - */ + /** + * Gets all the emotes this character has unlocked so far + * @return the emotes this character has unlocked + */ const std::vector& GetUnlockedEmotes() const { return m_UnlockedEmotes; } - /** - * Unlocks an emote, adding it to the unlocked list, also updates the state for the client - * @param emoteID the ID of the emote to unlock - */ + /** + * Unlocks an emote, adding it to the unlocked list, also updates the state for the client + * @param emoteID the ID of the emote to unlock + */ void UnlockEmote(int emoteID); /** @@ -399,13 +399,13 @@ public: * @param flagId the ID of the flag to set * @param value the value to set for the flag */ - void SetPlayerFlag(uint32_t flagId, bool value); + void SetPlayerFlag(uint32_t flagId, bool value); - /** - * Gets the value for a certain character flag - * @param flagId the ID of the flag to get a value for - * @return the value of the flag given the ID (the default is false, obviously) - */ + /** + * Gets the value for a certain character flag + * @param flagId the ID of the flag to get a value for + * @return the value of the flag given the ID (the default is false, obviously) + */ bool GetPlayerFlag(uint32_t flagId) const; /** @@ -413,18 +413,18 @@ public: */ void SendMuteNotice() const; - /** - * Sets any flags that are meant to have been set that may not have been set due to them being - * missing in a previous patch. - */ - void SetRetroactiveFlags(); - - /** - * Get the equipped items for this character, only used for character creation - * @return the equipped items for this character on world load - */ + /** + * Sets any flags that are meant to have been set that may not have been set due to them being + * missing in a previous patch. + */ + void SetRetroactiveFlags(); + + /** + * Get the equipped items for this character, only used for character creation + * @return the equipped items for this character on world load + */ const std::vector& GetEquippedItems() const { return m_EquippedItems; } - + private: /** * The ID of this character. First 32 bits of the ObjectID. @@ -448,7 +448,7 @@ private: /** * 0-9, the Game Master level of this character. - * + * * @see eGameMasterLevel */ int32_t m_GMLevel; @@ -458,34 +458,34 @@ private: */ PermissionMap m_PermissionMap; - /** - * The default name of this character - */ + /** + * The default name of this character + */ std::string m_Name; - /** - * The custom name of the character - */ + /** + * The custom name of the character + */ std::string m_UnapprovedName; - /** - * Whether the custom name of this character is rejected - */ + /** + * Whether the custom name of this character is rejected + */ bool m_NameRejected; - /** - * The current amount of coins of this character - */ + /** + * The current amount of coins of this character + */ int64_t m_Coins; - /** - * Whether the character is building - */ + /** + * Whether the character is building + */ bool m_BuildMode; - /** - * The items equipped by the character on world load - */ + /** + * The items equipped by the character on world load + */ std::vector m_EquippedItems; /** @@ -493,126 +493,126 @@ private: */ uint32_t m_ShirtColor = 0; - /** - * The default shirt style of the character - */ + /** + * The default shirt style of the character + */ uint32_t m_ShirtStyle = 0; - /** - * The default pants color of the character - */ + /** + * The default pants color of the character + */ uint32_t m_PantsColor = 1; - /** - * The default hair color of the character - */ + /** + * The default hair color of the character + */ uint32_t m_HairColor = 0; - /** - * The default hair style of the character - */ + /** + * The default hair style of the character + */ uint32_t m_HairStyle = 0; - /** - * The eyes style of the character - */ + /** + * The eyes style of the character + */ uint32_t m_Eyes = 1; - /** - * The eyebrow style of the character - */ + /** + * The eyebrow style of the character + */ uint32_t m_Eyebrows = 33; - /** - * The mouth style of the character - */ + /** + * The mouth style of the character + */ uint32_t m_Mouth = 8; - /* - * The left hand ID of the character - * NOTE: This might just be client stack garbage. - */ + /* + * The left hand ID of the character + * NOTE: This might just be client stack garbage. + */ uint32_t m_LeftHand = 23571472; - /** - * The right hand ID of the character - * NOTE: This might just be client stack garbage. - */ + /** + * The right hand ID of the character + * NOTE: This might just be client stack garbage. + */ uint32_t m_RightHand = 23124164; - /** - * The emotes unlocked by this character - */ + /** + * The emotes unlocked by this character + */ std::vector m_UnlockedEmotes; - /** - * The ID of the properties of this character - */ + /** + * The ID of the properties of this character + */ uint32_t m_PropertyCloneID; - /** - * The XML data for this character, stored as string - */ + /** + * The XML data for this character, stored as string + */ std::string m_XMLData; - /** - * The last zone visited by the character that was not an instance zone - */ + /** + * The last zone visited by the character that was not an instance zone + */ uint32_t m_LastNonInstanceZoneID = 0; - /** - * The ID of the zone the character is currently in - */ + /** + * The ID of the zone the character is currently in + */ uint32_t m_ZoneID = 0; - /** - * The instance ID of the zone the character is currently in (for boss battles) - */ + /** + * The instance ID of the zone the character is currently in (for boss battles) + */ uint32_t m_ZoneInstanceID = 0; - /** - * The clone ID of the zone the character is currently in (for properties) - */ + /** + * The clone ID of the zone the character is currently in (for properties) + */ uint32_t m_ZoneCloneID = 0; - /** - * The last time this character logged in - */ + /** + * The last time this character logged in + */ uint64_t m_LastLogin; - /** - * The gameplay flags this character has (not just true values) - */ - std::unordered_map m_PlayerFlags; + /** + * The gameplay flags this character has (not just true values) + */ + std::unordered_map m_PlayerFlags; - /** - * The character XML belonging to this character - */ - tinyxml2::XMLDocument* m_Doc; + /** + * The character XML belonging to this character + */ + tinyxml2::XMLDocument* m_Doc; - /** - * Title of an announcement this character made (reserved for GMs) - */ + /** + * Title of an announcement this character made (reserved for GMs) + */ std::string m_AnnouncementTitle; - /** - * The body of an announcement this character made (reserved for GMs) - */ + /** + * The body of an announcement this character made (reserved for GMs) + */ std::string m_AnnouncementMessage; - /** - * The spawn position of this character when loading in - */ + /** + * The spawn position of this character when loading in + */ NiPoint3 m_OriginalPosition; - /** - * The spawn rotation of this character when loading in - */ + /** + * The spawn rotation of this character when loading in + */ NiQuaternion m_OriginalRotation; - /** - * The respawn points of this character, per world - */ + /** + * The respawn points of this character, per world + */ std::map m_WorldRespawnCheckpoints; /** @@ -620,7 +620,7 @@ private: * Set by the launchpad the player used to get to the current world. */ std::string m_TargetScene; - + /** * Queries the character XML and updates all the fields of this object * NOTE: quick as there's no DB lookups diff --git a/dGame/Entity.cpp b/dGame/Entity.cpp index fbb61437..89289004 100644 --- a/dGame/Entity.cpp +++ b/dGame/Entity.cpp @@ -90,8 +90,8 @@ Entity::Entity(const LWOOBJID& objectID, EntityInfo info, Entity* parentEntity) m_Scale = info.scale; m_Spawner = info.spawner; m_SpawnerID = info.spawnerID; - m_HasSpawnerNodeID = info.hasSpawnerNodeID; - m_SpawnerNodeID = info.spawnerNodeID; + m_HasSpawnerNodeID = info.hasSpawnerNodeID; + m_SpawnerNodeID = info.spawnerNodeID; if (info.lot != 1) m_PlayerIsReadyForUpdates = true; } @@ -105,7 +105,7 @@ Entity::~Entity() { CancelCallbackTimers(); const auto components = m_Components; - + for (const auto& pair : components) { delete pair.second; @@ -121,8 +121,7 @@ Entity::~Entity() { } } -void Entity::Initialize() -{ +void Entity::Initialize() { /** * Setup trigger */ @@ -197,12 +196,12 @@ void Entity::Initialize() destroyableComponent->SetIsSmashable(true); m_Components.insert(std::make_pair(COMPONENT_TYPE_DESTROYABLE, destroyableComponent)); // We have all our components. - return; + return; } /** * Go through all the components and check if this entity has them. - * + * * Not all components are implemented. Some are represented by a nullptr, as they hold no data. */ @@ -245,7 +244,7 @@ void Entity::Initialize() const auto propertyEntranceComponentID = compRegistryTable->GetByIDAndType(m_TemplateID, COMPONENT_TYPE_PROPERTY_ENTRANCE); if (propertyEntranceComponentID > 0) { m_Components.insert(std::make_pair(COMPONENT_TYPE_PROPERTY_ENTRANCE, - new PropertyEntranceComponent(propertyEntranceComponentID, this))); + new PropertyEntranceComponent(propertyEntranceComponentID, this))); } if (compRegistryTable->GetByIDAndType(m_TemplateID, COMPONENT_TYPE_CONTROLLABLE_PHYSICS) > 0) { @@ -267,21 +266,18 @@ void Entity::Initialize() if (m_Character->HasBeenToWorld(mapID) && targetSceneName.empty()) { pos = m_Character->GetRespawnPoint(mapID); rot = dZoneManager::Instance()->GetZone()->GetSpawnRot(); - } - else if (targetScene != nullptr) { + } else if (targetScene != nullptr) { pos = targetScene->GetPosition(); rot = targetScene->GetRotation(); - } - else { - pos = dZoneManager::Instance()->GetZone()->GetSpawnPos(); - rot = dZoneManager::Instance()->GetZone()->GetSpawnRot(); + } else { + pos = dZoneManager::Instance()->GetZone()->GetSpawnPos(); + rot = dZoneManager::Instance()->GetZone()->GetSpawnRot(); } controllablePhysics->SetPosition(pos); controllablePhysics->SetRotation(rot); } - } - else { + } else { controllablePhysics->SetPosition(m_DefaultPosition); controllablePhysics->SetRotation(m_DefaultRotation); } @@ -315,10 +311,10 @@ void Entity::Initialize() vehiclePhysicsComponent->SetPosition(m_DefaultPosition); vehiclePhysicsComponent->SetRotation(m_DefaultRotation); } - + if (compRegistryTable->GetByIDAndType(m_TemplateID, COMPONENT_TYPE_SOUND_TRIGGER, -1) != -1) { - auto* comp = new SoundTriggerComponent(this); - m_Components.insert(std::make_pair(COMPONENT_TYPE_SOUND_TRIGGER, comp)); + auto* comp = new SoundTriggerComponent(this); + m_Components.insert(std::make_pair(COMPONENT_TYPE_SOUND_TRIGGER, comp)); } //Check to see if we have a moving platform component: @@ -340,7 +336,7 @@ void Entity::Initialize() int collectibleComponentID = compRegistryTable->GetByIDAndType(m_TemplateID, COMPONENT_TYPE_COLLECTIBLE); - if (collectibleComponentID > 0){ + if (collectibleComponentID > 0) { m_Components.insert(std::make_pair(COMPONENT_TYPE_COLLECTIBLE, nullptr)); } @@ -363,14 +359,12 @@ void Entity::Initialize() DestroyableComponent* comp = new DestroyableComponent(this); if (m_Character) { comp->LoadFromXml(m_Character->GetXMLDoc()); - } - else { + } else { if (componentID > 0) { std::vector destCompData = destCompTable->Query([=](CDDestructibleComponent entry) { return (entry.id == componentID); }); if (destCompData.size() > 0) { - if (HasComponent(COMPONENT_TYPE_RACING_STATS)) - { + if (HasComponent(COMPONENT_TYPE_RACING_STATS)) { destCompData[0].imagination = 60; } @@ -402,8 +396,7 @@ void Entity::Initialize() // extraInfo overrides comp->SetIsSmashable(GetVarAs(u"is_smashable") != 0); } - } - else { + } else { comp->SetHealth(1); comp->SetArmor(0); @@ -480,18 +473,15 @@ void Entity::Initialize() CDScriptComponent scriptCompData = scriptCompTable->GetByID(scriptComponentID); scriptName = scriptCompData.script_name; clientScriptName = scriptCompData.client_script_name; - } - else { + } else { scriptName = ""; } if (scriptName != "" || (scriptName == "" && m_Character)) { - - } - else if (clientScriptName != "") { + + } else if (clientScriptName != "") { client = true; - } - else if (!m_Character) { + } else if (!m_Character) { client = true; } } @@ -525,8 +515,7 @@ void Entity::Initialize() const auto zoneID = dZoneManager::Instance()->GetZoneID(); const CDZoneTable* zoneData = zoneTable->Query(zoneID.GetMapID()); - if (zoneData != nullptr) - { + if (zoneData != nullptr) { int zoneScriptID = zoneData->scriptID; CDScriptComponent zoneScriptData = scriptCompTable->GetByID(zoneScriptID); @@ -598,14 +587,12 @@ void Entity::Initialize() m_Components.insert(std::make_pair(COMPONENT_TYPE_VENDOR, comp)); } - if (compRegistryTable->GetByIDAndType(m_TemplateID, COMPONENT_TYPE_PROPERTY_VENDOR, -1) != -1) - { + if (compRegistryTable->GetByIDAndType(m_TemplateID, COMPONENT_TYPE_PROPERTY_VENDOR, -1) != -1) { auto* component = new PropertyVendorComponent(this); m_Components.insert_or_assign(COMPONENT_TYPE_PROPERTY_VENDOR, component); } - if (compRegistryTable->GetByIDAndType(m_TemplateID, COMPONENT_TYPE_PROPERTY_MANAGEMENT, -1) != -1) - { + if (compRegistryTable->GetByIDAndType(m_TemplateID, COMPONENT_TYPE_PROPERTY_MANAGEMENT, -1) != -1) { auto* component = new PropertyManagementComponent(this); m_Components.insert_or_assign(COMPONENT_TYPE_PROPERTY_MANAGEMENT, component); } @@ -634,8 +621,8 @@ void Entity::Initialize() m_Components.insert(std::make_pair(COMPONENT_TYPE_SCRIPTED_ACTIVITY, new ScriptedActivityComponent(this, scriptedActivityID))); } - if (compRegistryTable->GetByIDAndType(m_TemplateID, COMPONENT_TYPE_MODEL, -1) != -1 && !GetComponent()) { - m_Components.insert(std::make_pair(COMPONENT_TYPE_MODEL, new ModelComponent(this))); + if (compRegistryTable->GetByIDAndType(m_TemplateID, COMPONENT_TYPE_MODEL, -1) != -1 && !GetComponent()) { + m_Components.insert(std::make_pair(COMPONENT_TYPE_MODEL, new ModelComponent(this))); if (m_Components.find(COMPONENT_TYPE_DESTROYABLE) == m_Components.end()) { auto destroyableComponent = new DestroyableComponent(this); destroyableComponent->SetHealth(1); @@ -644,7 +631,7 @@ void Entity::Initialize() destroyableComponent->SetIsSmashable(true); m_Components.insert(std::make_pair(COMPONENT_TYPE_DESTROYABLE, destroyableComponent)); } - } + } PetComponent* petComponent; if (compRegistryTable->GetByIDAndType(m_TemplateID, COMPONENT_TYPE_ITEM) > 0 && !TryGetComponent(COMPONENT_TYPE_PET, petComponent) && !HasComponent(COMPONENT_TYPE_MODEL)) { @@ -652,9 +639,9 @@ void Entity::Initialize() } // Shooting gallery component - if (compRegistryTable->GetByIDAndType(m_TemplateID, COMPONENT_TYPE_SHOOTING_GALLERY) > 0) { - m_Components.insert(std::make_pair(COMPONENT_TYPE_SHOOTING_GALLERY, new ShootingGalleryComponent(this))); - } + if (compRegistryTable->GetByIDAndType(m_TemplateID, COMPONENT_TYPE_SHOOTING_GALLERY) > 0) { + m_Components.insert(std::make_pair(COMPONENT_TYPE_SHOOTING_GALLERY, new ShootingGalleryComponent(this))); + } if (compRegistryTable->GetByIDAndType(m_TemplateID, COMPONENT_TYPE_PROPERTY, -1) != -1) { m_Components.insert(std::make_pair(COMPONENT_TYPE_PROPERTY, new PropertyComponent(this))); @@ -667,7 +654,7 @@ void Entity::Initialize() const int32_t railComponentID = compRegistryTable->GetByIDAndType(m_TemplateID, COMPONENT_TYPE_RAIL_ACTIVATOR); if (railComponentID > 0) { - m_Components.insert(std::make_pair(COMPONENT_TYPE_RAIL_ACTIVATOR, new RailActivatorComponent(this, railComponentID))); + m_Components.insert(std::make_pair(COMPONENT_TYPE_RAIL_ACTIVATOR, new RailActivatorComponent(this, railComponentID))); } int movementAIID = compRegistryTable->GetByIDAndType(m_TemplateID, COMPONENT_TYPE_MOVEMENT_AI); @@ -697,9 +684,7 @@ void Entity::Initialize() m_Components.insert(std::make_pair(COMPONENT_TYPE_MOVEMENT_AI, new MovementAIComponent(this, moveInfo))); } - } - else if (petComponentId > 0 || combatAiId > 0 && GetComponent()->GetTetherSpeed() > 0) - { + } else if (petComponentId > 0 || combatAiId > 0 && GetComponent()->GetTetherSpeed() > 0) { MovementAIInfo moveInfo = MovementAIInfo(); moveInfo.movementType = ""; moveInfo.wanderChance = 0; @@ -727,49 +712,45 @@ void Entity::Initialize() for (CppScripts::Script* script : CppScripts::GetEntityScripts(this)) { script->OnStartup(this); } - }); + }); - if (!m_Character && EntityManager::Instance()->GetGhostingEnabled()) - { + if (!m_Character && EntityManager::Instance()->GetGhostingEnabled()) { // Don't ghost what is likely large scene elements - if (m_Components.size() == 2 && HasComponent(COMPONENT_TYPE_SIMPLE_PHYSICS) && HasComponent(COMPONENT_TYPE_RENDER)) - { + if (m_Components.size() == 2 && HasComponent(COMPONENT_TYPE_SIMPLE_PHYSICS) && HasComponent(COMPONENT_TYPE_RENDER)) { goto no_ghosting; } /* Filter for ghosting candidates. - * + * * Don't ghost moving platforms, until we've got proper syncing for those. * Don't ghost big phantom physics triggers, as putting those to sleep might prevent interactions. * Don't ghost property related objects, as the client expects those to always be loaded. */ if ( !EntityManager::IsExcludedFromGhosting(GetLOT()) && - !HasComponent(COMPONENT_TYPE_SCRIPTED_ACTIVITY) && - !HasComponent(COMPONENT_TYPE_MOVING_PLATFORM) && - !HasComponent(COMPONENT_TYPE_PHANTOM_PHYSICS) && - !HasComponent(COMPONENT_TYPE_PROPERTY) && - !HasComponent(COMPONENT_TYPE_RACING_CONTROL) && + !HasComponent(COMPONENT_TYPE_SCRIPTED_ACTIVITY) && + !HasComponent(COMPONENT_TYPE_MOVING_PLATFORM) && + !HasComponent(COMPONENT_TYPE_PHANTOM_PHYSICS) && + !HasComponent(COMPONENT_TYPE_PROPERTY) && + !HasComponent(COMPONENT_TYPE_RACING_CONTROL) && !HasComponent(COMPONENT_TYPE_VEHICLE_PHYSICS) - ) - //if (HasComponent(COMPONENT_TYPE_BASE_COMBAT_AI)) + ) + //if (HasComponent(COMPONENT_TYPE_BASE_COMBAT_AI)) { m_IsGhostingCandidate = true; } - if (GetLOT() == 6368) - { + if (GetLOT() == 6368) { m_IsGhostingCandidate = true; } // Special case for collectibles in Ninjago - if (HasComponent(COMPONENT_TYPE_COLLECTIBLE) && Game::server->GetZoneID() == 2000) - { + if (HasComponent(COMPONENT_TYPE_COLLECTIBLE) && Game::server->GetZoneID() == 2000) { m_IsGhostingCandidate = true; } } - no_ghosting: +no_ghosting: TriggerEvent("OnCreate"); @@ -791,10 +772,8 @@ bool Entity::operator!=(const Entity& other) const { return other.m_ObjectID != m_ObjectID; } -User* Entity::GetParentUser() const -{ - if (!IsPlayer()) - { +User* Entity::GetParentUser() const { + if (!IsPlayer()) { return nullptr; } @@ -804,23 +783,19 @@ User* Entity::GetParentUser() const Component* Entity::GetComponent(int32_t componentID) const { const auto& index = m_Components.find(componentID); - if (index == m_Components.end()) - { + if (index == m_Components.end()) { return nullptr; } - + return index->second; } -bool Entity::HasComponent(const int32_t componentId) const -{ +bool Entity::HasComponent(const int32_t componentId) const { return m_Components.find(componentId) != m_Components.end(); } -void Entity::AddComponent(const int32_t componentId, Component* component) -{ - if (HasComponent(componentId)) - { +void Entity::AddComponent(const int32_t componentId, Component* component) { + if (HasComponent(componentId)) { return; } @@ -834,7 +809,7 @@ std::vector Entity::GetScriptComponents() { comps.push_back(static_cast(p.second)); } } - + return comps; } @@ -884,8 +859,7 @@ void Entity::WriteBaseReplicaData(RakNet::BitStream* outBitStream, eReplicaPacke for (size_t i = 0; i < name.size(); ++i) { outBitStream->Write(name[i]); } - } - else { + } else { const auto& name = GetVar(u"npcName"); outBitStream->Write(uint8_t(name.size())); @@ -901,7 +875,7 @@ void Entity::WriteBaseReplicaData(RakNet::BitStream* outBitStream, eReplicaPacke // Only sync for models. if (m_Settings.size() > 0 && (GetComponent() && !GetComponent())) { outBitStream->Write1(); //ldf data - + RakNet::BitStream settingStream; settingStream.Write(m_Settings.size()); @@ -914,8 +888,7 @@ void Entity::WriteBaseReplicaData(RakNet::BitStream* outBitStream, eReplicaPacke outBitStream->Write(settingStream.GetNumberOfBytesUsed() + 1); outBitStream->Write(0); //no compression used outBitStream->Write(settingStream); - } - else if (!syncLDF.empty()) { + } else if (!syncLDF.empty()) { std::vector ldfData; for (const auto& data : syncLDF) { @@ -936,15 +909,13 @@ void Entity::WriteBaseReplicaData(RakNet::BitStream* outBitStream, eReplicaPacke outBitStream->Write(settingStream.GetNumberOfBytesUsed() + 1); outBitStream->Write(0); //no compression used outBitStream->Write(settingStream); - } - else { - outBitStream->Write0(); //No ldf data + } else { + outBitStream->Write0(); //No ldf data } if (m_Trigger != nullptr && m_Trigger->events.size() > 0) { outBitStream->Write1(); - } - else { + } else { outBitStream->Write0(); } @@ -953,8 +924,7 @@ void Entity::WriteBaseReplicaData(RakNet::BitStream* outBitStream, eReplicaPacke if (m_ParentEntity != nullptr) outBitStream->Write(GeneralUtils::SetBit(m_ParentEntity->GetObjectID(), OBJECT_BIT_CLIENT)); else if (m_Spawner != nullptr && m_Spawner->m_Info.isNetwork) outBitStream->Write(m_SpawnerID); else outBitStream->Write(GeneralUtils::SetBit(m_SpawnerID, OBJECT_BIT_CLIENT)); - } - else outBitStream->Write0(); + } else outBitStream->Write0(); outBitStream->Write(m_HasSpawnerNodeID); if (m_HasSpawnerNodeID) outBitStream->Write(m_SpawnerNodeID); @@ -972,10 +942,9 @@ void Entity::WriteBaseReplicaData(RakNet::BitStream* outBitStream, eReplicaPacke if (m_GMLevel != 0) { outBitStream->Write1(); outBitStream->Write(m_GMLevel); - } - else outBitStream->Write0(); //No GM Level + } else outBitStream->Write0(); //No GM Level } - + // Only serialize parent / child info should the info be dirty (changed) or if this is the construction of the entity. outBitStream->Write(m_IsParentChildDirty || packetType == PACKET_TYPE_CONSTRUCTION); if (m_IsParentChildDirty || packetType == PACKET_TYPE_CONSTRUCTION) { @@ -1007,60 +976,51 @@ void Entity::WriteComponents(RakNet::BitStream* outBitStream, eReplicaPacketType unsigned int flags = 0; PossessableComponent* possessableComponent; - if (TryGetComponent(COMPONENT_TYPE_POSSESSABLE, possessableComponent)) - { + if (TryGetComponent(COMPONENT_TYPE_POSSESSABLE, possessableComponent)) { possessableComponent->Serialize(outBitStream, bIsInitialUpdate, flags); } ModuleAssemblyComponent* moduleAssemblyComponent; - if (TryGetComponent(COMPONENT_TYPE_MODULE_ASSEMBLY, moduleAssemblyComponent)) - { + if (TryGetComponent(COMPONENT_TYPE_MODULE_ASSEMBLY, moduleAssemblyComponent)) { moduleAssemblyComponent->Serialize(outBitStream, bIsInitialUpdate, flags); } - + ControllablePhysicsComponent* controllablePhysicsComponent; - if (TryGetComponent(COMPONENT_TYPE_CONTROLLABLE_PHYSICS, controllablePhysicsComponent)) - { + if (TryGetComponent(COMPONENT_TYPE_CONTROLLABLE_PHYSICS, controllablePhysicsComponent)) { controllablePhysicsComponent->Serialize(outBitStream, bIsInitialUpdate, flags); } SimplePhysicsComponent* simplePhysicsComponent; - if (TryGetComponent(COMPONENT_TYPE_SIMPLE_PHYSICS, simplePhysicsComponent)) - { + if (TryGetComponent(COMPONENT_TYPE_SIMPLE_PHYSICS, simplePhysicsComponent)) { simplePhysicsComponent->Serialize(outBitStream, bIsInitialUpdate, flags); } RigidbodyPhantomPhysicsComponent* rigidbodyPhantomPhysics; - if (TryGetComponent(COMPONENT_TYPE_RIGID_BODY_PHANTOM_PHYSICS, rigidbodyPhantomPhysics)) - { + if (TryGetComponent(COMPONENT_TYPE_RIGID_BODY_PHANTOM_PHYSICS, rigidbodyPhantomPhysics)) { rigidbodyPhantomPhysics->Serialize(outBitStream, bIsInitialUpdate, flags); } VehiclePhysicsComponent* vehiclePhysicsComponent; - if (TryGetComponent(COMPONENT_TYPE_VEHICLE_PHYSICS, vehiclePhysicsComponent)) - { + if (TryGetComponent(COMPONENT_TYPE_VEHICLE_PHYSICS, vehiclePhysicsComponent)) { vehiclePhysicsComponent->Serialize(outBitStream, bIsInitialUpdate, flags); } PhantomPhysicsComponent* phantomPhysicsComponent; - if (TryGetComponent(COMPONENT_TYPE_PHANTOM_PHYSICS, phantomPhysicsComponent)) - { + if (TryGetComponent(COMPONENT_TYPE_PHANTOM_PHYSICS, phantomPhysicsComponent)) { phantomPhysicsComponent->Serialize(outBitStream, bIsInitialUpdate, flags); } SoundTriggerComponent* soundTriggerComponent; if (TryGetComponent(COMPONENT_TYPE_SOUND_TRIGGER, soundTriggerComponent)) { - soundTriggerComponent->Serialize(outBitStream, bIsInitialUpdate, flags); + soundTriggerComponent->Serialize(outBitStream, bIsInitialUpdate, flags); } BuffComponent* buffComponent; - if (TryGetComponent(COMPONENT_TYPE_BUFF, buffComponent)) - { + if (TryGetComponent(COMPONENT_TYPE_BUFF, buffComponent)) { buffComponent->Serialize(outBitStream, bIsInitialUpdate, flags); DestroyableComponent* destroyableComponent; - if (TryGetComponent(COMPONENT_TYPE_DESTROYABLE, destroyableComponent)) - { + if (TryGetComponent(COMPONENT_TYPE_DESTROYABLE, destroyableComponent)) { destroyableComponent->Serialize(outBitStream, bIsInitialUpdate, flags); } destroyableSerialized = true; @@ -1068,8 +1028,7 @@ void Entity::WriteComponents(RakNet::BitStream* outBitStream, eReplicaPacketType if (HasComponent(COMPONENT_TYPE_COLLECTIBLE)) { DestroyableComponent* destroyableComponent; - if (TryGetComponent(COMPONENT_TYPE_DESTROYABLE, destroyableComponent) && !destroyableSerialized) - { + if (TryGetComponent(COMPONENT_TYPE_DESTROYABLE, destroyableComponent) && !destroyableSerialized) { destroyableComponent->Serialize(outBitStream, bIsInitialUpdate, flags); } destroyableSerialized = true; @@ -1077,8 +1036,7 @@ void Entity::WriteComponents(RakNet::BitStream* outBitStream, eReplicaPacketType } PetComponent* petComponent; - if (TryGetComponent(COMPONENT_TYPE_PET, petComponent)) - { + if (TryGetComponent(COMPONENT_TYPE_PET, petComponent)) { petComponent->Serialize(outBitStream, bIsInitialUpdate, flags); } @@ -1112,41 +1070,34 @@ void Entity::WriteComponents(RakNet::BitStream* outBitStream, eReplicaPacketType characterComponent->Serialize(outBitStream, bIsInitialUpdate, flags); } - if (HasComponent(COMPONENT_TYPE_ITEM)) - { + if (HasComponent(COMPONENT_TYPE_ITEM)) { outBitStream->Write0(); } InventoryComponent* inventoryComponent; - if (TryGetComponent(COMPONENT_TYPE_INVENTORY, inventoryComponent)) - { + if (TryGetComponent(COMPONENT_TYPE_INVENTORY, inventoryComponent)) { inventoryComponent->Serialize(outBitStream, bIsInitialUpdate, flags); } ScriptComponent* scriptComponent; - if (TryGetComponent(COMPONENT_TYPE_SCRIPT, scriptComponent)) - { + if (TryGetComponent(COMPONENT_TYPE_SCRIPT, scriptComponent)) { scriptComponent->Serialize(outBitStream, bIsInitialUpdate, flags); } SkillComponent* skillComponent; - if (TryGetComponent(COMPONENT_TYPE_SKILL, skillComponent)) - { + if (TryGetComponent(COMPONENT_TYPE_SKILL, skillComponent)) { skillComponent->Serialize(outBitStream, bIsInitialUpdate, flags); } BaseCombatAIComponent* baseCombatAiComponent; - if (TryGetComponent(COMPONENT_TYPE_BASE_COMBAT_AI, baseCombatAiComponent)) - { + if (TryGetComponent(COMPONENT_TYPE_BASE_COMBAT_AI, baseCombatAiComponent)) { baseCombatAiComponent->Serialize(outBitStream, bIsInitialUpdate, flags); } RebuildComponent* rebuildComponent; - if (TryGetComponent(COMPONENT_TYPE_REBUILD, rebuildComponent)) - { + if (TryGetComponent(COMPONENT_TYPE_REBUILD, rebuildComponent)) { DestroyableComponent* destroyableComponent; - if (TryGetComponent(COMPONENT_TYPE_DESTROYABLE, destroyableComponent) && !destroyableSerialized) - { + if (TryGetComponent(COMPONENT_TYPE_DESTROYABLE, destroyableComponent) && !destroyableSerialized) { destroyableComponent->Serialize(outBitStream, bIsInitialUpdate, flags); } destroyableSerialized = true; @@ -1154,8 +1105,7 @@ void Entity::WriteComponents(RakNet::BitStream* outBitStream, eReplicaPacketType } MovingPlatformComponent* movingPlatformComponent; - if (TryGetComponent(COMPONENT_TYPE_MOVING_PLATFORM, movingPlatformComponent)) - { + if (TryGetComponent(COMPONENT_TYPE_MOVING_PLATFORM, movingPlatformComponent)) { movingPlatformComponent->Serialize(outBitStream, bIsInitialUpdate, flags); } @@ -1165,14 +1115,12 @@ void Entity::WriteComponents(RakNet::BitStream* outBitStream, eReplicaPacketType } VendorComponent* vendorComponent; - if (TryGetComponent(COMPONENT_TYPE_VENDOR, vendorComponent)) - { + if (TryGetComponent(COMPONENT_TYPE_VENDOR, vendorComponent)) { vendorComponent->Serialize(outBitStream, bIsInitialUpdate, flags); } BouncerComponent* bouncerComponent; - if (TryGetComponent(COMPONENT_TYPE_BOUNCER, bouncerComponent)) - { + if (TryGetComponent(COMPONENT_TYPE_BOUNCER, bouncerComponent)) { bouncerComponent->Serialize(outBitStream, bIsInitialUpdate, flags); } @@ -1181,20 +1129,18 @@ void Entity::WriteComponents(RakNet::BitStream* outBitStream, eReplicaPacketType scriptedActivityComponent->Serialize(outBitStream, bIsInitialUpdate, flags); } - ShootingGalleryComponent* shootingGalleryComponent; - if (TryGetComponent(COMPONENT_TYPE_SHOOTING_GALLERY, shootingGalleryComponent)) { - shootingGalleryComponent->Serialize(outBitStream, bIsInitialUpdate, flags); - } + ShootingGalleryComponent* shootingGalleryComponent; + if (TryGetComponent(COMPONENT_TYPE_SHOOTING_GALLERY, shootingGalleryComponent)) { + shootingGalleryComponent->Serialize(outBitStream, bIsInitialUpdate, flags); + } RacingControlComponent* racingControlComponent; - if (TryGetComponent(COMPONENT_TYPE_RACING_CONTROL, racingControlComponent)) - { + if (TryGetComponent(COMPONENT_TYPE_RACING_CONTROL, racingControlComponent)) { racingControlComponent->Serialize(outBitStream, bIsInitialUpdate, flags); } LUPExhibitComponent* lupExhibitComponent; - if (TryGetComponent(COMPONENT_TYPE_EXHIBIT, lupExhibitComponent)) - { + if (TryGetComponent(COMPONENT_TYPE_EXHIBIT, lupExhibitComponent)) { lupExhibitComponent->Serialize(outBitStream, bIsInitialUpdate, flags); } @@ -1204,8 +1150,7 @@ void Entity::WriteComponents(RakNet::BitStream* outBitStream, eReplicaPacketType } RenderComponent* renderComponent; - if (TryGetComponent(COMPONENT_TYPE_RENDER, renderComponent)) - { + if (TryGetComponent(COMPONENT_TYPE_RENDER, renderComponent)) { renderComponent->Serialize(outBitStream, bIsInitialUpdate, flags); } @@ -1217,8 +1162,7 @@ void Entity::WriteComponents(RakNet::BitStream* outBitStream, eReplicaPacketType } } - if (HasComponent(COMPONENT_TYPE_ZONE_CONTROL)) - { + if (HasComponent(COMPONENT_TYPE_ZONE_CONTROL)) { outBitStream->Write(0x40000000); } @@ -1236,8 +1180,7 @@ void Entity::UpdateXMLDoc(tinyxml2::XMLDocument* doc) { //This function should only ever be called from within Character, meaning doc should always exist when this is called. //Naturally, we don't include any non-player components in this update function. - for (const auto& pair : m_Components) - { + for (const auto& pair : m_Components) { if (pair.second == nullptr) continue; pair.second->UpdateXml(doc); @@ -1271,7 +1214,7 @@ void Entity::Update(const float deltaTime) { m_CallbackTimers.erase(m_CallbackTimers.begin() + i); } } - + // Add pending timers to the list of timers so they start next tick. if (m_PendingTimers.size() > 0) { for (auto namedTimer : m_PendingTimers) { @@ -1280,14 +1223,11 @@ void Entity::Update(const float deltaTime) { m_PendingTimers.clear(); } - if (IsSleeping()) - { + if (IsSleeping()) { Sleep(); return; - } - else - { + } else { Wake(); } @@ -1295,8 +1235,7 @@ void Entity::Update(const float deltaTime) { script->OnUpdate(this); } - for (const auto& pair : m_Components) - { + for (const auto& pair : m_Components) { if (pair.second == nullptr) continue; pair.second->Update(deltaTime); @@ -1329,8 +1268,8 @@ void Entity::OnCollisionPhantom(const LWOOBJID otherEntity) { script->OnCollisionPhantom(this, other); } - for (const auto& callback: m_PhantomCollisionCallbacks) { - callback(other); + for (const auto& callback : m_PhantomCollisionCallbacks) { + callback(other); } SwitchComponent* switchComp = GetComponent(); @@ -1345,19 +1284,16 @@ void Entity::OnCollisionPhantom(const LWOOBJID otherEntity) { if (!poi.empty()) { auto* missionComponent = other->GetComponent(); - - if (missionComponent != nullptr) - { + + if (missionComponent != nullptr) { missionComponent->Progress(MissionTaskType::MISSION_TASK_TYPE_LOCATION, 0, 0, GeneralUtils::UTF16ToWTF8(poi)); } } - if (!other->GetIsDead()) - { + if (!other->GetIsDead()) { auto* combat = GetComponent(); - - if (combat != nullptr) - { + + if (combat != nullptr) { const auto index = std::find(m_TargetsInPhantom.begin(), m_TargetsInPhantom.end(), otherEntity); if (index != m_TargetsInPhantom.end()) return; @@ -1371,8 +1307,7 @@ void Entity::OnCollisionPhantom(const LWOOBJID otherEntity) { } } -void Entity::OnCollisionLeavePhantom(const LWOOBJID otherEntity) -{ +void Entity::OnCollisionLeavePhantom(const LWOOBJID otherEntity) { auto* other = EntityManager::Instance()->GetEntity(otherEntity); if (!other) return; @@ -1384,44 +1319,41 @@ void Entity::OnCollisionLeavePhantom(const LWOOBJID otherEntity) } const auto index = std::find(m_TargetsInPhantom.begin(), m_TargetsInPhantom.end(), otherEntity); - + if (index == m_TargetsInPhantom.end()) return; m_TargetsInPhantom.erase(index); } void Entity::OnFireEventServerSide(Entity* sender, std::string args, int32_t param1, int32_t param2, int32_t param3) { - for (CppScripts::Script* script : CppScripts::GetEntityScripts(this)) { - script->OnFireEventServerSide(this, sender, args, param1, param2, param3); + for (CppScripts::Script* script : CppScripts::GetEntityScripts(this)) { + script->OnFireEventServerSide(this, sender, args, param1, param2, param3); } } void Entity::OnActivityStateChangeRequest(LWOOBJID senderID, int32_t value1, int32_t value2, const std::u16string& stringValue) { - for (CppScripts::Script *script : CppScripts::GetEntityScripts(this)) { - script->OnActivityStateChangeRequest(this, senderID, value1, value2, stringValue); + for (CppScripts::Script* script : CppScripts::GetEntityScripts(this)) { + script->OnActivityStateChangeRequest(this, senderID, value1, value2, stringValue); } } -void Entity::OnCinematicUpdate(Entity *self, Entity *sender, eCinematicEvent event, const std::u16string &pathName, - float_t pathTime, float_t totalTime, int32_t waypoint) { - for (CppScripts::Script* script : CppScripts::GetEntityScripts(this)) { - script->OnCinematicUpdate(self, sender, event, pathName, pathTime, totalTime, waypoint); - } +void Entity::OnCinematicUpdate(Entity* self, Entity* sender, eCinematicEvent event, const std::u16string& pathName, + float_t pathTime, float_t totalTime, int32_t waypoint) { + for (CppScripts::Script* script : CppScripts::GetEntityScripts(this)) { + script->OnCinematicUpdate(self, sender, event, pathName, pathTime, totalTime, waypoint); + } } -void Entity::NotifyObject(Entity* sender, const std::string& name, int32_t param1, int32_t param2) -{ +void Entity::NotifyObject(Entity* sender, const std::string& name, int32_t param1, int32_t param2) { GameMessages::SendNotifyObject(GetObjectID(), sender->GetObjectID(), GeneralUtils::ASCIIToUTF16(name), UNASSIGNED_SYSTEM_ADDRESS); - for (CppScripts::Script* script : CppScripts::GetEntityScripts(this)) { - script->OnNotifyObject(this, sender, name, param1, param2); + for (CppScripts::Script* script : CppScripts::GetEntityScripts(this)) { + script->OnNotifyObject(this, sender, name, param1, param2); } } -void Entity::OnEmoteReceived(const int32_t emote, Entity* target) -{ - for (auto* script : CppScripts::GetEntityScripts(this)) - { +void Entity::OnEmoteReceived(const int32_t emote, Entity* target) { + for (auto* script : CppScripts::GetEntityScripts(this)) { script->OnEmoteReceived(this, emote, target); } } @@ -1434,9 +1366,8 @@ void Entity::OnUse(Entity* originator) { } // component base class when - - for (const auto& pair : m_Components) - { + + for (const auto& pair : m_Components) { if (pair.second == nullptr) continue; pair.second->OnUse(originator); @@ -1455,83 +1386,71 @@ void Entity::OnHit(Entity* attacker) { } } -void Entity::OnZonePropertyEditBegin() -{ +void Entity::OnZonePropertyEditBegin() { for (CppScripts::Script* script : CppScripts::GetEntityScripts(this)) { script->OnZonePropertyEditBegin(this); } } -void Entity::OnZonePropertyEditEnd() -{ +void Entity::OnZonePropertyEditEnd() { for (CppScripts::Script* script : CppScripts::GetEntityScripts(this)) { script->OnZonePropertyEditEnd(this); } } -void Entity::OnZonePropertyModelEquipped() -{ +void Entity::OnZonePropertyModelEquipped() { for (CppScripts::Script* script : CppScripts::GetEntityScripts(this)) { script->OnZonePropertyModelEquipped(this); } } -void Entity::OnZonePropertyModelPlaced(Entity* player) -{ +void Entity::OnZonePropertyModelPlaced(Entity* player) { for (CppScripts::Script* script : CppScripts::GetEntityScripts(this)) { script->OnZonePropertyModelPlaced(this, player); } } -void Entity::OnZonePropertyModelPickedUp(Entity* player) -{ +void Entity::OnZonePropertyModelPickedUp(Entity* player) { for (CppScripts::Script* script : CppScripts::GetEntityScripts(this)) { script->OnZonePropertyModelPickedUp(this, player); } } -void Entity::OnZonePropertyModelRemoved(Entity* player) -{ +void Entity::OnZonePropertyModelRemoved(Entity* player) { for (CppScripts::Script* script : CppScripts::GetEntityScripts(this)) { script->OnZonePropertyModelRemoved(this, player); } } -void Entity::OnZonePropertyModelRemovedWhileEquipped(Entity* player) -{ +void Entity::OnZonePropertyModelRemovedWhileEquipped(Entity* player) { for (CppScripts::Script* script : CppScripts::GetEntityScripts(this)) { script->OnZonePropertyModelRemovedWhileEquipped(this, player); } } -void Entity::OnZonePropertyModelRotated(Entity* player) -{ +void Entity::OnZonePropertyModelRotated(Entity* player) { for (CppScripts::Script* script : CppScripts::GetEntityScripts(this)) { script->OnZonePropertyModelRotated(this, player); } } -void Entity::OnMessageBoxResponse(Entity* sender, int32_t button, const std::u16string& identifier, const std::u16string& userData) -{ +void Entity::OnMessageBoxResponse(Entity* sender, int32_t button, const std::u16string& identifier, const std::u16string& userData) { for (CppScripts::Script* script : CppScripts::GetEntityScripts(this)) { script->OnMessageBoxResponse(this, sender, button, identifier, userData); } } -void Entity::OnChoiceBoxResponse(Entity* sender, int32_t button, const std::u16string& buttonIdentifier, const std::u16string& identifier) -{ +void Entity::OnChoiceBoxResponse(Entity* sender, int32_t button, const std::u16string& buttonIdentifier, const std::u16string& identifier) { for (CppScripts::Script* script : CppScripts::GetEntityScripts(this)) { script->OnChoiceBoxResponse(this, sender, button, buttonIdentifier, identifier); } } -void Entity::Smash(const LWOOBJID source, const eKillType killType, const std::u16string& deathType) -{ +void Entity::Smash(const LWOOBJID source, const eKillType killType, const std::u16string& deathType) { if (!m_PlayerIsReadyForUpdates) return; auto* destroyableComponent = GetComponent(); - if (destroyableComponent == nullptr) - { + if (destroyableComponent == nullptr) { Kill(EntityManager::Instance()->GetEntity(source)); return; } @@ -1550,62 +1469,53 @@ void Entity::Kill(Entity* murderer) { //OMAI WA MOU, SHINDERIU - for (CppScripts::Script* script : CppScripts::GetEntityScripts(this)) - { + for (CppScripts::Script* script : CppScripts::GetEntityScripts(this)) { script->OnDie(this, murderer); } - if (m_Spawner != nullptr) - { + if (m_Spawner != nullptr) { m_Spawner->NotifyOfEntityDeath(m_ObjectID); } - if (!IsPlayer()) - { + if (!IsPlayer()) { EntityManager::Instance()->DestroyEntity(this); } - + const auto& grpNameQBShowBricks = GetVar(u"grpNameQBShowBricks"); - if (!grpNameQBShowBricks.empty()) - { + if (!grpNameQBShowBricks.empty()) { auto spawners = dZoneManager::Instance()->GetSpawnersByName(grpNameQBShowBricks); Spawner* spawner = nullptr; - if (!spawners.empty()) - { + if (!spawners.empty()) { spawner = spawners[0]; - } - else - { + } else { spawners = dZoneManager::Instance()->GetSpawnersInGroup(grpNameQBShowBricks); - if (!spawners.empty()) - { + if (!spawners.empty()) { spawner = spawners[0]; } } - if (spawner != nullptr) - { + if (spawner != nullptr) { spawner->Spawn(); } } - // Track a player being smashed - auto* characterComponent = GetComponent(); - if (characterComponent != nullptr) { - characterComponent->UpdatePlayerStatistic(TimesSmashed); - } + // Track a player being smashed + auto* characterComponent = GetComponent(); + if (characterComponent != nullptr) { + characterComponent->UpdatePlayerStatistic(TimesSmashed); + } - // Track a player smashing something else - if (murderer != nullptr) { - auto* murdererCharacterComponent = murderer->GetComponent(); - if (murdererCharacterComponent != nullptr) { - murdererCharacterComponent->UpdatePlayerStatistic(SmashablesSmashed); - } - } + // Track a player smashing something else + if (murderer != nullptr) { + auto* murdererCharacterComponent = murderer->GetComponent(); + if (murdererCharacterComponent != nullptr) { + murdererCharacterComponent->UpdatePlayerStatistic(SmashablesSmashed); + } + } } void Entity::AddDieCallback(const std::function& callback) { @@ -1613,14 +1523,14 @@ void Entity::AddDieCallback(const std::function& callback) { } void Entity::AddCollisionPhantomCallback(const std::function& callback) { - m_PhantomCollisionCallbacks.push_back(callback); + m_PhantomCollisionCallbacks.push_back(callback); } -void Entity::AddRebuildCompleteCallback(const std::function &callback) const { - auto* rebuildComponent = GetComponent(); - if (rebuildComponent != nullptr) { - rebuildComponent->AddRebuildCompleteCallback(callback); - } +void Entity::AddRebuildCompleteCallback(const std::function& callback) const { + auto* rebuildComponent = GetComponent(); + if (rebuildComponent != nullptr) { + rebuildComponent->AddRebuildCompleteCallback(callback); + } } bool Entity::GetIsDead() const { @@ -1642,15 +1552,15 @@ void Entity::PickupItem(const LWOOBJID& objectID) { if (!inv) return; CDObjectsTable* objectsTable = CDClientManager::Instance()->GetTable("Objects"); - + auto& droppedLoot = static_cast(this)->GetDroppedLoot(); for (const auto& p : droppedLoot) { if (p.first == objectID) { - auto* characterComponent = GetComponent(); - if (characterComponent != nullptr) { - characterComponent->TrackLOTCollection(p.second.lot); - } + auto* characterComponent = GetComponent(); + if (characterComponent != nullptr) { + characterComponent->TrackLOTCollection(p.second.lot); + } const CDObjects& object = objectsTable->GetByID(p.second.lot); if (object.id != 0 && object.type == "Powerup") { @@ -1664,13 +1574,11 @@ void Entity::PickupItem(const LWOOBJID& objectID) { auto* missionComponent = GetComponent(); - if (missionComponent != nullptr) - { + if (missionComponent != nullptr) { missionComponent->Progress(MissionTaskType::MISSION_TASK_TYPE_POWERUP, skill.skillID); } } - } - else { + } else { inv->AddItem(p.second.lot, p.second.count, eLootSourceType::LOOT_SOURCE_PICKUP, eInventoryType::INVALID, {}, LWOOBJID_EMPTY, true, false, LWOOBJID_EMPTY, eInventoryType::INVALID, 1); } } @@ -1683,7 +1591,7 @@ bool Entity::CanPickupCoins(uint64_t count) { if (!IsPlayer()) return false; auto* player = static_cast(this); auto droppedCoins = player->GetDroppedCoins(); - if (count > droppedCoins) { + if (count > droppedCoins) { return false; } else { player->SetDroppedCoins(droppedCoins - count); @@ -1731,12 +1639,9 @@ void Entity::AddCallbackTimer(float time, std::function callback) { m_CallbackTimers.push_back(timer); } -bool Entity::HasTimer(const std::string& name) -{ - for (auto* timer : m_Timers) - { - if (timer->GetName() == name) - { +bool Entity::HasTimer(const std::string& name) { + for (auto* timer : m_Timers) { + if (timer->GetName() == name) { return true; } } @@ -1744,13 +1649,11 @@ bool Entity::HasTimer(const std::string& name) return false; } -void Entity::CancelCallbackTimers() -{ - for (auto* callback : m_CallbackTimers) - { +void Entity::CancelCallbackTimers() { + for (auto* callback : m_CallbackTimers) { delete callback; } - + m_CallbackTimers.clear(); } @@ -1762,13 +1665,13 @@ void Entity::ScheduleKillAfterUpdate(Entity* murderer) { } void Entity::CancelTimer(const std::string& name) { - for (int i = 0; i < m_Timers.size(); i++) { - if (m_Timers[i]->GetName() == name) { - delete m_Timers[i]; - m_Timers.erase(m_Timers.begin() + i); - return; - } - } + for (int i = 0; i < m_Timers.size(); i++) { + if (m_Timers[i]->GetName() == name) { + delete m_Timers[i]; + m_Timers.erase(m_Timers.begin() + i); + return; + } + } } void Entity::CancelAllTimers() { @@ -1776,8 +1679,7 @@ void Entity::CancelAllTimers() { if (timer) delete timer; }*/ - for (auto* timer : m_Timers) - { + for (auto* timer : m_Timers) { delete timer; } @@ -1859,17 +1761,16 @@ void Entity::HandleTriggerCommand(std::string id, std::string target, std::strin if (target == "self") { EntityManager::Instance()->ConstructEntity(this); } - } - else if (id == "updateMission") { + } else if (id == "updateMission") { CDMissionTasksTable* missionTasksTable = CDClientManager::Instance()->GetTable("MissionTasks"); std::vector missionTasks = missionTasksTable->Query([=](CDMissionTasks entry) { std::string lowerTargetGroup; for (char character : entry.targetGroup) { lowerTargetGroup.push_back(std::tolower(character)); // make lowercase to ensure it works } - + return (lowerTargetGroup == argArray[4]); - }); + }); for (const CDMissionTasks& task : missionTasks) { MissionComponent* missionComponent = targetEntity->GetComponent(); @@ -1877,23 +1778,19 @@ void Entity::HandleTriggerCommand(std::string id, std::string target, std::strin missionComponent->ForceProgress(task.id, task.uid, std::stoi(argArray[2])); } - } - else if (id == "fireEvent") { + } else if (id == "fireEvent") { for (CppScripts::Script* script : CppScripts::GetEntityScripts(targetEntity)) { - script->OnFireEventServerSide(targetEntity, this, args, 0, 0, 0); + script->OnFireEventServerSide(targetEntity, this, args, 0, 0, 0); } } } } -Entity* Entity::GetOwner() const -{ - if (m_OwnerOverride != LWOOBJID_EMPTY) - { +Entity* Entity::GetOwner() const { + if (m_OwnerOverride != LWOOBJID_EMPTY) { auto* other = EntityManager::Instance()->GetEntity(m_OwnerOverride); - if (other != nullptr) - { + if (other != nullptr) { return other->GetOwner(); } } @@ -1901,272 +1798,225 @@ Entity* Entity::GetOwner() const return const_cast(this); } -const NiPoint3& Entity::GetDefaultPosition() const -{ +const NiPoint3& Entity::GetDefaultPosition() const { return m_DefaultPosition; } -const NiQuaternion& Entity::GetDefaultRotation() const -{ +const NiQuaternion& Entity::GetDefaultRotation() const { return m_DefaultRotation; } -float Entity::GetDefaultScale() const -{ +float Entity::GetDefaultScale() const { return m_Scale; } -void Entity::SetOwnerOverride(const LWOOBJID value) -{ +void Entity::SetOwnerOverride(const LWOOBJID value) { m_OwnerOverride = value; } -bool Entity::GetIsGhostingCandidate() const -{ +bool Entity::GetIsGhostingCandidate() const { return m_IsGhostingCandidate; } -int8_t Entity::GetObservers() const -{ +int8_t Entity::GetObservers() const { return m_Observers; } -void Entity::SetObservers(int8_t value) -{ - if (value < 0) - { +void Entity::SetObservers(int8_t value) { + if (value < 0) { value = 0; } m_Observers = value; } -void Entity::Sleep() -{ +void Entity::Sleep() { auto* baseCombatAIComponent = GetComponent(); - - if (baseCombatAIComponent != nullptr) - { + + if (baseCombatAIComponent != nullptr) { baseCombatAIComponent->Sleep(); - } + } } -void Entity::Wake() -{ +void Entity::Wake() { auto* baseCombatAIComponent = GetComponent(); - - if (baseCombatAIComponent != nullptr) - { + + if (baseCombatAIComponent != nullptr) { baseCombatAIComponent->Wake(); } } -bool Entity::IsSleeping() const -{ +bool Entity::IsSleeping() const { return m_IsGhostingCandidate && m_Observers == 0; } -const NiPoint3& Entity::GetPosition() const -{ +const NiPoint3& Entity::GetPosition() const { if (!this) return NiPoint3::ZERO; auto* controllable = GetComponent(); - if (controllable != nullptr) - { + if (controllable != nullptr) { return controllable->GetPosition(); } auto* phantom = GetComponent(); - if (phantom != nullptr) - { + if (phantom != nullptr) { return phantom->GetPosition(); } auto* simple = GetComponent(); - if (simple != nullptr) - { + if (simple != nullptr) { return simple->GetPosition(); } auto* vehicel = GetComponent(); - if (vehicel != nullptr) - { + if (vehicel != nullptr) { return vehicel->GetPosition(); } return NiPoint3::ZERO; } -const NiQuaternion& Entity::GetRotation() const -{ +const NiQuaternion& Entity::GetRotation() const { auto* controllable = GetComponent(); - if (controllable != nullptr) - { + if (controllable != nullptr) { return controllable->GetRotation(); } auto* phantom = GetComponent(); - if (phantom != nullptr) - { + if (phantom != nullptr) { return phantom->GetRotation(); } auto* simple = GetComponent(); - if (simple != nullptr) - { + if (simple != nullptr) { return simple->GetRotation(); } - + auto* vehicel = GetComponent(); - if (vehicel != nullptr) - { + if (vehicel != nullptr) { return vehicel->GetRotation(); } return NiQuaternion::IDENTITY; } -void Entity::SetPosition(NiPoint3 position) -{ +void Entity::SetPosition(NiPoint3 position) { auto* controllable = GetComponent(); - if (controllable != nullptr) - { + if (controllable != nullptr) { controllable->SetPosition(position); } auto* phantom = GetComponent(); - if (phantom != nullptr) - { + if (phantom != nullptr) { phantom->SetPosition(position); } auto* simple = GetComponent(); - if (simple != nullptr) - { + if (simple != nullptr) { simple->SetPosition(position); } auto* vehicel = GetComponent(); - if (vehicel != nullptr) - { + if (vehicel != nullptr) { vehicel->SetPosition(position); } EntityManager::Instance()->SerializeEntity(this); } -void Entity::SetRotation(NiQuaternion rotation) -{ +void Entity::SetRotation(NiQuaternion rotation) { auto* controllable = GetComponent(); - if (controllable != nullptr) - { + if (controllable != nullptr) { controllable->SetRotation(rotation); } auto* phantom = GetComponent(); - if (phantom != nullptr) - { + if (phantom != nullptr) { phantom->SetRotation(rotation); } auto* simple = GetComponent(); - if (simple != nullptr) - { + if (simple != nullptr) { simple->SetRotation(rotation); } auto* vehicel = GetComponent(); - if (vehicel != nullptr) - { + if (vehicel != nullptr) { vehicel->SetRotation(rotation); } EntityManager::Instance()->SerializeEntity(this); } -bool Entity::GetBoolean(const std::u16string& name) const -{ +bool Entity::GetBoolean(const std::u16string& name) const { return GetVar(name); } -int32_t Entity::GetI32(const std::u16string& name) const -{ +int32_t Entity::GetI32(const std::u16string& name) const { return GetVar(name); } -int64_t Entity::GetI64(const std::u16string& name) const -{ +int64_t Entity::GetI64(const std::u16string& name) const { return GetVar(name); } -void Entity::SetBoolean(const std::u16string& name, const bool value) -{ +void Entity::SetBoolean(const std::u16string& name, const bool value) { SetVar(name, value); } -void Entity::SetI32(const std::u16string& name, const int32_t value) -{ +void Entity::SetI32(const std::u16string& name, const int32_t value) { SetVar(name, value); } -void Entity::SetI64(const std::u16string& name, const int64_t value) -{ +void Entity::SetI64(const std::u16string& name, const int64_t value) { SetVar(name, value); } -bool Entity::HasVar(const std::u16string& name) const -{ - for (auto* data : m_Settings) - { - if (data->GetKey() == name) - { +bool Entity::HasVar(const std::u16string& name) const { + for (auto* data : m_Settings) { + if (data->GetKey() == name) { return true; } } - + return false; } -uint16_t Entity::GetNetworkId() const -{ +uint16_t Entity::GetNetworkId() const { return m_NetworkID; } -void Entity::SetNetworkId(const uint16_t id) -{ +void Entity::SetNetworkId(const uint16_t id) { m_NetworkID = id; } -std::vector& Entity::GetTargetsInPhantom() -{ +std::vector& Entity::GetTargetsInPhantom() { std::vector valid; // Clean up invalid targets, like disconnected players - for (auto i = 0u; i < m_TargetsInPhantom.size(); ++i) - { + for (auto i = 0u; i < m_TargetsInPhantom.size(); ++i) { const auto id = m_TargetsInPhantom.at(i); auto* entity = EntityManager::Instance()->GetEntity(id); - if (entity == nullptr) - { + if (entity == nullptr) { continue; } @@ -2179,20 +2029,16 @@ std::vector& Entity::GetTargetsInPhantom() } void Entity::SendNetworkVar(const std::string& data, const SystemAddress& sysAddr) { - GameMessages::SendSetNetworkScriptVar(this, sysAddr, data); + GameMessages::SendSetNetworkScriptVar(this, sysAddr, data); } -LDFBaseData* Entity::GetVarData(const std::u16string& name) const -{ - for (auto* data : m_Settings) - { - if (data == nullptr) - { +LDFBaseData* Entity::GetVarData(const std::u16string& name) const { + for (auto* data : m_Settings) { + if (data == nullptr) { continue; } - if (data->GetKey() != name) - { + if (data->GetKey() != name) { continue; } @@ -2202,12 +2048,10 @@ LDFBaseData* Entity::GetVarData(const std::u16string& name) const return nullptr; } -std::string Entity::GetVarAsString(const std::u16string& name) const -{ +std::string Entity::GetVarAsString(const std::u16string& name) const { auto* data = GetVarData(name); - if (data == nullptr) - { + if (data == nullptr) { return ""; } @@ -2215,15 +2059,15 @@ std::string Entity::GetVarAsString(const std::u16string& name) const } void Entity::Resurrect() { - if (IsPlayer()) { - GameMessages::SendResurrect(this); - } + if (IsPlayer()) { + GameMessages::SendResurrect(this); + } } void Entity::AddToGroup(const std::string& group) { - if (std::find(m_Groups.begin(), m_Groups.end(), group) == m_Groups.end()) { - m_Groups.push_back(group); - } + if (std::find(m_Groups.begin(), m_Groups.end(), group) == m_Groups.end()) { + m_Groups.push_back(group); + } } void Entity::RetroactiveVaultSize() { diff --git a/dGame/Entity.h b/dGame/Entity.h index 85f992e8..6c0968f8 100644 --- a/dGame/Entity.h +++ b/dGame/Entity.h @@ -33,27 +33,27 @@ class Character; */ class Entity { public: - explicit Entity(const LWOOBJID& objectID, EntityInfo info, Entity* parentEntity = nullptr); - virtual ~Entity(); + explicit Entity(const LWOOBJID& objectID, EntityInfo info, Entity* parentEntity = nullptr); + virtual ~Entity(); virtual void Initialize(); - - bool operator==(const Entity& other) const; - bool operator!=(const Entity& other) const; + + bool operator==(const Entity& other) const; + bool operator!=(const Entity& other) const; /** * Getters */ - - const LWOOBJID& GetObjectID() const { return m_ObjectID; } - const LOT GetLOT() const { return m_TemplateID; } + const LWOOBJID& GetObjectID() const { return m_ObjectID; } - Character* GetCharacter() const { return m_Character; } + const LOT GetLOT() const { return m_TemplateID; } - uint8_t GetGMLevel() const { return m_GMLevel; } + Character* GetCharacter() const { return m_Character; } - uint8_t GetCollectibleID() const { return uint8_t(m_CollectibleID); } + uint8_t GetGMLevel() const { return m_GMLevel; } + + uint8_t GetCollectibleID() const { return uint8_t(m_CollectibleID); } Entity* GetParentEntity() const { return m_ParentEntity; } @@ -62,7 +62,7 @@ public: std::vector& GetGroups() { return m_Groups; }; Spawner* GetSpawner() const { return m_Spawner; } - + LWOOBJID GetSpawnerID() const { return m_SpawnerID; } const std::vector& GetSettings() const { return m_Settings; } @@ -71,7 +71,7 @@ public: bool GetIsDead() const; - bool GetPlayerReadyForUpdates() const { return m_PlayerIsReadyForUpdates;} + bool GetPlayerReadyForUpdates() const { return m_PlayerIsReadyForUpdates; } bool GetIsGhostingCandidate() const; @@ -86,7 +86,7 @@ public: const NiQuaternion& GetDefaultRotation() const; float GetDefaultScale() const; - + const NiPoint3& GetPosition() const; const NiQuaternion& GetRotation() const; @@ -99,9 +99,9 @@ public: * Setters */ - void SetCharacter(Character* value) { m_Character = value; } - - void SetGMLevel(uint8_t value); + void SetCharacter(Character* value) { m_Character = value; } + + void SetGMLevel(uint8_t value); void SetOwnerOverride(LWOOBJID value); @@ -118,14 +118,14 @@ public: virtual void SetRespawnPos(NiPoint3 position) {} virtual void SetRespawnRot(NiQuaternion rotation) {} - + virtual void SetSystemAddress(const SystemAddress& value) {}; /** * Component management */ - Component* GetComponent(int32_t componentID) const; + Component* GetComponent(int32_t componentID) const; template T* GetComponent() const; @@ -152,32 +152,32 @@ public: void CancelAllTimers(); void CancelTimer(const std::string& name); - void AddToGroup(const std::string& group); + void AddToGroup(const std::string& group); bool IsPlayer() const; std::unordered_map& GetComponents() { return m_Components; } // TODO: Remove - + void WriteBaseReplicaData(RakNet::BitStream* outBitStream, eReplicaPacketType packetType); void WriteComponents(RakNet::BitStream* outBitStream, eReplicaPacketType packetType); - void ResetFlags(); - void UpdateXMLDoc(tinyxml2::XMLDocument* doc); + void ResetFlags(); + void UpdateXMLDoc(tinyxml2::XMLDocument* doc); void Update(float deltaTime); // Events void OnCollisionProximity(LWOOBJID otherEntity, const std::string& proxName, const std::string& status); void OnCollisionPhantom(LWOOBJID otherEntity); - void OnCollisionLeavePhantom(LWOOBJID otherEntity); + void OnCollisionLeavePhantom(LWOOBJID otherEntity); - void OnFireEventServerSide(Entity* sender, std::string args, int32_t param1 = -1, int32_t param2 = -1, int32_t param3 = -1); - void OnActivityStateChangeRequest(const LWOOBJID senderID, const int32_t value1, const int32_t value2, - const std::u16string& stringValue); - void OnCinematicUpdate(Entity* self, Entity* sender, eCinematicEvent event, const std::u16string& pathName, - float_t pathTime, float_t totalTime, int32_t waypoint); + void OnFireEventServerSide(Entity* sender, std::string args, int32_t param1 = -1, int32_t param2 = -1, int32_t param3 = -1); + void OnActivityStateChangeRequest(const LWOOBJID senderID, const int32_t value1, const int32_t value2, + const std::u16string& stringValue); + void OnCinematicUpdate(Entity* self, Entity* sender, eCinematicEvent event, const std::u16string& pathName, + float_t pathTime, float_t totalTime, int32_t waypoint); void NotifyObject(Entity* sender, const std::string& name, int32_t param1 = 0, int32_t param2 = 0); void OnEmoteReceived(int32_t emote, Entity* target); - - void OnUse(Entity* originator); + + void OnUse(Entity* originator); void OnHitOrHealResult(Entity* attacker, int32_t damage); void OnHit(Entity* attacker); @@ -196,7 +196,7 @@ public: void Smash(const LWOOBJID source = LWOOBJID_EMPTY, const eKillType killType = eKillType::VIOLENT, const std::u16string& deathType = u""); void Kill(Entity* murderer = nullptr); - void AddRebuildCompleteCallback(const std::function& callback) const; + void AddRebuildCompleteCallback(const std::function& callback) const; void AddCollisionPhantomCallback(const std::function& callback); void AddDieCallback(const std::function& callback); void Resurrect(); @@ -222,15 +222,15 @@ public: /* * Utility */ - /** - * Retroactively corrects the model vault size due to incorrect initialization in a previous patch. - * - */ + /** + * Retroactively corrects the model vault size due to incorrect initialization in a previous patch. + * + */ void RetroactiveVaultSize(); bool GetBoolean(const std::u16string& name) const; int32_t GetI32(const std::u16string& name) const; int64_t GetI64(const std::u16string& name) const; - + void SetBoolean(const std::u16string& name, bool value); void SetI32(const std::u16string& name, int32_t value); void SetI64(const std::u16string& name, int64_t value); @@ -248,11 +248,11 @@ public: template void SetNetworkVar(const std::u16string& name, T value, const SystemAddress& sysAddr = UNASSIGNED_SYSTEM_ADDRESS); - template - void SetNetworkVar(const std::u16string& name, std::vector value, const SystemAddress& sysAddr = UNASSIGNED_SYSTEM_ADDRESS); + template + void SetNetworkVar(const std::u16string& name, std::vector value, const SystemAddress& sysAddr = UNASSIGNED_SYSTEM_ADDRESS); - template - T GetNetworkVar(const std::u16string& name); + template + T GetNetworkVar(const std::u16string& name); /** * Get the LDF value and cast it as T. @@ -278,37 +278,37 @@ public: Entity* GetScheduledKiller() { return m_ScheduleKiller; } protected: - LWOOBJID m_ObjectID; - - LOT m_TemplateID; - - std::vector m_Settings; - std::vector m_NetworkSettings; + LWOOBJID m_ObjectID; - NiPoint3 m_DefaultPosition; - NiQuaternion m_DefaultRotation; + LOT m_TemplateID; + + std::vector m_Settings; + std::vector m_NetworkSettings; + + NiPoint3 m_DefaultPosition; + NiQuaternion m_DefaultRotation; float m_Scale; Spawner* m_Spawner; - LWOOBJID m_SpawnerID; - - bool m_HasSpawnerNodeID; - uint32_t m_SpawnerNodeID; - + LWOOBJID m_SpawnerID; + + bool m_HasSpawnerNodeID; + uint32_t m_SpawnerNodeID; + LUTriggers::Trigger* m_Trigger; Character* m_Character; - - Entity* m_ParentEntity; //For spawners and the like + + Entity* m_ParentEntity; //For spawners and the like std::vector m_ChildEntities; - uint8_t m_GMLevel; - uint16_t m_CollectibleID; + uint8_t m_GMLevel; + uint16_t m_CollectibleID; std::vector m_Groups; uint16_t m_NetworkID; std::vector> m_DieCallbacks; - std::vector> m_PhantomCollisionCallbacks; - - std::unordered_map m_Components; //The int is the ID of the component + std::vector> m_PhantomCollisionCallbacks; + + std::unordered_map m_Components; //The int is the ID of the component std::vector m_Timers; std::vector m_PendingTimers; std::vector m_CallbackTimers; @@ -338,12 +338,10 @@ protected: */ template -bool Entity::TryGetComponent(const int32_t componentId, T*& component) const -{ +bool Entity::TryGetComponent(const int32_t componentId, T*& component) const { const auto& index = m_Components.find(componentId); - if (index == m_Components.end()) - { + if (index == m_Components.end()) { component = nullptr; return false; @@ -355,26 +353,22 @@ bool Entity::TryGetComponent(const int32_t componentId, T*& component) const } template -T* Entity::GetComponent() const -{ +T* Entity::GetComponent() const { return dynamic_cast(GetComponent(T::ComponentType)); } template -const T& Entity::GetVar(const std::u16string& name) const -{ +const T& Entity::GetVar(const std::u16string& name) const { auto* data = GetVarData(name); - if (data == nullptr) - { + if (data == nullptr) { return LDFData::Default; } auto* typed = dynamic_cast*>(data); - if (typed == nullptr) - { + if (typed == nullptr) { return LDFData::Default; } @@ -382,14 +376,12 @@ const T& Entity::GetVar(const std::u16string& name) const } template -T Entity::GetVarAs(const std::u16string& name) const -{ +T Entity::GetVarAs(const std::u16string& name) const { const auto data = GetVarAsString(name); T value; - if (!GeneralUtils::TryParse(data, value)) - { + if (!GeneralUtils::TryParse(data, value)) { return LDFData::Default; } @@ -397,12 +389,10 @@ T Entity::GetVarAs(const std::u16string& name) const } template -void Entity::SetVar(const std::u16string& name, T value) -{ +void Entity::SetVar(const std::u16string& name, T value) { auto* data = GetVarData(name); - if (data == nullptr) - { + if (data == nullptr) { auto* data = new LDFData(name, value); m_Settings.push_back(data); @@ -412,8 +402,7 @@ void Entity::SetVar(const std::u16string& name, T value) auto* typed = dynamic_cast*>(data); - if (typed == nullptr) - { + if (typed == nullptr) { return; } @@ -422,81 +411,81 @@ void Entity::SetVar(const std::u16string& name, T value) template void Entity::SetNetworkVar(const std::u16string& name, T value, const SystemAddress& sysAddr) { - LDFData* newData = nullptr; + LDFData* newData = nullptr; - for (auto* data :m_NetworkSettings) { - if (data->GetKey() != name) - continue; + for (auto* data : m_NetworkSettings) { + if (data->GetKey() != name) + continue; - newData = dynamic_cast*>(data); - if (newData != nullptr) { - newData->SetValue(value); - } else { // If we're changing types - m_NetworkSettings.erase( + newData = dynamic_cast*>(data); + if (newData != nullptr) { + newData->SetValue(value); + } else { // If we're changing types + m_NetworkSettings.erase( std::remove(m_NetworkSettings.begin(), m_NetworkSettings.end(), data), m_NetworkSettings.end() ); - delete data; - } + delete data; + } - break; - } + break; + } - if (newData == nullptr) { - newData = new LDFData(name, value); - } + if (newData == nullptr) { + newData = new LDFData(name, value); + } - m_NetworkSettings.push_back(newData); - SendNetworkVar(newData->GetString(true), sysAddr); + m_NetworkSettings.push_back(newData); + SendNetworkVar(newData->GetString(true), sysAddr); } template void Entity::SetNetworkVar(const std::u16string& name, std::vector values, const SystemAddress& sysAddr) { - std::stringstream updates; - auto index = 1; + std::stringstream updates; + auto index = 1; - for (const auto& value : values) { - LDFData* newData = nullptr; - const auto& indexedName = name + u"." + GeneralUtils::to_u16string(index); + for (const auto& value : values) { + LDFData* newData = nullptr; + const auto& indexedName = name + u"." + GeneralUtils::to_u16string(index); - for (auto* data : m_NetworkSettings) { - if (data->GetKey() != indexedName) - continue; + for (auto* data : m_NetworkSettings) { + if (data->GetKey() != indexedName) + continue; - newData = dynamic_cast*>(data); - newData->SetValue(value); - break; - } + newData = dynamic_cast*>(data); + newData->SetValue(value); + break; + } - if (newData == nullptr) { - newData = new LDFData(indexedName, value); - } + if (newData == nullptr) { + newData = new LDFData(indexedName, value); + } - m_NetworkSettings.push_back(newData); + m_NetworkSettings.push_back(newData); - if (index == values.size()) { - updates << newData->GetString(true); - } else { - updates << newData->GetString(true) << "\n"; - } + if (index == values.size()) { + updates << newData->GetString(true); + } else { + updates << newData->GetString(true) << "\n"; + } - index++; - } + index++; + } - SendNetworkVar(updates.str(), sysAddr); + SendNetworkVar(updates.str(), sysAddr); } template T Entity::GetNetworkVar(const std::u16string& name) { - for (auto* data : m_NetworkSettings) { - if (data == nullptr || data->GetKey() != name) - continue; + for (auto* data : m_NetworkSettings) { + if (data == nullptr || data->GetKey() != name) + continue; - auto* typed = dynamic_cast*>(data); - if (typed == nullptr) - continue; + auto* typed = dynamic_cast*>(data); + if (typed == nullptr) + continue; - return typed->GetValue(); - } + return typed->GetValue(); + } - return LDFData::Default; + return LDFData::Default; } diff --git a/dGame/EntityManager.cpp b/dGame/EntityManager.cpp index d6e6256f..02b8b59e 100644 --- a/dGame/EntityManager.cpp +++ b/dGame/EntityManager.cpp @@ -65,7 +65,7 @@ EntityManager::~EntityManager() { Entity* EntityManager::CreateEntity(EntityInfo info, User* user, Entity* parentEntity, const bool controller, const LWOOBJID explicitId) { // Determine the objectID for the new entity - LWOOBJID id; + LWOOBJID id; // If an explicit ID was provided, use it if (explicitId != LWOOBJID_EMPTY) { @@ -76,17 +76,17 @@ Entity* EntityManager::CreateEntity(EntityInfo info, User* user, Entity* parentE else if (user == nullptr || info.lot != 1) { // Entities with no ID already set, often spawned entities, we'll generate a new sequencial ID - if (info.id == 0) { + if (info.id == 0) { id = ObjectIDManager::Instance()->GenerateObjectID(); } // Entities with an ID already set, often level entities, we'll use that ID as a base - else { + else { id = info.id; } // Exclude the zone control object from any flags - if(!controller && info.lot != 14) { + if (!controller && info.lot != 14) { // The client flags means the client should render the entity id = GeneralUtils::SetBit(id, OBJECT_BIT_CLIENT); @@ -96,22 +96,21 @@ Entity* EntityManager::CreateEntity(EntityInfo info, User* user, Entity* parentE id = GeneralUtils::SetBit(id, OBJECT_BIT_SPAWNED); } } - } + } // For players, we'll use the persistent ID for that character else { id = user->GetLastUsedChar()->GetObjectID(); } - info.id = id; + info.id = id; Entity* entity; // Check if the entitty if a player, in case use the extended player entity class if (user != nullptr) { entity = new Player(id, info, user, parentEntity); - } - else { + } else { entity = new Entity(id, info, parentEntity); } @@ -133,7 +132,7 @@ Entity* EntityManager::CreateEntity(EntityInfo info, User* user, Entity* parentE m_SpawnPoints.insert_or_assign(GeneralUtils::UTF16ToWTF8(spawnName), entity->GetObjectID()); } - return entity; + return entity; } void EntityManager::DestroyEntity(const LWOOBJID& objectID) { @@ -229,11 +228,10 @@ void EntityManager::UpdateEntities(const float deltaTime) { m_EntitiesToDelete.clear(); } -Entity * EntityManager::GetEntity(const LWOOBJID& objectId) const { +Entity* EntityManager::GetEntity(const LWOOBJID& objectId) const { const auto& index = m_Entities.find(objectId); - if (index == m_Entities.end()) - { + if (index == m_Entities.end()) { return nullptr; } @@ -263,29 +261,26 @@ std::vector EntityManager::GetEntitiesByComponent(const int componentTy return withComp; } -std::vector EntityManager::GetEntitiesByLOT(const LOT &lot) const { - std::vector entities; +std::vector EntityManager::GetEntitiesByLOT(const LOT& lot) const { + std::vector entities; - for (const auto& entity : m_Entities) { - if (entity.second->GetLOT() == lot) - entities.push_back(entity.second); - } + for (const auto& entity : m_Entities) { + if (entity.second->GetLOT() == lot) + entities.push_back(entity.second); + } - return entities; + return entities; } -Entity* EntityManager::GetZoneControlEntity() const -{ +Entity* EntityManager::GetZoneControlEntity() const { return m_ZoneControlEntity; } -Entity* EntityManager::GetSpawnPointEntity(const std::string& spawnName) const -{ +Entity* EntityManager::GetSpawnPointEntity(const std::string& spawnName) const { // Lookup the spawn point entity in the map const auto& spawnPoint = m_SpawnPoints.find(spawnName); - if (spawnPoint == m_SpawnPoints.end()) - { + if (spawnPoint == m_SpawnPoints.end()) { return nullptr; } @@ -293,23 +288,18 @@ Entity* EntityManager::GetSpawnPointEntity(const std::string& spawnName) const return GetEntity(spawnPoint->second); } -const std::unordered_map& EntityManager::GetSpawnPointEntities() const -{ +const std::unordered_map& EntityManager::GetSpawnPointEntities() const { return m_SpawnPoints; } void EntityManager::ConstructEntity(Entity* entity, const SystemAddress& sysAddr, const bool skipChecks) { - if (entity->GetNetworkId() == 0) - { + if (entity->GetNetworkId() == 0) { uint16_t networkId; - if (!m_LostNetworkIds.empty()) - { + if (!m_LostNetworkIds.empty()) { networkId = m_LostNetworkIds.top(); m_LostNetworkIds.pop(); - } - else - { + } else { networkId = ++m_NetworkIdCounter; } @@ -318,18 +308,15 @@ void EntityManager::ConstructEntity(Entity* entity, const SystemAddress& sysAddr const auto checkGhosting = entity->GetIsGhostingCandidate(); - if (checkGhosting) - { + if (checkGhosting) { const auto& iter = std::find(m_EntitiesToGhost.begin(), m_EntitiesToGhost.end(), entity); - if (iter == m_EntitiesToGhost.end()) - { + if (iter == m_EntitiesToGhost.end()) { m_EntitiesToGhost.push_back(entity); } } - if (checkGhosting && sysAddr == UNASSIGNED_SYSTEM_ADDRESS) - { + if (checkGhosting && sysAddr == UNASSIGNED_SYSTEM_ADDRESS) { CheckGhosting(entity); return; @@ -346,38 +333,26 @@ void EntityManager::ConstructEntity(Entity* entity, const SystemAddress& sysAddr entity->WriteBaseReplicaData(&stream, PACKET_TYPE_CONSTRUCTION); entity->WriteComponents(&stream, PACKET_TYPE_CONSTRUCTION); - if (sysAddr == UNASSIGNED_SYSTEM_ADDRESS) - { - if (skipChecks) - { + if (sysAddr == UNASSIGNED_SYSTEM_ADDRESS) { + if (skipChecks) { Game::server->Send(&stream, UNASSIGNED_SYSTEM_ADDRESS, true); - } - else - { - for (auto* player : Player::GetAllPlayers()) - { - if (player->GetPlayerReadyForUpdates()) - { + } else { + for (auto* player : Player::GetAllPlayers()) { + if (player->GetPlayerReadyForUpdates()) { Game::server->Send(&stream, player->GetSystemAddress(), false); - } - else - { + } else { player->AddLimboConstruction(entity->GetObjectID()); } } } - } - else - { + } else { Game::server->Send(&stream, sysAddr, false); } // PacketUtils::SavePacket("[24]_"+std::to_string(entity->GetObjectID()) + "_" + std::to_string(m_SerializationCounter) + ".bin", (char*)stream.GetData(), stream.GetNumberOfBytesUsed()); - if (entity->IsPlayer()) - { - if (entity->GetGMLevel() > GAME_MASTER_LEVEL_CIVILIAN) - { + if (entity->IsPlayer()) { + if (entity->GetGMLevel() > GAME_MASTER_LEVEL_CIVILIAN) { GameMessages::SendToggleGMInvis(entity->GetObjectID(), true, sysAddr); } } @@ -387,18 +362,17 @@ void EntityManager::ConstructAllEntities(const SystemAddress& sysAddr) { //ZoneControl is special: ConstructEntity(m_ZoneControlEntity, sysAddr); - for (const auto& e : m_Entities) { + for (const auto& e : m_Entities) { if (e.second && (e.second->GetSpawnerID() != 0 || e.second->GetLOT() == 1) && !e.second->GetIsGhostingCandidate()) { ConstructEntity(e.second, sysAddr); } - } + } UpdateGhosting(Player::GetPlayer(sysAddr)); } void EntityManager::DestructEntity(Entity* entity, const SystemAddress& sysAddr) { - if (entity->GetNetworkId() == 0) - { + if (entity->GetNetworkId() == 0) { return; } @@ -409,23 +383,19 @@ void EntityManager::DestructEntity(Entity* entity, const SystemAddress& sysAddr) Game::server->Send(&stream, sysAddr, sysAddr == UNASSIGNED_SYSTEM_ADDRESS); - for (auto* player : Player::GetAllPlayers()) - { - if (!player->GetPlayerReadyForUpdates()) - { + for (auto* player : Player::GetAllPlayers()) { + if (!player->GetPlayerReadyForUpdates()) { player->RemoveLimboConstruction(entity->GetObjectID()); } } } void EntityManager::SerializeEntity(Entity* entity) { - if (entity->GetNetworkId() == 0) - { + if (entity->GetNetworkId() == 0) { return; } - if (std::find(m_EntitiesToSerialize.begin(), m_EntitiesToSerialize.end(), entity->GetObjectID()) == m_EntitiesToSerialize.end()) - { + if (std::find(m_EntitiesToSerialize.begin(), m_EntitiesToSerialize.end(), entity->GetObjectID()) == m_EntitiesToSerialize.end()) { m_EntitiesToSerialize.push_back(entity->GetObjectID()); } @@ -433,49 +403,40 @@ void EntityManager::SerializeEntity(Entity* entity) { } void EntityManager::DestructAllEntities(const SystemAddress& sysAddr) { - for (const auto& e : m_Entities) { + for (const auto& e : m_Entities) { DestructEntity(e.second, sysAddr); - } + } } -void EntityManager::SetGhostDistanceMax(float value) -{ +void EntityManager::SetGhostDistanceMax(float value) { m_GhostDistanceMaxSquared = value * value; } -float EntityManager::GetGhostDistanceMax() const -{ +float EntityManager::GetGhostDistanceMax() const { return std::sqrt(m_GhostDistanceMaxSquared); } -void EntityManager::SetGhostDistanceMin(float value) -{ +void EntityManager::SetGhostDistanceMin(float value) { m_GhostDistanceMinSqaured = value * value; } -float EntityManager::GetGhostDistanceMin() const -{ +float EntityManager::GetGhostDistanceMin() const { return std::sqrt(m_GhostDistanceMinSqaured); } -void EntityManager::QueueGhostUpdate(LWOOBJID playerID) -{ +void EntityManager::QueueGhostUpdate(LWOOBJID playerID) { const auto& iter = std::find(m_PlayersToUpdateGhosting.begin(), m_PlayersToUpdateGhosting.end(), playerID); - if (iter == m_PlayersToUpdateGhosting.end()) - { + if (iter == m_PlayersToUpdateGhosting.end()) { m_PlayersToUpdateGhosting.push_back(playerID); } } -void EntityManager::UpdateGhosting() -{ - for (const auto playerID : m_PlayersToUpdateGhosting) - { +void EntityManager::UpdateGhosting() { + for (const auto playerID : m_PlayersToUpdateGhosting) { auto* player = Player::GetPlayer(playerID); - if (player == nullptr) - { + if (player == nullptr) { continue; } @@ -485,25 +446,21 @@ void EntityManager::UpdateGhosting() m_PlayersToUpdateGhosting.clear(); } -void EntityManager::UpdateGhosting(Player* player) -{ - if (player == nullptr) - { +void EntityManager::UpdateGhosting(Player* player) { + if (player == nullptr) { return; } auto* missionComponent = player->GetComponent(); - if (missionComponent == nullptr) - { + if (missionComponent == nullptr) { return; } const auto& referencePoint = player->GetGhostReferencePoint(); const auto isOverride = player->GetGhostOverride(); - for (auto* entity : m_EntitiesToGhost) - { + for (auto* entity : m_EntitiesToGhost) { const auto isAudioEmitter = entity->GetLOT() == 6368; const auto& entityPoint = entity->GetPosition(); @@ -517,30 +474,24 @@ void EntityManager::UpdateGhosting(Player* player) auto ghostingDistanceMax = m_GhostDistanceMaxSquared; auto ghostingDistanceMin = m_GhostDistanceMinSqaured; - if (isAudioEmitter) - { + if (isAudioEmitter) { ghostingDistanceMax = ghostingDistanceMin; } - if (observed && distance > ghostingDistanceMax && !isOverride) - { + if (observed && distance > ghostingDistanceMax && !isOverride) { player->GhostEntity(id); DestructEntity(entity, player->GetSystemAddress()); entity->SetObservers(entity->GetObservers() - 1); - } - else if (!observed && ghostingDistanceMin > distance) - { + } else if (!observed && ghostingDistanceMin > distance) { // Check collectables, don't construct if it has been collected uint32_t collectionId = entity->GetCollectibleID(); - if (collectionId != 0) - { + if (collectionId != 0) { collectionId = static_cast(collectionId) + static_cast(Game::server->GetZoneID() << 8); - if (missionComponent->HasCollectible(collectionId)) - { + if (missionComponent->HasCollectible(collectionId)) { continue; } } @@ -554,10 +505,8 @@ void EntityManager::UpdateGhosting(Player* player) } } -void EntityManager::CheckGhosting(Entity* entity) -{ - if (entity == nullptr) - { +void EntityManager::CheckGhosting(Entity* entity) { + if (entity == nullptr) { return; } @@ -568,8 +517,7 @@ void EntityManager::CheckGhosting(Entity* entity) const auto isAudioEmitter = entity->GetLOT() == 6368; - for (auto* player : Player::GetAllPlayers()) - { + for (auto* player : Player::GetAllPlayers()) { const auto& entityPoint = player->GetGhostReferencePoint(); const int32_t id = entity->GetObjectID(); @@ -578,16 +526,13 @@ void EntityManager::CheckGhosting(Entity* entity) const auto distance = NiPoint3::DistanceSquared(referencePoint, entityPoint); - if (observed && distance > ghostingDistanceMax) - { + if (observed && distance > ghostingDistanceMax) { player->GhostEntity(id); DestructEntity(entity, player->GetSystemAddress()); entity->SetObservers(entity->GetObservers() - 1); - } - else if (!observed && ghostingDistanceMin > distance) - { + } else if (!observed && ghostingDistanceMin > distance) { player->ObserveEntity(id); ConstructEntity(entity, player->GetSystemAddress()); @@ -597,12 +542,9 @@ void EntityManager::CheckGhosting(Entity* entity) } } -Entity* EntityManager::GetGhostCandidate(int32_t id) -{ - for (auto* entity : m_EntitiesToGhost) - { - if (entity->GetObjectID() == id) - { +Entity* EntityManager::GetGhostCandidate(int32_t id) { + for (auto* entity : m_EntitiesToGhost) { + if (entity->GetObjectID() == id) { return entity; } } @@ -610,8 +552,7 @@ Entity* EntityManager::GetGhostCandidate(int32_t id) return nullptr; } -bool EntityManager::GetGhostingEnabled() const -{ +bool EntityManager::GetGhostingEnabled() const { return m_GhostingEnabled; } @@ -633,18 +574,15 @@ void EntityManager::ScheduleForKill(Entity* entity) { const auto objectId = entity->GetObjectID(); - if (std::count(m_EntitiesToKill.begin(), m_EntitiesToKill.end(), objectId)) - { + if (std::count(m_EntitiesToKill.begin(), m_EntitiesToKill.end(), objectId)) { return; } m_EntitiesToKill.push_back(objectId); } -void EntityManager::ScheduleForDeletion(LWOOBJID entity) -{ - if (std::count(m_EntitiesToDelete.begin(), m_EntitiesToDelete.end(), entity)) - { +void EntityManager::ScheduleForDeletion(LWOOBJID entity) { + if (std::count(m_EntitiesToDelete.begin(), m_EntitiesToDelete.end(), entity)) { return; } @@ -660,7 +598,6 @@ void EntityManager::FireEventServerSide(Entity* origin, std::string args) { } } -bool EntityManager::IsExcludedFromGhosting(LOT lot) -{ +bool EntityManager::IsExcludedFromGhosting(LOT lot) { return std::find(m_GhostingExcludedLOTs.begin(), m_GhostingExcludedLOTs.end(), lot) != m_GhostingExcludedLOTs.end(); } diff --git a/dGame/EntityManager.h b/dGame/EntityManager.h index 8fb2585c..40a98076 100644 --- a/dGame/EntityManager.h +++ b/dGame/EntityManager.h @@ -14,24 +14,24 @@ class User; class EntityManager { public: - static EntityManager* Instance() { + static EntityManager* Instance() { if (!m_Address) { m_Address = new EntityManager(); m_Address->Initialize(); } - + return m_Address; } - - void Initialize(); - ~EntityManager(); - - void UpdateEntities(float deltaTime); - Entity* CreateEntity(EntityInfo info, User* user = nullptr, Entity* parentEntity = nullptr, bool controller = false, LWOOBJID explicitId = LWOOBJID_EMPTY); - void DestroyEntity(const LWOOBJID& objectID); + void Initialize(); + + ~EntityManager(); + + void UpdateEntities(float deltaTime); + Entity* CreateEntity(EntityInfo info, User* user = nullptr, Entity* parentEntity = nullptr, bool controller = false, LWOOBJID explicitId = LWOOBJID_EMPTY); + void DestroyEntity(const LWOOBJID& objectID); void DestroyEntity(Entity* entity); - Entity* GetEntity(const LWOOBJID& objectId) const; + Entity* GetEntity(const LWOOBJID& objectId) const; std::vector GetEntitiesInGroup(const std::string& group); std::vector GetEntitiesByComponent(int componentType) const; std::vector GetEntitiesByLOT(const LOT& lot) const; @@ -48,12 +48,12 @@ public: const std::unordered_map GetAllEntities() const { return m_Entities; } #endif - void ConstructEntity(Entity * entity, const SystemAddress& sysAddr = UNASSIGNED_SYSTEM_ADDRESS, bool skipChecks = false); - void DestructEntity(Entity * entity, const SystemAddress& sysAddr = UNASSIGNED_SYSTEM_ADDRESS); + void ConstructEntity(Entity* entity, const SystemAddress& sysAddr = UNASSIGNED_SYSTEM_ADDRESS, bool skipChecks = false); + void DestructEntity(Entity* entity, const SystemAddress& sysAddr = UNASSIGNED_SYSTEM_ADDRESS); void SerializeEntity(Entity* entity); - - void ConstructAllEntities(const SystemAddress& sysAddr); - void DestructAllEntities(const SystemAddress& sysAddr); + + void ConstructAllEntities(const SystemAddress& sysAddr); + void DestructAllEntities(const SystemAddress& sysAddr); void SetGhostDistanceMax(float value); float GetGhostDistanceMax() const; @@ -69,19 +69,19 @@ public: void ResetFlags(); void ScheduleForKill(Entity* entity); - + void ScheduleForDeletion(LWOOBJID entity); void FireEventServerSide(Entity* origin, std::string args); - + static bool IsExcludedFromGhosting(LOT lot); private: - static EntityManager* m_Address; //For singleton method + static EntityManager* m_Address; //For singleton method static std::vector m_GhostingExcludedZones; static std::vector m_GhostingExcludedLOTs; - std::unordered_map m_Entities; + std::unordered_map m_Entities; std::vector m_EntitiesToKill; std::vector m_EntitiesToDelete; std::vector m_EntitiesToSerialize; @@ -95,7 +95,7 @@ private: float m_GhostDistanceMinSqaured = 100 * 100; float m_GhostDistanceMaxSquared = 150 * 150; bool m_GhostingEnabled = true; - + std::stack m_LostNetworkIds; // Map of spawnname to entity object ID diff --git a/dGame/LeaderboardManager.cpp b/dGame/LeaderboardManager.cpp index 793d402c..71a154bd 100644 --- a/dGame/LeaderboardManager.cpp +++ b/dGame/LeaderboardManager.cpp @@ -9,244 +9,243 @@ #include "dConfig.h" Leaderboard::Leaderboard(uint32_t gameID, uint32_t infoType, bool weekly, std::vector entries, - LWOOBJID relatedPlayer, LeaderboardType leaderboardType) { - this->relatedPlayer = relatedPlayer; - this->gameID = gameID; - this->weekly = weekly; - this->infoType = infoType; - this->entries = std::move(entries); - this->leaderboardType = leaderboardType; + LWOOBJID relatedPlayer, LeaderboardType leaderboardType) { + this->relatedPlayer = relatedPlayer; + this->gameID = gameID; + this->weekly = weekly; + this->infoType = infoType; + this->entries = std::move(entries); + this->leaderboardType = leaderboardType; } std::u16string Leaderboard::ToString() const { - std::string leaderboard; + std::string leaderboard; - leaderboard += "ADO.Result=7:1\n"; - leaderboard += "Result.Count=1:1\n"; - leaderboard += "Result[0].Index=0:RowNumber\n"; - leaderboard += "Result[0].RowCount=1:" + std::to_string(entries.size()) + "\n"; + leaderboard += "ADO.Result=7:1\n"; + leaderboard += "Result.Count=1:1\n"; + leaderboard += "Result[0].Index=0:RowNumber\n"; + leaderboard += "Result[0].RowCount=1:" + std::to_string(entries.size()) + "\n"; - auto index = 0; - for (const auto& entry : entries) { - leaderboard += "Result[0].Row[" + std::to_string(index) + "].LastPlayed=8:" + std::to_string(entry.lastPlayed) + "\n"; - leaderboard += "Result[0].Row[" + std::to_string(index) + "].CharacterID=8:" + std::to_string(entry.playerID) + "\n"; - leaderboard += "Result[0].Row[" + std::to_string(index) + "].NumPlayed=1:1\n"; - leaderboard += "Result[0].Row[" + std::to_string(index) + "].RowNumber=8:" + std::to_string(entry.placement) + "\n"; - leaderboard += "Result[0].Row[" + std::to_string(index) + "].Time=1:" + std::to_string(entry.time) + "\n"; + auto index = 0; + for (const auto& entry : entries) { + leaderboard += "Result[0].Row[" + std::to_string(index) + "].LastPlayed=8:" + std::to_string(entry.lastPlayed) + "\n"; + leaderboard += "Result[0].Row[" + std::to_string(index) + "].CharacterID=8:" + std::to_string(entry.playerID) + "\n"; + leaderboard += "Result[0].Row[" + std::to_string(index) + "].NumPlayed=1:1\n"; + leaderboard += "Result[0].Row[" + std::to_string(index) + "].RowNumber=8:" + std::to_string(entry.placement) + "\n"; + leaderboard += "Result[0].Row[" + std::to_string(index) + "].Time=1:" + std::to_string(entry.time) + "\n"; - // Only these minigames have a points system - if (leaderboardType == Survival || leaderboardType == ShootingGallery) { - leaderboard += "Result[0].Row[" + std::to_string(index) + "].Points=1:" + std::to_string(entry.score) + "\n"; - } else if (leaderboardType == SurvivalNS) { - leaderboard += "Result[0].Row[" + std::to_string(index) + "].Wave=1:" + std::to_string(entry.score) + "\n"; - } + // Only these minigames have a points system + if (leaderboardType == Survival || leaderboardType == ShootingGallery) { + leaderboard += "Result[0].Row[" + std::to_string(index) + "].Points=1:" + std::to_string(entry.score) + "\n"; + } else if (leaderboardType == SurvivalNS) { + leaderboard += "Result[0].Row[" + std::to_string(index) + "].Wave=1:" + std::to_string(entry.score) + "\n"; + } - leaderboard += "Result[0].Row[" + std::to_string(index) + "].name=0:" + entry.playerName + "\n"; - index++; - } + leaderboard += "Result[0].Row[" + std::to_string(index) + "].name=0:" + entry.playerName + "\n"; + index++; + } - return GeneralUtils::ASCIIToUTF16(leaderboard); + return GeneralUtils::ASCIIToUTF16(leaderboard); } std::vector Leaderboard::GetEntries() { - return entries; + return entries; } uint32_t Leaderboard::GetGameID() const { - return gameID; + return gameID; } uint32_t Leaderboard::GetInfoType() const { - return infoType; + return infoType; } void Leaderboard::Send(LWOOBJID targetID) const { - auto* player = EntityManager::Instance()->GetEntity(relatedPlayer); - if (player != nullptr) { - GameMessages::SendActivitySummaryLeaderboardData(targetID, this, player->GetSystemAddress()); - } + auto* player = EntityManager::Instance()->GetEntity(relatedPlayer); + if (player != nullptr) { + GameMessages::SendActivitySummaryLeaderboardData(targetID, this, player->GetSystemAddress()); + } } void LeaderboardManager::SaveScore(LWOOBJID playerID, uint32_t gameID, uint32_t score, uint32_t time) { - const auto* player = EntityManager::Instance()->GetEntity(playerID); - if (player == nullptr) - return; + const auto* player = EntityManager::Instance()->GetEntity(playerID); + if (player == nullptr) + return; - auto* character = player->GetCharacter(); - if (character == nullptr) - return; + auto* character = player->GetCharacter(); + if (character == nullptr) + return; - auto* select = Database::CreatePreppedStmt("SELECT time, score FROM leaderboard WHERE character_id = ? AND game_id = ?;"); + auto* select = Database::CreatePreppedStmt("SELECT time, score FROM leaderboard WHERE character_id = ? AND game_id = ?;"); - select->setUInt64(1, character->GetID()); - select->setInt(2, gameID); + select->setUInt64(1, character->GetID()); + select->setInt(2, gameID); - auto any = false; - auto* result = select->executeQuery(); - auto leaderboardType = GetLeaderboardType(gameID); + auto any = false; + auto* result = select->executeQuery(); + auto leaderboardType = GetLeaderboardType(gameID); - // Check if the new score is a high score - while (result->next()) { - any = true; + // Check if the new score is a high score + while (result->next()) { + any = true; - const auto storedTime = result->getInt(1); - const auto storedScore = result->getInt(2); - auto highscore = true; - bool classicSurvivalScoring = Game::config->GetValue("classic_survival_scoring") == "1"; + const auto storedTime = result->getInt(1); + const auto storedScore = result->getInt(2); + auto highscore = true; + bool classicSurvivalScoring = Game::config->GetValue("classic_survival_scoring") == "1"; - switch (leaderboardType) { - case ShootingGallery: - if (score <= storedScore) - highscore = false; - break; - case Racing: - if (time >= storedTime) - highscore = false; - break; - case MonumentRace: - if (time >= storedTime) - highscore = false; - break; - case FootRace: - if (time <= storedTime) - highscore = false; - break; - case Survival: - if (classicSurvivalScoring) { - if (time <= storedTime) { // Based on time (LU live) - highscore = false; - } - } - else { - if (score <= storedScore) // Based on score (DLU) - highscore = false; - } - break; - case SurvivalNS: - if (!(score > storedScore || (time < storedTime && score >= storedScore))) - highscore = false; - break; - default: - highscore = false; - } + switch (leaderboardType) { + case ShootingGallery: + if (score <= storedScore) + highscore = false; + break; + case Racing: + if (time >= storedTime) + highscore = false; + break; + case MonumentRace: + if (time >= storedTime) + highscore = false; + break; + case FootRace: + if (time <= storedTime) + highscore = false; + break; + case Survival: + if (classicSurvivalScoring) { + if (time <= storedTime) { // Based on time (LU live) + highscore = false; + } + } else { + if (score <= storedScore) // Based on score (DLU) + highscore = false; + } + break; + case SurvivalNS: + if (!(score > storedScore || (time < storedTime && score >= storedScore))) + highscore = false; + break; + default: + highscore = false; + } - if (!highscore) { - delete select; - delete result; - return; - } - } + if (!highscore) { + delete select; + delete result; + return; + } + } - delete select; - delete result; + delete select; + delete result; - if (any) { - auto* statement = Database::CreatePreppedStmt("UPDATE leaderboard SET time = ?, score = ?, last_played=SYSDATE() WHERE character_id = ? AND game_id = ?;"); - statement->setInt(1, time); - statement->setInt(2, score); - statement->setUInt64(3, character->GetID()); - statement->setInt(4, gameID); - statement->execute(); + if (any) { + auto* statement = Database::CreatePreppedStmt("UPDATE leaderboard SET time = ?, score = ?, last_played=SYSDATE() WHERE character_id = ? AND game_id = ?;"); + statement->setInt(1, time); + statement->setInt(2, score); + statement->setUInt64(3, character->GetID()); + statement->setInt(4, gameID); + statement->execute(); - delete statement; - } else { - // Note: last_played will be set to SYSDATE() by default when inserting into leaderboard - auto* statement = Database::CreatePreppedStmt("INSERT INTO leaderboard (character_id, game_id, time, score) VALUES (?, ?, ?, ?);"); - statement->setUInt64(1, character->GetID()); - statement->setInt(2, gameID); - statement->setInt(3, time); - statement->setInt(4, score); - statement->execute(); + delete statement; + } else { + // Note: last_played will be set to SYSDATE() by default when inserting into leaderboard + auto* statement = Database::CreatePreppedStmt("INSERT INTO leaderboard (character_id, game_id, time, score) VALUES (?, ?, ?, ?);"); + statement->setUInt64(1, character->GetID()); + statement->setInt(2, gameID); + statement->setInt(3, time); + statement->setInt(4, score); + statement->execute(); - delete statement; - } + delete statement; + } } -Leaderboard *LeaderboardManager::GetLeaderboard(uint32_t gameID, InfoType infoType, bool weekly, LWOOBJID playerID) { - auto leaderboardType = GetLeaderboardType(gameID); +Leaderboard* LeaderboardManager::GetLeaderboard(uint32_t gameID, InfoType infoType, bool weekly, LWOOBJID playerID) { + auto leaderboardType = GetLeaderboardType(gameID); - std::string query; - bool classicSurvivalScoring = Game::config->GetValue("classic_survival_scoring") == "1"; - switch (infoType) { - case InfoType::Standings: - switch (leaderboardType) { - case ShootingGallery: - query = standingsScoreQuery; // Shooting gallery is based on the highest score. - break; - case FootRace: - query = standingsTimeQuery; // The higher your time, the better for FootRace. - break; - case Survival: - query = classicSurvivalScoring ? standingsTimeQuery : standingsScoreQuery; - break; - case SurvivalNS: - query = standingsScoreQueryAsc; // BoNS is scored by highest wave (score) first, then time. - break; - default: - query = standingsTimeQueryAsc; // MonumentRace and Racing are based on the shortest time. - } - break; - case InfoType::Friends: - switch (leaderboardType) { - case ShootingGallery: - query = friendsScoreQuery; // Shooting gallery is based on the highest score. - break; - case FootRace: - query = friendsTimeQuery; // The higher your time, the better for FootRace. - break; - case Survival: - query = classicSurvivalScoring ? friendsTimeQuery : friendsScoreQuery; - break; - case SurvivalNS: - query = friendsScoreQueryAsc; // BoNS is scored by highest wave (score) first, then time. - break; - default: - query = friendsTimeQueryAsc; // MonumentRace and Racing are based on the shortest time. - } - break; + std::string query; + bool classicSurvivalScoring = Game::config->GetValue("classic_survival_scoring") == "1"; + switch (infoType) { + case InfoType::Standings: + switch (leaderboardType) { + case ShootingGallery: + query = standingsScoreQuery; // Shooting gallery is based on the highest score. + break; + case FootRace: + query = standingsTimeQuery; // The higher your time, the better for FootRace. + break; + case Survival: + query = classicSurvivalScoring ? standingsTimeQuery : standingsScoreQuery; + break; + case SurvivalNS: + query = standingsScoreQueryAsc; // BoNS is scored by highest wave (score) first, then time. + break; + default: + query = standingsTimeQueryAsc; // MonumentRace and Racing are based on the shortest time. + } + break; + case InfoType::Friends: + switch (leaderboardType) { + case ShootingGallery: + query = friendsScoreQuery; // Shooting gallery is based on the highest score. + break; + case FootRace: + query = friendsTimeQuery; // The higher your time, the better for FootRace. + break; + case Survival: + query = classicSurvivalScoring ? friendsTimeQuery : friendsScoreQuery; + break; + case SurvivalNS: + query = friendsScoreQueryAsc; // BoNS is scored by highest wave (score) first, then time. + break; + default: + query = friendsTimeQueryAsc; // MonumentRace and Racing are based on the shortest time. + } + break; - default: - switch (leaderboardType) { - case ShootingGallery: - query = topPlayersScoreQuery; // Shooting gallery is based on the highest score. - break; - case FootRace: - query = topPlayersTimeQuery; // The higher your time, the better for FootRace. - break; - case Survival: - query = classicSurvivalScoring ? topPlayersTimeQuery : topPlayersScoreQuery; - break; - case SurvivalNS: - query = topPlayersScoreQueryAsc; // BoNS is scored by highest wave (score) first, then time. - break; - default: - query = topPlayersTimeQueryAsc; // MonumentRace and Racing are based on the shortest time. - } - } + default: + switch (leaderboardType) { + case ShootingGallery: + query = topPlayersScoreQuery; // Shooting gallery is based on the highest score. + break; + case FootRace: + query = topPlayersTimeQuery; // The higher your time, the better for FootRace. + break; + case Survival: + query = classicSurvivalScoring ? topPlayersTimeQuery : topPlayersScoreQuery; + break; + case SurvivalNS: + query = topPlayersScoreQueryAsc; // BoNS is scored by highest wave (score) first, then time. + break; + default: + query = topPlayersTimeQueryAsc; // MonumentRace and Racing are based on the shortest time. + } + } - auto* statement = Database::CreatePreppedStmt(query); - statement->setUInt(1, gameID); + auto* statement = Database::CreatePreppedStmt(query); + statement->setUInt(1, gameID); - // Only the standings and friends leaderboards require the character ID to be set - if (infoType == Standings || infoType == Friends) { - auto characterID = 0; + // Only the standings and friends leaderboards require the character ID to be set + if (infoType == Standings || infoType == Friends) { + auto characterID = 0; - const auto* player = EntityManager::Instance()->GetEntity(playerID); - if (player != nullptr) { - auto* character = player->GetCharacter(); - if (character != nullptr) - characterID = character->GetID(); - } + const auto* player = EntityManager::Instance()->GetEntity(playerID); + if (player != nullptr) { + auto* character = player->GetCharacter(); + if (character != nullptr) + characterID = character->GetID(); + } - statement->setUInt64(2, characterID); - } + statement->setUInt64(2, characterID); + } - auto* res = statement->executeQuery(); + auto* res = statement->executeQuery(); - std::vector entries {}; + std::vector entries{}; - uint32_t index = 0; - while (res->next()) { + uint32_t index = 0; + while (res->next()) { LeaderboardEntry entry; entry.playerID = res->getUInt64(4); entry.playerName = res->getString(5); @@ -256,124 +255,124 @@ Leaderboard *LeaderboardManager::GetLeaderboard(uint32_t gameID, InfoType infoTy entry.lastPlayed = res->getUInt(6); entries.push_back(entry); - index++; - } + index++; + } - delete res; - delete statement; + delete res; + delete statement; - return new Leaderboard(gameID, infoType, weekly, entries, playerID, leaderboardType); + return new Leaderboard(gameID, infoType, weekly, entries, playerID, leaderboardType); } void LeaderboardManager::SendLeaderboard(uint32_t gameID, InfoType infoType, bool weekly, LWOOBJID targetID, - LWOOBJID playerID) { - const auto* leaderboard = LeaderboardManager::GetLeaderboard(gameID, infoType, weekly, playerID); - leaderboard->Send(targetID); - delete leaderboard; + LWOOBJID playerID) { + const auto* leaderboard = LeaderboardManager::GetLeaderboard(gameID, infoType, weekly, playerID); + leaderboard->Send(targetID); + delete leaderboard; } LeaderboardType LeaderboardManager::GetLeaderboardType(uint32_t gameID) { - auto* activitiesTable = CDClientManager::Instance()->GetTable("Activities"); - std::vector activities = activitiesTable->Query([=](const CDActivities& entry) { - return (entry.ActivityID == gameID); - }); + auto* activitiesTable = CDClientManager::Instance()->GetTable("Activities"); + std::vector activities = activitiesTable->Query([=](const CDActivities& entry) { + return (entry.ActivityID == gameID); + }); - for (const auto& activity : activities) { - return static_cast(activity.leaderboardType); - } + for (const auto& activity : activities) { + return static_cast(activity.leaderboardType); + } - return LeaderboardType::None; + return LeaderboardType::None; } const std::string LeaderboardManager::topPlayersScoreQuery = - "WITH leaderboard_vales AS ( " - " SELECT l.time, l.score, UNIX_TIMESTAMP(l.last_played) last_played, c.name, c.id, " - "RANK() OVER ( ORDER BY l.score DESC, l.time DESC, last_played ) leaderboard_rank " - " FROM leaderboard l " - "INNER JOIN charinfo c ON l.character_id = c.id " - "WHERE l.game_id = ? " - "ORDER BY leaderboard_rank) " - "SELECT time, score, leaderboard_rank, id, name, last_played " - "FROM leaderboard_vales LIMIT 11;"; +"WITH leaderboard_vales AS ( " +" SELECT l.time, l.score, UNIX_TIMESTAMP(l.last_played) last_played, c.name, c.id, " +"RANK() OVER ( ORDER BY l.score DESC, l.time DESC, last_played ) leaderboard_rank " +" FROM leaderboard l " +"INNER JOIN charinfo c ON l.character_id = c.id " +"WHERE l.game_id = ? " +"ORDER BY leaderboard_rank) " +"SELECT time, score, leaderboard_rank, id, name, last_played " +"FROM leaderboard_vales LIMIT 11;"; const std::string LeaderboardManager::friendsScoreQuery = - "WITH leaderboard_vales AS ( " - " SELECT l.time, l.score, UNIX_TIMESTAMP(l.last_played) last_played, c.name, c.id, f.friend_id, f.player_id, " - " RANK() OVER ( ORDER BY l.score DESC, l.time DESC, last_played ) leaderboard_rank " - " FROM leaderboard l " - " INNER JOIN charinfo c ON l.character_id = c.id " - " INNER JOIN friends f ON f.player_id = c.id " - " WHERE l.game_id = ? " - " ORDER BY leaderboard_rank), " - " personal_values AS ( " - " SELECT id as related_player_id, " - " GREATEST(CAST(leaderboard_rank AS SIGNED) - 5, 1) AS min_rank, " - " GREATEST(leaderboard_rank + 5, 11) AS max_rank " - " FROM leaderboard_vales WHERE leaderboard_vales.id = ? LIMIT 1) " - "SELECT time, score, leaderboard_rank, id, name, last_played " - "FROM leaderboard_vales, personal_values " - "WHERE leaderboard_rank BETWEEN min_rank AND max_rank AND (player_id = related_player_id OR friend_id = related_player_id);"; +"WITH leaderboard_vales AS ( " +" SELECT l.time, l.score, UNIX_TIMESTAMP(l.last_played) last_played, c.name, c.id, f.friend_id, f.player_id, " +" RANK() OVER ( ORDER BY l.score DESC, l.time DESC, last_played ) leaderboard_rank " +" FROM leaderboard l " +" INNER JOIN charinfo c ON l.character_id = c.id " +" INNER JOIN friends f ON f.player_id = c.id " +" WHERE l.game_id = ? " +" ORDER BY leaderboard_rank), " +" personal_values AS ( " +" SELECT id as related_player_id, " +" GREATEST(CAST(leaderboard_rank AS SIGNED) - 5, 1) AS min_rank, " +" GREATEST(leaderboard_rank + 5, 11) AS max_rank " +" FROM leaderboard_vales WHERE leaderboard_vales.id = ? LIMIT 1) " +"SELECT time, score, leaderboard_rank, id, name, last_played " +"FROM leaderboard_vales, personal_values " +"WHERE leaderboard_rank BETWEEN min_rank AND max_rank AND (player_id = related_player_id OR friend_id = related_player_id);"; const std::string LeaderboardManager::standingsScoreQuery = - "WITH leaderboard_vales AS ( " - " SELECT l.time, l.score, UNIX_TIMESTAMP(l.last_played) last_played, c.name, c.id, " - " RANK() OVER ( ORDER BY l.score DESC, l.time DESC, last_played ) leaderboard_rank " - " FROM leaderboard l " - " INNER JOIN charinfo c ON l.character_id = c.id " - " WHERE l.game_id = ? " - " ORDER BY leaderboard_rank), " - "personal_values AS ( " - " SELECT GREATEST(CAST(leaderboard_rank AS SIGNED) - 5, 1) AS min_rank, " - " GREATEST(leaderboard_rank + 5, 11) AS max_rank " - " FROM leaderboard_vales WHERE id = ? LIMIT 1) " - "SELECT time, score, leaderboard_rank, id, name, last_played " - "FROM leaderboard_vales, personal_values " - "WHERE leaderboard_rank BETWEEN min_rank AND max_rank;"; +"WITH leaderboard_vales AS ( " +" SELECT l.time, l.score, UNIX_TIMESTAMP(l.last_played) last_played, c.name, c.id, " +" RANK() OVER ( ORDER BY l.score DESC, l.time DESC, last_played ) leaderboard_rank " +" FROM leaderboard l " +" INNER JOIN charinfo c ON l.character_id = c.id " +" WHERE l.game_id = ? " +" ORDER BY leaderboard_rank), " +"personal_values AS ( " +" SELECT GREATEST(CAST(leaderboard_rank AS SIGNED) - 5, 1) AS min_rank, " +" GREATEST(leaderboard_rank + 5, 11) AS max_rank " +" FROM leaderboard_vales WHERE id = ? LIMIT 1) " +"SELECT time, score, leaderboard_rank, id, name, last_played " +"FROM leaderboard_vales, personal_values " +"WHERE leaderboard_rank BETWEEN min_rank AND max_rank;"; const std::string LeaderboardManager::topPlayersScoreQueryAsc = - "WITH leaderboard_vales AS ( " - " SELECT l.time, l.score, UNIX_TIMESTAMP(l.last_played) last_played, c.name, c.id, " - "RANK() OVER ( ORDER BY l.score DESC, l.time ASC, last_played ) leaderboard_rank " - " FROM leaderboard l " - "INNER JOIN charinfo c ON l.character_id = c.id " - "WHERE l.game_id = ? " - "ORDER BY leaderboard_rank) " - "SELECT time, score, leaderboard_rank, id, name, last_played " - "FROM leaderboard_vales LIMIT 11;"; +"WITH leaderboard_vales AS ( " +" SELECT l.time, l.score, UNIX_TIMESTAMP(l.last_played) last_played, c.name, c.id, " +"RANK() OVER ( ORDER BY l.score DESC, l.time ASC, last_played ) leaderboard_rank " +" FROM leaderboard l " +"INNER JOIN charinfo c ON l.character_id = c.id " +"WHERE l.game_id = ? " +"ORDER BY leaderboard_rank) " +"SELECT time, score, leaderboard_rank, id, name, last_played " +"FROM leaderboard_vales LIMIT 11;"; const std::string LeaderboardManager::friendsScoreQueryAsc = - "WITH leaderboard_vales AS ( " - " SELECT l.time, l.score, UNIX_TIMESTAMP(l.last_played) last_played, c.name, c.id, f.friend_id, f.player_id, " - " RANK() OVER ( ORDER BY l.score DESC, l.time ASC, last_played ) leaderboard_rank " - " FROM leaderboard l " - " INNER JOIN charinfo c ON l.character_id = c.id " - " INNER JOIN friends f ON f.player_id = c.id " - " WHERE l.game_id = ? " - " ORDER BY leaderboard_rank), " - " personal_values AS ( " - " SELECT id as related_player_id, " - " GREATEST(CAST(leaderboard_rank AS SIGNED) - 5, 1) AS min_rank, " - " GREATEST(leaderboard_rank + 5, 11) AS max_rank " - " FROM leaderboard_vales WHERE leaderboard_vales.id = ? LIMIT 1) " - "SELECT time, score, leaderboard_rank, id, name, last_played " - "FROM leaderboard_vales, personal_values " - "WHERE leaderboard_rank BETWEEN min_rank AND max_rank AND (player_id = related_player_id OR friend_id = related_player_id);"; +"WITH leaderboard_vales AS ( " +" SELECT l.time, l.score, UNIX_TIMESTAMP(l.last_played) last_played, c.name, c.id, f.friend_id, f.player_id, " +" RANK() OVER ( ORDER BY l.score DESC, l.time ASC, last_played ) leaderboard_rank " +" FROM leaderboard l " +" INNER JOIN charinfo c ON l.character_id = c.id " +" INNER JOIN friends f ON f.player_id = c.id " +" WHERE l.game_id = ? " +" ORDER BY leaderboard_rank), " +" personal_values AS ( " +" SELECT id as related_player_id, " +" GREATEST(CAST(leaderboard_rank AS SIGNED) - 5, 1) AS min_rank, " +" GREATEST(leaderboard_rank + 5, 11) AS max_rank " +" FROM leaderboard_vales WHERE leaderboard_vales.id = ? LIMIT 1) " +"SELECT time, score, leaderboard_rank, id, name, last_played " +"FROM leaderboard_vales, personal_values " +"WHERE leaderboard_rank BETWEEN min_rank AND max_rank AND (player_id = related_player_id OR friend_id = related_player_id);"; const std::string LeaderboardManager::standingsScoreQueryAsc = - "WITH leaderboard_vales AS ( " - " SELECT l.time, l.score, UNIX_TIMESTAMP(l.last_played) last_played, c.name, c.id, " - " RANK() OVER ( ORDER BY l.score DESC, l.time ASC, last_played ) leaderboard_rank " - " FROM leaderboard l " - " INNER JOIN charinfo c ON l.character_id = c.id " - " WHERE l.game_id = ? " - " ORDER BY leaderboard_rank), " - "personal_values AS ( " - " SELECT GREATEST(CAST(leaderboard_rank AS SIGNED) - 5, 1) AS min_rank, " - " GREATEST(leaderboard_rank + 5, 11) AS max_rank " - " FROM leaderboard_vales WHERE id = ? LIMIT 1) " - "SELECT time, score, leaderboard_rank, id, name, last_played " - "FROM leaderboard_vales, personal_values " - "WHERE leaderboard_rank BETWEEN min_rank AND max_rank;"; +"WITH leaderboard_vales AS ( " +" SELECT l.time, l.score, UNIX_TIMESTAMP(l.last_played) last_played, c.name, c.id, " +" RANK() OVER ( ORDER BY l.score DESC, l.time ASC, last_played ) leaderboard_rank " +" FROM leaderboard l " +" INNER JOIN charinfo c ON l.character_id = c.id " +" WHERE l.game_id = ? " +" ORDER BY leaderboard_rank), " +"personal_values AS ( " +" SELECT GREATEST(CAST(leaderboard_rank AS SIGNED) - 5, 1) AS min_rank, " +" GREATEST(leaderboard_rank + 5, 11) AS max_rank " +" FROM leaderboard_vales WHERE id = ? LIMIT 1) " +"SELECT time, score, leaderboard_rank, id, name, last_played " +"FROM leaderboard_vales, personal_values " +"WHERE leaderboard_rank BETWEEN min_rank AND max_rank;"; const std::string LeaderboardManager::topPlayersTimeQuery = "WITH leaderboard_vales AS ( " diff --git a/dGame/LeaderboardManager.h b/dGame/LeaderboardManager.h index c4479f1a..cabdf2d6 100644 --- a/dGame/LeaderboardManager.h +++ b/dGame/LeaderboardManager.h @@ -4,77 +4,77 @@ #include "dCommonVars.h" struct LeaderboardEntry { - uint64_t playerID; - std::string playerName; - uint32_t time; - uint32_t score; - uint32_t placement; - time_t lastPlayed; + uint64_t playerID; + std::string playerName; + uint32_t time; + uint32_t score; + uint32_t placement; + time_t lastPlayed; }; enum InfoType : uint32_t { - Top, // Top 11 all time players - Standings, // Ranking of the current player - Friends // Ranking between friends + Top, // Top 11 all time players + Standings, // Ranking of the current player + Friends // Ranking between friends }; enum LeaderboardType : uint32_t { - ShootingGallery, - Racing, - MonumentRace, - FootRace, - Survival = 5, - SurvivalNS = 6, - None = UINT_MAX + ShootingGallery, + Racing, + MonumentRace, + FootRace, + Survival = 5, + SurvivalNS = 6, + None = UINT_MAX }; class Leaderboard { public: - Leaderboard(uint32_t gameID, uint32_t infoType, bool weekly, std::vector entries, - LWOOBJID relatedPlayer = LWOOBJID_EMPTY, LeaderboardType = None); - std::vector GetEntries(); - [[nodiscard]] std::u16string ToString() const; - [[nodiscard]] uint32_t GetGameID() const; - [[nodiscard]] uint32_t GetInfoType() const; - void Send(LWOOBJID targetID) const; + Leaderboard(uint32_t gameID, uint32_t infoType, bool weekly, std::vector entries, + LWOOBJID relatedPlayer = LWOOBJID_EMPTY, LeaderboardType = None); + std::vector GetEntries(); + [[nodiscard]] std::u16string ToString() const; + [[nodiscard]] uint32_t GetGameID() const; + [[nodiscard]] uint32_t GetInfoType() const; + void Send(LWOOBJID targetID) const; private: - std::vector entries {}; - LWOOBJID relatedPlayer; - uint32_t gameID; - uint32_t infoType; - LeaderboardType leaderboardType; - bool weekly; + std::vector entries{}; + LWOOBJID relatedPlayer; + uint32_t gameID; + uint32_t infoType; + LeaderboardType leaderboardType; + bool weekly; }; class LeaderboardManager { public: - static LeaderboardManager* Instance() { - if (address == nullptr) - address = new LeaderboardManager; - return address; - } - static void SendLeaderboard(uint32_t gameID, InfoType infoType, bool weekly, LWOOBJID targetID, - LWOOBJID playerID = LWOOBJID_EMPTY); - static Leaderboard* GetLeaderboard(uint32_t gameID, InfoType infoType, bool weekly, LWOOBJID playerID = LWOOBJID_EMPTY); - static void SaveScore(LWOOBJID playerID, uint32_t gameID, uint32_t score, uint32_t time); - static LeaderboardType GetLeaderboardType(uint32_t gameID); + static LeaderboardManager* Instance() { + if (address == nullptr) + address = new LeaderboardManager; + return address; + } + static void SendLeaderboard(uint32_t gameID, InfoType infoType, bool weekly, LWOOBJID targetID, + LWOOBJID playerID = LWOOBJID_EMPTY); + static Leaderboard* GetLeaderboard(uint32_t gameID, InfoType infoType, bool weekly, LWOOBJID playerID = LWOOBJID_EMPTY); + static void SaveScore(LWOOBJID playerID, uint32_t gameID, uint32_t score, uint32_t time); + static LeaderboardType GetLeaderboardType(uint32_t gameID); private: - static LeaderboardManager* address; + static LeaderboardManager* address; - // Modified 12/12/2021: Existing queries were renamed to be more descriptive. - static const std::string topPlayersScoreQuery; - static const std::string friendsScoreQuery; - static const std::string standingsScoreQuery; - static const std::string topPlayersScoreQueryAsc; - static const std::string friendsScoreQueryAsc; - static const std::string standingsScoreQueryAsc; + // Modified 12/12/2021: Existing queries were renamed to be more descriptive. + static const std::string topPlayersScoreQuery; + static const std::string friendsScoreQuery; + static const std::string standingsScoreQuery; + static const std::string topPlayersScoreQueryAsc; + static const std::string friendsScoreQueryAsc; + static const std::string standingsScoreQueryAsc; - // Added 12/12/2021: Queries dictated by time are needed for certain minigames. - static const std::string topPlayersTimeQuery; - static const std::string friendsTimeQuery; - static const std::string standingsTimeQuery; - static const std::string topPlayersTimeQueryAsc; - static const std::string friendsTimeQueryAsc; - static const std::string standingsTimeQueryAsc; + // Added 12/12/2021: Queries dictated by time are needed for certain minigames. + static const std::string topPlayersTimeQuery; + static const std::string friendsTimeQuery; + static const std::string standingsTimeQuery; + static const std::string topPlayersTimeQueryAsc; + static const std::string friendsTimeQueryAsc; + static const std::string standingsTimeQueryAsc; }; diff --git a/dGame/Player.cpp b/dGame/Player.cpp index 56ae5a70..dd269f95 100644 --- a/dGame/Player.cpp +++ b/dGame/Player.cpp @@ -17,8 +17,7 @@ std::vector Player::m_Players = {}; -Player::Player(const LWOOBJID& objectID, const EntityInfo info, User* user, Entity* parentEntity) : Entity(objectID, info, parentEntity) -{ +Player::Player(const LWOOBJID& objectID, const EntityInfo info, User* user, Entity* parentEntity) : Entity(objectID, info, parentEntity) { m_ParentUser = user; m_Character = m_ParentUser->GetLastUsedChar(); m_ParentUser->SetLoggedInChar(objectID); @@ -38,58 +37,48 @@ Player::Player(const LWOOBJID& objectID, const EntityInfo info, User* user, Enti const auto& iter = std::find(m_Players.begin(), m_Players.end(), this); - if (iter != m_Players.end()) - { + if (iter != m_Players.end()) { return; } m_Players.push_back(this); } -User* Player::GetParentUser() const -{ +User* Player::GetParentUser() const { return m_ParentUser; } -SystemAddress Player::GetSystemAddress() const -{ +SystemAddress Player::GetSystemAddress() const { return m_SystemAddress; } -void Player::SetSystemAddress(const SystemAddress& value) -{ +void Player::SetSystemAddress(const SystemAddress& value) { m_SystemAddress = value; } -void Player::SetRespawnPos(const NiPoint3 position) -{ +void Player::SetRespawnPos(const NiPoint3 position) { m_respawnPos = position; m_Character->SetRespawnPoint(dZoneManager::Instance()->GetZone()->GetWorldID(), position); } -void Player::SetRespawnRot(const NiQuaternion rotation) -{ +void Player::SetRespawnRot(const NiQuaternion rotation) { m_respawnRot = rotation; } -NiPoint3 Player::GetRespawnPosition() const -{ +NiPoint3 Player::GetRespawnPosition() const { return m_respawnPos; } -NiQuaternion Player::GetRespawnRotation() const -{ +NiQuaternion Player::GetRespawnRotation() const { return m_respawnRot; } -void Player::SendMail(const LWOOBJID sender, const std::string& senderName, const std::string& subject, const std::string& body, LOT attachment, uint16_t attachmentCount) const -{ +void Player::SendMail(const LWOOBJID sender, const std::string& senderName, const std::string& subject, const std::string& body, LOT attachment, uint16_t attachmentCount) const { Mail::SendMail(sender, senderName, this, subject, body, attachment, attachmentCount); } -void Player::SendToZone(LWOMAPID zoneId, LWOCLONEID cloneId) -{ +void Player::SendToZone(LWOMAPID zoneId, LWOCLONEID cloneId) { const auto objid = GetObjectID(); ZoneInstanceManager::Instance()->RequestZoneTransfer(Game::server, zoneId, cloneId, false, [objid](bool mythranShift, uint32_t zoneID, uint32_t zoneInstance, uint32_t zoneClone, std::string serverIP, uint16_t serverPort) { @@ -118,41 +107,34 @@ void Player::SendToZone(LWOMAPID zoneId, LWOCLONEID cloneId) EntityManager::Instance()->DestructEntity(entity); return; - }); + }); } -void Player::AddLimboConstruction(LWOOBJID objectId) -{ +void Player::AddLimboConstruction(LWOOBJID objectId) { const auto& iter = std::find(m_LimboConstructions.begin(), m_LimboConstructions.end(), objectId); - if (iter != m_LimboConstructions.end()) - { + if (iter != m_LimboConstructions.end()) { return; } m_LimboConstructions.push_back(objectId); } -void Player::RemoveLimboConstruction(LWOOBJID objectId) -{ +void Player::RemoveLimboConstruction(LWOOBJID objectId) { const auto& iter = std::find(m_LimboConstructions.begin(), m_LimboConstructions.end(), objectId); - if (iter == m_LimboConstructions.end()) - { + if (iter == m_LimboConstructions.end()) { return; } m_LimboConstructions.erase(iter); } -void Player::ConstructLimboEntities() -{ - for (const auto objectId : m_LimboConstructions) - { +void Player::ConstructLimboEntities() { + for (const auto objectId : m_LimboConstructions) { auto* entity = EntityManager::Instance()->GetEntity(objectId); - if (entity == nullptr) - { + if (entity == nullptr) { continue; } @@ -162,52 +144,41 @@ void Player::ConstructLimboEntities() m_LimboConstructions.clear(); } -std::map& Player::GetDroppedLoot() -{ +std::map& Player::GetDroppedLoot() { return m_DroppedLoot; } -const NiPoint3& Player::GetGhostReferencePoint() const -{ +const NiPoint3& Player::GetGhostReferencePoint() const { return m_GhostOverride ? m_GhostOverridePoint : m_GhostReferencePoint; } -const NiPoint3& Player::GetOriginGhostReferencePoint() const -{ +const NiPoint3& Player::GetOriginGhostReferencePoint() const { return m_GhostReferencePoint; } -void Player::SetGhostReferencePoint(const NiPoint3& value) -{ +void Player::SetGhostReferencePoint(const NiPoint3& value) { m_GhostReferencePoint = value; } -void Player::SetGhostOverridePoint(const NiPoint3& value) -{ +void Player::SetGhostOverridePoint(const NiPoint3& value) { m_GhostOverridePoint = value; } -const NiPoint3& Player::GetGhostOverridePoint() const -{ +const NiPoint3& Player::GetGhostOverridePoint() const { return m_GhostOverridePoint; } -void Player::SetGhostOverride(bool value) -{ +void Player::SetGhostOverride(bool value) { m_GhostOverride = value; } -bool Player::GetGhostOverride() const -{ +bool Player::GetGhostOverride() const { return m_GhostOverride; } -void Player::ObserveEntity(int32_t id) -{ - for (int32_t i = 0; i < m_ObservedEntitiesUsed; i++) - { - if (m_ObservedEntities[i] == 0 || m_ObservedEntities[i] == id) - { +void Player::ObserveEntity(int32_t id) { + for (int32_t i = 0; i < m_ObservedEntitiesUsed; i++) { + if (m_ObservedEntities[i] == 0 || m_ObservedEntities[i] == id) { m_ObservedEntities[i] = id; return; @@ -216,8 +187,7 @@ void Player::ObserveEntity(int32_t id) const auto index = m_ObservedEntitiesUsed++; - if (m_ObservedEntitiesUsed > m_ObservedEntitiesLength) - { + if (m_ObservedEntitiesUsed > m_ObservedEntitiesLength) { m_ObservedEntities.resize(m_ObservedEntitiesLength + m_ObservedEntitiesLength); m_ObservedEntitiesLength = m_ObservedEntitiesLength + m_ObservedEntitiesLength; @@ -226,12 +196,9 @@ void Player::ObserveEntity(int32_t id) m_ObservedEntities[index] = id; } -bool Player::IsObserved(int32_t id) -{ - for (int32_t i = 0; i < m_ObservedEntitiesUsed; i++) - { - if (m_ObservedEntities[i] == id) - { +bool Player::IsObserved(int32_t id) { + for (int32_t i = 0; i < m_ObservedEntitiesUsed; i++) { + if (m_ObservedEntities[i] == id) { return true; } } @@ -239,34 +206,27 @@ bool Player::IsObserved(int32_t id) return false; } -void Player::GhostEntity(int32_t id) -{ - for (int32_t i = 0; i < m_ObservedEntitiesUsed; i++) - { - if (m_ObservedEntities[i] == id) - { +void Player::GhostEntity(int32_t id) { + for (int32_t i = 0; i < m_ObservedEntitiesUsed; i++) { + if (m_ObservedEntities[i] == id) { m_ObservedEntities[i] = 0; } } } -Player* Player::GetPlayer(const SystemAddress& sysAddr) -{ +Player* Player::GetPlayer(const SystemAddress& sysAddr) { auto* entity = UserManager::Instance()->GetUser(sysAddr)->GetLastUsedChar()->GetEntity(); return static_cast(entity); } -Player* Player::GetPlayer(const std::string& name) -{ +Player* Player::GetPlayer(const std::string& name) { const auto characters = EntityManager::Instance()->GetEntitiesByComponent(COMPONENT_TYPE_CHARACTER); - for (auto* character : characters) - { + for (auto* character : characters) { if (!character->IsPlayer()) continue; - if (character->GetCharacter()->GetName() == name) - { + if (character->GetCharacter()->GetName() == name) { return static_cast(character); } } @@ -274,12 +234,9 @@ Player* Player::GetPlayer(const std::string& name) return nullptr; } -Player* Player::GetPlayer(LWOOBJID playerID) -{ - for (auto* player : m_Players) - { - if (player->GetObjectID() == playerID) - { +Player* Player::GetPlayer(LWOOBJID playerID) { + for (auto* player : m_Players) { + if (player->GetObjectID() == playerID) { return player; } } @@ -287,8 +244,7 @@ Player* Player::GetPlayer(LWOOBJID playerID) return nullptr; } -const std::vector& Player::GetAllPlayers() -{ +const std::vector& Player::GetAllPlayers() { return m_Players; } @@ -300,23 +256,19 @@ void Player::SetDroppedCoins(uint64_t value) { m_DroppedCoins = value; } -Player::~Player() -{ +Player::~Player() { Game::logger->Log("Player", "Deleted player"); - for (int32_t i = 0; i < m_ObservedEntitiesUsed; i++) - { + for (int32_t i = 0; i < m_ObservedEntitiesUsed; i++) { const auto id = m_ObservedEntities[i]; - if (id == 0) - { + if (id == 0) { continue; } auto* entity = EntityManager::Instance()->GetGhostCandidate(id); - if (entity != nullptr) - { + if (entity != nullptr) { entity->SetObservers(entity->GetObservers() - 1); } } @@ -325,25 +277,24 @@ Player::~Player() const auto& iter = std::find(m_Players.begin(), m_Players.end(), this); - if (iter == m_Players.end()) - { + if (iter == m_Players.end()) { return; } if (IsPlayer()) { - Entity* zoneControl = EntityManager::Instance()->GetZoneControlEntity(); - for (CppScripts::Script* script : CppScripts::GetEntityScripts(zoneControl)) { - script->OnPlayerExit(zoneControl, this); - } + Entity* zoneControl = EntityManager::Instance()->GetZoneControlEntity(); + for (CppScripts::Script* script : CppScripts::GetEntityScripts(zoneControl)) { + script->OnPlayerExit(zoneControl, this); + } - std::vector scriptedActs = EntityManager::Instance()->GetEntitiesByComponent(COMPONENT_TYPE_SCRIPTED_ACTIVITY); - for (Entity* scriptEntity : scriptedActs) { - if (scriptEntity->GetObjectID() != zoneControl->GetObjectID()) { // Don't want to trigger twice on instance worlds - for (CppScripts::Script* script : CppScripts::GetEntityScripts(scriptEntity)) { - script->OnPlayerExit(scriptEntity, this); - } - } - } + std::vector scriptedActs = EntityManager::Instance()->GetEntitiesByComponent(COMPONENT_TYPE_SCRIPTED_ACTIVITY); + for (Entity* scriptEntity : scriptedActs) { + if (scriptEntity->GetObjectID() != zoneControl->GetObjectID()) { // Don't want to trigger twice on instance worlds + for (CppScripts::Script* script : CppScripts::GetEntityScripts(scriptEntity)) { + script->OnPlayerExit(scriptEntity, this); + } + } + } } m_Players.erase(iter); diff --git a/dGame/Player.h b/dGame/Player.h index bba01363..caad5361 100644 --- a/dGame/Player.h +++ b/dGame/Player.h @@ -4,26 +4,26 @@ /** * Extended Entity for player data and behavior. - * + * * Contains properties only a player entity would require, like associated SystemAddress and User. - * + * * Keeps track of which entities are observed by this user for ghosting. */ class Player final : public Entity { public: explicit Player(const LWOOBJID& objectID, EntityInfo info, User* user, Entity* parentEntity = nullptr); - + /** * Getters */ User* GetParentUser() const override; - + SystemAddress GetSystemAddress() const override; - + NiPoint3 GetRespawnPosition() const override; - + NiQuaternion GetRespawnRotation() const override; const NiPoint3& GetGhostReferencePoint() const; @@ -41,11 +41,11 @@ public: /** * Setters */ - + void SetSystemAddress(const SystemAddress& value) override; - + void SetRespawnPos(NiPoint3 position) override; - + void SetRespawnRot(NiQuaternion rotation) override; void SetGhostReferencePoint(const NiPoint3& value); @@ -58,7 +58,7 @@ public: /** * Wrapper for sending an in-game mail. - * + * * @param sender id of the sender. LWOOBJID_EMPTY for system mail * @param senderName name of the sender. Max 32 characters. * @param subject mail subject. Max 50 characters. @@ -67,10 +67,10 @@ public: * @param attachmentCount stack size for attachment. */ void SendMail(LWOOBJID sender, const std::string& senderName, const std::string& subject, const std::string& body, LOT attachment, uint16_t attachmentCount) const; - + /** * Wrapper for transfering the player to another instance. - * + * * @param zoneId zoneID for the new instance. * @param cloneId cloneID for the new instance. */ @@ -81,7 +81,7 @@ public: */ void AddLimboConstruction(LWOOBJID objectId); - + void RemoveLimboConstruction(LWOOBJID objectId); void ConstructLimboEntities(); @@ -99,19 +99,19 @@ public: static Player* GetPlayer(const SystemAddress& sysAddr); static Player* GetPlayer(const std::string& name); - + static Player* GetPlayer(LWOOBJID playerID); static const std::vector& GetAllPlayers(); - + ~Player() override; private: SystemAddress m_SystemAddress; - + NiPoint3 m_respawnPos; - + NiQuaternion m_respawnRot; - + User* m_ParentUser; NiPoint3 m_GhostReferencePoint; @@ -121,7 +121,7 @@ private: bool m_GhostOverride; std::vector m_ObservedEntities; - + int32_t m_ObservedEntitiesLength; int32_t m_ObservedEntitiesUsed; diff --git a/dGame/TeamManager.cpp b/dGame/TeamManager.cpp index 8836dd8d..0258ce3e 100644 --- a/dGame/TeamManager.cpp +++ b/dGame/TeamManager.cpp @@ -3,74 +3,60 @@ TeamManager* TeamManager::m_Address = nullptr; //For singleton method -TeamManager::TeamManager() -{ +TeamManager::TeamManager() { } -Team* TeamManager::GetTeam(LWOOBJID member) const -{ - for (const auto& pair : m_Teams) - { - for (const auto memberId : pair.second->members) - { - if (memberId == member) - { - return pair.second; - } - } - } - - return nullptr; +Team* TeamManager::GetTeam(LWOOBJID member) const { + for (const auto& pair : m_Teams) { + for (const auto memberId : pair.second->members) { + if (memberId == member) { + return pair.second; + } + } + } + + return nullptr; } -LWOOBJID TeamManager::GetNextLootOwner(Team* team) const -{ - team->lootRound++; +LWOOBJID TeamManager::GetNextLootOwner(Team* team) const { + team->lootRound++; - if (team->lootRound >= team->members.size()) - { - team->lootRound = 0; - } + if (team->lootRound >= team->members.size()) { + team->lootRound = 0; + } - return team->members[team->lootRound]; + return team->members[team->lootRound]; } -void TeamManager::UpdateTeam(LWOOBJID teamId, char lootOption, const std::vector& members) -{ - const auto& pair = m_Teams.find(teamId); +void TeamManager::UpdateTeam(LWOOBJID teamId, char lootOption, const std::vector& members) { + const auto& pair = m_Teams.find(teamId); - Team* team; + Team* team; - if (pair == m_Teams.end()) - { - if (members.size() <= 1) - { - return; - } + if (pair == m_Teams.end()) { + if (members.size() <= 1) { + return; + } - team = new Team(); - m_Teams[teamId] = team; - } - else - { - team = pair->second; - } + team = new Team(); + m_Teams[teamId] = team; + } else { + team = pair->second; + } - team->members = members; - team->lootOption = lootOption; + team->members = members; + team->lootOption = lootOption; } -void TeamManager::DeleteTeam(LWOOBJID teamId) -{ - const auto& pair = m_Teams.find(teamId); +void TeamManager::DeleteTeam(LWOOBJID teamId) { + const auto& pair = m_Teams.find(teamId); - if (pair == m_Teams.end()) return; + if (pair == m_Teams.end()) return; - delete pair->second; + delete pair->second; - m_Teams.erase(teamId); + m_Teams.erase(teamId); } -TeamManager::~TeamManager() -{ +TeamManager::~TeamManager() { } diff --git a/dGame/TeamManager.h b/dGame/TeamManager.h index ffab3764..eb1b5c5b 100644 --- a/dGame/TeamManager.h +++ b/dGame/TeamManager.h @@ -6,18 +6,18 @@ struct Team { LWOOBJID teamID = LWOOBJID_EMPTY; char lootOption = 0; - std::vector members {}; + std::vector members{}; char lootRound = 0; }; class TeamManager { public: - static TeamManager* Instance() { + static TeamManager* Instance() { if (!m_Address) { m_Address = new TeamManager(); } - + return m_Address; } @@ -26,11 +26,11 @@ public: void UpdateTeam(LWOOBJID teamId, char lootOption, const std::vector& members); void DeleteTeam(LWOOBJID teamId); - explicit TeamManager(); - ~TeamManager(); + explicit TeamManager(); + ~TeamManager(); private: - static TeamManager* m_Address; //For singleton method - std::unordered_map m_Teams {}; + static TeamManager* m_Address; //For singleton method + std::unordered_map m_Teams{}; }; diff --git a/dGame/TradingManager.cpp b/dGame/TradingManager.cpp index 1d23126a..e49cca70 100644 --- a/dGame/TradingManager.cpp +++ b/dGame/TradingManager.cpp @@ -12,297 +12,246 @@ TradingManager* TradingManager::m_Address = nullptr; -Trade::Trade(LWOOBJID tradeId, LWOOBJID participantA, LWOOBJID participantB) -{ - m_TradeId = tradeId; - m_ParticipantA = participantA; - m_ParticipantB = participantB; +Trade::Trade(LWOOBJID tradeId, LWOOBJID participantA, LWOOBJID participantB) { + m_TradeId = tradeId; + m_ParticipantA = participantA; + m_ParticipantB = participantB; } -Trade::~Trade() -{ +Trade::~Trade() { } -LWOOBJID Trade::GetTradeId() const -{ - return m_TradeId; +LWOOBJID Trade::GetTradeId() const { + return m_TradeId; } -bool Trade::IsParticipant(LWOOBJID playerId) const -{ - return m_ParticipantA == playerId || m_ParticipantB == playerId; +bool Trade::IsParticipant(LWOOBJID playerId) const { + return m_ParticipantA == playerId || m_ParticipantB == playerId; } -LWOOBJID Trade::GetParticipantA() const -{ - return m_ParticipantA; +LWOOBJID Trade::GetParticipantA() const { + return m_ParticipantA; } -LWOOBJID Trade::GetParticipantB() const -{ - return m_ParticipantB; +LWOOBJID Trade::GetParticipantB() const { + return m_ParticipantB; } -Entity* Trade::GetParticipantAEntity() const -{ - return EntityManager::Instance()->GetEntity(m_ParticipantA); +Entity* Trade::GetParticipantAEntity() const { + return EntityManager::Instance()->GetEntity(m_ParticipantA); } -Entity* Trade::GetParticipantBEntity() const -{ - return EntityManager::Instance()->GetEntity(m_ParticipantB); +Entity* Trade::GetParticipantBEntity() const { + return EntityManager::Instance()->GetEntity(m_ParticipantB); } -void Trade::SetCoins(LWOOBJID participant, uint64_t coins) -{ - if (participant == m_ParticipantA) - { - m_CoinsA = coins; - } - else if (participant == m_ParticipantB) - { - m_CoinsB = coins; - } +void Trade::SetCoins(LWOOBJID participant, uint64_t coins) { + if (participant == m_ParticipantA) { + m_CoinsA = coins; + } else if (participant == m_ParticipantB) { + m_CoinsB = coins; + } } -void Trade::SetItems(LWOOBJID participant, std::vector items) -{ - if (participant == m_ParticipantA) - { - m_ItemsA = items; - } - else if (participant == m_ParticipantB) - { - m_ItemsB = items; - } +void Trade::SetItems(LWOOBJID participant, std::vector items) { + if (participant == m_ParticipantA) { + m_ItemsA = items; + } else if (participant == m_ParticipantB) { + m_ItemsB = items; + } } -void Trade::SetAccepted(LWOOBJID participant, bool value) -{ - if (participant == m_ParticipantA) - { - m_AcceptedA = !value; +void Trade::SetAccepted(LWOOBJID participant, bool value) { + if (participant == m_ParticipantA) { + m_AcceptedA = !value; - Game::logger->Log("Trade", "Accepted from A (%d), B: (%d)", value, m_AcceptedB); + Game::logger->Log("Trade", "Accepted from A (%d), B: (%d)", value, m_AcceptedB); - auto* entityB = GetParticipantBEntity(); + auto* entityB = GetParticipantBEntity(); - if (entityB != nullptr) - { - GameMessages::SendServerTradeAccept(m_ParticipantB, value, entityB->GetSystemAddress()); - } - } - else if (participant == m_ParticipantB) - { - m_AcceptedB = !value; + if (entityB != nullptr) { + GameMessages::SendServerTradeAccept(m_ParticipantB, value, entityB->GetSystemAddress()); + } + } else if (participant == m_ParticipantB) { + m_AcceptedB = !value; - Game::logger->Log("Trade", "Accepted from B (%d), A: (%d)", value, m_AcceptedA); + Game::logger->Log("Trade", "Accepted from B (%d), A: (%d)", value, m_AcceptedA); - auto* entityA = GetParticipantAEntity(); + auto* entityA = GetParticipantAEntity(); - if (entityA != nullptr) - { - GameMessages::SendServerTradeAccept(m_ParticipantA, value, entityA->GetSystemAddress()); - } - } + if (entityA != nullptr) { + GameMessages::SendServerTradeAccept(m_ParticipantA, value, entityA->GetSystemAddress()); + } + } - if (m_AcceptedA && m_AcceptedB) - { - auto* entityB = GetParticipantBEntity(); + if (m_AcceptedA && m_AcceptedB) { + auto* entityB = GetParticipantBEntity(); - if (entityB != nullptr) - { - GameMessages::SendServerTradeAccept(m_ParticipantB, false, entityB->GetSystemAddress()); - } - else - { - return; - } + if (entityB != nullptr) { + GameMessages::SendServerTradeAccept(m_ParticipantB, false, entityB->GetSystemAddress()); + } else { + return; + } - auto* entityA = GetParticipantAEntity(); + auto* entityA = GetParticipantAEntity(); - if (entityA != nullptr) - { - GameMessages::SendServerTradeAccept(m_ParticipantA, false, entityA->GetSystemAddress()); - } - else - { - return; - } + if (entityA != nullptr) { + GameMessages::SendServerTradeAccept(m_ParticipantA, false, entityA->GetSystemAddress()); + } else { + return; + } - Complete(); - } + Complete(); + } } -void Trade::Complete() -{ - auto* entityA = GetParticipantAEntity(); - auto* entityB = GetParticipantBEntity(); +void Trade::Complete() { + auto* entityA = GetParticipantAEntity(); + auto* entityB = GetParticipantBEntity(); - if (entityA == nullptr || entityB == nullptr) return; + if (entityA == nullptr || entityB == nullptr) return; - auto* inventoryA = entityA->GetComponent(); - auto* inventoryB = entityB->GetComponent(); - auto* missionsA = entityA->GetComponent(); - auto* missionsB = entityB->GetComponent(); - auto* characterA = entityA->GetCharacter(); - auto* characterB = entityB->GetCharacter(); + auto* inventoryA = entityA->GetComponent(); + auto* inventoryB = entityB->GetComponent(); + auto* missionsA = entityA->GetComponent(); + auto* missionsB = entityB->GetComponent(); + auto* characterA = entityA->GetCharacter(); + auto* characterB = entityB->GetCharacter(); - if (inventoryA == nullptr || inventoryB == nullptr || characterA == nullptr || characterB == nullptr || missionsA == nullptr || missionsB == nullptr) return; + if (inventoryA == nullptr || inventoryB == nullptr || characterA == nullptr || characterB == nullptr || missionsA == nullptr || missionsB == nullptr) return; - characterA->SetCoins(characterA->GetCoins() - m_CoinsA + m_CoinsB, eLootSourceType::LOOT_SOURCE_TRADE); - characterB->SetCoins(characterB->GetCoins() - m_CoinsB + m_CoinsA, eLootSourceType::LOOT_SOURCE_TRADE); + characterA->SetCoins(characterA->GetCoins() - m_CoinsA + m_CoinsB, eLootSourceType::LOOT_SOURCE_TRADE); + characterB->SetCoins(characterB->GetCoins() - m_CoinsB + m_CoinsA, eLootSourceType::LOOT_SOURCE_TRADE); - for (const auto& tradeItem : m_ItemsA) - { - inventoryA->RemoveItem(tradeItem.itemLot, tradeItem.itemCount, INVALID, true); + for (const auto& tradeItem : m_ItemsA) { + inventoryA->RemoveItem(tradeItem.itemLot, tradeItem.itemCount, INVALID, true); - missionsA->Progress(MissionTaskType::MISSION_TASK_TYPE_ITEM_COLLECTION, tradeItem.itemLot, LWOOBJID_EMPTY, "", -tradeItem.itemCount); - } + missionsA->Progress(MissionTaskType::MISSION_TASK_TYPE_ITEM_COLLECTION, tradeItem.itemLot, LWOOBJID_EMPTY, "", -tradeItem.itemCount); + } - for (const auto& tradeItem : m_ItemsB) - { - inventoryB->RemoveItem(tradeItem.itemLot, tradeItem.itemCount, INVALID, true); + for (const auto& tradeItem : m_ItemsB) { + inventoryB->RemoveItem(tradeItem.itemLot, tradeItem.itemCount, INVALID, true); - missionsB->Progress(MissionTaskType::MISSION_TASK_TYPE_ITEM_COLLECTION, tradeItem.itemLot, LWOOBJID_EMPTY, "", -tradeItem.itemCount); - } + missionsB->Progress(MissionTaskType::MISSION_TASK_TYPE_ITEM_COLLECTION, tradeItem.itemLot, LWOOBJID_EMPTY, "", -tradeItem.itemCount); + } - for (const auto& tradeItem : m_ItemsA) - { - inventoryB->AddItem(tradeItem.itemLot, tradeItem.itemCount, eLootSourceType::LOOT_SOURCE_TRADE); - } + for (const auto& tradeItem : m_ItemsA) { + inventoryB->AddItem(tradeItem.itemLot, tradeItem.itemCount, eLootSourceType::LOOT_SOURCE_TRADE); + } - for (const auto& tradeItem : m_ItemsB) - { - inventoryA->AddItem(tradeItem.itemLot, tradeItem.itemCount, eLootSourceType::LOOT_SOURCE_TRADE); - } + for (const auto& tradeItem : m_ItemsB) { + inventoryA->AddItem(tradeItem.itemLot, tradeItem.itemCount, eLootSourceType::LOOT_SOURCE_TRADE); + } - TradingManager::Instance()->CancelTrade(m_TradeId); + TradingManager::Instance()->CancelTrade(m_TradeId); - characterA->SaveXMLToDatabase(); - characterB->SaveXMLToDatabase(); + characterA->SaveXMLToDatabase(); + characterB->SaveXMLToDatabase(); } -void Trade::Cancel() -{ - auto* entityA = GetParticipantAEntity(); - auto* entityB = GetParticipantBEntity(); +void Trade::Cancel() { + auto* entityA = GetParticipantAEntity(); + auto* entityB = GetParticipantBEntity(); - if (entityA == nullptr || entityB == nullptr) return; + if (entityA == nullptr || entityB == nullptr) return; - GameMessages::SendServerTradeCancel(entityA->GetObjectID(), entityA->GetSystemAddress()); - GameMessages::SendServerTradeCancel(entityB->GetObjectID(), entityB->GetSystemAddress()); + GameMessages::SendServerTradeCancel(entityA->GetObjectID(), entityA->GetSystemAddress()); + GameMessages::SendServerTradeCancel(entityB->GetObjectID(), entityB->GetSystemAddress()); } -void Trade::SendUpdateToOther(LWOOBJID participant) -{ - Entity* other = nullptr; - Entity* self = nullptr; - uint64_t coins; - std::vector itemIds; +void Trade::SendUpdateToOther(LWOOBJID participant) { + Entity* other = nullptr; + Entity* self = nullptr; + uint64_t coins; + std::vector itemIds; - Game::logger->Log("Trade", "Attempting to send trade update"); + Game::logger->Log("Trade", "Attempting to send trade update"); - if (participant == m_ParticipantA) - { - other = GetParticipantBEntity(); - self = GetParticipantAEntity(); - coins = m_CoinsA; - itemIds = m_ItemsA; - } - else if (participant == m_ParticipantB) - { - other = GetParticipantAEntity(); - self = GetParticipantBEntity(); - coins = m_CoinsB; - itemIds = m_ItemsB; - } - else - { - return; - } + if (participant == m_ParticipantA) { + other = GetParticipantBEntity(); + self = GetParticipantAEntity(); + coins = m_CoinsA; + itemIds = m_ItemsA; + } else if (participant == m_ParticipantB) { + other = GetParticipantAEntity(); + self = GetParticipantBEntity(); + coins = m_CoinsB; + itemIds = m_ItemsB; + } else { + return; + } - if (other == nullptr || self == nullptr) return; + if (other == nullptr || self == nullptr) return; - std::vector items {}; + std::vector items{}; - auto* inventoryComponent = self->GetComponent(); + auto* inventoryComponent = self->GetComponent(); - if (inventoryComponent == nullptr) return; + if (inventoryComponent == nullptr) return; - for (const auto tradeItem : itemIds) - { - auto* item = inventoryComponent->FindItemById(tradeItem.itemId); + for (const auto tradeItem : itemIds) { + auto* item = inventoryComponent->FindItemById(tradeItem.itemId); - if (item == nullptr) return; + if (item == nullptr) return; - if (tradeItem.itemCount > item->GetCount()) return; + if (tradeItem.itemCount > item->GetCount()) return; - items.push_back(tradeItem); - } + items.push_back(tradeItem); + } - Game::logger->Log("Trade", "Sending trade update"); + Game::logger->Log("Trade", "Sending trade update"); - GameMessages::SendServerTradeUpdate(other->GetObjectID(), coins, items, other->GetSystemAddress()); + GameMessages::SendServerTradeUpdate(other->GetObjectID(), coins, items, other->GetSystemAddress()); } -TradingManager::TradingManager() -{ +TradingManager::TradingManager() { } -TradingManager::~TradingManager() -{ - for (const auto& pair : trades) - { - delete pair.second; - } +TradingManager::~TradingManager() { + for (const auto& pair : trades) { + delete pair.second; + } - trades.clear(); + trades.clear(); } -Trade* TradingManager::GetTrade(LWOOBJID tradeId) const -{ - const auto& pair = trades.find(tradeId); +Trade* TradingManager::GetTrade(LWOOBJID tradeId) const { + const auto& pair = trades.find(tradeId); - if (pair == trades.end()) return nullptr; + if (pair == trades.end()) return nullptr; - return pair->second; + return pair->second; } -Trade* TradingManager::GetPlayerTrade(LWOOBJID playerId) const -{ - for (const auto& pair : trades) - { - if (pair.second->IsParticipant(playerId)) - { - return pair.second; - } - } +Trade* TradingManager::GetPlayerTrade(LWOOBJID playerId) const { + for (const auto& pair : trades) { + if (pair.second->IsParticipant(playerId)) { + return pair.second; + } + } - return nullptr; + return nullptr; } -void TradingManager::CancelTrade(LWOOBJID tradeId) -{ - auto* trade = GetTrade(tradeId); +void TradingManager::CancelTrade(LWOOBJID tradeId) { + auto* trade = GetTrade(tradeId); - if (trade == nullptr) return; + if (trade == nullptr) return; - delete trade; + delete trade; - trades.erase(tradeId); + trades.erase(tradeId); } -Trade* TradingManager::NewTrade(LWOOBJID participantA, LWOOBJID participantB) -{ - const LWOOBJID tradeId = ObjectIDManager::Instance()->GenerateObjectID(); +Trade* TradingManager::NewTrade(LWOOBJID participantA, LWOOBJID participantB) { + const LWOOBJID tradeId = ObjectIDManager::Instance()->GenerateObjectID(); - auto* trade = new Trade(tradeId, participantA, participantB); + auto* trade = new Trade(tradeId, participantA, participantB); - trades[tradeId] = trade; + trades[tradeId] = trade; - Game::logger->Log("TradingManager", "Created new trade between (%llu) <-> (%llu)", participantA, participantB); + Game::logger->Log("TradingManager", "Created new trade between (%llu) <-> (%llu)", participantA, participantB); - return trade; + return trade; } diff --git a/dGame/TradingManager.h b/dGame/TradingManager.h index 6962acaa..ec0d332f 100644 --- a/dGame/TradingManager.h +++ b/dGame/TradingManager.h @@ -4,73 +4,73 @@ struct TradeItem { - LWOOBJID itemId; - LOT itemLot; - uint32_t itemCount; + LWOOBJID itemId; + LOT itemLot; + uint32_t itemCount; }; class Trade { public: - explicit Trade(LWOOBJID tradeId, LWOOBJID participantA, LWOOBJID participantB); - ~Trade(); + explicit Trade(LWOOBJID tradeId, LWOOBJID participantA, LWOOBJID participantB); + ~Trade(); - LWOOBJID GetTradeId() const; + LWOOBJID GetTradeId() const; - bool IsParticipant(LWOOBJID playerId) const; + bool IsParticipant(LWOOBJID playerId) const; - LWOOBJID GetParticipantA() const; - LWOOBJID GetParticipantB() const; + LWOOBJID GetParticipantA() const; + LWOOBJID GetParticipantB() const; - Entity* GetParticipantAEntity() const; - Entity* GetParticipantBEntity() const; + Entity* GetParticipantAEntity() const; + Entity* GetParticipantBEntity() const; - void SetCoins(LWOOBJID participant, uint64_t coins); - void SetItems(LWOOBJID participant, std::vector items); - void SetAccepted(LWOOBJID participant, bool value); + void SetCoins(LWOOBJID participant, uint64_t coins); + void SetItems(LWOOBJID participant, std::vector items); + void SetAccepted(LWOOBJID participant, bool value); - void Complete(); - void Cancel(); + void Complete(); + void Cancel(); - void SendUpdateToOther(LWOOBJID participant); + void SendUpdateToOther(LWOOBJID participant); private: - LWOOBJID m_TradeId = LWOOBJID_EMPTY; - LWOOBJID m_ParticipantA = LWOOBJID_EMPTY; - LWOOBJID m_ParticipantB = LWOOBJID_EMPTY; + LWOOBJID m_TradeId = LWOOBJID_EMPTY; + LWOOBJID m_ParticipantA = LWOOBJID_EMPTY; + LWOOBJID m_ParticipantB = LWOOBJID_EMPTY; - uint64_t m_CoinsA = 0; - uint64_t m_CoinsB = 0; + uint64_t m_CoinsA = 0; + uint64_t m_CoinsB = 0; - std::vector m_ItemsA {}; - std::vector m_ItemsB {}; + std::vector m_ItemsA{}; + std::vector m_ItemsB{}; - bool m_AcceptedA = false; - bool m_AcceptedB = false; + bool m_AcceptedA = false; + bool m_AcceptedB = false; }; class TradingManager { public: - static TradingManager* Instance() { + static TradingManager* Instance() { if (!m_Address) { m_Address = new TradingManager(); } - + return m_Address; } - explicit TradingManager(); - ~TradingManager(); + explicit TradingManager(); + ~TradingManager(); - Trade* GetTrade(LWOOBJID tradeId) const; - Trade* GetPlayerTrade(LWOOBJID playerId) const; - void CancelTrade(LWOOBJID tradeId); - Trade* NewTrade(LWOOBJID participantA, LWOOBJID participantB); + Trade* GetTrade(LWOOBJID tradeId) const; + Trade* GetPlayerTrade(LWOOBJID playerId) const; + void CancelTrade(LWOOBJID tradeId); + Trade* NewTrade(LWOOBJID participantA, LWOOBJID participantB); private: - static TradingManager* m_Address; //For singleton method + static TradingManager* m_Address; //For singleton method - std::unordered_map trades; + std::unordered_map trades; }; diff --git a/dGame/User.cpp b/dGame/User.cpp index 33329199..20cc3ab4 100644 --- a/dGame/User.cpp +++ b/dGame/User.cpp @@ -17,7 +17,7 @@ User::User(const SystemAddress& sysAddr, const std::string& username, const std: m_SessionKey = sessionKey; m_SystemAddress = sysAddr; m_Username = username; - m_LoggedInCharID = 0; + m_LoggedInCharID = 0; m_IsBestFriendMap = std::unordered_map(); @@ -39,88 +39,85 @@ User::User(const SystemAddress& sysAddr, const std::string& username, const std: delete res; delete stmt; - //If we're loading a zone, we'll load the last used (aka current) character: + //If we're loading a zone, we'll load the last used (aka current) character: if (Game::server->GetZoneID() != 0) { - sql::PreparedStatement* stmt = Database::CreatePreppedStmt("SELECT id FROM charinfo WHERE account_id=? ORDER BY last_login DESC LIMIT 1;"); - stmt->setUInt(1, m_AccountID); + sql::PreparedStatement* stmt = Database::CreatePreppedStmt("SELECT id FROM charinfo WHERE account_id=? ORDER BY last_login DESC LIMIT 1;"); + stmt->setUInt(1, m_AccountID); - sql::ResultSet* res = stmt->executeQuery(); - if (res->rowsCount() > 0) { - while (res->next()) { - LWOOBJID objID = res->getUInt64(1); - Character* character = new Character(uint32_t(objID), this); - m_Characters.push_back(character); - Game::logger->Log("User", "Loaded %llu as it is the last used char", objID); - } - } + sql::ResultSet* res = stmt->executeQuery(); + if (res->rowsCount() > 0) { + while (res->next()) { + LWOOBJID objID = res->getUInt64(1); + Character* character = new Character(uint32_t(objID), this); + m_Characters.push_back(character); + Game::logger->Log("User", "Loaded %llu as it is the last used char", objID); + } + } - delete res; - delete stmt; - } + delete res; + delete stmt; + } } -User::User ( const User& other ) { +User::User(const User& other) { this->m_AccountID = other.m_AccountID; this->m_LastCharID = other.m_LastCharID; this->m_MaxGMLevel = other.m_MaxGMLevel; this->m_SessionKey = other.m_SessionKey; this->m_SystemAddress = other.m_SystemAddress; this->m_Username = other.m_Username; - this->m_LoggedInCharID = other.m_LoggedInCharID; + this->m_LoggedInCharID = other.m_LoggedInCharID; } User::~User() { for (Character* c : m_Characters) { - if (c) { - delete c; - c = nullptr; - } - } + if (c) { + delete c; + c = nullptr; + } + } } -User& User::operator= ( const User& other ) { +User& User::operator= (const User& other) { this->m_AccountID = other.m_AccountID; this->m_LastCharID = other.m_LastCharID; this->m_MaxGMLevel = other.m_MaxGMLevel; this->m_SessionKey = other.m_SessionKey; this->m_SystemAddress = other.m_SystemAddress; this->m_Username = other.m_Username; - this->m_LoggedInCharID = other.m_LoggedInCharID; + this->m_LoggedInCharID = other.m_LoggedInCharID; return *this; } -bool User::operator== ( const User& other ) const { +bool User::operator== (const User& other) const { if (m_Username == other.m_Username || m_SessionKey == other.m_SessionKey || m_SystemAddress == other.m_SystemAddress) return true; return false; } -Character * User::GetLastUsedChar() { - if (m_Characters.size() == 0) return nullptr; - else if (m_Characters.size() == 1) return m_Characters[0]; - else { - Character* toReturn = m_Characters[0]; - for (size_t i = 0; i < m_Characters.size(); ++i) { - if (m_Characters[i]->GetLastLogin() > toReturn->GetLastLogin()) toReturn = m_Characters[i]; - } +Character* User::GetLastUsedChar() { + if (m_Characters.size() == 0) return nullptr; + else if (m_Characters.size() == 1) return m_Characters[0]; + else { + Character* toReturn = m_Characters[0]; + for (size_t i = 0; i < m_Characters.size(); ++i) { + if (m_Characters[i]->GetLastLogin() > toReturn->GetLastLogin()) toReturn = m_Characters[i]; + } - return toReturn; - } + return toReturn; + } } -bool User::GetIsMuted() const -{ +bool User::GetIsMuted() const { return m_MuteExpire == 1 || m_MuteExpire > time(NULL); } -time_t User::GetMuteExpire() const -{ +time_t User::GetMuteExpire() const { return m_MuteExpire; } -void User::SetMuteExpire(time_t value) -{ +void User::SetMuteExpire(time_t value) { m_MuteExpire = value; } diff --git a/dGame/User.h b/dGame/User.h index 78640b38..59416c4c 100644 --- a/dGame/User.h +++ b/dGame/User.h @@ -10,7 +10,7 @@ class Character; -struct BehaviorParams{ +struct BehaviorParams { uint32_t behavior; LWOOBJID objid; bool followup; @@ -23,21 +23,21 @@ public: ~User(); User& operator=(const User& other); bool operator==(const User& other) const; - + uint32_t GetAccountID() { return m_AccountID; } std::string& GetUsername() { return m_Username; } std::string& GetSessionKey() { return m_SessionKey; } SystemAddress& GetSystemAddress() { return m_SystemAddress; } - + uint32_t GetMaxGMLevel() { return m_MaxGMLevel; } uint32_t GetLastCharID() { return m_LastCharID; } void SetLastCharID(uint32_t newCharID) { m_LastCharID = newCharID; } - + std::vector& GetCharacters() { return m_Characters; } Character* GetLastUsedChar(); - - void SetLoggedInChar(const LWOOBJID& objID) { m_LoggedInCharID = objID; } - LWOOBJID& GetLoggedInChar() { return m_LoggedInCharID; } + + void SetLoggedInChar(const LWOOBJID& objID) { m_LoggedInCharID = objID; } + LWOOBJID& GetLoggedInChar() { return m_LoggedInCharID; } bool GetLastChatMessageApproved() { return m_LastChatMessageApproved; } void SetLastChatMessageApproved(bool approved) { m_LastChatMessageApproved = approved; } @@ -52,7 +52,7 @@ public: // Added for GameMessageHandler std::unordered_map uiBehaviorHandles; - + void UserOutOfSync(); private: @@ -60,11 +60,11 @@ private: std::string m_Username; std::string m_SessionKey; SystemAddress m_SystemAddress; - + uint32_t m_MaxGMLevel; //The max GM level this account can assign to it's characters uint32_t m_LastCharID; std::vector m_Characters; - LWOOBJID m_LoggedInCharID; + LWOOBJID m_LoggedInCharID; std::unordered_map m_IsBestFriendMap; diff --git a/dGame/UserManager.cpp b/dGame/UserManager.cpp index 5a320b51..7da26b9a 100644 --- a/dGame/UserManager.cpp +++ b/dGame/UserManager.cpp @@ -21,7 +21,7 @@ #include "EntityManager.h" #include "SkillComponent.h" -UserManager * UserManager::m_Address = nullptr; +UserManager* UserManager::m_Address = nullptr; //Local functions as they aren't needed by anything else, leave the implementations at the bottom! uint32_t FindCharShirtID(uint32_t shirtColor, uint32_t shirtStyle); @@ -75,7 +75,7 @@ UserManager::~UserManager() { } -User* UserManager::CreateUser ( const SystemAddress& sysAddr, const std::string& username, const std::string& sessionKey ) { +User* UserManager::CreateUser(const SystemAddress& sysAddr, const std::string& username, const std::string& sessionKey) { User* user = new User(sysAddr, username, sessionKey); if (user && Game::server->IsConnected(sysAddr)) m_Users.insert(std::make_pair(sysAddr, user)); @@ -89,28 +89,27 @@ User* UserManager::CreateUser ( const SystemAddress& sysAddr, const std::string& return user; } -User* UserManager::GetUser ( const SystemAddress& sysAddr ) { +User* UserManager::GetUser(const SystemAddress& sysAddr) { auto it = m_Users.find(sysAddr); if (it != m_Users.end() && it->second) return it->second; - return nullptr; + return nullptr; } -User* UserManager::GetUser ( const std::string& username ) { +User* UserManager::GetUser(const std::string& username) { for (auto p : m_Users) { if (p.second) { if (p.second->GetUsername() == username) return p.second; } } - return nullptr; + return nullptr; } -bool UserManager::DeleteUser ( const SystemAddress& sysAddr ) { +bool UserManager::DeleteUser(const SystemAddress& sysAddr) { const auto& it = m_Users.find(sysAddr); - if (it != m_Users.end()) - { + if (it != m_Users.end()) { if (std::count(m_UsersToDelete.begin(), m_UsersToDelete.end(), it->second)) return false; m_UsersToDelete.push_back(it->second); @@ -123,10 +122,8 @@ bool UserManager::DeleteUser ( const SystemAddress& sysAddr ) { return false; } -void UserManager::DeletePendingRemovals() -{ - for (auto* user : m_UsersToDelete) - { +void UserManager::DeletePendingRemovals() { + for (auto* user : m_UsersToDelete) { Game::logger->Log("UserManager", "Deleted user %i", user->GetAccountID()); delete user; @@ -135,7 +132,7 @@ void UserManager::DeletePendingRemovals() m_UsersToDelete.clear(); } -bool UserManager::IsNameAvailable ( const std::string& requestedName ) { +bool UserManager::IsNameAvailable(const std::string& requestedName) { bool toReturn = false; //To allow for a clean exit sql::PreparedStatement* stmt = Database::CreatePreppedStmt("SELECT id FROM charinfo WHERE name=? OR pending_name=? LIMIT 1;"); stmt->setString(1, requestedName.c_str()); @@ -149,12 +146,12 @@ bool UserManager::IsNameAvailable ( const std::string& requestedName ) { return toReturn; } -std::string UserManager::GetPredefinedName ( uint32_t firstNameIndex, uint32_t middleNameIndex, uint32_t lastNameIndex ) { +std::string UserManager::GetPredefinedName(uint32_t firstNameIndex, uint32_t middleNameIndex, uint32_t lastNameIndex) { if (firstNameIndex > m_FirstNames.size() || middleNameIndex > m_MiddleNames.size() || lastNameIndex > m_LastNames.size()) return std::string("INVALID"); return std::string(m_FirstNames[firstNameIndex] + m_MiddleNames[middleNameIndex] + m_LastNames[lastNameIndex]); } -bool UserManager::IsNamePreapproved ( const std::string& requestedName ) { +bool UserManager::IsNamePreapproved(const std::string& requestedName) { for (std::string& s : m_PreapprovedNames) { if (s == requestedName) return true; } @@ -174,7 +171,7 @@ bool UserManager::IsNamePreapproved ( const std::string& requestedName ) { return false; } -void UserManager::RequestCharacterList ( const SystemAddress& sysAddr ) { +void UserManager::RequestCharacterList(const SystemAddress& sysAddr) { User* u = GetUser(sysAddr); if (!u) return; @@ -185,8 +182,7 @@ void UserManager::RequestCharacterList ( const SystemAddress& sysAddr ) { if (res->rowsCount() > 0) { std::vector& chars = u->GetCharacters(); - for (size_t i = 0; i < chars.size(); ++i) - { + for (size_t i = 0; i < chars.size(); ++i) { if (chars[i]->GetEntity() == nullptr) // We don't have entity data to save { delete chars[i]; @@ -196,8 +192,7 @@ void UserManager::RequestCharacterList ( const SystemAddress& sysAddr ) { auto* skillComponent = chars[i]->GetEntity()->GetComponent(); - if (skillComponent != nullptr) - { + if (skillComponent != nullptr) { skillComponent->Reset(); } @@ -226,166 +221,164 @@ void UserManager::RequestCharacterList ( const SystemAddress& sysAddr ) { } void UserManager::CreateCharacter(const SystemAddress& sysAddr, Packet* packet) { - User* u = GetUser(sysAddr); - if (!u) return; + User* u = GetUser(sysAddr); + if (!u) return; - std::string name = PacketUtils::ReadString(8, packet, true); + std::string name = PacketUtils::ReadString(8, packet, true); - uint32_t firstNameIndex = PacketUtils::ReadPacketU32(74, packet); - uint32_t middleNameIndex = PacketUtils::ReadPacketU32(78, packet); - uint32_t lastNameIndex = PacketUtils::ReadPacketU32(82, packet); - std::string predefinedName = GetPredefinedName(firstNameIndex, middleNameIndex, lastNameIndex); + uint32_t firstNameIndex = PacketUtils::ReadPacketU32(74, packet); + uint32_t middleNameIndex = PacketUtils::ReadPacketU32(78, packet); + uint32_t lastNameIndex = PacketUtils::ReadPacketU32(82, packet); + std::string predefinedName = GetPredefinedName(firstNameIndex, middleNameIndex, lastNameIndex); - uint32_t shirtColor = PacketUtils::ReadPacketU32(95, packet); - uint32_t shirtStyle = PacketUtils::ReadPacketU32(99, packet); - uint32_t pantsColor = PacketUtils::ReadPacketU32(103, packet); - uint32_t hairStyle = PacketUtils::ReadPacketU32(107, packet); - uint32_t hairColor = PacketUtils::ReadPacketU32(111, packet); - uint32_t lh = PacketUtils::ReadPacketU32(115, packet); - uint32_t rh = PacketUtils::ReadPacketU32(119, packet); - uint32_t eyebrows = PacketUtils::ReadPacketU32(123, packet); - uint32_t eyes = PacketUtils::ReadPacketU32(127, packet); - uint32_t mouth = PacketUtils::ReadPacketU32(131, packet); + uint32_t shirtColor = PacketUtils::ReadPacketU32(95, packet); + uint32_t shirtStyle = PacketUtils::ReadPacketU32(99, packet); + uint32_t pantsColor = PacketUtils::ReadPacketU32(103, packet); + uint32_t hairStyle = PacketUtils::ReadPacketU32(107, packet); + uint32_t hairColor = PacketUtils::ReadPacketU32(111, packet); + uint32_t lh = PacketUtils::ReadPacketU32(115, packet); + uint32_t rh = PacketUtils::ReadPacketU32(119, packet); + uint32_t eyebrows = PacketUtils::ReadPacketU32(123, packet); + uint32_t eyes = PacketUtils::ReadPacketU32(127, packet); + uint32_t mouth = PacketUtils::ReadPacketU32(131, packet); - LOT shirtLOT = FindCharShirtID(shirtColor, shirtStyle); + LOT shirtLOT = FindCharShirtID(shirtColor, shirtStyle); LOT pantsLOT = FindCharPantsID(pantsColor); - if (name != "" && !UserManager::IsNameAvailable(name)) { - Game::logger->Log("UserManager", "AccountID: %i chose unavailable name: %s", u->GetAccountID(), name.c_str()); - WorldPackets::SendCharacterCreationResponse(sysAddr, CREATION_RESPONSE_CUSTOM_NAME_IN_USE); - return; - } + if (name != "" && !UserManager::IsNameAvailable(name)) { + Game::logger->Log("UserManager", "AccountID: %i chose unavailable name: %s", u->GetAccountID(), name.c_str()); + WorldPackets::SendCharacterCreationResponse(sysAddr, CREATION_RESPONSE_CUSTOM_NAME_IN_USE); + return; + } - if (!IsNameAvailable(predefinedName)) { - Game::logger->Log("UserManager", "AccountID: %i chose unavailable predefined name: %s", u->GetAccountID(), predefinedName.c_str()); - WorldPackets::SendCharacterCreationResponse(sysAddr, CREATION_RESPONSE_PREDEFINED_NAME_IN_USE); - return; - } + if (!IsNameAvailable(predefinedName)) { + Game::logger->Log("UserManager", "AccountID: %i chose unavailable predefined name: %s", u->GetAccountID(), predefinedName.c_str()); + WorldPackets::SendCharacterCreationResponse(sysAddr, CREATION_RESPONSE_PREDEFINED_NAME_IN_USE); + return; + } - if (name == "") { - Game::logger->Log("UserManager", "AccountID: %i is creating a character with predefined name: %s", u->GetAccountID(), predefinedName.c_str()); - } - else { - Game::logger->Log("UserManager", "AccountID: %i is creating a character with name: %s (temporary: %s)", u->GetAccountID(), name.c_str(), predefinedName.c_str()); - } + if (name == "") { + Game::logger->Log("UserManager", "AccountID: %i is creating a character with predefined name: %s", u->GetAccountID(), predefinedName.c_str()); + } else { + Game::logger->Log("UserManager", "AccountID: %i is creating a character with name: %s (temporary: %s)", u->GetAccountID(), name.c_str(), predefinedName.c_str()); + } - //Now that the name is ok, we can get an objectID from Master: - ObjectIDManager::Instance()->RequestPersistentID([=](uint32_t objectID) { + //Now that the name is ok, we can get an objectID from Master: + ObjectIDManager::Instance()->RequestPersistentID([=](uint32_t objectID) { sql::PreparedStatement* overlapStmt = Database::CreatePreppedStmt("SELECT id FROM charinfo WHERE id = ?"); overlapStmt->setUInt(1, objectID); auto* overlapResult = overlapStmt->executeQuery(); - if (overlapResult->next()) { + if (overlapResult->next()) { Game::logger->Log("UserManager", "Character object id unavailable, check objectidtracker!"); WorldPackets::SendCharacterCreationResponse(sysAddr, CREATION_RESPONSE_OBJECT_ID_UNAVAILABLE); - return; - } + return; + } - std::stringstream xml; - xml << ""; + std::stringstream xml; + xml << ""; - xml << "GetAccountID() << "\" cc=\"0\" gm=\"0\" ft=\"0\" llog=\"" << time(NULL) << "\" "; - xml << "ls=\"0\" lzx=\"-626.5847\" lzy=\"613.3515\" lzz=\"-28.6374\" lzrx=\"0.0\" lzry=\"0.7015\" lzrz=\"0.0\" lzrw=\"0.7126\" "; - xml << "stt=\"0;0;0;0;0;0;0;0;0;0;0;0;0;0;0;0;0;0;0;0;0;0;0;0;0;0;0;\">"; - xml << ""; - xml << ""; - std::string xmlSave1 = xml.str(); + xml << "GetAccountID() << "\" cc=\"0\" gm=\"0\" ft=\"0\" llog=\"" << time(NULL) << "\" "; + xml << "ls=\"0\" lzx=\"-626.5847\" lzy=\"613.3515\" lzz=\"-28.6374\" lzrx=\"0.0\" lzry=\"0.7015\" lzrz=\"0.0\" lzrw=\"0.7126\" "; + xml << "stt=\"0;0;0;0;0;0;0;0;0;0;0;0;0;0;0;0;0;0;0;0;0;0;0;0;0;0;0;\">"; + xml << ""; + xml << ""; + std::string xmlSave1 = xml.str(); - ObjectIDManager::Instance()->RequestPersistentID([=](uint32_t idforshirt) { - std::stringstream xml2; + ObjectIDManager::Instance()->RequestPersistentID([=](uint32_t idforshirt) { + std::stringstream xml2; - LWOOBJID lwoidforshirt = idforshirt; - lwoidforshirt = GeneralUtils::SetBit(lwoidforshirt, OBJECT_BIT_CHARACTER); - lwoidforshirt = GeneralUtils::SetBit(lwoidforshirt, OBJECT_BIT_PERSISTENT); - xml2 << xmlSave1 << ""; + LWOOBJID lwoidforshirt = idforshirt; + lwoidforshirt = GeneralUtils::SetBit(lwoidforshirt, OBJECT_BIT_CHARACTER); + lwoidforshirt = GeneralUtils::SetBit(lwoidforshirt, OBJECT_BIT_PERSISTENT); + xml2 << xmlSave1 << ""; - std::string xmlSave2 = xml2.str(); + std::string xmlSave2 = xml2.str(); - ObjectIDManager::Instance()->RequestPersistentID([=](uint32_t idforpants) { - LWOOBJID lwoidforpants = idforpants; - lwoidforpants = GeneralUtils::SetBit(lwoidforpants, OBJECT_BIT_CHARACTER); - lwoidforpants = GeneralUtils::SetBit(lwoidforpants, OBJECT_BIT_PERSISTENT); + ObjectIDManager::Instance()->RequestPersistentID([=](uint32_t idforpants) { + LWOOBJID lwoidforpants = idforpants; + lwoidforpants = GeneralUtils::SetBit(lwoidforpants, OBJECT_BIT_CHARACTER); + lwoidforpants = GeneralUtils::SetBit(lwoidforpants, OBJECT_BIT_PERSISTENT); - std::stringstream xml3; - xml3 << xmlSave2 << ""; + std::stringstream xml3; + xml3 << xmlSave2 << ""; - xml3 << ""; + xml3 << ""; - //Check to see if our name was pre-approved: - bool nameOk = IsNamePreapproved(name); - if (!nameOk && u->GetMaxGMLevel() > 1) nameOk = true; + //Check to see if our name was pre-approved: + bool nameOk = IsNamePreapproved(name); + if (!nameOk && u->GetMaxGMLevel() > 1) nameOk = true; - if (name != "") { - sql::PreparedStatement* stmt = Database::CreatePreppedStmt("INSERT INTO `charinfo`(`id`, `account_id`, `name`, `pending_name`, `needs_rename`, `last_login`) VALUES (?,?,?,?,?,?)"); - stmt->setUInt(1, objectID); - stmt->setUInt(2, u->GetAccountID()); - stmt->setString(3, predefinedName.c_str()); - stmt->setString(4, name.c_str()); - stmt->setBoolean(5, false); - stmt->setUInt64(6, time(NULL)); + if (name != "") { + sql::PreparedStatement* stmt = Database::CreatePreppedStmt("INSERT INTO `charinfo`(`id`, `account_id`, `name`, `pending_name`, `needs_rename`, `last_login`) VALUES (?,?,?,?,?,?)"); + stmt->setUInt(1, objectID); + stmt->setUInt(2, u->GetAccountID()); + stmt->setString(3, predefinedName.c_str()); + stmt->setString(4, name.c_str()); + stmt->setBoolean(5, false); + stmt->setUInt64(6, time(NULL)); - if (nameOk) { - stmt->setString(3, name.c_str()); - stmt->setString(4, ""); - } + if (nameOk) { + stmt->setString(3, name.c_str()); + stmt->setString(4, ""); + } - stmt->execute(); - delete stmt; - } else { - sql::PreparedStatement* stmt = Database::CreatePreppedStmt("INSERT INTO `charinfo`(`id`, `account_id`, `name`, `pending_name`, `needs_rename`, `last_login`) VALUES (?,?,?,?,?,?)"); - stmt->setUInt(1, objectID); - stmt->setUInt(2, u->GetAccountID()); - stmt->setString(3, predefinedName.c_str()); - stmt->setString(4, ""); - stmt->setBoolean(5, false); - stmt->setUInt64(6, time(NULL)); + stmt->execute(); + delete stmt; + } else { + sql::PreparedStatement* stmt = Database::CreatePreppedStmt("INSERT INTO `charinfo`(`id`, `account_id`, `name`, `pending_name`, `needs_rename`, `last_login`) VALUES (?,?,?,?,?,?)"); + stmt->setUInt(1, objectID); + stmt->setUInt(2, u->GetAccountID()); + stmt->setString(3, predefinedName.c_str()); + stmt->setString(4, ""); + stmt->setBoolean(5, false); + stmt->setUInt64(6, time(NULL)); - stmt->execute(); - delete stmt; - } + stmt->execute(); + delete stmt; + } - //Now finally insert our character xml: - sql::PreparedStatement* stmt = Database::CreatePreppedStmt("INSERT INTO `charxml`(`id`, `xml_data`) VALUES (?,?)"); - stmt->setUInt(1, objectID); - stmt->setString(2, xml3.str().c_str()); - stmt->execute(); - delete stmt; + //Now finally insert our character xml: + sql::PreparedStatement* stmt = Database::CreatePreppedStmt("INSERT INTO `charxml`(`id`, `xml_data`) VALUES (?,?)"); + stmt->setUInt(1, objectID); + stmt->setString(2, xml3.str().c_str()); + stmt->execute(); + delete stmt; - WorldPackets::SendCharacterCreationResponse(sysAddr, CREATION_RESPONSE_SUCCESS); - UserManager::RequestCharacterList(sysAddr); - }); - }); - }); + WorldPackets::SendCharacterCreationResponse(sysAddr, CREATION_RESPONSE_SUCCESS); + UserManager::RequestCharacterList(sysAddr); + }); + }); + }); } void UserManager::DeleteCharacter(const SystemAddress& sysAddr, Packet* packet) { - User* u = GetUser(sysAddr); - if (!u) { - Game::logger->Log("UserManager", "Couldn't get user to delete character"); - return; - } + User* u = GetUser(sysAddr); + if (!u) { + Game::logger->Log("UserManager", "Couldn't get user to delete character"); + return; + } - LWOOBJID objectID = PacketUtils::ReadPacketS64(8, packet); + LWOOBJID objectID = PacketUtils::ReadPacketS64(8, packet); uint32_t charID = static_cast(objectID); - Game::logger->Log("UserManager", "Received char delete req for ID: %llu (%u)", objectID, charID); + Game::logger->Log("UserManager", "Received char delete req for ID: %llu (%u)", objectID, charID); - //Check if this user has this character: - bool hasCharacter = false; - std::vector& characters = u->GetCharacters(); - for (size_t i = 0; i < characters.size(); ++i) { - if (characters[i]->GetID() == charID) { hasCharacter = true; } - } + //Check if this user has this character: + bool hasCharacter = false; + std::vector& characters = u->GetCharacters(); + for (size_t i = 0; i < characters.size(); ++i) { + if (characters[i]->GetID() == charID) { hasCharacter = true; } + } - if (!hasCharacter) { - Game::logger->Log("UserManager", "User %i tried to delete a character that it does not own!", u->GetAccountID()); - WorldPackets::SendCharacterDeleteResponse(sysAddr, false); - } - else { - Game::logger->Log("UserManager", "Deleting character %i", charID); + if (!hasCharacter) { + Game::logger->Log("UserManager", "User %i tried to delete a character that it does not own!", u->GetAccountID()); + WorldPackets::SendCharacterDeleteResponse(sysAddr, false); + } else { + Game::logger->Log("UserManager", "Deleting character %i", charID); { sql::PreparedStatement* stmt = Database::CreatePreppedStmt("DELETE FROM charxml WHERE id=? LIMIT 1;"); stmt->setUInt64(1, charID); @@ -454,115 +447,115 @@ void UserManager::DeleteCharacter(const SystemAddress& sysAddr, Packet* packet) delete stmt; } - WorldPackets::SendCharacterDeleteResponse(sysAddr, true); - } + WorldPackets::SendCharacterDeleteResponse(sysAddr, true); + } } void UserManager::RenameCharacter(const SystemAddress& sysAddr, Packet* packet) { - User* u = GetUser(sysAddr); - if (!u) { - Game::logger->Log("UserManager", "Couldn't get user to delete character"); - return; - } + User* u = GetUser(sysAddr); + if (!u) { + Game::logger->Log("UserManager", "Couldn't get user to delete character"); + return; + } - LWOOBJID objectID = PacketUtils::ReadPacketS64(8, packet); - objectID = GeneralUtils::ClearBit(objectID, OBJECT_BIT_CHARACTER); - objectID = GeneralUtils::ClearBit(objectID, OBJECT_BIT_PERSISTENT); + LWOOBJID objectID = PacketUtils::ReadPacketS64(8, packet); + objectID = GeneralUtils::ClearBit(objectID, OBJECT_BIT_CHARACTER); + objectID = GeneralUtils::ClearBit(objectID, OBJECT_BIT_PERSISTENT); - uint32_t charID = static_cast(objectID); - Game::logger->Log("UserManager", "Received char rename request for ID: %llu (%u)", objectID, charID); + uint32_t charID = static_cast(objectID); + Game::logger->Log("UserManager", "Received char rename request for ID: %llu (%u)", objectID, charID); - std::string newName = PacketUtils::ReadString(16, packet, true); + std::string newName = PacketUtils::ReadString(16, packet, true); - Character* character = nullptr; + Character* character = nullptr; - //Check if this user has this character: - bool hasCharacter = false; - std::vector& characters = u->GetCharacters(); - for (size_t i = 0; i < characters.size(); ++i) { - if (characters[i]->GetID() == charID) { hasCharacter = true; character = characters[i]; } - } + //Check if this user has this character: + bool hasCharacter = false; + std::vector& characters = u->GetCharacters(); + for (size_t i = 0; i < characters.size(); ++i) { + if (characters[i]->GetID() == charID) { hasCharacter = true; character = characters[i]; } + } - if (!hasCharacter || !character) { - Game::logger->Log("UserManager", "User %i tried to rename a character that it does not own!", u->GetAccountID()); - WorldPackets::SendCharacterRenameResponse(sysAddr, RENAME_RESPONSE_UNKNOWN_ERROR); - } else if (hasCharacter && character) { - if (newName == character->GetName()) { - WorldPackets::SendCharacterRenameResponse(sysAddr, RENAME_RESPONSE_NAME_UNAVAILABLE); - return; - } + if (!hasCharacter || !character) { + Game::logger->Log("UserManager", "User %i tried to rename a character that it does not own!", u->GetAccountID()); + WorldPackets::SendCharacterRenameResponse(sysAddr, RENAME_RESPONSE_UNKNOWN_ERROR); + } else if (hasCharacter && character) { + if (newName == character->GetName()) { + WorldPackets::SendCharacterRenameResponse(sysAddr, RENAME_RESPONSE_NAME_UNAVAILABLE); + return; + } - if (IsNameAvailable(newName)) { - if (IsNamePreapproved(newName)) { - sql::PreparedStatement* stmt = Database::CreatePreppedStmt("UPDATE charinfo SET name=?, pending_name='', needs_rename=0, last_login=? WHERE id=? LIMIT 1"); - stmt->setString(1, newName); - stmt->setUInt64(2, time(NULL)); - stmt->setUInt(3, character->GetID()); - stmt->execute(); - delete stmt; + if (IsNameAvailable(newName)) { + if (IsNamePreapproved(newName)) { + sql::PreparedStatement* stmt = Database::CreatePreppedStmt("UPDATE charinfo SET name=?, pending_name='', needs_rename=0, last_login=? WHERE id=? LIMIT 1"); + stmt->setString(1, newName); + stmt->setUInt64(2, time(NULL)); + stmt->setUInt(3, character->GetID()); + stmt->execute(); + delete stmt; - Game::logger->Log("UserManager", "Character %s now known as %s", character->GetName().c_str(), newName.c_str()); - WorldPackets::SendCharacterRenameResponse(sysAddr, RENAME_RESPONSE_SUCCESS); - UserManager::RequestCharacterList(sysAddr); - } else { - sql::PreparedStatement* stmt = Database::CreatePreppedStmt("UPDATE charinfo SET pending_name=?, needs_rename=0, last_login=? WHERE id=? LIMIT 1"); - stmt->setString(1, newName); - stmt->setUInt64(2, time(NULL)); - stmt->setUInt(3, character->GetID()); - stmt->execute(); - delete stmt; + Game::logger->Log("UserManager", "Character %s now known as %s", character->GetName().c_str(), newName.c_str()); + WorldPackets::SendCharacterRenameResponse(sysAddr, RENAME_RESPONSE_SUCCESS); + UserManager::RequestCharacterList(sysAddr); + } else { + sql::PreparedStatement* stmt = Database::CreatePreppedStmt("UPDATE charinfo SET pending_name=?, needs_rename=0, last_login=? WHERE id=? LIMIT 1"); + stmt->setString(1, newName); + stmt->setUInt64(2, time(NULL)); + stmt->setUInt(3, character->GetID()); + stmt->execute(); + delete stmt; - Game::logger->Log("UserManager", "Character %s has been renamed to %s and is pending approval by a moderator.", character->GetName().c_str(), newName.c_str()); - WorldPackets::SendCharacterRenameResponse(sysAddr, RENAME_RESPONSE_SUCCESS); - UserManager::RequestCharacterList(sysAddr); - } - } else { - WorldPackets::SendCharacterRenameResponse(sysAddr, RENAME_RESPONSE_NAME_IN_USE); - } - } else { - Game::logger->Log("UserManager", "Unknown error occurred when renaming character, either hasCharacter or character variable != true."); - WorldPackets::SendCharacterRenameResponse(sysAddr, RENAME_RESPONSE_UNKNOWN_ERROR); - } + Game::logger->Log("UserManager", "Character %s has been renamed to %s and is pending approval by a moderator.", character->GetName().c_str(), newName.c_str()); + WorldPackets::SendCharacterRenameResponse(sysAddr, RENAME_RESPONSE_SUCCESS); + UserManager::RequestCharacterList(sysAddr); + } + } else { + WorldPackets::SendCharacterRenameResponse(sysAddr, RENAME_RESPONSE_NAME_IN_USE); + } + } else { + Game::logger->Log("UserManager", "Unknown error occurred when renaming character, either hasCharacter or character variable != true."); + WorldPackets::SendCharacterRenameResponse(sysAddr, RENAME_RESPONSE_UNKNOWN_ERROR); + } } void UserManager::LoginCharacter(const SystemAddress& sysAddr, uint32_t playerID) { - User* u = GetUser(sysAddr); - if (!u) { - Game::logger->Log("UserManager", "Couldn't get user to log in character"); - return; - } + User* u = GetUser(sysAddr); + if (!u) { + Game::logger->Log("UserManager", "Couldn't get user to log in character"); + return; + } - Character* character = nullptr; - bool hasCharacter = false; - std::vector& characters = u->GetCharacters(); + Character* character = nullptr; + bool hasCharacter = false; + std::vector& characters = u->GetCharacters(); - for (size_t i = 0; i < characters.size(); ++i) { - if (characters[i]->GetID() == playerID) { hasCharacter = true; character = characters[i]; } - } + for (size_t i = 0; i < characters.size(); ++i) { + if (characters[i]->GetID() == playerID) { hasCharacter = true; character = characters[i]; } + } - if (hasCharacter && character) { - sql::PreparedStatement* stmt = Database::CreatePreppedStmt("UPDATE charinfo SET last_login=? WHERE id=? LIMIT 1"); - stmt->setUInt64(1, time(NULL)); - stmt->setUInt(2, playerID); - stmt->execute(); - delete stmt; + if (hasCharacter && character) { + sql::PreparedStatement* stmt = Database::CreatePreppedStmt("UPDATE charinfo SET last_login=? WHERE id=? LIMIT 1"); + stmt->setUInt64(1, time(NULL)); + stmt->setUInt(2, playerID); + stmt->execute(); + delete stmt; - uint32_t zoneID = character->GetZoneID(); + uint32_t zoneID = character->GetZoneID(); if (zoneID == LWOZONEID_INVALID) zoneID = 1000; //Send char to VE - ZoneInstanceManager::Instance()->RequestZoneTransfer(Game::server, zoneID, character->GetZoneClone(), false, [=](bool mythranShift, uint32_t zoneID, uint32_t zoneInstance, uint32_t zoneClone, std::string serverIP, uint16_t serverPort) { - Game::logger->Log("UserManager", "Transferring %s to Zone %i (Instance %i | Clone %i | Mythran Shift: %s) with IP %s and Port %i", character->GetName().c_str(), zoneID, zoneInstance, zoneClone, mythranShift == true ? "true" : "false", serverIP.c_str(), serverPort); + ZoneInstanceManager::Instance()->RequestZoneTransfer(Game::server, zoneID, character->GetZoneClone(), false, [=](bool mythranShift, uint32_t zoneID, uint32_t zoneInstance, uint32_t zoneClone, std::string serverIP, uint16_t serverPort) { + Game::logger->Log("UserManager", "Transferring %s to Zone %i (Instance %i | Clone %i | Mythran Shift: %s) with IP %s and Port %i", character->GetName().c_str(), zoneID, zoneInstance, zoneClone, mythranShift == true ? "true" : "false", serverIP.c_str(), serverPort); if (character) { character->SetZoneID(zoneID); character->SetZoneInstance(zoneInstance); character->SetZoneClone(zoneClone); } WorldPackets::SendTransferToWorld(sysAddr, serverIP, serverPort, mythranShift); - return; - }); - } else { - Game::logger->Log("UserManager", "Unknown error occurred when logging in a character, either hasCharacter or character variable != true."); - } + return; + }); + } else { + Game::logger->Log("UserManager", "Unknown error occurred when logging in a character, either hasCharacter or character variable != true."); + } } uint32_t FindCharShirtID(uint32_t shirtColor, uint32_t shirtStyle) { @@ -575,8 +568,7 @@ uint32_t FindCharShirtID(uint32_t shirtColor, uint32_t shirtStyle) { auto shirtLOT = tableData.getIntField(0, -1); tableData.finalize(); return shirtLOT; - } - catch (const std::exception&){ + } catch (const std::exception&) { Game::logger->Log("Character Create", "Failed to execute query! Using backup..."); // in case of no shirt found in CDServer, return problematic red vest. return 4069; @@ -591,8 +583,7 @@ uint32_t FindCharPantsID(uint32_t pantsColor) { auto pantsLOT = tableData.getIntField(0, -1); tableData.finalize(); return pantsLOT; - } - catch (const std::exception&){ + } catch (const std::exception&) { Game::logger->Log("Character Create", "Failed to execute query! Using backup..."); // in case of no pants color found in CDServer, return red pants. return 2508; diff --git a/dGame/UserManager.h b/dGame/UserManager.h index a5db6979..bf9985a1 100644 --- a/dGame/UserManager.h +++ b/dGame/UserManager.h @@ -15,23 +15,23 @@ public: if (!m_Address) { m_Address = new UserManager(); } - + return m_Address; } - + void Initialize(); ~UserManager(); - + User* CreateUser(const SystemAddress& sysAddr, const std::string& username, const std::string& sessionKey); User* GetUser(const SystemAddress& sysAddr); User* GetUser(const std::string& username); bool DeleteUser(const SystemAddress& sysAddr); //Returns true on succesful deletion void DeletePendingRemovals(); - + bool IsNameAvailable(const std::string& requestedName); std::string GetPredefinedName(uint32_t firstNameIndex, uint32_t middleNameIndex, uint32_t lastNameIndex); bool IsNamePreapproved(const std::string& requestedName); - + void RequestCharacterList(const SystemAddress& sysAddr); void CreateCharacter(const SystemAddress& sysAddr, Packet* packet); void DeleteCharacter(const SystemAddress& sysAddr, Packet* packet); @@ -46,7 +46,7 @@ private: static UserManager* m_Address; //Singleton std::map m_Users; std::vector m_UsersToDelete; - + std::vector m_FirstNames; std::vector m_MiddleNames; std::vector m_LastNames; diff --git a/dGame/dBehaviors/AirMovementBehavior.cpp b/dGame/dBehaviors/AirMovementBehavior.cpp index ac7bf667..188d743d 100644 --- a/dGame/dBehaviors/AirMovementBehavior.cpp +++ b/dGame/dBehaviors/AirMovementBehavior.cpp @@ -3,8 +3,7 @@ #include "BehaviorContext.h" #include "EntityManager.h" -void AirMovementBehavior::Handle(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) -{ +void AirMovementBehavior::Handle(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) { uint32_t handle; bitStream->Read(handle); @@ -12,15 +11,13 @@ void AirMovementBehavior::Handle(BehaviorContext* context, RakNet::BitStream* bi context->RegisterSyncBehavior(handle, this, branch); } -void AirMovementBehavior::Calculate(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) -{ +void AirMovementBehavior::Calculate(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) { const auto handle = context->GetUniqueSkillId(); bitStream->Write(handle); } -void AirMovementBehavior::Sync(BehaviorContext* context, RakNet::BitStream* bit_stream, BehaviorBranchContext branch) -{ +void AirMovementBehavior::Sync(BehaviorContext* context, RakNet::BitStream* bit_stream, BehaviorBranchContext branch) { uint32_t behaviorId; bit_stream->Read(behaviorId); @@ -31,14 +28,12 @@ void AirMovementBehavior::Sync(BehaviorContext* context, RakNet::BitStream* bit_ auto* behavior = CreateBehavior(behaviorId); - if (EntityManager::Instance()->GetEntity(target) != nullptr) - { + if (EntityManager::Instance()->GetEntity(target) != nullptr) { branch.target = target; } - + behavior->Handle(context, bit_stream, branch); } -void AirMovementBehavior::Load() -{ +void AirMovementBehavior::Load() { } diff --git a/dGame/dBehaviors/AirMovementBehavior.h b/dGame/dBehaviors/AirMovementBehavior.h index 0a9755e6..6c3a2abf 100644 --- a/dGame/dBehaviors/AirMovementBehavior.h +++ b/dGame/dBehaviors/AirMovementBehavior.h @@ -9,8 +9,7 @@ public: * Inherited */ - explicit AirMovementBehavior(const uint32_t behavior_id) : Behavior(behavior_id) - { + explicit AirMovementBehavior(const uint32_t behavior_id) : Behavior(behavior_id) { } void Handle(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) override; diff --git a/dGame/dBehaviors/AndBehavior.cpp b/dGame/dBehaviors/AndBehavior.cpp index 5fc1e113..d54d9ec5 100644 --- a/dGame/dBehaviors/AndBehavior.cpp +++ b/dGame/dBehaviors/AndBehavior.cpp @@ -3,18 +3,14 @@ #include "Game.h" #include "dLogger.h" -void AndBehavior::Handle(BehaviorContext* context, RakNet::BitStream* bitStream, const BehaviorBranchContext branch) -{ - for (auto* behavior : this->m_behaviors) - { +void AndBehavior::Handle(BehaviorContext* context, RakNet::BitStream* bitStream, const BehaviorBranchContext branch) { + for (auto* behavior : this->m_behaviors) { behavior->Handle(context, bitStream, branch); } } -void AndBehavior::Calculate(BehaviorContext* context, RakNet::BitStream* bitStream, const BehaviorBranchContext branch) -{ - for (auto* behavior : this->m_behaviors) - { +void AndBehavior::Calculate(BehaviorContext* context, RakNet::BitStream* bitStream, const BehaviorBranchContext branch) { + for (auto* behavior : this->m_behaviors) { behavior->Calculate(context, bitStream, branch); } } @@ -25,14 +21,11 @@ void AndBehavior::UnCast(BehaviorContext* context, const BehaviorBranchContext b } } -void AndBehavior::Load() -{ +void AndBehavior::Load() { const auto parameters = GetParameterNames(); - for (const auto& parameter : parameters) - { - if (parameter.first.rfind("behavior", 0) == 0) - { + for (const auto& parameter : parameters) { + if (parameter.first.rfind("behavior", 0) == 0) { auto* action = GetAction(parameter.second); this->m_behaviors.push_back(action); diff --git a/dGame/dBehaviors/AndBehavior.h b/dGame/dBehaviors/AndBehavior.h index 9cbce569..17d1e51e 100644 --- a/dGame/dBehaviors/AndBehavior.h +++ b/dGame/dBehaviors/AndBehavior.h @@ -8,18 +8,17 @@ class AndBehavior final : public Behavior { public: std::vector m_behaviors; - + /* * Inherited */ - explicit AndBehavior(const uint32_t behaviorId) : Behavior(behaviorId) - { + explicit AndBehavior(const uint32_t behaviorId) : Behavior(behaviorId) { } void Handle(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) override; void Calculate(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) override; - + void UnCast(BehaviorContext* context, BehaviorBranchContext branch) override; void Load() override; diff --git a/dGame/dBehaviors/ApplyBuffBehavior.cpp b/dGame/dBehaviors/ApplyBuffBehavior.cpp index 46422aa1..35b0f269 100644 --- a/dGame/dBehaviors/ApplyBuffBehavior.cpp +++ b/dGame/dBehaviors/ApplyBuffBehavior.cpp @@ -5,48 +5,44 @@ #include "BuffComponent.h" -void ApplyBuffBehavior::Handle(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) -{ - auto* entity = EntityManager::Instance()->GetEntity(branch.target == LWOOBJID_EMPTY ? context->originator : branch.target); +void ApplyBuffBehavior::Handle(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) { + auto* entity = EntityManager::Instance()->GetEntity(branch.target == LWOOBJID_EMPTY ? context->originator : branch.target); - if (entity == nullptr) return; + if (entity == nullptr) return; - auto* buffComponent = entity->GetComponent(); + auto* buffComponent = entity->GetComponent(); - if (buffComponent == nullptr) return; + if (buffComponent == nullptr) return; - buffComponent->ApplyBuff(m_BuffId, m_Duration, context->originator, addImmunity, cancelOnDamaged, cancelOnDeath, - cancelOnLogout, cancelonRemoveBuff, cancelOnUi, cancelOnUnequip, cancelOnZone); + buffComponent->ApplyBuff(m_BuffId, m_Duration, context->originator, addImmunity, cancelOnDamaged, cancelOnDeath, + cancelOnLogout, cancelonRemoveBuff, cancelOnUi, cancelOnUnequip, cancelOnZone); } -void ApplyBuffBehavior::UnCast(BehaviorContext* context, BehaviorBranchContext branch) -{ - auto* entity = EntityManager::Instance()->GetEntity(branch.target); +void ApplyBuffBehavior::UnCast(BehaviorContext* context, BehaviorBranchContext branch) { + auto* entity = EntityManager::Instance()->GetEntity(branch.target); - if (entity == nullptr) return; + if (entity == nullptr) return; - auto* buffComponent = entity->GetComponent(); + auto* buffComponent = entity->GetComponent(); - if (buffComponent == nullptr) return; + if (buffComponent == nullptr) return; - buffComponent->RemoveBuff(m_BuffId); + buffComponent->RemoveBuff(m_BuffId); } -void ApplyBuffBehavior::Calculate(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) -{ - Handle(context, bitStream, branch); +void ApplyBuffBehavior::Calculate(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) { + Handle(context, bitStream, branch); } -void ApplyBuffBehavior::Load() -{ - m_BuffId = GetInt("buff_id"); - m_Duration = GetFloat("duration_secs"); - addImmunity = GetBoolean("add_immunity"); - cancelOnDamaged = GetBoolean("cancel_on_damaged"); - cancelOnDeath = GetBoolean("cancel_on_death"); - cancelOnLogout = GetBoolean("cancel_on_logout"); - cancelonRemoveBuff = GetBoolean("cancel_on_remove_buff"); - cancelOnUi = GetBoolean("cancel_on_ui"); - cancelOnUnequip = GetBoolean("cancel_on_unequip"); - cancelOnZone = GetBoolean("cancel_on_zone"); +void ApplyBuffBehavior::Load() { + m_BuffId = GetInt("buff_id"); + m_Duration = GetFloat("duration_secs"); + addImmunity = GetBoolean("add_immunity"); + cancelOnDamaged = GetBoolean("cancel_on_damaged"); + cancelOnDeath = GetBoolean("cancel_on_death"); + cancelOnLogout = GetBoolean("cancel_on_logout"); + cancelonRemoveBuff = GetBoolean("cancel_on_remove_buff"); + cancelOnUi = GetBoolean("cancel_on_ui"); + cancelOnUnequip = GetBoolean("cancel_on_unequip"); + cancelOnZone = GetBoolean("cancel_on_zone"); } diff --git a/dGame/dBehaviors/ApplyBuffBehavior.h b/dGame/dBehaviors/ApplyBuffBehavior.h index 536d3501..139082df 100644 --- a/dGame/dBehaviors/ApplyBuffBehavior.h +++ b/dGame/dBehaviors/ApplyBuffBehavior.h @@ -7,29 +7,28 @@ class ApplyBuffBehavior final : public Behavior { public: - int32_t m_BuffId; - float m_Duration; - bool addImmunity; - bool cancelOnDamaged; - bool cancelOnDeath; - bool cancelOnLogout; - bool cancelonRemoveBuff; - bool cancelOnUi; - bool cancelOnUnequip; - bool cancelOnZone; + int32_t m_BuffId; + float m_Duration; + bool addImmunity; + bool cancelOnDamaged; + bool cancelOnDeath; + bool cancelOnLogout; + bool cancelonRemoveBuff; + bool cancelOnUi; + bool cancelOnUnequip; + bool cancelOnZone; /* * Inherited */ - explicit ApplyBuffBehavior(const uint32_t behaviorId) : Behavior(behaviorId) - { + explicit ApplyBuffBehavior(const uint32_t behaviorId) : Behavior(behaviorId) { } void Handle(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) override; - void UnCast(BehaviorContext* context, BehaviorBranchContext branch) override; + void UnCast(BehaviorContext* context, BehaviorBranchContext branch) override; void Calculate(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) override; - + void Load() override; }; diff --git a/dGame/dBehaviors/AreaOfEffectBehavior.cpp b/dGame/dBehaviors/AreaOfEffectBehavior.cpp index e3f992e7..ba0f69a5 100644 --- a/dGame/dBehaviors/AreaOfEffectBehavior.cpp +++ b/dGame/dBehaviors/AreaOfEffectBehavior.cpp @@ -10,14 +10,12 @@ #include "RebuildComponent.h" #include "DestroyableComponent.h" -void AreaOfEffectBehavior::Handle(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) -{ +void AreaOfEffectBehavior::Handle(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) { uint32_t targetCount; bitStream->Read(targetCount); - if (targetCount > this->m_maxTargets) - { + if (targetCount > this->m_maxTargets) { return; } @@ -25,8 +23,7 @@ void AreaOfEffectBehavior::Handle(BehaviorContext* context, RakNet::BitStream* b targets.reserve(targetCount); - for (auto i = 0u; i < targetCount; ++i) - { + for (auto i = 0u; i < targetCount; ++i) { LWOOBJID target; bitStream->Read(target); @@ -34,20 +31,17 @@ void AreaOfEffectBehavior::Handle(BehaviorContext* context, RakNet::BitStream* b targets.push_back(target); } - for (auto target : targets) - { + for (auto target : targets) { branch.target = target; this->m_action->Handle(context, bitStream, branch); } } -void AreaOfEffectBehavior::Calculate(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) -{ +void AreaOfEffectBehavior::Calculate(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) { auto* self = EntityManager::Instance()->GetEntity(context->caster); - if (self == nullptr) - { + if (self == nullptr) { Game::logger->Log("TacArcBehavior", "Invalid self for (%llu)!", context->originator); return; @@ -59,10 +53,8 @@ void AreaOfEffectBehavior::Calculate(BehaviorContext* context, RakNet::BitStream auto* presetTarget = EntityManager::Instance()->GetEntity(branch.target); - if (presetTarget != nullptr) - { - if (this->m_radius * this->m_radius >= Vector3::DistanceSquared(reference, presetTarget->GetPosition())) - { + if (presetTarget != nullptr) { + if (this->m_radius * this->m_radius >= Vector3::DistanceSquared(reference, presetTarget->GetPosition())) { targets.push_back(presetTarget); } } @@ -75,78 +67,67 @@ void AreaOfEffectBehavior::Calculate(BehaviorContext* context, RakNet::BitStream } // Gets all of the valid targets, passing in if should target enemies and friends - for (auto validTarget : context->GetValidTargets(m_ignoreFaction , includeFaction, m_TargetSelf == 1, m_targetEnemy == 1, m_targetFriend == 1)) - { + for (auto validTarget : context->GetValidTargets(m_ignoreFaction, includeFaction, m_TargetSelf == 1, m_targetEnemy == 1, m_targetFriend == 1)) { auto* entity = EntityManager::Instance()->GetEntity(validTarget); - if (entity == nullptr) - { + if (entity == nullptr) { Game::logger->Log("TacArcBehavior", "Invalid target (%llu) for (%llu)!", validTarget, context->originator); continue; } - if (std::find(targets.begin(), targets.end(), entity) != targets.end()) - { + if (std::find(targets.begin(), targets.end(), entity) != targets.end()) { continue; } auto* destroyableComponent = entity->GetComponent(); - if (destroyableComponent == nullptr) - { + if (destroyableComponent == nullptr) { continue; } - if (destroyableComponent->HasFaction(m_ignoreFaction)) - { + if (destroyableComponent->HasFaction(m_ignoreFaction)) { continue; } const auto distance = Vector3::DistanceSquared(reference, entity->GetPosition()); - if (this->m_radius * this->m_radius >= distance && (this->m_maxTargets == 0 || targets.size() < this->m_maxTargets)) - { + if (this->m_radius * this->m_radius >= distance && (this->m_maxTargets == 0 || targets.size() < this->m_maxTargets)) { targets.push_back(entity); } } - std::sort(targets.begin(), targets.end(), [reference](Entity* a, Entity* b) - { + std::sort(targets.begin(), targets.end(), [reference](Entity* a, Entity* b) { const auto aDistance = Vector3::DistanceSquared(a->GetPosition(), reference); const auto bDistance = Vector3::DistanceSquared(b->GetPosition(), reference); return aDistance > bDistance; - }); + }); const uint32_t size = targets.size(); bitStream->Write(size); - if (size == 0) - { + if (size == 0) { return; } context->foundTarget = true; - for (auto* target : targets) - { + for (auto* target : targets) { bitStream->Write(target->GetObjectID()); PlayFx(u"cast", context->originator, target->GetObjectID()); } - for (auto* target : targets) - { + for (auto* target : targets) { branch.target = target->GetObjectID(); this->m_action->Calculate(context, bitStream, branch); } } -void AreaOfEffectBehavior::Load() -{ +void AreaOfEffectBehavior::Load() { this->m_action = GetAction("action"); this->m_radius = GetFloat("radius"); @@ -157,7 +138,7 @@ void AreaOfEffectBehavior::Load() this->m_includeFaction = GetInt("include_faction"); - this->m_TargetSelf = GetInt("target_self"); + this->m_TargetSelf = GetInt("target_self"); this->m_targetEnemy = GetInt("target_enemy"); diff --git a/dGame/dBehaviors/AreaOfEffectBehavior.h b/dGame/dBehaviors/AreaOfEffectBehavior.h index 9a8b7290..863ce8f7 100644 --- a/dGame/dBehaviors/AreaOfEffectBehavior.h +++ b/dGame/dBehaviors/AreaOfEffectBehavior.h @@ -14,21 +14,20 @@ public: int32_t m_includeFaction; - int32_t m_TargetSelf; + int32_t m_TargetSelf; int32_t m_targetEnemy; int32_t m_targetFriend; - + /* * Inherited */ - explicit AreaOfEffectBehavior(const uint32_t behaviorId) : Behavior(behaviorId) - { + explicit AreaOfEffectBehavior(const uint32_t behaviorId) : Behavior(behaviorId) { } void Handle(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) override; - + void Calculate(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) override; void Load() override; diff --git a/dGame/dBehaviors/AttackDelayBehavior.cpp b/dGame/dBehaviors/AttackDelayBehavior.cpp index c536f925..9d1eb872 100644 --- a/dGame/dBehaviors/AttackDelayBehavior.cpp +++ b/dGame/dBehaviors/AttackDelayBehavior.cpp @@ -4,48 +4,41 @@ #include "Game.h" #include "dLogger.h" -void AttackDelayBehavior::Handle(BehaviorContext* context, RakNet::BitStream* bitStream, const BehaviorBranchContext branch) -{ +void AttackDelayBehavior::Handle(BehaviorContext* context, RakNet::BitStream* bitStream, const BehaviorBranchContext branch) { uint32_t handle; bitStream->Read(handle); - - for (auto i = 0u; i < this->m_numIntervals; ++i) - { + + for (auto i = 0u; i < this->m_numIntervals; ++i) { context->RegisterSyncBehavior(handle, this, branch); } } -void AttackDelayBehavior::Calculate(BehaviorContext* context, RakNet::BitStream* bitStream, const BehaviorBranchContext branch) -{ +void AttackDelayBehavior::Calculate(BehaviorContext* context, RakNet::BitStream* bitStream, const BehaviorBranchContext branch) { const auto handle = context->GetUniqueSkillId(); bitStream->Write(handle); context->foundTarget = true; - for (auto i = 0u; i < this->m_numIntervals; ++i) - { + for (auto i = 0u; i < this->m_numIntervals; ++i) { const auto multiple = static_cast(i + 1); context->SyncCalculation(handle, this->m_delay * multiple, this, branch, m_ignoreInterrupts); } } -void AttackDelayBehavior::Sync(BehaviorContext* context, RakNet::BitStream* bitStream, const BehaviorBranchContext branch) -{ +void AttackDelayBehavior::Sync(BehaviorContext* context, RakNet::BitStream* bitStream, const BehaviorBranchContext branch) { this->m_action->Handle(context, bitStream, branch); } -void AttackDelayBehavior::SyncCalculation(BehaviorContext* context, RakNet::BitStream* bitStream, const BehaviorBranchContext branch) -{ +void AttackDelayBehavior::SyncCalculation(BehaviorContext* context, RakNet::BitStream* bitStream, const BehaviorBranchContext branch) { PlayFx(u"cast", context->originator); this->m_action->Calculate(context, bitStream, branch); } -void AttackDelayBehavior::Load() -{ +void AttackDelayBehavior::Load() { this->m_numIntervals = GetInt("num_intervals"); this->m_action = GetAction("action"); @@ -54,8 +47,7 @@ void AttackDelayBehavior::Load() this->m_ignoreInterrupts = GetBoolean("ignore_interrupts"); - if (this->m_numIntervals == 0) - { + if (this->m_numIntervals == 0) { this->m_numIntervals = 1; } } diff --git a/dGame/dBehaviors/AttackDelayBehavior.h b/dGame/dBehaviors/AttackDelayBehavior.h index e798bf87..4223aba4 100644 --- a/dGame/dBehaviors/AttackDelayBehavior.h +++ b/dGame/dBehaviors/AttackDelayBehavior.h @@ -15,9 +15,8 @@ public: /* * Inherited */ - - explicit AttackDelayBehavior(const uint32_t behaviorId) : Behavior(behaviorId) - { + + explicit AttackDelayBehavior(const uint32_t behaviorId) : Behavior(behaviorId) { } void Handle(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) override; @@ -27,6 +26,6 @@ public: void Sync(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) override; void SyncCalculation(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) override; - + void Load() override; }; diff --git a/dGame/dBehaviors/BasicAttackBehavior.cpp b/dGame/dBehaviors/BasicAttackBehavior.cpp index 8f0fd287..0c0b0d56 100644 --- a/dGame/dBehaviors/BasicAttackBehavior.cpp +++ b/dGame/dBehaviors/BasicAttackBehavior.cpp @@ -43,7 +43,7 @@ void BasicAttackBehavior::Handle(BehaviorContext* context, RakNet::BitStream* bi uint32_t damageDealt; bitStream->Read(damageDealt); - // A value that's too large may be a cheating attempt, so we set it to MIN too + // A value that's too large may be a cheating attempt, so we set it to MIN too if (damageDealt > this->m_maxDamage || damageDealt < this->m_minDamage) { damageDealt = this->m_minDamage; } @@ -53,7 +53,7 @@ void BasicAttackBehavior::Handle(BehaviorContext* context, RakNet::BitStream* bi bitStream->Read(died); if (entity != nullptr) { - auto* destroyableComponent = entity->GetComponent(); + auto* destroyableComponent = entity->GetComponent(); if (destroyableComponent != nullptr) { PlayFx(u"onhit", entity->GetObjectID()); destroyableComponent->Damage(damageDealt, context->originator, context->skillID); @@ -113,7 +113,7 @@ void BasicAttackBehavior::Calculate(BehaviorContext* context, RakNet::BitStream* auto* destroyableComponent = entity->GetComponent(); if (damage != 0 && destroyableComponent != nullptr) { PlayFx(u"onhit", entity->GetObjectID(), 1); - destroyableComponent->Damage(damage, context->originator, context->skillID, false); + destroyableComponent->Damage(damage, context->originator, context->skillID, false); context->ScheduleUpdate(branch.target); } } diff --git a/dGame/dBehaviors/BasicAttackBehavior.h b/dGame/dBehaviors/BasicAttackBehavior.h index fa4dc0e8..9e6874b9 100644 --- a/dGame/dBehaviors/BasicAttackBehavior.h +++ b/dGame/dBehaviors/BasicAttackBehavior.h @@ -9,14 +9,13 @@ public: uint32_t m_maxDamage; Behavior* m_onSuccess; - - explicit BasicAttackBehavior(const uint32_t behaviorId) : Behavior(behaviorId) - { + + explicit BasicAttackBehavior(const uint32_t behaviorId) : Behavior(behaviorId) { } void Handle(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) override; void Calculate(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) override; - + void Load() override; }; diff --git a/dGame/dBehaviors/Behavior.cpp b/dGame/dBehaviors/Behavior.cpp index a1b746cd..ed8f2f8c 100644 --- a/dGame/dBehaviors/Behavior.cpp +++ b/dGame/dBehaviors/Behavior.cpp @@ -60,7 +60,7 @@ #include "DamageReductionBehavior.h" #include "JetPackBehavior.h" -//CDClient includes + //CDClient includes #include "CDBehaviorParameterTable.h" #include "CDClientDatabase.h" #include "CDClientManager.h" @@ -73,34 +73,28 @@ std::unordered_map Behavior::Cache = {}; CDBehaviorParameterTable* Behavior::BehaviorParameterTable = nullptr; -Behavior* Behavior::GetBehavior(const uint32_t behaviorId) -{ - if (BehaviorParameterTable == nullptr) - { +Behavior* Behavior::GetBehavior(const uint32_t behaviorId) { + if (BehaviorParameterTable == nullptr) { BehaviorParameterTable = CDClientManager::Instance()->GetTable("BehaviorParameter"); } const auto pair = Cache.find(behaviorId); - if (pair == Cache.end()) - { + if (pair == Cache.end()) { return nullptr; } return static_cast(pair->second); } -Behavior* Behavior::CreateBehavior(const uint32_t behaviorId) -{ +Behavior* Behavior::CreateBehavior(const uint32_t behaviorId) { auto* cached = GetBehavior(behaviorId); - if (cached != nullptr) - { + if (cached != nullptr) { return cached; } - if (behaviorId == 0) - { + if (behaviorId == 0) { return new EmptyBehavior(0); } @@ -108,8 +102,7 @@ Behavior* Behavior::CreateBehavior(const uint32_t behaviorId) Behavior* behavior = nullptr; - switch (templateId) - { + switch (templateId) { case BehaviorTemplates::BEHAVIOR_EMPTY: break; case BehaviorTemplates::BEHAVIOR_BASIC_ATTACK: behavior = new BasicAttackBehavior(behaviorId); @@ -273,8 +266,7 @@ Behavior* Behavior::CreateBehavior(const uint32_t behaviorId) break; } - if (behavior == nullptr) - { + if (behavior == nullptr) { //Game::logger->Log("Behavior", "Failed to load unimplemented template id (%i)!", templateId); behavior = new EmptyBehavior(behaviorId); @@ -305,19 +297,16 @@ BehaviorTemplates Behavior::GetBehaviorTemplate(const uint32_t behaviorId) { } // For use with enemies, to display the correct damage animations on the players -void Behavior::PlayFx(std::u16string type, const LWOOBJID target, const LWOOBJID secondary) -{ +void Behavior::PlayFx(std::u16string type, const LWOOBJID target, const LWOOBJID secondary) { auto* targetEntity = EntityManager::Instance()->GetEntity(target); - if (targetEntity == nullptr) - { + if (targetEntity == nullptr) { return; } const auto effectId = this->m_effectId; - if (effectId == 0) - { + if (effectId == 0) { GameMessages::SendPlayFXEffect(targetEntity, -1, type, "", secondary, 1, 1, true); return; @@ -327,23 +316,17 @@ void Behavior::PlayFx(std::u16string type, const LWOOBJID target, const LWOOBJID const auto typeString = GeneralUtils::UTF16ToWTF8(type); - if (m_effectNames == nullptr) - { + if (m_effectNames == nullptr) { m_effectNames = new std::unordered_map(); - } - else - { + } else { const auto pair = m_effectNames->find(typeString); - if (type.empty()) - { + if (type.empty()) { type = GeneralUtils::ASCIIToUTF16(*m_effectType); } - if (pair != m_effectNames->end()) - { - if (renderComponent == nullptr) - { + if (pair != m_effectNames->end()) { + if (renderComponent == nullptr) { GameMessages::SendPlayFXEffect(targetEntity, effectId, type, pair->second, secondary, 1, 1, true); return; @@ -366,24 +349,22 @@ void Behavior::PlayFx(std::u16string type, const LWOOBJID target, const LWOOBJID if (!type.empty()) { typeQuery.bind(1, typeString.c_str()); - typeQuery.bind(2, (int) effectId); + typeQuery.bind(2, (int)effectId); result = typeQuery.execQuery(); } else { - idQuery.bind(1, (int) effectId); + idQuery.bind(1, (int)effectId); result = idQuery.execQuery(); } - if (result.eof() || result.fieldIsNull(0)) - { + if (result.eof() || result.fieldIsNull(0)) { return; } const auto name = std::string(result.getStringField(0)); - if (type.empty()) - { + if (type.empty()) { const auto typeResult = result.getStringField(1); type = GeneralUtils::ASCIIToUTF16(typeResult); @@ -395,8 +376,7 @@ void Behavior::PlayFx(std::u16string type, const LWOOBJID target, const LWOOBJID m_effectNames->insert_or_assign(typeString, name); - if (renderComponent == nullptr) - { + if (renderComponent == nullptr) { GameMessages::SendPlayFXEffect(targetEntity, effectId, type, name, secondary, 1, 1, true); return; @@ -405,8 +385,7 @@ void Behavior::PlayFx(std::u16string type, const LWOOBJID target, const LWOOBJID renderComponent->PlayEffect(effectId, type, name, secondary); } -Behavior::Behavior(const uint32_t behaviorId) -{ +Behavior::Behavior(const uint32_t behaviorId) { auto behaviorTemplateTable = CDClientManager::Instance()->GetTable("BehaviorTemplate"); CDBehaviorTemplate templateInDatabase{}; @@ -430,8 +409,7 @@ Behavior::Behavior(const uint32_t behaviorId) } // Make sure we do not proceed if we are trying to load an invalid behavior - if (templateInDatabase.behaviorID == 0) - { + if (templateInDatabase.behaviorID == 0) { Game::logger->Log("Behavior", "Failed to load behavior with id (%i)!", behaviorId); this->m_effectId = 0; @@ -449,40 +427,34 @@ Behavior::Behavior(const uint32_t behaviorId) } -float Behavior::GetFloat(const std::string& name, const float defaultValue) const -{ +float Behavior::GetFloat(const std::string& name, const float defaultValue) const { // Get the behavior parameter entry and return its value. if (!BehaviorParameterTable) BehaviorParameterTable = CDClientManager::Instance()->GetTable("BehaviorParameter"); return BehaviorParameterTable->GetEntry(this->m_behaviorId, name, defaultValue).value; } -bool Behavior::GetBoolean(const std::string& name, const bool defaultValue) const -{ +bool Behavior::GetBoolean(const std::string& name, const bool defaultValue) const { return GetFloat(name, defaultValue) > 0; } -int32_t Behavior::GetInt(const std::string& name, const int defaultValue) const -{ +int32_t Behavior::GetInt(const std::string& name, const int defaultValue) const { return static_cast(GetFloat(name, defaultValue)); } -Behavior* Behavior::GetAction(const std::string& name) const -{ +Behavior* Behavior::GetAction(const std::string& name) const { const auto id = GetInt(name); return CreateBehavior(id); } -Behavior* Behavior::GetAction(float value) const -{ +Behavior* Behavior::GetAction(float value) const { return CreateBehavior(static_cast(value)); } -std::map Behavior::GetParameterNames() const -{ +std::map Behavior::GetParameterNames() const { std::map templatesInDatabase; // Find behavior template by its behavior id. if (!BehaviorParameterTable) BehaviorParameterTable = CDClientManager::Instance()->GetTable("BehaviorParameter"); @@ -493,40 +465,31 @@ std::map Behavior::GetParameterNames() const return templatesInDatabase; } -void Behavior::Load() -{ +void Behavior::Load() { } -void Behavior::Handle(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) -{ +void Behavior::Handle(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) { } -void Behavior::Sync(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) -{ +void Behavior::Sync(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) { } -void Behavior::UnCast(BehaviorContext* context, BehaviorBranchContext branch) -{ +void Behavior::UnCast(BehaviorContext* context, BehaviorBranchContext branch) { } -void Behavior::Timer(BehaviorContext* context, BehaviorBranchContext branch, LWOOBJID second) -{ +void Behavior::Timer(BehaviorContext* context, BehaviorBranchContext branch, LWOOBJID second) { } -void Behavior::End(BehaviorContext* context, BehaviorBranchContext branch, LWOOBJID second) -{ +void Behavior::End(BehaviorContext* context, BehaviorBranchContext branch, LWOOBJID second) { } -void Behavior::Calculate(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) -{ +void Behavior::Calculate(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) { } -void Behavior::SyncCalculation(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) -{ +void Behavior::SyncCalculation(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) { } -Behavior::~Behavior() -{ +Behavior::~Behavior() { delete m_effectNames; delete m_effectType; delete m_effectHandle; diff --git a/dGame/dBehaviors/Behavior.h b/dGame/dBehaviors/Behavior.h index 34ba469b..bf656e1b 100644 --- a/dGame/dBehaviors/Behavior.h +++ b/dGame/dBehaviors/Behavior.h @@ -31,24 +31,24 @@ public: /* * Utilities */ - + void PlayFx(std::u16string type, LWOOBJID target, LWOOBJID secondary = LWOOBJID_EMPTY); /* * Members */ - + uint32_t m_behaviorId; BehaviorTemplates m_templateId; uint32_t m_effectId; std::string* m_effectHandle = nullptr; std::unordered_map* m_effectNames = nullptr; std::string* m_effectType = nullptr; - + /* * Behavior parameters */ - + float GetFloat(const std::string& name, const float defaultValue = 0) const; bool GetBoolean(const std::string& name, const bool defaultValue = false) const; @@ -60,7 +60,7 @@ public: Behavior* GetAction(float value) const; std::map GetParameterNames() const; - + /* * Virtual */ @@ -69,15 +69,15 @@ public: // Player side virtual void Handle(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch); - + virtual void Sync(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch); virtual void UnCast(BehaviorContext* context, BehaviorBranchContext branch); virtual void Timer(BehaviorContext* context, BehaviorBranchContext branch, LWOOBJID second); - + virtual void End(BehaviorContext* context, BehaviorBranchContext branch, LWOOBJID second); - + // Npc side virtual void Calculate(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch); @@ -86,7 +86,7 @@ public: /* * Creations/destruction */ - + explicit Behavior(uint32_t behaviorId); virtual ~Behavior(); }; diff --git a/dGame/dBehaviors/BehaviorBranchContext.cpp b/dGame/dBehaviors/BehaviorBranchContext.cpp index 91791d89..7793eb54 100644 --- a/dGame/dBehaviors/BehaviorBranchContext.cpp +++ b/dGame/dBehaviors/BehaviorBranchContext.cpp @@ -1,13 +1,11 @@ #include "BehaviorBranchContext.h" -BehaviorBranchContext::BehaviorBranchContext() -{ +BehaviorBranchContext::BehaviorBranchContext() { this->isProjectile = false; } -BehaviorBranchContext::BehaviorBranchContext(const LWOOBJID target, const float duration, const NiPoint3& referencePosition) -{ +BehaviorBranchContext::BehaviorBranchContext(const LWOOBJID target, const float duration, const NiPoint3& referencePosition) { this->target = target; this->duration = duration; this->referencePosition = referencePosition; diff --git a/dGame/dBehaviors/BehaviorBranchContext.h b/dGame/dBehaviors/BehaviorBranchContext.h index bd4e6722..dfd76fad 100644 --- a/dGame/dBehaviors/BehaviorBranchContext.h +++ b/dGame/dBehaviors/BehaviorBranchContext.h @@ -6,9 +6,9 @@ struct BehaviorBranchContext { LWOOBJID target = LWOOBJID_EMPTY; - + float duration = 0; - + NiPoint3 referencePosition = {}; bool isProjectile = false; @@ -16,6 +16,6 @@ struct BehaviorBranchContext uint32_t start = 0; BehaviorBranchContext(); - + BehaviorBranchContext(LWOOBJID target, float duration = 0, const NiPoint3& referencePosition = NiPoint3(0, 0, 0)); }; diff --git a/dGame/dBehaviors/BehaviorContext.cpp b/dGame/dBehaviors/BehaviorContext.cpp index 87e63a59..54325bac 100644 --- a/dGame/dBehaviors/BehaviorContext.cpp +++ b/dGame/dBehaviors/BehaviorContext.cpp @@ -15,24 +15,19 @@ #include "PhantomPhysicsComponent.h" #include "RebuildComponent.h" -BehaviorSyncEntry::BehaviorSyncEntry() -{ +BehaviorSyncEntry::BehaviorSyncEntry() { } -BehaviorTimerEntry::BehaviorTimerEntry() -{ +BehaviorTimerEntry::BehaviorTimerEntry() { } -BehaviorEndEntry::BehaviorEndEntry() -{ +BehaviorEndEntry::BehaviorEndEntry() { } -uint32_t BehaviorContext::GetUniqueSkillId() const -{ +uint32_t BehaviorContext::GetUniqueSkillId() const { auto* entity = EntityManager::Instance()->GetEntity(this->originator); - if (entity == nullptr) - { + if (entity == nullptr) { Game::logger->Log("BehaviorContext", "Invalid entity for (%llu)!", this->originator); return 0; @@ -40,8 +35,7 @@ uint32_t BehaviorContext::GetUniqueSkillId() const auto* component = entity->GetComponent(); - if (component == nullptr) - { + if (component == nullptr) { Game::logger->Log("BehaviorContext", "No skill component attached to (%llu)!", this->originator);; return 0; @@ -51,8 +45,7 @@ uint32_t BehaviorContext::GetUniqueSkillId() const } -void BehaviorContext::RegisterSyncBehavior(const uint32_t syncId, Behavior* behavior, const BehaviorBranchContext& branchContext) -{ +void BehaviorContext::RegisterSyncBehavior(const uint32_t syncId, Behavior* behavior, const BehaviorBranchContext& branchContext) { auto entry = BehaviorSyncEntry(); entry.handle = syncId; @@ -62,8 +55,7 @@ void BehaviorContext::RegisterSyncBehavior(const uint32_t syncId, Behavior* beha this->syncEntries.push_back(entry); } -void BehaviorContext::RegisterTimerBehavior(Behavior* behavior, const BehaviorBranchContext& branchContext, const LWOOBJID second) -{ +void BehaviorContext::RegisterTimerBehavior(Behavior* behavior, const BehaviorBranchContext& branchContext, const LWOOBJID second) { BehaviorTimerEntry entry; entry.time = branchContext.duration; @@ -74,8 +66,7 @@ void BehaviorContext::RegisterTimerBehavior(Behavior* behavior, const BehaviorBr this->timerEntries.push_back(entry); } -void BehaviorContext::RegisterEndBehavior(Behavior* behavior, const BehaviorBranchContext& branchContext, const LWOOBJID second) -{ +void BehaviorContext::RegisterEndBehavior(Behavior* behavior, const BehaviorBranchContext& branchContext, const LWOOBJID second) { BehaviorEndEntry entry; entry.behavior = behavior; @@ -86,20 +77,16 @@ void BehaviorContext::RegisterEndBehavior(Behavior* behavior, const BehaviorBran this->endEntries.push_back(entry); } -void BehaviorContext::ScheduleUpdate(const LWOOBJID id) -{ - if (std::find(this->scheduledUpdates.begin(), this->scheduledUpdates.end(), id) != this->scheduledUpdates.end()) - { +void BehaviorContext::ScheduleUpdate(const LWOOBJID id) { + if (std::find(this->scheduledUpdates.begin(), this->scheduledUpdates.end(), id) != this->scheduledUpdates.end()) { return; } this->scheduledUpdates.push_back(id); } -void BehaviorContext::ExecuteUpdates() -{ - for (const auto& id : this->scheduledUpdates) - { +void BehaviorContext::ExecuteUpdates() { + for (const auto& id : this->scheduledUpdates) { auto* entity = EntityManager::Instance()->GetEntity(id); if (entity == nullptr) continue; @@ -110,20 +97,17 @@ void BehaviorContext::ExecuteUpdates() this->scheduledUpdates.clear(); } -void BehaviorContext::SyncBehavior(const uint32_t syncId, RakNet::BitStream* bitStream) -{ +void BehaviorContext::SyncBehavior(const uint32_t syncId, RakNet::BitStream* bitStream) { BehaviorSyncEntry entry; auto found = false; /* * There may be more than one of each handle */ - for (auto i = 0u; i < this->syncEntries.size(); ++i) - { + for (auto i = 0u; i < this->syncEntries.size(); ++i) { const auto syncEntry = this->syncEntries.at(i); - if (syncEntry.handle == syncId) - { + if (syncEntry.handle == syncId) { found = true; entry = syncEntry; @@ -133,8 +117,7 @@ void BehaviorContext::SyncBehavior(const uint32_t syncId, RakNet::BitStream* bit } } - if (!found) - { + if (!found) { Game::logger->Log("BehaviorContext", "Failed to find behavior sync entry with sync id (%i)!", syncId); return; @@ -143,8 +126,7 @@ void BehaviorContext::SyncBehavior(const uint32_t syncId, RakNet::BitStream* bit auto* behavior = entry.behavior; const auto branch = entry.branchContext; - if (behavior == nullptr) - { + if (behavior == nullptr) { Game::logger->Log("BehaviorContext", "Invalid behavior for sync id (%i)!", syncId); return; @@ -154,21 +136,17 @@ void BehaviorContext::SyncBehavior(const uint32_t syncId, RakNet::BitStream* bit } -void BehaviorContext::Update(const float deltaTime) -{ - for (auto i = 0u; i < this->timerEntries.size(); ++i) - { +void BehaviorContext::Update(const float deltaTime) { + for (auto i = 0u; i < this->timerEntries.size(); ++i) { auto entry = this->timerEntries.at(i); - if (entry.time > 0) - { + if (entry.time > 0) { entry.time -= deltaTime; this->timerEntries[i] = entry; } - if (entry.time > 0) - { + if (entry.time > 0) { continue; } @@ -177,10 +155,8 @@ void BehaviorContext::Update(const float deltaTime) std::vector valid; - for (const auto& entry : this->timerEntries) - { - if (entry.time <= 0) - { + for (const auto& entry : this->timerEntries) { + if (entry.time <= 0) { continue; } @@ -191,8 +167,7 @@ void BehaviorContext::Update(const float deltaTime) } -void BehaviorContext::SyncCalculation(const uint32_t syncId, const float time, Behavior* behavior, const BehaviorBranchContext& branch, const bool ignoreInterrupts) -{ +void BehaviorContext::SyncCalculation(const uint32_t syncId, const float time, Behavior* behavior, const BehaviorBranchContext& branch, const bool ignoreInterrupts) { BehaviorSyncEntry entry; entry.behavior = behavior; @@ -204,14 +179,11 @@ void BehaviorContext::SyncCalculation(const uint32_t syncId, const float time, B this->syncEntries.push_back(entry); } -void BehaviorContext::InvokeEnd(const uint32_t id) -{ +void BehaviorContext::InvokeEnd(const uint32_t id) { std::vector entries; - for (const auto& entry : this->endEntries) - { - if (entry.start == id) - { + for (const auto& entry : this->endEntries) { + if (entry.start == id) { entry.behavior->End(this, entry.branchContext, entry.second); continue; @@ -223,23 +195,19 @@ void BehaviorContext::InvokeEnd(const uint32_t id) this->endEntries = entries; } -bool BehaviorContext::CalculateUpdate(const float deltaTime) -{ +bool BehaviorContext::CalculateUpdate(const float deltaTime) { auto any = false; - for (auto i = 0u; i < this->syncEntries.size(); ++i) - { + for (auto i = 0u; i < this->syncEntries.size(); ++i) { auto entry = this->syncEntries.at(i); - if (entry.time > 0) - { + if (entry.time > 0) { entry.time -= deltaTime; this->syncEntries[i] = entry; } - if (entry.time > 0) - { + if (entry.time > 0) { any = true; continue; @@ -257,9 +225,8 @@ bool BehaviorContext::CalculateUpdate(const float deltaTime) // Calculate sync entry.behavior->SyncCalculation(this, bitStream, entry.branchContext); - if (!clientInitalized) - { - echo.sBitStream.assign((char*) bitStream->GetData(), bitStream->GetNumberOfBytesUsed()); + if (!clientInitalized) { + echo.sBitStream.assign((char*)bitStream->GetData(), bitStream->GetNumberOfBytesUsed()); // Write message RakNet::BitStream message; @@ -278,10 +245,8 @@ bool BehaviorContext::CalculateUpdate(const float deltaTime) std::vector valid; - for (const auto& entry : this->syncEntries) - { - if (entry.time <= 0) - { + for (const auto& entry : this->syncEntries) { + if (entry.time <= 0) { continue; } @@ -293,12 +258,10 @@ bool BehaviorContext::CalculateUpdate(const float deltaTime) return any; } -void BehaviorContext::Interrupt() -{ - std::vector keptSync {}; +void BehaviorContext::Interrupt() { + std::vector keptSync{}; - for (const auto& entry : this->syncEntries) - { + for (const auto& entry : this->syncEntries) { if (!entry.ignoreInterrupts) continue; keptSync.push_back(entry); @@ -307,15 +270,12 @@ void BehaviorContext::Interrupt() this->syncEntries = keptSync; } -void BehaviorContext::Reset() -{ - for (const auto& entry : this->timerEntries) - { +void BehaviorContext::Reset() { + for (const auto& entry : this->timerEntries) { entry.behavior->Timer(this, entry.branchContext, entry.second); } - for (const auto& entry : this->endEntries) - { + for (const auto& entry : this->endEntries) { entry.behavior->End(this, entry.branchContext, entry.second); } @@ -325,27 +285,22 @@ void BehaviorContext::Reset() this->scheduledUpdates.clear(); } -std::vector BehaviorContext::GetValidTargets(int32_t ignoreFaction, int32_t includeFaction, bool targetSelf, bool targetEnemy, bool targetFriend) const -{ +std::vector BehaviorContext::GetValidTargets(int32_t ignoreFaction, int32_t includeFaction, bool targetSelf, bool targetEnemy, bool targetFriend) const { auto* entity = EntityManager::Instance()->GetEntity(this->caster); std::vector targets; - if (entity == nullptr) - { + if (entity == nullptr) { Game::logger->Log("BehaviorContext", "Invalid entity for (%llu)!", this->originator); return targets; } - if (!ignoreFaction && !includeFaction) - { - for (auto entry : entity->GetTargetsInPhantom()) - { + if (!ignoreFaction && !includeFaction) { + for (auto entry : entity->GetTargetsInPhantom()) { auto* instance = EntityManager::Instance()->GetEntity(entry); - if (instance == nullptr) - { + if (instance == nullptr) { continue; } @@ -353,21 +308,17 @@ std::vector BehaviorContext::GetValidTargets(int32_t ignoreFaction, in } } - if (ignoreFaction || includeFaction || (!entity->HasComponent(COMPONENT_TYPE_PHANTOM_PHYSICS) && targets.empty())) - { - DestroyableComponent* destroyableComponent; - if (!entity->TryGetComponent(COMPONENT_TYPE_DESTROYABLE, destroyableComponent)) - { + if (ignoreFaction || includeFaction || (!entity->HasComponent(COMPONENT_TYPE_PHANTOM_PHYSICS) && targets.empty())) { + DestroyableComponent* destroyableComponent; + if (!entity->TryGetComponent(COMPONENT_TYPE_DESTROYABLE, destroyableComponent)) { return targets; } auto entities = EntityManager::Instance()->GetEntitiesByComponent(COMPONENT_TYPE_CONTROLLABLE_PHYSICS); - for (auto* candidate : entities) - { + for (auto* candidate : entities) { const auto id = candidate->GetObjectID(); - if ((id != entity->GetObjectID() || targetSelf) && destroyableComponent->CheckValidity(id, ignoreFaction || includeFaction, targetEnemy, targetFriend)) - { + if ((id != entity->GetObjectID() || targetSelf) && destroyableComponent->CheckValidity(id, ignoreFaction || includeFaction, targetEnemy, targetFriend)) { targets.push_back(id); } } @@ -377,23 +328,18 @@ std::vector BehaviorContext::GetValidTargets(int32_t ignoreFaction, in } -BehaviorContext::BehaviorContext(const LWOOBJID originator, const bool calculation) -{ +BehaviorContext::BehaviorContext(const LWOOBJID originator, const bool calculation) { this->originator = originator; this->syncEntries = {}; this->timerEntries = {}; - if (calculation) - { + if (calculation) { this->skillUId = GetUniqueSkillId(); - } - else - { + } else { this->skillUId = 0; } } -BehaviorContext::~BehaviorContext() -{ +BehaviorContext::~BehaviorContext() { Reset(); } diff --git a/dGame/dBehaviors/BehaviorContext.h b/dGame/dBehaviors/BehaviorContext.h index f27889f1..af8e66b4 100644 --- a/dGame/dBehaviors/BehaviorContext.h +++ b/dGame/dBehaviors/BehaviorContext.h @@ -16,7 +16,7 @@ struct BehaviorSyncEntry float time = 0; bool ignoreInterrupts = false; - + Behavior* behavior = nullptr; BehaviorBranchContext branchContext; @@ -46,7 +46,7 @@ struct BehaviorEndEntry BehaviorBranchContext branchContext; LWOOBJID second = LWOOBJID_EMPTY; - + BehaviorEndEntry(); }; @@ -65,11 +65,11 @@ struct BehaviorContext bool failed = false; bool clientInitalized = false; - + std::vector syncEntries; - + std::vector timerEntries; - + std::vector endEntries; std::vector scheduledUpdates; @@ -89,15 +89,15 @@ struct BehaviorContext void ScheduleUpdate(LWOOBJID id); void ExecuteUpdates(); - + void SyncBehavior(uint32_t syncId, RakNet::BitStream* bitStream); void Update(float deltaTime); - + void SyncCalculation(uint32_t syncId, float time, Behavior* behavior, const BehaviorBranchContext& branch, bool ignoreInterrupts = false); void InvokeEnd(uint32_t id); - + bool CalculateUpdate(float deltaTime); void Interrupt(); @@ -105,7 +105,7 @@ struct BehaviorContext void Reset(); std::vector GetValidTargets(int32_t ignoreFaction = 0, int32_t includeFaction = 0, const bool targetSelf = false, const bool targetEnemy = true, const bool targetFriend = false) const; - + explicit BehaviorContext(LWOOBJID originator, bool calculation = false); ~BehaviorContext(); diff --git a/dGame/dBehaviors/BehaviorTemplates.h b/dGame/dBehaviors/BehaviorTemplates.h index 04c15fc0..af7ab376 100644 --- a/dGame/dBehaviors/BehaviorTemplates.h +++ b/dGame/dBehaviors/BehaviorTemplates.h @@ -67,4 +67,4 @@ enum class BehaviorTemplates : unsigned int { BEHAVIOR_TAKE_PICTURE, BEHAVIOR_MOUNT, BEHAVIOR_SKILL_SET -}; \ No newline at end of file +}; diff --git a/dGame/dBehaviors/BlockBehavior.cpp b/dGame/dBehaviors/BlockBehavior.cpp index 13012f98..25650b2a 100644 --- a/dGame/dBehaviors/BlockBehavior.cpp +++ b/dGame/dBehaviors/BlockBehavior.cpp @@ -7,14 +7,12 @@ #include "dLogger.h" #include "DestroyableComponent.h" -void BlockBehavior::Handle(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) -{ +void BlockBehavior::Handle(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) { const auto target = context->originator; auto* entity = EntityManager::Instance()->GetEntity(target); - if (entity == nullptr) - { + if (entity == nullptr) { Game::logger->Log("DamageAbsorptionBehavior", "Failed to find target (%llu)!", branch.target); return; @@ -22,36 +20,29 @@ void BlockBehavior::Handle(BehaviorContext* context, RakNet::BitStream* bitStrea auto* destroyableComponent = entity->GetComponent(); - if (destroyableComponent == nullptr) - { + if (destroyableComponent == nullptr) { return; } destroyableComponent->SetAttacksToBlock(this->m_numAttacksCanBlock); - if (branch.start > 0) - { + if (branch.start > 0) { context->RegisterEndBehavior(this, branch); - } - else if (branch.duration > 0) - { + } else if (branch.duration > 0) { context->RegisterTimerBehavior(this, branch); } } -void BlockBehavior::Calculate(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) -{ +void BlockBehavior::Calculate(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) { Handle(context, bitStream, branch); } -void BlockBehavior::UnCast(BehaviorContext* context, BehaviorBranchContext branch) -{ +void BlockBehavior::UnCast(BehaviorContext* context, BehaviorBranchContext branch) { const auto target = context->originator; auto* entity = EntityManager::Instance()->GetEntity(target); - if (entity == nullptr) - { + if (entity == nullptr) { Game::logger->Log("DamageAbsorptionBehavior", "Failed to find target (%llu)!", branch.target); return; @@ -61,25 +52,21 @@ void BlockBehavior::UnCast(BehaviorContext* context, BehaviorBranchContext branc destroyableComponent->SetAttacksToBlock(this->m_numAttacksCanBlock); - if (destroyableComponent == nullptr) - { + if (destroyableComponent == nullptr) { return; } destroyableComponent->SetAttacksToBlock(0); } -void BlockBehavior::Timer(BehaviorContext* context, BehaviorBranchContext branch, LWOOBJID second) -{ +void BlockBehavior::Timer(BehaviorContext* context, BehaviorBranchContext branch, LWOOBJID second) { UnCast(context, branch); } -void BlockBehavior::End(BehaviorContext* context, BehaviorBranchContext branch, LWOOBJID second) -{ +void BlockBehavior::End(BehaviorContext* context, BehaviorBranchContext branch, LWOOBJID second) { UnCast(context, branch); } -void BlockBehavior::Load() -{ +void BlockBehavior::Load() { this->m_numAttacksCanBlock = GetInt("num_attacks_can_block"); } diff --git a/dGame/dBehaviors/BlockBehavior.h b/dGame/dBehaviors/BlockBehavior.h index 5de3d309..139fa0af 100644 --- a/dGame/dBehaviors/BlockBehavior.h +++ b/dGame/dBehaviors/BlockBehavior.h @@ -5,13 +5,12 @@ class BlockBehavior final : public Behavior { public: int32_t m_numAttacksCanBlock; - + /* * Inherited */ - explicit BlockBehavior(const uint32_t behaviorId) : Behavior(behaviorId) - { + explicit BlockBehavior(const uint32_t behaviorId) : Behavior(behaviorId) { } void Handle(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) override; @@ -19,10 +18,10 @@ public: void Calculate(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) override; void UnCast(BehaviorContext* context, BehaviorBranchContext branch) override; - + void Timer(BehaviorContext* context, BehaviorBranchContext branch, LWOOBJID second) override; void End(BehaviorContext* context, BehaviorBranchContext branch, LWOOBJID second) override; - + void Load() override; }; diff --git a/dGame/dBehaviors/BuffBehavior.cpp b/dGame/dBehaviors/BuffBehavior.cpp index 09b70e03..8bd14529 100644 --- a/dGame/dBehaviors/BuffBehavior.cpp +++ b/dGame/dBehaviors/BuffBehavior.cpp @@ -7,14 +7,12 @@ #include "dLogger.h" #include "DestroyableComponent.h" -void BuffBehavior::Handle(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) -{ +void BuffBehavior::Handle(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) { const auto target = branch.target != LWOOBJID_EMPTY ? branch.target : context->originator; auto* entity = EntityManager::Instance()->GetEntity(target); - if (entity == nullptr) - { + if (entity == nullptr) { Game::logger->Log("BuffBehavior", "Invalid target (%llu)!", target); return; @@ -22,8 +20,7 @@ void BuffBehavior::Handle(BehaviorContext* context, RakNet::BitStream* bitStream auto* component = entity->GetComponent(); - if (component == nullptr) - { + if (component == nullptr) { Game::logger->Log("BuffBehavior", "Invalid target, no destroyable component (%llu)!", target); return; @@ -35,27 +32,21 @@ void BuffBehavior::Handle(BehaviorContext* context, RakNet::BitStream* bitStream EntityManager::Instance()->SerializeEntity(entity); - if (!context->unmanaged) - { - if (branch.duration > 0) - { + if (!context->unmanaged) { + if (branch.duration > 0) { context->RegisterTimerBehavior(this, branch); - } - else if (branch.start > 0) - { + } else if (branch.start > 0) { context->RegisterEndBehavior(this, branch); } } } -void BuffBehavior::UnCast(BehaviorContext* context, BehaviorBranchContext branch) -{ +void BuffBehavior::UnCast(BehaviorContext* context, BehaviorBranchContext branch) { const auto target = branch.target != LWOOBJID_EMPTY ? branch.target : context->originator; auto* entity = EntityManager::Instance()->GetEntity(target); - if (entity == nullptr) - { + if (entity == nullptr) { Game::logger->Log("BuffBehavior", "Invalid target (%llu)!", target); return; @@ -63,8 +54,7 @@ void BuffBehavior::UnCast(BehaviorContext* context, BehaviorBranchContext branch auto* component = entity->GetComponent(); - if (component == nullptr) - { + if (component == nullptr) { Game::logger->Log("BuffBehavior", "Invalid target, no destroyable component (%llu)!", target); return; @@ -77,18 +67,15 @@ void BuffBehavior::UnCast(BehaviorContext* context, BehaviorBranchContext branch EntityManager::Instance()->SerializeEntity(entity); } -void BuffBehavior::Timer(BehaviorContext* context, const BehaviorBranchContext branch, LWOOBJID second) -{ +void BuffBehavior::Timer(BehaviorContext* context, const BehaviorBranchContext branch, LWOOBJID second) { UnCast(context, branch); } -void BuffBehavior::End(BehaviorContext* context, const BehaviorBranchContext branch, LWOOBJID second) -{ +void BuffBehavior::End(BehaviorContext* context, const BehaviorBranchContext branch, LWOOBJID second) { UnCast(context, branch); } -void BuffBehavior::Load() -{ +void BuffBehavior::Load() { this->m_health = GetInt("life"); this->m_armor = GetInt("armor"); diff --git a/dGame/dBehaviors/BuffBehavior.h b/dGame/dBehaviors/BuffBehavior.h index cfb26aef..ffc853fa 100644 --- a/dGame/dBehaviors/BuffBehavior.h +++ b/dGame/dBehaviors/BuffBehavior.h @@ -9,12 +9,11 @@ public: uint32_t m_armor; uint32_t m_imagination; - + /* * Inherited */ - explicit BuffBehavior(const uint32_t behaviorId) : Behavior(behaviorId) - { + explicit BuffBehavior(const uint32_t behaviorId) : Behavior(behaviorId) { } void Handle(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) override; @@ -24,6 +23,6 @@ public: void Timer(BehaviorContext* context, BehaviorBranchContext branch, LWOOBJID second) override; void End(BehaviorContext* context, BehaviorBranchContext branch, LWOOBJID second) override; - + void Load() override; }; diff --git a/dGame/dBehaviors/CarBoostBehavior.cpp b/dGame/dBehaviors/CarBoostBehavior.cpp index adfae01b..1ab0af95 100644 --- a/dGame/dBehaviors/CarBoostBehavior.cpp +++ b/dGame/dBehaviors/CarBoostBehavior.cpp @@ -8,44 +8,41 @@ #include "dLogger.h" #include "PossessableComponent.h" -void CarBoostBehavior::Handle(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) -{ - GameMessages::SendVehicleAddPassiveBoostAction(branch.target, UNASSIGNED_SYSTEM_ADDRESS); +void CarBoostBehavior::Handle(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) { + GameMessages::SendVehicleAddPassiveBoostAction(branch.target, UNASSIGNED_SYSTEM_ADDRESS); - auto* entity = EntityManager::Instance()->GetEntity(context->originator); + auto* entity = EntityManager::Instance()->GetEntity(context->originator); - if (entity == nullptr) - { - return; - } + if (entity == nullptr) { + return; + } - Game::logger->Log("Car boost", "Activating car boost!"); + Game::logger->Log("Car boost", "Activating car boost!"); - auto* possessableComponent = entity->GetComponent(); - if (possessableComponent != nullptr) { + auto* possessableComponent = entity->GetComponent(); + if (possessableComponent != nullptr) { - auto* possessor = EntityManager::Instance()->GetEntity(possessableComponent->GetPossessor()); - if (possessor != nullptr) { + auto* possessor = EntityManager::Instance()->GetEntity(possessableComponent->GetPossessor()); + if (possessor != nullptr) { - auto* characterComponent = possessor->GetComponent(); - if (characterComponent != nullptr) { - Game::logger->Log("Car boost", "Tracking car boost!"); - characterComponent->UpdatePlayerStatistic(RacingCarBoostsActivated); - } - } - } + auto* characterComponent = possessor->GetComponent(); + if (characterComponent != nullptr) { + Game::logger->Log("Car boost", "Tracking car boost!"); + characterComponent->UpdatePlayerStatistic(RacingCarBoostsActivated); + } + } + } - m_Action->Handle(context, bitStream, branch); + m_Action->Handle(context, bitStream, branch); - entity->AddCallbackTimer(m_Time, [entity] () { - GameMessages::SendVehicleRemovePassiveBoostAction(entity->GetObjectID(), UNASSIGNED_SYSTEM_ADDRESS); - }); + entity->AddCallbackTimer(m_Time, [entity]() { + GameMessages::SendVehicleRemovePassiveBoostAction(entity->GetObjectID(), UNASSIGNED_SYSTEM_ADDRESS); + }); } -void CarBoostBehavior::Load() -{ - m_Action = GetAction("action"); +void CarBoostBehavior::Load() { + m_Action = GetAction("action"); - m_Time = GetFloat("time"); + m_Time = GetFloat("time"); } diff --git a/dGame/dBehaviors/CarBoostBehavior.h b/dGame/dBehaviors/CarBoostBehavior.h index 32eb00c8..3f4265b9 100644 --- a/dGame/dBehaviors/CarBoostBehavior.h +++ b/dGame/dBehaviors/CarBoostBehavior.h @@ -14,10 +14,9 @@ public: * Inherited */ - explicit CarBoostBehavior(const uint32_t behaviorId) : Behavior(behaviorId) - { + explicit CarBoostBehavior(const uint32_t behaviorId) : Behavior(behaviorId) { } - + void Handle(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) override; void Load() override; diff --git a/dGame/dBehaviors/ChainBehavior.cpp b/dGame/dBehaviors/ChainBehavior.cpp index 0d49de82..df8b223f 100644 --- a/dGame/dBehaviors/ChainBehavior.cpp +++ b/dGame/dBehaviors/ChainBehavior.cpp @@ -3,35 +3,29 @@ #include "Game.h" #include "dLogger.h" -void ChainBehavior::Handle(BehaviorContext* context, RakNet::BitStream* bitStream, const BehaviorBranchContext branch) -{ +void ChainBehavior::Handle(BehaviorContext* context, RakNet::BitStream* bitStream, const BehaviorBranchContext branch) { uint32_t chain_index; bitStream->Read(chain_index); chain_index--; - if (chain_index < this->m_behaviors.size()) - { + if (chain_index < this->m_behaviors.size()) { this->m_behaviors.at(chain_index)->Handle(context, bitStream, branch); } } -void ChainBehavior::Calculate(BehaviorContext* context, RakNet::BitStream* bitStream, const BehaviorBranchContext branch) -{ +void ChainBehavior::Calculate(BehaviorContext* context, RakNet::BitStream* bitStream, const BehaviorBranchContext branch) { bitStream->Write(1); this->m_behaviors.at(0)->Calculate(context, bitStream, branch); } -void ChainBehavior::Load() -{ +void ChainBehavior::Load() { const auto parameters = GetParameterNames(); - for (const auto& parameter : parameters) - { - if (parameter.first.rfind("behavior", 0) == 0) - { + for (const auto& parameter : parameters) { + if (parameter.first.rfind("behavior", 0) == 0) { auto* action = GetAction(parameter.second); this->m_behaviors.push_back(action); diff --git a/dGame/dBehaviors/ChainBehavior.h b/dGame/dBehaviors/ChainBehavior.h index 733707dc..626ecbe3 100644 --- a/dGame/dBehaviors/ChainBehavior.h +++ b/dGame/dBehaviors/ChainBehavior.h @@ -13,10 +13,9 @@ public: * Inherited */ - explicit ChainBehavior(const uint32_t behaviorId) : Behavior(behaviorId) - { + explicit ChainBehavior(const uint32_t behaviorId) : Behavior(behaviorId) { } - + void Handle(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) override; void Calculate(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) override; diff --git a/dGame/dBehaviors/ChangeOrientationBehavior.cpp b/dGame/dBehaviors/ChangeOrientationBehavior.cpp index 60dcf2ac..a60be62f 100644 --- a/dGame/dBehaviors/ChangeOrientationBehavior.cpp +++ b/dGame/dBehaviors/ChangeOrientationBehavior.cpp @@ -4,47 +4,41 @@ #include "EntityManager.h" #include "BaseCombatAIComponent.h" -void ChangeOrientationBehavior::Handle(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) -{ +void ChangeOrientationBehavior::Handle(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) { } -void ChangeOrientationBehavior::Calculate(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) -{ - if (!m_ToTarget) return; // TODO: Add the other arguments to this behavior +void ChangeOrientationBehavior::Calculate(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) { + if (!m_ToTarget) return; // TODO: Add the other arguments to this behavior - auto* self = EntityManager::Instance()->GetEntity(context->originator); - auto* other = EntityManager::Instance()->GetEntity(branch.target); + auto* self = EntityManager::Instance()->GetEntity(context->originator); + auto* other = EntityManager::Instance()->GetEntity(branch.target); - if (self == nullptr || other == nullptr) return; + if (self == nullptr || other == nullptr) return; - const auto source = self->GetPosition(); - const auto destination = self->GetPosition(); + const auto source = self->GetPosition(); + const auto destination = self->GetPosition(); - if (m_OrientCaster) - { - auto* baseCombatAIComponent = self->GetComponent(); + if (m_OrientCaster) { + auto* baseCombatAIComponent = self->GetComponent(); - /*if (baseCombatAIComponent != nullptr) - { - baseCombatAIComponent->LookAt(destination); - } - else*/ - { - self->SetRotation(NiQuaternion::LookAt(source, destination)); - } + /*if (baseCombatAIComponent != nullptr) + { + baseCombatAIComponent->LookAt(destination); + } + else*/ + { + self->SetRotation(NiQuaternion::LookAt(source, destination)); + } - EntityManager::Instance()->SerializeEntity(self); - } - else - { - other->SetRotation(NiQuaternion::LookAt(destination, source)); + EntityManager::Instance()->SerializeEntity(self); + } else { + other->SetRotation(NiQuaternion::LookAt(destination, source)); - EntityManager::Instance()->SerializeEntity(other); - } + EntityManager::Instance()->SerializeEntity(other); + } } -void ChangeOrientationBehavior::Load() -{ - m_OrientCaster = GetBoolean("orient_caster"); - m_ToTarget = GetBoolean("to_target"); +void ChangeOrientationBehavior::Load() { + m_OrientCaster = GetBoolean("orient_caster"); + m_ToTarget = GetBoolean("to_target"); } diff --git a/dGame/dBehaviors/ChangeOrientationBehavior.h b/dGame/dBehaviors/ChangeOrientationBehavior.h index 960ec8ea..eb038ffb 100644 --- a/dGame/dBehaviors/ChangeOrientationBehavior.h +++ b/dGame/dBehaviors/ChangeOrientationBehavior.h @@ -7,17 +7,16 @@ class ChangeOrientationBehavior final : public Behavior { public: - bool m_OrientCaster; - bool m_ToTarget; + bool m_OrientCaster; + bool m_ToTarget; /* * Inherited */ - explicit ChangeOrientationBehavior(const uint32_t behaviorId) : Behavior(behaviorId) - { + explicit ChangeOrientationBehavior(const uint32_t behaviorId) : Behavior(behaviorId) { } - + void Handle(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) override; void Calculate(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) override; diff --git a/dGame/dBehaviors/ChargeUpBehavior.cpp b/dGame/dBehaviors/ChargeUpBehavior.cpp index c9259801..5fc9822e 100644 --- a/dGame/dBehaviors/ChargeUpBehavior.cpp +++ b/dGame/dBehaviors/ChargeUpBehavior.cpp @@ -3,8 +3,7 @@ #include "BehaviorContext.h" #include "dLogger.h" -void ChargeUpBehavior::Handle(BehaviorContext* context, RakNet::BitStream* bitStream, const BehaviorBranchContext branch) -{ +void ChargeUpBehavior::Handle(BehaviorContext* context, RakNet::BitStream* bitStream, const BehaviorBranchContext branch) { uint32_t handle; bitStream->Read(handle); @@ -12,16 +11,13 @@ void ChargeUpBehavior::Handle(BehaviorContext* context, RakNet::BitStream* bitSt context->RegisterSyncBehavior(handle, this, branch); } -void ChargeUpBehavior::Calculate(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) -{ +void ChargeUpBehavior::Calculate(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) { } -void ChargeUpBehavior::Sync(BehaviorContext* context, RakNet::BitStream* bitStream, const BehaviorBranchContext branch) -{ +void ChargeUpBehavior::Sync(BehaviorContext* context, RakNet::BitStream* bitStream, const BehaviorBranchContext branch) { this->m_action->Handle(context, bitStream, branch); } -void ChargeUpBehavior::Load() -{ +void ChargeUpBehavior::Load() { this->m_action = GetAction("action"); } diff --git a/dGame/dBehaviors/ChargeUpBehavior.h b/dGame/dBehaviors/ChargeUpBehavior.h index f9c8d30a..a80026c5 100644 --- a/dGame/dBehaviors/ChargeUpBehavior.h +++ b/dGame/dBehaviors/ChargeUpBehavior.h @@ -5,13 +5,12 @@ class ChargeUpBehavior final : public Behavior { public: Behavior* m_action; - + /* * Inherited */ - explicit ChargeUpBehavior(const uint32_t behaviorId) : Behavior(behaviorId) - { + explicit ChargeUpBehavior(const uint32_t behaviorId) : Behavior(behaviorId) { } void Handle(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) override; @@ -19,6 +18,6 @@ public: void Calculate(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) override; void Sync(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) override; - + void Load() override; }; diff --git a/dGame/dBehaviors/ClearTargetBehavior.cpp b/dGame/dBehaviors/ClearTargetBehavior.cpp index 3428e754..e37161f3 100644 --- a/dGame/dBehaviors/ClearTargetBehavior.cpp +++ b/dGame/dBehaviors/ClearTargetBehavior.cpp @@ -3,23 +3,20 @@ #include "BehaviorContext.h" -void ClearTargetBehavior::Handle(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) -{ +void ClearTargetBehavior::Handle(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) { branch.target = LWOOBJID_EMPTY; this->m_action->Handle(context, bitStream, branch); } -void ClearTargetBehavior::Calculate(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) -{ +void ClearTargetBehavior::Calculate(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) { branch.target = LWOOBJID_EMPTY; this->m_action->Calculate(context, bitStream, branch); } -void ClearTargetBehavior::Load() -{ +void ClearTargetBehavior::Load() { this->m_action = GetAction("action"); - + this->m_clearIfCaster = GetBoolean("clear_if_caster"); } diff --git a/dGame/dBehaviors/ClearTargetBehavior.h b/dGame/dBehaviors/ClearTargetBehavior.h index ccb631a4..e1235eea 100644 --- a/dGame/dBehaviors/ClearTargetBehavior.h +++ b/dGame/dBehaviors/ClearTargetBehavior.h @@ -7,12 +7,11 @@ public: Behavior* m_action; bool m_clearIfCaster; - + /* * Inherited */ - explicit ClearTargetBehavior(const uint32_t behaviorId) : Behavior(behaviorId) - { + explicit ClearTargetBehavior(const uint32_t behaviorId) : Behavior(behaviorId) { } void Handle(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) override; diff --git a/dGame/dBehaviors/DamageAbsorptionBehavior.cpp b/dGame/dBehaviors/DamageAbsorptionBehavior.cpp index f02c4eea..4f4e5b81 100644 --- a/dGame/dBehaviors/DamageAbsorptionBehavior.cpp +++ b/dGame/dBehaviors/DamageAbsorptionBehavior.cpp @@ -7,12 +7,10 @@ #include "dLogger.h" #include "DestroyableComponent.h" -void DamageAbsorptionBehavior::Handle(BehaviorContext* context, RakNet::BitStream* bitStream, const BehaviorBranchContext branch) -{ +void DamageAbsorptionBehavior::Handle(BehaviorContext* context, RakNet::BitStream* bitStream, const BehaviorBranchContext branch) { auto* target = EntityManager::Instance()->GetEntity(branch.target); - if (target == nullptr) - { + if (target == nullptr) { Game::logger->Log("DamageAbsorptionBehavior", "Failed to find target (%llu)!", branch.target); return; @@ -20,8 +18,7 @@ void DamageAbsorptionBehavior::Handle(BehaviorContext* context, RakNet::BitStrea auto* destroyable = target->GetComponent(); - if (destroyable == nullptr) - { + if (destroyable == nullptr) { return; } @@ -32,17 +29,14 @@ void DamageAbsorptionBehavior::Handle(BehaviorContext* context, RakNet::BitStrea context->RegisterTimerBehavior(this, branch, target->GetObjectID()); } -void DamageAbsorptionBehavior::Calculate(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) -{ +void DamageAbsorptionBehavior::Calculate(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) { Handle(context, bitStream, branch); } -void DamageAbsorptionBehavior::Timer(BehaviorContext* context, BehaviorBranchContext branch, const LWOOBJID second) -{ +void DamageAbsorptionBehavior::Timer(BehaviorContext* context, BehaviorBranchContext branch, const LWOOBJID second) { auto* target = EntityManager::Instance()->GetEntity(second); - if (target == nullptr) - { + if (target == nullptr) { Game::logger->Log("DamageAbsorptionBehavior", "Failed to find target (%llu)!", second); return; @@ -50,8 +44,7 @@ void DamageAbsorptionBehavior::Timer(BehaviorContext* context, BehaviorBranchCon auto* destroyable = target->GetComponent(); - if (destroyable == nullptr) - { + if (destroyable == nullptr) { return; } @@ -62,7 +55,6 @@ void DamageAbsorptionBehavior::Timer(BehaviorContext* context, BehaviorBranchCon destroyable->SetDamageToAbsorb(present - toRemove); } -void DamageAbsorptionBehavior::Load() -{ +void DamageAbsorptionBehavior::Load() { this->m_absorbAmount = GetInt("absorb_amount"); } diff --git a/dGame/dBehaviors/DamageAbsorptionBehavior.h b/dGame/dBehaviors/DamageAbsorptionBehavior.h index 34b564a5..533fe554 100644 --- a/dGame/dBehaviors/DamageAbsorptionBehavior.h +++ b/dGame/dBehaviors/DamageAbsorptionBehavior.h @@ -5,13 +5,12 @@ class DamageAbsorptionBehavior final : public Behavior { public: uint32_t m_absorbAmount; - + /* * Inherited */ - explicit DamageAbsorptionBehavior(const uint32_t behaviorId) : Behavior(behaviorId) - { + explicit DamageAbsorptionBehavior(const uint32_t behaviorId) : Behavior(behaviorId) { } void Handle(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) override; diff --git a/dGame/dBehaviors/DamageReductionBehavior.cpp b/dGame/dBehaviors/DamageReductionBehavior.cpp index 45a30975..2b18b7c2 100644 --- a/dGame/dBehaviors/DamageReductionBehavior.cpp +++ b/dGame/dBehaviors/DamageReductionBehavior.cpp @@ -7,12 +7,10 @@ #include "dLogger.h" #include "DestroyableComponent.h" -void DamageReductionBehavior::Handle(BehaviorContext* context, RakNet::BitStream* bitStream, const BehaviorBranchContext branch) -{ +void DamageReductionBehavior::Handle(BehaviorContext* context, RakNet::BitStream* bitStream, const BehaviorBranchContext branch) { auto* target = EntityManager::Instance()->GetEntity(branch.target); - if (target == nullptr) - { + if (target == nullptr) { Game::logger->Log("DamageReductionBehavior", "Failed to find target (%llu)!", branch.target); return; @@ -20,8 +18,7 @@ void DamageReductionBehavior::Handle(BehaviorContext* context, RakNet::BitStream auto* destroyable = target->GetComponent(); - if (destroyable == nullptr) - { + if (destroyable == nullptr) { return; } @@ -30,17 +27,14 @@ void DamageReductionBehavior::Handle(BehaviorContext* context, RakNet::BitStream context->RegisterTimerBehavior(this, branch, target->GetObjectID()); } -void DamageReductionBehavior::Calculate(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) -{ +void DamageReductionBehavior::Calculate(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) { Handle(context, bitStream, branch); } -void DamageReductionBehavior::Timer(BehaviorContext* context, BehaviorBranchContext branch, const LWOOBJID second) -{ +void DamageReductionBehavior::Timer(BehaviorContext* context, BehaviorBranchContext branch, const LWOOBJID second) { auto* target = EntityManager::Instance()->GetEntity(second); - if (target == nullptr) - { + if (target == nullptr) { Game::logger->Log("DamageReductionBehavior", "Failed to find target (%llu)!", second); return; @@ -48,15 +42,13 @@ void DamageReductionBehavior::Timer(BehaviorContext* context, BehaviorBranchCont auto* destroyable = target->GetComponent(); - if (destroyable == nullptr) - { + if (destroyable == nullptr) { return; } destroyable->SetDamageReduction(0); } -void DamageReductionBehavior::Load() -{ +void DamageReductionBehavior::Load() { this->m_ReductionAmount = GetInt("reduction_amount"); } diff --git a/dGame/dBehaviors/DamageReductionBehavior.h b/dGame/dBehaviors/DamageReductionBehavior.h index 8881b88d..bddd31fb 100644 --- a/dGame/dBehaviors/DamageReductionBehavior.h +++ b/dGame/dBehaviors/DamageReductionBehavior.h @@ -5,13 +5,12 @@ class DamageReductionBehavior final : public Behavior { public: uint32_t m_ReductionAmount; - + /* * Inherited */ - explicit DamageReductionBehavior(const uint32_t behaviorId) : Behavior(behaviorId) - { + explicit DamageReductionBehavior(const uint32_t behaviorId) : Behavior(behaviorId) { } void Handle(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) override; diff --git a/dGame/dBehaviors/DurationBehavior.cpp b/dGame/dBehaviors/DurationBehavior.cpp index 1f95d7d4..6fc1b4d9 100644 --- a/dGame/dBehaviors/DurationBehavior.cpp +++ b/dGame/dBehaviors/DurationBehavior.cpp @@ -2,22 +2,19 @@ #include "BehaviorBranchContext.h" #include "BehaviorContext.h" -void DurationBehavior::Handle(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) -{ +void DurationBehavior::Handle(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) { branch.duration = this->m_duration; this->m_action->Handle(context, bitStream, branch); } -void DurationBehavior::Calculate(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) -{ +void DurationBehavior::Calculate(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) { branch.duration = this->m_duration; this->m_action->Calculate(context, bitStream, branch); } -void DurationBehavior::Load() -{ +void DurationBehavior::Load() { this->m_duration = GetFloat("duration"); this->m_action = GetAction("action"); diff --git a/dGame/dBehaviors/DurationBehavior.h b/dGame/dBehaviors/DurationBehavior.h index 82bc3230..b8533700 100644 --- a/dGame/dBehaviors/DurationBehavior.h +++ b/dGame/dBehaviors/DurationBehavior.h @@ -7,11 +7,10 @@ public: float m_duration; Behavior* m_action; - - explicit DurationBehavior(const uint32_t behavior_id) : Behavior(behavior_id) - { + + explicit DurationBehavior(const uint32_t behavior_id) : Behavior(behavior_id) { } - + void Handle(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) override; void Calculate(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) override; diff --git a/dGame/dBehaviors/EmptyBehavior.h b/dGame/dBehaviors/EmptyBehavior.h index f3f6a77f..64990ec4 100644 --- a/dGame/dBehaviors/EmptyBehavior.h +++ b/dGame/dBehaviors/EmptyBehavior.h @@ -5,7 +5,6 @@ class EmptyBehavior final : public Behavior { public: - explicit EmptyBehavior(const uint32_t behavior_id) : Behavior(behavior_id) - { + explicit EmptyBehavior(const uint32_t behavior_id) : Behavior(behavior_id) { } }; diff --git a/dGame/dBehaviors/EndBehavior.cpp b/dGame/dBehaviors/EndBehavior.cpp index 4e7b8351..bf35932f 100644 --- a/dGame/dBehaviors/EndBehavior.cpp +++ b/dGame/dBehaviors/EndBehavior.cpp @@ -3,17 +3,14 @@ #include "BehaviorContext.h" #include "BehaviorBranchContext.h" -void EndBehavior::Handle(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) -{ +void EndBehavior::Handle(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) { context->InvokeEnd(this->m_startBehavior); } -void EndBehavior::Calculate(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) -{ +void EndBehavior::Calculate(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) { context->InvokeEnd(this->m_startBehavior); } -void EndBehavior::Load() -{ +void EndBehavior::Load() { this->m_startBehavior = GetInt("start_action"); } diff --git a/dGame/dBehaviors/EndBehavior.h b/dGame/dBehaviors/EndBehavior.h index afa539ce..8503f7ba 100644 --- a/dGame/dBehaviors/EndBehavior.h +++ b/dGame/dBehaviors/EndBehavior.h @@ -5,17 +5,16 @@ class EndBehavior final : public Behavior { public: uint32_t m_startBehavior; - + /* * Inherited */ - explicit EndBehavior(const uint32_t behaviorId) : Behavior(behaviorId) - { + explicit EndBehavior(const uint32_t behaviorId) : Behavior(behaviorId) { } - + void Handle(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) override; - + void Calculate(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) override; void Load() override; diff --git a/dGame/dBehaviors/ForceMovementBehavior.cpp b/dGame/dBehaviors/ForceMovementBehavior.cpp index ea8c04a7..8074dbcc 100644 --- a/dGame/dBehaviors/ForceMovementBehavior.cpp +++ b/dGame/dBehaviors/ForceMovementBehavior.cpp @@ -5,77 +5,75 @@ #include "EntityManager.h" void ForceMovementBehavior::Handle(BehaviorContext* context, RakNet::BitStream* bitStream, const BehaviorBranchContext branch) { - if (this->m_hitAction->m_templateId == BehaviorTemplates::BEHAVIOR_EMPTY && this->m_hitEnemyAction->m_templateId == BehaviorTemplates::BEHAVIOR_EMPTY && this->m_hitFactionAction->m_templateId == BehaviorTemplates::BEHAVIOR_EMPTY) { - return; - } + if (this->m_hitAction->m_templateId == BehaviorTemplates::BEHAVIOR_EMPTY && this->m_hitEnemyAction->m_templateId == BehaviorTemplates::BEHAVIOR_EMPTY && this->m_hitFactionAction->m_templateId == BehaviorTemplates::BEHAVIOR_EMPTY) { + return; + } - uint32_t handle; - bitStream->Read(handle); - context->RegisterSyncBehavior(handle, this, branch); + uint32_t handle; + bitStream->Read(handle); + context->RegisterSyncBehavior(handle, this, branch); } -void ForceMovementBehavior::Sync(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) -{ - uint32_t next; - bitStream->Read(next); +void ForceMovementBehavior::Sync(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) { + uint32_t next; + bitStream->Read(next); - LWOOBJID target; - bitStream->Read(target); + LWOOBJID target; + bitStream->Read(target); - branch.target = target; - auto* behavior = CreateBehavior(next); - behavior->Handle(context, bitStream, branch); + branch.target = target; + auto* behavior = CreateBehavior(next); + behavior->Handle(context, bitStream, branch); } void ForceMovementBehavior::Calculate(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) { - if (this->m_hitAction->m_templateId == BehaviorTemplates::BEHAVIOR_EMPTY && this->m_hitEnemyAction->m_templateId == BehaviorTemplates::BEHAVIOR_EMPTY && this->m_hitFactionAction->m_templateId == BehaviorTemplates::BEHAVIOR_EMPTY) { - return; - } + if (this->m_hitAction->m_templateId == BehaviorTemplates::BEHAVIOR_EMPTY && this->m_hitEnemyAction->m_templateId == BehaviorTemplates::BEHAVIOR_EMPTY && this->m_hitFactionAction->m_templateId == BehaviorTemplates::BEHAVIOR_EMPTY) { + return; + } - auto* casterEntity = EntityManager::Instance()->GetEntity(context->caster); - if (casterEntity != nullptr) { - auto* controllablePhysicsComponent = casterEntity->GetComponent(); - if (controllablePhysicsComponent != nullptr) { + auto* casterEntity = EntityManager::Instance()->GetEntity(context->caster); + if (casterEntity != nullptr) { + auto* controllablePhysicsComponent = casterEntity->GetComponent(); + if (controllablePhysicsComponent != nullptr) { - if (m_Forward == 1) { - controllablePhysicsComponent->SetVelocity(controllablePhysicsComponent->GetRotation().GetForwardVector() * 25); - } + if (m_Forward == 1) { + controllablePhysicsComponent->SetVelocity(controllablePhysicsComponent->GetRotation().GetForwardVector() * 25); + } - EntityManager::Instance()->SerializeEntity(casterEntity); - } - } + EntityManager::Instance()->SerializeEntity(casterEntity); + } + } - const auto skillHandle = context->GetUniqueSkillId(); - bitStream->Write(skillHandle); + const auto skillHandle = context->GetUniqueSkillId(); + bitStream->Write(skillHandle); - context->SyncCalculation(skillHandle, this->m_Duration, this, branch); + context->SyncCalculation(skillHandle, this->m_Duration, this, branch); } -void ForceMovementBehavior::Load() -{ - this->m_hitAction = GetAction("hit_action"); - this->m_hitEnemyAction = GetAction("hit_action_enemy"); - this->m_hitFactionAction = GetAction("hit_action_faction"); - this->m_Duration = GetFloat("duration"); - this->m_Forward = GetFloat("forward"); - this->m_Left = GetFloat("left"); - this->m_Yaw = GetFloat("yaw"); +void ForceMovementBehavior::Load() { + this->m_hitAction = GetAction("hit_action"); + this->m_hitEnemyAction = GetAction("hit_action_enemy"); + this->m_hitFactionAction = GetAction("hit_action_faction"); + this->m_Duration = GetFloat("duration"); + this->m_Forward = GetFloat("forward"); + this->m_Left = GetFloat("left"); + this->m_Yaw = GetFloat("yaw"); } void ForceMovementBehavior::SyncCalculation(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) { - auto* casterEntity = EntityManager::Instance()->GetEntity(context->caster); - if (casterEntity != nullptr) { - auto* controllablePhysicsComponent = casterEntity->GetComponent(); - if (controllablePhysicsComponent != nullptr) { + auto* casterEntity = EntityManager::Instance()->GetEntity(context->caster); + if (casterEntity != nullptr) { + auto* controllablePhysicsComponent = casterEntity->GetComponent(); + if (controllablePhysicsComponent != nullptr) { - controllablePhysicsComponent->SetPosition(controllablePhysicsComponent->GetPosition() + controllablePhysicsComponent->GetVelocity() * m_Duration); - controllablePhysicsComponent->SetVelocity({}); + controllablePhysicsComponent->SetPosition(controllablePhysicsComponent->GetPosition() + controllablePhysicsComponent->GetVelocity() * m_Duration); + controllablePhysicsComponent->SetVelocity({}); - EntityManager::Instance()->SerializeEntity(casterEntity); - } - } + EntityManager::Instance()->SerializeEntity(casterEntity); + } + } - this->m_hitAction->Calculate(context, bitStream, branch); - this->m_hitEnemyAction->Calculate(context, bitStream, branch); - this->m_hitEnemyAction->Calculate(context, bitStream, branch); + this->m_hitAction->Calculate(context, bitStream, branch); + this->m_hitEnemyAction->Calculate(context, bitStream, branch); + this->m_hitEnemyAction->Calculate(context, bitStream, branch); } diff --git a/dGame/dBehaviors/ForceMovementBehavior.h b/dGame/dBehaviors/ForceMovementBehavior.h index 50b0aa26..26b5ce89 100644 --- a/dGame/dBehaviors/ForceMovementBehavior.h +++ b/dGame/dBehaviors/ForceMovementBehavior.h @@ -10,27 +10,26 @@ public: Behavior* m_hitFactionAction; - float_t m_Duration; - float_t m_Forward; - float_t m_Left; - float_t m_Yaw; - + float_t m_Duration; + float_t m_Forward; + float_t m_Left; + float_t m_Yaw; + /* * Inherited */ - explicit ForceMovementBehavior(const uint32_t behaviorId) : Behavior(behaviorId) - { + explicit ForceMovementBehavior(const uint32_t behaviorId) : Behavior(behaviorId) { } - void Calculate(BehaviorContext *context, RakNet::BitStream *bitStream, BehaviorBranchContext branch) override; + void Calculate(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) override; void Handle(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) override; - void SyncCalculation(BehaviorContext *context, RakNet::BitStream *bitStream, BehaviorBranchContext branch) override; + void SyncCalculation(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) override; void Sync(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) override; - + void Load() override; - + }; diff --git a/dGame/dBehaviors/HealBehavior.cpp b/dGame/dBehaviors/HealBehavior.cpp index 41107203..da0d4a3b 100644 --- a/dGame/dBehaviors/HealBehavior.cpp +++ b/dGame/dBehaviors/HealBehavior.cpp @@ -6,12 +6,10 @@ #include "DestroyableComponent.h" -void HealBehavior::Handle(BehaviorContext* context, RakNet::BitStream* bit_stream, const BehaviorBranchContext branch) -{ +void HealBehavior::Handle(BehaviorContext* context, RakNet::BitStream* bit_stream, const BehaviorBranchContext branch) { auto* entity = EntityManager::Instance()->GetEntity(branch.target); - if (entity == nullptr) - { + if (entity == nullptr) { Game::logger->Log("HealBehavior", "Failed to find entity for (%llu)!", branch.target); return; @@ -19,8 +17,7 @@ void HealBehavior::Handle(BehaviorContext* context, RakNet::BitStream* bit_strea auto* destroyable = static_cast(entity->GetComponent(COMPONENT_TYPE_DESTROYABLE)); - if (destroyable == nullptr) - { + if (destroyable == nullptr) { Game::logger->Log("HealBehavior", "Failed to find destroyable component for %(llu)!", branch.target); return; @@ -30,13 +27,11 @@ void HealBehavior::Handle(BehaviorContext* context, RakNet::BitStream* bit_strea } -void HealBehavior::Calculate(BehaviorContext* context, RakNet::BitStream* bit_stream, const BehaviorBranchContext branch) -{ +void HealBehavior::Calculate(BehaviorContext* context, RakNet::BitStream* bit_stream, const BehaviorBranchContext branch) { Handle(context, bit_stream, branch); } -void HealBehavior::Load() -{ +void HealBehavior::Load() { this->m_health = GetInt("health"); } diff --git a/dGame/dBehaviors/HealBehavior.h b/dGame/dBehaviors/HealBehavior.h index f5568551..0a719b6c 100644 --- a/dGame/dBehaviors/HealBehavior.h +++ b/dGame/dBehaviors/HealBehavior.h @@ -5,13 +5,12 @@ class HealBehavior final : public Behavior { public: uint32_t m_health; - + /* * Inherited */ - explicit HealBehavior(const uint32_t behavior_id) : Behavior(behavior_id) - { + explicit HealBehavior(const uint32_t behavior_id) : Behavior(behavior_id) { } void Handle(BehaviorContext* context, RakNet::BitStream* bit_stream, BehaviorBranchContext branch) override; diff --git a/dGame/dBehaviors/ImaginationBehavior.cpp b/dGame/dBehaviors/ImaginationBehavior.cpp index d2d50fbe..cf2cd757 100644 --- a/dGame/dBehaviors/ImaginationBehavior.cpp +++ b/dGame/dBehaviors/ImaginationBehavior.cpp @@ -6,19 +6,16 @@ #include "dLogger.h" -void ImaginationBehavior::Handle(BehaviorContext* context, RakNet::BitStream* bit_stream, const BehaviorBranchContext branch) -{ +void ImaginationBehavior::Handle(BehaviorContext* context, RakNet::BitStream* bit_stream, const BehaviorBranchContext branch) { auto* entity = EntityManager::Instance()->GetEntity(branch.target); - if (entity == nullptr) - { + if (entity == nullptr) { return; } auto* destroyable = entity->GetComponent(); - if (destroyable == nullptr) - { + if (destroyable == nullptr) { return; } @@ -26,12 +23,10 @@ void ImaginationBehavior::Handle(BehaviorContext* context, RakNet::BitStream* bi } -void ImaginationBehavior::Calculate(BehaviorContext* context, RakNet::BitStream* bit_stream, const BehaviorBranchContext branch) -{ +void ImaginationBehavior::Calculate(BehaviorContext* context, RakNet::BitStream* bit_stream, const BehaviorBranchContext branch) { Handle(context, bit_stream, branch); } -void ImaginationBehavior::Load() -{ +void ImaginationBehavior::Load() { this->m_imagination = GetInt("imagination"); } diff --git a/dGame/dBehaviors/ImaginationBehavior.h b/dGame/dBehaviors/ImaginationBehavior.h index 52a2c1b3..59d864f9 100644 --- a/dGame/dBehaviors/ImaginationBehavior.h +++ b/dGame/dBehaviors/ImaginationBehavior.h @@ -10,8 +10,7 @@ public: * Inherited */ - explicit ImaginationBehavior(const uint32_t behavior_id) : Behavior(behavior_id) - { + explicit ImaginationBehavior(const uint32_t behavior_id) : Behavior(behavior_id) { } void Handle(BehaviorContext* context, RakNet::BitStream* bit_stream, BehaviorBranchContext branch) override; diff --git a/dGame/dBehaviors/ImmunityBehavior.cpp b/dGame/dBehaviors/ImmunityBehavior.cpp index 4e72ba36..93110cde 100644 --- a/dGame/dBehaviors/ImmunityBehavior.cpp +++ b/dGame/dBehaviors/ImmunityBehavior.cpp @@ -7,12 +7,10 @@ #include "dLogger.h" #include "DestroyableComponent.h" -void ImmunityBehavior::Handle(BehaviorContext* context, RakNet::BitStream* bitStream, const BehaviorBranchContext branch) -{ +void ImmunityBehavior::Handle(BehaviorContext* context, RakNet::BitStream* bitStream, const BehaviorBranchContext branch) { auto* target = EntityManager::Instance()->GetEntity(branch.target); - if (target == nullptr) - { + if (target == nullptr) { Game::logger->Log("DamageAbsorptionBehavior", "Failed to find target (%llu)!", branch.target); return; @@ -20,13 +18,11 @@ void ImmunityBehavior::Handle(BehaviorContext* context, RakNet::BitStream* bitSt auto* destroyable = static_cast(target->GetComponent(COMPONENT_TYPE_DESTROYABLE)); - if (destroyable == nullptr) - { + if (destroyable == nullptr) { return; } - if (!this->m_immuneBasicAttack) - { + if (!this->m_immuneBasicAttack) { return; } @@ -35,17 +31,14 @@ void ImmunityBehavior::Handle(BehaviorContext* context, RakNet::BitStream* bitSt context->RegisterTimerBehavior(this, branch, target->GetObjectID()); } -void ImmunityBehavior::Calculate(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) -{ +void ImmunityBehavior::Calculate(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) { Handle(context, bitStream, branch); } -void ImmunityBehavior::Timer(BehaviorContext* context, BehaviorBranchContext branch, const LWOOBJID second) -{ +void ImmunityBehavior::Timer(BehaviorContext* context, BehaviorBranchContext branch, const LWOOBJID second) { auto* target = EntityManager::Instance()->GetEntity(second); - if (target == nullptr) - { + if (target == nullptr) { Game::logger->Log("DamageAbsorptionBehavior", "Failed to find target (%llu)!", second); return; @@ -53,15 +46,13 @@ void ImmunityBehavior::Timer(BehaviorContext* context, BehaviorBranchContext bra auto* destroyable = static_cast(target->GetComponent(COMPONENT_TYPE_DESTROYABLE)); - if (destroyable == nullptr) - { + if (destroyable == nullptr) { return; } destroyable->PopImmunity(); } -void ImmunityBehavior::Load() -{ +void ImmunityBehavior::Load() { this->m_immuneBasicAttack = GetBoolean("immune_basic_attack"); } diff --git a/dGame/dBehaviors/ImmunityBehavior.h b/dGame/dBehaviors/ImmunityBehavior.h index 72ea843b..8a66b3d2 100644 --- a/dGame/dBehaviors/ImmunityBehavior.h +++ b/dGame/dBehaviors/ImmunityBehavior.h @@ -5,13 +5,12 @@ class ImmunityBehavior final : public Behavior { public: uint32_t m_immuneBasicAttack; - + /* * Inherited */ - explicit ImmunityBehavior(const uint32_t behaviorId) : Behavior(behaviorId) - { + explicit ImmunityBehavior(const uint32_t behaviorId) : Behavior(behaviorId) { } void Handle(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) override; diff --git a/dGame/dBehaviors/InterruptBehavior.cpp b/dGame/dBehaviors/InterruptBehavior.cpp index 559a699d..b0695430 100644 --- a/dGame/dBehaviors/InterruptBehavior.cpp +++ b/dGame/dBehaviors/InterruptBehavior.cpp @@ -7,10 +7,8 @@ #include "SkillComponent.h" -void InterruptBehavior::Handle(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) -{ - if (branch.target != context->originator) - { +void InterruptBehavior::Handle(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) { + if (branch.target != context->originator) { bool unknown = false; bitStream->Read(unknown); @@ -18,8 +16,7 @@ void InterruptBehavior::Handle(BehaviorContext* context, RakNet::BitStream* bitS if (unknown) return; } - if (!this->m_interruptBlock) - { + if (!this->m_interruptBlock) { bool unknown = false; bitStream->Read(unknown); @@ -48,15 +45,12 @@ void InterruptBehavior::Handle(BehaviorContext* context, RakNet::BitStream* bitS } -void InterruptBehavior::Calculate(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) -{ - if (branch.target != context->originator) - { +void InterruptBehavior::Calculate(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) { + if (branch.target != context->originator) { bitStream->Write(false); } - if (!this->m_interruptBlock) - { + if (!this->m_interruptBlock) { bitStream->Write(false); } @@ -71,14 +65,13 @@ void InterruptBehavior::Calculate(BehaviorContext* context, RakNet::BitStream* b auto* skillComponent = target->GetComponent(); if (skillComponent == nullptr) return; - + skillComponent->Interrupt(); } -void InterruptBehavior::Load() -{ +void InterruptBehavior::Load() { this->m_target = GetBoolean("target"); - + this->m_interruptBlock = GetBoolean("interrupt_block"); } diff --git a/dGame/dBehaviors/InterruptBehavior.h b/dGame/dBehaviors/InterruptBehavior.h index b5e3b6f6..35a2def9 100644 --- a/dGame/dBehaviors/InterruptBehavior.h +++ b/dGame/dBehaviors/InterruptBehavior.h @@ -5,20 +5,19 @@ class InterruptBehavior final : public Behavior { public: bool m_target; - + bool m_interruptBlock; /* * Inherited */ - explicit InterruptBehavior(const uint32_t behavior_id) : Behavior(behavior_id) - { + explicit InterruptBehavior(const uint32_t behavior_id) : Behavior(behavior_id) { } - + void Handle(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) override; - + void Calculate(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) override; - + void Load() override; }; diff --git a/dGame/dBehaviors/JetPackBehavior.cpp b/dGame/dBehaviors/JetPackBehavior.cpp index 63c0c6a9..00900735 100644 --- a/dGame/dBehaviors/JetPackBehavior.cpp +++ b/dGame/dBehaviors/JetPackBehavior.cpp @@ -4,26 +4,26 @@ #include "GameMessages.h" void JetPackBehavior::Handle(BehaviorContext* context, RakNet::BitStream* bit_stream, const BehaviorBranchContext branch) { - auto* entity = EntityManager::Instance()->GetEntity(branch.target); - + auto* entity = EntityManager::Instance()->GetEntity(branch.target); + GameMessages::SendSetJetPackMode(entity, true, this->m_BypassChecks, this->m_EnableHover, this->m_effectId, this->m_Airspeed, this->m_MaxAirspeed, this->m_VerticalVelocity, this->m_WarningEffectID); } void JetPackBehavior::UnCast(BehaviorContext* context, BehaviorBranchContext branch) { - auto* entity = EntityManager::Instance()->GetEntity(branch.target); + auto* entity = EntityManager::Instance()->GetEntity(branch.target); GameMessages::SendSetJetPackMode(entity, false); } void JetPackBehavior::Calculate(BehaviorContext* context, RakNet::BitStream* bit_stream, const BehaviorBranchContext branch) { - Handle(context, bit_stream, branch); + Handle(context, bit_stream, branch); } void JetPackBehavior::Load() { - this->m_WarningEffectID = GetInt("warning_effect_id"); - this->m_Airspeed = GetFloat("airspeed"); - this->m_MaxAirspeed = GetFloat("max_airspeed"); - this->m_VerticalVelocity = GetFloat("vertical_velocity"); - this->m_EnableHover = GetBoolean("enable_hover"); - this->m_BypassChecks = GetBoolean("bypass_checks", true); + this->m_WarningEffectID = GetInt("warning_effect_id"); + this->m_Airspeed = GetFloat("airspeed"); + this->m_MaxAirspeed = GetFloat("max_airspeed"); + this->m_VerticalVelocity = GetFloat("vertical_velocity"); + this->m_EnableHover = GetBoolean("enable_hover"); + this->m_BypassChecks = GetBoolean("bypass_checks", true); } diff --git a/dGame/dBehaviors/JetPackBehavior.h b/dGame/dBehaviors/JetPackBehavior.h index d891bf54..0cc6c399 100644 --- a/dGame/dBehaviors/JetPackBehavior.h +++ b/dGame/dBehaviors/JetPackBehavior.h @@ -1,7 +1,7 @@ #pragma once #include "Behavior.h" -class JetPackBehavior final : public Behavior +class JetPackBehavior final : public Behavior { public: int32_t m_WarningEffectID; diff --git a/dGame/dBehaviors/KnockbackBehavior.cpp b/dGame/dBehaviors/KnockbackBehavior.cpp index 37092536..0b1fc5d7 100644 --- a/dGame/dBehaviors/KnockbackBehavior.cpp +++ b/dGame/dBehaviors/KnockbackBehavior.cpp @@ -7,25 +7,21 @@ #include "GameMessages.h" #include "DestroyableComponent.h" -void KnockbackBehavior::Handle(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) -{ +void KnockbackBehavior::Handle(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) { bool unknown; bitStream->Read(unknown); } -void KnockbackBehavior::Calculate(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) -{ +void KnockbackBehavior::Calculate(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) { bool blocked = false; auto* target = EntityManager::Instance()->GetEntity(branch.target); - if (target != nullptr) - { + if (target != nullptr) { auto* destroyableComponent = target->GetComponent(); - if (destroyableComponent != nullptr) - { + if (destroyableComponent != nullptr) { blocked = destroyableComponent->IsKnockbackImmune(); } } @@ -33,8 +29,7 @@ void KnockbackBehavior::Calculate(BehaviorContext* context, RakNet::BitStream* b bitStream->Write(blocked); } -void KnockbackBehavior::Load() -{ +void KnockbackBehavior::Load() { this->m_strength = GetInt("strength"); this->m_angle = GetInt("angle"); this->m_relative = GetBoolean("relative"); diff --git a/dGame/dBehaviors/KnockbackBehavior.h b/dGame/dBehaviors/KnockbackBehavior.h index 0f939acd..4feb592c 100644 --- a/dGame/dBehaviors/KnockbackBehavior.h +++ b/dGame/dBehaviors/KnockbackBehavior.h @@ -12,10 +12,9 @@ public: uint32_t m_angle; bool m_relative; uint32_t m_time; - - explicit KnockbackBehavior(const uint32_t behaviorID) : Behavior(behaviorID) - { + + explicit KnockbackBehavior(const uint32_t behaviorID) : Behavior(behaviorID) { } void Handle(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) override; diff --git a/dGame/dBehaviors/LootBuffBehavior.cpp b/dGame/dBehaviors/LootBuffBehavior.cpp index fe46f7bb..6e5634fc 100644 --- a/dGame/dBehaviors/LootBuffBehavior.cpp +++ b/dGame/dBehaviors/LootBuffBehavior.cpp @@ -1,38 +1,38 @@ #include "LootBuffBehavior.h" -void LootBuffBehavior::Handle(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) { - auto target = EntityManager::Instance()->GetEntity(context->caster); - if (!target) return; +void LootBuffBehavior::Handle(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) { + auto target = EntityManager::Instance()->GetEntity(context->caster); + if (!target) return; - auto controllablePhysicsComponent = target->GetComponent(); - if (!controllablePhysicsComponent) return; + auto controllablePhysicsComponent = target->GetComponent(); + if (!controllablePhysicsComponent) return; - controllablePhysicsComponent->AddPickupRadiusScale(m_Scale); - EntityManager::Instance()->SerializeEntity(target); + controllablePhysicsComponent->AddPickupRadiusScale(m_Scale); + EntityManager::Instance()->SerializeEntity(target); - if (branch.duration > 0) context->RegisterTimerBehavior(this, branch); + if (branch.duration > 0) context->RegisterTimerBehavior(this, branch); } void LootBuffBehavior::Calculate(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) { - Handle(context, bitStream, branch); + Handle(context, bitStream, branch); } void LootBuffBehavior::UnCast(BehaviorContext* context, BehaviorBranchContext branch) { - auto target = EntityManager::Instance()->GetEntity(context->caster); - if (!target) return; + auto target = EntityManager::Instance()->GetEntity(context->caster); + if (!target) return; - auto controllablePhysicsComponent = target->GetComponent(); - if (!controllablePhysicsComponent) return; + auto controllablePhysicsComponent = target->GetComponent(); + if (!controllablePhysicsComponent) return; - controllablePhysicsComponent->RemovePickupRadiusScale(m_Scale); - EntityManager::Instance()->SerializeEntity(target); + controllablePhysicsComponent->RemovePickupRadiusScale(m_Scale); + EntityManager::Instance()->SerializeEntity(target); } void LootBuffBehavior::Timer(BehaviorContext* context, BehaviorBranchContext branch, LWOOBJID second) { - UnCast(context, branch); + UnCast(context, branch); } void LootBuffBehavior::Load() { - this->m_Scale = GetFloat("scale"); -} \ No newline at end of file + this->m_Scale = GetFloat("scale"); +} diff --git a/dGame/dBehaviors/LootBuffBehavior.h b/dGame/dBehaviors/LootBuffBehavior.h index 0f85b3b0..b6f700ca 100644 --- a/dGame/dBehaviors/LootBuffBehavior.h +++ b/dGame/dBehaviors/LootBuffBehavior.h @@ -6,7 +6,7 @@ /** * @brief This is the behavior class to be used for all Loot Buff behavior nodes in the Behavior tree. - * + * */ class LootBuffBehavior final : public Behavior { @@ -17,13 +17,13 @@ public: /* * Inherited */ - + explicit LootBuffBehavior(const uint32_t behaviorId) : Behavior(behaviorId) {} void Handle(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) override; void Calculate(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) override; - + void UnCast(BehaviorContext* context, BehaviorBranchContext branch) override; void Timer(BehaviorContext* context, BehaviorBranchContext branch, LWOOBJID second) override; diff --git a/dGame/dBehaviors/MovementSwitchBehavior.cpp b/dGame/dBehaviors/MovementSwitchBehavior.cpp index 066f6224..de1b0b50 100644 --- a/dGame/dBehaviors/MovementSwitchBehavior.cpp +++ b/dGame/dBehaviors/MovementSwitchBehavior.cpp @@ -3,15 +3,13 @@ #include "Game.h" #include "dLogger.h" -void MovementSwitchBehavior::Handle(BehaviorContext* context, RakNet::BitStream* bitStream, const BehaviorBranchContext branch) -{ +void MovementSwitchBehavior::Handle(BehaviorContext* context, RakNet::BitStream* bitStream, const BehaviorBranchContext branch) { if (this->m_groundAction->m_templateId == BehaviorTemplates::BEHAVIOR_EMPTY && this->m_jumpAction->m_templateId == BehaviorTemplates::BEHAVIOR_EMPTY && this->m_fallingAction->m_templateId == BehaviorTemplates::BEHAVIOR_EMPTY && this->m_doubleJumpAction->m_templateId == BehaviorTemplates::BEHAVIOR_EMPTY && this->m_airAction->m_templateId == BehaviorTemplates::BEHAVIOR_EMPTY && - this->m_jetpackAction->m_templateId == BehaviorTemplates::BEHAVIOR_EMPTY) - { + this->m_jetpackAction->m_templateId == BehaviorTemplates::BEHAVIOR_EMPTY) { return; } @@ -19,8 +17,7 @@ void MovementSwitchBehavior::Handle(BehaviorContext* context, RakNet::BitStream* bitStream->Read(movementType); - switch (movementType) - { + switch (movementType) { case 1: this->m_groundAction->Handle(context, bitStream, branch); break; @@ -45,8 +42,7 @@ void MovementSwitchBehavior::Handle(BehaviorContext* context, RakNet::BitStream* } } -void MovementSwitchBehavior::Load() -{ +void MovementSwitchBehavior::Load() { this->m_airAction = GetAction("air_action"); this->m_doubleJumpAction = GetAction("double_jump_action"); diff --git a/dGame/dBehaviors/MovementSwitchBehavior.h b/dGame/dBehaviors/MovementSwitchBehavior.h index 59069eff..8a1e83a3 100644 --- a/dGame/dBehaviors/MovementSwitchBehavior.h +++ b/dGame/dBehaviors/MovementSwitchBehavior.h @@ -8,7 +8,7 @@ public: * Members */ Behavior* m_airAction; - + Behavior* m_doubleJumpAction; Behavior* m_fallingAction; @@ -18,14 +18,13 @@ public: Behavior* m_jetpackAction; Behavior* m_jumpAction; - + /* * Inherited */ - explicit MovementSwitchBehavior(const uint32_t behavior_id) : Behavior(behavior_id) - { + explicit MovementSwitchBehavior(const uint32_t behavior_id) : Behavior(behavior_id) { } - + void Handle(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) override; void Load() override; diff --git a/dGame/dBehaviors/NpcCombatSkillBehavior.cpp b/dGame/dBehaviors/NpcCombatSkillBehavior.cpp index c2aff256..d541033c 100644 --- a/dGame/dBehaviors/NpcCombatSkillBehavior.cpp +++ b/dGame/dBehaviors/NpcCombatSkillBehavior.cpp @@ -3,26 +3,21 @@ #include "BehaviorContext.h" -void NpcCombatSkillBehavior::Calculate(BehaviorContext* context, RakNet::BitStream* bit_stream, BehaviorBranchContext branch) -{ +void NpcCombatSkillBehavior::Calculate(BehaviorContext* context, RakNet::BitStream* bit_stream, BehaviorBranchContext branch) { context->skillTime = this->m_npcSkillTime; - - for (auto* behavior : this->m_behaviors) - { + + for (auto* behavior : this->m_behaviors) { behavior->Calculate(context, bit_stream, branch); } } -void NpcCombatSkillBehavior::Load() -{ +void NpcCombatSkillBehavior::Load() { this->m_npcSkillTime = GetFloat("npc skill time"); - + const auto parameters = GetParameterNames(); - for (const auto& parameter : parameters) - { - if (parameter.first.rfind("behavior", 0) == 0) - { + for (const auto& parameter : parameters) { + if (parameter.first.rfind("behavior", 0) == 0) { auto* action = GetAction(parameter.second); this->m_behaviors.push_back(action); diff --git a/dGame/dBehaviors/NpcCombatSkillBehavior.h b/dGame/dBehaviors/NpcCombatSkillBehavior.h index a5523acd..f2ed60b9 100644 --- a/dGame/dBehaviors/NpcCombatSkillBehavior.h +++ b/dGame/dBehaviors/NpcCombatSkillBehavior.h @@ -12,10 +12,9 @@ public: * Inherited */ - explicit NpcCombatSkillBehavior(const uint32_t behavior_id) : Behavior(behavior_id) - { + explicit NpcCombatSkillBehavior(const uint32_t behavior_id) : Behavior(behavior_id) { } - + void Calculate(BehaviorContext* context, RakNet::BitStream* bit_stream, BehaviorBranchContext branch) override; void Load() override; diff --git a/dGame/dBehaviors/OverTimeBehavior.cpp b/dGame/dBehaviors/OverTimeBehavior.cpp index 9e8618df..43ac9bc2 100644 --- a/dGame/dBehaviors/OverTimeBehavior.cpp +++ b/dGame/dBehaviors/OverTimeBehavior.cpp @@ -7,43 +7,39 @@ #include "SkillComponent.h" #include "DestroyableComponent.h" -void OverTimeBehavior::Handle(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) -{ - const auto originator = context->originator; +void OverTimeBehavior::Handle(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) { + const auto originator = context->originator; - auto* entity = EntityManager::Instance()->GetEntity(originator); + auto* entity = EntityManager::Instance()->GetEntity(originator); - if (entity == nullptr) return; + if (entity == nullptr) return; - for (size_t i = 0; i < m_NumIntervals; i++) - { - entity->AddCallbackTimer((i + 1) * m_Delay, [originator, branch, this]() { - auto* entity = EntityManager::Instance()->GetEntity(originator); + for (size_t i = 0; i < m_NumIntervals; i++) { + entity->AddCallbackTimer((i + 1) * m_Delay, [originator, branch, this]() { + auto* entity = EntityManager::Instance()->GetEntity(originator); - if (entity == nullptr) return; + if (entity == nullptr) return; - auto* skillComponent = entity->GetComponent(); + auto* skillComponent = entity->GetComponent(); - if (skillComponent == nullptr) return; + if (skillComponent == nullptr) return; - skillComponent->CalculateBehavior(m_Action, m_ActionBehaviorId, branch.target, true, true); - }); - } + skillComponent->CalculateBehavior(m_Action, m_ActionBehaviorId, branch.target, true, true); + }); + } } -void OverTimeBehavior::Calculate(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) -{ - +void OverTimeBehavior::Calculate(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) { + } -void OverTimeBehavior::Load() -{ - m_Action = GetInt("action"); - // Since m_Action is a skillID and not a behavior, get is correlated behaviorID. +void OverTimeBehavior::Load() { + m_Action = GetInt("action"); + // Since m_Action is a skillID and not a behavior, get is correlated behaviorID. - CDSkillBehaviorTable* skillTable = CDClientManager::Instance()->GetTable("SkillBehavior"); - m_ActionBehaviorId = skillTable->GetSkillByID(m_Action).behaviorID; + CDSkillBehaviorTable* skillTable = CDClientManager::Instance()->GetTable("SkillBehavior"); + m_ActionBehaviorId = skillTable->GetSkillByID(m_Action).behaviorID; - m_Delay = GetFloat("delay"); - m_NumIntervals = GetInt("num_intervals"); + m_Delay = GetFloat("delay"); + m_NumIntervals = GetInt("num_intervals"); } diff --git a/dGame/dBehaviors/OverTimeBehavior.h b/dGame/dBehaviors/OverTimeBehavior.h index 5c177926..73a07865 100644 --- a/dGame/dBehaviors/OverTimeBehavior.h +++ b/dGame/dBehaviors/OverTimeBehavior.h @@ -4,19 +4,18 @@ class OverTimeBehavior final : public Behavior { public: - uint32_t m_Action; + uint32_t m_Action; uint32_t m_ActionBehaviorId; - float m_Delay; - int32_t m_NumIntervals; + float m_Delay; + int32_t m_NumIntervals; /* * Inherited */ - explicit OverTimeBehavior(const uint32_t behaviorId) : Behavior(behaviorId) - { + explicit OverTimeBehavior(const uint32_t behaviorId) : Behavior(behaviorId) { } - + void Handle(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) override; void Calculate(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) override; diff --git a/dGame/dBehaviors/PlayEffectBehavior.cpp b/dGame/dBehaviors/PlayEffectBehavior.cpp index 20148132..9793c1db 100644 --- a/dGame/dBehaviors/PlayEffectBehavior.cpp +++ b/dGame/dBehaviors/PlayEffectBehavior.cpp @@ -3,8 +3,7 @@ #include "BehaviorContext.h" #include "BehaviorBranchContext.h" -void PlayEffectBehavior::Handle(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) -{ +void PlayEffectBehavior::Handle(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) { // On managed behaviors this is handled by the client if (!context->unmanaged) return; @@ -14,13 +13,11 @@ void PlayEffectBehavior::Handle(BehaviorContext* context, RakNet::BitStream* bit PlayFx(u"", target); } -void PlayEffectBehavior::Calculate(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) -{ +void PlayEffectBehavior::Calculate(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) { const auto& target = branch.target == LWOOBJID_EMPTY ? context->originator : branch.target; //PlayFx(u"", target); } -void PlayEffectBehavior::Load() -{ +void PlayEffectBehavior::Load() { } diff --git a/dGame/dBehaviors/PlayEffectBehavior.h b/dGame/dBehaviors/PlayEffectBehavior.h index 3f49f38c..d6069305 100644 --- a/dGame/dBehaviors/PlayEffectBehavior.h +++ b/dGame/dBehaviors/PlayEffectBehavior.h @@ -7,13 +7,12 @@ public: /* * Inherited */ - explicit PlayEffectBehavior(const uint32_t behaviorId) : Behavior(behaviorId) - { + explicit PlayEffectBehavior(const uint32_t behaviorId) : Behavior(behaviorId) { } void Handle(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) override; void Calculate(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) override; - + void Load() override; }; diff --git a/dGame/dBehaviors/ProjectileAttackBehavior.cpp b/dGame/dBehaviors/ProjectileAttackBehavior.cpp index 5bf8b6a1..861837e7 100644 --- a/dGame/dBehaviors/ProjectileAttackBehavior.cpp +++ b/dGame/dBehaviors/ProjectileAttackBehavior.cpp @@ -7,16 +7,14 @@ #include "SkillComponent.h" #include "../dWorldServer/ObjectIDManager.h" -void ProjectileAttackBehavior::Handle(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) -{ +void ProjectileAttackBehavior::Handle(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) { LWOOBJID target; bitStream->Read(target); auto* entity = EntityManager::Instance()->GetEntity(context->originator); - if (entity == nullptr) - { + if (entity == nullptr) { Game::logger->Log("ProjectileAttackBehavior", "Failed to find originator (%llu)!", context->originator); return; @@ -24,23 +22,20 @@ void ProjectileAttackBehavior::Handle(BehaviorContext* context, RakNet::BitStrea auto* skillComponent = entity->GetComponent(); - if (skillComponent == nullptr) - { + if (skillComponent == nullptr) { Game::logger->Log("ProjectileAttackBehavior", "Failed to find skill component for (%llu)!", -context->originator); return; } - if (m_useMouseposit) - { + if (m_useMouseposit) { NiPoint3 targetPosition = NiPoint3::ZERO; bitStream->Read(targetPosition); } auto* targetEntity = EntityManager::Instance()->GetEntity(target); - for (auto i = 0u; i < this->m_projectileCount; ++i) - { + for (auto i = 0u; i < this->m_projectileCount; ++i) { LWOOBJID projectileId; bitStream->Read(projectileId); @@ -53,14 +48,12 @@ void ProjectileAttackBehavior::Handle(BehaviorContext* context, RakNet::BitStrea } } -void ProjectileAttackBehavior::Calculate(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) -{ +void ProjectileAttackBehavior::Calculate(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) { bitStream->Write(branch.target); auto* entity = EntityManager::Instance()->GetEntity(context->originator); - if (entity == nullptr) - { + if (entity == nullptr) { Game::logger->Log("ProjectileAttackBehavior", "Failed to find originator (%llu)!", context->originator); return; @@ -68,8 +61,7 @@ void ProjectileAttackBehavior::Calculate(BehaviorContext* context, RakNet::BitSt auto* skillComponent = entity->GetComponent(); - if (skillComponent == nullptr) - { + if (skillComponent == nullptr) { Game::logger->Log("ProjectileAttackBehavior", "Failed to find skill component for (%llu)!", context->originator); return; @@ -78,8 +70,7 @@ void ProjectileAttackBehavior::Calculate(BehaviorContext* context, RakNet::BitSt auto* other = EntityManager::Instance()->GetEntity(branch.target); - if (other == nullptr) - { + if (other == nullptr) { Game::logger->Log("ProjectileAttackBehavior", "Invalid projectile target (%llu)!", branch.target); return; @@ -104,8 +95,7 @@ void ProjectileAttackBehavior::Calculate(BehaviorContext* context, RakNet::BitSt const auto maxTime = this->m_maxDistance / this->m_projectileSpeed; - for (auto i = 0u; i < this->m_projectileCount; ++i) - { + for (auto i = 0u; i < this->m_projectileCount; ++i) { auto id = static_cast(ObjectIDManager::Instance()->GenerateObjectID()); id = GeneralUtils::SetBit(id, OBJECT_BIT_CLIENT); @@ -128,25 +118,20 @@ void ProjectileAttackBehavior::Calculate(BehaviorContext* context, RakNet::BitSt skillComponent->RegisterCalculatedProjectile(id, context, branch, this->m_lot, maxTime, position, direction * this->m_projectileSpeed, this->m_trackTarget, this->m_trackRadius); // No idea how to calculate this properly - if (this->m_projectileCount == 2) - { + if (this->m_projectileCount == 2) { angle += angleDelta; - } - else if (this->m_projectileCount == 3) - { + } else if (this->m_projectileCount == 3) { angle += angleStep; } } } -void ProjectileAttackBehavior::Load() -{ +void ProjectileAttackBehavior::Load() { this->m_lot = GetInt("LOT_ID"); this->m_projectileCount = GetInt("spread_count"); - if (this->m_projectileCount == 0) - { + if (this->m_projectileCount == 0) { this->m_projectileCount = 1; } diff --git a/dGame/dBehaviors/ProjectileAttackBehavior.h b/dGame/dBehaviors/ProjectileAttackBehavior.h index 9d40e97c..0003c2dc 100644 --- a/dGame/dBehaviors/ProjectileAttackBehavior.h +++ b/dGame/dBehaviors/ProjectileAttackBehavior.h @@ -27,8 +27,7 @@ public: * Inherited */ - explicit ProjectileAttackBehavior(const uint32_t behavior_id) : Behavior(behavior_id) - { + explicit ProjectileAttackBehavior(const uint32_t behavior_id) : Behavior(behavior_id) { } void Handle(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) override; diff --git a/dGame/dBehaviors/PullToPointBehavior.cpp b/dGame/dBehaviors/PullToPointBehavior.cpp index 8b87cbfb..2cdbaa7e 100644 --- a/dGame/dBehaviors/PullToPointBehavior.cpp +++ b/dGame/dBehaviors/PullToPointBehavior.cpp @@ -5,21 +5,18 @@ #include "EntityManager.h" #include "MovementAIComponent.h" -void PullToPointBehavior::Handle(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) -{ +void PullToPointBehavior::Handle(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) { auto* entity = EntityManager::Instance()->GetEntity(context->originator); - + auto* target = EntityManager::Instance()->GetEntity(branch.target); - if (entity == nullptr || target == nullptr) - { + if (entity == nullptr || target == nullptr) { return; } - + auto* movement = target->GetComponent(); - if (movement == nullptr) - { + if (movement == nullptr) { return; } @@ -28,11 +25,9 @@ void PullToPointBehavior::Handle(BehaviorContext* context, RakNet::BitStream* bi movement->PullToPoint(position); } -void PullToPointBehavior::Calculate(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) -{ +void PullToPointBehavior::Calculate(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) { Handle(context, bitStream, branch); } -void PullToPointBehavior::Load() -{ +void PullToPointBehavior::Load() { } diff --git a/dGame/dBehaviors/PullToPointBehavior.h b/dGame/dBehaviors/PullToPointBehavior.h index ecd50bab..09e4310c 100644 --- a/dGame/dBehaviors/PullToPointBehavior.h +++ b/dGame/dBehaviors/PullToPointBehavior.h @@ -9,8 +9,7 @@ public: * Inherited */ - explicit PullToPointBehavior(const uint32_t behaviorId) : Behavior(behaviorId) - { + explicit PullToPointBehavior(const uint32_t behaviorId) : Behavior(behaviorId) { } void Handle(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) override; diff --git a/dGame/dBehaviors/RepairBehavior.cpp b/dGame/dBehaviors/RepairBehavior.cpp index c3e8a4d3..470fb4d4 100644 --- a/dGame/dBehaviors/RepairBehavior.cpp +++ b/dGame/dBehaviors/RepairBehavior.cpp @@ -6,12 +6,10 @@ #include "dLogger.h" #include "Game.h" -void RepairBehavior::Handle(BehaviorContext* context, RakNet::BitStream* bit_stream, const BehaviorBranchContext branch) -{ +void RepairBehavior::Handle(BehaviorContext* context, RakNet::BitStream* bit_stream, const BehaviorBranchContext branch) { auto* entity = EntityManager::Instance()->GetEntity(branch.target); - if (entity == nullptr) - { + if (entity == nullptr) { Game::logger->Log("RepairBehavior", "Failed to find entity for (%llu)!", branch.target); return; @@ -19,8 +17,7 @@ void RepairBehavior::Handle(BehaviorContext* context, RakNet::BitStream* bit_str auto* destroyable = static_cast(entity->GetComponent(COMPONENT_TYPE_DESTROYABLE)); - if (destroyable == nullptr) - { + if (destroyable == nullptr) { Game::logger->Log("RepairBehavior", "Failed to find destroyable component for %(llu)!", branch.target); return; @@ -29,12 +26,10 @@ void RepairBehavior::Handle(BehaviorContext* context, RakNet::BitStream* bit_str destroyable->Repair(this->m_armor); } -void RepairBehavior::Calculate(BehaviorContext* context, RakNet::BitStream* bit_stream, const BehaviorBranchContext branch) -{ +void RepairBehavior::Calculate(BehaviorContext* context, RakNet::BitStream* bit_stream, const BehaviorBranchContext branch) { Handle(context, bit_stream, branch); } -void RepairBehavior::Load() -{ +void RepairBehavior::Load() { this->m_armor = GetInt("armor"); } diff --git a/dGame/dBehaviors/RepairBehavior.h b/dGame/dBehaviors/RepairBehavior.h index 46ca6bfb..38f97b05 100644 --- a/dGame/dBehaviors/RepairBehavior.h +++ b/dGame/dBehaviors/RepairBehavior.h @@ -10,8 +10,7 @@ public: * Inherited */ - explicit RepairBehavior(const uint32_t behavior_id) : Behavior(behavior_id) - { + explicit RepairBehavior(const uint32_t behavior_id) : Behavior(behavior_id) { } void Handle(BehaviorContext* context, RakNet::BitStream* bit_stream, BehaviorBranchContext branch) override; diff --git a/dGame/dBehaviors/SkillCastFailedBehavior.cpp b/dGame/dBehaviors/SkillCastFailedBehavior.cpp index ef8ba3e1..7a0166f9 100644 --- a/dGame/dBehaviors/SkillCastFailedBehavior.cpp +++ b/dGame/dBehaviors/SkillCastFailedBehavior.cpp @@ -3,16 +3,13 @@ #include "BehaviorContext.h" #include "BehaviorBranchContext.h" -void SkillCastFailedBehavior::Handle(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) -{ +void SkillCastFailedBehavior::Handle(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) { context->failed = true; } -void SkillCastFailedBehavior::Calculate(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) -{ +void SkillCastFailedBehavior::Calculate(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) { context->failed = true; } -void SkillCastFailedBehavior::Load() -{ +void SkillCastFailedBehavior::Load() { } diff --git a/dGame/dBehaviors/SkillCastFailedBehavior.h b/dGame/dBehaviors/SkillCastFailedBehavior.h index cdd2adb4..1f414f90 100644 --- a/dGame/dBehaviors/SkillCastFailedBehavior.h +++ b/dGame/dBehaviors/SkillCastFailedBehavior.h @@ -8,12 +8,11 @@ public: /* * Inherited */ - explicit SkillCastFailedBehavior(const uint32_t behaviorId) : Behavior(behaviorId) - { + explicit SkillCastFailedBehavior(const uint32_t behaviorId) : Behavior(behaviorId) { } void Handle(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) override; - + void Calculate(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) override; void Load() override; diff --git a/dGame/dBehaviors/SkillEventBehavior.cpp b/dGame/dBehaviors/SkillEventBehavior.cpp index 35a9aa6f..837d70c9 100644 --- a/dGame/dBehaviors/SkillEventBehavior.cpp +++ b/dGame/dBehaviors/SkillEventBehavior.cpp @@ -4,25 +4,25 @@ #include "EntityManager.h" #include "CppScripts.h" -void SkillEventBehavior::Handle(BehaviorContext *context, RakNet::BitStream *bitStream, BehaviorBranchContext branch) { - auto* target = EntityManager::Instance()->GetEntity(branch.target); - auto* caster = EntityManager::Instance()->GetEntity(context->originator); +void SkillEventBehavior::Handle(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) { + auto* target = EntityManager::Instance()->GetEntity(branch.target); + auto* caster = EntityManager::Instance()->GetEntity(context->originator); - if (caster != nullptr && target != nullptr && this->m_effectHandle != nullptr && !this->m_effectHandle->empty()) { - for (CppScripts::Script* script : CppScripts::GetEntityScripts(target)) { - script->OnSkillEventFired(target, caster, *this->m_effectHandle); - } - } + if (caster != nullptr && target != nullptr && this->m_effectHandle != nullptr && !this->m_effectHandle->empty()) { + for (CppScripts::Script* script : CppScripts::GetEntityScripts(target)) { + script->OnSkillEventFired(target, caster, *this->m_effectHandle); + } + } } void -SkillEventBehavior::Calculate(BehaviorContext *context, RakNet::BitStream *bitStream, BehaviorBranchContext branch) { - auto* target = EntityManager::Instance()->GetEntity(branch.target); - auto* caster = EntityManager::Instance()->GetEntity(context->originator); +SkillEventBehavior::Calculate(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) { + auto* target = EntityManager::Instance()->GetEntity(branch.target); + auto* caster = EntityManager::Instance()->GetEntity(context->originator); - if (caster != nullptr && target != nullptr && this->m_effectHandle != nullptr && !this->m_effectHandle->empty()) { - for (CppScripts::Script* script : CppScripts::GetEntityScripts(target)) { - script->OnSkillEventFired(target, caster, *this->m_effectHandle); - } - } + if (caster != nullptr && target != nullptr && this->m_effectHandle != nullptr && !this->m_effectHandle->empty()) { + for (CppScripts::Script* script : CppScripts::GetEntityScripts(target)) { + script->OnSkillEventFired(target, caster, *this->m_effectHandle); + } + } } diff --git a/dGame/dBehaviors/SkillEventBehavior.h b/dGame/dBehaviors/SkillEventBehavior.h index 720cd440..540f6d4a 100644 --- a/dGame/dBehaviors/SkillEventBehavior.h +++ b/dGame/dBehaviors/SkillEventBehavior.h @@ -6,10 +6,10 @@ */ class SkillEventBehavior final : public Behavior { public: - explicit SkillEventBehavior(const uint32_t behaviorID) : Behavior(behaviorID) { - } + explicit SkillEventBehavior(const uint32_t behaviorID) : Behavior(behaviorID) { + } - void Handle(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) override; - void Calculate(BehaviorContext *context, RakNet::BitStream *bitStream, BehaviorBranchContext branch) override; + void Handle(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) override; + void Calculate(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) override; }; diff --git a/dGame/dBehaviors/SpawnBehavior.cpp b/dGame/dBehaviors/SpawnBehavior.cpp index 6d0e7490..592a8a22 100644 --- a/dGame/dBehaviors/SpawnBehavior.cpp +++ b/dGame/dBehaviors/SpawnBehavior.cpp @@ -8,23 +8,19 @@ #include "DestroyableComponent.h" #include "RebuildComponent.h" -void SpawnBehavior::Handle(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) -{ +void SpawnBehavior::Handle(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) { auto* origin = EntityManager::Instance()->GetEntity(context->originator); - if (origin == nullptr) - { + if (origin == nullptr) { Game::logger->Log("SpawnBehavior", "Failed to find self entity (%llu)!", context->originator); return; } - if (branch.isProjectile) - { + if (branch.isProjectile) { auto* target = EntityManager::Instance()->GetEntity(branch.target); - if (target != nullptr) - { + if (target != nullptr) { origin = target; } } @@ -42,11 +38,10 @@ void SpawnBehavior::Handle(BehaviorContext* context, RakNet::BitStream* bitStrea auto* entity = EntityManager::Instance()->CreateEntity( info, nullptr, - EntityManager::Instance()->GetEntity(context->originator) + EntityManager::Instance()->GetEntity(context->originator) ); - if (entity == nullptr) - { + if (entity == nullptr) { Game::logger->Log("SpawnBehavior", "Failed to spawn entity (%i)!", this->m_lot); return; @@ -57,39 +52,33 @@ void SpawnBehavior::Handle(BehaviorContext* context, RakNet::BitStream* bitStrea // Unset the flag to reposition the player, this makes it harder to glitch out of the map auto* rebuildComponent = entity->GetComponent(); - if (rebuildComponent != nullptr) - { + if (rebuildComponent != nullptr) { rebuildComponent->SetRepositionPlayer(false); } EntityManager::Instance()->ConstructEntity(entity); - if (branch.duration > 0) - { + if (branch.duration > 0) { context->RegisterTimerBehavior(this, branch, entity->GetObjectID()); } - if (branch.start != 0) - { + if (branch.start != 0) { context->RegisterEndBehavior(this, branch, entity->GetObjectID()); } - entity->AddCallbackTimer(60, [entity] () { + entity->AddCallbackTimer(60, [entity]() { entity->Smash(); - }); + }); } -void SpawnBehavior::Calculate(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) -{ +void SpawnBehavior::Calculate(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) { Handle(context, bitStream, branch); } -void SpawnBehavior::Timer(BehaviorContext* context, const BehaviorBranchContext branch, const LWOOBJID second) -{ +void SpawnBehavior::Timer(BehaviorContext* context, const BehaviorBranchContext branch, const LWOOBJID second) { auto* entity = EntityManager::Instance()->GetEntity(second); - if (entity == nullptr) - { + if (entity == nullptr) { Game::logger->Log("SpawnBehavior", "Failed to find spawned entity (%llu)!", second); return; @@ -97,8 +86,7 @@ void SpawnBehavior::Timer(BehaviorContext* context, const BehaviorBranchContext auto* destroyable = static_cast(entity->GetComponent(COMPONENT_TYPE_DESTROYABLE)); - if (destroyable == nullptr) - { + if (destroyable == nullptr) { entity->Smash(context->originator); return; @@ -107,14 +95,12 @@ void SpawnBehavior::Timer(BehaviorContext* context, const BehaviorBranchContext destroyable->Smash(second); } -void SpawnBehavior::End(BehaviorContext* context, const BehaviorBranchContext branch, const LWOOBJID second) -{ +void SpawnBehavior::End(BehaviorContext* context, const BehaviorBranchContext branch, const LWOOBJID second) { Timer(context, branch, second); } -void SpawnBehavior::Load() -{ +void SpawnBehavior::Load() { this->m_lot = GetInt("LOT_ID"); this->m_Distance = GetFloat("distance"); } diff --git a/dGame/dBehaviors/SpawnBehavior.h b/dGame/dBehaviors/SpawnBehavior.h index a4adbcad..0617f781 100644 --- a/dGame/dBehaviors/SpawnBehavior.h +++ b/dGame/dBehaviors/SpawnBehavior.h @@ -6,21 +6,20 @@ class SpawnBehavior final : public Behavior public: LOT m_lot; float m_Distance; - + /* * Inherited */ - explicit SpawnBehavior(const uint32_t behaviorId) : Behavior(behaviorId) - { + explicit SpawnBehavior(const uint32_t behaviorId) : Behavior(behaviorId) { } void Handle(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) override; void Calculate(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) override; - + void Timer(BehaviorContext* context, BehaviorBranchContext branch, LWOOBJID second) override; void End(BehaviorContext* context, BehaviorBranchContext branch, LWOOBJID second) override; - + void Load() override; -}; \ No newline at end of file +}; diff --git a/dGame/dBehaviors/SpawnQuickbuildBehavior.cpp b/dGame/dBehaviors/SpawnQuickbuildBehavior.cpp index 3072d53c..2b78f12e 100644 --- a/dGame/dBehaviors/SpawnQuickbuildBehavior.cpp +++ b/dGame/dBehaviors/SpawnQuickbuildBehavior.cpp @@ -3,11 +3,8 @@ #include "BehaviorBranchContext.h" #include "BehaviorContext.h" -void SpawnQuickbuildBehavior::Handle(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) -{ +void SpawnQuickbuildBehavior::Handle(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) { } -void SpawnQuickbuildBehavior::Load() -{ +void SpawnQuickbuildBehavior::Load() { } - \ No newline at end of file diff --git a/dGame/dBehaviors/SpawnQuickbuildBehavior.h b/dGame/dBehaviors/SpawnQuickbuildBehavior.h index 2172d25e..d1ed2e53 100644 --- a/dGame/dBehaviors/SpawnQuickbuildBehavior.h +++ b/dGame/dBehaviors/SpawnQuickbuildBehavior.h @@ -8,8 +8,7 @@ public: /* * Inherited */ - explicit SpawnQuickbuildBehavior(const uint32_t behaviorId) : Behavior(behaviorId) - { + explicit SpawnQuickbuildBehavior(const uint32_t behaviorId) : Behavior(behaviorId) { } void Handle(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) override; diff --git a/dGame/dBehaviors/SpeedBehavior.cpp b/dGame/dBehaviors/SpeedBehavior.cpp index 73bc9029..c7855557 100644 --- a/dGame/dBehaviors/SpeedBehavior.cpp +++ b/dGame/dBehaviors/SpeedBehavior.cpp @@ -6,101 +6,86 @@ #include "dLogger.h" -void SpeedBehavior::Handle(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) -{ - if (m_AffectsCaster) - { - branch.target = context->caster; - } +void SpeedBehavior::Handle(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) { + if (m_AffectsCaster) { + branch.target = context->caster; + } auto* target = EntityManager::Instance()->GetEntity(branch.target); - if (target == nullptr) - { - return; - } + if (target == nullptr) { + return; + } - auto* controllablePhysicsComponent = target->GetComponent(); + auto* controllablePhysicsComponent = target->GetComponent(); - if (controllablePhysicsComponent == nullptr) - { - return; - } + if (controllablePhysicsComponent == nullptr) { + return; + } - const auto current = controllablePhysicsComponent->GetSpeedMultiplier(); + const auto current = controllablePhysicsComponent->GetSpeedMultiplier(); - controllablePhysicsComponent->SetSpeedMultiplier(current + ((m_RunSpeed - 500.0f) / 500.0f)); + controllablePhysicsComponent->SetSpeedMultiplier(current + ((m_RunSpeed - 500.0f) / 500.0f)); - EntityManager::Instance()->SerializeEntity(target); + EntityManager::Instance()->SerializeEntity(target); - if (branch.duration > 0.0f) - { - context->RegisterTimerBehavior(this, branch); - } - else if (branch.start > 0) - { - controllablePhysicsComponent->SetIgnoreMultipliers(true); + if (branch.duration > 0.0f) { + context->RegisterTimerBehavior(this, branch); + } else if (branch.start > 0) { + controllablePhysicsComponent->SetIgnoreMultipliers(true); - context->RegisterEndBehavior(this, branch); - } + context->RegisterEndBehavior(this, branch); + } } -void SpeedBehavior::Timer(BehaviorContext* context, BehaviorBranchContext branch, LWOOBJID second) -{ - auto* target = EntityManager::Instance()->GetEntity(branch.target); +void SpeedBehavior::Timer(BehaviorContext* context, BehaviorBranchContext branch, LWOOBJID second) { + auto* target = EntityManager::Instance()->GetEntity(branch.target); - if (target == nullptr) - { - return; - } + if (target == nullptr) { + return; + } - auto* controllablePhysicsComponent = target->GetComponent(); + auto* controllablePhysicsComponent = target->GetComponent(); - if (controllablePhysicsComponent == nullptr) - { - return; - } + if (controllablePhysicsComponent == nullptr) { + return; + } - const auto current = controllablePhysicsComponent->GetSpeedMultiplier(); + const auto current = controllablePhysicsComponent->GetSpeedMultiplier(); - controllablePhysicsComponent->SetSpeedMultiplier(current - ((m_RunSpeed - 500.0f) / 500.0f)); + controllablePhysicsComponent->SetSpeedMultiplier(current - ((m_RunSpeed - 500.0f) / 500.0f)); - EntityManager::Instance()->SerializeEntity(target); + EntityManager::Instance()->SerializeEntity(target); } -void SpeedBehavior::End(BehaviorContext* context, BehaviorBranchContext branch, LWOOBJID second) -{ - auto* target = EntityManager::Instance()->GetEntity(branch.target); +void SpeedBehavior::End(BehaviorContext* context, BehaviorBranchContext branch, LWOOBJID second) { + auto* target = EntityManager::Instance()->GetEntity(branch.target); - if (target == nullptr) - { - return; - } + if (target == nullptr) { + return; + } - auto* controllablePhysicsComponent = target->GetComponent(); + auto* controllablePhysicsComponent = target->GetComponent(); - if (controllablePhysicsComponent == nullptr) - { - return; - } + if (controllablePhysicsComponent == nullptr) { + return; + } - const auto current = controllablePhysicsComponent->GetSpeedMultiplier(); + const auto current = controllablePhysicsComponent->GetSpeedMultiplier(); - controllablePhysicsComponent->SetIgnoreMultipliers(false); + controllablePhysicsComponent->SetIgnoreMultipliers(false); - controllablePhysicsComponent->SetSpeedMultiplier(current - ((m_RunSpeed - 500.0f) / 500.0f)); + controllablePhysicsComponent->SetSpeedMultiplier(current - ((m_RunSpeed - 500.0f) / 500.0f)); - EntityManager::Instance()->SerializeEntity(target); + EntityManager::Instance()->SerializeEntity(target); } -void SpeedBehavior::Load() -{ - m_RunSpeed = GetFloat("run_speed"); +void SpeedBehavior::Load() { + m_RunSpeed = GetFloat("run_speed"); - if (m_RunSpeed < 500.0f) - { - m_RunSpeed = 500.0f; - } + if (m_RunSpeed < 500.0f) { + m_RunSpeed = 500.0f; + } - m_AffectsCaster = GetBoolean("affects_caster"); + m_AffectsCaster = GetBoolean("affects_caster"); } diff --git a/dGame/dBehaviors/SpeedBehavior.h b/dGame/dBehaviors/SpeedBehavior.h index 9b8aa688..04c0090f 100644 --- a/dGame/dBehaviors/SpeedBehavior.h +++ b/dGame/dBehaviors/SpeedBehavior.h @@ -8,20 +8,19 @@ public: /* * Inherited */ - explicit SpeedBehavior(const uint32_t behaviorId) : Behavior(behaviorId) - { + explicit SpeedBehavior(const uint32_t behaviorId) : Behavior(behaviorId) { } void Handle(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) override; - - void Timer(BehaviorContext* context, BehaviorBranchContext branch, LWOOBJID second) override; - void End(BehaviorContext* context, BehaviorBranchContext branch, LWOOBJID second) override; + void Timer(BehaviorContext* context, BehaviorBranchContext branch, LWOOBJID second) override; + + void End(BehaviorContext* context, BehaviorBranchContext branch, LWOOBJID second) override; void Load() override; private: - float m_RunSpeed; + float m_RunSpeed; - bool m_AffectsCaster; + bool m_AffectsCaster; }; diff --git a/dGame/dBehaviors/StartBehavior.cpp b/dGame/dBehaviors/StartBehavior.cpp index af03c333..436984d1 100644 --- a/dGame/dBehaviors/StartBehavior.cpp +++ b/dGame/dBehaviors/StartBehavior.cpp @@ -1,21 +1,18 @@ #include "StartBehavior.h" #include "BehaviorBranchContext.h" -void StartBehavior::Handle(BehaviorContext* context, RakNet::BitStream* bit_stream, BehaviorBranchContext branch) -{ +void StartBehavior::Handle(BehaviorContext* context, RakNet::BitStream* bit_stream, BehaviorBranchContext branch) { branch.start = this->m_behaviorId; - + this->m_action->Handle(context, bit_stream, branch); } -void StartBehavior::Calculate(BehaviorContext* context, RakNet::BitStream* bit_stream, BehaviorBranchContext branch) -{ +void StartBehavior::Calculate(BehaviorContext* context, RakNet::BitStream* bit_stream, BehaviorBranchContext branch) { branch.start = this->m_behaviorId; this->m_action->Calculate(context, bit_stream, branch); } -void StartBehavior::Load() -{ +void StartBehavior::Load() { this->m_action = GetAction("action"); } diff --git a/dGame/dBehaviors/StartBehavior.h b/dGame/dBehaviors/StartBehavior.h index d93526f6..9ee461fc 100644 --- a/dGame/dBehaviors/StartBehavior.h +++ b/dGame/dBehaviors/StartBehavior.h @@ -5,13 +5,12 @@ class StartBehavior final : public Behavior { public: Behavior* m_action; - + /* * Inherited */ - explicit StartBehavior(const uint32_t behaviorID) : Behavior(behaviorID) - { + explicit StartBehavior(const uint32_t behaviorID) : Behavior(behaviorID) { } void Handle(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) override; diff --git a/dGame/dBehaviors/StunBehavior.cpp b/dGame/dBehaviors/StunBehavior.cpp index 5c0ea310..3cbfe9c4 100644 --- a/dGame/dBehaviors/StunBehavior.cpp +++ b/dGame/dBehaviors/StunBehavior.cpp @@ -9,8 +9,7 @@ #include "DestroyableComponent.h" -void StunBehavior::Handle(BehaviorContext* context, RakNet::BitStream* bitStream, const BehaviorBranchContext branch) -{ +void StunBehavior::Handle(BehaviorContext* context, RakNet::BitStream* bitStream, const BehaviorBranchContext branch) { if (this->m_stunCaster || branch.target == context->originator) { return; } @@ -20,8 +19,7 @@ void StunBehavior::Handle(BehaviorContext* context, RakNet::BitStream* bitStream auto* target = EntityManager::Instance()->GetEntity(branch.target); - if (target == nullptr) - { + if (target == nullptr) { Game::logger->Log("StunBehavior", "Failed to find target (%llu)!", branch.target); return; @@ -33,22 +31,18 @@ void StunBehavior::Handle(BehaviorContext* context, RakNet::BitStream* bitStream auto* combatAiComponent = static_cast(target->GetComponent(COMPONENT_TYPE_BASE_COMBAT_AI)); - if (combatAiComponent == nullptr) - { + if (combatAiComponent == nullptr) { return; } combatAiComponent->Stun(branch.duration); } -void StunBehavior::Calculate(BehaviorContext* context, RakNet::BitStream* bitStream, const BehaviorBranchContext branch) -{ - if (this->m_stunCaster || branch.target == context->originator) - { +void StunBehavior::Calculate(BehaviorContext* context, RakNet::BitStream* bitStream, const BehaviorBranchContext branch) { + if (this->m_stunCaster || branch.target == context->originator) { auto* self = EntityManager::Instance()->GetEntity(context->originator); - if (self == nullptr) - { + if (self == nullptr) { Game::logger->Log("StunBehavior", "Invalid self entity (%llu)!", context->originator); return; @@ -60,8 +54,7 @@ void StunBehavior::Calculate(BehaviorContext* context, RakNet::BitStream* bitStr auto* combatAiComponent = static_cast(self->GetComponent(COMPONENT_TYPE_BASE_COMBAT_AI)); - if (combatAiComponent == nullptr) - { + if (combatAiComponent == nullptr) { return; } @@ -74,20 +67,17 @@ void StunBehavior::Calculate(BehaviorContext* context, RakNet::BitStream* bitStr auto* target = EntityManager::Instance()->GetEntity(branch.target); - if (target != nullptr) - { + if (target != nullptr) { auto* destroyableComponent = target->GetComponent(); - if (destroyableComponent != nullptr) - { + if (destroyableComponent != nullptr) { blocked = destroyableComponent->IsKnockbackImmune(); } } bitStream->Write(blocked); - if (target == nullptr) - { + if (target == nullptr) { Game::logger->Log("StunBehavior", "Failed to find target (%llu)!", branch.target); return; @@ -99,15 +89,13 @@ void StunBehavior::Calculate(BehaviorContext* context, RakNet::BitStream* bitStr auto* combatAiComponent = static_cast(target->GetComponent(COMPONENT_TYPE_BASE_COMBAT_AI)); - if (combatAiComponent == nullptr) - { + if (combatAiComponent == nullptr) { return; } combatAiComponent->Stun(branch.duration); } -void StunBehavior::Load() -{ +void StunBehavior::Load() { this->m_stunCaster = GetBoolean("stun_caster"); } diff --git a/dGame/dBehaviors/StunBehavior.h b/dGame/dBehaviors/StunBehavior.h index 0ec36129..a512528d 100644 --- a/dGame/dBehaviors/StunBehavior.h +++ b/dGame/dBehaviors/StunBehavior.h @@ -9,10 +9,9 @@ public: /* * Inherited */ - explicit StunBehavior(const uint32_t behavior_id) : Behavior(behavior_id) - { + explicit StunBehavior(const uint32_t behavior_id) : Behavior(behavior_id) { } - + void Handle(BehaviorContext* context, RakNet::BitStream* bit_stream, BehaviorBranchContext branch) override; void Calculate(BehaviorContext* context, RakNet::BitStream* bit_stream, BehaviorBranchContext branch) override; diff --git a/dGame/dBehaviors/SwitchBehavior.cpp b/dGame/dBehaviors/SwitchBehavior.cpp index 8af8a334..ff3d7baf 100644 --- a/dGame/dBehaviors/SwitchBehavior.cpp +++ b/dGame/dBehaviors/SwitchBehavior.cpp @@ -6,57 +6,46 @@ #include "BehaviorContext.h" #include "BuffComponent.h" -void SwitchBehavior::Handle(BehaviorContext* context, RakNet::BitStream* bitStream, const BehaviorBranchContext branch) -{ +void SwitchBehavior::Handle(BehaviorContext* context, RakNet::BitStream* bitStream, const BehaviorBranchContext branch) { auto state = true; - if (this->m_imagination > 0 || !this->m_isEnemyFaction) - { + if (this->m_imagination > 0 || !this->m_isEnemyFaction) { bitStream->Read(state); } - auto* entity = EntityManager::Instance()->GetEntity(context->originator); + auto* entity = EntityManager::Instance()->GetEntity(context->originator); - if (entity == nullptr) - { - return; - } - - auto* destroyableComponent = entity->GetComponent(); - - if (destroyableComponent == nullptr) - { + if (entity == nullptr) { return; } - Game::logger->Log("SwitchBehavior", "[%i] State: (%d), imagination: (%i) / (%f)", entity->GetLOT(), state, destroyableComponent->GetImagination(), destroyableComponent->GetMaxImagination()); + auto* destroyableComponent = entity->GetComponent(); - if (state || (entity->GetLOT() == 8092 && destroyableComponent->GetImagination() >= m_imagination)) - { - this->m_actionTrue->Handle(context, bitStream, branch); + if (destroyableComponent == nullptr) { + return; } - else - { + + Game::logger->Log("SwitchBehavior", "[%i] State: (%d), imagination: (%i) / (%f)", entity->GetLOT(), state, destroyableComponent->GetImagination(), destroyableComponent->GetMaxImagination()); + + if (state || (entity->GetLOT() == 8092 && destroyableComponent->GetImagination() >= m_imagination)) { + this->m_actionTrue->Handle(context, bitStream, branch); + } else { this->m_actionFalse->Handle(context, bitStream, branch); } } -void SwitchBehavior::Calculate(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) -{ +void SwitchBehavior::Calculate(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) { auto state = true; - if (this->m_imagination > 0 || !this->m_isEnemyFaction) - { + if (this->m_imagination > 0 || !this->m_isEnemyFaction) { auto* entity = EntityManager::Instance()->GetEntity(branch.target); state = entity != nullptr; - if (state && m_targetHasBuff != 0) - { - auto* buffComponent = entity->GetComponent(); + if (state && m_targetHasBuff != 0) { + auto* buffComponent = entity->GetComponent(); - if (buffComponent != nullptr && !buffComponent->HasBuff(m_targetHasBuff)) - { + if (buffComponent != nullptr && !buffComponent->HasBuff(m_targetHasBuff)) { state = false; } } @@ -64,18 +53,14 @@ void SwitchBehavior::Calculate(BehaviorContext* context, RakNet::BitStream* bitS bitStream->Write(state); } - if (state) - { + if (state) { this->m_actionTrue->Calculate(context, bitStream, branch); - } - else - { + } else { this->m_actionFalse->Calculate(context, bitStream, branch); } } -void SwitchBehavior::Load() -{ +void SwitchBehavior::Load() { this->m_actionTrue = GetAction("action_true"); this->m_actionFalse = GetAction("action_false"); diff --git a/dGame/dBehaviors/SwitchBehavior.h b/dGame/dBehaviors/SwitchBehavior.h index 8dc43e71..675c1a35 100644 --- a/dGame/dBehaviors/SwitchBehavior.h +++ b/dGame/dBehaviors/SwitchBehavior.h @@ -13,13 +13,12 @@ public: bool m_isEnemyFaction; int32_t m_targetHasBuff; - + /* * Inherited */ - explicit SwitchBehavior(const uint32_t behaviorId) : Behavior(behaviorId) - { + explicit SwitchBehavior(const uint32_t behaviorId) : Behavior(behaviorId) { } void Handle(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) override; diff --git a/dGame/dBehaviors/SwitchMultipleBehavior.cpp b/dGame/dBehaviors/SwitchMultipleBehavior.cpp index 93662060..b34b1144 100644 --- a/dGame/dBehaviors/SwitchMultipleBehavior.cpp +++ b/dGame/dBehaviors/SwitchMultipleBehavior.cpp @@ -9,20 +9,19 @@ #include "EntityManager.h" -void SwitchMultipleBehavior::Handle(BehaviorContext* context, RakNet::BitStream* bit_stream, BehaviorBranchContext branch) -{ +void SwitchMultipleBehavior::Handle(BehaviorContext* context, RakNet::BitStream* bit_stream, BehaviorBranchContext branch) { float value; bit_stream->Read(value); - + uint32_t trigger = 0; for (unsigned int i = 0; i < this->m_behaviors.size(); i++) { - + const double data = this->m_behaviors.at(i).first; - + if (value <= data) { - + trigger = i; break; @@ -34,8 +33,7 @@ void SwitchMultipleBehavior::Handle(BehaviorContext* context, RakNet::BitStream* behavior->Handle(context, bit_stream, branch); } -void SwitchMultipleBehavior::Calculate(BehaviorContext* context, RakNet::BitStream* bit_stream, BehaviorBranchContext branch) -{ +void SwitchMultipleBehavior::Calculate(BehaviorContext* context, RakNet::BitStream* bit_stream, BehaviorBranchContext branch) { // TODO } @@ -45,7 +43,7 @@ void SwitchMultipleBehavior::Load() { "(select bP2.value FROM BehaviorParameter bP2 WHERE bP2.behaviorID = ?1 AND bP2.parameterID LIKE 'value %' " "AND replace(bP1.parameterID, 'behavior ', '') = replace(bP2.parameterID, 'value ', '')) as value " "FROM BehaviorParameter bP1 WHERE bP1.behaviorID = ?1 AND bP1.parameterID LIKE 'behavior %';"); - query.bind(1, (int) this->m_behaviorId); + query.bind(1, (int)this->m_behaviorId); auto result = query.execQuery(); @@ -57,7 +55,7 @@ void SwitchMultipleBehavior::Load() { auto value = result.getFloatField(2); this->m_behaviors.emplace_back(value, behavior); - + result.nextRow(); } } diff --git a/dGame/dBehaviors/SwitchMultipleBehavior.h b/dGame/dBehaviors/SwitchMultipleBehavior.h index c25049ae..c60fcd6d 100644 --- a/dGame/dBehaviors/SwitchMultipleBehavior.h +++ b/dGame/dBehaviors/SwitchMultipleBehavior.h @@ -7,13 +7,12 @@ class SwitchMultipleBehavior final : public Behavior { public: std::vector> m_behaviors; - + /* * Inherited */ - explicit SwitchMultipleBehavior(const uint32_t behavior_id) : Behavior(behavior_id) - { + explicit SwitchMultipleBehavior(const uint32_t behavior_id) : Behavior(behavior_id) { } void Handle(BehaviorContext* context, RakNet::BitStream* bit_stream, BehaviorBranchContext branch) override; diff --git a/dGame/dBehaviors/TacArcBehavior.cpp b/dGame/dBehaviors/TacArcBehavior.cpp index 2d012305..21885624 100644 --- a/dGame/dBehaviors/TacArcBehavior.cpp +++ b/dGame/dBehaviors/TacArcBehavior.cpp @@ -11,10 +11,8 @@ #include -void TacArcBehavior::Handle(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) -{ - if (this->m_targetEnemy && this->m_usePickedTarget && branch.target > 0) - { +void TacArcBehavior::Handle(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) { + if (this->m_targetEnemy && this->m_usePickedTarget && branch.target > 0) { this->m_action->Handle(context, bitStream, branch); return; @@ -24,35 +22,30 @@ void TacArcBehavior::Handle(BehaviorContext* context, RakNet::BitStream* bitStre bitStream->Read(hit); - if (this->m_checkEnv) - { + if (this->m_checkEnv) { bool blocked = false; bitStream->Read(blocked); - if (blocked) - { + if (blocked) { this->m_blockedAction->Handle(context, bitStream, branch); return; } } - if (hit) - { + if (hit) { uint32_t count = 0; bitStream->Read(count); - if (count > m_maxTargets && m_maxTargets > 0) - { + if (count > m_maxTargets && m_maxTargets > 0) { count = m_maxTargets; } std::vector targets; - for (auto i = 0u; i < count; ++i) - { + for (auto i = 0u; i < count; ++i) { LWOOBJID id; bitStream->Read(id); @@ -60,46 +53,41 @@ void TacArcBehavior::Handle(BehaviorContext* context, RakNet::BitStream* bitStre targets.push_back(id); } - for (auto target : targets) - { + for (auto target : targets) { branch.target = target; this->m_action->Handle(context, bitStream, branch); } - } - else - { + } else { this->m_missAction->Handle(context, bitStream, branch); } } -void TacArcBehavior::Calculate(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) -{ - auto* self = EntityManager::Instance()->GetEntity(context->originator); - if (self == nullptr) { - Game::logger->Log("TacArcBehavior", "Invalid self for (%llu)!", context->originator); - return; - } +void TacArcBehavior::Calculate(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) { + auto* self = EntityManager::Instance()->GetEntity(context->originator); + if (self == nullptr) { + Game::logger->Log("TacArcBehavior", "Invalid self for (%llu)!", context->originator); + return; + } - const auto* destroyableComponent = self->GetComponent(); + const auto* destroyableComponent = self->GetComponent(); - if ((this->m_usePickedTarget || context->clientInitalized) && branch.target > 0) { - const auto* target = EntityManager::Instance()->GetEntity(branch.target); + if ((this->m_usePickedTarget || context->clientInitalized) && branch.target > 0) { + const auto* target = EntityManager::Instance()->GetEntity(branch.target); - if (target == nullptr) - { + if (target == nullptr) { return; } - // If the game is specific about who to target, check that - if (destroyableComponent == nullptr || ((!m_targetFriend && !m_targetEnemy - || m_targetFriend && destroyableComponent->IsFriend(target) - || m_targetEnemy && destroyableComponent->IsEnemy(target)))) { - this->m_action->Calculate(context, bitStream, branch); - } + // If the game is specific about who to target, check that + if (destroyableComponent == nullptr || ((!m_targetFriend && !m_targetEnemy + || m_targetFriend && destroyableComponent->IsFriend(target) + || m_targetEnemy && destroyableComponent->IsEnemy(target)))) { + this->m_action->Calculate(context, bitStream, branch); + } - return; - } + return; + } auto* combatAi = self->GetComponent(); @@ -111,46 +99,40 @@ void TacArcBehavior::Calculate(BehaviorContext* context, RakNet::BitStream* bitS std::vector validTargets; - if (combatAi != nullptr) - { - if (combatAi->GetTarget() != LWOOBJID_EMPTY) - { + if (combatAi != nullptr) { + if (combatAi->GetTarget() != LWOOBJID_EMPTY) { validTargets.push_back(combatAi->GetTarget()); } } // Find all valid targets, based on whether we target enemies or friends for (const auto& contextTarget : context->GetValidTargets()) { - if (destroyableComponent != nullptr) { - const auto* targetEntity = EntityManager::Instance()->GetEntity(contextTarget); + if (destroyableComponent != nullptr) { + const auto* targetEntity = EntityManager::Instance()->GetEntity(contextTarget); - if (m_targetEnemy && destroyableComponent->IsEnemy(targetEntity) - || m_targetFriend && destroyableComponent->IsFriend(targetEntity)) { - validTargets.push_back(contextTarget); - } - } else { - validTargets.push_back(contextTarget); - } + if (m_targetEnemy && destroyableComponent->IsEnemy(targetEntity) + || m_targetFriend && destroyableComponent->IsFriend(targetEntity)) { + validTargets.push_back(contextTarget); + } + } else { + validTargets.push_back(contextTarget); + } } - for (auto validTarget : validTargets) - { - if (targets.size() >= this->m_maxTargets) - { + for (auto validTarget : validTargets) { + if (targets.size() >= this->m_maxTargets) { break; } auto* entity = EntityManager::Instance()->GetEntity(validTarget); - if (entity == nullptr) - { + if (entity == nullptr) { Game::logger->Log("TacArcBehavior", "Invalid target (%llu) for (%llu)!", validTarget, context->originator); continue; } - if (std::find(targets.begin(), targets.end(), entity) != targets.end()) - { + if (std::find(targets.begin(), targets.end(), entity) != targets.end()) { continue; } @@ -174,12 +156,10 @@ void TacArcBehavior::Calculate(BehaviorContext* context, RakNet::BitStream* bitS const auto distance = Vector3::Distance(reference, otherPosition); - if (m_method == 2) - { + if (m_method == 2) { NiPoint3 rayPoint = casterPosition + forward * distance; - if (m_farWidth > 0 && Vector3::DistanceSquared(rayPoint, otherPosition) > this->m_farWidth * this->m_farWidth) - { + if (m_farWidth > 0 && Vector3::DistanceSquared(rayPoint, otherPosition) > this->m_farWidth * this->m_farWidth) { continue; } } @@ -188,35 +168,30 @@ void TacArcBehavior::Calculate(BehaviorContext* context, RakNet::BitStream* bitS const float degreeAngle = std::abs(Vector3::Angle(forward, normalized) * (180 / 3.14) - 180); - if (distance >= this->m_minDistance && this->m_maxDistance >= distance && degreeAngle <= 2 * this->m_angle) - { + if (distance >= this->m_minDistance && this->m_maxDistance >= distance && degreeAngle <= 2 * this->m_angle) { targets.push_back(entity); } } - std::sort(targets.begin(), targets.end(), [reference](Entity* a, Entity* b) - { + std::sort(targets.begin(), targets.end(), [reference](Entity* a, Entity* b) { const auto aDistance = Vector3::DistanceSquared(reference, a->GetPosition()); const auto bDistance = Vector3::DistanceSquared(reference, b->GetPosition()); return aDistance > bDistance; - }); + }); const auto hit = !targets.empty(); bitStream->Write(hit); - if (this->m_checkEnv) - { + if (this->m_checkEnv) { const auto blocked = false; // TODO bitStream->Write(blocked); } - if (hit) - { - if (combatAi != nullptr) - { + if (hit) { + if (combatAi != nullptr) { combatAi->LookAt(targets[0]->GetPosition()); } @@ -226,26 +201,21 @@ void TacArcBehavior::Calculate(BehaviorContext* context, RakNet::BitStream* bitS bitStream->Write(count); - for (auto* target : targets) - { + for (auto* target : targets) { bitStream->Write(target->GetObjectID()); } - for (auto* target : targets) - { + for (auto* target : targets) { branch.target = target->GetObjectID(); this->m_action->Calculate(context, bitStream, branch); } - } - else - { + } else { this->m_missAction->Calculate(context, bitStream, branch); } } -void TacArcBehavior::Load() -{ +void TacArcBehavior::Load() { this->m_usePickedTarget = GetBoolean("use_picked_target"); this->m_action = GetAction("action"); diff --git a/dGame/dBehaviors/TacArcBehavior.h b/dGame/dBehaviors/TacArcBehavior.h index 774e65a1..211ed6b7 100644 --- a/dGame/dBehaviors/TacArcBehavior.h +++ b/dGame/dBehaviors/TacArcBehavior.h @@ -45,11 +45,10 @@ public: /* * Inherited */ - - explicit TacArcBehavior(const uint32_t behavior_id) : Behavior(behavior_id) - { + + explicit TacArcBehavior(const uint32_t behavior_id) : Behavior(behavior_id) { } - + void Handle(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) override; void Calculate(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) override; diff --git a/dGame/dBehaviors/TargetCasterBehavior.cpp b/dGame/dBehaviors/TargetCasterBehavior.cpp index 41b5e73a..fb76b90d 100644 --- a/dGame/dBehaviors/TargetCasterBehavior.cpp +++ b/dGame/dBehaviors/TargetCasterBehavior.cpp @@ -3,27 +3,23 @@ #include "BehaviorContext.h" -void TargetCasterBehavior::Handle(BehaviorContext* context, RakNet::BitStream* bit_stream, BehaviorBranchContext branch) -{ +void TargetCasterBehavior::Handle(BehaviorContext* context, RakNet::BitStream* bit_stream, BehaviorBranchContext branch) { branch.target = context->caster; this->m_action->Handle(context, bit_stream, branch); } -void TargetCasterBehavior::UnCast(BehaviorContext* context, BehaviorBranchContext branch) -{ +void TargetCasterBehavior::UnCast(BehaviorContext* context, BehaviorBranchContext branch) { this->m_action->UnCast(context, branch); } -void TargetCasterBehavior::Calculate(BehaviorContext* context, RakNet::BitStream* bit_stream, BehaviorBranchContext branch) -{ +void TargetCasterBehavior::Calculate(BehaviorContext* context, RakNet::BitStream* bit_stream, BehaviorBranchContext branch) { branch.target = context->caster; this->m_action->Calculate(context, bit_stream, branch); } -void TargetCasterBehavior::Load() -{ +void TargetCasterBehavior::Load() { this->m_action = GetAction("action"); } diff --git a/dGame/dBehaviors/TargetCasterBehavior.h b/dGame/dBehaviors/TargetCasterBehavior.h index 4054f81d..4f2a0f5f 100644 --- a/dGame/dBehaviors/TargetCasterBehavior.h +++ b/dGame/dBehaviors/TargetCasterBehavior.h @@ -5,18 +5,17 @@ class TargetCasterBehavior final : public Behavior { public: Behavior* m_action; - + /* * Inherited */ - explicit TargetCasterBehavior(const uint32_t behavior_id) : Behavior(behavior_id) - { + explicit TargetCasterBehavior(const uint32_t behavior_id) : Behavior(behavior_id) { } void Handle(BehaviorContext* context, RakNet::BitStream* bit_stream, BehaviorBranchContext branch) override; - void UnCast(BehaviorContext* context, BehaviorBranchContext branch) override; + void UnCast(BehaviorContext* context, BehaviorBranchContext branch) override; void Calculate(BehaviorContext* context, RakNet::BitStream* bit_stream, BehaviorBranchContext branch) override; diff --git a/dGame/dBehaviors/TauntBehavior.cpp b/dGame/dBehaviors/TauntBehavior.cpp index 8ccc3abc..7ed3b897 100644 --- a/dGame/dBehaviors/TauntBehavior.cpp +++ b/dGame/dBehaviors/TauntBehavior.cpp @@ -6,12 +6,10 @@ #include "dLogger.h" -void TauntBehavior::Handle(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) -{ +void TauntBehavior::Handle(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) { auto* target = EntityManager::Instance()->GetEntity(branch.target); - if (target == nullptr) - { + if (target == nullptr) { Game::logger->Log("TauntBehavior", "Failed to find target (%llu)!", branch.target); return; @@ -19,18 +17,15 @@ void TauntBehavior::Handle(BehaviorContext* context, RakNet::BitStream* bitStrea auto* combatComponent = target->GetComponent(); - if (combatComponent != nullptr) - { + if (combatComponent != nullptr) { combatComponent->Taunt(context->originator, m_threatToAdd); } } -void TauntBehavior::Calculate(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) -{ +void TauntBehavior::Calculate(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) { auto* target = EntityManager::Instance()->GetEntity(branch.target); - if (target == nullptr) - { + if (target == nullptr) { Game::logger->Log("TauntBehavior", "Failed to find target (%llu)!", branch.target); return; @@ -38,14 +33,12 @@ void TauntBehavior::Calculate(BehaviorContext* context, RakNet::BitStream* bitSt auto* combatComponent = target->GetComponent(); - if (combatComponent != nullptr) - { + if (combatComponent != nullptr) { combatComponent->Taunt(context->originator, m_threatToAdd); } } -void TauntBehavior::Load() -{ +void TauntBehavior::Load() { this->m_threatToAdd = GetFloat("threat to add"); } diff --git a/dGame/dBehaviors/TauntBehavior.h b/dGame/dBehaviors/TauntBehavior.h index a482d0b5..3ae7db9d 100644 --- a/dGame/dBehaviors/TauntBehavior.h +++ b/dGame/dBehaviors/TauntBehavior.h @@ -6,13 +6,12 @@ class TauntBehavior final : public Behavior { public: float m_threatToAdd; - + /* * Inherited */ - explicit TauntBehavior(const uint32_t behaviorId) : Behavior(behaviorId) - { + explicit TauntBehavior(const uint32_t behaviorId) : Behavior(behaviorId) { } void Handle(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) override; diff --git a/dGame/dBehaviors/VentureVisionBehavior.cpp b/dGame/dBehaviors/VentureVisionBehavior.cpp index 9061deb7..93feb8e9 100644 --- a/dGame/dBehaviors/VentureVisionBehavior.cpp +++ b/dGame/dBehaviors/VentureVisionBehavior.cpp @@ -2,8 +2,8 @@ #include "BehaviorBranchContext.h" #include "CharacterComponent.h" #include "BehaviorContext.h" - -void VentureVisionBehavior::Handle(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch){ + +void VentureVisionBehavior::Handle(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) { const auto targetEntity = EntityManager::Instance()->GetEntity(branch.target); @@ -38,7 +38,7 @@ void VentureVisionBehavior::Timer(BehaviorContext* context, BehaviorBranchContex UnCast(context, branch); } -void VentureVisionBehavior::Load(){ +void VentureVisionBehavior::Load() { this->m_show_pet_digs = GetBoolean("show_pet_digs"); this->m_show_minibosses = GetBoolean("show_minibosses"); diff --git a/dGame/dBehaviors/VentureVisionBehavior.h b/dGame/dBehaviors/VentureVisionBehavior.h index 96b2642b..72758949 100644 --- a/dGame/dBehaviors/VentureVisionBehavior.h +++ b/dGame/dBehaviors/VentureVisionBehavior.h @@ -25,10 +25,9 @@ public: * Inherited */ - explicit VentureVisionBehavior(const uint32_t behaviorId) : Behavior(behaviorId) - { + explicit VentureVisionBehavior(const uint32_t behaviorId) : Behavior(behaviorId) { } - + void Handle(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) override; void UnCast(BehaviorContext* context, BehaviorBranchContext branch) override; diff --git a/dGame/dBehaviors/VerifyBehavior.cpp b/dGame/dBehaviors/VerifyBehavior.cpp index 17ba1001..cbc3c6df 100644 --- a/dGame/dBehaviors/VerifyBehavior.cpp +++ b/dGame/dBehaviors/VerifyBehavior.cpp @@ -7,22 +7,17 @@ #include "dLogger.h" -void VerifyBehavior::Calculate(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) -{ +void VerifyBehavior::Calculate(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) { auto* entity = EntityManager::Instance()->GetEntity(branch.target); auto success = true; - if (entity == nullptr) - { + if (entity == nullptr) { success = false; - } - else if (this->m_rangeCheck) - { + } else if (this->m_rangeCheck) { auto* self = EntityManager::Instance()->GetEntity(context->originator); - if (self == nullptr) - { + if (self == nullptr) { Game::logger->Log("VerifyBehavior", "Invalid self for (%llu)", context->originator); return; @@ -30,38 +25,31 @@ void VerifyBehavior::Calculate(BehaviorContext* context, RakNet::BitStream* bitS const auto distance = Vector3::DistanceSquared(self->GetPosition(), entity->GetPosition()); - if (distance > this->m_range * this->m_range) - { + if (distance > this->m_range * this->m_range) { success = false; } - } - else if (this->m_blockCheck) - { + } else if (this->m_blockCheck) { // TODO } - if (branch.target != LWOOBJID_EMPTY && branch.target != context->originator) - { + if (branch.target != LWOOBJID_EMPTY && branch.target != context->originator) { bitStream->Write(success); - if (success) - { + if (success) { bitStream->Write(1); bitStream->Write0(); bitStream->Write0(); } } - if (!success) - { + if (!success) { branch.target = LWOOBJID_EMPTY; } m_action->Calculate(context, bitStream, branch); } -void VerifyBehavior::Load() -{ +void VerifyBehavior::Load() { this->m_rangeCheck = GetBoolean("check_range"); this->m_blockCheck = GetBoolean("check blocking"); diff --git a/dGame/dBehaviors/VerifyBehavior.h b/dGame/dBehaviors/VerifyBehavior.h index f4f295aa..b38d1953 100644 --- a/dGame/dBehaviors/VerifyBehavior.h +++ b/dGame/dBehaviors/VerifyBehavior.h @@ -16,10 +16,9 @@ public: * Inherited */ - explicit VerifyBehavior(const uint32_t behaviorId) : Behavior(behaviorId) - { + explicit VerifyBehavior(const uint32_t behaviorId) : Behavior(behaviorId) { } - + void Calculate(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) override; void Load() override; diff --git a/dGame/dComponents/BaseCombatAIComponent.cpp b/dGame/dComponents/BaseCombatAIComponent.cpp index 022b3e6c..2ac2cf04 100644 --- a/dGame/dComponents/BaseCombatAIComponent.cpp +++ b/dGame/dComponents/BaseCombatAIComponent.cpp @@ -37,12 +37,11 @@ BaseCombatAIComponent::BaseCombatAIComponent(Entity* parent, const uint32_t id) //Grab the aggro information from BaseCombatAI: auto componentQuery = CDClientDatabase::CreatePreppedStmt( "SELECT aggroRadius, tetherSpeed, pursuitSpeed, softTetherRadius, hardTetherRadius FROM BaseCombatAIComponent WHERE id = ?;"); - componentQuery.bind(1, (int) id); + componentQuery.bind(1, (int)id); auto componentResult = componentQuery.execQuery(); - if (!componentResult.eof()) - { + if (!componentResult.eof()) { if (!componentResult.fieldIsNull(0)) m_AggroRadius = componentResult.getFloatField(0); @@ -75,7 +74,7 @@ BaseCombatAIComponent::BaseCombatAIComponent(Entity* parent, const uint32_t id) */ auto skillQuery = CDClientDatabase::CreatePreppedStmt( "SELECT skillID, cooldown, behaviorID FROM SkillBehavior WHERE skillID IN (SELECT skillID FROM ObjectSkills WHERE objectTemplate = ?);"); - skillQuery.bind(1, (int) parent->GetLOT()); + skillQuery.bind(1, (int)parent->GetLOT()); auto result = skillQuery.execQuery(); @@ -110,11 +109,9 @@ BaseCombatAIComponent::BaseCombatAIComponent(Entity* parent, const uint32_t id) CDPhysicsComponentTable* physicsComponentTable = CDClientManager::Instance()->GetTable("PhysicsComponent"); - if (physicsComponentTable != nullptr) - { + if (physicsComponentTable != nullptr) { auto* info = physicsComponentTable->GetByID(componentID); - if (info != nullptr) - { + if (info != nullptr) { collisionGroup = info->bStatic ? COLLISION_GROUP_NEUTRAL : info->collisionGroup; } } @@ -166,37 +163,32 @@ void BaseCombatAIComponent::Update(const float deltaTime) { if (m_Target != LWOOBJID_EMPTY || (NiPoint3::DistanceSquared( m_StartPosition, m_Parent->GetPosition()) < 20 * 20 && m_TetherTime <= 0) - ) { + ) { GameMessages::SendStopFXEffect(m_Parent, true, "tether"); m_TetherEffectActive = false; } } - if (m_SoftTimer <= 0.0f) - { + if (m_SoftTimer <= 0.0f) { EntityManager::Instance()->SerializeEntity(m_Parent); m_SoftTimer = 5.0f; - } - else - { + } else { m_SoftTimer -= deltaTime; } if (m_Disabled || m_Parent->GetIsDead()) - return; + return; CalculateCombat(deltaTime); // Putting this here for now - if (m_StartPosition == NiPoint3::ZERO) - { + if (m_StartPosition == NiPoint3::ZERO) { m_StartPosition = m_Parent->GetPosition(); } m_MovementAI = m_Parent->GetComponent(); - if (m_MovementAI == nullptr) - { + if (m_MovementAI == nullptr) { return; } @@ -222,7 +214,7 @@ void BaseCombatAIComponent::Update(const float deltaTime) { break; case AiState::aggro: - OnAggro(); + OnAggro(); break; case AiState::tether: @@ -248,8 +240,7 @@ void BaseCombatAIComponent::CalculateCombat(const float deltaTime) { auto* skillComponent = m_Parent->GetComponent(); - if (skillComponent == nullptr) - { + if (skillComponent == nullptr) { return; } @@ -257,8 +248,7 @@ void BaseCombatAIComponent::CalculateCombat(const float deltaTime) { if (m_Disabled) return; - if (m_StunTime > 0.0f) - { + if (m_StunTime > 0.0f) { m_StunTime -= deltaTime; if (m_StunTime > 0.0f) { @@ -278,8 +268,7 @@ void BaseCombatAIComponent::CalculateCombat(const float deltaTime) { if (m_Target != LWOOBJID_EMPTY && newTarget == LWOOBJID_EMPTY) { m_OutOfCombat = true; m_OutOfCombatTime = 1.0f; - } - else if (newTarget != LWOOBJID_EMPTY) { + } else if (newTarget != LWOOBJID_EMPTY) { m_OutOfCombat = false; m_OutOfCombatTime = 0.0f; } @@ -332,8 +321,7 @@ void BaseCombatAIComponent::CalculateCombat(const float deltaTime) { } m_State = AiState::aggro; - } - else { + } else { m_State = AiState::idle; } @@ -359,8 +347,7 @@ void BaseCombatAIComponent::CalculateCombat(const float deltaTime) { return; } - if (m_Target == LWOOBJID_EMPTY) - { + if (m_Target == LWOOBJID_EMPTY) { m_State = AiState::idle; return; @@ -370,13 +357,11 @@ void BaseCombatAIComponent::CalculateCombat(const float deltaTime) { auto* target = GetTargetEntity(); - if (target != nullptr) - { + if (target != nullptr) { LookAt(target->GetPosition()); } - for (auto i = 0; i < m_SkillEntries.size(); ++i) - { + for (auto i = 0; i < m_SkillEntries.size(); ++i) { auto entry = m_SkillEntries.at(i); if (entry.cooldown > 0) { @@ -414,12 +399,10 @@ LWOOBJID BaseCombatAIComponent::FindTarget() { auto* target = GetTargetEntity(); - if (target != nullptr && !m_DirtyThreat) - { + if (target != nullptr && !m_DirtyThreat) { const auto targetPosition = target->GetPosition(); - if (Vector3::DistanceSquared(targetPosition, m_StartPosition) < m_HardTetherRadius * m_HardTetherRadius) - { + if (Vector3::DistanceSquared(targetPosition, m_StartPosition) < m_HardTetherRadius * m_HardTetherRadius) { return m_Target; } @@ -428,8 +411,7 @@ LWOOBJID BaseCombatAIComponent::FindTarget() { auto possibleTargets = GetTargetWithinAggroRange(); - if (possibleTargets.empty() && m_ThreatEntries.empty()) - { + if (possibleTargets.empty() && m_ThreatEntries.empty()) { m_DirtyThreat = false; return LWOOBJID_EMPTY; @@ -438,8 +420,7 @@ LWOOBJID BaseCombatAIComponent::FindTarget() { Entity* optimalTarget = nullptr; float biggestThreat = 0; - for (const auto& entry : possibleTargets) - { + for (const auto& entry : possibleTargets) { auto* entity = EntityManager::Instance()->GetEntity(entry); if (entity == nullptr) { @@ -452,53 +433,43 @@ LWOOBJID BaseCombatAIComponent::FindTarget() { const auto maxDistanceSquared = m_HardTetherRadius * m_HardTetherRadius; - if (Vector3::DistanceSquared(targetPosition, m_StartPosition) > maxDistanceSquared) - { - if (threat > 0) - { + if (Vector3::DistanceSquared(targetPosition, m_StartPosition) > maxDistanceSquared) { + if (threat > 0) { SetThreat(entry, 0); } continue; } - if (threat > biggestThreat) - { + if (threat > biggestThreat) { biggestThreat = threat; optimalTarget = entity; continue; } - const auto proximityThreat = - (Vector3::DistanceSquared(targetPosition, reference) - maxDistanceSquared) / 100; // Proximity threat takes last priority + const auto proximityThreat = -(Vector3::DistanceSquared(targetPosition, reference) - maxDistanceSquared) / 100; // Proximity threat takes last priority - if (proximityThreat > biggestThreat) - { + if (proximityThreat > biggestThreat) { biggestThreat = proximityThreat; optimalTarget = entity; } } - if (!m_DirtyThreat) - { - if (optimalTarget == nullptr) - { + if (!m_DirtyThreat) { + if (optimalTarget == nullptr) { return LWOOBJID_EMPTY; - } - else - { + } else { return optimalTarget->GetObjectID(); } } - std::vector deadThreats {}; + std::vector deadThreats{}; - for (const auto& threatTarget : m_ThreatEntries) - { + for (const auto& threatTarget : m_ThreatEntries) { auto* entity = EntityManager::Instance()->GetEntity(threatTarget.first); - if (entity == nullptr) - { + if (entity == nullptr) { deadThreats.push_back(threatTarget.first); continue; @@ -506,33 +477,27 @@ LWOOBJID BaseCombatAIComponent::FindTarget() { const auto targetPosition = entity->GetPosition(); - if (Vector3::DistanceSquared(targetPosition, m_StartPosition) > m_HardTetherRadius * m_HardTetherRadius) - { + if (Vector3::DistanceSquared(targetPosition, m_StartPosition) > m_HardTetherRadius * m_HardTetherRadius) { deadThreats.push_back(threatTarget.first); continue; } - if (threatTarget.second > biggestThreat) - { + if (threatTarget.second > biggestThreat) { optimalTarget = entity; biggestThreat = threatTarget.second; } } - for (const auto& deadThreat : deadThreats) - { + for (const auto& deadThreat : deadThreats) { SetThreat(deadThreat, 0); } m_DirtyThreat = false; - if (optimalTarget == nullptr) - { + if (optimalTarget == nullptr) { return LWOOBJID_EMPTY; - } - else - { + } else { return optimalTarget->GetObjectID(); } } @@ -598,12 +563,10 @@ bool BaseCombatAIComponent::IsEnemy(LWOOBJID target) const { auto* quickbuild = entity->GetComponent(); - if (quickbuild != nullptr) - { + if (quickbuild != nullptr) { const auto state = quickbuild->GetState(); - if (state != REBUILD_COMPLETED) - { + if (state != REBUILD_COMPLETED) { return false; } } @@ -630,9 +593,9 @@ Entity* BaseCombatAIComponent::GetTargetEntity() const { } void BaseCombatAIComponent::Taunt(LWOOBJID offender, float threat) { - // Can't taunt self - if (offender == m_Parent->GetObjectID()) - return; + // Can't taunt self + if (offender == m_Parent->GetObjectID()) + return; m_ThreatEntries[offender] += threat; m_DirtyThreat = true; @@ -649,21 +612,18 @@ float BaseCombatAIComponent::GetThreat(LWOOBJID offender) { void BaseCombatAIComponent::SetThreat(LWOOBJID offender, float threat) { if (threat == 0) { m_ThreatEntries.erase(offender); - } - else { + } else { m_ThreatEntries[offender] = threat; } m_DirtyThreat = true; } -const NiPoint3& BaseCombatAIComponent::GetStartPosition() const -{ +const NiPoint3& BaseCombatAIComponent::GetStartPosition() const { return m_StartPosition; } -void BaseCombatAIComponent::ClearThreat() -{ +void BaseCombatAIComponent::ClearThreat() { m_ThreatEntries.clear(); m_DirtyThreat = true; @@ -727,14 +687,12 @@ void BaseCombatAIComponent::OnAggro() { // If the player's position is within range, attack if (Vector3::DistanceSquared(currentPos, targetPos) <= m_AttackRadius * m_AttackRadius) { m_MovementAI->Stop(); - } - else if (Vector3::DistanceSquared(m_StartPosition, targetPos) > m_HardTetherRadius * m_HardTetherRadius) //Return to spawn if we're too far + } else if (Vector3::DistanceSquared(m_StartPosition, targetPos) > m_HardTetherRadius * m_HardTetherRadius) //Return to spawn if we're too far { m_MovementAI->SetSpeed(m_PursuitSpeed); m_MovementAI->SetDestination(m_StartPosition); - } - else //Chase the player's new position + } else //Chase the player's new position { if (IsMech() && Vector3::DistanceSquared(targetPos, currentPos) > m_AttackRadius * m_AttackRadius * 3 * 3) return; @@ -762,16 +720,14 @@ void BaseCombatAIComponent::OnTether() { if (Vector3::DistanceSquared(currentPos, targetPos) <= m_AttackRadius * m_AttackRadius) { m_MovementAI->Stop(); - } - else if (Vector3::DistanceSquared(m_StartPosition, targetPos) > m_HardTetherRadius * m_HardTetherRadius) //Return to spawn if we're too far + } else if (Vector3::DistanceSquared(m_StartPosition, targetPos) > m_HardTetherRadius * m_HardTetherRadius) //Return to spawn if we're too far { m_MovementAI->SetSpeed(m_PursuitSpeed); m_MovementAI->SetDestination(m_StartPosition); m_State = AiState::aggro; - } - else { + } else { if (IsMech() && Vector3::DistanceSquared(targetPos, currentPos) > m_AttackRadius * m_AttackRadius * 3 * 3) return; m_MovementAI->SetSpeed(m_PursuitSpeed); @@ -790,23 +746,19 @@ void BaseCombatAIComponent::SetStunned(const bool value) { m_Stunned = value; } -bool BaseCombatAIComponent::GetStunImmune() const -{ +bool BaseCombatAIComponent::GetStunImmune() const { return m_StunImmune; } -void BaseCombatAIComponent::SetStunImmune(bool value) -{ +void BaseCombatAIComponent::SetStunImmune(bool value) { m_StunImmune = value; } -float BaseCombatAIComponent::GetTetherSpeed() const -{ +float BaseCombatAIComponent::GetTetherSpeed() const { return m_TetherSpeed; } -void BaseCombatAIComponent::SetTetherSpeed(float value) -{ +void BaseCombatAIComponent::SetTetherSpeed(float value) { m_TetherSpeed = value; } @@ -828,34 +780,28 @@ void BaseCombatAIComponent::SetAggroRadius(const float value) { m_AggroRadius = value; } -void BaseCombatAIComponent::LookAt(const NiPoint3& point) -{ - if (m_Stunned) - { +void BaseCombatAIComponent::LookAt(const NiPoint3& point) { + if (m_Stunned) { return; } m_Parent->SetRotation(NiQuaternion::LookAt(m_Parent->GetPosition(), point)); } -void BaseCombatAIComponent::SetDisabled(bool value) -{ +void BaseCombatAIComponent::SetDisabled(bool value) { m_Disabled = value; } -bool BaseCombatAIComponent::GetDistabled() const -{ +bool BaseCombatAIComponent::GetDistabled() const { return m_Disabled; } -void BaseCombatAIComponent::Sleep() -{ +void BaseCombatAIComponent::Sleep() { m_dpEntity->SetSleeping(true); m_dpEntityEnemy->SetSleeping(true); } -void BaseCombatAIComponent::Wake() -{ +void BaseCombatAIComponent::Wake() { m_dpEntity->SetSleeping(false); m_dpEntityEnemy->SetSleeping(false); -} \ No newline at end of file +} diff --git a/dGame/dComponents/BaseCombatAIComponent.h b/dGame/dComponents/BaseCombatAIComponent.h index ff291736..70a88a42 100644 --- a/dGame/dComponents/BaseCombatAIComponent.h +++ b/dGame/dComponents/BaseCombatAIComponent.h @@ -60,318 +60,318 @@ public: */ AiState GetState() const { return m_State; } - /** - * Set the current behavioral state of the enemy - * @param state the state to change to - */ + /** + * Set the current behavioral state of the enemy + * @param state the state to change to + */ void SetState(AiState state) { m_State = state; } - /** - * Checks if the target may be an enemy of this entity - * @param target the target to check for - * @return whether the target is a valid enemy for this entity or not - */ + /** + * Checks if the target may be an enemy of this entity + * @param target the target to check for + * @return whether the target is a valid enemy for this entity or not + */ bool IsEnemy(LWOOBJID target) const; - /** - * Gets the current target ID that this entity will attack - * @return the current target ID of this entity - */ + /** + * Gets the current target ID that this entity will attack + * @return the current target ID of this entity + */ LWOOBJID GetTarget() const { return m_Target; } - /** - * Sets the target that this entity will attack - * @param target the target to set - */ + /** + * Sets the target that this entity will attack + * @param target the target to set + */ void SetTarget(LWOOBJID target); - /** - * Gets the current target entity that this entity will attack - * @return the current target entity of this entity - */ + /** + * Gets the current target entity that this entity will attack + * @return the current target entity of this entity + */ Entity* GetTargetEntity() const; - /** - * Taunts this entity, making it a higher or lower threat for this entity. Increasing or decreasing the chance to - * be attacked. - * @param offender the entity that triggered the taunt - * @param threat how high to increase the threat for the offender - */ + /** + * Taunts this entity, making it a higher or lower threat for this entity. Increasing or decreasing the chance to + * be attacked. + * @param offender the entity that triggered the taunt + * @param threat how high to increase the threat for the offender + */ void Taunt(LWOOBJID offender, float threat); - /** - * Gets the current threat level for an offending entity - * @param offender the entity to get the threat for - * @return the current threat level of the offending entity, 0 if the entity is not a threat - */ + /** + * Gets the current threat level for an offending entity + * @param offender the entity to get the threat for + * @return the current threat level of the offending entity, 0 if the entity is not a threat + */ float GetThreat(LWOOBJID offender); - /** - * Sets the threat level for an entity - * @param offender the entity to set the threat level for - * @param threat the threat level to set - */ + /** + * Sets the threat level for an entity + * @param offender the entity to set the threat level for + * @param threat the threat level to set + */ void SetThreat(LWOOBJID offender, float threat); - /** - * Gets the position where the entity spawned - * @return the position where the entity spawned - */ + /** + * Gets the position where the entity spawned + * @return the position where the entity spawned + */ const NiPoint3& GetStartPosition() const; - /** - * Removes all threats for this entities, and thus chances for it attacking other entities - */ + /** + * Removes all threats for this entities, and thus chances for it attacking other entities + */ void ClearThreat(); - /** - * Makes the entity continue to wander to a random point around it's starting position - */ + /** + * Makes the entity continue to wander to a random point around it's starting position + */ void Wander(); - /** - * Continues a step in the aggro state, making sure that the entity is around its start position, if an entity - * crosses its aggro range this will set the state to tether. - */ + /** + * Continues a step in the aggro state, making sure that the entity is around its start position, if an entity + * crosses its aggro range this will set the state to tether. + */ void OnAggro(); - /** - * Continues a step in the tether state, making the entity run towards its target, if the target is outside of its - * tether range, this will change the state to aggro - */ + /** + * Continues a step in the tether state, making the entity run towards its target, if the target is outside of its + * tether range, this will change the state to aggro + */ void OnTether(); - /** - * Gets whether or not the entity is currently stunned - * @return whether the entity is currently stunned - */ - bool GetStunned() const; + /** + * Gets whether or not the entity is currently stunned + * @return whether the entity is currently stunned + */ + bool GetStunned() const; - /** - * (un)stuns the entity, determining whether it'll be able to attack other entities - * @param value whether the enemy is stunned - */ + /** + * (un)stuns the entity, determining whether it'll be able to attack other entities + * @param value whether the enemy is stunned + */ void SetStunned(bool value); - /** - * Gets if this entity may be stunned - * @return if this entity may be stunned - */ + /** + * Gets if this entity may be stunned + * @return if this entity may be stunned + */ bool GetStunImmune() const; - /** - * Set the stun immune value, determining if the entity may be stunned - * @param value - */ + /** + * Set the stun immune value, determining if the entity may be stunned + * @param value + */ void SetStunImmune(bool value); - /** - * Gets the current speed at which an entity runs when tethering - * @return the current speed at which an entity runs when tethering - */ + /** + * Gets the current speed at which an entity runs when tethering + * @return the current speed at which an entity runs when tethering + */ float GetTetherSpeed() const; - /** - * Sets the speed at which an entity will tether - * @param value the new tether speed - */ + /** + * Sets the speed at which an entity will tether + * @param value the new tether speed + */ void SetTetherSpeed(float value); - /** - * Stuns the entity for a certain amount of time, will not work if the entity is stun immune - * @param time the time to stun the entity, if stunnable - */ + /** + * Stuns the entity for a certain amount of time, will not work if the entity is stun immune + * @param time the time to stun the entity, if stunnable + */ void Stun(float time); - /** - * Gets the radius that will cause this entity to get aggro'd, causing a target chase - * @return the aggro radius of the entity - */ + /** + * Gets the radius that will cause this entity to get aggro'd, causing a target chase + * @return the aggro radius of the entity + */ float GetAggroRadius() const; - /** - * Sets the aggro radius, causing the entity to start chasing enemies in this range - * @param value the aggro radius to set - */ + /** + * Sets the aggro radius, causing the entity to start chasing enemies in this range + * @param value the aggro radius to set + */ void SetAggroRadius(float value); - /** - * Makes the entity look at a certain point in space - * @param point the point to look at - */ + /** + * Makes the entity look at a certain point in space + * @param point the point to look at + */ void LookAt(const NiPoint3& point); - /** - * (dis)ables the AI, causing it to stop/start attacking enemies - * @param value - */ + /** + * (dis)ables the AI, causing it to stop/start attacking enemies + * @param value + */ void SetDisabled(bool value); - /** - * Gets the current state of the AI, whether or not it's looking for enemies to attack - * @return - */ + /** + * Gets the current state of the AI, whether or not it's looking for enemies to attack + * @return + */ bool GetDistabled() const; - /** - * Turns the entity asleep, stopping updates to its physics volumes - */ + /** + * Turns the entity asleep, stopping updates to its physics volumes + */ void Sleep(); - /** - * Wakes the entity, allowing updates to its physics volumes - */ + /** + * Wakes the entity, allowing updates to its physics volumes + */ void Wake(); private: - /** - * Returns the current target or the target that currently is the largest threat to this entity - * @return the current highest priority enemy of this entity - */ + /** + * Returns the current target or the target that currently is the largest threat to this entity + * @return the current highest priority enemy of this entity + */ LWOOBJID FindTarget(); - /** - * Handles anything attack related for the game loop, e.g.: finding targets, sticking with targets and attacking - * them, depending on cooldowns. - * @param deltaTime the time since the last game tick - */ + /** + * Handles anything attack related for the game loop, e.g.: finding targets, sticking with targets and attacking + * them, depending on cooldowns. + * @param deltaTime the time since the last game tick + */ void CalculateCombat(float deltaTime); - /** - * Gets all the targets that are in the aggro collision phantom of this entity - * @return the targets within the aggro range of this entity - */ + /** + * Gets all the targets that are in the aggro collision phantom of this entity + * @return the targets within the aggro range of this entity + */ std::vector GetTargetWithinAggroRange() const; - /** - * The current state of the AI - */ + /** + * The current state of the AI + */ AiState m_State; - /** - * The target this entity is currently trying to attack - */ + /** + * The target this entity is currently trying to attack + */ LWOOBJID m_Target; - /** - * The aggro physics volumes of this entity - */ + /** + * The aggro physics volumes of this entity + */ dpEntity* m_dpEntity; dpEntity* m_dpEntityEnemy; - /** - * The max radius of this entity to an enemy allowing it to be chased - */ + /** + * The max radius of this entity to an enemy allowing it to be chased + */ float m_HardTetherRadius = 100; - /** - * A soft radius for the tether, currently unused - */ + /** + * A soft radius for the tether, currently unused + */ float m_SoftTetherRadius = 25; - /** - * The speed at which this entity chases enemies - */ + /** + * The speed at which this entity chases enemies + */ float m_PursuitSpeed = 2; - /** - * The radius that can cause enemies to aggro this entity - */ + /** + * The radius that can cause enemies to aggro this entity + */ float m_AggroRadius = 25; - /** - * The speed at which an enemy wanders around - */ + /** + * The speed at which an enemy wanders around + */ float m_TetherSpeed = 4; - /** - * How close this entity needs to be to an enemy to allow attacks - */ + /** + * How close this entity needs to be to an enemy to allow attacks + */ float m_AttackRadius = 5.0f; - /** - * Timer before we start attacking others - */ + /** + * Timer before we start attacking others + */ float m_Timer = 0.0f; - /** - * Timer to serializing this entity - */ + /** + * Timer to serializing this entity + */ float m_SoftTimer = 0.0f; - /** - * The skills this entity can cast on enemies - */ + /** + * The skills this entity can cast on enemies + */ std::vector m_SkillEntries; - /** - * The current enemies and their respective threats to this entity - */ + /** + * The current enemies and their respective threats to this entity + */ std::map m_ThreatEntries; - /** - * The component that handles movement AI, also owned by this entity - */ + /** + * The component that handles movement AI, also owned by this entity + */ MovementAIComponent* m_MovementAI; - /** - * The position at which this entity spawned - */ + /** + * The position at which this entity spawned + */ NiPoint3 m_StartPosition; - /** - * For how long this entity has been stunned - */ + /** + * For how long this entity has been stunned + */ float m_StunTime = 0; - /** - * If this entity is stunned - */ + /** + * If this entity is stunned + */ bool m_Stunned = false; - /** - * If this entity is immune to stunds - */ + /** + * If this entity is immune to stunds + */ bool m_StunImmune = false; - /** - * Time taken between actions - */ + /** + * Time taken between actions + */ float m_Downtime = 0; - /** - * How long this entity needs to execute its skill - */ + /** + * How long this entity needs to execute its skill + */ float m_SkillTime = 0; - /** - * If the entity is currently showing the exclamation mark icon above its head - */ + /** + * If the entity is currently showing the exclamation mark icon above its head + */ bool m_TetherEffectActive = false; - /** - * How long the tether effect will remain active - */ + /** + * How long the tether effect will remain active + */ float m_TetherTime = 0; - /** - * How long until we will consider this entity out of combat, resetting its health and armor - */ + /** + * How long until we will consider this entity out of combat, resetting its health and armor + */ float m_OutOfCombatTime = 0; - /** - * If the entity is currently out of combat, resetting its health and armor if it just came out of combat - */ + /** + * If the entity is currently out of combat, resetting its health and armor if it just came out of combat + */ bool m_OutOfCombat = false; - /** - * If the AI is currently disabled - */ + /** + * If the AI is currently disabled + */ bool m_Disabled = false; - /** - * If the threat list should be updated - */ + /** + * If the threat list should be updated + */ bool m_DirtyThreat = false; /** diff --git a/dGame/dComponents/BouncerComponent.cpp b/dGame/dComponents/BouncerComponent.cpp index 2e24b1ed..1f32d6e5 100644 --- a/dGame/dComponents/BouncerComponent.cpp +++ b/dGame/dComponents/BouncerComponent.cpp @@ -13,8 +13,7 @@ BouncerComponent::BouncerComponent(Entity* parent) : Component(parent) { m_PetBouncerEnabled = false; m_PetSwitchLoaded = false; - if (parent->GetLOT() == 7625) - { + if (parent->GetLOT() == 7625) { LookupPetSwitch(); } } @@ -22,68 +21,56 @@ BouncerComponent::BouncerComponent(Entity* parent) : Component(parent) { BouncerComponent::~BouncerComponent() { } -void BouncerComponent::Serialize(RakNet::BitStream* outBitStream, bool bIsInitialUpdate, unsigned int& flags){ +void BouncerComponent::Serialize(RakNet::BitStream* outBitStream, bool bIsInitialUpdate, unsigned int& flags) { outBitStream->Write(m_PetEnabled); if (m_PetEnabled) { outBitStream->Write(m_PetBouncerEnabled); } } -Entity* BouncerComponent::GetParentEntity() const -{ +Entity* BouncerComponent::GetParentEntity() const { return m_Parent; } -void BouncerComponent::SetPetEnabled(bool value) -{ +void BouncerComponent::SetPetEnabled(bool value) { m_PetEnabled = value; EntityManager::Instance()->SerializeEntity(m_Parent); } -void BouncerComponent::SetPetBouncerEnabled(bool value) -{ +void BouncerComponent::SetPetBouncerEnabled(bool value) { m_PetBouncerEnabled = value; GameMessages::SendBouncerActiveStatus(m_Parent->GetObjectID(), value, UNASSIGNED_SYSTEM_ADDRESS); EntityManager::Instance()->SerializeEntity(m_Parent); - if (value) - { + if (value) { GameMessages::SendPlayFXEffect(m_Parent->GetObjectID(), 1513, u"create", "PetOnSwitch", LWOOBJID_EMPTY, 1, 1, true); - } - else - { + } else { GameMessages::SendStopFXEffect(m_Parent, true, "PetOnSwitch"); } } -bool BouncerComponent::GetPetEnabled() const -{ +bool BouncerComponent::GetPetEnabled() const { return m_PetEnabled; } -bool BouncerComponent::GetPetBouncerEnabled() const -{ +bool BouncerComponent::GetPetBouncerEnabled() const { return m_PetBouncerEnabled; } -void BouncerComponent::LookupPetSwitch() -{ +void BouncerComponent::LookupPetSwitch() { const auto& groups = m_Parent->GetGroups(); - for (const auto& group : groups) - { + for (const auto& group : groups) { const auto& entities = EntityManager::Instance()->GetEntitiesInGroup(group); - for (auto* entity : entities) - { + for (auto* entity : entities) { auto* switchComponent = entity->GetComponent(); - if (switchComponent != nullptr) - { + if (switchComponent != nullptr) { switchComponent->SetPetBouncer(this); m_PetSwitchLoaded = true; @@ -96,12 +83,11 @@ void BouncerComponent::LookupPetSwitch() } } - if (!m_PetSwitchLoaded) - { + if (!m_PetSwitchLoaded) { Game::logger->Log("BouncerComponent", "Failed to load pet bouncer"); m_Parent->AddCallbackTimer(0.5f, [this]() { LookupPetSwitch(); - }); + }); } } diff --git a/dGame/dComponents/BouncerComponent.h b/dGame/dComponents/BouncerComponent.h index 557f737f..f179998b 100644 --- a/dGame/dComponents/BouncerComponent.h +++ b/dGame/dComponents/BouncerComponent.h @@ -12,7 +12,7 @@ class BouncerComponent : public Component { public: static const uint32_t ComponentType = COMPONENT_TYPE_BOUNCER; - + BouncerComponent(Entity* parentEntity); ~BouncerComponent() override; @@ -20,50 +20,50 @@ public: Entity* GetParentEntity() const; - /** - * Sets whether or not this bouncer needs to be activated by a pet - * @param value whether or not this bouncer needs to be activated by a pet - */ + /** + * Sets whether or not this bouncer needs to be activated by a pet + * @param value whether or not this bouncer needs to be activated by a pet + */ void SetPetEnabled(bool value); - /** - * Sets whether or not this bouncer is currently being activated by a pet, allowing entities to bounce off of it, - * also displays FX accordingly. - * @param value whether or not this bouncer is activated by a pet - */ + /** + * Sets whether or not this bouncer is currently being activated by a pet, allowing entities to bounce off of it, + * also displays FX accordingly. + * @param value whether or not this bouncer is activated by a pet + */ void SetPetBouncerEnabled(bool value); - /** - * Gets whether this bouncer should be enabled using pets - * @return whether this bouncer should be enabled using pets - */ + /** + * Gets whether this bouncer should be enabled using pets + * @return whether this bouncer should be enabled using pets + */ bool GetPetEnabled() const; - /** - * Gets whether this bouncer is currently activated by a pet - * @return whether this bouncer is currently activated by a pet - */ + /** + * Gets whether this bouncer is currently activated by a pet + * @return whether this bouncer is currently activated by a pet + */ bool GetPetBouncerEnabled() const; - /** - * Finds the switch used to activate this bouncer if its pet-enabled and stores this components' state there - */ + /** + * Finds the switch used to activate this bouncer if its pet-enabled and stores this components' state there + */ void LookupPetSwitch(); private: - /** - * Whether this bouncer needs to be activated by a pet - */ + /** + * Whether this bouncer needs to be activated by a pet + */ bool m_PetEnabled; - /** - * Whether this bouncer is currently being activated by a pet - */ + /** + * Whether this bouncer is currently being activated by a pet + */ bool m_PetBouncerEnabled; - /** - * Whether the pet switch for this bouncer has been located - */ + /** + * Whether the pet switch for this bouncer has been located + */ bool m_PetSwitchLoaded; }; diff --git a/dGame/dComponents/BuffComponent.cpp b/dGame/dComponents/BuffComponent.cpp index 5874f8a6..ecb10017 100644 --- a/dGame/dComponents/BuffComponent.cpp +++ b/dGame/dComponents/BuffComponent.cpp @@ -10,28 +10,23 @@ #include "ControllablePhysicsComponent.h" #include "EntityManager.h" -std::unordered_map> BuffComponent::m_Cache {}; +std::unordered_map> BuffComponent::m_Cache{}; -BuffComponent::BuffComponent(Entity* parent) : Component(parent) -{ +BuffComponent::BuffComponent(Entity* parent) : Component(parent) { } BuffComponent::~BuffComponent() { } void BuffComponent::Serialize(RakNet::BitStream* outBitStream, bool bIsInitialUpdate, unsigned int& flags) { - if (!bIsInitialUpdate) return; - if (m_Buffs.empty()) - { + if (!bIsInitialUpdate) return; + if (m_Buffs.empty()) { outBitStream->Write0(); - } - else - { + } else { outBitStream->Write1(); outBitStream->Write(m_Buffs.size()); - for (const auto& buff : m_Buffs) - { + for (const auto& buff : m_Buffs) { outBitStream->Write(buff.first); outBitStream->Write0(); outBitStream->Write0(); @@ -53,21 +48,17 @@ void BuffComponent::Serialize(RakNet::BitStream* outBitStream, bool bIsInitialUp outBitStream->Write0(); } -void BuffComponent::Update(float deltaTime) -{ +void BuffComponent::Update(float deltaTime) { /** * Loop through all buffs and apply deltaTime to ther time. * If they have expired, remove the buff and break. */ - for (auto& buff : m_Buffs) - { + for (auto& buff : m_Buffs) { // For damage buffs - if (buff.second.tick != 0.0f && buff.second.stacks > 0) - { + if (buff.second.tick != 0.0f && buff.second.stacks > 0) { buff.second.tickTime -= deltaTime; - if (buff.second.tickTime <= 0.0f) - { + if (buff.second.tickTime <= 0.0f) { buff.second.tickTime = buff.second.tick; buff.second.stacks--; @@ -76,15 +67,13 @@ void BuffComponent::Update(float deltaTime) } // These are indefinate buffs, don't update them. - if (buff.second.time == 0.0f) - { + if (buff.second.time == 0.0f) { continue; } buff.second.time -= deltaTime; - if (buff.second.time <= 0.0f) - { + if (buff.second.time <= 0.0f) { RemoveBuff(buff.first); break; @@ -93,28 +82,24 @@ void BuffComponent::Update(float deltaTime) } void BuffComponent::ApplyBuff(const int32_t id, const float duration, const LWOOBJID source, bool addImmunity, - bool cancelOnDamaged, bool cancelOnDeath, bool cancelOnLogout, bool cancelOnRemoveBuff, - bool cancelOnUi, bool cancelOnUnequip, bool cancelOnZone) -{ + bool cancelOnDamaged, bool cancelOnDeath, bool cancelOnLogout, bool cancelOnRemoveBuff, + bool cancelOnUi, bool cancelOnUnequip, bool cancelOnZone) { // Prevent buffs from stacking. - if (HasBuff(id)) - { + if (HasBuff(id)) { return; } - GameMessages::SendAddBuff(const_cast(m_Parent->GetObjectID()), source, (uint32_t) id, - (uint32_t) duration * 1000, addImmunity, cancelOnDamaged, cancelOnDeath, - cancelOnLogout, cancelOnRemoveBuff, cancelOnUi, cancelOnUnequip, cancelOnZone); + GameMessages::SendAddBuff(const_cast(m_Parent->GetObjectID()), source, (uint32_t)id, + (uint32_t)duration * 1000, addImmunity, cancelOnDamaged, cancelOnDeath, + cancelOnLogout, cancelOnRemoveBuff, cancelOnUi, cancelOnUnequip, cancelOnZone); float tick = 0; float stacks = 0; int32_t behaviorID = 0; const auto& parameters = GetBuffParameters(id); - for (const auto& parameter : parameters) - { - if (parameter.name == "overtime") - { + for (const auto& parameter : parameters) { + if (parameter.name == "overtime") { auto* behaviorTemplateTable = CDClientManager::Instance()->GetTable("SkillBehavior"); behaviorID = behaviorTemplateTable->GetSkillByID(parameter.values[0]).behaviorID; @@ -138,12 +123,10 @@ void BuffComponent::ApplyBuff(const int32_t id, const float duration, const LWOO m_Buffs.emplace(id, buff); } -void BuffComponent::RemoveBuff(int32_t id) -{ +void BuffComponent::RemoveBuff(int32_t id) { const auto& iter = m_Buffs.find(id); - if (iter == m_Buffs.end()) - { + if (iter == m_Buffs.end()) { return; } @@ -152,18 +135,14 @@ void BuffComponent::RemoveBuff(int32_t id) RemoveBuffEffect(id); } -bool BuffComponent::HasBuff(int32_t id) -{ +bool BuffComponent::HasBuff(int32_t id) { return m_Buffs.find(id) != m_Buffs.end(); } -void BuffComponent::ApplyBuffEffect(int32_t id) -{ +void BuffComponent::ApplyBuffEffect(int32_t id) { const auto& parameters = GetBuffParameters(id); - for (const auto& parameter : parameters) - { - if (parameter.name == "max_health") - { + for (const auto& parameter : parameters) { + if (parameter.name == "max_health") { const auto maxHealth = parameter.value; auto* destroyable = this->GetParent()->GetComponent(); @@ -171,9 +150,7 @@ void BuffComponent::ApplyBuffEffect(int32_t id) if (destroyable == nullptr) return; destroyable->SetMaxHealth(destroyable->GetMaxHealth() + maxHealth); - } - else if (parameter.name == "max_armor") - { + } else if (parameter.name == "max_armor") { const auto maxArmor = parameter.value; auto* destroyable = this->GetParent()->GetComponent(); @@ -181,9 +158,7 @@ void BuffComponent::ApplyBuffEffect(int32_t id) if (destroyable == nullptr) return; destroyable->SetMaxArmor(destroyable->GetMaxArmor() + maxArmor); - } - else if (parameter.name == "max_imagination") - { + } else if (parameter.name == "max_imagination") { const auto maxImagination = parameter.value; auto* destroyable = this->GetParent()->GetComponent(); @@ -191,9 +166,7 @@ void BuffComponent::ApplyBuffEffect(int32_t id) if (destroyable == nullptr) return; destroyable->SetMaxImagination(destroyable->GetMaxImagination() + maxImagination); - } - else if (parameter.name == "speed") - { + } else if (parameter.name == "speed") { const auto speed = parameter.value; auto* controllablePhysicsComponent = this->GetParent()->GetComponent(); @@ -209,13 +182,10 @@ void BuffComponent::ApplyBuffEffect(int32_t id) } } -void BuffComponent::RemoveBuffEffect(int32_t id) -{ +void BuffComponent::RemoveBuffEffect(int32_t id) { const auto& parameters = GetBuffParameters(id); - for (const auto& parameter : parameters) - { - if (parameter.name == "max_health") - { + for (const auto& parameter : parameters) { + if (parameter.name == "max_health") { const auto maxHealth = parameter.value; auto* destroyable = this->GetParent()->GetComponent(); @@ -223,9 +193,7 @@ void BuffComponent::RemoveBuffEffect(int32_t id) if (destroyable == nullptr) return; destroyable->SetMaxHealth(destroyable->GetMaxHealth() - maxHealth); - } - else if (parameter.name == "max_armor") - { + } else if (parameter.name == "max_armor") { const auto maxArmor = parameter.value; auto* destroyable = this->GetParent()->GetComponent(); @@ -233,9 +201,7 @@ void BuffComponent::RemoveBuffEffect(int32_t id) if (destroyable == nullptr) return; destroyable->SetMaxArmor(destroyable->GetMaxArmor() - maxArmor); - } - else if (parameter.name == "max_imagination") - { + } else if (parameter.name == "max_imagination") { const auto maxImagination = parameter.value; auto* destroyable = this->GetParent()->GetComponent(); @@ -243,9 +209,7 @@ void BuffComponent::RemoveBuffEffect(int32_t id) if (destroyable == nullptr) return; destroyable->SetMaxImagination(destroyable->GetMaxImagination() - maxImagination); - } - else if (parameter.name == "speed") - { + } else if (parameter.name == "speed") { const auto speed = parameter.value; auto* controllablePhysicsComponent = this->GetParent()->GetComponent(); @@ -261,36 +225,29 @@ void BuffComponent::RemoveBuffEffect(int32_t id) } } -void BuffComponent::RemoveAllBuffs() -{ - for (const auto& buff : m_Buffs) - { +void BuffComponent::RemoveAllBuffs() { + for (const auto& buff : m_Buffs) { RemoveBuffEffect(buff.first); } m_Buffs.clear(); } -void BuffComponent::Reset() -{ +void BuffComponent::Reset() { RemoveAllBuffs(); } -void BuffComponent::ReApplyBuffs() -{ - for (const auto& buff : m_Buffs) - { +void BuffComponent::ReApplyBuffs() { + for (const auto& buff : m_Buffs) { ApplyBuffEffect(buff.first); } } -Entity* BuffComponent::GetParent() const -{ +Entity* BuffComponent::GetParent() const { return m_Parent; } -void BuffComponent::LoadFromXml(tinyxml2::XMLDocument* doc) -{ +void BuffComponent::LoadFromXml(tinyxml2::XMLDocument* doc) { // Load buffs auto* dest = doc->FirstChildElement("obj")->FirstChildElement("dest"); @@ -298,15 +255,13 @@ void BuffComponent::LoadFromXml(tinyxml2::XMLDocument* doc) auto* buffElement = dest->FirstChildElement("buff"); // Old character, no buffs to load - if (buffElement == nullptr) - { + if (buffElement == nullptr) { return; } auto* buffEntry = buffElement->FirstChildElement("b"); - while (buffEntry != nullptr) - { + while (buffEntry != nullptr) { int32_t id = buffEntry->IntAttribute("id"); float t = buffEntry->FloatAttribute("t"); float tk = buffEntry->FloatAttribute("tk"); @@ -328,27 +283,22 @@ void BuffComponent::LoadFromXml(tinyxml2::XMLDocument* doc) } } -void BuffComponent::UpdateXml(tinyxml2::XMLDocument* doc) -{ +void BuffComponent::UpdateXml(tinyxml2::XMLDocument* doc) { // Save buffs auto* dest = doc->FirstChildElement("obj")->FirstChildElement("dest"); // Make sure we have a clean buff element. auto* buffElement = dest->FirstChildElement("buff"); - if (buffElement == nullptr) - { + if (buffElement == nullptr) { buffElement = doc->NewElement("buff"); dest->LinkEndChild(buffElement); - } - else - { + } else { buffElement->DeleteChildren(); } - for (const auto& buff : m_Buffs) - { + for (const auto& buff : m_Buffs) { auto* buffEntry = doc->NewElement("b"); buffEntry->SetAttribute("id", buff.first); @@ -362,46 +312,38 @@ void BuffComponent::UpdateXml(tinyxml2::XMLDocument* doc) } } -const std::vector& BuffComponent::GetBuffParameters(int32_t buffId) -{ +const std::vector& BuffComponent::GetBuffParameters(int32_t buffId) { const auto& pair = m_Cache.find(buffId); - if (pair != m_Cache.end()) - { + if (pair != m_Cache.end()) { return pair->second; } auto query = CDClientDatabase::CreatePreppedStmt( "SELECT * FROM BuffParameters WHERE BuffID = ?;"); - query.bind(1, (int) buffId); + query.bind(1, (int)buffId); auto result = query.execQuery(); - std::vector parameters {}; + std::vector parameters{}; - while (!result.eof()) - { + while (!result.eof()) { BuffParameter param; param.buffId = buffId; param.name = result.getStringField(1); param.value = result.getFloatField(2); - if (!result.fieldIsNull(3)) - { + if (!result.fieldIsNull(3)) { std::istringstream stream(result.getStringField(3)); std::string token; - while (std::getline(stream, token, ',')) - { - try - { + while (std::getline(stream, token, ',')) { + try { const auto value = std::stof(token); param.values.push_back(value); - } - catch (std::invalid_argument& exception) - { + } catch (std::invalid_argument& exception) { Game::logger->Log("BuffComponent", "Failed to parse value (%s): (%s)!", token.c_str(), exception.what()); } } diff --git a/dGame/dComponents/BuffComponent.h b/dGame/dComponents/BuffComponent.h index 49d7fec4..aa669b13 100644 --- a/dGame/dComponents/BuffComponent.h +++ b/dGame/dComponents/BuffComponent.h @@ -15,11 +15,11 @@ class Entity; */ struct BuffParameter { - int32_t buffId; - std::string name; - float value; - std::vector values; - int32_t effectId; + int32_t buffId; + std::string name; + float value; + std::vector values; + int32_t effectId; }; /** @@ -27,13 +27,13 @@ struct BuffParameter */ struct Buff { - int32_t id = 0; - float time = 0; - float tick = 0; - float tickTime = 0; - int32_t stacks = 0; - LWOOBJID source = 0; - int32_t behaviorID = 0; + int32_t id = 0; + float time = 0; + float tick = 0; + float tickTime = 0; + int32_t stacks = 0; + LWOOBJID source = 0; + int32_t behaviorID = 0; }; /** @@ -41,97 +41,97 @@ struct Buff */ class BuffComponent : public Component { public: - static const uint32_t ComponentType = COMPONENT_TYPE_BUFF; - - explicit BuffComponent(Entity* parent); + static const uint32_t ComponentType = COMPONENT_TYPE_BUFF; - ~BuffComponent(); + explicit BuffComponent(Entity* parent); - Entity* GetParent() const; + ~BuffComponent(); - void LoadFromXml(tinyxml2::XMLDocument* doc) override; + Entity* GetParent() const; - void UpdateXml(tinyxml2::XMLDocument* doc) override; - - void Serialize(RakNet::BitStream* outBitStream, bool bIsInitialUpdate, unsigned int& flags); + void LoadFromXml(tinyxml2::XMLDocument* doc) override; - void Update(float deltaTime) override; + void UpdateXml(tinyxml2::XMLDocument* doc) override; - /** - * Applies a buff to the parent entity - * @param id the id of the buff to apply - * @param duration the duration of the buff in seconds - * @param source an optional source entity that cast the buff - * @param addImmunity client flag - * @param cancelOnDamaged client flag to indicate that the buff should disappear when damaged - * @param cancelOnDeath client flag to indicate that the buff should disappear when dying - * @param cancelOnLogout client flag to indicate that the buff should disappear when logging out - * @param cancelOnRemoveBuff client flag to indicate that the buff should disappear when a concrete GM to do so comes around - * @param cancelOnUi client flag to indicate that the buff should disappear when interacting with UI - * @param cancelOnUnequip client flag to indicate that the buff should disappear when the triggering item is unequipped - * @param cancelOnZone client flag to indicate that the buff should disappear when changing zones - */ - void ApplyBuff(int32_t id, float duration, LWOOBJID source, bool addImmunity = false, bool cancelOnDamaged = false, - bool cancelOnDeath = true, bool cancelOnLogout = false, bool cancelOnRemoveBuff = true, - bool cancelOnUi = false, bool cancelOnUnequip = false, bool cancelOnZone = false); + void Serialize(RakNet::BitStream* outBitStream, bool bIsInitialUpdate, unsigned int& flags); - /** - * Removes a buff from the parent entity, reversing its effects - * @param id the id of the buff to remove - */ - void RemoveBuff(int32_t id); + void Update(float deltaTime) override; - /** - * Returns whether or not the entity has a buff identified by `id` - * @param id the id of the buff to find - * @return whether or not the entity has a buff with the specified id active - */ - bool HasBuff(int32_t id); + /** + * Applies a buff to the parent entity + * @param id the id of the buff to apply + * @param duration the duration of the buff in seconds + * @param source an optional source entity that cast the buff + * @param addImmunity client flag + * @param cancelOnDamaged client flag to indicate that the buff should disappear when damaged + * @param cancelOnDeath client flag to indicate that the buff should disappear when dying + * @param cancelOnLogout client flag to indicate that the buff should disappear when logging out + * @param cancelOnRemoveBuff client flag to indicate that the buff should disappear when a concrete GM to do so comes around + * @param cancelOnUi client flag to indicate that the buff should disappear when interacting with UI + * @param cancelOnUnequip client flag to indicate that the buff should disappear when the triggering item is unequipped + * @param cancelOnZone client flag to indicate that the buff should disappear when changing zones + */ + void ApplyBuff(int32_t id, float duration, LWOOBJID source, bool addImmunity = false, bool cancelOnDamaged = false, + bool cancelOnDeath = true, bool cancelOnLogout = false, bool cancelOnRemoveBuff = true, + bool cancelOnUi = false, bool cancelOnUnequip = false, bool cancelOnZone = false); - /** - * Applies the effects of the buffs on the entity, e.g.: changing armor, health, imag, etc. - * @param id the id of the buff effects to apply - */ - void ApplyBuffEffect(int32_t id); + /** + * Removes a buff from the parent entity, reversing its effects + * @param id the id of the buff to remove + */ + void RemoveBuff(int32_t id); - /** - * Reverses the effects of the applied buff - * @param id the id of the buff for which to remove the effects - */ - void RemoveBuffEffect(int32_t id); + /** + * Returns whether or not the entity has a buff identified by `id` + * @param id the id of the buff to find + * @return whether or not the entity has a buff with the specified id active + */ + bool HasBuff(int32_t id); - /** - * Removes all buffs for the entity and reverses all of their effects - */ - void RemoveAllBuffs(); + /** + * Applies the effects of the buffs on the entity, e.g.: changing armor, health, imag, etc. + * @param id the id of the buff effects to apply + */ + void ApplyBuffEffect(int32_t id); - /** - * Removes all buffs for the entity and reverses all of their effects - */ - void Reset(); + /** + * Reverses the effects of the applied buff + * @param id the id of the buff for which to remove the effects + */ + void RemoveBuffEffect(int32_t id); - /** - * Applies all effects for all buffs, active or not, again - */ - void ReApplyBuffs(); + /** + * Removes all buffs for the entity and reverses all of their effects + */ + void RemoveAllBuffs(); - /** - * Gets all the parameters (= effects), for the buffs that belong to this component - * @param buffId - * @return - */ - const std::vector& GetBuffParameters(int32_t buffId); + /** + * Removes all buffs for the entity and reverses all of their effects + */ + void Reset(); + + /** + * Applies all effects for all buffs, active or not, again + */ + void ReApplyBuffs(); + + /** + * Gets all the parameters (= effects), for the buffs that belong to this component + * @param buffId + * @return + */ + const std::vector& GetBuffParameters(int32_t buffId); private: - /** - * The currently active buffs - */ - std::map m_Buffs; + /** + * The currently active buffs + */ + std::map m_Buffs; - /** - * Parameters (=effects) for each buff - */ - static std::unordered_map> m_Cache; + /** + * Parameters (=effects) for each buff + */ + static std::unordered_map> m_Cache; }; #endif // BUFFCOMPONENT_H diff --git a/dGame/dComponents/BuildBorderComponent.cpp b/dGame/dComponents/BuildBorderComponent.cpp index c565af97..f9ead9e4 100644 --- a/dGame/dComponents/BuildBorderComponent.cpp +++ b/dGame/dComponents/BuildBorderComponent.cpp @@ -9,12 +9,10 @@ #include "Item.h" #include "PropertyManagementComponent.h" -BuildBorderComponent::BuildBorderComponent(Entity* parent) : Component(parent) -{ +BuildBorderComponent::BuildBorderComponent(Entity* parent) : Component(parent) { } -BuildBorderComponent::~BuildBorderComponent() -{ +BuildBorderComponent::~BuildBorderComponent() { } void BuildBorderComponent::OnUse(Entity* originator) { @@ -23,8 +21,7 @@ void BuildBorderComponent::OnUse(Entity* originator) { auto buildArea = m_Parent->GetObjectID(); - if (!entities.empty()) - { + if (!entities.empty()) { buildArea = entities[0]->GetObjectID(); Game::logger->Log("BuildBorderComponent", "Using PropertyPlaque"); @@ -62,8 +59,7 @@ void BuildBorderComponent::OnUse(Entity* originator) { NiPoint3::ZERO, 0 ); - } - else { + } else { GameMessages::SendStartArrangingWithItem(originator, originator->GetSystemAddress(), true, buildArea, originator->GetPosition()); } diff --git a/dGame/dComponents/BuildBorderComponent.h b/dGame/dComponents/BuildBorderComponent.h index bd615b48..ba677e37 100644 --- a/dGame/dComponents/BuildBorderComponent.h +++ b/dGame/dComponents/BuildBorderComponent.h @@ -10,20 +10,20 @@ #include "Entity.h" #include "Component.h" -/** - * Component for the build border, allowing the user to start building when interacting with it - */ + /** + * Component for the build border, allowing the user to start building when interacting with it + */ class BuildBorderComponent : public Component { public: static const uint32_t ComponentType = COMPONENT_TYPE_BUILD_BORDER; - + BuildBorderComponent(Entity* parent); ~BuildBorderComponent() override; - /** - * Causes the originator to start build with this entity as a reference point - * @param originator the entity (probably a player) that triggered the event - */ + /** + * Causes the originator to start build with this entity as a reference point + * @param originator the entity (probably a player) that triggered the event + */ void OnUse(Entity* originator) override; private: }; diff --git a/dGame/dComponents/CharacterComponent.cpp b/dGame/dComponents/CharacterComponent.cpp index 1f726a79..91666014 100644 --- a/dGame/dComponents/CharacterComponent.cpp +++ b/dGame/dComponents/CharacterComponent.cpp @@ -31,7 +31,7 @@ CharacterComponent::CharacterComponent(Entity* parent, Character* character) : C m_EditorEnabled = false; m_EditorLevel = m_GMLevel; - m_Reputation = 0; + m_Reputation = 0; m_CurrentActivity = 0; m_CountryCode = 0; @@ -163,13 +163,11 @@ void CharacterComponent::Serialize(RakNet::BitStream* outBitStream, bool bIsInit } } -bool CharacterComponent::GetPvpEnabled() const -{ +bool CharacterComponent::GetPvpEnabled() const { return m_PvpEnabled; } -void CharacterComponent::SetPvpEnabled(const bool value) -{ +void CharacterComponent::SetPvpEnabled(const bool value) { m_DirtyGMInfo = true; m_PvpEnabled = value; @@ -189,66 +187,64 @@ void CharacterComponent::LoadFromXml(tinyxml2::XMLDocument* doc) { Game::logger->Log("CharacterComponent", "Failed to find char tag while loading XML!"); return; } - if (character->QueryAttribute("rpt", &m_Reputation) == tinyxml2::XML_NO_ATTRIBUTE) { - SetReputation(0); - } + if (character->QueryAttribute("rpt", &m_Reputation) == tinyxml2::XML_NO_ATTRIBUTE) { + SetReputation(0); + } character->QueryInt64Attribute("ls", &m_Uscore); // Load the statistics - const auto* statisticsAttribute = character->FindAttribute("stt"); - if (statisticsAttribute) { - InitializeStatisticsFromString(std::string(statisticsAttribute->Value())); - } else { - InitializeEmptyStatistics(); - } + const auto* statisticsAttribute = character->FindAttribute("stt"); + if (statisticsAttribute) { + InitializeStatisticsFromString(std::string(statisticsAttribute->Value())); + } else { + InitializeEmptyStatistics(); + } - // Load the zone statistics - m_ZoneStatistics = {}; - auto zoneStatistics = character->FirstChildElement("zs"); + // Load the zone statistics + m_ZoneStatistics = {}; + auto zoneStatistics = character->FirstChildElement("zs"); - if (zoneStatistics) { - auto child = zoneStatistics->FirstChildElement(); - while (child) { - ZoneStatistics statistics = {}; + if (zoneStatistics) { + auto child = zoneStatistics->FirstChildElement(); + while (child) { + ZoneStatistics statistics = {}; - child->QueryUnsigned64Attribute("ac", &statistics.m_AchievementsCollected); - child->QueryUnsigned64Attribute("bc", &statistics.m_BricksCollected); - child->QueryUnsigned64Attribute("cc", &statistics.m_CoinsCollected); - child->QueryUnsigned64Attribute("es", &statistics.m_EnemiesSmashed); - child->QueryUnsigned64Attribute("qbc", &statistics.m_QuickBuildsCompleted); + child->QueryUnsigned64Attribute("ac", &statistics.m_AchievementsCollected); + child->QueryUnsigned64Attribute("bc", &statistics.m_BricksCollected); + child->QueryUnsigned64Attribute("cc", &statistics.m_CoinsCollected); + child->QueryUnsigned64Attribute("es", &statistics.m_EnemiesSmashed); + child->QueryUnsigned64Attribute("qbc", &statistics.m_QuickBuildsCompleted); - uint32_t mapID; - child->QueryAttribute("map", &mapID); + uint32_t mapID; + child->QueryAttribute("map", &mapID); - m_ZoneStatistics.insert({ (LWOMAPID) mapID, statistics }); + m_ZoneStatistics.insert({ (LWOMAPID)mapID, statistics }); - child = child->NextSiblingElement(); - } - } + child = child->NextSiblingElement(); + } + } - const tinyxml2::XMLAttribute *rocketConfig = character->FindAttribute("lcbp"); + const tinyxml2::XMLAttribute* rocketConfig = character->FindAttribute("lcbp"); if (rocketConfig) { m_LastRocketConfig = GeneralUtils::ASCIIToUTF16(std::string(rocketConfig->Value())); - } - else - { + } else { m_LastRocketConfig = u""; } - // - // Begin custom attributes - // + // + // Begin custom attributes + // - // Load the last rocket item ID - const tinyxml2::XMLAttribute *lastRocketItemID = character->FindAttribute("lrid"); - if (lastRocketItemID) { - m_LastRocketItemID = lastRocketItemID->Int64Value(); - } + // Load the last rocket item ID + const tinyxml2::XMLAttribute* lastRocketItemID = character->FindAttribute("lrid"); + if (lastRocketItemID) { + m_LastRocketItemID = lastRocketItemID->Int64Value(); + } - // - // End custom attributes - // + // + // End custom attributes + // if (m_GMLevel > 0) { m_IsGM = true; @@ -258,7 +254,7 @@ void CharacterComponent::LoadFromXml(tinyxml2::XMLDocument* doc) { } //Annoying guild bs: - const tinyxml2::XMLAttribute *guildName = character->FindAttribute("gn"); + const tinyxml2::XMLAttribute* guildName = character->FindAttribute("gn"); if (guildName) { const char* gn = guildName->Value(); int64_t gid = 0; @@ -272,32 +268,32 @@ void CharacterComponent::LoadFromXml(tinyxml2::XMLDocument* doc) { } if (character->FindAttribute("time")) { - character->QueryUnsigned64Attribute("time", &m_TotalTimePlayed); + character->QueryUnsigned64Attribute("time", &m_TotalTimePlayed); } else { - m_TotalTimePlayed = 0; + m_TotalTimePlayed = 0; } } void CharacterComponent::UpdateXml(tinyxml2::XMLDocument* doc) { - tinyxml2::XMLElement* minifig = doc->FirstChildElement("obj")->FirstChildElement("mf"); + tinyxml2::XMLElement* minifig = doc->FirstChildElement("obj")->FirstChildElement("mf"); if (!minifig) { Game::logger->Log("CharacterComponent", "Failed to find mf tag while updating XML!"); return; } - // write minifig information that might have been changed by commands + // write minifig information that might have been changed by commands - minifig->SetAttribute("es", m_Character->GetEyebrows()); - minifig->SetAttribute("ess", m_Character->GetEyes()); - minifig->SetAttribute("hc", m_Character->GetHairColor()); - minifig->SetAttribute("hs", m_Character->GetHairStyle()); - minifig->SetAttribute("l", m_Character->GetPantsColor()); - minifig->SetAttribute("lh", m_Character->GetLeftHand()); - minifig->SetAttribute("ms", m_Character->GetMouth()); - minifig->SetAttribute("rh", m_Character->GetRightHand()); - minifig->SetAttribute("t", m_Character->GetShirtColor()); + minifig->SetAttribute("es", m_Character->GetEyebrows()); + minifig->SetAttribute("ess", m_Character->GetEyes()); + minifig->SetAttribute("hc", m_Character->GetHairColor()); + minifig->SetAttribute("hs", m_Character->GetHairStyle()); + minifig->SetAttribute("l", m_Character->GetPantsColor()); + minifig->SetAttribute("lh", m_Character->GetLeftHand()); + minifig->SetAttribute("ms", m_Character->GetMouth()); + minifig->SetAttribute("rh", m_Character->GetRightHand()); + minifig->SetAttribute("t", m_Character->GetShirtColor()); - // done with minifig + // done with minifig tinyxml2::XMLElement* character = doc->FirstChildElement("obj")->FirstChildElement("char"); if (!character) { @@ -306,8 +302,8 @@ void CharacterComponent::UpdateXml(tinyxml2::XMLDocument* doc) { } character->SetAttribute("ls", m_Uscore); - // Custom attribute to keep track of reputation. - character->SetAttribute("rpt", GetReputation()); + // Custom attribute to keep track of reputation. + character->SetAttribute("rpt", GetReputation()); character->SetAttribute("stt", StatisticsToString().c_str()); // Set the zone statistics of the form ... @@ -316,16 +312,16 @@ void CharacterComponent::UpdateXml(tinyxml2::XMLDocument* doc) { zoneStatistics->DeleteChildren(); for (auto pair : m_ZoneStatistics) { - auto zoneStatistic = doc->NewElement("s"); + auto zoneStatistic = doc->NewElement("s"); - zoneStatistic->SetAttribute("map", pair.first); - zoneStatistic->SetAttribute("ac", pair.second.m_AchievementsCollected); - zoneStatistic->SetAttribute("bc", pair.second.m_BricksCollected); - zoneStatistic->SetAttribute("cc", pair.second.m_CoinsCollected); - zoneStatistic->SetAttribute("es", pair.second.m_EnemiesSmashed); - zoneStatistic->SetAttribute("qbc", pair.second.m_QuickBuildsCompleted); + zoneStatistic->SetAttribute("map", pair.first); + zoneStatistic->SetAttribute("ac", pair.second.m_AchievementsCollected); + zoneStatistic->SetAttribute("bc", pair.second.m_BricksCollected); + zoneStatistic->SetAttribute("cc", pair.second.m_CoinsCollected); + zoneStatistic->SetAttribute("es", pair.second.m_EnemiesSmashed); + zoneStatistic->SetAttribute("qbc", pair.second.m_QuickBuildsCompleted); - zoneStatistics->LinkEndChild(zoneStatistic); + zoneStatistics->LinkEndChild(zoneStatistic); } character->LinkEndChild(zoneStatistics); @@ -333,22 +329,20 @@ void CharacterComponent::UpdateXml(tinyxml2::XMLDocument* doc) { if (!m_LastRocketConfig.empty()) { std::string config = GeneralUtils::UTF16ToWTF8(m_LastRocketConfig); character->SetAttribute("lcbp", config.c_str()); - } - else - { + } else { character->DeleteAttribute("lcbp"); } - // - // Begin custom attributes - // + // + // Begin custom attributes + // - // Store last rocket item ID - character->SetAttribute("lrid", m_LastRocketItemID); + // Store last rocket item ID + character->SetAttribute("lrid", m_LastRocketItemID); - // - // End custom attributes - // + // + // End custom attributes + // auto newUpdateTimestamp = std::time(nullptr); Game::logger->Log("TotalTimePlayed", "Time since last save: %d", newUpdateTimestamp - m_LastUpdateTimestamp); @@ -372,7 +366,7 @@ Item* CharacterComponent::GetRocket(Entity* player) { if (!inventoryComponent) return rocket; // Select the rocket - if (!rocket){ + if (!rocket) { rocket = inventoryComponent->FindItemById(GetLastRocketItemID()); } @@ -415,325 +409,325 @@ void CharacterComponent::RocketUnEquip(Entity* player) { } void CharacterComponent::TrackMissionCompletion(bool isAchievement) { - UpdatePlayerStatistic(MissionsCompleted); + UpdatePlayerStatistic(MissionsCompleted); - // Achievements are tracked separately for the zone - if (isAchievement) { - const auto mapID = dZoneManager::Instance()->GetZoneID().GetMapID(); - GetZoneStatisticsForMap(mapID).m_AchievementsCollected++; - } + // Achievements are tracked separately for the zone + if (isAchievement) { + const auto mapID = dZoneManager::Instance()->GetZoneID().GetMapID(); + GetZoneStatisticsForMap(mapID).m_AchievementsCollected++; + } } void CharacterComponent::TrackLOTCollection(LOT lot) { - switch (lot) { - // Handle all the imagination powerup lots - case 935: // 1 point - case 4035: // 2 points - case 11910: // 3 points - case 11911: // 5 points - case 11918: // 10 points - UpdatePlayerStatistic(ImaginationPowerUpsCollected); - break; - // Handle all the armor powerup lots - case 6431: // 1 point - case 11912: // 2 points - case 11913: // 3 points - case 11914: // 5 points - case 11919: // 10 points - UpdatePlayerStatistic(ArmorPowerUpsCollected); - break; - // Handle all the life powerup lots - case 177: // 1 point - case 11915: // 2 points - case 11916: // 3 points - case 11917: // 5 points - case 11920: // 10 points - UpdatePlayerStatistic(LifePowerUpsCollected); - break; - default: - break; - } + switch (lot) { + // Handle all the imagination powerup lots + case 935: // 1 point + case 4035: // 2 points + case 11910: // 3 points + case 11911: // 5 points + case 11918: // 10 points + UpdatePlayerStatistic(ImaginationPowerUpsCollected); + break; + // Handle all the armor powerup lots + case 6431: // 1 point + case 11912: // 2 points + case 11913: // 3 points + case 11914: // 5 points + case 11919: // 10 points + UpdatePlayerStatistic(ArmorPowerUpsCollected); + break; + // Handle all the life powerup lots + case 177: // 1 point + case 11915: // 2 points + case 11916: // 3 points + case 11917: // 5 points + case 11920: // 10 points + UpdatePlayerStatistic(LifePowerUpsCollected); + break; + default: + break; + } } void CharacterComponent::TrackHealthDelta(int32_t health) { - if (health > 0) { - UpdatePlayerStatistic(TotalDamageHealed, health); - } else { - UpdatePlayerStatistic(TotalDamageTaken, -health); - } + if (health > 0) { + UpdatePlayerStatistic(TotalDamageHealed, health); + } else { + UpdatePlayerStatistic(TotalDamageTaken, -health); + } } void CharacterComponent::TrackImaginationDelta(int32_t imagination) { - if (imagination > 0) { - UpdatePlayerStatistic(TotalImaginationRestored, imagination); - } else { - UpdatePlayerStatistic(TotalImaginationUsed, -imagination); - } + if (imagination > 0) { + UpdatePlayerStatistic(TotalImaginationRestored, imagination); + } else { + UpdatePlayerStatistic(TotalImaginationUsed, -imagination); + } } void CharacterComponent::TrackArmorDelta(int32_t armor) { - if (armor > 0) { - UpdatePlayerStatistic(TotalArmorRepaired, armor); - } + if (armor > 0) { + UpdatePlayerStatistic(TotalArmorRepaired, armor); + } } void CharacterComponent::TrackRebuildComplete() { - UpdatePlayerStatistic(QuickBuildsCompleted); + UpdatePlayerStatistic(QuickBuildsCompleted); - const auto mapID = dZoneManager::Instance()->GetZoneID().GetMapID(); - GetZoneStatisticsForMap(mapID).m_QuickBuildsCompleted++; + const auto mapID = dZoneManager::Instance()->GetZoneID().GetMapID(); + GetZoneStatisticsForMap(mapID).m_QuickBuildsCompleted++; } void CharacterComponent::TrackRaceCompleted(bool won) { - m_RacesFinished++; - if (won) - m_FirstPlaceRaceFinishes++; + m_RacesFinished++; + if (won) + m_FirstPlaceRaceFinishes++; } void CharacterComponent::TrackPositionUpdate(const NiPoint3& newPosition) { - const auto distance = NiPoint3::Distance(newPosition, m_Parent->GetPosition()); + const auto distance = NiPoint3::Distance(newPosition, m_Parent->GetPosition()); - if (m_IsRacing) { - UpdatePlayerStatistic(DistanceDriven, (uint64_t) distance); - } else { - UpdatePlayerStatistic(MetersTraveled, (uint64_t) distance); - } + if (m_IsRacing) { + UpdatePlayerStatistic(DistanceDriven, (uint64_t)distance); + } else { + UpdatePlayerStatistic(MetersTraveled, (uint64_t)distance); + } } -void CharacterComponent::HandleZoneStatisticsUpdate(LWOMAPID zoneID, const std::u16string &name, int32_t value) { - auto zoneStatistics = &GetZoneStatisticsForMap(zoneID); +void CharacterComponent::HandleZoneStatisticsUpdate(LWOMAPID zoneID, const std::u16string& name, int32_t value) { + auto zoneStatistics = &GetZoneStatisticsForMap(zoneID); - if (name == u"BricksCollected") { - m_BricksCollected += value; - zoneStatistics->m_BricksCollected += value; - } else if (name == u"CoinsCollected") { - m_CurrencyCollected += value; - zoneStatistics->m_CoinsCollected += value; - } else if (name == u"EnemiesSmashed") { - m_EnemiesSmashed += value; - zoneStatistics->m_EnemiesSmashed += value; - } + if (name == u"BricksCollected") { + m_BricksCollected += value; + zoneStatistics->m_BricksCollected += value; + } else if (name == u"CoinsCollected") { + m_CurrencyCollected += value; + zoneStatistics->m_CoinsCollected += value; + } else if (name == u"EnemiesSmashed") { + m_EnemiesSmashed += value; + zoneStatistics->m_EnemiesSmashed += value; + } } void CharacterComponent::UpdatePlayerStatistic(StatisticID updateID, uint64_t updateValue) { - switch (updateID) { - case CurrencyCollected: - m_CurrencyCollected += updateValue; - break; - case BricksCollected: - m_BricksCollected += updateValue; - break; - case SmashablesSmashed: - m_SmashablesSmashed += updateValue; - break; - case QuickBuildsCompleted: - m_QuickBuildsCompleted += updateValue; - break; - case EnemiesSmashed: - m_EnemiesSmashed += updateValue; - break; - case RocketsUsed: - m_RocketsUsed += updateValue; - break; - case MissionsCompleted: - m_MissionsCompleted += updateValue; - break; - case PetsTamed: - m_PetsTamed += updateValue; - break; - case ImaginationPowerUpsCollected: - m_ImaginationPowerUpsCollected += updateValue; - break; - case LifePowerUpsCollected: - m_LifePowerUpsCollected += updateValue; - break; - case ArmorPowerUpsCollected: - m_ArmorPowerUpsCollected += updateValue; - break; - case MetersTraveled: - m_MetersTraveled += updateValue; - break; - case TimesSmashed: - m_TimesSmashed += updateValue; - break; - case TotalDamageTaken: - m_TotalDamageTaken += updateValue; - break; - case TotalDamageHealed: - m_TotalDamageHealed += updateValue; - break; - case TotalArmorRepaired: - m_TotalArmorRepaired += updateValue; - break; - case TotalImaginationRestored: - m_TotalImaginationRestored += updateValue; - break; - case TotalImaginationUsed: - m_TotalImaginationUsed += updateValue; - break; - case DistanceDriven: - m_DistanceDriven += updateValue; - break; - case TimeAirborneInCar: - m_TimeAirborneInCar += updateValue; - break; - case RacingImaginationPowerUpsCollected: - m_RacingImaginationPowerUpsCollected += updateValue; - break; - case RacingImaginationCratesSmashed: - m_RacingImaginationCratesSmashed += updateValue; - break; - case RacingCarBoostsActivated: - m_RacingCarBoostsActivated += updateValue; - break; - case RacingTimesWrecked: - m_RacingTimesWrecked += updateValue; - break; - case RacingSmashablesSmashed: - m_RacingSmashablesSmashed += updateValue; - break; - case RacesFinished: - m_RacesFinished += updateValue; - break; - case FirstPlaceRaceFinishes: - m_FirstPlaceRaceFinishes += updateValue; - break; - default: - break; - } + switch (updateID) { + case CurrencyCollected: + m_CurrencyCollected += updateValue; + break; + case BricksCollected: + m_BricksCollected += updateValue; + break; + case SmashablesSmashed: + m_SmashablesSmashed += updateValue; + break; + case QuickBuildsCompleted: + m_QuickBuildsCompleted += updateValue; + break; + case EnemiesSmashed: + m_EnemiesSmashed += updateValue; + break; + case RocketsUsed: + m_RocketsUsed += updateValue; + break; + case MissionsCompleted: + m_MissionsCompleted += updateValue; + break; + case PetsTamed: + m_PetsTamed += updateValue; + break; + case ImaginationPowerUpsCollected: + m_ImaginationPowerUpsCollected += updateValue; + break; + case LifePowerUpsCollected: + m_LifePowerUpsCollected += updateValue; + break; + case ArmorPowerUpsCollected: + m_ArmorPowerUpsCollected += updateValue; + break; + case MetersTraveled: + m_MetersTraveled += updateValue; + break; + case TimesSmashed: + m_TimesSmashed += updateValue; + break; + case TotalDamageTaken: + m_TotalDamageTaken += updateValue; + break; + case TotalDamageHealed: + m_TotalDamageHealed += updateValue; + break; + case TotalArmorRepaired: + m_TotalArmorRepaired += updateValue; + break; + case TotalImaginationRestored: + m_TotalImaginationRestored += updateValue; + break; + case TotalImaginationUsed: + m_TotalImaginationUsed += updateValue; + break; + case DistanceDriven: + m_DistanceDriven += updateValue; + break; + case TimeAirborneInCar: + m_TimeAirborneInCar += updateValue; + break; + case RacingImaginationPowerUpsCollected: + m_RacingImaginationPowerUpsCollected += updateValue; + break; + case RacingImaginationCratesSmashed: + m_RacingImaginationCratesSmashed += updateValue; + break; + case RacingCarBoostsActivated: + m_RacingCarBoostsActivated += updateValue; + break; + case RacingTimesWrecked: + m_RacingTimesWrecked += updateValue; + break; + case RacingSmashablesSmashed: + m_RacingSmashablesSmashed += updateValue; + break; + case RacesFinished: + m_RacesFinished += updateValue; + break; + case FirstPlaceRaceFinishes: + m_FirstPlaceRaceFinishes += updateValue; + break; + default: + break; + } } -void CharacterComponent::InitializeStatisticsFromString(const std::string &statisticsString) { - auto split = GeneralUtils::SplitString(statisticsString, ';'); +void CharacterComponent::InitializeStatisticsFromString(const std::string& statisticsString) { + auto split = GeneralUtils::SplitString(statisticsString, ';'); - m_CurrencyCollected = GetStatisticFromSplit(split, 0); - m_BricksCollected = GetStatisticFromSplit(split, 1); - m_SmashablesSmashed = GetStatisticFromSplit(split, 2); - m_QuickBuildsCompleted = GetStatisticFromSplit(split, 3); - m_EnemiesSmashed = GetStatisticFromSplit(split, 4); - m_RocketsUsed = GetStatisticFromSplit(split, 5); - m_MissionsCompleted = GetStatisticFromSplit(split, 6); - m_PetsTamed = GetStatisticFromSplit(split, 7); - m_ImaginationPowerUpsCollected = GetStatisticFromSplit(split, 8); - m_LifePowerUpsCollected = GetStatisticFromSplit(split, 9); - m_ArmorPowerUpsCollected = GetStatisticFromSplit(split, 10); - m_MetersTraveled = GetStatisticFromSplit(split, 11); - m_TimesSmashed = GetStatisticFromSplit(split, 12); - m_TotalDamageTaken = GetStatisticFromSplit(split, 13); - m_TotalDamageHealed = GetStatisticFromSplit(split, 14); - m_TotalArmorRepaired = GetStatisticFromSplit(split, 15); - m_TotalImaginationRestored = GetStatisticFromSplit(split, 16); - m_TotalImaginationUsed = GetStatisticFromSplit(split, 17); - m_DistanceDriven = GetStatisticFromSplit(split, 18); - m_TimeAirborneInCar = GetStatisticFromSplit(split, 19); // WONTFIX - m_RacingImaginationPowerUpsCollected = GetStatisticFromSplit(split, 20); - m_RacingImaginationCratesSmashed = GetStatisticFromSplit(split, 21); - m_RacingCarBoostsActivated = GetStatisticFromSplit(split, 22); - m_RacingTimesWrecked = GetStatisticFromSplit(split, 23); - m_RacingSmashablesSmashed = GetStatisticFromSplit(split, 24); - m_RacesFinished = GetStatisticFromSplit(split, 25); - m_FirstPlaceRaceFinishes = GetStatisticFromSplit(split, 26); + m_CurrencyCollected = GetStatisticFromSplit(split, 0); + m_BricksCollected = GetStatisticFromSplit(split, 1); + m_SmashablesSmashed = GetStatisticFromSplit(split, 2); + m_QuickBuildsCompleted = GetStatisticFromSplit(split, 3); + m_EnemiesSmashed = GetStatisticFromSplit(split, 4); + m_RocketsUsed = GetStatisticFromSplit(split, 5); + m_MissionsCompleted = GetStatisticFromSplit(split, 6); + m_PetsTamed = GetStatisticFromSplit(split, 7); + m_ImaginationPowerUpsCollected = GetStatisticFromSplit(split, 8); + m_LifePowerUpsCollected = GetStatisticFromSplit(split, 9); + m_ArmorPowerUpsCollected = GetStatisticFromSplit(split, 10); + m_MetersTraveled = GetStatisticFromSplit(split, 11); + m_TimesSmashed = GetStatisticFromSplit(split, 12); + m_TotalDamageTaken = GetStatisticFromSplit(split, 13); + m_TotalDamageHealed = GetStatisticFromSplit(split, 14); + m_TotalArmorRepaired = GetStatisticFromSplit(split, 15); + m_TotalImaginationRestored = GetStatisticFromSplit(split, 16); + m_TotalImaginationUsed = GetStatisticFromSplit(split, 17); + m_DistanceDriven = GetStatisticFromSplit(split, 18); + m_TimeAirborneInCar = GetStatisticFromSplit(split, 19); // WONTFIX + m_RacingImaginationPowerUpsCollected = GetStatisticFromSplit(split, 20); + m_RacingImaginationCratesSmashed = GetStatisticFromSplit(split, 21); + m_RacingCarBoostsActivated = GetStatisticFromSplit(split, 22); + m_RacingTimesWrecked = GetStatisticFromSplit(split, 23); + m_RacingSmashablesSmashed = GetStatisticFromSplit(split, 24); + m_RacesFinished = GetStatisticFromSplit(split, 25); + m_FirstPlaceRaceFinishes = GetStatisticFromSplit(split, 26); } void CharacterComponent::InitializeEmptyStatistics() { - m_CurrencyCollected = 0; - m_BricksCollected = 0; - m_SmashablesSmashed = 0; - m_QuickBuildsCompleted = 0; - m_EnemiesSmashed = 0; - m_RocketsUsed = 0; - m_MissionsCompleted = 0; - m_PetsTamed = 0; - m_ImaginationPowerUpsCollected = 0; - m_LifePowerUpsCollected = 0; - m_ArmorPowerUpsCollected = 0; - m_MetersTraveled = 0; - m_TimesSmashed = 0; - m_TotalDamageTaken = 0; - m_TotalDamageHealed = 0; - m_TotalArmorRepaired = 0; - m_TotalImaginationRestored = 0; - m_TotalImaginationUsed = 0; - m_DistanceDriven = 0; - m_TimeAirborneInCar = 0; - m_RacingImaginationPowerUpsCollected = 0; - m_RacingImaginationCratesSmashed = 0; - m_RacingCarBoostsActivated = 0; - m_RacingTimesWrecked = 0; - m_RacingSmashablesSmashed = 0; - m_RacesFinished = 0; - m_FirstPlaceRaceFinishes = 0; + m_CurrencyCollected = 0; + m_BricksCollected = 0; + m_SmashablesSmashed = 0; + m_QuickBuildsCompleted = 0; + m_EnemiesSmashed = 0; + m_RocketsUsed = 0; + m_MissionsCompleted = 0; + m_PetsTamed = 0; + m_ImaginationPowerUpsCollected = 0; + m_LifePowerUpsCollected = 0; + m_ArmorPowerUpsCollected = 0; + m_MetersTraveled = 0; + m_TimesSmashed = 0; + m_TotalDamageTaken = 0; + m_TotalDamageHealed = 0; + m_TotalArmorRepaired = 0; + m_TotalImaginationRestored = 0; + m_TotalImaginationUsed = 0; + m_DistanceDriven = 0; + m_TimeAirborneInCar = 0; + m_RacingImaginationPowerUpsCollected = 0; + m_RacingImaginationCratesSmashed = 0; + m_RacingCarBoostsActivated = 0; + m_RacingTimesWrecked = 0; + m_RacingSmashablesSmashed = 0; + m_RacesFinished = 0; + m_FirstPlaceRaceFinishes = 0; } std::string CharacterComponent::StatisticsToString() const { - std::stringstream result; - result << std::to_string(m_CurrencyCollected) << ';' - << std::to_string(m_BricksCollected) << ';' - << std::to_string(m_SmashablesSmashed) << ';' - << std::to_string(m_QuickBuildsCompleted) << ';' - << std::to_string(m_EnemiesSmashed) << ';' - << std::to_string(m_RocketsUsed) << ';' - << std::to_string(m_MissionsCompleted) << ';' - << std::to_string(m_PetsTamed) << ';' - << std::to_string(m_ImaginationPowerUpsCollected) << ';' - << std::to_string(m_LifePowerUpsCollected) << ';' - << std::to_string(m_ArmorPowerUpsCollected) << ';' - << std::to_string(m_MetersTraveled) << ';' - << std::to_string(m_TimesSmashed) << ';' - << std::to_string(m_TotalDamageTaken) << ';' - << std::to_string(m_TotalDamageHealed) << ';' - << std::to_string(m_TotalArmorRepaired) << ';' - << std::to_string(m_TotalImaginationRestored) << ';' - << std::to_string(m_TotalImaginationUsed) << ';' - << std::to_string(m_DistanceDriven) << ';' - << std::to_string(m_TimeAirborneInCar) << ';' - << std::to_string(m_RacingImaginationPowerUpsCollected) << ';' - << std::to_string(m_RacingImaginationCratesSmashed) << ';' - << std::to_string(m_RacingCarBoostsActivated) << ';' - << std::to_string(m_RacingTimesWrecked) << ';' - << std::to_string(m_RacingSmashablesSmashed) << ';' - << std::to_string(m_RacesFinished) << ';' - << std::to_string(m_FirstPlaceRaceFinishes) << ';'; + std::stringstream result; + result << std::to_string(m_CurrencyCollected) << ';' + << std::to_string(m_BricksCollected) << ';' + << std::to_string(m_SmashablesSmashed) << ';' + << std::to_string(m_QuickBuildsCompleted) << ';' + << std::to_string(m_EnemiesSmashed) << ';' + << std::to_string(m_RocketsUsed) << ';' + << std::to_string(m_MissionsCompleted) << ';' + << std::to_string(m_PetsTamed) << ';' + << std::to_string(m_ImaginationPowerUpsCollected) << ';' + << std::to_string(m_LifePowerUpsCollected) << ';' + << std::to_string(m_ArmorPowerUpsCollected) << ';' + << std::to_string(m_MetersTraveled) << ';' + << std::to_string(m_TimesSmashed) << ';' + << std::to_string(m_TotalDamageTaken) << ';' + << std::to_string(m_TotalDamageHealed) << ';' + << std::to_string(m_TotalArmorRepaired) << ';' + << std::to_string(m_TotalImaginationRestored) << ';' + << std::to_string(m_TotalImaginationUsed) << ';' + << std::to_string(m_DistanceDriven) << ';' + << std::to_string(m_TimeAirborneInCar) << ';' + << std::to_string(m_RacingImaginationPowerUpsCollected) << ';' + << std::to_string(m_RacingImaginationCratesSmashed) << ';' + << std::to_string(m_RacingCarBoostsActivated) << ';' + << std::to_string(m_RacingTimesWrecked) << ';' + << std::to_string(m_RacingSmashablesSmashed) << ';' + << std::to_string(m_RacesFinished) << ';' + << std::to_string(m_FirstPlaceRaceFinishes) << ';'; - return result.str(); + return result.str(); } uint64_t CharacterComponent::GetStatisticFromSplit(std::vector split, uint32_t index) { - return split.size() > index ? std::stoul(split.at(index)) : 0; + return split.size() > index ? std::stoul(split.at(index)) : 0; } ZoneStatistics& CharacterComponent::GetZoneStatisticsForMap(LWOMAPID mapID) { - auto stats = m_ZoneStatistics.find(mapID); - if (stats == m_ZoneStatistics.end()) - m_ZoneStatistics.insert({ mapID, {0, 0, 0, 0, 0 } }); - return m_ZoneStatistics.at(mapID); + auto stats = m_ZoneStatistics.find(mapID); + if (stats == m_ZoneStatistics.end()) + m_ZoneStatistics.insert({ mapID, {0, 0, 0, 0, 0 } }); + return m_ZoneStatistics.at(mapID); } void CharacterComponent::AddVentureVisionEffect(std::string ventureVisionType) { - const auto ventureVisionTypeIterator = m_ActiveVentureVisionEffects.find(ventureVisionType); + const auto ventureVisionTypeIterator = m_ActiveVentureVisionEffects.find(ventureVisionType); - if (ventureVisionTypeIterator != m_ActiveVentureVisionEffects.end()) { - ventureVisionTypeIterator->second = ++ventureVisionTypeIterator->second; - } else { - // If the effect it not found, insert it into the active effects. - m_ActiveVentureVisionEffects.insert(std::make_pair(ventureVisionType, 1U)); - } + if (ventureVisionTypeIterator != m_ActiveVentureVisionEffects.end()) { + ventureVisionTypeIterator->second = ++ventureVisionTypeIterator->second; + } else { + // If the effect it not found, insert it into the active effects. + m_ActiveVentureVisionEffects.insert(std::make_pair(ventureVisionType, 1U)); + } - UpdateClientMinimap(true, ventureVisionType); + UpdateClientMinimap(true, ventureVisionType); } void CharacterComponent::RemoveVentureVisionEffect(std::string ventureVisionType) { - const auto ventureVisionTypeIterator = m_ActiveVentureVisionEffects.find(ventureVisionType); + const auto ventureVisionTypeIterator = m_ActiveVentureVisionEffects.find(ventureVisionType); - if (ventureVisionTypeIterator != m_ActiveVentureVisionEffects.end()) { - ventureVisionTypeIterator->second = --ventureVisionTypeIterator->second; - UpdateClientMinimap(ventureVisionTypeIterator->second != 0U, ventureVisionType); - } + if (ventureVisionTypeIterator != m_ActiveVentureVisionEffects.end()) { + ventureVisionTypeIterator->second = --ventureVisionTypeIterator->second; + UpdateClientMinimap(ventureVisionTypeIterator->second != 0U, ventureVisionType); + } } void CharacterComponent::UpdateClientMinimap(bool showFaction, std::string ventureVisionType) const { - if (!m_Parent) return; - AMFArrayValue arrayToSend; - arrayToSend.InsertValue(ventureVisionType, showFaction ? static_cast(new AMFTrueValue()) : static_cast(new AMFFalseValue())); - GameMessages::SendUIMessageServerToSingleClient(m_Parent, m_Parent ? m_Parent->GetSystemAddress() : UNASSIGNED_SYSTEM_ADDRESS, "SetFactionVisibility", &arrayToSend); + if (!m_Parent) return; + AMFArrayValue arrayToSend; + arrayToSend.InsertValue(ventureVisionType, showFaction ? static_cast(new AMFTrueValue()) : static_cast(new AMFFalseValue())); + GameMessages::SendUIMessageServerToSingleClient(m_Parent, m_Parent ? m_Parent->GetSystemAddress() : UNASSIGNED_SYSTEM_ADDRESS, "SetFactionVisibility", &arrayToSend); } diff --git a/dGame/dComponents/CharacterComponent.h b/dGame/dComponents/CharacterComponent.h index cd5809f0..f6bf1e70 100644 --- a/dGame/dComponents/CharacterComponent.h +++ b/dGame/dComponents/CharacterComponent.h @@ -14,44 +14,44 @@ * The statistics that can be achieved per zone */ struct ZoneStatistics { - uint64_t m_AchievementsCollected; - uint64_t m_BricksCollected; - uint64_t m_CoinsCollected; - uint64_t m_EnemiesSmashed; - uint64_t m_QuickBuildsCompleted; + uint64_t m_AchievementsCollected; + uint64_t m_BricksCollected; + uint64_t m_CoinsCollected; + uint64_t m_EnemiesSmashed; + uint64_t m_QuickBuildsCompleted; }; /** * The IDs of each of the possible statistics */ enum StatisticID { - CurrencyCollected = 1, - BricksCollected, - SmashablesSmashed, - QuickBuildsCompleted, - EnemiesSmashed, - RocketsUsed, - MissionsCompleted, - PetsTamed, - ImaginationPowerUpsCollected, - LifePowerUpsCollected, - ArmorPowerUpsCollected, - MetersTraveled, - TimesSmashed, - TotalDamageTaken, - TotalDamageHealed, - TotalArmorRepaired, - TotalImaginationRestored, - TotalImaginationUsed, - DistanceDriven, - TimeAirborneInCar, - RacingImaginationPowerUpsCollected, - RacingImaginationCratesSmashed, - RacingCarBoostsActivated, - RacingTimesWrecked, - RacingSmashablesSmashed, - RacesFinished, - FirstPlaceRaceFinishes, + CurrencyCollected = 1, + BricksCollected, + SmashablesSmashed, + QuickBuildsCompleted, + EnemiesSmashed, + RocketsUsed, + MissionsCompleted, + PetsTamed, + ImaginationPowerUpsCollected, + LifePowerUpsCollected, + ArmorPowerUpsCollected, + MetersTraveled, + TimesSmashed, + TotalDamageTaken, + TotalDamageHealed, + TotalArmorRepaired, + TotalImaginationRestored, + TotalImaginationUsed, + DistanceDriven, + TimeAirborneInCar, + RacingImaginationPowerUpsCollected, + RacingImaginationCratesSmashed, + RacingCarBoostsActivated, + RacingTimesWrecked, + RacingSmashablesSmashed, + RacesFinished, + FirstPlaceRaceFinishes, }; /** @@ -60,19 +60,19 @@ enum StatisticID { class CharacterComponent : public Component { public: static const uint32_t ComponentType = COMPONENT_TYPE_CHARACTER; - - CharacterComponent(Entity* parent, Character* character); - ~CharacterComponent() override; - - void LoadFromXml(tinyxml2::XMLDocument* doc) override; + + CharacterComponent(Entity* parent, Character* character); + ~CharacterComponent() override; + + void LoadFromXml(tinyxml2::XMLDocument* doc) override; void UpdateXml(tinyxml2::XMLDocument* doc) override; - void Serialize(RakNet::BitStream* outBitStream, bool bIsInitialUpdate, unsigned int& flags); + void Serialize(RakNet::BitStream* outBitStream, bool bIsInitialUpdate, unsigned int& flags); - /** - * Updates the rocket configuration using a LOT string separated by commas - * @param config the rocket config to use - */ + /** + * Updates the rocket configuration using a LOT string separated by commas + * @param config the rocket config to use + */ void SetLastRocketConfig(std::u16string config); /** @@ -95,76 +95,76 @@ public: */ void RocketUnEquip(Entity* player); - /** - * Gets the universe score of the entity - * @return the universe score of the entity - */ + /** + * Gets the universe score of the entity + * @return the universe score of the entity + */ const int64_t GetUScore() const { return m_Uscore; } - /** - * Sets the universe score for this entity - * @param uscore the universe score to set - */ + /** + * Sets the universe score for this entity + * @param uscore the universe score to set + */ void SetUScore(int64_t uscore) { m_Uscore = uscore; } - /** - * Gets the current activity that the character is partaking in, see ScriptedActivityComponent for more details - * @return the current activity that the character is partaking in - */ + /** + * Gets the current activity that the character is partaking in, see ScriptedActivityComponent for more details + * @return the current activity that the character is partaking in + */ const uint32_t GetCurrentActivity() const { return m_CurrentActivity; } - /** - * Set the current activity of the character, see ScriptedActivityComponent for more details - * @param currentActivity the activity to set - */ + /** + * Set the current activity of the character, see ScriptedActivityComponent for more details + * @param currentActivity the activity to set + */ void SetCurrentActivity(uint32_t currentActivity) { m_CurrentActivity = currentActivity; m_DirtyCurrentActivity = true; } - /** - * Gets if the entity is currently racing - * @return whether the entity is currently racing - */ + /** + * Gets if the entity is currently racing + * @return whether the entity is currently racing + */ const bool GetIsRacing() const { return m_IsRacing; } - /** - * Sets the state of whether the character is racing - * @param isRacing whether the character is racing - */ + /** + * Sets the state of whether the character is racing + * @param isRacing whether the character is racing + */ void SetIsRacing(bool isRacing) { m_IsRacing = isRacing; } - /** - * Gets whether this character has PvP enabled, allowing combat between players - * @return - */ + /** + * Gets whether this character has PvP enabled, allowing combat between players + * @return + */ bool GetPvpEnabled() const; - /** - * Returns the characters lifetime reputation - * @return The lifetime reputation of this character. - */ - int64_t GetReputation() { return m_Reputation; }; + /** + * Returns the characters lifetime reputation + * @return The lifetime reputation of this character. + */ + int64_t GetReputation() { return m_Reputation; }; - /** - * Sets the lifetime reputation of the character to newValue - * @param newValue the value to set reputation to - */ - void SetReputation(int64_t newValue) { m_Reputation = newValue; }; + /** + * Sets the lifetime reputation of the character to newValue + * @param newValue the value to set reputation to + */ + void SetReputation(int64_t newValue) { m_Reputation = newValue; }; - /** - * Sets the current value of PvP combat being enabled - * @param value whether to enable PvP combat - */ + /** + * Sets the current value of PvP combat being enabled + * @param value whether to enable PvP combat + */ void SetPvpEnabled(bool value); - /** - * Gets the object ID of the rocket that was last used, allowing it to be rendered on launch pads - * @return the object ID of the rocket that was last used, if available - */ + /** + * Gets the object ID of the rocket that was last used, allowing it to be rendered on launch pads + * @return the object ID of the rocket that was last used, if available + */ LWOOBJID GetLastRocketItemID() const { return m_LastRocketItemID; } - /** - * Sets the object ID of the last used rocket - * @param lastRocketItemID the object ID of the last used rocket - */ + /** + * Sets the object ID of the last used rocket + * @param lastRocketItemID the object ID of the last used rocket + */ void SetLastRocketItemID(LWOOBJID lastRocketItemID) { m_LastRocketItemID = lastRocketItemID; } /** @@ -179,40 +179,40 @@ public: */ void SetMountItemID(LWOOBJID mountItemID) { m_MountItemID = mountItemID; } - /** - * Gets the name of this character - * @return the name of this character - */ + /** + * Gets the name of this character + * @return the name of this character + */ std::string GetName() const { return m_Character->GetName(); } - /** - * Sets the GM level of the character, should be called in the entity. Here it's set for serialization - * @param gmlevel the gm level to set - */ + /** + * Sets the GM level of the character, should be called in the entity. Here it's set for serialization + * @param gmlevel the gm level to set + */ void SetGMLevel(int gmlevel); - /** - * Initializes the player statistics from the string stored in the XML - * @param statisticsString the string to parse - */ + /** + * Initializes the player statistics from the string stored in the XML + * @param statisticsString the string to parse + */ void InitializeStatisticsFromString(const std::string& statisticsString); - /** - * Initializes all the statistics with empty stats when there's no stats available up until that point - */ + /** + * Initializes all the statistics with empty stats when there's no stats available up until that point + */ void InitializeEmptyStatistics(); - /** - * Turns character statistics into a stats string - * @return the statistics of the character as a string, in order, split by semicolon (;) - */ + /** + * Turns character statistics into a stats string + * @return the statistics of the character as a string, in order, split by semicolon (;) + */ std::string StatisticsToString() const; /** * Updates the statistics for when a user completes a mission * @param mission the mission info to track */ - void TrackMissionCompletion(bool isAchievement); + void TrackMissionCompletion(bool isAchievement); /** * Handles statistics related to collecting heart flags and imagination bricks @@ -269,301 +269,301 @@ public: */ void UpdatePlayerStatistic(StatisticID updateID, uint64_t updateValue = 1); - /** - * Add a venture vision effect to the player minimap. - */ - void AddVentureVisionEffect(std::string ventureVisionType); + /** + * Add a venture vision effect to the player minimap. + */ + void AddVentureVisionEffect(std::string ventureVisionType); - /** - * Remove a venture vision effect from the player minimap. - * When an effect hits 0 active effects, it is deactivated. - */ - void RemoveVentureVisionEffect(std::string ventureVisionType); + /** + * Remove a venture vision effect from the player minimap. + * When an effect hits 0 active effects, it is deactivated. + */ + void RemoveVentureVisionEffect(std::string ventureVisionType); - /** - * Update the client minimap to reveal the specified factions - */ - void UpdateClientMinimap(bool showFaction, std::string ventureVisionType) const; + /** + * Update the client minimap to reveal the specified factions + */ + void UpdateClientMinimap(bool showFaction, std::string ventureVisionType) const; - /** - * Character info regarding this character, including clothing styles, etc. - */ - Character* m_Character; + /** + * Character info regarding this character, including clothing styles, etc. + */ + Character* m_Character; private: - - /** - * The map of active venture vision effects - */ - std::map m_ActiveVentureVisionEffects; - /** - * Whether this character is racing - */ + /** + * The map of active venture vision effects + */ + std::map m_ActiveVentureVisionEffects; + + /** + * Whether this character is racing + */ bool m_IsRacing; - /** - * Possessible type, used by the shooting gallery - */ + /** + * Possessible type, used by the shooting gallery + */ uint8_t m_PossessableType = 1; - /** - * Universe score of the entity - */ + /** + * Universe score of the entity + */ int64_t m_Uscore; - /** - * The lifetime reputation earned by the entity - */ - int64_t m_Reputation; + /** + * The lifetime reputation earned by the entity + */ + int64_t m_Reputation; - /** - * Whether the character is landing by rocket - */ + /** + * Whether the character is landing by rocket + */ bool m_IsLanding; - /** - * The configuration of the last used rocket, essentially a string of LOTs separated by commas - */ + /** + * The configuration of the last used rocket, essentially a string of LOTs separated by commas + */ std::u16string m_LastRocketConfig; - /** - * Whether the GM info has been changed - */ + /** + * Whether the GM info has been changed + */ bool m_DirtyGMInfo = false; - /** - * Whether PvP is enabled for this entity - */ + /** + * Whether PvP is enabled for this entity + */ bool m_PvpEnabled; - /** - * Whether this entity is a GM - */ + /** + * Whether this entity is a GM + */ bool m_IsGM; - /** - * The current GM level of this character (anything > 0 counts as a GM) - */ + /** + * The current GM level of this character (anything > 0 counts as a GM) + */ unsigned char m_GMLevel; - /** - * Whether the character has HF enabled - */ + /** + * Whether the character has HF enabled + */ bool m_EditorEnabled; - /** - * The level of the character in HF - */ + /** + * The level of the character in HF + */ unsigned char m_EditorLevel; - /** - * Whether the currently active activity has been changed - */ + /** + * Whether the currently active activity has been changed + */ bool m_DirtyCurrentActivity = false; - /** - * The ID of the curently active activity - */ + /** + * The ID of the curently active activity + */ int m_CurrentActivity; - /** - * Whether the social info has been changed - */ + /** + * Whether the social info has been changed + */ bool m_DirtySocialInfo = false; - /** - * The guild this character is in - */ + /** + * The guild this character is in + */ LWOOBJID m_GuildID; - /** - * The name of the guild this character is in - */ + /** + * The name of the guild this character is in + */ std::u16string m_GuildName; - /** - * Whether this character is a lego club member - */ + /** + * Whether this character is a lego club member + */ bool m_IsLEGOClubMember; - /** - * The country code that the character is from - */ + /** + * The country code that the character is from + */ int m_CountryCode; - /** - * Returns whether the landing animation is enabled for a certain zone - * @param zoneID the zone to check for - * @return whether the landing animation is enabled for that zone - */ + /** + * Returns whether the landing animation is enabled for a certain zone + * @param zoneID the zone to check for + * @return whether the landing animation is enabled for that zone + */ bool LandingAnimDisabled(int zoneID); - /** - * Returns the statistics for a certain statistics ID, from a statistics string - * @param split the statistics string to look in - * @param index the statistics ID in the string - * @return the integer value of this statistic, parsed from the string - */ + /** + * Returns the statistics for a certain statistics ID, from a statistics string + * @param split the statistics string to look in + * @param index the statistics ID in the string + * @return the integer value of this statistic, parsed from the string + */ static uint64_t GetStatisticFromSplit(std::vector split, uint32_t index); - /** - * Gets all the statistics for a certain map, if it doesn't exist, it creates empty stats - * @param mapID the ID of the zone to get statistics for - * @return the statistics for the zone - */ + /** + * Gets all the statistics for a certain map, if it doesn't exist, it creates empty stats + * @param mapID the ID of the zone to get statistics for + * @return the statistics for the zone + */ ZoneStatistics& GetZoneStatisticsForMap(const LWOMAPID mapID); - /** - * The last time we saved this character, used to update the total time played - */ - time_t m_LastUpdateTimestamp; + /** + * The last time we saved this character, used to update the total time played + */ + time_t m_LastUpdateTimestamp; - /** - * The total time the character has played, in MS - */ - uint64_t m_TotalTimePlayed; + /** + * The total time the character has played, in MS + */ + uint64_t m_TotalTimePlayed; - /** - * The total amount of currency collected by this character - */ - uint64_t m_CurrencyCollected; + /** + * The total amount of currency collected by this character + */ + uint64_t m_CurrencyCollected; - /** - * The total amount of bricks collected by this character - */ - uint64_t m_BricksCollected; + /** + * The total amount of bricks collected by this character + */ + uint64_t m_BricksCollected; - /** - * The total amount of entities smashed by this character - */ - uint64_t m_SmashablesSmashed; + /** + * The total amount of entities smashed by this character + */ + uint64_t m_SmashablesSmashed; - /** - * The total amount of quickbuilds completed by this character - */ - uint64_t m_QuickBuildsCompleted; + /** + * The total amount of quickbuilds completed by this character + */ + uint64_t m_QuickBuildsCompleted; - /** - * The total amount of enemies killd by this character - */ - uint64_t m_EnemiesSmashed; + /** + * The total amount of enemies killd by this character + */ + uint64_t m_EnemiesSmashed; - /** - * The total amount of rockets used by this character - */ - uint64_t m_RocketsUsed; + /** + * The total amount of rockets used by this character + */ + uint64_t m_RocketsUsed; - /** - * The total amount of missions completed by this character - */ - uint64_t m_MissionsCompleted; + /** + * The total amount of missions completed by this character + */ + uint64_t m_MissionsCompleted; - /** - * The total number of pets tamed by this character - */ - uint64_t m_PetsTamed; + /** + * The total number of pets tamed by this character + */ + uint64_t m_PetsTamed; - /** - * The total amount of imagination powerups collected by this character, this includes the ones in racing - */ - uint64_t m_ImaginationPowerUpsCollected; + /** + * The total amount of imagination powerups collected by this character, this includes the ones in racing + */ + uint64_t m_ImaginationPowerUpsCollected; - /** - * The total amount of life powerups collected (note: not the total amount of life gained) - */ - uint64_t m_LifePowerUpsCollected; + /** + * The total amount of life powerups collected (note: not the total amount of life gained) + */ + uint64_t m_LifePowerUpsCollected; - /** - * The total amount of armor powerups collected (note: not the total amount of armor gained) - */ - uint64_t m_ArmorPowerUpsCollected; + /** + * The total amount of armor powerups collected (note: not the total amount of armor gained) + */ + uint64_t m_ArmorPowerUpsCollected; - /** - * Total amount of meters traveled by this character - */ - uint64_t m_MetersTraveled; + /** + * Total amount of meters traveled by this character + */ + uint64_t m_MetersTraveled; - /** - * Total amount of times this character was smashed, either by other entities or by going out of bounds - */ - uint64_t m_TimesSmashed; + /** + * Total amount of times this character was smashed, either by other entities or by going out of bounds + */ + uint64_t m_TimesSmashed; - /** - * The total amount of damage inflicted on this character - */ - uint64_t m_TotalDamageTaken; + /** + * The total amount of damage inflicted on this character + */ + uint64_t m_TotalDamageTaken; - /** - * The total amount of damage healed by this character (excludes armor polish, etc) - */ - uint64_t m_TotalDamageHealed; + /** + * The total amount of damage healed by this character (excludes armor polish, etc) + */ + uint64_t m_TotalDamageHealed; - /** - * Total amount of armor repaired by this character - */ - uint64_t m_TotalArmorRepaired; + /** + * Total amount of armor repaired by this character + */ + uint64_t m_TotalArmorRepaired; - /** - * Total amount of imagination resored by this character - */ - uint64_t m_TotalImaginationRestored; + /** + * Total amount of imagination resored by this character + */ + uint64_t m_TotalImaginationRestored; - /** - * Total amount of imagination used by this character - */ - uint64_t m_TotalImaginationUsed; + /** + * Total amount of imagination used by this character + */ + uint64_t m_TotalImaginationUsed; - /** - * Amount of distance driven, mutually exclusively tracked to meters travelled based on whether the charcter - * is currently driving - */ - uint64_t m_DistanceDriven; + /** + * Amount of distance driven, mutually exclusively tracked to meters travelled based on whether the charcter + * is currently driving + */ + uint64_t m_DistanceDriven; - /** - * Time airborne in a car, currently untracked. - * Honestly, who even cares about this. - */ - uint64_t m_TimeAirborneInCar; + /** + * Time airborne in a car, currently untracked. + * Honestly, who even cares about this. + */ + uint64_t m_TimeAirborneInCar; - /** - * Amount of imagination powerups found on racing tracks being collected, generally triggered by scripts - */ - uint64_t m_RacingImaginationPowerUpsCollected; + /** + * Amount of imagination powerups found on racing tracks being collected, generally triggered by scripts + */ + uint64_t m_RacingImaginationPowerUpsCollected; - /** - * Total amount of racing imagination crates smashed, generally tracked by scripts - */ - uint64_t m_RacingImaginationCratesSmashed; + /** + * Total amount of racing imagination crates smashed, generally tracked by scripts + */ + uint64_t m_RacingImaginationCratesSmashed; - /** - * The amount of times this character triggered a car boost - */ - uint64_t m_RacingCarBoostsActivated; + /** + * The amount of times this character triggered a car boost + */ + uint64_t m_RacingCarBoostsActivated; - /** - * The amount of times a car of this character was wrecked - */ - uint64_t m_RacingTimesWrecked; + /** + * The amount of times a car of this character was wrecked + */ + uint64_t m_RacingTimesWrecked; - /** - * The amount of entities smashed by the character while driving - */ - uint64_t m_RacingSmashablesSmashed; + /** + * The amount of entities smashed by the character while driving + */ + uint64_t m_RacingSmashablesSmashed; - /** - * The total amount of races completed by this character - */ - uint64_t m_RacesFinished; + /** + * The total amount of races completed by this character + */ + uint64_t m_RacesFinished; - /** - * The total amount of races won by this character - */ - uint64_t m_FirstPlaceRaceFinishes; + /** + * The total amount of races won by this character + */ + uint64_t m_FirstPlaceRaceFinishes; - /** - * Special stats which are tracked per zone - */ - std::map m_ZoneStatistics {}; + /** + * Special stats which are tracked per zone + */ + std::map m_ZoneStatistics{}; /** * ID of the last rocket used diff --git a/dGame/dComponents/Component.cpp b/dGame/dComponents/Component.cpp index 1a38b871..ca018c29 100644 --- a/dGame/dComponents/Component.cpp +++ b/dGame/dComponents/Component.cpp @@ -1,36 +1,30 @@ #include "Component.h" -Component::Component(Entity* parent) -{ - m_Parent = parent; +Component::Component(Entity* parent) { + m_Parent = parent; } -Component::~Component() -{ - -} - -Entity* Component::GetParent() const -{ - return m_Parent; -} - -void Component::Update(float deltaTime) -{ - -} - -void Component::OnUse(Entity* originator) -{ - -} - -void Component::UpdateXml(tinyxml2::XMLDocument* doc) -{ - -} - -void Component::LoadFromXml(tinyxml2::XMLDocument *doc) { +Component::~Component() { + +} + +Entity* Component::GetParent() const { + return m_Parent; +} + +void Component::Update(float deltaTime) { + +} + +void Component::OnUse(Entity* originator) { + +} + +void Component::UpdateXml(tinyxml2::XMLDocument* doc) { + +} + +void Component::LoadFromXml(tinyxml2::XMLDocument* doc) { } diff --git a/dGame/dComponents/Component.h b/dGame/dComponents/Component.h index b84537bc..9b0df9fd 100644 --- a/dGame/dComponents/Component.h +++ b/dGame/dComponents/Component.h @@ -10,43 +10,43 @@ class Entity; class Component { public: - Component(Entity* parent); - virtual ~Component(); + Component(Entity* parent); + virtual ~Component(); - /** - * Gets the owner of this component - * @return the owner of this component - */ - Entity* GetParent() const; + /** + * Gets the owner of this component + * @return the owner of this component + */ + Entity* GetParent() const; - /** - * Updates the component in the game loop - * @param deltaTime time passed since last update - */ - virtual void Update(float deltaTime); + /** + * Updates the component in the game loop + * @param deltaTime time passed since last update + */ + virtual void Update(float deltaTime); - /** - * Event called when this component is being used, e.g. when some entity interacted with it - * @param originator - */ - virtual void OnUse(Entity* originator); + /** + * Event called when this component is being used, e.g. when some entity interacted with it + * @param originator + */ + virtual void OnUse(Entity* originator); - /** - * Save data from this componennt to character XML - * @param doc the document to write data to - */ - virtual void UpdateXml(tinyxml2::XMLDocument* doc); + /** + * Save data from this componennt to character XML + * @param doc the document to write data to + */ + virtual void UpdateXml(tinyxml2::XMLDocument* doc); - /** - * Load base data for this component from character XML - * @param doc the document to read data from - */ - virtual void LoadFromXml(tinyxml2::XMLDocument* doc); + /** + * Load base data for this component from character XML + * @param doc the document to read data from + */ + virtual void LoadFromXml(tinyxml2::XMLDocument* doc); protected: - /** - * The entity that owns this component - */ - Entity* m_Parent; + /** + * The entity that owns this component + */ + Entity* m_Parent; }; diff --git a/dGame/dComponents/ControllablePhysicsComponent.h b/dGame/dComponents/ControllablePhysicsComponent.h index 73b3bb69..bc05657c 100644 --- a/dGame/dComponents/ControllablePhysicsComponent.h +++ b/dGame/dComponents/ControllablePhysicsComponent.h @@ -18,343 +18,343 @@ class dpEntity; */ class ControllablePhysicsComponent : public Component { public: - static const uint32_t ComponentType = COMPONENT_TYPE_CONTROLLABLE_PHYSICS; - - ControllablePhysicsComponent(Entity* entity); - ~ControllablePhysicsComponent() override; - - void Update(float deltaTime) override; - void Serialize(RakNet::BitStream* outBitStream, bool bIsInitialUpdate, unsigned int& flags); - void LoadFromXml(tinyxml2::XMLDocument* doc) override; - void ResetFlags(); - void UpdateXml(tinyxml2::XMLDocument* doc) override; - - /** - * Sets the position of this entity, also ensures this update is serialized next tick. - * If the entity is static, this is a no-op. - * @param pos The position to set - */ - void SetPosition(const NiPoint3& pos); + static const uint32_t ComponentType = COMPONENT_TYPE_CONTROLLABLE_PHYSICS; - /** - * Returns the current position of the entity - * @return The current position of the entity - */ - const NiPoint3& GetPosition() const { return m_Position; } + ControllablePhysicsComponent(Entity* entity); + ~ControllablePhysicsComponent() override; - /** - * Sets the rotation of this entity, ensures this change is serialized next tick. If the entity is static, this is - * a no-op. - * @param rot the rotation to set - */ - void SetRotation(const NiQuaternion& rot); + void Update(float deltaTime) override; + void Serialize(RakNet::BitStream* outBitStream, bool bIsInitialUpdate, unsigned int& flags); + void LoadFromXml(tinyxml2::XMLDocument* doc) override; + void ResetFlags(); + void UpdateXml(tinyxml2::XMLDocument* doc) override; - /** - * Returns the current rotation of this entity - * @return the current rotation of this entity - */ - const NiQuaternion& GetRotation() const { return m_Rotation; } + /** + * Sets the position of this entity, also ensures this update is serialized next tick. + * If the entity is static, this is a no-op. + * @param pos The position to set + */ + void SetPosition(const NiPoint3& pos); - /** - * Sets the current velocity of this entity, ensures that this change is serialized next tick. If the entity is - * marked as static this is a no-op. - * @param vel the velocity to set - */ - void SetVelocity(const NiPoint3& vel); + /** + * Returns the current position of the entity + * @return The current position of the entity + */ + const NiPoint3& GetPosition() const { return m_Position; } - /** - * Returns the current velocity of this entity - * @return the current velocity of this entity - */ - const NiPoint3& GetVelocity() const { return m_Velocity; } + /** + * Sets the rotation of this entity, ensures this change is serialized next tick. If the entity is static, this is + * a no-op. + * @param rot the rotation to set + */ + void SetRotation(const NiQuaternion& rot); - /** - * Sets the angular velocity (e.g. rotational velocity) of this entity and ensures this is serialized next tick. - * If the entity is marked as static this is a no-op. - * @param vel the angular velocity to set. - */ - void SetAngularVelocity(const NiPoint3& vel); + /** + * Returns the current rotation of this entity + * @return the current rotation of this entity + */ + const NiQuaternion& GetRotation() const { return m_Rotation; } - /** - * Returns the current angular velocity of this entity - * @return the current angular velocity of this entity - */ - const NiPoint3& GetAngularVelocity() const { return m_AngularVelocity; } + /** + * Sets the current velocity of this entity, ensures that this change is serialized next tick. If the entity is + * marked as static this is a no-op. + * @param vel the velocity to set + */ + void SetVelocity(const NiPoint3& vel); - /** - * Sets the IsOnGround value, determining whether or not the entity is stuck to the ground. Note that this is mostly - * a client side flag as no server-side entities jump around and therefore this does not have to be updated server - * side. - * @param val whether the entity is on the ground. - */ - void SetIsOnGround(bool val); + /** + * Returns the current velocity of this entity + * @return the current velocity of this entity + */ + const NiPoint3& GetVelocity() const { return m_Velocity; } - /** - * Returns whether or not the entity is currently on the ground - * @return whether the entity is currently on the ground - */ - const bool GetIsOnGround() const { return m_IsOnGround; } + /** + * Sets the angular velocity (e.g. rotational velocity) of this entity and ensures this is serialized next tick. + * If the entity is marked as static this is a no-op. + * @param vel the angular velocity to set. + */ + void SetAngularVelocity(const NiPoint3& vel); - /** - * Sets the on-rail parameter, determining if a player is currently on a rail (e.g. the lamps in Ninjago). - * Also ensures that this change is serialized. - * @param val whether the player is currently on a rail - */ - void SetIsOnRail(bool val); + /** + * Returns the current angular velocity of this entity + * @return the current angular velocity of this entity + */ + const NiPoint3& GetAngularVelocity() const { return m_AngularVelocity; } - /** - * Returns whether or not this entity is currently on a rail. - * @return whether or not this entity is currently on a rail - */ - const bool GetIsOnRail() const { return m_IsOnRail; } + /** + * Sets the IsOnGround value, determining whether or not the entity is stuck to the ground. Note that this is mostly + * a client side flag as no server-side entities jump around and therefore this does not have to be updated server + * side. + * @param val whether the entity is on the ground. + */ + void SetIsOnGround(bool val); - /** - * Mark the position as dirty, forcing a serialization update next tick - * @param val whether or not the position is dirty - */ - void SetDirtyPosition(bool val); + /** + * Returns whether or not the entity is currently on the ground + * @return whether the entity is currently on the ground + */ + const bool GetIsOnGround() const { return m_IsOnGround; } - /** - * Mark the velocity as dirty, forcing a serializtion update next tick - * @param val whether or not the velocity is dirty - */ - void SetDirtyVelocity(bool val); + /** + * Sets the on-rail parameter, determining if a player is currently on a rail (e.g. the lamps in Ninjago). + * Also ensures that this change is serialized. + * @param val whether the player is currently on a rail + */ + void SetIsOnRail(bool val); - /** - * Mark the angular velocity as dirty, forcing a serialization update next tick - * @param val whether or not the angular velocity is dirty - */ - void SetDirtyAngularVelocity(bool val); + /** + * Returns whether or not this entity is currently on a rail. + * @return whether or not this entity is currently on a rail + */ + const bool GetIsOnRail() const { return m_IsOnRail; } - /** - * Sets whether or not the entity is currently wearing a jetpack - * @param val whether or not the entity is currently wearing a jetpack - */ - void SetInJetpackMode(bool val) { m_InJetpackMode = val; } + /** + * Mark the position as dirty, forcing a serialization update next tick + * @param val whether or not the position is dirty + */ + void SetDirtyPosition(bool val); - /** - * Returns whether or not the entity is currently wearing a jetpack - * @return whether or not the entity is currently wearing a jetpack - */ - const bool GetInJetpackMode() const { return m_InJetpackMode; } + /** + * Mark the velocity as dirty, forcing a serializtion update next tick + * @param val whether or not the velocity is dirty + */ + void SetDirtyVelocity(bool val); - /** - * Sets whether or not the entity is currently flying a jetpack - * @param val whether or not the entity is currently flying a jetpack - */ - void SetJetpackFlying(bool val) { m_JetpackFlying = val; } + /** + * Mark the angular velocity as dirty, forcing a serialization update next tick + * @param val whether or not the angular velocity is dirty + */ + void SetDirtyAngularVelocity(bool val); - /** - * Returns whether or not an entity is currently flying a jetpack - * @return whether or not an entity is currently flying a jetpack - */ - const bool GetJetpackFlying() const { return m_JetpackFlying; } + /** + * Sets whether or not the entity is currently wearing a jetpack + * @param val whether or not the entity is currently wearing a jetpack + */ + void SetInJetpackMode(bool val) { m_InJetpackMode = val; } - /** - * UNUSED: necessary for serialization - */ - void SetJetpackBypassChecks(bool val) { m_JetpackBypassChecks = val; } + /** + * Returns whether or not the entity is currently wearing a jetpack + * @return whether or not the entity is currently wearing a jetpack + */ + const bool GetInJetpackMode() const { return m_InJetpackMode; } - /** - * UNUSUED: necessary for serialization - */ - const bool GetJetpackBypassChecks() const { return m_JetpackBypassChecks; } + /** + * Sets whether or not the entity is currently flying a jetpack + * @param val whether or not the entity is currently flying a jetpack + */ + void SetJetpackFlying(bool val) { m_JetpackFlying = val; } - /** - * Set the jetpack effect ID - * @param effectID the effect to play while using the jetpack - */ - void SetJetpackEffectID(int effectID) { m_JetpackEffectID = effectID; } + /** + * Returns whether or not an entity is currently flying a jetpack + * @return whether or not an entity is currently flying a jetpack + */ + const bool GetJetpackFlying() const { return m_JetpackFlying; } - /** - * Returns the current jetpack effect ID - * @return the current jetpack effect ID - */ - const int GetJetpackEffectID() const { return m_JetpackEffectID; } + /** + * UNUSED: necessary for serialization + */ + void SetJetpackBypassChecks(bool val) { m_JetpackBypassChecks = val; } - /** - * Sets a speed multiplier, altering the entities speed - * @param value the multiplier to set - */ - void SetSpeedMultiplier(float value) { m_SpeedMultiplier = value; m_DirtyCheats = true; } + /** + * UNUSUED: necessary for serialization + */ + const bool GetJetpackBypassChecks() const { return m_JetpackBypassChecks; } - /** - * Returns the current speed multiplier - * @return the current speed multiplier - */ - const float GetSpeedMultiplier() const { return m_SpeedMultiplier; } + /** + * Set the jetpack effect ID + * @param effectID the effect to play while using the jetpack + */ + void SetJetpackEffectID(int effectID) { m_JetpackEffectID = effectID; } - /** - * Sets the current gravity scale, allowing the entity to move using altered gravity - * @param value the gravity value to set - */ - void SetGravityScale(float value) { m_GravityScale = value; m_DirtyCheats = true; } + /** + * Returns the current jetpack effect ID + * @return the current jetpack effect ID + */ + const int GetJetpackEffectID() const { return m_JetpackEffectID; } - /** - * Returns the current gravity scale - * @return the current gravity scale - */ - const float GetGravityScale() const { return m_GravityScale; } + /** + * Sets a speed multiplier, altering the entities speed + * @param value the multiplier to set + */ + void SetSpeedMultiplier(float value) { m_SpeedMultiplier = value; m_DirtyCheats = true; } - /** - * Sets the ignore multipliers value, allowing you to skip the serialization of speed and gravity multipliers - * @param value whether or not to ignore multipliers - */ - void SetIgnoreMultipliers(bool value) { m_IgnoreMultipliers = value; } + /** + * Returns the current speed multiplier + * @return the current speed multiplier + */ + const float GetSpeedMultiplier() const { return m_SpeedMultiplier; } - /** - * Returns the current ignore multipliers value - * @return the current ignore multipliers value - */ - const bool GetIgnoreMultipliers() const { return m_IgnoreMultipliers; } + /** + * Sets the current gravity scale, allowing the entity to move using altered gravity + * @param value the gravity value to set + */ + void SetGravityScale(float value) { m_GravityScale = value; m_DirtyCheats = true; } - /** - * Can make an entity static, making it unable to move around - * @param value whether or not the entity is static - */ - void SetStatic(const bool value) { m_Static = value; } + /** + * Returns the current gravity scale + * @return the current gravity scale + */ + const float GetGravityScale() const { return m_GravityScale; } - /** - * Returns whether or not this entity is currently static - * @return whether or not this entity is currently static - */ - bool GetStatic() const { return m_Static; } + /** + * Sets the ignore multipliers value, allowing you to skip the serialization of speed and gravity multipliers + * @param value whether or not to ignore multipliers + */ + void SetIgnoreMultipliers(bool value) { m_IgnoreMultipliers = value; } - /** - * Returns the Physics entity for the component - * @return Physics entity for the component - */ + /** + * Returns the current ignore multipliers value + * @return the current ignore multipliers value + */ + const bool GetIgnoreMultipliers() const { return m_IgnoreMultipliers; } - dpEntity* GetdpEntity() const { return m_dpEntity; } + /** + * Can make an entity static, making it unable to move around + * @param value whether or not the entity is static + */ + void SetStatic(const bool value) { m_Static = value; } - /** - * I store this in a vector because if I have 2 separate pickup radii being applied to the player, I dont know which one is correctly active. - * This method adds the pickup radius to the vector of active radii and if its larger than the current one, is applied as the new pickup radius. - */ - void AddPickupRadiusScale(float value) ; + /** + * Returns whether or not this entity is currently static + * @return whether or not this entity is currently static + */ + bool GetStatic() const { return m_Static; } - /** - * Removes the provided pickup radius scale from our list of buffs - * The recalculates what our pickup radius is. - */ - void RemovePickupRadiusScale(float value) ; + /** + * Returns the Physics entity for the component + * @return Physics entity for the component + */ - /** - * The pickup radii of this component. - * @return All active radii scales for this component. - */ - std::vector GetActivePickupRadiusScales() { return m_ActivePickupRadiusScales; }; + dpEntity* GetdpEntity() const { return m_dpEntity; } + + /** + * I store this in a vector because if I have 2 separate pickup radii being applied to the player, I dont know which one is correctly active. + * This method adds the pickup radius to the vector of active radii and if its larger than the current one, is applied as the new pickup radius. + */ + void AddPickupRadiusScale(float value); + + /** + * Removes the provided pickup radius scale from our list of buffs + * The recalculates what our pickup radius is. + */ + void RemovePickupRadiusScale(float value); + + /** + * The pickup radii of this component. + * @return All active radii scales for this component. + */ + std::vector GetActivePickupRadiusScales() { return m_ActivePickupRadiusScales; }; private: - /** - * The entity that owns this component - */ - dpEntity* m_dpEntity; + /** + * The entity that owns this component + */ + dpEntity* m_dpEntity; - /** - * Whether or not the position is dirty, forcing a serialization update of the position - */ - bool m_DirtyPosition; + /** + * Whether or not the position is dirty, forcing a serialization update of the position + */ + bool m_DirtyPosition; - /** - * The current position of the entity - */ - NiPoint3 m_Position; + /** + * The current position of the entity + */ + NiPoint3 m_Position; - /** - * The current rotation of the entity - */ - NiQuaternion m_Rotation; + /** + * The current rotation of the entity + */ + NiQuaternion m_Rotation; - /** - * Whether or not the velocity is dirty, forcing a serialization of the velocity - */ - bool m_DirtyVelocity; + /** + * Whether or not the velocity is dirty, forcing a serialization of the velocity + */ + bool m_DirtyVelocity; - /** - * The current velocity of the entity - */ - NiPoint3 m_Velocity; + /** + * The current velocity of the entity + */ + NiPoint3 m_Velocity; - /** - * Whether or not the angular velocity is dirty, forcing a serialization - */ - bool m_DirtyAngularVelocity; + /** + * Whether or not the angular velocity is dirty, forcing a serialization + */ + bool m_DirtyAngularVelocity; - /** - * The current angular velocity of the entity - */ - NiPoint3 m_AngularVelocity; + /** + * The current angular velocity of the entity + */ + NiPoint3 m_AngularVelocity; - /** - * Whether or not the entity is on the ground, generally unused - */ - bool m_IsOnGround; + /** + * Whether or not the entity is on the ground, generally unused + */ + bool m_IsOnGround; - /** - * Whether or not the entity is on a rail, e.g. in Ninjago - */ - bool m_IsOnRail; + /** + * Whether or not the entity is on a rail, e.g. in Ninjago + */ + bool m_IsOnRail; - /** - * Whether or not this entity has a jetpack equipped - */ - bool m_InJetpackMode; + /** + * Whether or not this entity has a jetpack equipped + */ + bool m_InJetpackMode; - /** - * Whether or not this entity is currently flying a jetpack - */ - bool m_JetpackFlying; + /** + * Whether or not this entity is currently flying a jetpack + */ + bool m_JetpackFlying; - /** - * Bypass jetpack checks, currently unused - */ - bool m_JetpackBypassChecks; + /** + * Bypass jetpack checks, currently unused + */ + bool m_JetpackBypassChecks; - /** - * The effect that plays while using the jetpack - */ - int32_t m_JetpackEffectID; + /** + * The effect that plays while using the jetpack + */ + int32_t m_JetpackEffectID; - /** - * The current speed multiplier, allowing an entity to run faster - */ - float m_SpeedMultiplier; + /** + * The current speed multiplier, allowing an entity to run faster + */ + float m_SpeedMultiplier; - /** - * The current gravity scale, allowing an entity to move at an altered gravity - */ - float m_GravityScale; + /** + * The current gravity scale, allowing an entity to move at an altered gravity + */ + float m_GravityScale; - /** - * Forces a serialization of the speed multiplier and the gravity scale - */ - bool m_DirtyCheats; + /** + * Forces a serialization of the speed multiplier and the gravity scale + */ + bool m_DirtyCheats; - /** - * Makes it so that the speed multiplier and gravity scale are no longer serialized if false - */ - bool m_IgnoreMultipliers; + /** + * Makes it so that the speed multiplier and gravity scale are no longer serialized if false + */ + bool m_IgnoreMultipliers; - /** - * Whether this entity is static, making it unable to move - */ - bool m_Static; + /** + * Whether this entity is static, making it unable to move + */ + bool m_Static; - /** - * Whether the pickup scale is dirty. - */ - bool m_DirtyPickupRadiusScale; + /** + * Whether the pickup scale is dirty. + */ + bool m_DirtyPickupRadiusScale; - /** - * The list of pickup radius scales for this entity - */ - std::vector m_ActivePickupRadiusScales; + /** + * The list of pickup radius scales for this entity + */ + std::vector m_ActivePickupRadiusScales; - /** - * The active pickup radius for this entity - */ - float m_PickupRadius; + /** + * The active pickup radius for this entity + */ + float m_PickupRadius; }; #endif // CONTROLLABLEPHYSICSCOMPONENT_H diff --git a/dGame/dComponents/DestroyableComponent.cpp b/dGame/dComponents/DestroyableComponent.cpp index c2532f42..1cbf7aad 100644 --- a/dGame/dComponents/DestroyableComponent.cpp +++ b/dGame/dComponents/DestroyableComponent.cpp @@ -29,21 +29,21 @@ #include "dZoneManager.h" DestroyableComponent::DestroyableComponent(Entity* parent) : Component(parent) { - m_iArmor = 0; - m_fMaxArmor = 0.0f; - m_iImagination = 0; - m_fMaxImagination = 0.0f; - m_FactionIDs = std::vector(); - m_EnemyFactionIDs = std::vector(); - m_IsSmashable = false; - m_IsDead = false; - m_IsSmashed = false; - m_IsGMImmune = false; - m_IsShielded = false; - m_DamageToAbsorb = 0; - m_HasBricks = false; - m_DirtyThreatList = false; - m_HasThreats = false; + m_iArmor = 0; + m_fMaxArmor = 0.0f; + m_iImagination = 0; + m_fMaxImagination = 0.0f; + m_FactionIDs = std::vector(); + m_EnemyFactionIDs = std::vector(); + m_IsSmashable = false; + m_IsDead = false; + m_IsSmashed = false; + m_IsGMImmune = false; + m_IsShielded = false; + m_DamageToAbsorb = 0; + m_HasBricks = false; + m_DirtyThreatList = false; + m_HasThreats = false; m_ExplodeFactor = 1.0f; m_iHealth = 0; m_fMaxHealth = 0; @@ -87,8 +87,7 @@ void DestroyableComponent::Reinitialize(LOT templateID) { SetIsSmashable(destCompData[0].isSmashable); } - } - else { + } else { SetHealth(1); SetImagination(0); SetArmor(0); @@ -102,65 +101,65 @@ void DestroyableComponent::Reinitialize(LOT templateID) { } void DestroyableComponent::Serialize(RakNet::BitStream* outBitStream, bool bIsInitialUpdate, uint32_t& flags) { - if (bIsInitialUpdate) { - outBitStream->Write0(); //Contains info about immunities this object has, but it's left out for now. - } + if (bIsInitialUpdate) { + outBitStream->Write0(); //Contains info about immunities this object has, but it's left out for now. + } - outBitStream->Write(m_DirtyHealth || bIsInitialUpdate); - if (m_DirtyHealth || bIsInitialUpdate) { - outBitStream->Write(m_iHealth); - outBitStream->Write(m_fMaxHealth); - outBitStream->Write(m_iArmor); - outBitStream->Write(m_fMaxArmor); - outBitStream->Write(m_iImagination); - outBitStream->Write(m_fMaxImagination); + outBitStream->Write(m_DirtyHealth || bIsInitialUpdate); + if (m_DirtyHealth || bIsInitialUpdate) { + outBitStream->Write(m_iHealth); + outBitStream->Write(m_fMaxHealth); + outBitStream->Write(m_iArmor); + outBitStream->Write(m_fMaxArmor); + outBitStream->Write(m_iImagination); + outBitStream->Write(m_fMaxImagination); - outBitStream->Write(m_DamageToAbsorb); - outBitStream->Write(IsImmune()); - outBitStream->Write(m_IsGMImmune); - outBitStream->Write(m_IsShielded); + outBitStream->Write(m_DamageToAbsorb); + outBitStream->Write(IsImmune()); + outBitStream->Write(m_IsGMImmune); + outBitStream->Write(m_IsShielded); - outBitStream->Write(m_fMaxHealth); - outBitStream->Write(m_fMaxArmor); - outBitStream->Write(m_fMaxImagination); + outBitStream->Write(m_fMaxHealth); + outBitStream->Write(m_fMaxArmor); + outBitStream->Write(m_fMaxImagination); outBitStream->Write(uint32_t(m_FactionIDs.size())); for (size_t i = 0; i < m_FactionIDs.size(); ++i) { outBitStream->Write(m_FactionIDs[i]); } - outBitStream->Write(m_IsSmashable); + outBitStream->Write(m_IsSmashable); - if (bIsInitialUpdate) { - outBitStream->Write(m_IsDead); - outBitStream->Write(m_IsSmashed); + if (bIsInitialUpdate) { + outBitStream->Write(m_IsDead); + outBitStream->Write(m_IsSmashed); - if (m_IsSmashable) { - outBitStream->Write(m_HasBricks); + if (m_IsSmashable) { + outBitStream->Write(m_HasBricks); - if (m_ExplodeFactor != 1.0f) { - outBitStream->Write1(); - outBitStream->Write(m_ExplodeFactor); - } else { - outBitStream->Write0(); - } - } - } + if (m_ExplodeFactor != 1.0f) { + outBitStream->Write1(); + outBitStream->Write(m_ExplodeFactor); + } else { + outBitStream->Write0(); + } + } + } m_DirtyHealth = false; - } + } - if (m_DirtyThreatList || bIsInitialUpdate) { - outBitStream->Write1(); - outBitStream->Write(m_HasThreats); + if (m_DirtyThreatList || bIsInitialUpdate) { + outBitStream->Write1(); + outBitStream->Write(m_HasThreats); m_DirtyThreatList = false; - } else { - outBitStream->Write0(); - } + } else { + outBitStream->Write0(); + } } void DestroyableComponent::LoadFromXml(tinyxml2::XMLDocument* doc) { - tinyxml2::XMLElement* dest = doc->FirstChildElement("obj")->FirstChildElement("dest"); + tinyxml2::XMLElement* dest = doc->FirstChildElement("obj")->FirstChildElement("dest"); if (!dest) { Game::logger->Log("DestroyableComponent", "Failed to find dest tag!"); return; @@ -173,16 +172,16 @@ void DestroyableComponent::LoadFromXml(tinyxml2::XMLDocument* doc) { } dest->QueryAttribute("hc", &m_iHealth); - dest->QueryAttribute("hm", &m_fMaxHealth); - dest->QueryAttribute("im", &m_fMaxImagination); - dest->QueryAttribute("ic", &m_iImagination); - dest->QueryAttribute("ac", &m_iArmor); - dest->QueryAttribute("am", &m_fMaxArmor); - m_DirtyHealth = true; + dest->QueryAttribute("hm", &m_fMaxHealth); + dest->QueryAttribute("im", &m_fMaxImagination); + dest->QueryAttribute("ic", &m_iImagination); + dest->QueryAttribute("ac", &m_iArmor); + dest->QueryAttribute("am", &m_fMaxArmor); + m_DirtyHealth = true; } void DestroyableComponent::UpdateXml(tinyxml2::XMLDocument* doc) { - tinyxml2::XMLElement* dest = doc->FirstChildElement("obj")->FirstChildElement("dest"); + tinyxml2::XMLElement* dest = doc->FirstChildElement("obj")->FirstChildElement("dest"); if (!dest) { Game::logger->Log("DestroyableComponent", "Failed to find dest tag!"); return; @@ -195,11 +194,11 @@ void DestroyableComponent::UpdateXml(tinyxml2::XMLDocument* doc) { } dest->SetAttribute("hc", m_iHealth); - dest->SetAttribute("hm", m_fMaxHealth); - dest->SetAttribute("im", m_fMaxImagination); - dest->SetAttribute("ic", m_iImagination); - dest->SetAttribute("ac", m_iArmor); - dest->SetAttribute("am", m_fMaxArmor); + dest->SetAttribute("hm", m_fMaxHealth); + dest->SetAttribute("im", m_fMaxImagination); + dest->SetAttribute("ic", m_iImagination); + dest->SetAttribute("ac", m_iArmor); + dest->SetAttribute("am", m_fMaxArmor); } void DestroyableComponent::SetHealth(int32_t value) { @@ -207,7 +206,7 @@ void DestroyableComponent::SetHealth(int32_t value) { auto* characterComponent = m_Parent->GetComponent(); if (characterComponent != nullptr) { - characterComponent->TrackHealthDelta(value - m_iHealth); + characterComponent->TrackHealthDelta(value - m_iHealth); } m_iHealth = value; @@ -242,17 +241,17 @@ void DestroyableComponent::SetMaxHealth(float value, bool playAnim) { } void DestroyableComponent::SetArmor(int32_t value) { - m_DirtyHealth = true; + m_DirtyHealth = true; // If Destroyable Component already has zero armor do not trigger the passive ability again. bool hadArmor = m_iArmor > 0; - auto* characterComponent = m_Parent->GetComponent(); - if (characterComponent != nullptr) { - characterComponent->TrackArmorDelta(value - m_iArmor); - } + auto* characterComponent = m_Parent->GetComponent(); + if (characterComponent != nullptr) { + characterComponent->TrackArmorDelta(value - m_iArmor); + } - m_iArmor = value; + m_iArmor = value; auto* inventroyComponent = m_Parent->GetComponent(); if (m_iArmor == 0 && inventroyComponent != nullptr && hadArmor) { @@ -261,8 +260,8 @@ void DestroyableComponent::SetArmor(int32_t value) { } void DestroyableComponent::SetMaxArmor(float value, bool playAnim) { - m_DirtyHealth = true; - m_fMaxArmor = value; + m_DirtyHealth = true; + m_fMaxArmor = value; if (m_iArmor > m_fMaxArmor) { m_iArmor = m_fMaxArmor; @@ -287,14 +286,14 @@ void DestroyableComponent::SetMaxArmor(float value, bool playAnim) { } void DestroyableComponent::SetImagination(int32_t value) { - m_DirtyHealth = true; + m_DirtyHealth = true; - auto* characterComponent = m_Parent->GetComponent(); - if (characterComponent != nullptr) { - characterComponent->TrackImaginationDelta(value - m_iImagination); - } + auto* characterComponent = m_Parent->GetComponent(); + if (characterComponent != nullptr) { + characterComponent->TrackImaginationDelta(value - m_iImagination); + } - m_iImagination = value; + m_iImagination = value; auto* inventroyComponent = m_Parent->GetComponent(); if (m_iImagination == 0 && inventroyComponent != nullptr) { @@ -303,10 +302,10 @@ void DestroyableComponent::SetImagination(int32_t value) { } void DestroyableComponent::SetMaxImagination(float value, bool playAnim) { - m_DirtyHealth = true; + m_DirtyHealth = true; // Used for playAnim if opted in for. int32_t difference = static_cast(std::abs(m_fMaxImagination - value)); - m_fMaxImagination = value; + m_fMaxImagination = value; if (m_iImagination > m_fMaxImagination) { m_iImagination = m_fMaxImagination; @@ -329,32 +328,27 @@ void DestroyableComponent::SetMaxImagination(float value, bool playAnim) { EntityManager::Instance()->SerializeEntity(m_Parent); } -void DestroyableComponent::SetDamageToAbsorb(int32_t value) -{ +void DestroyableComponent::SetDamageToAbsorb(int32_t value) { m_DirtyHealth = true; m_DamageToAbsorb = value; } -void DestroyableComponent::SetDamageReduction(int32_t value) -{ +void DestroyableComponent::SetDamageReduction(int32_t value) { m_DirtyHealth = true; m_DamageReduction = value; } -void DestroyableComponent::SetIsImmune(bool value) -{ +void DestroyableComponent::SetIsImmune(bool value) { m_DirtyHealth = true; m_ImmuneStacks = value ? 1 : 0; } -void DestroyableComponent::SetIsGMImmune(bool value) -{ +void DestroyableComponent::SetIsGMImmune(bool value) { m_DirtyHealth = true; m_IsGMImmune = value; } -void DestroyableComponent::SetIsShielded(bool value) -{ +void DestroyableComponent::SetIsShielded(bool value) { m_DirtyHealth = true; m_IsShielded = value; } @@ -365,12 +359,12 @@ void DestroyableComponent::AddFaction(const int32_t factionID, const bool ignore return; } - m_FactionIDs.push_back(factionID); - m_DirtyHealth = true; + m_FactionIDs.push_back(factionID); + m_DirtyHealth = true; auto query = CDClientDatabase::CreatePreppedStmt( "SELECT enemyList FROM Factions WHERE faction = ?;"); - query.bind(1, (int) factionID); + query.bind(1, (int)factionID); auto result = query.execQuery(); @@ -390,13 +384,11 @@ void DestroyableComponent::AddFaction(const int32_t factionID, const bool ignore auto exclude = std::find(m_FactionIDs.begin(), m_FactionIDs.end(), id) != m_FactionIDs.end(); - if (!exclude) - { + if (!exclude) { exclude = std::find(m_EnemyFactionIDs.begin(), m_EnemyFactionIDs.end(), id) != m_EnemyFactionIDs.end(); } - if (exclude) - { + if (exclude) { continue; } @@ -406,60 +398,56 @@ void DestroyableComponent::AddFaction(const int32_t factionID, const bool ignore result.finalize(); } -bool DestroyableComponent::IsEnemy (const Entity* other) const { - const auto* otherDestroyableComponent = other->GetComponent(); - if (otherDestroyableComponent != nullptr) { - for (const auto enemyFaction : m_EnemyFactionIDs) { - for (const auto otherFaction : otherDestroyableComponent->GetFactionIDs()) { - if (enemyFaction == otherFaction) - return true; - } - } - } +bool DestroyableComponent::IsEnemy(const Entity* other) const { + const auto* otherDestroyableComponent = other->GetComponent(); + if (otherDestroyableComponent != nullptr) { + for (const auto enemyFaction : m_EnemyFactionIDs) { + for (const auto otherFaction : otherDestroyableComponent->GetFactionIDs()) { + if (enemyFaction == otherFaction) + return true; + } + } + } - return false; + return false; } -bool DestroyableComponent::IsFriend (const Entity* other) const { - const auto* otherDestroyableComponent = other->GetComponent(); - if (otherDestroyableComponent != nullptr) { - for (const auto enemyFaction : m_EnemyFactionIDs) { - for (const auto otherFaction : otherDestroyableComponent->GetFactionIDs()) { - if (enemyFaction == otherFaction) - return false; - } - } +bool DestroyableComponent::IsFriend(const Entity* other) const { + const auto* otherDestroyableComponent = other->GetComponent(); + if (otherDestroyableComponent != nullptr) { + for (const auto enemyFaction : m_EnemyFactionIDs) { + for (const auto otherFaction : otherDestroyableComponent->GetFactionIDs()) { + if (enemyFaction == otherFaction) + return false; + } + } - return true; - } + return true; + } - return false; + return false; } -void DestroyableComponent::AddEnemyFaction(int32_t factionID) -{ +void DestroyableComponent::AddEnemyFaction(int32_t factionID) { m_EnemyFactionIDs.push_back(factionID); } void DestroyableComponent::SetIsSmashable(bool value) { - m_DirtyHealth = true; - m_IsSmashable = value; - //m_HasBricks = value; + m_DirtyHealth = true; + m_IsSmashable = value; + //m_HasBricks = value; } -void DestroyableComponent::SetAttacksToBlock(const uint32_t value) -{ +void DestroyableComponent::SetAttacksToBlock(const uint32_t value) { m_AttacksToBlock = value; } -bool DestroyableComponent::IsImmune() const -{ +bool DestroyableComponent::IsImmune() const { return m_ImmuneStacks > 0 || m_IsGMImmune; } -bool DestroyableComponent::IsKnockbackImmune() const -{ +bool DestroyableComponent::IsKnockbackImmune() const { auto* characterComponent = m_Parent->GetComponent(); auto* inventoryComponent = m_Parent->GetComponent(); @@ -468,7 +456,7 @@ bool DestroyableComponent::IsKnockbackImmune() const ItemSetPassiveAbilityID::EngineerRank2, ItemSetPassiveAbilityID::EngineerRank3, ItemSetPassiveAbilityID::SummonerRank2, ItemSetPassiveAbilityID::SummonerRank3, ItemSetPassiveAbilityID::InventorRank2, ItemSetPassiveAbilityID::InventorRank3, - }, 5); + }, 5); if (hasPassive) { return true; @@ -478,52 +466,43 @@ bool DestroyableComponent::IsKnockbackImmune() const return IsImmune() || m_IsShielded || m_AttacksToBlock > 0; } -bool DestroyableComponent::HasFaction(int32_t factionID) const -{ +bool DestroyableComponent::HasFaction(int32_t factionID) const { return std::find(m_FactionIDs.begin(), m_FactionIDs.end(), factionID) != m_FactionIDs.end(); } -LWOOBJID DestroyableComponent::GetKillerID() const -{ +LWOOBJID DestroyableComponent::GetKillerID() const { return m_KillerID; } -Entity* DestroyableComponent::GetKiller() const -{ +Entity* DestroyableComponent::GetKiller() const { return EntityManager::Instance()->GetEntity(m_KillerID); } -bool DestroyableComponent::CheckValidity(const LWOOBJID target, const bool ignoreFactions, const bool targetEnemy, const bool targetFriend) const -{ +bool DestroyableComponent::CheckValidity(const LWOOBJID target, const bool ignoreFactions, const bool targetEnemy, const bool targetFriend) const { auto* targetEntity = EntityManager::Instance()->GetEntity(target); - if (targetEntity == nullptr) - { + if (targetEntity == nullptr) { Game::logger->Log("DestroyableComponent", "Invalid entity for checking validity (%llu)!", target); return false; } auto* targetDestroyable = targetEntity->GetComponent(); - if (targetDestroyable == nullptr) - { + if (targetDestroyable == nullptr) { return false; } auto* targetQuickbuild = targetEntity->GetComponent(); - if (targetQuickbuild != nullptr) - { + if (targetQuickbuild != nullptr) { const auto state = targetQuickbuild->GetState(); - if (state != REBUILD_COMPLETED) - { + if (state != REBUILD_COMPLETED) { return false; } } - if (ignoreFactions) - { + if (ignoreFactions) { return true; } @@ -536,8 +515,7 @@ bool DestroyableComponent::CheckValidity(const LWOOBJID target, const bool ignor } -void DestroyableComponent::Heal(const uint32_t health) -{ +void DestroyableComponent::Heal(const uint32_t health) { auto current = static_cast(GetHealth()); const auto max = static_cast(GetMaxHealth()); @@ -551,8 +529,7 @@ void DestroyableComponent::Heal(const uint32_t health) } -void DestroyableComponent::Imagine(const int32_t deltaImagination) -{ +void DestroyableComponent::Imagine(const int32_t deltaImagination) { auto current = static_cast(GetImagination()); const auto max = static_cast(GetMaxImagination()); @@ -560,8 +537,7 @@ void DestroyableComponent::Imagine(const int32_t deltaImagination) current = std::min(current, max); - if (current < 0) - { + if (current < 0) { current = 0; } @@ -571,8 +547,7 @@ void DestroyableComponent::Imagine(const int32_t deltaImagination) } -void DestroyableComponent::Repair(const uint32_t armor) -{ +void DestroyableComponent::Repair(const uint32_t armor) { auto current = static_cast(GetArmor()); const auto max = static_cast(GetMaxArmor()); @@ -586,34 +561,26 @@ void DestroyableComponent::Repair(const uint32_t armor) } -void DestroyableComponent::Damage(uint32_t damage, const LWOOBJID source, uint32_t skillID, bool echo) -{ - if (GetHealth() <= 0) - { +void DestroyableComponent::Damage(uint32_t damage, const LWOOBJID source, uint32_t skillID, bool echo) { + if (GetHealth() <= 0) { return; } - if (IsImmune()) - { + if (IsImmune()) { return; } - if (m_AttacksToBlock > 0) - { + if (m_AttacksToBlock > 0) { m_AttacksToBlock--; return; } // If this entity has damage reduction, reduce the damage to a minimum of 1 - if (m_DamageReduction > 0 && damage > 0) - { - if (damage > m_DamageReduction) - { + if (m_DamageReduction > 0 && damage > 0) { + if (damage > m_DamageReduction) { damage -= m_DamageReduction; - } - else - { + } else { damage = 1; } } @@ -641,13 +608,11 @@ void DestroyableComponent::Damage(uint32_t damage, const LWOOBJID source, uint32 SetHealth(health); SetIsShielded(absorb > 0); - if (m_Parent->GetLOT() != 1) - { + if (m_Parent->GetLOT() != 1) { echo = true; } - if (echo) - { + if (echo) { EntityManager::Instance()->SerializeEntity(m_Parent); } @@ -656,15 +621,13 @@ void DestroyableComponent::Damage(uint32_t damage, const LWOOBJID source, uint32 m_Parent->OnHitOrHealResult(attacker, sourceDamage); for (const auto& cb : m_OnHitCallbacks) { - cb(attacker); + cb(attacker); } - if (health != 0) - { + if (health != 0) { auto* combatComponent = m_Parent->GetComponent(); - if (combatComponent != nullptr) - { + if (combatComponent != nullptr) { combatComponent->Taunt(source, sourceDamage * 10); // * 10 is arbatrary } @@ -673,10 +636,8 @@ void DestroyableComponent::Damage(uint32_t damage, const LWOOBJID source, uint32 Smash(source, eKillType::VIOLENT, u"", skillID); } -void DestroyableComponent::Smash(const LWOOBJID source, const eKillType killType, const std::u16string& deathType, uint32_t skillID) -{ - if (m_iHealth > 0) - { +void DestroyableComponent::Smash(const LWOOBJID source, const eKillType killType, const std::u16string& deathType, uint32_t skillID) { + if (m_iHealth > 0) { SetArmor(0); SetHealth(0); @@ -687,8 +648,7 @@ void DestroyableComponent::Smash(const LWOOBJID source, const eKillType killType auto* owner = EntityManager::Instance()->GetEntity(source); - if (owner != nullptr) - { + if (owner != nullptr) { owner = owner->GetOwner(); // If the owner is overwritten, we collect that here auto* team = TeamManager::Instance()->GetTeam(owner->GetObjectID()); @@ -697,19 +657,15 @@ void DestroyableComponent::Smash(const LWOOBJID source, const eKillType killType auto* inventoryComponent = owner->GetComponent(); - if (inventoryComponent != nullptr && isEnemy) - { + if (inventoryComponent != nullptr && isEnemy) { inventoryComponent->TriggerPassiveAbility(PassiveAbilityTrigger::EnemySmashed); } auto* missions = owner->GetComponent(); - if (missions != nullptr) - { - if (team != nullptr && isEnemy) - { - for (const auto memberId : team->members) - { + if (missions != nullptr) { + if (team != nullptr && isEnemy) { + for (const auto memberId : team->members) { auto* member = EntityManager::Instance()->GetEntity(memberId); if (member == nullptr) continue; @@ -721,9 +677,7 @@ void DestroyableComponent::Smash(const LWOOBJID source, const eKillType killType memberMissions->Progress(MissionTaskType::MISSION_TASK_TYPE_SMASH, m_Parent->GetLOT()); memberMissions->Progress(MissionTaskType::MISSION_TASK_TYPE_SKILL, m_Parent->GetLOT(), skillID); } - } - else - { + } else { missions->Progress(MissionTaskType::MISSION_TASK_TYPE_SMASH, m_Parent->GetLOT()); missions->Progress(MissionTaskType::MISSION_TASK_TYPE_SKILL, m_Parent->GetLOT(), skillID); } @@ -735,14 +689,11 @@ void DestroyableComponent::Smash(const LWOOBJID source, const eKillType killType GameMessages::SendDie(m_Parent, source, source, true, killType, deathType, 0, 0, 0, isPlayer, false, 1); //NANI?! - if (!isPlayer) - { - if (owner != nullptr) - { + if (!isPlayer) { + if (owner != nullptr) { auto* team = TeamManager::Instance()->GetTeam(owner->GetObjectID()); - if (team != nullptr && m_Parent->GetComponent() != nullptr) - { + if (team != nullptr && m_Parent->GetComponent() != nullptr) { LWOOBJID specificOwner = LWOOBJID_EMPTY; auto* scriptedActivityComponent = m_Parent->GetComponent(); uint32_t teamSize = team->members.size(); @@ -757,9 +708,8 @@ void DestroyableComponent::Smash(const LWOOBJID source, const eKillType killType auto* member = EntityManager::Instance()->GetEntity(specificOwner); - if (member) LootGenerator::Instance().DropLoot(member, m_Parent, lootMatrixId, GetMinCoins(), GetMaxCoins()); - } - else { + if (member) LootGenerator::Instance().DropLoot(member, m_Parent, lootMatrixId, GetMinCoins(), GetMaxCoins()); + } else { for (const auto memberId : team->members) { // Free for all auto* member = EntityManager::Instance()->GetEntity(memberId); @@ -768,32 +718,25 @@ void DestroyableComponent::Smash(const LWOOBJID source, const eKillType killType LootGenerator::Instance().DropLoot(member, m_Parent, lootMatrixId, GetMinCoins(), GetMaxCoins()); } } - } - else { // drop loot for non team user + } else { // drop loot for non team user LootGenerator::Instance().DropLoot(owner, m_Parent, GetLootMatrixID(), GetMinCoins(), GetMaxCoins()); } } - } - else - { + } else { //Check if this zone allows coin drops - if (dZoneManager::Instance()->GetPlayerLoseCoinOnDeath()) - { + if (dZoneManager::Instance()->GetPlayerLoseCoinOnDeath()) { auto* character = m_Parent->GetCharacter(); uint64_t coinsTotal = character->GetCoins(); - if (coinsTotal > 0) - { + if (coinsTotal > 0) { uint64_t coinsToLoose = 1; - if (coinsTotal >= 200) - { + if (coinsTotal >= 200) { float hundreth = (coinsTotal / 100.0f); coinsToLoose = static_cast(hundreth); } - if (coinsToLoose > 10000) - { + if (coinsToLoose > 10000) { coinsToLoose = 10000; } @@ -804,19 +747,19 @@ void DestroyableComponent::Smash(const LWOOBJID source, const eKillType killType } } - Entity* zoneControl = EntityManager::Instance()->GetZoneControlEntity(); - for (CppScripts::Script* script : CppScripts::GetEntityScripts(zoneControl)) { - script->OnPlayerDied(zoneControl, m_Parent); - } + Entity* zoneControl = EntityManager::Instance()->GetZoneControlEntity(); + for (CppScripts::Script* script : CppScripts::GetEntityScripts(zoneControl)) { + script->OnPlayerDied(zoneControl, m_Parent); + } - std::vector scriptedActs = EntityManager::Instance()->GetEntitiesByComponent(COMPONENT_TYPE_SCRIPTED_ACTIVITY); - for (Entity* scriptEntity : scriptedActs) { - if (scriptEntity->GetObjectID() != zoneControl->GetObjectID()) { // Don't want to trigger twice on instance worlds - for (CppScripts::Script* script : CppScripts::GetEntityScripts(scriptEntity)) { - script->OnPlayerDied(scriptEntity, m_Parent); - } - } - } + std::vector scriptedActs = EntityManager::Instance()->GetEntitiesByComponent(COMPONENT_TYPE_SCRIPTED_ACTIVITY); + for (Entity* scriptEntity : scriptedActs) { + if (scriptEntity->GetObjectID() != zoneControl->GetObjectID()) { // Don't want to trigger twice on instance worlds + for (CppScripts::Script* script : CppScripts::GetEntityScripts(scriptEntity)) { + script->OnPlayerDied(scriptEntity, m_Parent); + } + } + } } m_Parent->Kill(owner); @@ -829,18 +772,15 @@ void DestroyableComponent::SetFaction(int32_t factionID, bool ignoreChecks) { AddFaction(factionID, ignoreChecks); } -void DestroyableComponent::PushImmunity(int32_t stacks) -{ +void DestroyableComponent::PushImmunity(int32_t stacks) { m_ImmuneStacks += stacks; } -void DestroyableComponent::PopImmunity(int32_t stacks) -{ +void DestroyableComponent::PopImmunity(int32_t stacks) { m_ImmuneStacks -= stacks; } -void DestroyableComponent::FixStats() -{ +void DestroyableComponent::FixStats() { auto* entity = GetParent(); if (entity == nullptr) return; @@ -853,8 +793,7 @@ void DestroyableComponent::FixStats() auto* destroyableComponent = entity->GetComponent(); // If any of the components are nullptr, return - if (skillComponent == nullptr || buffComponent == nullptr || missionComponent == nullptr || inventoryComponent == nullptr || destroyableComponent == nullptr) - { + if (skillComponent == nullptr || buffComponent == nullptr || missionComponent == nullptr || inventoryComponent == nullptr || destroyableComponent == nullptr) { return; } @@ -866,13 +805,11 @@ void DestroyableComponent::FixStats() // Unequip all items auto equipped = inventoryComponent->GetEquippedItems(); - for (auto& equippedItem : equipped) - { + for (auto& equippedItem : equipped) { // Get the item with the item ID auto* item = inventoryComponent->FindItemById(equippedItem.second.id); - if (item == nullptr) - { + if (item == nullptr) { continue; } @@ -886,12 +823,10 @@ void DestroyableComponent::FixStats() int32_t maxImagination = 0; // Go through all completed missions and add the reward stats - for (auto& pair : missionComponent->GetMissions()) - { + for (auto& pair : missionComponent->GetMissions()) { auto* mission = pair.second; - if (!mission->IsComplete()) - { + if (!mission->IsComplete()) { continue; } @@ -911,13 +846,11 @@ void DestroyableComponent::FixStats() buffComponent->ReApplyBuffs(); // Requip all items - for (auto& equippedItem : equipped) - { + for (auto& equippedItem : equipped) { // Get the item with the item ID auto* item = inventoryComponent->FindItemById(equippedItem.second.id); - if (item == nullptr) - { + if (item == nullptr) { continue; } @@ -945,5 +878,5 @@ void DestroyableComponent::FixStats() } void DestroyableComponent::AddOnHitCallback(const std::function& callback) { - m_OnHitCallbacks.push_back(callback); + m_OnHitCallbacks.push_back(callback); } diff --git a/dGame/dComponents/DestroyableComponent.h b/dGame/dComponents/DestroyableComponent.h index 9d2b228f..a403717b 100644 --- a/dGame/dComponents/DestroyableComponent.h +++ b/dGame/dComponents/DestroyableComponent.h @@ -13,542 +13,542 @@ */ class DestroyableComponent : public Component { public: - static const uint32_t ComponentType = COMPONENT_TYPE_DESTROYABLE; - - DestroyableComponent(Entity* parentEntity); - ~DestroyableComponent() override; + static const uint32_t ComponentType = COMPONENT_TYPE_DESTROYABLE; - void Serialize(RakNet::BitStream* outBitStream, bool bIsInitialUpdate, uint32_t& flags); - void LoadFromXml(tinyxml2::XMLDocument* doc) override; - void UpdateXml(tinyxml2::XMLDocument* doc) override; + DestroyableComponent(Entity* parentEntity); + ~DestroyableComponent() override; - /** - * Initializes the component using a different LOT - * @param templateID the ID to use for initialization - */ + void Serialize(RakNet::BitStream* outBitStream, bool bIsInitialUpdate, uint32_t& flags); + void LoadFromXml(tinyxml2::XMLDocument* doc) override; + void UpdateXml(tinyxml2::XMLDocument* doc) override; + + /** + * Initializes the component using a different LOT + * @param templateID the ID to use for initialization + */ void Reinitialize(LOT templateID); - /** - * Sets the health of this entity. Makes sure this is serialized on the next tick and if this is a character its - * stats will also update. - * @param value the new health value - */ - void SetHealth(int32_t value); + /** + * Sets the health of this entity. Makes sure this is serialized on the next tick and if this is a character its + * stats will also update. + * @param value the new health value + */ + void SetHealth(int32_t value); - /** - * Heals the entity by some delta amount - * @param health the delta amount to heal - */ - void Heal(uint32_t health); + /** + * Heals the entity by some delta amount + * @param health the delta amount to heal + */ + void Heal(uint32_t health); - /** - * Returns the current health of this entity - * @return the current health of this entity - */ - int32_t GetHealth() const { return m_iHealth; } + /** + * Returns the current health of this entity + * @return the current health of this entity + */ + int32_t GetHealth() const { return m_iHealth; } - /** - * Updates the max health this entity has (e.g. what it can heal to), and optionally displays a UI animation indicating that - * @param value the max health value to set - * @param playAnim whether or not to play a UI animation indicating the change in max health - */ - void SetMaxHealth(float value, bool playAnim = false); + /** + * Updates the max health this entity has (e.g. what it can heal to), and optionally displays a UI animation indicating that + * @param value the max health value to set + * @param playAnim whether or not to play a UI animation indicating the change in max health + */ + void SetMaxHealth(float value, bool playAnim = false); - /** - * Returns the curent max health of this entity - * @return the current max health of this entity - */ - float GetMaxHealth() const { return m_fMaxHealth; } + /** + * Returns the curent max health of this entity + * @return the current max health of this entity + */ + float GetMaxHealth() const { return m_fMaxHealth; } - /** - * Sets the armor for this entity. This also makes sure this change is serialized and if this is a character it also - * updates their stats. - * @param value the armor value to set - */ - void SetArmor(int32_t value); + /** + * Sets the armor for this entity. This also makes sure this change is serialized and if this is a character it also + * updates their stats. + * @param value the armor value to set + */ + void SetArmor(int32_t value); - /** - * Repairs armor of this entity, updating it by a delta amount - * @param armor the amount of armor to repair - */ - void Repair(uint32_t armor); + /** + * Repairs armor of this entity, updating it by a delta amount + * @param armor the amount of armor to repair + */ + void Repair(uint32_t armor); - /** - * Returns the current armor value for the entity - * @return the current armor value for the entity - */ - int32_t GetArmor() const { return m_iArmor; } + /** + * Returns the current armor value for the entity + * @return the current armor value for the entity + */ + int32_t GetArmor() const { return m_iArmor; } - /** - * Updates the max armor this entity has (e.g. what it can heal to), and optionally displays a UI animation indicating that - * @param value the max armor value to set - * @param playAnim whether or not to play a UI animation indicating the change in max armor - */ - void SetMaxArmor(float value, bool playAnim = false); + /** + * Updates the max armor this entity has (e.g. what it can heal to), and optionally displays a UI animation indicating that + * @param value the max armor value to set + * @param playAnim whether or not to play a UI animation indicating the change in max armor + */ + void SetMaxArmor(float value, bool playAnim = false); - /** - * Returns the current maximum armor this entity can have - * @return the current maximum armor this entity can have - */ - float GetMaxArmor() const { return m_fMaxArmor; } + /** + * Returns the current maximum armor this entity can have + * @return the current maximum armor this entity can have + */ + float GetMaxArmor() const { return m_fMaxArmor; } - /** - * Sets the imagination value for this entity. Ensures that the change is serialized and if this is a character - * their stats will be updated. Can also trigger the assembly passive ability to restore on 0 imag. - * @param value - */ - void SetImagination(int32_t value); + /** + * Sets the imagination value for this entity. Ensures that the change is serialized and if this is a character + * their stats will be updated. Can also trigger the assembly passive ability to restore on 0 imag. + * @param value + */ + void SetImagination(int32_t value); - /** - * Updates the imagination of this entity by a delta amount - * @param deltaImagination the imagination to update - */ - void Imagine(int32_t deltaImagination); + /** + * Updates the imagination of this entity by a delta amount + * @param deltaImagination the imagination to update + */ + void Imagine(int32_t deltaImagination); - /** - * Returns the current imagination value of this entity - * @return the current imagination value of this entity - */ - int32_t GetImagination() const { return m_iImagination; } + /** + * Returns the current imagination value of this entity + * @return the current imagination value of this entity + */ + int32_t GetImagination() const { return m_iImagination; } - /** - * Updates the max imagination this entity has (e.g. what it can heal to), and optionally displays a UI animation indicating that - * @param value the max imagination value to set - * @param playAnim whether or not to play a UI animation indicating the change in max imagination - */ - void SetMaxImagination(float value, bool playAnim = false); + /** + * Updates the max imagination this entity has (e.g. what it can heal to), and optionally displays a UI animation indicating that + * @param value the max imagination value to set + * @param playAnim whether or not to play a UI animation indicating the change in max imagination + */ + void SetMaxImagination(float value, bool playAnim = false); - /** - * Returns the current max imagination value - * @return the current max imagination value - */ - float GetMaxImagination() const { return m_fMaxImagination; } + /** + * Returns the current max imagination value + * @return the current max imagination value + */ + float GetMaxImagination() const { return m_fMaxImagination; } - /** - * Sets the damage this entity can absorb before getting hurt, also serializes this change. - * @param value the damage to absorb - */ - void SetDamageToAbsorb(int32_t value); + /** + * Sets the damage this entity can absorb before getting hurt, also serializes this change. + * @param value the damage to absorb + */ + void SetDamageToAbsorb(int32_t value); - /** - * Returns the current damage to absorb - * @return the current damage to absorb - */ - int32_t GetDamageToAbsorb() const { return m_DamageToAbsorb; } + /** + * Returns the current damage to absorb + * @return the current damage to absorb + */ + int32_t GetDamageToAbsorb() const { return m_DamageToAbsorb; } - /** - * Sets the reduced damage value for each attack for this entity, also serializes that change. - * @param value the damage to reduce for each attack - */ - void SetDamageReduction(int32_t value); + /** + * Sets the reduced damage value for each attack for this entity, also serializes that change. + * @param value the damage to reduce for each attack + */ + void SetDamageReduction(int32_t value); - /** - * Returns the current damage reduction value - * @return the current damage reduction value - */ - int32_t GetDamageReduction() const { return m_DamageReduction; } + /** + * Returns the current damage reduction value + * @return the current damage reduction value + */ + int32_t GetDamageReduction() const { return m_DamageReduction; } - /** - * Sets whether or not this entity is immune to attacks - * @param value whether or not this entity is immune to attacks - */ - void SetIsImmune(bool value); + /** + * Sets whether or not this entity is immune to attacks + * @param value whether or not this entity is immune to attacks + */ + void SetIsImmune(bool value); - /** - * Returns whether or not this entity is immune to attacks - * @return whether or not this entity is immune to attacks - */ - bool IsImmune() const; + /** + * Returns whether or not this entity is immune to attacks + * @return whether or not this entity is immune to attacks + */ + bool IsImmune() const; - /** - * Sets if this entity has GM immunity, making it not killable - * @param value the GM immunity of this entity - */ - void SetIsGMImmune(bool value); + /** + * Sets if this entity has GM immunity, making it not killable + * @param value the GM immunity of this entity + */ + void SetIsGMImmune(bool value); - /** - * Returns whether or not this entity has GM immunity - * @return whether or not this entity has GM immunity - */ - bool GetIsGMImmune() const { return m_IsGMImmune; } + /** + * Returns whether or not this entity has GM immunity + * @return whether or not this entity has GM immunity + */ + bool GetIsGMImmune() const { return m_IsGMImmune; } - /** - * Sets whether or not this entity is shielded for a certain amount of damage - * @param value whether or not this entity is shielded for a certain amount of damage - */ - void SetIsShielded(bool value); + /** + * Sets whether or not this entity is shielded for a certain amount of damage + * @param value whether or not this entity is shielded for a certain amount of damage + */ + void SetIsShielded(bool value); - /** - * Returns if this entity is currently shielded from damage - * @return if this entity is currently shielded from damage - */ - bool GetIsShielded() const { return m_IsShielded; } + /** + * Returns if this entity is currently shielded from damage + * @return if this entity is currently shielded from damage + */ + bool GetIsShielded() const { return m_IsShielded; } - /** - * Adds a faction to the faction list of this entity, potentially making more factions friendly. Fetches the info - * from the CDClient. - * @param factionID the faction ID to add - * @param ignoreChecks whether or not to allow factionID -1 - */ - void AddFaction(int32_t factionID, bool ignoreChecks = false); + /** + * Adds a faction to the faction list of this entity, potentially making more factions friendly. Fetches the info + * from the CDClient. + * @param factionID the faction ID to add + * @param ignoreChecks whether or not to allow factionID -1 + */ + void AddFaction(int32_t factionID, bool ignoreChecks = false); - /** - * Adds a faction ID to the enemy list - * @param factionID the faction ID to make an enemy - */ - void AddEnemyFaction(int32_t factionID); + /** + * Adds a faction ID to the enemy list + * @param factionID the faction ID to make an enemy + */ + void AddEnemyFaction(int32_t factionID); - /** - * Sets whether or not this entity can be smashed, does not indicate the smashable glow, which is indicated by - * faction ids - * @param value whether or not this entity is smashable - */ - void SetIsSmashable(bool value); + /** + * Sets whether or not this entity can be smashed, does not indicate the smashable glow, which is indicated by + * faction ids + * @param value whether or not this entity is smashable + */ + void SetIsSmashable(bool value); - /** - * Returns whether or not this entity is smashable - * @return whether or not this entity is smashable - */ - bool GetIsSmashable() const { return m_IsSmashable; } + /** + * Returns whether or not this entity is smashable + * @return whether or not this entity is smashable + */ + bool GetIsSmashable() const { return m_IsSmashable; } - /** - * Returns the current is-dead value, this is mostly unused - * @return the current is-dead value, this is mostly unused - */ - bool GetIsDead() const { return m_IsDead; } + /** + * Returns the current is-dead value, this is mostly unused + * @return the current is-dead value, this is mostly unused + */ + bool GetIsDead() const { return m_IsDead; } - /** - * Returns the current is-smashed value, this is mostly unused - * @return the current is-smashed value, this is mostly unused - */ - bool GetIsSmashed() const { return m_IsSmashed; } + /** + * Returns the current is-smashed value, this is mostly unused + * @return the current is-smashed value, this is mostly unused + */ + bool GetIsSmashed() const { return m_IsSmashed; } - /** - * Sets whether or not this entity has bricks flying out when smashed - * @param value whether or not this entity has bricks flying out when smashed - */ - void SetHasBricks(bool value); + /** + * Sets whether or not this entity has bricks flying out when smashed + * @param value whether or not this entity has bricks flying out when smashed + */ + void SetHasBricks(bool value); - /** - * Returns whether or not this entity has bricks flying out when smashed - * @return whether or not this entity has bricks flying out when smashed - */ - bool GetHasBricks() const { return m_HasBricks; } + /** + * Returns whether or not this entity has bricks flying out when smashed + * @return whether or not this entity has bricks flying out when smashed + */ + bool GetHasBricks() const { return m_HasBricks; } - /** - * Sets the multiplier for the explosion that's visible when the bricks fly out when this entity is smashed - * @param value the multiplier for the explosion that's visible when the bricks fly out when this entity is smashed - */ - void SetExplodeFactor(float value); + /** + * Sets the multiplier for the explosion that's visible when the bricks fly out when this entity is smashed + * @param value the multiplier for the explosion that's visible when the bricks fly out when this entity is smashed + */ + void SetExplodeFactor(float value); - /** - * Returns the current multiplier for explosions - * @return the current multiplier for explosions - */ - float GetExplodeFactor() const { return m_ExplodeFactor; } + /** + * Returns the current multiplier for explosions + * @return the current multiplier for explosions + */ + float GetExplodeFactor() const { return m_ExplodeFactor; } - /** - * Sets the amount of attacks this entity can block before being able to be damaged again, useful for example for - * shields. - * @param value the amount of attacks this entity can block before being able to be damaged again - */ - void SetAttacksToBlock(uint32_t value); + /** + * Sets the amount of attacks this entity can block before being able to be damaged again, useful for example for + * shields. + * @param value the amount of attacks this entity can block before being able to be damaged again + */ + void SetAttacksToBlock(uint32_t value); - /** - * Returns the current amount of attacks this entity can block - * @return the current amount of attacks this entity can block - */ - uint32_t GetAttacksToBlock() const { return m_AttacksToBlock; } + /** + * Returns the current amount of attacks this entity can block + * @return the current amount of attacks this entity can block + */ + uint32_t GetAttacksToBlock() const { return m_AttacksToBlock; } - /** - * Sets whether or not this enemy currently has threats, NOTE: only here for serialization, has no use internally - * @param value whether or not this enemy currently has threats - */ - void SetHasThreats(bool value); + /** + * Sets whether or not this enemy currently has threats, NOTE: only here for serialization, has no use internally + * @param value whether or not this enemy currently has threats + */ + void SetHasThreats(bool value); - /** - * Returns whether or not this entity currently has threats, NOTE: unused internally - * @return whether or not this entity currently has threats - */ - bool GetHasThreats() const { return m_HasThreats; } + /** + * Returns whether or not this entity currently has threats, NOTE: unused internally + * @return whether or not this entity currently has threats + */ + bool GetHasThreats() const { return m_HasThreats; } - /** - * Returns whether or not this entity is knockback immune, based on whether it's quickbuilding or has assembly gear - * @return whether or not this entity is knockback immune - */ - bool IsKnockbackImmune() const; + /** + * Returns whether or not this entity is knockback immune, based on whether it's quickbuilding or has assembly gear + * @return whether or not this entity is knockback immune + */ + bool IsKnockbackImmune() const; - /** - * Sets the faction ID of this entity, overriding all previously set entries - * @param factionID the faction ID to set - */ - void SetFaction(int32_t factionID, bool ignoreChecks = false); + /** + * Sets the faction ID of this entity, overriding all previously set entries + * @param factionID the faction ID to set + */ + void SetFaction(int32_t factionID, bool ignoreChecks = false); - /** - * Returns whether or not the provided entity is an enemy of this entity - * @param other the entity to check - * @return whether the provided entity is an enemy of this entity or not - */ - bool IsEnemy(const Entity *other) const; + /** + * Returns whether or not the provided entity is an enemy of this entity + * @param other the entity to check + * @return whether the provided entity is an enemy of this entity or not + */ + bool IsEnemy(const Entity* other) const; - /** - * Returns whether or not the provided entity is a friend of this entity - * @param other the entity to check - * @return whether or not the provided entity is a friend of this entity - */ - bool IsFriend(const Entity *other) const; + /** + * Returns whether or not the provided entity is a friend of this entity + * @param other the entity to check + * @return whether or not the provided entity is a friend of this entity + */ + bool IsFriend(const Entity* other) const; - /** - * Returns all the faction IDs that this entity considers a friend - * @return all the faction IDs that this entity considers a friend - */ - const std::vector& GetFactionIDs() const { return m_FactionIDs; } + /** + * Returns all the faction IDs that this entity considers a friend + * @return all the faction IDs that this entity considers a friend + */ + const std::vector& GetFactionIDs() const { return m_FactionIDs; } - /** - * Returns all the faction IDs that this entity considers an enemy - * @return all the faction IDs that this entity considers an enemy - */ - const std::vector& GetEnemyFactionsIDs() const { return m_EnemyFactionIDs; } + /** + * Returns all the faction IDs that this entity considers an enemy + * @return all the faction IDs that this entity considers an enemy + */ + const std::vector& GetEnemyFactionsIDs() const { return m_EnemyFactionIDs; } - /** - * Returns whether the provided faction is a friendly faction - * @param factionID the faction ID to check - * @return whether the provided faction is a friendly faction - */ - bool HasFaction(int32_t factionID) const; + /** + * Returns whether the provided faction is a friendly faction + * @param factionID the faction ID to check + * @return whether the provided faction is a friendly faction + */ + bool HasFaction(int32_t factionID) const; - /** - * Sets the minimum amount of coins this entity drops when smashed - * @param minCoins the minimum amount of coins this entity drops when smashed - */ + /** + * Sets the minimum amount of coins this entity drops when smashed + * @param minCoins the minimum amount of coins this entity drops when smashed + */ void SetMinCoins(uint32_t minCoins) { m_MinCoins = minCoins; } - /** - * Returns the minimum amount of coins this entity drops when smashed - * @return the minimum amount of coins this entity drops when smashed - */ + /** + * Returns the minimum amount of coins this entity drops when smashed + * @return the minimum amount of coins this entity drops when smashed + */ uint32_t GetMinCoins() const { return m_MinCoins; } - /** - * Sets the maximum amount of coins this entity drops when smashed - * @param maxCoins the maximum amount of coins this entity drops when smashed - */ + /** + * Sets the maximum amount of coins this entity drops when smashed + * @param maxCoins the maximum amount of coins this entity drops when smashed + */ void SetMaxCoins(uint32_t maxCoins) { m_MaxCoins = maxCoins; } - /** - * Returns the maximum amount of coins this entity drops when smashed - * @return the maximum amount of coins this entity drops when smashed - */ + /** + * Returns the maximum amount of coins this entity drops when smashed + * @return the maximum amount of coins this entity drops when smashed + */ uint32_t GetMaxCoins() const { return m_MaxCoins; } - /** - * Sets the loot matrix ID that will be used to determine what items to drop when this entity is smashed - * @param lootMatrixID the loot matrix ID to set - */ + /** + * Sets the loot matrix ID that will be used to determine what items to drop when this entity is smashed + * @param lootMatrixID the loot matrix ID to set + */ void SetLootMatrixID(uint32_t lootMatrixID) { m_LootMatrixID = lootMatrixID; } - /** - * Returns the current loot matrix ID that will be used to determine loot drops when this entity is smashed - * @return the current loot matrix ID - */ + /** + * Returns the current loot matrix ID that will be used to determine loot drops when this entity is smashed + * @return the current loot matrix ID + */ uint32_t GetLootMatrixID() const { return m_LootMatrixID; } - /** - * Returns the ID of the entity that killed this entity, if any - * @return the ID of the entity that killed this entity, if any - */ - LWOOBJID GetKillerID() const; + /** + * Returns the ID of the entity that killed this entity, if any + * @return the ID of the entity that killed this entity, if any + */ + LWOOBJID GetKillerID() const; - /** - * Returns the entity that killed this entity, if any - * @return the entity that killed this entity, if any - */ - Entity* GetKiller() const; + /** + * Returns the entity that killed this entity, if any + * @return the entity that killed this entity, if any + */ + Entity* GetKiller() const; - /** - * Checks if the target ID is a valid enemy of this entity - * @param target the target ID to check for - * @param ignoreFactions whether or not check for the factions, e.g. just return true if the entity cannot be smashed - * @return if the target ID is a valid enemy - */ - bool CheckValidity(LWOOBJID target, bool ignoreFactions = false, bool targetEnemy = true, bool targetFriend = false) const; + /** + * Checks if the target ID is a valid enemy of this entity + * @param target the target ID to check for + * @param ignoreFactions whether or not check for the factions, e.g. just return true if the entity cannot be smashed + * @return if the target ID is a valid enemy + */ + bool CheckValidity(LWOOBJID target, bool ignoreFactions = false, bool targetEnemy = true, bool targetFriend = false) const; - /** - * Attempt to damage this entity, handles everything from health and armor to absorption, immunity and callbacks. - * @param damage the damage to attempt to apply - * @param source the attacker that caused this damage - * @param skillID the skill that damaged this entity - * @param echo whether or not to serialize the damage - */ + /** + * Attempt to damage this entity, handles everything from health and armor to absorption, immunity and callbacks. + * @param damage the damage to attempt to apply + * @param source the attacker that caused this damage + * @param skillID the skill that damaged this entity + * @param echo whether or not to serialize the damage + */ void Damage(uint32_t damage, LWOOBJID source, uint32_t skillID = 0, bool echo = true); - /** - * Smashes this entity, notifying all clients - * @param source the source that smashed this entity - * @param skillID the skill that killed this entity - * @param killType the way this entity was killed, determines if a client animation is played - * @param deathType the animation to play when killed - */ - void Smash(LWOOBJID source, eKillType killType = eKillType::VIOLENT, const std::u16string& deathType = u"", uint32_t skillID = 0); + /** + * Smashes this entity, notifying all clients + * @param source the source that smashed this entity + * @param skillID the skill that killed this entity + * @param killType the way this entity was killed, determines if a client animation is played + * @param deathType the animation to play when killed + */ + void Smash(LWOOBJID source, eKillType killType = eKillType::VIOLENT, const std::u16string& deathType = u"", uint32_t skillID = 0); - /** - * Pushes a layer of immunity to this entity, making it immune for longer - * @param stacks the amount of immunity to add - */ - void PushImmunity(int32_t stacks = 1); + /** + * Pushes a layer of immunity to this entity, making it immune for longer + * @param stacks the amount of immunity to add + */ + void PushImmunity(int32_t stacks = 1); - /** - * Pops layers of immunity, making it immune for less longer - * @param stacks the number of layers of immunity to remove - */ - void PopImmunity(int32_t stacks = 1); + /** + * Pops layers of immunity, making it immune for less longer + * @param stacks the number of layers of immunity to remove + */ + void PopImmunity(int32_t stacks = 1); - /** - * Utility to reset all stats to the default stats based on items and completed missions - */ + /** + * Utility to reset all stats to the default stats based on items and completed missions + */ void FixStats(); - /** - * Adds a callback that is called when this entity is hit by some other entity - * @param callback the callback to add - */ + /** + * Adds a callback that is called when this entity is hit by some other entity + * @param callback the callback to add + */ void AddOnHitCallback(const std::function& callback); private: - /** - * Whether or not the health should be serialized - */ - bool m_DirtyHealth; + /** + * Whether or not the health should be serialized + */ + bool m_DirtyHealth; - /** - * The health of the entity - */ - int32_t m_iHealth; + /** + * The health of the entity + */ + int32_t m_iHealth; - /** - * The max health of the entity - */ - float m_fMaxHealth; + /** + * The max health of the entity + */ + float m_fMaxHealth; - /** - * The armor of the entity - */ - int32_t m_iArmor; + /** + * The armor of the entity + */ + int32_t m_iArmor; - /** - * The max armor of the entity - */ - float m_fMaxArmor; + /** + * The max armor of the entity + */ + float m_fMaxArmor; - /** - * The imagination of the entity - */ - int32_t m_iImagination; + /** + * The imagination of the entity + */ + int32_t m_iImagination; - /** - * The max imagination of the entity - */ - float m_fMaxImagination; + /** + * The max imagination of the entity + */ + float m_fMaxImagination; - /** - * The damage this entity can absord before being able to be damaged again - */ - int32_t m_DamageToAbsorb; + /** + * The damage this entity can absord before being able to be damaged again + */ + int32_t m_DamageToAbsorb; - /** - * Whether this entity currently has GM immunity, making it unsmashable - */ - bool m_IsGMImmune; + /** + * Whether this entity currently has GM immunity, making it unsmashable + */ + bool m_IsGMImmune; - /** - * Whether this entity is currently shielded from other attacks - */ - bool m_IsShielded; + /** + * Whether this entity is currently shielded from other attacks + */ + bool m_IsShielded; - /** - * The number of attacks this entity can block before being able to be attacked again - */ - uint32_t m_AttacksToBlock; + /** + * The number of attacks this entity can block before being able to be attacked again + */ + uint32_t m_AttacksToBlock; - /** - * The layers of immunity this entity has left - */ - int32_t m_ImmuneStacks; + /** + * The layers of immunity this entity has left + */ + int32_t m_ImmuneStacks; - /** - * The amount of damage that should be reduced from every attack - */ - int32_t m_DamageReduction; + /** + * The amount of damage that should be reduced from every attack + */ + int32_t m_DamageReduction; - /** - * The faction IDs this entity considers friendly - */ - std::vector m_FactionIDs; + /** + * The faction IDs this entity considers friendly + */ + std::vector m_FactionIDs; - /** - * The faction IDs this entity considers hostile - */ - std::vector m_EnemyFactionIDs; + /** + * The faction IDs this entity considers hostile + */ + std::vector m_EnemyFactionIDs; - /** - * Whether this entity is smasahble, mostly unused - */ - bool m_IsSmashable; + /** + * Whether this entity is smasahble, mostly unused + */ + bool m_IsSmashable; - /** - * Whether this entity is dead. Unused, here for serialization - */ - bool m_IsDead; + /** + * Whether this entity is dead. Unused, here for serialization + */ + bool m_IsDead; - /** - * Whether this entity is smashed. Unused, here for serialization - */ - bool m_IsSmashed; + /** + * Whether this entity is smashed. Unused, here for serialization + */ + bool m_IsSmashed; - /** - * Whether this entity has bricks flying out when smashed (causes the client to look up the files) - */ - bool m_HasBricks; + /** + * Whether this entity has bricks flying out when smashed (causes the client to look up the files) + */ + bool m_HasBricks; - /** - * The rate at which bricks fly out when smashed - */ - float m_ExplodeFactor; + /** + * The rate at which bricks fly out when smashed + */ + float m_ExplodeFactor; - /** - * Whether the list of potential enemies has changed - */ - bool m_DirtyThreatList; + /** + * Whether the list of potential enemies has changed + */ + bool m_DirtyThreatList; - /** - * Whether the entity has threats. Unused: here for serialization - */ - bool m_HasThreats; + /** + * Whether the entity has threats. Unused: here for serialization + */ + bool m_HasThreats; - /** - * The loot matrix that will be used to drop items when the entity is smashed - */ + /** + * The loot matrix that will be used to drop items when the entity is smashed + */ uint32_t m_LootMatrixID; - /** - * The min amount of coins that will drop when this entity is smashed - */ + /** + * The min amount of coins that will drop when this entity is smashed + */ uint32_t m_MinCoins; - /** - * The max amount of coins that will drop when this entity is smashed - */ + /** + * The max amount of coins that will drop when this entity is smashed + */ uint32_t m_MaxCoins; - /** - * The ID of the entity that smashed this entity, if any - */ - LWOOBJID m_KillerID; + /** + * The ID of the entity that smashed this entity, if any + */ + LWOOBJID m_KillerID; - /** - * The list of callbacks that will be called when this entity gets hit - */ - std::vector> m_OnHitCallbacks; + /** + * The list of callbacks that will be called when this entity gets hit + */ + std::vector> m_OnHitCallbacks; }; #endif // DESTROYABLECOMPONENT_H diff --git a/dGame/dComponents/InventoryComponent.cpp b/dGame/dComponents/InventoryComponent.cpp index ea6c8368..a48173bb 100644 --- a/dGame/dComponents/InventoryComponent.cpp +++ b/dGame/dComponents/InventoryComponent.cpp @@ -27,8 +27,7 @@ #include "dConfig.h" #include "eItemType.h" -InventoryComponent::InventoryComponent(Entity* parent, tinyxml2::XMLDocument* document) : Component(parent) -{ +InventoryComponent::InventoryComponent(Entity* parent, tinyxml2::XMLDocument* document) : Component(parent) { this->m_Dirty = true; this->m_Equipped = {}; this->m_Pushed = {}; @@ -37,8 +36,7 @@ InventoryComponent::InventoryComponent(Entity* parent, tinyxml2::XMLDocument* do const auto lot = parent->GetLOT(); - if (lot == 1) - { + if (lot == 1) { LoadXml(document); CheckProxyIntegrity(); @@ -54,10 +52,8 @@ InventoryComponent::InventoryComponent(Entity* parent, tinyxml2::XMLDocument* do auto slot = 0u; - for (const auto& item : items) - { - if (!item.equip || !Inventory::IsValidItem(item.itemid)) - { + for (const auto& item : items) { + if (!item.equip || !Inventory::IsValidItem(item.itemid)) { continue; } @@ -69,20 +65,17 @@ InventoryComponent::InventoryComponent(Entity* parent, tinyxml2::XMLDocument* do } } -Inventory* InventoryComponent::GetInventory(const eInventoryType type) -{ +Inventory* InventoryComponent::GetInventory(const eInventoryType type) { const auto index = m_Inventories.find(type); - if (index != m_Inventories.end()) - { + if (index != m_Inventories.end()) { return index->second; } // Create new empty inventory uint32_t size = 240u; - switch (type) - { + switch (type) { case eInventoryType::ITEMS: size = 20u; break; @@ -104,29 +97,24 @@ Inventory* InventoryComponent::GetInventory(const eInventoryType type) return inventory; } -const std::map& InventoryComponent::GetInventories() const -{ +const std::map& InventoryComponent::GetInventories() const { return m_Inventories; } -uint32_t InventoryComponent::GetLotCount(const LOT lot) const -{ +uint32_t InventoryComponent::GetLotCount(const LOT lot) const { uint32_t count = 0; - for (const auto& inventory : m_Inventories) - { + for (const auto& inventory : m_Inventories) { count += inventory.second->GetLotCount(lot); } return count; } -uint32_t InventoryComponent::GetLotCountNonTransfer(LOT lot) const -{ +uint32_t InventoryComponent::GetLotCountNonTransfer(LOT lot) const { uint32_t count = 0; - for (const auto& inventory : m_Inventories) - { + for (const auto& inventory : m_Inventories) { if (IsTransferInventory(inventory.second->GetType())) continue; count += inventory.second->GetLotCount(lot); @@ -135,8 +123,7 @@ uint32_t InventoryComponent::GetLotCountNonTransfer(LOT lot) const return count; } -const EquipmentMap& InventoryComponent::GetEquippedItems() const -{ +const EquipmentMap& InventoryComponent::GetEquippedItems() const { return m_Equipped; } @@ -153,27 +140,22 @@ void InventoryComponent::AddItem( const eInventoryType inventorySourceType, const int32_t sourceType, const bool bound, - int32_t preferredSlot) -{ - if (count == 0) - { + int32_t preferredSlot) { + if (count == 0) { Game::logger->Log("InventoryComponent", "Attempted to add 0 of item (%i) to the inventory!", lot); return; } - if (!Inventory::IsValidItem(lot)) - { - if (lot > 0) - { + if (!Inventory::IsValidItem(lot)) { + if (lot > 0) { Game::logger->Log("InventoryComponent", "Attempted to add invalid item (%i) to the inventory!", lot); } return; } - if (inventoryType == INVALID) - { + if (inventoryType == INVALID) { inventoryType = Inventory::FindInventoryTypeForLot(lot); } @@ -181,12 +163,10 @@ void InventoryComponent::AddItem( auto* inventory = GetInventory(inventoryType); - if (!config.empty() || bound) - { + if (!config.empty() || bound) { const auto slot = preferredSlot != -1 && inventory->IsSlotEmpty(preferredSlot) ? preferredSlot : inventory->FindEmptySlot(); - if (slot == -1) - { + if (slot == -1) { Game::logger->Log("InventoryComponent", "Failed to find empty slot for inventory (%i)!", inventoryType); return; @@ -194,8 +174,7 @@ void InventoryComponent::AddItem( auto* item = new Item(lot, inventory, slot, count, config, parent, showFlyingLoot, isModMoveAndEquip, subKey, bound, lootSourceType); - if (missions != nullptr && !IsTransferInventory(inventoryType)) - { + if (missions != nullptr && !IsTransferInventory(inventoryType)) { missions->Progress(MissionTaskType::MISSION_TASK_TYPE_ITEM_COLLECTION, lot, LWOOBJID_EMPTY, "", count, IsTransferInventory(inventorySourceType)); } @@ -211,72 +190,59 @@ void InventoryComponent::AddItem( auto stack = static_cast(info.stackSize); // info.itemType of 1 is item type brick - if (inventoryType == eInventoryType::BRICKS || (stack == 0 && info.itemType == 1)) - { + if (inventoryType == eInventoryType::BRICKS || (stack == 0 && info.itemType == 1)) { stack = 999; - } - else if (stack == 0) - { + } else if (stack == 0) { stack = 1; } auto* existing = FindItemByLot(lot, inventoryType); - if (existing != nullptr) - { + if (existing != nullptr) { const auto delta = std::min(left, stack - existing->GetCount()); left -= delta; existing->SetCount(existing->GetCount() + delta, false, true, showFlyingLoot, lootSourceType); - if (isModMoveAndEquip) - { + if (isModMoveAndEquip) { existing->Equip(); isModMoveAndEquip = false; } } - while (left > 0) - { + while (left > 0) { const auto size = std::min(left, stack); left -= size; int32_t slot; - if (preferredSlot != -1 && inventory->IsSlotEmpty(preferredSlot)) - { + if (preferredSlot != -1 && inventory->IsSlotEmpty(preferredSlot)) { slot = preferredSlot; preferredSlot = -1; - } - else - { + } else { slot = inventory->FindEmptySlot(); } - if (slot == -1) - { + if (slot == -1) { auto* player = dynamic_cast(GetParent()); - if (player == nullptr) - { + if (player == nullptr) { return; } outOfSpace += size; - switch (sourceType) - { + switch (sourceType) { case 0: player->SendMail(LWOOBJID_EMPTY, "Darkflame Universe", "Lost Reward", "You received an item and didn't have room for it.", lot, size); break; case 1: - for (size_t i = 0; i < size; i++) - { + for (size_t i = 0; i < size; i++) { GameMessages::SendDropClientLoot(this->m_Parent, this->m_Parent->GetObjectID(), lot, 0, this->m_Parent->GetPosition(), 1); } @@ -293,41 +259,34 @@ void InventoryComponent::AddItem( isModMoveAndEquip = false; } - if (missions != nullptr && !IsTransferInventory(inventoryType)) - { + if (missions != nullptr && !IsTransferInventory(inventoryType)) { missions->Progress(MissionTaskType::MISSION_TASK_TYPE_ITEM_COLLECTION, lot, LWOOBJID_EMPTY, "", count - outOfSpace, IsTransferInventory(inventorySourceType)); } } -void InventoryComponent::RemoveItem(const LOT lot, const uint32_t count, eInventoryType inventoryType, const bool ignoreBound) -{ - if (count == 0) - { +void InventoryComponent::RemoveItem(const LOT lot, const uint32_t count, eInventoryType inventoryType, const bool ignoreBound) { + if (count == 0) { Game::logger->Log("InventoryComponent", "Attempted to remove 0 of item (%i) from the inventory!", lot); return; } - if (inventoryType == INVALID) - { + if (inventoryType == INVALID) { inventoryType = Inventory::FindInventoryTypeForLot(lot); } auto* inventory = GetInventory(inventoryType); - if (inventory == nullptr) - { + if (inventory == nullptr) { return; } auto left = std::min(count, inventory->GetLotCount(lot)); - while (left > 0) - { + while (left > 0) { auto* item = FindItemByLot(lot, inventoryType, false, ignoreBound); - if (item == nullptr) - { + if (item == nullptr) { break; } @@ -339,10 +298,8 @@ void InventoryComponent::RemoveItem(const LOT lot, const uint32_t count, eInvent } } -void InventoryComponent::MoveItemToInventory(Item* item, const eInventoryType inventory, const uint32_t count, const bool showFlyingLot, bool isModMoveAndEquip, const bool ignoreEquipped, const int32_t preferredSlot) -{ - if (item == nullptr) - { +void InventoryComponent::MoveItemToInventory(Item* item, const eInventoryType inventory, const uint32_t count, const bool showFlyingLot, bool isModMoveAndEquip, const bool ignoreEquipped, const int32_t preferredSlot) { + if (item == nullptr) { return; } @@ -350,18 +307,14 @@ void InventoryComponent::MoveItemToInventory(Item* item, const eInventoryType in const auto lot = item->GetLot(); - if (item->GetConfig().empty() && !item->GetBound() || (item->GetBound() && item->GetInfo().isBOP)) - { + if (item->GetConfig().empty() && !item->GetBound() || (item->GetBound() && item->GetInfo().isBOP)) { auto left = std::min(count, origin->GetLotCount(lot)); - while (left > 0) - { - if (item == nullptr) - { + while (left > 0) { + if (item == nullptr) { item = origin->FindItemByLot(lot, false); - if (item == nullptr) - { + if (item == nullptr) { break; } } @@ -376,13 +329,10 @@ void InventoryComponent::MoveItemToInventory(Item* item, const eInventoryType in isModMoveAndEquip = false; } - } - else - { + } else { std::vector config; - for (auto* const data : item->GetConfig()) - { + for (auto* const data : item->GetConfig()) { config.push_back(data->Copy()); } @@ -395,19 +345,15 @@ void InventoryComponent::MoveItemToInventory(Item* item, const eInventoryType in auto* missionComponent = m_Parent->GetComponent(); - if (missionComponent != nullptr) - { - if (IsTransferInventory(inventory)) - { + if (missionComponent != nullptr) { + if (IsTransferInventory(inventory)) { missionComponent->Progress(MissionTaskType::MISSION_TASK_TYPE_ITEM_COLLECTION, lot, LWOOBJID_EMPTY, "", -static_cast(count)); } } } -void InventoryComponent::MoveStack(Item* item, const eInventoryType inventory, const uint32_t slot) -{ - if (inventory != INVALID && item->GetInventory()->GetType() != inventory) - { +void InventoryComponent::MoveStack(Item* item, const eInventoryType inventory, const uint32_t slot) { + if (inventory != INVALID && item->GetInventory()->GetType() != inventory) { auto* newInventory = GetInventory(inventory); item->SetInventory(newInventory); @@ -416,14 +362,11 @@ void InventoryComponent::MoveStack(Item* item, const eInventoryType inventory, c item->SetSlot(slot); } -Item* InventoryComponent::FindItemById(const LWOOBJID id) const -{ - for (const auto& inventory : m_Inventories) - { +Item* InventoryComponent::FindItemById(const LWOOBJID id) const { + for (const auto& inventory : m_Inventories) { auto* item = inventory.second->FindItemById(id); - if (item != nullptr) - { + if (item != nullptr) { return item; } } @@ -431,10 +374,8 @@ Item* InventoryComponent::FindItemById(const LWOOBJID id) const return nullptr; } -Item* InventoryComponent::FindItemByLot(const LOT lot, eInventoryType inventoryType, const bool ignoreEquipped, const bool ignoreBound) -{ - if (inventoryType == INVALID) - { +Item* InventoryComponent::FindItemByLot(const LOT lot, eInventoryType inventoryType, const bool ignoreEquipped, const bool ignoreBound) { + if (inventoryType == INVALID) { inventoryType = Inventory::FindInventoryTypeForLot(lot); } @@ -443,47 +384,37 @@ Item* InventoryComponent::FindItemByLot(const LOT lot, eInventoryType inventoryT return inventory->FindItemByLot(lot, ignoreEquipped, ignoreBound); } -Item* InventoryComponent::FindItemBySubKey(LWOOBJID id, eInventoryType inventoryType) -{ - if (inventoryType == INVALID) - { - for (const auto& inventory : m_Inventories) - { +Item* InventoryComponent::FindItemBySubKey(LWOOBJID id, eInventoryType inventoryType) { + if (inventoryType == INVALID) { + for (const auto& inventory : m_Inventories) { auto* item = inventory.second->FindItemBySubKey(id); - if (item != nullptr) - { + if (item != nullptr) { return item; } } return nullptr; - } - else - { + } else { return GetInventory(inventoryType)->FindItemBySubKey(id); } } -bool InventoryComponent::HasSpaceForLoot(const std::unordered_map& loot) -{ - std::unordered_map spaceOffset {}; +bool InventoryComponent::HasSpaceForLoot(const std::unordered_map& loot) { + std::unordered_map spaceOffset{}; uint32_t slotsNeeded = 0; - for (const auto& pair : loot) - { + for (const auto& pair : loot) { const auto inventoryType = Inventory::FindInventoryTypeForLot(pair.first); - if (inventoryType == BRICKS) - { + if (inventoryType == BRICKS) { continue; } auto* inventory = GetInventory(inventoryType); - if (inventory == nullptr) - { + if (inventory == nullptr) { return false; } @@ -495,8 +426,7 @@ bool InventoryComponent::HasSpaceForLoot(const std::unordered_map& auto* partial = inventory->FindItemByLot(pair.first); - if (partial != nullptr && partial->GetCount() < stack) - { + if (partial != nullptr && partial->GetCount() < stack) { left -= stack - partial->GetCount(); } @@ -506,16 +436,14 @@ bool InventoryComponent::HasSpaceForLoot(const std::unordered_map& auto freeSpace = inventory->GetEmptySlots() - (offsetIter == spaceOffset.end() ? 0 : offsetIter->second); - if (requiredSlots > freeSpace) - { + if (requiredSlots > freeSpace) { slotsNeeded += requiredSlots - freeSpace; } spaceOffset[inventoryType] = offsetIter == spaceOffset.end() ? requiredSlots : offsetIter->second + requiredSlots; } - if (slotsNeeded > 0) - { + if (slotsNeeded > 0) { GameMessages::SendNotifyNotEnoughInvSpace(m_Parent->GetObjectID(), slotsNeeded, ITEMS, m_Parent->GetSystemAddress()); return false; @@ -524,14 +452,12 @@ bool InventoryComponent::HasSpaceForLoot(const std::unordered_map& return true; } -void InventoryComponent::LoadXml(tinyxml2::XMLDocument* document) -{ +void InventoryComponent::LoadXml(tinyxml2::XMLDocument* document) { LoadPetXml(document); auto* inventoryElement = document->FirstChildElement("obj")->FirstChildElement("inv"); - if (inventoryElement == nullptr) - { + if (inventoryElement == nullptr) { Game::logger->Log("InventoryComponent", "Failed to find 'inv' xml element!"); return; @@ -539,8 +465,7 @@ void InventoryComponent::LoadXml(tinyxml2::XMLDocument* document) auto* bags = inventoryElement->FirstChildElement("bag"); - if (bags == nullptr) - { + if (bags == nullptr) { Game::logger->Log("InventoryComponent", "Failed to find 'bags' xml element!"); return; @@ -550,8 +475,7 @@ void InventoryComponent::LoadXml(tinyxml2::XMLDocument* document) auto* bag = bags->FirstChildElement(); - while (bag != nullptr) - { + while (bag != nullptr) { unsigned int type; unsigned int size; @@ -567,8 +491,7 @@ void InventoryComponent::LoadXml(tinyxml2::XMLDocument* document) auto* items = inventoryElement->FirstChildElement("items"); - if (items == nullptr) - { + if (items == nullptr) { Game::logger->Log("InventoryComponent", "Failed to find 'items' xml element!"); return; @@ -576,16 +499,14 @@ void InventoryComponent::LoadXml(tinyxml2::XMLDocument* document) bag = items->FirstChildElement(); - while (bag != nullptr) - { + while (bag != nullptr) { unsigned int type; bag->QueryAttribute("t", &type); auto* inventory = GetInventory(static_cast(type)); - if (inventory == nullptr) - { + if (inventory == nullptr) { Game::logger->Log("InventoryComponent", "Failed to find inventory (%i)!", type); return; @@ -593,8 +514,7 @@ void InventoryComponent::LoadXml(tinyxml2::XMLDocument* document) auto* itemElement = bag->FirstChildElement(); - while (itemElement != nullptr) - { + while (itemElement != nullptr) { LWOOBJID id; LOT lot; bool equipped; @@ -621,8 +541,7 @@ void InventoryComponent::LoadXml(tinyxml2::XMLDocument* document) auto* extraInfo = itemElement->FirstChildElement("x"); - if (extraInfo) - { + if (extraInfo) { std::string modInfo = extraInfo->Attribute("ma"); LDFBaseData* moduleAssembly = new LDFData(u"assemblyPartLOTs", GeneralUtils::ASCIIToUTF16(modInfo.substr(2, modInfo.size() - 1))); @@ -632,8 +551,7 @@ void InventoryComponent::LoadXml(tinyxml2::XMLDocument* document) const auto* item = new Item(id, lot, inventory, slot, count, bound, config, parent, subKey); - if (equipped) - { + if (equipped) { const auto info = Inventory::FindItemComponent(lot); UpdateSlot(info.equipLocation, { item->GetId(), item->GetLot(), item->GetCount(), item->GetSlot() }); @@ -647,25 +565,21 @@ void InventoryComponent::LoadXml(tinyxml2::XMLDocument* document) bag = bag->NextSiblingElement(); } - for (const auto inventory : m_Inventories) - { + for (const auto inventory : m_Inventories) { const auto itemCount = inventory.second->GetItems().size(); - if (inventory.second->GetSize() < itemCount) - { + if (inventory.second->GetSize() < itemCount) { inventory.second->SetSize(itemCount); } } } -void InventoryComponent::UpdateXml(tinyxml2::XMLDocument* document) -{ +void InventoryComponent::UpdateXml(tinyxml2::XMLDocument* document) { UpdatePetXml(document); auto* inventoryElement = document->FirstChildElement("obj")->FirstChildElement("inv"); - if (inventoryElement == nullptr) - { + if (inventoryElement == nullptr) { Game::logger->Log("InventoryComponent", "Failed to find 'inv' xml element!"); return; @@ -673,12 +587,10 @@ void InventoryComponent::UpdateXml(tinyxml2::XMLDocument* document) std::vector inventories; - for (const auto& pair : this->m_Inventories) - { + for (const auto& pair : this->m_Inventories) { auto* inventory = pair.second; - if (inventory->GetType() == VENDOR_BUYBACK) - { + if (inventory->GetType() == VENDOR_BUYBACK) { continue; } @@ -689,8 +601,7 @@ void InventoryComponent::UpdateXml(tinyxml2::XMLDocument* document) auto* bags = inventoryElement->FirstChildElement("bag"); - if (bags == nullptr) - { + if (bags == nullptr) { Game::logger->Log("InventoryComponent", "Failed to find 'bags' xml element!"); return; @@ -698,8 +609,7 @@ void InventoryComponent::UpdateXml(tinyxml2::XMLDocument* document) bags->DeleteChildren(); - for (const auto* inventory : inventories) - { + for (const auto* inventory : inventories) { auto* bag = document->NewElement("b"); bag->SetAttribute("t", inventory->GetType()); @@ -710,8 +620,7 @@ void InventoryComponent::UpdateXml(tinyxml2::XMLDocument* document) auto* items = inventoryElement->FirstChildElement("items"); - if (items == nullptr) - { + if (items == nullptr) { Game::logger->Log("InventoryComponent", "Failed to find 'items' xml element!"); return; @@ -719,10 +628,8 @@ void InventoryComponent::UpdateXml(tinyxml2::XMLDocument* document) items->DeleteChildren(); - for (auto* inventory : inventories) - { - if (inventory->GetSize() == 0) - { + for (auto* inventory : inventories) { + if (inventory->GetSize() == 0) { continue; } @@ -730,8 +637,7 @@ void InventoryComponent::UpdateXml(tinyxml2::XMLDocument* document) bagElement->SetAttribute("t", inventory->GetType()); - for (const auto& pair : inventory->GetItems()) - { + for (const auto& pair : inventory->GetItems()) { auto* item = pair.second; auto* itemElement = document->NewElement("i"); @@ -748,10 +654,8 @@ void InventoryComponent::UpdateXml(tinyxml2::XMLDocument* document) itemElement->SetAttribute("parent", item->GetParent()); // End custom xml - for (auto* data : item->GetConfig()) - { - if (data->GetKey() != u"assemblyPartLOTs") - { + for (auto* data : item->GetConfig()) { + if (data->GetKey() != u"assemblyPartLOTs") { continue; } @@ -769,35 +673,31 @@ void InventoryComponent::UpdateXml(tinyxml2::XMLDocument* document) } } -void InventoryComponent::Serialize(RakNet::BitStream* outBitStream, const bool bIsInitialUpdate, unsigned& flags) -{ - if (bIsInitialUpdate || m_Dirty) - { +void InventoryComponent::Serialize(RakNet::BitStream* outBitStream, const bool bIsInitialUpdate, unsigned& flags) { + if (bIsInitialUpdate || m_Dirty) { outBitStream->Write(true); outBitStream->Write(m_Equipped.size()); - for (const auto& pair : m_Equipped) - { + for (const auto& pair : m_Equipped) { const auto item = pair.second; - if (bIsInitialUpdate) - { + if (bIsInitialUpdate) { AddItemSkills(item.lot); } outBitStream->Write(item.id); - outBitStream->Write(item.lot); + outBitStream->Write(item.lot); - outBitStream->Write0(); + outBitStream->Write0(); - outBitStream->Write(item.count > 0); - if (item.count > 0) outBitStream->Write(item.count); + outBitStream->Write(item.count > 0); + if (item.count > 0) outBitStream->Write(item.count); - outBitStream->Write(item.slot != 0); - if (item.slot != 0) outBitStream->Write(item.slot); + outBitStream->Write(item.slot != 0); + if (item.slot != 0) outBitStream->Write(item.slot); - outBitStream->Write0(); + outBitStream->Write0(); bool flag = !item.config.empty(); outBitStream->Write(flag); @@ -824,34 +724,27 @@ void InventoryComponent::Serialize(RakNet::BitStream* outBitStream, const bool b } m_Dirty = false; - } - else - { + } else { outBitStream->Write(false); } outBitStream->Write(false); } -void InventoryComponent::ResetFlags() -{ +void InventoryComponent::ResetFlags() { m_Dirty = false; } -void InventoryComponent::Update(float deltaTime) -{ - for (auto* set : m_Itemsets) - { +void InventoryComponent::Update(float deltaTime) { + for (auto* set : m_Itemsets) { set->Update(deltaTime); } } -void InventoryComponent::UpdateSlot(const std::string& location, EquippedItem item, bool keepCurrent) -{ +void InventoryComponent::UpdateSlot(const std::string& location, EquippedItem item, bool keepCurrent) { const auto index = m_Equipped.find(location); - if (index != m_Equipped.end()) - { + if (index != m_Equipped.end()) { if (keepCurrent) { m_Equipped.insert_or_assign(location + std::to_string(m_Equipped.size()), item); @@ -862,8 +755,7 @@ void InventoryComponent::UpdateSlot(const std::string& location, EquippedItem it auto* old = FindItemById(index->second.id); - if (old != nullptr) - { + if (old != nullptr) { UnEquipItem(old); } } @@ -873,10 +765,8 @@ void InventoryComponent::UpdateSlot(const std::string& location, EquippedItem it m_Dirty = true; } -void InventoryComponent::RemoveSlot(const std::string& location) -{ - if (m_Equipped.find(location) == m_Equipped.end()) - { +void InventoryComponent::RemoveSlot(const std::string& location) { + if (m_Equipped.find(location) == m_Equipped.end()) { return; } @@ -885,39 +775,33 @@ void InventoryComponent::RemoveSlot(const std::string& location) m_Dirty = true; } -void InventoryComponent::EquipItem(Item* item, const bool skipChecks) -{ - if (!Inventory::IsValidItem(item->GetLot())) - { +void InventoryComponent::EquipItem(Item* item, const bool skipChecks) { + if (!Inventory::IsValidItem(item->GetLot())) { return; } - // Temp items should be equippable but other transfer items shouldn't be (for example the instruments in RB) + // Temp items should be equippable but other transfer items shouldn't be (for example the instruments in RB) if (item->IsEquipped() - || (item->GetInventory()->GetType() != TEMP_ITEMS && IsTransferInventory(item->GetInventory()->GetType())) - || IsPet(item->GetSubKey())) { + || (item->GetInventory()->GetType() != TEMP_ITEMS && IsTransferInventory(item->GetInventory()->GetType())) + || IsPet(item->GetSubKey())) { return; } auto* character = m_Parent->GetCharacter(); - if (character != nullptr && !skipChecks) - { + if (character != nullptr && !skipChecks) { // Hacky proximity rocket - if (item->GetLot() == 6416) - { + if (item->GetLot() == 6416) { const auto rocketLauchPads = EntityManager::Instance()->GetEntitiesByComponent(COMPONENT_TYPE_ROCKET_LAUNCH); const auto position = m_Parent->GetPosition(); - for (auto* lauchPad : rocketLauchPads) - { + for (auto* lauchPad : rocketLauchPads) { if (Vector3::DistanceSquared(lauchPad->GetPosition(), position) > 13 * 13) continue; auto* characterComponent = m_Parent->GetComponent(); - if (characterComponent != nullptr) - { + if (characterComponent != nullptr) { characterComponent->SetLastRocketItemID(item->GetId()); } @@ -933,8 +817,7 @@ void InventoryComponent::EquipItem(Item* item, const bool skipChecks) const auto type = static_cast(item->GetInfo().itemType); - if (item->GetLot() == 8092 && m_Parent->GetGMLevel() >= GAME_MASTER_LEVEL_OPERATOR && hasCarEquipped == false) - { + if (item->GetLot() == 8092 && m_Parent->GetGMLevel() >= GAME_MASTER_LEVEL_OPERATOR && hasCarEquipped == false) { auto startPosition = m_Parent->GetPosition(); auto startRotation = NiQuaternion::LookAt(startPosition, startPosition + NiPoint3::UNIT_X); @@ -944,7 +827,7 @@ void InventoryComponent::EquipItem(Item* item, const bool skipChecks) GameMessages::SendTeleport(m_Parent->GetObjectID(), startPosition, startRotation, m_Parent->GetSystemAddress(), true, true); - EntityInfo info {}; + EntityInfo info{}; info.lot = 8092; info.pos = startPosition; info.rot = startRotation; @@ -953,33 +836,29 @@ void InventoryComponent::EquipItem(Item* item, const bool skipChecks) auto* carEntity = EntityManager::Instance()->CreateEntity(info, nullptr, m_Parent); m_Parent->AddChild(carEntity); - auto *destroyableComponent = carEntity->GetComponent(); + auto* destroyableComponent = carEntity->GetComponent(); - // Setup the vehicle stats. - if (destroyableComponent != nullptr) { + // Setup the vehicle stats. + if (destroyableComponent != nullptr) { destroyableComponent->SetIsSmashable(false); destroyableComponent->SetIsImmune(true); - } + } // #108 auto* possessableComponent = carEntity->GetComponent(); - if (possessableComponent != nullptr) - { + if (possessableComponent != nullptr) { previousPossessableID = possessableComponent->GetPossessor(); possessableComponent->SetPossessor(m_Parent->GetObjectID()); } auto* moduleAssemblyComponent = carEntity->GetComponent(); - if (moduleAssemblyComponent != nullptr) - { + if (moduleAssemblyComponent != nullptr) { moduleAssemblyComponent->SetSubKey(item->GetSubKey()); moduleAssemblyComponent->SetUseOptionalParts(false); - for (auto* config : item->GetConfig()) - { - if (config->GetKey() == u"assemblyPartLOTs") - { + for (auto* config : item->GetConfig()) { + if (config->GetKey() == u"assemblyPartLOTs") { moduleAssemblyComponent->SetAssemblyPartsLOTs(GeneralUtils::ASCIIToUTF16(config->GetValueAsString())); } } @@ -1001,14 +880,13 @@ void InventoryComponent::EquipItem(Item* item, const bool skipChecks) GameMessages::SendRacingPlayerLoaded(LWOOBJID_EMPTY, m_Parent->GetObjectID(), carEntity->GetObjectID(), UNASSIGNED_SYSTEM_ADDRESS); GameMessages::SendVehicleUnlockInput(carEntity->GetObjectID(), false, UNASSIGNED_SYSTEM_ADDRESS); GameMessages::SendTeleport(m_Parent->GetObjectID(), startPosition, startRotation, m_Parent->GetSystemAddress(), true, true); - GameMessages::SendTeleport(carEntity->GetObjectID(), startPosition, startRotation, m_Parent->GetSystemAddress(), true, true); + GameMessages::SendTeleport(carEntity->GetObjectID(), startPosition, startRotation, m_Parent->GetSystemAddress(), true, true); EntityManager::Instance()->SerializeEntity(m_Parent); hasCarEquipped = true; equippedCarEntity = carEntity; return; - } else if (item->GetLot() == 8092 && m_Parent->GetGMLevel() >= GAME_MASTER_LEVEL_OPERATOR && hasCarEquipped == true) - { + } else if (item->GetLot() == 8092 && m_Parent->GetGMLevel() >= GAME_MASTER_LEVEL_OPERATOR && hasCarEquipped == true) { GameMessages::SendNotifyRacingClient(LWOOBJID_EMPTY, 3, 0, LWOOBJID_EMPTY, u"", m_Parent->GetObjectID(), UNASSIGNED_SYSTEM_ADDRESS); auto player = dynamic_cast(m_Parent); player->SendToZone(player->GetCharacter()->GetZoneID()); @@ -1018,23 +896,18 @@ void InventoryComponent::EquipItem(Item* item, const bool skipChecks) return; } - if (!building) - { - if (item->GetLot() == 6086) - { + if (!building) { + if (item->GetLot() == 6086) { return; } - if (type == eItemType::ITEM_TYPE_LOOT_MODEL || type == eItemType::ITEM_TYPE_VEHICLE) - { + if (type == eItemType::ITEM_TYPE_LOOT_MODEL || type == eItemType::ITEM_TYPE_VEHICLE) { return; } } - if (type != eItemType::ITEM_TYPE_LOOT_MODEL && type != eItemType::ITEM_TYPE_MODEL) - { - if (!item->GetBound() && !item->GetPreconditionExpression()->Check(m_Parent)) - { + if (type != eItemType::ITEM_TYPE_LOOT_MODEL && type != eItemType::ITEM_TYPE_MODEL) { + if (!item->GetBound() && !item->GetPreconditionExpression()->Check(m_Parent)) { return; } } @@ -1044,13 +917,11 @@ void InventoryComponent::EquipItem(Item* item, const bool skipChecks) CheckItemSet(lot); - for (auto* set : m_Itemsets) - { + for (auto* set : m_Itemsets) { set->OnEquip(lot); } - if (item->GetInfo().isBOE) - { + if (item->GetInfo().isBOE) { item->SetBound(true); } @@ -1065,24 +936,20 @@ void InventoryComponent::EquipItem(Item* item, const bool skipChecks) EntityManager::Instance()->SerializeEntity(m_Parent); } -void InventoryComponent::UnEquipItem(Item* item) -{ - if (!item->IsEquipped()) - { +void InventoryComponent::UnEquipItem(Item* item) { + if (!item->IsEquipped()) { return; } const auto lot = item->GetLot(); - if (!Inventory::IsValidItem(lot)) - { + if (!Inventory::IsValidItem(lot)) { return; } CheckItemSet(lot); - for (auto* set : m_Itemsets) - { + for (auto* set : m_Itemsets) { set->OnUnEquip(lot); } @@ -1097,62 +964,51 @@ void InventoryComponent::UnEquipItem(Item* item) EntityManager::Instance()->SerializeEntity(m_Parent); // Trigger property event - if (PropertyManagementComponent::Instance() != nullptr && item->GetCount() > 0 && Inventory::FindInventoryTypeForLot(item->GetLot()) == MODELS) - { + if (PropertyManagementComponent::Instance() != nullptr && item->GetCount() > 0 && Inventory::FindInventoryTypeForLot(item->GetLot()) == MODELS) { PropertyManagementComponent::Instance()->GetParent()->OnZonePropertyModelRemovedWhileEquipped(m_Parent); dZoneManager::Instance()->GetZoneControlObject()->OnZonePropertyModelRemovedWhileEquipped(m_Parent); } } -void InventoryComponent::ApplyBuff(Item* item) const -{ +void InventoryComponent::ApplyBuff(Item* item) const { const auto buffs = FindBuffs(item, true); - for (const auto buff : buffs) - { + for (const auto buff : buffs) { SkillComponent::HandleUnmanaged(buff, m_Parent->GetObjectID()); } } -void InventoryComponent::RemoveBuff(Item* item) const -{ +void InventoryComponent::RemoveBuff(Item* item) const { const auto buffs = FindBuffs(item, false); - for (const auto buff : buffs) - { + for (const auto buff : buffs) { SkillComponent::HandleUnCast(buff, m_Parent->GetObjectID()); } } -void InventoryComponent::PushEquippedItems() -{ +void InventoryComponent::PushEquippedItems() { m_Pushed = m_Equipped; m_Dirty = true; } -void InventoryComponent::PopEquippedItems() -{ +void InventoryComponent::PopEquippedItems() { auto current = m_Equipped; - for (const auto& pair : current) - { + for (const auto& pair : current) { auto* const item = FindItemById(pair.second.id); - if (item == nullptr) - { + if (item == nullptr) { continue; } item->UnEquip(); } - for (const auto& pair : m_Pushed) - { + for (const auto& pair : m_Pushed) { auto* const item = FindItemById(pair.second.id); - if (item == nullptr) - { + if (item == nullptr) { continue; } @@ -1175,12 +1031,9 @@ void InventoryComponent::PopEquippedItems() } -bool InventoryComponent::IsEquipped(const LOT lot) const -{ - for (const auto& pair : m_Equipped) - { - if (pair.second.lot == lot) - { +bool InventoryComponent::IsEquipped(const LOT lot) const { + for (const auto& pair : m_Equipped) { + if (pair.second.lot == lot) { return true; } } @@ -1208,17 +1061,14 @@ void InventoryComponent::CheckItemSet(const LOT lot) { bool found = false; // Check if we have the set already - for (auto* itemset : m_Itemsets) - { - if (itemset->GetID() == id) - { + for (auto* itemset : m_Itemsets) { + if (itemset->GetID() == id) { found = true; break; } } - if (!found) - { + if (!found) { auto* set = new ItemSet(id, this); m_Itemsets.push_back(set); @@ -1232,24 +1082,20 @@ void InventoryComponent::CheckItemSet(const LOT lot) { result.finalize(); } -void InventoryComponent::SetConsumable(LOT lot) -{ +void InventoryComponent::SetConsumable(LOT lot) { m_Consumable = lot; } -LOT InventoryComponent::GetConsumable() const -{ +LOT InventoryComponent::GetConsumable() const { return m_Consumable; } -void InventoryComponent::AddItemSkills(const LOT lot) -{ +void InventoryComponent::AddItemSkills(const LOT lot) { const auto info = Inventory::FindItemComponent(lot); const auto slot = FindBehaviorSlot(static_cast(info.itemType)); - if (slot == BehaviorSlot::Invalid) - { + if (slot == BehaviorSlot::Invalid) { return; } @@ -1257,13 +1103,11 @@ void InventoryComponent::AddItemSkills(const LOT lot) const auto skill = FindSkill(lot); - if (skill == 0) - { + if (skill == 0) { return; } - if (index != m_Skills.end()) - { + if (index != m_Skills.end()) { const auto old = index->second; GameMessages::SendRemoveSkill(m_Parent, old); @@ -1274,21 +1118,18 @@ void InventoryComponent::AddItemSkills(const LOT lot) m_Skills.insert_or_assign(slot, skill); } -void InventoryComponent::RemoveItemSkills(const LOT lot) -{ +void InventoryComponent::RemoveItemSkills(const LOT lot) { const auto info = Inventory::FindItemComponent(lot); const auto slot = FindBehaviorSlot(static_cast(info.itemType)); - if (slot == BehaviorSlot::Invalid) - { + if (slot == BehaviorSlot::Invalid) { return; } const auto index = m_Skills.find(slot); - if (index == m_Skills.end()) - { + if (index == m_Skills.end()) { return; } @@ -1298,34 +1139,27 @@ void InventoryComponent::RemoveItemSkills(const LOT lot) m_Skills.erase(slot); - if (slot == BehaviorSlot::Primary) - { + if (slot == BehaviorSlot::Primary) { m_Skills.insert_or_assign(BehaviorSlot::Primary, 1); GameMessages::SendAddSkill(m_Parent, 1, static_cast(BehaviorSlot::Primary)); } } -void InventoryComponent::TriggerPassiveAbility(PassiveAbilityTrigger trigger) -{ - for (auto* set : m_Itemsets) - { +void InventoryComponent::TriggerPassiveAbility(PassiveAbilityTrigger trigger) { + for (auto* set : m_Itemsets) { set->TriggerPassiveAbility(trigger); } } -bool InventoryComponent::HasAnyPassive(const std::vector& passiveIDs, int32_t equipmentRequirement) const -{ - for (auto* set : m_Itemsets) - { - if (set->GetEquippedCount() < equipmentRequirement) - { +bool InventoryComponent::HasAnyPassive(const std::vector& passiveIDs, int32_t equipmentRequirement) const { + for (auto* set : m_Itemsets) { + if (set->GetEquippedCount() < equipmentRequirement) { continue; } // Check if the set has any of the passive abilities - if (std::find(passiveIDs.begin(), passiveIDs.end(), static_cast(set->GetID())) != passiveIDs.end()) - { + if (std::find(passiveIDs.begin(), passiveIDs.end(), static_cast(set->GetID())) != passiveIDs.end()) { return true; } } @@ -1333,26 +1167,21 @@ bool InventoryComponent::HasAnyPassive(const std::vectorGetObjectID()); - if (current != nullptr) - { + if (current != nullptr) { current->Deactivate(); } } -void InventoryComponent::SpawnPet(Item* item) -{ +void InventoryComponent::SpawnPet(Item* item) { auto* current = PetComponent::GetActivePet(m_Parent->GetObjectID()); - if (current != nullptr) - { + if (current != nullptr) { current->Deactivate(); - if (current->GetDatabaseId() == item->GetSubKey()) - { + if (current->GetDatabaseId() == item->GetSubKey()) { return; } } @@ -1365,7 +1194,7 @@ void InventoryComponent::SpawnPet(Item* item) return; } - EntityInfo info {}; + EntityInfo info{}; info.lot = item->GetLot(); info.pos = m_Parent->GetPosition(); info.rot = NiQuaternion::IDENTITY; @@ -1375,21 +1204,18 @@ void InventoryComponent::SpawnPet(Item* item) auto* petComponent = pet->GetComponent(); - if (petComponent != nullptr) - { + if (petComponent != nullptr) { petComponent->Activate(item); } EntityManager::Instance()->ConstructEntity(pet); } -void InventoryComponent::SetDatabasePet(LWOOBJID id, const DatabasePet& data) -{ +void InventoryComponent::SetDatabasePet(LWOOBJID id, const DatabasePet& data) { m_Pets.insert_or_assign(id, data); } -const DatabasePet& InventoryComponent::GetDatabasePet(LWOOBJID id) const -{ +const DatabasePet& InventoryComponent::GetDatabasePet(LWOOBJID id) const { const auto& pair = m_Pets.find(id); if (pair == m_Pets.end()) return DATABASE_PET_INVALID; @@ -1397,20 +1223,17 @@ const DatabasePet& InventoryComponent::GetDatabasePet(LWOOBJID id) const return pair->second; } -bool InventoryComponent::IsPet(LWOOBJID id) const -{ +bool InventoryComponent::IsPet(LWOOBJID id) const { const auto& pair = m_Pets.find(id); return pair != m_Pets.end(); } -void InventoryComponent::RemoveDatabasePet(LWOOBJID id) -{ +void InventoryComponent::RemoveDatabasePet(LWOOBJID id) { m_Pets.erase(id); } -BehaviorSlot InventoryComponent::FindBehaviorSlot(const eItemType type) -{ +BehaviorSlot InventoryComponent::FindBehaviorSlot(const eItemType type) { switch (type) { case eItemType::ITEM_TYPE_HAT: return BehaviorSlot::Head; @@ -1427,24 +1250,19 @@ BehaviorSlot InventoryComponent::FindBehaviorSlot(const eItemType type) } } -bool InventoryComponent::IsTransferInventory(eInventoryType type) -{ +bool InventoryComponent::IsTransferInventory(eInventoryType type) { return type == VENDOR_BUYBACK || type == VAULT_ITEMS || type == VAULT_MODELS || type == TEMP_ITEMS || type == TEMP_MODELS; } -uint32_t InventoryComponent::FindSkill(const LOT lot) -{ +uint32_t InventoryComponent::FindSkill(const LOT lot) { auto* table = CDClientManager::Instance()->GetTable("ObjectSkills"); - const auto results = table->Query([=](const CDObjectSkills& entry) - { + const auto results = table->Query([=](const CDObjectSkills& entry) { return entry.objectTemplate == static_cast(lot); - }); + }); - for (const auto& result : results) - { - if (result.castOnType == 0) - { + for (const auto& result : results) { + if (result.castOnType == 0) { return result.skillID; } } @@ -1452,35 +1270,29 @@ uint32_t InventoryComponent::FindSkill(const LOT lot) return 0; } -std::vector InventoryComponent::FindBuffs(Item* item, bool castOnEquip) const -{ +std::vector InventoryComponent::FindBuffs(Item* item, bool castOnEquip) const { std::vector buffs; if (item == nullptr) return buffs; auto* table = CDClientManager::Instance()->GetTable("ObjectSkills"); auto* behaviors = CDClientManager::Instance()->GetTable("SkillBehavior"); - const auto results = table->Query([=](const CDObjectSkills& entry) - { + const auto results = table->Query([=](const CDObjectSkills& entry) { return entry.objectTemplate == static_cast(item->GetLot()); - }); + }); auto* missions = static_cast(m_Parent->GetComponent(COMPONENT_TYPE_MISSION)); - for (const auto& result : results) - { - if (result.castOnType == 1) - { + for (const auto& result : results) { + if (result.castOnType == 1) { const auto entry = behaviors->GetSkillByID(result.skillID); - if (entry.skillID == 0) - { + if (entry.skillID == 0) { Game::logger->Log("InventoryComponent", "Failed to find buff behavior for skill (%i)!", result.skillID); continue; } - if (missions != nullptr && castOnEquip) - { + if (missions != nullptr && castOnEquip) { missions->Progress(MissionTaskType::MISSION_TASK_TYPE_SKILL, result.skillID); } @@ -1492,14 +1304,12 @@ std::vector InventoryComponent::FindBuffs(Item* item, bool castOnEquip return buffs; } -void InventoryComponent::SetNPCItems(const std::vector& items) -{ +void InventoryComponent::SetNPCItems(const std::vector& items) { m_Equipped.clear(); auto slot = 0u; - for (const auto& item : items) - { + for (const auto& item : items) { const LWOOBJID id = ObjectIDManager::Instance()->GenerateObjectID(); const auto& info = Inventory::FindItemComponent(item); @@ -1510,17 +1320,14 @@ void InventoryComponent::SetNPCItems(const std::vector& items) EntityManager::Instance()->SerializeEntity(m_Parent); } -InventoryComponent::~InventoryComponent() -{ - for (const auto& inventory : m_Inventories) - { +InventoryComponent::~InventoryComponent() { + for (const auto& inventory : m_Inventories) { delete inventory.second; } m_Inventories.clear(); - for (auto* set : m_Itemsets) - { + for (auto* set : m_Itemsets) { delete set; } @@ -1528,14 +1335,12 @@ InventoryComponent::~InventoryComponent() m_Pets.clear(); } -std::vector InventoryComponent::GenerateProxies(Item* parent) -{ +std::vector InventoryComponent::GenerateProxies(Item* parent) { std::vector proxies; auto subItems = parent->GetInfo().subItems; - if (subItems.empty()) - { + if (subItems.empty()) { return proxies; } @@ -1545,22 +1350,16 @@ std::vector InventoryComponent::GenerateProxies(Item* parent) std::string segment; std::vector lots; - while (std::getline(stream, segment, ',')) - { - try - { + while (std::getline(stream, segment, ',')) { + try { lots.push_back(std::stoi(segment)); - } - catch (std::invalid_argument& exception) - { + } catch (std::invalid_argument& exception) { Game::logger->Log("InventoryComponent", "Failed to parse proxy (%s): (%s)!", segment.c_str(), exception.what()); } } - for (const auto lot : lots) - { - if (!Inventory::IsValidItem(lot)) - { + for (const auto lot : lots) { + if (!Inventory::IsValidItem(lot)) { continue; } @@ -1576,18 +1375,15 @@ std::vector InventoryComponent::GenerateProxies(Item* parent) return proxies; } -std::vector InventoryComponent::FindProxies(const LWOOBJID parent) -{ +std::vector InventoryComponent::FindProxies(const LWOOBJID parent) { auto* inventory = GetInventory(ITEM_SETS); std::vector proxies; - for (const auto& pair : inventory->GetItems()) - { + for (const auto& pair : inventory->GetItems()) { auto* item = pair.second; - if (item->GetParent() == parent) - { + if (item->GetParent() == parent) { proxies.push_back(item); } } @@ -1595,18 +1391,14 @@ std::vector InventoryComponent::FindProxies(const LWOOBJID parent) return proxies; } -bool InventoryComponent::IsValidProxy(const LWOOBJID parent) -{ - for (const auto& pair : m_Inventories) - { +bool InventoryComponent::IsValidProxy(const LWOOBJID parent) { + for (const auto& pair : m_Inventories) { const auto items = pair.second->GetItems(); - for (const auto& candidate : items) - { + for (const auto& candidate : items) { auto* item = candidate.second; - if (item->GetId() == parent) - { + if (item->GetId() == parent) { return true; } } @@ -1615,25 +1407,20 @@ bool InventoryComponent::IsValidProxy(const LWOOBJID parent) return false; } -bool InventoryComponent::IsParentValid(Item* root) -{ - if (root->GetInfo().subItems.empty()) - { +bool InventoryComponent::IsParentValid(Item* root) { + if (root->GetInfo().subItems.empty()) { return true; } const auto id = root->GetId(); - for (const auto& pair : m_Inventories) - { + for (const auto& pair : m_Inventories) { const auto items = pair.second->GetItems(); - for (const auto& candidate : items) - { + for (const auto& candidate : items) { auto* item = candidate.second; - if (item->GetParent() == id) - { + if (item->GetParent() == id) { return true; } } @@ -1642,27 +1429,22 @@ bool InventoryComponent::IsParentValid(Item* root) return false; } -void InventoryComponent::CheckProxyIntegrity() -{ +void InventoryComponent::CheckProxyIntegrity() { std::vector dead; - for (const auto& pair : m_Inventories) - { + for (const auto& pair : m_Inventories) { const auto& items = pair.second->GetItems(); - for (const auto& candidate : items) - { + for (const auto& candidate : items) { auto* item = candidate.second; const auto parent = item->GetParent(); - if (parent == LWOOBJID_EMPTY) - { + if (parent == LWOOBJID_EMPTY) { continue; } - if (IsValidProxy(parent)) - { + if (IsValidProxy(parent)) { continue; } @@ -1670,8 +1452,7 @@ void InventoryComponent::CheckProxyIntegrity() } } - for (auto* item : dead) - { + for (auto* item : dead) { item->RemoveFromInventory(); } @@ -1714,16 +1495,13 @@ void InventoryComponent::CheckProxyIntegrity() */ } -void InventoryComponent::PurgeProxies(Item* item) -{ +void InventoryComponent::PurgeProxies(Item* item) { const auto root = item->GetParent(); - if (root != LWOOBJID_EMPTY) - { + if (root != LWOOBJID_EMPTY) { item = FindItemById(root); - if (item != nullptr) - { + if (item != nullptr) { UnEquipItem(item); } @@ -1732,20 +1510,17 @@ void InventoryComponent::PurgeProxies(Item* item) auto proxies = FindProxies(item->GetId()); - for (auto* proxy : proxies) - { + for (auto* proxy : proxies) { proxy->UnEquip(); proxy->RemoveFromInventory(); } } -void InventoryComponent::LoadPetXml(tinyxml2::XMLDocument* document) -{ +void InventoryComponent::LoadPetXml(tinyxml2::XMLDocument* document) { auto* petInventoryElement = document->FirstChildElement("obj")->FirstChildElement("pet"); - if (petInventoryElement == nullptr) - { + if (petInventoryElement == nullptr) { m_Pets.clear(); return; @@ -1753,8 +1528,7 @@ void InventoryComponent::LoadPetXml(tinyxml2::XMLDocument* document) auto* petElement = petInventoryElement->FirstChildElement(); - while (petElement != nullptr) - { + while (petElement != nullptr) { LWOOBJID id; LOT lot; int32_t moderationStatus; @@ -1775,12 +1549,10 @@ void InventoryComponent::LoadPetXml(tinyxml2::XMLDocument* document) } } -void InventoryComponent::UpdatePetXml(tinyxml2::XMLDocument* document) -{ +void InventoryComponent::UpdatePetXml(tinyxml2::XMLDocument* document) { auto* petInventoryElement = document->FirstChildElement("obj")->FirstChildElement("pet"); - if (petInventoryElement == nullptr) - { + if (petInventoryElement == nullptr) { petInventoryElement = document->NewElement("pet"); document->FirstChildElement("obj")->LinkEndChild(petInventoryElement); @@ -1788,8 +1560,7 @@ void InventoryComponent::UpdatePetXml(tinyxml2::XMLDocument* document) petInventoryElement->DeleteChildren(); - for (const auto& pet : m_Pets) - { + for (const auto& pet : m_Pets) { auto* petElement = document->NewElement("p"); petElement->SetAttribute("id", pet.first); diff --git a/dGame/dComponents/InventoryComponent.h b/dGame/dComponents/InventoryComponent.h index a7d3f8ea..01b4ca86 100644 --- a/dGame/dComponents/InventoryComponent.h +++ b/dGame/dComponents/InventoryComponent.h @@ -38,66 +38,66 @@ public: static const uint32_t ComponentType = COMPONENT_TYPE_INVENTORY; explicit InventoryComponent(Entity* parent, tinyxml2::XMLDocument* document = nullptr); - void Update(float deltaTime) override; - void Serialize(RakNet::BitStream* outBitStream, bool bIsInitialUpdate, unsigned int& flags); - void LoadXml(tinyxml2::XMLDocument* document); - void UpdateXml(tinyxml2::XMLDocument* document) override; - void ResetFlags(); + void Update(float deltaTime) override; + void Serialize(RakNet::BitStream* outBitStream, bool bIsInitialUpdate, unsigned int& flags); + void LoadXml(tinyxml2::XMLDocument* document); + void UpdateXml(tinyxml2::XMLDocument* document) override; + void ResetFlags(); - /** - * Returns an inventory of the specified type, if it exists - * @param type the inventory type to find an inventory for - * @return the inventory of the specified type - */ + /** + * Returns an inventory of the specified type, if it exists + * @param type the inventory type to find an inventory for + * @return the inventory of the specified type + */ Inventory* GetInventory(eInventoryType type); - /** - * Returns all the inventories this entity has, indexed by type - * @return all the inventories this entity has, indexed by type - */ + /** + * Returns all the inventories this entity has, indexed by type + * @return all the inventories this entity has, indexed by type + */ const std::map& GetInventories() const; - /** - * Returns the amount of items this entity possesses of a certain LOT - * @param lot the lot to search for - * @return the amount of items this entity possesses the specified LOT - */ + /** + * Returns the amount of items this entity possesses of a certain LOT + * @param lot the lot to search for + * @return the amount of items this entity possesses the specified LOT + */ uint32_t GetLotCount(LOT lot) const; - /** - * Returns the amount of items this entity possesses of a LOT, given that they're not in a temporary inventory - * (vendor buyback, vault, etc). - * @param lot the lot to search for - * @return the amount of items this entity possesses of the specified lot - */ + /** + * Returns the amount of items this entity possesses of a LOT, given that they're not in a temporary inventory + * (vendor buyback, vault, etc). + * @param lot the lot to search for + * @return the amount of items this entity possesses of the specified lot + */ uint32_t GetLotCountNonTransfer(LOT lot) const; - /** - * Returns the items that are currently equipped by this entity - * @return the items that are currently equipped by this entity - */ + /** + * Returns the items that are currently equipped by this entity + * @return the items that are currently equipped by this entity + */ const EquipmentMap& GetEquippedItems() const; - /** - * Adds an item to the inventory of the entity - * @param lot the lot to add - * @param count the amount of items to add - * @param inventoryType the inventory to add the item to - * @param config optional config for this item, used for example for rockets - * @param parent optional parent of this item, used for proxy items - * @param showFlyingLoot show a client animation if the item is added - * @param isModMoveAndEquip equips the item - * @param subKey optional sub ID of a related object, used by pets - * @param inventorySourceType if the inventory was moved, the source inventory - * @param sourceType the source of the item, used to determine if the item is dropped or mailed if the inventory is full - * @param bound whether this item is bound - * @param preferredSlot the preferred slot to store this item - * @param lootSourceType The source of the loot. Defaults to none. - */ + /** + * Adds an item to the inventory of the entity + * @param lot the lot to add + * @param count the amount of items to add + * @param inventoryType the inventory to add the item to + * @param config optional config for this item, used for example for rockets + * @param parent optional parent of this item, used for proxy items + * @param showFlyingLoot show a client animation if the item is added + * @param isModMoveAndEquip equips the item + * @param subKey optional sub ID of a related object, used by pets + * @param inventorySourceType if the inventory was moved, the source inventory + * @param sourceType the source of the item, used to determine if the item is dropped or mailed if the inventory is full + * @param bound whether this item is bound + * @param preferredSlot the preferred slot to store this item + * @param lootSourceType The source of the loot. Defaults to none. + */ void AddItem( LOT lot, uint32_t count, - eLootSourceType lootSourceType = eLootSourceType::LOOT_SOURCE_NONE, + eLootSourceType lootSourceType = eLootSourceType::LOOT_SOURCE_NONE, eInventoryType inventoryType = INVALID, const std::vector& config = {}, LWOOBJID parent = LWOOBJID_EMPTY, @@ -110,65 +110,65 @@ public: int32_t preferredSlot = -1 ); - /** - * Removes a LOT from the inventory - * @param lot the lot to remove - * @param count the number of items to remove - * @param inventoryType optional inventory type to remove the item from - * @param ignoreBound ignores bound items - */ + /** + * Removes a LOT from the inventory + * @param lot the lot to remove + * @param count the number of items to remove + * @param inventoryType optional inventory type to remove the item from + * @param ignoreBound ignores bound items + */ void RemoveItem(LOT lot, uint32_t count, eInventoryType inventoryType = INVALID, bool ignoreBound = false); - /** - * Moves an existing item to an inventory of the entity - * @param item the item to add - * @param inventory the inventory to add the item to - * @param count the number of items to add - * @param showFlyingLot displays UI animation to the user - * @param isModMoveAndEquip equips the item - * @param ignoreEquipped does not stack on equipped items - * @param preferredSlot the preferred slot to store the item in - */ + /** + * Moves an existing item to an inventory of the entity + * @param item the item to add + * @param inventory the inventory to add the item to + * @param count the number of items to add + * @param showFlyingLot displays UI animation to the user + * @param isModMoveAndEquip equips the item + * @param ignoreEquipped does not stack on equipped items + * @param preferredSlot the preferred slot to store the item in + */ void MoveItemToInventory(Item* item, eInventoryType inventory, uint32_t count, bool showFlyingLot = true, bool isModMoveAndEquip = false, bool ignoreEquipped = false, int32_t preferredSlot = -1); - /** - * Moves a stack of items to an inventory - * @param item the item to move - * @param inventory the inventory to move the item to - * @param slot the slot in the inventory to move the item to - */ + /** + * Moves a stack of items to an inventory + * @param item the item to move + * @param inventory the inventory to move the item to + * @param slot the slot in the inventory to move the item to + */ void MoveStack(Item* item, eInventoryType inventory, uint32_t slot = 0); - /** - * Returns an item in the inventory by object ID - * @param id the id of the item to find - * @return item in the inventory by object ID - */ + /** + * Returns an item in the inventory by object ID + * @param id the id of the item to find + * @return item in the inventory by object ID + */ Item* FindItemById(LWOOBJID id) const; - /** - * Returns an item in the inventory that matches the specified LOT - * @param lot the lot of the item to find - * @param inventoryType optional inventory to search in - * @param ignoreEquipped ignores items that are equipped - * @param ignoreBound ignores items that are bound - * @return item in the inventory that matches the specified LOT - */ + /** + * Returns an item in the inventory that matches the specified LOT + * @param lot the lot of the item to find + * @param inventoryType optional inventory to search in + * @param ignoreEquipped ignores items that are equipped + * @param ignoreBound ignores items that are bound + * @return item in the inventory that matches the specified LOT + */ Item* FindItemByLot(LOT lot, eInventoryType inventoryType = INVALID, bool ignoreEquipped = false, bool ignoreBound = false); - /** - * Finds an item in the inventory that has the specified subkey, useful for pets - * @param id the subkey to look for - * @param inventoryType optional inventory type to search in - * @return item in the inventory that has the specified subkey - */ + /** + * Finds an item in the inventory that has the specified subkey, useful for pets + * @param id the subkey to look for + * @param inventoryType optional inventory type to search in + * @return item in the inventory that has the specified subkey + */ Item* FindItemBySubKey(LWOOBJID id, eInventoryType inventoryType = INVALID); - /** - * Checks if the entity has enough space for a batch of loot - * @param loot a map of items to add and how many to add - * @return whether the entity has enough space for all the items - */ + /** + * Checks if the entity has enough space for a batch of loot + * @param loot a map of items to add and how many to add + * @return whether the entity has enough space for all the items + */ bool HasSpaceForLoot(const std::unordered_map& loot); /** @@ -179,84 +179,84 @@ public: */ void UpdateSlot(const std::string& location, EquippedItem item, bool keepCurrent = false); - /** - * Removes a slot from the inventory - * @param location the slot to remove - */ + /** + * Removes a slot from the inventory + * @param location the slot to remove + */ void RemoveSlot(const std::string& location); - /** - * Equips the given item, guesses the slot to equip it in - * @param item the item to equip - * @param skipChecks skips checks for equipping cars and rockets (e.g. no special behavior follows) - */ + /** + * Equips the given item, guesses the slot to equip it in + * @param item the item to equip + * @param skipChecks skips checks for equipping cars and rockets (e.g. no special behavior follows) + */ void EquipItem(Item* item, bool skipChecks = false); - /** - * Unequips an item from the inventory - * @param item the item to unequip - */ + /** + * Unequips an item from the inventory + * @param item the item to unequip + */ void UnEquipItem(Item* item); - /** - * Adds a buff related to equipping a lot to the entity - * @param item the item to find buffs for - */ + /** + * Adds a buff related to equipping a lot to the entity + * @param item the item to find buffs for + */ void ApplyBuff(Item* item) const; - /** - * Removes buffs related to equipping a lot from the entity - * @param item the item to find buffs for - */ + /** + * Removes buffs related to equipping a lot from the entity + * @param item the item to find buffs for + */ void RemoveBuff(Item* item) const; - /** - * Saves the equipped items into a temp state - */ + /** + * Saves the equipped items into a temp state + */ void PushEquippedItems(); - /** - * Unequips all the temporary items and equips the previous item state - */ + /** + * Unequips all the temporary items and equips the previous item state + */ void PopEquippedItems(); - /** - * Returns if the entity has an item equipped of the given lot - * @param lot to lot to search for - * @return if the entity has an item equipped of the given lot - */ + /** + * Returns if the entity has an item equipped of the given lot + * @param lot to lot to search for + * @return if the entity has an item equipped of the given lot + */ bool IsEquipped(LOT lot) const; - /** - * Checks and ensures that we have loaded the item set that might be related to this item - * @param lot the lot to check the item set for - */ + /** + * Checks and ensures that we have loaded the item set that might be related to this item + * @param lot the lot to check the item set for + */ void CheckItemSet(LOT lot); - /** - * Sets the current consumable lot - * @param lot the lot to set as consumable - */ + /** + * Sets the current consumable lot + * @param lot the lot to set as consumable + */ void SetConsumable(LOT lot); - /** - * Returns the current consumable lot - * @return the current consumable lot - */ + /** + * Returns the current consumable lot + * @return the current consumable lot + */ LOT GetConsumable() const; - /** - * Finds all the buffs related to a lot - * @param item the item to get the buffs for - * @param castOnEquip if true, the skill missions for these buffs will be progressed - * @return the buffs related to the specified lot - */ + /** + * Finds all the buffs related to a lot + * @param item the item to get the buffs for + * @param castOnEquip if true, the skill missions for these buffs will be progressed + * @return the buffs related to the specified lot + */ std::vector FindBuffs(Item* item, bool castOnEquip) const; - /** - * Initializes the equipped items with a list of items - * @param items the items to equip - */ + /** + * Initializes the equipped items with a list of items + * @param items the items to equip + */ void SetNPCItems(const std::vector& items); /** @@ -265,189 +265,189 @@ public: */ void AddItemSkills(LOT lot); - /** - * Removes the skills related to the passed LOT from the currently equipped skills - * @param lot the lot to remove - */ + /** + * Removes the skills related to the passed LOT from the currently equipped skills + * @param lot the lot to remove + */ void RemoveItemSkills(LOT lot); - /** - * Triggers one of the passive abilities from the equipped item set - * @param trigger the trigger to fire - */ + /** + * Triggers one of the passive abilities from the equipped item set + * @param trigger the trigger to fire + */ void TriggerPassiveAbility(PassiveAbilityTrigger trigger); - /** - * Returns if the entity has any of the passed passive abilities equipped - * @param passiveIDs the IDs to check for - * @param equipmentRequirement the number of equipment required to be allowed to have the ability - * @return if the entity has any of the passed passive abilities equipped - */ + /** + * Returns if the entity has any of the passed passive abilities equipped + * @param passiveIDs the IDs to check for + * @param equipmentRequirement the number of equipment required to be allowed to have the ability + * @return if the entity has any of the passed passive abilities equipped + */ bool HasAnyPassive(const std::vector& passiveIDs, int32_t equipmentRequirement) const; - /** - * Despawns the currently active pet, if any - */ + /** + * Despawns the currently active pet, if any + */ void DespawnPet(); - /** - * Spawns the item as a pet (if it is one) - * @param item the pet to spawn - */ + /** + * Spawns the item as a pet (if it is one) + * @param item the pet to spawn + */ void SpawnPet(Item* item); - /** - * Updates the database pet data for an item (e.g. moderation status) - * @param id the id of the pet to find - * @param data the data to store on the pet - */ + /** + * Updates the database pet data for an item (e.g. moderation status) + * @param id the id of the pet to find + * @param data the data to store on the pet + */ void SetDatabasePet(LWOOBJID id, const DatabasePet& data); - /** - * Returns the database pet information for an object - * @param id the object ID to search for - * @return the database pet information for the object that belongs to the passed id - */ + /** + * Returns the database pet information for an object + * @param id the object ID to search for + * @return the database pet information for the object that belongs to the passed id + */ const DatabasePet& GetDatabasePet(LWOOBJID id) const; - /** - * Checks if the provided object ID is in this inventory and is a pet - * @param id the id of the object to check for - * @return if the provided object ID is in this inventory and is a pet - */ + /** + * Checks if the provided object ID is in this inventory and is a pet + * @param id the id of the object to check for + * @return if the provided object ID is in this inventory and is a pet + */ bool IsPet(LWOOBJID id) const; - /** - * Removes pet database information from the item with the specified object id - * @param id the object id to remove pet info for - */ + /** + * Removes pet database information from the item with the specified object id + * @param id the object id to remove pet info for + */ void RemoveDatabasePet(LWOOBJID id); - /** - * Returns the current behavior slot active for the passed item type - * @param type the item type to find the behavior slot for - * @return the current behavior slot active for the passed item type - */ + /** + * Returns the current behavior slot active for the passed item type + * @param type the item type to find the behavior slot for + * @return the current behavior slot active for the passed item type + */ static BehaviorSlot FindBehaviorSlot(eItemType type); - /** - * Checks if the inventory type is a temp inventory - * @param type the inventory type to check - * @return if the inventory type is a temp inventory - */ + /** + * Checks if the inventory type is a temp inventory + * @param type the inventory type to check + * @return if the inventory type is a temp inventory + */ static bool IsTransferInventory(eInventoryType type); - /** - * Finds the skill related to the passed LOT from the ObjectSkills table - * @param lot the lot to find - * @return the skill related to the passed LOT - */ + /** + * Finds the skill related to the passed LOT from the ObjectSkills table + * @param lot the lot to find + * @return the skill related to the passed LOT + */ static uint32_t FindSkill(LOT lot); - + ~InventoryComponent() override; - + private: - /** - * All the inventory this entity possesses - */ + /** + * All the inventory this entity possesses + */ std::map m_Inventories; - /** - * The skills that this entity currently has active - */ + /** + * The skills that this entity currently has active + */ std::map m_Skills; - /** - * The pets this entity has, mapped by object ID and pet info - */ + /** + * The pets this entity has, mapped by object ID and pet info + */ std::unordered_map m_Pets; - /** - * Cache of item sets this entity has encountered - */ + /** + * Cache of item sets this entity has encountered + */ std::vector m_Itemsets; - /** - * The LOTs we've checked all the item sets for (for cache reasons) - */ + /** + * The LOTs we've checked all the item sets for (for cache reasons) + */ std::vector m_ItemSetsChecked; - /** - * all the equipped items - */ + /** + * all the equipped items + */ EquipmentMap m_Equipped; - /** - * Clone of the equipped items before unequipping all of them - */ + /** + * Clone of the equipped items before unequipping all of them + */ EquipmentMap m_Pushed; - /** - * If the inventory has changed - */ + /** + * If the inventory has changed + */ bool m_Dirty; - /** - * The currently active consumable - */ + /** + * The currently active consumable + */ LOT m_Consumable; - /** - * Currently has a car equipped - */ - bool hasCarEquipped = false; - Entity* equippedCarEntity = nullptr; - LWOOBJID previousPossessableID = LWOOBJID_EMPTY; - LWOOBJID previousPossessorID = LWOOBJID_EMPTY; - /** - * Creates all the proxy items (subitems) for a parent item - * @param parent the parent item to generate all the subitems for - * @return the proxy items (subitems) for a parent item - */ + /** + * Currently has a car equipped + */ + bool hasCarEquipped = false; + Entity* equippedCarEntity = nullptr; + LWOOBJID previousPossessableID = LWOOBJID_EMPTY; + LWOOBJID previousPossessorID = LWOOBJID_EMPTY; + /** + * Creates all the proxy items (subitems) for a parent item + * @param parent the parent item to generate all the subitems for + * @return the proxy items (subitems) for a parent item + */ std::vector GenerateProxies(Item* parent); - /** - * Finds all the proxy items in this inventory for a given parent item - * @param parent the parent to find proxy items for - * @return the proxy items for the parent - */ + /** + * Finds all the proxy items in this inventory for a given parent item + * @param parent the parent to find proxy items for + * @return the proxy items for the parent + */ std::vector FindProxies(LWOOBJID parent); - /** - * Returns true if the provided LWOOBJID is the parent of this Item. - * @param parent the parent item to check for proxies - * @return if the provided ID is a valid proxy item - */ + /** + * Returns true if the provided LWOOBJID is the parent of this Item. + * @param parent the parent item to check for proxies + * @return if the provided ID is a valid proxy item + */ bool IsValidProxy(LWOOBJID parent); - /** - * Returns if the provided ID is a valid proxy item (e.g. we have children for it) - * @param parent the parent item to check for - * @return if the provided ID is a valid proxy item - */ + /** + * Returns if the provided ID is a valid proxy item (e.g. we have children for it) + * @param parent the parent item to check for + * @return if the provided ID is a valid proxy item + */ bool IsParentValid(Item* root); - /** - * Removes all the proxy items that have a dangling parent - */ + /** + * Removes all the proxy items that have a dangling parent + */ void CheckProxyIntegrity(); - /** - * Removes all the proxy items for a given parent from the inventory - * @param item the item to remove proxy items for - */ + /** + * Removes all the proxy items for a given parent from the inventory + * @param item the item to remove proxy items for + */ void PurgeProxies(Item* item); - /** - * Saves all the pet information stored in inventory items to the database - * @param document the xml doc to save to - */ + /** + * Saves all the pet information stored in inventory items to the database + * @param document the xml doc to save to + */ void LoadPetXml(tinyxml2::XMLDocument* document); - /** - * Loads all the pet information from an xml doc into items - * @param document the xml doc to load from - */ + /** + * Loads all the pet information from an xml doc into items + * @param document the xml doc to load from + */ void UpdatePetXml(tinyxml2::XMLDocument* document); }; diff --git a/dGame/dComponents/LUPExhibitComponent.cpp b/dGame/dComponents/LUPExhibitComponent.cpp index 8c825a30..7b8c85ba 100644 --- a/dGame/dComponents/LUPExhibitComponent.cpp +++ b/dGame/dComponents/LUPExhibitComponent.cpp @@ -2,50 +2,43 @@ #include "EntityManager.h" -LUPExhibitComponent::LUPExhibitComponent(Entity* parent) : Component(parent) -{ - m_Exhibits = { 11121, 11295, 11423, 11979 }; +LUPExhibitComponent::LUPExhibitComponent(Entity* parent) : Component(parent) { + m_Exhibits = { 11121, 11295, 11423, 11979 }; - m_ExhibitIndex = 0; + m_ExhibitIndex = 0; - m_Exhibit = m_Exhibits[m_ExhibitIndex]; + m_Exhibit = m_Exhibits[m_ExhibitIndex]; } -LUPExhibitComponent::~LUPExhibitComponent() -{ - +LUPExhibitComponent::~LUPExhibitComponent() { + } -void LUPExhibitComponent::Update(float deltaTime) -{ - m_UpdateTimer += deltaTime; +void LUPExhibitComponent::Update(float deltaTime) { + m_UpdateTimer += deltaTime; - if (m_UpdateTimer > 20.0f) - { - NextExhibit(); + if (m_UpdateTimer > 20.0f) { + NextExhibit(); - m_UpdateTimer = 0.0f; - } + m_UpdateTimer = 0.0f; + } } -void LUPExhibitComponent::NextExhibit() -{ - m_ExhibitIndex++; +void LUPExhibitComponent::NextExhibit() { + m_ExhibitIndex++; - if (m_ExhibitIndex >= m_Exhibits.size()) - { - m_ExhibitIndex = 0; - } + if (m_ExhibitIndex >= m_Exhibits.size()) { + m_ExhibitIndex = 0; + } - m_Exhibit = m_Exhibits[m_ExhibitIndex]; + m_Exhibit = m_Exhibits[m_ExhibitIndex]; - EntityManager::Instance()->SerializeEntity(m_Parent); + EntityManager::Instance()->SerializeEntity(m_Parent); } -void LUPExhibitComponent::Serialize(RakNet::BitStream* outBitStream, bool bIsInitialUpdate, uint32_t& flags) -{ - outBitStream->Write1(); // Dirty flag? - outBitStream->Write(m_Exhibit); +void LUPExhibitComponent::Serialize(RakNet::BitStream* outBitStream, bool bIsInitialUpdate, uint32_t& flags) { + outBitStream->Write1(); // Dirty flag? + outBitStream->Write(m_Exhibit); } diff --git a/dGame/dComponents/LUPExhibitComponent.h b/dGame/dComponents/LUPExhibitComponent.h index b9ecf70a..2d128f6c 100644 --- a/dGame/dComponents/LUPExhibitComponent.h +++ b/dGame/dComponents/LUPExhibitComponent.h @@ -11,34 +11,34 @@ class LUPExhibitComponent : public Component { public: static const uint32_t ComponentType = COMPONENT_TYPE_EXHIBIT; - - LUPExhibitComponent(Entity* parent); - ~LUPExhibitComponent(); - void Update(float deltaTime) override; - void Serialize(RakNet::BitStream* outBitStream, bool bIsInitialUpdate, uint32_t& flags); - /** - * After the timer runs out, this changes the currently exhibited LOT to the next one - */ - void NextExhibit(); + LUPExhibitComponent(Entity* parent); + ~LUPExhibitComponent(); + void Update(float deltaTime) override; + void Serialize(RakNet::BitStream* outBitStream, bool bIsInitialUpdate, uint32_t& flags); + + /** + * After the timer runs out, this changes the currently exhibited LOT to the next one + */ + void NextExhibit(); private: - /** - * The LOT that's currently on exhibit - */ - LOT m_Exhibit; + /** + * The LOT that's currently on exhibit + */ + LOT m_Exhibit; - /** - * The time since we've last updated the exhibit - */ - float m_UpdateTimer; + /** + * The time since we've last updated the exhibit + */ + float m_UpdateTimer; - /** - * The list of possible exhibits to show - */ - std::vector m_Exhibits; + /** + * The list of possible exhibits to show + */ + std::vector m_Exhibits; - /** - * The current index in the exhibit list - */ - size_t m_ExhibitIndex; + /** + * The current index in the exhibit list + */ + size_t m_ExhibitIndex; }; diff --git a/dGame/dComponents/LevelProgressionComponent.cpp b/dGame/dComponents/LevelProgressionComponent.cpp index ff4f3f85..ee3cfc6b 100644 --- a/dGame/dComponents/LevelProgressionComponent.cpp +++ b/dGame/dComponents/LevelProgressionComponent.cpp @@ -19,7 +19,7 @@ void LevelProgressionComponent::UpdateXml(tinyxml2::XMLDocument* doc) { } -void LevelProgressionComponent::LoadFromXml(tinyxml2::XMLDocument* doc){ +void LevelProgressionComponent::LoadFromXml(tinyxml2::XMLDocument* doc) { tinyxml2::XMLElement* level = doc->FirstChildElement("obj")->FirstChildElement("lvl"); if (!level) { Game::logger->Log("LevelProgressionComponent", "Failed to find lvl tag while loading XML!"); @@ -29,7 +29,7 @@ void LevelProgressionComponent::LoadFromXml(tinyxml2::XMLDocument* doc){ } -void LevelProgressionComponent::Serialize(RakNet::BitStream* outBitStream, bool bIsInitialUpdate, unsigned int& flags){ +void LevelProgressionComponent::Serialize(RakNet::BitStream* outBitStream, bool bIsInitialUpdate, unsigned int& flags) { outBitStream->Write(bIsInitialUpdate || m_DirtyLevelInfo); if (bIsInitialUpdate || m_DirtyLevelInfo) outBitStream->Write(m_Level); m_DirtyLevelInfo = false; @@ -46,7 +46,7 @@ void LevelProgressionComponent::HandleLevelUp() { if (!inventoryComponent || !controllablePhysicsComponent) return; // Tell the client we beginning to send level rewards. - if(rewardingItem) GameMessages::NotifyLevelRewards(m_Parent->GetObjectID(), m_Parent->GetSystemAddress(), m_Level, rewardingItem); + if (rewardingItem) GameMessages::NotifyLevelRewards(m_Parent->GetObjectID(), m_Parent->GetSystemAddress(), m_Level, rewardingItem); for (auto* reward : rewards) { switch (reward->rewardType) { @@ -54,11 +54,11 @@ void LevelProgressionComponent::HandleLevelUp() { inventoryComponent->AddItem(reward->value, reward->count, eLootSourceType::LOOT_SOURCE_LEVEL_REWARD); break; case 4: - { - auto* items = inventoryComponent->GetInventory(eInventoryType::ITEMS); - items->SetSize(items->GetSize() + reward->value); - } - break; + { + auto* items = inventoryComponent->GetInventory(eInventoryType::ITEMS); + items->SetSize(items->GetSize() + reward->value); + } + break; case 9: controllablePhysicsComponent->SetSpeedMultiplier(static_cast(reward->value) / 500.0f); break; @@ -70,5 +70,5 @@ void LevelProgressionComponent::HandleLevelUp() { } } // Tell the client we have finished sending level rewards. - if(rewardingItem) GameMessages::NotifyLevelRewards(m_Parent->GetObjectID(), m_Parent->GetSystemAddress(), m_Level, !rewardingItem); + if (rewardingItem) GameMessages::NotifyLevelRewards(m_Parent->GetObjectID(), m_Parent->GetSystemAddress(), m_Level, !rewardingItem); } diff --git a/dGame/dComponents/MissionComponent.cpp b/dGame/dComponents/MissionComponent.cpp index 03cb65ea..ad77cf34 100644 --- a/dGame/dComponents/MissionComponent.cpp +++ b/dGame/dComponents/MissionComponent.cpp @@ -18,7 +18,7 @@ #include "Mail.h" #include "MissionPrerequisites.h" -// MARK: Mission Component + // MARK: Mission Component std::unordered_map> MissionComponent::m_AchievementCache = {}; @@ -28,588 +28,582 @@ MissionComponent::MissionComponent(Entity* parent) : Component(parent) { //! Destructor MissionComponent::~MissionComponent() { - for (const auto& mission : m_Missions) { - delete mission.second; - } + for (const auto& mission : m_Missions) { + delete mission.second; + } - this->m_Missions.clear(); + this->m_Missions.clear(); } Mission* MissionComponent::GetMission(const uint32_t missionId) const { - if (m_Missions.count(missionId) == 0) { - return nullptr; - } + if (m_Missions.count(missionId) == 0) { + return nullptr; + } - const auto& index = m_Missions.find(missionId); + const auto& index = m_Missions.find(missionId); - if (index == m_Missions.end()) { - return nullptr; - } + if (index == m_Missions.end()) { + return nullptr; + } - return index->second; + return index->second; } MissionState MissionComponent::GetMissionState(const uint32_t missionId) const { - auto* mission = GetMission(missionId); + auto* mission = GetMission(missionId); - if (mission == nullptr) { - return CanAccept(missionId) ? MissionState::MISSION_STATE_AVAILABLE : MissionState::MISSION_STATE_UNKNOWN; - } + if (mission == nullptr) { + return CanAccept(missionId) ? MissionState::MISSION_STATE_AVAILABLE : MissionState::MISSION_STATE_UNKNOWN; + } - return mission->GetMissionState(); + return mission->GetMissionState(); } const std::unordered_map& MissionComponent::GetMissions() const { - return m_Missions; + return m_Missions; } bool MissionComponent::CanAccept(const uint32_t missionId) const { - return MissionPrerequisites::CanAccept(missionId, m_Missions); + return MissionPrerequisites::CanAccept(missionId, m_Missions); } void MissionComponent::AcceptMission(const uint32_t missionId, const bool skipChecks) { - if (!skipChecks && !CanAccept(missionId)) { - return; - } + if (!skipChecks && !CanAccept(missionId)) { + return; + } - // If this is a daily mission, it may already be "accepted" - auto* mission = this->GetMission(missionId); + // If this is a daily mission, it may already be "accepted" + auto* mission = this->GetMission(missionId); - if (mission != nullptr) { - if (mission->GetClientInfo().repeatable) { - mission->Accept(); - } + if (mission != nullptr) { + if (mission->GetClientInfo().repeatable) { + mission->Accept(); + } - return; - } + return; + } - mission = new Mission(this, missionId); + mission = new Mission(this, missionId); - mission->Accept(); + mission->Accept(); - this->m_Missions.insert_or_assign(missionId, mission); + this->m_Missions.insert_or_assign(missionId, mission); - if (missionId == 1728) { - //Needs to send a mail + if (missionId == 1728) { + //Needs to send a mail - auto address = m_Parent->GetSystemAddress(); + auto address = m_Parent->GetSystemAddress(); - Mail::HandleNotificationRequest(address, m_Parent->GetObjectID()); - } + Mail::HandleNotificationRequest(address, m_Parent->GetObjectID()); + } } void MissionComponent::CompleteMission(const uint32_t missionId, const bool skipChecks, const bool yieldRewards) { - // Get the mission first - auto* mission = this->GetMission(missionId); + // Get the mission first + auto* mission = this->GetMission(missionId); - if (mission == nullptr) { - AcceptMission(missionId, skipChecks); + if (mission == nullptr) { + AcceptMission(missionId, skipChecks); - mission = this->GetMission(missionId); + mission = this->GetMission(missionId); - if (mission == nullptr) { - return; - } - } + if (mission == nullptr) { + return; + } + } - //If this mission is not repeatable, and already completed, we stop here. - if (mission->IsComplete() && !mission->IsRepeatable()) { - return; - } + //If this mission is not repeatable, and already completed, we stop here. + if (mission->IsComplete() && !mission->IsRepeatable()) { + return; + } - mission->Complete(yieldRewards); + mission->Complete(yieldRewards); } void MissionComponent::RemoveMission(uint32_t missionId) { - auto* mission = this->GetMission(missionId); + auto* mission = this->GetMission(missionId); - if (mission == nullptr) { - return; - } + if (mission == nullptr) { + return; + } - delete mission; + delete mission; - m_Missions.erase(missionId); + m_Missions.erase(missionId); } void MissionComponent::Progress(MissionTaskType type, int32_t value, LWOOBJID associate, const std::string& targets, int32_t count, bool ignoreAchievements) { - for (const auto& pair : m_Missions) { - auto* mission = pair.second; + for (const auto& pair : m_Missions) { + auto* mission = pair.second; - if (mission->IsAchievement() && ignoreAchievements) continue; + if (mission->IsAchievement() && ignoreAchievements) continue; - if (mission->IsComplete()) continue; + if (mission->IsComplete()) continue; - mission->Progress(type, value, associate, targets, count); - } + mission->Progress(type, value, associate, targets, count); + } - if (count > 0 && !ignoreAchievements) { - LookForAchievements(type, value, true, associate, targets, count); - } + if (count > 0 && !ignoreAchievements) { + LookForAchievements(type, value, true, associate, targets, count); + } } void MissionComponent::ForceProgress(const uint32_t missionId, const uint32_t taskId, const int32_t value, const bool acceptMission) { - auto* mission = GetMission(missionId); + auto* mission = GetMission(missionId); - if (mission == nullptr) { - if (!acceptMission) { - return; - } + if (mission == nullptr) { + if (!acceptMission) { + return; + } - AcceptMission(missionId); + AcceptMission(missionId); - mission = GetMission(missionId); + mission = GetMission(missionId); - if (mission == nullptr) { - return; - } - } + if (mission == nullptr) { + return; + } + } - for (auto* element : mission->GetTasks()) { - if (element->GetClientInfo().uid != taskId) continue; + for (auto* element : mission->GetTasks()) { + if (element->GetClientInfo().uid != taskId) continue; - element->AddProgress(value); - } + element->AddProgress(value); + } - if (!mission->IsComplete()) { - mission->CheckCompletion(); - } + if (!mission->IsComplete()) { + mission->CheckCompletion(); + } } void MissionComponent::ForceProgressTaskType(const uint32_t missionId, const uint32_t taskType, const int32_t value, const bool acceptMission) { - auto* mission = GetMission(missionId); + auto* mission = GetMission(missionId); - if (mission == nullptr) { - if (!acceptMission) { - return; - } + if (mission == nullptr) { + if (!acceptMission) { + return; + } - CDMissions missionInfo; + CDMissions missionInfo; - if (!GetMissionInfo(missionId, missionInfo)) { - return; - } + if (!GetMissionInfo(missionId, missionInfo)) { + return; + } - if (missionInfo.isMission) { - return; - } + if (missionInfo.isMission) { + return; + } - AcceptMission(missionId); + AcceptMission(missionId); - mission = GetMission(missionId); + mission = GetMission(missionId); - if (mission == nullptr) { - return; - } - } + if (mission == nullptr) { + return; + } + } - for (auto* element : mission->GetTasks()) { - if (element->GetType() != static_cast(taskType)) continue; + for (auto* element : mission->GetTasks()) { + if (element->GetType() != static_cast(taskType)) continue; - element->AddProgress(value); - } + element->AddProgress(value); + } - if (!mission->IsComplete()) { - mission->CheckCompletion(); - } + if (!mission->IsComplete()) { + mission->CheckCompletion(); + } } -void MissionComponent::ForceProgressValue(uint32_t missionId, uint32_t taskType, int32_t value, bool acceptMission) -{ - auto* mission = GetMission(missionId); +void MissionComponent::ForceProgressValue(uint32_t missionId, uint32_t taskType, int32_t value, bool acceptMission) { + auto* mission = GetMission(missionId); - if (mission == nullptr) { - if (!acceptMission) { - return; - } + if (mission == nullptr) { + if (!acceptMission) { + return; + } - CDMissions missionInfo; + CDMissions missionInfo; - if (!GetMissionInfo(missionId, missionInfo)) { - return; - } + if (!GetMissionInfo(missionId, missionInfo)) { + return; + } - if (missionInfo.isMission) { - return; - } + if (missionInfo.isMission) { + return; + } - AcceptMission(missionId); + AcceptMission(missionId); - mission = GetMission(missionId); + mission = GetMission(missionId); - if (mission == nullptr) { - return; - } - } + if (mission == nullptr) { + return; + } + } - for (auto* element : mission->GetTasks()) { - if (element->GetType() != static_cast(taskType) || !element->InAllTargets(value)) continue; + for (auto* element : mission->GetTasks()) { + if (element->GetType() != static_cast(taskType) || !element->InAllTargets(value)) continue; - element->AddProgress(1); - } + element->AddProgress(1); + } - if (!mission->IsComplete()) { - mission->CheckCompletion(); - } + if (!mission->IsComplete()) { + mission->CheckCompletion(); + } } bool MissionComponent::GetMissionInfo(uint32_t missionId, CDMissions& result) { - auto* missionsTable = CDClientManager::Instance()->GetTable("Missions"); + auto* missionsTable = CDClientManager::Instance()->GetTable("Missions"); - const auto missions = missionsTable->Query([=](const CDMissions& entry) { - return entry.id == static_cast(missionId); - }); + const auto missions = missionsTable->Query([=](const CDMissions& entry) { + return entry.id == static_cast(missionId); + }); - if (missions.empty()) { - return false; - } + if (missions.empty()) { + return false; + } - result = missions[0]; + result = missions[0]; - return true; + return true; } #define MISSION_NEW_METHOD bool MissionComponent::LookForAchievements(MissionTaskType type, int32_t value, bool progress, LWOOBJID associate, const std::string& targets, int32_t count) { #ifdef MISSION_NEW_METHOD - // Query for achievments, using the cache - const auto& result = QueryAchievements(type, value, targets); + // Query for achievments, using the cache + const auto& result = QueryAchievements(type, value, targets); - bool any = false; + bool any = false; - for (const uint32_t missionID : result) { - // Check if we already have this achievement - if (GetMission(missionID) != nullptr) { - continue; - } + for (const uint32_t missionID : result) { + // Check if we already have this achievement + if (GetMission(missionID) != nullptr) { + continue; + } - // Check if we can accept this achievement - if (!MissionPrerequisites::CanAccept(missionID, m_Missions)) { - continue; - } + // Check if we can accept this achievement + if (!MissionPrerequisites::CanAccept(missionID, m_Missions)) { + continue; + } - // Instantiate new mission and accept it - auto* instance = new Mission(this, missionID); + // Instantiate new mission and accept it + auto* instance = new Mission(this, missionID); - m_Missions.insert_or_assign(missionID, instance); + m_Missions.insert_or_assign(missionID, instance); - instance->Accept(); + instance->Accept(); - any = true; + any = true; - if (progress) { - // Progress mission to bring it up to speed - instance->Progress(type, value, associate, targets, count); - } - } + if (progress) { + // Progress mission to bring it up to speed + instance->Progress(type, value, associate, targets, count); + } + } - return any; + return any; #else - auto* missionTasksTable = CDClientManager::Instance()->GetTable("MissionTasks"); - auto* missionsTable = CDClientManager::Instance()->GetTable("Missions"); + auto* missionTasksTable = CDClientManager::Instance()->GetTable("MissionTasks"); + auto* missionsTable = CDClientManager::Instance()->GetTable("Missions"); - auto tasks = missionTasksTable->Query([=](const CDMissionTasks& entry) { - return entry.taskType == static_cast(type); - }); + auto tasks = missionTasksTable->Query([=](const CDMissionTasks& entry) { + return entry.taskType == static_cast(type); + }); - auto any = false; + auto any = false; - for (const auto& task : tasks) { - if (GetMission(task.id) != nullptr) { - continue; - } + for (const auto& task : tasks) { + if (GetMission(task.id) != nullptr) { + continue; + } - const auto missionEntries = missionsTable->Query([=](const CDMissions& entry) { - return entry.id == static_cast(task.id) && !entry.isMission; - }); + const auto missionEntries = missionsTable->Query([=](const CDMissions& entry) { + return entry.id == static_cast(task.id) && !entry.isMission; + }); - if (missionEntries.empty()) { - continue; - } + if (missionEntries.empty()) { + continue; + } - const auto mission = missionEntries[0]; + const auto mission = missionEntries[0]; - if (mission.isMission || !MissionPrerequisites::CanAccept(mission.id, m_Missions)) { - continue; - } + if (mission.isMission || !MissionPrerequisites::CanAccept(mission.id, m_Missions)) { + continue; + } - if (task.target != value && task.targetGroup != targets) { - auto stream = std::istringstream(task.targetGroup); - std::string token; + if (task.target != value && task.targetGroup != targets) { + auto stream = std::istringstream(task.targetGroup); + std::string token; - auto found = false; + auto found = false; - while (std::getline(stream, token, ',')) { - try { - const auto target = std::stoul(token); + while (std::getline(stream, token, ',')) { + try { + const auto target = std::stoul(token); - found = target == value; + found = target == value; - if (found) { - break; - } - } - catch (std::invalid_argument& exception) { - Game::logger->Log("MissionComponent", "Failed to parse target (%s): (%s)!", token.c_str(), exception.what()); - } - } + if (found) { + break; + } + } catch (std::invalid_argument& exception) { + Game::logger->Log("MissionComponent", "Failed to parse target (%s): (%s)!", token.c_str(), exception.what()); + } + } - if (!found) { - continue; - } - } + if (!found) { + continue; + } + } - auto* instance = new Mission(this, mission.id); + auto* instance = new Mission(this, mission.id); - m_Missions.insert_or_assign(mission.id, instance); + m_Missions.insert_or_assign(mission.id, instance); - instance->Accept(); + instance->Accept(); - any = true; + any = true; - if (progress) { - instance->Progress(type, value, associate, targets, count); - } - } + if (progress) { + instance->Progress(type, value, associate, targets, count); + } + } - return any; + return any; #endif } const std::vector& MissionComponent::QueryAchievements(MissionTaskType type, int32_t value, const std::string targets) { - // Create a hash which represent this query for achievements - size_t hash = 0; - GeneralUtils::hash_combine(hash, type); - GeneralUtils::hash_combine(hash, value); - GeneralUtils::hash_combine(hash, targets); + // Create a hash which represent this query for achievements + size_t hash = 0; + GeneralUtils::hash_combine(hash, type); + GeneralUtils::hash_combine(hash, value); + GeneralUtils::hash_combine(hash, targets); - const std::unordered_map>::iterator& iter = m_AchievementCache.find(hash); + const std::unordered_map>::iterator& iter = m_AchievementCache.find(hash); - // Check if this query is cached - if (iter != m_AchievementCache.end()) { - return iter->second; - } + // Check if this query is cached + if (iter != m_AchievementCache.end()) { + return iter->second; + } - // Find relevent tables - auto* missionTasksTable = CDClientManager::Instance()->GetTable("MissionTasks"); - auto* missionsTable = CDClientManager::Instance()->GetTable("Missions"); + // Find relevent tables + auto* missionTasksTable = CDClientManager::Instance()->GetTable("MissionTasks"); + auto* missionsTable = CDClientManager::Instance()->GetTable("Missions"); - std::vector result; + std::vector result; - // Loop through all mission tasks, might cache this task check later - for (const auto& task : missionTasksTable->GetEntries()) { - if (task.taskType != static_cast(type)) { - continue; - } + // Loop through all mission tasks, might cache this task check later + for (const auto& task : missionTasksTable->GetEntries()) { + if (task.taskType != static_cast(type)) { + continue; + } - // Seek the assosicated mission - auto foundMission = false; + // Seek the assosicated mission + auto foundMission = false; - const auto& mission = missionsTable->GetByMissionID(task.id, foundMission); + const auto& mission = missionsTable->GetByMissionID(task.id, foundMission); - if (!foundMission || mission.isMission) { - continue; - } + if (!foundMission || mission.isMission) { + continue; + } - // Compare the easy values - if (task.target == value || task.targetGroup == targets) { - result.push_back(mission.id); + // Compare the easy values + if (task.target == value || task.targetGroup == targets) { + result.push_back(mission.id); - continue; - } + continue; + } - // Compare the target group, array separated by ',' - auto stream = std::istringstream(task.targetGroup); - std::string token; + // Compare the target group, array separated by ',' + auto stream = std::istringstream(task.targetGroup); + std::string token; - while (std::getline(stream, token, ',')) { - try { - if (std::stoi(token) == value) { - result.push_back(mission.id); + while (std::getline(stream, token, ',')) { + try { + if (std::stoi(token) == value) { + result.push_back(mission.id); - continue; - } - } - catch (std::invalid_argument& exception) { - // Ignored - } - } - } + continue; + } + } catch (std::invalid_argument& exception) { + // Ignored + } + } + } - // Insert into cache - m_AchievementCache.insert_or_assign(hash, result); + // Insert into cache + m_AchievementCache.insert_or_assign(hash, result); - return m_AchievementCache.find(hash)->second; + return m_AchievementCache.find(hash)->second; } bool MissionComponent::RequiresItem(const LOT lot) { - auto query = CDClientDatabase::CreatePreppedStmt( - "SELECT type FROM Objects WHERE id = ?;"); - query.bind(1, (int) lot); + auto query = CDClientDatabase::CreatePreppedStmt( + "SELECT type FROM Objects WHERE id = ?;"); + query.bind(1, (int)lot); - auto result = query.execQuery(); + auto result = query.execQuery(); - if (result.eof()) { - return false; - } + if (result.eof()) { + return false; + } - if (!result.fieldIsNull(0)) { - const auto type = std::string(result.getStringField(0)); + if (!result.fieldIsNull(0)) { + const auto type = std::string(result.getStringField(0)); - result.finalize(); + result.finalize(); - if (type == "Powerup") { - return true; - } - } + if (type == "Powerup") { + return true; + } + } - result.finalize(); + result.finalize(); - for (const auto& pair : m_Missions) { - auto* mission = pair.second; + for (const auto& pair : m_Missions) { + auto* mission = pair.second; - if (mission->IsComplete()) { - continue; - } + if (mission->IsComplete()) { + continue; + } - for (auto* task : mission->GetTasks()) { - if (task->IsComplete() || task->GetType() != MissionTaskType::MISSION_TASK_TYPE_ITEM_COLLECTION) { - continue; - } + for (auto* task : mission->GetTasks()) { + if (task->IsComplete() || task->GetType() != MissionTaskType::MISSION_TASK_TYPE_ITEM_COLLECTION) { + continue; + } - if (!task->InAllTargets(lot)) { - continue; - } + if (!task->InAllTargets(lot)) { + continue; + } - return true; - } - } + return true; + } + } - const auto required = LookForAchievements(MissionTaskType::MISSION_TASK_TYPE_ITEM_COLLECTION, lot, false); + const auto required = LookForAchievements(MissionTaskType::MISSION_TASK_TYPE_ITEM_COLLECTION, lot, false); - return required; + return required; } void MissionComponent::LoadFromXml(tinyxml2::XMLDocument* doc) { - if (doc == nullptr) return; + if (doc == nullptr) return; - auto* mis = doc->FirstChildElement("obj")->FirstChildElement("mis"); + auto* mis = doc->FirstChildElement("obj")->FirstChildElement("mis"); - if (mis == nullptr) return; + if (mis == nullptr) return; - auto* cur = mis->FirstChildElement("cur"); - auto* done = mis->FirstChildElement("done"); + auto* cur = mis->FirstChildElement("cur"); + auto* done = mis->FirstChildElement("done"); - auto* doneM = done->FirstChildElement(); + auto* doneM = done->FirstChildElement(); - while (doneM) { - int missionId; + while (doneM) { + int missionId; - doneM->QueryAttribute("id", &missionId); + doneM->QueryAttribute("id", &missionId); - auto* mission = new Mission(this, missionId); + auto* mission = new Mission(this, missionId); - mission->LoadFromXml(doneM); + mission->LoadFromXml(doneM); - doneM = doneM->NextSiblingElement(); + doneM = doneM->NextSiblingElement(); - m_Missions.insert_or_assign(missionId, mission); - } + m_Missions.insert_or_assign(missionId, mission); + } - auto* currentM = cur->FirstChildElement(); + auto* currentM = cur->FirstChildElement(); - while (currentM) { - int missionId; + while (currentM) { + int missionId; - currentM->QueryAttribute("id", &missionId); + currentM->QueryAttribute("id", &missionId); - auto* mission = new Mission(this, missionId); + auto* mission = new Mission(this, missionId); - mission->LoadFromXml(currentM); + mission->LoadFromXml(currentM); - currentM = currentM->NextSiblingElement(); + currentM = currentM->NextSiblingElement(); - m_Missions.insert_or_assign(missionId, mission); - } + m_Missions.insert_or_assign(missionId, mission); + } } void MissionComponent::UpdateXml(tinyxml2::XMLDocument* doc) { - if (doc == nullptr) return; + if (doc == nullptr) return; - auto shouldInsertMis = false; + auto shouldInsertMis = false; - auto* obj = doc->FirstChildElement("obj"); + auto* obj = doc->FirstChildElement("obj"); - auto* mis = obj->FirstChildElement("mis"); + auto* mis = obj->FirstChildElement("mis"); - if (mis == nullptr) { - mis = doc->NewElement("mis"); + if (mis == nullptr) { + mis = doc->NewElement("mis"); - shouldInsertMis = true; - } + shouldInsertMis = true; + } - mis->DeleteChildren(); + mis->DeleteChildren(); - auto* done = doc->NewElement("done"); - auto* cur = doc->NewElement("cur"); + auto* done = doc->NewElement("done"); + auto* cur = doc->NewElement("cur"); - for (const auto& pair : m_Missions) { - auto* mission = pair.second; + for (const auto& pair : m_Missions) { + auto* mission = pair.second; - if (mission) { - const auto complete = mission->IsComplete(); + if (mission) { + const auto complete = mission->IsComplete(); - if (complete) { - auto* m = doc->NewElement("m"); + if (complete) { + auto* m = doc->NewElement("m"); - mission->UpdateXml(m); + mission->UpdateXml(m); - done->LinkEndChild(m); + done->LinkEndChild(m); - continue; - } + continue; + } - auto* m = doc->NewElement("m"); + auto* m = doc->NewElement("m"); - mission->UpdateXml(m); + mission->UpdateXml(m); - cur->LinkEndChild(m); - } - } + cur->LinkEndChild(m); + } + } - mis->InsertFirstChild(done); - mis->InsertEndChild(cur); + mis->InsertFirstChild(done); + mis->InsertEndChild(cur); - if (shouldInsertMis) { - obj->LinkEndChild(mis); - } + if (shouldInsertMis) { + obj->LinkEndChild(mis); + } } -void MissionComponent::AddCollectible(int32_t collectibleID) -{ - // Check if this collectible is already in the list - if (HasCollectible(collectibleID)) { - return; - } +void MissionComponent::AddCollectible(int32_t collectibleID) { + // Check if this collectible is already in the list + if (HasCollectible(collectibleID)) { + return; + } - m_Collectibles.push_back(collectibleID); + m_Collectibles.push_back(collectibleID); } -bool MissionComponent::HasCollectible(int32_t collectibleID) -{ - return std::find(m_Collectibles.begin(), m_Collectibles.end(), collectibleID) != m_Collectibles.end(); +bool MissionComponent::HasCollectible(int32_t collectibleID) { + return std::find(m_Collectibles.begin(), m_Collectibles.end(), collectibleID) != m_Collectibles.end(); } -bool MissionComponent::HasMission(uint32_t missionId) -{ - return GetMission(missionId) != nullptr; -} \ No newline at end of file +bool MissionComponent::HasMission(uint32_t missionId) { + return GetMission(missionId) != nullptr; +} diff --git a/dGame/dComponents/MissionComponent.h b/dGame/dComponents/MissionComponent.h index 13a812d2..b4e53001 100644 --- a/dGame/dComponents/MissionComponent.h +++ b/dGame/dComponents/MissionComponent.h @@ -17,182 +17,182 @@ #include "CDMissionsTable.h" #include "Component.h" -/** - * The mission inventory of an entity. Tracks mission state for each mission that can be accepted and allows for - * progression of each of the mission task types (see MissionTaskType). - */ + /** + * The mission inventory of an entity. Tracks mission state for each mission that can be accepted and allows for + * progression of each of the mission task types (see MissionTaskType). + */ class MissionComponent : public Component { public: - static const uint32_t ComponentType = COMPONENT_TYPE_MISSION; + static const uint32_t ComponentType = COMPONENT_TYPE_MISSION; explicit MissionComponent(Entity* parent); - ~MissionComponent() override; - void Serialize(RakNet::BitStream* outBitStream, bool bIsInitialUpdate, unsigned int& flags); - void LoadFromXml(tinyxml2::XMLDocument* doc) override; - void UpdateXml(tinyxml2::XMLDocument* doc) override; + ~MissionComponent() override; + void Serialize(RakNet::BitStream* outBitStream, bool bIsInitialUpdate, unsigned int& flags); + void LoadFromXml(tinyxml2::XMLDocument* doc) override; + void UpdateXml(tinyxml2::XMLDocument* doc) override; - /** - * Returns all the missions for this entity, mapped by mission ID - * @return the missions for this entity, mapped by mission ID - */ - const std::unordered_map& GetMissions() const; + /** + * Returns all the missions for this entity, mapped by mission ID + * @return the missions for this entity, mapped by mission ID + */ + const std::unordered_map& GetMissions() const; - /** - * Returns the mission for the given mission ID, if it exists - * @param missionId the id of the mission to get - * @return the mission for the given mission ID - */ - Mission* GetMission(uint32_t missionId) const; + /** + * Returns the mission for the given mission ID, if it exists + * @param missionId the id of the mission to get + * @return the mission for the given mission ID + */ + Mission* GetMission(uint32_t missionId) const; - /** - * Returns the current state of the entities progression for the mission of the specified ID - * @param missionId the ID of the mission to get the mission state for - * @return the mission state of the mission specified by the ID - */ - MissionState GetMissionState(uint32_t missionId) const; + /** + * Returns the current state of the entities progression for the mission of the specified ID + * @param missionId the ID of the mission to get the mission state for + * @return the mission state of the mission specified by the ID + */ + MissionState GetMissionState(uint32_t missionId) const; - /** - * Checks if the entity has all the requirements for accepting the mission specified by the ID. - * @param missionId the mission ID to check for if the character may accept it - * @return whether this entity can accept the mission represented by the given mission ID - */ - bool CanAccept(uint32_t missionId) const; + /** + * Checks if the entity has all the requirements for accepting the mission specified by the ID. + * @param missionId the mission ID to check for if the character may accept it + * @return whether this entity can accept the mission represented by the given mission ID + */ + bool CanAccept(uint32_t missionId) const; - /** - * Accepts the mission specified by the ID, if the entity may accept it. Also stores it in the mission inventory. - * @param missionId the ID of the mission to accept - * @param skipChecks skips the checks for the mission prerequisites - */ - void AcceptMission(uint32_t missionId, bool skipChecks = false); + /** + * Accepts the mission specified by the ID, if the entity may accept it. Also stores it in the mission inventory. + * @param missionId the ID of the mission to accept + * @param skipChecks skips the checks for the mission prerequisites + */ + void AcceptMission(uint32_t missionId, bool skipChecks = false); - /** - * Completes the mission specified by the given ID, if the entity has fulfilled all progress requirements. - * @param missionId the ID of the mission to complete - * @param skipChecks skips the checks for having completed all of the mission tasks - * @param yieldRewards whether to yield mission rewards, currently unused - */ - void CompleteMission(uint32_t missionId, bool skipChecks = false, bool yieldRewards = true); + /** + * Completes the mission specified by the given ID, if the entity has fulfilled all progress requirements. + * @param missionId the ID of the mission to complete + * @param skipChecks skips the checks for having completed all of the mission tasks + * @param yieldRewards whether to yield mission rewards, currently unused + */ + void CompleteMission(uint32_t missionId, bool skipChecks = false, bool yieldRewards = true); - /** - * Removes the mission from the entities' mission chain. Not used for normal gameplay but useful for debugging. - * @param missionId the ID of the mission to remove - */ - void RemoveMission(uint32_t missionId); + /** + * Removes the mission from the entities' mission chain. Not used for normal gameplay but useful for debugging. + * @param missionId the ID of the mission to remove + */ + void RemoveMission(uint32_t missionId); - /** - * Attempts to progress mission tasks for a given type using parameters to progress. Note that this function is - * very abstract and different mission tasks require different combinations of parameters. This also progresses - * achievements, which are basically just missions with the isMission flag set to false. - * @param type the type of the mission task to try and progress with - * @param value the value to progress with, could be a LOT for item collection for example - * @param associate an associated entity for the progression, might be an activity host for example - * @param targets optionally multiple target values that could exist for the mission that we wish to progress - * @param count the number to progress by, for example the number of items - * @param ignoreAchievements do not progress achievements - */ - void Progress(MissionTaskType type, int32_t value, LWOOBJID associate = 0, const std::string& targets = "", int32_t count = 1, bool ignoreAchievements = false); + /** + * Attempts to progress mission tasks for a given type using parameters to progress. Note that this function is + * very abstract and different mission tasks require different combinations of parameters. This also progresses + * achievements, which are basically just missions with the isMission flag set to false. + * @param type the type of the mission task to try and progress with + * @param value the value to progress with, could be a LOT for item collection for example + * @param associate an associated entity for the progression, might be an activity host for example + * @param targets optionally multiple target values that could exist for the mission that we wish to progress + * @param count the number to progress by, for example the number of items + * @param ignoreAchievements do not progress achievements + */ + void Progress(MissionTaskType type, int32_t value, LWOOBJID associate = 0, const std::string& targets = "", int32_t count = 1, bool ignoreAchievements = false); - /** - * Forces progression for a mission and task, ignoring checks - * @param missionId the mission ID to try and progress - * @param taskId the task ID of the task belonging to the mission trying to progress - * @param value the value to progress with - * @param acceptMission accept the mission if it was not already accepted - */ - void ForceProgress(uint32_t missionId, uint32_t taskId, int32_t value, bool acceptMission = true); + /** + * Forces progression for a mission and task, ignoring checks + * @param missionId the mission ID to try and progress + * @param taskId the task ID of the task belonging to the mission trying to progress + * @param value the value to progress with + * @param acceptMission accept the mission if it was not already accepted + */ + void ForceProgress(uint32_t missionId, uint32_t taskId, int32_t value, bool acceptMission = true); - /** - * Forces progress for all tasks of a certain type that belong to the same mission - * @param missionId the mission to progress - * @param taskType the task tyoe to progress - * @param value the value to progress with - * @param acceptMission accept the mission if it wasn't already - */ - void ForceProgressTaskType(uint32_t missionId, uint32_t taskType, int32_t value, bool acceptMission = true); + /** + * Forces progress for all tasks of a certain type that belong to the same mission + * @param missionId the mission to progress + * @param taskType the task tyoe to progress + * @param value the value to progress with + * @param acceptMission accept the mission if it wasn't already + */ + void ForceProgressTaskType(uint32_t missionId, uint32_t taskType, int32_t value, bool acceptMission = true); - /** - * Force progresses by checking the value and progressing by 1 - * @param missionId the mission to progress - * @param taskType the task to progress for - * @param value the value to check the mission values before progressing - * @param acceptMission accept the mission if it wasn't already - */ - void ForceProgressValue(uint32_t missionId, uint32_t taskType, int32_t value, bool acceptMission = true); + /** + * Force progresses by checking the value and progressing by 1 + * @param missionId the mission to progress + * @param taskType the task to progress for + * @param value the value to check the mission values before progressing + * @param acceptMission accept the mission if it wasn't already + */ + void ForceProgressValue(uint32_t missionId, uint32_t taskType, int32_t value, bool acceptMission = true); - /** - * Returns client database mission information for a mission - * @param missionId the ID of the mission to get the info for - * @param result the result to store the information in - * @return true if the information was succesfully retrieved, false otherwise - */ - bool GetMissionInfo(uint32_t missionId, CDMissions& result); + /** + * Returns client database mission information for a mission + * @param missionId the ID of the mission to get the info for + * @param result the result to store the information in + * @return true if the information was succesfully retrieved, false otherwise + */ + bool GetMissionInfo(uint32_t missionId, CDMissions& result); - /** - * Checks if there's any achievements we might be able to accept for the given parameters - * @param type the task type for tasks in the achievement that we wish to progress - * @param value the value to progress by - * @param progress if we can accept the mission, this will apply the progression - * @param associate optional associate related to mission progression - * @param targets optional multiple targets related to mission progression - * @param count the number of values to progress by (differs by task type) - * @return true if a achievement was accepted, false otherwise - */ + /** + * Checks if there's any achievements we might be able to accept for the given parameters + * @param type the task type for tasks in the achievement that we wish to progress + * @param value the value to progress by + * @param progress if we can accept the mission, this will apply the progression + * @param associate optional associate related to mission progression + * @param targets optional multiple targets related to mission progression + * @param count the number of values to progress by (differs by task type) + * @return true if a achievement was accepted, false otherwise + */ bool LookForAchievements(MissionTaskType type, int32_t value, bool progress = true, LWOOBJID associate = LWOOBJID_EMPTY, const std::string& targets = "", int32_t count = 1); - /** - * Checks if there's a mission active that requires the collection of the specified LOT - * @param lot the LOT to check for - * @return if there's a mission active that requires the collection of the specified LOT - */ - bool RequiresItem(LOT lot); + /** + * Checks if there's a mission active that requires the collection of the specified LOT + * @param lot the LOT to check for + * @return if there's a mission active that requires the collection of the specified LOT + */ + bool RequiresItem(LOT lot); - /** - * Collects a collectable for the entity, unrendering it for the entity - * @param collectibleID the ID of the collectable to add - */ - void AddCollectible(int32_t collectibleID); + /** + * Collects a collectable for the entity, unrendering it for the entity + * @param collectibleID the ID of the collectable to add + */ + void AddCollectible(int32_t collectibleID); - /** - * Checks if the entity already has a collectible of the specified ID - * @param collectibleID the ID of the collectible to check - * @return if the entity already has a collectible of the specified ID - */ - bool HasCollectible(int32_t collectibleID); + /** + * Checks if the entity already has a collectible of the specified ID + * @param collectibleID the ID of the collectible to check + * @return if the entity already has a collectible of the specified ID + */ + bool HasCollectible(int32_t collectibleID); + + /** + * Checks if the entity has a certain mission in its inventory + * @param missionId the ID of the mission to check + * @return if the entity has a certain mission in its inventory + */ + bool HasMission(uint32_t missionId); - /** - * Checks if the entity has a certain mission in its inventory - * @param missionId the ID of the mission to check - * @return if the entity has a certain mission in its inventory - */ - bool HasMission(uint32_t missionId); - private: - /** - * All the missions owned by this entity, mapped by mission ID - */ - std::unordered_map m_Missions; + /** + * All the missions owned by this entity, mapped by mission ID + */ + std::unordered_map m_Missions; - /** - * All the collectibles currently collected by the entity - */ - std::vector m_Collectibles; + /** + * All the collectibles currently collected by the entity + */ + std::vector m_Collectibles; - /** - * For the given parameters, finds the mission IDs of the achievements that may be unlcoked - * @param type the mission task type to try and progress - * @param value the value to try and progress with - * @param targets optional targets to progress with - * @return list of mission IDs (achievements) that can be progressed for the given parameters - */ - static const std::vector& QueryAchievements(MissionTaskType type, int32_t value, const std::string targets); + /** + * For the given parameters, finds the mission IDs of the achievements that may be unlcoked + * @param type the mission task type to try and progress + * @param value the value to try and progress with + * @param targets optional targets to progress with + * @return list of mission IDs (achievements) that can be progressed for the given parameters + */ + static const std::vector& QueryAchievements(MissionTaskType type, int32_t value, const std::string targets); - /** - * As achievements can be hard to query, we here store a list of all the mission IDs that can be unlocked for a - * combination of tasks and values, so that they can be easily re-queried later - */ - static std::unordered_map> m_AchievementCache; + /** + * As achievements can be hard to query, we here store a list of all the mission IDs that can be unlocked for a + * combination of tasks and values, so that they can be easily re-queried later + */ + static std::unordered_map> m_AchievementCache; }; #endif // MISSIONCOMPONENT_H diff --git a/dGame/dComponents/MissionOfferComponent.cpp b/dGame/dComponents/MissionOfferComponent.cpp index 6e44d2e3..2f2ed0f0 100644 --- a/dGame/dComponents/MissionOfferComponent.cpp +++ b/dGame/dComponents/MissionOfferComponent.cpp @@ -15,224 +15,193 @@ #include "Game.h" #include "MissionPrerequisites.h" -OfferedMission::OfferedMission(const uint32_t missionId, const bool offersMission, const bool acceptsMission) -{ - this->missionId = missionId; - this->offersMission = offersMission; - this->acceptsMission = acceptsMission; +OfferedMission::OfferedMission(const uint32_t missionId, const bool offersMission, const bool acceptsMission) { + this->missionId = missionId; + this->offersMission = offersMission; + this->acceptsMission = acceptsMission; } -uint32_t OfferedMission::GetMissionId() const -{ - return this->missionId; +uint32_t OfferedMission::GetMissionId() const { + return this->missionId; } -bool OfferedMission::GetOfferMission() const -{ - return this->offersMission; +bool OfferedMission::GetOfferMission() const { + return this->offersMission; } -bool OfferedMission::GetAcceptMission() const -{ - return this->acceptsMission; +bool OfferedMission::GetAcceptMission() const { + return this->acceptsMission; } //------------------------ MissionOfferComponent below ------------------------ MissionOfferComponent::MissionOfferComponent(Entity* parent, const LOT parentLot) : Component(parent) { - auto* compRegistryTable = CDClientManager::Instance()->GetTable("ComponentsRegistry"); + auto* compRegistryTable = CDClientManager::Instance()->GetTable("ComponentsRegistry"); - auto value = compRegistryTable->GetByIDAndType(parentLot, COMPONENT_TYPE_MISSION_OFFER, -1); + auto value = compRegistryTable->GetByIDAndType(parentLot, COMPONENT_TYPE_MISSION_OFFER, -1); - if (value != -1) { - const uint32_t componentId = value; + if (value != -1) { + const uint32_t componentId = value; - // Now lookup the missions in the MissionNPCComponent table - auto* missionNpcComponentTable = CDClientManager::Instance()->GetTable("MissionNPCComponent"); + // Now lookup the missions in the MissionNPCComponent table + auto* missionNpcComponentTable = CDClientManager::Instance()->GetTable("MissionNPCComponent"); - auto missions = missionNpcComponentTable->Query([=](const CDMissionNPCComponent& entry) - { - return entry.id == static_cast(componentId); - }); + auto missions = missionNpcComponentTable->Query([=](const CDMissionNPCComponent& entry) { + return entry.id == static_cast(componentId); + }); - for (auto& mission : missions) - { - auto* offeredMission = new OfferedMission(mission.missionID, mission.offersMission, mission.acceptsMission); - this->offeredMissions.push_back(offeredMission); - } - } + for (auto& mission : missions) { + auto* offeredMission = new OfferedMission(mission.missionID, mission.offersMission, mission.acceptsMission); + this->offeredMissions.push_back(offeredMission); + } + } } -MissionOfferComponent::~MissionOfferComponent() -{ - for (auto* mission : this->offeredMissions) { - if (mission) { - delete mission; - mission = nullptr; - } - } +MissionOfferComponent::~MissionOfferComponent() { + for (auto* mission : this->offeredMissions) { + if (mission) { + delete mission; + mission = nullptr; + } + } - offeredMissions.clear(); + offeredMissions.clear(); } -void MissionOfferComponent::OnUse(Entity* originator) -{ - OfferMissions(originator); +void MissionOfferComponent::OnUse(Entity* originator) { + OfferMissions(originator); } -void MissionOfferComponent::OfferMissions(Entity* entity, const uint32_t specifiedMissionId) -{ - // First, get the entity's MissionComponent. If there is not one, then we cannot offer missions to this entity. - auto* missionComponent = static_cast(entity->GetComponent(COMPONENT_TYPE_MISSION)); +void MissionOfferComponent::OfferMissions(Entity* entity, const uint32_t specifiedMissionId) { + // First, get the entity's MissionComponent. If there is not one, then we cannot offer missions to this entity. + auto* missionComponent = static_cast(entity->GetComponent(COMPONENT_TYPE_MISSION)); - if (!missionComponent) { - Game::logger->Log("MissionOfferComponent", "Unable to get mission component for Entity %llu", entity->GetObjectID()); - return; - } + if (!missionComponent) { + Game::logger->Log("MissionOfferComponent", "Unable to get mission component for Entity %llu", entity->GetObjectID()); + return; + } - std::vector offered {}; + std::vector offered{}; - CDMissions info {}; + CDMissions info{}; - if (specifiedMissionId > 0 && !Mission::IsValidMission(specifiedMissionId, info)) - { - return; - } + if (specifiedMissionId > 0 && !Mission::IsValidMission(specifiedMissionId, info)) { + return; + } - for (auto* offeredMission : this->offeredMissions) - { - if (specifiedMissionId > 0) - { - if (offeredMission->GetMissionId() != specifiedMissionId && !info.isRandom) - { - continue; - } - } + for (auto* offeredMission : this->offeredMissions) { + if (specifiedMissionId > 0) { + if (offeredMission->GetMissionId() != specifiedMissionId && !info.isRandom) { + continue; + } + } - // First, check if we already have the mission - const auto missionId = offeredMission->GetMissionId(); + // First, check if we already have the mission + const auto missionId = offeredMission->GetMissionId(); - auto* mission = missionComponent->GetMission(missionId); + auto* mission = missionComponent->GetMission(missionId); - if (mission != nullptr) - { - if (specifiedMissionId <= 0) - { - // Handles the odd case where the offer object should not display the mission again - if (!mission->IsComplete() && mission->GetClientInfo().offer_objectID == m_Parent->GetLOT() && mission->GetClientInfo().target_objectID != m_Parent->GetLOT() && mission->IsFetchMission()) - { - continue; - } - } + if (mission != nullptr) { + if (specifiedMissionId <= 0) { + // Handles the odd case where the offer object should not display the mission again + if (!mission->IsComplete() && mission->GetClientInfo().offer_objectID == m_Parent->GetLOT() && mission->GetClientInfo().target_objectID != m_Parent->GetLOT() && mission->IsFetchMission()) { + continue; + } + } - // We have the mission, if it is not complete, offer it - if (mission->IsActive() || mission->IsReadyToComplete()) - { - GameMessages::SendOfferMission(entity->GetObjectID(), entity->GetSystemAddress(), missionId, m_Parent->GetObjectID()); + // We have the mission, if it is not complete, offer it + if (mission->IsActive() || mission->IsReadyToComplete()) { + GameMessages::SendOfferMission(entity->GetObjectID(), entity->GetSystemAddress(), missionId, m_Parent->GetObjectID()); - offered.push_back(missionId); + offered.push_back(missionId); - continue; - } - } + continue; + } + } - const auto canAccept = MissionPrerequisites::CanAccept(missionId, missionComponent->GetMissions()); + const auto canAccept = MissionPrerequisites::CanAccept(missionId, missionComponent->GetMissions()); - // Mission has not yet been accepted - check the prereqs - if (!canAccept) - continue; + // Mission has not yet been accepted - check the prereqs + if (!canAccept) + continue; - if (!Mission::IsValidMission(missionId, info)) - { - continue; - } + if (!Mission::IsValidMission(missionId, info)) { + continue; + } - const auto& randomPool = info.randomPool; - const auto isRandom = info.isRandom; + const auto& randomPool = info.randomPool; + const auto isRandom = info.isRandom; - if (isRandom && randomPool.empty()) // This means the mission is part of a random pool of missions. - { - continue; - } + if (isRandom && randomPool.empty()) // This means the mission is part of a random pool of missions. + { + continue; + } - if (isRandom && !randomPool.empty()) - { - std::istringstream stream(randomPool); - std::string token; + if (isRandom && !randomPool.empty()) { + std::istringstream stream(randomPool); + std::string token; - std::vector randomMissionPool; + std::vector randomMissionPool; - while (std::getline(stream, token, ',')) - { - try - { - const auto value = std::stoul(token); + while (std::getline(stream, token, ',')) { + try { + const auto value = std::stoul(token); - randomMissionPool.push_back(value); - } - catch (std::invalid_argument& exception) - { - Game::logger->Log("MissionOfferComponent", "Failed to parse value (%s): (%s)!", token.c_str(), exception.what()); - } - } + randomMissionPool.push_back(value); + } catch (std::invalid_argument& exception) { + Game::logger->Log("MissionOfferComponent", "Failed to parse value (%s): (%s)!", token.c_str(), exception.what()); + } + } - if (specifiedMissionId > 0) - { - const auto& iter = std::find(randomMissionPool.begin(), randomMissionPool.end(), specifiedMissionId); + if (specifiedMissionId > 0) { + const auto& iter = std::find(randomMissionPool.begin(), randomMissionPool.end(), specifiedMissionId); - if (iter != randomMissionPool.end() && MissionPrerequisites::CanAccept(specifiedMissionId, missionComponent->GetMissions())) - { - GameMessages::SendOfferMission(entity->GetObjectID(), entity->GetSystemAddress(), specifiedMissionId, m_Parent->GetObjectID()); + if (iter != randomMissionPool.end() && MissionPrerequisites::CanAccept(specifiedMissionId, missionComponent->GetMissions())) { + GameMessages::SendOfferMission(entity->GetObjectID(), entity->GetSystemAddress(), specifiedMissionId, m_Parent->GetObjectID()); - return; - } - } + return; + } + } - std::vector canAcceptPool; + std::vector canAcceptPool; - for (const auto sample : randomMissionPool) - { - const auto state = missionComponent->GetMissionState(sample); + for (const auto sample : randomMissionPool) { + const auto state = missionComponent->GetMissionState(sample); - if (state == MissionState::MISSION_STATE_ACTIVE || - state == MissionState::MISSION_STATE_COMPLETE_ACTIVE || - state == MissionState::MISSION_STATE_READY_TO_COMPLETE || - state == MissionState::MISSION_STATE_COMPLETE_READY_TO_COMPLETE || - sample == specifiedMissionId) - { - mission = missionComponent->GetMission(sample); + if (state == MissionState::MISSION_STATE_ACTIVE || + state == MissionState::MISSION_STATE_COMPLETE_ACTIVE || + state == MissionState::MISSION_STATE_READY_TO_COMPLETE || + state == MissionState::MISSION_STATE_COMPLETE_READY_TO_COMPLETE || + sample == specifiedMissionId) { + mission = missionComponent->GetMission(sample); - if (mission == nullptr || mission->IsAchievement()) - { - continue; - } + if (mission == nullptr || mission->IsAchievement()) { + continue; + } - GameMessages::SendOfferMission(entity->GetObjectID(), entity->GetSystemAddress(), sample, m_Parent->GetObjectID()); + GameMessages::SendOfferMission(entity->GetObjectID(), entity->GetSystemAddress(), sample, m_Parent->GetObjectID()); - canAcceptPool.clear(); + canAcceptPool.clear(); - break; - } + break; + } - if (std::find(offered.begin(), offered.end(), sample) == offered.end() && MissionPrerequisites::CanAccept(sample, missionComponent->GetMissions())) - { - canAcceptPool.push_back(sample); - } - } + if (std::find(offered.begin(), offered.end(), sample) == offered.end() && MissionPrerequisites::CanAccept(sample, missionComponent->GetMissions())) { + canAcceptPool.push_back(sample); + } + } - // If the mission is already active or we already completed one of them today - if (canAcceptPool.empty()) - continue; + // If the mission is already active or we already completed one of them today + if (canAcceptPool.empty()) + continue; - const auto selected = canAcceptPool[GeneralUtils::GenerateRandomNumber(0, canAcceptPool.size() - 1)]; + const auto selected = canAcceptPool[GeneralUtils::GenerateRandomNumber(0, canAcceptPool.size() - 1)]; - GameMessages::SendOfferMission(entity->GetObjectID(), entity->GetSystemAddress(), selected, m_Parent->GetObjectID()); - } - else if (std::find(offered.begin(), offered.end(), missionId) == offered.end() && offeredMission->GetOfferMission()) - { - GameMessages::SendOfferMission(entity->GetObjectID(), entity->GetSystemAddress(), missionId, m_Parent->GetObjectID()); - } - } + GameMessages::SendOfferMission(entity->GetObjectID(), entity->GetSystemAddress(), selected, m_Parent->GetObjectID()); + } else if (std::find(offered.begin(), offered.end(), missionId) == offered.end() && offeredMission->GetOfferMission()) { + GameMessages::SendOfferMission(entity->GetObjectID(), entity->GetSystemAddress(), missionId, m_Parent->GetObjectID()); + } + } } diff --git a/dGame/dComponents/MissionOfferComponent.h b/dGame/dComponents/MissionOfferComponent.h index 6719810e..42aad3c4 100644 --- a/dGame/dComponents/MissionOfferComponent.h +++ b/dGame/dComponents/MissionOfferComponent.h @@ -19,40 +19,40 @@ class Entity; struct OfferedMission { OfferedMission(uint32_t missionId, bool offersMission, bool acceptsMission); - /** - * Returns the ID of the mission - * @return the ID of the mission - */ - uint32_t GetMissionId() const; + /** + * Returns the ID of the mission + * @return the ID of the mission + */ + uint32_t GetMissionId() const; - /** - * Returns if this mission is offered by the entity - * @return true if this mission is offered by the entity, false otherwise - */ - bool GetOfferMission() const; + /** + * Returns if this mission is offered by the entity + * @return true if this mission is offered by the entity, false otherwise + */ + bool GetOfferMission() const; + + /** + * Returns if this mission may be accepted by the entity (currently unused) + * @return true if this mission may be accepted by the entity, false otherwise + */ + bool GetAcceptMission() const; - /** - * Returns if this mission may be accepted by the entity (currently unused) - * @return true if this mission may be accepted by the entity, false otherwise - */ - bool GetAcceptMission() const; - private: - /** - * The ID of the mission - */ - uint32_t missionId; + /** + * The ID of the mission + */ + uint32_t missionId; - /** - * Determines if the mission is offered by the entity - */ - bool offersMission; + /** + * Determines if the mission is offered by the entity + */ + bool offersMission; - /** - * Determines if the mission can be accepted by the entity - */ - bool acceptsMission; + /** + * Determines if the mission can be accepted by the entity + */ + bool acceptsMission; }; /** @@ -60,31 +60,31 @@ private: */ class MissionOfferComponent : public Component { public: - static const uint32_t ComponentType = COMPONENT_TYPE_MISSION_OFFER; - - MissionOfferComponent(Entity* parent, LOT parentLot); - ~MissionOfferComponent() override; + static const uint32_t ComponentType = COMPONENT_TYPE_MISSION_OFFER; - /** - * Handles the OnUse event triggered by some entity, determines which missions to show based on what they may - * hand in now and what they may start based on their mission history. - * @param originator the entity that triggered the event - */ - void OnUse(Entity* originator) override; + MissionOfferComponent(Entity* parent, LOT parentLot); + ~MissionOfferComponent() override; - /** - * Offers all the missions an entity can accept to said entity - * @param entity the entity to offer missions to - * @param specifiedMissionId optional mission ID if you wish to offer a specific mission - */ - void OfferMissions(Entity* entity, uint32_t specifiedMissionId = 0); + /** + * Handles the OnUse event triggered by some entity, determines which missions to show based on what they may + * hand in now and what they may start based on their mission history. + * @param originator the entity that triggered the event + */ + void OnUse(Entity* originator) override; + + /** + * Offers all the missions an entity can accept to said entity + * @param entity the entity to offer missions to + * @param specifiedMissionId optional mission ID if you wish to offer a specific mission + */ + void OfferMissions(Entity* entity, uint32_t specifiedMissionId = 0); private: - /** - * The missions this entity has to offer - */ - std::vector offeredMissions; + /** + * The missions this entity has to offer + */ + std::vector offeredMissions; }; #endif // MISSIONOFFERCOMPONENT_H diff --git a/dGame/dComponents/ModelComponent.cpp b/dGame/dComponents/ModelComponent.cpp index 65259912..8fa085f2 100644 --- a/dGame/dComponents/ModelComponent.cpp +++ b/dGame/dComponents/ModelComponent.cpp @@ -1,8 +1,7 @@ #include "ModelComponent.h" #include "Entity.h" -ModelComponent::ModelComponent(Entity* parent) : Component(parent) -{ +ModelComponent::ModelComponent(Entity* parent) : Component(parent) { m_OriginalPosition = m_Parent->GetDefaultPosition(); m_OriginalRotation = m_Parent->GetDefaultRotation(); @@ -16,17 +15,17 @@ void ModelComponent::Serialize(RakNet::BitStream* outBitStream, bool bIsInitialU outBitStream->Write(m_userModelID != LWOOBJID_EMPTY ? m_userModelID : m_Parent->GetObjectID()); outBitStream->Write(0); outBitStream->Write0(); - } - + } + //actual model component: outBitStream->Write1(); // Yes we are writing model info - outBitStream->Write0(); // Is pickable - outBitStream->Write(2); // Physics type - outBitStream->Write(m_OriginalPosition); // Original position - outBitStream->Write(m_OriginalRotation); // Original rotation + outBitStream->Write0(); // Is pickable + outBitStream->Write(2); // Physics type + outBitStream->Write(m_OriginalPosition); // Original position + outBitStream->Write(m_OriginalRotation); // Original rotation outBitStream->Write1(); // We are writing behavior info - outBitStream->Write(0); // Number of behaviors - outBitStream->Write1(); // Is this model paused + outBitStream->Write(0); // Number of behaviors + outBitStream->Write1(); // Is this model paused if (bIsInitialUpdate) outBitStream->Write0(); // We are not writing model editing info } diff --git a/dGame/dComponents/ModuleAssemblyComponent.cpp b/dGame/dComponents/ModuleAssemblyComponent.cpp index 0095b68f..8e197f0c 100644 --- a/dGame/dComponents/ModuleAssemblyComponent.cpp +++ b/dGame/dComponents/ModuleAssemblyComponent.cpp @@ -1,84 +1,70 @@ #include "ModuleAssemblyComponent.h" -ModuleAssemblyComponent::ModuleAssemblyComponent(Entity* parent) : Component(parent) -{ - m_SubKey = LWOOBJID_EMPTY; - m_UseOptionalParts = false; - m_AssemblyPartsLOTs = u""; +ModuleAssemblyComponent::ModuleAssemblyComponent(Entity* parent) : Component(parent) { + m_SubKey = LWOOBJID_EMPTY; + m_UseOptionalParts = false; + m_AssemblyPartsLOTs = u""; } -ModuleAssemblyComponent::~ModuleAssemblyComponent() -{ - +ModuleAssemblyComponent::~ModuleAssemblyComponent() { + } -void ModuleAssemblyComponent::SetSubKey(LWOOBJID value) -{ - m_SubKey = value; +void ModuleAssemblyComponent::SetSubKey(LWOOBJID value) { + m_SubKey = value; } -LWOOBJID ModuleAssemblyComponent::GetSubKey() const -{ - return m_SubKey; +LWOOBJID ModuleAssemblyComponent::GetSubKey() const { + return m_SubKey; } -void ModuleAssemblyComponent::SetUseOptionalParts(bool value) -{ - m_UseOptionalParts = value; +void ModuleAssemblyComponent::SetUseOptionalParts(bool value) { + m_UseOptionalParts = value; } -bool ModuleAssemblyComponent::GetUseOptionalParts() const -{ - return m_UseOptionalParts; +bool ModuleAssemblyComponent::GetUseOptionalParts() const { + return m_UseOptionalParts; } -void ModuleAssemblyComponent::SetAssemblyPartsLOTs(const std::u16string& value) -{ - std::u16string val {}; +void ModuleAssemblyComponent::SetAssemblyPartsLOTs(const std::u16string& value) { + std::u16string val{}; - val.reserve(value.size() + 1); + val.reserve(value.size() + 1); - for (auto character : value) - { - if (character == '+') character = ';'; + for (auto character : value) { + if (character == '+') character = ';'; - val.push_back(character); - } + val.push_back(character); + } - val.push_back(';'); - - m_AssemblyPartsLOTs = val; + val.push_back(';'); + + m_AssemblyPartsLOTs = val; } -const std::u16string& ModuleAssemblyComponent::GetAssemblyPartsLOTs() const -{ - return m_AssemblyPartsLOTs; +const std::u16string& ModuleAssemblyComponent::GetAssemblyPartsLOTs() const { + return m_AssemblyPartsLOTs; } -void ModuleAssemblyComponent::Serialize(RakNet::BitStream* outBitStream, bool bIsInitialUpdate, unsigned int& flags) -{ - if (bIsInitialUpdate) - { - outBitStream->Write1(); +void ModuleAssemblyComponent::Serialize(RakNet::BitStream* outBitStream, bool bIsInitialUpdate, unsigned int& flags) { + if (bIsInitialUpdate) { + outBitStream->Write1(); - outBitStream->Write(m_SubKey != LWOOBJID_EMPTY); - if (m_SubKey != LWOOBJID_EMPTY) - { - outBitStream->Write(m_SubKey); - } + outBitStream->Write(m_SubKey != LWOOBJID_EMPTY); + if (m_SubKey != LWOOBJID_EMPTY) { + outBitStream->Write(m_SubKey); + } - outBitStream->Write(m_UseOptionalParts); + outBitStream->Write(m_UseOptionalParts); - outBitStream->Write(static_cast(m_AssemblyPartsLOTs.size())); - for (char16_t character : m_AssemblyPartsLOTs) - { - outBitStream->Write(character); - } - } + outBitStream->Write(static_cast(m_AssemblyPartsLOTs.size())); + for (char16_t character : m_AssemblyPartsLOTs) { + outBitStream->Write(character); + } + } } -void ModuleAssemblyComponent::Update(float deltaTime) -{ - +void ModuleAssemblyComponent::Update(float deltaTime) { + } diff --git a/dGame/dComponents/ModuleAssemblyComponent.h b/dGame/dComponents/ModuleAssemblyComponent.h index 7153f30b..24e1c1ee 100644 --- a/dGame/dComponents/ModuleAssemblyComponent.h +++ b/dGame/dComponents/ModuleAssemblyComponent.h @@ -12,65 +12,65 @@ class ModuleAssemblyComponent : public Component { public: static const uint32_t ComponentType = COMPONENT_TYPE_MODULE_ASSEMBLY; - + ModuleAssemblyComponent(Entity* MSG_CHAT_INTERNAL_PLAYER_REMOVED_NOTIFICATION); ~ModuleAssemblyComponent() override; - void Serialize(RakNet::BitStream* outBitStream, bool bIsInitialUpdate, unsigned int& flags); - void Update(float deltaTime) override; + void Serialize(RakNet::BitStream* outBitStream, bool bIsInitialUpdate, unsigned int& flags); + void Update(float deltaTime) override; - /** - * Sets the subkey of this entity - * @param value the subkey to set - */ - void SetSubKey(LWOOBJID value); + /** + * Sets the subkey of this entity + * @param value the subkey to set + */ + void SetSubKey(LWOOBJID value); - /** - * Returns the subkey for this entity - * @return the subkey for this entity - */ - LWOOBJID GetSubKey() const; + /** + * Returns the subkey for this entity + * @return the subkey for this entity + */ + LWOOBJID GetSubKey() const; - /** - * Sets the optional parts value - * @param value the value to set - */ - void SetUseOptionalParts(bool value); + /** + * Sets the optional parts value + * @param value the value to set + */ + void SetUseOptionalParts(bool value); - /** - * Returns the optional parts value - * @return the value to set - */ - bool GetUseOptionalParts() const; + /** + * Returns the optional parts value + * @return the value to set + */ + bool GetUseOptionalParts() const; - /** - * Sets the assembly part lots (the subsections of this modular build) - * @param value the assembly part lots to set - */ - void SetAssemblyPartsLOTs(const std::u16string& value); + /** + * Sets the assembly part lots (the subsections of this modular build) + * @param value the assembly part lots to set + */ + void SetAssemblyPartsLOTs(const std::u16string& value); - /** - * Returns the assembly part lots (the subsections of this modular build) - * @return - */ - const std::u16string& GetAssemblyPartsLOTs() const; + /** + * Returns the assembly part lots (the subsections of this modular build) + * @return + */ + const std::u16string& GetAssemblyPartsLOTs() const; private: - /** - * The sub key is the entity that this entity is an instance of. E.g. the item in the inventory. If a car for - * example is to be rendered, this sub key refers to the car item that was used to build this entity. - */ - LWOOBJID m_SubKey; + /** + * The sub key is the entity that this entity is an instance of. E.g. the item in the inventory. If a car for + * example is to be rendered, this sub key refers to the car item that was used to build this entity. + */ + LWOOBJID m_SubKey; - /** - * Whether to use optional parts, currently unused - */ - bool m_UseOptionalParts; + /** + * Whether to use optional parts, currently unused + */ + bool m_UseOptionalParts; - /** - * The sub items that this entity is made of - */ - std::u16string m_AssemblyPartsLOTs; + /** + * The sub items that this entity is made of + */ + std::u16string m_AssemblyPartsLOTs; }; diff --git a/dGame/dComponents/MovementAIComponent.cpp b/dGame/dComponents/MovementAIComponent.cpp index ff7c0cef..9c76b286 100644 --- a/dGame/dComponents/MovementAIComponent.cpp +++ b/dGame/dComponents/MovementAIComponent.cpp @@ -17,7 +17,7 @@ MovementAIComponent::MovementAIComponent(Entity* parent, MovementAIInfo info) : m_Done = true; m_BaseCombatAI = nullptr; - + m_BaseCombatAI = reinterpret_cast(m_Parent->GetComponent(COMPONENT_TYPE_BASE_COMBAT_AI)); //Try and fix the insane values: @@ -42,12 +42,11 @@ MovementAIComponent::MovementAIComponent(Entity* parent, MovementAIInfo info) : MovementAIComponent::~MovementAIComponent() = default; void MovementAIComponent::Update(const float deltaTime) { - if (m_Interrupted) - { + if (m_Interrupted) { const auto source = GetCurrentWaypoint(); const auto speed = deltaTime * 2.5f; - + NiPoint3 velocity; velocity.x = (m_PullPoint.x - source.x) * speed; @@ -56,21 +55,19 @@ void MovementAIComponent::Update(const float deltaTime) { SetPosition(source + velocity); - if (Vector3::DistanceSquared(GetCurrentPosition(), m_PullPoint) < 2 * 2) - { + if (Vector3::DistanceSquared(GetCurrentPosition(), m_PullPoint) < 2 * 2) { m_Interrupted = false; } return; } - + if (AtFinalWaypoint()) // Are we done? { return; } - if (m_HaltDistance > 0) - { + if (m_HaltDistance > 0) { if (Vector3::DistanceSquared(ApproximateLocation(), GetDestination()) < m_HaltDistance * m_HaltDistance) // Prevent us from hugging the target { Stop(); @@ -79,12 +76,10 @@ void MovementAIComponent::Update(const float deltaTime) { } } - if (m_Timer > 0) - { + if (m_Timer > 0) { m_Timer -= deltaTime; - if (m_Timer > 0) - { + if (m_Timer > 0) { return; } @@ -92,7 +87,7 @@ void MovementAIComponent::Update(const float deltaTime) { } const auto source = GetCurrentWaypoint(); - + SetPosition(source); NiPoint3 velocity = NiPoint3::ZERO; @@ -101,20 +96,17 @@ void MovementAIComponent::Update(const float deltaTime) { { m_NextWaypoint = GetCurrentWaypoint(); - if (m_NextWaypoint == source) - { + if (m_NextWaypoint == source) { m_Timer = 0; goto nextAction; } - if (m_CurrentSpeed < m_Speed) - { + if (m_CurrentSpeed < m_Speed) { m_CurrentSpeed += m_Acceleration; } - if (m_CurrentSpeed > m_Speed) - { + if (m_CurrentSpeed > m_Speed) { m_CurrentSpeed = m_Speed; } @@ -125,8 +117,7 @@ void MovementAIComponent::Update(const float deltaTime) { // Normalize the vector const auto length = sqrtf(delta.x * delta.x + delta.y * delta.y + delta.z * delta.z); - if (length > 0) - { + if (length > 0) { velocity.x = (delta.x / length) * speed; velocity.y = (delta.y / length) * speed; velocity.z = (delta.z / length) * speed; @@ -134,80 +125,66 @@ void MovementAIComponent::Update(const float deltaTime) { // Calclute the time it will take to reach the next waypoint with the current speed m_TotalTime = m_Timer = length / speed; - + SetRotation(NiQuaternion::LookAt(source, m_NextWaypoint)); - } - else - { + } else { // Check if there are more waypoints in the queue, if so set our next destination to the next waypoint - if (!m_Queue.empty()) - { + if (!m_Queue.empty()) { SetDestination(m_Queue.top()); m_Queue.pop(); - } - else - { + } else { // We have reached our final waypoint Stop(); return; } } - - nextAction: + +nextAction: SetVelocity(velocity); EntityManager::Instance()->SerializeEntity(m_Parent); } -const MovementAIInfo& MovementAIComponent::GetInfo() const -{ +const MovementAIInfo& MovementAIComponent::GetInfo() const { return m_Info; } -bool MovementAIComponent::AdvanceWaypointIndex() -{ - if (m_PathIndex >= m_CurrentPath.size()) - { +bool MovementAIComponent::AdvanceWaypointIndex() { + if (m_PathIndex >= m_CurrentPath.size()) { return false; } - + m_PathIndex++; return true; } -NiPoint3 MovementAIComponent::GetCurrentWaypoint() const -{ - if (m_PathIndex >= m_CurrentPath.size()) - { +NiPoint3 MovementAIComponent::GetCurrentWaypoint() const { + if (m_PathIndex >= m_CurrentPath.size()) { return GetCurrentPosition(); } return m_CurrentPath[m_PathIndex]; } -NiPoint3 MovementAIComponent::GetNextWaypoint() const -{ +NiPoint3 MovementAIComponent::GetNextWaypoint() const { return m_NextWaypoint; } -NiPoint3 MovementAIComponent::GetCurrentPosition() const -{ +NiPoint3 MovementAIComponent::GetCurrentPosition() const { return m_Parent->GetPosition(); } -NiPoint3 MovementAIComponent::ApproximateLocation() const -{ +NiPoint3 MovementAIComponent::ApproximateLocation() const { auto source = GetCurrentPosition(); - - if (m_Done) - { + + if (m_Done) { return source; } - + auto destination = m_NextWaypoint; auto factor = m_TotalTime > 0 ? (m_TotalTime - m_Timer) / m_TotalTime : 0; @@ -217,27 +194,23 @@ NiPoint3 MovementAIComponent::ApproximateLocation() const auto z = source.z + factor * (destination.z - source.z); NiPoint3 approximation = NiPoint3(x, y, z); - - if (dpWorld::Instance().IsLoaded()) - { + + if (dpWorld::Instance().IsLoaded()) { approximation.y = dpWorld::Instance().GetHeightAtPoint(approximation); } return approximation; } -bool MovementAIComponent::Warp(const NiPoint3& point) -{ +bool MovementAIComponent::Warp(const NiPoint3& point) { Stop(); - + NiPoint3 destination = point; - if (dpWorld::Instance().IsLoaded()) - { + if (dpWorld::Instance().IsLoaded()) { destination.y = dpWorld::Instance().GetHeightAtPoint(point); - if (std::abs(destination.y - point.y) > 3) - { + if (std::abs(destination.y - point.y) > 3) { return false; } } @@ -249,29 +222,25 @@ bool MovementAIComponent::Warp(const NiPoint3& point) return true; } -float MovementAIComponent::GetTimer() const -{ +float MovementAIComponent::GetTimer() const { return m_Timer; } -bool MovementAIComponent::AtFinalWaypoint() const -{ +bool MovementAIComponent::AtFinalWaypoint() const { return m_Done; } -void MovementAIComponent::Stop() -{ - if (m_Done) - { +void MovementAIComponent::Stop() { + if (m_Done) { return; } SetPosition(ApproximateLocation()); SetVelocity(NiPoint3::ZERO); - + m_TotalTime = m_Timer = 0; - + m_Done = true; m_CurrentPath = {}; @@ -279,24 +248,21 @@ void MovementAIComponent::Stop() m_PathIndex = 0; m_CurrentSpeed = 0; - + EntityManager::Instance()->SerializeEntity(m_Parent); } -void MovementAIComponent::PullToPoint(const NiPoint3& point) -{ +void MovementAIComponent::PullToPoint(const NiPoint3& point) { Stop(); - + m_Interrupted = true; m_PullPoint = point; } -void MovementAIComponent::SetPath(std::vector path) -{ +void MovementAIComponent::SetPath(std::vector path) { std::reverse(path.begin(), path.end()); - for (const auto& point : path) - { + for (const auto& point : path) { m_Queue.push(point); } @@ -305,26 +271,23 @@ void MovementAIComponent::SetPath(std::vector path) m_Queue.pop(); } -float MovementAIComponent::GetBaseSpeed(LOT lot) -{ +float MovementAIComponent::GetBaseSpeed(LOT lot) { // Check if the lot is in the cache const auto& it = m_PhysicsSpeedCache.find(lot); - - if (it != m_PhysicsSpeedCache.end()) - { + + if (it != m_PhysicsSpeedCache.end()) { return it->second; } - + CDComponentsRegistryTable* componentRegistryTable = CDClientManager::Instance()->GetTable("ComponentsRegistry"); CDPhysicsComponentTable* physicsComponentTable = CDClientManager::Instance()->GetTable("PhysicsComponent"); int32_t componentID; CDPhysicsComponent* physicsComponent = nullptr; - componentID = componentRegistryTable->GetByIDAndType(lot, COMPONENT_TYPE_CONTROLLABLE_PHYSICS, -1); + componentID = componentRegistryTable->GetByIDAndType(lot, COMPONENT_TYPE_CONTROLLABLE_PHYSICS, -1); - if (componentID != -1) - { + if (componentID != -1) { physicsComponent = physicsComponentTable->GetByID(componentID); goto foundComponent; @@ -332,23 +295,19 @@ float MovementAIComponent::GetBaseSpeed(LOT lot) componentID = componentRegistryTable->GetByIDAndType(lot, COMPONENT_TYPE_SIMPLE_PHYSICS, -1); - if (componentID != -1) - { + if (componentID != -1) { physicsComponent = physicsComponentTable->GetByID(componentID); goto foundComponent; } - foundComponent: +foundComponent: float speed; - if (physicsComponent == nullptr) - { + if (physicsComponent == nullptr) { speed = 8; - } - else - { + } else { speed = physicsComponent->speed; } @@ -357,12 +316,10 @@ float MovementAIComponent::GetBaseSpeed(LOT lot) return speed; } -void MovementAIComponent::SetPosition(const NiPoint3& value) -{ +void MovementAIComponent::SetPosition(const NiPoint3& value) { auto* controllablePhysicsComponent = m_Parent->GetComponent(); - if (controllablePhysicsComponent != nullptr) - { + if (controllablePhysicsComponent != nullptr) { controllablePhysicsComponent->SetPosition(value); return; @@ -370,23 +327,19 @@ void MovementAIComponent::SetPosition(const NiPoint3& value) auto* simplePhysicsComponent = m_Parent->GetComponent(); - if (simplePhysicsComponent != nullptr) - { + if (simplePhysicsComponent != nullptr) { simplePhysicsComponent->SetPosition(value); } } -void MovementAIComponent::SetRotation(const NiQuaternion& value) -{ - if (m_LockRotation) - { +void MovementAIComponent::SetRotation(const NiQuaternion& value) { + if (m_LockRotation) { return; } auto* controllablePhysicsComponent = m_Parent->GetComponent(); - if (controllablePhysicsComponent != nullptr) - { + if (controllablePhysicsComponent != nullptr) { controllablePhysicsComponent->SetRotation(value); return; @@ -394,18 +347,15 @@ void MovementAIComponent::SetRotation(const NiQuaternion& value) auto* simplePhysicsComponent = m_Parent->GetComponent(); - if (simplePhysicsComponent != nullptr) - { + if (simplePhysicsComponent != nullptr) { simplePhysicsComponent->SetRotation(value); } } -void MovementAIComponent::SetVelocity(const NiPoint3& value) -{ +void MovementAIComponent::SetVelocity(const NiPoint3& value) { auto* controllablePhysicsComponent = m_Parent->GetComponent(); - if (controllablePhysicsComponent != nullptr) - { + if (controllablePhysicsComponent != nullptr) { controllablePhysicsComponent->SetVelocity(value); return; @@ -413,19 +363,16 @@ void MovementAIComponent::SetVelocity(const NiPoint3& value) auto* simplePhysicsComponent = m_Parent->GetComponent(); - if (simplePhysicsComponent != nullptr) - { + if (simplePhysicsComponent != nullptr) { simplePhysicsComponent->SetVelocity(value); } } -void MovementAIComponent::SetDestination(const NiPoint3& value) -{ - if (m_Interrupted) - { +void MovementAIComponent::SetDestination(const NiPoint3& value) { + if (m_Interrupted) { return; } - + /*if (Vector3::DistanceSquared(value, GetDestination()) < 2 * 2) { return; @@ -433,19 +380,15 @@ void MovementAIComponent::SetDestination(const NiPoint3& value) const auto location = ApproximateLocation(); - if (!AtFinalWaypoint()) - { + if (!AtFinalWaypoint()) { SetPosition(location); } std::vector computedPath; - - if (dpWorld::Instance().IsLoaded()) - { + + if (dpWorld::Instance().IsLoaded()) { computedPath = dpWorld::Instance().GetPath(GetCurrentPosition(), value, m_Info.wanderSpeed); - } - else - { + } else { // Than take 10 points between the current position and the destination and make that the path auto point = location; @@ -454,8 +397,7 @@ void MovementAIComponent::SetDestination(const NiPoint3& value) auto step = delta / 10; - for (int i = 0; i < 10; i++) - { + for (int i = 0; i < 10; i++) { point = point + step; computedPath.push_back(point); @@ -472,10 +414,8 @@ void MovementAIComponent::SetDestination(const NiPoint3& value) m_CurrentPath.push_back(location); // Simply path - for (auto point : computedPath) - { - if (dpWorld::Instance().IsLoaded()) - { + for (auto point : computedPath) { + if (dpWorld::Instance().IsLoaded()) { point.y = dpWorld::Instance().GetHeightAtPoint(point); } @@ -483,71 +423,59 @@ void MovementAIComponent::SetDestination(const NiPoint3& value) } m_CurrentPath.push_back(computedPath[computedPath.size() - 1]); - + m_PathIndex = 0; - + m_TotalTime = m_Timer = 0; - + m_Done = false; } -NiPoint3 MovementAIComponent::GetDestination() const -{ - if (m_CurrentPath.empty()) - { +NiPoint3 MovementAIComponent::GetDestination() const { + if (m_CurrentPath.empty()) { return GetCurrentPosition(); } return m_CurrentPath[m_CurrentPath.size() - 1]; } -void MovementAIComponent::SetSpeed(const float value) -{ +void MovementAIComponent::SetSpeed(const float value) { m_Speed = value; m_Acceleration = value / 5; } -float MovementAIComponent::GetSpeed() const -{ +float MovementAIComponent::GetSpeed() const { return m_Speed; } -void MovementAIComponent::SetAcceleration(const float value) -{ +void MovementAIComponent::SetAcceleration(const float value) { m_Acceleration = value; } -float MovementAIComponent::GetAcceleration() const -{ +float MovementAIComponent::GetAcceleration() const { return m_Acceleration; } -void MovementAIComponent::SetHaltDistance(const float value) -{ +void MovementAIComponent::SetHaltDistance(const float value) { m_HaltDistance = value; } -float MovementAIComponent::GetHaltDistance() const -{ +float MovementAIComponent::GetHaltDistance() const { return m_HaltDistance; } -void MovementAIComponent::SetCurrentSpeed(float value) -{ +void MovementAIComponent::SetCurrentSpeed(float value) { m_CurrentSpeed = value; } -float MovementAIComponent::GetCurrentSpeed() const -{ +float MovementAIComponent::GetCurrentSpeed() const { return m_CurrentSpeed; } -void MovementAIComponent::SetLockRotation(bool value) -{ +void MovementAIComponent::SetLockRotation(bool value) { m_LockRotation = value; } -bool MovementAIComponent::GetLockRotation() const -{ +bool MovementAIComponent::GetLockRotation() const { return m_LockRotation; } diff --git a/dGame/dComponents/MovementAIComponent.h b/dGame/dComponents/MovementAIComponent.h index 032732cc..82cd48a0 100644 --- a/dGame/dComponents/MovementAIComponent.h +++ b/dGame/dComponents/MovementAIComponent.h @@ -24,29 +24,29 @@ class BaseCombatAIComponent; struct MovementAIInfo { std::string movementType; - /** - * The radius that the entity can wander in - */ + /** + * The radius that the entity can wander in + */ float wanderRadius; - /** - * The speed at which the entity wanders - */ + /** + * The speed at which the entity wanders + */ float wanderSpeed; - /** - * This is only used for the emotes - */ + /** + * This is only used for the emotes + */ float wanderChance; - /** - * The min amount of delay before wandering - */ + /** + * The min amount of delay before wandering + */ float wanderDelayMin; - /** - * The max amount of delay before wandering - */ + /** + * The max amount of delay before wandering + */ float wanderDelayMax; }; @@ -57,273 +57,273 @@ struct MovementAIInfo { class MovementAIComponent : public Component { public: static const uint32_t ComponentType = COMPONENT_TYPE_MOVEMENT_AI; - + MovementAIComponent(Entity* parentEntity, MovementAIInfo info); ~MovementAIComponent() override; - + void Update(float deltaTime) override; - /** - * Returns the basic settings that this entity uses to move around - * @return the basic settings that this entity uses to move around - */ + /** + * Returns the basic settings that this entity uses to move around + * @return the basic settings that this entity uses to move around + */ const MovementAIInfo& GetInfo() const; - /** - * Set a destination point for the entity to move towards - * @param value the destination point to move towards - */ + /** + * Set a destination point for the entity to move towards + * @param value the destination point to move towards + */ void SetDestination(const NiPoint3& value); - /** - * Returns the current rotation this entity is moving towards - * @return the current rotation this entity is moving towards - */ + /** + * Returns the current rotation this entity is moving towards + * @return the current rotation this entity is moving towards + */ NiPoint3 GetDestination() const; - /** - * Sets the max speed at which this entity may run - * @param value the speed value to set - */ + /** + * Sets the max speed at which this entity may run + * @param value the speed value to set + */ void SetSpeed(float value); - /** - * Returns the max speed at which this entity may run - * @return the max speed at which this entity may run - */ + /** + * Returns the max speed at which this entity may run + * @return the max speed at which this entity may run + */ float GetSpeed() const; - /** - * Sets how fast the entity will accelerate when not running at full speed - * @param value the acceleration to set - */ + /** + * Sets how fast the entity will accelerate when not running at full speed + * @param value the acceleration to set + */ void SetAcceleration(float value); - /** - * Returns the current speed at which this entity accelerates when not running at full speed - * @return the current speed at which this entity accelerates when not running at full speed - */ + /** + * Returns the current speed at which this entity accelerates when not running at full speed + * @return the current speed at which this entity accelerates when not running at full speed + */ float GetAcceleration() const; - /** - * Sets the halting distance (the distance at which we consider the target to be reached) - * @param value the halting distance to set - */ + /** + * Sets the halting distance (the distance at which we consider the target to be reached) + * @param value the halting distance to set + */ void SetHaltDistance(float value); - /** - * Returns the current halting distance (the distance at which we consider the target to be reached) - * @return the current halting distance - */ + /** + * Returns the current halting distance (the distance at which we consider the target to be reached) + * @return the current halting distance + */ float GetHaltDistance() const; - /** - * Sets the speed the entity is currently running at - * @param value the speed value to set - */ + /** + * Sets the speed the entity is currently running at + * @param value the speed value to set + */ void SetCurrentSpeed(float value); - /** - * Returns the speed the entity is currently running at - * @return the speed the entity is currently running at - */ + /** + * Returns the speed the entity is currently running at + * @return the speed the entity is currently running at + */ float GetCurrentSpeed() const; - /** - * Locks the rotation of this entity in place, depending on the argument - * @param value if true, the entity will be rotationally locked - */ + /** + * Locks the rotation of this entity in place, depending on the argument + * @param value if true, the entity will be rotationally locked + */ void SetLockRotation(bool value); - /** - * Returns whether this entity is currently rotationally locked - * @return true if the entity is rotationally locked, false otherwise - */ + /** + * Returns whether this entity is currently rotationally locked + * @return true if the entity is rotationally locked, false otherwise + */ bool GetLockRotation() const; - /** - * Attempts to update the waypoint index, making the entity move to the next waypoint - * @return true if the waypoint could be increased, false if the entity is at the last waypoint already - */ + /** + * Attempts to update the waypoint index, making the entity move to the next waypoint + * @return true if the waypoint could be increased, false if the entity is at the last waypoint already + */ bool AdvanceWaypointIndex(); - /** - * Returns the waypoint the entity is currently moving towards - * @return the waypoint the entity is currently moving towards - */ + /** + * Returns the waypoint the entity is currently moving towards + * @return the waypoint the entity is currently moving towards + */ NiPoint3 GetCurrentWaypoint() const; - /** - * Returns the waypoint this entity is supposed to move towards next - * @return the waypoint this entity is supposed to move towards next - */ + /** + * Returns the waypoint this entity is supposed to move towards next + * @return the waypoint this entity is supposed to move towards next + */ NiPoint3 GetNextWaypoint() const; - /** - * Returns the current position of this entity - * @return the current position of this entity - */ + /** + * Returns the current position of this entity + * @return the current position of this entity + */ NiPoint3 GetCurrentPosition() const; - /** - * Returns the approximate current location of the entity, including y coordinates - * @return the approximate current location of the entity - */ + /** + * Returns the approximate current location of the entity, including y coordinates + * @return the approximate current location of the entity + */ NiPoint3 ApproximateLocation() const; - /** - * Teleports this entity to a position. If the distance between the provided point and the y it should have - * according to map data, this will not succeed (to avoid teleporting entities into the sky). - * @param point the point to teleport to - * @return true if the warp was successful, false otherwise - */ + /** + * Teleports this entity to a position. If the distance between the provided point and the y it should have + * according to map data, this will not succeed (to avoid teleporting entities into the sky). + * @param point the point to teleport to + * @return true if the warp was successful, false otherwise + */ bool Warp(const NiPoint3& point); - /** - * Returns the time it will take to reach the final waypoint according to the current speed - * @return the time it will take to reach the final waypoint according to the current speed - */ + /** + * Returns the time it will take to reach the final waypoint according to the current speed + * @return the time it will take to reach the final waypoint according to the current speed + */ float GetTimer() const; - /** - * Returns if the entity is at its final waypoint - * @return if the entity is at its final waypoint - */ + /** + * Returns if the entity is at its final waypoint + * @return if the entity is at its final waypoint + */ bool AtFinalWaypoint() const; - /** - * Renders the entity stationary - */ + /** + * Renders the entity stationary + */ void Stop(); - /** - * Stops the current movement and moves the entity to a certain point. Will continue until it's close enough, - * after which its AI is enabled again. - * @param point the point to move towards - */ + /** + * Stops the current movement and moves the entity to a certain point. Will continue until it's close enough, + * after which its AI is enabled again. + * @param point the point to move towards + */ void PullToPoint(const NiPoint3& point); - /** - * Sets a path to follow for the AI - * @param path the path to follow - */ + /** + * Sets a path to follow for the AI + * @param path the path to follow + */ void SetPath(std::vector path); - /** - * Returns the base speed from the DB for a given LOT - * @param lot the lot to check for - * @return the base speed of the lot - */ + /** + * Returns the base speed from the DB for a given LOT + * @param lot the lot to check for + * @return the base speed of the lot + */ static float GetBaseSpeed(LOT lot); private: - /** - * Sets the current position of the entity - * @param value the position to set - */ + /** + * Sets the current position of the entity + * @param value the position to set + */ void SetPosition(const NiPoint3& value); - /** - * Sets the current rotation of the entity - * @param value the rotation to set - */ + /** + * Sets the current rotation of the entity + * @param value the rotation to set + */ void SetRotation(const NiQuaternion& value); - /** - * Sets the current velocity of the entityes - * @param value the velocity to set - */ + /** + * Sets the current velocity of the entityes + * @param value the velocity to set + */ void SetVelocity(const NiPoint3& value); - /** - * Base information regarding the movement information for this entity - */ + /** + * Base information regarding the movement information for this entity + */ MovementAIInfo m_Info; - /** - * The point this entity is moving towards - */ + /** + * The point this entity is moving towards + */ NiPoint3 m_NextWaypoint; - /** - * The max speed this entity may move at - */ + /** + * The max speed this entity may move at + */ float m_Speed; - /** - * The time it will take to reach the next waypoint using the current speed - */ + /** + * The time it will take to reach the next waypoint using the current speed + */ float m_Timer; - /** - * The total time it will take to reach the waypoint form its starting point - */ + /** + * The total time it will take to reach the waypoint form its starting point + */ float m_TotalTime; - /** - * The path this entity is currently traversing - */ + /** + * The path this entity is currently traversing + */ uint32_t m_PathIndex; - /** - * If the entity has reached it last waypoint - */ + /** + * If the entity has reached it last waypoint + */ bool m_Done; - /** - * The speed the entity is currently moving at - */ + /** + * The speed the entity is currently moving at + */ float m_CurrentSpeed; - /** - * The acceleration this entity has when not moving at its top speed yet - */ + /** + * The acceleration this entity has when not moving at its top speed yet + */ float m_Acceleration; - /** - * The distance between the current position and the target waypoint to consider it reached (to not ghost into it). - */ + /** + * The distance between the current position and the target waypoint to consider it reached (to not ghost into it). + */ float m_HaltDistance; - /** - * The base speed this entity has - */ + /** + * The base speed this entity has + */ float m_BaseSpeed; - /** - * If the AI is currently turned of (e.g. when teleporting to some location) - */ + /** + * If the AI is currently turned of (e.g. when teleporting to some location) + */ bool m_Interrupted; - /** - * A position that the entity is currently moving towards while being interrupted - */ + /** + * A position that the entity is currently moving towards while being interrupted + */ NiPoint3 m_PullPoint; - /** - * If the entity is currently rotationally locked - */ + /** + * If the entity is currently rotationally locked + */ bool m_LockRotation; - /** - * Optional direct link to the combat AI component of the parent entity - */ + /** + * Optional direct link to the combat AI component of the parent entity + */ BaseCombatAIComponent* m_BaseCombatAI = nullptr; - /** - * The path the entity is currently following - */ + /** + * The path the entity is currently following + */ std::vector m_CurrentPath; - /** - * Queue of positions to traverse - */ + /** + * Queue of positions to traverse + */ std::stack m_Queue; - /** - * Cache of all lots and their respective speeds - */ + /** + * Cache of all lots and their respective speeds + */ static std::map m_PhysicsSpeedCache; }; diff --git a/dGame/dComponents/MovingPlatformComponent.cpp b/dGame/dComponents/MovingPlatformComponent.cpp index 4e99e6d6..42699672 100644 --- a/dGame/dComponents/MovingPlatformComponent.cpp +++ b/dGame/dComponents/MovingPlatformComponent.cpp @@ -14,370 +14,339 @@ #include "SimplePhysicsComponent.h" MoverSubComponent::MoverSubComponent(const NiPoint3& startPos) { - mPosition = {}; + mPosition = {}; mState = MovementPlatformState::Stopped; - mDesiredWaypointIndex = 0; // -1; - mInReverse = false; - mShouldStopAtDesiredWaypoint = false; + mDesiredWaypointIndex = 0; // -1; + mInReverse = false; + mShouldStopAtDesiredWaypoint = false; - mPercentBetweenPoints = 0.0f; + mPercentBetweenPoints = 0.0f; - mCurrentWaypointIndex = 0; - mNextWaypointIndex = 0; //mCurrentWaypointIndex + 1; + mCurrentWaypointIndex = 0; + mNextWaypointIndex = 0; //mCurrentWaypointIndex + 1; - mIdleTimeElapsed = 0.0f; + mIdleTimeElapsed = 0.0f; } MoverSubComponent::~MoverSubComponent() = default; void MoverSubComponent::Serialize(RakNet::BitStream* outBitStream, bool bIsInitialUpdate, unsigned int& flags) const { - outBitStream->Write(true); + outBitStream->Write(true); - outBitStream->Write(static_cast(mState)); - outBitStream->Write(mDesiredWaypointIndex); - outBitStream->Write(mShouldStopAtDesiredWaypoint); - outBitStream->Write(mInReverse); + outBitStream->Write(static_cast(mState)); + outBitStream->Write(mDesiredWaypointIndex); + outBitStream->Write(mShouldStopAtDesiredWaypoint); + outBitStream->Write(mInReverse); - outBitStream->Write(mPercentBetweenPoints); + outBitStream->Write(mPercentBetweenPoints); - outBitStream->Write(mPosition.x); - outBitStream->Write(mPosition.y); - outBitStream->Write(mPosition.z); + outBitStream->Write(mPosition.x); + outBitStream->Write(mPosition.y); + outBitStream->Write(mPosition.z); - outBitStream->Write(mCurrentWaypointIndex); - outBitStream->Write(mNextWaypointIndex); + outBitStream->Write(mCurrentWaypointIndex); + outBitStream->Write(mNextWaypointIndex); - outBitStream->Write(mIdleTimeElapsed); - outBitStream->Write(0.0f); // Move time elapsed + outBitStream->Write(mIdleTimeElapsed); + outBitStream->Write(0.0f); // Move time elapsed } //------------- MovingPlatformComponent below -------------- MovingPlatformComponent::MovingPlatformComponent(Entity* parent, const std::string& pathName) : Component(parent) { - m_MoverSubComponentType = eMoverSubComponentType::mover; - m_MoverSubComponent = new MoverSubComponent(m_Parent->GetDefaultPosition()); - m_PathName = GeneralUtils::ASCIIToUTF16(pathName); - m_Path = dZoneManager::Instance()->GetZone()->GetPath(pathName); - m_NoAutoStart = false; + m_MoverSubComponentType = eMoverSubComponentType::mover; + m_MoverSubComponent = new MoverSubComponent(m_Parent->GetDefaultPosition()); + m_PathName = GeneralUtils::ASCIIToUTF16(pathName); + m_Path = dZoneManager::Instance()->GetZone()->GetPath(pathName); + m_NoAutoStart = false; - if (m_Path == nullptr) { - Game::logger->Log("MovingPlatformComponent", "Path not found: %s", pathName.c_str()); - } + if (m_Path == nullptr) { + Game::logger->Log("MovingPlatformComponent", "Path not found: %s", pathName.c_str()); + } } MovingPlatformComponent::~MovingPlatformComponent() { - delete static_cast(m_MoverSubComponent); + delete static_cast(m_MoverSubComponent); } void MovingPlatformComponent::Serialize(RakNet::BitStream* outBitStream, bool bIsInitialUpdate, unsigned int& flags) { - // Here we don't serialize the moving platform to let the client simulate the movement + // Here we don't serialize the moving platform to let the client simulate the movement - if (!m_Serialize) - { - outBitStream->Write(false); - outBitStream->Write(false); + if (!m_Serialize) { + outBitStream->Write(false); + outBitStream->Write(false); - return; - } + return; + } - outBitStream->Write(true); + outBitStream->Write(true); - auto hasPath = !m_PathingStopped && !m_PathName.empty(); - outBitStream->Write(hasPath); + auto hasPath = !m_PathingStopped && !m_PathName.empty(); + outBitStream->Write(hasPath); - if (hasPath) { - // Is on rail - outBitStream->Write1(); + if (hasPath) { + // Is on rail + outBitStream->Write1(); - outBitStream->Write(static_cast(m_PathName.size())); - for (const auto& c : m_PathName) { - outBitStream->Write(static_cast(c)); - } + outBitStream->Write(static_cast(m_PathName.size())); + for (const auto& c : m_PathName) { + outBitStream->Write(static_cast(c)); + } - // Starting point - outBitStream->Write(0); + // Starting point + outBitStream->Write(0); - // Reverse - outBitStream->Write(false); - } + // Reverse + outBitStream->Write(false); + } - const auto hasPlatform = m_MoverSubComponent != nullptr; - outBitStream->Write(hasPlatform); + const auto hasPlatform = m_MoverSubComponent != nullptr; + outBitStream->Write(hasPlatform); - if (hasPlatform) { - auto* mover = static_cast(m_MoverSubComponent); - outBitStream->Write(static_cast(m_MoverSubComponentType)); + if (hasPlatform) { + auto* mover = static_cast(m_MoverSubComponent); + outBitStream->Write(static_cast(m_MoverSubComponentType)); - if (m_MoverSubComponentType == eMoverSubComponentType::simpleMover) { - // TODO - } else { - mover->Serialize(outBitStream, bIsInitialUpdate, flags); - } - } + if (m_MoverSubComponentType == eMoverSubComponentType::simpleMover) { + // TODO + } else { + mover->Serialize(outBitStream, bIsInitialUpdate, flags); + } + } } void MovingPlatformComponent::OnRebuildInitilized() { - StopPathing(); + StopPathing(); } void MovingPlatformComponent::OnCompleteRebuild() { - if (m_NoAutoStart) - return; + if (m_NoAutoStart) + return; - StartPathing(); + StartPathing(); } -void MovingPlatformComponent::SetMovementState(MovementPlatformState value) -{ - auto* subComponent = static_cast(m_MoverSubComponent); +void MovingPlatformComponent::SetMovementState(MovementPlatformState value) { + auto* subComponent = static_cast(m_MoverSubComponent); - subComponent->mState = value; + subComponent->mState = value; - EntityManager::Instance()->SerializeEntity(m_Parent); + EntityManager::Instance()->SerializeEntity(m_Parent); } -void MovingPlatformComponent::GotoWaypoint(uint32_t index, bool stopAtWaypoint) -{ - auto* subComponent = static_cast(m_MoverSubComponent); +void MovingPlatformComponent::GotoWaypoint(uint32_t index, bool stopAtWaypoint) { + auto* subComponent = static_cast(m_MoverSubComponent); - subComponent->mDesiredWaypointIndex = index; - subComponent->mNextWaypointIndex = index; - subComponent->mShouldStopAtDesiredWaypoint = stopAtWaypoint; + subComponent->mDesiredWaypointIndex = index; + subComponent->mNextWaypointIndex = index; + subComponent->mShouldStopAtDesiredWaypoint = stopAtWaypoint; - StartPathing(); + StartPathing(); } -void MovingPlatformComponent::StartPathing() -{ +void MovingPlatformComponent::StartPathing() { //GameMessages::SendStartPathing(m_Parent); - m_PathingStopped = false; + m_PathingStopped = false; - auto* subComponent = static_cast(m_MoverSubComponent); + auto* subComponent = static_cast(m_MoverSubComponent); - subComponent->mShouldStopAtDesiredWaypoint = true; - subComponent->mState = MovementPlatformState::Stationary; + subComponent->mShouldStopAtDesiredWaypoint = true; + subComponent->mState = MovementPlatformState::Stationary; - NiPoint3 targetPosition; + NiPoint3 targetPosition; - if (m_Path != nullptr) { - const auto& currentWaypoint = m_Path->pathWaypoints[subComponent->mCurrentWaypointIndex]; - const auto& nextWaypoint = m_Path->pathWaypoints[subComponent->mNextWaypointIndex]; + if (m_Path != nullptr) { + const auto& currentWaypoint = m_Path->pathWaypoints[subComponent->mCurrentWaypointIndex]; + const auto& nextWaypoint = m_Path->pathWaypoints[subComponent->mNextWaypointIndex]; - subComponent->mPosition = currentWaypoint.position; - subComponent->mSpeed = currentWaypoint.movingPlatform.speed; - subComponent->mWaitTime = currentWaypoint.movingPlatform.wait; + subComponent->mPosition = currentWaypoint.position; + subComponent->mSpeed = currentWaypoint.movingPlatform.speed; + subComponent->mWaitTime = currentWaypoint.movingPlatform.wait; - targetPosition = nextWaypoint.position; - } - else { - subComponent->mPosition = m_Parent->GetPosition(); - subComponent->mSpeed = 1.0f; - subComponent->mWaitTime = 2.0f; + targetPosition = nextWaypoint.position; + } else { + subComponent->mPosition = m_Parent->GetPosition(); + subComponent->mSpeed = 1.0f; + subComponent->mWaitTime = 2.0f; - targetPosition = m_Parent->GetPosition() + NiPoint3(0.0f, 10.0f, 0.0f); - } + targetPosition = m_Parent->GetPosition() + NiPoint3(0.0f, 10.0f, 0.0f); + } - m_Parent->AddCallbackTimer(subComponent->mWaitTime, [this] - { - SetMovementState(MovementPlatformState::Moving); - }); + m_Parent->AddCallbackTimer(subComponent->mWaitTime, [this] { + SetMovementState(MovementPlatformState::Moving); + }); - const auto travelTime = Vector3::Distance(targetPosition, subComponent->mPosition) / subComponent->mSpeed + 1.5f; + const auto travelTime = Vector3::Distance(targetPosition, subComponent->mPosition) / subComponent->mSpeed + 1.5f; - const auto travelNext = subComponent->mWaitTime + travelTime; + const auto travelNext = subComponent->mWaitTime + travelTime; - m_Parent->AddCallbackTimer(travelTime, [subComponent, this] { - for (CppScripts::Script* script : CppScripts::GetEntityScripts(m_Parent)) { - script->OnWaypointReached(m_Parent, subComponent->mNextWaypointIndex); - } - }); + m_Parent->AddCallbackTimer(travelTime, [subComponent, this] { + for (CppScripts::Script* script : CppScripts::GetEntityScripts(m_Parent)) { + script->OnWaypointReached(m_Parent, subComponent->mNextWaypointIndex); + } + }); - m_Parent->AddCallbackTimer(travelNext, [this] - { - ContinuePathing(); - }); + m_Parent->AddCallbackTimer(travelNext, [this] { + ContinuePathing(); + }); - //GameMessages::SendPlatformResync(m_Parent, UNASSIGNED_SYSTEM_ADDRESS); + //GameMessages::SendPlatformResync(m_Parent, UNASSIGNED_SYSTEM_ADDRESS); - EntityManager::Instance()->SerializeEntity(m_Parent); + EntityManager::Instance()->SerializeEntity(m_Parent); } -void MovingPlatformComponent::ContinuePathing() -{ - auto* subComponent = static_cast(m_MoverSubComponent); +void MovingPlatformComponent::ContinuePathing() { + auto* subComponent = static_cast(m_MoverSubComponent); - subComponent->mState = MovementPlatformState::Stationary; + subComponent->mState = MovementPlatformState::Stationary; - subComponent->mCurrentWaypointIndex = subComponent->mNextWaypointIndex; + subComponent->mCurrentWaypointIndex = subComponent->mNextWaypointIndex; - NiPoint3 targetPosition; - uint32_t pathSize; - PathBehavior behavior; + NiPoint3 targetPosition; + uint32_t pathSize; + PathBehavior behavior; - if (m_Path != nullptr) { - const auto& currentWaypoint = m_Path->pathWaypoints[subComponent->mCurrentWaypointIndex]; - const auto& nextWaypoint = m_Path->pathWaypoints[subComponent->mNextWaypointIndex]; + if (m_Path != nullptr) { + const auto& currentWaypoint = m_Path->pathWaypoints[subComponent->mCurrentWaypointIndex]; + const auto& nextWaypoint = m_Path->pathWaypoints[subComponent->mNextWaypointIndex]; - subComponent->mPosition = currentWaypoint.position; - subComponent->mSpeed = currentWaypoint.movingPlatform.speed; - subComponent->mWaitTime = currentWaypoint.movingPlatform.wait; // + 2; + subComponent->mPosition = currentWaypoint.position; + subComponent->mSpeed = currentWaypoint.movingPlatform.speed; + subComponent->mWaitTime = currentWaypoint.movingPlatform.wait; // + 2; - pathSize = m_Path->pathWaypoints.size() - 1; + pathSize = m_Path->pathWaypoints.size() - 1; - behavior = static_cast(m_Path->pathBehavior); + behavior = static_cast(m_Path->pathBehavior); - targetPosition = nextWaypoint.position; - } - else - { - subComponent->mPosition = m_Parent->GetPosition(); - subComponent->mSpeed = 1.0f; - subComponent->mWaitTime = 2.0f; + targetPosition = nextWaypoint.position; + } else { + subComponent->mPosition = m_Parent->GetPosition(); + subComponent->mSpeed = 1.0f; + subComponent->mWaitTime = 2.0f; - targetPosition = m_Parent->GetPosition() + NiPoint3(0.0f, 10.0f, 0.0f); + targetPosition = m_Parent->GetPosition() + NiPoint3(0.0f, 10.0f, 0.0f); - pathSize = 1; - behavior = PathBehavior::Loop; - } + pathSize = 1; + behavior = PathBehavior::Loop; + } - if (m_Parent->GetLOT() == 9483) - { - behavior = PathBehavior::Bounce; - } - else - { - return; - } + if (m_Parent->GetLOT() == 9483) { + behavior = PathBehavior::Bounce; + } else { + return; + } - if (subComponent->mCurrentWaypointIndex >= pathSize) - { - subComponent->mCurrentWaypointIndex = pathSize; - switch (behavior) - { - case PathBehavior::Once: - EntityManager::Instance()->SerializeEntity(m_Parent); - return; + if (subComponent->mCurrentWaypointIndex >= pathSize) { + subComponent->mCurrentWaypointIndex = pathSize; + switch (behavior) { + case PathBehavior::Once: + EntityManager::Instance()->SerializeEntity(m_Parent); + return; - case PathBehavior::Bounce: - subComponent->mInReverse = true; - break; + case PathBehavior::Bounce: + subComponent->mInReverse = true; + break; - case PathBehavior::Loop: - subComponent->mNextWaypointIndex = 0; - break; + case PathBehavior::Loop: + subComponent->mNextWaypointIndex = 0; + break; - default: - break; - } - } - else if (subComponent->mCurrentWaypointIndex == 0) - { - subComponent->mInReverse = false; - } + default: + break; + } + } else if (subComponent->mCurrentWaypointIndex == 0) { + subComponent->mInReverse = false; + } - if (subComponent->mInReverse) - { - subComponent->mNextWaypointIndex = subComponent->mCurrentWaypointIndex - 1; - } - else - { - subComponent->mNextWaypointIndex = subComponent->mCurrentWaypointIndex + 1; - } + if (subComponent->mInReverse) { + subComponent->mNextWaypointIndex = subComponent->mCurrentWaypointIndex - 1; + } else { + subComponent->mNextWaypointIndex = subComponent->mCurrentWaypointIndex + 1; + } - /* - subComponent->mNextWaypointIndex = 0; - subComponent->mCurrentWaypointIndex = 1; - */ + /* + subComponent->mNextWaypointIndex = 0; + subComponent->mCurrentWaypointIndex = 1; + */ - //GameMessages::SendPlatformResync(m_Parent, UNASSIGNED_SYSTEM_ADDRESS); + //GameMessages::SendPlatformResync(m_Parent, UNASSIGNED_SYSTEM_ADDRESS); - if (subComponent->mCurrentWaypointIndex == subComponent->mDesiredWaypointIndex) - { - // TODO: Send event? - StopPathing(); + if (subComponent->mCurrentWaypointIndex == subComponent->mDesiredWaypointIndex) { + // TODO: Send event? + StopPathing(); - return; - } + return; + } - m_Parent->CancelCallbackTimers(); + m_Parent->CancelCallbackTimers(); - m_Parent->AddCallbackTimer(subComponent->mWaitTime, [this] - { - SetMovementState(MovementPlatformState::Moving); - }); + m_Parent->AddCallbackTimer(subComponent->mWaitTime, [this] { + SetMovementState(MovementPlatformState::Moving); + }); - auto travelTime = Vector3::Distance(targetPosition, subComponent->mPosition) / subComponent->mSpeed + 1.5; + auto travelTime = Vector3::Distance(targetPosition, subComponent->mPosition) / subComponent->mSpeed + 1.5; - if (m_Parent->GetLOT() == 9483) - { - travelTime += 20; - } + if (m_Parent->GetLOT() == 9483) { + travelTime += 20; + } - const auto travelNext = subComponent->mWaitTime + travelTime; + const auto travelNext = subComponent->mWaitTime + travelTime; - m_Parent->AddCallbackTimer(travelTime, [subComponent, this] { - for (CppScripts::Script* script : CppScripts::GetEntityScripts(m_Parent)) { - script->OnWaypointReached(m_Parent, subComponent->mNextWaypointIndex); - } - }); + m_Parent->AddCallbackTimer(travelTime, [subComponent, this] { + for (CppScripts::Script* script : CppScripts::GetEntityScripts(m_Parent)) { + script->OnWaypointReached(m_Parent, subComponent->mNextWaypointIndex); + } + }); - m_Parent->AddCallbackTimer(travelNext, [this] - { - ContinuePathing(); - }); + m_Parent->AddCallbackTimer(travelNext, [this] { + ContinuePathing(); + }); - EntityManager::Instance()->SerializeEntity(m_Parent); + EntityManager::Instance()->SerializeEntity(m_Parent); } -void MovingPlatformComponent::StopPathing() -{ - //m_Parent->CancelCallbackTimers(); +void MovingPlatformComponent::StopPathing() { + //m_Parent->CancelCallbackTimers(); - auto* subComponent = static_cast(m_MoverSubComponent); + auto* subComponent = static_cast(m_MoverSubComponent); - m_PathingStopped = true; + m_PathingStopped = true; - subComponent->mState = MovementPlatformState::Stopped; - subComponent->mDesiredWaypointIndex = -1; - subComponent->mShouldStopAtDesiredWaypoint = false; + subComponent->mState = MovementPlatformState::Stopped; + subComponent->mDesiredWaypointIndex = -1; + subComponent->mShouldStopAtDesiredWaypoint = false; - EntityManager::Instance()->SerializeEntity(m_Parent); + EntityManager::Instance()->SerializeEntity(m_Parent); - //GameMessages::SendPlatformResync(m_Parent, UNASSIGNED_SYSTEM_ADDRESS); + //GameMessages::SendPlatformResync(m_Parent, UNASSIGNED_SYSTEM_ADDRESS); } -void MovingPlatformComponent::SetSerialized(bool value) -{ - m_Serialize = value; +void MovingPlatformComponent::SetSerialized(bool value) { + m_Serialize = value; } -bool MovingPlatformComponent::GetNoAutoStart() const -{ - return m_NoAutoStart; +bool MovingPlatformComponent::GetNoAutoStart() const { + return m_NoAutoStart; } -void MovingPlatformComponent::SetNoAutoStart(const bool value) -{ - m_NoAutoStart = value; +void MovingPlatformComponent::SetNoAutoStart(const bool value) { + m_NoAutoStart = value; } -void MovingPlatformComponent::WarpToWaypoint(size_t index) -{ - const auto& waypoint = m_Path->pathWaypoints[index]; +void MovingPlatformComponent::WarpToWaypoint(size_t index) { + const auto& waypoint = m_Path->pathWaypoints[index]; - m_Parent->SetPosition(waypoint.position); - m_Parent->SetRotation(waypoint.rotation); + m_Parent->SetPosition(waypoint.position); + m_Parent->SetRotation(waypoint.rotation); - EntityManager::Instance()->SerializeEntity(m_Parent); + EntityManager::Instance()->SerializeEntity(m_Parent); } -size_t MovingPlatformComponent::GetLastWaypointIndex() const -{ - return m_Path->pathWaypoints.size() - 1; +size_t MovingPlatformComponent::GetLastWaypointIndex() const { + return m_Path->pathWaypoints.size() - 1; } -MoverSubComponent* MovingPlatformComponent::GetMoverSubComponent() const -{ - return static_cast(m_MoverSubComponent); +MoverSubComponent* MovingPlatformComponent::GetMoverSubComponent() const { + return static_cast(m_MoverSubComponent); } diff --git a/dGame/dComponents/MovingPlatformComponent.h b/dGame/dComponents/MovingPlatformComponent.h index da377916..efa3a4cf 100644 --- a/dGame/dComponents/MovingPlatformComponent.h +++ b/dGame/dComponents/MovingPlatformComponent.h @@ -14,16 +14,16 @@ #include "EntityManager.h" #include "Component.h" -/** - * Different types of available platforms - */ + /** + * Different types of available platforms + */ enum class eMoverSubComponentType : uint32_t { - mover = 4, + mover = 4, - /** - * Used in NJ - */ - simpleMover = 5, + /** + * Used in NJ + */ + simpleMover = 5, }; /** @@ -31,9 +31,9 @@ enum class eMoverSubComponentType : uint32_t { */ enum class MovementPlatformState : uint32_t { - Moving = 0b00010, - Stationary = 0b11001, - Stopped = 0b01100 + Moving = 0b00010, + Stationary = 0b11001, + Stopped = 0b01100 }; /** @@ -41,65 +41,65 @@ enum class MovementPlatformState : uint32_t */ class MoverSubComponent { public: - MoverSubComponent(const NiPoint3& startPos); - ~MoverSubComponent(); - - void Serialize(RakNet::BitStream* outBitStream, bool bIsInitialUpdate, unsigned int& flags) const; + MoverSubComponent(const NiPoint3& startPos); + ~MoverSubComponent(); - /** - * The state the platform is currently in - */ - MovementPlatformState mState = MovementPlatformState::Stationary; + void Serialize(RakNet::BitStream* outBitStream, bool bIsInitialUpdate, unsigned int& flags) const; - /** - * The waypoint this platform currently wants to traverse to - */ - int32_t mDesiredWaypointIndex = 0; + /** + * The state the platform is currently in + */ + MovementPlatformState mState = MovementPlatformState::Stationary; - /** - * Whether the platform is currently reversing away from the desired waypoint - */ - bool mInReverse = false; + /** + * The waypoint this platform currently wants to traverse to + */ + int32_t mDesiredWaypointIndex = 0; - /** - * Whether the platform should stop moving when reaching the desired waypoint - */ - bool mShouldStopAtDesiredWaypoint = false; + /** + * Whether the platform is currently reversing away from the desired waypoint + */ + bool mInReverse = false; - /** - * The percentage of the way between the last point and the desired point - */ - float mPercentBetweenPoints = 0; + /** + * Whether the platform should stop moving when reaching the desired waypoint + */ + bool mShouldStopAtDesiredWaypoint = false; - /** - * The current position of the platofrm - */ - NiPoint3 mPosition {}; + /** + * The percentage of the way between the last point and the desired point + */ + float mPercentBetweenPoints = 0; - /** - * The waypoint the platform is (was) at - */ - uint32_t mCurrentWaypointIndex; + /** + * The current position of the platofrm + */ + NiPoint3 mPosition{}; - /** - * The waypoint the platform is attempting to go to - */ - uint32_t mNextWaypointIndex; + /** + * The waypoint the platform is (was) at + */ + uint32_t mCurrentWaypointIndex; - /** - * The timer that handles the time before stopping idling and continue platform movement - */ - float mIdleTimeElapsed = 0; + /** + * The waypoint the platform is attempting to go to + */ + uint32_t mNextWaypointIndex; - /** - * The speed the platform is currently moving at - */ - float mSpeed = 0; + /** + * The timer that handles the time before stopping idling and continue platform movement + */ + float mIdleTimeElapsed = 0; - /** - * The time to wait before continuing movement - */ - float mWaitTime = 0; + /** + * The speed the platform is currently moving at + */ + float mSpeed = 0; + + /** + * The time to wait before continuing movement + */ + float mWaitTime = 0; }; @@ -112,123 +112,123 @@ public: */ class MovingPlatformComponent : public Component { public: - static const uint32_t ComponentType = COMPONENT_TYPE_MOVING_PLATFORM; - - MovingPlatformComponent(Entity* parent, const std::string& pathName); - ~MovingPlatformComponent() override; - - void Serialize(RakNet::BitStream* outBitStream, bool bIsInitialUpdate, unsigned int& flags); + static const uint32_t ComponentType = COMPONENT_TYPE_MOVING_PLATFORM; - /** - * Stops all pathing, called when an entity starts a quick build associated with this platform - */ - void OnRebuildInitilized(); + MovingPlatformComponent(Entity* parent, const std::string& pathName); + ~MovingPlatformComponent() override; - /** - * Starts the pathing, called when an entity completed a quick build associated with this platform - */ - void OnCompleteRebuild(); + void Serialize(RakNet::BitStream* outBitStream, bool bIsInitialUpdate, unsigned int& flags); - /** - * Updates the movement state for the moving platform - * @param value the movement state to set - */ - void SetMovementState(MovementPlatformState value); + /** + * Stops all pathing, called when an entity starts a quick build associated with this platform + */ + void OnRebuildInitilized(); - /** - * Instructs the moving platform to go to some waypoint - * @param index the index of the waypoint - * @param stopAtWaypoint determines if the platform should stop at the waypoint - */ - void GotoWaypoint(uint32_t index, bool stopAtWaypoint = true); + /** + * Starts the pathing, called when an entity completed a quick build associated with this platform + */ + void OnCompleteRebuild(); - /** - * Starts the pathing of this platform, setting appropriate waypoints and speeds - */ - void StartPathing(); + /** + * Updates the movement state for the moving platform + * @param value the movement state to set + */ + void SetMovementState(MovementPlatformState value); - /** - * Continues the path of the platform, after it's been stopped - */ - void ContinuePathing(); + /** + * Instructs the moving platform to go to some waypoint + * @param index the index of the waypoint + * @param stopAtWaypoint determines if the platform should stop at the waypoint + */ + void GotoWaypoint(uint32_t index, bool stopAtWaypoint = true); - /** - * Stops the platform from moving, waiting for it to be activated again. - */ - void StopPathing(); + /** + * Starts the pathing of this platform, setting appropriate waypoints and speeds + */ + void StartPathing(); - /** - * Determines if the entity should be serialized on the next update - * @param value whether to serialize the entity or not - */ - void SetSerialized(bool value); + /** + * Continues the path of the platform, after it's been stopped + */ + void ContinuePathing(); - /** - * Returns if this platform will start automatically after spawn - * @return if this platform will start automatically after spawn - */ - bool GetNoAutoStart() const; + /** + * Stops the platform from moving, waiting for it to be activated again. + */ + void StopPathing(); - /** - * Sets the auto start value for this platform - * @param value the auto start value to set - */ - void SetNoAutoStart(bool value); + /** + * Determines if the entity should be serialized on the next update + * @param value whether to serialize the entity or not + */ + void SetSerialized(bool value); - /** - * Warps the platform to a waypoint index, skipping its current path - * @param index the index to go to - */ - void WarpToWaypoint(size_t index); + /** + * Returns if this platform will start automatically after spawn + * @return if this platform will start automatically after spawn + */ + bool GetNoAutoStart() const; - /** - * Returns the waypoint this platform was previously at - * @return the waypoint this platform was previously at - */ - size_t GetLastWaypointIndex() const; + /** + * Sets the auto start value for this platform + * @param value the auto start value to set + */ + void SetNoAutoStart(bool value); + + /** + * Warps the platform to a waypoint index, skipping its current path + * @param index the index to go to + */ + void WarpToWaypoint(size_t index); + + /** + * Returns the waypoint this platform was previously at + * @return the waypoint this platform was previously at + */ + size_t GetLastWaypointIndex() const; + + /** + * Returns the sub component that actually defines how the platform moves around (speeds, etc). + * @return the sub component that actually defines how the platform moves around + */ + MoverSubComponent* GetMoverSubComponent() const; - /** - * Returns the sub component that actually defines how the platform moves around (speeds, etc). - * @return the sub component that actually defines how the platform moves around - */ - MoverSubComponent* GetMoverSubComponent() const; - private: - /** - * The path this platform is currently on - */ - const Path* m_Path = nullptr; + /** + * The path this platform is currently on + */ + const Path* m_Path = nullptr; - /** - * The name of the path this platform is currently on - */ - std::u16string m_PathName; + /** + * The name of the path this platform is currently on + */ + std::u16string m_PathName; - /** - * Whether the platform has stopped pathing - */ - bool m_PathingStopped = false; + /** + * Whether the platform has stopped pathing + */ + bool m_PathingStopped = false; - /** - * The type of the subcomponent - */ - eMoverSubComponentType m_MoverSubComponentType; + /** + * The type of the subcomponent + */ + eMoverSubComponentType m_MoverSubComponentType; - /** - * The mover sub component that belongs to this platform - */ - void* m_MoverSubComponent; + /** + * The mover sub component that belongs to this platform + */ + void* m_MoverSubComponent; - /** - * Whether the platform shouldn't auto start - */ - bool m_NoAutoStart; + /** + * Whether the platform shouldn't auto start + */ + bool m_NoAutoStart; - /** - * Whether to serialize the entity on the next update - */ - bool m_Serialize = false; + /** + * Whether to serialize the entity on the next update + */ + bool m_Serialize = false; }; #endif // MOVINGPLATFORMCOMPONENT_H diff --git a/dGame/dComponents/PetComponent.cpp b/dGame/dComponents/PetComponent.cpp index 0151fbf4..42aceaf3 100644 --- a/dGame/dComponents/PetComponent.cpp +++ b/dGame/dComponents/PetComponent.cpp @@ -20,860 +20,783 @@ #include "dChatFilter.h" #include "Database.h" -std::unordered_map PetComponent::buildCache {}; -std::unordered_map PetComponent::currentActivities {}; -std::unordered_map PetComponent::activePets {}; +std::unordered_map PetComponent::buildCache{}; +std::unordered_map PetComponent::currentActivities{}; +std::unordered_map PetComponent::activePets{}; /** * Maps all the pet lots to a flag indicating that the player has caught it. All basic pets have been guessed by ObjID * while the faction ones could be checked using their respective missions. */ std::map PetComponent::petFlags = { - { 3050, 801 }, // Elephant - { 3054, 803 }, // Cat - { 3195, 806 }, // Triceratops - { 3254, 807 }, // Terrier - { 3261, 811 }, // Skunk - { 3672, 813 }, // Bunny - { 3994, 814 }, // Crocodile - { 5635, 815 }, // Doberman - { 5636, 816 }, // Buffalo - { 5637, 818 }, // Robot Dog - { 5639, 819 }, // Red Dragon - { 5640, 820 }, // Tortoise - { 5641, 821 }, // Green Dragon - { 5643, 822 }, // Panda, see mission 786 - { 5642, 823 }, // Mantis - { 6720, 824 }, // Warthog - { 3520, 825 }, // Lion, see mission 1318 - { 7638, 826 }, // Goat - { 7694, 827 }, // Crab - { 12294, 829 }, // Reindeer - { 12431, 830 }, // Stegosaurus, see mission 1386 - { 12432, 831 }, // Saber cat, see mission 1389 - { 12433, 832 }, // Gryphon, see mission 1392 - { 12434, 833 }, // Alien, see mission 1188 - // 834: unknown?, see mission 506, 688 - { 16210, 836 }, // Ninjago Earth Dragon, see mission 1836 - { 13067, 838 }, // Skeleton dragon + { 3050, 801 }, // Elephant + { 3054, 803 }, // Cat + { 3195, 806 }, // Triceratops + { 3254, 807 }, // Terrier + { 3261, 811 }, // Skunk + { 3672, 813 }, // Bunny + { 3994, 814 }, // Crocodile + { 5635, 815 }, // Doberman + { 5636, 816 }, // Buffalo + { 5637, 818 }, // Robot Dog + { 5639, 819 }, // Red Dragon + { 5640, 820 }, // Tortoise + { 5641, 821 }, // Green Dragon + { 5643, 822 }, // Panda, see mission 786 + { 5642, 823 }, // Mantis + { 6720, 824 }, // Warthog + { 3520, 825 }, // Lion, see mission 1318 + { 7638, 826 }, // Goat + { 7694, 827 }, // Crab + { 12294, 829 }, // Reindeer + { 12431, 830 }, // Stegosaurus, see mission 1386 + { 12432, 831 }, // Saber cat, see mission 1389 + { 12433, 832 }, // Gryphon, see mission 1392 + { 12434, 833 }, // Alien, see mission 1188 + // 834: unknown?, see mission 506, 688 + { 16210, 836 }, // Ninjago Earth Dragon, see mission 1836 + { 13067, 838 }, // Skeleton dragon }; -PetComponent::PetComponent(Entity* parent, uint32_t componentId) : Component(parent) -{ - m_ComponentId = componentId; +PetComponent::PetComponent(Entity* parent, uint32_t componentId) : Component(parent) { + m_ComponentId = componentId; - m_Interaction = LWOOBJID_EMPTY; - m_Owner = LWOOBJID_EMPTY; - m_ModerationStatus = 0; - m_Tamer = LWOOBJID_EMPTY; - m_ModelId = LWOOBJID_EMPTY; - m_Timer = 0; - m_TimerAway = 0; - m_DatabaseId = LWOOBJID_EMPTY; - m_Status = 67108866; // Tamable - m_Ability = PetAbilityType::Invalid; - m_StartPosition = NiPoint3::ZERO; - m_MovementAI = nullptr; - m_TresureTime = 0; - m_Preconditions = nullptr; + m_Interaction = LWOOBJID_EMPTY; + m_Owner = LWOOBJID_EMPTY; + m_ModerationStatus = 0; + m_Tamer = LWOOBJID_EMPTY; + m_ModelId = LWOOBJID_EMPTY; + m_Timer = 0; + m_TimerAway = 0; + m_DatabaseId = LWOOBJID_EMPTY; + m_Status = 67108866; // Tamable + m_Ability = PetAbilityType::Invalid; + m_StartPosition = NiPoint3::ZERO; + m_MovementAI = nullptr; + m_TresureTime = 0; + m_Preconditions = nullptr; std::string checkPreconditions = GeneralUtils::UTF16ToWTF8(parent->GetVar(u"CheckPrecondition")); if (!checkPreconditions.empty()) { SetPreconditions(checkPreconditions); } - // Get the imagination drain rate from the CDClient - auto query = CDClientDatabase::CreatePreppedStmt("SELECT imaginationDrainRate FROM PetComponent WHERE id = ?;"); + // Get the imagination drain rate from the CDClient + auto query = CDClientDatabase::CreatePreppedStmt("SELECT imaginationDrainRate FROM PetComponent WHERE id = ?;"); - query.bind(1, static_cast(componentId)); + query.bind(1, static_cast(componentId)); - auto result = query.execQuery(); + auto result = query.execQuery(); - // Should a result not exist for this pet default to 60 seconds. - if (!result.eof() && !result.fieldIsNull(0)) { - imaginationDrainRate = result.getFloatField(0, 60.0f); - } else { - imaginationDrainRate = 60.0f; - } - result.finalize(); + // Should a result not exist for this pet default to 60 seconds. + if (!result.eof() && !result.fieldIsNull(0)) { + imaginationDrainRate = result.getFloatField(0, 60.0f); + } else { + imaginationDrainRate = 60.0f; + } + result.finalize(); } -void PetComponent::Serialize(RakNet::BitStream* outBitStream, bool bIsInitialUpdate, unsigned int& flags) -{ - const bool tamed = m_Owner != LWOOBJID_EMPTY; +void PetComponent::Serialize(RakNet::BitStream* outBitStream, bool bIsInitialUpdate, unsigned int& flags) { + const bool tamed = m_Owner != LWOOBJID_EMPTY; - outBitStream->Write1(); // Always serialize as dirty for now + outBitStream->Write1(); // Always serialize as dirty for now - outBitStream->Write(static_cast(m_Status)); - outBitStream->Write(static_cast(tamed ? m_Ability : PetAbilityType::Invalid)); // Something with the overhead icon? + outBitStream->Write(static_cast(m_Status)); + outBitStream->Write(static_cast(tamed ? m_Ability : PetAbilityType::Invalid)); // Something with the overhead icon? - const bool interacting = m_Interaction != LWOOBJID_EMPTY; + const bool interacting = m_Interaction != LWOOBJID_EMPTY; - outBitStream->Write(interacting); - if (interacting) - { - outBitStream->Write(m_Interaction); - } + outBitStream->Write(interacting); + if (interacting) { + outBitStream->Write(m_Interaction); + } - outBitStream->Write(tamed); - if (tamed) - { - outBitStream->Write(m_Owner); - } + outBitStream->Write(tamed); + if (tamed) { + outBitStream->Write(m_Owner); + } - outBitStream->Write(tamed); - if (tamed) - { - outBitStream->Write(m_ModerationStatus); + outBitStream->Write(tamed); + if (tamed) { + outBitStream->Write(m_ModerationStatus); - const auto nameData = GeneralUtils::ASCIIToUTF16(m_Name); - const auto ownerNameData = GeneralUtils::ASCIIToUTF16(m_OwnerName); + const auto nameData = GeneralUtils::ASCIIToUTF16(m_Name); + const auto ownerNameData = GeneralUtils::ASCIIToUTF16(m_OwnerName); - outBitStream->Write(static_cast(nameData.size())); - for (const auto c : nameData) - { - outBitStream->Write(c); - } + outBitStream->Write(static_cast(nameData.size())); + for (const auto c : nameData) { + outBitStream->Write(c); + } - outBitStream->Write(static_cast(ownerNameData.size())); - for (const auto c : ownerNameData) - { - outBitStream->Write(c); - } - } + outBitStream->Write(static_cast(ownerNameData.size())); + for (const auto c : ownerNameData) { + outBitStream->Write(c); + } + } } -void PetComponent::OnUse(Entity* originator) -{ - if (m_Owner != LWOOBJID_EMPTY) - { - return; - } +void PetComponent::OnUse(Entity* originator) { + if (m_Owner != LWOOBJID_EMPTY) { + return; + } - if (m_Tamer != LWOOBJID_EMPTY) - { - auto* tamer = EntityManager::Instance()->GetEntity(m_Tamer); + if (m_Tamer != LWOOBJID_EMPTY) { + auto* tamer = EntityManager::Instance()->GetEntity(m_Tamer); - if (tamer != nullptr) - { - return; - } + if (tamer != nullptr) { + return; + } - m_Tamer = LWOOBJID_EMPTY; - } + m_Tamer = LWOOBJID_EMPTY; + } - auto* inventoryComponent = originator->GetComponent(); + auto* inventoryComponent = originator->GetComponent(); - if (inventoryComponent == nullptr) - { - return; - } + if (inventoryComponent == nullptr) { + return; + } - if (m_Preconditions != nullptr && !m_Preconditions->Check(originator, true)) { - return; - } + if (m_Preconditions != nullptr && !m_Preconditions->Check(originator, true)) { + return; + } - auto* movementAIComponent = m_Parent->GetComponent(); + auto* movementAIComponent = m_Parent->GetComponent(); - if (movementAIComponent != nullptr) - { - movementAIComponent->Stop(); - } + if (movementAIComponent != nullptr) { + movementAIComponent->Stop(); + } - inventoryComponent->DespawnPet(); + inventoryComponent->DespawnPet(); - const auto& cached = buildCache.find(m_Parent->GetLOT()); - int32_t imaginationCost = 0; + const auto& cached = buildCache.find(m_Parent->GetLOT()); + int32_t imaginationCost = 0; - std::string buildFile; + std::string buildFile; - if (cached == buildCache.end()) { - auto query = CDClientDatabase::CreatePreppedStmt( - "SELECT ValidPiecesLXF, PuzzleModelLot, Timelimit, NumValidPieces, imagCostPerBuild FROM TamingBuildPuzzles WHERE NPCLot = ?;"); - query.bind(1, (int) m_Parent->GetLOT()); + if (cached == buildCache.end()) { + auto query = CDClientDatabase::CreatePreppedStmt( + "SELECT ValidPiecesLXF, PuzzleModelLot, Timelimit, NumValidPieces, imagCostPerBuild FROM TamingBuildPuzzles WHERE NPCLot = ?;"); + query.bind(1, (int)m_Parent->GetLOT()); - auto result = query.execQuery(); + auto result = query.execQuery(); - if (result.eof()) - { - ChatPackets::SendSystemMessage(originator->GetSystemAddress(), u"Failed to find the puzzle minigame for this pet."); + if (result.eof()) { + ChatPackets::SendSystemMessage(originator->GetSystemAddress(), u"Failed to find the puzzle minigame for this pet."); - return; - } + return; + } - if (result.fieldIsNull(0)) - { - result.finalize(); + if (result.fieldIsNull(0)) { + result.finalize(); - return; - } + return; + } - auto lxfAsset = std::string(result.getStringField(0)); + auto lxfAsset = std::string(result.getStringField(0)); - std::vector lxfAssetSplit = GeneralUtils::SplitString(lxfAsset, '\\'); + std::vector lxfAssetSplit = GeneralUtils::SplitString(lxfAsset, '\\'); - lxfAssetSplit.erase(lxfAssetSplit.begin()); + lxfAssetSplit.erase(lxfAssetSplit.begin()); - buildFile = "res/BrickModels"; + buildFile = "res/BrickModels"; - for (auto part: lxfAssetSplit) - { - std::transform(part.begin(), part.end(), part.begin(), [](unsigned char c) { - return std::tolower(c); - }); + for (auto part : lxfAssetSplit) { + std::transform(part.begin(), part.end(), part.begin(), [](unsigned char c) { + return std::tolower(c); + }); - buildFile += "/" + part; - } + buildFile += "/" + part; + } - PetPuzzleData data; - data.buildFile = buildFile; - data.puzzleModelLot = result.getIntField(1); - data.timeLimit = result.getFloatField(2); - data.numValidPieces = result.getIntField(3); - data.imaginationCost = result.getIntField(4); - if (data.timeLimit <= 0) data.timeLimit = 60; - imaginationCost = data.imaginationCost; + PetPuzzleData data; + data.buildFile = buildFile; + data.puzzleModelLot = result.getIntField(1); + data.timeLimit = result.getFloatField(2); + data.numValidPieces = result.getIntField(3); + data.imaginationCost = result.getIntField(4); + if (data.timeLimit <= 0) data.timeLimit = 60; + imaginationCost = data.imaginationCost; - buildCache[m_Parent->GetLOT()] = data; + buildCache[m_Parent->GetLOT()] = data; - result.finalize(); - } - else - { - buildFile = cached->second.buildFile; - imaginationCost = cached->second.imaginationCost; - } + result.finalize(); + } else { + buildFile = cached->second.buildFile; + imaginationCost = cached->second.imaginationCost; + } - auto* destroyableComponent = originator->GetComponent(); + auto* destroyableComponent = originator->GetComponent(); - if (destroyableComponent == nullptr) - { - return; - } + if (destroyableComponent == nullptr) { + return; + } - auto imagination = destroyableComponent->GetImagination(); + auto imagination = destroyableComponent->GetImagination(); - if (imagination < imaginationCost) - { - return; - } + if (imagination < imaginationCost) { + return; + } - auto& bricks = BrickDatabase::Instance()->GetBricks(buildFile); + auto& bricks = BrickDatabase::Instance()->GetBricks(buildFile); - if (bricks.empty()) - { - ChatPackets::SendSystemMessage(originator->GetSystemAddress(), u"Failed to load the puzzle minigame for this pet."); - Game::logger->Log("PetComponent", "Couldn't find %s for minigame!", buildFile.c_str()); + if (bricks.empty()) { + ChatPackets::SendSystemMessage(originator->GetSystemAddress(), u"Failed to load the puzzle minigame for this pet."); + Game::logger->Log("PetComponent", "Couldn't find %s for minigame!", buildFile.c_str()); - return; - } + return; + } - auto petPosition = m_Parent->GetPosition(); + auto petPosition = m_Parent->GetPosition(); - auto originatorPosition = originator->GetPosition(); + auto originatorPosition = originator->GetPosition(); - m_Parent->SetRotation(NiQuaternion::LookAt(petPosition, originatorPosition)); + m_Parent->SetRotation(NiQuaternion::LookAt(petPosition, originatorPosition)); - float interactionDistance = m_Parent->GetVar(u"interaction_distance"); + float interactionDistance = m_Parent->GetVar(u"interaction_distance"); - if (interactionDistance <= 0) - { - interactionDistance = 15; - } + if (interactionDistance <= 0) { + interactionDistance = 15; + } - auto position = originatorPosition; + auto position = originatorPosition; - NiPoint3 forward = NiQuaternion::LookAt(m_Parent->GetPosition(), originator->GetPosition()).GetForwardVector(); - forward.y = 0; + NiPoint3 forward = NiQuaternion::LookAt(m_Parent->GetPosition(), originator->GetPosition()).GetForwardVector(); + forward.y = 0; - if (dpWorld::Instance().IsLoaded()) - { - NiPoint3 attempt = petPosition + forward * interactionDistance; + if (dpWorld::Instance().IsLoaded()) { + NiPoint3 attempt = petPosition + forward * interactionDistance; - float y = dpWorld::Instance().GetHeightAtPoint(attempt); + float y = dpWorld::Instance().GetHeightAtPoint(attempt); - while (std::abs(y - petPosition.y) > 4 && interactionDistance > 10) - { - const NiPoint3 forward = m_Parent->GetRotation().GetForwardVector(); + while (std::abs(y - petPosition.y) > 4 && interactionDistance > 10) { + const NiPoint3 forward = m_Parent->GetRotation().GetForwardVector(); - attempt = originatorPosition + forward * interactionDistance; + attempt = originatorPosition + forward * interactionDistance; - y = dpWorld::Instance().GetHeightAtPoint(attempt); + y = dpWorld::Instance().GetHeightAtPoint(attempt); - interactionDistance -= 0.5f; - } + interactionDistance -= 0.5f; + } - position = attempt; - } - else - { - position = petPosition + forward * interactionDistance; - } + position = attempt; + } else { + position = petPosition + forward * interactionDistance; + } - auto rotation = NiQuaternion::LookAt(position, petPosition); + auto rotation = NiQuaternion::LookAt(position, petPosition); - GameMessages::SendNotifyPetTamingMinigame( - originator->GetObjectID(), - m_Parent->GetObjectID(), - LWOOBJID_EMPTY, - true, - NOTIFY_TYPE_BEGIN, - petPosition, - position, - rotation, - UNASSIGNED_SYSTEM_ADDRESS - ); + GameMessages::SendNotifyPetTamingMinigame( + originator->GetObjectID(), + m_Parent->GetObjectID(), + LWOOBJID_EMPTY, + true, + NOTIFY_TYPE_BEGIN, + petPosition, + position, + rotation, + UNASSIGNED_SYSTEM_ADDRESS + ); - GameMessages::SendNotifyPetTamingMinigame( - m_Parent->GetObjectID(), - LWOOBJID_EMPTY, - originator->GetObjectID(), - true, - NOTIFY_TYPE_BEGIN, - petPosition, - position, - rotation, - UNASSIGNED_SYSTEM_ADDRESS - ); + GameMessages::SendNotifyPetTamingMinigame( + m_Parent->GetObjectID(), + LWOOBJID_EMPTY, + originator->GetObjectID(), + true, + NOTIFY_TYPE_BEGIN, + petPosition, + position, + rotation, + UNASSIGNED_SYSTEM_ADDRESS + ); - GameMessages::SendNotifyPetTamingPuzzleSelected(originator->GetObjectID(), bricks, originator->GetSystemAddress()); + GameMessages::SendNotifyPetTamingPuzzleSelected(originator->GetObjectID(), bricks, originator->GetSystemAddress()); - m_Tamer = originator->GetObjectID(); - SetStatus(5); + m_Tamer = originator->GetObjectID(); + SetStatus(5); - currentActivities.insert_or_assign(m_Tamer, m_Parent->GetObjectID()); + currentActivities.insert_or_assign(m_Tamer, m_Parent->GetObjectID()); - // Notify the start of a pet taming minigame - for (CppScripts::Script* script : CppScripts::GetEntityScripts(m_Parent)) { - script->OnNotifyPetTamingMinigame(m_Parent, originator, NOTIFY_TYPE_BEGIN); - } + // Notify the start of a pet taming minigame + for (CppScripts::Script* script : CppScripts::GetEntityScripts(m_Parent)) { + script->OnNotifyPetTamingMinigame(m_Parent, originator, NOTIFY_TYPE_BEGIN); + } } -void PetComponent::Update(float deltaTime) -{ - if (m_StartPosition == NiPoint3::ZERO) - { - m_StartPosition = m_Parent->GetPosition(); - } +void PetComponent::Update(float deltaTime) { + if (m_StartPosition == NiPoint3::ZERO) { + m_StartPosition = m_Parent->GetPosition(); + } - if (m_Owner == LWOOBJID_EMPTY) - { - if (m_Tamer != LWOOBJID_EMPTY) - { - if (m_Timer > 0) - { - m_Timer -= deltaTime; + if (m_Owner == LWOOBJID_EMPTY) { + if (m_Tamer != LWOOBJID_EMPTY) { + if (m_Timer > 0) { + m_Timer -= deltaTime; - if (m_Timer <= 0) - { - m_Timer = 0; + if (m_Timer <= 0) { + m_Timer = 0; - ClientFailTamingMinigame(); - } - } - } - else - { - if (m_Timer > 0) - { - m_Timer -= deltaTime; + ClientFailTamingMinigame(); + } + } + } else { + if (m_Timer > 0) { + m_Timer -= deltaTime; - if (m_Timer <= 0) - { - Wander(); - EntityManager::Instance()->SerializeEntity(m_Parent); - } - } - else - { - m_Timer = 5; - } - } + if (m_Timer <= 0) { + Wander(); + EntityManager::Instance()->SerializeEntity(m_Parent); + } + } else { + m_Timer = 5; + } + } - return; - } + return; + } - auto* owner = GetOwner(); + auto* owner = GetOwner(); - if (owner == nullptr) - { - m_Parent->Kill(); + if (owner == nullptr) { + m_Parent->Kill(); - return; - } + return; + } - m_MovementAI = m_Parent->GetComponent(); + m_MovementAI = m_Parent->GetComponent(); - if (m_MovementAI == nullptr) - { - return; - } + if (m_MovementAI == nullptr) { + return; + } - if (m_TresureTime > 0) - { - auto* tresure = EntityManager::Instance()->GetEntity(m_Interaction); + if (m_TresureTime > 0) { + auto* tresure = EntityManager::Instance()->GetEntity(m_Interaction); - if (tresure == nullptr) - { - m_TresureTime = 0; + if (tresure == nullptr) { + m_TresureTime = 0; - return; - } + return; + } - m_TresureTime -= deltaTime; + m_TresureTime -= deltaTime; - m_MovementAI->Stop(); + m_MovementAI->Stop(); - if (m_TresureTime <= 0) - { - m_Parent->SetOwnerOverride(m_Owner); + if (m_TresureTime <= 0) { + m_Parent->SetOwnerOverride(m_Owner); - tresure->Smash(m_Parent->GetObjectID()); + tresure->Smash(m_Parent->GetObjectID()); - m_Interaction = LWOOBJID_EMPTY; + m_Interaction = LWOOBJID_EMPTY; - m_TresureTime = 0; - } + m_TresureTime = 0; + } - return; - } + return; + } - auto destination = owner->GetPosition(); - NiPoint3 position = m_MovementAI->GetCurrentPosition(); + auto destination = owner->GetPosition(); + NiPoint3 position = m_MovementAI->GetCurrentPosition(); - float distanceToOwner = Vector3::DistanceSquared(position, destination); + float distanceToOwner = Vector3::DistanceSquared(position, destination); - if (distanceToOwner > 50 * 50 || m_TimerAway > 5) - { - m_MovementAI->Warp(destination); + if (distanceToOwner > 50 * 50 || m_TimerAway > 5) { + m_MovementAI->Warp(destination); - m_Timer = 1; - m_TimerAway = 0; + m_Timer = 1; + m_TimerAway = 0; - return; - } + return; + } - if (distanceToOwner > 15 * 15 || std::abs(destination.y - position.y) >= 3) - { - m_TimerAway += deltaTime; - } - else - { - m_TimerAway = 0; - } + if (distanceToOwner > 15 * 15 || std::abs(destination.y - position.y) >= 3) { + m_TimerAway += deltaTime; + } else { + m_TimerAway = 0; + } - if (m_Timer > 0) - { - m_Timer -= deltaTime; + if (m_Timer > 0) { + m_Timer -= deltaTime; - return; - } + return; + } - SwitchComponent* closestSwitch = SwitchComponent::GetClosestSwitch(position); + SwitchComponent* closestSwitch = SwitchComponent::GetClosestSwitch(position); - float haltDistance = 5; + float haltDistance = 5; - if (closestSwitch != nullptr) - { - if (!closestSwitch->GetActive()) - { - NiPoint3 switchPosition = closestSwitch->GetParentEntity()->GetPosition(); - float distance = Vector3::DistanceSquared(position, switchPosition); - if (distance < 3 * 3) - { - m_Interaction = closestSwitch->GetParentEntity()->GetObjectID(); - closestSwitch->EntityEnter(m_Parent); - } - else if (distance < 20 * 20) - { - haltDistance = 1; + if (closestSwitch != nullptr) { + if (!closestSwitch->GetActive()) { + NiPoint3 switchPosition = closestSwitch->GetParentEntity()->GetPosition(); + float distance = Vector3::DistanceSquared(position, switchPosition); + if (distance < 3 * 3) { + m_Interaction = closestSwitch->GetParentEntity()->GetObjectID(); + closestSwitch->EntityEnter(m_Parent); + } else if (distance < 20 * 20) { + haltDistance = 1; - destination = switchPosition; - } - } - } + destination = switchPosition; + } + } + } - Entity* closestTresure = PetDigServer::GetClosestTresure(position); + Entity* closestTresure = PetDigServer::GetClosestTresure(position); - if (closestTresure != nullptr) - { - // Skeleton Dragon Pat special case for bone digging - if (closestTresure->GetLOT() == 12192 && m_Parent->GetLOT() != 13067) - { - goto skipTresure; - } + if (closestTresure != nullptr) { + // Skeleton Dragon Pat special case for bone digging + if (closestTresure->GetLOT() == 12192 && m_Parent->GetLOT() != 13067) { + goto skipTresure; + } - NiPoint3 tresurePosition = closestTresure->GetPosition(); - float distance = Vector3::DistanceSquared(position, tresurePosition); - if (distance < 3 * 3) - { - m_Interaction = closestTresure->GetObjectID(); + NiPoint3 tresurePosition = closestTresure->GetPosition(); + float distance = Vector3::DistanceSquared(position, tresurePosition); + if (distance < 3 * 3) { + m_Interaction = closestTresure->GetObjectID(); - Command(NiPoint3::ZERO, LWOOBJID_EMPTY, 1, 202, true); + Command(NiPoint3::ZERO, LWOOBJID_EMPTY, 1, 202, true); - m_TresureTime = 2; - } - else if (distance < 10 * 10) - { - haltDistance = 1; + m_TresureTime = 2; + } else if (distance < 10 * 10) { + haltDistance = 1; - destination = tresurePosition; - } - } + destination = tresurePosition; + } + } - skipTresure: +skipTresure: - m_MovementAI->SetHaltDistance(haltDistance); + m_MovementAI->SetHaltDistance(haltDistance); - m_MovementAI->SetSpeed(2.5f); + m_MovementAI->SetSpeed(2.5f); - m_MovementAI->SetDestination(destination); + m_MovementAI->SetDestination(destination); - m_Timer = 1; + m_Timer = 1; } void PetComponent::TryBuild(uint32_t numBricks, bool clientFailed) { - if (m_Tamer == LWOOBJID_EMPTY) return; + if (m_Tamer == LWOOBJID_EMPTY) return; - auto* tamer = EntityManager::Instance()->GetEntity(m_Tamer); + auto* tamer = EntityManager::Instance()->GetEntity(m_Tamer); - if (tamer == nullptr) { - m_Tamer = LWOOBJID_EMPTY; + if (tamer == nullptr) { + m_Tamer = LWOOBJID_EMPTY; - return; - } + return; + } - const auto& cached = buildCache.find(m_Parent->GetLOT()); + const auto& cached = buildCache.find(m_Parent->GetLOT()); - if (cached == buildCache.end()) return; + if (cached == buildCache.end()) return; - auto* destroyableComponent = tamer->GetComponent(); + auto* destroyableComponent = tamer->GetComponent(); - if (destroyableComponent == nullptr) return; + if (destroyableComponent == nullptr) return; - auto imagination = destroyableComponent->GetImagination(); + auto imagination = destroyableComponent->GetImagination(); - imagination -= cached->second.imaginationCost; + imagination -= cached->second.imaginationCost; - destroyableComponent->SetImagination(imagination); + destroyableComponent->SetImagination(imagination); - EntityManager::Instance()->SerializeEntity(tamer); + EntityManager::Instance()->SerializeEntity(tamer); - if (clientFailed) { - if (imagination < cached->second.imaginationCost) { - ClientFailTamingMinigame(); - } - } else { - m_Timer = 0; - } + if (clientFailed) { + if (imagination < cached->second.imaginationCost) { + ClientFailTamingMinigame(); + } + } else { + m_Timer = 0; + } - if (numBricks == 0) return; + if (numBricks == 0) return; - GameMessages::SendPetTamingTryBuildResult(m_Tamer, !clientFailed, numBricks, tamer->GetSystemAddress()); + GameMessages::SendPetTamingTryBuildResult(m_Tamer, !clientFailed, numBricks, tamer->GetSystemAddress()); } -void PetComponent::NotifyTamingBuildSuccess(NiPoint3 position) -{ - if (m_Tamer == LWOOBJID_EMPTY) return; +void PetComponent::NotifyTamingBuildSuccess(NiPoint3 position) { + if (m_Tamer == LWOOBJID_EMPTY) return; - auto* tamer = EntityManager::Instance()->GetEntity(m_Tamer); + auto* tamer = EntityManager::Instance()->GetEntity(m_Tamer); - if (tamer == nullptr) - { - m_Tamer = LWOOBJID_EMPTY; + if (tamer == nullptr) { + m_Tamer = LWOOBJID_EMPTY; - return; - } + return; + } - const auto& cached = buildCache.find(m_Parent->GetLOT()); + const auto& cached = buildCache.find(m_Parent->GetLOT()); - if (cached == buildCache.end()) - { - return; - } + if (cached == buildCache.end()) { + return; + } - GameMessages::SendPlayFXEffect(tamer, -1, u"petceleb", "", LWOOBJID_EMPTY, 1, 1, true); - GameMessages::SendPlayAnimation(tamer, u"rebuild-celebrate"); + GameMessages::SendPlayFXEffect(tamer, -1, u"petceleb", "", LWOOBJID_EMPTY, 1, 1, true); + GameMessages::SendPlayAnimation(tamer, u"rebuild-celebrate"); - EntityInfo info {}; - info.lot = cached->second.puzzleModelLot; - info.pos = position; - info.rot = NiQuaternion::IDENTITY; - info.spawnerID = tamer->GetObjectID(); + EntityInfo info{}; + info.lot = cached->second.puzzleModelLot; + info.pos = position; + info.rot = NiQuaternion::IDENTITY; + info.spawnerID = tamer->GetObjectID(); - auto* modelEntity = EntityManager::Instance()->CreateEntity(info); + auto* modelEntity = EntityManager::Instance()->CreateEntity(info); - m_ModelId = modelEntity->GetObjectID(); + m_ModelId = modelEntity->GetObjectID(); - EntityManager::Instance()->ConstructEntity(modelEntity); + EntityManager::Instance()->ConstructEntity(modelEntity); - GameMessages::SendNotifyTamingModelLoadedOnServer(m_Tamer, tamer->GetSystemAddress()); + GameMessages::SendNotifyTamingModelLoadedOnServer(m_Tamer, tamer->GetSystemAddress()); - GameMessages::SendPetResponse(m_Tamer, m_Parent->GetObjectID(), 0, 10, 0, tamer->GetSystemAddress()); + GameMessages::SendPetResponse(m_Tamer, m_Parent->GetObjectID(), 0, 10, 0, tamer->GetSystemAddress()); - auto* inventoryComponent = tamer->GetComponent(); + auto* inventoryComponent = tamer->GetComponent(); - if (inventoryComponent == nullptr) - { - return; - } + if (inventoryComponent == nullptr) { + return; + } - LWOOBJID petSubKey = ObjectIDManager::Instance()->GenerateRandomObjectID(); + LWOOBJID petSubKey = ObjectIDManager::Instance()->GenerateRandomObjectID(); petSubKey = GeneralUtils::SetBit(petSubKey, OBJECT_BIT_CHARACTER); petSubKey = GeneralUtils::SetBit(petSubKey, OBJECT_BIT_PERSISTENT); - m_DatabaseId = petSubKey; + m_DatabaseId = petSubKey; - std::string petName = tamer->GetCharacter()->GetName(); - petName += "'s Pet"; + std::string petName = tamer->GetCharacter()->GetName(); + petName += "'s Pet"; - GameMessages::SendAddPetToPlayer(m_Tamer, 0, GeneralUtils::ASCIIToUTF16(petName), petSubKey, m_Parent->GetLOT(), tamer->GetSystemAddress()); + GameMessages::SendAddPetToPlayer(m_Tamer, 0, GeneralUtils::ASCIIToUTF16(petName), petSubKey, m_Parent->GetLOT(), tamer->GetSystemAddress()); - GameMessages::SendRegisterPetID(m_Tamer, m_Parent->GetObjectID(), tamer->GetSystemAddress()); + GameMessages::SendRegisterPetID(m_Tamer, m_Parent->GetObjectID(), tamer->GetSystemAddress()); - GameMessages::SendRegisterPetDBID(m_Tamer, petSubKey, tamer->GetSystemAddress()); + GameMessages::SendRegisterPetDBID(m_Tamer, petSubKey, tamer->GetSystemAddress()); - inventoryComponent->AddItem(m_Parent->GetLOT(), 1, eLootSourceType::LOOT_SOURCE_ACTIVITY, eInventoryType::MODELS, {}, LWOOBJID_EMPTY, true, false, petSubKey); - auto* item = inventoryComponent->FindItemBySubKey(petSubKey, MODELS); + inventoryComponent->AddItem(m_Parent->GetLOT(), 1, eLootSourceType::LOOT_SOURCE_ACTIVITY, eInventoryType::MODELS, {}, LWOOBJID_EMPTY, true, false, petSubKey); + auto* item = inventoryComponent->FindItemBySubKey(petSubKey, MODELS); - if (item == nullptr) - { - return; - } + if (item == nullptr) { + return; + } - DatabasePet databasePet {}; + DatabasePet databasePet{}; - databasePet.lot = m_Parent->GetLOT(); - databasePet.moderationState = 1; - databasePet.name = petName; + databasePet.lot = m_Parent->GetLOT(); + databasePet.moderationState = 1; + databasePet.name = petName; - inventoryComponent->SetDatabasePet(petSubKey, databasePet); + inventoryComponent->SetDatabasePet(petSubKey, databasePet); - Activate(item, false, true); + Activate(item, false, true); - m_Timer = 0; + m_Timer = 0; - GameMessages::SendNotifyPetTamingMinigame( - m_Tamer, - LWOOBJID_EMPTY, - LWOOBJID_EMPTY, - false, - NOTIFY_TYPE_NAMINGPET, - NiPoint3::ZERO, - NiPoint3::ZERO, - NiQuaternion::IDENTITY, - UNASSIGNED_SYSTEM_ADDRESS - ); + GameMessages::SendNotifyPetTamingMinigame( + m_Tamer, + LWOOBJID_EMPTY, + LWOOBJID_EMPTY, + false, + NOTIFY_TYPE_NAMINGPET, + NiPoint3::ZERO, + NiPoint3::ZERO, + NiQuaternion::IDENTITY, + UNASSIGNED_SYSTEM_ADDRESS + ); - // Triggers the catch a pet missions - if (petFlags.find(m_Parent->GetLOT()) != petFlags.end()) { - tamer->GetCharacter()->SetPlayerFlag(petFlags.at(m_Parent->GetLOT()), true); - } + // Triggers the catch a pet missions + if (petFlags.find(m_Parent->GetLOT()) != petFlags.end()) { + tamer->GetCharacter()->SetPlayerFlag(petFlags.at(m_Parent->GetLOT()), true); + } - auto* missionComponent = tamer->GetComponent(); + auto* missionComponent = tamer->GetComponent(); - if (missionComponent != nullptr) - { - missionComponent->Progress(MissionTaskType::MISSION_TASK_TYPE_PET_TAMING, m_Parent->GetLOT()); - } + if (missionComponent != nullptr) { + missionComponent->Progress(MissionTaskType::MISSION_TASK_TYPE_PET_TAMING, m_Parent->GetLOT()); + } - SetStatus(1); + SetStatus(1); - auto* characterComponent = tamer->GetComponent(); - if (characterComponent != nullptr) { - characterComponent->UpdatePlayerStatistic(PetsTamed); - } + auto* characterComponent = tamer->GetComponent(); + if (characterComponent != nullptr) { + characterComponent->UpdatePlayerStatistic(PetsTamed); + } } -void PetComponent::RequestSetPetName(std::u16string name) -{ - if (m_Tamer == LWOOBJID_EMPTY) - { - if (m_Owner != LWOOBJID_EMPTY) - { - auto* owner = GetOwner(); +void PetComponent::RequestSetPetName(std::u16string name) { + if (m_Tamer == LWOOBJID_EMPTY) { + if (m_Owner != LWOOBJID_EMPTY) { + auto* owner = GetOwner(); - m_ModerationStatus = 1; // Pending - m_Name = ""; + m_ModerationStatus = 1; // Pending + m_Name = ""; - //Save our pet's new name to the db: - SetPetNameForModeration(GeneralUtils::UTF16ToWTF8(name)); + //Save our pet's new name to the db: + SetPetNameForModeration(GeneralUtils::UTF16ToWTF8(name)); - GameMessages::SendSetPetName(m_Owner, GeneralUtils::ASCIIToUTF16(m_Name), m_DatabaseId, owner->GetSystemAddress()); - GameMessages::SendSetPetNameModerated(m_Owner, m_DatabaseId, m_ModerationStatus, owner->GetSystemAddress()); - } + GameMessages::SendSetPetName(m_Owner, GeneralUtils::ASCIIToUTF16(m_Name), m_DatabaseId, owner->GetSystemAddress()); + GameMessages::SendSetPetNameModerated(m_Owner, m_DatabaseId, m_ModerationStatus, owner->GetSystemAddress()); + } - return; - } + return; + } - auto* tamer = EntityManager::Instance()->GetEntity(m_Tamer); + auto* tamer = EntityManager::Instance()->GetEntity(m_Tamer); - if (tamer == nullptr) - { - m_Tamer = LWOOBJID_EMPTY; + if (tamer == nullptr) { + m_Tamer = LWOOBJID_EMPTY; - return; - } + return; + } - Game::logger->Log("PetComponent", "Got set pet name (%s)", GeneralUtils::UTF16ToWTF8(name).c_str()); + Game::logger->Log("PetComponent", "Got set pet name (%s)", GeneralUtils::UTF16ToWTF8(name).c_str()); - auto* inventoryComponent = tamer->GetComponent(); + auto* inventoryComponent = tamer->GetComponent(); - if (inventoryComponent == nullptr) - { - return; - } + if (inventoryComponent == nullptr) { + return; + } - m_ModerationStatus = 1; // Pending - m_Name = ""; + m_ModerationStatus = 1; // Pending + m_Name = ""; - //Save our pet's new name to the db: - SetPetNameForModeration(GeneralUtils::UTF16ToWTF8(name)); + //Save our pet's new name to the db: + SetPetNameForModeration(GeneralUtils::UTF16ToWTF8(name)); - EntityManager::Instance()->SerializeEntity(m_Parent); + EntityManager::Instance()->SerializeEntity(m_Parent); - GameMessages::SendSetPetName(m_Tamer, GeneralUtils::ASCIIToUTF16(m_Name), m_DatabaseId, tamer->GetSystemAddress()); - GameMessages::SendSetPetName(m_Tamer, GeneralUtils::ASCIIToUTF16(m_Name), LWOOBJID_EMPTY, tamer->GetSystemAddress()); - GameMessages::SendPetNameChanged(m_Parent->GetObjectID(), m_ModerationStatus, GeneralUtils::ASCIIToUTF16(m_Name), GeneralUtils::ASCIIToUTF16(m_OwnerName), UNASSIGNED_SYSTEM_ADDRESS); - GameMessages::SendSetPetNameModerated(m_Tamer, m_DatabaseId, m_ModerationStatus, tamer->GetSystemAddress()); + GameMessages::SendSetPetName(m_Tamer, GeneralUtils::ASCIIToUTF16(m_Name), m_DatabaseId, tamer->GetSystemAddress()); + GameMessages::SendSetPetName(m_Tamer, GeneralUtils::ASCIIToUTF16(m_Name), LWOOBJID_EMPTY, tamer->GetSystemAddress()); + GameMessages::SendPetNameChanged(m_Parent->GetObjectID(), m_ModerationStatus, GeneralUtils::ASCIIToUTF16(m_Name), GeneralUtils::ASCIIToUTF16(m_OwnerName), UNASSIGNED_SYSTEM_ADDRESS); + GameMessages::SendSetPetNameModerated(m_Tamer, m_DatabaseId, m_ModerationStatus, tamer->GetSystemAddress()); - GameMessages::SendNotifyPetTamingMinigame( - m_Tamer, - m_Parent->GetObjectID(), - m_Tamer, - false, - NOTIFY_TYPE_SUCCESS, - NiPoint3::ZERO, - NiPoint3::ZERO, - NiQuaternion::IDENTITY, - UNASSIGNED_SYSTEM_ADDRESS - ); + GameMessages::SendNotifyPetTamingMinigame( + m_Tamer, + m_Parent->GetObjectID(), + m_Tamer, + false, + NOTIFY_TYPE_SUCCESS, + NiPoint3::ZERO, + NiPoint3::ZERO, + NiQuaternion::IDENTITY, + UNASSIGNED_SYSTEM_ADDRESS + ); - GameMessages::SendTerminateInteraction(m_Tamer, eTerminateType::FROM_INTERACTION, m_Parent->GetObjectID()); + GameMessages::SendTerminateInteraction(m_Tamer, eTerminateType::FROM_INTERACTION, m_Parent->GetObjectID()); - auto* modelEntity = EntityManager::Instance()->GetEntity(m_ModelId); + auto* modelEntity = EntityManager::Instance()->GetEntity(m_ModelId); - if (modelEntity != nullptr) - { - modelEntity->Smash(m_Tamer); - } + if (modelEntity != nullptr) { + modelEntity->Smash(m_Tamer); + } - currentActivities.erase(m_Tamer); + currentActivities.erase(m_Tamer); - m_Tamer = LWOOBJID_EMPTY; + m_Tamer = LWOOBJID_EMPTY; - // Notify the end of a pet taming minigame - for (CppScripts::Script* script : CppScripts::GetEntityScripts(m_Parent)) { - script->OnNotifyPetTamingMinigame(m_Parent, tamer, NOTIFY_TYPE_SUCCESS); - } + // Notify the end of a pet taming minigame + for (CppScripts::Script* script : CppScripts::GetEntityScripts(m_Parent)) { + script->OnNotifyPetTamingMinigame(m_Parent, tamer, NOTIFY_TYPE_SUCCESS); + } } -void PetComponent::ClientExitTamingMinigame(bool voluntaryExit) -{ - if (m_Tamer == LWOOBJID_EMPTY) return; +void PetComponent::ClientExitTamingMinigame(bool voluntaryExit) { + if (m_Tamer == LWOOBJID_EMPTY) return; - auto* tamer = EntityManager::Instance()->GetEntity(m_Tamer); + auto* tamer = EntityManager::Instance()->GetEntity(m_Tamer); - if (tamer == nullptr) - { - m_Tamer = LWOOBJID_EMPTY; + if (tamer == nullptr) { + m_Tamer = LWOOBJID_EMPTY; - return; - } + return; + } - GameMessages::SendNotifyPetTamingMinigame( - m_Tamer, - m_Parent->GetObjectID(), - m_Tamer, - false, - NOTIFY_TYPE_QUIT, - NiPoint3::ZERO, - NiPoint3::ZERO, - NiQuaternion::IDENTITY, - UNASSIGNED_SYSTEM_ADDRESS - ); + GameMessages::SendNotifyPetTamingMinigame( + m_Tamer, + m_Parent->GetObjectID(), + m_Tamer, + false, + NOTIFY_TYPE_QUIT, + NiPoint3::ZERO, + NiPoint3::ZERO, + NiQuaternion::IDENTITY, + UNASSIGNED_SYSTEM_ADDRESS + ); - GameMessages::SendNotifyTamingModelLoadedOnServer(m_Tamer, tamer->GetSystemAddress()); + GameMessages::SendNotifyTamingModelLoadedOnServer(m_Tamer, tamer->GetSystemAddress()); - GameMessages::SendTerminateInteraction(m_Tamer, eTerminateType::FROM_INTERACTION, m_Parent->GetObjectID()); + GameMessages::SendTerminateInteraction(m_Tamer, eTerminateType::FROM_INTERACTION, m_Parent->GetObjectID()); - currentActivities.erase(m_Tamer); + currentActivities.erase(m_Tamer); - SetStatus(67108866); - m_Tamer = LWOOBJID_EMPTY; - m_Timer = 0; + SetStatus(67108866); + m_Tamer = LWOOBJID_EMPTY; + m_Timer = 0; - EntityManager::Instance()->SerializeEntity(m_Parent); + EntityManager::Instance()->SerializeEntity(m_Parent); - // Notify the end of a pet taming minigame - for (CppScripts::Script* script : CppScripts::GetEntityScripts(m_Parent)) { - script->OnNotifyPetTamingMinigame(m_Parent, tamer, NOTIFY_TYPE_QUIT); - } + // Notify the end of a pet taming minigame + for (CppScripts::Script* script : CppScripts::GetEntityScripts(m_Parent)) { + script->OnNotifyPetTamingMinigame(m_Parent, tamer, NOTIFY_TYPE_QUIT); + } } -void PetComponent::StartTimer() -{ - const auto& cached = buildCache.find(m_Parent->GetLOT()); +void PetComponent::StartTimer() { + const auto& cached = buildCache.find(m_Parent->GetLOT()); - if (cached == buildCache.end()) - { - return; - } + if (cached == buildCache.end()) { + return; + } - m_Timer = cached->second.timeLimit; + m_Timer = cached->second.timeLimit; } -void PetComponent::ClientFailTamingMinigame() -{ - if (m_Tamer == LWOOBJID_EMPTY) return; +void PetComponent::ClientFailTamingMinigame() { + if (m_Tamer == LWOOBJID_EMPTY) return; - auto* tamer = EntityManager::Instance()->GetEntity(m_Tamer); + auto* tamer = EntityManager::Instance()->GetEntity(m_Tamer); - if (tamer == nullptr) - { - m_Tamer = LWOOBJID_EMPTY; + if (tamer == nullptr) { + m_Tamer = LWOOBJID_EMPTY; - return; - } + return; + } - GameMessages::SendNotifyPetTamingMinigame( - m_Tamer, - m_Parent->GetObjectID(), - m_Tamer, - false, - NOTIFY_TYPE_FAILED, - NiPoint3::ZERO, - NiPoint3::ZERO, - NiQuaternion::IDENTITY, - UNASSIGNED_SYSTEM_ADDRESS - ); + GameMessages::SendNotifyPetTamingMinigame( + m_Tamer, + m_Parent->GetObjectID(), + m_Tamer, + false, + NOTIFY_TYPE_FAILED, + NiPoint3::ZERO, + NiPoint3::ZERO, + NiQuaternion::IDENTITY, + UNASSIGNED_SYSTEM_ADDRESS + ); - GameMessages::SendNotifyTamingModelLoadedOnServer(m_Tamer, tamer->GetSystemAddress()); + GameMessages::SendNotifyTamingModelLoadedOnServer(m_Tamer, tamer->GetSystemAddress()); - GameMessages::SendTerminateInteraction(m_Tamer, eTerminateType::FROM_INTERACTION, m_Parent->GetObjectID()); + GameMessages::SendTerminateInteraction(m_Tamer, eTerminateType::FROM_INTERACTION, m_Parent->GetObjectID()); - currentActivities.erase(m_Tamer); + currentActivities.erase(m_Tamer); - SetStatus(67108866); - m_Tamer = LWOOBJID_EMPTY; - m_Timer = 0; + SetStatus(67108866); + m_Tamer = LWOOBJID_EMPTY; + m_Timer = 0; - EntityManager::Instance()->SerializeEntity(m_Parent); + EntityManager::Instance()->SerializeEntity(m_Parent); - // Notify the end of a pet taming minigame - for (CppScripts::Script* script : CppScripts::GetEntityScripts(m_Parent)) { - script->OnNotifyPetTamingMinigame(m_Parent, tamer, NOTIFY_TYPE_FAILED); - } + // Notify the end of a pet taming minigame + for (CppScripts::Script* script : CppScripts::GetEntityScripts(m_Parent)) { + script->OnNotifyPetTamingMinigame(m_Parent, tamer, NOTIFY_TYPE_FAILED); + } } -void PetComponent::Wander() -{ - m_MovementAI = m_Parent->GetComponent(); +void PetComponent::Wander() { + m_MovementAI = m_Parent->GetComponent(); - if (m_MovementAI == nullptr || !m_MovementAI->AtFinalWaypoint()) { - return; + if (m_MovementAI == nullptr || !m_MovementAI->AtFinalWaypoint()) { + return; } m_MovementAI->SetHaltDistance(0); @@ -912,325 +835,294 @@ void PetComponent::Wander() m_Timer += (m_MovementAI->GetCurrentPosition().x - destination.x) / info.wanderSpeed; } -void PetComponent::Activate(Item* item, bool registerPet, bool fromTaming) -{ - AddDrainImaginationTimer(item, fromTaming); +void PetComponent::Activate(Item* item, bool registerPet, bool fromTaming) { + AddDrainImaginationTimer(item, fromTaming); - m_ItemId = item->GetId(); - m_DatabaseId = item->GetSubKey(); + m_ItemId = item->GetId(); + m_DatabaseId = item->GetSubKey(); - auto* inventoryComponent = item->GetInventory()->GetComponent(); + auto* inventoryComponent = item->GetInventory()->GetComponent(); - if (inventoryComponent == nullptr) return; + if (inventoryComponent == nullptr) return; - inventoryComponent->DespawnPet(); + inventoryComponent->DespawnPet(); - m_Owner = inventoryComponent->GetParent()->GetObjectID(); + m_Owner = inventoryComponent->GetParent()->GetObjectID(); - auto* owner = GetOwner(); + auto* owner = GetOwner(); - if (owner == nullptr) return; - SetStatus(1); + if (owner == nullptr) return; + SetStatus(1); - auto databaseData = inventoryComponent->GetDatabasePet(m_DatabaseId); + auto databaseData = inventoryComponent->GetDatabasePet(m_DatabaseId); - m_ModerationStatus = databaseData.moderationState; + m_ModerationStatus = databaseData.moderationState; - bool updatedModerationStatus = false; + bool updatedModerationStatus = false; - //Load mod status from db: - if (m_ModerationStatus != 2) - { - LoadPetNameFromModeration(); + //Load mod status from db: + if (m_ModerationStatus != 2) { + LoadPetNameFromModeration(); - databaseData.name = m_Name; - databaseData.moderationState = m_ModerationStatus; + databaseData.name = m_Name; + databaseData.moderationState = m_ModerationStatus; - inventoryComponent->SetDatabasePet(m_DatabaseId, databaseData); + inventoryComponent->SetDatabasePet(m_DatabaseId, databaseData); - updatedModerationStatus = true; - } - else - { - m_Name = databaseData.name; - } + updatedModerationStatus = true; + } else { + m_Name = databaseData.name; + } - m_OwnerName = owner->GetCharacter()->GetName(); + m_OwnerName = owner->GetCharacter()->GetName(); - if (updatedModerationStatus) - { - GameMessages::SendSetPetName(m_Owner, GeneralUtils::ASCIIToUTF16(m_Name), m_DatabaseId, owner->GetSystemAddress()); - GameMessages::SendSetPetNameModerated(m_Owner, m_DatabaseId, m_ModerationStatus, owner->GetSystemAddress()); - } + if (updatedModerationStatus) { + GameMessages::SendSetPetName(m_Owner, GeneralUtils::ASCIIToUTF16(m_Name), m_DatabaseId, owner->GetSystemAddress()); + GameMessages::SendSetPetNameModerated(m_Owner, m_DatabaseId, m_ModerationStatus, owner->GetSystemAddress()); + } - GameMessages::SendMarkInventoryItemAsActive(m_Owner, true, 0, m_ItemId, GetOwner()->GetSystemAddress()); + GameMessages::SendMarkInventoryItemAsActive(m_Owner, true, 0, m_ItemId, GetOwner()->GetSystemAddress()); - activePets[m_Owner] = m_Parent->GetObjectID(); + activePets[m_Owner] = m_Parent->GetObjectID(); - m_Timer = 3; + m_Timer = 3; - EntityManager::Instance()->SerializeEntity(m_Parent); + EntityManager::Instance()->SerializeEntity(m_Parent); - owner->GetCharacter()->SetPlayerFlag(69, true); + owner->GetCharacter()->SetPlayerFlag(69, true); - if (registerPet) - { - GameMessages::SendAddPetToPlayer(m_Owner, 0, GeneralUtils::ASCIIToUTF16(m_Name), m_DatabaseId, m_Parent->GetLOT(), owner->GetSystemAddress()); + if (registerPet) { + GameMessages::SendAddPetToPlayer(m_Owner, 0, GeneralUtils::ASCIIToUTF16(m_Name), m_DatabaseId, m_Parent->GetLOT(), owner->GetSystemAddress()); - GameMessages::SendRegisterPetID(m_Owner, m_Parent->GetObjectID(), owner->GetSystemAddress()); + GameMessages::SendRegisterPetID(m_Owner, m_Parent->GetObjectID(), owner->GetSystemAddress()); - GameMessages::SendRegisterPetDBID(m_Owner, m_DatabaseId, owner->GetSystemAddress()); - } + GameMessages::SendRegisterPetDBID(m_Owner, m_DatabaseId, owner->GetSystemAddress()); + } - GameMessages::SendShowPetActionButton(m_Owner, 3, true, owner->GetSystemAddress()); + GameMessages::SendShowPetActionButton(m_Owner, 3, true, owner->GetSystemAddress()); } void PetComponent::AddDrainImaginationTimer(Item* item, bool fromTaming) { - if (Game::config->GetValue("pets_take_imagination") != "1") return; + if (Game::config->GetValue("pets_take_imagination") != "1") return; - auto playerInventory = item->GetInventory(); - if (!playerInventory) return; + auto playerInventory = item->GetInventory(); + if (!playerInventory) return; - auto playerInventoryComponent = playerInventory->GetComponent(); - if (!playerInventoryComponent) return; + auto playerInventoryComponent = playerInventory->GetComponent(); + if (!playerInventoryComponent) return; - auto playerEntity = playerInventoryComponent->GetParent(); - if (!playerEntity) return; + auto playerEntity = playerInventoryComponent->GetParent(); + if (!playerEntity) return; - auto playerDestroyableComponent = playerEntity->GetComponent(); - if (!playerDestroyableComponent) return; + auto playerDestroyableComponent = playerEntity->GetComponent(); + if (!playerDestroyableComponent) return; - // Drain by 1 when you summon pet or when this method is called, but not when we have just tamed this pet. - if (!fromTaming) playerDestroyableComponent->Imagine(-1); + // Drain by 1 when you summon pet or when this method is called, but not when we have just tamed this pet. + if (!fromTaming) playerDestroyableComponent->Imagine(-1); - // Set this to a variable so when this is called back from the player the timer doesn't fire off. - m_Parent->AddCallbackTimer(imaginationDrainRate, [playerDestroyableComponent, this, item](){ - if (!playerDestroyableComponent) { - Game::logger->Log("PetComponent", "No petComponent and/or no playerDestroyableComponent"); - return; - } + // Set this to a variable so when this is called back from the player the timer doesn't fire off. + m_Parent->AddCallbackTimer(imaginationDrainRate, [playerDestroyableComponent, this, item]() { + if (!playerDestroyableComponent) { + Game::logger->Log("PetComponent", "No petComponent and/or no playerDestroyableComponent"); + return; + } - // If we are out of imagination despawn the pet. - if (playerDestroyableComponent->GetImagination() == 0) { - this->Deactivate(); - auto playerEntity = playerDestroyableComponent->GetParent(); - if (!playerEntity) return; + // If we are out of imagination despawn the pet. + if (playerDestroyableComponent->GetImagination() == 0) { + this->Deactivate(); + auto playerEntity = playerDestroyableComponent->GetParent(); + if (!playerEntity) return; - GameMessages::SendUseItemRequirementsResponse(playerEntity->GetObjectID(), playerEntity->GetSystemAddress(), UseItemResponse::NoImaginationForPet); - } + GameMessages::SendUseItemRequirementsResponse(playerEntity->GetObjectID(), playerEntity->GetSystemAddress(), UseItemResponse::NoImaginationForPet); + } - this->AddDrainImaginationTimer(item); - }); + this->AddDrainImaginationTimer(item); + }); } -void PetComponent::Deactivate() -{ - GameMessages::SendPlayFXEffect(m_Parent->GetObjectID(), -1, u"despawn", "", LWOOBJID_EMPTY, 1, 1, true); +void PetComponent::Deactivate() { + GameMessages::SendPlayFXEffect(m_Parent->GetObjectID(), -1, u"despawn", "", LWOOBJID_EMPTY, 1, 1, true); - GameMessages::SendMarkInventoryItemAsActive(m_Owner, false, 0, m_ItemId, GetOwner()->GetSystemAddress()); + GameMessages::SendMarkInventoryItemAsActive(m_Owner, false, 0, m_ItemId, GetOwner()->GetSystemAddress()); - activePets.erase(m_Owner); + activePets.erase(m_Owner); - m_Parent->Kill(); + m_Parent->Kill(); - auto* owner = GetOwner(); + auto* owner = GetOwner(); - if (owner == nullptr) return; + if (owner == nullptr) return; - GameMessages::SendAddPetToPlayer(m_Owner, 0, u"", LWOOBJID_EMPTY, LOT_NULL, owner->GetSystemAddress()); + GameMessages::SendAddPetToPlayer(m_Owner, 0, u"", LWOOBJID_EMPTY, LOT_NULL, owner->GetSystemAddress()); - GameMessages::SendRegisterPetID(m_Owner, LWOOBJID_EMPTY, owner->GetSystemAddress()); + GameMessages::SendRegisterPetID(m_Owner, LWOOBJID_EMPTY, owner->GetSystemAddress()); - GameMessages::SendRegisterPetDBID(m_Owner, LWOOBJID_EMPTY, owner->GetSystemAddress()); + GameMessages::SendRegisterPetDBID(m_Owner, LWOOBJID_EMPTY, owner->GetSystemAddress()); - GameMessages::SendShowPetActionButton(m_Owner, 0, false, owner->GetSystemAddress()); + GameMessages::SendShowPetActionButton(m_Owner, 0, false, owner->GetSystemAddress()); } -void PetComponent::Release() -{ - auto* inventoryComponent = GetOwner()->GetComponent(); +void PetComponent::Release() { + auto* inventoryComponent = GetOwner()->GetComponent(); - if (inventoryComponent == nullptr) - { - return; - } + if (inventoryComponent == nullptr) { + return; + } - Deactivate(); + Deactivate(); - inventoryComponent->RemoveDatabasePet(m_DatabaseId); + inventoryComponent->RemoveDatabasePet(m_DatabaseId); - auto* item = inventoryComponent->FindItemBySubKey(m_DatabaseId); + auto* item = inventoryComponent->FindItemBySubKey(m_DatabaseId); - item->SetCount(0, false, false); + item->SetCount(0, false, false); } -void PetComponent::Command(NiPoint3 position, LWOOBJID source, int32_t commandType, int32_t typeId, bool overrideObey) -{ - auto* owner = GetOwner(); +void PetComponent::Command(NiPoint3 position, LWOOBJID source, int32_t commandType, int32_t typeId, bool overrideObey) { + auto* owner = GetOwner(); - if (owner == nullptr) - { - return; - } + if (owner == nullptr) { + return; + } - if (commandType == 1) { - // Emotes - GameMessages::SendPlayEmote(m_Parent->GetObjectID(), typeId, owner->GetObjectID(), UNASSIGNED_SYSTEM_ADDRESS); - } else if (commandType == 3) { - // Follow me, ??? - } else if (commandType == 6) { - // TODO: Go to player - } + if (commandType == 1) { + // Emotes + GameMessages::SendPlayEmote(m_Parent->GetObjectID(), typeId, owner->GetObjectID(), UNASSIGNED_SYSTEM_ADDRESS); + } else if (commandType == 3) { + // Follow me, ??? + } else if (commandType == 6) { + // TODO: Go to player + } - if (owner->GetGMLevel() >= GAME_MASTER_LEVEL_DEVELOPER) - { - ChatPackets::SendSystemMessage(owner->GetSystemAddress(), u"Commmand Type: " + (GeneralUtils::to_u16string(commandType)) + u" - Type Id: " + (GeneralUtils::to_u16string(typeId))); - } + if (owner->GetGMLevel() >= GAME_MASTER_LEVEL_DEVELOPER) { + ChatPackets::SendSystemMessage(owner->GetSystemAddress(), u"Commmand Type: " + (GeneralUtils::to_u16string(commandType)) + u" - Type Id: " + (GeneralUtils::to_u16string(typeId))); + } } -LWOOBJID PetComponent::GetOwnerId() const -{ - return m_Owner; +LWOOBJID PetComponent::GetOwnerId() const { + return m_Owner; } -Entity* PetComponent::GetOwner() const -{ - return EntityManager::Instance()->GetEntity(m_Owner); +Entity* PetComponent::GetOwner() const { + return EntityManager::Instance()->GetEntity(m_Owner); } -LWOOBJID PetComponent::GetDatabaseId() const -{ - return m_DatabaseId; +LWOOBJID PetComponent::GetDatabaseId() const { + return m_DatabaseId; } -LWOOBJID PetComponent::GetInteraction() const -{ - return m_Interaction; +LWOOBJID PetComponent::GetInteraction() const { + return m_Interaction; } -LWOOBJID PetComponent::GetItemId() const -{ - return m_ItemId; +LWOOBJID PetComponent::GetItemId() const { + return m_ItemId; } -uint32_t PetComponent::GetStatus() const -{ - return m_Status; +uint32_t PetComponent::GetStatus() const { + return m_Status; } -PetAbilityType PetComponent::GetAbility() const -{ - return m_Ability; +PetAbilityType PetComponent::GetAbility() const { + return m_Ability; } -void PetComponent::SetInteraction(LWOOBJID value) -{ - m_Interaction = value; +void PetComponent::SetInteraction(LWOOBJID value) { + m_Interaction = value; } -void PetComponent::SetStatus(uint32_t value) -{ - m_Status = value; +void PetComponent::SetStatus(uint32_t value) { + m_Status = value; } -void PetComponent::SetAbility(PetAbilityType value) -{ - m_Ability = value; +void PetComponent::SetAbility(PetAbilityType value) { + m_Ability = value; } -PetComponent* PetComponent::GetTamingPet(LWOOBJID tamer) -{ - const auto& pair = currentActivities.find(tamer); +PetComponent* PetComponent::GetTamingPet(LWOOBJID tamer) { + const auto& pair = currentActivities.find(tamer); - if (pair == currentActivities.end()) - { - return nullptr; - } + if (pair == currentActivities.end()) { + return nullptr; + } - auto* entity = EntityManager::Instance()->GetEntity(pair->second); + auto* entity = EntityManager::Instance()->GetEntity(pair->second); - if (entity == nullptr) - { - currentActivities.erase(tamer); + if (entity == nullptr) { + currentActivities.erase(tamer); - return nullptr; - } + return nullptr; + } - return entity->GetComponent(); + return entity->GetComponent(); } -PetComponent* PetComponent::GetActivePet(LWOOBJID owner) -{ - const auto& pair = activePets.find(owner); +PetComponent* PetComponent::GetActivePet(LWOOBJID owner) { + const auto& pair = activePets.find(owner); - if (pair == activePets.end()) - { - return nullptr; - } + if (pair == activePets.end()) { + return nullptr; + } - auto* entity = EntityManager::Instance()->GetEntity(pair->second); + auto* entity = EntityManager::Instance()->GetEntity(pair->second); - if (entity == nullptr) - { - activePets.erase(owner); + if (entity == nullptr) { + activePets.erase(owner); - return nullptr; - } + return nullptr; + } - return entity->GetComponent(); + return entity->GetComponent(); } -Entity* PetComponent::GetParentEntity() const -{ - return m_Parent; +Entity* PetComponent::GetParentEntity() const { + return m_Parent; } -PetComponent::~PetComponent() -{ +PetComponent::~PetComponent() { } void PetComponent::SetPetNameForModeration(const std::string& petName) { - int approved = 1; //default, in mod + int approved = 1; //default, in mod - //Make sure that the name isn't already auto-approved: - if (Game::chatFilter->IsSentenceOkay(petName, 0).empty()) { - approved = 2; //approved - } + //Make sure that the name isn't already auto-approved: + if (Game::chatFilter->IsSentenceOkay(petName, 0).empty()) { + approved = 2; //approved + } - auto deleteStmt = Database::CreatePreppedStmt("DELETE FROM pet_names WHERE id = ? LIMIT 1;"); - deleteStmt->setUInt64(1, m_DatabaseId); + auto deleteStmt = Database::CreatePreppedStmt("DELETE FROM pet_names WHERE id = ? LIMIT 1;"); + deleteStmt->setUInt64(1, m_DatabaseId); - deleteStmt->execute(); + deleteStmt->execute(); - delete deleteStmt; + delete deleteStmt; - //Save to db: - auto stmt = Database::CreatePreppedStmt("INSERT INTO `pet_names` (`id`, `pet_name`, `approved`) VALUES (?, ?, ?);"); - stmt->setUInt64(1, m_DatabaseId); - stmt->setString(2, petName); - stmt->setInt(3, approved); - stmt->execute(); - delete stmt; + //Save to db: + auto stmt = Database::CreatePreppedStmt("INSERT INTO `pet_names` (`id`, `pet_name`, `approved`) VALUES (?, ?, ?);"); + stmt->setUInt64(1, m_DatabaseId); + stmt->setString(2, petName); + stmt->setInt(3, approved); + stmt->execute(); + delete stmt; } void PetComponent::LoadPetNameFromModeration() { - auto stmt = Database::CreatePreppedStmt("SELECT pet_name, approved FROM pet_names WHERE id = ? LIMIT 1;"); - stmt->setUInt64(1, m_DatabaseId); + auto stmt = Database::CreatePreppedStmt("SELECT pet_name, approved FROM pet_names WHERE id = ? LIMIT 1;"); + stmt->setUInt64(1, m_DatabaseId); - auto res = stmt->executeQuery(); - while (res->next()) { - m_ModerationStatus = res->getInt(2); + auto res = stmt->executeQuery(); + while (res->next()) { + m_ModerationStatus = res->getInt(2); - if (m_ModerationStatus == 2) - { - m_Name = res->getString(1); - } - } + if (m_ModerationStatus == 2) { + m_Name = res->getString(1); + } + } - delete res; - delete stmt; + delete res; + delete stmt; } void PetComponent::SetPreconditions(std::string& preconditions) { - m_Preconditions = new PreconditionExpression(preconditions); + m_Preconditions = new PreconditionExpression(preconditions); } diff --git a/dGame/dComponents/PetComponent.h b/dGame/dComponents/PetComponent.h index 913cbc56..efde0e8a 100644 --- a/dGame/dComponents/PetComponent.h +++ b/dGame/dComponents/PetComponent.h @@ -7,10 +7,10 @@ enum class PetAbilityType { - Invalid, - GoToObject, - JumpOnObject, - DigAtPosition + Invalid, + GoToObject, + JumpOnObject, + DigAtPosition }; /** @@ -20,343 +20,343 @@ enum class PetAbilityType class PetComponent : public Component { public: - static const uint32_t ComponentType = COMPONENT_TYPE_PET; + static const uint32_t ComponentType = COMPONENT_TYPE_PET; - explicit PetComponent(Entity* parentEntity, uint32_t componentId); - ~PetComponent() override; + explicit PetComponent(Entity* parentEntity, uint32_t componentId); + ~PetComponent() override; - void Serialize(RakNet::BitStream* outBitStream, bool bIsInitialUpdate, unsigned int& flags); - void Update(float deltaTime) override; + void Serialize(RakNet::BitStream* outBitStream, bool bIsInitialUpdate, unsigned int& flags); + void Update(float deltaTime) override; - /** - * Handles an OnUse event from another entity, initializing the pet taming minigame if this pet is untamed. - * @param originator the entity that triggered the event - */ - void OnUse(Entity* originator) override; + /** + * Handles an OnUse event from another entity, initializing the pet taming minigame if this pet is untamed. + * @param originator the entity that triggered the event + */ + void OnUse(Entity* originator) override; - /** - * Attempts to complete the pet minigame by passing a list of bricks to build the minigame model. - * @param bricks the bricks to try to complete the minigame with - * @param clientFailed unused - */ - void TryBuild(uint32_t numBricks, bool clientFailed); + /** + * Attempts to complete the pet minigame by passing a list of bricks to build the minigame model. + * @param bricks the bricks to try to complete the minigame with + * @param clientFailed unused + */ + void TryBuild(uint32_t numBricks, bool clientFailed); - /** - * Handles a notification from the client regarding the completion of the pet minigame, adding the pet to their - * inventory. - * @param position the position to spawn the completed model at - */ - void NotifyTamingBuildSuccess(NiPoint3 position); + /** + * Handles a notification from the client regarding the completion of the pet minigame, adding the pet to their + * inventory. + * @param position the position to spawn the completed model at + */ + void NotifyTamingBuildSuccess(NiPoint3 position); - /** - * Handles the notification of the client to set the name of the pet (indicating that minigame was completed - * successfully). - * @param name the name of the pet to set - */ - void RequestSetPetName(std::u16string name); + /** + * Handles the notification of the client to set the name of the pet (indicating that minigame was completed + * successfully). + * @param name the name of the pet to set + */ + void RequestSetPetName(std::u16string name); - /** - * Handles a notification of the client that the taming entity is leaving the minigame, either voluntary or because - * time ran out. - * @param voluntaryExit whether the client voluntarily exited the minigame - */ - void ClientExitTamingMinigame(bool voluntaryExit); + /** + * Handles a notification of the client that the taming entity is leaving the minigame, either voluntary or because + * time ran out. + * @param voluntaryExit whether the client voluntarily exited the minigame + */ + void ClientExitTamingMinigame(bool voluntaryExit); - /** - * Starts the internal timer for the build limit for building the minigame model - */ - void StartTimer(); + /** + * Starts the internal timer for the build limit for building the minigame model + */ + void StartTimer(); - /** - * Notifies the client that they failed the minigame because time ran out - */ - void ClientFailTamingMinigame(); + /** + * Notifies the client that they failed the minigame because time ran out + */ + void ClientFailTamingMinigame(); - /** - * Makes the pet wander around - */ - void Wander(); + /** + * Makes the pet wander around + */ + void Wander(); - /** - * Spawns a pet from an item in the inventory of an owner - * @param item the item to create the pet from - * @param registerPet notifies the client that the pet was spawned, not necessary if this pet is being tamed - */ - void Activate(Item* item, bool registerPet = true, bool fromTaming = false); + /** + * Spawns a pet from an item in the inventory of an owner + * @param item the item to create the pet from + * @param registerPet notifies the client that the pet was spawned, not necessary if this pet is being tamed + */ + void Activate(Item* item, bool registerPet = true, bool fromTaming = false); - /** - * Despawns the pet - */ - void Deactivate(); + /** + * Despawns the pet + */ + void Deactivate(); - /** - * Removes the pet from the inventory - */ - void Release(); + /** + * Removes the pet from the inventory + */ + void Release(); - /** - * Commands the pet to do an action, actions are still a relative mystery, next to playing emotes - * @param position a position to execute the command at, currently unused - * @param source the source object that triggered the command - * @param commandType the type of the command (see function body for types) - * @param typeId extra information about the command, e.g. the emote to play - * @param overrideObey unused - */ - void Command(NiPoint3 position, LWOOBJID source, int32_t commandType, int32_t typeId, bool overrideObey); + /** + * Commands the pet to do an action, actions are still a relative mystery, next to playing emotes + * @param position a position to execute the command at, currently unused + * @param source the source object that triggered the command + * @param commandType the type of the command (see function body for types) + * @param typeId extra information about the command, e.g. the emote to play + * @param overrideObey unused + */ + void Command(NiPoint3 position, LWOOBJID source, int32_t commandType, int32_t typeId, bool overrideObey); - /** - * Returns the ID of the owner of this pet (if any) - * @return the ID of the owner of this pet - */ - LWOOBJID GetOwnerId() const; + /** + * Returns the ID of the owner of this pet (if any) + * @return the ID of the owner of this pet + */ + LWOOBJID GetOwnerId() const; - /** - * Returns the entity that owns this pet (if any) - * @return the entity that owns this pet - */ - Entity* GetOwner() const; + /** + * Returns the entity that owns this pet (if any) + * @return the entity that owns this pet + */ + Entity* GetOwner() const; - /** - * Returns the ID that is stored in the database with regards to this pet, only set for pets that are tamed - * @return the ID that is stored in the database with regards to this pet - */ - LWOOBJID GetDatabaseId() const; + /** + * Returns the ID that is stored in the database with regards to this pet, only set for pets that are tamed + * @return the ID that is stored in the database with regards to this pet + */ + LWOOBJID GetDatabaseId() const; - /** - * Returns the ID of the object that the pet is currently interacting with, could be a treasure chest or a switch - * @return the ID of the object that the pet is currently interacting with - */ - LWOOBJID GetInteraction() const; + /** + * Returns the ID of the object that the pet is currently interacting with, could be a treasure chest or a switch + * @return the ID of the object that the pet is currently interacting with + */ + LWOOBJID GetInteraction() const; - /** - * Sets the ID that the pet is interacting with - * @param value the ID that the pet is interacting with - */ - void SetInteraction(LWOOBJID value); + /** + * Sets the ID that the pet is interacting with + * @param value the ID that the pet is interacting with + */ + void SetInteraction(LWOOBJID value); - /** - * Returns the ID that this pet was spawned from, only set for tamed pets - * @return the ID that this pet was spawned from - */ - LWOOBJID GetItemId() const; + /** + * Returns the ID that this pet was spawned from, only set for tamed pets + * @return the ID that this pet was spawned from + */ + LWOOBJID GetItemId() const; - /** - * Returns the status of this pet, e.g. tamable or tamed. The values here are still a bit of mystery and likely a - * bit map - * @return the status of this pet - */ - uint32_t GetStatus() const; + /** + * Returns the status of this pet, e.g. tamable or tamed. The values here are still a bit of mystery and likely a + * bit map + * @return the status of this pet + */ + uint32_t GetStatus() const; - /** - * Sets the current status of the pet - * @param value the current status of the pet to set - */ - void SetStatus(uint32_t value); + /** + * Sets the current status of the pet + * @param value the current status of the pet to set + */ + void SetStatus(uint32_t value); - /** - * Returns an ability the pet may perform, currently unused - * @return an ability the pet may perform - */ - PetAbilityType GetAbility() const; + /** + * Returns an ability the pet may perform, currently unused + * @return an ability the pet may perform + */ + PetAbilityType GetAbility() const; - /** - * Sets the ability of the pet, currently unused - * @param value the ability to set - */ - void SetAbility(PetAbilityType value); + /** + * Sets the ability of the pet, currently unused + * @param value the ability to set + */ + void SetAbility(PetAbilityType value); - /** - * Sets preconditions for the pet that need to be met before it can be tamed - * @param conditions the preconditions to set - */ - void SetPreconditions(std::string& conditions); + /** + * Sets preconditions for the pet that need to be met before it can be tamed + * @param conditions the preconditions to set + */ + void SetPreconditions(std::string& conditions); - /** - * Returns the entity that this component belongs to - * @return the entity that this component belongs to - */ - Entity* GetParentEntity() const; + /** + * Returns the entity that this component belongs to + * @return the entity that this component belongs to + */ + Entity* GetParentEntity() const; - /** - * Sets the name of the pet to be moderated - * @param petName the name of the pet to set - */ - void SetPetNameForModeration(const std::string& petName); + /** + * Sets the name of the pet to be moderated + * @param petName the name of the pet to set + */ + void SetPetNameForModeration(const std::string& petName); - /** - * Loads the pet name up for moderation along with the moderation status from the database and sets them for this - * pet. - */ - void LoadPetNameFromModeration(); + /** + * Loads the pet name up for moderation along with the moderation status from the database and sets them for this + * pet. + */ + void LoadPetNameFromModeration(); - /** - * Returns the component of the pet some entity is currently taming (if any) - * @param tamer the entity that's currently taming - * @return the pet component of the entity that's being tamed - */ - static PetComponent* GetTamingPet(LWOOBJID tamer); + /** + * Returns the component of the pet some entity is currently taming (if any) + * @param tamer the entity that's currently taming + * @return the pet component of the entity that's being tamed + */ + static PetComponent* GetTamingPet(LWOOBJID tamer); - /** - * Returns the pet that's currently spawned for some entity (if any) - * @param owner the owner of the pet that's spawned - * @return the pet component of the entity that was spawned by the owner - */ - static PetComponent* GetActivePet(LWOOBJID owner); + /** + * Returns the pet that's currently spawned for some entity (if any) + * @param owner the owner of the pet that's spawned + * @return the pet component of the entity that was spawned by the owner + */ + static PetComponent* GetActivePet(LWOOBJID owner); - /** - * Adds the timer to the owner of this pet to drain imagination at the rate - * specified by the parameter imaginationDrainRate - * - * @param item The item that represents this pet in the inventory. - */ - void AddDrainImaginationTimer(Item* item, bool fromTaming = false); + /** + * Adds the timer to the owner of this pet to drain imagination at the rate + * specified by the parameter imaginationDrainRate + * + * @param item The item that represents this pet in the inventory. + */ + void AddDrainImaginationTimer(Item* item, bool fromTaming = false); private: - /** - * Information for the minigame to be completed - */ - struct PetPuzzleData - { - /** - * The LOT of the object that is to be created - */ - LOT puzzleModelLot; + /** + * Information for the minigame to be completed + */ + struct PetPuzzleData + { + /** + * The LOT of the object that is to be created + */ + LOT puzzleModelLot; - /** - * That file that contains the bricks required to build the model - */ - std::string buildFile; + /** + * That file that contains the bricks required to build the model + */ + std::string buildFile; - /** - * The time limit to complete the build - */ - int32_t timeLimit; + /** + * The time limit to complete the build + */ + int32_t timeLimit; - /** - * The imagination cost for the tamer to start the minigame - */ - int32_t imaginationCost; + /** + * The imagination cost for the tamer to start the minigame + */ + int32_t imaginationCost; - /** - * The number of pieces required to complete the minigame - */ - int32_t numValidPieces; - }; + /** + * The number of pieces required to complete the minigame + */ + int32_t numValidPieces; + }; - /** - * Cache of all the pets that are currently spawned, indexed by tamer - */ - static std::unordered_map activePets; + /** + * Cache of all the pets that are currently spawned, indexed by tamer + */ + static std::unordered_map activePets; - /** - * Cache of all the pets that are currently being tamed, indexed by tamer - */ - static std::unordered_map currentActivities; + /** + * Cache of all the pets that are currently being tamed, indexed by tamer + */ + static std::unordered_map currentActivities; - /** - * Cache of all the minigames and their information from the database - */ - static std::unordered_map buildCache; + /** + * Cache of all the minigames and their information from the database + */ + static std::unordered_map buildCache; - /** - * Flags that indicate that a player has tamed a pet, indexed by the LOT of the pet - */ - static std::map petFlags; + /** + * Flags that indicate that a player has tamed a pet, indexed by the LOT of the pet + */ + static std::map petFlags; - /** - * The ID of the component in the pet component table - */ - uint32_t m_ComponentId; + /** + * The ID of the component in the pet component table + */ + uint32_t m_ComponentId; - /** - * The ID of the model that was built to complete the taming minigame for this pet - */ - LWOOBJID m_ModelId; + /** + * The ID of the model that was built to complete the taming minigame for this pet + */ + LWOOBJID m_ModelId; - /** - * The ID of the object that the pet is currently interacting with (e.g. a treasure chest or switch) - */ - LWOOBJID m_Interaction; + /** + * The ID of the object that the pet is currently interacting with (e.g. a treasure chest or switch) + */ + LWOOBJID m_Interaction; - /** - * The ID of the entity that owns this pet - */ - LWOOBJID m_Owner; + /** + * The ID of the entity that owns this pet + */ + LWOOBJID m_Owner; - /** - * The ID of the entity that is currently taming this pet - */ - LWOOBJID m_Tamer; + /** + * The ID of the entity that is currently taming this pet + */ + LWOOBJID m_Tamer; - /** - * The ID under which this pet is stored in the database (if it's tamed) - */ - LWOOBJID m_DatabaseId; + /** + * The ID under which this pet is stored in the database (if it's tamed) + */ + LWOOBJID m_DatabaseId; - /** - * The ID of the item from which this pet was created - */ - LWOOBJID m_ItemId; + /** + * The ID of the item from which this pet was created + */ + LWOOBJID m_ItemId; - /** - * The moderation status for the name of this pet - */ - uint32_t m_ModerationStatus; + /** + * The moderation status for the name of this pet + */ + uint32_t m_ModerationStatus; - /** - * The name of this pet - */ - std::string m_Name; + /** + * The name of this pet + */ + std::string m_Name; - /** - * The name of the owner of this pet - */ - std::string m_OwnerName; + /** + * The name of the owner of this pet + */ + std::string m_OwnerName; - /** - * The current state of the pet (e.g. tamable, tamed, etc). - */ - uint32_t m_Status; + /** + * The current state of the pet (e.g. tamable, tamed, etc). + */ + uint32_t m_Status; - /** - * A currently active ability, mostly unused - */ - PetAbilityType m_Ability; + /** + * A currently active ability, mostly unused + */ + PetAbilityType m_Ability; - /** - * The time an entity has left to complete the minigame - */ - float m_Timer; + /** + * The time an entity has left to complete the minigame + */ + float m_Timer; - /** - * A timer that tracks how long a tamed pet has been to far away from its owner, triggering a teleport after timeout - */ - float m_TimerAway; + /** + * A timer that tracks how long a tamed pet has been to far away from its owner, triggering a teleport after timeout + */ + float m_TimerAway; - /** - * Timer that tracks how long a pet has been digging up some treasure, required to spawn the treasure contents - * on time - */ - float m_TresureTime; + /** + * Timer that tracks how long a pet has been digging up some treasure, required to spawn the treasure contents + * on time + */ + float m_TresureTime; - /** - * The position that this pet was spawned at - */ - NiPoint3 m_StartPosition; + /** + * The position that this pet was spawned at + */ + NiPoint3 m_StartPosition; - /** - * The movement AI component that is related to this pet, required to move it around - */ - MovementAIComponent* m_MovementAI; + /** + * The movement AI component that is related to this pet, required to move it around + */ + MovementAIComponent* m_MovementAI; - /** - * Preconditions that need to be met before an entity can tame this pet - */ - PreconditionExpression* m_Preconditions; + /** + * Preconditions that need to be met before an entity can tame this pet + */ + PreconditionExpression* m_Preconditions; - /** - * The rate at which imagination is drained from the user for having the pet out. - */ - float imaginationDrainRate; -}; \ No newline at end of file + /** + * The rate at which imagination is drained from the user for having the pet out. + */ + float imaginationDrainRate; +}; diff --git a/dGame/dComponents/PhantomPhysicsComponent.cpp b/dGame/dComponents/PhantomPhysicsComponent.cpp index 3c8394f6..8cafec52 100644 --- a/dGame/dComponents/PhantomPhysicsComponent.cpp +++ b/dGame/dComponents/PhantomPhysicsComponent.cpp @@ -27,23 +27,23 @@ PhantomPhysicsComponent::PhantomPhysicsComponent(Entity* parent) : Component(parent) { m_Position = m_Parent->GetDefaultPosition(); - m_Rotation = m_Parent->GetDefaultRotation(); + m_Rotation = m_Parent->GetDefaultRotation(); m_Scale = m_Parent->GetDefaultScale(); m_dpEntity = nullptr; - m_EffectInfoDirty = false; + m_EffectInfoDirty = false; m_PositionInfoDirty = false; - m_IsPhysicsEffectActive = false; - m_EffectType = 0; - m_DirectionalMultiplier = 0.0f; + m_IsPhysicsEffectActive = false; + m_EffectType = 0; + m_DirectionalMultiplier = 0.0f; - m_MinMax = false; - m_Min = 0; - m_Max = 1; + m_MinMax = false; + m_Min = 0; + m_Max = 1; - m_IsDirectional = false; - m_Direction = NiPoint3(); // * m_DirectionalMultiplier + m_IsDirectional = false; + m_Direction = NiPoint3(); // * m_DirectionalMultiplier if (m_Parent->GetVar(u"create_physics")) { CreatePhysics(); @@ -82,8 +82,7 @@ PhantomPhysicsComponent::PhantomPhysicsComponent(Entity* parent) : Component(par } // HF - RespawnPoints. Legacy respawn entity. - if (m_Parent->GetLOT() == 4945) - { + if (m_Parent->GetLOT() == 4945) { m_IsRespawnVolume = true; m_RespawnPos = m_Position; m_RespawnRot = m_Rotation; @@ -162,8 +161,7 @@ PhantomPhysicsComponent::PhantomPhysicsComponent(Entity* parent) : Component(par m_dpEntity->SetPosition(m_Position); dpWorld::Instance().AddEntity(m_dpEntity); - } - else if (info->physicsAsset == "miscellaneous\\misc_phys_640x640.hkx") { + } else if (info->physicsAsset == "miscellaneous\\misc_phys_640x640.hkx") { m_dpEntity = new dpEntity(m_Parent->GetObjectID(), 640.0f, 20.0f, 640.0f); m_dpEntity->SetScale(m_Scale); @@ -171,53 +169,43 @@ PhantomPhysicsComponent::PhantomPhysicsComponent(Entity* parent) : Component(par m_dpEntity->SetPosition(m_Position); dpWorld::Instance().AddEntity(m_dpEntity); - } - else if (info->physicsAsset == "env\\trigger_wall_tall.hkx") { - m_dpEntity = new dpEntity(m_Parent->GetObjectID(), 10.0f, 25.0f, 1.0f); + } else if (info->physicsAsset == "env\\trigger_wall_tall.hkx") { + m_dpEntity = new dpEntity(m_Parent->GetObjectID(), 10.0f, 25.0f, 1.0f); m_dpEntity->SetScale(m_Scale); m_dpEntity->SetRotation(m_Rotation); m_dpEntity->SetPosition(m_Position); dpWorld::Instance().AddEntity(m_dpEntity); - } - else if (info->physicsAsset == "env\\env_gen_placeholderphysics.hkx") { + } else if (info->physicsAsset == "env\\env_gen_placeholderphysics.hkx") { m_dpEntity = new dpEntity(m_Parent->GetObjectID(), 20.0f, 20.0f, 20.0f); m_dpEntity->SetScale(m_Scale); m_dpEntity->SetRotation(m_Rotation); m_dpEntity->SetPosition(m_Position); dpWorld::Instance().AddEntity(m_dpEntity); - } - else if (info->physicsAsset == "env\\POI_trigger_wall.hkx") { + } else if (info->physicsAsset == "env\\POI_trigger_wall.hkx") { m_dpEntity = new dpEntity(m_Parent->GetObjectID(), 1.0f, 12.5f, 20.0f); // Not sure what the real size is m_dpEntity->SetScale(m_Scale); m_dpEntity->SetRotation(m_Rotation); m_dpEntity->SetPosition(m_Position); dpWorld::Instance().AddEntity(m_dpEntity); - } - else if (info->physicsAsset == "env\\NG_NinjaGo\\env_ng_gen_gate_chamber_puzzle_ceiling_tile_falling_phantom.hkx") - { + } else if (info->physicsAsset == "env\\NG_NinjaGo\\env_ng_gen_gate_chamber_puzzle_ceiling_tile_falling_phantom.hkx") { m_dpEntity = new dpEntity(m_Parent->GetObjectID(), 18.0f, 5.0f, 15.0f); m_dpEntity->SetScale(m_Scale); m_dpEntity->SetRotation(m_Rotation); m_dpEntity->SetPosition(m_Position + m_Rotation.GetForwardVector() * 7.5f); dpWorld::Instance().AddEntity(m_dpEntity); - } - else if (info->physicsAsset == "env\\NG_NinjaGo\\ng_flamejet_brick_phantom.HKX") - { + } else if (info->physicsAsset == "env\\NG_NinjaGo\\ng_flamejet_brick_phantom.HKX") { m_dpEntity = new dpEntity(m_Parent->GetObjectID(), 1.0f, 1.0f, 12.0f); m_dpEntity->SetScale(m_Scale); m_dpEntity->SetRotation(m_Rotation); m_dpEntity->SetPosition(m_Position + m_Rotation.GetForwardVector() * 6.0f); dpWorld::Instance().AddEntity(m_dpEntity); - } - else if (info->physicsAsset == "env\\Ring_Trigger.hkx") - { + } else if (info->physicsAsset == "env\\Ring_Trigger.hkx") { m_dpEntity = new dpEntity(m_Parent->GetObjectID(), 6.0f, 6.0f, 6.0f); m_dpEntity->SetScale(m_Scale); m_dpEntity->SetRotation(m_Rotation); m_dpEntity->SetPosition(m_Position); dpWorld::Instance().AddEntity(m_dpEntity); - } - else { + } else { //Game::logger->Log("PhantomPhysicsComponent", "This one is supposed to have %s", info->physicsAsset.c_str()); //add fallback cube: @@ -254,8 +242,7 @@ void PhantomPhysicsComponent::CreatePhysics() { x = m_Parent->GetVar(u"primitiveModelValueX"); y = m_Parent->GetVar(u"primitiveModelValueY"); z = m_Parent->GetVar(u"primitiveModelValueZ"); - } - else { + } else { CDComponentsRegistryTable* compRegistryTable = CDClientManager::Instance()->GetTable("ComponentsRegistry"); auto componentID = compRegistryTable->GetByIDAndType(m_Parent->GetLOT(), COMPONENT_TYPE_PHANTOM_PHYSICS); @@ -294,7 +281,7 @@ void PhantomPhysicsComponent::CreatePhysics() { if (!m_dpEntity) return; - m_dpEntity->SetPosition({m_Position.x, m_Position.y - (height / 2), m_Position.z}); + m_dpEntity->SetPosition({ m_Position.x, m_Position.y - (height / 2), m_Position.z }); dpWorld::Instance().AddEntity(m_dpEntity); @@ -302,9 +289,8 @@ void PhantomPhysicsComponent::CreatePhysics() { } void PhantomPhysicsComponent::Serialize(RakNet::BitStream* outBitStream, bool bIsInitialUpdate, unsigned int& flags) { - outBitStream->Write(m_PositionInfoDirty || bIsInitialUpdate); - if (m_PositionInfoDirty || bIsInitialUpdate) - { + outBitStream->Write(m_PositionInfoDirty || bIsInitialUpdate); + if (m_PositionInfoDirty || bIsInitialUpdate) { outBitStream->Write(m_Position.x); outBitStream->Write(m_Position.y); outBitStream->Write(m_Position.z); @@ -316,13 +302,13 @@ void PhantomPhysicsComponent::Serialize(RakNet::BitStream* outBitStream, bool bI m_PositionInfoDirty = false; } - outBitStream->Write(m_EffectInfoDirty || bIsInitialUpdate); - if (m_EffectInfoDirty || bIsInitialUpdate) { - outBitStream->Write(m_IsPhysicsEffectActive); + outBitStream->Write(m_EffectInfoDirty || bIsInitialUpdate); + if (m_EffectInfoDirty || bIsInitialUpdate) { + outBitStream->Write(m_IsPhysicsEffectActive); - if (m_IsPhysicsEffectActive) { - outBitStream->Write(m_EffectType); - outBitStream->Write(m_DirectionalMultiplier); + if (m_IsPhysicsEffectActive) { + outBitStream->Write(m_EffectType); + outBitStream->Write(m_DirectionalMultiplier); // forgive me father for i have sinned outBitStream->Write0(); @@ -332,20 +318,20 @@ void PhantomPhysicsComponent::Serialize(RakNet::BitStream* outBitStream, bool bI //outBitStream->Write(m_Max); //} - outBitStream->Write(m_IsDirectional); - if (m_IsDirectional) { - outBitStream->Write(m_Direction.x); - outBitStream->Write(m_Direction.y); - outBitStream->Write(m_Direction.z); - } - } + outBitStream->Write(m_IsDirectional); + if (m_IsDirectional) { + outBitStream->Write(m_Direction.x); + outBitStream->Write(m_Direction.y); + outBitStream->Write(m_Direction.z); + } + } m_EffectInfoDirty = false; - } + } } void PhantomPhysicsComponent::ResetFlags() { - m_EffectInfoDirty = false; + m_EffectInfoDirty = false; m_PositionInfoDirty = false; } @@ -375,13 +361,13 @@ void PhantomPhysicsComponent::Update(float deltaTime) { } void PhantomPhysicsComponent::SetDirection(const NiPoint3& pos) { - m_Direction = pos; - m_Direction.x *= m_DirectionalMultiplier; - m_Direction.y *= m_DirectionalMultiplier; - m_Direction.z *= m_DirectionalMultiplier; + m_Direction = pos; + m_Direction.x *= m_DirectionalMultiplier; + m_Direction.y *= m_DirectionalMultiplier; + m_Direction.z *= m_DirectionalMultiplier; - m_EffectInfoDirty = true; - m_IsDirectional = true; + m_EffectInfoDirty = true; + m_IsDirectional = true; } void PhantomPhysicsComponent::SpawnVertices() { @@ -405,35 +391,35 @@ void PhantomPhysicsComponent::SpawnVertices() { } void PhantomPhysicsComponent::SetDirectionalMultiplier(float mul) { - m_DirectionalMultiplier = mul; - m_EffectInfoDirty = true; + m_DirectionalMultiplier = mul; + m_EffectInfoDirty = true; } void PhantomPhysicsComponent::SetEffectType(uint32_t type) { - m_EffectType = type; - m_EffectInfoDirty = true; + m_EffectType = type; + m_EffectInfoDirty = true; } void PhantomPhysicsComponent::SetMin(uint32_t min) { - m_Min = min; - m_MinMax = true; - m_EffectInfoDirty = true; + m_Min = min; + m_MinMax = true; + m_EffectInfoDirty = true; } void PhantomPhysicsComponent::SetMax(uint32_t max) { - m_Max = max; - m_MinMax = true; - m_EffectInfoDirty = true; + m_Max = max; + m_MinMax = true; + m_EffectInfoDirty = true; } void PhantomPhysicsComponent::SetPosition(const NiPoint3& pos) { - m_Position = pos; + m_Position = pos; if (m_dpEntity) m_dpEntity->SetPosition(pos); } void PhantomPhysicsComponent::SetRotation(const NiQuaternion& rot) { - m_Rotation = rot; + m_Rotation = rot; if (m_dpEntity) m_dpEntity->SetRotation(rot); } diff --git a/dGame/dComponents/PhantomPhysicsComponent.h b/dGame/dComponents/PhantomPhysicsComponent.h index faf6362f..1e9a7b60 100644 --- a/dGame/dComponents/PhantomPhysicsComponent.h +++ b/dGame/dComponents/PhantomPhysicsComponent.h @@ -25,191 +25,191 @@ class dpEntity; */ class PhantomPhysicsComponent : public Component { public: - static const uint32_t ComponentType = COMPONENT_TYPE_PHANTOM_PHYSICS; - - PhantomPhysicsComponent(Entity* parent); - ~PhantomPhysicsComponent() override; - void Update(float deltaTime) override; - void Serialize(RakNet::BitStream* outBitStream, bool bIsInitialUpdate, unsigned int& flags); - void ResetFlags(); + static const uint32_t ComponentType = COMPONENT_TYPE_PHANTOM_PHYSICS; - /** - * Creates the physics shape for this entity based on LDF data - */ + PhantomPhysicsComponent(Entity* parent); + ~PhantomPhysicsComponent() override; + void Update(float deltaTime) override; + void Serialize(RakNet::BitStream* outBitStream, bool bIsInitialUpdate, unsigned int& flags); + void ResetFlags(); + + /** + * Creates the physics shape for this entity based on LDF data + */ void CreatePhysics(); - /** - * Sets the direction this physics object is pointed at - * @param pos the direction to set - */ - void SetDirection(const NiPoint3& pos); + /** + * Sets the direction this physics object is pointed at + * @param pos the direction to set + */ + void SetDirection(const NiPoint3& pos); - /** - * Returns the direction this physics object is pointed at - * @return the direction this physics object is pointed at - */ - const NiPoint3& GetDirection() const { return m_Direction; } + /** + * Returns the direction this physics object is pointed at + * @return the direction this physics object is pointed at + */ + const NiPoint3& GetDirection() const { return m_Direction; } - /** - * Returns the multiplier by which the direction coordinates are multiplied - * @return the multiplier by which the direction coordinates are multiplied - */ - float GetDirectionalMultiplier() const { return m_DirectionalMultiplier; } + /** + * Returns the multiplier by which the direction coordinates are multiplied + * @return the multiplier by which the direction coordinates are multiplied + */ + float GetDirectionalMultiplier() const { return m_DirectionalMultiplier; } - /** - * Sets the multiplier by which direction coordinates are multiplied - * @param mul the multiplier to set - */ - void SetDirectionalMultiplier(float mul); + /** + * Sets the multiplier by which direction coordinates are multiplied + * @param mul the multiplier to set + */ + void SetDirectionalMultiplier(float mul); - /** - * Returns whether or not there's currently an effect active - * @return true if there's an effect active, false otherwise - */ - bool GetPhysicsEffectActive() const { return m_IsPhysicsEffectActive; } + /** + * Returns whether or not there's currently an effect active + * @return true if there's an effect active, false otherwise + */ + bool GetPhysicsEffectActive() const { return m_IsPhysicsEffectActive; } - /** - * Sets whether or not there's a physics effect active - * @param val whether or not there's an effect active - */ - void SetPhysicsEffectActive(bool val) { m_IsPhysicsEffectActive = val; m_EffectInfoDirty = true; } + /** + * Sets whether or not there's a physics effect active + * @param val whether or not there's an effect active + */ + void SetPhysicsEffectActive(bool val) { m_IsPhysicsEffectActive = val; m_EffectInfoDirty = true; } - /** - * Returns the position of this physics object - * @return the position of this physics object - */ - const NiPoint3& GetPosition() const { return m_Position; } + /** + * Returns the position of this physics object + * @return the position of this physics object + */ + const NiPoint3& GetPosition() const { return m_Position; } - /** - * Sets the position of this physics object - * @param pos the position to set - */ - void SetPosition(const NiPoint3& pos); + /** + * Sets the position of this physics object + * @param pos the position to set + */ + void SetPosition(const NiPoint3& pos); - /** - * Returns the rotation of this physics object - * @return the rotation of this physics object - */ - const NiQuaternion& GetRotation() const { return m_Rotation; } + /** + * Returns the rotation of this physics object + * @return the rotation of this physics object + */ + const NiQuaternion& GetRotation() const { return m_Rotation; } - /** - * Sets the rotation of this physics object - * @param rot the rotation to set - */ - void SetRotation(const NiQuaternion& rot); + /** + * Sets the rotation of this physics object + * @param rot the rotation to set + */ + void SetRotation(const NiQuaternion& rot); - /** - * Returns the effect that's currently active, defaults to 0 - * @return the effect that's currently active - */ - uint32_t GetEffectType() const { return m_EffectType; } + /** + * Returns the effect that's currently active, defaults to 0 + * @return the effect that's currently active + */ + uint32_t GetEffectType() const { return m_EffectType; } - /** - * Sets the effect that's currently active - * @param type the effect to set - */ - void SetEffectType(uint32_t type); + /** + * Sets the effect that's currently active + * @param type the effect to set + */ + void SetEffectType(uint32_t type); - /** - * Returns the Physics entity for the component - * @return Physics entity for the component - */ + /** + * Returns the Physics entity for the component + * @return Physics entity for the component + */ - dpEntity* GetdpEntity() const { return m_dpEntity; } + dpEntity* GetdpEntity() const { return m_dpEntity; } - /** - * Spawns an object at each of the vertices for debugging purposes - */ - void SpawnVertices(); + /** + * Spawns an object at each of the vertices for debugging purposes + */ + void SpawnVertices(); - /** - * Legacy stuff no clue what this does - */ - void SetMin(uint32_t min); + /** + * Legacy stuff no clue what this does + */ + void SetMin(uint32_t min); + + /** + * Legacy stuff no clue what this does + */ + void SetMax(uint32_t max); - /** - * Legacy stuff no clue what this does - */ - void SetMax(uint32_t max); - private: - /** - * The position of the physics object - */ - NiPoint3 m_Position; + /** + * The position of the physics object + */ + NiPoint3 m_Position; - /** - * The rotation of the physics object - */ - NiQuaternion m_Rotation; + /** + * The rotation of the physics object + */ + NiQuaternion m_Rotation; - /** - * A scale to apply to the size of the physics object - */ + /** + * A scale to apply to the size of the physics object + */ float m_Scale; - /** - * Whether or not the position has changed and needs to be serialized - */ - bool m_PositionInfoDirty; + /** + * Whether or not the position has changed and needs to be serialized + */ + bool m_PositionInfoDirty; - /** - * Whether or not the effect has changed and needs to be serialized - */ - bool m_EffectInfoDirty; + /** + * Whether or not the effect has changed and needs to be serialized + */ + bool m_EffectInfoDirty; - /** - * Whether or not there's currently a physics effect active - */ - bool m_IsPhysicsEffectActive; + /** + * Whether or not there's currently a physics effect active + */ + bool m_IsPhysicsEffectActive; - /** - * The physics effect that's currently active, defaults to 0 - */ - uint32_t m_EffectType; + /** + * The physics effect that's currently active, defaults to 0 + */ + uint32_t m_EffectType; - /** - * A scaling multiplier to add to the directional vector - */ - float m_DirectionalMultiplier; - - bool m_MinMax; - uint32_t m_Min; - uint32_t m_Max; + /** + * A scaling multiplier to add to the directional vector + */ + float m_DirectionalMultiplier; - /** - * Whether or not this physics object is pointed in some direction - */ - bool m_IsDirectional; + bool m_MinMax; + uint32_t m_Min; + uint32_t m_Max; - /** - * The direction this physics object is pointed in, if any - */ - NiPoint3 m_Direction; + /** + * Whether or not this physics object is pointed in some direction + */ + bool m_IsDirectional; - /** - * The parent entity of this component - */ - dpEntity* m_dpEntity; + /** + * The direction this physics object is pointed in, if any + */ + NiPoint3 m_Direction; - /** - * Whether or not the physics object has been created yet - */ + /** + * The parent entity of this component + */ + dpEntity* m_dpEntity; + + /** + * Whether or not the physics object has been created yet + */ bool m_HasCreatedPhysics = false; - /** - * Whether or not this physics object represents an object that updates the respawn pos of an entity that crosses it - */ + /** + * Whether or not this physics object represents an object that updates the respawn pos of an entity that crosses it + */ bool m_IsRespawnVolume = false; - /** - * If this is a respawn volume, the exact position an entity will respawn - */ + /** + * If this is a respawn volume, the exact position an entity will respawn + */ NiPoint3 m_RespawnPos; - /** - * If this is a respawn volume, the exact rotation an entity will respawn - */ + /** + * If this is a respawn volume, the exact rotation an entity will respawn + */ NiQuaternion m_RespawnRot; -}; \ No newline at end of file +}; diff --git a/dGame/dComponents/PlayerForcedMovementComponent.cpp b/dGame/dComponents/PlayerForcedMovementComponent.cpp index 94b79188..3bcad677 100644 --- a/dGame/dComponents/PlayerForcedMovementComponent.cpp +++ b/dGame/dComponents/PlayerForcedMovementComponent.cpp @@ -6,11 +6,11 @@ PlayerForcedMovementComponent::PlayerForcedMovementComponent(Entity* parent) : C PlayerForcedMovementComponent::~PlayerForcedMovementComponent() {} -void PlayerForcedMovementComponent::Serialize(RakNet::BitStream* outBitStream, bool bIsInitialUpdate, unsigned int& flags){ +void PlayerForcedMovementComponent::Serialize(RakNet::BitStream* outBitStream, bool bIsInitialUpdate, unsigned int& flags) { outBitStream->Write(m_DirtyInfo); if (m_DirtyInfo) { outBitStream->Write(m_PlayerOnRail); outBitStream->Write(m_ShowBillboard); } m_DirtyInfo = false; -} \ No newline at end of file +} diff --git a/dGame/dComponents/PlayerForcedMovementComponent.h b/dGame/dComponents/PlayerForcedMovementComponent.h index d023155c..43b99997 100644 --- a/dGame/dComponents/PlayerForcedMovementComponent.h +++ b/dGame/dComponents/PlayerForcedMovementComponent.h @@ -25,14 +25,14 @@ public: * * @param value if the player is on a rail */ - void SetPlayerOnRail(bool value){ m_PlayerOnRail = value; m_DirtyInfo = true; } + void SetPlayerOnRail(bool value) { m_PlayerOnRail = value; m_DirtyInfo = true; } /** * @brief Set the Show Billboard object * * @param value if the billboard should be shown */ - void SetShowBillboard(bool value){ m_ShowBillboard = value; m_DirtyInfo = true; } + void SetShowBillboard(bool value) { m_ShowBillboard = value; m_DirtyInfo = true; } /** * @brief Get the Player On Rail object @@ -41,14 +41,14 @@ public: * @return false */ - /** - * @brief Get the Player On Rail object - * - * @return true - * @return false - */ - bool GetPlayerOnRail(){ return m_PlayerOnRail; } - bool GetShowBillboard(){ return m_ShowBillboard; } + /** + * @brief Get the Player On Rail object + * + * @return true + * @return false + */ + bool GetPlayerOnRail() { return m_PlayerOnRail; } + bool GetShowBillboard() { return m_ShowBillboard; } private: /** diff --git a/dGame/dComponents/PossessableComponent.cpp b/dGame/dComponents/PossessableComponent.cpp index 8190b9eb..be31914b 100644 --- a/dGame/dComponents/PossessableComponent.cpp +++ b/dGame/dComponents/PossessableComponent.cpp @@ -4,7 +4,7 @@ #include "Inventory.h" #include "Item.h" -PossessableComponent::PossessableComponent(Entity* parent, uint32_t componentId) : Component(parent){ +PossessableComponent::PossessableComponent(Entity* parent, uint32_t componentId) : Component(parent) { m_Possessor = LWOOBJID_EMPTY; CDItemComponent item = Inventory::FindItemComponent(m_Parent->GetLOT()); m_AnimationFlag = static_cast(item.animationFlag); @@ -35,7 +35,7 @@ void PossessableComponent::Serialize(RakNet::BitStream* outBitStream, bool bIsIn if (m_Possessor != LWOOBJID_EMPTY) outBitStream->Write(m_Possessor); outBitStream->Write(m_AnimationFlag != eAnimationFlags::IDLE_INVALID); - if(m_AnimationFlag != eAnimationFlags::IDLE_INVALID) outBitStream->Write(m_AnimationFlag); + if (m_AnimationFlag != eAnimationFlags::IDLE_INVALID) outBitStream->Write(m_AnimationFlag); outBitStream->Write(m_ImmediatelyDepossess); } @@ -43,4 +43,4 @@ void PossessableComponent::Serialize(RakNet::BitStream* outBitStream, bool bIsIn void PossessableComponent::OnUse(Entity* originator) { // TODO: Implement this -} \ No newline at end of file +} diff --git a/dGame/dComponents/PossessableComponent.h b/dGame/dComponents/PossessableComponent.h index a37b6e34..77905c9c 100644 --- a/dGame/dComponents/PossessableComponent.h +++ b/dGame/dComponents/PossessableComponent.h @@ -12,104 +12,104 @@ * player is controlling it. */ class PossessableComponent : public Component { - public: - static const uint32_t ComponentType = COMPONENT_TYPE_POSSESSABLE; +public: + static const uint32_t ComponentType = COMPONENT_TYPE_POSSESSABLE; - PossessableComponent(Entity* parentEntity, uint32_t componentId); + PossessableComponent(Entity* parentEntity, uint32_t componentId); - void Serialize(RakNet::BitStream* outBitStream, bool bIsInitialUpdate, unsigned int& flags); + void Serialize(RakNet::BitStream* outBitStream, bool bIsInitialUpdate, unsigned int& flags); - /** - * Sets the possessor of this entity - * @param value the ID of the possessor to set - */ - void SetPossessor(LWOOBJID value) { m_Possessor = value; m_DirtyPossessable = true;}; + /** + * Sets the possessor of this entity + * @param value the ID of the possessor to set + */ + void SetPossessor(LWOOBJID value) { m_Possessor = value; m_DirtyPossessable = true; }; - /** - * Returns the possessor of this entity - * @return the possessor of this entity - */ - LWOOBJID GetPossessor() const { return m_Possessor; }; + /** + * Returns the possessor of this entity + * @return the possessor of this entity + */ + LWOOBJID GetPossessor() const { return m_Possessor; }; - /** - * Sets the animation Flag of the possessable - * @param value the animation flag to set to - */ - void SetAnimationFlag(eAnimationFlags value) { m_AnimationFlag = value; m_DirtyPossessable = true;}; + /** + * Sets the animation Flag of the possessable + * @param value the animation flag to set to + */ + void SetAnimationFlag(eAnimationFlags value) { m_AnimationFlag = value; m_DirtyPossessable = true; }; - /** - * Returns the possession type of this entity - * @return the possession type of this entity - */ - ePossessionType GetPossessionType() const { return m_PossessionType; }; + /** + * Returns the possession type of this entity + * @return the possession type of this entity + */ + ePossessionType GetPossessionType() const { return m_PossessionType; }; - /** - * Returns if the entity should deposses on hit - * @return if the entity should deposses on hit - */ - bool GetDepossessOnHit() const { return m_DepossessOnHit; }; + /** + * Returns if the entity should deposses on hit + * @return if the entity should deposses on hit + */ + bool GetDepossessOnHit() const { return m_DepossessOnHit; }; - /** - * Forcibly depossess the entity - */ - void ForceDepossess() { m_ImmediatelyDepossess = true; m_DirtyPossessable = true;}; + /** + * Forcibly depossess the entity + */ + void ForceDepossess() { m_ImmediatelyDepossess = true; m_DirtyPossessable = true; }; - /** - * Set if the parent entity was spawned from an item - * @param value if the parent entity was spawned from an item - */ - void SetItemSpawned(bool value) { m_ItemSpawned = value;}; + /** + * Set if the parent entity was spawned from an item + * @param value if the parent entity was spawned from an item + */ + void SetItemSpawned(bool value) { m_ItemSpawned = value; }; - /** - * Returns if the parent entity was spawned from an item - * @return if the parent entity was spawned from an item - */ - LWOOBJID GetItemSpawned() const { return m_ItemSpawned; }; + /** + * Returns if the parent entity was spawned from an item + * @return if the parent entity was spawned from an item + */ + LWOOBJID GetItemSpawned() const { return m_ItemSpawned; }; - /** - * Handles an OnUsed event by some other entity, if said entity has a Possessor it becomes the possessor - * of this entity - * @param originator the entity that caused the event to trigger - */ - void OnUse(Entity* originator) override; + /** + * Handles an OnUsed event by some other entity, if said entity has a Possessor it becomes the possessor + * of this entity + * @param originator the entity that caused the event to trigger + */ + void OnUse(Entity* originator) override; - private: +private: - /** - * @brief Whether the possessor is dirty - */ - bool m_DirtyPossessable = true; + /** + * @brief Whether the possessor is dirty + */ + bool m_DirtyPossessable = true; - /** - * @brief The possessor of this entity, e.g. the entity that controls this entity - */ - LWOOBJID m_Possessor = LWOOBJID_EMPTY; + /** + * @brief The possessor of this entity, e.g. the entity that controls this entity + */ + LWOOBJID m_Possessor = LWOOBJID_EMPTY; - /** - * @brief The type of possesstion to use on this entity - */ - ePossessionType m_PossessionType = ePossessionType::NO_POSSESSION; + /** + * @brief The type of possesstion to use on this entity + */ + ePossessionType m_PossessionType = ePossessionType::NO_POSSESSION; - /** - * @brief Should the possessable be dismount on hit - */ - bool m_DepossessOnHit = false; + /** + * @brief Should the possessable be dismount on hit + */ + bool m_DepossessOnHit = false; - /** - * @brief What animaiton flag to use - * - */ - eAnimationFlags m_AnimationFlag = eAnimationFlags::IDLE_INVALID; + /** + * @brief What animaiton flag to use + * + */ + eAnimationFlags m_AnimationFlag = eAnimationFlags::IDLE_INVALID; - /** - * @brief Should this be immediately depossessed - * - */ - bool m_ImmediatelyDepossess = false; + /** + * @brief Should this be immediately depossessed + * + */ + bool m_ImmediatelyDepossess = false; - /** - * @brief Whether the parent entity was spawned from an item - * - */ - bool m_ItemSpawned = false; + /** + * @brief Whether the parent entity was spawned from an item + * + */ + bool m_ItemSpawned = false; }; diff --git a/dGame/dComponents/PossessorComponent.h b/dGame/dComponents/PossessorComponent.h index a81868a5..2735adac 100644 --- a/dGame/dComponents/PossessorComponent.h +++ b/dGame/dComponents/PossessorComponent.h @@ -16,66 +16,66 @@ enum class ePossessionType : uint8_t { * Represents an entity that can posess other entities. Generally used by players to drive a car. */ class PossessorComponent : public Component { - public: - static const uint32_t ComponentType = COMPONENT_TYPE_POSSESSOR; +public: + static const uint32_t ComponentType = COMPONENT_TYPE_POSSESSOR; - PossessorComponent(Entity* parent); - ~PossessorComponent() override; + PossessorComponent(Entity* parent); + ~PossessorComponent() override; - void Serialize(RakNet::BitStream* outBitStream, bool bIsInitialUpdate, unsigned int& flags); + void Serialize(RakNet::BitStream* outBitStream, bool bIsInitialUpdate, unsigned int& flags); - /** - * Sets the entity that this entity is possessing - * @param value the ID of the entity this ID should posess - */ - void SetPossessable(LWOOBJID value) { m_Possessable = value; m_DirtyPossesor = true; } + /** + * Sets the entity that this entity is possessing + * @param value the ID of the entity this ID should posess + */ + void SetPossessable(LWOOBJID value) { m_Possessable = value; m_DirtyPossesor = true; } - /** - * Returns the entity that this entity is currently posessing - * @return the entity that this entity is currently posessing - */ - LWOOBJID GetPossessable() const { return m_Possessable; } + /** + * Returns the entity that this entity is currently posessing + * @return the entity that this entity is currently posessing + */ + LWOOBJID GetPossessable() const { return m_Possessable; } - /** - * Sets if we are busy mounting or dismounting - * @param value if we are busy mounting or dismounting - */ - void SetIsBusy(bool value) { m_IsBusy = value; } + /** + * Sets if we are busy mounting or dismounting + * @param value if we are busy mounting or dismounting + */ + void SetIsBusy(bool value) { m_IsBusy = value; } - /** - * Returns if we are busy mounting or dismounting - * @return if we are busy mounting or dismounting - */ - bool GetIsBusy() const { return m_IsBusy; } + /** + * Returns if we are busy mounting or dismounting + * @return if we are busy mounting or dismounting + */ + bool GetIsBusy() const { return m_IsBusy; } - /** - * Sets the possesible type that's currently used, merely used by the shooting gallery if it's 0 - * @param value the possesible type to set - */ - void SetPossessableType(ePossessionType value) { m_PossessableType = value; m_DirtyPossesor = true; } + /** + * Sets the possesible type that's currently used, merely used by the shooting gallery if it's 0 + * @param value the possesible type to set + */ + void SetPossessableType(ePossessionType value) { m_PossessableType = value; m_DirtyPossesor = true; } - private: +private: - /** - * The ID of the entity this entity is possessing (e.g. the ID of a car) - */ - LWOOBJID m_Possessable = LWOOBJID_EMPTY; + /** + * The ID of the entity this entity is possessing (e.g. the ID of a car) + */ + LWOOBJID m_Possessable = LWOOBJID_EMPTY; - /** - * @brief possessable type - * - */ - ePossessionType m_PossessableType = ePossessionType::NO_POSSESSION; + /** + * @brief possessable type + * + */ + ePossessionType m_PossessableType = ePossessionType::NO_POSSESSION; - /** - * @brief if the possessor is dirty - * - */ - bool m_DirtyPossesor = false; + /** + * @brief if the possessor is dirty + * + */ + bool m_DirtyPossesor = false; - /** - * @brief if the possessor is busy mounting or dismounting - * - */ - bool m_IsBusy = false; + /** + * @brief if the possessor is busy mounting or dismounting + * + */ + bool m_IsBusy = false; }; diff --git a/dGame/dComponents/PropertyComponent.cpp b/dGame/dComponents/PropertyComponent.cpp index cbe8d156..4f8df40c 100644 --- a/dGame/dComponents/PropertyComponent.cpp +++ b/dGame/dComponents/PropertyComponent.cpp @@ -3,7 +3,7 @@ #include "dZoneManager.h" PropertyComponent::PropertyComponent(Entity* parent) : Component(parent) { - m_PropertyName = parent->GetVar(u"propertyName"); + m_PropertyName = parent->GetVar(u"propertyName"); m_PropertyState = new PropertyState(); } diff --git a/dGame/dComponents/PropertyEntranceComponent.cpp b/dGame/dComponents/PropertyEntranceComponent.cpp index 5bc24a9f..e6540417 100644 --- a/dGame/dComponents/PropertyEntranceComponent.cpp +++ b/dGame/dComponents/PropertyEntranceComponent.cpp @@ -12,15 +12,14 @@ #include "UserManager.h" #include "dLogger.h" -PropertyEntranceComponent::PropertyEntranceComponent(uint32_t componentID, Entity* parent) : Component(parent) -{ - this->propertyQueries = {}; +PropertyEntranceComponent::PropertyEntranceComponent(uint32_t componentID, Entity* parent) : Component(parent) { + this->propertyQueries = {}; - auto table = CDClientManager::Instance()->GetTable("PropertyEntranceComponent"); - const auto& entry = table->GetByID(componentID); + auto table = CDClientManager::Instance()->GetTable("PropertyEntranceComponent"); + const auto& entry = table->GetByID(componentID); - this->m_MapID = entry.mapID; - this->m_PropertyName = entry.propertyName; + this->m_MapID = entry.mapID; + this->m_PropertyName = entry.propertyName; } void PropertyEntranceComponent::OnUse(Entity* entity) { @@ -42,304 +41,294 @@ void PropertyEntranceComponent::OnUse(Entity* entity) { GameMessages::SendUIMessageServerToSingleClient(entity, entity->GetSystemAddress(), "pushGameState", &args); } -void PropertyEntranceComponent::OnEnterProperty(Entity* entity, uint32_t index, bool returnToZone, const SystemAddress& sysAddr) -{ - LWOCLONEID cloneId = 0; +void PropertyEntranceComponent::OnEnterProperty(Entity* entity, uint32_t index, bool returnToZone, const SystemAddress& sysAddr) { + LWOCLONEID cloneId = 0; - if (index == -1 && !returnToZone) - { - cloneId = entity->GetCharacter()->GetPropertyCloneID(); - } - else if (index == -1 && returnToZone) - { - cloneId = 0; - } - else if (index >= 0) - { - // Increment index once here because the first index of other player properties is 2 in the propertyQueries cache. - index++; + if (index == -1 && !returnToZone) { + cloneId = entity->GetCharacter()->GetPropertyCloneID(); + } else if (index == -1 && returnToZone) { + cloneId = 0; + } else if (index >= 0) { + // Increment index once here because the first index of other player properties is 2 in the propertyQueries cache. + index++; - const auto& pair = propertyQueries.find(entity->GetObjectID()); + const auto& pair = propertyQueries.find(entity->GetObjectID()); - if (pair == propertyQueries.end()) return; + if (pair == propertyQueries.end()) return; - const auto& query = pair->second; + const auto& query = pair->second; - if (index >= query.size()) return; + if (index >= query.size()) return; - cloneId = query[index].CloneId; - } + cloneId = query[index].CloneId; + } - auto* launcher = m_Parent->GetComponent(); + auto* launcher = m_Parent->GetComponent(); - if (launcher == nullptr) - { - return; - } + if (launcher == nullptr) { + return; + } - launcher->SetSelectedCloneId(entity->GetObjectID(), cloneId); + launcher->SetSelectedCloneId(entity->GetObjectID(), cloneId); - launcher->Launch(entity, launcher->GetTargetZone(), cloneId); + launcher->Launch(entity, launcher->GetTargetZone(), cloneId); } PropertySelectQueryProperty PropertyEntranceComponent::SetPropertyValues(PropertySelectQueryProperty property, LWOCLONEID cloneId, std::string ownerName, std::string propertyName, std::string propertyDescription, float reputation, bool isBFF, bool isFriend, bool isModeratorApproved, bool isAlt, bool isOwned, uint32_t privacyOption, uint32_t timeLastUpdated, float performanceCost) { - property.CloneId = cloneId; - property.OwnerName = ownerName; - property.Name = propertyName; - property.Description = propertyDescription; - property.Reputation = reputation; - property.IsBestFriend = isBFF; - property.IsFriend = isFriend; - property.IsModeratorApproved = isModeratorApproved; - property.IsAlt = isAlt; - property.IsOwned = isOwned; - property.AccessType = privacyOption; - property.DateLastPublished = timeLastUpdated; - property.PerformanceCost = performanceCost; + property.CloneId = cloneId; + property.OwnerName = ownerName; + property.Name = propertyName; + property.Description = propertyDescription; + property.Reputation = reputation; + property.IsBestFriend = isBFF; + property.IsFriend = isFriend; + property.IsModeratorApproved = isModeratorApproved; + property.IsAlt = isAlt; + property.IsOwned = isOwned; + property.AccessType = privacyOption; + property.DateLastPublished = timeLastUpdated; + property.PerformanceCost = performanceCost; - return property; + return property; } std::string PropertyEntranceComponent::BuildQuery(Entity* entity, int32_t sortMethod, Character* character, std::string customQuery, bool wantLimits) { - std::string base; - if (customQuery == "") { - base = baseQueryForProperties; - } else { - base = customQuery; - } - std::string orderBy = ""; - if (sortMethod == SORT_TYPE_FEATURED || sortMethod == SORT_TYPE_FRIENDS) { - std::string friendsList = " AND p.owner_id IN ("; + std::string base; + if (customQuery == "") { + base = baseQueryForProperties; + } else { + base = customQuery; + } + std::string orderBy = ""; + if (sortMethod == SORT_TYPE_FEATURED || sortMethod == SORT_TYPE_FRIENDS) { + std::string friendsList = " AND p.owner_id IN ("; - auto friendsListQuery = Database::CreatePreppedStmt("SELECT * FROM (SELECT CASE WHEN player_id = ? THEN friend_id WHEN friend_id = ? THEN player_id END AS requested_player FROM friends ) AS fr WHERE requested_player IS NOT NULL ORDER BY requested_player DESC;"); + auto friendsListQuery = Database::CreatePreppedStmt("SELECT * FROM (SELECT CASE WHEN player_id = ? THEN friend_id WHEN friend_id = ? THEN player_id END AS requested_player FROM friends ) AS fr WHERE requested_player IS NOT NULL ORDER BY requested_player DESC;"); - friendsListQuery->setUInt(1, character->GetID()); - friendsListQuery->setUInt(2, character->GetID()); + friendsListQuery->setUInt(1, character->GetID()); + friendsListQuery->setUInt(2, character->GetID()); - auto friendsListQueryResult = friendsListQuery->executeQuery(); + auto friendsListQueryResult = friendsListQuery->executeQuery(); - while (friendsListQueryResult->next()) { - auto playerIDToConvert = friendsListQueryResult->getInt(1); - friendsList = friendsList + std::to_string(playerIDToConvert) + ","; - } - // Replace trailing comma with the closing parenthesis. - if (friendsList.at(friendsList.size() - 1) == ',') friendsList.erase(friendsList.size() - 1, 1); - friendsList += ") "; + while (friendsListQueryResult->next()) { + auto playerIDToConvert = friendsListQueryResult->getInt(1); + friendsList = friendsList + std::to_string(playerIDToConvert) + ","; + } + // Replace trailing comma with the closing parenthesis. + if (friendsList.at(friendsList.size() - 1) == ',') friendsList.erase(friendsList.size() - 1, 1); + friendsList += ") "; - // If we have no friends then use a -1 for the query. - if (friendsList.find("()") != std::string::npos) friendsList = " AND p.owner_id IN (-1) "; + // If we have no friends then use a -1 for the query. + if (friendsList.find("()") != std::string::npos) friendsList = " AND p.owner_id IN (-1) "; - orderBy += friendsList + "ORDER BY ci.name ASC "; + orderBy += friendsList + "ORDER BY ci.name ASC "; - delete friendsListQueryResult; - friendsListQueryResult = nullptr; + delete friendsListQueryResult; + friendsListQueryResult = nullptr; - delete friendsListQuery; - friendsListQuery = nullptr; - } - else if (sortMethod == SORT_TYPE_RECENT) { - orderBy = "ORDER BY p.last_updated DESC "; - } - else if (sortMethod == SORT_TYPE_REPUTATION) { - orderBy = "ORDER BY p.reputation DESC, p.last_updated DESC "; - } - else { - orderBy = "ORDER BY p.last_updated DESC "; - } - return base + orderBy + (wantLimits ? "LIMIT ? OFFSET ?;" : ";"); + delete friendsListQuery; + friendsListQuery = nullptr; + } else if (sortMethod == SORT_TYPE_RECENT) { + orderBy = "ORDER BY p.last_updated DESC "; + } else if (sortMethod == SORT_TYPE_REPUTATION) { + orderBy = "ORDER BY p.reputation DESC, p.last_updated DESC "; + } else { + orderBy = "ORDER BY p.last_updated DESC "; + } + return base + orderBy + (wantLimits ? "LIMIT ? OFFSET ?;" : ";"); } -void PropertyEntranceComponent::OnPropertyEntranceSync(Entity* entity, bool includeNullAddress, bool includeNullDescription, bool playerOwn, bool updateUi, int32_t numResults, int32_t lReputationTime, int32_t sortMethod, int32_t startIndex, std::string filterText, const SystemAddress& sysAddr){ +void PropertyEntranceComponent::OnPropertyEntranceSync(Entity* entity, bool includeNullAddress, bool includeNullDescription, bool playerOwn, bool updateUi, int32_t numResults, int32_t lReputationTime, int32_t sortMethod, int32_t startIndex, std::string filterText, const SystemAddress& sysAddr) { - std::vector entries {}; - PropertySelectQueryProperty playerEntry {}; + std::vector entries{}; + PropertySelectQueryProperty playerEntry{}; - auto character = entity->GetCharacter(); - if (!character) return; + auto character = entity->GetCharacter(); + if (!character) return; - // Player property goes in index 1 of the vector. This is how the client expects it. - auto playerPropertyLookup = Database::CreatePreppedStmt("SELECT * FROM properties WHERE owner_id = ? AND zone_id = ?"); + // Player property goes in index 1 of the vector. This is how the client expects it. + auto playerPropertyLookup = Database::CreatePreppedStmt("SELECT * FROM properties WHERE owner_id = ? AND zone_id = ?"); - playerPropertyLookup->setInt(1, character->GetID()); - playerPropertyLookup->setInt(2, this->m_MapID); + playerPropertyLookup->setInt(1, character->GetID()); + playerPropertyLookup->setInt(2, this->m_MapID); - auto playerPropertyLookupResults = playerPropertyLookup->executeQuery(); + auto playerPropertyLookupResults = playerPropertyLookup->executeQuery(); - // If the player has a property this query will have a single result. - if (playerPropertyLookupResults->next()) { - const auto cloneId = playerPropertyLookupResults->getUInt64(4); - const auto propertyName = std::string(playerPropertyLookupResults->getString(5).c_str()); - const auto propertyDescription = std::string(playerPropertyLookupResults->getString(6).c_str()); - const auto privacyOption = playerPropertyLookupResults->getInt(9); - const auto modApproved = playerPropertyLookupResults->getBoolean(10); - const auto dateLastUpdated = playerPropertyLookupResults->getInt64(11); - const auto reputation = playerPropertyLookupResults->getUInt(14); - const auto performanceCost = (float)playerPropertyLookupResults->getDouble(16); + // If the player has a property this query will have a single result. + if (playerPropertyLookupResults->next()) { + const auto cloneId = playerPropertyLookupResults->getUInt64(4); + const auto propertyName = std::string(playerPropertyLookupResults->getString(5).c_str()); + const auto propertyDescription = std::string(playerPropertyLookupResults->getString(6).c_str()); + const auto privacyOption = playerPropertyLookupResults->getInt(9); + const auto modApproved = playerPropertyLookupResults->getBoolean(10); + const auto dateLastUpdated = playerPropertyLookupResults->getInt64(11); + const auto reputation = playerPropertyLookupResults->getUInt(14); + const auto performanceCost = (float)playerPropertyLookupResults->getDouble(16); - playerEntry = SetPropertyValues(playerEntry, cloneId, character->GetName(), propertyName, propertyDescription, reputation, true, true, modApproved, true, true, privacyOption, dateLastUpdated, performanceCost); - } else { - playerEntry = SetPropertyValues(playerEntry, character->GetPropertyCloneID(), character->GetName(), "", "", 0, true, true); - } + playerEntry = SetPropertyValues(playerEntry, cloneId, character->GetName(), propertyName, propertyDescription, reputation, true, true, modApproved, true, true, privacyOption, dateLastUpdated, performanceCost); + } else { + playerEntry = SetPropertyValues(playerEntry, character->GetPropertyCloneID(), character->GetName(), "", "", 0, true, true); + } - delete playerPropertyLookupResults; - playerPropertyLookupResults = nullptr; + delete playerPropertyLookupResults; + playerPropertyLookupResults = nullptr; - delete playerPropertyLookup; - playerPropertyLookup = nullptr; + delete playerPropertyLookup; + playerPropertyLookup = nullptr; - entries.push_back(playerEntry); + entries.push_back(playerEntry); - const auto query = BuildQuery(entity, sortMethod, character); + const auto query = BuildQuery(entity, sortMethod, character); - auto propertyLookup = Database::CreatePreppedStmt(query); + auto propertyLookup = Database::CreatePreppedStmt(query); - const auto searchString = "%" + filterText + "%"; - propertyLookup->setUInt(1, this->m_MapID); - propertyLookup->setString(2, searchString.c_str()); - propertyLookup->setString(3, searchString.c_str()); - propertyLookup->setString(4, searchString.c_str()); - propertyLookup->setInt(5, sortMethod == SORT_TYPE_FEATURED || sortMethod == SORT_TYPE_FRIENDS ? (uint32_t)PropertyPrivacyOption::Friends : (uint32_t)PropertyPrivacyOption::Public); - propertyLookup->setInt(6, numResults); - propertyLookup->setInt(7, startIndex); + const auto searchString = "%" + filterText + "%"; + propertyLookup->setUInt(1, this->m_MapID); + propertyLookup->setString(2, searchString.c_str()); + propertyLookup->setString(3, searchString.c_str()); + propertyLookup->setString(4, searchString.c_str()); + propertyLookup->setInt(5, sortMethod == SORT_TYPE_FEATURED || sortMethod == SORT_TYPE_FRIENDS ? (uint32_t)PropertyPrivacyOption::Friends : (uint32_t)PropertyPrivacyOption::Public); + propertyLookup->setInt(6, numResults); + propertyLookup->setInt(7, startIndex); - auto propertyEntry = propertyLookup->executeQuery(); + auto propertyEntry = propertyLookup->executeQuery(); - while (propertyEntry->next()) { - const auto propertyId = propertyEntry->getUInt64(1); - const auto owner = propertyEntry->getInt(2); - const auto cloneId = propertyEntry->getUInt64(4); - const auto propertyNameFromDb = std::string(propertyEntry->getString(5).c_str()); - const auto propertyDescriptionFromDb = std::string(propertyEntry->getString(6).c_str()); - const auto privacyOption = propertyEntry->getInt(9); - const auto modApproved = propertyEntry->getBoolean(10); - const auto dateLastUpdated = propertyEntry->getInt(11); - const float reputation = propertyEntry->getInt(14); - const auto performanceCost = (float)propertyEntry->getDouble(16); + while (propertyEntry->next()) { + const auto propertyId = propertyEntry->getUInt64(1); + const auto owner = propertyEntry->getInt(2); + const auto cloneId = propertyEntry->getUInt64(4); + const auto propertyNameFromDb = std::string(propertyEntry->getString(5).c_str()); + const auto propertyDescriptionFromDb = std::string(propertyEntry->getString(6).c_str()); + const auto privacyOption = propertyEntry->getInt(9); + const auto modApproved = propertyEntry->getBoolean(10); + const auto dateLastUpdated = propertyEntry->getInt(11); + const float reputation = propertyEntry->getInt(14); + const auto performanceCost = (float)propertyEntry->getDouble(16); - PropertySelectQueryProperty entry{}; + PropertySelectQueryProperty entry{}; - std::string ownerName = ""; - bool isOwned = true; - auto nameLookup = Database::CreatePreppedStmt("SELECT name FROM charinfo WHERE prop_clone_id = ?;"); + std::string ownerName = ""; + bool isOwned = true; + auto nameLookup = Database::CreatePreppedStmt("SELECT name FROM charinfo WHERE prop_clone_id = ?;"); - nameLookup->setUInt64(1, cloneId); + nameLookup->setUInt64(1, cloneId); - auto nameResult = nameLookup->executeQuery(); + auto nameResult = nameLookup->executeQuery(); - if (!nameResult->next()) { - delete nameLookup; - nameLookup = nullptr; + if (!nameResult->next()) { + delete nameLookup; + nameLookup = nullptr; - Game::logger->Log("PropertyEntranceComponent", "Failed to find property owner name for %llu!", cloneId); + Game::logger->Log("PropertyEntranceComponent", "Failed to find property owner name for %llu!", cloneId); - continue; - } else { - isOwned = cloneId == character->GetPropertyCloneID(); - ownerName = std::string(nameResult->getString(1).c_str()); - } + continue; + } else { + isOwned = cloneId == character->GetPropertyCloneID(); + ownerName = std::string(nameResult->getString(1).c_str()); + } - delete nameResult; - nameResult = nullptr; + delete nameResult; + nameResult = nullptr; - delete nameLookup; - nameLookup = nullptr; + delete nameLookup; + nameLookup = nullptr; - std::string propertyName = propertyNameFromDb; - std::string propertyDescription = propertyDescriptionFromDb; + std::string propertyName = propertyNameFromDb; + std::string propertyDescription = propertyDescriptionFromDb; - bool isBestFriend = false; - bool isFriend = false; + bool isBestFriend = false; + bool isFriend = false; - // Convert owner char id to LWOOBJID - LWOOBJID ownerObjId = owner; - ownerObjId = GeneralUtils::SetBit(ownerObjId, OBJECT_BIT_CHARACTER); - ownerObjId = GeneralUtils::SetBit(ownerObjId, OBJECT_BIT_PERSISTENT); + // Convert owner char id to LWOOBJID + LWOOBJID ownerObjId = owner; + ownerObjId = GeneralUtils::SetBit(ownerObjId, OBJECT_BIT_CHARACTER); + ownerObjId = GeneralUtils::SetBit(ownerObjId, OBJECT_BIT_PERSISTENT); - // Query to get friend and best friend fields - auto friendCheck = Database::CreatePreppedStmt("SELECT best_friend FROM friends WHERE (player_id = ? AND friend_id = ?) OR (player_id = ? AND friend_id = ?)"); + // Query to get friend and best friend fields + auto friendCheck = Database::CreatePreppedStmt("SELECT best_friend FROM friends WHERE (player_id = ? AND friend_id = ?) OR (player_id = ? AND friend_id = ?)"); - friendCheck->setUInt(1, character->GetID()); - friendCheck->setUInt(2, ownerObjId); - friendCheck->setUInt(3, ownerObjId); - friendCheck->setUInt(4, character->GetID()); + friendCheck->setUInt(1, character->GetID()); + friendCheck->setUInt(2, ownerObjId); + friendCheck->setUInt(3, ownerObjId); + friendCheck->setUInt(4, character->GetID()); - auto friendResult = friendCheck->executeQuery(); + auto friendResult = friendCheck->executeQuery(); - // If we got a result than the two players are friends. - if (friendResult->next()) { - isFriend = true; - if (friendResult->getInt(1) == 3) { - isBestFriend = true; - } - } + // If we got a result than the two players are friends. + if (friendResult->next()) { + isFriend = true; + if (friendResult->getInt(1) == 3) { + isBestFriend = true; + } + } - delete friendCheck; - friendCheck = nullptr; + delete friendCheck; + friendCheck = nullptr; - delete friendResult; - friendResult = nullptr; + delete friendResult; + friendResult = nullptr; - bool isModeratorApproved = propertyEntry->getBoolean(10); + bool isModeratorApproved = propertyEntry->getBoolean(10); - if (!isModeratorApproved && entity->GetGMLevel() >= GAME_MASTER_LEVEL_LEAD_MODERATOR) { - propertyName = "[AWAITING APPROVAL]"; - propertyDescription = "[AWAITING APPROVAL]"; - isModeratorApproved = true; - } + if (!isModeratorApproved && entity->GetGMLevel() >= GAME_MASTER_LEVEL_LEAD_MODERATOR) { + propertyName = "[AWAITING APPROVAL]"; + propertyDescription = "[AWAITING APPROVAL]"; + isModeratorApproved = true; + } - bool isAlt = false; - // Query to determine whether this property is an alt character of the entity. - auto isAltQuery = Database::CreatePreppedStmt("SELECT id FROM charinfo where account_id in (SELECT account_id from charinfo WHERE id = ?) AND id = ?;"); + bool isAlt = false; + // Query to determine whether this property is an alt character of the entity. + auto isAltQuery = Database::CreatePreppedStmt("SELECT id FROM charinfo where account_id in (SELECT account_id from charinfo WHERE id = ?) AND id = ?;"); - isAltQuery->setInt(1, character->GetID()); - isAltQuery->setInt(2, owner); + isAltQuery->setInt(1, character->GetID()); + isAltQuery->setInt(2, owner); - auto isAltQueryResults = isAltQuery->executeQuery(); + auto isAltQueryResults = isAltQuery->executeQuery(); - if (isAltQueryResults->next()) { - isAlt = true; - } + if (isAltQueryResults->next()) { + isAlt = true; + } - delete isAltQueryResults; - isAltQueryResults = nullptr; + delete isAltQueryResults; + isAltQueryResults = nullptr; - delete isAltQuery; - isAltQuery = nullptr; + delete isAltQuery; + isAltQuery = nullptr; - entry = SetPropertyValues(entry, cloneId, ownerName, propertyName, propertyDescription, reputation, isBestFriend, isFriend, isModeratorApproved, isAlt, isOwned, privacyOption, dateLastUpdated, performanceCost); + entry = SetPropertyValues(entry, cloneId, ownerName, propertyName, propertyDescription, reputation, isBestFriend, isFriend, isModeratorApproved, isAlt, isOwned, privacyOption, dateLastUpdated, performanceCost); - entries.push_back(entry); - } + entries.push_back(entry); + } - delete propertyEntry; - propertyEntry = nullptr; + delete propertyEntry; + propertyEntry = nullptr; - delete propertyLookup; - propertyLookup = nullptr; + delete propertyLookup; + propertyLookup = nullptr; - propertyQueries[entity->GetObjectID()] = entries; + propertyQueries[entity->GetObjectID()] = entries; - // Query here is to figure out whether or not to display the button to go to the next page or not. - int32_t numberOfProperties = 0; + // Query here is to figure out whether or not to display the button to go to the next page or not. + int32_t numberOfProperties = 0; - auto buttonQuery = BuildQuery(entity, sortMethod, character, "SELECT COUNT(*) FROM properties as p JOIN charinfo as ci ON ci.prop_clone_id = p.clone_id where p.zone_id = ? AND (p.description LIKE ? OR p.name LIKE ? OR ci.name LIKE ?) AND p.privacy_option >= ? ", false); - auto propertiesLeft = Database::CreatePreppedStmt(buttonQuery); + auto buttonQuery = BuildQuery(entity, sortMethod, character, "SELECT COUNT(*) FROM properties as p JOIN charinfo as ci ON ci.prop_clone_id = p.clone_id where p.zone_id = ? AND (p.description LIKE ? OR p.name LIKE ? OR ci.name LIKE ?) AND p.privacy_option >= ? ", false); + auto propertiesLeft = Database::CreatePreppedStmt(buttonQuery); - propertiesLeft->setUInt(1, this->m_MapID); - propertiesLeft->setString(2, searchString.c_str()); - propertiesLeft->setString(3, searchString.c_str()); - propertiesLeft->setString(4, searchString.c_str()); - propertiesLeft->setInt(5, sortMethod == SORT_TYPE_FEATURED || sortMethod == SORT_TYPE_FRIENDS ? 1 : 2); + propertiesLeft->setUInt(1, this->m_MapID); + propertiesLeft->setString(2, searchString.c_str()); + propertiesLeft->setString(3, searchString.c_str()); + propertiesLeft->setString(4, searchString.c_str()); + propertiesLeft->setInt(5, sortMethod == SORT_TYPE_FEATURED || sortMethod == SORT_TYPE_FRIENDS ? 1 : 2); - auto result = propertiesLeft->executeQuery(); - result->next(); - numberOfProperties = result->getInt(1); + auto result = propertiesLeft->executeQuery(); + result->next(); + numberOfProperties = result->getInt(1); - delete result; - result = nullptr; + delete result; + result = nullptr; - delete propertiesLeft; - propertiesLeft = nullptr; + delete propertiesLeft; + propertiesLeft = nullptr; - GameMessages::SendPropertySelectQuery(m_Parent->GetObjectID(), startIndex, numberOfProperties - (startIndex + numResults) > 0, character->GetPropertyCloneID(), false, true, entries, sysAddr); + GameMessages::SendPropertySelectQuery(m_Parent->GetObjectID(), startIndex, numberOfProperties - (startIndex + numResults) > 0, character->GetPropertyCloneID(), false, true, entries, sysAddr); } diff --git a/dGame/dComponents/PropertyEntranceComponent.h b/dGame/dComponents/PropertyEntranceComponent.h index fe583e92..6087faf2 100644 --- a/dGame/dComponents/PropertyEntranceComponent.h +++ b/dGame/dComponents/PropertyEntranceComponent.h @@ -11,79 +11,79 @@ * Represents the launch pad that's used to select and browse properties */ class PropertyEntranceComponent : public Component { - public: - static const uint32_t ComponentType = COMPONENT_TYPE_PROPERTY_ENTRANCE; - explicit PropertyEntranceComponent(uint32_t componentID, Entity* parent); +public: + static const uint32_t ComponentType = COMPONENT_TYPE_PROPERTY_ENTRANCE; + explicit PropertyEntranceComponent(uint32_t componentID, Entity* parent); - /** - * Handles an OnUse request for some other entity, rendering the property browse menu - * @param entity the entity that triggered the event - */ - void OnUse(Entity* entity) override; + /** + * Handles an OnUse request for some other entity, rendering the property browse menu + * @param entity the entity that triggered the event + */ + void OnUse(Entity* entity) override; - /** - * Handles the event triggered when the entity selects a property to visit and makes the entity to there - * @param entity the entity that triggered the event - * @param index the index of the property property - * @param returnToZone whether or not the entity wishes to go back to the launch zone - * @param sysAddr the address to send gamemessage responses to - */ - void OnEnterProperty(Entity* entity, uint32_t index, bool returnToZone, const SystemAddress& sysAddr); + /** + * Handles the event triggered when the entity selects a property to visit and makes the entity to there + * @param entity the entity that triggered the event + * @param index the index of the property property + * @param returnToZone whether or not the entity wishes to go back to the launch zone + * @param sysAddr the address to send gamemessage responses to + */ + void OnEnterProperty(Entity* entity, uint32_t index, bool returnToZone, const SystemAddress& sysAddr); - /** - * Handles a request for information on available properties when an entity lands on the property - * @param entity the entity that triggered the event - * @param includeNullAddress unused - * @param includeNullDescription unused - * @param playerOwn only query properties owned by the entity - * @param updateUi unused - * @param numResults unused - * @param lReputationTime unused - * @param sortMethod unused - * @param startIndex the minimum index to start the query off - * @param filterText property names to search for - * @param sysAddr the address to send gamemessage responses to - */ - void OnPropertyEntranceSync(Entity* entity, bool includeNullAddress, bool includeNullDescription, bool playerOwn, bool updateUi, int32_t numResults, int32_t lReputationTime, int32_t sortMethod, int32_t startIndex, std::string filterText, const SystemAddress& sysAddr); + /** + * Handles a request for information on available properties when an entity lands on the property + * @param entity the entity that triggered the event + * @param includeNullAddress unused + * @param includeNullDescription unused + * @param playerOwn only query properties owned by the entity + * @param updateUi unused + * @param numResults unused + * @param lReputationTime unused + * @param sortMethod unused + * @param startIndex the minimum index to start the query off + * @param filterText property names to search for + * @param sysAddr the address to send gamemessage responses to + */ + void OnPropertyEntranceSync(Entity* entity, bool includeNullAddress, bool includeNullDescription, bool playerOwn, bool updateUi, int32_t numResults, int32_t lReputationTime, int32_t sortMethod, int32_t startIndex, std::string filterText, const SystemAddress& sysAddr); - /** - * Returns the name of this property - * @return the name of this property - */ - [[nodiscard]] std::string GetPropertyName() const { return m_PropertyName; }; + /** + * Returns the name of this property + * @return the name of this property + */ + [[nodiscard]] std::string GetPropertyName() const { return m_PropertyName; }; - /** - * Returns the map ID for this property - * @return the map ID for this property - */ - [[nodiscard]] LWOMAPID GetMapID() const { return m_MapID; }; + /** + * Returns the map ID for this property + * @return the map ID for this property + */ + [[nodiscard]] LWOMAPID GetMapID() const { return m_MapID; }; - PropertySelectQueryProperty SetPropertyValues(PropertySelectQueryProperty property, LWOCLONEID cloneId = LWOCLONEID_INVALID, std::string ownerName = "", std::string propertyName = "", std::string propertyDescription = "", float reputation = 0, bool isBFF = false, bool isFriend = false, bool isModeratorApproved = false, bool isAlt = false, bool isOwned = false, uint32_t privacyOption = 0, uint32_t timeLastUpdated = 0, float performanceCost = 0.0f); + PropertySelectQueryProperty SetPropertyValues(PropertySelectQueryProperty property, LWOCLONEID cloneId = LWOCLONEID_INVALID, std::string ownerName = "", std::string propertyName = "", std::string propertyDescription = "", float reputation = 0, bool isBFF = false, bool isFriend = false, bool isModeratorApproved = false, bool isAlt = false, bool isOwned = false, uint32_t privacyOption = 0, uint32_t timeLastUpdated = 0, float performanceCost = 0.0f); - std::string BuildQuery(Entity* entity, int32_t sortMethod, Character* character, std::string customQuery = "", bool wantLimits = true); + std::string BuildQuery(Entity* entity, int32_t sortMethod, Character* character, std::string customQuery = "", bool wantLimits = true); - private: - /** - * Cache of property information that was queried for property launched, indexed by property ID - */ - std::map> propertyQueries; +private: + /** + * Cache of property information that was queried for property launched, indexed by property ID + */ + std::map> propertyQueries; - /** - * The custom name for this property - */ - std::string m_PropertyName; + /** + * The custom name for this property + */ + std::string m_PropertyName; - /** - * The base map ID for this property (Avant Grove, etc). - */ - LWOMAPID m_MapID; + /** + * The base map ID for this property (Avant Grove, etc). + */ + LWOMAPID m_MapID; - enum ePropertySortType : int32_t { - SORT_TYPE_FRIENDS = 0, - SORT_TYPE_REPUTATION = 1, - SORT_TYPE_RECENT = 3, - SORT_TYPE_FEATURED = 5 - }; + enum ePropertySortType : int32_t { + SORT_TYPE_FRIENDS = 0, + SORT_TYPE_REPUTATION = 1, + SORT_TYPE_RECENT = 3, + SORT_TYPE_FEATURED = 5 + }; - std::string baseQueryForProperties = "SELECT p.* FROM properties as p JOIN charinfo as ci ON ci.prop_clone_id = p.clone_id where p.zone_id = ? AND (p.description LIKE ? OR p.name LIKE ? OR ci.name LIKE ?) AND p.privacy_option >= ? "; + std::string baseQueryForProperties = "SELECT p.* FROM properties as p JOIN charinfo as ci ON ci.prop_clone_id = p.clone_id where p.zone_id = ? AND (p.description LIKE ? OR p.name LIKE ? OR ci.name LIKE ?) AND p.privacy_option >= ? "; }; diff --git a/dGame/dComponents/PropertyManagementComponent.cpp b/dGame/dComponents/PropertyManagementComponent.cpp index fa9a7e52..bc3d8395 100644 --- a/dGame/dComponents/PropertyManagementComponent.cpp +++ b/dGame/dComponents/PropertyManagementComponent.cpp @@ -23,8 +23,7 @@ PropertyManagementComponent* PropertyManagementComponent::instance = nullptr; -PropertyManagementComponent::PropertyManagementComponent(Entity* parent) : Component(parent) -{ +PropertyManagementComponent::PropertyManagementComponent(Entity* parent) : Component(parent) { this->owner = LWOOBJID_EMPTY; this->templateId = 0; this->propertyId = LWOOBJID_EMPTY; @@ -43,12 +42,11 @@ PropertyManagementComponent::PropertyManagementComponent(Entity* parent) : Compo auto query = CDClientDatabase::CreatePreppedStmt( "SELECT id FROM PropertyTemplate WHERE mapID = ?;"); - query.bind(1, (int) zoneId); + query.bind(1, (int)zoneId); auto result = query.execQuery(); - if (result.eof() || result.fieldIsNull(0)) - { + if (result.eof() || result.fieldIsNull(0)) { return; } @@ -63,8 +61,7 @@ PropertyManagementComponent::PropertyManagementComponent(Entity* parent) : Compo auto* propertyEntry = propertyLookup->executeQuery(); - if (propertyEntry->next()) - { + if (propertyEntry->next()) { this->propertyId = propertyEntry->getUInt64(1); this->owner = propertyEntry->getUInt64(2); this->owner = GeneralUtils::SetBit(this->owner, OBJECT_BIT_CHARACTER); @@ -85,35 +82,30 @@ PropertyManagementComponent::PropertyManagementComponent(Entity* parent) : Compo delete propertyLookup; } -LWOOBJID PropertyManagementComponent::GetOwnerId() const -{ +LWOOBJID PropertyManagementComponent::GetOwnerId() const { return owner; } -Entity* PropertyManagementComponent::GetOwner() const -{ +Entity* PropertyManagementComponent::GetOwner() const { return EntityManager::Instance()->GetEntity(owner); } -void PropertyManagementComponent::SetOwner(Entity* value) -{ +void PropertyManagementComponent::SetOwner(Entity* value) { owner = value->GetObjectID(); } -std::vector PropertyManagementComponent::GetPaths() const -{ +std::vector PropertyManagementComponent::GetPaths() const { const auto zoneId = dZoneManager::Instance()->GetZone()->GetWorldID(); auto query = CDClientDatabase::CreatePreppedStmt( "SELECT path FROM PropertyTemplate WHERE mapID = ?;"); - query.bind(1, (int) zoneId); + query.bind(1, (int)zoneId); auto result = query.execQuery(); - std::vector paths {}; + std::vector paths{}; - if (result.eof()) - { + if (result.eof()) { return paths; } @@ -122,35 +114,28 @@ std::vector PropertyManagementComponent::GetPaths() const std::istringstream stream(result.getStringField(0)); std::string token; - while (std::getline(stream, token, ' ')) - { - try - { + while (std::getline(stream, token, ' ')) { + try { auto value = std::stof(token); points.push_back(value); - } - catch (std::invalid_argument& exception) - { + } catch (std::invalid_argument& exception) { Game::logger->Log("PropertyManagementComponent", "Failed to parse value (%s): (%s)!", token.c_str(), exception.what()); } } - for (auto i = 0u; i < points.size(); i += 3) - { + for (auto i = 0u; i < points.size(); i += 3) { paths.emplace_back(points[i], points[i + 1], points[i + 2]); } return paths; } -PropertyPrivacyOption PropertyManagementComponent::GetPrivacyOption() const -{ +PropertyPrivacyOption PropertyManagementComponent::GetPrivacyOption() const { return privacyOption; } -void PropertyManagementComponent::SetPrivacyOption(PropertyPrivacyOption value) -{ +void PropertyManagementComponent::SetPrivacyOption(PropertyPrivacyOption value) { if (owner == LWOOBJID_EMPTY) return; if (value == static_cast(3)) // Client sends 3 for private for some reason, but expects 0 in return? @@ -174,8 +159,7 @@ void PropertyManagementComponent::SetPrivacyOption(PropertyPrivacyOption value) propertyUpdate->executeUpdate(); } -void PropertyManagementComponent::UpdatePropertyDetails(std::string name, std::string description) -{ +void PropertyManagementComponent::UpdatePropertyDetails(std::string name, std::string description) { if (owner == LWOOBJID_EMPTY) return; propertyName = name; @@ -193,10 +177,8 @@ void PropertyManagementComponent::UpdatePropertyDetails(std::string name, std::s OnQueryPropertyData(GetOwner(), UNASSIGNED_SYSTEM_ADDRESS); } -bool PropertyManagementComponent::Claim(const LWOOBJID playerId) -{ - if (owner != LWOOBJID_EMPTY) - { +bool PropertyManagementComponent::Claim(const LWOOBJID playerId) { + if (owner != LWOOBJID_EMPTY) { return false; } @@ -228,19 +210,16 @@ bool PropertyManagementComponent::Claim(const LWOOBJID playerId) "VALUES (?, ?, ?, ?, ?, '', 0, 0, 0, UNIX_TIMESTAMP(), UNIX_TIMESTAMP(), '', 0, ?, 0.0)" ); insertion->setUInt64(1, propertyId); - insertion->setUInt64(2, (uint32_t) playerId); + insertion->setUInt64(2, (uint32_t)playerId); insertion->setUInt(3, templateId); insertion->setUInt64(4, playerCloneId); insertion->setString(5, zone->GetZoneName().c_str()); insertion->setInt(6, propertyZoneId); // Try and execute the query, print an error if it fails. - try - { + try { insertion->execute(); - } - catch (sql::SQLException& exception) - { + } catch (sql::SQLException& exception) { Game::logger->Log("PropertyManagementComponent", "Failed to execute query: (%s)!", exception.what()); throw exception; @@ -248,14 +227,13 @@ bool PropertyManagementComponent::Claim(const LWOOBJID playerId) } auto* zoneControlObject = dZoneManager::Instance()->GetZoneControlObject(); - for (CppScripts::Script* script : CppScripts::GetEntityScripts(zoneControlObject)) { - script->OnZonePropertyRented(zoneControlObject, entity); - } + for (CppScripts::Script* script : CppScripts::GetEntityScripts(zoneControlObject)) { + script->OnZonePropertyRented(zoneControlObject, entity); + } return true; } -void PropertyManagementComponent::OnStartBuilding() -{ +void PropertyManagementComponent::OnStartBuilding() { auto* ownerEntity = GetOwner(); if (ownerEntity == nullptr) return; @@ -270,18 +248,15 @@ void PropertyManagementComponent::OnStartBuilding() SetPrivacyOption(PropertyPrivacyOption::Private); // Cant visit player which is building - if (!entrance.empty()) - { + if (!entrance.empty()) { auto* rocketPad = entrance[0]->GetComponent(); - if (rocketPad != nullptr) - { + if (rocketPad != nullptr) { zoneId = rocketPad->GetDefaultZone(); } } - for (auto* player : players) - { + for (auto* player : players) { if (player == ownerEntity) continue; player->SendToZone(zoneId); @@ -292,8 +267,7 @@ void PropertyManagementComponent::OnStartBuilding() if (inventoryComponent) inventoryComponent->PushEquippedItems(); } -void PropertyManagementComponent::OnFinishBuilding() -{ +void PropertyManagementComponent::OnFinishBuilding() { auto* ownerEntity = GetOwner(); if (ownerEntity == nullptr) return; @@ -305,28 +279,24 @@ void PropertyManagementComponent::OnFinishBuilding() Save(); } -void PropertyManagementComponent::UpdateModelPosition(const LWOOBJID id, const NiPoint3 position, NiQuaternion rotation) -{ +void PropertyManagementComponent::UpdateModelPosition(const LWOOBJID id, const NiPoint3 position, NiQuaternion rotation) { Game::logger->Log("PropertyManagementComponent", "Placing model <%f, %f, %f>", position.x, position.y, position.z); auto* entity = GetOwner(); - if (entity == nullptr) - { + if (entity == nullptr) { return; } auto* inventoryComponent = entity->GetComponent(); - if (inventoryComponent == nullptr) - { + if (inventoryComponent == nullptr) { return; } auto* item = inventoryComponent->FindItemById(id); - if (item == nullptr) - { + if (item == nullptr) { Game::logger->Log("PropertyManagementComponent", "Failed to find item with id %d", id); return; @@ -336,8 +306,7 @@ void PropertyManagementComponent::UpdateModelPosition(const LWOOBJID id, const N const auto modelLOT = item->GetLot(); - if (rotation != NiQuaternion::IDENTITY) - { + if (rotation != NiQuaternion::IDENTITY) { rotation = { rotation.w, rotation.z, rotation.y, rotation.x }; } @@ -377,78 +346,73 @@ void PropertyManagementComponent::UpdateModelPosition(const LWOOBJID id, const N node->position = position; node->rotation = rotation; - ObjectIDManager::Instance()->RequestPersistentID([this, node, modelLOT, entity, position, rotation, originalRotation](uint32_t persistentId) - { - SpawnerInfo info{}; + ObjectIDManager::Instance()->RequestPersistentID([this, node, modelLOT, entity, position, rotation, originalRotation](uint32_t persistentId) { + SpawnerInfo info{}; - info.templateID = modelLOT; - info.nodes = { node }; - info.templateScale = 1.0f; - info.activeOnLoad = true; - info.amountMaintained = 1; - info.respawnTime = 10; + info.templateID = modelLOT; + info.nodes = { node }; + info.templateScale = 1.0f; + info.activeOnLoad = true; + info.amountMaintained = 1; + info.respawnTime = 10; - info.emulated = true; - info.emulator = EntityManager::Instance()->GetZoneControlEntity()->GetObjectID(); + info.emulated = true; + info.emulator = EntityManager::Instance()->GetZoneControlEntity()->GetObjectID(); - LWOOBJID id = static_cast(persistentId) | 1ull << OBJECT_BIT_CLIENT; + LWOOBJID id = static_cast(persistentId) | 1ull << OBJECT_BIT_CLIENT; - info.spawnerID = id; + info.spawnerID = id; - const auto spawnerId = dZoneManager::Instance()->MakeSpawner(info); + const auto spawnerId = dZoneManager::Instance()->MakeSpawner(info); - auto* spawner = dZoneManager::Instance()->GetSpawner(spawnerId); + auto* spawner = dZoneManager::Instance()->GetSpawner(spawnerId); - auto ldfModelBehavior = new LDFData(u"modelBehaviors", 0); - auto userModelID = new LDFData(u"userModelID", id); - auto modelType = new LDFData(u"modelType", 2); - auto propertyObjectID = new LDFData(u"propertyObjectID", true); - auto componentWhitelist = new LDFData(u"componentWhitelist", 1); - info.nodes[0]->config.push_back(componentWhitelist); - info.nodes[0]->config.push_back(ldfModelBehavior); - info.nodes[0]->config.push_back(modelType); - info.nodes[0]->config.push_back(propertyObjectID); - info.nodes[0]->config.push_back(userModelID); + auto ldfModelBehavior = new LDFData(u"modelBehaviors", 0); + auto userModelID = new LDFData(u"userModelID", id); + auto modelType = new LDFData(u"modelType", 2); + auto propertyObjectID = new LDFData(u"propertyObjectID", true); + auto componentWhitelist = new LDFData(u"componentWhitelist", 1); + info.nodes[0]->config.push_back(componentWhitelist); + info.nodes[0]->config.push_back(ldfModelBehavior); + info.nodes[0]->config.push_back(modelType); + info.nodes[0]->config.push_back(propertyObjectID); + info.nodes[0]->config.push_back(userModelID); - auto* model = spawner->Spawn(); + auto* model = spawner->Spawn(); - models.insert_or_assign(model->GetObjectID(), spawnerId); + models.insert_or_assign(model->GetObjectID(), spawnerId); - GameMessages::SendPlaceModelResponse(entity->GetObjectID(), entity->GetSystemAddress(), position, m_Parent->GetObjectID(), 14, originalRotation); + GameMessages::SendPlaceModelResponse(entity->GetObjectID(), entity->GetSystemAddress(), position, m_Parent->GetObjectID(), 14, originalRotation); - GameMessages::SendUGCEquipPreCreateBasedOnEditMode(entity->GetObjectID(), entity->GetSystemAddress(), 0, spawnerId); + GameMessages::SendUGCEquipPreCreateBasedOnEditMode(entity->GetObjectID(), entity->GetSystemAddress(), 0, spawnerId); - GameMessages::SendGetModelsOnProperty(entity->GetObjectID(), GetModels(), UNASSIGNED_SYSTEM_ADDRESS); + GameMessages::SendGetModelsOnProperty(entity->GetObjectID(), GetModels(), UNASSIGNED_SYSTEM_ADDRESS); - EntityManager::Instance()->GetZoneControlEntity()->OnZonePropertyModelPlaced(entity); + EntityManager::Instance()->GetZoneControlEntity()->OnZonePropertyModelPlaced(entity); }); - // Progress place model missions - auto missionComponent = entity->GetComponent(); - if (missionComponent != nullptr) missionComponent->Progress(MissionTaskType::MISSION_TASK_TYPE_PLACE_MODEL, 0); + // Progress place model missions + auto missionComponent = entity->GetComponent(); + if (missionComponent != nullptr) missionComponent->Progress(MissionTaskType::MISSION_TASK_TYPE_PLACE_MODEL, 0); } -void PropertyManagementComponent::DeleteModel(const LWOOBJID id, const int deleteReason) -{ +void PropertyManagementComponent::DeleteModel(const LWOOBJID id, const int deleteReason) { Game::logger->Log("PropertyManagementComponent", "Delete model: (%llu) (%i)", id, deleteReason); auto* entity = GetOwner(); - if (entity == nullptr) - { + if (entity == nullptr) { return; } auto* inventoryComponent = entity->GetComponent(); - if (inventoryComponent == nullptr) - { + if (inventoryComponent == nullptr) { return; } const auto index = models.find(id); - if (index == models.end()) - { + if (index == models.end()) { Game::logger->Log("PropertyManagementComponent", "Failed to find model"); return; @@ -460,15 +424,13 @@ void PropertyManagementComponent::DeleteModel(const LWOOBJID id, const int delet models.erase(id); - if (spawner == nullptr) - { + if (spawner == nullptr) { Game::logger->Log("PropertyManagementComponent", "Failed to find spawner"); } auto* model = EntityManager::Instance()->GetEntity(id); - if (model == nullptr) - { + if (model == nullptr) { Game::logger->Log("PropertyManagementComponent", "Failed to find model entity"); return; @@ -478,8 +440,7 @@ void PropertyManagementComponent::DeleteModel(const LWOOBJID id, const int delet Game::logger->Log("PropertyManagementComponent", "Deleting model LOT %i", model->GetLOT()); - if (model->GetLOT() == 14) - { + if (model->GetLOT() == 14) { //add it to the inv std::vector settings; @@ -509,13 +470,11 @@ void PropertyManagementComponent::DeleteModel(const LWOOBJID id, const int delet return; } - if (deleteReason == 0) - { + if (deleteReason == 0) { //item->Equip(); } - if (deleteReason == 0 || deleteReason == 2) - { + if (deleteReason == 0 || deleteReason == 2) { GameMessages::SendUGCEquipPostDeleteBasedOnEditMode(entity->GetObjectID(), entity->GetSystemAddress(), item->GetId(), item->GetCount()); } @@ -523,12 +482,9 @@ void PropertyManagementComponent::DeleteModel(const LWOOBJID id, const int delet GameMessages::SendPlaceModelResponse(entity->GetObjectID(), entity->GetSystemAddress(), NiPoint3::ZERO, LWOOBJID_EMPTY, 16, NiQuaternion::IDENTITY); - if (spawner != nullptr) - { + if (spawner != nullptr) { dZoneManager::Instance()->RemoveSpawner(spawner->m_Info.spawnerID); - } - else - { + } else { model->Smash(SILENT); } @@ -545,8 +501,7 @@ void PropertyManagementComponent::DeleteModel(const LWOOBJID id, const int delet return; } - switch (deleteReason) - { + switch (deleteReason) { case 0: // Pickup { item->Equip(); @@ -580,18 +535,14 @@ void PropertyManagementComponent::DeleteModel(const LWOOBJID id, const int delet GameMessages::SendPlaceModelResponse(entity->GetObjectID(), entity->GetSystemAddress(), NiPoint3::ZERO, LWOOBJID_EMPTY, 16, NiQuaternion::IDENTITY); - if (spawner != nullptr) - { + if (spawner != nullptr) { dZoneManager::Instance()->RemoveSpawner(spawner->m_Info.spawnerID); - } - else - { + } else { model->Smash(SILENT); } } -void PropertyManagementComponent::UpdateApprovedStatus(const bool value) -{ +void PropertyManagementComponent::UpdateApprovedStatus(const bool value) { if (owner == LWOOBJID_EMPTY) return; auto* update = Database::CreatePreppedStmt("UPDATE properties SET mod_approved = ? WHERE id = ?;"); @@ -604,10 +555,8 @@ void PropertyManagementComponent::UpdateApprovedStatus(const bool value) delete update; } -void PropertyManagementComponent::Load() -{ - if (propertyId == LWOOBJID_EMPTY) - { +void PropertyManagementComponent::Load() { + if (propertyId == LWOOBJID_EMPTY) { return; } @@ -617,8 +566,7 @@ void PropertyManagementComponent::Load() auto* lookupResult = lookup->executeQuery(); - while (lookupResult->next()) - { + while (lookupResult->next()) { const LWOOBJID id = lookupResult->getUInt64(1); const LOT lot = lookupResult->getInt(2); @@ -703,10 +651,8 @@ void PropertyManagementComponent::Load() delete lookup; } -void PropertyManagementComponent::Save() -{ - if (propertyId == LWOOBJID_EMPTY) - { +void PropertyManagementComponent::Save() { + if (propertyId == LWOOBJID_EMPTY) { return; } @@ -724,8 +670,7 @@ void PropertyManagementComponent::Save() } std::vector present; - while (lookupResult->next()) - { + while (lookupResult->next()) { const auto dbId = lookupResult->getUInt64(1); present.push_back(dbId); @@ -735,24 +680,21 @@ void PropertyManagementComponent::Save() std::vector modelIds; - for (const auto& pair : models) - { + for (const auto& pair : models) { const auto id = pair.second; modelIds.push_back(id); auto* entity = EntityManager::Instance()->GetEntity(pair.first); - if (entity == nullptr) - { + if (entity == nullptr) { continue; } const auto position = entity->GetPosition(); const auto rotation = entity->GetRotation(); - if (std::find(present.begin(), present.end(), id) == present.end()) - { + if (std::find(present.begin(), present.end(), id) == present.end()) { insertion->setInt64(1, id); insertion->setUInt64(2, propertyId); insertion->setNull(3, 0); @@ -769,9 +711,7 @@ void PropertyManagementComponent::Save() } catch (sql::SQLException& ex) { Game::logger->Log("PropertyManagementComponent", "Error inserting into properties_contents. Error %s", ex.what()); } - } - else - { + } else { update->setDouble(1, position.x); update->setDouble(2, position.y); update->setDouble(3, position.z); @@ -789,10 +729,8 @@ void PropertyManagementComponent::Save() } } - for (auto id : present) - { - if (std::find(modelIds.begin(), modelIds.end(), id) != modelIds.end()) - { + for (auto id : present) { + if (std::find(modelIds.begin(), modelIds.end(), id) != modelIds.end()) { continue; } @@ -815,26 +753,23 @@ void PropertyManagementComponent::Save() delete remove; } -void PropertyManagementComponent::AddModel(LWOOBJID modelId, LWOOBJID spawnerId) -{ +void PropertyManagementComponent::AddModel(LWOOBJID modelId, LWOOBJID spawnerId) { models[modelId] = spawnerId; } -PropertyManagementComponent* PropertyManagementComponent::Instance() -{ +PropertyManagementComponent* PropertyManagementComponent::Instance() { return instance; } -void PropertyManagementComponent::OnQueryPropertyData(Entity* originator, const SystemAddress& sysAddr, LWOOBJID author) -{ +void PropertyManagementComponent::OnQueryPropertyData(Entity* originator, const SystemAddress& sysAddr, LWOOBJID author) { if (author == LWOOBJID_EMPTY) { author = m_Parent->GetObjectID(); } - const auto& worldId = dZoneManager::Instance()->GetZone()->GetZoneID(); - const auto zoneId = worldId.GetMapID(); + const auto& worldId = dZoneManager::Instance()->GetZone()->GetZoneID(); + const auto zoneId = worldId.GetMapID(); - Game::logger->Log("Properties", "Getting property info for %d", zoneId); + Game::logger->Log("Properties", "Getting property info for %d", zoneId); GameMessages::PropertyDataMessage message = GameMessages::PropertyDataMessage(zoneId); const auto isClaimed = GetOwnerId() != LWOOBJID_EMPTY; @@ -904,18 +839,15 @@ void PropertyManagementComponent::OnQueryPropertyData(Entity* originator, const // send rejection here? } -void PropertyManagementComponent::OnUse(Entity* originator) -{ +void PropertyManagementComponent::OnUse(Entity* originator) { OnQueryPropertyData(originator, UNASSIGNED_SYSTEM_ADDRESS); GameMessages::SendOpenPropertyManagment(m_Parent->GetObjectID(), originator->GetSystemAddress()); } -void PropertyManagementComponent::SetOwnerId(const LWOOBJID value) -{ +void PropertyManagementComponent::SetOwnerId(const LWOOBJID value) { owner = value; } -const std::map& PropertyManagementComponent::GetModels() const -{ +const std::map& PropertyManagementComponent::GetModels() const { return models; } diff --git a/dGame/dComponents/PropertyManagementComponent.h b/dGame/dComponents/PropertyManagementComponent.h index c03c4949..c22adc21 100644 --- a/dGame/dComponents/PropertyManagementComponent.h +++ b/dGame/dComponents/PropertyManagementComponent.h @@ -9,20 +9,20 @@ */ enum class PropertyPrivacyOption { - /** - * Default, only you can visit your property - */ + /** + * Default, only you can visit your property + */ Private = 0, - /** - * Your friends can visit your property - */ - Friends = 1, + /** + * Your friends can visit your property + */ + Friends = 1, - /** - * Requires Mythran approval, everyone can visit your property - */ - Public = 2 + /** + * Requires Mythran approval, everyone can visit your property + */ + Public = 2 }; /** @@ -33,209 +33,209 @@ class PropertyManagementComponent : public Component public: static const uint32_t ComponentType = COMPONENT_TYPE_PROPERTY_MANAGEMENT; PropertyManagementComponent(Entity* parent); - static PropertyManagementComponent* Instance(); + static PropertyManagementComponent* Instance(); - /** - * Event handler for when an entity requests information about this property, will send back whether it's owned, etc. - * @param originator the entity that triggered the event - * @param sysAddr the address to send game message responses to - * @param author optional explicit ID for the property, if not set defaults to the originator - */ + /** + * Event handler for when an entity requests information about this property, will send back whether it's owned, etc. + * @param originator the entity that triggered the event + * @param sysAddr the address to send game message responses to + * @param author optional explicit ID for the property, if not set defaults to the originator + */ void OnQueryPropertyData(Entity* originator, const SystemAddress& sysAddr, LWOOBJID author = LWOOBJID_EMPTY); - /** - * Handles an OnUse event, telling the client who owns this property, etc. - * @param originator the entity that triggered the event - */ + /** + * Handles an OnUse event, telling the client who owns this property, etc. + * @param originator the entity that triggered the event + */ void OnUse(Entity* originator) override; - /** - * Sets the owner of this property - * @param value the owner to set - */ + /** + * Sets the owner of this property + * @param value the owner to set + */ void SetOwnerId(LWOOBJID value); - /** - * Returns the ID of the owner of this property - * @return the ID of the owner of this property - */ + /** + * Returns the ID of the owner of this property + * @return the ID of the owner of this property + */ LWOOBJID GetOwnerId() const; - /** - * Returns the owner of this property - * @return the owner of this property - */ + /** + * Returns the owner of this property + * @return the owner of this property + */ Entity* GetOwner() const; - /** - * sets the owner of this property - * @param value the owner to set - */ + /** + * sets the owner of this property + * @param value the owner to set + */ void SetOwner(Entity* value); - /** - * Returns the paths that this property has - * @return the paths that this property has - */ + /** + * Returns the paths that this property has + * @return the paths that this property has + */ std::vector GetPaths() const; - /** - * Returns the privacy options for this property - * @return the privacy options for this property - */ + /** + * Returns the privacy options for this property + * @return the privacy options for this property + */ PropertyPrivacyOption GetPrivacyOption() const; - /** - * Updates the privacy option for this property - * @param value the privacy option to set - */ + /** + * Updates the privacy option for this property + * @param value the privacy option to set + */ void SetPrivacyOption(PropertyPrivacyOption value); - /** - * Updates information of this property, saving it to the database - * @param name the name to set for the property - * @param description the description to set for the property - */ + /** + * Updates information of this property, saving it to the database + * @param name the name to set for the property + * @param description the description to set for the property + */ void UpdatePropertyDetails(std::string name, std::string description); - /** - * Makes this property owned by the passed player ID, storing it in the database - * @param playerId the ID of the entity that claimed the property - * - * @return If the claim is successful return true. - */ + /** + * Makes this property owned by the passed player ID, storing it in the database + * @param playerId the ID of the entity that claimed the property + * + * @return If the claim is successful return true. + */ bool Claim(LWOOBJID playerId); - /** - * Event triggered when the owner of the property starts building, will kick other entities out - */ + /** + * Event triggered when the owner of the property starts building, will kick other entities out + */ void OnStartBuilding(); - /** - * Event triggered when the owner of the property finished building, will re-apply this property for moderation - * request. - */ + /** + * Event triggered when the owner of the property finished building, will re-apply this property for moderation + * request. + */ void OnFinishBuilding(); - /** - * Updates the position of a model on the property - * @param id the ID of the model to reposition - * @param position the position to place the model on - * @param rotation the rotation to place the model on - */ + /** + * Updates the position of a model on the property + * @param id the ID of the model to reposition + * @param position the position to place the model on + * @param rotation the rotation to place the model on + */ void UpdateModelPosition(LWOOBJID id, NiPoint3 position, NiQuaternion rotation); - /** - * Deletes a model for a property - * @param id the ID of the model to delete - * @param deleteReason the reason of the deletion, e.g. picked up or destroyed (in case of UGC) - */ + /** + * Deletes a model for a property + * @param id the ID of the model to delete + * @param deleteReason the reason of the deletion, e.g. picked up or destroyed (in case of UGC) + */ void DeleteModel(LWOOBJID id, int deleteReason); - /** - * Updates whether or not this property is approved by a moderator - * @param value true if the property should be approved, false otherwise - */ + /** + * Updates whether or not this property is approved by a moderator + * @param value true if the property should be approved, false otherwise + */ void UpdateApprovedStatus(bool value); - /** - * Loads all the models on this property from the database - */ + /** + * Loads all the models on this property from the database + */ void Load(); - /** - * Saves all the models from this property to the database - */ + /** + * Saves all the models from this property to the database + */ void Save(); - /** - * Adds a model to the cache of models - * @param modelId the ID of the model - * @param spawnerId the ID of the object that spawned the model - */ + /** + * Adds a model to the cache of models + * @param modelId the ID of the model + * @param spawnerId the ID of the object that spawned the model + */ void AddModel(LWOOBJID modelId, LWOOBJID spawnerId); - /** - * Returns all the models on this property, indexed by property ID, containing their spawn objects - * @return all the models on this proeprty - */ + /** + * Returns all the models on this property, indexed by property ID, containing their spawn objects + * @return all the models on this proeprty + */ const std::map& GetModels() const; - - LWOCLONEID GetCloneId() { return clone_Id; }; + + LWOCLONEID GetCloneId() { return clone_Id; }; private: - /** - * This - */ + /** + * This + */ static PropertyManagementComponent* instance; - /** - * The ID of the owner of this property - */ + /** + * The ID of the owner of this property + */ LWOOBJID owner = LWOOBJID_EMPTY; - /** - * The LOT of this console - */ + /** + * The LOT of this console + */ uint32_t templateId = 0; - /** - * The unique ID for this property, if it's owned - */ + /** + * The unique ID for this property, if it's owned + */ LWOOBJID propertyId = LWOOBJID_EMPTY; - /** - * The time since this property was claimed - */ + /** + * The time since this property was claimed + */ uint64_t claimedTime = std::chrono::duration_cast(std::chrono::system_clock::now().time_since_epoch()).count(); - /** - * The models that are placed on this property - */ + /** + * The models that are placed on this property + */ std::map models = {}; - /** - * The name of this property - */ + /** + * The name of this property + */ std::string propertyName = ""; - /** - * The clone ID of this property - */ + /** + * The clone ID of this property + */ LWOCLONEID clone_Id = 0; - /** - * Whether a moderator was requested - */ - bool moderatorRequested = false; + /** + * Whether a moderator was requested + */ + bool moderatorRequested = false; - /** - * The rejection reason for the property - */ + /** + * The rejection reason for the property + */ std::string rejectionReason = ""; - /** - * The description of this property - */ + /** + * The description of this property + */ std::string propertyDescription = ""; - /** - * The reputation of this property - */ + /** + * The reputation of this property + */ uint32_t reputation = 0; - /** - * The last time this property was updated - */ - uint32_t LastUpdatedTime = std::chrono::duration_cast(std::chrono::system_clock::now().time_since_epoch()).count(); + /** + * The last time this property was updated + */ + uint32_t LastUpdatedTime = std::chrono::duration_cast(std::chrono::system_clock::now().time_since_epoch()).count(); - /** - * Determines which players may visit this property - */ + /** + * Determines which players may visit this property + */ PropertyPrivacyOption privacyOption = PropertyPrivacyOption::Private; - /** - * The privacy setting before it was changed, saved to set back after a player finishes building - */ + /** + * The privacy setting before it was changed, saved to set back after a player finishes building + */ PropertyPrivacyOption originalPrivacyOption = PropertyPrivacyOption::Private; }; diff --git a/dGame/dComponents/PropertyVendorComponent.cpp b/dGame/dComponents/PropertyVendorComponent.cpp index 5ab8340b..4ad24af5 100644 --- a/dGame/dComponents/PropertyVendorComponent.cpp +++ b/dGame/dComponents/PropertyVendorComponent.cpp @@ -10,18 +10,15 @@ #include "PropertyManagementComponent.h" #include "UserManager.h" -PropertyVendorComponent::PropertyVendorComponent(Entity* parent) : Component(parent) -{ +PropertyVendorComponent::PropertyVendorComponent(Entity* parent) : Component(parent) { } -void PropertyVendorComponent::OnUse(Entity* originator) -{ +void PropertyVendorComponent::OnUse(Entity* originator) { if (PropertyManagementComponent::Instance() == nullptr) return; OnQueryPropertyData(originator, originator->GetSystemAddress()); - if (PropertyManagementComponent::Instance()->GetOwnerId() == LWOOBJID_EMPTY) - { + if (PropertyManagementComponent::Instance()->GetOwnerId() == LWOOBJID_EMPTY) { Game::logger->Log("PropertyVendorComponent", "Property vendor opening!"); GameMessages::SendOpenPropertyVendor(m_Parent->GetObjectID(), originator->GetSystemAddress()); @@ -30,15 +27,13 @@ void PropertyVendorComponent::OnUse(Entity* originator) } } -void PropertyVendorComponent::OnQueryPropertyData(Entity* originator, const SystemAddress& sysAddr) -{ +void PropertyVendorComponent::OnQueryPropertyData(Entity* originator, const SystemAddress& sysAddr) { if (PropertyManagementComponent::Instance() == nullptr) return; PropertyManagementComponent::Instance()->OnQueryPropertyData(originator, sysAddr, m_Parent->GetObjectID()); } -void PropertyVendorComponent::OnBuyFromVendor(Entity* originator, const bool confirmed, const LOT lot, const uint32_t count) -{ +void PropertyVendorComponent::OnBuyFromVendor(Entity* originator, const bool confirmed, const LOT lot, const uint32_t count) { if (PropertyManagementComponent::Instance() == nullptr) return; if (PropertyManagementComponent::Instance()->Claim(originator->GetObjectID()) == false) { diff --git a/dGame/dComponents/PropertyVendorComponent.h b/dGame/dComponents/PropertyVendorComponent.h index 1a469589..4641b38d 100644 --- a/dGame/dComponents/PropertyVendorComponent.h +++ b/dGame/dComponents/PropertyVendorComponent.h @@ -12,26 +12,26 @@ public: static const uint32_t ComponentType = COMPONENT_TYPE_PROPERTY_VENDOR; explicit PropertyVendorComponent(Entity* parent); - /** - * Handles a use event from some entity, if the property is cleared this allows the entity to claim it - * @param originator the entity that triggered this event - */ + /** + * Handles a use event from some entity, if the property is cleared this allows the entity to claim it + * @param originator the entity that triggered this event + */ void OnUse(Entity* originator) override; - /** - * Handles a property data query after the property has been claimed, sending information about the property to the - * triggering entity. - * @param originator the entity that triggered the event - * @param sysAddr the system address to send game message response to - */ + /** + * Handles a property data query after the property has been claimed, sending information about the property to the + * triggering entity. + * @param originator the entity that triggered the event + * @param sysAddr the system address to send game message response to + */ void OnQueryPropertyData(Entity* originator, const SystemAddress& sysAddr); - /** - * Claims the property - * @param originator the entity that attempted to claim the property - * @param confirmed unused - * @param lot unused - * @param count unused - */ + /** + * Claims the property + * @param originator the entity that attempted to claim the property + * @param confirmed unused + * @param lot unused + * @param count unused + */ void OnBuyFromVendor(Entity* originator, bool confirmed, LOT lot, uint32_t count); }; diff --git a/dGame/dComponents/ProximityMonitorComponent.cpp b/dGame/dComponents/ProximityMonitorComponent.cpp index f2ef9b9a..acc93fde 100644 --- a/dGame/dComponents/ProximityMonitorComponent.cpp +++ b/dGame/dComponents/ProximityMonitorComponent.cpp @@ -27,7 +27,7 @@ ProximityMonitorComponent::~ProximityMonitorComponent() { void ProximityMonitorComponent::SetProximityRadius(float proxRadius, const std::string& name) { dpEntity* en = new dpEntity(m_Parent->GetObjectID(), proxRadius); en->SetPosition(m_Parent->GetPosition()); - + dpWorld::Instance().AddEntity(en); m_ProximitiesData.insert(std::make_pair(name, en)); } diff --git a/dGame/dComponents/ProximityMonitorComponent.h b/dGame/dComponents/ProximityMonitorComponent.h index 11cc7ab3..a98397a2 100644 --- a/dGame/dComponents/ProximityMonitorComponent.h +++ b/dGame/dComponents/ProximityMonitorComponent.h @@ -12,63 +12,63 @@ #include "dpEntity.h" #include "Component.h" -/** - * Utility component for detecting how close entities are to named proximities for this entity. Allows you to store - * proximity checks for multiple ojects. - */ + /** + * Utility component for detecting how close entities are to named proximities for this entity. Allows you to store + * proximity checks for multiple ojects. + */ class ProximityMonitorComponent : public Component { public: static const uint32_t ComponentType = COMPONENT_TYPE_PROXIMITY_MONITOR; - + ProximityMonitorComponent(Entity* parentEntity, int smallRadius = -1, int largeRadius = -1); ~ProximityMonitorComponent() override; - void Update(float deltaTime) override; + void Update(float deltaTime) override; - /** - * Creates an entry to check proximity for, given a name - * @param proxRadius the radius to use for the physics entity we use to detect proximity - * @param name the name of this check - */ + /** + * Creates an entry to check proximity for, given a name + * @param proxRadius the radius to use for the physics entity we use to detect proximity + * @param name the name of this check + */ void SetProximityRadius(float proxRadius, const std::string& name); - /** - * Creates an entry to check proximity for, given a name - * @param entity the physics entity to add to our proximity sensors - * @param name the name of this check - */ + /** + * Creates an entry to check proximity for, given a name + * @param entity the physics entity to add to our proximity sensors + * @param name the name of this check + */ void SetProximityRadius(dpEntity* entity, const std::string& name); - /** - * Returns the last of entities that are used to check proximity, given a name - * @param name the proximity name to retrieve physics objects for - * @return a map of physics entities for this name, indexed by object ID - */ + /** + * Returns the last of entities that are used to check proximity, given a name + * @param name the proximity name to retrieve physics objects for + * @return a map of physics entities for this name, indexed by object ID + */ const std::map& GetProximityObjects(const std::string& name); - /** - * Checks if the passed object is in proximity of the named proximity sensor - * @param name the name of the sensor to check proximity for - * @param objectID the entity to check if they're in proximity - * @return true if the object is in proximity, false otherwise - */ + /** + * Checks if the passed object is in proximity of the named proximity sensor + * @param name the name of the sensor to check proximity for + * @param objectID the entity to check if they're in proximity + * @return true if the object is in proximity, false otherwise + */ bool IsInProximity(const std::string& name, LWOOBJID objectID); - /** - * Returns all the proximity sensors stored on this component, indexed by name - * @return all the proximity sensors stored on this component - */ + /** + * Returns all the proximity sensors stored on this component, indexed by name + * @return all the proximity sensors stored on this component + */ const std::map& GetProximitiesData() const { return m_ProximitiesData; } private: - /** - * All the proximity sensors for this component, indexed by name - */ + /** + * All the proximity sensors for this component, indexed by name + */ std::map m_ProximitiesData = {}; - /** - * Default value for the proximity data - */ + /** + * Default value for the proximity data + */ static const std::map m_EmptyObjectMap; }; diff --git a/dGame/dComponents/RacingControlComponent.cpp b/dGame/dComponents/RacingControlComponent.cpp index e157ca5f..f6f257d2 100644 --- a/dGame/dComponents/RacingControlComponent.cpp +++ b/dGame/dComponents/RacingControlComponent.cpp @@ -26,884 +26,884 @@ #define M_PI 3.14159265358979323846264338327950288 #endif -RacingControlComponent::RacingControlComponent(Entity *parent) - : Component(parent) { - m_PathName = u"MainPath"; - m_RemainingLaps = 3; - m_LeadingPlayer = LWOOBJID_EMPTY; - m_RaceBestTime = 0; - m_RaceBestLap = 0; - m_Started = false; - m_StartTimer = 0; - m_Loaded = false; - m_LoadedPlayers = 0; - m_LoadTimer = 0; - m_Finished = 0; - m_StartTime = 0; - m_EmptyTimer = 0; - m_SoloRacing = Game::config->GetValue("solo_racing") == "1"; +RacingControlComponent::RacingControlComponent(Entity* parent) + : Component(parent) { + m_PathName = u"MainPath"; + m_RemainingLaps = 3; + m_LeadingPlayer = LWOOBJID_EMPTY; + m_RaceBestTime = 0; + m_RaceBestLap = 0; + m_Started = false; + m_StartTimer = 0; + m_Loaded = false; + m_LoadedPlayers = 0; + m_LoadTimer = 0; + m_Finished = 0; + m_StartTime = 0; + m_EmptyTimer = 0; + m_SoloRacing = Game::config->GetValue("solo_racing") == "1"; - // Select the main world ID as fallback when a player fails to load. + // Select the main world ID as fallback when a player fails to load. - const auto worldID = Game::server->GetZoneID(); + const auto worldID = Game::server->GetZoneID(); - switch (worldID) { - case 1203: - m_ActivityID = 42; - m_MainWorld = 1200; - break; + switch (worldID) { + case 1203: + m_ActivityID = 42; + m_MainWorld = 1200; + break; - case 1261: - m_ActivityID = 60; - m_MainWorld = 1260; - break; + case 1261: + m_ActivityID = 60; + m_MainWorld = 1260; + break; - case 1303: - m_ActivityID = 39; - m_MainWorld = 1300; - break; + case 1303: + m_ActivityID = 39; + m_MainWorld = 1300; + break; - case 1403: - m_ActivityID = 54; - m_MainWorld = 1400; - break; + case 1403: + m_ActivityID = 54; + m_MainWorld = 1400; + break; - default: - m_ActivityID = 42; - m_MainWorld = 1200; - break; - } + default: + m_ActivityID = 42; + m_MainWorld = 1200; + break; + } } RacingControlComponent::~RacingControlComponent() {} -void RacingControlComponent::OnPlayerLoaded(Entity *player) { - // If the race has already started, send the player back to the main world. - if (m_Loaded) { - auto *playerInstance = dynamic_cast(player); +void RacingControlComponent::OnPlayerLoaded(Entity* player) { + // If the race has already started, send the player back to the main world. + if (m_Loaded) { + auto* playerInstance = dynamic_cast(player); - playerInstance->SendToZone(m_MainWorld); + playerInstance->SendToZone(m_MainWorld); - return; - } + return; + } - const auto objectID = player->GetObjectID(); + const auto objectID = player->GetObjectID(); - m_LoadedPlayers++; + m_LoadedPlayers++; - Game::logger->Log("RacingControlComponent", "Loading player %i", - m_LoadedPlayers); + Game::logger->Log("RacingControlComponent", "Loading player %i", + m_LoadedPlayers); - m_LobbyPlayers.push_back(objectID); + m_LobbyPlayers.push_back(objectID); } -void RacingControlComponent::LoadPlayerVehicle(Entity *player, - bool initialLoad) { - // Load the player's vehicle. +void RacingControlComponent::LoadPlayerVehicle(Entity* player, + bool initialLoad) { + // Load the player's vehicle. - if (player == nullptr) { - return; - } + if (player == nullptr) { + return; + } - auto *inventoryComponent = player->GetComponent(); + auto* inventoryComponent = player->GetComponent(); - if (inventoryComponent == nullptr) { - return; - } + if (inventoryComponent == nullptr) { + return; + } - // Find the player's vehicle. + // Find the player's vehicle. - auto *item = inventoryComponent->FindItemByLot(8092); + auto* item = inventoryComponent->FindItemByLot(8092); - if (item == nullptr) { - Game::logger->Log("RacingControlComponent", "Failed to find item"); + if (item == nullptr) { + Game::logger->Log("RacingControlComponent", "Failed to find item"); - return; - } + return; + } - // Calculate the vehicle's starting position. + // Calculate the vehicle's starting position. - auto *path = dZoneManager::Instance()->GetZone()->GetPath( - GeneralUtils::UTF16ToWTF8(m_PathName)); + auto* path = dZoneManager::Instance()->GetZone()->GetPath( + GeneralUtils::UTF16ToWTF8(m_PathName)); - auto startPosition = path->pathWaypoints[0].position + NiPoint3::UNIT_Y * 3; + auto startPosition = path->pathWaypoints[0].position + NiPoint3::UNIT_Y * 3; - const auto spacing = 15; + const auto spacing = 15; - // This sometimes spawns the vehicle out of the map if there are lots of - // players loaded. + // This sometimes spawns the vehicle out of the map if there are lots of + // players loaded. - const auto range = m_LoadedPlayers * spacing; + const auto range = m_LoadedPlayers * spacing; - startPosition = - startPosition + NiPoint3::UNIT_Z * ((m_LeadingPlayer / 2) + - m_RacingPlayers.size() * spacing); + startPosition = + startPosition + NiPoint3::UNIT_Z * ((m_LeadingPlayer / 2) + + m_RacingPlayers.size() * spacing); - auto startRotation = - NiQuaternion::LookAt(startPosition, startPosition + NiPoint3::UNIT_X); + auto startRotation = + NiQuaternion::LookAt(startPosition, startPosition + NiPoint3::UNIT_X); - auto angles = startRotation.GetEulerAngles(); + auto angles = startRotation.GetEulerAngles(); - angles.y -= M_PI; + angles.y -= M_PI; - startRotation = NiQuaternion::FromEulerAngles(angles); + startRotation = NiQuaternion::FromEulerAngles(angles); - Game::logger->Log("RacingControlComponent", - "Start position <%f, %f, %f>, <%f, %f, %f>", - startPosition.x, startPosition.y, startPosition.z, - angles.x * (180.0f / M_PI), angles.y * (180.0f / M_PI), - angles.z * (180.0f / M_PI)); + Game::logger->Log("RacingControlComponent", + "Start position <%f, %f, %f>, <%f, %f, %f>", + startPosition.x, startPosition.y, startPosition.z, + angles.x * (180.0f / M_PI), angles.y * (180.0f / M_PI), + angles.z * (180.0f / M_PI)); - // Make sure the player is at the correct position. + // Make sure the player is at the correct position. - GameMessages::SendTeleport(player->GetObjectID(), startPosition, - startRotation, player->GetSystemAddress(), true, - true); + GameMessages::SendTeleport(player->GetObjectID(), startPosition, + startRotation, player->GetSystemAddress(), true, + true); - // Spawn the vehicle entity. + // Spawn the vehicle entity. - EntityInfo info{}; - info.lot = 8092; - info.pos = startPosition; - info.rot = startRotation; - info.spawnerID = m_Parent->GetObjectID(); + EntityInfo info{}; + info.lot = 8092; + info.pos = startPosition; + info.rot = startRotation; + info.spawnerID = m_Parent->GetObjectID(); - auto *carEntity = - EntityManager::Instance()->CreateEntity(info, nullptr, m_Parent); + auto* carEntity = + EntityManager::Instance()->CreateEntity(info, nullptr, m_Parent); - // Make the vehicle a child of the racing controller. - m_Parent->AddChild(carEntity); + // Make the vehicle a child of the racing controller. + m_Parent->AddChild(carEntity); - auto *destroyableComponent = - carEntity->GetComponent(); + auto* destroyableComponent = + carEntity->GetComponent(); - // Setup the vehicle stats. - if (destroyableComponent != nullptr) { - destroyableComponent->SetMaxImagination(60); - destroyableComponent->SetImagination(0); - } + // Setup the vehicle stats. + if (destroyableComponent != nullptr) { + destroyableComponent->SetMaxImagination(60); + destroyableComponent->SetImagination(0); + } - // Setup the vehicle as being possessed by the player. - auto *possessableComponent = - carEntity->GetComponent(); + // Setup the vehicle as being possessed by the player. + auto* possessableComponent = + carEntity->GetComponent(); - if (possessableComponent != nullptr) { - possessableComponent->SetPossessor(player->GetObjectID()); - } + if (possessableComponent != nullptr) { + possessableComponent->SetPossessor(player->GetObjectID()); + } - // Load the vehicle's assemblyPartLOTs for display. - auto *moduleAssemblyComponent = - carEntity->GetComponent(); + // Load the vehicle's assemblyPartLOTs for display. + auto* moduleAssemblyComponent = + carEntity->GetComponent(); - if (moduleAssemblyComponent) { - moduleAssemblyComponent->SetSubKey(item->GetSubKey()); - moduleAssemblyComponent->SetUseOptionalParts(false); + if (moduleAssemblyComponent) { + moduleAssemblyComponent->SetSubKey(item->GetSubKey()); + moduleAssemblyComponent->SetUseOptionalParts(false); - for (auto *config : item->GetConfig()) { - if (config->GetKey() == u"assemblyPartLOTs") { - moduleAssemblyComponent->SetAssemblyPartsLOTs( - GeneralUtils::ASCIIToUTF16(config->GetValueAsString())); - } - } - } + for (auto* config : item->GetConfig()) { + if (config->GetKey() == u"assemblyPartLOTs") { + moduleAssemblyComponent->SetAssemblyPartsLOTs( + GeneralUtils::ASCIIToUTF16(config->GetValueAsString())); + } + } + } - // Setup the player as possessing the vehicle. - auto *possessorComponent = player->GetComponent(); + // Setup the player as possessing the vehicle. + auto* possessorComponent = player->GetComponent(); - if (possessorComponent != nullptr) { - possessorComponent->SetPossessable(carEntity->GetObjectID()); - possessorComponent->SetPossessableType(ePossessionType::ATTACHED_VISIBLE); // for racing it's always Attached_Visible - } + if (possessorComponent != nullptr) { + possessorComponent->SetPossessable(carEntity->GetObjectID()); + possessorComponent->SetPossessableType(ePossessionType::ATTACHED_VISIBLE); // for racing it's always Attached_Visible + } - // Set the player's current activity as racing. - auto *characterComponent = player->GetComponent(); + // Set the player's current activity as racing. + auto* characterComponent = player->GetComponent(); - if (characterComponent != nullptr) { - characterComponent->SetIsRacing(true); - } + if (characterComponent != nullptr) { + characterComponent->SetIsRacing(true); + } - // Init the player's racing entry. - if (initialLoad) { - m_RacingPlayers.push_back( - {player->GetObjectID(), - carEntity->GetObjectID(), - static_cast(m_RacingPlayers.size()), - false, - {}, - startPosition, - startRotation, - 0, - 0, - 0, - 0}); - } + // Init the player's racing entry. + if (initialLoad) { + m_RacingPlayers.push_back( + { player->GetObjectID(), + carEntity->GetObjectID(), + static_cast(m_RacingPlayers.size()), + false, + {}, + startPosition, + startRotation, + 0, + 0, + 0, + 0 }); + } - // Construct and serialize everything when done. + // Construct and serialize everything when done. - EntityManager::Instance()->ConstructEntity(carEntity); - EntityManager::Instance()->SerializeEntity(player); - EntityManager::Instance()->SerializeEntity(m_Parent); + EntityManager::Instance()->ConstructEntity(carEntity); + EntityManager::Instance()->SerializeEntity(player); + EntityManager::Instance()->SerializeEntity(m_Parent); - GameMessages::SendRacingSetPlayerResetInfo( - m_Parent->GetObjectID(), 0, 0, player->GetObjectID(), startPosition, 1, - UNASSIGNED_SYSTEM_ADDRESS); + GameMessages::SendRacingSetPlayerResetInfo( + m_Parent->GetObjectID(), 0, 0, player->GetObjectID(), startPosition, 1, + UNASSIGNED_SYSTEM_ADDRESS); - const auto playerID = player->GetObjectID(); + const auto playerID = player->GetObjectID(); - // Reset the player to the start position during downtime, in case something - // went wrong. - m_Parent->AddCallbackTimer(1, [this, playerID]() { - auto *player = EntityManager::Instance()->GetEntity(playerID); + // Reset the player to the start position during downtime, in case something + // went wrong. + m_Parent->AddCallbackTimer(1, [this, playerID]() { + auto* player = EntityManager::Instance()->GetEntity(playerID); - if (player == nullptr) { - return; - } + if (player == nullptr) { + return; + } - GameMessages::SendRacingResetPlayerToLastReset( - m_Parent->GetObjectID(), playerID, UNASSIGNED_SYSTEM_ADDRESS); - }); + GameMessages::SendRacingResetPlayerToLastReset( + m_Parent->GetObjectID(), playerID, UNASSIGNED_SYSTEM_ADDRESS); + }); - GameMessages::SendSetJetPackMode(player, false); + GameMessages::SendSetJetPackMode(player, false); - // Set the vehicle's state. - GameMessages::SendNotifyVehicleOfRacingObject(carEntity->GetObjectID(), - m_Parent->GetObjectID(), - UNASSIGNED_SYSTEM_ADDRESS); + // Set the vehicle's state. + GameMessages::SendNotifyVehicleOfRacingObject(carEntity->GetObjectID(), + m_Parent->GetObjectID(), + UNASSIGNED_SYSTEM_ADDRESS); - GameMessages::SendVehicleSetWheelLockState(carEntity->GetObjectID(), false, - initialLoad, - UNASSIGNED_SYSTEM_ADDRESS); + GameMessages::SendVehicleSetWheelLockState(carEntity->GetObjectID(), false, + initialLoad, + UNASSIGNED_SYSTEM_ADDRESS); - // Make sure everything has the correct position. - GameMessages::SendTeleport(player->GetObjectID(), startPosition, - startRotation, player->GetSystemAddress(), true, - true); - GameMessages::SendTeleport(carEntity->GetObjectID(), startPosition, - startRotation, player->GetSystemAddress(), true, - true); + // Make sure everything has the correct position. + GameMessages::SendTeleport(player->GetObjectID(), startPosition, + startRotation, player->GetSystemAddress(), true, + true); + GameMessages::SendTeleport(carEntity->GetObjectID(), startPosition, + startRotation, player->GetSystemAddress(), true, + true); } -void RacingControlComponent::OnRacingClientReady(Entity *player) { - // Notify the other players that this player is ready. +void RacingControlComponent::OnRacingClientReady(Entity* player) { + // Notify the other players that this player is ready. - for (auto &racingPlayer : m_RacingPlayers) { - if (racingPlayer.playerID != player->GetObjectID()) { - if (racingPlayer.playerLoaded) { - GameMessages::SendRacingPlayerLoaded( - m_Parent->GetObjectID(), racingPlayer.playerID, - racingPlayer.vehicleID, UNASSIGNED_SYSTEM_ADDRESS); - } + for (auto& racingPlayer : m_RacingPlayers) { + if (racingPlayer.playerID != player->GetObjectID()) { + if (racingPlayer.playerLoaded) { + GameMessages::SendRacingPlayerLoaded( + m_Parent->GetObjectID(), racingPlayer.playerID, + racingPlayer.vehicleID, UNASSIGNED_SYSTEM_ADDRESS); + } - continue; - } + continue; + } - racingPlayer.playerLoaded = true; + racingPlayer.playerLoaded = true; - GameMessages::SendRacingPlayerLoaded( - m_Parent->GetObjectID(), racingPlayer.playerID, - racingPlayer.vehicleID, UNASSIGNED_SYSTEM_ADDRESS); - } + GameMessages::SendRacingPlayerLoaded( + m_Parent->GetObjectID(), racingPlayer.playerID, + racingPlayer.vehicleID, UNASSIGNED_SYSTEM_ADDRESS); + } - EntityManager::Instance()->SerializeEntity(m_Parent); + EntityManager::Instance()->SerializeEntity(m_Parent); } -void RacingControlComponent::OnRequestDie(Entity *player) { - // Sent by the client when they collide with something which should smash - // them. +void RacingControlComponent::OnRequestDie(Entity* player) { + // Sent by the client when they collide with something which should smash + // them. - for (auto &racingPlayer : m_RacingPlayers) { - if (racingPlayer.playerID != player->GetObjectID()) { - continue; - } + for (auto& racingPlayer : m_RacingPlayers) { + if (racingPlayer.playerID != player->GetObjectID()) { + continue; + } - auto *vehicle = - EntityManager::Instance()->GetEntity(racingPlayer.vehicleID); + auto* vehicle = + EntityManager::Instance()->GetEntity(racingPlayer.vehicleID); - if (vehicle == nullptr) { - return; - } + if (vehicle == nullptr) { + return; + } - if (!racingPlayer.noSmashOnReload) { - racingPlayer.smashedTimes++; - } + if (!racingPlayer.noSmashOnReload) { + racingPlayer.smashedTimes++; + } - // Reset player to last checkpoint - GameMessages::SendRacingSetPlayerResetInfo( - m_Parent->GetObjectID(), racingPlayer.lap, - racingPlayer.respawnIndex, player->GetObjectID(), - racingPlayer.respawnPosition, racingPlayer.respawnIndex + 1, - UNASSIGNED_SYSTEM_ADDRESS); - GameMessages::SendRacingResetPlayerToLastReset( - m_Parent->GetObjectID(), racingPlayer.playerID, - UNASSIGNED_SYSTEM_ADDRESS); + // Reset player to last checkpoint + GameMessages::SendRacingSetPlayerResetInfo( + m_Parent->GetObjectID(), racingPlayer.lap, + racingPlayer.respawnIndex, player->GetObjectID(), + racingPlayer.respawnPosition, racingPlayer.respawnIndex + 1, + UNASSIGNED_SYSTEM_ADDRESS); + GameMessages::SendRacingResetPlayerToLastReset( + m_Parent->GetObjectID(), racingPlayer.playerID, + UNASSIGNED_SYSTEM_ADDRESS); - auto *characterComponent = player->GetComponent(); - if (characterComponent != nullptr) { - characterComponent->UpdatePlayerStatistic(RacingTimesWrecked); - } + auto* characterComponent = player->GetComponent(); + if (characterComponent != nullptr) { + characterComponent->UpdatePlayerStatistic(RacingTimesWrecked); + } - return; - } + return; + } } -void RacingControlComponent::OnRacingPlayerInfoResetFinished(Entity *player) { - // When the player has respawned. +void RacingControlComponent::OnRacingPlayerInfoResetFinished(Entity* player) { + // When the player has respawned. - for (auto &racingPlayer : m_RacingPlayers) { - if (racingPlayer.playerID != player->GetObjectID()) { - continue; - } + for (auto& racingPlayer : m_RacingPlayers) { + if (racingPlayer.playerID != player->GetObjectID()) { + continue; + } - auto *vehicle = - EntityManager::Instance()->GetEntity(racingPlayer.vehicleID); + auto* vehicle = + EntityManager::Instance()->GetEntity(racingPlayer.vehicleID); - if (vehicle == nullptr) { - return; - } + if (vehicle == nullptr) { + return; + } - if (!racingPlayer.noSmashOnReload) { - GameMessages::SendDie(vehicle, LWOOBJID_EMPTY, LWOOBJID_EMPTY, true, - VIOLENT, u"", 0, 0, 0, true, false, 0); + if (!racingPlayer.noSmashOnReload) { + GameMessages::SendDie(vehicle, LWOOBJID_EMPTY, LWOOBJID_EMPTY, true, + VIOLENT, u"", 0, 0, 0, true, false, 0); - GameMessages::SendVehicleUnlockInput(racingPlayer.vehicleID, false, - UNASSIGNED_SYSTEM_ADDRESS); - GameMessages::SendVehicleSetWheelLockState( - racingPlayer.vehicleID, false, false, - UNASSIGNED_SYSTEM_ADDRESS); + GameMessages::SendVehicleUnlockInput(racingPlayer.vehicleID, false, + UNASSIGNED_SYSTEM_ADDRESS); + GameMessages::SendVehicleSetWheelLockState( + racingPlayer.vehicleID, false, false, + UNASSIGNED_SYSTEM_ADDRESS); - GameMessages::SendResurrect(vehicle); - } + GameMessages::SendResurrect(vehicle); + } - racingPlayer.noSmashOnReload = false; + racingPlayer.noSmashOnReload = false; - return; - } + return; + } } -void RacingControlComponent::HandleMessageBoxResponse(Entity *player, - const std::string &id) { - auto *data = GetPlayerData(player->GetObjectID()); +void RacingControlComponent::HandleMessageBoxResponse(Entity* player, + const std::string& id) { + auto* data = GetPlayerData(player->GetObjectID()); - if (data == nullptr) { - return; - } + if (data == nullptr) { + return; + } - if (id == "rewardButton") { - if (data->collectedRewards) { - return; - } + if (id == "rewardButton") { + if (data->collectedRewards) { + return; + } - data->collectedRewards = true; + data->collectedRewards = true; - // Calculate the score, different loot depending on player count - const auto score = m_LoadedPlayers * 10 + data->finished; + // Calculate the score, different loot depending on player count + const auto score = m_LoadedPlayers * 10 + data->finished; - LootGenerator::Instance().GiveActivityLoot(player, m_Parent, m_ActivityID, score); + LootGenerator::Instance().GiveActivityLoot(player, m_Parent, m_ActivityID, score); - // Giving rewards - GameMessages::SendNotifyRacingClient( - m_Parent->GetObjectID(), 2, 0, LWOOBJID_EMPTY, u"", - player->GetObjectID(), UNASSIGNED_SYSTEM_ADDRESS); + // Giving rewards + GameMessages::SendNotifyRacingClient( + m_Parent->GetObjectID(), 2, 0, LWOOBJID_EMPTY, u"", + player->GetObjectID(), UNASSIGNED_SYSTEM_ADDRESS); - auto *missionComponent = player->GetComponent(); + auto* missionComponent = player->GetComponent(); - if (missionComponent == nullptr) return; + if (missionComponent == nullptr) return; - missionComponent->Progress(MissionTaskType::MISSION_TASK_TYPE_RACING, 0, (LWOOBJID)RacingTaskParam::RACING_TASK_PARAM_COMPETED_IN_RACE); // Progress task for competing in a race - missionComponent->Progress(MissionTaskType::MISSION_TASK_TYPE_RACING, data->smashedTimes, (LWOOBJID)RacingTaskParam::RACING_TASK_PARAM_SAFE_DRIVER); // Finish a race without being smashed. + missionComponent->Progress(MissionTaskType::MISSION_TASK_TYPE_RACING, 0, (LWOOBJID)RacingTaskParam::RACING_TASK_PARAM_COMPETED_IN_RACE); // Progress task for competing in a race + missionComponent->Progress(MissionTaskType::MISSION_TASK_TYPE_RACING, data->smashedTimes, (LWOOBJID)RacingTaskParam::RACING_TASK_PARAM_SAFE_DRIVER); // Finish a race without being smashed. - // If solo racing is enabled OR if there are 3 players in the race, progress placement tasks. - if(m_SoloRacing || m_LoadedPlayers > 2) { - missionComponent->Progress(MissionTaskType::MISSION_TASK_TYPE_RACING, data->finished, (LWOOBJID)RacingTaskParam::RACING_TASK_PARAM_FINISH_WITH_PLACEMENT); // Finish in 1st place on a race - if(data->finished == 1) { - missionComponent->Progress(MissionTaskType::MISSION_TASK_TYPE_RACING, dZoneManager::Instance()->GetZone()->GetWorldID(), (LWOOBJID)RacingTaskParam::RACING_TASK_PARAM_FIRST_PLACE_MULTIPLE_TRACKS); // Finish in 1st place on multiple tracks. - missionComponent->Progress(MissionTaskType::MISSION_TASK_TYPE_RACING, dZoneManager::Instance()->GetZone()->GetWorldID(), (LWOOBJID)RacingTaskParam::RACING_TASK_PARAM_WIN_RACE_IN_WORLD); // Finished first place in specific world. - } - if (data->finished == m_LoadedPlayers) { - missionComponent->Progress(MissionTaskType::MISSION_TASK_TYPE_RACING, dZoneManager::Instance()->GetZone()->GetWorldID(), (LWOOBJID)RacingTaskParam::RACING_TASK_PARAM_LAST_PLACE_FINISH); // Finished first place in specific world. - } - } - } else if (id == "ACT_RACE_EXIT_THE_RACE?" || id == "Exit") { - auto *vehicle = EntityManager::Instance()->GetEntity(data->vehicleID); + // If solo racing is enabled OR if there are 3 players in the race, progress placement tasks. + if (m_SoloRacing || m_LoadedPlayers > 2) { + missionComponent->Progress(MissionTaskType::MISSION_TASK_TYPE_RACING, data->finished, (LWOOBJID)RacingTaskParam::RACING_TASK_PARAM_FINISH_WITH_PLACEMENT); // Finish in 1st place on a race + if (data->finished == 1) { + missionComponent->Progress(MissionTaskType::MISSION_TASK_TYPE_RACING, dZoneManager::Instance()->GetZone()->GetWorldID(), (LWOOBJID)RacingTaskParam::RACING_TASK_PARAM_FIRST_PLACE_MULTIPLE_TRACKS); // Finish in 1st place on multiple tracks. + missionComponent->Progress(MissionTaskType::MISSION_TASK_TYPE_RACING, dZoneManager::Instance()->GetZone()->GetWorldID(), (LWOOBJID)RacingTaskParam::RACING_TASK_PARAM_WIN_RACE_IN_WORLD); // Finished first place in specific world. + } + if (data->finished == m_LoadedPlayers) { + missionComponent->Progress(MissionTaskType::MISSION_TASK_TYPE_RACING, dZoneManager::Instance()->GetZone()->GetWorldID(), (LWOOBJID)RacingTaskParam::RACING_TASK_PARAM_LAST_PLACE_FINISH); // Finished first place in specific world. + } + } + } else if (id == "ACT_RACE_EXIT_THE_RACE?" || id == "Exit") { + auto* vehicle = EntityManager::Instance()->GetEntity(data->vehicleID); - if (vehicle == nullptr) { - return; - } + if (vehicle == nullptr) { + return; + } - // Exiting race - GameMessages::SendNotifyRacingClient( - m_Parent->GetObjectID(), 3, 0, LWOOBJID_EMPTY, u"", - player->GetObjectID(), UNASSIGNED_SYSTEM_ADDRESS); + // Exiting race + GameMessages::SendNotifyRacingClient( + m_Parent->GetObjectID(), 3, 0, LWOOBJID_EMPTY, u"", + player->GetObjectID(), UNASSIGNED_SYSTEM_ADDRESS); - auto *playerInstance = dynamic_cast(player); + auto* playerInstance = dynamic_cast(player); - playerInstance->SendToZone(m_MainWorld); + playerInstance->SendToZone(m_MainWorld); - vehicle->Kill(); - } + vehicle->Kill(); + } } -void RacingControlComponent::Serialize(RakNet::BitStream *outBitStream, - bool bIsInitialUpdate, - unsigned int &flags) { - // BEGIN Scripted Activity +void RacingControlComponent::Serialize(RakNet::BitStream* outBitStream, + bool bIsInitialUpdate, + unsigned int& flags) { + // BEGIN Scripted Activity - outBitStream->Write1(); + outBitStream->Write1(); - outBitStream->Write(static_cast(m_RacingPlayers.size())); - for (const auto &player : m_RacingPlayers) { - outBitStream->Write(player.playerID); + outBitStream->Write(static_cast(m_RacingPlayers.size())); + for (const auto& player : m_RacingPlayers) { + outBitStream->Write(player.playerID); - for (int i = 0; i < 10; i++) { - outBitStream->Write(player.data[i]); - } - } + for (int i = 0; i < 10; i++) { + outBitStream->Write(player.data[i]); + } + } - // END Scripted Activity + // END Scripted Activity - outBitStream->Write1(); // Dirty? - outBitStream->Write(static_cast(m_RacingPlayers.size())); + outBitStream->Write1(); // Dirty? + outBitStream->Write(static_cast(m_RacingPlayers.size())); - outBitStream->Write(!m_RacingPlayers.empty()); - if (!m_RacingPlayers.empty()) { - for (const auto &player : m_RacingPlayers) { - outBitStream->Write1(); // Has more date + outBitStream->Write(!m_RacingPlayers.empty()); + if (!m_RacingPlayers.empty()) { + for (const auto& player : m_RacingPlayers) { + outBitStream->Write1(); // Has more date - outBitStream->Write(player.playerID); - outBitStream->Write(player.vehicleID); - outBitStream->Write(player.playerIndex); - outBitStream->Write(player.playerLoaded); - } + outBitStream->Write(player.playerID); + outBitStream->Write(player.vehicleID); + outBitStream->Write(player.playerIndex); + outBitStream->Write(player.playerLoaded); + } - outBitStream->Write0(); // No more data - } + outBitStream->Write0(); // No more data + } - outBitStream->Write(!m_RacingPlayers.empty()); - if (!m_RacingPlayers.empty()) { - for (const auto &player : m_RacingPlayers) { - outBitStream->Write1(); // Has more date + outBitStream->Write(!m_RacingPlayers.empty()); + if (!m_RacingPlayers.empty()) { + for (const auto& player : m_RacingPlayers) { + outBitStream->Write1(); // Has more date - outBitStream->Write(player.playerID); - outBitStream->Write(0); - } + outBitStream->Write(player.playerID); + outBitStream->Write(0); + } - outBitStream->Write0(); // No more data - } + outBitStream->Write0(); // No more data + } - outBitStream->Write1(); // Dirty? + outBitStream->Write1(); // Dirty? - outBitStream->Write(m_RemainingLaps); + outBitStream->Write(m_RemainingLaps); - outBitStream->Write(static_cast(m_PathName.size())); - for (const auto character : m_PathName) { - outBitStream->Write(character); - } + outBitStream->Write(static_cast(m_PathName.size())); + for (const auto character : m_PathName) { + outBitStream->Write(character); + } - outBitStream->Write1(); // ??? - outBitStream->Write1(); // ??? + outBitStream->Write1(); // ??? + outBitStream->Write1(); // ??? - outBitStream->Write(m_LeadingPlayer); - outBitStream->Write(m_RaceBestLap); - outBitStream->Write(m_RaceBestTime); + outBitStream->Write(m_LeadingPlayer); + outBitStream->Write(m_RaceBestLap); + outBitStream->Write(m_RaceBestTime); } -RacingPlayerInfo *RacingControlComponent::GetPlayerData(LWOOBJID playerID) { - for (auto &player : m_RacingPlayers) { - if (player.playerID == playerID) { - return &player; - } - } +RacingPlayerInfo* RacingControlComponent::GetPlayerData(LWOOBJID playerID) { + for (auto& player : m_RacingPlayers) { + if (player.playerID == playerID) { + return &player; + } + } - return nullptr; + return nullptr; } void RacingControlComponent::Update(float deltaTime) { - // This method is a mess. + // This method is a mess. - // Pre-load routine - if (!m_Loaded) { - // Check if any players has disconnected before loading in - for (size_t i = 0; i < m_LobbyPlayers.size(); i++) { - auto *playerEntity = - EntityManager::Instance()->GetEntity(m_LobbyPlayers[i]); + // Pre-load routine + if (!m_Loaded) { + // Check if any players has disconnected before loading in + for (size_t i = 0; i < m_LobbyPlayers.size(); i++) { + auto* playerEntity = + EntityManager::Instance()->GetEntity(m_LobbyPlayers[i]); - if (playerEntity == nullptr) { - --m_LoadedPlayers; + if (playerEntity == nullptr) { + --m_LoadedPlayers; - m_LobbyPlayers.erase(m_LobbyPlayers.begin() + i); + m_LobbyPlayers.erase(m_LobbyPlayers.begin() + i); - return; - } - } + return; + } + } - if (m_LoadedPlayers >= 2 || (m_LoadedPlayers == 1 && m_SoloRacing)) { - m_LoadTimer += deltaTime; - } else { - m_EmptyTimer += deltaTime; - } + if (m_LoadedPlayers >= 2 || (m_LoadedPlayers == 1 && m_SoloRacing)) { + m_LoadTimer += deltaTime; + } else { + m_EmptyTimer += deltaTime; + } - // If a player happens to be left alone for more then 30 seconds without - // anyone else loading in, send them back to the main world - if (m_EmptyTimer >= 30) { - for (const auto player : m_LobbyPlayers) { - auto *playerEntity = - EntityManager::Instance()->GetEntity(player); + // If a player happens to be left alone for more then 30 seconds without + // anyone else loading in, send them back to the main world + if (m_EmptyTimer >= 30) { + for (const auto player : m_LobbyPlayers) { + auto* playerEntity = + EntityManager::Instance()->GetEntity(player); - if (playerEntity == nullptr) { - continue; - } + if (playerEntity == nullptr) { + continue; + } - auto *playerInstance = dynamic_cast(playerEntity); + auto* playerInstance = dynamic_cast(playerEntity); - playerInstance->SendToZone(m_MainWorld); - } + playerInstance->SendToZone(m_MainWorld); + } - m_LobbyPlayers.clear(); - } + m_LobbyPlayers.clear(); + } - // From the first 2 players loading in the rest have a max of 15 seconds - // to load in, can raise this if it's too low - if (m_LoadTimer >= 15) { - Game::logger->Log("RacingControlComponent", - "Loading all players..."); + // From the first 2 players loading in the rest have a max of 15 seconds + // to load in, can raise this if it's too low + if (m_LoadTimer >= 15) { + Game::logger->Log("RacingControlComponent", + "Loading all players..."); - for (size_t i = 0; i < m_LobbyPlayers.size(); i++) { - Game::logger->Log("RacingControlComponent", - "Loading player now!"); + for (size_t i = 0; i < m_LobbyPlayers.size(); i++) { + Game::logger->Log("RacingControlComponent", + "Loading player now!"); - auto *player = - EntityManager::Instance()->GetEntity(m_LobbyPlayers[i]); + auto* player = + EntityManager::Instance()->GetEntity(m_LobbyPlayers[i]); - if (player == nullptr) { - return; - } - - Game::logger->Log("RacingControlComponent", - "Loading player now NOW!"); + if (player == nullptr) { + return; + } + + Game::logger->Log("RacingControlComponent", + "Loading player now NOW!"); - LoadPlayerVehicle(player, true); + LoadPlayerVehicle(player, true); - m_Loaded = true; - } + m_Loaded = true; + } - m_Loaded = true; - } + m_Loaded = true; + } - return; - } + return; + } - // The players who will be participating have loaded - if (!m_Started) { - // Check if anyone has disconnected during this period - for (size_t i = 0; i < m_RacingPlayers.size(); i++) { - auto *playerEntity = EntityManager::Instance()->GetEntity( - m_RacingPlayers[i].playerID); - - if (playerEntity == nullptr) { - m_RacingPlayers.erase(m_RacingPlayers.begin() + i); + // The players who will be participating have loaded + if (!m_Started) { + // Check if anyone has disconnected during this period + for (size_t i = 0; i < m_RacingPlayers.size(); i++) { + auto* playerEntity = EntityManager::Instance()->GetEntity( + m_RacingPlayers[i].playerID); + + if (playerEntity == nullptr) { + m_RacingPlayers.erase(m_RacingPlayers.begin() + i); - --m_LoadedPlayers; + --m_LoadedPlayers; - return; - } - } - - // If less then 2 players are left, send the rest back to the main world - if (m_LoadedPlayers < 2 && !(m_LoadedPlayers == 1 && m_SoloRacing)) { - for (const auto player : m_LobbyPlayers) { - auto *playerEntity = - EntityManager::Instance()->GetEntity(player); - - if (playerEntity == nullptr) { - continue; - } - - auto *playerInstance = dynamic_cast(playerEntity); - - playerInstance->SendToZone(m_MainWorld); - } - - return; - } - - // Check if all players have send a ready message - - int32_t readyPlayers = 0; - - for (const auto &player : m_RacingPlayers) { - if (player.playerLoaded) { - ++readyPlayers; - } - } + return; + } + } + + // If less then 2 players are left, send the rest back to the main world + if (m_LoadedPlayers < 2 && !(m_LoadedPlayers == 1 && m_SoloRacing)) { + for (const auto player : m_LobbyPlayers) { + auto* playerEntity = + EntityManager::Instance()->GetEntity(player); + + if (playerEntity == nullptr) { + continue; + } + + auto* playerInstance = dynamic_cast(playerEntity); + + playerInstance->SendToZone(m_MainWorld); + } + + return; + } + + // Check if all players have send a ready message + + int32_t readyPlayers = 0; + + for (const auto& player : m_RacingPlayers) { + if (player.playerLoaded) { + ++readyPlayers; + } + } - if (readyPlayers >= m_LoadedPlayers) { - // Setup for racing - if (m_StartTimer == 0) { - GameMessages::SendNotifyRacingClient( - m_Parent->GetObjectID(), 1, 0, LWOOBJID_EMPTY, u"", - LWOOBJID_EMPTY, UNASSIGNED_SYSTEM_ADDRESS); - - for (const auto &player : m_RacingPlayers) { - auto *vehicle = - EntityManager::Instance()->GetEntity(player.vehicleID); - auto *playerEntity = - EntityManager::Instance()->GetEntity(player.playerID); + if (readyPlayers >= m_LoadedPlayers) { + // Setup for racing + if (m_StartTimer == 0) { + GameMessages::SendNotifyRacingClient( + m_Parent->GetObjectID(), 1, 0, LWOOBJID_EMPTY, u"", + LWOOBJID_EMPTY, UNASSIGNED_SYSTEM_ADDRESS); + + for (const auto& player : m_RacingPlayers) { + auto* vehicle = + EntityManager::Instance()->GetEntity(player.vehicleID); + auto* playerEntity = + EntityManager::Instance()->GetEntity(player.playerID); - if (vehicle != nullptr && playerEntity != nullptr) { - GameMessages::SendTeleport( - player.playerID, player.respawnPosition, - player.respawnRotation, - playerEntity->GetSystemAddress(), true, true); + if (vehicle != nullptr && playerEntity != nullptr) { + GameMessages::SendTeleport( + player.playerID, player.respawnPosition, + player.respawnRotation, + playerEntity->GetSystemAddress(), true, true); - vehicle->SetPosition(player.respawnPosition); - vehicle->SetRotation(player.respawnRotation); + vehicle->SetPosition(player.respawnPosition); + vehicle->SetRotation(player.respawnRotation); - auto *destroyableComponent = - vehicle->GetComponent(); + auto* destroyableComponent = + vehicle->GetComponent(); - if (destroyableComponent != nullptr) { - destroyableComponent->SetImagination(0); - } - - EntityManager::Instance()->SerializeEntity(vehicle); - EntityManager::Instance()->SerializeEntity( - playerEntity); - } - } + if (destroyableComponent != nullptr) { + destroyableComponent->SetImagination(0); + } + + EntityManager::Instance()->SerializeEntity(vehicle); + EntityManager::Instance()->SerializeEntity( + playerEntity); + } + } - // Spawn imagination pickups - auto *minSpawner = dZoneManager::Instance()->GetSpawnersByName( - "ImaginationSpawn_Min")[0]; - auto *medSpawner = dZoneManager::Instance()->GetSpawnersByName( - "ImaginationSpawn_Med")[0]; - auto *maxSpawner = dZoneManager::Instance()->GetSpawnersByName( - "ImaginationSpawn_Max")[0]; - - minSpawner->Activate(); - - if (m_LoadedPlayers > 2) { - medSpawner->Activate(); - } - - if (m_LoadedPlayers > 4) { - maxSpawner->Activate(); - } - - // Reset players to their start location, without smashing them - for (auto &player : m_RacingPlayers) { - auto *vehicleEntity = - EntityManager::Instance()->GetEntity(player.vehicleID); - auto *playerEntity = - EntityManager::Instance()->GetEntity(player.playerID); - - if (vehicleEntity == nullptr || playerEntity == nullptr) { - continue; - } + // Spawn imagination pickups + auto* minSpawner = dZoneManager::Instance()->GetSpawnersByName( + "ImaginationSpawn_Min")[0]; + auto* medSpawner = dZoneManager::Instance()->GetSpawnersByName( + "ImaginationSpawn_Med")[0]; + auto* maxSpawner = dZoneManager::Instance()->GetSpawnersByName( + "ImaginationSpawn_Max")[0]; + + minSpawner->Activate(); + + if (m_LoadedPlayers > 2) { + medSpawner->Activate(); + } + + if (m_LoadedPlayers > 4) { + maxSpawner->Activate(); + } + + // Reset players to their start location, without smashing them + for (auto& player : m_RacingPlayers) { + auto* vehicleEntity = + EntityManager::Instance()->GetEntity(player.vehicleID); + auto* playerEntity = + EntityManager::Instance()->GetEntity(player.playerID); + + if (vehicleEntity == nullptr || playerEntity == nullptr) { + continue; + } - player.noSmashOnReload = true; + player.noSmashOnReload = true; - OnRequestDie(playerEntity); - } - } - // This 6 seconds seems to be hardcoded in the client, start race - // after that amount of time - else if (m_StartTimer >= 6) { - // Activate the players movement - for (auto &player : m_RacingPlayers) { - auto *vehicleEntity = - EntityManager::Instance()->GetEntity(player.vehicleID); - auto *playerEntity = - EntityManager::Instance()->GetEntity(player.playerID); - - if (vehicleEntity == nullptr || playerEntity == nullptr) { - continue; - } - - GameMessages::SendVehicleUnlockInput( - player.vehicleID, false, UNASSIGNED_SYSTEM_ADDRESS); - } - - // Start the race - GameMessages::SendActivityStart(m_Parent->GetObjectID(), - UNASSIGNED_SYSTEM_ADDRESS); - - m_Started = true; - - Game::logger->Log("RacingControlComponent", "Starting race"); - - EntityManager::Instance()->SerializeEntity(m_Parent); - - m_StartTime = std::time(nullptr); - } - - m_StartTimer += deltaTime; - } else { - m_StartTimer = 0; - } + OnRequestDie(playerEntity); + } + } + // This 6 seconds seems to be hardcoded in the client, start race + // after that amount of time + else if (m_StartTimer >= 6) { + // Activate the players movement + for (auto& player : m_RacingPlayers) { + auto* vehicleEntity = + EntityManager::Instance()->GetEntity(player.vehicleID); + auto* playerEntity = + EntityManager::Instance()->GetEntity(player.playerID); + + if (vehicleEntity == nullptr || playerEntity == nullptr) { + continue; + } + + GameMessages::SendVehicleUnlockInput( + player.vehicleID, false, UNASSIGNED_SYSTEM_ADDRESS); + } + + // Start the race + GameMessages::SendActivityStart(m_Parent->GetObjectID(), + UNASSIGNED_SYSTEM_ADDRESS); + + m_Started = true; + + Game::logger->Log("RacingControlComponent", "Starting race"); + + EntityManager::Instance()->SerializeEntity(m_Parent); + + m_StartTime = std::time(nullptr); + } + + m_StartTimer += deltaTime; + } else { + m_StartTimer = 0; + } - return; - } + return; + } - // Race routines - auto *path = dZoneManager::Instance()->GetZone()->GetPath( - GeneralUtils::UTF16ToWTF8(m_PathName)); + // Race routines + auto* path = dZoneManager::Instance()->GetZone()->GetPath( + GeneralUtils::UTF16ToWTF8(m_PathName)); - for (auto &player : m_RacingPlayers) { - auto *vehicle = EntityManager::Instance()->GetEntity(player.vehicleID); - auto *playerEntity = - EntityManager::Instance()->GetEntity(player.playerID); + for (auto& player : m_RacingPlayers) { + auto* vehicle = EntityManager::Instance()->GetEntity(player.vehicleID); + auto* playerEntity = + EntityManager::Instance()->GetEntity(player.playerID); - if (vehicle == nullptr || playerEntity == nullptr) { - continue; - } + if (vehicle == nullptr || playerEntity == nullptr) { + continue; + } - const auto vehiclePosition = vehicle->GetPosition(); + const auto vehiclePosition = vehicle->GetPosition(); - // If the player is this far below the map, safe to assume they should - // be smashed by death plane - if (vehiclePosition.y < -500) { - GameMessages::SendDie(vehicle, m_Parent->GetObjectID(), - LWOOBJID_EMPTY, true, VIOLENT, u"", 0, 0, 0, - true, false, 0); + // If the player is this far below the map, safe to assume they should + // be smashed by death plane + if (vehiclePosition.y < -500) { + GameMessages::SendDie(vehicle, m_Parent->GetObjectID(), + LWOOBJID_EMPTY, true, VIOLENT, u"", 0, 0, 0, + true, false, 0); - OnRequestDie(playerEntity); + OnRequestDie(playerEntity); - continue; - } + continue; + } - // Loop through all the waypoints and see if the player has reached a - // new checkpoint - uint32_t respawnIndex = 0; - for (const auto &waypoint : path->pathWaypoints) { - if (player.lap == 3) { - break; - } + // Loop through all the waypoints and see if the player has reached a + // new checkpoint + uint32_t respawnIndex = 0; + for (const auto& waypoint : path->pathWaypoints) { + if (player.lap == 3) { + break; + } - if (player.respawnIndex == respawnIndex) { - ++respawnIndex; + if (player.respawnIndex == respawnIndex) { + ++respawnIndex; - continue; - } + continue; + } - const auto &position = waypoint.position; + const auto& position = waypoint.position; - if (std::abs((int)respawnIndex - (int)player.respawnIndex) > 10 && - player.respawnIndex != path->pathWaypoints.size() - 1) { - ++respawnIndex; + if (std::abs((int)respawnIndex - (int)player.respawnIndex) > 10 && + player.respawnIndex != path->pathWaypoints.size() - 1) { + ++respawnIndex; - continue; - } + continue; + } - if (Vector3::DistanceSquared(position, vehiclePosition) > 50 * 50) { - ++respawnIndex; + if (Vector3::DistanceSquared(position, vehiclePosition) > 50 * 50) { + ++respawnIndex; - continue; - } + continue; + } - // Only go upwards, except if we've lapped - // Not sure how we are supposed to check if they've reach a - // checkpoint, within 50 units seems safe - if (!(respawnIndex > player.respawnIndex || - player.respawnIndex == path->pathWaypoints.size() - 1)) { - ++respawnIndex; + // Only go upwards, except if we've lapped + // Not sure how we are supposed to check if they've reach a + // checkpoint, within 50 units seems safe + if (!(respawnIndex > player.respawnIndex || + player.respawnIndex == path->pathWaypoints.size() - 1)) { + ++respawnIndex; - continue; - } + continue; + } - // Some offset up to make they don't fall through the terrain on a - // respawn, seems to fix itself to the track anyhow - player.respawnPosition = position + NiPoint3::UNIT_Y * 5; - player.respawnRotation = vehicle->GetRotation(); - player.respawnIndex = respawnIndex; + // Some offset up to make they don't fall through the terrain on a + // respawn, seems to fix itself to the track anyhow + player.respawnPosition = position + NiPoint3::UNIT_Y * 5; + player.respawnRotation = vehicle->GetRotation(); + player.respawnIndex = respawnIndex; - // Reached the start point, lapped - if (respawnIndex == 0) { - time_t lapTime = std::time(nullptr) - (player.lap == 1 ? m_StartTime : player.lapTime); + // Reached the start point, lapped + if (respawnIndex == 0) { + time_t lapTime = std::time(nullptr) - (player.lap == 1 ? m_StartTime : player.lapTime); - // Cheating check - if (lapTime < 40) { - continue; - } + // Cheating check + if (lapTime < 40) { + continue; + } - player.lap++; + player.lap++; - player.lapTime = std::time(nullptr); + player.lapTime = std::time(nullptr); - if (player.bestLapTime == 0 || player.bestLapTime > lapTime) { - player.bestLapTime = lapTime; + if (player.bestLapTime == 0 || player.bestLapTime > lapTime) { + player.bestLapTime = lapTime; - Game::logger->Log("RacingControlComponent", - "Best lap time (%llu)", lapTime); - } + Game::logger->Log("RacingControlComponent", + "Best lap time (%llu)", lapTime); + } - auto *missionComponent = - playerEntity->GetComponent(); + auto* missionComponent = + playerEntity->GetComponent(); - if (missionComponent != nullptr) { + if (missionComponent != nullptr) { - // Progress lap time tasks - missionComponent->Progress(MissionTaskType::MISSION_TASK_TYPE_RACING, (lapTime)*1000, (LWOOBJID)RacingTaskParam::RACING_TASK_PARAM_LAP_TIME); + // Progress lap time tasks + missionComponent->Progress(MissionTaskType::MISSION_TASK_TYPE_RACING, (lapTime) * 1000, (LWOOBJID)RacingTaskParam::RACING_TASK_PARAM_LAP_TIME); - if (player.lap == 3) { - m_Finished++; - player.finished = m_Finished; + if (player.lap == 3) { + m_Finished++; + player.finished = m_Finished; - const auto raceTime = - (std::time(nullptr) - m_StartTime); + const auto raceTime = + (std::time(nullptr) - m_StartTime); - player.raceTime = raceTime; + player.raceTime = raceTime; - Game::logger->Log("RacingControlComponent", - "Completed time %llu, %llu", - raceTime, raceTime * 1000); + Game::logger->Log("RacingControlComponent", + "Completed time %llu, %llu", + raceTime, raceTime * 1000); - // Entire race time - missionComponent->Progress(MissionTaskType::MISSION_TASK_TYPE_RACING, (raceTime)*1000, (LWOOBJID)RacingTaskParam::RACING_TASK_PARAM_TOTAL_TRACK_TIME); + // Entire race time + missionComponent->Progress(MissionTaskType::MISSION_TASK_TYPE_RACING, (raceTime) * 1000, (LWOOBJID)RacingTaskParam::RACING_TASK_PARAM_TOTAL_TRACK_TIME); - auto *characterComponent = playerEntity->GetComponent(); - if (characterComponent != nullptr) { - characterComponent->TrackRaceCompleted(m_Finished == 1); - } + auto* characterComponent = playerEntity->GetComponent(); + if (characterComponent != nullptr) { + characterComponent->TrackRaceCompleted(m_Finished == 1); + } - // TODO: Figure out how to update the GUI leaderboard. - } - } + // TODO: Figure out how to update the GUI leaderboard. + } + } - Game::logger->Log("RacingControlComponent", - "Lapped (%i) in (%llu)", player.lap, - lapTime); - } + Game::logger->Log("RacingControlComponent", + "Lapped (%i) in (%llu)", player.lap, + lapTime); + } - Game::logger->Log("RacingControlComponent", - "Reached point (%i)/(%i)", player.respawnIndex, - path->pathWaypoints.size()); + Game::logger->Log("RacingControlComponent", + "Reached point (%i)/(%i)", player.respawnIndex, + path->pathWaypoints.size()); - break; - } - } + break; + } + } } std::string RacingControlComponent::FormatTimeString(time_t time) { - int32_t min = time / 60; - time -= min * 60; - int32_t sec = time; + int32_t min = time / 60; + time -= min * 60; + int32_t sec = time; - std::string minText; - std::string secText; + std::string minText; + std::string secText; - if (min <= 0) { - minText = "0"; - } else { - minText = std::to_string(min); - } + if (min <= 0) { + minText = "0"; + } else { + minText = std::to_string(min); + } - if (sec <= 0) { - secText = "00"; - } else if (sec <= 9) { - secText = "0" + std::to_string(sec); - } else { - secText = std::to_string(sec); - } + if (sec <= 0) { + secText = "00"; + } else if (sec <= 9) { + secText = "0" + std::to_string(sec); + } else { + secText = std::to_string(sec); + } - return minText + ":" + secText + ".00"; + return minText + ":" + secText + ".00"; } diff --git a/dGame/dComponents/RacingControlComponent.h b/dGame/dComponents/RacingControlComponent.h index 63d5b2e4..dac60962 100644 --- a/dGame/dComponents/RacingControlComponent.h +++ b/dGame/dComponents/RacingControlComponent.h @@ -8,95 +8,95 @@ #include "Entity.h" #include "Component.h" -/** - * Information for each player in the race - */ + /** + * Information for each player in the race + */ struct RacingPlayerInfo { - /** - * The ID of the player - */ - LWOOBJID playerID; + /** + * The ID of the player + */ + LWOOBJID playerID; - /** - * The ID of the car the player is driving - */ - LWOOBJID vehicleID; + /** + * The ID of the car the player is driving + */ + LWOOBJID vehicleID; - /** - * The index of this player in the list of players - */ - uint32_t playerIndex; + /** + * The index of this player in the list of players + */ + uint32_t playerIndex; - /** - * Whether the player has finished loading or not - */ - bool playerLoaded; + /** + * Whether the player has finished loading or not + */ + bool playerLoaded; - /** - * Scripted activity component score - */ - float data[10] {}; + /** + * Scripted activity component score + */ + float data[10]{}; - /** - * Point that the player will respawn at if they smash their car - */ - NiPoint3 respawnPosition; + /** + * Point that the player will respawn at if they smash their car + */ + NiPoint3 respawnPosition; - /** - * Rotation that the player will respawn at if they smash their car - */ - NiQuaternion respawnRotation; + /** + * Rotation that the player will respawn at if they smash their car + */ + NiQuaternion respawnRotation; - /** - * The index in the respawn point the player is now at - */ - uint32_t respawnIndex; + /** + * The index in the respawn point the player is now at + */ + uint32_t respawnIndex; - /** - * The number of laps the player has completed - */ - uint32_t lap; + /** + * The number of laps the player has completed + */ + uint32_t lap; - /** - * Whether or not the player has finished the race - */ - uint32_t finished; + /** + * Whether or not the player has finished the race + */ + uint32_t finished; - /** - * Unused - */ - uint16_t reachedPoints; + /** + * Unused + */ + uint16_t reachedPoints; - /** - * The fastest lap time of the player - */ - time_t bestLapTime = 0; + /** + * The fastest lap time of the player + */ + time_t bestLapTime = 0; - /** - * The current lap time of the player - */ - time_t lapTime = 0; + /** + * The current lap time of the player + */ + time_t lapTime = 0; - /** - * The number of times this player smashed their car - */ - uint32_t smashedTimes = 0; + /** + * The number of times this player smashed their car + */ + uint32_t smashedTimes = 0; - /** - * Whether or not the player should be smashed if the game is reloaded - */ - bool noSmashOnReload = false; + /** + * Whether or not the player should be smashed if the game is reloaded + */ + bool noSmashOnReload = false; - /** - * Whether or not this player has collected their rewards from completing the race - */ - bool collectedRewards = false; + /** + * Whether or not this player has collected their rewards from completing the race + */ + bool collectedRewards = false; - /** - * Unused - */ - time_t raceTime = 0; + /** + * Unused + */ + time_t raceTime = 0; }; /** @@ -105,144 +105,144 @@ struct RacingPlayerInfo { class RacingControlComponent : public Component { public: static const uint32_t ComponentType = COMPONENT_TYPE_RACING_CONTROL; - + RacingControlComponent(Entity* parentEntity); ~RacingControlComponent(); - void Serialize(RakNet::BitStream* outBitStream, bool bIsInitialUpdate, unsigned int& flags); - void Update(float deltaTime); + void Serialize(RakNet::BitStream* outBitStream, bool bIsInitialUpdate, unsigned int& flags); + void Update(float deltaTime); - /** - * Invoked when a player loads into the zone. - */ - void OnPlayerLoaded(Entity* player); + /** + * Invoked when a player loads into the zone. + */ + void OnPlayerLoaded(Entity* player); - /** - * Initalize the player's vehicle. - * - * @param player The player who's vehicle to initialize. - * @param initialLoad Is this the first time the player is loading in this race? - */ - void LoadPlayerVehicle(Entity* player, bool initialLoad = false); + /** + * Initalize the player's vehicle. + * + * @param player The player who's vehicle to initialize. + * @param initialLoad Is this the first time the player is loading in this race? + */ + void LoadPlayerVehicle(Entity* player, bool initialLoad = false); - /** - * Invoked when the client says it has loaded in. - */ - void OnRacingClientReady(Entity* player); + /** + * Invoked when the client says it has loaded in. + */ + void OnRacingClientReady(Entity* player); - /** - * Invoked when the client says it should be smashed. - */ - void OnRequestDie(Entity* player); + /** + * Invoked when the client says it should be smashed. + */ + void OnRequestDie(Entity* player); - /** - * Invoked when the player has finished respawning. - */ - void OnRacingPlayerInfoResetFinished(Entity* player); + /** + * Invoked when the player has finished respawning. + */ + void OnRacingPlayerInfoResetFinished(Entity* player); - /** - * Invoked when the player responds to the GUI. - */ - void HandleMessageBoxResponse(Entity* player, const std::string& id); + /** + * Invoked when the player responds to the GUI. + */ + void HandleMessageBoxResponse(Entity* player, const std::string& id); - /** - * Get the racing data from a player's LWOOBJID. - */ - RacingPlayerInfo* GetPlayerData(LWOOBJID playerID); + /** + * Get the racing data from a player's LWOOBJID. + */ + RacingPlayerInfo* GetPlayerData(LWOOBJID playerID); - /** - * Formats a time to a string, currently unused - * @param time the time to format - * @return the time formatted as string - */ - static std::string FormatTimeString(time_t time); + /** + * Formats a time to a string, currently unused + * @param time the time to format + * @return the time formatted as string + */ + static std::string FormatTimeString(time_t time); private: - /** - * The players that are currently racing - */ - std::vector m_RacingPlayers; + /** + * The players that are currently racing + */ + std::vector m_RacingPlayers; - /** - * The paths that are followed for the camera scenes - */ - std::u16string m_PathName; + /** + * The paths that are followed for the camera scenes + */ + std::u16string m_PathName; - /** - * The ID of the activity for participating in this race - */ - uint32_t m_ActivityID; + /** + * The ID of the activity for participating in this race + */ + uint32_t m_ActivityID; - /** - * The world the players return to when they finish the race - */ - uint32_t m_MainWorld; + /** + * The world the players return to when they finish the race + */ + uint32_t m_MainWorld; - /** - * The number of laps that are remaining for the winning player - */ - uint16_t m_RemainingLaps; + /** + * The number of laps that are remaining for the winning player + */ + uint16_t m_RemainingLaps; - /** - * The ID of the player that's currently winning the race - */ - LWOOBJID m_LeadingPlayer; + /** + * The ID of the player that's currently winning the race + */ + LWOOBJID m_LeadingPlayer; - /** - * The overall best lap from all the players - */ - float m_RaceBestLap; + /** + * The overall best lap from all the players + */ + float m_RaceBestLap; - /** - * The overall best time from all the players - */ - float m_RaceBestTime; + /** + * The overall best time from all the players + */ + float m_RaceBestTime; - /** - * Whether or not the race has started - */ - bool m_Started; + /** + * Whether or not the race has started + */ + bool m_Started; - /** - * The time left until the race will start - */ - float m_StartTimer; + /** + * The time left until the race will start + */ + float m_StartTimer; - /** - * The time left for loading the players - */ - float m_LoadTimer; + /** + * The time left for loading the players + */ + float m_LoadTimer; - /** - * Whether or not all players have loaded - */ - bool m_Loaded; + /** + * Whether or not all players have loaded + */ + bool m_Loaded; - /** - * The number of loaded players - */ - uint32_t m_LoadedPlayers; + /** + * The number of loaded players + */ + uint32_t m_LoadedPlayers; - /** - * All the players that are in the lobby, loaded or not - */ - std::vector m_LobbyPlayers; + /** + * All the players that are in the lobby, loaded or not + */ + std::vector m_LobbyPlayers; - /** - * The number of players that have finished the race - */ - uint32_t m_Finished; + /** + * The number of players that have finished the race + */ + uint32_t m_Finished; - /** - * The time the race was started - */ - time_t m_StartTime; + /** + * The time the race was started + */ + time_t m_StartTime; - /** - * Timer for tracking how long a player was alone in this race - */ - float m_EmptyTimer; + /** + * Timer for tracking how long a player was alone in this race + */ + float m_EmptyTimer; - bool m_SoloRacing; + bool m_SoloRacing; }; diff --git a/dGame/dComponents/RailActivatorComponent.cpp b/dGame/dComponents/RailActivatorComponent.cpp index 9cdc93f1..1b94fc4a 100644 --- a/dGame/dComponents/RailActivatorComponent.cpp +++ b/dGame/dComponents/RailActivatorComponent.cpp @@ -8,159 +8,150 @@ #include "Game.h" #include "dLogger.h" -RailActivatorComponent::RailActivatorComponent(Entity *parent, int32_t componentID) : Component(parent) { - m_ComponentID = componentID; - const auto tableData = CDClientManager::Instance() - ->GetTable("RailActivatorComponent")->GetEntryByID(componentID); +RailActivatorComponent::RailActivatorComponent(Entity* parent, int32_t componentID) : Component(parent) { + m_ComponentID = componentID; + const auto tableData = CDClientManager::Instance() + ->GetTable("RailActivatorComponent")->GetEntryByID(componentID); - m_Path = parent->GetVar(u"rail_path"); - m_PathDirection = parent->GetVar(u"rail_path_direction"); - m_PathStart = parent->GetVar(u"rail_path_start"); + m_Path = parent->GetVar(u"rail_path"); + m_PathDirection = parent->GetVar(u"rail_path_direction"); + m_PathStart = parent->GetVar(u"rail_path_start"); - m_StartSound = tableData.startSound; - m_loopSound = tableData.loopSound; - m_StopSound = tableData.stopSound; + m_StartSound = tableData.startSound; + m_loopSound = tableData.loopSound; + m_StopSound = tableData.stopSound; - m_StartAnimation = tableData.startAnimation; - m_LoopAnimation = tableData.loopAnimation; - m_StopAnimation = tableData.stopAnimation; + m_StartAnimation = tableData.startAnimation; + m_LoopAnimation = tableData.loopAnimation; + m_StopAnimation = tableData.stopAnimation; - m_StartEffect = tableData.startEffectID; - m_LoopEffect = tableData.loopEffectID; - m_StopEffect = tableData.stopEffectID; + m_StartEffect = tableData.startEffectID; + m_LoopEffect = tableData.loopEffectID; + m_StopEffect = tableData.stopEffectID; - m_DamageImmune = parent->GetVar(u"rail_activator_damage_immune"); - m_NoAggro = parent->GetVar(u"rail_no_aggro"); - m_NotifyArrived = parent->GetVar(u"rail_notify_activator_arrived"); - m_ShowNameBillboard = parent->GetVar(u"rail_show_name_billboard"); - m_UseDB = parent->GetVar(u"rail_use_db"); - m_CameraLocked = tableData.cameraLocked; - m_CollisionEnabled = tableData.playerCollision; + m_DamageImmune = parent->GetVar(u"rail_activator_damage_immune"); + m_NoAggro = parent->GetVar(u"rail_no_aggro"); + m_NotifyArrived = parent->GetVar(u"rail_notify_activator_arrived"); + m_ShowNameBillboard = parent->GetVar(u"rail_show_name_billboard"); + m_UseDB = parent->GetVar(u"rail_use_db"); + m_CameraLocked = tableData.cameraLocked; + m_CollisionEnabled = tableData.playerCollision; } RailActivatorComponent::~RailActivatorComponent() = default; -void RailActivatorComponent::OnUse(Entity *originator) { - auto* rebuildComponent = m_Parent->GetComponent(); - if (rebuildComponent != nullptr && rebuildComponent->GetState() != REBUILD_COMPLETED) - return; +void RailActivatorComponent::OnUse(Entity* originator) { + auto* rebuildComponent = m_Parent->GetComponent(); + if (rebuildComponent != nullptr && rebuildComponent->GetState() != REBUILD_COMPLETED) + return; - if (rebuildComponent != nullptr) { - // Don't want it to be destroyed while a player is using it - rebuildComponent->SetResetTime(rebuildComponent->GetResetTime() + 10.0f); - } + if (rebuildComponent != nullptr) { + // Don't want it to be destroyed while a player is using it + rebuildComponent->SetResetTime(rebuildComponent->GetResetTime() + 10.0f); + } - m_EntitiesOnRail.push_back(originator->GetObjectID()); + m_EntitiesOnRail.push_back(originator->GetObjectID()); - // Start the initial effects - if (!m_StartEffect.second.empty()) { - GameMessages::SendPlayFXEffect(originator->GetObjectID(), m_StartEffect.first, m_StartEffect.second, - std::to_string(m_StartEffect.first)); - } + // Start the initial effects + if (!m_StartEffect.second.empty()) { + GameMessages::SendPlayFXEffect(originator->GetObjectID(), m_StartEffect.first, m_StartEffect.second, + std::to_string(m_StartEffect.first)); + } - if (!m_StartAnimation.empty()) { - GameMessages::SendPlayAnimation(originator, m_StartAnimation); - } + if (!m_StartAnimation.empty()) { + GameMessages::SendPlayAnimation(originator, m_StartAnimation); + } - float animationLength; - - if (m_StartAnimation == u"whirlwind-rail-up-earth") - { - animationLength = 1.5f; - } - else if (m_StartAnimation == u"whirlwind-rail-up-lightning") - { - animationLength = 0.5f; - } - else if (m_StartAnimation == u"whirlwind-rail-up-ice") - { - animationLength = 0.5f; - } - else if (m_StartAnimation == u"whirlwind-rail-up-fire") - { - animationLength = 0.5f; - } - else - { - animationLength = 0.5f; - } + float animationLength; - const auto originatorID = originator->GetObjectID(); + if (m_StartAnimation == u"whirlwind-rail-up-earth") { + animationLength = 1.5f; + } else if (m_StartAnimation == u"whirlwind-rail-up-lightning") { + animationLength = 0.5f; + } else if (m_StartAnimation == u"whirlwind-rail-up-ice") { + animationLength = 0.5f; + } else if (m_StartAnimation == u"whirlwind-rail-up-fire") { + animationLength = 0.5f; + } else { + animationLength = 0.5f; + } - m_Parent->AddCallbackTimer(animationLength, [originatorID, this] () { - auto* originator = EntityManager::Instance()->GetEntity(originatorID); + const auto originatorID = originator->GetObjectID(); - if (originator == nullptr) { - return; - } + m_Parent->AddCallbackTimer(animationLength, [originatorID, this]() { + auto* originator = EntityManager::Instance()->GetEntity(originatorID); - GameMessages::SendStartRailMovement(originator->GetObjectID(), m_Path, m_StartSound, - m_loopSound, m_StopSound, originator->GetSystemAddress(), - m_PathStart, m_PathDirection, m_DamageImmune, m_NoAggro, m_NotifyArrived, - m_ShowNameBillboard, m_CameraLocked, m_CollisionEnabled, m_UseDB, m_ComponentID, - m_Parent->GetObjectID()); - }); + if (originator == nullptr) { + return; + } + + GameMessages::SendStartRailMovement(originator->GetObjectID(), m_Path, m_StartSound, + m_loopSound, m_StopSound, originator->GetSystemAddress(), + m_PathStart, m_PathDirection, m_DamageImmune, m_NoAggro, m_NotifyArrived, + m_ShowNameBillboard, m_CameraLocked, m_CollisionEnabled, m_UseDB, m_ComponentID, + m_Parent->GetObjectID()); + }); } -void RailActivatorComponent::OnRailMovementReady(Entity *originator) const { - // Stun the originator - GameMessages::SendSetStunned(originator->GetObjectID(), PUSH, originator->GetSystemAddress(), LWOOBJID_EMPTY, - true, true, true, true, true, true, true - ); +void RailActivatorComponent::OnRailMovementReady(Entity* originator) const { + // Stun the originator + GameMessages::SendSetStunned(originator->GetObjectID(), PUSH, originator->GetSystemAddress(), LWOOBJID_EMPTY, + true, true, true, true, true, true, true + ); - if (std::find(m_EntitiesOnRail.begin(), m_EntitiesOnRail.end(), originator->GetObjectID()) != m_EntitiesOnRail.end()) { - // Stop the initial effects - if (!m_StartEffect.second.empty()) { - GameMessages::SendStopFXEffect(originator, false, std::to_string(m_StartEffect.first)); - } + if (std::find(m_EntitiesOnRail.begin(), m_EntitiesOnRail.end(), originator->GetObjectID()) != m_EntitiesOnRail.end()) { + // Stop the initial effects + if (!m_StartEffect.second.empty()) { + GameMessages::SendStopFXEffect(originator, false, std::to_string(m_StartEffect.first)); + } - // Start the looping effects - if (!m_LoopEffect.second.empty()) { - GameMessages::SendPlayFXEffect(originator->GetObjectID(), m_LoopEffect.first, m_LoopEffect.second, - std::to_string(m_LoopEffect.first)); - } + // Start the looping effects + if (!m_LoopEffect.second.empty()) { + GameMessages::SendPlayFXEffect(originator->GetObjectID(), m_LoopEffect.first, m_LoopEffect.second, + std::to_string(m_LoopEffect.first)); + } - if (!m_LoopAnimation.empty()) { - GameMessages::SendPlayAnimation(originator, m_LoopAnimation); - } + if (!m_LoopAnimation.empty()) { + GameMessages::SendPlayAnimation(originator, m_LoopAnimation); + } - GameMessages::SendSetRailMovement(originator->GetObjectID(), m_PathDirection, m_Path, m_PathStart, - originator->GetSystemAddress(), m_ComponentID, - m_Parent->GetObjectID()); - } + GameMessages::SendSetRailMovement(originator->GetObjectID(), m_PathDirection, m_Path, m_PathStart, + originator->GetSystemAddress(), m_ComponentID, + m_Parent->GetObjectID()); + } } -void RailActivatorComponent::OnCancelRailMovement(Entity *originator) { - // Remove the stun from the originator - GameMessages::SendSetStunned(originator->GetObjectID(), POP, originator->GetSystemAddress(), LWOOBJID_EMPTY, - true, true, true, true, true, true, true - ); +void RailActivatorComponent::OnCancelRailMovement(Entity* originator) { + // Remove the stun from the originator + GameMessages::SendSetStunned(originator->GetObjectID(), POP, originator->GetSystemAddress(), LWOOBJID_EMPTY, + true, true, true, true, true, true, true + ); - auto* rebuildComponent = m_Parent->GetComponent(); + auto* rebuildComponent = m_Parent->GetComponent(); - if (rebuildComponent != nullptr) { - // Set back reset time - rebuildComponent->SetResetTime(rebuildComponent->GetResetTime() - 10.0f); - } + if (rebuildComponent != nullptr) { + // Set back reset time + rebuildComponent->SetResetTime(rebuildComponent->GetResetTime() - 10.0f); + } - if (std::find(m_EntitiesOnRail.begin(), m_EntitiesOnRail.end(), originator->GetObjectID()) != m_EntitiesOnRail.end()) { - // Stop the looping effects - if (!m_LoopEffect.second.empty()) { - GameMessages::SendStopFXEffect(originator, false, std::to_string(m_LoopEffect.first)); - } + if (std::find(m_EntitiesOnRail.begin(), m_EntitiesOnRail.end(), originator->GetObjectID()) != m_EntitiesOnRail.end()) { + // Stop the looping effects + if (!m_LoopEffect.second.empty()) { + GameMessages::SendStopFXEffect(originator, false, std::to_string(m_LoopEffect.first)); + } - // Start the end effects - if (!m_StopEffect.second.empty()) { - GameMessages::SendPlayFXEffect(originator->GetObjectID(), m_StopEffect.first, m_StopEffect.second, - std::to_string(m_StopEffect.first)); - } + // Start the end effects + if (!m_StopEffect.second.empty()) { + GameMessages::SendPlayFXEffect(originator->GetObjectID(), m_StopEffect.first, m_StopEffect.second, + std::to_string(m_StopEffect.first)); + } - if (!m_StopAnimation.empty()) { - GameMessages::SendPlayAnimation(originator, m_StopAnimation); - } + if (!m_StopAnimation.empty()) { + GameMessages::SendPlayAnimation(originator, m_StopAnimation); + } - // Remove the player after they've signalled they're done railing - m_EntitiesOnRail.erase(std::remove(m_EntitiesOnRail.begin(), m_EntitiesOnRail.end(), - originator->GetObjectID()),m_EntitiesOnRail.end()); - } + // Remove the player after they've signalled they're done railing + m_EntitiesOnRail.erase(std::remove(m_EntitiesOnRail.begin(), m_EntitiesOnRail.end(), + originator->GetObjectID()), m_EntitiesOnRail.end()); + } } diff --git a/dGame/dComponents/RailActivatorComponent.h b/dGame/dComponents/RailActivatorComponent.h index 82607dcf..8f67e7e3 100644 --- a/dGame/dComponents/RailActivatorComponent.h +++ b/dGame/dComponents/RailActivatorComponent.h @@ -11,134 +11,134 @@ */ class RailActivatorComponent final : public Component { public: - explicit RailActivatorComponent(Entity* parent, int32_t componentID); - ~RailActivatorComponent() override; + explicit RailActivatorComponent(Entity* parent, int32_t componentID); + ~RailActivatorComponent() override; - static const uint32_t ComponentType = COMPONENT_TYPE_RAIL_ACTIVATOR; + static const uint32_t ComponentType = COMPONENT_TYPE_RAIL_ACTIVATOR; - /** - * Handles the OnUse event from some entity, initiates the rail movement - * @param originator the entity that triggered the event - */ - void OnUse(Entity *originator) override; + /** + * Handles the OnUse event from some entity, initiates the rail movement + * @param originator the entity that triggered the event + */ + void OnUse(Entity* originator) override; - /** - * Event handler that's called when some entity has played the start animation for rail movement and now wants to - * start the actual movement. - * @param originator the entity that triggered the event - */ - void OnRailMovementReady(Entity* originator) const; + /** + * Event handler that's called when some entity has played the start animation for rail movement and now wants to + * start the actual movement. + * @param originator the entity that triggered the event + */ + void OnRailMovementReady(Entity* originator) const; - /** - * Event handler that's called when some entity has finished traversing the rail and wants to end its interaction - * with it - * @param originator the entity that triggered the event - */ - void OnCancelRailMovement(Entity* originator); + /** + * Event handler that's called when some entity has finished traversing the rail and wants to end its interaction + * with it + * @param originator the entity that triggered the event + */ + void OnCancelRailMovement(Entity* originator); private: - /** - * The ID of this component in the components database - */ - int32_t m_ComponentID; + /** + * The ID of this component in the components database + */ + int32_t m_ComponentID; - /** - * The entities that are currently traversing the rail - */ - std::vector m_EntitiesOnRail {}; + /** + * The entities that are currently traversing the rail + */ + std::vector m_EntitiesOnRail{}; - /** - * The path the entities will follow when traversing the rail - */ - std::u16string m_Path; + /** + * The path the entities will follow when traversing the rail + */ + std::u16string m_Path; - /** - * The index of the path that is the start - */ - uint32_t m_PathStart; + /** + * The index of the path that is the start + */ + uint32_t m_PathStart; - /** - * The direction on the path - */ - bool m_PathDirection; + /** + * The direction on the path + */ + bool m_PathDirection; - /** - * The animation that plays when starting the rail - */ - std::u16string m_StartAnimation; + /** + * The animation that plays when starting the rail + */ + std::u16string m_StartAnimation; - /** - * The animation that plays during the rail - */ - std::u16string m_LoopAnimation; + /** + * The animation that plays during the rail + */ + std::u16string m_LoopAnimation; - /** - * The animation that plays after the rail - */ - std::u16string m_StopAnimation; + /** + * The animation that plays after the rail + */ + std::u16string m_StopAnimation; - /** - * The sound that plays at the start of the rail - */ - std::u16string m_StartSound; + /** + * The sound that plays at the start of the rail + */ + std::u16string m_StartSound; - /** - * The sound that plays during the rail - */ - std::u16string m_loopSound; + /** + * The sound that plays during the rail + */ + std::u16string m_loopSound; - /** - * The sound that plays at the end of the rail - */ - std::u16string m_StopSound; + /** + * The sound that plays at the end of the rail + */ + std::u16string m_StopSound; - /** - * The effects that play at the start of the rail - */ - std::pair m_StartEffect; + /** + * The effects that play at the start of the rail + */ + std::pair m_StartEffect; - /** - * The effects that play during the rail - */ - std::pair m_LoopEffect; + /** + * The effects that play during the rail + */ + std::pair m_LoopEffect; - /** - * The effects that play at the end of the rail - */ - std::pair m_StopEffect; + /** + * The effects that play at the end of the rail + */ + std::pair m_StopEffect; - /** - * Client flag - */ - bool m_DamageImmune; + /** + * Client flag + */ + bool m_DamageImmune; - /** - * Client flag - */ - bool m_NoAggro; + /** + * Client flag + */ + bool m_NoAggro; - /** - * Client flag - */ - bool m_UseDB; + /** + * Client flag + */ + bool m_UseDB; - /** - * Client flag - */ - bool m_CameraLocked; + /** + * Client flag + */ + bool m_CameraLocked; - /** - * Client flag - */ - bool m_CollisionEnabled; + /** + * Client flag + */ + bool m_CollisionEnabled; - /** - * Client flag, notifies the server when the player finished the rail - */ - bool m_NotifyArrived; + /** + * Client flag, notifies the server when the player finished the rail + */ + bool m_NotifyArrived; - /** - * Client flag - */ - bool m_ShowNameBillboard; + /** + * Client flag + */ + bool m_ShowNameBillboard; }; diff --git a/dGame/dComponents/RebuildComponent.cpp b/dGame/dComponents/RebuildComponent.cpp index f2c2707f..6ec9b964 100644 --- a/dGame/dComponents/RebuildComponent.cpp +++ b/dGame/dComponents/RebuildComponent.cpp @@ -20,8 +20,7 @@ RebuildComponent::RebuildComponent(Entity* entity) : Component(entity) { std::u16string checkPreconditions = entity->GetVar(u"CheckPrecondition"); - if (!checkPreconditions.empty()) - { + if (!checkPreconditions.empty()) { m_Precondition = new PreconditionExpression(GeneralUtils::UTF16ToWTF8(checkPreconditions)); } @@ -81,8 +80,7 @@ void RebuildComponent::Serialize(RakNet::BitStream* outBitStream, bool bIsInitia for (int i = 0; i < 10; i++) { outBitStream->Write(0.0f); } - } - else { + } else { outBitStream->Write((uint32_t)0); } // END Scripted Activity @@ -154,20 +152,20 @@ void RebuildComponent::Update(float deltaTime) { // For reset times < 0 this has to be handled manually if (m_ResetTime > 0) { - if (m_Timer >= m_ResetTime - 4.0f) { - if (!m_ShowResetEffect) { - m_ShowResetEffect = true; + if (m_Timer >= m_ResetTime - 4.0f) { + if (!m_ShowResetEffect) { + m_ShowResetEffect = true; - EntityManager::Instance()->SerializeEntity(m_Parent); - } - } + EntityManager::Instance()->SerializeEntity(m_Parent); + } + } - if (m_Timer >= m_ResetTime) { + if (m_Timer >= m_ResetTime) { - GameMessages::SendDieNoImplCode(m_Parent, LWOOBJID_EMPTY, LWOOBJID_EMPTY, eKillType::VIOLENT, u"", 0.0f, 0.0f, 0.0f, false, true); + GameMessages::SendDieNoImplCode(m_Parent, LWOOBJID_EMPTY, LWOOBJID_EMPTY, eKillType::VIOLENT, u"", 0.0f, 0.0f, 0.0f, false, true); - ResetRebuild(false); - } + ResetRebuild(false); + } } break; } @@ -175,8 +173,7 @@ void RebuildComponent::Update(float deltaTime) { { Entity* builder = GetBuilder(); - if (builder == nullptr) - { + if (builder == nullptr) { ResetRebuild(false); return; @@ -218,19 +215,19 @@ void RebuildComponent::Update(float deltaTime) { // For reset times < 0 this has to be handled manually if (m_TimeBeforeSmash > 0) { - if (m_TimerIncomplete >= m_TimeBeforeSmash - 4.0f) { - m_ShowResetEffect = true; + if (m_TimerIncomplete >= m_TimeBeforeSmash - 4.0f) { + m_ShowResetEffect = true; - EntityManager::Instance()->SerializeEntity(m_Parent); - } + EntityManager::Instance()->SerializeEntity(m_Parent); + } - if (m_TimerIncomplete >= m_TimeBeforeSmash) { + if (m_TimerIncomplete >= m_TimeBeforeSmash) { m_Builder = LWOOBJID_EMPTY; - GameMessages::SendDieNoImplCode(m_Parent, LWOOBJID_EMPTY, LWOOBJID_EMPTY, eKillType::VIOLENT, u"", 0.0f, 0.0f, 0.0f, false, true); + GameMessages::SendDieNoImplCode(m_Parent, LWOOBJID_EMPTY, LWOOBJID_EMPTY, eKillType::VIOLENT, u"", 0.0f, 0.0f, 0.0f, false, true); - ResetRebuild(false); - } + ResetRebuild(false); + } } break; } @@ -281,8 +278,7 @@ void RebuildComponent::DespawnActivator() { } } -Entity* RebuildComponent::GetActivator() -{ +Entity* RebuildComponent::GetActivator() { return EntityManager::Instance()->GetEntity(m_ActivatorId); } @@ -345,14 +341,13 @@ void RebuildComponent::SetActivatorPosition(NiPoint3 value) { } void RebuildComponent::SetResetTime(float value) { - m_ResetTime = value; + m_ResetTime = value; } void RebuildComponent::SetCompleteTime(float value) { if (value < 0) { m_CompleteTime = 4.5f; - } - else { + } else { m_CompleteTime = value; } } @@ -384,8 +379,7 @@ void RebuildComponent::SetPostImaginationCost(int value) { void RebuildComponent::SetTimeBeforeSmash(float value) { if (value < 0) { m_TimeBeforeSmash = 10.0f; - } - else { + } else { m_TimeBeforeSmash = value; } } @@ -419,11 +413,11 @@ void RebuildComponent::StartRebuild(Entity* user) { script->OnRebuildStart(m_Parent, user); } - // Notify scripts and possible subscribers - for (auto* script : CppScripts::GetEntityScripts(m_Parent)) - script->OnRebuildNotifyState(m_Parent, m_State); - for (const auto& cb : m_RebuildStateCallbacks) - cb(m_State); + // Notify scripts and possible subscribers + for (auto* script : CppScripts::GetEntityScripts(m_Parent)) + script->OnRebuildNotifyState(m_Parent, m_State); + for (const auto& cb : m_RebuildStateCallbacks) + cb(m_State); } } @@ -435,7 +429,7 @@ void RebuildComponent::CompleteRebuild(Entity* user) { auto* characterComponent = user->GetComponent(); if (characterComponent != nullptr) { characterComponent->SetCurrentActivity(eGameActivities::ACTIVITY_NONE); - characterComponent->TrackRebuildComplete(); + characterComponent->TrackRebuildComplete(); } else { Game::logger->Log("RebuildComponent", "Some user tried to finish the rebuild but they didn't have a character somehow."); return; @@ -465,7 +459,7 @@ void RebuildComponent::CompleteRebuild(Entity* user) { DespawnActivator(); - // Set owner override so that entities smashed by this quickbuild will result in the builder getting rewards. + // Set owner override so that entities smashed by this quickbuild will result in the builder getting rewards. m_Parent->SetOwnerOverride(user->GetObjectID()); auto* builder = GetBuilder(); @@ -487,9 +481,9 @@ void RebuildComponent::CompleteRebuild(Entity* user) { // Notify subscribers for (const auto& callback : m_RebuildStateCallbacks) - callback(m_State); + callback(m_State); for (const auto& callback : m_RebuildCompleteCallbacks) - callback(user); + callback(user); auto* movingPlatform = m_Parent->GetComponent(); if (movingPlatform != nullptr) { @@ -535,12 +529,11 @@ void RebuildComponent::ResetRebuild(bool failed) { for (auto* script : CppScripts::GetEntityScripts(m_Parent)) script->OnRebuildNotifyState(m_Parent, m_State); for (const auto& cb : m_RebuildStateCallbacks) - cb(m_State); + cb(m_State); m_Parent->ScheduleKillAfterUpdate(); - if (m_Activator) - { + if (m_Activator) { m_Activator->ScheduleKillAfterUpdate(); } } @@ -564,11 +557,11 @@ void RebuildComponent::CancelRebuild(Entity* entity, eFailReason failReason, boo m_State = eRebuildState::REBUILD_INCOMPLETE; m_StateDirty = true; - // Notify scripts and possible subscribers - for (auto* script : CppScripts::GetEntityScripts(m_Parent)) - script->OnRebuildNotifyState(m_Parent, m_State); - for (const auto& cb : m_RebuildStateCallbacks) - cb(m_State); + // Notify scripts and possible subscribers + for (auto* script : CppScripts::GetEntityScripts(m_Parent)) + script->OnRebuildNotifyState(m_Parent, m_State); + for (const auto& cb : m_RebuildStateCallbacks) + cb(m_State); EntityManager::Instance()->SerializeEntity(m_Parent); } @@ -585,9 +578,9 @@ void RebuildComponent::CancelRebuild(Entity* entity, eFailReason failReason, boo } void RebuildComponent::AddRebuildCompleteCallback(const std::function& callback) { - m_RebuildCompleteCallbacks.push_back(callback); + m_RebuildCompleteCallbacks.push_back(callback); } void RebuildComponent::AddRebuildStateCallback(const std::function& callback) { - m_RebuildStateCallbacks.push_back(callback); + m_RebuildStateCallbacks.push_back(callback); } diff --git a/dGame/dComponents/RebuildComponent.h b/dGame/dComponents/RebuildComponent.h index 72c57bb0..bd3edd7d 100644 --- a/dGame/dComponents/RebuildComponent.h +++ b/dGame/dComponents/RebuildComponent.h @@ -20,342 +20,342 @@ class Entity; class RebuildComponent : public Component { public: static const uint32_t ComponentType = COMPONENT_TYPE_REBUILD; - + RebuildComponent(Entity* entity); ~RebuildComponent() override; void Serialize(RakNet::BitStream* outBitStream, bool bIsInitialUpdate, unsigned int& flags); void Update(float deltaTime) override; - /** - * Handles a OnUse event from some entity, initiating the quick build - * @param originator the entity that triggered the event - */ + /** + * Handles a OnUse event from some entity, initiating the quick build + * @param originator the entity that triggered the event + */ void OnUse(Entity* originator) override; - /** - * Spawns the activator that can be used to initiate the rebuild - */ + /** + * Spawns the activator that can be used to initiate the rebuild + */ void SpawnActivator(); - /** - * Despawns the activiator that can be used to initiate the rebuild - */ + /** + * Despawns the activiator that can be used to initiate the rebuild + */ void DespawnActivator(); - /** - * Returns the entity that acts as the activator for this rebuild - * @return the entity that acts as the activator for this rebuild - */ + /** + * Returns the entity that acts as the activator for this rebuild + * @return the entity that acts as the activator for this rebuild + */ Entity* GetActivator(); - /** - * Returns the spawn position of the activator for this rebuild, if any - * @return the spawn position of the activator for this rebuild, if any - */ + /** + * Returns the spawn position of the activator for this rebuild, if any + * @return the spawn position of the activator for this rebuild, if any + */ NiPoint3 GetActivatorPosition(); - /** - * Sets the spawn position for the activator of this rebuild - * @param value the spawn position to set for the activator - */ + /** + * Sets the spawn position for the activator of this rebuild + * @param value the spawn position to set for the activator + */ void SetActivatorPosition(NiPoint3 value); - /** - * Returns the time it takes for the rebuild to reset after being built - * @return the time it takes for the rebuild to reset after being built - */ + /** + * Returns the time it takes for the rebuild to reset after being built + * @return the time it takes for the rebuild to reset after being built + */ float GetResetTime(); - /** - * Sets the time it takes for the rebuild to reset after being built - * @param value the reset time to set - */ - void SetResetTime(float value); + /** + * Sets the time it takes for the rebuild to reset after being built + * @param value the reset time to set + */ + void SetResetTime(float value); - /** - * Returns the time it takes to complete the rebuild - * @return the time it takes to complete the rebuild - */ + /** + * Returns the time it takes to complete the rebuild + * @return the time it takes to complete the rebuild + */ float GetCompleteTime(); - /** - * Sets the time it takes to complete the rebuild - * @param value the completion time to set - */ - void SetCompleteTime(float value); + /** + * Sets the time it takes to complete the rebuild + * @param value the completion time to set + */ + void SetCompleteTime(float value); - /** - * Returns the imagination that's taken when completing the rebuild - * @return the imagination that's taken when completing the rebuild - */ + /** + * Returns the imagination that's taken when completing the rebuild + * @return the imagination that's taken when completing the rebuild + */ int GetTakeImagination(); - /** - * Sets the imagination that's taken when completing the rebuild - * @param value the imagination deduction to set - */ - void SetTakeImagination(int value); + /** + * Sets the imagination that's taken when completing the rebuild + * @param value the imagination deduction to set + */ + void SetTakeImagination(int value); - /** - * Returns if the rebuild can be interrupted, currently unused - * @return if the rebuild can be interrupted - */ + /** + * Returns if the rebuild can be interrupted, currently unused + * @return if the rebuild can be interrupted + */ bool GetInterruptible(); - /** - * Sets whether or not the rebuild can be interrupted, currently unused - * @param value true if the rebuild may be interrupted, false otherwise - */ - void SetInterruptible(bool value); + /** + * Sets whether or not the rebuild can be interrupted, currently unused + * @param value true if the rebuild may be interrupted, false otherwise + */ + void SetInterruptible(bool value); - /** - * Returns whether or not this entity contains a built-in activator - * @return whether or not this entity contains a built-in activator - */ + /** + * Returns whether or not this entity contains a built-in activator + * @return whether or not this entity contains a built-in activator + */ bool GetSelfActivator(); - /** - * Sets whether or not this entity contains a built-in activator. If set to false this will spawn activators on - * each new rebuild. - * @param value whether or not this entity contains a built-in activator - */ - void SetSelfActivator(bool value); + /** + * Sets whether or not this entity contains a built-in activator. If set to false this will spawn activators on + * each new rebuild. + * @param value whether or not this entity contains a built-in activator + */ + void SetSelfActivator(bool value); - /** - * Currently unused - */ + /** + * Currently unused + */ std::vector GetCustomModules(); - /** - * Currently unused - */ - void SetCustomModules(std::vector value); + /** + * Currently unused + */ + void SetCustomModules(std::vector value); - /** - * Returns the activity ID for participating in this rebuild - * @return the activity ID for participating in this rebuild - */ + /** + * Returns the activity ID for participating in this rebuild + * @return the activity ID for participating in this rebuild + */ int GetActivityId(); - /** - * Sets the activity ID for participating in this rebuild - * @param value the activity ID to set - */ - void SetActivityId(int value); + /** + * Sets the activity ID for participating in this rebuild + * @param value the activity ID to set + */ + void SetActivityId(int value); - /** - * Currently unused - */ + /** + * Currently unused + */ int GetPostImaginationCost(); - /** - * Currently unused - */ - void SetPostImaginationCost(int value); + /** + * Currently unused + */ + void SetPostImaginationCost(int value); - /** - * Returns the time it takes for an incomplete rebuild to be smashed automatically - * @return the time it takes for an incomplete rebuild to be smashed automatically - */ + /** + * Returns the time it takes for an incomplete rebuild to be smashed automatically + * @return the time it takes for an incomplete rebuild to be smashed automatically + */ float GetTimeBeforeSmash(); - /** - * Sets the time it takes for an incomplete rebuild to be smashed automatically - * @param value the time to set - */ - void SetTimeBeforeSmash(float value); + /** + * Sets the time it takes for an incomplete rebuild to be smashed automatically + * @param value the time to set + */ + void SetTimeBeforeSmash(float value); - /** - * Returns the current rebuild state - * @return the current rebuild state - */ + /** + * Returns the current rebuild state + * @return the current rebuild state + */ eRebuildState GetState(); - /** - * Returns the player that is currently building this rebuild - * @return the player that is currently building this rebuild - */ + /** + * Returns the player that is currently building this rebuild + * @return the player that is currently building this rebuild + */ Entity* GetBuilder() const; - /** - * Returns whether or not the player is repositioned when initiating the rebuild - * @return whether or not the player is repositioned when initiating the rebuild - */ + /** + * Returns whether or not the player is repositioned when initiating the rebuild + * @return whether or not the player is repositioned when initiating the rebuild + */ bool GetRepositionPlayer() const; - /** - * Sets whether or not the player is repositioned when initiating the rebuild - * @param value whether or not the player is repositioned when initiating the rebuild - */ + /** + * Sets whether or not the player is repositioned when initiating the rebuild + * @param value whether or not the player is repositioned when initiating the rebuild + */ void SetRepositionPlayer(bool value); - /** - * Adds a callback that is called when the rebuild is completed - * @param callback the callback to add - */ + /** + * Adds a callback that is called when the rebuild is completed + * @param callback the callback to add + */ void AddRebuildCompleteCallback(const std::function& callback); - /** - * Adds a callback when the rebuild state is updated - * @param callback the callback to add - */ + /** + * Adds a callback when the rebuild state is updated + * @param callback the callback to add + */ void AddRebuildStateCallback(const std::function& callback); - /** - * Resets the rebuild - * @param failed whether or not the player failed to complete the rebuild, triggers an extra animation - */ - void ResetRebuild(bool failed); + /** + * Resets the rebuild + * @param failed whether or not the player failed to complete the rebuild, triggers an extra animation + */ + void ResetRebuild(bool failed); - /** - * Cancels the rebuild if it wasn't completed - * @param builder the player that's currently building - * @param failReason the reason the rebuild was cancelled - * @param skipChecks whether or not to skip the check for the rebuild not being completed - */ + /** + * Cancels the rebuild if it wasn't completed + * @param builder the player that's currently building + * @param failReason the reason the rebuild was cancelled + * @param skipChecks whether or not to skip the check for the rebuild not being completed + */ void CancelRebuild(Entity* builder, eFailReason failReason, bool skipChecks = false); private: - /** - * Whether or not the quickbuild state has been changed since we last serialized it. - */ - bool m_StateDirty = true; - - /** - * The state the rebuild is currently in - */ + /** + * Whether or not the quickbuild state has been changed since we last serialized it. + */ + bool m_StateDirty = true; + + /** + * The state the rebuild is currently in + */ eRebuildState m_State = eRebuildState::REBUILD_OPEN; - /** - * The time that has passed since initiating the rebuild - */ + /** + * The time that has passed since initiating the rebuild + */ float m_Timer = 0; - /** - * The time that has passed before completing the rebuild - */ + /** + * The time that has passed before completing the rebuild + */ float m_TimerIncomplete = 0; - /** - * The position that the rebuild activator is spawned at - */ + /** + * The position that the rebuild activator is spawned at + */ NiPoint3 m_ActivatorPosition = NiPoint3::ZERO; - /** - * The entity that represents the rebuild activator - */ + /** + * The entity that represents the rebuild activator + */ Entity* m_Activator = nullptr; - /** - * The ID of the entity that represents the rebuild activator - */ + /** + * The ID of the entity that represents the rebuild activator + */ LWOOBJID m_ActivatorId = LWOOBJID_EMPTY; - /** - * Triggers the blinking that indicates that the rebuild is resetting - */ + /** + * Triggers the blinking that indicates that the rebuild is resetting + */ bool m_ShowResetEffect = false; - /** - * Currently unused - */ + /** + * Currently unused + */ float m_Taken = 0; - /** - * The callbacks that are called when the rebuild is completed - */ - std::vector> m_RebuildCompleteCallbacks {}; + /** + * The callbacks that are called when the rebuild is completed + */ + std::vector> m_RebuildCompleteCallbacks{}; - /** - * The callbacks that are called when the rebuild state is updated - */ - std::vector> m_RebuildStateCallbacks {}; + /** + * The callbacks that are called when the rebuild state is updated + */ + std::vector> m_RebuildStateCallbacks{}; - /** - * The time it takes for the rebuild to reset after being completed - */ + /** + * The time it takes for the rebuild to reset after being completed + */ float m_ResetTime = 0; - /** - * The time it takes to complete the rebuild - */ + /** + * The time it takes to complete the rebuild + */ float m_CompleteTime = 0; - /** - * The imagination that's deducted when compeleting the rebuild - */ + /** + * The imagination that's deducted when compeleting the rebuild + */ int m_TakeImagination = 0; - /** - * Currently unused - */ + /** + * Currently unused + */ bool m_Interruptible = false; - /** - * Whether or not this rebuild entity also has an activator attached. If not a new one will be spawned - */ + /** + * Whether or not this rebuild entity also has an activator attached. If not a new one will be spawned + */ bool m_SelfActivator = false; - /** - * Currently unused - */ - std::vector m_CustomModules {}; + /** + * Currently unused + */ + std::vector m_CustomModules{}; - /** - * The activity ID that players partake in when doing this rebuild - */ + /** + * The activity ID that players partake in when doing this rebuild + */ int m_ActivityId = 0; - /** - * Currently unused - */ + /** + * Currently unused + */ int m_PostImaginationCost = 0; - /** - * The time it takes for the rebuild to reset when it's not completed yet - */ + /** + * The time it takes for the rebuild to reset when it's not completed yet + */ float m_TimeBeforeSmash = 0; - /** - * The time it takes to drain imagination - */ + /** + * The time it takes to drain imagination + */ float m_TimeBeforeDrain = 0; - /** - * The amount of imagination that was drained when building this rebuild - */ + /** + * The amount of imagination that was drained when building this rebuild + */ int m_DrainedImagination = 0; - /** - * Whether to reposition the player or not when building - */ + /** + * Whether to reposition the player or not when building + */ bool m_RepositionPlayer = true; - /** - * Currently unused - */ + /** + * Currently unused + */ float m_SoftTimer = 0; - /** - * The ID of the entity that's currently building the rebuild - */ + /** + * The ID of the entity that's currently building the rebuild + */ LWOOBJID m_Builder = LWOOBJID_EMPTY; - /** - * Preconditions to be met before being able to start the rebuild - */ + /** + * Preconditions to be met before being able to start the rebuild + */ PreconditionExpression* m_Precondition = nullptr; - /** - * Starts the rebuild for a certain entity - * @param user the entity to start the rebuild - */ + /** + * Starts the rebuild for a certain entity + * @param user the entity to start the rebuild + */ void StartRebuild(Entity* user); - /** - * Completes the rebuild for an entity, dropping loot and despawning the activator - * @param user the entity that completed the rebuild - */ + /** + * Completes the rebuild for an entity, dropping loot and despawning the activator + * @param user the entity that completed the rebuild + */ void CompleteRebuild(Entity* user); }; diff --git a/dGame/dComponents/RenderComponent.cpp b/dGame/dComponents/RenderComponent.cpp index faec4ab6..3002ae33 100644 --- a/dGame/dComponents/RenderComponent.cpp +++ b/dGame/dComponents/RenderComponent.cpp @@ -12,226 +12,215 @@ #include "Game.h" #include "dLogger.h" -std::unordered_map RenderComponent::m_DurationCache {}; +std::unordered_map RenderComponent::m_DurationCache{}; RenderComponent::RenderComponent(Entity* parent) : Component(parent) { - m_Effects = std::vector(); + m_Effects = std::vector(); - return; + return; - /* - auto* table = CDClientManager::Instance()->GetTable("ComponentsRegistry"); + /* + auto* table = CDClientManager::Instance()->GetTable("ComponentsRegistry"); - const auto entry = table->GetByIDAndType(parent->GetLOT(), COMPONENT_TYPE_RENDER); + const auto entry = table->GetByIDAndType(parent->GetLOT(), COMPONENT_TYPE_RENDER); std::stringstream query; - query << "SELECT effect1, effect2, effect3, effect4, effect5, effect6 FROM RenderComponent WHERE id = " << std::to_string(entry) << ";"; + query << "SELECT effect1, effect2, effect3, effect4, effect5, effect6 FROM RenderComponent WHERE id = " << std::to_string(entry) << ";"; - auto result = CDClientDatabase::ExecuteQuery(query.str()); + auto result = CDClientDatabase::ExecuteQuery(query.str()); + + if (result.eof()) + { + return; + } - if (result.eof()) - { - return; - } - for (auto i = 0; i < 6; ++i) - { + { if (result.fieldIsNull(i)) { continue; } - - const auto id = result.getIntField(i); + + const auto id = result.getIntField(i); if (id <= 0) { continue; } - - query.clear(); - query << "SELECT effectType, effectName FROM BehaviorEffect WHERE effectID = " << std::to_string(id) << ";"; + query.clear(); - auto effectResult = CDClientDatabase::ExecuteQuery(query.str()); + query << "SELECT effectType, effectName FROM BehaviorEffect WHERE effectID = " << std::to_string(id) << ";"; - while (!effectResult.eof()) - { - const auto type = effectResult.fieldIsNull(0) ? "" : std::string(effectResult.getStringField(0)); - - const auto name = effectResult.fieldIsNull(1) ? "" : std::string(effectResult.getStringField(1)); + auto effectResult = CDClientDatabase::ExecuteQuery(query.str()); - auto* effect = new Effect(); + while (!effectResult.eof()) + { + const auto type = effectResult.fieldIsNull(0) ? "" : std::string(effectResult.getStringField(0)); - effect->name = name; - effect->type = GeneralUtils::ASCIIToUTF16(type); - effect->scale = 1; - effect->effectID = id; - effect->secondary = LWOOBJID_EMPTY; - - m_Effects.push_back(effect); - - effectResult.nextRow(); - } - } + const auto name = effectResult.fieldIsNull(1) ? "" : std::string(effectResult.getStringField(1)); + + auto* effect = new Effect(); + + effect->name = name; + effect->type = GeneralUtils::ASCIIToUTF16(type); + effect->scale = 1; + effect->effectID = id; + effect->secondary = LWOOBJID_EMPTY; + + m_Effects.push_back(effect); + + effectResult.nextRow(); + } + } result.finalize(); - */ + */ } RenderComponent::~RenderComponent() { - for (Effect* eff : m_Effects) { - if (eff) { - delete eff; - eff = nullptr; - } - } - - m_Effects.clear(); + for (Effect* eff : m_Effects) { + if (eff) { + delete eff; + eff = nullptr; + } + } + + m_Effects.clear(); } void RenderComponent::Serialize(RakNet::BitStream* outBitStream, bool bIsInitialUpdate, unsigned int& flags) { - if (!bIsInitialUpdate) return; - - outBitStream->Write(m_Effects.size()); - - for (Effect* eff : m_Effects) { - // Check that the effect is non-null - assert(eff); + if (!bIsInitialUpdate) return; - outBitStream->Write(eff->name.size()); - for (const auto& value : eff->name) - outBitStream->Write(value); + outBitStream->Write(m_Effects.size()); - outBitStream->Write(eff->effectID); + for (Effect* eff : m_Effects) { + // Check that the effect is non-null + assert(eff); - outBitStream->Write(eff->type.size()); - for (const auto& value : eff->type) - outBitStream->Write(value); + outBitStream->Write(eff->name.size()); + for (const auto& value : eff->name) + outBitStream->Write(value); - outBitStream->Write(eff->scale); - outBitStream->Write(eff->secondary); - } + outBitStream->Write(eff->effectID); + + outBitStream->Write(eff->type.size()); + for (const auto& value : eff->type) + outBitStream->Write(value); + + outBitStream->Write(eff->scale); + outBitStream->Write(eff->secondary); + } } Effect* RenderComponent::AddEffect(const int32_t effectId, const std::string& name, const std::u16string& type) { - auto* eff = new Effect(); - - eff->effectID = effectId; - - eff->name = name; - - eff->type = type; - - m_Effects.push_back(eff); + auto* eff = new Effect(); - return eff; + eff->effectID = effectId; + + eff->name = name; + + eff->type = type; + + m_Effects.push_back(eff); + + return eff; } void RenderComponent::RemoveEffect(const std::string& name) { - uint32_t index = -1; + uint32_t index = -1; - for (auto i = 0u; i < m_Effects.size(); ++i) - { - auto* eff = m_Effects[i]; + for (auto i = 0u; i < m_Effects.size(); ++i) { + auto* eff = m_Effects[i]; - if (eff->name == name) - { - index = i; + if (eff->name == name) { + index = i; - delete eff; + delete eff; - break; - } - } + break; + } + } - if (index == -1) - { + if (index == -1) { return; } - - m_Effects.erase(m_Effects.begin() + index);} -void RenderComponent::Update(const float deltaTime) -{ - std::vector dead; - - for (auto* effect : m_Effects) - { - if (effect->time == 0) - { - continue; // Skip persistent effects - } - - const auto result = effect->time - deltaTime; - - if (result <= 0) - { - dead.push_back(effect); - - continue; - } - - effect->time = result; - } - - for (auto* effect : dead) - { -// StopEffect(effect->name); - } + m_Effects.erase(m_Effects.begin() + index); } -void RenderComponent::PlayEffect(const int32_t effectId, const std::u16string& effectType, const std::string& name, const LWOOBJID secondary, const float priority, const float scale, const bool serialize) -{ - RemoveEffect(name); - - GameMessages::SendPlayFXEffect(m_Parent, effectId, effectType, name, secondary, priority, scale, serialize); +void RenderComponent::Update(const float deltaTime) { + std::vector dead; - auto* effect = AddEffect(effectId, name, effectType); + for (auto* effect : m_Effects) { + if (effect->time == 0) { + continue; // Skip persistent effects + } - const auto& pair = m_DurationCache.find(effectId); + const auto result = effect->time - deltaTime; - if (pair != m_DurationCache.end()) - { - effect->time = pair->second; + if (result <= 0) { + dead.push_back(effect); - return; - } + continue; + } - const std::string effectType_str = GeneralUtils::UTF16ToWTF8(effectType); + effect->time = result; + } - auto query = CDClientDatabase::CreatePreppedStmt( - "SELECT animation_length FROM Animations WHERE animation_type IN (SELECT animationName FROM BehaviorEffect WHERE effectID = ? AND effectType = ?);"); - query.bind(1, effectId); - query.bind(2, effectType_str.c_str()); + for (auto* effect : dead) { + // StopEffect(effect->name); + } +} - auto result = query.execQuery(); +void RenderComponent::PlayEffect(const int32_t effectId, const std::u16string& effectType, const std::string& name, const LWOOBJID secondary, const float priority, const float scale, const bool serialize) { + RemoveEffect(name); - if (result.eof() || result.fieldIsNull(0)) { - result.finalize(); + GameMessages::SendPlayFXEffect(m_Parent, effectId, effectType, name, secondary, priority, scale, serialize); - m_DurationCache[effectId] = 0; + auto* effect = AddEffect(effectId, name, effectType); - effect->time = 0; // Persistent effect - - return; - } + const auto& pair = m_DurationCache.find(effectId); + + if (pair != m_DurationCache.end()) { + effect->time = pair->second; + + return; + } + + const std::string effectType_str = GeneralUtils::UTF16ToWTF8(effectType); + + auto query = CDClientDatabase::CreatePreppedStmt( + "SELECT animation_length FROM Animations WHERE animation_type IN (SELECT animationName FROM BehaviorEffect WHERE effectID = ? AND effectType = ?);"); + query.bind(1, effectId); + query.bind(2, effectType_str.c_str()); + + auto result = query.execQuery(); + + if (result.eof() || result.fieldIsNull(0)) { + result.finalize(); + + m_DurationCache[effectId] = 0; + + effect->time = 0; // Persistent effect + + return; + } + + effect->time = static_cast(result.getFloatField(0)); - effect->time = static_cast(result.getFloatField(0)); - result.finalize(); - - m_DurationCache[effectId] = effect->time; + + m_DurationCache[effectId] = effect->time; } -void RenderComponent::StopEffect(const std::string& name, const bool killImmediate) -{ - GameMessages::SendStopFXEffect(m_Parent, killImmediate, name); +void RenderComponent::StopEffect(const std::string& name, const bool killImmediate) { + GameMessages::SendStopFXEffect(m_Parent, killImmediate, name); - RemoveEffect(name); + RemoveEffect(name); } -std::vector& RenderComponent::GetEffects() -{ - return m_Effects; +std::vector& RenderComponent::GetEffects() { + return m_Effects; } diff --git a/dGame/dComponents/RenderComponent.h b/dGame/dComponents/RenderComponent.h index 5107ae7b..e6184564 100644 --- a/dGame/dComponents/RenderComponent.h +++ b/dGame/dComponents/RenderComponent.h @@ -18,35 +18,35 @@ class Entity; struct Effect { Effect() { scale = 1.0f; } - /** - * The ID of the effect - */ - int32_t effectID = 0; + /** + * The ID of the effect + */ + int32_t effectID = 0; - /** - * The name of the effect - */ - std::string name = ""; + /** + * The name of the effect + */ + std::string name = ""; - /** - * The type of the effect - */ - std::u16string type = u""; + /** + * The type of the effect + */ + std::u16string type = u""; - /** - * How scaled (enlarged) the effect is - */ - float scale = 1.0f; + /** + * How scaled (enlarged) the effect is + */ + float scale = 1.0f; - /** - * Some related entity that casted the effect - */ - uint64_t secondary = 0; + /** + * Some related entity that casted the effect + */ + uint64_t secondary = 0; - /** - * The time that this effect plays for - */ - float time = 0; + /** + * The time that this effect plays for + */ + float time = 0; }; /** @@ -55,65 +55,65 @@ struct Effect { */ class RenderComponent : public Component { public: - static const uint32_t ComponentType = COMPONENT_TYPE_RENDER; - - RenderComponent(Entity* entity); - ~RenderComponent() override; - - void Serialize(RakNet::BitStream* outBitStream, bool bIsInitialUpdate, unsigned int& flags); - void Update(float deltaTime) override; + static const uint32_t ComponentType = COMPONENT_TYPE_RENDER; - /** - * Adds an effect to this entity, if successful the effect is returned - * @param effectId the ID of the effect - * @param name the name of the effect - * @param type the type of the effect - * @return if successful, the effect that was created - */ - Effect* AddEffect(int32_t effectId, const std::string& name, const std::u16string& type); + RenderComponent(Entity* entity); + ~RenderComponent() override; - /** - * Removes an effect for this entity - * @param name the name of the effect to remove - */ - void RemoveEffect(const std::string& name); + void Serialize(RakNet::BitStream* outBitStream, bool bIsInitialUpdate, unsigned int& flags); + void Update(float deltaTime) override; - /** - * Plays an effect, removes any effects under this name and plays the one according to these params - * @param effectId the ID of the effect - * @param effectType the type of the effect - * @param name the name of the effect - * @param secondary some entity that cast the effect - * @param priority effect priority (determines if the client will play it over other effects) - * @param scale effect scale - * @param serialize whether to serialize the change or not - */ - void PlayEffect(int32_t effectId, const std::u16string& effectType, const std::string& name, LWOOBJID secondary = LWOOBJID_EMPTY, float priority = 1, float scale = 1, bool serialize = true); + /** + * Adds an effect to this entity, if successful the effect is returned + * @param effectId the ID of the effect + * @param name the name of the effect + * @param type the type of the effect + * @return if successful, the effect that was created + */ + Effect* AddEffect(int32_t effectId, const std::string& name, const std::u16string& type); - /** - * Removes and stops the effect for a certain name - * @param name name of the effect to stop - * @param killImmediate whether ot not to immediately stop playing the effect or phase it out - */ - void StopEffect(const std::string& name, bool killImmediate = true); + /** + * Removes an effect for this entity + * @param name the name of the effect to remove + */ + void RemoveEffect(const std::string& name); + + /** + * Plays an effect, removes any effects under this name and plays the one according to these params + * @param effectId the ID of the effect + * @param effectType the type of the effect + * @param name the name of the effect + * @param secondary some entity that cast the effect + * @param priority effect priority (determines if the client will play it over other effects) + * @param scale effect scale + * @param serialize whether to serialize the change or not + */ + void PlayEffect(int32_t effectId, const std::u16string& effectType, const std::string& name, LWOOBJID secondary = LWOOBJID_EMPTY, float priority = 1, float scale = 1, bool serialize = true); + + /** + * Removes and stops the effect for a certain name + * @param name name of the effect to stop + * @param killImmediate whether ot not to immediately stop playing the effect or phase it out + */ + void StopEffect(const std::string& name, bool killImmediate = true); + + /** + * Returns the list of currently active effects + * @return + */ + std::vector& GetEffects(); - /** - * Returns the list of currently active effects - * @return - */ - std::vector& GetEffects(); - private: - /** - * List of currently active effects - */ - std::vector m_Effects; + /** + * List of currently active effects + */ + std::vector m_Effects; - /** - * Cache of queries that look for the length of each effect, indexed by effect ID - */ - static std::unordered_map m_DurationCache; + /** + * Cache of queries that look for the length of each effect, indexed by effect ID + */ + static std::unordered_map m_DurationCache; }; #endif // RENDERCOMPONENT_H diff --git a/dGame/dComponents/RigidbodyPhantomPhysicsComponent.cpp b/dGame/dComponents/RigidbodyPhantomPhysicsComponent.cpp index 7a656d31..babd1974 100644 --- a/dGame/dComponents/RigidbodyPhantomPhysicsComponent.cpp +++ b/dGame/dComponents/RigidbodyPhantomPhysicsComponent.cpp @@ -7,27 +7,26 @@ #include "Entity.h" RigidbodyPhantomPhysicsComponent::RigidbodyPhantomPhysicsComponent(Entity* parent) : Component(parent) { - m_Position = m_Parent->GetDefaultPosition(); - m_Rotation = m_Parent->GetDefaultRotation(); - m_IsDirty = true; + m_Position = m_Parent->GetDefaultPosition(); + m_Rotation = m_Parent->GetDefaultRotation(); + m_IsDirty = true; } RigidbodyPhantomPhysicsComponent::~RigidbodyPhantomPhysicsComponent() { } void RigidbodyPhantomPhysicsComponent::Serialize(RakNet::BitStream* outBitStream, bool bIsInitialUpdate, unsigned int& flags) { - outBitStream->Write(m_IsDirty || bIsInitialUpdate); - if (m_IsDirty || bIsInitialUpdate) - { - outBitStream->Write(m_Position.x); - outBitStream->Write(m_Position.y); - outBitStream->Write(m_Position.z); - - outBitStream->Write(m_Rotation.x); - outBitStream->Write(m_Rotation.y); - outBitStream->Write(m_Rotation.z); - outBitStream->Write(m_Rotation.w); + outBitStream->Write(m_IsDirty || bIsInitialUpdate); + if (m_IsDirty || bIsInitialUpdate) { + outBitStream->Write(m_Position.x); + outBitStream->Write(m_Position.y); + outBitStream->Write(m_Position.z); - m_IsDirty = false; - } + outBitStream->Write(m_Rotation.x); + outBitStream->Write(m_Rotation.y); + outBitStream->Write(m_Rotation.z); + outBitStream->Write(m_Rotation.w); + + m_IsDirty = false; + } } diff --git a/dGame/dComponents/RigidbodyPhantomPhysicsComponent.h b/dGame/dComponents/RigidbodyPhantomPhysicsComponent.h index e3ef45c2..c8faa930 100644 --- a/dGame/dComponents/RigidbodyPhantomPhysicsComponent.h +++ b/dGame/dComponents/RigidbodyPhantomPhysicsComponent.h @@ -12,59 +12,59 @@ #include "NiQuaternion.h" #include "Component.h" -/** - * Component that handles rigid bodies that can be interacted with, mostly client-side rendered. An example is the - * bananas that fall from trees in GF. - */ + /** + * Component that handles rigid bodies that can be interacted with, mostly client-side rendered. An example is the + * bananas that fall from trees in GF. + */ class RigidbodyPhantomPhysicsComponent : public Component { public: - static const uint32_t ComponentType = COMPONENT_TYPE_PHANTOM_PHYSICS; - - RigidbodyPhantomPhysicsComponent(Entity* parent); - ~RigidbodyPhantomPhysicsComponent() override; - - void Serialize(RakNet::BitStream* outBitStream, bool bIsInitialUpdate, unsigned int& flags); + static const uint32_t ComponentType = COMPONENT_TYPE_PHANTOM_PHYSICS; - /** - * Returns the position of this entity - * @return the position of this entity - */ - NiPoint3& GetPosition() { return m_Position; } + RigidbodyPhantomPhysicsComponent(Entity* parent); + ~RigidbodyPhantomPhysicsComponent() override; - /** - * Sets the position of this entity - * @param pos the position to set - */ - void SetPosition(const NiPoint3& pos) { m_Position = pos; m_IsDirty = true; } + void Serialize(RakNet::BitStream* outBitStream, bool bIsInitialUpdate, unsigned int& flags); - /** - * Returns the rotation of this entity - * @return the rotation of this entity - */ - NiQuaternion& GetRotation() { return m_Rotation; } + /** + * Returns the position of this entity + * @return the position of this entity + */ + NiPoint3& GetPosition() { return m_Position; } - /** - * Sets the rotation for this entity - * @param rot the rotation to tset - */ - void SetRotation(const NiQuaternion& rot) { m_Rotation = rot; m_IsDirty = true; } + /** + * Sets the position of this entity + * @param pos the position to set + */ + void SetPosition(const NiPoint3& pos) { m_Position = pos; m_IsDirty = true; } + + /** + * Returns the rotation of this entity + * @return the rotation of this entity + */ + NiQuaternion& GetRotation() { return m_Rotation; } + + /** + * Sets the rotation for this entity + * @param rot the rotation to tset + */ + void SetRotation(const NiQuaternion& rot) { m_Rotation = rot; m_IsDirty = true; } private: - /** - * The position of this entity - */ - NiPoint3 m_Position; + /** + * The position of this entity + */ + NiPoint3 m_Position; - /** - * The rotation of this entity - */ - NiQuaternion m_Rotation; + /** + * The rotation of this entity + */ + NiQuaternion m_Rotation; - /** - * Whether or not the component should be serialized - */ - bool m_IsDirty; + /** + * Whether or not the component should be serialized + */ + bool m_IsDirty; }; #endif // RIGIDBODYPHANTOMPHYSICS_H diff --git a/dGame/dComponents/RocketLaunchLupComponent.h b/dGame/dComponents/RocketLaunchLupComponent.h index ce915d70..3fc0b444 100644 --- a/dGame/dComponents/RocketLaunchLupComponent.h +++ b/dGame/dComponents/RocketLaunchLupComponent.h @@ -35,5 +35,5 @@ private: /** * vector of the LUP World Zone IDs, built from CDServer's LUPZoneIDs table */ - std::vector m_LUPWorlds {}; + std::vector m_LUPWorlds{}; }; diff --git a/dGame/dComponents/RocketLaunchpadControlComponent.cpp b/dGame/dComponents/RocketLaunchpadControlComponent.cpp index 108335ae..4f248a40 100644 --- a/dGame/dComponents/RocketLaunchpadControlComponent.cpp +++ b/dGame/dComponents/RocketLaunchpadControlComponent.cpp @@ -25,8 +25,7 @@ RocketLaunchpadControlComponent::RocketLaunchpadControlComponent(Entity* parent, auto result = query.execQuery(); - if (!result.eof() && !result.fieldIsNull(0)) - { + if (!result.eof() && !result.fieldIsNull(0)) { m_TargetZone = result.getIntField(0); m_DefaultZone = result.getIntField(1); m_TargetScene = result.getStringField(2); @@ -44,8 +43,7 @@ RocketLaunchpadControlComponent::~RocketLaunchpadControlComponent() { void RocketLaunchpadControlComponent::Launch(Entity* originator, LWOMAPID mapId, LWOCLONEID cloneId) { auto zone = mapId == LWOMAPID_INVALID ? m_TargetZone : mapId; - if (zone == 0) - { + if (zone == 0) { return; } @@ -67,8 +65,7 @@ void RocketLaunchpadControlComponent::Launch(Entity* originator, LWOMAPID mapId, // Achievement unlocked: "All zones unlocked" if (!m_AltLandingScene.empty() && m_AltPrecondition->Check(originator)) { character->SetTargetScene(m_AltLandingScene); - } - else { + } else { character->SetTargetScene(m_TargetScene); } @@ -112,13 +109,11 @@ void RocketLaunchpadControlComponent::OnProximityUpdate(Entity* entering, std::s // Proximity rockets are handled by item equipment } -void RocketLaunchpadControlComponent::SetSelectedMapId(LWOOBJID player, LWOMAPID mapID) -{ +void RocketLaunchpadControlComponent::SetSelectedMapId(LWOOBJID player, LWOMAPID mapID) { m_SelectedMapIds[player] = mapID; } -LWOMAPID RocketLaunchpadControlComponent::GetSelectedMapId(LWOOBJID player) const -{ +LWOMAPID RocketLaunchpadControlComponent::GetSelectedMapId(LWOOBJID player) const { const auto index = m_SelectedMapIds.find(player); if (index == m_SelectedMapIds.end()) return 0; @@ -126,13 +121,11 @@ LWOMAPID RocketLaunchpadControlComponent::GetSelectedMapId(LWOOBJID player) cons return index->second; } -void RocketLaunchpadControlComponent::SetSelectedCloneId(LWOOBJID player, LWOCLONEID cloneId) -{ +void RocketLaunchpadControlComponent::SetSelectedCloneId(LWOOBJID player, LWOCLONEID cloneId) { m_SelectedCloneIds[player] = cloneId; } -LWOCLONEID RocketLaunchpadControlComponent::GetSelectedCloneId(LWOOBJID player) const -{ +LWOCLONEID RocketLaunchpadControlComponent::GetSelectedCloneId(LWOOBJID player) const { const auto index = m_SelectedCloneIds.find(player); if (index == m_SelectedCloneIds.end()) return 0; @@ -148,12 +141,10 @@ void RocketLaunchpadControlComponent::TellMasterToPrepZone(int zoneID) { } -LWOMAPID RocketLaunchpadControlComponent::GetTargetZone() const -{ +LWOMAPID RocketLaunchpadControlComponent::GetTargetZone() const { return m_TargetZone; } -LWOMAPID RocketLaunchpadControlComponent::GetDefaultZone() const -{ +LWOMAPID RocketLaunchpadControlComponent::GetDefaultZone() const { return m_DefaultZone; } diff --git a/dGame/dComponents/RocketLaunchpadControlComponent.h b/dGame/dComponents/RocketLaunchpadControlComponent.h index 7fdf4b32..8a10f0f7 100644 --- a/dGame/dComponents/RocketLaunchpadControlComponent.h +++ b/dGame/dComponents/RocketLaunchpadControlComponent.h @@ -18,114 +18,114 @@ class PreconditionExpression; class RocketLaunchpadControlComponent : public Component { public: static const uint32_t ComponentType = COMPONENT_TYPE_ROCKET_LAUNCH; - + RocketLaunchpadControlComponent(Entity* parent, int rocketId); ~RocketLaunchpadControlComponent() override; - /** - * Launches some entity to another world - * @param originator the entity to launch - * @param mapId the world to go to - * @param cloneId the clone ID (for properties) - */ + /** + * Launches some entity to another world + * @param originator the entity to launch + * @param mapId the world to go to + * @param cloneId the clone ID (for properties) + */ void Launch(Entity* originator, LWOMAPID mapId = LWOMAPID_INVALID, LWOCLONEID cloneId = LWOCLONEID_INVALID); - /** - * Handles an OnUse event from some entity, preparing it for launch to some other world - * @param originator the entity that triggered the event - */ + /** + * Handles an OnUse event from some entity, preparing it for launch to some other world + * @param originator the entity that triggered the event + */ void OnUse(Entity* originator) override; - /** - * Currently unused - */ + /** + * Currently unused + */ void OnProximityUpdate(Entity* entering, std::string name, std::string status); - /** - * Sets the map ID that a player will go to - * @param player the entity to set the map ID for - * @param cloneId the map ID of the property to set - */ + /** + * Sets the map ID that a player will go to + * @param player the entity to set the map ID for + * @param cloneId the map ID of the property to set + */ void SetSelectedMapId(LWOOBJID player, LWOMAPID cloneId); - /** - * Returns the map ID that a player will go to - * @param player the player to find the map ID for - * @return the map ID that a player will go to - */ + /** + * Returns the map ID that a player will go to + * @param player the player to find the map ID for + * @return the map ID that a player will go to + */ LWOMAPID GetSelectedMapId(LWOOBJID player) const; - /** - * Sets the clone ID that a player will go to (for properties) - * @param player the entity to set the clone ID for - * @param cloneId the clone ID of the property to set - */ + /** + * Sets the clone ID that a player will go to (for properties) + * @param player the entity to set the clone ID for + * @param cloneId the clone ID of the property to set + */ void SetSelectedCloneId(LWOOBJID player, LWOCLONEID cloneId); - /** - * Returns the clone ID that a player will go to (for properties) - * @param player the player to find the clone ID for - * @return the clone ID that a player will go to - */ + /** + * Returns the clone ID that a player will go to (for properties) + * @param player the player to find the clone ID for + * @return the clone ID that a player will go to + */ LWOCLONEID GetSelectedCloneId(LWOOBJID player) const; - /** - * Returns the zone that this rocket launchpad points to by default - * @return the zone that this rocket launchpad points to by default - */ + /** + * Returns the zone that this rocket launchpad points to by default + * @return the zone that this rocket launchpad points to by default + */ LWOMAPID GetTargetZone() const; - /** - * Currently unused - */ + /** + * Currently unused + */ LWOMAPID GetDefaultZone() const; private: - /** - * All the players that are in the proximity of the rocket launchpad - */ + /** + * All the players that are in the proximity of the rocket launchpad + */ std::map m_PlayersInRadius = {}; - /** - * The map that the launchpad goes to - */ + /** + * The map that the launchpad goes to + */ LWOMAPID m_TargetZone; - /** - * Currently unused - */ + /** + * Currently unused + */ LWOMAPID m_DefaultZone; - /** - * The clone IDs selected for each player to go to (for properies) - */ + /** + * The clone IDs selected for each player to go to (for properies) + */ std::map m_SelectedCloneIds = {}; - /** - * The map IDs selected for each player to go to - */ + /** + * The map IDs selected for each player to go to + */ std::map m_SelectedMapIds = {}; - /** - * The scene that plays when the player lands - */ + /** + * The scene that plays when the player lands + */ std::string m_TargetScene; - /** - * Alternative landing scene that plays if the alternative precondition is met - */ + /** + * Alternative landing scene that plays if the alternative precondition is met + */ std::string m_AltLandingScene; - /** - * Some precondition that needs to be met to trigger the alternative landing scene - */ + /** + * Some precondition that needs to be met to trigger the alternative landing scene + */ PreconditionExpression* m_AltPrecondition; - /** - * Notifies the master server to prepare some world for a player to be able to travel to it - * @param zoneID the ID of the zone to prepare - */ + /** + * Notifies the master server to prepare some world for a player to be able to travel to it + * @param zoneID the ID of the zone to prepare + */ void TellMasterToPrepZone(int zoneID); }; diff --git a/dGame/dComponents/ScriptedActivityComponent.cpp b/dGame/dComponents/ScriptedActivityComponent.cpp index edc6b70d..4b5ec41d 100644 --- a/dGame/dComponents/ScriptedActivityComponent.cpp +++ b/dGame/dComponents/ScriptedActivityComponent.cpp @@ -18,29 +18,28 @@ #include "dConfig.h" #include "DestroyableComponent.h" -ScriptedActivityComponent::ScriptedActivityComponent(Entity* parent, int activityID) : Component(parent) -{ +ScriptedActivityComponent::ScriptedActivityComponent(Entity* parent, int activityID) : Component(parent) { CDActivitiesTable* activitiesTable = CDClientManager::Instance()->GetTable("Activities"); std::vector activities = activitiesTable->Query([=](CDActivities entry) {return (entry.ActivityID == activityID); }); for (CDActivities activity : activities) { m_ActivityInfo = activity; - const auto mapID = m_ActivityInfo.instanceMapID; + const auto mapID = m_ActivityInfo.instanceMapID; - if ((mapID == 1203 || mapID == 1261 || mapID == 1303 || mapID == 1403) && Game::config->GetValue("solo_racing") == "1") { - m_ActivityInfo.minTeamSize = 1; - m_ActivityInfo.minTeams = 1; - } + if ((mapID == 1203 || mapID == 1261 || mapID == 1303 || mapID == 1403) && Game::config->GetValue("solo_racing") == "1") { + m_ActivityInfo.minTeamSize = 1; + m_ActivityInfo.minTeams = 1; + } - const auto& transferOverride = parent->GetVar(u"transferZoneID"); - if (!transferOverride.empty()) { - m_ActivityInfo.instanceMapID = std::stoi(GeneralUtils::UTF16ToWTF8(transferOverride)); + const auto& transferOverride = parent->GetVar(u"transferZoneID"); + if (!transferOverride.empty()) { + m_ActivityInfo.instanceMapID = std::stoi(GeneralUtils::UTF16ToWTF8(transferOverride)); // TODO: LU devs made me do it (for some reason cannon cove instancer is marked to go to GF survival) // NOTE: 1301 is GF survival if (m_ActivityInfo.instanceMapID == 1301) { - m_ActivityInfo.instanceMapID = 1302; + m_ActivityInfo.instanceMapID = 1302; } } } @@ -75,30 +74,30 @@ ScriptedActivityComponent::~ScriptedActivityComponent() = default; void ScriptedActivityComponent::Serialize(RakNet::BitStream* outBitStream, bool bIsInitialUpdate, unsigned int& flags) const { - outBitStream->Write(true); - outBitStream->Write(m_ActivityPlayers.size()); + outBitStream->Write(true); + outBitStream->Write(m_ActivityPlayers.size()); - if (!m_ActivityPlayers.empty()) { - for (const auto& activityPlayer : m_ActivityPlayers) { + if (!m_ActivityPlayers.empty()) { + for (const auto& activityPlayer : m_ActivityPlayers) { - outBitStream->Write(activityPlayer->playerID); - for (const auto& activityValue : activityPlayer->values) { - outBitStream->Write(activityValue); - } - } - } + outBitStream->Write(activityPlayer->playerID); + for (const auto& activityValue : activityPlayer->values) { + outBitStream->Write(activityValue); + } + } + } } void ScriptedActivityComponent::HandleMessageBoxResponse(Entity* player, const std::string& id) { - if (m_ActivityInfo.ActivityID == 103) { - return; - } + if (m_ActivityInfo.ActivityID == 103) { + return; + } - if (id == "LobbyExit") { - PlayerLeave(player->GetObjectID()); - } else if (id == "PlayButton") { - PlayerJoin(player); - } + if (id == "LobbyExit") { + PlayerLeave(player->GetObjectID()); + } else if (id == "PlayButton") { + PlayerJoin(player); + } } void ScriptedActivityComponent::PlayerJoin(Entity* player) { @@ -108,10 +107,10 @@ void ScriptedActivityComponent::PlayerJoin(Entity* player) { // If we have a lobby, queue the player and allow others to join, otherwise spin up an instance on the spot if (HasLobby()) { - PlayerJoinLobby(player); + PlayerJoinLobby(player); } else if (!IsPlayedBy(player)) { - auto* instance = NewInstance(); - instance->AddParticipant(player); + auto* instance = NewInstance(); + instance->AddParticipant(player); } EntityManager::Instance()->SerializeEntity(m_Parent); @@ -119,57 +118,56 @@ void ScriptedActivityComponent::PlayerJoin(Entity* player) { void ScriptedActivityComponent::PlayerJoinLobby(Entity* player) { if (!m_Parent->HasComponent(COMPONENT_TYPE_REBUILD)) - GameMessages::SendMatchResponse(player, player->GetSystemAddress(), 0); // tell the client they joined a lobby - LobbyPlayer* newLobbyPlayer = new LobbyPlayer(); - newLobbyPlayer->entityID = player->GetObjectID(); - Lobby* playerLobby = nullptr; + GameMessages::SendMatchResponse(player, player->GetSystemAddress(), 0); // tell the client they joined a lobby + LobbyPlayer* newLobbyPlayer = new LobbyPlayer(); + newLobbyPlayer->entityID = player->GetObjectID(); + Lobby* playerLobby = nullptr; - auto* character = player->GetCharacter(); - if (character != nullptr) - character->SetLastNonInstanceZoneID(dZoneManager::Instance()->GetZone()->GetWorldID()); + auto* character = player->GetCharacter(); + if (character != nullptr) + character->SetLastNonInstanceZoneID(dZoneManager::Instance()->GetZone()->GetWorldID()); - for (Lobby* lobby : m_Queue) { - if (lobby->players.size() < m_ActivityInfo.maxTeamSize || m_ActivityInfo.maxTeamSize == 1 && lobby->players.size() < m_ActivityInfo.maxTeams) { - // If an empty slot in an existing lobby is found - lobby->players.push_back(newLobbyPlayer); - playerLobby = lobby; + for (Lobby* lobby : m_Queue) { + if (lobby->players.size() < m_ActivityInfo.maxTeamSize || m_ActivityInfo.maxTeamSize == 1 && lobby->players.size() < m_ActivityInfo.maxTeams) { + // If an empty slot in an existing lobby is found + lobby->players.push_back(newLobbyPlayer); + playerLobby = lobby; - // Update the joining player on players already in the lobby, and update players already in the lobby on the joining player - std::string matchUpdateJoined = "player=9:" + std::to_string(player->GetObjectID()) + "\nplayerName=0:" + player->GetCharacter()->GetName(); - for (LobbyPlayer* joinedPlayer : lobby->players) { - auto* entity = joinedPlayer->GetEntity(); + // Update the joining player on players already in the lobby, and update players already in the lobby on the joining player + std::string matchUpdateJoined = "player=9:" + std::to_string(player->GetObjectID()) + "\nplayerName=0:" + player->GetCharacter()->GetName(); + for (LobbyPlayer* joinedPlayer : lobby->players) { + auto* entity = joinedPlayer->GetEntity(); - if (entity == nullptr) - { - continue; - } + if (entity == nullptr) { + continue; + } - std::string matchUpdate = "player=9:" + std::to_string(entity->GetObjectID()) + "\nplayerName=0:" + entity->GetCharacter()->GetName(); - GameMessages::SendMatchUpdate(player, player->GetSystemAddress(), matchUpdate, eMatchUpdate::MATCH_UPDATE_PLAYER_JOINED); - PlayerReady(entity, joinedPlayer->ready); - GameMessages::SendMatchUpdate(entity, entity->GetSystemAddress(), matchUpdateJoined, eMatchUpdate::MATCH_UPDATE_PLAYER_JOINED); - } - } - } + std::string matchUpdate = "player=9:" + std::to_string(entity->GetObjectID()) + "\nplayerName=0:" + entity->GetCharacter()->GetName(); + GameMessages::SendMatchUpdate(player, player->GetSystemAddress(), matchUpdate, eMatchUpdate::MATCH_UPDATE_PLAYER_JOINED); + PlayerReady(entity, joinedPlayer->ready); + GameMessages::SendMatchUpdate(entity, entity->GetSystemAddress(), matchUpdateJoined, eMatchUpdate::MATCH_UPDATE_PLAYER_JOINED); + } + } + } - if (!playerLobby) { - // If all lobbies are full - playerLobby = new Lobby(); - playerLobby->players.push_back(newLobbyPlayer); - playerLobby->timer = m_ActivityInfo.waitTime / 1000; - m_Queue.push_back(playerLobby); - } + if (!playerLobby) { + // If all lobbies are full + playerLobby = new Lobby(); + playerLobby->players.push_back(newLobbyPlayer); + playerLobby->timer = m_ActivityInfo.waitTime / 1000; + m_Queue.push_back(playerLobby); + } - if (m_ActivityInfo.maxTeamSize != 1 && playerLobby->players.size() >= m_ActivityInfo.minTeamSize || m_ActivityInfo.maxTeamSize == 1 && playerLobby->players.size() >= m_ActivityInfo.minTeams) { - // Update the joining player on the match timer - std::string matchTimerUpdate = "time=3:" + std::to_string(playerLobby->timer); - GameMessages::SendMatchUpdate(player, player->GetSystemAddress(), matchTimerUpdate, eMatchUpdate::MATCH_UPDATE_TIME); - } + if (m_ActivityInfo.maxTeamSize != 1 && playerLobby->players.size() >= m_ActivityInfo.minTeamSize || m_ActivityInfo.maxTeamSize == 1 && playerLobby->players.size() >= m_ActivityInfo.minTeams) { + // Update the joining player on the match timer + std::string matchTimerUpdate = "time=3:" + std::to_string(playerLobby->timer); + GameMessages::SendMatchUpdate(player, player->GetSystemAddress(), matchTimerUpdate, eMatchUpdate::MATCH_UPDATE_TIME); + } } void ScriptedActivityComponent::PlayerLeave(LWOOBJID playerID) { - // Removes the player from a lobby and notifies the others, not applicable for non-lobby instances + // Removes the player from a lobby and notifies the others, not applicable for non-lobby instances for (Lobby* lobby : m_Queue) { for (int i = 0; i < lobby->players.size(); ++i) { if (lobby->players[i]->entityID == playerID) { @@ -194,7 +192,7 @@ void ScriptedActivityComponent::PlayerLeave(LWOOBJID playerID) { void ScriptedActivityComponent::Update(float deltaTime) { - // Ticks all the lobbies, not applicable for non-instance activities + // Ticks all the lobbies, not applicable for non-instance activities for (Lobby* lobby : m_Queue) { for (LobbyPlayer* player : lobby->players) { auto* entity = player->GetEntity(); @@ -206,7 +204,7 @@ void ScriptedActivityComponent::Update(float deltaTime) { // Update the match time for all players if (m_ActivityInfo.maxTeamSize != 1 && lobby->players.size() >= m_ActivityInfo.minTeamSize - || m_ActivityInfo.maxTeamSize == 1 && lobby->players.size() >= m_ActivityInfo.minTeams) { + || m_ActivityInfo.maxTeamSize == 1 && lobby->players.size() >= m_ActivityInfo.minTeams) { if (lobby->timer == m_ActivityInfo.waitTime / 1000) { for (LobbyPlayer* joinedPlayer : lobby->players) { auto* entity = joinedPlayer->GetEntity(); @@ -266,25 +264,25 @@ void ScriptedActivityComponent::RemoveLobby(Lobby* lobby) { } bool ScriptedActivityComponent::HasLobby() const { - // If the player is not in the world he has to be, create a lobby for the transfer - return m_ActivityInfo.instanceMapID != UINT_MAX && m_ActivityInfo.instanceMapID != Game::server->GetZoneID(); + // If the player is not in the world he has to be, create a lobby for the transfer + return m_ActivityInfo.instanceMapID != UINT_MAX && m_ActivityInfo.instanceMapID != Game::server->GetZoneID(); } bool ScriptedActivityComponent::IsValidActivity(Entity* player) { - // Makes it so that scripted activities with an unimplemented map cannot be joined - /*if (player->GetGMLevel() < GAME_MASTER_LEVEL_DEVELOPER && (m_ActivityInfo.instanceMapID == 1302 || m_ActivityInfo.instanceMapID == 1301)) { - if (m_Parent->GetLOT() == 4860) { - auto* missionComponent = player->GetComponent(); - missionComponent->CompleteMission(229); - } + // Makes it so that scripted activities with an unimplemented map cannot be joined + /*if (player->GetGMLevel() < GAME_MASTER_LEVEL_DEVELOPER && (m_ActivityInfo.instanceMapID == 1302 || m_ActivityInfo.instanceMapID == 1301)) { + if (m_Parent->GetLOT() == 4860) { + auto* missionComponent = player->GetComponent(); + missionComponent->CompleteMission(229); + } - ChatPackets::SendSystemMessage(player->GetSystemAddress(), u"Sorry, this activity is not ready."); - static_cast(player)->SendToZone(dZoneManager::Instance()->GetZone()->GetWorldID()); // Gets them out of this stuck state + ChatPackets::SendSystemMessage(player->GetSystemAddress(), u"Sorry, this activity is not ready."); + static_cast(player)->SendToZone(dZoneManager::Instance()->GetZone()->GetWorldID()); // Gets them out of this stuck state - return false; - }*/ + return false; + }*/ - return true; + return true; } bool ScriptedActivityComponent::PlayerIsInQueue(Entity* player) { @@ -298,25 +296,25 @@ bool ScriptedActivityComponent::PlayerIsInQueue(Entity* player) { } bool ScriptedActivityComponent::IsPlayedBy(Entity* player) const { - for (const auto* instance : this->m_Instances) { - for (const auto* instancePlayer : instance->GetParticipants()) { - if (instancePlayer != nullptr && instancePlayer->GetObjectID() == player->GetObjectID()) - return true; - } - } + for (const auto* instance : this->m_Instances) { + for (const auto* instancePlayer : instance->GetParticipants()) { + if (instancePlayer != nullptr && instancePlayer->GetObjectID() == player->GetObjectID()) + return true; + } + } - return false; + return false; } bool ScriptedActivityComponent::IsPlayedBy(LWOOBJID playerID) const { - for (const auto* instance : this->m_Instances) { - for (const auto* instancePlayer : instance->GetParticipants()) { - if (instancePlayer != nullptr && instancePlayer->GetObjectID() == playerID) - return true; - } - } + for (const auto* instance : this->m_Instances) { + for (const auto* instancePlayer : instance->GetParticipants()) { + if (instancePlayer != nullptr && instancePlayer->GetObjectID() == playerID) + return true; + } + } - return false; + return false; } bool ScriptedActivityComponent::TakeCost(Entity* player) const { @@ -365,14 +363,14 @@ ActivityInstance* ScriptedActivityComponent::NewInstance() { } void ScriptedActivityComponent::LoadPlayersIntoInstance(ActivityInstance* instance, const std::vector& lobby) const { - for (LobbyPlayer* player : lobby) { - auto* entity = player->GetEntity(); - if (entity == nullptr || !TakeCost(entity)) { - continue; - } + for (LobbyPlayer* player : lobby) { + auto* entity = player->GetEntity(); + if (entity == nullptr || !TakeCost(entity)) { + continue; + } - instance->AddParticipant(entity); - } + instance->AddParticipant(entity); + } } const std::vector& ScriptedActivityComponent::GetInstances() const { @@ -380,14 +378,14 @@ const std::vector& ScriptedActivityComponent::GetInstances() } ActivityInstance* ScriptedActivityComponent::GetInstance(const LWOOBJID playerID) { - for (const auto* instance : GetInstances()) { - for (const auto* participant : instance->GetParticipants()) { - if (participant->GetObjectID() == playerID) - return const_cast(instance); - } - } + for (const auto* instance : GetInstances()) { + for (const auto* participant : instance->GetParticipants()) { + if (participant->GetObjectID() == playerID) + return const_cast(instance); + } + } - return nullptr; + return nullptr; } void ScriptedActivityComponent::ClearInstances() { @@ -397,12 +395,9 @@ void ScriptedActivityComponent::ClearInstances() { m_Instances.clear(); } -ActivityPlayer* ScriptedActivityComponent::GetActivityPlayerData(LWOOBJID playerID) -{ - for (auto* activityData : m_ActivityPlayers) - { - if (activityData->playerID == playerID) - { +ActivityPlayer* ScriptedActivityComponent::GetActivityPlayerData(LWOOBJID playerID) { + for (auto* activityData : m_ActivityPlayers) { + if (activityData->playerID == playerID) { return activityData; } } @@ -410,87 +405,83 @@ ActivityPlayer* ScriptedActivityComponent::GetActivityPlayerData(LWOOBJID player return nullptr; } -void ScriptedActivityComponent::RemoveActivityPlayerData(LWOOBJID playerID) -{ - for (size_t i = 0; i < m_ActivityPlayers.size(); i++) - { - if (m_ActivityPlayers[i]->playerID == playerID) - { +void ScriptedActivityComponent::RemoveActivityPlayerData(LWOOBJID playerID) { + for (size_t i = 0; i < m_ActivityPlayers.size(); i++) { + if (m_ActivityPlayers[i]->playerID == playerID) { delete m_ActivityPlayers[i]; m_ActivityPlayers[i] = nullptr; m_ActivityPlayers.erase(m_ActivityPlayers.begin() + i); - EntityManager::Instance()->SerializeEntity(m_Parent); + EntityManager::Instance()->SerializeEntity(m_Parent); return; } } } -ActivityPlayer* ScriptedActivityComponent::AddActivityPlayerData(LWOOBJID playerID) -{ +ActivityPlayer* ScriptedActivityComponent::AddActivityPlayerData(LWOOBJID playerID) { auto* data = GetActivityPlayerData(playerID); if (data != nullptr) - return data; + return data; - m_ActivityPlayers.push_back(new ActivityPlayer{playerID, {}}); - EntityManager::Instance()->SerializeEntity(m_Parent); + m_ActivityPlayers.push_back(new ActivityPlayer{ playerID, {} }); + EntityManager::Instance()->SerializeEntity(m_Parent); return GetActivityPlayerData(playerID); } float_t ScriptedActivityComponent::GetActivityValue(LWOOBJID playerID, uint32_t index) { - auto value = -1.0f; + auto value = -1.0f; - auto* data = GetActivityPlayerData(playerID); - if (data != nullptr) { - value = data->values[std::min(index, (uint32_t) 9)]; - } + auto* data = GetActivityPlayerData(playerID); + if (data != nullptr) { + value = data->values[std::min(index, (uint32_t)9)]; + } - return value; + return value; } void ScriptedActivityComponent::SetActivityValue(LWOOBJID playerID, uint32_t index, float_t value) { - auto* data = AddActivityPlayerData(playerID); - if (data != nullptr) { - data->values[std::min(index, (uint32_t) 9)] = value; - } + auto* data = AddActivityPlayerData(playerID); + if (data != nullptr) { + data->values[std::min(index, (uint32_t)9)] = value; + } - EntityManager::Instance()->SerializeEntity(m_Parent); + EntityManager::Instance()->SerializeEntity(m_Parent); } void ScriptedActivityComponent::PlayerRemove(LWOOBJID playerID) { - for (auto* instance : GetInstances()) { - auto participants = instance->GetParticipants(); - for (const auto* participant : participants) { - if (participant != nullptr && participant->GetObjectID() == playerID) { - instance->RemoveParticipant(participant); - RemoveActivityPlayerData(playerID); + for (auto* instance : GetInstances()) { + auto participants = instance->GetParticipants(); + for (const auto* participant : participants) { + if (participant != nullptr && participant->GetObjectID() == playerID) { + instance->RemoveParticipant(participant); + RemoveActivityPlayerData(playerID); - // If the instance is empty after the delete of the participant, delete the instance too - if (instance->GetParticipants().empty()) { - m_Instances.erase(std::find(m_Instances.begin(), m_Instances.end(), instance)); - delete instance; - } - return; - } - } - } + // If the instance is empty after the delete of the participant, delete the instance too + if (instance->GetParticipants().empty()) { + m_Instances.erase(std::find(m_Instances.begin(), m_Instances.end(), instance)); + delete instance; + } + return; + } + } + } } void ActivityInstance::StartZone() { if (m_Participants.empty()) - return; + return; const auto& participants = GetParticipants(); if (participants.empty()) - return; + return; auto* leader = participants[0]; LWOZONEID zoneId = LWOZONEID(m_ActivityInfo.instanceMapID, 0, leader->GetCharacter()->GetPropertyCloneID()); // only make a team if we have more than one participant - if (participants.size() > 1){ + if (participants.size() > 1) { CBITSTREAM; PacketUtils::WriteHeader(bitStream, CHAT_INTERNAL, MSG_CHAT_INTERNAL_CREATE_TEAM); @@ -524,7 +515,7 @@ void ActivityInstance::StartZone() { WorldPackets::SendTransferToWorld(player->GetSystemAddress(), serverIP, serverPort, mythranShift); return; - }); + }); } m_NextZoneCloneID++; @@ -572,24 +563,24 @@ std::vector ActivityInstance::GetParticipants() const { void ActivityInstance::AddParticipant(Entity* participant) { const auto id = participant->GetObjectID(); if (std::count(m_Participants.begin(), m_Participants.end(), id)) - return; + return; m_Participants.push_back(id); } -void ActivityInstance::RemoveParticipant(const Entity *participant) { - const auto loadedParticipant = std::find(m_Participants.begin(), m_Participants.end(), participant->GetObjectID()); - if (loadedParticipant != m_Participants.end()) { - m_Participants.erase(loadedParticipant); - } +void ActivityInstance::RemoveParticipant(const Entity* participant) { + const auto loadedParticipant = std::find(m_Participants.begin(), m_Participants.end(), participant->GetObjectID()); + if (loadedParticipant != m_Participants.end()) { + m_Participants.erase(loadedParticipant); + } } uint32_t ActivityInstance::GetScore() const { - return score; + return score; } void ActivityInstance::SetScore(uint32_t score) { - this->score = score; + this->score = score; } Entity* LobbyPlayer::GetEntity() const { diff --git a/dGame/dComponents/ScriptedActivityComponent.h b/dGame/dComponents/ScriptedActivityComponent.h index 8d79df8b..66ca799f 100644 --- a/dGame/dComponents/ScriptedActivityComponent.h +++ b/dGame/dComponents/ScriptedActivityComponent.h @@ -12,82 +12,82 @@ #include "Entity.h" #include "Component.h" -/** - * Represents an instance of an activity, having participants and score - */ + /** + * Represents an instance of an activity, having participants and score + */ class ActivityInstance { public: ActivityInstance(Entity* parent, CDActivities activityInfo) { m_Parent = parent; m_ActivityInfo = activityInfo; }; //~ActivityInstance(); - /** - * Adds an entity to this activity - * @param participant the entity to add - */ + /** + * Adds an entity to this activity + * @param participant the entity to add + */ void AddParticipant(Entity* participant); - /** - * Removes all the participants from this activity - */ + /** + * Removes all the participants from this activity + */ void ClearParticipants() { m_Participants.clear(); }; - /** - * Starts the instance world for this activity and sends all participants there - */ + /** + * Starts the instance world for this activity and sends all participants there + */ void StartZone(); - /** - * Gives the rewards for completing this activity to some participant - * @param participant the participant to give rewards to - */ + /** + * Gives the rewards for completing this activity to some participant + * @param participant the participant to give rewards to + */ void RewardParticipant(Entity* participant); - /** - * Removes a participant from this activity - * @param participant the participant to remove - */ + /** + * Removes a participant from this activity + * @param participant the participant to remove + */ void RemoveParticipant(const Entity* participant); - /** - * Returns all the participants of this activity - * @return all the participants of this activity - */ + /** + * Returns all the participants of this activity + * @return all the participants of this activity + */ std::vector GetParticipants() const; - /** - * Currently unused - */ + /** + * Currently unused + */ uint32_t GetScore() const; - /** - * Currently unused - */ + /** + * Currently unused + */ void SetScore(uint32_t score); private: - /** - * Currently unused - */ - uint32_t score = 0; + /** + * Currently unused + */ + uint32_t score = 0; - /** - * The instance ID of this activity - */ + /** + * The instance ID of this activity + */ uint32_t m_NextZoneCloneID = 0; - /** - * The database information for this activity - */ + /** + * The database information for this activity + */ CDActivities m_ActivityInfo; - /** - * The entity that owns this activity (the entity that has the ScriptedActivityComponent) - */ + /** + * The entity that owns this activity (the entity that has the ScriptedActivityComponent) + */ Entity* m_Parent; - /** - * All the participants of this activity - */ + /** + * All the participants of this activity + */ std::vector m_Participants; }; @@ -96,20 +96,20 @@ private: */ struct LobbyPlayer { - /** - * The ID of the entity that is in the lobby - */ + /** + * The ID of the entity that is in the lobby + */ LWOOBJID entityID; - /** - * Whether or not the entity is ready - */ + /** + * Whether or not the entity is ready + */ bool ready = false; - /** - * Returns the entity that is in the lobby - * @return the entity that is in the lobby - */ + /** + * Returns the entity that is in the lobby + * @return the entity that is in the lobby + */ Entity* GetEntity() const; }; @@ -118,14 +118,14 @@ struct LobbyPlayer { */ struct Lobby { - /** - * The lobby of players - */ + /** + * The lobby of players + */ std::vector players; - /** - * The timer that determines when the activity should start - */ + /** + * The timer that determines when the activity should start + */ float timer; }; @@ -134,14 +134,14 @@ struct Lobby { */ struct ActivityPlayer { - /** - * The entity that the score is tracked for - */ + /** + * The entity that the score is tracked for + */ LWOOBJID playerID; - /** - * The list of score for this entity - */ + /** + * The list of score for this entity + */ float values[10]; }; @@ -154,213 +154,213 @@ struct ActivityPlayer { class ScriptedActivityComponent : public Component { public: static const uint32_t ComponentType = COMPONENT_TYPE_SCRIPTED_ACTIVITY; - + ScriptedActivityComponent(Entity* parent, int activityID); ~ScriptedActivityComponent() override; - void Update(float deltaTime) override; - void Serialize(RakNet::BitStream* outBitStream, bool bIsInitialUpdate, unsigned int& flags) const; + void Update(float deltaTime) override; + void Serialize(RakNet::BitStream* outBitStream, bool bIsInitialUpdate, unsigned int& flags) const; - /** - * Makes some entity join the minigame, if it's a lobbied one, the entity will be placed in the lobby - * @param player the entity to join the game - */ + /** + * Makes some entity join the minigame, if it's a lobbied one, the entity will be placed in the lobby + * @param player the entity to join the game + */ void PlayerJoin(Entity* player); - /** - * Makes an entity join the lobby for this minigame, if it exists - * @param player the entity to join - */ + /** + * Makes an entity join the lobby for this minigame, if it exists + * @param player the entity to join + */ void PlayerJoinLobby(Entity* player); - /** - * Makes the player leave the lobby - * @param playerID the entity to leave the lobby - */ + /** + * Makes the player leave the lobby + * @param playerID the entity to leave the lobby + */ void PlayerLeave(LWOOBJID playerID); - /** - * Removes the entity from the minigame (and its score) - * @param playerID the entity to remove from the minigame - */ + /** + * Removes the entity from the minigame (and its score) + * @param playerID the entity to remove from the minigame + */ void PlayerRemove(LWOOBJID playerID); - /** - * Adds all the players to an instance of some activity - * @param instance the instance to load the players into - * @param lobby the players to load into the instance - */ + /** + * Adds all the players to an instance of some activity + * @param instance the instance to load the players into + * @param lobby the players to load into the instance + */ void LoadPlayersIntoInstance(ActivityInstance* instance, const std::vector& lobby) const; - /** - * Removes a lobby from the activity manager - * @param lobby the lobby to remove - */ + /** + * Removes a lobby from the activity manager + * @param lobby the lobby to remove + */ void RemoveLobby(Lobby* lobby); - /** - * Marks a player as (un)ready in a lobby - * @param player the entity to mark - * @param bReady true if the entity is ready, false otherwise - */ + /** + * Marks a player as (un)ready in a lobby + * @param player the entity to mark + * @param bReady true if the entity is ready, false otherwise + */ void PlayerReady(Entity* player, bool bReady); - /** - * Returns the ID of this activity - * @return the ID of this activity - */ + /** + * Returns the ID of this activity + * @return the ID of this activity + */ int GetActivityID() { return m_ActivityInfo.ActivityID; } - /** - * Returns if this activity has a lobby, e.g. if it needs to instance players to some other map - * @return true if this activity has a lobby, false otherwise - */ - bool HasLobby() const; + /** + * Returns if this activity has a lobby, e.g. if it needs to instance players to some other map + * @return true if this activity has a lobby, false otherwise + */ + bool HasLobby() const; - /** - * Checks if a player is currently waiting in a lobby - * @param player the entity to check for - * @return true if the entity is waiting in a lobby, false otherwise - */ + /** + * Checks if a player is currently waiting in a lobby + * @param player the entity to check for + * @return true if the entity is waiting in a lobby, false otherwise + */ bool PlayerIsInQueue(Entity* player); - /** - * Checks if an entity is currently playing this activity - * @param player the entity to check - * @return true if the entity is playing this lobby, false otherwise - */ + /** + * Checks if an entity is currently playing this activity + * @param player the entity to check + * @return true if the entity is playing this lobby, false otherwise + */ bool IsPlayedBy(Entity* player) const; - /** - * Checks if an entity is currently playing this activity - * @param playerID the entity to check - * @return true if the entity is playing this lobby, false otherwise - */ - bool IsPlayedBy(LWOOBJID playerID) const; + /** + * Checks if an entity is currently playing this activity + * @param playerID the entity to check + * @return true if the entity is playing this lobby, false otherwise + */ + bool IsPlayedBy(LWOOBJID playerID) const; - /** - * Legacy: used to check for unimplemented maps, gladly, this now just returns true :) - */ + /** + * Legacy: used to check for unimplemented maps, gladly, this now just returns true :) + */ bool IsValidActivity(Entity* player); - /** - * Removes the cost of the activity (e.g. green imaginate) for the entity that plays this activity - * @param player the entity to take cost for - * @return true if the cost was successfully deducted, false otherwise - */ + /** + * Removes the cost of the activity (e.g. green imaginate) for the entity that plays this activity + * @param player the entity to take cost for + * @return true if the cost was successfully deducted, false otherwise + */ bool TakeCost(Entity* player) const; - /** - * Handles any response from a player clicking on a lobby / instance menu - * @param player the entity that clicked - * @param id the message that was passed - */ + /** + * Handles any response from a player clicking on a lobby / instance menu + * @param player the entity that clicked + * @param id the message that was passed + */ void HandleMessageBoxResponse(Entity* player, const std::string& id); - /** - * Creates a new instance for this activity - * @return a new instance for this activity - */ + /** + * Creates a new instance for this activity + * @return a new instance for this activity + */ ActivityInstance* NewInstance(); - /** - * Returns all the currently active instances of this activity - * @return all the currently active instances of this activity - */ + /** + * Returns all the currently active instances of this activity + * @return all the currently active instances of this activity + */ const std::vector& GetInstances() const; - /** - * Returns the instance that some entity is currently playing in - * @param playerID the entity to check for - * @return if any, the instance that the entity is currently in - */ + /** + * Returns the instance that some entity is currently playing in + * @param playerID the entity to check for + * @return if any, the instance that the entity is currently in + */ ActivityInstance* GetInstance(const LWOOBJID playerID); - /** - * Removes all the instances - */ + /** + * Removes all the instances + */ void ClearInstances(); - /** - * Returns all the score for the players that are currently playing this activity - * @return - */ + /** + * Returns all the score for the players that are currently playing this activity + * @return + */ std::vector GetActivityPlayers() { return m_ActivityPlayers; }; - /** - * Returns activity data for a specific entity (e.g. score and such). - * @param playerID the entity to get data for - * @return the activity data (score) for the passed player in this activity, if it exists - */ + /** + * Returns activity data for a specific entity (e.g. score and such). + * @param playerID the entity to get data for + * @return the activity data (score) for the passed player in this activity, if it exists + */ ActivityPlayer* GetActivityPlayerData(LWOOBJID playerID); - /** - * Sets some score value for an entity - * @param playerID the entity to set score for - * @param index the score index to set - * @param value the value to set in for that index - */ + /** + * Sets some score value for an entity + * @param playerID the entity to set score for + * @param index the score index to set + * @param value the value to set in for that index + */ void SetActivityValue(LWOOBJID playerID, uint32_t index, float_t value); - /** - * Returns activity score for the passed parameters - * @param playerID the entity to get score for - * @param index the index to get score for - * @return activity score for the passed parameters - */ + /** + * Returns activity score for the passed parameters + * @param playerID the entity to get score for + * @param index the index to get score for + * @return activity score for the passed parameters + */ float_t GetActivityValue(LWOOBJID playerID, uint32_t index); - /** - * Removes activity score tracking for some entity - * @param playerID the entity to remove score for - */ + /** + * Removes activity score tracking for some entity + * @param playerID the entity to remove score for + */ void RemoveActivityPlayerData(LWOOBJID playerID); - /** - * Adds activity score tracking for some entity - * @param playerID the entity to add the activity score for - * @return the created entry - */ + /** + * Adds activity score tracking for some entity + * @param playerID the entity to add the activity score for + * @return the created entry + */ ActivityPlayer* AddActivityPlayerData(LWOOBJID playerID); - /** - * Sets the mapID that this activity points to - * @param mapID the map ID to set - */ + /** + * Sets the mapID that this activity points to + * @param mapID the map ID to set + */ void SetInstanceMapID(uint32_t mapID) { m_ActivityInfo.instanceMapID = mapID; }; - /** - * Returns the LMI that this activity points to for a team size - * @param teamSize the team size to get the LMI for - * @return the LMI that this activity points to for a team size - */ - uint32_t GetLootMatrixForTeamSize(uint32_t teamSize) { return m_ActivityLootMatrices[teamSize]; } + /** + * Returns the LMI that this activity points to for a team size + * @param teamSize the team size to get the LMI for + * @return the LMI that this activity points to for a team size + */ + uint32_t GetLootMatrixForTeamSize(uint32_t teamSize) { return m_ActivityLootMatrices[teamSize]; } private: - /** - * The database information for this activity - */ + /** + * The database information for this activity + */ CDActivities m_ActivityInfo; - /** - * All the active instances of this activity - */ + /** + * All the active instances of this activity + */ std::vector m_Instances; - /** - * The current lobbies for this activity - */ + /** + * The current lobbies for this activity + */ std::vector m_Queue; - /** - * All the activity score for the players in this activity - */ + /** + * All the activity score for the players in this activity + */ std::vector m_ActivityPlayers; - /** - * LMIs for team sizes - */ - std::unordered_map m_ActivityLootMatrices; + /** + * LMIs for team sizes + */ + std::unordered_map m_ActivityLootMatrices; }; #endif // SCRIPTEDACTIVITYCOMPONENT_H diff --git a/dGame/dComponents/ShootingGalleryComponent.cpp b/dGame/dComponents/ShootingGalleryComponent.cpp index f0fac7f4..d5e12b28 100644 --- a/dGame/dComponents/ShootingGalleryComponent.cpp +++ b/dGame/dComponents/ShootingGalleryComponent.cpp @@ -2,66 +2,64 @@ #include "EntityManager.h" #include "ScriptedActivityComponent.h" -ShootingGalleryComponent::ShootingGalleryComponent(Entity *parent) : Component(parent) { +ShootingGalleryComponent::ShootingGalleryComponent(Entity* parent) : Component(parent) { } ShootingGalleryComponent::~ShootingGalleryComponent() = default; -void ShootingGalleryComponent::SetStaticParams(const StaticShootingGalleryParams ¶ms) { - m_StaticParams = params; +void ShootingGalleryComponent::SetStaticParams(const StaticShootingGalleryParams& params) { + m_StaticParams = params; } -void ShootingGalleryComponent::SetDynamicParams(const DynamicShootingGalleryParams ¶ms) { - m_DynamicParams = params; - m_Dirty = true; - EntityManager::Instance()->SerializeEntity(m_Parent); +void ShootingGalleryComponent::SetDynamicParams(const DynamicShootingGalleryParams& params) { + m_DynamicParams = params; + m_Dirty = true; + EntityManager::Instance()->SerializeEntity(m_Parent); } -void ShootingGalleryComponent::Serialize(RakNet::BitStream *outBitStream, bool isInitialUpdate, uint32_t& flags) const { - // Start ScriptedActivityComponent - outBitStream->Write(true); - if (m_CurrentPlayerID == LWOOBJID_EMPTY) { - outBitStream->Write(0); - } - else { - outBitStream->Write(1); - for (size_t i = 0; i < 10; i++) - { - outBitStream->Write(0.0f); - } - - } - // End ScriptedActivityComponent +void ShootingGalleryComponent::Serialize(RakNet::BitStream* outBitStream, bool isInitialUpdate, uint32_t& flags) const { + // Start ScriptedActivityComponent + outBitStream->Write(true); + if (m_CurrentPlayerID == LWOOBJID_EMPTY) { + outBitStream->Write(0); + } else { + outBitStream->Write(1); + for (size_t i = 0; i < 10; i++) { + outBitStream->Write(0.0f); + } - if (isInitialUpdate) { - outBitStream->Write(m_StaticParams.cameraPosition.GetX()); - outBitStream->Write(m_StaticParams.cameraPosition.GetY()); - outBitStream->Write(m_StaticParams.cameraPosition.GetZ()); + } + // End ScriptedActivityComponent - outBitStream->Write(m_StaticParams.cameraLookatPosition.GetX()); - outBitStream->Write(m_StaticParams.cameraLookatPosition.GetY()); - outBitStream->Write(m_StaticParams.cameraLookatPosition.GetZ()); - } + if (isInitialUpdate) { + outBitStream->Write(m_StaticParams.cameraPosition.GetX()); + outBitStream->Write(m_StaticParams.cameraPosition.GetY()); + outBitStream->Write(m_StaticParams.cameraPosition.GetZ()); - outBitStream->Write(m_Dirty || isInitialUpdate); - if (m_Dirty || isInitialUpdate) { - outBitStream->Write(m_DynamicParams.cannonVelocity); - outBitStream->Write(m_DynamicParams.cannonRefireRate); - outBitStream->Write(m_DynamicParams.cannonMinDistance); + outBitStream->Write(m_StaticParams.cameraLookatPosition.GetX()); + outBitStream->Write(m_StaticParams.cameraLookatPosition.GetY()); + outBitStream->Write(m_StaticParams.cameraLookatPosition.GetZ()); + } - outBitStream->Write(m_DynamicParams.cameraBarrelOffset.GetX()); - outBitStream->Write(m_DynamicParams.cameraBarrelOffset.GetY()); - outBitStream->Write(m_DynamicParams.cameraBarrelOffset.GetZ()); + outBitStream->Write(m_Dirty || isInitialUpdate); + if (m_Dirty || isInitialUpdate) { + outBitStream->Write(m_DynamicParams.cannonVelocity); + outBitStream->Write(m_DynamicParams.cannonRefireRate); + outBitStream->Write(m_DynamicParams.cannonMinDistance); - outBitStream->Write(m_DynamicParams.cannonAngle); + outBitStream->Write(m_DynamicParams.cameraBarrelOffset.GetX()); + outBitStream->Write(m_DynamicParams.cameraBarrelOffset.GetY()); + outBitStream->Write(m_DynamicParams.cameraBarrelOffset.GetZ()); - outBitStream->Write(m_DynamicParams.facing.GetX()); - outBitStream->Write(m_DynamicParams.facing.GetY()); - outBitStream->Write(m_DynamicParams.facing.GetZ()); + outBitStream->Write(m_DynamicParams.cannonAngle); - outBitStream->Write(m_CurrentPlayerID); - outBitStream->Write(m_DynamicParams.cannonTimeout); - outBitStream->Write(m_DynamicParams.cannonFOV); - } + outBitStream->Write(m_DynamicParams.facing.GetX()); + outBitStream->Write(m_DynamicParams.facing.GetY()); + outBitStream->Write(m_DynamicParams.facing.GetZ()); + + outBitStream->Write(m_CurrentPlayerID); + outBitStream->Write(m_DynamicParams.cannonTimeout); + outBitStream->Write(m_DynamicParams.cannonFOV); + } } diff --git a/dGame/dComponents/ShootingGalleryComponent.h b/dGame/dComponents/ShootingGalleryComponent.h index 323bf88f..c43f20c2 100644 --- a/dGame/dComponents/ShootingGalleryComponent.h +++ b/dGame/dComponents/ShootingGalleryComponent.h @@ -9,45 +9,45 @@ */ struct DynamicShootingGalleryParams { - /** - * The distance from the camera to the barrel - */ - Vector3 cameraBarrelOffset; + /** + * The distance from the camera to the barrel + */ + Vector3 cameraBarrelOffset; - /** - * The area the barrel is looking at - */ - Vector3 facing; + /** + * The area the barrel is looking at + */ + Vector3 facing; - /** - * The velocity of the cannonballs - */ - double_t cannonVelocity; + /** + * The velocity of the cannonballs + */ + double_t cannonVelocity; - /** - * The max firerate of the cannon - */ - double_t cannonRefireRate; + /** + * The max firerate of the cannon + */ + double_t cannonRefireRate; - /** - * The min distance the cannonballs traverse - */ - double_t cannonMinDistance; + /** + * The min distance the cannonballs traverse + */ + double_t cannonMinDistance; - /** - * The angle at which the cannon is shooting - */ - float_t cannonAngle; + /** + * The angle at which the cannon is shooting + */ + float_t cannonAngle; - /** - * The timeout between cannon shots - */ - float_t cannonTimeout; + /** + * The timeout between cannon shots + */ + float_t cannonTimeout; - /** - * The FOV while in the canon - */ - float_t cannonFOV; + /** + * The FOV while in the canon + */ + float_t cannonFOV; }; /** @@ -55,15 +55,15 @@ struct DynamicShootingGalleryParams { */ struct StaticShootingGalleryParams { - /** - * The position of the camera - */ - Vector3 cameraPosition; + /** + * The position of the camera + */ + Vector3 cameraPosition; - /** - * The position that the camera is looking at - */ - Vector3 cameraLookatPosition; + /** + * The position that the camera is looking at + */ + Vector3 cameraLookatPosition; }; /** @@ -72,66 +72,66 @@ struct StaticShootingGalleryParams { */ class ShootingGalleryComponent : public Component { public: - static const uint32_t ComponentType = COMPONENT_TYPE_SHOOTING_GALLERY; + static const uint32_t ComponentType = COMPONENT_TYPE_SHOOTING_GALLERY; - explicit ShootingGalleryComponent(Entity* parent); - ~ShootingGalleryComponent(); - void Serialize(RakNet::BitStream* outBitStream, bool isInitialUpdate, uint32_t& flags) const; + explicit ShootingGalleryComponent(Entity* parent); + ~ShootingGalleryComponent(); + void Serialize(RakNet::BitStream* outBitStream, bool isInitialUpdate, uint32_t& flags) const; - /** - * Returns the static params for the shooting gallery - * @return the static params for the shooting gallery - */ - const StaticShootingGalleryParams& GetStaticParams() const { return m_StaticParams; }; + /** + * Returns the static params for the shooting gallery + * @return the static params for the shooting gallery + */ + const StaticShootingGalleryParams& GetStaticParams() const { return m_StaticParams; }; - /** - * Sets the static parameters for the shooting gallery, see `StaticShootingGalleryParams` - * @param params the params to set - */ - void SetStaticParams(const StaticShootingGalleryParams& params); + /** + * Sets the static parameters for the shooting gallery, see `StaticShootingGalleryParams` + * @param params the params to set + */ + void SetStaticParams(const StaticShootingGalleryParams& params); - /** - * Returns the dynamic params for the shooting gallery - * @return the dynamic params for the shooting gallery - */ - const DynamicShootingGalleryParams& GetDynamicParams() const { return m_DynamicParams; }; + /** + * Returns the dynamic params for the shooting gallery + * @return the dynamic params for the shooting gallery + */ + const DynamicShootingGalleryParams& GetDynamicParams() const { return m_DynamicParams; }; - /** - * Sets the mutable params for the shooting gallery, see `DynamicShootingGalleryParams` - * @param params the params to set - */ - void SetDynamicParams(const DynamicShootingGalleryParams& params); + /** + * Sets the mutable params for the shooting gallery, see `DynamicShootingGalleryParams` + * @param params the params to set + */ + void SetDynamicParams(const DynamicShootingGalleryParams& params); - /** - * Sets the entity that's currently playing the shooting gallery - * @param playerID the entity to set - */ - void SetCurrentPlayerID(LWOOBJID playerID) { m_CurrentPlayerID = playerID; m_Dirty = true; }; + /** + * Sets the entity that's currently playing the shooting gallery + * @param playerID the entity to set + */ + void SetCurrentPlayerID(LWOOBJID playerID) { m_CurrentPlayerID = playerID; m_Dirty = true; }; - /** - * Returns the player that's currently playing the shooting gallery - * @return the player that's currently playing the shooting gallery - */ - LWOOBJID GetCurrentPlayerID() const { return m_CurrentPlayerID; }; + /** + * Returns the player that's currently playing the shooting gallery + * @return the player that's currently playing the shooting gallery + */ + LWOOBJID GetCurrentPlayerID() const { return m_CurrentPlayerID; }; private: - /** - * The player that's currently playing the shooting gallery - */ - LWOOBJID m_CurrentPlayerID = LWOOBJID_EMPTY; + /** + * The player that's currently playing the shooting gallery + */ + LWOOBJID m_CurrentPlayerID = LWOOBJID_EMPTY; - /** - * The static parameters for the shooting gallery, see `StaticShootingGalleryParams` - */ - StaticShootingGalleryParams m_StaticParams {}; + /** + * The static parameters for the shooting gallery, see `StaticShootingGalleryParams` + */ + StaticShootingGalleryParams m_StaticParams{}; - /** - * The dynamic params for the shooting gallery, see `DynamicShootingGalleryParams` - */ - DynamicShootingGalleryParams m_DynamicParams {}; + /** + * The dynamic params for the shooting gallery, see `DynamicShootingGalleryParams` + */ + DynamicShootingGalleryParams m_DynamicParams{}; - /** - * Whether or not the component should be serialized - */ - bool m_Dirty = false; + /** + * Whether or not the component should be serialized + */ + bool m_Dirty = false; }; diff --git a/dGame/dComponents/SimplePhysicsComponent.cpp b/dGame/dComponents/SimplePhysicsComponent.cpp index c9a42971..54a2e616 100644 --- a/dGame/dComponents/SimplePhysicsComponent.cpp +++ b/dGame/dComponents/SimplePhysicsComponent.cpp @@ -14,70 +14,65 @@ #include "Entity.h" SimplePhysicsComponent::SimplePhysicsComponent(uint32_t componentID, Entity* parent) : Component(parent) { - m_Position = m_Parent->GetDefaultPosition(); - m_Rotation = m_Parent->GetDefaultRotation(); - m_IsDirty = true; + m_Position = m_Parent->GetDefaultPosition(); + m_Rotation = m_Parent->GetDefaultRotation(); + m_IsDirty = true; - const auto& climbable_type = m_Parent->GetVar(u"climbable"); - if (climbable_type == u"wall") { - SetClimbableType(eClimbableType::CLIMBABLE_TYPE_WALL); - } else if (climbable_type == u"ladder") { - SetClimbableType(eClimbableType::CLIMBABLE_TYPE_LADDER); - } else if (climbable_type == u"wallstick") { - SetClimbableType(eClimbableType::CLIMBABLE_TYPE_WALL_STICK); - } else { - SetClimbableType(eClimbableType::CLIMBABLE_TYPE_NOT); - } + const auto& climbable_type = m_Parent->GetVar(u"climbable"); + if (climbable_type == u"wall") { + SetClimbableType(eClimbableType::CLIMBABLE_TYPE_WALL); + } else if (climbable_type == u"ladder") { + SetClimbableType(eClimbableType::CLIMBABLE_TYPE_LADDER); + } else if (climbable_type == u"wallstick") { + SetClimbableType(eClimbableType::CLIMBABLE_TYPE_WALL_STICK); + } else { + SetClimbableType(eClimbableType::CLIMBABLE_TYPE_NOT); + } } SimplePhysicsComponent::~SimplePhysicsComponent() { } void SimplePhysicsComponent::Serialize(RakNet::BitStream* outBitStream, bool bIsInitialUpdate, unsigned int& flags) { - if (bIsInitialUpdate) { - outBitStream->Write(m_ClimbableType != eClimbableType::CLIMBABLE_TYPE_NOT); - outBitStream->Write(m_ClimbableType); - } + if (bIsInitialUpdate) { + outBitStream->Write(m_ClimbableType != eClimbableType::CLIMBABLE_TYPE_NOT); + outBitStream->Write(m_ClimbableType); + } - outBitStream->Write(m_DirtyVelocity || bIsInitialUpdate); - if (m_DirtyVelocity || bIsInitialUpdate) { - outBitStream->Write(m_Velocity); - outBitStream->Write(m_AngularVelocity); + outBitStream->Write(m_DirtyVelocity || bIsInitialUpdate); + if (m_DirtyVelocity || bIsInitialUpdate) { + outBitStream->Write(m_Velocity); + outBitStream->Write(m_AngularVelocity); - m_DirtyVelocity = false; - } + m_DirtyVelocity = false; + } - // Physics motion state - if (m_PhysicsMotionState != 0) - { - outBitStream->Write1(); - outBitStream->Write(m_PhysicsMotionState); - } - else - { - outBitStream->Write0(); - } + // Physics motion state + if (m_PhysicsMotionState != 0) { + outBitStream->Write1(); + outBitStream->Write(m_PhysicsMotionState); + } else { + outBitStream->Write0(); + } - outBitStream->Write(m_IsDirty || bIsInitialUpdate); - if (m_IsDirty || bIsInitialUpdate) { - outBitStream->Write(m_Position.x); - outBitStream->Write(m_Position.y); - outBitStream->Write(m_Position.z); - outBitStream->Write(m_Rotation.x); - outBitStream->Write(m_Rotation.y); - outBitStream->Write(m_Rotation.z); - outBitStream->Write(m_Rotation.w); + outBitStream->Write(m_IsDirty || bIsInitialUpdate); + if (m_IsDirty || bIsInitialUpdate) { + outBitStream->Write(m_Position.x); + outBitStream->Write(m_Position.y); + outBitStream->Write(m_Position.z); + outBitStream->Write(m_Rotation.x); + outBitStream->Write(m_Rotation.y); + outBitStream->Write(m_Rotation.z); + outBitStream->Write(m_Rotation.w); - m_IsDirty = false; - } + m_IsDirty = false; + } } -uint32_t SimplePhysicsComponent::GetPhysicsMotionState() const -{ - return m_PhysicsMotionState; +uint32_t SimplePhysicsComponent::GetPhysicsMotionState() const { + return m_PhysicsMotionState; } -void SimplePhysicsComponent::SetPhysicsMotionState(uint32_t value) -{ - m_PhysicsMotionState = value; +void SimplePhysicsComponent::SetPhysicsMotionState(uint32_t value) { + m_PhysicsMotionState = value; } diff --git a/dGame/dComponents/SimplePhysicsComponent.h b/dGame/dComponents/SimplePhysicsComponent.h index 49e6be5b..ebb8b124 100644 --- a/dGame/dComponents/SimplePhysicsComponent.h +++ b/dGame/dComponents/SimplePhysicsComponent.h @@ -27,72 +27,72 @@ enum class eClimbableType : int32_t { */ class SimplePhysicsComponent : public Component { public: - static const uint32_t ComponentType = COMPONENT_TYPE_SIMPLE_PHYSICS; + static const uint32_t ComponentType = COMPONENT_TYPE_SIMPLE_PHYSICS; SimplePhysicsComponent(uint32_t componentID, Entity* parent); - ~SimplePhysicsComponent() override; + ~SimplePhysicsComponent() override; - void Serialize(RakNet::BitStream* outBitStream, bool bIsInitialUpdate, unsigned int& flags); + void Serialize(RakNet::BitStream* outBitStream, bool bIsInitialUpdate, unsigned int& flags); - /** - * Returns the position of this entity - * @return the position of this entity - */ - NiPoint3& GetPosition() { return m_Position; } + /** + * Returns the position of this entity + * @return the position of this entity + */ + NiPoint3& GetPosition() { return m_Position; } - /** - * Sets the position of this entity - * @param pos the position to set - */ - void SetPosition(const NiPoint3& pos) { m_Position = pos; m_IsDirty = true; } + /** + * Sets the position of this entity + * @param pos the position to set + */ + void SetPosition(const NiPoint3& pos) { m_Position = pos; m_IsDirty = true; } - /** - * Returns the rotation of this entity - * @return the rotation of this entity - */ - NiQuaternion& GetRotation() { return m_Rotation; } + /** + * Returns the rotation of this entity + * @return the rotation of this entity + */ + NiQuaternion& GetRotation() { return m_Rotation; } - /** - * Sets the rotation of this entity - * @param rot - */ - void SetRotation(const NiQuaternion& rot) { m_Rotation = rot; m_IsDirty = true; } + /** + * Sets the rotation of this entity + * @param rot + */ + void SetRotation(const NiQuaternion& rot) { m_Rotation = rot; m_IsDirty = true; } - /** - * Returns the velocity of this entity - * @return the velocity of this entity - */ - const NiPoint3& GetVelocity() { return m_Velocity; } + /** + * Returns the velocity of this entity + * @return the velocity of this entity + */ + const NiPoint3& GetVelocity() { return m_Velocity; } - /** - * Sets the velocity of this entity - * @param value the velocity to set - */ - void SetVelocity(const NiPoint3& value) { m_Velocity = value; m_DirtyVelocity = true; } + /** + * Sets the velocity of this entity + * @param value the velocity to set + */ + void SetVelocity(const NiPoint3& value) { m_Velocity = value; m_DirtyVelocity = true; } - /** - * Returns the angular velocity of this entity - * @return the angular velocity of this entity - */ - const NiPoint3& GetAngularVelocity() { return m_AngularVelocity; } + /** + * Returns the angular velocity of this entity + * @return the angular velocity of this entity + */ + const NiPoint3& GetAngularVelocity() { return m_AngularVelocity; } - /** - * Sets the angular velocity of this entity - * @param value the angular velocity to set - */ - void SetAngularVelocity(const NiPoint3& value) { m_AngularVelocity = value; m_DirtyVelocity = true; } + /** + * Sets the angular velocity of this entity + * @param value the angular velocity to set + */ + void SetAngularVelocity(const NiPoint3& value) { m_AngularVelocity = value; m_DirtyVelocity = true; } - /** - * Returns the physics motion state - * @return the physics motion state - */ - uint32_t GetPhysicsMotionState() const; + /** + * Returns the physics motion state + * @return the physics motion state + */ + uint32_t GetPhysicsMotionState() const; - /** - * Sets the physics motion state - * @param value the motion state to set - */ - void SetPhysicsMotionState(uint32_t value); + /** + * Sets the physics motion state + * @param value the motion state to set + */ + void SetPhysicsMotionState(uint32_t value); /** * Returns the ClimbableType of this entity @@ -108,45 +108,45 @@ public: private: - /** - * The current position of the entity - */ - NiPoint3 m_Position = NiPoint3::ZERO; + /** + * The current position of the entity + */ + NiPoint3 m_Position = NiPoint3::ZERO; - /** - * The current rotation of the entity - */ - NiQuaternion m_Rotation = NiQuaternion::IDENTITY; + /** + * The current rotation of the entity + */ + NiQuaternion m_Rotation = NiQuaternion::IDENTITY; - /** - * The current velocity of the entity - */ - NiPoint3 m_Velocity = NiPoint3::ZERO; + /** + * The current velocity of the entity + */ + NiPoint3 m_Velocity = NiPoint3::ZERO; - /** - * The current angular velocity of the entity - */ - NiPoint3 m_AngularVelocity = NiPoint3::ZERO; + /** + * The current angular velocity of the entity + */ + NiPoint3 m_AngularVelocity = NiPoint3::ZERO; - /** - * Whether or not the velocity has changed - */ - bool m_DirtyVelocity = true; + /** + * Whether or not the velocity has changed + */ + bool m_DirtyVelocity = true; - /** - * Whether or not the position has changed - */ - bool m_IsDirty = true; + /** + * Whether or not the position has changed + */ + bool m_IsDirty = true; - /** - * The current physics motion state - */ - uint32_t m_PhysicsMotionState = 0; + /** + * The current physics motion state + */ + uint32_t m_PhysicsMotionState = 0; - /** - * Whether or not the entity is climbable - */ - eClimbableType m_ClimbableType = eClimbableType::CLIMBABLE_TYPE_NOT; + /** + * Whether or not the entity is climbable + */ + eClimbableType m_ClimbableType = eClimbableType::CLIMBABLE_TYPE_NOT; }; #endif // SIMPLEPHYSICSCOMPONENT_H diff --git a/dGame/dComponents/SkillComponent.cpp b/dGame/dComponents/SkillComponent.cpp index 608eced6..f7e8e7d9 100644 --- a/dGame/dComponents/SkillComponent.cpp +++ b/dGame/dComponents/SkillComponent.cpp @@ -21,12 +21,10 @@ #include "BuffComponent.h" -ProjectileSyncEntry::ProjectileSyncEntry() -{ +ProjectileSyncEntry::ProjectileSyncEntry() { } -bool SkillComponent::CastPlayerSkill(const uint32_t behaviorId, const uint32_t skillUid, RakNet::BitStream* bitStream, const LWOOBJID target, uint32_t skillID) -{ +bool SkillComponent::CastPlayerSkill(const uint32_t behaviorId, const uint32_t skillUid, RakNet::BitStream* bitStream, const LWOOBJID target, uint32_t skillID) { auto* context = new BehaviorContext(this->m_Parent->GetObjectID()); context->caster = m_Parent->GetObjectID(); @@ -46,12 +44,10 @@ bool SkillComponent::CastPlayerSkill(const uint32_t behaviorId, const uint32_t s return !context->failed; } -void SkillComponent::SyncPlayerSkill(const uint32_t skillUid, const uint32_t syncId, RakNet::BitStream* bitStream) -{ +void SkillComponent::SyncPlayerSkill(const uint32_t skillUid, const uint32_t syncId, RakNet::BitStream* bitStream) { const auto index = this->m_managedBehaviors.find(skillUid); - if (index == this->m_managedBehaviors.end()) - { + if (index == this->m_managedBehaviors.end()) { Game::logger->Log("SkillComponent", "Failed to find skill with uid (%i)!", skillUid, syncId); return; @@ -63,24 +59,20 @@ void SkillComponent::SyncPlayerSkill(const uint32_t skillUid, const uint32_t syn } -void SkillComponent::SyncPlayerProjectile(const LWOOBJID projectileId, RakNet::BitStream* bitStream, const LWOOBJID target) -{ +void SkillComponent::SyncPlayerProjectile(const LWOOBJID projectileId, RakNet::BitStream* bitStream, const LWOOBJID target) { auto index = -1; - for (auto i = 0u; i < this->m_managedProjectiles.size(); ++i) - { + for (auto i = 0u; i < this->m_managedProjectiles.size(); ++i) { const auto& projectile = this->m_managedProjectiles.at(i); - if (projectile.id == projectileId) - { + if (projectile.id == projectileId) { index = i; break; } } - if (index == -1) - { + if (index == -1) { Game::logger->Log("SkillComponent", "Failed to find projectile id (%llu)!", projectileId); return; @@ -90,7 +82,7 @@ void SkillComponent::SyncPlayerProjectile(const LWOOBJID projectileId, RakNet::B auto query = CDClientDatabase::CreatePreppedStmt( "SELECT behaviorID FROM SkillBehavior WHERE skillID = (SELECT skillID FROM ObjectSkills WHERE objectTemplate = ?);"); - query.bind(1, (int) sync_entry.lot); + query.bind(1, (int)sync_entry.lot); auto result = query.execQuery(); @@ -110,8 +102,7 @@ void SkillComponent::SyncPlayerProjectile(const LWOOBJID projectileId, RakNet::B branch.isProjectile = true; - if (target != LWOOBJID_EMPTY) - { + if (target != LWOOBJID_EMPTY) { branch.target = target; } @@ -120,8 +111,7 @@ void SkillComponent::SyncPlayerProjectile(const LWOOBJID projectileId, RakNet::B this->m_managedProjectiles.erase(this->m_managedProjectiles.begin() + index); } -void SkillComponent::RegisterPlayerProjectile(const LWOOBJID projectileId, BehaviorContext* context, const BehaviorBranchContext& branch, const LOT lot) -{ +void SkillComponent::RegisterPlayerProjectile(const LWOOBJID projectileId, BehaviorContext* context, const BehaviorBranchContext& branch, const LOT lot) { ProjectileSyncEntry entry; entry.context = context; @@ -132,50 +122,39 @@ void SkillComponent::RegisterPlayerProjectile(const LWOOBJID projectileId, Behav this->m_managedProjectiles.push_back(entry); } -void SkillComponent::Update(const float deltaTime) -{ - if (!m_Parent->HasComponent(COMPONENT_TYPE_BASE_COMBAT_AI) && m_Parent->GetLOT() != 1) - { +void SkillComponent::Update(const float deltaTime) { + if (!m_Parent->HasComponent(COMPONENT_TYPE_BASE_COMBAT_AI) && m_Parent->GetLOT() != 1) { CalculateUpdate(deltaTime); } - std::map keep {}; + std::map keep{}; - for (const auto& pair : this->m_managedBehaviors) - { + for (const auto& pair : this->m_managedBehaviors) { auto* context = pair.second; - if (context == nullptr) - { + if (context == nullptr) { continue; } - if (context->clientInitalized) - { + if (context->clientInitalized) { context->CalculateUpdate(deltaTime); - } - else - { + } else { context->Update(deltaTime); } // Cleanup old behaviors - if (context->syncEntries.empty() && context->timerEntries.empty()) - { + if (context->syncEntries.empty() && context->timerEntries.empty()) { auto any = false; - for (const auto& projectile : this->m_managedProjectiles) - { - if (projectile.context == context) - { + for (const auto& projectile : this->m_managedProjectiles) { + if (projectile.context == context) { any = true; break; } } - if (!any) - { + if (!any) { context->Reset(); delete context; @@ -192,10 +171,8 @@ void SkillComponent::Update(const float deltaTime) this->m_managedBehaviors = keep; } -void SkillComponent::Reset() -{ - for (const auto& behavior : this->m_managedBehaviors) - { +void SkillComponent::Reset() { + for (const auto& behavior : this->m_managedBehaviors) { delete behavior.second; } @@ -203,26 +180,22 @@ void SkillComponent::Reset() this->m_managedBehaviors.clear(); } -void SkillComponent::Interrupt() -{ +void SkillComponent::Interrupt() { if (m_Parent->IsPlayer()) return; auto* combat = m_Parent->GetComponent(); - if (combat != nullptr && combat->GetStunImmune()) - { + if (combat != nullptr && combat->GetStunImmune()) { return; } - for (const auto& behavior : this->m_managedBehaviors) - { + for (const auto& behavior : this->m_managedBehaviors) { behavior.second->Interrupt(); } } void SkillComponent::RegisterCalculatedProjectile(const LWOOBJID projectileId, BehaviorContext* context, const BehaviorBranchContext& branch, const LOT lot, const float maxTime, - const NiPoint3& startPosition, const NiPoint3& velocity, const bool trackTarget, const float trackRadius) -{ + const NiPoint3& startPosition, const NiPoint3& velocity, const bool trackTarget, const float trackRadius) { ProjectileSyncEntry entry; entry.context = context; @@ -242,8 +215,7 @@ void SkillComponent::RegisterCalculatedProjectile(const LWOOBJID projectileId, B } -SkillExecutionResult SkillComponent::CalculateBehavior(const uint32_t skillId, const uint32_t behaviorId, const LWOOBJID target, const bool ignoreTarget, const bool clientInitalized, const LWOOBJID originatorOverride) -{ +SkillExecutionResult SkillComponent::CalculateBehavior(const uint32_t skillId, const uint32_t behaviorId, const LWOOBJID target, const bool ignoreTarget, const bool clientInitalized, const LWOOBJID originatorOverride) { auto* bitStream = new RakNet::BitStream(); auto* behavior = Behavior::CreateBehavior(behaviorId); @@ -256,14 +228,13 @@ SkillExecutionResult SkillComponent::CalculateBehavior(const uint32_t skillId, c context->foundTarget = target != LWOOBJID_EMPTY || ignoreTarget || clientInitalized; - behavior->Calculate(context, bitStream, { target, 0}); + behavior->Calculate(context, bitStream, { target, 0 }); for (auto* script : CppScripts::GetEntityScripts(m_Parent)) { - script->OnSkillCast(m_Parent, skillId); + script->OnSkillCast(m_Parent, skillId); } - if (!context->foundTarget) - { + if (!context->foundTarget) { delete bitStream; delete context; @@ -273,8 +244,7 @@ SkillExecutionResult SkillComponent::CalculateBehavior(const uint32_t skillId, c this->m_managedBehaviors.insert_or_assign(context->skillUId, context); - if (!clientInitalized) - { + if (!clientInitalized) { // Echo start skill GameMessages::EchoStartSkill start; @@ -285,8 +255,7 @@ SkillExecutionResult SkillComponent::CalculateBehavior(const uint32_t skillId, c auto* originator = EntityManager::Instance()->GetEntity(context->originator); - if (originator != nullptr) - { + if (originator != nullptr) { start.originatorRot = originator->GetRotation(); } //start.optionalTargetID = target; @@ -311,23 +280,19 @@ SkillExecutionResult SkillComponent::CalculateBehavior(const uint32_t skillId, c return { true, context->skillTime }; } -void SkillComponent::CalculateUpdate(const float deltaTime) -{ - if (this->m_managedBehaviors.empty()) - return; +void SkillComponent::CalculateUpdate(const float deltaTime) { + if (this->m_managedBehaviors.empty()) + return; - for (const auto& managedBehavior : this->m_managedBehaviors) - { - if (managedBehavior.second == nullptr) - { + for (const auto& managedBehavior : this->m_managedBehaviors) { + if (managedBehavior.second == nullptr) { continue; } managedBehavior.second->CalculateUpdate(deltaTime); } - for (auto& managedProjectile : this->m_managedProjectiles) - { + for (auto& managedProjectile : this->m_managedProjectiles) { auto entry = managedProjectile; if (!entry.calculation) continue; @@ -336,8 +301,7 @@ void SkillComponent::CalculateUpdate(const float deltaTime) auto* origin = EntityManager::Instance()->GetEntity(entry.context->originator); - if (origin == nullptr) - { + if (origin == nullptr) { continue; } @@ -345,8 +309,7 @@ void SkillComponent::CalculateUpdate(const float deltaTime) const auto position = entry.startPosition + (entry.velocity * entry.time); - for (const auto& targetId : targets) - { + for (const auto& targetId : targets) { auto* target = EntityManager::Instance()->GetEntity(targetId); const auto targetPosition = target->GetPosition(); @@ -355,8 +318,7 @@ void SkillComponent::CalculateUpdate(const float deltaTime) const auto distance = Vector3::DistanceSquared(targetPosition, closestPoint); - if (distance > 3 * 3) - { + if (distance > 3 * 3) { /* if (entry.TrackTarget && distance <= entry.TrackRadius) { @@ -404,12 +366,9 @@ void SkillComponent::CalculateUpdate(const float deltaTime) std::vector valid; - for (auto& entry : this->m_managedProjectiles) - { - if (entry.calculation) - { - if (entry.time >= entry.maxTime) - { + for (auto& entry : this->m_managedProjectiles) { + if (entry.calculation) { + if (entry.time >= entry.maxTime) { entry.branchContext.target = LWOOBJID_EMPTY; SyncProjectileCalculation(entry); @@ -425,13 +384,11 @@ void SkillComponent::CalculateUpdate(const float deltaTime) } -void SkillComponent::SyncProjectileCalculation(const ProjectileSyncEntry& entry) const -{ +void SkillComponent::SyncProjectileCalculation(const ProjectileSyncEntry& entry) const { auto* other = EntityManager::Instance()->GetEntity(entry.branchContext.target); if (other == nullptr) { - if (entry.branchContext.target != LWOOBJID_EMPTY) - { + if (entry.branchContext.target != LWOOBJID_EMPTY) { Game::logger->Log("SkillComponent", "Invalid projectile target (%llu)!", entry.branchContext.target); } @@ -440,7 +397,7 @@ void SkillComponent::SyncProjectileCalculation(const ProjectileSyncEntry& entry) auto query = CDClientDatabase::CreatePreppedStmt( "SELECT behaviorID FROM SkillBehavior WHERE skillID = (SELECT skillID FROM ObjectSkills WHERE objectTemplate = ?);"); - query.bind(1, (int) entry.lot); + query.bind(1, (int)entry.lot); auto result = query.execQuery(); if (result.eof()) { @@ -461,7 +418,7 @@ void SkillComponent::SyncProjectileCalculation(const ProjectileSyncEntry& entry) GameMessages::DoClientProjectileImpact projectileImpact; - projectileImpact.sBitStream.assign((char*) bitStream->GetData(), bitStream->GetNumberOfBytesUsed()); + projectileImpact.sBitStream.assign((char*)bitStream->GetData(), bitStream->GetNumberOfBytesUsed()); projectileImpact.i64OwnerID = this->m_Parent->GetObjectID(); projectileImpact.i64OrgID = entry.id; projectileImpact.i64TargetID = entry.branchContext.target; @@ -479,8 +436,7 @@ void SkillComponent::SyncProjectileCalculation(const ProjectileSyncEntry& entry) delete bitStream; } -void SkillComponent::HandleUnmanaged(const uint32_t behaviorId, const LWOOBJID target, LWOOBJID source) -{ +void SkillComponent::HandleUnmanaged(const uint32_t behaviorId, const LWOOBJID target, LWOOBJID source) { auto* context = new BehaviorContext(source); context->unmanaged = true; @@ -497,8 +453,7 @@ void SkillComponent::HandleUnmanaged(const uint32_t behaviorId, const LWOOBJID t delete context; } -void SkillComponent::HandleUnCast(const uint32_t behaviorId, const LWOOBJID target) -{ +void SkillComponent::HandleUnCast(const uint32_t behaviorId, const LWOOBJID target) { auto* context = new BehaviorContext(target); context->caster = target; @@ -510,25 +465,22 @@ void SkillComponent::HandleUnCast(const uint32_t behaviorId, const LWOOBJID targ delete context; } -SkillComponent::SkillComponent(Entity* parent) : Component(parent) -{ +SkillComponent::SkillComponent(Entity* parent) : Component(parent) { this->m_skillUid = 0; } -SkillComponent::~SkillComponent() -{ +SkillComponent::~SkillComponent() { Reset(); } void SkillComponent::Serialize(RakNet::BitStream* outBitStream, bool bIsInitialUpdate, unsigned int& flags) { - if (bIsInitialUpdate) outBitStream->Write0(); + if (bIsInitialUpdate) outBitStream->Write0(); } /// /// Get a unique skill ID for syncing behaviors to the client /// /// Unique skill ID -uint32_t SkillComponent::GetUniqueSkillId() -{ +uint32_t SkillComponent::GetUniqueSkillId() { return ++this->m_skillUid; } diff --git a/dGame/dComponents/SkillComponent.h b/dGame/dComponents/SkillComponent.h index ad2449c3..f43276f1 100644 --- a/dGame/dComponents/SkillComponent.h +++ b/dGame/dComponents/SkillComponent.h @@ -15,186 +15,186 @@ #include "dLogger.h" struct ProjectileSyncEntry { - LWOOBJID id = LWOOBJID_EMPTY; + LWOOBJID id = LWOOBJID_EMPTY; - bool calculation = false; + bool calculation = false; - mutable float time = 0; + mutable float time = 0; - float maxTime = 0; + float maxTime = 0; - NiPoint3 startPosition{}; + NiPoint3 startPosition{}; - NiPoint3 lastPosition{}; + NiPoint3 lastPosition{}; - NiPoint3 velocity{}; + NiPoint3 velocity{}; - bool trackTarget = false; + bool trackTarget = false; - float trackRadius = 0; + float trackRadius = 0; - BehaviorContext* context = nullptr; + BehaviorContext* context = nullptr; - LOT lot = LOT_NULL; + LOT lot = LOT_NULL; - BehaviorBranchContext branchContext{0, 0}; + BehaviorBranchContext branchContext{ 0, 0 }; - explicit ProjectileSyncEntry(); + explicit ProjectileSyncEntry(); }; struct SkillExecutionResult { - bool success; + bool success; - float skillTime; + float skillTime; }; /** * The SkillComponent of an entity. This manages both player and AI skills, such as attacks and consumables. * There are two sets of skill methods: one for player skills and one for server-side calculations. - * + * * Skills are a built up by a tree of behaviors. See dGame/dBehaviors/ for a list of behaviors. - * + * * This system is very conveluted and still has a lot of unknowns. */ class SkillComponent : public Component { public: - static const uint32_t ComponentType = COMPONENT_TYPE_SKILL; + static const uint32_t ComponentType = COMPONENT_TYPE_SKILL; - explicit SkillComponent(Entity* parent); - ~SkillComponent() override; + explicit SkillComponent(Entity* parent); + ~SkillComponent() override; - static void Serialize(RakNet::BitStream* outBitStream, bool bIsInitialUpdate, unsigned int& flags); + static void Serialize(RakNet::BitStream* outBitStream, bool bIsInitialUpdate, unsigned int& flags); - /** - * Computes skill updates. Invokes CalculateUpdate. - */ - void Update(float deltaTime) override; + /** + * Computes skill updates. Invokes CalculateUpdate. + */ + void Update(float deltaTime) override; - /** - * Computes server-side skill updates. - */ - void CalculateUpdate(float deltaTime); + /** + * Computes server-side skill updates. + */ + void CalculateUpdate(float deltaTime); - /** - * Resets all skills, projectiles, and other calculations. - */ - void Reset(); + /** + * Resets all skills, projectiles, and other calculations. + */ + void Reset(); - /** - * Interrupts active skills. - */ - void Interrupt(); + /** + * Interrupts active skills. + */ + void Interrupt(); - /** - * Starts a player skill. Should only be called when the server receives a start skill message from the client. - * @param behaviorId the root behavior ID of the skill - * @param skillUid the unique ID of the skill given by the client - * @param bitStream the bitSteam given by the client to determine the behavior path - * @param target the explicit target of the skill - */ - bool CastPlayerSkill(uint32_t behaviorId, uint32_t skillUid, RakNet::BitStream* bitStream, LWOOBJID target, uint32_t skillID = 0); + /** + * Starts a player skill. Should only be called when the server receives a start skill message from the client. + * @param behaviorId the root behavior ID of the skill + * @param skillUid the unique ID of the skill given by the client + * @param bitStream the bitSteam given by the client to determine the behavior path + * @param target the explicit target of the skill + */ + bool CastPlayerSkill(uint32_t behaviorId, uint32_t skillUid, RakNet::BitStream* bitStream, LWOOBJID target, uint32_t skillID = 0); - /** - * Continues a player skill. Should only be called when the server receives a sync message from the client. - * @param skillUid the unique ID of the skill given by the client - * @param syncId the unique sync ID of the skill given by the client - * @param bitStream the bitSteam given by the client to determine the behavior path - */ - void SyncPlayerSkill(uint32_t skillUid, uint32_t syncId, RakNet::BitStream* bitStream); - - /** - * Continues a player projectile calculation. Should only be called when the server receives a projectile sync message from the client. - * @param projectileId the unique ID of the projectile given by the client - * @param bitStream the bitSteam given by the client to determine the behavior path - * @param target the explicit target of the target - */ - void SyncPlayerProjectile(LWOOBJID projectileId, RakNet::BitStream* bitStream, LWOOBJID target); + /** + * Continues a player skill. Should only be called when the server receives a sync message from the client. + * @param skillUid the unique ID of the skill given by the client + * @param syncId the unique sync ID of the skill given by the client + * @param bitStream the bitSteam given by the client to determine the behavior path + */ + void SyncPlayerSkill(uint32_t skillUid, uint32_t syncId, RakNet::BitStream* bitStream); - /** - * Registers a player projectile. Should only be called when the server is computing a player projectile. - * @param projectileId the unique ID of the projectile given by the client - * @param context the current behavior context of the active skill - * @param branch the current behavior branch context of the active skill - * @param lot the LOT of the projectile - */ - void RegisterPlayerProjectile(LWOOBJID projectileId, BehaviorContext* context, const BehaviorBranchContext& branch, LOT lot); + /** + * Continues a player projectile calculation. Should only be called when the server receives a projectile sync message from the client. + * @param projectileId the unique ID of the projectile given by the client + * @param bitStream the bitSteam given by the client to determine the behavior path + * @param target the explicit target of the target + */ + void SyncPlayerProjectile(LWOOBJID projectileId, RakNet::BitStream* bitStream, LWOOBJID target); - /** - * Initializes a server-side skill calculation. - * @param skillId the skill ID - * @param behaviorId the root behavior ID of the skill - * @param target the explicit target of the skill - * @param ignoreTarget continue the skill calculation even if the target is invalid or no target is found - * @param clientInitalized indicates if the skill calculation was initiated by a client skill, ignores some checks - * @param originatorOverride an override for the originator of the skill calculation - * @return the result of the skill calculation - */ - SkillExecutionResult CalculateBehavior(uint32_t skillId, uint32_t behaviorId, LWOOBJID target, bool ignoreTarget = false, bool clientInitalized = false, LWOOBJID originatorOverride = LWOOBJID_EMPTY); + /** + * Registers a player projectile. Should only be called when the server is computing a player projectile. + * @param projectileId the unique ID of the projectile given by the client + * @param context the current behavior context of the active skill + * @param branch the current behavior branch context of the active skill + * @param lot the LOT of the projectile + */ + void RegisterPlayerProjectile(LWOOBJID projectileId, BehaviorContext* context, const BehaviorBranchContext& branch, LOT lot); - /** - * Register a server-side projectile. - * @param projectileId the unique ID of the projectile - * @param context the current behavior context of the active skill - * @param branch the current behavior branch context of the active skill - * @param lot the LOT of the projectile - * @param maxTime the maximum travel time of the projectile - * @param startPosition the start position of the projectile - * @param velocity the velocity of the projectile - * @param trackTarget whether the projectile should track the target - * @param trackRadius the radius of the tracking circle - */ - void RegisterCalculatedProjectile( - LWOOBJID projectileId, - BehaviorContext* context, - const BehaviorBranchContext& branch, - LOT lot, - const float maxTime, - const NiPoint3& startPosition, - const NiPoint3& velocity, - bool trackTarget, - float TrackRadius); + /** + * Initializes a server-side skill calculation. + * @param skillId the skill ID + * @param behaviorId the root behavior ID of the skill + * @param target the explicit target of the skill + * @param ignoreTarget continue the skill calculation even if the target is invalid or no target is found + * @param clientInitalized indicates if the skill calculation was initiated by a client skill, ignores some checks + * @param originatorOverride an override for the originator of the skill calculation + * @return the result of the skill calculation + */ + SkillExecutionResult CalculateBehavior(uint32_t skillId, uint32_t behaviorId, LWOOBJID target, bool ignoreTarget = false, bool clientInitalized = false, LWOOBJID originatorOverride = LWOOBJID_EMPTY); - /** - * Computes a server-side skill calculation without an associated entity. - * @param behaviorId the root behavior ID of the skill - * @param target the explicit target of the skill - * @param source the explicit source of the skill - */ - static void HandleUnmanaged(uint32_t behaviorId, LWOOBJID target, LWOOBJID source = LWOOBJID_EMPTY); + /** + * Register a server-side projectile. + * @param projectileId the unique ID of the projectile + * @param context the current behavior context of the active skill + * @param branch the current behavior branch context of the active skill + * @param lot the LOT of the projectile + * @param maxTime the maximum travel time of the projectile + * @param startPosition the start position of the projectile + * @param velocity the velocity of the projectile + * @param trackTarget whether the projectile should track the target + * @param trackRadius the radius of the tracking circle + */ + void RegisterCalculatedProjectile( + LWOOBJID projectileId, + BehaviorContext* context, + const BehaviorBranchContext& branch, + LOT lot, + const float maxTime, + const NiPoint3& startPosition, + const NiPoint3& velocity, + bool trackTarget, + float TrackRadius); - /** - * Computes a server-side skill uncast calculation without an associated entity. - * @param behaviorId the root behavior ID of the skill - * @param target the explicit target of the skill - */ - static void HandleUnCast(uint32_t behaviorId, LWOOBJID target); + /** + * Computes a server-side skill calculation without an associated entity. + * @param behaviorId the root behavior ID of the skill + * @param target the explicit target of the skill + * @param source the explicit source of the skill + */ + static void HandleUnmanaged(uint32_t behaviorId, LWOOBJID target, LWOOBJID source = LWOOBJID_EMPTY); - /** - * @returns a unique ID for the next skill calculation - */ - uint32_t GetUniqueSkillId(); + /** + * Computes a server-side skill uncast calculation without an associated entity. + * @param behaviorId the root behavior ID of the skill + * @param target the explicit target of the skill + */ + static void HandleUnCast(uint32_t behaviorId, LWOOBJID target); + + /** + * @returns a unique ID for the next skill calculation + */ + uint32_t GetUniqueSkillId(); private: - /** - * All of the active skills mapped by their unique ID. - */ - std::map m_managedBehaviors; + /** + * All of the active skills mapped by their unique ID. + */ + std::map m_managedBehaviors; - /** - * All active projectiles. - */ - std::vector m_managedProjectiles; + /** + * All active projectiles. + */ + std::vector m_managedProjectiles; - /** - * Unique ID counter. - */ - uint32_t m_skillUid; + /** + * Unique ID counter. + */ + uint32_t m_skillUid; - /** - * Sync a server-side projectile calculation. - * @param entry the projectile information - */ - void SyncProjectileCalculation(const ProjectileSyncEntry& entry) const; + /** + * Sync a server-side projectile calculation. + * @param entry the projectile information + */ + void SyncProjectileCalculation(const ProjectileSyncEntry& entry) const; }; #endif // SKILLCOMPONENT_H diff --git a/dGame/dComponents/SoundTriggerComponent.cpp b/dGame/dComponents/SoundTriggerComponent.cpp index 9714eca7..be62beee 100644 --- a/dGame/dComponents/SoundTriggerComponent.cpp +++ b/dGame/dComponents/SoundTriggerComponent.cpp @@ -3,91 +3,91 @@ #include "Game.h" SoundTriggerComponent::SoundTriggerComponent(Entity* parent) : Component(parent) { - const auto musicCueName = parent->GetVar(u"NDAudioMusicCue_Name"); - const auto musicCueBoredomTime = parent->GetVar(u"NDAudioMusicCue_BoredomTime"); + const auto musicCueName = parent->GetVar(u"NDAudioMusicCue_Name"); + const auto musicCueBoredomTime = parent->GetVar(u"NDAudioMusicCue_BoredomTime"); - this->musicCues.push_back({ - musicCueName, - 1, - musicCueBoredomTime - }); + this->musicCues.push_back({ + musicCueName, + 1, + musicCueBoredomTime + }); - const auto mixerName = parent->GetVar(u"NDAudioMixerProgram_Name"); - this->mixerPrograms.push_back(mixerName); + const auto mixerName = parent->GetVar(u"NDAudioMixerProgram_Name"); + this->mixerPrograms.push_back(mixerName); - const auto guid2String = parent->GetVar(u"NDAudioEventGUID2"); - if (!guid2String.empty()) { - this->guids.emplace_back(guid2String); - } + const auto guid2String = parent->GetVar(u"NDAudioEventGUID2"); + if (!guid2String.empty()) { + this->guids.emplace_back(guid2String); + } } SoundTriggerComponent::~SoundTriggerComponent() = default; -void SoundTriggerComponent::Serialize(RakNet::BitStream *outBitStream, bool bIsInitialUpdate, unsigned int &flags) { - if (bIsInitialUpdate) - dirty = true; +void SoundTriggerComponent::Serialize(RakNet::BitStream* outBitStream, bool bIsInitialUpdate, unsigned int& flags) { + if (bIsInitialUpdate) + dirty = true; - outBitStream->Write(dirty); + outBitStream->Write(dirty); - if (dirty) { - outBitStream->Write(this->musicCues.size()); - for (const auto& musicCue : this->musicCues) { - outBitStream->Write(musicCue.name.size()); - outBitStream->Write(musicCue.name.c_str(), musicCue.name.size()); - outBitStream->Write(musicCue.result); - outBitStream->Write(musicCue.boredomTime); - } + if (dirty) { + outBitStream->Write(this->musicCues.size()); + for (const auto& musicCue : this->musicCues) { + outBitStream->Write(musicCue.name.size()); + outBitStream->Write(musicCue.name.c_str(), musicCue.name.size()); + outBitStream->Write(musicCue.result); + outBitStream->Write(musicCue.boredomTime); + } - // Unknown part - outBitStream->Write(0); + // Unknown part + outBitStream->Write(0); - // GUID part - outBitStream->Write(this->guids.size()); + // GUID part + outBitStream->Write(this->guids.size()); - for (const auto guid : this->guids) { - outBitStream->Write(guid.GetData1()); - outBitStream->Write(guid.GetData2()); - outBitStream->Write(guid.GetData3()); - for (const auto& guidSubPart : guid.GetData4()) { - outBitStream->Write(guidSubPart); - } - outBitStream->Write(1); // Unknown - } + for (const auto guid : this->guids) { + outBitStream->Write(guid.GetData1()); + outBitStream->Write(guid.GetData2()); + outBitStream->Write(guid.GetData3()); + for (const auto& guidSubPart : guid.GetData4()) { + outBitStream->Write(guidSubPart); + } + outBitStream->Write(1); // Unknown + } - // Mixer program part - outBitStream->Write(this->mixerPrograms.size()); - for (const auto& mixerProgram : mixerPrograms) { - outBitStream->Write(mixerProgram.size()); - outBitStream->Write(mixerProgram.c_str(), mixerProgram.size()); - outBitStream->Write(1); // Unknown - } + // Mixer program part + outBitStream->Write(this->mixerPrograms.size()); + for (const auto& mixerProgram : mixerPrograms) { + outBitStream->Write(mixerProgram.size()); + outBitStream->Write(mixerProgram.c_str(), mixerProgram.size()); + outBitStream->Write(1); // Unknown + } - dirty = false; - } + dirty = false; + } } void SoundTriggerComponent::ActivateMusicCue(const std::string& name) { - if (std::find_if(this->musicCues.begin(), this->musicCues.end(), [name](const MusicCue& musicCue) { - return musicCue.name == name; - }) == this->musicCues.end()) { - this->musicCues.push_back({ - name, - 1, - -1.0f - }); - dirty = true; - EntityManager::Instance()->SerializeEntity(m_Parent); - } + if (std::find_if(this->musicCues.begin(), this->musicCues.end(), [name](const MusicCue& musicCue) { + return musicCue.name == name; + }) == this->musicCues.end()) { + this->musicCues.push_back({ + name, + 1, + -1.0f + }); + dirty = true; + EntityManager::Instance()->SerializeEntity(m_Parent); + } } void SoundTriggerComponent::DeactivateMusicCue(const std::string& name) { - const auto musicCue = std::find_if(this->musicCues.begin(), this->musicCues.end(), [name](const MusicCue& musicCue) { - return musicCue.name == name; - }); + const auto musicCue = std::find_if(this->musicCues.begin(), this->musicCues.end(), [name](const MusicCue& musicCue) { + return musicCue.name == name; + }); - if (musicCue != this->musicCues.end()) { - this->musicCues.erase(musicCue); - dirty = true; - EntityManager::Instance()->SerializeEntity(m_Parent); - } + if (musicCue != this->musicCues.end()) { + this->musicCues.erase(musicCue); + dirty = true; + EntityManager::Instance()->SerializeEntity(m_Parent); + } } diff --git a/dGame/dComponents/SoundTriggerComponent.h b/dGame/dComponents/SoundTriggerComponent.h index 6f16a0dd..e1178150 100644 --- a/dGame/dComponents/SoundTriggerComponent.h +++ b/dGame/dComponents/SoundTriggerComponent.h @@ -8,9 +8,9 @@ * Music that should be played by the client */ struct MusicCue { - std::string name; - uint32_t result; - float boredomTime; + std::string name; + uint32_t result; + float boredomTime; }; /** @@ -19,40 +19,40 @@ struct MusicCue { */ class SoundTriggerComponent : public Component { public: - static const uint32_t ComponentType = COMPONENT_TYPE_SOUND_TRIGGER; + static const uint32_t ComponentType = COMPONENT_TYPE_SOUND_TRIGGER; - explicit SoundTriggerComponent(Entity* parent); - ~SoundTriggerComponent() override; + explicit SoundTriggerComponent(Entity* parent); + ~SoundTriggerComponent() override; - void Serialize(RakNet::BitStream* outBitStream, bool bIsInitialUpdate, unsigned int& flags); + void Serialize(RakNet::BitStream* outBitStream, bool bIsInitialUpdate, unsigned int& flags); - /** - * Activates a music cue, making it played by any client in range - * @param name the name of the music to play - */ - void ActivateMusicCue(const std::string& name); + /** + * Activates a music cue, making it played by any client in range + * @param name the name of the music to play + */ + void ActivateMusicCue(const std::string& name); - /** - * Deactivates a music cue (if active) - * @param name name of the music to deactivate - */ - void DeactivateMusicCue(const std::string& name); + /** + * Deactivates a music cue (if active) + * @param name name of the music to deactivate + */ + void DeactivateMusicCue(const std::string& name); private: - /** - * Currently active cues - */ - std::vector musicCues = {}; + /** + * Currently active cues + */ + std::vector musicCues = {}; - /** - * Currently active mixer programs - */ - std::vector mixerPrograms = {}; + /** + * Currently active mixer programs + */ + std::vector mixerPrograms = {}; - /** - * GUID found in the LDF - */ - std::vector guids = {}; - bool dirty = false; + /** + * GUID found in the LDF + */ + std::vector guids = {}; + bool dirty = false; }; diff --git a/dGame/dComponents/SwitchComponent.cpp b/dGame/dComponents/SwitchComponent.cpp index fb694e30..2263a866 100644 --- a/dGame/dComponents/SwitchComponent.cpp +++ b/dGame/dComponents/SwitchComponent.cpp @@ -7,15 +7,14 @@ SwitchComponent::SwitchComponent(Entity* parent) : Component(parent) { m_Active = false; m_ResetTime = m_Parent->GetVarAs(u"switch_reset_time"); - + m_Rebuild = m_Parent->GetComponent(); } SwitchComponent::~SwitchComponent() { const auto& iterator = std::find(petSwitches.begin(), petSwitches.end(), this); - if (iterator != petSwitches.end()) - { + if (iterator != petSwitches.end()) { petSwitches.erase(iterator); } } @@ -27,14 +26,12 @@ void SwitchComponent::Serialize(RakNet::BitStream* outBitStream, bool bIsInitial void SwitchComponent::SetActive(bool active) { m_Active = active; - if (m_PetBouncer != nullptr) - { + if (m_PetBouncer != nullptr) { m_PetBouncer->SetPetBouncerEnabled(active); } } -bool SwitchComponent::GetActive() const -{ +bool SwitchComponent::GetActive() const { return m_Active; } @@ -49,85 +46,71 @@ void SwitchComponent::EntityEnter(Entity* entity) { const auto grpName = m_Parent->GetVarAsString(u"grp_name"); - if (!grpName.empty()) - { + if (!grpName.empty()) { const auto entities = EntityManager::Instance()->GetEntitiesInGroup(grpName); - for (auto* entity : entities) - { + for (auto* entity : entities) { entity->OnFireEventServerSide(entity, "OnActivated"); } } m_Timer = m_ResetTime; - if (m_PetBouncer != nullptr) - { + if (m_PetBouncer != nullptr) { GameMessages::SendPlayFXEffect(m_Parent->GetObjectID(), 2602, u"pettriggeractive", "BounceEffect", LWOOBJID_EMPTY, 1, 1, true); GameMessages::SendPlayAnimation(m_Parent, u"engaged", 0, 1); m_PetBouncer->SetPetBouncerEnabled(true); - } - else - { + } else { EntityManager::Instance()->SerializeEntity(m_Parent); } - + } } void SwitchComponent::EntityLeave(Entity* entity) { - + } void SwitchComponent::Update(float deltaTime) { if (m_Active) { m_Timer -= deltaTime; - + if (m_Timer <= 0.0f) { m_Active = false; if (!m_Parent) return; m_Parent->TriggerEvent("OnDectivated"); - + const auto grpName = m_Parent->GetVarAsString(u"grp_name"); - if (!grpName.empty()) - { + if (!grpName.empty()) { const auto entities = EntityManager::Instance()->GetEntitiesInGroup(grpName); - for (auto* entity : entities) - { + for (auto* entity : entities) { entity->OnFireEventServerSide(entity, "OnDectivated"); } } - if (m_PetBouncer != nullptr) - { + if (m_PetBouncer != nullptr) { m_PetBouncer->SetPetBouncerEnabled(false); - } - else - { + } else { EntityManager::Instance()->SerializeEntity(m_Parent); } } } } -Entity* SwitchComponent::GetParentEntity() const -{ +Entity* SwitchComponent::GetParentEntity() const { return m_Parent; } -SwitchComponent* SwitchComponent::GetClosestSwitch(NiPoint3 position) -{ +SwitchComponent* SwitchComponent::GetClosestSwitch(NiPoint3 position) { float closestDistance = 0; SwitchComponent* closest = nullptr; - for (SwitchComponent* petSwitch : petSwitches) - { + for (SwitchComponent* petSwitch : petSwitches) { float distance = Vector3::DistanceSquared(petSwitch->m_Parent->GetPosition(), position); - - if (closest == nullptr || distance < closestDistance) - { + + if (closest == nullptr || distance < closestDistance) { closestDistance = distance; closest = petSwitch; } @@ -137,18 +120,15 @@ SwitchComponent* SwitchComponent::GetClosestSwitch(NiPoint3 position) } -void SwitchComponent::SetPetBouncer(BouncerComponent* value) -{ +void SwitchComponent::SetPetBouncer(BouncerComponent* value) { m_PetBouncer = value; - - if (value != nullptr) - { + + if (value != nullptr) { m_PetBouncer->SetPetEnabled(true); petSwitches.push_back(this); } } -BouncerComponent* SwitchComponent::GetPetBouncer() const -{ +BouncerComponent* SwitchComponent::GetPetBouncer() const { return m_PetBouncer; } diff --git a/dGame/dComponents/SwitchComponent.h b/dGame/dComponents/SwitchComponent.h index c7ff04c2..ea5955d8 100644 --- a/dGame/dComponents/SwitchComponent.h +++ b/dGame/dComponents/SwitchComponent.h @@ -16,12 +16,12 @@ class SwitchComponent : public Component { public: static const uint32_t ComponentType = COMPONENT_TYPE_SWITCH; - + SwitchComponent(Entity* parent); ~SwitchComponent() override; void Update(float deltaTime) override; - + Entity* GetParentEntity() const; void Serialize(RakNet::BitStream* outBitStream, bool bIsInitialUpdate, unsigned int& flags); diff --git a/dGame/dComponents/VehiclePhysicsComponent.cpp b/dGame/dComponents/VehiclePhysicsComponent.cpp index dc6dcf1a..bf6a3bb7 100644 --- a/dGame/dComponents/VehiclePhysicsComponent.cpp +++ b/dGame/dComponents/VehiclePhysicsComponent.cpp @@ -1,8 +1,7 @@ #include "VehiclePhysicsComponent.h" #include "EntityManager.h" -VehiclePhysicsComponent::VehiclePhysicsComponent(Entity* parent) : Component(parent) -{ +VehiclePhysicsComponent::VehiclePhysicsComponent(Entity* parent) : Component(parent) { m_Position = NiPoint3::ZERO; m_Rotation = NiQuaternion::IDENTITY; m_Velocity = NiPoint3::ZERO; @@ -14,119 +13,99 @@ VehiclePhysicsComponent::VehiclePhysicsComponent(Entity* parent) : Component(par m_DirtyAngularVelocity = true; } -VehiclePhysicsComponent::~VehiclePhysicsComponent() -{ - +VehiclePhysicsComponent::~VehiclePhysicsComponent() { + } -void VehiclePhysicsComponent::SetPosition(const NiPoint3& pos) -{ - m_Position = pos; +void VehiclePhysicsComponent::SetPosition(const NiPoint3& pos) { + m_Position = pos; } -void VehiclePhysicsComponent::SetRotation(const NiQuaternion& rot) -{ +void VehiclePhysicsComponent::SetRotation(const NiQuaternion& rot) { m_DirtyPosition = true; - m_Rotation = rot; + m_Rotation = rot; } -void VehiclePhysicsComponent::SetVelocity(const NiPoint3& vel) -{ +void VehiclePhysicsComponent::SetVelocity(const NiPoint3& vel) { m_DirtyPosition = true; - m_Velocity = vel; + m_Velocity = vel; } -void VehiclePhysicsComponent::SetAngularVelocity(const NiPoint3& vel) -{ +void VehiclePhysicsComponent::SetAngularVelocity(const NiPoint3& vel) { m_DirtyPosition = true; - m_AngularVelocity = vel; + m_AngularVelocity = vel; } -void VehiclePhysicsComponent::SetIsOnGround(bool val) -{ +void VehiclePhysicsComponent::SetIsOnGround(bool val) { m_DirtyPosition = true; - m_IsOnGround = val; + m_IsOnGround = val; } -void VehiclePhysicsComponent::SetIsOnRail(bool val) -{ +void VehiclePhysicsComponent::SetIsOnRail(bool val) { m_DirtyPosition = true; - m_IsOnRail = val; + m_IsOnRail = val; } -void VehiclePhysicsComponent::SetDirtyPosition(bool val) -{ - m_DirtyPosition = val; +void VehiclePhysicsComponent::SetDirtyPosition(bool val) { + m_DirtyPosition = val; } -void VehiclePhysicsComponent::SetDirtyVelocity(bool val) -{ - m_DirtyVelocity = val; +void VehiclePhysicsComponent::SetDirtyVelocity(bool val) { + m_DirtyVelocity = val; } -void VehiclePhysicsComponent::SetDirtyAngularVelocity(bool val) -{ - m_DirtyAngularVelocity = val; +void VehiclePhysicsComponent::SetDirtyAngularVelocity(bool val) { + m_DirtyAngularVelocity = val; } -void VehiclePhysicsComponent::Serialize(RakNet::BitStream* outBitStream, bool bIsInitialUpdate, unsigned int& flags) -{ - outBitStream->Write(bIsInitialUpdate || m_DirtyPosition); +void VehiclePhysicsComponent::Serialize(RakNet::BitStream* outBitStream, bool bIsInitialUpdate, unsigned int& flags) { + outBitStream->Write(bIsInitialUpdate || m_DirtyPosition); - if (bIsInitialUpdate || m_DirtyPosition) - { - outBitStream->Write(m_Position); - - outBitStream->Write(m_Rotation); + if (bIsInitialUpdate || m_DirtyPosition) { + outBitStream->Write(m_Position); - outBitStream->Write(m_IsOnGround); - outBitStream->Write(m_IsOnRail); + outBitStream->Write(m_Rotation); - outBitStream->Write(bIsInitialUpdate || m_DirtyVelocity); + outBitStream->Write(m_IsOnGround); + outBitStream->Write(m_IsOnRail); - if (bIsInitialUpdate || m_DirtyVelocity) - { - outBitStream->Write(m_Velocity); - } + outBitStream->Write(bIsInitialUpdate || m_DirtyVelocity); - outBitStream->Write(bIsInitialUpdate || m_DirtyAngularVelocity); + if (bIsInitialUpdate || m_DirtyVelocity) { + outBitStream->Write(m_Velocity); + } - if (bIsInitialUpdate || m_DirtyAngularVelocity) - { - outBitStream->Write(m_AngularVelocity); - } + outBitStream->Write(bIsInitialUpdate || m_DirtyAngularVelocity); - outBitStream->Write0(); + if (bIsInitialUpdate || m_DirtyAngularVelocity) { + outBitStream->Write(m_AngularVelocity); + } + + outBitStream->Write0(); outBitStream->Write0(); outBitStream->Write(0.0f); - if (!bIsInitialUpdate) - { - outBitStream->Write0(); - } - } + if (!bIsInitialUpdate) { + outBitStream->Write0(); + } + } - if (bIsInitialUpdate) - { - outBitStream->Write(5); - outBitStream->Write1(); - } + if (bIsInitialUpdate) { + outBitStream->Write(5); + outBitStream->Write1(); + } - outBitStream->Write0(); + outBitStream->Write0(); } -void VehiclePhysicsComponent::Update(float deltaTime) -{ - if (m_SoftUpdate > 5) - { - EntityManager::Instance()->SerializeEntity(m_Parent); +void VehiclePhysicsComponent::Update(float deltaTime) { + if (m_SoftUpdate > 5) { + EntityManager::Instance()->SerializeEntity(m_Parent); - m_SoftUpdate = 0; - } - else - { - m_SoftUpdate += deltaTime; - } + m_SoftUpdate = 0; + } else { + m_SoftUpdate += deltaTime; + } } diff --git a/dGame/dComponents/VehiclePhysicsComponent.h b/dGame/dComponents/VehiclePhysicsComponent.h index de2e6b82..f5ab1917 100644 --- a/dGame/dComponents/VehiclePhysicsComponent.h +++ b/dGame/dComponents/VehiclePhysicsComponent.h @@ -10,102 +10,102 @@ class VehiclePhysicsComponent : public Component { public: static const uint32_t ComponentType = COMPONENT_TYPE_VEHICLE_PHYSICS; - + VehiclePhysicsComponent(Entity* parentEntity); ~VehiclePhysicsComponent() override; void Serialize(RakNet::BitStream* outBitStream, bool bIsInitialUpdate, unsigned int& flags); - void Update(float deltaTime) override; - - /** - * Sets the position - * @param pos the new position - */ - void SetPosition(const NiPoint3& pos); - - /** - * Gets the position - * @return the position - */ - const NiPoint3& GetPosition() const { return m_Position; } - - /** - * Sets the rotation - * @param rot the new rotation - */ - void SetRotation(const NiQuaternion& rot); + void Update(float deltaTime) override; - /** - * Gets the rotation - * @return the rotation - */ - const NiQuaternion& GetRotation() const { return m_Rotation; } + /** + * Sets the position + * @param pos the new position + */ + void SetPosition(const NiPoint3& pos); - /** - * Sets the velocity - * @param vel the new velocity - */ - void SetVelocity(const NiPoint3& vel); + /** + * Gets the position + * @return the position + */ + const NiPoint3& GetPosition() const { return m_Position; } - /** - * Gets the velocity - * @return the velocity - */ - const NiPoint3& GetVelocity() const { return m_Velocity; } + /** + * Sets the rotation + * @param rot the new rotation + */ + void SetRotation(const NiQuaternion& rot); - /** - * Sets the angular velocity - * @param vel the new angular velocity - */ - void SetAngularVelocity(const NiPoint3& vel); + /** + * Gets the rotation + * @return the rotation + */ + const NiQuaternion& GetRotation() const { return m_Rotation; } - /** - * Gets the angular velocity - * @return the angular velocity - */ - const NiPoint3& GetAngularVelocity() const { return m_AngularVelocity; } + /** + * Sets the velocity + * @param vel the new velocity + */ + void SetVelocity(const NiPoint3& vel); - /** - * Sets whether the vehicle is on the ground - * @param val whether the vehicle is on the ground - */ - void SetIsOnGround(bool val); + /** + * Gets the velocity + * @return the velocity + */ + const NiPoint3& GetVelocity() const { return m_Velocity; } - /** - * Gets whether the vehicle is on the ground - * @return whether the vehicle is on the ground - */ - const bool GetIsOnGround() const { return m_IsOnGround; } + /** + * Sets the angular velocity + * @param vel the new angular velocity + */ + void SetAngularVelocity(const NiPoint3& vel); - /** - * Gets whether the vehicle is on rail - * @return whether the vehicle is on rail - */ - void SetIsOnRail(bool val); + /** + * Gets the angular velocity + * @return the angular velocity + */ + const NiPoint3& GetAngularVelocity() const { return m_AngularVelocity; } - /** - * Gets whether the vehicle is on rail - * @return whether the vehicle is on rail - */ - const bool GetIsOnRail() const { return m_IsOnRail; } + /** + * Sets whether the vehicle is on the ground + * @param val whether the vehicle is on the ground + */ + void SetIsOnGround(bool val); - void SetDirtyPosition(bool val); - void SetDirtyVelocity(bool val); - void SetDirtyAngularVelocity(bool val); + /** + * Gets whether the vehicle is on the ground + * @return whether the vehicle is on the ground + */ + const bool GetIsOnGround() const { return m_IsOnGround; } + + /** + * Gets whether the vehicle is on rail + * @return whether the vehicle is on rail + */ + void SetIsOnRail(bool val); + + /** + * Gets whether the vehicle is on rail + * @return whether the vehicle is on rail + */ + const bool GetIsOnRail() const { return m_IsOnRail; } + + void SetDirtyPosition(bool val); + void SetDirtyVelocity(bool val); + void SetDirtyAngularVelocity(bool val); private: - bool m_DirtyPosition; - NiPoint3 m_Position; - NiQuaternion m_Rotation; - - bool m_DirtyVelocity; - NiPoint3 m_Velocity; - - bool m_DirtyAngularVelocity; - NiPoint3 m_AngularVelocity; - bool m_IsOnGround; - bool m_IsOnRail; + bool m_DirtyPosition; + NiPoint3 m_Position; + NiQuaternion m_Rotation; - float m_SoftUpdate = 0; + bool m_DirtyVelocity; + NiPoint3 m_Velocity; + + bool m_DirtyAngularVelocity; + NiPoint3 m_AngularVelocity; + bool m_IsOnGround; + bool m_IsOnRail; + + float m_SoftUpdate = 0; }; diff --git a/dGame/dComponents/VendorComponent.cpp b/dGame/dComponents/VendorComponent.cpp index 6a8e7356..96dfb2c0 100644 --- a/dGame/dComponents/VendorComponent.cpp +++ b/dGame/dComponents/VendorComponent.cpp @@ -13,9 +13,9 @@ VendorComponent::VendorComponent(Entity* parent) : Component(parent) { VendorComponent::~VendorComponent() = default; void VendorComponent::Serialize(RakNet::BitStream* outBitStream, bool bIsInitialUpdate, unsigned int& flags) { - outBitStream->Write1(); + outBitStream->Write1(); outBitStream->Write1(); // Has standard items (Required for vendors with missions.) - outBitStream->Write(HasCraftingStation()); // Has multi use items + outBitStream->Write(HasCraftingStation()); // Has multi use items } void VendorComponent::OnUse(Entity* originator) { @@ -52,10 +52,10 @@ void VendorComponent::RefreshInventory(bool isCreation) { //Custom code for Max vanity NPC if (m_Parent->GetLOT() == 9749 && Game::server->GetZoneID() == 1201) { if (!isCreation) return; - m_Inventory.insert({11909, 0}); //Top hat w frog - m_Inventory.insert({7785, 0}); //Flash bulb - m_Inventory.insert({12764, 0}); //Big fountain soda - m_Inventory.insert({12241, 0}); //Hot cocoa (from fb) + m_Inventory.insert({ 11909, 0 }); //Top hat w frog + m_Inventory.insert({ 7785, 0 }); //Flash bulb + m_Inventory.insert({ 12764, 0 }); //Big fountain soda + m_Inventory.insert({ 12241, 0 }); //Hot cocoa (from fb) return; } m_Inventory.clear(); @@ -72,7 +72,7 @@ void VendorComponent::RefreshInventory(bool isCreation) { std::vector vendorItems = lootTableTable->Query([=](CDLootTable entry) { return (entry.LootTableIndex == lootTableID); }); if (lootMatrix.maxToDrop == 0 || lootMatrix.minToDrop == 0) { for (CDLootTable item : vendorItems) { - m_Inventory.insert({item.itemid, item.sortPriority}); + m_Inventory.insert({ item.itemid, item.sortPriority }); } } else { auto randomCount = GeneralUtils::GenerateRandomNumber(lootMatrix.minToDrop, lootMatrix.maxToDrop); @@ -86,7 +86,7 @@ void VendorComponent::RefreshInventory(bool isCreation) { vendorItems.erase(vendorItems.begin() + randomItemIndex); - m_Inventory.insert({randomItem.itemid, randomItem.sortPriority}); + m_Inventory.insert({ randomItem.itemid, randomItem.sortPriority }); } } } @@ -96,24 +96,24 @@ void VendorComponent::RefreshInventory(bool isCreation) { auto randomCamera = GeneralUtils::GenerateRandomNumber(0, 2); switch (randomCamera) { - case 0: - m_Inventory.insert({16253, 0}); //Grungagroid - break; - case 1: - m_Inventory.insert({16254, 0}); //Hipstabrick - break; - case 2: - m_Inventory.insert({16204, 0}); //Megabrixel snapshot - break; - default: - break; + case 0: + m_Inventory.insert({ 16253, 0 }); //Grungagroid + break; + case 1: + m_Inventory.insert({ 16254, 0 }); //Hipstabrick + break; + case 2: + m_Inventory.insert({ 16204, 0 }); //Megabrixel snapshot + break; + default: + break; } } // Callback timer to refresh this inventory. m_Parent->AddCallbackTimer(m_RefreshTimeSeconds, [this]() { RefreshInventory(); - }); + }); GameMessages::SendVendorStatusUpdate(m_Parent, UNASSIGNED_SYSTEM_ADDRESS); } @@ -128,4 +128,4 @@ void VendorComponent::SetupConstants() { m_SellScalar = vendorComps[0].sellScalar; m_RefreshTimeSeconds = vendorComps[0].refreshTimeSeconds; m_LootMatrixID = vendorComps[0].LootMatrixIndex; -} \ No newline at end of file +} diff --git a/dGame/dComponents/VendorComponent.h b/dGame/dComponents/VendorComponent.h index c037d875..72a5816d 100644 --- a/dGame/dComponents/VendorComponent.h +++ b/dGame/dComponents/VendorComponent.h @@ -14,43 +14,43 @@ class VendorComponent : public Component { public: static const uint32_t ComponentType = COMPONENT_TYPE_VENDOR; - + VendorComponent(Entity* parent); ~VendorComponent() override; void Serialize(RakNet::BitStream* outBitStream, bool bIsInitialUpdate, unsigned int& flags); - + void OnUse(Entity* originator) override; - + /** * Gets the buy scaler * @return the buy scaler */ float GetBuyScalar() const; - /** - * Sets the buy scalar. - * @param value the new value. - */ + /** + * Sets the buy scalar. + * @param value the new value. + */ void SetBuyScalar(float value); - + /** * Gets the buy scaler * @return the buy scaler */ float GetSellScalar() const; - /** - * Sets the sell scalar. - * @param value the new value. - */ + /** + * Sets the sell scalar. + * @param value the new value. + */ void SetSellScalar(float value); /** * True if the NPC LOT is 13800, the only NPC with a crafting station. */ bool HasCraftingStation(); - + /** * Gets the list if items the vendor sells. * @return the list of items. @@ -61,7 +61,7 @@ public: * Refresh the inventory of this vendor. */ void RefreshInventory(bool isCreation = false); - + /** * Called on startup of vendor to setup the variables for the component. */ diff --git a/dGame/dEntity/EntityCallbackTimer.cpp b/dGame/dEntity/EntityCallbackTimer.cpp index 48a0ab06..e07c1189 100644 --- a/dGame/dEntity/EntityCallbackTimer.cpp +++ b/dGame/dEntity/EntityCallbackTimer.cpp @@ -6,7 +6,7 @@ EntityCallbackTimer::EntityCallbackTimer(float time, std::function callb } EntityCallbackTimer::~EntityCallbackTimer() { - + } std::function EntityCallbackTimer::GetCallback() { diff --git a/dGame/dEntity/EntityCallbackTimer.h b/dGame/dEntity/EntityCallbackTimer.h index 63613dda..2a7e58f0 100644 --- a/dGame/dEntity/EntityCallbackTimer.h +++ b/dGame/dEntity/EntityCallbackTimer.h @@ -10,7 +10,7 @@ public: std::function GetCallback(); float GetTime(); - + void Update(float deltaTime); private: diff --git a/dGame/dEntity/EntityInfo.h b/dGame/dEntity/EntityInfo.h index 7e5fa5b5..049c5ce3 100644 --- a/dGame/dEntity/EntityInfo.h +++ b/dGame/dEntity/EntityInfo.h @@ -17,24 +17,24 @@ struct EntityInfo { spawnerNodeID = 0; id = 0; lot = LOT_NULL; - pos = {0,0,0}; - rot = {0,0,0,0}; + pos = { 0,0,0 }; + rot = { 0,0,0,0 }; settings = {}; networkSettings = {}; scale = 1.0f; } Spawner* spawner; - LWOOBJID spawnerID; - - bool hasSpawnerNodeID; - uint32_t spawnerNodeID; - - LWOOBJID id; - LOT lot; - NiPoint3 pos; - NiQuaternion rot; - std::vector settings; - std::vector networkSettings; + LWOOBJID spawnerID; + + bool hasSpawnerNodeID; + uint32_t spawnerNodeID; + + LWOOBJID id; + LOT lot; + NiPoint3 pos; + NiQuaternion rot; + std::vector settings; + std::vector networkSettings; float scale; }; diff --git a/dGame/dEntity/EntityTimer.cpp b/dGame/dEntity/EntityTimer.cpp index deff2d31..0363fc5b 100644 --- a/dGame/dEntity/EntityTimer.cpp +++ b/dGame/dEntity/EntityTimer.cpp @@ -6,7 +6,7 @@ EntityTimer::EntityTimer(std::string name, float time) { } EntityTimer::~EntityTimer() { - + } std::string EntityTimer::GetName() { @@ -19,4 +19,4 @@ float EntityTimer::GetTime() { void EntityTimer::Update(float deltaTime) { m_Time -= deltaTime; -} \ No newline at end of file +} diff --git a/dGame/dGameMessages/GameMessageHandler.cpp b/dGame/dGameMessages/GameMessageHandler.cpp index 9cd8995a..b9115e50 100644 --- a/dGame/dGameMessages/GameMessageHandler.cpp +++ b/dGame/dGameMessages/GameMessageHandler.cpp @@ -33,13 +33,12 @@ void GameMessageHandler::HandleMessage(RakNet::BitStream* inStream, const System CBITSTREAM - // Get the entity - Entity* entity = EntityManager::Instance()->GetEntity(objectID); + // Get the entity + Entity* entity = EntityManager::Instance()->GetEntity(objectID); - User * usr = UserManager::Instance()->GetUser(sysAddr); + User* usr = UserManager::Instance()->GetUser(sysAddr); - if (!entity) - { + if (!entity) { Game::logger->Log("GameMessageHandler", "Failed to find associated entity (%llu), aborting GM (%X)!", objectID, messageID); return; @@ -47,618 +46,615 @@ void GameMessageHandler::HandleMessage(RakNet::BitStream* inStream, const System switch (messageID) { - case GAME_MSG_PLAY_EMOTE: { - GameMessages::HandlePlayEmote(inStream, entity); - break; + case GAME_MSG_PLAY_EMOTE: { + GameMessages::HandlePlayEmote(inStream, entity); + break; + } + + case GAME_MSG_MOVE_ITEM_IN_INVENTORY: { + GameMessages::HandleMoveItemInInventory(inStream, entity); + break; + } + + case GAME_MSG_REMOVE_ITEM_FROM_INVENTORY: { + GameMessages::HandleRemoveItemFromInventory(inStream, entity, sysAddr); + break; + } + + case GAME_MSG_EQUIP_ITEM: + GameMessages::HandleEquipItem(inStream, entity); + break; + + case GAME_MSG_UN_EQUIP_ITEM: + GameMessages::HandleUnequipItem(inStream, entity); + break; + + case GAME_MSG_RESPOND_TO_MISSION: { + GameMessages::HandleRespondToMission(inStream, entity); + break; + } + + case GAME_MSG_REQUEST_USE: { + GameMessages::HandleRequestUse(inStream, entity, sysAddr); + break; + } + + case GAME_MSG_SET_FLAG: { + GameMessages::HandleSetFlag(inStream, entity); + break; + } + + case GAME_MSG_HAS_BEEN_COLLECTED: { + GameMessages::HandleHasBeenCollected(inStream, entity); + break; + } + + case GAME_MSG_PLAYER_LOADED: { + GameMessages::SendRestoreToPostLoadStats(entity, sysAddr); + entity->SetPlayerReadyForUpdates(); + + auto* player = dynamic_cast(entity); + if (player != nullptr) { + player->ConstructLimboEntities(); } - case GAME_MSG_MOVE_ITEM_IN_INVENTORY: { - GameMessages::HandleMoveItemInInventory(inStream, entity); - break; - } + InventoryComponent* inv = entity->GetComponent(); + if (inv) { + auto items = inv->GetEquippedItems(); + for (auto pair : items) { + const auto item = pair.second; - case GAME_MSG_REMOVE_ITEM_FROM_INVENTORY: { - GameMessages::HandleRemoveItemFromInventory(inStream, entity, sysAddr); - break; - } - - case GAME_MSG_EQUIP_ITEM: - GameMessages::HandleEquipItem(inStream, entity); - break; - - case GAME_MSG_UN_EQUIP_ITEM: - GameMessages::HandleUnequipItem(inStream, entity); - break; - - case GAME_MSG_RESPOND_TO_MISSION: { - GameMessages::HandleRespondToMission(inStream, entity); - break; - } - - case GAME_MSG_REQUEST_USE: { - GameMessages::HandleRequestUse(inStream, entity, sysAddr); - break; - } - - case GAME_MSG_SET_FLAG: { - GameMessages::HandleSetFlag(inStream, entity); - break; - } - - case GAME_MSG_HAS_BEEN_COLLECTED: { - GameMessages::HandleHasBeenCollected(inStream, entity); - break; - } - - case GAME_MSG_PLAYER_LOADED: { - GameMessages::SendRestoreToPostLoadStats(entity, sysAddr); - entity->SetPlayerReadyForUpdates(); - - auto* player = dynamic_cast(entity); - if (player != nullptr) - { - player->ConstructLimboEntities(); + inv->AddItemSkills(item.lot); } + } - InventoryComponent* inv = entity->GetComponent(); - if (inv) { - auto items = inv->GetEquippedItems(); - for (auto pair : items) { - const auto item = pair.second; + auto* destroyable = entity->GetComponent(); + destroyable->SetImagination(destroyable->GetImagination()); + EntityManager::Instance()->SerializeEntity(entity); - inv->AddItemSkills(item.lot); + std::vector racingControllers = EntityManager::Instance()->GetEntitiesByComponent(COMPONENT_TYPE_RACING_CONTROL); + for (Entity* racingController : racingControllers) { + auto* racingComponent = racingController->GetComponent(); + if (racingComponent != nullptr) { + racingComponent->OnPlayerLoaded(entity); + } + } + + Entity* zoneControl = EntityManager::Instance()->GetZoneControlEntity(); + for (CppScripts::Script* script : CppScripts::GetEntityScripts(zoneControl)) { + script->OnPlayerLoaded(zoneControl, player); + } + + std::vector scriptedActs = EntityManager::Instance()->GetEntitiesByComponent(COMPONENT_TYPE_SCRIPT); + for (Entity* scriptEntity : scriptedActs) { + if (scriptEntity->GetObjectID() != zoneControl->GetObjectID()) { // Don't want to trigger twice on instance worlds + for (CppScripts::Script* script : CppScripts::GetEntityScripts(scriptEntity)) { + script->OnPlayerLoaded(scriptEntity, player); } } + } - auto* destroyable = entity->GetComponent(); - destroyable->SetImagination(destroyable->GetImagination()); + //Kill player if health == 0 + if (entity->GetIsDead()) { + entity->Smash(entity->GetObjectID()); + } + + //if the player has moved significantly, move them back: + if ((entity->GetPosition().y - entity->GetCharacter()->GetOriginalPos().y) > 2.0f) { + // Disabled until fixed + //GameMessages::SendTeleport(entity->GetObjectID(), entity->GetCharacter()->GetOriginalPos(), entity->GetCharacter()->GetOriginalRot(), entity->GetSystemAddress(), true, true); + } + + /** + * Invoke the OnZoneLoad event on the player character + */ + auto* character = entity->GetCharacter(); + + if (character != nullptr) { + character->OnZoneLoad(); + } + + Game::logger->Log("GameMessageHandler", "Player %s (%llu) loaded.", entity->GetCharacter()->GetName().c_str(), entity->GetObjectID()); + + // After we've done our thing, tell the client they're ready + GameMessages::SendPlayerReady(dZoneManager::Instance()->GetZoneControlObject(), sysAddr); + GameMessages::SendPlayerReady(entity, sysAddr); + + break; + } + + case GAME_MSG_REQUEST_LINKED_MISSION: { + GameMessages::HandleRequestLinkedMission(inStream, entity); + break; + } + + case GAME_MSG_MISSION_DIALOGUE_OK: { + GameMessages::HandleMissionDialogOK(inStream, entity); + break; + } + + case GAME_MSG_MISSION_DIALOGUE_CANCELLED: { + //This message is pointless for our implementation, as the client just carries on after + //rejecting a mission offer. We dont need to do anything. This is just here to remove a warning in our logs :) + break; + } + + case GAME_MSG_REQUEST_PLATFORM_RESYNC: { + GameMessages::HandleRequestPlatformResync(inStream, entity, sysAddr); + break; + } + + case GAME_MSG_FIRE_EVENT_SERVER_SIDE: { + GameMessages::HandleFireEventServerSide(inStream, entity, sysAddr); + break; + } + + case GAME_MSG_SEND_ACTIVITY_SUMMARY_LEADERBOARD_DATA: { + GameMessages::HandleActivitySummaryLeaderboardData(inStream, entity, sysAddr); + break; + } + + case GAME_MSG_REQUEST_ACTIVITY_SUMMARY_LEADERBOARD_DATA: { + GameMessages::HandleRequestActivitySummaryLeaderboardData(inStream, entity, sysAddr); + break; + } + + case GAME_MSG_ACTIVITY_STATE_CHANGE_REQUEST: { + GameMessages::HandleActivityStateChangeRequest(inStream, entity); + break; + } + + case GAME_MSG_PARSE_CHAT_MESSAGE: { + GameMessages::HandleParseChatMessage(inStream, entity, sysAddr); + break; + } + + case GAME_MSG_NOTIFY_SERVER_LEVEL_PROCESSING_COMPLETE: { + GameMessages::HandleNotifyServerLevelProcessingComplete(inStream, entity); + break; + } + + case GAME_MSG_PICKUP_CURRENCY: { + GameMessages::HandlePickupCurrency(inStream, entity); + break; + } + + case GAME_MSG_PICKUP_ITEM: { + GameMessages::HandlePickupItem(inStream, entity); + break; + } + + case GAME_MSG_RESURRECT: { + GameMessages::HandleResurrect(inStream, entity); + break; + } + + case GAME_MSG_REQUEST_RESURRECT: { + GameMessages::SendResurrect(entity); + /*auto* dest = static_cast(entity->GetComponent(COMPONENT_TYPE_DESTROYABLE)); + if (dest) { + dest->SetHealth(4); + dest->SetArmor(0); + dest->SetImagination(6); EntityManager::Instance()->SerializeEntity(entity); + }*/ + break; + } + case GAME_MSG_HANDLE_HOT_PROPERTY_DATA: { + GameMessages::HandleGetHotPropertyData(inStream, entity, sysAddr); + break; + } - std::vector racingControllers = EntityManager::Instance()->GetEntitiesByComponent(COMPONENT_TYPE_RACING_CONTROL); - for (Entity* racingController : racingControllers) { - auto* racingComponent = racingController->GetComponent(); - if (racingComponent != nullptr) - { - racingComponent->OnPlayerLoaded(entity); - } + case GAME_MSG_REQUEST_SERVER_PROJECTILE_IMPACT: + { + auto message = GameMessages::RequestServerProjectileImpact(); + + message.Deserialize(inStream); + + auto* skill_component = entity->GetComponent(); + + if (skill_component != nullptr) { + auto* bs = new RakNet::BitStream((unsigned char*)message.sBitStream.c_str(), message.sBitStream.size(), false); + + skill_component->SyncPlayerProjectile(message.i64LocalID, bs, message.i64TargetID); + + delete bs; + } + + break; + } + + case GAME_MSG_START_SKILL: { + GameMessages::StartSkill startSkill = GameMessages::StartSkill(); + startSkill.Deserialize(inStream); // inStream replaces &bitStream + + if (startSkill.skillID == 1561 || startSkill.skillID == 1562 || startSkill.skillID == 1541) return; + + MissionComponent* comp = entity->GetComponent(); + if (comp) { + comp->Progress(MissionTaskType::MISSION_TASK_TYPE_SKILL, startSkill.skillID); + } + + CDSkillBehaviorTable* skillTable = CDClientManager::Instance()->GetTable("SkillBehavior"); + unsigned int behaviorId = skillTable->GetSkillByID(startSkill.skillID).behaviorID; + + bool success = false; + + if (behaviorId > 0) { + RakNet::BitStream* bs = new RakNet::BitStream((unsigned char*)startSkill.sBitStream.c_str(), startSkill.sBitStream.size(), false); + + auto* skillComponent = entity->GetComponent(); + + success = skillComponent->CastPlayerSkill(behaviorId, startSkill.uiSkillHandle, bs, startSkill.optionalTargetID, startSkill.skillID); + + if (success && entity->GetCharacter()) { + DestroyableComponent* destComp = entity->GetComponent(); + destComp->SetImagination(destComp->GetImagination() - skillTable->GetSkillByID(startSkill.skillID).imaginationcost); } - Entity* zoneControl = EntityManager::Instance()->GetZoneControlEntity(); - for (CppScripts::Script* script : CppScripts::GetEntityScripts(zoneControl)) { - script->OnPlayerLoaded(zoneControl, player); - } - - std::vector scriptedActs = EntityManager::Instance()->GetEntitiesByComponent(COMPONENT_TYPE_SCRIPT); - for (Entity* scriptEntity : scriptedActs) { - if (scriptEntity->GetObjectID() != zoneControl->GetObjectID()) { // Don't want to trigger twice on instance worlds - for (CppScripts::Script* script : CppScripts::GetEntityScripts(scriptEntity)) { - script->OnPlayerLoaded(scriptEntity, player); - } - } - } - - //Kill player if health == 0 - if (entity->GetIsDead()) { - entity->Smash(entity->GetObjectID()); - } - - //if the player has moved significantly, move them back: - if ((entity->GetPosition().y - entity->GetCharacter()->GetOriginalPos().y) > 2.0f) { - // Disabled until fixed - //GameMessages::SendTeleport(entity->GetObjectID(), entity->GetCharacter()->GetOriginalPos(), entity->GetCharacter()->GetOriginalRot(), entity->GetSystemAddress(), true, true); - } - - /** - * Invoke the OnZoneLoad event on the player character - */ - auto* character = entity->GetCharacter(); - - if (character != nullptr) { - character->OnZoneLoad(); - } - - Game::logger->Log("GameMessageHandler", "Player %s (%llu) loaded.", entity->GetCharacter()->GetName().c_str(), entity->GetObjectID()); - - // After we've done our thing, tell the client they're ready - GameMessages::SendPlayerReady(dZoneManager::Instance()->GetZoneControlObject(), sysAddr); - GameMessages::SendPlayerReady(entity, sysAddr); + delete bs; + } + if (Game::server->GetZoneID() == 1302) { break; } - case GAME_MSG_REQUEST_LINKED_MISSION: { - GameMessages::HandleRequestLinkedMission(inStream, entity); - break; - } - - case GAME_MSG_MISSION_DIALOGUE_OK: { - GameMessages::HandleMissionDialogOK(inStream, entity); - break; - } - - case GAME_MSG_MISSION_DIALOGUE_CANCELLED: { - //This message is pointless for our implementation, as the client just carries on after - //rejecting a mission offer. We dont need to do anything. This is just here to remove a warning in our logs :) - break; - } - - case GAME_MSG_REQUEST_PLATFORM_RESYNC: { - GameMessages::HandleRequestPlatformResync(inStream, entity, sysAddr); - break; - } - - case GAME_MSG_FIRE_EVENT_SERVER_SIDE: { - GameMessages::HandleFireEventServerSide(inStream, entity, sysAddr); - break; - } - - case GAME_MSG_SEND_ACTIVITY_SUMMARY_LEADERBOARD_DATA: { - GameMessages::HandleActivitySummaryLeaderboardData(inStream, entity, sysAddr); - break; - } - - case GAME_MSG_REQUEST_ACTIVITY_SUMMARY_LEADERBOARD_DATA: { - GameMessages::HandleRequestActivitySummaryLeaderboardData(inStream, entity, sysAddr); - break; - } - - case GAME_MSG_ACTIVITY_STATE_CHANGE_REQUEST: { - GameMessages::HandleActivityStateChangeRequest(inStream, entity); - break; - } - - case GAME_MSG_PARSE_CHAT_MESSAGE: { - GameMessages::HandleParseChatMessage(inStream, entity, sysAddr); - break; - } - - case GAME_MSG_NOTIFY_SERVER_LEVEL_PROCESSING_COMPLETE: { - GameMessages::HandleNotifyServerLevelProcessingComplete(inStream, entity); - break; - } - - case GAME_MSG_PICKUP_CURRENCY: { - GameMessages::HandlePickupCurrency(inStream, entity); - break; - } - - case GAME_MSG_PICKUP_ITEM: { - GameMessages::HandlePickupItem(inStream, entity); - break; - } - - case GAME_MSG_RESURRECT: { - GameMessages::HandleResurrect(inStream, entity); - break; - } - - case GAME_MSG_REQUEST_RESURRECT: { - GameMessages::SendResurrect(entity); - /*auto* dest = static_cast(entity->GetComponent(COMPONENT_TYPE_DESTROYABLE)); - if (dest) { - dest->SetHealth(4); - dest->SetArmor(0); - dest->SetImagination(6); - EntityManager::Instance()->SerializeEntity(entity); - }*/ - break; - } - case GAME_MSG_HANDLE_HOT_PROPERTY_DATA: { - GameMessages::HandleGetHotPropertyData(inStream, entity, sysAddr); - break; - } - - case GAME_MSG_REQUEST_SERVER_PROJECTILE_IMPACT: - { - auto message = GameMessages::RequestServerProjectileImpact(); - - message.Deserialize(inStream); - - auto* skill_component = entity->GetComponent(); - - if (skill_component != nullptr) - { - auto* bs = new RakNet::BitStream((unsigned char*) message.sBitStream.c_str(), message.sBitStream.size(), false); - - skill_component->SyncPlayerProjectile(message.i64LocalID, bs, message.i64TargetID); - - delete bs; - } - - break; - } - - case GAME_MSG_START_SKILL: { - GameMessages::StartSkill startSkill = GameMessages::StartSkill(); - startSkill.Deserialize(inStream); // inStream replaces &bitStream - - if (startSkill.skillID == 1561 || startSkill.skillID == 1562 || startSkill.skillID == 1541) return; - - MissionComponent* comp = entity->GetComponent(); - if (comp) { - comp->Progress(MissionTaskType::MISSION_TASK_TYPE_SKILL, startSkill.skillID); - } - - CDSkillBehaviorTable* skillTable = CDClientManager::Instance()->GetTable("SkillBehavior"); - unsigned int behaviorId = skillTable->GetSkillByID(startSkill.skillID).behaviorID; - - bool success = false; - - if (behaviorId > 0) { - RakNet::BitStream * bs = new RakNet::BitStream((unsigned char *)startSkill.sBitStream.c_str(), startSkill.sBitStream.size(), false); - - auto* skillComponent = entity->GetComponent(); - - success = skillComponent->CastPlayerSkill(behaviorId, startSkill.uiSkillHandle, bs, startSkill.optionalTargetID, startSkill.skillID); - - if (success && entity->GetCharacter()) { - DestroyableComponent* destComp = entity->GetComponent(); - destComp->SetImagination(destComp->GetImagination() - skillTable->GetSkillByID(startSkill.skillID).imaginationcost); - } - - delete bs; - } - - if (Game::server->GetZoneID() == 1302) { - break; - } - - if (success) { - //Broadcast our startSkill: - RakNet::BitStream bitStreamLocal; - PacketUtils::WriteHeader(bitStreamLocal, CLIENT, MSG_CLIENT_GAME_MSG); - bitStreamLocal.Write(entity->GetObjectID()); - - GameMessages::EchoStartSkill echoStartSkill; - echoStartSkill.bUsedMouse = startSkill.bUsedMouse; - echoStartSkill.fCasterLatency = startSkill.fCasterLatency; - echoStartSkill.iCastType = startSkill.iCastType; - echoStartSkill.lastClickedPosit = startSkill.lastClickedPosit; - echoStartSkill.optionalOriginatorID = startSkill.optionalOriginatorID; - echoStartSkill.optionalTargetID = startSkill.optionalTargetID; - echoStartSkill.originatorRot = startSkill.originatorRot; - echoStartSkill.sBitStream = startSkill.sBitStream; - echoStartSkill.skillID = startSkill.skillID; - echoStartSkill.uiSkillHandle = startSkill.uiSkillHandle; - echoStartSkill.Serialize(&bitStreamLocal); - - Game::server->Send(&bitStreamLocal, entity->GetSystemAddress(), true); - } - } break; - - case GAME_MSG_SYNC_SKILL: { + if (success) { + //Broadcast our startSkill: RakNet::BitStream bitStreamLocal; PacketUtils::WriteHeader(bitStreamLocal, CLIENT, MSG_CLIENT_GAME_MSG); bitStreamLocal.Write(entity->GetObjectID()); - //bitStreamLocal.Write((unsigned short)GAME_MSG_ECHO_SYNC_SKILL); - //bitStreamLocal.Write(inStream); - GameMessages::SyncSkill sync = GameMessages::SyncSkill(inStream); // inStream replaced &bitStream - //sync.Serialize(&bitStreamLocal); + GameMessages::EchoStartSkill echoStartSkill; + echoStartSkill.bUsedMouse = startSkill.bUsedMouse; + echoStartSkill.fCasterLatency = startSkill.fCasterLatency; + echoStartSkill.iCastType = startSkill.iCastType; + echoStartSkill.lastClickedPosit = startSkill.lastClickedPosit; + echoStartSkill.optionalOriginatorID = startSkill.optionalOriginatorID; + echoStartSkill.optionalTargetID = startSkill.optionalTargetID; + echoStartSkill.originatorRot = startSkill.originatorRot; + echoStartSkill.sBitStream = startSkill.sBitStream; + echoStartSkill.skillID = startSkill.skillID; + echoStartSkill.uiSkillHandle = startSkill.uiSkillHandle; + echoStartSkill.Serialize(&bitStreamLocal); - ostringstream buffer; + Game::server->Send(&bitStreamLocal, entity->GetSystemAddress(), true); + } + } break; - for (unsigned int k = 0; k < sync.sBitStream.size(); k++){ - char s; - s = sync.sBitStream.at(k); - buffer << setw(2) << hex << setfill('0') << (int) s << " "; - } + case GAME_MSG_SYNC_SKILL: { + RakNet::BitStream bitStreamLocal; + PacketUtils::WriteHeader(bitStreamLocal, CLIENT, MSG_CLIENT_GAME_MSG); + bitStreamLocal.Write(entity->GetObjectID()); + //bitStreamLocal.Write((unsigned short)GAME_MSG_ECHO_SYNC_SKILL); + //bitStreamLocal.Write(inStream); - //cout << buffer.str() << endl; + GameMessages::SyncSkill sync = GameMessages::SyncSkill(inStream); // inStream replaced &bitStream + //sync.Serialize(&bitStreamLocal); - if(usr != nullptr) { - RakNet::BitStream * bs = new RakNet::BitStream((unsigned char *)sync.sBitStream.c_str(), sync.sBitStream.size(), false); + ostringstream buffer; - auto* skillComponent = entity->GetComponent(); + for (unsigned int k = 0; k < sync.sBitStream.size(); k++) { + char s; + s = sync.sBitStream.at(k); + buffer << setw(2) << hex << setfill('0') << (int)s << " "; + } - skillComponent->SyncPlayerSkill(sync.uiSkillHandle, sync.uiBehaviorHandle, bs); + //cout << buffer.str() << endl; - delete bs; - } + if (usr != nullptr) { + RakNet::BitStream* bs = new RakNet::BitStream((unsigned char*)sync.sBitStream.c_str(), sync.sBitStream.size(), false); - GameMessages::EchoSyncSkill echo = GameMessages::EchoSyncSkill(); - echo.bDone = sync.bDone; - echo.sBitStream = sync.sBitStream; - echo.uiBehaviorHandle = sync.uiBehaviorHandle; - echo.uiSkillHandle = sync.uiSkillHandle; + auto* skillComponent = entity->GetComponent(); - echo.Serialize(&bitStreamLocal); + skillComponent->SyncPlayerSkill(sync.uiSkillHandle, sync.uiBehaviorHandle, bs); - Game::server->Send(&bitStreamLocal, sysAddr, true); - } break; + delete bs; + } - case GAME_MSG_REQUEST_SMASH_PLAYER: - entity->Smash(entity->GetObjectID()); - break; + GameMessages::EchoSyncSkill echo = GameMessages::EchoSyncSkill(); + echo.bDone = sync.bDone; + echo.sBitStream = sync.sBitStream; + echo.uiBehaviorHandle = sync.uiBehaviorHandle; + echo.uiSkillHandle = sync.uiSkillHandle; - case GAME_MSG_MOVE_ITEM_BETWEEN_INVENTORY_TYPES: - GameMessages::HandleMoveItemBetweenInventoryTypes(inStream, entity, sysAddr); - break; + echo.Serialize(&bitStreamLocal); - case GAME_MSG_MODULAR_BUILD_FINISH: - GameMessages::HandleModularBuildFinish(inStream, entity, sysAddr); - break; + Game::server->Send(&bitStreamLocal, sysAddr, true); + } break; - case GAME_MSG_PUSH_EQUIPPED_ITEMS_STATE: - GameMessages::HandlePushEquippedItemsState(inStream, entity); - break; + case GAME_MSG_REQUEST_SMASH_PLAYER: + entity->Smash(entity->GetObjectID()); + break; - case GAME_MSG_POP_EQUIPPED_ITEMS_STATE: - GameMessages::HandlePopEquippedItemsState(inStream, entity); - break; + case GAME_MSG_MOVE_ITEM_BETWEEN_INVENTORY_TYPES: + GameMessages::HandleMoveItemBetweenInventoryTypes(inStream, entity, sysAddr); + break; - case GAME_MSG_BUY_FROM_VENDOR: - GameMessages::HandleBuyFromVendor(inStream, entity, sysAddr); - break; + case GAME_MSG_MODULAR_BUILD_FINISH: + GameMessages::HandleModularBuildFinish(inStream, entity, sysAddr); + break; - case GAME_MSG_SELL_TO_VENDOR: - GameMessages::HandleSellToVendor(inStream, entity, sysAddr); - break; + case GAME_MSG_PUSH_EQUIPPED_ITEMS_STATE: + GameMessages::HandlePushEquippedItemsState(inStream, entity); + break; - case GAME_MSG_BUYBACK_FROM_VENDOR: - GameMessages::HandleBuybackFromVendor(inStream, entity, sysAddr); - break; + case GAME_MSG_POP_EQUIPPED_ITEMS_STATE: + GameMessages::HandlePopEquippedItemsState(inStream, entity); + break; - case GAME_MSG_MODULAR_BUILD_MOVE_AND_EQUIP: - GameMessages::HandleModularBuildMoveAndEquip(inStream, entity, sysAddr); - break; + case GAME_MSG_BUY_FROM_VENDOR: + GameMessages::HandleBuyFromVendor(inStream, entity, sysAddr); + break; - case GAME_MSG_DONE_ARRANGING_WITH_ITEM: - GameMessages::HandleDoneArrangingWithItem(inStream, entity, sysAddr); - break; + case GAME_MSG_SELL_TO_VENDOR: + GameMessages::HandleSellToVendor(inStream, entity, sysAddr); + break; - case GAME_MSG_MODULAR_BUILD_CONVERT_MODEL: - GameMessages::HandleModularBuildConvertModel(inStream, entity, sysAddr); - break; + case GAME_MSG_BUYBACK_FROM_VENDOR: + GameMessages::HandleBuybackFromVendor(inStream, entity, sysAddr); + break; - case GAME_MSG_BUILD_MODE_SET: - GameMessages::HandleBuildModeSet(inStream, entity); - break; + case GAME_MSG_MODULAR_BUILD_MOVE_AND_EQUIP: + GameMessages::HandleModularBuildMoveAndEquip(inStream, entity, sysAddr); + break; - case GAME_MSG_REBUILD_CANCEL: - GameMessages::HandleRebuildCancel(inStream, entity); - break; + case GAME_MSG_DONE_ARRANGING_WITH_ITEM: + GameMessages::HandleDoneArrangingWithItem(inStream, entity, sysAddr); + break; - case GAME_MSG_MATCH_REQUEST: - GameMessages::HandleMatchRequest(inStream, entity); - break; + case GAME_MSG_MODULAR_BUILD_CONVERT_MODEL: + GameMessages::HandleModularBuildConvertModel(inStream, entity, sysAddr); + break; - case GAME_MSG_USE_NON_EQUIPMENT_ITEM: - GameMessages::HandleUseNonEquipmentItem(inStream, entity); - break; + case GAME_MSG_BUILD_MODE_SET: + GameMessages::HandleBuildModeSet(inStream, entity); + break; - case GAME_MSG_CLIENT_ITEM_CONSUMED: - GameMessages::HandleClientItemConsumed(inStream, entity); - break; + case GAME_MSG_REBUILD_CANCEL: + GameMessages::HandleRebuildCancel(inStream, entity); + break; - case GAME_MSG_SET_CONSUMABLE_ITEM: - GameMessages::HandleSetConsumableItem(inStream, entity, sysAddr); - break; + case GAME_MSG_MATCH_REQUEST: + GameMessages::HandleMatchRequest(inStream, entity); + break; - case GAME_MSG_VERIFY_ACK: - GameMessages::HandleVerifyAck(inStream, entity, sysAddr); - break; + case GAME_MSG_USE_NON_EQUIPMENT_ITEM: + GameMessages::HandleUseNonEquipmentItem(inStream, entity); + break; + + case GAME_MSG_CLIENT_ITEM_CONSUMED: + GameMessages::HandleClientItemConsumed(inStream, entity); + break; + + case GAME_MSG_SET_CONSUMABLE_ITEM: + GameMessages::HandleSetConsumableItem(inStream, entity, sysAddr); + break; + + case GAME_MSG_VERIFY_ACK: + GameMessages::HandleVerifyAck(inStream, entity, sysAddr); + break; // Trading - case GAME_MSG_CLIENT_TRADE_REQUEST: - GameMessages::HandleClientTradeRequest(inStream, entity, sysAddr); - break; - case GAME_MSG_CLIENT_TRADE_CANCEL: - GameMessages::HandleClientTradeCancel(inStream, entity, sysAddr); - break; - case GAME_MSG_CLIENT_TRADE_ACCEPT: - GameMessages::HandleClientTradeAccept(inStream, entity, sysAddr); - break; - case GAME_MSG_CLIENT_TRADE_UPDATE: - GameMessages::HandleClientTradeUpdate(inStream, entity, sysAddr); - break; + case GAME_MSG_CLIENT_TRADE_REQUEST: + GameMessages::HandleClientTradeRequest(inStream, entity, sysAddr); + break; + case GAME_MSG_CLIENT_TRADE_CANCEL: + GameMessages::HandleClientTradeCancel(inStream, entity, sysAddr); + break; + case GAME_MSG_CLIENT_TRADE_ACCEPT: + GameMessages::HandleClientTradeAccept(inStream, entity, sysAddr); + break; + case GAME_MSG_CLIENT_TRADE_UPDATE: + GameMessages::HandleClientTradeUpdate(inStream, entity, sysAddr); + break; // Pets - case GAME_MSG_PET_TAMING_TRY_BUILD: - GameMessages::HandlePetTamingTryBuild(inStream, entity, sysAddr); - break; + case GAME_MSG_PET_TAMING_TRY_BUILD: + GameMessages::HandlePetTamingTryBuild(inStream, entity, sysAddr); + break; - case GAME_MSG_NOTIFY_TAMING_BUILD_SUCCESS: - GameMessages::HandleNotifyTamingBuildSuccess(inStream, entity, sysAddr); - break; + case GAME_MSG_NOTIFY_TAMING_BUILD_SUCCESS: + GameMessages::HandleNotifyTamingBuildSuccess(inStream, entity, sysAddr); + break; - case GAME_MSG_REQUEST_SET_PET_NAME: - GameMessages::HandleRequestSetPetName(inStream, entity, sysAddr); - break; + case GAME_MSG_REQUEST_SET_PET_NAME: + GameMessages::HandleRequestSetPetName(inStream, entity, sysAddr); + break; - case GAME_MSG_START_SERVER_PET_MINIGAME_TIMER: - GameMessages::HandleStartServerPetMinigameTimer(inStream, entity, sysAddr); - break; + case GAME_MSG_START_SERVER_PET_MINIGAME_TIMER: + GameMessages::HandleStartServerPetMinigameTimer(inStream, entity, sysAddr); + break; - case GAME_MSG_CLIENT_EXIT_TAMING_MINIGAME: - GameMessages::HandleClientExitTamingMinigame(inStream, entity, sysAddr); - break; + case GAME_MSG_CLIENT_EXIT_TAMING_MINIGAME: + GameMessages::HandleClientExitTamingMinigame(inStream, entity, sysAddr); + break; - case GAME_MSG_COMMAND_PET: - GameMessages::HandleCommandPet(inStream, entity, sysAddr); - break; + case GAME_MSG_COMMAND_PET: + GameMessages::HandleCommandPet(inStream, entity, sysAddr); + break; - case GAME_MSG_DESPAWN_PET: - GameMessages::HandleDespawnPet(inStream, entity, sysAddr); - break; + case GAME_MSG_DESPAWN_PET: + GameMessages::HandleDespawnPet(inStream, entity, sysAddr); + break; - case GAME_MSG_MESSAGE_BOX_RESPOND: - GameMessages::HandleMessageBoxResponse(inStream, entity, sysAddr); - break; + case GAME_MSG_MESSAGE_BOX_RESPOND: + GameMessages::HandleMessageBoxResponse(inStream, entity, sysAddr); + break; - case GAME_MSG_CHOICE_BOX_RESPOND: - GameMessages::HandleChoiceBoxRespond(inStream, entity, sysAddr); - break; + case GAME_MSG_CHOICE_BOX_RESPOND: + GameMessages::HandleChoiceBoxRespond(inStream, entity, sysAddr); + break; // Property - case GAME_MSG_QUERY_PROPERTY_DATA: - GameMessages::HandleQueryPropertyData(inStream, entity, sysAddr); - break; + case GAME_MSG_QUERY_PROPERTY_DATA: + GameMessages::HandleQueryPropertyData(inStream, entity, sysAddr); + break; - case GAME_MSG_START_BUILDING_WITH_ITEM: - GameMessages::HandleStartBuildingWithItem(inStream, entity, sysAddr); - break; + case GAME_MSG_START_BUILDING_WITH_ITEM: + GameMessages::HandleStartBuildingWithItem(inStream, entity, sysAddr); + break; - case GAME_MSG_SET_BUILD_MODE: - GameMessages::HandleSetBuildMode(inStream, entity, sysAddr); - break; + case GAME_MSG_SET_BUILD_MODE: + GameMessages::HandleSetBuildMode(inStream, entity, sysAddr); + break; - case GAME_MSG_PROPERTY_EDITOR_BEGIN: - GameMessages::HandlePropertyEditorBegin(inStream, entity, sysAddr); - break; + case GAME_MSG_PROPERTY_EDITOR_BEGIN: + GameMessages::HandlePropertyEditorBegin(inStream, entity, sysAddr); + break; - case GAME_MSG_PROPERTY_EDITOR_END: - GameMessages::HandlePropertyEditorEnd(inStream, entity, sysAddr); - break; + case GAME_MSG_PROPERTY_EDITOR_END: + GameMessages::HandlePropertyEditorEnd(inStream, entity, sysAddr); + break; - case GAME_MSG_PROPERTY_CONTENTS_FROM_CLIENT: - GameMessages::HandlePropertyContentsFromClient(inStream, entity, sysAddr); - break; + case GAME_MSG_PROPERTY_CONTENTS_FROM_CLIENT: + GameMessages::HandlePropertyContentsFromClient(inStream, entity, sysAddr); + break; - case GAME_MSG_ZONE_PROPERTY_MODEL_EQUIPPED: - GameMessages::HandlePropertyModelEquipped(inStream, entity, sysAddr); - break; + case GAME_MSG_ZONE_PROPERTY_MODEL_EQUIPPED: + GameMessages::HandlePropertyModelEquipped(inStream, entity, sysAddr); + break; - case GAME_MSG_PLACE_PROPERTY_MODEL: - GameMessages::HandlePlacePropertyModel(inStream, entity, sysAddr); - break; + case GAME_MSG_PLACE_PROPERTY_MODEL: + GameMessages::HandlePlacePropertyModel(inStream, entity, sysAddr); + break; - case GAME_MSG_UPDATE_MODEL_FROM_CLIENT: - GameMessages::HandleUpdatePropertyModel(inStream, entity, sysAddr); - break; + case GAME_MSG_UPDATE_MODEL_FROM_CLIENT: + GameMessages::HandleUpdatePropertyModel(inStream, entity, sysAddr); + break; - case GAME_MSG_DELETE_MODEL_FROM_CLIENT: - GameMessages::HandleDeletePropertyModel(inStream, entity, sysAddr); - break; + case GAME_MSG_DELETE_MODEL_FROM_CLIENT: + GameMessages::HandleDeletePropertyModel(inStream, entity, sysAddr); + break; - case GAME_MSG_BBB_LOAD_ITEM_REQUEST: - GameMessages::HandleBBBLoadItemRequest(inStream, entity, sysAddr); - break; + case GAME_MSG_BBB_LOAD_ITEM_REQUEST: + GameMessages::HandleBBBLoadItemRequest(inStream, entity, sysAddr); + break; - case GAME_MSG_BBB_SAVE_REQUEST: - GameMessages::HandleBBBSaveRequest(inStream, entity, sysAddr); - break; + case GAME_MSG_BBB_SAVE_REQUEST: + GameMessages::HandleBBBSaveRequest(inStream, entity, sysAddr); + break; - case GAME_MSG_CONTROL_BEHAVIOR: - GameMessages::HandleControlBehaviors(inStream, entity, sysAddr); - break; + case GAME_MSG_CONTROL_BEHAVIOR: + GameMessages::HandleControlBehaviors(inStream, entity, sysAddr); + break; - case GAME_MSG_PROPERTY_ENTRANCE_SYNC: - GameMessages::HandlePropertyEntranceSync(inStream, entity, sysAddr); - break; + case GAME_MSG_PROPERTY_ENTRANCE_SYNC: + GameMessages::HandlePropertyEntranceSync(inStream, entity, sysAddr); + break; - case GAME_MSG_ENTER_PROPERTY1: - GameMessages::HandleEnterProperty(inStream, entity, sysAddr); - break; + case GAME_MSG_ENTER_PROPERTY1: + GameMessages::HandleEnterProperty(inStream, entity, sysAddr); + break; - case GAME_MSG_ZONE_PROPERTY_MODEL_ROTATED: - EntityManager::Instance()->GetZoneControlEntity()->OnZonePropertyModelRotated(usr->GetLastUsedChar()->GetEntity()); - break; + case GAME_MSG_ZONE_PROPERTY_MODEL_ROTATED: + EntityManager::Instance()->GetZoneControlEntity()->OnZonePropertyModelRotated(usr->GetLastUsedChar()->GetEntity()); + break; - case GAME_MSG_UPDATE_PROPERTY_OR_MODEL_FOR_FILTER_CHECK: - GameMessages::HandleUpdatePropertyOrModelForFilterCheck(inStream, entity, sysAddr); - break; + case GAME_MSG_UPDATE_PROPERTY_OR_MODEL_FOR_FILTER_CHECK: + GameMessages::HandleUpdatePropertyOrModelForFilterCheck(inStream, entity, sysAddr); + break; - case GAME_MSG_SET_PROPERTY_ACCESS: - GameMessages::HandleSetPropertyAccess(inStream, entity, sysAddr); - break; + case GAME_MSG_SET_PROPERTY_ACCESS: + GameMessages::HandleSetPropertyAccess(inStream, entity, sysAddr); + break; // Racing - case GAME_MSG_MODULE_ASSEMBLY_QUERY_DATA: - GameMessages::HandleModuleAssemblyQueryData(inStream, entity, sysAddr); - break; + case GAME_MSG_MODULE_ASSEMBLY_QUERY_DATA: + GameMessages::HandleModuleAssemblyQueryData(inStream, entity, sysAddr); + break; - case GAME_MSG_ACKNOWLEDGE_POSSESSION: - GameMessages::HandleAcknowledgePossession(inStream, entity, sysAddr); - break; + case GAME_MSG_ACKNOWLEDGE_POSSESSION: + GameMessages::HandleAcknowledgePossession(inStream, entity, sysAddr); + break; - case GAME_MSG_VEHICLE_SET_WHEEL_LOCK_STATE: - GameMessages::HandleVehicleSetWheelLockState(inStream, entity, sysAddr); - break; + case GAME_MSG_VEHICLE_SET_WHEEL_LOCK_STATE: + GameMessages::HandleVehicleSetWheelLockState(inStream, entity, sysAddr); + break; - case GAME_MSG_MODULAR_ASSEMBLY_NIF_COMPLETED: - GameMessages::HandleModularAssemblyNIFCompleted(inStream, entity, sysAddr); - break; + case GAME_MSG_MODULAR_ASSEMBLY_NIF_COMPLETED: + GameMessages::HandleModularAssemblyNIFCompleted(inStream, entity, sysAddr); + break; - case GAME_MSG_RACING_CLIENT_READY: - GameMessages::HandleRacingClientReady(inStream, entity, sysAddr); - break; + case GAME_MSG_RACING_CLIENT_READY: + GameMessages::HandleRacingClientReady(inStream, entity, sysAddr); + break; - case GAME_MSG_REQUEST_DIE: - GameMessages::HandleRequestDie(inStream, entity, sysAddr); - break; + case GAME_MSG_REQUEST_DIE: + GameMessages::HandleRequestDie(inStream, entity, sysAddr); + break; - case GAME_MSG_VEHICLE_NOTIFY_SERVER_ADD_PASSIVE_BOOST_ACTION: - GameMessages::HandleVehicleNotifyServerAddPassiveBoostAction(inStream, entity, sysAddr); - break; + case GAME_MSG_VEHICLE_NOTIFY_SERVER_ADD_PASSIVE_BOOST_ACTION: + GameMessages::HandleVehicleNotifyServerAddPassiveBoostAction(inStream, entity, sysAddr); + break; - case GAME_MSG_VEHICLE_NOTIFY_SERVER_REMOVE_PASSIVE_BOOST_ACTION: - GameMessages::HandleVehicleNotifyServerRemovePassiveBoostAction(inStream, entity, sysAddr); - break; + case GAME_MSG_VEHICLE_NOTIFY_SERVER_REMOVE_PASSIVE_BOOST_ACTION: + GameMessages::HandleVehicleNotifyServerRemovePassiveBoostAction(inStream, entity, sysAddr); + break; - case GAME_MSG_RACING_PLAYER_INFO_RESET_FINISHED: - GameMessages::HandleRacingPlayerInfoResetFinished(inStream, entity, sysAddr); - break; + case GAME_MSG_RACING_PLAYER_INFO_RESET_FINISHED: + GameMessages::HandleRacingPlayerInfoResetFinished(inStream, entity, sysAddr); + break; - case GAME_MSG_VEHICLE_NOTIFY_HIT_IMAGINATION_SERVER: - GameMessages::HandleVehicleNotifyHitImaginationServer(inStream, entity, sysAddr); - break; - case GAME_MSG_UPDATE_PROPERTY_PERFORMANCE_COST: - GameMessages::HandleUpdatePropertyPerformanceCost(inStream, entity, sysAddr); - break; + case GAME_MSG_VEHICLE_NOTIFY_HIT_IMAGINATION_SERVER: + GameMessages::HandleVehicleNotifyHitImaginationServer(inStream, entity, sysAddr); + break; + case GAME_MSG_UPDATE_PROPERTY_PERFORMANCE_COST: + GameMessages::HandleUpdatePropertyPerformanceCost(inStream, entity, sysAddr); + break; // SG - case GAME_MSG_UPDATE_SHOOTING_GALLERY_ROTATION: - GameMessages::HandleUpdateShootingGalleryRotation(inStream, entity, sysAddr); - break; + case GAME_MSG_UPDATE_SHOOTING_GALLERY_ROTATION: + GameMessages::HandleUpdateShootingGalleryRotation(inStream, entity, sysAddr); + break; // NT - case GAME_MSG_REQUEST_MOVE_ITEM_BETWEEN_INVENTORY_TYPES: - GameMessages::HandleRequestMoveItemBetweenInventoryTypes(inStream, entity, sysAddr); - break; + case GAME_MSG_REQUEST_MOVE_ITEM_BETWEEN_INVENTORY_TYPES: + GameMessages::HandleRequestMoveItemBetweenInventoryTypes(inStream, entity, sysAddr); + break; - case GAME_MSG_TOGGLE_GHOST_REFERENCE_OVERRIDE: - GameMessages::HandleToggleGhostReferenceOverride(inStream, entity, sysAddr); - break; + case GAME_MSG_TOGGLE_GHOST_REFERENCE_OVERRIDE: + GameMessages::HandleToggleGhostReferenceOverride(inStream, entity, sysAddr); + break; - case GAME_MSG_SET_GHOST_REFERENCE_POSITION: - GameMessages::HandleSetGhostReferencePosition(inStream, entity, sysAddr); - break; + case GAME_MSG_SET_GHOST_REFERENCE_POSITION: + GameMessages::HandleSetGhostReferencePosition(inStream, entity, sysAddr); + break; - case GAME_MSG_READY_FOR_UPDATES: - //We don't really care about this message, as it's simply here to inform us that the client is done loading an object. - //In the event we _do_ send an update to an object that hasn't finished loading, the client will handle it anyway. - break; + case GAME_MSG_READY_FOR_UPDATES: + //We don't really care about this message, as it's simply here to inform us that the client is done loading an object. + //In the event we _do_ send an update to an object that hasn't finished loading, the client will handle it anyway. + break; - case GAME_MSG_REPORT_BUG: - GameMessages::HandleReportBug(inStream, entity); - break; + case GAME_MSG_REPORT_BUG: + GameMessages::HandleReportBug(inStream, entity); + break; - case GAME_MSG_CLIENT_RAIL_MOVEMENT_READY: - GameMessages::HandleClientRailMovementReady(inStream, entity, sysAddr); - break; + case GAME_MSG_CLIENT_RAIL_MOVEMENT_READY: + GameMessages::HandleClientRailMovementReady(inStream, entity, sysAddr); + break; - case GAME_MSG_CANCEL_RAIL_MOVEMENT: - GameMessages::HandleCancelRailMovement(inStream, entity, sysAddr); - break; + case GAME_MSG_CANCEL_RAIL_MOVEMENT: + GameMessages::HandleCancelRailMovement(inStream, entity, sysAddr); + break; - case GAME_MSG_PLAYER_RAIL_ARRIVED_NOTIFICATION: - GameMessages::HandlePlayerRailArrivedNotification(inStream, entity, sysAddr); - break; + case GAME_MSG_PLAYER_RAIL_ARRIVED_NOTIFICATION: + GameMessages::HandlePlayerRailArrivedNotification(inStream, entity, sysAddr); + break; - case GAME_MSG_CINEMATIC_UPDATE: - GameMessages::HandleCinematicUpdate(inStream, entity, sysAddr); - break; + case GAME_MSG_CINEMATIC_UPDATE: + GameMessages::HandleCinematicUpdate(inStream, entity, sysAddr); + break; - case GAME_MSG_MODIFY_PLAYER_ZONE_STATISTIC: - GameMessages::HandleModifyPlayerZoneStatistic(inStream, entity); - break; + case GAME_MSG_MODIFY_PLAYER_ZONE_STATISTIC: + GameMessages::HandleModifyPlayerZoneStatistic(inStream, entity); + break; - case GAME_MSG_UPDATE_PLAYER_STATISTIC: - GameMessages::HandleUpdatePlayerStatistic(inStream, entity); - break; + case GAME_MSG_UPDATE_PLAYER_STATISTIC: + GameMessages::HandleUpdatePlayerStatistic(inStream, entity); + break; - default: - //Game::logger->Log("GameMessageHandler", "Unknown game message ID: %X", messageID); - break; + default: + //Game::logger->Log("GameMessageHandler", "Unknown game message ID: %X", messageID); + break; } } diff --git a/dGame/dGameMessages/GameMessageHandler.h b/dGame/dGameMessages/GameMessageHandler.h index 0d14dc5b..063e97f6 100644 --- a/dGame/dGameMessages/GameMessageHandler.h +++ b/dGame/dGameMessages/GameMessageHandler.h @@ -22,7 +22,7 @@ #include "../dDatabase/CDClientDatabase.h" namespace GameMessageHandler { - void HandleMessage(RakNet::BitStream* inStream, const SystemAddress& sysAddr, LWOOBJID objectID, GAME_MSG messageID); + void HandleMessage(RakNet::BitStream* inStream, const SystemAddress& sysAddr, LWOOBJID objectID, GAME_MSG messageID); }; #endif // GAMEMESSAGEHANDLER_H diff --git a/dGame/dGameMessages/GameMessages.cpp b/dGame/dGameMessages/GameMessages.cpp index 66d71ca1..f4546416 100644 --- a/dGame/dGameMessages/GameMessages.cpp +++ b/dGame/dGameMessages/GameMessages.cpp @@ -70,9 +70,9 @@ void GameMessages::SendFireEventClientSide(const LWOOBJID& objectID, const SystemAddress& sysAddr, std::u16string args, const LWOOBJID& object, int64_t param1, int param2, const LWOOBJID& sender) { CBITSTREAM - CMSGHEADER + CMSGHEADER - bitStream.Write(objectID); + bitStream.Write(objectID); bitStream.Write(GAME_MSG::GAME_MSG_FIRE_EVENT_CLIENT_SIDE); //bitStream.Write(args); @@ -93,8 +93,8 @@ void GameMessages::SendFireEventClientSide(const LWOOBJID& objectID, const Syste void GameMessages::SendTeleport(const LWOOBJID& objectID, const NiPoint3& pos, const NiQuaternion& rot, const SystemAddress& sysAddr, bool bSetRotation, bool noGravTeleport) { CBITSTREAM - CMSGHEADER - bitStream.Write(objectID); + CMSGHEADER + bitStream.Write(objectID); bitStream.Write(GAME_MSG::GAME_MSG_TELEPORT); bool bIgnoreY = (pos.y == 0.0f); @@ -170,9 +170,9 @@ void GameMessages::SendPlayerReady(Entity* entity, const SystemAddress& sysAddr) SEND_PACKET; } -void GameMessages::SendPlayerAllowedRespawn(LWOOBJID entityID, bool doNotPromptRespawn, const SystemAddress &sysAddr) { +void GameMessages::SendPlayerAllowedRespawn(LWOOBJID entityID, bool doNotPromptRespawn, const SystemAddress& sysAddr) { CBITSTREAM - CMSGHEADER; + CMSGHEADER; bitStream.Write(entityID); bitStream.Write(GAME_MSG::GAME_MSG_SET_PLAYER_ALLOWED_RESPAWN); @@ -183,9 +183,9 @@ void GameMessages::SendPlayerAllowedRespawn(LWOOBJID entityID, bool doNotPromptR void GameMessages::SendInvalidZoneTransferList(Entity* entity, const SystemAddress& sysAddr, const std::u16string& feedbackURL, const std::u16string& invalidMapTransferList, bool feedbackOnExit, bool feedbackOnInvalidTransfer) { CBITSTREAM - CMSGHEADER + CMSGHEADER - bitStream.Write(entity->GetObjectID()); + bitStream.Write(entity->GetObjectID()); bitStream.Write(GAME_MSG::GAME_MSG_INVALID_ZONE_TRANSFER_LIST); uint32_t CustomerFeedbackURLLength = feedbackURL.size(); @@ -206,12 +206,11 @@ void GameMessages::SendInvalidZoneTransferList(Entity* entity, const SystemAddre SEND_PACKET } -void GameMessages::SendKnockback(const LWOOBJID& objectID, const LWOOBJID& caster, const LWOOBJID& originator, int knockBackTimeMS, const NiPoint3& vector) -{ +void GameMessages::SendKnockback(const LWOOBJID& objectID, const LWOOBJID& caster, const LWOOBJID& originator, int knockBackTimeMS, const NiPoint3& vector) { CBITSTREAM - CMSGHEADER + CMSGHEADER - bitStream.Write(objectID); + bitStream.Write(objectID); bitStream.Write(GAME_MSG_KNOCKBACK); bool casterFlag = caster != LWOOBJID_EMPTY; @@ -245,9 +244,9 @@ void GameMessages::SendStartArrangingWithItem( int targetTYPE ) { CBITSTREAM - CMSGHEADER + CMSGHEADER - bitStream.Write(entity->GetObjectID()); + bitStream.Write(entity->GetObjectID()); bitStream.Write(GAME_MSG::GAME_MSG_START_ARRANGING_WITH_ITEM); bitStream.Write(bFirstTime); @@ -267,11 +266,11 @@ void GameMessages::SendStartArrangingWithItem( } void GameMessages::SendPlayerSetCameraCyclingMode(const LWOOBJID& objectID, const SystemAddress& sysAddr, - bool bAllowCyclingWhileDeadOnly, eCyclingMode cyclingMode) { + bool bAllowCyclingWhileDeadOnly, eCyclingMode cyclingMode) { CBITSTREAM - CMSGHEADER + CMSGHEADER - bitStream.Write(objectID); + bitStream.Write(objectID); bitStream.Write(GAME_MSG_PLAYER_SET_CAMERA_CYCLING_MODE); bitStream.Write(bAllowCyclingWhileDeadOnly); @@ -286,9 +285,9 @@ void GameMessages::SendPlayerSetCameraCyclingMode(const LWOOBJID& objectID, cons void GameMessages::SendPlayNDAudioEmitter(Entity* entity, const SystemAddress& sysAddr, std::string audioGUID) { CBITSTREAM - CMSGHEADER + CMSGHEADER - bitStream.Write(entity->GetObjectID()); + bitStream.Write(entity->GetObjectID()); bitStream.Write((uint16_t)GAME_MSG_PLAY_ND_AUDIO_EMITTER); bitStream.Write0(); bitStream.Write0(); @@ -324,15 +323,14 @@ void GameMessages::SendStartPathing(Entity* entity) { } void GameMessages::SendPlatformResync(Entity* entity, const SystemAddress& sysAddr, bool bStopAtDesiredWaypoint, - int iIndex, int iDesiredWaypointIndex, int nextIndex, - MovementPlatformState movementState) { + int iIndex, int iDesiredWaypointIndex, int nextIndex, + MovementPlatformState movementState) { CBITSTREAM - CMSGHEADER + CMSGHEADER - const auto lot = entity->GetLOT(); + const auto lot = entity->GetLOT(); - if (lot == 12341 || lot == 5027 || lot == 5028 || lot == 14335 || lot == 14447 || lot == 14449) - { + if (lot == 12341 || lot == 5027 || lot == 5028 || lot == 14335 || lot == 14447 || lot == 14449) { iDesiredWaypointIndex = 0; iIndex = 0; nextIndex = 0; @@ -380,24 +378,24 @@ void GameMessages::SendPlatformResync(Entity* entity, const SystemAddress& sysAd void GameMessages::SendRestoreToPostLoadStats(Entity* entity, const SystemAddress& sysAddr) { CBITSTREAM - CMSGHEADER - bitStream.Write(entity->GetObjectID()); + CMSGHEADER + bitStream.Write(entity->GetObjectID()); bitStream.Write(GAME_MSG::GAME_MSG_RESTORE_TO_POST_LOAD_STATS); SEND_PACKET } void GameMessages::SendServerDoneLoadingAllObjects(Entity* entity, const SystemAddress& sysAddr) { CBITSTREAM - CMSGHEADER - bitStream.Write(entity->GetObjectID()); + CMSGHEADER + bitStream.Write(entity->GetObjectID()); bitStream.Write(GAME_MSG::GAME_MSG_SERVER_DONE_LOADING_ALL_OBJECTS); SEND_PACKET } void GameMessages::SendChatModeUpdate(const LWOOBJID& objectID, uint8_t level) { CBITSTREAM - CMSGHEADER - bitStream.Write(objectID); + CMSGHEADER + bitStream.Write(objectID); bitStream.Write((uint16_t)GAME_MSG_UPDATE_CHAT_MODE); bitStream.Write(level); SEND_PACKET_BROADCAST @@ -405,8 +403,8 @@ void GameMessages::SendChatModeUpdate(const LWOOBJID& objectID, uint8_t level) { void GameMessages::SendGMLevelBroadcast(const LWOOBJID& objectID, uint8_t level) { CBITSTREAM - CMSGHEADER - bitStream.Write(objectID); + CMSGHEADER + bitStream.Write(objectID); bitStream.Write((uint16_t)GAME_MSG_SET_GM_LEVEL); bitStream.Write1(); bitStream.Write(level); @@ -415,9 +413,9 @@ void GameMessages::SendGMLevelBroadcast(const LWOOBJID& objectID, uint8_t level) void GameMessages::SendAddItemToInventoryClientSync(Entity* entity, const SystemAddress& sysAddr, Item* item, const LWOOBJID& objectID, bool showFlyingLoot, int itemCount, LWOOBJID subKey, eLootSourceType lootSourceType) { CBITSTREAM - CMSGHEADER + CMSGHEADER - bitStream.Write(entity->GetObjectID()); + bitStream.Write(entity->GetObjectID()); bitStream.Write(static_cast(GAME_MSG_ADD_ITEM_TO_INVENTORY_CLIENT_SYNC)); bitStream.Write(item->GetBound()); bitStream.Write(item->GetInfo().isBOE); @@ -429,8 +427,7 @@ void GameMessages::SendAddItemToInventoryClientSync(Entity* entity, const System auto config = item->GetConfig(); - for (auto* data : config) - { + for (auto* data : config) { extraInfo.name += GeneralUtils::ASCIIToUTF16(data->GetString()) + u","; } @@ -475,9 +472,9 @@ void GameMessages::SendAddItemToInventoryClientSync(Entity* entity, const System void GameMessages::SendNotifyClientFlagChange(const LWOOBJID& objectID, int iFlagID, bool bFlag, const SystemAddress& sysAddr) { CBITSTREAM - CMSGHEADER + CMSGHEADER - bitStream.Write(objectID); + bitStream.Write(objectID); bitStream.Write((uint16_t)GAME_MSG_NOTIFY_CLIENT_FLAG_CHANGE); bitStream.Write(bFlag); bitStream.Write(iFlagID); @@ -485,17 +482,16 @@ void GameMessages::SendNotifyClientFlagChange(const LWOOBJID& objectID, int iFla SEND_PACKET } -void GameMessages::SendChangeObjectWorldState(const LWOOBJID& objectID, int state, const SystemAddress& sysAddr) -{ +void GameMessages::SendChangeObjectWorldState(const LWOOBJID& objectID, int state, const SystemAddress& sysAddr) { CBITSTREAM - CMSGHEADER + CMSGHEADER - bitStream.Write(objectID); + bitStream.Write(objectID); bitStream.Write((uint16_t)GAME_MSG_CHANGE_OBJECT_WORLD_STATE); bitStream.Write(state); if (sysAddr == UNASSIGNED_SYSTEM_ADDRESS) SEND_PACKET_BROADCAST - SEND_PACKET + SEND_PACKET } void GameMessages::SendOfferMission(const LWOOBJID& entity, const SystemAddress& sysAddr, int32_t missionID, const LWOOBJID& offererID) { @@ -506,9 +502,9 @@ void GameMessages::SendOfferMission(const LWOOBJID& entity, const SystemAddress& //Why is it like this? Because LU isn't just a clown, it's the entire circus. CBITSTREAM - CMSGHEADER + CMSGHEADER - bitStream.Write(offererID); + bitStream.Write(offererID); bitStream.Write(uint16_t(GAME_MSG_OFFER_MISSION)); bitStream.Write(missionID); bitStream.Write(offererID); @@ -530,9 +526,9 @@ void GameMessages::SendOfferMission(const LWOOBJID& entity, const SystemAddress& void GameMessages::SendNotifyMission(Entity* entity, const SystemAddress& sysAddr, int missionID, int missionState, bool sendingRewards) { CBITSTREAM - CMSGHEADER + CMSGHEADER - bitStream.Write(entity->GetObjectID()); + bitStream.Write(entity->GetObjectID()); bitStream.Write(uint16_t(GAME_MSG_NOTIFY_MISSION)); bitStream.Write(missionID); bitStream.Write(missionState); @@ -543,9 +539,9 @@ void GameMessages::SendNotifyMission(Entity* entity, const SystemAddress& sysAdd void GameMessages::SendNotifyMissionTask(Entity* entity, const SystemAddress& sysAddr, int missionID, int taskMask, std::vector updates) { CBITSTREAM - CMSGHEADER + CMSGHEADER - bitStream.Write(entity->GetObjectID()); + bitStream.Write(entity->GetObjectID()); bitStream.Write((uint16_t)GAME_MSG_NOTIFY_MISSION_TASK); bitStream.Write(missionID); @@ -561,9 +557,9 @@ void GameMessages::SendNotifyMissionTask(Entity* entity, const SystemAddress& sy void GameMessages::SendModifyLEGOScore(Entity* entity, const SystemAddress& sysAddr, int64_t score, eLootSourceType sourceType) { CBITSTREAM - CMSGHEADER + CMSGHEADER - bitStream.Write(entity->GetObjectID()); + bitStream.Write(entity->GetObjectID()); bitStream.Write((uint16_t)GAME_MSG_MODIFY_LEGO_SCORE); bitStream.Write(score); @@ -575,9 +571,9 @@ void GameMessages::SendModifyLEGOScore(Entity* entity, const SystemAddress& sysA void GameMessages::SendUIMessageServerToSingleClient(Entity* entity, const SystemAddress& sysAddr, const std::string& message, NDGFxValue args) { CBITSTREAM - CMSGHEADER + CMSGHEADER - bitStream.Write(entity->GetObjectID()); + bitStream.Write(entity->GetObjectID()); bitStream.Write((uint16_t)GAME_MSG_UI_MESSAGE_SERVER_TO_SINGLE_CLIENT); bitStream.Write(args); @@ -610,12 +606,11 @@ void GameMessages::SendUIMessageServerToAllClients(const std::string& message, N SEND_PACKET_BROADCAST; } -void GameMessages::SendPlayEmbeddedEffectOnAllClientsNearObject(Entity* entity, std::u16string effectName, const LWOOBJID& fromObjectID, float radius) -{ +void GameMessages::SendPlayEmbeddedEffectOnAllClientsNearObject(Entity* entity, std::u16string effectName, const LWOOBJID& fromObjectID, float radius) { CBITSTREAM - CMSGHEADER + CMSGHEADER - bitStream.Write(entity->GetObjectID()); + bitStream.Write(entity->GetObjectID()); bitStream.Write((uint16_t)GAME_MSG_PLAY_EMBEDDED_EFFECT_ON_ALL_CLIENTS_NEAR_OBJECT); bitStream.Write(static_cast(effectName.length())); @@ -668,9 +663,9 @@ void GameMessages::SendPlayFXEffect(const LWOOBJID& entity, int32_t effectID, co void GameMessages::SendStopFXEffect(Entity* entity, bool killImmediate, std::string name) { CBITSTREAM - CMSGHEADER + CMSGHEADER - bitStream.Write(entity->GetObjectID()); + bitStream.Write(entity->GetObjectID()); bitStream.Write(GAME_MSG::GAME_MSG_STOP_FX_EFFECT); bitStream.Write(killImmediate); @@ -682,9 +677,9 @@ void GameMessages::SendStopFXEffect(Entity* entity, bool killImmediate, std::str void GameMessages::SendBroadcastTextToChatbox(Entity* entity, const SystemAddress& sysAddr, const std::u16string& attrs, const std::u16string& wsText) { CBITSTREAM - CMSGHEADER + CMSGHEADER - bitStream.Write(entity->GetObjectID()); + bitStream.Write(entity->GetObjectID()); bitStream.Write((uint16_t)GAME_MSG::GAME_MSG_BROADCAST_TEXT_TO_CHATBOX); LWONameValue attribs; @@ -708,9 +703,9 @@ void GameMessages::SendBroadcastTextToChatbox(Entity* entity, const SystemAddres void GameMessages::SendSetCurrency(Entity* entity, int64_t currency, int lootType, const LWOOBJID& sourceID, const LOT& sourceLOT, int sourceTradeID, bool overrideCurrent, eLootSourceType sourceType) { CBITSTREAM - CMSGHEADER + CMSGHEADER - bitStream.Write(entity->GetObjectID()); + bitStream.Write(entity->GetObjectID()); bitStream.Write(uint16_t(GAME_MSG_SET_CURRENCY)); bitStream.Write(currency); @@ -736,12 +731,11 @@ void GameMessages::SendSetCurrency(Entity* entity, int64_t currency, int lootTyp SEND_PACKET } -void GameMessages::SendRebuildNotifyState(Entity* entity, int prevState, int state, const LWOOBJID& playerID) -{ +void GameMessages::SendRebuildNotifyState(Entity* entity, int prevState, int state, const LWOOBJID& playerID) { CBITSTREAM - CMSGHEADER + CMSGHEADER - bitStream.Write(entity->GetObjectID()); + bitStream.Write(entity->GetObjectID()); bitStream.Write((uint16_t)GAME_MSG_REBUILD_NOTIFY_STATE); bitStream.Write(prevState); @@ -751,12 +745,11 @@ void GameMessages::SendRebuildNotifyState(Entity* entity, int prevState, int sta SEND_PACKET_BROADCAST } -void GameMessages::SendEnableRebuild(Entity* entity, bool enable, bool fail, bool success, int failReason, float duration, const LWOOBJID& playerID) -{ +void GameMessages::SendEnableRebuild(Entity* entity, bool enable, bool fail, bool success, int failReason, float duration, const LWOOBJID& playerID) { CBITSTREAM - CMSGHEADER + CMSGHEADER - bitStream.Write(entity->GetObjectID()); + bitStream.Write(entity->GetObjectID()); bitStream.Write((uint16_t)GAME_MSG_ENABLE_REBUILD); bitStream.Write(enable); @@ -774,9 +767,9 @@ void GameMessages::SendEnableRebuild(Entity* entity, bool enable, bool fail, boo void GameMessages::SendTerminateInteraction(const LWOOBJID& objectID, eTerminateType type, const LWOOBJID& terminator) { CBITSTREAM - CMSGHEADER + CMSGHEADER - bitStream.Write(objectID); + bitStream.Write(objectID); bitStream.Write((uint16_t)GAME_MSG_TERMINATE_INTERACTION); bitStream.Write(terminator); @@ -785,12 +778,11 @@ void GameMessages::SendTerminateInteraction(const LWOOBJID& objectID, eTerminate SEND_PACKET_BROADCAST } -void GameMessages::SendDieNoImplCode(Entity* entity, const LWOOBJID& killerID, const LWOOBJID& lootOwnerID, eKillType killType, std::u16string deathType, float directionRelative_AngleY, float directionRelative_AngleXZ, float directionRelative_Force, bool bClientDeath, bool bSpawnLoot) -{ +void GameMessages::SendDieNoImplCode(Entity* entity, const LWOOBJID& killerID, const LWOOBJID& lootOwnerID, eKillType killType, std::u16string deathType, float directionRelative_AngleY, float directionRelative_AngleXZ, float directionRelative_Force, bool bClientDeath, bool bSpawnLoot) { CBITSTREAM - CMSGHEADER + CMSGHEADER - bitStream.Write(entity->GetObjectID()); + bitStream.Write(entity->GetObjectID()); bitStream.Write(uint16_t(GAME_MSG_DIE)); bitStream.Write(bClientDeath); bitStream.Write(bSpawnLoot); @@ -847,9 +839,9 @@ void GameMessages::SendDie(Entity* entity, const LWOOBJID& killerID, const LWOOB void GameMessages::SendSetInventorySize(Entity* entity, int invType, int size) { CBITSTREAM - CMSGHEADER + CMSGHEADER - bitStream.Write(entity->GetObjectID()); + bitStream.Write(entity->GetObjectID()); bitStream.Write(uint16_t(GAME_MSG_SET_INVENTORY_SIZE)); bitStream.Write(invType); bitStream.Write(size); @@ -858,12 +850,11 @@ void GameMessages::SendSetInventorySize(Entity* entity, int invType, int size) { SEND_PACKET } -void GameMessages::SendSetEmoteLockState(Entity* entity, bool bLock, int emoteID) -{ +void GameMessages::SendSetEmoteLockState(Entity* entity, bool bLock, int emoteID) { CBITSTREAM - CMSGHEADER + CMSGHEADER - bitStream.Write(entity->GetObjectID()); + bitStream.Write(entity->GetObjectID()); bitStream.Write(uint16_t(GAME_MSG_SET_EMOTE_LOCK_STATE)); bitStream.Write(bLock); bitStream.Write(emoteID); @@ -882,9 +873,9 @@ void GameMessages::SendSetJetPackMode(Entity* entity, bool use, bool bypassCheck */ CBITSTREAM - CMSGHEADER + CMSGHEADER - bitStream.Write(entity->GetObjectID()); + bitStream.Write(entity->GetObjectID()); bitStream.Write(uint16_t(GAME_MSG_SET_JET_PACK_MODE)); bitStream.Write(bypassChecks); @@ -938,12 +929,11 @@ void GameMessages::SendResurrect(Entity* entity) { SEND_PACKET_BROADCAST; } -void GameMessages::SendStop2DAmbientSound(Entity* entity, bool force, std::string audioGUID, bool result) -{ +void GameMessages::SendStop2DAmbientSound(Entity* entity, bool force, std::string audioGUID, bool result) { CBITSTREAM - CMSGHEADER + CMSGHEADER - bitStream.Write(entity->GetObjectID()); + bitStream.Write(entity->GetObjectID()); bitStream.Write((uint16_t)GAME_MSG_PLAY2_DAMBIENT_SOUND); uint32_t audioGUIDSize = audioGUID.size(); @@ -951,8 +941,7 @@ void GameMessages::SendStop2DAmbientSound(Entity* entity, bool force, std::strin bitStream.Write(force); bitStream.Write(audioGUIDSize); - for (uint32_t k = 0; k < audioGUIDSize; k++) - { + for (uint32_t k = 0; k < audioGUIDSize; k++) { bitStream.Write(static_cast(audioGUID[k])); } @@ -965,9 +954,9 @@ void GameMessages::SendStop2DAmbientSound(Entity* entity, bool force, std::strin void GameMessages::SendPlay2DAmbientSound(Entity* entity, std::string audioGUID, bool result) { CBITSTREAM - CMSGHEADER + CMSGHEADER - bitStream.Write(entity->GetObjectID()); + bitStream.Write(entity->GetObjectID()); bitStream.Write((uint16_t)GAME_MSG_PLAY2_DAMBIENT_SOUND); uint32_t audioGUIDSize = audioGUID.size(); @@ -984,9 +973,9 @@ void GameMessages::SendPlay2DAmbientSound(Entity* entity, std::string audioGUID, void GameMessages::SendSetNetworkScriptVar(Entity* entity, const SystemAddress& sysAddr, std::string data) { CBITSTREAM - CMSGHEADER + CMSGHEADER - bitStream.Write(entity->GetObjectID()); + bitStream.Write(entity->GetObjectID()); bitStream.Write((uint16_t)GAME_MSG_SET_NETWORK_SCRIPT_VAR); const auto u16Data = GeneralUtils::ASCIIToUTF16(data); @@ -1063,16 +1052,13 @@ void GameMessages::SendDropClientLoot(Entity* entity, const LWOOBJID& sourceID, auto* team = TeamManager::Instance()->GetTeam(owner); // Currency and powerups should not sync - if (team != nullptr && currency == 0) - { + if (team != nullptr && currency == 0) { CDObjectsTable* objectsTable = CDClientManager::Instance()->GetTable("Objects"); const CDObjects& object = objectsTable->GetByID(item); - if (object.type != "Powerup") - { - for (const auto memberId : team->members) - { + if (object.type != "Powerup") { + for (const auto memberId : team->members) { auto* member = EntityManager::Instance()->GetEntity(memberId); if (member == nullptr) continue; @@ -1190,9 +1176,9 @@ void GameMessages::SendRemoveSkill(Entity* entity, TSkillID skillID) { void GameMessages::SendFinishArrangingWithItem(Entity* entity, const LWOOBJID& buildArea) { CBITSTREAM - CMSGHEADER + CMSGHEADER - bool bFirstTime = true; + bool bFirstTime = true; const LWOOBJID& buildAreaID = buildArea; int newSourceBAG = 0; const LWOOBJID& newSourceID = LWOOBJID_EMPTY; @@ -1232,9 +1218,9 @@ void GameMessages::SendFinishArrangingWithItem(Entity* entity, const LWOOBJID& b void GameMessages::SendModularBuildEnd(Entity* entity) { CBITSTREAM - CMSGHEADER + CMSGHEADER - bitStream.Write(entity->GetObjectID()); + bitStream.Write(entity->GetObjectID()); bitStream.Write(GAME_MSG::GAME_MSG_MODULAR_BUILD_END); SystemAddress sysAddr = entity->GetSystemAddress(); @@ -1243,9 +1229,9 @@ void GameMessages::SendModularBuildEnd(Entity* entity) { void GameMessages::SendVendorOpenWindow(Entity* entity, const SystemAddress& sysAddr) { CBITSTREAM - CMSGHEADER + CMSGHEADER - bitStream.Write(entity->GetObjectID()); + bitStream.Write(entity->GetObjectID()); bitStream.Write(GAME_MSG::GAME_MSG_VENDOR_OPEN_WINDOW); SEND_PACKET @@ -1253,9 +1239,9 @@ void GameMessages::SendVendorOpenWindow(Entity* entity, const SystemAddress& sys void GameMessages::SendVendorStatusUpdate(Entity* entity, const SystemAddress& sysAddr, bool bUpdateOnly) { CBITSTREAM - CMSGHEADER + CMSGHEADER - VendorComponent* vendor = static_cast(entity->GetComponent(COMPONENT_TYPE_VENDOR)); + VendorComponent* vendor = static_cast(entity->GetComponent(COMPONENT_TYPE_VENDOR)); if (!vendor) return; std::map vendorItems = vendor->GetInventory(); @@ -1272,14 +1258,14 @@ void GameMessages::SendVendorStatusUpdate(Entity* entity, const SystemAddress& s } if (sysAddr == UNASSIGNED_SYSTEM_ADDRESS) SEND_PACKET_BROADCAST - SEND_PACKET + SEND_PACKET } void GameMessages::SendVendorTransactionResult(Entity* entity, const SystemAddress& sysAddr) { CBITSTREAM - CMSGHEADER + CMSGHEADER - int iResult = 0x02; // success, seems to be the only relevant one + int iResult = 0x02; // success, seems to be the only relevant one bitStream.Write(entity->GetObjectID()); bitStream.Write(GAME_MSG::GAME_MSG_VENDOR_TRANSACTION_RESULT); @@ -1290,9 +1276,9 @@ void GameMessages::SendVendorTransactionResult(Entity* entity, const SystemAddre void GameMessages::SendRemoveItemFromInventory(Entity* entity, const SystemAddress& sysAddr, LWOOBJID objectID, LOT templateID, int inventoryType, uint32_t stackCount, uint32_t stackRemaining) { CBITSTREAM - CMSGHEADER - // this is used for a lot more than just inventory trashing (trades, vendors, etc.) but for now since it's just used for that, that's all im going to implement - bool bConfirmed = true; + CMSGHEADER + // this is used for a lot more than just inventory trashing (trades, vendors, etc.) but for now since it's just used for that, that's all im going to implement + bool bConfirmed = true; bool bDeleteItem = true; bool bOutSuccess = false; int eInvType = inventoryType; @@ -1337,9 +1323,9 @@ void GameMessages::SendRemoveItemFromInventory(Entity* entity, const SystemAddre void GameMessages::SendConsumeClientItem(Entity* entity, bool bSuccess, LWOOBJID item) { CBITSTREAM - CMSGHEADER + CMSGHEADER - bitStream.Write(entity->GetObjectID()); + bitStream.Write(entity->GetObjectID()); bitStream.Write(GAME_MSG_CONSUME_CLIENT_ITEM); bitStream.Write(bSuccess); bitStream.Write(item); @@ -1350,9 +1336,9 @@ void GameMessages::SendConsumeClientItem(Entity* entity, bool bSuccess, LWOOBJID void GameMessages::SendUseItemResult(Entity* entity, LOT templateID, bool useItemResult) { CBITSTREAM - CMSGHEADER + CMSGHEADER - bitStream.Write(entity->GetObjectID()); + bitStream.Write(entity->GetObjectID()); bitStream.Write(GAME_MSG_USE_ITEM_RESULT); bitStream.Write(templateID); bitStream.Write(useItemResult); @@ -1363,9 +1349,9 @@ void GameMessages::SendUseItemResult(Entity* entity, LOT templateID, bool useIte void GameMessages::SendUseItemRequirementsResponse(LWOOBJID objectID, const SystemAddress& sysAddr, UseItemResponse itemResponse) { CBITSTREAM - CMSGHEADER + CMSGHEADER - bitStream.Write(objectID); + bitStream.Write(objectID); bitStream.Write(GAME_MSG::GAME_MSG_USE_ITEM_REQUIREMENTS_RESPONSE); bitStream.Write(itemResponse); @@ -1375,9 +1361,9 @@ void GameMessages::SendUseItemRequirementsResponse(LWOOBJID objectID, const Syst void GameMessages::SendMoveInventoryBatch(Entity* entity, uint32_t stackCount, int srcInv, int dstInv, const LWOOBJID& iObjID) { CBITSTREAM - CMSGHEADER + CMSGHEADER - InventoryComponent* inv = static_cast(entity->GetComponent(COMPONENT_TYPE_INVENTORY)); + InventoryComponent* inv = static_cast(entity->GetComponent(COMPONENT_TYPE_INVENTORY)); if (!inv) return; Item* itemStack = inv->FindItemById(iObjID); @@ -1397,15 +1383,13 @@ void GameMessages::SendMoveInventoryBatch(Entity* entity, uint32_t stackCount, i bitStream.Write(bOutSuccess); if (count == 1) { bitStream.Write0(); - } - else { + } else { bitStream.Write1(); bitStream.Write(count); } if (dstBag == 0) { bitStream.Write0(); - } - else { + } else { bitStream.Write1(); bitStream.Write(dstBag); } @@ -1413,8 +1397,7 @@ void GameMessages::SendMoveInventoryBatch(Entity* entity, uint32_t stackCount, i bitStream.Write(showFlyingLoot); if (srcBag == 0) { bitStream.Write0(); - } - else { + } else { bitStream.Write1(); bitStream.Write(srcBag); } @@ -1428,9 +1411,9 @@ void GameMessages::SendMoveInventoryBatch(Entity* entity, uint32_t stackCount, i void GameMessages::SendMatchResponse(Entity* entity, const SystemAddress& sysAddr, int response) { CBITSTREAM - CMSGHEADER + CMSGHEADER - bitStream.Write(entity->GetObjectID()); + bitStream.Write(entity->GetObjectID()); bitStream.Write(GAME_MSG::GAME_MSG_MATCH_RESPONSE); bitStream.Write(response); @@ -1439,9 +1422,9 @@ void GameMessages::SendMatchResponse(Entity* entity, const SystemAddress& sysAdd void GameMessages::SendMatchUpdate(Entity* entity, const SystemAddress& sysAddr, std::string data, int type) { CBITSTREAM - CMSGHEADER + CMSGHEADER - bitStream.Write(entity->GetObjectID()); + bitStream.Write(entity->GetObjectID()); bitStream.Write(GAME_MSG::GAME_MSG_MATCH_UPDATE); bitStream.Write(uint32_t(data.size())); for (char character : data) { @@ -1454,13 +1437,13 @@ void GameMessages::SendMatchUpdate(Entity* entity, const SystemAddress& sysAddr, } void GameMessages::SendRequestActivitySummaryLeaderboardData(const LWOOBJID& objectID, const LWOOBJID& targetID, - const SystemAddress& sysAddr, const int32_t& gameID, - const int32_t& queryType, const int32_t& resultsEnd, - const int32_t& resultsStart, bool weekly) { + const SystemAddress& sysAddr, const int32_t& gameID, + const int32_t& queryType, const int32_t& resultsEnd, + const int32_t& resultsStart, bool weekly) { CBITSTREAM - CMSGHEADER + CMSGHEADER - bitStream.Write(objectID); + bitStream.Write(objectID); bitStream.Write(GAME_MSG::GAME_MSG_REQUEST_ACTIVITY_SUMMARY_LEADERBOARD_DATA); bitStream.Write(gameID != 0); @@ -1491,9 +1474,9 @@ void GameMessages::SendRequestActivitySummaryLeaderboardData(const LWOOBJID& obj void GameMessages::SendActivityPause(LWOOBJID objectId, bool pause, const SystemAddress& sysAddr) { CBITSTREAM - CMSGHEADER + CMSGHEADER - bitStream.Write(objectId); + bitStream.Write(objectId); bitStream.Write(GAME_MSG::GAME_MSG_ACTIVITY_PAUSE); bitStream.Write(pause); @@ -1503,9 +1486,9 @@ void GameMessages::SendActivityPause(LWOOBJID objectId, bool pause, const System void GameMessages::SendStartActivityTime(LWOOBJID objectId, float_t startTime, const SystemAddress& sysAddr) { CBITSTREAM - CMSGHEADER + CMSGHEADER - bitStream.Write(objectId); + bitStream.Write(objectId); bitStream.Write(GAME_MSG::GAME_MSG_START_ACTIVITY_TIME); bitStream.Write(startTime); @@ -1515,9 +1498,9 @@ void GameMessages::SendStartActivityTime(LWOOBJID objectId, float_t startTime, c void GameMessages::SendRequestActivityEnter(LWOOBJID objectId, const SystemAddress& sysAddr, bool bStart, LWOOBJID userID) { CBITSTREAM - CMSGHEADER + CMSGHEADER - bitStream.Write(objectId); + bitStream.Write(objectId); bitStream.Write(GAME_MSG::GAME_MSG_REQUEST_ACTIVITY_ENTER); bitStream.Write(bStart); bitStream.Write(userID); @@ -1528,9 +1511,9 @@ void GameMessages::SendRequestActivityEnter(LWOOBJID objectId, const SystemAddre void GameMessages::NotifyLevelRewards(LWOOBJID objectID, const SystemAddress& sysAddr, int level, bool sending_rewards) { CBITSTREAM - CMSGHEADER + CMSGHEADER - bitStream.Write(objectID); + bitStream.Write(objectID); bitStream.Write((uint16_t)GAME_MSG::GAME_MSG_NOTIFY_LEVEL_REWARDS); bitStream.Write(level); @@ -1540,19 +1523,18 @@ void GameMessages::NotifyLevelRewards(LWOOBJID objectID, const SystemAddress& sy } void GameMessages::SendSetShootingGalleryParams(LWOOBJID objectId, const SystemAddress& sysAddr, - float cameraFOV, - float cooldown, - float minDistance, - NiPoint3 muzzlePosOffset, - NiPoint3 playerPosOffset, - float projectileVelocity, - float timeLimit, - bool bUseLeaderboards) -{ + float cameraFOV, + float cooldown, + float minDistance, + NiPoint3 muzzlePosOffset, + NiPoint3 playerPosOffset, + float projectileVelocity, + float timeLimit, + bool bUseLeaderboards) { CBITSTREAM - CMSGHEADER + CMSGHEADER - bitStream.Write(objectId); + bitStream.Write(objectId); bitStream.Write(GAME_MSG::GAME_MSG_SET_SHOOTING_GALLERY_PARAMS); /* bitStream.Write(cameraFOV); @@ -1580,15 +1562,14 @@ void GameMessages::SendSetShootingGalleryParams(LWOOBJID objectId, const SystemA void GameMessages::SendNotifyClientShootingGalleryScore(LWOOBJID objectId, const SystemAddress& sysAddr, - float addTime, - int32_t score, - LWOOBJID target, - NiPoint3 targetPos) -{ + float addTime, + int32_t score, + LWOOBJID target, + NiPoint3 targetPos) { CBITSTREAM - CMSGHEADER + CMSGHEADER - bitStream.Write(objectId); + bitStream.Write(objectId); bitStream.Write(GAME_MSG::GAME_MSG_NOTIFY_CLIENT_SHOOTING_GALLERY_SCORE); bitStream.Write(addTime); bitStream.Write(score); @@ -1600,8 +1581,7 @@ void GameMessages::SendNotifyClientShootingGalleryScore(LWOOBJID objectId, const } -void GameMessages::HandleUpdateShootingGalleryRotation(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr) -{ +void GameMessages::HandleUpdateShootingGalleryRotation(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr) { float angle = 0.0f; NiPoint3 facing = NiPoint3::ZERO; NiPoint3 muzzlePos = NiPoint3::ZERO; @@ -1612,15 +1592,15 @@ void GameMessages::HandleUpdateShootingGalleryRotation(RakNet::BitStream* inStre void GameMessages::HandleActivitySummaryLeaderboardData(RakNet::BitStream* instream, Entity* entity, - const SystemAddress& sysAddr) { + const SystemAddress& sysAddr) { Game::logger->Log("AGS", "We got mail!"); } void GameMessages::SendActivitySummaryLeaderboardData(const LWOOBJID& objectID, const Leaderboard* leaderboard, const SystemAddress& sysAddr) { CBITSTREAM - CMSGHEADER + CMSGHEADER - bitStream.Write(objectID); + bitStream.Write(objectID); bitStream.Write(GAME_MSG::GAME_MSG_SEND_ACTIVITY_SUMMARY_LEADERBOARD_DATA); bitStream.Write(leaderboard->GetGameID()); @@ -1653,7 +1633,7 @@ void GameMessages::HandleRequestActivitySummaryLeaderboardData(RakNet::BitStream int32_t resultsStart = 0; if (inStream->ReadBit()) inStream->Read(resultsStart); - LWOOBJID target {}; + LWOOBJID target{}; inStream->Read(target); bool weekly = inStream->ReadBit(); @@ -1663,7 +1643,7 @@ void GameMessages::HandleRequestActivitySummaryLeaderboardData(RakNet::BitStream delete leaderboard; } -void GameMessages::HandleActivityStateChangeRequest(RakNet::BitStream *inStream, Entity *entity) { +void GameMessages::HandleActivityStateChangeRequest(RakNet::BitStream* inStream, Entity* entity) { LWOOBJID objectID; inStream->Read(objectID); @@ -1725,8 +1705,8 @@ void GameMessages::SendStartCelebrationEffect(Entity* entity, const SystemAddres void GameMessages::SendSetRailMovement(const LWOOBJID& objectID, bool pathGoForward, std::u16string pathName, - uint32_t pathStart, const SystemAddress& sysAddr, int32_t railActivatorComponentID, - LWOOBJID railActivatorObjectID) { + uint32_t pathStart, const SystemAddress& sysAddr, int32_t railActivatorComponentID, + LWOOBJID railActivatorObjectID) { CBITSTREAM; CMSGHEADER; @@ -1756,11 +1736,11 @@ void GameMessages::SendSetRailMovement(const LWOOBJID& objectID, bool pathGoForw SEND_PACKET; } -void GameMessages::SendStartRailMovement(const LWOOBJID &objectID, std::u16string pathName, std::u16string startSound, - std::u16string loopSound, std::u16string stopSound, const SystemAddress& sysAddr, - uint32_t pathStart, bool goForward, bool damageImmune, bool noAggro, bool notifyActor, - bool showNameBillboard, bool cameraLocked, bool collisionEnabled, bool useDB, - int32_t railComponentID, LWOOBJID railActivatorObjectID) { +void GameMessages::SendStartRailMovement(const LWOOBJID& objectID, std::u16string pathName, std::u16string startSound, + std::u16string loopSound, std::u16string stopSound, const SystemAddress& sysAddr, + uint32_t pathStart, bool goForward, bool damageImmune, bool noAggro, bool notifyActor, + bool showNameBillboard, bool cameraLocked, bool collisionEnabled, bool useDB, + int32_t railComponentID, LWOOBJID railActivatorObjectID) { CBITSTREAM; CMSGHEADER; @@ -1848,8 +1828,8 @@ void GameMessages::SendNotifyClientObject(const LWOOBJID& objectID, std::u16stri } void GameMessages::SendNotifyClientZoneObject(const LWOOBJID& objectID, const std::u16string& name, int param1, - int param2, const LWOOBJID& paramObj, const std::string& paramStr, - const SystemAddress& sysAddr) { + int param2, const LWOOBJID& paramObj, const std::string& paramStr, + const SystemAddress& sysAddr) { CBITSTREAM; CMSGHEADER; @@ -1875,8 +1855,7 @@ void GameMessages::SendNotifyClientZoneObject(const LWOOBJID& objectID, const st } void GameMessages::SendNotifyClientFailedPrecondition(LWOOBJID objectId, const SystemAddress& sysAddr, - const std::u16string& failedReason, int preconditionID) -{ + const std::u16string& failedReason, int preconditionID) { CBITSTREAM; CMSGHEADER; @@ -1894,8 +1873,7 @@ void GameMessages::SendNotifyClientFailedPrecondition(LWOOBJID objectId, const S SEND_PACKET; } -void GameMessages::SendToggleGMInvis(LWOOBJID objectId, bool enabled, const SystemAddress& sysAddr) -{ +void GameMessages::SendToggleGMInvis(LWOOBJID objectId, bool enabled, const SystemAddress& sysAddr) { CBITSTREAM; CMSGHEADER; @@ -1907,8 +1885,7 @@ void GameMessages::SendToggleGMInvis(LWOOBJID objectId, bool enabled, const Syst SEND_PACKET; } -void GameMessages::SendSetName(LWOOBJID objectID, std::u16string name, const SystemAddress& sysAddr) -{ +void GameMessages::SendSetName(LWOOBJID objectID, std::u16string name, const SystemAddress& sysAddr) { CBITSTREAM; CMSGHEADER; @@ -1951,8 +1928,7 @@ void GameMessages::SendBBBSaveResponse(const LWOOBJID& objectId, const LWOOBJID& // Property -void GameMessages::SendOpenPropertyVendor(const LWOOBJID objectId, const SystemAddress& sysAddr) -{ +void GameMessages::SendOpenPropertyVendor(const LWOOBJID objectId, const SystemAddress& sysAddr) { CBITSTREAM; CMSGHEADER; @@ -1963,20 +1939,18 @@ void GameMessages::SendOpenPropertyVendor(const LWOOBJID objectId, const SystemA SEND_PACKET; } -void GameMessages::SendOpenPropertyManagment(const LWOOBJID objectId, const SystemAddress& sysAddr) -{ +void GameMessages::SendOpenPropertyManagment(const LWOOBJID objectId, const SystemAddress& sysAddr) { CBITSTREAM - CMSGHEADER + CMSGHEADER - bitStream.Write(PropertyManagementComponent::Instance()->GetParent()->GetObjectID()); + bitStream.Write(PropertyManagementComponent::Instance()->GetParent()->GetObjectID()); bitStream.Write(GAME_MSG::GAME_MSG_OPEN_PROPERTY_MANAGEMENT); if (sysAddr == UNASSIGNED_SYSTEM_ADDRESS) SEND_PACKET_BROADCAST; SEND_PACKET; } -void GameMessages::SendDownloadPropertyData(const LWOOBJID objectId, const PropertyDataMessage& data, const SystemAddress& sysAddr) -{ +void GameMessages::SendDownloadPropertyData(const LWOOBJID objectId, const PropertyDataMessage& data, const SystemAddress& sysAddr) { CBITSTREAM; CMSGHEADER; @@ -1991,8 +1965,7 @@ void GameMessages::SendDownloadPropertyData(const LWOOBJID objectId, const Prope SEND_PACKET; } -void GameMessages::SendPropertyRentalResponse(const LWOOBJID objectId, const LWOCLONEID cloneId, const uint32_t code, const LWOOBJID propertyId, const int64_t rentDue, const SystemAddress& sysAddr) -{ +void GameMessages::SendPropertyRentalResponse(const LWOOBJID objectId, const LWOCLONEID cloneId, const uint32_t code, const LWOOBJID propertyId, const int64_t rentDue, const SystemAddress& sysAddr) { CBITSTREAM; CMSGHEADER; @@ -2023,8 +1996,7 @@ void GameMessages::SendLockNodeRotation(Entity* entity, std::string nodeName) { SEND_PACKET_BROADCAST; } -void GameMessages::SendSetBuildModeConfirmed(LWOOBJID objectId, const SystemAddress& sysAddr, bool start, bool warnVisitors, bool modePaused, int32_t modeValue, LWOOBJID playerId, NiPoint3 startPos) -{ +void GameMessages::SendSetBuildModeConfirmed(LWOOBJID objectId, const SystemAddress& sysAddr, bool start, bool warnVisitors, bool modePaused, int32_t modeValue, LWOOBJID playerId, NiPoint3 startPos) { CBITSTREAM; CMSGHEADER; @@ -2044,8 +2016,7 @@ void GameMessages::SendSetBuildModeConfirmed(LWOOBJID objectId, const SystemAddr SEND_PACKET; } -void GameMessages::SendGetModelsOnProperty(LWOOBJID objectId, std::map models, const SystemAddress& sysAddr) -{ +void GameMessages::SendGetModelsOnProperty(LWOOBJID objectId, std::map models, const SystemAddress& sysAddr) { CBITSTREAM; CMSGHEADER; @@ -2054,8 +2025,7 @@ void GameMessages::SendGetModelsOnProperty(LWOOBJID objectId, std::map(models.size())); - for (const auto& pair : models) - { + for (const auto& pair : models) { bitStream.Write(pair.first); bitStream.Write(pair.second); } @@ -2066,8 +2036,7 @@ void GameMessages::SendGetModelsOnProperty(LWOOBJID objectId, std::mapSetPrivacyOption(static_cast(accessType)); } -void GameMessages::HandleUpdatePropertyOrModelForFilterCheck(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr) -{ +void GameMessages::HandleUpdatePropertyOrModelForFilterCheck(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr) { bool isProperty{}; LWOOBJID objectId{}; LWOOBJID playerId{}; @@ -2191,16 +2150,14 @@ void GameMessages::HandleUpdatePropertyOrModelForFilterCheck(RakNet::BitStream* inStream->Read(worldId); inStream->Read(descriptionLength); - for (uint32_t i = 0; i < descriptionLength; ++i) - { + for (uint32_t i = 0; i < descriptionLength; ++i) { uint16_t character; inStream->Read(character); description.push_back(character); } inStream->Read(nameLength); - for (uint32_t i = 0; i < nameLength; ++i) - { + for (uint32_t i = 0; i < nameLength; ++i) { uint16_t character; inStream->Read(character); name.push_back(character); @@ -2209,8 +2166,7 @@ void GameMessages::HandleUpdatePropertyOrModelForFilterCheck(RakNet::BitStream* PropertyManagementComponent::Instance()->UpdatePropertyDetails(GeneralUtils::UTF16ToWTF8(name), GeneralUtils::UTF16ToWTF8(description)); } -void GameMessages::HandleQueryPropertyData(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr) -{ +void GameMessages::HandleQueryPropertyData(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr) { Game::logger->Log("HandleQueryPropertyData", "Entity (%i) requesting data", entity->GetLOT()); /* @@ -2238,8 +2194,7 @@ void GameMessages::HandleQueryPropertyData(RakNet::BitStream* inStream, Entity* } } -void GameMessages::HandleSetBuildMode(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr) -{ +void GameMessages::HandleSetBuildMode(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr) { bool start{}; int32_t distanceType = -1; bool modePaused{}; @@ -2275,10 +2230,8 @@ void GameMessages::HandleSetBuildMode(RakNet::BitStream* inStream, Entity* entit SendSetBuildModeConfirmed(entity->GetObjectID(), UNASSIGNED_SYSTEM_ADDRESS, start, false, modePaused, modeValue, playerId, startPosition); } -void GameMessages::HandleStartBuildingWithItem(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr) -{ - if (!entity->HasComponent(COMPONENT_TYPE_PROPERTY_MANAGEMENT)) - { +void GameMessages::HandleStartBuildingWithItem(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr) { + if (!entity->HasComponent(COMPONENT_TYPE_PROPERTY_MANAGEMENT)) { return; } @@ -2331,22 +2284,19 @@ void GameMessages::HandleStartBuildingWithItem(RakNet::BitStream* inStream, Enti ); } -void GameMessages::HandlePropertyEditorBegin(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr) -{ +void GameMessages::HandlePropertyEditorBegin(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr) { PropertyManagementComponent::Instance()->OnStartBuilding(); dZoneManager::Instance()->GetZoneControlObject()->OnZonePropertyEditBegin(); } -void GameMessages::HandlePropertyEditorEnd(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr) -{ +void GameMessages::HandlePropertyEditorEnd(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr) { PropertyManagementComponent::Instance()->OnFinishBuilding(); dZoneManager::Instance()->GetZoneControlObject()->OnZonePropertyEditEnd(); } -void GameMessages::HandlePropertyContentsFromClient(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr) -{ +void GameMessages::HandlePropertyContentsFromClient(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr) { User* user = UserManager::Instance()->GetUser(sysAddr); Entity* player = EntityManager::Instance()->GetEntity(user->GetLoggedInChar()); @@ -2354,13 +2304,11 @@ void GameMessages::HandlePropertyContentsFromClient(RakNet::BitStream* inStream, SendGetModelsOnProperty(player->GetObjectID(), PropertyManagementComponent::Instance()->GetModels(), UNASSIGNED_SYSTEM_ADDRESS); } -void GameMessages::HandlePropertyModelEquipped(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr) -{ +void GameMessages::HandlePropertyModelEquipped(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr) { dZoneManager::Instance()->GetZoneControlObject()->OnZonePropertyModelEquipped(); } -void GameMessages::HandlePlacePropertyModel(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr) -{ +void GameMessages::HandlePlacePropertyModel(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr) { LWOOBJID model; inStream->Read(model); @@ -2368,8 +2316,7 @@ void GameMessages::HandlePlacePropertyModel(RakNet::BitStream* inStream, Entity* PropertyManagementComponent::Instance()->UpdateModelPosition(model, NiPoint3::ZERO, NiQuaternion::IDENTITY); } -void GameMessages::HandleUpdatePropertyModel(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr) -{ +void GameMessages::HandleUpdatePropertyModel(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr) { LWOOBJID model; NiPoint3 position; NiQuaternion rotation = NiQuaternion::IDENTITY; @@ -2377,26 +2324,22 @@ void GameMessages::HandleUpdatePropertyModel(RakNet::BitStream* inStream, Entity inStream->Read(model); inStream->Read(position); - if (inStream->ReadBit()) - { + if (inStream->ReadBit()) { inStream->Read(rotation); } PropertyManagementComponent::Instance()->UpdateModelPosition(model, position, rotation); } -void GameMessages::HandleDeletePropertyModel(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr) -{ +void GameMessages::HandleDeletePropertyModel(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr) { LWOOBJID model = LWOOBJID_EMPTY; int deleteReason = 0; - if (inStream->ReadBit()) - { + if (inStream->ReadBit()) { inStream->Read(model); } - if (inStream->ReadBit()) - { + if (inStream->ReadBit()) { inStream->Read(deleteReason); } @@ -2420,9 +2363,9 @@ void GameMessages::HandleBBBLoadItemRequest(RakNet::BitStream* inStream, Entity* void GameMessages::SendSmash(Entity* entity, float force, float ghostOpacity, LWOOBJID killerID, bool ignoreObjectVisibility) { CBITSTREAM - CMSGHEADER + CMSGHEADER - bitStream.Write(entity->GetObjectID()); + bitStream.Write(entity->GetObjectID()); bitStream.Write(GAME_MSG::GAME_MSG_SMASH); bitStream.Write(ignoreObjectVisibility); @@ -2435,9 +2378,9 @@ void GameMessages::SendSmash(Entity* entity, float force, float ghostOpacity, LW void GameMessages::SendUnSmash(Entity* entity, LWOOBJID builderID, float duration) { CBITSTREAM - CMSGHEADER + CMSGHEADER - bitStream.Write(entity->GetObjectID()); + bitStream.Write(entity->GetObjectID()); bitStream.Write(GAME_MSG::GAME_MSG_UNSMASH); bitStream.Write(builderID != LWOOBJID_EMPTY); @@ -2563,7 +2506,7 @@ void GameMessages::HandleBBBSaveRequest(RakNet::BitStream* inStream, Entity* ent auto query = CDClientDatabase::CreatePreppedStmt( "SELECT id FROM PropertyTemplate WHERE mapID = ?;"); - query.bind(1, (int) zoneId); + query.bind(1, (int)zoneId); auto result = query.execQuery(); @@ -2707,13 +2650,12 @@ void GameMessages::HandleBBBSaveRequest(RakNet::BitStream* inStream, Entity* ent //there was an issue with builds not appearing since it was placed above ConstructEntity. PropertyManagementComponent::Instance()->AddModel(newEntity->GetObjectID(), newIDL); } + }); }); }); - }); } -void GameMessages::HandlePropertyEntranceSync(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr) -{ +void GameMessages::HandlePropertyEntranceSync(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr) { bool includeNullAddress{}; bool includeNullDescription{}; bool playerOwn{}; @@ -2735,8 +2677,7 @@ void GameMessages::HandlePropertyEntranceSync(RakNet::BitStream* inStream, Entit inStream->Read(startIndex); inStream->Read(filterTextLength); - for (auto i = 0u; i < filterTextLength; i++) - { + for (auto i = 0u; i < filterTextLength; i++) { char c; inStream->Read(c); filterText.push_back(c); @@ -2762,8 +2703,7 @@ void GameMessages::HandlePropertyEntranceSync(RakNet::BitStream* inStream, Entit ); } -void GameMessages::HandleEnterProperty(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr) -{ +void GameMessages::HandleEnterProperty(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr) { uint32_t index{}; bool returnToZone{}; @@ -2784,8 +2724,7 @@ void GameMessages::HandleEnterProperty(RakNet::BitStream* inStream, Entity* enti } } -void GameMessages::HandleSetConsumableItem(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr) -{ +void GameMessages::HandleSetConsumableItem(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr) { LOT lot; inStream->Read(lot); @@ -2798,10 +2737,9 @@ void GameMessages::HandleSetConsumableItem(RakNet::BitStream* inStream, Entity* } void GameMessages::SendPlayCinematic(LWOOBJID objectId, std::u16string pathName, const SystemAddress& sysAddr, - bool allowGhostUpdates, bool bCloseMultiInteract, bool bSendServerNotify, bool bUseControlledObjectForAudioListener, - int endBehavior, bool hidePlayerDuringCine, float leadIn, bool leavePlayerLockedWhenFinished, - bool lockPlayer, bool result, bool skipIfSamePath, float startTimeAdvance) -{ + bool allowGhostUpdates, bool bCloseMultiInteract, bool bSendServerNotify, bool bUseControlledObjectForAudioListener, + int endBehavior, bool hidePlayerDuringCine, float leadIn, bool leavePlayerLockedWhenFinished, + bool lockPlayer, bool result, bool skipIfSamePath, float startTimeAdvance) { CBITSTREAM; CMSGHEADER; @@ -2840,8 +2778,7 @@ void GameMessages::SendPlayCinematic(LWOOBJID objectId, std::u16string pathName, } void GameMessages::SendEndCinematic(LWOOBJID objectId, std::u16string pathName, const SystemAddress& sysAddr, - float leadOut, bool leavePlayerLocked) -{ + float leadOut, bool leavePlayerLocked) { CBITSTREAM; CMSGHEADER; @@ -2862,7 +2799,7 @@ void GameMessages::SendEndCinematic(LWOOBJID objectId, std::u16string pathName, SEND_PACKET; } -void GameMessages::HandleCinematicUpdate(RakNet::BitStream *inStream, Entity *entity, const SystemAddress &sysAddr) { +void GameMessages::HandleCinematicUpdate(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr) { eCinematicEvent event; if (!inStream->ReadBit()) { event = STARTED; @@ -2908,14 +2845,13 @@ void GameMessages::HandleCinematicUpdate(RakNet::BitStream *inStream, Entity *en } void GameMessages::SendSetStunned(LWOOBJID objectId, eStunState stateChangeType, const SystemAddress& sysAddr, - LWOOBJID originator, bool bCantAttack, bool bCantEquip, - bool bCantInteract, bool bCantJump, bool bCantMove, bool bCantTurn, - bool bCantUseItem, bool bDontTerminateInteract, bool bIgnoreImmunity, - bool bCantAttackOutChangeWasApplied, bool bCantEquipOutChangeWasApplied, - bool bCantInteractOutChangeWasApplied, bool bCantJumpOutChangeWasApplied, - bool bCantMoveOutChangeWasApplied, bool bCantTurnOutChangeWasApplied, - bool bCantUseItemOutChangeWasApplied) -{ + LWOOBJID originator, bool bCantAttack, bool bCantEquip, + bool bCantInteract, bool bCantJump, bool bCantMove, bool bCantTurn, + bool bCantUseItem, bool bDontTerminateInteract, bool bIgnoreImmunity, + bool bCantAttackOutChangeWasApplied, bool bCantEquipOutChangeWasApplied, + bool bCantInteractOutChangeWasApplied, bool bCantJumpOutChangeWasApplied, + bool bCantMoveOutChangeWasApplied, bool bCantTurnOutChangeWasApplied, + bool bCantUseItemOutChangeWasApplied) { CBITSTREAM; CMSGHEADER; @@ -2957,8 +2893,7 @@ void GameMessages::SendSetStunned(LWOOBJID objectId, eStunState stateChangeType, } -void GameMessages::SendOrientToAngle(LWOOBJID objectId, bool bRelativeToCurrent, float fAngle, const SystemAddress& sysAddr) -{ +void GameMessages::SendOrientToAngle(LWOOBJID objectId, bool bRelativeToCurrent, float fAngle, const SystemAddress& sysAddr) { CBITSTREAM; CMSGHEADER; @@ -2973,8 +2908,7 @@ void GameMessages::SendOrientToAngle(LWOOBJID objectId, bool bRelativeToCurrent, } -void GameMessages::SendAddRunSpeedModifier(LWOOBJID objectId, LWOOBJID caster, uint32_t modifier, const SystemAddress& sysAddr) -{ +void GameMessages::SendAddRunSpeedModifier(LWOOBJID objectId, LWOOBJID caster, uint32_t modifier, const SystemAddress& sysAddr) { CBITSTREAM; CMSGHEADER; @@ -2991,8 +2925,7 @@ void GameMessages::SendAddRunSpeedModifier(LWOOBJID objectId, LWOOBJID caster, u SEND_PACKET; } -void GameMessages::SendRemoveRunSpeedModifier(LWOOBJID objectId, uint32_t modifier, const SystemAddress& sysAddr) -{ +void GameMessages::SendRemoveRunSpeedModifier(LWOOBJID objectId, uint32_t modifier, const SystemAddress& sysAddr) { CBITSTREAM; CMSGHEADER; @@ -3006,8 +2939,7 @@ void GameMessages::SendRemoveRunSpeedModifier(LWOOBJID objectId, uint32_t modifi SEND_PACKET; } -void GameMessages::SendPropertyEntranceBegin(LWOOBJID objectId, const SystemAddress& sysAddr) -{ +void GameMessages::SendPropertyEntranceBegin(LWOOBJID objectId, const SystemAddress& sysAddr) { CBITSTREAM; CMSGHEADER; @@ -3018,8 +2950,7 @@ void GameMessages::SendPropertyEntranceBegin(LWOOBJID objectId, const SystemAddr SEND_PACKET; } -void GameMessages::SendPropertySelectQuery(LWOOBJID objectId, int32_t navOffset, bool thereAreMore, int32_t cloneId, bool hasFeaturedProperty, bool wasFriends, const std::vector& entries, const SystemAddress& sysAddr) -{ +void GameMessages::SendPropertySelectQuery(LWOOBJID objectId, int32_t navOffset, bool thereAreMore, int32_t cloneId, bool hasFeaturedProperty, bool wasFriends, const std::vector& entries, const SystemAddress& sysAddr) { CBITSTREAM; CMSGHEADER; @@ -3034,8 +2965,7 @@ void GameMessages::SendPropertySelectQuery(LWOOBJID objectId, int32_t navOffset, bitStream.Write(entries.size()); - for (auto& entry : entries) - { + for (auto& entry : entries) { entry.Serialize(bitStream); } @@ -3043,8 +2973,7 @@ void GameMessages::SendPropertySelectQuery(LWOOBJID objectId, int32_t navOffset, SEND_PACKET; } -void GameMessages::SendNotifyObject(LWOOBJID objectId, LWOOBJID objIDSender, std::u16string name, const SystemAddress& sysAddr, int param1, int param2) -{ +void GameMessages::SendNotifyObject(LWOOBJID objectId, LWOOBJID objIDSender, std::u16string name, const SystemAddress& sysAddr, int param1, int param2) { CBITSTREAM; CMSGHEADER; @@ -3053,8 +2982,7 @@ void GameMessages::SendNotifyObject(LWOOBJID objectId, LWOOBJID objIDSender, std bitStream.Write(objIDSender); bitStream.Write(static_cast(name.size())); - for (const auto character : name) - { + for (const auto character : name) { bitStream.Write(character); } @@ -3065,8 +2993,7 @@ void GameMessages::SendNotifyObject(LWOOBJID objectId, LWOOBJID objIDSender, std SEND_PACKET; } -void GameMessages::HandleVerifyAck(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr) -{ +void GameMessages::HandleVerifyAck(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr) { bool bDifferent; std::string sBitStream; uint32_t uiHandle = 0; @@ -3081,14 +3008,12 @@ void GameMessages::HandleVerifyAck(RakNet::BitStream* inStream, Entity* entity, sBitStream.push_back(character); } - if (inStream->ReadBit()) - { + if (inStream->ReadBit()) { inStream->Read(uiHandle); } } -void GameMessages::SendTeamPickupItem(LWOOBJID objectId, LWOOBJID lootID, LWOOBJID lootOwnerID, const SystemAddress& sysAddr) -{ +void GameMessages::SendTeamPickupItem(LWOOBJID objectId, LWOOBJID lootID, LWOOBJID lootOwnerID, const SystemAddress& sysAddr) { CBITSTREAM; CMSGHEADER; @@ -3104,8 +3029,7 @@ void GameMessages::SendTeamPickupItem(LWOOBJID objectId, LWOOBJID lootID, LWOOBJ //Trading: -void GameMessages::SendServerTradeInvite(LWOOBJID objectId, bool bNeedInvitePopUp, LWOOBJID i64Requestor, std::u16string wsName, const SystemAddress& sysAddr) -{ +void GameMessages::SendServerTradeInvite(LWOOBJID objectId, bool bNeedInvitePopUp, LWOOBJID i64Requestor, std::u16string wsName, const SystemAddress& sysAddr) { CBITSTREAM; CMSGHEADER; @@ -3115,8 +3039,7 @@ void GameMessages::SendServerTradeInvite(LWOOBJID objectId, bool bNeedInvitePopU bitStream.Write(bNeedInvitePopUp); bitStream.Write(i64Requestor); bitStream.Write(static_cast(wsName.size())); - for (const auto character : wsName) - { + for (const auto character : wsName) { bitStream.Write(character); } @@ -3124,8 +3047,7 @@ void GameMessages::SendServerTradeInvite(LWOOBJID objectId, bool bNeedInvitePopU SEND_PACKET; } -void GameMessages::SendServerTradeInitialReply(LWOOBJID objectId, LWOOBJID i64Invitee, int32_t resultType, std::u16string wsName, const SystemAddress& sysAddr) -{ +void GameMessages::SendServerTradeInitialReply(LWOOBJID objectId, LWOOBJID i64Invitee, int32_t resultType, std::u16string wsName, const SystemAddress& sysAddr) { CBITSTREAM; CMSGHEADER; @@ -3135,8 +3057,7 @@ void GameMessages::SendServerTradeInitialReply(LWOOBJID objectId, LWOOBJID i64In bitStream.Write(i64Invitee); bitStream.Write(resultType); bitStream.Write(static_cast(wsName.size())); - for (const auto character : wsName) - { + for (const auto character : wsName) { bitStream.Write(character); } @@ -3144,8 +3065,7 @@ void GameMessages::SendServerTradeInitialReply(LWOOBJID objectId, LWOOBJID i64In SEND_PACKET; } -void GameMessages::SendServerTradeFinalReply(LWOOBJID objectId, bool bResult, LWOOBJID i64Invitee, std::u16string wsName, const SystemAddress& sysAddr) -{ +void GameMessages::SendServerTradeFinalReply(LWOOBJID objectId, bool bResult, LWOOBJID i64Invitee, std::u16string wsName, const SystemAddress& sysAddr) { CBITSTREAM; CMSGHEADER; @@ -3155,8 +3075,7 @@ void GameMessages::SendServerTradeFinalReply(LWOOBJID objectId, bool bResult, LW bitStream.Write(bResult); bitStream.Write(i64Invitee); bitStream.Write(static_cast(wsName.size())); - for (const auto character : wsName) - { + for (const auto character : wsName) { bitStream.Write(character); } @@ -3164,8 +3083,7 @@ void GameMessages::SendServerTradeFinalReply(LWOOBJID objectId, bool bResult, LW SEND_PACKET; } -void GameMessages::SendServerTradeAccept(LWOOBJID objectId, bool bFirst, const SystemAddress& sysAddr) -{ +void GameMessages::SendServerTradeAccept(LWOOBJID objectId, bool bFirst, const SystemAddress& sysAddr) { CBITSTREAM; CMSGHEADER; @@ -3178,8 +3096,7 @@ void GameMessages::SendServerTradeAccept(LWOOBJID objectId, bool bFirst, const S SEND_PACKET; } -void GameMessages::SendServerTradeCancel(LWOOBJID objectId, const SystemAddress& sysAddr) -{ +void GameMessages::SendServerTradeCancel(LWOOBJID objectId, const SystemAddress& sysAddr) { CBITSTREAM; CMSGHEADER; @@ -3190,8 +3107,7 @@ void GameMessages::SendServerTradeCancel(LWOOBJID objectId, const SystemAddress& SEND_PACKET; } -void GameMessages::SendServerTradeUpdate(LWOOBJID objectId, uint64_t coins, const std::vector& items, const SystemAddress& sysAddr) -{ +void GameMessages::SendServerTradeUpdate(LWOOBJID objectId, uint64_t coins, const std::vector& items, const SystemAddress& sysAddr) { CBITSTREAM; CMSGHEADER; @@ -3202,8 +3118,7 @@ void GameMessages::SendServerTradeUpdate(LWOOBJID objectId, uint64_t coins, cons bitStream.Write(coins); bitStream.Write(static_cast(items.size())); - for (const auto& item : items) - { + for (const auto& item : items) { bitStream.Write(item.itemId); bitStream.Write(item.itemId); @@ -3221,13 +3136,11 @@ void GameMessages::SendServerTradeUpdate(LWOOBJID objectId, uint64_t coins, cons SEND_PACKET; } -void GameMessages::HandleClientTradeRequest(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr) -{ +void GameMessages::HandleClientTradeRequest(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr) { // Check if the player has restricted trade access auto* character = entity->GetCharacter(); - if (character->HasPermission(PermissionMap::RestrictedTradeAccess)) - { + if (character->HasPermission(PermissionMap::RestrictedTradeAccess)) { // Send a message to the player ChatPackets::SendSystemMessage( sysAddr, @@ -3244,12 +3157,10 @@ void GameMessages::HandleClientTradeRequest(RakNet::BitStream* inStream, Entity* auto* invitee = EntityManager::Instance()->GetEntity(i64Invitee); - if (invitee != nullptr && invitee->IsPlayer()) - { + if (invitee != nullptr && invitee->IsPlayer()) { character = invitee->GetCharacter(); - if (character->HasPermission(PermissionMap::RestrictedTradeAccess)) - { + if (character->HasPermission(PermissionMap::RestrictedTradeAccess)) { // Send a message to the player ChatPackets::SendSystemMessage( sysAddr, @@ -3263,17 +3174,13 @@ void GameMessages::HandleClientTradeRequest(RakNet::BitStream* inStream, Entity* auto* trade = TradingManager::Instance()->GetPlayerTrade(entity->GetObjectID()); - if (trade != nullptr) - { - if (!trade->IsParticipant(i64Invitee)) - { + if (trade != nullptr) { + if (!trade->IsParticipant(i64Invitee)) { TradingManager::Instance()->CancelTrade(trade->GetTradeId()); TradingManager::Instance()->NewTrade(entity->GetObjectID(), i64Invitee); } - } - else - { + } else { TradingManager::Instance()->NewTrade(entity->GetObjectID(), i64Invitee); } @@ -3287,8 +3194,7 @@ void GameMessages::HandleClientTradeRequest(RakNet::BitStream* inStream, Entity* } } -void GameMessages::HandleClientTradeCancel(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr) -{ +void GameMessages::HandleClientTradeCancel(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr) { auto* trade = TradingManager::Instance()->GetPlayerTrade(entity->GetObjectID()); if (trade == nullptr) return; @@ -3298,8 +3204,7 @@ void GameMessages::HandleClientTradeCancel(RakNet::BitStream* inStream, Entity* TradingManager::Instance()->CancelTrade(trade->GetTradeId()); } -void GameMessages::HandleClientTradeAccept(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr) -{ +void GameMessages::HandleClientTradeAccept(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr) { bool bFirst = inStream->ReadBit(); Game::logger->Log("GameMessages", "Trade accepted from (%llu) -> (%d)", entity->GetObjectID(), bFirst); @@ -3311,8 +3216,7 @@ void GameMessages::HandleClientTradeAccept(RakNet::BitStream* inStream, Entity* trade->SetAccepted(entity->GetObjectID(), bFirst); } -void GameMessages::HandleClientTradeUpdate(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr) -{ +void GameMessages::HandleClientTradeUpdate(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr) { uint64_t currency; uint32_t itemCount; @@ -3321,10 +3225,9 @@ void GameMessages::HandleClientTradeUpdate(RakNet::BitStream* inStream, Entity* Game::logger->Log("GameMessages", "Trade update from (%llu) -> (%llu), (%i)", entity->GetObjectID(), currency, itemCount); - std::vector items {}; + std::vector items{}; - for (size_t i = 0; i < itemCount; i++) - { + for (size_t i = 0; i < itemCount; i++) { LWOOBJID itemId; LWOOBJID itemId2; @@ -3340,40 +3243,33 @@ void GameMessages::HandleClientTradeUpdate(RakNet::BitStream* inStream, Entity* bool unknown4; inStream->Read(lot); - if (inStream->ReadBit()) - { + if (inStream->ReadBit()) { inStream->Read(unknown1); } - if (inStream->ReadBit()) - { + if (inStream->ReadBit()) { inStream->Read(unknown2); } - if (inStream->ReadBit()) - { + if (inStream->ReadBit()) { inStream->Read(slot); } - if (inStream->ReadBit()) - { + if (inStream->ReadBit()) { inStream->Read(unknown3); } if (inStream->ReadBit()) // No { inStream->Read(ldfSize); bool compressed = inStream->ReadBit(); - if (compressed) - { + if (compressed) { uint32_t ldfCompressedSize = 0; inStream->Read(ldfCompressedSize); inStream->IgnoreBytes(ldfCompressedSize); - } - else - { + } else { inStream->IgnoreBytes(ldfSize); } } unknown4 = inStream->ReadBit(); - items.push_back({itemId, lot, unknown2}); + items.push_back({ itemId, lot, unknown2 }); Game::logger->Log("GameMessages", "Trade item from (%llu) -> (%llu)/(%llu), (%i), (%llu), (%i), (%i)", entity->GetObjectID(), itemId, itemId2, lot, unknown1, unknown2, unknown3); } @@ -3389,8 +3285,7 @@ void GameMessages::HandleClientTradeUpdate(RakNet::BitStream* inStream, Entity* //Pets: -void GameMessages::SendNotifyPetTamingMinigame(LWOOBJID objectId, LWOOBJID petId, LWOOBJID playerTamingId, bool bForceTeleport, uint32_t notifyType, NiPoint3 petsDestPos, NiPoint3 telePos, NiQuaternion teleRot, const SystemAddress& sysAddr) -{ +void GameMessages::SendNotifyPetTamingMinigame(LWOOBJID objectId, LWOOBJID petId, LWOOBJID playerTamingId, bool bForceTeleport, uint32_t notifyType, NiPoint3 petsDestPos, NiPoint3 telePos, NiQuaternion teleRot, const SystemAddress& sysAddr) { CBITSTREAM; CMSGHEADER; @@ -3412,8 +3307,7 @@ void GameMessages::SendNotifyPetTamingMinigame(LWOOBJID objectId, LWOOBJID petId SEND_PACKET; } -void GameMessages::SendNotifyTamingModelLoadedOnServer(LWOOBJID objectId, const SystemAddress& sysAddr) -{ +void GameMessages::SendNotifyTamingModelLoadedOnServer(LWOOBJID objectId, const SystemAddress& sysAddr) { CBITSTREAM; CMSGHEADER; @@ -3424,8 +3318,7 @@ void GameMessages::SendNotifyTamingModelLoadedOnServer(LWOOBJID objectId, const SEND_PACKET; } -void GameMessages::SendNotifyPetTamingPuzzleSelected(LWOOBJID objectId, std::vector& bricks, const SystemAddress& sysAddr) -{ +void GameMessages::SendNotifyPetTamingPuzzleSelected(LWOOBJID objectId, std::vector& bricks, const SystemAddress& sysAddr) { CBITSTREAM; CMSGHEADER; @@ -3433,8 +3326,7 @@ void GameMessages::SendNotifyPetTamingPuzzleSelected(LWOOBJID objectId, std::vec bitStream.Write(GAME_MSG::GAME_MSG_NOTIFY_PET_TAMING_PUZZLE_SELECTED); bitStream.Write(static_cast(bricks.size())); - for (const auto& brick : bricks) - { + for (const auto& brick : bricks) { bitStream.Write(brick.designerID); bitStream.Write(brick.materialID); } @@ -3443,8 +3335,7 @@ void GameMessages::SendNotifyPetTamingPuzzleSelected(LWOOBJID objectId, std::vec SEND_PACKET; } -void GameMessages::SendPetTamingTryBuildResult(LWOOBJID objectId, bool bSuccess, int32_t iNumCorrect, const SystemAddress& sysAddr) -{ +void GameMessages::SendPetTamingTryBuildResult(LWOOBJID objectId, bool bSuccess, int32_t iNumCorrect, const SystemAddress& sysAddr) { CBITSTREAM; CMSGHEADER; @@ -3459,8 +3350,7 @@ void GameMessages::SendPetTamingTryBuildResult(LWOOBJID objectId, bool bSuccess, SEND_PACKET; } -void GameMessages::SendPetResponse(LWOOBJID objectId, LWOOBJID objIDPet, int32_t iPetCommandType, int32_t iResponse, int32_t iTypeID, const SystemAddress& sysAddr) -{ +void GameMessages::SendPetResponse(LWOOBJID objectId, LWOOBJID objIDPet, int32_t iPetCommandType, int32_t iResponse, int32_t iTypeID, const SystemAddress& sysAddr) { CBITSTREAM; CMSGHEADER; @@ -3476,8 +3366,7 @@ void GameMessages::SendPetResponse(LWOOBJID objectId, LWOOBJID objIDPet, int32_t SEND_PACKET; } -void GameMessages::SendAddPetToPlayer(LWOOBJID objectId, int32_t iElementalType, std::u16string name, LWOOBJID petDBID, LOT petLOT, const SystemAddress& sysAddr) -{ +void GameMessages::SendAddPetToPlayer(LWOOBJID objectId, int32_t iElementalType, std::u16string name, LWOOBJID petDBID, LOT petLOT, const SystemAddress& sysAddr) { CBITSTREAM; CMSGHEADER; @@ -3486,8 +3375,7 @@ void GameMessages::SendAddPetToPlayer(LWOOBJID objectId, int32_t iElementalType, bitStream.Write(iElementalType); bitStream.Write(static_cast(name.size())); - for (const auto character : name) - { + for (const auto character : name) { bitStream.Write(character); } @@ -3498,8 +3386,7 @@ void GameMessages::SendAddPetToPlayer(LWOOBJID objectId, int32_t iElementalType, SEND_PACKET; } -void GameMessages::SendRegisterPetID(LWOOBJID objectId, LWOOBJID objID, const SystemAddress& sysAddr) -{ +void GameMessages::SendRegisterPetID(LWOOBJID objectId, LWOOBJID objID, const SystemAddress& sysAddr) { CBITSTREAM; CMSGHEADER; @@ -3512,8 +3399,7 @@ void GameMessages::SendRegisterPetID(LWOOBJID objectId, LWOOBJID objID, const Sy SEND_PACKET; } -void GameMessages::SendRegisterPetDBID(LWOOBJID objectId, LWOOBJID petDBID, const SystemAddress& sysAddr) -{ +void GameMessages::SendRegisterPetDBID(LWOOBJID objectId, LWOOBJID petDBID, const SystemAddress& sysAddr) { CBITSTREAM; CMSGHEADER; @@ -3526,8 +3412,7 @@ void GameMessages::SendRegisterPetDBID(LWOOBJID objectId, LWOOBJID petDBID, cons SEND_PACKET; } -void GameMessages::SendMarkInventoryItemAsActive(LWOOBJID objectId, bool bActive, int32_t iType, LWOOBJID itemID, const SystemAddress& sysAddr) -{ +void GameMessages::SendMarkInventoryItemAsActive(LWOOBJID objectId, bool bActive, int32_t iType, LWOOBJID itemID, const SystemAddress& sysAddr) { CBITSTREAM; CMSGHEADER; @@ -3546,8 +3431,7 @@ void GameMessages::SendMarkInventoryItemAsActive(LWOOBJID objectId, bool bActive SEND_PACKET; } -void GameMessages::SendClientExitTamingMinigame(LWOOBJID objectId, bool bVoluntaryExit, const SystemAddress& sysAddr) -{ +void GameMessages::SendClientExitTamingMinigame(LWOOBJID objectId, bool bVoluntaryExit, const SystemAddress& sysAddr) { CBITSTREAM; CMSGHEADER; @@ -3560,8 +3444,7 @@ void GameMessages::SendClientExitTamingMinigame(LWOOBJID objectId, bool bVolunta SEND_PACKET; } -void GameMessages::SendShowPetActionButton(LWOOBJID objectId, int32_t buttonLabel, bool bShow, const SystemAddress& sysAddr) -{ +void GameMessages::SendShowPetActionButton(LWOOBJID objectId, int32_t buttonLabel, bool bShow, const SystemAddress& sysAddr) { CBITSTREAM; CMSGHEADER; @@ -3575,8 +3458,7 @@ void GameMessages::SendShowPetActionButton(LWOOBJID objectId, int32_t buttonLabe SEND_PACKET; } -void GameMessages::SendPlayEmote(LWOOBJID objectId, int32_t emoteID, LWOOBJID target, const SystemAddress& sysAddr) -{ +void GameMessages::SendPlayEmote(LWOOBJID objectId, int32_t emoteID, LWOOBJID target, const SystemAddress& sysAddr) { CBITSTREAM; CMSGHEADER; @@ -3591,8 +3473,7 @@ void GameMessages::SendPlayEmote(LWOOBJID objectId, int32_t emoteID, LWOOBJID ta } -void GameMessages::SendBouncerActiveStatus(LWOOBJID objectId, bool bActive, const SystemAddress& sysAddr) -{ +void GameMessages::SendBouncerActiveStatus(LWOOBJID objectId, bool bActive, const SystemAddress& sysAddr) { CBITSTREAM; CMSGHEADER; @@ -3606,8 +3487,7 @@ void GameMessages::SendBouncerActiveStatus(LWOOBJID objectId, bool bActive, cons } -void GameMessages::SendSetPetName(LWOOBJID objectId, std::u16string name, LWOOBJID petDBID, const SystemAddress& sysAddr) -{ +void GameMessages::SendSetPetName(LWOOBJID objectId, std::u16string name, LWOOBJID petDBID, const SystemAddress& sysAddr) { CBITSTREAM; CMSGHEADER; @@ -3615,8 +3495,7 @@ void GameMessages::SendSetPetName(LWOOBJID objectId, std::u16string name, LWOOBJ bitStream.Write(GAME_MSG::GAME_MSG_SET_PET_NAME); bitStream.Write(static_cast(name.size())); - for (const auto character : name) - { + for (const auto character : name) { bitStream.Write(character); } @@ -3628,8 +3507,7 @@ void GameMessages::SendSetPetName(LWOOBJID objectId, std::u16string name, LWOOBJ } -void GameMessages::SendSetPetNameModerated(LWOOBJID objectId, LWOOBJID petDBID, int32_t nModerationStatus, const SystemAddress& sysAddr) -{ +void GameMessages::SendSetPetNameModerated(LWOOBJID objectId, LWOOBJID petDBID, int32_t nModerationStatus, const SystemAddress& sysAddr) { CBITSTREAM; CMSGHEADER; @@ -3646,8 +3524,7 @@ void GameMessages::SendSetPetNameModerated(LWOOBJID objectId, LWOOBJID petDBID, } -void GameMessages::SendPetNameChanged(LWOOBJID objectId, int32_t moderationStatus, std::u16string name, std::u16string ownerName, const SystemAddress& sysAddr) -{ +void GameMessages::SendPetNameChanged(LWOOBJID objectId, int32_t moderationStatus, std::u16string name, std::u16string ownerName, const SystemAddress& sysAddr) { CBITSTREAM; CMSGHEADER; @@ -3657,14 +3534,12 @@ void GameMessages::SendPetNameChanged(LWOOBJID objectId, int32_t moderationStatu bitStream.Write(moderationStatus); bitStream.Write(static_cast(name.size())); - for (const auto character : name) - { + for (const auto character : name) { bitStream.Write(character); } bitStream.Write(static_cast(ownerName.size())); - for (const auto character : ownerName) - { + for (const auto character : ownerName) { bitStream.Write(character); } @@ -3673,34 +3548,29 @@ void GameMessages::SendPetNameChanged(LWOOBJID objectId, int32_t moderationStatu } -void GameMessages::HandleClientExitTamingMinigame(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr) -{ +void GameMessages::HandleClientExitTamingMinigame(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr) { bool bVoluntaryExit = inStream->ReadBit(); auto* petComponent = PetComponent::GetTamingPet(entity->GetObjectID()); - if (petComponent == nullptr) - { + if (petComponent == nullptr) { return; } petComponent->ClientExitTamingMinigame(bVoluntaryExit); } -void GameMessages::HandleStartServerPetMinigameTimer(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr) -{ +void GameMessages::HandleStartServerPetMinigameTimer(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr) { auto* petComponent = PetComponent::GetTamingPet(entity->GetObjectID()); - if (petComponent == nullptr) - { + if (petComponent == nullptr) { return; } petComponent->StartTimer(); } -void GameMessages::HandlePetTamingTryBuild(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr) -{ +void GameMessages::HandlePetTamingTryBuild(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr) { uint32_t brickCount; std::vector bricks; bool clientFailed; @@ -3709,8 +3579,7 @@ void GameMessages::HandlePetTamingTryBuild(RakNet::BitStream* inStream, Entity* bricks.reserve(brickCount); - for (uint32_t i = 0; i < brickCount; i++) - { + for (uint32_t i = 0; i < brickCount; i++) { Brick brick; inStream->Read(brick); @@ -3722,39 +3591,34 @@ void GameMessages::HandlePetTamingTryBuild(RakNet::BitStream* inStream, Entity* auto* petComponent = PetComponent::GetTamingPet(entity->GetObjectID()); - if (petComponent == nullptr) - { + if (petComponent == nullptr) { return; } petComponent->TryBuild(bricks.size(), clientFailed); } -void GameMessages::HandleNotifyTamingBuildSuccess(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr) -{ +void GameMessages::HandleNotifyTamingBuildSuccess(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr) { NiPoint3 position; inStream->Read(position); auto* petComponent = PetComponent::GetTamingPet(entity->GetObjectID()); - if (petComponent == nullptr) - { + if (petComponent == nullptr) { return; } petComponent->NotifyTamingBuildSuccess(position); } -void GameMessages::HandleRequestSetPetName(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr) -{ +void GameMessages::HandleRequestSetPetName(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr) { uint32_t nameLength; std::u16string name; inStream->Read(nameLength); - for (size_t i = 0; i < nameLength; i++) - { + for (size_t i = 0; i < nameLength; i++) { char16_t character; inStream->Read(character); name.push_back(character); @@ -3762,12 +3626,10 @@ void GameMessages::HandleRequestSetPetName(RakNet::BitStream* inStream, Entity* auto* petComponent = PetComponent::GetTamingPet(entity->GetObjectID()); - if (petComponent == nullptr) - { + if (petComponent == nullptr) { petComponent = PetComponent::GetActivePet(entity->GetObjectID()); - if (petComponent == nullptr) - { + if (petComponent == nullptr) { return; } } @@ -3775,8 +3637,7 @@ void GameMessages::HandleRequestSetPetName(RakNet::BitStream* inStream, Entity* petComponent->RequestSetPetName(name); } -void GameMessages::HandleCommandPet(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr) -{ +void GameMessages::HandleCommandPet(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr) { NiPoint3 genericPosInfo; LWOOBJID objIdSource; int32_t iPetCommandType; @@ -3791,39 +3652,32 @@ void GameMessages::HandleCommandPet(RakNet::BitStream* inStream, Entity* entity, auto* petComponent = entity->GetComponent(); - if (petComponent == nullptr) - { + if (petComponent == nullptr) { return; } petComponent->Command(genericPosInfo, objIdSource, iPetCommandType, iTypeID, overrideObey); } -void GameMessages::HandleDespawnPet(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr) -{ +void GameMessages::HandleDespawnPet(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr) { bool bDeletePet; bDeletePet = inStream->ReadBit(); auto* petComponent = PetComponent::GetActivePet(entity->GetObjectID()); - if (petComponent == nullptr) - { + if (petComponent == nullptr) { return; } - if (bDeletePet) - { + if (bDeletePet) { petComponent->Release(); - } - else - { + } else { petComponent->Deactivate(); } } -void GameMessages::HandleMessageBoxResponse(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr) -{ +void GameMessages::HandleMessageBoxResponse(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr) { int32_t iButton; uint32_t identifierLength; std::u16string identifier; @@ -3833,16 +3687,14 @@ void GameMessages::HandleMessageBoxResponse(RakNet::BitStream* inStream, Entity* inStream->Read(iButton); inStream->Read(identifierLength); - for (size_t i = 0; i < identifierLength; i++) - { + for (size_t i = 0; i < identifierLength; i++) { char16_t character; inStream->Read(character); identifier.push_back(character); } inStream->Read(userDataLength); - for (size_t i = 0; i < userDataLength; i++) - { + for (size_t i = 0; i < userDataLength; i++) { char16_t character; inStream->Read(character); userData.push_back(character); @@ -3852,15 +3704,13 @@ void GameMessages::HandleMessageBoxResponse(RakNet::BitStream* inStream, Entity* auto* user = UserManager::Instance()->GetUser(sysAddr); - if (user == nullptr) - { + if (user == nullptr) { return; } auto* userEntity = user->GetLastUsedChar()->GetEntity(); - if (userEntity == nullptr) - { + if (userEntity == nullptr) { return; } @@ -3868,26 +3718,22 @@ void GameMessages::HandleMessageBoxResponse(RakNet::BitStream* inStream, Entity* auto* scriptedActivityComponent = entity->GetComponent(); - if (scriptedActivityComponent != nullptr) - { + if (scriptedActivityComponent != nullptr) { scriptedActivityComponent->HandleMessageBoxResponse(userEntity, GeneralUtils::UTF16ToWTF8(identifier)); } auto* racingControlComponent = entity->GetComponent(); - if (racingControlComponent != nullptr) - { + if (racingControlComponent != nullptr) { racingControlComponent->HandleMessageBoxResponse(userEntity, GeneralUtils::UTF16ToWTF8(identifier)); } - for (auto* shootingGallery : EntityManager::Instance()->GetEntitiesByComponent(COMPONENT_TYPE_SHOOTING_GALLERY)) - { + for (auto* shootingGallery : EntityManager::Instance()->GetEntitiesByComponent(COMPONENT_TYPE_SHOOTING_GALLERY)) { shootingGallery->OnMessageBoxResponse(userEntity, iButton, identifier, userData); } } -void GameMessages::HandleChoiceBoxRespond(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr) -{ +void GameMessages::HandleChoiceBoxRespond(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr) { int32_t iButton; uint32_t buttonIdentifierLength; std::u16string buttonIdentifier; @@ -3895,8 +3741,7 @@ void GameMessages::HandleChoiceBoxRespond(RakNet::BitStream* inStream, Entity* e std::u16string identifier; inStream->Read(buttonIdentifierLength); - for (size_t i = 0; i < buttonIdentifierLength; i++) - { + for (size_t i = 0; i < buttonIdentifierLength; i++) { char16_t character; inStream->Read(character); buttonIdentifier.push_back(character); @@ -3905,8 +3750,7 @@ void GameMessages::HandleChoiceBoxRespond(RakNet::BitStream* inStream, Entity* e inStream->Read(iButton); inStream->Read(identifierLength); - for (size_t i = 0; i < identifierLength; i++) - { + for (size_t i = 0; i < identifierLength; i++) { char16_t character; inStream->Read(character); identifier.push_back(character); @@ -3916,23 +3760,20 @@ void GameMessages::HandleChoiceBoxRespond(RakNet::BitStream* inStream, Entity* e auto* user = UserManager::Instance()->GetUser(sysAddr); - if (user == nullptr) - { + if (user == nullptr) { return; } auto* userEntity = user->GetLastUsedChar()->GetEntity(); - if (userEntity == nullptr) - { + if (userEntity == nullptr) { return; } entity->OnChoiceBoxResponse(userEntity, iButton, buttonIdentifier, identifier); } -void GameMessages::SendDisplayZoneSummary(LWOOBJID objectId, const SystemAddress& sysAddr, bool isPropertyMap, bool isZoneStart, LWOOBJID sender) -{ +void GameMessages::SendDisplayZoneSummary(LWOOBJID objectId, const SystemAddress& sysAddr, bool isPropertyMap, bool isZoneStart, LWOOBJID sender) { CBITSTREAM; CMSGHEADER; @@ -3950,8 +3791,7 @@ void GameMessages::SendDisplayZoneSummary(LWOOBJID objectId, const SystemAddress //UI -void GameMessages::SendNotifyNotEnoughInvSpace(LWOOBJID objectId, uint32_t freeSlotsNeeded, eInventoryType inventoryType, const SystemAddress& sysAddr) -{ +void GameMessages::SendNotifyNotEnoughInvSpace(LWOOBJID objectId, uint32_t freeSlotsNeeded, eInventoryType inventoryType, const SystemAddress& sysAddr) { CBITSTREAM; CMSGHEADER; @@ -3966,8 +3806,7 @@ void GameMessages::SendNotifyNotEnoughInvSpace(LWOOBJID objectId, uint32_t freeS SEND_PACKET; } -void GameMessages::SendDisplayMessageBox(LWOOBJID objectId, bool bShow, LWOOBJID callbackClient, const std::u16string& identifier, int32_t imageID, const std::u16string& text, const std::u16string& userData, const SystemAddress& sysAddr) -{ +void GameMessages::SendDisplayMessageBox(LWOOBJID objectId, bool bShow, LWOOBJID callbackClient, const std::u16string& identifier, int32_t imageID, const std::u16string& text, const std::u16string& userData, const SystemAddress& sysAddr) { CBITSTREAM; CMSGHEADER; @@ -3978,22 +3817,19 @@ void GameMessages::SendDisplayMessageBox(LWOOBJID objectId, bool bShow, LWOOBJID bitStream.Write(callbackClient); bitStream.Write(static_cast(identifier.size())); - for (const auto character : identifier) - { + for (const auto character : identifier) { bitStream.Write(character); } bitStream.Write(imageID); bitStream.Write(static_cast(text.size())); - for (const auto character : text) - { + for (const auto character : text) { bitStream.Write(character); } bitStream.Write(static_cast(userData.size())); - for (const auto character : userData) - { + for (const auto character : userData) { bitStream.Write(character); } @@ -4001,8 +3837,7 @@ void GameMessages::SendDisplayMessageBox(LWOOBJID objectId, bool bShow, LWOOBJID SEND_PACKET; } -void GameMessages::SendDisplayChatBubble(LWOOBJID objectId, const std::u16string& text, const SystemAddress& sysAddr) -{ +void GameMessages::SendDisplayChatBubble(LWOOBJID objectId, const std::u16string& text, const SystemAddress& sysAddr) { // GAME_MSG_DISPLAY_CHAT_BUBBLE CBITSTREAM; CMSGHEADER; @@ -4011,8 +3846,7 @@ void GameMessages::SendDisplayChatBubble(LWOOBJID objectId, const std::u16string bitStream.Write(GAME_MSG::GAME_MSG_DISPLAY_CHAT_BUBBLE); bitStream.Write(static_cast(text.size())); - for (const auto character : text) - { + for (const auto character : text) { bitStream.Write(character); } @@ -4022,7 +3856,7 @@ void GameMessages::SendDisplayChatBubble(LWOOBJID objectId, const std::u16string // Mounts -void GameMessages::SendSetMountInventoryID(Entity* entity, const LWOOBJID& objectID, const SystemAddress& sysAddr){ +void GameMessages::SendSetMountInventoryID(Entity* entity, const LWOOBJID& objectID, const SystemAddress& sysAddr) { CBITSTREAM; CMSGHEADER; @@ -4034,7 +3868,7 @@ void GameMessages::SendSetMountInventoryID(Entity* entity, const LWOOBJID& objec } -void GameMessages::HandleDismountComplete(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr){ +void GameMessages::HandleDismountComplete(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr) { LWOOBJID objectId{}; inStream->Read(objectId); auto* mount = EntityManager::Instance()->GetEntity(objectId); @@ -4063,14 +3897,12 @@ void GameMessages::HandleAcknowledgePossession(RakNet::BitStream* inStream, Enti //Racing -void GameMessages::HandleModuleAssemblyQueryData(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr) -{ +void GameMessages::HandleModuleAssemblyQueryData(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr) { auto* moduleAssemblyComponent = entity->GetComponent(); Game::logger->Log("HandleModuleAssemblyQueryData", "Got Query from %i", entity->GetLOT()); - if (moduleAssemblyComponent != nullptr) - { + if (moduleAssemblyComponent != nullptr) { Game::logger->Log("HandleModuleAssemblyQueryData", "Returning assembly %s", GeneralUtils::UTF16ToWTF8(moduleAssemblyComponent->GetAssemblyPartsLOTs()).c_str()); SendModuleAssemblyDBDataForClient(entity->GetObjectID(), moduleAssemblyComponent->GetSubKey(), moduleAssemblyComponent->GetAssemblyPartsLOTs(), UNASSIGNED_SYSTEM_ADDRESS); @@ -4078,38 +3910,33 @@ void GameMessages::HandleModuleAssemblyQueryData(RakNet::BitStream* inStream, En } -void GameMessages::HandleModularAssemblyNIFCompleted(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr) -{ +void GameMessages::HandleModularAssemblyNIFCompleted(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr) { LWOOBJID objectID; inStream->Read(objectID); } -void GameMessages::HandleVehicleSetWheelLockState(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr) -{ +void GameMessages::HandleVehicleSetWheelLockState(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr) { bool bExtraFriction = inStream->ReadBit(); bool bLocked = inStream->ReadBit(); } -void GameMessages::HandleRacingClientReady(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr) -{ +void GameMessages::HandleRacingClientReady(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr) { LWOOBJID playerID; inStream->Read(playerID); auto* player = EntityManager::Instance()->GetEntity(playerID); - if (player == nullptr) - { + if (player == nullptr) { return; } auto* racingControlComponent = dZoneManager::Instance()->GetZoneControlObject()->GetComponent(); - if (racingControlComponent == nullptr) - { + if (racingControlComponent == nullptr) { return; } @@ -4117,8 +3944,7 @@ void GameMessages::HandleRacingClientReady(RakNet::BitStream* inStream, Entity* } -void GameMessages::HandleRequestDie(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr) -{ +void GameMessages::HandleRequestDie(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr) { bool bClientDeath; bool bSpawnLoot; std::u16string deathType; @@ -4135,8 +3961,7 @@ void GameMessages::HandleRequestDie(RakNet::BitStream* inStream, Entity* entity, uint32_t deathTypeLength = 0; inStream->Read(deathTypeLength); - for (size_t i = 0; i < deathTypeLength; i++) - { + for (size_t i = 0; i < deathTypeLength; i++) { char16_t character; inStream->Read(character); @@ -4147,15 +3972,13 @@ void GameMessages::HandleRequestDie(RakNet::BitStream* inStream, Entity* entity, inStream->Read(directionRelativeAngleY); inStream->Read(directionRelativeForce); - if (inStream->ReadBit()) - { + if (inStream->ReadBit()) { inStream->Read(killType); } inStream->Read(killerID); - if (inStream->ReadBit()) - { + if (inStream->ReadBit()) { inStream->Read(lootOwnerID); } @@ -4165,16 +3988,13 @@ void GameMessages::HandleRequestDie(RakNet::BitStream* inStream, Entity* entity, Game::logger->Log("HandleRequestDie", "Got die request: %i", entity->GetLOT()); - if (racingControlComponent != nullptr) - { + if (racingControlComponent != nullptr) { auto* possessableComponent = entity->GetComponent(); - if (possessableComponent != nullptr) - { + if (possessableComponent != nullptr) { entity = EntityManager::Instance()->GetEntity(possessableComponent->GetPossessor()); - if (entity == nullptr) - { + if (entity == nullptr) { return; } } @@ -4184,28 +4004,24 @@ void GameMessages::HandleRequestDie(RakNet::BitStream* inStream, Entity* entity, } -void GameMessages::HandleVehicleNotifyServerAddPassiveBoostAction(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr) -{ +void GameMessages::HandleVehicleNotifyServerAddPassiveBoostAction(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr) { //SendVehicleAddPassiveBoostAction(entity->GetObjectID(), sysAddr); } -void GameMessages::HandleVehicleNotifyServerRemovePassiveBoostAction(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr) -{ +void GameMessages::HandleVehicleNotifyServerRemovePassiveBoostAction(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr) { //SendVehicleRemovePassiveBoostAction(entity->GetObjectID(), sysAddr); } -void GameMessages::HandleRacingPlayerInfoResetFinished(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr) -{ +void GameMessages::HandleRacingPlayerInfoResetFinished(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr) { LWOOBJID playerID; inStream->Read(playerID); auto* player = EntityManager::Instance()->GetEntity(playerID); - if (player == nullptr) - { + if (player == nullptr) { return; } @@ -4215,8 +4031,7 @@ void GameMessages::HandleRacingPlayerInfoResetFinished(RakNet::BitStream* inStre Game::logger->Log("HandleRacingPlayerInfoResetFinished", "Got finished: %i", entity->GetLOT()); - if (racingControlComponent != nullptr) - { + if (racingControlComponent != nullptr) { racingControlComponent->OnRacingPlayerInfoResetFinished(player); } } @@ -4257,8 +4072,7 @@ void GameMessages::HandleUpdatePropertyPerformanceCost(RakNet::BitStream* inStre updatePerformanceCostQuery = nullptr; } -void GameMessages::HandleVehicleNotifyHitImaginationServer(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr) -{ +void GameMessages::HandleVehicleNotifyHitImaginationServer(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr) { LWOOBJID pickupObjID = LWOOBJID_EMPTY; LWOOBJID pickupSpawnerID = LWOOBJID_EMPTY; int32_t pickupSpawnerIndex = -1; @@ -4271,19 +4085,16 @@ void GameMessages::HandleVehicleNotifyHitImaginationServer(RakNet::BitStream* in auto* pickup = EntityManager::Instance()->GetEntity(pickupObjID); - if (pickup == nullptr) - { + if (pickup == nullptr) { return; } auto* possessableComponent = entity->GetComponent(); - if (possessableComponent != nullptr) - { + if (possessableComponent != nullptr) { entity = EntityManager::Instance()->GetEntity(possessableComponent->GetPossessor()); - if (entity == nullptr) - { + if (entity == nullptr) { return; } } @@ -4299,8 +4110,7 @@ void GameMessages::HandleVehicleNotifyHitImaginationServer(RakNet::BitStream* in } -void GameMessages::SendModuleAssemblyDBDataForClient(LWOOBJID objectId, LWOOBJID assemblyID, const std::u16string& data, const SystemAddress& sysAddr) -{ +void GameMessages::SendModuleAssemblyDBDataForClient(LWOOBJID objectId, LWOOBJID assemblyID, const std::u16string& data, const SystemAddress& sysAddr) { CBITSTREAM; CMSGHEADER; @@ -4310,8 +4120,7 @@ void GameMessages::SendModuleAssemblyDBDataForClient(LWOOBJID objectId, LWOOBJID bitStream.Write(assemblyID); bitStream.Write(static_cast(data.size())); - for (auto character : data) - { + for (auto character : data) { bitStream.Write(character); } @@ -4320,8 +4129,7 @@ void GameMessages::SendModuleAssemblyDBDataForClient(LWOOBJID objectId, LWOOBJID } -void GameMessages::SendNotifyVehicleOfRacingObject(LWOOBJID objectId, LWOOBJID racingObjectID, const SystemAddress& sysAddr) -{ +void GameMessages::SendNotifyVehicleOfRacingObject(LWOOBJID objectId, LWOOBJID racingObjectID, const SystemAddress& sysAddr) { CBITSTREAM; CMSGHEADER; @@ -4336,8 +4144,7 @@ void GameMessages::SendNotifyVehicleOfRacingObject(LWOOBJID objectId, LWOOBJID r } -void GameMessages::SendRacingPlayerLoaded(LWOOBJID objectId, LWOOBJID playerID, LWOOBJID vehicleID, const SystemAddress& sysAddr) -{ +void GameMessages::SendRacingPlayerLoaded(LWOOBJID objectId, LWOOBJID playerID, LWOOBJID vehicleID, const SystemAddress& sysAddr) { CBITSTREAM; CMSGHEADER; @@ -4352,8 +4159,7 @@ void GameMessages::SendRacingPlayerLoaded(LWOOBJID objectId, LWOOBJID playerID, } -void GameMessages::SendVehicleUnlockInput(LWOOBJID objectId, bool bLockWheels, const SystemAddress& sysAddr) -{ +void GameMessages::SendVehicleUnlockInput(LWOOBJID objectId, bool bLockWheels, const SystemAddress& sysAddr) { CBITSTREAM; CMSGHEADER; @@ -4367,8 +4173,7 @@ void GameMessages::SendVehicleUnlockInput(LWOOBJID objectId, bool bLockWheels, c } -void GameMessages::SendVehicleSetWheelLockState(LWOOBJID objectId, bool bExtraFriction, bool bLocked, const SystemAddress& sysAddr) -{ +void GameMessages::SendVehicleSetWheelLockState(LWOOBJID objectId, bool bExtraFriction, bool bLocked, const SystemAddress& sysAddr) { CBITSTREAM; CMSGHEADER; @@ -4383,8 +4188,7 @@ void GameMessages::SendVehicleSetWheelLockState(LWOOBJID objectId, bool bExtraFr } -void GameMessages::SendRacingSetPlayerResetInfo(LWOOBJID objectId, int32_t currentLap, uint32_t furthestResetPlane, LWOOBJID playerID, NiPoint3 respawnPos, uint32_t upcomingPlane, const SystemAddress& sysAddr) -{ +void GameMessages::SendRacingSetPlayerResetInfo(LWOOBJID objectId, int32_t currentLap, uint32_t furthestResetPlane, LWOOBJID playerID, NiPoint3 respawnPos, uint32_t upcomingPlane, const SystemAddress& sysAddr) { CBITSTREAM; CMSGHEADER; @@ -4402,8 +4206,7 @@ void GameMessages::SendRacingSetPlayerResetInfo(LWOOBJID objectId, int32_t curre } -void GameMessages::SendRacingResetPlayerToLastReset(LWOOBJID objectId, LWOOBJID playerID, const SystemAddress& sysAddr) -{ +void GameMessages::SendRacingResetPlayerToLastReset(LWOOBJID objectId, LWOOBJID playerID, const SystemAddress& sysAddr) { CBITSTREAM; CMSGHEADER; @@ -4417,8 +4220,7 @@ void GameMessages::SendRacingResetPlayerToLastReset(LWOOBJID objectId, LWOOBJID } -void GameMessages::SendNotifyRacingClient(LWOOBJID objectId, int32_t eventType, int32_t param1, LWOOBJID paramObj, std::u16string paramStr, LWOOBJID singleClient, const SystemAddress& sysAddr) -{ +void GameMessages::SendNotifyRacingClient(LWOOBJID objectId, int32_t eventType, int32_t param1, LWOOBJID paramObj, std::u16string paramStr, LWOOBJID singleClient, const SystemAddress& sysAddr) { CBITSTREAM; CMSGHEADER; @@ -4433,8 +4235,7 @@ void GameMessages::SendNotifyRacingClient(LWOOBJID objectId, int32_t eventType, bitStream.Write(paramObj); bitStream.Write(static_cast(paramStr.size())); - for (auto character : paramStr) - { + for (auto character : paramStr) { bitStream.Write(character); } @@ -4445,8 +4246,7 @@ void GameMessages::SendNotifyRacingClient(LWOOBJID objectId, int32_t eventType, } -void GameMessages::SendActivityEnter(LWOOBJID objectId, const SystemAddress& sysAddr) -{ +void GameMessages::SendActivityEnter(LWOOBJID objectId, const SystemAddress& sysAddr) { CBITSTREAM; CMSGHEADER; @@ -4458,8 +4258,7 @@ void GameMessages::SendActivityEnter(LWOOBJID objectId, const SystemAddress& sys } -void GameMessages::SendActivityStart(LWOOBJID objectId, const SystemAddress& sysAddr) -{ +void GameMessages::SendActivityStart(LWOOBJID objectId, const SystemAddress& sysAddr) { CBITSTREAM; CMSGHEADER; @@ -4471,8 +4270,7 @@ void GameMessages::SendActivityStart(LWOOBJID objectId, const SystemAddress& sys } -void GameMessages::SendActivityExit(LWOOBJID objectId, const SystemAddress& sysAddr) -{ +void GameMessages::SendActivityExit(LWOOBJID objectId, const SystemAddress& sysAddr) { CBITSTREAM; CMSGHEADER; @@ -4484,8 +4282,7 @@ void GameMessages::SendActivityExit(LWOOBJID objectId, const SystemAddress& sysA } -void GameMessages::SendActivityStop(LWOOBJID objectId, bool bExit, bool bUserCancel, const SystemAddress& sysAddr) -{ +void GameMessages::SendActivityStop(LWOOBJID objectId, bool bExit, bool bUserCancel, const SystemAddress& sysAddr) { CBITSTREAM; CMSGHEADER; @@ -4500,8 +4297,7 @@ void GameMessages::SendActivityStop(LWOOBJID objectId, bool bExit, bool bUserCan } -void GameMessages::SendVehicleAddPassiveBoostAction(LWOOBJID objectId, const SystemAddress& sysAddr) -{ +void GameMessages::SendVehicleAddPassiveBoostAction(LWOOBJID objectId, const SystemAddress& sysAddr) { CBITSTREAM; CMSGHEADER; @@ -4513,8 +4309,7 @@ void GameMessages::SendVehicleAddPassiveBoostAction(LWOOBJID objectId, const Sys } -void GameMessages::SendVehicleRemovePassiveBoostAction(LWOOBJID objectId, const SystemAddress& sysAddr) -{ +void GameMessages::SendVehicleRemovePassiveBoostAction(LWOOBJID objectId, const SystemAddress& sysAddr) { CBITSTREAM; CMSGHEADER; @@ -4526,8 +4321,7 @@ void GameMessages::SendVehicleRemovePassiveBoostAction(LWOOBJID objectId, const } -void GameMessages::SendVehicleNotifyFinishedRace(LWOOBJID objectId, const SystemAddress& sysAddr) -{ +void GameMessages::SendVehicleNotifyFinishedRace(LWOOBJID objectId, const SystemAddress& sysAddr) { CBITSTREAM; CMSGHEADER; @@ -4539,9 +4333,9 @@ void GameMessages::SendVehicleNotifyFinishedRace(LWOOBJID objectId, const System } void GameMessages::SendAddBuff(LWOOBJID& objectID, const LWOOBJID& casterID, uint32_t buffID, uint32_t msDuration, - bool addImmunity, bool cancelOnDamaged, bool cancelOnDeath, bool cancelOnLogout, - bool cancelOnRemoveBuff, bool cancelOnUi, bool cancelOnUnequip, bool cancelOnZone, - const SystemAddress& sysAddr) { + bool addImmunity, bool cancelOnDamaged, bool cancelOnDeath, bool cancelOnLogout, + bool cancelOnRemoveBuff, bool cancelOnUi, bool cancelOnUnequip, bool cancelOnZone, + const SystemAddress& sysAddr) { CBITSTREAM; CMSGHEADER; @@ -4577,8 +4371,7 @@ void GameMessages::SendAddBuff(LWOOBJID& objectID, const LWOOBJID& casterID, uin // NT -void GameMessages::HandleRequestMoveItemBetweenInventoryTypes(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr) -{ +void GameMessages::HandleRequestMoveItemBetweenInventoryTypes(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr) { bool bAllowPartial; int32_t destSlot = -1; int32_t iStackCount = 1; @@ -4599,26 +4392,21 @@ void GameMessages::HandleRequestMoveItemBetweenInventoryTypes(RakNet::BitStream* if (inStream->ReadBit()) inStream->Read(subkey); if (inStream->ReadBit()) inStream->Read(itemLOT); - if (invTypeDst == invTypeSrc) - { + if (invTypeDst == invTypeSrc) { return; } auto* inventoryComponent = entity->GetComponent(); - if (inventoryComponent != nullptr) - { - if (itemID != LWOOBJID_EMPTY) - { + if (inventoryComponent != nullptr) { + if (itemID != LWOOBJID_EMPTY) { auto* item = inventoryComponent->FindItemById(itemID); - if (item == nullptr) - { + if (item == nullptr) { return; } - if (inventoryComponent->IsPet(item->GetSubKey()) || !item->GetConfig().empty()) - { + if (inventoryComponent->IsPet(item->GetSubKey()) || !item->GetConfig().empty()) { return; } @@ -4628,8 +4416,7 @@ void GameMessages::HandleRequestMoveItemBetweenInventoryTypes(RakNet::BitStream* } -void GameMessages::SendShowActivityCountdown(LWOOBJID objectId, bool bPlayAdditionalSound, bool bPlayCountdownSound, std::u16string sndName, int32_t stateToPlaySoundOn, const SystemAddress& sysAddr) -{ +void GameMessages::SendShowActivityCountdown(LWOOBJID objectId, bool bPlayAdditionalSound, bool bPlayCountdownSound, std::u16string sndName, int32_t stateToPlaySoundOn, const SystemAddress& sysAddr) { CBITSTREAM; CMSGHEADER; @@ -4641,8 +4428,7 @@ void GameMessages::SendShowActivityCountdown(LWOOBJID objectId, bool bPlayAdditi bitStream.Write(bPlayCountdownSound); bitStream.Write(static_cast(sndName.size())); - for (auto character : sndName) - { + for (auto character : sndName) { bitStream.Write(character); } @@ -4657,16 +4443,14 @@ void GameMessages::SendShowActivityCountdown(LWOOBJID objectId, bool bPlayAdditi //------------------------------------------------------------------- Handlers ------------------------------------------------------------------ //----------------------------------------------------------------------------------------------------------------------------------------------- -void GameMessages::HandleToggleGhostReferenceOverride(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr) -{ +void GameMessages::HandleToggleGhostReferenceOverride(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr) { bool bOverride = false; inStream->Read(bOverride); auto* player = Player::GetPlayer(sysAddr); - if (player != nullptr) - { + if (player != nullptr) { player->SetGhostOverride(bOverride); EntityManager::Instance()->UpdateGhosting(player); @@ -4674,16 +4458,14 @@ void GameMessages::HandleToggleGhostReferenceOverride(RakNet::BitStream* inStrea } -void GameMessages::HandleSetGhostReferencePosition(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr) -{ +void GameMessages::HandleSetGhostReferencePosition(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr) { NiPoint3 position; inStream->Read(position); auto* player = Player::GetPlayer(sysAddr); - if (player != nullptr) - { + if (player != nullptr) { player->SetGhostOverridePoint(position); EntityManager::Instance()->UpdateGhosting(player); @@ -4709,8 +4491,7 @@ void GameMessages::HandleBuyFromVendor(RakNet::BitStream* inStream, Entity* enti auto* propertyVendorComponent = static_cast(entity->GetComponent(COMPONENT_TYPE_PROPERTY_VENDOR)); - if (propertyVendorComponent != nullptr) - { + if (propertyVendorComponent != nullptr) { propertyVendorComponent->OnBuyFromVendor(player, bConfirmed, item, count); return; @@ -4739,17 +4520,14 @@ void GameMessages::HandleBuyFromVendor(RakNet::BitStream* inStream, Entity* enti inv->RemoveItem(craftingCurrency.first, craftingCurrency.second * count); } - if (isCommendationVendor) - { - if (itemComp.commendationLOT != 13763) - { + if (isCommendationVendor) { + if (itemComp.commendationLOT != 13763) { return; } auto* missionComponent = player->GetComponent(); - if (missionComponent == nullptr) - { + if (missionComponent == nullptr) { return; } @@ -4777,32 +4555,26 @@ void GameMessages::HandleBuyFromVendor(RakNet::BitStream* inStream, Entity* enti const uint32_t altCurrencyCost = itemComp.commendationCost * count; - if (inv->GetLotCount(tokenId) < altCurrencyCost) - { + if (inv->GetLotCount(tokenId) < altCurrencyCost) { return; } inv->RemoveItem(tokenId, altCurrencyCost); inv->AddItem(item, count, eLootSourceType::LOOT_SOURCE_VENDOR); - } - else - { + } else { float buyScalar = vend->GetBuyScalar(); const auto coinCost = static_cast(std::floor((itemComp.baseValue * buyScalar) * count)); - if (character->GetCoins() < coinCost) - { + if (character->GetCoins() < coinCost) { return; } - if (Inventory::IsValidItem(itemComp.currencyLOT)) - { + if (Inventory::IsValidItem(itemComp.currencyLOT)) { const uint32_t altCurrencyCost = std::floor(itemComp.altCurrencyCost * buyScalar) * count; - if (inv->GetLotCount(itemComp.currencyLOT) < altCurrencyCost) - { + if (inv->GetLotCount(itemComp.currencyLOT) < altCurrencyCost) { return; } @@ -4850,15 +4622,14 @@ void GameMessages::HandleSellToVendor(RakNet::BitStream* inStream, Entity* entit if (itemComp.baseValue == 0 || itemComp.baseValue == UINT_MAX) return; float sellScalar = vend->GetSellScalar(); - if (Inventory::IsValidItem(itemComp.currencyLOT)) - { + if (Inventory::IsValidItem(itemComp.currencyLOT)) { const auto altCurrency = (itemComp.altCurrencyCost * sellScalar) * count; inv->AddItem(itemComp.currencyLOT, std::floor(altCurrency), eLootSourceType::LOOT_SOURCE_VENDOR); // Return alt currencies like faction tokens. } //inv->RemoveItem(count, -1, iObjID); inv->MoveItemToInventory(item, eInventoryType::VENDOR_BUYBACK, count, true, false, true); - character->SetCoins(std::floor(character->GetCoins() + ((itemComp.baseValue * sellScalar)*count)), eLootSourceType::LOOT_SOURCE_VENDOR); + character->SetCoins(std::floor(character->GetCoins() + ((itemComp.baseValue * sellScalar) * count)), eLootSourceType::LOOT_SOURCE_VENDOR); //EntityManager::Instance()->SerializeEntity(player); // so inventory updates GameMessages::SendVendorTransactionResult(entity, sysAddr); } @@ -4901,17 +4672,14 @@ void GameMessages::HandleBuybackFromVendor(RakNet::BitStream* inStream, Entity* const auto cost = static_cast(std::floor(((itemComp.baseValue * sellScalar) * count))); - if (character->GetCoins() < cost) - { + if (character->GetCoins() < cost) { return; } - if (Inventory::IsValidItem(itemComp.currencyLOT)) - { + if (Inventory::IsValidItem(itemComp.currencyLOT)) { const uint32_t altCurrencyCost = std::floor(itemComp.altCurrencyCost * sellScalar) * count; - if (inv->GetLotCount(itemComp.currencyLOT) < altCurrencyCost) - { + if (inv->GetLotCount(itemComp.currencyLOT) < altCurrencyCost) { return; } @@ -4996,22 +4764,19 @@ void GameMessages::HandleFireEventServerSide(RakNet::BitStream* inStream, Entity if (param2) { mapId = rocketPad->GetDefaultZone(); - } - else { + } else { mapId = param3; } - if (mapId == 0) - { + if (mapId == 0) { mapId = rocketPad->GetSelectedMapId(player->GetObjectID()); } - if (mapId == 0) - { + if (mapId == 0) { mapId = dZoneManager::Instance()->GetZoneID().GetMapID(); // Fallback to sending the player back to the same zone. } - Game::logger->Log("FireEventServerSide", "Player %llu has requested zone transfer to (%i, %i).", sender->GetObjectID(), (int) mapId, (int) cloneId); + Game::logger->Log("FireEventServerSide", "Player %llu has requested zone transfer to (%i, %i).", sender->GetObjectID(), (int)mapId, (int)cloneId); auto* character = player->GetCharacter(); @@ -5030,7 +4795,7 @@ void GameMessages::HandleFireEventServerSide(RakNet::BitStream* inStream, Entity WorldPackets::SendTransferToWorld(sysAddr, serverIP, serverPort, mythranShift); return; - }); + }); } entity->OnFireEventServerSide(sender, GeneralUtils::UTF16ToWTF8(args), param1, param2, param3); @@ -5069,35 +4834,27 @@ void GameMessages::HandleRequestUse(RakNet::BitStream* inStream, Entity* entity, Entity* interactedObject = EntityManager::Instance()->GetEntity(objectID); - if (interactedObject == nullptr) - { + if (interactedObject == nullptr) { Game::logger->Log("GameMessages", "Object %llu tried to interact, but doesn't exist!", objectID); return; } - if (interactedObject->GetLOT() == 9524) - { + if (interactedObject->GetLOT() == 9524) { entity->GetCharacter()->SetBuildMode(true); } - if (bIsMultiInteractUse) - { - if (multiInteractType == 0) - { + if (bIsMultiInteractUse) { + if (multiInteractType == 0) { auto* missionOfferComponent = static_cast(interactedObject->GetComponent(COMPONENT_TYPE_MISSION_OFFER)); - if (missionOfferComponent != nullptr) - { + if (missionOfferComponent != nullptr) { missionOfferComponent->OfferMissions(entity, multiInteractID); } - } - else { + } else { interactedObject->OnUse(entity); } - } - else - { + } else { interactedObject->OnUse(entity); } @@ -5129,25 +4886,20 @@ void GameMessages::HandlePlayEmote(RakNet::BitStream* inStream, Entity* entity) mission->Progress(MissionTaskType::MISSION_TASK_TYPE_EMOTE, emoteID, targetID); } - if (targetID != LWOOBJID_EMPTY) - { + if (targetID != LWOOBJID_EMPTY) { auto* targetEntity = EntityManager::Instance()->GetEntity(targetID); Game::logger->Log("GameMessages", "Emote target found (%d)", targetEntity != nullptr); - if (targetEntity != nullptr) - { + if (targetEntity != nullptr) { targetEntity->OnEmoteReceived(emoteID, entity); } - } - else - { + } else { const auto scriptedEntities = EntityManager::Instance()->GetEntitiesByComponent(COMPONENT_TYPE_SCRIPT); const auto& referencePoint = entity->GetPosition(); - for (auto* scripted : scriptedEntities) - { + for (auto* scripted : scriptedEntities) { if (Vector3::DistanceSquared(scripted->GetPosition(), referencePoint) > 5.0f * 5.0f) continue; scripted->OnEmoteReceived(emoteID, entity); @@ -5177,8 +4929,7 @@ void GameMessages::HandleModularBuildConvertModel(RakNet::BitStream* inStream, E auto* item = inv->FindItemById(modelID); - if (item == nullptr) - { + if (item == nullptr) { return; } @@ -5225,8 +4976,7 @@ void GameMessages::HandleRespondToMission(RakNet::BitStream* inStream, Entity* e Mission* mission = missionComponent->GetMission(missionID); if (mission) { mission->SetReward(reward); - } - else { + } else { Game::logger->Log("GameMessages", "Unable to get mission %i for entity %llu to update reward in RespondToMission", missionID, playerID); } @@ -5268,8 +5018,7 @@ void GameMessages::HandleMissionDialogOK(RakNet::BitStream* inStream, Entity* en if (iMissionState == MissionState::MISSION_STATE_AVAILABLE || iMissionState == MissionState::MISSION_STATE_COMPLETE_AVAILABLE) { missionComponent->AcceptMission(missionID); - } - else if (iMissionState == MissionState::MISSION_STATE_READY_TO_COMPLETE || iMissionState == MissionState::MISSION_STATE_COMPLETE_READY_TO_COMPLETE) { + } else if (iMissionState == MissionState::MISSION_STATE_READY_TO_COMPLETE || iMissionState == MissionState::MISSION_STATE_COMPLETE_READY_TO_COMPLETE) { missionComponent->CompleteMission(missionID); } } @@ -5287,8 +5036,7 @@ void GameMessages::HandleRequestLinkedMission(RakNet::BitStream* inStream, Entit auto* missionOfferComponent = static_cast(entity->GetComponent(COMPONENT_TYPE_MISSION_OFFER)); - if (missionOfferComponent != nullptr) - { + if (missionOfferComponent != nullptr) { missionOfferComponent->OfferMissions(player, 0); } } @@ -5408,10 +5156,10 @@ void GameMessages::HandleEquipItem(RakNet::BitStream* inStream, Entity* entity) Item* item = inv->FindItemById(objectID); if (!item) return; - item->Equip(); + item->Equip(); - EntityManager::Instance()->SerializeEntity(entity); - } + EntityManager::Instance()->SerializeEntity(entity); +} void GameMessages::HandleUnequipItem(RakNet::BitStream* inStream, Entity* entity) { bool immediate; @@ -5501,8 +5249,7 @@ void GameMessages::HandleRemoveItemFromInventory(RakNet::BitStream* inStream, En auto* item = inv->FindItemById(iObjID); - if (item == nullptr) - { + if (item == nullptr) { return; } @@ -5510,8 +5257,7 @@ void GameMessages::HandleRemoveItemFromInventory(RakNet::BitStream* inStream, En if (bConfirmed) { for (auto i = 0; i < iStackCount; ++i) { - if (eInvType == eInventoryType::MODELS) - { + if (eInvType == eInventoryType::MODELS) { item->DisassembleModel(); } } @@ -5521,8 +5267,7 @@ void GameMessages::HandleRemoveItemFromInventory(RakNet::BitStream* inStream, En auto* missionComponent = entity->GetComponent(); - if (missionComponent != nullptr) - { + if (missionComponent != nullptr) { missionComponent->Progress(MissionTaskType::MISSION_TASK_TYPE_ITEM_COLLECTION, item->GetLot(), LWOOBJID_EMPTY, "", -iStackCount); } } @@ -5547,8 +5292,7 @@ void GameMessages::HandleMoveItemInInventory(RakNet::BitStream* inStream, Entity auto* item = inv->FindItemById(iObjID); - if (!item) - { + if (!item) { return; } @@ -5648,12 +5392,9 @@ void GameMessages::HandleModularBuildFinish(RakNet::BitStream* inStream, Entity* modules += u"1:" + (GeneralUtils::to_u16string(mod)); if (k + 1 != count) modules += u"+"; - if (temp->GetLotCount(mod) > 0) - { + if (temp->GetLotCount(mod) > 0) { inv->RemoveItem(mod, 1, TEMP_MODELS); - } - else - { + } else { inv->RemoveItem(mod, 1); } } @@ -5663,21 +5404,16 @@ void GameMessages::HandleModularBuildFinish(RakNet::BitStream* inStream, Entity* std::vector config; config.push_back(moduleAssembly); - if (count == 3) - { + if (count == 3) { inv->AddItem(6416, 1, eLootSourceType::LOOT_SOURCE_QUICKBUILD, eInventoryType::MODELS, config); - } - else if (count == 7) - { + } else if (count == 7) { inv->AddItem(8092, 1, eLootSourceType::LOOT_SOURCE_QUICKBUILD, eInventoryType::MODELS, config); } auto* missionComponent = character->GetComponent(); - if (entity->GetLOT() != 9980 || Game::server->GetZoneID() != 1200) - { - if (missionComponent != nullptr) - { + if (entity->GetLOT() != 9980 || Game::server->GetZoneID() != 1200) { + if (missionComponent != nullptr) { missionComponent->Progress(MissionTaskType::MISSION_TASK_TYPE_SCRIPT, entity->GetLOT(), entity->GetObjectID()); } } @@ -5692,13 +5428,11 @@ void GameMessages::HandleModularBuildFinish(RakNet::BitStream* inStream, Entity* // Move remaining temp models back to models std::vector items; - for (const auto& pair : temp->GetItems()) - { + for (const auto& pair : temp->GetItems()) { items.push_back(pair.second); } - for (auto* item : items) - { + for (auto* item : items) { inv->MoveItemToInventory(item, eInventoryType::MODELS, item->GetCount(), false); } } @@ -5767,13 +5501,11 @@ void GameMessages::HandleDoneArrangingWithItem(RakNet::BitStream* inStream, Enti if (!buildAreas.empty()) { buildArea = buildAreas[0]; - } - else if (!entities.empty()) { + } else if (!entities.empty()) { buildArea = entities[0]; Game::logger->Log("BuildBorderComponent", "Using PropertyPlaque"); - } - else { + } else { Game::logger->Log("BuildBorderComponent", "No build area found"); return; @@ -5807,13 +5539,11 @@ void GameMessages::HandleDoneArrangingWithItem(RakNet::BitStream* inStream, Enti std::vector items; - for (const auto& pair : inventory->GetItems()) - { + for (const auto& pair : inventory->GetItems()) { items.push_back(pair.second); } - for (auto* item : items) - { + for (auto* item : items) { inv->MoveItemToInventory(item, eInventoryType::MODELS, item->GetCount(), false, false); } } @@ -5835,8 +5565,7 @@ void GameMessages::HandleModularBuildMoveAndEquip(RakNet::BitStream* inStream, E auto* item = inv->FindItemByLot(templateID, TEMP_MODELS); - if (item == nullptr) - { + if (item == nullptr) { return; } @@ -5853,10 +5582,8 @@ void GameMessages::HandlePickupItem(RakNet::BitStream* inStream, Entity* entity) auto* team = TeamManager::Instance()->GetTeam(entity->GetObjectID()); - if (team != nullptr) - { - for (const auto memberId : team->members) - { + if (team != nullptr) { + for (const auto memberId : team->members) { auto* member = EntityManager::Instance()->GetEntity(memberId); if (member == nullptr || memberId == playerID) continue; @@ -5898,31 +5625,27 @@ void GameMessages::HandlePopEquippedItemsState(RakNet::BitStream* inStream, Enti } -void GameMessages::HandleClientItemConsumed(RakNet::BitStream* inStream, Entity* entity) -{ +void GameMessages::HandleClientItemConsumed(RakNet::BitStream* inStream, Entity* entity) { LWOOBJID itemConsumed; inStream->Read(itemConsumed); auto* inventory = static_cast(entity->GetComponent(COMPONENT_TYPE_INVENTORY)); - if (inventory == nullptr) - { + if (inventory == nullptr) { return; } auto* item = inventory->FindItemById(itemConsumed); - if (item == nullptr) - { + if (item == nullptr) { return; } item->Consume(); auto* missions = static_cast(entity->GetComponent(COMPONENT_TYPE_MISSION)); - if (missions != nullptr) - { + if (missions != nullptr) { missions->Progress(MissionTaskType::MISSION_TASK_TYPE_FOOD, item->GetLot()); } } @@ -5939,8 +5662,7 @@ void GameMessages::HandleUseNonEquipmentItem(RakNet::BitStream* inStream, Entity auto* item = inv->FindItemById(itemConsumed); - if (item == nullptr) - { + if (item == nullptr) { return; } @@ -5979,12 +5701,10 @@ void GameMessages::HandleMatchRequest(RakNet::BitStream* inStream, Entity* entit comp->PlayerJoin(entity); } } - } - else { + } else { } - } - else if (type == 1) { // ready/unready + } else if (type == 1) { // ready/unready for (Entity* scriptedAct : scriptedActs) { ScriptedActivityComponent* comp = static_cast(scriptedAct->GetComponent(COMPONENT_TYPE_SCRIPTED_ACTIVITY)); if (!comp) continue; @@ -6001,43 +5721,43 @@ void GameMessages::HandleGetHotPropertyData(RakNet::BitStream* inStream, Entity* void GameMessages::SendGetHotPropertyData(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr) { CBITSTREAM - CMSGHEADER - /** - * [u32] - Number of properties - * [objid] - property id - * [objid] - property owner id - * [wstring] - property owner name - * [u64] - total reputation - * [i32] - property template id - * [wstring] - property name - * [wstring] - property description - * [float] - performance cost - * [timestamp] - time last published - * [cloneid] - clone id - * - */ - // TODO This needs to be implemented when reputation is implemented for getting hot properties. - /** - bitStream.Write(entity->GetObjectID()); - bitStream.Write(GAME_MSG::GAME_MSG_SEND_HOT_PROPERTY_DATA); - std::vector t = {25166, 25188, 25191, 25194}; - bitStream.Write(4); - for (uint8_t i = 0; i < 4; i++) { - bitStream.Write(entity->GetObjectID()); - bitStream.Write(entity->GetObjectID()); - bitStream.Write(1); - bitStream.Write('c'); - bitStream.Write(42069); - bitStream.Write(t[i]); - bitStream.Write(1); - bitStream.Write('c'); - bitStream.Write(1); - bitStream.Write('c'); - bitStream.Write(420.69f); - bitStream.Write(1658376385); - bitStream.Write(25166); - } - SEND_PACKET*/ + CMSGHEADER + /** + * [u32] - Number of properties + * [objid] - property id + * [objid] - property owner id + * [wstring] - property owner name + * [u64] - total reputation + * [i32] - property template id + * [wstring] - property name + * [wstring] - property description + * [float] - performance cost + * [timestamp] - time last published + * [cloneid] - clone id + * + */ + // TODO This needs to be implemented when reputation is implemented for getting hot properties. + /** + bitStream.Write(entity->GetObjectID()); + bitStream.Write(GAME_MSG::GAME_MSG_SEND_HOT_PROPERTY_DATA); + std::vector t = {25166, 25188, 25191, 25194}; + bitStream.Write(4); + for (uint8_t i = 0; i < 4; i++) { + bitStream.Write(entity->GetObjectID()); + bitStream.Write(entity->GetObjectID()); + bitStream.Write(1); + bitStream.Write('c'); + bitStream.Write(42069); + bitStream.Write(t[i]); + bitStream.Write(1); + bitStream.Write('c'); + bitStream.Write(1); + bitStream.Write('c'); + bitStream.Write(420.69f); + bitStream.Write(1658376385); + bitStream.Write(25166); + } + SEND_PACKET*/ } void GameMessages::HandleReportBug(RakNet::BitStream* inStream, Entity* entity) { @@ -6097,14 +5817,13 @@ void GameMessages::HandleReportBug(RakNet::BitStream* inStream, Entity* entity) insertBug->setInt(5, reporterID); insertBug->execute(); delete insertBug; - } - catch (sql::SQLException& e) { + } catch (sql::SQLException& e) { Game::logger->Log("HandleReportBug", "Couldn't save bug report! (%s)", e.what()); } } void -GameMessages::HandleClientRailMovementReady(RakNet::BitStream *inStream, Entity *entity, const SystemAddress &sysAddr) { +GameMessages::HandleClientRailMovementReady(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr) { const auto possibleRails = EntityManager::Instance()->GetEntitiesByComponent(COMPONENT_TYPE_RAIL_ACTIVATOR); for (const auto* possibleRail : possibleRails) { const auto* rail = possibleRail->GetComponent(); @@ -6114,7 +5833,7 @@ GameMessages::HandleClientRailMovementReady(RakNet::BitStream *inStream, Entity } } -void GameMessages::HandleCancelRailMovement(RakNet::BitStream *inStream, Entity *entity, const SystemAddress &sysAddr) { +void GameMessages::HandleCancelRailMovement(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr) { const auto immediate = inStream->ReadBit(); const auto possibleRails = EntityManager::Instance()->GetEntitiesByComponent(COMPONENT_TYPE_RAIL_ACTIVATOR); @@ -6126,8 +5845,8 @@ void GameMessages::HandleCancelRailMovement(RakNet::BitStream *inStream, Entity } } -void GameMessages::HandlePlayerRailArrivedNotification(RakNet::BitStream *inStream, Entity *entity, - const SystemAddress &sysAddr) { +void GameMessages::HandlePlayerRailArrivedNotification(RakNet::BitStream* inStream, Entity* entity, + const SystemAddress& sysAddr) { uint32_t pathNameLength; inStream->Read(pathNameLength); @@ -6149,7 +5868,7 @@ void GameMessages::HandlePlayerRailArrivedNotification(RakNet::BitStream *inStre } } -void GameMessages::HandleModifyPlayerZoneStatistic(RakNet::BitStream *inStream, Entity *entity) { +void GameMessages::HandleModifyPlayerZoneStatistic(RakNet::BitStream* inStream, Entity* entity) { const auto set = inStream->ReadBit(); const auto statisticsName = GeneralUtils::ReadWString(inStream); @@ -6187,6 +5906,6 @@ void GameMessages::HandleUpdatePlayerStatistic(RakNet::BitStream* inStream, Enti auto* characterComponent = entity->GetComponent(); if (characterComponent != nullptr) { - characterComponent->UpdatePlayerStatistic((StatisticID) updateID, (uint64_t) std::max(updateValue, int64_t(0))); + characterComponent->UpdatePlayerStatistic((StatisticID)updateID, (uint64_t)std::max(updateValue, int64_t(0))); } } diff --git a/dGame/dGameMessages/GameMessages.h b/dGame/dGameMessages/GameMessages.h index c5b7888d..47e5f41c 100644 --- a/dGame/dGameMessages/GameMessages.h +++ b/dGame/dGameMessages/GameMessages.h @@ -25,9 +25,9 @@ namespace GameMessages { void SendFireEventClientSide(const LWOOBJID& objectID, const SystemAddress& sysAddr, std::u16string args, const LWOOBJID& object, int64_t param1, int param2, const LWOOBJID& sender); void SendTeleport(const LWOOBJID& objectID, const NiPoint3& pos, const NiQuaternion& rot, const SystemAddress& sysAddr, bool bSetRotation = false, bool noGravTeleport = true); void SendPlayAnimation(Entity* entity, const std::u16string& animationName, float fPriority = 0.0f, float fScale = 1.0f); - void SendPlayerReady(Entity * entity, const SystemAddress& sysAddr); + void SendPlayerReady(Entity* entity, const SystemAddress& sysAddr); void SendPlayerAllowedRespawn(LWOOBJID entityID, bool doNotPromptRespawn, const SystemAddress& systemAddress); - void SendInvalidZoneTransferList(Entity * entity, const SystemAddress& sysAddr, const std::u16string& feedbackURL, const std::u16string& invalidMapTransferList, bool feedbackOnExit, bool feedbackOnInvalidTransfer); + void SendInvalidZoneTransferList(Entity* entity, const SystemAddress& sysAddr, const std::u16string& feedbackURL, const std::u16string& invalidMapTransferList, bool feedbackOnExit, bool feedbackOnInvalidTransfer); void SendKnockback(const LWOOBJID& objectID, const LWOOBJID& caster, const LWOOBJID& originator, int knockBackTimeMS, const NiPoint3& vector); void SendStartArrangingWithItem( @@ -47,27 +47,27 @@ namespace GameMessages { ); void SendPlayerSetCameraCyclingMode(const LWOOBJID& objectID, const SystemAddress& sysAddr, - bool bAllowCyclingWhileDeadOnly = true, eCyclingMode cyclingMode = ALLOW_CYCLE_TEAMMATES); + bool bAllowCyclingWhileDeadOnly = true, eCyclingMode cyclingMode = ALLOW_CYCLE_TEAMMATES); void SendPlayNDAudioEmitter(Entity* entity, const SystemAddress& sysAddr, std::string audioGUID); void SendStartPathing(Entity* entity); void SendPlatformResync(Entity* entity, const SystemAddress& sysAddr, bool bStopAtDesiredWaypoint = false, - int iIndex = 0, int iDesiredWaypointIndex = 1, int nextIndex = 1, - MovementPlatformState movementState = MovementPlatformState::Moving); - - void SendRestoreToPostLoadStats(Entity * entity, const SystemAddress& sysAddr); - void SendServerDoneLoadingAllObjects(Entity * entity, const SystemAddress& sysAddr); + int iIndex = 0, int iDesiredWaypointIndex = 1, int nextIndex = 1, + MovementPlatformState movementState = MovementPlatformState::Moving); + + void SendRestoreToPostLoadStats(Entity* entity, const SystemAddress& sysAddr); + void SendServerDoneLoadingAllObjects(Entity* entity, const SystemAddress& sysAddr); void SendGMLevelBroadcast(const LWOOBJID& objectID, uint8_t level); void SendChatModeUpdate(const LWOOBJID& objectID, uint8_t level); - + void SendAddItemToInventoryClientSync(Entity* entity, const SystemAddress& sysAddr, Item* item, const LWOOBJID& objectID, bool showFlyingLoot, int itemCount, LWOOBJID subKey = LWOOBJID_EMPTY, eLootSourceType lootSourceType = eLootSourceType::LOOT_SOURCE_NONE); void SendNotifyClientFlagChange(const LWOOBJID& objectID, int iFlagID, bool bFlag, const SystemAddress& sysAddr); void SendChangeObjectWorldState(const LWOOBJID& objectID, int state, const SystemAddress& sysAddr); - + void SendOfferMission(const LWOOBJID& entity, const SystemAddress& sysAddr, int32_t missionID, const LWOOBJID& offererID); - void SendNotifyMission(Entity * entity, const SystemAddress& sysAddr, int missionID, int missionState, bool sendingRewards); - void SendNotifyMissionTask(Entity * entity, const SystemAddress& sysAddr, int missionID, int taskMask, std::vector updates); + void SendNotifyMission(Entity* entity, const SystemAddress& sysAddr, int missionID, int missionState, bool sendingRewards); + void SendNotifyMissionTask(Entity* entity, const SystemAddress& sysAddr, int missionID, int taskMask, std::vector updates); void NotifyLevelRewards(LWOOBJID objectID, const SystemAddress& sysAddr, int level, bool sending_rewards); void SendModifyLEGOScore(Entity* entity, const SystemAddress& sysAddr, int64_t score, eLootSourceType sourceType); @@ -90,7 +90,7 @@ namespace GameMessages { void SendDie(Entity* entity, const LWOOBJID& killerID, const LWOOBJID& lootOwnerID, bool bDieAccepted, eKillType killType, std::u16string deathType, float directionRelative_AngleY, float directionRelative_AngleXZ, float directionRelative_Force, bool bClientDeath, bool bSpawnLoot, float coinSpawnTime); void SendSetInventorySize(Entity* entity, int invType, int size); - + void SendSetEmoteLockState(Entity* entity, bool bLock, int emoteID); void SendSetJetPackMode(Entity* entity, bool use, bool bypassChecks = false, bool doHover = false, int effectID = -1, float airspeed = 10, float maxAirspeed = 15, float verticalVelocity = 1, int warningEffectID = -1); void SendResurrect(Entity* entity); @@ -124,7 +124,7 @@ namespace GameMessages { /** * Sends a message to an Entity to smash itself, but not delete or destroy itself from the world - * + * * @param entity The Entity that will smash itself into bricks * @param force The force the Entity will be smashed with * @param ghostOpacity The ghosting opacity of the smashed Entity @@ -135,7 +135,7 @@ namespace GameMessages { /** * Sends a message to an Entity to UnSmash itself (aka rebuild itself over a duration) - * + * * @param entity The Entity that will UnSmash itself * @param builderID The Entity that invoked the build (LWOOBJID_EMPTY if none exists or invoked the rebuild) * @param duration The duration for the Entity to rebuild over. 3 seconds by default @@ -144,11 +144,11 @@ namespace GameMessages { /** * @brief This GameMessage is the one that handles all of the property behavior incoming messages from the client. - * + * * The GameMessage struct can be located here https://lcdruniverse.org/lu_packets/lu_packets/world/gm/server/struct.ControlBehaviors.html * For information on the AMF3 format can be found here https://rtmp.veriskope.com/pdf/amf3-file-format-spec.pdf * For any questions regarding AMF3 you can contact EmosewaMC on GitHub - * + * * @param inStream The incoming data sent from the client * @param entity The Entity that sent the message * @param sysAddr The SystemAddress that sent the message @@ -157,15 +157,15 @@ namespace GameMessages { // Rails stuff void SendSetRailMovement(const LWOOBJID& objectID, bool pathGoForward, std::u16string pathName, uint32_t pathStart, - const SystemAddress& sysAddr = UNASSIGNED_SYSTEM_ADDRESS, - int32_t railActivatorComponentID = -1, LWOOBJID railActivatorObjectID = LWOOBJID_EMPTY); + const SystemAddress& sysAddr = UNASSIGNED_SYSTEM_ADDRESS, + int32_t railActivatorComponentID = -1, LWOOBJID railActivatorObjectID = LWOOBJID_EMPTY); void SendStartRailMovement(const LWOOBJID& objectID, std::u16string pathName, std::u16string startSound, - std::u16string loopSound, std::u16string stopSound, const SystemAddress& sysAddr = UNASSIGNED_SYSTEM_ADDRESS, - uint32_t pathStart = 0, bool goForward = true, bool damageImmune = true, bool noAggro = true, - bool notifyActor = false, bool showNameBillboard = true, bool cameraLocked = true, - bool collisionEnabled = true, bool useDB = true, int32_t railComponentID = -1, - LWOOBJID railActivatorObjectID = LWOOBJID_EMPTY); + std::u16string loopSound, std::u16string stopSound, const SystemAddress& sysAddr = UNASSIGNED_SYSTEM_ADDRESS, + uint32_t pathStart = 0, bool goForward = true, bool damageImmune = true, bool noAggro = true, + bool notifyActor = false, bool showNameBillboard = true, bool cameraLocked = true, + bool collisionEnabled = true, bool useDB = true, int32_t railComponentID = -1, + LWOOBJID railActivatorObjectID = LWOOBJID_EMPTY); void HandleClientRailMovementReady(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr); void HandleCancelRailMovement(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr); @@ -175,14 +175,14 @@ namespace GameMessages { void SendNotifyClientZoneObject(const LWOOBJID& objectID, const std::u16string& name, int param1, int param2, const LWOOBJID& paramObj, const std::string& paramStr, const SystemAddress& sysAddr); void SendNotifyClientFailedPrecondition(LWOOBJID objectId, const SystemAddress& sysAddr, const std::u16string& failedReason, int preconditionID); - + // The success or failure response sent back to the client will preserve the same value for localID. void SendBBBSaveResponse(const LWOOBJID& objectId, const LWOOBJID& localID, unsigned char* buffer, uint32_t bufferSize, const SystemAddress& sysAddr); void SendAddBuff(LWOOBJID& objectID, const LWOOBJID& casterID, uint32_t buffID, uint32_t msDuration, - bool addImmunity = false, bool cancelOnDamaged = false, bool cancelOnDeath = true, - bool cancelOnLogout = false, bool cancelOnRemoveBuff = true, bool cancelOnUi = false, - bool cancelOnUnequip = false, bool cancelOnZone = false, const SystemAddress& sysAddr = UNASSIGNED_SYSTEM_ADDRESS); + bool addImmunity = false, bool cancelOnDamaged = false, bool cancelOnDeath = true, + bool cancelOnLogout = false, bool cancelOnRemoveBuff = true, bool cancelOnUi = false, + bool cancelOnUnequip = false, bool cancelOnZone = false, const SystemAddress& sysAddr = UNASSIGNED_SYSTEM_ADDRESS); void SendToggleGMInvis(LWOOBJID objectId, bool enabled, const SystemAddress& sysAddr); @@ -209,7 +209,7 @@ namespace GameMessages { void SendPlaceModelResponse(LWOOBJID objectId, const SystemAddress& sysAddr, NiPoint3 position, LWOOBJID plaque, int32_t response, NiQuaternion rotation); void SendUGCEquipPreCreateBasedOnEditMode(LWOOBJID objectId, const SystemAddress& sysAddr, int modelCount, LWOOBJID model); - + void SendUGCEquipPostDeleteBasedOnEditMode(LWOOBJID objectId, const SystemAddress& sysAddr, LWOOBJID inventoryItem, int itemTotal); void HandleSetPropertyAccess(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr); @@ -219,11 +219,11 @@ namespace GameMessages { void HandleQueryPropertyData(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr); void HandleSetBuildMode(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr); - + void HandleStartBuildingWithItem(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr); void HandlePropertyEditorBegin(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr); - + void HandlePropertyEditorEnd(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr); void HandlePropertyContentsFromClient(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr); @@ -246,13 +246,13 @@ namespace GameMessages { void HandleSetConsumableItem(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr); - void SendPlayCinematic(LWOOBJID objectId, std::u16string pathName, const SystemAddress& sysAddr, + void SendPlayCinematic(LWOOBJID objectId, std::u16string pathName, const SystemAddress& sysAddr, bool allowGhostUpdates = true, bool bCloseMultiInteract = true, bool bSendServerNotify = false, bool bUseControlledObjectForAudioListener = false, int endBehavior = 0, bool hidePlayerDuringCine = false, float leadIn = -1, bool leavePlayerLockedWhenFinished = false, bool lockPlayer = true, bool result = false, bool skipIfSamePath = false, float startTimeAdvance = 0); void SendEndCinematic(LWOOBJID objectID, std::u16string pathName, const SystemAddress& sysAddr = UNASSIGNED_SYSTEM_ADDRESS, - float leadOut = -1.0f, bool leavePlayerLocked = false); + float leadOut = -1.0f, bool leavePlayerLocked = false); void HandleCinematicUpdate(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr); void SendSetStunned(LWOOBJID objectId, eStunState stateChangeType, const SystemAddress& sysAddr, @@ -392,7 +392,7 @@ namespace GameMessages { /** * @brief A request from a client to get the hot properties that would appear on the news feed * This incoming message has NO DATA and is simply a request that expects to send a reply to the sender. - * + * * @param inStream packet of data * @param entity The Entity that sent the request * @param sysAddr The SystemAddress of the Entity that sent the request @@ -402,7 +402,7 @@ namespace GameMessages { /** * @brief A request from a client to get the hot properties that would appear on the news feed * The struct of data to send is as follows - * + * * [u32] - Number of properties * [objid] - property id * [objid] - property owner id @@ -414,7 +414,7 @@ namespace GameMessages { * [float] - performance cost * [timestamp] - time last published * [cloneid] - clone id - * + * * @param inStream packet of data * @param entity The Entity that sent the request * @param sysAddr The SystemAddress of the Entity that sent the request @@ -493,12 +493,12 @@ namespace GameMessages { // Leaderboards void SendActivitySummaryLeaderboardData(const LWOOBJID& objectID, const Leaderboard* leaderboard, - const SystemAddress& sysAddr = UNASSIGNED_SYSTEM_ADDRESS); + const SystemAddress& sysAddr = UNASSIGNED_SYSTEM_ADDRESS); void HandleActivitySummaryLeaderboardData(RakNet::BitStream* instream, Entity* entity, const SystemAddress& sysAddr); void SendRequestActivitySummaryLeaderboardData(const LWOOBJID& objectID, const LWOOBJID& targetID, - const SystemAddress& sysAddr, const int32_t& gameID = 0, - const int32_t& queryType = 1, const int32_t& resultsEnd = 10, - const int32_t& resultsStart = 0, bool weekly = false); + const SystemAddress& sysAddr, const int32_t& gameID = 0, + const int32_t& queryType = 1, const int32_t& resultsEnd = 10, + const int32_t& resultsStart = 0, bool weekly = false); void HandleRequestActivitySummaryLeaderboardData(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr); void HandleActivityStateChangeRequest(RakNet::BitStream* inStream, Entity* entity); @@ -509,13 +509,13 @@ namespace GameMessages { void SendVehicleNotifyFinishedRace(LWOOBJID objectId, const SystemAddress& sysAddr); //NT: - + void HandleRequestMoveItemBetweenInventoryTypes(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr); void SendShowActivityCountdown(LWOOBJID objectId, bool bPlayAdditionalSound, bool bPlayCountdownSound, std::u16string sndName, int32_t stateToPlaySoundOn, const SystemAddress& sysAddr); //Handlers: - + void HandleToggleGhostReferenceOverride(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr); void HandleSetGhostReferencePosition(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr); @@ -558,555 +558,555 @@ namespace GameMessages { void HandlePopEquippedItemsState(RakNet::BitStream* inStream, Entity* entity); void HandleClientItemConsumed(RakNet::BitStream* inStream, Entity* entity); - + void HandleUseNonEquipmentItem(RakNet::BitStream* inStream, Entity* entity); void HandleMatchRequest(RakNet::BitStream* inStream, Entity* entity); void HandleReportBug(RakNet::BitStream* inStream, Entity* entity); - /* Message to synchronize a skill cast */ - class EchoSyncSkill { - static const GAME_MSG MsgID = GAME_MSG_ECHO_SYNC_SKILL; + /* Message to synchronize a skill cast */ + class EchoSyncSkill { + static const GAME_MSG MsgID = GAME_MSG_ECHO_SYNC_SKILL; - public: - EchoSyncSkill() { - bDone = false; - } + public: + EchoSyncSkill() { + bDone = false; + } - EchoSyncSkill(std::string _sBitStream, unsigned int _uiBehaviorHandle, unsigned int _uiSkillHandle, bool _bDone = false) { - bDone = _bDone; - sBitStream = _sBitStream; - uiBehaviorHandle = _uiBehaviorHandle; - uiSkillHandle = _uiSkillHandle; - } + EchoSyncSkill(std::string _sBitStream, unsigned int _uiBehaviorHandle, unsigned int _uiSkillHandle, bool _bDone = false) { + bDone = _bDone; + sBitStream = _sBitStream; + uiBehaviorHandle = _uiBehaviorHandle; + uiSkillHandle = _uiSkillHandle; + } - EchoSyncSkill(RakNet::BitStream* stream) { - bDone = false; + EchoSyncSkill(RakNet::BitStream* stream) { + bDone = false; - Deserialize(stream); - } + Deserialize(stream); + } - ~EchoSyncSkill() { - } - - void Serialize(RakNet::BitStream* stream) { - stream->Write((unsigned short)MsgID); + ~EchoSyncSkill() { + } - stream->Write(bDone); - uint32_t sBitStreamLength = sBitStream.length(); - stream->Write(sBitStreamLength); - for (unsigned int k = 0; k < sBitStreamLength; k++) { - stream->Write(sBitStream[k]); - } + void Serialize(RakNet::BitStream* stream) { + stream->Write((unsigned short)MsgID); - stream->Write(uiBehaviorHandle); - stream->Write(uiSkillHandle); - } - - bool Deserialize(RakNet::BitStream* stream) { - stream->Read(bDone); - uint32_t sBitStreamLength{}; - stream->Read(sBitStreamLength); - for (unsigned int k = 0; k < sBitStreamLength; k++) { - unsigned char character; - stream->Read(character); - sBitStream.push_back(character); - } + stream->Write(bDone); + uint32_t sBitStreamLength = sBitStream.length(); + stream->Write(sBitStreamLength); + for (unsigned int k = 0; k < sBitStreamLength; k++) { + stream->Write(sBitStream[k]); + } - stream->Read(uiBehaviorHandle); - stream->Read(uiSkillHandle); + stream->Write(uiBehaviorHandle); + stream->Write(uiSkillHandle); + } - return true; - } + bool Deserialize(RakNet::BitStream* stream) { + stream->Read(bDone); + uint32_t sBitStreamLength{}; + stream->Read(sBitStreamLength); + for (unsigned int k = 0; k < sBitStreamLength; k++) { + unsigned char character; + stream->Read(character); + sBitStream.push_back(character); + } - bool bDone{}; - std::string sBitStream{}; - unsigned int uiBehaviorHandle{}; - unsigned int uiSkillHandle{}; - }; + stream->Read(uiBehaviorHandle); + stream->Read(uiSkillHandle); + + return true; + } + + bool bDone{}; + std::string sBitStream{}; + unsigned int uiBehaviorHandle{}; + unsigned int uiSkillHandle{}; + }; /* Message to synchronize a skill cast */ - class SyncSkill { - static const GAME_MSG MsgID = GAME_MSG_SYNC_SKILL; + class SyncSkill { + static const GAME_MSG MsgID = GAME_MSG_SYNC_SKILL; - public: - SyncSkill() { - bDone = false; - } + public: + SyncSkill() { + bDone = false; + } - SyncSkill(std::string _sBitStream, unsigned int _uiBehaviorHandle, unsigned int _uiSkillHandle, bool _bDone = false) { - bDone = _bDone; - sBitStream = _sBitStream; - uiBehaviorHandle = _uiBehaviorHandle; - uiSkillHandle = _uiSkillHandle; - } + SyncSkill(std::string _sBitStream, unsigned int _uiBehaviorHandle, unsigned int _uiSkillHandle, bool _bDone = false) { + bDone = _bDone; + sBitStream = _sBitStream; + uiBehaviorHandle = _uiBehaviorHandle; + uiSkillHandle = _uiSkillHandle; + } - SyncSkill(RakNet::BitStream* stream) { - bDone = false; - Deserialize(stream); - } + SyncSkill(RakNet::BitStream* stream) { + bDone = false; + Deserialize(stream); + } - ~SyncSkill() { - } - - void Serialize(RakNet::BitStream* stream) { - stream->Write((unsigned short)MsgID); + ~SyncSkill() { + } - stream->Write(bDone); - uint32_t sBitStreamLength = sBitStream.length(); - stream->Write(sBitStreamLength); - for (unsigned int k = 0; k < sBitStreamLength; k++) { - stream->Write(sBitStream[k]); - } + void Serialize(RakNet::BitStream* stream) { + stream->Write((unsigned short)MsgID); - stream->Write(uiBehaviorHandle); - stream->Write(uiSkillHandle); - } - - bool Deserialize(RakNet::BitStream* stream) { - stream->Read(bDone); - uint32_t sBitStreamLength{}; - stream->Read(sBitStreamLength); - for (unsigned int k = 0; k < sBitStreamLength; k++) { - unsigned char character; - stream->Read(character); - sBitStream.push_back(character); - } + stream->Write(bDone); + uint32_t sBitStreamLength = sBitStream.length(); + stream->Write(sBitStreamLength); + for (unsigned int k = 0; k < sBitStreamLength; k++) { + stream->Write(sBitStream[k]); + } - stream->Read(uiBehaviorHandle); - stream->Read(uiSkillHandle); + stream->Write(uiBehaviorHandle); + stream->Write(uiSkillHandle); + } - return true; - } + bool Deserialize(RakNet::BitStream* stream) { + stream->Read(bDone); + uint32_t sBitStreamLength{}; + stream->Read(sBitStreamLength); + for (unsigned int k = 0; k < sBitStreamLength; k++) { + unsigned char character; + stream->Read(character); + sBitStream.push_back(character); + } - bool bDone{}; - std::string sBitStream{}; - unsigned int uiBehaviorHandle{}; - unsigned int uiSkillHandle{}; - }; + stream->Read(uiBehaviorHandle); + stream->Read(uiSkillHandle); + + return true; + } + + bool bDone{}; + std::string sBitStream{}; + unsigned int uiBehaviorHandle{}; + unsigned int uiSkillHandle{}; + }; /* Notifying the server that a locally owned projectil impacted. Sent to the caster of the projectile should always be the local char. */ - class RequestServerProjectileImpact { - static const GAME_MSG MsgID = GAME_MSG_REQUEST_SERVER_PROJECTILE_IMPACT; + class RequestServerProjectileImpact { + static const GAME_MSG MsgID = GAME_MSG_REQUEST_SERVER_PROJECTILE_IMPACT; - public: - RequestServerProjectileImpact() { - i64LocalID = LWOOBJID_EMPTY; - i64TargetID = LWOOBJID_EMPTY; - } + public: + RequestServerProjectileImpact() { + i64LocalID = LWOOBJID_EMPTY; + i64TargetID = LWOOBJID_EMPTY; + } - RequestServerProjectileImpact(std::string _sBitStream, LWOOBJID _i64LocalID = LWOOBJID_EMPTY, LWOOBJID _i64TargetID = LWOOBJID_EMPTY) { - i64LocalID = _i64LocalID; - i64TargetID = _i64TargetID; - sBitStream = _sBitStream; - } + RequestServerProjectileImpact(std::string _sBitStream, LWOOBJID _i64LocalID = LWOOBJID_EMPTY, LWOOBJID _i64TargetID = LWOOBJID_EMPTY) { + i64LocalID = _i64LocalID; + i64TargetID = _i64TargetID; + sBitStream = _sBitStream; + } - RequestServerProjectileImpact(RakNet::BitStream* stream) { - i64LocalID = LWOOBJID_EMPTY; - i64TargetID = LWOOBJID_EMPTY; + RequestServerProjectileImpact(RakNet::BitStream* stream) { + i64LocalID = LWOOBJID_EMPTY; + i64TargetID = LWOOBJID_EMPTY; - Deserialize(stream); - } + Deserialize(stream); + } - ~RequestServerProjectileImpact() { - } - - void Serialize(RakNet::BitStream* stream) { - stream->Write((unsigned short)MsgID); + ~RequestServerProjectileImpact() { + } - stream->Write(i64LocalID != LWOOBJID_EMPTY); - if (i64LocalID != LWOOBJID_EMPTY) stream->Write(i64LocalID); + void Serialize(RakNet::BitStream* stream) { + stream->Write((unsigned short)MsgID); - stream->Write(i64TargetID != LWOOBJID_EMPTY); - if (i64TargetID != LWOOBJID_EMPTY) stream->Write(i64TargetID); + stream->Write(i64LocalID != LWOOBJID_EMPTY); + if (i64LocalID != LWOOBJID_EMPTY) stream->Write(i64LocalID); - uint32_t sBitStreamLength = sBitStream.length(); - stream->Write(sBitStreamLength); - for (unsigned int k = 0; k < sBitStreamLength; k++) { - stream->Write(sBitStream[k]); - } + stream->Write(i64TargetID != LWOOBJID_EMPTY); + if (i64TargetID != LWOOBJID_EMPTY) stream->Write(i64TargetID); - } - - bool Deserialize(RakNet::BitStream* stream) { - bool i64LocalIDIsDefault{}; - stream->Read(i64LocalIDIsDefault); - if (i64LocalIDIsDefault != 0) stream->Read(i64LocalID); + uint32_t sBitStreamLength = sBitStream.length(); + stream->Write(sBitStreamLength); + for (unsigned int k = 0; k < sBitStreamLength; k++) { + stream->Write(sBitStream[k]); + } - bool i64TargetIDIsDefault{}; - stream->Read(i64TargetIDIsDefault); - if (i64TargetIDIsDefault != 0) stream->Read(i64TargetID); + } - uint32_t sBitStreamLength{}; - stream->Read(sBitStreamLength); - for (unsigned int k = 0; k < sBitStreamLength; k++) { - unsigned char character; - stream->Read(character); - sBitStream.push_back(character); - } + bool Deserialize(RakNet::BitStream* stream) { + bool i64LocalIDIsDefault{}; + stream->Read(i64LocalIDIsDefault); + if (i64LocalIDIsDefault != 0) stream->Read(i64LocalID); + + bool i64TargetIDIsDefault{}; + stream->Read(i64TargetIDIsDefault); + if (i64TargetIDIsDefault != 0) stream->Read(i64TargetID); + + uint32_t sBitStreamLength{}; + stream->Read(sBitStreamLength); + for (unsigned int k = 0; k < sBitStreamLength; k++) { + unsigned char character; + stream->Read(character); + sBitStream.push_back(character); + } - return true; - } + return true; + } - LWOOBJID i64LocalID; - LWOOBJID i64TargetID; - std::string sBitStream; - }; + LWOOBJID i64LocalID; + LWOOBJID i64TargetID; + std::string sBitStream; + }; /* Tell a client local projectile to impact */ - class DoClientProjectileImpact { - static const GAME_MSG MsgID = GAME_MSG_DO_CLIENT_PROJECTILE_IMPACT; + class DoClientProjectileImpact { + static const GAME_MSG MsgID = GAME_MSG_DO_CLIENT_PROJECTILE_IMPACT; - public: - DoClientProjectileImpact() { - i64OrgID = LWOOBJID_EMPTY; - i64OwnerID = LWOOBJID_EMPTY; - i64TargetID = LWOOBJID_EMPTY; - } + public: + DoClientProjectileImpact() { + i64OrgID = LWOOBJID_EMPTY; + i64OwnerID = LWOOBJID_EMPTY; + i64TargetID = LWOOBJID_EMPTY; + } - DoClientProjectileImpact(std::string _sBitStream, LWOOBJID _i64OrgID = LWOOBJID_EMPTY, LWOOBJID _i64OwnerID = LWOOBJID_EMPTY, LWOOBJID _i64TargetID = LWOOBJID_EMPTY) { - i64OrgID = _i64OrgID; - i64OwnerID = _i64OwnerID; - i64TargetID = _i64TargetID; - sBitStream = _sBitStream; - } + DoClientProjectileImpact(std::string _sBitStream, LWOOBJID _i64OrgID = LWOOBJID_EMPTY, LWOOBJID _i64OwnerID = LWOOBJID_EMPTY, LWOOBJID _i64TargetID = LWOOBJID_EMPTY) { + i64OrgID = _i64OrgID; + i64OwnerID = _i64OwnerID; + i64TargetID = _i64TargetID; + sBitStream = _sBitStream; + } - DoClientProjectileImpact(RakNet::BitStream* stream) { - i64OrgID = LWOOBJID_EMPTY; - i64OwnerID = LWOOBJID_EMPTY; - i64TargetID = LWOOBJID_EMPTY; + DoClientProjectileImpact(RakNet::BitStream* stream) { + i64OrgID = LWOOBJID_EMPTY; + i64OwnerID = LWOOBJID_EMPTY; + i64TargetID = LWOOBJID_EMPTY; - Deserialize(stream); - } + Deserialize(stream); + } - ~DoClientProjectileImpact() { - } - - void Serialize(RakNet::BitStream* stream) { - stream->Write((unsigned short)MsgID); + ~DoClientProjectileImpact() { + } - stream->Write(i64OrgID != LWOOBJID_EMPTY); - if (i64OrgID != LWOOBJID_EMPTY) stream->Write(i64OrgID); + void Serialize(RakNet::BitStream* stream) { + stream->Write((unsigned short)MsgID); - stream->Write(i64OwnerID != LWOOBJID_EMPTY); - if (i64OwnerID != LWOOBJID_EMPTY) stream->Write(i64OwnerID); + stream->Write(i64OrgID != LWOOBJID_EMPTY); + if (i64OrgID != LWOOBJID_EMPTY) stream->Write(i64OrgID); - stream->Write(i64TargetID != LWOOBJID_EMPTY); - if (i64TargetID != LWOOBJID_EMPTY) stream->Write(i64TargetID); + stream->Write(i64OwnerID != LWOOBJID_EMPTY); + if (i64OwnerID != LWOOBJID_EMPTY) stream->Write(i64OwnerID); - uint32_t sBitStreamLength = sBitStream.length(); - stream->Write(sBitStreamLength); - for (unsigned int k = 0; k < sBitStreamLength; k++) { - stream->Write(sBitStream[k]); - } + stream->Write(i64TargetID != LWOOBJID_EMPTY); + if (i64TargetID != LWOOBJID_EMPTY) stream->Write(i64TargetID); - } - - bool Deserialize(RakNet::BitStream* stream) { - bool i64OrgIDIsDefault{}; - stream->Read(i64OrgIDIsDefault); - if (i64OrgIDIsDefault != 0) stream->Read(i64OrgID); + uint32_t sBitStreamLength = sBitStream.length(); + stream->Write(sBitStreamLength); + for (unsigned int k = 0; k < sBitStreamLength; k++) { + stream->Write(sBitStream[k]); + } - bool i64OwnerIDIsDefault{}; - stream->Read(i64OwnerIDIsDefault); - if (i64OwnerIDIsDefault != 0) stream->Read(i64OwnerID); + } - bool i64TargetIDIsDefault{}; - stream->Read(i64TargetIDIsDefault); - if (i64TargetIDIsDefault != 0) stream->Read(i64TargetID); + bool Deserialize(RakNet::BitStream* stream) { + bool i64OrgIDIsDefault{}; + stream->Read(i64OrgIDIsDefault); + if (i64OrgIDIsDefault != 0) stream->Read(i64OrgID); - uint32_t sBitStreamLength{}; - stream->Read(sBitStreamLength); - for (unsigned int k = 0; k < sBitStreamLength; k++) { - unsigned char character; - stream->Read(character); - sBitStream.push_back(character); - } + bool i64OwnerIDIsDefault{}; + stream->Read(i64OwnerIDIsDefault); + if (i64OwnerIDIsDefault != 0) stream->Read(i64OwnerID); + + bool i64TargetIDIsDefault{}; + stream->Read(i64TargetIDIsDefault); + if (i64TargetIDIsDefault != 0) stream->Read(i64TargetID); + + uint32_t sBitStreamLength{}; + stream->Read(sBitStreamLength); + for (unsigned int k = 0; k < sBitStreamLength; k++) { + unsigned char character; + stream->Read(character); + sBitStream.push_back(character); + } - return true; - } + return true; + } + + LWOOBJID i64OrgID; + LWOOBJID i64OwnerID; + LWOOBJID i64TargetID; + std::string sBitStream; + }; - LWOOBJID i64OrgID; - LWOOBJID i64OwnerID; - LWOOBJID i64TargetID; - std::string sBitStream; - }; - /* Same as start skill but with different network options. An echo down to other clients that need to play the skill. */ class EchoStartSkill { static const GAME_MSG MsgID = GAME_MSG_ECHO_START_SKILL; - public: - EchoStartSkill() { - bUsedMouse = false; - fCasterLatency = 0.0f; - iCastType = 0; - lastClickedPosit = NiPoint3::ZERO; - optionalTargetID = LWOOBJID_EMPTY; - originatorRot = NiQuaternion::IDENTITY; - uiSkillHandle = 0; + public: + EchoStartSkill() { + bUsedMouse = false; + fCasterLatency = 0.0f; + iCastType = 0; + lastClickedPosit = NiPoint3::ZERO; + optionalTargetID = LWOOBJID_EMPTY; + originatorRot = NiQuaternion::IDENTITY; + uiSkillHandle = 0; + } + + EchoStartSkill(LWOOBJID _optionalOriginatorID, std::string _sBitStream, TSkillID _skillID, bool _bUsedMouse = false, float _fCasterLatency = 0.0f, int _iCastType = 0, NiPoint3 _lastClickedPosit = NiPoint3::ZERO, LWOOBJID _optionalTargetID = LWOOBJID_EMPTY, NiQuaternion _originatorRot = NiQuaternion::IDENTITY, unsigned int _uiSkillHandle = 0) { + bUsedMouse = _bUsedMouse; + fCasterLatency = _fCasterLatency; + iCastType = _iCastType; + lastClickedPosit = _lastClickedPosit; + optionalOriginatorID = _optionalOriginatorID; + optionalTargetID = _optionalTargetID; + originatorRot = _originatorRot; + sBitStream = _sBitStream; + skillID = _skillID; + uiSkillHandle = _uiSkillHandle; + } + + EchoStartSkill(RakNet::BitStream* stream) { + bUsedMouse = false; + fCasterLatency = 0.0f; + iCastType = 0; + lastClickedPosit = NiPoint3::ZERO; + optionalTargetID = LWOOBJID_EMPTY; + originatorRot = NiQuaternion::IDENTITY; + uiSkillHandle = 0; + + Deserialize(stream); + } + + ~EchoStartSkill() { + } + + void Serialize(RakNet::BitStream* stream) { + stream->Write((unsigned short)MsgID); + + stream->Write(bUsedMouse); + + stream->Write(fCasterLatency != 0.0f); + if (fCasterLatency != 0.0f) stream->Write(fCasterLatency); + + stream->Write(iCastType != 0); + if (iCastType != 0) stream->Write(iCastType); + + stream->Write(lastClickedPosit != NiPoint3::ZERO); + if (lastClickedPosit != NiPoint3::ZERO) stream->Write(lastClickedPosit); + + stream->Write(optionalOriginatorID); + + stream->Write(optionalTargetID != LWOOBJID_EMPTY); + if (optionalTargetID != LWOOBJID_EMPTY) stream->Write(optionalTargetID); + + stream->Write(originatorRot != NiQuaternion::IDENTITY); + if (originatorRot != NiQuaternion::IDENTITY) stream->Write(originatorRot); + + uint32_t sBitStreamLength = sBitStream.length(); + stream->Write(sBitStreamLength); + for (unsigned int k = 0; k < sBitStreamLength; k++) { + stream->Write(sBitStream[k]); } - EchoStartSkill(LWOOBJID _optionalOriginatorID, std::string _sBitStream, TSkillID _skillID, bool _bUsedMouse = false, float _fCasterLatency = 0.0f, int _iCastType = 0, NiPoint3 _lastClickedPosit = NiPoint3::ZERO, LWOOBJID _optionalTargetID = LWOOBJID_EMPTY, NiQuaternion _originatorRot = NiQuaternion::IDENTITY, unsigned int _uiSkillHandle = 0) { - bUsedMouse = _bUsedMouse; - fCasterLatency = _fCasterLatency; - iCastType = _iCastType; - lastClickedPosit = _lastClickedPosit; - optionalOriginatorID = _optionalOriginatorID; - optionalTargetID = _optionalTargetID; - originatorRot = _originatorRot; - sBitStream = _sBitStream; - skillID = _skillID; - uiSkillHandle = _uiSkillHandle; + stream->Write(skillID); + + stream->Write(uiSkillHandle != 0); + if (uiSkillHandle != 0) stream->Write(uiSkillHandle); + } + + bool Deserialize(RakNet::BitStream* stream) { + stream->Read(bUsedMouse); + + bool fCasterLatencyIsDefault{}; + stream->Read(fCasterLatencyIsDefault); + if (fCasterLatencyIsDefault != 0) stream->Read(fCasterLatency); + + bool iCastTypeIsDefault{}; + stream->Read(iCastTypeIsDefault); + if (iCastTypeIsDefault != 0) stream->Read(iCastType); + + bool lastClickedPositIsDefault{}; + stream->Read(lastClickedPositIsDefault); + if (lastClickedPositIsDefault != 0) stream->Read(lastClickedPosit); + + stream->Read(optionalOriginatorID); + + bool optionalTargetIDIsDefault{}; + stream->Read(optionalTargetIDIsDefault); + if (optionalTargetIDIsDefault != 0) stream->Read(optionalTargetID); + + bool originatorRotIsDefault{}; + stream->Read(originatorRotIsDefault); + if (originatorRotIsDefault != 0) stream->Read(originatorRot); + + uint32_t sBitStreamLength{}; + stream->Read(sBitStreamLength); + for (unsigned int k = 0; k < sBitStreamLength; k++) { + unsigned char character; + stream->Read(character); + sBitStream.push_back(character); } - EchoStartSkill(RakNet::BitStream* stream) { - bUsedMouse = false; - fCasterLatency = 0.0f; - iCastType = 0; - lastClickedPosit = NiPoint3::ZERO; - optionalTargetID = LWOOBJID_EMPTY; - originatorRot = NiQuaternion::IDENTITY; - uiSkillHandle = 0; + stream->Read(skillID); - Deserialize(stream); - } + bool uiSkillHandleIsDefault{}; + stream->Read(uiSkillHandleIsDefault); + if (uiSkillHandleIsDefault != 0) stream->Read(uiSkillHandle); - ~EchoStartSkill() { - } - - void Serialize(RakNet::BitStream* stream) { - stream->Write((unsigned short)MsgID); + return true; + } - stream->Write(bUsedMouse); - - stream->Write(fCasterLatency != 0.0f); - if (fCasterLatency != 0.0f) stream->Write(fCasterLatency); - - stream->Write(iCastType != 0); - if (iCastType != 0) stream->Write(iCastType); - - stream->Write(lastClickedPosit != NiPoint3::ZERO); - if (lastClickedPosit != NiPoint3::ZERO) stream->Write(lastClickedPosit); - - stream->Write(optionalOriginatorID); - - stream->Write(optionalTargetID != LWOOBJID_EMPTY); - if (optionalTargetID != LWOOBJID_EMPTY) stream->Write(optionalTargetID); - - stream->Write(originatorRot != NiQuaternion::IDENTITY); - if (originatorRot != NiQuaternion::IDENTITY) stream->Write(originatorRot); - - uint32_t sBitStreamLength = sBitStream.length(); - stream->Write(sBitStreamLength); - for (unsigned int k = 0; k < sBitStreamLength; k++) { - stream->Write(sBitStream[k]); - } - - stream->Write(skillID); - - stream->Write(uiSkillHandle != 0); - if (uiSkillHandle != 0) stream->Write(uiSkillHandle); - } - - bool Deserialize(RakNet::BitStream* stream) { - stream->Read(bUsedMouse); - - bool fCasterLatencyIsDefault{}; - stream->Read(fCasterLatencyIsDefault); - if (fCasterLatencyIsDefault != 0) stream->Read(fCasterLatency); - - bool iCastTypeIsDefault{}; - stream->Read(iCastTypeIsDefault); - if (iCastTypeIsDefault != 0) stream->Read(iCastType); - - bool lastClickedPositIsDefault{}; - stream->Read(lastClickedPositIsDefault); - if (lastClickedPositIsDefault != 0) stream->Read(lastClickedPosit); - - stream->Read(optionalOriginatorID); - - bool optionalTargetIDIsDefault{}; - stream->Read(optionalTargetIDIsDefault); - if (optionalTargetIDIsDefault != 0) stream->Read(optionalTargetID); - - bool originatorRotIsDefault{}; - stream->Read(originatorRotIsDefault); - if (originatorRotIsDefault != 0) stream->Read(originatorRot); - - uint32_t sBitStreamLength{}; - stream->Read(sBitStreamLength); - for (unsigned int k = 0; k < sBitStreamLength; k++) { - unsigned char character; - stream->Read(character); - sBitStream.push_back(character); - } - - stream->Read(skillID); - - bool uiSkillHandleIsDefault{}; - stream->Read(uiSkillHandleIsDefault); - if (uiSkillHandleIsDefault != 0) stream->Read(uiSkillHandle); - - return true; - } - - bool bUsedMouse; - float fCasterLatency; - int iCastType; - NiPoint3 lastClickedPosit; - LWOOBJID optionalOriginatorID; - LWOOBJID optionalTargetID; - NiQuaternion originatorRot; - std::string sBitStream; - TSkillID skillID; - unsigned int uiSkillHandle; + bool bUsedMouse; + float fCasterLatency; + int iCastType; + NiPoint3 lastClickedPosit; + LWOOBJID optionalOriginatorID; + LWOOBJID optionalTargetID; + NiQuaternion originatorRot; + std::string sBitStream; + TSkillID skillID; + unsigned int uiSkillHandle; }; /* Same as sync skill but with different network options. An echo down to other clients that need to play the skill. */ class StartSkill { static const GAME_MSG MsgID = GAME_MSG_START_SKILL; - public: - StartSkill() { - bUsedMouse = false; - consumableItemID = LWOOBJID_EMPTY; - fCasterLatency = 0.0f; - iCastType = 0; - lastClickedPosit = NiPoint3::ZERO; - optionalTargetID = LWOOBJID_EMPTY; - originatorRot = NiQuaternion::IDENTITY; - uiSkillHandle = 0; + public: + StartSkill() { + bUsedMouse = false; + consumableItemID = LWOOBJID_EMPTY; + fCasterLatency = 0.0f; + iCastType = 0; + lastClickedPosit = NiPoint3::ZERO; + optionalTargetID = LWOOBJID_EMPTY; + originatorRot = NiQuaternion::IDENTITY; + uiSkillHandle = 0; + } + + StartSkill(LWOOBJID _optionalOriginatorID, std::string _sBitStream, TSkillID _skillID, bool _bUsedMouse = false, LWOOBJID _consumableItemID = LWOOBJID_EMPTY, float _fCasterLatency = 0.0f, int _iCastType = 0, NiPoint3 _lastClickedPosit = NiPoint3::ZERO, LWOOBJID _optionalTargetID = LWOOBJID_EMPTY, NiQuaternion _originatorRot = NiQuaternion::IDENTITY, unsigned int _uiSkillHandle = 0) { + bUsedMouse = _bUsedMouse; + consumableItemID = _consumableItemID; + fCasterLatency = _fCasterLatency; + iCastType = _iCastType; + lastClickedPosit = _lastClickedPosit; + optionalOriginatorID = _optionalOriginatorID; + optionalTargetID = _optionalTargetID; + originatorRot = _originatorRot; + sBitStream = _sBitStream; + skillID = _skillID; + uiSkillHandle = _uiSkillHandle; + } + + StartSkill(RakNet::BitStream* stream) { + bUsedMouse = false; + consumableItemID = LWOOBJID_EMPTY; + fCasterLatency = 0.0f; + iCastType = 0; + lastClickedPosit = NiPoint3::ZERO; + optionalTargetID = LWOOBJID_EMPTY; + originatorRot = NiQuaternion::IDENTITY; + uiSkillHandle = 0; + + Deserialize(stream); + } + + ~StartSkill() { + } + + void Serialize(RakNet::BitStream* stream) { + stream->Write((unsigned short)MsgID); + + stream->Write(bUsedMouse); + + stream->Write(consumableItemID != LWOOBJID_EMPTY); + if (consumableItemID != LWOOBJID_EMPTY) stream->Write(consumableItemID); + + stream->Write(fCasterLatency != 0.0f); + if (fCasterLatency != 0.0f) stream->Write(fCasterLatency); + + stream->Write(iCastType != 0); + if (iCastType != 0) stream->Write(iCastType); + + stream->Write(lastClickedPosit != NiPoint3::ZERO); + if (lastClickedPosit != NiPoint3::ZERO) stream->Write(lastClickedPosit); + + stream->Write(optionalOriginatorID); + + stream->Write(optionalTargetID != LWOOBJID_EMPTY); + if (optionalTargetID != LWOOBJID_EMPTY) stream->Write(optionalTargetID); + + stream->Write(originatorRot != NiQuaternion::IDENTITY); + if (originatorRot != NiQuaternion::IDENTITY) stream->Write(originatorRot); + + uint32_t sBitStreamLength = sBitStream.length(); + stream->Write(sBitStreamLength); + for (unsigned int k = 0; k < sBitStreamLength; k++) { + stream->Write(sBitStream[k]); } - StartSkill(LWOOBJID _optionalOriginatorID, std::string _sBitStream, TSkillID _skillID, bool _bUsedMouse = false, LWOOBJID _consumableItemID = LWOOBJID_EMPTY, float _fCasterLatency = 0.0f, int _iCastType = 0, NiPoint3 _lastClickedPosit = NiPoint3::ZERO, LWOOBJID _optionalTargetID = LWOOBJID_EMPTY, NiQuaternion _originatorRot = NiQuaternion::IDENTITY, unsigned int _uiSkillHandle = 0) { - bUsedMouse = _bUsedMouse; - consumableItemID = _consumableItemID; - fCasterLatency = _fCasterLatency; - iCastType = _iCastType; - lastClickedPosit = _lastClickedPosit; - optionalOriginatorID = _optionalOriginatorID; - optionalTargetID = _optionalTargetID; - originatorRot = _originatorRot; - sBitStream = _sBitStream; - skillID = _skillID; - uiSkillHandle = _uiSkillHandle; + stream->Write(skillID); + + stream->Write(uiSkillHandle != 0); + if (uiSkillHandle != 0) stream->Write(uiSkillHandle); + } + + bool Deserialize(RakNet::BitStream* stream) { + stream->Read(bUsedMouse); + + bool consumableItemIDIsDefault{}; + stream->Read(consumableItemIDIsDefault); + if (consumableItemIDIsDefault != 0) stream->Read(consumableItemID); + + bool fCasterLatencyIsDefault{}; + stream->Read(fCasterLatencyIsDefault); + if (fCasterLatencyIsDefault != 0) stream->Read(fCasterLatency); + + bool iCastTypeIsDefault{}; + stream->Read(iCastTypeIsDefault); + if (iCastTypeIsDefault != 0) stream->Read(iCastType); + + bool lastClickedPositIsDefault{}; + stream->Read(lastClickedPositIsDefault); + if (lastClickedPositIsDefault != 0) stream->Read(lastClickedPosit); + + stream->Read(optionalOriginatorID); + + bool optionalTargetIDIsDefault{}; + stream->Read(optionalTargetIDIsDefault); + if (optionalTargetIDIsDefault != 0) stream->Read(optionalTargetID); + + bool originatorRotIsDefault{}; + stream->Read(originatorRotIsDefault); + if (originatorRotIsDefault != 0) stream->Read(originatorRot); + + uint32_t sBitStreamLength{}; + stream->Read(sBitStreamLength); + for (unsigned int k = 0; k < sBitStreamLength; k++) { + unsigned char character; + stream->Read(character); + sBitStream.push_back(character); } - StartSkill(RakNet::BitStream* stream) { - bUsedMouse = false; - consumableItemID = LWOOBJID_EMPTY; - fCasterLatency = 0.0f; - iCastType = 0; - lastClickedPosit = NiPoint3::ZERO; - optionalTargetID = LWOOBJID_EMPTY; - originatorRot = NiQuaternion::IDENTITY; - uiSkillHandle = 0; + stream->Read(skillID); - Deserialize(stream); - } + bool uiSkillHandleIsDefault{}; + stream->Read(uiSkillHandleIsDefault); + if (uiSkillHandleIsDefault != 0) stream->Read(uiSkillHandle); - ~StartSkill() { - } - - void Serialize(RakNet::BitStream* stream) { - stream->Write((unsigned short)MsgID); + return true; + } - stream->Write(bUsedMouse); - - stream->Write(consumableItemID != LWOOBJID_EMPTY); - if (consumableItemID != LWOOBJID_EMPTY) stream->Write(consumableItemID); - - stream->Write(fCasterLatency != 0.0f); - if (fCasterLatency != 0.0f) stream->Write(fCasterLatency); - - stream->Write(iCastType != 0); - if (iCastType != 0) stream->Write(iCastType); - - stream->Write(lastClickedPosit != NiPoint3::ZERO); - if (lastClickedPosit != NiPoint3::ZERO) stream->Write(lastClickedPosit); - - stream->Write(optionalOriginatorID); - - stream->Write(optionalTargetID != LWOOBJID_EMPTY); - if (optionalTargetID != LWOOBJID_EMPTY) stream->Write(optionalTargetID); - - stream->Write(originatorRot != NiQuaternion::IDENTITY); - if (originatorRot != NiQuaternion::IDENTITY) stream->Write(originatorRot); - - uint32_t sBitStreamLength = sBitStream.length(); - stream->Write(sBitStreamLength); - for (unsigned int k = 0; k < sBitStreamLength; k++) { - stream->Write(sBitStream[k]); - } - - stream->Write(skillID); - - stream->Write(uiSkillHandle != 0); - if (uiSkillHandle != 0) stream->Write(uiSkillHandle); - } - - bool Deserialize(RakNet::BitStream* stream) { - stream->Read(bUsedMouse); - - bool consumableItemIDIsDefault{}; - stream->Read(consumableItemIDIsDefault); - if (consumableItemIDIsDefault != 0) stream->Read(consumableItemID); - - bool fCasterLatencyIsDefault{}; - stream->Read(fCasterLatencyIsDefault); - if (fCasterLatencyIsDefault != 0) stream->Read(fCasterLatency); - - bool iCastTypeIsDefault{}; - stream->Read(iCastTypeIsDefault); - if (iCastTypeIsDefault != 0) stream->Read(iCastType); - - bool lastClickedPositIsDefault{}; - stream->Read(lastClickedPositIsDefault); - if (lastClickedPositIsDefault != 0) stream->Read(lastClickedPosit); - - stream->Read(optionalOriginatorID); - - bool optionalTargetIDIsDefault{}; - stream->Read(optionalTargetIDIsDefault); - if (optionalTargetIDIsDefault != 0) stream->Read(optionalTargetID); - - bool originatorRotIsDefault{}; - stream->Read(originatorRotIsDefault); - if (originatorRotIsDefault != 0) stream->Read(originatorRot); - - uint32_t sBitStreamLength{}; - stream->Read(sBitStreamLength); - for (unsigned int k = 0; k < sBitStreamLength; k++) { - unsigned char character; - stream->Read(character); - sBitStream.push_back(character); - } - - stream->Read(skillID); - - bool uiSkillHandleIsDefault{}; - stream->Read(uiSkillHandleIsDefault); - if (uiSkillHandleIsDefault != 0) stream->Read(uiSkillHandle); - - return true; - } - - bool bUsedMouse = false; - LWOOBJID consumableItemID{}; - float fCasterLatency{}; - int iCastType{}; - NiPoint3 lastClickedPosit{}; - LWOOBJID optionalOriginatorID{}; - LWOOBJID optionalTargetID{}; - NiQuaternion originatorRot{}; - std::string sBitStream = ""; - TSkillID skillID = 0; - unsigned int uiSkillHandle = 0; + bool bUsedMouse = false; + LWOOBJID consumableItemID{}; + float fCasterLatency{}; + int iCastType{}; + NiPoint3 lastClickedPosit{}; + LWOOBJID optionalOriginatorID{}; + LWOOBJID optionalTargetID{}; + NiQuaternion originatorRot{}; + std::string sBitStream = ""; + TSkillID skillID = 0; + unsigned int uiSkillHandle = 0; }; }; diff --git a/dGame/dGameMessages/PropertyDataMessage.cpp b/dGame/dGameMessages/PropertyDataMessage.cpp index 85eb54cb..853151c9 100644 --- a/dGame/dGameMessages/PropertyDataMessage.cpp +++ b/dGame/dGameMessages/PropertyDataMessage.cpp @@ -6,8 +6,7 @@ #include "dLogger.h" #include "CDClientManager.h" -void GameMessages::PropertyDataMessage::Serialize(RakNet::BitStream& stream) const -{ +void GameMessages::PropertyDataMessage::Serialize(RakNet::BitStream& stream) const { stream.Write(0); // - property id stream.Write(TemplateID); // - template id @@ -39,9 +38,9 @@ void GameMessages::PropertyDataMessage::Serialize(RakNet::BitStream& stream) con stream.Write(0); // - zone code stream.Write(0); // - minimum price stream.Write(1); // - rent duration - + stream.Write(LastUpdatedTime); // - timestamp - + stream.Write(1); stream.Write(reputation); // Reputation @@ -52,7 +51,7 @@ void GameMessages::PropertyDataMessage::Serialize(RakNet::BitStream& stream) con for (uint32_t i = 0; i < spawn.size(); ++i) { stream.Write(uint16_t(spawn[i])); } - + stream.Write(0); // String length stream.Write(0); // String length @@ -89,13 +88,12 @@ void GameMessages::PropertyDataMessage::Serialize(RakNet::BitStream& stream) con stream.Write(MaxBuildHeight); stream.Write(ClaimedTime); // - timestamp - + stream.Write(PrivacyOption); stream.Write(uint32_t(Paths.size())); - for (const auto& path : Paths) - { + for (const auto& path : Paths) { stream.Write(path.x); stream.Write(path.y); stream.Write(path.z); @@ -103,11 +101,11 @@ void GameMessages::PropertyDataMessage::Serialize(RakNet::BitStream& stream) con } GameMessages::PropertyDataMessage::PropertyDataMessage(uint32_t mapID) { - const auto propertyTemplate = CDClientManager::Instance()-> - GetTable("PropertyTemplate")->GetByMapID(mapID); + const auto propertyTemplate = CDClientManager::Instance()-> + GetTable("PropertyTemplate")->GetByMapID(mapID); - TemplateID = propertyTemplate.id; - ZoneId = propertyTemplate.mapID; - VendorMapId = propertyTemplate.vendorMapID; - SpawnName = propertyTemplate.spawnName; + TemplateID = propertyTemplate.id; + ZoneId = propertyTemplate.mapID; + VendorMapId = propertyTemplate.vendorMapID; + SpawnName = propertyTemplate.spawnName; } diff --git a/dGame/dGameMessages/PropertyDataMessage.h b/dGame/dGameMessages/PropertyDataMessage.h index 5b5d7d0f..819c5dbb 100644 --- a/dGame/dGameMessages/PropertyDataMessage.h +++ b/dGame/dGameMessages/PropertyDataMessage.h @@ -8,12 +8,11 @@ #include "NiPoint3.h" #include "dCommonVars.h" -namespace GameMessages -{ +namespace GameMessages { class PropertyDataMessage final { public: - explicit PropertyDataMessage(uint32_t mapID); + explicit PropertyDataMessage(uint32_t mapID); void Serialize(RakNet::BitStream& stream) const; @@ -47,4 +46,4 @@ namespace GameMessages REJECTION_STATUS_REJECTED = 2 }; }; -} \ No newline at end of file +} diff --git a/dGame/dGameMessages/PropertySelectQueryProperty.cpp b/dGame/dGameMessages/PropertySelectQueryProperty.cpp index 38e7cea2..18d23d2b 100644 --- a/dGame/dGameMessages/PropertySelectQueryProperty.cpp +++ b/dGame/dGameMessages/PropertySelectQueryProperty.cpp @@ -1,8 +1,7 @@ #include "PropertySelectQueryProperty.h" -void PropertySelectQueryProperty::Serialize(RakNet::BitStream& stream) const -{ - stream.Write(CloneId); +void PropertySelectQueryProperty::Serialize(RakNet::BitStream& stream) const { + stream.Write(CloneId); const auto& owner = GeneralUtils::ASCIIToUTF16(OwnerName); stream.Write(uint32_t(owner.size())); @@ -34,7 +33,6 @@ void PropertySelectQueryProperty::Serialize(RakNet::BitStream& stream) const stream.Write(PerformanceCost); } -void PropertySelectQueryProperty::Deserialize(RakNet::BitStream& stream) const -{ - // Do we need this? +void PropertySelectQueryProperty::Deserialize(RakNet::BitStream& stream) const { + // Do we need this? } diff --git a/dGame/dGameMessages/PropertySelectQueryProperty.h b/dGame/dGameMessages/PropertySelectQueryProperty.h index e633f41b..7826900d 100644 --- a/dGame/dGameMessages/PropertySelectQueryProperty.h +++ b/dGame/dGameMessages/PropertySelectQueryProperty.h @@ -12,20 +12,20 @@ public: void Deserialize(RakNet::BitStream& stream) const; - LWOCLONEID CloneId = LWOCLONEID_INVALID; // The cloneID of the property - std::string OwnerName = ""; // The property owners name - std::string Name = ""; // The property name - std::string Description = ""; // The property description - float Reputation = 0; // The reputation of the property - bool IsBestFriend = false; // Whether or not the property belongs to a best friend - bool IsFriend = false; // Whether or not the property belongs to a friend - bool IsModeratorApproved = false; // Whether or not a moderator has approved this property - bool IsAlt = false; // Whether or not the property is owned by an alt of the account owner - bool IsOwned = false; // Whether or not the property is owned - uint32_t AccessType = 0; // The privacy option of the property - uint32_t DateLastPublished = 0; // The last day the property was published - float PerformanceCost = 0; // The performance cost of the property - uint32_t PerformanceIndex = 0; // The performance index of the property? Always 0? + LWOCLONEID CloneId = LWOCLONEID_INVALID; // The cloneID of the property + std::string OwnerName = ""; // The property owners name + std::string Name = ""; // The property name + std::string Description = ""; // The property description + float Reputation = 0; // The reputation of the property + bool IsBestFriend = false; // Whether or not the property belongs to a best friend + bool IsFriend = false; // Whether or not the property belongs to a friend + bool IsModeratorApproved = false; // Whether or not a moderator has approved this property + bool IsAlt = false; // Whether or not the property is owned by an alt of the account owner + bool IsOwned = false; // Whether or not the property is owned + uint32_t AccessType = 0; // The privacy option of the property + uint32_t DateLastPublished = 0; // The last day the property was published + float PerformanceCost = 0; // The performance cost of the property + uint32_t PerformanceIndex = 0; // The performance index of the property? Always 0? }; #endif diff --git a/dGame/dInventory/DatabasePet.h b/dGame/dInventory/DatabasePet.h index 068c6195..2dd8649a 100644 --- a/dGame/dInventory/DatabasePet.h +++ b/dGame/dInventory/DatabasePet.h @@ -7,20 +7,20 @@ */ struct DatabasePet { - /** - * The lot of this pet - */ - LOT lot = LOT_NULL; + /** + * The lot of this pet + */ + LOT lot = LOT_NULL; - /** - * The name of the pet - */ - std::string name; + /** + * The name of the pet + */ + std::string name; - /** - * The current moderation state, see PetComponent for more info - */ - int32_t moderationState = 0; + /** + * The current moderation state, see PetComponent for more info + */ + int32_t moderationState = 0; }; const DatabasePet DATABASE_PET_INVALID; diff --git a/dGame/dInventory/EquippedItem.h b/dGame/dInventory/EquippedItem.h index cf5ba253..78da9e8d 100644 --- a/dGame/dInventory/EquippedItem.h +++ b/dGame/dInventory/EquippedItem.h @@ -8,24 +8,24 @@ */ struct EquippedItem { - /** - * The object ID of the equipped item - */ + /** + * The object ID of the equipped item + */ LWOOBJID id = LWOOBJID_EMPTY; - /** - * The LOT of this equipped item - */ + /** + * The LOT of this equipped item + */ LOT lot = LOT_NULL; - /** - * The number of items that are stored in this slot - */ + /** + * The number of items that are stored in this slot + */ uint32_t count = 0; - /** - * The slot this item is stored in - */ + /** + * The slot this item is stored in + */ uint32_t slot = 0; /** diff --git a/dGame/dInventory/Inventory.cpp b/dGame/dInventory/Inventory.cpp index 012bcacf..151e3164 100644 --- a/dGame/dInventory/Inventory.cpp +++ b/dGame/dInventory/Inventory.cpp @@ -14,40 +14,33 @@ std::vector Inventory::m_GameMasterRestrictedItems = { 14442 // The jamesster jetpack }; -Inventory::Inventory(const eInventoryType type, const uint32_t size, const std::vector& items, InventoryComponent* component) -{ +Inventory::Inventory(const eInventoryType type, const uint32_t size, const std::vector& items, InventoryComponent* component) { this->type = type; this->size = size; this->free = size; this->component = component; - for (auto* item : items) - { + for (auto* item : items) { AddManagedItem(item); } } -eInventoryType Inventory::GetType() const -{ +eInventoryType Inventory::GetType() const { return type; } -uint32_t Inventory::GetSize() const -{ +uint32_t Inventory::GetSize() const { return size; } -std::map& Inventory::GetItems() -{ +std::map& Inventory::GetItems() { return items; } -std::map Inventory::GetSlots() const -{ +std::map Inventory::GetSlots() const { std::map slots; - for (const auto& pair : items) - { + for (const auto& pair : items) { auto* item = pair.second; slots.insert_or_assign(item->GetSlot(), item); @@ -56,21 +49,17 @@ std::map Inventory::GetSlots() const return slots; } -InventoryComponent* Inventory::GetComponent() const -{ +InventoryComponent* Inventory::GetComponent() const { return component; } -uint32_t Inventory::GetLotCount(const LOT lot) const -{ +uint32_t Inventory::GetLotCount(const LOT lot) const { uint32_t count = 0; - for (const auto& pair : items) - { + for (const auto& pair : items) { const auto* item = pair.second; - if (item->GetLot() == lot) - { + if (item->GetLot() == lot) { count += item->GetCount(); } } @@ -78,8 +67,7 @@ uint32_t Inventory::GetLotCount(const LOT lot) const return count; } -void Inventory::SetSize(const uint32_t value) -{ +void Inventory::SetSize(const uint32_t value) { free += static_cast(value) - static_cast(size); size = value; @@ -87,45 +75,34 @@ void Inventory::SetSize(const uint32_t value) GameMessages::SendSetInventorySize(component->GetParent(), type, static_cast(size)); } -int32_t Inventory::FindEmptySlot() -{ +int32_t Inventory::FindEmptySlot() { if (free <= 6) // Up from 1 { - if (type != ITEMS && type != VAULT_ITEMS && type != eInventoryType::VAULT_MODELS) - { + if (type != ITEMS && type != VAULT_ITEMS && type != eInventoryType::VAULT_MODELS) { uint32_t newSize = size; - if (type == MODELS) - { + if (type == MODELS) { newSize = 240; - } - else if (type == eInventoryType::VENDOR_BUYBACK) - { + } else if (type == eInventoryType::VENDOR_BUYBACK) { newSize += 9u; - } - else - { + } else { newSize += 10u; } - if (newSize > GetSize()) - { + if (newSize > GetSize()) { SetSize(newSize); } } } - if (free == 0) - { + if (free == 0) { return -1; } const auto slots = GetSlots(); - for (auto i = 0u; i < size; ++i) - { - if (slots.find(i) == slots.end()) - { + for (auto i = 0u; i < size; ++i) { + if (slots.find(i) == slots.end()) { return i; } } @@ -133,13 +110,11 @@ int32_t Inventory::FindEmptySlot() return -1; } -int32_t Inventory::GetEmptySlots() -{ +int32_t Inventory::GetEmptySlots() { return free; } -bool Inventory::IsSlotEmpty(int32_t slot) -{ +bool Inventory::IsSlotEmpty(int32_t slot) { const auto slots = GetSlots(); const auto& index = slots.find(slot); @@ -147,50 +122,41 @@ bool Inventory::IsSlotEmpty(int32_t slot) return index == slots.end(); } -Item* Inventory::FindItemById(const LWOOBJID id) const -{ +Item* Inventory::FindItemById(const LWOOBJID id) const { const auto& index = items.find(id); - if (index == items.end()) - { + if (index == items.end()) { return nullptr; } return index->second; } -Item* Inventory::FindItemByLot(const LOT lot, const bool ignoreEquipped, const bool ignoreBound) const -{ +Item* Inventory::FindItemByLot(const LOT lot, const bool ignoreEquipped, const bool ignoreBound) const { Item* smallest = nullptr; - for (const auto& pair : items) - { + for (const auto& pair : items) { auto* item = pair.second; - if (item->GetLot() != lot) - { + if (item->GetLot() != lot) { continue; } - if (ignoreEquipped && item->IsEquipped()) - { + if (ignoreEquipped && item->IsEquipped()) { continue; } - if (ignoreBound && item->GetBound()) - { + if (ignoreBound && item->GetBound()) { continue; } - if (smallest == nullptr) - { + if (smallest == nullptr) { smallest = item; continue; } - if (smallest->GetCount() > item->GetCount()) - { + if (smallest->GetCount() > item->GetCount()) { smallest = item; } } @@ -198,26 +164,21 @@ Item* Inventory::FindItemByLot(const LOT lot, const bool ignoreEquipped, const b return smallest; } -Item* Inventory::FindItemBySlot(const uint32_t slot) const -{ +Item* Inventory::FindItemBySlot(const uint32_t slot) const { const auto slots = GetSlots(); const auto index = slots.find(slot); - if (index == slots.end()) - { + if (index == slots.end()) { return nullptr; } return index->second; } -Item* Inventory::FindItemBySubKey(LWOOBJID id) const -{ - for (const auto& item : items) - { - if (item.second->GetSubKey() == id) - { +Item* Inventory::FindItemBySubKey(LWOOBJID id) const { + for (const auto& item : items) { + if (item.second->GetSubKey() == id) { return item.second; } } @@ -225,12 +186,10 @@ Item* Inventory::FindItemBySubKey(LWOOBJID id) const return nullptr; } -void Inventory::AddManagedItem(Item* item) -{ +void Inventory::AddManagedItem(Item* item) { const auto id = item->GetId(); - if (items.find(id) != items.end()) - { + if (items.find(id) != items.end()) { Game::logger->Log("Inventory", "Attempting to add an item with an already present id (%llu)!", id); return; @@ -240,8 +199,7 @@ void Inventory::AddManagedItem(Item* item) const auto slot = item->GetSlot(); - if (slots.find(slot) != slots.end()) - { + if (slots.find(slot) != slots.end()) { Game::logger->Log("Inventory", "Attempting to add an item with an already present slot (%i)!", slot); return; @@ -252,12 +210,10 @@ void Inventory::AddManagedItem(Item* item) free--; } -void Inventory::RemoveManagedItem(Item* item) -{ +void Inventory::RemoveManagedItem(Item* item) { const auto id = item->GetId(); - if (items.find(id) == items.end()) - { + if (items.find(id) == items.end()) { Game::logger->Log("Inventory", "Attempting to remove an item with an invalid id (%llu), lot (%i)!", id, item->GetLot()); return; @@ -268,8 +224,7 @@ void Inventory::RemoveManagedItem(Item* item) free++; } -eInventoryType Inventory::FindInventoryTypeForLot(const LOT lot) -{ +eInventoryType Inventory::FindInventoryTypeForLot(const LOT lot) { auto itemComponent = FindItemComponent(lot); const auto itemType = static_cast(itemComponent.itemType); @@ -315,16 +270,14 @@ eInventoryType Inventory::FindInventoryTypeForLot(const LOT lot) } } -const CDItemComponent& Inventory::FindItemComponent(const LOT lot) -{ +const CDItemComponent& Inventory::FindItemComponent(const LOT lot) { auto* registry = CDClientManager::Instance()->GetTable("ComponentsRegistry"); auto* itemComponents = CDClientManager::Instance()->GetTable("ItemComponent"); const auto componentId = registry->GetByIDAndType(lot, COMPONENT_TYPE_ITEM); - if (componentId == 0) - { + if (componentId == 0) { Game::logger->Log("Inventory", "Failed to find item component for (%i)!", lot); return CDItemComponentTable::Default; @@ -335,8 +288,7 @@ const CDItemComponent& Inventory::FindItemComponent(const LOT lot) return itemComponent; } -bool Inventory::IsValidItem(const LOT lot) -{ +bool Inventory::IsValidItem(const LOT lot) { auto* registry = CDClientManager::Instance()->GetTable("ComponentsRegistry"); const auto componentId = registry->GetByIDAndType(lot, COMPONENT_TYPE_ITEM); @@ -344,15 +296,12 @@ bool Inventory::IsValidItem(const LOT lot) return componentId != 0; } -const std::vector& Inventory::GetAllGMItems() -{ +const std::vector& Inventory::GetAllGMItems() { return m_GameMasterRestrictedItems; } -Inventory::~Inventory() -{ - for (auto item : items) - { +Inventory::~Inventory() { + for (auto item : items) { delete item.second; } diff --git a/dGame/dInventory/Inventory.h b/dGame/dInventory/Inventory.h index b65a2040..1f7bb425 100644 --- a/dGame/dInventory/Inventory.h +++ b/dGame/dInventory/Inventory.h @@ -21,168 +21,168 @@ class Inventory final public: explicit Inventory(eInventoryType type, uint32_t size, const std::vector& items, InventoryComponent* component); - /** - * Returns the type of this inventory - * @return the type of this inventory - */ + /** + * Returns the type of this inventory + * @return the type of this inventory + */ eInventoryType GetType() const; - /** - * Returns the maximum amount of items this inventory can contain - * @return the maximum amount of items this inventory can contain - */ + /** + * Returns the maximum amount of items this inventory can contain + * @return the maximum amount of items this inventory can contain + */ uint32_t GetSize() const; - /** - * Returns all the items that are currently in this inventory, mapped by object ID - * @return all the items that are currently in this inventory, mapped by object ID - */ + /** + * Returns all the items that are currently in this inventory, mapped by object ID + * @return all the items that are currently in this inventory, mapped by object ID + */ std::map& GetItems(); - /** - * Returns all the items that are currently in this inventory, mapped by slot - * @return all the items that are currently in this inventory, mapped by slot - */ + /** + * Returns all the items that are currently in this inventory, mapped by slot + * @return all the items that are currently in this inventory, mapped by slot + */ std::map GetSlots() const; - /** - * Returns the inventory component that this inventory is part of - * @return the inventory component that this inventory is part of - */ + /** + * Returns the inventory component that this inventory is part of + * @return the inventory component that this inventory is part of + */ InventoryComponent* GetComponent() const; - /** - * Returns the amount of items this inventory contains of the specified LOT - * @param lot the lot to find items for - * @return the amount of items this inventory contains of the specified LOT - */ + /** + * Returns the amount of items this inventory contains of the specified LOT + * @param lot the lot to find items for + * @return the amount of items this inventory contains of the specified LOT + */ uint32_t GetLotCount(LOT lot) const; - /** - * Updates the max size of this inventory - * @param value the size to set - */ + /** + * Updates the max size of this inventory + * @param value the size to set + */ void SetSize(uint32_t value); - /** - * Returns the first slot in this inventory that does not contain an item - * @return the first slot in this inventory that does not contain an item - */ + /** + * Returns the first slot in this inventory that does not contain an item + * @return the first slot in this inventory that does not contain an item + */ int32_t FindEmptySlot(); - /** - * Returns the number of empty slots this inventory has left - * @return the number of empty slots this inventory has left - */ + /** + * Returns the number of empty slots this inventory has left + * @return the number of empty slots this inventory has left + */ int32_t GetEmptySlots(); - /** - * Returns if the slot for the specified index is empty - * @param slot the index to check occupation for - * @return if the slot for the specified index is empty - */ + /** + * Returns if the slot for the specified index is empty + * @param slot the index to check occupation for + * @return if the slot for the specified index is empty + */ bool IsSlotEmpty(int32_t slot); - /** - * Finds an item in this inventory by the provided id - * @param id the object ID of the item to find - * @return item in this inventory by the provided id - */ + /** + * Finds an item in this inventory by the provided id + * @param id the object ID of the item to find + * @return item in this inventory by the provided id + */ Item* FindItemById(LWOOBJID id) const; - /** - * Finds an item in the inventory for the provided LOT - * @param lot the lot to find items for - * @param ignoreEquipped ignores equipped items - * @param ignoreBound ignores bound items - * @return item in the inventory for the provided LOT - */ + /** + * Finds an item in the inventory for the provided LOT + * @param lot the lot to find items for + * @param ignoreEquipped ignores equipped items + * @param ignoreBound ignores bound items + * @return item in the inventory for the provided LOT + */ Item* FindItemByLot(LOT lot, bool ignoreEquipped = false, bool ignoreBound = false) const; - /** - * Finds an item in the inventory stored on the provied slot - * @param slot to slot to find an item for - * @return item in the inventory stored on the provied slot - */ + /** + * Finds an item in the inventory stored on the provied slot + * @param slot to slot to find an item for + * @return item in the inventory stored on the provied slot + */ Item* FindItemBySlot(uint32_t slot) const; - /** - * Finds an item based on a specified subkey (useful for pets) - * @param id the subkey to look for in the items - * @return item based on a specified subkey - */ + /** + * Finds an item based on a specified subkey (useful for pets) + * @param id the subkey to look for in the items + * @return item based on a specified subkey + */ Item* FindItemBySubKey(LWOOBJID id) const; - /** - * Adds an item to the inventory, finding a slot to place it in - * @param item item to add to the inventory - */ + /** + * Adds an item to the inventory, finding a slot to place it in + * @param item item to add to the inventory + */ void AddManagedItem(Item* item); - /** - * Removes an item from the inventory, clearing its slot - * @param item - */ + /** + * Removes an item from the inventory, clearing its slot + * @param item + */ void RemoveManagedItem(Item* item); - /** - * Returns the inventory type an item of the specified lot should be placed in - * @param lot the lot to find the inventory type for - * @return the inventory type an item of the specified lot should be placed in - */ + /** + * Returns the inventory type an item of the specified lot should be placed in + * @param lot the lot to find the inventory type for + * @return the inventory type an item of the specified lot should be placed in + */ static eInventoryType FindInventoryTypeForLot(LOT lot); - /** - * Finds the database item component for a item of a certain LOT - * @param lot the LOT of the item to get the database item component for - * @return the database item component for a item of a certain LOT - */ + /** + * Finds the database item component for a item of a certain LOT + * @param lot the LOT of the item to get the database item component for + * @return the database item component for a item of a certain LOT + */ static const CDItemComponent& FindItemComponent(LOT lot); - /** - * Cheks if the provided lot has a database item component - * @param lot the LOT to check item validity for - * @return if the provided lot has a database item component - */ + /** + * Cheks if the provided lot has a database item component + * @param lot the LOT to check item validity for + * @return if the provided lot has a database item component + */ static bool IsValidItem(LOT lot); - /** - * Returns all the items that are restricted to GMs - * @return all the items that are restricted to GMs - */ + /** + * Returns all the items that are restricted to GMs + * @return all the items that are restricted to GMs + */ static const std::vector& GetAllGMItems(); - + ~Inventory(); private: - /** - * The type of this inventory - */ + /** + * The type of this inventory + */ eInventoryType type; - /** - * The max size of this inventory - */ + /** + * The max size of this inventory + */ uint32_t size; - /** - * The amount of items that can still be stored in this inventroy - */ + /** + * The amount of items that can still be stored in this inventroy + */ uint32_t free; - /** - * The items stored in this inventory - */ + /** + * The items stored in this inventory + */ std::map items; - /** - * The inventory component this inventory belongs to - */ + /** + * The inventory component this inventory belongs to + */ InventoryComponent* component; - /** - * List of items that are GM restricted - */ + /** + * List of items that are GM restricted + */ static std::vector m_GameMasterRestrictedItems; }; diff --git a/dGame/dInventory/Item.cpp b/dGame/dInventory/Item.cpp index 71ded509..b502d5eb 100644 --- a/dGame/dInventory/Item.cpp +++ b/dGame/dInventory/Item.cpp @@ -14,10 +14,8 @@ class Inventory; -Item::Item(const LWOOBJID id, const LOT lot, Inventory* inventory, const uint32_t slot, const uint32_t count, const bool bound, const std::vector& config, const LWOOBJID parent, LWOOBJID subKey, eLootSourceType lootSourceType) -{ - if (!Inventory::IsValidItem(lot)) - { +Item::Item(const LWOOBJID id, const LOT lot, Inventory* inventory, const uint32_t slot, const uint32_t count, const bool bound, const std::vector& config, const LWOOBJID parent, LWOOBJID subKey, eLootSourceType lootSourceType) { + if (!Inventory::IsValidItem(lot)) { return; } @@ -47,15 +45,12 @@ Item::Item( bool isModMoveAndEquip, LWOOBJID subKey, bool bound, - eLootSourceType lootSourceType) -{ - if (!Inventory::IsValidItem(lot)) - { + eLootSourceType lootSourceType) { + if (!Inventory::IsValidItem(lot)) { return; } - if (isModMoveAndEquip) - { + if (isModMoveAndEquip) { showFlyingLoot = false; } @@ -83,8 +78,7 @@ Item::Item( auto* entity = inventory->GetComponent()->GetParent(); GameMessages::SendAddItemToInventoryClientSync(entity, entity->GetSystemAddress(), this, id, showFlyingLoot, static_cast(this->count), subKey, lootSourceType); - if (isModMoveAndEquip) - { + if (isModMoveAndEquip) { Equip(); Game::logger->Log("Item", "Move and equipped (%i) from (%i)", this->lot, this->inventory->GetType()); @@ -93,65 +87,52 @@ Item::Item( } } -LWOOBJID Item::GetId() const -{ +LWOOBJID Item::GetId() const { return id; } -LOT Item::GetLot() const -{ +LOT Item::GetLot() const { return lot; } -uint32_t Item::GetCount() const -{ +uint32_t Item::GetCount() const { return count; } -uint32_t Item::GetSlot() const -{ +uint32_t Item::GetSlot() const { return slot; } -std::vector& Item::GetConfig() -{ +std::vector& Item::GetConfig() { return config; } -const CDItemComponent& Item::GetInfo() const -{ +const CDItemComponent& Item::GetInfo() const { return *info; } -bool Item::GetBound() const -{ +bool Item::GetBound() const { return bound; } -Inventory* Item::GetInventory() const -{ +Inventory* Item::GetInventory() const { return inventory; } -LWOOBJID Item::GetParent() const -{ +LWOOBJID Item::GetParent() const { return parent; } -LWOOBJID Item::GetSubKey() const -{ +LWOOBJID Item::GetSubKey() const { return subKey; } -PreconditionExpression* Item::GetPreconditionExpression() const -{ +PreconditionExpression* Item::GetPreconditionExpression() const { return preconditions; } -void Item::SetCount(const uint32_t value, const bool silent, const bool disassemble, const bool showFlyingLoot, eLootSourceType lootSourceType) -{ - if (value == count) - { +void Item::SetCount(const uint32_t value, const bool silent, const bool disassemble, const bool showFlyingLoot, eLootSourceType lootSourceType) { + if (value == count) { return; } @@ -159,52 +140,40 @@ void Item::SetCount(const uint32_t value, const bool silent, const bool disassem const auto type = static_cast(info->itemType); - if (disassemble) - { - if (value < count) - { - for (auto i = 0; i < delta; ++i) - { + if (disassemble) { + if (value < count) { + for (auto i = 0; i < delta; ++i) { Disassemble(); } } } - if (!silent) - { + if (!silent) { auto* entity = inventory->GetComponent()->GetParent(); - if (value > count) - { + if (value > count) { GameMessages::SendAddItemToInventoryClientSync(entity, entity->GetSystemAddress(), this, id, showFlyingLoot, delta, LWOOBJID_EMPTY, lootSourceType); - } - else - { + } else { GameMessages::SendRemoveItemFromInventory(entity, entity->GetSystemAddress(), id, lot, inventory->GetType(), delta, value); } } count = value; - if (count == 0) - { + if (count == 0) { RemoveFromInventory(); } } -void Item::SetSlot(const uint32_t value) -{ - if (slot == value) - { +void Item::SetSlot(const uint32_t value) { + if (slot == value) { return; } - for (const auto& pair : inventory->GetItems()) - { + for (const auto& pair : inventory->GetItems()) { auto* item = pair.second; - if (item->slot == value) - { + if (item->slot == value) { item->slot = slot; } } @@ -212,18 +181,15 @@ void Item::SetSlot(const uint32_t value) slot = value; } -void Item::SetBound(const bool value) -{ +void Item::SetBound(const bool value) { bound = value; } -void Item::SetSubKey(LWOOBJID value) -{ +void Item::SetSubKey(LWOOBJID value) { subKey = value; } -void Item::SetInventory(Inventory* value) -{ +void Item::SetInventory(Inventory* value) { inventory->RemoveManagedItem(this); inventory = value; @@ -231,36 +197,29 @@ void Item::SetInventory(Inventory* value) inventory->AddManagedItem(this); } -void Item::Equip(const bool skipChecks) -{ - if (IsEquipped()) - { +void Item::Equip(const bool skipChecks) { + if (IsEquipped()) { return; } inventory->GetComponent()->EquipItem(this, skipChecks); } -void Item::UnEquip() -{ - if (!IsEquipped()) - { +void Item::UnEquip() { + if (!IsEquipped()) { return; } inventory->GetComponent()->UnEquipItem(this); } -bool Item::IsEquipped() const -{ +bool Item::IsEquipped() const { auto* component = inventory->GetComponent(); - for (const auto& pair : component->GetEquippedItems()) - { + for (const auto& pair : component->GetEquippedItems()) { const auto item = pair.second; - if (item.id == id) - { + if (item.id == id) { return true; } } @@ -268,19 +227,16 @@ bool Item::IsEquipped() const return false; } -bool Item::Consume() -{ +bool Item::Consume() { auto* skillsTable = CDClientManager::Instance()->GetTable("ObjectSkills"); - auto skills = skillsTable->Query([=](const CDObjectSkills entry) - { + auto skills = skillsTable->Query([=](const CDObjectSkills entry) { return entry.objectTemplate == static_cast(lot); - }); + }); auto success = false; - for (auto& skill : skills) - { + for (auto& skill : skills) { if (skill.castOnType == 3) // Consumable type { success = true; @@ -291,16 +247,14 @@ bool Item::Consume() GameMessages::SendUseItemResult(inventory->GetComponent()->GetParent(), lot, success); - if (success) - { + if (success) { inventory->GetComponent()->RemoveItem(lot, 1); } return success; } -bool Item::UseNonEquip() -{ +bool Item::UseNonEquip() { auto* compRegistryTable = CDClientManager::Instance()->GetTable("ComponentsRegistry"); const auto packageComponentId = compRegistryTable->GetByIDAndType(lot, COMPONENT_TYPE_PACKAGE); @@ -315,29 +269,24 @@ bool Item::UseNonEquip() auto playerEntity = inventoryComponent->GetParent(); - if (subKey != LWOOBJID_EMPTY) - { + if (subKey != LWOOBJID_EMPTY) { const auto& databasePet = GetInventory()->GetComponent()->GetDatabasePet(subKey); - if (databasePet.lot != LOT_NULL) - { + if (databasePet.lot != LOT_NULL) { GetInventory()->GetComponent()->SpawnPet(this); return true; } } - if (success && (playerEntity->GetGMLevel() >= eGameMasterLevel::GAME_MASTER_LEVEL_JUNIOR_DEVELOPER || this->GetPreconditionExpression()->Check(playerEntity))) - { + if (success && (playerEntity->GetGMLevel() >= eGameMasterLevel::GAME_MASTER_LEVEL_JUNIOR_DEVELOPER || this->GetPreconditionExpression()->Check(playerEntity))) { auto* entityParent = inventory->GetComponent()->GetParent(); - for (auto& pack : packages) - { - std::unordered_map result {}; + for (auto& pack : packages) { + std::unordered_map result{}; result = LootGenerator::Instance().RollLootMatrix(entityParent, pack.LootMatrixIndex); - if (!inventory->GetComponent()->HasSpaceForLoot(result)) - { + if (!inventory->GetComponent()->HasSpaceForLoot(result)) { return false; } @@ -350,12 +299,9 @@ bool Item::UseNonEquip() return success; } -void Item::Disassemble(const eInventoryType inventoryType) -{ - for (auto* data : config) - { - if (data->GetKey() == u"assemblyPartLOTs") - { +void Item::Disassemble(const eInventoryType inventoryType) { + for (auto* data : config) { + if (data->GetKey() == u"assemblyPartLOTs") { auto modStr = data->GetValueAsString(); std::vector modArray; @@ -366,35 +312,31 @@ void Item::Disassemble(const eInventoryType inventoryType) const auto deliminator = '+'; - while (std::getline(ssData, token, deliminator)) - { + while (std::getline(ssData, token, deliminator)) { const auto modLot = std::stoi(token.substr(2, token.size() - 1)); modArray.push_back(modLot); } - for (const auto mod : modArray) - { + for (const auto mod : modArray) { inventory->GetComponent()->AddItem(mod, 1, eLootSourceType::LOOT_SOURCE_DELETION, inventoryType); } } } } -void Item::DisassembleModel() -{ +void Item::DisassembleModel() { auto* table = CDClientManager::Instance()->GetTable("ComponentsRegistry"); const auto componentId = table->GetByIDAndType(GetLot(), COMPONENT_TYPE_RENDER); auto query = CDClientDatabase::CreatePreppedStmt( "SELECT render_asset FROM RenderComponent WHERE id = ?;"); - query.bind(1, (int) componentId); + query.bind(1, (int)componentId); auto result = query.execQuery(); - if (result.eof()) - { + if (result.eof()) { return; } @@ -406,28 +348,24 @@ void Item::DisassembleModel() result.finalize(); - if (!file.good()) - { + if (!file.good()) { return; } std::stringstream data; data << file.rdbuf(); - if (data.str().empty()) - { + if (data.str().empty()) { return; } auto* doc = new tinyxml2::XMLDocument(); - if (!doc) - { + if (!doc) { return; } - if (doc->Parse(data.str().c_str(), data.str().size()) != 0) - { + if (doc->Parse(data.str().c_str(), data.str().size()) != 0) { return; } @@ -437,22 +375,18 @@ void Item::DisassembleModel() auto* bricks = lxfml->FirstChildElement("Bricks"); std::string searchTerm = "Brick"; - if (!bricks) - { + if (!bricks) { searchTerm = "Part"; bricks = lxfml->FirstChildElement("Scene")->FirstChildElement("Model")->FirstChildElement("Group"); - if (!bricks) - { + if (!bricks) { return; } } auto* currentBrick = bricks->FirstChildElement(searchTerm.c_str()); - while (currentBrick) - { - if (currentBrick->Attribute("designID") != nullptr) - { + while (currentBrick) { + if (currentBrick->Attribute("designID") != nullptr) { parts.push_back(std::stoi(currentBrick->Attribute("designID"))); } @@ -461,15 +395,12 @@ void Item::DisassembleModel() auto* brickIDTable = CDClientManager::Instance()->GetTable("BrickIDTable"); - for (unsigned int part : parts) - { - const auto brickID = brickIDTable->Query([=](const CDBrickIDTable& entry) - { + for (unsigned int part : parts) { + const auto brickID = brickIDTable->Query([=](const CDBrickIDTable& entry) { return entry.LEGOBrickID == part; - }); + }); - if (brickID.empty()) - { + if (brickID.empty()) { continue; } @@ -477,8 +408,7 @@ void Item::DisassembleModel() } } -void Item::RemoveFromInventory() -{ +void Item::RemoveFromInventory() { UnEquip(); count = 0; @@ -488,12 +418,10 @@ void Item::RemoveFromInventory() delete this; } -Item::~Item() -{ +Item::~Item() { delete preconditions; - for (auto* value : config) - { + for (auto* value : config) { delete value; } diff --git a/dGame/dInventory/Item.h b/dGame/dInventory/Item.h index 0be9449a..3987471c 100644 --- a/dGame/dInventory/Item.h +++ b/dGame/dInventory/Item.h @@ -15,18 +15,18 @@ class Item final { public: - /** - * Creates an item, should be used if the item is not picked up but already exists - * @param id the object ID of the item to create - * @param lot the LOT of the item - * @param inventory the inventory to add this item to - * @param slot the slot in the inventory to add this item to - * @param count the amount of items to add to the inventory - * @param bound if the item should be bound - * @param config config data for this item, e.g. for rockets - * @param parent optional parent of this item, e.g. for proxy items - * @param subKey optional subkey for this item, e.g. for pets - */ + /** + * Creates an item, should be used if the item is not picked up but already exists + * @param id the object ID of the item to create + * @param lot the LOT of the item + * @param inventory the inventory to add this item to + * @param slot the slot in the inventory to add this item to + * @param count the amount of items to add to the inventory + * @param bound if the item should be bound + * @param config config data for this item, e.g. for rockets + * @param parent optional parent of this item, e.g. for proxy items + * @param subKey optional subkey for this item, e.g. for pets + */ explicit Item( LWOOBJID id, LOT lot, @@ -37,22 +37,22 @@ public: const std::vector& config, LWOOBJID parent, LWOOBJID subKey, - eLootSourceType lootSourceType = eLootSourceType::LOOT_SOURCE_NONE + eLootSourceType lootSourceType = eLootSourceType::LOOT_SOURCE_NONE ); - /** - * Creates an item, should be used if the item is picked up / added to the inventory after load - * @param lot the LOT of the item - * @param inventory the inventory to add this item to - * @param slot the slot in the inventory to add this item to - * @param count the amount of items to add to the inventory - * @param config config data for this item, e.g. for rockets - * @param parent optional parent of this item, e.g. for proxy items - * @param showFlyingLoot show UI animation of the item being added - * @param isModMoveAndEquip equips the item - * @param subKey optional subkey for this item, e.g. for pets - * @param bound if the item should be bound - */ + /** + * Creates an item, should be used if the item is picked up / added to the inventory after load + * @param lot the LOT of the item + * @param inventory the inventory to add this item to + * @param slot the slot in the inventory to add this item to + * @param count the amount of items to add to the inventory + * @param config config data for this item, e.g. for rockets + * @param parent optional parent of this item, e.g. for proxy items + * @param showFlyingLoot show UI animation of the item being added + * @param isModMoveAndEquip equips the item + * @param subKey optional subkey for this item, e.g. for pets + * @param bound if the item should be bound + */ explicit Item( LOT lot, Inventory* inventory, @@ -64,209 +64,208 @@ public: bool isModMoveAndEquip = false, LWOOBJID subKey = LWOOBJID_EMPTY, bool bound = false, - eLootSourceType lootSourceType = eLootSourceType::LOOT_SOURCE_NONE + eLootSourceType lootSourceType = eLootSourceType::LOOT_SOURCE_NONE ); - ~Item(); + ~Item(); - /** - * Returns the object ID of this item - * @return the object ID of this item - */ + /** + * Returns the object ID of this item + * @return the object ID of this item + */ LWOOBJID GetId() const; - /** - * Returns the lot of this item - * @return the lot of this item - */ + /** + * Returns the lot of this item + * @return the lot of this item + */ LOT GetLot() const; - /** - * Sets the number of items this item represents - * @param value the number to update by - * @param silent if true, the client will not be notified of the change with GMs - * @param disassemble if items were removed, this returns all the sub parts of the item individually if it had assembly part lots - * @param showFlyingLoot shows flying loot to the client, if not silent - */ - void SetCount(uint32_t value, bool silent = false, bool disassemble = true, bool showFlyingLoot = true, eLootSourceType lootSourceType = eLootSourceType::LOOT_SOURCE_NONE); + /** + * Sets the number of items this item represents + * @param value the number to update by + * @param silent if true, the client will not be notified of the change with GMs + * @param disassemble if items were removed, this returns all the sub parts of the item individually if it had assembly part lots + * @param showFlyingLoot shows flying loot to the client, if not silent + */ + void SetCount(uint32_t value, bool silent = false, bool disassemble = true, bool showFlyingLoot = true, eLootSourceType lootSourceType = eLootSourceType::LOOT_SOURCE_NONE); - /** - * Returns the number of items this item represents (e.g. for stacks) - * @return the number of items this item represents - */ + /** + * Returns the number of items this item represents (e.g. for stacks) + * @return the number of items this item represents + */ uint32_t GetCount() const; - /** - * Sets the slot this item is stored in - * @param value the slot this item is stored in - */ - void SetSlot(uint32_t value); + /** + * Sets the slot this item is stored in + * @param value the slot this item is stored in + */ + void SetSlot(uint32_t value); - /** - * Returns the slot this item is in - * @return the slot this item is in - */ + /** + * Returns the slot this item is in + * @return the slot this item is in + */ uint32_t GetSlot() const; - /** - * Returns current config info for this item, e.g. for rockets - * @return current config info for this item - */ + /** + * Returns current config info for this item, e.g. for rockets + * @return current config info for this item + */ std::vector& GetConfig(); - /** - * Returns the database info for this item - * @return the database info for this item - */ + /** + * Returns the database info for this item + * @return the database info for this item + */ const CDItemComponent& GetInfo() const; - /** - * Sets if the item is bound - * @param value if the item is bound - */ - void SetBound(bool value); + /** + * Sets if the item is bound + * @param value if the item is bound + */ + void SetBound(bool value); - /** - * Returns if the item is bound - * @return if the item is bound - */ + /** + * Returns if the item is bound + * @return if the item is bound + */ bool GetBound() const; - /** - * Sets the inventory this item belongs to - * @param value the inventory this item belongs to - */ - void SetInventory(Inventory* value); + /** + * Sets the inventory this item belongs to + * @param value the inventory this item belongs to + */ + void SetInventory(Inventory* value); - /** - * Returns the inventory this item belongs to - * @return the inventory this item belongs to - */ + /** + * Returns the inventory this item belongs to + * @return the inventory this item belongs to + */ Inventory* GetInventory() const; - /** - * Returns the parent of this item, e.g. for proxy items - * @return the parent of this item - */ + /** + * Returns the parent of this item, e.g. for proxy items + * @return the parent of this item + */ LWOOBJID GetParent() const; - /** - * Sets the subkey for this item, e.g. for pets - * @param value the subkey for this item - */ - void SetSubKey(LWOOBJID value); + /** + * Sets the subkey for this item, e.g. for pets + * @param value the subkey for this item + */ + void SetSubKey(LWOOBJID value); - /** - * Returns the sub key this item has, e.g. for pets - * @return the sub key this item has - */ + /** + * Returns the sub key this item has, e.g. for pets + * @return the sub key this item has + */ LWOOBJID GetSubKey() const; - /** - * Returns the preconditions that must be met before this item may be used - * @return the preconditions that must be met before this item may be used - */ + /** + * Returns the preconditions that must be met before this item may be used + * @return the preconditions that must be met before this item may be used + */ PreconditionExpression* GetPreconditionExpression() const; - /** - * Equips this item into the linked inventory - * @param skipChecks skips equip checks for special items like rockets and cars - */ + /** + * Equips this item into the linked inventory + * @param skipChecks skips equip checks for special items like rockets and cars + */ void Equip(bool skipChecks = false); - /** - * Unequps the item from the linked inventory - */ + /** + * Unequps the item from the linked inventory + */ void UnEquip(); - /** - * Returns if the item is equipped in the linked inventory - * @return if the item is equipped - */ + /** + * Returns if the item is equipped in the linked inventory + * @return if the item is equipped + */ bool IsEquipped() const; - /** - * Attempts to consume one of this item, applying its skills - * @return whether the consumption was successful, e.g. the skill was cast - */ + /** + * Attempts to consume one of this item, applying its skills + * @return whether the consumption was successful, e.g. the skill was cast + */ bool Consume(); - /** - * Uses this item if its non equip, essentially an interface for the linked GM - * @return whether the use was successful, e.g. the skill was cast - */ + /** + * Uses this item if its non equip, essentially an interface for the linked GM + * @return whether the use was successful, e.g. the skill was cast + */ bool UseNonEquip(); - /** - * Disassembles the part LOTs of this item back into the inventory, if it has any - * @param inventoryType the inventory to dissassemble into - */ + /** + * Disassembles the part LOTs of this item back into the inventory, if it has any + * @param inventoryType the inventory to dissassemble into + */ void Disassemble(eInventoryType inventoryType = INVALID); - /** - * Disassembles this item into bricks - */ + /** + * Disassembles this item into bricks + */ void DisassembleModel(); - /** - * Removes the item from the linked inventory - */ + /** + * Removes the item from the linked inventory + */ void RemoveFromInventory(); private: - /** - * The object ID of this item - */ + /** + * The object ID of this item + */ LWOOBJID id; - /** - * The LOT of this item - */ + /** + * The LOT of this item + */ LOT lot; - /** - * The number of items this represents - */ + /** + * The number of items this represents + */ uint32_t count; - /** - * The slot this item is stored in - */ + /** + * The slot this item is stored in + */ uint32_t slot; - /** - * If this item is bound - */ + /** + * If this item is bound + */ bool bound; - /** - * A potential parent of this item, if this item is a subitem - */ + /** + * A potential parent of this item, if this item is a subitem + */ LWOOBJID parent; - /** - * A potential subkey of this item, e.g. for pets - */ + /** + * A potential subkey of this item, e.g. for pets + */ LWOOBJID subKey; - /** - * Config data for this item, e.g. for rocket parts and car parts - */ + /** + * Config data for this item, e.g. for rocket parts and car parts + */ std::vector config; - /** - * The inventory this item belongs to - */ + /** + * The inventory this item belongs to + */ Inventory* inventory; - /** - * The database information of this item - */ + /** + * The database information of this item + */ const CDItemComponent* info; - /** - * A precondition to using this item - */ + /** + * A precondition to using this item + */ PreconditionExpression* preconditions = nullptr; }; - \ No newline at end of file diff --git a/dGame/dInventory/ItemSet.cpp b/dGame/dInventory/ItemSet.cpp index feddd757..5d8ea226 100644 --- a/dGame/dInventory/ItemSet.cpp +++ b/dGame/dInventory/ItemSet.cpp @@ -8,8 +8,7 @@ #include "MissionComponent.h" #include -ItemSet::ItemSet(const uint32_t id, InventoryComponent* inventoryComponent) -{ +ItemSet::ItemSet(const uint32_t id, InventoryComponent* inventoryComponent) { this->m_ID = id; this->m_InventoryComponent = inventoryComponent; @@ -17,19 +16,16 @@ ItemSet::ItemSet(const uint32_t id, InventoryComponent* inventoryComponent) auto query = CDClientDatabase::CreatePreppedStmt( "SELECT skillSetWith2, skillSetWith3, skillSetWith4, skillSetWith5, skillSetWith6, itemIDs FROM ItemSets WHERE setID = ?;"); - query.bind(1, (int) id); + query.bind(1, (int)id); auto result = query.execQuery(); - if (result.eof()) - { + if (result.eof()) { return; } - for (auto i = 0; i < 5; ++i) - { - if (result.fieldIsNull(i)) - { + for (auto i = 0; i < 5; ++i) { + if (result.fieldIsNull(i)) { continue; } @@ -39,15 +35,12 @@ ItemSet::ItemSet(const uint32_t id, InventoryComponent* inventoryComponent) auto skillResult = skillQuery.execQuery(); - if (skillResult.eof()) - { + if (skillResult.eof()) { return; } - while (!skillResult.eof()) - { - if (skillResult.fieldIsNull(0)) - { + while (!skillResult.eof()) { + if (skillResult.fieldIsNull(0)) { skillResult.nextRow(); continue; @@ -55,8 +48,7 @@ ItemSet::ItemSet(const uint32_t id, InventoryComponent* inventoryComponent) const auto skillId = skillResult.getIntField(0); - switch (i) - { + switch (i) { case 0: m_SkillsWith2.push_back(skillId); break; @@ -91,42 +83,34 @@ ItemSet::ItemSet(const uint32_t id, InventoryComponent* inventoryComponent) m_Items = {}; - while (std::getline(stream, token, ',')) - { + while (std::getline(stream, token, ',')) { int32_t value; - if (GeneralUtils::TryParse(token, value)) - { + if (GeneralUtils::TryParse(token, value)) { m_Items.push_back(value); } } m_Equipped = {}; - for (const auto item : m_Items) - { - if (inventoryComponent->IsEquipped(item)) - { + for (const auto item : m_Items) { + if (inventoryComponent->IsEquipped(item)) { m_Equipped.push_back(item); } } } -bool ItemSet::Contains(const LOT lot) -{ +bool ItemSet::Contains(const LOT lot) { return std::find(m_Items.begin(), m_Items.end(), lot) != m_Items.end(); } -void ItemSet::OnEquip(const LOT lot) -{ - if (!Contains(lot)) - { +void ItemSet::OnEquip(const LOT lot) { + if (!Contains(lot)) { return; } const auto& index = std::find(m_Equipped.begin(), m_Equipped.end(), lot); - if (index != m_Equipped.end()) - { + if (index != m_Equipped.end()) { return; } @@ -134,16 +118,14 @@ void ItemSet::OnEquip(const LOT lot) const auto& skillSet = GetSkillSet(m_Equipped.size()); - if (skillSet.empty()) - { + if (skillSet.empty()) { return; } auto* skillComponent = m_InventoryComponent->GetParent()->GetComponent(); auto* missionComponent = m_InventoryComponent->GetParent()->GetComponent(); - for (const auto skill : skillSet) - { + for (const auto skill : skillSet) { auto* skillTable = CDClientManager::Instance()->GetTable("SkillBehavior"); const auto behaviorId = skillTable->GetSkillByID(skill).behaviorID; @@ -154,17 +136,14 @@ void ItemSet::OnEquip(const LOT lot) } } -void ItemSet::OnUnEquip(const LOT lot) -{ - if (!Contains(lot)) - { +void ItemSet::OnUnEquip(const LOT lot) { + if (!Contains(lot)) { return; } const auto& index = std::find(m_Equipped.begin(), m_Equipped.end(), lot); - if (index == m_Equipped.end()) - { + if (index == m_Equipped.end()) { return; } @@ -172,15 +151,13 @@ void ItemSet::OnUnEquip(const LOT lot) m_Equipped.erase(index); - if (skillSet.empty()) - { + if (skillSet.empty()) { return; } const auto& skillComponent = m_InventoryComponent->GetParent()->GetComponent(); - for (const auto skill : skillSet) - { + for (const auto skill : skillSet) { auto* skillTable = CDClientManager::Instance()->GetTable("SkillBehavior"); const auto behaviorId = skillTable->GetSkillByID(skill).behaviorID; @@ -189,36 +166,28 @@ void ItemSet::OnUnEquip(const LOT lot) } } -uint32_t ItemSet::GetEquippedCount() const -{ +uint32_t ItemSet::GetEquippedCount() const { return m_Equipped.size(); } -uint32_t ItemSet::GetID() const -{ +uint32_t ItemSet::GetID() const { return m_ID; } -void ItemSet::Update(float deltaTime) -{ - for (auto& passiveAbility : m_PassiveAbilities) - { +void ItemSet::Update(float deltaTime) { + for (auto& passiveAbility : m_PassiveAbilities) { passiveAbility.Update(deltaTime); } } -void ItemSet::TriggerPassiveAbility(PassiveAbilityTrigger trigger) -{ - for (auto& passiveAbility : m_PassiveAbilities) - { +void ItemSet::TriggerPassiveAbility(PassiveAbilityTrigger trigger) { + for (auto& passiveAbility : m_PassiveAbilities) { passiveAbility.Trigger(trigger); } } -std::vector ItemSet::GetSkillSet(const uint32_t itemCount) const -{ - switch (itemCount) - { +std::vector ItemSet::GetSkillSet(const uint32_t itemCount) const { + switch (itemCount) { case 2: return m_SkillsWith2; case 3: diff --git a/dGame/dInventory/ItemSet.h b/dGame/dInventory/ItemSet.h index d443ca06..2ed3be14 100644 --- a/dGame/dInventory/ItemSet.h +++ b/dGame/dInventory/ItemSet.h @@ -15,100 +15,100 @@ class ItemSet { public: explicit ItemSet(uint32_t id, InventoryComponent* inventoryComponent); - void Update(float deltaTime); + void Update(float deltaTime); - /** - * Returns if this item set contains the LOT specified - * @param lot the lot to check for - * @return if this item set contains the LOT specified - */ + /** + * Returns if this item set contains the LOT specified + * @param lot the lot to check for + * @return if this item set contains the LOT specified + */ bool Contains(LOT lot); - /** - * Equips the item set skill for this LOT (if it's in the item set) - * @param lot the LOT of the item to equip skills for - */ + /** + * Equips the item set skill for this LOT (if it's in the item set) + * @param lot the LOT of the item to equip skills for + */ void OnEquip(LOT lot); - /** - * Unequips the item set skill for this LOT (if it's in the item set) - * @param lot the LOT of the item to unequip skills for - */ + /** + * Unequips the item set skill for this LOT (if it's in the item set) + * @param lot the LOT of the item to unequip skills for + */ void OnUnEquip(LOT lot); - /** - * Returns the number of items in the item set that are currently equipped - * @return the number of items in the item set that are currently equipped - */ + /** + * Returns the number of items in the item set that are currently equipped + * @return the number of items in the item set that are currently equipped + */ uint32_t GetEquippedCount() const; - /** - * Returns the ID of this item set - * @return the ID of this item set - */ + /** + * Returns the ID of this item set + * @return the ID of this item set + */ uint32_t GetID() const; - /** - * Triggers all the passive abilities in this item set that match this trigger - * @param trigger the trigger to use to trigger passive abilities - */ - void TriggerPassiveAbility(PassiveAbilityTrigger trigger); + /** + * Triggers all the passive abilities in this item set that match this trigger + * @param trigger the trigger to use to trigger passive abilities + */ + void TriggerPassiveAbility(PassiveAbilityTrigger trigger); - /** - * Returns the skills that can be equipped for a specified amount of equipped items - * @param itemCount the amount of items equipped to check for - * @return the skills that can be equipped for a specified amount of equipped items - */ + /** + * Returns the skills that can be equipped for a specified amount of equipped items + * @param itemCount the amount of items equipped to check for + * @return the skills that can be equipped for a specified amount of equipped items + */ std::vector GetSkillSet(uint32_t itemCount) const; private: - /** - * The ID of this skill set - */ + /** + * The ID of this skill set + */ uint32_t m_ID; - /** - * The inventory this skill set belongs to - */ + /** + * The inventory this skill set belongs to + */ InventoryComponent* m_InventoryComponent; - /** - * The items in the skill set that are currently equipped - */ + /** + * The items in the skill set that are currently equipped + */ std::vector m_Equipped; - /** - * The total list of items in this skill set - */ + /** + * The total list of items in this skill set + */ std::vector m_Items; - /** - * The skills that can be triggered when 2 items are equipped - */ + /** + * The skills that can be triggered when 2 items are equipped + */ std::vector m_SkillsWith2; - /** - * The skills that can be triggered when 3 items are equipped - */ + /** + * The skills that can be triggered when 3 items are equipped + */ std::vector m_SkillsWith3; - /** - * The skills that can be triggered when 4 items are equipped - */ + /** + * The skills that can be triggered when 4 items are equipped + */ std::vector m_SkillsWith4; - /** - * The skills that can be triggered when 5 items are equipped - */ + /** + * The skills that can be triggered when 5 items are equipped + */ std::vector m_SkillsWith5; - /** - * The skills that can be triggered when 6 items are equipped - */ + /** + * The skills that can be triggered when 6 items are equipped + */ std::vector m_SkillsWith6; - /** - * The passive abilities associated with this skill set - */ + /** + * The passive abilities associated with this skill set + */ std::vector m_PassiveAbilities; -}; \ No newline at end of file +}; diff --git a/dGame/dInventory/ItemSetPassiveAbility.cpp b/dGame/dInventory/ItemSetPassiveAbility.cpp index 9edb671b..d90f6e4e 100644 --- a/dGame/dInventory/ItemSetPassiveAbility.cpp +++ b/dGame/dInventory/ItemSetPassiveAbility.cpp @@ -5,330 +5,316 @@ #include "ItemSet.h" #include "ItemSetPassiveAbilityID.h" -ItemSetPassiveAbility::ItemSetPassiveAbility(PassiveAbilityTrigger trigger, Entity* parent, ItemSet* itemSet) -{ - m_Trigger = trigger; - m_Parent = parent; - m_ItemSet = itemSet; +ItemSetPassiveAbility::ItemSetPassiveAbility(PassiveAbilityTrigger trigger, Entity* parent, ItemSet* itemSet) { + m_Trigger = trigger; + m_Parent = parent; + m_ItemSet = itemSet; - m_Cooldown = 0.0f; + m_Cooldown = 0.0f; } -ItemSetPassiveAbility::~ItemSetPassiveAbility() -{ +ItemSetPassiveAbility::~ItemSetPassiveAbility() { } -void ItemSetPassiveAbility::Trigger(PassiveAbilityTrigger trigger) -{ - if (m_Trigger != trigger || m_Cooldown > 0.0f) - { - return; - } +void ItemSetPassiveAbility::Trigger(PassiveAbilityTrigger trigger) { + if (m_Trigger != trigger || m_Cooldown > 0.0f) { + return; + } - Activate(); + Activate(); } -void ItemSetPassiveAbility::Update(float deltaTime) -{ - if (m_Cooldown > 0.0f) - { - m_Cooldown -= deltaTime; - } +void ItemSetPassiveAbility::Update(float deltaTime) { + if (m_Cooldown > 0.0f) { + m_Cooldown -= deltaTime; + } } -void ItemSetPassiveAbility::Activate() -{ - if (m_Trigger == PassiveAbilityTrigger::EnemySmashed) - { - OnEnemySmshed(); +void ItemSetPassiveAbility::Activate() { + if (m_Trigger == PassiveAbilityTrigger::EnemySmashed) { + OnEnemySmshed(); - return; - } + return; + } - auto* destroyableComponent = m_Parent->GetComponent(); - auto* skillComponent = m_Parent->GetComponent(); + auto* destroyableComponent = m_Parent->GetComponent(); + auto* skillComponent = m_Parent->GetComponent(); - if (destroyableComponent == nullptr || skillComponent == nullptr) - { - return; - } + if (destroyableComponent == nullptr || skillComponent == nullptr) { + return; + } - EntityManager::Instance()->SerializeEntity(m_Parent); + EntityManager::Instance()->SerializeEntity(m_Parent); - const auto id = static_cast(m_ItemSet->GetID()); - const auto parentID = m_Parent->GetObjectID(); - const auto equippedCount = m_ItemSet->GetEquippedCount(); + const auto id = static_cast(m_ItemSet->GetID()); + const auto parentID = m_Parent->GetObjectID(); + const auto equippedCount = m_ItemSet->GetEquippedCount(); - switch (id) - { - // Assembly - case ItemSetPassiveAbilityID::InventorRank1: - case ItemSetPassiveAbilityID::SummonerRank1: - case ItemSetPassiveAbilityID::EngineerRank1: { - if (equippedCount < 4) return; - m_Cooldown = 11.0f; - skillComponent->CalculateBehavior(394, 4401, parentID); - break; - } - case ItemSetPassiveAbilityID::InventorRank2: - case ItemSetPassiveAbilityID::SummonerRank2: - case ItemSetPassiveAbilityID::EngineerRank2: { - if (equippedCount < 4) return; - m_Cooldown = 11.0f; - skillComponent->CalculateBehavior(581, 9433, parentID); - break; - } - case ItemSetPassiveAbilityID::InventorRank3: - case ItemSetPassiveAbilityID::SummonerRank3: - case ItemSetPassiveAbilityID::EngineerRank3: { - if (equippedCount < 4) return; - m_Cooldown = 11.0f; - skillComponent->CalculateBehavior(582, 9435, parentID); - break; - } + switch (id) { + // Assembly + case ItemSetPassiveAbilityID::InventorRank1: + case ItemSetPassiveAbilityID::SummonerRank1: + case ItemSetPassiveAbilityID::EngineerRank1: { + if (equippedCount < 4) return; + m_Cooldown = 11.0f; + skillComponent->CalculateBehavior(394, 4401, parentID); + break; + } + case ItemSetPassiveAbilityID::InventorRank2: + case ItemSetPassiveAbilityID::SummonerRank2: + case ItemSetPassiveAbilityID::EngineerRank2: { + if (equippedCount < 4) return; + m_Cooldown = 11.0f; + skillComponent->CalculateBehavior(581, 9433, parentID); + break; + } + case ItemSetPassiveAbilityID::InventorRank3: + case ItemSetPassiveAbilityID::SummonerRank3: + case ItemSetPassiveAbilityID::EngineerRank3: { + if (equippedCount < 4) return; + m_Cooldown = 11.0f; + skillComponent->CalculateBehavior(582, 9435, parentID); + break; + } - // Sentinel - case ItemSetPassiveAbilityID::KnightRank1: { - if (equippedCount < 4) return; - m_Cooldown = 11.0f; - skillComponent->CalculateBehavior(559, 8884, parentID); - break; - } - case ItemSetPassiveAbilityID::KnightRank2: { - if (equippedCount < 4) return; - m_Cooldown = 11.0f; - skillComponent->CalculateBehavior(560, 8885, parentID); - break; - } - case ItemSetPassiveAbilityID::KnightRank3: { - if (equippedCount < 4) return; - m_Cooldown = 11.0f; - skillComponent->CalculateBehavior(561, 8890, parentID); - break; - } + // Sentinel + case ItemSetPassiveAbilityID::KnightRank1: { + if (equippedCount < 4) return; + m_Cooldown = 11.0f; + skillComponent->CalculateBehavior(559, 8884, parentID); + break; + } + case ItemSetPassiveAbilityID::KnightRank2: { + if (equippedCount < 4) return; + m_Cooldown = 11.0f; + skillComponent->CalculateBehavior(560, 8885, parentID); + break; + } + case ItemSetPassiveAbilityID::KnightRank3: { + if (equippedCount < 4) return; + m_Cooldown = 11.0f; + skillComponent->CalculateBehavior(561, 8890, parentID); + break; + } - case ItemSetPassiveAbilityID::SpaceRangerRank1: { - if (equippedCount < 4) return; - m_Cooldown = 11.0f; - skillComponent->CalculateBehavior(1101, 24612, parentID); - break; - } - case ItemSetPassiveAbilityID::SpaceRangerRank2: { - if (equippedCount < 4) return; - m_Cooldown = 11.0f; - skillComponent->CalculateBehavior(1102, 24617, parentID); - break; - } - case ItemSetPassiveAbilityID::SpaceRangerRank3: { - if (equippedCount < 4) return; - m_Cooldown = 11.0f; - skillComponent->CalculateBehavior(1103, 24622, parentID); - break; - } + case ItemSetPassiveAbilityID::SpaceRangerRank1: { + if (equippedCount < 4) return; + m_Cooldown = 11.0f; + skillComponent->CalculateBehavior(1101, 24612, parentID); + break; + } + case ItemSetPassiveAbilityID::SpaceRangerRank2: { + if (equippedCount < 4) return; + m_Cooldown = 11.0f; + skillComponent->CalculateBehavior(1102, 24617, parentID); + break; + } + case ItemSetPassiveAbilityID::SpaceRangerRank3: { + if (equippedCount < 4) return; + m_Cooldown = 11.0f; + skillComponent->CalculateBehavior(1103, 24622, parentID); + break; + } - case ItemSetPassiveAbilityID::SamuraiRank1: { - if (equippedCount < 4) return; - m_Cooldown = 11.0f; - skillComponent->CalculateBehavior(562, 8899, parentID); - break; - } - case ItemSetPassiveAbilityID::SamuraiRank2: { - if (equippedCount < 4) return; - m_Cooldown = 11.0f; - skillComponent->CalculateBehavior(563, 8904, parentID); - break; - } - case ItemSetPassiveAbilityID::SamuraiRank3: { - if (equippedCount < 4) return; - m_Cooldown = 11.0f; - skillComponent->CalculateBehavior(564, 8909, parentID); - break; - } + case ItemSetPassiveAbilityID::SamuraiRank1: { + if (equippedCount < 4) return; + m_Cooldown = 11.0f; + skillComponent->CalculateBehavior(562, 8899, parentID); + break; + } + case ItemSetPassiveAbilityID::SamuraiRank2: { + if (equippedCount < 4) return; + m_Cooldown = 11.0f; + skillComponent->CalculateBehavior(563, 8904, parentID); + break; + } + case ItemSetPassiveAbilityID::SamuraiRank3: { + if (equippedCount < 4) return; + m_Cooldown = 11.0f; + skillComponent->CalculateBehavior(564, 8909, parentID); + break; + } - default: - break; - } + default: + break; + } } -std::vector ItemSetPassiveAbility::FindAbilities(uint32_t itemSetID, Entity* parent, ItemSet* itemSet) -{ - std::vector abilities; +std::vector ItemSetPassiveAbility::FindAbilities(uint32_t itemSetID, Entity* parent, ItemSet* itemSet) { + std::vector abilities; - switch (static_cast(itemSetID)) { - // Assembly - case ItemSetPassiveAbilityID::SummonerRank1: - case ItemSetPassiveAbilityID::SummonerRank2: - case ItemSetPassiveAbilityID::SummonerRank3: - case ItemSetPassiveAbilityID::InventorRank1: - case ItemSetPassiveAbilityID::InventorRank2: - case ItemSetPassiveAbilityID::InventorRank3: - case ItemSetPassiveAbilityID::EngineerRank1: - case ItemSetPassiveAbilityID::EngineerRank2: - case ItemSetPassiveAbilityID::EngineerRank3: { - abilities.emplace_back(PassiveAbilityTrigger::AssemblyImagination, parent, itemSet); + switch (static_cast(itemSetID)) { + // Assembly + case ItemSetPassiveAbilityID::SummonerRank1: + case ItemSetPassiveAbilityID::SummonerRank2: + case ItemSetPassiveAbilityID::SummonerRank3: + case ItemSetPassiveAbilityID::InventorRank1: + case ItemSetPassiveAbilityID::InventorRank2: + case ItemSetPassiveAbilityID::InventorRank3: + case ItemSetPassiveAbilityID::EngineerRank1: + case ItemSetPassiveAbilityID::EngineerRank2: + case ItemSetPassiveAbilityID::EngineerRank3: { + abilities.emplace_back(PassiveAbilityTrigger::AssemblyImagination, parent, itemSet); - break; - } - // Sentinel - case ItemSetPassiveAbilityID::KnightRank1: - case ItemSetPassiveAbilityID::KnightRank2: - case ItemSetPassiveAbilityID::KnightRank3: - case ItemSetPassiveAbilityID::SpaceRangerRank1: - case ItemSetPassiveAbilityID::SpaceRangerRank2: - case ItemSetPassiveAbilityID::SpaceRangerRank3: - case ItemSetPassiveAbilityID::SamuraiRank1: - case ItemSetPassiveAbilityID::SamuraiRank2: - case ItemSetPassiveAbilityID::SamuraiRank3: { - abilities.emplace_back(PassiveAbilityTrigger::SentinelArmor, parent, itemSet); - abilities.emplace_back(PassiveAbilityTrigger::EnemySmashed, parent, itemSet); + break; + } + // Sentinel + case ItemSetPassiveAbilityID::KnightRank1: + case ItemSetPassiveAbilityID::KnightRank2: + case ItemSetPassiveAbilityID::KnightRank3: + case ItemSetPassiveAbilityID::SpaceRangerRank1: + case ItemSetPassiveAbilityID::SpaceRangerRank2: + case ItemSetPassiveAbilityID::SpaceRangerRank3: + case ItemSetPassiveAbilityID::SamuraiRank1: + case ItemSetPassiveAbilityID::SamuraiRank2: + case ItemSetPassiveAbilityID::SamuraiRank3: { + abilities.emplace_back(PassiveAbilityTrigger::SentinelArmor, parent, itemSet); + abilities.emplace_back(PassiveAbilityTrigger::EnemySmashed, parent, itemSet); - break; - } - // Paradox - case ItemSetPassiveAbilityID::BatLord: - case ItemSetPassiveAbilityID::SpaceMarauderRank1: - case ItemSetPassiveAbilityID::SpaceMarauderRank2: - case ItemSetPassiveAbilityID::SpaceMarauderRank3: - case ItemSetPassiveAbilityID::SorcererRank1: - case ItemSetPassiveAbilityID::SorcererRank2: - case ItemSetPassiveAbilityID::SorcererRank3: - case ItemSetPassiveAbilityID::ShinobiRank1: - case ItemSetPassiveAbilityID::ShinobiRank2: - case ItemSetPassiveAbilityID::ShinobiRank3: { - abilities.emplace_back(PassiveAbilityTrigger::EnemySmashed, parent, itemSet); + break; + } + // Paradox + case ItemSetPassiveAbilityID::BatLord: + case ItemSetPassiveAbilityID::SpaceMarauderRank1: + case ItemSetPassiveAbilityID::SpaceMarauderRank2: + case ItemSetPassiveAbilityID::SpaceMarauderRank3: + case ItemSetPassiveAbilityID::SorcererRank1: + case ItemSetPassiveAbilityID::SorcererRank2: + case ItemSetPassiveAbilityID::SorcererRank3: + case ItemSetPassiveAbilityID::ShinobiRank1: + case ItemSetPassiveAbilityID::ShinobiRank2: + case ItemSetPassiveAbilityID::ShinobiRank3: { + abilities.emplace_back(PassiveAbilityTrigger::EnemySmashed, parent, itemSet); - break; - } - default: - break; - } - - return abilities; + break; + } + default: + break; + } + + return abilities; } -void ItemSetPassiveAbility::OnEnemySmshed() -{ - auto* destroyableComponent = m_Parent->GetComponent(); - auto* skillComponent = m_Parent->GetComponent(); +void ItemSetPassiveAbility::OnEnemySmshed() { + auto* destroyableComponent = m_Parent->GetComponent(); + auto* skillComponent = m_Parent->GetComponent(); - if (destroyableComponent == nullptr || skillComponent == nullptr) - { - return; - } + if (destroyableComponent == nullptr || skillComponent == nullptr) { + return; + } - EntityManager::Instance()->SerializeEntity(m_Parent); + EntityManager::Instance()->SerializeEntity(m_Parent); - const auto id = static_cast(m_ItemSet->GetID()); - const auto parentID = m_Parent->GetObjectID(); - const auto equippedCount = m_ItemSet->GetEquippedCount(); + const auto id = static_cast(m_ItemSet->GetID()); + const auto parentID = m_Parent->GetObjectID(); + const auto equippedCount = m_ItemSet->GetEquippedCount(); - switch (id) - { - // Bat Lord - case ItemSetPassiveAbilityID::BatLord: { - if(equippedCount < 5) return; - destroyableComponent->Heal(3); - break; - } - // Sentinel - case ItemSetPassiveAbilityID::KnightRank1: { - if (equippedCount < 5) return; - destroyableComponent->Repair(1); - break; - } - case ItemSetPassiveAbilityID::KnightRank2: { - if (equippedCount < 5) return; - destroyableComponent->Repair(1); - break; - } - case ItemSetPassiveAbilityID::KnightRank3: { - if (equippedCount < 5) return; - destroyableComponent->Repair(1); - break; - } + switch (id) { + // Bat Lord + case ItemSetPassiveAbilityID::BatLord: { + if (equippedCount < 5) return; + destroyableComponent->Heal(3); + break; + } + // Sentinel + case ItemSetPassiveAbilityID::KnightRank1: { + if (equippedCount < 5) return; + destroyableComponent->Repair(1); + break; + } + case ItemSetPassiveAbilityID::KnightRank2: { + if (equippedCount < 5) return; + destroyableComponent->Repair(1); + break; + } + case ItemSetPassiveAbilityID::KnightRank3: { + if (equippedCount < 5) return; + destroyableComponent->Repair(1); + break; + } - case ItemSetPassiveAbilityID::SpaceRangerRank1: { - if (equippedCount < 5) return; - destroyableComponent->Repair(1); - break; - } - case ItemSetPassiveAbilityID::SpaceRangerRank2: { - if (equippedCount < 5) return; - destroyableComponent->Repair(1); - break; - } - case ItemSetPassiveAbilityID::SpaceRangerRank3: { - if (equippedCount < 5) return; - destroyableComponent->Repair(1); - break; - } + case ItemSetPassiveAbilityID::SpaceRangerRank1: { + if (equippedCount < 5) return; + destroyableComponent->Repair(1); + break; + } + case ItemSetPassiveAbilityID::SpaceRangerRank2: { + if (equippedCount < 5) return; + destroyableComponent->Repair(1); + break; + } + case ItemSetPassiveAbilityID::SpaceRangerRank3: { + if (equippedCount < 5) return; + destroyableComponent->Repair(1); + break; + } - case ItemSetPassiveAbilityID::SamuraiRank1: { - if (equippedCount < 5) return; - destroyableComponent->Repair(1); - break; - } - case ItemSetPassiveAbilityID::SamuraiRank2: { - if (equippedCount < 5) return; - destroyableComponent->Repair(1); - break; - } - case ItemSetPassiveAbilityID::SamuraiRank3: { - if (equippedCount < 5) return; - destroyableComponent->Repair(1); - break; - } + case ItemSetPassiveAbilityID::SamuraiRank1: { + if (equippedCount < 5) return; + destroyableComponent->Repair(1); + break; + } + case ItemSetPassiveAbilityID::SamuraiRank2: { + if (equippedCount < 5) return; + destroyableComponent->Repair(1); + break; + } + case ItemSetPassiveAbilityID::SamuraiRank3: { + if (equippedCount < 5) return; + destroyableComponent->Repair(1); + break; + } - // Paradox - case ItemSetPassiveAbilityID::SpaceMarauderRank1: { - if (equippedCount < 4) return; - destroyableComponent->Imagine(1); - break; - } - case ItemSetPassiveAbilityID::SpaceMarauderRank2: { - if (equippedCount < 4) return; - destroyableComponent->Imagine(2); - break; - } - case ItemSetPassiveAbilityID::SpaceMarauderRank3: { - if (equippedCount < 4) return; - destroyableComponent->Imagine(3); - break; - } - - case ItemSetPassiveAbilityID::ShinobiRank1: { - if (equippedCount < 4) return; - destroyableComponent->Imagine(1); - break; - } - case ItemSetPassiveAbilityID::ShinobiRank2: { - if (equippedCount < 4) return; - destroyableComponent->Imagine(2); - break; - } - case ItemSetPassiveAbilityID::ShinobiRank3: { - if (equippedCount < 4) return; - destroyableComponent->Imagine(3); - break; - } + // Paradox + case ItemSetPassiveAbilityID::SpaceMarauderRank1: { + if (equippedCount < 4) return; + destroyableComponent->Imagine(1); + break; + } + case ItemSetPassiveAbilityID::SpaceMarauderRank2: { + if (equippedCount < 4) return; + destroyableComponent->Imagine(2); + break; + } + case ItemSetPassiveAbilityID::SpaceMarauderRank3: { + if (equippedCount < 4) return; + destroyableComponent->Imagine(3); + break; + } - case ItemSetPassiveAbilityID::SorcererRank1: { - if (equippedCount < 4) return; - destroyableComponent->Imagine(1); - break; - } - case ItemSetPassiveAbilityID::SorcererRank2: { - if (equippedCount < 4) return; - destroyableComponent->Imagine(2); - break; - } - case ItemSetPassiveAbilityID::SorcererRank3: { - if (equippedCount < 4) return; - destroyableComponent->Imagine(3); - break; - } + case ItemSetPassiveAbilityID::ShinobiRank1: { + if (equippedCount < 4) return; + destroyableComponent->Imagine(1); + break; + } + case ItemSetPassiveAbilityID::ShinobiRank2: { + if (equippedCount < 4) return; + destroyableComponent->Imagine(2); + break; + } + case ItemSetPassiveAbilityID::ShinobiRank3: { + if (equippedCount < 4) return; + destroyableComponent->Imagine(3); + break; + } - default: - break; - } + case ItemSetPassiveAbilityID::SorcererRank1: { + if (equippedCount < 4) return; + destroyableComponent->Imagine(1); + break; + } + case ItemSetPassiveAbilityID::SorcererRank2: { + if (equippedCount < 4) return; + destroyableComponent->Imagine(2); + break; + } + case ItemSetPassiveAbilityID::SorcererRank3: { + if (equippedCount < 4) return; + destroyableComponent->Imagine(3); + break; + } + + default: + break; + } } diff --git a/dGame/dInventory/ItemSetPassiveAbility.h b/dGame/dInventory/ItemSetPassiveAbility.h index 151ce341..ff945df2 100644 --- a/dGame/dInventory/ItemSetPassiveAbility.h +++ b/dGame/dInventory/ItemSetPassiveAbility.h @@ -9,11 +9,11 @@ class ItemSet; enum class PassiveAbilityTrigger { - AssemblyImagination, // Less than 1 imagination - ParadoxHealth, // Less or equal to 1 health - SentinelArmor, // Less than 1 armor - VentureHealth, // Less than 3 health - EnemySmashed, // Enemy is smashed + AssemblyImagination, // Less than 1 imagination + ParadoxHealth, // Less or equal to 1 health + SentinelArmor, // Less than 1 armor + VentureHealth, // Less than 3 health + EnemySmashed, // Enemy is smashed }; /** @@ -22,50 +22,50 @@ enum class PassiveAbilityTrigger class ItemSetPassiveAbility { public: - ItemSetPassiveAbility(PassiveAbilityTrigger trigger, Entity* parent, ItemSet* itemSet); - ~ItemSetPassiveAbility(); - void Update(float deltaTime); + ItemSetPassiveAbility(PassiveAbilityTrigger trigger, Entity* parent, ItemSet* itemSet); + ~ItemSetPassiveAbility(); + void Update(float deltaTime); - /** - * Attempts to trigger a passive ability for this item set, if this is the wrong trigger this is a no-op - * @param trigger the trigger to attempt to fire - */ - void Trigger(PassiveAbilityTrigger trigger); + /** + * Attempts to trigger a passive ability for this item set, if this is the wrong trigger this is a no-op + * @param trigger the trigger to attempt to fire + */ + void Trigger(PassiveAbilityTrigger trigger); - /** - * Activates the passive ability - */ - void Activate(); + /** + * Activates the passive ability + */ + void Activate(); - /** - * Finds all the passive abilities associated with a certain item set - * @param itemSetID the item set to find abilities for - * @param parent the parent to add to the passive abilities - * @param itemSet the item set to add to the passive abilities - * @return the passive abilities for the provided item set - */ - static std::vector FindAbilities(uint32_t itemSetID, Entity* parent, ItemSet* itemSet); + /** + * Finds all the passive abilities associated with a certain item set + * @param itemSetID the item set to find abilities for + * @param parent the parent to add to the passive abilities + * @param itemSet the item set to add to the passive abilities + * @return the passive abilities for the provided item set + */ + static std::vector FindAbilities(uint32_t itemSetID, Entity* parent, ItemSet* itemSet); private: - void OnEnemySmshed(); + void OnEnemySmshed(); - /** - * The means of triggering this ability - */ - PassiveAbilityTrigger m_Trigger; + /** + * The means of triggering this ability + */ + PassiveAbilityTrigger m_Trigger; - /** - * The owner of this ability - */ - Entity* m_Parent; + /** + * The owner of this ability + */ + Entity* m_Parent; - /** - * The item set this ability belongs to - */ - ItemSet* m_ItemSet; + /** + * The item set this ability belongs to + */ + ItemSet* m_ItemSet; - /** - * The cooldown on this ability until it can be activated again - */ - float m_Cooldown; + /** + * The cooldown on this ability until it can be activated again + */ + float m_Cooldown; }; diff --git a/dGame/dInventory/ItemSetPassiveAbilityID.h b/dGame/dInventory/ItemSetPassiveAbilityID.h index 12ba8409..92caea19 100644 --- a/dGame/dInventory/ItemSetPassiveAbilityID.h +++ b/dGame/dInventory/ItemSetPassiveAbilityID.h @@ -49,57 +49,57 @@ 49 [Unnamed] Item Set 50 Fire Spinjitzu Item Set 51 Ice Spinjitzu Item Set -52 Lightning Spinjitzu Item Set +52 Lightning Spinjitzu Item Set */ enum class ItemSetPassiveAbilityID { - EngineerRank1 = 2, - EngineerRank2 = 3, - EngineerRank3 = 4, - KnightRank1 = 7, - KnightRank2 = 8, - KnightRank3 = 9, - SpaceRangerRank1 = 10, - SpaceRangerRank2 = 11, - SpaceRangerRank3 = 12, - SamuraiRank1 = 13, - SamuraiRank2 = 14, - SamuraiRank3 = 15, - SorcererRank1 = 16, - SorcererRank2 = 17, - SorcererRank3 = 18, - SpaceMarauderRank1 = 19, - SpaceMarauderRank2 = 20, - SpaceMarauderRank3 = 21, - ShinobiRank1 = 22, - ShinobiRank2 = 23, - ShinobiRank3 = 24, - InventorRank1 = 25, - InventorRank2 = 26, - InventorRank3 = 27, - SummonerRank1 = 28, - SummonerRank2 = 29, - SummonerRank3 = 30, - AdventurerRank1 = 31, - AdventurerRank2 = 32, - AdventurerRank3 = 33, - DaredevilRank1 = 34, - DaredevilRank2 = 35, - DaredevilRank3 = 36, - BuccaneerRank1 = 37, - BuccaneerRank2 = 38, - BuccaneerRank3 = 39, - BoneSuit = 40, - ImaginationSpinjitzu = 41, - BatLord = 42, - MosaicJester = 43, - ExplorienBot = 44, - Unnamed1 = 45, - Unnamed2 = 46, - Unnamed3 = 47, - EarthSpinjitzu = 48, - Unnamed4 = 49, - FireSpinjitzu = 50, - IceSpinjitzu = 51, - LightningSpinjitzu = 52 + EngineerRank1 = 2, + EngineerRank2 = 3, + EngineerRank3 = 4, + KnightRank1 = 7, + KnightRank2 = 8, + KnightRank3 = 9, + SpaceRangerRank1 = 10, + SpaceRangerRank2 = 11, + SpaceRangerRank3 = 12, + SamuraiRank1 = 13, + SamuraiRank2 = 14, + SamuraiRank3 = 15, + SorcererRank1 = 16, + SorcererRank2 = 17, + SorcererRank3 = 18, + SpaceMarauderRank1 = 19, + SpaceMarauderRank2 = 20, + SpaceMarauderRank3 = 21, + ShinobiRank1 = 22, + ShinobiRank2 = 23, + ShinobiRank3 = 24, + InventorRank1 = 25, + InventorRank2 = 26, + InventorRank3 = 27, + SummonerRank1 = 28, + SummonerRank2 = 29, + SummonerRank3 = 30, + AdventurerRank1 = 31, + AdventurerRank2 = 32, + AdventurerRank3 = 33, + DaredevilRank1 = 34, + DaredevilRank2 = 35, + DaredevilRank3 = 36, + BuccaneerRank1 = 37, + BuccaneerRank2 = 38, + BuccaneerRank3 = 39, + BoneSuit = 40, + ImaginationSpinjitzu = 41, + BatLord = 42, + MosaicJester = 43, + ExplorienBot = 44, + Unnamed1 = 45, + Unnamed2 = 46, + Unnamed3 = 47, + EarthSpinjitzu = 48, + Unnamed4 = 49, + FireSpinjitzu = 50, + IceSpinjitzu = 51, + LightningSpinjitzu = 52 }; diff --git a/dGame/dMission/Mission.cpp b/dGame/dMission/Mission.cpp index 4e7a5826..bb02c4c8 100644 --- a/dGame/dMission/Mission.cpp +++ b/dGame/dMission/Mission.cpp @@ -20,596 +20,596 @@ #include "Database.h" Mission::Mission(MissionComponent* missionComponent, const uint32_t missionId) { - m_MissionComponent = missionComponent; + m_MissionComponent = missionComponent; - m_Completions = 0; + m_Completions = 0; - m_Timestamp = 0; + m_Timestamp = 0; - m_Reward = 0; + m_Reward = 0; - m_State = MissionState::MISSION_STATE_UNKNOWN; + m_State = MissionState::MISSION_STATE_UNKNOWN; - auto* missionsTable = CDClientManager::Instance()->GetTable("Missions"); + auto* missionsTable = CDClientManager::Instance()->GetTable("Missions"); - info = missionsTable->GetPtrByMissionID(missionId); + info = missionsTable->GetPtrByMissionID(missionId); - if (info == &CDMissionsTable::Default) { - Game::logger->Log("Missions", "Failed to find mission (%i)!", missionId); + if (info == &CDMissionsTable::Default) { + Game::logger->Log("Missions", "Failed to find mission (%i)!", missionId); - return; - } + return; + } - auto* tasksTable = CDClientManager::Instance()->GetTable("MissionTasks"); + auto* tasksTable = CDClientManager::Instance()->GetTable("MissionTasks"); - auto tasks = tasksTable->GetByMissionID(missionId); + auto tasks = tasksTable->GetByMissionID(missionId); - for (auto i = 0U; i < tasks.size(); ++i) { - auto* info = tasks[i]; + for (auto i = 0U; i < tasks.size(); ++i) { + auto* info = tasks[i]; - auto* task = new MissionTask(this, info, i); + auto* task = new MissionTask(this, info, i); - m_Tasks.push_back(task); - } + m_Tasks.push_back(task); + } } void Mission::LoadFromXml(tinyxml2::XMLElement* element) { - // Start custom XML - if (element->Attribute("state") != nullptr) { - m_State = static_cast(std::stoul(element->Attribute("state"))); - } - // End custom XML + // Start custom XML + if (element->Attribute("state") != nullptr) { + m_State = static_cast(std::stoul(element->Attribute("state"))); + } + // End custom XML - if (element->Attribute("cct") != nullptr) { - m_Completions = std::stoul(element->Attribute("cct")); + if (element->Attribute("cct") != nullptr) { + m_Completions = std::stoul(element->Attribute("cct")); - m_Timestamp = std::stoul(element->Attribute("cts")); + m_Timestamp = std::stoul(element->Attribute("cts")); - if (IsComplete()) { - return; - } - } + if (IsComplete()) { + return; + } + } - auto* task = element->FirstChildElement(); + auto* task = element->FirstChildElement(); - auto index = 0U; + auto index = 0U; - while (task != nullptr) { - if (index >= m_Tasks.size()) { - break; - } + while (task != nullptr) { + if (index >= m_Tasks.size()) { + break; + } - const auto type = m_Tasks[index]->GetType(); + const auto type = m_Tasks[index]->GetType(); - if (type == MissionTaskType::MISSION_TASK_TYPE_ENVIRONMENT || - type == MissionTaskType::MISSION_TASK_TYPE_VISIT_PROPERTY) { - std::vector uniques; + if (type == MissionTaskType::MISSION_TASK_TYPE_ENVIRONMENT || + type == MissionTaskType::MISSION_TASK_TYPE_VISIT_PROPERTY) { + std::vector uniques; - const auto value = std::stoul(task->Attribute("v")); + const auto value = std::stoul(task->Attribute("v")); - m_Tasks[index]->SetProgress(value, false); + m_Tasks[index]->SetProgress(value, false); - task = task->NextSiblingElement(); + task = task->NextSiblingElement(); - while (task != nullptr) { - const auto unique = std::stoul(task->Attribute("v")); + while (task != nullptr) { + const auto unique = std::stoul(task->Attribute("v")); - uniques.push_back(unique); + uniques.push_back(unique); - if (m_MissionComponent != nullptr && type == MissionTaskType::MISSION_TASK_TYPE_ENVIRONMENT) { - m_MissionComponent->AddCollectible(unique); - } + if (m_MissionComponent != nullptr && type == MissionTaskType::MISSION_TASK_TYPE_ENVIRONMENT) { + m_MissionComponent->AddCollectible(unique); + } - task = task->NextSiblingElement(); - } + task = task->NextSiblingElement(); + } - m_Tasks[index]->SetUnique(uniques); + m_Tasks[index]->SetUnique(uniques); - m_Tasks[index]->SetProgress(uniques.size(), false); + m_Tasks[index]->SetProgress(uniques.size(), false); - break; - } else { - const auto value = std::stoul(task->Attribute("v")); + break; + } else { + const auto value = std::stoul(task->Attribute("v")); - m_Tasks[index]->SetProgress(value, false); + m_Tasks[index]->SetProgress(value, false); - task = task->NextSiblingElement(); - } + task = task->NextSiblingElement(); + } - index++; - } + index++; + } } void Mission::UpdateXml(tinyxml2::XMLElement* element) { - // Start custom XML - element->SetAttribute("state", static_cast(m_State)); - // End custom XML + // Start custom XML + element->SetAttribute("state", static_cast(m_State)); + // End custom XML - element->DeleteChildren(); + element->DeleteChildren(); - element->SetAttribute("id", static_cast(info->id)); + element->SetAttribute("id", static_cast(info->id)); - if (m_Completions > 0) { - element->SetAttribute("cct", static_cast(m_Completions)); + if (m_Completions > 0) { + element->SetAttribute("cct", static_cast(m_Completions)); - element->SetAttribute("cts", static_cast(m_Timestamp)); + element->SetAttribute("cts", static_cast(m_Timestamp)); - if (IsComplete()) { - return; - } - } + if (IsComplete()) { + return; + } + } - for (auto* task : m_Tasks) { - if (task->GetType() == MissionTaskType::MISSION_TASK_TYPE_ENVIRONMENT || - task->GetType() == MissionTaskType::MISSION_TASK_TYPE_VISIT_PROPERTY) { + for (auto* task : m_Tasks) { + if (task->GetType() == MissionTaskType::MISSION_TASK_TYPE_ENVIRONMENT || + task->GetType() == MissionTaskType::MISSION_TASK_TYPE_VISIT_PROPERTY) { - auto* child = element->GetDocument()->NewElement("sv"); + auto* child = element->GetDocument()->NewElement("sv"); - child->SetAttribute("v", static_cast(task->GetProgress())); + child->SetAttribute("v", static_cast(task->GetProgress())); - element->LinkEndChild(child); + element->LinkEndChild(child); - for (auto unique : task->GetUnique()) { - auto* uniqueElement = element->GetDocument()->NewElement("sv"); + for (auto unique : task->GetUnique()) { + auto* uniqueElement = element->GetDocument()->NewElement("sv"); - uniqueElement->SetAttribute("v", static_cast(unique)); + uniqueElement->SetAttribute("v", static_cast(unique)); - element->LinkEndChild(uniqueElement); - } + element->LinkEndChild(uniqueElement); + } - break; - } - auto* child = element->GetDocument()->NewElement("sv"); + break; + } + auto* child = element->GetDocument()->NewElement("sv"); - child->SetAttribute("v", static_cast(task->GetProgress())); + child->SetAttribute("v", static_cast(task->GetProgress())); - element->LinkEndChild(child); - } + element->LinkEndChild(child); + } } bool Mission::IsValidMission(const uint32_t missionId) { - auto* table = CDClientManager::Instance()->GetTable("Missions"); + auto* table = CDClientManager::Instance()->GetTable("Missions"); - const auto missions = table->Query([=](const CDMissions& entry) { - return entry.id == static_cast(missionId); - }); + const auto missions = table->Query([=](const CDMissions& entry) { + return entry.id == static_cast(missionId); + }); - return !missions.empty(); + return !missions.empty(); } bool Mission::IsValidMission(const uint32_t missionId, CDMissions& info) { - auto* table = CDClientManager::Instance()->GetTable("Missions"); + auto* table = CDClientManager::Instance()->GetTable("Missions"); - const auto missions = table->Query([=](const CDMissions& entry) { - return entry.id == static_cast(missionId); - }); + const auto missions = table->Query([=](const CDMissions& entry) { + return entry.id == static_cast(missionId); + }); - if (missions.empty()) { - return false; - } + if (missions.empty()) { + return false; + } - info = missions[0]; + info = missions[0]; - return true; + return true; } Entity* Mission::GetAssociate() const { - return m_MissionComponent->GetParent(); + return m_MissionComponent->GetParent(); } User* Mission::GetUser() const { - return GetAssociate()->GetParentUser(); + return GetAssociate()->GetParentUser(); } uint32_t Mission::GetMissionId() const { - return info->id; + return info->id; } const CDMissions& Mission::GetClientInfo() const { - return *info; + return *info; } uint32_t Mission::GetCompletions() const { - return m_Completions; + return m_Completions; } uint32_t Mission::GetTimestamp() const { - return m_Timestamp; + return m_Timestamp; } LOT Mission::GetReward() const { - return m_Reward; + return m_Reward; } std::vector Mission::GetTasks() const { - return m_Tasks; + return m_Tasks; } MissionState Mission::GetMissionState() const { - return m_State; + return m_State; } bool Mission::IsAchievement() const { - return !info->isMission; + return !info->isMission; } bool Mission::IsMission() const { - return info->isMission; + return info->isMission; } bool Mission::IsRepeatable() const { - return info->repeatable; + return info->repeatable; } bool Mission::IsComplete() const { - return m_State == MissionState::MISSION_STATE_COMPLETE; + return m_State == MissionState::MISSION_STATE_COMPLETE; } bool Mission::IsActive() const { - return m_State == MissionState::MISSION_STATE_ACTIVE || m_State == MissionState::MISSION_STATE_COMPLETE_AVAILABLE; + return m_State == MissionState::MISSION_STATE_ACTIVE || m_State == MissionState::MISSION_STATE_COMPLETE_AVAILABLE; } void Mission::MakeActive() { - SetMissionState(m_Completions == 0 ? MissionState::MISSION_STATE_ACTIVE : MissionState::MISSION_STATE_COMPLETE_ACTIVE); + SetMissionState(m_Completions == 0 ? MissionState::MISSION_STATE_ACTIVE : MissionState::MISSION_STATE_COMPLETE_ACTIVE); } bool Mission::IsReadyToComplete() const { - return m_State == MissionState::MISSION_STATE_READY_TO_COMPLETE || m_State == MissionState::MISSION_STATE_COMPLETE_READY_TO_COMPLETE; + return m_State == MissionState::MISSION_STATE_READY_TO_COMPLETE || m_State == MissionState::MISSION_STATE_COMPLETE_READY_TO_COMPLETE; } void Mission::MakeReadyToComplete() { - SetMissionState(m_Completions == 0 ? MissionState::MISSION_STATE_READY_TO_COMPLETE : MissionState::MISSION_STATE_COMPLETE_READY_TO_COMPLETE); + SetMissionState(m_Completions == 0 ? MissionState::MISSION_STATE_READY_TO_COMPLETE : MissionState::MISSION_STATE_COMPLETE_READY_TO_COMPLETE); } bool Mission::IsAvalible() const { - return m_State == MissionState::MISSION_STATE_AVAILABLE || m_State == MissionState::MISSION_STATE_COMPLETE_AVAILABLE; + return m_State == MissionState::MISSION_STATE_AVAILABLE || m_State == MissionState::MISSION_STATE_COMPLETE_AVAILABLE; } bool Mission::IsFetchMission() const { - return m_Tasks.size() == 1 && m_Tasks[0]->GetType() == MissionTaskType::MISSION_TASK_TYPE_MISSION_INTERACTION; + return m_Tasks.size() == 1 && m_Tasks[0]->GetType() == MissionTaskType::MISSION_TASK_TYPE_MISSION_INTERACTION; } void Mission::MakeAvalible() { - SetMissionState(m_Completions == 0 ? MissionState::MISSION_STATE_AVAILABLE : MissionState::MISSION_STATE_COMPLETE_AVAILABLE); + SetMissionState(m_Completions == 0 ? MissionState::MISSION_STATE_AVAILABLE : MissionState::MISSION_STATE_COMPLETE_AVAILABLE); } void Mission::Accept() { - SetMissionTypeState(MissionLockState::MISSION_LOCK_NEW, info->defined_type, info->defined_subtype); + SetMissionTypeState(MissionLockState::MISSION_LOCK_NEW, info->defined_type, info->defined_subtype); - SetMissionState(m_Completions > 0 ? MissionState::MISSION_STATE_COMPLETE_ACTIVE : MissionState::MISSION_STATE_ACTIVE); + SetMissionState(m_Completions > 0 ? MissionState::MISSION_STATE_COMPLETE_ACTIVE : MissionState::MISSION_STATE_ACTIVE); - Catchup(); + Catchup(); } void Mission::Complete(const bool yieldRewards) { - if (m_State != MissionState::MISSION_STATE_ACTIVE && m_State != MissionState::MISSION_STATE_COMPLETE_ACTIVE) { - Accept(); - } + if (m_State != MissionState::MISSION_STATE_ACTIVE && m_State != MissionState::MISSION_STATE_COMPLETE_ACTIVE) { + Accept(); + } - for (auto* task : m_Tasks) { - task->Complete(); - } + for (auto* task : m_Tasks) { + task->Complete(); + } - SetMissionState(MissionState::MISSION_STATE_REWARDING, true); + SetMissionState(MissionState::MISSION_STATE_REWARDING, true); - if (yieldRewards) { - YieldRewards(); - } + if (yieldRewards) { + YieldRewards(); + } - SetMissionState(MissionState::MISSION_STATE_COMPLETE); + SetMissionState(MissionState::MISSION_STATE_COMPLETE); - m_Completions++; + m_Completions++; - m_Timestamp = std::time(nullptr); + m_Timestamp = std::time(nullptr); - auto* entity = GetAssociate(); + auto* entity = GetAssociate(); - if (entity == nullptr) { - return; - } + if (entity == nullptr) { + return; + } - auto* characterComponent = entity->GetComponent(); - if (characterComponent != nullptr) { - characterComponent->TrackMissionCompletion(!info->isMission); - } + auto* characterComponent = entity->GetComponent(); + if (characterComponent != nullptr) { + characterComponent->TrackMissionCompletion(!info->isMission); + } - auto* missionComponent = entity->GetComponent(); + auto* missionComponent = entity->GetComponent(); - missionComponent->Progress(MissionTaskType::MISSION_TASK_TYPE_MISSION_COMPLETE, info->id); + missionComponent->Progress(MissionTaskType::MISSION_TASK_TYPE_MISSION_COMPLETE, info->id); - missionComponent->Progress(MissionTaskType::MISSION_TASK_TYPE_RACING, info->id, (LWOOBJID)RacingTaskParam::RACING_TASK_PARAM_COMPLETE_ANY_RACING_TASK); + missionComponent->Progress(MissionTaskType::MISSION_TASK_TYPE_RACING, info->id, (LWOOBJID)RacingTaskParam::RACING_TASK_PARAM_COMPLETE_ANY_RACING_TASK); - missionComponent->Progress(MissionTaskType::MISSION_TASK_TYPE_RACING, info->id, (LWOOBJID)RacingTaskParam::RACING_TASK_PARAM_COMPLETE_TRACK_TASKS); + missionComponent->Progress(MissionTaskType::MISSION_TASK_TYPE_RACING, info->id, (LWOOBJID)RacingTaskParam::RACING_TASK_PARAM_COMPLETE_TRACK_TASKS); - auto* missionEmailTable = CDClientManager::Instance()->GetTable("MissionEmail"); + auto* missionEmailTable = CDClientManager::Instance()->GetTable("MissionEmail"); - const auto missionId = GetMissionId(); + const auto missionId = GetMissionId(); - const auto missionEmails = missionEmailTable->Query([missionId](const CDMissionEmail& entry) { - return entry.missionID == missionId; - }); + const auto missionEmails = missionEmailTable->Query([missionId](const CDMissionEmail& entry) { + return entry.missionID == missionId; + }); - for (const auto& email : missionEmails) { - const auto missionEmailBase = "MissionEmail_" + std::to_string(email.ID) + "_"; + for (const auto& email : missionEmails) { + const auto missionEmailBase = "MissionEmail_" + std::to_string(email.ID) + "_"; - const auto senderLocale = missionEmailBase + "senderName"; - const auto announceLocale = missionEmailBase + "announceText"; + const auto senderLocale = missionEmailBase + "senderName"; + const auto announceLocale = missionEmailBase + "announceText"; - if (email.messageType == 1 && Game::locale->HasPhrase(senderLocale)) { - const auto subject = dLocale::GetTemplate(missionEmailBase + "subjectText"); - const auto body = dLocale::GetTemplate(missionEmailBase + "bodyText"); - const auto sender = dLocale::GetTemplate(senderLocale); + if (email.messageType == 1 && Game::locale->HasPhrase(senderLocale)) { + const auto subject = dLocale::GetTemplate(missionEmailBase + "subjectText"); + const auto body = dLocale::GetTemplate(missionEmailBase + "bodyText"); + const auto sender = dLocale::GetTemplate(senderLocale); - Mail::SendMail(LWOOBJID_EMPTY, sender, GetAssociate(), subject, body, email.attachmentLOT, 1); - } - } + Mail::SendMail(LWOOBJID_EMPTY, sender, GetAssociate(), subject, body, email.attachmentLOT, 1); + } + } } void Mission::CheckCompletion() { - for (auto* task : m_Tasks) { - if (!task->IsComplete()) { - return; - } - } + for (auto* task : m_Tasks) { + if (!task->IsComplete()) { + return; + } + } - if (IsAchievement()) { - Complete(); + if (IsAchievement()) { + Complete(); - return; - } + return; + } - MakeReadyToComplete(); + MakeReadyToComplete(); } void Mission::Catchup() { - auto* entity = GetAssociate(); + auto* entity = GetAssociate(); - auto* inventory = static_cast(entity->GetComponent(COMPONENT_TYPE_INVENTORY)); + auto* inventory = static_cast(entity->GetComponent(COMPONENT_TYPE_INVENTORY)); - for (auto* task : m_Tasks) { - const auto type = task->GetType(); + for (auto* task : m_Tasks) { + const auto type = task->GetType(); - if (type == MissionTaskType::MISSION_TASK_TYPE_ITEM_COLLECTION) { - for (auto target : task->GetAllTargets()) { - const auto count = inventory->GetLotCountNonTransfer(target); + if (type == MissionTaskType::MISSION_TASK_TYPE_ITEM_COLLECTION) { + for (auto target : task->GetAllTargets()) { + const auto count = inventory->GetLotCountNonTransfer(target); - for (auto i = 0U; i < count; ++i) { - task->Progress(target); - } - } - } + for (auto i = 0U; i < count; ++i) { + task->Progress(target); + } + } + } - if (type == MissionTaskType::MISSION_TASK_TYPE_PLAYER_FLAG) { - for (auto target : task->GetAllTargets()) { - const auto flag = GetUser()->GetLastUsedChar()->GetPlayerFlag(target); + if (type == MissionTaskType::MISSION_TASK_TYPE_PLAYER_FLAG) { + for (auto target : task->GetAllTargets()) { + const auto flag = GetUser()->GetLastUsedChar()->GetPlayerFlag(target); - if (!flag) { - continue; - } + if (!flag) { + continue; + } - task->Progress(target); + task->Progress(target); - if (task->IsComplete()) { - break; - } - } - } - } + if (task->IsComplete()) { + break; + } + } + } + } } void Mission::YieldRewards() { - auto* entity = GetAssociate(); + auto* entity = GetAssociate(); - if (entity == nullptr) { - return; - } + if (entity == nullptr) { + return; + } - auto* character = GetUser()->GetLastUsedChar(); + auto* character = GetUser()->GetLastUsedChar(); - auto* inventoryComponent = entity->GetComponent(); - auto* levelComponent = entity->GetComponent(); - auto* characterComponent = entity->GetComponent(); - auto* destroyableComponent = entity->GetComponent(); - auto* missionComponent = entity->GetComponent(); + auto* inventoryComponent = entity->GetComponent(); + auto* levelComponent = entity->GetComponent(); + auto* characterComponent = entity->GetComponent(); + auto* destroyableComponent = entity->GetComponent(); + auto* missionComponent = entity->GetComponent(); - // Remove mission items - for (auto* task : m_Tasks) { - if (task->GetType() != MissionTaskType::MISSION_TASK_TYPE_ITEM_COLLECTION) { - continue; - } + // Remove mission items + for (auto* task : m_Tasks) { + if (task->GetType() != MissionTaskType::MISSION_TASK_TYPE_ITEM_COLLECTION) { + continue; + } - const auto& param = task->GetParameters(); + const auto& param = task->GetParameters(); - if (param.empty() || (param[0] & 1) == 0) // Should items be removed? - { - for (const auto target : task->GetAllTargets()) { - // This is how live did it. ONLY remove item collection items from the items and hidden inventories and none of the others. - inventoryComponent->RemoveItem(target, task->GetClientInfo().targetValue, eInventoryType::ITEMS); - inventoryComponent->RemoveItem(target, task->GetClientInfo().targetValue, eInventoryType::HIDDEN); + if (param.empty() || (param[0] & 1) == 0) // Should items be removed? + { + for (const auto target : task->GetAllTargets()) { + // This is how live did it. ONLY remove item collection items from the items and hidden inventories and none of the others. + inventoryComponent->RemoveItem(target, task->GetClientInfo().targetValue, eInventoryType::ITEMS); + inventoryComponent->RemoveItem(target, task->GetClientInfo().targetValue, eInventoryType::HIDDEN); - missionComponent->Progress(MissionTaskType::MISSION_TASK_TYPE_ITEM_COLLECTION, target, LWOOBJID_EMPTY, "", -task->GetClientInfo().targetValue); - } - } - } + missionComponent->Progress(MissionTaskType::MISSION_TASK_TYPE_ITEM_COLLECTION, target, LWOOBJID_EMPTY, "", -task->GetClientInfo().targetValue); + } + } + } - int32_t coinsToSend = 0; - if (info->LegoScore > 0) { - eLootSourceType lootSource = info->isMission ? eLootSourceType::LOOT_SOURCE_MISSION : eLootSourceType::LOOT_SOURCE_ACHIEVEMENT; - if(levelComponent->GetLevel() >= dZoneManager::Instance()->GetMaxLevel()) { - // Since the character is at the level cap we reward them with coins instead of UScore. - coinsToSend += info->LegoScore * dZoneManager::Instance()->GetLevelCapCurrencyConversion(); - } else { - characterComponent->SetUScore(characterComponent->GetUScore() + info->LegoScore); - GameMessages::SendModifyLEGOScore(entity, entity->GetSystemAddress(), info->LegoScore, lootSource); - } - } + int32_t coinsToSend = 0; + if (info->LegoScore > 0) { + eLootSourceType lootSource = info->isMission ? eLootSourceType::LOOT_SOURCE_MISSION : eLootSourceType::LOOT_SOURCE_ACHIEVEMENT; + if (levelComponent->GetLevel() >= dZoneManager::Instance()->GetMaxLevel()) { + // Since the character is at the level cap we reward them with coins instead of UScore. + coinsToSend += info->LegoScore * dZoneManager::Instance()->GetLevelCapCurrencyConversion(); + } else { + characterComponent->SetUScore(characterComponent->GetUScore() + info->LegoScore); + GameMessages::SendModifyLEGOScore(entity, entity->GetSystemAddress(), info->LegoScore, lootSource); + } + } - if (m_Completions > 0) { - std::vector> items; + if (m_Completions > 0) { + std::vector> items; - items.emplace_back(info->reward_item1_repeatable, info->reward_item1_repeat_count); - items.emplace_back(info->reward_item2_repeatable, info->reward_item2_repeat_count); - items.emplace_back(info->reward_item3_repeatable, info->reward_item3_repeat_count); - items.emplace_back(info->reward_item4_repeatable, info->reward_item4_repeat_count); + items.emplace_back(info->reward_item1_repeatable, info->reward_item1_repeat_count); + items.emplace_back(info->reward_item2_repeatable, info->reward_item2_repeat_count); + items.emplace_back(info->reward_item3_repeatable, info->reward_item3_repeat_count); + items.emplace_back(info->reward_item4_repeatable, info->reward_item4_repeat_count); - for (const auto& pair : items) { - // Some missions reward zero of an item and so they must be allowed through this clause, - // hence pair.second < 0 instead of pair.second <= 0. - if (pair.second < 0 || (m_Reward > 0 && pair.first != m_Reward)) { - continue; - } + for (const auto& pair : items) { + // Some missions reward zero of an item and so they must be allowed through this clause, + // hence pair.second < 0 instead of pair.second <= 0. + if (pair.second < 0 || (m_Reward > 0 && pair.first != m_Reward)) { + continue; + } - // If a mission rewards zero of an item, make it reward 1. - auto count = pair.second > 0 ? pair.second : 1; + // If a mission rewards zero of an item, make it reward 1. + auto count = pair.second > 0 ? pair.second : 1; - // Sanity check, 6 is the max any mission yields - if (count > 6) { - count = 0; - } + // Sanity check, 6 is the max any mission yields + if (count > 6) { + count = 0; + } - inventoryComponent->AddItem(pair.first, count, IsMission() ? eLootSourceType::LOOT_SOURCE_MISSION : eLootSourceType::LOOT_SOURCE_ACHIEVEMENT); - } + inventoryComponent->AddItem(pair.first, count, IsMission() ? eLootSourceType::LOOT_SOURCE_MISSION : eLootSourceType::LOOT_SOURCE_ACHIEVEMENT); + } - if (info->reward_currency_repeatable > 0 || coinsToSend > 0) { - eLootSourceType lootSource = info->isMission ? eLootSourceType::LOOT_SOURCE_MISSION : eLootSourceType::LOOT_SOURCE_ACHIEVEMENT; - character->SetCoins(character->GetCoins() + info->reward_currency_repeatable + coinsToSend, lootSource); - } + if (info->reward_currency_repeatable > 0 || coinsToSend > 0) { + eLootSourceType lootSource = info->isMission ? eLootSourceType::LOOT_SOURCE_MISSION : eLootSourceType::LOOT_SOURCE_ACHIEVEMENT; + character->SetCoins(character->GetCoins() + info->reward_currency_repeatable + coinsToSend, lootSource); + } - return; - } + return; + } - std::vector> items; + std::vector> items; - items.emplace_back(info->reward_item1, info->reward_item1_count); - items.emplace_back(info->reward_item2, info->reward_item2_count); - items.emplace_back(info->reward_item3, info->reward_item3_count); - items.emplace_back(info->reward_item4, info->reward_item4_count); + items.emplace_back(info->reward_item1, info->reward_item1_count); + items.emplace_back(info->reward_item2, info->reward_item2_count); + items.emplace_back(info->reward_item3, info->reward_item3_count); + items.emplace_back(info->reward_item4, info->reward_item4_count); - for (const auto& pair : items) { - // Some missions reward zero of an item and so they must be allowed through this clause, - // hence pair.second < 0 instead of pair.second <= 0. - if (pair.second < 0 || (m_Reward > 0 && pair.first != m_Reward)) { - continue; - } + for (const auto& pair : items) { + // Some missions reward zero of an item and so they must be allowed through this clause, + // hence pair.second < 0 instead of pair.second <= 0. + if (pair.second < 0 || (m_Reward > 0 && pair.first != m_Reward)) { + continue; + } - // If a mission rewards zero of an item, make it reward 1. - auto count = pair.second > 0 ? pair.second : 1; + // If a mission rewards zero of an item, make it reward 1. + auto count = pair.second > 0 ? pair.second : 1; - // Sanity check, 6 is the max any mission yields - if (count > 6) { - count = 0; - } + // Sanity check, 6 is the max any mission yields + if (count > 6) { + count = 0; + } - inventoryComponent->AddItem(pair.first, count, IsMission() ? eLootSourceType::LOOT_SOURCE_MISSION : eLootSourceType::LOOT_SOURCE_ACHIEVEMENT); - } + inventoryComponent->AddItem(pair.first, count, IsMission() ? eLootSourceType::LOOT_SOURCE_MISSION : eLootSourceType::LOOT_SOURCE_ACHIEVEMENT); + } - if (info->reward_currency > 0 || coinsToSend > 0) { - eLootSourceType lootSource = info->isMission ? eLootSourceType::LOOT_SOURCE_MISSION : eLootSourceType::LOOT_SOURCE_ACHIEVEMENT; - character->SetCoins(character->GetCoins() + info->reward_currency + coinsToSend, lootSource); - } + if (info->reward_currency > 0 || coinsToSend > 0) { + eLootSourceType lootSource = info->isMission ? eLootSourceType::LOOT_SOURCE_MISSION : eLootSourceType::LOOT_SOURCE_ACHIEVEMENT; + character->SetCoins(character->GetCoins() + info->reward_currency + coinsToSend, lootSource); + } - if (info->reward_maxinventory > 0) { - auto* inventory = inventoryComponent->GetInventory(ITEMS); + if (info->reward_maxinventory > 0) { + auto* inventory = inventoryComponent->GetInventory(ITEMS); - inventory->SetSize(inventory->GetSize() + info->reward_maxinventory); - } + inventory->SetSize(inventory->GetSize() + info->reward_maxinventory); + } - if (info->reward_bankinventory > 0) { - auto* inventory = inventoryComponent->GetInventory(eInventoryType::VAULT_ITEMS); - auto modelInventory = inventoryComponent->GetInventory(eInventoryType::VAULT_MODELS); + if (info->reward_bankinventory > 0) { + auto* inventory = inventoryComponent->GetInventory(eInventoryType::VAULT_ITEMS); + auto modelInventory = inventoryComponent->GetInventory(eInventoryType::VAULT_MODELS); - inventory->SetSize(inventory->GetSize() + info->reward_bankinventory); - modelInventory->SetSize(modelInventory->GetSize() + info->reward_bankinventory); - } + inventory->SetSize(inventory->GetSize() + info->reward_bankinventory); + modelInventory->SetSize(modelInventory->GetSize() + info->reward_bankinventory); + } - if (info->reward_reputation > 0) { - missionComponent->Progress(MissionTaskType::MISSION_TASK_TYPE_EARN_REPUTATION, 0, 0L, "", info->reward_reputation); - auto character = entity->GetComponent(); - if (character) { - character->SetReputation(character->GetReputation() + info->reward_reputation); - GameMessages::SendUpdateReputation(entity->GetObjectID(), character->GetReputation(), entity->GetSystemAddress()); - } - } + if (info->reward_reputation > 0) { + missionComponent->Progress(MissionTaskType::MISSION_TASK_TYPE_EARN_REPUTATION, 0, 0L, "", info->reward_reputation); + auto character = entity->GetComponent(); + if (character) { + character->SetReputation(character->GetReputation() + info->reward_reputation); + GameMessages::SendUpdateReputation(entity->GetObjectID(), character->GetReputation(), entity->GetSystemAddress()); + } + } - if (info->reward_maxhealth > 0) { - destroyableComponent->SetMaxHealth(destroyableComponent->GetMaxHealth() + static_cast(info->reward_maxhealth), true); - } + if (info->reward_maxhealth > 0) { + destroyableComponent->SetMaxHealth(destroyableComponent->GetMaxHealth() + static_cast(info->reward_maxhealth), true); + } - if (info->reward_maximagination > 0) { - destroyableComponent->SetMaxImagination(destroyableComponent->GetMaxImagination() + static_cast(info->reward_maximagination), true); - } + if (info->reward_maximagination > 0) { + destroyableComponent->SetMaxImagination(destroyableComponent->GetMaxImagination() + static_cast(info->reward_maximagination), true); + } - EntityManager::Instance()->SerializeEntity(entity); + EntityManager::Instance()->SerializeEntity(entity); - if (info->reward_emote > 0) { - character->UnlockEmote(info->reward_emote); - } + if (info->reward_emote > 0) { + character->UnlockEmote(info->reward_emote); + } - if (info->reward_emote2 > 0) { - character->UnlockEmote(info->reward_emote2); - } + if (info->reward_emote2 > 0) { + character->UnlockEmote(info->reward_emote2); + } - if (info->reward_emote3 > 0) { - character->UnlockEmote(info->reward_emote3); - } + if (info->reward_emote3 > 0) { + character->UnlockEmote(info->reward_emote3); + } - if (info->reward_emote4 > 0) { - character->UnlockEmote(info->reward_emote4); - } + if (info->reward_emote4 > 0) { + character->UnlockEmote(info->reward_emote4); + } } void Mission::Progress(MissionTaskType type, int32_t value, LWOOBJID associate, const std::string& targets, int32_t count) { - const auto isRemoval = count < 0; + const auto isRemoval = count < 0; - if (isRemoval && (IsComplete() || IsAchievement())) { - return; - } + if (isRemoval && (IsComplete() || IsAchievement())) { + return; + } - for (auto* task : m_Tasks) { - if (task->IsComplete() && !isRemoval) { - continue; - } + for (auto* task : m_Tasks) { + if (task->IsComplete() && !isRemoval) { + continue; + } - if (task->GetType() != type) { - continue; - } + if (task->GetType() != type) { + continue; + } - if (isRemoval && !task->InAllTargets(value)) { - continue; - } + if (isRemoval && !task->InAllTargets(value)) { + continue; + } - task->Progress(value, associate, targets, count); - } + task->Progress(value, associate, targets, count); + } } void Mission::SetMissionState(const MissionState state, const bool sendingRewards) { - this->m_State = state; + this->m_State = state; - auto* entity = GetAssociate(); + auto* entity = GetAssociate(); - if (entity == nullptr) { - return; - } + if (entity == nullptr) { + return; + } - GameMessages::SendNotifyMission(entity, entity->GetParentUser()->GetSystemAddress(), info->id, static_cast(state), sendingRewards); + GameMessages::SendNotifyMission(entity, entity->GetParentUser()->GetSystemAddress(), info->id, static_cast(state), sendingRewards); } void Mission::SetMissionTypeState(MissionLockState state, const std::string& type, const std::string& subType) { - // TODO + // TODO } void Mission::SetCompletions(const uint32_t value) { - m_Completions = value; + m_Completions = value; } void Mission::SetReward(const LOT lot) { - m_Reward = lot; + m_Reward = lot; } Mission::~Mission() { - for (auto* task : m_Tasks) { - delete task; - } + for (auto* task : m_Tasks) { + delete task; + } - m_Tasks.clear(); -} \ No newline at end of file + m_Tasks.clear(); +} diff --git a/dGame/dMission/Mission.h b/dGame/dMission/Mission.h index 4fb6c60f..94920cba 100644 --- a/dGame/dMission/Mission.h +++ b/dGame/dMission/Mission.h @@ -22,244 +22,244 @@ class Mission final { public: Mission(MissionComponent* missionComponent, uint32_t missionId); - ~Mission(); + ~Mission(); - void LoadFromXml(tinyxml2::XMLElement* element); - void UpdateXml(tinyxml2::XMLElement* element); + void LoadFromXml(tinyxml2::XMLElement* element); + void UpdateXml(tinyxml2::XMLElement* element); - /** - * Returns the ID of this mission - * @return the ID of this mission - */ + /** + * Returns the ID of this mission + * @return the ID of this mission + */ uint32_t GetMissionId() const; - /** - * Returns the entity that is currently progressing this mission - * @return the entity that is currently progressing this mission - */ + /** + * Returns the entity that is currently progressing this mission + * @return the entity that is currently progressing this mission + */ Entity* GetAssociate() const; - /** - * Returns the account owns the entity that is currently progressing this mission - * @return the account owns the entity that is currently progressing this mission - */ + /** + * Returns the account owns the entity that is currently progressing this mission + * @return the account owns the entity that is currently progressing this mission + */ User* GetUser() const; - /** - * Returns the current state of this mission - * @return the current state of this mission - */ + /** + * Returns the current state of this mission + * @return the current state of this mission + */ MissionState GetMissionState() const; - /** - * Returns the database information that represents to this mission. - * @return the database information that represents to this mission. - */ + /** + * Returns the database information that represents to this mission. + * @return the database information that represents to this mission. + */ const CDMissions& GetClientInfo() const; - /** - * Returns the number of times the entity has completed this mission, can only be > 0 for dailies. - * @return the number of thimes the entity has completed this mission - */ + /** + * Returns the number of times the entity has completed this mission, can only be > 0 for dailies. + * @return the number of thimes the entity has completed this mission + */ uint32_t GetCompletions() const; - /** - * Sets the number of times this mission has been completed - * @param value the number of times this mission should be completed - */ - void SetCompletions(uint32_t value); + /** + * Sets the number of times this mission has been completed + * @param value the number of times this mission should be completed + */ + void SetCompletions(uint32_t value); - /** - * Returns the last timestamp at which the entity completed this mission - * @return the last timestamp at which the entity completed this mission - */ + /** + * Returns the last timestamp at which the entity completed this mission + * @return the last timestamp at which the entity completed this mission + */ uint32_t GetTimestamp() const; - /** - * Returns some specific reward that should be returned from the possible rewards indicated by the client - * @return some specific reward that should be returned from the possible rewards indicated by the client - */ + /** + * Returns some specific reward that should be returned from the possible rewards indicated by the client + * @return some specific reward that should be returned from the possible rewards indicated by the client + */ LOT GetReward() const; - /** - * Sets an some specific reward that should be returned from the possible rewards indicated by the client - * @param lot the reward to set - */ - void SetReward(LOT lot); + /** + * Sets an some specific reward that should be returned from the possible rewards indicated by the client + * @param lot the reward to set + */ + void SetReward(LOT lot); - /** - * Returns all the tasks that must be completed to mark this mission as complete - * @return all the tasks that must be completed to mark this mission as complete - */ + /** + * Returns all the tasks that must be completed to mark this mission as complete + * @return all the tasks that must be completed to mark this mission as complete + */ std::vector GetTasks() const; - /** - * Updates the mission state to the one provided - * @param state the mission state to set - * @param sendingRewards a flag indicating to the client that rewards wil lfollow - */ + /** + * Updates the mission state to the one provided + * @param state the mission state to set + * @param sendingRewards a flag indicating to the client that rewards wil lfollow + */ void SetMissionState(MissionState state, bool sendingRewards = false); - /** - * Currently unimplemented - */ + /** + * Currently unimplemented + */ void SetMissionTypeState(MissionLockState state, const std::string& type, const std::string& subType); - /** - * Returns whether this mission is an achievement - * @return true if this mission is an achievement, false otherwise - */ + /** + * Returns whether this mission is an achievement + * @return true if this mission is an achievement, false otherwise + */ bool IsAchievement() const; - /** - * Returns whether this mission is a mission (e.g.: not an achievement) - * @return true if this mission is not an achievement, false otherwise - */ + /** + * Returns whether this mission is a mission (e.g.: not an achievement) + * @return true if this mission is not an achievement, false otherwise + */ bool IsMission() const; - /** - * Returns whether this mission can be repeated (mostly used for dailies) - * @return true if this mission can be repeated, false otherwise - */ + /** + * Returns whether this mission can be repeated (mostly used for dailies) + * @return true if this mission can be repeated, false otherwise + */ bool IsRepeatable() const; - /** - * Returns whether the entity has completed this mission before - * @return true if the mission has been completed before, false otherwise - */ + /** + * Returns whether the entity has completed this mission before + * @return true if the mission has been completed before, false otherwise + */ bool IsComplete() const; - /** - * Returns whether the mission is currently active - * @return true if the mission is currently active, false otherwise - */ + /** + * Returns whether the mission is currently active + * @return true if the mission is currently active, false otherwise + */ bool IsActive() const; - /** - * Sets the mission state to active, takes into account if this is a repeatable mission. - */ + /** + * Sets the mission state to active, takes into account if this is a repeatable mission. + */ void MakeActive(); - /** - * Returns whether the entity has completed all tasks and can hand the mission in for rewards. - * @return true if the entity can hand the mission in, false otherwise - */ + /** + * Returns whether the entity has completed all tasks and can hand the mission in for rewards. + * @return true if the entity can hand the mission in, false otherwise + */ bool IsReadyToComplete() const; - /** - * Sets the mission state to ready to complete, takes into account if this is a repeatable mission - */ + /** + * Sets the mission state to ready to complete, takes into account if this is a repeatable mission + */ void MakeReadyToComplete(); - /** - * Returns whether this mission can be accepted by the entity - * @return true if the mission can be accepted by the entity, false otherwise - */ + /** + * Returns whether this mission can be accepted by the entity + * @return true if the mission can be accepted by the entity, false otherwise + */ bool IsAvalible() const; - /** - * Sets the mission state to available, takes into account if this mission is repeatable - */ - void MakeAvalible(); + /** + * Sets the mission state to available, takes into account if this mission is repeatable + */ + void MakeAvalible(); - /** - * Returns whether this mission is one where an entity simply has to go somewhere, but doesn't have to turn in the - * mission tasks at the original mission giver (called a fetch mission). - * @return true if this is a fetch mission, false otherwise - */ + /** + * Returns whether this mission is one where an entity simply has to go somewhere, but doesn't have to turn in the + * mission tasks at the original mission giver (called a fetch mission). + * @return true if this is a fetch mission, false otherwise + */ bool IsFetchMission() const; - /** - * Accepts this mission, setting it to available. Also progresses any of the tasks if the entity has already - * progressed for them (for example "collect X bricks", will fast track for the amount of bricks the entity - * already has). - */ + /** + * Accepts this mission, setting it to available. Also progresses any of the tasks if the entity has already + * progressed for them (for example "collect X bricks", will fast track for the amount of bricks the entity + * already has). + */ void Accept(); - /** - * Completes the mission and handles all logistics regarding that: checking all tasks, handing out rewards, - * emailing them if the inventory is full, etc. If the mission tasks have not all been completed this is a no-op. - * @param yieldRewards if true, rewards will be given to the entity - */ + /** + * Completes the mission and handles all logistics regarding that: checking all tasks, handing out rewards, + * emailing them if the inventory is full, etc. If the mission tasks have not all been completed this is a no-op. + * @param yieldRewards if true, rewards will be given to the entity + */ void Complete(bool yieldRewards = true); - /** - * Checks if this mission is ready to be completed and updates the state if so. If this is an achievement, the - * state will automatically be updated to completed as there's nobody to hand achievements in to. - */ + /** + * Checks if this mission is ready to be completed and updates the state if so. If this is an achievement, the + * state will automatically be updated to completed as there's nobody to hand achievements in to. + */ void CheckCompletion(); - /** - * Gives all the rewards (items, score, stats, etc.) to the entity. Takes into account if the entity has completed - * the mission before. - */ + /** + * Gives all the rewards (items, score, stats, etc.) to the entity. Takes into account if the entity has completed + * the mission before. + */ void YieldRewards(); - /** - * Attempts to progress tasks of a certain type for this mission. Note that the interpretation of any of these - * arguments is up to the mission task at hand. - * @param type the mission task type to progress - * @param value the value to progress the mission task with - * @param associate optional object ID that was related to the progression - * @param targets optional multiple targets that need to be met for progression - * @param count optional count to progress with - */ + /** + * Attempts to progress tasks of a certain type for this mission. Note that the interpretation of any of these + * arguments is up to the mission task at hand. + * @param type the mission task type to progress + * @param value the value to progress the mission task with + * @param associate optional object ID that was related to the progression + * @param targets optional multiple targets that need to be met for progression + * @param count optional count to progress with + */ void Progress(MissionTaskType type, int32_t value, LWOOBJID associate = 0, const std::string& targets = "", int32_t count = 1); - /** - * Returns if the mission ID that's given belongs to an existing mission - * @param missionId the mission ID to check for - * @return true if the mission exists, false otherwise - */ + /** + * Returns if the mission ID that's given belongs to an existing mission + * @param missionId the mission ID to check for + * @return true if the mission exists, false otherwise + */ static bool IsValidMission(uint32_t missionId); - /** - * Returns if the mission ID that's given belongs to an existing mission - * @param missionId the mission ID to check for - * @param info variable to store the queried mission information in - * @return true if the mission exists, false otherwise - */ + /** + * Returns if the mission ID that's given belongs to an existing mission + * @param missionId the mission ID to check for + * @param info variable to store the queried mission information in + * @return true if the mission exists, false otherwise + */ static bool IsValidMission(uint32_t missionId, CDMissions& info); private: - /** - * Progresses all the newly accepted tasks for this mission after it has been accepted to reflect the state of the - * inventory of the entity. - */ + /** + * Progresses all the newly accepted tasks for this mission after it has been accepted to reflect the state of the + * inventory of the entity. + */ void Catchup(); - /** - * The database information that corresponds to this mission - */ + /** + * The database information that corresponds to this mission + */ const CDMissions* info; - /** - * The current state this mission is in - */ + /** + * The current state this mission is in + */ MissionState m_State; - /** - * The number of times the entity has completed this mission - */ + /** + * The number of times the entity has completed this mission + */ uint32_t m_Completions; - /** - * The last time the entity completed this mission - */ + /** + * The last time the entity completed this mission + */ uint32_t m_Timestamp; - /** - * The mission component of the entity that owns this mission - */ + /** + * The mission component of the entity that owns this mission + */ MissionComponent* m_MissionComponent; - /** - * Optionally specific reward that should be returned from the possible rewards indicated by the client - */ + /** + * Optionally specific reward that should be returned from the possible rewards indicated by the client + */ LOT m_Reward; - /** - * All the tasks that can be progressed for this mission - */ + /** + * All the tasks that can be progressed for this mission + */ std::vector m_Tasks; }; diff --git a/dGame/dMission/MissionPrerequisites.cpp b/dGame/dMission/MissionPrerequisites.cpp index 93d55437..3d4e6355 100644 --- a/dGame/dMission/MissionPrerequisites.cpp +++ b/dGame/dMission/MissionPrerequisites.cpp @@ -52,8 +52,7 @@ PrerequisiteExpression::PrerequisiteExpression(const std::string& str) { case '9': if (sub) { s << character; - } - else { + } else { a << character; } break; @@ -71,8 +70,7 @@ PrerequisiteExpression::PrerequisiteExpression(const std::string& str) { if (!aString.empty()) { this->a = std::stoul(a.str()); - } - else { + } else { this->a = 0; } @@ -80,8 +78,7 @@ PrerequisiteExpression::PrerequisiteExpression(const std::string& str) { if (!subString.empty()) { this->sub = std::stoul(s.str()); - } - else { + } else { this->sub = 0; } @@ -89,8 +86,7 @@ PrerequisiteExpression::PrerequisiteExpression(const std::string& str) { if (!bString.empty()) { this->b = new PrerequisiteExpression(bString); - } - else { + } else { this->b = nullptr; } } @@ -109,11 +105,10 @@ bool PrerequisiteExpression::Execute(const std::unordered_mapsub != 0) { // Special case for one Wisp Lee repeatable mission. - a = mission->GetClientInfo().id == 1883 ? - mission->GetMissionState() == static_cast(this->sub) : + a = mission->GetClientInfo().id == 1883 ? + mission->GetMissionState() == static_cast(this->sub) : mission->GetMissionState() >= static_cast(this->sub); - } - else if (mission->IsComplete()) { + } else if (mission->IsComplete()) { a = true; } } @@ -144,42 +139,42 @@ bool MissionPrerequisites::CanAccept(const uint32_t missionId, const std::unorde const auto& info = mission->GetClientInfo(); if (info.repeatable) { - const auto prerequisitesMet = CheckPrerequisites(missionId, missions); + const auto prerequisitesMet = CheckPrerequisites(missionId, missions); - // Checked by client + // Checked by client const time_t time = std::time(nullptr); const time_t lock = mission->GetTimestamp() + info.cooldownTime * 60; - // If there's no time limit, just check the prerequisites, otherwise make sure both conditions are met + // If there's no time limit, just check the prerequisites, otherwise make sure both conditions are met return (info.cooldownTime == -1 ? prerequisitesMet : (lock - time < 0)) && prerequisitesMet; } - // Mission is already accepted and cannot be repeatedly accepted + // Mission is already accepted and cannot be repeatedly accepted return false; } - // Mission is not yet accepted, check the prerequisites + // Mission is not yet accepted, check the prerequisites return CheckPrerequisites(missionId, missions); } bool MissionPrerequisites::CheckPrerequisites(uint32_t missionId, const std::unordered_map& missions) { - const auto& index = expressions.find(missionId); - if (index != expressions.end()) { - return index->second->Execute(missions); - } + const auto& index = expressions.find(missionId); + if (index != expressions.end()) { + return index->second->Execute(missions); + } - auto* missionsTable = CDClientManager::Instance()->GetTable("Missions"); - const auto missionEntries = missionsTable->Query([=](const CDMissions& entry) { - return entry.id == static_cast(missionId); - }); + auto* missionsTable = CDClientManager::Instance()->GetTable("Missions"); + const auto missionEntries = missionsTable->Query([=](const CDMissions& entry) { + return entry.id == static_cast(missionId); + }); - if (missionEntries.empty()) - return false; + if (missionEntries.empty()) + return false; - auto* expression = new PrerequisiteExpression(missionEntries[0].prereqMissionID); - expressions.insert_or_assign(missionId, expression); + auto* expression = new PrerequisiteExpression(missionEntries[0].prereqMissionID); + expressions.insert_or_assign(missionId, expression); - return expression->Execute(missions); + return expression->Execute(missions); } std::unordered_map MissionPrerequisites::expressions = {}; diff --git a/dGame/dMission/MissionPrerequisites.h b/dGame/dMission/MissionPrerequisites.h index f426e916..dd349cb1 100644 --- a/dGame/dMission/MissionPrerequisites.h +++ b/dGame/dMission/MissionPrerequisites.h @@ -16,11 +16,11 @@ class PrerequisiteExpression final PrerequisiteExpression* b; public: - /** - * Executes the prerequisite, checking its contents and returning whether or not the mission may be accepted - * @param missions the list of missions to check the prerequisites against (f.e. whether they're completed) - * @return whether or not all the prerequisites are met - */ + /** + * Executes the prerequisite, checking its contents and returning whether or not the mission may be accepted + * @param missions the list of missions to check the prerequisites against (f.e. whether they're completed) + * @return whether or not all the prerequisites are met + */ bool Execute(const std::unordered_map& missions) const; explicit PrerequisiteExpression(const std::string& str); @@ -33,26 +33,26 @@ public: class MissionPrerequisites final { public: - /** - * Checks whether or not the mission identified by the specified ID can be accepted based on the mission inventory passed. - * Also performs checks for daily missions (e.g. if the time out is valid). - * @param missionId the mission ID to check prerequisites for - * @param missions the mission inventory to check the prerequisites against - * @return whether or not the mission identified by the specified ID can be accepted - */ + /** + * Checks whether or not the mission identified by the specified ID can be accepted based on the mission inventory passed. + * Also performs checks for daily missions (e.g. if the time out is valid). + * @param missionId the mission ID to check prerequisites for + * @param missions the mission inventory to check the prerequisites against + * @return whether or not the mission identified by the specified ID can be accepted + */ static bool CanAccept(uint32_t missionId, const std::unordered_map& missions); private: - /** - * Cache of all the executed prerequisites - */ + /** + * Cache of all the executed prerequisites + */ static std::unordered_map expressions; - /** - * Checks the prerequisites for a mission - * @param missionId the mission ID to check prerequisites for - * @param missions the mission inventory to check the prerequisites against - * @return whether or not the mission identified by the specified ID can be accepted - */ - static bool CheckPrerequisites(uint32_t missionId, const std::unordered_map& missions); + /** + * Checks the prerequisites for a mission + * @param missionId the mission ID to check prerequisites for + * @param missions the mission inventory to check the prerequisites against + * @return whether or not the mission identified by the specified ID can be accepted + */ + static bool CheckPrerequisites(uint32_t missionId, const std::unordered_map& missions); }; diff --git a/dGame/dMission/MissionState.h b/dGame/dMission/MissionState.h index c189c708..5ee480da 100644 --- a/dGame/dMission/MissionState.h +++ b/dGame/dMission/MissionState.h @@ -7,50 +7,50 @@ * Represents the possible states a mission can be in */ enum class MissionState : int { - /** - * The mission state is unknown - */ - MISSION_STATE_UNKNOWN = -1, + /** + * The mission state is unknown + */ + MISSION_STATE_UNKNOWN = -1, - /** - * The mission is yielding rewards - */ - MISSION_STATE_REWARDING = 0, + /** + * The mission is yielding rewards + */ + MISSION_STATE_REWARDING = 0, - /** - * The mission can be accepted - */ - MISSION_STATE_AVAILABLE = 1, + /** + * The mission can be accepted + */ + MISSION_STATE_AVAILABLE = 1, - /** - * The mission has been accepted but not yet completed - */ - MISSION_STATE_ACTIVE = 2, + /** + * The mission has been accepted but not yet completed + */ + MISSION_STATE_ACTIVE = 2, - /** - * All the tasks for the mission have been completed and the entity can turn the mission in to complete it - */ - MISSION_STATE_READY_TO_COMPLETE = 4, //!< The mission is ready to complete + /** + * All the tasks for the mission have been completed and the entity can turn the mission in to complete it + */ + MISSION_STATE_READY_TO_COMPLETE = 4, //!< The mission is ready to complete - /** - * The mission has been completed - */ - MISSION_STATE_COMPLETE = 8, + /** + * The mission has been completed + */ + MISSION_STATE_COMPLETE = 8, - /** - * The mission is available again and has been completed before. Used for daily missions. - */ - MISSION_STATE_COMPLETE_AVAILABLE = 9, + /** + * The mission is available again and has been completed before. Used for daily missions. + */ + MISSION_STATE_COMPLETE_AVAILABLE = 9, - /** - * The mission is active and has been completed before. Used for daily missions. - */ - MISSION_STATE_COMPLETE_ACTIVE = 10, + /** + * The mission is active and has been completed before. Used for daily missions. + */ + MISSION_STATE_COMPLETE_ACTIVE = 10, - /** - * The mission has been completed before and has now been completed again. Used for daily missions. - */ - MISSION_STATE_COMPLETE_READY_TO_COMPLETE = 12 + /** + * The mission has been completed before and has now been completed again. Used for daily missions. + */ + MISSION_STATE_COMPLETE_READY_TO_COMPLETE = 12 }; #endif //!__MISSIONSTATE__H__ diff --git a/dGame/dMission/MissionTask.cpp b/dGame/dMission/MissionTask.cpp index 36051305..e08dc146 100644 --- a/dGame/dMission/MissionTask.cpp +++ b/dGame/dMission/MissionTask.cpp @@ -14,8 +14,7 @@ #include "MissionComponent.h" -MissionTask::MissionTask(Mission* mission, CDMissionTasks* info, uint32_t mask) -{ +MissionTask::MissionTask(Mission* mission, CDMissionTasks* info, uint32_t mask) { this->info = info; this->mission = mission; this->mask = mask; @@ -43,36 +42,30 @@ MissionTask::MissionTask(Mission* mission, CDMissionTasks* info, uint32_t mask) } -MissionTaskType MissionTask::GetType() const -{ +MissionTaskType MissionTask::GetType() const { return static_cast(info->taskType); } -uint32_t MissionTask::GetProgress() const -{ +uint32_t MissionTask::GetProgress() const { return progress; } -void MissionTask::SetProgress(const uint32_t value, const bool echo) -{ - if (progress == value) - { +void MissionTask::SetProgress(const uint32_t value, const bool echo) { + if (progress == value) { return; } progress = value; - if (!echo) - { + if (!echo) { return; } auto* entity = mission->GetAssociate(); - if (entity == nullptr) - { + if (entity == nullptr) { return; } @@ -82,23 +75,19 @@ void MissionTask::SetProgress(const uint32_t value, const bool echo) } -void MissionTask::SetUnique(const std::vector& value) -{ +void MissionTask::SetUnique(const std::vector& value) { unique = value; } -void MissionTask::AddProgress(int32_t value) -{ +void MissionTask::AddProgress(int32_t value) { value += progress; - if (value > info->targetValue) - { + if (value > info->targetValue) { value = info->targetValue; } - if (value < 0) - { + if (value < 0) { value = 0; } @@ -106,50 +95,42 @@ void MissionTask::AddProgress(int32_t value) } -Mission* MissionTask::GetMission() const -{ +Mission* MissionTask::GetMission() const { return mission; } -uint32_t MissionTask::GetTarget() const -{ +uint32_t MissionTask::GetTarget() const { return info->target; } -const CDMissionTasks& MissionTask::GetClientInfo() const -{ +const CDMissionTasks& MissionTask::GetClientInfo() const { return *info; } -uint32_t MissionTask::GetMask() const -{ +uint32_t MissionTask::GetMask() const { return mask; } -const std::vector& MissionTask::GetUnique() const -{ +const std::vector& MissionTask::GetUnique() const { return unique; } -const std::vector& MissionTask::GetTargets() const -{ +const std::vector& MissionTask::GetTargets() const { return targets; } -const std::vector& MissionTask::GetParameters() const -{ +const std::vector& MissionTask::GetParameters() const { return parameters; } -std::vector MissionTask::GetAllTargets() const -{ +std::vector MissionTask::GetAllTargets() const { auto targets = GetTargets(); targets.push_back(GetTarget()); @@ -158,83 +139,68 @@ std::vector MissionTask::GetAllTargets() const } -bool MissionTask::InTargets(const uint32_t value) const -{ +bool MissionTask::InTargets(const uint32_t value) const { auto targets = GetTargets(); return std::find(targets.begin(), targets.end(), value) != targets.end(); } -bool MissionTask::InAllTargets(const uint32_t value) const -{ +bool MissionTask::InAllTargets(const uint32_t value) const { auto targets = GetAllTargets(); return std::find(targets.begin(), targets.end(), value) != targets.end(); } -bool MissionTask::InParameters(const uint32_t value) const -{ +bool MissionTask::InParameters(const uint32_t value) const { auto parameters = GetParameters(); return std::find(parameters.begin(), parameters.end(), value) != parameters.end(); } -bool MissionTask::IsComplete() const -{ +bool MissionTask::IsComplete() const { // Mission 668 has task uid 984 which is a bit mask. Its completion value is 3. if (info->uid == 984) { return progress >= 3; - } - else { + } else { return progress >= info->targetValue; } } -void MissionTask::Complete() -{ +void MissionTask::Complete() { SetProgress(info->targetValue); } -void MissionTask::CheckCompletion() const -{ - if (IsComplete()) - { +void MissionTask::CheckCompletion() const { + if (IsComplete()) { mission->CheckCompletion(); } } -void MissionTask::Progress(int32_t value, LWOOBJID associate, const std::string& targets, int32_t count) -{ +void MissionTask::Progress(int32_t value, LWOOBJID associate, const std::string& targets, int32_t count) { if (IsComplete() && count > 0) return; const auto type = GetType(); - if (count < 0) - { - if (mission->IsMission() && type == MissionTaskType::MISSION_TASK_TYPE_ITEM_COLLECTION && InAllTargets(value)) - { - if (parameters.size() > 0 && (parameters[0] & 1) != 0) - { + if (count < 0) { + if (mission->IsMission() && type == MissionTaskType::MISSION_TASK_TYPE_ITEM_COLLECTION && InAllTargets(value)) { + if (parameters.size() > 0 && (parameters[0] & 1) != 0) { return; } auto* inventoryComponent = mission->GetAssociate()->GetComponent(); - if (inventoryComponent != nullptr) - { + if (inventoryComponent != nullptr) { int32_t itemCount = inventoryComponent->GetLotCountNonTransfer(value); - if (itemCount < info->targetValue) - { + if (itemCount < info->targetValue) { SetProgress(itemCount); - if (mission->IsReadyToComplete()) - { + if (mission->IsReadyToComplete()) { mission->MakeActive(); } } @@ -271,8 +237,7 @@ void MissionTask::Progress(int32_t value, LWOOBJID associate, const std::string& } activity = static_cast(entity->GetComponent(COMPONENT_TYPE_REBUILD)); - if (activity == nullptr) - { + if (activity == nullptr) { break; } @@ -280,8 +245,7 @@ void MissionTask::Progress(int32_t value, LWOOBJID associate, const std::string& const auto activityIdOverride = entity->GetVar(u"activityID"); - if (activityIdOverride != 0) - { + if (activityIdOverride != 0) { activityId = activityIdOverride; } @@ -308,8 +272,7 @@ void MissionTask::Progress(int32_t value, LWOOBJID associate, const std::string& entity = EntityManager::Instance()->GetEntity(associate); - if (entity == nullptr) - { + if (entity == nullptr) { Game::logger->Log("MissionTask", "Failed to find associated entity (%llu)!", associate); break; @@ -335,11 +298,11 @@ void MissionTask::Progress(int32_t value, LWOOBJID associate, const std::string& break; } - case MissionTaskType::MISSION_TASK_TYPE_MINIGAME: + case MissionTaskType::MISSION_TASK_TYPE_MINIGAME: { auto* minigameManager = EntityManager::Instance()->GetEntity(associate); if (minigameManager == nullptr) - break; + break; int32_t gameID = minigameManager->GetLOT(); @@ -353,11 +316,11 @@ void MissionTask::Progress(int32_t value, LWOOBJID associate, const std::string& } // This special case is for shooting gallery missions that want their // progress value set to 1 instead of being set to the target value. - if(info->targetGroup == targets && value >= info->targetValue && GetMission()->IsMission() && info->target == 1864 && info->targetGroup == "performact_score") { + if (info->targetGroup == targets && value >= info->targetValue && GetMission()->IsMission() && info->target == 1864 && info->targetGroup == "performact_score") { SetProgress(1); break; } - if(info->targetGroup == targets && value >= info->targetValue) { + if (info->targetGroup == targets && value >= info->targetValue) { SetProgress(info->targetValue); break; } @@ -383,8 +346,7 @@ void MissionTask::Progress(int32_t value, LWOOBJID associate, const std::string& entity = EntityManager::Instance()->GetEntity(associate); - if (entity == nullptr) - { + if (entity == nullptr) { Game::logger->Log("MissionTask", "Failed to find associated entity (%llu)!", associate); break; @@ -431,8 +393,7 @@ void MissionTask::Progress(int32_t value, LWOOBJID associate, const std::string& if (parameters[0] != associate) break; - if (associate == 1 || associate == 2 || associate == 3) - { + if (associate == 1 || associate == 2 || associate == 3) { if (value > info->targetValue) break; AddProgress(info->targetValue); @@ -447,26 +408,18 @@ void MissionTask::Progress(int32_t value, LWOOBJID associate, const std::string& // If we won at Gnarled Forest, set bit 1 else if (value == 1303) SetProgress(tempProgress |= 1 << 1); // If both bits are set, then the client sees the mission as complete. - } - else if (associate == 10) - { + } else if (associate == 10) { // If the player did not crash during the race, progress this task by count. if (value != 0) break; AddProgress(count); - } - else if (associate == 4 || associate == 5 || associate == 14) - { + } else if (associate == 4 || associate == 5 || associate == 14) { if (!InAllTargets(value)) break; AddProgress(count); - } - else if (associate == 17) - { + } else if (associate == 17) { if (!InAllTargets(value)) break; AddProgress(count); - } - else - { + } else { AddProgress(count); } @@ -503,8 +456,7 @@ void MissionTask::Progress(int32_t value, LWOOBJID associate, const std::string& } -MissionTask::~MissionTask() -{ +MissionTask::~MissionTask() { targets.clear(); parameters.clear(); diff --git a/dGame/dMission/MissionTask.h b/dGame/dMission/MissionTask.h index 3fcbbe3d..14d885c3 100644 --- a/dGame/dMission/MissionTask.h +++ b/dGame/dMission/MissionTask.h @@ -16,172 +16,172 @@ class MissionTask final { public: MissionTask(Mission* mission, CDMissionTasks* info, uint32_t mask); - ~MissionTask(); + ~MissionTask(); - /** - * Attempts to progress this task using the provided parameters. Note that the behavior of this method is different - * for each mission task type. - * @param value the value to progress by - * @param associate optional object ID of an entity that was related to the progression - * @param targets optional multiple targets that need to be met to progress - * @param count a number that indicates the times to progress - */ + /** + * Attempts to progress this task using the provided parameters. Note that the behavior of this method is different + * for each mission task type. + * @param value the value to progress by + * @param associate optional object ID of an entity that was related to the progression + * @param targets optional multiple targets that need to be met to progress + * @param count a number that indicates the times to progress + */ void Progress(int32_t value, LWOOBJID associate = 0, const std::string& targets = "", int32_t count = 1); - /** - * Returns the current progression of this task - * @return the current progression of this task - */ + /** + * Returns the current progression of this task + * @return the current progression of this task + */ uint32_t GetProgress() const; - /** - * Progresses the progress of this task by the provided value. Does not exceed the target progress. - * @param value the value to progress by - */ - void AddProgress(int32_t value); + /** + * Progresses the progress of this task by the provided value. Does not exceed the target progress. + * @param value the value to progress by + */ + void AddProgress(int32_t value); - /** - * Sets the progress of the task and optionally notifies the client - * @param value the value to set for the progress - * @param echo if true, this will notify the client of the change - */ - void SetProgress(uint32_t value, bool echo = true); + /** + * Sets the progress of the task and optionally notifies the client + * @param value the value to set for the progress + * @param echo if true, this will notify the client of the change + */ + void SetProgress(uint32_t value, bool echo = true); - /** - * Returns the mission this task belongs to - * @return the mission this task belongs to - */ + /** + * Returns the mission this task belongs to + * @return the mission this task belongs to + */ Mission* GetMission() const; - /** - * Returns the type of this task - * @return the type of this task - */ + /** + * Returns the type of this task + * @return the type of this task + */ MissionTaskType GetType() const; - /** - * Returns the value that should be progressed to, to complete the mission (the target value) - * @return the target value - */ + /** + * Returns the value that should be progressed to, to complete the mission (the target value) + * @return the target value + */ uint32_t GetTarget() const; - /** - * Returns the database information for this mission - * @return the database information for this mission - */ + /** + * Returns the database information for this mission + * @return the database information for this mission + */ const CDMissionTasks& GetClientInfo() const; - /** - * Returns the mask for this mission, used for communicating updates - * @return the mask for this mission, used for communicating updates - */ + /** + * Returns the mask for this mission, used for communicating updates + * @return the mask for this mission, used for communicating updates + */ uint32_t GetMask() const; - /** - * Returns the currently visited list of unique locations (only used for visiting mission types) - * @return the currently visited list of unique locations - */ + /** + * Returns the currently visited list of unique locations (only used for visiting mission types) + * @return the currently visited list of unique locations + */ const std::vector& GetUnique() const; - /** - * Sets the uniquely visited list of locations - * @param value the uniquely visited list of locations - */ - void SetUnique(const std::vector& value); + /** + * Sets the uniquely visited list of locations + * @param value the uniquely visited list of locations + */ + void SetUnique(const std::vector& value); - /** - * Returns the possibly target values for this mission task for progression - * @return the possibly target values for this mission task for progression - */ + /** + * Returns the possibly target values for this mission task for progression + * @return the possibly target values for this mission task for progression + */ const std::vector& GetTargets() const; - /** - * Returns the parameters for this task: meta information that determines if the task can be progressed. Note: - * not used by all task types. - * @return the parameters for this task - */ + /** + * Returns the parameters for this task: meta information that determines if the task can be progressed. Note: + * not used by all task types. + * @return the parameters for this task + */ const std::vector& GetParameters() const; - /** - * Returns all the target values for this mission, including the target value concatenated by the optional list of - * targets parsed as ints. - * @return all the targets for this task - */ + /** + * Returns all the target values for this mission, including the target value concatenated by the optional list of + * targets parsed as ints. + * @return all the targets for this task + */ std::vector GetAllTargets() const; - /** - * Returns whether the value is in the list of target values of this task - * @param value the value to check for - * @return true if the value is in the target list, false otherwise - */ + /** + * Returns whether the value is in the list of target values of this task + * @param value the value to check for + * @return true if the value is in the target list, false otherwise + */ bool InTargets(uint32_t value) const; - /** - * Returns whether the value is in one of the target values or equals the individual target value of this task - * @param value the value to check for - * @return true if the value is one of the targets, false otherwise - */ + /** + * Returns whether the value is in one of the target values or equals the individual target value of this task + * @param value the value to check for + * @return true if the value is one of the targets, false otherwise + */ bool InAllTargets(uint32_t value) const; - /** - * Checks if the provided is one of the parameters for this task - * @param value the value to check for - * @return true if the value is one of the parameters, false otherwise - */ + /** + * Checks if the provided is one of the parameters for this task + * @param value the value to check for + * @return true if the value is one of the parameters, false otherwise + */ bool InParameters(uint32_t value) const; - /** - * Checks if this task has been completed by comparing its progress against the target value - * @return true if the task has been completed, false otherwise - */ + /** + * Checks if this task has been completed by comparing its progress against the target value + * @return true if the task has been completed, false otherwise + */ bool IsComplete() const; - /** - * Completes the mission by setting the progress to the required value - */ + /** + * Completes the mission by setting the progress to the required value + */ void Complete(); private: - /** - * Datbase information about this task - */ + /** + * Datbase information about this task + */ CDMissionTasks* info; - /** - * The mission this task belongs to - */ + /** + * The mission this task belongs to + */ Mission* mission; - /** - * Mask used for communicating mission updates - */ + /** + * Mask used for communicating mission updates + */ uint32_t mask; - /** - * The current progression towards the target - */ + /** + * The current progression towards the target + */ uint32_t progress; - /** - * The list of target values for progressing this task - */ + /** + * The list of target values for progressing this task + */ std::vector targets; - /** - * The list of parameters for progressing this task (not used by all task types) - */ + /** + * The list of parameters for progressing this task (not used by all task types) + */ std::vector parameters; - /** - * The unique places visited for progression (not used by all task types) - */ + /** + * The unique places visited for progression (not used by all task types) + */ std::vector unique; - /** - * Checks if the task is complete, and if so checks if the parent mission is complete - */ + /** + * Checks if the task is complete, and if so checks if the parent mission is complete + */ void CheckCompletion() const; }; -#endif +#endif diff --git a/dGame/dMission/MissionTaskType.h b/dGame/dMission/MissionTaskType.h index 345f8fff..08f1bff9 100644 --- a/dGame/dMission/MissionTaskType.h +++ b/dGame/dMission/MissionTaskType.h @@ -5,27 +5,27 @@ //! An enum for mission task types enum class MissionTaskType : int { - MISSION_TASK_TYPE_UNKNOWN = -1, //!< The task type is unknown - MISSION_TASK_TYPE_SMASH = 0, //!< A task for smashing something - MISSION_TASK_TYPE_SCRIPT = 1, //!< A task handled by a server LUA script - MISSION_TASK_TYPE_ACTIVITY = 2, //!< A task for completing a quickbuild - MISSION_TASK_TYPE_ENVIRONMENT = 3, //!< A task for something in the environment - MISSION_TASK_TYPE_MISSION_INTERACTION = 4, //!< A task for interacting with a mission - MISSION_TASK_TYPE_EMOTE = 5, //!< A task for playing an emote - MISSION_TASK_TYPE_FOOD = 9, //!< A task for eating food - MISSION_TASK_TYPE_SKILL = 10, //!< A task for performing a skill - MISSION_TASK_TYPE_ITEM_COLLECTION = 11, //!< A task for collecting an item - MISSION_TASK_TYPE_LOCATION = 12, //!< A task for finding a location - MISSION_TASK_TYPE_MINIGAME = 14, //!< A task for doing something in a minigame - MISSION_TASK_TYPE_NON_MISSION_INTERACTION = 15, //!< A task for interacting with a non-mission - MISSION_TASK_TYPE_MISSION_COMPLETE = 16, //!< A task for completing a mission - MISSION_TASK_TYPE_EARN_REPUTATION = 17, //!< A task for earning reputation - MISSION_TASK_TYPE_POWERUP = 21, //!< A task for collecting a powerup - MISSION_TASK_TYPE_PET_TAMING = 22, //!< A task for taming a pet - MISSION_TASK_TYPE_RACING = 23, //!< A task for racing - MISSION_TASK_TYPE_PLAYER_FLAG = 24, //!< A task for setting a player flag - MISSION_TASK_TYPE_PLACE_MODEL = 25, //!< A task for picking up a model - MISSION_TASK_TYPE_VISIT_PROPERTY = 30 //!< A task for visiting a property + MISSION_TASK_TYPE_UNKNOWN = -1, //!< The task type is unknown + MISSION_TASK_TYPE_SMASH = 0, //!< A task for smashing something + MISSION_TASK_TYPE_SCRIPT = 1, //!< A task handled by a server LUA script + MISSION_TASK_TYPE_ACTIVITY = 2, //!< A task for completing a quickbuild + MISSION_TASK_TYPE_ENVIRONMENT = 3, //!< A task for something in the environment + MISSION_TASK_TYPE_MISSION_INTERACTION = 4, //!< A task for interacting with a mission + MISSION_TASK_TYPE_EMOTE = 5, //!< A task for playing an emote + MISSION_TASK_TYPE_FOOD = 9, //!< A task for eating food + MISSION_TASK_TYPE_SKILL = 10, //!< A task for performing a skill + MISSION_TASK_TYPE_ITEM_COLLECTION = 11, //!< A task for collecting an item + MISSION_TASK_TYPE_LOCATION = 12, //!< A task for finding a location + MISSION_TASK_TYPE_MINIGAME = 14, //!< A task for doing something in a minigame + MISSION_TASK_TYPE_NON_MISSION_INTERACTION = 15, //!< A task for interacting with a non-mission + MISSION_TASK_TYPE_MISSION_COMPLETE = 16, //!< A task for completing a mission + MISSION_TASK_TYPE_EARN_REPUTATION = 17, //!< A task for earning reputation + MISSION_TASK_TYPE_POWERUP = 21, //!< A task for collecting a powerup + MISSION_TASK_TYPE_PET_TAMING = 22, //!< A task for taming a pet + MISSION_TASK_TYPE_RACING = 23, //!< A task for racing + MISSION_TASK_TYPE_PLAYER_FLAG = 24, //!< A task for setting a player flag + MISSION_TASK_TYPE_PLACE_MODEL = 25, //!< A task for picking up a model + MISSION_TASK_TYPE_VISIT_PROPERTY = 30 //!< A task for visiting a property }; #endif diff --git a/dGame/dMission/RacingTaskParam.h b/dGame/dMission/RacingTaskParam.h index 38f8dd8e..5958cb5a 100644 --- a/dGame/dMission/RacingTaskParam.h +++ b/dGame/dMission/RacingTaskParam.h @@ -3,18 +3,18 @@ #include enum class RacingTaskParam : int32_t { - RACING_TASK_PARAM_FINISH_WITH_PLACEMENT = 1, // BrickDatabase::emptyCache {}; +std::vector BrickDatabase::emptyCache{}; BrickDatabase* BrickDatabase::m_Address = nullptr; BrickDatabase::BrickDatabase() = default; BrickDatabase::~BrickDatabase() = default; -std::vector& BrickDatabase::GetBricks(const std::string& lxfmlPath) -{ - const auto cached = m_Cache.find(lxfmlPath); +std::vector& BrickDatabase::GetBricks(const std::string& lxfmlPath) { + const auto cached = m_Cache.find(lxfmlPath); - if (cached != m_Cache.end()) { - return cached->second; - } + if (cached != m_Cache.end()) { + return cached->second; + } - std::ifstream file(lxfmlPath); + std::ifstream file(lxfmlPath); if (!file.good()) { return emptyCache; } - + std::stringstream data; data << file.rdbuf(); if (data.str().empty()) { @@ -40,53 +39,53 @@ std::vector& BrickDatabase::GetBricks(const std::string& lxfmlPath) auto* lxfml = doc->FirstChildElement("LXFML"); auto* bricks = lxfml->FirstChildElement("Bricks"); std::string searchTerm = "Brick"; - + if (!bricks) { searchTerm = "Part"; bricks = lxfml->FirstChildElement("Scene")->FirstChildElement("Model")->FirstChildElement("Group"); - + if (!bricks) { - return emptyCache; + return emptyCache; } } - + auto* currentBrick = bricks->FirstChildElement(searchTerm.c_str()); while (currentBrick != nullptr) { - auto* part = currentBrick->FirstChildElement("Part"); + auto* part = currentBrick->FirstChildElement("Part"); if (part == nullptr) part = currentBrick; if (part->Attribute("designID") != nullptr) { - Brick brick { static_cast(part->IntAttribute("designID")) }; + Brick brick{ static_cast(part->IntAttribute("designID")) }; - // Depends on the file, some don't specify a list but just a single material - const auto* materialList = part->Attribute("materials"); - const auto* materialID = part->Attribute("materialID"); + // Depends on the file, some don't specify a list but just a single material + const auto* materialList = part->Attribute("materials"); + const auto* materialID = part->Attribute("materialID"); - if (materialList != nullptr) { - std::string materialString(materialList); - const auto materials = GeneralUtils::SplitString(materialString, ','); + if (materialList != nullptr) { + std::string materialString(materialList); + const auto materials = GeneralUtils::SplitString(materialString, ','); - if (!materials.empty()) { - brick.materialID = std::stoi(materials[0]); - } else { - brick.materialID = 0; - } - } else if (materialID != nullptr) { - brick.materialID = std::stoi(materialID); - } else { - brick.materialID = 0; // This is bad, makes it so the minigame can't be played - } + if (!materials.empty()) { + brick.materialID = std::stoi(materials[0]); + } else { + brick.materialID = 0; + } + } else if (materialID != nullptr) { + brick.materialID = std::stoi(materialID); + } else { + brick.materialID = 0; // This is bad, makes it so the minigame can't be played + } parts.push_back(brick); } - + currentBrick = currentBrick->NextSiblingElement(searchTerm.c_str()); } - m_Cache[lxfmlPath] = parts; + m_Cache[lxfmlPath] = parts; delete doc; - return m_Cache[lxfmlPath]; + return m_Cache[lxfmlPath]; } diff --git a/dGame/dUtilities/BrickDatabase.h b/dGame/dUtilities/BrickDatabase.h index 7e16c2ea..589d46ae 100644 --- a/dGame/dUtilities/BrickDatabase.h +++ b/dGame/dUtilities/BrickDatabase.h @@ -4,28 +4,26 @@ class BrickDatabase { public: - static BrickDatabase* Instance() - { - if (m_Address == nullptr) - { - m_Address = new BrickDatabase(); - } + static BrickDatabase* Instance() { + if (m_Address == nullptr) { + m_Address = new BrickDatabase(); + } - return m_Address; - } + return m_Address; + } - std::vector& GetBricks(const std::string& lxfmlPath); + std::vector& GetBricks(const std::string& lxfmlPath); - explicit BrickDatabase(); + explicit BrickDatabase(); + + ~BrickDatabase(); - ~BrickDatabase(); - private: - std::unordered_map> m_Cache; + std::unordered_map> m_Cache; - static std::vector emptyCache; + static std::vector emptyCache; - static BrickDatabase* m_Address; //For singleton method + static BrickDatabase* m_Address; //For singleton method - /* data */ + /* data */ }; diff --git a/dGame/dUtilities/GUID.cpp b/dGame/dUtilities/GUID.cpp index fb87139a..57f76a81 100644 --- a/dGame/dUtilities/GUID.cpp +++ b/dGame/dUtilities/GUID.cpp @@ -1,27 +1,27 @@ #include "GUID.h" -GUID::GUID(const std::string &guid) { - sscanf(guid.c_str(), - "{%8x-%4hx-%4hx-%2hhx%2hhx-%2hhx%2hhx%2hhx%2hhx%2hhx%2hhx}", - &this->data1, &this->data2, &this->data3, - &this->data4[0], &this->data4[1], &this->data4[2], &this->data4[3], - &this->data4[4], &this->data4[5], &this->data4[6], &this->data4[7]); +GUID::GUID(const std::string& guid) { + sscanf(guid.c_str(), + "{%8x-%4hx-%4hx-%2hhx%2hhx-%2hhx%2hhx%2hhx%2hhx%2hhx%2hhx}", + &this->data1, &this->data2, &this->data3, + &this->data4[0], &this->data4[1], &this->data4[2], &this->data4[3], + &this->data4[4], &this->data4[5], &this->data4[6], &this->data4[7]); } uint32_t GUID::GetData1() const { - return data1; + return data1; } uint16_t GUID::GetData2() const { - return data2; + return data2; } uint16_t GUID::GetData3() const { - return data3; + return data3; } std::array GUID::GetData4() const { - return data4; + return data4; } GUID::GUID() = default; diff --git a/dGame/dUtilities/GUID.h b/dGame/dUtilities/GUID.h index 24518785..2d958c10 100644 --- a/dGame/dUtilities/GUID.h +++ b/dGame/dUtilities/GUID.h @@ -5,15 +5,15 @@ class GUID { public: - explicit GUID(); - explicit GUID(const std::string& guid); - uint32_t GetData1() const; - uint16_t GetData2() const; - uint16_t GetData3() const; - std::array GetData4() const; + explicit GUID(); + explicit GUID(const std::string& guid); + uint32_t GetData1() const; + uint16_t GetData2() const; + uint16_t GetData3() const; + std::array GetData4() const; private: - uint32_t data1 = 0; - uint16_t data2 = 0; - uint16_t data3 = 0; - std::array data4 = { 0, 0, 0, 0, 0, 0, 0, 0}; + uint32_t data1 = 0; + uint16_t data2 = 0; + uint16_t data3 = 0; + std::array data4 = { 0, 0, 0, 0, 0, 0, 0, 0 }; }; diff --git a/dGame/dUtilities/GameConfig.cpp b/dGame/dUtilities/GameConfig.cpp index bd57ee65..ad201e6f 100644 --- a/dGame/dUtilities/GameConfig.cpp +++ b/dGame/dUtilities/GameConfig.cpp @@ -1,8 +1,8 @@ #include "GameConfig.h" #include -std::map GameConfig::m_Config {}; -std::string GameConfig::m_EmptyString {}; +std::map GameConfig::m_Config{}; +std::string GameConfig::m_EmptyString{}; void GameConfig::Load(const std::string& filepath) { m_EmptyString = ""; @@ -15,7 +15,7 @@ void GameConfig::Load(const std::string& filepath) { if (line[0] != '#') ProcessLine(line); } } -} +} const std::string& GameConfig::GetValue(const std::string& key) { const auto& it = m_Config.find(key); @@ -37,14 +37,14 @@ void GameConfig::ProcessLine(const std::string& line) { std::vector seglist; while (std::getline(ss, segment, '=')) { - seglist.push_back(segment); + seglist.push_back(segment); } if (seglist.size() != 2) return; //Make sure that on Linux, we remove special characters: if (!seglist[1].empty() && seglist[1][seglist[1].size() - 1] == '\r') - seglist[1].erase(seglist[1].size() - 1); + seglist[1].erase(seglist[1].size() - 1); m_Config.insert_or_assign(seglist[0], seglist[1]); -} \ No newline at end of file +} diff --git a/dGame/dUtilities/GameConfig.h b/dGame/dUtilities/GameConfig.h index e5fc3987..55089f89 100644 --- a/dGame/dUtilities/GameConfig.h +++ b/dGame/dUtilities/GameConfig.h @@ -35,4 +35,4 @@ private: static std::map m_Config; static std::string m_EmptyString; -}; \ No newline at end of file +}; diff --git a/dGame/dUtilities/Loot.cpp b/dGame/dUtilities/Loot.cpp index 8305e152..784d873f 100644 --- a/dGame/dUtilities/Loot.cpp +++ b/dGame/dUtilities/Loot.cpp @@ -15,375 +15,375 @@ #include "MissionComponent.h" LootGenerator::LootGenerator() { - CDLootTableTable* lootTableTable = CDClientManager::Instance()->GetTable("LootTable"); - CDComponentsRegistryTable* componentsRegistryTable = CDClientManager::Instance()->GetTable("ComponentsRegistry"); - CDItemComponentTable* itemComponentTable = CDClientManager::Instance()->GetTable("ItemComponent"); - CDLootMatrixTable* lootMatrixTable = CDClientManager::Instance()->GetTable("LootMatrix"); - CDRarityTableTable* rarityTableTable = CDClientManager::Instance()->GetTable("RarityTable"); + CDLootTableTable* lootTableTable = CDClientManager::Instance()->GetTable("LootTable"); + CDComponentsRegistryTable* componentsRegistryTable = CDClientManager::Instance()->GetTable("ComponentsRegistry"); + CDItemComponentTable* itemComponentTable = CDClientManager::Instance()->GetTable("ItemComponent"); + CDLootMatrixTable* lootMatrixTable = CDClientManager::Instance()->GetTable("LootMatrix"); + CDRarityTableTable* rarityTableTable = CDClientManager::Instance()->GetTable("RarityTable"); - // ============================== - // Cache Item Rarities - // ============================== + // ============================== + // Cache Item Rarities + // ============================== - std::vector uniqueItems; + std::vector uniqueItems; - for (const CDLootTable& loot : lootTableTable->GetEntries()) { - uniqueItems.push_back(loot.itemid); - } + for (const CDLootTable& loot : lootTableTable->GetEntries()) { + uniqueItems.push_back(loot.itemid); + } - // filter out duplicates - std::sort(uniqueItems.begin(), uniqueItems.end()); - uniqueItems.erase(std::unique(uniqueItems.begin(), uniqueItems.end()), uniqueItems.end()); + // filter out duplicates + std::sort(uniqueItems.begin(), uniqueItems.end()); + uniqueItems.erase(std::unique(uniqueItems.begin(), uniqueItems.end()), uniqueItems.end()); - for (const uint32_t itemID : uniqueItems) { - uint32_t itemComponentID = componentsRegistryTable->GetByIDAndType(itemID, COMPONENT_TYPE_ITEM); - const CDItemComponent& item = itemComponentTable->GetItemComponentByID(itemComponentID); + for (const uint32_t itemID : uniqueItems) { + uint32_t itemComponentID = componentsRegistryTable->GetByIDAndType(itemID, COMPONENT_TYPE_ITEM); + const CDItemComponent& item = itemComponentTable->GetItemComponentByID(itemComponentID); - m_ItemRarities.insert({itemID, item.rarity}); - } + m_ItemRarities.insert({ itemID, item.rarity }); + } - // ============================== - // Cache Rarity Tables - // ============================== + // ============================== + // Cache Rarity Tables + // ============================== - std::vector uniqueRarityIndices; + std::vector uniqueRarityIndices; - for (const CDRarityTable& rarity : rarityTableTable->GetEntries()) { - uniqueRarityIndices.push_back(rarity.RarityTableIndex); - } + for (const CDRarityTable& rarity : rarityTableTable->GetEntries()) { + uniqueRarityIndices.push_back(rarity.RarityTableIndex); + } - // filter out duplicates - std::sort(uniqueRarityIndices.begin(), uniqueRarityIndices.end()); - uniqueRarityIndices.erase(std::unique(uniqueRarityIndices.begin(), uniqueRarityIndices.end()), uniqueRarityIndices.end()); + // filter out duplicates + std::sort(uniqueRarityIndices.begin(), uniqueRarityIndices.end()); + uniqueRarityIndices.erase(std::unique(uniqueRarityIndices.begin(), uniqueRarityIndices.end()), uniqueRarityIndices.end()); - for (const uint32_t index : uniqueRarityIndices) { - std::vector table = rarityTableTable->Query([index](const CDRarityTable& entry) { return entry.RarityTableIndex == index; }); + for (const uint32_t index : uniqueRarityIndices) { + std::vector table = rarityTableTable->Query([index](const CDRarityTable& entry) { return entry.RarityTableIndex == index; }); - RarityTable rarityTable; + RarityTable rarityTable; - for (const CDRarityTable& entry : table) { - RarityTableEntry rarity{entry.rarity, entry.randmax}; - rarityTable.push_back(rarity); - } + for (const CDRarityTable& entry : table) { + RarityTableEntry rarity{ entry.rarity, entry.randmax }; + rarityTable.push_back(rarity); + } - // sort in descending order based on randMax - std::sort(rarityTable.begin(), rarityTable.end(), [](const RarityTableEntry& x, const RarityTableEntry& y) { return x.randMax > y.randMax; }); + // sort in descending order based on randMax + std::sort(rarityTable.begin(), rarityTable.end(), [](const RarityTableEntry& x, const RarityTableEntry& y) { return x.randMax > y.randMax; }); - m_RarityTables.insert({index, rarityTable}); - } + m_RarityTables.insert({ index, rarityTable }); + } - // ============================== - // Cache Loot Matrices - // ============================== + // ============================== + // Cache Loot Matrices + // ============================== - std::vector uniqueMatrixIndices; + std::vector uniqueMatrixIndices; - for (const CDLootMatrix& matrix : lootMatrixTable->GetEntries()) { - uniqueMatrixIndices.push_back(matrix.LootMatrixIndex); - } + for (const CDLootMatrix& matrix : lootMatrixTable->GetEntries()) { + uniqueMatrixIndices.push_back(matrix.LootMatrixIndex); + } - // filter out duplicates - std::sort(uniqueMatrixIndices.begin(), uniqueMatrixIndices.end()); - uniqueMatrixIndices.erase(std::unique(uniqueMatrixIndices.begin(), uniqueMatrixIndices.end()), uniqueMatrixIndices.end()); + // filter out duplicates + std::sort(uniqueMatrixIndices.begin(), uniqueMatrixIndices.end()); + uniqueMatrixIndices.erase(std::unique(uniqueMatrixIndices.begin(), uniqueMatrixIndices.end()), uniqueMatrixIndices.end()); - for (const uint32_t index : uniqueMatrixIndices) { - std::vector matrix = lootMatrixTable->Query([index](const CDLootMatrix& entry) { return entry.LootMatrixIndex == index; }); + for (const uint32_t index : uniqueMatrixIndices) { + std::vector matrix = lootMatrixTable->Query([index](const CDLootMatrix& entry) { return entry.LootMatrixIndex == index; }); - LootMatrix lootMatrix; + LootMatrix lootMatrix; - for (const CDLootMatrix& entry : matrix) { - LootMatrixEntry matrixEntry{entry.LootTableIndex, entry.RarityTableIndex, entry.percent, entry.minToDrop, entry.maxToDrop}; - lootMatrix.push_back(matrixEntry); - } + for (const CDLootMatrix& entry : matrix) { + LootMatrixEntry matrixEntry{ entry.LootTableIndex, entry.RarityTableIndex, entry.percent, entry.minToDrop, entry.maxToDrop }; + lootMatrix.push_back(matrixEntry); + } - m_LootMatrices.insert({index, lootMatrix}); - } + m_LootMatrices.insert({ index, lootMatrix }); + } - // ============================== - // Cache Loot Tables - // ============================== + // ============================== + // Cache Loot Tables + // ============================== - std::vector uniqueTableIndices; + std::vector uniqueTableIndices; - for (const CDLootTable& entry : lootTableTable->GetEntries()) { - uniqueTableIndices.push_back(entry.LootTableIndex); - } + for (const CDLootTable& entry : lootTableTable->GetEntries()) { + uniqueTableIndices.push_back(entry.LootTableIndex); + } - // filter out duplicates - std::sort(uniqueTableIndices.begin(), uniqueTableIndices.end()); - uniqueTableIndices.erase(std::unique(uniqueTableIndices.begin(), uniqueTableIndices.end()), uniqueTableIndices.end()); + // filter out duplicates + std::sort(uniqueTableIndices.begin(), uniqueTableIndices.end()); + uniqueTableIndices.erase(std::unique(uniqueTableIndices.begin(), uniqueTableIndices.end()), uniqueTableIndices.end()); - for (const uint32_t index : uniqueTableIndices) { - std::vector entries = lootTableTable->Query([index](const CDLootTable& entry) { return entry.LootTableIndex == index; }); + for (const uint32_t index : uniqueTableIndices) { + std::vector entries = lootTableTable->Query([index](const CDLootTable& entry) { return entry.LootTableIndex == index; }); - LootTable lootTable; + LootTable lootTable; - for (const CDLootTable& entry : entries) { - LootTableEntry tableEntry{(LOT)entry.itemid, entry.MissionDrop}; - lootTable.push_back(tableEntry); - } + for (const CDLootTable& entry : entries) { + LootTableEntry tableEntry{ (LOT)entry.itemid, entry.MissionDrop }; + lootTable.push_back(tableEntry); + } - // sort by item rarity descending - std::sort(lootTable.begin(), lootTable.end(), [&](const LootTableEntry& x, const LootTableEntry& y) { - return m_ItemRarities[x.itemID] > m_ItemRarities[y.itemID]; - }); + // sort by item rarity descending + std::sort(lootTable.begin(), lootTable.end(), [&](const LootTableEntry& x, const LootTableEntry& y) { + return m_ItemRarities[x.itemID] > m_ItemRarities[y.itemID]; + }); - m_LootTables.insert({index, lootTable}); - } + m_LootTables.insert({ index, lootTable }); + } } std::unordered_map LootGenerator::RollLootMatrix(Entity* player, uint32_t matrixIndex) { - auto* missionComponent = player->GetComponent(); + auto* missionComponent = player->GetComponent(); - std::unordered_map drops; + std::unordered_map drops; - if (missionComponent == nullptr) { - return drops; - } + if (missionComponent == nullptr) { + return drops; + } - const LootMatrix& matrix = m_LootMatrices[matrixIndex]; + const LootMatrix& matrix = m_LootMatrices[matrixIndex]; - for (const LootMatrixEntry& entry : matrix) { - if (GeneralUtils::GenerateRandomNumber(0, 1) < entry.percent) { - const LootTable& lootTable = m_LootTables[entry.lootTableIndex]; - const RarityTable& rarityTable = m_RarityTables[entry.rarityTableIndex]; + for (const LootMatrixEntry& entry : matrix) { + if (GeneralUtils::GenerateRandomNumber(0, 1) < entry.percent) { + const LootTable& lootTable = m_LootTables[entry.lootTableIndex]; + const RarityTable& rarityTable = m_RarityTables[entry.rarityTableIndex]; - uint32_t dropCount = GeneralUtils::GenerateRandomNumber(entry.minDrop, entry.maxDrop); - for (uint32_t i = 0; i < dropCount; ++i) { - uint32_t maxRarity = 1; + uint32_t dropCount = GeneralUtils::GenerateRandomNumber(entry.minDrop, entry.maxDrop); + for (uint32_t i = 0; i < dropCount; ++i) { + uint32_t maxRarity = 1; - float rarityRoll = GeneralUtils::GenerateRandomNumber(0, 1); + float rarityRoll = GeneralUtils::GenerateRandomNumber(0, 1); - for (const RarityTableEntry& rarity : rarityTable) { - if (rarity.randMax >= rarityRoll) { - maxRarity = rarity.rarity; - } else { - break; - } - } + for (const RarityTableEntry& rarity : rarityTable) { + if (rarity.randMax >= rarityRoll) { + maxRarity = rarity.rarity; + } else { + break; + } + } - bool rarityFound = false; - std::vector possibleDrops; + bool rarityFound = false; + std::vector possibleDrops; - for (const LootTableEntry& loot : lootTable) { - uint32_t rarity = m_ItemRarities[loot.itemID]; + for (const LootTableEntry& loot : lootTable) { + uint32_t rarity = m_ItemRarities[loot.itemID]; - if (rarity == maxRarity) { - possibleDrops.push_back(loot); - rarityFound = true; - } else if (rarity < maxRarity && !rarityFound) { - possibleDrops.push_back(loot); - maxRarity = rarity; - } - } + if (rarity == maxRarity) { + possibleDrops.push_back(loot); + rarityFound = true; + } else if (rarity < maxRarity && !rarityFound) { + possibleDrops.push_back(loot); + maxRarity = rarity; + } + } - if (possibleDrops.size() > 0) { - LootTableEntry drop = possibleDrops[GeneralUtils::GenerateRandomNumber(0, possibleDrops.size() - 1)]; + if (possibleDrops.size() > 0) { + LootTableEntry drop = possibleDrops[GeneralUtils::GenerateRandomNumber(0, possibleDrops.size() - 1)]; - // filter out uneeded mission items - if (drop.isMissionDrop && !missionComponent->RequiresItem(drop.itemID)) - continue; + // filter out uneeded mission items + if (drop.isMissionDrop && !missionComponent->RequiresItem(drop.itemID)) + continue; - // convert faction token proxy - if (drop.itemID == 13763) { - if (missionComponent->GetMissionState(545) == MissionState::MISSION_STATE_COMPLETE) - drop.itemID = 8318; // "Assembly Token" - else if (missionComponent->GetMissionState(556) == MissionState::MISSION_STATE_COMPLETE) - drop.itemID = 8321; // "Venture League Token" - else if (missionComponent->GetMissionState(567) == MissionState::MISSION_STATE_COMPLETE) - drop.itemID = 8319; // "Sentinels Token" - else if (missionComponent->GetMissionState(578) == MissionState::MISSION_STATE_COMPLETE) - drop.itemID = 8320; // "Paradox Token" - } + // convert faction token proxy + if (drop.itemID == 13763) { + if (missionComponent->GetMissionState(545) == MissionState::MISSION_STATE_COMPLETE) + drop.itemID = 8318; // "Assembly Token" + else if (missionComponent->GetMissionState(556) == MissionState::MISSION_STATE_COMPLETE) + drop.itemID = 8321; // "Venture League Token" + else if (missionComponent->GetMissionState(567) == MissionState::MISSION_STATE_COMPLETE) + drop.itemID = 8319; // "Sentinels Token" + else if (missionComponent->GetMissionState(578) == MissionState::MISSION_STATE_COMPLETE) + drop.itemID = 8320; // "Paradox Token" + } - if (drop.itemID == 13763) { - continue; - } // check if we aren't in faction + if (drop.itemID == 13763) { + continue; + } // check if we aren't in faction - if (drops.find(drop.itemID) == drops.end()) { - drops.insert({drop.itemID, 1}); - } else { - ++drops[drop.itemID]; - } - } - } - } - } + if (drops.find(drop.itemID) == drops.end()) { + drops.insert({ drop.itemID, 1 }); + } else { + ++drops[drop.itemID]; + } + } + } + } + } - return drops; + return drops; } std::unordered_map LootGenerator::RollLootMatrix(uint32_t matrixIndex) { - std::unordered_map drops; + std::unordered_map drops; - const LootMatrix& matrix = m_LootMatrices[matrixIndex]; + const LootMatrix& matrix = m_LootMatrices[matrixIndex]; - for (const LootMatrixEntry& entry : matrix) { - if (GeneralUtils::GenerateRandomNumber(0, 1) < entry.percent) { - const LootTable& lootTable = m_LootTables[entry.lootTableIndex]; - const RarityTable& rarityTable = m_RarityTables[entry.rarityTableIndex]; + for (const LootMatrixEntry& entry : matrix) { + if (GeneralUtils::GenerateRandomNumber(0, 1) < entry.percent) { + const LootTable& lootTable = m_LootTables[entry.lootTableIndex]; + const RarityTable& rarityTable = m_RarityTables[entry.rarityTableIndex]; - uint32_t dropCount = GeneralUtils::GenerateRandomNumber(entry.minDrop, entry.maxDrop); - for (uint32_t i = 0; i < dropCount; ++i) { - uint32_t maxRarity = 1; + uint32_t dropCount = GeneralUtils::GenerateRandomNumber(entry.minDrop, entry.maxDrop); + for (uint32_t i = 0; i < dropCount; ++i) { + uint32_t maxRarity = 1; - float rarityRoll = GeneralUtils::GenerateRandomNumber(0, 1); + float rarityRoll = GeneralUtils::GenerateRandomNumber(0, 1); - for (const RarityTableEntry& rarity : rarityTable) { - if (rarity.randMax >= rarityRoll) { - maxRarity = rarity.rarity; - } else { - break; - } - } + for (const RarityTableEntry& rarity : rarityTable) { + if (rarity.randMax >= rarityRoll) { + maxRarity = rarity.rarity; + } else { + break; + } + } - bool rarityFound = false; - std::vector possibleDrops; + bool rarityFound = false; + std::vector possibleDrops; - for (const LootTableEntry& loot : lootTable) { - uint32_t rarity = m_ItemRarities[loot.itemID]; + for (const LootTableEntry& loot : lootTable) { + uint32_t rarity = m_ItemRarities[loot.itemID]; - if (rarity == maxRarity) { - possibleDrops.push_back(loot); - rarityFound = true; - } else if (rarity < maxRarity && !rarityFound) { - possibleDrops.push_back(loot); - maxRarity = rarity; - } - } + if (rarity == maxRarity) { + possibleDrops.push_back(loot); + rarityFound = true; + } else if (rarity < maxRarity && !rarityFound) { + possibleDrops.push_back(loot); + maxRarity = rarity; + } + } - if (possibleDrops.size() > 0) { - const LootTableEntry& drop = possibleDrops[GeneralUtils::GenerateRandomNumber(0, possibleDrops.size() - 1)]; + if (possibleDrops.size() > 0) { + const LootTableEntry& drop = possibleDrops[GeneralUtils::GenerateRandomNumber(0, possibleDrops.size() - 1)]; - if (drops.find(drop.itemID) == drops.end()) { - drops.insert({drop.itemID, 1}); - } else { - ++drops[drop.itemID]; - } - } - } - } - } + if (drops.find(drop.itemID) == drops.end()) { + drops.insert({ drop.itemID, 1 }); + } else { + ++drops[drop.itemID]; + } + } + } + } + } - return drops; + return drops; } void LootGenerator::GiveLoot(Entity* player, uint32_t matrixIndex, eLootSourceType lootSourceType) { - player = player->GetOwner(); // If the owner is overwritten, we collect that here + player = player->GetOwner(); // If the owner is overwritten, we collect that here - std::unordered_map result = RollLootMatrix(player, matrixIndex); + std::unordered_map result = RollLootMatrix(player, matrixIndex); - GiveLoot(player, result, lootSourceType); + GiveLoot(player, result, lootSourceType); } void LootGenerator::GiveLoot(Entity* player, std::unordered_map& result, eLootSourceType lootSourceType) { - player = player->GetOwner(); // if the owner is overwritten, we collect that here + player = player->GetOwner(); // if the owner is overwritten, we collect that here - auto* inventoryComponent = player->GetComponent(); + auto* inventoryComponent = player->GetComponent(); - if (!inventoryComponent) - return; + if (!inventoryComponent) + return; - for (const auto& pair : result) { - inventoryComponent->AddItem(pair.first, pair.second, lootSourceType); - } + for (const auto& pair : result) { + inventoryComponent->AddItem(pair.first, pair.second, lootSourceType); + } } void LootGenerator::GiveActivityLoot(Entity* player, Entity* source, uint32_t activityID, int32_t rating) { - CDActivityRewardsTable* activityRewardsTable = CDClientManager::Instance()->GetTable("ActivityRewards"); - std::vector activityRewards = activityRewardsTable->Query([activityID](CDActivityRewards entry) { return (entry.objectTemplate == activityID); }); + CDActivityRewardsTable* activityRewardsTable = CDClientManager::Instance()->GetTable("ActivityRewards"); + std::vector activityRewards = activityRewardsTable->Query([activityID](CDActivityRewards entry) { return (entry.objectTemplate == activityID); }); - const CDActivityRewards* selectedReward = nullptr; - for (const auto& activityReward : activityRewards) { - if (activityReward.activityRating <= rating && (selectedReward == nullptr || activityReward.activityRating > selectedReward->activityRating)) { - selectedReward = &activityReward; - } - } + const CDActivityRewards* selectedReward = nullptr; + for (const auto& activityReward : activityRewards) { + if (activityReward.activityRating <= rating && (selectedReward == nullptr || activityReward.activityRating > selectedReward->activityRating)) { + selectedReward = &activityReward; + } + } - if (!selectedReward) - return; + if (!selectedReward) + return; - uint32_t minCoins = 0; - uint32_t maxCoins = 0; + uint32_t minCoins = 0; + uint32_t maxCoins = 0; - CDCurrencyTableTable* currencyTableTable = CDClientManager::Instance()->GetTable("CurrencyTable"); - std::vector currencyTable = currencyTableTable->Query([selectedReward](CDCurrencyTable entry) { return (entry.currencyIndex == selectedReward->CurrencyIndex && entry.npcminlevel == 1); }); + CDCurrencyTableTable* currencyTableTable = CDClientManager::Instance()->GetTable("CurrencyTable"); + std::vector currencyTable = currencyTableTable->Query([selectedReward](CDCurrencyTable entry) { return (entry.currencyIndex == selectedReward->CurrencyIndex && entry.npcminlevel == 1); }); - if (currencyTable.size() > 0) { - minCoins = currencyTable[0].minvalue; - maxCoins = currencyTable[0].maxvalue; - } + if (currencyTable.size() > 0) { + minCoins = currencyTable[0].minvalue; + maxCoins = currencyTable[0].maxvalue; + } - GiveLoot(player, selectedReward->LootMatrixIndex, eLootSourceType::LOOT_SOURCE_ACTIVITY); + GiveLoot(player, selectedReward->LootMatrixIndex, eLootSourceType::LOOT_SOURCE_ACTIVITY); - uint32_t coins = (int)(minCoins + GeneralUtils::GenerateRandomNumber(0, 1) * (maxCoins - minCoins)); + uint32_t coins = (int)(minCoins + GeneralUtils::GenerateRandomNumber(0, 1) * (maxCoins - minCoins)); - auto* character = player->GetCharacter(); + auto* character = player->GetCharacter(); - character->SetCoins(character->GetCoins() + coins, eLootSourceType::LOOT_SOURCE_ACTIVITY); + character->SetCoins(character->GetCoins() + coins, eLootSourceType::LOOT_SOURCE_ACTIVITY); } void LootGenerator::DropLoot(Entity* player, Entity* killedObject, uint32_t matrixIndex, uint32_t minCoins, uint32_t maxCoins) { - player = player->GetOwner(); // if the owner is overwritten, we collect that here + player = player->GetOwner(); // if the owner is overwritten, we collect that here - auto* inventoryComponent = player->GetComponent(); + auto* inventoryComponent = player->GetComponent(); - if (!inventoryComponent) - return; + if (!inventoryComponent) + return; - std::unordered_map result = RollLootMatrix(player, matrixIndex); + std::unordered_map result = RollLootMatrix(player, matrixIndex); - DropLoot(player, killedObject, result, minCoins, maxCoins); + DropLoot(player, killedObject, result, minCoins, maxCoins); } void LootGenerator::DropLoot(Entity* player, Entity* killedObject, std::unordered_map& result, uint32_t minCoins, uint32_t maxCoins) { - player = player->GetOwner(); // if the owner is overwritten, we collect that here + player = player->GetOwner(); // if the owner is overwritten, we collect that here - auto* inventoryComponent = player->GetComponent(); + auto* inventoryComponent = player->GetComponent(); - if (!inventoryComponent) - return; + if (!inventoryComponent) + return; - const auto spawnPosition = killedObject->GetPosition(); + const auto spawnPosition = killedObject->GetPosition(); - const auto source = killedObject->GetObjectID(); + const auto source = killedObject->GetObjectID(); - for (const auto& pair : result) { - for (int i = 0; i < pair.second; ++i) { - GameMessages::SendDropClientLoot(player, source, pair.first, 0, spawnPosition, 1); - } - } + for (const auto& pair : result) { + for (int i = 0; i < pair.second; ++i) { + GameMessages::SendDropClientLoot(player, source, pair.first, 0, spawnPosition, 1); + } + } - uint32_t coins = (int)(minCoins + GeneralUtils::GenerateRandomNumber(0, 1) * (maxCoins - minCoins)); + uint32_t coins = (int)(minCoins + GeneralUtils::GenerateRandomNumber(0, 1) * (maxCoins - minCoins)); - GameMessages::SendDropClientLoot(player, source, LOT_NULL, coins, spawnPosition); + GameMessages::SendDropClientLoot(player, source, LOT_NULL, coins, spawnPosition); } void LootGenerator::DropActivityLoot(Entity* player, Entity* source, uint32_t activityID, int32_t rating) { - CDActivityRewardsTable* activityRewardsTable = CDClientManager::Instance()->GetTable("ActivityRewards"); - std::vector activityRewards = activityRewardsTable->Query([activityID](CDActivityRewards entry) { return (entry.objectTemplate == activityID); }); + CDActivityRewardsTable* activityRewardsTable = CDClientManager::Instance()->GetTable("ActivityRewards"); + std::vector activityRewards = activityRewardsTable->Query([activityID](CDActivityRewards entry) { return (entry.objectTemplate == activityID); }); - const CDActivityRewards* selectedReward = nullptr; - for (const auto& activityReward : activityRewards) { - if (activityReward.activityRating <= rating && (selectedReward == nullptr || activityReward.activityRating > selectedReward->activityRating)) { - selectedReward = &activityReward; - } - } + const CDActivityRewards* selectedReward = nullptr; + for (const auto& activityReward : activityRewards) { + if (activityReward.activityRating <= rating && (selectedReward == nullptr || activityReward.activityRating > selectedReward->activityRating)) { + selectedReward = &activityReward; + } + } - if (selectedReward == nullptr) { - return; - } + if (selectedReward == nullptr) { + return; + } - uint32_t minCoins = 0; - uint32_t maxCoins = 0; + uint32_t minCoins = 0; + uint32_t maxCoins = 0; - CDCurrencyTableTable* currencyTableTable = CDClientManager::Instance()->GetTable("CurrencyTable"); - std::vector currencyTable = currencyTableTable->Query([selectedReward](CDCurrencyTable entry) { return (entry.currencyIndex == selectedReward->CurrencyIndex && entry.npcminlevel == 1); }); + CDCurrencyTableTable* currencyTableTable = CDClientManager::Instance()->GetTable("CurrencyTable"); + std::vector currencyTable = currencyTableTable->Query([selectedReward](CDCurrencyTable entry) { return (entry.currencyIndex == selectedReward->CurrencyIndex && entry.npcminlevel == 1); }); - if (currencyTable.size() > 0) { - minCoins = currencyTable[0].minvalue; - maxCoins = currencyTable[0].maxvalue; - } + if (currencyTable.size() > 0) { + minCoins = currencyTable[0].minvalue; + maxCoins = currencyTable[0].maxvalue; + } - DropLoot(player, source, selectedReward->LootMatrixIndex, minCoins, maxCoins); + DropLoot(player, source, selectedReward->LootMatrixIndex, minCoins, maxCoins); } diff --git a/dGame/dUtilities/Loot.h b/dGame/dUtilities/Loot.h index b16c834a..7ecc22b8 100644 --- a/dGame/dUtilities/Loot.h +++ b/dGame/dUtilities/Loot.h @@ -8,55 +8,55 @@ class Entity; struct RarityTableEntry { - uint32_t rarity; - float randMax; + uint32_t rarity; + float randMax; }; typedef std::vector RarityTable; struct LootMatrixEntry { - uint32_t lootTableIndex; - uint32_t rarityTableIndex; - float percent; - uint32_t minDrop; - uint32_t maxDrop; + uint32_t lootTableIndex; + uint32_t rarityTableIndex; + float percent; + uint32_t minDrop; + uint32_t maxDrop; }; typedef std::vector LootMatrix; struct LootTableEntry { - LOT itemID; - bool isMissionDrop; + LOT itemID; + bool isMissionDrop; }; typedef std::vector LootTable; // used for glue code with Entity and Player classes namespace Loot { - struct Info { - LWOOBJID id; - LOT lot; - uint32_t count; - }; + struct Info { + LWOOBJID id; + LOT lot; + uint32_t count; + }; } class LootGenerator : public Singleton { - public: - LootGenerator(); +public: + LootGenerator(); - std::unordered_map RollLootMatrix(Entity* player, uint32_t matrixIndex); - std::unordered_map RollLootMatrix(uint32_t matrixIndex); - void GiveLoot(Entity* player, uint32_t matrixIndex, eLootSourceType lootSourceType = eLootSourceType::LOOT_SOURCE_NONE); - void GiveLoot(Entity* player, std::unordered_map& result, eLootSourceType lootSourceType = eLootSourceType::LOOT_SOURCE_NONE); - void GiveActivityLoot(Entity* player, Entity* source, uint32_t activityID, int32_t rating = 0); - void DropLoot(Entity* player, Entity* killedObject, uint32_t matrixIndex, uint32_t minCoins, uint32_t maxCoins); - void DropLoot(Entity* player, Entity* killedObject, std::unordered_map& result, uint32_t minCoins, uint32_t maxCoins); - void DropActivityLoot(Entity* player, Entity* source, uint32_t activityID, int32_t rating = 0); + std::unordered_map RollLootMatrix(Entity* player, uint32_t matrixIndex); + std::unordered_map RollLootMatrix(uint32_t matrixIndex); + void GiveLoot(Entity* player, uint32_t matrixIndex, eLootSourceType lootSourceType = eLootSourceType::LOOT_SOURCE_NONE); + void GiveLoot(Entity* player, std::unordered_map& result, eLootSourceType lootSourceType = eLootSourceType::LOOT_SOURCE_NONE); + void GiveActivityLoot(Entity* player, Entity* source, uint32_t activityID, int32_t rating = 0); + void DropLoot(Entity* player, Entity* killedObject, uint32_t matrixIndex, uint32_t minCoins, uint32_t maxCoins); + void DropLoot(Entity* player, Entity* killedObject, std::unordered_map& result, uint32_t minCoins, uint32_t maxCoins); + void DropActivityLoot(Entity* player, Entity* source, uint32_t activityID, int32_t rating = 0); - private: - std::unordered_map m_ItemRarities; - std::unordered_map m_RarityTables; - std::unordered_map m_LootMatrices; - std::unordered_map m_LootTables; +private: + std::unordered_map m_ItemRarities; + std::unordered_map m_RarityTables; + std::unordered_map m_LootMatrices; + std::unordered_map m_LootTables; }; diff --git a/dGame/dUtilities/Mail.cpp b/dGame/dUtilities/Mail.cpp index b15d3bb6..59ce8444 100644 --- a/dGame/dUtilities/Mail.cpp +++ b/dGame/dUtilities/Mail.cpp @@ -24,8 +24,7 @@ #include "Character.h" void Mail::SendMail(const Entity* recipient, const std::string& subject, const std::string& body, const LOT attachment, - const uint16_t attachmentCount) -{ + const uint16_t attachmentCount) { SendMail( LWOOBJID_EMPTY, ServerName, @@ -40,8 +39,7 @@ void Mail::SendMail(const Entity* recipient, const std::string& subject, const s } void Mail::SendMail(const LWOOBJID recipient, const std::string& recipientName, const std::string& subject, - const std::string& body, const LOT attachment, const uint16_t attachmentCount, const SystemAddress& sysAddr) -{ + const std::string& body, const LOT attachment, const uint16_t attachmentCount, const SystemAddress& sysAddr) { SendMail( LWOOBJID_EMPTY, ServerName, @@ -56,8 +54,7 @@ void Mail::SendMail(const LWOOBJID recipient, const std::string& recipientName, } void Mail::SendMail(const LWOOBJID sender, const std::string& senderName, const Entity* recipient, const std::string& subject, - const std::string& body, const LOT attachment, const uint16_t attachmentCount) -{ + const std::string& body, const LOT attachment, const uint16_t attachmentCount) { SendMail( sender, senderName, @@ -72,9 +69,8 @@ void Mail::SendMail(const LWOOBJID sender, const std::string& senderName, const } void Mail::SendMail(const LWOOBJID sender, const std::string& senderName, LWOOBJID recipient, - const std::string& recipientName, const std::string& subject, const std::string& body, const LOT attachment, - const uint16_t attachmentCount, const SystemAddress& sysAddr) -{ + const std::string& recipientName, const std::string& subject, const std::string& body, const LOT attachment, + const uint16_t attachmentCount, const SystemAddress& sysAddr) { auto* ins = Database::CreatePreppedStmt("INSERT INTO `mail`(`sender_id`, `sender_name`, `receiver_id`, `receiver_name`, `time_sent`, `subject`, `body`, `attachment_id`, `attachment_lot`, `attachment_subkey`, `attachment_count`, `was_read`) VALUES (?,?,?,?,?,?,?,?,?,?,?,0)"); ins->setUInt(1, sender); @@ -154,7 +150,7 @@ void Mail::HandleMailStuff(RakNet::BitStream* packet, const SystemAddress& sysAd default: Game::logger->Log("Mail", "Unhandled and possibly undefined MailStuffID: %i", int(stuffID)); } - }); + }); } void Mail::HandleSendMail(RakNet::BitStream* packet, const SystemAddress& sysAddr, Entity* entity) { @@ -167,8 +163,7 @@ void Mail::HandleSendMail(RakNet::BitStream* packet, const SystemAddress& sysAdd if (!character) return; - if (character->HasPermission(PermissionMap::RestrictedMailAccess)) - { + if (character->HasPermission(PermissionMap::RestrictedMailAccess)) { // Send a message to the player ChatPackets::SendSystemMessage( sysAddr, @@ -227,8 +222,7 @@ void Mail::HandleSendMail(RakNet::BitStream* packet, const SystemAddress& sysAdd if (res->rowsCount() > 0) { while (res->next()) receiverID = res->getUInt(1); - } - else { + } else { Mail::SendSendResponse(sysAddr, Mail::MailSendResponse::RecipientNotFound); delete stmt; delete res; @@ -242,8 +236,7 @@ void Mail::HandleSendMail(RakNet::BitStream* packet, const SystemAddress& sysAdd if (GeneralUtils::CaseInsensitiveStringCompare(recipient, character->GetName()) || receiverID == character->GetObjectID()) { Mail::SendSendResponse(sysAddr, Mail::MailSendResponse::CannotMailSelf); return; - } - else { + } else { uint64_t currentTime = time(NULL); sql::PreparedStatement* ins = Database::CreatePreppedStmt("INSERT INTO `mail`(`sender_id`, `sender_name`, `receiver_id`, `receiver_name`, `time_sent`, `subject`, `body`, `attachment_id`, `attachment_lot`, `attachment_subkey`, `attachment_count`, `was_read`) VALUES (?,?,?,?,?,?,?,?,?,?,?,0)"); ins->setUInt(1, character->GetObjectID()); @@ -272,8 +265,7 @@ void Mail::HandleSendMail(RakNet::BitStream* packet, const SystemAddress& sysAdd auto* missionCompoent = entity->GetComponent(); - if (missionCompoent != nullptr) - { + if (missionCompoent != nullptr) { missionCompoent->Progress(MissionTaskType::MISSION_TASK_TYPE_ITEM_COLLECTION, itemLOT, LWOOBJID_EMPTY, "", -attachmentCount); } } @@ -405,7 +397,7 @@ void Mail::HandleNotificationRequest(const SystemAddress& sysAddr, uint32_t obje if (res->rowsCount() > 0) Mail::SendNotification(sysAddr, res->rowsCount()); delete res; delete stmt; - }); + }); } void Mail::SendSendResponse(const SystemAddress& sysAddr, MailSendResponse response) { diff --git a/dGame/dUtilities/Mail.h b/dGame/dUtilities/Mail.h index 4853db18..c8eabe6b 100644 --- a/dGame/dUtilities/Mail.h +++ b/dGame/dUtilities/Mail.h @@ -56,7 +56,7 @@ namespace Mail { uint16_t attachmentCount, const SystemAddress& sysAddr ); - + void SendMail( LWOOBJID sender, const std::string& senderName, @@ -92,4 +92,4 @@ namespace Mail { void SendAttachmentRemoveConfirm(const SystemAddress& sysAddr, uint64_t mailID); void SendDeleteConfirm(const SystemAddress& sysAddr, uint64_t mailID, LWOOBJID playerID); void SendReadConfirm(const SystemAddress& sysAddr, uint64_t mailID); -}; \ No newline at end of file +}; diff --git a/dGame/dUtilities/Preconditions.cpp b/dGame/dUtilities/Preconditions.cpp index 1b442f49..1f719433 100644 --- a/dGame/dUtilities/Preconditions.cpp +++ b/dGame/dUtilities/Preconditions.cpp @@ -19,12 +19,11 @@ std::map Preconditions::cache = {}; Precondition::Precondition(const uint32_t condition) { auto query = CDClientDatabase::CreatePreppedStmt( "SELECT type, targetLOT, targetCount FROM Preconditions WHERE id = ?;"); - query.bind(1, (int) condition); + query.bind(1, (int)condition); auto result = query.execQuery(); - if (result.eof()) - { + if (result.eof()) { this->type = PreconditionType::ItemEquipped; this->count = 1; this->values = { 0 }; @@ -36,16 +35,13 @@ Precondition::Precondition(const uint32_t condition) { this->type = static_cast(result.fieldIsNull(0) ? 0 : result.getIntField(0)); - if (!result.fieldIsNull(1)) - { + if (!result.fieldIsNull(1)) { std::istringstream stream(result.getStringField(1)); std::string token; - while (std::getline(stream, token, ',')) - { + while (std::getline(stream, token, ',')) { uint32_t value; - if (GeneralUtils::TryParse(token, value)) - { + if (GeneralUtils::TryParse(token, value)) { this->values.push_back(value); } } @@ -57,10 +53,8 @@ Precondition::Precondition(const uint32_t condition) { } -bool Precondition::Check(Entity* player, bool evaluateCosts) const -{ - if (values.empty()) - { +bool Precondition::Check(Entity* player, bool evaluateCosts) const { + if (values.empty()) { return true; // There are very few of these } @@ -100,22 +94,18 @@ bool Precondition::Check(Entity* player, bool evaluateCosts) const auto passedAny = false; - for (const auto value : values) - { + for (const auto value : values) { const auto passed = CheckValue(player, value, evaluateCosts); - if (passed && any) - { + if (passed && any) { return true; } - if (!passed && !any) - { + if (!passed && !any) { return false; } - if (passed) - { + if (passed) { passedAny = true; } } @@ -124,8 +114,7 @@ bool Precondition::Check(Entity* player, bool evaluateCosts) const } -bool Precondition::CheckValue(Entity* player, const uint32_t value, bool evaluateCosts) const -{ +bool Precondition::CheckValue(Entity* player, const uint32_t value, bool evaluateCosts) const { auto* missionComponent = player->GetComponent(); auto* inventoryComponent = player->GetComponent(); auto* destroyableComponent = player->GetComponent(); @@ -134,8 +123,7 @@ bool Precondition::CheckValue(Entity* player, const uint32_t value, bool evaluat Mission* mission; - switch (type) - { + switch (type) { case PreconditionType::ItemEquipped: return inventoryComponent->IsEquipped(value); case PreconditionType::ItemNotEquipped: @@ -180,20 +168,16 @@ bool Precondition::CheckValue(Entity* player, const uint32_t value, bool evaluat case PreconditionType::IsPetTaming: return false; // TODO case PreconditionType::HasFaction: - for (const auto faction : destroyableComponent->GetFactionIDs()) - { - if (faction == static_cast(value)) - { + for (const auto faction : destroyableComponent->GetFactionIDs()) { + if (faction == static_cast(value)) { return true; } } return false; case PreconditionType::DoesNotHaveFaction: - for (const auto faction : destroyableComponent->GetFactionIDs()) - { - if (faction == static_cast(value)) - { + for (const auto faction : destroyableComponent->GetFactionIDs()) { + if (faction == static_cast(value)) { return false; } } @@ -214,10 +198,8 @@ bool Precondition::CheckValue(Entity* player, const uint32_t value, bool evaluat } } -PreconditionExpression::PreconditionExpression(const std::string& conditions) -{ - if (conditions.empty()) - { +PreconditionExpression::PreconditionExpression(const std::string& conditions) { + if (conditions.empty()) { empty = true; return; @@ -230,17 +212,14 @@ PreconditionExpression::PreconditionExpression(const std::string& conditions) auto done = false; - for (auto i = 0u; i < conditions.size(); ++i) - { - if (done) - { + for (auto i = 0u; i < conditions.size(); ++i) { + if (done) { break; } const auto character = conditions[i]; - switch (character) - { + switch (character) { case '|': bor = true; b << conditions.substr(i + 1); @@ -277,32 +256,24 @@ PreconditionExpression::PreconditionExpression(const std::string& conditions) const auto aString = a.str(); - if (!aString.empty()) - { + if (!aString.empty()) { this->condition = std::stoul(a.str()); - } - else - { + } else { this->condition = 0; } const auto bString = b.str(); - if (!bString.empty()) - { + if (!bString.empty()) { this->next = new PreconditionExpression(bString); - } - else - { + } else { this->next = nullptr; } } -bool PreconditionExpression::Check(Entity* player, bool evaluateCosts) const -{ - if (empty) - { +bool PreconditionExpression::Check(Entity* player, bool evaluateCosts) const { + if (empty) { return true; } @@ -313,8 +284,7 @@ bool PreconditionExpression::Check(Entity* player, bool evaluateCosts) const const auto a = Preconditions::Check(player, condition, evaluateCosts); - if (!a) - { + if (!a) { GameMessages::SendNotifyClientFailedPrecondition(player->GetObjectID(), player->GetSystemAddress(), u"", condition); } @@ -323,24 +293,19 @@ bool PreconditionExpression::Check(Entity* player, bool evaluateCosts) const return m_or ? a || b : a && b; } -PreconditionExpression::~PreconditionExpression() -{ +PreconditionExpression::~PreconditionExpression() { delete next; } -bool Preconditions::Check(Entity* player, const uint32_t condition, bool evaluateCosts) -{ +bool Preconditions::Check(Entity* player, const uint32_t condition, bool evaluateCosts) { Precondition* precondition; const auto& index = cache.find(condition); - if (index != cache.end()) - { + if (index != cache.end()) { precondition = index->second; - } - else - { + } else { precondition = new Precondition(condition); cache.insert_or_assign(condition, precondition); @@ -350,16 +315,13 @@ bool Preconditions::Check(Entity* player, const uint32_t condition, bool evaluat } -PreconditionExpression Preconditions::CreateExpression(const std::string& conditions) -{ +PreconditionExpression Preconditions::CreateExpression(const std::string& conditions) { return PreconditionExpression(conditions); } -Preconditions::~Preconditions() -{ - for (const auto& condition : cache) - { +Preconditions::~Preconditions() { + for (const auto& condition : cache) { delete condition.second; } diff --git a/dGame/dUtilities/Preconditions.h b/dGame/dUtilities/Preconditions.h index 0ceeb32a..08e564bf 100644 --- a/dGame/dUtilities/Preconditions.h +++ b/dGame/dUtilities/Preconditions.h @@ -6,26 +6,26 @@ enum class PreconditionType { - ItemEquipped, - ItemNotEquipped, - HasItem, - DoesNotHaveItem, - HasAchievement, - MissionAvailable, - OnMission, - MissionComplete, - PetDeployed, - HasFlag, - WithinShape, - InBuild, - TeamCheck, - IsPetTaming, - HasFaction, - DoesNotHaveFaction, - HasRacingLicence, - DoesNotHaveRacingLicence, - LegoClubMember, - NoInteraction, + ItemEquipped, + ItemNotEquipped, + HasItem, + DoesNotHaveItem, + HasAchievement, + MissionAvailable, + OnMission, + MissionComplete, + PetDeployed, + HasFlag, + WithinShape, + InBuild, + TeamCheck, + IsPetTaming, + HasFaction, + DoesNotHaveFaction, + HasRacingLicence, + DoesNotHaveRacingLicence, + LegoClubMember, + NoInteraction, HasLevel = 22 }; @@ -33,49 +33,49 @@ enum class PreconditionType class Precondition final { public: - explicit Precondition(uint32_t condition); - - bool Check(Entity* player, bool evaluateCosts = false) const; - + explicit Precondition(uint32_t condition); + + bool Check(Entity* player, bool evaluateCosts = false) const; + private: - bool CheckValue(Entity* player, uint32_t value, bool evaluateCosts = false) const; - - PreconditionType type; + bool CheckValue(Entity* player, uint32_t value, bool evaluateCosts = false) const; - std::vector values; + PreconditionType type; - uint32_t count; + std::vector values; + + uint32_t count; }; class PreconditionExpression final { public: - explicit PreconditionExpression(const std::string& conditions); + explicit PreconditionExpression(const std::string& conditions); + + bool Check(Entity* player, bool evaluateCosts = false) const; + + ~PreconditionExpression(); - bool Check(Entity* player, bool evaluateCosts = false) const; - - ~PreconditionExpression(); - private: - uint32_t condition = 0; + uint32_t condition = 0; - bool m_or = false; + bool m_or = false; - bool empty = false; + bool empty = false; - PreconditionExpression* next = nullptr; + PreconditionExpression* next = nullptr; }; class Preconditions final { public: - static bool Check(Entity* player, uint32_t condition, bool evaluateCosts = false); + static bool Check(Entity* player, uint32_t condition, bool evaluateCosts = false); - static PreconditionExpression CreateExpression(const std::string& conditions); + static PreconditionExpression CreateExpression(const std::string& conditions); ~Preconditions(); - + private: - static std::map cache; + static std::map cache; }; diff --git a/dGame/dUtilities/SlashCommandHandler.cpp b/dGame/dUtilities/SlashCommandHandler.cpp index ecb3bbda..16cdddbb 100644 --- a/dGame/dUtilities/SlashCommandHandler.cpp +++ b/dGame/dUtilities/SlashCommandHandler.cpp @@ -65,80 +65,74 @@ #include "LevelProgressionComponent.h" void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entity* entity, const SystemAddress& sysAddr) { - std::string chatCommand; - std::vector args; + std::string chatCommand; + std::vector args; - uint32_t breakIndex = 0; - for (uint32_t i = 1; i < command.size(); ++i) { - if (command[i] == L' ') { - breakIndex = i; - break; - } + uint32_t breakIndex = 0; + for (uint32_t i = 1; i < command.size(); ++i) { + if (command[i] == L' ') { + breakIndex = i; + break; + } - chatCommand.push_back(static_cast(command[i])); - breakIndex++; - } + chatCommand.push_back(static_cast(command[i])); + breakIndex++; + } - uint32_t index = ++breakIndex; - while (true) { - std::string arg; + uint32_t index = ++breakIndex; + while (true) { + std::string arg; - while (index < command.size()) { - if (command[index] == L' ') { - args.push_back(arg); - arg = ""; - index++; - continue; - } + while (index < command.size()) { + if (command[index] == L' ') { + args.push_back(arg); + arg = ""; + index++; + continue; + } - arg.push_back(static_cast(command[index])); - index++; - } + arg.push_back(static_cast(command[index])); + index++; + } - if (arg != "") { - args.push_back(arg); - } + if (arg != "") { + args.push_back(arg); + } - break; - } + break; + } - //Game::logger->Log("SlashCommandHandler", "Received chat command \"%s\"", GeneralUtils::UTF16ToWTF8(command).c_str()); + //Game::logger->Log("SlashCommandHandler", "Received chat command \"%s\"", GeneralUtils::UTF16ToWTF8(command).c_str()); - User* user = UserManager::Instance()->GetUser(sysAddr); - if ((chatCommand == "setgmlevel" || chatCommand == "makegm" || chatCommand == "gmlevel") && user->GetMaxGMLevel() > GAME_MASTER_LEVEL_CIVILIAN) { - if (args.size() != 1) return; + User* user = UserManager::Instance()->GetUser(sysAddr); + if ((chatCommand == "setgmlevel" || chatCommand == "makegm" || chatCommand == "gmlevel") && user->GetMaxGMLevel() > GAME_MASTER_LEVEL_CIVILIAN) { + if (args.size() != 1) return; uint32_t level; - if (!GeneralUtils::TryParse(args[0], level)) - { + if (!GeneralUtils::TryParse(args[0], level)) { ChatPackets::SendSystemMessage(sysAddr, u"Invalid gm level."); return; } #ifndef DEVELOPER_SERVER - if (user->GetMaxGMLevel() == GAME_MASTER_LEVEL_JUNIOR_DEVELOPER) - { + if (user->GetMaxGMLevel() == GAME_MASTER_LEVEL_JUNIOR_DEVELOPER) { level = GAME_MASTER_LEVEL_CIVILIAN; } #endif - if (level > user->GetMaxGMLevel()) - { + if (level > user->GetMaxGMLevel()) { level = user->GetMaxGMLevel(); } - if (level == entity->GetGMLevel()) return; - bool success = user->GetMaxGMLevel() >= level; + if (level == entity->GetGMLevel()) return; + bool success = user->GetMaxGMLevel() >= level; - if (success) { + if (success) { - if (entity->GetGMLevel() > GAME_MASTER_LEVEL_CIVILIAN && level == GAME_MASTER_LEVEL_CIVILIAN) - { + if (entity->GetGMLevel() > GAME_MASTER_LEVEL_CIVILIAN && level == GAME_MASTER_LEVEL_CIVILIAN) { GameMessages::SendToggleGMInvis(entity->GetObjectID(), false, UNASSIGNED_SYSTEM_ADDRESS); - } - else if (entity->GetGMLevel() == GAME_MASTER_LEVEL_CIVILIAN && level > GAME_MASTER_LEVEL_CIVILIAN) - { + } else if (entity->GetGMLevel() == GAME_MASTER_LEVEL_CIVILIAN && level > GAME_MASTER_LEVEL_CIVILIAN) { GameMessages::SendToggleGMInvis(entity->GetObjectID(), true, UNASSIGNED_SYSTEM_ADDRESS); } @@ -150,8 +144,7 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit } #ifndef DEVELOPER_SERVER - if ((entity->GetGMLevel() > user->GetMaxGMLevel()) || (entity->GetGMLevel() > GAME_MASTER_LEVEL_CIVILIAN && user->GetMaxGMLevel() == GAME_MASTER_LEVEL_JUNIOR_DEVELOPER)) - { + if ((entity->GetGMLevel() > user->GetMaxGMLevel()) || (entity->GetGMLevel() > GAME_MASTER_LEVEL_CIVILIAN && user->GetMaxGMLevel() == GAME_MASTER_LEVEL_JUNIOR_DEVELOPER)) { WorldPackets::SendGMLevelChange(sysAddr, true, user->GetMaxGMLevel(), entity->GetGMLevel(), GAME_MASTER_LEVEL_CIVILIAN); GameMessages::SendChatModeUpdate(entity->GetObjectID(), GAME_MASTER_LEVEL_CIVILIAN); entity->SetGMLevel(GAME_MASTER_LEVEL_CIVILIAN); @@ -185,15 +178,13 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit return; } - if (chatCommand == "who") - { + if (chatCommand == "who") { ChatPackets::SendSystemMessage( sysAddr, u"Players in this instance: (" + GeneralUtils::to_u16string(Player::GetAllPlayers().size()) + u")" ); - for (auto* player : Player::GetAllPlayers()) - { + for (auto* player : Player::GetAllPlayers()) { const auto& name = player->GetCharacter()->GetName(); ChatPackets::SendSystemMessage( @@ -204,15 +195,12 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit } if (chatCommand == "ping") { - if (!args.empty() && args[0] == "-l") - { + if (!args.empty() && args[0] == "-l") { std::stringstream message; message << "Your latest ping: " << std::to_string(Game::server->GetLatestPing(sysAddr)) << "ms"; ChatPackets::SendSystemMessage(sysAddr, GeneralUtils::ASCIIToUTF16(message.str())); - } - else - { + } else { std::stringstream message; message << "Your average ping: " << std::to_string(Game::server->GetPing(sysAddr)) << "ms"; @@ -221,36 +209,30 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit return; } - if (chatCommand == "skip-ags") - { + if (chatCommand == "skip-ags") { auto* missionComponent = entity->GetComponent(); - if (missionComponent != nullptr && missionComponent->HasMission(479)) - { + if (missionComponent != nullptr && missionComponent->HasMission(479)) { missionComponent->CompleteMission(479); } } - if (chatCommand == "skip-sg") - { + if (chatCommand == "skip-sg") { auto* missionComponent = entity->GetComponent(); - if (missionComponent != nullptr && missionComponent->HasMission(229)) - { + if (missionComponent != nullptr && missionComponent->HasMission(229)) { missionComponent->CompleteMission(229); } } - if (chatCommand == "fix-stats") - { + if (chatCommand == "fix-stats") { // Reset skill component and buff component auto* skillComponent = entity->GetComponent(); auto* buffComponent = entity->GetComponent(); auto* destroyableComponent = entity->GetComponent(); // If any of the components are nullptr, return - if (skillComponent == nullptr || buffComponent == nullptr || destroyableComponent == nullptr) - { + if (skillComponent == nullptr || buffComponent == nullptr || destroyableComponent == nullptr) { return; } @@ -264,8 +246,7 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit destroyableComponent->FixStats(); } - if (chatCommand == "credits" || chatCommand == "info") - { + if (chatCommand == "credits" || chatCommand == "info") { const auto& customText = chatCommand == "credits" ? VanityUtilities::ParseMarkdown("./vanity/CREDITS.md") : VanityUtilities::ParseMarkdown("./vanity/INFO.md"); { @@ -279,8 +260,7 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit GameMessages::SendUIMessageServerToSingleClient(entity, entity->GetSystemAddress(), "pushGameState", &args); } - entity->AddCallbackTimer(0.5f, [customText, entity] () - { + entity->AddCallbackTimer(0.5f, [customText, entity]() { AMFArrayValue args; auto* text = new AMFStringValue(); @@ -292,7 +272,7 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit Game::logger->Log("SlashCommandHandler", "Sending %s", customText.c_str()); GameMessages::SendUIMessageServerToSingleClient(entity, entity->GetSystemAddress(), "ToggleStoryBox", &args); - }); + }); return; } @@ -314,27 +294,26 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit const auto objid = entity->GetObjectID(); - ZoneInstanceManager::Instance()->RequestZoneTransfer(Game::server, newZone, 0, false, [objid](bool mythranShift, uint32_t zoneID, uint32_t zoneInstance, uint32_t zoneClone, std::string serverIP, uint16_t serverPort) - { - auto* entity = EntityManager::Instance()->GetEntity(objid); + ZoneInstanceManager::Instance()->RequestZoneTransfer(Game::server, newZone, 0, false, [objid](bool mythranShift, uint32_t zoneID, uint32_t zoneInstance, uint32_t zoneClone, std::string serverIP, uint16_t serverPort) { + auto* entity = EntityManager::Instance()->GetEntity(objid); - if (entity == nullptr) { - return; - } + if (entity == nullptr) { + return; + } - const auto sysAddr = entity->GetSystemAddress(); + const auto sysAddr = entity->GetSystemAddress(); - Game::logger->Log("UserManager", "Transferring %s to Zone %i (Instance %i | Clone %i | Mythran Shift: %s) with IP %s and Port %i", entity->GetCharacter()->GetName().c_str(), zoneID, zoneInstance, zoneClone, mythranShift == true ? "true" : "false", serverIP.c_str(), serverPort); + Game::logger->Log("UserManager", "Transferring %s to Zone %i (Instance %i | Clone %i | Mythran Shift: %s) with IP %s and Port %i", entity->GetCharacter()->GetName().c_str(), zoneID, zoneInstance, zoneClone, mythranShift == true ? "true" : "false", serverIP.c_str(), serverPort); - if (entity->GetCharacter()) { - entity->GetCharacter()->SetZoneID(zoneID); - entity->GetCharacter()->SetZoneInstance(zoneInstance); - entity->GetCharacter()->SetZoneClone(zoneClone); - } + if (entity->GetCharacter()) { + entity->GetCharacter()->SetZoneID(zoneID); + entity->GetCharacter()->SetZoneInstance(zoneInstance); + entity->GetCharacter()->SetZoneClone(zoneClone); + } - entity->GetCharacter()->SaveXMLToDatabase(); + entity->GetCharacter()->SaveXMLToDatabase(); - WorldPackets::SendTransferToWorld(sysAddr, serverIP, serverPort, mythranShift); + WorldPackets::SendTransferToWorld(sysAddr, serverIP, serverPort, mythranShift); }); } @@ -342,19 +321,18 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit ChatPackets::SendSystemMessage(sysAddr, u"Requesting private map..."); const auto& password = args[0]; - ZoneInstanceManager::Instance()->RequestPrivateZone(Game::server, false, password, [=](bool mythranShift, uint32_t zoneID, uint32_t zoneInstance, uint32_t zoneClone, std::string serverIP, uint16_t serverPort) - { - Game::logger->Log("UserManager", "Transferring %s to Zone %i (Instance %i | Clone %i | Mythran Shift: %s) with IP %s and Port %i", sysAddr.ToString(), zoneID, zoneInstance, zoneClone, mythranShift == true ? "true" : "false", serverIP.c_str(), serverPort); + ZoneInstanceManager::Instance()->RequestPrivateZone(Game::server, false, password, [=](bool mythranShift, uint32_t zoneID, uint32_t zoneInstance, uint32_t zoneClone, std::string serverIP, uint16_t serverPort) { + Game::logger->Log("UserManager", "Transferring %s to Zone %i (Instance %i | Clone %i | Mythran Shift: %s) with IP %s and Port %i", sysAddr.ToString(), zoneID, zoneInstance, zoneClone, mythranShift == true ? "true" : "false", serverIP.c_str(), serverPort); - if (entity->GetCharacter()) { - entity->GetCharacter()->SetZoneID(zoneID); - entity->GetCharacter()->SetZoneInstance(zoneInstance); - entity->GetCharacter()->SetZoneClone(zoneClone); - } + if (entity->GetCharacter()) { + entity->GetCharacter()->SetZoneID(zoneID); + entity->GetCharacter()->SetZoneInstance(zoneInstance); + entity->GetCharacter()->SetZoneClone(zoneClone); + } - entity->GetCharacter()->SaveXMLToDatabase(); + entity->GetCharacter()->SaveXMLToDatabase(); - WorldPackets::SendTransferToWorld(sysAddr, serverIP, serverPort, mythranShift); + WorldPackets::SendTransferToWorld(sysAddr, serverIP, serverPort, mythranShift); }); } @@ -391,8 +369,8 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit auto stmt = Database::CreatePreppedStmt("INSERT INTO command_log (character_id, command) VALUES (?, ?);"); stmt->setInt(1, entity->GetCharacter()->GetID()); stmt->setString(2, GeneralUtils::UTF16ToWTF8(command).c_str()); - stmt->execute(); - delete stmt; + stmt->execute(); + delete stmt; if (chatCommand == "setminifig" && args.size() == 2 && entity->GetGMLevel() >= GAME_MASTER_LEVEL_FORUM_MODERATOR) { // could break characters so only allow if GM > 0 int32_t minifigItemId; @@ -456,8 +434,7 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit if (chatCommand == "unlock-emote" && entity->GetGMLevel() >= GAME_MASTER_LEVEL_DEVELOPER) { int32_t emoteID; - if (!GeneralUtils::TryParse(args[0], emoteID)) - { + if (!GeneralUtils::TryParse(args[0], emoteID)) { ChatPackets::SendSystemMessage(sysAddr, u"Invalid emote ID."); return; } @@ -484,20 +461,17 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit return; } - if (chatCommand == "speedboost" && args.size() == 1 && entity->GetGMLevel() >= GAME_MASTER_LEVEL_DEVELOPER) - { + if (chatCommand == "speedboost" && args.size() == 1 && entity->GetGMLevel() >= GAME_MASTER_LEVEL_DEVELOPER) { float boost; - if (!GeneralUtils::TryParse(args[0], boost)) - { + if (!GeneralUtils::TryParse(args[0], boost)) { ChatPackets::SendSystemMessage(sysAddr, u"Invalid boost."); return; } auto* controllablePhysicsComponent = entity->GetComponent(); - if (controllablePhysicsComponent == nullptr) - { + if (controllablePhysicsComponent == nullptr) { return; } @@ -519,8 +493,7 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit if (chatCommand == "setcontrolscheme" && args.size() == 1 && entity->GetGMLevel() >= GAME_MASTER_LEVEL_DEVELOPER) { uint32_t scheme; - if (!GeneralUtils::TryParse(args[0], scheme)) - { + if (!GeneralUtils::TryParse(args[0], scheme)) { ChatPackets::SendSystemMessage(sysAddr, u"Invalid control scheme."); return; } @@ -533,8 +506,7 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit if (chatCommand == "approveproperty" && entity->GetGMLevel() >= GAME_MASTER_LEVEL_LEAD_MODERATOR) { - if (PropertyManagementComponent::Instance() != nullptr) - { + if (PropertyManagementComponent::Instance() != nullptr) { PropertyManagementComponent::Instance()->UpdateApprovedStatus(true); } @@ -571,15 +543,13 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit uint32_t size; - if (!GeneralUtils::TryParse(args[0], size)) - { + if (!GeneralUtils::TryParse(args[0], size)) { ChatPackets::SendSystemMessage(sysAddr, u"Invalid size."); return; } InventoryComponent* inventory = static_cast(entity->GetComponent(COMPONENT_TYPE_INVENTORY)); - if (inventory) - { + if (inventory) { auto* items = inventory->GetInventory(ITEMS); items->SetSize(size); @@ -602,8 +572,7 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit while (std::getline(infile, line)) { SlashCommandHandler::HandleChatCommand(GeneralUtils::ASCIIToUTF16(line), entity, sysAddr); } - } - else { + } else { ChatPackets::SendSystemMessage(sysAddr, u"Unknown macro! Is the filename right?"); } @@ -615,8 +584,7 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit uint32_t missionID; - if (!GeneralUtils::TryParse(args[0], missionID)) - { + if (!GeneralUtils::TryParse(args[0], missionID)) { ChatPackets::SendSystemMessage(sysAddr, u"Invalid mission id."); return; } @@ -631,8 +599,7 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit uint32_t missionID; - if (!GeneralUtils::TryParse(args[0], missionID)) - { + if (!GeneralUtils::TryParse(args[0], missionID)) { ChatPackets::SendSystemMessage(sysAddr, u"Invalid mission id."); return; } @@ -642,12 +609,10 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit return; } - if (chatCommand == "setflag" && entity->GetGMLevel() >= GAME_MASTER_LEVEL_DEVELOPER && args.size() == 1) - { + if (chatCommand == "setflag" && entity->GetGMLevel() >= GAME_MASTER_LEVEL_DEVELOPER && args.size() == 1) { uint32_t flagId; - if (!GeneralUtils::TryParse(args[0], flagId)) - { + if (!GeneralUtils::TryParse(args[0], flagId)) { ChatPackets::SendSystemMessage(sysAddr, u"Invalid flag id."); return; } @@ -655,12 +620,10 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit entity->GetCharacter()->SetPlayerFlag(flagId, true); } - if (chatCommand == "setflag" && entity->GetGMLevel() >= GAME_MASTER_LEVEL_DEVELOPER && args.size() == 2) - { + if (chatCommand == "setflag" && entity->GetGMLevel() >= GAME_MASTER_LEVEL_DEVELOPER && args.size() == 2) { uint32_t flagId; std::string onOffFlag = args[0]; - if (!GeneralUtils::TryParse(args[1], flagId)) - { + if (!GeneralUtils::TryParse(args[1], flagId)) { ChatPackets::SendSystemMessage(sysAddr, u"Invalid flag id."); return; } @@ -670,12 +633,10 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit } entity->GetCharacter()->SetPlayerFlag(flagId, onOffFlag == "on"); } - if (chatCommand == "clearflag" && entity->GetGMLevel() >= GAME_MASTER_LEVEL_DEVELOPER && args.size() == 1) - { + if (chatCommand == "clearflag" && entity->GetGMLevel() >= GAME_MASTER_LEVEL_DEVELOPER && args.size() == 1) { uint32_t flagId; - if (!GeneralUtils::TryParse(args[0], flagId)) - { + if (!GeneralUtils::TryParse(args[0], flagId)) { ChatPackets::SendSystemMessage(sysAddr, u"Invalid flag id."); return; } @@ -688,8 +649,7 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit uint32_t missionID; - if (!GeneralUtils::TryParse(args[0], missionID)) - { + if (!GeneralUtils::TryParse(args[0], missionID)) { ChatPackets::SendSystemMessage(sysAddr, u"Invalid mission id."); return; } @@ -782,28 +742,25 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit if (args.size() == 1) { uint32_t itemLOT; - if (!GeneralUtils::TryParse(args[0], itemLOT)) - { + if (!GeneralUtils::TryParse(args[0], itemLOT)) { ChatPackets::SendSystemMessage(sysAddr, u"Invalid item LOT."); return; } - InventoryComponent * inventory = static_cast(entity->GetComponent(COMPONENT_TYPE_INVENTORY)); + InventoryComponent* inventory = static_cast(entity->GetComponent(COMPONENT_TYPE_INVENTORY)); inventory->AddItem(itemLOT, 1, eLootSourceType::LOOT_SOURCE_MODERATION); - } else if(args.size() == 2) { + } else if (args.size() == 2) { uint32_t itemLOT; - if (!GeneralUtils::TryParse(args[0], itemLOT)) - { + if (!GeneralUtils::TryParse(args[0], itemLOT)) { ChatPackets::SendSystemMessage(sysAddr, u"Invalid item LOT."); return; } uint32_t count; - if (!GeneralUtils::TryParse(args[1], count)) - { + if (!GeneralUtils::TryParse(args[1], count)) { ChatPackets::SendSystemMessage(sysAddr, u"Invalid item count."); return; } @@ -811,8 +768,7 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit InventoryComponent* inventory = static_cast(entity->GetComponent(COMPONENT_TYPE_INVENTORY)); inventory->AddItem(itemLOT, count, eLootSourceType::LOOT_SOURCE_MODERATION); - } - else { + } else { ChatPackets::SendSystemMessage(sysAddr, u"Correct usage: /gmadditem "); } } @@ -832,8 +788,7 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit delete stmt; delete res; - if (receiverID == 0) - { + if (receiverID == 0) { ChatPackets::SendSystemMessage(sysAddr, u"Failed to find that player"); return; @@ -841,8 +796,7 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit uint32_t lot; - if (!GeneralUtils::TryParse(args[1], lot)) - { + if (!GeneralUtils::TryParse(args[1], lot)) { ChatPackets::SendSystemMessage(sysAddr, u"Invalid item lot."); return; } @@ -868,24 +822,20 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit return; } - if (chatCommand == "setname" && entity->GetGMLevel() >= GAME_MASTER_LEVEL_DEVELOPER) - { + if (chatCommand == "setname" && entity->GetGMLevel() >= GAME_MASTER_LEVEL_DEVELOPER) { std::string name = ""; - for (const auto& arg : args) - { + for (const auto& arg : args) { name += arg + " "; } GameMessages::SendSetName(entity->GetObjectID(), GeneralUtils::ASCIIToUTF16(name), UNASSIGNED_SYSTEM_ADDRESS); } - if (chatCommand == "title" && entity->GetGMLevel() >= GAME_MASTER_LEVEL_DEVELOPER) - { + if (chatCommand == "title" && entity->GetGMLevel() >= GAME_MASTER_LEVEL_DEVELOPER) { std::string name = entity->GetCharacter()->GetName() + " - "; - for (const auto& arg : args) - { + for (const auto& arg : args) { name += arg + " "; } @@ -893,47 +843,42 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit } if ((chatCommand == "teleport" || chatCommand == "tele") && entity->GetGMLevel() >= GAME_MASTER_LEVEL_JUNIOR_MODERATOR) { - NiPoint3 pos {}; + NiPoint3 pos{}; if (args.size() == 3) { float x, y, z; - if (!GeneralUtils::TryParse(args[0], x)) - { + if (!GeneralUtils::TryParse(args[0], x)) { ChatPackets::SendSystemMessage(sysAddr, u"Invalid x."); return; } - if (!GeneralUtils::TryParse(args[1], y)) - { + if (!GeneralUtils::TryParse(args[1], y)) { ChatPackets::SendSystemMessage(sysAddr, u"Invalid y."); return; } - if (!GeneralUtils::TryParse(args[2], z)) - { + if (!GeneralUtils::TryParse(args[2], z)) { ChatPackets::SendSystemMessage(sysAddr, u"Invalid z."); return; } - pos.SetX(x); - pos.SetY(y); - pos.SetZ(z); + pos.SetX(x); + pos.SetY(y); + pos.SetZ(z); - Game::logger->Log("SlashCommandHandler", "Teleporting objectID: %llu to %f, %f, %f", entity->GetObjectID(), pos.x, pos.y, pos.z); - GameMessages::SendTeleport(entity->GetObjectID(), pos, NiQuaternion(), sysAddr); - } else if (args.size() == 2) { + Game::logger->Log("SlashCommandHandler", "Teleporting objectID: %llu to %f, %f, %f", entity->GetObjectID(), pos.x, pos.y, pos.z); + GameMessages::SendTeleport(entity->GetObjectID(), pos, NiQuaternion(), sysAddr); + } else if (args.size() == 2) { float x, z; - if (!GeneralUtils::TryParse(args[0], x)) - { + if (!GeneralUtils::TryParse(args[0], x)) { ChatPackets::SendSystemMessage(sysAddr, u"Invalid x."); return; } - if (!GeneralUtils::TryParse(args[1], z)) - { + if (!GeneralUtils::TryParse(args[1], z)) { ChatPackets::SendSystemMessage(sysAddr, u"Invalid z."); return; } @@ -942,24 +887,21 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit pos.SetY(0.0f); pos.SetZ(z); - Game::logger->Log("SlashCommandHandler", "Teleporting objectID: %llu to X: %f, Z: %f", entity->GetObjectID(), pos.x, pos.z); - GameMessages::SendTeleport(entity->GetObjectID(), pos, NiQuaternion(), sysAddr); - } else { - ChatPackets::SendSystemMessage(sysAddr, u"Correct usage: /teleport () - if no Y given, will teleport to the height of the terrain (or any physics object)."); - } + Game::logger->Log("SlashCommandHandler", "Teleporting objectID: %llu to X: %f, Z: %f", entity->GetObjectID(), pos.x, pos.z); + GameMessages::SendTeleport(entity->GetObjectID(), pos, NiQuaternion(), sysAddr); + } else { + ChatPackets::SendSystemMessage(sysAddr, u"Correct usage: /teleport () - if no Y given, will teleport to the height of the terrain (or any physics object)."); + } auto* possessorComponent = entity->GetComponent(); - if (possessorComponent != nullptr) - { + if (possessorComponent != nullptr) { auto* possassableEntity = EntityManager::Instance()->GetEntity(possessorComponent->GetPossessable()); - if (possassableEntity != nullptr) - { + if (possassableEntity != nullptr) { auto* vehiclePhysicsComponent = possassableEntity->GetComponent(); - if (vehiclePhysicsComponent != nullptr) - { + if (vehiclePhysicsComponent != nullptr) { vehiclePhysicsComponent->SetPosition(pos); EntityManager::Instance()->SerializeEntity(possassableEntity); @@ -970,22 +912,19 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit } } - if (chatCommand == "tpall" && entity->GetGMLevel() >= GAME_MASTER_LEVEL_DEVELOPER) - { + if (chatCommand == "tpall" && entity->GetGMLevel() >= GAME_MASTER_LEVEL_DEVELOPER) { const auto pos = entity->GetPosition(); const auto characters = EntityManager::Instance()->GetEntitiesByComponent(COMPONENT_TYPE_CHARACTER); - for (auto* character : characters) - { + for (auto* character : characters) { GameMessages::SendTeleport(character->GetObjectID(), pos, NiQuaternion(), character->GetSystemAddress()); } return; } - if (chatCommand == "dismount" && entity->GetGMLevel() >= GAME_MASTER_LEVEL_DEVELOPER) - { + if (chatCommand == "dismount" && entity->GetGMLevel() >= GAME_MASTER_LEVEL_DEVELOPER) { PossessorComponent* possessorComponent; if (entity->TryGetComponent(COMPONENT_TYPE_POSSESSOR, possessorComponent)) { Entity* vehicle = EntityManager::Instance()->GetEntity(possessorComponent->GetPossessable()); @@ -1011,16 +950,14 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit uint32_t accountId = 0; LWOOBJID characterId = 0; - if (player == nullptr) - { + if (player == nullptr) { auto* accountQuery = Database::CreatePreppedStmt("SELECT account_id, id FROM charinfo WHERE name=? LIMIT 1;"); accountQuery->setString(1, args[0]); auto result = accountQuery->executeQuery(); - if (result->rowsCount() > 0) - { + if (result->rowsCount() > 0) { while (result->next()) { accountId = result->getUInt(1); characterId = result->getUInt64(2); @@ -1033,15 +970,12 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit delete accountQuery; delete result; - if (accountId == 0) - { + if (accountId == 0) { ChatPackets::SendSystemMessage(sysAddr, u"Count not find player of name: " + GeneralUtils::ASCIIToUTF16(args[0])); return; } - } - else - { + } else { accountId = player->GetParentUser()->GetAccountID(); characterId = player->GetCharacter()->GetID(); } @@ -1050,21 +984,17 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit time_t expire = 1; // Default to indefinate mute - if (args.size() >= 2) - { + if (args.size() >= 2) { uint32_t days = 0; uint32_t hours = 0; - if (!GeneralUtils::TryParse(args[1], days)) - { + if (!GeneralUtils::TryParse(args[1], days)) { ChatPackets::SendSystemMessage(sysAddr, u"Invalid days."); return; } - if (args.size() >= 3) - { - if (!GeneralUtils::TryParse(args[2], hours)) - { + if (args.size() >= 3) { + if (!GeneralUtils::TryParse(args[2], hours)) { ChatPackets::SendSystemMessage(sysAddr, u"Invalid hours."); return; @@ -1085,9 +1015,8 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit char buffer[32] = "brought up for review.\0"; - if (expire != 1) - { - std::tm * ptm = std::localtime(&expire); + if (expire != 1) { + std::tm* ptm = std::localtime(&expire); // Format: Mo, 15.06.2009 20:20:00 std::strftime(buffer, 32, "%a, %d.%m.%Y %H:%M:%S", ptm); } @@ -1104,8 +1033,7 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit bitStream.Write(expire); Game::chatServer->Send(&bitStream, SYSTEM_PRIORITY, RELIABLE, 0, Game::chatSysAddr, false); - } - else { + } else { ChatPackets::SendSystemMessage(sysAddr, u"Correct usage: /mute "); } } @@ -1114,8 +1042,7 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit if (args.size() == 1) { auto* player = Player::GetPlayer(args[0]); - if (player == nullptr) - { + if (player == nullptr) { ChatPackets::SendSystemMessage(sysAddr, u"Count not find player of name: " + GeneralUtils::ASCIIToUTF16(args[0])); return; @@ -1124,8 +1051,7 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit Game::server->Disconnect(player->GetSystemAddress(), SERVER_DISCON_KICK); ChatPackets::SendSystemMessage(sysAddr, u"Kicked: " + GeneralUtils::ASCIIToUTF16(args[0])); - } - else { + } else { ChatPackets::SendSystemMessage(sysAddr, u"Correct usage: /kick "); } } @@ -1136,31 +1062,26 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit uint32_t accountId = 0; - if (player == nullptr) - { + if (player == nullptr) { auto* accountQuery = Database::CreatePreppedStmt("SELECT account_id FROM charinfo WHERE name=? LIMIT 1;"); accountQuery->setString(1, args[0]); auto result = accountQuery->executeQuery(); - if (result->rowsCount() > 0) - { + if (result->rowsCount() > 0) { while (result->next()) accountId = result->getUInt(1); } delete accountQuery; delete result; - if (accountId == 0) - { + if (accountId == 0) { ChatPackets::SendSystemMessage(sysAddr, u"Count not find player of name: " + GeneralUtils::ASCIIToUTF16(args[0])); return; } - } - else - { + } else { accountId = player->GetParentUser()->GetAccountID(); } @@ -1172,21 +1093,19 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit delete userUpdate; - if (player != nullptr) - { + if (player != nullptr) { Game::server->Disconnect(player->GetSystemAddress(), SERVER_DISCON_KICK); } ChatPackets::SendSystemMessage(sysAddr, u"Banned: " + GeneralUtils::ASCIIToUTF16(args[0])); - } - else { + } else { ChatPackets::SendSystemMessage(sysAddr, u"Correct usage: /ban "); } } //------------------------------------------------- - if (chatCommand == "buffme" && entity->GetGMLevel() >= GAME_MASTER_LEVEL_DEVELOPER) { + if (chatCommand == "buffme" && entity->GetGMLevel() >= GAME_MASTER_LEVEL_DEVELOPER) { auto dest = static_cast(entity->GetComponent(COMPONENT_TYPE_DESTROYABLE)); if (dest) { dest->SetHealth(999); @@ -1196,14 +1115,13 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit dest->SetImagination(999); dest->SetMaxImagination(999.0f); } - EntityManager::Instance()->SerializeEntity(entity); - } + EntityManager::Instance()->SerializeEntity(entity); + } if (chatCommand == "startcelebration" && entity->GetGMLevel() >= GAME_MASTER_LEVEL_DEVELOPER && args.size() == 1) { int32_t celebration; - if (!GeneralUtils::TryParse(args[0], celebration)) - { + if (!GeneralUtils::TryParse(args[0], celebration)) { ChatPackets::SendSystemMessage(sysAddr, u"Invalid celebration."); return; } @@ -1211,7 +1129,7 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit GameMessages::SendStartCelebrationEffect(entity, entity->GetSystemAddress(), celebration); } - if (chatCommand == "buffmed" && entity->GetGMLevel() >= GAME_MASTER_LEVEL_DEVELOPER) { + if (chatCommand == "buffmed" && entity->GetGMLevel() >= GAME_MASTER_LEVEL_DEVELOPER) { auto dest = static_cast(entity->GetComponent(COMPONENT_TYPE_DESTROYABLE)); if (dest) { dest->SetHealth(9); @@ -1221,10 +1139,10 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit dest->SetImagination(9); dest->SetMaxImagination(9.0f); } - EntityManager::Instance()->SerializeEntity(entity); - } + EntityManager::Instance()->SerializeEntity(entity); + } - if (chatCommand == "refillstats" && entity->GetGMLevel() >= GAME_MASTER_LEVEL_DEVELOPER) { + if (chatCommand == "refillstats" && entity->GetGMLevel() >= GAME_MASTER_LEVEL_DEVELOPER) { auto dest = static_cast(entity->GetComponent(COMPONENT_TYPE_DESTROYABLE)); if (dest) { @@ -1233,8 +1151,8 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit dest->SetImagination((int)dest->GetMaxImagination()); } - EntityManager::Instance()->SerializeEntity(entity); - } + EntityManager::Instance()->SerializeEntity(entity); + } if (chatCommand == "lookup" && entity->GetGMLevel() >= GAME_MASTER_LEVEL_DEVELOPER && args.size() == 1) { auto query = CDClientDatabase::CreatePreppedStmt( @@ -1245,21 +1163,20 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit auto tables = query.execQuery(); - while (!tables.eof()) { - std::string message = std::to_string(tables.getIntField(0)) + " - " + tables.getStringField(1); - ChatPackets::SendSystemMessage(sysAddr, GeneralUtils::ASCIIToUTF16(message, message.size())); - tables.nextRow(); - } - } + while (!tables.eof()) { + std::string message = std::to_string(tables.getIntField(0)) + " - " + tables.getStringField(1); + ChatPackets::SendSystemMessage(sysAddr, GeneralUtils::ASCIIToUTF16(message, message.size())); + tables.nextRow(); + } + } - if (chatCommand == "spawn" && entity->GetGMLevel() >= GAME_MASTER_LEVEL_DEVELOPER && args.size() >= 1) { - ControllablePhysicsComponent* comp = static_cast(entity->GetComponent(COMPONENT_TYPE_CONTROLLABLE_PHYSICS)); - if (!comp) return; + if (chatCommand == "spawn" && entity->GetGMLevel() >= GAME_MASTER_LEVEL_DEVELOPER && args.size() >= 1) { + ControllablePhysicsComponent* comp = static_cast(entity->GetComponent(COMPONENT_TYPE_CONTROLLABLE_PHYSICS)); + if (!comp) return; uint32_t lot; - if (!GeneralUtils::TryParse(args[0], lot)) - { + if (!GeneralUtils::TryParse(args[0], lot)) { ChatPackets::SendSystemMessage(sysAddr, u"Invalid lot."); return; } @@ -1285,8 +1202,7 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit if ((chatCommand == "giveuscore") && args.size() == 1 && entity->GetGMLevel() >= GAME_MASTER_LEVEL_DEVELOPER) { int32_t uscore; - if (!GeneralUtils::TryParse(args[0], uscore)) - { + if (!GeneralUtils::TryParse(args[0], uscore)) { ChatPackets::SendSystemMessage(sysAddr, u"Invalid uscore."); return; } @@ -1297,8 +1213,7 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit GameMessages::SendModifyLEGOScore(entity, entity->GetSystemAddress(), uscore, eLootSourceType::LOOT_SOURCE_MODERATION); } - if ((chatCommand == "setlevel") && args.size() >= 1 && entity->GetGMLevel() >= GAME_MASTER_LEVEL_DEVELOPER) - { + if ((chatCommand == "setlevel") && args.size() >= 1 && entity->GetGMLevel() >= GAME_MASTER_LEVEL_DEVELOPER) { // We may be trying to set a specific players level to a level. If so override the entity with the requested players. std::string requestedPlayerToSetLevelOf = ""; if (args.size() > 1) { @@ -1322,8 +1237,7 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit uint32_t oldLevel; // first check the level is valid - if (!GeneralUtils::TryParse(args[0], requestedLevel)) - { + if (!GeneralUtils::TryParse(args[0], requestedLevel)) { ChatPackets::SendSystemMessage(sysAddr, u"Invalid level."); return; } @@ -1345,7 +1259,7 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit // handle level up for each level we have passed if we set our level to be higher than the current one. if (oldLevel < requestedLevel) { while (oldLevel < requestedLevel) { - oldLevel+=1; + oldLevel += 1; levelComponent->SetLevel(oldLevel); levelComponent->HandleLevelUp(); } @@ -1354,15 +1268,15 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit } if (requestedPlayerToSetLevelOf != "") { - ChatPackets::SendSystemMessage( - sysAddr, u"Set " + GeneralUtils::ASCIIToUTF16(requestedPlayerToSetLevelOf) + u"'s level to " + GeneralUtils::to_u16string(requestedLevel) + - u" and UScore to " + GeneralUtils::to_u16string(characterComponent->GetUScore()) + - u". Relog to see changes."); + ChatPackets::SendSystemMessage( + sysAddr, u"Set " + GeneralUtils::ASCIIToUTF16(requestedPlayerToSetLevelOf) + u"'s level to " + GeneralUtils::to_u16string(requestedLevel) + + u" and UScore to " + GeneralUtils::to_u16string(characterComponent->GetUScore()) + + u". Relog to see changes."); } else { - ChatPackets::SendSystemMessage( - sysAddr, u"Set your level to " + GeneralUtils::to_u16string(requestedLevel) + - u" and UScore to " + GeneralUtils::to_u16string(characterComponent->GetUScore()) + - u". Relog to see changes."); + ChatPackets::SendSystemMessage( + sysAddr, u"Set your level to " + GeneralUtils::to_u16string(requestedLevel) + + u" and UScore to " + GeneralUtils::to_u16string(characterComponent->GetUScore()) + + u". Relog to see changes."); } return; } @@ -1370,7 +1284,7 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit if (chatCommand == "pos" && entity->GetGMLevel() >= GAME_MASTER_LEVEL_DEVELOPER) { const auto position = entity->GetPosition(); - ChatPackets::SendSystemMessage(sysAddr, u"<" + (GeneralUtils::to_u16string(position.x)) + u", " + (GeneralUtils::to_u16string(position.y)) + u", " + (GeneralUtils::to_u16string(position.z)) + u">"); + ChatPackets::SendSystemMessage(sysAddr, u"<" + (GeneralUtils::to_u16string(position.x)) + u", " + (GeneralUtils::to_u16string(position.y)) + u", " + (GeneralUtils::to_u16string(position.z)) + u">"); std::cout << position.x << ", " << position.y << ", " << position.z << std::endl; } @@ -1378,7 +1292,7 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit if (chatCommand == "rot" && entity->GetGMLevel() >= GAME_MASTER_LEVEL_DEVELOPER) { const auto rotation = entity->GetRotation(); - ChatPackets::SendSystemMessage(sysAddr, u"<" + (GeneralUtils::to_u16string(rotation.w)) + u", " + (GeneralUtils::to_u16string(rotation.x)) + u", " + (GeneralUtils::to_u16string(rotation.y)) + u", " + (GeneralUtils::to_u16string(rotation.z)) + u">"); + ChatPackets::SendSystemMessage(sysAddr, u"<" + (GeneralUtils::to_u16string(rotation.w)) + u", " + (GeneralUtils::to_u16string(rotation.x)) + u", " + (GeneralUtils::to_u16string(rotation.y)) + u", " + (GeneralUtils::to_u16string(rotation.z)) + u">"); std::cout << rotation.w << ", " << rotation.x << ", " << rotation.y << ", " << rotation.z << std::endl; } @@ -1401,8 +1315,7 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit if ((chatCommand == "freemoney" && entity->GetGMLevel() >= GAME_MASTER_LEVEL_DEVELOPER) && args.size() == 1) { int32_t money; - if (!GeneralUtils::TryParse(args[0], money)) - { + if (!GeneralUtils::TryParse(args[0], money)) { ChatPackets::SendSystemMessage(sysAddr, u"Invalid money."); return; } @@ -1414,8 +1327,7 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit if ((chatCommand == "setcurrency") && args.size() == 1 && entity->GetGMLevel() >= GAME_MASTER_LEVEL_DEVELOPER) { int32_t money; - if (!GeneralUtils::TryParse(args[0], money)) - { + if (!GeneralUtils::TryParse(args[0], money)) { ChatPackets::SendSystemMessage(sysAddr, u"Invalid money."); return; } @@ -1425,54 +1337,46 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit } // Allow for this on even while not a GM, as it sometimes toggles incorrrectly. - if (chatCommand == "gminvis" && entity->GetParentUser()->GetMaxGMLevel() >= GAME_MASTER_LEVEL_DEVELOPER) - { + if (chatCommand == "gminvis" && entity->GetParentUser()->GetMaxGMLevel() >= GAME_MASTER_LEVEL_DEVELOPER) { GameMessages::SendToggleGMInvis(entity->GetObjectID(), true, UNASSIGNED_SYSTEM_ADDRESS); return; } - if (chatCommand == "gmimmune" && args.size() >= 1 && entity->GetGMLevel() >= GAME_MASTER_LEVEL_DEVELOPER) - { + if (chatCommand == "gmimmune" && args.size() >= 1 && entity->GetGMLevel() >= GAME_MASTER_LEVEL_DEVELOPER) { auto* destroyableComponent = entity->GetComponent(); int32_t state = false; - if (!GeneralUtils::TryParse(args[0], state)) - { + if (!GeneralUtils::TryParse(args[0], state)) { ChatPackets::SendSystemMessage(sysAddr, u"Invalid state."); return; } - if (destroyableComponent != nullptr) - { + if (destroyableComponent != nullptr) { destroyableComponent->SetIsGMImmune(state); } return; } - if (chatCommand == "buff" && args.size() >= 2 && entity->GetGMLevel() >= GAME_MASTER_LEVEL_DEVELOPER) - { + if (chatCommand == "buff" && args.size() >= 2 && entity->GetGMLevel() >= GAME_MASTER_LEVEL_DEVELOPER) { auto* buffComponent = entity->GetComponent(); int32_t id = 0; int32_t duration = 0; - if (!GeneralUtils::TryParse(args[0], id)) - { + if (!GeneralUtils::TryParse(args[0], id)) { ChatPackets::SendSystemMessage(sysAddr, u"Invalid buff id."); return; } - if (!GeneralUtils::TryParse(args[1], duration)) - { + if (!GeneralUtils::TryParse(args[1], duration)) { ChatPackets::SendSystemMessage(sysAddr, u"Invalid buff duration."); return; } - if (buffComponent != nullptr) - { + if (buffComponent != nullptr) { buffComponent->ApplyBuff(id, duration, entity->GetObjectID()); } @@ -1485,25 +1389,21 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit LWOCLONEID cloneId = 0; bool force = false; - if (!GeneralUtils::TryParse(args[0], reqZone)) - { + if (!GeneralUtils::TryParse(args[0], reqZone)) { ChatPackets::SendSystemMessage(sysAddr, u"Invalid zone."); return; } - if (args.size() > 1) - { + if (args.size() > 1) { auto index = 1; - if (args[index] == "force") - { + if (args[index] == "force") { index++; force = true; } - if (args.size() > index && !GeneralUtils::TryParse(args[index], cloneId)) - { + if (args.size() > index && !GeneralUtils::TryParse(args[index], cloneId)) { ChatPackets::SendSystemMessage(sysAddr, u"Invalid clone id."); return; } @@ -1534,7 +1434,7 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit WorldPackets::SendTransferToWorld(sysAddr, serverIP, serverPort, mythranShift); return; - }); + }); } else { std::string msg = "ZoneID not found or allowed: "; msg.append(args[0]); @@ -1542,20 +1442,17 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit } } - if (chatCommand == "createprivate" && entity->GetGMLevel() >= GAME_MASTER_LEVEL_DEVELOPER && args.size() >= 3) - { + if (chatCommand == "createprivate" && entity->GetGMLevel() >= GAME_MASTER_LEVEL_DEVELOPER && args.size() >= 3) { uint32_t zone; - if (!GeneralUtils::TryParse(args[0], zone)) - { + if (!GeneralUtils::TryParse(args[0], zone)) { ChatPackets::SendSystemMessage(sysAddr, u"Invalid zone."); return; } uint32_t clone; - if (!GeneralUtils::TryParse(args[1], clone)) - { + if (!GeneralUtils::TryParse(args[1], clone)) { ChatPackets::SendSystemMessage(sysAddr, u"Invalid clone."); return; } @@ -1578,34 +1475,29 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit if ((chatCommand == "boost") && entity->GetGMLevel() >= GAME_MASTER_LEVEL_DEVELOPER) { auto* possessorComponent = entity->GetComponent(); - if (possessorComponent == nullptr) - { + if (possessorComponent == nullptr) { return; } auto* vehicle = EntityManager::Instance()->GetEntity(possessorComponent->GetPossessable()); - if (vehicle == nullptr) - { + if (vehicle == nullptr) { return; } GameMessages::SendVehicleAddPassiveBoostAction(vehicle->GetObjectID(), UNASSIGNED_SYSTEM_ADDRESS); } - if (chatCommand == "activatespawner" && entity->GetGMLevel() >= GAME_MASTER_LEVEL_DEVELOPER && args.size() >= 1) - { + if (chatCommand == "activatespawner" && entity->GetGMLevel() >= GAME_MASTER_LEVEL_DEVELOPER && args.size() >= 1) { auto spawners = dZoneManager::Instance()->GetSpawnersByName(args[0]); - for (auto* spawner : spawners) - { + for (auto* spawner : spawners) { spawner->Activate(); } spawners = dZoneManager::Instance()->GetSpawnersInGroup(args[0]); - for (auto* spawner : spawners) - { + for (auto* spawner : spawners) { spawner->Activate(); } } @@ -1636,25 +1528,21 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit } } - if (chatCommand == "triggerspawner" && entity->GetGMLevel() >= GAME_MASTER_LEVEL_DEVELOPER && args.size() >= 1) - { + if (chatCommand == "triggerspawner" && entity->GetGMLevel() >= GAME_MASTER_LEVEL_DEVELOPER && args.size() >= 1) { auto spawners = dZoneManager::Instance()->GetSpawnersByName(args[0]); - for (auto* spawner : spawners) - { + for (auto* spawner : spawners) { spawner->Spawn(); } spawners = dZoneManager::Instance()->GetSpawnersInGroup(args[0]); - for (auto* spawner : spawners) - { + for (auto* spawner : spawners) { spawner->Spawn(); } } - if (chatCommand == "reforge" && entity->GetGMLevel() >= GAME_MASTER_LEVEL_DEVELOPER && args.size() >= 2) - { + if (chatCommand == "reforge" && entity->GetGMLevel() >= GAME_MASTER_LEVEL_DEVELOPER && args.size() >= 2) { LOT baseItem; LOT reforgedItem; @@ -1665,14 +1553,13 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit if (inventoryComponent == nullptr) return; - std::vector data {}; + std::vector data{}; data.push_back(new LDFData(u"reforgedLOT", reforgedItem)); inventoryComponent->AddItem(baseItem, 1, eLootSourceType::LOOT_SOURCE_MODERATION, eInventoryType::INVALID, data); } - if (chatCommand == "crash" && entity->GetGMLevel() >= GAME_MASTER_LEVEL_OPERATOR) - { + if (chatCommand == "crash" && entity->GetGMLevel() >= GAME_MASTER_LEVEL_OPERATOR) { ChatPackets::SendSystemMessage(sysAddr, u"Crashing..."); int* badPtr = nullptr; @@ -1681,8 +1568,7 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit return; } - if (chatCommand == "config-set" && entity->GetGMLevel() >= GAME_MASTER_LEVEL_DEVELOPER && args.size() >= 2) - { + if (chatCommand == "config-set" && entity->GetGMLevel() >= GAME_MASTER_LEVEL_DEVELOPER && args.size() >= 2) { GameConfig::SetValue(args[0], args[1]); ChatPackets::SendSystemMessage( @@ -1690,28 +1576,21 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit ); } - if (chatCommand == "config-get" && entity->GetGMLevel() >= GAME_MASTER_LEVEL_DEVELOPER && args.size() >= 1) - { + if (chatCommand == "config-get" && entity->GetGMLevel() >= GAME_MASTER_LEVEL_DEVELOPER && args.size() >= 1) { const auto& value = GameConfig::GetValue(args[0]); - if (value.empty()) - { + if (value.empty()) { ChatPackets::SendSystemMessage(sysAddr, u"No value found for " + GeneralUtils::ASCIIToUTF16(args[0])); - } - else - { + } else { ChatPackets::SendSystemMessage(sysAddr, u"Value for " + GeneralUtils::ASCIIToUTF16(args[0]) + u": " + GeneralUtils::ASCIIToUTF16(value)); } } - if (chatCommand == "metrics" && entity->GetGMLevel() >= GAME_MASTER_LEVEL_DEVELOPER) - { - for (const auto variable : Metrics::GetAllMetrics()) - { + if (chatCommand == "metrics" && entity->GetGMLevel() >= GAME_MASTER_LEVEL_DEVELOPER) { + for (const auto variable : Metrics::GetAllMetrics()) { auto* metric = Metrics::GetMetric(variable); - if (metric == nullptr) - { + if (metric == nullptr) { continue; } @@ -1726,13 +1605,13 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit ChatPackets::SendSystemMessage( sysAddr, - u"Peak RSS: " + GeneralUtils::to_u16string((float) ((double) Metrics::GetPeakRSS() / 1.024e6)) + + u"Peak RSS: " + GeneralUtils::to_u16string((float)((double)Metrics::GetPeakRSS() / 1.024e6)) + u"MB" ); ChatPackets::SendSystemMessage( sysAddr, - u"Current RSS: " + GeneralUtils::to_u16string((float) ((double) Metrics::GetCurrentRSS() / 1.024e6)) + + u"Current RSS: " + GeneralUtils::to_u16string((float)((double)Metrics::GetCurrentRSS() / 1.024e6)) + u"MB" ); @@ -1776,13 +1655,12 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit + u" times. It ran " + GeneralUtils::to_u16string(totalRuns) + u" times. Averaging out at " - + GeneralUtils::to_u16string((float) totalRuns / loops); + + GeneralUtils::to_u16string((float)totalRuns / loops); ChatPackets::SendSystemMessage(sysAddr, message); } - if (chatCommand == "inspect" && entity->GetGMLevel() >= GAME_MASTER_LEVEL_DEVELOPER && args.size() >= 1) - { + if (chatCommand == "inspect" && entity->GetGMLevel() >= GAME_MASTER_LEVEL_DEVELOPER && args.size() >= 1) { Entity* closest = nullptr; int32_t component; @@ -1791,8 +1669,7 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit bool isLDF = false; - if (!GeneralUtils::TryParse(args[0], component)) - { + if (!GeneralUtils::TryParse(args[0], component)) { component = -1; ldf = GeneralUtils::ASCIIToUTF16(args[0]); @@ -1806,20 +1683,16 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit const auto candidates = EntityManager::Instance()->GetEntitiesByComponent(component); - for (auto* candidate : candidates) - { - if (candidate->GetLOT() == 1 || candidate->GetLOT() == 8092) - { + for (auto* candidate : candidates) { + if (candidate->GetLOT() == 1 || candidate->GetLOT() == 8092) { continue; } - if (isLDF && !candidate->HasVar(ldf)) - { + if (isLDF && !candidate->HasVar(ldf)) { continue; } - if (closest == nullptr) - { + if (closest == nullptr) { closest = candidate; closestDistance = NiPoint3::Distance(candidate->GetPosition(), reference); @@ -1829,16 +1702,14 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit const auto distance = NiPoint3::Distance(candidate->GetPosition(), reference); - if (distance < closestDistance) - { + if (distance < closestDistance) { closest = candidate; closestDistance = distance; } } - if (closest == nullptr) - { + if (closest == nullptr) { return; } @@ -1854,8 +1725,7 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit ChatPackets::SendSystemMessage(sysAddr, GeneralUtils::ASCIIToUTF16(header.str())); - for (const auto& pair : closest->GetComponents()) - { + for (const auto& pair : closest->GetComponents()) { auto id = pair.first; std::stringstream stream; @@ -1865,61 +1735,45 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit ChatPackets::SendSystemMessage(sysAddr, GeneralUtils::ASCIIToUTF16(stream.str())); } - if (args.size() >= 2) - { - if (args[1] == "-m" && args.size() >= 3) - { + if (args.size() >= 2) { + if (args[1] == "-m" && args.size() >= 3) { auto* movingPlatformComponent = closest->GetComponent(); int32_t value = 0; - if (movingPlatformComponent == nullptr || !GeneralUtils::TryParse(args[2], value)) - { + if (movingPlatformComponent == nullptr || !GeneralUtils::TryParse(args[2], value)) { return; } movingPlatformComponent->SetSerialized(true); - if (value == -1) - { + if (value == -1) { movingPlatformComponent->StopPathing(); - } - else - { + } else { movingPlatformComponent->GotoWaypoint(value); } EntityManager::Instance()->SerializeEntity(closest); - } - else if (args[1] == "-a" && args.size() >= 3) - { + } else if (args[1] == "-a" && args.size() >= 3) { GameMessages::SendPlayAnimation(closest, GeneralUtils::ASCIIToUTF16(args[2])); - } - else if (args[1] == "-s") - { - for (auto* entry : closest->GetSettings()) - { + } else if (args[1] == "-s") { + for (auto* entry : closest->GetSettings()) { ChatPackets::SendSystemMessage(sysAddr, GeneralUtils::ASCIIToUTF16(entry->GetString())); } ChatPackets::SendSystemMessage(sysAddr, u"------"); ChatPackets::SendSystemMessage(sysAddr, u"Spawner ID: " + GeneralUtils::to_u16string(closest->GetSpawnerID())); - } - else if (args[1] == "-p") - { + } else if (args[1] == "-p") { const auto postion = closest->GetPosition(); ChatPackets::SendSystemMessage( sysAddr, GeneralUtils::ASCIIToUTF16("< " + std::to_string(postion.x) + ", " + std::to_string(postion.y) + ", " + std::to_string(postion.z) + " >") ); - } - else if (args[1] == "-f") - { + } else if (args[1] == "-f") { auto* destuctable = closest->GetComponent(); - if (destuctable == nullptr) - { + if (destuctable == nullptr) { ChatPackets::SendSystemMessage(sysAddr, u"No destroyable component on this entity!"); return; } @@ -1927,44 +1781,36 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit ChatPackets::SendSystemMessage(sysAddr, u"Smashable: " + (GeneralUtils::to_u16string(destuctable->GetIsSmashable()))); ChatPackets::SendSystemMessage(sysAddr, u"Friendly factions:"); - for (const auto entry : destuctable->GetFactionIDs()) - { + for (const auto entry : destuctable->GetFactionIDs()) { ChatPackets::SendSystemMessage(sysAddr, (GeneralUtils::to_u16string(entry))); } ChatPackets::SendSystemMessage(sysAddr, u"Enemy factions:"); - for (const auto entry : destuctable->GetEnemyFactionsIDs()) - { + for (const auto entry : destuctable->GetEnemyFactionsIDs()) { ChatPackets::SendSystemMessage(sysAddr, (GeneralUtils::to_u16string(entry))); } - if (args.size() >= 3) - { + if (args.size() >= 3) { int32_t faction; - if (!GeneralUtils::TryParse(args[2], faction)) - { + if (!GeneralUtils::TryParse(args[2], faction)) { return; } destuctable->SetFaction(-1); destuctable->AddFaction(faction, true); } - } - else if (args[1] == "-t") - { + } else if (args[1] == "-t") { auto* phantomPhysicsComponent = closest->GetComponent(); - if (phantomPhysicsComponent != nullptr) - { + if (phantomPhysicsComponent != nullptr) { ChatPackets::SendSystemMessage(sysAddr, u"Type: " + (GeneralUtils::to_u16string(phantomPhysicsComponent->GetEffectType()))); const auto dir = phantomPhysicsComponent->GetDirection(); - ChatPackets::SendSystemMessage(sysAddr, u"Direction: <" + (GeneralUtils::to_u16string(dir.x)) + u", " + (GeneralUtils::to_u16string(dir.y)) + u", "+ (GeneralUtils::to_u16string(dir.z)) + u">"); + ChatPackets::SendSystemMessage(sysAddr, u"Direction: <" + (GeneralUtils::to_u16string(dir.x)) + u", " + (GeneralUtils::to_u16string(dir.y)) + u", " + (GeneralUtils::to_u16string(dir.z)) + u">"); ChatPackets::SendSystemMessage(sysAddr, u"Multiplier: " + (GeneralUtils::to_u16string(phantomPhysicsComponent->GetDirectionalMultiplier()))); ChatPackets::SendSystemMessage(sysAddr, u"Active: " + (GeneralUtils::to_u16string(phantomPhysicsComponent->GetPhysicsEffectActive()))); } - if (closest->GetTrigger() != nullptr) - { + if (closest->GetTrigger() != nullptr) { ChatPackets::SendSystemMessage(sysAddr, u"Trigger: " + (GeneralUtils::to_u16string(closest->GetTrigger()->id))); } } @@ -1974,7 +1820,7 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit bool SlashCommandHandler::CheckIfAccessibleZone(const unsigned int zoneID) { //We're gonna go ahead and presume we've got the db loaded already: - CDZoneTableTable * zoneTable = CDClientManager::Instance()->GetTable("ZoneTable"); + CDZoneTableTable* zoneTable = CDClientManager::Instance()->GetTable("ZoneTable"); const CDZoneTable* zone = zoneTable->Query(zoneID); if (zone != nullptr) { std::string zonePath = "./res/maps/" + zone->zoneName; diff --git a/dGame/dUtilities/SlashCommandHandler.h b/dGame/dUtilities/SlashCommandHandler.h index 32b267ef..9ef09a2f 100644 --- a/dGame/dUtilities/SlashCommandHandler.h +++ b/dGame/dUtilities/SlashCommandHandler.h @@ -12,10 +12,10 @@ class Entity; namespace SlashCommandHandler { - void HandleChatCommand(const std::u16string& command, Entity* entity, const SystemAddress& sysAddr); - bool CheckIfAccessibleZone(const unsigned int zoneID); + void HandleChatCommand(const std::u16string& command, Entity* entity, const SystemAddress& sysAddr); + bool CheckIfAccessibleZone(const unsigned int zoneID); - void SendAnnouncement(const std::string& title, const std::string& message); + void SendAnnouncement(const std::string& title, const std::string& message); }; #endif // SLASHCOMMANDHANDLER_H diff --git a/dGame/dUtilities/VanityUtilities.cpp b/dGame/dUtilities/VanityUtilities.cpp index 1b85077b..733d94c4 100644 --- a/dGame/dUtilities/VanityUtilities.cpp +++ b/dGame/dUtilities/VanityUtilities.cpp @@ -20,520 +20,513 @@ std::vector VanityUtilities::m_NPCs = {}; std::vector VanityUtilities::m_Parties = {}; std::vector VanityUtilities::m_PartyPhrases = {}; -void VanityUtilities::SpawnVanity() -{ - if (Game::config->GetValue("disable_vanity") == "1") { - return; - } +void VanityUtilities::SpawnVanity() { + if (Game::config->GetValue("disable_vanity") == "1") { + return; + } - const uint32_t zoneID = Game::server->GetZoneID(); + const uint32_t zoneID = Game::server->GetZoneID(); - ParseXML("./vanity/NPC.xml"); + ParseXML("./vanity/NPC.xml"); - // Loop through all parties - for (const auto& party : m_Parties) { - const auto chance = party.m_Chance; - const auto zone = party.m_Zone; + // Loop through all parties + for (const auto& party : m_Parties) { + const auto chance = party.m_Chance; + const auto zone = party.m_Zone; - if (zone != Game::server->GetZoneID()) { - continue; - } + if (zone != Game::server->GetZoneID()) { + continue; + } - float rate = GeneralUtils::GenerateRandomNumber(0, 1); - if (chance < rate) { - continue; - } + float rate = GeneralUtils::GenerateRandomNumber(0, 1); + if (chance < rate) { + continue; + } - // Copy m_NPCs into a new vector - std::vector npcList = m_NPCs; - std::vector taken = {}; + // Copy m_NPCs into a new vector + std::vector npcList = m_NPCs; + std::vector taken = {}; - Game::logger->Log("VanityUtilities", "Spawning party with %i locations", party.m_Locations.size()); + Game::logger->Log("VanityUtilities", "Spawning party with %i locations", party.m_Locations.size()); - // Loop through all locations - for (const auto& location : party.m_Locations) { - rate = GeneralUtils::GenerateRandomNumber(0, 1); - if (0.75f < rate) { - continue; - } + // Loop through all locations + for (const auto& location : party.m_Locations) { + rate = GeneralUtils::GenerateRandomNumber(0, 1); + if (0.75f < rate) { + continue; + } - // Get a random NPC - auto npcIndex = GeneralUtils::GenerateRandomNumber(0, npcList.size() - 1); + // Get a random NPC + auto npcIndex = GeneralUtils::GenerateRandomNumber(0, npcList.size() - 1); - while (std::find(taken.begin(), taken.end(), npcIndex) != taken.end()) { - npcIndex = GeneralUtils::GenerateRandomNumber(0, npcList.size() - 1); - } + while (std::find(taken.begin(), taken.end(), npcIndex) != taken.end()) { + npcIndex = GeneralUtils::GenerateRandomNumber(0, npcList.size() - 1); + } - const auto& npc = npcList[npcIndex]; + const auto& npc = npcList[npcIndex]; - taken.push_back(npcIndex); + taken.push_back(npcIndex); - // Spawn the NPC - std::vector data = { new LDFData>( - u"syncLDF", { u"custom_script_client" }), - new LDFData(u"custom_script_client", u"scripts\\ai\\SPEC\\MISSION_MINIGAME_CLIENT.lua") }; + // Spawn the NPC + std::vector data = { new LDFData>( + u"syncLDF", { u"custom_script_client" }), + new LDFData(u"custom_script_client", u"scripts\\ai\\SPEC\\MISSION_MINIGAME_CLIENT.lua") }; - // Spawn the NPC - auto* npcEntity = SpawnNPC(npc.m_LOT, npc.m_Name, location.m_Position, location.m_Rotation, npc.m_Equipment, data); + // Spawn the NPC + auto* npcEntity = SpawnNPC(npc.m_LOT, npc.m_Name, location.m_Position, location.m_Rotation, npc.m_Equipment, data); - npcEntity->SetVar>(u"chats", m_PartyPhrases); + npcEntity->SetVar>(u"chats", m_PartyPhrases); - SetupNPCTalk(npcEntity); - } + SetupNPCTalk(npcEntity); + } - return; - } + return; + } - // Loop through all NPCs - for (const auto& pair : m_NPCs) { - if (pair.m_Locations.find(Game::server->GetZoneID()) == pair.m_Locations.end()) - continue; + // Loop through all NPCs + for (const auto& pair : m_NPCs) { + if (pair.m_Locations.find(Game::server->GetZoneID()) == pair.m_Locations.end()) + continue; - const std::vector& locations = pair.m_Locations.at(Game::server->GetZoneID()); + const std::vector& locations = pair.m_Locations.at(Game::server->GetZoneID()); - // Pick a random location - const auto& location = locations[GeneralUtils::GenerateRandomNumber( - static_cast(0), static_cast(locations.size() - 1))]; + // Pick a random location + const auto& location = locations[GeneralUtils::GenerateRandomNumber( + static_cast(0), static_cast(locations.size() - 1))]; - float rate = GeneralUtils::GenerateRandomNumber(0, 1); - if (location.m_Chance < rate) { - continue; - } + float rate = GeneralUtils::GenerateRandomNumber(0, 1); + if (location.m_Chance < rate) { + continue; + } - std::vector data = { new LDFData>( - u"syncLDF", { u"custom_script_client" }), - new LDFData(u"custom_script_client", u"scripts\\ai\\SPEC\\MISSION_MINIGAME_CLIENT.lua") }; + std::vector data = { new LDFData>( + u"syncLDF", { u"custom_script_client" }), + new LDFData(u"custom_script_client", u"scripts\\ai\\SPEC\\MISSION_MINIGAME_CLIENT.lua") }; - // Spawn the NPC - auto* npc = SpawnNPC(pair.m_LOT, pair.m_Name, location.m_Position, location.m_Rotation, pair.m_Equipment, data); + // Spawn the NPC + auto* npc = SpawnNPC(pair.m_LOT, pair.m_Name, location.m_Position, location.m_Rotation, pair.m_Equipment, data); - npc->SetVar>(u"chats", pair.m_Phrases); + npc->SetVar>(u"chats", pair.m_Phrases); - auto* scriptComponent = npc->GetComponent(); + auto* scriptComponent = npc->GetComponent(); - if (scriptComponent != nullptr) { - scriptComponent->SetScript(pair.m_Script); - scriptComponent->SetSerialized(false); + if (scriptComponent != nullptr) { + scriptComponent->SetScript(pair.m_Script); + scriptComponent->SetSerialized(false); - for (const auto& pair : pair.m_Flags) { - npc->SetVar(GeneralUtils::ASCIIToUTF16(pair.first), pair.second); - } - } + for (const auto& pair : pair.m_Flags) { + npc->SetVar(GeneralUtils::ASCIIToUTF16(pair.first), pair.second); + } + } - SetupNPCTalk(npc); - } + SetupNPCTalk(npc); + } - if (zoneID == 1200) { - { - EntityInfo info; - info.lot = 8139; - info.pos = { 259.5f, 246.4f, -705.2f }; - info.rot = { 0.0f, 0.0f, 1.0f, 0.0f }; - info.spawnerID = EntityManager::Instance()->GetZoneControlEntity()->GetObjectID(); + if (zoneID == 1200) { + { + EntityInfo info; + info.lot = 8139; + info.pos = { 259.5f, 246.4f, -705.2f }; + info.rot = { 0.0f, 0.0f, 1.0f, 0.0f }; + info.spawnerID = EntityManager::Instance()->GetZoneControlEntity()->GetObjectID(); - info.settings = { new LDFData(u"hasCustomText", true), - new LDFData(u"customText", ParseMarkdown("./vanity/TESTAMENT.md")) }; + info.settings = { new LDFData(u"hasCustomText", true), + new LDFData(u"customText", ParseMarkdown("./vanity/TESTAMENT.md")) }; - auto* entity = EntityManager::Instance()->CreateEntity(info); + auto* entity = EntityManager::Instance()->CreateEntity(info); - EntityManager::Instance()->ConstructEntity(entity); - } - } + EntityManager::Instance()->ConstructEntity(entity); + } + } } Entity* VanityUtilities::SpawnNPC(LOT lot, const std::string& name, const NiPoint3& position, - const NiQuaternion& rotation, const std::vector& inventory, const std::vector& ldf) -{ - EntityInfo info; - info.lot = lot; - info.pos = position; - info.rot = rotation; - info.spawnerID = EntityManager::Instance()->GetZoneControlEntity()->GetObjectID(); - info.settings = ldf; + const NiQuaternion& rotation, const std::vector& inventory, const std::vector& ldf) { + EntityInfo info; + info.lot = lot; + info.pos = position; + info.rot = rotation; + info.spawnerID = EntityManager::Instance()->GetZoneControlEntity()->GetObjectID(); + info.settings = ldf; - auto* entity = EntityManager::Instance()->CreateEntity(info); - entity->SetVar(u"npcName", name); + auto* entity = EntityManager::Instance()->CreateEntity(info); + entity->SetVar(u"npcName", name); - auto* inventoryComponent = entity->GetComponent(); + auto* inventoryComponent = entity->GetComponent(); - if (inventoryComponent != nullptr) { - inventoryComponent->SetNPCItems(inventory); - } + if (inventoryComponent != nullptr) { + inventoryComponent->SetNPCItems(inventory); + } - auto* destroyableComponent = entity->GetComponent(); + auto* destroyableComponent = entity->GetComponent(); - if (destroyableComponent != nullptr) { - destroyableComponent->SetIsGMImmune(true); - destroyableComponent->SetMaxHealth(0); - destroyableComponent->SetHealth(0); - } + if (destroyableComponent != nullptr) { + destroyableComponent->SetIsGMImmune(true); + destroyableComponent->SetMaxHealth(0); + destroyableComponent->SetHealth(0); + } - EntityManager::Instance()->ConstructEntity(entity); + EntityManager::Instance()->ConstructEntity(entity); - return entity; + return entity; } -void VanityUtilities::ParseXML(const std::string& file) -{ - // Read the entire file - std::ifstream xmlFile(file); - std::string xml((std::istreambuf_iterator(xmlFile)), std::istreambuf_iterator()); +void VanityUtilities::ParseXML(const std::string& file) { + // Read the entire file + std::ifstream xmlFile(file); + std::string xml((std::istreambuf_iterator(xmlFile)), std::istreambuf_iterator()); - // Parse the XML - tinyxml2::XMLDocument doc; - doc.Parse(xml.c_str(), xml.size()); + // Parse the XML + tinyxml2::XMLDocument doc; + doc.Parse(xml.c_str(), xml.size()); - // Read the NPCs - auto* npcs = doc.FirstChildElement("npcs"); + // Read the NPCs + auto* npcs = doc.FirstChildElement("npcs"); - if (npcs == nullptr) { - Game::logger->Log("VanityUtilities", "Failed to parse NPCs"); - return; - } + if (npcs == nullptr) { + Game::logger->Log("VanityUtilities", "Failed to parse NPCs"); + return; + } - for (auto* party = npcs->FirstChildElement("party"); party != nullptr; party = party->NextSiblingElement("party")) { - // Get 'zone' as uint32_t and 'chance' as float - uint32_t zone = 0; - float chance = 0.0f; + for (auto* party = npcs->FirstChildElement("party"); party != nullptr; party = party->NextSiblingElement("party")) { + // Get 'zone' as uint32_t and 'chance' as float + uint32_t zone = 0; + float chance = 0.0f; - if (party->Attribute("zone") != nullptr) { - zone = std::stoul(party->Attribute("zone")); - } + if (party->Attribute("zone") != nullptr) { + zone = std::stoul(party->Attribute("zone")); + } - if (party->Attribute("chance") != nullptr) { - chance = std::stof(party->Attribute("chance")); - } + if (party->Attribute("chance") != nullptr) { + chance = std::stof(party->Attribute("chance")); + } - VanityParty partyInfo; - partyInfo.m_Zone = zone; - partyInfo.m_Chance = chance; + VanityParty partyInfo; + partyInfo.m_Zone = zone; + partyInfo.m_Chance = chance; - auto* locations = party->FirstChildElement("locations"); + auto* locations = party->FirstChildElement("locations"); - if (locations == nullptr) { - Game::logger->Log("VanityUtilities", "Failed to parse party locations"); - continue; - } + if (locations == nullptr) { + Game::logger->Log("VanityUtilities", "Failed to parse party locations"); + continue; + } - for (auto* location = locations->FirstChildElement("location"); location != nullptr; - location = location->NextSiblingElement("location")) { - // Get the location data - auto* x = location->Attribute("x"); - auto* y = location->Attribute("y"); - auto* z = location->Attribute("z"); - auto* rw = location->Attribute("rw"); - auto* rx = location->Attribute("rx"); - auto* ry = location->Attribute("ry"); - auto* rz = location->Attribute("rz"); + for (auto* location = locations->FirstChildElement("location"); location != nullptr; + location = location->NextSiblingElement("location")) { + // Get the location data + auto* x = location->Attribute("x"); + auto* y = location->Attribute("y"); + auto* z = location->Attribute("z"); + auto* rw = location->Attribute("rw"); + auto* rx = location->Attribute("rx"); + auto* ry = location->Attribute("ry"); + auto* rz = location->Attribute("rz"); - if (x == nullptr || y == nullptr || z == nullptr || rw == nullptr || rx == nullptr || ry == nullptr - || rz == nullptr) { - Game::logger->Log("VanityUtilities", "Failed to parse party location data"); - continue; - } + if (x == nullptr || y == nullptr || z == nullptr || rw == nullptr || rx == nullptr || ry == nullptr + || rz == nullptr) { + Game::logger->Log("VanityUtilities", "Failed to parse party location data"); + continue; + } - VanityNPCLocation locationData; - locationData.m_Position = { std::stof(x), std::stof(y), std::stof(z) }; - locationData.m_Rotation = { std::stof(rw), std::stof(rx), std::stof(ry), std::stof(rz) }; - locationData.m_Chance = 1.0f; + VanityNPCLocation locationData; + locationData.m_Position = { std::stof(x), std::stof(y), std::stof(z) }; + locationData.m_Rotation = { std::stof(rw), std::stof(rx), std::stof(ry), std::stof(rz) }; + locationData.m_Chance = 1.0f; - partyInfo.m_Locations.push_back(locationData); - } + partyInfo.m_Locations.push_back(locationData); + } - m_Parties.push_back(partyInfo); - } + m_Parties.push_back(partyInfo); + } - auto* partyPhrases = npcs->FirstChildElement("partyphrases"); + auto* partyPhrases = npcs->FirstChildElement("partyphrases"); - if (partyPhrases == nullptr) { - Game::logger->Log("VanityUtilities", "Failed to parse party phrases"); - return; - } + if (partyPhrases == nullptr) { + Game::logger->Log("VanityUtilities", "Failed to parse party phrases"); + return; + } - for (auto* phrase = partyPhrases->FirstChildElement("phrase"); phrase != nullptr; - phrase = phrase->NextSiblingElement("phrase")) { - // Get the phrase - auto* text = phrase->GetText(); + for (auto* phrase = partyPhrases->FirstChildElement("phrase"); phrase != nullptr; + phrase = phrase->NextSiblingElement("phrase")) { + // Get the phrase + auto* text = phrase->GetText(); - if (text == nullptr) { - Game::logger->Log("VanityUtilities", "Failed to parse party phrase"); - continue; - } + if (text == nullptr) { + Game::logger->Log("VanityUtilities", "Failed to parse party phrase"); + continue; + } - m_PartyPhrases.push_back(text); - } + m_PartyPhrases.push_back(text); + } - for (auto* npc = npcs->FirstChildElement("npc"); npc != nullptr; npc = npc->NextSiblingElement("npc")) { - // Get the NPC name - auto* name = npc->Attribute("name"); + for (auto* npc = npcs->FirstChildElement("npc"); npc != nullptr; npc = npc->NextSiblingElement("npc")) { + // Get the NPC name + auto* name = npc->Attribute("name"); - if (name == nullptr) { - Game::logger->Log("VanityUtilities", "Failed to parse NPC name"); - continue; - } + if (name == nullptr) { + Game::logger->Log("VanityUtilities", "Failed to parse NPC name"); + continue; + } - // Get the NPC lot - auto* lot = npc->Attribute("lot"); + // Get the NPC lot + auto* lot = npc->Attribute("lot"); - if (lot == nullptr) { - Game::logger->Log("VanityUtilities", "Failed to parse NPC lot"); - continue; - } + if (lot == nullptr) { + Game::logger->Log("VanityUtilities", "Failed to parse NPC lot"); + continue; + } - // Get the equipment - auto* equipment = npc->FirstChildElement("equipment"); + // Get the equipment + auto* equipment = npc->FirstChildElement("equipment"); - if (equipment == nullptr) { - Game::logger->Log("VanityUtilities", "Failed to parse NPC equipment"); - continue; - } + if (equipment == nullptr) { + Game::logger->Log("VanityUtilities", "Failed to parse NPC equipment"); + continue; + } - auto* text = equipment->GetText(); + auto* text = equipment->GetText(); - std::vector inventory; + std::vector inventory; - if (text != nullptr) { - std::string equipmentString(text); + if (text != nullptr) { + std::string equipmentString(text); - std::vector splitEquipment = GeneralUtils::SplitString(equipmentString, ','); + std::vector splitEquipment = GeneralUtils::SplitString(equipmentString, ','); - for (auto& item : splitEquipment) { - inventory.push_back(std::stoi(item)); - } - } + for (auto& item : splitEquipment) { + inventory.push_back(std::stoi(item)); + } + } - // Get the phrases - auto* phrases = npc->FirstChildElement("phrases"); + // Get the phrases + auto* phrases = npc->FirstChildElement("phrases"); - if (phrases == nullptr) { - Game::logger->Log("VanityUtilities", "Failed to parse NPC phrases"); - continue; - } + if (phrases == nullptr) { + Game::logger->Log("VanityUtilities", "Failed to parse NPC phrases"); + continue; + } - std::vector phraseList; + std::vector phraseList; - for (auto* phrase = phrases->FirstChildElement("phrase"); phrase != nullptr; - phrase = phrase->NextSiblingElement("phrase")) { - // Get the phrase - auto* text = phrase->GetText(); + for (auto* phrase = phrases->FirstChildElement("phrase"); phrase != nullptr; + phrase = phrase->NextSiblingElement("phrase")) { + // Get the phrase + auto* text = phrase->GetText(); - if (text == nullptr) { - Game::logger->Log("VanityUtilities", "Failed to parse NPC phrase"); - continue; - } + if (text == nullptr) { + Game::logger->Log("VanityUtilities", "Failed to parse NPC phrase"); + continue; + } - phraseList.push_back(text); - } + phraseList.push_back(text); + } - // Get the script - auto* scriptElement = npc->FirstChildElement("script"); + // Get the script + auto* scriptElement = npc->FirstChildElement("script"); - std::string scriptName; + std::string scriptName; - if (scriptElement != nullptr) { - auto* scriptNameAttribute = scriptElement->Attribute("name"); + if (scriptElement != nullptr) { + auto* scriptNameAttribute = scriptElement->Attribute("name"); - if (scriptNameAttribute == nullptr) { - Game::logger->Log("VanityUtilities", "Failed to parse NPC script name"); - continue; - } + if (scriptNameAttribute == nullptr) { + Game::logger->Log("VanityUtilities", "Failed to parse NPC script name"); + continue; + } - scriptName = scriptNameAttribute; - } + scriptName = scriptNameAttribute; + } - VanityNPC npcData; - npcData.m_Name = name; - npcData.m_LOT = std::stoi(lot); - npcData.m_Equipment = inventory; - npcData.m_Phrases = phraseList; - npcData.m_Script = scriptName; + VanityNPC npcData; + npcData.m_Name = name; + npcData.m_LOT = std::stoi(lot); + npcData.m_Equipment = inventory; + npcData.m_Phrases = phraseList; + npcData.m_Script = scriptName; - // Get flags - auto* flags = npc->FirstChildElement("flags"); + // Get flags + auto* flags = npc->FirstChildElement("flags"); - if (flags != nullptr) { - for (auto* flag = flags->FirstChildElement("flag"); flag != nullptr; - flag = flag->NextSiblingElement("flag")) { - // Get the flag name - auto* name = flag->Attribute("name"); + if (flags != nullptr) { + for (auto* flag = flags->FirstChildElement("flag"); flag != nullptr; + flag = flag->NextSiblingElement("flag")) { + // Get the flag name + auto* name = flag->Attribute("name"); - if (name == nullptr) { - Game::logger->Log("VanityUtilities", "Failed to parse NPC flag name"); - continue; - } + if (name == nullptr) { + Game::logger->Log("VanityUtilities", "Failed to parse NPC flag name"); + continue; + } - // Get the flag value - auto* value = flag->Attribute("value"); + // Get the flag value + auto* value = flag->Attribute("value"); - if (value == nullptr) { - Game::logger->Log("VanityUtilities", "Failed to parse NPC flag value"); - continue; - } + if (value == nullptr) { + Game::logger->Log("VanityUtilities", "Failed to parse NPC flag value"); + continue; + } - npcData.m_Flags[name] = std::stoi(value); - } - } + npcData.m_Flags[name] = std::stoi(value); + } + } - // Get the zones - for (auto* zone = npc->FirstChildElement("zone"); zone != nullptr; zone = zone->NextSiblingElement("zone")) { - // Get the zone ID - auto* zoneID = zone->Attribute("id"); + // Get the zones + for (auto* zone = npc->FirstChildElement("zone"); zone != nullptr; zone = zone->NextSiblingElement("zone")) { + // Get the zone ID + auto* zoneID = zone->Attribute("id"); - if (zoneID == nullptr) { - Game::logger->Log("VanityUtilities", "Failed to parse NPC zone ID"); - continue; - } + if (zoneID == nullptr) { + Game::logger->Log("VanityUtilities", "Failed to parse NPC zone ID"); + continue; + } - // Get the locations - auto* locations = zone->FirstChildElement("locations"); + // Get the locations + auto* locations = zone->FirstChildElement("locations"); - if (locations == nullptr) { - Game::logger->Log("VanityUtilities", "Failed to parse NPC locations"); - continue; - } + if (locations == nullptr) { + Game::logger->Log("VanityUtilities", "Failed to parse NPC locations"); + continue; + } - for (auto* location = locations->FirstChildElement("location"); location != nullptr; - location = location->NextSiblingElement("location")) { - // Get the location data - auto* x = location->Attribute("x"); - auto* y = location->Attribute("y"); - auto* z = location->Attribute("z"); - auto* rw = location->Attribute("rw"); - auto* rx = location->Attribute("rx"); - auto* ry = location->Attribute("ry"); - auto* rz = location->Attribute("rz"); + for (auto* location = locations->FirstChildElement("location"); location != nullptr; + location = location->NextSiblingElement("location")) { + // Get the location data + auto* x = location->Attribute("x"); + auto* y = location->Attribute("y"); + auto* z = location->Attribute("z"); + auto* rw = location->Attribute("rw"); + auto* rx = location->Attribute("rx"); + auto* ry = location->Attribute("ry"); + auto* rz = location->Attribute("rz"); - if (x == nullptr || y == nullptr || z == nullptr || rw == nullptr || rx == nullptr || ry == nullptr - || rz == nullptr) { - Game::logger->Log("VanityUtilities", "Failed to parse NPC location data"); - continue; - } + if (x == nullptr || y == nullptr || z == nullptr || rw == nullptr || rx == nullptr || ry == nullptr + || rz == nullptr) { + Game::logger->Log("VanityUtilities", "Failed to parse NPC location data"); + continue; + } - VanityNPCLocation locationData; - locationData.m_Position = { std::stof(x), std::stof(y), std::stof(z) }; - locationData.m_Rotation = { std::stof(rw), std::stof(rx), std::stof(ry), std::stof(rz) }; - locationData.m_Chance = 1.0f; + VanityNPCLocation locationData; + locationData.m_Position = { std::stof(x), std::stof(y), std::stof(z) }; + locationData.m_Rotation = { std::stof(rw), std::stof(rx), std::stof(ry), std::stof(rz) }; + locationData.m_Chance = 1.0f; - if (location->Attribute("chance") != nullptr) { - locationData.m_Chance = std::stof(location->Attribute("chance")); - } + if (location->Attribute("chance") != nullptr) { + locationData.m_Chance = std::stof(location->Attribute("chance")); + } - const auto& it = npcData.m_Locations.find(std::stoi(zoneID)); + const auto& it = npcData.m_Locations.find(std::stoi(zoneID)); - if (it != npcData.m_Locations.end()) { - it->second.push_back(locationData); - } else { - std::vector locations; - locations.push_back(locationData); - npcData.m_Locations.insert(std::make_pair(std::stoi(zoneID), locations)); - } - } - } + if (it != npcData.m_Locations.end()) { + it->second.push_back(locationData); + } else { + std::vector locations; + locations.push_back(locationData); + npcData.m_Locations.insert(std::make_pair(std::stoi(zoneID), locations)); + } + } + } - m_NPCs.push_back(npcData); - } + m_NPCs.push_back(npcData); + } } -VanityNPC* VanityUtilities::GetNPC(const std::string& name) -{ - for (size_t i = 0; i < m_NPCs.size(); i++) { - if (m_NPCs[i].m_Name == name) { - return &m_NPCs[i]; - } - } +VanityNPC* VanityUtilities::GetNPC(const std::string& name) { + for (size_t i = 0; i < m_NPCs.size(); i++) { + if (m_NPCs[i].m_Name == name) { + return &m_NPCs[i]; + } + } - return nullptr; + return nullptr; } -std::string VanityUtilities::ParseMarkdown(const std::string& file) -{ - // This function will read the file and return the content formatted as ASCII text. +std::string VanityUtilities::ParseMarkdown(const std::string& file) { + // This function will read the file and return the content formatted as ASCII text. - // Read the file into a string - std::ifstream t(file); + // Read the file into a string + std::ifstream t(file); - // If the file does not exist, return an empty string. - if (!t.good()) { - return ""; - } + // If the file does not exist, return an empty string. + if (!t.good()) { + return ""; + } - std::stringstream buffer; - buffer << t.rdbuf(); - std::string fileContents = buffer.str(); + std::stringstream buffer; + buffer << t.rdbuf(); + std::string fileContents = buffer.str(); - // Loop through all lines in the file. - // Replace all instances of the markdown syntax with the corresponding HTML. - // Only care about headers - std::stringstream output; - std::string line; - std::stringstream ss; - ss << fileContents; - while (std::getline(ss, line)) { + // Loop through all lines in the file. + // Replace all instances of the markdown syntax with the corresponding HTML. + // Only care about headers + std::stringstream output; + std::string line; + std::stringstream ss; + ss << fileContents; + while (std::getline(ss, line)) { #define TOSTRING(x) #x #define STRINGIFY(x) TOSTRING(x) - // Replace "__TIMESTAMP__" with the __TIMESTAMP__ - GeneralUtils::ReplaceInString(line, "__TIMESTAMP__", __TIMESTAMP__); - // Replace "__VERSION__" wit'h the PROJECT_VERSION - GeneralUtils::ReplaceInString(line, "__VERSION__", STRINGIFY(PROJECT_VERSION)); - // Replace "__SOURCE__" with SOURCE - GeneralUtils::ReplaceInString(line, "__SOURCE__", Game::config->GetValue("source")); - // Replace "__LICENSE__" with LICENSE - GeneralUtils::ReplaceInString(line, "__LICENSE__", STRINGIFY(LICENSE)); + // Replace "__TIMESTAMP__" with the __TIMESTAMP__ + GeneralUtils::ReplaceInString(line, "__TIMESTAMP__", __TIMESTAMP__); + // Replace "__VERSION__" wit'h the PROJECT_VERSION + GeneralUtils::ReplaceInString(line, "__VERSION__", STRINGIFY(PROJECT_VERSION)); + // Replace "__SOURCE__" with SOURCE + GeneralUtils::ReplaceInString(line, "__SOURCE__", Game::config->GetValue("source")); + // Replace "__LICENSE__" with LICENSE + GeneralUtils::ReplaceInString(line, "__LICENSE__", STRINGIFY(LICENSE)); - if (line.find("##") != std::string::npos) { - // Add "<font size='18' color='#000000'>" before the header - output << ""; - // Add the header without the markdown syntax - output << line.substr(3); + if (line.find("##") != std::string::npos) { + // Add "<font size='18' color='#000000'>" before the header + output << ""; + // Add the header without the markdown syntax + output << line.substr(3); - output << ""; - } else if (line.find("#") != std::string::npos) { - // Add "<font size='18' color='#000000'>" before the header - output << ""; - // Add the header without the markdown syntax - output << line.substr(2); + output << ""; + } else if (line.find("#") != std::string::npos) { + // Add "<font size='18' color='#000000'>" before the header + output << ""; + // Add the header without the markdown syntax + output << line.substr(2); - output << ""; - } else { - output << line; - } + output << ""; + } else { + output << line; + } - output << "\n"; - } + output << "\n"; + } - return output.str(); + return output.str(); } -void VanityUtilities::SetupNPCTalk(Entity* npc) -{ - npc->AddCallbackTimer(15.0f, [npc]() { NPCTalk(npc); }); +void VanityUtilities::SetupNPCTalk(Entity* npc) { + npc->AddCallbackTimer(15.0f, [npc]() { NPCTalk(npc); }); - npc->SetProximityRadius(20.0f, "talk"); + npc->SetProximityRadius(20.0f, "talk"); } -void VanityUtilities::NPCTalk(Entity* npc) -{ - auto* proximityMonitorComponent = npc->GetComponent(); +void VanityUtilities::NPCTalk(Entity* npc) { + auto* proximityMonitorComponent = npc->GetComponent(); - if (!proximityMonitorComponent->GetProximityObjects("talk").empty()) { - const auto& chats = npc->GetVar>(u"chats"); + if (!proximityMonitorComponent->GetProximityObjects("talk").empty()) { + const auto& chats = npc->GetVar>(u"chats"); - if (chats.empty()) { - return; - } + if (chats.empty()) { + return; + } - const auto& selected - = chats[GeneralUtils::GenerateRandomNumber(0, static_cast(chats.size() - 1))]; + const auto& selected + = chats[GeneralUtils::GenerateRandomNumber(0, static_cast(chats.size() - 1))]; - GameMessages::SendNotifyClientZoneObject( - npc->GetObjectID(), u"sendToclient_bubble", 0, 0, npc->GetObjectID(), selected, UNASSIGNED_SYSTEM_ADDRESS); - } + GameMessages::SendNotifyClientZoneObject( + npc->GetObjectID(), u"sendToclient_bubble", 0, 0, npc->GetObjectID(), selected, UNASSIGNED_SYSTEM_ADDRESS); + } - EntityManager::Instance()->SerializeEntity(npc); + EntityManager::Instance()->SerializeEntity(npc); - const float nextTime = GeneralUtils::GenerateRandomNumber(15, 60); + const float nextTime = GeneralUtils::GenerateRandomNumber(15, 60); - npc->AddCallbackTimer(nextTime, [npc]() { NPCTalk(npc); }); + npc->AddCallbackTimer(nextTime, [npc]() { NPCTalk(npc); }); } diff --git a/dGame/dUtilities/VanityUtilities.h b/dGame/dUtilities/VanityUtilities.h index b8462421..2f1886ed 100644 --- a/dGame/dUtilities/VanityUtilities.h +++ b/dGame/dUtilities/VanityUtilities.h @@ -6,61 +6,61 @@ struct VanityNPCLocation { - float m_Chance = 1.0f; - NiPoint3 m_Position; - NiQuaternion m_Rotation; + float m_Chance = 1.0f; + NiPoint3 m_Position; + NiQuaternion m_Rotation; }; struct VanityNPC { - std::string m_Name; - LOT m_LOT; - std::vector m_Equipment; - std::vector m_Phrases; - std::string m_Script; - std::map m_Flags; - std::map> m_Locations; + std::string m_Name; + LOT m_LOT; + std::vector m_Equipment; + std::vector m_Phrases; + std::string m_Script; + std::map m_Flags; + std::map> m_Locations; }; struct VanityParty { - uint32_t m_Zone; - float m_Chance = 1.0f; - std::vector m_Locations; + uint32_t m_Zone; + float m_Chance = 1.0f; + std::vector m_Locations; }; class VanityUtilities { public: - static void SpawnVanity(); + static void SpawnVanity(); - static Entity* SpawnNPC( - LOT lot, - const std::string& name, - const NiPoint3& position, - const NiQuaternion& rotation, - const std::vector& inventory, - const std::vector& ldf - ); + static Entity* SpawnNPC( + LOT lot, + const std::string& name, + const NiPoint3& position, + const NiQuaternion& rotation, + const std::vector& inventory, + const std::vector& ldf + ); - static std::string ParseMarkdown( - const std::string& file - ); + static std::string ParseMarkdown( + const std::string& file + ); - static void ParseXML( - const std::string& file - ); + static void ParseXML( + const std::string& file + ); - static VanityNPC* GetNPC(const std::string& name); + static VanityNPC* GetNPC(const std::string& name); private: - static void SetupNPCTalk(Entity* npc); + static void SetupNPCTalk(Entity* npc); - static void NPCTalk(Entity* npc); + static void NPCTalk(Entity* npc); - static std::vector m_NPCs; + static std::vector m_NPCs; - static std::vector m_Parties; + static std::vector m_Parties; - static std::vector m_PartyPhrases; + static std::vector m_PartyPhrases; }; diff --git a/dGame/dUtilities/dLocale.cpp b/dGame/dUtilities/dLocale.cpp index 5f918fec..65ef3a58 100644 --- a/dGame/dUtilities/dLocale.cpp +++ b/dGame/dUtilities/dLocale.cpp @@ -11,71 +11,71 @@ #include "dConfig.h" dLocale::dLocale() { - if (Game::config->GetValue("locale_enabled") != "1") { - return; - } + if (Game::config->GetValue("locale_enabled") != "1") { + return; + } - std::ifstream file(m_LocalePath); + std::ifstream file(m_LocalePath); - if (!file.good()) { - return; - } + if (!file.good()) { + return; + } - std::stringstream data; - data << file.rdbuf(); + std::stringstream data; + data << file.rdbuf(); - if (data.str().empty()) { - return; - } + if (data.str().empty()) { + return; + } - auto* doc = new tinyxml2::XMLDocument(); + auto* doc = new tinyxml2::XMLDocument(); - if (doc == nullptr) { - return; - } + if (doc == nullptr) { + return; + } - if (doc->Parse(data.str().c_str(), data.str().size()) != 0) { - return; - } + if (doc->Parse(data.str().c_str(), data.str().size()) != 0) { + return; + } - std::hash hash; + std::hash hash; - auto* localization = doc->FirstChildElement("localization"); - auto* phrases = localization->FirstChildElement("phrases"); + auto* localization = doc->FirstChildElement("localization"); + auto* phrases = localization->FirstChildElement("phrases"); - auto* phrase = phrases->FirstChildElement("phrase"); + auto* phrase = phrases->FirstChildElement("phrase"); - while (phrase != nullptr) { - // Add the phrase hash to the vector - m_Phrases.push_back(hash(phrase->Attribute("id"))); - phrase = phrase->NextSiblingElement("phrase"); - } + while (phrase != nullptr) { + // Add the phrase hash to the vector + m_Phrases.push_back(hash(phrase->Attribute("id"))); + phrase = phrase->NextSiblingElement("phrase"); + } - file.close(); + file.close(); - delete doc; + delete doc; } dLocale::~dLocale() = default; std::string dLocale::GetTemplate(const std::string& phraseID) { - return "%[" + phraseID + "]"; + return "%[" + phraseID + "]"; } bool dLocale::HasPhrase(const std::string& phraseID) { - if (Game::config->GetValue("locale_enabled") != "1") { - return true; - } + if (Game::config->GetValue("locale_enabled") != "1") { + return true; + } - // Compute the hash and see if it's in the vector - std::hash hash; - std::size_t hashValue = hash(phraseID); - return std::find(m_Phrases.begin(), m_Phrases.end(), hashValue) != m_Phrases.end(); + // Compute the hash and see if it's in the vector + std::hash hash; + std::size_t hashValue = hash(phraseID); + return std::find(m_Phrases.begin(), m_Phrases.end(), hashValue) != m_Phrases.end(); } /*std::string dLocale::GetPhrase(const std::string& phraseID) { - if (m_Phrases.find(phraseID) == m_Phrases.end()) { - return ""; - } - return m_Phrases[phraseID]; -}*/ \ No newline at end of file + if (m_Phrases.find(phraseID) == m_Phrases.end()) { + return ""; + } + return m_Phrases[phraseID]; +}*/ diff --git a/dGame/dUtilities/dLocale.h b/dGame/dUtilities/dLocale.h index 398f903b..db5d2a4f 100644 --- a/dGame/dUtilities/dLocale.h +++ b/dGame/dUtilities/dLocale.h @@ -6,14 +6,14 @@ class dLocale { public: - dLocale(); - ~dLocale(); - static std::string GetTemplate(const std::string& phraseID); - bool HasPhrase(const std::string& phraseID); - //std::string GetPhrase(const std::string& phraseID); + dLocale(); + ~dLocale(); + static std::string GetTemplate(const std::string& phraseID); + bool HasPhrase(const std::string& phraseID); + //std::string GetPhrase(const std::string& phraseID); private: - std::string m_LocalePath = "./locale/locale.xml"; - std::string m_Locale = "en_US"; // TODO: add to config - std::vector m_Phrases; -}; \ No newline at end of file + std::string m_LocalePath = "./locale/locale.xml"; + std::string m_Locale = "en_US"; // TODO: add to config + std::vector m_Phrases; +}; diff --git a/dMasterServer/InstanceManager.cpp b/dMasterServer/InstanceManager.cpp index 2c4c3287..0c605ed6 100644 --- a/dMasterServer/InstanceManager.cpp +++ b/dMasterServer/InstanceManager.cpp @@ -25,65 +25,64 @@ InstanceManager::~InstanceManager() { } } -Instance * InstanceManager::GetInstance(LWOMAPID mapID, bool isFriendTransfer, LWOCLONEID cloneID) { - mLogger->Log("InstanceManager", "Searching for an instance for mapID %i/%i", mapID, cloneID); +Instance* InstanceManager::GetInstance(LWOMAPID mapID, bool isFriendTransfer, LWOCLONEID cloneID) { + mLogger->Log("InstanceManager", "Searching for an instance for mapID %i/%i", mapID, cloneID); Instance* instance = FindInstance(mapID, isFriendTransfer, cloneID); if (instance) return instance; - //TODO: Update this so that the IP is read from a configuration file instead + //TODO: Update this so that the IP is read from a configuration file instead - int softCap = 8; - int maxPlayers = 12; + int softCap = 8; + int maxPlayers = 12; - if (mapID == 0) { - softCap = 999; - maxPlayers = softCap; - } else { + if (mapID == 0) { + softCap = 999; + maxPlayers = softCap; + } else { softCap = GetSoftCap(mapID); maxPlayers = GetHardCap(mapID); } - uint32_t port = GetFreePort(); - instance = new Instance(mExternalIP, port, mapID, ++m_LastInstanceID, cloneID, softCap, maxPlayers); + uint32_t port = GetFreePort(); + instance = new Instance(mExternalIP, port, mapID, ++m_LastInstanceID, cloneID, softCap, maxPlayers); - //Start the actual process: + //Start the actual process: #ifdef _WIN32 std::string cmd = "start ./WorldServer.exe -zone "; #else std::string cmd; - if (std::atoi(Game::config->GetValue("use_sudo_world").c_str())) { + if (std::atoi(Game::config->GetValue("use_sudo_world").c_str())) { cmd = "sudo ./WorldServer -zone "; } else { cmd = "./WorldServer -zone "; } #endif - cmd.append(std::to_string(mapID)); - cmd.append(" -port "); - cmd.append(std::to_string(port)); - cmd.append(" -instance "); - cmd.append(std::to_string(m_LastInstanceID)); - cmd.append(" -maxclients "); - cmd.append(std::to_string(maxPlayers)); + cmd.append(std::to_string(mapID)); + cmd.append(" -port "); + cmd.append(std::to_string(port)); + cmd.append(" -instance "); + cmd.append(std::to_string(m_LastInstanceID)); + cmd.append(" -maxclients "); + cmd.append(std::to_string(maxPlayers)); - cmd.append(" -clone "); - cmd.append(std::to_string(cloneID)); + cmd.append(" -clone "); + cmd.append(std::to_string(cloneID)); #ifndef _WIN32 - cmd.append("&"); //Sends our next process to the background on Linux + cmd.append("&"); //Sends our next process to the background on Linux #endif - system(cmd.c_str()); + system(cmd.c_str()); - m_Instances.push_back(instance); + m_Instances.push_back(instance); - if (instance) { - mLogger->Log("InstanceManager", "Created new instance: %i/%i/%i with min/max %i/%i", mapID, m_LastInstanceID, cloneID, softCap, maxPlayers); - return instance; - } - else mLogger->Log("InstanceManager", "Failed to create a new instance!"); + if (instance) { + mLogger->Log("InstanceManager", "Created new instance: %i/%i/%i with min/max %i/%i", mapID, m_LastInstanceID, cloneID, softCap, maxPlayers); + return instance; + } else mLogger->Log("InstanceManager", "Failed to create a new instance!"); - return nullptr; + return nullptr; } bool InstanceManager::IsPortInUse(uint32_t port) { @@ -97,22 +96,22 @@ bool InstanceManager::IsPortInUse(uint32_t port) { } uint32_t InstanceManager::GetFreePort() { - uint32_t port = m_LastPort; - std::vector usedPorts; - for (Instance* i : m_Instances) { - usedPorts.push_back(i->GetPort()); - } + uint32_t port = m_LastPort; + std::vector usedPorts; + for (Instance* i : m_Instances) { + usedPorts.push_back(i->GetPort()); + } - std::sort(usedPorts.begin(), usedPorts.end()); + std::sort(usedPorts.begin(), usedPorts.end()); - int portIdx = 0; - while (portIdx < usedPorts.size() && port == usedPorts[portIdx]) { - //increment by 3 since each instance uses 3 ports (instance, world-server, world-chat) - port += 3; - portIdx++; - } + int portIdx = 0; + while (portIdx < usedPorts.size() && port == usedPorts[portIdx]) { + //increment by 3 since each instance uses 3 ports (instance, world-server, world-chat) + port += 3; + portIdx++; + } - return port; + return port; } void InstanceManager::AddPlayer(SystemAddress systemAddr, LWOMAPID mapID, LWOINSTANCEID instanceID) { @@ -135,8 +134,7 @@ void InstanceManager::RemovePlayer(SystemAddress systemAddr, LWOMAPID mapID, LWO } } -std::vector InstanceManager::GetInstances() const -{ +std::vector InstanceManager::GetInstances() const { return m_Instances; } @@ -147,10 +145,8 @@ void InstanceManager::AddInstance(Instance* instance) { } void InstanceManager::RemoveInstance(Instance* instance) { - for (uint32_t i = 0; i < m_Instances.size(); ++i) - { - if (m_Instances[i] == instance) - { + for (uint32_t i = 0; i < m_Instances.size(); ++i) { + if (m_Instances[i] == instance) { instance->SetShutdownComplete(true); RedirectPendingRequests(instance); @@ -164,14 +160,12 @@ void InstanceManager::RemoveInstance(Instance* instance) { } } -void InstanceManager::ReadyInstance(Instance* instance) -{ +void InstanceManager::ReadyInstance(Instance* instance) { instance->SetIsReady(true); auto& pending = instance->GetPendingRequests(); - for (const auto& request : pending) - { + for (const auto& request : pending) { const auto& zoneId = instance->GetZoneID(); Game::logger->Log("InstanceManager", "Responding to pending request %llu -> %i (%i)", request, zoneId.GetMapID(), zoneId.GetCloneID()); @@ -192,8 +186,7 @@ void InstanceManager::ReadyInstance(Instance* instance) pending.clear(); } -void InstanceManager::RequestAffirmation(Instance* instance, const PendingInstanceRequest& request) -{ +void InstanceManager::RequestAffirmation(Instance* instance, const PendingInstanceRequest& request) { instance->GetPendingAffirmations().push_back(request); CBITSTREAM; @@ -210,12 +203,10 @@ void InstanceManager::RequestAffirmation(Instance* instance, const PendingInstan ); } -void InstanceManager::AffirmTransfer(Instance* instance, const uint64_t transferID) -{ +void InstanceManager::AffirmTransfer(Instance* instance, const uint64_t transferID) { auto& pending = instance->GetPendingAffirmations(); - for (auto i = 0u; i < pending.size(); ++i) - { + for (auto i = 0u; i < pending.size(); ++i) { const auto& request = pending[i]; if (request.id != transferID) continue; @@ -240,12 +231,10 @@ void InstanceManager::AffirmTransfer(Instance* instance, const uint64_t transfer } } -void InstanceManager::RedirectPendingRequests(Instance* instance) -{ +void InstanceManager::RedirectPendingRequests(Instance* instance) { const auto& zoneId = instance->GetZoneID(); - for (const auto& request : instance->GetPendingAffirmations()) - { + for (const auto& request : instance->GetPendingAffirmations()) { auto* in = Game::im->GetInstance(zoneId.GetMapID(), false, zoneId.GetCloneID()); if (!in->GetIsReady()) // Instance not ready, make a pending request @@ -278,7 +267,7 @@ bool InstanceManager::IsInstanceFull(Instance* instance, bool isFriendTransfer) return true; } -Instance * InstanceManager::FindInstance(LWOMAPID mapID, bool isFriendTransfer, LWOCLONEID cloneId) { +Instance* InstanceManager::FindInstance(LWOMAPID mapID, bool isFriendTransfer, LWOCLONEID cloneId) { for (Instance* i : m_Instances) { if (i && i->GetMapID() == mapID && i->GetCloneID() == cloneId && !IsInstanceFull(i, isFriendTransfer) && !i->GetIsPrivate() && !i->GetShutdownComplete() && !i->GetIsShuttingDown()) { return i; @@ -288,9 +277,9 @@ Instance * InstanceManager::FindInstance(LWOMAPID mapID, bool isFriendTransfer, return nullptr; } -Instance * InstanceManager::FindInstance(LWOMAPID mapID, LWOINSTANCEID instanceID) { +Instance* InstanceManager::FindInstance(LWOMAPID mapID, LWOINSTANCEID instanceID) { for (Instance* i : m_Instances) { - if (i && i->GetMapID() == mapID && i->GetInstanceID() == instanceID && !i->GetIsPrivate() && !i->GetShutdownComplete() && !i->GetIsShuttingDown()) { + if (i && i->GetMapID() == mapID && i->GetInstanceID() == instanceID && !i->GetIsPrivate() && !i->GetShutdownComplete() && !i->GetIsShuttingDown()) { return i; } } @@ -298,12 +287,10 @@ Instance * InstanceManager::FindInstance(LWOMAPID mapID, LWOINSTANCEID instanceI return nullptr; } -Instance* InstanceManager::CreatePrivateInstance(LWOMAPID mapID, LWOCLONEID cloneID, const std::string& password) -{ +Instance* InstanceManager::CreatePrivateInstance(LWOMAPID mapID, LWOCLONEID cloneID, const std::string& password) { auto* instance = FindPrivateInstance(password); - if (instance != nullptr) - { + if (instance != nullptr) { return instance; } @@ -312,29 +299,29 @@ Instance* InstanceManager::CreatePrivateInstance(LWOMAPID mapID, LWOCLONEID clon uint32_t port = GetFreePort(); instance = new Instance(mExternalIP, port, mapID, ++m_LastInstanceID, cloneID, maxPlayers, maxPlayers, true, password); - //Start the actual process: - std::string cmd = "start ./WorldServer.exe -zone "; + //Start the actual process: + std::string cmd = "start ./WorldServer.exe -zone "; #ifndef _WIN32 cmd = "./WorldServer -zone "; #endif - cmd.append(std::to_string(mapID)); - cmd.append(" -port "); - cmd.append(std::to_string(port)); - cmd.append(" -instance "); - cmd.append(std::to_string(m_LastInstanceID)); - cmd.append(" -maxclients "); - cmd.append(std::to_string(maxPlayers)); + cmd.append(std::to_string(mapID)); + cmd.append(" -port "); + cmd.append(std::to_string(port)); + cmd.append(" -instance "); + cmd.append(std::to_string(m_LastInstanceID)); + cmd.append(" -maxclients "); + cmd.append(std::to_string(maxPlayers)); - cmd.append(" -clone "); - cmd.append(std::to_string(cloneID)); + cmd.append(" -clone "); + cmd.append(std::to_string(cloneID)); #ifndef WIN32 - cmd.append("&"); //Sends our next process to the background on Linux + cmd.append("&"); //Sends our next process to the background on Linux #endif - system(cmd.c_str()); + system(cmd.c_str()); m_Instances.push_back(instance); @@ -344,21 +331,17 @@ Instance* InstanceManager::CreatePrivateInstance(LWOMAPID mapID, LWOCLONEID clon return instance; } -Instance* InstanceManager::FindPrivateInstance(const std::string& password) -{ - for (auto* instance : m_Instances) - { +Instance* InstanceManager::FindPrivateInstance(const std::string& password) { + for (auto* instance : m_Instances) { if (!instance) continue; - if (!instance->GetIsPrivate()) - { + if (!instance->GetIsPrivate()) { continue; } mLogger->Log("InstanceManager", "Password: %s == %s => %d", password.c_str(), instance->GetPassword().c_str(), password == instance->GetPassword()); - if (instance->GetPassword() == password) - { + if (instance->GetPassword() == password) { return instance; } } @@ -392,18 +375,15 @@ int InstanceManager::GetHardCap(LWOMAPID mapID) { return 12; } -void Instance::SetShutdownComplete(const bool value) -{ +void Instance::SetShutdownComplete(const bool value) { m_Shutdown = value; } -bool Instance::GetShutdownComplete() const -{ +bool Instance::GetShutdownComplete() const { return m_Shutdown; } -void Instance::Shutdown() -{ +void Instance::Shutdown() { CBITSTREAM; PacketUtils::WriteHeader(bitStream, MASTER, MSG_MASTER_SHUTDOWN); diff --git a/dMasterServer/InstanceManager.h b/dMasterServer/InstanceManager.h index ea261343..2c5083d4 100644 --- a/dMasterServer/InstanceManager.h +++ b/dMasterServer/InstanceManager.h @@ -51,7 +51,7 @@ public: void SetIsShuttingDown(bool value) { m_IsShuttingDown = value; } std::vector& GetPendingRequests() { return m_PendingRequests; } std::vector& GetPendingAffirmations() { return m_PendingAffirmations; } - + int GetHardCap() const { return m_MaxClientsHardCap; } int GetSoftCap() const { return m_MaxClientsSoftCap; } int GetCurrentClientCount() const { return m_CurrentClientCount; } @@ -60,10 +60,10 @@ public: uint32_t GetAffirmationTimeout() const { return m_AffirmationTimeout; } void AddPlayer(Player player) { /*m_Players.push_back(player);*/ m_CurrentClientCount++; } - void RemovePlayer(Player player) { + void RemovePlayer(Player player) { m_CurrentClientCount--; if (m_CurrentClientCount < 0) m_CurrentClientCount = 0; - /*for (size_t i = 0; i < m_Players.size(); ++i) + /*for (size_t i = 0; i < m_Players.size(); ++i) if (m_Players[i].addr == player.addr) m_Players.erase(m_Players.begin() + i);*/ } @@ -72,7 +72,7 @@ public: void SetShutdownComplete(bool value); bool GetShutdownComplete() const; - + void Shutdown(); private: @@ -90,7 +90,7 @@ private: std::vector m_PendingAffirmations; uint32_t m_AffirmationTimeout; - + bool m_IsPrivate; std::string m_Password; @@ -107,7 +107,7 @@ public: Instance* GetInstance(LWOMAPID mapID, bool isFriendTransfer, LWOCLONEID cloneID); //Creates an instance if none found bool IsPortInUse(uint32_t port); uint32_t GetFreePort(); - + void AddPlayer(SystemAddress systemAddr, LWOMAPID mapID, LWOINSTANCEID instanceID); void RemovePlayer(SystemAddress systemAddr, LWOMAPID mapID, LWOINSTANCEID instanceID); diff --git a/dMasterServer/MasterServer.cpp b/dMasterServer/MasterServer.cpp index e679940b..a692e826 100644 --- a/dMasterServer/MasterServer.cpp +++ b/dMasterServer/MasterServer.cpp @@ -104,8 +104,7 @@ int main(int argc, char** argv) { Game::logger->Log("MigrationRunner", "Finished running migrations"); return EXIT_SUCCESS; - } - else { + } else { //Check CDClient exists const std::string cdclient_path = "./res/CDServer.sqlite"; @@ -229,8 +228,7 @@ int main(int argc, char** argv) { updateStatement->setInt(3, result->getInt("id")); updateStatement->execute(); delete updateStatement; - } - else { + } else { //If we didn't find a server, create one. auto* insertStatement = Database::CreatePreppedStmt("INSERT INTO `servers` (`name`, `ip`, `port`, `state`, `version`) VALUES ('master', ?, ?, 0, 171023)"); insertStatement->setString(1, master_server_ip); @@ -274,8 +272,7 @@ int main(int argc, char** argv) { if (framesSinceLastFlush >= 900) { Game::logger->Flush(); framesSinceLastFlush = 0; - } - else + } else framesSinceLastFlush++; //Every 10 min we ping our sql server to keep it alive hopefully: @@ -294,8 +291,7 @@ int main(int argc, char** argv) { delete stmt; framesSinceLastSQLPing = 0; - } - else + } else framesSinceLastSQLPing++; //10m shutdown for universe kill command @@ -303,8 +299,7 @@ int main(int argc, char** argv) { if (framesSinceKillUniverseCommand >= 40000) { //Break main loop and exit break; - } - else + } else framesSinceKillUniverseCommand++; } @@ -319,8 +314,7 @@ int main(int argc, char** argv) { if (!instance->GetPendingAffirmations().empty()) { affirmTimeout++; - } - else { + } else { affirmTimeout = 0; } @@ -415,7 +409,7 @@ void HandlePacket(Packet* packet) { } case MSG_MASTER_REQUEST_ZONE_TRANSFER: { - Game::logger->Log("MasterServer","Received zone transfer req"); + Game::logger->Log("MasterServer", "Received zone transfer req"); RakNet::BitStream inStream(packet->data, packet->length, false); uint64_t header = inStream.Read(header); uint64_t requestID = 0; @@ -431,7 +425,7 @@ void HandlePacket(Packet* packet) { Instance* in = Game::im->GetInstance(zoneID, false, zoneClone); for (auto* instance : Game::im->GetInstances()) { - Game::logger->Log("MasterServer", "Instance: %i/%i/%i -> %i",instance->GetMapID(), instance->GetCloneID(),instance->GetInstanceID(), instance == in); + Game::logger->Log("MasterServer", "Instance: %i/%i/%i -> %i", instance->GetMapID(), instance->GetCloneID(), instance->GetInstanceID(), instance == in); } if (!in->GetIsReady()) //Instance not ready, make a pending request @@ -477,8 +471,7 @@ void HandlePacket(Packet* packet) { in->SetSysAddr(copy); Game::im->AddInstance(in); - } - else { + } else { auto instance = Game::im->FindInstance( theirZoneID, static_cast(theirInstanceID)); if (instance) { @@ -562,8 +555,7 @@ void HandlePacket(Packet* packet) { Game::im->FindInstance(theirZoneID, theirInstanceID); if (instance) { instance->AddPlayer(Player()); - } - else { + } else { printf("Instance missing? What?"); } break; @@ -633,7 +625,7 @@ void HandlePacket(Packet* packet) { auto* instance = Game::im->FindPrivateInstance(password.c_str()); - Game::logger->Log( "MasterServer", "Join private zone: %llu %d %s %p", requestID, mythranShift, password.c_str(), instance); + Game::logger->Log("MasterServer", "Join private zone: %llu %d %s %p", requestID, mythranShift, password.c_str(), instance); if (instance == nullptr) { return; @@ -641,7 +633,7 @@ void HandlePacket(Packet* packet) { const auto& zone = instance->GetZoneID(); - MasterPackets::SendZoneTransferResponse(Game::server, packet->systemAddress, requestID,(bool)mythranShift, zone.GetMapID(),instance->GetInstanceID(), zone.GetCloneID(),instance->GetIP(), instance->GetPort()); + MasterPackets::SendZoneTransferResponse(Game::server, packet->systemAddress, requestID, (bool)mythranShift, zone.GetMapID(), instance->GetInstanceID(), zone.GetCloneID(), instance->GetIP(), instance->GetPort()); break; } @@ -656,12 +648,12 @@ void HandlePacket(Packet* packet) { inStream.Read(zoneID); inStream.Read(instanceID); - Game::logger->Log("MasterServer", "Got world ready %i %i",zoneID, instanceID); + Game::logger->Log("MasterServer", "Got world ready %i %i", zoneID, instanceID); auto* instance = Game::im->FindInstance(zoneID, instanceID); if (instance == nullptr) { - Game::logger->Log("MasterServer","Failed to find zone to ready"); + Game::logger->Log("MasterServer", "Failed to find zone to ready"); return; } @@ -690,15 +682,15 @@ void HandlePacket(Packet* packet) { inStream.Read(requestID); - Game::logger->Log("MasterServer","Got affirmation of transfer %llu",requestID); + Game::logger->Log("MasterServer", "Got affirmation of transfer %llu", requestID); - auto* instance =Game::im->GetInstanceBySysAddr(packet->systemAddress); + auto* instance = Game::im->GetInstanceBySysAddr(packet->systemAddress); if (instance == nullptr) return; Game::im->AffirmTransfer(instance, requestID); - Game::logger->Log("MasterServer", "Affirmation complete %llu",requestID); + Game::logger->Log("MasterServer", "Affirmation complete %llu", requestID); break; } @@ -718,45 +710,43 @@ void HandlePacket(Packet* packet) { } case MSG_MASTER_SHUTDOWN_UNIVERSE: { - Game::logger->Log("MasterServer","Received shutdown universe command, shutting down in 10 minutes."); + Game::logger->Log("MasterServer", "Received shutdown universe command, shutting down in 10 minutes."); shouldShutdown = true; break; } default: - Game::logger->Log("MasterServer","Unknown master packet ID from server: %i",packet->data[3]); + Game::logger->Log("MasterServer", "Unknown master packet ID from server: %i", packet->data[3]); } } } void StartChatServer() { #ifdef __APPLE__ - //macOS doesn't need sudo to run on ports < 1024 - system("./ChatServer&"); + //macOS doesn't need sudo to run on ports < 1024 + system("./ChatServer&"); #elif _WIN32 - system("start ./ChatServer.exe"); + system("start ./ChatServer.exe"); #else - if (std::atoi(Game::config->GetValue("use_sudo_chat").c_str())) { - system("sudo ./ChatServer&"); - } - else { - system("./ChatServer&"); - } + if (std::atoi(Game::config->GetValue("use_sudo_chat").c_str())) { + system("sudo ./ChatServer&"); + } else { + system("./ChatServer&"); + } #endif } void StartAuthServer() { #ifdef __APPLE__ - system("./AuthServer&"); + system("./AuthServer&"); #elif _WIN32 - system("start ./AuthServer.exe"); + system("start ./AuthServer.exe"); #else - if (std::atoi(Game::config->GetValue("use_sudo_auth").c_str())) { - system("sudo ./AuthServer&"); - } - else { - system("./AuthServer&"); - } + if (std::atoi(Game::config->GetValue("use_sudo_auth").c_str())) { + system("sudo ./AuthServer&"); + } else { + system("./AuthServer&"); + } #endif } diff --git a/dMasterServer/ObjectIDManager.cpp b/dMasterServer/ObjectIDManager.cpp index 160a3859..0f3b98c9 100644 --- a/dMasterServer/ObjectIDManager.cpp +++ b/dMasterServer/ObjectIDManager.cpp @@ -5,67 +5,67 @@ #include "dLogger.h" // Static Variables -ObjectIDManager *ObjectIDManager::m_Address = nullptr; +ObjectIDManager* ObjectIDManager::m_Address = nullptr; //! Initializes the manager -void ObjectIDManager::Initialize(dLogger *logger) { - this->mLogger = logger; - this->currentPersistentID = 1; +void ObjectIDManager::Initialize(dLogger* logger) { + this->mLogger = logger; + this->currentPersistentID = 1; - try { - sql::PreparedStatement *stmt = Database::CreatePreppedStmt( - "SELECT last_object_id FROM object_id_tracker"); + try { + sql::PreparedStatement* stmt = Database::CreatePreppedStmt( + "SELECT last_object_id FROM object_id_tracker"); - sql::ResultSet *result = stmt->executeQuery(); - auto next = result->next(); + sql::ResultSet* result = stmt->executeQuery(); + auto next = result->next(); - if (!next) { - sql::PreparedStatement *insertStmt = Database::CreatePreppedStmt( - "INSERT INTO object_id_tracker VALUES (1)"); + if (!next) { + sql::PreparedStatement* insertStmt = Database::CreatePreppedStmt( + "INSERT INTO object_id_tracker VALUES (1)"); - insertStmt->execute(); + insertStmt->execute(); - delete insertStmt; + delete insertStmt; - return; - } + return; + } - while (next) { - this->currentPersistentID = - result->getInt(1) > 0 ? result->getInt(1) : 1; - next = result->next(); - } + while (next) { + this->currentPersistentID = + result->getInt(1) > 0 ? result->getInt(1) : 1; + next = result->next(); + } - delete result; - delete stmt; - } catch (sql::SQLException &e) { - mLogger->Log("ObjectIDManager", "Unable to fetch max persistent object " - "ID in use. Defaulting to 1."); - mLogger->Log("ObjectIDManager", "SQL error: %s", e.what()); - this->currentPersistentID = 1; - } + delete result; + delete stmt; + } catch (sql::SQLException& e) { + mLogger->Log("ObjectIDManager", "Unable to fetch max persistent object " + "ID in use. Defaulting to 1."); + mLogger->Log("ObjectIDManager", "SQL error: %s", e.what()); + this->currentPersistentID = 1; + } } //! Generates a new persistent ID uint32_t ObjectIDManager::GeneratePersistentID(void) { - uint32_t toReturn = ++this->currentPersistentID; + uint32_t toReturn = ++this->currentPersistentID; - // So we peroidically save our ObjID to the database: - if (toReturn % 25 == 0) { // TEMP: DISABLED FOR DEBUG / DEVELOPMENT! - sql::PreparedStatement *stmt = Database::CreatePreppedStmt( - "UPDATE object_id_tracker SET last_object_id=?"); - stmt->setUInt(1, toReturn); - stmt->execute(); - delete stmt; - } + // So we peroidically save our ObjID to the database: + if (toReturn % 25 == 0) { // TEMP: DISABLED FOR DEBUG / DEVELOPMENT! + sql::PreparedStatement* stmt = Database::CreatePreppedStmt( + "UPDATE object_id_tracker SET last_object_id=?"); + stmt->setUInt(1, toReturn); + stmt->execute(); + delete stmt; + } - return toReturn; + return toReturn; } void ObjectIDManager::SaveToDatabase() { - sql::PreparedStatement *stmt = Database::CreatePreppedStmt( - "UPDATE object_id_tracker SET last_object_id=?"); - stmt->setUInt(1, currentPersistentID); - stmt->execute(); - delete stmt; + sql::PreparedStatement* stmt = Database::CreatePreppedStmt( + "UPDATE object_id_tracker SET last_object_id=?"); + stmt->setUInt(1, currentPersistentID); + stmt->execute(); + delete stmt; } diff --git a/dMasterServer/ObjectIDManager.h b/dMasterServer/ObjectIDManager.h index fd63434b..b18619bc 100644 --- a/dMasterServer/ObjectIDManager.h +++ b/dMasterServer/ObjectIDManager.h @@ -10,38 +10,38 @@ class dLogger; \brief A manager that handles requests for object IDs */ -//! The Object ID Manager + //! The Object ID Manager class ObjectIDManager { private: dLogger* mLogger; - static ObjectIDManager * m_Address; //!< The singleton instance - - uint32_t currentPersistentID; //!< The highest current persistent ID in use - + static ObjectIDManager* m_Address; //!< The singleton instance + + uint32_t currentPersistentID; //!< The highest current persistent ID in use + public: - - //! Return the singleton if it is initialized - static ObjectIDManager* TryInstance() { - return m_Address; - } - //! The singleton method - static ObjectIDManager * Instance() { - if (m_Address == nullptr) { - m_Address = new ObjectIDManager; - } - - return m_Address; - } - - //! Initializes the manager - void Initialize(dLogger* logger); - - //! Generates a new persistent ID - /*! - \return The new persistent ID - */ - uint32_t GeneratePersistentID(void); + //! Return the singleton if it is initialized + static ObjectIDManager* TryInstance() { + return m_Address; + } - void SaveToDatabase(); + //! The singleton method + static ObjectIDManager* Instance() { + if (m_Address == nullptr) { + m_Address = new ObjectIDManager; + } + + return m_Address; + } + + //! Initializes the manager + void Initialize(dLogger* logger); + + //! Generates a new persistent ID + /*! + \return The new persistent ID + */ + uint32_t GeneratePersistentID(void); + + void SaveToDatabase(); }; diff --git a/dNet/AuthPackets.cpp b/dNet/AuthPackets.cpp index 0efce260..60fe13c5 100644 --- a/dNet/AuthPackets.cpp +++ b/dNet/AuthPackets.cpp @@ -119,11 +119,11 @@ void AuthPackets::HandleLoginRequest(dServer* server, Packet* packet) { } if (sqlBanned) { - AuthPackets::SendLoginResponse(server, packet->systemAddress, LOGIN_RESPONSE_BANNED, "", "", 2001, username); return; + AuthPackets::SendLoginResponse(server, packet->systemAddress, LOGIN_RESPONSE_BANNED, "", "", 2001, username); return; } if (sqlLocked) { - AuthPackets::SendLoginResponse(server, packet->systemAddress, LOGIN_RESPONSE_ACCOUNT_LOCKED, "", "", 2001, username); return; + AuthPackets::SendLoginResponse(server, packet->systemAddress, LOGIN_RESPONSE_ACCOUNT_LOCKED, "", "", 2001, username); return; } /* @@ -136,18 +136,14 @@ void AuthPackets::HandleLoginRequest(dServer* server, Packet* packet) { int32_t bcryptState = ::bcrypt_checkpw(password.c_str(), sqlPass.c_str()); - if (bcryptState != 0) - { + if (bcryptState != 0) { // Fallback on old method std::string oldPassword = sha512(password + username); - if (sqlPass != oldPassword) - { + if (sqlPass != oldPassword) { loginSuccess = false; - } - else - { + } else { // Generate new hash for bcrypt char salt[BCRYPT_HASHSIZE]; @@ -168,17 +164,14 @@ void AuthPackets::HandleLoginRequest(dServer* server, Packet* packet) { accountUpdate->executeUpdate(); } - } - else - { + } else { // Login success with bcrypt } if (!loginSuccess) { - AuthPackets::SendLoginResponse(server, packet->systemAddress, LOGIN_RESPONSE_WRONG_PASS_OR_USER, "", "", 2001, username); + AuthPackets::SendLoginResponse(server, packet->systemAddress, LOGIN_RESPONSE_WRONG_PASS_OR_USER, "", "", 2001, username); server->GetLogger()->Log("AuthPackets", "Wrong password used"); - } - else { + } else { SystemAddress system = packet->systemAddress; //Copy the sysAddr before the Packet gets destroyed from main if (!server->GetIsConnectedToMaster()) { @@ -188,74 +181,74 @@ void AuthPackets::HandleLoginRequest(dServer* server, Packet* packet) { ZoneInstanceManager::Instance()->RequestZoneTransfer(server, 0, 0, false, [system, server, username](bool mythranShift, uint32_t zoneID, uint32_t zoneInstance, uint32_t zoneClone, std::string zoneIP, uint16_t zonePort) { AuthPackets::SendLoginResponse(server, system, LOGIN_RESPONSE_SUCCESS, "", zoneIP, zonePort, username); - }); + }); } } void AuthPackets::SendLoginResponse(dServer* server, const SystemAddress& sysAddr, eLoginResponse responseCode, const std::string& errorMsg, const std::string& wServerIP, uint16_t wServerPort, std::string username) { - RakNet::BitStream packet; - PacketUtils::WriteHeader(packet, CLIENT, MSG_CLIENT_LOGIN_RESPONSE); + RakNet::BitStream packet; + PacketUtils::WriteHeader(packet, CLIENT, MSG_CLIENT_LOGIN_RESPONSE); - packet.Write(static_cast(responseCode)); + packet.Write(static_cast(responseCode)); - PacketUtils::WritePacketString("Talk_Like_A_Pirate", 33, &packet); + PacketUtils::WritePacketString("Talk_Like_A_Pirate", 33, &packet); - // 7 unknown strings - perhaps other IP addresses? - PacketUtils::WritePacketString("", 33, &packet); - PacketUtils::WritePacketString("", 33, &packet); - PacketUtils::WritePacketString("", 33, &packet); - PacketUtils::WritePacketString("", 33, &packet); - PacketUtils::WritePacketString("", 33, &packet); - PacketUtils::WritePacketString("", 33, &packet); - PacketUtils::WritePacketString("", 33, &packet); + // 7 unknown strings - perhaps other IP addresses? + PacketUtils::WritePacketString("", 33, &packet); + PacketUtils::WritePacketString("", 33, &packet); + PacketUtils::WritePacketString("", 33, &packet); + PacketUtils::WritePacketString("", 33, &packet); + PacketUtils::WritePacketString("", 33, &packet); + PacketUtils::WritePacketString("", 33, &packet); + PacketUtils::WritePacketString("", 33, &packet); - packet.Write(static_cast(1)); // Version Major - packet.Write(static_cast(10)); // Version Current - packet.Write(static_cast(64)); // Version Minor + packet.Write(static_cast(1)); // Version Major + packet.Write(static_cast(10)); // Version Current + packet.Write(static_cast(64)); // Version Minor - // Writes the user key + // Writes the user key uint32_t sessionKey = rand(); // not mt but whatever std::string userHash = std::to_string(sessionKey); - userHash = md5(userHash); - PacketUtils::WritePacketWString(userHash, 33, &packet); + userHash = md5(userHash); + PacketUtils::WritePacketWString(userHash, 33, &packet); - // Write the Character and Chat IPs - PacketUtils::WritePacketString(wServerIP, 33, &packet); - PacketUtils::WritePacketString("", 33, &packet); + // Write the Character and Chat IPs + PacketUtils::WritePacketString(wServerIP, 33, &packet); + PacketUtils::WritePacketString("", 33, &packet); - // Write the Character and Chat Ports - packet.Write(static_cast(wServerPort)); - packet.Write(static_cast(0)); + // Write the Character and Chat Ports + packet.Write(static_cast(wServerPort)); + packet.Write(static_cast(0)); - // Write another IP - PacketUtils::WritePacketString("", 33, &packet); + // Write another IP + PacketUtils::WritePacketString("", 33, &packet); - // Write a GUID or something... - PacketUtils::WritePacketString("00000000-0000-0000-0000-000000000000", 37, &packet); + // Write a GUID or something... + PacketUtils::WritePacketString("00000000-0000-0000-0000-000000000000", 37, &packet); - packet.Write(static_cast(0)); // ??? + packet.Write(static_cast(0)); // ??? - // Write the localization - PacketUtils::WritePacketString("US", 3, &packet); + // Write the localization + PacketUtils::WritePacketString("US", 3, &packet); - packet.Write(static_cast(false)); // User first logged in? - packet.Write(static_cast(false)); // User is F2P? - packet.Write(static_cast(0)); // ??? + packet.Write(static_cast(false)); // User first logged in? + packet.Write(static_cast(false)); // User is F2P? + packet.Write(static_cast(0)); // ??? - // Write custom error message - packet.Write(static_cast(errorMsg.length())); - PacketUtils::WritePacketWString(errorMsg, static_cast(errorMsg.length()), &packet); + // Write custom error message + packet.Write(static_cast(errorMsg.length())); + PacketUtils::WritePacketWString(errorMsg, static_cast(errorMsg.length()), &packet); - // Here write auth logs - packet.Write(static_cast(20)); - for (uint32_t i = 0; i < 20; ++i) { - packet.Write(static_cast(8)); - packet.Write(static_cast(44)); - packet.Write(static_cast(14000)); - packet.Write(static_cast(0)); - } + // Here write auth logs + packet.Write(static_cast(20)); + for (uint32_t i = 0; i < 20; ++i) { + packet.Write(static_cast(8)); + packet.Write(static_cast(44)); + packet.Write(static_cast(14000)); + packet.Write(static_cast(0)); + } - server->Send(&packet, sysAddr, false); + server->Send(&packet, sysAddr, false); //Inform the master server that we've created a session for this user: { diff --git a/dNet/AuthPackets.h b/dNet/AuthPackets.h index 2830480f..e972d2f7 100644 --- a/dNet/AuthPackets.h +++ b/dNet/AuthPackets.h @@ -10,9 +10,9 @@ class dServer; namespace AuthPackets { void HandleHandshake(dServer* server, Packet* packet); void SendHandshake(dServer* server, const SystemAddress& sysAddr, const std::string& nextServerIP, uint16_t nextServerPort); - + void HandleLoginRequest(dServer* server, Packet* packet); void SendLoginResponse(dServer* server, const SystemAddress& sysAddr, eLoginResponse responseCode, const std::string& errorMsg, const std::string& wServerIP, uint16_t wServerPort, std::string username); } -#endif // AUTHPACKETS_H \ No newline at end of file +#endif // AUTHPACKETS_H diff --git a/dNet/ChatPackets.cpp b/dNet/ChatPackets.cpp index db90bcfe..eb3bda71 100644 --- a/dNet/ChatPackets.cpp +++ b/dNet/ChatPackets.cpp @@ -12,63 +12,63 @@ #include "dServer.h" void ChatPackets::SendChatMessage(const SystemAddress& sysAddr, char chatChannel, const std::string& senderName, LWOOBJID playerObjectID, bool senderMythran, const std::u16string& message) { - CBITSTREAM - PacketUtils::WriteHeader(bitStream, CHAT, MSG_CHAT_GENERAL_CHAT_MESSAGE); - - bitStream.Write(static_cast(0)); - bitStream.Write(chatChannel); - - bitStream.Write(static_cast(message.size())); - PacketUtils::WriteWString(bitStream, senderName, 33); + CBITSTREAM + PacketUtils::WriteHeader(bitStream, CHAT, MSG_CHAT_GENERAL_CHAT_MESSAGE); - bitStream.Write(playerObjectID); - bitStream.Write(static_cast(0)); - bitStream.Write(static_cast(0)); + bitStream.Write(static_cast(0)); + bitStream.Write(chatChannel); - for (uint32_t i = 0; i < message.size(); ++i) { - bitStream.Write(static_cast(message[i])); - } - bitStream.Write(static_cast(0)); - - SEND_PACKET_BROADCAST + bitStream.Write(static_cast(message.size())); + PacketUtils::WriteWString(bitStream, senderName, 33); + + bitStream.Write(playerObjectID); + bitStream.Write(static_cast(0)); + bitStream.Write(static_cast(0)); + + for (uint32_t i = 0; i < message.size(); ++i) { + bitStream.Write(static_cast(message[i])); + } + bitStream.Write(static_cast(0)); + + SEND_PACKET_BROADCAST } void ChatPackets::SendSystemMessage(const SystemAddress& sysAddr, const std::u16string& message, const bool broadcast) { - CBITSTREAM - PacketUtils::WriteHeader(bitStream, CHAT, MSG_CHAT_GENERAL_CHAT_MESSAGE); - - bitStream.Write(static_cast(0)); - bitStream.Write(static_cast(4)); + CBITSTREAM + PacketUtils::WriteHeader(bitStream, CHAT, MSG_CHAT_GENERAL_CHAT_MESSAGE); - bitStream.Write(static_cast(message.size())); - PacketUtils::WriteWString(bitStream, "", 33); + bitStream.Write(static_cast(0)); + bitStream.Write(static_cast(4)); - bitStream.Write(static_cast(0)); - bitStream.Write(static_cast(0)); - bitStream.Write(static_cast(0)); + bitStream.Write(static_cast(message.size())); + PacketUtils::WriteWString(bitStream, "", 33); - for (uint32_t i = 0; i < message.size(); ++i) { - bitStream.Write(static_cast(message[i])); - } + bitStream.Write(static_cast(0)); + bitStream.Write(static_cast(0)); + bitStream.Write(static_cast(0)); + + for (uint32_t i = 0; i < message.size(); ++i) { + bitStream.Write(static_cast(message[i])); + } + + bitStream.Write(static_cast(0)); - bitStream.Write(static_cast(0)); - //This is so Wincent's announcement works: if (sysAddr != UNASSIGNED_SYSTEM_ADDRESS) { SEND_PACKET; return; } - + SEND_PACKET_BROADCAST; } void ChatPackets::SendMessageFail(const SystemAddress& sysAddr) { - //0x00 - "Chat is currently disabled." - //0x01 - "Upgrade to a full LEGO Universe Membership to chat with other players." + //0x00 - "Chat is currently disabled." + //0x01 - "Upgrade to a full LEGO Universe Membership to chat with other players." - CBITSTREAM; - PacketUtils::WriteHeader(bitStream, CLIENT, MSG_CLIENT_SEND_CANNED_TEXT); - bitStream.Write(0); //response type, options above ^ - //docs say there's a wstring here-- no idea what it's for, or if it's even needed so leaving it as is for now. - SEND_PACKET; + CBITSTREAM; + PacketUtils::WriteHeader(bitStream, CLIENT, MSG_CLIENT_SEND_CANNED_TEXT); + bitStream.Write(0); //response type, options above ^ + //docs say there's a wstring here-- no idea what it's for, or if it's even needed so leaving it as is for now. + SEND_PACKET; } diff --git a/dNet/ChatPackets.h b/dNet/ChatPackets.h index aa58977c..8f6de175 100644 --- a/dNet/ChatPackets.h +++ b/dNet/ChatPackets.h @@ -12,9 +12,9 @@ struct SystemAddress; #include "dCommonVars.h" namespace ChatPackets { - void SendChatMessage(const SystemAddress& sysAddr, char chatChannel, const std::string& senderName, LWOOBJID playerObjectID, bool senderMythran, const std::u16string& message); - void SendSystemMessage(const SystemAddress& sysAddr, const std::u16string& message, bool broadcast = false); - void SendMessageFail(const SystemAddress& sysAddr); + void SendChatMessage(const SystemAddress& sysAddr, char chatChannel, const std::string& senderName, LWOOBJID playerObjectID, bool senderMythran, const std::u16string& message); + void SendSystemMessage(const SystemAddress& sysAddr, const std::u16string& message, bool broadcast = false); + void SendMessageFail(const SystemAddress& sysAddr); }; #endif // CHATPACKETS_H diff --git a/dNet/ClientPackets.cpp b/dNet/ClientPackets.cpp index 00c16133..b49801cc 100644 --- a/dNet/ClientPackets.cpp +++ b/dNet/ClientPackets.cpp @@ -176,7 +176,7 @@ void ClientPackets::HandleClientPositionUpdate(const SystemAddress& sysAddr, Pac // Handle statistics auto* characterComponent = entity->GetComponent(); if (characterComponent != nullptr) { - characterComponent->TrackPositionUpdate(position); + characterComponent->TrackPositionUpdate(position); } comp->SetPosition(position); @@ -254,8 +254,7 @@ void ClientPackets::HandleChatModerationRequest(const SystemAddress& sysAddr, Pa // Check if the player has restricted chat access auto* character = entity->GetCharacter(); - if (character->HasPermission(PermissionMap::RestrictedChatAccess)) - { + if (character->HasPermission(PermissionMap::RestrictedChatAccess)) { // Send a message to the player ChatPackets::SendSystemMessage( sysAddr, @@ -341,8 +340,7 @@ void ClientPackets::HandleChatModerationRequest(const SystemAddress& sysAddr, Pa delete res; delete stmt; - } - else if (user->GetIsBestFriendMap().find(receiver) != user->GetIsBestFriendMap().end()) { + } else if (user->GetIsBestFriendMap().find(receiver) != user->GetIsBestFriendMap().end()) { isBestFriend = true; } } diff --git a/dNet/ClientPackets.h b/dNet/ClientPackets.h index 236955fc..a36384e2 100644 --- a/dNet/ClientPackets.h +++ b/dNet/ClientPackets.h @@ -9,9 +9,9 @@ #include "RakNetTypes.h" namespace ClientPackets { - void HandleChatMessage(const SystemAddress& sysAddr, Packet* packet); - void HandleClientPositionUpdate(const SystemAddress& sysAddr, Packet* packet); - void HandleChatModerationRequest(const SystemAddress& sysAddr, Packet* packet); + void HandleChatMessage(const SystemAddress& sysAddr, Packet* packet); + void HandleClientPositionUpdate(const SystemAddress& sysAddr, Packet* packet); + void HandleChatModerationRequest(const SystemAddress& sysAddr, Packet* packet); }; #endif // CLIENTPACKETS_H diff --git a/dNet/MasterPackets.cpp b/dNet/MasterPackets.cpp index bf58d71c..6c55b7dc 100644 --- a/dNet/MasterPackets.cpp +++ b/dNet/MasterPackets.cpp @@ -9,30 +9,30 @@ void MasterPackets::SendPersistentIDRequest(dServer* server, uint64_t requestID) { CBITSTREAM - PacketUtils::WriteHeader(bitStream, MASTER, MSG_MASTER_REQUEST_PERSISTENT_ID); - bitStream.Write(requestID); + PacketUtils::WriteHeader(bitStream, MASTER, MSG_MASTER_REQUEST_PERSISTENT_ID); + bitStream.Write(requestID); server->SendToMaster(&bitStream); } void MasterPackets::SendPersistentIDResponse(dServer* server, const SystemAddress& sysAddr, uint64_t requestID, uint32_t objID) { RakNet::BitStream bitStream; PacketUtils::WriteHeader(bitStream, MASTER, MSG_MASTER_REQUEST_PERSISTENT_ID_RESPONSE); - + bitStream.Write(requestID); bitStream.Write(objID); - + server->Send(&bitStream, sysAddr, false); } void MasterPackets::SendZoneTransferRequest(dServer* server, uint64_t requestID, bool mythranShift, uint32_t zoneID, uint32_t cloneID) { RakNet::BitStream bitStream; - PacketUtils::WriteHeader(bitStream, MASTER, MSG_MASTER_REQUEST_ZONE_TRANSFER); - - bitStream.Write(requestID); - bitStream.Write(static_cast(mythranShift)); - bitStream.Write(zoneID); - bitStream.Write(cloneID); - + PacketUtils::WriteHeader(bitStream, MASTER, MSG_MASTER_REQUEST_ZONE_TRANSFER); + + bitStream.Write(requestID); + bitStream.Write(static_cast(mythranShift)); + bitStream.Write(zoneID); + bitStream.Write(cloneID); + server->SendToMaster(&bitStream); } @@ -66,58 +66,57 @@ void MasterPackets::SendZoneRequestPrivate(dServer* server, uint64_t requestID, server->SendToMaster(&bitStream); } -void MasterPackets::SendWorldReady(dServer* server, LWOMAPID zoneId, LWOINSTANCEID instanceId) -{ +void MasterPackets::SendWorldReady(dServer* server, LWOMAPID zoneId, LWOINSTANCEID instanceId) { RakNet::BitStream bitStream; PacketUtils::WriteHeader(bitStream, MASTER, MSG_MASTER_WORLD_READY); bitStream.Write(zoneId); bitStream.Write(instanceId); - + server->SendToMaster(&bitStream); } void MasterPackets::SendZoneTransferResponse(dServer* server, const SystemAddress& sysAddr, uint64_t requestID, bool mythranShift, uint32_t zoneID, uint32_t zoneInstance, uint32_t zoneClone, const std::string& serverIP, uint32_t serverPort) { - RakNet::BitStream bitStream; - PacketUtils::WriteHeader(bitStream, MASTER, MSG_MASTER_REQUEST_ZONE_TRANSFER_RESPONSE); - - bitStream.Write(requestID); - bitStream.Write(static_cast(mythranShift)); - bitStream.Write(zoneID); - bitStream.Write(zoneInstance); - bitStream.Write(zoneClone); - bitStream.Write(static_cast(serverPort)); - PacketUtils::WriteString(bitStream, serverIP, static_cast(serverIP.size() + 1)); - - server->Send(&bitStream, sysAddr, false); + RakNet::BitStream bitStream; + PacketUtils::WriteHeader(bitStream, MASTER, MSG_MASTER_REQUEST_ZONE_TRANSFER_RESPONSE); + + bitStream.Write(requestID); + bitStream.Write(static_cast(mythranShift)); + bitStream.Write(zoneID); + bitStream.Write(zoneInstance); + bitStream.Write(zoneClone); + bitStream.Write(static_cast(serverPort)); + PacketUtils::WriteString(bitStream, serverIP, static_cast(serverIP.size() + 1)); + + server->Send(&bitStream, sysAddr, false); } void MasterPackets::HandleServerInfo(Packet* packet) { RakNet::BitStream inStream(packet->data, packet->length, false); uint64_t header = inStream.Read(header); - + uint32_t theirPort = 0; uint32_t theirZoneID = 0; uint32_t theirInstanceID = 0; std::string theirIP = ""; - + inStream.Read(theirPort); inStream.Read(theirZoneID); inStream.Read(theirInstanceID); theirIP = PacketUtils::ReadString(inStream.GetReadOffset(), packet, false); //20 is the current offset - + //TODO: Actually mark this server as an available server in the manager } void MasterPackets::SendServerInfo(dServer* server, Packet* packet) { RakNet::BitStream bitStream; PacketUtils::WriteHeader(bitStream, MASTER, MSG_MASTER_SERVER_INFO); - + bitStream.Write(server->GetPort()); bitStream.Write(server->GetZoneID()); bitStream.Write(server->GetInstanceID()); bitStream.Write(server->GetServerType()); PacketUtils::WriteString(bitStream, server->GetIP(), server->GetIP().size()); - + server->SendToMaster(&bitStream); } diff --git a/dNet/MasterPackets.h b/dNet/MasterPackets.h index 19979092..93fd158e 100644 --- a/dNet/MasterPackets.h +++ b/dNet/MasterPackets.h @@ -8,21 +8,21 @@ class dServer; namespace MasterPackets { - void SendPersistentIDRequest(dServer* server, uint64_t requestID); //Called from the World server + void SendPersistentIDRequest(dServer* server, uint64_t requestID); //Called from the World server void SendPersistentIDResponse(dServer* server, const SystemAddress& sysAddr, uint64_t requestID, uint32_t objID); - + void SendZoneTransferRequest(dServer* server, uint64_t requestID, bool mythranShift, uint32_t zoneID, uint32_t cloneID); void SendZoneTransferResponse(dServer* server, const SystemAddress& sysAddr, uint64_t requestID, bool mythranShift, uint32_t zoneID, uint32_t zoneInstance, uint32_t zoneClone, const std::string& serverIP, uint32_t serverPort); - + void HandleServerInfo(Packet* packet); void SendServerInfo(dServer* server, Packet* packet); - + void SendZoneCreatePrivate(dServer* server, uint32_t zoneID, uint32_t cloneID, const std::string& password); - + void SendZoneRequestPrivate(dServer* server, uint64_t requestID, bool mythranShift, const std::string& password); void SendWorldReady(dServer* server, LWOMAPID zoneId, LWOINSTANCEID instanceId); - + void HandleSetSessionKey(Packet* packet); } diff --git a/dNet/PacketUtils.cpp b/dNet/PacketUtils.cpp index 352f54b9..307ff633 100644 --- a/dNet/PacketUtils.cpp +++ b/dNet/PacketUtils.cpp @@ -12,75 +12,74 @@ void PacketUtils::WriteHeader(RakNet::BitStream& bitStream, uint16_t connectionT bitStream.Write(uint8_t(0)); } -uint16_t PacketUtils::ReadPacketU16(uint32_t startLoc, Packet * packet) { - if (startLoc + 2 > packet->length) return 0; - - std::vector t; - for (uint32_t i = startLoc; i < startLoc + 2; i++) t.push_back(packet->data[i]); - return *(uint16_t*)t.data(); +uint16_t PacketUtils::ReadPacketU16(uint32_t startLoc, Packet* packet) { + if (startLoc + 2 > packet->length) return 0; + + std::vector t; + for (uint32_t i = startLoc; i < startLoc + 2; i++) t.push_back(packet->data[i]); + return *(uint16_t*)t.data(); } -uint32_t PacketUtils::ReadPacketU32(uint32_t startLoc, Packet * packet) { - if (startLoc + 4 > packet->length) return 0; - - std::vector t; - for (uint32_t i = startLoc; i < startLoc + 4; i++) { - t.push_back(packet->data[i]); - } - return *(uint32_t*)t.data(); +uint32_t PacketUtils::ReadPacketU32(uint32_t startLoc, Packet* packet) { + if (startLoc + 4 > packet->length) return 0; + + std::vector t; + for (uint32_t i = startLoc; i < startLoc + 4; i++) { + t.push_back(packet->data[i]); + } + return *(uint32_t*)t.data(); } -uint64_t PacketUtils::ReadPacketU64(uint32_t startLoc, Packet * packet) { - if (startLoc + 8 > packet->length) return 0; - - std::vector t; - for (uint32_t i = startLoc; i < startLoc + 8; i++) t.push_back(packet->data[i]); - return *(uint64_t*)t.data(); +uint64_t PacketUtils::ReadPacketU64(uint32_t startLoc, Packet* packet) { + if (startLoc + 8 > packet->length) return 0; + + std::vector t; + for (uint32_t i = startLoc; i < startLoc + 8; i++) t.push_back(packet->data[i]); + return *(uint64_t*)t.data(); } -int64_t PacketUtils::ReadPacketS64(uint32_t startLoc, Packet * packet) { - if (startLoc + 8 > packet->length) return 0; - - std::vector t; - for (size_t i = startLoc; i < startLoc + 8; i++) t.push_back(packet->data[i]); - return *(int64_t*)t.data(); +int64_t PacketUtils::ReadPacketS64(uint32_t startLoc, Packet* packet) { + if (startLoc + 8 > packet->length) return 0; + + std::vector t; + for (size_t i = startLoc; i < startLoc + 8; i++) t.push_back(packet->data[i]); + return *(int64_t*)t.data(); } std::string PacketUtils::ReadString(uint32_t startLoc, Packet* packet, bool wide, uint32_t maxLen) { - std::string readString = ""; + std::string readString = ""; - if (wide) maxLen *= 2; + if (wide) maxLen *= 2; - if (packet->length > startLoc) { - uint32_t i = 0; - while (packet->data[startLoc + i] != '\0' && packet->length > (uint32_t)(startLoc + i) && maxLen > i) { - readString.push_back(packet->data[startLoc + i]); + if (packet->length > startLoc) { + uint32_t i = 0; + while (packet->data[startLoc + i] != '\0' && packet->length > (uint32_t)(startLoc + i) && maxLen > i) { + readString.push_back(packet->data[startLoc + i]); - if (wide) { - i += 2; // Wide-char string - } - else { - i++; // Regular string - } - } - } + if (wide) { + i += 2; // Wide-char string + } else { + i++; // Regular string + } + } + } - return readString; + return readString; } -void PacketUtils::WritePacketString(const std::string& string, uint32_t maxSize, RakNet::BitStream * bitStream) { - uint32_t size = static_cast(string.size()); - uint32_t remSize = static_cast(maxSize - size); - - if (size > maxSize) size = maxSize; - - for (uint32_t i = 0; i < size; ++i) { - bitStream->Write(static_cast(string[i])); - } - - for (uint32_t j = 0; j < remSize; ++j) { - bitStream->Write(static_cast(0)); - } +void PacketUtils::WritePacketString(const std::string& string, uint32_t maxSize, RakNet::BitStream* bitStream) { + uint32_t size = static_cast(string.size()); + uint32_t remSize = static_cast(maxSize - size); + + if (size > maxSize) size = maxSize; + + for (uint32_t i = 0; i < size; ++i) { + bitStream->Write(static_cast(string[i])); + } + + for (uint32_t j = 0; j < remSize; ++j) { + bitStream->Write(static_cast(0)); + } } void PacketUtils::WriteString(RakNet::BitStream& bitStream, const std::string& s, uint32_t maxSize) { @@ -99,60 +98,60 @@ void PacketUtils::WriteString(RakNet::BitStream& bitStream, const std::string& s } void PacketUtils::WriteWString(RakNet::BitStream& bitStream, const std::string& string, uint32_t maxSize) { - uint32_t size = static_cast(string.length()); - uint32_t remSize = static_cast(maxSize - size); - - if (size > maxSize) size = maxSize; - - for (uint32_t i = 0; i < size; ++i) { - bitStream.Write(static_cast(string[i])); - } - - for (uint32_t j = 0; j < remSize; ++j) { - bitStream.Write(static_cast(0)); - } + uint32_t size = static_cast(string.length()); + uint32_t remSize = static_cast(maxSize - size); + + if (size > maxSize) size = maxSize; + + for (uint32_t i = 0; i < size; ++i) { + bitStream.Write(static_cast(string[i])); + } + + for (uint32_t j = 0; j < remSize; ++j) { + bitStream.Write(static_cast(0)); + } } void PacketUtils::WriteWString(RakNet::BitStream& bitStream, const std::u16string& string, uint32_t maxSize) { - uint32_t size = static_cast(string.length()); - uint32_t remSize = static_cast(maxSize - size); - - if (size > maxSize) size = maxSize; - - for (uint32_t i = 0; i < size; ++i) { - bitStream.Write(static_cast(string[i])); - } - - for (uint32_t j = 0; j < remSize; ++j) { - bitStream.Write(static_cast(0)); - } + uint32_t size = static_cast(string.length()); + uint32_t remSize = static_cast(maxSize - size); + + if (size > maxSize) size = maxSize; + + for (uint32_t i = 0; i < size; ++i) { + bitStream.Write(static_cast(string[i])); + } + + for (uint32_t j = 0; j < remSize; ++j) { + bitStream.Write(static_cast(0)); + } } -void PacketUtils::WritePacketWString(const std::string& string, uint32_t maxSize, RakNet::BitStream * bitStream) { - uint32_t size = static_cast(string.length()); - uint32_t remSize = static_cast(maxSize - size); - - if (size > maxSize) size = maxSize; - - for (uint32_t i = 0; i < size; ++i) { - bitStream->Write(static_cast(string[i])); - } - - for (uint32_t j = 0; j < remSize; ++j) { - bitStream->Write(static_cast(0)); - } +void PacketUtils::WritePacketWString(const std::string& string, uint32_t maxSize, RakNet::BitStream* bitStream) { + uint32_t size = static_cast(string.length()); + uint32_t remSize = static_cast(maxSize - size); + + if (size > maxSize) size = maxSize; + + for (uint32_t i = 0; i < size; ++i) { + bitStream->Write(static_cast(string[i])); + } + + for (uint32_t j = 0; j < remSize; ++j) { + bitStream->Write(static_cast(0)); + } } //! Saves a packet to the filesystem -void PacketUtils::SavePacket(const std::string& filename, const char * data, size_t length) { +void PacketUtils::SavePacket(const std::string& filename, const char* data, size_t length) { //If we don't log to the console, don't save the bin files either. This takes up a lot of time. if (!Game::logger->GetIsLoggingToConsole()) return; - std::string path = "packets/" + filename; - - std::ofstream file(path, std::ios::binary); - if (!file.is_open()) return; - - file.write(data, length); - file.close(); + std::string path = "packets/" + filename; + + std::ofstream file(path, std::ios::binary); + if (!file.is_open()) return; + + file.write(data, length); + file.close(); } diff --git a/dNet/PacketUtils.h b/dNet/PacketUtils.h index 61517ccf..fbbd1839 100644 --- a/dNet/PacketUtils.h +++ b/dNet/PacketUtils.h @@ -6,20 +6,20 @@ namespace PacketUtils { void WriteHeader(RakNet::BitStream& bitStream, uint16_t connectionType, uint32_t internalPacketID); - - uint16_t ReadPacketU16(uint32_t startLoc, Packet * packet); - uint32_t ReadPacketU32(uint32_t startLoc, Packet * packet); - uint64_t ReadPacketU64(uint32_t startLoc, Packet * packet); - int64_t ReadPacketS64(uint32_t startLoc, Packet * packet); - std::string ReadString(uint32_t startLoc, Packet * packet, bool wide, uint32_t maxLen = 33); - - void WritePacketString(const std::string& string, uint32_t maxSize, RakNet::BitStream * bitStream); + + uint16_t ReadPacketU16(uint32_t startLoc, Packet* packet); + uint32_t ReadPacketU32(uint32_t startLoc, Packet* packet); + uint64_t ReadPacketU64(uint32_t startLoc, Packet* packet); + int64_t ReadPacketS64(uint32_t startLoc, Packet* packet); + std::string ReadString(uint32_t startLoc, Packet* packet, bool wide, uint32_t maxLen = 33); + + void WritePacketString(const std::string& string, uint32_t maxSize, RakNet::BitStream* bitStream); void WriteString(RakNet::BitStream& bitStream, const std::string& s, uint32_t maxSize); void WriteWString(RakNet::BitStream& bitStream, const std::string& string, uint32_t maxSize); void WriteWString(RakNet::BitStream& bitStream, const std::u16string& string, uint32_t maxSize); - void WritePacketWString(const std::string& string, uint32_t maxSize, RakNet::BitStream * bitStream); - - void SavePacket(const std::string& filename, const char * data, size_t length); + void WritePacketWString(const std::string& string, uint32_t maxSize, RakNet::BitStream* bitStream); + + void SavePacket(const std::string& filename, const char* data, size_t length); }; #endif // PACKETUTILS_H diff --git a/dNet/WorldPackets.cpp b/dNet/WorldPackets.cpp index f7a15c7f..04a7940c 100644 --- a/dNet/WorldPackets.cpp +++ b/dNet/WorldPackets.cpp @@ -16,8 +16,8 @@ #include "ZCompression.h" void WorldPackets::SendLoadStaticZone(const SystemAddress& sysAddr, float x, float y, float z, uint32_t checksum) { - RakNet::BitStream bitStream; - PacketUtils::WriteHeader(bitStream, CLIENT, MSG_CLIENT_LOAD_STATIC_ZONE); + RakNet::BitStream bitStream; + PacketUtils::WriteHeader(bitStream, CLIENT, MSG_CLIENT_LOAD_STATIC_ZONE); auto zone = dZoneManager::Instance()->GetZone()->GetZoneID(); bitStream.Write(static_cast(zone.GetMapID())); @@ -25,19 +25,19 @@ void WorldPackets::SendLoadStaticZone(const SystemAddress& sysAddr, float x, flo //bitStream.Write(static_cast(zone.GetCloneID())); bitStream.Write(0); - bitStream.Write(checksum); - bitStream.Write(static_cast(0)); // ?? + bitStream.Write(checksum); + bitStream.Write(static_cast(0)); // ?? - bitStream.Write(x); - bitStream.Write(y); - bitStream.Write(z); + bitStream.Write(x); + bitStream.Write(y); + bitStream.Write(z); - bitStream.Write(static_cast(0)); // Change this to eventually use 4 on activity worlds + bitStream.Write(static_cast(0)); // Change this to eventually use 4 on activity worlds - SEND_PACKET + SEND_PACKET } -void WorldPackets::SendCharacterList ( const SystemAddress& sysAddr, User* user ) { +void WorldPackets::SendCharacterList(const SystemAddress& sysAddr, User* user) { if (!user) return; RakNet::BitStream bitStream; @@ -45,57 +45,57 @@ void WorldPackets::SendCharacterList ( const SystemAddress& sysAddr, User* user std::vector characters = user->GetCharacters(); bitStream.Write(static_cast(characters.size())); - bitStream.Write(static_cast(0)); //character index in front, just picking 0 + bitStream.Write(static_cast(0)); //character index in front, just picking 0 for (uint32_t i = 0; i < characters.size(); ++i) { bitStream.Write(characters[i]->GetObjectID()); - bitStream.Write(static_cast(0)); + bitStream.Write(static_cast(0)); PacketUtils::WriteWString(bitStream, characters[i]->GetName(), 33); - PacketUtils::WriteWString(bitStream, characters[i]->GetUnapprovedName(), 33); + PacketUtils::WriteWString(bitStream, characters[i]->GetUnapprovedName(), 33); bitStream.Write(static_cast(characters[i]->GetNameRejected())); - bitStream.Write(static_cast(false)); + bitStream.Write(static_cast(false)); PacketUtils::WriteString(bitStream, "", 10); bitStream.Write(characters[i]->GetShirtColor()); - bitStream.Write(characters[i]->GetShirtStyle()); - bitStream.Write(characters[i]->GetPantsColor()); - bitStream.Write(characters[i]->GetHairStyle()); - bitStream.Write(characters[i]->GetHairColor()); - bitStream.Write(characters[i]->GetLeftHand()); - bitStream.Write(characters[i]->GetRightHand()); - bitStream.Write(characters[i]->GetEyebrows()); - bitStream.Write(characters[i]->GetEyes()); - bitStream.Write(characters[i]->GetMouth()); - bitStream.Write(static_cast(0)); + bitStream.Write(characters[i]->GetShirtStyle()); + bitStream.Write(characters[i]->GetPantsColor()); + bitStream.Write(characters[i]->GetHairStyle()); + bitStream.Write(characters[i]->GetHairColor()); + bitStream.Write(characters[i]->GetLeftHand()); + bitStream.Write(characters[i]->GetRightHand()); + bitStream.Write(characters[i]->GetEyebrows()); + bitStream.Write(characters[i]->GetEyes()); + bitStream.Write(characters[i]->GetMouth()); + bitStream.Write(static_cast(0)); - bitStream.Write(static_cast(characters[i]->GetZoneID())); - bitStream.Write(static_cast(characters[i]->GetZoneInstance())); - bitStream.Write(characters[i]->GetZoneClone()); + bitStream.Write(static_cast(characters[i]->GetZoneID())); + bitStream.Write(static_cast(characters[i]->GetZoneInstance())); + bitStream.Write(characters[i]->GetZoneClone()); - bitStream.Write(characters[i]->GetLastLogin()); + bitStream.Write(characters[i]->GetLastLogin()); - const auto& equippedItems = characters[i]->GetEquippedItems(); - bitStream.Write(static_cast(equippedItems.size())); + const auto& equippedItems = characters[i]->GetEquippedItems(); + bitStream.Write(static_cast(equippedItems.size())); - for (uint32_t j = 0; j < equippedItems.size(); ++j) { - bitStream.Write(equippedItems[j]); - } + for (uint32_t j = 0; j < equippedItems.size(); ++j) { + bitStream.Write(equippedItems[j]); + } } SEND_PACKET } -void WorldPackets::SendCharacterCreationResponse ( const SystemAddress& sysAddr, eCreationResponse response ) { +void WorldPackets::SendCharacterCreationResponse(const SystemAddress& sysAddr, eCreationResponse response) { RakNet::BitStream bitStream; PacketUtils::WriteHeader(bitStream, CLIENT, MSG_CLIENT_CHARACTER_CREATE_RESPONSE); bitStream.Write(response); SEND_PACKET } -void WorldPackets::SendCharacterRenameResponse ( const SystemAddress& sysAddr, eRenameResponse response ) { +void WorldPackets::SendCharacterRenameResponse(const SystemAddress& sysAddr, eRenameResponse response) { RakNet::BitStream bitStream; PacketUtils::WriteHeader(bitStream, CLIENT, MSG_CLIENT_CHARACTER_RENAME_RESPONSE); bitStream.Write(response); @@ -103,13 +103,13 @@ void WorldPackets::SendCharacterRenameResponse ( const SystemAddress& sysAddr, e } void WorldPackets::SendCharacterDeleteResponse(const SystemAddress& sysAddr, bool response) { - RakNet::BitStream bitStream; - PacketUtils::WriteHeader(bitStream, CLIENT, MSG_CLIENT_DELETE_CHARACTER_RESPONSE); - bitStream.Write(static_cast(response)); - SEND_PACKET + RakNet::BitStream bitStream; + PacketUtils::WriteHeader(bitStream, CLIENT, MSG_CLIENT_DELETE_CHARACTER_RESPONSE); + bitStream.Write(static_cast(response)); + SEND_PACKET } -void WorldPackets::SendTransferToWorld ( const SystemAddress& sysAddr, const std::string& serverIP, uint32_t serverPort, bool mythranShift ) { +void WorldPackets::SendTransferToWorld(const SystemAddress& sysAddr, const std::string& serverIP, uint32_t serverPort, bool mythranShift) { RakNet::BitStream bitStream; PacketUtils::WriteHeader(bitStream, CLIENT, MSG_CLIENT_TRANSFER_TO_WORLD); @@ -120,7 +120,7 @@ void WorldPackets::SendTransferToWorld ( const SystemAddress& sysAddr, const std SEND_PACKET } -void WorldPackets::SendServerState ( const SystemAddress& sysAddr ) { +void WorldPackets::SendServerState(const SystemAddress& sysAddr) { RakNet::BitStream bitStream; PacketUtils::WriteHeader(bitStream, CLIENT, MSG_CLIENT_SERVER_STATES); bitStream.Write(static_cast(1)); //If the server is receiving this request, it probably is ready anyway. @@ -128,98 +128,98 @@ void WorldPackets::SendServerState ( const SystemAddress& sysAddr ) { } void WorldPackets::SendCreateCharacter(const SystemAddress& sysAddr, Entity* entity, const std::string& xmlData, const std::u16string& username, int32_t gm) { - RakNet::BitStream bitStream; - PacketUtils::WriteHeader(bitStream, CLIENT, MSG_CLIENT_CREATE_CHARACTER); + RakNet::BitStream bitStream; + PacketUtils::WriteHeader(bitStream, CLIENT, MSG_CLIENT_CREATE_CHARACTER); - RakNet::BitStream data; - data.Write(7); //LDF key count + RakNet::BitStream data; + data.Write(7); //LDF key count - auto character = entity->GetComponent(); - if (!character) { - Game::logger->Log("WorldPackets", "Entity is not a character?? what??"); - return; - } + auto character = entity->GetComponent(); + if (!character) { + Game::logger->Log("WorldPackets", "Entity is not a character?? what??"); + return; + } - LDFData* objid = new LDFData(u"objid", entity->GetObjectID()); - LDFData* lot = new LDFData(u"template", 1); - LDFData * xmlConfigData = new LDFData(u"xmlData", xmlData); - LDFData* name = new LDFData(u"name", username); - LDFData* gmlevel = new LDFData(u"gmlevel", gm); - LDFData* chatmode = new LDFData(u"chatmode", gm); - LDFData* reputation = new LDFData(u"reputation", character->GetReputation()); + LDFData* objid = new LDFData(u"objid", entity->GetObjectID()); + LDFData* lot = new LDFData(u"template", 1); + LDFData* xmlConfigData = new LDFData(u"xmlData", xmlData); + LDFData* name = new LDFData(u"name", username); + LDFData* gmlevel = new LDFData(u"gmlevel", gm); + LDFData* chatmode = new LDFData(u"chatmode", gm); + LDFData* reputation = new LDFData(u"reputation", character->GetReputation()); - objid->WriteToPacket(&data); - lot->WriteToPacket(&data); - name->WriteToPacket(&data); - gmlevel->WriteToPacket(&data); - chatmode->WriteToPacket(&data); - xmlConfigData->WriteToPacket(&data); - reputation->WriteToPacket(&data); + objid->WriteToPacket(&data); + lot->WriteToPacket(&data); + name->WriteToPacket(&data); + gmlevel->WriteToPacket(&data); + chatmode->WriteToPacket(&data); + xmlConfigData->WriteToPacket(&data); + reputation->WriteToPacket(&data); - delete objid; - delete lot; - delete xmlConfigData; - delete gmlevel; - delete chatmode; - delete name; - delete reputation; + delete objid; + delete lot; + delete xmlConfigData; + delete gmlevel; + delete chatmode; + delete name; + delete reputation; #ifdef _WIN32 - bitStream.Write(data.GetNumberOfBytesUsed() + 1); - bitStream.Write(0); - bitStream.Write((char*)data.GetData(), data.GetNumberOfBytesUsed()); + bitStream.Write(data.GetNumberOfBytesUsed() + 1); + bitStream.Write(0); + bitStream.Write((char*)data.GetData(), data.GetNumberOfBytesUsed()); #else - //Compress the data before sending: - const int reservedSize = 5 * 1024 * 1024; - uint8_t compressedData[reservedSize]; - size_t size = ZCompression::Compress(data.GetData(), data.GetNumberOfBytesUsed(), compressedData, reservedSize); + //Compress the data before sending: + const int reservedSize = 5 * 1024 * 1024; + uint8_t compressedData[reservedSize]; + size_t size = ZCompression::Compress(data.GetData(), data.GetNumberOfBytesUsed(), compressedData, reservedSize); - bitStream.Write(size + 9); //size of data + header bytes (8) - bitStream.Write(1); //compressed boolean, true - bitStream.Write(data.GetNumberOfBytesUsed()); - bitStream.Write(size); + bitStream.Write(size + 9); //size of data + header bytes (8) + bitStream.Write(1); //compressed boolean, true + bitStream.Write(data.GetNumberOfBytesUsed()); + bitStream.Write(size); - for (size_t i = 0; i < size; i++) - bitStream.Write(compressedData[i]); + for (size_t i = 0; i < size; i++) + bitStream.Write(compressedData[i]); #endif - PacketUtils::SavePacket("chardata.bin", (const char *)bitStream.GetData(), static_cast(bitStream.GetNumberOfBytesUsed())); - SEND_PACKET - Game::logger->Log("WorldPackets", "Sent CreateCharacter for ID: %llu", entity->GetObjectID()); + PacketUtils::SavePacket("chardata.bin", (const char*)bitStream.GetData(), static_cast(bitStream.GetNumberOfBytesUsed())); + SEND_PACKET + Game::logger->Log("WorldPackets", "Sent CreateCharacter for ID: %llu", entity->GetObjectID()); } void WorldPackets::SendChatModerationResponse(const SystemAddress& sysAddr, bool requestAccepted, uint32_t requestID, const std::string& receiver, std::vector> unacceptedItems) { - CBITSTREAM - PacketUtils::WriteHeader(bitStream, CLIENT, MSG_CLIENT_CHAT_MODERATION_STRING); + CBITSTREAM + PacketUtils::WriteHeader(bitStream, CLIENT, MSG_CLIENT_CHAT_MODERATION_STRING); - bitStream.Write(unacceptedItems.empty()); // Is sentence ok? - bitStream.Write(0x16); // Source ID, unknown + bitStream.Write(unacceptedItems.empty()); // Is sentence ok? + bitStream.Write(0x16); // Source ID, unknown - bitStream.Write(static_cast(requestID)); // request ID - bitStream.Write(static_cast(0)); // chat mode + bitStream.Write(static_cast(requestID)); // request ID + bitStream.Write(static_cast(0)); // chat mode - PacketUtils::WritePacketWString(receiver, 42, &bitStream); // receiver name + PacketUtils::WritePacketWString(receiver, 42, &bitStream); // receiver name - for (auto it : unacceptedItems) { - bitStream.Write(it.first); // start index - bitStream.Write(it.second); // length - } + for (auto it : unacceptedItems) { + bitStream.Write(it.first); // start index + bitStream.Write(it.second); // length + } - for (int i = unacceptedItems.size(); 64 > i; i++) { - bitStream.Write(0); - } + for (int i = unacceptedItems.size(); 64 > i; i++) { + bitStream.Write(0); + } - SEND_PACKET + SEND_PACKET } void WorldPackets::SendGMLevelChange(const SystemAddress& sysAddr, bool success, uint8_t highestLevel, uint8_t prevLevel, uint8_t newLevel) { - CBITSTREAM - PacketUtils::WriteHeader(bitStream, CLIENT, MSG_CLIENT_MAKE_GM_RESPONSE); + CBITSTREAM + PacketUtils::WriteHeader(bitStream, CLIENT, MSG_CLIENT_MAKE_GM_RESPONSE); - bitStream.Write(success); - bitStream.Write(highestLevel); - bitStream.Write(prevLevel); - bitStream.Write(newLevel); + bitStream.Write(success); + bitStream.Write(highestLevel); + bitStream.Write(prevLevel); + bitStream.Write(newLevel); - SEND_PACKET + SEND_PACKET } diff --git a/dNet/WorldPackets.h b/dNet/WorldPackets.h index b88602a4..d9951941 100644 --- a/dNet/WorldPackets.h +++ b/dNet/WorldPackets.h @@ -10,16 +10,16 @@ class User; struct SystemAddress; namespace WorldPackets { - void SendLoadStaticZone(const SystemAddress& sysAddr, float x, float y, float z, uint32_t checksum); - void SendCharacterList(const SystemAddress& sysAddr, User * user); + void SendLoadStaticZone(const SystemAddress& sysAddr, float x, float y, float z, uint32_t checksum); + void SendCharacterList(const SystemAddress& sysAddr, User* user); void SendCharacterCreationResponse(const SystemAddress& sysAddr, eCreationResponse response); void SendCharacterRenameResponse(const SystemAddress& sysAddr, eRenameResponse response); - void SendCharacterDeleteResponse(const SystemAddress& sysAddr, bool response); + void SendCharacterDeleteResponse(const SystemAddress& sysAddr, bool response); void SendTransferToWorld(const SystemAddress& sysAddr, const std::string& serverIP, uint32_t serverPort, bool mythranShift); void SendServerState(const SystemAddress& sysAddr); - void SendCreateCharacter(const SystemAddress& sysAddr, Entity* entity, const std::string& xmlData, const std::u16string& username, int32_t gm); + void SendCreateCharacter(const SystemAddress& sysAddr, Entity* entity, const std::string& xmlData, const std::u16string& username, int32_t gm); void SendChatModerationResponse(const SystemAddress& sysAddr, bool requestAccepted, uint32_t requestID, const std::string& receiver, std::vector> unacceptedItems); - void SendGMLevelChange(const SystemAddress& sysAddr, bool success, uint8_t highestLevel, uint8_t prevLevel, uint8_t newLevel); + void SendGMLevelChange(const SystemAddress& sysAddr, bool success, uint8_t highestLevel, uint8_t prevLevel, uint8_t newLevel); } #endif // WORLDPACKETS_H diff --git a/dNet/ZoneInstanceManager.cpp b/dNet/ZoneInstanceManager.cpp index 9e7653a6..b57bb634 100644 --- a/dNet/ZoneInstanceManager.cpp +++ b/dNet/ZoneInstanceManager.cpp @@ -10,60 +10,58 @@ #include // Static Variables -ZoneInstanceManager * ZoneInstanceManager::m_Address = nullptr; +ZoneInstanceManager* ZoneInstanceManager::m_Address = nullptr; //! Requests a zone transfer void ZoneInstanceManager::RequestZoneTransfer(dServer* server, uint32_t zoneID, uint32_t zoneClone, bool mythranShift, std::function callback) { - - ZoneTransferRequest * request = new ZoneTransferRequest(); - request->requestID = ++currentRequestID; - request->callback = callback; - - this->requests.push_back(request); - - MasterPackets::SendZoneTransferRequest(server, request->requestID, mythranShift, zoneID, zoneClone); + + ZoneTransferRequest* request = new ZoneTransferRequest(); + request->requestID = ++currentRequestID; + request->callback = callback; + + this->requests.push_back(request); + + MasterPackets::SendZoneTransferRequest(server, request->requestID, mythranShift, zoneID, zoneClone); } //! Handles a zone transfer response -void ZoneInstanceManager::HandleRequestZoneTransferResponse(uint64_t requestID, Packet * packet) { - - bool mythranShift = static_cast(packet->data[16]); - uint32_t zoneID = PacketUtils::ReadPacketU32(17, packet); - uint32_t zoneInstance = PacketUtils::ReadPacketU32(21, packet); - uint32_t zoneClone = PacketUtils::ReadPacketU32(25, packet); - uint16_t serverPort = PacketUtils::ReadPacketU16(29, packet); - std::string serverIP = PacketUtils::ReadString(31, packet, false); - - for (uint32_t i = 0; i < this->requests.size(); ++i) { - if (this->requests[i]->requestID == requestID) { - - // Call the request callback - this->requests[i]->callback(mythranShift, zoneID, zoneInstance, zoneClone, serverIP, serverPort); - - delete this->requests[i]; - this->requests.erase(this->requests.begin() + i); - return; - } - } - +void ZoneInstanceManager::HandleRequestZoneTransferResponse(uint64_t requestID, Packet* packet) { + + bool mythranShift = static_cast(packet->data[16]); + uint32_t zoneID = PacketUtils::ReadPacketU32(17, packet); + uint32_t zoneInstance = PacketUtils::ReadPacketU32(21, packet); + uint32_t zoneClone = PacketUtils::ReadPacketU32(25, packet); + uint16_t serverPort = PacketUtils::ReadPacketU16(29, packet); + std::string serverIP = PacketUtils::ReadString(31, packet, false); + + for (uint32_t i = 0; i < this->requests.size(); ++i) { + if (this->requests[i]->requestID == requestID) { + + // Call the request callback + this->requests[i]->callback(mythranShift, zoneID, zoneInstance, zoneClone, serverIP, serverPort); + + delete this->requests[i]; + this->requests.erase(this->requests.begin() + i); + return; + } + } + } -void ZoneInstanceManager::CreatePrivateZone(dServer* server, uint32_t zoneID, uint32_t zoneClone, const std::string& password) -{ - MasterPackets::SendZoneCreatePrivate(server, zoneID, zoneClone, password); +void ZoneInstanceManager::CreatePrivateZone(dServer* server, uint32_t zoneID, uint32_t zoneClone, const std::string& password) { + MasterPackets::SendZoneCreatePrivate(server, zoneID, zoneClone, password); } void ZoneInstanceManager::RequestPrivateZone( - dServer* server, - bool mythranShift, + dServer* server, + bool mythranShift, const std::string& password, - std::function callback) -{ - ZoneTransferRequest* request = new ZoneTransferRequest(); - request->requestID = ++currentRequestID; - request->callback = callback; + std::function callback) { + ZoneTransferRequest* request = new ZoneTransferRequest(); + request->requestID = ++currentRequestID; + request->callback = callback; - this->requests.push_back(request); + this->requests.push_back(request); - MasterPackets::SendZoneRequestPrivate(server, request->requestID, mythranShift, password); + MasterPackets::SendZoneRequestPrivate(server, request->requestID, mythranShift, password); } diff --git a/dNet/ZoneInstanceManager.h b/dNet/ZoneInstanceManager.h index d81fe3c3..a8e32c4e 100644 --- a/dNet/ZoneInstanceManager.h +++ b/dNet/ZoneInstanceManager.h @@ -16,50 +16,50 @@ class dServer; \brief A class for handling zone transfers and zone-related functions */ -//! The zone request + //! The zone request struct ZoneTransferRequest { - uint64_t requestID; - std::function callback; + uint64_t requestID; + std::function callback; }; //! The zone manager class ZoneInstanceManager { private: - static ZoneInstanceManager * m_Address; //!< The singleton instance - - std::vector requests; //!< The zone transfer requests - uint64_t currentRequestID; //!< The current request ID - -public: - - //! The singleton method - static ZoneInstanceManager * Instance() { - if (m_Address == 0) { - m_Address = new ZoneInstanceManager; - m_Address->currentRequestID = 0; - } - - return m_Address; - } - - //! Requests a zone transfer - /*! - \param zoneID The zone ID - \param zoneClone The zone clone - \param mythranShift Whether or not this is a mythran shift - \param callback The callback function - */ - void RequestZoneTransfer(dServer* server, uint32_t zoneID, uint32_t zoneClone, bool mythranShift, std::function callback); - - //! Handles a zone transfer response - /*! - \param requestID The request ID - \param packet The packet - */ - void HandleRequestZoneTransferResponse(uint64_t requestID, Packet * packet); + static ZoneInstanceManager* m_Address; //!< The singleton instance - void CreatePrivateZone(dServer* server, uint32_t zoneID, uint32_t zoneClone, const std::string& password); - - void RequestPrivateZone(dServer* server, bool mythranShift, const std::string& password, std::function callback); + std::vector requests; //!< The zone transfer requests + uint64_t currentRequestID; //!< The current request ID + +public: + + //! The singleton method + static ZoneInstanceManager* Instance() { + if (m_Address == 0) { + m_Address = new ZoneInstanceManager; + m_Address->currentRequestID = 0; + } + + return m_Address; + } + + //! Requests a zone transfer + /*! + \param zoneID The zone ID + \param zoneClone The zone clone + \param mythranShift Whether or not this is a mythran shift + \param callback The callback function + */ + void RequestZoneTransfer(dServer* server, uint32_t zoneID, uint32_t zoneClone, bool mythranShift, std::function callback); + + //! Handles a zone transfer response + /*! + \param requestID The request ID + \param packet The packet + */ + void HandleRequestZoneTransferResponse(uint64_t requestID, Packet* packet); + + void CreatePrivateZone(dServer* server, uint32_t zoneID, uint32_t zoneClone, const std::string& password); + + void RequestPrivateZone(dServer* server, bool mythranShift, const std::string& password, std::function callback); }; diff --git a/dNet/dMessageIdentifiers.h b/dNet/dMessageIdentifiers.h index 4e88a9af..7dc08711 100644 --- a/dNet/dMessageIdentifiers.h +++ b/dNet/dMessageIdentifiers.h @@ -252,7 +252,7 @@ enum MASTER { MSG_MASTER_WORLD_READY, MSG_MASTER_PREP_ZONE, - + MSG_MASTER_SHUTDOWN, MSG_MASTER_SHUTDOWN_RESPONSE, MSG_MASTER_SHUTDOWN_IMMEDIATE, diff --git a/dNet/dNetCommon.h b/dNet/dNetCommon.h index 10103f3b..73a90bc0 100644 --- a/dNet/dNetCommon.h +++ b/dNet/dNetCommon.h @@ -3,4 +3,4 @@ #include "RakPeer.h" #define NET_PASSWORD_EXTERNAL "3.25 ND1" -#define NET_PASSWORD_INTERNAL "3.25 DARKFLAME1" \ No newline at end of file +#define NET_PASSWORD_INTERNAL "3.25 DARKFLAME1" diff --git a/dNet/dServer.cpp b/dNet/dServer.cpp index 56a73c1f..4c032f33 100644 --- a/dNet/dServer.cpp +++ b/dNet/dServer.cpp @@ -14,25 +14,25 @@ //! Replica Constructor class class ReplicaConstructor : public ReceiveConstructionInterface { public: - ReplicaReturnResult ReceiveConstruction(RakNet::BitStream *inBitStream, RakNetTime timestamp, NetworkID networkID, NetworkIDObject *existingObject, SystemAddress senderId, ReplicaManager *caller) { - return REPLICA_PROCESSING_DONE; - } + ReplicaReturnResult ReceiveConstruction(RakNet::BitStream* inBitStream, RakNetTime timestamp, NetworkID networkID, NetworkIDObject* existingObject, SystemAddress senderId, ReplicaManager* caller) { + return REPLICA_PROCESSING_DONE; + } } ConstructionCB; //! Replica Download Sender class class ReplicaSender : public SendDownloadCompleteInterface { public: - ReplicaReturnResult SendDownloadComplete(RakNet::BitStream *outBitStream, RakNetTime currentTime, SystemAddress senderId, ReplicaManager *caller) { - return REPLICA_PROCESSING_DONE; - } + ReplicaReturnResult SendDownloadComplete(RakNet::BitStream* outBitStream, RakNetTime currentTime, SystemAddress senderId, ReplicaManager* caller) { + return REPLICA_PROCESSING_DONE; + } } SendDownloadCompleteCB; //! Replica Download Receiver class class ReplicaReceiever : public ReceiveDownloadCompleteInterface { public: - ReplicaReturnResult ReceiveDownloadComplete(RakNet::BitStream *inBitStream, SystemAddress senderId, ReplicaManager *caller) { - return REPLICA_PROCESSING_DONE; - } + ReplicaReturnResult ReceiveDownloadComplete(RakNet::BitStream* inBitStream, SystemAddress senderId, ReplicaManager* caller) { + return REPLICA_PROCESSING_DONE; + } } ReceiveDownloadCompleteCB; dServer::dServer(const std::string& ip, int port, int instanceID, int maxConnections, bool isInternal, bool useEncryption, dLogger* logger, const std::string masterIP, int masterPort, ServerType serverType, unsigned int zoneID) { @@ -63,8 +63,7 @@ dServer::dServer(const std::string& ip, int port, int instanceID, int maxConnect mLogger->Log("dServer", "Server is listening on %s:%i with encryption: %i", ip.c_str(), port, int(useEncryption)); else mLogger->Log("dServer", "Server is listening on %s:%i with encryption: %i, running zone %i / %i", ip.c_str(), port, int(useEncryption), zoneID, instanceID); - } - else { mLogger->Log("dServer", "FAILED TO START SERVER ON IP/PORT: %s:%i", ip.c_str(), port); return; } + } else { mLogger->Log("dServer", "FAILED TO START SERVER ON IP/PORT: %s:%i", ip.c_str(), port); return; } mLogger->SetLogToConsole(prevLogSetting); @@ -110,7 +109,7 @@ Packet* dServer::ReceiveFromMaster() { } if (packet->data[0] == ID_CONNECTION_REQUEST_ACCEPTED) { - mLogger->Log("dServer", "Established connection to master, zone (%i), instance (%i)",this->GetZoneID(), this->GetInstanceID()); + mLogger->Log("dServer", "Established connection to master, zone (%i), instance (%i)", this->GetZoneID(), this->GetInstanceID()); mMasterConnectionActive = true; mMasterSystemAddress = packet->systemAddress; MasterPackets::SendServerInfo(this, packet); @@ -119,16 +118,16 @@ Packet* dServer::ReceiveFromMaster() { if (packet->data[0] == ID_USER_PACKET_ENUM) { if (packet->data[1] == MASTER) { switch (packet->data[3]) { - case MSG_MASTER_REQUEST_ZONE_TRANSFER_RESPONSE: { - uint64_t requestID = PacketUtils::ReadPacketU64(8, packet); - ZoneInstanceManager::Instance()->HandleRequestZoneTransferResponse(requestID, packet); - break; - } + case MSG_MASTER_REQUEST_ZONE_TRANSFER_RESPONSE: { + uint64_t requestID = PacketUtils::ReadPacketU64(8, packet); + ZoneInstanceManager::Instance()->HandleRequestZoneTransferResponse(requestID, packet); + break; + } - //When we handle these packets in World instead dServer, we just return the packet's pointer. - default: + //When we handle these packets in World instead dServer, we just return the packet's pointer. + default: - return packet; + return packet; } } } @@ -143,15 +142,15 @@ Packet* dServer::Receive() { return mPeer->Receive(); } -void dServer::DeallocatePacket(Packet * packet) { +void dServer::DeallocatePacket(Packet* packet) { mPeer->DeallocatePacket(packet); } -void dServer::DeallocateMasterPacket(Packet * packet) { +void dServer::DeallocateMasterPacket(Packet* packet) { mMasterPeer->DeallocatePacket(packet); } -void dServer::Send(RakNet::BitStream * bitStream, const SystemAddress & sysAddr, bool broadcast) { +void dServer::Send(RakNet::BitStream* bitStream, const SystemAddress& sysAddr, bool broadcast) { mPeer->Send(bitStream, SYSTEM_PRIORITY, RELIABLE_ORDERED, 0, sysAddr, broadcast); } @@ -182,8 +181,7 @@ bool dServer::Startup() { if (mIsInternal) { mPeer->SetIncomingPassword("3.25 DARKFLAME1", 15); - } - else { + } else { //mPeer->SetPerConnectionOutgoingBandwidthLimit(800000); //100Kb/s mPeer->SetIncomingPassword("3.25 ND1", 8); } @@ -228,12 +226,10 @@ void dServer::UpdateReplica() { mReplicaManager->Update(mPeer); } -int dServer::GetPing(const SystemAddress& sysAddr) const -{ +int dServer::GetPing(const SystemAddress& sysAddr) const { return mPeer->GetAveragePing(sysAddr); } -int dServer::GetLatestPing(const SystemAddress& sysAddr) const -{ +int dServer::GetLatestPing(const SystemAddress& sysAddr) const { return mPeer->GetLastPing(sysAddr); } diff --git a/dNet/dServer.h b/dNet/dServer.h index 3ac6700a..bd052f86 100644 --- a/dNet/dServer.h +++ b/dNet/dServer.h @@ -61,7 +61,7 @@ private: NetworkIDManager* mNetIDManager; SocketDescriptor mSocketDescriptor; std::string mIP; - int mPort; + int mPort; int mMaxConnections; unsigned int mZoneID; int mInstanceID; @@ -76,4 +76,4 @@ private: SystemAddress mMasterSystemAddress; std::string mMasterIP; int mMasterPort; -}; \ No newline at end of file +}; diff --git a/dPhysics/Singleton.h b/dPhysics/Singleton.h index b923202f..750a4996 100644 --- a/dPhysics/Singleton.h +++ b/dPhysics/Singleton.h @@ -16,4 +16,4 @@ public: protected: Singleton() = default; -}; \ No newline at end of file +}; diff --git a/dPhysics/dpCollisionChecks.cpp b/dPhysics/dpCollisionChecks.cpp index 5e18f894..c2efee90 100644 --- a/dPhysics/dpCollisionChecks.cpp +++ b/dPhysics/dpCollisionChecks.cpp @@ -54,7 +54,7 @@ bool dpCollisionChecks::CheckBoxes(dpEntity* a, dpEntity* b) { /*//Check if we're overlapping on X/Z: if ((boxA->GetMaxWidth() >= boxB->GetMinWidth()) && //If our max width is greater than starting X of b (boxA->GetMinWidth() <= boxB->GetMaxWidth()) && //If our start x is less than b's max width - (boxA->GetMaxDepth() >= boxB->GetMinDepth()) && + (boxA->GetMaxDepth() >= boxB->GetMinDepth()) && (boxA->GetMinDepth() <= boxB->GetMaxDepth())) { //Check if we're in the right height @@ -93,8 +93,7 @@ bool dpCollisionChecks::CheckSphereBox(dpEntity* a, dpEntity* b) { sphere = static_cast(b->GetShape()); boxPos = a->GetPosition(); spherePos = b->GetPosition(); - } - else { + } else { box = static_cast(b->GetShape()); sphere = static_cast(a->GetShape()); boxPos = b->GetPosition(); @@ -110,8 +109,8 @@ bool dpCollisionChecks::CheckSphereBox(dpEntity* a, dpEntity* b) { float dX = x - spherePos.x; float dY = y - spherePos.y; float dZ = z - spherePos.z; - float distanceSquared = (dX * dX) + (dY * dY) + (dZ * dZ); + float distanceSquared = (dX * dX) + (dY * dY) + (dZ * dZ); const float radius = sphere->GetRadius(); - return distanceSquared < radius * radius; + return distanceSquared < radius* radius; } diff --git a/dPhysics/dpCollisionChecks.h b/dPhysics/dpCollisionChecks.h index ed51bbe4..069832f9 100644 --- a/dPhysics/dpCollisionChecks.h +++ b/dPhysics/dpCollisionChecks.h @@ -9,4 +9,4 @@ namespace dpCollisionChecks { bool CheckBoxes(dpEntity* a, dpEntity* b); bool CheckSphereBox(dpEntity* a, dpEntity* b); -}; \ No newline at end of file +}; diff --git a/dPhysics/dpCollisionGroups.h b/dPhysics/dpCollisionGroups.h index 5853070f..ad9807b9 100644 --- a/dPhysics/dpCollisionGroups.h +++ b/dPhysics/dpCollisionGroups.h @@ -8,9 +8,9 @@ enum eCollisionGroup : uint8_t { - COLLISION_GROUP_ALL = 0 << 0, - COLLISION_GROUP_NEUTRAL = 1 << 0, - COLLISION_GROUP_FRIENDLY = 1 << 1, - COLLISION_GROUP_ENEMY = 1 << 2, - COLLISION_GROUP_DYNAMIC = 1 << 3, + COLLISION_GROUP_ALL = 0 << 0, + COLLISION_GROUP_NEUTRAL = 1 << 0, + COLLISION_GROUP_FRIENDLY = 1 << 1, + COLLISION_GROUP_ENEMY = 1 << 2, + COLLISION_GROUP_DYNAMIC = 1 << 3, }; diff --git a/dPhysics/dpCommon.h b/dPhysics/dpCommon.h index 344ad9c0..51583048 100644 --- a/dPhysics/dpCommon.h +++ b/dPhysics/dpCommon.h @@ -4,4 +4,4 @@ enum class dpShapeType : unsigned short { Invalid = 0, Sphere, Box -}; \ No newline at end of file +}; diff --git a/dPhysics/dpEntity.cpp b/dPhysics/dpEntity.cpp index 78920807..42c195f2 100644 --- a/dPhysics/dpEntity.cpp +++ b/dPhysics/dpEntity.cpp @@ -89,8 +89,7 @@ void dpEntity::CheckCollision(dpEntity* other) { //if (m_CollisionShape->GetShapeType() == dpShapeType::Sphere && other->GetShape()->GetShapeType() == dpShapeType::Sphere) //std::cout << "started sphere col at: " << other->GetPosition().x << ", " << other->GetPosition().y << ", " << other->GetPosition().z << std::endl; - } - else if (!isColliding && wasFound) { + } else if (!isColliding && wasFound) { m_CurrentlyCollidingObjects.erase(other->GetObjectID()); m_RemovedObjects.push_back(other); diff --git a/dPhysics/dpEntity.h b/dPhysics/dpEntity.h index cc363f8b..ea7a49b2 100644 --- a/dPhysics/dpEntity.h +++ b/dPhysics/dpEntity.h @@ -83,4 +83,4 @@ private: std::vector m_NewObjects; std::vector m_RemovedObjects; std::map m_CurrentlyCollidingObjects; -}; \ No newline at end of file +}; diff --git a/dPhysics/dpGrid.h b/dPhysics/dpGrid.h index 532ee02f..a10f165e 100644 --- a/dPhysics/dpGrid.h +++ b/dPhysics/dpGrid.h @@ -9,26 +9,26 @@ class dpEntity; class dpGrid { public: - //LU has a chunk size of 64x64, with each chunk unit being 3.2 ingame units. - int NUM_CELLS = 12; //Most worlds consist of 10 or 11 chunks, so I'm picking 12 to be safe. - int CELL_SIZE = 205; //64 * 3.2 = 204.8 rounded up + //LU has a chunk size of 64x64, with each chunk unit being 3.2 ingame units. + int NUM_CELLS = 12; //Most worlds consist of 10 or 11 chunks, so I'm picking 12 to be safe. + int CELL_SIZE = 205; //64 * 3.2 = 204.8 rounded up public: - dpGrid(int numCells, int cellSize); - ~dpGrid(); + dpGrid(int numCells, int cellSize); + ~dpGrid(); - void Add(dpEntity* entity); - void Move(dpEntity* entity, float x, float z); - void Delete(dpEntity* entity); + void Add(dpEntity* entity); + void Move(dpEntity* entity, float x, float z); + void Delete(dpEntity* entity); - void Update(float deltaTime); + void Update(float deltaTime); private: - void HandleEntity(dpEntity* entity, dpEntity* other); - void HandleCell(int x, int z, float deltaTime); + void HandleEntity(dpEntity* entity, dpEntity* other); + void HandleCell(int x, int z, float deltaTime); private: - //cells on X, cells on Y for that X, then another vector that contains the entities within that cell. - std::vector>> m_Cells; - std::map m_GargantuanObjects; + //cells on X, cells on Y for that X, then another vector that contains the entities within that cell. + std::vector>> m_Cells; + std::map m_GargantuanObjects; }; diff --git a/dPhysics/dpShapeBase.cpp b/dPhysics/dpShapeBase.cpp index c6562e71..54575159 100644 --- a/dPhysics/dpShapeBase.cpp +++ b/dPhysics/dpShapeBase.cpp @@ -3,8 +3,7 @@ #include dpShapeBase::dpShapeBase(dpEntity* parentEntity) : - m_ParentEntity(parentEntity) -{ + m_ParentEntity(parentEntity) { } dpShapeBase::~dpShapeBase() { @@ -14,4 +13,4 @@ bool dpShapeBase::IsColliding(dpShapeBase* other) { std::cout << "Base shapes do not have any *shape* to them, and thus cannot be overlapping." << std::endl; std::cout << "You should be using a shape class inherited from this base class." << std::endl; return false; -} \ No newline at end of file +} diff --git a/dPhysics/dpShapeBase.h b/dPhysics/dpShapeBase.h index 3bf52f50..60d908c9 100644 --- a/dPhysics/dpShapeBase.h +++ b/dPhysics/dpShapeBase.h @@ -17,4 +17,4 @@ public: protected: dpEntity* m_ParentEntity; dpShapeType m_ShapeType = dpShapeType::Invalid; -}; \ No newline at end of file +}; diff --git a/dPhysics/dpShapeBox.cpp b/dPhysics/dpShapeBox.cpp index 766ffb35..b40be6af 100644 --- a/dPhysics/dpShapeBox.cpp +++ b/dPhysics/dpShapeBox.cpp @@ -11,11 +11,10 @@ dpShapeBox::dpShapeBox(dpEntity* parentEntity, float width, float height, float depth) : dpShapeBase(parentEntity), - m_Width(width/2), - m_Height(height/2), - m_Depth(depth/2), - m_Scale(1.0f) -{ + m_Width(width / 2), + m_Height(height / 2), + m_Depth(depth / 2), + m_Scale(1.0f) { m_ShapeType = dpShapeType::Box; InitVertices(); diff --git a/dPhysics/dpShapeBox.h b/dPhysics/dpShapeBox.h index ec80012b..4af0396e 100644 --- a/dPhysics/dpShapeBox.h +++ b/dPhysics/dpShapeBox.h @@ -69,4 +69,4 @@ private: bool isTransformed = false; void InsertVertices(); -}; \ No newline at end of file +}; diff --git a/dPhysics/dpShapeSphere.cpp b/dPhysics/dpShapeSphere.cpp index bc1ceef5..168a3b21 100644 --- a/dPhysics/dpShapeSphere.cpp +++ b/dPhysics/dpShapeSphere.cpp @@ -4,8 +4,7 @@ dpShapeSphere::dpShapeSphere(dpEntity* parentEntity, float radius) : dpShapeBase(parentEntity), - m_Radius(radius) -{ + m_Radius(radius) { m_ShapeType = dpShapeType::Sphere; } diff --git a/dPhysics/dpShapeSphere.h b/dPhysics/dpShapeSphere.h index 3b23673a..a5d8142b 100644 --- a/dPhysics/dpShapeSphere.h +++ b/dPhysics/dpShapeSphere.h @@ -14,4 +14,4 @@ public: private: float m_Radius; -}; \ No newline at end of file +}; diff --git a/dPhysics/dpWorld.cpp b/dPhysics/dpWorld.cpp index 4caaab40..666171c0 100644 --- a/dPhysics/dpWorld.cpp +++ b/dPhysics/dpWorld.cpp @@ -77,8 +77,7 @@ void dpWorld::RemoveEntity(dpEntity* entity) { if (m_Grid) { m_Grid->Delete(entity); - } - else { + } else { if (entity->GetIsStatic()) { for (size_t i = 0; i < m_StaticEntities.size(); ++i) { if (m_StaticEntities[i] == entity) { @@ -87,8 +86,7 @@ void dpWorld::RemoveEntity(dpEntity* entity) { break; } } - } - else { + } else { for (size_t i = 0; i < m_DynamicEntites.size(); ++i) { if (m_DynamicEntites[i] == entity) { delete m_DynamicEntites[i]; @@ -127,8 +125,7 @@ bool dpWorld::LoadNavmeshByZoneID(unsigned int zoneID) { std::string path = "./res/maps/navmeshes/" + std::to_string(zoneID) + ".bin"; m_navMesh = LoadNavmesh(path.c_str()); - if (m_navMesh) { m_navQuery = dtAllocNavMeshQuery(); m_navQuery->init(m_navMesh, 2048); } - else return false; + if (m_navMesh) { m_navQuery = dtAllocNavMeshQuery(); m_navQuery->init(m_navMesh, 2048); } else return false; return true; } @@ -136,14 +133,14 @@ bool dpWorld::LoadNavmeshByZoneID(unsigned int zoneID) { dtNavMesh* dpWorld::LoadNavmesh(const char* path) { FILE* fp; - #ifdef _WIN32 - fopen_s(&fp, path, "rb"); - #elif __APPLE__ - // macOS has 64bit file IO by default - fp = fopen(path, "rb"); - #else - fp = fopen64(path, "rb"); - #endif +#ifdef _WIN32 + fopen_s(&fp, path, "rb"); +#elif __APPLE__ + // macOS has 64bit file IO by default + fp = fopen(path, "rb"); +#else + fp = fopen64(path, "rb"); +#endif if (!fp) { return 0; @@ -347,8 +344,7 @@ std::vector dpWorld::GetPath(const NiPoint3& startPos, const NiPoint3& path.push_back(newPoint); } } - } - else { + } else { m_npolys = 0; m_nstraightPath = 0; } diff --git a/dPhysics/dpWorld.h b/dPhysics/dpWorld.h index 5897a7cd..5362803f 100644 --- a/dPhysics/dpWorld.h +++ b/dPhysics/dpWorld.h @@ -77,4 +77,4 @@ private: class dtNavMeshQuery* m_navQuery; unsigned char m_navMeshDrawFlags; rcContext* m_ctx; -}; \ No newline at end of file +}; diff --git a/dPhysics/main.cpp b/dPhysics/main.cpp index a4c303a3..7de1555a 100644 --- a/dPhysics/main.cpp +++ b/dPhysics/main.cpp @@ -32,4 +32,4 @@ int main() { } return 0; -}*/ \ No newline at end of file +}*/ diff --git a/dScripts/ActMine.cpp b/dScripts/ActMine.cpp index 9cc116b1..637bd805 100644 --- a/dScripts/ActMine.cpp +++ b/dScripts/ActMine.cpp @@ -8,8 +8,7 @@ void ActMine::OnStartup(Entity* self) { self->SetProximityRadius(MINE_RADIUS, "mineRadius"); } -void ActMine::OnRebuildNotifyState(Entity* self, eRebuildState state) -{ +void ActMine::OnRebuildNotifyState(Entity* self, eRebuildState state) { if (state == eRebuildState::REBUILD_COMPLETED) { auto* rebuild = self->GetComponent(); if (rebuild) { @@ -35,7 +34,7 @@ void ActMine::OnProximityUpdate(Entity* self, Entity* entering, std::string name void ActMine::OnTimerDone(Entity* self, std::string timerName) { if (timerName == "Tick") { - if (self->GetVar(u"NumWarnings") >= MAX_WARNINGS){ + if (self->GetVar(u"NumWarnings") >= MAX_WARNINGS) { auto* skill = self->GetComponent(); if (!skill) return; skill->CalculateBehavior(SKILL_ID, BEHAVIOR_ID, LWOOBJID_EMPTY); @@ -50,4 +49,4 @@ void ActMine::OnTimerDone(Entity* self, std::string timerName) { if (timerName == "BlowedUp") { self->Kill(self); } -} \ No newline at end of file +} diff --git a/dScripts/ActMine.h b/dScripts/ActMine.h index ae6ef17e..fb222f2e 100644 --- a/dScripts/ActMine.h +++ b/dScripts/ActMine.h @@ -2,17 +2,17 @@ #include "CppScripts.h" class ActMine : public CppScripts::Script { - public: - void OnStartup(Entity* self) override; - void OnRebuildNotifyState(Entity* self, eRebuildState state) override; - void OnProximityUpdate(Entity* self, Entity* entering, std::string name, std::string status) override; - void OnTimerDone(Entity* self, std::string timerName) override; - private: - int MAX_WARNINGS = 3; - float MINE_RADIUS = 10.0; - float TICK_TIME = 0.25; - float BLOWED_UP_TIME = 0.1; - uint32_t SKILL_ID = 317; - uint32_t BEHAVIOR_ID = 3719; +public: + void OnStartup(Entity* self) override; + void OnRebuildNotifyState(Entity* self, eRebuildState state) override; + void OnProximityUpdate(Entity* self, Entity* entering, std::string name, std::string status) override; + void OnTimerDone(Entity* self, std::string timerName) override; +private: + int MAX_WARNINGS = 3; + float MINE_RADIUS = 10.0; + float TICK_TIME = 0.25; + float BLOWED_UP_TIME = 0.1; + uint32_t SKILL_ID = 317; + uint32_t BEHAVIOR_ID = 3719; }; diff --git a/dScripts/ActNinjaTurret.cpp b/dScripts/ActNinjaTurret.cpp index 8c361ad7..79e502b4 100644 --- a/dScripts/ActNinjaTurret.cpp +++ b/dScripts/ActNinjaTurret.cpp @@ -1,23 +1,17 @@ #include "ActNinjaTurret.h" -void ActNinjaTurret::OnRebuildNotifyState(Entity* self, eRebuildState state) -{ - if (state == eRebuildState::REBUILD_COMPLETED) - { - self->SetVar(u"AmBuilt", true); - } - else if (state == eRebuildState::REBUILD_RESETTING) - { - self->SetVar(u"AmBuilt", false); - } +void ActNinjaTurret::OnRebuildNotifyState(Entity* self, eRebuildState state) { + if (state == eRebuildState::REBUILD_COMPLETED) { + self->SetVar(u"AmBuilt", true); + } else if (state == eRebuildState::REBUILD_RESETTING) { + self->SetVar(u"AmBuilt", false); + } } void -ActNinjaTurret::OnFireEventServerSide(Entity *self, Entity *sender, std::string args, int32_t param1, int32_t param2, - int32_t param3) -{ - if (args == "ISpawned" && self->GetVar(u"AmBuilt")) - { - sender->Smash(); - } +ActNinjaTurret::OnFireEventServerSide(Entity* self, Entity* sender, std::string args, int32_t param1, int32_t param2, + int32_t param3) { + if (args == "ISpawned" && self->GetVar(u"AmBuilt")) { + sender->Smash(); + } } diff --git a/dScripts/ActNinjaTurret.h b/dScripts/ActNinjaTurret.h index 5251750a..d06e6afd 100644 --- a/dScripts/ActNinjaTurret.h +++ b/dScripts/ActNinjaTurret.h @@ -5,7 +5,7 @@ class ActNinjaTurret : public CppScripts::Script { public: void OnRebuildNotifyState(Entity* self, eRebuildState state) override; - void OnFireEventServerSide(Entity *self, Entity *sender, std::string args, int32_t param1, int32_t param2, - int32_t param3) override; + void OnFireEventServerSide(Entity* self, Entity* sender, std::string args, int32_t param1, int32_t param2, + int32_t param3) override; }; diff --git a/dScripts/ActParadoxPipeFix.cpp b/dScripts/ActParadoxPipeFix.cpp index 2b592512..1dddde64 100644 --- a/dScripts/ActParadoxPipeFix.cpp +++ b/dScripts/ActParadoxPipeFix.cpp @@ -4,70 +4,58 @@ #include "GameMessages.h" #include "MissionComponent.h" -void ActParadoxPipeFix::OnRebuildComplete(Entity* self, Entity* target) -{ - const auto myGroup = "AllPipes"; +void ActParadoxPipeFix::OnRebuildComplete(Entity* self, Entity* target) { + const auto myGroup = "AllPipes"; - const auto groupObjs = EntityManager::Instance()->GetEntitiesInGroup(myGroup); + const auto groupObjs = EntityManager::Instance()->GetEntitiesInGroup(myGroup); - auto indexCount = 0; + auto indexCount = 0; - self->SetVar(u"PlayerID", target->GetObjectID()); + self->SetVar(u"PlayerID", target->GetObjectID()); - for (auto* object : groupObjs) - { - if (object == self) - { - continue; - } + for (auto* object : groupObjs) { + if (object == self) { + continue; + } - auto* rebuildComponent = object->GetComponent(); + auto* rebuildComponent = object->GetComponent(); - if (rebuildComponent->GetState() == REBUILD_COMPLETED) - { - indexCount++; - } - } + if (rebuildComponent->GetState() == REBUILD_COMPLETED) { + indexCount++; + } + } - if (indexCount >= 2) - { - const auto refinery = EntityManager::Instance()->GetEntitiesInGroup("Paradox"); + if (indexCount >= 2) { + const auto refinery = EntityManager::Instance()->GetEntitiesInGroup("Paradox"); - if (!refinery.empty()) - { - GameMessages::SendPlayFXEffect(refinery[0]->GetObjectID(), 3999, u"create", "pipeFX"); - } + if (!refinery.empty()) { + GameMessages::SendPlayFXEffect(refinery[0]->GetObjectID(), 3999, u"create", "pipeFX"); + } - for (auto* object : groupObjs) - { - auto* player = EntityManager::Instance()->GetEntity(object->GetVar(u"PlayerID")); + for (auto* object : groupObjs) { + auto* player = EntityManager::Instance()->GetEntity(object->GetVar(u"PlayerID")); - if (player != nullptr) - { - auto* missionComponent = player->GetComponent(); + if (player != nullptr) { + auto* missionComponent = player->GetComponent(); - if (missionComponent != nullptr) - { - missionComponent->ForceProgressTaskType(769, 1, 1, false); - } + if (missionComponent != nullptr) { + missionComponent->ForceProgressTaskType(769, 1, 1, false); + } - GameMessages::SendPlayCinematic(player->GetObjectID(), u"ParadoxPipeFinish", player->GetSystemAddress(), true, true, false, false, 0, false, 2.0f); - } - - object->SetVar(u"PlayerID", LWOOBJID_EMPTY); - } - } + GameMessages::SendPlayCinematic(player->GetObjectID(), u"ParadoxPipeFinish", player->GetSystemAddress(), true, true, false, false, 0, false, 2.0f); + } + + object->SetVar(u"PlayerID", LWOOBJID_EMPTY); + } + } } -void ActParadoxPipeFix::OnRebuildNotifyState(Entity* self, eRebuildState state) -{ - if (state == REBUILD_RESETTING) - { - const auto refinery = EntityManager::Instance()->GetEntitiesInGroup("Paradox"); +void ActParadoxPipeFix::OnRebuildNotifyState(Entity* self, eRebuildState state) { + if (state == REBUILD_RESETTING) { + const auto refinery = EntityManager::Instance()->GetEntitiesInGroup("Paradox"); - if (!refinery.empty()) - { - GameMessages::SendStopFXEffect(refinery[0], true, "pipeFX"); - } - } + if (!refinery.empty()) { + GameMessages::SendStopFXEffect(refinery[0], true, "pipeFX"); + } + } } diff --git a/dScripts/ActParadoxPipeFix.h b/dScripts/ActParadoxPipeFix.h index b8b19cc2..df323b00 100644 --- a/dScripts/ActParadoxPipeFix.h +++ b/dScripts/ActParadoxPipeFix.h @@ -4,7 +4,7 @@ class ActParadoxPipeFix : public CppScripts::Script { public: - void OnRebuildComplete(Entity* self, Entity* target) override; + void OnRebuildComplete(Entity* self, Entity* target) override; void OnRebuildNotifyState(Entity* self, eRebuildState state) override; }; diff --git a/dScripts/ActPlayerDeathTrigger.cpp b/dScripts/ActPlayerDeathTrigger.cpp index 0601e25d..28f1ef43 100644 --- a/dScripts/ActPlayerDeathTrigger.cpp +++ b/dScripts/ActPlayerDeathTrigger.cpp @@ -1,8 +1,7 @@ #include "ActPlayerDeathTrigger.h" -void ActPlayerDeathTrigger::OnCollisionPhantom(Entity* self, Entity* target) -{ +void ActPlayerDeathTrigger::OnCollisionPhantom(Entity* self, Entity* target) { if (!target->IsPlayer() || target->GetIsDead() || !target->GetPlayerReadyForUpdates()) return; //Don't kill already dead players or players not ready - - target->Smash(self->GetObjectID(), eKillType::SILENT); + + target->Smash(self->GetObjectID(), eKillType::SILENT); } diff --git a/dScripts/ActSharkPlayerDeathTrigger.cpp b/dScripts/ActSharkPlayerDeathTrigger.cpp index a8aaac8b..420fc4d7 100644 --- a/dScripts/ActSharkPlayerDeathTrigger.cpp +++ b/dScripts/ActSharkPlayerDeathTrigger.cpp @@ -3,8 +3,8 @@ #include "MissionTaskType.h" #include "Entity.h" -void ActSharkPlayerDeathTrigger::OnFireEventServerSide(Entity *self, Entity *sender, std::string args, int32_t param1, - int32_t param2, int32_t param3) { +void ActSharkPlayerDeathTrigger::OnFireEventServerSide(Entity* self, Entity* sender, std::string args, int32_t param1, + int32_t param2, int32_t param3) { if (args == "achieve") { auto missionComponent = sender->GetComponent(); if (!missionComponent) return; diff --git a/dScripts/ActSharkPlayerDeathTrigger.h b/dScripts/ActSharkPlayerDeathTrigger.h index cbd3c960..d76ae5be 100644 --- a/dScripts/ActSharkPlayerDeathTrigger.h +++ b/dScripts/ActSharkPlayerDeathTrigger.h @@ -4,7 +4,7 @@ class ActSharkPlayerDeathTrigger : public CppScripts::Script { public: - void OnFireEventServerSide(Entity *self, Entity *sender, std::string args, int32_t param1, int32_t param2, - int32_t param3) override; + void OnFireEventServerSide(Entity* self, Entity* sender, std::string args, int32_t param1, int32_t param2, + int32_t param3) override; }; diff --git a/dScripts/ActVehicleDeathTrigger.cpp b/dScripts/ActVehicleDeathTrigger.cpp index 9a970a35..77a3b65a 100644 --- a/dScripts/ActVehicleDeathTrigger.cpp +++ b/dScripts/ActVehicleDeathTrigger.cpp @@ -7,56 +7,46 @@ #include "PossessorComponent.h" -void ActVehicleDeathTrigger::OnCollisionPhantom(Entity* self, Entity* target) -{ - auto* possessableComponent = target->GetComponent(); +void ActVehicleDeathTrigger::OnCollisionPhantom(Entity* self, Entity* target) { + auto* possessableComponent = target->GetComponent(); - Entity* vehicle; - Entity* player; + Entity* vehicle; + Entity* player; - if (possessableComponent != nullptr) - { - auto* player = EntityManager::Instance()->GetEntity(possessableComponent->GetPossessor()); + if (possessableComponent != nullptr) { + auto* player = EntityManager::Instance()->GetEntity(possessableComponent->GetPossessor()); - if (player == nullptr) - { - return; - } + if (player == nullptr) { + return; + } - return; - } - else if (target->IsPlayer()) - { - auto* possessorComponent = target->GetComponent(); + return; + } else if (target->IsPlayer()) { + auto* possessorComponent = target->GetComponent(); - if (possessorComponent == nullptr) - { - return; - } + if (possessorComponent == nullptr) { + return; + } - vehicle = EntityManager::Instance()->GetEntity(possessorComponent->GetPossessable()); + vehicle = EntityManager::Instance()->GetEntity(possessorComponent->GetPossessable()); - if (vehicle == nullptr) - { - return; - } + if (vehicle == nullptr) { + return; + } - player = target; - } - else - { - return; - } - + player = target; + } else { + return; + } - GameMessages::SendDie(vehicle, self->GetObjectID(), LWOOBJID_EMPTY, true, VIOLENT, u"", 0, 0, 0, true, false, 0); - auto* zoneController = dZoneManager::Instance()->GetZoneControlObject(); + GameMessages::SendDie(vehicle, self->GetObjectID(), LWOOBJID_EMPTY, true, VIOLENT, u"", 0, 0, 0, true, false, 0); - auto* racingControlComponent = zoneController->GetComponent(); + auto* zoneController = dZoneManager::Instance()->GetZoneControlObject(); - if (racingControlComponent != nullptr) - { - racingControlComponent->OnRequestDie(player); - } + auto* racingControlComponent = zoneController->GetComponent(); + + if (racingControlComponent != nullptr) { + racingControlComponent->OnRequestDie(player); + } } diff --git a/dScripts/ActivityManager.cpp b/dScripts/ActivityManager.cpp index 56766482..18d72311 100644 --- a/dScripts/ActivityManager.cpp +++ b/dScripts/ActivityManager.cpp @@ -6,215 +6,212 @@ #include #include "dLogger.h" -bool ActivityManager::IsPlayerInActivity(Entity *self, LWOOBJID playerID) { - const auto* sac = self->GetComponent(); - return sac != nullptr && sac->IsPlayedBy(playerID); +bool ActivityManager::IsPlayerInActivity(Entity* self, LWOOBJID playerID) { + const auto* sac = self->GetComponent(); + return sac != nullptr && sac->IsPlayedBy(playerID); } -void ActivityManager::UpdatePlayer(Entity *self, LWOOBJID playerID, const bool remove) { - auto* sac = self->GetComponent(); - if (sac == nullptr) - return; +void ActivityManager::UpdatePlayer(Entity* self, LWOOBJID playerID, const bool remove) { + auto* sac = self->GetComponent(); + if (sac == nullptr) + return; - if (remove) { - sac->PlayerRemove(playerID); - } else { - auto* player = EntityManager::Instance()->GetEntity(playerID); - if (player != nullptr) { - sac->PlayerJoin(player); - SetActivityScore(self, playerID, 0); - } - } + if (remove) { + sac->PlayerRemove(playerID); + } else { + auto* player = EntityManager::Instance()->GetEntity(playerID); + if (player != nullptr) { + sac->PlayerJoin(player); + SetActivityScore(self, playerID, 0); + } + } } -void ActivityManager::SetActivityScore(Entity *self, LWOOBJID playerID, uint32_t score) { - SetActivityValue(self, playerID, 0, score); +void ActivityManager::SetActivityScore(Entity* self, LWOOBJID playerID, uint32_t score) { + SetActivityValue(self, playerID, 0, score); } -void ActivityManager::SetActivityValue(Entity *self, const LWOOBJID playerID, const uint32_t valueIndex, - const float_t value) { - auto* sac = self->GetComponent(); - if (sac == nullptr) - return; +void ActivityManager::SetActivityValue(Entity* self, const LWOOBJID playerID, const uint32_t valueIndex, + const float_t value) { + auto* sac = self->GetComponent(); + if (sac == nullptr) + return; - sac->SetActivityValue(playerID, valueIndex, value); + sac->SetActivityValue(playerID, valueIndex, value); } -float_t ActivityManager::GetActivityValue(Entity *self, const LWOOBJID playerID, const uint32_t valueIndex) { - auto* sac = self->GetComponent(); - if (sac == nullptr) - return -1.0f; +float_t ActivityManager::GetActivityValue(Entity* self, const LWOOBJID playerID, const uint32_t valueIndex) { + auto* sac = self->GetComponent(); + if (sac == nullptr) + return -1.0f; - return sac->GetActivityValue(playerID, valueIndex); + return sac->GetActivityValue(playerID, valueIndex); } -void ActivityManager::StopActivity(Entity *self, const LWOOBJID playerID, const uint32_t score, - const uint32_t value1, const uint32_t value2, bool quit) { - int32_t gameID = 0; +void ActivityManager::StopActivity(Entity* self, const LWOOBJID playerID, const uint32_t score, + const uint32_t value1, const uint32_t value2, bool quit) { + int32_t gameID = 0; - auto* sac = self->GetComponent(); - if (sac == nullptr) { - gameID = self->GetLOT(); - } - else { - gameID = sac->GetActivityID(); - } + auto* sac = self->GetComponent(); + if (sac == nullptr) { + gameID = self->GetLOT(); + } else { + gameID = sac->GetActivityID(); + } - if (quit) { - UpdatePlayer(self, playerID, true); - } else { - auto* player = EntityManager::Instance()->GetEntity(playerID); - if (player == nullptr) - return; + if (quit) { + UpdatePlayer(self, playerID, true); + } else { + auto* player = EntityManager::Instance()->GetEntity(playerID); + if (player == nullptr) + return; - SetActivityScore(self, playerID, score); - SetActivityValue(self, playerID, 1, value1); - SetActivityValue(self, playerID, 2, value2); + SetActivityScore(self, playerID, score); + SetActivityValue(self, playerID, 1, value1); + SetActivityValue(self, playerID, 2, value2); - LootGenerator::Instance().GiveActivityLoot(player, self, gameID, CalculateActivityRating(self, playerID)); + LootGenerator::Instance().GiveActivityLoot(player, self, gameID, CalculateActivityRating(self, playerID)); - // Save the new score to the leaderboard and show the leaderboard to the player - LeaderboardManager::SaveScore(playerID, gameID, score, value1); - const auto* leaderboard = LeaderboardManager::GetLeaderboard(gameID, InfoType::Standings, - false, player->GetObjectID()); - GameMessages::SendActivitySummaryLeaderboardData(self->GetObjectID(), leaderboard, player->GetSystemAddress()); - delete leaderboard; + // Save the new score to the leaderboard and show the leaderboard to the player + LeaderboardManager::SaveScore(playerID, gameID, score, value1); + const auto* leaderboard = LeaderboardManager::GetLeaderboard(gameID, InfoType::Standings, + false, player->GetObjectID()); + GameMessages::SendActivitySummaryLeaderboardData(self->GetObjectID(), leaderboard, player->GetSystemAddress()); + delete leaderboard; - // Makes the leaderboard show up for the player - GameMessages::SendNotifyClientObject(self->GetObjectID(), u"ToggleLeaderBoard", - gameID,0, playerID, "", - player->GetSystemAddress()); + // Makes the leaderboard show up for the player + GameMessages::SendNotifyClientObject(self->GetObjectID(), u"ToggleLeaderBoard", + gameID, 0, playerID, "", + player->GetSystemAddress()); - if (sac != nullptr) { - sac->PlayerRemove(player->GetObjectID()); - } - } + if (sac != nullptr) { + sac->PlayerRemove(player->GetObjectID()); + } + } } -bool ActivityManager::TakeActivityCost(const Entity *self, const LWOOBJID playerID) { - auto* sac = self->GetComponent(); - if (sac == nullptr) - return false; +bool ActivityManager::TakeActivityCost(const Entity* self, const LWOOBJID playerID) { + auto* sac = self->GetComponent(); + if (sac == nullptr) + return false; - auto* player = EntityManager::Instance()->GetEntity(playerID); - if (player == nullptr) - return false; + auto* player = EntityManager::Instance()->GetEntity(playerID); + if (player == nullptr) + return false; - return sac->TakeCost(player); + return sac->TakeCost(player); } -uint32_t ActivityManager::CalculateActivityRating(Entity *self, const LWOOBJID playerID) { - auto* sac = self->GetComponent(); - if (sac == nullptr) - return 0; +uint32_t ActivityManager::CalculateActivityRating(Entity* self, const LWOOBJID playerID) { + auto* sac = self->GetComponent(); + if (sac == nullptr) + return 0; - return sac->GetInstance(playerID)->GetParticipants().size(); + return sac->GetInstance(playerID)->GetParticipants().size(); } uint32_t ActivityManager::GetActivityID(const Entity* self) { - auto* sac = self->GetComponent(); - return sac != nullptr ? sac->GetActivityID() : 0; + auto* sac = self->GetComponent(); + return sac != nullptr ? sac->GetActivityID() : 0; } -void ActivityManager::GetLeaderboardData(Entity *self, const LWOOBJID playerID, const uint32_t activityID, uint32_t numResults) { - LeaderboardManager::SendLeaderboard(activityID, Standings, false, self->GetObjectID(), playerID); +void ActivityManager::GetLeaderboardData(Entity* self, const LWOOBJID playerID, const uint32_t activityID, uint32_t numResults) { + LeaderboardManager::SendLeaderboard(activityID, Standings, false, self->GetObjectID(), playerID); } -void ActivityManager::ActivityTimerStart(Entity *self, const std::string& timerName, const float_t updateInterval, - const float_t stopTime) { - auto* timer = new ActivityTimer { timerName, updateInterval, stopTime }; - activeTimers.push_back(timer); +void ActivityManager::ActivityTimerStart(Entity* self, const std::string& timerName, const float_t updateInterval, + const float_t stopTime) { + auto* timer = new ActivityTimer{ timerName, updateInterval, stopTime }; + activeTimers.push_back(timer); - Game::logger->Log("ActivityManager", "Starting timer '%s', %f, %f", timerName.c_str(), updateInterval, stopTime); + Game::logger->Log("ActivityManager", "Starting timer '%s', %f, %f", timerName.c_str(), updateInterval, stopTime); - self->AddTimer(GetPrefixedName(timer->name), timer->updateInterval); + self->AddTimer(GetPrefixedName(timer->name), timer->updateInterval); } void ActivityManager::ActivityTimerStopAllTimers(Entity* self) { - for (auto* timer : activeTimers) { - self->CancelTimer(GetPrefixedName(timer->name)); - delete timer; - } + for (auto* timer : activeTimers) { + self->CancelTimer(GetPrefixedName(timer->name)); + delete timer; + } - activeTimers.clear(); + activeTimers.clear(); } -float_t ActivityManager::ActivityTimerGetCurrentTime(Entity *self, const std::string &timerName) const { - auto* timer = GetTimer(timerName); - return timer != nullptr ? timer->runTime : 0.0f; +float_t ActivityManager::ActivityTimerGetCurrentTime(Entity* self, const std::string& timerName) const { + auto* timer = GetTimer(timerName); + return timer != nullptr ? timer->runTime : 0.0f; } -int32_t ActivityManager::GetGameID(Entity *self) const -{ - int32_t gameID = 0; +int32_t ActivityManager::GetGameID(Entity* self) const { + int32_t gameID = 0; - auto* sac = self->GetComponent(); - if (sac == nullptr) { - gameID = self->GetLOT(); - } - else { - gameID = sac->GetActivityID(); - } + auto* sac = self->GetComponent(); + if (sac == nullptr) { + gameID = self->GetLOT(); + } else { + gameID = sac->GetActivityID(); + } - return gameID; + return gameID; } -float_t ActivityManager::ActivityTimerGetRemainingTime(Entity *self, const std::string &timerName) const { - auto* timer = GetTimer(timerName); - return timer != nullptr ? std::min(timer->stopTime - timer->runTime, 0.0f) : 0.0f; +float_t ActivityManager::ActivityTimerGetRemainingTime(Entity* self, const std::string& timerName) const { + auto* timer = GetTimer(timerName); + return timer != nullptr ? std::min(timer->stopTime - timer->runTime, 0.0f) : 0.0f; } -void ActivityManager::ActivityTimerReset(Entity *self, const std::string &timerName) { - auto* timer = GetTimer(timerName); - if (timer != nullptr) { - timer->runTime = 0.0f; - } +void ActivityManager::ActivityTimerReset(Entity* self, const std::string& timerName) { + auto* timer = GetTimer(timerName); + if (timer != nullptr) { + timer->runTime = 0.0f; + } } -ActivityTimer* ActivityManager::GetTimer(const std::string &name) const { - for (auto* timer : activeTimers) { - if (timer->name == name) - return timer; - } +ActivityTimer* ActivityManager::GetTimer(const std::string& name) const { + for (auto* timer : activeTimers) { + if (timer->name == name) + return timer; + } - return nullptr; + return nullptr; } -void ActivityManager::ActivityTimerStop(Entity *self, const std::string &timerName) { - auto* timer = GetTimer(timerName); - if (timer != nullptr) { - self->CancelTimer(GetPrefixedName(timer->name)); +void ActivityManager::ActivityTimerStop(Entity* self, const std::string& timerName) { + auto* timer = GetTimer(timerName); + if (timer != nullptr) { + self->CancelTimer(GetPrefixedName(timer->name)); - activeTimers.erase(std::remove(activeTimers.begin(), activeTimers.end(), timer), - activeTimers.end()); - delete timer; - } + activeTimers.erase(std::remove(activeTimers.begin(), activeTimers.end(), timer), + activeTimers.end()); + delete timer; + } } -std::string ActivityManager::GetPrefixedName(const std::string &name) const { - return TimerPrefix + "_" + name; +std::string ActivityManager::GetPrefixedName(const std::string& name) const { + return TimerPrefix + "_" + name; } -void ActivityManager::OnTimerDone(Entity *self, std::string timerName) { - auto nameSplit = GeneralUtils::SplitString(timerName, '_'); - if (nameSplit.size() > 1 && nameSplit.at(0) == TimerPrefix) { - const auto& activityTimerName = nameSplit.at(1); - auto* timer = GetTimer(activityTimerName); +void ActivityManager::OnTimerDone(Entity* self, std::string timerName) { + auto nameSplit = GeneralUtils::SplitString(timerName, '_'); + if (nameSplit.size() > 1 && nameSplit.at(0) == TimerPrefix) { + const auto& activityTimerName = nameSplit.at(1); + auto* timer = GetTimer(activityTimerName); - if (timer != nullptr) { - timer->runTime += timer->updateInterval; + if (timer != nullptr) { + timer->runTime += timer->updateInterval; - if (timer->stopTime != -1.0f && timer->runTime >= timer->stopTime) { - activeTimers.erase(std::remove(activeTimers.begin(), activeTimers.end(), timer), - activeTimers.end()); - delete timer; - Game::logger->Log("ActivityManager", "Executing timer '%s'", activityTimerName.c_str()); - OnActivityTimerDone(self, activityTimerName); - } else { - Game::logger->Log("ActivityManager", "Updating timer '%s'", activityTimerName.c_str()); - OnActivityTimerUpdate(self, timer->name, timer->stopTime - timer->runTime, timer->runTime); - self->AddTimer(GetPrefixedName(timer->name), timer->updateInterval); - } - } - } + if (timer->stopTime != -1.0f && timer->runTime >= timer->stopTime) { + activeTimers.erase(std::remove(activeTimers.begin(), activeTimers.end(), timer), + activeTimers.end()); + delete timer; + Game::logger->Log("ActivityManager", "Executing timer '%s'", activityTimerName.c_str()); + OnActivityTimerDone(self, activityTimerName); + } else { + Game::logger->Log("ActivityManager", "Updating timer '%s'", activityTimerName.c_str()); + OnActivityTimerUpdate(self, timer->name, timer->stopTime - timer->runTime, timer->runTime); + self->AddTimer(GetPrefixedName(timer->name), timer->updateInterval); + } + } + } } diff --git a/dScripts/ActivityManager.h b/dScripts/ActivityManager.h index 3b5783ad..640cf4bf 100644 --- a/dScripts/ActivityManager.h +++ b/dScripts/ActivityManager.h @@ -2,41 +2,41 @@ #include "CppScripts.h" struct ActivityTimer { - std::string name; - float_t updateInterval; - float_t stopTime; - float_t runTime = 0; + std::string name; + float_t updateInterval; + float_t stopTime; + float_t runTime = 0; }; class ActivityManager : public CppScripts::Script { public: - static bool IsPlayerInActivity(Entity *self, LWOOBJID playerID); - static void UpdatePlayer(Entity *self, LWOOBJID playerID, bool remove = false); - static void SetActivityScore(Entity *self, LWOOBJID playerID, uint32_t score); - static void SetActivityValue(Entity *self, LWOOBJID playerID, uint32_t valueIndex, float_t value); - static float_t GetActivityValue(Entity *self, LWOOBJID playerID, uint32_t valueIndex) ; - static bool TakeActivityCost(const Entity* self, LWOOBJID playerID); - static uint32_t GetActivityID(const Entity* self); - void StopActivity(Entity *self, LWOOBJID playerID, uint32_t score, uint32_t value1 = 0, uint32_t value2 = 0, bool quit = false); - virtual uint32_t CalculateActivityRating(Entity* self, LWOOBJID playerID); - static void GetLeaderboardData(Entity *self, LWOOBJID playerID, uint32_t activityID, uint32_t numResults = 0); -// void FreezePlayer(Entity *self, const LWOOBJID playerID, const bool state) const; + static bool IsPlayerInActivity(Entity* self, LWOOBJID playerID); + static void UpdatePlayer(Entity* self, LWOOBJID playerID, bool remove = false); + static void SetActivityScore(Entity* self, LWOOBJID playerID, uint32_t score); + static void SetActivityValue(Entity* self, LWOOBJID playerID, uint32_t valueIndex, float_t value); + static float_t GetActivityValue(Entity* self, LWOOBJID playerID, uint32_t valueIndex); + static bool TakeActivityCost(const Entity* self, LWOOBJID playerID); + static uint32_t GetActivityID(const Entity* self); + void StopActivity(Entity* self, LWOOBJID playerID, uint32_t score, uint32_t value1 = 0, uint32_t value2 = 0, bool quit = false); + virtual uint32_t CalculateActivityRating(Entity* self, LWOOBJID playerID); + static void GetLeaderboardData(Entity* self, LWOOBJID playerID, uint32_t activityID, uint32_t numResults = 0); + // void FreezePlayer(Entity *self, const LWOOBJID playerID, const bool state) const; - // Activity timer - void OnTimerDone(Entity *self, std::string timerName) override; - virtual void OnActivityTimerDone(Entity* self, const std::string& name) {}; - virtual void OnActivityTimerUpdate(Entity* self, const std::string& name, float_t timeRemaining, float_t elapsedTime) {}; - void ActivityTimerStart(Entity *self, const std::string& timerName, float_t updateInterval, float_t stopTime = -1.0f); - void ActivityTimerReset(Entity *self, const std::string& timerName); - void ActivityTimerStop(Entity* self, const std::string& timerName); - void ActivityTimerStopAllTimers(Entity* self); - float_t ActivityTimerGetRemainingTime(Entity *self, const std::string& timerName) const; - float_t ActivityTimerGetCurrentTime(Entity *self, const std::string& timerName) const; - int32_t GetGameID(Entity* self) const; + // Activity timer + void OnTimerDone(Entity* self, std::string timerName) override; + virtual void OnActivityTimerDone(Entity* self, const std::string& name) {}; + virtual void OnActivityTimerUpdate(Entity* self, const std::string& name, float_t timeRemaining, float_t elapsedTime) {}; + void ActivityTimerStart(Entity* self, const std::string& timerName, float_t updateInterval, float_t stopTime = -1.0f); + void ActivityTimerReset(Entity* self, const std::string& timerName); + void ActivityTimerStop(Entity* self, const std::string& timerName); + void ActivityTimerStopAllTimers(Entity* self); + float_t ActivityTimerGetRemainingTime(Entity* self, const std::string& timerName) const; + float_t ActivityTimerGetCurrentTime(Entity* self, const std::string& timerName) const; + int32_t GetGameID(Entity* self) const; private: - std::string GetPrefixedName(const std::string& name) const; - [[nodiscard]] ActivityTimer* GetTimer(const std::string& name) const; - std::vector activeTimers {}; + std::string GetPrefixedName(const std::string& name) const; + [[nodiscard]] ActivityTimer* GetTimer(const std::string& name) const; + std::vector activeTimers{}; - std::string TimerPrefix = "ActivityTimer"; + std::string TimerPrefix = "ActivityTimer"; }; diff --git a/dScripts/AgBugsprayer.cpp b/dScripts/AgBugsprayer.cpp index cfea5cf4..d4ab7aa3 100644 --- a/dScripts/AgBugsprayer.cpp +++ b/dScripts/AgBugsprayer.cpp @@ -1,20 +1,17 @@ #include "AgBugsprayer.h" #include "SkillComponent.h" -void AgBugsprayer::OnRebuildComplete(Entity* self, Entity* target) -{ - self->AddTimer("castSkill", 1); - self->SetOwnerOverride(target->GetObjectID()); +void AgBugsprayer::OnRebuildComplete(Entity* self, Entity* target) { + self->AddTimer("castSkill", 1); + self->SetOwnerOverride(target->GetObjectID()); } -void AgBugsprayer::OnTimerDone(Entity* self, std::string timerName) -{ - if (timerName == "castSkill") - { - auto* skillComponent = self->GetComponent(); - - if (skillComponent == nullptr) return; +void AgBugsprayer::OnTimerDone(Entity* self, std::string timerName) { + if (timerName == "castSkill") { + auto* skillComponent = self->GetComponent(); - skillComponent->CalculateBehavior(1435, 36581, LWOOBJID_EMPTY); - } -} \ No newline at end of file + if (skillComponent == nullptr) return; + + skillComponent->CalculateBehavior(1435, 36581, LWOOBJID_EMPTY); + } +} diff --git a/dScripts/AgBugsprayer.h b/dScripts/AgBugsprayer.h index 711fe708..055feb36 100644 --- a/dScripts/AgBugsprayer.h +++ b/dScripts/AgBugsprayer.h @@ -5,6 +5,6 @@ class AgBugsprayer : public CppScripts::Script { public: void OnRebuildComplete(Entity* self, Entity* target) override; - void OnTimerDone(Entity* self, std::string timerName) override; + void OnTimerDone(Entity* self, std::string timerName) override; }; diff --git a/dScripts/AgBusDoor.cpp b/dScripts/AgBusDoor.cpp index 4453fcad..4910d0c5 100644 --- a/dScripts/AgBusDoor.cpp +++ b/dScripts/AgBusDoor.cpp @@ -23,14 +23,12 @@ void AgBusDoor::OnProximityUpdate(Entity* self, Entity* entering, std::string na m_Counter = 0; m_OuterCounter = 0; - for (const auto& pair : proximityMonitorComponent->GetProximityObjects("busDoor")) - { + for (const auto& pair : proximityMonitorComponent->GetProximityObjects("busDoor")) { auto* entity = EntityManager::Instance()->GetEntity(pair.first); if (entity != nullptr && entity->IsPlayer()) m_Counter++; } - for (const auto& pair : proximityMonitorComponent->GetProximityObjects("busDoorOuter")) - { + for (const auto& pair : proximityMonitorComponent->GetProximityObjects("busDoorOuter")) { auto* entity = EntityManager::Instance()->GetEntity(pair.first); if (entity != nullptr && entity->IsPlayer()) m_OuterCounter++; } @@ -40,8 +38,7 @@ void AgBusDoor::OnProximityUpdate(Entity* self, Entity* entering, std::string na if (m_Counter > 0) { MoveDoor(self, true); } - } - else if (status == "LEAVE") { + } else if (status == "LEAVE") { // move down when no players are inside either radii if (m_Counter <= 0) { MoveDoor(self, false); @@ -52,13 +49,12 @@ void AgBusDoor::OnProximityUpdate(Entity* self, Entity* entering, std::string na void AgBusDoor::MoveDoor(Entity* self, bool bOpen) { if (bOpen) { GameMessages::SendPlatformResync(self, UNASSIGNED_SYSTEM_ADDRESS, true, 1, 0); - } - else { + } else { GameMessages::SendPlatformResync(self, UNASSIGNED_SYSTEM_ADDRESS, true, 0, 1); self->AddTimer("dustTimer", 2.0f); } - //This is currently commented out because it might be the reason that people's audio is cutting out. + //This is currently commented out because it might be the reason that people's audio is cutting out. GameMessages::SendPlayNDAudioEmitter(self, UNASSIGNED_SYSTEM_ADDRESS, "{9a24f1fa-3177-4745-a2df-fbd996d6e1e3}"); } @@ -66,4 +62,4 @@ void AgBusDoor::OnTimerDone(Entity* self, std::string timerName) { if (timerName == "dustTimer") { GameMessages::SendPlayFXEffect(self->GetObjectID(), 642, u"create", "busDust", LWOOBJID_EMPTY, 1.0f, 1.0f, true); } -} \ No newline at end of file +} diff --git a/dScripts/AgCagedBricksServer.cpp b/dScripts/AgCagedBricksServer.cpp index ec9f5306..6d1360de 100644 --- a/dScripts/AgCagedBricksServer.cpp +++ b/dScripts/AgCagedBricksServer.cpp @@ -20,9 +20,8 @@ void AgCagedBricksServer::OnUse(Entity* self, Entity* user) { //Remove the maelstrom cube: auto inv = static_cast(user->GetComponent(COMPONENT_TYPE_INVENTORY)); - - if (inv) - { + + if (inv) { inv->RemoveItem(14553, 1); } } diff --git a/dScripts/AgCagedBricksServer.h b/dScripts/AgCagedBricksServer.h index 4ec128ac..27ce9e70 100644 --- a/dScripts/AgCagedBricksServer.h +++ b/dScripts/AgCagedBricksServer.h @@ -3,4 +3,4 @@ class AgCagedBricksServer : public CppScripts::Script { void OnUse(Entity* self, Entity* user); -}; \ No newline at end of file +}; diff --git a/dScripts/AgDarkSpiderling.cpp b/dScripts/AgDarkSpiderling.cpp index 55ef62ec..5dbd350a 100644 --- a/dScripts/AgDarkSpiderling.cpp +++ b/dScripts/AgDarkSpiderling.cpp @@ -1,9 +1,9 @@ #include "AgDarkSpiderling.h" #include "BaseCombatAIComponent.h" -void AgDarkSpiderling::OnStartup(Entity *self) { - auto* combatAI = self->GetComponent(); - if (combatAI != nullptr) { - combatAI->SetStunImmune(true); - } +void AgDarkSpiderling::OnStartup(Entity* self) { + auto* combatAI = self->GetComponent(); + if (combatAI != nullptr) { + combatAI->SetStunImmune(true); + } } diff --git a/dScripts/AgDarkSpiderling.h b/dScripts/AgDarkSpiderling.h index fe680f9c..8797812c 100644 --- a/dScripts/AgDarkSpiderling.h +++ b/dScripts/AgDarkSpiderling.h @@ -2,5 +2,5 @@ #include "CppScripts.h" class AgDarkSpiderling : public CppScripts::Script { - void OnStartup(Entity *self) override; + void OnStartup(Entity* self) override; }; diff --git a/dScripts/AgFans.cpp b/dScripts/AgFans.cpp index dbc09547..27d3b940 100644 --- a/dScripts/AgFans.cpp +++ b/dScripts/AgFans.cpp @@ -29,7 +29,7 @@ void AgFans::ToggleFX(Entity* self, bool hit) { if (renderComponent == nullptr) { return; } - + if (fanVolumes.size() == 0 || !self->GetVar(u"alive")) return; if (self->GetVar(u"on")) { @@ -37,7 +37,7 @@ void AgFans::ToggleFX(Entity* self, bool hit) { renderComponent->StopEffect("fanOn"); self->SetVar(u"on", false); - + for (Entity* volume : fanVolumes) { PhantomPhysicsComponent* volumePhys = static_cast(volume->GetComponent(COMPONENT_TYPE_PHANTOM_PHYSICS)); if (!volumePhys) continue; @@ -48,8 +48,7 @@ void AgFans::ToggleFX(Entity* self, bool hit) { GameMessages::SendPlayAnimation(fxObj, u"trigger"); } } - } - else if (!self->GetVar(u"on") && self->GetVar(u"alive")) { + } else if (!self->GetVar(u"on") && self->GetVar(u"alive")) { GameMessages::SendPlayAnimation(self, u"fan-on"); renderComponent->PlayEffect(495, u"fanOn", "fanOn"); @@ -68,8 +67,8 @@ void AgFans::ToggleFX(Entity* self, bool hit) { } } -void AgFans::OnFireEventServerSide(Entity *self, Entity *sender, std::string args, int32_t param1, int32_t param2, - int32_t param3) { +void AgFans::OnFireEventServerSide(Entity* self, Entity* sender, std::string args, int32_t param1, int32_t param2, + int32_t param3) { if (args.length() == 0 || !self->GetVar(u"alive")) return; if ((args == "turnOn" && self->GetVar(u"on")) || (args == "turnOff" && !self->GetVar(u"on"))) return; @@ -81,4 +80,4 @@ void AgFans::OnDie(Entity* self, Entity* killer) { ToggleFX(self, true); } self->SetVar(u"alive", false); -} \ No newline at end of file +} diff --git a/dScripts/AgFans.h b/dScripts/AgFans.h index 800267af..01f919d1 100644 --- a/dScripts/AgFans.h +++ b/dScripts/AgFans.h @@ -7,8 +7,8 @@ public: void OnStartup(Entity* self) override; void OnDie(Entity* self, Entity* killer) override; void OnFireEventServerSide( - Entity *self, - Entity *sender, + Entity* self, + Entity* sender, std::string args, int32_t param1, int32_t param2, diff --git a/dScripts/AgImagSmashable.h b/dScripts/AgImagSmashable.h index fd047c34..1cea25b9 100644 --- a/dScripts/AgImagSmashable.h +++ b/dScripts/AgImagSmashable.h @@ -6,4 +6,4 @@ public: void OnDie(Entity* self, Entity* killer); private: void CrateAnimal(Entity* self); -}; \ No newline at end of file +}; diff --git a/dScripts/AgJetEffectServer.cpp b/dScripts/AgJetEffectServer.cpp index 7336c8b8..748b947b 100644 --- a/dScripts/AgJetEffectServer.cpp +++ b/dScripts/AgJetEffectServer.cpp @@ -3,10 +3,8 @@ #include "EntityManager.h" #include "SkillComponent.h" -void AgJetEffectServer::OnUse(Entity* self, Entity* user) -{ - if (inUse) - { +void AgJetEffectServer::OnUse(Entity* self, Entity* user) { + if (inUse) { return; } @@ -24,8 +22,7 @@ void AgJetEffectServer::OnUse(Entity* self, Entity* user) auto entities = EntityManager::Instance()->GetEntitiesInGroup("Jet_FX"); - if (entities.empty()) - { + if (entities.empty()) { return; } @@ -37,12 +34,10 @@ void AgJetEffectServer::OnUse(Entity* self, Entity* user) self->AddTimer("CineDone", 9); } -void AgJetEffectServer::OnRebuildComplete(Entity* self, Entity* target) -{ +void AgJetEffectServer::OnRebuildComplete(Entity* self, Entity* target) { auto entities = EntityManager::Instance()->GetEntitiesInGroup("Jet_FX"); - if (entities.empty()) - { + if (entities.empty()) { return; } @@ -50,8 +45,7 @@ void AgJetEffectServer::OnRebuildComplete(Entity* self, Entity* target) auto groups = self->GetGroups(); - if (groups.empty()) - { + if (groups.empty()) { return; } @@ -63,34 +57,28 @@ void AgJetEffectServer::OnRebuildComplete(Entity* self, Entity* target) self->AddTimer("PlayEffect", 2.5f); - if (group == "Base_Radar") - { + if (group == "Base_Radar") { self->AddTimer("CineDone", 5); } } -void AgJetEffectServer::OnTimerDone(Entity* self, std::string timerName) -{ - if (timerName == "radarDish") - { +void AgJetEffectServer::OnTimerDone(Entity* self, std::string timerName) { + if (timerName == "radarDish") { GameMessages::SendStopFXEffect(self, true, "radarDish"); return; } - if (timerName == "PlayEffect") - { + if (timerName == "PlayEffect") { auto entities = EntityManager::Instance()->GetEntitiesInGroup("mortarMain"); - if (entities.empty()) - { + if (entities.empty()) { return; } const auto size = entities.size(); - if (size == 0) - { + if (size == 0) { return; } @@ -103,8 +91,7 @@ void AgJetEffectServer::OnTimerDone(Entity* self, std::string timerName) mortar->SetOwnerOverride(builder); SkillComponent* skillComponent; - if (!mortar->TryGetComponent(COMPONENT_TYPE_SKILL, skillComponent)) - { + if (!mortar->TryGetComponent(COMPONENT_TYPE_SKILL, skillComponent)) { return; } @@ -113,8 +100,7 @@ void AgJetEffectServer::OnTimerDone(Entity* self, std::string timerName) return; } - if (timerName == "CineDone") - { + if (timerName == "CineDone") { GameMessages::SendNotifyClientObject( self->GetObjectID(), u"toggleInUse", diff --git a/dScripts/AgLaserSensorServer.cpp b/dScripts/AgLaserSensorServer.cpp index 342cc7e1..9efae1ca 100644 --- a/dScripts/AgLaserSensorServer.cpp +++ b/dScripts/AgLaserSensorServer.cpp @@ -13,7 +13,7 @@ void AgLaserSensorServer::OnStartup(Entity* self) { physComp->SetEffectType(2); // repulse (prolly should make definitions of these are in Entity.cpp) physComp->SetDirectionalMultiplier(static_cast(m_RepelForce)); physComp->SetDirection(NiPoint3::UNIT_Y); - + m_Skill = self->GetComponent(); } @@ -36,16 +36,13 @@ void AgLaserSensorServer::OnCollisionPhantom(Entity* self, Entity* target) { if (obj == 76690936093053 && Vector3::DistanceSquared(source, NiPoint3(149.007f, 417.083f, 218.346f)) <= 1.0f) { laser = script; break; - } - else if (obj == 75866302318824 && Vector3::DistanceSquared(source, NiPoint3(48.6403f, 403.803f, 196.711f)) <= 1.0f) { + } else if (obj == 75866302318824 && Vector3::DistanceSquared(source, NiPoint3(48.6403f, 403.803f, 196.711f)) <= 1.0f) { laser = script; break; - } - else if (obj == 75866302318822 && Vector3::DistanceSquared(source, NiPoint3(19.2155f, 420.083f, 249.226f)) <= 1.0f) { + } else if (obj == 75866302318822 && Vector3::DistanceSquared(source, NiPoint3(19.2155f, 420.083f, 249.226f)) <= 1.0f) { laser = script; break; - } - else if (obj == 75866302318823 && Vector3::DistanceSquared(source, NiPoint3(-6.61596f, 404.633f, 274.323f)) <= 1.0f) { + } else if (obj == 75866302318823 && Vector3::DistanceSquared(source, NiPoint3(-6.61596f, 404.633f, 274.323f)) <= 1.0f) { laser = script; break; } diff --git a/dScripts/AgMonumentBirds.cpp b/dScripts/AgMonumentBirds.cpp index 5870cfff..ad3417a4 100644 --- a/dScripts/AgMonumentBirds.cpp +++ b/dScripts/AgMonumentBirds.cpp @@ -28,6 +28,6 @@ void AgMonumentBirds::OnTimerDone(Entity* self, std::string timerName) { auto* player = EntityManager::Instance()->GetEntity(self->GetVar(u"PlayerID")); if (player == nullptr) return; - + self->ScheduleKillAfterUpdate(player); } diff --git a/dScripts/AgMonumentLaserServer.cpp b/dScripts/AgMonumentLaserServer.cpp index 646ca998..6efda89e 100644 --- a/dScripts/AgMonumentLaserServer.cpp +++ b/dScripts/AgMonumentLaserServer.cpp @@ -3,7 +3,7 @@ void AgMonumentLaserServer::OnStartup(Entity* self) { /* self->SetProximityRadius(m_Radius, "MonumentLaser"); - + std::cout << "Monument Laser " << self->GetObjectID() << " is at " << self->GetPosition().GetX() << ","<< self->GetPosition().GetY() << "," << self->GetPosition().GetZ() << std::endl; */ diff --git a/dScripts/AgMonumentRaceCancel.cpp b/dScripts/AgMonumentRaceCancel.cpp index 205aee57..2e744434 100644 --- a/dScripts/AgMonumentRaceCancel.cpp +++ b/dScripts/AgMonumentRaceCancel.cpp @@ -1,9 +1,9 @@ #include "AgMonumentRaceCancel.h" #include "EntityManager.h" -void AgMonumentRaceCancel::OnCollisionPhantom(Entity *self, Entity *target) { - auto managers = EntityManager::Instance()->GetEntitiesInGroup("race_manager"); - if (!managers.empty()) { - managers[0]->OnFireEventServerSide(target, "course_cancel"); - } +void AgMonumentRaceCancel::OnCollisionPhantom(Entity* self, Entity* target) { + auto managers = EntityManager::Instance()->GetEntitiesInGroup("race_manager"); + if (!managers.empty()) { + managers[0]->OnFireEventServerSide(target, "course_cancel"); + } } diff --git a/dScripts/AgMonumentRaceCancel.h b/dScripts/AgMonumentRaceCancel.h index fd324d25..8ddbc5b1 100644 --- a/dScripts/AgMonumentRaceCancel.h +++ b/dScripts/AgMonumentRaceCancel.h @@ -2,5 +2,5 @@ #include "CppScripts.h" class AgMonumentRaceCancel : public CppScripts::Script { - void OnCollisionPhantom(Entity *self, Entity *target) override; + void OnCollisionPhantom(Entity* self, Entity* target) override; }; diff --git a/dScripts/AgMonumentRaceGoal.cpp b/dScripts/AgMonumentRaceGoal.cpp index 13122695..78bbaee5 100644 --- a/dScripts/AgMonumentRaceGoal.cpp +++ b/dScripts/AgMonumentRaceGoal.cpp @@ -2,17 +2,14 @@ #include "EntityManager.h" -void AgMonumentRaceGoal::OnStartup(Entity* self) -{ - self->SetProximityRadius(15, "RaceGoal"); +void AgMonumentRaceGoal::OnStartup(Entity* self) { + self->SetProximityRadius(15, "RaceGoal"); } -void AgMonumentRaceGoal::OnProximityUpdate(Entity* self, Entity* entering, std::string name, std::string status) -{ - if (name == "RaceGoal" && entering->IsPlayer() && status == "ENTER") - { - auto* manager = EntityManager::Instance()->GetEntitiesInGroup("race_manager")[0]; +void AgMonumentRaceGoal::OnProximityUpdate(Entity* self, Entity* entering, std::string name, std::string status) { + if (name == "RaceGoal" && entering->IsPlayer() && status == "ENTER") { + auto* manager = EntityManager::Instance()->GetEntitiesInGroup("race_manager")[0]; - manager->OnFireEventServerSide(entering, "course_finish"); - } + manager->OnFireEventServerSide(entering, "course_finish"); + } } diff --git a/dScripts/AgPicnicBlanket.cpp b/dScripts/AgPicnicBlanket.cpp index 3d13cb40..30fb2950 100644 --- a/dScripts/AgPicnicBlanket.cpp +++ b/dScripts/AgPicnicBlanket.cpp @@ -1,16 +1,16 @@ #include "AgPicnicBlanket.h" #include "GameMessages.h" -void AgPicnicBlanket::OnUse(Entity *self, Entity *user) { - GameMessages::SendTerminateInteraction(user->GetObjectID(), FROM_INTERACTION, self->GetObjectID()); - if (self->GetVar(u"active")) - return; - self->SetVar(u"active", true); +void AgPicnicBlanket::OnUse(Entity* self, Entity* user) { + GameMessages::SendTerminateInteraction(user->GetObjectID(), FROM_INTERACTION, self->GetObjectID()); + if (self->GetVar(u"active")) + return; + self->SetVar(u"active", true); - auto lootTable = std::unordered_map {{935, 3}}; - LootGenerator::Instance().DropLoot(user, self, lootTable, 0, 0); + auto lootTable = std::unordered_map{ {935, 3} }; + LootGenerator::Instance().DropLoot(user, self, lootTable, 0, 0); - self->AddCallbackTimer(5.0f, [self]() { - self->SetVar(u"active", false); - }); + self->AddCallbackTimer(5.0f, [self]() { + self->SetVar(u"active", false); + }); } diff --git a/dScripts/AgPicnicBlanket.h b/dScripts/AgPicnicBlanket.h index af603dd7..2a5a0d7a 100644 --- a/dScripts/AgPicnicBlanket.h +++ b/dScripts/AgPicnicBlanket.h @@ -2,5 +2,5 @@ #include "CppScripts.h" class AgPicnicBlanket : public CppScripts::Script { - void OnUse(Entity *self, Entity *user) override; + void OnUse(Entity* self, Entity* user) override; }; diff --git a/dScripts/AgPropGuard.cpp b/dScripts/AgPropGuard.cpp index b05eef4f..c8376b3e 100644 --- a/dScripts/AgPropGuard.cpp +++ b/dScripts/AgPropGuard.cpp @@ -6,43 +6,34 @@ #include "MissionComponent.h" #include "Item.h" -void AgPropGuard::OnMissionDialogueOK(Entity* self, Entity* target, int missionID, MissionState missionState) -{ - auto* character = target->GetCharacter(); - auto* missionComponent = target->GetComponent(); - auto* inventoryComponent = target->GetComponent(); +void AgPropGuard::OnMissionDialogueOK(Entity* self, Entity* target, int missionID, MissionState missionState) { + auto* character = target->GetCharacter(); + auto* missionComponent = target->GetComponent(); + auto* inventoryComponent = target->GetComponent(); - const auto state = missionComponent->GetMissionState(320); - if (missionID == 768 && missionState == MissionState::MISSION_STATE_AVAILABLE) - { - if (!character->GetPlayerFlag(71)) - { - // TODO: Cinematic "MissionCam" - } - } - else if (missionID == 768 && missionState >= MissionState::MISSION_STATE_READY_TO_COMPLETE) - { + const auto state = missionComponent->GetMissionState(320); + if (missionID == 768 && missionState == MissionState::MISSION_STATE_AVAILABLE) { + if (!character->GetPlayerFlag(71)) { + // TODO: Cinematic "MissionCam" + } + } else if (missionID == 768 && missionState >= MissionState::MISSION_STATE_READY_TO_COMPLETE) { //remove the inventory items - for (int item : gearSets) - { + for (int item : gearSets) { auto* id = inventoryComponent->FindItemByLot(item); - if (id) - { + if (id) { inventoryComponent->UnEquipItem(id); inventoryComponent->RemoveItem(id->GetLot(), id->GetCount()); } } - } - else if ( - (missionID == 320 && state == MissionState::MISSION_STATE_AVAILABLE) /*|| - (state == MissionState::MISSION_STATE_COMPLETE && missionID == 891 && missionState == MissionState::MISSION_STATE_READY_TO_COMPLETE)*/ - ) - { - //GameMessages::SendNotifyClientObject(EntityManager::Instance()->GetZoneControlEntity()->GetObjectID(), u"GuardChat", target->GetObjectID(), 0, target->GetObjectID(), "", target->GetSystemAddress()); + } else if ( + (missionID == 320 && state == MissionState::MISSION_STATE_AVAILABLE) /*|| + (state == MissionState::MISSION_STATE_COMPLETE && missionID == 891 && missionState == MissionState::MISSION_STATE_READY_TO_COMPLETE)*/ + ) { + //GameMessages::SendNotifyClientObject(EntityManager::Instance()->GetZoneControlEntity()->GetObjectID(), u"GuardChat", target->GetObjectID(), 0, target->GetObjectID(), "", target->GetSystemAddress()); - target->GetCharacter()->SetPlayerFlag(113, true); + target->GetCharacter()->SetPlayerFlag(113, true); - EntityManager::Instance()->GetZoneControlEntity()->AddTimer("GuardFlyAway", 1.0f); - } + EntityManager::Instance()->GetZoneControlEntity()->AddTimer("GuardFlyAway", 1.0f); + } } diff --git a/dScripts/AgPropguards.cpp b/dScripts/AgPropguards.cpp index 4170defe..674c4bdd 100644 --- a/dScripts/AgPropguards.cpp +++ b/dScripts/AgPropguards.cpp @@ -4,53 +4,53 @@ #include "EntityManager.h" #include "dZoneManager.h" -void AgPropguards::OnMissionDialogueOK(Entity *self, Entity *target, int missionID, MissionState missionState) { - auto* character = target->GetCharacter(); - if (character == nullptr) - return; +void AgPropguards::OnMissionDialogueOK(Entity* self, Entity* target, int missionID, MissionState missionState) { + auto* character = target->GetCharacter(); + if (character == nullptr) + return; - const auto flag = GetFlagForMission(missionID); - if (flag == 0) - return; + const auto flag = GetFlagForMission(missionID); + if (flag == 0) + return; - if ((missionState == MissionState::MISSION_STATE_AVAILABLE || missionState == MissionState::MISSION_STATE_ACTIVE) - && !character->GetPlayerFlag(flag)) { - // If the player just started the mission, play a cinematic highlighting the target - GameMessages::SendPlayCinematic(target->GetObjectID(), u"MissionCam", target->GetSystemAddress()); - } else if (missionState == MissionState::MISSION_STATE_COMPLETE_READY_TO_COMPLETE) { - // Makes the guard disappear once the mission has been completed - const auto zoneControlID = EntityManager::Instance()->GetZoneControlEntity()->GetObjectID(); - GameMessages::SendNotifyClientObject(zoneControlID, u"GuardChat", 0, 0, self->GetObjectID(), - "", UNASSIGNED_SYSTEM_ADDRESS); + if ((missionState == MissionState::MISSION_STATE_AVAILABLE || missionState == MissionState::MISSION_STATE_ACTIVE) + && !character->GetPlayerFlag(flag)) { + // If the player just started the mission, play a cinematic highlighting the target + GameMessages::SendPlayCinematic(target->GetObjectID(), u"MissionCam", target->GetSystemAddress()); + } else if (missionState == MissionState::MISSION_STATE_COMPLETE_READY_TO_COMPLETE) { + // Makes the guard disappear once the mission has been completed + const auto zoneControlID = EntityManager::Instance()->GetZoneControlEntity()->GetObjectID(); + GameMessages::SendNotifyClientObject(zoneControlID, u"GuardChat", 0, 0, self->GetObjectID(), + "", UNASSIGNED_SYSTEM_ADDRESS); - self->AddCallbackTimer(5.0f, [self]() { - auto spawnerName = self->GetVar(u"spawner_name"); - if (spawnerName.empty()) - spawnerName = "Guard"; + self->AddCallbackTimer(5.0f, [self]() { + auto spawnerName = self->GetVar(u"spawner_name"); + if (spawnerName.empty()) + spawnerName = "Guard"; - auto spawners = dZoneManager::Instance()->GetSpawnersByName(spawnerName); - for (auto* spawner : spawners) { - spawner->Deactivate(); - } + auto spawners = dZoneManager::Instance()->GetSpawnersByName(spawnerName); + for (auto* spawner : spawners) { + spawner->Deactivate(); + } - self->Smash(); - }); - } + self->Smash(); + }); + } } uint32_t AgPropguards::GetFlagForMission(uint32_t missionID) { - switch (missionID) { - case 872: - return 97; - case 873: - return 98; - case 874: - return 99; - case 1293: - return 118; - case 1322: - return 122; - default: - return 0; - } + switch (missionID) { + case 872: + return 97; + case 873: + return 98; + case 874: + return 99; + case 1293: + return 118; + case 1322: + return 122; + default: + return 0; + } } diff --git a/dScripts/AgPropguards.h b/dScripts/AgPropguards.h index 710096ce..511b7b6a 100644 --- a/dScripts/AgPropguards.h +++ b/dScripts/AgPropguards.h @@ -2,7 +2,7 @@ #include "CppScripts.h" class AgPropguards : public CppScripts::Script { - void OnMissionDialogueOK(Entity *self, Entity *target, int missionID, MissionState missionState) override; + void OnMissionDialogueOK(Entity* self, Entity* target, int missionID, MissionState missionState) override; private: - static uint32_t GetFlagForMission(uint32_t missionID); + static uint32_t GetFlagForMission(uint32_t missionID); }; diff --git a/dScripts/AgQbElevator.cpp b/dScripts/AgQbElevator.cpp index 3ef0cf0b..ccb4d3b1 100644 --- a/dScripts/AgQbElevator.cpp +++ b/dScripts/AgQbElevator.cpp @@ -3,7 +3,7 @@ #include "GameMessages.h" void AgQbElevator::OnStartup(Entity* self) { - + } //when the QB is finished being built by a player @@ -15,7 +15,7 @@ void AgQbElevator::OnRebuildComplete(Entity* self, Entity* target) { if (delayTime < 1) delayTime = 1; GameMessages::SendPlatformResync(self, UNASSIGNED_SYSTEM_ADDRESS, true, 0, - 0, 0, MovementPlatformState::Stationary); + 0, 0, MovementPlatformState::Stationary); //add a timer that will kill the QB if no players get on in the killTime self->AddTimer("startKillTimer", killTime); @@ -33,9 +33,8 @@ void AgQbElevator::OnProximityUpdate(Entity* self, Entity* entering, std::string self->CancelTimer("StartElevator"); GameMessages::SendPlatformResync(self, UNASSIGNED_SYSTEM_ADDRESS, true, 0, - 1, 1, MovementPlatformState::Moving); - } - else if (!self->GetBoolean(u"StartTimer")) { + 1, 1, MovementPlatformState::Moving); + } else if (!self->GetBoolean(u"StartTimer")) { self->SetBoolean(u"StartTimer", true); self->AddTimer("StartElevator", startTime); } @@ -46,9 +45,8 @@ void AgQbElevator::OnTimerDone(Entity* self, std::string timerName) { if (timerName == "StartElevator") { GameMessages::SendPlatformResync(self, UNASSIGNED_SYSTEM_ADDRESS, true, 0, - 1, 1, MovementPlatformState::Moving); - } - else if (timerName == "startKillTimer") { + 1, 1, MovementPlatformState::Moving); + } else if (timerName == "startKillTimer") { killTimerStartup(self); } else if (timerName == "KillTimer") { self->Smash(self->GetObjectID(), VIOLENT); diff --git a/dScripts/AgQbElevator.h b/dScripts/AgQbElevator.h index ab4f9a6d..4d07b8a2 100644 --- a/dScripts/AgQbElevator.h +++ b/dScripts/AgQbElevator.h @@ -16,4 +16,4 @@ private: float startTime = 8.0f; float killTime = 10.0f; float proxRadius = 5.0f; -}; \ No newline at end of file +}; diff --git a/dScripts/AgSalutingNpcs.cpp b/dScripts/AgSalutingNpcs.cpp index 618dc631..28495f58 100644 --- a/dScripts/AgSalutingNpcs.cpp +++ b/dScripts/AgSalutingNpcs.cpp @@ -2,10 +2,8 @@ #include "GameMessages.h" -void AgSalutingNpcs::OnEmoteReceived(Entity* self, const int32_t emote, Entity* target) -{ - if (emote != 356) - { +void AgSalutingNpcs::OnEmoteReceived(Entity* self, const int32_t emote, Entity* target) { + if (emote != 356) { return; } diff --git a/dScripts/AgShipPlayerDeathTrigger.cpp b/dScripts/AgShipPlayerDeathTrigger.cpp index d20edee7..a580be6e 100644 --- a/dScripts/AgShipPlayerDeathTrigger.cpp +++ b/dScripts/AgShipPlayerDeathTrigger.cpp @@ -5,4 +5,4 @@ void AgShipPlayerDeathTrigger::OnCollisionPhantom(Entity* self, Entity* target) if (target->GetLOT() == 1 && !target->GetIsDead()) { target->Smash(self->GetObjectID(), eKillType::VIOLENT, u"electro-shock-death"); } -} \ No newline at end of file +} diff --git a/dScripts/AgShipPlayerShockServer.cpp b/dScripts/AgShipPlayerShockServer.cpp index 628f0bb4..2bed8152 100644 --- a/dScripts/AgShipPlayerShockServer.cpp +++ b/dScripts/AgShipPlayerShockServer.cpp @@ -1,8 +1,7 @@ #include "AgShipPlayerShockServer.h" #include "GameMessages.h" -void AgShipPlayerShockServer::OnUse(Entity* self, Entity* user) -{ +void AgShipPlayerShockServer::OnUse(Entity* self, Entity* user) { GameMessages::SendTerminateInteraction(user->GetObjectID(), eTerminateType::FROM_INTERACTION, self->GetObjectID()); if (active) { return; @@ -15,8 +14,7 @@ void AgShipPlayerShockServer::OnUse(Entity* self, Entity* user) self->AddTimer("FXTime", fxTime); } -void AgShipPlayerShockServer::OnTimerDone(Entity* self, std::string timerName) -{ +void AgShipPlayerShockServer::OnTimerDone(Entity* self, std::string timerName) { GameMessages::SendStopFXEffect(self, true, "console_sparks"); active = false; } diff --git a/dScripts/AgSpaceStuff.cpp b/dScripts/AgSpaceStuff.cpp index 18e4eb47..80a87e70 100644 --- a/dScripts/AgSpaceStuff.cpp +++ b/dScripts/AgSpaceStuff.cpp @@ -28,18 +28,15 @@ void AgSpaceStuff::OnTimerDone(Entity* self, std::string timerName) { GameMessages::SendPlayAnimation(self, u"scale_0" + GeneralUtils::to_u16string(scaleType)); self->AddTimer("FloaterPath", 0.4); - } - else if (timerName == "FloaterPath") { + } else if (timerName == "FloaterPath") { int pathType = GeneralUtils::GenerateRandomNumber(1, 4); int randTime = GeneralUtils::GenerateRandomNumber(20, 25); GameMessages::SendPlayAnimation(self, u"path_0" + (GeneralUtils::to_u16string(pathType))); self->AddTimer("FloaterScale", randTime); - } - else if (timerName == "ShipShakeExplode") { + } else if (timerName == "ShipShakeExplode") { DoShake(self, true); - } - else if (timerName == "ShipShakeIdle") { + } else if (timerName == "ShipShakeIdle") { DoShake(self, false); } } @@ -79,8 +76,7 @@ void AgSpaceStuff::DoShake(Entity* self, bool explodeIdle) { auto* shipFxObject2 = GetEntityInGroup(ShipFX2); if (shipFxObject2) GameMessages::SendPlayAnimation(shipFxObject2, u"explosion"); - } - else { + } else { auto* shipFxObject = GetEntityInGroup(ShipFX); auto* shipFxObject2 = GetEntityInGroup(ShipFX2); diff --git a/dScripts/AgStagePlatforms.cpp b/dScripts/AgStagePlatforms.cpp index cb401647..9ba4c4b7 100644 --- a/dScripts/AgStagePlatforms.cpp +++ b/dScripts/AgStagePlatforms.cpp @@ -1,16 +1,16 @@ #include "AgStagePlatforms.h" #include "MovingPlatformComponent.h" -void AgStagePlatforms::OnStartup(Entity *self) { - auto* component = self->GetComponent(); - if (component) { - component->SetNoAutoStart(true); - component->StopPathing(); - } +void AgStagePlatforms::OnStartup(Entity* self) { + auto* component = self->GetComponent(); + if (component) { + component->SetNoAutoStart(true); + component->StopPathing(); + } } void AgStagePlatforms::OnWaypointReached(Entity* self, uint32_t waypointIndex) { - auto* component = self->GetComponent(); - if (waypointIndex == 0 && component) - component->StopPathing(); + auto* component = self->GetComponent(); + if (waypointIndex == 0 && component) + component->StopPathing(); } diff --git a/dScripts/AgStagePlatforms.h b/dScripts/AgStagePlatforms.h index e315664a..62c6bc91 100644 --- a/dScripts/AgStagePlatforms.h +++ b/dScripts/AgStagePlatforms.h @@ -3,6 +3,6 @@ class AgStagePlatforms : public CppScripts::Script { public: - void OnStartup(Entity* self) override; - void OnWaypointReached(Entity* self, uint32_t waypointIndex) override; + void OnStartup(Entity* self) override; + void OnWaypointReached(Entity* self, uint32_t waypointIndex) override; }; diff --git a/dScripts/AgStromlingProperty.cpp b/dScripts/AgStromlingProperty.cpp index b1b8d45f..36d8d378 100644 --- a/dScripts/AgStromlingProperty.cpp +++ b/dScripts/AgStromlingProperty.cpp @@ -1,16 +1,16 @@ #include "AgStromlingProperty.h" #include "MovementAIComponent.h" -void AgStromlingProperty::OnStartup(Entity *self) { - auto movementInfo = MovementAIInfo { - "Wander", - 71, - 3, - 100, - 1, - 4 - }; +void AgStromlingProperty::OnStartup(Entity* self) { + auto movementInfo = MovementAIInfo{ + "Wander", + 71, + 3, + 100, + 1, + 4 + }; - auto* movementAIComponent = new MovementAIComponent(self, movementInfo); - self->AddComponent(COMPONENT_TYPE_MOVEMENT_AI, movementAIComponent); + auto* movementAIComponent = new MovementAIComponent(self, movementInfo); + self->AddComponent(COMPONENT_TYPE_MOVEMENT_AI, movementAIComponent); } diff --git a/dScripts/AgStromlingProperty.h b/dScripts/AgStromlingProperty.h index 92a179f5..12128b03 100644 --- a/dScripts/AgStromlingProperty.h +++ b/dScripts/AgStromlingProperty.h @@ -2,5 +2,5 @@ #include "CppScripts.h" class AgStromlingProperty : public CppScripts::Script { - void OnStartup(Entity *self) override; + void OnStartup(Entity* self) override; }; diff --git a/dScripts/AgSurvivalBuffStation.cpp b/dScripts/AgSurvivalBuffStation.cpp index 8a6cfb05..4d3482c4 100644 --- a/dScripts/AgSurvivalBuffStation.cpp +++ b/dScripts/AgSurvivalBuffStation.cpp @@ -6,60 +6,60 @@ #include "TeamManager.h" void AgSurvivalBuffStation::OnRebuildComplete(Entity* self, Entity* target) { - auto destroyableComponent = self->GetComponent(); - // We set the faction to 1 so that the buff station sees players as friendly targets to buff - if (destroyableComponent != nullptr) destroyableComponent->SetFaction(1); + auto destroyableComponent = self->GetComponent(); + // We set the faction to 1 so that the buff station sees players as friendly targets to buff + if (destroyableComponent != nullptr) destroyableComponent->SetFaction(1); - auto skillComponent = self->GetComponent(); + auto skillComponent = self->GetComponent(); - if (skillComponent != nullptr) skillComponent->CalculateBehavior(skillIdForBuffStation, behaviorIdForBuffStation, self->GetObjectID()); + if (skillComponent != nullptr) skillComponent->CalculateBehavior(skillIdForBuffStation, behaviorIdForBuffStation, self->GetObjectID()); - self->AddCallbackTimer(smashTimer, [self]() { - self->Smash(); - }); - self->AddTimer("DropArmor", dropArmorTimer); - self->AddTimer("DropLife", dropLifeTimer); - self->AddTimer("Dropimagination", dropImaginationTimer); - // Since all survival players should be on the same team, we get the team. - auto team = TeamManager::Instance()->GetTeam(target->GetObjectID()); + self->AddCallbackTimer(smashTimer, [self]() { + self->Smash(); + }); + self->AddTimer("DropArmor", dropArmorTimer); + self->AddTimer("DropLife", dropLifeTimer); + self->AddTimer("Dropimagination", dropImaginationTimer); + // Since all survival players should be on the same team, we get the team. + auto team = TeamManager::Instance()->GetTeam(target->GetObjectID()); - std::vector builderTeam; - // Not on a team - if (team == nullptr) { - builderTeam.push_back(target->GetObjectID()); - self->SetVar>(u"BuilderTeam", builderTeam); - return; - } + std::vector builderTeam; + // Not on a team + if (team == nullptr) { + builderTeam.push_back(target->GetObjectID()); + self->SetVar>(u"BuilderTeam", builderTeam); + return; + } - for (auto memberID : team->members) { - builderTeam.push_back(memberID); - } - self->SetVar>(u"BuilderTeam", builderTeam); + for (auto memberID : team->members) { + builderTeam.push_back(memberID); + } + self->SetVar>(u"BuilderTeam", builderTeam); } void AgSurvivalBuffStation::OnTimerDone(Entity* self, std::string timerName) { - uint32_t powerupToDrop = lifePowerup; - if (timerName == "DropArmor") { - powerupToDrop = armorPowerup; - self->AddTimer("DropArmor", dropArmorTimer); - } - if (timerName == "DropLife") { - powerupToDrop = lifePowerup; - self->AddTimer("DropLife", dropLifeTimer); - } - if (timerName == "Dropimagination") { - powerupToDrop = imaginationPowerup; - self->AddTimer("Dropimagination", dropImaginationTimer); - } - auto team = self->GetVar>(u"BuilderTeam"); - for (auto memberID : team) { - auto member = EntityManager::Instance()->GetEntity(memberID); - if (member != nullptr && !member->GetIsDead()) { - GameMessages::SendDropClientLoot(member, self->GetObjectID(), powerupToDrop, 0, self->GetPosition()); - } else { - // If player left the team or left early erase them from the team variable. - team.erase(std::find(team.begin(), team.end(), memberID)); - self->SetVar>(u"BuilderTeam", team); - } - } + uint32_t powerupToDrop = lifePowerup; + if (timerName == "DropArmor") { + powerupToDrop = armorPowerup; + self->AddTimer("DropArmor", dropArmorTimer); + } + if (timerName == "DropLife") { + powerupToDrop = lifePowerup; + self->AddTimer("DropLife", dropLifeTimer); + } + if (timerName == "Dropimagination") { + powerupToDrop = imaginationPowerup; + self->AddTimer("Dropimagination", dropImaginationTimer); + } + auto team = self->GetVar>(u"BuilderTeam"); + for (auto memberID : team) { + auto member = EntityManager::Instance()->GetEntity(memberID); + if (member != nullptr && !member->GetIsDead()) { + GameMessages::SendDropClientLoot(member, self->GetObjectID(), powerupToDrop, 0, self->GetPosition()); + } else { + // If player left the team or left early erase them from the team variable. + team.erase(std::find(team.begin(), team.end(), memberID)); + self->SetVar>(u"BuilderTeam", team); + } + } } diff --git a/dScripts/AgSurvivalBuffStation.h b/dScripts/AgSurvivalBuffStation.h index b2beaba6..5434b0cd 100644 --- a/dScripts/AgSurvivalBuffStation.h +++ b/dScripts/AgSurvivalBuffStation.h @@ -4,49 +4,49 @@ class AgSurvivalBuffStation : public CppScripts::Script { public: - /** - * @brief When the rebuild of self is complete, we calculate the behavior that is assigned to self in the database. - * - * @param self The Entity that called this script. - * @param target The target of the self that called this script. - */ - void OnRebuildComplete(Entity* self, Entity* target) override; - void OnTimerDone(Entity* self, std::string timerName) override; + /** + * @brief When the rebuild of self is complete, we calculate the behavior that is assigned to self in the database. + * + * @param self The Entity that called this script. + * @param target The target of the self that called this script. + */ + void OnRebuildComplete(Entity* self, Entity* target) override; + void OnTimerDone(Entity* self, std::string timerName) override; private: - /** - * Skill ID for the buff station. - */ - uint32_t skillIdForBuffStation = 201; - /** - * Behavior ID for the buff station. - */ - uint32_t behaviorIdForBuffStation = 1784; - /** - * Timer for dropping armor. - */ - float dropArmorTimer = 6.0f; - /** - * Timer for dropping life. - */ - float dropLifeTimer = 3.0f; - /** - * Timer for dropping imagination. - */ - float dropImaginationTimer = 4.0f; - /** - * Timer for smashing. - */ - float smashTimer = 25.0f; - /** - * LOT for armor powerup. - */ - LOT armorPowerup = 6431; - /** - * LOT for life powerup. - */ - LOT lifePowerup = 177; - /** - * LOT for imagination powerup. - */ - LOT imaginationPowerup = 935; -}; \ No newline at end of file + /** + * Skill ID for the buff station. + */ + uint32_t skillIdForBuffStation = 201; + /** + * Behavior ID for the buff station. + */ + uint32_t behaviorIdForBuffStation = 1784; + /** + * Timer for dropping armor. + */ + float dropArmorTimer = 6.0f; + /** + * Timer for dropping life. + */ + float dropLifeTimer = 3.0f; + /** + * Timer for dropping imagination. + */ + float dropImaginationTimer = 4.0f; + /** + * Timer for smashing. + */ + float smashTimer = 25.0f; + /** + * LOT for armor powerup. + */ + LOT armorPowerup = 6431; + /** + * LOT for life powerup. + */ + LOT lifePowerup = 177; + /** + * LOT for imagination powerup. + */ + LOT imaginationPowerup = 935; +}; diff --git a/dScripts/AgSurvivalMech.cpp b/dScripts/AgSurvivalMech.cpp index e31c8aba..99f40b8b 100644 --- a/dScripts/AgSurvivalMech.cpp +++ b/dScripts/AgSurvivalMech.cpp @@ -1,15 +1,15 @@ #include "AgSurvivalMech.h" #include "DestroyableComponent.h" -void AgSurvivalMech::OnStartup(Entity *self) { - BaseWavesGenericEnemy::OnStartup(self); +void AgSurvivalMech::OnStartup(Entity* self) { + BaseWavesGenericEnemy::OnStartup(self); - auto* destroyable = self->GetComponent(); - if (destroyable != nullptr) { - destroyable->SetFaction(4); - } + auto* destroyable = self->GetComponent(); + if (destroyable != nullptr) { + destroyable->SetFaction(4); + } } uint32_t AgSurvivalMech::GetPoints() { - return 200; + return 200; } diff --git a/dScripts/AgSurvivalMech.h b/dScripts/AgSurvivalMech.h index 8d6ba270..cc972b67 100644 --- a/dScripts/AgSurvivalMech.h +++ b/dScripts/AgSurvivalMech.h @@ -2,6 +2,6 @@ #include "BaseWavesGenericEnemy.h" class AgSurvivalMech : public BaseWavesGenericEnemy { - void OnStartup(Entity *self) override; - uint32_t GetPoints() override; + void OnStartup(Entity* self) override; + uint32_t GetPoints() override; }; diff --git a/dScripts/AgSurvivalSpiderling.cpp b/dScripts/AgSurvivalSpiderling.cpp index d44455d8..8e2c173c 100644 --- a/dScripts/AgSurvivalSpiderling.cpp +++ b/dScripts/AgSurvivalSpiderling.cpp @@ -1,15 +1,15 @@ #include "AgSurvivalSpiderling.h" #include "BaseCombatAIComponent.h" -void AgSurvivalSpiderling::OnStartup(Entity *self) { - BaseWavesGenericEnemy::OnStartup(self); +void AgSurvivalSpiderling::OnStartup(Entity* self) { + BaseWavesGenericEnemy::OnStartup(self); - auto* combatAI = self->GetComponent(); - if (combatAI != nullptr) { - combatAI->SetStunImmune(true); - } + auto* combatAI = self->GetComponent(); + if (combatAI != nullptr) { + combatAI->SetStunImmune(true); + } } uint32_t AgSurvivalSpiderling::GetPoints() { - return 300; + return 300; } diff --git a/dScripts/AgSurvivalSpiderling.h b/dScripts/AgSurvivalSpiderling.h index 2f374563..4aa51024 100644 --- a/dScripts/AgSurvivalSpiderling.h +++ b/dScripts/AgSurvivalSpiderling.h @@ -2,6 +2,6 @@ #include "BaseWavesGenericEnemy.h" class AgSurvivalSpiderling : public BaseWavesGenericEnemy { - void OnStartup(Entity *self) override; - uint32_t GetPoints() override; + void OnStartup(Entity* self) override; + uint32_t GetPoints() override; }; diff --git a/dScripts/AgSurvivalStromling.cpp b/dScripts/AgSurvivalStromling.cpp index bc6a6c74..2f4c6623 100644 --- a/dScripts/AgSurvivalStromling.cpp +++ b/dScripts/AgSurvivalStromling.cpp @@ -1,5 +1,5 @@ #include "AgSurvivalStromling.h" uint32_t AgSurvivalStromling::GetPoints() { - return 100; + return 100; } diff --git a/dScripts/AgSurvivalStromling.h b/dScripts/AgSurvivalStromling.h index cfd46a63..e43a603d 100644 --- a/dScripts/AgSurvivalStromling.h +++ b/dScripts/AgSurvivalStromling.h @@ -2,5 +2,5 @@ #include "BaseWavesGenericEnemy.h" class AgSurvivalStromling : public BaseWavesGenericEnemy { - uint32_t GetPoints() override; + uint32_t GetPoints() override; }; diff --git a/dScripts/AgTurret.h b/dScripts/AgTurret.h index 2aa12432..1cbba31a 100644 --- a/dScripts/AgTurret.h +++ b/dScripts/AgTurret.h @@ -5,4 +5,4 @@ class AgTurret : public CppScripts::Script { void OnStartup(Entity* self); void OnTimerDone(Entity* self, std::string timerName); void OnRebuildStart(Entity* self, Entity* user); -}; \ No newline at end of file +}; diff --git a/dScripts/AmBlueX.cpp b/dScripts/AmBlueX.cpp index db464186..97f80e77 100644 --- a/dScripts/AmBlueX.cpp +++ b/dScripts/AmBlueX.cpp @@ -3,53 +3,53 @@ #include "EntityManager.h" #include "Character.h" -void AmBlueX::OnUse(Entity *self, Entity *user) { - auto* skillComponent = user->GetComponent(); - if (skillComponent != nullptr) { - skillComponent->CalculateBehavior(m_SwordSkill, m_SwordBehavior, self->GetObjectID()); - } +void AmBlueX::OnUse(Entity* self, Entity* user) { + auto* skillComponent = user->GetComponent(); + if (skillComponent != nullptr) { + skillComponent->CalculateBehavior(m_SwordSkill, m_SwordBehavior, self->GetObjectID()); + } } -void AmBlueX::OnSkillEventFired(Entity *self, Entity *caster, const std::string &message) { - if (message == "FireDukesStrike") { - self->SetNetworkVar(m_XUsedVariable, true); - self->SetNetworkVar(m_StartEffectVariable, true); +void AmBlueX::OnSkillEventFired(Entity* self, Entity* caster, const std::string& message) { + if (message == "FireDukesStrike") { + self->SetNetworkVar(m_XUsedVariable, true); + self->SetNetworkVar(m_StartEffectVariable, true); - auto* character = caster->GetCharacter(); - if (character != nullptr) { - character->SetPlayerFlag(self->GetVar(m_FlagVariable), true); - } + auto* character = caster->GetCharacter(); + if (character != nullptr) { + character->SetPlayerFlag(self->GetVar(m_FlagVariable), true); + } - EntityInfo info {}; - info.lot = m_FXObject; - info.pos = self->GetPosition(); - info.rot = self->GetRotation(); - info.spawnerID = self->GetObjectID(); + EntityInfo info{}; + info.lot = m_FXObject; + info.pos = self->GetPosition(); + info.rot = self->GetRotation(); + info.spawnerID = self->GetObjectID(); - auto* fxObject = EntityManager::Instance()->CreateEntity(info, nullptr, self); - EntityManager::Instance()->ConstructEntity(fxObject); + auto* fxObject = EntityManager::Instance()->CreateEntity(info, nullptr, self); + EntityManager::Instance()->ConstructEntity(fxObject); - auto fxObjectID = fxObject->GetObjectID(); - auto playerID = caster->GetObjectID(); + auto fxObjectID = fxObject->GetObjectID(); + auto playerID = caster->GetObjectID(); - // Add a callback for the bomb to explode - self->AddCallbackTimer(m_BombTime, [this, self, fxObjectID, playerID]() { - auto* fxObject = EntityManager::Instance()->GetEntity(fxObjectID); - auto* player = EntityManager::Instance()->GetEntity(playerID); - auto* skillComponent = self->GetComponent(); + // Add a callback for the bomb to explode + self->AddCallbackTimer(m_BombTime, [this, self, fxObjectID, playerID]() { + auto* fxObject = EntityManager::Instance()->GetEntity(fxObjectID); + auto* player = EntityManager::Instance()->GetEntity(playerID); + auto* skillComponent = self->GetComponent(); - if (skillComponent == nullptr) - return; + if (skillComponent == nullptr) + return; - // Cast the skill that destroys the object - if (player != nullptr) { - skillComponent->CalculateBehavior(m_AOESkill, m_AOEBehavior, LWOOBJID_EMPTY, false, false, playerID); - } else { - skillComponent->CalculateBehavior(m_AOESkill, m_AOEBehavior, LWOOBJID_EMPTY); - } + // Cast the skill that destroys the object + if (player != nullptr) { + skillComponent->CalculateBehavior(m_AOESkill, m_AOEBehavior, LWOOBJID_EMPTY, false, false, playerID); + } else { + skillComponent->CalculateBehavior(m_AOESkill, m_AOEBehavior, LWOOBJID_EMPTY); + } - fxObject->Smash(); - self->Smash(); - }); - } + fxObject->Smash(); + self->Smash(); + }); + } } diff --git a/dScripts/AmBlueX.h b/dScripts/AmBlueX.h index 99f6ede4..79428514 100644 --- a/dScripts/AmBlueX.h +++ b/dScripts/AmBlueX.h @@ -2,19 +2,19 @@ #include "CppScripts.h" class AmBlueX : public CppScripts::Script { - void OnUse(Entity *self, Entity *user) override; - void OnSkillEventFired(Entity *self, Entity *caster, const std::string &message) override; + void OnUse(Entity* self, Entity* user) override; + void OnSkillEventFired(Entity* self, Entity* caster, const std::string& message) override; private: - const float_t m_BombTime = 3.3f; - const uint32_t m_MissionID = 1448; - const uint32_t m_SwordSkill = 1259; - const uint32_t m_SwordBehavior = 29305; - const uint32_t m_AOESkill = 1258; - const uint32_t m_AOEBehavior = 29301; - const LOT m_FXObject = 13808; + const float_t m_BombTime = 3.3f; + const uint32_t m_MissionID = 1448; + const uint32_t m_SwordSkill = 1259; + const uint32_t m_SwordBehavior = 29305; + const uint32_t m_AOESkill = 1258; + const uint32_t m_AOEBehavior = 29301; + const LOT m_FXObject = 13808; - // Variables - const std::u16string m_XUsedVariable = u"XUsed"; - const std::u16string m_FlagVariable = u"flag"; - const std::u16string m_StartEffectVariable = u"startEffect"; + // Variables + const std::u16string m_XUsedVariable = u"XUsed"; + const std::u16string m_FlagVariable = u"flag"; + const std::u16string m_StartEffectVariable = u"startEffect"; }; diff --git a/dScripts/AmBridge.cpp b/dScripts/AmBridge.cpp index e2e21033..88f30642 100644 --- a/dScripts/AmBridge.cpp +++ b/dScripts/AmBridge.cpp @@ -1,33 +1,28 @@ #include "AmBridge.h" #include "EntityManager.h" -void AmBridge::OnStartup(Entity* self) -{ - +void AmBridge::OnStartup(Entity* self) { + } -void AmBridge::OnRebuildComplete(Entity* self, Entity* target) -{ - const auto consoles = EntityManager::Instance()->GetEntitiesInGroup("Console" + GeneralUtils::UTF16ToWTF8(self->GetVar(u"bridge"))); +void AmBridge::OnRebuildComplete(Entity* self, Entity* target) { + const auto consoles = EntityManager::Instance()->GetEntitiesInGroup("Console" + GeneralUtils::UTF16ToWTF8(self->GetVar(u"bridge"))); - if (consoles.empty()) - { - return; - } + if (consoles.empty()) { + return; + } - auto* console = consoles[0]; + auto* console = consoles[0]; - console->NotifyObject(self, "BridgeBuilt"); + console->NotifyObject(self, "BridgeBuilt"); - self->AddTimer("SmashBridge", 50); + self->AddTimer("SmashBridge", 50); } -void AmBridge::OnTimerDone(Entity* self, std::string timerName) -{ - if (timerName != "SmashBridge") - { - return; - } +void AmBridge::OnTimerDone(Entity* self, std::string timerName) { + if (timerName != "SmashBridge") { + return; + } - self->Smash(self->GetObjectID(), VIOLENT); + self->Smash(self->GetObjectID(), VIOLENT); } diff --git a/dScripts/AmBridge.h b/dScripts/AmBridge.h index bae35624..0dc025f9 100644 --- a/dScripts/AmBridge.h +++ b/dScripts/AmBridge.h @@ -4,7 +4,7 @@ class AmBridge : public CppScripts::Script { public: - void OnStartup(Entity* self) override; - void OnRebuildComplete(Entity* self, Entity* target) override; - void OnTimerDone(Entity* self, std::string timerName) override; + void OnStartup(Entity* self) override; + void OnRebuildComplete(Entity* self, Entity* target) override; + void OnTimerDone(Entity* self, std::string timerName) override; }; diff --git a/dScripts/AmConsoleTeleportServer.cpp b/dScripts/AmConsoleTeleportServer.cpp index 5087aae2..f3931e0d 100644 --- a/dScripts/AmConsoleTeleportServer.cpp +++ b/dScripts/AmConsoleTeleportServer.cpp @@ -2,35 +2,29 @@ #include "ChooseYourDestinationNsToNt.h" #include "AMFFormat.h" -void AmConsoleTeleportServer::OnStartup(Entity* self) -{ - self->SetVar(u"teleportAnim", m_TeleportAnim); - self->SetVar(u"teleportString", m_TeleportString); - self->SetVar(u"teleportEffectID", m_TeleportEffectID); - self->SetVar(u"teleportEffectTypes", m_TeleportEffectTypes); +void AmConsoleTeleportServer::OnStartup(Entity* self) { + self->SetVar(u"teleportAnim", m_TeleportAnim); + self->SetVar(u"teleportString", m_TeleportString); + self->SetVar(u"teleportEffectID", m_TeleportEffectID); + self->SetVar(u"teleportEffectTypes", m_TeleportEffectTypes); } -void AmConsoleTeleportServer::OnUse(Entity* self, Entity* user) -{ - BaseOnUse(self, user); +void AmConsoleTeleportServer::OnUse(Entity* self, Entity* user) { + BaseOnUse(self, user); } -void AmConsoleTeleportServer::OnMessageBoxResponse(Entity* self, Entity* sender, int32_t button, const std::u16string& identifier, const std::u16string& userData) -{ - BaseOnMessageBoxResponse(self, sender, button, identifier, userData); +void AmConsoleTeleportServer::OnMessageBoxResponse(Entity* self, Entity* sender, int32_t button, const std::u16string& identifier, const std::u16string& userData) { + BaseOnMessageBoxResponse(self, sender, button, identifier, userData); } -void AmConsoleTeleportServer::OnChoiceBoxResponse(Entity* self, Entity* sender, int32_t button, const std::u16string& buttonIdentifier, const std::u16string& identifier) -{ - +void AmConsoleTeleportServer::OnChoiceBoxResponse(Entity* self, Entity* sender, int32_t button, const std::u16string& buttonIdentifier, const std::u16string& identifier) { + } -void AmConsoleTeleportServer::OnTimerDone(Entity* self, std::string timerName) -{ - BaseOnTimerDone(self, timerName); +void AmConsoleTeleportServer::OnTimerDone(Entity* self, std::string timerName) { + BaseOnTimerDone(self, timerName); } -void AmConsoleTeleportServer::OnFireEventServerSide(Entity *self, Entity *sender, std::string args, int32_t param1, int32_t param2, int32_t param3) -{ - BaseOnFireEventServerSide(self, sender, args, param1, param2, param3); +void AmConsoleTeleportServer::OnFireEventServerSide(Entity* self, Entity* sender, std::string args, int32_t param1, int32_t param2, int32_t param3) { + BaseOnFireEventServerSide(self, sender, args, param1, param2, param3); } diff --git a/dScripts/AmConsoleTeleportServer.h b/dScripts/AmConsoleTeleportServer.h index 8236e67e..6206f22c 100644 --- a/dScripts/AmConsoleTeleportServer.h +++ b/dScripts/AmConsoleTeleportServer.h @@ -5,18 +5,18 @@ class AmConsoleTeleportServer : public CppScripts::Script, BaseConsoleTeleportServer { public: - void OnStartup(Entity* self) override; - void OnUse(Entity* self, Entity* user) override; - void OnMessageBoxResponse(Entity* self, Entity* sender, int32_t button, const std::u16string& identifier, const std::u16string& userData) override; - void OnChoiceBoxResponse(Entity* self, Entity* sender, int32_t button, const std::u16string& buttonIdentifier, const std::u16string& identifier) override; - void OnTimerDone(Entity* self, std::string timerName) override; - void OnFireEventServerSide(Entity *self, Entity *sender, std::string args, int32_t param1, int32_t param2, int32_t param3) override; + void OnStartup(Entity* self) override; + void OnUse(Entity* self, Entity* user) override; + void OnMessageBoxResponse(Entity* self, Entity* sender, int32_t button, const std::u16string& identifier, const std::u16string& userData) override; + void OnChoiceBoxResponse(Entity* self, Entity* sender, int32_t button, const std::u16string& buttonIdentifier, const std::u16string& identifier) override; + void OnTimerDone(Entity* self, std::string timerName) override; + void OnFireEventServerSide(Entity* self, Entity* sender, std::string args, int32_t param1, int32_t param2, int32_t param3) override; private: - int32_t m_ChoiceZoneID = 1900; - std::string m_SpawnPoint = "NS_LW"; - std::u16string m_TeleportAnim = u"nexus-teleport"; - std::u16string m_TeleportString = u"UI_TRAVEL_TO_NEXUS_TOWER"; - int32_t m_TeleportEffectID = 6478; - std::vector m_TeleportEffectTypes = {u"teleportRings", u"teleportBeam"}; + int32_t m_ChoiceZoneID = 1900; + std::string m_SpawnPoint = "NS_LW"; + std::u16string m_TeleportAnim = u"nexus-teleport"; + std::u16string m_TeleportString = u"UI_TRAVEL_TO_NEXUS_TOWER"; + int32_t m_TeleportEffectID = 6478; + std::vector m_TeleportEffectTypes = { u"teleportRings", u"teleportBeam" }; }; diff --git a/dScripts/AmDarklingDragon.cpp b/dScripts/AmDarklingDragon.cpp index 94066167..8ec49d3e 100644 --- a/dScripts/AmDarklingDragon.cpp +++ b/dScripts/AmDarklingDragon.cpp @@ -7,153 +7,146 @@ #include "BaseCombatAIComponent.h" void AmDarklingDragon::OnStartup(Entity* self) { - self->SetVar(u"weakspot", 0); + self->SetVar(u"weakspot", 0); - auto* baseCombatAIComponent = self->GetComponent(); + auto* baseCombatAIComponent = self->GetComponent(); - if (baseCombatAIComponent != nullptr) { - baseCombatAIComponent->SetStunImmune(true); - } + if (baseCombatAIComponent != nullptr) { + baseCombatAIComponent->SetStunImmune(true); + } } void AmDarklingDragon::OnDie(Entity* self, Entity* killer) { - if (self->GetVar(u"bDied")) { - return; - } + if (self->GetVar(u"bDied")) { + return; + } - self->SetVar(u"bDied", true); - - auto golemId = self->GetVar(u"Golem"); + self->SetVar(u"bDied", true); - auto* golem = EntityManager::Instance()->GetEntity(golemId); + auto golemId = self->GetVar(u"Golem"); - if (golem != nullptr) { - golem->Smash(self->GetObjectID()); - } + auto* golem = EntityManager::Instance()->GetEntity(golemId); + + if (golem != nullptr) { + golem->Smash(self->GetObjectID()); + } } void AmDarklingDragon::OnHitOrHealResult(Entity* self, Entity* attacker, int32_t damage) { - GameMessages::SendPlayFXEffect(self, -1, u"gothit", "", LWOOBJID_EMPTY, 1, 1, true); + GameMessages::SendPlayFXEffect(self, -1, u"gothit", "", LWOOBJID_EMPTY, 1, 1, true); - if (true) { - auto weakpoint = self->GetVar(u"weakspot"); + if (true) { + auto weakpoint = self->GetVar(u"weakspot"); - if (weakpoint == 1) - { - self->Smash(attacker->GetObjectID()); - } - } + if (weakpoint == 1) { + self->Smash(attacker->GetObjectID()); + } + } - auto* destroyableComponent = self->GetComponent(); + auto* destroyableComponent = self->GetComponent(); - if (destroyableComponent != nullptr) { - if (destroyableComponent->GetArmor() > 0) return; + if (destroyableComponent != nullptr) { + if (destroyableComponent->GetArmor() > 0) return; - auto weakpoint = self->GetVar(u"weakpoint"); + auto weakpoint = self->GetVar(u"weakpoint"); - if (weakpoint == 0) { - self->AddTimer("ReviveTimer", 12); + if (weakpoint == 0) { + self->AddTimer("ReviveTimer", 12); - auto* baseCombatAIComponent = self->GetComponent(); - auto* skillComponent = self->GetComponent(); + auto* baseCombatAIComponent = self->GetComponent(); + auto* skillComponent = self->GetComponent(); - if (baseCombatAIComponent != nullptr) { - baseCombatAIComponent->SetDisabled(true); - baseCombatAIComponent->SetStunned(true); - } + if (baseCombatAIComponent != nullptr) { + baseCombatAIComponent->SetDisabled(true); + baseCombatAIComponent->SetStunned(true); + } - if (skillComponent != nullptr) { - skillComponent->Interrupt(); - } + if (skillComponent != nullptr) { + skillComponent->Interrupt(); + } - self->SetVar(u"weakpoint", 2); + self->SetVar(u"weakpoint", 2); - GameMessages::SendPlayAnimation(self, u"stunstart", 1.7f); + GameMessages::SendPlayAnimation(self, u"stunstart", 1.7f); - self->AddTimer("timeToStunLoop", 1); + self->AddTimer("timeToStunLoop", 1); - auto position = self->GetPosition(); - auto forward = self->GetRotation().GetForwardVector(); - auto backwards = forward * -1; + auto position = self->GetPosition(); + auto forward = self->GetRotation().GetForwardVector(); + auto backwards = forward * -1; - forward.x *= 10; - forward.z *= 10; + forward.x *= 10; + forward.z *= 10; - auto rotation = self->GetRotation(); + auto rotation = self->GetRotation(); - auto objectPosition = NiPoint3(); + auto objectPosition = NiPoint3(); - objectPosition.y = position.y; - objectPosition.x = position.x - (backwards.x * 8); - objectPosition.z = position.z - (backwards.z * 8); + objectPosition.y = position.y; + objectPosition.x = position.x - (backwards.x * 8); + objectPosition.z = position.z - (backwards.z * 8); - auto golem = self->GetVar(u"DragonSmashingGolem"); + auto golem = self->GetVar(u"DragonSmashingGolem"); - EntityInfo info {}; - info.lot = golem != 0 ? golem : 8340; - info.pos = objectPosition; - info.rot = rotation; - info.spawnerID = self->GetObjectID(); - info.settings = { - new LDFData(u"rebuild_activators", - std::to_string(objectPosition.x + forward.x) + "\x1f" + - std::to_string(objectPosition.y) + "\x1f" + - std::to_string(objectPosition.z + forward.z) - ), - new LDFData(u"respawn", 100000), - new LDFData(u"rebuild_reset_time", 15), - new LDFData(u"no_timed_spawn", true), - new LDFData(u"Dragon", self->GetObjectID()) - }; + EntityInfo info{}; + info.lot = golem != 0 ? golem : 8340; + info.pos = objectPosition; + info.rot = rotation; + info.spawnerID = self->GetObjectID(); + info.settings = { + new LDFData(u"rebuild_activators", + std::to_string(objectPosition.x + forward.x) + "\x1f" + + std::to_string(objectPosition.y) + "\x1f" + + std::to_string(objectPosition.z + forward.z) + ), + new LDFData(u"respawn", 100000), + new LDFData(u"rebuild_reset_time", 15), + new LDFData(u"no_timed_spawn", true), + new LDFData(u"Dragon", self->GetObjectID()) + }; - auto* golemObject = EntityManager::Instance()->CreateEntity(info); + auto* golemObject = EntityManager::Instance()->CreateEntity(info); - EntityManager::Instance()->ConstructEntity(golemObject); - } - } + EntityManager::Instance()->ConstructEntity(golemObject); + } + } } -void AmDarklingDragon::OnTimerDone(Entity* self, std::string timerName) { - if (timerName == "ReviveHeldTimer") { - self->AddTimer("backToAttack", 2.5); - } - else if (timerName == "ExposeWeakSpotTimer") { - self->SetVar(u"weakspot", 1); - } - else if (timerName == "timeToStunLoop") { - GameMessages::SendPlayAnimation(self, u"stunloop", 1.8f); - } - else if (timerName == "ReviveTimer") { - GameMessages::SendPlayAnimation(self, u"stunend", 2.0f); - self->AddTimer("backToAttack", 1); - } - else if (timerName == "backToAttack") { - auto* baseCombatAIComponent = self->GetComponent(); - auto* skillComponent = self->GetComponent(); - if (baseCombatAIComponent != nullptr) - { - baseCombatAIComponent->SetDisabled(false); - baseCombatAIComponent->SetStunned(false); - } - if (skillComponent != nullptr) - { - skillComponent->Interrupt(); - } - self->SetVar(u"weakspot", -1); - GameMessages::SendNotifyObject(self->GetObjectID(), self->GetObjectID(), u"DragonRevive", UNASSIGNED_SYSTEM_ADDRESS); - } +void AmDarklingDragon::OnTimerDone(Entity* self, std::string timerName) { + if (timerName == "ReviveHeldTimer") { + self->AddTimer("backToAttack", 2.5); + } else if (timerName == "ExposeWeakSpotTimer") { + self->SetVar(u"weakspot", 1); + } else if (timerName == "timeToStunLoop") { + GameMessages::SendPlayAnimation(self, u"stunloop", 1.8f); + } else if (timerName == "ReviveTimer") { + GameMessages::SendPlayAnimation(self, u"stunend", 2.0f); + self->AddTimer("backToAttack", 1); + } else if (timerName == "backToAttack") { + auto* baseCombatAIComponent = self->GetComponent(); + auto* skillComponent = self->GetComponent(); + if (baseCombatAIComponent != nullptr) { + baseCombatAIComponent->SetDisabled(false); + baseCombatAIComponent->SetStunned(false); + } + if (skillComponent != nullptr) { + skillComponent->Interrupt(); + } + self->SetVar(u"weakspot", -1); + GameMessages::SendNotifyObject(self->GetObjectID(), self->GetObjectID(), u"DragonRevive", UNASSIGNED_SYSTEM_ADDRESS); + } } -void AmDarklingDragon::OnFireEventServerSide(Entity *self, Entity *sender, std::string args, int32_t param1, int32_t param2, int32_t param3) { - if (args != "rebuildDone") return; +void AmDarklingDragon::OnFireEventServerSide(Entity* self, Entity* sender, std::string args, int32_t param1, int32_t param2, int32_t param3) { + if (args != "rebuildDone") return; - self->AddTimer("ExposeWeakSpotTimer", 3.8f); + self->AddTimer("ExposeWeakSpotTimer", 3.8f); - self->CancelTimer("ReviveTimer"); + self->CancelTimer("ReviveTimer"); - self->AddTimer("ReviveHeldTimer", 10.5f); + self->AddTimer("ReviveHeldTimer", 10.5f); - self->SetVar(u"Golem", sender->GetObjectID()); + self->SetVar(u"Golem", sender->GetObjectID()); - GameMessages::SendPlayAnimation(self, u"quickbuildhold", 1.9f); -} \ No newline at end of file + GameMessages::SendPlayAnimation(self, u"quickbuildhold", 1.9f); +} diff --git a/dScripts/AmDarklingDragon.h b/dScripts/AmDarklingDragon.h index ea4c2a19..5a85e329 100644 --- a/dScripts/AmDarklingDragon.h +++ b/dScripts/AmDarklingDragon.h @@ -4,45 +4,45 @@ class AmDarklingDragon : public CppScripts::Script { public: - /** - * @brief When called, this function will make self immune to stuns and initialize a weakspot boolean to false. - * - * @param self The Entity that called this function. - */ - void OnStartup(Entity* self) override; - /** - * @brief When called, this function will destroy the golem if it was alive, otherwise returns immediately. - * - * @param self The Entity that called this function. - * @param killer The Entity that killed self. - */ - void OnDie(Entity* self, Entity* killer) override; - /** - * @brief When self is hit or healed, this function will check if self is at zero armor. If self is at zero armor, a golem Entity Quick Build - * is spawned that, when built, will reveal a weakpoint on the dragon that if hit will smash the dragon instantly. If at more than zero armor, - * this function returns early. - * - * @param self The Entity that was hit. - * @param attacker The Entity that attacked self. - * @param damage The amount of damage attacker did to self. - */ - void OnHitOrHealResult(Entity* self, Entity* attacker, int32_t damage) override; - /** - * @brief Called when self has a timer that ended. - * - * @param self The Entity who owns a timer that finished. - * @param timerName The name of a timer attacked to self that has ended. - */ - void OnTimerDone(Entity* self, std::string timerName) override; - /** - * @brief When the Client has finished rebuilding the Golem for the dragon, this function exposes the weak spot for a set amount of time. - * - * @param self The Entity that called this script. - * @param sender The Entity that sent a fired event. - * @param args The argument that tells us what event has been fired off. - * @param param1 Unused in this script. - * @param param2 Unused in this script. - * @param param3 Unused in this script. - */ - void OnFireEventServerSide(Entity *self, Entity *sender, std::string args, int32_t param1, int32_t param2, int32_t param3) override; + /** + * @brief When called, this function will make self immune to stuns and initialize a weakspot boolean to false. + * + * @param self The Entity that called this function. + */ + void OnStartup(Entity* self) override; + /** + * @brief When called, this function will destroy the golem if it was alive, otherwise returns immediately. + * + * @param self The Entity that called this function. + * @param killer The Entity that killed self. + */ + void OnDie(Entity* self, Entity* killer) override; + /** + * @brief When self is hit or healed, this function will check if self is at zero armor. If self is at zero armor, a golem Entity Quick Build + * is spawned that, when built, will reveal a weakpoint on the dragon that if hit will smash the dragon instantly. If at more than zero armor, + * this function returns early. + * + * @param self The Entity that was hit. + * @param attacker The Entity that attacked self. + * @param damage The amount of damage attacker did to self. + */ + void OnHitOrHealResult(Entity* self, Entity* attacker, int32_t damage) override; + /** + * @brief Called when self has a timer that ended. + * + * @param self The Entity who owns a timer that finished. + * @param timerName The name of a timer attacked to self that has ended. + */ + void OnTimerDone(Entity* self, std::string timerName) override; + /** + * @brief When the Client has finished rebuilding the Golem for the dragon, this function exposes the weak spot for a set amount of time. + * + * @param self The Entity that called this script. + * @param sender The Entity that sent a fired event. + * @param args The argument that tells us what event has been fired off. + * @param param1 Unused in this script. + * @param param2 Unused in this script. + * @param param3 Unused in this script. + */ + void OnFireEventServerSide(Entity* self, Entity* sender, std::string args, int32_t param1, int32_t param2, int32_t param3) override; }; diff --git a/dScripts/AmDarklingMech.cpp b/dScripts/AmDarklingMech.cpp index 33c3fcbf..922296c2 100644 --- a/dScripts/AmDarklingMech.cpp +++ b/dScripts/AmDarklingMech.cpp @@ -1,7 +1,6 @@ #include "AmDarklingMech.h" -void AmDarklingMech::OnStartup(Entity* self) -{ - BaseEnemyMech::OnStartup(self); - qbTurretLOT = 13171; +void AmDarklingMech::OnStartup(Entity* self) { + BaseEnemyMech::OnStartup(self); + qbTurretLOT = 13171; } diff --git a/dScripts/AmDarklingMech.h b/dScripts/AmDarklingMech.h index cc179795..0f54ba7f 100644 --- a/dScripts/AmDarklingMech.h +++ b/dScripts/AmDarklingMech.h @@ -5,5 +5,5 @@ class AmDarklingMech : public BaseEnemyMech { public: - void OnStartup(Entity* self) override; + void OnStartup(Entity* self) override; }; diff --git a/dScripts/AmDrawBridge.cpp b/dScripts/AmDrawBridge.cpp index 8e52e3e4..20636b13 100644 --- a/dScripts/AmDrawBridge.cpp +++ b/dScripts/AmDrawBridge.cpp @@ -3,141 +3,119 @@ #include "GameMessages.h" #include "SimplePhysicsComponent.h" -void AmDrawBridge::OnStartup(Entity* self) -{ - self->SetNetworkVar(u"InUse", false); - self->SetVar(u"BridgeDown", false); +void AmDrawBridge::OnStartup(Entity* self) { + self->SetNetworkVar(u"InUse", false); + self->SetVar(u"BridgeDown", false); } -void AmDrawBridge::OnUse(Entity* self, Entity* user) -{ - auto* bridge = GetBridge(self); +void AmDrawBridge::OnUse(Entity* self, Entity* user) { + auto* bridge = GetBridge(self); - if (bridge == nullptr) - { - return; - } + if (bridge == nullptr) { + return; + } - if (!self->GetNetworkVar(u"InUse")) - { - self->SetNetworkVar(u"startEffect", 5); + if (!self->GetNetworkVar(u"InUse")) { + self->SetNetworkVar(u"startEffect", 5); - self->AddTimer("ChangeBridge", 5); + self->AddTimer("ChangeBridge", 5); - self->SetNetworkVar(u"InUse", true); - } + self->SetNetworkVar(u"InUse", true); + } - auto* player = user; + auto* player = user; - GameMessages::SendTerminateInteraction(player->GetObjectID(), FROM_INTERACTION, self->GetObjectID()); + GameMessages::SendTerminateInteraction(player->GetObjectID(), FROM_INTERACTION, self->GetObjectID()); } -void AmDrawBridge::OnTimerDone(Entity* self, std::string timerName) -{ - if (timerName == "ChangeBridge") - { - auto* bridge = GetBridge(self); +void AmDrawBridge::OnTimerDone(Entity* self, std::string timerName) { + if (timerName == "ChangeBridge") { + auto* bridge = GetBridge(self); - if (bridge == nullptr) - { - return; - } + if (bridge == nullptr) { + return; + } - if (!self->GetVar(u"BridgeDown")) - { - self->SetVar(u"BridgeDown", true); + if (!self->GetVar(u"BridgeDown")) { + self->SetVar(u"BridgeDown", true); - MoveBridgeDown(self, bridge, true); - } - else - { - self->SetVar(u"BridgeDown", false); + MoveBridgeDown(self, bridge, true); + } else { + self->SetVar(u"BridgeDown", false); - MoveBridgeDown(self, bridge, false); - } + MoveBridgeDown(self, bridge, false); + } - self->SetNetworkVar(u"BridgeLeaving", true); - self->SetVar(u"BridgeDown", false); - } - else if (timerName == "SmashEffectBridge") - { - self->SetNetworkVar(u"SmashBridge", 5); - } - else if (timerName == "rotateBridgeDown") - { - auto* bridge = GetBridge(self); + self->SetNetworkVar(u"BridgeLeaving", true); + self->SetVar(u"BridgeDown", false); + } else if (timerName == "SmashEffectBridge") { + self->SetNetworkVar(u"SmashBridge", 5); + } else if (timerName == "rotateBridgeDown") { + auto* bridge = GetBridge(self); - if (bridge == nullptr) - { - return; - } + if (bridge == nullptr) { + return; + } - self->SetNetworkVar(u"BridgeLeaving", false); + self->SetNetworkVar(u"BridgeLeaving", false); - auto* simplePhysicsComponent = bridge->GetComponent(); + auto* simplePhysicsComponent = bridge->GetComponent(); - if (simplePhysicsComponent == nullptr) - { - return; - } + if (simplePhysicsComponent == nullptr) { + return; + } - simplePhysicsComponent->SetAngularVelocity(NiPoint3::ZERO); + simplePhysicsComponent->SetAngularVelocity(NiPoint3::ZERO); - EntityManager::Instance()->SerializeEntity(bridge); - } + EntityManager::Instance()->SerializeEntity(bridge); + } } -void AmDrawBridge::OnNotifyObject(Entity *self, Entity *sender, const std::string& name, int32_t param1, int32_t param2) -{ - if (name == "BridgeBuilt") - { - self->SetVar(u"BridgeID", sender->GetObjectID()); +void AmDrawBridge::OnNotifyObject(Entity* self, Entity* sender, const std::string& name, int32_t param1, int32_t param2) { + if (name == "BridgeBuilt") { + self->SetVar(u"BridgeID", sender->GetObjectID()); - self->AddTimer("SmashEffectBridge", 45); + self->AddTimer("SmashEffectBridge", 45); - self->SetNetworkVar(u"BridgeDead", true); + self->SetNetworkVar(u"BridgeDead", true); - sender->AddDieCallback([this, self, sender] () { - NotifyDie(self, sender); - }); - } + sender->AddDieCallback([this, self, sender]() { + NotifyDie(self, sender); + }); + } } -void AmDrawBridge::MoveBridgeDown(Entity* self, Entity* bridge, bool down) -{ - auto* simplePhysicsComponent = bridge->GetComponent(); +void AmDrawBridge::MoveBridgeDown(Entity* self, Entity* bridge, bool down) { + auto* simplePhysicsComponent = bridge->GetComponent(); - if (simplePhysicsComponent == nullptr) - { - return; - } + if (simplePhysicsComponent == nullptr) { + return; + } - auto forwardVect = simplePhysicsComponent->GetRotation().GetForwardVector(); + auto forwardVect = simplePhysicsComponent->GetRotation().GetForwardVector(); - auto degrees = down ? 90.0f : -90.0f; + auto degrees = down ? 90.0f : -90.0f; - const auto travelTime = 2.0f; + const auto travelTime = 2.0f; - forwardVect = forwardVect * (float) ((degrees / travelTime) * (3.14f / 180.0f)); + forwardVect = forwardVect * (float)((degrees / travelTime) * (3.14f / 180.0f)); - simplePhysicsComponent->SetAngularVelocity(forwardVect); + simplePhysicsComponent->SetAngularVelocity(forwardVect); - EntityManager::Instance()->SerializeEntity(bridge); + EntityManager::Instance()->SerializeEntity(bridge); - self->AddTimer("rotateBridgeDown", travelTime); + self->AddTimer("rotateBridgeDown", travelTime); } -void AmDrawBridge::NotifyDie(Entity* self, Entity* other) -{ - self->SetNetworkVar(u"InUse", false); - self->SetVar(u"BridgeDown", false); +void AmDrawBridge::NotifyDie(Entity* self, Entity* other) { + self->SetNetworkVar(u"InUse", false); + self->SetVar(u"BridgeDown", false); - self->CancelAllTimers(); + self->CancelAllTimers(); } -Entity* AmDrawBridge::GetBridge(Entity* self) -{ - const auto bridgeID = self->GetVar(u"BridgeID"); +Entity* AmDrawBridge::GetBridge(Entity* self) { + const auto bridgeID = self->GetVar(u"BridgeID"); - return EntityManager::Instance()->GetEntity(bridgeID); + return EntityManager::Instance()->GetEntity(bridgeID); } diff --git a/dScripts/AmDrawBridge.h b/dScripts/AmDrawBridge.h index e7b801df..86237b7f 100644 --- a/dScripts/AmDrawBridge.h +++ b/dScripts/AmDrawBridge.h @@ -4,13 +4,13 @@ class AmDrawBridge : public CppScripts::Script { public: - void OnStartup(Entity* self) override; - void OnUse(Entity* self, Entity* user) override; - void OnTimerDone(Entity* self, std::string timerName) override; - void OnNotifyObject(Entity *self, Entity *sender, const std::string& name, int32_t param1 = 0, int32_t param2 = 0) override; + void OnStartup(Entity* self) override; + void OnUse(Entity* self, Entity* user) override; + void OnTimerDone(Entity* self, std::string timerName) override; + void OnNotifyObject(Entity* self, Entity* sender, const std::string& name, int32_t param1 = 0, int32_t param2 = 0) override; - void MoveBridgeDown(Entity* self, Entity* bridge, bool down); - void NotifyDie(Entity* self, Entity* other); + void MoveBridgeDown(Entity* self, Entity* bridge, bool down); + void NotifyDie(Entity* self, Entity* other); - Entity* GetBridge(Entity* self); + Entity* GetBridge(Entity* self); }; diff --git a/dScripts/AmDropshipComputer.cpp b/dScripts/AmDropshipComputer.cpp index d25bd4f2..909beaaf 100644 --- a/dScripts/AmDropshipComputer.cpp +++ b/dScripts/AmDropshipComputer.cpp @@ -4,94 +4,78 @@ #include "InventoryComponent.h" #include "dZoneManager.h" -void AmDropshipComputer::OnStartup(Entity* self) -{ - self->AddTimer("reset", 45.0f); +void AmDropshipComputer::OnStartup(Entity* self) { + self->AddTimer("reset", 45.0f); } -void AmDropshipComputer::OnUse(Entity* self, Entity* user) -{ - auto* rebuildComponent = self->GetComponent(); +void AmDropshipComputer::OnUse(Entity* self, Entity* user) { + auto* rebuildComponent = self->GetComponent(); - if (rebuildComponent == nullptr || rebuildComponent->GetState() != REBUILD_COMPLETED) - { - return; - } + if (rebuildComponent == nullptr || rebuildComponent->GetState() != REBUILD_COMPLETED) { + return; + } - auto* missionComponent = user->GetComponent(); - auto* inventoryComponent = user->GetComponent(); - - if (missionComponent == nullptr || inventoryComponent == nullptr) - { - return; - } + auto* missionComponent = user->GetComponent(); + auto* inventoryComponent = user->GetComponent(); - if (inventoryComponent->GetLotCount(m_NexusTalonDataCard) != 0 || missionComponent->GetMission(979)->GetMissionState() == MissionState::MISSION_STATE_COMPLETE) - { - return; - } + if (missionComponent == nullptr || inventoryComponent == nullptr) { + return; + } - inventoryComponent->AddItem(m_NexusTalonDataCard, 1, eLootSourceType::LOOT_SOURCE_NONE); + if (inventoryComponent->GetLotCount(m_NexusTalonDataCard) != 0 || missionComponent->GetMission(979)->GetMissionState() == MissionState::MISSION_STATE_COMPLETE) { + return; + } + + inventoryComponent->AddItem(m_NexusTalonDataCard, 1, eLootSourceType::LOOT_SOURCE_NONE); } -void AmDropshipComputer::OnDie(Entity* self, Entity* killer) -{ - const auto myGroup = GeneralUtils::UTF16ToWTF8(self->GetVar(u"spawner_name")); +void AmDropshipComputer::OnDie(Entity* self, Entity* killer) { + const auto myGroup = GeneralUtils::UTF16ToWTF8(self->GetVar(u"spawner_name")); - int32_t pipeNum = 0; - if (!GeneralUtils::TryParse(myGroup.substr(10, 1), pipeNum)) - { - return; - } + int32_t pipeNum = 0; + if (!GeneralUtils::TryParse(myGroup.substr(10, 1), pipeNum)) { + return; + } - const auto pipeGroup = myGroup.substr(0, 10); + const auto pipeGroup = myGroup.substr(0, 10); - const auto nextPipeNum = pipeNum + 1; + const auto nextPipeNum = pipeNum + 1; - const auto samePipeSpawners = dZoneManager::Instance()->GetSpawnersByName(myGroup); + const auto samePipeSpawners = dZoneManager::Instance()->GetSpawnersByName(myGroup); - if (!samePipeSpawners.empty()) - { - samePipeSpawners[0]->SoftReset(); + if (!samePipeSpawners.empty()) { + samePipeSpawners[0]->SoftReset(); - samePipeSpawners[0]->Deactivate(); - } + samePipeSpawners[0]->Deactivate(); + } - if (killer != nullptr && killer->IsPlayer()) - { - const auto nextPipe = pipeGroup + std::to_string(nextPipeNum); + if (killer != nullptr && killer->IsPlayer()) { + const auto nextPipe = pipeGroup + std::to_string(nextPipeNum); - const auto nextPipeSpawners = dZoneManager::Instance()->GetSpawnersByName(nextPipe); + const auto nextPipeSpawners = dZoneManager::Instance()->GetSpawnersByName(nextPipe); - if (!nextPipeSpawners.empty()) - { - nextPipeSpawners[0]->Activate(); - } - } - else - { - const auto nextPipe = pipeGroup + "1"; + if (!nextPipeSpawners.empty()) { + nextPipeSpawners[0]->Activate(); + } + } else { + const auto nextPipe = pipeGroup + "1"; - const auto firstPipeSpawners = dZoneManager::Instance()->GetSpawnersByName(nextPipe); + const auto firstPipeSpawners = dZoneManager::Instance()->GetSpawnersByName(nextPipe); - if (!firstPipeSpawners.empty()) - { - firstPipeSpawners[0]->Activate(); - } - } + if (!firstPipeSpawners.empty()) { + firstPipeSpawners[0]->Activate(); + } + } } -void AmDropshipComputer::OnTimerDone(Entity* self, std::string timerName) -{ - auto* rebuildComponent = self->GetComponent(); +void AmDropshipComputer::OnTimerDone(Entity* self, std::string timerName) { + auto* rebuildComponent = self->GetComponent(); - if (rebuildComponent == nullptr) - { - return; - } + if (rebuildComponent == nullptr) { + return; + } - if (timerName == "reset" && rebuildComponent->GetState() == REBUILD_OPEN) - { - self->Smash(self->GetObjectID(), SILENT); - } + if (timerName == "reset" && rebuildComponent->GetState() == REBUILD_OPEN) { + self->Smash(self->GetObjectID(), SILENT); + } } diff --git a/dScripts/AmDropshipComputer.h b/dScripts/AmDropshipComputer.h index 620770af..730f2222 100644 --- a/dScripts/AmDropshipComputer.h +++ b/dScripts/AmDropshipComputer.h @@ -4,10 +4,10 @@ class AmDropshipComputer : public CppScripts::Script { public: - void OnStartup(Entity* self) override; - void OnUse(Entity* self, Entity* user) override; - void OnDie(Entity* self, Entity* killer) override; - void OnTimerDone(Entity* self, std::string timerName) override; + void OnStartup(Entity* self) override; + void OnUse(Entity* self, Entity* user) override; + void OnDie(Entity* self, Entity* killer) override; + void OnTimerDone(Entity* self, std::string timerName) override; private: - const LOT m_NexusTalonDataCard = 12323; + const LOT m_NexusTalonDataCard = 12323; }; diff --git a/dScripts/AmScrollReaderServer.cpp b/dScripts/AmScrollReaderServer.cpp index 280833c2..cb8a7dba 100644 --- a/dScripts/AmScrollReaderServer.cpp +++ b/dScripts/AmScrollReaderServer.cpp @@ -1,17 +1,14 @@ #include "AmScrollReaderServer.h" #include "MissionComponent.h" -void AmScrollReaderServer::OnMessageBoxResponse(Entity* self, Entity* sender, int32_t button, const std::u16string& identifier, const std::u16string& userData) -{ - if (identifier == u"story_end") - { - auto* missionComponent = sender->GetComponent(); +void AmScrollReaderServer::OnMessageBoxResponse(Entity* self, Entity* sender, int32_t button, const std::u16string& identifier, const std::u16string& userData) { + if (identifier == u"story_end") { + auto* missionComponent = sender->GetComponent(); - if (missionComponent == nullptr) - { - return; - } + if (missionComponent == nullptr) { + return; + } - missionComponent->ForceProgressTaskType(969, 1, 1, false); - } + missionComponent->ForceProgressTaskType(969, 1, 1, false); + } } diff --git a/dScripts/AmScrollReaderServer.h b/dScripts/AmScrollReaderServer.h index b9e5943d..f00e29e0 100644 --- a/dScripts/AmScrollReaderServer.h +++ b/dScripts/AmScrollReaderServer.h @@ -4,5 +4,5 @@ class AmScrollReaderServer : public CppScripts::Script { public: - void OnMessageBoxResponse(Entity* self, Entity* sender, int32_t button, const std::u16string& identifier, const std::u16string& userData) override; + void OnMessageBoxResponse(Entity* self, Entity* sender, int32_t button, const std::u16string& identifier, const std::u16string& userData) override; }; diff --git a/dScripts/AmShieldGenerator.cpp b/dScripts/AmShieldGenerator.cpp index 0e942612..d16acb87 100644 --- a/dScripts/AmShieldGenerator.cpp +++ b/dScripts/AmShieldGenerator.cpp @@ -6,167 +6,139 @@ #include "BaseCombatAIComponent.h" #include "SkillComponent.h" -void AmShieldGenerator::OnStartup(Entity* self) -{ - self->SetProximityRadius(20, "shield"); - self->SetProximityRadius(21, "buffer"); - - StartShield(self); +void AmShieldGenerator::OnStartup(Entity* self) { + self->SetProximityRadius(20, "shield"); + self->SetProximityRadius(21, "buffer"); + + StartShield(self); } -void AmShieldGenerator::OnProximityUpdate(Entity* self, Entity* entering, std::string name, std::string status) -{ - auto* destroyableComponent = entering->GetComponent(); +void AmShieldGenerator::OnProximityUpdate(Entity* self, Entity* entering, std::string name, std::string status) { + auto* destroyableComponent = entering->GetComponent(); - if (status == "ENTER" && name == "shield") - { - if (destroyableComponent->HasFaction(4)) - { - EnemyEnteredShield(self, entering); - } - } - - if (name != "buffer" || !entering->IsPlayer()) - { - return; - } + if (status == "ENTER" && name == "shield") { + if (destroyableComponent->HasFaction(4)) { + EnemyEnteredShield(self, entering); + } + } - auto entitiesInProximity = self->GetVar>(u"Players"); + if (name != "buffer" || !entering->IsPlayer()) { + return; + } - if (status == "ENTER") - { - const auto& iter = std::find(entitiesInProximity.begin(), entitiesInProximity.end(), entering->GetObjectID()); + auto entitiesInProximity = self->GetVar>(u"Players"); - if (iter == entitiesInProximity.end()) - { - entitiesInProximity.push_back(entering->GetObjectID()); - } - } - else if (status == "LEAVE") - { - const auto& iter = std::find(entitiesInProximity.begin(), entitiesInProximity.end(), entering->GetObjectID()); + if (status == "ENTER") { + const auto& iter = std::find(entitiesInProximity.begin(), entitiesInProximity.end(), entering->GetObjectID()); - if (iter != entitiesInProximity.end()) - { - entitiesInProximity.erase(iter); - } - } + if (iter == entitiesInProximity.end()) { + entitiesInProximity.push_back(entering->GetObjectID()); + } + } else if (status == "LEAVE") { + const auto& iter = std::find(entitiesInProximity.begin(), entitiesInProximity.end(), entering->GetObjectID()); - self->SetVar>(u"Players", entitiesInProximity); + if (iter != entitiesInProximity.end()) { + entitiesInProximity.erase(iter); + } + } + + self->SetVar>(u"Players", entitiesInProximity); } -void AmShieldGenerator::OnDie(Entity* self, Entity* killer) -{ - self->CancelAllTimers(); +void AmShieldGenerator::OnDie(Entity* self, Entity* killer) { + self->CancelAllTimers(); - auto* child = EntityManager::Instance()->GetEntity(self->GetVar(u"Child")); + auto* child = EntityManager::Instance()->GetEntity(self->GetVar(u"Child")); - if (child != nullptr) - { - child->Kill(); - } + if (child != nullptr) { + child->Kill(); + } } -void AmShieldGenerator::OnTimerDone(Entity* self, std::string timerName) -{ - if (timerName == "BuffPlayers") - { - BuffPlayers(self); +void AmShieldGenerator::OnTimerDone(Entity* self, std::string timerName) { + if (timerName == "BuffPlayers") { + BuffPlayers(self); - self->AddTimer("BuffPlayers", 3.0f); - } - else if (timerName == "PlayFX") - { - GameMessages::SendPlayFXEffect(self->GetObjectID(), 5351, u"generatorOn", "generatorOn"); + self->AddTimer("BuffPlayers", 3.0f); + } else if (timerName == "PlayFX") { + GameMessages::SendPlayFXEffect(self->GetObjectID(), 5351, u"generatorOn", "generatorOn"); - self->AddTimer("PlayFX", 1.5f); - } - else if (timerName == "RefreshEnemies") - { - auto enemiesInProximity = self->GetVar>(u"Enemies"); + self->AddTimer("PlayFX", 1.5f); + } else if (timerName == "RefreshEnemies") { + auto enemiesInProximity = self->GetVar>(u"Enemies"); - for (const auto enemyID : enemiesInProximity) - { - auto* enemy = EntityManager::Instance()->GetEntity(enemyID); + for (const auto enemyID : enemiesInProximity) { + auto* enemy = EntityManager::Instance()->GetEntity(enemyID); - if (enemy != nullptr) - { - EnemyEnteredShield(self, enemy); - } - } + if (enemy != nullptr) { + EnemyEnteredShield(self, enemy); + } + } - self->AddTimer("RefreshEnemies", 1.5f); - } + self->AddTimer("RefreshEnemies", 1.5f); + } } -void AmShieldGenerator::StartShield(Entity* self) -{ - self->AddTimer("PlayFX", 1.5f); - self->AddTimer("BuffPlayers", 3.0f); - self->AddTimer("RefreshEnemies", 1.5f); +void AmShieldGenerator::StartShield(Entity* self) { + self->AddTimer("PlayFX", 1.5f); + self->AddTimer("BuffPlayers", 3.0f); + self->AddTimer("RefreshEnemies", 1.5f); - const auto myPos = self->GetPosition(); - const auto myRot = self->GetRotation(); + const auto myPos = self->GetPosition(); + const auto myRot = self->GetRotation(); - EntityInfo info {}; - info.lot = 13111; - info.pos = myPos; - info.rot = myRot; - info.spawnerID = self->GetObjectID(); + EntityInfo info{}; + info.lot = 13111; + info.pos = myPos; + info.rot = myRot; + info.spawnerID = self->GetObjectID(); - auto* child = EntityManager::Instance()->CreateEntity(info); + auto* child = EntityManager::Instance()->CreateEntity(info); - self->SetVar(u"Child", child->GetObjectID()); + self->SetVar(u"Child", child->GetObjectID()); - BuffPlayers(self); + BuffPlayers(self); } -void AmShieldGenerator::BuffPlayers(Entity* self) -{ - auto* skillComponent = self->GetComponent(); +void AmShieldGenerator::BuffPlayers(Entity* self) { + auto* skillComponent = self->GetComponent(); - if (skillComponent == nullptr) - { - return; - } + if (skillComponent == nullptr) { + return; + } - auto entitiesInProximity = self->GetVar>(u"Players"); + auto entitiesInProximity = self->GetVar>(u"Players"); - for (const auto playerID : entitiesInProximity) - { - auto* player = EntityManager::Instance()->GetEntity(playerID); + for (const auto playerID : entitiesInProximity) { + auto* player = EntityManager::Instance()->GetEntity(playerID); - if (player == nullptr) - { - return; - } + if (player == nullptr) { + return; + } - skillComponent->CalculateBehavior(1200, 27024, playerID, true); - } + skillComponent->CalculateBehavior(1200, 27024, playerID, true); + } } -void AmShieldGenerator::EnemyEnteredShield(Entity* self, Entity* intruder) -{ - auto* baseCombatAIComponent = intruder->GetComponent(); - auto* movementAIComponent = intruder->GetComponent(); +void AmShieldGenerator::EnemyEnteredShield(Entity* self, Entity* intruder) { + auto* baseCombatAIComponent = intruder->GetComponent(); + auto* movementAIComponent = intruder->GetComponent(); - if (baseCombatAIComponent == nullptr || movementAIComponent == nullptr) - { - return; - } + if (baseCombatAIComponent == nullptr || movementAIComponent == nullptr) { + return; + } - auto dir = intruder->GetRotation().GetForwardVector() * -1; - dir.y += 15; - dir.x *= 50; - dir.z *= 50; + auto dir = intruder->GetRotation().GetForwardVector() * -1; + dir.y += 15; + dir.x *= 50; + dir.z *= 50; - // TODO: Figure out how todo knockback, I'll stun them for now + // TODO: Figure out how todo knockback, I'll stun them for now - if (NiPoint3::DistanceSquared(self->GetPosition(), movementAIComponent->GetCurrentPosition()) < 20 * 20) - { - baseCombatAIComponent->Stun(2.0f); - movementAIComponent->SetDestination(baseCombatAIComponent->GetStartPosition()); - } + if (NiPoint3::DistanceSquared(self->GetPosition(), movementAIComponent->GetCurrentPosition()) < 20 * 20) { + baseCombatAIComponent->Stun(2.0f); + movementAIComponent->SetDestination(baseCombatAIComponent->GetStartPosition()); + } - baseCombatAIComponent->ClearThreat(); + baseCombatAIComponent->ClearThreat(); } diff --git a/dScripts/AmShieldGenerator.h b/dScripts/AmShieldGenerator.h index b88a89cb..9b46f021 100644 --- a/dScripts/AmShieldGenerator.h +++ b/dScripts/AmShieldGenerator.h @@ -4,12 +4,12 @@ class AmShieldGenerator : public CppScripts::Script { public: - void OnStartup(Entity* self) override; - void OnProximityUpdate(Entity* self, Entity* entering, std::string name, std::string status) override; - void OnDie(Entity* self, Entity* killer) override; - void OnTimerDone(Entity* self, std::string timerName) override; + void OnStartup(Entity* self) override; + void OnProximityUpdate(Entity* self, Entity* entering, std::string name, std::string status) override; + void OnDie(Entity* self, Entity* killer) override; + void OnTimerDone(Entity* self, std::string timerName) override; - void StartShield(Entity* self); - void BuffPlayers(Entity* self); - void EnemyEnteredShield(Entity* self, Entity* intruder); + void StartShield(Entity* self); + void BuffPlayers(Entity* self); + void EnemyEnteredShield(Entity* self, Entity* intruder); }; diff --git a/dScripts/AmShieldGeneratorQuickbuild.cpp b/dScripts/AmShieldGeneratorQuickbuild.cpp index aa80148c..9f27b904 100644 --- a/dScripts/AmShieldGeneratorQuickbuild.cpp +++ b/dScripts/AmShieldGeneratorQuickbuild.cpp @@ -8,235 +8,195 @@ #include "RebuildComponent.h" #include "MissionComponent.h" -void AmShieldGeneratorQuickbuild::OnStartup(Entity* self) -{ - self->SetProximityRadius(20, "shield"); - self->SetProximityRadius(21, "buffer"); +void AmShieldGeneratorQuickbuild::OnStartup(Entity* self) { + self->SetProximityRadius(20, "shield"); + self->SetProximityRadius(21, "buffer"); } -void AmShieldGeneratorQuickbuild::OnProximityUpdate(Entity* self, Entity* entering, std::string name, std::string status) -{ - auto* destroyableComponent = entering->GetComponent(); +void AmShieldGeneratorQuickbuild::OnProximityUpdate(Entity* self, Entity* entering, std::string name, std::string status) { + auto* destroyableComponent = entering->GetComponent(); - if (name == "shield") - { - if (!destroyableComponent->HasFaction(4) || entering->IsPlayer()) - { - return; - } + if (name == "shield") { + if (!destroyableComponent->HasFaction(4) || entering->IsPlayer()) { + return; + } - auto enemiesInProximity = self->GetVar>(u"Enemies"); + auto enemiesInProximity = self->GetVar>(u"Enemies"); - if (status == "ENTER") - { - EnemyEnteredShield(self, entering); + if (status == "ENTER") { + EnemyEnteredShield(self, entering); - const auto& iter = std::find(enemiesInProximity.begin(), enemiesInProximity.end(), entering->GetObjectID()); + const auto& iter = std::find(enemiesInProximity.begin(), enemiesInProximity.end(), entering->GetObjectID()); - if (iter == enemiesInProximity.end()) - { - enemiesInProximity.push_back(entering->GetObjectID()); - } - } - else if (status == "LEAVE") - { - const auto& iter = std::find(enemiesInProximity.begin(), enemiesInProximity.end(), entering->GetObjectID()); + if (iter == enemiesInProximity.end()) { + enemiesInProximity.push_back(entering->GetObjectID()); + } + } else if (status == "LEAVE") { + const auto& iter = std::find(enemiesInProximity.begin(), enemiesInProximity.end(), entering->GetObjectID()); - if (iter != enemiesInProximity.end()) - { - enemiesInProximity.erase(iter); - } - } + if (iter != enemiesInProximity.end()) { + enemiesInProximity.erase(iter); + } + } - self->SetVar>(u"Enemies", enemiesInProximity); - } + self->SetVar>(u"Enemies", enemiesInProximity); + } - if (name != "buffer" || !entering->IsPlayer()) - { - return; - } + if (name != "buffer" || !entering->IsPlayer()) { + return; + } - auto entitiesInProximity = self->GetVar>(u"Players"); + auto entitiesInProximity = self->GetVar>(u"Players"); - if (status == "ENTER") - { - const auto& iter = std::find(entitiesInProximity.begin(), entitiesInProximity.end(), entering->GetObjectID()); + if (status == "ENTER") { + const auto& iter = std::find(entitiesInProximity.begin(), entitiesInProximity.end(), entering->GetObjectID()); - if (iter == entitiesInProximity.end()) - { - entitiesInProximity.push_back(entering->GetObjectID()); - } - } - else if (status == "LEAVE") - { - const auto& iter = std::find(entitiesInProximity.begin(), entitiesInProximity.end(), entering->GetObjectID()); + if (iter == entitiesInProximity.end()) { + entitiesInProximity.push_back(entering->GetObjectID()); + } + } else if (status == "LEAVE") { + const auto& iter = std::find(entitiesInProximity.begin(), entitiesInProximity.end(), entering->GetObjectID()); - if (iter != entitiesInProximity.end()) - { - entitiesInProximity.erase(iter); - } - } + if (iter != entitiesInProximity.end()) { + entitiesInProximity.erase(iter); + } + } - self->SetVar>(u"Players", entitiesInProximity); + self->SetVar>(u"Players", entitiesInProximity); } -void AmShieldGeneratorQuickbuild::OnDie(Entity* self, Entity* killer) -{ - self->CancelAllTimers(); +void AmShieldGeneratorQuickbuild::OnDie(Entity* self, Entity* killer) { + self->CancelAllTimers(); - auto* child = EntityManager::Instance()->GetEntity(self->GetVar(u"Child")); + auto* child = EntityManager::Instance()->GetEntity(self->GetVar(u"Child")); - if (child != nullptr) - { - child->Kill(); - } + if (child != nullptr) { + child->Kill(); + } } -void AmShieldGeneratorQuickbuild::OnTimerDone(Entity* self, std::string timerName) -{ - if (timerName == "BuffPlayers") - { - BuffPlayers(self); +void AmShieldGeneratorQuickbuild::OnTimerDone(Entity* self, std::string timerName) { + if (timerName == "BuffPlayers") { + BuffPlayers(self); - self->AddTimer("BuffPlayers", 3.0f); - } - else if (timerName == "PlayFX") - { - GameMessages::SendPlayFXEffect(self->GetObjectID(), 5351, u"generatorOn", "generatorOn"); + self->AddTimer("BuffPlayers", 3.0f); + } else if (timerName == "PlayFX") { + GameMessages::SendPlayFXEffect(self->GetObjectID(), 5351, u"generatorOn", "generatorOn"); - self->AddTimer("PlayFX", 1.5f); - } - else if (timerName == "RefreshEnemies") - { - auto enemiesInProximity = self->GetVar>(u"Enemies"); + self->AddTimer("PlayFX", 1.5f); + } else if (timerName == "RefreshEnemies") { + auto enemiesInProximity = self->GetVar>(u"Enemies"); - for (const auto enemyID : enemiesInProximity) - { - auto* enemy = EntityManager::Instance()->GetEntity(enemyID); + for (const auto enemyID : enemiesInProximity) { + auto* enemy = EntityManager::Instance()->GetEntity(enemyID); - if (enemy != nullptr) - { - EnemyEnteredShield(self, enemy); - } - } + if (enemy != nullptr) { + EnemyEnteredShield(self, enemy); + } + } - self->AddTimer("RefreshEnemies", 1.5f); - } + self->AddTimer("RefreshEnemies", 1.5f); + } } -void AmShieldGeneratorQuickbuild::OnRebuildComplete(Entity* self, Entity* target) -{ - StartShield(self); +void AmShieldGeneratorQuickbuild::OnRebuildComplete(Entity* self, Entity* target) { + StartShield(self); - auto enemiesInProximity = self->GetVar>(u"Enemies"); + auto enemiesInProximity = self->GetVar>(u"Enemies"); - for (const auto enemyID : enemiesInProximity) - { - auto* enemy = EntityManager::Instance()->GetEntity(enemyID); + for (const auto enemyID : enemiesInProximity) { + auto* enemy = EntityManager::Instance()->GetEntity(enemyID); - if (enemy != nullptr) - { - enemy->Smash(); - } - } + if (enemy != nullptr) { + enemy->Smash(); + } + } - auto entitiesInProximity = self->GetVar>(u"Players"); + auto entitiesInProximity = self->GetVar>(u"Players"); - for (const auto playerID : entitiesInProximity) - { - auto* player = EntityManager::Instance()->GetEntity(playerID); + for (const auto playerID : entitiesInProximity) { + auto* player = EntityManager::Instance()->GetEntity(playerID); - if (player == nullptr) - { - continue; - } - - auto* missionComponent = player->GetComponent(); + if (player == nullptr) { + continue; + } - if (missionComponent == nullptr) - { - return; - } + auto* missionComponent = player->GetComponent(); - missionComponent->ForceProgressTaskType(987, 1, 1, false); - } + if (missionComponent == nullptr) { + return; + } + + missionComponent->ForceProgressTaskType(987, 1, 1, false); + } } -void AmShieldGeneratorQuickbuild::StartShield(Entity* self) -{ - self->AddTimer("PlayFX", 1.5f); - self->AddTimer("BuffPlayers", 3.0f); - self->AddTimer("RefreshEnemies", 1.5f); +void AmShieldGeneratorQuickbuild::StartShield(Entity* self) { + self->AddTimer("PlayFX", 1.5f); + self->AddTimer("BuffPlayers", 3.0f); + self->AddTimer("RefreshEnemies", 1.5f); - const auto myPos = self->GetPosition(); - const auto myRot = self->GetRotation(); + const auto myPos = self->GetPosition(); + const auto myRot = self->GetRotation(); - EntityInfo info {}; - info.lot = 13111; - info.pos = myPos; - info.rot = myRot; - info.spawnerID = self->GetObjectID(); + EntityInfo info{}; + info.lot = 13111; + info.pos = myPos; + info.rot = myRot; + info.spawnerID = self->GetObjectID(); - auto* child = EntityManager::Instance()->CreateEntity(info); + auto* child = EntityManager::Instance()->CreateEntity(info); - self->SetVar(u"Child", child->GetObjectID()); + self->SetVar(u"Child", child->GetObjectID()); - BuffPlayers(self); + BuffPlayers(self); } -void AmShieldGeneratorQuickbuild::BuffPlayers(Entity* self) -{ - auto* skillComponent = self->GetComponent(); +void AmShieldGeneratorQuickbuild::BuffPlayers(Entity* self) { + auto* skillComponent = self->GetComponent(); - if (skillComponent == nullptr) - { - return; - } + if (skillComponent == nullptr) { + return; + } - auto entitiesInProximity = self->GetVar>(u"Players"); + auto entitiesInProximity = self->GetVar>(u"Players"); - for (const auto playerID : entitiesInProximity) - { - auto* player = EntityManager::Instance()->GetEntity(playerID); + for (const auto playerID : entitiesInProximity) { + auto* player = EntityManager::Instance()->GetEntity(playerID); - if (player == nullptr) - { - return; - } + if (player == nullptr) { + return; + } - skillComponent->CalculateBehavior(1200, 27024, playerID, true); - } + skillComponent->CalculateBehavior(1200, 27024, playerID, true); + } } -void AmShieldGeneratorQuickbuild::EnemyEnteredShield(Entity* self, Entity* intruder) -{ - auto* rebuildComponent = self->GetComponent(); +void AmShieldGeneratorQuickbuild::EnemyEnteredShield(Entity* self, Entity* intruder) { + auto* rebuildComponent = self->GetComponent(); - if (rebuildComponent == nullptr || rebuildComponent->GetState() != REBUILD_COMPLETED) - { - return; - } + if (rebuildComponent == nullptr || rebuildComponent->GetState() != REBUILD_COMPLETED) { + return; + } - auto* baseCombatAIComponent = intruder->GetComponent(); - auto* movementAIComponent = intruder->GetComponent(); + auto* baseCombatAIComponent = intruder->GetComponent(); + auto* movementAIComponent = intruder->GetComponent(); - if (baseCombatAIComponent == nullptr || movementAIComponent == nullptr) - { - return; - } + if (baseCombatAIComponent == nullptr || movementAIComponent == nullptr) { + return; + } - auto dir = intruder->GetRotation().GetForwardVector() * -1; - dir.y += 15; - dir.x *= 50; - dir.z *= 50; + auto dir = intruder->GetRotation().GetForwardVector() * -1; + dir.y += 15; + dir.x *= 50; + dir.z *= 50; - // TODO: Figure out how todo knockback, I'll stun them for now + // TODO: Figure out how todo knockback, I'll stun them for now - if (NiPoint3::DistanceSquared(self->GetPosition(), movementAIComponent->GetCurrentPosition()) < 20 * 20) - { - baseCombatAIComponent->Stun(2.0f); - movementAIComponent->SetDestination(baseCombatAIComponent->GetStartPosition()); - } + if (NiPoint3::DistanceSquared(self->GetPosition(), movementAIComponent->GetCurrentPosition()) < 20 * 20) { + baseCombatAIComponent->Stun(2.0f); + movementAIComponent->SetDestination(baseCombatAIComponent->GetStartPosition()); + } - baseCombatAIComponent->ClearThreat(); + baseCombatAIComponent->ClearThreat(); } diff --git a/dScripts/AmShieldGeneratorQuickbuild.h b/dScripts/AmShieldGeneratorQuickbuild.h index 3a8ab61e..2aef6926 100644 --- a/dScripts/AmShieldGeneratorQuickbuild.h +++ b/dScripts/AmShieldGeneratorQuickbuild.h @@ -4,13 +4,13 @@ class AmShieldGeneratorQuickbuild : public CppScripts::Script { public: - void OnStartup(Entity* self) override; - void OnProximityUpdate(Entity* self, Entity* entering, std::string name, std::string status) override; - void OnDie(Entity* self, Entity* killer) override; - void OnTimerDone(Entity* self, std::string timerName) override; - void OnRebuildComplete(Entity* self, Entity* target) override; + void OnStartup(Entity* self) override; + void OnProximityUpdate(Entity* self, Entity* entering, std::string name, std::string status) override; + void OnDie(Entity* self, Entity* killer) override; + void OnTimerDone(Entity* self, std::string timerName) override; + void OnRebuildComplete(Entity* self, Entity* target) override; - void StartShield(Entity* self); - void BuffPlayers(Entity* self); - void EnemyEnteredShield(Entity* self, Entity* intruder); + void StartShield(Entity* self); + void BuffPlayers(Entity* self); + void EnemyEnteredShield(Entity* self, Entity* intruder); }; diff --git a/dScripts/AmSkeletonEngineer.cpp b/dScripts/AmSkeletonEngineer.cpp index 9ef27d75..a4972729 100644 --- a/dScripts/AmSkeletonEngineer.cpp +++ b/dScripts/AmSkeletonEngineer.cpp @@ -2,26 +2,23 @@ #include "DestroyableComponent.h" #include "SkillComponent.h" -void AmSkeletonEngineer::OnHit(Entity* self, Entity* attacker) -{ - auto* destroyableComponent = self->GetComponent(); - auto* skillComponent = self->GetComponent(); +void AmSkeletonEngineer::OnHit(Entity* self, Entity* attacker) { + auto* destroyableComponent = self->GetComponent(); + auto* skillComponent = self->GetComponent(); - if (destroyableComponent == nullptr || skillComponent == nullptr) - { - return; - } + if (destroyableComponent == nullptr || skillComponent == nullptr) { + return; + } - if (destroyableComponent->GetHealth() < 12 && !self->GetVar(u"injured")) - { - self->SetVar(u"injured", true); + if (destroyableComponent->GetHealth() < 12 && !self->GetVar(u"injured")) { + self->SetVar(u"injured", true); - skillComponent->CalculateBehavior(953, 19864, self->GetObjectID(), true); + skillComponent->CalculateBehavior(953, 19864, self->GetObjectID(), true); - const auto attackerID = attacker->GetObjectID(); + const auto attackerID = attacker->GetObjectID(); - self->AddCallbackTimer(4.5f, [this, self, attackerID] () { - self->Smash(attackerID); - }); - } + self->AddCallbackTimer(4.5f, [this, self, attackerID]() { + self->Smash(attackerID); + }); + } } diff --git a/dScripts/AmSkeletonEngineer.h b/dScripts/AmSkeletonEngineer.h index d4f6f36e..77a14d88 100644 --- a/dScripts/AmSkeletonEngineer.h +++ b/dScripts/AmSkeletonEngineer.h @@ -5,5 +5,5 @@ class AmSkeletonEngineer : public EnemyNjBuff { public: - void OnHit(Entity* self, Entity* attacker) override; + void OnHit(Entity* self, Entity* attacker) override; }; diff --git a/dScripts/AmSkullkinDrill.cpp b/dScripts/AmSkullkinDrill.cpp index d5b7e7e6..321660e2 100644 --- a/dScripts/AmSkullkinDrill.cpp +++ b/dScripts/AmSkullkinDrill.cpp @@ -5,372 +5,319 @@ #include "ProximityMonitorComponent.h" #include "MissionComponent.h" -void AmSkullkinDrill::OnStartup(Entity* self) -{ - self->SetNetworkVar(u"bIsInUse", false); - self->SetVar(u"bActive", true); +void AmSkullkinDrill::OnStartup(Entity* self) { + self->SetNetworkVar(u"bIsInUse", false); + self->SetVar(u"bActive", true); - GameMessages::SendPlayFXEffect(self->GetObjectID(), -1, u"spin", "active"); - - auto* movingPlatformComponent = self->GetComponent(); + GameMessages::SendPlayFXEffect(self->GetObjectID(), -1, u"spin", "active"); - if (movingPlatformComponent == nullptr) - { - return; - } + auto* movingPlatformComponent = self->GetComponent(); - movingPlatformComponent->SetSerialized(true); + if (movingPlatformComponent == nullptr) { + return; + } - movingPlatformComponent->GotoWaypoint(0); + movingPlatformComponent->SetSerialized(true); - auto* standObj = GetStandObj(self); + movingPlatformComponent->GotoWaypoint(0); - if (standObj != nullptr) - { - standObj->SetVar(u"bActive", true); - } + auto* standObj = GetStandObj(self); - self->SetProximityRadius(5, "spin_distance"); + if (standObj != nullptr) { + standObj->SetVar(u"bActive", true); + } + + self->SetProximityRadius(5, "spin_distance"); } -Entity* AmSkullkinDrill::GetStandObj(Entity* self) -{ - const auto& myGroup = self->GetGroups(); +Entity* AmSkullkinDrill::GetStandObj(Entity* self) { + const auto& myGroup = self->GetGroups(); - if (myGroup.empty()) - { - return nullptr; - } + if (myGroup.empty()) { + return nullptr; + } - std::string groupName = "Drill_Stand_"; + std::string groupName = "Drill_Stand_"; - groupName.push_back(myGroup[0][myGroup[0].size() - 1]); + groupName.push_back(myGroup[0][myGroup[0].size() - 1]); - const auto standObjs = EntityManager::Instance()->GetEntitiesInGroup(groupName); + const auto standObjs = EntityManager::Instance()->GetEntitiesInGroup(groupName); - if (standObjs.empty()) - { - return nullptr; - } + if (standObjs.empty()) { + return nullptr; + } - return standObjs[0]; + return standObjs[0]; } -void AmSkullkinDrill::OnSkillEventFired(Entity* self, Entity* caster, const std::string& message) -{ - if (message != "NinjagoSpinEvent" || self->GetNetworkVar(u"bIsInUse")) - { - return; - } +void AmSkullkinDrill::OnSkillEventFired(Entity* self, Entity* caster, const std::string& message) { + if (message != "NinjagoSpinEvent" || self->GetNetworkVar(u"bIsInUse")) { + return; + } - auto* proximityMonitorComponent = self->GetComponent(); + auto* proximityMonitorComponent = self->GetComponent(); - if (proximityMonitorComponent == nullptr || !proximityMonitorComponent->IsInProximity("spin_distance", caster->GetObjectID())) - { - return; - } + if (proximityMonitorComponent == nullptr || !proximityMonitorComponent->IsInProximity("spin_distance", caster->GetObjectID())) { + return; + } - self->SetVar(u"activaterID", caster->GetObjectID()); + self->SetVar(u"activaterID", caster->GetObjectID()); - self->SetNetworkVar(u"bIsInUse", true); + self->SetNetworkVar(u"bIsInUse", true); - TriggerDrill(self); + TriggerDrill(self); } -void AmSkullkinDrill::TriggerDrill(Entity* self) -{ - GameMessages::SendPlayAnimation(self, u"slowdown"); +void AmSkullkinDrill::TriggerDrill(Entity* self) { + GameMessages::SendPlayAnimation(self, u"slowdown"); - self->AddTimer("killDrill", 10.0f); - - auto* standObj = GetStandObj(self); + self->AddTimer("killDrill", 10.0f); - if (standObj != nullptr) - { - standObj->SetVar(u"bActive", false); - } + auto* standObj = GetStandObj(self); - auto* movingPlatformComponent = self->GetComponent(); + if (standObj != nullptr) { + standObj->SetVar(u"bActive", false); + } - if (movingPlatformComponent == nullptr) - { - return; - } + auto* movingPlatformComponent = self->GetComponent(); - movingPlatformComponent->GotoWaypoint(1); + if (movingPlatformComponent == nullptr) { + return; + } + + movingPlatformComponent->GotoWaypoint(1); } -void AmSkullkinDrill::OnWaypointReached(Entity* self, uint32_t waypointIndex) -{ - if (waypointIndex == 1) - { - auto myPos = self->GetPosition(); - auto myRot = self->GetRotation(); +void AmSkullkinDrill::OnWaypointReached(Entity* self, uint32_t waypointIndex) { + if (waypointIndex == 1) { + auto myPos = self->GetPosition(); + auto myRot = self->GetRotation(); - myPos.y -= 21; + myPos.y -= 21; - EntityInfo info = {}; - info.lot = 12346; - info.pos = myPos; - info.rot = myRot; - info.scale = 3; // Needs the scale, otherwise attacks fail - info.spawnerID = self->GetObjectID(); + EntityInfo info = {}; + info.lot = 12346; + info.pos = myPos; + info.rot = myRot; + info.scale = 3; // Needs the scale, otherwise attacks fail + info.spawnerID = self->GetObjectID(); - auto* child = EntityManager::Instance()->CreateEntity(info); + auto* child = EntityManager::Instance()->CreateEntity(info); - EntityManager::Instance()->ConstructEntity(child); + EntityManager::Instance()->ConstructEntity(child); - self->SetVar(u"ChildSmash", child->GetObjectID()); + self->SetVar(u"ChildSmash", child->GetObjectID()); - child->AddDieCallback([this, self] () { - const auto& userID = self->GetVar(u"activaterID"); + child->AddDieCallback([this, self]() { + const auto& userID = self->GetVar(u"activaterID"); - auto* player = EntityManager::Instance()->GetEntity(userID); + auto* player = EntityManager::Instance()->GetEntity(userID); - if (player == nullptr) - { - return; - } + if (player == nullptr) { + return; + } - OnHitOrHealResult(self, player, 1); - }); - } - - OnArrived(self, waypointIndex); + OnHitOrHealResult(self, player, 1); + }); + } + + OnArrived(self, waypointIndex); } -void AmSkullkinDrill::OnUse(Entity* self, Entity* user) -{ - if (self->GetNetworkVar(u"bIsInUse")) - { - return; - } +void AmSkullkinDrill::OnUse(Entity* self, Entity* user) { + if (self->GetNetworkVar(u"bIsInUse")) { + return; + } - self->SetNetworkVar(u"bIsInUse", true); + self->SetNetworkVar(u"bIsInUse", true); - GameMessages::SendPlayFXEffect(user->GetObjectID(), 5499, u"on-anim", "tornado"); - GameMessages::SendPlayFXEffect(user->GetObjectID(), 5502, u"on-anim", "staff"); + GameMessages::SendPlayFXEffect(user->GetObjectID(), 5499, u"on-anim", "tornado"); + GameMessages::SendPlayFXEffect(user->GetObjectID(), 5502, u"on-anim", "staff"); - const auto userID = user->GetObjectID(); + const auto userID = user->GetObjectID(); - self->SetVar(u"userID", userID); - self->SetVar(u"activaterID", userID); + self->SetVar(u"userID", userID); + self->SetVar(u"activaterID", userID); - PlayAnim(self, user, "spinjitzu-staff-windup"); - PlayCinematic(self); + PlayAnim(self, user, "spinjitzu-staff-windup"); + PlayCinematic(self); - FreezePlayer(self, user, true); + FreezePlayer(self, user, true); } -void AmSkullkinDrill::FreezePlayer(Entity* self, Entity* player, bool bFreeze) -{ - eStunState eChangeType = POP; +void AmSkullkinDrill::FreezePlayer(Entity* self, Entity* player, bool bFreeze) { + eStunState eChangeType = POP; - if (bFreeze) - { - if (player->GetIsDead()) - { - return; - } + if (bFreeze) { + if (player->GetIsDead()) { + return; + } - eChangeType = PUSH; - } - else - { - if (player->GetIsDead()) - { - // - } - } - - GameMessages::SendSetStunned(player->GetObjectID(), eChangeType, player->GetSystemAddress(), self->GetObjectID(), - true, false, true, false, true, false, true - ); + eChangeType = PUSH; + } else { + if (player->GetIsDead()) { + // + } + } + + GameMessages::SendSetStunned(player->GetObjectID(), eChangeType, player->GetSystemAddress(), self->GetObjectID(), + true, false, true, false, true, false, true + ); } -void AmSkullkinDrill::OnArrived(Entity* self, uint32_t waypointIndex) -{ - auto* standObj = GetStandObj(self); +void AmSkullkinDrill::OnArrived(Entity* self, uint32_t waypointIndex) { + auto* standObj = GetStandObj(self); - if (waypointIndex == 1) - { - GameMessages::SendPlayAnimation(self, u"no-spin"); - GameMessages::SendStopFXEffect(self, true, "active"); - GameMessages::SendPlayFXEffect(self->GetObjectID(), -1, u"indicator", "indicator"); + if (waypointIndex == 1) { + GameMessages::SendPlayAnimation(self, u"no-spin"); + GameMessages::SendStopFXEffect(self, true, "active"); + GameMessages::SendPlayFXEffect(self->GetObjectID(), -1, u"indicator", "indicator"); - self->SetVar(u"bActive", false); - - const auto playerID = self->GetVar(u"userID"); + self->SetVar(u"bActive", false); - auto* player = EntityManager::Instance()->GetEntity(playerID); + const auto playerID = self->GetVar(u"userID"); - if (player != nullptr) - { - PlayAnim(self, player, "spinjitzu-staff-end"); - } + auto* player = EntityManager::Instance()->GetEntity(playerID); - if (standObj != nullptr) - { - standObj->SetVar(u"bActive", false); - } + if (player != nullptr) { + PlayAnim(self, player, "spinjitzu-staff-end"); + } - return; - } - else - { - GameMessages::SendPlayAnimation(self, u"idle"); - GameMessages::SendPlayFXEffect(self->GetObjectID(), -1, u"spin", "active"); - GameMessages::SendStopFXEffect(self, true, "indicator"); - } + if (standObj != nullptr) { + standObj->SetVar(u"bActive", false); + } + + return; + } else { + GameMessages::SendPlayAnimation(self, u"idle"); + GameMessages::SendPlayFXEffect(self->GetObjectID(), -1, u"spin", "active"); + GameMessages::SendStopFXEffect(self, true, "indicator"); + } } -void AmSkullkinDrill::PlayCinematic(Entity* self) -{ - auto* player = EntityManager::Instance()->GetEntity(self->GetVar(u"userID")); +void AmSkullkinDrill::PlayCinematic(Entity* self) { + auto* player = EntityManager::Instance()->GetEntity(self->GetVar(u"userID")); - if (player == nullptr) - { - return; - } + if (player == nullptr) { + return; + } - const auto& cine = self->GetVar(u"cinematic"); + const auto& cine = self->GetVar(u"cinematic"); - if (cine.empty()) - { - return; - } + if (cine.empty()) { + return; + } - GameMessages::SendPlayCinematic(player->GetObjectID(), cine, player->GetSystemAddress()); + GameMessages::SendPlayCinematic(player->GetObjectID(), cine, player->GetSystemAddress()); } -void AmSkullkinDrill::PlayAnim(Entity* self, Entity* player, const std::string& animName) -{ - const auto animTime = animName == "spinjitzu-staff-end" ? 0.5f : 1.0f; +void AmSkullkinDrill::PlayAnim(Entity* self, Entity* player, const std::string& animName) { + const auto animTime = animName == "spinjitzu-staff-end" ? 0.5f : 1.0f; - GameMessages::SendPlayAnimation(player, GeneralUtils::ASCIIToUTF16(animName)); + GameMessages::SendPlayAnimation(player, GeneralUtils::ASCIIToUTF16(animName)); - self->AddTimer("AnimDone_" + animName, animTime); + self->AddTimer("AnimDone_" + animName, animTime); } -void AmSkullkinDrill::OnHitOrHealResult(Entity* self, Entity* attacker, int32_t damage) -{ - auto* destroyableComponent = self->GetComponent(); +void AmSkullkinDrill::OnHitOrHealResult(Entity* self, Entity* attacker, int32_t damage) { + auto* destroyableComponent = self->GetComponent(); - if (destroyableComponent == nullptr || !attacker->IsPlayer()) - { - return; - } + if (destroyableComponent == nullptr || !attacker->IsPlayer()) { + return; + } - if (self->GetVar(u"bActive")) - { - return; - } + if (self->GetVar(u"bActive")) { + return; + } - const auto activaterID = self->GetVar(u"activaterID"); + const auto activaterID = self->GetVar(u"activaterID"); - auto* activator = EntityManager::Instance()->GetEntity(activaterID); + auto* activator = EntityManager::Instance()->GetEntity(activaterID); - // TODO: Missions - if (activator != nullptr) - { - auto* missionComponent = activator->GetComponent(); + // TODO: Missions + if (activator != nullptr) { + auto* missionComponent = activator->GetComponent(); - if (missionComponent != nullptr) - { - for (const auto missionID : m_MissionsToUpdate) - { - missionComponent->ForceProgressValue(missionID, 1, self->GetLOT()); - } - } - } + if (missionComponent != nullptr) { + for (const auto missionID : m_MissionsToUpdate) { + missionComponent->ForceProgressValue(missionID, 1, self->GetLOT()); + } + } + } - self->Smash(attacker->GetObjectID(), SILENT); + self->Smash(attacker->GetObjectID(), SILENT); - self->CancelAllTimers(); + self->CancelAllTimers(); - auto* standObj = GetStandObj(self); + auto* standObj = GetStandObj(self); - if (standObj != nullptr) - { - GameMessages::SendPlayFXEffect(standObj->GetObjectID(), 4946, u"explode", "explode"); - } + if (standObj != nullptr) { + GameMessages::SendPlayFXEffect(standObj->GetObjectID(), 4946, u"explode", "explode"); + } } -void AmSkullkinDrill::OnTimerDone(Entity* self, std::string timerName) -{ - if (timerName == "killDrill") - { - const auto childID = self->GetVar(u"ChildSmash"); +void AmSkullkinDrill::OnTimerDone(Entity* self, std::string timerName) { + if (timerName == "killDrill") { + const auto childID = self->GetVar(u"ChildSmash"); - auto* child = EntityManager::Instance()->GetEntity(childID); + auto* child = EntityManager::Instance()->GetEntity(childID); - if (child != nullptr) - { - child->Smash(self->GetObjectID(), SILENT); - } + if (child != nullptr) { + child->Smash(self->GetObjectID(), SILENT); + } - self->SetNetworkVar(u"bIsInUse", false); - self->SetVar(u"bActive", true); - self->SetVar(u"activaterID", LWOOBJID_EMPTY); + self->SetNetworkVar(u"bIsInUse", false); + self->SetVar(u"bActive", true); + self->SetVar(u"activaterID", LWOOBJID_EMPTY); - auto* standObj = GetStandObj(self); + auto* standObj = GetStandObj(self); - if (standObj != nullptr) - { - standObj->SetVar(u"bActive", true); - } + if (standObj != nullptr) { + standObj->SetVar(u"bActive", true); + } - auto* movingPlatformComponent = self->GetComponent(); + auto* movingPlatformComponent = self->GetComponent(); - if (movingPlatformComponent == nullptr) - { - return; - } + if (movingPlatformComponent == nullptr) { + return; + } - movingPlatformComponent->GotoWaypoint(0); + movingPlatformComponent->GotoWaypoint(0); - return; - } + return; + } - const auto& data = GeneralUtils::SplitString(timerName, '_'); + const auto& data = GeneralUtils::SplitString(timerName, '_'); - if (data.empty()) - { - return; - } + if (data.empty()) { + return; + } - if (data[0] == "AnimDone") - { - const auto& animName = data[1]; + if (data[0] == "AnimDone") { + const auto& animName = data[1]; - const auto playerID = self->GetVar(u"userID"); + const auto playerID = self->GetVar(u"userID"); - auto* player = EntityManager::Instance()->GetEntity(playerID); + auto* player = EntityManager::Instance()->GetEntity(playerID); - if (player == nullptr) - { - return; - } + if (player == nullptr) { + return; + } - if (animName == "spinjitzu-staff-windup") - { - TriggerDrill(self); + if (animName == "spinjitzu-staff-windup") { + TriggerDrill(self); - GameMessages::SendPlayAnimation(player, u"spinjitzu-staff-loop"); - } - else if (animName == "spinjitzu-staff-end") - { - FreezePlayer(self, player, false); + GameMessages::SendPlayAnimation(player, u"spinjitzu-staff-loop"); + } else if (animName == "spinjitzu-staff-end") { + FreezePlayer(self, player, false); - self->SetVar(u"userID", LWOOBJID_EMPTY); + self->SetVar(u"userID", LWOOBJID_EMPTY); - GameMessages::SendStopFXEffect(player, true, "tornado"); - GameMessages::SendStopFXEffect(player, true, "staff"); - } + GameMessages::SendStopFXEffect(player, true, "tornado"); + GameMessages::SendStopFXEffect(player, true, "staff"); + } - } - else if (data[0] == "TryUnFreezeAgain") - { + } else if (data[0] == "TryUnFreezeAgain") { - } + } } diff --git a/dScripts/AmSkullkinDrill.h b/dScripts/AmSkullkinDrill.h index a996cefd..5e6c3179 100644 --- a/dScripts/AmSkullkinDrill.h +++ b/dScripts/AmSkullkinDrill.h @@ -4,30 +4,30 @@ class AmSkullkinDrill : public CppScripts::Script { public: - void OnStartup(Entity* self) override; + void OnStartup(Entity* self) override; - Entity* GetStandObj(Entity* self); + Entity* GetStandObj(Entity* self); - void OnSkillEventFired(Entity* self, Entity* caster, const std::string& message) override; + void OnSkillEventFired(Entity* self, Entity* caster, const std::string& message) override; - void TriggerDrill(Entity* self); + void TriggerDrill(Entity* self); - void OnWaypointReached(Entity* self, uint32_t waypointIndex) override; + void OnWaypointReached(Entity* self, uint32_t waypointIndex) override; - void OnUse(Entity* self, Entity* user) override; + void OnUse(Entity* self, Entity* user) override; - void FreezePlayer(Entity* self, Entity* player, bool bFreeze); + void FreezePlayer(Entity* self, Entity* player, bool bFreeze); - void OnArrived(Entity* self, uint32_t waypointIndex); + void OnArrived(Entity* self, uint32_t waypointIndex); - void PlayCinematic(Entity* self); + void PlayCinematic(Entity* self); - void PlayAnim(Entity* self, Entity* player, const std::string& animName); + void PlayAnim(Entity* self, Entity* player, const std::string& animName); - void OnHitOrHealResult(Entity* self, Entity* attacker, int32_t damage) override; + void OnHitOrHealResult(Entity* self, Entity* attacker, int32_t damage) override; - void OnTimerDone(Entity* self, std::string timerName) override; + void OnTimerDone(Entity* self, std::string timerName) override; private: - std::vector m_MissionsToUpdate = {972, 1305, 1308}; + std::vector m_MissionsToUpdate = { 972, 1305, 1308 }; }; diff --git a/dScripts/AmSkullkinDrillStand.cpp b/dScripts/AmSkullkinDrillStand.cpp index ddae2f60..628d616a 100644 --- a/dScripts/AmSkullkinDrillStand.cpp +++ b/dScripts/AmSkullkinDrillStand.cpp @@ -2,39 +2,34 @@ #include "GameMessages.h" #include "dpEntity.h" -void AmSkullkinDrillStand::OnStartup(Entity* self) -{ - self->SetVar(u"bActive", true); +void AmSkullkinDrillStand::OnStartup(Entity* self) { + self->SetVar(u"bActive", true); - self->SetProximityRadius(new dpEntity(self->GetObjectID(), {6, 14, 6}), "knockback"); + self->SetProximityRadius(new dpEntity(self->GetObjectID(), { 6, 14, 6 }), "knockback"); } -void AmSkullkinDrillStand::OnNotifyObject(Entity *self, Entity *sender, const std::string& name, int32_t param1, int32_t param2) -{ - +void AmSkullkinDrillStand::OnNotifyObject(Entity* self, Entity* sender, const std::string& name, int32_t param1, int32_t param2) { + } -void AmSkullkinDrillStand::OnProximityUpdate(Entity* self, Entity* entering, std::string name, std::string status) -{ - if (!self->GetVar(u"bActive")) - { - return; - } +void AmSkullkinDrillStand::OnProximityUpdate(Entity* self, Entity* entering, std::string name, std::string status) { + if (!self->GetVar(u"bActive")) { + return; + } - if (!entering->IsPlayer() || status != "ENTER" || name != "knockback") - { - return; - } + if (!entering->IsPlayer() || status != "ENTER" || name != "knockback") { + return; + } - auto myPos = self->GetPosition(); + auto myPos = self->GetPosition(); - auto objPos = entering->GetPosition(); + auto objPos = entering->GetPosition(); - NiPoint3 newVec = {(objPos.x - myPos.x) * 4.5f, 15, (objPos.z - myPos.z) * 4.5f}; + NiPoint3 newVec = { (objPos.x - myPos.x) * 4.5f, 15, (objPos.z - myPos.z) * 4.5f }; - GameMessages::SendKnockback(entering->GetObjectID(), self->GetObjectID(), self->GetObjectID(), 0, newVec); + GameMessages::SendKnockback(entering->GetObjectID(), self->GetObjectID(), self->GetObjectID(), 0, newVec); - GameMessages::SendPlayFXEffect(entering->GetObjectID(), 1378, u"create", "pushBack"); - - GameMessages::SendPlayAnimation(entering, u"knockback-recovery"); + GameMessages::SendPlayFXEffect(entering->GetObjectID(), 1378, u"create", "pushBack"); + + GameMessages::SendPlayAnimation(entering, u"knockback-recovery"); } diff --git a/dScripts/AmSkullkinDrillStand.h b/dScripts/AmSkullkinDrillStand.h index 3879b3b4..673dee05 100644 --- a/dScripts/AmSkullkinDrillStand.h +++ b/dScripts/AmSkullkinDrillStand.h @@ -4,9 +4,9 @@ class AmSkullkinDrillStand : public CppScripts::Script { public: - void OnStartup(Entity* self) override; + void OnStartup(Entity* self) override; - void OnNotifyObject(Entity *self, Entity *sender, const std::string& name, int32_t param1 = 0, int32_t param2 = 0) override; + void OnNotifyObject(Entity* self, Entity* sender, const std::string& name, int32_t param1 = 0, int32_t param2 = 0) override; - void OnProximityUpdate(Entity* self, Entity* entering, std::string name, std::string status) override; + void OnProximityUpdate(Entity* self, Entity* entering, std::string name, std::string status) override; }; diff --git a/dScripts/AmSkullkinTower.cpp b/dScripts/AmSkullkinTower.cpp index 1b9e8c6d..180bbdac 100644 --- a/dScripts/AmSkullkinTower.cpp +++ b/dScripts/AmSkullkinTower.cpp @@ -5,278 +5,239 @@ #include "GameMessages.h" #include "MissionComponent.h" -void AmSkullkinTower::OnStartup(Entity* self) -{ - self->SetProximityRadius(20, "Tower"); +void AmSkullkinTower::OnStartup(Entity* self) { + self->SetProximityRadius(20, "Tower"); - // onPhysicsComponentReady + // onPhysicsComponentReady - auto* movingPlatformComponent = self->GetComponent(); + auto* movingPlatformComponent = self->GetComponent(); - if (movingPlatformComponent != nullptr) - { - movingPlatformComponent->StopPathing(); - } + if (movingPlatformComponent != nullptr) { + movingPlatformComponent->StopPathing(); + } - SpawnLegs(self, "Left"); - SpawnLegs(self, "Right"); - SpawnLegs(self, "Rear"); + SpawnLegs(self, "Left"); + SpawnLegs(self, "Right"); + SpawnLegs(self, "Rear"); } -void AmSkullkinTower::SpawnLegs(Entity* self, const std::string& loc) -{ - auto pos = self->GetPosition(); - auto rot = self->GetRotation(); - pos.y += self->GetVarAs(u"vert_offset"); +void AmSkullkinTower::SpawnLegs(Entity* self, const std::string& loc) { + auto pos = self->GetPosition(); + auto rot = self->GetRotation(); + pos.y += self->GetVarAs(u"vert_offset"); - auto newRot = rot; - auto offset = self->GetVarAs(u"hort_offset"); + auto newRot = rot; + auto offset = self->GetVarAs(u"hort_offset"); - auto legLOT = self->GetVar(u"legLOT"); + auto legLOT = self->GetVar(u"legLOT"); - if (legLOT == 0) - { - return; - } + if (legLOT == 0) { + return; + } - std::vector config = { new LDFData(u"Leg", loc) }; + std::vector config = { new LDFData(u"Leg", loc) }; - EntityInfo info {}; - info.lot = legLOT; - info.spawnerID = self->GetObjectID(); - info.settings = config; - info.rot = newRot; + EntityInfo info{}; + info.lot = legLOT; + info.spawnerID = self->GetObjectID(); + info.settings = config; + info.rot = newRot; - if (loc == "Right") - { - const auto dir = rot.GetForwardVector(); - pos.x += dir.x * offset; - pos.z += dir.z * offset; - info.pos = pos; - } - else if (loc == "Rear") - { - const auto dir = rot.GetRightVector(); - pos.x += dir.x * offset; - pos.z += dir.z * offset; - info.pos = pos; - } - else if (loc == "Left") - { - const auto dir = rot.GetForwardVector() * -1; - pos.x += dir.x * offset; - pos.z += dir.z * offset; - info.pos = pos; - } + if (loc == "Right") { + const auto dir = rot.GetForwardVector(); + pos.x += dir.x * offset; + pos.z += dir.z * offset; + info.pos = pos; + } else if (loc == "Rear") { + const auto dir = rot.GetRightVector(); + pos.x += dir.x * offset; + pos.z += dir.z * offset; + info.pos = pos; + } else if (loc == "Left") { + const auto dir = rot.GetForwardVector() * -1; + pos.x += dir.x * offset; + pos.z += dir.z * offset; + info.pos = pos; + } - info.rot = NiQuaternion::LookAt(info.pos, self->GetPosition()); + info.rot = NiQuaternion::LookAt(info.pos, self->GetPosition()); - auto* entity = EntityManager::Instance()->CreateEntity(info); + auto* entity = EntityManager::Instance()->CreateEntity(info); - EntityManager::Instance()->ConstructEntity(entity); + EntityManager::Instance()->ConstructEntity(entity); - OnChildLoaded(self, entity); + OnChildLoaded(self, entity); } -void AmSkullkinTower::OnChildLoaded(Entity* self, Entity* child) -{ - auto legTable = self->GetVar>(u"legTable"); +void AmSkullkinTower::OnChildLoaded(Entity* self, Entity* child) { + auto legTable = self->GetVar>(u"legTable"); - legTable.push_back(child->GetObjectID()); + legTable.push_back(child->GetObjectID()); - self->SetVar(u"legTable", legTable); + self->SetVar(u"legTable", legTable); - const auto selfID = self->GetObjectID(); + const auto selfID = self->GetObjectID(); - child->AddDieCallback([this, selfID, child] () { - auto* self = EntityManager::Instance()->GetEntity(selfID); - auto* destroyableComponent = child->GetComponent(); + child->AddDieCallback([this, selfID, child]() { + auto* self = EntityManager::Instance()->GetEntity(selfID); + auto* destroyableComponent = child->GetComponent(); - if (destroyableComponent == nullptr || self == nullptr) - { - return; - } + if (destroyableComponent == nullptr || self == nullptr) { + return; + } - NotifyDie(self, child, destroyableComponent->GetKiller()); - }); + NotifyDie(self, child, destroyableComponent->GetKiller()); + }); } -void AmSkullkinTower::NotifyDie(Entity* self, Entity* other, Entity* killer) -{ - auto players = self->GetVar>(u"Players"); +void AmSkullkinTower::NotifyDie(Entity* self, Entity* other, Entity* killer) { + auto players = self->GetVar>(u"Players"); - const auto& iter = std::find(players.begin(), players.end(), killer->GetObjectID()); + const auto& iter = std::find(players.begin(), players.end(), killer->GetObjectID()); - if (iter == players.end()) - { - players.push_back(killer->GetObjectID()); - } + if (iter == players.end()) { + players.push_back(killer->GetObjectID()); + } - self->SetVar(u"Players", players); + self->SetVar(u"Players", players); - OnChildRemoved(self, other); + OnChildRemoved(self, other); } -void AmSkullkinTower::OnChildRemoved(Entity* self, Entity* child) -{ - auto legTable = self->GetVar>(u"legTable"); +void AmSkullkinTower::OnChildRemoved(Entity* self, Entity* child) { + auto legTable = self->GetVar>(u"legTable"); - const auto& iter = std::find(legTable.begin(), legTable.end(), child->GetObjectID()); + const auto& iter = std::find(legTable.begin(), legTable.end(), child->GetObjectID()); - if (iter != legTable.end()) - { - legTable.erase(iter); - } + if (iter != legTable.end()) { + legTable.erase(iter); + } - self->SetVar(u"legTable", legTable); + self->SetVar(u"legTable", legTable); - if (legTable.size() == 2) - { - GameMessages::SendPlayAnimation(self, u"wobble-1"); - } - else if (legTable.size() == 1) - { - GameMessages::SendPlayAnimation(self, u"wobble-2"); - } - else if (legTable.empty()) - { - const auto animTime = 2.5f; + if (legTable.size() == 2) { + GameMessages::SendPlayAnimation(self, u"wobble-1"); + } else if (legTable.size() == 1) { + GameMessages::SendPlayAnimation(self, u"wobble-2"); + } else if (legTable.empty()) { + const auto animTime = 2.5f; - GameMessages::SendPlayAnimation(self, u"fall"); + GameMessages::SendPlayAnimation(self, u"fall"); - self->AddTimer("spawnGuys", animTime - 0.2f); + self->AddTimer("spawnGuys", animTime - 0.2f); - self->CancelTimer("RespawnLeg"); - self->CancelTimer("RespawnLeg"); - self->CancelTimer("RespawnLeg"); + self->CancelTimer("RespawnLeg"); + self->CancelTimer("RespawnLeg"); + self->CancelTimer("RespawnLeg"); - std::vector missionIDs; + std::vector missionIDs; - auto missionsString = self->GetVar(u"missions"); + auto missionsString = self->GetVar(u"missions"); - if (!missionsString.empty()) - { - // Split the missions string by '_' - const auto missions = GeneralUtils::SplitString( - GeneralUtils::UTF16ToWTF8(missionsString), - '_' - ); + if (!missionsString.empty()) { + // Split the missions string by '_' + const auto missions = GeneralUtils::SplitString( + GeneralUtils::UTF16ToWTF8(missionsString), + '_' + ); - for (const auto& mission : missions) - { - int32_t missionID = 0; + for (const auto& mission : missions) { + int32_t missionID = 0; - if (!GeneralUtils::TryParse(mission, missionID)) - { - continue; - } + if (!GeneralUtils::TryParse(mission, missionID)) { + continue; + } - missionIDs.push_back(missionID); - } - } + missionIDs.push_back(missionID); + } + } - const auto& players = self->GetVar>(u"Players"); + const auto& players = self->GetVar>(u"Players"); - for (const auto& playerID : players) - { - auto* player = EntityManager::Instance()->GetEntity(playerID); - - if (player == nullptr) - { - continue; - } + for (const auto& playerID : players) { + auto* player = EntityManager::Instance()->GetEntity(playerID); - auto* missionComponent = player->GetComponent(); + if (player == nullptr) { + continue; + } - if (missionComponent == nullptr) - { - continue; - } + auto* missionComponent = player->GetComponent(); - for (const auto missionID : missionIDs) - { - missionComponent->ForceProgressValue(missionID, 1, self->GetLOT()); - } + if (missionComponent == nullptr) { + continue; + } - //missionComponent->ForceProgressValue(1305, 1, self->GetLOT()); - } - } + for (const auto missionID : missionIDs) { + missionComponent->ForceProgressValue(missionID, 1, self->GetLOT()); + } - auto deadLegs = self->GetVar>(u"DeadLegs"); + //missionComponent->ForceProgressValue(1305, 1, self->GetLOT()); + } + } - const auto& leg = child->GetVar(u"Leg"); + auto deadLegs = self->GetVar>(u"DeadLegs"); - const auto& legIter = std::find(deadLegs.begin(), deadLegs.end(), leg); + const auto& leg = child->GetVar(u"Leg"); - if (legIter == deadLegs.end()) - { - deadLegs.push_back(leg); - } + const auto& legIter = std::find(deadLegs.begin(), deadLegs.end(), leg); - self->SetVar(u"DeadLegs", deadLegs); + if (legIter == deadLegs.end()) { + deadLegs.push_back(leg); + } - self->AddTimer("RespawnLeg", 20); + self->SetVar(u"DeadLegs", deadLegs); + + self->AddTimer("RespawnLeg", 20); } -void AmSkullkinTower::OnProximityUpdate(Entity* self, Entity* entering, std::string name, std::string status) -{ - if (status != "LEAVE") - { - return; - } +void AmSkullkinTower::OnProximityUpdate(Entity* self, Entity* entering, std::string name, std::string status) { + if (status != "LEAVE") { + return; + } - auto players = self->GetVar>(u"Players"); + auto players = self->GetVar>(u"Players"); - const auto& iter = std::find(players.begin(), players.end(), entering->GetObjectID()); + const auto& iter = std::find(players.begin(), players.end(), entering->GetObjectID()); - if (iter != players.end()) - { - players.erase(iter); - } + if (iter != players.end()) { + players.erase(iter); + } - self->SetVar(u"Players", players); + self->SetVar(u"Players", players); } -void AmSkullkinTower::OnTimerDone(Entity* self, std::string timerName) -{ - if (timerName == "RespawnLeg") - { - auto deadLegs = self->GetVar>(u"DeadLegs"); +void AmSkullkinTower::OnTimerDone(Entity* self, std::string timerName) { + if (timerName == "RespawnLeg") { + auto deadLegs = self->GetVar>(u"DeadLegs"); - if (deadLegs.empty()) - { - return; - } + if (deadLegs.empty()) { + return; + } - SpawnLegs(self, deadLegs[0]); + SpawnLegs(self, deadLegs[0]); - deadLegs.erase(deadLegs.begin()); + deadLegs.erase(deadLegs.begin()); - self->SetVar>(u"DeadLegs", deadLegs); - } - else if (timerName == "spawnGuys") - { - EntityInfo info {}; - info.lot = self->GetVar(u"enemyToSpawn"); - auto pos = self->GetPosition(); - pos.y += 7; - info.pos = pos; - info.rot = self->GetRotation(); - info.spawnerID = self->GetObjectID(); - - for (size_t i = 0; i < 2; i++) - { - info.pos.x += i * 2; // Just to set the apart a bit + self->SetVar>(u"DeadLegs", deadLegs); + } else if (timerName == "spawnGuys") { + EntityInfo info{}; + info.lot = self->GetVar(u"enemyToSpawn"); + auto pos = self->GetPosition(); + pos.y += 7; + info.pos = pos; + info.rot = self->GetRotation(); + info.spawnerID = self->GetObjectID(); - auto* entity = EntityManager::Instance()->CreateEntity(info); + for (size_t i = 0; i < 2; i++) { + info.pos.x += i * 2; // Just to set the apart a bit - EntityManager::Instance()->ConstructEntity(entity); - } + auto* entity = EntityManager::Instance()->CreateEntity(info); - self->AddTimer("killTower", 0.7f); - } - else if (timerName == "killTower") - { - self->Smash(self->GetObjectID()); - } + EntityManager::Instance()->ConstructEntity(entity); + } + + self->AddTimer("killTower", 0.7f); + } else if (timerName == "killTower") { + self->Smash(self->GetObjectID()); + } } diff --git a/dScripts/AmSkullkinTower.h b/dScripts/AmSkullkinTower.h index c7d6a732..495641de 100644 --- a/dScripts/AmSkullkinTower.h +++ b/dScripts/AmSkullkinTower.h @@ -4,17 +4,17 @@ class AmSkullkinTower : public CppScripts::Script { public: - void OnStartup(Entity* self) override; + void OnStartup(Entity* self) override; - void SpawnLegs(Entity* self, const std::string& loc); + void SpawnLegs(Entity* self, const std::string& loc); - void OnChildLoaded(Entity* self, Entity* child); + void OnChildLoaded(Entity* self, Entity* child); - void NotifyDie(Entity* self, Entity* other, Entity* killer); + void NotifyDie(Entity* self, Entity* other, Entity* killer); - void OnChildRemoved(Entity* self, Entity* child); + void OnChildRemoved(Entity* self, Entity* child); - void OnProximityUpdate(Entity* self, Entity* entering, std::string name, std::string status) override; + void OnProximityUpdate(Entity* self, Entity* entering, std::string name, std::string status) override; void OnTimerDone(Entity* self, std::string timerName) override; }; diff --git a/dScripts/AmTeapotServer.cpp b/dScripts/AmTeapotServer.cpp index 17b95eeb..32abafd6 100644 --- a/dScripts/AmTeapotServer.cpp +++ b/dScripts/AmTeapotServer.cpp @@ -7,7 +7,7 @@ void AmTeapotServer::OnUse(Entity* self, Entity* user) { auto* inventoryComponent = user->GetComponent(); if (!inventoryComponent) return; - if (inventoryComponent->GetLotCount(BLUE_FLOWER_LEAVES) >= 10){ + if (inventoryComponent->GetLotCount(BLUE_FLOWER_LEAVES) >= 10) { inventoryComponent->RemoveItem(BLUE_FLOWER_LEAVES, 10); inventoryComponent->AddItem(WU_S_IMAGINATION_TEA, 1); } diff --git a/dScripts/AmTeapotServer.h b/dScripts/AmTeapotServer.h index 19cb5639..3ba2e331 100644 --- a/dScripts/AmTeapotServer.h +++ b/dScripts/AmTeapotServer.h @@ -2,9 +2,9 @@ #include "CppScripts.h" class AmTeapotServer : public CppScripts::Script { - public: - void OnUse(Entity* self, Entity* user) override; - private: - LOT BLUE_FLOWER_LEAVES = 12317; - LOT WU_S_IMAGINATION_TEA = 12109; +public: + void OnUse(Entity* self, Entity* user) override; +private: + LOT BLUE_FLOWER_LEAVES = 12317; + LOT WU_S_IMAGINATION_TEA = 12109; }; diff --git a/dScripts/AmTemplateSkillVolume.cpp b/dScripts/AmTemplateSkillVolume.cpp index a0d2a95e..3acc9063 100644 --- a/dScripts/AmTemplateSkillVolume.cpp +++ b/dScripts/AmTemplateSkillVolume.cpp @@ -1,27 +1,23 @@ #include "AmTemplateSkillVolume.h" #include "MissionComponent.h" -void AmTemplateSkillVolume::OnSkillEventFired(Entity* self, Entity* caster, const std::string& message) -{ - if (message != "NinjagoSpinAttackEvent") - { - return; - } +void AmTemplateSkillVolume::OnSkillEventFired(Entity* self, Entity* caster, const std::string& message) { + if (message != "NinjagoSpinAttackEvent") { + return; + } - auto* missionComponent = caster->GetComponent(); + auto* missionComponent = caster->GetComponent(); - const auto missionIDsVariable = GeneralUtils::UTF16ToWTF8(self->GetVar(u"missions")); - const auto missionIDs = GeneralUtils::SplitString(missionIDsVariable, '_'); + const auto missionIDsVariable = GeneralUtils::UTF16ToWTF8(self->GetVar(u"missions")); + const auto missionIDs = GeneralUtils::SplitString(missionIDsVariable, '_'); - for (const auto& missionIDStr : missionIDs) - { - int32_t missionID = 0; + for (const auto& missionIDStr : missionIDs) { + int32_t missionID = 0; - if (!GeneralUtils::TryParse(missionIDStr, missionID)) - { - continue; - } + if (!GeneralUtils::TryParse(missionIDStr, missionID)) { + continue; + } - missionComponent->ForceProgressTaskType(missionID, 1, 1, false); - } + missionComponent->ForceProgressTaskType(missionID, 1, 1, false); + } } diff --git a/dScripts/AmTemplateSkillVolume.h b/dScripts/AmTemplateSkillVolume.h index ab912f4d..f4002213 100644 --- a/dScripts/AmTemplateSkillVolume.h +++ b/dScripts/AmTemplateSkillVolume.h @@ -4,5 +4,5 @@ class AmTemplateSkillVolume : public CppScripts::Script { public: - void OnSkillEventFired(Entity* self, Entity* caster, const std::string& message) override; + void OnSkillEventFired(Entity* self, Entity* caster, const std::string& message) override; }; diff --git a/dScripts/AnvilOfArmor.cpp b/dScripts/AnvilOfArmor.cpp index f3712ff2..3704cb00 100644 --- a/dScripts/AnvilOfArmor.cpp +++ b/dScripts/AnvilOfArmor.cpp @@ -1,13 +1,13 @@ #include "AnvilOfArmor.h" -void AnvilOfArmor::OnStartup(Entity *self) { - self->SetVar(u"numCycles", 8); - self->SetVar(u"secPerCycle", 25.0f); - self->SetVar(u"delayToFirstCycle", 1.5f); - self->SetVar(u"deathDelay", 25.0f); - self->SetVar(u"numberOfPowerups", 4); - self->SetVar(u"lootLOT", 6431); +void AnvilOfArmor::OnStartup(Entity* self) { + self->SetVar(u"numCycles", 8); + self->SetVar(u"secPerCycle", 25.0f); + self->SetVar(u"delayToFirstCycle", 1.5f); + self->SetVar(u"deathDelay", 25.0f); + self->SetVar(u"numberOfPowerups", 4); + self->SetVar(u"lootLOT", 6431); - // Initiate the actual script - OnTemplateStartup(self); + // Initiate the actual script + OnTemplateStartup(self); } diff --git a/dScripts/AnvilOfArmor.h b/dScripts/AnvilOfArmor.h index 64c95216..2ff568aa 100644 --- a/dScripts/AnvilOfArmor.h +++ b/dScripts/AnvilOfArmor.h @@ -2,5 +2,5 @@ #include "ScriptedPowerupSpawner.h" class AnvilOfArmor : public ScriptedPowerupSpawner { - void OnStartup(Entity* self) override; + void OnStartup(Entity* self) override; }; diff --git a/dScripts/BankInteractServer.cpp b/dScripts/BankInteractServer.cpp index dc119056..db5ebb98 100644 --- a/dScripts/BankInteractServer.cpp +++ b/dScripts/BankInteractServer.cpp @@ -1,26 +1,23 @@ #include "BankInteractServer.h" #include "GameMessages.h" -void BankInteractServer::OnUse(Entity* self, Entity* user) -{ - AMFArrayValue args; - AMFStringValue* bank = new AMFStringValue(); - bank->SetStringValue("bank"); - args.InsertValue("state", bank); +void BankInteractServer::OnUse(Entity* self, Entity* user) { + AMFArrayValue args; + AMFStringValue* bank = new AMFStringValue(); + bank->SetStringValue("bank"); + args.InsertValue("state", bank); - GameMessages::SendUIMessageServerToSingleClient(user, user->GetSystemAddress(), "pushGameState", &args); + GameMessages::SendUIMessageServerToSingleClient(user, user->GetSystemAddress(), "pushGameState", &args); } -void BankInteractServer::OnFireEventServerSide(Entity *self, Entity *sender, std::string args, int32_t param1, - int32_t param2, int32_t param3) -{ - if (args == "ToggleBank") - { - AMFArrayValue args; +void BankInteractServer::OnFireEventServerSide(Entity* self, Entity* sender, std::string args, int32_t param1, + int32_t param2, int32_t param3) { + if (args == "ToggleBank") { + AMFArrayValue args; args.InsertValue("visible", new AMFFalseValue()); - GameMessages::SendUIMessageServerToSingleClient(sender, sender->GetSystemAddress(), "ToggleBank", &args); + GameMessages::SendUIMessageServerToSingleClient(sender, sender->GetSystemAddress(), "ToggleBank", &args); - GameMessages::SendNotifyClientObject(self->GetObjectID(), u"CloseBank", 0, 0, LWOOBJID_EMPTY, "", sender->GetSystemAddress()); - } + GameMessages::SendNotifyClientObject(self->GetObjectID(), u"CloseBank", 0, 0, LWOOBJID_EMPTY, "", sender->GetSystemAddress()); + } } diff --git a/dScripts/BankInteractServer.h b/dScripts/BankInteractServer.h index 45a40fe0..3fe4d25c 100644 --- a/dScripts/BankInteractServer.h +++ b/dScripts/BankInteractServer.h @@ -4,7 +4,7 @@ class BankInteractServer : public CppScripts::Script { public: - void OnUse(Entity* self, Entity* user) override; - void OnFireEventServerSide(Entity *self, Entity *sender, std::string args, int32_t param1, int32_t param2, - int32_t param3) override; + void OnUse(Entity* self, Entity* user) override; + void OnFireEventServerSide(Entity* self, Entity* sender, std::string args, int32_t param1, int32_t param2, + int32_t param3) override; }; diff --git a/dScripts/BaseConsoleTeleportServer.cpp b/dScripts/BaseConsoleTeleportServer.cpp index 6475e025..a8538de5 100644 --- a/dScripts/BaseConsoleTeleportServer.cpp +++ b/dScripts/BaseConsoleTeleportServer.cpp @@ -2,120 +2,101 @@ #include "GameMessages.h" #include "Player.h" -void BaseConsoleTeleportServer::BaseOnUse(Entity* self, Entity* user) -{ - auto* player = user; +void BaseConsoleTeleportServer::BaseOnUse(Entity* self, Entity* user) { + auto* player = user; - const auto& teleportLocString = self->GetVar(u"teleportString"); + const auto& teleportLocString = self->GetVar(u"teleportString"); - GameMessages::SendDisplayMessageBox(player->GetObjectID(), true, self->GetObjectID(), u"TransferBox", 0, teleportLocString, u"", player->GetSystemAddress()); + GameMessages::SendDisplayMessageBox(player->GetObjectID(), true, self->GetObjectID(), u"TransferBox", 0, teleportLocString, u"", player->GetSystemAddress()); } -void BaseConsoleTeleportServer::BaseOnMessageBoxResponse(Entity* self, Entity* sender, int32_t button, const std::u16string& identifier, const std::u16string& userData) -{ - auto* player = sender; +void BaseConsoleTeleportServer::BaseOnMessageBoxResponse(Entity* self, Entity* sender, int32_t button, const std::u16string& identifier, const std::u16string& userData) { + auto* player = sender; - if (button == 1) - { + if (button == 1) { - GameMessages::SendSetStunned(player->GetObjectID(), PUSH, player->GetSystemAddress(), player->GetObjectID(), - true, true, true, true, true, true, true - ); + GameMessages::SendSetStunned(player->GetObjectID(), PUSH, player->GetSystemAddress(), player->GetObjectID(), + true, true, true, true, true, true, true + ); - const auto teleportFXID = self->GetVar(u"teleportEffectID"); + const auto teleportFXID = self->GetVar(u"teleportEffectID"); - if (teleportFXID != 0) - { - const auto& teleportFXs = self->GetVar>(u"teleportEffectTypes"); + if (teleportFXID != 0) { + const auto& teleportFXs = self->GetVar>(u"teleportEffectTypes"); - for (const auto& type : teleportFXs) - { - GameMessages::SendPlayFXEffect(player->GetObjectID(), teleportFXID, type, "FX" + GeneralUtils::UTF16ToWTF8(type)); - } - } + for (const auto& type : teleportFXs) { + GameMessages::SendPlayFXEffect(player->GetObjectID(), teleportFXID, type, "FX" + GeneralUtils::UTF16ToWTF8(type)); + } + } - const auto& teleIntroAnim = self->GetVar(u"teleportAnim"); + const auto& teleIntroAnim = self->GetVar(u"teleportAnim"); - if (!teleIntroAnim.empty()) - { - GameMessages::SendPlayAnimation(player, teleIntroAnim); - } + if (!teleIntroAnim.empty()) { + GameMessages::SendPlayAnimation(player, teleIntroAnim); + } - const auto animTime = 3.32999992370605f; + const auto animTime = 3.32999992370605f; - UpdatePlayerTable(self, player, true); + UpdatePlayerTable(self, player, true); - const auto playerID = player->GetObjectID(); + const auto playerID = player->GetObjectID(); - self->AddCallbackTimer(animTime, [playerID, self] () { - auto* player = EntityManager::Instance()->GetEntity(playerID); + self->AddCallbackTimer(animTime, [playerID, self]() { + auto* player = EntityManager::Instance()->GetEntity(playerID); - if (player == nullptr) - { - return; - } + if (player == nullptr) { + return; + } - GameMessages::SendDisplayZoneSummary(playerID, player->GetSystemAddress(), false, false, self->GetObjectID()); - }); - } - else if (button == -1 || button == 0) - { - GameMessages::SendTerminateInteraction(player->GetObjectID(), FROM_INTERACTION, player->GetObjectID()); - } + GameMessages::SendDisplayZoneSummary(playerID, player->GetSystemAddress(), false, false, self->GetObjectID()); + }); + } else if (button == -1 || button == 0) { + GameMessages::SendTerminateInteraction(player->GetObjectID(), FROM_INTERACTION, player->GetObjectID()); + } } -void BaseConsoleTeleportServer::UpdatePlayerTable(Entity* self, Entity* player, bool bAdd) -{ - const auto iter = std::find(m_Players.begin(), m_Players.end(), player->GetObjectID()); +void BaseConsoleTeleportServer::UpdatePlayerTable(Entity* self, Entity* player, bool bAdd) { + const auto iter = std::find(m_Players.begin(), m_Players.end(), player->GetObjectID()); - if (iter == m_Players.end() && bAdd) - { - m_Players.push_back(player->GetObjectID()); - } - else if (iter != m_Players.end() && !bAdd) - { - m_Players.erase(iter); - } + if (iter == m_Players.end() && bAdd) { + m_Players.push_back(player->GetObjectID()); + } else if (iter != m_Players.end() && !bAdd) { + m_Players.erase(iter); + } } -bool BaseConsoleTeleportServer::CheckPlayerTable(Entity* self, Entity* player) -{ - const auto iter = std::find(m_Players.begin(), m_Players.end(), player->GetObjectID()); +bool BaseConsoleTeleportServer::CheckPlayerTable(Entity* self, Entity* player) { + const auto iter = std::find(m_Players.begin(), m_Players.end(), player->GetObjectID()); - return iter != m_Players.end(); + return iter != m_Players.end(); } -void BaseConsoleTeleportServer::BaseOnFireEventServerSide(Entity *self, Entity *sender, std::string args, int32_t param1, int32_t param2, int32_t param3) -{ - if (args == "summaryComplete") - { - TransferPlayer(self, sender, 0); - } +void BaseConsoleTeleportServer::BaseOnFireEventServerSide(Entity* self, Entity* sender, std::string args, int32_t param1, int32_t param2, int32_t param3) { + if (args == "summaryComplete") { + TransferPlayer(self, sender, 0); + } } -void BaseConsoleTeleportServer::TransferPlayer(Entity* self, Entity* player, int32_t altMapID) -{ - if (player == nullptr || !CheckPlayerTable(self, player)) - { - return; - } +void BaseConsoleTeleportServer::TransferPlayer(Entity* self, Entity* player, int32_t altMapID) { + if (player == nullptr || !CheckPlayerTable(self, player)) { + return; + } - // Ignoring extra effects for now + // Ignoring extra effects for now - /*GameMessages::SendSetStunned(player->GetObjectID(), POP, player->GetSystemAddress(), player->GetObjectID(), - true, true, true, true, true, true, true - );*/ + /*GameMessages::SendSetStunned(player->GetObjectID(), POP, player->GetSystemAddress(), player->GetObjectID(), + true, true, true, true, true, true, true + );*/ - GameMessages::SendTerminateInteraction(player->GetObjectID(), FROM_INTERACTION, player->GetObjectID()); + GameMessages::SendTerminateInteraction(player->GetObjectID(), FROM_INTERACTION, player->GetObjectID()); - const auto& teleportZone = self->GetVar(u"transferZoneID"); + const auto& teleportZone = self->GetVar(u"transferZoneID"); - static_cast(player)->SendToZone(std::stoi(GeneralUtils::UTF16ToWTF8(teleportZone))); + static_cast(player)->SendToZone(std::stoi(GeneralUtils::UTF16ToWTF8(teleportZone))); - UpdatePlayerTable(self, player, false); + UpdatePlayerTable(self, player, false); } -void BaseConsoleTeleportServer::BaseOnTimerDone(Entity* self, const std::string& timerName) -{ - +void BaseConsoleTeleportServer::BaseOnTimerDone(Entity* self, const std::string& timerName) { + } diff --git a/dScripts/BaseConsoleTeleportServer.h b/dScripts/BaseConsoleTeleportServer.h index 086586e3..60c70d75 100644 --- a/dScripts/BaseConsoleTeleportServer.h +++ b/dScripts/BaseConsoleTeleportServer.h @@ -4,14 +4,14 @@ class BaseConsoleTeleportServer { public: - void BaseOnUse(Entity* self, Entity* user); - void BaseOnMessageBoxResponse(Entity* self, Entity* sender, int32_t button, const std::u16string& identifier, const std::u16string& userData); - void UpdatePlayerTable(Entity* self, Entity* player, bool bAdd); - bool CheckPlayerTable(Entity* self, Entity* player); - void BaseOnFireEventServerSide(Entity *self, Entity *sender, std::string args, int32_t param1, int32_t param2, int32_t param3); - void TransferPlayer(Entity* self, Entity* player, int32_t altMapID); - void BaseOnTimerDone(Entity* self, const std::string& timerName); + void BaseOnUse(Entity* self, Entity* user); + void BaseOnMessageBoxResponse(Entity* self, Entity* sender, int32_t button, const std::u16string& identifier, const std::u16string& userData); + void UpdatePlayerTable(Entity* self, Entity* player, bool bAdd); + bool CheckPlayerTable(Entity* self, Entity* player); + void BaseOnFireEventServerSide(Entity* self, Entity* sender, std::string args, int32_t param1, int32_t param2, int32_t param3); + void TransferPlayer(Entity* self, Entity* player, int32_t altMapID); + void BaseOnTimerDone(Entity* self, const std::string& timerName); private: - std::vector m_Players = {}; + std::vector m_Players = {}; }; diff --git a/dScripts/BaseEnemyApe.cpp b/dScripts/BaseEnemyApe.cpp index 9aa391d1..3d0b8e25 100644 --- a/dScripts/BaseEnemyApe.cpp +++ b/dScripts/BaseEnemyApe.cpp @@ -5,130 +5,130 @@ #include "EntityManager.h" #include "SkillComponent.h" -void BaseEnemyApe::OnStartup(Entity *self) { - self->SetVar(u"timesStunned", 2); - self->SetVar(u"knockedOut", false); +void BaseEnemyApe::OnStartup(Entity* self) { + self->SetVar(u"timesStunned", 2); + self->SetVar(u"knockedOut", false); } -void BaseEnemyApe::OnDie(Entity *self, Entity *killer) { - auto* anchor = EntityManager::Instance()->GetEntity(self->GetVar(u"QB")); - if (anchor != nullptr && !anchor->GetIsDead()) { - anchor->Smash(self->GetObjectID(), SILENT); - } +void BaseEnemyApe::OnDie(Entity* self, Entity* killer) { + auto* anchor = EntityManager::Instance()->GetEntity(self->GetVar(u"QB")); + if (anchor != nullptr && !anchor->GetIsDead()) { + anchor->Smash(self->GetObjectID(), SILENT); + } } -void BaseEnemyApe::OnSkillCast(Entity *self, uint32_t skillID) { - const auto groundPoundSkill = self->GetVar(u"GroundPoundSkill") != 0 ? self->GetVar(u"GroundPoundSkill") : 725; - const auto spawnQuickBuildTime = self->GetVar(u"spawnQBTime") != 0.0f ? self->GetVar(u"spawnQBTime") : 5.0f; +void BaseEnemyApe::OnSkillCast(Entity* self, uint32_t skillID) { + const auto groundPoundSkill = self->GetVar(u"GroundPoundSkill") != 0 ? self->GetVar(u"GroundPoundSkill") : 725; + const auto spawnQuickBuildTime = self->GetVar(u"spawnQBTime") != 0.0f ? self->GetVar(u"spawnQBTime") : 5.0f; - if (skillID == groundPoundSkill && self->GetVar(u"QB") == LWOOBJID_EMPTY) { - self->AddTimer("spawnQBTime", spawnQuickBuildTime); - } + if (skillID == groundPoundSkill && self->GetVar(u"QB") == LWOOBJID_EMPTY) { + self->AddTimer("spawnQBTime", spawnQuickBuildTime); + } } -void BaseEnemyApe::OnHit(Entity *self, Entity *attacker) { - auto* destroyableComponent = self->GetComponent(); - if (destroyableComponent != nullptr && destroyableComponent->GetArmor() < 1 && !self->GetBoolean(u"knockedOut")) { - StunApe(self, true); - self->CancelTimer("spawnQBTime"); +void BaseEnemyApe::OnHit(Entity* self, Entity* attacker) { + auto* destroyableComponent = self->GetComponent(); + if (destroyableComponent != nullptr && destroyableComponent->GetArmor() < 1 && !self->GetBoolean(u"knockedOut")) { + StunApe(self, true); + self->CancelTimer("spawnQBTime"); - GameMessages::SendPlayAnimation(self, u"disable", 1.7f); + GameMessages::SendPlayAnimation(self, u"disable", 1.7f); - const auto reviveTime = self->GetVar(u"reviveTime") != 0.0f - ? self->GetVar(u"reviveTime") : 12.0f; - self->AddTimer("reviveTime", reviveTime); - } + const auto reviveTime = self->GetVar(u"reviveTime") != 0.0f + ? self->GetVar(u"reviveTime") : 12.0f; + self->AddTimer("reviveTime", reviveTime); + } } -void BaseEnemyApe::OnTimerDone(Entity *self, std::string timerName) { - if (timerName == "reviveTime") { +void BaseEnemyApe::OnTimerDone(Entity* self, std::string timerName) { + if (timerName == "reviveTime") { - // Revives the ape, giving it back some armor - const auto timesStunned = self->GetVar(u"timesStunned"); - auto* destroyableComponent = self->GetComponent(); - if (destroyableComponent != nullptr) { - destroyableComponent->SetArmor(destroyableComponent->GetMaxArmor() / timesStunned); - } - EntityManager::Instance()->SerializeEntity(self); - self->SetVar(u"timesStunned", timesStunned + 1); - StunApe(self, false); + // Revives the ape, giving it back some armor + const auto timesStunned = self->GetVar(u"timesStunned"); + auto* destroyableComponent = self->GetComponent(); + if (destroyableComponent != nullptr) { + destroyableComponent->SetArmor(destroyableComponent->GetMaxArmor() / timesStunned); + } + EntityManager::Instance()->SerializeEntity(self); + self->SetVar(u"timesStunned", timesStunned + 1); + StunApe(self, false); - } else if (timerName == "spawnQBTime" && self->GetVar(u"QB") == LWOOBJID_EMPTY) { - // Spawn QB in front of ape. - const auto position = self->GetPosition(); - const auto rotation = self->GetRotation(); + } else if (timerName == "spawnQBTime" && self->GetVar(u"QB") == LWOOBJID_EMPTY) { + // Spawn QB in front of ape. + const auto position = self->GetPosition(); + const auto rotation = self->GetRotation(); - const auto backwardVector = rotation.GetForwardVector() * -1; - const auto objectPosition = NiPoint3( - position.GetX() - (backwardVector.GetX() * 8), - position.GetY(), - position.GetZ() - (backwardVector.GetZ() * 8) - ); + const auto backwardVector = rotation.GetForwardVector() * -1; + const auto objectPosition = NiPoint3( + position.GetX() - (backwardVector.GetX() * 8), + position.GetY(), + position.GetZ() - (backwardVector.GetZ() * 8) + ); - EntityInfo entityInfo {}; + EntityInfo entityInfo{}; - entityInfo.pos = position; - entityInfo.rot = rotation; - entityInfo.pos.SetY(entityInfo.pos.GetY() + 13.0f); + entityInfo.pos = position; + entityInfo.rot = rotation; + entityInfo.pos.SetY(entityInfo.pos.GetY() + 13.0f); - entityInfo.spawnerID = self->GetObjectID(); - entityInfo.lot = self->GetVar(u"QuickbuildAnchorLOT") != 0 - ? self->GetVar(u"QuickbuildAnchorLOT") : 7549; - entityInfo.settings = { - new LDFData(u"rebuild_activators", - std::to_string(objectPosition.GetX()) + "\x1f" + - std::to_string(objectPosition.GetY()) + "\x1f" + - std::to_string(objectPosition.GetZ()) - ), - new LDFData(u"no_timed_spawn", true), - new LDFData(u"ape", self->GetObjectID()) - }; + entityInfo.spawnerID = self->GetObjectID(); + entityInfo.lot = self->GetVar(u"QuickbuildAnchorLOT") != 0 + ? self->GetVar(u"QuickbuildAnchorLOT") : 7549; + entityInfo.settings = { + new LDFData(u"rebuild_activators", + std::to_string(objectPosition.GetX()) + "\x1f" + + std::to_string(objectPosition.GetY()) + "\x1f" + + std::to_string(objectPosition.GetZ()) + ), + new LDFData(u"no_timed_spawn", true), + new LDFData(u"ape", self->GetObjectID()) + }; - auto* anchor = EntityManager::Instance()->CreateEntity(entityInfo); - EntityManager::Instance()->ConstructEntity(anchor); - self->SetVar(u"QB", anchor->GetObjectID()); + auto* anchor = EntityManager::Instance()->CreateEntity(entityInfo); + EntityManager::Instance()->ConstructEntity(anchor); + self->SetVar(u"QB", anchor->GetObjectID()); - } else if (timerName == "anchorDamageTimer") { + } else if (timerName == "anchorDamageTimer") { - // Attacks the ape with some god skill - const auto* player = EntityManager::Instance()->GetEntity(self->GetVar(u"smasher")); - if (player == nullptr) { - return; - } + // Attacks the ape with some god skill + const auto* player = EntityManager::Instance()->GetEntity(self->GetVar(u"smasher")); + if (player == nullptr) { + return; + } - auto* skillComponent = self->GetComponent(); - if (skillComponent != nullptr) { - skillComponent->CalculateBehavior(1273, 29446, self->GetObjectID(), true, false, player->GetObjectID()); - } + auto* skillComponent = self->GetComponent(); + if (skillComponent != nullptr) { + skillComponent->CalculateBehavior(1273, 29446, self->GetObjectID(), true, false, player->GetObjectID()); + } - self->SetVar(u"QB", LWOOBJID_EMPTY); - } + self->SetVar(u"QB", LWOOBJID_EMPTY); + } } -void BaseEnemyApe::OnFireEventServerSide(Entity *self, Entity *sender, std::string args, int32_t param1, int32_t param2, - int32_t param3) { - if (args == "rebuildDone" && sender != nullptr) { - self->SetVar(u"smasher", sender->GetObjectID()); - const auto anchorDamageDelayTime = self->GetVar(u"AnchorDamageDelayTime") != 0.0f ? self->GetVar(u"AnchorDamageDelayTime") : 0.5f; - self->AddTimer("anchorDamageTimer", anchorDamageDelayTime); - } +void BaseEnemyApe::OnFireEventServerSide(Entity* self, Entity* sender, std::string args, int32_t param1, int32_t param2, + int32_t param3) { + if (args == "rebuildDone" && sender != nullptr) { + self->SetVar(u"smasher", sender->GetObjectID()); + const auto anchorDamageDelayTime = self->GetVar(u"AnchorDamageDelayTime") != 0.0f ? self->GetVar(u"AnchorDamageDelayTime") : 0.5f; + self->AddTimer("anchorDamageTimer", anchorDamageDelayTime); + } } -void BaseEnemyApe::StunApe(Entity *self, bool stunState) { - auto* combatAIComponent = self->GetComponent(); - if (combatAIComponent != nullptr) { - combatAIComponent->SetDisabled(stunState); - combatAIComponent->SetStunned(stunState); +void BaseEnemyApe::StunApe(Entity* self, bool stunState) { + auto* combatAIComponent = self->GetComponent(); + if (combatAIComponent != nullptr) { + combatAIComponent->SetDisabled(stunState); + combatAIComponent->SetStunned(stunState); - auto* skillComponent = self->GetComponent(); - if (skillComponent != nullptr) { - skillComponent->Interrupt(); - } + auto* skillComponent = self->GetComponent(); + if (skillComponent != nullptr) { + skillComponent->Interrupt(); + } - GameMessages::SendSetStunned(self->GetObjectID(), stunState ? PUSH : POP, UNASSIGNED_SYSTEM_ADDRESS, self->GetObjectID(), - true, true, true, true, true, - true, true, true, true); + GameMessages::SendSetStunned(self->GetObjectID(), stunState ? PUSH : POP, UNASSIGNED_SYSTEM_ADDRESS, self->GetObjectID(), + true, true, true, true, true, + true, true, true, true); - self->SetBoolean(u"knockedOut", stunState); - } + self->SetBoolean(u"knockedOut", stunState); + } } diff --git a/dScripts/BaseEnemyApe.h b/dScripts/BaseEnemyApe.h index 1553d3ae..938312b6 100644 --- a/dScripts/BaseEnemyApe.h +++ b/dScripts/BaseEnemyApe.h @@ -3,13 +3,13 @@ class BaseEnemyApe : public CppScripts::Script { public: - void OnStartup(Entity *self) override; - void OnDie(Entity *self, Entity *killer) override; - void OnSkillCast(Entity *self, uint32_t skillID) override; - void OnHit(Entity *self, Entity *attacker) override; - void OnTimerDone(Entity *self, std::string timerName) override; - void OnFireEventServerSide(Entity *self, Entity *sender, std::string args, int32_t param1, int32_t param2, - int32_t param3) override; + void OnStartup(Entity* self) override; + void OnDie(Entity* self, Entity* killer) override; + void OnSkillCast(Entity* self, uint32_t skillID) override; + void OnHit(Entity* self, Entity* attacker) override; + void OnTimerDone(Entity* self, std::string timerName) override; + void OnFireEventServerSide(Entity* self, Entity* sender, std::string args, int32_t param1, int32_t param2, + int32_t param3) override; private: - static void StunApe(Entity* self, bool stunState); + static void StunApe(Entity* self, bool stunState); }; diff --git a/dScripts/BaseEnemyMech.cpp b/dScripts/BaseEnemyMech.cpp index 17c7a347..32dc38dd 100644 --- a/dScripts/BaseEnemyMech.cpp +++ b/dScripts/BaseEnemyMech.cpp @@ -7,17 +7,17 @@ #include "DestroyableComponent.h" void BaseEnemyMech::OnStartup(Entity* self) { - auto* destroyableComponent = self->GetComponent(); - if (destroyableComponent != nullptr) { - destroyableComponent->SetFaction(4); - } + auto* destroyableComponent = self->GetComponent(); + if (destroyableComponent != nullptr) { + destroyableComponent->SetFaction(4); + } } void BaseEnemyMech::OnDie(Entity* self, Entity* killer) { ControllablePhysicsComponent* controlPhys = static_cast(self->GetComponent(COMPONENT_TYPE_CONTROLLABLE_PHYSICS)); if (!controlPhys) return; - NiPoint3 newLoc = {controlPhys->GetPosition().x, dpWorld::Instance().GetHeightAtPoint(controlPhys->GetPosition()), controlPhys->GetPosition().z }; + NiPoint3 newLoc = { controlPhys->GetPosition().x, dpWorld::Instance().GetHeightAtPoint(controlPhys->GetPosition()), controlPhys->GetPosition().z }; EntityInfo info = EntityInfo(); std::vector cfg; diff --git a/dScripts/BaseEnemyMech.h b/dScripts/BaseEnemyMech.h index a8955061..133b855e 100644 --- a/dScripts/BaseEnemyMech.h +++ b/dScripts/BaseEnemyMech.h @@ -4,7 +4,7 @@ class BaseEnemyMech : public CppScripts::Script { public: - void OnStartup(Entity* self) override; + void OnStartup(Entity* self) override; void OnDie(Entity* self, Entity* killer) override; protected: LOT qbTurretLOT = 6254; diff --git a/dScripts/BaseFootRaceManager.cpp b/dScripts/BaseFootRaceManager.cpp index 0da51bc5..699ee096 100644 --- a/dScripts/BaseFootRaceManager.cpp +++ b/dScripts/BaseFootRaceManager.cpp @@ -2,47 +2,47 @@ #include "EntityManager.h" #include "Character.h" -void BaseFootRaceManager::OnStartup(Entity *self) { - // TODO: Add to FootRaceStarter group +void BaseFootRaceManager::OnStartup(Entity* self) { + // TODO: Add to FootRaceStarter group } -void BaseFootRaceManager::OnFireEventServerSide(Entity *self, Entity *sender, std::string args, int32_t param1, - int32_t param2, int32_t param3) { - const auto splitArguments = GeneralUtils::SplitString(args, '_'); - if (splitArguments.size() > 1) { +void BaseFootRaceManager::OnFireEventServerSide(Entity* self, Entity* sender, std::string args, int32_t param1, + int32_t param2, int32_t param3) { + const auto splitArguments = GeneralUtils::SplitString(args, '_'); + if (splitArguments.size() > 1) { - const auto eventName = splitArguments[0]; - const auto player = EntityManager::Instance()->GetEntity(std::stoull(splitArguments[1])); + const auto eventName = splitArguments[0]; + const auto player = EntityManager::Instance()->GetEntity(std::stoull(splitArguments[1])); - if (player != nullptr) { - if (eventName == "updatePlayer") { - UpdatePlayer(self, player->GetObjectID()); - } else if (IsPlayerInActivity(self, player->GetObjectID())) { - if (eventName == "initialActivityScore") { - auto* character = player->GetCharacter(); - if (character != nullptr) { - character->SetPlayerFlag(115, true); - } + if (player != nullptr) { + if (eventName == "updatePlayer") { + UpdatePlayer(self, player->GetObjectID()); + } else if (IsPlayerInActivity(self, player->GetObjectID())) { + if (eventName == "initialActivityScore") { + auto* character = player->GetCharacter(); + if (character != nullptr) { + character->SetPlayerFlag(115, true); + } - SetActivityScore(self, player->GetObjectID(), 1); - } else if (eventName == "updatePlayerTrue") { - auto* character = player->GetCharacter(); - if (character != nullptr) { - character->SetPlayerFlag(115, false); - } + SetActivityScore(self, player->GetObjectID(), 1); + } else if (eventName == "updatePlayerTrue") { + auto* character = player->GetCharacter(); + if (character != nullptr) { + character->SetPlayerFlag(115, false); + } - UpdatePlayer(self, player->GetObjectID(), true); - } else if (eventName == "PlayerWon") { - auto* character = player->GetCharacter(); - if (character != nullptr) { - character->SetPlayerFlag(115, false); - if (param2 != -1) // Certain footraces set a flag - character->SetPlayerFlag(param2, true); - } + UpdatePlayer(self, player->GetObjectID(), true); + } else if (eventName == "PlayerWon") { + auto* character = player->GetCharacter(); + if (character != nullptr) { + character->SetPlayerFlag(115, false); + if (param2 != -1) // Certain footraces set a flag + character->SetPlayerFlag(param2, true); + } - StopActivity(self, player->GetObjectID(), 0, param1); - } - } - } - } + StopActivity(self, player->GetObjectID(), 0, param1); + } + } + } + } } diff --git a/dScripts/BaseFootRaceManager.h b/dScripts/BaseFootRaceManager.h index 1a76cf19..477a6eb9 100644 --- a/dScripts/BaseFootRaceManager.h +++ b/dScripts/BaseFootRaceManager.h @@ -3,7 +3,7 @@ #include "CppScripts.h" class BaseFootRaceManager : public ActivityManager { - void OnStartup(Entity* self) override; - void OnFireEventServerSide(Entity *self, Entity *sender, std::string args, int32_t param1, int32_t param2, - int32_t param3) override; + void OnStartup(Entity* self) override; + void OnFireEventServerSide(Entity* self, Entity* sender, std::string args, int32_t param1, int32_t param2, + int32_t param3) override; }; diff --git a/dScripts/BaseInteractDropLootServer.cpp b/dScripts/BaseInteractDropLootServer.cpp index 0dbce047..44698956 100644 --- a/dScripts/BaseInteractDropLootServer.cpp +++ b/dScripts/BaseInteractDropLootServer.cpp @@ -2,32 +2,29 @@ #include "Loot.h" #include "GameMessages.h" -void BaseInteractDropLootServer::OnUse(Entity* self, Entity* user) -{ - BaseUse(self, user); +void BaseInteractDropLootServer::OnUse(Entity* self, Entity* user) { + BaseUse(self, user); } -void BaseInteractDropLootServer::BaseUse(Entity* self, Entity* user) -{ - auto cooldownTime = self->GetVar(u"cooldownTime"); - if (cooldownTime == 0) cooldownTime = 5; +void BaseInteractDropLootServer::BaseUse(Entity* self, Entity* user) { + auto cooldownTime = self->GetVar(u"cooldownTime"); + if (cooldownTime == 0) cooldownTime = 5; - uint32_t lootMatrix = self->GetVar(u"UseLootMatrix"); - if (lootMatrix == 0) lootMatrix = self->GetVar(u"smashable_loot_matrix"); - if (lootMatrix == 0) lootMatrix = 715; + uint32_t lootMatrix = self->GetVar(u"UseLootMatrix"); + if (lootMatrix == 0) lootMatrix = self->GetVar(u"smashable_loot_matrix"); + if (lootMatrix == 0) lootMatrix = 715; - auto useSound = self->GetVar(u"sound1"); + auto useSound = self->GetVar(u"sound1"); - if (!useSound.empty()) - { - GameMessages::SendPlayNDAudioEmitter(self, user->GetSystemAddress(), useSound); - } + if (!useSound.empty()) { + GameMessages::SendPlayNDAudioEmitter(self, user->GetSystemAddress(), useSound); + } - self->SetNetworkVar(u"bInUse", true); + self->SetNetworkVar(u"bInUse", true); - LootGenerator::Instance().DropLoot(user, self, lootMatrix, 0, 0); + LootGenerator::Instance().DropLoot(user, self, lootMatrix, 0, 0); - self->AddCallbackTimer(cooldownTime, [this, self] () { - self->SetNetworkVar(u"bInUse", false); - }); + self->AddCallbackTimer(cooldownTime, [this, self]() { + self->SetNetworkVar(u"bInUse", false); + }); } diff --git a/dScripts/BaseInteractDropLootServer.h b/dScripts/BaseInteractDropLootServer.h index d2e9b600..f2a084f5 100644 --- a/dScripts/BaseInteractDropLootServer.h +++ b/dScripts/BaseInteractDropLootServer.h @@ -4,7 +4,7 @@ class BaseInteractDropLootServer : public CppScripts::Script { public: - virtual void OnUse(Entity* self, Entity* user) override; - void BaseUse(Entity* self, Entity* user); + virtual void OnUse(Entity* self, Entity* user) override; + void BaseUse(Entity* self, Entity* user); }; diff --git a/dScripts/BasePropertyServer.cpp b/dScripts/BasePropertyServer.cpp index ce36caa9..a182c9c1 100644 --- a/dScripts/BasePropertyServer.cpp +++ b/dScripts/BasePropertyServer.cpp @@ -9,61 +9,61 @@ #include "PropertyManagementComponent.h" #include "MissionComponent.h" -void BasePropertyServer::SetGameVariables(Entity *self) { - self->SetVar(ClaimMarkerGroup, ""); - self->SetVar(GeneratorGroup, ""); - self->SetVar(GuardGroup, ""); - self->SetVar(PropertyPlaqueGroup, ""); - self->SetVar(PropertyVendorGroup, ""); - self->SetVar(SpotsGroup, ""); - self->SetVar(MSCloudsGroup, ""); - self->SetVar(EnemiesGroup, ""); - self->SetVar(FXManagerGroup, ""); - self->SetVar(ImagOrbGroup, ""); - self->SetVar(GeneratorFXGroup, ""); +void BasePropertyServer::SetGameVariables(Entity* self) { + self->SetVar(ClaimMarkerGroup, ""); + self->SetVar(GeneratorGroup, ""); + self->SetVar(GuardGroup, ""); + self->SetVar(PropertyPlaqueGroup, ""); + self->SetVar(PropertyVendorGroup, ""); + self->SetVar(SpotsGroup, ""); + self->SetVar(MSCloudsGroup, ""); + self->SetVar(EnemiesGroup, ""); + self->SetVar(FXManagerGroup, ""); + self->SetVar(ImagOrbGroup, ""); + self->SetVar(GeneratorFXGroup, ""); - self->SetVar>(EnemiesSpawner, {}); - self->SetVar(ClaimMarkerSpawner, ""); - self->SetVar(GeneratorSpawner, ""); - self->SetVar(DamageFXSpawner, ""); - self->SetVar(FXSpotsSpawner, ""); - self->SetVar(PropertyMGSpawner, ""); - self->SetVar(ImageOrbSpawner, ""); - self->SetVar(GeneratorFXSpawner, ""); - self->SetVar(SmashablesSpawner, ""); - self->SetVar(FXManagerSpawner, ""); - self->SetVar(PropObjsSpawner, ""); - self->SetVar>(AmbientFXSpawner, {}); - self->SetVar>(BehaviorObjsSpawner, {}); + self->SetVar>(EnemiesSpawner, {}); + self->SetVar(ClaimMarkerSpawner, ""); + self->SetVar(GeneratorSpawner, ""); + self->SetVar(DamageFXSpawner, ""); + self->SetVar(FXSpotsSpawner, ""); + self->SetVar(PropertyMGSpawner, ""); + self->SetVar(ImageOrbSpawner, ""); + self->SetVar(GeneratorFXSpawner, ""); + self->SetVar(SmashablesSpawner, ""); + self->SetVar(FXManagerSpawner, ""); + self->SetVar(PropObjsSpawner, ""); + self->SetVar>(AmbientFXSpawner, {}); + self->SetVar>(BehaviorObjsSpawner, {}); - self->SetVar(defeatedProperyFlag, 0); - self->SetVar(placedModelFlag, 0); - self->SetVar(guardMissionFlag, 0); - self->SetVar(brickLinkMissionIDFlag, 0); - self->SetVar(passwordFlag, "s3kratK1ttN"); - self->SetVar(generatorIdFlag, 0); - self->SetVar(orbIDFlag, 0); - self->SetVar(behaviorQBID, 0); + self->SetVar(defeatedProperyFlag, 0); + self->SetVar(placedModelFlag, 0); + self->SetVar(guardMissionFlag, 0); + self->SetVar(brickLinkMissionIDFlag, 0); + self->SetVar(passwordFlag, "s3kratK1ttN"); + self->SetVar(generatorIdFlag, 0); + self->SetVar(orbIDFlag, 0); + self->SetVar(behaviorQBID, 0); } void BasePropertyServer::CheckForOwner(Entity* self) { - if (EntityManager::Instance()->GetEntitiesInGroup(self->GetVar(PropertyPlaqueGroup)).empty()) { - self->AddTimer(RunPlayerLoadedAgainTimer, 0.5f); - return; - } + if (EntityManager::Instance()->GetEntitiesInGroup(self->GetVar(PropertyPlaqueGroup)).empty()) { + self->AddTimer(RunPlayerLoadedAgainTimer, 0.5f); + return; + } self->SetI64(PropertyOwnerVariable, GetOwner()); } -void BasePropertyServer::OnStartup(Entity *self) { - SetGameVariables(self); +void BasePropertyServer::OnStartup(Entity* self) { + SetGameVariables(self); } -void BasePropertyServer::OnFireEventServerSide(Entity *self, Entity *sender, std::string args, int32_t param1, - int32_t param2, int32_t param3) { - if (args == CheckForPropertyOwnerEvent) { - sender->SetNetworkVar(PropertyOwnerIDVariable, std::to_string(self->GetVar(PropertyOwnerVariable))); - } +void BasePropertyServer::OnFireEventServerSide(Entity* self, Entity* sender, std::string args, int32_t param1, + int32_t param2, int32_t param3) { + if (args == CheckForPropertyOwnerEvent) { + sender->SetNetworkVar(PropertyOwnerIDVariable, std::to_string(self->GetVar(PropertyOwnerVariable))); + } } void BasePropertyServer::BasePlayerLoaded(Entity* self, Entity* player) { @@ -73,7 +73,7 @@ void BasePropertyServer::BasePlayerLoaded(Entity* self, Entity* player) { auto propertyOwner = PropertyManagementComponent::Instance()->GetOwnerId(); self->OnFireEventServerSide(self, CheckForPropertyOwnerEvent); - + if (propertyOwner > 0) { rented = true; } @@ -85,19 +85,17 @@ void BasePropertyServer::BasePlayerLoaded(Entity* self, Entity* player) { self->SetNetworkVar(PropertyOwnerIDVariable, propertyOwner); if (rented) { - auto plaques = EntityManager::Instance()->GetEntitiesInGroup("PropertyVendor"); - for (auto* plaque : plaques) { - EntityManager::Instance()->DestructEntity(plaque); - } + auto plaques = EntityManager::Instance()->GetEntitiesInGroup("PropertyVendor"); + for (auto* plaque : plaques) { + EntityManager::Instance()->DestructEntity(plaque); + } const auto& mapID = dZoneManager::Instance()->GetZone()->GetZoneID(); - if (propertyOwner > 0) - { + if (propertyOwner > 0) { auto* missionComponent = player->GetComponent(); - if (missionComponent != nullptr) - { + if (missionComponent != nullptr) { missionComponent->Progress( MissionTaskType::MISSION_TASK_TYPE_VISIT_PROPERTY, mapID.GetMapID(), @@ -115,7 +113,7 @@ void BasePropertyServer::BasePlayerLoaded(Entity* self, Entity* player) { if (!self->GetBoolean(FXObjectsGoneVariable)) { self->AddTimer(KillFXObjectTimer, 1.0f); } - + GameMessages::SendPlay2DAmbientSound(player, GUIDPeaceful); // activate property safe spawner network @@ -130,7 +128,7 @@ void BasePropertyServer::BasePlayerLoaded(Entity* self, Entity* player) { const auto defeatedFlag = player->GetCharacter()->GetPlayerFlag(self->GetVar(defeatedProperyFlag)); self->SetNetworkVar(UnclaimedVariable, true); - self->SetVar(PlayerIDVariable, player->GetObjectID()); + self->SetVar(PlayerIDVariable, player->GetObjectID()); if (!defeatedFlag) { StartMaelstrom(self, player); @@ -152,27 +150,27 @@ void BasePropertyServer::PropGuardCheck(Entity* self, Entity* player) { auto* missionComponent = player->GetComponent(); if (missionComponent != nullptr - && missionComponent->GetMissionState(self->GetVar(guardMissionFlag)) != MissionState::MISSION_STATE_COMPLETE) { - ActivateSpawner(self->GetVar(PropertyMGSpawner)); + && missionComponent->GetMissionState(self->GetVar(guardMissionFlag)) != MissionState::MISSION_STATE_COMPLETE) { + ActivateSpawner(self->GetVar(PropertyMGSpawner)); } } void BasePropertyServer::BaseZonePropertyRented(Entity* self, Entity* player) const { GameMessages::SendNotifyClientObject(self->GetObjectID(), u"PlayCinematic", 0, 0, LWOOBJID_EMPTY, "ShowProperty", - UNASSIGNED_SYSTEM_ADDRESS); + UNASSIGNED_SYSTEM_ADDRESS); self->AddTimer(BoundsVisOnTimer, 2); self->SetVar(PropertyOwnerVariable, player->GetObjectID()); - - auto plaques = EntityManager::Instance()->GetEntitiesInGroup("PropertyVendor"); - for (auto* plaque : plaques) { - EntityManager::Instance()->DestructEntity(plaque); - } - auto brickLinkMissionID = self->GetVar(brickLinkMissionIDFlag); + auto plaques = EntityManager::Instance()->GetEntitiesInGroup("PropertyVendor"); + for (auto* plaque : plaques) { + EntityManager::Instance()->DestructEntity(plaque); + } + + auto brickLinkMissionID = self->GetVar(brickLinkMissionIDFlag); if (brickLinkMissionID != 0) { - auto missionComponent = player->GetComponent(); - if (missionComponent) missionComponent->CompleteMission(brickLinkMissionID, true); + auto missionComponent = player->GetComponent(); + if (missionComponent) missionComponent->CompleteMission(brickLinkMissionID, true); } ActivateSpawner(self->GetVar(PropObjsSpawner)); @@ -185,7 +183,7 @@ void BasePropertyServer::BaseZonePropertyModelPlaced(Entity* self, Entity* playe auto flag = self->GetVar(placedModelFlag); if (flag) - character->SetPlayerFlag(flag, true); + character->SetPlayerFlag(flag, true); } void BasePropertyServer::KillClouds(Entity* self) { @@ -203,13 +201,13 @@ void BasePropertyServer::KillSpots(Entity* self) { } void BasePropertyServer::StartMaelstrom(Entity* self, Entity* player) { - for (const auto& enemySpawner : self->GetVar>(EnemiesSpawner)) { - ActivateSpawner(enemySpawner); - } + for (const auto& enemySpawner : self->GetVar>(EnemiesSpawner)) { + ActivateSpawner(enemySpawner); + } - for (const auto& behaviorObjectSpawner : self->GetVar>(BehaviorObjsSpawner)) { - ActivateSpawner(behaviorObjectSpawner); - } + for (const auto& behaviorObjectSpawner : self->GetVar>(BehaviorObjsSpawner)) { + ActivateSpawner(behaviorObjectSpawner); + } ActivateSpawner(self->GetVar(DamageFXSpawner)); ActivateSpawner(self->GetVar(GeneratorSpawner)); @@ -221,13 +219,13 @@ void BasePropertyServer::StartMaelstrom(Entity* self, Entity* player) { DestroySpawner(self->GetVar(ClaimMarkerSpawner)); for (const auto& ambientFXSpawner : self->GetVar>(AmbientFXSpawner)) { - DestroySpawner(ambientFXSpawner); + DestroySpawner(ambientFXSpawner); } StartTornadoFx(self); GameMessages::SendNotifyClientObject(self->GetObjectID(), u"maelstromSkyOn", 0, 0, LWOOBJID_EMPTY, - "", player->GetSystemAddress()); + "", player->GetSystemAddress()); self->AddTimer(StartGeneratorTimer, 0.0f); self->AddTimer(StartOrbTimer, 0.0f); @@ -241,20 +239,20 @@ void BasePropertyServer::StartTornadoFx(Entity* self) const { } for (auto* entity : entities) { - auto* renderComponent = entity->GetComponent(); - if (renderComponent != nullptr) { - renderComponent->PlayEffect(-1, u"debrisOn", "TornadoDebris"); - renderComponent->PlayEffect(-1, u"VortexOn", "TornadoVortex"); - renderComponent->PlayEffect(-1, u"onSilhouette", "silhouette"); - } + auto* renderComponent = entity->GetComponent(); + if (renderComponent != nullptr) { + renderComponent->PlayEffect(-1, u"debrisOn", "TornadoDebris"); + renderComponent->PlayEffect(-1, u"VortexOn", "TornadoVortex"); + renderComponent->PlayEffect(-1, u"onSilhouette", "silhouette"); + } } } -void BasePropertyServer::BasePlayerExit(Entity *self, Entity *player) { +void BasePropertyServer::BasePlayerExit(Entity* self, Entity* player) { if (self->GetBoolean(UnclaimedVariable)) { - if (player->GetObjectID() == self->GetVar(PlayerIDVariable)) { - // Destroy all spawners - } + if (player->GetObjectID() == self->GetVar(PlayerIDVariable)) { + // Destroy all spawners + } } } @@ -284,9 +282,9 @@ void BasePropertyServer::ActivateSpawner(const std::string& spawnerName) { } void BasePropertyServer::DeactivateSpawner(const std::string& spawnerName) { - for (auto* spawner : dZoneManager::Instance()->GetSpawnersByName(spawnerName)) { - spawner->Deactivate(); - } + for (auto* spawner : dZoneManager::Instance()->GetSpawnersByName(spawnerName)) { + spawner->Deactivate(); + } } void BasePropertyServer::TriggerSpawner(const std::string& spawnerName) { @@ -296,27 +294,27 @@ void BasePropertyServer::TriggerSpawner(const std::string& spawnerName) { } void BasePropertyServer::ResetSpawner(const std::string& spawnerName) { - for (auto* spawner : dZoneManager::Instance()->GetSpawnersByName(spawnerName)) { - spawner->Reset(); - } + for (auto* spawner : dZoneManager::Instance()->GetSpawnersByName(spawnerName)) { + spawner->Reset(); + } } void BasePropertyServer::DestroySpawner(const std::string& spawnerName) { - for (auto* spawner : dZoneManager::Instance()->GetSpawnersByName(spawnerName)) { - for (auto* node : spawner->m_Info.nodes) { - for (const auto& element : node->entities) { - auto* entity = EntityManager::Instance()->GetEntity(element); - if (entity == nullptr) - continue; + for (auto* spawner : dZoneManager::Instance()->GetSpawnersByName(spawnerName)) { + for (auto* node : spawner->m_Info.nodes) { + for (const auto& element : node->entities) { + auto* entity = EntityManager::Instance()->GetEntity(element); + if (entity == nullptr) + continue; - entity->Kill(); - } + entity->Kill(); + } - node->entities.clear(); - } + node->entities.clear(); + } - spawner->Deactivate(); - } + spawner->Deactivate(); + } } LWOOBJID BasePropertyServer::GetOwner() { @@ -325,194 +323,194 @@ LWOOBJID BasePropertyServer::GetOwner() { } void BasePropertyServer::BaseTimerDone(Entity* self, const std::string& timerName) { - if (timerName == StartGeneratorTimer) { - HandleGeneratorTimer(self); - } else if (timerName == StartOrbTimer) { - HandleOrbsTimer(self); - } else if (timerName == StartQuickbuildTimer) { - HandleQuickBuildTimer(self); - } else if (timerName == "GuardFlyAway") { - const auto zoneId = dZoneManager::Instance()->GetZone()->GetWorldID(); + if (timerName == StartGeneratorTimer) { + HandleGeneratorTimer(self); + } else if (timerName == StartOrbTimer) { + HandleOrbsTimer(self); + } else if (timerName == StartQuickbuildTimer) { + HandleQuickBuildTimer(self); + } else if (timerName == "GuardFlyAway") { + const auto zoneId = dZoneManager::Instance()->GetZone()->GetWorldID(); - // No guard for the spider instance fight - if (dZoneManager::Instance()->GetZoneID().GetMapID() == 1150) - return; + // No guard for the spider instance fight + if (dZoneManager::Instance()->GetZoneID().GetMapID() == 1150) + return; - const auto entities = EntityManager::Instance()->GetEntitiesInGroup(self->GetVar(GuardGroup)); - if (entities.empty()) - return; + const auto entities = EntityManager::Instance()->GetEntitiesInGroup(self->GetVar(GuardGroup)); + if (entities.empty()) + return; - auto* guard = entities[0]; - GameMessages::SendNotifyClientObject(EntityManager::Instance()->GetZoneControlEntity()->GetObjectID(), - u"GuardChat", 0, 0, guard->GetObjectID(), - "", UNASSIGNED_SYSTEM_ADDRESS); + auto* guard = entities[0]; + GameMessages::SendNotifyClientObject(EntityManager::Instance()->GetZoneControlEntity()->GetObjectID(), + u"GuardChat", 0, 0, guard->GetObjectID(), + "", UNASSIGNED_SYSTEM_ADDRESS); - self->AddTimer(KillGuardTimer, 5.0f); - } else if (timerName == KillGuardTimer) { - KillGuard(self); - } else if (timerName == TornadoOffTimer) { - auto fxManagers = EntityManager::Instance()->GetEntitiesInGroup(self->GetVar(FXManagerGroup)); + self->AddTimer(KillGuardTimer, 5.0f); + } else if (timerName == KillGuardTimer) { + KillGuard(self); + } else if (timerName == TornadoOffTimer) { + auto fxManagers = EntityManager::Instance()->GetEntitiesInGroup(self->GetVar(FXManagerGroup)); - for (auto *fxManager : fxManagers) { - auto *renderComponent = fxManager->GetComponent(); - if (renderComponent != nullptr) { - renderComponent->StopEffect("TornadoDebris", false); - renderComponent->StopEffect("TornadoVortex", false); - renderComponent->StopEffect("silhouette", false); - } - } + for (auto* fxManager : fxManagers) { + auto* renderComponent = fxManager->GetComponent(); + if (renderComponent != nullptr) { + renderComponent->StopEffect("TornadoDebris", false); + renderComponent->StopEffect("TornadoVortex", false); + renderComponent->StopEffect("silhouette", false); + } + } - self->AddTimer(ShowClearEffectsTimer, 2); - } else if (timerName == ShowClearEffectsTimer) { - auto fxManagers = EntityManager::Instance()->GetEntitiesInGroup(self->GetVar(FXManagerGroup)); + self->AddTimer(ShowClearEffectsTimer, 2); + } else if (timerName == ShowClearEffectsTimer) { + auto fxManagers = EntityManager::Instance()->GetEntitiesInGroup(self->GetVar(FXManagerGroup)); - for (auto *fxManager : fxManagers) { - auto *renderComponent = fxManager->GetComponent(); - if (renderComponent != nullptr) - renderComponent->PlayEffect(-1, u"beamOn", "beam"); - } + for (auto* fxManager : fxManagers) { + auto* renderComponent = fxManager->GetComponent(); + if (renderComponent != nullptr) + renderComponent->PlayEffect(-1, u"beamOn", "beam"); + } - self->AddTimer(KillStrombiesTimer, 2.0f); - self->AddTimer(TurnSkyOffTimer, 1.5f); - self->AddTimer(KillFXObjectTimer, 8.0f); - } else if (timerName == TurnSkyOffTimer) { - auto* controller = dZoneManager::Instance()->GetZoneControlObject(); - GameMessages::SendNotifyClientObject(controller->GetObjectID(), u"SkyOff", 0, 0, - LWOOBJID_EMPTY, "", UNASSIGNED_SYSTEM_ADDRESS); - } else if (timerName == KillStrombiesTimer) { - const auto enemies = EntityManager::Instance()->GetEntitiesInGroup(self->GetVar(EnemiesGroup)); - for (auto* enemy : enemies) { - RequestDie(self, enemy); - } + self->AddTimer(KillStrombiesTimer, 2.0f); + self->AddTimer(TurnSkyOffTimer, 1.5f); + self->AddTimer(KillFXObjectTimer, 8.0f); + } else if (timerName == TurnSkyOffTimer) { + auto* controller = dZoneManager::Instance()->GetZoneControlObject(); + GameMessages::SendNotifyClientObject(controller->GetObjectID(), u"SkyOff", 0, 0, + LWOOBJID_EMPTY, "", UNASSIGNED_SYSTEM_ADDRESS); + } else if (timerName == KillStrombiesTimer) { + const auto enemies = EntityManager::Instance()->GetEntitiesInGroup(self->GetVar(EnemiesGroup)); + for (auto* enemy : enemies) { + RequestDie(self, enemy); + } - DestroySpawner(self->GetVar(SmashablesSpawner)); - KillSpots(self); + DestroySpawner(self->GetVar(SmashablesSpawner)); + KillSpots(self); - auto* player = EntityManager::Instance()->GetEntity(self->GetVar(PlayerIDVariable)); - if (player == nullptr) - return; + auto* player = EntityManager::Instance()->GetEntity(self->GetVar(PlayerIDVariable)); + if (player == nullptr) + return; - GameMessages::SendStop2DAmbientSound(player, true, GUIDMaelstrom); - GameMessages::SendPlay2DAmbientSound(player, GUIDPeaceful); + GameMessages::SendStop2DAmbientSound(player, true, GUIDMaelstrom); + GameMessages::SendPlay2DAmbientSound(player, GUIDPeaceful); - self->AddTimer(ShowVendorTimer, 5.0f); - } else if (timerName == KillMarkerTimer) { - DestroySpawner(self->GetVar(ClaimMarkerSpawner)); + self->AddTimer(ShowVendorTimer, 5.0f); + } else if (timerName == KillMarkerTimer) { + DestroySpawner(self->GetVar(ClaimMarkerSpawner)); - for (const auto& behaviorObjectSpawner : self->GetVar>(BehaviorObjsSpawner)) { - DestroySpawner(behaviorObjectSpawner); - } + for (const auto& behaviorObjectSpawner : self->GetVar>(BehaviorObjsSpawner)) { + DestroySpawner(behaviorObjectSpawner); + } - for (auto* entity : EntityManager::Instance()->GetEntitiesInGroup(self->GetVar(ImagOrbGroup))) { - entity->Smash(); - } + for (auto* entity : EntityManager::Instance()->GetEntitiesInGroup(self->GetVar(ImagOrbGroup))) { + entity->Smash(); + } - DestroySpawner(self->GetVar(ImageOrbSpawner)); + DestroySpawner(self->GetVar(ImageOrbSpawner)); - self->AddTimer(ShowVendorTimer, 1.0f); - } else if (timerName == ShowVendorTimer) { - GameMessages::SendNotifyClientObject(EntityManager::Instance()->GetZoneControlEntity()->GetObjectID(), - u"vendorOn", 0, 0, LWOOBJID_EMPTY, "", - UNASSIGNED_SYSTEM_ADDRESS); + self->AddTimer(ShowVendorTimer, 1.0f); + } else if (timerName == ShowVendorTimer) { + GameMessages::SendNotifyClientObject(EntityManager::Instance()->GetZoneControlEntity()->GetObjectID(), + u"vendorOn", 0, 0, LWOOBJID_EMPTY, "", + UNASSIGNED_SYSTEM_ADDRESS); - for (const auto& ambientFXSpawner : self->GetVar>(AmbientFXSpawner)) { - ActivateSpawner(ambientFXSpawner); - } - } else if (timerName == BoundsVisOnTimer) { - GameMessages::SendNotifyClientObject(self->GetObjectID(), u"boundsAnim", 0, 0, - LWOOBJID_EMPTY, "", UNASSIGNED_SYSTEM_ADDRESS); - } else if (timerName == RunPlayerLoadedAgainTimer) { - CheckForOwner(self); - } else if (timerName == PollTornadoFXTimer) { - StartTornadoFx(self); - } else if (timerName == KillFXObjectTimer) { - const auto fxManagers = EntityManager::Instance()->GetEntitiesInGroup(self->GetVar(FXManagerGroup)); - if (fxManagers.empty()) { - self->AddTimer(KillFXObjectTimer, 1.0f); - return; - } + for (const auto& ambientFXSpawner : self->GetVar>(AmbientFXSpawner)) { + ActivateSpawner(ambientFXSpawner); + } + } else if (timerName == BoundsVisOnTimer) { + GameMessages::SendNotifyClientObject(self->GetObjectID(), u"boundsAnim", 0, 0, + LWOOBJID_EMPTY, "", UNASSIGNED_SYSTEM_ADDRESS); + } else if (timerName == RunPlayerLoadedAgainTimer) { + CheckForOwner(self); + } else if (timerName == PollTornadoFXTimer) { + StartTornadoFx(self); + } else if (timerName == KillFXObjectTimer) { + const auto fxManagers = EntityManager::Instance()->GetEntitiesInGroup(self->GetVar(FXManagerGroup)); + if (fxManagers.empty()) { + self->AddTimer(KillFXObjectTimer, 1.0f); + return; + } - for (auto* fxManager : fxManagers) { - auto* renderComponent = fxManager->GetComponent(); - if (renderComponent != nullptr) { - renderComponent->StopEffect("beam"); - } - } + for (auto* fxManager : fxManagers) { + auto* renderComponent = fxManager->GetComponent(); + if (renderComponent != nullptr) { + renderComponent->StopEffect("beam"); + } + } - DestroySpawner(self->GetVar(FXManagerSpawner)); - self->SetVar(u"FXObjectGone", true); - } + DestroySpawner(self->GetVar(FXManagerSpawner)); + self->SetVar(u"FXObjectGone", true); + } } void BasePropertyServer::HandleOrbsTimer(Entity* self) { - self->SetVar(CollidedVariable, false); - auto orbs = EntityManager::Instance()->GetEntitiesInGroup(self->GetVar(ImagOrbGroup)); - if (orbs.empty()) { - self->AddTimer(StartOrbTimer, 0.5f); - return; - } + self->SetVar(CollidedVariable, false); + auto orbs = EntityManager::Instance()->GetEntitiesInGroup(self->GetVar(ImagOrbGroup)); + if (orbs.empty()) { + self->AddTimer(StartOrbTimer, 0.5f); + return; + } - for (auto* orb : orbs) { - orb->AddCollisionPhantomCallback([self, this](Entity* other) { - if (other != nullptr && other->IsPlayer() && !self->GetVar(CollidedVariable)) { - self->SetVar(CollidedVariable, true); + for (auto* orb : orbs) { + orb->AddCollisionPhantomCallback([self, this](Entity* other) { + if (other != nullptr && other->IsPlayer() && !self->GetVar(CollidedVariable)) { + self->SetVar(CollidedVariable, true); - KillClouds(self); - DeactivateSpawner(self->GetVar(GeneratorSpawner)); + KillClouds(self); + DeactivateSpawner(self->GetVar(GeneratorSpawner)); - for (const auto& enemySpawner : self->GetVar>(EnemiesSpawner)) { - DeactivateSpawner(enemySpawner); - } + for (const auto& enemySpawner : self->GetVar>(EnemiesSpawner)) { + DeactivateSpawner(enemySpawner); + } - DestroySpawner(self->GetVar(GeneratorFXSpawner)); - GameMessages::SendNotifyClientObject(EntityManager::Instance()->GetZoneControlEntity()->GetObjectID(), - u"PlayCinematic", 0, 0, LWOOBJID_EMPTY, - "DestroyMaelstrom", UNASSIGNED_SYSTEM_ADDRESS); + DestroySpawner(self->GetVar(GeneratorFXSpawner)); + GameMessages::SendNotifyClientObject(EntityManager::Instance()->GetZoneControlEntity()->GetObjectID(), + u"PlayCinematic", 0, 0, LWOOBJID_EMPTY, + "DestroyMaelstrom", UNASSIGNED_SYSTEM_ADDRESS); - // Notifies the client that the property has been claimed with a flag, completes missions too - auto* player = EntityManager::Instance()->GetEntity(self->GetVar(PlayerIDVariable)); - if (player != nullptr) { - auto* character = player->GetCharacter(); - if (character != nullptr) { - character->SetPlayerFlag(self->GetVar(defeatedProperyFlag), true); - } - } + // Notifies the client that the property has been claimed with a flag, completes missions too + auto* player = EntityManager::Instance()->GetEntity(self->GetVar(PlayerIDVariable)); + if (player != nullptr) { + auto* character = player->GetCharacter(); + if (character != nullptr) { + character->SetPlayerFlag(self->GetVar(defeatedProperyFlag), true); + } + } - self->AddTimer(TornadoOffTimer, 0.5f); - self->AddTimer(KillMarkerTimer, 0.7f); - } - }); - } + self->AddTimer(TornadoOffTimer, 0.5f); + self->AddTimer(KillMarkerTimer, 0.7f); + } + }); + } } void BasePropertyServer::HandleGeneratorTimer(Entity* self) { - auto generators = EntityManager::Instance()->GetEntitiesInGroup(self->GetVar(GeneratorGroup)); - if (generators.empty()) { - self->AddTimer(StartGeneratorTimer, 0.5f); - return; - } + auto generators = EntityManager::Instance()->GetEntitiesInGroup(self->GetVar(GeneratorGroup)); + if (generators.empty()) { + self->AddTimer(StartGeneratorTimer, 0.5f); + return; + } - for (auto* generator : generators) { - generator->AddDieCallback([self, this]() { - ActivateSpawner(self->GetVar(ClaimMarkerSpawner)); - self->AddTimer(StartQuickbuildTimer, 0.0f); + for (auto* generator : generators) { + generator->AddDieCallback([self, this]() { + ActivateSpawner(self->GetVar(ClaimMarkerSpawner)); + self->AddTimer(StartQuickbuildTimer, 0.0f); - for (const auto& enemySpawner : self->GetVar>(EnemiesSpawner)) { - DeactivateSpawner(enemySpawner); - } - DeactivateSpawner(self->GetVar(GeneratorSpawner)); - }); - } + for (const auto& enemySpawner : self->GetVar>(EnemiesSpawner)) { + DeactivateSpawner(enemySpawner); + } + DeactivateSpawner(self->GetVar(GeneratorSpawner)); + }); + } } void BasePropertyServer::HandleQuickBuildTimer(Entity* self) { - auto claimMarkers = EntityManager::Instance()->GetEntitiesInGroup(self->GetVar(ClaimMarkerGroup)); - if (claimMarkers.empty()) { - self->AddTimer(StartQuickbuildTimer, 0.5f); - return; - } + auto claimMarkers = EntityManager::Instance()->GetEntitiesInGroup(self->GetVar(ClaimMarkerGroup)); + if (claimMarkers.empty()) { + self->AddTimer(StartQuickbuildTimer, 0.5f); + return; + } - for (auto* claimMarker : claimMarkers) { - // TODO: Send password? - } + for (auto* claimMarker : claimMarkers) { + // TODO: Send password? + } } diff --git a/dScripts/BasePropertyServer.h b/dScripts/BasePropertyServer.h index 79a52f54..da2d315b 100644 --- a/dScripts/BasePropertyServer.h +++ b/dScripts/BasePropertyServer.h @@ -4,24 +4,24 @@ class BasePropertyServer : public CppScripts::Script { public: - virtual void SetGameVariables(Entity* self); - virtual void CheckForOwner(Entity* self); - virtual void PropGuardCheck(Entity* self, Entity* player); + virtual void SetGameVariables(Entity* self); + virtual void CheckForOwner(Entity* self); + virtual void PropGuardCheck(Entity* self, Entity* player); - void OnStartup(Entity *self) override; - void OnFireEventServerSide(Entity *self, Entity *sender, std::string args, int32_t param1, int32_t param2, - int32_t param3) override; - void OnPlayerLoaded(Entity *self, Entity *player) override { BasePlayerLoaded(self, player); }; - void OnPlayerExit(Entity *self, Entity *player) override { BasePlayerExit(self, player); }; - void OnZonePropertyModelPlaced(Entity *self, Entity *player) override { BaseZonePropertyModelPlaced(self, player); } - void OnZonePropertyRented(Entity *self, Entity* renter) override { BaseZonePropertyRented(self, renter); }; - void OnTimerDone(Entity *self, std::string timerName) override { BaseTimerDone(self, timerName); }; + void OnStartup(Entity* self) override; + void OnFireEventServerSide(Entity* self, Entity* sender, std::string args, int32_t param1, int32_t param2, + int32_t param3) override; + void OnPlayerLoaded(Entity* self, Entity* player) override { BasePlayerLoaded(self, player); }; + void OnPlayerExit(Entity* self, Entity* player) override { BasePlayerExit(self, player); }; + void OnZonePropertyModelPlaced(Entity* self, Entity* player) override { BaseZonePropertyModelPlaced(self, player); } + void OnZonePropertyRented(Entity* self, Entity* renter) override { BaseZonePropertyRented(self, renter); }; + void OnTimerDone(Entity* self, std::string timerName) override { BaseTimerDone(self, timerName); }; virtual void BasePlayerLoaded(Entity* self, Entity* player); virtual void BaseZonePropertyRented(Entity* self, Entity* player) const; virtual void BaseZonePropertyModelPlaced(Entity* self, Entity* player) const; - virtual void BasePlayerExit(Entity *self, Entity *player); - virtual void BaseTimerDone(Entity* self, const std::string& timerName); + virtual void BasePlayerExit(Entity* self, Entity* player); + virtual void BaseTimerDone(Entity* self, const std::string& timerName); void KillClouds(Entity* self); virtual void SpawnSpots(Entity* self); @@ -39,79 +39,79 @@ public: static LWOOBJID GetOwner(); protected: - void HandleOrbsTimer(Entity* self); - void HandleGeneratorTimer(Entity* self); - void HandleQuickBuildTimer(Entity* self); + void HandleOrbsTimer(Entity* self); + void HandleGeneratorTimer(Entity* self); + void HandleQuickBuildTimer(Entity* self); - // GUIDs - std::string GUIDMaelstrom = "{7881e0a1-ef6d-420c-8040-f59994aa3357}"; - std::string GUIDPeaceful = "{c5725665-58d0-465f-9e11-aeb1d21842ba}"; + // GUIDs + std::string GUIDMaelstrom = "{7881e0a1-ef6d-420c-8040-f59994aa3357}"; + std::string GUIDPeaceful = "{c5725665-58d0-465f-9e11-aeb1d21842ba}"; - // Groups - std::u16string PropertyPlaqueGroup = u"PropertyPlaqueGroup"; - std::u16string PropertyVendorGroup = u"PropertyVendorGroup"; - std::u16string PropertyBorderGroup = u"PropertyBorderGroup"; - std::u16string SpotsGroup = u"SpotsGroup"; - std::u16string MSCloudsGroup = u"MSCloudsGroup"; - std::u16string GeneratorFXGroup = u"GeneratorFXGroup"; - std::u16string GeneratorGroup = u"GeneratorGroup"; - std::u16string ImagOrbGroup = u"ImagOrbGroup"; - std::u16string FXManagerGroup = u"FXManagerGroup"; - std::u16string ClaimMarkerGroup = u"ClaimMarkerGroup"; - std::u16string GuardGroup = u"GuardGroup"; - std::u16string EnemiesGroup = u"EnemiesGroup"; + // Groups + std::u16string PropertyPlaqueGroup = u"PropertyPlaqueGroup"; + std::u16string PropertyVendorGroup = u"PropertyVendorGroup"; + std::u16string PropertyBorderGroup = u"PropertyBorderGroup"; + std::u16string SpotsGroup = u"SpotsGroup"; + std::u16string MSCloudsGroup = u"MSCloudsGroup"; + std::u16string GeneratorFXGroup = u"GeneratorFXGroup"; + std::u16string GeneratorGroup = u"GeneratorGroup"; + std::u16string ImagOrbGroup = u"ImagOrbGroup"; + std::u16string FXManagerGroup = u"FXManagerGroup"; + std::u16string ClaimMarkerGroup = u"ClaimMarkerGroup"; + std::u16string GuardGroup = u"GuardGroup"; + std::u16string EnemiesGroup = u"EnemiesGroup"; - // Spawners - std::u16string EnemiesSpawner = u"EnemiesSpawner"; - std::u16string PropObjsSpawner = u"PropObjsSpawner"; - std::u16string PropertyMGSpawner = u"PropertyMGSpawner"; - std::u16string DamageFXSpawner = u"DamageFXSpawner"; - std::u16string FXSpotsSpawner = u"FXSpotsSpawner"; - std::u16string GeneratorSpawner = u"GeneratorSpawner"; - std::u16string GeneratorFXSpawner = u"GeneratorFXSpawner"; - std::u16string FXManagerSpawner = u"FXManagerSpawner"; - std::u16string ImageOrbSpawner = u"ImageOrbSpawner"; - std::u16string AmbientFXSpawner = u"AmbientFXSpawners"; - std::u16string SmashablesSpawner = u"SmashablesSpawner"; - std::u16string ClaimMarkerSpawner = u"ClaimMarkerSpawner"; - std::u16string BehaviorObjsSpawner = u"BehaviorObjsSpawner"; + // Spawners + std::u16string EnemiesSpawner = u"EnemiesSpawner"; + std::u16string PropObjsSpawner = u"PropObjsSpawner"; + std::u16string PropertyMGSpawner = u"PropertyMGSpawner"; + std::u16string DamageFXSpawner = u"DamageFXSpawner"; + std::u16string FXSpotsSpawner = u"FXSpotsSpawner"; + std::u16string GeneratorSpawner = u"GeneratorSpawner"; + std::u16string GeneratorFXSpawner = u"GeneratorFXSpawner"; + std::u16string FXManagerSpawner = u"FXManagerSpawner"; + std::u16string ImageOrbSpawner = u"ImageOrbSpawner"; + std::u16string AmbientFXSpawner = u"AmbientFXSpawners"; + std::u16string SmashablesSpawner = u"SmashablesSpawner"; + std::u16string ClaimMarkerSpawner = u"ClaimMarkerSpawner"; + std::u16string BehaviorObjsSpawner = u"BehaviorObjsSpawner"; - //Flags / constants - std::u16string guardFirstMissionFlag = u"guardFirstMissionFlag"; - std::u16string guardMissionFlag = u"guardMissionFlag"; - std::u16string brickLinkMissionIDFlag = u"brickLinkMissionIDFlag"; - std::u16string placedModelFlag = u"placedModelFlag"; - std::u16string generatorIdFlag = u"generatorIdFlag"; - std::u16string defeatedProperyFlag = u"defeatedProperyFlag"; - std::u16string passwordFlag = u"passwordFlag"; - std::u16string orbIDFlag = u"orbIDFlag"; - std::u16string behaviorQBID = u"behaviorQBID"; + //Flags / constants + std::u16string guardFirstMissionFlag = u"guardFirstMissionFlag"; + std::u16string guardMissionFlag = u"guardMissionFlag"; + std::u16string brickLinkMissionIDFlag = u"brickLinkMissionIDFlag"; + std::u16string placedModelFlag = u"placedModelFlag"; + std::u16string generatorIdFlag = u"generatorIdFlag"; + std::u16string defeatedProperyFlag = u"defeatedProperyFlag"; + std::u16string passwordFlag = u"passwordFlag"; + std::u16string orbIDFlag = u"orbIDFlag"; + std::u16string behaviorQBID = u"behaviorQBID"; - // Variables - std::u16string PlayerIDVariable = u"playerID"; - std::u16string CollidedVariable = u"collided"; - std::u16string PropertyOwnerVariable = u"PropertyOwner"; - std::u16string PropertyOwnerIDVariable = u"PropertyOwnerID"; - std::u16string FXObjectsGoneVariable = u"FXObjectGone"; - std::u16string RenterVariable = u"renter"; - std::u16string UnclaimedVariable = u"unclaimed"; + // Variables + std::u16string PlayerIDVariable = u"playerID"; + std::u16string CollidedVariable = u"collided"; + std::u16string PropertyOwnerVariable = u"PropertyOwner"; + std::u16string PropertyOwnerIDVariable = u"PropertyOwnerID"; + std::u16string FXObjectsGoneVariable = u"FXObjectGone"; + std::u16string RenterVariable = u"renter"; + std::u16string UnclaimedVariable = u"unclaimed"; - // Events - std::string CheckForPropertyOwnerEvent = "CheckForPropertyOwner"; + // Events + std::string CheckForPropertyOwnerEvent = "CheckForPropertyOwner"; - // Timers - std::string StartGeneratorTimer = "startGenerator"; - std::string StartOrbTimer = "startOrb"; - std::string StartQuickbuildTimer = "startQuickbuild"; - std::string TornadoOffTimer = "tornadoOff"; - std::string KillMarkerTimer = "killMarker"; - std::string KillGuardTimer = "KillGuard"; - std::string ShowClearEffectsTimer = "ShowClearEffects"; - std::string TurnSkyOffTimer = "turnSkyOff"; - std::string KillStrombiesTimer = "killStrombies"; - std::string KillFXObjectTimer = "killFXObject"; - std::string ShowVendorTimer = "ShowVendor"; - std::string BoundsVisOnTimer = "BoundsVisOn"; - std::string RunPlayerLoadedAgainTimer = "runPlayerLoadedAgain"; - std::string PollTornadoFXTimer = "pollTornadoFX"; + // Timers + std::string StartGeneratorTimer = "startGenerator"; + std::string StartOrbTimer = "startOrb"; + std::string StartQuickbuildTimer = "startQuickbuild"; + std::string TornadoOffTimer = "tornadoOff"; + std::string KillMarkerTimer = "killMarker"; + std::string KillGuardTimer = "KillGuard"; + std::string ShowClearEffectsTimer = "ShowClearEffects"; + std::string TurnSkyOffTimer = "turnSkyOff"; + std::string KillStrombiesTimer = "killStrombies"; + std::string KillFXObjectTimer = "killFXObject"; + std::string ShowVendorTimer = "ShowVendor"; + std::string BoundsVisOnTimer = "BoundsVisOn"; + std::string RunPlayerLoadedAgainTimer = "runPlayerLoadedAgain"; + std::string PollTornadoFXTimer = "pollTornadoFX"; }; diff --git a/dScripts/BaseRandomServer.cpp b/dScripts/BaseRandomServer.cpp index c2d335c4..8cc4f993 100644 --- a/dScripts/BaseRandomServer.cpp +++ b/dScripts/BaseRandomServer.cpp @@ -4,199 +4,169 @@ #include "dLogger.h" #include "Entity.h" -void BaseRandomServer::BaseStartup(Entity* self) -{ - self->SetVar(u"SpawnState", "min"); - self->SetVar(u"JustChanged", false); +void BaseRandomServer::BaseStartup(Entity* self) { + self->SetVar(u"SpawnState", "min"); + self->SetVar(u"JustChanged", false); - CheckEvents(self); - SpawnMapZones(self); + CheckEvents(self); + SpawnMapZones(self); } -void BaseRandomServer::CheckEvents(Entity* self) -{ - // TODO: Add events? +void BaseRandomServer::CheckEvents(Entity* self) { + // TODO: Add events? } -void BaseRandomServer::SpawnMapZones(Entity* self) -{ - for (const auto& pair : sectionMultipliers) - { - const auto sectionName = zonePrefix + "_" + zoneName + "_" + pair.first; +void BaseRandomServer::SpawnMapZones(Entity* self) { + for (const auto& pair : sectionMultipliers) { + const auto sectionName = zonePrefix + "_" + zoneName + "_" + pair.first; - SpawnSection(self, sectionName, pair.second); - } + SpawnSection(self, sectionName, pair.second); + } - if (zoneName == "str") - { - SpawnNamedEnemy(self); - } + if (zoneName == "str") { + SpawnNamedEnemy(self); + } - self->SetVar(u"bInit", true); + self->SetVar(u"bInit", true); } -void BaseRandomServer::SpawnSection(Entity* self, const std::string& sectionName, float iMultiplier) -{ - Zone* spawnLoad = GetRandomLoad(self, sectionName); +void BaseRandomServer::SpawnSection(Entity* self, const std::string& sectionName, float iMultiplier) { + Zone* spawnLoad = GetRandomLoad(self, sectionName); - if (spawnLoad == nullptr) - { - Game::logger->Log("BaseRandomServer", "Failed to find section: %s", sectionName.c_str()); + if (spawnLoad == nullptr) { + Game::logger->Log("BaseRandomServer", "Failed to find section: %s", sectionName.c_str()); - return; - } + return; + } - for (const auto& spawnerData : spawnLoad->entries) - { - if (spawnerData.name.empty()) - { - continue; - } + for (const auto& spawnerData : spawnLoad->entries) { + if (spawnerData.name.empty()) { + continue; + } - const auto spawnNum = std::floor(spawnerData.num * iMultiplier); - const auto spawnerName = sectionName + "_" + spawnerData.name; + const auto spawnNum = std::floor(spawnerData.num * iMultiplier); + const auto spawnerName = sectionName + "_" + spawnerData.name; - SetSpawnerNetwork(self, spawnerName, spawnNum, spawnerData.lot); - } + SetSpawnerNetwork(self, spawnerName, spawnNum, spawnerData.lot); + } } -void BaseRandomServer::SetSpawnerNetwork(Entity* self, const std::string& spawnerName, int32_t spawnNum, LOT spawnLOT) -{ - const auto& spawners = dZoneManager::Instance()->GetSpawnersByName(spawnerName); +void BaseRandomServer::SetSpawnerNetwork(Entity* self, const std::string& spawnerName, int32_t spawnNum, LOT spawnLOT) { + const auto& spawners = dZoneManager::Instance()->GetSpawnersByName(spawnerName); - if (spawnLOT == 11217 && spawnNum > 1) - { - spawnNum = 1; - } + if (spawnLOT == 11217 && spawnNum > 1) { + spawnNum = 1; + } - if (spawners.empty()) - { - Game::logger->Log("BaseRandomServer", "Failed to find spawner: %s", spawnerName.c_str()); + if (spawners.empty()) { + Game::logger->Log("BaseRandomServer", "Failed to find spawner: %s", spawnerName.c_str()); - return; - } + return; + } - auto* spawner = spawners[0]; + auto* spawner = spawners[0]; - if (spawnLOT != 0) - { - spawner->SetSpawnLot(spawnLOT); - spawner->SetRespawnTime(respawnTime); - } + if (spawnLOT != 0) { + spawner->SetSpawnLot(spawnLOT); + spawner->SetRespawnTime(respawnTime); + } - if (spawnNum != 0) - { - spawner->SetNumToMaintain(spawnNum); - } + if (spawnNum != 0) { + spawner->SetNumToMaintain(spawnNum); + } - if (spawnerName == "Named_Enemies") - { - spawner->SoftReset(); - } + if (spawnerName == "Named_Enemies") { + spawner->SoftReset(); + } - spawner->Activate(); + spawner->Activate(); - if (std::find(spawnersWatched.begin(), spawnersWatched.end(), spawner) != spawnersWatched.end()) - { - return; - } + if (std::find(spawnersWatched.begin(), spawnersWatched.end(), spawner) != spawnersWatched.end()) { + return; + } - spawner->AddSpawnedEntityDieCallback([this, self, spawner] () { - NotifySpawnerOfDeath(self, spawner); - }); + spawner->AddSpawnedEntityDieCallback([this, self, spawner]() { + NotifySpawnerOfDeath(self, spawner); + }); - spawnersWatched.push_back(spawner); + spawnersWatched.push_back(spawner); } -BaseRandomServer::Zone* BaseRandomServer::GetRandomLoad(Entity* self, const std::string& sectionName) -{ - const auto zoneInfo = GeneralUtils::SplitString(sectionName, '_'); +BaseRandomServer::Zone* BaseRandomServer::GetRandomLoad(Entity* self, const std::string& sectionName) { + const auto zoneInfo = GeneralUtils::SplitString(sectionName, '_'); - int32_t totalWeight = 0; + int32_t totalWeight = 0; - for (const auto& load : zones) - { - totalWeight += load.iChance; - } + for (const auto& load : zones) { + totalWeight += load.iChance; + } - const auto randWeight = GeneralUtils::GenerateRandomNumber(0, totalWeight); + const auto randWeight = GeneralUtils::GenerateRandomNumber(0, totalWeight); - int32_t weight = 0; - for (auto& zone : zones) - { - weight += zone.iChance; + int32_t weight = 0; + for (auto& zone : zones) { + weight += zone.iChance; - if (randWeight <= weight) - { - return &zone; - } - } + if (randWeight <= weight) { + return &zone; + } + } - return nullptr; + return nullptr; } -void BaseRandomServer::NotifySpawnerOfDeath(Entity* self, Spawner* spawner) -{ - const auto& spawnerName = spawner->GetName(); +void BaseRandomServer::NotifySpawnerOfDeath(Entity* self, Spawner* spawner) { + const auto& spawnerName = spawner->GetName(); - if (spawnerName == "Named_Enemies") - { - NamedEnemyDeath(self, spawner); + if (spawnerName == "Named_Enemies") { + NamedEnemyDeath(self, spawner); - return; - } + return; + } - const auto& sectionName = spawnerName.substr(0, spawnerName.size() - 7); + const auto& sectionName = spawnerName.substr(0, spawnerName.size() - 7); - const auto variableName = u"mobsDead" + GeneralUtils::ASCIIToUTF16(sectionName); + const auto variableName = u"mobsDead" + GeneralUtils::ASCIIToUTF16(sectionName); - auto mobDeathCount = self->GetVar(variableName); + auto mobDeathCount = self->GetVar(variableName); - mobDeathCount++; + mobDeathCount++; - if (mobDeathCount >= mobDeathResetNumber) - { - const auto& zoneInfo = GeneralUtils::SplitString(sectionName, '_'); + if (mobDeathCount >= mobDeathResetNumber) { + const auto& zoneInfo = GeneralUtils::SplitString(sectionName, '_'); - SpawnSection(self, sectionName, sectionMultipliers[zoneInfo[sectionIDConst - 1]]); - } + SpawnSection(self, sectionName, sectionMultipliers[zoneInfo[sectionIDConst - 1]]); + } - self->SetVar(variableName, mobDeathCount); + self->SetVar(variableName, mobDeathCount); } -void BaseRandomServer::NamedEnemyDeath(Entity* self, Spawner* spawner) -{ - const auto spawnDelay = GeneralUtils::GenerateRandomNumber(1, 2) * 450; +void BaseRandomServer::NamedEnemyDeath(Entity* self, Spawner* spawner) { + const auto spawnDelay = GeneralUtils::GenerateRandomNumber(1, 2) * 450; - self->AddTimer("SpawnNewEnemy", spawnDelay); + self->AddTimer("SpawnNewEnemy", spawnDelay); } -void BaseRandomServer::SpawnersUp(Entity* self) -{ +void BaseRandomServer::SpawnersUp(Entity* self) { } -void BaseRandomServer::SpawnersDown(Entity* self) -{ +void BaseRandomServer::SpawnersDown(Entity* self) { } -void BaseRandomServer::BaseOnTimerDone(Entity* self, const std::string& timerName) -{ - NamedTimerDone(self, timerName); +void BaseRandomServer::BaseOnTimerDone(Entity* self, const std::string& timerName) { + NamedTimerDone(self, timerName); } -void BaseRandomServer::SpawnNamedEnemy(Entity* self) -{ - const auto enemy = namedMobs[GeneralUtils::GenerateRandomNumber(0, namedMobs.size() - 1)]; +void BaseRandomServer::SpawnNamedEnemy(Entity* self) { + const auto enemy = namedMobs[GeneralUtils::GenerateRandomNumber(0, namedMobs.size() - 1)]; - SetSpawnerNetwork(self, "Named_Enemies", 1, enemy); + SetSpawnerNetwork(self, "Named_Enemies", 1, enemy); } -void BaseRandomServer::NamedTimerDone(Entity* self, const std::string& timerName) -{ - if (timerName == "SpawnNewEnemy") - { - SpawnNamedEnemy(self); - } +void BaseRandomServer::NamedTimerDone(Entity* self, const std::string& timerName) { + if (timerName == "SpawnNewEnemy") { + SpawnNamedEnemy(self); + } } diff --git a/dScripts/BaseRandomServer.h b/dScripts/BaseRandomServer.h index 68aadf30..bc5d6b21 100644 --- a/dScripts/BaseRandomServer.h +++ b/dScripts/BaseRandomServer.h @@ -6,54 +6,54 @@ class Spawner; class BaseRandomServer { public: - struct ZoneEntry - { - LOT lot; - int32_t num; - std::string name; - }; + struct ZoneEntry + { + LOT lot; + int32_t num; + std::string name; + }; - struct Zone - { - std::vector entries; - int32_t iChance; - }; + struct Zone + { + std::vector entries; + int32_t iChance; + }; - void BaseStartup(Entity* self); - void CheckEvents(Entity* self); - void SpawnMapZones(Entity* self); - void SpawnSection(Entity* self, const std::string& sectionName, float iMultiplier); - void SetSpawnerNetwork(Entity* self, const std::string& spawnerName, int32_t spawnNum, LOT spawnLOT); - BaseRandomServer::Zone* GetRandomLoad(Entity* self, const std::string& sectionName); - void SpawnersUp(Entity* self); - void SpawnersDown(Entity* self); - void BaseOnTimerDone(Entity* self, const std::string& timerName); - - void NotifySpawnerOfDeath(Entity* self, Spawner* spawner); - void NamedEnemyDeath(Entity* self, Spawner* spawner); + void BaseStartup(Entity* self); + void CheckEvents(Entity* self); + void SpawnMapZones(Entity* self); + void SpawnSection(Entity* self, const std::string& sectionName, float iMultiplier); + void SetSpawnerNetwork(Entity* self, const std::string& spawnerName, int32_t spawnNum, LOT spawnLOT); + BaseRandomServer::Zone* GetRandomLoad(Entity* self, const std::string& sectionName); + void SpawnersUp(Entity* self); + void SpawnersDown(Entity* self); + void BaseOnTimerDone(Entity* self, const std::string& timerName); - void SpawnNamedEnemy(Entity* self); + void NotifySpawnerOfDeath(Entity* self, Spawner* spawner); + void NamedEnemyDeath(Entity* self, Spawner* spawner); - void NamedTimerDone(Entity* self, const std::string& timerName); + void SpawnNamedEnemy(Entity* self); + + void NamedTimerDone(Entity* self, const std::string& timerName); protected: - std::vector namedMobs = { - 11988, // Ronin - 11984, // Spiderling - 12654, // Horsemen - 11986, // Admiral - 11983, // Mech - 11982, // Stromling - 11985 // Pirate - }; - std::map sectionMultipliers = {}; - int32_t mobDeathResetNumber = 30; - std::string zonePrefix = "em"; - int32_t zoneNameConst = 2; - int32_t sectionIDConst = 3; - std::string zoneName = "fin"; - std::vector zones = {}; - int32_t changeNum = 15; - int32_t respawnTime = 80; - std::vector spawnersWatched; + std::vector namedMobs = { + 11988, // Ronin + 11984, // Spiderling + 12654, // Horsemen + 11986, // Admiral + 11983, // Mech + 11982, // Stromling + 11985 // Pirate + }; + std::map sectionMultipliers = {}; + int32_t mobDeathResetNumber = 30; + std::string zonePrefix = "em"; + int32_t zoneNameConst = 2; + int32_t sectionIDConst = 3; + std::string zoneName = "fin"; + std::vector zones = {}; + int32_t changeNum = 15; + int32_t respawnTime = 80; + std::vector spawnersWatched; }; diff --git a/dScripts/BaseSurvivalServer.cpp b/dScripts/BaseSurvivalServer.cpp index f6a326e8..270b6741 100644 --- a/dScripts/BaseSurvivalServer.cpp +++ b/dScripts/BaseSurvivalServer.cpp @@ -8,570 +8,566 @@ #include "MissionComponent.h" #include "Character.h" -void BaseSurvivalServer::SetGameVariables(Entity *self) { - this->constants = std::move(GetConstants()); - this->mobSets = std::move(GetMobSets()); - this->spawnerNetworks = std::move(GetSpawnerNetworks()); - this->missionsToUpdate = std::move(GetMissionsToUpdate()); +void BaseSurvivalServer::SetGameVariables(Entity* self) { + this->constants = std::move(GetConstants()); + this->mobSets = std::move(GetMobSets()); + this->spawnerNetworks = std::move(GetSpawnerNetworks()); + this->missionsToUpdate = std::move(GetMissionsToUpdate()); } void BaseSurvivalServer::BasePlayerLoaded(Entity* self, Entity* player) { - const auto& waitingIter = std::find(state.waitingPlayers.begin(), state.waitingPlayers.end(), player->GetObjectID()); - const auto& playersIter = std::find(state.players.begin(), state.players.end(), player->GetObjectID()); + const auto& waitingIter = std::find(state.waitingPlayers.begin(), state.waitingPlayers.end(), player->GetObjectID()); + const auto& playersIter = std::find(state.players.begin(), state.players.end(), player->GetObjectID()); - if (waitingIter != state.waitingPlayers.end() || playersIter != state.players.end()) - { - static_cast(player)->SendToZone(player->GetCharacter()->GetLastNonInstanceZoneID()); + if (waitingIter != state.waitingPlayers.end() || playersIter != state.players.end()) { + static_cast(player)->SendToZone(player->GetCharacter()->GetLastNonInstanceZoneID()); - return; - } + return; + } - state.waitingPlayers.push_back(player->GetObjectID()); - state.players.push_back(player->GetObjectID()); + state.waitingPlayers.push_back(player->GetObjectID()); + state.players.push_back(player->GetObjectID()); - self->SetNetworkVar(NumberOfPlayersVariable, self->GetNetworkVar(NumberOfPlayersVariable) + 1); - self->SetNetworkVar(DefinePlayerToUIVariable, std::to_string(player->GetObjectID()), player->GetSystemAddress()); + self->SetNetworkVar(NumberOfPlayersVariable, self->GetNetworkVar(NumberOfPlayersVariable) + 1); + self->SetNetworkVar(DefinePlayerToUIVariable, std::to_string(player->GetObjectID()), player->GetSystemAddress()); - // Notify the players of all other players - if (!self->GetNetworkVar(WavesStartedVariable)) { - auto counter = 1; - for (const auto& playerID : state.players) { - self->SetNetworkVar(UpdateScoreboardPlayersVariable + GeneralUtils::to_u16string(counter), std::to_string(playerID)); - counter++; - } + // Notify the players of all other players + if (!self->GetNetworkVar(WavesStartedVariable)) { + auto counter = 1; + for (const auto& playerID : state.players) { + self->SetNetworkVar(UpdateScoreboardPlayersVariable + GeneralUtils::to_u16string(counter), std::to_string(playerID)); + counter++; + } - self->SetNetworkVar(ShowScoreboardVariable, true); - } + self->SetNetworkVar(ShowScoreboardVariable, true); + } - SetPlayerSpawnPoints(); + SetPlayerSpawnPoints(); - if (!self->GetNetworkVar(WavesStartedVariable)) { - PlayerConfirmed(self); - } else { - UpdatePlayer(self, player->GetObjectID()); - GetLeaderboardData(self, player->GetObjectID(), GetActivityID(self), 50); - ResetStats(player->GetObjectID()); - } + if (!self->GetNetworkVar(WavesStartedVariable)) { + PlayerConfirmed(self); + } else { + UpdatePlayer(self, player->GetObjectID()); + GetLeaderboardData(self, player->GetObjectID(), GetActivityID(self), 50); + ResetStats(player->GetObjectID()); + } - player->AddCallbackTimer(5.0f, [this, self, player] () { - self->SetNetworkVar(NumberOfPlayersVariable, self->GetNetworkVar(NumberOfPlayersVariable)); - self->SetNetworkVar(DefinePlayerToUIVariable, std::to_string(player->GetObjectID()), player->GetSystemAddress()); - if (!self->GetNetworkVar(WavesStartedVariable)) { - auto counter = 1; - for (const auto& playerID : state.players) { - self->SetNetworkVar(UpdateScoreboardPlayersVariable + GeneralUtils::to_u16string(counter), std::to_string(playerID)); - counter++; - } + player->AddCallbackTimer(5.0f, [this, self, player]() { + self->SetNetworkVar(NumberOfPlayersVariable, self->GetNetworkVar(NumberOfPlayersVariable)); + self->SetNetworkVar(DefinePlayerToUIVariable, std::to_string(player->GetObjectID()), player->GetSystemAddress()); + if (!self->GetNetworkVar(WavesStartedVariable)) { + auto counter = 1; + for (const auto& playerID : state.players) { + self->SetNetworkVar(UpdateScoreboardPlayersVariable + GeneralUtils::to_u16string(counter), std::to_string(playerID)); + counter++; + } - self->SetNetworkVar(ShowScoreboardVariable, true); - } - }); + self->SetNetworkVar(ShowScoreboardVariable, true); + } + }); } void BaseSurvivalServer::BaseStartup(Entity* self) { - self->SetVar(PlayersAcceptedVariable, 0); - self->SetVar(PlayersReadyVariable, false); + self->SetVar(PlayersAcceptedVariable, 0); + self->SetVar(PlayersReadyVariable, false); } void BaseSurvivalServer::BasePlayerExit(Entity* self, Entity* player) { - const auto& waitingIter = std::find(state.waitingPlayers.begin(), state.waitingPlayers.end(), player->GetObjectID()); - const auto& playersIter = std::find(state.players.begin(), state.players.end(), player->GetObjectID()); + const auto& waitingIter = std::find(state.waitingPlayers.begin(), state.waitingPlayers.end(), player->GetObjectID()); + const auto& playersIter = std::find(state.players.begin(), state.players.end(), player->GetObjectID()); - if (waitingIter != state.waitingPlayers.end()) - { - state.waitingPlayers.erase(waitingIter); - } + if (waitingIter != state.waitingPlayers.end()) { + state.waitingPlayers.erase(waitingIter); + } - if (playersIter != state.players.end()) - { - state.players.erase(playersIter); - } + if (playersIter != state.players.end()) { + state.players.erase(playersIter); + } - if (waitingIter == state.waitingPlayers.end() && playersIter == state.players.end()) - { - return; - } + if (waitingIter == state.waitingPlayers.end() && playersIter == state.players.end()) { + return; + } - if (!self->GetNetworkVar(WavesStartedVariable)) { - PlayerConfirmed(self); + if (!self->GetNetworkVar(WavesStartedVariable)) { + PlayerConfirmed(self); - if (state.players.empty()) - return; + if (state.players.empty()) + return; - if (state.waitingPlayers.empty()) { - ActivityTimerStopAllTimers(self); - ActivityTimerStart(self, AllAcceptedDelayTimer, 1.0f, constants.startDelay); - } else if (state.players.size() > state.waitingPlayers.size()) { - if (!self->GetVar(AcceptedDelayStartedVariable)) { - self->SetVar(AcceptedDelayStartedVariable, true); - ActivityTimerStart(self, AcceptedDelayTimer, 1.0f, constants.acceptedDelay); - } - } - } else { - UpdatePlayer(self, player->GetObjectID(), true); - if (CheckAllPlayersDead()) { - GameOver(self); - } - } + if (state.waitingPlayers.empty()) { + ActivityTimerStopAllTimers(self); + ActivityTimerStart(self, AllAcceptedDelayTimer, 1.0f, constants.startDelay); + } else if (state.players.size() > state.waitingPlayers.size()) { + if (!self->GetVar(AcceptedDelayStartedVariable)) { + self->SetVar(AcceptedDelayStartedVariable, true); + ActivityTimerStart(self, AcceptedDelayTimer, 1.0f, constants.acceptedDelay); + } + } + } else { + UpdatePlayer(self, player->GetObjectID(), true); + if (CheckAllPlayersDead()) { + GameOver(self); + } + } - SetActivityValue(self, player->GetObjectID(), 1, 0); - self->SetNetworkVar(NumberOfPlayersVariable, - std::min((uint32_t) 0, self->GetNetworkVar(NumberOfPlayersVariable) - 1)); + SetActivityValue(self, player->GetObjectID(), 1, 0); + self->SetNetworkVar(NumberOfPlayersVariable, + std::min((uint32_t)0, self->GetNetworkVar(NumberOfPlayersVariable) - 1)); } void BaseSurvivalServer::BaseFireEvent(Entity* self, Entity* sender, const std::string& args, int32_t param1, int32_t param2, - int32_t param3) { - if (args == "start") { - StartWaves(self); - } else if (args == "DeactivateRewards") { - SpawnerReset(spawnerNetworks.rewardNetworks); - } else if (sender != nullptr && IsPlayerInActivity(self, sender->GetObjectID())) { - auto currentScore = GetActivityValue(self, sender->GetObjectID(), 0); - SetActivityValue(self, sender->GetObjectID(), 0, currentScore + param1); - } + int32_t param3) { + if (args == "start") { + StartWaves(self); + } else if (args == "DeactivateRewards") { + SpawnerReset(spawnerNetworks.rewardNetworks); + } else if (sender != nullptr && IsPlayerInActivity(self, sender->GetObjectID())) { + auto currentScore = GetActivityValue(self, sender->GetObjectID(), 0); + SetActivityValue(self, sender->GetObjectID(), 0, currentScore + param1); + } } void BaseSurvivalServer::BasePlayerDied(Entity* self, Entity* player) { - if (self->GetNetworkVar(WavesStartedVariable)) { - const auto finalTime = ActivityTimerGetCurrentTime(self, ClockTickTimer); - SetActivityValue(self, player->GetObjectID(), 1, finalTime); + if (self->GetNetworkVar(WavesStartedVariable)) { + const auto finalTime = ActivityTimerGetCurrentTime(self, ClockTickTimer); + SetActivityValue(self, player->GetObjectID(), 1, finalTime); - auto paramString = CheckAllPlayersDead() ? "true" : "false"; - GameMessages::SendNotifyClientZoneObject(self->GetObjectID(), u"Player_Died", finalTime, 0, - player->GetObjectID(), paramString, player->GetSystemAddress()); - GameOver(self); - } else { - player->Resurrect(); - SetPlayerSpawnPoints(); - } + auto paramString = CheckAllPlayersDead() ? "true" : "false"; + GameMessages::SendNotifyClientZoneObject(self->GetObjectID(), u"Player_Died", finalTime, 0, + player->GetObjectID(), paramString, player->GetSystemAddress()); + GameOver(self); + } else { + player->Resurrect(); + SetPlayerSpawnPoints(); + } } -void BaseSurvivalServer::BasePlayerResurrected(Entity *self, Entity *player) { - self->SetNetworkVar(ShowScoreboardVariable, true); +void BaseSurvivalServer::BasePlayerResurrected(Entity* self, Entity* player) { + self->SetNetworkVar(ShowScoreboardVariable, true); } void BaseSurvivalServer::BaseMessageBoxResponse(Entity* self, Entity* sender, int32_t button, - const std::u16string &identifier, const std::u16string &userData) { - if (identifier == u"RePlay") { - PlayerAccepted(self, sender->GetObjectID()); - PlayerConfirmed(self); - } else if (identifier == u"Exit_Question" && button == 1) { - ResetStats(sender->GetObjectID()); - self->SetNetworkVar(ExitWavesVariable, std::to_string(sender->GetObjectID())); + const std::u16string& identifier, const std::u16string& userData) { + if (identifier == u"RePlay") { + PlayerAccepted(self, sender->GetObjectID()); + PlayerConfirmed(self); + } else if (identifier == u"Exit_Question" && button == 1) { + ResetStats(sender->GetObjectID()); + self->SetNetworkVar(ExitWavesVariable, std::to_string(sender->GetObjectID())); - if (sender->IsPlayer()) { - auto* character = sender->GetCharacter(); - if (character != nullptr) { - auto* player = dynamic_cast(sender); - player->SendToZone(character->GetLastNonInstanceZoneID()); - } - } - } + if (sender->IsPlayer()) { + auto* character = sender->GetCharacter(); + if (character != nullptr) { + auto* player = dynamic_cast(sender); + player->SendToZone(character->GetLastNonInstanceZoneID()); + } + } + } } -void BaseSurvivalServer::OnActivityTimerUpdate(Entity *self, const std::string &name, float_t remainingTime, float_t elapsedTime) { - if (name == AcceptedDelayTimer) { - self->SetNetworkVar(UpdateDefaultStartTimerVariable, remainingTime); - } else if (name == ClockTickTimer) { - self->SetNetworkVar(UpdateTimerVariable, elapsedTime); - } else if (name == SpawnTickTimer && !self->GetVar(IsCooldownVariable)) { - SpawnMobs(self); - } +void BaseSurvivalServer::OnActivityTimerUpdate(Entity* self, const std::string& name, float_t remainingTime, float_t elapsedTime) { + if (name == AcceptedDelayTimer) { + self->SetNetworkVar(UpdateDefaultStartTimerVariable, remainingTime); + } else if (name == ClockTickTimer) { + self->SetNetworkVar(UpdateTimerVariable, elapsedTime); + } else if (name == SpawnTickTimer && !self->GetVar(IsCooldownVariable)) { + SpawnMobs(self); + } } -void BaseSurvivalServer::OnActivityTimerDone(Entity *self, const std::string &name) { - auto cooldownTime = constants.rewardInterval * constants.waveTime; +void BaseSurvivalServer::OnActivityTimerDone(Entity* self, const std::string& name) { + auto cooldownTime = constants.rewardInterval * constants.waveTime; - if (name == AcceptedDelayTimer) { - self->SetNetworkVar(UpdateDefaultStartTimerVariable, 0); - ActivityTimerStart(self, AllAcceptedDelayTimer, 1, 1); - } else if (name == AllAcceptedDelayTimer) { - self->SetNetworkVar(ClearScoreboardVariable, true); - ActivityTimerStart(self, StartDelayTimer, 3, 3); + if (name == AcceptedDelayTimer) { + self->SetNetworkVar(UpdateDefaultStartTimerVariable, 0); + ActivityTimerStart(self, AllAcceptedDelayTimer, 1, 1); + } else if (name == AllAcceptedDelayTimer) { + self->SetNetworkVar(ClearScoreboardVariable, true); + ActivityTimerStart(self, StartDelayTimer, 3, 3); - StartWaves(self); - } else if (name == StartDelayTimer) { - ActivityTimerStart(self, ClockTickTimer, 1); - ActivityTimerStart(self, SpawnTickTimer, constants.waveTime); - SpawnMobs(self); - ActivityTimerStart(self, PlaySpawnSoundTimer, 3, 3); - ActivityTimerStart(self, CoolDownStartTimer, cooldownTime, cooldownTime); - } else if (name == CoolDownStartTimer) { - self->SetVar(IsCooldownVariable, true); + StartWaves(self); + } else if (name == StartDelayTimer) { + ActivityTimerStart(self, ClockTickTimer, 1); + ActivityTimerStart(self, SpawnTickTimer, constants.waveTime); + SpawnMobs(self); + ActivityTimerStart(self, PlaySpawnSoundTimer, 3, 3); + ActivityTimerStart(self, CoolDownStartTimer, cooldownTime, cooldownTime); + } else if (name == CoolDownStartTimer) { + self->SetVar(IsCooldownVariable, true); - ActivityTimerStop(self, SpawnTickTimer); - ActivityTimerStart(self, CoolDownStopTimer, 1, constants.coolDownTime); + ActivityTimerStop(self, SpawnTickTimer); + ActivityTimerStart(self, CoolDownStopTimer, 1, constants.coolDownTime); - ActivateSpawnerNetwork(spawnerNetworks.rewardNetworks); - SpawnerReset(spawnerNetworks.baseNetworks, false); - SpawnerReset(spawnerNetworks.randomNetworks, false); - } else if (name == CoolDownStopTimer) { - self->SetVar(IsCooldownVariable, false); + ActivateSpawnerNetwork(spawnerNetworks.rewardNetworks); + SpawnerReset(spawnerNetworks.baseNetworks, false); + SpawnerReset(spawnerNetworks.randomNetworks, false); + } else if (name == CoolDownStopTimer) { + self->SetVar(IsCooldownVariable, false); - ActivityTimerStart(self, SpawnTickTimer, constants.waveTime); - ActivityTimerStart(self, CoolDownStartTimer, cooldownTime, cooldownTime); + ActivityTimerStart(self, SpawnTickTimer, constants.waveTime); + ActivityTimerStart(self, CoolDownStartTimer, cooldownTime, cooldownTime); - SpawnMobs(self); - ActivityTimerStart(self, PlaySpawnSoundTimer, 3, 3); - } else if (name == PlaySpawnSoundTimer) { - for (const auto& playerID : state.players) { - auto* player = EntityManager::Instance()->GetEntity(playerID); - if (player != nullptr) { - GameMessages::SendPlayNDAudioEmitter(player, player->GetSystemAddress(), spawnSoundGUID); - } - } - } + SpawnMobs(self); + ActivityTimerStart(self, PlaySpawnSoundTimer, 3, 3); + } else if (name == PlaySpawnSoundTimer) { + for (const auto& playerID : state.players) { + auto* player = EntityManager::Instance()->GetEntity(playerID); + if (player != nullptr) { + GameMessages::SendPlayNDAudioEmitter(player, player->GetSystemAddress(), spawnSoundGUID); + } + } + } } void BaseSurvivalServer::ResetStats(LWOOBJID playerID) { - auto* player = EntityManager::Instance()->GetEntity(playerID); - if (player != nullptr) { + auto* player = EntityManager::Instance()->GetEntity(playerID); + if (player != nullptr) { - // Boost all the player stats when loading in - auto* destroyableComponent = player->GetComponent(); - if (destroyableComponent != nullptr) { - destroyableComponent->SetHealth(destroyableComponent->GetMaxHealth()); - destroyableComponent->SetArmor(destroyableComponent->GetMaxArmor()); - destroyableComponent->SetImagination(destroyableComponent->GetMaxImagination()); - } - } + // Boost all the player stats when loading in + auto* destroyableComponent = player->GetComponent(); + if (destroyableComponent != nullptr) { + destroyableComponent->SetHealth(destroyableComponent->GetMaxHealth()); + destroyableComponent->SetArmor(destroyableComponent->GetMaxArmor()); + destroyableComponent->SetImagination(destroyableComponent->GetMaxImagination()); + } + } } void BaseSurvivalServer::PlayerConfirmed(Entity* self) { - std::vector confirmedPlayers {}; + std::vector confirmedPlayers{}; - for (const auto& playerID : state.players) { - auto pass = false; - for (const auto& waitingPlayerID : state.waitingPlayers) { - if (waitingPlayerID == playerID) - pass = true; - } + for (const auto& playerID : state.players) { + auto pass = false; + for (const auto& waitingPlayerID : state.waitingPlayers) { + if (waitingPlayerID == playerID) + pass = true; + } - if (!pass) - confirmedPlayers.push_back(playerID); - } + if (!pass) + confirmedPlayers.push_back(playerID); + } - auto playerIndex = 1; - for (const auto& playerID : confirmedPlayers) { - self->SetNetworkVar(PlayerConfirmVariable + GeneralUtils::to_u16string(playerIndex), std::to_string(playerID)); - playerIndex++; - } + auto playerIndex = 1; + for (const auto& playerID : confirmedPlayers) { + self->SetNetworkVar(PlayerConfirmVariable + GeneralUtils::to_u16string(playerIndex), std::to_string(playerID)); + playerIndex++; + } } -void BaseSurvivalServer::PlayerAccepted(Entity *self, LWOOBJID playerID) { - const auto& iter = std::find(state.waitingPlayers.begin(), state.waitingPlayers.end(), playerID); +void BaseSurvivalServer::PlayerAccepted(Entity* self, LWOOBJID playerID) { + const auto& iter = std::find(state.waitingPlayers.begin(), state.waitingPlayers.end(), playerID); - if (iter == state.waitingPlayers.end()) { - return; - } + if (iter == state.waitingPlayers.end()) { + return; + } - state.waitingPlayers.erase(iter); + state.waitingPlayers.erase(iter); - if (state.waitingPlayers.empty() && state.players.size() >= self->GetNetworkVar(NumberOfPlayersVariable)) { - ActivityTimerStopAllTimers(self); - ActivityTimerStart(self, AllAcceptedDelayTimer, 1, constants.startDelay); - } else if (!self->GetVar(AcceptedDelayStartedVariable)) { - self->SetVar(AcceptedDelayStartedVariable, true); - ActivityTimerStart(self, AcceptedDelayTimer, 1, constants.acceptedDelay); - } + if (state.waitingPlayers.empty() && state.players.size() >= self->GetNetworkVar(NumberOfPlayersVariable)) { + ActivityTimerStopAllTimers(self); + ActivityTimerStart(self, AllAcceptedDelayTimer, 1, constants.startDelay); + } else if (!self->GetVar(AcceptedDelayStartedVariable)) { + self->SetVar(AcceptedDelayStartedVariable, true); + ActivityTimerStart(self, AcceptedDelayTimer, 1, constants.acceptedDelay); + } } -void BaseSurvivalServer::StartWaves(Entity *self) { - GameMessages::SendActivityStart(self->GetObjectID(), UNASSIGNED_SYSTEM_ADDRESS); +void BaseSurvivalServer::StartWaves(Entity* self) { + GameMessages::SendActivityStart(self->GetObjectID(), UNASSIGNED_SYSTEM_ADDRESS); - self->SetVar(PlayersReadyVariable, true); - self->SetVar(BaseMobSetIndexVariable, 0); - self->SetVar(RandMobSetIndexVariable, 0); - self->SetVar(AcceptedDelayStartedVariable, false); + self->SetVar(PlayersReadyVariable, true); + self->SetVar(BaseMobSetIndexVariable, 0); + self->SetVar(RandMobSetIndexVariable, 0); + self->SetVar(AcceptedDelayStartedVariable, false); - state.waitingPlayers.clear(); + state.waitingPlayers.clear(); - for (const auto& playerID : state.players) { - const auto player = EntityManager::Instance()->GetEntity(playerID); - if (player != nullptr) { - state.waitingPlayers.push_back(playerID); - UpdatePlayer(self, playerID); - GetLeaderboardData(self, playerID, GetActivityID(self), 50); - ResetStats(playerID); + for (const auto& playerID : state.players) { + const auto player = EntityManager::Instance()->GetEntity(playerID); + if (player != nullptr) { + state.waitingPlayers.push_back(playerID); + UpdatePlayer(self, playerID); + GetLeaderboardData(self, playerID, GetActivityID(self), 50); + ResetStats(playerID); - if (!self->GetVar(FirstTimeDoneVariable)) { - TakeActivityCost(self, playerID); - } + if (!self->GetVar(FirstTimeDoneVariable)) { + TakeActivityCost(self, playerID); + } - GameMessages::SendPlayerSetCameraCyclingMode(playerID, player->GetSystemAddress()); - } - } + GameMessages::SendPlayerSetCameraCyclingMode(playerID, player->GetSystemAddress()); + } + } - self->SetVar(FirstTimeDoneVariable, true); - self->SetVar(MissionTypeVariable, state.players.size() == 1 ? "survival_time_solo" : "survival_time_team"); + self->SetVar(FirstTimeDoneVariable, true); + self->SetVar(MissionTypeVariable, state.players.size() == 1 ? "survival_time_solo" : "survival_time_team"); - ActivateSpawnerNetwork(spawnerNetworks.smashNetworks); - self->SetNetworkVar(WavesStartedVariable, true); - self->SetNetworkVar(StartWaveMessageVariable, "Start!"); + ActivateSpawnerNetwork(spawnerNetworks.smashNetworks); + self->SetNetworkVar(WavesStartedVariable, true); + self->SetNetworkVar(StartWaveMessageVariable, "Start!"); } bool BaseSurvivalServer::CheckAllPlayersDead() { - auto deadPlayers = 0; + auto deadPlayers = 0; - for (const auto& playerID : state.players) { - auto* player = EntityManager::Instance()->GetEntity(playerID); - if (player == nullptr || player->GetIsDead()) { - deadPlayers++; - } - } + for (const auto& playerID : state.players) { + auto* player = EntityManager::Instance()->GetEntity(playerID); + if (player == nullptr || player->GetIsDead()) { + deadPlayers++; + } + } - return deadPlayers >= state.players.size(); + return deadPlayers >= state.players.size(); } void BaseSurvivalServer::SetPlayerSpawnPoints() { - auto spawnerIndex = 1; - for (const auto& playerID : state.players) { - auto* player = EntityManager::Instance()->GetEntity(playerID); - if (player != nullptr) { - auto possibleSpawners = EntityManager::Instance()->GetEntitiesInGroup("P" + std::to_string(spawnerIndex) + "_Spawn"); - if (!possibleSpawners.empty()) { - auto* spawner = possibleSpawners.at(0); - GameMessages::SendTeleport(playerID, spawner->GetPosition(), spawner->GetRotation(), player->GetSystemAddress(), true); - } - } + auto spawnerIndex = 1; + for (const auto& playerID : state.players) { + auto* player = EntityManager::Instance()->GetEntity(playerID); + if (player != nullptr) { + auto possibleSpawners = EntityManager::Instance()->GetEntitiesInGroup("P" + std::to_string(spawnerIndex) + "_Spawn"); + if (!possibleSpawners.empty()) { + auto* spawner = possibleSpawners.at(0); + GameMessages::SendTeleport(playerID, spawner->GetPosition(), spawner->GetRotation(), player->GetSystemAddress(), true); + } + } - spawnerIndex++; - } + spawnerIndex++; + } } -void BaseSurvivalServer::GameOver(Entity *self) { - if (!CheckAllPlayersDead()) - return; +void BaseSurvivalServer::GameOver(Entity* self) { + if (!CheckAllPlayersDead()) + return; - ActivityTimerStopAllTimers(self); + ActivityTimerStopAllTimers(self); - // Reset all the spawners - SpawnerReset(spawnerNetworks.baseNetworks); - SpawnerReset(spawnerNetworks.randomNetworks); - SpawnerReset(spawnerNetworks.rewardNetworks); + // Reset all the spawners + SpawnerReset(spawnerNetworks.baseNetworks); + SpawnerReset(spawnerNetworks.randomNetworks); + SpawnerReset(spawnerNetworks.rewardNetworks); - for (const auto& playerID : state.players) { - auto* player = EntityManager::Instance()->GetEntity(playerID); - if (player == nullptr) - continue; + for (const auto& playerID : state.players) { + auto* player = EntityManager::Instance()->GetEntity(playerID); + if (player == nullptr) + continue; - const auto score = GetActivityValue(self, playerID, 0); - const auto time = GetActivityValue(self, playerID, 1); + const auto score = GetActivityValue(self, playerID, 0); + const auto time = GetActivityValue(self, playerID, 1); - GameMessages::SendNotifyClientZoneObject(self->GetObjectID(), u"Update_ScoreBoard", time, 0, - playerID, std::to_string(score), UNASSIGNED_SYSTEM_ADDRESS); - player->Resurrect(); + GameMessages::SendNotifyClientZoneObject(self->GetObjectID(), u"Update_ScoreBoard", time, 0, + playerID, std::to_string(score), UNASSIGNED_SYSTEM_ADDRESS); + player->Resurrect(); - // Update all mission progression - auto* missionComponent = player->GetComponent(); - if (missionComponent != nullptr) { - missionComponent->Progress(MissionTaskType::MISSION_TASK_TYPE_MINIGAME, time, self->GetObjectID(), - self->GetVar(MissionTypeVariable)); + // Update all mission progression + auto* missionComponent = player->GetComponent(); + if (missionComponent != nullptr) { + missionComponent->Progress(MissionTaskType::MISSION_TASK_TYPE_MINIGAME, time, self->GetObjectID(), + self->GetVar(MissionTypeVariable)); - for (const auto& survivalMission : missionsToUpdate) { - auto* mission = missionComponent->GetMission(survivalMission.first); - if (mission != nullptr && (uint32_t) time >= survivalMission.second - && (mission->GetMissionState() == MissionState::MISSION_STATE_ACTIVE - || mission->GetMissionState() == MissionState::MISSION_STATE_COMPLETE_ACTIVE)) { + for (const auto& survivalMission : missionsToUpdate) { + auto* mission = missionComponent->GetMission(survivalMission.first); + if (mission != nullptr && (uint32_t)time >= survivalMission.second + && (mission->GetMissionState() == MissionState::MISSION_STATE_ACTIVE + || mission->GetMissionState() == MissionState::MISSION_STATE_COMPLETE_ACTIVE)) { - mission->Progress(MissionTaskType::MISSION_TASK_TYPE_SCRIPT, self->GetLOT()); - } - } - } + mission->Progress(MissionTaskType::MISSION_TASK_TYPE_SCRIPT, self->GetLOT()); + } + } + } - StopActivity(self, playerID, score, time); - } + StopActivity(self, playerID, score, time); + } - state.waveNumber = 1; - state.rewardTick = 1; - state.totalSpawned = 0; + state.waveNumber = 1; + state.rewardTick = 1; + state.totalSpawned = 0; - self->SetNetworkVar(WavesStartedVariable, false); + self->SetNetworkVar(WavesStartedVariable, false); - if (constants.useMobLots) { - constants.lotPhase = 0; - UpdateMobLots(spawnerNetworks.baseNetworks); - UpdateMobLots(spawnerNetworks.randomNetworks); - } + if (constants.useMobLots) { + constants.lotPhase = 0; + UpdateMobLots(spawnerNetworks.baseNetworks); + UpdateMobLots(spawnerNetworks.randomNetworks); + } - SetPlayerSpawnPoints(); + SetPlayerSpawnPoints(); } void BaseSurvivalServer::SpawnerReset(SpawnerNetworkCollection& spawnerNetworkCollection, bool hardReset) { - auto totalSpawned = 0; + auto totalSpawned = 0; - for (auto& spawner : spawnerNetworkCollection.networks) { - for (auto& spawnerName : spawner.names) { - auto spawners = dZoneManager::Instance()->GetSpawnersByName(spawnerName + spawner.number); - if (!spawners.empty()) { - auto* spawnerObject = spawners.at(0); + for (auto& spawner : spawnerNetworkCollection.networks) { + for (auto& spawnerName : spawner.names) { + auto spawners = dZoneManager::Instance()->GetSpawnersByName(spawnerName + spawner.number); + if (!spawners.empty()) { + auto* spawnerObject = spawners.at(0); - auto amountSpawned = spawnerObject->GetAmountSpawned(); - totalSpawned += amountSpawned; + auto amountSpawned = spawnerObject->GetAmountSpawned(); + totalSpawned += amountSpawned; - spawner.isActive = false; - if (hardReset) { - spawnerObject->Reset(); - } else { - spawnerObject->SoftReset(); - } + spawner.isActive = false; + if (hardReset) { + spawnerObject->Reset(); + } else { + spawnerObject->SoftReset(); + } - spawnerObject->Deactivate(); - } - } - } + spawnerObject->Deactivate(); + } + } + } - state.totalSpawned = std::max((uint32_t) totalSpawned, state.totalSpawned); + state.totalSpawned = std::max((uint32_t)totalSpawned, state.totalSpawned); } void BaseSurvivalServer::SpawnerUpdate(Entity* self, SpawnerNetworkCollection& spawnerNetworkCollection, uint32_t amount) { - if (spawnerNetworkCollection.networks.empty()) - return; + if (spawnerNetworkCollection.networks.empty()) + return; - // If we want to spawn something specific now - if (amount != 0) { - auto spawnerNetwork = spawnerNetworkCollection.networks.at(0); - auto possibleSpawners = dZoneManager::Instance()->GetSpawnersByName(spawnerNetwork.names.at(0) + spawnerNetwork.number); - if (!possibleSpawners.empty()) { - SpawnNow(possibleSpawners.at(0), amount); - return; - } - } + // If we want to spawn something specific now + if (amount != 0) { + auto spawnerNetwork = spawnerNetworkCollection.networks.at(0); + auto possibleSpawners = dZoneManager::Instance()->GetSpawnersByName(spawnerNetwork.names.at(0) + spawnerNetwork.number); + if (!possibleSpawners.empty()) { + SpawnNow(possibleSpawners.at(0), amount); + return; + } + } - auto setNumber = self->GetVar(GeneralUtils::ASCIIToUTF16(spawnerNetworkCollection.mobSetName + "Num")); - auto newSet = GetRandomMobSet(spawnerNetworkCollection, setNumber); + auto setNumber = self->GetVar(GeneralUtils::ASCIIToUTF16(spawnerNetworkCollection.mobSetName + "Num")); + auto newSet = GetRandomMobSet(spawnerNetworkCollection, setNumber); - if (!newSet.empty()) { - auto spawnerNetwork = GetRandomSpawner(spawnerNetworkCollection); - for (auto i = 0; i < spawnerNetwork.names.size(); i++) { - const auto& name = spawnerNetwork.names.at(i); - const auto& toSpawn = newSet.at(i); + if (!newSet.empty()) { + auto spawnerNetwork = GetRandomSpawner(spawnerNetworkCollection); + for (auto i = 0; i < spawnerNetwork.names.size(); i++) { + const auto& name = spawnerNetwork.names.at(i); + const auto& toSpawn = newSet.at(i); - auto possibleSpawners = dZoneManager::Instance()->GetSpawnersByName(name + spawnerNetwork.number); - if (!possibleSpawners.empty()) { - SpawnNow(possibleSpawners.front(), toSpawn); - } - } - } + auto possibleSpawners = dZoneManager::Instance()->GetSpawnersByName(name + spawnerNetwork.number); + if (!possibleSpawners.empty()) { + SpawnNow(possibleSpawners.front(), toSpawn); + } + } + } } -void BaseSurvivalServer::SpawnNow(Spawner *spawner, uint32_t amount) { - if (spawner != nullptr) { - if (!spawner->m_Active) { - spawner->m_Info.amountMaintained = amount; - spawner->Activate(); - } else { - spawner->m_Info.amountMaintained = amount; - } - } +void BaseSurvivalServer::SpawnNow(Spawner* spawner, uint32_t amount) { + if (spawner != nullptr) { + if (!spawner->m_Active) { + spawner->m_Info.amountMaintained = amount; + spawner->Activate(); + } else { + spawner->m_Info.amountMaintained = amount; + } + } } std::vector BaseSurvivalServer::GetRandomMobSet(SpawnerNetworkCollection& spawnerNetworkCollection, - uint32_t setNumber) { + uint32_t setNumber) { - if (mobSets.sets.find(spawnerNetworkCollection.mobSetName) != mobSets.sets.end()) { - auto mobSet = mobSets.sets.at(spawnerNetworkCollection.mobSetName); - if (setNumber < mobSet.size()) { - return mobSet.at(setNumber).at(rand() % mobSet.at(setNumber).size()); - } - } + if (mobSets.sets.find(spawnerNetworkCollection.mobSetName) != mobSets.sets.end()) { + auto mobSet = mobSets.sets.at(spawnerNetworkCollection.mobSetName); + if (setNumber < mobSet.size()) { + return mobSet.at(setNumber).at(rand() % mobSet.at(setNumber).size()); + } + } - return {}; + return {}; } SpawnerNetwork BaseSurvivalServer::GetRandomSpawner(SpawnerNetworkCollection& spawnerNetworkCollection) { - std::vector validSpawners {}; - for (const auto& spawner : spawnerNetworkCollection.networks) { - if (!spawner.isLocked) - validSpawners.push_back(spawner); - } + std::vector validSpawners{}; + for (const auto& spawner : spawnerNetworkCollection.networks) { + if (!spawner.isLocked) + validSpawners.push_back(spawner); + } - if (!validSpawners.empty()) { - auto spawner = validSpawners.at(rand() % validSpawners.size()); - spawner.isActive = true; - return spawner; - } + if (!validSpawners.empty()) { + auto spawner = validSpawners.at(rand() % validSpawners.size()); + spawner.isActive = true; + return spawner; + } - return {}; + return {}; } void BaseSurvivalServer::ActivateSpawnerNetwork(SpawnerNetworkCollection& spawnerNetworkCollection) { - for (auto& spawner : spawnerNetworkCollection.networks) { - for (const auto& spawnerName : spawner.names) { - auto possibleSpawners = dZoneManager::Instance()->GetSpawnersByName(spawnerName + spawner.number); - if (!possibleSpawners.empty()) { - auto* spawnerObject = possibleSpawners.at(0); - spawnerObject->Activate(); - spawnerObject->Reset(); - } - } - } + for (auto& spawner : spawnerNetworkCollection.networks) { + for (const auto& spawnerName : spawner.names) { + auto possibleSpawners = dZoneManager::Instance()->GetSpawnersByName(spawnerName + spawner.number); + if (!possibleSpawners.empty()) { + auto* spawnerObject = possibleSpawners.at(0); + spawnerObject->Activate(); + spawnerObject->Reset(); + } + } + } } void BaseSurvivalServer::UpdateMobLots(SpawnerNetworkCollection& spawnerNetworkCollection) { - for (auto& spawner : spawnerNetworkCollection.networks) { - for (auto& spawnerName : spawner.names) { - if (!spawnerName.empty()) { - auto spawnerObjects = dZoneManager::Instance()->GetSpawnersByName(spawnerName + spawner.number); - if (!spawnerObjects.empty()) { - auto splitName = GeneralUtils::SplitString(spawnerName, '_'); - auto cleanName = splitName.size() > 1 ? splitName.at(1) : splitName.at(0); + for (auto& spawner : spawnerNetworkCollection.networks) { + for (auto& spawnerName : spawner.names) { + if (!spawnerName.empty()) { + auto spawnerObjects = dZoneManager::Instance()->GetSpawnersByName(spawnerName + spawner.number); + if (!spawnerObjects.empty()) { + auto splitName = GeneralUtils::SplitString(spawnerName, '_'); + auto cleanName = splitName.size() > 1 ? splitName.at(1) : splitName.at(0); - if (!cleanName.empty()) { - auto spawnerObject = spawnerObjects.at(0); - spawnerObject->SetSpawnLot(mobSets.mobLots.at(cleanName).at(constants.lotPhase)); - } - } - } - } - } + if (!cleanName.empty()) { + auto spawnerObject = spawnerObjects.at(0); + spawnerObject->SetSpawnLot(mobSets.mobLots.at(cleanName).at(constants.lotPhase)); + } + } + } + } + } } -void BaseSurvivalServer::SpawnMobs(Entity *self) { - if (!self->GetNetworkVar(WavesStartedVariable)) - return; +void BaseSurvivalServer::SpawnMobs(Entity* self) { + if (!self->GetNetworkVar(WavesStartedVariable)) + return; - state.waveNumber++; - auto spawnNumber = state.waveNumber > constants.rewardInterval ? state.waveNumber - state.rewardTick - 1 : state.waveNumber; + state.waveNumber++; + auto spawnNumber = state.waveNumber > constants.rewardInterval ? state.waveNumber - state.rewardTick - 1 : state.waveNumber; - for (const auto& tier : constants.baseMobsStartTier) { - if (tier == spawnNumber) - self->SetVar(BaseMobSetIndexVariable, (self->GetVar(BaseMobSetIndexVariable) + 1) - % (constants.baseMobsStartTier.size() - 1)); - } + for (const auto& tier : constants.baseMobsStartTier) { + if (tier == spawnNumber) + self->SetVar(BaseMobSetIndexVariable, (self->GetVar(BaseMobSetIndexVariable) + 1) + % (constants.baseMobsStartTier.size() - 1)); + } - for (const auto& tier : constants.randMobsStartTier) { - if (tier == spawnNumber) - self->SetVar(RandMobSetIndexVariable, (self->GetVar(RandMobSetIndexVariable) + 1) - % (constants.randMobsStartTier.size() - 1)); - } + for (const auto& tier : constants.randMobsStartTier) { + if (tier == spawnNumber) + self->SetVar(RandMobSetIndexVariable, (self->GetVar(RandMobSetIndexVariable) + 1) + % (constants.randMobsStartTier.size() - 1)); + } - if (state.waveNumber == constants.unlockNetwork3) - spawnerNetworks.randomNetworks.networks.at(2).isLocked = false; + if (state.waveNumber == constants.unlockNetwork3) + spawnerNetworks.randomNetworks.networks.at(2).isLocked = false; - SpawnerReset(spawnerNetworks.baseNetworks, false); - SpawnerReset(spawnerNetworks.randomNetworks, false); - SpawnerUpdate(self, spawnerNetworks.baseNetworks); + SpawnerReset(spawnerNetworks.baseNetworks, false); + SpawnerReset(spawnerNetworks.randomNetworks, false); + SpawnerUpdate(self, spawnerNetworks.baseNetworks); - if (spawnNumber >= constants.mobSet2Wave) { - if (spawnNumber == constants.mobSet2Wave) - self->SetNetworkVar(SpawnMobVariable, "2"); - SpawnerUpdate(self, spawnerNetworks.randomNetworks); - } + if (spawnNumber >= constants.mobSet2Wave) { + if (spawnNumber == constants.mobSet2Wave) + self->SetNetworkVar(SpawnMobVariable, "2"); + SpawnerUpdate(self, spawnerNetworks.randomNetworks); + } - if (spawnNumber >= constants.mobSet3Wave) { - if (spawnNumber == constants.mobSet3Wave) - self->SetNetworkVar(SpawnMobVariable, "3"); - SpawnerUpdate(self, spawnerNetworks.randomNetworks); - } + if (spawnNumber >= constants.mobSet3Wave) { + if (spawnNumber == constants.mobSet3Wave) + self->SetNetworkVar(SpawnMobVariable, "3"); + SpawnerUpdate(self, spawnerNetworks.randomNetworks); + } - // If we reached the end of the spawn phase we increase the lost to make it more difficult - if (constants.useMobLots && constants.lotPhase < (mobSets.mobLots.begin()->second.size() - 1) - && spawnNumber >= constants.baseMobsStartTier.back()) { - state.waveNumber = 1; - constants.lotPhase++; + // If we reached the end of the spawn phase we increase the lost to make it more difficult + if (constants.useMobLots && constants.lotPhase < (mobSets.mobLots.begin()->second.size() - 1) + && spawnNumber >= constants.baseMobsStartTier.back()) { + state.waveNumber = 1; + constants.lotPhase++; - UpdateMobLots(spawnerNetworks.baseNetworks); - UpdateMobLots(spawnerNetworks.randomNetworks); - } + UpdateMobLots(spawnerNetworks.baseNetworks); + UpdateMobLots(spawnerNetworks.randomNetworks); + } } diff --git a/dScripts/BaseSurvivalServer.h b/dScripts/BaseSurvivalServer.h index c85f1bbf..a7c9a95a 100644 --- a/dScripts/BaseSurvivalServer.h +++ b/dScripts/BaseSurvivalServer.h @@ -5,149 +5,152 @@ * State for each active game */ struct GameState { - std::vector players {}; - std::vector waitingPlayers {}; - uint32_t totalSpawned = 0; - uint32_t rewardTick = 0; - uint32_t waveNumber = 1; + std::vector players{}; + std::vector waitingPlayers{}; + uint32_t totalSpawned = 0; + uint32_t rewardTick = 0; + uint32_t waveNumber = 1; }; /** * Constants that have to be set for each game */ struct Constants { - uint32_t acceptedDelay = 0; - uint32_t startDelay = 0; - uint32_t waveTime = 0; - uint32_t rewardInterval = 0; - uint32_t coolDownTime = 0; - uint32_t mobSet2Wave = 0; - uint32_t mobSet3Wave = 0; - uint32_t unlockNetwork3 = 0; - uint32_t lotPhase = 0; - bool useMobLots = false; - std::vector baseMobsStartTier {}; - std::vector randMobsStartTier {}; + uint32_t acceptedDelay = 0; + uint32_t startDelay = 0; + uint32_t waveTime = 0; + uint32_t rewardInterval = 0; + uint32_t coolDownTime = 0; + uint32_t mobSet2Wave = 0; + uint32_t mobSet3Wave = 0; + uint32_t unlockNetwork3 = 0; + uint32_t lotPhase = 0; + bool useMobLots = false; + std::vector baseMobsStartTier{}; + std::vector randMobsStartTier{}; }; /** * The lots of the mobs to spawn along with amounts to spawn for each wave */ struct MobSets { - std::map> mobLots {}; - std::map>>> sets {}; + std::map> mobLots{}; + std::map>>> sets{}; }; struct SpawnerNetwork { - std::vector names {}; - std::string number; - bool isLocked = false; - bool isActive = false; + std::vector names{}; + std::string number; + bool isLocked = false; + bool isActive = false; }; struct SpawnerNetworkCollection { - std::string mobSetName; - std::vector networks {}; + std::string mobSetName; + std::vector networks{}; }; struct SpawnerNetworks { - SpawnerNetworkCollection baseNetworks {}; - SpawnerNetworkCollection randomNetworks {}; - SpawnerNetworkCollection rewardNetworks {}; - SpawnerNetworkCollection smashNetworks {}; + SpawnerNetworkCollection baseNetworks{}; + SpawnerNetworkCollection randomNetworks{}; + SpawnerNetworkCollection rewardNetworks{}; + SpawnerNetworkCollection smashNetworks{}; }; class BaseSurvivalServer : public ActivityManager { public: - void OnStartup(Entity* self) override { SetGameVariables(self); BaseStartup(self); }; - void OnPlayerLoaded(Entity* self, Entity* player) override { BasePlayerLoaded(self, player); }; - void OnPlayerExit(Entity* self, Entity* player) override { BasePlayerExit(self, player); }; - void OnFireEventServerSide(Entity *self, Entity *sender, std::string args, int32_t param1, int32_t param2, - int32_t param3) override { BaseFireEvent(self, sender, args, param1, param2, param3); }; - void OnPlayerDied(Entity* self, Entity* player) override { BasePlayerDied(self, player); }; - void OnPlayerResurrected(Entity* self, Entity* player) override { BasePlayerResurrected(self, player); }; - void OnMessageBoxResponse(Entity* self, Entity* sender, int32_t button, const std::u16string& identifier, - const std::u16string& userData) override - { BaseMessageBoxResponse(self, sender, button, identifier, userData); }; + void OnStartup(Entity* self) override { SetGameVariables(self); BaseStartup(self); }; + void OnPlayerLoaded(Entity* self, Entity* player) override { BasePlayerLoaded(self, player); }; + void OnPlayerExit(Entity* self, Entity* player) override { BasePlayerExit(self, player); }; + void OnFireEventServerSide(Entity* self, Entity* sender, std::string args, int32_t param1, int32_t param2, + int32_t param3) override { + BaseFireEvent(self, sender, args, param1, param2, param3); + }; + void OnPlayerDied(Entity* self, Entity* player) override { BasePlayerDied(self, player); }; + void OnPlayerResurrected(Entity* self, Entity* player) override { BasePlayerResurrected(self, player); }; + void OnMessageBoxResponse(Entity* self, Entity* sender, int32_t button, const std::u16string& identifier, + const std::u16string& userData) override { + BaseMessageBoxResponse(self, sender, button, identifier, userData); + }; - void BasePlayerLoaded(Entity* self, Entity* player); + void BasePlayerLoaded(Entity* self, Entity* player); void BaseStartup(Entity* self); void BasePlayerExit(Entity* self, Entity* player); - void BaseFireEvent(Entity *self, Entity *sender, const std::string& args, int32_t param1, int32_t param2, - int32_t param3); + void BaseFireEvent(Entity* self, Entity* sender, const std::string& args, int32_t param1, int32_t param2, + int32_t param3); void BasePlayerDied(Entity* self, Entity* player); void BasePlayerResurrected(Entity* self, Entity* player); void BaseMessageBoxResponse(Entity* self, Entity* sender, int32_t button, const std::u16string& identifier, const std::u16string& userData); - void OnActivityTimerDone(Entity *self, const std::string &name) override; - void OnActivityTimerUpdate(Entity *self, const std::string &name, float_t remainingTime, float_t elapsedTime) override; + void OnActivityTimerDone(Entity* self, const std::string& name) override; + void OnActivityTimerUpdate(Entity* self, const std::string& name, float_t remainingTime, float_t elapsedTime) override; protected: - virtual Constants GetConstants() { return Constants(); }; - virtual MobSets GetMobSets() { return MobSets(); }; - virtual SpawnerNetworks GetSpawnerNetworks() { return SpawnerNetworks(); }; - virtual std::map GetMissionsToUpdate() { return {}; }; - GameState state {}; + virtual Constants GetConstants() { return Constants(); }; + virtual MobSets GetMobSets() { return MobSets(); }; + virtual SpawnerNetworks GetSpawnerNetworks() { return SpawnerNetworks(); }; + virtual std::map GetMissionsToUpdate() { return {}; }; + GameState state{}; - // Mob set default names - std::string BaseMobSet = "baseMobSet"; - std::string RandMobSet = "randMobSet"; + // Mob set default names + std::string BaseMobSet = "baseMobSet"; + std::string RandMobSet = "randMobSet"; - // Variable names - std::u16string WavesStartedVariable = u"wavesStarted"; - std::u16string ShowScoreboardVariable = u"Show_ScoreBoard"; - std::u16string ClearScoreboardVariable = u"Clear_Scoreboard"; - std::u16string DefinePlayerToUIVariable = u"Define_Player_To_UI"; - std::u16string UpdateScoreboardPlayersVariable = u"Update_ScoreBoard_Players."; - std::u16string PlayerConfirmVariable = u"PlayerConfirm_ScoreBoard."; - std::u16string PlayersAcceptedVariable = u"playersAccepted"; - std::u16string PlayersReadyVariable = u"playersReady"; - std::u16string BaseMobSetIndexVariable = u"baseMobSetNum"; - std::u16string RandMobSetIndexVariable = u"randMobSetNum"; - std::u16string AcceptedDelayStartedVariable = u"AcceptedDelayStarted"; - std::u16string NumberOfPlayersVariable = u"NumberOfPlayers"; - std::u16string FirstTimeDoneVariable = u"firstTimeDone"; - std::u16string MissionTypeVariable = u"missionType"; - std::u16string StartWaveMessageVariable = u"Start_Wave_Message"; - std::u16string ExitWavesVariable = u"Exit_waves"; - std::u16string UpdateDefaultStartTimerVariable = u"Update_Default_Start_Timer"; - std::u16string UpdateTimerVariable = u"Update_Timer"; - std::u16string IsCooldownVariable = u"isCoolDown"; - std::u16string SpawnMobVariable = u"Spawn_Mob"; + // Variable names + std::u16string WavesStartedVariable = u"wavesStarted"; + std::u16string ShowScoreboardVariable = u"Show_ScoreBoard"; + std::u16string ClearScoreboardVariable = u"Clear_Scoreboard"; + std::u16string DefinePlayerToUIVariable = u"Define_Player_To_UI"; + std::u16string UpdateScoreboardPlayersVariable = u"Update_ScoreBoard_Players."; + std::u16string PlayerConfirmVariable = u"PlayerConfirm_ScoreBoard."; + std::u16string PlayersAcceptedVariable = u"playersAccepted"; + std::u16string PlayersReadyVariable = u"playersReady"; + std::u16string BaseMobSetIndexVariable = u"baseMobSetNum"; + std::u16string RandMobSetIndexVariable = u"randMobSetNum"; + std::u16string AcceptedDelayStartedVariable = u"AcceptedDelayStarted"; + std::u16string NumberOfPlayersVariable = u"NumberOfPlayers"; + std::u16string FirstTimeDoneVariable = u"firstTimeDone"; + std::u16string MissionTypeVariable = u"missionType"; + std::u16string StartWaveMessageVariable = u"Start_Wave_Message"; + std::u16string ExitWavesVariable = u"Exit_waves"; + std::u16string UpdateDefaultStartTimerVariable = u"Update_Default_Start_Timer"; + std::u16string UpdateTimerVariable = u"Update_Timer"; + std::u16string IsCooldownVariable = u"isCoolDown"; + std::u16string SpawnMobVariable = u"Spawn_Mob"; - // Timer names - std::string SpawnTickTimer = "SpawnTick"; - std::string AllAcceptedDelayTimer = "AllAcceptedDelay"; - std::string AcceptedDelayTimer = "AcceptedDelay"; - std::string StartDelayTimer = "StartDelay"; - std::string ClockTickTimer = "ClockTick"; - std::string CoolDownStartTimer = "CoolDownStart"; - std::string CoolDownStopTimer = "CoolDownStop"; - std::string PlaySpawnSoundTimer = "PlaySpawnSound"; + // Timer names + std::string SpawnTickTimer = "SpawnTick"; + std::string AllAcceptedDelayTimer = "AllAcceptedDelay"; + std::string AcceptedDelayTimer = "AcceptedDelay"; + std::string StartDelayTimer = "StartDelay"; + std::string ClockTickTimer = "ClockTick"; + std::string CoolDownStartTimer = "CoolDownStart"; + std::string CoolDownStopTimer = "CoolDownStop"; + std::string PlaySpawnSoundTimer = "PlaySpawnSound"; - std::string spawnSoundGUID = "{ca36045d-89df-4e96-a317-1e152d226b69}"; + std::string spawnSoundGUID = "{ca36045d-89df-4e96-a317-1e152d226b69}"; private: - void SetGameVariables(Entity* self); - static void ResetStats(LWOOBJID player); - void GameOver(Entity* self); + void SetGameVariables(Entity* self); + static void ResetStats(LWOOBJID player); + void GameOver(Entity* self); - void StartWaves(Entity* self); + void StartWaves(Entity* self); static void ActivateSpawnerNetwork(SpawnerNetworkCollection& spawnerNetworkCollection); - void SpawnerReset(SpawnerNetworkCollection& spawnerNetworkCollection, bool hardReset = true); - void SpawnerUpdate(Entity* self, SpawnerNetworkCollection& spawnerNetworkCollection, uint32_t amount = 0); - void SpawnMobs(Entity* self); - static SpawnerNetwork GetRandomSpawner(SpawnerNetworkCollection& spawnerNetworkCollection); - std::vector GetRandomMobSet(SpawnerNetworkCollection& spawnerNetworkCollection, uint32_t setNumber); + void SpawnerReset(SpawnerNetworkCollection& spawnerNetworkCollection, bool hardReset = true); + void SpawnerUpdate(Entity* self, SpawnerNetworkCollection& spawnerNetworkCollection, uint32_t amount = 0); + void SpawnMobs(Entity* self); + static SpawnerNetwork GetRandomSpawner(SpawnerNetworkCollection& spawnerNetworkCollection); + std::vector GetRandomMobSet(SpawnerNetworkCollection& spawnerNetworkCollection, uint32_t setNumber); - static void SpawnNow(Spawner* spawner, uint32_t amount); + static void SpawnNow(Spawner* spawner, uint32_t amount); - bool CheckAllPlayersDead(); - void SetPlayerSpawnPoints(); + bool CheckAllPlayersDead(); + void SetPlayerSpawnPoints(); void UpdateMobLots(SpawnerNetworkCollection& spawnerNetworkCollection); void PlayerConfirmed(Entity* self); void PlayerAccepted(Entity* self, LWOOBJID playerID); - Constants constants {}; - MobSets mobSets {}; - SpawnerNetworks spawnerNetworks {}; - std::map missionsToUpdate {}; + Constants constants{}; + MobSets mobSets{}; + SpawnerNetworks spawnerNetworks{}; + std::map missionsToUpdate{}; }; diff --git a/dScripts/BaseWavesGenericEnemy.cpp b/dScripts/BaseWavesGenericEnemy.cpp index 7158accb..3270e2d8 100644 --- a/dScripts/BaseWavesGenericEnemy.cpp +++ b/dScripts/BaseWavesGenericEnemy.cpp @@ -1,13 +1,13 @@ #include "BaseWavesGenericEnemy.h" #include "dZoneManager.h" -void BaseWavesGenericEnemy::OnStartup(Entity *self) { - self->SetNetworkVar(u"points", GetPoints()); +void BaseWavesGenericEnemy::OnStartup(Entity* self) { + self->SetNetworkVar(u"points", GetPoints()); } -void BaseWavesGenericEnemy::OnDie(Entity *self, Entity *killer) { - auto* zoneControlObject = dZoneManager::Instance()->GetZoneControlObject(); - if (zoneControlObject != nullptr) { - zoneControlObject->OnFireEventServerSide(killer, "Survival_Update", GetPoints()); - } +void BaseWavesGenericEnemy::OnDie(Entity* self, Entity* killer) { + auto* zoneControlObject = dZoneManager::Instance()->GetZoneControlObject(); + if (zoneControlObject != nullptr) { + zoneControlObject->OnFireEventServerSide(killer, "Survival_Update", GetPoints()); + } } diff --git a/dScripts/BaseWavesGenericEnemy.h b/dScripts/BaseWavesGenericEnemy.h index 718f36e1..3c808b4e 100644 --- a/dScripts/BaseWavesGenericEnemy.h +++ b/dScripts/BaseWavesGenericEnemy.h @@ -3,8 +3,8 @@ class BaseWavesGenericEnemy : public CppScripts::Script { public: - void OnStartup(Entity *self) override; - void OnDie(Entity *self, Entity *killer) override; + void OnStartup(Entity* self) override; + void OnDie(Entity* self, Entity* killer) override; protected: - virtual uint32_t GetPoints() { return 0; }; + virtual uint32_t GetPoints() { return 0; }; }; diff --git a/dScripts/BaseWavesServer.cpp b/dScripts/BaseWavesServer.cpp index 2c8a2edd..8c32f984 100644 --- a/dScripts/BaseWavesServer.cpp +++ b/dScripts/BaseWavesServer.cpp @@ -9,582 +9,582 @@ #include "Character.h" // Done -void BaseWavesServer::SetGameVariables(Entity *self) { - this->constants = std::move(GetConstants()); - this->waves = std::move(GetWaves()); - this->missions = std::move(GetWaveMissions()); - this->spawners = std::move(GetSpawnerNames()); +void BaseWavesServer::SetGameVariables(Entity* self) { + this->constants = std::move(GetConstants()); + this->waves = std::move(GetWaves()); + this->missions = std::move(GetWaveMissions()); + this->spawners = std::move(GetSpawnerNames()); } // Done void BaseWavesServer::BasePlayerLoaded(Entity* self, Entity* player) { - GameMessages::SendPlayerSetCameraCyclingMode(player->GetObjectID(), player->GetSystemAddress()); - GameMessages::SendPlayerAllowedRespawn(player->GetObjectID(), true, player->GetSystemAddress()); + GameMessages::SendPlayerSetCameraCyclingMode(player->GetObjectID(), player->GetSystemAddress()); + GameMessages::SendPlayerAllowedRespawn(player->GetObjectID(), true, player->GetSystemAddress()); - state.waitingPlayers.push_back(player->GetObjectID()); - state.players.push_back(player->GetObjectID()); + state.waitingPlayers.push_back(player->GetObjectID()); + state.players.push_back(player->GetObjectID()); - self->SetNetworkVar(NumberOfPlayersVariable, self->GetNetworkVar(NumberOfPlayersVariable) + 1); - self->SetNetworkVar(DefinePlayerToUIVariable, std::to_string(player->GetObjectID()), player->GetSystemAddress()); + self->SetNetworkVar(NumberOfPlayersVariable, self->GetNetworkVar(NumberOfPlayersVariable) + 1); + self->SetNetworkVar(DefinePlayerToUIVariable, std::to_string(player->GetObjectID()), player->GetSystemAddress()); - // Notify the players of all other players - if (!self->GetNetworkVar(WavesStartedVariable)) { - auto counter = 1; - for (const auto& playerID : state.players) { - self->SetNetworkVar(UpdateScoreboardPlayersVariable + GeneralUtils::to_u16string(counter), std::to_string(playerID)); - counter++; - } + // Notify the players of all other players + if (!self->GetNetworkVar(WavesStartedVariable)) { + auto counter = 1; + for (const auto& playerID : state.players) { + self->SetNetworkVar(UpdateScoreboardPlayersVariable + GeneralUtils::to_u16string(counter), std::to_string(playerID)); + counter++; + } - if (!this->constants.introCelebration.empty()) { - self->SetNetworkVar(WatchingIntroVariable, this->constants.introCelebration + "_" - + std::to_string(player->GetObjectID())); - } else { - self->SetNetworkVar(ShowScoreboardVariable, true); - } - } + if (!this->constants.introCelebration.empty()) { + self->SetNetworkVar(WatchingIntroVariable, this->constants.introCelebration + "_" + + std::to_string(player->GetObjectID())); + } else { + self->SetNetworkVar(ShowScoreboardVariable, true); + } + } - SetPlayerSpawnPoints(); + SetPlayerSpawnPoints(); - if (!self->GetNetworkVar(WavesStartedVariable)) { - PlayerConfirmed(self); - } else { - UpdatePlayer(self, player->GetObjectID()); - GetLeaderboardData(self, player->GetObjectID(), GetActivityID(self), 50); - ResetStats(player->GetObjectID()); - } + if (!self->GetNetworkVar(WavesStartedVariable)) { + PlayerConfirmed(self); + } else { + UpdatePlayer(self, player->GetObjectID()); + GetLeaderboardData(self, player->GetObjectID(), GetActivityID(self), 50); + ResetStats(player->GetObjectID()); + } } // Done void BaseWavesServer::BaseStartup(Entity* self) { - self->SetVar(PlayersAcceptedVariable, 0); - self->SetVar(PlayersReadyVariable, false); + self->SetVar(PlayersAcceptedVariable, 0); + self->SetVar(PlayersReadyVariable, false); } // Done void BaseWavesServer::BasePlayerExit(Entity* self, Entity* player) { - auto waitingPlayerToErase = std::find(state.waitingPlayers.begin(), state.waitingPlayers.end(), player->GetObjectID()); - if (waitingPlayerToErase != state.waitingPlayers.end()) state.waitingPlayers.erase(waitingPlayerToErase); + auto waitingPlayerToErase = std::find(state.waitingPlayers.begin(), state.waitingPlayers.end(), player->GetObjectID()); + if (waitingPlayerToErase != state.waitingPlayers.end()) state.waitingPlayers.erase(waitingPlayerToErase); - auto playerToErase = std::find(state.players.begin(), state.players.end(), player->GetObjectID()); - if (playerToErase != state.players.end()) state.players.erase(playerToErase); + auto playerToErase = std::find(state.players.begin(), state.players.end(), player->GetObjectID()); + if (playerToErase != state.players.end()) state.players.erase(playerToErase); - if (!self->GetNetworkVar(WavesStartedVariable)) { - PlayerConfirmed(self); + if (!self->GetNetworkVar(WavesStartedVariable)) { + PlayerConfirmed(self); - if (state.players.empty()) - return; + if (state.players.empty()) + return; - if (state.waitingPlayers.empty()) { - ActivityTimerStopAllTimers(self); - ActivityTimerStart(self, AllAcceptedDelayTimer, 1.0f, constants.startDelay); - } else if (state.players.size() > state.waitingPlayers.size()) { - if (!self->GetVar(AcceptedDelayStartedVariable)) { - self->SetVar(AcceptedDelayStartedVariable, true); - ActivityTimerStart(self, AcceptedDelayTimer, 1.0f, constants.acceptedDelay); - } - } - } else { - UpdatePlayer(self, player->GetObjectID(), true); - if (CheckAllPlayersDead()) { - GameOver(self); - } - } + if (state.waitingPlayers.empty()) { + ActivityTimerStopAllTimers(self); + ActivityTimerStart(self, AllAcceptedDelayTimer, 1.0f, constants.startDelay); + } else if (state.players.size() > state.waitingPlayers.size()) { + if (!self->GetVar(AcceptedDelayStartedVariable)) { + self->SetVar(AcceptedDelayStartedVariable, true); + ActivityTimerStart(self, AcceptedDelayTimer, 1.0f, constants.acceptedDelay); + } + } + } else { + UpdatePlayer(self, player->GetObjectID(), true); + if (CheckAllPlayersDead()) { + GameOver(self); + } + } - SetActivityValue(self, player->GetObjectID(), 1, 0); - SetActivityValue(self, player->GetObjectID(), 2, 0); + SetActivityValue(self, player->GetObjectID(), 1, 0); + SetActivityValue(self, player->GetObjectID(), 2, 0); - self->SetNetworkVar(NumberOfPlayersVariable, - std::min((uint32_t) 0, self->GetNetworkVar(NumberOfPlayersVariable) - 1)); + self->SetNetworkVar(NumberOfPlayersVariable, + std::min((uint32_t)0, self->GetNetworkVar(NumberOfPlayersVariable) - 1)); } // Done void BaseWavesServer::BaseFireEvent(Entity* self, Entity* sender, const std::string& args, int32_t param1, int32_t param2, - int32_t param3) { - if (args == "start") { - StartWaves(self); - } else if (args == "Survival_Update") { - const auto senderID = sender != nullptr ? sender->GetObjectID() : LWOOBJID_EMPTY; - if (UpdateSpawnedEnemies(self, senderID, param1)) { - const auto currentTime = GetActivityValue(self, senderID, 1); - const auto currentWave = GetActivityValue(self, senderID, 2); + int32_t param3) { + if (args == "start") { + StartWaves(self); + } else if (args == "Survival_Update") { + const auto senderID = sender != nullptr ? sender->GetObjectID() : LWOOBJID_EMPTY; + if (UpdateSpawnedEnemies(self, senderID, param1)) { + const auto currentTime = GetActivityValue(self, senderID, 1); + const auto currentWave = GetActivityValue(self, senderID, 2); - for (const auto& mission : this->missions) { - if (currentWave == mission.wave && currentTime <= mission.time) { - UpdateMissionForAllPlayers(self, mission.missionID); - } - } - } - } + for (const auto& mission : this->missions) { + if (currentWave == mission.wave && currentTime <= mission.time) { + UpdateMissionForAllPlayers(self, mission.missionID); + } + } + } + } } // Done void BaseWavesServer::BasePlayerDied(Entity* self, Entity* player) { - const auto currentTime = ActivityTimerGetCurrentTime(self, ClockTickTimer); - const auto finalTime = GetActivityValue(self, player->GetObjectID(), 1); - const auto finalWave = GetActivityValue(self, player->GetObjectID(), 2); + const auto currentTime = ActivityTimerGetCurrentTime(self, ClockTickTimer); + const auto finalTime = GetActivityValue(self, player->GetObjectID(), 1); + const auto finalWave = GetActivityValue(self, player->GetObjectID(), 2); - auto paramString = CheckAllPlayersDead() ? "true" : "false"; + auto paramString = CheckAllPlayersDead() ? "true" : "false"; - GameMessages::SendNotifyClientZoneObject(self->GetObjectID(), u"Player_Died", finalTime, finalWave, - player->GetObjectID(), paramString, player->GetSystemAddress()); + GameMessages::SendNotifyClientZoneObject(self->GetObjectID(), u"Player_Died", finalTime, finalWave, + player->GetObjectID(), paramString, player->GetSystemAddress()); - if (!self->GetNetworkVar(WavesStartedVariable)) { - player->Resurrect(); - return; - } + if (!self->GetNetworkVar(WavesStartedVariable)) { + player->Resurrect(); + return; + } - GameOver(self); + GameOver(self); } // Done -void BaseWavesServer::BasePlayerResurrected(Entity *self, Entity *player) { - GameMessages::SendNotifyClientZoneObject(self->GetObjectID(), u"Player_Res", 0, 0, - player->GetObjectID(), "", player->GetSystemAddress()); +void BaseWavesServer::BasePlayerResurrected(Entity* self, Entity* player) { + GameMessages::SendNotifyClientZoneObject(self->GetObjectID(), u"Player_Res", 0, 0, + player->GetObjectID(), "", player->GetSystemAddress()); - if (self->GetNetworkVar(WavesStartedVariable)) - return; + if (self->GetNetworkVar(WavesStartedVariable)) + return; - self->SetNetworkVar(ShowScoreboardVariable, true); - SetPlayerSpawnPoints(player->GetObjectID()); + self->SetNetworkVar(ShowScoreboardVariable, true); + SetPlayerSpawnPoints(player->GetObjectID()); } // Done void BaseWavesServer::BaseMessageBoxResponse(Entity* self, Entity* sender, int32_t button, - const std::u16string &identifier, const std::u16string &userData) { - if (identifier == u"RePlay") { - PlayerAccepted(self, sender->GetObjectID()); - PlayerConfirmed(self); - } else if (identifier == u"Exit_Question" && button == 1) { - ResetStats(sender->GetObjectID()); - self->SetNetworkVar(ExitWavesVariable, std::to_string(sender->GetObjectID())); + const std::u16string& identifier, const std::u16string& userData) { + if (identifier == u"RePlay") { + PlayerAccepted(self, sender->GetObjectID()); + PlayerConfirmed(self); + } else if (identifier == u"Exit_Question" && button == 1) { + ResetStats(sender->GetObjectID()); + self->SetNetworkVar(ExitWavesVariable, std::to_string(sender->GetObjectID())); - if (sender->IsPlayer()) { - auto* character = sender->GetCharacter(); - if (character != nullptr) { - auto* player = dynamic_cast(sender); - player->SendToZone(character->GetLastNonInstanceZoneID()); - } - } - } + if (sender->IsPlayer()) { + auto* character = sender->GetCharacter(); + if (character != nullptr) { + auto* player = dynamic_cast(sender); + player->SendToZone(character->GetLastNonInstanceZoneID()); + } + } + } } // Done -void BaseWavesServer::OnActivityTimerUpdate(Entity *self, const std::string &name, float_t remainingTime, float_t elapsedTime) { - if (name == AcceptedDelayTimer) { - self->SetNetworkVar(UpdateDefaultStartTimerVariable, remainingTime); - } else if (name == ClockTickTimer) { - self->SetNetworkVar(UpdateTimerVariable, elapsedTime); - } else if (name == NextWaveTickTimer || name == TimedWaveTimer || name == GameOverWinTimer) { - self->SetNetworkVar(UpdateCooldownVariable, remainingTime); - } +void BaseWavesServer::OnActivityTimerUpdate(Entity* self, const std::string& name, float_t remainingTime, float_t elapsedTime) { + if (name == AcceptedDelayTimer) { + self->SetNetworkVar(UpdateDefaultStartTimerVariable, remainingTime); + } else if (name == ClockTickTimer) { + self->SetNetworkVar(UpdateTimerVariable, elapsedTime); + } else if (name == NextWaveTickTimer || name == TimedWaveTimer || name == GameOverWinTimer) { + self->SetNetworkVar(UpdateCooldownVariable, remainingTime); + } } // Done -void BaseWavesServer::OnActivityTimerDone(Entity *self, const std::string &name) { - if (name == AcceptedDelayTimer) { - self->SetNetworkVar(UpdateDefaultStartTimerVariable, 0); - ActivityTimerStart(self, AllAcceptedDelayTimer, 1, 1); - } else if (name == AllAcceptedDelayTimer) { - self->SetNetworkVar(ClearScoreboardVariable, true); - ActivityTimerStart(self, StartDelayTimer, 4, 4); - StartWaves(self); - } else if (name == StartDelayTimer) { - ActivityTimerStart(self, ClockTickTimer, 1); - SpawnWave(self); - ActivityTimerStart(self, PlaySpawnSoundTimer, 3, 3); - } else if (name == PlaySpawnSoundTimer) { - for (const auto& playerID : state.players) { - auto* player = EntityManager::Instance()->GetEntity(playerID); - if (player != nullptr) { - GameMessages::SendPlayNDAudioEmitter(player, player->GetSystemAddress(), spawnSoundGUID); - } - } - } else if (name == NextWaveTickTimer) { - self->SetNetworkVar(StartCooldownVariable, false); - SpawnWave(self); - } else if (name == WaveCompleteDelayTimer) { - self->SetNetworkVar(StartCooldownVariable, constants.waveTime); - ActivityTimerStart(self, NextWaveTickTimer, 1, constants.waveTime); - } else if (name == TimedWaveTimer) { - ActivityTimerStart(self, WaveCompleteDelayTimer, constants.waveCompleteDelay, constants.waveCompleteDelay); +void BaseWavesServer::OnActivityTimerDone(Entity* self, const std::string& name) { + if (name == AcceptedDelayTimer) { + self->SetNetworkVar(UpdateDefaultStartTimerVariable, 0); + ActivityTimerStart(self, AllAcceptedDelayTimer, 1, 1); + } else if (name == AllAcceptedDelayTimer) { + self->SetNetworkVar(ClearScoreboardVariable, true); + ActivityTimerStart(self, StartDelayTimer, 4, 4); + StartWaves(self); + } else if (name == StartDelayTimer) { + ActivityTimerStart(self, ClockTickTimer, 1); + SpawnWave(self); + ActivityTimerStart(self, PlaySpawnSoundTimer, 3, 3); + } else if (name == PlaySpawnSoundTimer) { + for (const auto& playerID : state.players) { + auto* player = EntityManager::Instance()->GetEntity(playerID); + if (player != nullptr) { + GameMessages::SendPlayNDAudioEmitter(player, player->GetSystemAddress(), spawnSoundGUID); + } + } + } else if (name == NextWaveTickTimer) { + self->SetNetworkVar(StartCooldownVariable, false); + SpawnWave(self); + } else if (name == WaveCompleteDelayTimer) { + self->SetNetworkVar(StartCooldownVariable, constants.waveTime); + ActivityTimerStart(self, NextWaveTickTimer, 1, constants.waveTime); + } else if (name == TimedWaveTimer) { + ActivityTimerStart(self, WaveCompleteDelayTimer, constants.waveCompleteDelay, constants.waveCompleteDelay); - const auto currentTime = ActivityTimerGetCurrentTime(self, ClockTickTimer); - const auto currentWave = state.waveNumber; + const auto currentTime = ActivityTimerGetCurrentTime(self, ClockTickTimer); + const auto currentWave = state.waveNumber; - self->SetNetworkVar(WaveCompleteVariable, { currentWave, (uint32_t) currentTime }); - } else if (name == GameOverWinTimer) { - GameOver(self, true); - } else if (name == CinematicDoneTimer) { - for (auto* boss : EntityManager::Instance()->GetEntitiesInGroup("boss")) { - boss->OnFireEventServerSide(self, "startAI"); - } - } + self->SetNetworkVar(WaveCompleteVariable, { currentWave, (uint32_t)currentTime }); + } else if (name == GameOverWinTimer) { + GameOver(self, true); + } else if (name == CinematicDoneTimer) { + for (auto* boss : EntityManager::Instance()->GetEntitiesInGroup("boss")) { + boss->OnFireEventServerSide(self, "startAI"); + } + } } // Done void BaseWavesServer::ResetStats(LWOOBJID playerID) { - auto* player = EntityManager::Instance()->GetEntity(playerID); - if (player != nullptr) { + auto* player = EntityManager::Instance()->GetEntity(playerID); + if (player != nullptr) { - // Boost all the player stats when loading in - auto* destroyableComponent = player->GetComponent(); - if (destroyableComponent != nullptr) { - destroyableComponent->SetHealth(destroyableComponent->GetMaxHealth()); - destroyableComponent->SetArmor(destroyableComponent->GetMaxArmor()); - destroyableComponent->SetImagination(destroyableComponent->GetMaxImagination()); - } - } + // Boost all the player stats when loading in + auto* destroyableComponent = player->GetComponent(); + if (destroyableComponent != nullptr) { + destroyableComponent->SetHealth(destroyableComponent->GetMaxHealth()); + destroyableComponent->SetArmor(destroyableComponent->GetMaxArmor()); + destroyableComponent->SetImagination(destroyableComponent->GetMaxImagination()); + } + } } // Done void BaseWavesServer::PlayerConfirmed(Entity* self) { - std::vector confirmedPlayers {}; + std::vector confirmedPlayers{}; - for (const auto& playerID : state.players) { - auto pass = false; - for (const auto& waitingPlayerID : state.waitingPlayers) { - if (waitingPlayerID == playerID) - pass = true; - } + for (const auto& playerID : state.players) { + auto pass = false; + for (const auto& waitingPlayerID : state.waitingPlayers) { + if (waitingPlayerID == playerID) + pass = true; + } - if (!pass) - confirmedPlayers.push_back(playerID); - } + if (!pass) + confirmedPlayers.push_back(playerID); + } - auto playerIndex = 1; - for (const auto& playerID : confirmedPlayers) { - self->SetNetworkVar(PlayerConfirmVariable + GeneralUtils::to_u16string(playerIndex), std::to_string(playerID)); - playerIndex++; - } + auto playerIndex = 1; + for (const auto& playerID : confirmedPlayers) { + self->SetNetworkVar(PlayerConfirmVariable + GeneralUtils::to_u16string(playerIndex), std::to_string(playerID)); + playerIndex++; + } } // Done -void BaseWavesServer::PlayerAccepted(Entity *self, LWOOBJID playerID) { - state.waitingPlayers.erase(std::find(state.waitingPlayers.begin(), state.waitingPlayers.end(), playerID)); - if (state.waitingPlayers.empty() && state.players.size() >= self->GetNetworkVar(NumberOfPlayersVariable)) { - ActivityTimerStopAllTimers(self); - ActivityTimerStart(self, AllAcceptedDelayTimer, 1, constants.startDelay); - } else if (!self->GetVar(AcceptedDelayStartedVariable)) { - self->SetVar(AcceptedDelayStartedVariable, true); - ActivityTimerStart(self, AcceptedDelayTimer, 1, constants.acceptedDelay); - } +void BaseWavesServer::PlayerAccepted(Entity* self, LWOOBJID playerID) { + state.waitingPlayers.erase(std::find(state.waitingPlayers.begin(), state.waitingPlayers.end(), playerID)); + if (state.waitingPlayers.empty() && state.players.size() >= self->GetNetworkVar(NumberOfPlayersVariable)) { + ActivityTimerStopAllTimers(self); + ActivityTimerStart(self, AllAcceptedDelayTimer, 1, constants.startDelay); + } else if (!self->GetVar(AcceptedDelayStartedVariable)) { + self->SetVar(AcceptedDelayStartedVariable, true); + ActivityTimerStart(self, AcceptedDelayTimer, 1, constants.acceptedDelay); + } } // Done -void BaseWavesServer::StartWaves(Entity *self) { - GameMessages::SendActivityStart(self->GetObjectID(), UNASSIGNED_SYSTEM_ADDRESS); +void BaseWavesServer::StartWaves(Entity* self) { + GameMessages::SendActivityStart(self->GetObjectID(), UNASSIGNED_SYSTEM_ADDRESS); - self->SetNetworkVar(WatchingIntroVariable, ""); - self->SetVar(PlayersReadyVariable, true); - self->SetVar(BaseMobSetIndexVariable, 0); - self->SetVar(RandMobSetIndexVariable, 0); - self->SetVar(AcceptedDelayStartedVariable, false); + self->SetNetworkVar(WatchingIntroVariable, ""); + self->SetVar(PlayersReadyVariable, true); + self->SetVar(BaseMobSetIndexVariable, 0); + self->SetVar(RandMobSetIndexVariable, 0); + self->SetVar(AcceptedDelayStartedVariable, false); - state.waitingPlayers.clear(); + state.waitingPlayers.clear(); - for (const auto& playerID : state.players) { - const auto player = EntityManager::Instance()->GetEntity(playerID); - if (player != nullptr) { - state.waitingPlayers.push_back(playerID); + for (const auto& playerID : state.players) { + const auto player = EntityManager::Instance()->GetEntity(playerID); + if (player != nullptr) { + state.waitingPlayers.push_back(playerID); - UpdatePlayer(self, playerID); - GetLeaderboardData(self, playerID, GetActivityID(self), 1); - ResetStats(playerID); + UpdatePlayer(self, playerID); + GetLeaderboardData(self, playerID, GetActivityID(self), 1); + ResetStats(playerID); - if (!self->GetVar(FirstTimeDoneVariable)) { - TakeActivityCost(self, playerID); - } - } - } + if (!self->GetVar(FirstTimeDoneVariable)) { + TakeActivityCost(self, playerID); + } + } + } - self->SetVar(FirstTimeDoneVariable, true); - self->SetVar(MissionTypeVariable, state.players.size() == 1 ? "survival_time_solo" : "survival_time_team"); - self->SetNetworkVar(WavesStartedVariable, true); - self->SetNetworkVar(StartWaveMessageVariable, "Start!"); + self->SetVar(FirstTimeDoneVariable, true); + self->SetVar(MissionTypeVariable, state.players.size() == 1 ? "survival_time_solo" : "survival_time_team"); + self->SetNetworkVar(WavesStartedVariable, true); + self->SetNetworkVar(StartWaveMessageVariable, "Start!"); } // Done bool BaseWavesServer::CheckAllPlayersDead() { - auto deadPlayers = 0; + auto deadPlayers = 0; - for (const auto& playerID : state.players) { - auto* player = EntityManager::Instance()->GetEntity(playerID); - if (player == nullptr || player->GetIsDead()) { - deadPlayers++; - } - } + for (const auto& playerID : state.players) { + auto* player = EntityManager::Instance()->GetEntity(playerID); + if (player == nullptr || player->GetIsDead()) { + deadPlayers++; + } + } - return deadPlayers >= state.players.size(); + return deadPlayers >= state.players.size(); } // Done void BaseWavesServer::SetPlayerSpawnPoints(const LWOOBJID& specificPlayerID) { - auto spawnerIndex = 1; - for (const auto& playerID : state.players) { - auto* player = EntityManager::Instance()->GetEntity(playerID); - if (player != nullptr && (specificPlayerID == LWOOBJID_EMPTY || playerID == specificPlayerID)) { - auto possibleSpawners = EntityManager::Instance()->GetEntitiesInGroup("P" + std::to_string(spawnerIndex) + "_Spawn"); - if (!possibleSpawners.empty()) { - auto* spawner = possibleSpawners.at(0); - GameMessages::SendTeleport(playerID, spawner->GetPosition(), spawner->GetRotation(), player->GetSystemAddress(), true); - } - } + auto spawnerIndex = 1; + for (const auto& playerID : state.players) { + auto* player = EntityManager::Instance()->GetEntity(playerID); + if (player != nullptr && (specificPlayerID == LWOOBJID_EMPTY || playerID == specificPlayerID)) { + auto possibleSpawners = EntityManager::Instance()->GetEntitiesInGroup("P" + std::to_string(spawnerIndex) + "_Spawn"); + if (!possibleSpawners.empty()) { + auto* spawner = possibleSpawners.at(0); + GameMessages::SendTeleport(playerID, spawner->GetPosition(), spawner->GetRotation(), player->GetSystemAddress(), true); + } + } - spawnerIndex++; - } + spawnerIndex++; + } } // Done -void BaseWavesServer::GameOver(Entity *self, bool won) { - if (!CheckAllPlayersDead() && !won) - return; +void BaseWavesServer::GameOver(Entity* self, bool won) { + if (!CheckAllPlayersDead() && !won) + return; - ActivityTimerStopAllTimers(self); + ActivityTimerStopAllTimers(self); - // Reset all the spawners - state.waveNumber = 0; - state.totalSpawned = 0; - state.currentSpawned = 0; + // Reset all the spawners + state.waveNumber = 0; + state.totalSpawned = 0; + state.currentSpawned = 0; - self->SetNetworkVar(WavesStartedVariable, false); - self->SetNetworkVar(StartCooldownVariable, 0); - SetPlayerSpawnPoints(); - ClearSpawners(); + self->SetNetworkVar(WavesStartedVariable, false); + self->SetNetworkVar(StartCooldownVariable, 0); + SetPlayerSpawnPoints(); + ClearSpawners(); - for (const auto& playerID : state.players) { - auto* player = EntityManager::Instance()->GetEntity(playerID); - if (player == nullptr) - continue; + for (const auto& playerID : state.players) { + auto* player = EntityManager::Instance()->GetEntity(playerID); + if (player == nullptr) + continue; - const auto score = GetActivityValue(self, playerID, 0); - const auto time = GetActivityValue(self, playerID, 1); - const auto wave = GetActivityValue(self, playerID, 2); + const auto score = GetActivityValue(self, playerID, 0); + const auto time = GetActivityValue(self, playerID, 1); + const auto wave = GetActivityValue(self, playerID, 2); - GameMessages::SendNotifyClientZoneObject(self->GetObjectID(), u"Update_ScoreBoard", time, 0, - playerID, std::to_string(wave), UNASSIGNED_SYSTEM_ADDRESS); + GameMessages::SendNotifyClientZoneObject(self->GetObjectID(), u"Update_ScoreBoard", time, 0, + playerID, std::to_string(wave), UNASSIGNED_SYSTEM_ADDRESS); - if (won) { - SetPlayerSpawnPoints(); - self->SetNetworkVar(ShowScoreboardVariable, true); - } else { - player->Resurrect(); - } + if (won) { + SetPlayerSpawnPoints(); + self->SetNetworkVar(ShowScoreboardVariable, true); + } else { + player->Resurrect(); + } - // Update all mission progression - auto* missionComponent = player->GetComponent(); - if (missionComponent != nullptr) { - missionComponent->Progress(MissionTaskType::MISSION_TASK_TYPE_MINIGAME, time, self->GetObjectID(), self->GetVar(MissionTypeVariable)); - } + // Update all mission progression + auto* missionComponent = player->GetComponent(); + if (missionComponent != nullptr) { + missionComponent->Progress(MissionTaskType::MISSION_TASK_TYPE_MINIGAME, time, self->GetObjectID(), self->GetVar(MissionTypeVariable)); + } - StopActivity(self, playerID, wave, time, score); - } + StopActivity(self, playerID, wave, time, score); + } } // Done -void BaseWavesServer::GameWon(Entity *self) { - ActivityTimerStopAllTimers(self); +void BaseWavesServer::GameWon(Entity* self) { + ActivityTimerStopAllTimers(self); - const auto winDelay = waves.back().winDelay; - ActivityTimerStart(self, GameOverWinTimer, 1, winDelay); - self->SetNetworkVar(StartTimedWaveVariable, { winDelay, state.waveNumber }); + const auto winDelay = waves.back().winDelay; + ActivityTimerStart(self, GameOverWinTimer, 1, winDelay); + self->SetNetworkVar(StartTimedWaveVariable, { winDelay, state.waveNumber }); } // Done void BaseWavesServer::SpawnNow(const std::string& spawnerName, uint32_t amount, LOT spawnLot) { - const auto spawners = dZoneManager::Instance()->GetSpawnersByName(spawnerName); - for (auto* spawner : spawners) { - if (spawnLot != LOT_NULL) { - spawner->SetSpawnLot(spawnLot); - } + const auto spawners = dZoneManager::Instance()->GetSpawnersByName(spawnerName); + for (auto* spawner : spawners) { + if (spawnLot != LOT_NULL) { + spawner->SetSpawnLot(spawnLot); + } - spawner->m_Info.amountMaintained = amount; - spawner->m_Info.maxToSpawn = amount; + spawner->m_Info.amountMaintained = amount; + spawner->m_Info.maxToSpawn = amount; - spawner->Reset(); - spawner->Activate(); - } + spawner->Reset(); + spawner->Activate(); + } } // Done -void BaseWavesServer::SpawnWave(Entity *self) { - if (!self->GetNetworkVar(WavesStartedVariable)) - return; +void BaseWavesServer::SpawnWave(Entity* self) { + if (!self->GetNetworkVar(WavesStartedVariable)) + return; - // If there's no wave left - if (state.waveNumber >= waves.size()) { - GameOver(self); - return; - } + // If there's no wave left + if (state.waveNumber >= waves.size()) { + GameOver(self); + return; + } - const auto wave = waves.at(state.waveNumber); + const auto wave = waves.at(state.waveNumber); - // Handles meta info to the client about the current round - if (wave.winDelay != (uint32_t) -1) { - self->SetNetworkVar(WonWaveVariable, true); + // Handles meta info to the client about the current round + if (wave.winDelay != (uint32_t)-1) { + self->SetNetworkVar(WonWaveVariable, true); - // Close the game if we don't expect a notification from an other entity to end it - if (!wave.notifyWin) { - GameWon(self); - } + // Close the game if we don't expect a notification from an other entity to end it + if (!wave.notifyWin) { + GameWon(self); + } - for (const auto& playerID : state.players) { - auto* player = EntityManager::Instance()->GetEntity(playerID); - if (player != nullptr) { - player->Resurrect(); - } - } - } else { - if (wave.timeLimit != (uint32_t) -1) { - ActivityTimerStart(self, TimedWaveTimer, 1.0f, wave.timeLimit); - self->SetNetworkVar(StartTimedWaveVariable, { wave.timeLimit, state.waveNumber + 1 } ); - } else { - self->SetNetworkVar(NewWaveVariable, state.waveNumber + 1); - } - } + for (const auto& playerID : state.players) { + auto* player = EntityManager::Instance()->GetEntity(playerID); + if (player != nullptr) { + player->Resurrect(); + } + } + } else { + if (wave.timeLimit != (uint32_t)-1) { + ActivityTimerStart(self, TimedWaveTimer, 1.0f, wave.timeLimit); + self->SetNetworkVar(StartTimedWaveVariable, { wave.timeLimit, state.waveNumber + 1 }); + } else { + self->SetNetworkVar(NewWaveVariable, state.waveNumber + 1); + } + } - // NOTE: The script does some stuff with events here, although BONS does not have those + // NOTE: The script does some stuff with events here, although BONS does not have those - // Optional cinematics to play - if (!wave.cinematic.empty()) { - ActivityTimerStart(self, CinematicDoneTimer, wave.cinematicLength, wave.cinematicLength); - self->SetNetworkVar(StartCinematicVariable, wave.cinematic); - } + // Optional cinematics to play + if (!wave.cinematic.empty()) { + ActivityTimerStart(self, CinematicDoneTimer, wave.cinematicLength, wave.cinematicLength); + self->SetNetworkVar(StartCinematicVariable, wave.cinematic); + } - // Spawn the enemies - state.currentSpawned = 0; + // Spawn the enemies + state.currentSpawned = 0; - for (const auto& mobDefinition : wave.waveMobs) { - SpawnNow(mobDefinition.spawnerName, mobDefinition.amountToSpawn, mobDefinition.lot); - state.currentSpawned += mobDefinition.amountToSpawn; - } + for (const auto& mobDefinition : wave.waveMobs) { + SpawnNow(mobDefinition.spawnerName, mobDefinition.amountToSpawn, mobDefinition.lot); + state.currentSpawned += mobDefinition.amountToSpawn; + } - state.waveNumber++; - state.totalSpawned += state.currentSpawned; - self->SetNetworkVar(NumRemainingVariable, state.currentSpawned); + state.waveNumber++; + state.totalSpawned += state.currentSpawned; + self->SetNetworkVar(NumRemainingVariable, state.currentSpawned); } // Done bool BaseWavesServer::UpdateSpawnedEnemies(Entity* self, LWOOBJID enemyID, uint32_t score) { - if (!self->GetNetworkVar(WavesStartedVariable)) - return false; + if (!self->GetNetworkVar(WavesStartedVariable)) + return false; - state.currentSpawned--; + state.currentSpawned--; - auto* enemy = EntityManager::Instance()->GetEntity(enemyID); - if (enemy != nullptr && enemy->IsPlayer() && IsPlayerInActivity(self, enemyID)) { - SetActivityValue(self, enemyID, 0, GetActivityValue(self, enemyID, 0) + score); - } + auto* enemy = EntityManager::Instance()->GetEntity(enemyID); + if (enemy != nullptr && enemy->IsPlayer() && IsPlayerInActivity(self, enemyID)) { + SetActivityValue(self, enemyID, 0, GetActivityValue(self, enemyID, 0) + score); + } - if (state.currentSpawned <= 0) { - const auto currentTime = ActivityTimerGetCurrentTime(self, ClockTickTimer); - const auto completedWave = state.waveNumber - 1; + if (state.currentSpawned <= 0) { + const auto currentTime = ActivityTimerGetCurrentTime(self, ClockTickTimer); + const auto completedWave = state.waveNumber - 1; - // When the last enemy is smashed (e.g. in last wave - 1) - if (state.waveNumber >= waves.size() - 1) { + // When the last enemy is smashed (e.g. in last wave - 1) + if (state.waveNumber >= waves.size() - 1) { - // If there's no more follow up waves, (e.g in last wave), end the game. Generally called by some other script - if (state.waveNumber >= waves.size()) { - GameWon(self); - return false; - } + // If there's no more follow up waves, (e.g in last wave), end the game. Generally called by some other script + if (state.waveNumber >= waves.size()) { + GameWon(self); + return false; + } - ActivityTimerStopAllTimers(self); - self->SetNetworkVar(UpdateTimerVariable, currentTime); - } + ActivityTimerStopAllTimers(self); + self->SetNetworkVar(UpdateTimerVariable, currentTime); + } - ActivityTimerStart(self, WaveCompleteDelayTimer, constants.waveCompleteDelay, constants.waveCompleteDelay); + ActivityTimerStart(self, WaveCompleteDelayTimer, constants.waveCompleteDelay, constants.waveCompleteDelay); - const auto waveMission = waves.at(completedWave).missions; - const auto soloWaveMissions = waves.at(completedWave).soloMissions; + const auto waveMission = waves.at(completedWave).missions; + const auto soloWaveMissions = waves.at(completedWave).soloMissions; - for (const auto& playerID : state.players) { - auto* player = EntityManager::Instance()->GetEntity(playerID); - if (player != nullptr && !player->GetIsDead()) { - SetActivityValue(self, playerID, 1, currentTime); - SetActivityValue(self, playerID, 2, state.waveNumber); + for (const auto& playerID : state.players) { + auto* player = EntityManager::Instance()->GetEntity(playerID); + if (player != nullptr && !player->GetIsDead()) { + SetActivityValue(self, playerID, 1, currentTime); + SetActivityValue(self, playerID, 2, state.waveNumber); - // Update player missions - auto* missionComponent = player->GetComponent(); - if (missionComponent != nullptr) { - for (const auto& missionID : waveMission) { - // Get the mission state - auto missionState = missionComponent->GetMissionState(missionID); - // For some reason these achievements are not accepted by default, so we accept them here if they arent already. - if (missionState != MissionState::MISSION_STATE_COMPLETE && missionState != MissionState::MISSION_STATE_UNKNOWN) { - missionComponent->AcceptMission(missionID); - missionState = missionComponent->GetMissionState(missionID); - } + // Update player missions + auto* missionComponent = player->GetComponent(); + if (missionComponent != nullptr) { + for (const auto& missionID : waveMission) { + // Get the mission state + auto missionState = missionComponent->GetMissionState(missionID); + // For some reason these achievements are not accepted by default, so we accept them here if they arent already. + if (missionState != MissionState::MISSION_STATE_COMPLETE && missionState != MissionState::MISSION_STATE_UNKNOWN) { + missionComponent->AcceptMission(missionID); + missionState = missionComponent->GetMissionState(missionID); + } - if (missionState != MissionState::MISSION_STATE_COMPLETE) { - auto mission = missionComponent->GetMission(missionID); - if (mission != nullptr) { - mission->Progress(MissionTaskType::MISSION_TASK_TYPE_SCRIPT, self->GetLOT()); - } - } - } - // Progress solo missions - if (state.players.size() == 1) { - for (const auto& missionID : soloWaveMissions) { - // Get the mission state - auto missionState = missionComponent->GetMissionState(missionID); - // For some reason these achievements are not accepted by default, so we accept them here if they arent already. - if (missionState != MissionState::MISSION_STATE_COMPLETE && missionState != MissionState::MISSION_STATE_UNKNOWN) { - missionComponent->AcceptMission(missionID); - missionState = missionComponent->GetMissionState(missionID); - } + if (missionState != MissionState::MISSION_STATE_COMPLETE) { + auto mission = missionComponent->GetMission(missionID); + if (mission != nullptr) { + mission->Progress(MissionTaskType::MISSION_TASK_TYPE_SCRIPT, self->GetLOT()); + } + } + } + // Progress solo missions + if (state.players.size() == 1) { + for (const auto& missionID : soloWaveMissions) { + // Get the mission state + auto missionState = missionComponent->GetMissionState(missionID); + // For some reason these achievements are not accepted by default, so we accept them here if they arent already. + if (missionState != MissionState::MISSION_STATE_COMPLETE && missionState != MissionState::MISSION_STATE_UNKNOWN) { + missionComponent->AcceptMission(missionID); + missionState = missionComponent->GetMissionState(missionID); + } - if (missionState != MissionState::MISSION_STATE_COMPLETE) { - auto mission = missionComponent->GetMission(missionID); - if (mission != nullptr) { - mission->Progress(MissionTaskType::MISSION_TASK_TYPE_SCRIPT, self->GetLOT()); - } - } - } - } - } - } - } + if (missionState != MissionState::MISSION_STATE_COMPLETE) { + auto mission = missionComponent->GetMission(missionID); + if (mission != nullptr) { + mission->Progress(MissionTaskType::MISSION_TASK_TYPE_SCRIPT, self->GetLOT()); + } + } + } + } + } + } + } - // Might seem odd to send the next wave but the client isn't 0-indexed so it thinks it completed the correct wave - self->SetNetworkVar(WaveCompleteVariable, { state.waveNumber, (uint32_t) currentTime }); - return true; - } + // Might seem odd to send the next wave but the client isn't 0-indexed so it thinks it completed the correct wave + self->SetNetworkVar(WaveCompleteVariable, { state.waveNumber, (uint32_t)currentTime }); + return true; + } - self->SetNetworkVar(NumRemainingVariable, state.currentSpawned); - return false; + self->SetNetworkVar(NumRemainingVariable, state.currentSpawned); + return false; } // Done void BaseWavesServer::UpdateMissionForAllPlayers(Entity* self, uint32_t missionID) { - for (const auto& playerID : state.players) { - auto* player = EntityManager::Instance()->GetEntity(playerID); - if (player != nullptr) { - auto* missionComponent = player->GetComponent(); - if (missionComponent == nullptr) return; - // Get the mission state - auto missionState = missionComponent->GetMissionState(missionID); - // For some reason these achievements are not accepted by default, so we accept them here if they arent already. - if (missionState != MissionState::MISSION_STATE_COMPLETE && missionState != MissionState::MISSION_STATE_UNKNOWN) { - missionComponent->AcceptMission(missionID); - missionState = missionComponent->GetMissionState(missionID); - } - if (missionState != MissionState::MISSION_STATE_COMPLETE) { - auto mission = missionComponent->GetMission(missionID); - if (mission != nullptr) { - mission->Progress(MissionTaskType::MISSION_TASK_TYPE_SCRIPT, self->GetLOT()); - } - } - } - } + for (const auto& playerID : state.players) { + auto* player = EntityManager::Instance()->GetEntity(playerID); + if (player != nullptr) { + auto* missionComponent = player->GetComponent(); + if (missionComponent == nullptr) return; + // Get the mission state + auto missionState = missionComponent->GetMissionState(missionID); + // For some reason these achievements are not accepted by default, so we accept them here if they arent already. + if (missionState != MissionState::MISSION_STATE_COMPLETE && missionState != MissionState::MISSION_STATE_UNKNOWN) { + missionComponent->AcceptMission(missionID); + missionState = missionComponent->GetMissionState(missionID); + } + if (missionState != MissionState::MISSION_STATE_COMPLETE) { + auto mission = missionComponent->GetMission(missionID); + if (mission != nullptr) { + mission->Progress(MissionTaskType::MISSION_TASK_TYPE_SCRIPT, self->GetLOT()); + } + } + } + } } void BaseWavesServer::ClearSpawners() { - for (const auto& spawnerName : spawners) { - const auto spawnerObjects = dZoneManager::Instance()->GetSpawnersByName(spawnerName); + for (const auto& spawnerName : spawners) { + const auto spawnerObjects = dZoneManager::Instance()->GetSpawnersByName(spawnerName); - for (auto* spawnerObject : spawnerObjects) { - spawnerObject->Reset(); - spawnerObject->Deactivate(); - } - } + for (auto* spawnerObject : spawnerObjects) { + spawnerObject->Reset(); + spawnerObject->Deactivate(); + } + } } diff --git a/dScripts/BaseWavesServer.h b/dScripts/BaseWavesServer.h index 3dc90da8..67eaf39d 100644 --- a/dScripts/BaseWavesServer.h +++ b/dScripts/BaseWavesServer.h @@ -5,151 +5,154 @@ * State for each active game */ struct WavesGameState { - std::vector players {}; - std::vector waitingPlayers {}; - uint32_t totalSpawned = 0; - uint32_t currentSpawned = 0; - uint32_t waveNumber = 0; - std::string introCelebration; + std::vector players{}; + std::vector waitingPlayers{}; + uint32_t totalSpawned = 0; + uint32_t currentSpawned = 0; + uint32_t waveNumber = 0; + std::string introCelebration; }; struct MobDefinition { - LOT lot; - uint32_t amountToSpawn; - std::string spawnerName; + LOT lot; + uint32_t amountToSpawn; + std::string spawnerName; }; struct WaveMission { - uint32_t time; - uint32_t wave; - uint32_t missionID; + uint32_t time; + uint32_t wave; + uint32_t missionID; }; struct Wave { - std::vector waveMobs {}; - std::vector soloMissions {}; - std::vector missions {}; - std::string cinematic; - float_t cinematicLength; - uint32_t timeLimit = UINT32_MAX; - bool notifyWin = false; - uint32_t winDelay = UINT32_MAX; + std::vector waveMobs{}; + std::vector soloMissions{}; + std::vector missions{}; + std::string cinematic; + float_t cinematicLength; + uint32_t timeLimit = UINT32_MAX; + bool notifyWin = false; + uint32_t winDelay = UINT32_MAX; }; /** * WaveConstants that have to be set for each game */ struct WaveConstants { - uint32_t acceptedDelay = 0; - uint32_t startDelay = 0; - uint32_t waveTime = 0; - uint32_t waveCompleteDelay = 0; - std::string eventGroup; - std::string introCelebration; + uint32_t acceptedDelay = 0; + uint32_t startDelay = 0; + uint32_t waveTime = 0; + uint32_t waveCompleteDelay = 0; + std::string eventGroup; + std::string introCelebration; }; class BaseWavesServer : public ActivityManager { public: - void OnStartup(Entity* self) override { SetGameVariables(self); BaseStartup(self); }; - void OnPlayerLoaded(Entity* self, Entity* player) override { BasePlayerLoaded(self, player); }; - void OnPlayerExit(Entity* self, Entity* player) override { BasePlayerExit(self, player); }; - void OnFireEventServerSide(Entity *self, Entity *sender, std::string args, int32_t param1, int32_t param2, - int32_t param3) override { BaseFireEvent(self, sender, args, param1, param2, param3); }; - void OnPlayerDied(Entity* self, Entity* player) override { BasePlayerDied(self, player); }; - void OnPlayerResurrected(Entity* self, Entity* player) override { BasePlayerResurrected(self, player); }; - void OnMessageBoxResponse(Entity* self, Entity* sender, int32_t button, const std::u16string& identifier, - const std::u16string& userData) override - { BaseMessageBoxResponse(self, sender, button, identifier, userData); }; + void OnStartup(Entity* self) override { SetGameVariables(self); BaseStartup(self); }; + void OnPlayerLoaded(Entity* self, Entity* player) override { BasePlayerLoaded(self, player); }; + void OnPlayerExit(Entity* self, Entity* player) override { BasePlayerExit(self, player); }; + void OnFireEventServerSide(Entity* self, Entity* sender, std::string args, int32_t param1, int32_t param2, + int32_t param3) override { + BaseFireEvent(self, sender, args, param1, param2, param3); + }; + void OnPlayerDied(Entity* self, Entity* player) override { BasePlayerDied(self, player); }; + void OnPlayerResurrected(Entity* self, Entity* player) override { BasePlayerResurrected(self, player); }; + void OnMessageBoxResponse(Entity* self, Entity* sender, int32_t button, const std::u16string& identifier, + const std::u16string& userData) override { + BaseMessageBoxResponse(self, sender, button, identifier, userData); + }; - void BasePlayerLoaded(Entity* self, Entity* player); - void BaseStartup(Entity* self); - void BasePlayerExit(Entity* self, Entity* player); - void BaseFireEvent(Entity *self, Entity *sender, const std::string& args, int32_t param1, int32_t param2, - int32_t param3); - void BasePlayerDied(Entity* self, Entity* player); - void BasePlayerResurrected(Entity* self, Entity* player); - void BaseMessageBoxResponse(Entity* self, Entity* sender, int32_t button, const std::u16string& identifier, const std::u16string& userData); + void BasePlayerLoaded(Entity* self, Entity* player); + void BaseStartup(Entity* self); + void BasePlayerExit(Entity* self, Entity* player); + void BaseFireEvent(Entity* self, Entity* sender, const std::string& args, int32_t param1, int32_t param2, + int32_t param3); + void BasePlayerDied(Entity* self, Entity* player); + void BasePlayerResurrected(Entity* self, Entity* player); + void BaseMessageBoxResponse(Entity* self, Entity* sender, int32_t button, const std::u16string& identifier, const std::u16string& userData); - void OnActivityTimerDone(Entity *self, const std::string &name) override; - void OnActivityTimerUpdate(Entity *self, const std::string &name, float_t remainingTime, float_t elapsedTime) override; + void OnActivityTimerDone(Entity* self, const std::string& name) override; + void OnActivityTimerUpdate(Entity* self, const std::string& name, float_t remainingTime, float_t elapsedTime) override; protected: - virtual WaveConstants GetConstants() { return WaveConstants(); }; - virtual std::vector GetWaves() { return {}; }; - virtual std::vector GetWaveMissions() { return {}; }; - virtual std::vector GetSpawnerNames() { return {}; } - WavesGameState state {}; + virtual WaveConstants GetConstants() { return WaveConstants(); }; + virtual std::vector GetWaves() { return {}; }; + virtual std::vector GetWaveMissions() { return {}; }; + virtual std::vector GetSpawnerNames() { return {}; } + WavesGameState state{}; - // Mob set default names - std::string BaseMobSet = "baseMobSet"; - std::string RandMobSet = "randMobSet"; + // Mob set default names + std::string BaseMobSet = "baseMobSet"; + std::string RandMobSet = "randMobSet"; - // Variable names - std::u16string WavesStartedVariable = u"wavesStarted"; - std::u16string ShowScoreboardVariable = u"Show_ScoreBoard"; - std::u16string WatchingIntroVariable = u"WatchingIntro"; - std::u16string ClearScoreboardVariable = u"Clear_Scoreboard"; - std::u16string DefinePlayerToUIVariable = u"Define_Player_To_UI"; - std::u16string UpdateScoreboardPlayersVariable = u"Update_ScoreBoard_Players."; - std::u16string PlayerConfirmVariable = u"PlayerConfirm_ScoreBoard."; - std::u16string PlayersAcceptedVariable = u"playersAccepted"; - std::u16string PlayersReadyVariable = u"playersReady"; - std::u16string BaseMobSetIndexVariable = u"baseMobSetNum"; - std::u16string RandMobSetIndexVariable = u"randMobSetNum"; - std::u16string AcceptedDelayStartedVariable = u"AcceptedDelayStarted"; - std::u16string NumberOfPlayersVariable = u"NumberOfPlayers"; - std::u16string FirstTimeDoneVariable = u"firstTimeDone"; - std::u16string MissionTypeVariable = u"missionType"; - std::u16string StartWaveMessageVariable = u"Start_Wave_Message"; - std::u16string ExitWavesVariable = u"Exit_waves"; - std::u16string UpdateDefaultStartTimerVariable = u"Update_Default_Start_Timer"; - std::u16string UpdateTimerVariable = u"Update_Timer"; - std::u16string UpdateCooldownVariable = u"Update_Cool_Down"; - std::u16string IsCooldownVariable = u"isCoolDown"; - std::u16string SpawnMobVariable = u"Spawn_Mob"; - std::u16string WonWaveVariable = u"Won_Wave"; - std::u16string WaveCompleteVariable = u"Wave_Complete"; - std::u16string StartTimedWaveVariable = u"Start_Timed_Wave"; - std::u16string NewWaveVariable = u"New_Wave"; - std::u16string StartCinematicVariable = u"startCinematic"; - std::u16string NumRemainingVariable = u"numRemaining"; - std::u16string StartCooldownVariable = u"Start_Cool_Down"; + // Variable names + std::u16string WavesStartedVariable = u"wavesStarted"; + std::u16string ShowScoreboardVariable = u"Show_ScoreBoard"; + std::u16string WatchingIntroVariable = u"WatchingIntro"; + std::u16string ClearScoreboardVariable = u"Clear_Scoreboard"; + std::u16string DefinePlayerToUIVariable = u"Define_Player_To_UI"; + std::u16string UpdateScoreboardPlayersVariable = u"Update_ScoreBoard_Players."; + std::u16string PlayerConfirmVariable = u"PlayerConfirm_ScoreBoard."; + std::u16string PlayersAcceptedVariable = u"playersAccepted"; + std::u16string PlayersReadyVariable = u"playersReady"; + std::u16string BaseMobSetIndexVariable = u"baseMobSetNum"; + std::u16string RandMobSetIndexVariable = u"randMobSetNum"; + std::u16string AcceptedDelayStartedVariable = u"AcceptedDelayStarted"; + std::u16string NumberOfPlayersVariable = u"NumberOfPlayers"; + std::u16string FirstTimeDoneVariable = u"firstTimeDone"; + std::u16string MissionTypeVariable = u"missionType"; + std::u16string StartWaveMessageVariable = u"Start_Wave_Message"; + std::u16string ExitWavesVariable = u"Exit_waves"; + std::u16string UpdateDefaultStartTimerVariable = u"Update_Default_Start_Timer"; + std::u16string UpdateTimerVariable = u"Update_Timer"; + std::u16string UpdateCooldownVariable = u"Update_Cool_Down"; + std::u16string IsCooldownVariable = u"isCoolDown"; + std::u16string SpawnMobVariable = u"Spawn_Mob"; + std::u16string WonWaveVariable = u"Won_Wave"; + std::u16string WaveCompleteVariable = u"Wave_Complete"; + std::u16string StartTimedWaveVariable = u"Start_Timed_Wave"; + std::u16string NewWaveVariable = u"New_Wave"; + std::u16string StartCinematicVariable = u"startCinematic"; + std::u16string NumRemainingVariable = u"numRemaining"; + std::u16string StartCooldownVariable = u"Start_Cool_Down"; - // Timer names - std::string SpawnTickTimer = "SpawnTick"; - std::string AllAcceptedDelayTimer = "AllAcceptedDelay"; - std::string AcceptedDelayTimer = "AcceptedDelay"; - std::string StartDelayTimer = "StartDelay"; - std::string ClockTickTimer = "ClockTick"; - std::string CoolDownStartTimer = "CoolDownStart"; - std::string CoolDownStopTimer = "CoolDownStop"; - std::string PlaySpawnSoundTimer = "PlaySpawnSound"; - std::string NextWaveTickTimer = "NextWaveTick"; - std::string WaveCompleteDelayTimer = "WaveCompleteDelay"; - std::string TimedWaveTimer = "TimedWave"; - std::string GameOverWinTimer = "GameOverWin"; - std::string CinematicDoneTimer = "CinematicDone"; + // Timer names + std::string SpawnTickTimer = "SpawnTick"; + std::string AllAcceptedDelayTimer = "AllAcceptedDelay"; + std::string AcceptedDelayTimer = "AcceptedDelay"; + std::string StartDelayTimer = "StartDelay"; + std::string ClockTickTimer = "ClockTick"; + std::string CoolDownStartTimer = "CoolDownStart"; + std::string CoolDownStopTimer = "CoolDownStop"; + std::string PlaySpawnSoundTimer = "PlaySpawnSound"; + std::string NextWaveTickTimer = "NextWaveTick"; + std::string WaveCompleteDelayTimer = "WaveCompleteDelay"; + std::string TimedWaveTimer = "TimedWave"; + std::string GameOverWinTimer = "GameOverWin"; + std::string CinematicDoneTimer = "CinematicDone"; - std::string spawnSoundGUID = "{ca36045d-89df-4e96-a317-1e152d226b69}"; + std::string spawnSoundGUID = "{ca36045d-89df-4e96-a317-1e152d226b69}"; private: - void SetGameVariables(Entity* self); - static void ResetStats(LWOOBJID player); - void GameOver(Entity* self, bool won = false); - void GameWon(Entity* self); - void UpdateMissionForAllPlayers(Entity* self, uint32_t missionID); + void SetGameVariables(Entity* self); + static void ResetStats(LWOOBJID player); + void GameOver(Entity* self, bool won = false); + void GameWon(Entity* self); + void UpdateMissionForAllPlayers(Entity* self, uint32_t missionID); - void StartWaves(Entity* self); - void SpawnWave(Entity* self); - static void SpawnNow(const std::string& spawnerName, uint32_t amount, LOT spawnLot); - bool UpdateSpawnedEnemies(Entity* self, LWOOBJID enemyID, uint32_t score); + void StartWaves(Entity* self); + void SpawnWave(Entity* self); + static void SpawnNow(const std::string& spawnerName, uint32_t amount, LOT spawnLot); + bool UpdateSpawnedEnemies(Entity* self, LWOOBJID enemyID, uint32_t score); - bool CheckAllPlayersDead(); - void SetPlayerSpawnPoints(const LWOOBJID& specificPlayerID = LWOOBJID_EMPTY); - void PlayerConfirmed(Entity* self); - void PlayerAccepted(Entity* self, LWOOBJID playerID); - void ClearSpawners(); + bool CheckAllPlayersDead(); + void SetPlayerSpawnPoints(const LWOOBJID& specificPlayerID = LWOOBJID_EMPTY); + void PlayerConfirmed(Entity* self); + void PlayerAccepted(Entity* self, LWOOBJID playerID); + void ClearSpawners(); - WaveConstants constants {}; - std::vector waves {}; - std::vector missions {}; - std::vector spawners {}; + WaveConstants constants{}; + std::vector waves{}; + std::vector missions{}; + std::vector spawners{}; }; diff --git a/dScripts/Binoculars.cpp b/dScripts/Binoculars.cpp index 348b3842..854ccf71 100644 --- a/dScripts/Binoculars.cpp +++ b/dScripts/Binoculars.cpp @@ -12,4 +12,4 @@ void Binoculars::OnUse(Entity* self, Entity* user) { user->GetCharacter()->SetPlayerFlag(flag, true); GameMessages::SendFireEventClientSide(self->GetObjectID(), user->GetSystemAddress(), u"achieve", LWOOBJID_EMPTY, 0, -1, LWOOBJID_EMPTY); } -} \ No newline at end of file +} diff --git a/dScripts/Binoculars.h b/dScripts/Binoculars.h index 141b3fb9..2f446119 100644 --- a/dScripts/Binoculars.h +++ b/dScripts/Binoculars.h @@ -4,4 +4,4 @@ class Binoculars : public CppScripts::Script { public: void OnUse(Entity* self, Entity* user); -}; \ No newline at end of file +}; diff --git a/dScripts/BootyDigServer.cpp b/dScripts/BootyDigServer.cpp index 50d873e0..d38791d8 100644 --- a/dScripts/BootyDigServer.cpp +++ b/dScripts/BootyDigServer.cpp @@ -4,49 +4,49 @@ #include "MissionComponent.h" #include "MissionTaskType.h" -void BootyDigServer::OnStartup(Entity *self) { - auto* zoneControlObject = EntityManager::Instance()->GetZoneControlEntity(); - if (zoneControlObject != nullptr) { - zoneControlObject->OnFireEventServerSide(self, "CheckForPropertyOwner"); - } +void BootyDigServer::OnStartup(Entity* self) { + auto* zoneControlObject = EntityManager::Instance()->GetZoneControlEntity(); + if (zoneControlObject != nullptr) { + zoneControlObject->OnFireEventServerSide(self, "CheckForPropertyOwner"); + } } -void BootyDigServer::OnPlayerLoaded(Entity *self, Entity *player) { - auto* zoneControlObject = EntityManager::Instance()->GetZoneControlEntity(); - if (zoneControlObject != nullptr) { - zoneControlObject->OnFireEventServerSide(self, "CheckForPropertyOwner"); - } +void BootyDigServer::OnPlayerLoaded(Entity* self, Entity* player) { + auto* zoneControlObject = EntityManager::Instance()->GetZoneControlEntity(); + if (zoneControlObject != nullptr) { + zoneControlObject->OnFireEventServerSide(self, "CheckForPropertyOwner"); + } } void -BootyDigServer::OnFireEventServerSide(Entity *self, Entity *sender, std::string args, int32_t param1, int32_t param2, - int32_t param3) { +BootyDigServer::OnFireEventServerSide(Entity* self, Entity* sender, std::string args, int32_t param1, int32_t param2, + int32_t param3) { - auto propertyOwner = self->GetNetworkVar(u"PropertyOwnerID"); - auto* player = self->GetParentEntity(); - if (player == nullptr) - return; + auto propertyOwner = self->GetNetworkVar(u"PropertyOwnerID"); + auto* player = self->GetParentEntity(); + if (player == nullptr) + return; - if (args == "ChestReady" && (propertyOwner == std::to_string(LWOOBJID_EMPTY) || player->GetVar(u"bootyDug"))) { - self->Smash(self->GetObjectID(), SILENT); - } else if (args == "ChestOpened") { - // Make sure players only dig up one booty per instance - player->SetVar(u"bootyDug", true); + if (args == "ChestReady" && (propertyOwner == std::to_string(LWOOBJID_EMPTY) || player->GetVar(u"bootyDug"))) { + self->Smash(self->GetObjectID(), SILENT); + } else if (args == "ChestOpened") { + // Make sure players only dig up one booty per instance + player->SetVar(u"bootyDug", true); - auto* missionComponent = player->GetComponent(); - if (missionComponent != nullptr) { - auto* mission = missionComponent->GetMission(1881); - if (mission != nullptr && (mission->GetMissionState() == MissionState::MISSION_STATE_ACTIVE || mission->GetMissionState() == MissionState::MISSION_STATE_COMPLETE_ACTIVE)) { - mission->Progress(MissionTaskType::MISSION_TASK_TYPE_SCRIPT, self->GetLOT()); + auto* missionComponent = player->GetComponent(); + if (missionComponent != nullptr) { + auto* mission = missionComponent->GetMission(1881); + if (mission != nullptr && (mission->GetMissionState() == MissionState::MISSION_STATE_ACTIVE || mission->GetMissionState() == MissionState::MISSION_STATE_COMPLETE_ACTIVE)) { + mission->Progress(MissionTaskType::MISSION_TASK_TYPE_SCRIPT, self->GetLOT()); - auto* renderComponent = self->GetComponent(); - if (renderComponent != nullptr) - renderComponent->PlayEffect(7730, u"cast", "bootyshine"); + auto* renderComponent = self->GetComponent(); + if (renderComponent != nullptr) + renderComponent->PlayEffect(7730, u"cast", "bootyshine"); - LootGenerator::Instance().DropLoot(player, self, 231, 75, 75); - } - } - } else if (args == "ChestDead") { - self->Smash(player->GetObjectID(), SILENT); - } + LootGenerator::Instance().DropLoot(player, self, 231, 75, 75); + } + } + } else if (args == "ChestDead") { + self->Smash(player->GetObjectID(), SILENT); + } } diff --git a/dScripts/BootyDigServer.h b/dScripts/BootyDigServer.h index dde41e29..3f73a530 100644 --- a/dScripts/BootyDigServer.h +++ b/dScripts/BootyDigServer.h @@ -2,7 +2,7 @@ #include "CppScripts.h" class BootyDigServer : public CppScripts::Script { - void OnStartup(Entity *self) override; - void OnPlayerLoaded(Entity *self, Entity *player) override; - void OnFireEventServerSide(Entity *self, Entity *sender, std::string args, int32_t param1, int32_t param2, int32_t param3) override; + void OnStartup(Entity* self) override; + void OnPlayerLoaded(Entity* self, Entity* player) override; + void OnFireEventServerSide(Entity* self, Entity* sender, std::string args, int32_t param1, int32_t param2, int32_t param3) override; }; diff --git a/dScripts/BossSpiderQueenEnemyServer.cpp b/dScripts/BossSpiderQueenEnemyServer.cpp index 88f05a4b..438493fe 100644 --- a/dScripts/BossSpiderQueenEnemyServer.cpp +++ b/dScripts/BossSpiderQueenEnemyServer.cpp @@ -67,7 +67,7 @@ void BossSpiderQueenEnemyServer::OnDie(Entity* self, Entity* killer) { GameMessages::SendNotifyClientObject(self->GetObjectID(), u"SetColGroup", 10, 0, 0, "", UNASSIGNED_SYSTEM_ADDRESS); - self->SetPosition({10000, 0, 10000}); + self->SetPosition({ 10000, 0, 10000 }); EntityManager::Instance()->SerializeEntity(self); @@ -119,8 +119,7 @@ void BossSpiderQueenEnemyServer::WithdrawSpider(Entity* self, const bool withdra self->AddTimer("WithdrawComplete", withdrawTime + 1.0f); waitForIdle = true; - } - else { + } else { controllable->SetStatic(false); //Cancel all remaining timers for say idle anims: @@ -131,10 +130,10 @@ void BossSpiderQueenEnemyServer::WithdrawSpider(Entity* self, const bool withdra baseCombatAi->SetDisabled(false); // Move the Spider to its ground location - // preparing its stage attacks, and removing invulnerability + // preparing its stage attacks, and removing invulnerability //destroyable->SetIsImmune(false); - // Run the advance animation and prepare a timer for resuming AI + // Run the advance animation and prepare a timer for resuming AI float animTime = PlayAnimAndReturnTime(self, spiderAdvanceAnim); animTime += 1.f; @@ -143,18 +142,18 @@ void BossSpiderQueenEnemyServer::WithdrawSpider(Entity* self, const bool withdra destroyable->SetFaction(4); destroyable->SetIsImmune(false); - //Advance stage + //Advance stage m_CurrentBossStage++; - //Reset the current wave death counter + //Reset the current wave death counter m_DeathCounter = 0; EntityManager::Instance()->SerializeEntity(self); - // Prepare a timer for post leap attack + // Prepare a timer for post leap attack self->AddTimer("AdvanceAttack", attackPause); - // Prepare a timer for post leap + // Prepare a timer for post leap self->AddTimer("AdvanceComplete", animTime); } @@ -179,7 +178,7 @@ void BossSpiderQueenEnemyServer::SpawnSpiderWave(Entity* self, int spiderCount) Game::logger->Log("SpiderQueen", "Trying to spawn %i spiders", hatchCounter); - // Run the wave manager + // Run the wave manager SpiderWaveManager(self); } @@ -268,8 +267,7 @@ void BossSpiderQueenEnemyServer::SpiderWaveManager(Entity* self) { // We still have more eggs to hatch, poll the SpiderWaveManager again self->AddTimer("PollSpiderWaveManager", 1.0f); - } - else { + } else { // We have successfully readied a full wave // initiate hatching! for (auto egg : hatchList) { @@ -298,17 +296,14 @@ void BossSpiderQueenEnemyServer::SpiderWaveManager(Entity* self) { } -void BossSpiderQueenEnemyServer::ToggleForSpecial(Entity* self, const bool state) -{ +void BossSpiderQueenEnemyServer::ToggleForSpecial(Entity* self, const bool state) { self->SetBoolean(u"stoppedFlag", state); combat->SetDisabled(state); } -void BossSpiderQueenEnemyServer::RunRainOfFire(Entity* self) -{ - if (self->GetBoolean(u"stoppedFlag")) - { +void BossSpiderQueenEnemyServer::RunRainOfFire(Entity* self) { + if (self->GetBoolean(u"stoppedFlag")) { self->AddTimer("ROF", GeneralUtils::GenerateRandomNumber(10, 20)); return; @@ -319,26 +314,20 @@ void BossSpiderQueenEnemyServer::RunRainOfFire(Entity* self) impactList.clear(); auto index = 0u; - for (const auto& rofGroup : ROFTargetGroupIDTable) - { + for (const auto& rofGroup : ROFTargetGroupIDTable) { const auto spawners = dZoneManager::Instance()->GetSpawnersInGroup(rofGroup); std::vector spawned; - for (auto* spawner : spawners) - { - for (const auto* node : spawner->m_Info.nodes) - { + for (auto* spawner : spawners) { + for (const auto* node : spawner->m_Info.nodes) { spawned.insert(spawned.end(), node->entities.begin(), node->entities.end()); } } - if (index == 0) - { + if (index == 0) { impactList.insert(impactList.end(), spawned.begin(), spawned.end()); - } - else - { + } else { const auto randomIndex = GeneralUtils::GenerateRandomNumber(0, spawned.size() - 1); impactList.push_back(spawned[randomIndex]); @@ -352,16 +341,13 @@ void BossSpiderQueenEnemyServer::RunRainOfFire(Entity* self) self->AddTimer("StartROF", animTime); } -void BossSpiderQueenEnemyServer::RainOfFireManager(Entity* self) -{ - if (!impactList.empty()) - { +void BossSpiderQueenEnemyServer::RainOfFireManager(Entity* self) { + if (!impactList.empty()) { auto* entity = EntityManager::Instance()->GetEntity(impactList[0]); impactList.erase(impactList.begin()); - if (entity == nullptr) - { + if (entity == nullptr) { Game::logger->Log("BossSpiderQueenEnemyServer", "Failed to find impact!"); return; @@ -369,8 +355,7 @@ void BossSpiderQueenEnemyServer::RainOfFireManager(Entity* self) auto* skillComponent = entity->GetComponent(); - if (skillComponent == nullptr) - { + if (skillComponent == nullptr) { Game::logger->Log("BossSpiderQueenEnemyServer", "Failed to find impact skill component!"); return; @@ -388,10 +373,8 @@ void BossSpiderQueenEnemyServer::RainOfFireManager(Entity* self) self->AddTimer("ROF", GeneralUtils::GenerateRandomNumber(20, 40)); } -void BossSpiderQueenEnemyServer::RapidFireShooterManager(Entity* self) -{ - if (attackTargetTable.empty()) - { +void BossSpiderQueenEnemyServer::RapidFireShooterManager(Entity* self) { + if (attackTargetTable.empty()) { const auto animationTime = PlayAnimAndReturnTime(self, spiderJeerAnim); self->AddTimer("RFSTauntComplete", animationTime); @@ -412,23 +395,20 @@ void BossSpiderQueenEnemyServer::RapidFireShooterManager(Entity* self) self->AddTimer("PollRFSManager", 0.3f); } -void BossSpiderQueenEnemyServer::RunRapidFireShooter(Entity* self) -{ +void BossSpiderQueenEnemyServer::RunRapidFireShooter(Entity* self) { /* const auto targets = EntityManager::Instance()->GetEntitiesByComponent(COMPONENT_TYPE_CHARACTER); */ const auto targets = self->GetTargetsInPhantom(); - if (self->GetBoolean(u"stoppedFlag")) - { + if (self->GetBoolean(u"stoppedFlag")) { self->AddTimer("RFS", GeneralUtils::GenerateRandomNumber(5, 10)); return; } - if (targets.empty()) - { + if (targets.empty()) { Game::logger->Log("BossSpiderQueenEnemyServer", "Failed to find RFS targets"); self->AddTimer("RFS", GeneralUtils::GenerateRandomNumber(5, 10)); @@ -459,12 +439,10 @@ void BossSpiderQueenEnemyServer::RunRapidFireShooter(Entity* self) void BossSpiderQueenEnemyServer::OnTimerDone(Entity* self, const std::string timerName) { if (timerName == "PollSpiderWaveManager") { - //Call the manager again to attempt to finish prepping a Spiderling wave - //Run the wave manager + //Call the manager again to attempt to finish prepping a Spiderling wave + //Run the wave manager SpiderWaveManager(self); - } - else if (timerName == "disableWaitForIdle") { waitForIdle = false; } - else if (timerName == "checkForSpiders") { + } else if (timerName == "disableWaitForIdle") { waitForIdle = false; } else if (timerName == "checkForSpiders") { //Don't do anything if we ain't withdrawn: const auto withdrawn = self->GetBoolean(u"isWithdrawn"); if (!withdrawn) return; @@ -491,54 +469,53 @@ void BossSpiderQueenEnemyServer::OnTimerDone(Entity* self, const std::string tim self->AddTimer("checkForSpiders", time); else WithdrawSpider(self, false); - } - else if (timerName == "PollROFManager") { - //Call the manager again to attempt to initiate an impact on another random location - //Run the ROF Manager + } else if (timerName == "PollROFManager") { + //Call the manager again to attempt to initiate an impact on another random location + //Run the ROF Manager RainOfFireManager(self); - } else if ( timerName == "PollRFSManager") { - //Call the manager again to attempt to initiate a rapid fire shot at the next sequential target - //Run the ROF Manager + } else if (timerName == "PollRFSManager") { + //Call the manager again to attempt to initiate a rapid fire shot at the next sequential target + //Run the ROF Manager RapidFireShooterManager(self); - } else if ( timerName == "StartROF") { - //Re-enable Spider Boss + } else if (timerName == "StartROF") { + //Re-enable Spider Boss //ToggleForSpecial(self, false); RainOfFireManager(self); - } else if ( timerName == "PollSpiderSkillManager") { - //Call the skill manager again to attempt to run the current Spider Boss - //stage's special attack again + } else if (timerName == "PollSpiderSkillManager") { + //Call the skill manager again to attempt to run the current Spider Boss + //stage's special attack again //SpiderSkillManager(self, true); PlayAnimAndReturnTime(self, spiderJeerAnim); - } else if ( timerName == "RFS") { + } else if (timerName == "RFS") { RunRapidFireShooter(self); - } else if ( timerName == "ROF") { + } else if (timerName == "ROF") { RunRainOfFire(self); - } else if ( timerName == "RFSTauntComplete") { - //Determine an appropriate random time to check our manager again - // local spiderCooldownDelay = math.random(s1DelayMin, s1DelayMax) + } else if (timerName == "RFSTauntComplete") { + //Determine an appropriate random time to check our manager again + // local spiderCooldownDelay = math.random(s1DelayMin, s1DelayMax) - //Set a timer based on our random cooldown determination - //to pulse the SpiderSkillManager again + //Set a timer based on our random cooldown determination + //to pulse the SpiderSkillManager again //GAMEOBJ:GetTimer():AddTimerWithCancel(spiderCooldownDelay, "PollSpiderSkillManager", self) - //Re-enable Spider Boss - //ToggleForSpecial(self, false); + //Re-enable Spider Boss + //ToggleForSpecial(self, false); - } else if ( timerName == "WithdrawComplete") { - //Play the Spider Boss' mountain idle anim + } else if (timerName == "WithdrawComplete") { + //Play the Spider Boss' mountain idle anim PlayAnimAndReturnTime(self, spiderWithdrawIdle); - //The Spider Boss has retreated, hatch a wave! + //The Spider Boss has retreated, hatch a wave! int currentStage = m_CurrentBossStage; - //Prepare a Spiderling wave and initiate egg hatch events - //self->SetVar(u"SpiderWaveCount", ) + //Prepare a Spiderling wave and initiate egg hatch events + //self->SetVar(u"SpiderWaveCount", ) //TODO: Actually spawn the spiders here hatchCounter = 2; @@ -546,53 +523,51 @@ void BossSpiderQueenEnemyServer::OnTimerDone(Entity* self, const std::string tim SpawnSpiderWave(self, spiderWaveCntTable[currentStage - 1]); - } else if ( timerName == "AdvanceAttack") { + } else if (timerName == "AdvanceAttack") { //TODO: Can we even do knockbacks yet? @Wincent01 // Yes ^ - //Fire the melee smash skill to throw players back - /*local landingTarget = self:GetVar("LandingTarget") or false + //Fire the melee smash skill to throw players back + /*local landingTarget = self:GetVar("LandingTarget") or false - if((landingTarget) and (landingTarget:Exists())) { - local advSmashFlag = landingTarget:CastSkill{skillID = bossLandingSkill} - landingTarget:PlayEmbeddedEffectOnAllClientsNearObject{radius = 100, fromObjectID = landingTarget, effectName = "camshake-bridge"} - }*/ + if((landingTarget) and (landingTarget:Exists())) { + local advSmashFlag = landingTarget:CastSkill{skillID = bossLandingSkill} + landingTarget:PlayEmbeddedEffectOnAllClientsNearObject{radius = 100, fromObjectID = landingTarget, effectName = "camshake-bridge"} + }*/ auto landingTarget = self->GetI64(u"LandingTarget"); auto landingEntity = EntityManager::Instance()->GetEntity(landingTarget); auto* skillComponent = self->GetComponent(); - if (skillComponent != nullptr) - { + if (skillComponent != nullptr) { skillComponent->CalculateBehavior(bossLandingSkill, 37739, LWOOBJID_EMPTY); } if (landingEntity) { auto* landingSkill = landingEntity->GetComponent(); - if (landingSkill != nullptr) - { + if (landingSkill != nullptr) { landingSkill->CalculateBehavior(bossLandingSkill, 37739, LWOOBJID_EMPTY, true); } } GameMessages::SendPlayEmbeddedEffectOnAllClientsNearObject(self, u"camshake-bridge", self->GetObjectID(), 100.0f); - } else if ( timerName == "AdvanceComplete") { - //Reset faction and collision - /*local SBFactionList = self:GetVar("SBFactionList") - local SBCollisionGroup = self:GetVar("SBCollisionGroup") + } else if (timerName == "AdvanceComplete") { + //Reset faction and collision + /*local SBFactionList = self:GetVar("SBFactionList") + local SBCollisionGroup = self:GetVar("SBCollisionGroup") - for i, fVal in ipairs(SBFactionList) { - if(i == 1) { - //Our first faction - flush and add - self:SetFaction{faction = fVal} - else - //Add - self:ModifyFaction{factionID = fVal, bAddFaction = true} - } - }*/ + for i, fVal in ipairs(SBFactionList) { + if(i == 1) { + //Our first faction - flush and add + self:SetFaction{faction = fVal} + else + //Add + self:ModifyFaction{factionID = fVal, bAddFaction = true} + } + }*/ /* auto SBCollisionGroup = self->GetI32(u"SBCollisionGroup"); @@ -602,71 +577,68 @@ void BossSpiderQueenEnemyServer::OnTimerDone(Entity* self, const std::string tim GameMessages::SendNotifyClientObject(self->GetObjectID(), u"SetColGroup", 11, 0, 0, "", UNASSIGNED_SYSTEM_ADDRESS); - //Wind up, telegraphing next round + //Wind up, telegraphing next round float animTime = PlayAnimAndReturnTime(self, spiderJeerAnim); self->AddTimer("AdvanceTauntComplete", animTime); - } else if ( timerName == "AdvanceTauntComplete") { + } else if (timerName == "AdvanceTauntComplete") { - //Declare a default special Spider Boss skill cooldown + //Declare a default special Spider Boss skill cooldown int spiderCooldownDelay = 10; - if(m_CurrentBossStage == 2) { + if (m_CurrentBossStage == 2) { spiderCooldownDelay = GeneralUtils::GenerateRandomNumber(s1DelayMin, s1DelayMax); - } else if (m_CurrentBossStage == 3) { - spiderCooldownDelay = GeneralUtils::GenerateRandomNumber(s2DelayMin, s2DelayMax); - } + } else if (m_CurrentBossStage == 3) { + spiderCooldownDelay = GeneralUtils::GenerateRandomNumber(s2DelayMin, s2DelayMax); + } - //Set a timer based on our random cooldown determination - //to pulse the SpiderSkillManager + //Set a timer based on our random cooldown determination + //to pulse the SpiderSkillManager self->AddTimer("PollSpiderSkillManager", spiderCooldownDelay); - //Remove current status immunity - /*self:SetStatusImmunity{ StateChangeType = "POP", bImmuneToSpeed = true, bImmuneToBasicAttack = true, bImmuneToDOT = true} + //Remove current status immunity + /*self:SetStatusImmunity{ StateChangeType = "POP", bImmuneToSpeed = true, bImmuneToBasicAttack = true, bImmuneToDOT = true} - self:SetStunned{StateChangeType = "POP", - bCantMove = true, - bCantJump = true, - bCantTurn = true, - bCantAttack = true, - bCantUseItem = true, - bCantEquip = true, - bCantInteract = true, - bIgnoreImmunity = true}*/ + self:SetStunned{StateChangeType = "POP", + bCantMove = true, + bCantJump = true, + bCantTurn = true, + bCantAttack = true, + bCantUseItem = true, + bCantEquip = true, + bCantInteract = true, + bIgnoreImmunity = true}*/ destroyable->SetIsImmune(false); destroyable->SetFaction(4); EntityManager::Instance()->SerializeEntity(self); - } else if ( timerName == "Clear") { + } else if (timerName == "Clear") { EntityManager::Instance()->FireEventServerSide(self, "ClearProperty"); self->CancelAllTimers(); - } else if ( timerName == "UnlockSpecials") { - //We no longer need to lock specials + } else if (timerName == "UnlockSpecials") { + //We no longer need to lock specials self->SetBoolean(u"bSpecialLock", false); - //Did we queue a spcial attack? - if(self->GetBoolean(u"bSpecialQueued")) { + //Did we queue a spcial attack? + if (self->GetBoolean(u"bSpecialQueued")) { self->SetBoolean(u"bSpecialQueued", false); //SpiderSkillManager(self, true); - } + } } } void BossSpiderQueenEnemyServer::OnHitOrHealResult(Entity* self, Entity* attacker, int32_t damage) { - if (m_CurrentBossStage > 0 && !self->HasTimer("RFS")) - { + if (m_CurrentBossStage > 0 && !self->HasTimer("RFS")) { self->AddTimer("RFS", 5.0f); } - if (m_CurrentBossStage > 0 && !self->HasTimer("ROF")) - { + if (m_CurrentBossStage > 0 && !self->HasTimer("ROF")) { self->AddTimer("ROF", 10.0f); } - if (m_CurrentBossStage > ThresholdTable.size()) - { + if (m_CurrentBossStage > ThresholdTable.size()) { return; } @@ -691,8 +663,7 @@ void BossSpiderQueenEnemyServer::OnUpdate(Entity* self) { if (!isWithdrawn) return; - if (controllable->GetRotation() == NiQuaternion::IDENTITY) - { + if (controllable->GetRotation() == NiQuaternion::IDENTITY) { return; } diff --git a/dScripts/BossSpiderQueenEnemyServer.h b/dScripts/BossSpiderQueenEnemyServer.h index f3219cf7..e41b878d 100644 --- a/dScripts/BossSpiderQueenEnemyServer.h +++ b/dScripts/BossSpiderQueenEnemyServer.h @@ -19,25 +19,25 @@ class BaseCombatAIComponent; class BossSpiderQueenEnemyServer final : public CppScripts::Script { public: void OnStartup(Entity* self) override; - + void OnDie(Entity* self, Entity* killer) override; - + void OnHitOrHealResult(Entity* self, Entity* attacker, int32_t damage) override; - + void OnUpdate(Entity* self) override; void WithdrawSpider(Entity* self, bool withdraw); void SpawnSpiderWave(Entity* self, int spiderCount); - + void SpiderWaveManager(Entity* self); void ToggleForSpecial(Entity* self, bool state); - + void RunRainOfFire(Entity* self); void RainOfFireManager(Entity* self); - + void RapidFireShooterManager(Entity* self); void RunRapidFireShooter(Entity* self); @@ -53,7 +53,7 @@ private: BaseCombatAIComponent* combat = nullptr; NiQuaternion originRotation; - + int m_CurrentBossStage = 0; int m_DeathCounter = 0; std::vector ThresholdTable; diff --git a/dScripts/BuccaneerValiantShip.cpp b/dScripts/BuccaneerValiantShip.cpp index 710a0d1a..3db214b5 100644 --- a/dScripts/BuccaneerValiantShip.cpp +++ b/dScripts/BuccaneerValiantShip.cpp @@ -2,17 +2,17 @@ #include "SkillComponent.h" void BuccaneerValiantShip::OnStartup(Entity* self) { - self->AddCallbackTimer(1.0F, [self]() { - auto* skillComponent = self->GetComponent(); - auto* owner = self->GetOwner(); + self->AddCallbackTimer(1.0F, [self]() { + auto* skillComponent = self->GetComponent(); + auto* owner = self->GetOwner(); - if (skillComponent != nullptr && owner != nullptr) { - skillComponent->CalculateBehavior(982, 20577, LWOOBJID_EMPTY, true, false, owner->GetObjectID()); + if (skillComponent != nullptr && owner != nullptr) { + skillComponent->CalculateBehavior(982, 20577, LWOOBJID_EMPTY, true, false, owner->GetObjectID()); - // Kill self if missed - self->AddCallbackTimer(1.1F, [self]() { - self->Kill(); - }); - } - }); + // Kill self if missed + self->AddCallbackTimer(1.1F, [self]() { + self->Kill(); + }); + } + }); } diff --git a/dScripts/BuccaneerValiantShip.h b/dScripts/BuccaneerValiantShip.h index f501d1b9..8ed3f7ad 100644 --- a/dScripts/BuccaneerValiantShip.h +++ b/dScripts/BuccaneerValiantShip.h @@ -2,5 +2,5 @@ #include "CppScripts.h" class BuccaneerValiantShip : public CppScripts::Script { - void OnStartup(Entity *self) override; + void OnStartup(Entity* self) override; }; diff --git a/dScripts/BurningTile.cpp b/dScripts/BurningTile.cpp index b9a05391..8ac3dc5d 100644 --- a/dScripts/BurningTile.cpp +++ b/dScripts/BurningTile.cpp @@ -1,17 +1,14 @@ #include "BurningTile.h" #include "SkillComponent.h" -void BurningTile::OnFireEventServerSide(Entity *self, Entity *sender, std::string args, int32_t param1, int32_t param2, int32_t param3) -{ - if (args == "PlayerEntered") - { - auto* skillComponent = sender->GetComponent(); +void BurningTile::OnFireEventServerSide(Entity* self, Entity* sender, std::string args, int32_t param1, int32_t param2, int32_t param3) { + if (args == "PlayerEntered") { + auto* skillComponent = sender->GetComponent(); - if (skillComponent == nullptr) - { - return; - } + if (skillComponent == nullptr) { + return; + } - skillComponent->CalculateBehavior(726, 11723, sender->GetObjectID(), true); - } + skillComponent->CalculateBehavior(726, 11723, sender->GetObjectID(), true); + } } diff --git a/dScripts/BurningTile.h b/dScripts/BurningTile.h index 5f43895e..024ec6fc 100644 --- a/dScripts/BurningTile.h +++ b/dScripts/BurningTile.h @@ -4,5 +4,5 @@ class BurningTile : public CppScripts::Script { public: - void OnFireEventServerSide(Entity *self, Entity *sender, std::string args, int32_t param1, int32_t param2, int32_t param3) override; -}; \ No newline at end of file + void OnFireEventServerSide(Entity* self, Entity* sender, std::string args, int32_t param1, int32_t param2, int32_t param3) override; +}; diff --git a/dScripts/CatapultBaseServer.cpp b/dScripts/CatapultBaseServer.cpp index 33539de8..fda103b0 100644 --- a/dScripts/CatapultBaseServer.cpp +++ b/dScripts/CatapultBaseServer.cpp @@ -2,30 +2,25 @@ #include "GameMessages.h" #include "EntityManager.h" -void CatapultBaseServer::OnNotifyObject(Entity *self, Entity *sender, const std::string& name, int32_t param1, int32_t param2) -{ - if (name == "BouncerBuilt") - { - // start a timer for the arm to player the with bouncer animation - self->AddTimer("PlatAnim", .75); +void CatapultBaseServer::OnNotifyObject(Entity* self, Entity* sender, const std::string& name, int32_t param1, int32_t param2) { + if (name == "BouncerBuilt") { + // start a timer for the arm to player the with bouncer animation + self->AddTimer("PlatAnim", .75); - // set the bouncer so we can use it later - self->SetVar(u"Bouncer", sender->GetObjectID()); + // set the bouncer so we can use it later + self->SetVar(u"Bouncer", sender->GetObjectID()); GameMessages::SendBouncerActiveStatus(sender->GetObjectID(), true, UNASSIGNED_SYSTEM_ADDRESS); } } -void CatapultBaseServer::OnTimerDone(Entity* self, std::string timerName) -{ - if (timerName == "PlatAnim") - { - // get the arm asset - const auto arm = EntityManager::Instance()->GetEntitiesInGroup(self->GetVarAsString(u"ArmGroup")); +void CatapultBaseServer::OnTimerDone(Entity* self, std::string timerName) { + if (timerName == "PlatAnim") { + // get the arm asset + const auto arm = EntityManager::Instance()->GetEntitiesInGroup(self->GetVarAsString(u"ArmGroup")); // tell the arm to the play the platform animation, which is just the arm laying there but with bouncer - for (auto* obj : arm) - { + for (auto* obj : arm) { GameMessages::SendPlayAnimation(obj, u"idle-platform"); GameMessages::SendPlayNDAudioEmitter(obj, UNASSIGNED_SYSTEM_ADDRESS, "{8cccf912-69e3-4041-a20b-63e4afafc993}"); // set the art so we can use it again @@ -35,9 +30,7 @@ void CatapultBaseServer::OnTimerDone(Entity* self, std::string timerName) // start a timer till the bouncer actually bounces self->AddTimer("bounce", 3); - } - else if (timerName == "launchAnim") - { + } else if (timerName == "launchAnim") { // get the arm asset auto* arm = EntityManager::Instance()->GetEntity(self->GetVar(u"Arm")); if (arm == nullptr) return; @@ -46,9 +39,7 @@ void CatapultBaseServer::OnTimerDone(Entity* self, std::string timerName) auto animTime = 1; self->AddTimer("resetArm", animTime); GameMessages::SendPlayAnimation(arm, u"launch"); - } - else if (timerName == "bounce") - { + } else if (timerName == "bounce") { auto* bouncer = EntityManager::Instance()->GetEntity(self->GetVar(u"Bouncer")); if (bouncer == nullptr) return; @@ -56,9 +47,7 @@ void CatapultBaseServer::OnTimerDone(Entity* self, std::string timerName) bouncer->NotifyObject(bouncer, "bounceAllInProximity"); // Likely to trigger server side bounce, bodging this // add a delay to play the animation self->AddTimer("launchAnim", .3); - } - else if (timerName == "resetArm") - { + } else if (timerName == "resetArm") { auto* arm = EntityManager::Instance()->GetEntity(self->GetVar(u"Arm")); if (arm == nullptr) return; diff --git a/dScripts/CatapultBaseServer.h b/dScripts/CatapultBaseServer.h index a174fcaf..cc5a1907 100644 --- a/dScripts/CatapultBaseServer.h +++ b/dScripts/CatapultBaseServer.h @@ -3,7 +3,7 @@ class CatapultBaseServer : public CppScripts::Script { public: - void OnNotifyObject(Entity *self, Entity *sender, const std::string& name, int32_t param1 = 0, int32_t param2 = 0) override; - - void OnTimerDone(Entity* self, std::string timerName) override; + void OnNotifyObject(Entity* self, Entity* sender, const std::string& name, int32_t param1 = 0, int32_t param2 = 0) override; + + void OnTimerDone(Entity* self, std::string timerName) override; }; diff --git a/dScripts/CatapultBouncerServer.cpp b/dScripts/CatapultBouncerServer.cpp index 098f38ac..89faf001 100644 --- a/dScripts/CatapultBouncerServer.cpp +++ b/dScripts/CatapultBouncerServer.cpp @@ -2,16 +2,14 @@ #include "GameMessages.h" #include "EntityManager.h" -void CatapultBouncerServer::OnRebuildComplete(Entity* self, Entity* target) -{ - GameMessages::SendNotifyClientObject(self->GetObjectID(), u"Built", 0, 0, LWOOBJID_EMPTY, "", UNASSIGNED_SYSTEM_ADDRESS); +void CatapultBouncerServer::OnRebuildComplete(Entity* self, Entity* target) { + GameMessages::SendNotifyClientObject(self->GetObjectID(), u"Built", 0, 0, LWOOBJID_EMPTY, "", UNASSIGNED_SYSTEM_ADDRESS); - self->SetNetworkVar(u"Built", true); + self->SetNetworkVar(u"Built", true); - const auto base = EntityManager::Instance()->GetEntitiesInGroup(self->GetVarAsString(u"BaseGroup")); + const auto base = EntityManager::Instance()->GetEntitiesInGroup(self->GetVarAsString(u"BaseGroup")); - for (auto* obj : base) - { - obj->NotifyObject(self, "BouncerBuilt"); - } + for (auto* obj : base) { + obj->NotifyObject(self, "BouncerBuilt"); + } } diff --git a/dScripts/CatapultBouncerServer.h b/dScripts/CatapultBouncerServer.h index 06f03bf4..46ec20ab 100644 --- a/dScripts/CatapultBouncerServer.h +++ b/dScripts/CatapultBouncerServer.h @@ -3,5 +3,5 @@ class CatapultBouncerServer : public CppScripts::Script { public: - void OnRebuildComplete(Entity* self, Entity* target) override; + void OnRebuildComplete(Entity* self, Entity* target) override; }; diff --git a/dScripts/CauldronOfLife.cpp b/dScripts/CauldronOfLife.cpp index 13e07775..3ddb5c61 100644 --- a/dScripts/CauldronOfLife.cpp +++ b/dScripts/CauldronOfLife.cpp @@ -1,13 +1,13 @@ #include "CauldronOfLife.h" -void CauldronOfLife::OnStartup(Entity *self) { - self->SetVar(u"numCycles", 10); - self->SetVar(u"secPerCycle", 20.0f); - self->SetVar(u"delayToFirstCycle", 1.5f); - self->SetVar(u"deathDelay", 20.0f); - self->SetVar(u"numberOfPowerups", 3); - self->SetVar(u"lootLOT", 177); +void CauldronOfLife::OnStartup(Entity* self) { + self->SetVar(u"numCycles", 10); + self->SetVar(u"secPerCycle", 20.0f); + self->SetVar(u"delayToFirstCycle", 1.5f); + self->SetVar(u"deathDelay", 20.0f); + self->SetVar(u"numberOfPowerups", 3); + self->SetVar(u"lootLOT", 177); - // Initiate the actual script - OnTemplateStartup(self); + // Initiate the actual script + OnTemplateStartup(self); } diff --git a/dScripts/CauldronOfLife.h b/dScripts/CauldronOfLife.h index 3a5892c6..f7b492b5 100644 --- a/dScripts/CauldronOfLife.h +++ b/dScripts/CauldronOfLife.h @@ -2,5 +2,5 @@ #include "ScriptedPowerupSpawner.h" class CauldronOfLife : public ScriptedPowerupSpawner { - void OnStartup(Entity* self) override; + void OnStartup(Entity* self) override; }; diff --git a/dScripts/CavePrisonCage.cpp b/dScripts/CavePrisonCage.cpp index 5fe47f2d..0df91884 100644 --- a/dScripts/CavePrisonCage.cpp +++ b/dScripts/CavePrisonCage.cpp @@ -5,241 +5,211 @@ #include "Character.h" #include "dZoneManager.h" -void CavePrisonCage::OnStartup(Entity *self) -{ - const auto& myNum = self->GetVar(u"myNumber"); +void CavePrisonCage::OnStartup(Entity* self) { + const auto& myNum = self->GetVar(u"myNumber"); - if (myNum.empty()) - { - return; - } + if (myNum.empty()) { + return; + } - auto* spawner = dZoneManager::Instance()->GetSpawnersByName("PrisonCounterweight_0" + GeneralUtils::UTF16ToWTF8(myNum))[0]; + auto* spawner = dZoneManager::Instance()->GetSpawnersByName("PrisonCounterweight_0" + GeneralUtils::UTF16ToWTF8(myNum))[0]; - self->SetVar(u"CWSpawner", spawner); + self->SetVar(u"CWSpawner", spawner); - Setup(self, spawner); + Setup(self, spawner); } -void CavePrisonCage::Setup(Entity *self, Spawner* spawner) -{ - SpawnCounterweight(self, spawner); +void CavePrisonCage::Setup(Entity* self, Spawner* spawner) { + SpawnCounterweight(self, spawner); - NiPoint3 mypos = self->GetPosition(); - NiQuaternion myrot = self->GetRotation(); + NiPoint3 mypos = self->GetPosition(); + NiQuaternion myrot = self->GetRotation(); - mypos.y += 1.5; - mypos.z -= 0.5; + mypos.y += 1.5; + mypos.z -= 0.5; - EntityInfo info {}; - info.lot = m_Villagers[self->GetVarAs(u"myNumber") - 1]; - info.pos = mypos; - info.rot = myrot; - info.spawnerID = self->GetObjectID(); + EntityInfo info{}; + info.lot = m_Villagers[self->GetVarAs(u"myNumber") - 1]; + info.pos = mypos; + info.rot = myrot; + info.spawnerID = self->GetObjectID(); - // Spawn the villager inside the jail - auto* entity = EntityManager::Instance()->CreateEntity(info); + // Spawn the villager inside the jail + auto* entity = EntityManager::Instance()->CreateEntity(info); - // Save the villeger ID - self->SetVar(u"villager", entity->GetObjectID()); + // Save the villeger ID + self->SetVar(u"villager", entity->GetObjectID()); - // Construct the entity - EntityManager::Instance()->ConstructEntity(entity); + // Construct the entity + EntityManager::Instance()->ConstructEntity(entity); } -void CavePrisonCage::OnRebuildNotifyState(Entity* self, eRebuildState state) -{ - if (state != eRebuildState::REBUILD_RESETTING) - { - return; - } +void CavePrisonCage::OnRebuildNotifyState(Entity* self, eRebuildState state) { + if (state != eRebuildState::REBUILD_RESETTING) { + return; + } - auto* spawner = self->GetVar(u"CWSpawner"); + auto* spawner = self->GetVar(u"CWSpawner"); - if (spawner == nullptr) - { - return; - } + if (spawner == nullptr) { + return; + } - spawner->Reset(); + spawner->Reset(); - SpawnCounterweight(self, spawner); + SpawnCounterweight(self, spawner); } -void CavePrisonCage::SpawnCounterweight(Entity* self, Spawner* spawner) -{ - spawner->Reset(); +void CavePrisonCage::SpawnCounterweight(Entity* self, Spawner* spawner) { + spawner->Reset(); - auto* counterweight = spawner->Spawn(); + auto* counterweight = spawner->Spawn(); - self->SetVar(u"Counterweight", counterweight->GetObjectID()); + self->SetVar(u"Counterweight", counterweight->GetObjectID()); - auto* rebuildComponent = counterweight->GetComponent(); + auto* rebuildComponent = counterweight->GetComponent(); - if (rebuildComponent != nullptr) - { - rebuildComponent->AddRebuildStateCallback([this, self] (eRebuildState state) { - OnRebuildNotifyState(self, state); - }); + if (rebuildComponent != nullptr) { + rebuildComponent->AddRebuildStateCallback([this, self](eRebuildState state) { + OnRebuildNotifyState(self, state); + }); - rebuildComponent->AddRebuildCompleteCallback([this, self] (Entity* user) { - // The counterweight is a simple mover, which is not implemented, so we'll just set it's position - auto* counterweight = EntityManager::Instance()->GetEntity(self->GetVar(u"Counterweight")); + rebuildComponent->AddRebuildCompleteCallback([this, self](Entity* user) { + // The counterweight is a simple mover, which is not implemented, so we'll just set it's position + auto* counterweight = EntityManager::Instance()->GetEntity(self->GetVar(u"Counterweight")); - if (counterweight == nullptr) - { - return; - } + if (counterweight == nullptr) { + return; + } - // Move the counterweight down 2 units - counterweight->SetPosition(counterweight->GetPosition() + NiPoint3(0, -2, 0)); + // Move the counterweight down 2 units + counterweight->SetPosition(counterweight->GetPosition() + NiPoint3(0, -2, 0)); - // Serialize the counterweight - EntityManager::Instance()->SerializeEntity(counterweight); + // Serialize the counterweight + EntityManager::Instance()->SerializeEntity(counterweight); - // notifyPlatformAtLastWaypoint - - // Save the userID as Builder - self->SetVar(u"Builder", user->GetObjectID()); + // notifyPlatformAtLastWaypoint - // Get the button and make sure it still exists - auto* button = EntityManager::Instance()->GetEntity(self->GetVar(u"Button")); + // Save the userID as Builder + self->SetVar(u"Builder", user->GetObjectID()); - if (button == nullptr) - { - return; - } + // Get the button and make sure it still exists + auto* button = EntityManager::Instance()->GetEntity(self->GetVar(u"Button")); - // Play the 'down' animation on the button - GameMessages::SendPlayAnimation(button, u"down"); + if (button == nullptr) { + return; + } - // Setup a timer named 'buttonGoingDown' to be triggered in 5 seconds - self->AddTimer("buttonGoingDown", 5.0f); - }); - } + // Play the 'down' animation on the button + GameMessages::SendPlayAnimation(button, u"down"); - if (self->GetVar(u"Button")) - { - return; - } + // Setup a timer named 'buttonGoingDown' to be triggered in 5 seconds + self->AddTimer("buttonGoingDown", 5.0f); + }); + } - GetButton(self); + if (self->GetVar(u"Button")) { + return; + } + + GetButton(self); } -void CavePrisonCage::GetButton(Entity* self) -{ - const auto buttons = EntityManager::Instance()->GetEntitiesInGroup("PrisonButton_0" + std::to_string(self->GetVarAs(u"myNumber"))); +void CavePrisonCage::GetButton(Entity* self) { + const auto buttons = EntityManager::Instance()->GetEntitiesInGroup("PrisonButton_0" + std::to_string(self->GetVarAs(u"myNumber"))); - if (buttons.size() == 0) - { - // Try again in 0.5 seconds - self->AddCallbackTimer(0.5, [this, self] () { - GetButton(self); - }); + if (buttons.size() == 0) { + // Try again in 0.5 seconds + self->AddCallbackTimer(0.5, [this, self]() { + GetButton(self); + }); - return; - } + return; + } - auto* button = buttons[0]; + auto* button = buttons[0]; - self->SetVar(u"Button", button->GetObjectID()); + self->SetVar(u"Button", button->GetObjectID()); } -void CavePrisonCage::OnTimerDone(Entity* self, std::string timerName) -{ - // the anim of the button down is over - if (timerName == "buttonGoingDown") - { - // Play the 'up' animation - GameMessages::SendPlayAnimation(self, u"up"); +void CavePrisonCage::OnTimerDone(Entity* self, std::string timerName) { + // the anim of the button down is over + if (timerName == "buttonGoingDown") { + // Play the 'up' animation + GameMessages::SendPlayAnimation(self, u"up"); - // Setup a timer named 'CageOpen' to be triggered in 1 second - self->AddTimer("CageOpen", 1.0f); - } - else if (timerName == "CageOpen") - { - // play the idle open anim - GameMessages::SendPlayAnimation(self, u"idle-up"); + // Setup a timer named 'CageOpen' to be triggered in 1 second + self->AddTimer("CageOpen", 1.0f); + } else if (timerName == "CageOpen") { + // play the idle open anim + GameMessages::SendPlayAnimation(self, u"idle-up"); - // Get the villeger - auto* villager = EntityManager::Instance()->GetEntity(self->GetVar(u"villager")); + // Get the villeger + auto* villager = EntityManager::Instance()->GetEntity(self->GetVar(u"villager")); - if (villager == nullptr) - { - return; - } + if (villager == nullptr) { + return; + } - GameMessages::SendNotifyClientObject(villager->GetObjectID(), u"TimeToChat", 0, 0, LWOOBJID_EMPTY, "", UNASSIGNED_SYSTEM_ADDRESS); + GameMessages::SendNotifyClientObject(villager->GetObjectID(), u"TimeToChat", 0, 0, LWOOBJID_EMPTY, "", UNASSIGNED_SYSTEM_ADDRESS); - // Get the builder and make sure it still exists - auto* builder = EntityManager::Instance()->GetEntity(self->GetVar(u"Builder")); + // Get the builder and make sure it still exists + auto* builder = EntityManager::Instance()->GetEntity(self->GetVar(u"Builder")); - if (builder == nullptr) - { - return; - } + if (builder == nullptr) { + return; + } - const auto flagNum = 2020 + self->GetVarAs(u"myNumber"); + const auto flagNum = 2020 + self->GetVarAs(u"myNumber"); - // Set the flag on the builder character - builder->GetCharacter()->SetPlayerFlag(flagNum, true); + // Set the flag on the builder character + builder->GetCharacter()->SetPlayerFlag(flagNum, true); - // Setup a timer named 'VillagerEscape' to be triggered in 5 seconds - self->AddTimer("VillagerEscape", 5.0f); - } - else if (timerName == "VillagerEscape") - { - // Get the villeger and make sure it still exists - auto* villager = EntityManager::Instance()->GetEntity(self->GetVar(u"villager")); - - if (villager == nullptr) - { - return; - } + // Setup a timer named 'VillagerEscape' to be triggered in 5 seconds + self->AddTimer("VillagerEscape", 5.0f); + } else if (timerName == "VillagerEscape") { + // Get the villeger and make sure it still exists + auto* villager = EntityManager::Instance()->GetEntity(self->GetVar(u"villager")); - // Kill the villager - villager->Kill(); + if (villager == nullptr) { + return; + } - // Setup a timer named 'SmashCounterweight' to be triggered in 2 seconds - self->AddTimer("SmashCounterweight", 2.0f); - } - else if (timerName == "SmashCounterweight") - { - // Get the counterweight and make sure it still exists - auto* counterweight = EntityManager::Instance()->GetEntity(self->GetVar(u"Counterweight")); + // Kill the villager + villager->Kill(); - if (counterweight == nullptr) - { - return; - } + // Setup a timer named 'SmashCounterweight' to be triggered in 2 seconds + self->AddTimer("SmashCounterweight", 2.0f); + } else if (timerName == "SmashCounterweight") { + // Get the counterweight and make sure it still exists + auto* counterweight = EntityManager::Instance()->GetEntity(self->GetVar(u"Counterweight")); - // Smash the counterweight - counterweight->Smash(); + if (counterweight == nullptr) { + return; + } - // Get the button and make sure it still exists - auto* button = EntityManager::Instance()->GetEntity(self->GetVar(u"Button")); + // Smash the counterweight + counterweight->Smash(); - if (button == nullptr) - { - return; - } + // Get the button and make sure it still exists + auto* button = EntityManager::Instance()->GetEntity(self->GetVar(u"Button")); - // Play the 'up' animation on the button - GameMessages::SendPlayAnimation(button, u"up"); + if (button == nullptr) { + return; + } - // Setup a timer named 'CageClosed' to be triggered in 1 second - self->AddTimer("CageClosed", 1.0f); - } - else if (timerName == "CageClosed") - { - // play the idle closed anim - GameMessages::SendPlayAnimation(self, u"idle"); + // Play the 'up' animation on the button + GameMessages::SendPlayAnimation(button, u"up"); - // Setup a timer named 'ResetPrison' to be triggered in 10 seconds - self->AddTimer("ResetPrison", 10.0f); - } - else if (timerName == "ResetPrison") - { - Setup(self, self->GetVar(u"CWSpawner")); - } + // Setup a timer named 'CageClosed' to be triggered in 1 second + self->AddTimer("CageClosed", 1.0f); + } else if (timerName == "CageClosed") { + // play the idle closed anim + GameMessages::SendPlayAnimation(self, u"idle"); + + // Setup a timer named 'ResetPrison' to be triggered in 10 seconds + self->AddTimer("ResetPrison", 10.0f); + } else if (timerName == "ResetPrison") { + Setup(self, self->GetVar(u"CWSpawner")); + } } diff --git a/dScripts/CavePrisonCage.h b/dScripts/CavePrisonCage.h index 5ae357d5..43d826c7 100644 --- a/dScripts/CavePrisonCage.h +++ b/dScripts/CavePrisonCage.h @@ -3,14 +3,14 @@ class CavePrisonCage : public CppScripts::Script { public: - void OnStartup(Entity *self) override; - void Setup(Entity *self, Spawner* spawner); + void OnStartup(Entity* self) override; + void Setup(Entity* self, Spawner* spawner); void OnRebuildNotifyState(Entity* self, eRebuildState state) override; - void SpawnCounterweight(Entity* self, Spawner* spawner); - void GetButton(Entity* self); + void SpawnCounterweight(Entity* self, Spawner* spawner); + void GetButton(Entity* self); void OnTimerDone(Entity* self, std::string timerName) override; private: - std::vector m_Villagers = { 15851, 15866, 15922, 15924, 15927, 15929 }; - std::vector m_Missions = { 1801, 2039 }; + std::vector m_Villagers = { 15851, 15866, 15922, 15924, 15927, 15929 }; + std::vector m_Missions = { 1801, 2039 }; }; diff --git a/dScripts/ChooseYourDestinationNsToNt.cpp b/dScripts/ChooseYourDestinationNsToNt.cpp index 823d7c85..e50d70c5 100644 --- a/dScripts/ChooseYourDestinationNsToNt.cpp +++ b/dScripts/ChooseYourDestinationNsToNt.cpp @@ -2,77 +2,63 @@ #include "Character.h" #include "GameMessages.h" -bool ChooseYourDestinationNsToNt::CheckChoice(Entity* self, Entity* player) -{ - const auto choiceZoneID = self->GetVar(u"choiceZone"); - const auto newZoneID = self->GetVar(u"currentZone"); +bool ChooseYourDestinationNsToNt::CheckChoice(Entity* self, Entity* player) { + const auto choiceZoneID = self->GetVar(u"choiceZone"); + const auto newZoneID = self->GetVar(u"currentZone"); - if (newZoneID == choiceZoneID) - { - auto* character = player->GetCharacter(); + if (newZoneID == choiceZoneID) { + auto* character = player->GetCharacter(); - if (character == nullptr) - { - return false; - } + if (character == nullptr) { + return false; + } - if (character->HasBeenToWorld(1900)) - { - return true; - } + if (character->HasBeenToWorld(1900)) { + return true; + } - self->SetVar(u"transferZoneID", GeneralUtils::to_u16string(1200)); - self->SetVar(u"teleportString", u"UI_TRAVEL_TO_NS"); + self->SetVar(u"transferZoneID", GeneralUtils::to_u16string(1200)); + self->SetVar(u"teleportString", u"UI_TRAVEL_TO_NS"); - return false; - } + return false; + } - return false; + return false; } -void ChooseYourDestinationNsToNt::SetDestination(Entity* self, Entity* player) -{ - const auto currentMap = self->GetVar(u"currentZone"); - auto newMap = self->GetVar(u"choiceZone"); +void ChooseYourDestinationNsToNt::SetDestination(Entity* self, Entity* player) { + const auto currentMap = self->GetVar(u"currentZone"); + auto newMap = self->GetVar(u"choiceZone"); - if (currentMap == newMap) - { - newMap = 1200; - } + if (currentMap == newMap) { + newMap = 1200; + } - self->SetVar(u"transferZoneID", GeneralUtils::to_u16string(newMap)); + self->SetVar(u"transferZoneID", GeneralUtils::to_u16string(newMap)); } -void ChooseYourDestinationNsToNt::BaseChoiceBoxRespond(Entity* self, Entity* sender, int32_t button, const std::u16string& buttonIdentifier, const std::u16string& identifier) -{ - if (button != -1) - { - const auto newMapStr = GeneralUtils::UTF16ToWTF8(buttonIdentifier).substr(7, -1); +void ChooseYourDestinationNsToNt::BaseChoiceBoxRespond(Entity* self, Entity* sender, int32_t button, const std::u16string& buttonIdentifier, const std::u16string& identifier) { + if (button != -1) { + const auto newMapStr = GeneralUtils::UTF16ToWTF8(buttonIdentifier).substr(7, -1); - int32_t newMap = 0; - if (!GeneralUtils::TryParse(newMapStr, newMap)) - { - return; - } + int32_t newMap = 0; + if (!GeneralUtils::TryParse(newMapStr, newMap)) { + return; + } - std::u16string strText = u""; + std::u16string strText = u""; - if (newMap == 1200) - { - strText = u"UI_TRAVEL_TO_NS"; - } - else - { - strText = u"UI_TRAVEL_TO_NEXUS_TOWER"; - } + if (newMap == 1200) { + strText = u"UI_TRAVEL_TO_NS"; + } else { + strText = u"UI_TRAVEL_TO_NEXUS_TOWER"; + } - self->SetVar(u"teleportString", strText); - self->SetVar(u"transferZoneID", GeneralUtils::to_u16string(newMap)); + self->SetVar(u"teleportString", strText); + self->SetVar(u"transferZoneID", GeneralUtils::to_u16string(newMap)); - GameMessages::SendDisplayMessageBox(sender->GetObjectID(), true, self->GetObjectID(), u"TransferBox", 0, strText, u"", sender->GetSystemAddress()); - } - else - { - GameMessages::SendTerminateInteraction(sender->GetObjectID(), FROM_INTERACTION, self->GetObjectID()); - } + GameMessages::SendDisplayMessageBox(sender->GetObjectID(), true, self->GetObjectID(), u"TransferBox", 0, strText, u"", sender->GetSystemAddress()); + } else { + GameMessages::SendTerminateInteraction(sender->GetObjectID(), FROM_INTERACTION, self->GetObjectID()); + } } diff --git a/dScripts/ChooseYourDestinationNsToNt.h b/dScripts/ChooseYourDestinationNsToNt.h index cbf3709e..9ce9988a 100644 --- a/dScripts/ChooseYourDestinationNsToNt.h +++ b/dScripts/ChooseYourDestinationNsToNt.h @@ -3,7 +3,7 @@ class ChooseYourDestinationNsToNt { public: - bool CheckChoice(Entity* self, Entity* player); - void SetDestination(Entity* self, Entity* player); - void BaseChoiceBoxRespond(Entity* self, Entity* sender, int32_t button, const std::u16string& buttonIdentifier, const std::u16string& identifier); + bool CheckChoice(Entity* self, Entity* player); + void SetDestination(Entity* self, Entity* player); + void BaseChoiceBoxRespond(Entity* self, Entity* sender, int32_t button, const std::u16string& buttonIdentifier, const std::u16string& identifier); }; diff --git a/dScripts/ClRing.cpp b/dScripts/ClRing.cpp index 5de3e683..37e76d88 100644 --- a/dScripts/ClRing.cpp +++ b/dScripts/ClRing.cpp @@ -1,6 +1,5 @@ #include "ClRing.h" -void ClRing::OnCollisionPhantom(Entity* self, Entity* target) -{ +void ClRing::OnCollisionPhantom(Entity* self, Entity* target) { self->Smash(target->GetObjectID()); } diff --git a/dScripts/CppScripts.cpp b/dScripts/CppScripts.cpp index 8569bf9e..fbcb660a 100644 --- a/dScripts/CppScripts.cpp +++ b/dScripts/CppScripts.cpp @@ -377,38 +377,38 @@ CppScripts::Script* CppScripts::GetScript(Entity* parent, const std::string& scr script = new NpcAgCourseStarter(); else if (scriptName == "scripts\\02_server\\Map\\AG\\L__AG_MONUMENT_RACE_GOAL.lua") script = new AgMonumentRaceGoal(); - else if (scriptName == "scripts\\02_server\\Map\\AG\\L__AG_MONUMENT_RACE_CANCEL.lua") - script = new AgMonumentRaceCancel(); - else if (scriptName == "scripts\\02_server\\Map\\AG_Spider_Queen\\L_ZONE_AG_SPIDER_QUEEN.lua") - script = (ZoneAgProperty*)new ZoneAgSpiderQueen(); - else if (scriptName == "scripts\\02_server\\Map\\AG_Spider_Queen\\L_SPIDER_BOSS_TREASURE_CHEST_SERVER.lua") - script = new SpiderBossTreasureChestServer(); + else if (scriptName == "scripts\\02_server\\Map\\AG\\L__AG_MONUMENT_RACE_CANCEL.lua") + script = new AgMonumentRaceCancel(); + else if (scriptName == "scripts\\02_server\\Map\\AG_Spider_Queen\\L_ZONE_AG_SPIDER_QUEEN.lua") + script = (ZoneAgProperty*)new ZoneAgSpiderQueen(); + else if (scriptName == "scripts\\02_server\\Map\\AG_Spider_Queen\\L_SPIDER_BOSS_TREASURE_CHEST_SERVER.lua") + script = new SpiderBossTreasureChestServer(); else if (scriptName == "scripts\\02_server\\Map\\AG\\L_NPC_COWBOY_SERVER.lua") script = new NpcCowboyServer(); else if (scriptName == "scripts\\02_server\\Map\\Property\\AG_Med\\L_ZONE_AG_MED_PROPERTY.lua") - script = new ZoneAgMedProperty(); + script = new ZoneAgMedProperty(); else if (scriptName == "scripts\\ai\\AG\\L_AG_STROMBIE_PROPERTY.lua") - script = new AgStromlingProperty(); + script = new AgStromlingProperty(); else if (scriptName == "scripts\\ai\\AG\\L_AG_DARKLING_MECH.lua") - script = new BaseEnemyMech(); + script = new BaseEnemyMech(); else if (scriptName == "scripts\\ai\\AG\\L_AG_DARK_SPIDERLING.lua") - script = new AgDarkSpiderling(); + script = new AgDarkSpiderling(); else if (scriptName == "scripts\\ai\\PROPERTY\\L_PROP_GUARDS.lua") - script = new AgPropguards(); + script = new AgPropguards(); else if (scriptName == "scripts\\ai\\PROPERTY\\L_PROPERTY_FX_DAMAGE.lua") - script = new PropertyFXDamage(); + script = new PropertyFXDamage(); else if (scriptName == "scripts\\02_server\\Map\\AG\\L_NPC_PIRATE_SERVER.lua") - script = new NpcPirateServer(); + script = new NpcPirateServer(); else if (scriptName == "scripts\\ai\\AG\\L_AG_PICNIC_BLANKET.lua") - script = new AgPicnicBlanket(); + script = new AgPicnicBlanket(); else if (scriptName == "scripts\\02_server\\Map\\Property\\L_PROPERTY_BANK_INTERACT_SERVER.lua") - script = new PropertyBankInteract(); - else if (scriptName == "scripts\\02_server\\Enemy\\VE\\L_VE_MECH.lua") - script = new VeMech(); - else if (scriptName == "scripts\\02_server\\Map\\VE\\L_MISSION_CONSOLE_SERVER.lua") - script = new VeMissionConsole(); - else if (scriptName == "scripts\\02_server\\Map\\VE\\L_EPSILON_SERVER.lua") - script = new VeEpsilonServer(); + script = new PropertyBankInteract(); + else if (scriptName == "scripts\\02_server\\Enemy\\VE\\L_VE_MECH.lua") + script = new VeMech(); + else if (scriptName == "scripts\\02_server\\Map\\VE\\L_MISSION_CONSOLE_SERVER.lua") + script = new VeMissionConsole(); + else if (scriptName == "scripts\\02_server\\Map\\VE\\L_EPSILON_SERVER.lua") + script = new VeEpsilonServer(); // Win32 thinks this if chain is too long, let's cut it up and serve it as a three course meal //NS: if (scriptName == "scripts\\ai\\NS\\L_NS_MODULAR_BUILD.lua") @@ -418,45 +418,45 @@ CppScripts::Script* CppScripts::GetScript(Entity* parent, const std::string& scr else if (scriptName == "scripts\\ai\\NS\\L_NS_QB_IMAGINATION_STATUE.lua") script = new NsQbImaginationStatue(); else if (scriptName == "scripts\\02_server\\Map\\NS\\CONCERT_CHOICEBUILD_MANAGER_SERVER.lua") - script = new NsConcertChoiceBuildManager(); + script = new NsConcertChoiceBuildManager(); else if (scriptName == "scripts\\ai\\NS\\L_NS_CONCERT_CHOICEBUILD.lua") - script = new NsConcertChoiceBuild(); + script = new NsConcertChoiceBuild(); else if (scriptName == "scripts\\ai\\NS\\L_NS_CONCERT_QUICKBUILD.lua") - script = new NsConcertQuickBuild(); + script = new NsConcertQuickBuild(); else if (scriptName == "scripts\\ai\\AG\\L_AG_STAGE_PLATFORMS.lua") - script = new AgStagePlatforms(); + script = new AgStagePlatforms(); else if (scriptName == "scripts\\ai\\NS\\L_NS_CONCERT_INSTRUMENT_QB.lua") - script = new NsConcertInstrument(); + script = new NsConcertInstrument(); else if (scriptName == "scripts\\ai\\NS\\L_NS_JONNY_FLAG_MISSION_SERVER.lua") - script = new NsJohnnyMissionServer(); + script = new NsJohnnyMissionServer(); else if (scriptName == "scripts\\02_server\\Objects\\L_STINKY_FISH_TARGET.lua") - script = new StinkyFishTarget(); + script = new StinkyFishTarget(); else if (scriptName == "scripts\\zone\\PROPERTY\\NS\\L_ZONE_NS_PROPERTY.lua") - script = new ZoneNsProperty(); + script = new ZoneNsProperty(); else if (scriptName == "scripts\\02_server\\Map\\Property\\NS_Med\\L_ZONE_NS_MED_PROPERTY.lua") - script = new ZoneNsMedProperty(); + script = new ZoneNsMedProperty(); else if (scriptName == "scripts\\02_server\\Map\\NS\\L_NS_TOKEN_CONSOLE_SERVER.lua") script = new NsTokenConsoleServer(); else if (scriptName == "scripts\\02_server\\Map\\NS\\L_NS_LUP_TELEPORT.lua") script = new NsLupTeleport(); else if (scriptName == "scripts\\02_server\\Map\\NS\\Waves\\L_ZONE_NS_WAVES.lua") - script = new ZoneNsWaves(); + script = new ZoneNsWaves(); else if (scriptName == "scripts\\02_server\\Enemy\\Waves\\L_WAVES_BOSS_HAMMERLING_ENEMY_SERVER.lua") - script = new WaveBossHammerling(); + script = new WaveBossHammerling(); else if (scriptName == "scripts\\02_server\\Enemy\\Waves\\L_WAVES_BOSS_APE_ENEMY_SERVER.lua") - script = (BaseEnemyApe*) new WaveBossApe(); + script = (BaseEnemyApe*) new WaveBossApe(); else if (scriptName == "scripts\\02_server\\Enemy\\Waves\\L_WAVES_BOSS_DARK_SPIDERLING_ENEMY_SERVER.lua") - script = new WaveBossSpiderling(); + script = new WaveBossSpiderling(); else if (scriptName == "scripts\\02_server\\Enemy\\Waves\\L_WAVES_BOSS_HORESEMEN_ENEMY_SERVER.lua") - script = new WaveBossHorsemen(); + script = new WaveBossHorsemen(); else if (scriptName == "scripts\\02_server\\Minigame\\General\\L_MINIGAME_TREASURE_CHEST_SERVER.lua") - script = new MinigameTreasureChestServer(); + script = new MinigameTreasureChestServer(); else if (scriptName == "scripts\\02_server\\Map\\NS\\L_NS_LEGO_CLUB_DOOR.lua") - script = new NsLegoClubDoor(); + script = new NsLegoClubDoor(); else if (scriptName == "scripts/ai/NS/L_CL_RING.lua") - script = new ClRing(); + script = new ClRing(); else if (scriptName == "scripts\\ai\\WILD\\L_WILD_AMBIENTS.lua") - script = new WildAmbients(); + script = new WildAmbients(); else if (scriptName == "scripts\\ai\\NS\\NS_PP_01\\L_NS_PP_01_TELEPORT.lua") script = new PropertyDeathPlane(); @@ -484,7 +484,7 @@ CppScripts::Script* CppScripts::GetScript(Entity* parent, const std::string& scr else if (scriptName == "scripts\\02_server\\Map\\General\\L_QB_ENEMY_STUNNER.lua") script = new QbEnemyStunner(); else if (scriptName == "scripts\\ai\\GF\\L_GF_PET_DIG_BUILD.lua") - script = new PetDigBuild(); // Technically also used once in AG + script = new PetDigBuild(); // Technically also used once in AG else if (scriptName == "scripts\\02_server\\Map\\GF\\L_SPAWN_LION_SERVER.lua") script = new SpawnLionServer(); else if (scriptName == "scripts\\02_server\\Enemy\\General\\L_BASE_ENEMY_APE.lua") @@ -492,13 +492,13 @@ CppScripts::Script* CppScripts::GetScript(Entity* parent, const std::string& scr else if (scriptName == "scripts\\02_server\\Enemy\\General\\L_GF_APE_SMASHING_QB.lua") script = new GfApeSmashingQB(); else if (scriptName == "scripts\\zone\\PROPERTY\\GF\\L_ZONE_GF_PROPERTY.lua") - script = new ZoneGfProperty(); + script = new ZoneGfProperty(); // SG else if (scriptName == "scripts\\ai\\MINIGAME\\SG_GF\\SERVER\\SG_CANNON.lua") - script = new SGCannon(); + script = new SGCannon(); else if (scriptName == "scripts\\ai\\MINIGAME\\SG_GF\\L_ZONE_SG_SERVER.lua") - script = new ZoneSGServer(); + script = new ZoneSGServer(); //PR: else if (scriptName == "scripts\\client\\ai\\PR\\L_PR_WHISTLE.lua") @@ -511,16 +511,16 @@ CppScripts::Script* CppScripts::GetScript(Entity* parent, const std::string& scr script = new HydrantBroken(); else if (scriptName == "scripts\\02_server\\Map\\General\\PET_DIG_SERVER.lua" || scriptName == "scripts\\02_server\\Map\\AM\\L_SKELETON_DRAGON_PET_DIG_SERVER.lua") script = new PetDigServer(); - else if (scriptName == "scripts\\client\\ai\\PR\\L_CRAB_SERVER.lua") - script = new CrabServer(); - else if (scriptName == "scripts\\02_server\\Pets\\L_PET_FROM_DIG_SERVER.lua") - script = new PetFromDigServer(); - else if (scriptName == "scripts\\02_server\\Pets\\L_PET_FROM_OBJECT_SERVER.lua") - script = new PetFromObjectServer(); - else if (scriptName == "scripts\\02_server\\Pets\\L_DAMAGING_PET.lua") - script = new DamagingPets(); - else if (scriptName == "scripts\\02_server\\Map\\PR\\L_SPAWN_GRYPHON_SERVER.lua") - script = new SpawnGryphonServer(); + else if (scriptName == "scripts\\client\\ai\\PR\\L_CRAB_SERVER.lua") + script = new CrabServer(); + else if (scriptName == "scripts\\02_server\\Pets\\L_PET_FROM_DIG_SERVER.lua") + script = new PetFromDigServer(); + else if (scriptName == "scripts\\02_server\\Pets\\L_PET_FROM_OBJECT_SERVER.lua") + script = new PetFromObjectServer(); + else if (scriptName == "scripts\\02_server\\Pets\\L_DAMAGING_PET.lua") + script = new DamagingPets(); + else if (scriptName == "scripts\\02_server\\Map\\PR\\L_SPAWN_GRYPHON_SERVER.lua") + script = new SpawnGryphonServer(); //FV Scripts: else if (scriptName == "scripts\\02_server\\Map\\FV\\L_ACT_CANDLE.lua") @@ -544,13 +544,13 @@ CppScripts::Script* CppScripts::GetScript(Entity* parent, const std::string& scr else if (scriptName == "scripts\\ai\\GENERAL\\L_INSTANCE_EXIT_TRANSFER_PLAYER_TO_LAST_NON_INSTANCE.lua") script = new InstanceExitTransferPlayerToLastNonInstance(); else if (scriptName == "scripts\\ai\\FV\\L_NPC_FREE_GF_NINJAS.lua") - script = new FvFreeGfNinjas(); + script = new FvFreeGfNinjas(); else if (scriptName == "scripts\\ai\\FV\\L_FV_PANDA_SPAWNER_SERVER.lua") - script = new FvPandaSpawnerServer(); + script = new FvPandaSpawnerServer(); else if (scriptName == "scripts\\ai\\FV\\L_FV_PANDA_SERVER.lua") - script = new FvPandaServer(); - else if (scriptName == "scripts\\zone\\PROPERTY\\FV\\L_ZONE_FV_PROPERTY.lua") - script = new ZoneFvProperty(); + script = new FvPandaServer(); + else if (scriptName == "scripts\\zone\\PROPERTY\\FV\\L_ZONE_FV_PROPERTY.lua") + script = new ZoneFvProperty(); else if (scriptName == "scripts\\ai\\FV\\L_FV_BRICK_PUZZLE_SERVER.lua") script = new FvBrickPuzzleServer(); else if (scriptName == "scripts\\ai\\FV\\L_FV_CONSOLE_LEFT_QUICKBUILD.lua") @@ -579,16 +579,16 @@ CppScripts::Script* CppScripts::GetScript(Entity* parent, const std::string& scr script = new WishingWellServer(); else if (scriptName == "scripts\\ai\\ACT\\L_ACT_PLAYER_DEATH_TRIGGER.lua") script = new ActPlayerDeathTrigger(); - else if (scriptName == "scripts\\02_server\\Map\\General\\L_GROWING_FLOWER_SERVER.lua") - script = new GrowingFlower(); + else if (scriptName == "scripts\\02_server\\Map\\General\\L_GROWING_FLOWER_SERVER.lua") + script = new GrowingFlower(); else if (scriptName == "scripts\\02_server\\Map\\General\\L_TOKEN_CONSOLE_SERVER.lua") script = new TokenConsoleServer(); - else if (scriptName == "scripts\\ai\\ACT\\FootRace\\L_ACT_BASE_FOOT_RACE.lua") - script = new BaseFootRaceManager(); - else if (scriptName == "scripts\\02_server\\Map\\General\\L_PROP_PLATFORM.lua") - script = new PropertyPlatform(); - else if (scriptName == "scripts\\02_server\\Map\\VE\\L_VE_BRICKSAMPLE_SERVER.lua") - return new VeBricksampleServer(); + else if (scriptName == "scripts\\ai\\ACT\\FootRace\\L_ACT_BASE_FOOT_RACE.lua") + script = new BaseFootRaceManager(); + else if (scriptName == "scripts\\02_server\\Map\\General\\L_PROP_PLATFORM.lua") + script = new PropertyPlatform(); + else if (scriptName == "scripts\\02_server\\Map\\VE\\L_VE_BRICKSAMPLE_SERVER.lua") + return new VeBricksampleServer(); else if (scriptName == "scripts\\02_server\\Map\\General\\L_MAIL_BOX_SERVER.lua") script = new MailBoxServer(); else if (scriptName == "scripts\\ai\\ACT\\L_ACT_MINE.lua") @@ -604,9 +604,9 @@ CppScripts::Script* CppScripts::GetScript(Entity* parent, const std::string& scr else if (scriptName == "scripts\\02_server\\Map\\FV\\Racing\\RACE_MAELSTROM_GEISER.lua") script = new RaceMaelstromGeiser(); else if (scriptName == "scripts\\ai\\RACING\\OBJECTS\\FV_RACE_SMASH_EGG_IMAGINE_SERVER.lua") - script = new FvRaceSmashEggImagineServer(); + script = new FvRaceSmashEggImagineServer(); else if (scriptName == "scripts\\ai\\RACING\\OBJECTS\\RACE_SMASH_SERVER.lua") - script = new RaceSmashServer(); + script = new RaceSmashServer(); //NT: else if (scriptName == "scripts\\02_server\\Map\\NT\\L_NT_SENTINELWALKWAY_SERVER.lua") @@ -642,19 +642,19 @@ CppScripts::Script* CppScripts::GetScript(Entity* parent, const std::string& scr else if (scriptName == "scripts\\02_server\\Map\\NT\\L_NT_CONSOLE_TELEPORT_SERVER.lua") script = new NtConsoleTeleportServer(); else if (scriptName == "scripts\\02_server\\Map\\NT\\L_SPAWN_STEGO_SERVER.lua") - script = new SpawnStegoServer(); + script = new SpawnStegoServer(); else if (scriptName == "scripts\\02_server\\Map\\NT\\L_SPAWN_SABERCAT_SERVER.lua") - script = new SpawnSaberCatServer(); + script = new SpawnSaberCatServer(); else if (scriptName == "scripts\\02_server\\Map\\NT\\L_SPAWN_SHRAKE_SERVER.lua") - script = new SpawnShrakeServer(); - else if (scriptName == "scripts\\02_server\\Map\\NT\\L_NT_DUKE_SERVER.lua") - script = new NtDukeServer(); - else if (scriptName == "scripts\\02_server\\Map\\NT\\L_NT_HAEL_SERVER.lua") - script = new NtHaelServer(); - else if (scriptName == "scripts\\02_server\\Map\\NT\\L_NT_OVERBUILD_SERVER.lua") - script = new NtOverbuildServer(); - else if (scriptName == "scripts\\02_server\\Map\\NT\\L_NT_VANDA_SERVER.lua") - script = new NtVandaServer(); + script = new SpawnShrakeServer(); + else if (scriptName == "scripts\\02_server\\Map\\NT\\L_NT_DUKE_SERVER.lua") + script = new NtDukeServer(); + else if (scriptName == "scripts\\02_server\\Map\\NT\\L_NT_HAEL_SERVER.lua") + script = new NtHaelServer(); + else if (scriptName == "scripts\\02_server\\Map\\NT\\L_NT_OVERBUILD_SERVER.lua") + script = new NtOverbuildServer(); + else if (scriptName == "scripts\\02_server\\Map\\NT\\L_NT_VANDA_SERVER.lua") + script = new NtVandaServer(); else if (scriptName == "scripts\\02_server\\Map\\General\\L_FORCE_VOLUME_SERVER.lua") script = new ForceVolumeServer(); else if (scriptName == "scripts\\02_server\\Map\\NT\\L_NT_XRAY_SERVER.lua") @@ -706,33 +706,33 @@ CppScripts::Script* CppScripts::GetScript(Entity* parent, const std::string& scr else if (scriptName == "scripts\\02_server\\Enemy\\AM\\L_AM_DARKLING_APE.lua") script = new BaseEnemyApe(); else if (scriptName == "scripts\\02_server\\Map\\AM\\L_BLUE_X.lua") - script = new AmBlueX(); + script = new AmBlueX(); else if (scriptName == "scripts\\02_server\\Map\\AM\\L_TEAPOT_SERVER.lua") script = new AmTeapotServer(); // Ninjago else if (scriptName == "scripts\\02_server\\Map\\njhub\\L_GARMADON_CELEBRATION_SERVER.lua") - script = new NjGarmadonCelebration(); - else if (scriptName == "scripts\\02_server\\Map\\njhub\\L_WU_NPC.lua") - script = new NjWuNPC(); - else if (scriptName == "scripts\\02_server\\Map\\njhub\\L_SCROLL_CHEST_SERVER.lua") - script = new NjScrollChestServer(); - else if (scriptName == "scripts\\02_server\\Map\\njhub\\L_COLE_NPC.lua") - script = new NjColeNPC(); - else if (scriptName == "scripts\\02_server\\Map\\njhub\\L_JAY_MISSION_ITEMS.lua") - script = (NjNPCMissionSpinjitzuServer*) new NjJayMissionItems(); - else if (scriptName == "scripts\\02_server\\Map\\njhub\\L_NPC_MISSION_SPINJITZU_SERVER.lua") - script = new NjNPCMissionSpinjitzuServer(); + script = new NjGarmadonCelebration(); + else if (scriptName == "scripts\\02_server\\Map\\njhub\\L_WU_NPC.lua") + script = new NjWuNPC(); + else if (scriptName == "scripts\\02_server\\Map\\njhub\\L_SCROLL_CHEST_SERVER.lua") + script = new NjScrollChestServer(); + else if (scriptName == "scripts\\02_server\\Map\\njhub\\L_COLE_NPC.lua") + script = new NjColeNPC(); + else if (scriptName == "scripts\\02_server\\Map\\njhub\\L_JAY_MISSION_ITEMS.lua") + script = (NjNPCMissionSpinjitzuServer*) new NjJayMissionItems(); + else if (scriptName == "scripts\\02_server\\Map\\njhub\\L_NPC_MISSION_SPINJITZU_SERVER.lua") + script = new NjNPCMissionSpinjitzuServer(); else if (scriptName == "scripts\\02_server\\Map\\njhub\\L_ENEMY_SKELETON_SPAWNER.lua") script = new EnemySkeletonSpawner(); - else if (scriptName == "scripts\\02_server\\Map\\General\\L_NJ_RAIL_SWITCH.lua") - script = new NjRailSwitch(); - else if (scriptName == "scripts\\02_server\\Map\\General\\Ninjago\\L_RAIL_ACTIVATORS_SERVER.lua") - script = new NjRailActivatorsServer(); - else if (scriptName == "scripts\\02_server\\Map\\General\\Ninjago\\L_RAIL_POST_SERVER.lua") - script = new NjRailPostServer(); - else if (scriptName == "scripts\\02_server\\Map\\General\\Ninjago\\L_ICE_RAIL_ACTIVATOR_SERVER.lua") - script = new NjIceRailActivator(); + else if (scriptName == "scripts\\02_server\\Map\\General\\L_NJ_RAIL_SWITCH.lua") + script = new NjRailSwitch(); + else if (scriptName == "scripts\\02_server\\Map\\General\\Ninjago\\L_RAIL_ACTIVATORS_SERVER.lua") + script = new NjRailActivatorsServer(); + else if (scriptName == "scripts\\02_server\\Map\\General\\Ninjago\\L_RAIL_POST_SERVER.lua") + script = new NjRailPostServer(); + else if (scriptName == "scripts\\02_server\\Map\\General\\Ninjago\\L_ICE_RAIL_ACTIVATOR_SERVER.lua") + script = new NjIceRailActivator(); else if (scriptName == "scripts\\02_server\\Map\\njhub\\L_FALLING_TILE.lua") script = new FallingTile(); else if (scriptName == "scripts\\02_server\\Enemy\\General\\L_ENEMY_NJ_BUFF_STUN_IMMUNITY.lua") @@ -746,7 +746,7 @@ CppScripts::Script* CppScripts::GetScript(Entity* parent, const std::string& scr else if (scriptName == "scripts\\02_server\\Map\\njhub\\L_CAVE_PRISON_CAGE.lua") script = new CavePrisonCage(); else if (scriptName == "scripts\\02_server\\Map\\njhub\\boss_instance\\L_MONASTERY_BOSS_INSTANCE_SERVER.lua") - script = new NjMonastryBossInstance(); + script = new NjMonastryBossInstance(); else if (scriptName == "scripts\\02_server\\Map\\njhub\\L_CATAPULT_BOUNCER_SERVER.lua") script = new CatapultBouncerServer(); else if (scriptName == "scripts\\02_server\\Map\\njhub\\L_CATAPULT_BASE_SERVER.lua") @@ -762,13 +762,13 @@ CppScripts::Script* CppScripts::GetScript(Entity* parent, const std::string& scr else if (scriptName == "scripts\\02_server\\Map\\njhub\\L_BURNING_TILE.lua") script = new BurningTile(); else if (scriptName == "scripts\\02_server\\Map\\njhub\\L_SPAWN_EARTH_PET_SERVER.lua") - script = new NjEarthDragonPetServer(); + script = new NjEarthDragonPetServer(); else if (scriptName == "scripts\\02_server\\Map\\njhub\\L_EARTH_PET_SERVER.lua") - script = new NjEarthPetServer(); + script = new NjEarthPetServer(); else if (scriptName == "scripts\\02_server\\Map\\njhub\\L_DRAGON_EMBLEM_CHEST_SERVER.lua") - script = new NjDragonEmblemChestServer(); + script = new NjDragonEmblemChestServer(); else if (scriptName == "scripts\\02_server\\Map\\njhub\\L_NYA_MISSION_ITEMS.lua") - script = new NjNyaMissionitems(); + script = new NjNyaMissionitems(); //DLU: else if (scriptName == "scripts\\02_server\\DLU\\DLUVanityNPC.lua") @@ -776,35 +776,35 @@ CppScripts::Script* CppScripts::GetScript(Entity* parent, const std::string& scr // Survival minigame else if (scriptName == "scripts\\02_server\\Enemy\\Survival\\L_AG_SURVIVAL_STROMBIE.lua") - script = new AgSurvivalStromling(); + script = new AgSurvivalStromling(); else if (scriptName == "scripts\\02_server\\Enemy\\Survival\\L_AG_SURVIVAL_DARKLING_MECH.lua") - script = new AgSurvivalMech(); + script = new AgSurvivalMech(); else if (scriptName == "scripts\\02_server\\Enemy\\Survival\\L_AG_SURVIVAL_DARK_SPIDERLING.lua") - script = new AgSurvivalSpiderling(); + script = new AgSurvivalSpiderling(); // Scripted equipment else if (scriptName == "scripts\\EquipmentScripts\\Sunflower.lua") - script = new Sunflower(); + script = new Sunflower(); else if (scriptName == "scripts/EquipmentScripts/AnvilOfArmor.lua") - script = new AnvilOfArmor(); + script = new AnvilOfArmor(); else if (scriptName == "scripts/EquipmentScripts/FountainOfImagination.lua") - script = new FountainOfImagination(); + script = new FountainOfImagination(); else if (scriptName == "scripts/EquipmentScripts/CauldronOfLife.lua") - script = new CauldronOfLife(); + script = new CauldronOfLife(); else if (scriptName == "scripts\\02_server\\Equipment\\L_BOOTYDIG_SERVER.lua") - script = new BootyDigServer(); + script = new BootyDigServer(); else if (scriptName == "scripts\\EquipmentScripts\\PersonalFortress.lua") script = new PersonalFortress(); else if (scriptName == "scripts\\02_server\\Map\\General\\L_PROPERTY_DEVICE.lua") - script = new PropertyDevice(); + script = new PropertyDevice(); else if (scriptName == "scripts\\02_server\\Map\\General\\L_IMAG_BACKPACK_HEALS_SERVER.lua") - script = new ImaginationBackpackHealServer(); + script = new ImaginationBackpackHealServer(); else if (scriptName == "scripts\\ai\\GENERAL\\L_LEGO_DIE_ROLL.lua") script = new LegoDieRoll(); - else if (scriptName == "scripts\\EquipmentScripts\\BuccaneerValiantShip.lua") - script = new BuccaneerValiantShip(); + else if (scriptName == "scripts\\EquipmentScripts\\BuccaneerValiantShip.lua") + script = new BuccaneerValiantShip(); else if (scriptName == "scripts\\EquipmentScripts\\FireFirstSkillonStartup.lua") - script = new FireFirstSkillonStartup(); + script = new FireFirstSkillonStartup(); // FB else if (scriptName == "scripts\\ai\\NS\\WH\\L_ROCKHYDRANT_BROKEN.lua") script = new RockHydrantBroken(); @@ -819,7 +819,7 @@ CppScripts::Script* CppScripts::GetScript(Entity* parent, const std::string& scr else if (script == invalidToReturn) { if (scriptName.length() > 0) Game::logger->LogDebug("CppScripts", "Attempted to load CppScript for '%s', but returned InvalidScript.", scriptName.c_str()); - // information not really needed for sys admins but is for developers + // information not really needed for sys admins but is for developers script = invalidToReturn; } diff --git a/dScripts/CppScripts.h b/dScripts/CppScripts.h index bf30017c..916d2638 100644 --- a/dScripts/CppScripts.h +++ b/dScripts/CppScripts.h @@ -11,15 +11,15 @@ class NiPoint3; namespace CppScripts { /** * Base class for all scripts. Includes virtual methods to be overridden to handle LUA equivelent events. - * + * * All methods pass 'self' as the first parameter, this is the associated parent entity for the event. * There will only ever be one instance of each script. - * + * * Do not use class members as entity specific variables unless you're sure there will only event be one instance of this script. * Do use class members as script wide variables, variables all entities which this script will access. - * + * * Use self->GetVar(u"variable_name") and self->SetVar(u"variable_name", value) to manage variables. - * + * * Designed to yield as close to a 1:1 mapping as possible with LUA. * There will be events which are not implemented or inheritetly LUA features not easily translated to C++. * Most of the time these can be worked around or ignored. @@ -31,79 +31,79 @@ namespace CppScripts { /** * Invoked one frame after the script is loaded. - * + * * Equivalent to 'function onStartup(self)' */ virtual void OnStartup(Entity* self) {}; /** * Invoked upon an entity entering the phantom collider on self. - * + * * Equivalent to 'function onCollisionPhantom(self, msg)' */ virtual void OnCollisionPhantom(Entity* self, Entity* target) {}; /** * Invoked when a player accepted a mission. - * + * * Equivalent to 'function onMissionDialogueOK(self, msg)' */ virtual void OnMissionDialogueOK(Entity* self, Entity* target, int missionID, MissionState missionState) {}; /** * Invoked when the client or the server invoked an event server-side. - * + * * Equivalent to 'function onFireEventServerSide(self, msg)' */ - virtual void OnFireEventServerSide(Entity *self, Entity *sender, std::string args, int32_t param1, int32_t param2, int32_t param3) {}; + virtual void OnFireEventServerSide(Entity* self, Entity* sender, std::string args, int32_t param1, int32_t param2, int32_t param3) {}; /** * Invoked upon sending a object notification. - * + * * Equivalent to 'function onNotifyObject(self, msg)' */ - virtual void OnNotifyObject(Entity *self, Entity *sender, const std::string& name, int32_t param1 = 0, int32_t param2 = 0) {}; - + virtual void OnNotifyObject(Entity* self, Entity* sender, const std::string& name, int32_t param1 = 0, int32_t param2 = 0) {}; + /** * Invoked upon a player exiting the modular build minigame. - * + * * Equivalent to 'function onModularBuildExit(self, msg)' */ virtual void OnModularBuildExit(Entity* self, Entity* player, bool bCompleted, std::vector modules) {}; - + /** * Invoked when a player has loaded into the zone. - * + * * Equivalent to 'function onPlayerLoaded(self, msg)' */ virtual void OnPlayerLoaded(Entity* self, Entity* player) {}; /** * Invoked when a player has died. - * + * * Equivalent to 'function onPlayerDied(self, msg)' */ virtual void OnPlayerDied(Entity* self, Entity* player) {}; /** * Invoked when a player has resurrected. - * + * * Equivalent to 'function onPlayerResurrected(self, msg)' */ virtual void OnPlayerResurrected(Entity* self, Entity* player) {}; /** * Invoked when a player has left the zone. - * + * * Equivalent to 'function onPlayerExit(self, msg)' */ virtual void OnPlayerExit(Entity* self, Entity* player) {}; /** * Invoked when a player has interacted with the proximity collider on self. - * + * * Equivalent to 'function onProximityUpdate(self, msg)' - * + * * @param name The name of the proximity collider recviving an interaction. * @param status "ENTER" if a player has entered the proximity collider; "LEAVE" if a player has left the proximity collider */ @@ -111,182 +111,182 @@ namespace CppScripts { /** * Invoked when a timer on self has expired. - * + * * Equivalent to 'function onTimerDone(self, msg)' */ virtual void OnTimerDone(Entity* self, std::string timerName) {}; /** * Invoked when a player interactions with self. - * + * * Equivalent to 'function onUse(self, msg)' */ virtual void OnUse(Entity* self, Entity* user) {}; /** * Invoked when self has died. - * + * * Equivalent to 'function onDie(self, msg)' */ virtual void OnDie(Entity* self, Entity* killer) {}; /** * Invoked when self has received a hit. - * + * * Equivalent to 'function onHit(self, msg)' */ virtual void OnHit(Entity* self, Entity* attacker) {}; /** * Invoked when self has received an emote from a player. - * + * * Equivalent to 'function onEmoteReceived(self, msg)' */ virtual void OnEmoteReceived(Entity* self, int32_t emote, Entity* target) {}; /** * Invoked when a player has started building this quickbuild. - * + * * Equivalent to 'function onRebuildStart(self, msg)' */ virtual void OnRebuildStart(Entity* self, Entity* target) {}; - + /** * Invoked when this quickbuild has changed state. - * + * * Equivalent to 'function onRebuildNotifyState(self, msg)' */ virtual void OnRebuildNotifyState(Entity* self, eRebuildState state) {}; /** * Invoked when this quickbuild has been completed. - * + * * Equivalent to 'function onRebuildComplete(self, msg)' */ virtual void OnRebuildComplete(Entity* self, Entity* target) {}; /** * Invoked when self has received either a hit or heal. - * + * * Equivalent to 'function onHitOrHealResult(self, msg)' */ virtual void OnHitOrHealResult(Entity* self, Entity* attacker, int32_t damage) {}; - + /** * Invoked when a player has responsed to a mission. - * + * * Equivalent to 'function onRespondToMission(self, msg)' */ virtual void OnRespondToMission(Entity* self, int missionID, Entity* player, int reward) {}; - + /** * Invoked once per frame. - * + * * No LUA eqivalent. */ virtual void OnUpdate(Entity* self) {}; - + /** * Invoked when this property has been rented. - * + * * Equivalent to 'function onZonePropertyRented(self, msg)' */ virtual void OnZonePropertyRented(Entity* self, Entity* renter) {}; - + /** * Invoked when a player has begun to edit this property. - * + * * Equivalent to 'function onZonePropertyEditBegin(self, msg)' */ virtual void OnZonePropertyEditBegin(Entity* self) {}; /** * Invoked when a player has concluded editing this property. - * + * * Equivalent to 'function onZonePropertyEditEnd(self, msg)' */ virtual void OnZonePropertyEditEnd(Entity* self) {}; /** * Invoked when a player has equipped a model while editing this property. - * + * * Equivalent to 'function onZonePropertyModelEquipped(self, msg)' */ virtual void OnZonePropertyModelEquipped(Entity* self) {}; /** * Invoked when a player has placed a model while editing this property. - * + * * Equivalent to 'function onZonePropertyModelPlaced(self, msg)' */ virtual void OnZonePropertyModelPlaced(Entity* self, Entity* player) {}; /** * Invoked when a player has picked up a model while editing this property. - * + * * Equivalent to 'function onZonePropertyModelPickedUp(self, msg)' */ virtual void OnZonePropertyModelPickedUp(Entity* self, Entity* player) {}; /** * Invoked when a player removed a model while editing this property. - * + * * Equivalent to 'function onZonePropertyModelRemoved(self, msg)' */ virtual void OnZonePropertyModelRemoved(Entity* self, Entity* player) {}; /** * Invoked when a player removed a model while holding it when editing this property. - * + * * Equivalent to 'function onZonePropertyModelRemoved(self, msg)' */ virtual void OnZonePropertyModelRemovedWhileEquipped(Entity* self, Entity* player) {}; - + /** * Invoked when a player rotated a model while editing this property. - * + * * Equivalent to 'function onZonePropertyModelRotated(self, msg)' */ virtual void OnZonePropertyModelRotated(Entity* self, Entity* player) {}; /** * Invoked when the pet taming minigame encounted an event. - * + * * Equivalent to 'function onNotifyPetTamingMinigame(self, msg)' */ virtual void OnNotifyPetTamingMinigame(Entity* self, Entity* tamer, eNotifyType type) {}; - + /** * Invoked when a player responded to a message box. - * + * * Equivalent to 'function onMessageBoxResponse(self, msg)' */ virtual void OnMessageBoxResponse(Entity* self, Entity* sender, int32_t button, const std::u16string& identifier, const std::u16string& userData) {}; - + /** * Invoked when a player responded to a choice box. - * + * * Equivalent to 'function onChoiceBoxResponse(self, msg)' */ virtual void OnChoiceBoxResponse(Entity* self, Entity* sender, int32_t button, const std::u16string& buttonIdentifier, const std::u16string& identifier) {}; - + /** * Invoked when self arrived at a moving platform waypoint. - * + * * Equivalent to 'function onWaypointReached(self, msg)' */ virtual void OnWaypointReached(Entity* self, uint32_t waypointIndex) {}; - + /** * Invoked when a player fired a skill event on self. - * + * * Equivalent to 'function onSkillEventFired(self, msg)' */ virtual void OnSkillEventFired(Entity* self, Entity* caster, const std::string& message) {}; - + /** * Invoked when self casted a skill. - * + * * Equivalent to 'function onSkillCast(self, msg)' */ virtual void OnSkillCast(Entity* self, uint32_t skillID) {}; @@ -309,13 +309,15 @@ namespace CppScripts { * @param value2 some other value to represent the change * @param stringValue some string value to represent the change */ - virtual void OnActivityStateChangeRequest(Entity* self, const LWOOBJID senderID, const int32_t value1, - const int32_t value2, const std::u16string& stringValue) {}; + virtual void OnActivityStateChangeRequest(Entity* self, const LWOOBJID senderID, const int32_t value1, + const int32_t value2, const std::u16string& stringValue) { + }; virtual void OnCinematicUpdate(Entity* self, Entity* sender, eCinematicEvent event, const std::u16string& pathName, - float_t pathTime, float_t totalTime, int32_t waypoint) {}; + float_t pathTime, float_t totalTime, int32_t waypoint) { + }; }; Script* GetScript(Entity* parent, const std::string& scriptName); std::vector GetEntityScripts(Entity* entity); -}; \ No newline at end of file +}; diff --git a/dScripts/CrabServer.cpp b/dScripts/CrabServer.cpp index 7cab7fb5..890b8ed9 100644 --- a/dScripts/CrabServer.cpp +++ b/dScripts/CrabServer.cpp @@ -2,42 +2,42 @@ #include "PetComponent.h" void CrabServer::OnStartup(Entity* self) { - auto* petComponent = self->GetComponent(); - if (petComponent == nullptr || petComponent->GetOwner() != nullptr) - return; + auto* petComponent = self->GetComponent(); + if (petComponent == nullptr || petComponent->GetOwner() != nullptr) + return; - // Triggers the local crab script for taming etc. - auto tamer = self->GetVar(u"tamer"); - // Client compares this with player:GetID() which is a string, so we'll have to give it a string - self->SetNetworkVar(u"crabtamer", std::to_string(tamer)); + // Triggers the local crab script for taming etc. + auto tamer = self->GetVar(u"tamer"); + // Client compares this with player:GetID() which is a string, so we'll have to give it a string + self->SetNetworkVar(u"crabtamer", std::to_string(tamer)); - // Kill if the player decides that the crab is not worthy - self->AddTimer("killself", 45.0f); + // Kill if the player decides that the crab is not worthy + self->AddTimer("killself", 45.0f); } void CrabServer::OnTimerDone(Entity* self, std::string timerName) { - if (timerName == "killself") { + if (timerName == "killself") { - // Don't accidentally kill a pet that is already owned - auto* petComponent = self->GetComponent(); - if (petComponent == nullptr || petComponent->GetOwner() != nullptr) - return; + // Don't accidentally kill a pet that is already owned + auto* petComponent = self->GetComponent(); + if (petComponent == nullptr || petComponent->GetOwner() != nullptr) + return; - self->Smash(self->GetObjectID(), SILENT); - } + self->Smash(self->GetObjectID(), SILENT); + } } void CrabServer::OnNotifyPetTamingMinigame(Entity* self, Entity* tamer, eNotifyType type) { - if (type == NOTIFY_TYPE_BEGIN) { - self->CancelTimer("killself"); - } else if (type == NOTIFY_TYPE_QUIT || type == NOTIFY_TYPE_FAILED) { - self->Smash(self->GetObjectID(), SILENT); - } else if (type == NOTIFY_TYPE_SUCCESS) { - auto* petComponent = self->GetComponent(); - if (petComponent == nullptr) - return; - // TODO: Remove custom group? - // Command the pet to the player as it may otherwise go to its spawn point which is non existant - // petComponent->Command(NiPoint3::ZERO, LWOOBJID_EMPTY, 6, 202, true); - } + if (type == NOTIFY_TYPE_BEGIN) { + self->CancelTimer("killself"); + } else if (type == NOTIFY_TYPE_QUIT || type == NOTIFY_TYPE_FAILED) { + self->Smash(self->GetObjectID(), SILENT); + } else if (type == NOTIFY_TYPE_SUCCESS) { + auto* petComponent = self->GetComponent(); + if (petComponent == nullptr) + return; + // TODO: Remove custom group? + // Command the pet to the player as it may otherwise go to its spawn point which is non existant + // petComponent->Command(NiPoint3::ZERO, LWOOBJID_EMPTY, 6, 202, true); + } } diff --git a/dScripts/CrabServer.h b/dScripts/CrabServer.h index b773ed75..28533cb5 100644 --- a/dScripts/CrabServer.h +++ b/dScripts/CrabServer.h @@ -4,7 +4,7 @@ class CrabServer : public CppScripts::Script { public: - void OnStartup(Entity* self) override; - void OnTimerDone(Entity* self, std::string timerName) override; - void OnNotifyPetTamingMinigame(Entity* self, Entity* tamer, eNotifyType type) override; + void OnStartup(Entity* self) override; + void OnTimerDone(Entity* self, std::string timerName) override; + void OnNotifyPetTamingMinigame(Entity* self, Entity* tamer, eNotifyType type) override; }; diff --git a/dScripts/DLUVanityNPC.cpp b/dScripts/DLUVanityNPC.cpp index c219a5f9..e3db2353 100644 --- a/dScripts/DLUVanityNPC.cpp +++ b/dScripts/DLUVanityNPC.cpp @@ -3,46 +3,44 @@ #include "dServer.h" #include "VanityUtilities.h" -void DLUVanityNPC::OnStartup(Entity* self) -{ - m_NPC = VanityUtilities::GetNPC("averysumner - Destroyer of Worlds"); +void DLUVanityNPC::OnStartup(Entity* self) { + m_NPC = VanityUtilities::GetNPC("averysumner - Destroyer of Worlds"); - if (m_NPC == nullptr) { - return; - } + if (m_NPC == nullptr) { + return; + } - if (self->GetVar(u"teleport")) { - self->AddTimer("setupTeleport", 15.0f); - } + if (self->GetVar(u"teleport")) { + self->AddTimer("setupTeleport", 15.0f); + } } -void DLUVanityNPC::OnTimerDone(Entity* self, std::string timerName) -{ - if (timerName == "setupTeleport") { - GameMessages::SendPlayAnimation(self, u"interact"); - GameMessages::SendPlayFXEffect(self->GetObjectID(), 6478, u"teleportBeam", "teleportBeam"); - GameMessages::SendPlayFXEffect(self->GetObjectID(), 6478, u"teleportRings", "teleportRings"); +void DLUVanityNPC::OnTimerDone(Entity* self, std::string timerName) { + if (timerName == "setupTeleport") { + GameMessages::SendPlayAnimation(self, u"interact"); + GameMessages::SendPlayFXEffect(self->GetObjectID(), 6478, u"teleportBeam", "teleportBeam"); + GameMessages::SendPlayFXEffect(self->GetObjectID(), 6478, u"teleportRings", "teleportRings"); - self->AddTimer("teleport", 2.0f); - self->AddTimer("stopFX", 2.0f); - } else if (timerName == "stopFX") { - GameMessages::SendStopFXEffect(self, true, "teleportBeam"); - GameMessages::SendStopFXEffect(self, true, "teleportRings"); - } else if (timerName == "teleport") { - std::vector& locations = m_NPC->m_Locations[Game::server->GetZoneID()]; + self->AddTimer("teleport", 2.0f); + self->AddTimer("stopFX", 2.0f); + } else if (timerName == "stopFX") { + GameMessages::SendStopFXEffect(self, true, "teleportBeam"); + GameMessages::SendStopFXEffect(self, true, "teleportRings"); + } else if (timerName == "teleport") { + std::vector& locations = m_NPC->m_Locations[Game::server->GetZoneID()]; -selectLocation: - VanityNPCLocation& newLocation = locations[GeneralUtils::GenerateRandomNumber(0, locations.size() - 1)]; + selectLocation: + VanityNPCLocation& newLocation = locations[GeneralUtils::GenerateRandomNumber(0, locations.size() - 1)]; - if (self->GetPosition() == newLocation.m_Position) { - goto selectLocation; // cry about it - } - - self->SetPosition(newLocation.m_Position); - self->SetRotation(newLocation.m_Rotation); - GameMessages::SendPlayFXEffect(self->GetObjectID(), 6478, u"teleportBeam", "teleportBeam"); - GameMessages::SendPlayFXEffect(self->GetObjectID(), 6478, u"teleportRings", "teleportRings"); - self->AddTimer("stopFX", 2.0f); - self->AddTimer("setupTeleport", 15.0f); - } + if (self->GetPosition() == newLocation.m_Position) { + goto selectLocation; // cry about it + } + + self->SetPosition(newLocation.m_Position); + self->SetRotation(newLocation.m_Rotation); + GameMessages::SendPlayFXEffect(self->GetObjectID(), 6478, u"teleportBeam", "teleportBeam"); + GameMessages::SendPlayFXEffect(self->GetObjectID(), 6478, u"teleportRings", "teleportRings"); + self->AddTimer("stopFX", 2.0f); + self->AddTimer("setupTeleport", 15.0f); + } } diff --git a/dScripts/DLUVanityNPC.h b/dScripts/DLUVanityNPC.h index 4eba3554..aeb8e051 100644 --- a/dScripts/DLUVanityNPC.h +++ b/dScripts/DLUVanityNPC.h @@ -5,9 +5,9 @@ class VanityNPC; class DLUVanityNPC : public CppScripts::Script { public: - void OnStartup(Entity* self) override; - void OnTimerDone(Entity* self, std::string timerName) override; + void OnStartup(Entity* self) override; + void OnTimerDone(Entity* self, std::string timerName) override; private: - VanityNPC* m_NPC; + VanityNPC* m_NPC; }; diff --git a/dScripts/DamagingPets.cpp b/dScripts/DamagingPets.cpp index f82bc83e..f7eada00 100644 --- a/dScripts/DamagingPets.cpp +++ b/dScripts/DamagingPets.cpp @@ -4,142 +4,142 @@ #include "BaseCombatAIComponent.h" #include "RenderComponent.h" -void DamagingPets::OnStartup(Entity *self) { +void DamagingPets::OnStartup(Entity* self) { - // Make the pet hostile or non-hostile based on whether or not it is tamed - const auto* petComponent = self->GetComponent(); - if (petComponent != nullptr && petComponent->GetOwner() == nullptr) { - self->AddTimer("GoEvil", 0.5f); - } + // Make the pet hostile or non-hostile based on whether or not it is tamed + const auto* petComponent = self->GetComponent(); + if (petComponent != nullptr && petComponent->GetOwner() == nullptr) { + self->AddTimer("GoEvil", 0.5f); + } } -void DamagingPets::OnPlayerLoaded(Entity *self, Entity *player) { +void DamagingPets::OnPlayerLoaded(Entity* self, Entity* player) { - // Makes it so that new players also see the effect - self->AddCallbackTimer(2.5f, [self]() { - if (self != nullptr) { - const auto* petComponent = self->GetComponent(); - if (petComponent != nullptr && petComponent->GetOwner() == nullptr && self->GetVar(u"IsEvil")) { - auto* renderComponent = self->GetComponent(); - if (renderComponent != nullptr) { - auto counter = 1; - for (const auto petEffect : GetPetInfo(self).effect) { - renderComponent->PlayEffect(petEffect, u"create", "FXname" + std::to_string(counter)); - counter++; - } - } - } - } - }); + // Makes it so that new players also see the effect + self->AddCallbackTimer(2.5f, [self]() { + if (self != nullptr) { + const auto* petComponent = self->GetComponent(); + if (petComponent != nullptr && petComponent->GetOwner() == nullptr && self->GetVar(u"IsEvil")) { + auto* renderComponent = self->GetComponent(); + if (renderComponent != nullptr) { + auto counter = 1; + for (const auto petEffect : GetPetInfo(self).effect) { + renderComponent->PlayEffect(petEffect, u"create", "FXname" + std::to_string(counter)); + counter++; + } + } + } + } + }); } -void DamagingPets::OnNotifyPetTamingMinigame(Entity *self, Entity *tamer, eNotifyType type) { - switch (type) { - case NOTIFY_TYPE_SUCCESS: - case NOTIFY_TYPE_BEGIN: - self->CancelAllTimers(); - ClearEffects(self); - break; - case NOTIFY_TYPE_FAILED: - case NOTIFY_TYPE_QUIT: - { - self->SetNetworkVar(u"bIAmTamable", false); - self->AddTimer("GoEvil", 1.0f); - break; - } - default: - break; - } +void DamagingPets::OnNotifyPetTamingMinigame(Entity* self, Entity* tamer, eNotifyType type) { + switch (type) { + case NOTIFY_TYPE_SUCCESS: + case NOTIFY_TYPE_BEGIN: + self->CancelAllTimers(); + ClearEffects(self); + break; + case NOTIFY_TYPE_FAILED: + case NOTIFY_TYPE_QUIT: + { + self->SetNetworkVar(u"bIAmTamable", false); + self->AddTimer("GoEvil", 1.0f); + break; + } + default: + break; + } } -void DamagingPets::OnSkillEventFired(Entity *self, Entity *caster, const std::string &message) { - const auto infoForPet = GetPetInfo(self); - if (infoForPet.skill == message) { +void DamagingPets::OnSkillEventFired(Entity* self, Entity* caster, const std::string& message) { + const auto infoForPet = GetPetInfo(self); + if (infoForPet.skill == message) { - // Only make pets tamable that aren't tamed yet - const auto* petComponent = self->GetComponent(); - if (petComponent != nullptr && petComponent->GetOwner() == nullptr && self->GetVar(u"IsEvil")) { - ClearEffects(self); - self->AddTimer("GoEvil", 30.0f); - self->SetNetworkVar(u"bIAmTamable", true); - } - } + // Only make pets tamable that aren't tamed yet + const auto* petComponent = self->GetComponent(); + if (petComponent != nullptr && petComponent->GetOwner() == nullptr && self->GetVar(u"IsEvil")) { + ClearEffects(self); + self->AddTimer("GoEvil", 30.0f); + self->SetNetworkVar(u"bIAmTamable", true); + } + } } -void DamagingPets::OnTimerDone(Entity *self, std::string message) { - if (message == "GoEvil") { - MakeUntamable(self); - } +void DamagingPets::OnTimerDone(Entity* self, std::string message) { + if (message == "GoEvil") { + MakeUntamable(self); + } } -void DamagingPets::MakeUntamable(Entity *self) { - auto* petComponent = self->GetComponent(); +void DamagingPets::MakeUntamable(Entity* self) { + auto* petComponent = self->GetComponent(); - // If the pet is currently not being tamed, make it hostile - if (petComponent != nullptr && petComponent->GetStatus() != 5) { - self->SetNetworkVar(u"bIAmTamable", false); - self->SetVar(u"IsEvil", true); - petComponent->SetStatus(1); + // If the pet is currently not being tamed, make it hostile + if (petComponent != nullptr && petComponent->GetStatus() != 5) { + self->SetNetworkVar(u"bIAmTamable", false); + self->SetVar(u"IsEvil", true); + petComponent->SetStatus(1); - auto* combatAIComponent = self->GetComponent(); - if (combatAIComponent != nullptr) { - combatAIComponent->SetDisabled(false); - } + auto* combatAIComponent = self->GetComponent(); + if (combatAIComponent != nullptr) { + combatAIComponent->SetDisabled(false); + } - // Special faction that can attack the player but the player can't attack - auto* destroyableComponent = self->GetComponent(); - if (destroyableComponent != nullptr) { - destroyableComponent->SetFaction(114); - destroyableComponent->SetHealth(5); - } + // Special faction that can attack the player but the player can't attack + auto* destroyableComponent = self->GetComponent(); + if (destroyableComponent != nullptr) { + destroyableComponent->SetFaction(114); + destroyableComponent->SetHealth(5); + } - auto* renderComponent = self->GetComponent(); - if (renderComponent != nullptr) { - auto counter = 1; - for (const auto petEffect : GetPetInfo(self).effect) { - renderComponent->PlayEffect(petEffect, u"create", "FXname" + std::to_string(counter)); - counter++; - } - } - } + auto* renderComponent = self->GetComponent(); + if (renderComponent != nullptr) { + auto counter = 1; + for (const auto petEffect : GetPetInfo(self).effect) { + renderComponent->PlayEffect(petEffect, u"create", "FXname" + std::to_string(counter)); + counter++; + } + } + } } -void DamagingPets::ClearEffects(Entity *self) { - self->SetVar(u"IsEvil", false); +void DamagingPets::ClearEffects(Entity* self) { + self->SetVar(u"IsEvil", false); - auto* petComponent = self->GetComponent(); - if (petComponent != nullptr) { - petComponent->SetStatus(67108866); - } + auto* petComponent = self->GetComponent(); + if (petComponent != nullptr) { + petComponent->SetStatus(67108866); + } - auto* combatAIComponent = self->GetComponent(); - if (combatAIComponent != nullptr) { - combatAIComponent->SetDisabled(true); - } + auto* combatAIComponent = self->GetComponent(); + if (combatAIComponent != nullptr) { + combatAIComponent->SetDisabled(true); + } - auto* destroyableComponent = self->GetComponent(); - if (destroyableComponent != nullptr) { - destroyableComponent->SetFaction(99); - } + auto* destroyableComponent = self->GetComponent(); + if (destroyableComponent != nullptr) { + destroyableComponent->SetFaction(99); + } - auto* renderComponent = self->GetComponent(); - if (renderComponent != nullptr) { - auto counter = 1; - for (const auto petEffect : GetPetInfo(self).effect) { - renderComponent->StopEffect("FXname" + std::to_string(counter)); - counter++; - } - } + auto* renderComponent = self->GetComponent(); + if (renderComponent != nullptr) { + auto counter = 1; + for (const auto petEffect : GetPetInfo(self).effect) { + renderComponent->StopEffect("FXname" + std::to_string(counter)); + counter++; + } + } } -PetInfo DamagingPets::GetPetInfo(Entity *self) { - const auto infoForPet = petInfo.find(self->GetLOT()); - return infoForPet != petInfo.end() ? infoForPet->second : petInfo.begin()->second; +PetInfo DamagingPets::GetPetInfo(Entity* self) { + const auto infoForPet = petInfo.find(self->GetLOT()); + return infoForPet != petInfo.end() ? infoForPet->second : petInfo.begin()->second; } // Does not compile on Win32 with name specifiers const std::map DamagingPets::petInfo = { - { 5639, { /*.effect =*/ { 3170, 4058 }, /*.skill =*/ "waterspray"}}, // Red dragon - { 5641, { /*.effect =*/ { 3170, 4058 }, /*.skill =*/ "waterspray"}}, // Green dragon - { 3261, { /*.effect =*/ { 1490 }, /*.skill =*/ "waterspray"}}, // Skunk + { 5639, { /*.effect =*/ { 3170, 4058 }, /*.skill =*/ "waterspray"}}, // Red dragon + { 5641, { /*.effect =*/ { 3170, 4058 }, /*.skill =*/ "waterspray"}}, // Green dragon + { 3261, { /*.effect =*/ { 1490 }, /*.skill =*/ "waterspray"}}, // Skunk }; diff --git a/dScripts/DamagingPets.h b/dScripts/DamagingPets.h index 04c4e6bf..2ce0ddc1 100644 --- a/dScripts/DamagingPets.h +++ b/dScripts/DamagingPets.h @@ -5,20 +5,20 @@ * Information about pets regarding which effect to play when a skill is cast */ struct PetInfo { - const std::vector effect; - const std::string skill; + const std::vector effect; + const std::string skill; }; class DamagingPets : public CppScripts::Script { public: - void OnStartup(Entity* self) override; - void OnTimerDone(Entity* self, std::string message) override; - void OnNotifyPetTamingMinigame(Entity* self, Entity* tamer, eNotifyType type) override; - void OnSkillEventFired(Entity* self, Entity* target, const std::string& message) override; - void OnPlayerLoaded(Entity* self, Entity* player) override; + void OnStartup(Entity* self) override; + void OnTimerDone(Entity* self, std::string message) override; + void OnNotifyPetTamingMinigame(Entity* self, Entity* tamer, eNotifyType type) override; + void OnSkillEventFired(Entity* self, Entity* target, const std::string& message) override; + void OnPlayerLoaded(Entity* self, Entity* player) override; private: - static void MakeUntamable(Entity* self); - static PetInfo GetPetInfo(Entity* self); - static void ClearEffects(Entity* self); - static const std::map petInfo; + static void MakeUntamable(Entity* self); + static PetInfo GetPetInfo(Entity* self); + static void ClearEffects(Entity* self); + static const std::map petInfo; }; diff --git a/dScripts/Darkitect.cpp b/dScripts/Darkitect.cpp index c4e1e45d..323d0247 100644 --- a/dScripts/Darkitect.cpp +++ b/dScripts/Darkitect.cpp @@ -5,8 +5,7 @@ #include "GameMessages.h" #include "Character.h" -void Darkitect::Reveal(Entity* self, Entity* player) -{ +void Darkitect::Reveal(Entity* self, Entity* player) { const auto playerID = player->GetObjectID(); GameMessages::SendNotifyClientObject(self->GetObjectID(), u"reveal", 0, 0, playerID, "", player->GetSystemAddress()); @@ -31,5 +30,5 @@ void Darkitect::Reveal(Entity* self, Entity* player) EntityManager::Instance()->SerializeEntity(player); } - }); + }); } diff --git a/dScripts/EnemyNjBuff.cpp b/dScripts/EnemyNjBuff.cpp index 8dd19cce..07b2d899 100644 --- a/dScripts/EnemyNjBuff.cpp +++ b/dScripts/EnemyNjBuff.cpp @@ -1,14 +1,12 @@ #include "EnemyNjBuff.h" #include "SkillComponent.h" -void EnemyNjBuff::OnStartup(Entity* self) -{ - auto* skillComponent = self->GetComponent(); +void EnemyNjBuff::OnStartup(Entity* self) { + auto* skillComponent = self->GetComponent(); - if (skillComponent == nullptr) - { - return; - } + if (skillComponent == nullptr) { + return; + } - skillComponent->CalculateBehavior(1127, 24812, self->GetObjectID(), true); + skillComponent->CalculateBehavior(1127, 24812, self->GetObjectID(), true); } diff --git a/dScripts/EnemyRoninSpawner.cpp b/dScripts/EnemyRoninSpawner.cpp index 25288968..b6cae3bb 100644 --- a/dScripts/EnemyRoninSpawner.cpp +++ b/dScripts/EnemyRoninSpawner.cpp @@ -3,78 +3,66 @@ #include "RenderComponent.h" #include "EntityManager.h" -void EnemyRoninSpawner::OnStartup(Entity* self) -{ - self->SetProximityRadius(15, "ronin"); +void EnemyRoninSpawner::OnStartup(Entity* self) { + self->SetProximityRadius(15, "ronin"); } -void EnemyRoninSpawner::OnTimerDone(Entity* self, std::string timerName) -{ - if (timerName == "hatchTime") - { - auto* renderComponent = self->GetComponent(); +void EnemyRoninSpawner::OnTimerDone(Entity* self, std::string timerName) { + if (timerName == "hatchTime") { + auto* renderComponent = self->GetComponent(); - if (renderComponent != nullptr) - { - renderComponent->PlayEffect(644, u"create", "BurstFX1"); - } + if (renderComponent != nullptr) { + renderComponent->PlayEffect(644, u"create", "BurstFX1"); + } - EntityInfo info {}; - info.lot = 7815; - info.pos = self->GetPosition(); - info.rot = self->GetRotation(); - info.spawnerID = self->GetObjectID(); + EntityInfo info{}; + info.lot = 7815; + info.pos = self->GetPosition(); + info.rot = self->GetRotation(); + info.spawnerID = self->GetObjectID(); - auto* spawnedEntity = EntityManager::Instance()->CreateEntity(info); + auto* spawnedEntity = EntityManager::Instance()->CreateEntity(info); - if (spawnedEntity == nullptr) - { - return; - } + if (spawnedEntity == nullptr) { + return; + } - EntityManager::Instance()->ConstructEntity(spawnedEntity); + EntityManager::Instance()->ConstructEntity(spawnedEntity); - spawnedEntity->AddCallbackTimer(60, [spawnedEntity]() { - spawnedEntity->Smash(spawnedEntity->GetObjectID()); - }); + spawnedEntity->AddCallbackTimer(60, [spawnedEntity]() { + spawnedEntity->Smash(spawnedEntity->GetObjectID()); + }); - self->Smash(self->GetObjectID()); - } + self->Smash(self->GetObjectID()); + } } -void EnemyRoninSpawner::OnProximityUpdate(Entity* self, Entity* entering, std::string name, std::string status) -{ - if (entering->IsPlayer() && name == "ronin" && status == "ENTER" && !self->GetVar(u"hatching")) - { - StartHatching(self); +void EnemyRoninSpawner::OnProximityUpdate(Entity* self, Entity* entering, std::string name, std::string status) { + if (entering->IsPlayer() && name == "ronin" && status == "ENTER" && !self->GetVar(u"hatching")) { + StartHatching(self); - auto* skillComponent = self->GetComponent(); + auto* skillComponent = self->GetComponent(); - if (skillComponent != nullptr) - { - skillComponent->CalculateBehavior(305, 3568, LWOOBJID_EMPTY); - } - } + if (skillComponent != nullptr) { + skillComponent->CalculateBehavior(305, 3568, LWOOBJID_EMPTY); + } + } } -void EnemyRoninSpawner::OnHit(Entity* self, Entity* attacker) -{ - if (!self->GetVar(u"hatching")) - { - StartHatching(self); - } +void EnemyRoninSpawner::OnHit(Entity* self, Entity* attacker) { + if (!self->GetVar(u"hatching")) { + StartHatching(self); + } } -void EnemyRoninSpawner::StartHatching(Entity* self) -{ - self->SetVar(u"hatching", true); +void EnemyRoninSpawner::StartHatching(Entity* self) { + self->SetVar(u"hatching", true); - auto* renderComponent = self->GetComponent(); + auto* renderComponent = self->GetComponent(); - if (renderComponent != nullptr) - { - renderComponent->PlayEffect(2260, u"rebuild_medium", "WakeUpFX1"); - } + if (renderComponent != nullptr) { + renderComponent->PlayEffect(2260, u"rebuild_medium", "WakeUpFX1"); + } - self->AddTimer("hatchTime", 2); + self->AddTimer("hatchTime", 2); } diff --git a/dScripts/EnemyRoninSpawner.h b/dScripts/EnemyRoninSpawner.h index 0b14d0cf..02990f36 100644 --- a/dScripts/EnemyRoninSpawner.h +++ b/dScripts/EnemyRoninSpawner.h @@ -5,8 +5,8 @@ class EnemyRoninSpawner final : public CppScripts::Script { public: void OnStartup(Entity* self) override; void OnTimerDone(Entity* self, std::string timerName) override; - void OnProximityUpdate(Entity* self, Entity* entering, std::string name, std::string status) override; - void OnHit(Entity* self, Entity* attacker) override; - void StartHatching(Entity* self); + void OnProximityUpdate(Entity* self, Entity* entering, std::string name, std::string status) override; + void OnHit(Entity* self, Entity* attacker) override; + void StartHatching(Entity* self); }; diff --git a/dScripts/EnemySkeletonSpawner.cpp b/dScripts/EnemySkeletonSpawner.cpp index f8c89ec6..451fa1d5 100644 --- a/dScripts/EnemySkeletonSpawner.cpp +++ b/dScripts/EnemySkeletonSpawner.cpp @@ -3,86 +3,73 @@ #include "RenderComponent.h" #include "EntityManager.h" -void EnemySkeletonSpawner::OnStartup(Entity* self) -{ - self->SetProximityRadius(15, "ronin"); +void EnemySkeletonSpawner::OnStartup(Entity* self) { + self->SetProximityRadius(15, "ronin"); - auto* skillComponent = self->GetComponent(); + auto* skillComponent = self->GetComponent(); - if (skillComponent != nullptr) - { - skillComponent->CalculateBehavior(1127, 24812, LWOOBJID_EMPTY, true); - } + if (skillComponent != nullptr) { + skillComponent->CalculateBehavior(1127, 24812, LWOOBJID_EMPTY, true); + } } -void EnemySkeletonSpawner::OnTimerDone(Entity* self, std::string timerName) -{ - if (timerName == "hatchTime") - { - auto* renderComponent = self->GetComponent(); +void EnemySkeletonSpawner::OnTimerDone(Entity* self, std::string timerName) { + if (timerName == "hatchTime") { + auto* renderComponent = self->GetComponent(); - if (renderComponent != nullptr) - { - renderComponent->PlayEffect(644, u"create", "BurstFX1"); - } + if (renderComponent != nullptr) { + renderComponent->PlayEffect(644, u"create", "BurstFX1"); + } - EntityInfo info {}; - info.lot = 14024; - info.pos = self->GetPosition(); - info.rot = self->GetRotation(); - info.spawnerID = self->GetObjectID(); + EntityInfo info{}; + info.lot = 14024; + info.pos = self->GetPosition(); + info.rot = self->GetRotation(); + info.spawnerID = self->GetObjectID(); - auto* spawnedEntity = EntityManager::Instance()->CreateEntity(info); + auto* spawnedEntity = EntityManager::Instance()->CreateEntity(info); - if (spawnedEntity == nullptr) - { - return; - } + if (spawnedEntity == nullptr) { + return; + } - EntityManager::Instance()->ConstructEntity(spawnedEntity); + EntityManager::Instance()->ConstructEntity(spawnedEntity); - spawnedEntity->AddCallbackTimer(60, [spawnedEntity]() { - spawnedEntity->Smash(spawnedEntity->GetObjectID()); - }); + spawnedEntity->AddCallbackTimer(60, [spawnedEntity]() { + spawnedEntity->Smash(spawnedEntity->GetObjectID()); + }); - self->Smash(self->GetObjectID()); - } + self->Smash(self->GetObjectID()); + } } -void EnemySkeletonSpawner::OnProximityUpdate(Entity* self, Entity* entering, std::string name, std::string status) -{ - if (entering->IsPlayer() && name == "ronin" && status == "ENTER" && !self->GetVar(u"hatching")) - { - StartHatching(self); +void EnemySkeletonSpawner::OnProximityUpdate(Entity* self, Entity* entering, std::string name, std::string status) { + if (entering->IsPlayer() && name == "ronin" && status == "ENTER" && !self->GetVar(u"hatching")) { + StartHatching(self); - auto* skillComponent = self->GetComponent(); + auto* skillComponent = self->GetComponent(); - if (skillComponent != nullptr) - { - skillComponent->CalculateBehavior(305, 3568, LWOOBJID_EMPTY); - } - } + if (skillComponent != nullptr) { + skillComponent->CalculateBehavior(305, 3568, LWOOBJID_EMPTY); + } + } } -void EnemySkeletonSpawner::OnHit(Entity* self, Entity* attacker) -{ - if (!self->GetVar(u"hatching")) - { - StartHatching(self); - } +void EnemySkeletonSpawner::OnHit(Entity* self, Entity* attacker) { + if (!self->GetVar(u"hatching")) { + StartHatching(self); + } } -void EnemySkeletonSpawner::StartHatching(Entity* self) -{ - self->SetVar(u"hatching", true); +void EnemySkeletonSpawner::StartHatching(Entity* self) { + self->SetVar(u"hatching", true); - auto* renderComponent = self->GetComponent(); + auto* renderComponent = self->GetComponent(); - if (renderComponent != nullptr) - { - renderComponent->PlayEffect(9017, u"cast", "WakeUpFX1"); - renderComponent->PlayEffect(9018, u"burst", "WakeUpFX1"); - } + if (renderComponent != nullptr) { + renderComponent->PlayEffect(9017, u"cast", "WakeUpFX1"); + renderComponent->PlayEffect(9018, u"burst", "WakeUpFX1"); + } - self->AddTimer("hatchTime", 2); + self->AddTimer("hatchTime", 2); } diff --git a/dScripts/EnemySkeletonSpawner.h b/dScripts/EnemySkeletonSpawner.h index a4a212d2..16bbfdd9 100644 --- a/dScripts/EnemySkeletonSpawner.h +++ b/dScripts/EnemySkeletonSpawner.h @@ -5,8 +5,8 @@ class EnemySkeletonSpawner final : public CppScripts::Script { public: void OnStartup(Entity* self) override; void OnTimerDone(Entity* self, std::string timerName) override; - void OnProximityUpdate(Entity* self, Entity* entering, std::string name, std::string status) override; - void OnHit(Entity* self, Entity* attacker) override; - void StartHatching(Entity* self); + void OnProximityUpdate(Entity* self, Entity* entering, std::string name, std::string status) override; + void OnHit(Entity* self, Entity* attacker) override; + void StartHatching(Entity* self); }; diff --git a/dScripts/EnemySpiderSpawner.cpp b/dScripts/EnemySpiderSpawner.cpp index 98524ae1..96302a33 100644 --- a/dScripts/EnemySpiderSpawner.cpp +++ b/dScripts/EnemySpiderSpawner.cpp @@ -6,22 +6,22 @@ //---------------------------------------------- //--Initiate egg hatching on call //---------------------------------------------- -void EnemySpiderSpawner::OnFireEventServerSide(Entity *self, Entity *sender, std::string args, int32_t param1, - int32_t param2, int32_t param3) { +void EnemySpiderSpawner::OnFireEventServerSide(Entity* self, Entity* sender, std::string args, int32_t param1, + int32_t param2, int32_t param3) { if (args == "prepEgg") { // Highlight eggs about to hatch with Maelstrom effect GameMessages::SendPlayFXEffect(self->GetObjectID(), 2856, u"maelstrom", "test", LWOOBJID_EMPTY, 1.0f, 1.0f, true); - + // Make indestructible auto dest = static_cast(self->GetComponent(COMPONENT_TYPE_DESTROYABLE)); if (dest) { dest->SetFaction(-1); } EntityManager::Instance()->SerializeEntity(self); - + // Keep track of who prepped me self->SetI64(u"SpawnOwner", sender->GetObjectID()); - + } else if (args == "hatchEgg") { // Final countdown to pop self->AddTimer("StartSpawnTime", hatchTime); @@ -36,10 +36,10 @@ void EnemySpiderSpawner::OnTimerDone(Entity* self, std::string timerName) { SpawnSpiderling(self); } else if (timerName == "SpawnSpiderling") { GameMessages::SendPlayFXEffect(self->GetObjectID(), 644, u"create", "egg_puff_b", LWOOBJID_EMPTY, 1.0f, 1.0f, true); - + //TODO: set the aggro radius larger - EntityInfo info {}; + EntityInfo info{}; info.lot = 16197; info.pos = self->GetPosition(); info.spawner = nullptr; @@ -59,7 +59,7 @@ void EnemySpiderSpawner::OnTimerDone(Entity* self, std::string timerName) { } self->ScheduleKillAfterUpdate(); - } + } } //-------------------------------------------------------------- diff --git a/dScripts/EnemySpiderSpawner.h b/dScripts/EnemySpiderSpawner.h index def08ab1..f850a6eb 100644 --- a/dScripts/EnemySpiderSpawner.h +++ b/dScripts/EnemySpiderSpawner.h @@ -16,8 +16,8 @@ class EnemySpiderSpawner final : public CppScripts::Script { public: - void OnFireEventServerSide(Entity *self, Entity *sender, std::string args, int32_t param1, int32_t param2, - int32_t param3) override; + void OnFireEventServerSide(Entity* self, Entity* sender, std::string args, int32_t param1, int32_t param2, + int32_t param3) override; void OnTimerDone(Entity* self, std::string timerName) override; private: diff --git a/dScripts/ExplodingAsset.cpp b/dScripts/ExplodingAsset.cpp index b4bd6913..46ff1522 100644 --- a/dScripts/ExplodingAsset.cpp +++ b/dScripts/ExplodingAsset.cpp @@ -26,7 +26,7 @@ void ExplodingAsset::OnHit(Entity* self, Entity* attacker) { if (destroyable == nullptr) { continue; } - + destroyable->Smash(attacker->GetObjectID()); } } @@ -49,26 +49,25 @@ void ExplodingAsset::OnHit(Entity* self, Entity* attacker) { // Progress all scripted missions related to this asset auto* missionComponent = attacker->GetComponent(); if (missionComponent != nullptr) { - if (missionID != 0) { - missionComponent->ForceProgressValue(missionID, - static_cast(MissionTaskType::MISSION_TASK_TYPE_SCRIPT), - self->GetLOT(), false); - } + if (missionID != 0) { + missionComponent->ForceProgressValue(missionID, + static_cast(MissionTaskType::MISSION_TASK_TYPE_SCRIPT), + self->GetLOT(), false); + } - if (!achievementIDs.empty()) { - for (const auto& achievementID : GeneralUtils::SplitString(achievementIDs, u'_')) { - missionComponent->ForceProgressValue(std::stoi(GeneralUtils::UTF16ToWTF8(achievementID)), - static_cast(MissionTaskType::MISSION_TASK_TYPE_SCRIPT), - self->GetLOT()); - } - } + if (!achievementIDs.empty()) { + for (const auto& achievementID : GeneralUtils::SplitString(achievementIDs, u'_')) { + missionComponent->ForceProgressValue(std::stoi(GeneralUtils::UTF16ToWTF8(achievementID)), + static_cast(MissionTaskType::MISSION_TASK_TYPE_SCRIPT), + self->GetLOT()); + } + } } self->ScheduleKillAfterUpdate(); } -void ExplodingAsset::OnProximityUpdate(Entity* self, Entity* entering, std::string name, std::string status) -{ +void ExplodingAsset::OnProximityUpdate(Entity* self, Entity* entering, std::string name, std::string status) { /* if msg.objId:BelongsToFaction{factionID = 1}.bIsInFaction then if (msg.status == "ENTER") then @@ -94,21 +93,17 @@ void ExplodingAsset::OnProximityUpdate(Entity* self, Entity* entering, std::stri if (!std::count(factions.begin(), factions.end(), 1)) return; - if (status == "ENTER") - { + if (status == "ENTER") { GameMessages::SendPlayAnimation(self, u"bounce"); GameMessages::SendPlayFXEffect(self, -1, u"anim", "bouncin", LWOOBJID_EMPTY, 1, 1, true); self->SetVar(u"playersNearChest", self->GetVar(u"playersNearChest") + 1); - } - else if (status == "LEAVE") - { + } else if (status == "LEAVE") { self->SetVar(u"playersNearChest", self->GetVar(u"playersNearChest") - 1); - if (self->GetVar(u"playersNearChest") < 1) - { + if (self->GetVar(u"playersNearChest") < 1) { GameMessages::SendPlayAnimation(self, u"idle"); GameMessages::SendStopFXEffect(self, true, "bouncin"); self->SetVar(u"playersNearChest", 0); } } -} \ No newline at end of file +} diff --git a/dScripts/ExplodingAsset.h b/dScripts/ExplodingAsset.h index bd2c2544..9b97ecc7 100644 --- a/dScripts/ExplodingAsset.h +++ b/dScripts/ExplodingAsset.h @@ -7,4 +7,4 @@ public: void OnStartup(Entity* self); void OnHit(Entity* self, Entity* attacker); void OnProximityUpdate(Entity* self, Entity* entering, std::string name, std::string status); -}; \ No newline at end of file +}; diff --git a/dScripts/FallingTile.cpp b/dScripts/FallingTile.cpp index 2dd8c7bc..7804c8bc 100644 --- a/dScripts/FallingTile.cpp +++ b/dScripts/FallingTile.cpp @@ -2,67 +2,54 @@ #include "MovingPlatformComponent.h" #include "GameMessages.h" -void FallingTile::OnStartup(Entity* self) -{ - auto* movingPlatfromComponent = self->GetComponent(); +void FallingTile::OnStartup(Entity* self) { + auto* movingPlatfromComponent = self->GetComponent(); - if (movingPlatfromComponent == nullptr) - { - return; - } + if (movingPlatfromComponent == nullptr) { + return; + } - movingPlatfromComponent->SetSerialized(true); + movingPlatfromComponent->SetSerialized(true); } -void FallingTile::OnCollisionPhantom(Entity* self, Entity* target) -{ - if (self->GetVar(u"AboutToFall")) - { - return; - } +void FallingTile::OnCollisionPhantom(Entity* self, Entity* target) { + if (self->GetVar(u"AboutToFall")) { + return; + } - self->AddTimer("flipTime", 0.75f); + self->AddTimer("flipTime", 0.75f); - self->SetVar(u"AboutToFall", true); + self->SetVar(u"AboutToFall", true); - self->SetNetworkVar(u"startEffect", 2); + self->SetNetworkVar(u"startEffect", 2); } -void FallingTile::OnWaypointReached(Entity* self, uint32_t waypointIndex) -{ - if (waypointIndex == 1) - { - } - else if (waypointIndex == 0) - { - } +void FallingTile::OnWaypointReached(Entity* self, uint32_t waypointIndex) { + if (waypointIndex == 1) { + } else if (waypointIndex == 0) { + } } -void FallingTile::OnTimerDone(Entity* self, std::string timerName) -{ - auto* movingPlatfromComponent = self->GetComponent(); +void FallingTile::OnTimerDone(Entity* self, std::string timerName) { + auto* movingPlatfromComponent = self->GetComponent(); - if (movingPlatfromComponent == nullptr) - { - return; - } + if (movingPlatfromComponent == nullptr) { + return; + } - if (timerName == "flipTime") - { - self->AddTimer("flipBack", 2.0f); + if (timerName == "flipTime") { + self->AddTimer("flipBack", 2.0f); - self->SetNetworkVar(u"stopEffect", 3); + self->SetNetworkVar(u"stopEffect", 3); - movingPlatfromComponent->GotoWaypoint(1); + movingPlatfromComponent->GotoWaypoint(1); - GameMessages::SendPlayFXEffect(self->GetObjectID(), -1, u"down", "down"); - } - else if (timerName == "flipBack") - { - self->SetVar(u"AboutToFall", false); + GameMessages::SendPlayFXEffect(self->GetObjectID(), -1, u"down", "down"); + } else if (timerName == "flipBack") { + self->SetVar(u"AboutToFall", false); - movingPlatfromComponent->GotoWaypoint(0); - - GameMessages::SendPlayFXEffect(self->GetObjectID(), -1, u"up", "up"); - } + movingPlatfromComponent->GotoWaypoint(0); + + GameMessages::SendPlayFXEffect(self->GetObjectID(), -1, u"up", "up"); + } } diff --git a/dScripts/FallingTile.h b/dScripts/FallingTile.h index 073fc403..bac1c73b 100644 --- a/dScripts/FallingTile.h +++ b/dScripts/FallingTile.h @@ -5,7 +5,7 @@ class FallingTile : public CppScripts::Script { public: void OnStartup(Entity* self) override; - void OnCollisionPhantom(Entity* self, Entity* target) override; - void OnWaypointReached(Entity* self, uint32_t waypointIndex) override; - void OnTimerDone(Entity* self, std::string timerName) override; -}; \ No newline at end of file + void OnCollisionPhantom(Entity* self, Entity* target) override; + void OnWaypointReached(Entity* self, uint32_t waypointIndex) override; + void OnTimerDone(Entity* self, std::string timerName) override; +}; diff --git a/dScripts/FireFirstSkillonStartup.cpp b/dScripts/FireFirstSkillonStartup.cpp index da1b420e..cd0d94f2 100644 --- a/dScripts/FireFirstSkillonStartup.cpp +++ b/dScripts/FireFirstSkillonStartup.cpp @@ -5,20 +5,20 @@ #include "CDObjectSkillsTable.h" void FireFirstSkillonStartup::OnStartup(Entity* self) { - auto skillComponent = self->GetComponent(); - if (!skillComponent) return; + auto skillComponent = self->GetComponent(); + if (!skillComponent) return; - // Get the skill IDs of this object. - CDObjectSkillsTable* skillsTable = CDClientManager::Instance()->GetTable("ObjectSkills"); - std::vector skills = skillsTable->Query([=](CDObjectSkills entry) {return (entry.objectTemplate == self->GetLOT()); }); + // Get the skill IDs of this object. + CDObjectSkillsTable* skillsTable = CDClientManager::Instance()->GetTable("ObjectSkills"); + std::vector skills = skillsTable->Query([=](CDObjectSkills entry) {return (entry.objectTemplate == self->GetLOT()); }); - // For each skill, cast it with the associated behavior ID. - for (auto skill : skills) { - CDSkillBehaviorTable* skillBehaviorTable = CDClientManager::Instance()->GetTable("SkillBehavior"); + // For each skill, cast it with the associated behavior ID. + for (auto skill : skills) { + CDSkillBehaviorTable* skillBehaviorTable = CDClientManager::Instance()->GetTable("SkillBehavior"); CDSkillBehavior behaviorData = skillBehaviorTable->GetSkillByID(skill.skillID); - // Should parent entity be null, make the originator self. - const auto target = self->GetParentEntity() ? self->GetParentEntity()->GetObjectID() : self->GetObjectID(); - skillComponent->CalculateBehavior(skill.skillID, behaviorData.behaviorID, LWOOBJID_EMPTY, false, false, target); - } -} \ No newline at end of file + // Should parent entity be null, make the originator self. + const auto target = self->GetParentEntity() ? self->GetParentEntity()->GetObjectID() : self->GetObjectID(); + skillComponent->CalculateBehavior(skill.skillID, behaviorData.behaviorID, LWOOBJID_EMPTY, false, false, target); + } +} diff --git a/dScripts/FireFirstSkillonStartup.h b/dScripts/FireFirstSkillonStartup.h index ad182e70..6b10f362 100644 --- a/dScripts/FireFirstSkillonStartup.h +++ b/dScripts/FireFirstSkillonStartup.h @@ -5,8 +5,8 @@ #include "CppScripts.h" class FireFirstSkillonStartup : public CppScripts::Script { - public: - void OnStartup(Entity* self) override; +public: + void OnStartup(Entity* self) override; }; #endif //!__FIREFIRSTSKILLONSTARTUP__H__ diff --git a/dScripts/FlameJetServer.cpp b/dScripts/FlameJetServer.cpp index 936f2a94..771dd841 100644 --- a/dScripts/FlameJetServer.cpp +++ b/dScripts/FlameJetServer.cpp @@ -2,56 +2,46 @@ #include "SkillComponent.h" #include "GameMessages.h" -void FlameJetServer::OnStartup(Entity* self) -{ - if (self->GetVar(u"NotActive")) - { - return; - } +void FlameJetServer::OnStartup(Entity* self) { + if (self->GetVar(u"NotActive")) { + return; + } - self->SetNetworkVar(u"FlameOn", true); + self->SetNetworkVar(u"FlameOn", true); } -void FlameJetServer::OnCollisionPhantom(Entity* self, Entity* target) -{ - if (!target->IsPlayer()) - { - return; - } +void FlameJetServer::OnCollisionPhantom(Entity* self, Entity* target) { + if (!target->IsPlayer()) { + return; + } - if (!self->GetNetworkVar(u"FlameOn")) - { - return; - } + if (!self->GetNetworkVar(u"FlameOn")) { + return; + } - auto* skillComponent = target->GetComponent(); + auto* skillComponent = target->GetComponent(); - if (skillComponent == nullptr) - { - return; - } + if (skillComponent == nullptr) { + return; + } - skillComponent->CalculateBehavior(726, 11723, target->GetObjectID(), true); + skillComponent->CalculateBehavior(726, 11723, target->GetObjectID(), true); - auto dir = target->GetRotation().GetForwardVector(); + auto dir = target->GetRotation().GetForwardVector(); - dir.y = 25; - dir.x = -dir.x * 15; - dir.z = -dir.z * 15; + dir.y = 25; + dir.x = -dir.x * 15; + dir.z = -dir.z * 15; - GameMessages::SendKnockback(target->GetObjectID(), self->GetObjectID(), self->GetObjectID(), 1000, dir); + GameMessages::SendKnockback(target->GetObjectID(), self->GetObjectID(), self->GetObjectID(), 1000, dir); } -void FlameJetServer::OnFireEventServerSide(Entity *self, Entity *sender, std::string args, int32_t param1, int32_t param2, int32_t param3) -{ - Game::logger->Log("FlameJetServer::OnFireEventServerSide", "Event: %s", args.c_str()); +void FlameJetServer::OnFireEventServerSide(Entity* self, Entity* sender, std::string args, int32_t param1, int32_t param2, int32_t param3) { + Game::logger->Log("FlameJetServer::OnFireEventServerSide", "Event: %s", args.c_str()); - if (args == "OnActivated") - { - self->SetNetworkVar(u"FlameOn", false); - } - else if (args == "OnDectivated") - { - self->SetNetworkVar(u"FlameOn", true); - } + if (args == "OnActivated") { + self->SetNetworkVar(u"FlameOn", false); + } else if (args == "OnDectivated") { + self->SetNetworkVar(u"FlameOn", true); + } } diff --git a/dScripts/FlameJetServer.h b/dScripts/FlameJetServer.h index 4f815d63..e8123c43 100644 --- a/dScripts/FlameJetServer.h +++ b/dScripts/FlameJetServer.h @@ -5,6 +5,6 @@ class FlameJetServer : public CppScripts::Script { public: void OnStartup(Entity* self) override; - void OnCollisionPhantom(Entity* self, Entity* target) override; - void OnFireEventServerSide(Entity *self, Entity *sender, std::string args, int32_t param1, int32_t param2, int32_t param3) override; -}; \ No newline at end of file + void OnCollisionPhantom(Entity* self, Entity* target) override; + void OnFireEventServerSide(Entity* self, Entity* sender, std::string args, int32_t param1, int32_t param2, int32_t param3) override; +}; diff --git a/dScripts/ForceVolumeServer.cpp b/dScripts/ForceVolumeServer.cpp index e9320527..fbaad6ee 100644 --- a/dScripts/ForceVolumeServer.cpp +++ b/dScripts/ForceVolumeServer.cpp @@ -2,21 +2,20 @@ #include "PhantomPhysicsComponent.h" #include "EntityManager.h" -void ForceVolumeServer::OnStartup(Entity* self) -{ - auto* phantomPhysicsComponent = self->GetComponent(); - - if (phantomPhysicsComponent == nullptr) return; +void ForceVolumeServer::OnStartup(Entity* self) { + auto* phantomPhysicsComponent = self->GetComponent(); - const auto forceAmount = self->GetVar(u"ForceAmt"); - const auto forceX = self->GetVar(u"ForceX"); - const auto forceY = self->GetVar(u"ForceY"); - const auto forceZ = self->GetVar(u"ForceZ"); + if (phantomPhysicsComponent == nullptr) return; - phantomPhysicsComponent->SetEffectType(0); // PUSH - phantomPhysicsComponent->SetDirectionalMultiplier(forceAmount); - phantomPhysicsComponent->SetDirection({ forceX, forceY, forceZ }); - phantomPhysicsComponent->SetPhysicsEffectActive(true); + const auto forceAmount = self->GetVar(u"ForceAmt"); + const auto forceX = self->GetVar(u"ForceX"); + const auto forceY = self->GetVar(u"ForceY"); + const auto forceZ = self->GetVar(u"ForceZ"); - EntityManager::Instance()->SerializeEntity(self); + phantomPhysicsComponent->SetEffectType(0); // PUSH + phantomPhysicsComponent->SetDirectionalMultiplier(forceAmount); + phantomPhysicsComponent->SetDirection({ forceX, forceY, forceZ }); + phantomPhysicsComponent->SetPhysicsEffectActive(true); + + EntityManager::Instance()->SerializeEntity(self); } diff --git a/dScripts/FountainOfImagination.cpp b/dScripts/FountainOfImagination.cpp index 43351e18..6560e1cf 100644 --- a/dScripts/FountainOfImagination.cpp +++ b/dScripts/FountainOfImagination.cpp @@ -2,14 +2,14 @@ #include "dCommonVars.h" #include "Entity.h" -void FountainOfImagination::OnStartup(Entity *self) { - self->SetVar(u"numCycles", 6); - self->SetVar(u"secPerCycle", 30.0f); - self->SetVar(u"delayToFirstCycle", 1.5f); - self->SetVar(u"deathDelay", 30.0f); - self->SetVar(u"numberOfPowerups", 5); - self->SetVar(u"lootLOT", 935); +void FountainOfImagination::OnStartup(Entity* self) { + self->SetVar(u"numCycles", 6); + self->SetVar(u"secPerCycle", 30.0f); + self->SetVar(u"delayToFirstCycle", 1.5f); + self->SetVar(u"deathDelay", 30.0f); + self->SetVar(u"numberOfPowerups", 5); + self->SetVar(u"lootLOT", 935); - // Initiate the actual script - OnTemplateStartup(self); + // Initiate the actual script + OnTemplateStartup(self); } diff --git a/dScripts/FountainOfImagination.h b/dScripts/FountainOfImagination.h index 6ad0becd..e477a026 100644 --- a/dScripts/FountainOfImagination.h +++ b/dScripts/FountainOfImagination.h @@ -2,5 +2,5 @@ #include "ScriptedPowerupSpawner.h" class FountainOfImagination : public ScriptedPowerupSpawner { - void OnStartup(Entity* self) override; + void OnStartup(Entity* self) override; }; diff --git a/dScripts/FvBounceOverWall.cpp b/dScripts/FvBounceOverWall.cpp index 1c85ffbd..294c11f0 100644 --- a/dScripts/FvBounceOverWall.cpp +++ b/dScripts/FvBounceOverWall.cpp @@ -2,9 +2,9 @@ #include "MissionComponent.h" void FvBounceOverWall::OnCollisionPhantom(Entity* self, Entity* target) { - auto missionComponent = target->GetComponent(); - if (missionComponent == nullptr) return; + auto missionComponent = target->GetComponent(); + if (missionComponent == nullptr) return; - // We force progress here to the Gate Crasher mission due to an overlap in LOTs with the 'Shark Bite' missions. - missionComponent->ForceProgress(GateCrasherMissionId, GateCrasherMissionUid, 1); -} \ No newline at end of file + // We force progress here to the Gate Crasher mission due to an overlap in LOTs with the 'Shark Bite' missions. + missionComponent->ForceProgress(GateCrasherMissionId, GateCrasherMissionUid, 1); +} diff --git a/dScripts/FvBounceOverWall.h b/dScripts/FvBounceOverWall.h index 875122c9..ee8c8b3a 100644 --- a/dScripts/FvBounceOverWall.h +++ b/dScripts/FvBounceOverWall.h @@ -3,20 +3,20 @@ class FvBounceOverWall : public CppScripts::Script { - /** - * @brief When a collision has been made with self this method is called. - * - * @param self The Entity that called this function. - * @param target The target Entity of self. - */ - void OnCollisionPhantom(Entity* self, Entity* target) override; + /** + * @brief When a collision has been made with self this method is called. + * + * @param self The Entity that called this function. + * @param target The target Entity of self. + */ + void OnCollisionPhantom(Entity* self, Entity* target) override; private: - /** - * MissionId for the Gate Crasher mission. - */ - int32_t GateCrasherMissionId = 849; - /** - * MissionUid for the Gate Crasher mission. - */ - int32_t GateCrasherMissionUid = 1241; -}; \ No newline at end of file + /** + * MissionId for the Gate Crasher mission. + */ + int32_t GateCrasherMissionId = 849; + /** + * MissionUid for the Gate Crasher mission. + */ + int32_t GateCrasherMissionUid = 1241; +}; diff --git a/dScripts/FvBrickPuzzleServer.cpp b/dScripts/FvBrickPuzzleServer.cpp index df6cc395..cea6146b 100644 --- a/dScripts/FvBrickPuzzleServer.cpp +++ b/dScripts/FvBrickPuzzleServer.cpp @@ -4,79 +4,65 @@ #include "Spawner.h" #include "RebuildComponent.h" -void FvBrickPuzzleServer::OnStartup(Entity* self) -{ - const auto myGroup = GeneralUtils::UTF16ToWTF8(self->GetVar(u"spawner_name")); +void FvBrickPuzzleServer::OnStartup(Entity* self) { + const auto myGroup = GeneralUtils::UTF16ToWTF8(self->GetVar(u"spawner_name")); - int32_t pipeNum = 0; - if (!GeneralUtils::TryParse(myGroup.substr(10, 1), pipeNum)) - { - return; - } + int32_t pipeNum = 0; + if (!GeneralUtils::TryParse(myGroup.substr(10, 1), pipeNum)) { + return; + } - if (pipeNum != 1) - { - self->AddTimer("reset", 30); - } + if (pipeNum != 1) { + self->AddTimer("reset", 30); + } } -void FvBrickPuzzleServer::OnDie(Entity* self, Entity* killer) -{ - const auto myGroup = GeneralUtils::UTF16ToWTF8(self->GetVar(u"spawner_name")); +void FvBrickPuzzleServer::OnDie(Entity* self, Entity* killer) { + const auto myGroup = GeneralUtils::UTF16ToWTF8(self->GetVar(u"spawner_name")); - int32_t pipeNum = 0; - if (!GeneralUtils::TryParse(myGroup.substr(10, 1), pipeNum)) - { - return; - } + int32_t pipeNum = 0; + if (!GeneralUtils::TryParse(myGroup.substr(10, 1), pipeNum)) { + return; + } - const auto pipeGroup = myGroup.substr(0, 10); + const auto pipeGroup = myGroup.substr(0, 10); - const auto nextPipeNum = pipeNum + 1; + const auto nextPipeNum = pipeNum + 1; - const auto samePipeSpawners = dZoneManager::Instance()->GetSpawnersByName(myGroup); + const auto samePipeSpawners = dZoneManager::Instance()->GetSpawnersByName(myGroup); - if (!samePipeSpawners.empty()) - { - samePipeSpawners[0]->SoftReset(); + if (!samePipeSpawners.empty()) { + samePipeSpawners[0]->SoftReset(); - samePipeSpawners[0]->Deactivate(); - } + samePipeSpawners[0]->Deactivate(); + } - if (killer != nullptr && killer->IsPlayer()) - { - const auto nextPipe = pipeGroup + std::to_string(nextPipeNum); + if (killer != nullptr && killer->IsPlayer()) { + const auto nextPipe = pipeGroup + std::to_string(nextPipeNum); - const auto nextPipeSpawners = dZoneManager::Instance()->GetSpawnersByName(nextPipe); + const auto nextPipeSpawners = dZoneManager::Instance()->GetSpawnersByName(nextPipe); - if (!nextPipeSpawners.empty()) - { - nextPipeSpawners[0]->Activate(); - } - } - else - { - const auto nextPipe = pipeGroup + "1"; + if (!nextPipeSpawners.empty()) { + nextPipeSpawners[0]->Activate(); + } + } else { + const auto nextPipe = pipeGroup + "1"; - const auto firstPipeSpawners = dZoneManager::Instance()->GetSpawnersByName(nextPipe); + const auto firstPipeSpawners = dZoneManager::Instance()->GetSpawnersByName(nextPipe); + + if (!firstPipeSpawners.empty()) { + firstPipeSpawners[0]->Activate(); + } + } - if (!firstPipeSpawners.empty()) - { - firstPipeSpawners[0]->Activate(); - } - } - } -void FvBrickPuzzleServer::OnTimerDone(Entity* self, std::string timerName) -{ - if (timerName == "reset") - { - auto* rebuildComponent = self->GetComponent(); +void FvBrickPuzzleServer::OnTimerDone(Entity* self, std::string timerName) { + if (timerName == "reset") { + auto* rebuildComponent = self->GetComponent(); - if (rebuildComponent != nullptr && rebuildComponent->GetState() == REBUILD_OPEN) - { - self->Smash(self->GetObjectID(), SILENT); - } - } + if (rebuildComponent != nullptr && rebuildComponent->GetState() == REBUILD_OPEN) { + self->Smash(self->GetObjectID(), SILENT); + } + } } diff --git a/dScripts/FvBrickPuzzleServer.h b/dScripts/FvBrickPuzzleServer.h index f5eceaee..4297100e 100644 --- a/dScripts/FvBrickPuzzleServer.h +++ b/dScripts/FvBrickPuzzleServer.h @@ -1,10 +1,10 @@ #pragma once #include "CppScripts.h" -class FvBrickPuzzleServer : public CppScripts::Script +class FvBrickPuzzleServer : public CppScripts::Script { public: void OnStartup(Entity* self) override; void OnDie(Entity* self, Entity* killer) override; void OnTimerDone(Entity* self, std::string timerName) override; -}; \ No newline at end of file +}; diff --git a/dScripts/FvCandle.cpp b/dScripts/FvCandle.cpp index 63f90f0b..efd717ee 100644 --- a/dScripts/FvCandle.cpp +++ b/dScripts/FvCandle.cpp @@ -2,7 +2,7 @@ #include "MissionComponent.h" #include "RenderComponent.h" -std::vector FvCandle::m_Missions = {850, 1431, 1529, 1566, 1603}; +std::vector FvCandle::m_Missions = { 850, 1431, 1529, 1566, 1603 }; void FvCandle::OnStartup(Entity* self) { auto* render = static_cast(self->GetComponent(COMPONENT_TYPE_RENDER)); @@ -25,13 +25,11 @@ void FvCandle::BlowOutCandle(Entity* self, Entity* blower) { auto* render = static_cast(self->GetComponent(COMPONENT_TYPE_RENDER)); if (render == nullptr) return; - + auto* missionComponent = blower->GetComponent(); - if (missionComponent != nullptr) - { - for (const auto mission : m_Missions) - { + if (missionComponent != nullptr) { + for (const auto mission : m_Missions) { missionComponent->ForceProgressTaskType(mission, 1, 1); } } @@ -54,4 +52,4 @@ void FvCandle::OnTimerDone(Entity* self, std::string timerName) { render->StopEffect("candle_smoke", false); render->PlayEffect(2108, u"create", "candle_light", LWOOBJID_EMPTY, 1.0f, 1.0f, true); -} \ No newline at end of file +} diff --git a/dScripts/FvCandle.h b/dScripts/FvCandle.h index 362d2a05..e0cd4e04 100644 --- a/dScripts/FvCandle.h +++ b/dScripts/FvCandle.h @@ -1,7 +1,7 @@ #pragma once #include "CppScripts.h" -class FvCandle : public CppScripts::Script +class FvCandle : public CppScripts::Script { public: void OnStartup(Entity* self); @@ -11,4 +11,4 @@ private: void BlowOutCandle(Entity* self, Entity* blower); static std::vector m_Missions; -}; \ No newline at end of file +}; diff --git a/dScripts/FvConsoleLeftQuickbuild.cpp b/dScripts/FvConsoleLeftQuickbuild.cpp index ef281f15..b998b9ec 100644 --- a/dScripts/FvConsoleLeftQuickbuild.cpp +++ b/dScripts/FvConsoleLeftQuickbuild.cpp @@ -2,57 +2,46 @@ #include "EntityManager.h" #include "GameMessages.h" -void FvConsoleLeftQuickbuild::OnStartup(Entity* self) -{ - self->SetVar(u"IAmBuilt", false); - self->SetVar(u"AmActive", false); +void FvConsoleLeftQuickbuild::OnStartup(Entity* self) { + self->SetVar(u"IAmBuilt", false); + self->SetVar(u"AmActive", false); } -void FvConsoleLeftQuickbuild::OnRebuildNotifyState(Entity* self, eRebuildState state) -{ - if (state == REBUILD_COMPLETED) - { - self->SetVar(u"IAmBuilt", true); - - const auto objects = EntityManager::Instance()->GetEntitiesInGroup("Facility"); +void FvConsoleLeftQuickbuild::OnRebuildNotifyState(Entity* self, eRebuildState state) { + if (state == REBUILD_COMPLETED) { + self->SetVar(u"IAmBuilt", true); - if (!objects.empty()) - { - objects[0]->NotifyObject(self, "ConsoleLeftUp"); - } - } - else if (state == REBUILD_RESETTING) - { - self->SetVar(u"IAmBuilt", false); - self->SetVar(u"AmActive", false); - - const auto objects = EntityManager::Instance()->GetEntitiesInGroup("Facility"); + const auto objects = EntityManager::Instance()->GetEntitiesInGroup("Facility"); - if (!objects.empty()) - { - objects[0]->NotifyObject(self, "ConsoleLeftDown"); - } - } + if (!objects.empty()) { + objects[0]->NotifyObject(self, "ConsoleLeftUp"); + } + } else if (state == REBUILD_RESETTING) { + self->SetVar(u"IAmBuilt", false); + self->SetVar(u"AmActive", false); + + const auto objects = EntityManager::Instance()->GetEntitiesInGroup("Facility"); + + if (!objects.empty()) { + objects[0]->NotifyObject(self, "ConsoleLeftDown"); + } + } } -void FvConsoleLeftQuickbuild::OnUse(Entity* self, Entity* user) -{ - if (self->GetVar(u"AmActive")) - { - return; - } +void FvConsoleLeftQuickbuild::OnUse(Entity* self, Entity* user) { + if (self->GetVar(u"AmActive")) { + return; + } - if (self->GetVar(u"IAmBuilt")) - { - self->SetVar(u"AmActive", true); + if (self->GetVar(u"IAmBuilt")) { + self->SetVar(u"AmActive", true); - const auto objects = EntityManager::Instance()->GetEntitiesInGroup("Facility"); + const auto objects = EntityManager::Instance()->GetEntitiesInGroup("Facility"); - if (!objects.empty()) - { - objects[0]->NotifyObject(self, "ConsoleLeftActive"); - } - } + if (!objects.empty()) { + objects[0]->NotifyObject(self, "ConsoleLeftActive"); + } + } - GameMessages::SendTerminateInteraction(user->GetObjectID(), FROM_INTERACTION, self->GetObjectID()); + GameMessages::SendTerminateInteraction(user->GetObjectID(), FROM_INTERACTION, self->GetObjectID()); } diff --git a/dScripts/FvConsoleLeftQuickbuild.h b/dScripts/FvConsoleLeftQuickbuild.h index 8c796e0f..bbdea27e 100644 --- a/dScripts/FvConsoleLeftQuickbuild.h +++ b/dScripts/FvConsoleLeftQuickbuild.h @@ -1,10 +1,10 @@ #pragma once #include "CppScripts.h" -class FvConsoleLeftQuickbuild : public CppScripts::Script +class FvConsoleLeftQuickbuild : public CppScripts::Script { public: void OnStartup(Entity* self) override; void OnRebuildNotifyState(Entity* self, eRebuildState state) override; void OnUse(Entity* self, Entity* user) override; -}; \ No newline at end of file +}; diff --git a/dScripts/FvConsoleRightQuickbuild.cpp b/dScripts/FvConsoleRightQuickbuild.cpp index 0bf9849a..ea047cd8 100644 --- a/dScripts/FvConsoleRightQuickbuild.cpp +++ b/dScripts/FvConsoleRightQuickbuild.cpp @@ -2,57 +2,46 @@ #include "EntityManager.h" #include "GameMessages.h" -void FvConsoleRightQuickbuild::OnStartup(Entity* self) -{ - self->SetVar(u"IAmBuilt", false); - self->SetVar(u"AmActive", false); +void FvConsoleRightQuickbuild::OnStartup(Entity* self) { + self->SetVar(u"IAmBuilt", false); + self->SetVar(u"AmActive", false); } -void FvConsoleRightQuickbuild::OnRebuildNotifyState(Entity* self, eRebuildState state) -{ - if (state == REBUILD_COMPLETED) - { - self->SetVar(u"IAmBuilt", true); - - const auto objects = EntityManager::Instance()->GetEntitiesInGroup("Facility"); +void FvConsoleRightQuickbuild::OnRebuildNotifyState(Entity* self, eRebuildState state) { + if (state == REBUILD_COMPLETED) { + self->SetVar(u"IAmBuilt", true); - if (!objects.empty()) - { - objects[0]->NotifyObject(self, "ConsoleRightUp"); - } - } - else if (state == REBUILD_RESETTING) - { - self->SetVar(u"IAmBuilt", false); - self->SetVar(u"AmActive", false); - - const auto objects = EntityManager::Instance()->GetEntitiesInGroup("Facility"); + const auto objects = EntityManager::Instance()->GetEntitiesInGroup("Facility"); - if (!objects.empty()) - { - objects[0]->NotifyObject(self, "ConsoleRightDown"); - } - } + if (!objects.empty()) { + objects[0]->NotifyObject(self, "ConsoleRightUp"); + } + } else if (state == REBUILD_RESETTING) { + self->SetVar(u"IAmBuilt", false); + self->SetVar(u"AmActive", false); + + const auto objects = EntityManager::Instance()->GetEntitiesInGroup("Facility"); + + if (!objects.empty()) { + objects[0]->NotifyObject(self, "ConsoleRightDown"); + } + } } -void FvConsoleRightQuickbuild::OnUse(Entity* self, Entity* user) -{ - if (self->GetVar(u"AmActive")) - { - return; - } +void FvConsoleRightQuickbuild::OnUse(Entity* self, Entity* user) { + if (self->GetVar(u"AmActive")) { + return; + } - if (self->GetVar(u"IAmBuilt")) - { - self->SetVar(u"AmActive", true); + if (self->GetVar(u"IAmBuilt")) { + self->SetVar(u"AmActive", true); - const auto objects = EntityManager::Instance()->GetEntitiesInGroup("Facility"); + const auto objects = EntityManager::Instance()->GetEntitiesInGroup("Facility"); - if (!objects.empty()) - { - objects[0]->NotifyObject(self, "ConsoleRightActive"); - } - } + if (!objects.empty()) { + objects[0]->NotifyObject(self, "ConsoleRightActive"); + } + } - GameMessages::SendTerminateInteraction(user->GetObjectID(), FROM_INTERACTION, self->GetObjectID()); + GameMessages::SendTerminateInteraction(user->GetObjectID(), FROM_INTERACTION, self->GetObjectID()); } diff --git a/dScripts/FvConsoleRightQuickbuild.h b/dScripts/FvConsoleRightQuickbuild.h index cd0f4a04..fab8c814 100644 --- a/dScripts/FvConsoleRightQuickbuild.h +++ b/dScripts/FvConsoleRightQuickbuild.h @@ -1,10 +1,10 @@ #pragma once #include "CppScripts.h" -class FvConsoleRightQuickbuild : public CppScripts::Script +class FvConsoleRightQuickbuild : public CppScripts::Script { public: void OnStartup(Entity* self) override; void OnRebuildNotifyState(Entity* self, eRebuildState state) override; void OnUse(Entity* self, Entity* user) override; -}; \ No newline at end of file +}; diff --git a/dScripts/FvDragonSmashingGolemQb.cpp b/dScripts/FvDragonSmashingGolemQb.cpp index 6a88d9a0..a9d38aa5 100644 --- a/dScripts/FvDragonSmashingGolemQb.cpp +++ b/dScripts/FvDragonSmashingGolemQb.cpp @@ -2,35 +2,29 @@ #include "GameMessages.h" #include "EntityManager.h" -void FvDragonSmashingGolemQb::OnStartup(Entity* self) -{ - self->AddTimer("GolemBreakTimer", 10.5f); +void FvDragonSmashingGolemQb::OnStartup(Entity* self) { + self->AddTimer("GolemBreakTimer", 10.5f); } -void FvDragonSmashingGolemQb::OnTimerDone(Entity* self, std::string timerName) -{ - if (timerName == "GolemBreakTimer") - { - self->Smash(); - } +void FvDragonSmashingGolemQb::OnTimerDone(Entity* self, std::string timerName) { + if (timerName == "GolemBreakTimer") { + self->Smash(); + } } -void FvDragonSmashingGolemQb::OnRebuildNotifyState(Entity* self, eRebuildState state) -{ - if (state == eRebuildState::REBUILD_COMPLETED) - { - GameMessages::SendPlayAnimation(self, u"dragonsmash"); +void FvDragonSmashingGolemQb::OnRebuildNotifyState(Entity* self, eRebuildState state) { + if (state == eRebuildState::REBUILD_COMPLETED) { + GameMessages::SendPlayAnimation(self, u"dragonsmash"); - const auto dragonId = self->GetVar(u"Dragon"); + const auto dragonId = self->GetVar(u"Dragon"); - auto* dragon = EntityManager::Instance()->GetEntity(dragonId); + auto* dragon = EntityManager::Instance()->GetEntity(dragonId); - if (dragon != nullptr) - { - dragon->OnFireEventServerSide(self, "rebuildDone"); - } + if (dragon != nullptr) { + dragon->OnFireEventServerSide(self, "rebuildDone"); + } - self->CancelTimer("GolemBreakTimer"); - self->AddTimer("GolemBreakTimer", 10.5f); - } + self->CancelTimer("GolemBreakTimer"); + self->AddTimer("GolemBreakTimer", 10.5f); + } } diff --git a/dScripts/FvDragonSmashingGolemQb.h b/dScripts/FvDragonSmashingGolemQb.h index 3cbe9a40..8aa772a3 100644 --- a/dScripts/FvDragonSmashingGolemQb.h +++ b/dScripts/FvDragonSmashingGolemQb.h @@ -1,10 +1,10 @@ #pragma once #include "CppScripts.h" -class FvDragonSmashingGolemQb : public CppScripts::Script +class FvDragonSmashingGolemQb : public CppScripts::Script { public: void OnStartup(Entity* self) override; - void OnTimerDone(Entity* self, std::string timerName) override; - void OnRebuildNotifyState(Entity* self, eRebuildState state) override; + void OnTimerDone(Entity* self, std::string timerName) override; + void OnRebuildNotifyState(Entity* self, eRebuildState state) override; }; diff --git a/dScripts/FvFacilityBrick.cpp b/dScripts/FvFacilityBrick.cpp index fce9e630..1ae910e4 100644 --- a/dScripts/FvFacilityBrick.cpp +++ b/dScripts/FvFacilityBrick.cpp @@ -3,117 +3,95 @@ #include "dZoneManager.h" #include "EntityManager.h" -void FvFacilityBrick::OnStartup(Entity* self) -{ - self->SetVar(u"ConsoleLEFTActive", false); - self->SetVar(u"ConsoleRIGHTtActive", false); +void FvFacilityBrick::OnStartup(Entity* self) { + self->SetVar(u"ConsoleLEFTActive", false); + self->SetVar(u"ConsoleRIGHTtActive", false); } -void FvFacilityBrick::OnNotifyObject(Entity *self, Entity *sender, const std::string& name, int32_t param1, int32_t param2) -{ - auto* brickSpawner = dZoneManager::Instance()->GetSpawnersByName("ImaginationBrick")[0]; - auto* bugSpawner = dZoneManager::Instance()->GetSpawnersByName("MaelstromBug")[0]; - auto* canisterSpawner = dZoneManager::Instance()->GetSpawnersByName("BrickCanister")[0]; +void FvFacilityBrick::OnNotifyObject(Entity* self, Entity* sender, const std::string& name, int32_t param1, int32_t param2) { + auto* brickSpawner = dZoneManager::Instance()->GetSpawnersByName("ImaginationBrick")[0]; + auto* bugSpawner = dZoneManager::Instance()->GetSpawnersByName("MaelstromBug")[0]; + auto* canisterSpawner = dZoneManager::Instance()->GetSpawnersByName("BrickCanister")[0]; - if (name == "ConsoleLeftUp") - { - GameMessages::SendStopFXEffect(self, true, "LeftPipeOff"); - GameMessages::SendPlayFXEffect(self->GetObjectID(), 2775, u"create", "LeftPipeEnergy"); - } - else if (name == "ConsoleLeftDown") - { - self->SetVar(u"ConsoleLEFTActive", false); + if (name == "ConsoleLeftUp") { + GameMessages::SendStopFXEffect(self, true, "LeftPipeOff"); + GameMessages::SendPlayFXEffect(self->GetObjectID(), 2775, u"create", "LeftPipeEnergy"); + } else if (name == "ConsoleLeftDown") { + self->SetVar(u"ConsoleLEFTActive", false); - GameMessages::SendStopFXEffect(self, true, "LeftPipeEnergy"); - GameMessages::SendStopFXEffect(self, true, "LeftPipeOn"); - GameMessages::SendPlayFXEffect(self->GetObjectID(), 2774, u"create", "LeftPipeOff"); - } - else if (name == "ConsoleLeftActive") - { - self->SetVar(u"ConsoleLEFTActive", true); + GameMessages::SendStopFXEffect(self, true, "LeftPipeEnergy"); + GameMessages::SendStopFXEffect(self, true, "LeftPipeOn"); + GameMessages::SendPlayFXEffect(self->GetObjectID(), 2774, u"create", "LeftPipeOff"); + } else if (name == "ConsoleLeftActive") { + self->SetVar(u"ConsoleLEFTActive", true); - GameMessages::SendStopFXEffect(self, true, "LeftPipeEnergy"); - GameMessages::SendPlayFXEffect(self->GetObjectID(), 2776, u"create", "LeftPipeOn"); - } - - else if (name == "ConsoleRightUp") - { - GameMessages::SendStopFXEffect(self, true, "RightPipeOff"); - GameMessages::SendPlayFXEffect(self->GetObjectID(), 2778, u"create", "RightPipeEnergy"); - } - else if (name == "ConsoleRightDown") - { - self->SetVar(u"ConsoleRIGHTActive", false); + GameMessages::SendStopFXEffect(self, true, "LeftPipeEnergy"); + GameMessages::SendPlayFXEffect(self->GetObjectID(), 2776, u"create", "LeftPipeOn"); + } - GameMessages::SendStopFXEffect(self, true, "RightPipeEnergy"); - GameMessages::SendStopFXEffect(self, true, "RightPipeOn"); - GameMessages::SendPlayFXEffect(self->GetObjectID(), 2777, u"create", "RightPipeOff"); - } - else if (name == "ConsoleRightActive") - { - self->SetVar(u"ConsoleRIGHTActive", true); + else if (name == "ConsoleRightUp") { + GameMessages::SendStopFXEffect(self, true, "RightPipeOff"); + GameMessages::SendPlayFXEffect(self->GetObjectID(), 2778, u"create", "RightPipeEnergy"); + } else if (name == "ConsoleRightDown") { + self->SetVar(u"ConsoleRIGHTActive", false); - GameMessages::SendStopFXEffect(self, true, "RightPipeOff"); - GameMessages::SendPlayFXEffect(self->GetObjectID(), 2779, u"create", "RightPipeEnergy"); - } + GameMessages::SendStopFXEffect(self, true, "RightPipeEnergy"); + GameMessages::SendStopFXEffect(self, true, "RightPipeOn"); + GameMessages::SendPlayFXEffect(self->GetObjectID(), 2777, u"create", "RightPipeOff"); + } else if (name == "ConsoleRightActive") { + self->SetVar(u"ConsoleRIGHTActive", true); - if (self->GetVar(u"ConsoleLEFTActive") && self->GetVar(u"ConsoleRIGHTActive")) - { - auto* object = EntityManager::Instance()->GetEntitiesInGroup("Brick")[0]; + GameMessages::SendStopFXEffect(self, true, "RightPipeOff"); + GameMessages::SendPlayFXEffect(self->GetObjectID(), 2779, u"create", "RightPipeEnergy"); + } - if (object != nullptr) - { - GameMessages::SendPlayFXEffect(object->GetObjectID(), 122, u"create", "bluebrick"); - GameMessages::SendPlayFXEffect(object->GetObjectID(), 1034, u"cast", "imaginationexplosion"); - } + if (self->GetVar(u"ConsoleLEFTActive") && self->GetVar(u"ConsoleRIGHTActive")) { + auto* object = EntityManager::Instance()->GetEntitiesInGroup("Brick")[0]; - object = EntityManager::Instance()->GetEntitiesInGroup("Canister")[0]; + if (object != nullptr) { + GameMessages::SendPlayFXEffect(object->GetObjectID(), 122, u"create", "bluebrick"); + GameMessages::SendPlayFXEffect(object->GetObjectID(), 1034, u"cast", "imaginationexplosion"); + } - if (object != nullptr) - { - object->Smash(self->GetObjectID(), SILENT); - } + object = EntityManager::Instance()->GetEntitiesInGroup("Canister")[0]; - canisterSpawner->Reset(); - canisterSpawner->Deactivate(); - } - else if (self->GetVar(u"ConsoleLEFTActive") || self->GetVar(u"ConsoleRIGHTActive")) - { - brickSpawner->Activate(); + if (object != nullptr) { + object->Smash(self->GetObjectID(), SILENT); + } - auto* object = EntityManager::Instance()->GetEntitiesInGroup("Brick")[0]; + canisterSpawner->Reset(); + canisterSpawner->Deactivate(); + } else if (self->GetVar(u"ConsoleLEFTActive") || self->GetVar(u"ConsoleRIGHTActive")) { + brickSpawner->Activate(); - if (object != nullptr) - { - GameMessages::SendStopFXEffect(object, true, "bluebrick"); - } + auto* object = EntityManager::Instance()->GetEntitiesInGroup("Brick")[0]; - bugSpawner->Reset(); - bugSpawner->Deactivate(); + if (object != nullptr) { + GameMessages::SendStopFXEffect(object, true, "bluebrick"); + } - canisterSpawner->Reset(); - canisterSpawner->Activate(); - } - else - { - brickSpawner->Reset(); - brickSpawner->Deactivate(); + bugSpawner->Reset(); + bugSpawner->Deactivate(); - bugSpawner->Reset(); - bugSpawner->Activate(); - } + canisterSpawner->Reset(); + canisterSpawner->Activate(); + } else { + brickSpawner->Reset(); + brickSpawner->Deactivate(); + + bugSpawner->Reset(); + bugSpawner->Activate(); + } } -void FvFacilityBrick::OnFireEventServerSide(Entity *self, Entity *sender, std::string args, int32_t param1, int32_t param2, - int32_t param3) -{ - if (args != "PlayFX") - { - return; - } +void FvFacilityBrick::OnFireEventServerSide(Entity* self, Entity* sender, std::string args, int32_t param1, int32_t param2, + int32_t param3) { + if (args != "PlayFX") { + return; + } - GameMessages::SendPlayFXEffect(self->GetObjectID(), 2774, u"create", "LeftPipeOff"); - GameMessages::SendPlayFXEffect(self->GetObjectID(), 2777, u"create", "RightPipeOff"); - GameMessages::SendPlayFXEffect(self->GetObjectID(), 2750, u"create", "imagination_canister"); - GameMessages::SendPlayFXEffect(self->GetObjectID(), 2751, u"create", "canister_light_filler"); + GameMessages::SendPlayFXEffect(self->GetObjectID(), 2774, u"create", "LeftPipeOff"); + GameMessages::SendPlayFXEffect(self->GetObjectID(), 2777, u"create", "RightPipeOff"); + GameMessages::SendPlayFXEffect(self->GetObjectID(), 2750, u"create", "imagination_canister"); + GameMessages::SendPlayFXEffect(self->GetObjectID(), 2751, u"create", "canister_light_filler"); } diff --git a/dScripts/FvFacilityBrick.h b/dScripts/FvFacilityBrick.h index 794dd5b6..c7580c25 100644 --- a/dScripts/FvFacilityBrick.h +++ b/dScripts/FvFacilityBrick.h @@ -1,11 +1,11 @@ #pragma once #include "CppScripts.h" -class FvFacilityBrick : public CppScripts::Script +class FvFacilityBrick : public CppScripts::Script { public: void OnStartup(Entity* self) override; - void OnNotifyObject(Entity *self, Entity *sender, const std::string& name, int32_t param1 = 0, int32_t param2 = 0) override; - void OnFireEventServerSide(Entity *self, Entity *sender, std::string args, int32_t param1, int32_t param2, - int32_t param3) override; -}; \ No newline at end of file + void OnNotifyObject(Entity* self, Entity* sender, const std::string& name, int32_t param1 = 0, int32_t param2 = 0) override; + void OnFireEventServerSide(Entity* self, Entity* sender, std::string args, int32_t param1, int32_t param2, + int32_t param3) override; +}; diff --git a/dScripts/FvFlyingCreviceDragon.cpp b/dScripts/FvFlyingCreviceDragon.cpp index 4255daf5..16eda512 100644 --- a/dScripts/FvFlyingCreviceDragon.cpp +++ b/dScripts/FvFlyingCreviceDragon.cpp @@ -4,129 +4,104 @@ #include "SkillComponent.h" #include "GeneralUtils.h" -void FvFlyingCreviceDragon::OnStartup(Entity* self) -{ - self->AddTimer("waypoint", 5); +void FvFlyingCreviceDragon::OnStartup(Entity* self) { + self->AddTimer("waypoint", 5); } -void FvFlyingCreviceDragon::OnTimerDone(Entity* self, std::string timerName) -{ - if (timerName == "waypoint") - { - auto point = self->GetVar(u"waypoint"); +void FvFlyingCreviceDragon::OnTimerDone(Entity* self, std::string timerName) { + if (timerName == "waypoint") { + auto point = self->GetVar(u"waypoint"); - if (point >= 20) - { - point = 0; - } + if (point >= 20) { + point = 0; + } - self->SetVar(u"waypoint", point + 1); + self->SetVar(u"waypoint", point + 1); - self->AddTimer("waypoint", 5); + self->AddTimer("waypoint", 5); - OnArrived(self); + OnArrived(self); - return; - } + return; + } - std::string groupName = ""; + std::string groupName = ""; - if (timerName == "platform1attack") - { - groupName = "dragonFireballs1"; - } - else if (timerName == "platform3attack") - { - groupName = "dragonFireballs3"; - } + if (timerName == "platform1attack") { + groupName = "dragonFireballs1"; + } else if (timerName == "platform3attack") { + groupName = "dragonFireballs3"; + } - const auto& group = EntityManager::Instance()->GetEntitiesInGroup(groupName); + const auto& group = EntityManager::Instance()->GetEntitiesInGroup(groupName); - if (group.empty()) - { - return; - } + if (group.empty()) { + return; + } - auto* skillComponent = group[0]->GetComponent(); + auto* skillComponent = group[0]->GetComponent(); - if (skillComponent != nullptr) - { - skillComponent->CalculateBehavior(762, 12506, LWOOBJID_EMPTY, true); - } + if (skillComponent != nullptr) { + skillComponent->CalculateBehavior(762, 12506, LWOOBJID_EMPTY, true); + } - auto minionCount = 1; - for (size_t i = 1; i < group.size(); i++) - { - if (minionCount == 4) - { - return; - } + auto minionCount = 1; + for (size_t i = 1; i < group.size(); i++) { + if (minionCount == 4) { + return; + } - if (/*GeneralUtils::GenerateRandomNumber(1, 5) > 3*/ true) - { - skillComponent = group[i]->GetComponent(); + if (/*GeneralUtils::GenerateRandomNumber(1, 5) > 3*/ true) { + skillComponent = group[i]->GetComponent(); - if (skillComponent != nullptr) - { - skillComponent->CalculateBehavior(762, 12506, LWOOBJID_EMPTY); + if (skillComponent != nullptr) { + skillComponent->CalculateBehavior(762, 12506, LWOOBJID_EMPTY); - ++minionCount; - } - } - } + ++minionCount; + } + } + } } -void FvFlyingCreviceDragon::OnArrived(Entity* self) -{ - auto point = self->GetVar(u"waypoint"); +void FvFlyingCreviceDragon::OnArrived(Entity* self) { + auto point = self->GetVar(u"waypoint"); - if (point == 4) - { - GameMessages::SendPlayAnimation(self, u"attack1", 2); - self->AddTimer("platform1attack", 1.75f); - } - else if (point == 12) - { - GameMessages::SendPlayAnimation(self, u"attack2", 2); + if (point == 4) { + GameMessages::SendPlayAnimation(self, u"attack1", 2); + self->AddTimer("platform1attack", 1.75f); + } else if (point == 12) { + GameMessages::SendPlayAnimation(self, u"attack2", 2); - const auto& group2 = EntityManager::Instance()->GetEntitiesInGroup("dragonFireballs2"); + const auto& group2 = EntityManager::Instance()->GetEntitiesInGroup("dragonFireballs2"); - if (group2.empty()) - { - return; - } + if (group2.empty()) { + return; + } - auto* skillComponent = group2[0]->GetComponent(); + auto* skillComponent = group2[0]->GetComponent(); - if (skillComponent != nullptr) - { - skillComponent->CalculateBehavior(762, 12506, LWOOBJID_EMPTY); - } + if (skillComponent != nullptr) { + skillComponent->CalculateBehavior(762, 12506, LWOOBJID_EMPTY); + } - auto minionCount = 1; - for (size_t i = 1; i < group2.size(); i++) - { - if (minionCount == 4) - { - return; - } + auto minionCount = 1; + for (size_t i = 1; i < group2.size(); i++) { + if (minionCount == 4) { + return; + } - if (GeneralUtils::GenerateRandomNumber(1, 5) > 3) - { - skillComponent = group2[i]->GetComponent(); + if (GeneralUtils::GenerateRandomNumber(1, 5) > 3) { + skillComponent = group2[i]->GetComponent(); - if (skillComponent != nullptr) - { - skillComponent->CalculateBehavior(762, 12506, LWOOBJID_EMPTY, true); + if (skillComponent != nullptr) { + skillComponent->CalculateBehavior(762, 12506, LWOOBJID_EMPTY, true); - ++minionCount; - } - } - } - } - else if (point == 16) - { - GameMessages::SendPlayAnimation(self, u"attack3", 2); - self->AddTimer("platform3attack", 0.5f); - } + ++minionCount; + } + } + } + } else if (point == 16) { + GameMessages::SendPlayAnimation(self, u"attack3", 2); + self->AddTimer("platform3attack", 0.5f); + } } diff --git a/dScripts/FvFlyingCreviceDragon.h b/dScripts/FvFlyingCreviceDragon.h index 657f4eed..92e95d26 100644 --- a/dScripts/FvFlyingCreviceDragon.h +++ b/dScripts/FvFlyingCreviceDragon.h @@ -1,10 +1,10 @@ #pragma once #include "CppScripts.h" -class FvFlyingCreviceDragon : public CppScripts::Script +class FvFlyingCreviceDragon : public CppScripts::Script { public: void OnStartup(Entity* self) override; - void OnTimerDone(Entity* self, std::string timerName) override; - void OnArrived(Entity* self); + void OnTimerDone(Entity* self, std::string timerName) override; + void OnArrived(Entity* self); }; diff --git a/dScripts/FvFong.cpp b/dScripts/FvFong.cpp index 9a3de0b2..7f63e5e5 100644 --- a/dScripts/FvFong.cpp +++ b/dScripts/FvFong.cpp @@ -2,10 +2,8 @@ #include "Darkitect.h" #include "MissionState.h" -void FvFong::OnMissionDialogueOK(Entity* self, Entity* target, int missionID, MissionState missionState) -{ - if (missionID == 734 && missionState == MissionState::MISSION_STATE_READY_TO_COMPLETE) - { +void FvFong::OnMissionDialogueOK(Entity* self, Entity* target, int missionID, MissionState missionState) { + if (missionID == 734 && missionState == MissionState::MISSION_STATE_READY_TO_COMPLETE) { Darkitect Baron; Baron.Reveal(self, target); } diff --git a/dScripts/FvFong.h b/dScripts/FvFong.h index fc47b484..074e6d8c 100644 --- a/dScripts/FvFong.h +++ b/dScripts/FvFong.h @@ -3,6 +3,6 @@ class FvFong : public CppScripts::Script { - public: - void OnMissionDialogueOK(Entity* self, Entity* target, int missionID, MissionState missionState) override; +public: + void OnMissionDialogueOK(Entity* self, Entity* target, int missionID, MissionState missionState) override; }; diff --git a/dScripts/FvFreeGfNinjas.cpp b/dScripts/FvFreeGfNinjas.cpp index 8022b32f..1751b6a7 100644 --- a/dScripts/FvFreeGfNinjas.cpp +++ b/dScripts/FvFreeGfNinjas.cpp @@ -2,42 +2,41 @@ #include "Character.h" #include "MissionComponent.h" -void FvFreeGfNinjas::OnMissionDialogueOK(Entity *self, Entity *target, int missionID, MissionState missionState) { - if (missionID == 705 && missionState == MissionState::MISSION_STATE_AVAILABLE) { - auto* missionComponent = target->GetComponent(); - if (missionComponent == nullptr) - return; +void FvFreeGfNinjas::OnMissionDialogueOK(Entity* self, Entity* target, int missionID, MissionState missionState) { + if (missionID == 705 && missionState == MissionState::MISSION_STATE_AVAILABLE) { + auto* missionComponent = target->GetComponent(); + if (missionComponent == nullptr) + return; - missionComponent->AcceptMission(701); - missionComponent->AcceptMission(702); - missionComponent->AcceptMission(703); - missionComponent->AcceptMission(704); + missionComponent->AcceptMission(701); + missionComponent->AcceptMission(702); + missionComponent->AcceptMission(703); + missionComponent->AcceptMission(704); - auto* character = target->GetCharacter(); - if (character != nullptr) - character->SetPlayerFlag(68, true); - } else if (missionID == 786) { - auto* character = target->GetCharacter(); - if (character != nullptr) - character->SetPlayerFlag(81, true); - } + auto* character = target->GetCharacter(); + if (character != nullptr) + character->SetPlayerFlag(68, true); + } else if (missionID == 786) { + auto* character = target->GetCharacter(); + if (character != nullptr) + character->SetPlayerFlag(81, true); + } } -void FvFreeGfNinjas::OnUse(Entity* self, Entity* user) -{ - // To allow player who already have the mission to progress. - auto* missionComponent = user->GetComponent(); - if (missionComponent == nullptr) - return; +void FvFreeGfNinjas::OnUse(Entity* self, Entity* user) { + // To allow player who already have the mission to progress. + auto* missionComponent = user->GetComponent(); + if (missionComponent == nullptr) + return; - if (missionComponent->GetMissionState(705) == MissionState::MISSION_STATE_ACTIVE) { - auto* character = user->GetCharacter(); - if (character != nullptr) - character->SetPlayerFlag(68, true); + if (missionComponent->GetMissionState(705) == MissionState::MISSION_STATE_ACTIVE) { + auto* character = user->GetCharacter(); + if (character != nullptr) + character->SetPlayerFlag(68, true); - missionComponent->AcceptMission(701, true); - missionComponent->AcceptMission(702, true); - missionComponent->AcceptMission(703, true); - missionComponent->AcceptMission(704, true); - } + missionComponent->AcceptMission(701, true); + missionComponent->AcceptMission(702, true); + missionComponent->AcceptMission(703, true); + missionComponent->AcceptMission(704, true); + } } diff --git a/dScripts/FvFreeGfNinjas.h b/dScripts/FvFreeGfNinjas.h index cdff0d2d..c7e4876e 100644 --- a/dScripts/FvFreeGfNinjas.h +++ b/dScripts/FvFreeGfNinjas.h @@ -3,6 +3,6 @@ class FvFreeGfNinjas : public CppScripts::Script { public: - void OnMissionDialogueOK(Entity *self, Entity *target, int missionID, MissionState missionState) override; - void OnUse(Entity* self, Entity* user) override; + void OnMissionDialogueOK(Entity* self, Entity* target, int missionID, MissionState missionState) override; + void OnUse(Entity* self, Entity* user) override; }; diff --git a/dScripts/FvHorsemenTrigger.cpp b/dScripts/FvHorsemenTrigger.cpp index 541c11e0..e87d9629 100644 --- a/dScripts/FvHorsemenTrigger.cpp +++ b/dScripts/FvHorsemenTrigger.cpp @@ -2,64 +2,52 @@ #include "EntityManager.h" #include "MissionComponent.h" -void FvHorsemenTrigger::OnStartup(Entity* self) -{ - self->SetProximityRadius(40, "horsemenTrigger"); +void FvHorsemenTrigger::OnStartup(Entity* self) { + self->SetProximityRadius(40, "horsemenTrigger"); - self->SetVar>(u"players", {}); + self->SetVar>(u"players", {}); } -void FvHorsemenTrigger::OnProximityUpdate(Entity* self, Entity* entering, std::string name, std::string status) -{ - if (name != "horsemenTrigger" || !entering->IsPlayer()) - { - return; - } +void FvHorsemenTrigger::OnProximityUpdate(Entity* self, Entity* entering, std::string name, std::string status) { + if (name != "horsemenTrigger" || !entering->IsPlayer()) { + return; + } - auto players = self->GetVar>(u"players"); + auto players = self->GetVar>(u"players"); - const auto& iter = std::find(players.begin(), players.end(), entering->GetObjectID()); + const auto& iter = std::find(players.begin(), players.end(), entering->GetObjectID()); - if (status == "ENTER" && iter == players.end()) - { - players.push_back(entering->GetObjectID()); - } - else if (status == "LEAVE" && iter != players.end()) - { - players.erase(iter); - } + if (status == "ENTER" && iter == players.end()) { + players.push_back(entering->GetObjectID()); + } else if (status == "LEAVE" && iter != players.end()) { + players.erase(iter); + } - self->SetVar>(u"players", players); + self->SetVar>(u"players", players); } void -FvHorsemenTrigger::OnFireEventServerSide(Entity *self, Entity *sender, std::string args, int32_t param1, int32_t param2, - int32_t param3) -{ - auto players = self->GetVar>(u"players"); +FvHorsemenTrigger::OnFireEventServerSide(Entity* self, Entity* sender, std::string args, int32_t param1, int32_t param2, + int32_t param3) { + auto players = self->GetVar>(u"players"); - if (args == "HorsemenDeath") - { - for (const auto& playerId : self->GetVar>(u"players")) - { - auto* player = EntityManager::Instance()->GetEntity(playerId); + if (args == "HorsemenDeath") { + for (const auto& playerId : self->GetVar>(u"players")) { + auto* player = EntityManager::Instance()->GetEntity(playerId); - if (player == nullptr) - { - continue; - } + if (player == nullptr) { + continue; + } - auto* missionComponent = player->GetComponent(); + auto* missionComponent = player->GetComponent(); - if (missionComponent == nullptr) - { - continue; - } + if (missionComponent == nullptr) { + continue; + } - for (const auto missionId : m_Missions) - { - missionComponent->ForceProgressTaskType(missionId, 1, 1); - } - } - } + for (const auto missionId : m_Missions) { + missionComponent->ForceProgressTaskType(missionId, 1, 1); + } + } + } } diff --git a/dScripts/FvHorsemenTrigger.h b/dScripts/FvHorsemenTrigger.h index 9ec47084..233e2f5b 100644 --- a/dScripts/FvHorsemenTrigger.h +++ b/dScripts/FvHorsemenTrigger.h @@ -2,14 +2,14 @@ #include "CppScripts.h" #include "RenderComponent.h" -class FvHorsemenTrigger : public CppScripts::Script +class FvHorsemenTrigger : public CppScripts::Script { public: void OnStartup(Entity* self) override; - void OnProximityUpdate(Entity* self, Entity* entering, std::string name, std::string status) override; - void OnFireEventServerSide(Entity *self, Entity *sender, std::string args, int32_t param1, int32_t param2, - int32_t param3) override; + void OnProximityUpdate(Entity* self, Entity* entering, std::string name, std::string status) override; + void OnFireEventServerSide(Entity* self, Entity* sender, std::string args, int32_t param1, int32_t param2, + int32_t param3) override; private: - std::vector m_Missions = {854, 738, 1432, 1530, 1567, 1604}; + std::vector m_Missions = { 854, 738, 1432, 1530, 1567, 1604 }; }; diff --git a/dScripts/FvMaelstromCavalry.cpp b/dScripts/FvMaelstromCavalry.cpp index b4a32991..9214667e 100644 --- a/dScripts/FvMaelstromCavalry.cpp +++ b/dScripts/FvMaelstromCavalry.cpp @@ -1,37 +1,30 @@ #include "FvMaelstromCavalry.h" #include "EntityManager.h" -void FvMaelstromCavalry::OnStartup(Entity* self) -{ - for (const auto& group : self->GetGroups()) - { - const auto& objects = EntityManager::Instance()->GetEntitiesInGroup(group); +void FvMaelstromCavalry::OnStartup(Entity* self) { + for (const auto& group : self->GetGroups()) { + const auto& objects = EntityManager::Instance()->GetEntitiesInGroup(group); - for (auto* obj : objects) - { - if (obj->GetLOT() != 8551) continue; + for (auto* obj : objects) { + if (obj->GetLOT() != 8551) continue; - obj->OnFireEventServerSide(self, "ISpawned"); - } - } + obj->OnFireEventServerSide(self, "ISpawned"); + } + } } -void FvMaelstromCavalry::OnDie(Entity* self, Entity* killer) -{ - if (killer == nullptr) - { - return; - } +void FvMaelstromCavalry::OnDie(Entity* self, Entity* killer) { + if (killer == nullptr) { + return; + } - if (killer->GetLOT() != 8665) - { - return; - } + if (killer->GetLOT() != 8665) { + return; + } - const auto& triggers = EntityManager::Instance()->GetEntitiesInGroup("HorsemenTrigger"); + const auto& triggers = EntityManager::Instance()->GetEntitiesInGroup("HorsemenTrigger"); - for (auto* trigger : triggers) - { - trigger->OnFireEventServerSide(self, "HorsemenDeath"); - } + for (auto* trigger : triggers) { + trigger->OnFireEventServerSide(self, "HorsemenDeath"); + } } diff --git a/dScripts/FvMaelstromCavalry.h b/dScripts/FvMaelstromCavalry.h index 0fc3e840..40784ba9 100644 --- a/dScripts/FvMaelstromCavalry.h +++ b/dScripts/FvMaelstromCavalry.h @@ -1,7 +1,7 @@ #pragma once #include "CppScripts.h" -class FvMaelstromCavalry : public CppScripts::Script +class FvMaelstromCavalry : public CppScripts::Script { public: void OnStartup(Entity* self); diff --git a/dScripts/FvMaelstromDragon.cpp b/dScripts/FvMaelstromDragon.cpp index 66e7de85..47ddb4bf 100644 --- a/dScripts/FvMaelstromDragon.cpp +++ b/dScripts/FvMaelstromDragon.cpp @@ -4,197 +4,172 @@ #include "BaseCombatAIComponent.h" #include "DestroyableComponent.h" -void FvMaelstromDragon::OnStartup(Entity* self) -{ - self->SetVar(u"weakspot", 0); +void FvMaelstromDragon::OnStartup(Entity* self) { + self->SetVar(u"weakspot", 0); - auto* baseCombatAIComponent = self->GetComponent(); + auto* baseCombatAIComponent = self->GetComponent(); - if (baseCombatAIComponent != nullptr) - { - baseCombatAIComponent->SetStunImmune(true); - } + if (baseCombatAIComponent != nullptr) { + baseCombatAIComponent->SetStunImmune(true); + } } -void FvMaelstromDragon::OnDie(Entity* self, Entity* killer) -{ - if (self->GetVar(u"bDied")) - { - return; - } +void FvMaelstromDragon::OnDie(Entity* self, Entity* killer) { + if (self->GetVar(u"bDied")) { + return; + } - self->SetVar(u"bDied", true); + self->SetVar(u"bDied", true); - auto position = self->GetPosition(); - auto rotation = self->GetRotation(); + auto position = self->GetPosition(); + auto rotation = self->GetRotation(); - auto chestObject = 11229; + auto chestObject = 11229; - EntityInfo info {}; - info.lot = chestObject; - info.pos = position; - info.rot = rotation; - info.spawnerID = self->GetObjectID(); + EntityInfo info{}; + info.lot = chestObject; + info.pos = position; + info.rot = rotation; + info.spawnerID = self->GetObjectID(); - auto* chest = EntityManager::Instance()->CreateEntity(info); + auto* chest = EntityManager::Instance()->CreateEntity(info); - EntityManager::Instance()->ConstructEntity(chest); + EntityManager::Instance()->ConstructEntity(chest); - auto golemId = self->GetVar(u"Golem"); + auto golemId = self->GetVar(u"Golem"); - auto* golem = EntityManager::Instance()->GetEntity(golemId); + auto* golem = EntityManager::Instance()->GetEntity(golemId); - if (golem != nullptr) - { - golem->Smash(self->GetObjectID()); - } + if (golem != nullptr) { + golem->Smash(self->GetObjectID()); + } } -void FvMaelstromDragon::OnHitOrHealResult(Entity* self, Entity* attacker, int32_t damage) -{ - GameMessages::SendPlayFXEffect(self, -1, u"gothit", "", LWOOBJID_EMPTY, 1, 1, true); +void FvMaelstromDragon::OnHitOrHealResult(Entity* self, Entity* attacker, int32_t damage) { + GameMessages::SendPlayFXEffect(self, -1, u"gothit", "", LWOOBJID_EMPTY, 1, 1, true); - if (true) - { - auto weakpoint = self->GetVar(u"weakspot"); + if (true) { + auto weakpoint = self->GetVar(u"weakspot"); - if (weakpoint == 1) - { - self->Smash(attacker->GetObjectID()); - } - } + if (weakpoint == 1) { + self->Smash(attacker->GetObjectID()); + } + } - auto* destroyableComponent = self->GetComponent(); + auto* destroyableComponent = self->GetComponent(); - if (destroyableComponent != nullptr) - { - Game::logger->Log("FvMaelstromDragon", "Hit %i", destroyableComponent->GetArmor()); + if (destroyableComponent != nullptr) { + Game::logger->Log("FvMaelstromDragon", "Hit %i", destroyableComponent->GetArmor()); - if (destroyableComponent->GetArmor() > 0) return; + if (destroyableComponent->GetArmor() > 0) return; - auto weakpoint = self->GetVar(u"weakpoint"); + auto weakpoint = self->GetVar(u"weakpoint"); - if (weakpoint == 0) - { - Game::logger->Log("FvMaelstromDragon", "Activating weakpoint"); + if (weakpoint == 0) { + Game::logger->Log("FvMaelstromDragon", "Activating weakpoint"); - self->AddTimer("ReviveTimer", 12); + self->AddTimer("ReviveTimer", 12); - auto* baseCombatAIComponent = self->GetComponent(); - auto* skillComponent = self->GetComponent(); + auto* baseCombatAIComponent = self->GetComponent(); + auto* skillComponent = self->GetComponent(); - if (baseCombatAIComponent != nullptr) - { - baseCombatAIComponent->SetDisabled(true); - baseCombatAIComponent->SetStunned(true); - } + if (baseCombatAIComponent != nullptr) { + baseCombatAIComponent->SetDisabled(true); + baseCombatAIComponent->SetStunned(true); + } - if (skillComponent != nullptr) - { - skillComponent->Interrupt(); - } + if (skillComponent != nullptr) { + skillComponent->Interrupt(); + } - self->SetVar(u"weakpoint", 2); + self->SetVar(u"weakpoint", 2); - GameMessages::SendPlayAnimation(self, u"stunstart", 1.7f); + GameMessages::SendPlayAnimation(self, u"stunstart", 1.7f); - self->AddTimer("timeToStunLoop", 1); + self->AddTimer("timeToStunLoop", 1); - auto position = self->GetPosition(); - auto forward = self->GetRotation().GetForwardVector(); - auto backwards = forward * -1; + auto position = self->GetPosition(); + auto forward = self->GetRotation().GetForwardVector(); + auto backwards = forward * -1; - forward.x *= 10; - forward.z *= 10; + forward.x *= 10; + forward.z *= 10; - auto rotation = self->GetRotation(); + auto rotation = self->GetRotation(); - auto objectPosition = NiPoint3(); + auto objectPosition = NiPoint3(); - objectPosition.y = position.y; - objectPosition.x = position.x - (backwards.x * 8); - objectPosition.z = position.z - (backwards.z * 8); + objectPosition.y = position.y; + objectPosition.x = position.x - (backwards.x * 8); + objectPosition.z = position.z - (backwards.z * 8); - auto golem = self->GetVar(u"DragonSmashingGolem"); + auto golem = self->GetVar(u"DragonSmashingGolem"); - EntityInfo info {}; - info.lot = golem != 0 ? golem : 8340; - info.pos = objectPosition; - info.rot = rotation; - info.spawnerID = self->GetObjectID(); - info.settings = { - new LDFData(u"rebuild_activators", - std::to_string(objectPosition.x + forward.x) + "\x1f" + - std::to_string(objectPosition.y) + "\x1f" + - std::to_string(objectPosition.z + forward.z) - ), - new LDFData(u"respawn", 100000), - new LDFData(u"rebuild_reset_time", 15), - new LDFData(u"no_timed_spawn", true), - new LDFData(u"Dragon", self->GetObjectID()) - }; + EntityInfo info{}; + info.lot = golem != 0 ? golem : 8340; + info.pos = objectPosition; + info.rot = rotation; + info.spawnerID = self->GetObjectID(); + info.settings = { + new LDFData(u"rebuild_activators", + std::to_string(objectPosition.x + forward.x) + "\x1f" + + std::to_string(objectPosition.y) + "\x1f" + + std::to_string(objectPosition.z + forward.z) + ), + new LDFData(u"respawn", 100000), + new LDFData(u"rebuild_reset_time", 15), + new LDFData(u"no_timed_spawn", true), + new LDFData(u"Dragon", self->GetObjectID()) + }; - auto* golemObject = EntityManager::Instance()->CreateEntity(info); + auto* golemObject = EntityManager::Instance()->CreateEntity(info); - EntityManager::Instance()->ConstructEntity(golemObject); - } - } + EntityManager::Instance()->ConstructEntity(golemObject); + } + } } -void FvMaelstromDragon::OnTimerDone(Entity* self, std::string timerName) -{ - if (timerName == "ReviveHeldTimer") - { - self->AddTimer("backToAttack", 2.5); - } - else if (timerName == "ExposeWeakSpotTimer") - { - self->SetVar(u"weakspot", 1); - } - else if (timerName == "timeToStunLoop") - { - GameMessages::SendPlayAnimation(self, u"stunloop", 1.8f); - } - else if (timerName == "ReviveTimer") - { - GameMessages::SendPlayAnimation(self, u"stunend", 2.0f); - self->AddTimer("backToAttack", 1); - } - else if (timerName == "backToAttack") - { - auto* baseCombatAIComponent = self->GetComponent(); - auto* skillComponent = self->GetComponent(); +void FvMaelstromDragon::OnTimerDone(Entity* self, std::string timerName) { + if (timerName == "ReviveHeldTimer") { + self->AddTimer("backToAttack", 2.5); + } else if (timerName == "ExposeWeakSpotTimer") { + self->SetVar(u"weakspot", 1); + } else if (timerName == "timeToStunLoop") { + GameMessages::SendPlayAnimation(self, u"stunloop", 1.8f); + } else if (timerName == "ReviveTimer") { + GameMessages::SendPlayAnimation(self, u"stunend", 2.0f); + self->AddTimer("backToAttack", 1); + } else if (timerName == "backToAttack") { + auto* baseCombatAIComponent = self->GetComponent(); + auto* skillComponent = self->GetComponent(); - if (baseCombatAIComponent != nullptr) - { - baseCombatAIComponent->SetDisabled(false); - baseCombatAIComponent->SetStunned(false); - } + if (baseCombatAIComponent != nullptr) { + baseCombatAIComponent->SetDisabled(false); + baseCombatAIComponent->SetStunned(false); + } - if (skillComponent != nullptr) - { - skillComponent->Interrupt(); - } + if (skillComponent != nullptr) { + skillComponent->Interrupt(); + } - self->SetVar(u"weakspot", -1); + self->SetVar(u"weakspot", -1); - GameMessages::SendNotifyObject(self->GetObjectID(), self->GetObjectID(), u"DragonRevive", UNASSIGNED_SYSTEM_ADDRESS); - } + GameMessages::SendNotifyObject(self->GetObjectID(), self->GetObjectID(), u"DragonRevive", UNASSIGNED_SYSTEM_ADDRESS); + } } void -FvMaelstromDragon::OnFireEventServerSide(Entity *self, Entity *sender, std::string args, int32_t param1, int32_t param2, - int32_t param3) -{ - if (args != "rebuildDone") return; +FvMaelstromDragon::OnFireEventServerSide(Entity* self, Entity* sender, std::string args, int32_t param1, int32_t param2, + int32_t param3) { + if (args != "rebuildDone") return; - self->AddTimer("ExposeWeakSpotTimer", 3.8f); + self->AddTimer("ExposeWeakSpotTimer", 3.8f); - self->CancelTimer("ReviveTimer"); + self->CancelTimer("ReviveTimer"); - self->AddTimer("ReviveHeldTimer", 10.5f); + self->AddTimer("ReviveHeldTimer", 10.5f); - self->SetVar(u"Golem", sender->GetObjectID()); + self->SetVar(u"Golem", sender->GetObjectID()); - GameMessages::SendPlayAnimation(self, u"quickbuildhold", 1.9f); + GameMessages::SendPlayAnimation(self, u"quickbuildhold", 1.9f); } diff --git a/dScripts/FvMaelstromDragon.h b/dScripts/FvMaelstromDragon.h index 52af80c4..d12e1bb4 100644 --- a/dScripts/FvMaelstromDragon.h +++ b/dScripts/FvMaelstromDragon.h @@ -1,13 +1,13 @@ #pragma once #include "CppScripts.h" -class FvMaelstromDragon : public CppScripts::Script +class FvMaelstromDragon : public CppScripts::Script { public: void OnStartup(Entity* self) override; void OnDie(Entity* self, Entity* killer) override; - void OnHitOrHealResult(Entity* self, Entity* attacker, int32_t damage) override; - void OnTimerDone(Entity* self, std::string timerName) override; - void OnFireEventServerSide(Entity *self, Entity *sender, std::string args, int32_t param1, int32_t param2, - int32_t param3) override; + void OnHitOrHealResult(Entity* self, Entity* attacker, int32_t damage) override; + void OnTimerDone(Entity* self, std::string timerName) override; + void OnFireEventServerSide(Entity* self, Entity* sender, std::string args, int32_t param1, int32_t param2, + int32_t param3) override; }; diff --git a/dScripts/FvNinjaGuard.cpp b/dScripts/FvNinjaGuard.cpp index dc2bb54b..0a3cb19c 100644 --- a/dScripts/FvNinjaGuard.cpp +++ b/dScripts/FvNinjaGuard.cpp @@ -2,22 +2,16 @@ #include "GameMessages.h" #include "MissionComponent.h" -void FvNinjaGuard::OnStartup(Entity* self) -{ - if (self->GetLOT() == 7412) - { +void FvNinjaGuard::OnStartup(Entity* self) { + if (self->GetLOT() == 7412) { m_LeftGuard = self->GetObjectID(); - } - else if (self->GetLOT() == 11128) - { + } else if (self->GetLOT() == 11128) { m_RightGuard = self->GetObjectID(); } } -void FvNinjaGuard::OnEmoteReceived(Entity* self, const int32_t emote, Entity* target) -{ - if (emote != 392) - { +void FvNinjaGuard::OnEmoteReceived(Entity* self, const int32_t emote, Entity* target) { + if (emote != 392) { GameMessages::SendPlayAnimation(self, u"no"); return; @@ -27,26 +21,20 @@ void FvNinjaGuard::OnEmoteReceived(Entity* self, const int32_t emote, Entity* ta auto* missionComponent = target->GetComponent(); - if (missionComponent != nullptr && missionComponent->HasMission(737)) - { + if (missionComponent != nullptr && missionComponent->HasMission(737)) { missionComponent->ForceProgressTaskType(737, 5, 1, false); } - if (self->GetLOT() == 7412) - { + if (self->GetLOT() == 7412) { auto* rightGuard = EntityManager::Instance()->GetEntity(m_RightGuard); - if (rightGuard != nullptr) - { + if (rightGuard != nullptr) { GameMessages::SendPlayAnimation(rightGuard, u"laugh_rt"); } - } - else if (self->GetLOT() == 11128) - { + } else if (self->GetLOT() == 11128) { auto* leftGuard = EntityManager::Instance()->GetEntity(m_LeftGuard); - if (leftGuard != nullptr) - { + if (leftGuard != nullptr) { GameMessages::SendPlayAnimation(leftGuard, u"laugh_lt"); } } diff --git a/dScripts/FvPandaServer.cpp b/dScripts/FvPandaServer.cpp index ea814936..bea93a6c 100644 --- a/dScripts/FvPandaServer.cpp +++ b/dScripts/FvPandaServer.cpp @@ -2,34 +2,34 @@ #include "PetComponent.h" #include "Character.h" -void FvPandaServer::OnStartup(Entity *self) { - const auto* petComponent = self->GetComponent(); - if (petComponent != nullptr && petComponent->GetOwner() == nullptr) { - self->SetNetworkVar(u"pandatamer", std::to_string(self->GetVar(u"tamer"))); - self->AddTimer("killSelf", 45); - } +void FvPandaServer::OnStartup(Entity* self) { + const auto* petComponent = self->GetComponent(); + if (petComponent != nullptr && petComponent->GetOwner() == nullptr) { + self->SetNetworkVar(u"pandatamer", std::to_string(self->GetVar(u"tamer"))); + self->AddTimer("killSelf", 45); + } } -void FvPandaServer::OnNotifyPetTamingMinigame(Entity *self, Entity *tamer, eNotifyType type) { - if (type == NOTIFY_TYPE_BEGIN) { - self->CancelAllTimers(); - } else if (type == NOTIFY_TYPE_QUIT || type == NOTIFY_TYPE_FAILED) { - self->Smash(); - } else if (type == NOTIFY_TYPE_SUCCESS) { - // TODO: Remove from groups +void FvPandaServer::OnNotifyPetTamingMinigame(Entity* self, Entity* tamer, eNotifyType type) { + if (type == NOTIFY_TYPE_BEGIN) { + self->CancelAllTimers(); + } else if (type == NOTIFY_TYPE_QUIT || type == NOTIFY_TYPE_FAILED) { + self->Smash(); + } else if (type == NOTIFY_TYPE_SUCCESS) { + // TODO: Remove from groups - auto* character = tamer->GetCharacter(); - if (character != nullptr) { - character->SetPlayerFlag(82, true); - } - } + auto* character = tamer->GetCharacter(); + if (character != nullptr) { + character->SetPlayerFlag(82, true); + } + } } -void FvPandaServer::OnTimerDone(Entity *self, std::string timerName) { - if (timerName == "killSelf") { - const auto* petComponent = self->GetComponent(); - if (petComponent != nullptr && petComponent->GetOwner() == nullptr) { - self->Smash(self->GetObjectID(), SILENT); - } - } +void FvPandaServer::OnTimerDone(Entity* self, std::string timerName) { + if (timerName == "killSelf") { + const auto* petComponent = self->GetComponent(); + if (petComponent != nullptr && petComponent->GetOwner() == nullptr) { + self->Smash(self->GetObjectID(), SILENT); + } + } } diff --git a/dScripts/FvPandaServer.h b/dScripts/FvPandaServer.h index 377371c1..4948fdf4 100644 --- a/dScripts/FvPandaServer.h +++ b/dScripts/FvPandaServer.h @@ -2,7 +2,7 @@ #include "CppScripts.h" class FvPandaServer : public CppScripts::Script { - void OnStartup(Entity *self) override; - void OnNotifyPetTamingMinigame(Entity *self, Entity *tamer, eNotifyType type) override; - void OnTimerDone(Entity *self, std::string timerName) override; + void OnStartup(Entity* self) override; + void OnNotifyPetTamingMinigame(Entity* self, Entity* tamer, eNotifyType type) override; + void OnTimerDone(Entity* self, std::string timerName) override; }; diff --git a/dScripts/FvPandaSpawnerServer.cpp b/dScripts/FvPandaSpawnerServer.cpp index 97738271..e1f3fb96 100644 --- a/dScripts/FvPandaSpawnerServer.cpp +++ b/dScripts/FvPandaSpawnerServer.cpp @@ -4,45 +4,45 @@ #include "GameMessages.h" #include "ScriptedActivityComponent.h" -void FvPandaSpawnerServer::OnCollisionPhantom(Entity *self, Entity *target) { - auto* character = target->GetCharacter(); - if (character != nullptr && character->GetPlayerFlag(81)) { +void FvPandaSpawnerServer::OnCollisionPhantom(Entity* self, Entity* target) { + auto* character = target->GetCharacter(); + if (character != nullptr && character->GetPlayerFlag(81)) { - auto raceObjects = EntityManager::Instance()->GetEntitiesInGroup("PandaRaceObject"); - if (raceObjects.empty()) - return; + auto raceObjects = EntityManager::Instance()->GetEntitiesInGroup("PandaRaceObject"); + if (raceObjects.empty()) + return; - // Check if the player is currently in a footrace - auto* scriptedActivityComponent = raceObjects.at(0)->GetComponent(); - if (scriptedActivityComponent == nullptr || !scriptedActivityComponent->IsPlayedBy(target)) - return; + // Check if the player is currently in a footrace + auto* scriptedActivityComponent = raceObjects.at(0)->GetComponent(); + if (scriptedActivityComponent == nullptr || !scriptedActivityComponent->IsPlayedBy(target)) + return; - // If the player already spawned a panda - auto playerPandas = EntityManager::Instance()->GetEntitiesInGroup("panda" + std::to_string(target->GetObjectID())); - if (!playerPandas.empty()) { - GameMessages::SendFireEventClientSide(self->GetObjectID(), target->GetSystemAddress(), u"playerPanda", - target->GetObjectID(), 0, 0, target->GetObjectID()); - return; - } + // If the player already spawned a panda + auto playerPandas = EntityManager::Instance()->GetEntitiesInGroup("panda" + std::to_string(target->GetObjectID())); + if (!playerPandas.empty()) { + GameMessages::SendFireEventClientSide(self->GetObjectID(), target->GetSystemAddress(), u"playerPanda", + target->GetObjectID(), 0, 0, target->GetObjectID()); + return; + } - // If there's already too many spawned pandas - auto pandas = EntityManager::Instance()->GetEntitiesInGroup("pandas"); - if (pandas.size() > 4) { - GameMessages::SendFireEventClientSide(self->GetObjectID(), target->GetSystemAddress(), u"tooManyPandas", - target->GetObjectID(), 0, 0, target->GetObjectID()); - return; - } + // If there's already too many spawned pandas + auto pandas = EntityManager::Instance()->GetEntitiesInGroup("pandas"); + if (pandas.size() > 4) { + GameMessages::SendFireEventClientSide(self->GetObjectID(), target->GetSystemAddress(), u"tooManyPandas", + target->GetObjectID(), 0, 0, target->GetObjectID()); + return; + } - EntityInfo info {}; - info.spawnerID = target->GetObjectID(); - info.pos = self->GetPosition(); - info.lot = 5643; - info.settings = { - new LDFData(u"tamer", target->GetObjectID()), - new LDFData(u"groupID", u"panda" + (GeneralUtils::to_u16string(target->GetObjectID())) + u";pandas") - }; + EntityInfo info{}; + info.spawnerID = target->GetObjectID(); + info.pos = self->GetPosition(); + info.lot = 5643; + info.settings = { + new LDFData(u"tamer", target->GetObjectID()), + new LDFData(u"groupID", u"panda" + (GeneralUtils::to_u16string(target->GetObjectID())) + u";pandas") + }; - auto* panda = EntityManager::Instance()->CreateEntity(info); - EntityManager::Instance()->ConstructEntity(panda); - } + auto* panda = EntityManager::Instance()->CreateEntity(info); + EntityManager::Instance()->ConstructEntity(panda); + } } diff --git a/dScripts/FvPandaSpawnerServer.h b/dScripts/FvPandaSpawnerServer.h index 0aa459e5..5c138240 100644 --- a/dScripts/FvPandaSpawnerServer.h +++ b/dScripts/FvPandaSpawnerServer.h @@ -2,5 +2,5 @@ #include "CppScripts.h" class FvPandaSpawnerServer : public CppScripts::Script { - void OnCollisionPhantom(Entity *self, Entity *target) override; + void OnCollisionPhantom(Entity* self, Entity* target) override; }; diff --git a/dScripts/FvPassThroughWall.cpp b/dScripts/FvPassThroughWall.cpp index e894f923..08de5a77 100644 --- a/dScripts/FvPassThroughWall.cpp +++ b/dScripts/FvPassThroughWall.cpp @@ -3,16 +3,16 @@ #include "MissionComponent.h" void FvPassThroughWall::OnCollisionPhantom(Entity* self, Entity* target) { - auto missionComponent = target->GetComponent(); - if (missionComponent == nullptr) return; + auto missionComponent = target->GetComponent(); + if (missionComponent == nullptr) return; - //Because at the moment we do not have an ItemComponent component, we check to make sure a Maelstrom-Infused hood is equipped. There are only three in the game right now. - auto inventoryComponent = target->GetComponent(); - // If no inventory component is found then abort. - if (inventoryComponent == nullptr) return; - // If no Maelstrom hoods are equipped then abort. - if (!inventoryComponent->IsEquipped(WhiteMaelstromHood) && !inventoryComponent->IsEquipped(BlackMaelstromHood) && !inventoryComponent->IsEquipped(RedMaelstromHood)) return; + //Because at the moment we do not have an ItemComponent component, we check to make sure a Maelstrom-Infused hood is equipped. There are only three in the game right now. + auto inventoryComponent = target->GetComponent(); + // If no inventory component is found then abort. + if (inventoryComponent == nullptr) return; + // If no Maelstrom hoods are equipped then abort. + if (!inventoryComponent->IsEquipped(WhiteMaelstromHood) && !inventoryComponent->IsEquipped(BlackMaelstromHood) && !inventoryComponent->IsEquipped(RedMaelstromHood)) return; - // Progress mission Friend of the Ninja since all prerequisites are met. - missionComponent->ForceProgress(friendOfTheNinjaMissionId, friendOfTheNinjaMissionUid, 1); -} \ No newline at end of file + // Progress mission Friend of the Ninja since all prerequisites are met. + missionComponent->ForceProgress(friendOfTheNinjaMissionId, friendOfTheNinjaMissionUid, 1); +} diff --git a/dScripts/FvPassThroughWall.h b/dScripts/FvPassThroughWall.h index 4dacc74e..2f996118 100644 --- a/dScripts/FvPassThroughWall.h +++ b/dScripts/FvPassThroughWall.h @@ -3,32 +3,32 @@ class FvPassThroughWall : public CppScripts::Script { - /** - * @brief This method is called when there is a collision with self from target. - * - * @param self The Entity that called this method. - * @param target The Entity that self is targetting. - */ - void OnCollisionPhantom(Entity* self, Entity* target) override; + /** + * @brief This method is called when there is a collision with self from target. + * + * @param self The Entity that called this method. + * @param target The Entity that self is targetting. + */ + void OnCollisionPhantom(Entity* self, Entity* target) override; private: - /** - * Mission ID for Friend of the Ninjas. - */ - int32_t friendOfTheNinjaMissionId = 848; - /** - * Mission UID for Friend of the Ninjas. - */ - int32_t friendOfTheNinjaMissionUid = 1221; - /** - * Item LOT for Maelstrom-Infused White Ninja Hood - */ - int32_t WhiteMaelstromHood = 2641; - /** - * Item LOT for Maelstrom-Infused Black Ninja Hood - */ - int32_t BlackMaelstromHood = 2642; - /** - * Item LOT for Red Ninja Hood - Maelstrom Infused - */ - int32_t RedMaelstromHood = 1889; -}; \ No newline at end of file + /** + * Mission ID for Friend of the Ninjas. + */ + int32_t friendOfTheNinjaMissionId = 848; + /** + * Mission UID for Friend of the Ninjas. + */ + int32_t friendOfTheNinjaMissionUid = 1221; + /** + * Item LOT for Maelstrom-Infused White Ninja Hood + */ + int32_t WhiteMaelstromHood = 2641; + /** + * Item LOT for Maelstrom-Infused Black Ninja Hood + */ + int32_t BlackMaelstromHood = 2642; + /** + * Item LOT for Red Ninja Hood - Maelstrom Infused + */ + int32_t RedMaelstromHood = 1889; +}; diff --git a/dScripts/FvRaceSmashEggImagineServer.cpp b/dScripts/FvRaceSmashEggImagineServer.cpp index 696504e2..32dbf619 100644 --- a/dScripts/FvRaceSmashEggImagineServer.cpp +++ b/dScripts/FvRaceSmashEggImagineServer.cpp @@ -6,33 +6,33 @@ #include "RacingTaskParam.h" #include "MissionComponent.h" -void FvRaceSmashEggImagineServer::OnDie(Entity *self, Entity *killer) { - if (killer != nullptr) { - auto* destroyableComponent = killer->GetComponent(); - if (destroyableComponent != nullptr) { - destroyableComponent->SetImagination(destroyableComponent->GetImagination() + 10); - EntityManager::Instance()->SerializeEntity(killer); - } +void FvRaceSmashEggImagineServer::OnDie(Entity* self, Entity* killer) { + if (killer != nullptr) { + auto* destroyableComponent = killer->GetComponent(); + if (destroyableComponent != nullptr) { + destroyableComponent->SetImagination(destroyableComponent->GetImagination() + 10); + EntityManager::Instance()->SerializeEntity(killer); + } - // get possessor to progress statistics and tasks. - auto* possessableComponent = killer->GetComponent(); - if (possessableComponent != nullptr) { + // get possessor to progress statistics and tasks. + auto* possessableComponent = killer->GetComponent(); + if (possessableComponent != nullptr) { - auto* possessor = EntityManager::Instance()->GetEntity(possessableComponent->GetPossessor()); - if (possessor != nullptr) { + auto* possessor = EntityManager::Instance()->GetEntity(possessableComponent->GetPossessor()); + if (possessor != nullptr) { - auto* missionComponent = possessor->GetComponent(); - auto* characterComponent = possessor->GetComponent(); - if (characterComponent != nullptr) { - characterComponent->UpdatePlayerStatistic(ImaginationPowerUpsCollected); - characterComponent->UpdatePlayerStatistic(RacingSmashablesSmashed); - } - if (missionComponent == nullptr) return; - // Dragon eggs have their own smash server so we handle mission progression for them here. - missionComponent->Progress(MissionTaskType::MISSION_TASK_TYPE_RACING, 0, (LWOOBJID)RacingTaskParam::RACING_TASK_PARAM_SMASHABLES); - missionComponent->Progress(MissionTaskType::MISSION_TASK_TYPE_RACING, self->GetLOT(), (LWOOBJID)RacingTaskParam::RACING_TASK_PARAM_SMASH_SPECIFIC_SMASHABLE); - } - } + auto* missionComponent = possessor->GetComponent(); + auto* characterComponent = possessor->GetComponent(); + if (characterComponent != nullptr) { + characterComponent->UpdatePlayerStatistic(ImaginationPowerUpsCollected); + characterComponent->UpdatePlayerStatistic(RacingSmashablesSmashed); + } + if (missionComponent == nullptr) return; + // Dragon eggs have their own smash server so we handle mission progression for them here. + missionComponent->Progress(MissionTaskType::MISSION_TASK_TYPE_RACING, 0, (LWOOBJID)RacingTaskParam::RACING_TASK_PARAM_SMASHABLES); + missionComponent->Progress(MissionTaskType::MISSION_TASK_TYPE_RACING, self->GetLOT(), (LWOOBJID)RacingTaskParam::RACING_TASK_PARAM_SMASH_SPECIFIC_SMASHABLE); + } + } - } + } } diff --git a/dScripts/FvRaceSmashEggImagineServer.h b/dScripts/FvRaceSmashEggImagineServer.h index 7c682c36..dd697440 100644 --- a/dScripts/FvRaceSmashEggImagineServer.h +++ b/dScripts/FvRaceSmashEggImagineServer.h @@ -2,5 +2,5 @@ #include "CppScripts.h" class FvRaceSmashEggImagineServer : public CppScripts::Script { - void OnDie(Entity *self, Entity *killer) override; + void OnDie(Entity* self, Entity* killer) override; }; diff --git a/dScripts/GfApeSmashingQB.cpp b/dScripts/GfApeSmashingQB.cpp index 973cb728..5bba6450 100644 --- a/dScripts/GfApeSmashingQB.cpp +++ b/dScripts/GfApeSmashingQB.cpp @@ -2,21 +2,21 @@ #include "EntityManager.h" #include "GameMessages.h" -void GfApeSmashingQB::OnStartup(Entity *self) { - self->SetNetworkVar(u"lootTagOwner", self->GetVar(u"lootTagOwner")); +void GfApeSmashingQB::OnStartup(Entity* self) { + self->SetNetworkVar(u"lootTagOwner", self->GetVar(u"lootTagOwner")); } -void GfApeSmashingQB::OnTimerDone(Entity *self, std::string timerName) { - if (timerName == "anchorBreakTime") { - self->Smash(); - } +void GfApeSmashingQB::OnTimerDone(Entity* self, std::string timerName) { + if (timerName == "anchorBreakTime") { + self->Smash(); + } } -void GfApeSmashingQB::OnRebuildComplete(Entity *self, Entity *target) { - auto* ape = EntityManager::Instance()->GetEntity(self->GetVar(u"ape")); - if (ape != nullptr) { - ape->OnFireEventServerSide(target, "rebuildDone"); - GameMessages::SendPlayAnimation(self, u"smash", 1.7f); - self->AddTimer("anchorBreakTime", 1.0f); - } +void GfApeSmashingQB::OnRebuildComplete(Entity* self, Entity* target) { + auto* ape = EntityManager::Instance()->GetEntity(self->GetVar(u"ape")); + if (ape != nullptr) { + ape->OnFireEventServerSide(target, "rebuildDone"); + GameMessages::SendPlayAnimation(self, u"smash", 1.7f); + self->AddTimer("anchorBreakTime", 1.0f); + } } diff --git a/dScripts/GfApeSmashingQB.h b/dScripts/GfApeSmashingQB.h index 825fe916..0306c260 100644 --- a/dScripts/GfApeSmashingQB.h +++ b/dScripts/GfApeSmashingQB.h @@ -2,7 +2,7 @@ #include "CppScripts.h" class GfApeSmashingQB : public CppScripts::Script { - void OnStartup(Entity *self) override; - void OnTimerDone(Entity *self, std::string timerName) override; - void OnRebuildComplete(Entity *self, Entity *target) override; + void OnStartup(Entity* self) override; + void OnTimerDone(Entity* self, std::string timerName) override; + void OnRebuildComplete(Entity* self, Entity* target) override; }; diff --git a/dScripts/GfBanana.cpp b/dScripts/GfBanana.cpp index 346c9ad7..d64f1620 100644 --- a/dScripts/GfBanana.cpp +++ b/dScripts/GfBanana.cpp @@ -4,16 +4,15 @@ #include "DestroyableComponent.h" #include "EntityManager.h" -void GfBanana::SpawnBanana(Entity* self) -{ +void GfBanana::SpawnBanana(Entity* self) { auto position = self->GetPosition(); const auto rotation = self->GetRotation(); - + position.y += 12; position.x -= rotation.GetRightVector().x * 5; position.z -= rotation.GetRightVector().z * 5; - EntityInfo info {}; + EntityInfo info{}; info.pos = position; info.rot = rotation; @@ -26,21 +25,18 @@ void GfBanana::SpawnBanana(Entity* self) self->SetVar(u"banana", entity->GetObjectID()); - entity->AddDieCallback([self]() - { + entity->AddDieCallback([self]() { self->SetVar(u"banana", LWOOBJID_EMPTY); self->AddTimer("bananaTimer", 30); - }); + }); } -void GfBanana::OnStartup(Entity* self) -{ +void GfBanana::OnStartup(Entity* self) { SpawnBanana(self); } -void GfBanana::OnHit(Entity* self, Entity* attacker) -{ +void GfBanana::OnHit(Entity* self, Entity* attacker) { auto* destroyable = self->GetComponent(); destroyable->SetHealth(9999); @@ -51,15 +47,14 @@ void GfBanana::OnHit(Entity* self, Entity* attacker) auto* bananaEntity = EntityManager::Instance()->GetEntity(bananaId); - if (bananaEntity == nullptr) - { + if (bananaEntity == nullptr) { self->SetVar(u"banana", LWOOBJID_EMPTY); self->AddTimer("bananaTimer", 30); return; } - + bananaEntity->SetPosition(bananaEntity->GetPosition() - NiPoint3::UNIT_Y * 8); auto* bananaDestroyable = bananaEntity->GetComponent(); @@ -71,7 +66,7 @@ void GfBanana::OnHit(Entity* self, Entity* attacker) /* auto position = self->GetPosition(); const auto rotation = self->GetRotation(); - + position.y += 12; position.x -= rotation.GetRightVector().x * 5; position.z -= rotation.GetRightVector().z * 5; @@ -91,10 +86,8 @@ void GfBanana::OnHit(Entity* self, Entity* attacker) EntityManager::Instance()->SerializeEntity(self); } -void GfBanana::OnTimerDone(Entity* self, std::string timerName) -{ - if (timerName == "bananaTimer") - { +void GfBanana::OnTimerDone(Entity* self, std::string timerName) { + if (timerName == "bananaTimer") { SpawnBanana(self); } -} \ No newline at end of file +} diff --git a/dScripts/GfBanana.h b/dScripts/GfBanana.h index d572c8d9..8deb2396 100644 --- a/dScripts/GfBanana.h +++ b/dScripts/GfBanana.h @@ -5,9 +5,9 @@ class GfBanana final : public CppScripts::Script { public: void SpawnBanana(Entity* self); - + void OnStartup(Entity* self) override; - + void OnHit(Entity* self, Entity* attacker) override; void OnTimerDone(Entity* self, std::string timerName) override; diff --git a/dScripts/GfBananaCluster.cpp b/dScripts/GfBananaCluster.cpp index aacba224..19d1b489 100644 --- a/dScripts/GfBananaCluster.cpp +++ b/dScripts/GfBananaCluster.cpp @@ -1,15 +1,12 @@ #include "GfBananaCluster.h" #include "Entity.h" -void GfBananaCluster::OnStartup(Entity* self) -{ +void GfBananaCluster::OnStartup(Entity* self) { self->AddTimer("startup", 100); } -void GfBananaCluster::OnTimerDone(Entity* self, std::string timerName) -{ - if (timerName == "startup") - { +void GfBananaCluster::OnTimerDone(Entity* self, std::string timerName) { + if (timerName == "startup") { self->ScheduleKillAfterUpdate(nullptr); } } diff --git a/dScripts/GfCampfire.cpp b/dScripts/GfCampfire.cpp index 48170c66..95e29a9a 100644 --- a/dScripts/GfCampfire.cpp +++ b/dScripts/GfCampfire.cpp @@ -17,10 +17,9 @@ void GfCampfire::OnStartup(Entity* self) { render->PlayEffect(295, u"running", "Burn"); } -void GfCampfire::OnFireEventServerSide(Entity *self, Entity *sender, std::string args, int32_t param1, int32_t param2, - int32_t param3) { - if (args == "physicsReady") - { +void GfCampfire::OnFireEventServerSide(Entity* self, Entity* sender, std::string args, int32_t param1, int32_t param2, + int32_t param3) { + if (args == "physicsReady") { auto* render = static_cast(self->GetComponent(COMPONENT_TYPE_RENDER)); render->PlayEffect(295, u"running", "Burn"); @@ -45,14 +44,12 @@ void GfCampfire::OnProximityUpdate(Entity* self, Entity* entering, std::string n auto* missionComponet = entering->GetComponent(); - if (missionComponet != nullptr) - { + if (missionComponet != nullptr) { missionComponet->ForceProgress(440, 658, 1); } } } - } - else { + } else { int32_t counter = self->GetI32(u"counter"); if (counter > 0) { counter = counter - 1; @@ -65,22 +62,21 @@ void GfCampfire::OnProximityUpdate(Entity* self, Entity* entering, std::string n } } -void GfCampfire::OnSkillEventFired(Entity *self, Entity *caster, const std::string &message) { - if (message == "waterspray" && self->GetVar(u"isBurning")) { - auto* renderComponent = self->GetComponent(); - if (renderComponent != nullptr) { - renderComponent->StopEffect("Burn"); - renderComponent->PlayEffect(295, u"idle", "Off"); +void GfCampfire::OnSkillEventFired(Entity* self, Entity* caster, const std::string& message) { + if (message == "waterspray" && self->GetVar(u"isBurning")) { + auto* renderComponent = self->GetComponent(); + if (renderComponent != nullptr) { + renderComponent->StopEffect("Burn"); + renderComponent->PlayEffect(295, u"idle", "Off"); - self->SetVar(u"isBurning", false); - self->AddTimer("FireRestart", 37); - } - } + self->SetVar(u"isBurning", false); + self->AddTimer("FireRestart", 37); + } + } } void GfCampfire::OnTimerDone(Entity* self, std::string timerName) { - if (timerName == "TimeBetweenCast") - { + if (timerName == "TimeBetweenCast") { /* self->AddTimer("TimeBetweenCast", FIRE_COOLDOWN); @@ -90,15 +86,15 @@ void GfCampfire::OnTimerDone(Entity* self, std::string timerName) { if (entering == nullptr) { - + } */ } else if (timerName == "FireRestart" && !self->GetVar(u"isBurning")) { - auto* renderComponent = self->GetComponent(); - if (renderComponent != nullptr) { - renderComponent->StopEffect("Off"); - renderComponent->PlayEffect(295, u"running", "Burn"); - self->SetVar(u"isBurning", true); - } + auto* renderComponent = self->GetComponent(); + if (renderComponent != nullptr) { + renderComponent->StopEffect("Off"); + renderComponent->PlayEffect(295, u"running", "Burn"); + self->SetVar(u"isBurning", true); + } } } diff --git a/dScripts/GfCampfire.h b/dScripts/GfCampfire.h index 9e678419..b1d61721 100644 --- a/dScripts/GfCampfire.h +++ b/dScripts/GfCampfire.h @@ -1,16 +1,16 @@ #pragma once #include "CppScripts.h" -class GfCampfire : public CppScripts::Script +class GfCampfire : public CppScripts::Script { public: void OnStartup(Entity* self) override; - void OnFireEventServerSide(Entity *self, Entity *sender, std::string args, int32_t param1, int32_t param2, - int32_t param3) override; + void OnFireEventServerSide(Entity* self, Entity* sender, std::string args, int32_t param1, int32_t param2, + int32_t param3) override; void OnProximityUpdate(Entity* self, Entity* entering, std::string name, std::string status) override; void OnTimerDone(Entity* self, std::string timerName) override; - void OnSkillEventFired(Entity *self, Entity *caster, const std::string &message) override; + void OnSkillEventFired(Entity* self, Entity* caster, const std::string& message) override; private: int32_t m_skillCastId = 43; int32_t FIRE_COOLDOWN = 2; -}; \ No newline at end of file +}; diff --git a/dScripts/GfCaptainsCannon.cpp b/dScripts/GfCaptainsCannon.cpp index ee973a13..7d67c781 100644 --- a/dScripts/GfCaptainsCannon.cpp +++ b/dScripts/GfCaptainsCannon.cpp @@ -3,90 +3,81 @@ #include "EntityManager.h" #include "MissionComponent.h" -void GfCaptainsCannon::OnUse(Entity* self, Entity* user) -{ - if (self->GetVar(u"bIsInUse")) - { - return; - } - - self->SetVar(u"userID", user->GetObjectID()); +void GfCaptainsCannon::OnUse(Entity* self, Entity* user) { + if (self->GetVar(u"bIsInUse")) { + return; + } - self->SetVar(u"bIsInUse", true); - self->SetNetworkVar(u"bIsInUse", true); + self->SetVar(u"userID", user->GetObjectID()); - GameMessages::SendSetStunned(user->GetObjectID(), PUSH, user->GetSystemAddress(), - LWOOBJID_EMPTY, true, true, true, true, true, true, true, true - ); + self->SetVar(u"bIsInUse", true); + self->SetNetworkVar(u"bIsInUse", true); - auto position = self->GetPosition(); - auto forward = self->GetRotation().GetForwardVector(); + GameMessages::SendSetStunned(user->GetObjectID(), PUSH, user->GetSystemAddress(), + LWOOBJID_EMPTY, true, true, true, true, true, true, true, true + ); - position.x += forward.x * -3; - position.z += forward.z * -3; + auto position = self->GetPosition(); + auto forward = self->GetRotation().GetForwardVector(); - auto rotation = self->GetRotation(); + position.x += forward.x * -3; + position.z += forward.z * -3; - GameMessages::SendTeleport(user->GetObjectID(), position, rotation, user->GetSystemAddress()); + auto rotation = self->GetRotation(); - GameMessages::SendPlayAnimation(user, u"cannon-strike-no-equip"); + GameMessages::SendTeleport(user->GetObjectID(), position, rotation, user->GetSystemAddress()); - GameMessages::SendPlayFXEffect(user->GetObjectID(), 6039, u"hook", "hook", LWOOBJID_EMPTY, 1, 1, true); + GameMessages::SendPlayAnimation(user, u"cannon-strike-no-equip"); - self->AddTimer("FireCannon", 1.667f); + GameMessages::SendPlayFXEffect(user->GetObjectID(), 6039, u"hook", "hook", LWOOBJID_EMPTY, 1, 1, true); + + self->AddTimer("FireCannon", 1.667f); } -void GfCaptainsCannon::OnTimerDone(Entity* self, std::string timerName) -{ - const auto playerId = self->GetVar(u"userID"); +void GfCaptainsCannon::OnTimerDone(Entity* self, std::string timerName) { + const auto playerId = self->GetVar(u"userID"); - auto* player = EntityManager::Instance()->GetEntity(playerId); + auto* player = EntityManager::Instance()->GetEntity(playerId); - if (player == nullptr) - { - self->SetVar(u"bIsInUse", false); - self->SetNetworkVar(u"bIsInUse", false); + if (player == nullptr) { + self->SetVar(u"bIsInUse", false); + self->SetNetworkVar(u"bIsInUse", false); - return; - } + return; + } - if (timerName == "FireCannon") - { - float cinematicTime = 6.3f; + if (timerName == "FireCannon") { + float cinematicTime = 6.3f; - GameMessages::SendPlayCinematic(playerId, u"Cannon_Cam", player->GetSystemAddress()); + GameMessages::SendPlayCinematic(playerId, u"Cannon_Cam", player->GetSystemAddress()); - self->AddTimer("cinematicTimer", cinematicTime); + self->AddTimer("cinematicTimer", cinematicTime); - const auto sharkObjects = EntityManager::Instance()->GetEntitiesInGroup("SharkCannon"); + const auto sharkObjects = EntityManager::Instance()->GetEntitiesInGroup("SharkCannon"); - for (auto* shark : sharkObjects) - { - if (shark->GetLOT() != m_SharkItemID) continue; + for (auto* shark : sharkObjects) { + if (shark->GetLOT() != m_SharkItemID) continue; - GameMessages::SendPlayAnimation(shark, u"cannon"); - } + GameMessages::SendPlayAnimation(shark, u"cannon"); + } - GameMessages::SendPlay2DAmbientSound(player, "{7457d85c-4537-4317-ac9d-2f549219ea87}"); - } - else if (timerName == "cinematicTimer") - { - GameMessages::SendSetStunned(playerId, POP, player->GetSystemAddress(), - LWOOBJID_EMPTY, true, true, true, true, true, true, true, true - ); + GameMessages::SendPlay2DAmbientSound(player, "{7457d85c-4537-4317-ac9d-2f549219ea87}"); + } else if (timerName == "cinematicTimer") { + GameMessages::SendSetStunned(playerId, POP, player->GetSystemAddress(), + LWOOBJID_EMPTY, true, true, true, true, true, true, true, true + ); - self->SetVar(u"bIsInUse", false); - self->SetNetworkVar(u"bIsInUse", false); + self->SetVar(u"bIsInUse", false); + self->SetNetworkVar(u"bIsInUse", false); - GameMessages::SendStopFXEffect(player, true, "hook"); + GameMessages::SendStopFXEffect(player, true, "hook"); - auto* missionComponent = player->GetComponent(); + auto* missionComponent = player->GetComponent(); - if (missionComponent != nullptr) - { - missionComponent->ForceProgress(601, 910, 1); - } + if (missionComponent != nullptr) { + missionComponent->ForceProgress(601, 910, 1); + } - GameMessages::SendTerminateInteraction(playerId, FROM_INTERACTION, self->GetObjectID()); - } + GameMessages::SendTerminateInteraction(playerId, FROM_INTERACTION, self->GetObjectID()); + } } diff --git a/dScripts/GfCaptainsCannon.h b/dScripts/GfCaptainsCannon.h index 44dd791c..23429b5d 100644 --- a/dScripts/GfCaptainsCannon.h +++ b/dScripts/GfCaptainsCannon.h @@ -1,11 +1,11 @@ #pragma once #include "CppScripts.h" -class GfCaptainsCannon : public CppScripts::Script +class GfCaptainsCannon : public CppScripts::Script { public: - void OnUse(Entity* self, Entity* user) override; - void OnTimerDone(Entity* self, std::string timerName) override; + void OnUse(Entity* self, Entity* user) override; + void OnTimerDone(Entity* self, std::string timerName) override; private: int32_t m_SharkItemID = 7343; }; diff --git a/dScripts/GfJailWalls.cpp b/dScripts/GfJailWalls.cpp index da547d0b..56710832 100644 --- a/dScripts/GfJailWalls.cpp +++ b/dScripts/GfJailWalls.cpp @@ -2,34 +2,28 @@ #include "dZoneManager.h" #include "GeneralUtils.h" -void GfJailWalls::OnRebuildComplete(Entity* self, Entity* target) -{ - const auto wall = GeneralUtils::UTF16ToWTF8(self->GetVar(u"Wall")); +void GfJailWalls::OnRebuildComplete(Entity* self, Entity* target) { + const auto wall = GeneralUtils::UTF16ToWTF8(self->GetVar(u"Wall")); - for (auto* spawner : dZoneManager::Instance()->GetSpawnersByName("Jail0" + wall)) - { - spawner->Deactivate(); - } - - for (auto* spawner : dZoneManager::Instance()->GetSpawnersByName("JailCaptain0" + wall)) - { - spawner->Deactivate(); - } + for (auto* spawner : dZoneManager::Instance()->GetSpawnersByName("Jail0" + wall)) { + spawner->Deactivate(); + } + + for (auto* spawner : dZoneManager::Instance()->GetSpawnersByName("JailCaptain0" + wall)) { + spawner->Deactivate(); + } } -void GfJailWalls::OnRebuildNotifyState(Entity* self, eRebuildState state) -{ - if (state != eRebuildState::REBUILD_RESETTING) return; +void GfJailWalls::OnRebuildNotifyState(Entity* self, eRebuildState state) { + if (state != eRebuildState::REBUILD_RESETTING) return; - const auto wall = GeneralUtils::UTF16ToWTF8(self->GetVar(u"Wall")); + const auto wall = GeneralUtils::UTF16ToWTF8(self->GetVar(u"Wall")); - for (auto* spawner : dZoneManager::Instance()->GetSpawnersByName("Jail0" + wall)) - { - spawner->Activate(); - } - - for (auto* spawner : dZoneManager::Instance()->GetSpawnersByName("JailCaptain0" + wall)) - { - spawner->Activate(); - } + for (auto* spawner : dZoneManager::Instance()->GetSpawnersByName("Jail0" + wall)) { + spawner->Activate(); + } + + for (auto* spawner : dZoneManager::Instance()->GetSpawnersByName("JailCaptain0" + wall)) { + spawner->Activate(); + } } diff --git a/dScripts/GfJailWalls.h b/dScripts/GfJailWalls.h index 8f3ad54b..f755f4d7 100644 --- a/dScripts/GfJailWalls.h +++ b/dScripts/GfJailWalls.h @@ -1,9 +1,9 @@ #pragma once #include "CppScripts.h" -class GfJailWalls final : public CppScripts::Script +class GfJailWalls final : public CppScripts::Script { public: - void OnRebuildComplete(Entity* self, Entity* target) override; - void OnRebuildNotifyState(Entity* self, eRebuildState state) override; + void OnRebuildComplete(Entity* self, Entity* target) override; + void OnRebuildNotifyState(Entity* self, eRebuildState state) override; }; diff --git a/dScripts/GfJailkeepMission.cpp b/dScripts/GfJailkeepMission.cpp index bf3b25f8..59f8db0e 100644 --- a/dScripts/GfJailkeepMission.cpp +++ b/dScripts/GfJailkeepMission.cpp @@ -2,39 +2,37 @@ #include "MissionComponent.h" #include "Character.h" -void GfJailkeepMission::OnMissionDialogueOK(Entity* self, Entity* target, int missionID, MissionState missionState) -{ - auto* missionComponent = target->GetComponent(); - if (missionComponent == nullptr) - return; +void GfJailkeepMission::OnMissionDialogueOK(Entity* self, Entity* target, int missionID, MissionState missionState) { + auto* missionComponent = target->GetComponent(); + if (missionComponent == nullptr) + return; - if (missionID == 385 && missionState == MissionState::MISSION_STATE_AVAILABLE) { - missionComponent->AcceptMission(386, true); - missionComponent->AcceptMission(387, true); - missionComponent->AcceptMission(388, true); - missionComponent->AcceptMission(390, true); - } else if (missionID == 385 && missionState == MissionState::MISSION_STATE_COMPLETE_READY_TO_COMPLETE) { - auto* character = target->GetCharacter(); - if (character != nullptr && character->GetPlayerFlag(68)) { - missionComponent->AcceptMission(701); - missionComponent->AcceptMission(702); - missionComponent->AcceptMission(703); - missionComponent->AcceptMission(704); - } - } + if (missionID == 385 && missionState == MissionState::MISSION_STATE_AVAILABLE) { + missionComponent->AcceptMission(386, true); + missionComponent->AcceptMission(387, true); + missionComponent->AcceptMission(388, true); + missionComponent->AcceptMission(390, true); + } else if (missionID == 385 && missionState == MissionState::MISSION_STATE_COMPLETE_READY_TO_COMPLETE) { + auto* character = target->GetCharacter(); + if (character != nullptr && character->GetPlayerFlag(68)) { + missionComponent->AcceptMission(701); + missionComponent->AcceptMission(702); + missionComponent->AcceptMission(703); + missionComponent->AcceptMission(704); + } + } } -void GfJailkeepMission::OnUse(Entity* self, Entity* user) -{ - auto* missionComponent = user->GetComponent(); - if (missionComponent == nullptr) - return; +void GfJailkeepMission::OnUse(Entity* self, Entity* user) { + auto* missionComponent = user->GetComponent(); + if (missionComponent == nullptr) + return; - if (missionComponent->GetMissionState(385) == MissionState::MISSION_STATE_ACTIVE) { - missionComponent->AcceptMission(386, true); - missionComponent->AcceptMission(387, true); - missionComponent->AcceptMission(388, true); - missionComponent->AcceptMission(390, true); - } + if (missionComponent->GetMissionState(385) == MissionState::MISSION_STATE_ACTIVE) { + missionComponent->AcceptMission(386, true); + missionComponent->AcceptMission(387, true); + missionComponent->AcceptMission(388, true); + missionComponent->AcceptMission(390, true); + } } diff --git a/dScripts/GfJailkeepMission.h b/dScripts/GfJailkeepMission.h index 6c1b2a3e..f9410032 100644 --- a/dScripts/GfJailkeepMission.h +++ b/dScripts/GfJailkeepMission.h @@ -1,9 +1,9 @@ #pragma once #include "CppScripts.h" -class GfJailkeepMission final : public CppScripts::Script +class GfJailkeepMission final : public CppScripts::Script { public: - void OnUse(Entity* self, Entity* user) override; + void OnUse(Entity* self, Entity* user) override; void OnMissionDialogueOK(Entity* self, Entity* target, int missionID, MissionState missionState) override; }; diff --git a/dScripts/GfOrgan.h b/dScripts/GfOrgan.h index 1ebd66a6..6af2d554 100644 --- a/dScripts/GfOrgan.h +++ b/dScripts/GfOrgan.h @@ -8,4 +8,4 @@ public: void OnTimerDone(Entity* self, std::string timerName); private: bool m_canUse; -}; \ No newline at end of file +}; diff --git a/dScripts/GfTikiTorch.cpp b/dScripts/GfTikiTorch.cpp index dd1c14a7..3a06b054 100644 --- a/dScripts/GfTikiTorch.cpp +++ b/dScripts/GfTikiTorch.cpp @@ -27,10 +27,9 @@ void GfTikiTorch::OnUse(Entity* self, Entity* killer) { void GfTikiTorch::OnTimerDone(Entity* self, std::string timerName) { if (timerName == "Relight") { LightTorch(self); - } - else if (timerName == "InteractionCooldown") { + } else if (timerName == "InteractionCooldown") { Entity* player = EntityManager::Instance()->GetEntity(self->GetI64(u"userID")); - + if (player != nullptr && player->GetCharacter()) { GameMessages::SendTerminateInteraction(player->GetObjectID(), FROM_INTERACTION, self->GetObjectID()); } @@ -45,32 +44,32 @@ void GfTikiTorch::LightTorch(Entity* self) { auto* renderComponent = static_cast(self->GetComponent(COMPONENT_TYPE_RENDER)); if (renderComponent == nullptr) return; - + self->SetBoolean(u"isInUse", false); renderComponent->PlayEffect(611, u"fire", "tikitorch"); self->SetBoolean(u"isBurning", true); } -void GfTikiTorch::OnSkillEventFired(Entity *self, Entity *caster, const std::string &message) { - if (self->GetBoolean(u"isBurning") && message == "waterspray") { - GameMessages::SendPlayAnimation(self, u"water"); +void GfTikiTorch::OnSkillEventFired(Entity* self, Entity* caster, const std::string& message) { + if (self->GetBoolean(u"isBurning") && message == "waterspray") { + GameMessages::SendPlayAnimation(self, u"water"); - auto* renderComponent = self->GetComponent(); - if (renderComponent != nullptr) { - renderComponent->StopEffect("tikitorch"); - renderComponent->PlayEffect(611, u"water", "water"); - renderComponent->PlayEffect(611, u"steam", "steam"); - } + auto* renderComponent = self->GetComponent(); + if (renderComponent != nullptr) { + renderComponent->StopEffect("tikitorch"); + renderComponent->PlayEffect(611, u"water", "water"); + renderComponent->PlayEffect(611, u"steam", "steam"); + } - auto* casterMissionComponent = caster->GetComponent(); - if (casterMissionComponent != nullptr) { - for (const auto missionID : m_missions) { - casterMissionComponent->ForceProgressTaskType(missionID, static_cast(MissionTaskType::MISSION_TASK_TYPE_SCRIPT), 1); - } - } + auto* casterMissionComponent = caster->GetComponent(); + if (casterMissionComponent != nullptr) { + for (const auto missionID : m_missions) { + casterMissionComponent->ForceProgressTaskType(missionID, static_cast(MissionTaskType::MISSION_TASK_TYPE_SCRIPT), 1); + } + } - self->AddTimer("Relight", 7.0f); - self->SetBoolean(u"isBurning", false); - } + self->AddTimer("Relight", 7.0f); + self->SetBoolean(u"isBurning", false); + } } diff --git a/dScripts/GfTikiTorch.h b/dScripts/GfTikiTorch.h index e9046ddc..5d3de0a8 100644 --- a/dScripts/GfTikiTorch.h +++ b/dScripts/GfTikiTorch.h @@ -1,17 +1,17 @@ #pragma once #include "CppScripts.h" -class GfTikiTorch : public CppScripts::Script +class GfTikiTorch : public CppScripts::Script { public: void OnStartup(Entity* self) override; void OnUse(Entity* self, Entity* killer) override; void OnTimerDone(Entity* self, std::string timerName) override; - void OnSkillEventFired(Entity* self, Entity* caster, const std::string& message) override; + void OnSkillEventFired(Entity* self, Entity* caster, const std::string& message) override; private: void LightTorch(Entity* self); LOT m_imaginationlot = 935; int32_t m_numspawn = 3; - std::vector m_missions = {472, 1429, 1527, 1564, 1601}; -}; \ No newline at end of file + std::vector m_missions = { 472, 1429, 1527, 1564, 1601 }; +}; diff --git a/dScripts/GrowingFlower.cpp b/dScripts/GrowingFlower.cpp index 1acb2455..7b495841 100644 --- a/dScripts/GrowingFlower.cpp +++ b/dScripts/GrowingFlower.cpp @@ -1,35 +1,35 @@ #include "GrowingFlower.h" #include "MissionComponent.h" -void GrowingFlower::OnSkillEventFired(Entity *self, Entity *target, const std::string &message) { - if (!self->GetVar(u"blooming") && (message == "waterspray" || message == "shovelgrow")) { - self->SetVar(u"blooming", true); - self->SetNetworkVar(u"blooming", true); - self->AddTimer("FlowerDie", GrowingFlower::aliveTime); +void GrowingFlower::OnSkillEventFired(Entity* self, Entity* target, const std::string& message) { + if (!self->GetVar(u"blooming") && (message == "waterspray" || message == "shovelgrow")) { + self->SetVar(u"blooming", true); + self->SetNetworkVar(u"blooming", true); + self->AddTimer("FlowerDie", GrowingFlower::aliveTime); - const auto mission1 = self->GetVar(u"missionID"); - const auto mission2 = self->GetVar(u"missionID2"); + const auto mission1 = self->GetVar(u"missionID"); + const auto mission2 = self->GetVar(u"missionID2"); - LootGenerator::Instance().DropActivityLoot(target, self, self->GetLOT(), 0); + LootGenerator::Instance().DropActivityLoot(target, self, self->GetLOT(), 0); - auto* missionComponent = target->GetComponent(); - if (missionComponent != nullptr) { - for (const auto mission : achievementIDs) - missionComponent->ForceProgressTaskType(mission, static_cast(MissionTaskType::MISSION_TASK_TYPE_SCRIPT), 1); + auto* missionComponent = target->GetComponent(); + if (missionComponent != nullptr) { + for (const auto mission : achievementIDs) + missionComponent->ForceProgressTaskType(mission, static_cast(MissionTaskType::MISSION_TASK_TYPE_SCRIPT), 1); - if (mission1 && missionComponent->GetMissionState(mission1) == MissionState::MISSION_STATE_ACTIVE) - missionComponent->ForceProgressTaskType(mission1, static_cast(MissionTaskType::MISSION_TASK_TYPE_SCRIPT), 1); + if (mission1 && missionComponent->GetMissionState(mission1) == MissionState::MISSION_STATE_ACTIVE) + missionComponent->ForceProgressTaskType(mission1, static_cast(MissionTaskType::MISSION_TASK_TYPE_SCRIPT), 1); - if (mission2 && missionComponent->GetMissionState(mission2) == MissionState::MISSION_STATE_ACTIVE) - missionComponent->ForceProgressTaskType(mission2, static_cast(MissionTaskType::MISSION_TASK_TYPE_SCRIPT), 1); - } - } + if (mission2 && missionComponent->GetMissionState(mission2) == MissionState::MISSION_STATE_ACTIVE) + missionComponent->ForceProgressTaskType(mission2, static_cast(MissionTaskType::MISSION_TASK_TYPE_SCRIPT), 1); + } + } } -void GrowingFlower::OnTimerDone(Entity *self, std::string message) { - if (message == "FlowerDie") { - self->Smash(); - } +void GrowingFlower::OnTimerDone(Entity* self, std::string message) { + if (message == "FlowerDie") { + self->Smash(); + } } const std::vector GrowingFlower::achievementIDs = { 143, 152, 153, 1409, 1507, 1544, 1581, 1845 }; diff --git a/dScripts/GrowingFlower.h b/dScripts/GrowingFlower.h index 92fc0035..b7090855 100644 --- a/dScripts/GrowingFlower.h +++ b/dScripts/GrowingFlower.h @@ -3,9 +3,9 @@ class GrowingFlower : public CppScripts::Script { public: - void OnSkillEventFired(Entity* self, Entity* target, const std::string& message) override; - void OnTimerDone(Entity* self, std::string message) override; + void OnSkillEventFired(Entity* self, Entity* target, const std::string& message) override; + void OnTimerDone(Entity* self, std::string message) override; private: - static const std::vector achievementIDs; - constexpr static const float aliveTime = 16.0f; -}; \ No newline at end of file + static const std::vector achievementIDs; + constexpr static const float aliveTime = 16.0f; +}; diff --git a/dScripts/HydrantBroken.cpp b/dScripts/HydrantBroken.cpp index 2b620a21..1409c9fb 100644 --- a/dScripts/HydrantBroken.cpp +++ b/dScripts/HydrantBroken.cpp @@ -2,43 +2,36 @@ #include "EntityManager.h" #include "GameMessages.h" -void HydrantBroken::OnStartup(Entity* self) -{ - self->AddTimer("playEffect", 1); +void HydrantBroken::OnStartup(Entity* self) { + self->AddTimer("playEffect", 1); - const auto hydrant = "hydrant" + self->GetVar(u"hydrant"); + const auto hydrant = "hydrant" + self->GetVar(u"hydrant"); - const auto bouncers = EntityManager::Instance()->GetEntitiesInGroup(hydrant); + const auto bouncers = EntityManager::Instance()->GetEntitiesInGroup(hydrant); - for (auto* bouncer : bouncers) - { - self->SetVar(u"bouncer", bouncer->GetObjectID()); + for (auto* bouncer : bouncers) { + self->SetVar(u"bouncer", bouncer->GetObjectID()); - GameMessages::SendBouncerActiveStatus(bouncer->GetObjectID(), true, UNASSIGNED_SYSTEM_ADDRESS); + GameMessages::SendBouncerActiveStatus(bouncer->GetObjectID(), true, UNASSIGNED_SYSTEM_ADDRESS); - GameMessages::SendNotifyObject(bouncer->GetObjectID(), self->GetObjectID(), u"enableCollision", UNASSIGNED_SYSTEM_ADDRESS); - } + GameMessages::SendNotifyObject(bouncer->GetObjectID(), self->GetObjectID(), u"enableCollision", UNASSIGNED_SYSTEM_ADDRESS); + } - self->AddTimer("KillBroken", 25); + self->AddTimer("KillBroken", 25); } -void HydrantBroken::OnTimerDone(Entity* self, std::string timerName) -{ - if (timerName == "KillBroken") - { - auto* bouncer = EntityManager::Instance()->GetEntity(self->GetVar(u"bouncer")); +void HydrantBroken::OnTimerDone(Entity* self, std::string timerName) { + if (timerName == "KillBroken") { + auto* bouncer = EntityManager::Instance()->GetEntity(self->GetVar(u"bouncer")); - if (bouncer != nullptr) - { - GameMessages::SendBouncerActiveStatus(bouncer->GetObjectID(), false, UNASSIGNED_SYSTEM_ADDRESS); + if (bouncer != nullptr) { + GameMessages::SendBouncerActiveStatus(bouncer->GetObjectID(), false, UNASSIGNED_SYSTEM_ADDRESS); - GameMessages::SendNotifyObject(bouncer->GetObjectID(), self->GetObjectID(), u"disableCollision", UNASSIGNED_SYSTEM_ADDRESS); - } + GameMessages::SendNotifyObject(bouncer->GetObjectID(), self->GetObjectID(), u"disableCollision", UNASSIGNED_SYSTEM_ADDRESS); + } - self->Kill(); - } - else if (timerName == "playEffect") - { - GameMessages::SendPlayFXEffect(self->GetObjectID(), 384, u"water", "water", LWOOBJID_EMPTY, 1, 1, true); - } + self->Kill(); + } else if (timerName == "playEffect") { + GameMessages::SendPlayFXEffect(self->GetObjectID(), 384, u"water", "water", LWOOBJID_EMPTY, 1, 1, true); + } } diff --git a/dScripts/HydrantBroken.h b/dScripts/HydrantBroken.h index 65f38604..9ed1f4ab 100644 --- a/dScripts/HydrantBroken.h +++ b/dScripts/HydrantBroken.h @@ -1,9 +1,9 @@ #pragma once #include "CppScripts.h" -class HydrantBroken : public CppScripts::Script +class HydrantBroken : public CppScripts::Script { public: void OnStartup(Entity* self) override; void OnTimerDone(Entity* self, std::string timerName) override; -}; \ No newline at end of file +}; diff --git a/dScripts/HydrantSmashable.cpp b/dScripts/HydrantSmashable.cpp index 5cdf84c9..20baa58b 100644 --- a/dScripts/HydrantSmashable.cpp +++ b/dScripts/HydrantSmashable.cpp @@ -2,20 +2,19 @@ #include "EntityManager.h" #include "GeneralUtils.h" -void HydrantSmashable::OnDie(Entity* self, Entity* killer) -{ - const auto hydrantName = self->GetVar(u"hydrant"); +void HydrantSmashable::OnDie(Entity* self, Entity* killer) { + const auto hydrantName = self->GetVar(u"hydrant"); - LDFBaseData* data = new LDFData(u"hydrant", GeneralUtils::UTF16ToWTF8(hydrantName)); + LDFBaseData* data = new LDFData(u"hydrant", GeneralUtils::UTF16ToWTF8(hydrantName)); - EntityInfo info {}; - info.lot = HYDRANT_BROKEN; - info.pos = self->GetPosition(); - info.rot = self->GetRotation(); - info.settings = {data}; - info.spawnerID = self->GetSpawnerID(); + EntityInfo info{}; + info.lot = HYDRANT_BROKEN; + info.pos = self->GetPosition(); + info.rot = self->GetRotation(); + info.settings = { data }; + info.spawnerID = self->GetSpawnerID(); - auto* hydrant = EntityManager::Instance()->CreateEntity(info); + auto* hydrant = EntityManager::Instance()->CreateEntity(info); - EntityManager::Instance()->ConstructEntity(hydrant); + EntityManager::Instance()->ConstructEntity(hydrant); } diff --git a/dScripts/HydrantSmashable.h b/dScripts/HydrantSmashable.h index 90b0f3a6..156f2e8f 100644 --- a/dScripts/HydrantSmashable.h +++ b/dScripts/HydrantSmashable.h @@ -7,4 +7,4 @@ public: void OnDie(Entity* self, Entity* killer) override; private: LOT HYDRANT_BROKEN = 7328; -}; \ No newline at end of file +}; diff --git a/dScripts/ImaginationBackpackHealServer.cpp b/dScripts/ImaginationBackpackHealServer.cpp index 1d7da2c5..1e0d35cf 100644 --- a/dScripts/ImaginationBackpackHealServer.cpp +++ b/dScripts/ImaginationBackpackHealServer.cpp @@ -2,19 +2,19 @@ #include "GameMessages.h" #include "MissionComponent.h" -void ImaginationBackpackHealServer::OnSkillEventFired(Entity *self, Entity *caster, const std::string &message) { - if (message == "CastImaginationBackpack") { - auto healMission = self->GetVar(u"FXOffMis"); - if (healMission == 0) - healMission = self->GetVar(u"FXOnMis"); - if (healMission == 0) - return; +void ImaginationBackpackHealServer::OnSkillEventFired(Entity* self, Entity* caster, const std::string& message) { + if (message == "CastImaginationBackpack") { + auto healMission = self->GetVar(u"FXOffMis"); + if (healMission == 0) + healMission = self->GetVar(u"FXOnMis"); + if (healMission == 0) + return; - auto* missionComponent = caster->GetComponent(); - if (missionComponent != nullptr && missionComponent->GetMissionState(healMission) == MissionState::MISSION_STATE_ACTIVE) { - missionComponent->Progress(MissionTaskType::MISSION_TASK_TYPE_SCRIPT, self->GetLOT()); - GameMessages::SendNotifyClientObject(self->GetObjectID(), u"ClearMaelstrom", 0, 0, - caster->GetObjectID(), "", caster->GetSystemAddress()); - } - } + auto* missionComponent = caster->GetComponent(); + if (missionComponent != nullptr && missionComponent->GetMissionState(healMission) == MissionState::MISSION_STATE_ACTIVE) { + missionComponent->Progress(MissionTaskType::MISSION_TASK_TYPE_SCRIPT, self->GetLOT()); + GameMessages::SendNotifyClientObject(self->GetObjectID(), u"ClearMaelstrom", 0, 0, + caster->GetObjectID(), "", caster->GetSystemAddress()); + } + } } diff --git a/dScripts/ImaginationBackpackHealServer.h b/dScripts/ImaginationBackpackHealServer.h index 387f38d7..dbe5ab01 100644 --- a/dScripts/ImaginationBackpackHealServer.h +++ b/dScripts/ImaginationBackpackHealServer.h @@ -2,5 +2,5 @@ #include "CppScripts.h" class ImaginationBackpackHealServer : public CppScripts::Script { - void OnSkillEventFired(Entity *self, Entity *caster, const std::string &message) override; + void OnSkillEventFired(Entity* self, Entity* caster, const std::string& message) override; }; diff --git a/dScripts/ImaginationShrineServer.cpp b/dScripts/ImaginationShrineServer.cpp index 54c02614..267d0480 100644 --- a/dScripts/ImaginationShrineServer.cpp +++ b/dScripts/ImaginationShrineServer.cpp @@ -1,19 +1,16 @@ #include "ImaginationShrineServer.h" #include "RebuildComponent.h" -void ImaginationShrineServer::OnUse(Entity* self, Entity* user) -{ - // If the rebuild component is complete, use the shrine - auto* rebuildComponent = self->GetComponent(); +void ImaginationShrineServer::OnUse(Entity* self, Entity* user) { + // If the rebuild component is complete, use the shrine + auto* rebuildComponent = self->GetComponent(); - if (rebuildComponent == nullptr) - { - return; - } + if (rebuildComponent == nullptr) { + return; + } - if (rebuildComponent->GetState() == REBUILD_COMPLETED) - { - // Use the shrine - BaseUse(self, user); - } + if (rebuildComponent->GetState() == REBUILD_COMPLETED) { + // Use the shrine + BaseUse(self, user); + } } diff --git a/dScripts/ImaginationShrineServer.h b/dScripts/ImaginationShrineServer.h index 6bbf84b5..bef137e9 100644 --- a/dScripts/ImaginationShrineServer.h +++ b/dScripts/ImaginationShrineServer.h @@ -5,6 +5,6 @@ class ImaginationShrineServer : public BaseInteractDropLootServer { public: - void OnUse(Entity* self, Entity* user) override; + void OnUse(Entity* self, Entity* user) override; }; diff --git a/dScripts/ImgBrickConsoleQB.cpp b/dScripts/ImgBrickConsoleQB.cpp index 0dfb6288..4a12324f 100644 --- a/dScripts/ImgBrickConsoleQB.cpp +++ b/dScripts/ImgBrickConsoleQB.cpp @@ -10,280 +10,231 @@ int32_t ImgBrickConsoleQB::ResetBricks = 30; int32_t ImgBrickConsoleQB::ResetConsole = 60; int32_t ImgBrickConsoleQB::ResetInteract = 45; -void ImgBrickConsoleQB::OnStartup(Entity* self) -{ - self->SetNetworkVar(u"used", false); +void ImgBrickConsoleQB::OnStartup(Entity* self) { + self->SetNetworkVar(u"used", false); - self->AddTimer("reset", ResetBricks); + self->AddTimer("reset", ResetBricks); } -void ImgBrickConsoleQB::OnUse(Entity* self, Entity* user) -{ - auto* rebuildComponent = self->GetComponent(); +void ImgBrickConsoleQB::OnUse(Entity* self, Entity* user) { + auto* rebuildComponent = self->GetComponent(); - if (rebuildComponent->GetState() == REBUILD_COMPLETED) - { - if (!self->GetNetworkVar(u"used")) - { - const auto consoles = EntityManager::Instance()->GetEntitiesInGroup("Console"); + if (rebuildComponent->GetState() == REBUILD_COMPLETED) { + if (!self->GetNetworkVar(u"used")) { + const auto consoles = EntityManager::Instance()->GetEntitiesInGroup("Console"); - auto bothBuilt = false; + auto bothBuilt = false; - for (auto* console : consoles) - { - auto* consoleRebuildComponent = console->GetComponent(); + for (auto* console : consoles) { + auto* consoleRebuildComponent = console->GetComponent(); - if (consoleRebuildComponent->GetState() != REBUILD_COMPLETED) - { - continue; - } + if (consoleRebuildComponent->GetState() != REBUILD_COMPLETED) { + continue; + } - console->CancelAllTimers(); + console->CancelAllTimers(); - if (console->GetNetworkVar(u"used")) - { - bothBuilt = true; - } - } + if (console->GetNetworkVar(u"used")) { + bothBuilt = true; + } + } - if (bothBuilt) - { - SmashCanister(self); - } - else - { - SpawnBrick(self); - } + if (bothBuilt) { + SmashCanister(self); + } else { + SpawnBrick(self); + } - self->AddTimer("Die", ResetInteract); + self->AddTimer("Die", ResetInteract); - auto onFX = 0; + auto onFX = 0; - const auto location = GeneralUtils::UTF16ToWTF8(self->GetVar(u"console")); + const auto location = GeneralUtils::UTF16ToWTF8(self->GetVar(u"console")); - if (location == "Left") - { - onFX = 2776; - } - else - { - onFX = 2779; - } + if (location == "Left") { + onFX = 2776; + } else { + onFX = 2779; + } - const auto& facility = EntityManager::Instance()->GetEntitiesInGroup("FacilityPipes"); + const auto& facility = EntityManager::Instance()->GetEntitiesInGroup("FacilityPipes"); - if (!facility.empty()) - { - GameMessages::SendStopFXEffect(facility[0], true, location + "PipeEnergy"); - GameMessages::SendPlayFXEffect(facility[0]->GetObjectID(), onFX, u"create", location + "PipeOn"); - } - } + if (!facility.empty()) { + GameMessages::SendStopFXEffect(facility[0], true, location + "PipeEnergy"); + GameMessages::SendPlayFXEffect(facility[0]->GetObjectID(), onFX, u"create", location + "PipeOn"); + } + } - auto* player = user; + auto* player = user; - auto* missionComponent = player->GetComponent(); - auto* inventoryComponent = player->GetComponent(); + auto* missionComponent = player->GetComponent(); + auto* inventoryComponent = player->GetComponent(); - if (missionComponent != nullptr && inventoryComponent != nullptr) - { - if (missionComponent->GetMissionState(1302) == MissionState::MISSION_STATE_ACTIVE) - { - inventoryComponent->RemoveItem(13074, 1); - - missionComponent->ForceProgressTaskType(1302, 1, 1); - } - - if (missionComponent->GetMissionState(1926) == MissionState::MISSION_STATE_ACTIVE) - { - inventoryComponent->RemoveItem(14472, 1); + if (missionComponent != nullptr && inventoryComponent != nullptr) { + if (missionComponent->GetMissionState(1302) == MissionState::MISSION_STATE_ACTIVE) { + inventoryComponent->RemoveItem(13074, 1); - missionComponent->ForceProgressTaskType(1926, 1, 1); - } - } + missionComponent->ForceProgressTaskType(1302, 1, 1); + } - self->SetNetworkVar(u"used", true); + if (missionComponent->GetMissionState(1926) == MissionState::MISSION_STATE_ACTIVE) { + inventoryComponent->RemoveItem(14472, 1); - GameMessages::SendTerminateInteraction(player->GetObjectID(), FROM_INTERACTION, self->GetObjectID()); - } + missionComponent->ForceProgressTaskType(1926, 1, 1); + } + } + + self->SetNetworkVar(u"used", true); + + GameMessages::SendTerminateInteraction(player->GetObjectID(), FROM_INTERACTION, self->GetObjectID()); + } } -void ImgBrickConsoleQB::SpawnBrick(Entity* self) -{ - const auto netDevil = dZoneManager::Instance()->GetSpawnersByName("MaelstromBug"); - if (!netDevil.empty()) - { - netDevil[0]->Reset(); - netDevil[0]->Deactivate(); - } +void ImgBrickConsoleQB::SpawnBrick(Entity* self) { + const auto netDevil = dZoneManager::Instance()->GetSpawnersByName("MaelstromBug"); + if (!netDevil.empty()) { + netDevil[0]->Reset(); + netDevil[0]->Deactivate(); + } - const auto brick = dZoneManager::Instance()->GetSpawnersByName("Imagination"); - if (!brick.empty()) - { - brick[0]->Activate(); - } + const auto brick = dZoneManager::Instance()->GetSpawnersByName("Imagination"); + if (!brick.empty()) { + brick[0]->Activate(); + } } -void ImgBrickConsoleQB::SmashCanister(Entity* self) -{ - const auto brick = EntityManager::Instance()->GetEntitiesInGroup("Imagination"); - if (!brick.empty()) - { - GameMessages::SendPlayFXEffect(brick[0]->GetObjectID(), 122, u"create", "bluebrick"); - GameMessages::SendPlayFXEffect(brick[0]->GetObjectID(), 1034, u"cast", "imaginationexplosion"); - } +void ImgBrickConsoleQB::SmashCanister(Entity* self) { + const auto brick = EntityManager::Instance()->GetEntitiesInGroup("Imagination"); + if (!brick.empty()) { + GameMessages::SendPlayFXEffect(brick[0]->GetObjectID(), 122, u"create", "bluebrick"); + GameMessages::SendPlayFXEffect(brick[0]->GetObjectID(), 1034, u"cast", "imaginationexplosion"); + } - const auto canisters = EntityManager::Instance()->GetEntitiesInGroup("Canister"); - for (auto* canister : canisters) - { - canister->Smash(canister->GetObjectID(), VIOLENT); - } - - const auto canister = dZoneManager::Instance()->GetSpawnersByName("BrickCanister"); - if (!canister.empty()) - { - canister[0]->Reset(); - canister[0]->Deactivate(); - } + const auto canisters = EntityManager::Instance()->GetEntitiesInGroup("Canister"); + for (auto* canister : canisters) { + canister->Smash(canister->GetObjectID(), VIOLENT); + } + + const auto canister = dZoneManager::Instance()->GetSpawnersByName("BrickCanister"); + if (!canister.empty()) { + canister[0]->Reset(); + canister[0]->Deactivate(); + } } -void ImgBrickConsoleQB::OnRebuildComplete(Entity* self, Entity* target) -{ - auto energyFX = 0; +void ImgBrickConsoleQB::OnRebuildComplete(Entity* self, Entity* target) { + auto energyFX = 0; - const auto location = GeneralUtils::UTF16ToWTF8(self->GetVar(u"console")); + const auto location = GeneralUtils::UTF16ToWTF8(self->GetVar(u"console")); - if (location == "Left") - { - energyFX = 2775; - } - else - { - energyFX = 2778; - } + if (location == "Left") { + energyFX = 2775; + } else { + energyFX = 2778; + } - const auto& facility = EntityManager::Instance()->GetEntitiesInGroup("FacilityPipes"); + const auto& facility = EntityManager::Instance()->GetEntitiesInGroup("FacilityPipes"); - if (!facility.empty()) - { - GameMessages::SendStopFXEffect(facility[0], true, location + "PipeOff"); - GameMessages::SendPlayFXEffect(facility[0]->GetObjectID(), energyFX, u"create", location + "PipeEnergy"); - } + if (!facility.empty()) { + GameMessages::SendStopFXEffect(facility[0], true, location + "PipeOff"); + GameMessages::SendPlayFXEffect(facility[0]->GetObjectID(), energyFX, u"create", location + "PipeEnergy"); + } - const auto consoles = EntityManager::Instance()->GetEntitiesInGroup("Console"); + const auto consoles = EntityManager::Instance()->GetEntitiesInGroup("Console"); - for (auto* console : consoles) - { - auto* consoleRebuildComponent = console->GetComponent(); + for (auto* console : consoles) { + auto* consoleRebuildComponent = console->GetComponent(); - if (consoleRebuildComponent->GetState() != REBUILD_COMPLETED) - { - continue; - } + if (consoleRebuildComponent->GetState() != REBUILD_COMPLETED) { + continue; + } - console->CancelAllTimers(); - } + console->CancelAllTimers(); + } - self->AddTimer("Die", ResetConsole); + self->AddTimer("Die", ResetConsole); } -void ImgBrickConsoleQB::OnDie(Entity* self, Entity* killer) -{ - if (self->GetVar(u"Died")) - { - return; - } +void ImgBrickConsoleQB::OnDie(Entity* self, Entity* killer) { + if (self->GetVar(u"Died")) { + return; + } - self->CancelAllTimers(); + self->CancelAllTimers(); - self->SetVar(u"Died", true); + self->SetVar(u"Died", true); - auto* rebuildComponent = self->GetComponent(); + auto* rebuildComponent = self->GetComponent(); - if (rebuildComponent->GetState() == REBUILD_COMPLETED) - { - auto offFX = 0; + if (rebuildComponent->GetState() == REBUILD_COMPLETED) { + auto offFX = 0; - const auto location = GeneralUtils::UTF16ToWTF8(self->GetVar(u"console")); + const auto location = GeneralUtils::UTF16ToWTF8(self->GetVar(u"console")); - if (location == "Left") - { - offFX = 2774; - } - else - { - offFX = 2777; - } + if (location == "Left") { + offFX = 2774; + } else { + offFX = 2777; + } - const auto& facility = EntityManager::Instance()->GetEntitiesInGroup("FacilityPipes"); + const auto& facility = EntityManager::Instance()->GetEntitiesInGroup("FacilityPipes"); - if (!facility.empty()) - { - GameMessages::SendStopFXEffect(facility[0], true, location + "PipeEnergy"); - GameMessages::SendStopFXEffect(facility[0], true, location + "PipeOn"); - GameMessages::SendPlayFXEffect(facility[0]->GetObjectID(), offFX, u"create", location + "PipeOff"); - GameMessages::SendPlayFXEffect(facility[0]->GetObjectID(), 2750, u"create", location + "imagination_canister"); - } - } - - const auto myGroup = GeneralUtils::UTF16ToWTF8(self->GetVar(u"spawner_name")); - - const auto pipeGroup = myGroup.substr(0, 10); + if (!facility.empty()) { + GameMessages::SendStopFXEffect(facility[0], true, location + "PipeEnergy"); + GameMessages::SendStopFXEffect(facility[0], true, location + "PipeOn"); + GameMessages::SendPlayFXEffect(facility[0]->GetObjectID(), offFX, u"create", location + "PipeOff"); + GameMessages::SendPlayFXEffect(facility[0]->GetObjectID(), 2750, u"create", location + "imagination_canister"); + } + } - const auto firstPipe = pipeGroup + "1"; + const auto myGroup = GeneralUtils::UTF16ToWTF8(self->GetVar(u"spawner_name")); - const auto samePipeSpawner = dZoneManager::Instance()->GetSpawnersByName(myGroup); - if (!samePipeSpawner.empty()) - { - samePipeSpawner[0]->Reset(); - samePipeSpawner[0]->Deactivate(); - } - - const auto firstPipeSpawner = dZoneManager::Instance()->GetSpawnersByName(firstPipe); - if (!firstPipeSpawner.empty()) - { - firstPipeSpawner[0]->Activate(); - } + const auto pipeGroup = myGroup.substr(0, 10); - const auto netdevil = dZoneManager::Instance()->GetSpawnersByName("Imagination"); - if (!netdevil.empty()) - { - netdevil[0]->Reset(); - netdevil[0]->Deactivate(); - } + const auto firstPipe = pipeGroup + "1"; - const auto brick = dZoneManager::Instance()->GetSpawnersByName("MaelstromBug"); - if (!brick.empty()) - { - brick[0]->Activate(); - } + const auto samePipeSpawner = dZoneManager::Instance()->GetSpawnersByName(myGroup); + if (!samePipeSpawner.empty()) { + samePipeSpawner[0]->Reset(); + samePipeSpawner[0]->Deactivate(); + } - const auto canister = dZoneManager::Instance()->GetSpawnersByName("BrickCanister"); - if (!canister.empty()) - { - canister[0]->Activate(); - } + const auto firstPipeSpawner = dZoneManager::Instance()->GetSpawnersByName(firstPipe); + if (!firstPipeSpawner.empty()) { + firstPipeSpawner[0]->Activate(); + } - self->SetNetworkVar(u"used", false); + const auto netdevil = dZoneManager::Instance()->GetSpawnersByName("Imagination"); + if (!netdevil.empty()) { + netdevil[0]->Reset(); + netdevil[0]->Deactivate(); + } + + const auto brick = dZoneManager::Instance()->GetSpawnersByName("MaelstromBug"); + if (!brick.empty()) { + brick[0]->Activate(); + } + + const auto canister = dZoneManager::Instance()->GetSpawnersByName("BrickCanister"); + if (!canister.empty()) { + canister[0]->Activate(); + } + + self->SetNetworkVar(u"used", false); } -void ImgBrickConsoleQB::OnTimerDone(Entity* self, std::string timerName) -{ - if (timerName == "reset") - { - auto* rebuildComponent = self->GetComponent(); +void ImgBrickConsoleQB::OnTimerDone(Entity* self, std::string timerName) { + if (timerName == "reset") { + auto* rebuildComponent = self->GetComponent(); - if (rebuildComponent->GetState() == REBUILD_OPEN) - { - self->Smash(self->GetObjectID(), SILENT); - } - } - else if (timerName == "Die") - { - const auto consoles = EntityManager::Instance()->GetEntitiesInGroup("Console"); + if (rebuildComponent->GetState() == REBUILD_OPEN) { + self->Smash(self->GetObjectID(), SILENT); + } + } else if (timerName == "Die") { + const auto consoles = EntityManager::Instance()->GetEntitiesInGroup("Console"); - for (auto* console : consoles) - { - console->Smash(console->GetObjectID(), VIOLENT); - } - } + for (auto* console : consoles) { + console->Smash(console->GetObjectID(), VIOLENT); + } + } } diff --git a/dScripts/ImgBrickConsoleQB.h b/dScripts/ImgBrickConsoleQB.h index f51f8e6c..062a5888 100644 --- a/dScripts/ImgBrickConsoleQB.h +++ b/dScripts/ImgBrickConsoleQB.h @@ -1,19 +1,19 @@ #pragma once #include "CppScripts.h" -class ImgBrickConsoleQB : public CppScripts::Script +class ImgBrickConsoleQB : public CppScripts::Script { public: - void OnStartup(Entity* self) override; - void OnUse(Entity* self, Entity* user) override; - void SpawnBrick(Entity* self); - void SmashCanister(Entity* self); - void OnRebuildComplete(Entity* self, Entity* target) override; - void OnDie(Entity* self, Entity* killer) override; - void OnTimerDone(Entity* self, std::string timerName) override; + void OnStartup(Entity* self) override; + void OnUse(Entity* self, Entity* user) override; + void SpawnBrick(Entity* self); + void SmashCanister(Entity* self); + void OnRebuildComplete(Entity* self, Entity* target) override; + void OnDie(Entity* self, Entity* killer) override; + void OnTimerDone(Entity* self, std::string timerName) override; public: - static int32_t ResetBricks; - static int32_t ResetConsole; - static int32_t ResetInteract; -}; \ No newline at end of file + static int32_t ResetBricks; + static int32_t ResetConsole; + static int32_t ResetInteract; +}; diff --git a/dScripts/InstanceExitTransferPlayerToLastNonInstance.cpp b/dScripts/InstanceExitTransferPlayerToLastNonInstance.cpp index 307c6c73..4e42e7fb 100644 --- a/dScripts/InstanceExitTransferPlayerToLastNonInstance.cpp +++ b/dScripts/InstanceExitTransferPlayerToLastNonInstance.cpp @@ -4,56 +4,53 @@ #include "Character.h" #include "dServer.h" -void InstanceExitTransferPlayerToLastNonInstance::OnUse(Entity* self, Entity* user) -{ - auto transferText = self->GetVar(u"transferText"); - if (transferText.empty()) - transferText = u"DRAGON_EXIT_QUESTION"; +void InstanceExitTransferPlayerToLastNonInstance::OnUse(Entity* self, Entity* user) { + auto transferText = self->GetVar(u"transferText"); + if (transferText.empty()) + transferText = u"DRAGON_EXIT_QUESTION"; - GameMessages::SendDisplayMessageBox( - user->GetObjectID(), - true, - self->GetObjectID(), - u"Instance_Exit", - 1, - transferText, - u"", - user->GetSystemAddress() - ); + GameMessages::SendDisplayMessageBox( + user->GetObjectID(), + true, + self->GetObjectID(), + u"Instance_Exit", + 1, + transferText, + u"", + user->GetSystemAddress() + ); } -void InstanceExitTransferPlayerToLastNonInstance::OnMessageBoxResponse(Entity* self, Entity* sender, int32_t button, const std::u16string& identifier, const std::u16string& userData) -{ - auto* player = dynamic_cast(sender); - if (player == nullptr) - return; +void InstanceExitTransferPlayerToLastNonInstance::OnMessageBoxResponse(Entity* self, Entity* sender, int32_t button, const std::u16string& identifier, const std::u16string& userData) { + auto* player = dynamic_cast(sender); + if (player == nullptr) + return; - auto* character = sender->GetCharacter(); - if (character != nullptr) { - if (identifier == u"Instance_Exit" && button == 1) { - auto lastInstance = character->GetLastNonInstanceZoneID(); + auto* character = sender->GetCharacter(); + if (character != nullptr) { + if (identifier == u"Instance_Exit" && button == 1) { + auto lastInstance = character->GetLastNonInstanceZoneID(); - // Sanity check - if (lastInstance == 0) { - switch (Game::server->GetZoneID()) - { - case 2001: - lastInstance = 2000; - break; - case 1402: - lastInstance = 1400; - break; - default: - lastInstance = 1100; - break; - } - } + // Sanity check + if (lastInstance == 0) { + switch (Game::server->GetZoneID()) { + case 2001: + lastInstance = 2000; + break; + case 1402: + lastInstance = 1400; + break; + default: + lastInstance = 1100; + break; + } + } - player->SendToZone(lastInstance); - } - } + player->SendToZone(lastInstance); + } + } - GameMessages::SendTerminateInteraction(sender->GetObjectID(), eTerminateType::FROM_INTERACTION, self->GetObjectID()); + GameMessages::SendTerminateInteraction(sender->GetObjectID(), eTerminateType::FROM_INTERACTION, self->GetObjectID()); } diff --git a/dScripts/InstanceExitTransferPlayerToLastNonInstance.h b/dScripts/InstanceExitTransferPlayerToLastNonInstance.h index 3321191d..01e9fe3f 100644 --- a/dScripts/InstanceExitTransferPlayerToLastNonInstance.h +++ b/dScripts/InstanceExitTransferPlayerToLastNonInstance.h @@ -1,7 +1,7 @@ #pragma once #include "CppScripts.h" -class InstanceExitTransferPlayerToLastNonInstance : public CppScripts::Script +class InstanceExitTransferPlayerToLastNonInstance : public CppScripts::Script { public: void OnUse(Entity* self, Entity* user) override; diff --git a/dScripts/LegoDieRoll.cpp b/dScripts/LegoDieRoll.cpp index 386313be..e86550f9 100644 --- a/dScripts/LegoDieRoll.cpp +++ b/dScripts/LegoDieRoll.cpp @@ -4,51 +4,49 @@ #include "MissionComponent.h" void LegoDieRoll::OnStartup(Entity* self) { - self->AddTimer("DoneRolling", 10.0f); - self->AddTimer("ThrowDice", LegoDieRoll::animTime); + self->AddTimer("DoneRolling", 10.0f); + self->AddTimer("ThrowDice", LegoDieRoll::animTime); } void LegoDieRoll::OnTimerDone(Entity* self, std::string timerName) { - if (timerName == "DoneRolling") { - self->Smash(self->GetObjectID(), SILENT); - } - else if (timerName == "ThrowDice") { - int dieRoll = GeneralUtils::GenerateRandomNumber(1, 6); + if (timerName == "DoneRolling") { + self->Smash(self->GetObjectID(), SILENT); + } else if (timerName == "ThrowDice") { + int dieRoll = GeneralUtils::GenerateRandomNumber(1, 6); - switch (dieRoll) - { - case 1: - GameMessages::SendPlayAnimation(self, u"roll-die-1"); - break; - case 2: - GameMessages::SendPlayAnimation(self, u"roll-die-2"); - break; - case 3: - GameMessages::SendPlayAnimation(self, u"roll-die-3"); - break; - case 4: - GameMessages::SendPlayAnimation(self, u"roll-die-4"); - break; - case 5: - GameMessages::SendPlayAnimation(self, u"roll-die-5"); - break; - case 6: - { - GameMessages::SendPlayAnimation(self, u"roll-die-6"); - // tracking the It's Truly Random Achievement - auto* owner = self->GetOwner(); - auto* missionComponent = owner->GetComponent(); + switch (dieRoll) { + case 1: + GameMessages::SendPlayAnimation(self, u"roll-die-1"); + break; + case 2: + GameMessages::SendPlayAnimation(self, u"roll-die-2"); + break; + case 3: + GameMessages::SendPlayAnimation(self, u"roll-die-3"); + break; + case 4: + GameMessages::SendPlayAnimation(self, u"roll-die-4"); + break; + case 5: + GameMessages::SendPlayAnimation(self, u"roll-die-5"); + break; + case 6: + { + GameMessages::SendPlayAnimation(self, u"roll-die-6"); + // tracking the It's Truly Random Achievement + auto* owner = self->GetOwner(); + auto* missionComponent = owner->GetComponent(); - if (missionComponent != nullptr) { - const auto rollMissionState = missionComponent->GetMissionState(756); - if (rollMissionState == MissionState::MISSION_STATE_ACTIVE) { - missionComponent->ForceProgress(756, 1103, 1); - } - } - break; - } - default: - break; - } - } -} \ No newline at end of file + if (missionComponent != nullptr) { + const auto rollMissionState = missionComponent->GetMissionState(756); + if (rollMissionState == MissionState::MISSION_STATE_ACTIVE) { + missionComponent->ForceProgress(756, 1103, 1); + } + } + break; + } + default: + break; + } + } +} diff --git a/dScripts/LegoDieRoll.h b/dScripts/LegoDieRoll.h index 3b28d529..ea047e04 100644 --- a/dScripts/LegoDieRoll.h +++ b/dScripts/LegoDieRoll.h @@ -6,6 +6,6 @@ public: void OnStartup(Entity* self); void OnTimerDone(Entity* self, std::string timerName); private: - constexpr static const float animTime = 2.0f; + constexpr static const float animTime = 2.0f; }; diff --git a/dScripts/Lieutenant.cpp b/dScripts/Lieutenant.cpp index 91ffce63..d3b0fc1f 100644 --- a/dScripts/Lieutenant.cpp +++ b/dScripts/Lieutenant.cpp @@ -2,49 +2,43 @@ #include "SkillComponent.h" #include "dZoneManager.h" -void Lieutenant::OnStartup(Entity* self) -{ - auto* skillComponent = self->GetComponent(); +void Lieutenant::OnStartup(Entity* self) { + auto* skillComponent = self->GetComponent(); - if (skillComponent == nullptr) - { - return; - } + if (skillComponent == nullptr) { + return; + } - skillComponent->CalculateBehavior(1127, 24812, self->GetObjectID(), true); + skillComponent->CalculateBehavior(1127, 24812, self->GetObjectID(), true); } -void Lieutenant::OnDie(Entity* self, Entity* killer) -{ - const auto myLOT = self->GetLOT(); +void Lieutenant::OnDie(Entity* self, Entity* killer) { + const auto myLOT = self->GetLOT(); - std::string spawnerName; + std::string spawnerName; - switch (myLOT) - { - case 16047: - spawnerName = "EarthShrine_ERail"; - break; - case 16050: - spawnerName = "IceShrine_QBBouncer"; - break; - case 16049: - spawnerName = "LightningShrine_LRail"; - break; - default: - return; - } + switch (myLOT) { + case 16047: + spawnerName = "EarthShrine_ERail"; + break; + case 16050: + spawnerName = "IceShrine_QBBouncer"; + break; + case 16049: + spawnerName = "LightningShrine_LRail"; + break; + default: + return; + } - const auto spawners = dZoneManager::Instance()->GetSpawnersByName(spawnerName); + const auto spawners = dZoneManager::Instance()->GetSpawnersByName(spawnerName); - if (spawners.empty()) - { - return; - } + if (spawners.empty()) { + return; + } - for (auto* spawner : spawners) - { - spawner->Reset(); - spawner->Activate(); - } + for (auto* spawner : spawners) { + spawner->Reset(); + spawner->Activate(); + } } diff --git a/dScripts/Lieutenant.h b/dScripts/Lieutenant.h index 8635671a..ff6212ef 100644 --- a/dScripts/Lieutenant.h +++ b/dScripts/Lieutenant.h @@ -6,6 +6,6 @@ class Lieutenant : public CppScripts::Script public: void OnStartup(Entity* self) override; - void OnDie(Entity* self, Entity* killer) override; + void OnDie(Entity* self, Entity* killer) override; }; diff --git a/dScripts/MaestromExtracticatorServer.cpp b/dScripts/MaestromExtracticatorServer.cpp index a542389f..caaba28f 100644 --- a/dScripts/MaestromExtracticatorServer.cpp +++ b/dScripts/MaestromExtracticatorServer.cpp @@ -12,8 +12,8 @@ void MaestromExtracticatorServer::OnStartup(Entity* self) { self->AddTimer("RemoveSample", destroyAfterNoSampleTime); } -void MaestromExtracticatorServer::OnFireEventServerSide(Entity *self, Entity *sender, std::string args, int32_t param1, - int32_t param2, int32_t param3) { +void MaestromExtracticatorServer::OnFireEventServerSide(Entity* self, Entity* sender, std::string args, int32_t param1, + int32_t param2, int32_t param3) { if (sender == nullptr) return; @@ -25,8 +25,8 @@ void MaestromExtracticatorServer::OnFireEventServerSide(Entity *self, Entity *se if (missionComponent == nullptr) return; missionComponent->Progress(MissionTaskType::MISSION_TASK_TYPE_SMASH, 14718); - CollectSample(self, sender->GetObjectID()); - sender->ScheduleKillAfterUpdate(); + CollectSample(self, sender->GetObjectID()); + sender->ScheduleKillAfterUpdate(); } } diff --git a/dScripts/MaestromExtracticatorServer.h b/dScripts/MaestromExtracticatorServer.h index e59628c9..c4adb51e 100644 --- a/dScripts/MaestromExtracticatorServer.h +++ b/dScripts/MaestromExtracticatorServer.h @@ -4,8 +4,8 @@ class MaestromExtracticatorServer : public CppScripts::Script { public: void OnStartup(Entity* self); - void OnFireEventServerSide(Entity *self, Entity *sender, std::string args, int32_t param1, int32_t param2, - int32_t param3); + void OnFireEventServerSide(Entity* self, Entity* sender, std::string args, int32_t param1, int32_t param2, + int32_t param3); void CollectSample(Entity* self, LWOOBJID sampleObj); void PlayAnimAndReturnTime(Entity* self, std::string animID); void OnTimerDone(Entity* self, std::string timerName); @@ -15,4 +15,4 @@ private: const std::string collectAnim = "collect_maelstrom"; const float defaultTime = 4.0f; const float destroyAfterNoSampleTime = 8.0f; -}; \ No newline at end of file +}; diff --git a/dScripts/MailBoxServer.cpp b/dScripts/MailBoxServer.cpp index 56e7793e..81156835 100644 --- a/dScripts/MailBoxServer.cpp +++ b/dScripts/MailBoxServer.cpp @@ -3,9 +3,9 @@ #include "GameMessages.h" void MailBoxServer::OnUse(Entity* self, Entity* user) { - AMFStringValue* value = new AMFStringValue(); + AMFStringValue* value = new AMFStringValue(); value->SetStringValue("Mail"); AMFArrayValue args; args.InsertValue("state", value); GameMessages::SendUIMessageServerToSingleClient(user, user->GetSystemAddress(), "pushGameState", &args); -} \ No newline at end of file +} diff --git a/dScripts/MailBoxServer.h b/dScripts/MailBoxServer.h index 9cd93e24..f459e8b3 100644 --- a/dScripts/MailBoxServer.h +++ b/dScripts/MailBoxServer.h @@ -4,12 +4,12 @@ class MailBoxServer : public CppScripts::Script { public: - /** - * When a mailbox is interacted with, this method updates the player game state - * to be in a mailbox. - * - * @param self The object that owns this script. - * @param user The user that interacted with this Entity. - */ - void OnUse(Entity* self, Entity* user) override; -}; \ No newline at end of file + /** + * When a mailbox is interacted with, this method updates the player game state + * to be in a mailbox. + * + * @param self The object that owns this script. + * @param user The user that interacted with this Entity. + */ + void OnUse(Entity* self, Entity* user) override; +}; diff --git a/dScripts/MastTeleport.cpp b/dScripts/MastTeleport.cpp index 94d5f552..ebde7b20 100644 --- a/dScripts/MastTeleport.cpp +++ b/dScripts/MastTeleport.cpp @@ -8,92 +8,81 @@ #include #endif -void MastTeleport::OnStartup(Entity* self) -{ - self->SetNetworkVar(u"hookPreconditions", "154;44", UNASSIGNED_SYSTEM_ADDRESS); +void MastTeleport::OnStartup(Entity* self) { + self->SetNetworkVar(u"hookPreconditions", "154;44", UNASSIGNED_SYSTEM_ADDRESS); } -void MastTeleport::OnRebuildComplete(Entity* self, Entity* target) -{ - if (Preconditions::Check(target, 154) && Preconditions::Check(target, 44)) - { - self->SetVar(u"userID", target->GetObjectID()); +void MastTeleport::OnRebuildComplete(Entity* self, Entity* target) { + if (Preconditions::Check(target, 154) && Preconditions::Check(target, 44)) { + self->SetVar(u"userID", target->GetObjectID()); - GameMessages::SendSetStunned(target->GetObjectID(), PUSH, target->GetSystemAddress(), - LWOOBJID_EMPTY, true, true, true, true, true, true, true - ); + GameMessages::SendSetStunned(target->GetObjectID(), PUSH, target->GetSystemAddress(), + LWOOBJID_EMPTY, true, true, true, true, true, true, true + ); - self->AddTimer("Start", 3); - } + self->AddTimer("Start", 3); + } } -void MastTeleport::OnTimerDone(Entity* self, std::string timerName) -{ - const auto playerId = self->GetVar(u"userID"); +void MastTeleport::OnTimerDone(Entity* self, std::string timerName) { + const auto playerId = self->GetVar(u"userID"); - auto* player = EntityManager::Instance()->GetEntity(playerId); - - if (player == nullptr) return; + auto* player = EntityManager::Instance()->GetEntity(playerId); - if (timerName == "Start") - { - auto position = self->GetPosition(); - auto rotation = self->GetRotation(); + if (player == nullptr) return; - GameMessages::SendTeleport(playerId, position, rotation, player->GetSystemAddress(), true); + if (timerName == "Start") { + auto position = self->GetPosition(); + auto rotation = self->GetRotation(); - // Hacky fix for odd rotations - if (self->GetVar(u"MastName") != u"Jail") - { - GameMessages::SendOrientToAngle(playerId, true, (M_PI / 180) * 140.0f, player->GetSystemAddress()); - } - else - { - GameMessages::SendOrientToAngle(playerId, true, (M_PI / 180) * 100.0f, player->GetSystemAddress()); - } - - const auto cinematic = GeneralUtils::UTF16ToWTF8(self->GetVar(u"Cinematic")); - const auto leanIn = self->GetVar(u"LeanIn"); + GameMessages::SendTeleport(playerId, position, rotation, player->GetSystemAddress(), true); - if (!cinematic.empty()) - { - GameMessages::SendPlayCinematic(playerId, GeneralUtils::ASCIIToUTF16(cinematic), player->GetSystemAddress(), - true, true, false, false, 0, false, leanIn - ); - } - - GameMessages::SendPlayFXEffect(playerId, 6039, u"hook", "hook", LWOOBJID_EMPTY, 1, 1, true); + // Hacky fix for odd rotations + if (self->GetVar(u"MastName") != u"Jail") { + GameMessages::SendOrientToAngle(playerId, true, (M_PI / 180) * 140.0f, player->GetSystemAddress()); + } else { + GameMessages::SendOrientToAngle(playerId, true, (M_PI / 180) * 100.0f, player->GetSystemAddress()); + } - GameMessages::SendPlayAnimation(player, u"crow-swing-no-equip"); + const auto cinematic = GeneralUtils::UTF16ToWTF8(self->GetVar(u"Cinematic")); + const auto leanIn = self->GetVar(u"LeanIn"); - GameMessages::SendPlayAnimation(self, u"swing"); + if (!cinematic.empty()) { + GameMessages::SendPlayCinematic(playerId, GeneralUtils::ASCIIToUTF16(cinematic), player->GetSystemAddress(), + true, true, false, false, 0, false, leanIn + ); + } - self->AddTimer("PlayerAnimDone", 6.25f); - } - else if (timerName == "PlayerAnimDone") - { - GameMessages::SendStopFXEffect(player, true, "hook"); + GameMessages::SendPlayFXEffect(playerId, 6039, u"hook", "hook", LWOOBJID_EMPTY, 1, 1, true); - auto forward = self->GetRotation().GetForwardVector(); + GameMessages::SendPlayAnimation(player, u"crow-swing-no-equip"); - const auto degrees = -25.0f; + GameMessages::SendPlayAnimation(self, u"swing"); - const auto rads = degrees * (static_cast(M_PI) / 180.0f); + self->AddTimer("PlayerAnimDone", 6.25f); + } else if (timerName == "PlayerAnimDone") { + GameMessages::SendStopFXEffect(player, true, "hook"); - const Vector3 newPlayerRot = {0, rads, 0}; + auto forward = self->GetRotation().GetForwardVector(); - auto position = self->GetPosition(); + const auto degrees = -25.0f; - position.x += (forward.x * 20.5f); - position.y += 12; - position.z += (forward.z * 20.5f); + const auto rads = degrees * (static_cast(M_PI) / 180.0f); - GameMessages::SendOrientToAngle(playerId, true, rads, player->GetSystemAddress()); + const Vector3 newPlayerRot = { 0, rads, 0 }; - GameMessages::SendTeleport(playerId, position, NiQuaternion::IDENTITY, player->GetSystemAddress()); + auto position = self->GetPosition(); - GameMessages::SendSetStunned(playerId, POP, player->GetSystemAddress(), - LWOOBJID_EMPTY, true, true, true, true, true, true, true - ); - } + position.x += (forward.x * 20.5f); + position.y += 12; + position.z += (forward.z * 20.5f); + + GameMessages::SendOrientToAngle(playerId, true, rads, player->GetSystemAddress()); + + GameMessages::SendTeleport(playerId, position, NiQuaternion::IDENTITY, player->GetSystemAddress()); + + GameMessages::SendSetStunned(playerId, POP, player->GetSystemAddress(), + LWOOBJID_EMPTY, true, true, true, true, true, true, true + ); + } } diff --git a/dScripts/MastTeleport.h b/dScripts/MastTeleport.h index 1b5dc481..ea35d754 100644 --- a/dScripts/MastTeleport.h +++ b/dScripts/MastTeleport.h @@ -4,6 +4,6 @@ class MastTeleport : public CppScripts::Script { public: void OnStartup(Entity* self) override; - void OnRebuildComplete(Entity* self, Entity* target) override; + void OnRebuildComplete(Entity* self, Entity* target) override; void OnTimerDone(Entity* self, std::string timerName) override; -}; \ No newline at end of file +}; diff --git a/dScripts/MinigameTreasureChestServer.cpp b/dScripts/MinigameTreasureChestServer.cpp index fc3f14c0..66222d59 100644 --- a/dScripts/MinigameTreasureChestServer.cpp +++ b/dScripts/MinigameTreasureChestServer.cpp @@ -4,61 +4,61 @@ #include "EntityManager.h" #include "dZoneManager.h" -void MinigameTreasureChestServer::OnUse(Entity *self, Entity *user) { - auto* sac = self->GetComponent(); - if (sac == nullptr) - return; +void MinigameTreasureChestServer::OnUse(Entity* self, Entity* user) { + auto* sac = self->GetComponent(); + if (sac == nullptr) + return; - if (self->GetVar(u"used")) - return; - self->SetVar(u"used", true); + if (self->GetVar(u"used")) + return; + self->SetVar(u"used", true); - if (!IsPlayerInActivity(self, user->GetObjectID())) - UpdatePlayer(self, user->GetObjectID()); + if (!IsPlayerInActivity(self, user->GetObjectID())) + UpdatePlayer(self, user->GetObjectID()); - auto* team = TeamManager::Instance()->GetTeam(user->GetObjectID()); - uint32_t activityRating = 0; - if (team != nullptr) { - for (const auto& teamMemberID : team->members) { - auto* teamMember = EntityManager::Instance()->GetEntity(teamMemberID); - if (teamMember != nullptr) { - activityRating = CalculateActivityRating(self, teamMemberID); + auto* team = TeamManager::Instance()->GetTeam(user->GetObjectID()); + uint32_t activityRating = 0; + if (team != nullptr) { + for (const auto& teamMemberID : team->members) { + auto* teamMember = EntityManager::Instance()->GetEntity(teamMemberID); + if (teamMember != nullptr) { + activityRating = CalculateActivityRating(self, teamMemberID); - if (self->GetLOT() == frakjawChestId) activityRating = team->members.size(); + if (self->GetLOT() == frakjawChestId) activityRating = team->members.size(); - LootGenerator::Instance().DropActivityLoot(teamMember, self, sac->GetActivityID(), activityRating); - } - } - } else { - activityRating = CalculateActivityRating(self, user->GetObjectID()); + LootGenerator::Instance().DropActivityLoot(teamMember, self, sac->GetActivityID(), activityRating); + } + } + } else { + activityRating = CalculateActivityRating(self, user->GetObjectID()); - if (self->GetLOT() == frakjawChestId) activityRating = 1; - - LootGenerator::Instance().DropActivityLoot(user, self, sac->GetActivityID(), activityRating); - } + if (self->GetLOT() == frakjawChestId) activityRating = 1; - sac->PlayerRemove(user->GetObjectID()); + LootGenerator::Instance().DropActivityLoot(user, self, sac->GetActivityID(), activityRating); + } - auto* zoneControl = dZoneManager::Instance()->GetZoneControlObject(); - if (zoneControl != nullptr) { - zoneControl->OnFireEventServerSide(self, "Survival_Update", 0); - } + sac->PlayerRemove(user->GetObjectID()); - self->Smash(self->GetObjectID()); + auto* zoneControl = dZoneManager::Instance()->GetZoneControlObject(); + if (zoneControl != nullptr) { + zoneControl->OnFireEventServerSide(self, "Survival_Update", 0); + } + + self->Smash(self->GetObjectID()); } -uint32_t MinigameTreasureChestServer::CalculateActivityRating(Entity *self, LWOOBJID playerID) { - auto* team = TeamManager::Instance()->GetTeam(playerID); - return team != nullptr ? team->members.size() * 100 : ActivityManager::CalculateActivityRating(self, playerID) * 100; +uint32_t MinigameTreasureChestServer::CalculateActivityRating(Entity* self, LWOOBJID playerID) { + auto* team = TeamManager::Instance()->GetTeam(playerID); + return team != nullptr ? team->members.size() * 100 : ActivityManager::CalculateActivityRating(self, playerID) * 100; } -void MinigameTreasureChestServer::OnStartup(Entity *self) { +void MinigameTreasureChestServer::OnStartup(Entity* self) { - // BONS treasure chest thinks it's on FV, causing it to start a lobby - if (dZoneManager::Instance()->GetZoneID().GetMapID() == 1204) { - auto* sac = self->GetComponent(); - if (sac != nullptr) { - sac->SetInstanceMapID(1204); - } - } + // BONS treasure chest thinks it's on FV, causing it to start a lobby + if (dZoneManager::Instance()->GetZoneID().GetMapID() == 1204) { + auto* sac = self->GetComponent(); + if (sac != nullptr) { + sac->SetInstanceMapID(1204); + } + } } diff --git a/dScripts/MinigameTreasureChestServer.h b/dScripts/MinigameTreasureChestServer.h index c718f016..3159e70e 100644 --- a/dScripts/MinigameTreasureChestServer.h +++ b/dScripts/MinigameTreasureChestServer.h @@ -3,9 +3,9 @@ class MinigameTreasureChestServer : public ActivityManager { public: - void OnStartup(Entity* self) override; - void OnUse(Entity* self, Entity* user) override; - uint32_t CalculateActivityRating(Entity *self, LWOOBJID playerID) override; + void OnStartup(Entity* self) override; + void OnUse(Entity* self, Entity* user) override; + uint32_t CalculateActivityRating(Entity* self, LWOOBJID playerID) override; private: - const uint32_t frakjawChestId = 16486; + const uint32_t frakjawChestId = 16486; }; diff --git a/dScripts/MonCoreNookDoors.cpp b/dScripts/MonCoreNookDoors.cpp index c3fcf9be..dc759c50 100644 --- a/dScripts/MonCoreNookDoors.cpp +++ b/dScripts/MonCoreNookDoors.cpp @@ -1,45 +1,37 @@ #include "MonCoreNookDoors.h" #include "dZoneManager.h" -void MonCoreNookDoors::OnStartup(Entity* self) -{ - SpawnDoor(self); +void MonCoreNookDoors::OnStartup(Entity* self) { + SpawnDoor(self); } -void MonCoreNookDoors::SpawnDoor(Entity* self) -{ - const auto doorNum = self->GetVarAsString(u"number"); +void MonCoreNookDoors::SpawnDoor(Entity* self) { + const auto doorNum = self->GetVarAsString(u"number"); - if (doorNum.empty()) - { - return; - } + if (doorNum.empty()) { + return; + } - const auto spawners = dZoneManager::Instance()->GetSpawnersByName("MonCoreNookDoor0" + doorNum); + const auto spawners = dZoneManager::Instance()->GetSpawnersByName("MonCoreNookDoor0" + doorNum); - if (spawners.empty()) - { - return; - } + if (spawners.empty()) { + return; + } - auto* spawner = spawners[0]; + auto* spawner = spawners[0]; - spawner->Reset(); - spawner->Activate(); + spawner->Reset(); + spawner->Activate(); } -void MonCoreNookDoors::OnFireEventServerSide(Entity *self, Entity *sender, std::string args, int32_t param1, int32_t param2, int32_t param3) -{ - if (args == "DoorSmashed") - { - self->AddTimer("RespawnDoor", 30); - } +void MonCoreNookDoors::OnFireEventServerSide(Entity* self, Entity* sender, std::string args, int32_t param1, int32_t param2, int32_t param3) { + if (args == "DoorSmashed") { + self->AddTimer("RespawnDoor", 30); + } } -void MonCoreNookDoors::OnTimerDone(Entity* self, std::string timerName) -{ - if (timerName == "RespawnDoor") - { - SpawnDoor(self); - } +void MonCoreNookDoors::OnTimerDone(Entity* self, std::string timerName) { + if (timerName == "RespawnDoor") { + SpawnDoor(self); + } } diff --git a/dScripts/MonCoreNookDoors.h b/dScripts/MonCoreNookDoors.h index a7ad7906..58661575 100644 --- a/dScripts/MonCoreNookDoors.h +++ b/dScripts/MonCoreNookDoors.h @@ -3,12 +3,12 @@ class MonCoreNookDoors : public CppScripts::Script { public: - void OnStartup(Entity* self) override; + void OnStartup(Entity* self) override; - void SpawnDoor(Entity* self); + void SpawnDoor(Entity* self); - void OnFireEventServerSide(Entity *self, Entity *sender, std::string args, int32_t param1, int32_t param2, int32_t param3) override; + void OnFireEventServerSide(Entity* self, Entity* sender, std::string args, int32_t param1, int32_t param2, int32_t param3) override; - void OnTimerDone(Entity* self, std::string timerName) override; + void OnTimerDone(Entity* self, std::string timerName) override; }; diff --git a/dScripts/MonCoreSmashableDoors.cpp b/dScripts/MonCoreSmashableDoors.cpp index 0e7950f5..4ec11e56 100644 --- a/dScripts/MonCoreSmashableDoors.cpp +++ b/dScripts/MonCoreSmashableDoors.cpp @@ -1,24 +1,21 @@ #include "MonCoreSmashableDoors.h" #include "EntityManager.h" -void MonCoreSmashableDoors::OnDie(Entity* self, Entity* killer) -{ - auto myNum = self->GetVarAsString(u"spawner_name"); +void MonCoreSmashableDoors::OnDie(Entity* self, Entity* killer) { + auto myNum = self->GetVarAsString(u"spawner_name"); myNum = myNum.substr(myNum.length() - 1, 1); - - auto triggerGroup = "CoreNookTrig0" + myNum; + + auto triggerGroup = "CoreNookTrig0" + myNum; // Get the trigger auto triggers = EntityManager::Instance()->GetEntitiesInGroup(triggerGroup); - if (triggers.empty()) - { + if (triggers.empty()) { return; } - for (auto trigger : triggers) - { + for (auto trigger : triggers) { trigger->OnFireEventServerSide(self, "DoorSmashed"); } } diff --git a/dScripts/MonCoreSmashableDoors.h b/dScripts/MonCoreSmashableDoors.h index 2c2f28ae..1f205e96 100644 --- a/dScripts/MonCoreSmashableDoors.h +++ b/dScripts/MonCoreSmashableDoors.h @@ -3,6 +3,6 @@ class MonCoreSmashableDoors : public CppScripts::Script { public: - void OnDie(Entity* self, Entity* killer) override; + void OnDie(Entity* self, Entity* killer) override; }; diff --git a/dScripts/NPCAddRemoveItem.cpp b/dScripts/NPCAddRemoveItem.cpp index 58c46ac0..ce47b12a 100644 --- a/dScripts/NPCAddRemoveItem.cpp +++ b/dScripts/NPCAddRemoveItem.cpp @@ -1,30 +1,30 @@ #include "NPCAddRemoveItem.h" #include "InventoryComponent.h" -void NPCAddRemoveItem::OnMissionDialogueOK(Entity *self, Entity *target, int missionID, MissionState missionState) { - auto* inventory = target->GetComponent(); - if (inventory == nullptr) - return; +void NPCAddRemoveItem::OnMissionDialogueOK(Entity* self, Entity* target, int missionID, MissionState missionState) { + auto* inventory = target->GetComponent(); + if (inventory == nullptr) + return; - for (const auto& missionSetting : m_MissionItemSettings) { - if (missionSetting.first == missionID) { - for (const auto& itemSetting : missionSetting.second) { - for (const auto& lot : itemSetting.items) { - if (itemSetting.add && (missionState == MissionState::MISSION_STATE_AVAILABLE || missionState == MissionState::MISSION_STATE_COMPLETE_AVAILABLE)) { - inventory->AddItem(lot, 1, eLootSourceType::LOOT_SOURCE_NONE); - } else if (itemSetting.remove && (missionState == MissionState::MISSION_STATE_READY_TO_COMPLETE || missionState == MissionState::MISSION_STATE_COMPLETE_READY_TO_COMPLETE)) { - inventory->RemoveItem(lot, 1); - } - } - } - } - } + for (const auto& missionSetting : m_MissionItemSettings) { + if (missionSetting.first == missionID) { + for (const auto& itemSetting : missionSetting.second) { + for (const auto& lot : itemSetting.items) { + if (itemSetting.add && (missionState == MissionState::MISSION_STATE_AVAILABLE || missionState == MissionState::MISSION_STATE_COMPLETE_AVAILABLE)) { + inventory->AddItem(lot, 1, eLootSourceType::LOOT_SOURCE_NONE); + } else if (itemSetting.remove && (missionState == MissionState::MISSION_STATE_READY_TO_COMPLETE || missionState == MissionState::MISSION_STATE_COMPLETE_READY_TO_COMPLETE)) { + inventory->RemoveItem(lot, 1); + } + } + } + } + } } std::map> NPCAddRemoveItem::GetSettings() { - return std::map>(); + return std::map>(); } -void NPCAddRemoveItem::OnStartup(Entity *self) { - m_MissionItemSettings = GetSettings(); +void NPCAddRemoveItem::OnStartup(Entity* self) { + m_MissionItemSettings = GetSettings(); } diff --git a/dScripts/NPCAddRemoveItem.h b/dScripts/NPCAddRemoveItem.h index 1b4aba13..a266f817 100644 --- a/dScripts/NPCAddRemoveItem.h +++ b/dScripts/NPCAddRemoveItem.h @@ -2,9 +2,9 @@ #include "CppScripts.h" struct ItemSetting { - std::vector items; // The items to add/remove - bool add; // Add items on mission accept - bool remove; // Remove items on mission complete + std::vector items; // The items to add/remove + bool add; // Add items on mission accept + bool remove; // Remove items on mission complete }; /** @@ -12,9 +12,9 @@ struct ItemSetting { */ class NPCAddRemoveItem : public CppScripts::Script { protected: - void OnMissionDialogueOK(Entity *self, Entity *target, int missionID, MissionState missionState) override; - virtual std::map> GetSettings(); + void OnMissionDialogueOK(Entity* self, Entity* target, int missionID, MissionState missionState) override; + virtual std::map> GetSettings(); private: - void OnStartup(Entity *self) override; - std::map> m_MissionItemSettings; + void OnStartup(Entity* self) override; + std::map> m_MissionItemSettings; }; diff --git a/dScripts/NjColeNPC.cpp b/dScripts/NjColeNPC.cpp index 1b889445..f151db40 100644 --- a/dScripts/NjColeNPC.cpp +++ b/dScripts/NjColeNPC.cpp @@ -2,58 +2,47 @@ #include "MissionComponent.h" #include "InventoryComponent.h" -void NjColeNPC::OnEmoteReceived(Entity* self, int32_t emote, Entity* target) -{ - if (emote != 393) - { - return; - } +void NjColeNPC::OnEmoteReceived(Entity* self, int32_t emote, Entity* target) { + if (emote != 393) { + return; + } - auto* inventoryComponent = target->GetComponent(); + auto* inventoryComponent = target->GetComponent(); - if (inventoryComponent == nullptr) - { - return; - } + if (inventoryComponent == nullptr) { + return; + } - if (!inventoryComponent->IsEquipped(14499) && !inventoryComponent->IsEquipped(16644)) - { - return; - } + if (!inventoryComponent->IsEquipped(14499) && !inventoryComponent->IsEquipped(16644)) { + return; + } - auto* missionComponent = target->GetComponent(); + auto* missionComponent = target->GetComponent(); - if (missionComponent == nullptr) - { - return; - } + if (missionComponent == nullptr) { + return; + } - missionComponent->ForceProgressTaskType(1818, 1, 1); + missionComponent->ForceProgressTaskType(1818, 1, 1); } -void NjColeNPC::OnMissionDialogueOK(Entity* self, Entity* target, int missionID, MissionState missionState) -{ - NjNPCMissionSpinjitzuServer::OnMissionDialogueOK(self, target, missionID, missionState); +void NjColeNPC::OnMissionDialogueOK(Entity* self, Entity* target, int missionID, MissionState missionState) { + NjNPCMissionSpinjitzuServer::OnMissionDialogueOK(self, target, missionID, missionState); - if (missionID == 1818 && missionState >= MissionState::MISSION_STATE_READY_TO_COMPLETE) - { - auto* missionComponent = target->GetComponent(); - auto* inventoryComponent = target->GetComponent(); + if (missionID == 1818 && missionState >= MissionState::MISSION_STATE_READY_TO_COMPLETE) { + auto* missionComponent = target->GetComponent(); + auto* inventoryComponent = target->GetComponent(); - if (missionComponent == nullptr || inventoryComponent == nullptr) - { - return; - } + if (missionComponent == nullptr || inventoryComponent == nullptr) { + return; + } - if (inventoryComponent->GetLotCount(14499) > 0) - { - inventoryComponent->RemoveItem(14499, 1); - } - else - { - return; - } + if (inventoryComponent->GetLotCount(14499) > 0) { + inventoryComponent->RemoveItem(14499, 1); + } else { + return; + } - inventoryComponent->AddItem(16644, 1, eLootSourceType::LOOT_SOURCE_NONE); - } + inventoryComponent->AddItem(16644, 1, eLootSourceType::LOOT_SOURCE_NONE); + } } diff --git a/dScripts/NjColeNPC.h b/dScripts/NjColeNPC.h index c6421a66..cf8e67e1 100644 --- a/dScripts/NjColeNPC.h +++ b/dScripts/NjColeNPC.h @@ -1,7 +1,7 @@ #include "NjNPCMissionSpinjitzuServer.h" class NjColeNPC : public NjNPCMissionSpinjitzuServer { - void OnEmoteReceived(Entity* self, int32_t emote, Entity* target) override; + void OnEmoteReceived(Entity* self, int32_t emote, Entity* target) override; - void OnMissionDialogueOK(Entity* self, Entity* target, int missionID, MissionState missionState) override; + void OnMissionDialogueOK(Entity* self, Entity* target, int missionID, MissionState missionState) override; }; diff --git a/dScripts/NjDragonEmblemChestServer.cpp b/dScripts/NjDragonEmblemChestServer.cpp index ea699c55..fa4d8556 100644 --- a/dScripts/NjDragonEmblemChestServer.cpp +++ b/dScripts/NjDragonEmblemChestServer.cpp @@ -2,14 +2,14 @@ #include "Character.h" #include "DestroyableComponent.h" -void NjDragonEmblemChestServer::OnUse(Entity *self, Entity *user) { - auto* character = user->GetCharacter(); - if (character != nullptr) { - character->SetPlayerFlag(NJ_WU_SHOW_DAILY_CHEST, false); - } +void NjDragonEmblemChestServer::OnUse(Entity* self, Entity* user) { + auto* character = user->GetCharacter(); + if (character != nullptr) { + character->SetPlayerFlag(NJ_WU_SHOW_DAILY_CHEST, false); + } - auto* destroyable = self->GetComponent(); - if (destroyable != nullptr) { - LootGenerator::Instance().DropLoot(user, self, destroyable->GetLootMatrixID(), 0, 0); - } + auto* destroyable = self->GetComponent(); + if (destroyable != nullptr) { + LootGenerator::Instance().DropLoot(user, self, destroyable->GetLootMatrixID(), 0, 0); + } } diff --git a/dScripts/NjDragonEmblemChestServer.h b/dScripts/NjDragonEmblemChestServer.h index ab0abc05..b1c59a22 100644 --- a/dScripts/NjDragonEmblemChestServer.h +++ b/dScripts/NjDragonEmblemChestServer.h @@ -2,5 +2,5 @@ #include "CppScripts.h" class NjDragonEmblemChestServer : public CppScripts::Script { - void OnUse(Entity *self, Entity *user) override; + void OnUse(Entity* self, Entity* user) override; }; diff --git a/dScripts/NjEarthDragonPetServer.cpp b/dScripts/NjEarthDragonPetServer.cpp index 2b91f33c..87f3dd4b 100644 --- a/dScripts/NjEarthDragonPetServer.cpp +++ b/dScripts/NjEarthDragonPetServer.cpp @@ -1,10 +1,10 @@ #include "NjEarthDragonPetServer.h" #include "Entity.h" -void NjEarthDragonPetServer::SetVariables(Entity *self) { - self->SetVar(u"petLOT", 16210); - self->SetVar(u"petType", "earthpet"); - self->SetVar(u"maxPets", 3); - self->SetVar(u"spawnAnim", u"spawn"); - self->SetVar(u"spawnCinematic", u"EarthPetSpawn"); +void NjEarthDragonPetServer::SetVariables(Entity* self) { + self->SetVar(u"petLOT", 16210); + self->SetVar(u"petType", "earthpet"); + self->SetVar(u"maxPets", 3); + self->SetVar(u"spawnAnim", u"spawn"); + self->SetVar(u"spawnCinematic", u"EarthPetSpawn"); } diff --git a/dScripts/NjEarthDragonPetServer.h b/dScripts/NjEarthDragonPetServer.h index 2227bbb6..51e84c34 100644 --- a/dScripts/NjEarthDragonPetServer.h +++ b/dScripts/NjEarthDragonPetServer.h @@ -2,5 +2,5 @@ #include "SpawnPetBaseServer.h" class NjEarthDragonPetServer : public SpawnPetBaseServer { - void SetVariables(Entity* self) override; + void SetVariables(Entity* self) override; }; diff --git a/dScripts/NjEarthPetServer.cpp b/dScripts/NjEarthPetServer.cpp index 12036355..36655c63 100644 --- a/dScripts/NjEarthPetServer.cpp +++ b/dScripts/NjEarthPetServer.cpp @@ -1,12 +1,12 @@ #include "NjEarthPetServer.h" #include "PetComponent.h" -void NjEarthPetServer::OnStartup(Entity *self) { - auto* petComponent = self->GetComponent(); - if (petComponent == nullptr || petComponent->GetOwnerId() != LWOOBJID_EMPTY) - return; +void NjEarthPetServer::OnStartup(Entity* self) { + auto* petComponent = self->GetComponent(); + if (petComponent == nullptr || petComponent->GetOwnerId() != LWOOBJID_EMPTY) + return; - // Removes the chocolate bars - petComponent->SetPreconditions(const_cast(m_Precondition)); - PetFromObjectServer::OnStartup(self); + // Removes the chocolate bars + petComponent->SetPreconditions(const_cast(m_Precondition)); + PetFromObjectServer::OnStartup(self); } diff --git a/dScripts/NjEarthPetServer.h b/dScripts/NjEarthPetServer.h index 0e327168..3423c019 100644 --- a/dScripts/NjEarthPetServer.h +++ b/dScripts/NjEarthPetServer.h @@ -2,6 +2,6 @@ #include "PetFromObjectServer.h" class NjEarthPetServer : public PetFromObjectServer { - void OnStartup(Entity *self) override; - const std::string m_Precondition = "279"; + void OnStartup(Entity* self) override; + const std::string m_Precondition = "279"; }; diff --git a/dScripts/NjGarmadonCelebration.cpp b/dScripts/NjGarmadonCelebration.cpp index ab71e092..c223c55c 100644 --- a/dScripts/NjGarmadonCelebration.cpp +++ b/dScripts/NjGarmadonCelebration.cpp @@ -2,16 +2,16 @@ #include "Character.h" #include "GameMessages.h" -void NjGarmadonCelebration::OnCollisionPhantom(Entity *self, Entity *target) { - auto* character = target->GetCharacter(); +void NjGarmadonCelebration::OnCollisionPhantom(Entity* self, Entity* target) { + auto* character = target->GetCharacter(); - if (character == nullptr) { - return; - } + if (character == nullptr) { + return; + } - if (!character->GetPlayerFlag(ePlayerFlags::NJ_GARMADON_CINEMATIC_SEEN)) { - character->SetPlayerFlag(ePlayerFlags::NJ_GARMADON_CINEMATIC_SEEN, true); + if (!character->GetPlayerFlag(ePlayerFlags::NJ_GARMADON_CINEMATIC_SEEN)) { + character->SetPlayerFlag(ePlayerFlags::NJ_GARMADON_CINEMATIC_SEEN, true); - GameMessages::SendStartCelebrationEffect(target, target->GetSystemAddress(), GarmadonCelebrationID); - } + GameMessages::SendStartCelebrationEffect(target, target->GetSystemAddress(), GarmadonCelebrationID); + } } diff --git a/dScripts/NjGarmadonCelebration.h b/dScripts/NjGarmadonCelebration.h index 858ecfce..fe08a169 100644 --- a/dScripts/NjGarmadonCelebration.h +++ b/dScripts/NjGarmadonCelebration.h @@ -2,7 +2,7 @@ #include "CppScripts.h" class NjGarmadonCelebration : public CppScripts::Script { - void OnCollisionPhantom(Entity *self, Entity *target) override; + void OnCollisionPhantom(Entity* self, Entity* target) override; private: - const int32_t GarmadonCelebrationID = 23; + const int32_t GarmadonCelebrationID = 23; }; diff --git a/dScripts/NjIceRailActivator.cpp b/dScripts/NjIceRailActivator.cpp index dbf0acd6..2549cd0f 100644 --- a/dScripts/NjIceRailActivator.cpp +++ b/dScripts/NjIceRailActivator.cpp @@ -2,24 +2,24 @@ #include "EntityManager.h" #include "GameMessages.h" -void NjIceRailActivator::OnPlayerRailArrived(Entity *self, Entity *sender, const std::u16string &pathName, - int32_t waypoint) { - const auto breakPoint = self->GetVar(BreakpointVariable); - if (breakPoint == waypoint) { - const auto& blockGroup = self->GetVar(BlockGroupVariable); +void NjIceRailActivator::OnPlayerRailArrived(Entity* self, Entity* sender, const std::u16string& pathName, + int32_t waypoint) { + const auto breakPoint = self->GetVar(BreakpointVariable); + if (breakPoint == waypoint) { + const auto& blockGroup = self->GetVar(BlockGroupVariable); - for (auto* block : EntityManager::Instance()->GetEntitiesInGroup(GeneralUtils::UTF16ToWTF8(blockGroup))) { - GameMessages::SendPlayAnimation(block, u"explode"); + for (auto* block : EntityManager::Instance()->GetEntitiesInGroup(GeneralUtils::UTF16ToWTF8(blockGroup))) { + GameMessages::SendPlayAnimation(block, u"explode"); - const auto blockID = block->GetObjectID(); + const auto blockID = block->GetObjectID(); - self->AddCallbackTimer(1.0f, [self, blockID]() { - auto* block = EntityManager::Instance()->GetEntity(blockID); + self->AddCallbackTimer(1.0f, [self, blockID]() { + auto* block = EntityManager::Instance()->GetEntity(blockID); - if (block != nullptr) { - block->Kill(self); - } - }); - } - } + if (block != nullptr) { + block->Kill(self); + } + }); + } + } } diff --git a/dScripts/NjIceRailActivator.h b/dScripts/NjIceRailActivator.h index dd56be62..05927898 100644 --- a/dScripts/NjIceRailActivator.h +++ b/dScripts/NjIceRailActivator.h @@ -1,10 +1,10 @@ #pragma once #include "NjRailActivatorsServer.h" -class NjIceRailActivator : public NjRailActivatorsServer{ - void OnPlayerRailArrived(Entity* self, Entity* sender, const std::u16string& pathName, int32_t waypoint) override; +class NjIceRailActivator : public NjRailActivatorsServer { + void OnPlayerRailArrived(Entity* self, Entity* sender, const std::u16string& pathName, int32_t waypoint) override; private: - std::u16string BreakpointVariable = u"BreakPoint"; - std::u16string BlockGroupVariable = u"BlockGroup"; - std::u16string IceBlockVariable = u"IceBlock"; + std::u16string BreakpointVariable = u"BreakPoint"; + std::u16string BlockGroupVariable = u"BlockGroup"; + std::u16string IceBlockVariable = u"IceBlock"; }; diff --git a/dScripts/NjJayMissionItems.cpp b/dScripts/NjJayMissionItems.cpp index c4b037bb..cc871b86 100644 --- a/dScripts/NjJayMissionItems.cpp +++ b/dScripts/NjJayMissionItems.cpp @@ -1,13 +1,13 @@ #include "NjJayMissionItems.h" -void NjJayMissionItems::OnMissionDialogueOK(Entity *self, Entity *target, int missionID, MissionState missionState) { - NjNPCMissionSpinjitzuServer::OnMissionDialogueOK(self, target, missionID, missionState); - NPCAddRemoveItem::OnMissionDialogueOK(self, target, missionID, missionState); +void NjJayMissionItems::OnMissionDialogueOK(Entity* self, Entity* target, int missionID, MissionState missionState) { + NjNPCMissionSpinjitzuServer::OnMissionDialogueOK(self, target, missionID, missionState); + NPCAddRemoveItem::OnMissionDialogueOK(self, target, missionID, missionState); } std::map> NjJayMissionItems::GetSettings() { - return { - {1789, {{{14474},false, true}}}, - {1927, {{{14493},false, true}}} - }; + return { + {1789, {{{14474},false, true}}}, + {1927, {{{14493},false, true}}} + }; } diff --git a/dScripts/NjJayMissionItems.h b/dScripts/NjJayMissionItems.h index 19cb4f40..c49f49ea 100644 --- a/dScripts/NjJayMissionItems.h +++ b/dScripts/NjJayMissionItems.h @@ -5,6 +5,6 @@ #include class NjJayMissionItems : public NjNPCMissionSpinjitzuServer, NPCAddRemoveItem { - void OnMissionDialogueOK(Entity *self, Entity *target, int missionID, MissionState missionState) override; - std::map> GetSettings() override; + void OnMissionDialogueOK(Entity* self, Entity* target, int missionID, MissionState missionState) override; + std::map> GetSettings() override; }; diff --git a/dScripts/NjMonastryBossInstance.cpp b/dScripts/NjMonastryBossInstance.cpp index 2aa7222e..dbab7365 100644 --- a/dScripts/NjMonastryBossInstance.cpp +++ b/dScripts/NjMonastryBossInstance.cpp @@ -14,510 +14,510 @@ // Event handling // // // // // // // // -void NjMonastryBossInstance::OnStartup(Entity *self) { - auto spawnerNames = std::vector { LedgeFrakjawSpawner, LowerFrakjawSpawner, BaseEnemiesSpawner + std::to_string(1), - BaseEnemiesSpawner + std::to_string(2), BaseEnemiesSpawner + std::to_string(3), - BaseEnemiesSpawner + std::to_string(4), CounterweightSpawner }; +void NjMonastryBossInstance::OnStartup(Entity* self) { + auto spawnerNames = std::vector{ LedgeFrakjawSpawner, LowerFrakjawSpawner, BaseEnemiesSpawner + std::to_string(1), + BaseEnemiesSpawner + std::to_string(2), BaseEnemiesSpawner + std::to_string(3), + BaseEnemiesSpawner + std::to_string(4), CounterweightSpawner }; - // Add a notification request for all the spawned entities, corresponds to notifySpawnedObjectLoaded - for (const auto& spawnerName : spawnerNames) { - for (auto* spawner : dZoneManager::Instance()->GetSpawnersByName(spawnerName)) { - spawner->AddEntitySpawnedCallback([self, this](Entity* entity) { - const auto lot = entity->GetLOT(); - switch (lot) { - case LedgedFrakjawLOT: - NjMonastryBossInstance::HandleLedgedFrakjawSpawned(self, entity); - return; - case CounterWeightLOT: - NjMonastryBossInstance::HandleCounterWeightSpawned(self, entity); - return; - case LowerFrakjawLOT: - NjMonastryBossInstance::HandleLowerFrakjawSpawned(self, entity); - return; - default: - NjMonastryBossInstance::HandleWaveEnemySpawned(self, entity); - return; - } - }); - } - } + // Add a notification request for all the spawned entities, corresponds to notifySpawnedObjectLoaded + for (const auto& spawnerName : spawnerNames) { + for (auto* spawner : dZoneManager::Instance()->GetSpawnersByName(spawnerName)) { + spawner->AddEntitySpawnedCallback([self, this](Entity* entity) { + const auto lot = entity->GetLOT(); + switch (lot) { + case LedgedFrakjawLOT: + NjMonastryBossInstance::HandleLedgedFrakjawSpawned(self, entity); + return; + case CounterWeightLOT: + NjMonastryBossInstance::HandleCounterWeightSpawned(self, entity); + return; + case LowerFrakjawLOT: + NjMonastryBossInstance::HandleLowerFrakjawSpawned(self, entity); + return; + default: + NjMonastryBossInstance::HandleWaveEnemySpawned(self, entity); + return; + } + }); + } + } } -void NjMonastryBossInstance::OnPlayerLoaded(Entity *self, Entity *player) { - ActivityTimerStop(self, WaitingForPlayersTimer); +void NjMonastryBossInstance::OnPlayerLoaded(Entity* self, Entity* player) { + ActivityTimerStop(self, WaitingForPlayersTimer); - // Join the player in the activity - UpdatePlayer(self, player->GetObjectID()); + // Join the player in the activity + UpdatePlayer(self, player->GetObjectID()); - // Buff the player - auto* destroyableComponent = player->GetComponent(); - if (destroyableComponent != nullptr) { - destroyableComponent->SetHealth((int32_t) destroyableComponent->GetMaxHealth()); - destroyableComponent->SetArmor((int32_t) destroyableComponent->GetMaxArmor()); - destroyableComponent->SetImagination((int32_t) destroyableComponent->GetMaxImagination()); - } + // Buff the player + auto* destroyableComponent = player->GetComponent(); + if (destroyableComponent != nullptr) { + destroyableComponent->SetHealth((int32_t)destroyableComponent->GetMaxHealth()); + destroyableComponent->SetArmor((int32_t)destroyableComponent->GetMaxArmor()); + destroyableComponent->SetImagination((int32_t)destroyableComponent->GetMaxImagination()); + } - // Add player ID to instance - auto totalPlayersLoaded = self->GetVar>(TotalPlayersLoadedVariable); - totalPlayersLoaded.push_back(player->GetObjectID()); + // Add player ID to instance + auto totalPlayersLoaded = self->GetVar>(TotalPlayersLoadedVariable); + totalPlayersLoaded.push_back(player->GetObjectID()); - // Properly position the player - self->SetVar>(TotalPlayersLoadedVariable, totalPlayersLoaded); - // This was always spawning all players at position one before and other values cause players to be invisible. - TeleportPlayer(player, 1); + // Properly position the player + self->SetVar>(TotalPlayersLoadedVariable, totalPlayersLoaded); + // This was always spawning all players at position one before and other values cause players to be invisible. + TeleportPlayer(player, 1); - // Large teams face a tougher challenge - if (totalPlayersLoaded.size() >= 3) - self->SetVar(LargeTeamVariable, true); + // Large teams face a tougher challenge + if (totalPlayersLoaded.size() >= 3) + self->SetVar(LargeTeamVariable, true); - // Start the game if all players in the team have loaded - auto* team = TeamManager::Instance()->GetTeam(player->GetObjectID()); - if (team == nullptr || totalPlayersLoaded.size() == team->members.size()) { - StartFight(self); - return; - } + // Start the game if all players in the team have loaded + auto* team = TeamManager::Instance()->GetTeam(player->GetObjectID()); + if (team == nullptr || totalPlayersLoaded.size() == team->members.size()) { + StartFight(self); + return; + } - self->AddCallbackTimer(0.0f, [self, player]() { - if (player != nullptr) { - // If we don't have enough players yet, wait for the others to load and notify the client to play a cool cinematic - GameMessages::SendNotifyClientObject(self->GetObjectID(), u"PlayerLoaded", 0, 0, - player->GetObjectID(), "", player->GetSystemAddress()); - } - }); + self->AddCallbackTimer(0.0f, [self, player]() { + if (player != nullptr) { + // If we don't have enough players yet, wait for the others to load and notify the client to play a cool cinematic + GameMessages::SendNotifyClientObject(self->GetObjectID(), u"PlayerLoaded", 0, 0, + player->GetObjectID(), "", player->GetSystemAddress()); + } + }); - ActivityTimerStart(self, WaitingForPlayersTimer, 45.0f, 45.0f); + ActivityTimerStart(self, WaitingForPlayersTimer, 45.0f, 45.0f); } -void NjMonastryBossInstance::OnPlayerExit(Entity *self, Entity *player) { - UpdatePlayer(self, player->GetObjectID(), true); - // Fetch the total players loaded from the vars - auto totalPlayersLoaded = self->GetVar >(TotalPlayersLoadedVariable); +void NjMonastryBossInstance::OnPlayerExit(Entity* self, Entity* player) { + UpdatePlayer(self, player->GetObjectID(), true); + // Fetch the total players loaded from the vars + auto totalPlayersLoaded = self->GetVar >(TotalPlayersLoadedVariable); - // Find the player to remove - auto playerToRemove = std::find(totalPlayersLoaded.begin(), totalPlayersLoaded.end(), player->GetObjectID()); + // Find the player to remove + auto playerToRemove = std::find(totalPlayersLoaded.begin(), totalPlayersLoaded.end(), player->GetObjectID()); - // If we found the player remove them from out list of players - if (playerToRemove != totalPlayersLoaded.end()) { - totalPlayersLoaded.erase(playerToRemove); - } else { - Game::logger->Log("NjMonastryBossInstance", "Failed to remove player at exit."); - } + // If we found the player remove them from out list of players + if (playerToRemove != totalPlayersLoaded.end()) { + totalPlayersLoaded.erase(playerToRemove); + } else { + Game::logger->Log("NjMonastryBossInstance", "Failed to remove player at exit."); + } - // Set the players loaded var back - self->SetVar>(TotalPlayersLoadedVariable, totalPlayersLoaded); + // Set the players loaded var back + self->SetVar>(TotalPlayersLoadedVariable, totalPlayersLoaded); - // Since this is an exit method, check if enough players have left. If enough have left - // resize the instance to account for such. - if (totalPlayersLoaded.size() <= 2) self->SetVar(LargeTeamVariable, false); + // Since this is an exit method, check if enough players have left. If enough have left + // resize the instance to account for such. + if (totalPlayersLoaded.size() <= 2) self->SetVar(LargeTeamVariable, false); - GameMessages::SendNotifyClientObject(self->GetObjectID(), u"PlayerLeft", 0, 0, player->GetObjectID(), "", UNASSIGNED_SYSTEM_ADDRESS); + GameMessages::SendNotifyClientObject(self->GetObjectID(), u"PlayerLeft", 0, 0, player->GetObjectID(), "", UNASSIGNED_SYSTEM_ADDRESS); } -void NjMonastryBossInstance::OnActivityTimerDone(Entity *self, const std::string &name) { - auto split = GeneralUtils::SplitString(name, TimerSplitChar); - auto timerName = split[0]; - auto objectID = split.size() > 1 ? (LWOOBJID) std::stoull(split[1]) : LWOOBJID_EMPTY; +void NjMonastryBossInstance::OnActivityTimerDone(Entity* self, const std::string& name) { + auto split = GeneralUtils::SplitString(name, TimerSplitChar); + auto timerName = split[0]; + auto objectID = split.size() > 1 ? (LWOOBJID)std::stoull(split[1]) : LWOOBJID_EMPTY; - if (timerName == WaitingForPlayersTimer) { - StartFight(self); - } else if (timerName == SpawnNextWaveTimer) { - auto* frakjaw = EntityManager::Instance()->GetEntity(self->GetVar(LedgeFrakjawVariable)); - if (frakjaw != nullptr) { - SummonWave(self, frakjaw); - } - } else if (timerName == SpawnWaveTimer) { - auto wave = self->GetVar(WaveNumberVariable); - self->SetVar(WaveNumberVariable, wave + 1); - self->SetVar(TotalAliveInWaveVariable, 0); + if (timerName == WaitingForPlayersTimer) { + StartFight(self); + } else if (timerName == SpawnNextWaveTimer) { + auto* frakjaw = EntityManager::Instance()->GetEntity(self->GetVar(LedgeFrakjawVariable)); + if (frakjaw != nullptr) { + SummonWave(self, frakjaw); + } + } else if (timerName == SpawnWaveTimer) { + auto wave = self->GetVar(WaveNumberVariable); + self->SetVar(WaveNumberVariable, wave + 1); + self->SetVar(TotalAliveInWaveVariable, 0); - if (wave < m_Waves.size()) { - auto waves = m_Waves.at(wave); - auto counter = 0; + if (wave < m_Waves.size()) { + auto waves = m_Waves.at(wave); + auto counter = 0; - for (const auto& waveEnemy : waves) { - const auto numberToSpawn = self->GetVar(LargeTeamVariable) - ? waveEnemy.largeNumber : waveEnemy.smallNumber; + for (const auto& waveEnemy : waves) { + const auto numberToSpawn = self->GetVar(LargeTeamVariable) + ? waveEnemy.largeNumber : waveEnemy.smallNumber; - auto spawnIndex = counter % 4 + 1; - SpawnOnNetwork(self, waveEnemy.lot, numberToSpawn, BaseEnemiesSpawner + std::to_string(spawnIndex)); - counter++; - } - } - } else if (timerName + TimerSplitChar == UnstunTimer) { - auto* entity = EntityManager::Instance()->GetEntity(objectID); - if (entity != nullptr) { - auto* combatAI = entity->GetComponent(); - if (combatAI != nullptr) { - combatAI->SetDisabled(false); - } - } - } else if (timerName == SpawnCounterWeightTimer) { - auto spawners = dZoneManager::Instance()->GetSpawnersByName(CounterweightSpawner); - if (!spawners.empty()) { - // Spawn the counter weight at a specific waypoint, there's one for each round - auto* spawner = spawners.front(); + auto spawnIndex = counter % 4 + 1; + SpawnOnNetwork(self, waveEnemy.lot, numberToSpawn, BaseEnemiesSpawner + std::to_string(spawnIndex)); + counter++; + } + } + } else if (timerName + TimerSplitChar == UnstunTimer) { + auto* entity = EntityManager::Instance()->GetEntity(objectID); + if (entity != nullptr) { + auto* combatAI = entity->GetComponent(); + if (combatAI != nullptr) { + combatAI->SetDisabled(false); + } + } + } else if (timerName == SpawnCounterWeightTimer) { + auto spawners = dZoneManager::Instance()->GetSpawnersByName(CounterweightSpawner); + if (!spawners.empty()) { + // Spawn the counter weight at a specific waypoint, there's one for each round + auto* spawner = spawners.front(); - spawner->Spawn({ - spawner->m_Info.nodes.at((self->GetVar(WaveNumberVariable) - 1) % 3) - }, true); - } - } else if (timerName == LowerFrakjawCamTimer) { - // Destroy the frakjaw on the ledge - auto* ledgeFrakjaw = EntityManager::Instance()->GetEntity(self->GetVar(LedgeFrakjawVariable)); - if (ledgeFrakjaw != nullptr) { - ledgeFrakjaw->Kill(); - } + spawner->Spawn({ + spawner->m_Info.nodes.at((self->GetVar(WaveNumberVariable) - 1) % 3) + }, true); + } + } else if (timerName == LowerFrakjawCamTimer) { + // Destroy the frakjaw on the ledge + auto* ledgeFrakjaw = EntityManager::Instance()->GetEntity(self->GetVar(LedgeFrakjawVariable)); + if (ledgeFrakjaw != nullptr) { + ledgeFrakjaw->Kill(); + } - ActivityTimerStart(self, SpawnLowerFrakjawTimer, 1.0f, 1.0f); - GameMessages::SendNotifyClientObject(self->GetObjectID(), PlayCinematicNotification, 0, 0, - LWOOBJID_EMPTY, BottomFrakSpawn, UNASSIGNED_SYSTEM_ADDRESS); - } else if (timerName == SpawnLowerFrakjawTimer) { - auto spawners = dZoneManager::Instance()->GetSpawnersByName(LowerFrakjawSpawner); - if (!spawners.empty()) { - auto* spawner = spawners.front(); - spawner->Activate(); - } - } else if (timerName == SpawnRailTimer) { - GameMessages::SendNotifyClientObject(self->GetObjectID(), PlayCinematicNotification, 0, 0, - LWOOBJID_EMPTY, FireRailSpawn, UNASSIGNED_SYSTEM_ADDRESS); + ActivityTimerStart(self, SpawnLowerFrakjawTimer, 1.0f, 1.0f); + GameMessages::SendNotifyClientObject(self->GetObjectID(), PlayCinematicNotification, 0, 0, + LWOOBJID_EMPTY, BottomFrakSpawn, UNASSIGNED_SYSTEM_ADDRESS); + } else if (timerName == SpawnLowerFrakjawTimer) { + auto spawners = dZoneManager::Instance()->GetSpawnersByName(LowerFrakjawSpawner); + if (!spawners.empty()) { + auto* spawner = spawners.front(); + spawner->Activate(); + } + } else if (timerName == SpawnRailTimer) { + GameMessages::SendNotifyClientObject(self->GetObjectID(), PlayCinematicNotification, 0, 0, + LWOOBJID_EMPTY, FireRailSpawn, UNASSIGNED_SYSTEM_ADDRESS); - auto spawners = dZoneManager::Instance()->GetSpawnersByName(FireRailSpawner); - if (!spawners.empty()) { - auto* spawner = spawners.front(); - spawner->Activate(); - } - } else if (timerName + TimerSplitChar == FrakjawSpawnInTimer) { - auto* lowerFrakjaw = EntityManager::Instance()->GetEntity(objectID); - if (lowerFrakjaw != nullptr) { - LowerFrakjawSummon(self, lowerFrakjaw); - } - } else if (timerName == WaveOverTimer) { - WaveOver(self); - } else if (timerName == FightOverTimer) { - FightOver(self); - } + auto spawners = dZoneManager::Instance()->GetSpawnersByName(FireRailSpawner); + if (!spawners.empty()) { + auto* spawner = spawners.front(); + spawner->Activate(); + } + } else if (timerName + TimerSplitChar == FrakjawSpawnInTimer) { + auto* lowerFrakjaw = EntityManager::Instance()->GetEntity(objectID); + if (lowerFrakjaw != nullptr) { + LowerFrakjawSummon(self, lowerFrakjaw); + } + } else if (timerName == WaveOverTimer) { + WaveOver(self); + } else if (timerName == FightOverTimer) { + FightOver(self); + } } // // // // // // // // // Custom functions // // // // // // // // // -void NjMonastryBossInstance::StartFight(Entity *self) { - if (self->GetVar(FightStartedVariable)) - return; +void NjMonastryBossInstance::StartFight(Entity* self) { + if (self->GetVar(FightStartedVariable)) + return; - self->SetVar(FightStartedVariable, true); + self->SetVar(FightStartedVariable, true); - // Activate the frakjaw spawner - for (auto* spawner : dZoneManager::Instance()->GetSpawnersByName(LedgeFrakjawSpawner)) { - spawner->Activate(); - } + // Activate the frakjaw spawner + for (auto* spawner : dZoneManager::Instance()->GetSpawnersByName(LedgeFrakjawSpawner)) { + spawner->Activate(); + } } -void NjMonastryBossInstance::HandleLedgedFrakjawSpawned(Entity *self, Entity *ledgedFrakjaw) { - self->SetVar(LedgeFrakjawVariable, ledgedFrakjaw->GetObjectID()); - SummonWave(self, ledgedFrakjaw); +void NjMonastryBossInstance::HandleLedgedFrakjawSpawned(Entity* self, Entity* ledgedFrakjaw) { + self->SetVar(LedgeFrakjawVariable, ledgedFrakjaw->GetObjectID()); + SummonWave(self, ledgedFrakjaw); } -void NjMonastryBossInstance::HandleCounterWeightSpawned(Entity *self, Entity *counterWeight) { - auto* rebuildComponent = counterWeight->GetComponent(); - if (rebuildComponent != nullptr) { - rebuildComponent->AddRebuildStateCallback([this, self, counterWeight](eRebuildState state) { +void NjMonastryBossInstance::HandleCounterWeightSpawned(Entity* self, Entity* counterWeight) { + auto* rebuildComponent = counterWeight->GetComponent(); + if (rebuildComponent != nullptr) { + rebuildComponent->AddRebuildStateCallback([this, self, counterWeight](eRebuildState state) { - switch (state) { - case REBUILD_BUILDING: - GameMessages::SendNotifyClientObject(self->GetObjectID(), PlayCinematicNotification, - 0, 0, counterWeight->GetObjectID(), - BaseCounterweightQB + std::to_string(self->GetVar(WaveNumberVariable)), - UNASSIGNED_SYSTEM_ADDRESS); - return; - case REBUILD_INCOMPLETE: - GameMessages::SendNotifyClientObject(self->GetObjectID(), EndCinematicNotification, - 0, 0, LWOOBJID_EMPTY,"", - UNASSIGNED_SYSTEM_ADDRESS); - return; - case REBUILD_RESETTING: - ActivityTimerStart(self, SpawnCounterWeightTimer, 0.0f, 0.0f); - return; - case REBUILD_COMPLETED: { - // TODO: Move the platform? + switch (state) { + case REBUILD_BUILDING: + GameMessages::SendNotifyClientObject(self->GetObjectID(), PlayCinematicNotification, + 0, 0, counterWeight->GetObjectID(), + BaseCounterweightQB + std::to_string(self->GetVar(WaveNumberVariable)), + UNASSIGNED_SYSTEM_ADDRESS); + return; + case REBUILD_INCOMPLETE: + GameMessages::SendNotifyClientObject(self->GetObjectID(), EndCinematicNotification, + 0, 0, LWOOBJID_EMPTY, "", + UNASSIGNED_SYSTEM_ADDRESS); + return; + case REBUILD_RESETTING: + ActivityTimerStart(self, SpawnCounterWeightTimer, 0.0f, 0.0f); + return; + case REBUILD_COMPLETED: { + // TODO: Move the platform? - // The counterweight is actually a moving platform and we should listen to the last waypoint event here - // 0.5f is a rough estimate of that path, though, and results in less needed logic - self->AddCallbackTimer(0.5f, [this, self, counterWeight]() { - if (counterWeight != nullptr) { - counterWeight->Kill(); - } + // The counterweight is actually a moving platform and we should listen to the last waypoint event here + // 0.5f is a rough estimate of that path, though, and results in less needed logic + self->AddCallbackTimer(0.5f, [this, self, counterWeight]() { + if (counterWeight != nullptr) { + counterWeight->Kill(); + } - auto* frakjaw = EntityManager::Instance()->GetEntity(self->GetVar(LedgeFrakjawVariable)); - if (frakjaw == nullptr) { - GameMessages::SendNotifyClientObject(self->GetObjectID(), u"LedgeFrakjawDead", 0, - 0, LWOOBJID_EMPTY, "", UNASSIGNED_SYSTEM_ADDRESS); - return; - } + auto* frakjaw = EntityManager::Instance()->GetEntity(self->GetVar(LedgeFrakjawVariable)); + if (frakjaw == nullptr) { + GameMessages::SendNotifyClientObject(self->GetObjectID(), u"LedgeFrakjawDead", 0, + 0, LWOOBJID_EMPTY, "", UNASSIGNED_SYSTEM_ADDRESS); + return; + } - auto* skillComponent = frakjaw->GetComponent(); - if (skillComponent != nullptr) { - skillComponent->CalculateBehavior(1635, 39097, frakjaw->GetObjectID(), true, false); - } + auto* skillComponent = frakjaw->GetComponent(); + if (skillComponent != nullptr) { + skillComponent->CalculateBehavior(1635, 39097, frakjaw->GetObjectID(), true, false); + } - GameMessages::SendPlayAnimation(frakjaw, StunnedAnimation); - GameMessages::SendPlayNDAudioEmitter(frakjaw, UNASSIGNED_SYSTEM_ADDRESS, CounterSmashAudio); + GameMessages::SendPlayAnimation(frakjaw, StunnedAnimation); + GameMessages::SendPlayNDAudioEmitter(frakjaw, UNASSIGNED_SYSTEM_ADDRESS, CounterSmashAudio); - // Before wave 4 we should lower frakjaw from the ledge - if (self->GetVar(WaveNumberVariable) == 3) { - LowerFrakjaw(self, frakjaw); - return; - } + // Before wave 4 we should lower frakjaw from the ledge + if (self->GetVar(WaveNumberVariable) == 3) { + LowerFrakjaw(self, frakjaw); + return; + } - ActivityTimerStart(self, SpawnNextWaveTimer, 2.0f, 2.0f); - }); - } - default: - return; - } - }); - } + ActivityTimerStart(self, SpawnNextWaveTimer, 2.0f, 2.0f); + }); + } + default: + return; + } + }); + } } -void NjMonastryBossInstance::HandleLowerFrakjawSpawned(Entity *self, Entity *lowerFrakjaw) { - GameMessages::SendPlayAnimation(lowerFrakjaw, TeleportInAnimation); - self->SetVar(LowerFrakjawVariable, lowerFrakjaw->GetObjectID()); +void NjMonastryBossInstance::HandleLowerFrakjawSpawned(Entity* self, Entity* lowerFrakjaw) { + GameMessages::SendPlayAnimation(lowerFrakjaw, TeleportInAnimation); + self->SetVar(LowerFrakjawVariable, lowerFrakjaw->GetObjectID()); - auto* combatAI = lowerFrakjaw->GetComponent(); - if (combatAI != nullptr) { - combatAI->SetDisabled(true); - } + auto* combatAI = lowerFrakjaw->GetComponent(); + if (combatAI != nullptr) { + combatAI->SetDisabled(true); + } - auto* destroyableComponent = lowerFrakjaw->GetComponent(); - if (destroyableComponent != nullptr) { - destroyableComponent->AddOnHitCallback([this, self, lowerFrakjaw](Entity* attacker) { - NjMonastryBossInstance::HandleLowerFrakjawHit(self, lowerFrakjaw, attacker); - }); - } + auto* destroyableComponent = lowerFrakjaw->GetComponent(); + if (destroyableComponent != nullptr) { + destroyableComponent->AddOnHitCallback([this, self, lowerFrakjaw](Entity* attacker) { + NjMonastryBossInstance::HandleLowerFrakjawHit(self, lowerFrakjaw, attacker); + }); + } - lowerFrakjaw->AddDieCallback([this, self, lowerFrakjaw]() { - NjMonastryBossInstance::HandleLowerFrakjawDied(self, lowerFrakjaw); - }); + lowerFrakjaw->AddDieCallback([this, self, lowerFrakjaw]() { + NjMonastryBossInstance::HandleLowerFrakjawDied(self, lowerFrakjaw); + }); - GameMessages::SendNotifyClientObject(self->GetObjectID(), u"LedgeFrakjawDead", 0, 0, - LWOOBJID_EMPTY, "", UNASSIGNED_SYSTEM_ADDRESS); + GameMessages::SendNotifyClientObject(self->GetObjectID(), u"LedgeFrakjawDead", 0, 0, + LWOOBJID_EMPTY, "", UNASSIGNED_SYSTEM_ADDRESS); - if (self->GetVar(LargeTeamVariable)) { - // Double frakjaws health for large teams - if (destroyableComponent != nullptr) { - const auto doubleHealth = destroyableComponent->GetHealth() * 2; - destroyableComponent->SetHealth(doubleHealth); - destroyableComponent->SetMaxHealth((float_t) doubleHealth); - } + if (self->GetVar(LargeTeamVariable)) { + // Double frakjaws health for large teams + if (destroyableComponent != nullptr) { + const auto doubleHealth = destroyableComponent->GetHealth() * 2; + destroyableComponent->SetHealth(doubleHealth); + destroyableComponent->SetMaxHealth((float_t)doubleHealth); + } - ActivityTimerStart(self, FrakjawSpawnInTimer + std::to_string(lowerFrakjaw->GetObjectID()), - 2.0f, 2.0f); - ActivityTimerStart(self, UnstunTimer + std::to_string(lowerFrakjaw->GetObjectID()), - 7.0f, 7.0f); - } else { - ActivityTimerStart(self, UnstunTimer + std::to_string(lowerFrakjaw->GetObjectID()), - 5.0f, 5.0f); - } + ActivityTimerStart(self, FrakjawSpawnInTimer + std::to_string(lowerFrakjaw->GetObjectID()), + 2.0f, 2.0f); + ActivityTimerStart(self, UnstunTimer + std::to_string(lowerFrakjaw->GetObjectID()), + 7.0f, 7.0f); + } else { + ActivityTimerStart(self, UnstunTimer + std::to_string(lowerFrakjaw->GetObjectID()), + 5.0f, 5.0f); + } } -void NjMonastryBossInstance::HandleLowerFrakjawHit(Entity *self, Entity *lowerFrakjaw, Entity *attacker) { - auto* destroyableComponent = lowerFrakjaw->GetComponent(); - if (destroyableComponent == nullptr) - return; +void NjMonastryBossInstance::HandleLowerFrakjawHit(Entity* self, Entity* lowerFrakjaw, Entity* attacker) { + auto* destroyableComponent = lowerFrakjaw->GetComponent(); + if (destroyableComponent == nullptr) + return; - // Progress the fight to the last wave if frakjaw has less than 50% of his health left - if (destroyableComponent->GetHealth() <= (uint32_t) destroyableComponent->GetMaxHealth() / 2 && !self->GetVar(OnLastWaveVarbiale)) { - self->SetVar(OnLastWaveVarbiale, true); + // Progress the fight to the last wave if frakjaw has less than 50% of his health left + if (destroyableComponent->GetHealth() <= (uint32_t)destroyableComponent->GetMaxHealth() / 2 && !self->GetVar(OnLastWaveVarbiale)) { + self->SetVar(OnLastWaveVarbiale, true); - // Stun frakjaw during the cinematic - auto* combatAI = lowerFrakjaw->GetComponent(); - if (combatAI != nullptr) { - combatAI->SetDisabled(true); - } - ActivityTimerStart(self, UnstunTimer + std::to_string(lowerFrakjaw->GetObjectID()), 5.0f, 5.0f); + // Stun frakjaw during the cinematic + auto* combatAI = lowerFrakjaw->GetComponent(); + if (combatAI != nullptr) { + combatAI->SetDisabled(true); + } + ActivityTimerStart(self, UnstunTimer + std::to_string(lowerFrakjaw->GetObjectID()), 5.0f, 5.0f); - const auto trashMobsAlive = self->GetVar>(TrashMobsAliveVariable); - std::vector newTrashMobs = {}; + const auto trashMobsAlive = self->GetVar>(TrashMobsAliveVariable); + std::vector newTrashMobs = {}; - for (const auto& trashMobID : trashMobsAlive) { - auto* trashMob = EntityManager::Instance()->GetEntity(trashMobID); - if (trashMob != nullptr) { - newTrashMobs.push_back(trashMobID); + for (const auto& trashMobID : trashMobsAlive) { + auto* trashMob = EntityManager::Instance()->GetEntity(trashMobID); + if (trashMob != nullptr) { + newTrashMobs.push_back(trashMobID); - // Stun all the enemies until the cinematic is over - auto* trashMobCombatAI = trashMob->GetComponent(); - if (trashMobCombatAI != nullptr) { - trashMobCombatAI->SetDisabled(true); - } - ActivityTimerStart(self, UnstunTimer + std::to_string(trashMobID), 5.0f, 5.0f); - } - } + // Stun all the enemies until the cinematic is over + auto* trashMobCombatAI = trashMob->GetComponent(); + if (trashMobCombatAI != nullptr) { + trashMobCombatAI->SetDisabled(true); + } + ActivityTimerStart(self, UnstunTimer + std::to_string(trashMobID), 5.0f, 5.0f); + } + } - self->SetVar>(TrashMobsAliveVariable, newTrashMobs); + self->SetVar>(TrashMobsAliveVariable, newTrashMobs); - LowerFrakjawSummon(self, lowerFrakjaw); - RemovePoison(self); - } + LowerFrakjawSummon(self, lowerFrakjaw); + RemovePoison(self); + } } -void NjMonastryBossInstance::HandleLowerFrakjawDied(Entity *self, Entity *lowerFrakjaw) { - ActivityTimerStart(self, FightOverTimer, 2.0f, 2.0f); +void NjMonastryBossInstance::HandleLowerFrakjawDied(Entity* self, Entity* lowerFrakjaw) { + ActivityTimerStart(self, FightOverTimer, 2.0f, 2.0f); } -void NjMonastryBossInstance::HandleWaveEnemySpawned(Entity *self, Entity *waveEnemy) { - waveEnemy->AddDieCallback([this, self, waveEnemy]() { - NjMonastryBossInstance::HandleWaveEnemyDied(self, waveEnemy); - }); +void NjMonastryBossInstance::HandleWaveEnemySpawned(Entity* self, Entity* waveEnemy) { + waveEnemy->AddDieCallback([this, self, waveEnemy]() { + NjMonastryBossInstance::HandleWaveEnemyDied(self, waveEnemy); + }); - auto waveEnemies = self->GetVar>(TrashMobsAliveVariable); - waveEnemies.push_back(waveEnemy->GetObjectID()); - self->SetVar>(TrashMobsAliveVariable, waveEnemies); + auto waveEnemies = self->GetVar>(TrashMobsAliveVariable); + waveEnemies.push_back(waveEnemy->GetObjectID()); + self->SetVar>(TrashMobsAliveVariable, waveEnemies); - auto* combatAI = waveEnemy->GetComponent(); - if (combatAI != nullptr) { - combatAI->SetDisabled(true); - ActivityTimerStart(self, UnstunTimer + std::to_string(waveEnemy->GetObjectID()), 3.0f, 3.0f); - } + auto* combatAI = waveEnemy->GetComponent(); + if (combatAI != nullptr) { + combatAI->SetDisabled(true); + ActivityTimerStart(self, UnstunTimer + std::to_string(waveEnemy->GetObjectID()), 3.0f, 3.0f); + } } -void NjMonastryBossInstance::HandleWaveEnemyDied(Entity *self, Entity* waveEnemy) { - auto waveEnemies = self->GetVar>(TrashMobsAliveVariable); - waveEnemies.erase(std::remove(waveEnemies.begin(), waveEnemies.end(), waveEnemy->GetObjectID()), waveEnemies.end()); - self->SetVar>(TrashMobsAliveVariable, waveEnemies); +void NjMonastryBossInstance::HandleWaveEnemyDied(Entity* self, Entity* waveEnemy) { + auto waveEnemies = self->GetVar>(TrashMobsAliveVariable); + waveEnemies.erase(std::remove(waveEnemies.begin(), waveEnemies.end(), waveEnemy->GetObjectID()), waveEnemies.end()); + self->SetVar>(TrashMobsAliveVariable, waveEnemies); - if (waveEnemies.empty()) { - ActivityTimerStart(self, WaveOverTimer, 2.0f, 2.0f); - } + if (waveEnemies.empty()) { + ActivityTimerStart(self, WaveOverTimer, 2.0f, 2.0f); + } } -void NjMonastryBossInstance::TeleportPlayer(Entity *player, uint32_t position) { - for (const auto* spawnPoint : EntityManager::Instance()->GetEntitiesInGroup("SpawnPoint" + std::to_string(position))) { - GameMessages::SendTeleport(player->GetObjectID(), spawnPoint->GetPosition(), spawnPoint->GetRotation(), - player->GetSystemAddress(), true); - } +void NjMonastryBossInstance::TeleportPlayer(Entity* player, uint32_t position) { + for (const auto* spawnPoint : EntityManager::Instance()->GetEntitiesInGroup("SpawnPoint" + std::to_string(position))) { + GameMessages::SendTeleport(player->GetObjectID(), spawnPoint->GetPosition(), spawnPoint->GetRotation(), + player->GetSystemAddress(), true); + } } void NjMonastryBossInstance::SummonWave(Entity* self, Entity* frakjaw) { - GameMessages::SendNotifyClientObject(self->GetObjectID(), PlayCinematicNotification, 0, 0, LWOOBJID_EMPTY, - LedgeFrakSummon, UNASSIGNED_SYSTEM_ADDRESS); - GameMessages::SendPlayAnimation(frakjaw, SummonAnimation); + GameMessages::SendNotifyClientObject(self->GetObjectID(), PlayCinematicNotification, 0, 0, LWOOBJID_EMPTY, + LedgeFrakSummon, UNASSIGNED_SYSTEM_ADDRESS); + GameMessages::SendPlayAnimation(frakjaw, SummonAnimation); - // Stop the music for the first, fourth and fifth wave - const auto wave = self->GetVar(WaveNumberVariable); - if (wave >= 1 || wave < (m_Waves.size() - 1)) { - GameMessages::SendNotifyClientObject(self->GetObjectID(), StopMusicNotification, 0, 0, - LWOOBJID_EMPTY, AudioWaveAudio + std::to_string(wave - 1), - UNASSIGNED_SYSTEM_ADDRESS); - } + // Stop the music for the first, fourth and fifth wave + const auto wave = self->GetVar(WaveNumberVariable); + if (wave >= 1 || wave < (m_Waves.size() - 1)) { + GameMessages::SendNotifyClientObject(self->GetObjectID(), StopMusicNotification, 0, 0, + LWOOBJID_EMPTY, AudioWaveAudio + std::to_string(wave - 1), + UNASSIGNED_SYSTEM_ADDRESS); + } - // After frakjaw moves down the music stays the same - if (wave < (m_Waves.size() - 1)) { - GameMessages::SendNotifyClientObject(self->GetObjectID(), StartMusicNotification, 0, 0, - LWOOBJID_EMPTY, AudioWaveAudio + std::to_string(wave), - UNASSIGNED_SYSTEM_ADDRESS); - } + // After frakjaw moves down the music stays the same + if (wave < (m_Waves.size() - 1)) { + GameMessages::SendNotifyClientObject(self->GetObjectID(), StartMusicNotification, 0, 0, + LWOOBJID_EMPTY, AudioWaveAudio + std::to_string(wave), + UNASSIGNED_SYSTEM_ADDRESS); + } - ActivityTimerStart(self, SpawnWaveTimer, 4.0f, 4.0f); + ActivityTimerStart(self, SpawnWaveTimer, 4.0f, 4.0f); } -void NjMonastryBossInstance::LowerFrakjawSummon(Entity *self, Entity *frakjaw) { - GameMessages::SendNotifyClientObject(self->GetObjectID(), PlayCinematicNotification, 0, 0, - LWOOBJID_EMPTY, BottomFrakSummon, UNASSIGNED_SYSTEM_ADDRESS); - ActivityTimerStart(self, SpawnWaveTimer, 2.0f, 2.0f); - GameMessages::SendPlayAnimation(frakjaw, SummonAnimation); +void NjMonastryBossInstance::LowerFrakjawSummon(Entity* self, Entity* frakjaw) { + GameMessages::SendNotifyClientObject(self->GetObjectID(), PlayCinematicNotification, 0, 0, + LWOOBJID_EMPTY, BottomFrakSummon, UNASSIGNED_SYSTEM_ADDRESS); + ActivityTimerStart(self, SpawnWaveTimer, 2.0f, 2.0f); + GameMessages::SendPlayAnimation(frakjaw, SummonAnimation); } -void NjMonastryBossInstance::RemovePoison(Entity *self) { - const auto& totalPlayer = self->GetVar>(TotalPlayersLoadedVariable); - for (const auto& playerID : totalPlayer) { +void NjMonastryBossInstance::RemovePoison(Entity* self) { + const auto& totalPlayer = self->GetVar>(TotalPlayersLoadedVariable); + for (const auto& playerID : totalPlayer) { - auto* player = EntityManager::Instance()->GetEntity(playerID); - if (player != nullptr) { + auto* player = EntityManager::Instance()->GetEntity(playerID); + if (player != nullptr) { - auto* buffComponent = player->GetComponent(); - if (buffComponent != nullptr) { - buffComponent->RemoveBuff(PoisonBuff); - } - } - } + auto* buffComponent = player->GetComponent(); + if (buffComponent != nullptr) { + buffComponent->RemoveBuff(PoisonBuff); + } + } + } } -void NjMonastryBossInstance::LowerFrakjaw(Entity *self, Entity* frakjaw) { - GameMessages::SendPlayAnimation(frakjaw, TeleportOutAnimation); - ActivityTimerStart(self, LowerFrakjawCamTimer, 2.0f, 2.0f); +void NjMonastryBossInstance::LowerFrakjaw(Entity* self, Entity* frakjaw) { + GameMessages::SendPlayAnimation(frakjaw, TeleportOutAnimation); + ActivityTimerStart(self, LowerFrakjawCamTimer, 2.0f, 2.0f); - GameMessages::SendNotifyClientObject(frakjaw->GetObjectID(), StopMusicNotification, 0, 0, - LWOOBJID_EMPTY, AudioWaveAudio + std::to_string(m_Waves.size() - 3), UNASSIGNED_SYSTEM_ADDRESS); - GameMessages::SendNotifyClientObject(frakjaw->GetObjectID(), StartMusicNotification, 0, 0, - LWOOBJID_EMPTY, AudioWaveAudio + std::to_string(m_Waves.size() - 2), UNASSIGNED_SYSTEM_ADDRESS); + GameMessages::SendNotifyClientObject(frakjaw->GetObjectID(), StopMusicNotification, 0, 0, + LWOOBJID_EMPTY, AudioWaveAudio + std::to_string(m_Waves.size() - 3), UNASSIGNED_SYSTEM_ADDRESS); + GameMessages::SendNotifyClientObject(frakjaw->GetObjectID(), StartMusicNotification, 0, 0, + LWOOBJID_EMPTY, AudioWaveAudio + std::to_string(m_Waves.size() - 2), UNASSIGNED_SYSTEM_ADDRESS); } void NjMonastryBossInstance::SpawnOnNetwork(Entity* self, const LOT& toSpawn, const uint32_t& numberToSpawn, const std::string& spawnerName) { - auto spawners = dZoneManager::Instance()->GetSpawnersByName(spawnerName); - if (spawners.empty() || numberToSpawn <= 0) - return; + auto spawners = dZoneManager::Instance()->GetSpawnersByName(spawnerName); + if (spawners.empty() || numberToSpawn <= 0) + return; - auto* spawner = spawners.front(); + auto* spawner = spawners.front(); - // Spawn the lot N times - spawner->SetSpawnLot(toSpawn); - for (auto i = 0; i < numberToSpawn; i++) - spawner->Spawn({ spawner->m_Info.nodes.at(i % spawner->m_Info.nodes.size()) }, true); + // Spawn the lot N times + spawner->SetSpawnLot(toSpawn); + for (auto i = 0; i < numberToSpawn; i++) + spawner->Spawn({ spawner->m_Info.nodes.at(i % spawner->m_Info.nodes.size()) }, true); } -void NjMonastryBossInstance::WaveOver(Entity *self) { - auto wave = self->GetVar(WaveNumberVariable); - if (wave >= m_Waves.size() - 1) - return; +void NjMonastryBossInstance::WaveOver(Entity* self) { + auto wave = self->GetVar(WaveNumberVariable); + if (wave >= m_Waves.size() - 1) + return; - GameMessages::SendNotifyClientObject(self->GetObjectID(), PlayCinematicNotification, 0, 0, - LWOOBJID_EMPTY, BaseCounterweightSpawn + std::to_string(wave), - UNASSIGNED_SYSTEM_ADDRESS); - ActivityTimerStart(self, SpawnCounterWeightTimer, 1.5f, 1.5f); - RemovePoison(self); + GameMessages::SendNotifyClientObject(self->GetObjectID(), PlayCinematicNotification, 0, 0, + LWOOBJID_EMPTY, BaseCounterweightSpawn + std::to_string(wave), + UNASSIGNED_SYSTEM_ADDRESS); + ActivityTimerStart(self, SpawnCounterWeightTimer, 1.5f, 1.5f); + RemovePoison(self); } -void NjMonastryBossInstance::FightOver(Entity *self) { - GameMessages::SendNotifyClientObject(self->GetObjectID(), u"GroundFrakjawDead", 0, 0, - LWOOBJID_EMPTY, "", UNASSIGNED_SYSTEM_ADDRESS); +void NjMonastryBossInstance::FightOver(Entity* self) { + GameMessages::SendNotifyClientObject(self->GetObjectID(), u"GroundFrakjawDead", 0, 0, + LWOOBJID_EMPTY, "", UNASSIGNED_SYSTEM_ADDRESS); - // Remove all the enemies from the battlefield - for (auto i = 1; i < 5; i++) { - auto spawners = dZoneManager::Instance()->GetSpawnersByName(BaseEnemiesSpawner + std::to_string(i)); - if (!spawners.empty()) { - auto* spawner = spawners.front(); - spawner->Deactivate(); - spawner->Reset(); - } - } + // Remove all the enemies from the battlefield + for (auto i = 1; i < 5; i++) { + auto spawners = dZoneManager::Instance()->GetSpawnersByName(BaseEnemiesSpawner + std::to_string(i)); + if (!spawners.empty()) { + auto* spawner = spawners.front(); + spawner->Deactivate(); + spawner->Reset(); + } + } - RemovePoison(self); - ActivityTimerStart(self, SpawnRailTimer, 1.5f, 1.5f); + RemovePoison(self); + ActivityTimerStart(self, SpawnRailTimer, 1.5f, 1.5f); - // Set the music to play the victory music - GameMessages::SendNotifyClientObject(self->GetObjectID(), StopMusicNotification, 0, 0, - LWOOBJID_EMPTY, AudioWaveAudio + std::to_string(m_Waves.size() - 2), - UNASSIGNED_SYSTEM_ADDRESS); - GameMessages::SendNotifyClientObject(self->GetObjectID(), FlashMusicNotification, 0, 0, - LWOOBJID_EMPTY, "Monastery_Frakjaw_Battle_Win", UNASSIGNED_SYSTEM_ADDRESS); - GameMessages::SendNotifyClientObject(self->GetObjectID(), PlayCinematicNotification, 0, 0, - LWOOBJID_EMPTY, TreasureChestSpawning, UNASSIGNED_SYSTEM_ADDRESS); + // Set the music to play the victory music + GameMessages::SendNotifyClientObject(self->GetObjectID(), StopMusicNotification, 0, 0, + LWOOBJID_EMPTY, AudioWaveAudio + std::to_string(m_Waves.size() - 2), + UNASSIGNED_SYSTEM_ADDRESS); + GameMessages::SendNotifyClientObject(self->GetObjectID(), FlashMusicNotification, 0, 0, + LWOOBJID_EMPTY, "Monastery_Frakjaw_Battle_Win", UNASSIGNED_SYSTEM_ADDRESS); + GameMessages::SendNotifyClientObject(self->GetObjectID(), PlayCinematicNotification, 0, 0, + LWOOBJID_EMPTY, TreasureChestSpawning, UNASSIGNED_SYSTEM_ADDRESS); - auto treasureChests = EntityManager::Instance()->GetEntitiesInGroup(ChestSpawnpointGroup); - for (auto* treasureChest : treasureChests) { - auto info = EntityInfo {}; + auto treasureChests = EntityManager::Instance()->GetEntitiesInGroup(ChestSpawnpointGroup); + for (auto* treasureChest : treasureChests) { + auto info = EntityInfo{}; - info.lot = ChestLOT; - info.pos = treasureChest->GetPosition(); - info.rot = treasureChest->GetRotation(); - info.spawnerID = self->GetObjectID(); - info.settings = { - new LDFData(u"parent_tag", self->GetObjectID()) - }; + info.lot = ChestLOT; + info.pos = treasureChest->GetPosition(); + info.rot = treasureChest->GetRotation(); + info.spawnerID = self->GetObjectID(); + info.settings = { + new LDFData(u"parent_tag", self->GetObjectID()) + }; - // Finally spawn a treasure chest at the correct spawn point - auto* chestObject = EntityManager::Instance()->CreateEntity(info); - EntityManager::Instance()->ConstructEntity(chestObject); - } + // Finally spawn a treasure chest at the correct spawn point + auto* chestObject = EntityManager::Instance()->CreateEntity(info); + EntityManager::Instance()->ConstructEntity(chestObject); + } } diff --git a/dScripts/NjMonastryBossInstance.h b/dScripts/NjMonastryBossInstance.h index 6153d84f..86553c18 100644 --- a/dScripts/NjMonastryBossInstance.h +++ b/dScripts/NjMonastryBossInstance.h @@ -2,156 +2,156 @@ #include "ActivityManager.h" enum FrakjawEnemies { - BoneWolf = 16191, - BlackSmith = 14007, - Marksman = 14008, - Commando = 14009, - MadScientist = 16511 + BoneWolf = 16191, + BlackSmith = 14007, + Marksman = 14008, + Commando = 14009, + MadScientist = 16511 }; enum FrakjawLots : LOT { - ChestLOT = 16486, - LedgedFrakjawLOT = 16289, - LowerFrakjawLOT = 16048, - CounterWeightLOT = 16141 + ChestLOT = 16486, + LedgedFrakjawLOT = 16289, + LowerFrakjawLOT = 16048, + CounterWeightLOT = 16141 }; struct FrakjawWaveEnemy { - LOT lot; - uint32_t largeNumber; - uint32_t smallNumber; + LOT lot; + uint32_t largeNumber; + uint32_t smallNumber; }; class NjMonastryBossInstance : public ActivityManager { public: - void OnStartup(Entity* self) override; - void OnPlayerLoaded(Entity* self, Entity* player) override; - void OnPlayerExit(Entity* self, Entity* player) override; - void OnActivityTimerDone(Entity *self, const std::string &name) override; + void OnStartup(Entity* self) override; + void OnPlayerLoaded(Entity* self, Entity* player) override; + void OnPlayerExit(Entity* self, Entity* player) override; + void OnActivityTimerDone(Entity* self, const std::string& name) override; private: - void StartFight(Entity* self); - void WaveOver(Entity* self); - void FightOver(Entity* self); - void SummonWave(Entity* self, Entity* frakjaw); - void LowerFrakjaw(Entity* self, Entity* frakjaw); - void LowerFrakjawSummon(Entity* self, Entity* frakjaw); - void RemovePoison(Entity* self); - static void SpawnOnNetwork(Entity* self, const LOT& toSpawn, const uint32_t& numberToSpawn, const std::string& spawnerName); - static void TeleportPlayer(Entity* player, uint32_t position); + void StartFight(Entity* self); + void WaveOver(Entity* self); + void FightOver(Entity* self); + void SummonWave(Entity* self, Entity* frakjaw); + void LowerFrakjaw(Entity* self, Entity* frakjaw); + void LowerFrakjawSummon(Entity* self, Entity* frakjaw); + void RemovePoison(Entity* self); + static void SpawnOnNetwork(Entity* self, const LOT& toSpawn, const uint32_t& numberToSpawn, const std::string& spawnerName); + static void TeleportPlayer(Entity* player, uint32_t position); - // Event handlers for anything spawned by the main spawner - void HandleLedgedFrakjawSpawned(Entity* self, Entity* ledgedFrakjaw); - void HandleCounterWeightSpawned(Entity* self, Entity* counterWeight); - void HandleLowerFrakjawSpawned(Entity* self, Entity* lowerFrakjaw); - void HandleWaveEnemySpawned(Entity* self, Entity* waveEnemy); - void HandleWaveEnemyDied(Entity* self, Entity* waveEnemy); - void HandleLowerFrakjawHit(Entity* self, Entity* lowerFrakjaw, Entity* attacker); - void HandleLowerFrakjawDied(Entity* self, Entity* lowerFrakjaw); + // Event handlers for anything spawned by the main spawner + void HandleLedgedFrakjawSpawned(Entity* self, Entity* ledgedFrakjaw); + void HandleCounterWeightSpawned(Entity* self, Entity* counterWeight); + void HandleLowerFrakjawSpawned(Entity* self, Entity* lowerFrakjaw); + void HandleWaveEnemySpawned(Entity* self, Entity* waveEnemy); + void HandleWaveEnemyDied(Entity* self, Entity* waveEnemy); + void HandleLowerFrakjawHit(Entity* self, Entity* lowerFrakjaw, Entity* attacker); + void HandleLowerFrakjawDied(Entity* self, Entity* lowerFrakjaw); - const std::vector> m_Waves = { - // Wave 1 - { - { FrakjawEnemies::Marksman, 2, 1}, - { FrakjawEnemies::BlackSmith, 4, 3}, - { FrakjawEnemies::Commando, 2, 1}, - { FrakjawEnemies::MadScientist, 1, 0}, - }, + const std::vector> m_Waves = { + // Wave 1 + { + { FrakjawEnemies::Marksman, 2, 1}, + { FrakjawEnemies::BlackSmith, 4, 3}, + { FrakjawEnemies::Commando, 2, 1}, + { FrakjawEnemies::MadScientist, 1, 0}, + }, - // Wave 2 - { - { FrakjawEnemies::BoneWolf, 1, 0}, - { FrakjawEnemies::BlackSmith, 2, 2}, - { FrakjawEnemies::Marksman, 2, 1}, - { FrakjawEnemies::MadScientist, 1, 1}, - }, + // Wave 2 + { + { FrakjawEnemies::BoneWolf, 1, 0}, + { FrakjawEnemies::BlackSmith, 2, 2}, + { FrakjawEnemies::Marksman, 2, 1}, + { FrakjawEnemies::MadScientist, 1, 1}, + }, - // Wave 3 - { - { FrakjawEnemies::BoneWolf, 2, 1}, - { FrakjawEnemies::Marksman, 2, 1}, - { FrakjawEnemies::Commando, 2, 2}, - { FrakjawEnemies::MadScientist, 1, 0}, - }, + // Wave 3 + { + { FrakjawEnemies::BoneWolf, 2, 1}, + { FrakjawEnemies::Marksman, 2, 1}, + { FrakjawEnemies::Commando, 2, 2}, + { FrakjawEnemies::MadScientist, 1, 0}, + }, - // Wave 4 - { - { FrakjawEnemies::BlackSmith, 2, 2}, - { FrakjawEnemies::BoneWolf, 1, 1}, - { FrakjawEnemies::Commando, 3, 1}, - { FrakjawEnemies::Marksman, 2, 0}, - }, + // Wave 4 + { + { FrakjawEnemies::BlackSmith, 2, 2}, + { FrakjawEnemies::BoneWolf, 1, 1}, + { FrakjawEnemies::Commando, 3, 1}, + { FrakjawEnemies::Marksman, 2, 0}, + }, - // Wave 5 - { - { FrakjawEnemies::MadScientist, 1, 0}, - { FrakjawEnemies::BoneWolf, 2, 0}, - { FrakjawEnemies::Commando, 3, 0}, - { FrakjawEnemies::Marksman, 2, 0}, - } - }; + // Wave 5 + { + { FrakjawEnemies::MadScientist, 1, 0}, + { FrakjawEnemies::BoneWolf, 2, 0}, + { FrakjawEnemies::Commando, 3, 0}, + { FrakjawEnemies::Marksman, 2, 0}, + } + }; - const int32_t PoisonBuff = 60; + const int32_t PoisonBuff = 60; - // Variables - const std::u16string TotalPlayersLoadedVariable = u"TotalPlayersLoaded"; - const std::u16string LargeTeamVariable = u"LargeTeam"; - const std::u16string FightStartedVariable = u"FightStarted"; - const std::u16string LedgeFrakjawVariable = u"LedgeFrakjaw"; - const std::u16string LowerFrakjawVariable = u"LowerFrakjaw"; - const std::u16string WaveNumberVariable = u"WaveNumber"; - const std::u16string OnLastWaveVarbiale = u"OnLastWave"; - const std::u16string TrashMobsAliveVariable = u"TrashMobsAlive"; - const std::u16string TotalAliveInWaveVariable = u"TotalAliveInWave"; + // Variables + const std::u16string TotalPlayersLoadedVariable = u"TotalPlayersLoaded"; + const std::u16string LargeTeamVariable = u"LargeTeam"; + const std::u16string FightStartedVariable = u"FightStarted"; + const std::u16string LedgeFrakjawVariable = u"LedgeFrakjaw"; + const std::u16string LowerFrakjawVariable = u"LowerFrakjaw"; + const std::u16string WaveNumberVariable = u"WaveNumber"; + const std::u16string OnLastWaveVarbiale = u"OnLastWave"; + const std::u16string TrashMobsAliveVariable = u"TrashMobsAlive"; + const std::u16string TotalAliveInWaveVariable = u"TotalAliveInWave"; - // Timers - const char TimerSplitChar = '+'; - const std::string WaitingForPlayersTimer = "WaitingForPlayers"; - const std::string SpawnWaveTimer = "SpawnWave"; - const std::string SpawnNextWaveTimer = "SpawnNextWave"; - const std::string UnstunTimer = "Unstun+"; - const std::string FrakjawSpawnInTimer = "LowerFrakjawSpawnIn+"; - const std::string WaveOverTimer = "WaveOverTimer"; - const std::string FightOverTimer = "FightOver"; - const std::string LowerFrakjawCamTimer = "StartLowerFrakjawCam"; - const std::string SpawnCounterWeightTimer = "SpawnQB"; - const std::string SpawnRailTimer = "SpawnRailQB"; - const std::string SpawnLowerFrakjawTimer = "SpawnLowerFrakjaw"; + // Timers + const char TimerSplitChar = '+'; + const std::string WaitingForPlayersTimer = "WaitingForPlayers"; + const std::string SpawnWaveTimer = "SpawnWave"; + const std::string SpawnNextWaveTimer = "SpawnNextWave"; + const std::string UnstunTimer = "Unstun+"; + const std::string FrakjawSpawnInTimer = "LowerFrakjawSpawnIn+"; + const std::string WaveOverTimer = "WaveOverTimer"; + const std::string FightOverTimer = "FightOver"; + const std::string LowerFrakjawCamTimer = "StartLowerFrakjawCam"; + const std::string SpawnCounterWeightTimer = "SpawnQB"; + const std::string SpawnRailTimer = "SpawnRailQB"; + const std::string SpawnLowerFrakjawTimer = "SpawnLowerFrakjaw"; - // Groups - const std::string ChestSpawnpointGroup = "ChestSpawnPoint"; + // Groups + const std::string ChestSpawnpointGroup = "ChestSpawnPoint"; - // Spawner network names - const std::string LedgeFrakjawSpawner = "LedgeFrakjaw"; - const std::string LowerFrakjawSpawner = "LowerFrakjaw"; - const std::string BaseEnemiesSpawner = "EnemySpawnPoints_"; - const std::string CounterweightSpawner = "Counterweights"; - const std::string FireRailSpawner = "FireRailActivatorQB"; - const std::string ExtraRocks = "ExtraRocks"; + // Spawner network names + const std::string LedgeFrakjawSpawner = "LedgeFrakjaw"; + const std::string LowerFrakjawSpawner = "LowerFrakjaw"; + const std::string BaseEnemiesSpawner = "EnemySpawnPoints_"; + const std::string CounterweightSpawner = "Counterweights"; + const std::string FireRailSpawner = "FireRailActivatorQB"; + const std::string ExtraRocks = "ExtraRocks"; - // Cinematics - const std::string LedgeFrakSummon = "FrakjawSummoning"; - const std::string BaseCounterweightQB = "CounterweightQB"; - const std::string BaseCounterweightSpawn = "CWQBSpawn"; - const std::string BottomFrakSummon = "BottomFrakjawSummoning"; - const std::string BottomFrakSpawn = "BottomFrakjawSpawning"; - const std::string TreasureChestSpawning = "TreasureChestSpawning"; - const std::string FireRailSpawn = "RailQBSpawn"; + // Cinematics + const std::string LedgeFrakSummon = "FrakjawSummoning"; + const std::string BaseCounterweightQB = "CounterweightQB"; + const std::string BaseCounterweightSpawn = "CWQBSpawn"; + const std::string BottomFrakSummon = "BottomFrakjawSummoning"; + const std::string BottomFrakSpawn = "BottomFrakjawSpawning"; + const std::string TreasureChestSpawning = "TreasureChestSpawning"; + const std::string FireRailSpawn = "RailQBSpawn"; - // Notifications - const std::u16string StopMusicNotification = u"StopMusic"; - const std::u16string StartMusicNotification = u"StartMusic"; - const std::u16string FlashMusicNotification = u"FlashMusic"; - const std::u16string PlayCinematicNotification = u"PlayCinematic"; - const std::u16string EndCinematicNotification = u"EndCinematic"; + // Notifications + const std::u16string StopMusicNotification = u"StopMusic"; + const std::u16string StartMusicNotification = u"StartMusic"; + const std::u16string FlashMusicNotification = u"FlashMusic"; + const std::u16string PlayCinematicNotification = u"PlayCinematic"; + const std::u16string EndCinematicNotification = u"EndCinematic"; - // Animations - const std::u16string SummonAnimation = u"summon"; - const std::u16string TeleportOutAnimation = u"teleport-out"; - const std::u16string TeleportInAnimation = u"teleport-in"; - const std::u16string StunnedAnimation = u"stunned"; + // Animations + const std::u16string SummonAnimation = u"summon"; + const std::u16string TeleportOutAnimation = u"teleport-out"; + const std::u16string TeleportInAnimation = u"teleport-in"; + const std::u16string StunnedAnimation = u"stunned"; - // Audio cues - const std::string AudioWaveAudio = "Monastery_Frakjaw_Battle_"; - const std::string BattleOverAudio = "Monastery_Frakjaw_Battle_Win"; - const std::string CounterSmashAudio = "{d76d7b9d-9dc2-4e52-a315-69b25ef521ca}"; + // Audio cues + const std::string AudioWaveAudio = "Monastery_Frakjaw_Battle_"; + const std::string BattleOverAudio = "Monastery_Frakjaw_Battle_Win"; + const std::string CounterSmashAudio = "{d76d7b9d-9dc2-4e52-a315-69b25ef521ca}"; }; diff --git a/dScripts/NjNPCMissionSpinjitzuServer.cpp b/dScripts/NjNPCMissionSpinjitzuServer.cpp index 74b01617..19f5f42a 100644 --- a/dScripts/NjNPCMissionSpinjitzuServer.cpp +++ b/dScripts/NjNPCMissionSpinjitzuServer.cpp @@ -2,23 +2,23 @@ #include "Character.h" #include "EntityManager.h" -void NjNPCMissionSpinjitzuServer::OnMissionDialogueOK(Entity *self, Entity *target, int missionID, - MissionState missionState) { +void NjNPCMissionSpinjitzuServer::OnMissionDialogueOK(Entity* self, Entity* target, int missionID, + MissionState missionState) { - const auto& element = self->GetVar(ElementVariable); - if (missionID == ElementMissions.at(element) && missionState >= MissionState::MISSION_STATE_READY_TO_COMPLETE) { + const auto& element = self->GetVar(ElementVariable); + if (missionID == ElementMissions.at(element) && missionState >= MissionState::MISSION_STATE_READY_TO_COMPLETE) { - const auto targetID = target->GetObjectID(); + const auto targetID = target->GetObjectID(); - // Wait for an animation to complete and flag that the player has learned spinjitzu - self->AddCallbackTimer(5.0f, [targetID, element]() { - auto* target = EntityManager::Instance()->GetEntity(targetID); - if (target != nullptr) { - auto* character = target->GetCharacter(); - if (character != nullptr) { - character->SetPlayerFlag(ElementFlags.at(element), true); - } - } - }); - } + // Wait for an animation to complete and flag that the player has learned spinjitzu + self->AddCallbackTimer(5.0f, [targetID, element]() { + auto* target = EntityManager::Instance()->GetEntity(targetID); + if (target != nullptr) { + auto* character = target->GetCharacter(); + if (character != nullptr) { + character->SetPlayerFlag(ElementFlags.at(element), true); + } + } + }); + } } diff --git a/dScripts/NjNPCMissionSpinjitzuServer.h b/dScripts/NjNPCMissionSpinjitzuServer.h index 5b346ee7..8f25a86a 100644 --- a/dScripts/NjNPCMissionSpinjitzuServer.h +++ b/dScripts/NjNPCMissionSpinjitzuServer.h @@ -3,22 +3,22 @@ #include static std::map ElementFlags = { - {u"earth", ePlayerFlags::NJ_EARTH_SPINJITZU}, - {u"lightning", ePlayerFlags::NJ_LIGHTNING_SPINJITZU}, - {u"ice", ePlayerFlags::NJ_ICE_SPINJITZU}, - {u"fire", ePlayerFlags::NJ_FIRE_SPINJITZU} + {u"earth", ePlayerFlags::NJ_EARTH_SPINJITZU}, + {u"lightning", ePlayerFlags::NJ_LIGHTNING_SPINJITZU}, + {u"ice", ePlayerFlags::NJ_ICE_SPINJITZU}, + {u"fire", ePlayerFlags::NJ_FIRE_SPINJITZU} }; static std::map ElementMissions = { - {u"earth", 1796}, - {u"lightning", 1952}, - {u"ice", 1959}, - {u"fire", 1962}, + {u"earth", 1796}, + {u"lightning", 1952}, + {u"ice", 1959}, + {u"fire", 1962}, }; class NjNPCMissionSpinjitzuServer : public CppScripts::Script { public: - void OnMissionDialogueOK(Entity *self, Entity *target, int missionID, MissionState missionState) override; + void OnMissionDialogueOK(Entity* self, Entity* target, int missionID, MissionState missionState) override; private: - const std::u16string ElementVariable = u"element"; + const std::u16string ElementVariable = u"element"; }; diff --git a/dScripts/NjNyaMissionitems.cpp b/dScripts/NjNyaMissionitems.cpp index 11ec74bd..4e5304d8 100644 --- a/dScripts/NjNyaMissionitems.cpp +++ b/dScripts/NjNyaMissionitems.cpp @@ -1,8 +1,8 @@ #include "NjNyaMissionitems.h" std::map> NjNyaMissionitems::GetSettings() { - return { - {1809, {{{14472}, true, false}}}, - {1821, {{{14500}, false, true}}} - }; + return { + {1809, {{{14472}, true, false}}}, + {1821, {{{14500}, false, true}}} + }; } diff --git a/dScripts/NjNyaMissionitems.h b/dScripts/NjNyaMissionitems.h index 5e2bbc7b..11b78ebd 100644 --- a/dScripts/NjNyaMissionitems.h +++ b/dScripts/NjNyaMissionitems.h @@ -4,5 +4,5 @@ #include class NjNyaMissionitems : public NPCAddRemoveItem { - std::map> GetSettings() override; + std::map> GetSettings() override; }; diff --git a/dScripts/NjRailActivatorsServer.cpp b/dScripts/NjRailActivatorsServer.cpp index 6c7e6ada..a07de24a 100644 --- a/dScripts/NjRailActivatorsServer.cpp +++ b/dScripts/NjRailActivatorsServer.cpp @@ -2,15 +2,15 @@ #include "RebuildComponent.h" #include "Character.h" -void NjRailActivatorsServer::OnUse(Entity *self, Entity *user) { - const auto flag = self->GetVar(u"RailFlagNum"); - auto* rebuildComponent = self->GetComponent(); +void NjRailActivatorsServer::OnUse(Entity* self, Entity* user) { + const auto flag = self->GetVar(u"RailFlagNum"); + auto* rebuildComponent = self->GetComponent(); - // Only allow use if this is not a quick build or the quick build is built - if (rebuildComponent == nullptr || rebuildComponent->GetState() == REBUILD_COMPLETED) { - auto* character = user->GetCharacter(); - if (character != nullptr) { - character->SetPlayerFlag(flag, true); - } - } + // Only allow use if this is not a quick build or the quick build is built + if (rebuildComponent == nullptr || rebuildComponent->GetState() == REBUILD_COMPLETED) { + auto* character = user->GetCharacter(); + if (character != nullptr) { + character->SetPlayerFlag(flag, true); + } + } } diff --git a/dScripts/NjRailActivatorsServer.h b/dScripts/NjRailActivatorsServer.h index 3e94f119..6f267705 100644 --- a/dScripts/NjRailActivatorsServer.h +++ b/dScripts/NjRailActivatorsServer.h @@ -2,5 +2,5 @@ #include "NjRailPostServer.h" class NjRailActivatorsServer : public NjRailPostServer { - void OnUse(Entity *self, Entity *user) override; + void OnUse(Entity* self, Entity* user) override; }; diff --git a/dScripts/NjRailPostServer.cpp b/dScripts/NjRailPostServer.cpp index 097006c7..23389a98 100644 --- a/dScripts/NjRailPostServer.cpp +++ b/dScripts/NjRailPostServer.cpp @@ -2,50 +2,50 @@ #include "RebuildComponent.h" #include "EntityManager.h" -void NjRailPostServer::OnStartup(Entity *self) { - auto* rebuildComponent = self->GetComponent(); - if (rebuildComponent != nullptr) { - self->SetNetworkVar(NetworkNotActiveVariable, true); - } +void NjRailPostServer::OnStartup(Entity* self) { + auto* rebuildComponent = self->GetComponent(); + if (rebuildComponent != nullptr) { + self->SetNetworkVar(NetworkNotActiveVariable, true); + } } -void NjRailPostServer::OnNotifyObject(Entity *self, Entity *sender, const std::string &name, int32_t param1, - int32_t param2) { - if (name == "PostRebuilt") { - self->SetNetworkVar(NetworkNotActiveVariable, false); - } else if (name == "PostDied") { - self->SetNetworkVar(NetworkNotActiveVariable, true); - } +void NjRailPostServer::OnNotifyObject(Entity* self, Entity* sender, const std::string& name, int32_t param1, + int32_t param2) { + if (name == "PostRebuilt") { + self->SetNetworkVar(NetworkNotActiveVariable, false); + } else if (name == "PostDied") { + self->SetNetworkVar(NetworkNotActiveVariable, true); + } } -void NjRailPostServer::OnRebuildNotifyState(Entity *self, eRebuildState state) { - if (state == REBUILD_COMPLETED) { - auto* relatedRail = GetRelatedRail(self); - if (relatedRail == nullptr) - return; +void NjRailPostServer::OnRebuildNotifyState(Entity* self, eRebuildState state) { + if (state == REBUILD_COMPLETED) { + auto* relatedRail = GetRelatedRail(self); + if (relatedRail == nullptr) + return; - relatedRail->NotifyObject(self, "PostRebuilt"); + relatedRail->NotifyObject(self, "PostRebuilt"); - if (self->GetVar(NotActiveVariable)) - return; + if (self->GetVar(NotActiveVariable)) + return; - self->SetNetworkVar(NetworkNotActiveVariable, false); - } else if (state == REBUILD_RESETTING) { - auto* relatedRail = GetRelatedRail(self); - if (relatedRail == nullptr) - return; + self->SetNetworkVar(NetworkNotActiveVariable, false); + } else if (state == REBUILD_RESETTING) { + auto* relatedRail = GetRelatedRail(self); + if (relatedRail == nullptr) + return; - relatedRail->NotifyObject(self, "PostDied"); - } + relatedRail->NotifyObject(self, "PostDied"); + } } -Entity *NjRailPostServer::GetRelatedRail(Entity* self) { - const auto& railGroup = self->GetVar(RailGroupVariable); - if (!railGroup.empty()) { - for (auto* entity : EntityManager::Instance()->GetEntitiesInGroup(GeneralUtils::UTF16ToWTF8(railGroup))) { - return entity; - } - } +Entity* NjRailPostServer::GetRelatedRail(Entity* self) { + const auto& railGroup = self->GetVar(RailGroupVariable); + if (!railGroup.empty()) { + for (auto* entity : EntityManager::Instance()->GetEntitiesInGroup(GeneralUtils::UTF16ToWTF8(railGroup))) { + return entity; + } + } - return nullptr; + return nullptr; } diff --git a/dScripts/NjRailPostServer.h b/dScripts/NjRailPostServer.h index 65a95733..3486db87 100644 --- a/dScripts/NjRailPostServer.h +++ b/dScripts/NjRailPostServer.h @@ -2,12 +2,12 @@ #include "CppScripts.h" class NjRailPostServer : public CppScripts::Script { - void OnStartup(Entity *self) override; - void OnNotifyObject(Entity *self, Entity *sender, const std::string &name, int32_t param1, int32_t param2) override; - void OnRebuildNotifyState(Entity *self, eRebuildState state) override; + void OnStartup(Entity* self) override; + void OnNotifyObject(Entity* self, Entity* sender, const std::string& name, int32_t param1, int32_t param2) override; + void OnRebuildNotifyState(Entity* self, eRebuildState state) override; private: - Entity* GetRelatedRail(Entity* self); - const std::u16string NetworkNotActiveVariable = u"NetworkNotActive"; - const std::u16string NotActiveVariable = u"NotActive"; - const std::u16string RailGroupVariable = u"RailGroup"; + Entity* GetRelatedRail(Entity* self); + const std::u16string NetworkNotActiveVariable = u"NetworkNotActive"; + const std::u16string NotActiveVariable = u"NotActive"; + const std::u16string RailGroupVariable = u"RailGroup"; }; diff --git a/dScripts/NjRailSwitch.cpp b/dScripts/NjRailSwitch.cpp index 70a52a0e..e53445d9 100644 --- a/dScripts/NjRailSwitch.cpp +++ b/dScripts/NjRailSwitch.cpp @@ -1,12 +1,12 @@ #include "NjRailSwitch.h" #include "GameMessages.h" -void NjRailSwitch::OnUse(Entity *self, Entity *user) { -// const auto path = self->GetVar(u"rail_path"); -// const auto pathStart = self->GetVar(u"rail_path_start"); -// const auto pathGoForward = self->GetVar(u"rail_path_direction"); -// const auto cinematicName = self->GetVar(u"cinematic"); -// -// GameMessages::SendSetRailMovement(self->GetObjectID(), pathGoForward, path, pathStart, user->GetSystemAddress()); -// GameMessages::SendPlayCinematic(self->GetObjectID(), cinematicName, user->GetSystemAddress()); +void NjRailSwitch::OnUse(Entity* self, Entity* user) { + // const auto path = self->GetVar(u"rail_path"); + // const auto pathStart = self->GetVar(u"rail_path_start"); + // const auto pathGoForward = self->GetVar(u"rail_path_direction"); + // const auto cinematicName = self->GetVar(u"cinematic"); + // + // GameMessages::SendSetRailMovement(self->GetObjectID(), pathGoForward, path, pathStart, user->GetSystemAddress()); + // GameMessages::SendPlayCinematic(self->GetObjectID(), cinematicName, user->GetSystemAddress()); } diff --git a/dScripts/NjRailSwitch.h b/dScripts/NjRailSwitch.h index 453b9650..38ce2095 100644 --- a/dScripts/NjRailSwitch.h +++ b/dScripts/NjRailSwitch.h @@ -2,5 +2,5 @@ #include "CppScripts.h" class NjRailSwitch : public CppScripts::Script { - void OnUse(Entity *self, Entity *user) override; + void OnUse(Entity* self, Entity* user) override; }; diff --git a/dScripts/NjScrollChestServer.cpp b/dScripts/NjScrollChestServer.cpp index b72f93cf..4e1350b4 100644 --- a/dScripts/NjScrollChestServer.cpp +++ b/dScripts/NjScrollChestServer.cpp @@ -1,17 +1,17 @@ #include "NjScrollChestServer.h" #include "InventoryComponent.h" -void NjScrollChestServer::OnUse(Entity *self, Entity *user) { - const auto keyLOT = self->GetVar(u"KeyNum"); - const auto rewardItemLOT = self->GetVar(u"openItemID"); +void NjScrollChestServer::OnUse(Entity* self, Entity* user) { + const auto keyLOT = self->GetVar(u"KeyNum"); + const auto rewardItemLOT = self->GetVar(u"openItemID"); - auto* playerInventory = user->GetComponent(); - if (playerInventory != nullptr && playerInventory->GetLotCount(keyLOT) == 1) { + auto* playerInventory = user->GetComponent(); + if (playerInventory != nullptr && playerInventory->GetLotCount(keyLOT) == 1) { - // Check for the key and remove - playerInventory->RemoveItem(keyLOT, 1); + // Check for the key and remove + playerInventory->RemoveItem(keyLOT, 1); - // Reward the player with the item set - playerInventory->AddItem(rewardItemLOT, 1, eLootSourceType::LOOT_SOURCE_NONE); - } + // Reward the player with the item set + playerInventory->AddItem(rewardItemLOT, 1, eLootSourceType::LOOT_SOURCE_NONE); + } } diff --git a/dScripts/NjScrollChestServer.h b/dScripts/NjScrollChestServer.h index c2891ab5..39a64473 100644 --- a/dScripts/NjScrollChestServer.h +++ b/dScripts/NjScrollChestServer.h @@ -2,5 +2,5 @@ #include "CppScripts.h" class NjScrollChestServer : public CppScripts::Script { - void OnUse(Entity *self, Entity *user) override; + void OnUse(Entity* self, Entity* user) override; }; diff --git a/dScripts/NjWuNPC.cpp b/dScripts/NjWuNPC.cpp index 9c950e5c..855e4433 100644 --- a/dScripts/NjWuNPC.cpp +++ b/dScripts/NjWuNPC.cpp @@ -4,60 +4,60 @@ #include "EntityManager.h" #include "GameMessages.h" -void NjWuNPC::OnMissionDialogueOK(Entity *self, Entity *target, int missionID, MissionState missionState) { +void NjWuNPC::OnMissionDialogueOK(Entity* self, Entity* target, int missionID, MissionState missionState) { - // The Dragon statue daily mission - if (missionID == m_MainDragonMissionID) { - auto* character = target->GetCharacter(); - auto* missionComponent = target->GetComponent(); - if (character == nullptr || missionComponent == nullptr) - return; + // The Dragon statue daily mission + if (missionID == m_MainDragonMissionID) { + auto* character = target->GetCharacter(); + auto* missionComponent = target->GetComponent(); + if (character == nullptr || missionComponent == nullptr) + return; - switch(missionState) { - case MissionState::MISSION_STATE_AVAILABLE: - case MissionState::MISSION_STATE_COMPLETE_AVAILABLE: - { - // Reset the sub missions - for (const auto& subMissionID : m_SubDragonMissionIDs) { - missionComponent->RemoveMission(subMissionID); - missionComponent->AcceptMission(subMissionID); - } + switch (missionState) { + case MissionState::MISSION_STATE_AVAILABLE: + case MissionState::MISSION_STATE_COMPLETE_AVAILABLE: + { + // Reset the sub missions + for (const auto& subMissionID : m_SubDragonMissionIDs) { + missionComponent->RemoveMission(subMissionID); + missionComponent->AcceptMission(subMissionID); + } - character->SetPlayerFlag(ePlayerFlags::NJ_WU_SHOW_DAILY_CHEST, false); + character->SetPlayerFlag(ePlayerFlags::NJ_WU_SHOW_DAILY_CHEST, false); - // Hide the chest - for (auto* chest : EntityManager::Instance()->GetEntitiesInGroup(m_DragonChestGroup)) { - GameMessages::SendNotifyClientObject(chest->GetObjectID(), m_ShowChestNotification, 0, -1, - target->GetObjectID(), "", target->GetSystemAddress()); - } + // Hide the chest + for (auto* chest : EntityManager::Instance()->GetEntitiesInGroup(m_DragonChestGroup)) { + GameMessages::SendNotifyClientObject(chest->GetObjectID(), m_ShowChestNotification, 0, -1, + target->GetObjectID(), "", target->GetSystemAddress()); + } - return; - } - case MissionState::MISSION_STATE_READY_TO_COMPLETE: - case MissionState::MISSION_STATE_COMPLETE_READY_TO_COMPLETE: - { - character->SetPlayerFlag(NJ_WU_SHOW_DAILY_CHEST, true); + return; + } + case MissionState::MISSION_STATE_READY_TO_COMPLETE: + case MissionState::MISSION_STATE_COMPLETE_READY_TO_COMPLETE: + { + character->SetPlayerFlag(NJ_WU_SHOW_DAILY_CHEST, true); - // Show the chest - for (auto* chest : EntityManager::Instance()->GetEntitiesInGroup(m_DragonChestGroup)) { - GameMessages::SendNotifyClientObject(chest->GetObjectID(), m_ShowChestNotification, 1, -1, - target->GetObjectID(), "", target->GetSystemAddress()); - } + // Show the chest + for (auto* chest : EntityManager::Instance()->GetEntitiesInGroup(m_DragonChestGroup)) { + GameMessages::SendNotifyClientObject(chest->GetObjectID(), m_ShowChestNotification, 1, -1, + target->GetObjectID(), "", target->GetSystemAddress()); + } - auto playerID = target->GetObjectID(); - self->AddCallbackTimer(5.0f, [this, playerID]() { - auto* player = EntityManager::Instance()->GetEntity(playerID); - if (player == nullptr) - return; + auto playerID = target->GetObjectID(); + self->AddCallbackTimer(5.0f, [this, playerID]() { + auto* player = EntityManager::Instance()->GetEntity(playerID); + if (player == nullptr) + return; - // Stop the dragon effects - for (auto* dragon : EntityManager::Instance()->GetEntitiesInGroup(m_DragonStatueGroup)) { - GameMessages::SendStopFXEffect(dragon, true, "on"); - } - }); - } - default: - return; - } - } + // Stop the dragon effects + for (auto* dragon : EntityManager::Instance()->GetEntitiesInGroup(m_DragonStatueGroup)) { + GameMessages::SendStopFXEffect(dragon, true, "on"); + } + }); + } + default: + return; + } + } } diff --git a/dScripts/NjWuNPC.h b/dScripts/NjWuNPC.h index 8ad6dbf3..d0cd750b 100644 --- a/dScripts/NjWuNPC.h +++ b/dScripts/NjWuNPC.h @@ -2,12 +2,12 @@ #include "AmTemplateSkillVolume.h" class NjWuNPC : public AmTemplateSkillVolume { - void OnMissionDialogueOK(Entity *self, Entity *target, int missionID, MissionState missionState) override; - const uint32_t m_MainDragonMissionID = 2040; - const std::vector m_SubDragonMissionIDs = {2064, 2065, 2066, 2067}; + void OnMissionDialogueOK(Entity* self, Entity* target, int missionID, MissionState missionState) override; + const uint32_t m_MainDragonMissionID = 2040; + const std::vector m_SubDragonMissionIDs = { 2064, 2065, 2066, 2067 }; - // Groups and variables - const std::string m_DragonChestGroup = "DragonEmblemChest"; - const std::string m_DragonStatueGroup = "Minidragons"; - const std::u16string m_ShowChestNotification = u"showChest"; + // Groups and variables + const std::string m_DragonChestGroup = "DragonEmblemChest"; + const std::string m_DragonStatueGroup = "Minidragons"; + const std::u16string m_ShowChestNotification = u"showChest"; }; diff --git a/dScripts/NjhubLavaPlayerDeathTrigger.cpp b/dScripts/NjhubLavaPlayerDeathTrigger.cpp index af47f99b..c065f84a 100644 --- a/dScripts/NjhubLavaPlayerDeathTrigger.cpp +++ b/dScripts/NjhubLavaPlayerDeathTrigger.cpp @@ -1,10 +1,9 @@ #include "NjhubLavaPlayerDeathTrigger.h" #include "Entity.h" -void NjhubLavaPlayerDeathTrigger::OnCollisionPhantom(Entity *self, Entity *target) -{ - if (!target->IsPlayer()) - return; +void NjhubLavaPlayerDeathTrigger::OnCollisionPhantom(Entity* self, Entity* target) { + if (!target->IsPlayer()) + return; - target->Smash(self->GetObjectID(), VIOLENT, u"drown"); + target->Smash(self->GetObjectID(), VIOLENT, u"drown"); } diff --git a/dScripts/NjhubLavaPlayerDeathTrigger.h b/dScripts/NjhubLavaPlayerDeathTrigger.h index 48ff85d0..2cf0883f 100644 --- a/dScripts/NjhubLavaPlayerDeathTrigger.h +++ b/dScripts/NjhubLavaPlayerDeathTrigger.h @@ -2,5 +2,5 @@ #include "CppScripts.h" class NjhubLavaPlayerDeathTrigger : public CppScripts::Script { - void OnCollisionPhantom(Entity *self, Entity *target) override; + void OnCollisionPhantom(Entity* self, Entity* target) override; }; diff --git a/dScripts/NpcAgCourseStarter.cpp b/dScripts/NpcAgCourseStarter.cpp index 188186fb..503d966a 100644 --- a/dScripts/NpcAgCourseStarter.cpp +++ b/dScripts/NpcAgCourseStarter.cpp @@ -19,8 +19,7 @@ void NpcAgCourseStarter::OnUse(Entity* self, Entity* user) { if (scriptedActivityComponent->GetActivityPlayerData(user->GetObjectID()) != nullptr) { GameMessages::SendNotifyClientObject(self->GetObjectID(), u"exit", 0, 0, LWOOBJID_EMPTY, "", user->GetSystemAddress()); - } - else { + } else { GameMessages::SendNotifyClientObject(self->GetObjectID(), u"start", 0, 0, LWOOBJID_EMPTY, "", user->GetSystemAddress()); } } @@ -40,8 +39,7 @@ void NpcAgCourseStarter::OnMessageBoxResponse(Entity* self, Entity* sender, int3 scriptedActivityComponent->RemoveActivityPlayerData(sender->GetObjectID()); EntityManager::Instance()->SerializeEntity(self); - } - else if (identifier == u"player_dialog_start_course" && button == 1) { + } else if (identifier == u"player_dialog_start_course" && button == 1) { GameMessages::SendNotifyClientObject(self->GetObjectID(), u"start_timer", 0, 0, LWOOBJID_EMPTY, "", sender->GetSystemAddress()); GameMessages::SendActivityStart(self->GetObjectID(), sender->GetSystemAddress()); @@ -55,14 +53,12 @@ void NpcAgCourseStarter::OnMessageBoxResponse(Entity* self, Entity* sender, int3 data->values[1] = *(float*)&startTime; EntityManager::Instance()->SerializeEntity(self); - } - else if (identifier == u"FootRaceCancel") { + } else if (identifier == u"FootRaceCancel") { GameMessages::SendNotifyClientObject(self->GetObjectID(), u"stop_timer", 0, 0, LWOOBJID_EMPTY, "", sender->GetSystemAddress()); if (scriptedActivityComponent->GetActivityPlayerData(sender->GetObjectID()) != nullptr) { GameMessages::SendNotifyClientObject(self->GetObjectID(), u"exit", 0, 0, LWOOBJID_EMPTY, "", sender->GetSystemAddress()); - } - else { + } else { GameMessages::SendNotifyClientObject(self->GetObjectID(), u"start", 0, 0, LWOOBJID_EMPTY, "", sender->GetSystemAddress()); } @@ -70,43 +66,43 @@ void NpcAgCourseStarter::OnMessageBoxResponse(Entity* self, Entity* sender, int3 } } -void NpcAgCourseStarter::OnFireEventServerSide(Entity *self, Entity *sender, std::string args, int32_t param1, int32_t param2, - int32_t param3) { +void NpcAgCourseStarter::OnFireEventServerSide(Entity* self, Entity* sender, std::string args, int32_t param1, int32_t param2, + int32_t param3) { auto* scriptedActivityComponent = self->GetComponent(); if (scriptedActivityComponent == nullptr) return; auto* data = scriptedActivityComponent->GetActivityPlayerData(sender->GetObjectID()); - if (data == nullptr) - return; + if (data == nullptr) + return; if (args == "course_cancel") { GameMessages::SendNotifyClientObject(self->GetObjectID(), u"cancel_timer", 0, 0, - LWOOBJID_EMPTY, "", sender->GetSystemAddress()); - scriptedActivityComponent->RemoveActivityPlayerData(sender->GetObjectID()); + LWOOBJID_EMPTY, "", sender->GetSystemAddress()); + scriptedActivityComponent->RemoveActivityPlayerData(sender->GetObjectID()); } else if (args == "course_finish") { - time_t endTime = std::time(0); - time_t finish = (endTime - *(time_t *) &data->values[1]); + time_t endTime = std::time(0); + time_t finish = (endTime - *(time_t*)&data->values[1]); - data->values[2] = *(float *) &finish; + data->values[2] = *(float*)&finish; - auto *missionComponent = sender->GetComponent(); - if (missionComponent != nullptr) { - missionComponent->ForceProgressTaskType(1884, 1, 1, false); - missionComponent->Progress(MissionTaskType::MISSION_TASK_TYPE_MINIGAME, -finish, self->GetObjectID(), - "performact_time"); - } + auto* missionComponent = sender->GetComponent(); + if (missionComponent != nullptr) { + missionComponent->ForceProgressTaskType(1884, 1, 1, false); + missionComponent->Progress(MissionTaskType::MISSION_TASK_TYPE_MINIGAME, -finish, self->GetObjectID(), + "performact_time"); + } - EntityManager::Instance()->SerializeEntity(self); - LeaderboardManager::SaveScore(sender->GetObjectID(), scriptedActivityComponent->GetActivityID(), - 0, (uint32_t) finish); + EntityManager::Instance()->SerializeEntity(self); + LeaderboardManager::SaveScore(sender->GetObjectID(), scriptedActivityComponent->GetActivityID(), + 0, (uint32_t)finish); - GameMessages::SendNotifyClientObject(self->GetObjectID(), u"ToggleLeaderBoard", - scriptedActivityComponent->GetActivityID(), 0, sender->GetObjectID(), - "", sender->GetSystemAddress()); - GameMessages::SendNotifyClientObject(self->GetObjectID(), u"stop_timer", 1, finish, LWOOBJID_EMPTY, "", - sender->GetSystemAddress()); + GameMessages::SendNotifyClientObject(self->GetObjectID(), u"ToggleLeaderBoard", + scriptedActivityComponent->GetActivityID(), 0, sender->GetObjectID(), + "", sender->GetSystemAddress()); + GameMessages::SendNotifyClientObject(self->GetObjectID(), u"stop_timer", 1, finish, LWOOBJID_EMPTY, "", + sender->GetSystemAddress()); - scriptedActivityComponent->RemoveActivityPlayerData(sender->GetObjectID()); + scriptedActivityComponent->RemoveActivityPlayerData(sender->GetObjectID()); } } diff --git a/dScripts/NpcAgCourseStarter.h b/dScripts/NpcAgCourseStarter.h index bc885a40..eda1fa93 100644 --- a/dScripts/NpcAgCourseStarter.h +++ b/dScripts/NpcAgCourseStarter.h @@ -8,6 +8,6 @@ class NpcAgCourseStarter : public CppScripts::Script { void OnMessageBoxResponse(Entity* self, Entity* sender, int32_t button, const std::u16string& identifier, const std::u16string& userData) override; - void OnFireEventServerSide(Entity *self, Entity *sender, std::string args, int32_t param1, int32_t param2, - int32_t param3) override; -}; \ No newline at end of file + void OnFireEventServerSide(Entity* self, Entity* sender, std::string args, int32_t param1, int32_t param2, + int32_t param3) override; +}; diff --git a/dScripts/NpcCowboyServer.cpp b/dScripts/NpcCowboyServer.cpp index f4986045..c4940e4d 100644 --- a/dScripts/NpcCowboyServer.cpp +++ b/dScripts/NpcCowboyServer.cpp @@ -2,32 +2,25 @@ #include "MissionState.h" #include "InventoryComponent.h" -void NpcCowboyServer::OnMissionDialogueOK(Entity* self, Entity* target, int missionID, MissionState missionState) -{ - if (missionID != 1880) - { - return; - } +void NpcCowboyServer::OnMissionDialogueOK(Entity* self, Entity* target, int missionID, MissionState missionState) { + if (missionID != 1880) { + return; + } - auto* inventoryComponent = target->GetComponent(); + auto* inventoryComponent = target->GetComponent(); - if (inventoryComponent == nullptr) - { - return; - } + if (inventoryComponent == nullptr) { + return; + } - if (missionState == MissionState::MISSION_STATE_COMPLETE_ACTIVE|| - missionState == MissionState::MISSION_STATE_ACTIVE || - missionState == MissionState::MISSION_STATE_AVAILABLE || - missionState == MissionState::MISSION_STATE_COMPLETE_AVAILABLE) - { - if (inventoryComponent->GetLotCount(14378) == 0) - { - inventoryComponent->AddItem(14378, 1, eLootSourceType::LOOT_SOURCE_NONE); - } - } - else if (missionState == MissionState::MISSION_STATE_READY_TO_COMPLETE || missionState == MissionState::MISSION_STATE_COMPLETE_READY_TO_COMPLETE) - { - inventoryComponent->RemoveItem(14378, 1); - } + if (missionState == MissionState::MISSION_STATE_COMPLETE_ACTIVE || + missionState == MissionState::MISSION_STATE_ACTIVE || + missionState == MissionState::MISSION_STATE_AVAILABLE || + missionState == MissionState::MISSION_STATE_COMPLETE_AVAILABLE) { + if (inventoryComponent->GetLotCount(14378) == 0) { + inventoryComponent->AddItem(14378, 1, eLootSourceType::LOOT_SOURCE_NONE); + } + } else if (missionState == MissionState::MISSION_STATE_READY_TO_COMPLETE || missionState == MissionState::MISSION_STATE_COMPLETE_READY_TO_COMPLETE) { + inventoryComponent->RemoveItem(14378, 1); + } } diff --git a/dScripts/NpcNjAssistantServer.cpp b/dScripts/NpcNjAssistantServer.cpp index b9743756..a53d8ba3 100644 --- a/dScripts/NpcNjAssistantServer.cpp +++ b/dScripts/NpcNjAssistantServer.cpp @@ -9,9 +9,9 @@ void NpcNjAssistantServer::OnMissionDialogueOK(Entity* self, Entity* target, int if (missionState == MissionState::MISSION_STATE_COMPLETE || missionState == MissionState::MISSION_STATE_READY_TO_COMPLETE) { GameMessages::SendNotifyClientObject(self->GetObjectID(), u"switch", 0, 0, LWOOBJID_EMPTY, "", target->GetSystemAddress()); - + auto* inv = static_cast(target->GetComponent(COMPONENT_TYPE_INVENTORY)); - + // If we are ready to complete our missions, we take the kit from you: if (inv && missionState == MissionState::MISSION_STATE_READY_TO_COMPLETE) { auto* id = inv->FindItemByLot(14397); //the kit's lot @@ -20,8 +20,7 @@ void NpcNjAssistantServer::OnMissionDialogueOK(Entity* self, Entity* target, int inv->RemoveItem(id->GetLot(), id->GetCount()); } } - } - else if (missionState == MissionState::MISSION_STATE_AVAILABLE) { + } else if (missionState == MissionState::MISSION_STATE_AVAILABLE) { auto* missionComponent = static_cast(target->GetComponent(COMPONENT_TYPE_MISSION)); missionComponent->CompleteMission(mailAchievement, true); } diff --git a/dScripts/NpcNjAssistantServer.h b/dScripts/NpcNjAssistantServer.h index c8fac54c..7ba847d0 100644 --- a/dScripts/NpcNjAssistantServer.h +++ b/dScripts/NpcNjAssistantServer.h @@ -7,4 +7,4 @@ class NpcNjAssistantServer : public CppScripts::Script { private: int mailMission = 1728; //mission to get the item out of your mailbox int mailAchievement = 1729; // fun fact: spelled "Achivement" in the actual script -}; \ No newline at end of file +}; diff --git a/dScripts/NpcNpSpacemanBob.cpp b/dScripts/NpcNpSpacemanBob.cpp index 91fe0f95..5157e488 100644 --- a/dScripts/NpcNpSpacemanBob.cpp +++ b/dScripts/NpcNpSpacemanBob.cpp @@ -2,14 +2,12 @@ #include "DestroyableComponent.h" #include "MissionComponent.h" -void NpcNpSpacemanBob::OnMissionDialogueOK(Entity* self, Entity* target, int missionID, MissionState missionState) -{ - if (missionState == MissionState::MISSION_STATE_READY_TO_COMPLETE && missionID == 173) - { +void NpcNpSpacemanBob::OnMissionDialogueOK(Entity* self, Entity* target, int missionID, MissionState missionState) { + if (missionState == MissionState::MISSION_STATE_READY_TO_COMPLETE && missionID == 173) { DestroyableComponent* destroyable = static_cast(target->GetComponent(COMPONENT_TYPE_DESTROYABLE)); destroyable->SetImagination(6); MissionComponent* mission = static_cast(target->GetComponent(COMPONENT_TYPE_MISSION)); - + mission->CompleteMission(664); } } diff --git a/dScripts/NpcPirateServer.cpp b/dScripts/NpcPirateServer.cpp index 04c62b47..47571fa6 100644 --- a/dScripts/NpcPirateServer.cpp +++ b/dScripts/NpcPirateServer.cpp @@ -1,17 +1,17 @@ #include "NpcPirateServer.h" #include "InventoryComponent.h" -void NpcPirateServer::OnMissionDialogueOK(Entity *self, Entity *target, int missionID, MissionState missionState) { - auto* inventory = target->GetComponent(); - if (inventory != nullptr && missionID == 1881) { - auto* luckyShovel = inventory->FindItemByLot(14591); +void NpcPirateServer::OnMissionDialogueOK(Entity* self, Entity* target, int missionID, MissionState missionState) { + auto* inventory = target->GetComponent(); + if (inventory != nullptr && missionID == 1881) { + auto* luckyShovel = inventory->FindItemByLot(14591); - // Add or remove the lucky shovel based on whether the mission was completed or started - if ((missionState == MissionState::MISSION_STATE_AVAILABLE || missionState == MissionState::MISSION_STATE_COMPLETE_AVAILABLE) - && luckyShovel == nullptr) { - inventory->AddItem(14591, 1, eLootSourceType::LOOT_SOURCE_NONE); - } else if (missionState == MissionState::MISSION_STATE_READY_TO_COMPLETE || missionState == MissionState::MISSION_STATE_COMPLETE_READY_TO_COMPLETE) { - inventory->RemoveItem(14591, 1); - } - } + // Add or remove the lucky shovel based on whether the mission was completed or started + if ((missionState == MissionState::MISSION_STATE_AVAILABLE || missionState == MissionState::MISSION_STATE_COMPLETE_AVAILABLE) + && luckyShovel == nullptr) { + inventory->AddItem(14591, 1, eLootSourceType::LOOT_SOURCE_NONE); + } else if (missionState == MissionState::MISSION_STATE_READY_TO_COMPLETE || missionState == MissionState::MISSION_STATE_COMPLETE_READY_TO_COMPLETE) { + inventory->RemoveItem(14591, 1); + } + } } diff --git a/dScripts/NpcPirateServer.h b/dScripts/NpcPirateServer.h index 795356d6..dcb399c5 100644 --- a/dScripts/NpcPirateServer.h +++ b/dScripts/NpcPirateServer.h @@ -2,5 +2,5 @@ #include "CppScripts.h" class NpcPirateServer : public CppScripts::Script { - void OnMissionDialogueOK(Entity *self, Entity *target, int missionID, MissionState missionState) override; + void OnMissionDialogueOK(Entity* self, Entity* target, int missionID, MissionState missionState) override; }; diff --git a/dScripts/NpcWispServer.cpp b/dScripts/NpcWispServer.cpp index 0f573d65..cd4a4d9c 100644 --- a/dScripts/NpcWispServer.cpp +++ b/dScripts/NpcWispServer.cpp @@ -6,38 +6,38 @@ void NpcWispServer::OnMissionDialogueOK(Entity* self, Entity* target, int missionID, MissionState missionState) { if (missionID != 1849 && missionID != 1883) - return; + return; auto* inventory = target->GetComponent(); if (inventory == nullptr) - return; + return; LOT maelstromVacuumLot = 14592; auto* maelstromVacuum = inventory->FindItemByLot(maelstromVacuumLot); // For the daily we add the maelstrom vacuum if the player doesn't have it yet if (missionID == 1883 && (missionState == MissionState::MISSION_STATE_AVAILABLE || missionState == MissionState::MISSION_STATE_COMPLETE_AVAILABLE) - && maelstromVacuum == nullptr) { - inventory->AddItem(maelstromVacuumLot, 1, eLootSourceType::LOOT_SOURCE_NONE); + && maelstromVacuum == nullptr) { + inventory->AddItem(maelstromVacuumLot, 1, eLootSourceType::LOOT_SOURCE_NONE); } else if (missionState == MissionState::MISSION_STATE_READY_TO_COMPLETE || missionState == MissionState::MISSION_STATE_COMPLETE_READY_TO_COMPLETE) { - inventory->RemoveItem(maelstromVacuumLot, 1); + inventory->RemoveItem(maelstromVacuumLot, 1); } // Next up hide or show the samples based on the mission state - auto visible = 1; - if (missionState == MissionState::MISSION_STATE_READY_TO_COMPLETE || missionState == MissionState::MISSION_STATE_COMPLETE_READY_TO_COMPLETE) { - visible = 0; - } + auto visible = 1; + if (missionState == MissionState::MISSION_STATE_READY_TO_COMPLETE || missionState == MissionState::MISSION_STATE_COMPLETE_READY_TO_COMPLETE) { + visible = 0; + } - auto groups = missionID == 1849 - ? std::vector { "MaelstromSamples" } - : std::vector { "MaelstromSamples", "MaelstromSamples2ndary1", "MaelstromSamples2ndary2"}; + auto groups = missionID == 1849 + ? std::vector { "MaelstromSamples" } + : std::vector{ "MaelstromSamples", "MaelstromSamples2ndary1", "MaelstromSamples2ndary2" }; - for (const auto& group : groups) { - auto samples = EntityManager::Instance()->GetEntitiesInGroup(group); - for (auto* sample : samples) { - GameMessages::SendNotifyClientObject(sample->GetObjectID(), u"SetVisibility", visible, 0, - target->GetObjectID(), "", target->GetSystemAddress()); - } - } + for (const auto& group : groups) { + auto samples = EntityManager::Instance()->GetEntitiesInGroup(group); + for (auto* sample : samples) { + GameMessages::SendNotifyClientObject(sample->GetObjectID(), u"SetVisibility", visible, 0, + target->GetObjectID(), "", target->GetSystemAddress()); + } + } } diff --git a/dScripts/NpcWispServer.h b/dScripts/NpcWispServer.h index 133a9d8f..86c9c33d 100644 --- a/dScripts/NpcWispServer.h +++ b/dScripts/NpcWispServer.h @@ -3,4 +3,4 @@ class NpcWispServer : public CppScripts::Script { void OnMissionDialogueOK(Entity* self, Entity* target, int missionID, MissionState missionState); -}; \ No newline at end of file +}; diff --git a/dScripts/NsConcertChoiceBuild.cpp b/dScripts/NsConcertChoiceBuild.cpp index 8a93544c..af6389cd 100644 --- a/dScripts/NsConcertChoiceBuild.cpp +++ b/dScripts/NsConcertChoiceBuild.cpp @@ -1,4 +1,4 @@ #include "NsConcertChoiceBuild.h" -void NsConcertChoiceBuild::OnStartup(Entity *self) { +void NsConcertChoiceBuild::OnStartup(Entity* self) { } diff --git a/dScripts/NsConcertChoiceBuild.h b/dScripts/NsConcertChoiceBuild.h index 310a0677..74fdc9dc 100644 --- a/dScripts/NsConcertChoiceBuild.h +++ b/dScripts/NsConcertChoiceBuild.h @@ -3,5 +3,5 @@ class NsConcertChoiceBuild : public CppScripts::Script { public: - void OnStartup(Entity* self) override; -}; \ No newline at end of file + void OnStartup(Entity* self) override; +}; diff --git a/dScripts/NsConcertChoiceBuildManager.cpp b/dScripts/NsConcertChoiceBuildManager.cpp index 8875beed..33436525 100644 --- a/dScripts/NsConcertChoiceBuildManager.cpp +++ b/dScripts/NsConcertChoiceBuildManager.cpp @@ -1,64 +1,64 @@ #include "NsConcertChoiceBuildManager.h" #include "EntityManager.h" -const std::vector NsConcertChoiceBuildManager::crates { - { "laser", 11203, 5.0, "Concert_Laser_QB_" }, - { "rocket", 11204, 3.0, "Concert_Rocket_QB_" }, - { "speaker", 11205, 5.0, "Concert_Speaker_QB_" }, - { "spotlight", 11206, 5.0, "Concert_Spotlight_QB_" } +const std::vector NsConcertChoiceBuildManager::crates{ + { "laser", 11203, 5.0, "Concert_Laser_QB_" }, + { "rocket", 11204, 3.0, "Concert_Rocket_QB_" }, + { "speaker", 11205, 5.0, "Concert_Speaker_QB_" }, + { "spotlight", 11206, 5.0, "Concert_Spotlight_QB_" } }; -void NsConcertChoiceBuildManager::OnStartup(Entity *self) { - NsConcertChoiceBuildManager::SpawnCrate(self); +void NsConcertChoiceBuildManager::OnStartup(Entity* self) { + NsConcertChoiceBuildManager::SpawnCrate(self); } -void NsConcertChoiceBuildManager::SpawnCrate(Entity *self) { - const auto spawnNumber = self->GetVar(u"spawnNumber") % crates.size(); - const auto crate = crates[spawnNumber]; +void NsConcertChoiceBuildManager::SpawnCrate(Entity* self) { + const auto spawnNumber = self->GetVar(u"spawnNumber") % crates.size(); + const auto crate = crates[spawnNumber]; - const auto groups = self->GetGroups(); - if (groups.empty()) - return; + const auto groups = self->GetGroups(); + if (groups.empty()) + return; - // Groups are of the form CB_1, CB_2, etc. - auto group = groups.at(0); - const auto splitGroup = GeneralUtils::SplitString(group, '_'); - if (splitGroup.size() < 2) - return; - const auto groupNumber = std::stoi(splitGroup.at(1)); + // Groups are of the form CB_1, CB_2, etc. + auto group = groups.at(0); + const auto splitGroup = GeneralUtils::SplitString(group, '_'); + if (splitGroup.size() < 2) + return; + const auto groupNumber = std::stoi(splitGroup.at(1)); - EntityInfo info {}; - info.lot = crate.lot; - info.pos = self->GetPosition(); - info.rot = self->GetRotation(); - info.spawnerID = self->GetObjectID(); - info.settings = { - new LDFData(u"startsQBActivator", true), - new LDFData(u"grpNameQBShowBricks", crate.group + std::to_string(groupNumber)), - new LDFData(u"groupID", GeneralUtils::ASCIIToUTF16("Crate_" + group)), - new LDFData(u"crateTime", crate.time), - }; + EntityInfo info{}; + info.lot = crate.lot; + info.pos = self->GetPosition(); + info.rot = self->GetRotation(); + info.spawnerID = self->GetObjectID(); + info.settings = { + new LDFData(u"startsQBActivator", true), + new LDFData(u"grpNameQBShowBricks", crate.group + std::to_string(groupNumber)), + new LDFData(u"groupID", GeneralUtils::ASCIIToUTF16("Crate_" + group)), + new LDFData(u"crateTime", crate.time), + }; - auto* spawnedCrate = EntityManager::Instance()->CreateEntity(info); - EntityManager::Instance()->ConstructEntity(spawnedCrate); + auto* spawnedCrate = EntityManager::Instance()->CreateEntity(info); + EntityManager::Instance()->ConstructEntity(spawnedCrate); - spawnedCrate->AddDieCallback([self]() { - self->CancelAllTimers(); // Don't switch if the crate was smashed - self->SetVar(u"currentCrate", LWOOBJID_EMPTY); - }); + spawnedCrate->AddDieCallback([self]() { + self->CancelAllTimers(); // Don't switch if the crate was smashed + self->SetVar(u"currentCrate", LWOOBJID_EMPTY); + }); - self->SetVar(u"spawnNumber", spawnNumber + 1); - self->SetVar(u"currentTimer", crate.time); - self->SetVar(u"currentCrate", spawnedCrate->GetObjectID()); + self->SetVar(u"spawnNumber", spawnNumber + 1); + self->SetVar(u"currentTimer", crate.time); + self->SetVar(u"currentCrate", spawnedCrate->GetObjectID()); - // Timer that rotates the crates - self->AddCallbackTimer(crate.time, [self]() { - auto crateID = self->GetVar(u"currentCrate"); - if (crateID != LWOOBJID_EMPTY) { - EntityManager::Instance()->DestroyEntity(crateID); - self->SetVar(u"currentCrate", LWOOBJID_EMPTY); - } + // Timer that rotates the crates + self->AddCallbackTimer(crate.time, [self]() { + auto crateID = self->GetVar(u"currentCrate"); + if (crateID != LWOOBJID_EMPTY) { + EntityManager::Instance()->DestroyEntity(crateID); + self->SetVar(u"currentCrate", LWOOBJID_EMPTY); + } - SpawnCrate(self); - }); + SpawnCrate(self); + }); } diff --git a/dScripts/NsConcertChoiceBuildManager.h b/dScripts/NsConcertChoiceBuildManager.h index 25c7690b..4e9ac4ba 100644 --- a/dScripts/NsConcertChoiceBuildManager.h +++ b/dScripts/NsConcertChoiceBuildManager.h @@ -2,16 +2,16 @@ #include "CppScripts.h" struct Crate { - std::string name; - LOT lot; - float time; - std::string group; + std::string name; + LOT lot; + float time; + std::string group; }; class NsConcertChoiceBuildManager : public CppScripts::Script { public: - void OnStartup(Entity *self) override; - static void SpawnCrate(Entity* self); + void OnStartup(Entity* self) override; + static void SpawnCrate(Entity* self); private: - static const std::vector crates; + static const std::vector crates; }; diff --git a/dScripts/NsConcertInstrument.cpp b/dScripts/NsConcertInstrument.cpp index a449a6a4..508b7b5b 100644 --- a/dScripts/NsConcertInstrument.cpp +++ b/dScripts/NsConcertInstrument.cpp @@ -9,350 +9,350 @@ // Constants are at the bottom -void NsConcertInstrument::OnStartup(Entity *self) { - self->SetVar(u"beingPlayed", false); - self->SetVar(u"activePlayer", LWOOBJID_EMPTY); - self->SetVar(u"oldItemLeft", LWOOBJID_EMPTY); - self->SetVar(u"oldItemRight", LWOOBJID_EMPTY); +void NsConcertInstrument::OnStartup(Entity* self) { + self->SetVar(u"beingPlayed", false); + self->SetVar(u"activePlayer", LWOOBJID_EMPTY); + self->SetVar(u"oldItemLeft", LWOOBJID_EMPTY); + self->SetVar(u"oldItemRight", LWOOBJID_EMPTY); } -void NsConcertInstrument::OnRebuildNotifyState(Entity *self, eRebuildState state) { - if (state == REBUILD_RESETTING || state == REBUILD_OPEN) { - self->SetVar(u"activePlayer", LWOOBJID_EMPTY); - } +void NsConcertInstrument::OnRebuildNotifyState(Entity* self, eRebuildState state) { + if (state == REBUILD_RESETTING || state == REBUILD_OPEN) { + self->SetVar(u"activePlayer", LWOOBJID_EMPTY); + } } -void NsConcertInstrument::OnRebuildComplete(Entity *self, Entity *target) { - if (!target->GetIsDead()) { - self->SetVar(u"activePlayer", target->GetObjectID()); +void NsConcertInstrument::OnRebuildComplete(Entity* self, Entity* target) { + if (!target->GetIsDead()) { + self->SetVar(u"activePlayer", target->GetObjectID()); - self->AddCallbackTimer(0.2f, [self, target]() { - RepositionPlayer(self, target); - if (hideInstrumentOnPlay.at(GetInstrumentLot(self))) - self->SetNetworkVar(u"Hide", true); - }); + self->AddCallbackTimer(0.2f, [self, target]() { + RepositionPlayer(self, target); + if (hideInstrumentOnPlay.at(GetInstrumentLot(self))) + self->SetNetworkVar(u"Hide", true); + }); - self->AddCallbackTimer(0.1f, [self, target]() { - StartPlayingInstrument(self, target); - }); - } + self->AddCallbackTimer(0.1f, [self, target]() { + StartPlayingInstrument(self, target); + }); + } } -void NsConcertInstrument::OnFireEventServerSide(Entity *self, Entity *sender, std::string args, int32_t param1, - int32_t param2, int32_t param3) { - if (args == "stopPlaying") { - const auto activePlayerID = self->GetVar(u"activePlayer"); - if (activePlayerID == LWOOBJID_EMPTY) - return; +void NsConcertInstrument::OnFireEventServerSide(Entity* self, Entity* sender, std::string args, int32_t param1, + int32_t param2, int32_t param3) { + if (args == "stopPlaying") { + const auto activePlayerID = self->GetVar(u"activePlayer"); + if (activePlayerID == LWOOBJID_EMPTY) + return; - const auto activePlayer = EntityManager::Instance()->GetEntity(activePlayerID); - if (activePlayer == nullptr) - return; + const auto activePlayer = EntityManager::Instance()->GetEntity(activePlayerID); + if (activePlayer == nullptr) + return; - StopPlayingInstrument(self, activePlayer); - } + StopPlayingInstrument(self, activePlayer); + } } -void NsConcertInstrument::OnTimerDone(Entity *self, std::string name) { - const auto activePlayerID = self->GetVar(u"activePlayer"); - if (activePlayerID == LWOOBJID_EMPTY) - return; +void NsConcertInstrument::OnTimerDone(Entity* self, std::string name) { + const auto activePlayerID = self->GetVar(u"activePlayer"); + if (activePlayerID == LWOOBJID_EMPTY) + return; - // If for some reason the player becomes null (for example an unexpected leave), we need to clean up - const auto activePlayer = EntityManager::Instance()->GetEntity(activePlayerID); - if (activePlayer == nullptr && name != "cleanupAfterStop") { - StopPlayingInstrument(self, nullptr); - return; - } + // If for some reason the player becomes null (for example an unexpected leave), we need to clean up + const auto activePlayer = EntityManager::Instance()->GetEntity(activePlayerID); + if (activePlayer == nullptr && name != "cleanupAfterStop") { + StopPlayingInstrument(self, nullptr); + return; + } - if (activePlayer != nullptr && name == "checkPlayer" && self->GetVar(u"beingPlayed")) { - GameMessages::SendNotifyClientObject(self->GetObjectID(), u"checkMovement", 0, 0, - activePlayer->GetObjectID(), "", UNASSIGNED_SYSTEM_ADDRESS); - auto* stats = activePlayer->GetComponent(); - if (stats) { - if (stats->GetImagination() > 0) { - self->AddTimer("checkPlayer", updateFrequency); - } else { - StopPlayingInstrument(self, activePlayer); - } - } - } else if (activePlayer != nullptr && name == "deductImagination" && self->GetVar(u"beingPlayed")) { - auto* stats = activePlayer->GetComponent(); - if (stats) - stats->SetImagination(stats->GetImagination() - instrumentImaginationCost); + if (activePlayer != nullptr && name == "checkPlayer" && self->GetVar(u"beingPlayed")) { + GameMessages::SendNotifyClientObject(self->GetObjectID(), u"checkMovement", 0, 0, + activePlayer->GetObjectID(), "", UNASSIGNED_SYSTEM_ADDRESS); + auto* stats = activePlayer->GetComponent(); + if (stats) { + if (stats->GetImagination() > 0) { + self->AddTimer("checkPlayer", updateFrequency); + } else { + StopPlayingInstrument(self, activePlayer); + } + } + } else if (activePlayer != nullptr && name == "deductImagination" && self->GetVar(u"beingPlayed")) { + auto* stats = activePlayer->GetComponent(); + if (stats) + stats->SetImagination(stats->GetImagination() - instrumentImaginationCost); - self->AddTimer("deductImagination", instrumentCostFrequency); - } else if (name == "cleanupAfterStop") { - if (activePlayer != nullptr) { - UnEquipInstruments(self, activePlayer); - GameMessages::SendNotifyClientObject(self->GetObjectID(), u"stopPlaying", 0, 0, - activePlayer->GetObjectID(), "", UNASSIGNED_SYSTEM_ADDRESS); - } + self->AddTimer("deductImagination", instrumentCostFrequency); + } else if (name == "cleanupAfterStop") { + if (activePlayer != nullptr) { + UnEquipInstruments(self, activePlayer); + GameMessages::SendNotifyClientObject(self->GetObjectID(), u"stopPlaying", 0, 0, + activePlayer->GetObjectID(), "", UNASSIGNED_SYSTEM_ADDRESS); + } - auto* rebuildComponent = self->GetComponent(); - if (rebuildComponent != nullptr) - rebuildComponent->ResetRebuild(false); + auto* rebuildComponent = self->GetComponent(); + if (rebuildComponent != nullptr) + rebuildComponent->ResetRebuild(false); - self->Smash(self->GetObjectID(), VIOLENT); - self->SetVar(u"activePlayer", LWOOBJID_EMPTY); - } else if (activePlayer != nullptr && name == "achievement") { - auto* missionComponent = activePlayer->GetComponent(); - if (missionComponent != nullptr) { - missionComponent->ForceProgress(302, 462, self->GetLOT()); - } - self->AddTimer("achievement2", 10.0f); - } else if (activePlayer != nullptr && name == "achievement2") { - auto* missionComponent = activePlayer->GetComponent(); - if (missionComponent != nullptr) { - missionComponent->ForceProgress(602, achievementTaskID.at(GetInstrumentLot(self)), self->GetLOT()); - } - } + self->Smash(self->GetObjectID(), VIOLENT); + self->SetVar(u"activePlayer", LWOOBJID_EMPTY); + } else if (activePlayer != nullptr && name == "achievement") { + auto* missionComponent = activePlayer->GetComponent(); + if (missionComponent != nullptr) { + missionComponent->ForceProgress(302, 462, self->GetLOT()); + } + self->AddTimer("achievement2", 10.0f); + } else if (activePlayer != nullptr && name == "achievement2") { + auto* missionComponent = activePlayer->GetComponent(); + if (missionComponent != nullptr) { + missionComponent->ForceProgress(602, achievementTaskID.at(GetInstrumentLot(self)), self->GetLOT()); + } + } } -void NsConcertInstrument::StartPlayingInstrument(Entity *self, Entity* player) { - const auto instrumentLot = GetInstrumentLot(self); - self->SetVar(u"beingPlayed", true); +void NsConcertInstrument::StartPlayingInstrument(Entity* self, Entity* player) { + const auto instrumentLot = GetInstrumentLot(self); + self->SetVar(u"beingPlayed", true); - // Stuff to notify the player - EquipInstruments(self, player); - GameMessages::SendNotifyClientObject(self->GetObjectID(), u"startPlaying", 0, 0, - player->GetObjectID(), "", UNASSIGNED_SYSTEM_ADDRESS); - GameMessages::SendPlayCinematic(player->GetObjectID(), cinematics.at(instrumentLot), UNASSIGNED_SYSTEM_ADDRESS); - self->AddCallbackTimer(1.0f, [player, instrumentLot]() { - GameMessages::SendPlayAnimation(player, animations.at(instrumentLot), 2.0f); - }); + // Stuff to notify the player + EquipInstruments(self, player); + GameMessages::SendNotifyClientObject(self->GetObjectID(), u"startPlaying", 0, 0, + player->GetObjectID(), "", UNASSIGNED_SYSTEM_ADDRESS); + GameMessages::SendPlayCinematic(player->GetObjectID(), cinematics.at(instrumentLot), UNASSIGNED_SYSTEM_ADDRESS); + self->AddCallbackTimer(1.0f, [player, instrumentLot]() { + GameMessages::SendPlayAnimation(player, animations.at(instrumentLot), 2.0f); + }); - for (auto* soundBox : EntityManager::Instance()->GetEntitiesInGroup("Audio-Concert")) { - auto* soundTrigger = soundBox->GetComponent(); - if (soundTrigger != nullptr) { - soundTrigger->ActivateMusicCue(music.at(instrumentLot)); - } - } + for (auto* soundBox : EntityManager::Instance()->GetEntitiesInGroup("Audio-Concert")) { + auto* soundTrigger = soundBox->GetComponent(); + if (soundTrigger != nullptr) { + soundTrigger->ActivateMusicCue(music.at(instrumentLot)); + } + } - // Add timers for deducting imagination and checking if the instruments can still be played - self->AddTimer("checkPlayer", updateFrequency); - self->AddTimer("deductImagination", instrumentCostFrequency); - self->AddTimer("achievement", 20.0f); + // Add timers for deducting imagination and checking if the instruments can still be played + self->AddTimer("checkPlayer", updateFrequency); + self->AddTimer("deductImagination", instrumentCostFrequency); + self->AddTimer("achievement", 20.0f); } -void NsConcertInstrument::StopPlayingInstrument(Entity *self, Entity* player) { - // No use in stopping twice - if (!self->GetVar(u"beingPlayed")) - return; +void NsConcertInstrument::StopPlayingInstrument(Entity* self, Entity* player) { + // No use in stopping twice + if (!self->GetVar(u"beingPlayed")) + return; - const auto instrumentLot = GetInstrumentLot(self); + const auto instrumentLot = GetInstrumentLot(self); - // Player might be null if they left - if (player != nullptr) { - auto* missions = player->GetComponent(); - if (missions != nullptr && missions->GetMissionState(176) == MissionState::MISSION_STATE_ACTIVE) { - missions->Progress(MissionTaskType::MISSION_TASK_TYPE_SCRIPT, self->GetLOT()); - } + // Player might be null if they left + if (player != nullptr) { + auto* missions = player->GetComponent(); + if (missions != nullptr && missions->GetMissionState(176) == MissionState::MISSION_STATE_ACTIVE) { + missions->Progress(MissionTaskType::MISSION_TASK_TYPE_SCRIPT, self->GetLOT()); + } - GameMessages::SendEndCinematic(player->GetObjectID(), cinematics.at(instrumentLot), UNASSIGNED_SYSTEM_ADDRESS, 1.0f); - GameMessages::SendPlayAnimation(player, smashAnimations.at(instrumentLot), 2.0f); - GameMessages::SendNotifyClientObject(self->GetObjectID(), u"stopCheckingMovement", 0, 0, - player->GetObjectID(), "", UNASSIGNED_SYSTEM_ADDRESS); - } + GameMessages::SendEndCinematic(player->GetObjectID(), cinematics.at(instrumentLot), UNASSIGNED_SYSTEM_ADDRESS, 1.0f); + GameMessages::SendPlayAnimation(player, smashAnimations.at(instrumentLot), 2.0f); + GameMessages::SendNotifyClientObject(self->GetObjectID(), u"stopCheckingMovement", 0, 0, + player->GetObjectID(), "", UNASSIGNED_SYSTEM_ADDRESS); + } - self->SetVar(u"beingPlayed", false); + self->SetVar(u"beingPlayed", false); - for (auto* soundBox : EntityManager::Instance()->GetEntitiesInGroup("Audio-Concert")) { - auto* soundTrigger = soundBox->GetComponent(); - if (soundTrigger != nullptr) { - soundTrigger->DeactivateMusicCue(music.at(instrumentLot)); - } - } + for (auto* soundBox : EntityManager::Instance()->GetEntitiesInGroup("Audio-Concert")) { + auto* soundTrigger = soundBox->GetComponent(); + if (soundTrigger != nullptr) { + soundTrigger->DeactivateMusicCue(music.at(instrumentLot)); + } + } - self->CancelAllTimers(); - self->AddTimer("cleanupAfterStop", instrumentSmashAnimationTime.at(instrumentLot)); + self->CancelAllTimers(); + self->AddTimer("cleanupAfterStop", instrumentSmashAnimationTime.at(instrumentLot)); } -void NsConcertInstrument::EquipInstruments(Entity *self, Entity *player) { - auto* inventory = player->GetComponent(); - if (inventory != nullptr) { - auto equippedItems = inventory->GetEquippedItems(); +void NsConcertInstrument::EquipInstruments(Entity* self, Entity* player) { + auto* inventory = player->GetComponent(); + if (inventory != nullptr) { + auto equippedItems = inventory->GetEquippedItems(); - // Un equip the current left item - const auto equippedLeftItem = equippedItems.find("special_l"); - if (equippedLeftItem != equippedItems.end()) { - auto* leftItem = inventory->FindItemById(equippedLeftItem->second.id); - if (leftItem != nullptr) { - leftItem->UnEquip(); - self->SetVar(u"oldItemLeft", leftItem->GetId()); - } - } + // Un equip the current left item + const auto equippedLeftItem = equippedItems.find("special_l"); + if (equippedLeftItem != equippedItems.end()) { + auto* leftItem = inventory->FindItemById(equippedLeftItem->second.id); + if (leftItem != nullptr) { + leftItem->UnEquip(); + self->SetVar(u"oldItemLeft", leftItem->GetId()); + } + } - // Un equip the current right item - const auto equippedRightItem = equippedItems.find("special_r"); - if (equippedRightItem != equippedItems.end()) { - auto* rightItem = inventory->FindItemById(equippedRightItem->second.id); - if (rightItem != nullptr) { - rightItem->UnEquip(); - self->SetVar(u"oldItemRight", rightItem->GetId()); - } - } + // Un equip the current right item + const auto equippedRightItem = equippedItems.find("special_r"); + if (equippedRightItem != equippedItems.end()) { + auto* rightItem = inventory->FindItemById(equippedRightItem->second.id); + if (rightItem != nullptr) { + rightItem->UnEquip(); + self->SetVar(u"oldItemRight", rightItem->GetId()); + } + } - // Equip the left hand instrument - const auto leftInstrumentLot = instrumentLotLeft.find(GetInstrumentLot(self))->second; - if (leftInstrumentLot != LOT_NULL) { - inventory->AddItem(leftInstrumentLot, 1, eLootSourceType::LOOT_SOURCE_NONE, TEMP_ITEMS, {}, LWOOBJID_EMPTY, false); - auto* leftInstrument = inventory->FindItemByLot(leftInstrumentLot, TEMP_ITEMS); - leftInstrument->Equip(); - } + // Equip the left hand instrument + const auto leftInstrumentLot = instrumentLotLeft.find(GetInstrumentLot(self))->second; + if (leftInstrumentLot != LOT_NULL) { + inventory->AddItem(leftInstrumentLot, 1, eLootSourceType::LOOT_SOURCE_NONE, TEMP_ITEMS, {}, LWOOBJID_EMPTY, false); + auto* leftInstrument = inventory->FindItemByLot(leftInstrumentLot, TEMP_ITEMS); + leftInstrument->Equip(); + } - // Equip the right hand instrument - const auto rightInstrumentLot = instrumentLotRight.find(GetInstrumentLot(self))->second; - if (rightInstrumentLot != LOT_NULL) { - inventory->AddItem(rightInstrumentLot, 1, eLootSourceType::LOOT_SOURCE_NONE, TEMP_ITEMS, {}, LWOOBJID_EMPTY, false); - auto* rightInstrument = inventory->FindItemByLot(rightInstrumentLot, TEMP_ITEMS); - rightInstrument->Equip(); - } - } + // Equip the right hand instrument + const auto rightInstrumentLot = instrumentLotRight.find(GetInstrumentLot(self))->second; + if (rightInstrumentLot != LOT_NULL) { + inventory->AddItem(rightInstrumentLot, 1, eLootSourceType::LOOT_SOURCE_NONE, TEMP_ITEMS, {}, LWOOBJID_EMPTY, false); + auto* rightInstrument = inventory->FindItemByLot(rightInstrumentLot, TEMP_ITEMS); + rightInstrument->Equip(); + } + } } -void NsConcertInstrument::UnEquipInstruments(Entity *self, Entity *player) { - auto* inventory = player->GetComponent(); - if (inventory != nullptr) { - auto equippedItems = inventory->GetEquippedItems(); +void NsConcertInstrument::UnEquipInstruments(Entity* self, Entity* player) { + auto* inventory = player->GetComponent(); + if (inventory != nullptr) { + auto equippedItems = inventory->GetEquippedItems(); - // Un equip the current left instrument - const auto equippedInstrumentLeft = equippedItems.find("special_l"); - if (equippedInstrumentLeft != equippedItems.end()) { - auto* leftItem = inventory->FindItemById(equippedInstrumentLeft->second.id); - if (leftItem != nullptr) { - leftItem->UnEquip(); - inventory->RemoveItem(leftItem->GetLot(), 1, TEMP_ITEMS); - } - } + // Un equip the current left instrument + const auto equippedInstrumentLeft = equippedItems.find("special_l"); + if (equippedInstrumentLeft != equippedItems.end()) { + auto* leftItem = inventory->FindItemById(equippedInstrumentLeft->second.id); + if (leftItem != nullptr) { + leftItem->UnEquip(); + inventory->RemoveItem(leftItem->GetLot(), 1, TEMP_ITEMS); + } + } - // Un equip the current right instrument - const auto equippedInstrumentRight = equippedItems.find("special_r"); - if (equippedInstrumentRight != equippedItems.end()) { - auto* rightItem = inventory->FindItemById(equippedInstrumentRight->second.id); - if (rightItem != nullptr) { - rightItem->UnEquip(); - inventory->RemoveItem(rightItem->GetLot(), 1, TEMP_ITEMS); - } - } + // Un equip the current right instrument + const auto equippedInstrumentRight = equippedItems.find("special_r"); + if (equippedInstrumentRight != equippedItems.end()) { + auto* rightItem = inventory->FindItemById(equippedInstrumentRight->second.id); + if (rightItem != nullptr) { + rightItem->UnEquip(); + inventory->RemoveItem(rightItem->GetLot(), 1, TEMP_ITEMS); + } + } - // Equip the old left hand item - const auto leftItemID = self->GetVar(u"oldItemLeft"); - if (leftItemID != LWOOBJID_EMPTY) { - auto* item = inventory->FindItemById(leftItemID); - if (item != nullptr) - item->Equip(); - self->SetVar(u"oldItemLeft", LWOOBJID_EMPTY); - } + // Equip the old left hand item + const auto leftItemID = self->GetVar(u"oldItemLeft"); + if (leftItemID != LWOOBJID_EMPTY) { + auto* item = inventory->FindItemById(leftItemID); + if (item != nullptr) + item->Equip(); + self->SetVar(u"oldItemLeft", LWOOBJID_EMPTY); + } - // Equip the old right hand item - const auto rightItemID = self->GetVar(u"oldItemRight"); - if (rightItemID != LWOOBJID_EMPTY) { - auto* item = inventory->FindItemById(rightItemID); - if (item != nullptr) - item->Equip(); - self->SetVar(u"oldItemRight", LWOOBJID_EMPTY); - } - } + // Equip the old right hand item + const auto rightItemID = self->GetVar(u"oldItemRight"); + if (rightItemID != LWOOBJID_EMPTY) { + auto* item = inventory->FindItemById(rightItemID); + if (item != nullptr) + item->Equip(); + self->SetVar(u"oldItemRight", LWOOBJID_EMPTY); + } + } } -void NsConcertInstrument::RepositionPlayer(Entity *self, Entity *player) { - auto position = self->GetPosition(); - auto rotation = self->GetRotation(); - position.SetY(0.0f); +void NsConcertInstrument::RepositionPlayer(Entity* self, Entity* player) { + auto position = self->GetPosition(); + auto rotation = self->GetRotation(); + position.SetY(0.0f); - switch (GetInstrumentLot(self)) { - case Bass: - case Guitar: - position.SetX(position.GetX() + 5.0f); - break; - case Keyboard: - position.SetX(position.GetX() - 0.45f); - position.SetZ(position.GetZ() + 0.75f); - rotation = NiQuaternion::CreateFromAxisAngle(position, -0.8f); // Slight rotation to make the animation sensible - break; - case Drum: - position.SetZ(position.GetZ() - 0.5f); - break; - } + switch (GetInstrumentLot(self)) { + case Bass: + case Guitar: + position.SetX(position.GetX() + 5.0f); + break; + case Keyboard: + position.SetX(position.GetX() - 0.45f); + position.SetZ(position.GetZ() + 0.75f); + rotation = NiQuaternion::CreateFromAxisAngle(position, -0.8f); // Slight rotation to make the animation sensible + break; + case Drum: + position.SetZ(position.GetZ() - 0.5f); + break; + } - GameMessages::SendTeleport(player->GetObjectID(), position, rotation, player->GetSystemAddress()); + GameMessages::SendTeleport(player->GetObjectID(), position, rotation, player->GetSystemAddress()); } -InstrumentLot NsConcertInstrument::GetInstrumentLot(Entity *self) { - return static_cast(self->GetLOT()); +InstrumentLot NsConcertInstrument::GetInstrumentLot(Entity* self) { + return static_cast(self->GetLOT()); } // Static stuff needed for script execution -const std::map NsConcertInstrument::animations { - { Guitar, u"guitar"}, - { Bass, u"bass"}, - { Keyboard, u"keyboard"}, - { Drum, u"drums"} +const std::map NsConcertInstrument::animations{ + { Guitar, u"guitar"}, + { Bass, u"bass"}, + { Keyboard, u"keyboard"}, + { Drum, u"drums"} }; -const std::map NsConcertInstrument::smashAnimations { - {Guitar, u"guitar-smash"}, - {Bass, u"bass-smash"}, - {Keyboard, u"keyboard-smash"}, - {Drum, u"keyboard-smash"} +const std::map NsConcertInstrument::smashAnimations{ + {Guitar, u"guitar-smash"}, + {Bass, u"bass-smash"}, + {Keyboard, u"keyboard-smash"}, + {Drum, u"keyboard-smash"} }; -const std::map NsConcertInstrument::instrumentSmashAnimationTime { - {Guitar, 2.167f}, - {Bass, 1.167f}, - {Keyboard, 1.0f}, - {Drum, 1.0f} +const std::map NsConcertInstrument::instrumentSmashAnimationTime{ + {Guitar, 2.167f}, + {Bass, 1.167f}, + {Keyboard, 1.0f}, + {Drum, 1.0f} }; -const std::map NsConcertInstrument::music { - {Guitar, "Concert_Guitar"}, - {Bass, "Concert_Bass"}, - {Keyboard, "Concert_Keys"}, - {Drum, "Concert_Drums"}, +const std::map NsConcertInstrument::music{ + {Guitar, "Concert_Guitar"}, + {Bass, "Concert_Bass"}, + {Keyboard, "Concert_Keys"}, + {Drum, "Concert_Drums"}, }; -const std::map NsConcertInstrument::cinematics { - {Guitar, u"Concert_Cam_G"}, - {Bass, u"Concert_Cam_B"}, - {Keyboard, u"Concert_Cam_K"}, - {Drum, u"Concert_Cam_D"}, +const std::map NsConcertInstrument::cinematics{ + {Guitar, u"Concert_Cam_G"}, + {Bass, u"Concert_Cam_B"}, + {Keyboard, u"Concert_Cam_K"}, + {Drum, u"Concert_Cam_D"}, }; -const std::map NsConcertInstrument::instrumentLotLeft { - {Guitar, 4991}, - {Bass, 4992}, - {Keyboard, LOT_NULL}, - {Drum, 4995}, +const std::map NsConcertInstrument::instrumentLotLeft{ + {Guitar, 4991}, + {Bass, 4992}, + {Keyboard, LOT_NULL}, + {Drum, 4995}, }; -const std::map NsConcertInstrument::instrumentLotRight { - {Guitar, LOT_NULL}, - {Bass, LOT_NULL}, - {Keyboard, LOT_NULL}, - {Drum, 4996}, +const std::map NsConcertInstrument::instrumentLotRight{ + {Guitar, LOT_NULL}, + {Bass, LOT_NULL}, + {Keyboard, LOT_NULL}, + {Drum, 4996}, }; -const std::map NsConcertInstrument::hideInstrumentOnPlay { - {Guitar, true}, - {Bass, true}, - {Keyboard, false}, - {Drum, false}, +const std::map NsConcertInstrument::hideInstrumentOnPlay{ + {Guitar, true}, + {Bass, true}, + {Keyboard, false}, + {Drum, false}, }; -const std::map NsConcertInstrument::instrumentEquipTime { - {Guitar, 1.033}, - {Bass, 0.75}, - {Keyboard, -1}, - {Drum, 0}, +const std::map NsConcertInstrument::instrumentEquipTime{ + {Guitar, 1.033}, + {Bass, 0.75}, + {Keyboard, -1}, + {Drum, 0}, }; -const std::map NsConcertInstrument::achievementTaskID { - {Guitar, 911}, - {Bass, 912}, - {Keyboard, 913}, - {Drum, 914}, +const std::map NsConcertInstrument::achievementTaskID{ + {Guitar, 911}, + {Bass, 912}, + {Keyboard, 913}, + {Drum, 914}, }; const uint32_t NsConcertInstrument::instrumentImaginationCost = 2; diff --git a/dScripts/NsConcertInstrument.h b/dScripts/NsConcertInstrument.h index bf59d886..87ccc419 100644 --- a/dScripts/NsConcertInstrument.h +++ b/dScripts/NsConcertInstrument.h @@ -2,90 +2,90 @@ #include "CppScripts.h" enum InstrumentLot { - Guitar = 4039, - Bass = 4040, - Keyboard = 4041, - Drum = 4042 + Guitar = 4039, + Bass = 4040, + Keyboard = 4041, + Drum = 4042 }; class NsConcertInstrument : public CppScripts::Script { public: - void OnStartup(Entity* self) override; - void OnRebuildNotifyState(Entity* self, eRebuildState state) override; - void OnFireEventServerSide(Entity *self, Entity *sender, std::string args, int32_t param1, int32_t param2, - int32_t param3) override; - void OnRebuildComplete(Entity* self, Entity* target) override; - void OnTimerDone(Entity* self, std::string name) override; + void OnStartup(Entity* self) override; + void OnRebuildNotifyState(Entity* self, eRebuildState state) override; + void OnFireEventServerSide(Entity* self, Entity* sender, std::string args, int32_t param1, int32_t param2, + int32_t param3) override; + void OnRebuildComplete(Entity* self, Entity* target) override; + void OnTimerDone(Entity* self, std::string name) override; private: - static void StartPlayingInstrument(Entity* self, Entity* player); - static void StopPlayingInstrument(Entity* self, Entity* player); - static void EquipInstruments(Entity* self, Entity* player); - static void UnEquipInstruments(Entity* self, Entity* player); - static void RepositionPlayer(Entity* self, Entity* player); - static InstrumentLot GetInstrumentLot(Entity* self); + static void StartPlayingInstrument(Entity* self, Entity* player); + static void StopPlayingInstrument(Entity* self, Entity* player); + static void EquipInstruments(Entity* self, Entity* player); + static void UnEquipInstruments(Entity* self, Entity* player); + static void RepositionPlayer(Entity* self, Entity* player); + static InstrumentLot GetInstrumentLot(Entity* self); - /** - * Animations played when using an instrument - */ - static const std::map animations; + /** + * Animations played when using an instrument + */ + static const std::map animations; - /** - * Animation played when an instrument is smashed - */ - static const std::map smashAnimations; + /** + * Animation played when an instrument is smashed + */ + static const std::map smashAnimations; - /** - * Music to play while playing an instrument - */ - static const std::map music; + /** + * Music to play while playing an instrument + */ + static const std::map music; - /** - * Cinematics to play while playing an instrument - */ - static const std::map cinematics; + /** + * Cinematics to play while playing an instrument + */ + static const std::map cinematics; - /** - * Lot to equip in your left hand when playing an instrument - */ - static const std::map instrumentLotLeft; + /** + * Lot to equip in your left hand when playing an instrument + */ + static const std::map instrumentLotLeft; - /** - * Lot to play in your right hand when playing an instrument - */ - static const std::map instrumentLotRight; + /** + * Lot to play in your right hand when playing an instrument + */ + static const std::map instrumentLotRight; - /** - * Whether to hide the instrument or not when someone is playing it - */ - static const std::map hideInstrumentOnPlay; + /** + * Whether to hide the instrument or not when someone is playing it + */ + static const std::map hideInstrumentOnPlay; - /** - * How long to wait before unequipping the instrument if the instrument was smashed - */ - static const std::map instrumentEquipTime; + /** + * How long to wait before unequipping the instrument if the instrument was smashed + */ + static const std::map instrumentEquipTime; - /** - * How long the smash animation takes for each of the instruments - */ - static const std::map instrumentSmashAnimationTime; + /** + * How long the smash animation takes for each of the instruments + */ + static const std::map instrumentSmashAnimationTime; - /** - * Task ID of tasks of the Solo Artist 2 achievement - */ - static const std::map achievementTaskID; + /** + * Task ID of tasks of the Solo Artist 2 achievement + */ + static const std::map achievementTaskID; - /** - * How much imagination playing an instrument costs per interval - */ - static const uint32_t instrumentImaginationCost; + /** + * How much imagination playing an instrument costs per interval + */ + static const uint32_t instrumentImaginationCost; - /** - * The interval to deduct imagination at when playing an instrument - */ - static const float instrumentCostFrequency; + /** + * The interval to deduct imagination at when playing an instrument + */ + static const float instrumentCostFrequency; - /** - * The interval to check if the player still has enough imagination - */ - static const float updateFrequency; -}; \ No newline at end of file + /** + * The interval to check if the player still has enough imagination + */ + static const float updateFrequency; +}; diff --git a/dScripts/NsConcertQuickBuild.cpp b/dScripts/NsConcertQuickBuild.cpp index ba7b4010..fcec4dc7 100644 --- a/dScripts/NsConcertQuickBuild.cpp +++ b/dScripts/NsConcertQuickBuild.cpp @@ -10,215 +10,215 @@ const float NsConcertQuickBuild::resetTime = 40.0f; const float NsConcertQuickBuild::resetBlinkTime = 6.0f; const float NsConcertQuickBuild::resetStageTime = 66.5f; const float NsConcertQuickBuild::resetActivatorTime = 30.0f; -const std::map NsConcertQuickBuild::quickBuildSets { - {5846, QuickBuildSet {"laser", {"discoball", "discofloor", "stagelights", "spotlight"}}}, - {5847, QuickBuildSet {"spotlight", {"spotlight", "stagelights"}}}, - {5848, QuickBuildSet {"rocket", {"flamethrower"}}}, - {5845, QuickBuildSet {"speaker", {"speaker", "speakerHill", "stagelights", "spotlight"}}} +const std::map NsConcertQuickBuild::quickBuildSets{ + {5846, QuickBuildSet {"laser", {"discoball", "discofloor", "stagelights", "spotlight"}}}, + {5847, QuickBuildSet {"spotlight", {"spotlight", "stagelights"}}}, + {5848, QuickBuildSet {"rocket", {"flamethrower"}}}, + {5845, QuickBuildSet {"speaker", {"speaker", "speakerHill", "stagelights", "spotlight"}}} }; -const std::map NsConcertQuickBuild::quickBuildFX { - {"discoball", "effectsDiscoball"}, - {"speaker", "effectsShell"}, - {"speakerHill", "effectsHill"}, - {"spotlight", "effectsHill"}, - {"discofloor", "effectsShell"}, - {"flamethrower", "effectsShell"}, - {"stagelights", "effectsShell"} +const std::map NsConcertQuickBuild::quickBuildFX{ + {"discoball", "effectsDiscoball"}, + {"speaker", "effectsShell"}, + {"speakerHill", "effectsHill"}, + {"spotlight", "effectsHill"}, + {"discofloor", "effectsShell"}, + {"flamethrower", "effectsShell"}, + {"stagelights", "effectsShell"} }; std::vector NsConcertQuickBuild::finishedQuickBuilds = {}; -void NsConcertQuickBuild::OnStartup(Entity *self) { - const auto groups = self->GetGroups(); - if (groups.empty()) - return; +void NsConcertQuickBuild::OnStartup(Entity* self) { + const auto groups = self->GetGroups(); + if (groups.empty()) + return; - // Groups are of the form Concert_Laser_QB_1, Concert_Laser_QB_2, etc. - auto group = groups.at(0); - const auto splitGroup = GeneralUtils::SplitString(group, '_'); - if (splitGroup.size() < 4) - return; + // Groups are of the form Concert_Laser_QB_1, Concert_Laser_QB_2, etc. + auto group = groups.at(0); + const auto splitGroup = GeneralUtils::SplitString(group, '_'); + if (splitGroup.size() < 4) + return; - // Get the manager of the crate of this quick build - const auto groupNumber = std::stoi(splitGroup.at(3)); - const auto managerObjects = EntityManager::Instance()->GetEntitiesInGroup("CB_" + std::to_string(groupNumber)); - if (managerObjects.empty()) - return; + // Get the manager of the crate of this quick build + const auto groupNumber = std::stoi(splitGroup.at(3)); + const auto managerObjects = EntityManager::Instance()->GetEntitiesInGroup("CB_" + std::to_string(groupNumber)); + if (managerObjects.empty()) + return; - auto* managerObject = managerObjects.at(0); - self->SetVar(u"managerObject", managerObject->GetObjectID()); - self->SetVar(u"groupNumber", groupNumber); + auto* managerObject = managerObjects.at(0); + self->SetVar(u"managerObject", managerObject->GetObjectID()); + self->SetVar(u"groupNumber", groupNumber); - // Makes the quick build blink after a certain amount of time - self->AddCallbackTimer(GetBlinkTime(resetActivatorTime), [self]() { - self->SetNetworkVar(u"startEffect", NsConcertQuickBuild::GetBlinkTime(resetActivatorTime)); - }); + // Makes the quick build blink after a certain amount of time + self->AddCallbackTimer(GetBlinkTime(resetActivatorTime), [self]() { + self->SetNetworkVar(u"startEffect", NsConcertQuickBuild::GetBlinkTime(resetActivatorTime)); + }); - // Destroys the quick build after a while if it wasn't built - self->AddCallbackTimer(resetActivatorTime, [self]() { - self->SetNetworkVar(u"startEffect", -1.0f); - self->Smash(self->GetObjectID(), SILENT); - }); + // Destroys the quick build after a while if it wasn't built + self->AddCallbackTimer(resetActivatorTime, [self]() { + self->SetNetworkVar(u"startEffect", -1.0f); + self->Smash(self->GetObjectID(), SILENT); + }); } float NsConcertQuickBuild::GetBlinkTime(float time) { - return time <= NsConcertQuickBuild::resetBlinkTime ? 1.0f : time - NsConcertQuickBuild::resetBlinkTime; + return time <= NsConcertQuickBuild::resetBlinkTime ? 1.0f : time - NsConcertQuickBuild::resetBlinkTime; } -void NsConcertQuickBuild::OnDie(Entity *self, Entity *killer) { - auto* managerObject = EntityManager::Instance()->GetEntity(self->GetVar(u"managerObject")); - if (managerObject) { - managerObject->CancelAllTimers(); - managerObject->AddCallbackTimer(1.0f, [managerObject]() { - NsConcertChoiceBuildManager::SpawnCrate(managerObject); - }); - } +void NsConcertQuickBuild::OnDie(Entity* self, Entity* killer) { + auto* managerObject = EntityManager::Instance()->GetEntity(self->GetVar(u"managerObject")); + if (managerObject) { + managerObject->CancelAllTimers(); + managerObject->AddCallbackTimer(1.0f, [managerObject]() { + NsConcertChoiceBuildManager::SpawnCrate(managerObject); + }); + } - auto position = std::find(finishedQuickBuilds.begin(), finishedQuickBuilds.end(), self->GetObjectID()); - if (position != finishedQuickBuilds.end()) - finishedQuickBuilds.erase(position); + auto position = std::find(finishedQuickBuilds.begin(), finishedQuickBuilds.end(), self->GetObjectID()); + if (position != finishedQuickBuilds.end()) + finishedQuickBuilds.erase(position); } -void NsConcertQuickBuild::OnRebuildComplete(Entity *self, Entity *target) { - const auto groupNumber = self->GetVar(u"groupNumber"); - finishedQuickBuilds.push_back(self->GetObjectID()); - self->SetNetworkVar(u"startEffect", -1.0f); +void NsConcertQuickBuild::OnRebuildComplete(Entity* self, Entity* target) { + const auto groupNumber = self->GetVar(u"groupNumber"); + finishedQuickBuilds.push_back(self->GetObjectID()); + self->SetNetworkVar(u"startEffect", -1.0f); - ProgressStageCraft(self, target); + ProgressStageCraft(self, target); - // Find all the quick build objects of the same lot - auto finishedQuickBuildObjects = std::vector(); - for (auto quickBuildID : finishedQuickBuilds) { - const auto quickBuildObject = EntityManager::Instance()->GetEntity(quickBuildID); - if (quickBuildObject && quickBuildObject->GetLOT() == self->GetLOT()) { - quickBuildObject->SetVar(u"Player_" + (GeneralUtils::to_u16string(groupNumber)), target->GetObjectID()); - finishedQuickBuildObjects.push_back(quickBuildObject); - } - } + // Find all the quick build objects of the same lot + auto finishedQuickBuildObjects = std::vector(); + for (auto quickBuildID : finishedQuickBuilds) { + const auto quickBuildObject = EntityManager::Instance()->GetEntity(quickBuildID); + if (quickBuildObject && quickBuildObject->GetLOT() == self->GetLOT()) { + quickBuildObject->SetVar(u"Player_" + (GeneralUtils::to_u16string(groupNumber)), target->GetObjectID()); + finishedQuickBuildObjects.push_back(quickBuildObject); + } + } - // If all 4 sets were built, do cool stuff - if (finishedQuickBuildObjects.size() >= 4) { + // If all 4 sets were built, do cool stuff + if (finishedQuickBuildObjects.size() >= 4) { - // Move all the platforms so the user can collect the imagination brick - const auto movingPlatforms = EntityManager::Instance()->GetEntitiesInGroup("ConcertPlatforms"); - for (auto* movingPlatform : movingPlatforms) { - auto* component = movingPlatform->GetComponent(); - if (component) { - component->WarpToWaypoint(component->GetLastWaypointIndex()); + // Move all the platforms so the user can collect the imagination brick + const auto movingPlatforms = EntityManager::Instance()->GetEntitiesInGroup("ConcertPlatforms"); + for (auto* movingPlatform : movingPlatforms) { + auto* component = movingPlatform->GetComponent(); + if (component) { + component->WarpToWaypoint(component->GetLastWaypointIndex()); - movingPlatform->AddCallbackTimer(resetStageTime, [movingPlatform, component]() { - component->WarpToWaypoint(0); - }); - } - } + movingPlatform->AddCallbackTimer(resetStageTime, [movingPlatform, component]() { + component->WarpToWaypoint(0); + }); + } + } - ProgressLicensedTechnician(self); + ProgressLicensedTechnician(self); - // Reset all timers for the quickbuilds and make them indestructible - for (auto quickBuild : finishedQuickBuildObjects) { - quickBuild->SetNetworkVar(u"startEffect", -1.0f); - quickBuild->CancelAllTimers(); + // Reset all timers for the quickbuilds and make them indestructible + for (auto quickBuild : finishedQuickBuildObjects) { + quickBuild->SetNetworkVar(u"startEffect", -1.0f); + quickBuild->CancelAllTimers(); - // Indicate that the stage will reset - quickBuild->AddCallbackTimer(GetBlinkTime(resetStageTime), [quickBuild]() { - quickBuild->SetNetworkVar(u"startEffect", GetBlinkTime(resetTime)); - }); + // Indicate that the stage will reset + quickBuild->AddCallbackTimer(GetBlinkTime(resetStageTime), [quickBuild]() { + quickBuild->SetNetworkVar(u"startEffect", GetBlinkTime(resetTime)); + }); - // Reset the stage - quickBuild->AddCallbackTimer(resetStageTime, [quickBuild]() { - CancelEffects(quickBuild); - quickBuild->SetNetworkVar(u"startEffect", -1); - quickBuild->Smash(); - }); + // Reset the stage + quickBuild->AddCallbackTimer(resetStageTime, [quickBuild]() { + CancelEffects(quickBuild); + quickBuild->SetNetworkVar(u"startEffect", -1); + quickBuild->Smash(); + }); - auto* destroyableComponent = quickBuild->GetComponent(); - if (destroyableComponent) - destroyableComponent->SetFaction(-1); - } + auto* destroyableComponent = quickBuild->GetComponent(); + if (destroyableComponent) + destroyableComponent->SetFaction(-1); + } - UpdateEffects(self); - return; - } + UpdateEffects(self); + return; + } - // If not all 4 sets were built, reset the timers that were set on spawn - self->CancelAllTimers(); + // If not all 4 sets were built, reset the timers that were set on spawn + self->CancelAllTimers(); - // Makes the quick build blink after a certain amount of time - self->AddCallbackTimer(GetBlinkTime(resetTime), [self]() { - self->SetNetworkVar(u"startEffect", NsConcertQuickBuild::GetBlinkTime(resetActivatorTime)); - }); + // Makes the quick build blink after a certain amount of time + self->AddCallbackTimer(GetBlinkTime(resetTime), [self]() { + self->SetNetworkVar(u"startEffect", NsConcertQuickBuild::GetBlinkTime(resetActivatorTime)); + }); - // Destroys the quick build after a while if it wasn't built - self->AddCallbackTimer(resetTime, [self]() { - self->SetNetworkVar(u"startEffect", -1.0f); - self->Smash(self->GetObjectID()); - }); + // Destroys the quick build after a while if it wasn't built + self->AddCallbackTimer(resetTime, [self]() { + self->SetNetworkVar(u"startEffect", -1.0f); + self->Smash(self->GetObjectID()); + }); } -void NsConcertQuickBuild::ProgressStageCraft(Entity *self, Entity* player) { - auto* missionComponent = player->GetComponent(); - if (missionComponent) { +void NsConcertQuickBuild::ProgressStageCraft(Entity* self, Entity* player) { + auto* missionComponent = player->GetComponent(); + if (missionComponent) { - // Has to be forced as to not accidentally trigger the licensed technician achievement - switch(self->GetLOT()) { - case 5845: - missionComponent->ForceProgress(283, 432, 5845); - break; - case 5846: - missionComponent->ForceProgress(283, 433, 5846); - break; - case 5847: - missionComponent->ForceProgress(283, 434, 5847); - break; - case 5848: - missionComponent->ForceProgress(283, 435, 5848); - break; - default: - break; - } - } + // Has to be forced as to not accidentally trigger the licensed technician achievement + switch (self->GetLOT()) { + case 5845: + missionComponent->ForceProgress(283, 432, 5845); + break; + case 5846: + missionComponent->ForceProgress(283, 433, 5846); + break; + case 5847: + missionComponent->ForceProgress(283, 434, 5847); + break; + case 5848: + missionComponent->ForceProgress(283, 435, 5848); + break; + default: + break; + } + } } -void NsConcertQuickBuild::ProgressLicensedTechnician(Entity *self) { - for (auto i = 1; i < 5; i++) { - const auto playerID = self->GetVar(u"Player_" + (GeneralUtils::to_u16string(i))); - if (playerID != LWOOBJID_EMPTY) { - const auto player = EntityManager::Instance()->GetEntity(playerID); - if (player) { - auto playerMissionComponent = player->GetComponent(); - if (playerMissionComponent) - playerMissionComponent->ForceProgress(598, 903, self->GetLOT()); - } - } - } +void NsConcertQuickBuild::ProgressLicensedTechnician(Entity* self) { + for (auto i = 1; i < 5; i++) { + const auto playerID = self->GetVar(u"Player_" + (GeneralUtils::to_u16string(i))); + if (playerID != LWOOBJID_EMPTY) { + const auto player = EntityManager::Instance()->GetEntity(playerID); + if (player) { + auto playerMissionComponent = player->GetComponent(); + if (playerMissionComponent) + playerMissionComponent->ForceProgress(598, 903, self->GetLOT()); + } + } + } } -void NsConcertQuickBuild::UpdateEffects(Entity *self) { - CancelEffects(self); +void NsConcertQuickBuild::UpdateEffects(Entity* self) { + CancelEffects(self); - auto setIterator = quickBuildSets.find(self->GetLOT()); - if (setIterator == quickBuildSets.end()) - return; + auto setIterator = quickBuildSets.find(self->GetLOT()); + if (setIterator == quickBuildSets.end()) + return; - for (const auto& effectName : setIterator->second.effects) { - const auto effectObjects = EntityManager::Instance()->GetEntitiesInGroup(quickBuildFX.at(effectName)); - for (auto* effectObject : effectObjects) { - GameMessages::SendPlayFXEffect(effectObject, 0, GeneralUtils::ASCIIToUTF16(effectName), - effectName + "Effect", LWOOBJID_EMPTY, 1, 1, true); - } - } + for (const auto& effectName : setIterator->second.effects) { + const auto effectObjects = EntityManager::Instance()->GetEntitiesInGroup(quickBuildFX.at(effectName)); + for (auto* effectObject : effectObjects) { + GameMessages::SendPlayFXEffect(effectObject, 0, GeneralUtils::ASCIIToUTF16(effectName), + effectName + "Effect", LWOOBJID_EMPTY, 1, 1, true); + } + } } -void NsConcertQuickBuild::CancelEffects(Entity *self) { - auto setIterator = quickBuildSets.find(self->GetLOT()); - if (setIterator == quickBuildSets.end()) - return; +void NsConcertQuickBuild::CancelEffects(Entity* self) { + auto setIterator = quickBuildSets.find(self->GetLOT()); + if (setIterator == quickBuildSets.end()) + return; - for (const auto& effectName : setIterator->second.effects) { - const auto effectObjects = EntityManager::Instance()->GetEntitiesInGroup(quickBuildFX.at(effectName)); - for (auto* effectObject : effectObjects) { - GameMessages::SendStopFXEffect(effectObject, true, effectName + "Effect"); - } - } + for (const auto& effectName : setIterator->second.effects) { + const auto effectObjects = EntityManager::Instance()->GetEntitiesInGroup(quickBuildFX.at(effectName)); + for (auto* effectObject : effectObjects) { + GameMessages::SendStopFXEffect(effectObject, true, effectName + "Effect"); + } + } } diff --git a/dScripts/NsConcertQuickBuild.h b/dScripts/NsConcertQuickBuild.h index b3f6d702..667580f6 100644 --- a/dScripts/NsConcertQuickBuild.h +++ b/dScripts/NsConcertQuickBuild.h @@ -2,26 +2,26 @@ #include "CppScripts.h" struct QuickBuildSet { - std::string name; - std::vector effects; + std::string name; + std::vector effects; }; class NsConcertQuickBuild : public CppScripts::Script { public: - void OnStartup(Entity* self) override; - void OnRebuildComplete(Entity* self, Entity* target) override; - void OnDie(Entity* self, Entity* killer) override; + void OnStartup(Entity* self) override; + void OnRebuildComplete(Entity* self, Entity* target) override; + void OnDie(Entity* self, Entity* killer) override; private: - static std::vector finishedQuickBuilds; - static const float resetBlinkTime; - static const float resetStageTime; - static const float resetActivatorTime; - static const float resetTime; - static const std::map quickBuildFX; - static const std::map quickBuildSets; - static float GetBlinkTime(float time); - static void ProgressStageCraft(Entity* self, Entity* player); - static void ProgressLicensedTechnician(Entity* self); - static void UpdateEffects(Entity* self); - static void CancelEffects(Entity* self); + static std::vector finishedQuickBuilds; + static const float resetBlinkTime; + static const float resetStageTime; + static const float resetActivatorTime; + static const float resetTime; + static const std::map quickBuildFX; + static const std::map quickBuildSets; + static float GetBlinkTime(float time); + static void ProgressStageCraft(Entity* self, Entity* player); + static void ProgressLicensedTechnician(Entity* self); + static void UpdateEffects(Entity* self); + static void CancelEffects(Entity* self); }; diff --git a/dScripts/NsGetFactionMissionServer.cpp b/dScripts/NsGetFactionMissionServer.cpp index d4d03243..d759e3ad 100644 --- a/dScripts/NsGetFactionMissionServer.cpp +++ b/dScripts/NsGetFactionMissionServer.cpp @@ -3,8 +3,7 @@ #include "MissionComponent.h" #include "Character.h" -void NsGetFactionMissionServer::OnRespondToMission(Entity* self, int missionID, Entity* player, int reward) -{ +void NsGetFactionMissionServer::OnRespondToMission(Entity* self, int missionID, Entity* player, int reward) { if (missionID != 474) return; if (reward != LOT_NULL) { @@ -17,20 +16,17 @@ void NsGetFactionMissionServer::OnRespondToMission(Entity* self, int missionID, factionMissions = { 555, 556 }; celebrationID = 14; flagID = 46; - } - else if (reward == 6979) { + } else if (reward == 6979) { // Assembly factionMissions = { 544, 545 }; celebrationID = 15; flagID = 47; - } - else if (reward == 6981) { + } else if (reward == 6981) { // Paradox factionMissions = { 577, 578 }; celebrationID = 16; flagID = 48; - } - else if (reward == 6978) { + } else if (reward == 6978) { // Sentinel factionMissions = { 566, 567 }; celebrationID = 17; diff --git a/dScripts/NsJohnnyMissionServer.cpp b/dScripts/NsJohnnyMissionServer.cpp index 6fc73a82..2d9ae93c 100644 --- a/dScripts/NsJohnnyMissionServer.cpp +++ b/dScripts/NsJohnnyMissionServer.cpp @@ -1,14 +1,14 @@ #include "NsJohnnyMissionServer.h" #include "MissionComponent.h" -void NsJohnnyMissionServer::OnMissionDialogueOK(Entity *self, Entity *target, int missionID, MissionState missionState) { - if (missionID == 773 && missionState <= MissionState::MISSION_STATE_ACTIVE) { - auto* missionComponent = target->GetComponent(); - if (missionComponent != nullptr) { - missionComponent->AcceptMission(774); - missionComponent->AcceptMission(775); - missionComponent->AcceptMission(776); - missionComponent->AcceptMission(777); - } - } +void NsJohnnyMissionServer::OnMissionDialogueOK(Entity* self, Entity* target, int missionID, MissionState missionState) { + if (missionID == 773 && missionState <= MissionState::MISSION_STATE_ACTIVE) { + auto* missionComponent = target->GetComponent(); + if (missionComponent != nullptr) { + missionComponent->AcceptMission(774); + missionComponent->AcceptMission(775); + missionComponent->AcceptMission(776); + missionComponent->AcceptMission(777); + } + } } diff --git a/dScripts/NsJohnnyMissionServer.h b/dScripts/NsJohnnyMissionServer.h index 920231da..8de39afa 100644 --- a/dScripts/NsJohnnyMissionServer.h +++ b/dScripts/NsJohnnyMissionServer.h @@ -2,5 +2,5 @@ #include "CppScripts.h" class NsJohnnyMissionServer : public CppScripts::Script { - void OnMissionDialogueOK(Entity *self, Entity *target, int missionID, MissionState missionState) override; + void OnMissionDialogueOK(Entity* self, Entity* target, int missionID, MissionState missionState) override; }; diff --git a/dScripts/NsLegoClubDoor.cpp b/dScripts/NsLegoClubDoor.cpp index 0a73c6d0..56a213b8 100644 --- a/dScripts/NsLegoClubDoor.cpp +++ b/dScripts/NsLegoClubDoor.cpp @@ -3,162 +3,150 @@ #include "GameMessages.h" #include "AMFFormat.h" -void NsLegoClubDoor::OnStartup(Entity* self) -{ - self->SetVar(u"currentZone", (int32_t) dZoneManager::Instance()->GetZoneID().GetMapID()); - self->SetVar(u"choiceZone", m_ChoiceZoneID); - self->SetVar(u"teleportAnim", m_TeleportAnim); - self->SetVar(u"teleportString", m_TeleportString); - self->SetVar(u"spawnPoint", m_SpawnPoint); +void NsLegoClubDoor::OnStartup(Entity* self) { + self->SetVar(u"currentZone", (int32_t)dZoneManager::Instance()->GetZoneID().GetMapID()); + self->SetVar(u"choiceZone", m_ChoiceZoneID); + self->SetVar(u"teleportAnim", m_TeleportAnim); + self->SetVar(u"teleportString", m_TeleportString); + self->SetVar(u"spawnPoint", m_SpawnPoint); - args = {}; + args = {}; - AMFStringValue* callbackClient = new AMFStringValue(); - callbackClient->SetStringValue(std::to_string(self->GetObjectID())); - args.InsertValue("callbackClient", callbackClient); + AMFStringValue* callbackClient = new AMFStringValue(); + callbackClient->SetStringValue(std::to_string(self->GetObjectID())); + args.InsertValue("callbackClient", callbackClient); - AMFStringValue* strIdentifier = new AMFStringValue(); - strIdentifier->SetStringValue("choiceDoor"); - args.InsertValue("strIdentifier", strIdentifier); + AMFStringValue* strIdentifier = new AMFStringValue(); + strIdentifier->SetStringValue("choiceDoor"); + args.InsertValue("strIdentifier", strIdentifier); - AMFStringValue* title = new AMFStringValue(); - title->SetStringValue("%[UI_CHOICE_DESTINATION]"); - args.InsertValue("title", title); + AMFStringValue* title = new AMFStringValue(); + title->SetStringValue("%[UI_CHOICE_DESTINATION]"); + args.InsertValue("title", title); - AMFArrayValue* choiceOptions = new AMFArrayValue(); + AMFArrayValue* choiceOptions = new AMFArrayValue(); - { - AMFArrayValue* nsArgs = new AMFArrayValue(); + { + AMFArrayValue* nsArgs = new AMFArrayValue(); - AMFStringValue* image = new AMFStringValue(); - image->SetStringValue("textures/ui/zone_thumnails/Nimbus_Station.dds"); - nsArgs->InsertValue("image", image); + AMFStringValue* image = new AMFStringValue(); + image->SetStringValue("textures/ui/zone_thumnails/Nimbus_Station.dds"); + nsArgs->InsertValue("image", image); - AMFStringValue* caption = new AMFStringValue(); - caption->SetStringValue("%[UI_CHOICE_NS]"); - nsArgs->InsertValue("caption", caption); + AMFStringValue* caption = new AMFStringValue(); + caption->SetStringValue("%[UI_CHOICE_NS]"); + nsArgs->InsertValue("caption", caption); - AMFStringValue* identifier = new AMFStringValue(); - identifier->SetStringValue("zoneID_1200"); - nsArgs->InsertValue("identifier", identifier); + AMFStringValue* identifier = new AMFStringValue(); + identifier->SetStringValue("zoneID_1200"); + nsArgs->InsertValue("identifier", identifier); - AMFStringValue* tooltipText = new AMFStringValue(); - tooltipText->SetStringValue("%[UI_CHOICE_NS_HOVER]"); - nsArgs->InsertValue("tooltipText", tooltipText); + AMFStringValue* tooltipText = new AMFStringValue(); + tooltipText->SetStringValue("%[UI_CHOICE_NS_HOVER]"); + nsArgs->InsertValue("tooltipText", tooltipText); - choiceOptions->PushBackValue(nsArgs); - } + choiceOptions->PushBackValue(nsArgs); + } - { - AMFArrayValue* ntArgs = new AMFArrayValue(); + { + AMFArrayValue* ntArgs = new AMFArrayValue(); - AMFStringValue* image = new AMFStringValue(); - image->SetStringValue("textures/ui/zone_thumnails/Nexus_Tower.dds"); - ntArgs->InsertValue("image", image); + AMFStringValue* image = new AMFStringValue(); + image->SetStringValue("textures/ui/zone_thumnails/Nexus_Tower.dds"); + ntArgs->InsertValue("image", image); - AMFStringValue* caption = new AMFStringValue(); - caption->SetStringValue("%[UI_CHOICE_NT]"); - ntArgs->InsertValue("caption", caption); + AMFStringValue* caption = new AMFStringValue(); + caption->SetStringValue("%[UI_CHOICE_NT]"); + ntArgs->InsertValue("caption", caption); - AMFStringValue* identifier = new AMFStringValue(); - identifier->SetStringValue("zoneID_1900"); - ntArgs->InsertValue("identifier", identifier); + AMFStringValue* identifier = new AMFStringValue(); + identifier->SetStringValue("zoneID_1900"); + ntArgs->InsertValue("identifier", identifier); - AMFStringValue* tooltipText = new AMFStringValue(); - tooltipText->SetStringValue("%[UI_CHOICE_NT_HOVER]"); - ntArgs->InsertValue("tooltipText", tooltipText); + AMFStringValue* tooltipText = new AMFStringValue(); + tooltipText->SetStringValue("%[UI_CHOICE_NT_HOVER]"); + ntArgs->InsertValue("tooltipText", tooltipText); - choiceOptions->PushBackValue(ntArgs); - } + choiceOptions->PushBackValue(ntArgs); + } - options = choiceOptions; + options = choiceOptions; - args.InsertValue("options", choiceOptions); + args.InsertValue("options", choiceOptions); } -void NsLegoClubDoor::OnUse(Entity* self, Entity* user) -{ - auto* player = user; +void NsLegoClubDoor::OnUse(Entity* self, Entity* user) { + auto* player = user; - if (CheckChoice(self, player)) - { - AMFArrayValue* multiArgs = new AMFArrayValue(); - - AMFStringValue* callbackClient = new AMFStringValue(); - callbackClient->SetStringValue(std::to_string(self->GetObjectID())); - multiArgs->InsertValue("callbackClient", callbackClient); + if (CheckChoice(self, player)) { + AMFArrayValue* multiArgs = new AMFArrayValue(); - AMFStringValue* strIdentifier = new AMFStringValue(); - strIdentifier->SetStringValue("choiceDoor"); - multiArgs->InsertValue("strIdentifier", strIdentifier); + AMFStringValue* callbackClient = new AMFStringValue(); + callbackClient->SetStringValue(std::to_string(self->GetObjectID())); + multiArgs->InsertValue("callbackClient", callbackClient); - AMFStringValue* title = new AMFStringValue(); - title->SetStringValue("%[UI_CHOICE_DESTINATION]"); - multiArgs->InsertValue("title", title); + AMFStringValue* strIdentifier = new AMFStringValue(); + strIdentifier->SetStringValue("choiceDoor"); + multiArgs->InsertValue("strIdentifier", strIdentifier); - multiArgs->InsertValue("options", options); + AMFStringValue* title = new AMFStringValue(); + title->SetStringValue("%[UI_CHOICE_DESTINATION]"); + multiArgs->InsertValue("title", title); - GameMessages::SendUIMessageServerToSingleClient(player, player->GetSystemAddress(), "QueueChoiceBox", multiArgs); - } - else if (self->GetVar(u"currentZone") != m_ChoiceZoneID) - { - AMFArrayValue* multiArgs = new AMFArrayValue(); + multiArgs->InsertValue("options", options); - AMFStringValue* state = new AMFStringValue(); - state->SetStringValue("Lobby"); - multiArgs->InsertValue("state", state); + GameMessages::SendUIMessageServerToSingleClient(player, player->GetSystemAddress(), "QueueChoiceBox", multiArgs); + } else if (self->GetVar(u"currentZone") != m_ChoiceZoneID) { + AMFArrayValue* multiArgs = new AMFArrayValue(); - AMFArrayValue* context = new AMFArrayValue(); + AMFStringValue* state = new AMFStringValue(); + state->SetStringValue("Lobby"); + multiArgs->InsertValue("state", state); - AMFStringValue* user = new AMFStringValue(); - user->SetStringValue(std::to_string(player->GetObjectID())); - context->InsertValue("user", user); + AMFArrayValue* context = new AMFArrayValue(); - AMFStringValue* callbackObj = new AMFStringValue(); - callbackObj->SetStringValue(std::to_string(self->GetObjectID())); - context->InsertValue("callbackObj", callbackObj); + AMFStringValue* user = new AMFStringValue(); + user->SetStringValue(std::to_string(player->GetObjectID())); + context->InsertValue("user", user); - AMFStringValue* helpVisible = new AMFStringValue(); - helpVisible->SetStringValue("show"); - context->InsertValue("HelpVisible", helpVisible); + AMFStringValue* callbackObj = new AMFStringValue(); + callbackObj->SetStringValue(std::to_string(self->GetObjectID())); + context->InsertValue("callbackObj", callbackObj); - AMFStringValue* type = new AMFStringValue(); - type->SetStringValue("Lego_Club_Valid"); - context->InsertValue("type", type); + AMFStringValue* helpVisible = new AMFStringValue(); + helpVisible->SetStringValue("show"); + context->InsertValue("HelpVisible", helpVisible); - multiArgs->InsertValue("context", context); + AMFStringValue* type = new AMFStringValue(); + type->SetStringValue("Lego_Club_Valid"); + context->InsertValue("type", type); - GameMessages::SendUIMessageServerToSingleClient(player, player->GetSystemAddress(), "pushGameState", multiArgs); - } - else - { - BaseOnUse(self, player); - } + multiArgs->InsertValue("context", context); + + GameMessages::SendUIMessageServerToSingleClient(player, player->GetSystemAddress(), "pushGameState", multiArgs); + } else { + BaseOnUse(self, player); + } } -void NsLegoClubDoor::OnMessageBoxResponse(Entity* self, Entity* sender, int32_t button, const std::u16string& identifier, const std::u16string& userData) -{ - std::u16string strIdentifier = identifier; +void NsLegoClubDoor::OnMessageBoxResponse(Entity* self, Entity* sender, int32_t button, const std::u16string& identifier, const std::u16string& userData) { + std::u16string strIdentifier = identifier; - if (strIdentifier == u"PlayButton" || strIdentifier == u"CloseButton") - { - strIdentifier = u"TransferBox"; - } + if (strIdentifier == u"PlayButton" || strIdentifier == u"CloseButton") { + strIdentifier = u"TransferBox"; + } - BaseOnMessageBoxResponse(self, sender, button, strIdentifier, userData); + BaseOnMessageBoxResponse(self, sender, button, strIdentifier, userData); } -void NsLegoClubDoor::OnChoiceBoxResponse(Entity* self, Entity* sender, int32_t button, const std::u16string& buttonIdentifier, const std::u16string& identifier) -{ - BaseChoiceBoxRespond(self, sender, button, buttonIdentifier, identifier); +void NsLegoClubDoor::OnChoiceBoxResponse(Entity* self, Entity* sender, int32_t button, const std::u16string& buttonIdentifier, const std::u16string& identifier) { + BaseChoiceBoxRespond(self, sender, button, buttonIdentifier, identifier); } -void NsLegoClubDoor::OnTimerDone(Entity* self, std::string timerName) -{ - BaseOnTimerDone(self, timerName); +void NsLegoClubDoor::OnTimerDone(Entity* self, std::string timerName) { + BaseOnTimerDone(self, timerName); } -void NsLegoClubDoor::OnFireEventServerSide(Entity *self, Entity *sender, std::string args, int32_t param1, int32_t param2, int32_t param3) -{ - BaseOnFireEventServerSide(self, sender, args, param1, param2, param3); +void NsLegoClubDoor::OnFireEventServerSide(Entity* self, Entity* sender, std::string args, int32_t param1, int32_t param2, int32_t param3) { + BaseOnFireEventServerSide(self, sender, args, param1, param2, param3); } diff --git a/dScripts/NsLegoClubDoor.h b/dScripts/NsLegoClubDoor.h index 7f17692d..0a7a6ee0 100644 --- a/dScripts/NsLegoClubDoor.h +++ b/dScripts/NsLegoClubDoor.h @@ -6,18 +6,18 @@ class NsLegoClubDoor : public CppScripts::Script, ChooseYourDestinationNsToNt, BaseConsoleTeleportServer { public: - void OnStartup(Entity* self) override; - void OnUse(Entity* self, Entity* user) override; - void OnMessageBoxResponse(Entity* self, Entity* sender, int32_t button, const std::u16string& identifier, const std::u16string& userData) override; - void OnChoiceBoxResponse(Entity* self, Entity* sender, int32_t button, const std::u16string& buttonIdentifier, const std::u16string& identifier) override; - void OnTimerDone(Entity* self, std::string timerName) override; - void OnFireEventServerSide(Entity *self, Entity *sender, std::string args, int32_t param1, int32_t param2, int32_t param3) override; + void OnStartup(Entity* self) override; + void OnUse(Entity* self, Entity* user) override; + void OnMessageBoxResponse(Entity* self, Entity* sender, int32_t button, const std::u16string& identifier, const std::u16string& userData) override; + void OnChoiceBoxResponse(Entity* self, Entity* sender, int32_t button, const std::u16string& buttonIdentifier, const std::u16string& identifier) override; + void OnTimerDone(Entity* self, std::string timerName) override; + void OnFireEventServerSide(Entity* self, Entity* sender, std::string args, int32_t param1, int32_t param2, int32_t param3) override; private: - int32_t m_ChoiceZoneID = 1700; - std::string m_SpawnPoint = "NS_LEGO_Club"; - std::u16string m_TeleportAnim = u"lup-teleport"; - std::u16string m_TeleportString = u"ROCKET_TOOLTIP_USE_THE_GATEWAY_TO_TRAVEL_TO_LUP_WORLD"; - AMFArrayValue args = {}; - AMFArrayValue* options = {}; + int32_t m_ChoiceZoneID = 1700; + std::string m_SpawnPoint = "NS_LEGO_Club"; + std::u16string m_TeleportAnim = u"lup-teleport"; + std::u16string m_TeleportString = u"ROCKET_TOOLTIP_USE_THE_GATEWAY_TO_TRAVEL_TO_LUP_WORLD"; + AMFArrayValue args = {}; + AMFArrayValue* options = {}; }; diff --git a/dScripts/NsLupTeleport.cpp b/dScripts/NsLupTeleport.cpp index 4c196d01..9cd4359b 100644 --- a/dScripts/NsLupTeleport.cpp +++ b/dScripts/NsLupTeleport.cpp @@ -3,107 +3,98 @@ #include "GameMessages.h" #include "AMFFormat.h" -void NsLupTeleport::OnStartup(Entity* self) -{ - self->SetVar(u"currentZone", (int32_t) dZoneManager::Instance()->GetZoneID().GetMapID()); - self->SetVar(u"choiceZone", m_ChoiceZoneID); - self->SetVar(u"teleportAnim", m_TeleportAnim); - self->SetVar(u"teleportString", m_TeleportString); - self->SetVar(u"spawnPoint", m_SpawnPoint); +void NsLupTeleport::OnStartup(Entity* self) { + self->SetVar(u"currentZone", (int32_t)dZoneManager::Instance()->GetZoneID().GetMapID()); + self->SetVar(u"choiceZone", m_ChoiceZoneID); + self->SetVar(u"teleportAnim", m_TeleportAnim); + self->SetVar(u"teleportString", m_TeleportString); + self->SetVar(u"spawnPoint", m_SpawnPoint); - args = {}; + args = {}; - AMFStringValue* callbackClient = new AMFStringValue(); - callbackClient->SetStringValue(std::to_string(self->GetObjectID())); - args.InsertValue("callbackClient", callbackClient); + AMFStringValue* callbackClient = new AMFStringValue(); + callbackClient->SetStringValue(std::to_string(self->GetObjectID())); + args.InsertValue("callbackClient", callbackClient); - AMFStringValue* strIdentifier = new AMFStringValue(); - strIdentifier->SetStringValue("choiceDoor"); - args.InsertValue("strIdentifier", strIdentifier); + AMFStringValue* strIdentifier = new AMFStringValue(); + strIdentifier->SetStringValue("choiceDoor"); + args.InsertValue("strIdentifier", strIdentifier); - AMFStringValue* title = new AMFStringValue(); - title->SetStringValue("%[UI_CHOICE_DESTINATION]"); - args.InsertValue("title", title); + AMFStringValue* title = new AMFStringValue(); + title->SetStringValue("%[UI_CHOICE_DESTINATION]"); + args.InsertValue("title", title); - AMFArrayValue* choiceOptions = new AMFArrayValue(); + AMFArrayValue* choiceOptions = new AMFArrayValue(); - { - AMFArrayValue* nsArgs = new AMFArrayValue(); + { + AMFArrayValue* nsArgs = new AMFArrayValue(); - AMFStringValue* image = new AMFStringValue(); - image->SetStringValue("textures/ui/zone_thumnails/Nimbus_Station.dds"); - nsArgs->InsertValue("image", image); + AMFStringValue* image = new AMFStringValue(); + image->SetStringValue("textures/ui/zone_thumnails/Nimbus_Station.dds"); + nsArgs->InsertValue("image", image); - AMFStringValue* caption = new AMFStringValue(); - caption->SetStringValue("%[UI_CHOICE_NS]"); - nsArgs->InsertValue("caption", caption); + AMFStringValue* caption = new AMFStringValue(); + caption->SetStringValue("%[UI_CHOICE_NS]"); + nsArgs->InsertValue("caption", caption); - AMFStringValue* identifier = new AMFStringValue(); - identifier->SetStringValue("zoneID_1200"); - nsArgs->InsertValue("identifier", identifier); + AMFStringValue* identifier = new AMFStringValue(); + identifier->SetStringValue("zoneID_1200"); + nsArgs->InsertValue("identifier", identifier); - AMFStringValue* tooltipText = new AMFStringValue(); - tooltipText->SetStringValue("%[UI_CHOICE_NS_HOVER]"); - nsArgs->InsertValue("tooltipText", tooltipText); + AMFStringValue* tooltipText = new AMFStringValue(); + tooltipText->SetStringValue("%[UI_CHOICE_NS_HOVER]"); + nsArgs->InsertValue("tooltipText", tooltipText); - choiceOptions->PushBackValue(nsArgs); - } + choiceOptions->PushBackValue(nsArgs); + } - { - AMFArrayValue* ntArgs = new AMFArrayValue(); + { + AMFArrayValue* ntArgs = new AMFArrayValue(); - AMFStringValue* image = new AMFStringValue(); - image->SetStringValue("textures/ui/zone_thumnails/Nexus_Tower.dds"); - ntArgs->InsertValue("image", image); + AMFStringValue* image = new AMFStringValue(); + image->SetStringValue("textures/ui/zone_thumnails/Nexus_Tower.dds"); + ntArgs->InsertValue("image", image); - AMFStringValue* caption = new AMFStringValue(); - caption->SetStringValue("%[UI_CHOICE_NT]"); - ntArgs->InsertValue("caption", caption); + AMFStringValue* caption = new AMFStringValue(); + caption->SetStringValue("%[UI_CHOICE_NT]"); + ntArgs->InsertValue("caption", caption); - AMFStringValue* identifier = new AMFStringValue(); - identifier->SetStringValue("zoneID_1900"); - ntArgs->InsertValue("identifier", identifier); + AMFStringValue* identifier = new AMFStringValue(); + identifier->SetStringValue("zoneID_1900"); + ntArgs->InsertValue("identifier", identifier); - AMFStringValue* tooltipText = new AMFStringValue(); - tooltipText->SetStringValue("%[UI_CHOICE_NT_HOVER]"); - ntArgs->InsertValue("tooltipText", tooltipText); + AMFStringValue* tooltipText = new AMFStringValue(); + tooltipText->SetStringValue("%[UI_CHOICE_NT_HOVER]"); + ntArgs->InsertValue("tooltipText", tooltipText); - choiceOptions->PushBackValue(ntArgs); - } + choiceOptions->PushBackValue(ntArgs); + } - args.InsertValue("options", choiceOptions); + args.InsertValue("options", choiceOptions); } -void NsLupTeleport::OnUse(Entity* self, Entity* user) -{ - auto* player = user; +void NsLupTeleport::OnUse(Entity* self, Entity* user) { + auto* player = user; - if (CheckChoice(self, player)) - { - GameMessages::SendUIMessageServerToSingleClient(player, player->GetSystemAddress(), "QueueChoiceBox", &args); - } - else - { - BaseOnUse(self, player); - } + if (CheckChoice(self, player)) { + GameMessages::SendUIMessageServerToSingleClient(player, player->GetSystemAddress(), "QueueChoiceBox", &args); + } else { + BaseOnUse(self, player); + } } -void NsLupTeleport::OnMessageBoxResponse(Entity* self, Entity* sender, int32_t button, const std::u16string& identifier, const std::u16string& userData) -{ - BaseOnMessageBoxResponse(self, sender, button, identifier, userData); +void NsLupTeleport::OnMessageBoxResponse(Entity* self, Entity* sender, int32_t button, const std::u16string& identifier, const std::u16string& userData) { + BaseOnMessageBoxResponse(self, sender, button, identifier, userData); } -void NsLupTeleport::OnChoiceBoxResponse(Entity* self, Entity* sender, int32_t button, const std::u16string& buttonIdentifier, const std::u16string& identifier) -{ - BaseChoiceBoxRespond(self, sender, button, buttonIdentifier, identifier); +void NsLupTeleport::OnChoiceBoxResponse(Entity* self, Entity* sender, int32_t button, const std::u16string& buttonIdentifier, const std::u16string& identifier) { + BaseChoiceBoxRespond(self, sender, button, buttonIdentifier, identifier); } -void NsLupTeleport::OnTimerDone(Entity* self, std::string timerName) -{ - BaseOnTimerDone(self, timerName); +void NsLupTeleport::OnTimerDone(Entity* self, std::string timerName) { + BaseOnTimerDone(self, timerName); } -void NsLupTeleport::OnFireEventServerSide(Entity *self, Entity *sender, std::string args, int32_t param1, int32_t param2, int32_t param3) -{ - BaseOnFireEventServerSide(self, sender, args, param1, param2, param3); +void NsLupTeleport::OnFireEventServerSide(Entity* self, Entity* sender, std::string args, int32_t param1, int32_t param2, int32_t param3) { + BaseOnFireEventServerSide(self, sender, args, param1, param2, param3); } diff --git a/dScripts/NsLupTeleport.h b/dScripts/NsLupTeleport.h index 833f5f0a..35edf0bc 100644 --- a/dScripts/NsLupTeleport.h +++ b/dScripts/NsLupTeleport.h @@ -6,17 +6,17 @@ class NsLupTeleport : public CppScripts::Script, ChooseYourDestinationNsToNt, BaseConsoleTeleportServer { public: - void OnStartup(Entity* self) override; - void OnUse(Entity* self, Entity* user) override; - void OnMessageBoxResponse(Entity* self, Entity* sender, int32_t button, const std::u16string& identifier, const std::u16string& userData) override; - void OnChoiceBoxResponse(Entity* self, Entity* sender, int32_t button, const std::u16string& buttonIdentifier, const std::u16string& identifier) override; - void OnTimerDone(Entity* self, std::string timerName) override; - void OnFireEventServerSide(Entity *self, Entity *sender, std::string args, int32_t param1, int32_t param2, int32_t param3) override; + void OnStartup(Entity* self) override; + void OnUse(Entity* self, Entity* user) override; + void OnMessageBoxResponse(Entity* self, Entity* sender, int32_t button, const std::u16string& identifier, const std::u16string& userData) override; + void OnChoiceBoxResponse(Entity* self, Entity* sender, int32_t button, const std::u16string& buttonIdentifier, const std::u16string& identifier) override; + void OnTimerDone(Entity* self, std::string timerName) override; + void OnFireEventServerSide(Entity* self, Entity* sender, std::string args, int32_t param1, int32_t param2, int32_t param3) override; private: - int32_t m_ChoiceZoneID = 1600; - std::string m_SpawnPoint = "NS_LW"; - std::u16string m_TeleportAnim = u"lup-teleport"; - std::u16string m_TeleportString = u"UI_TRAVEL_TO_LUP_STATION"; - AMFArrayValue args = {}; + int32_t m_ChoiceZoneID = 1600; + std::string m_SpawnPoint = "NS_LW"; + std::u16string m_TeleportAnim = u"lup-teleport"; + std::u16string m_TeleportString = u"UI_TRAVEL_TO_LUP_STATION"; + AMFArrayValue args = {}; }; diff --git a/dScripts/NsQbImaginationStatue.cpp b/dScripts/NsQbImaginationStatue.cpp index 4404ba5f..a2e335b7 100644 --- a/dScripts/NsQbImaginationStatue.cpp +++ b/dScripts/NsQbImaginationStatue.cpp @@ -2,46 +2,39 @@ #include "EntityManager.h" #include "GameMessages.h" -void NsQbImaginationStatue::OnStartup(Entity* self) -{ - +void NsQbImaginationStatue::OnStartup(Entity* self) { + } -void NsQbImaginationStatue::OnRebuildComplete(Entity* self, Entity* target) -{ - if (target == nullptr) return; +void NsQbImaginationStatue::OnRebuildComplete(Entity* self, Entity* target) { + if (target == nullptr) return; - self->SetVar(u"Player", target->GetObjectID()); + self->SetVar(u"Player", target->GetObjectID()); - SpawnLoot(self); - - self->AddTimer("SpawnDelay", 1.5f); + SpawnLoot(self); - self->AddTimer("StopSpawner", 10.0f); + self->AddTimer("SpawnDelay", 1.5f); + + self->AddTimer("StopSpawner", 10.0f); } -void NsQbImaginationStatue::OnTimerDone(Entity* self, std::string timerName) -{ - if (timerName == "SpawnDelay") - { - SpawnLoot(self); +void NsQbImaginationStatue::OnTimerDone(Entity* self, std::string timerName) { + if (timerName == "SpawnDelay") { + SpawnLoot(self); - self->AddTimer("SpawnDelay", 1.5f); - } - else if (timerName == "StopSpawner") - { - self->CancelAllTimers(); - } + self->AddTimer("SpawnDelay", 1.5f); + } else if (timerName == "StopSpawner") { + self->CancelAllTimers(); + } } -void NsQbImaginationStatue::SpawnLoot(Entity* self) -{ - const auto playerId = self->GetVar(u"Player"); +void NsQbImaginationStatue::SpawnLoot(Entity* self) { + const auto playerId = self->GetVar(u"Player"); - auto* player = EntityManager::Instance()->GetEntity(playerId); + auto* player = EntityManager::Instance()->GetEntity(playerId); - if (player == nullptr) return; - - GameMessages::SendDropClientLoot(player, self->GetObjectID(), 935, 0); - GameMessages::SendDropClientLoot(player, self->GetObjectID(), 935, 0); + if (player == nullptr) return; + + GameMessages::SendDropClientLoot(player, self->GetObjectID(), 935, 0); + GameMessages::SendDropClientLoot(player, self->GetObjectID(), 935, 0); } diff --git a/dScripts/NsQbImaginationStatue.h b/dScripts/NsQbImaginationStatue.h index 3d699ac9..b7a78c32 100644 --- a/dScripts/NsQbImaginationStatue.h +++ b/dScripts/NsQbImaginationStatue.h @@ -5,7 +5,7 @@ class NsQbImaginationStatue : public CppScripts::Script { public: void OnStartup(Entity* self) override; - void OnRebuildComplete(Entity* self, Entity* target) override; - void OnTimerDone(Entity* self, std::string timerName) override; - void SpawnLoot(Entity* self); + void OnRebuildComplete(Entity* self, Entity* target) override; + void OnTimerDone(Entity* self, std::string timerName) override; + void SpawnLoot(Entity* self); }; diff --git a/dScripts/NsTokenConsoleServer.cpp b/dScripts/NsTokenConsoleServer.cpp index 976b9bc8..a62c165c 100644 --- a/dScripts/NsTokenConsoleServer.cpp +++ b/dScripts/NsTokenConsoleServer.cpp @@ -5,71 +5,57 @@ #include "MissionComponent.h" #include "RebuildComponent.h" -void NsTokenConsoleServer::OnStartup(Entity* self) -{ - +void NsTokenConsoleServer::OnStartup(Entity* self) { + } -void NsTokenConsoleServer::OnUse(Entity* self, Entity* user) -{ - auto* rebuildComponent = self->GetComponent(); +void NsTokenConsoleServer::OnUse(Entity* self, Entity* user) { + auto* rebuildComponent = self->GetComponent(); - if (rebuildComponent == nullptr) - { - return; - } + if (rebuildComponent == nullptr) { + return; + } - if (rebuildComponent->GetState() != REBUILD_COMPLETED) - { - return; - } + if (rebuildComponent->GetState() != REBUILD_COMPLETED) { + return; + } - auto* inventoryComponent = user->GetComponent(); - auto* missionComponent = user->GetComponent(); - auto* character = user->GetCharacter(); + auto* inventoryComponent = user->GetComponent(); + auto* missionComponent = user->GetComponent(); + auto* character = user->GetCharacter(); - if (inventoryComponent == nullptr || missionComponent == nullptr || character == nullptr) - { - return; - } + if (inventoryComponent == nullptr || missionComponent == nullptr || character == nullptr) { + return; + } - if (inventoryComponent->GetLotCount(6194) < 25) - { - return; - } + if (inventoryComponent->GetLotCount(6194) < 25) { + return; + } - inventoryComponent->RemoveItem(6194, 25); + inventoryComponent->RemoveItem(6194, 25); - const auto useSound = self->GetVar(u"sound1"); + const auto useSound = self->GetVar(u"sound1"); - if (!useSound.empty()) - { - GameMessages::SendPlayNDAudioEmitter(self, UNASSIGNED_SYSTEM_ADDRESS, useSound); - } - - // Player must be in faction to interact with this entity. - LOT tokenLOT = 0; + if (!useSound.empty()) { + GameMessages::SendPlayNDAudioEmitter(self, UNASSIGNED_SYSTEM_ADDRESS, useSound); + } - if (character->GetPlayerFlag(46)) - { - tokenLOT = 8321; - } - else if (character->GetPlayerFlag(47)) - { - tokenLOT = 8318; - } - else if (character->GetPlayerFlag(48)) - { - tokenLOT = 8320; - } - else if (character->GetPlayerFlag(49)) - { - tokenLOT = 8319; - } + // Player must be in faction to interact with this entity. + LOT tokenLOT = 0; - inventoryComponent->AddItem(tokenLOT, 5, eLootSourceType::LOOT_SOURCE_NONE); + if (character->GetPlayerFlag(46)) { + tokenLOT = 8321; + } else if (character->GetPlayerFlag(47)) { + tokenLOT = 8318; + } else if (character->GetPlayerFlag(48)) { + tokenLOT = 8320; + } else if (character->GetPlayerFlag(49)) { + tokenLOT = 8319; + } - missionComponent->ForceProgressTaskType(863, 1, 1, false); - - GameMessages::SendTerminateInteraction(user->GetObjectID(), FROM_INTERACTION, self->GetObjectID()); + inventoryComponent->AddItem(tokenLOT, 5, eLootSourceType::LOOT_SOURCE_NONE); + + missionComponent->ForceProgressTaskType(863, 1, 1, false); + + GameMessages::SendTerminateInteraction(user->GetObjectID(), FROM_INTERACTION, self->GetObjectID()); } diff --git a/dScripts/NsTokenConsoleServer.h b/dScripts/NsTokenConsoleServer.h index d0cdb011..364cb714 100644 --- a/dScripts/NsTokenConsoleServer.h +++ b/dScripts/NsTokenConsoleServer.h @@ -5,5 +5,5 @@ class NsTokenConsoleServer : public CppScripts::Script { public: void OnStartup(Entity* self) override; - void OnUse(Entity* self, Entity* user) override; + void OnUse(Entity* self, Entity* user) override; }; diff --git a/dScripts/NtAssemblyTubeServer.cpp b/dScripts/NtAssemblyTubeServer.cpp index 935993f4..f30f4fc7 100644 --- a/dScripts/NtAssemblyTubeServer.cpp +++ b/dScripts/NtAssemblyTubeServer.cpp @@ -3,126 +3,112 @@ #include "EntityManager.h" #include "MissionComponent.h" -void NtAssemblyTubeServer::OnStartup(Entity* self) -{ - self->SetProximityRadius(5, "teleport"); +void NtAssemblyTubeServer::OnStartup(Entity* self) { + self->SetProximityRadius(5, "teleport"); } -void NtAssemblyTubeServer::OnPlayerLoaded(Entity* self, Entity* player) -{ - +void NtAssemblyTubeServer::OnPlayerLoaded(Entity* self, Entity* player) { + } -void NtAssemblyTubeServer::OnProximityUpdate(Entity* self, Entity* entering, std::string name, std::string status) -{ - if (status != "ENTER" || !entering->IsPlayer() || name != "teleport") return; +void NtAssemblyTubeServer::OnProximityUpdate(Entity* self, Entity* entering, std::string name, std::string status) { + if (status != "ENTER" || !entering->IsPlayer() || name != "teleport") return; - auto* player = entering; - const auto playerID = player->GetObjectID(); + auto* player = entering; + const auto playerID = player->GetObjectID(); - RunAssemblyTube(self, player); + RunAssemblyTube(self, player); - auto* missionComponent = player->GetComponent(); + auto* missionComponent = player->GetComponent(); - if (missionComponent != nullptr) - { - missionComponent->Progress(MissionTaskType::MISSION_TASK_TYPE_SCRIPT, self->GetLOT()); - } + if (missionComponent != nullptr) { + missionComponent->Progress(MissionTaskType::MISSION_TASK_TYPE_SCRIPT, self->GetLOT()); + } } -void NtAssemblyTubeServer::RunAssemblyTube(Entity* self, Entity* player) -{ - const auto playerID = player->GetObjectID(); - - const auto iter = m_TeleportingPlayerTable.find(playerID); - if (iter == m_TeleportingPlayerTable.end()) m_TeleportingPlayerTable[playerID] = false; - const auto bPlayerBeingTeleported = m_TeleportingPlayerTable[playerID]; +void NtAssemblyTubeServer::RunAssemblyTube(Entity* self, Entity* player) { + const auto playerID = player->GetObjectID(); - if (player->IsPlayer() && !bPlayerBeingTeleported) - { - auto teleCinematic = self->GetVar(u"Cinematic"); + const auto iter = m_TeleportingPlayerTable.find(playerID); + if (iter == m_TeleportingPlayerTable.end()) m_TeleportingPlayerTable[playerID] = false; + const auto bPlayerBeingTeleported = m_TeleportingPlayerTable[playerID]; - GameMessages::SendSetStunned(playerID, PUSH, player->GetSystemAddress(), LWOOBJID_EMPTY, - true, true, true, true, true, true, true - ); + if (player->IsPlayer() && !bPlayerBeingTeleported) { + auto teleCinematic = self->GetVar(u"Cinematic"); - if (!teleCinematic.empty()) - { - const auto teleCinematicUname = teleCinematic; - GameMessages::SendPlayCinematic(player->GetObjectID(), teleCinematicUname, player->GetSystemAddress(), - true, true, true, false, 0, false, -1, false, true - ); - } + GameMessages::SendSetStunned(playerID, PUSH, player->GetSystemAddress(), LWOOBJID_EMPTY, + true, true, true, true, true, true, true + ); - GameMessages::SendPlayAnimation(player, u"tube-sucker", 4.0f); + if (!teleCinematic.empty()) { + const auto teleCinematicUname = teleCinematic; + GameMessages::SendPlayCinematic(player->GetObjectID(), teleCinematicUname, player->GetSystemAddress(), + true, true, true, false, 0, false, -1, false, true + ); + } - const auto animTime = 3; + GameMessages::SendPlayAnimation(player, u"tube-sucker", 4.0f); - self->AddCallbackTimer(animTime, [this, self, playerID]() { - auto* player = EntityManager::Instance()->GetEntity(playerID); + const auto animTime = 3; - if (player == nullptr) - { - return; - } + self->AddCallbackTimer(animTime, [this, self, playerID]() { + auto* player = EntityManager::Instance()->GetEntity(playerID); - TeleportPlayer(self, player); - }); - } + if (player == nullptr) { + return; + } + + TeleportPlayer(self, player); + }); + } } -void NtAssemblyTubeServer::TeleportPlayer(Entity* self, Entity* player) -{ - auto destinationGroup = self->GetVar(u"teleGroup"); - auto* destination = self; +void NtAssemblyTubeServer::TeleportPlayer(Entity* self, Entity* player) { + auto destinationGroup = self->GetVar(u"teleGroup"); + auto* destination = self; - if (!destinationGroup.empty()) - { - const auto& groupObjs = EntityManager::Instance()->GetEntitiesInGroup(GeneralUtils::UTF16ToWTF8(destinationGroup)); + if (!destinationGroup.empty()) { + const auto& groupObjs = EntityManager::Instance()->GetEntitiesInGroup(GeneralUtils::UTF16ToWTF8(destinationGroup)); - if (!groupObjs.empty()) - { - destination = groupObjs[0]; - } - } + if (!groupObjs.empty()) { + destination = groupObjs[0]; + } + } - const auto destPosition = destination->GetPosition(); - const auto destRotation = destination->GetRotation(); + const auto destPosition = destination->GetPosition(); + const auto destRotation = destination->GetRotation(); - GameMessages::SendTeleport(player->GetObjectID(), destPosition, destRotation, player->GetSystemAddress(), true); + GameMessages::SendTeleport(player->GetObjectID(), destPosition, destRotation, player->GetSystemAddress(), true); - GameMessages::SendPlayAnimation(player, u"tube-resurrect", 4.0f); + GameMessages::SendPlayAnimation(player, u"tube-resurrect", 4.0f); - const auto animTime = 2; + const auto animTime = 2; - const auto playerID = player->GetObjectID(); - - self->AddCallbackTimer(animTime, [this, self, playerID]() { - auto* player = EntityManager::Instance()->GetEntity(playerID); + const auto playerID = player->GetObjectID(); - if (player == nullptr) - { - return; - } + self->AddCallbackTimer(animTime, [this, self, playerID]() { + auto* player = EntityManager::Instance()->GetEntity(playerID); - UnlockPlayer(self, player); - }); + if (player == nullptr) { + return; + } - const auto useSound = self->GetVar(u"sound1"); + UnlockPlayer(self, player); + }); - if (!useSound.empty()) - { - GameMessages::SendPlayNDAudioEmitter(player, player->GetSystemAddress(), useSound); - } + const auto useSound = self->GetVar(u"sound1"); + + if (!useSound.empty()) { + GameMessages::SendPlayNDAudioEmitter(player, player->GetSystemAddress(), useSound); + } } -void NtAssemblyTubeServer::UnlockPlayer(Entity* self, Entity* player) -{ - const auto playerID = player->GetObjectID(); +void NtAssemblyTubeServer::UnlockPlayer(Entity* self, Entity* player) { + const auto playerID = player->GetObjectID(); - m_TeleportingPlayerTable[playerID] = false; + m_TeleportingPlayerTable[playerID] = false; - GameMessages::SendSetStunned(playerID, POP, player->GetSystemAddress(), LWOOBJID_EMPTY, - true, true, true, true, true, true, true - ); + GameMessages::SendSetStunned(playerID, POP, player->GetSystemAddress(), LWOOBJID_EMPTY, + true, true, true, true, true, true, true + ); } diff --git a/dScripts/NtAssemblyTubeServer.h b/dScripts/NtAssemblyTubeServer.h index 116be068..35dcc6f6 100644 --- a/dScripts/NtAssemblyTubeServer.h +++ b/dScripts/NtAssemblyTubeServer.h @@ -5,12 +5,12 @@ class NtAssemblyTubeServer : public CppScripts::Script { public: void OnStartup(Entity* self) override; - void OnPlayerLoaded(Entity* self, Entity* player) override; - void OnProximityUpdate(Entity* self, Entity* entering, std::string name, std::string status) override; - void RunAssemblyTube(Entity* self, Entity* player); - void TeleportPlayer(Entity* self, Entity* player); - void UnlockPlayer(Entity* self, Entity* player); + void OnPlayerLoaded(Entity* self, Entity* player) override; + void OnProximityUpdate(Entity* self, Entity* entering, std::string name, std::string status) override; + void RunAssemblyTube(Entity* self, Entity* player); + void TeleportPlayer(Entity* self, Entity* player); + void UnlockPlayer(Entity* self, Entity* player); private: - std::map m_TeleportingPlayerTable; + std::map m_TeleportingPlayerTable; }; diff --git a/dScripts/NtBeamImaginationCollectors.cpp b/dScripts/NtBeamImaginationCollectors.cpp index ed756c02..b8036c89 100644 --- a/dScripts/NtBeamImaginationCollectors.cpp +++ b/dScripts/NtBeamImaginationCollectors.cpp @@ -2,33 +2,28 @@ #include "GeneralUtils.h" #include "GameMessages.h" -void NtBeamImaginationCollectors::OnStartup(Entity* self) -{ - self->AddTimer("PlayFX", GetRandomNum()); +void NtBeamImaginationCollectors::OnStartup(Entity* self) { + self->AddTimer("PlayFX", GetRandomNum()); } -int32_t NtBeamImaginationCollectors::GetRandomNum() -{ - int32_t randNum = m_LastRandom; +int32_t NtBeamImaginationCollectors::GetRandomNum() { + int32_t randNum = m_LastRandom; - while (randNum == m_LastRandom) - { - randNum = GeneralUtils::GenerateRandomNumber(m_RandMin, m_RandMax); - } + while (randNum == m_LastRandom) { + randNum = GeneralUtils::GenerateRandomNumber(m_RandMin, m_RandMax); + } - m_LastRandom = randNum; + m_LastRandom = randNum; - return randNum; + return randNum; } -void NtBeamImaginationCollectors::OnTimerDone(Entity* self, std::string timerName) -{ - if (timerName != "PlayFX") - { - return; - } +void NtBeamImaginationCollectors::OnTimerDone(Entity* self, std::string timerName) { + if (timerName != "PlayFX") { + return; + } - GameMessages::SendPlayFXEffect(self->GetObjectID(), -1, m_FxName, "Beam"); - - self->AddTimer("PlayFX", GetRandomNum()); + GameMessages::SendPlayFXEffect(self->GetObjectID(), -1, m_FxName, "Beam"); + + self->AddTimer("PlayFX", GetRandomNum()); } diff --git a/dScripts/NtBeamImaginationCollectors.h b/dScripts/NtBeamImaginationCollectors.h index d494d66c..28424766 100644 --- a/dScripts/NtBeamImaginationCollectors.h +++ b/dScripts/NtBeamImaginationCollectors.h @@ -4,13 +4,13 @@ class NtBeamImaginationCollectors : public CppScripts::Script { public: - void OnStartup(Entity* self) override; - int32_t GetRandomNum(); - void OnTimerDone(Entity* self, std::string timerName) override; + void OnStartup(Entity* self) override; + int32_t GetRandomNum(); + void OnTimerDone(Entity* self, std::string timerName) override; private: - int32_t m_LastRandom = 0; - int32_t m_RandMin = 5; - int32_t m_RandMax = 15; - std::u16string m_FxName = u"beam_collect"; + int32_t m_LastRandom = 0; + int32_t m_RandMin = 5; + int32_t m_RandMax = 15; + std::u16string m_FxName = u"beam_collect"; }; diff --git a/dScripts/NtCombatChallengeDummy.cpp b/dScripts/NtCombatChallengeDummy.cpp index a391e00f..c9cd8f0a 100644 --- a/dScripts/NtCombatChallengeDummy.cpp +++ b/dScripts/NtCombatChallengeDummy.cpp @@ -1,32 +1,26 @@ #include "NtCombatChallengeDummy.h" #include "EntityManager.h" -void NtCombatChallengeDummy::OnDie(Entity* self, Entity* killer) -{ - const auto challengeObjectID = self->GetVar(u"challengeObjectID"); +void NtCombatChallengeDummy::OnDie(Entity* self, Entity* killer) { + const auto challengeObjectID = self->GetVar(u"challengeObjectID"); - auto* challengeObject = EntityManager::Instance()->GetEntity(challengeObjectID); + auto* challengeObject = EntityManager::Instance()->GetEntity(challengeObjectID); - if (challengeObject != nullptr) - { - for (CppScripts::Script* script : CppScripts::GetEntityScripts(challengeObject)) - { - script->OnDie(challengeObject, killer); - } - } + if (challengeObject != nullptr) { + for (CppScripts::Script* script : CppScripts::GetEntityScripts(challengeObject)) { + script->OnDie(challengeObject, killer); + } + } } -void NtCombatChallengeDummy::OnHitOrHealResult(Entity* self, Entity* attacker, int32_t damage) -{ - const auto challengeObjectID = self->GetVar(u"challengeObjectID"); +void NtCombatChallengeDummy::OnHitOrHealResult(Entity* self, Entity* attacker, int32_t damage) { + const auto challengeObjectID = self->GetVar(u"challengeObjectID"); - auto* challengeObject = EntityManager::Instance()->GetEntity(challengeObjectID); + auto* challengeObject = EntityManager::Instance()->GetEntity(challengeObjectID); - if (challengeObject != nullptr) - { - for (CppScripts::Script* script : CppScripts::GetEntityScripts(challengeObject)) - { - script->OnHitOrHealResult(challengeObject, attacker, damage); - } - } + if (challengeObject != nullptr) { + for (CppScripts::Script* script : CppScripts::GetEntityScripts(challengeObject)) { + script->OnHitOrHealResult(challengeObject, attacker, damage); + } + } } diff --git a/dScripts/NtCombatChallengeDummy.h b/dScripts/NtCombatChallengeDummy.h index d9ef8cbd..bf7d4f04 100644 --- a/dScripts/NtCombatChallengeDummy.h +++ b/dScripts/NtCombatChallengeDummy.h @@ -4,6 +4,6 @@ class NtCombatChallengeDummy : public CppScripts::Script { public: - void OnDie(Entity* self, Entity* killer) override; - void OnHitOrHealResult(Entity* self, Entity* attacker, int32_t damage) override; + void OnDie(Entity* self, Entity* killer) override; + void OnHitOrHealResult(Entity* self, Entity* attacker, int32_t damage) override; }; diff --git a/dScripts/NtCombatChallengeExplodingDummy.cpp b/dScripts/NtCombatChallengeExplodingDummy.cpp index 24494939..c117c63a 100644 --- a/dScripts/NtCombatChallengeExplodingDummy.cpp +++ b/dScripts/NtCombatChallengeExplodingDummy.cpp @@ -2,36 +2,31 @@ #include "EntityManager.h" #include "SkillComponent.h" -void NtCombatChallengeExplodingDummy::OnDie(Entity* self, Entity* killer) -{ - const auto challengeObjectID = self->GetVar(u"challengeObjectID"); +void NtCombatChallengeExplodingDummy::OnDie(Entity* self, Entity* killer) { + const auto challengeObjectID = self->GetVar(u"challengeObjectID"); - auto* challengeObject = EntityManager::Instance()->GetEntity(challengeObjectID); + auto* challengeObject = EntityManager::Instance()->GetEntity(challengeObjectID); - if (challengeObject != nullptr) - { - for (CppScripts::Script* script : CppScripts::GetEntityScripts(challengeObject)) - { - script->OnDie(challengeObject, killer); - } - } + if (challengeObject != nullptr) { + for (CppScripts::Script* script : CppScripts::GetEntityScripts(challengeObject)) { + script->OnDie(challengeObject, killer); + } + } } void NtCombatChallengeExplodingDummy::OnHitOrHealResult(Entity* self, Entity* attacker, int32_t damage) { - const auto challengeObjectID = self->GetVar(u"challengeObjectID"); + const auto challengeObjectID = self->GetVar(u"challengeObjectID"); - auto* challengeObject = EntityManager::Instance()->GetEntity(challengeObjectID); + auto* challengeObject = EntityManager::Instance()->GetEntity(challengeObjectID); - if (challengeObject != nullptr) - { - for (CppScripts::Script* script : CppScripts::GetEntityScripts(challengeObject)) - { - script->OnHitOrHealResult(challengeObject, attacker, damage); - } - } - auto skillComponent = self->GetComponent(); - if (skillComponent != nullptr) { - skillComponent->CalculateBehavior(1338, 30875, attacker->GetObjectID()); - } - self->Kill(attacker); -} \ No newline at end of file + if (challengeObject != nullptr) { + for (CppScripts::Script* script : CppScripts::GetEntityScripts(challengeObject)) { + script->OnHitOrHealResult(challengeObject, attacker, damage); + } + } + auto skillComponent = self->GetComponent(); + if (skillComponent != nullptr) { + skillComponent->CalculateBehavior(1338, 30875, attacker->GetObjectID()); + } + self->Kill(attacker); +} diff --git a/dScripts/NtCombatChallengeExplodingDummy.h b/dScripts/NtCombatChallengeExplodingDummy.h index c1c5ef1c..ff48c726 100644 --- a/dScripts/NtCombatChallengeExplodingDummy.h +++ b/dScripts/NtCombatChallengeExplodingDummy.h @@ -3,6 +3,6 @@ class NtCombatChallengeExplodingDummy : public CppScripts::Script { - void OnDie(Entity* self, Entity* killer) override; - void OnHitOrHealResult(Entity* self, Entity* attacker, int32_t damage) override; -}; \ No newline at end of file + void OnDie(Entity* self, Entity* killer) override; + void OnHitOrHealResult(Entity* self, Entity* attacker, int32_t damage) override; +}; diff --git a/dScripts/NtCombatChallengeServer.cpp b/dScripts/NtCombatChallengeServer.cpp index 4bf5dffc..2b88ccf8 100644 --- a/dScripts/NtCombatChallengeServer.cpp +++ b/dScripts/NtCombatChallengeServer.cpp @@ -4,241 +4,205 @@ #include "InventoryComponent.h" #include "MissionComponent.h" -void NtCombatChallengeServer::OnUse(Entity* self, Entity* user) -{ - GameMessages::SendNotifyClientObject(self->GetObjectID(), u"UI_Open", 0, 0, user->GetObjectID(), "", user->GetSystemAddress()); +void NtCombatChallengeServer::OnUse(Entity* self, Entity* user) { + GameMessages::SendNotifyClientObject(self->GetObjectID(), u"UI_Open", 0, 0, user->GetObjectID(), "", user->GetSystemAddress()); } -void NtCombatChallengeServer::OnDie(Entity* self, Entity* killer) -{ - if (killer != self && killer != nullptr) - { - SpawnTargetDummy(self); - } +void NtCombatChallengeServer::OnDie(Entity* self, Entity* killer) { + if (killer != self && killer != nullptr) { + SpawnTargetDummy(self); + } } -void NtCombatChallengeServer::OnHitOrHealResult(Entity* self, Entity* attacker, int32_t damage) -{ - const auto playerID = self->GetVar(u"playerID"); +void NtCombatChallengeServer::OnHitOrHealResult(Entity* self, Entity* attacker, int32_t damage) { + const auto playerID = self->GetVar(u"playerID"); - auto* player = EntityManager::Instance()->GetEntity(playerID); + auto* player = EntityManager::Instance()->GetEntity(playerID); - if (player == nullptr) - { - return; - } + if (player == nullptr) { + return; + } - auto totalDmg = self->GetVar(u"totalDmg"); + auto totalDmg = self->GetVar(u"totalDmg"); - totalDmg += damage; + totalDmg += damage; - self->SetVar(u"totalDmg", totalDmg); - self->SetNetworkVar(u"totalDmg", totalDmg); + self->SetVar(u"totalDmg", totalDmg); + self->SetNetworkVar(u"totalDmg", totalDmg); - GameMessages::SendPlayNDAudioEmitter(self, attacker->GetSystemAddress(), scoreSound); + GameMessages::SendPlayNDAudioEmitter(self, attacker->GetSystemAddress(), scoreSound); } -void NtCombatChallengeServer::OnFireEventServerSide(Entity *self, Entity *sender, std::string args, int32_t param1, - int32_t param2, int32_t param3) -{ - GameMessages::SendNotifyClientObject(self->GetObjectID(), u"UI_Close", 0, 0, sender->GetObjectID(), "", sender->GetSystemAddress()); +void NtCombatChallengeServer::OnFireEventServerSide(Entity* self, Entity* sender, std::string args, int32_t param1, + int32_t param2, int32_t param3) { + GameMessages::SendNotifyClientObject(self->GetObjectID(), u"UI_Close", 0, 0, sender->GetObjectID(), "", sender->GetSystemAddress()); } -void NtCombatChallengeServer::OnMessageBoxResponse(Entity* self, Entity* sender, int32_t button, const std::u16string& identifier, const std::u16string& userData) -{ - if (identifier == u"PlayButton" && button == 1) - { - self->SetNetworkVar(u"bInUse", true); +void NtCombatChallengeServer::OnMessageBoxResponse(Entity* self, Entity* sender, int32_t button, const std::u16string& identifier, const std::u16string& userData) { + if (identifier == u"PlayButton" && button == 1) { + self->SetNetworkVar(u"bInUse", true); - self->SetVar(u"playerID", sender->GetObjectID()); + self->SetVar(u"playerID", sender->GetObjectID()); - auto* inventoryComponent = sender->GetComponent(); + auto* inventoryComponent = sender->GetComponent(); - if (inventoryComponent != nullptr) - { - inventoryComponent->RemoveItem(3039, 1); - } + if (inventoryComponent != nullptr) { + inventoryComponent->RemoveItem(3039, 1); + } - GameMessages::SendPlayNDAudioEmitter(self, sender->GetSystemAddress(), startSound); + GameMessages::SendPlayNDAudioEmitter(self, sender->GetSystemAddress(), startSound); - self->AddTimer("start_delay", 2.0f); + self->AddTimer("start_delay", 2.0f); - GameMessages::SendShowActivityCountdown(self->GetObjectID(), false, false, u"", 0, sender->GetSystemAddress()); + GameMessages::SendShowActivityCountdown(self->GetObjectID(), false, false, u"", 0, sender->GetSystemAddress()); - self->SetNetworkVar(u"toggle", true); - } - else if (identifier == u"CloseButton") - { - GameMessages::SendNotifyClientObject(self->GetObjectID(), u"UI_Close", 1, 0, sender->GetObjectID(), "", sender->GetSystemAddress()); - } + self->SetNetworkVar(u"toggle", true); + } else if (identifier == u"CloseButton") { + GameMessages::SendNotifyClientObject(self->GetObjectID(), u"UI_Close", 1, 0, sender->GetObjectID(), "", sender->GetSystemAddress()); + } } -void NtCombatChallengeServer::SpawnTargetDummy(Entity* self) -{ - const auto playerID = self->GetVar(u"playerID"); +void NtCombatChallengeServer::SpawnTargetDummy(Entity* self) { + const auto playerID = self->GetVar(u"playerID"); - auto* player = EntityManager::Instance()->GetEntity(playerID); + auto* player = EntityManager::Instance()->GetEntity(playerID); - if (player == nullptr) - { - return; - } + if (player == nullptr) { + return; + } - auto targetNumber = self->GetVar(u"TargetNumber"); - if (targetNumber == 0) targetNumber = 1; + auto targetNumber = self->GetVar(u"TargetNumber"); + if (targetNumber == 0) targetNumber = 1; - if (targetNumber > tTargets.size()) targetNumber = tTargets.size(); + if (targetNumber > tTargets.size()) targetNumber = tTargets.size(); - self->SetVar(u"TargetNumber", targetNumber + 1); + self->SetVar(u"TargetNumber", targetNumber + 1); - const auto dummyLOT = tTargets[targetNumber - 1]; + const auto dummyLOT = tTargets[targetNumber - 1]; - EntityInfo info {}; - info.lot = dummyLOT; - info.spawnerID = self->GetObjectID(); - info.pos = self->GetPosition(); - info.rot = self->GetRotation(); - info.settings = { new LDFData(u"custom_script_server", "scripts\\02_server\\Map\\NT\\L_NT_COMBAT_CHALLENGE_DUMMY.lua") }; + EntityInfo info{}; + info.lot = dummyLOT; + info.spawnerID = self->GetObjectID(); + info.pos = self->GetPosition(); + info.rot = self->GetRotation(); + info.settings = { new LDFData(u"custom_script_server", "scripts\\02_server\\Map\\NT\\L_NT_COMBAT_CHALLENGE_DUMMY.lua") }; - auto* dummy = EntityManager::Instance()->CreateEntity(info); + auto* dummy = EntityManager::Instance()->CreateEntity(info); - dummy->SetVar(u"challengeObjectID", self->GetObjectID()); + dummy->SetVar(u"challengeObjectID", self->GetObjectID()); - EntityManager::Instance()->ConstructEntity(dummy); + EntityManager::Instance()->ConstructEntity(dummy); - self->SetVar(u"currentDummy", dummy->GetObjectID()); + self->SetVar(u"currentDummy", dummy->GetObjectID()); } -void NtCombatChallengeServer::SetAttackImmunity(LWOOBJID objID, bool bTurnOn) -{ - +void NtCombatChallengeServer::SetAttackImmunity(LWOOBJID objID, bool bTurnOn) { + } -void NtCombatChallengeServer::OnChildLoaded(Entity* self, Entity* child) -{ - auto targetNumber = self->GetVar(u"TargetNumber"); - if (targetNumber == 0) targetNumber = 1; - self->SetVar(u"TargetNumber", targetNumber + 1); +void NtCombatChallengeServer::OnChildLoaded(Entity* self, Entity* child) { + auto targetNumber = self->GetVar(u"TargetNumber"); + if (targetNumber == 0) targetNumber = 1; + self->SetVar(u"TargetNumber", targetNumber + 1); - const auto playerID = self->GetVar(u"playerID"); + const auto playerID = self->GetVar(u"playerID"); - auto* player = EntityManager::Instance()->GetEntity(playerID); + auto* player = EntityManager::Instance()->GetEntity(playerID); - if (player == nullptr) - { - return; - } + if (player == nullptr) { + return; + } - child->SetRotation(NiQuaternion::LookAt(child->GetPosition(), player->GetPosition())); + child->SetRotation(NiQuaternion::LookAt(child->GetPosition(), player->GetPosition())); - self->SetVar(u"currentTargetID", child->GetObjectID()); + self->SetVar(u"currentTargetID", child->GetObjectID()); - EntityManager::Instance()->SerializeEntity(child); + EntityManager::Instance()->SerializeEntity(child); - child->GetGroups().push_back("targets_" + std::to_string(self->GetObjectID())); + child->GetGroups().push_back("targets_" + std::to_string(self->GetObjectID())); } -void NtCombatChallengeServer::ResetGame(Entity* self) -{ - const auto totalDmg = self->GetVar(u"totalDmg"); - const auto playerID = self->GetVar(u"playerID"); +void NtCombatChallengeServer::ResetGame(Entity* self) { + const auto totalDmg = self->GetVar(u"totalDmg"); + const auto playerID = self->GetVar(u"playerID"); - auto* player = EntityManager::Instance()->GetEntity(playerID); + auto* player = EntityManager::Instance()->GetEntity(playerID); - if (player != nullptr) - { - auto* missionComponent = player->GetComponent(); + if (player != nullptr) { + auto* missionComponent = player->GetComponent(); - if (missionComponent != nullptr) - { - for (const auto& mission : tMissions) - { - if (totalDmg >= mission.damage) - { - missionComponent->ForceProgressTaskType(mission.mission, 1, 1); - } - } - } - } + if (missionComponent != nullptr) { + for (const auto& mission : tMissions) { + if (totalDmg >= mission.damage) { + missionComponent->ForceProgressTaskType(mission.mission, 1, 1); + } + } + } + } - self->SetVar(u"TargetNumber", 1); - self->SetVar(u"playerID", LWOOBJID_EMPTY); - self->SetVar(u"totalDmg", 0); - self->SetNetworkVar(u"totalDmg", false); - self->SetNetworkVar(u"update_time", 0); + self->SetVar(u"TargetNumber", 1); + self->SetVar(u"playerID", LWOOBJID_EMPTY); + self->SetVar(u"totalDmg", 0); + self->SetNetworkVar(u"totalDmg", false); + self->SetNetworkVar(u"update_time", 0); - const auto& targetObjs = EntityManager::Instance()->GetEntitiesInGroup("targets_" + std::to_string(self->GetObjectID())); + const auto& targetObjs = EntityManager::Instance()->GetEntitiesInGroup("targets_" + std::to_string(self->GetObjectID())); - for (auto* target : targetObjs) - { - target->Smash(self->GetObjectID()); - } + for (auto* target : targetObjs) { + target->Smash(self->GetObjectID()); + } - const auto currentID = self->GetVar(u"currentDummy"); + const auto currentID = self->GetVar(u"currentDummy"); - auto* current = EntityManager::Instance()->GetEntity(currentID); + auto* current = EntityManager::Instance()->GetEntity(currentID); - if (current != nullptr) - { - current->Smash(self->GetObjectID()); - } + if (current != nullptr) { + current->Smash(self->GetObjectID()); + } } -void NtCombatChallengeServer::OnActivityTimerUpdate(Entity* self, float timeRemaining) -{ - self->SetNetworkVar(u"update_time", std::ceil(timeRemaining)); +void NtCombatChallengeServer::OnActivityTimerUpdate(Entity* self, float timeRemaining) { + self->SetNetworkVar(u"update_time", std::ceil(timeRemaining)); - if (timeRemaining <= 3) - { - GameMessages::SendPlayNDAudioEmitter(self, UNASSIGNED_SYSTEM_ADDRESS, timerLowSound); - } - else - { - GameMessages::SendPlayNDAudioEmitter(self, UNASSIGNED_SYSTEM_ADDRESS, timerSound); - } + if (timeRemaining <= 3) { + GameMessages::SendPlayNDAudioEmitter(self, UNASSIGNED_SYSTEM_ADDRESS, timerLowSound); + } else { + GameMessages::SendPlayNDAudioEmitter(self, UNASSIGNED_SYSTEM_ADDRESS, timerSound); + } } -void NtCombatChallengeServer::OnTimerDone(Entity* self, std::string timerName) -{ - if (timerName == "start_delay") - { - self->SetVar(u"game_tick", gameTime); +void NtCombatChallengeServer::OnTimerDone(Entity* self, std::string timerName) { + if (timerName == "start_delay") { + self->SetVar(u"game_tick", gameTime); - SpawnTargetDummy(self); + SpawnTargetDummy(self); - self->AddTimer("game_tick", 1); + self->AddTimer("game_tick", 1); - self->SetNetworkVar(u"totalTime", gameTime); - } - else if (timerName == "game_tick") - { - auto gameTick = self->GetVar(u"game_tick"); + self->SetNetworkVar(u"totalTime", gameTime); + } else if (timerName == "game_tick") { + auto gameTick = self->GetVar(u"game_tick"); - gameTick -= 1; + gameTick -= 1; - self->SetVar(u"game_tick", gameTick); + self->SetVar(u"game_tick", gameTick); - if (gameTick <= 0) - { - ResetGame(self); + if (gameTick <= 0) { + ResetGame(self); - GameMessages::SendPlayNDAudioEmitter(self, UNASSIGNED_SYSTEM_ADDRESS, stopSound); + GameMessages::SendPlayNDAudioEmitter(self, UNASSIGNED_SYSTEM_ADDRESS, stopSound); - self->AddTimer("reset_tick", 5); - } - else - { - self->AddTimer("game_tick", 1); + self->AddTimer("reset_tick", 5); + } else { + self->AddTimer("game_tick", 1); - OnActivityTimerUpdate(self, gameTick); - } - } - else if (timerName == "reset_tick") - { - self->SetNetworkVar(u"toggle", false); - self->SetNetworkVar(u"bInUse", false); - } + OnActivityTimerUpdate(self, gameTick); + } + } else if (timerName == "reset_tick") { + self->SetNetworkVar(u"toggle", false); + self->SetNetworkVar(u"bInUse", false); + } } diff --git a/dScripts/NtCombatChallengeServer.h b/dScripts/NtCombatChallengeServer.h index 6a193a11..72bb981f 100644 --- a/dScripts/NtCombatChallengeServer.h +++ b/dScripts/NtCombatChallengeServer.h @@ -4,44 +4,44 @@ class NtCombatChallengeServer : public CppScripts::Script { public: - void OnUse(Entity* self, Entity* user) override; - void OnDie(Entity* self, Entity* killer) override; - void OnHitOrHealResult(Entity* self, Entity* attacker, int32_t damage) override; - void OnFireEventServerSide(Entity *self, Entity *sender, std::string args, int32_t param1, int32_t param2, - int32_t param3) override; - void OnMessageBoxResponse(Entity* self, Entity* sender, int32_t button, const std::u16string& identifier, const std::u16string& userData) override; - void SpawnTargetDummy(Entity* self); - void SetAttackImmunity(LWOOBJID objID, bool bTurnOn); - void OnChildLoaded(Entity* self, Entity* child); - void ResetGame(Entity* self); - void OnActivityTimerUpdate(Entity* self, float timeRemaining); - void OnTimerDone(Entity* self, std::string timerName) override; + void OnUse(Entity* self, Entity* user) override; + void OnDie(Entity* self, Entity* killer) override; + void OnHitOrHealResult(Entity* self, Entity* attacker, int32_t damage) override; + void OnFireEventServerSide(Entity* self, Entity* sender, std::string args, int32_t param1, int32_t param2, + int32_t param3) override; + void OnMessageBoxResponse(Entity* self, Entity* sender, int32_t button, const std::u16string& identifier, const std::u16string& userData) override; + void SpawnTargetDummy(Entity* self); + void SetAttackImmunity(LWOOBJID objID, bool bTurnOn); + void OnChildLoaded(Entity* self, Entity* child); + void ResetGame(Entity* self); + void OnActivityTimerUpdate(Entity* self, float timeRemaining); + void OnTimerDone(Entity* self, std::string timerName) override; private: - float gameTime = 30.0f; - std::string startSound = "{a477f897-30da-4b15-8fce-895c6547adae}"; - std::string stopSound = "{a832b9c5-b000-4c97-820a-2a7d1e68dd9d}"; - std::string timerSound = "{79b38431-4fc7-403b-8ede-eaff700a7ab0}"; - std::string timerLowSound = "{0e1f1284-e1c4-42ed-8ef9-93e8756948f8}"; - std::string scoreSound = "{cfdade40-3d97-4cf5-b53c-862e0b84c1a1}"; + float gameTime = 30.0f; + std::string startSound = "{a477f897-30da-4b15-8fce-895c6547adae}"; + std::string stopSound = "{a832b9c5-b000-4c97-820a-2a7d1e68dd9d}"; + std::string timerSound = "{79b38431-4fc7-403b-8ede-eaff700a7ab0}"; + std::string timerLowSound = "{0e1f1284-e1c4-42ed-8ef9-93e8756948f8}"; + std::string scoreSound = "{cfdade40-3d97-4cf5-b53c-862e0b84c1a1}"; - std::vector tTargets = { - 13556, 13556, 13764, 13764, 13765, 13765, - 13766, 13766, 13767, 13767, 13768, 13768, - 13830, 13769, 13769, 13770, 13830, 13770, + std::vector tTargets = { + 13556, 13556, 13764, 13764, 13765, 13765, + 13766, 13766, 13767, 13767, 13768, 13768, + 13830, 13769, 13769, 13770, 13830, 13770, 13771, 13771, 13830, 13772 - }; + }; - struct MissionRequirements - { - int32_t mission; - int32_t damage; - }; + struct MissionRequirements + { + int32_t mission; + int32_t damage; + }; - std::vector tMissions = { - {1010, 25}, - {1340, 100}, - {1341, 240}, - {1342, 290} - }; + std::vector tMissions = { + {1010, 25}, + {1340, 100}, + {1341, 240}, + {1342, 290} + }; }; diff --git a/dScripts/NtConsoleTeleportServer.cpp b/dScripts/NtConsoleTeleportServer.cpp index b03ae34e..324a2fc0 100644 --- a/dScripts/NtConsoleTeleportServer.cpp +++ b/dScripts/NtConsoleTeleportServer.cpp @@ -2,33 +2,27 @@ #include "Entity.h" #include "AMFFormat.h" -void NtConsoleTeleportServer::OnStartup(Entity* self) -{ - self->SetVar(u"teleportAnim", m_TeleportAnim); - self->SetVar(u"teleportString", m_TeleportString); +void NtConsoleTeleportServer::OnStartup(Entity* self) { + self->SetVar(u"teleportAnim", m_TeleportAnim); + self->SetVar(u"teleportString", m_TeleportString); } -void NtConsoleTeleportServer::OnUse(Entity* self, Entity* user) -{ - BaseOnUse(self, user); +void NtConsoleTeleportServer::OnUse(Entity* self, Entity* user) { + BaseOnUse(self, user); } -void NtConsoleTeleportServer::OnMessageBoxResponse(Entity* self, Entity* sender, int32_t button, const std::u16string& identifier, const std::u16string& userData) -{ - BaseOnMessageBoxResponse(self, sender, button, identifier, userData); +void NtConsoleTeleportServer::OnMessageBoxResponse(Entity* self, Entity* sender, int32_t button, const std::u16string& identifier, const std::u16string& userData) { + BaseOnMessageBoxResponse(self, sender, button, identifier, userData); } -void NtConsoleTeleportServer::OnChoiceBoxResponse(Entity* self, Entity* sender, int32_t button, const std::u16string& buttonIdentifier, const std::u16string& identifier) -{ - +void NtConsoleTeleportServer::OnChoiceBoxResponse(Entity* self, Entity* sender, int32_t button, const std::u16string& buttonIdentifier, const std::u16string& identifier) { + } -void NtConsoleTeleportServer::OnTimerDone(Entity* self, std::string timerName) -{ - BaseOnTimerDone(self, timerName); +void NtConsoleTeleportServer::OnTimerDone(Entity* self, std::string timerName) { + BaseOnTimerDone(self, timerName); } -void NtConsoleTeleportServer::OnFireEventServerSide(Entity *self, Entity *sender, std::string args, int32_t param1, int32_t param2, int32_t param3) -{ - BaseOnFireEventServerSide(self, sender, args, param1, param2, param3); +void NtConsoleTeleportServer::OnFireEventServerSide(Entity* self, Entity* sender, std::string args, int32_t param1, int32_t param2, int32_t param3) { + BaseOnFireEventServerSide(self, sender, args, param1, param2, param3); } diff --git a/dScripts/NtConsoleTeleportServer.h b/dScripts/NtConsoleTeleportServer.h index 7bba7ee1..59ac7bf4 100644 --- a/dScripts/NtConsoleTeleportServer.h +++ b/dScripts/NtConsoleTeleportServer.h @@ -6,16 +6,16 @@ class NtConsoleTeleportServer : public CppScripts::Script, BaseConsoleTeleportServer { public: - void OnStartup(Entity* self) override; - void OnUse(Entity* self, Entity* user) override; - void OnMessageBoxResponse(Entity* self, Entity* sender, int32_t button, const std::u16string& identifier, const std::u16string& userData) override; - void OnChoiceBoxResponse(Entity* self, Entity* sender, int32_t button, const std::u16string& buttonIdentifier, const std::u16string& identifier) override; - void OnTimerDone(Entity* self, std::string timerName) override; - void OnFireEventServerSide(Entity *self, Entity *sender, std::string args, int32_t param1, int32_t param2, int32_t param3) override; + void OnStartup(Entity* self) override; + void OnUse(Entity* self, Entity* user) override; + void OnMessageBoxResponse(Entity* self, Entity* sender, int32_t button, const std::u16string& identifier, const std::u16string& userData) override; + void OnChoiceBoxResponse(Entity* self, Entity* sender, int32_t button, const std::u16string& buttonIdentifier, const std::u16string& identifier) override; + void OnTimerDone(Entity* self, std::string timerName) override; + void OnFireEventServerSide(Entity* self, Entity* sender, std::string args, int32_t param1, int32_t param2, int32_t param3) override; private: - int32_t m_ChoiceZoneID = 1800; - std::string m_SpawnPoint = "NS_LW"; - std::u16string m_TeleportAnim = u"lup-teleport"; - std::u16string m_TeleportString = u"UI_TRAVEL_TO_CRUX_PRIME"; + int32_t m_ChoiceZoneID = 1800; + std::string m_SpawnPoint = "NS_LW"; + std::u16string m_TeleportAnim = u"lup-teleport"; + std::u16string m_TeleportString = u"UI_TRAVEL_TO_CRUX_PRIME"; }; diff --git a/dScripts/NtDarkitectRevealServer.cpp b/dScripts/NtDarkitectRevealServer.cpp index b8afa510..80ceb91e 100644 --- a/dScripts/NtDarkitectRevealServer.cpp +++ b/dScripts/NtDarkitectRevealServer.cpp @@ -2,15 +2,13 @@ #include "Darkitect.h" #include "MissionComponent.h" -void NtDarkitectRevealServer::OnUse(Entity* self, Entity* user) -{ +void NtDarkitectRevealServer::OnUse(Entity* self, Entity* user) { Darkitect Baron; Baron.Reveal(self, user); auto* missionComponent = user->GetComponent(); - if (missionComponent != nullptr) - { + if (missionComponent != nullptr) { missionComponent->ForceProgressTaskType(1344, 1, 14293); } } diff --git a/dScripts/NtDirtCloudServer.cpp b/dScripts/NtDirtCloudServer.cpp index 82572703..a9a70c5c 100644 --- a/dScripts/NtDirtCloudServer.cpp +++ b/dScripts/NtDirtCloudServer.cpp @@ -1,53 +1,46 @@ #include "NtDirtCloudServer.h" #include "MissionComponent.h" -std::map> NtDirtCloudServer::m_Missions = +std::map> NtDirtCloudServer::m_Missions = { - {"Dirt_Clouds_Sent", {1333,1253}}, - {"Dirt_Clouds_Assem", {1333,1276}}, - {"Dirt_Clouds_Para", {1333,1277}}, - {"Dirt_Clouds_Halls", {1333,1283}} + {"Dirt_Clouds_Sent", {1333,1253}}, + {"Dirt_Clouds_Assem", {1333,1276}}, + {"Dirt_Clouds_Para", {1333,1277}}, + {"Dirt_Clouds_Halls", {1333,1283}} }; -void NtDirtCloudServer::OnStartup(Entity* self) -{ - self->SetVar(u"CloudOn", true); +void NtDirtCloudServer::OnStartup(Entity* self) { + self->SetVar(u"CloudOn", true); } -void NtDirtCloudServer::OnSkillEventFired(Entity* self, Entity* caster, const std::string& message) -{ - if (message != "soapspray") - { - return; - } +void NtDirtCloudServer::OnSkillEventFired(Entity* self, Entity* caster, const std::string& message) { + if (message != "soapspray") { + return; + } - if (!self->GetVar(u"CloudOn")) - { - return; - } + if (!self->GetVar(u"CloudOn")) { + return; + } - const auto mySpawner = GeneralUtils::UTF16ToWTF8(self->GetVar(u"spawner_name")); + const auto mySpawner = GeneralUtils::UTF16ToWTF8(self->GetVar(u"spawner_name")); - if (m_Missions.count(mySpawner) == 0) - { - return; - } + if (m_Missions.count(mySpawner) == 0) { + return; + } - const auto& myMis = m_Missions[mySpawner]; + const auto& myMis = m_Missions[mySpawner]; - auto* missionComponent = caster->GetComponent(); + auto* missionComponent = caster->GetComponent(); - if (missionComponent == nullptr) - { - return; - } + if (missionComponent == nullptr) { + return; + } - for (const auto missionID : myMis) - { - missionComponent->ForceProgressTaskType(missionID, 1, 1); - } - - self->SetVar(u"CloudOn", false); + for (const auto missionID : myMis) { + missionComponent->ForceProgressTaskType(missionID, 1, 1); + } - self->Smash(self->GetObjectID(), VIOLENT); + self->SetVar(u"CloudOn", false); + + self->Smash(self->GetObjectID(), VIOLENT); } diff --git a/dScripts/NtDirtCloudServer.h b/dScripts/NtDirtCloudServer.h index 0c9e50d1..150a33df 100644 --- a/dScripts/NtDirtCloudServer.h +++ b/dScripts/NtDirtCloudServer.h @@ -4,9 +4,9 @@ class NtDirtCloudServer : public CppScripts::Script { public: - void OnStartup(Entity* self) override; - void OnSkillEventFired(Entity* self, Entity* caster, const std::string& message) override; + void OnStartup(Entity* self) override; + void OnSkillEventFired(Entity* self, Entity* caster, const std::string& message) override; private: - static std::map> m_Missions; + static std::map> m_Missions; }; diff --git a/dScripts/NtDukeServer.cpp b/dScripts/NtDukeServer.cpp index df3f39d6..327d3290 100644 --- a/dScripts/NtDukeServer.cpp +++ b/dScripts/NtDukeServer.cpp @@ -2,37 +2,37 @@ #include "InventoryComponent.h" #include "MissionComponent.h" -void NtDukeServer::SetVariables(Entity *self) { - self->SetVar(m_SpyProximityVariable, 35.0f); +void NtDukeServer::SetVariables(Entity* self) { + self->SetVar(m_SpyProximityVariable, 35.0f); - self->SetVar(m_SpyDataVariable, { - NT_FACTION_SPY_DUKE, 13548, 1319 - }); + self->SetVar(m_SpyDataVariable, { + NT_FACTION_SPY_DUKE, 13548, 1319 + }); - self->SetVar>(m_SpyDialogueTableVariable, { - { "DUKE_NT_CONVO_1", 0 }, - { "DUKE_NT_CONVO_2", 0 }, - { "DUKE_NT_CONVO_3", 0 }, - }); + self->SetVar>(m_SpyDialogueTableVariable, { + { "DUKE_NT_CONVO_1", 0 }, + { "DUKE_NT_CONVO_2", 0 }, + { "DUKE_NT_CONVO_3", 0 }, + }); - // If there's an alternating conversation, indices should be provided using the conversationID variables - self->SetVar>(m_SpyCinematicObjectsVariable, { self->GetObjectID() }); + // If there's an alternating conversation, indices should be provided using the conversationID variables + self->SetVar>(m_SpyCinematicObjectsVariable, { self->GetObjectID() }); } -void NtDukeServer::OnMissionDialogueOK(Entity *self, Entity *target, int missionID, MissionState missionState) { +void NtDukeServer::OnMissionDialogueOK(Entity* self, Entity* target, int missionID, MissionState missionState) { - // Handles adding and removing the sword for the Crux Prime Sword mission - auto* missionComponent = target->GetComponent(); - auto* inventoryComponent = target->GetComponent(); + // Handles adding and removing the sword for the Crux Prime Sword mission + auto* missionComponent = target->GetComponent(); + auto* inventoryComponent = target->GetComponent(); - if (missionComponent != nullptr && inventoryComponent != nullptr) { - auto state = missionComponent->GetMissionState(m_SwordMissionID); - auto lotCount = inventoryComponent->GetLotCount(m_SwordLot); + if (missionComponent != nullptr && inventoryComponent != nullptr) { + auto state = missionComponent->GetMissionState(m_SwordMissionID); + auto lotCount = inventoryComponent->GetLotCount(m_SwordLot); - if ((state == MissionState::MISSION_STATE_AVAILABLE || state == MissionState::MISSION_STATE_ACTIVE) && lotCount < 1) { - inventoryComponent->AddItem(m_SwordLot, 1, eLootSourceType::LOOT_SOURCE_NONE); - } else if (state == MissionState::MISSION_STATE_READY_TO_COMPLETE) { - inventoryComponent->RemoveItem(m_SwordLot, lotCount); - } - } + if ((state == MissionState::MISSION_STATE_AVAILABLE || state == MissionState::MISSION_STATE_ACTIVE) && lotCount < 1) { + inventoryComponent->AddItem(m_SwordLot, 1, eLootSourceType::LOOT_SOURCE_NONE); + } else if (state == MissionState::MISSION_STATE_READY_TO_COMPLETE) { + inventoryComponent->RemoveItem(m_SwordLot, lotCount); + } + } } diff --git a/dScripts/NtDukeServer.h b/dScripts/NtDukeServer.h index f56e9912..0878e86c 100644 --- a/dScripts/NtDukeServer.h +++ b/dScripts/NtDukeServer.h @@ -2,8 +2,8 @@ #include "NtFactionSpyServer.h" class NtDukeServer : public NtFactionSpyServer { - void SetVariables(Entity *self) override; - void OnMissionDialogueOK(Entity* self, Entity* target, int missionID, MissionState missionState) override; - const uint32_t m_SwordMissionID = 1448; - const LOT m_SwordLot = 13777; + void SetVariables(Entity* self) override; + void OnMissionDialogueOK(Entity* self, Entity* target, int missionID, MissionState missionState) override; + const uint32_t m_SwordMissionID = 1448; + const LOT m_SwordLot = 13777; }; diff --git a/dScripts/NtFactionSpyServer.cpp b/dScripts/NtFactionSpyServer.cpp index f1104e34..ac068a32 100644 --- a/dScripts/NtFactionSpyServer.cpp +++ b/dScripts/NtFactionSpyServer.cpp @@ -5,96 +5,96 @@ #include "GameMessages.h" #include "MissionComponent.h" -void NtFactionSpyServer::OnStartup(Entity *self) { - SetVariables(self); +void NtFactionSpyServer::OnStartup(Entity* self) { + SetVariables(self); - // Set the proximity to sense later - auto* proximityMonitor = self->GetComponent(); - if (proximityMonitor == nullptr) { - proximityMonitor = new ProximityMonitorComponent(self, -1, -1); - self->AddComponent(COMPONENT_TYPE_PROXIMITY_MONITOR, proximityMonitor); - } + // Set the proximity to sense later + auto* proximityMonitor = self->GetComponent(); + if (proximityMonitor == nullptr) { + proximityMonitor = new ProximityMonitorComponent(self, -1, -1); + self->AddComponent(COMPONENT_TYPE_PROXIMITY_MONITOR, proximityMonitor); + } - proximityMonitor->SetProximityRadius(self->GetVar(m_SpyProximityVariable), m_ProximityName); + proximityMonitor->SetProximityRadius(self->GetVar(m_SpyProximityVariable), m_ProximityName); } void NtFactionSpyServer::SetVariables(Entity* self) { - self->SetVar(m_SpyProximityVariable, 0.0f); - self->SetVar(m_SpyDataVariable, {}); - self->SetVar>(m_SpyDialogueTableVariable, {}); + self->SetVar(m_SpyProximityVariable, 0.0f); + self->SetVar(m_SpyDataVariable, {}); + self->SetVar>(m_SpyDialogueTableVariable, {}); - // If there's an alternating conversation, indices should be provided using the conversationID variables - self->SetVar>(m_SpyCinematicObjectsVariable, { self->GetObjectID() }); + // If there's an alternating conversation, indices should be provided using the conversationID variables + self->SetVar>(m_SpyCinematicObjectsVariable, { self->GetObjectID() }); } -void NtFactionSpyServer::OnProximityUpdate(Entity *self, Entity *entering, std::string name, std::string status) { - if (name == m_ProximityName && status == "ENTER" && IsSpy(self, entering)) { - auto cinematic = self->GetVar(m_SpyCinematicVariable); - if (!cinematic.empty()) { +void NtFactionSpyServer::OnProximityUpdate(Entity* self, Entity* entering, std::string name, std::string status) { + if (name == m_ProximityName && status == "ENTER" && IsSpy(self, entering)) { + auto cinematic = self->GetVar(m_SpyCinematicVariable); + if (!cinematic.empty()) { - // Save the root of this cinematic so we can identify updates later - auto cinematicSplit = GeneralUtils::SplitString(cinematic, u'_'); - if (!cinematicSplit.empty()) { - self->SetVar(m_CinematicRootVariable, cinematicSplit.at(0)); - } + // Save the root of this cinematic so we can identify updates later + auto cinematicSplit = GeneralUtils::SplitString(cinematic, u'_'); + if (!cinematicSplit.empty()) { + self->SetVar(m_CinematicRootVariable, cinematicSplit.at(0)); + } - GameMessages::SendPlayCinematic(entering->GetObjectID(), cinematic, entering->GetSystemAddress(), - true, true, true); - } - } + GameMessages::SendPlayCinematic(entering->GetObjectID(), cinematic, entering->GetSystemAddress(), + true, true, true); + } + } } -bool NtFactionSpyServer::IsSpy(Entity* self, Entity *possibleSpy) { - auto spyData = self->GetVar(m_SpyDataVariable); - if (!spyData.missionID || !spyData.flagID || !spyData.itemID) - return false; +bool NtFactionSpyServer::IsSpy(Entity* self, Entity* possibleSpy) { + auto spyData = self->GetVar(m_SpyDataVariable); + if (!spyData.missionID || !spyData.flagID || !spyData.itemID) + return false; - auto* missionComponent = possibleSpy->GetComponent(); - auto* inventoryComponent = possibleSpy->GetComponent(); - auto* character = possibleSpy->GetCharacter(); + auto* missionComponent = possibleSpy->GetComponent(); + auto* inventoryComponent = possibleSpy->GetComponent(); + auto* character = possibleSpy->GetCharacter(); - // A player is a spy if they have the spy mission, have the spy equipment equipped and don't have the spy flag set yet - return missionComponent != nullptr && missionComponent->GetMissionState(spyData.missionID) == MissionState::MISSION_STATE_ACTIVE - && inventoryComponent != nullptr && inventoryComponent->IsEquipped(spyData.itemID) - && character != nullptr && !character->GetPlayerFlag(spyData.flagID); + // A player is a spy if they have the spy mission, have the spy equipment equipped and don't have the spy flag set yet + return missionComponent != nullptr && missionComponent->GetMissionState(spyData.missionID) == MissionState::MISSION_STATE_ACTIVE + && inventoryComponent != nullptr && inventoryComponent->IsEquipped(spyData.itemID) + && character != nullptr && !character->GetPlayerFlag(spyData.flagID); } -void NtFactionSpyServer::OnCinematicUpdate(Entity *self, Entity *sender, eCinematicEvent event, - const std::u16string &pathName, float_t pathTime, float_t totalTime, - int32_t waypoint) { +void NtFactionSpyServer::OnCinematicUpdate(Entity* self, Entity* sender, eCinematicEvent event, + const std::u16string& pathName, float_t pathTime, float_t totalTime, + int32_t waypoint) { - const auto& cinematicRoot = self->GetVar(m_CinematicRootVariable); - auto pathNameCopy = std::u16string(pathName); // Mutable copy - auto pathSplit = GeneralUtils::SplitString(pathNameCopy, u'_'); + const auto& cinematicRoot = self->GetVar(m_CinematicRootVariable); + auto pathNameCopy = std::u16string(pathName); // Mutable copy + auto pathSplit = GeneralUtils::SplitString(pathNameCopy, u'_'); - // Make sure we have a path of type _ - if (pathSplit.size() >= 2) { - auto pathRoot = pathSplit.at(0); - auto pathIndex = std::stoi(GeneralUtils::UTF16ToWTF8(pathSplit.at(1))) - 1; - const auto& dialogueTable = self->GetVar>(m_SpyDialogueTableVariable); + // Make sure we have a path of type _ + if (pathSplit.size() >= 2) { + auto pathRoot = pathSplit.at(0); + auto pathIndex = std::stoi(GeneralUtils::UTF16ToWTF8(pathSplit.at(1))) - 1; + const auto& dialogueTable = self->GetVar>(m_SpyDialogueTableVariable); - // Make sure we're listening to the root we're interested in - if (pathRoot == cinematicRoot) { - if (event == STARTED && pathIndex >= 0 && pathIndex < dialogueTable.size()) { + // Make sure we're listening to the root we're interested in + if (pathRoot == cinematicRoot) { + if (event == STARTED && pathIndex >= 0 && pathIndex < dialogueTable.size()) { - // If the cinematic started, show part of the conversation - GameMessages::SendNotifyClientObject(self->GetObjectID(), m_SpyDialogueNotification, 0, - 0, ParamObjectForConversationID(self, dialogueTable.at(pathIndex).conversationID), - dialogueTable.at(pathIndex).token, sender->GetSystemAddress()); + // If the cinematic started, show part of the conversation + GameMessages::SendNotifyClientObject(self->GetObjectID(), m_SpyDialogueNotification, 0, + 0, ParamObjectForConversationID(self, dialogueTable.at(pathIndex).conversationID), + dialogueTable.at(pathIndex).token, sender->GetSystemAddress()); - } else if (event == ENDED && pathIndex >= dialogueTable.size() - 1) { - auto spyData = self->GetVar(m_SpyDataVariable); - auto* character = sender->GetCharacter(); - if (character != nullptr) { - character->SetPlayerFlag(spyData.flagID, true); - } - } - } - } + } else if (event == ENDED && pathIndex >= dialogueTable.size() - 1) { + auto spyData = self->GetVar(m_SpyDataVariable); + auto* character = sender->GetCharacter(); + if (character != nullptr) { + character->SetPlayerFlag(spyData.flagID, true); + } + } + } + } } LWOOBJID NtFactionSpyServer::ParamObjectForConversationID(Entity* self, uint32_t conversationID) { - auto paramObjects = self->GetVar>(m_SpyCinematicObjectsVariable); - auto index = conversationID >= paramObjects.size() ? paramObjects.size() - 1 : conversationID; - return paramObjects.at(index); + auto paramObjects = self->GetVar>(m_SpyCinematicObjectsVariable); + auto index = conversationID >= paramObjects.size() ? paramObjects.size() - 1 : conversationID; + return paramObjects.at(index); } diff --git a/dScripts/NtFactionSpyServer.h b/dScripts/NtFactionSpyServer.h index ec8df1f4..67955dd4 100644 --- a/dScripts/NtFactionSpyServer.h +++ b/dScripts/NtFactionSpyServer.h @@ -2,31 +2,31 @@ #include "CppScripts.h" struct SpyDialogue { - std::string token; - uint32_t conversationID; + std::string token; + uint32_t conversationID; }; struct SpyData { - uint32_t flagID; - LOT itemID; - uint32_t missionID; + uint32_t flagID; + LOT itemID; + uint32_t missionID; }; class NtFactionSpyServer : public CppScripts::Script { - void OnStartup(Entity *self) override; - void OnProximityUpdate(Entity *self, Entity *entering, std::string name, std::string status) override; - void OnCinematicUpdate(Entity *self, Entity *sender, eCinematicEvent event, const std::u16string &pathName, float_t pathTime, float_t totalTime, int32_t waypoint) override; + void OnStartup(Entity* self) override; + void OnProximityUpdate(Entity* self, Entity* entering, std::string name, std::string status) override; + void OnCinematicUpdate(Entity* self, Entity* sender, eCinematicEvent event, const std::u16string& pathName, float_t pathTime, float_t totalTime, int32_t waypoint) override; protected: - virtual void SetVariables(Entity* self); - bool IsSpy(Entity* self, Entity* possibleSpy); - LWOOBJID ParamObjectForConversationID(Entity* self, uint32_t conversationID); + virtual void SetVariables(Entity* self); + bool IsSpy(Entity* self, Entity* possibleSpy); + LWOOBJID ParamObjectForConversationID(Entity* self, uint32_t conversationID); - const std::string m_ProximityName = "SpyDistance"; - const std::u16string m_SpyDialogueNotification = u"displayDialogueLine"; - const std::u16string m_SpyCinematicVariable = u"SpyCinematic"; - const std::u16string m_SpyCinematicObjectsVariable = u"SpyCinematicObjects"; - const std::u16string m_CinematicRootVariable = u"CinematicRoot"; - const std::u16string m_SpyProximityVariable = u"Proximity"; - const std::u16string m_SpyDialogueTableVariable = u"SpyDialogueTable"; - const std::u16string m_SpyDataVariable = u"SpyData"; + const std::string m_ProximityName = "SpyDistance"; + const std::u16string m_SpyDialogueNotification = u"displayDialogueLine"; + const std::u16string m_SpyCinematicVariable = u"SpyCinematic"; + const std::u16string m_SpyCinematicObjectsVariable = u"SpyCinematicObjects"; + const std::u16string m_CinematicRootVariable = u"CinematicRoot"; + const std::u16string m_SpyProximityVariable = u"Proximity"; + const std::u16string m_SpyDialogueTableVariable = u"SpyDialogueTable"; + const std::u16string m_SpyDataVariable = u"SpyData"; }; diff --git a/dScripts/NtHaelServer.cpp b/dScripts/NtHaelServer.cpp index a4c16e1f..fbad421f 100644 --- a/dScripts/NtHaelServer.cpp +++ b/dScripts/NtHaelServer.cpp @@ -1,20 +1,20 @@ #include "NtHaelServer.h" #include "Entity.h" -void NtHaelServer::SetVariables(Entity *self) { - self->SetVar(m_SpyProximityVariable, 25.0f); +void NtHaelServer::SetVariables(Entity* self) { + self->SetVar(m_SpyProximityVariable, 25.0f); - self->SetVar(m_SpyDataVariable, { - NT_FACTION_SPY_HAEL, 13892, 1321 - }); + self->SetVar(m_SpyDataVariable, { + NT_FACTION_SPY_HAEL, 13892, 1321 + }); - self->SetVar>(m_SpyDialogueTableVariable, { - { "HAEL_NT_CONVO_1", 0 }, - { "HAEL_NT_CONVO_2", 0 }, - { "HAEL_NT_CONVO_3", 0 }, - { "HAEL_NT_CONVO_4", 0 }, - }); + self->SetVar>(m_SpyDialogueTableVariable, { + { "HAEL_NT_CONVO_1", 0 }, + { "HAEL_NT_CONVO_2", 0 }, + { "HAEL_NT_CONVO_3", 0 }, + { "HAEL_NT_CONVO_4", 0 }, + }); - // If there's an alternating conversation, indices should be provided using the conversationID variables - self->SetVar>(m_SpyCinematicObjectsVariable, { self->GetObjectID() }); + // If there's an alternating conversation, indices should be provided using the conversationID variables + self->SetVar>(m_SpyCinematicObjectsVariable, { self->GetObjectID() }); } diff --git a/dScripts/NtHaelServer.h b/dScripts/NtHaelServer.h index 8e3dbe47..4597198f 100644 --- a/dScripts/NtHaelServer.h +++ b/dScripts/NtHaelServer.h @@ -2,5 +2,5 @@ #include "NtFactionSpyServer.h" class NtHaelServer : public NtFactionSpyServer { - void SetVariables(Entity *self) override; + void SetVariables(Entity* self) override; }; diff --git a/dScripts/NtImagBeamBuffer.cpp b/dScripts/NtImagBeamBuffer.cpp index 067a8d61..d98a7403 100644 --- a/dScripts/NtImagBeamBuffer.cpp +++ b/dScripts/NtImagBeamBuffer.cpp @@ -2,65 +2,52 @@ #include "EntityManager.h" #include "SkillComponent.h" -void NtImagBeamBuffer::OnStartup(Entity* self) -{ - self->SetProximityRadius(100, "ImagZone"); +void NtImagBeamBuffer::OnStartup(Entity* self) { + self->SetProximityRadius(100, "ImagZone"); - self->AddTimer("BuffImag", 2.0f); + self->AddTimer("BuffImag", 2.0f); } -void NtImagBeamBuffer::OnProximityUpdate(Entity* self, Entity* entering, std::string name, std::string status) -{ - if (name != "ImagZone" || !entering->IsPlayer()) - { - return; - } +void NtImagBeamBuffer::OnProximityUpdate(Entity* self, Entity* entering, std::string name, std::string status) { + if (name != "ImagZone" || !entering->IsPlayer()) { + return; + } - if (status == "ENTER") - { - const auto& iter = std::find(m_EntitiesInProximity.begin(), m_EntitiesInProximity.end(), entering->GetObjectID()); + if (status == "ENTER") { + const auto& iter = std::find(m_EntitiesInProximity.begin(), m_EntitiesInProximity.end(), entering->GetObjectID()); - if (iter == m_EntitiesInProximity.end()) - { - m_EntitiesInProximity.push_back(entering->GetObjectID()); - } - } - else if (status == "LEAVE") - { - const auto& iter = std::find(m_EntitiesInProximity.begin(), m_EntitiesInProximity.end(), entering->GetObjectID()); + if (iter == m_EntitiesInProximity.end()) { + m_EntitiesInProximity.push_back(entering->GetObjectID()); + } + } else if (status == "LEAVE") { + const auto& iter = std::find(m_EntitiesInProximity.begin(), m_EntitiesInProximity.end(), entering->GetObjectID()); - if (iter != m_EntitiesInProximity.end()) - { - m_EntitiesInProximity.erase(iter); - } - } + if (iter != m_EntitiesInProximity.end()) { + m_EntitiesInProximity.erase(iter); + } + } } -void NtImagBeamBuffer::OnTimerDone(Entity* self, std::string timerName) -{ - if (timerName != "BuffImag") - { - return; - } +void NtImagBeamBuffer::OnTimerDone(Entity* self, std::string timerName) { + if (timerName != "BuffImag") { + return; + } - auto* skillComponent = self->GetComponent(); + auto* skillComponent = self->GetComponent(); - if (skillComponent == nullptr) - { - return; - } + if (skillComponent == nullptr) { + return; + } - for (const auto entityID : m_EntitiesInProximity) - { - auto* entity = EntityManager::Instance()->GetEntity(entityID); + for (const auto entityID : m_EntitiesInProximity) { + auto* entity = EntityManager::Instance()->GetEntity(entityID); - if (entity == nullptr) - { - continue; - } + if (entity == nullptr) { + continue; + } - skillComponent->CalculateBehavior(1311, 30235, entityID, true); - } + skillComponent->CalculateBehavior(1311, 30235, entityID, true); + } - self->AddTimer("BuffImag", 2.0f); + self->AddTimer("BuffImag", 2.0f); } diff --git a/dScripts/NtImagBeamBuffer.h b/dScripts/NtImagBeamBuffer.h index 4c6c7fc3..38e3819c 100644 --- a/dScripts/NtImagBeamBuffer.h +++ b/dScripts/NtImagBeamBuffer.h @@ -4,10 +4,10 @@ class NtImagBeamBuffer : public CppScripts::Script { public: - void OnStartup(Entity* self) override; - void OnProximityUpdate(Entity* self, Entity* entering, std::string name, std::string status) override; - void OnTimerDone(Entity* self, std::string timerName) override; + void OnStartup(Entity* self) override; + void OnProximityUpdate(Entity* self, Entity* entering, std::string name, std::string status) override; + void OnTimerDone(Entity* self, std::string timerName) override; private: - std::vector m_EntitiesInProximity = {}; + std::vector m_EntitiesInProximity = {}; }; diff --git a/dScripts/NtOverbuildServer.cpp b/dScripts/NtOverbuildServer.cpp index 7bc62f50..8411e55b 100644 --- a/dScripts/NtOverbuildServer.cpp +++ b/dScripts/NtOverbuildServer.cpp @@ -1,30 +1,30 @@ #include "NtOverbuildServer.h" #include "EntityManager.h" -void NtOverbuildServer::SetVariables(Entity *self) { - self->SetVar(m_SpyProximityVariable, 30.0f); +void NtOverbuildServer::SetVariables(Entity* self) { + self->SetVar(m_SpyProximityVariable, 30.0f); - self->SetVar(m_SpyDataVariable, { - NT_FACTION_SPY_OVERBUILD, 13891, 1320 - }); + self->SetVar(m_SpyDataVariable, { + NT_FACTION_SPY_OVERBUILD, 13891, 1320 + }); - self->SetVar>(m_SpyDialogueTableVariable, { - { "OVERBUILD_NT_CONVO_1", 0 }, - { "OVERBUILD_NT_CONVO_2", 1 }, - { "OVERBUILD_NT_CONVO_3", 0 }, - { "OVERBUILD_NT_CONVO_4", 1 }, - { "OVERBUILD_NT_CONVO_5", 0 }, - { "OVERBUILD_NT_CONVO_6", 1 }, - { "OVERBUILD_NT_CONVO_7", 0 }, - }); + self->SetVar>(m_SpyDialogueTableVariable, { + { "OVERBUILD_NT_CONVO_1", 0 }, + { "OVERBUILD_NT_CONVO_2", 1 }, + { "OVERBUILD_NT_CONVO_3", 0 }, + { "OVERBUILD_NT_CONVO_4", 1 }, + { "OVERBUILD_NT_CONVO_5", 0 }, + { "OVERBUILD_NT_CONVO_6", 1 }, + { "OVERBUILD_NT_CONVO_7", 0 }, + }); - // Find the second object Dr. Overbuild interacts with - LWOOBJID otherConvoObjectID = LWOOBJID_EMPTY; - for (auto* otherConvoObject : EntityManager::Instance()->GetEntitiesInGroup(GeneralUtils::UTF16ToWTF8(self->GetVar(m_OtherEntitiesGroupVariable)))) { - otherConvoObjectID = otherConvoObject->GetObjectID(); - break; - } + // Find the second object Dr. Overbuild interacts with + LWOOBJID otherConvoObjectID = LWOOBJID_EMPTY; + for (auto* otherConvoObject : EntityManager::Instance()->GetEntitiesInGroup(GeneralUtils::UTF16ToWTF8(self->GetVar(m_OtherEntitiesGroupVariable)))) { + otherConvoObjectID = otherConvoObject->GetObjectID(); + break; + } - // If there's an alternating conversation, indices should be provided using the conversationID variables - self->SetVar>(m_SpyCinematicObjectsVariable, { self->GetObjectID(), otherConvoObjectID }); + // If there's an alternating conversation, indices should be provided using the conversationID variables + self->SetVar>(m_SpyCinematicObjectsVariable, { self->GetObjectID(), otherConvoObjectID }); } diff --git a/dScripts/NtOverbuildServer.h b/dScripts/NtOverbuildServer.h index 301dd4e3..a34d117e 100644 --- a/dScripts/NtOverbuildServer.h +++ b/dScripts/NtOverbuildServer.h @@ -2,6 +2,6 @@ #include "NtFactionSpyServer.h" class NtOverbuildServer : public NtFactionSpyServer { - void SetVariables(Entity *self) override; - const std::u16string m_OtherEntitiesGroupVariable = u"SpyConvo2Group"; + void SetVariables(Entity* self) override; + const std::u16string m_OtherEntitiesGroupVariable = u"SpyConvo2Group"; }; diff --git a/dScripts/NtParadoxPanelServer.cpp b/dScripts/NtParadoxPanelServer.cpp index 556002fe..06482c82 100644 --- a/dScripts/NtParadoxPanelServer.cpp +++ b/dScripts/NtParadoxPanelServer.cpp @@ -4,8 +4,7 @@ #include "EntityManager.h" #include "Character.h" -void NtParadoxPanelServer::OnUse(Entity* self, Entity* user) -{ +void NtParadoxPanelServer::OnUse(Entity* self, Entity* user) { GameMessages::SendNotifyClientObject(self->GetObjectID(), u"bActive", 1, 0, user->GetObjectID(), "", user->GetSystemAddress()); GameMessages::SendTerminateInteraction(user->GetObjectID(), eTerminateType::FROM_INTERACTION, self->GetObjectID()); @@ -16,18 +15,15 @@ void NtParadoxPanelServer::OnUse(Entity* self, Entity* user) const auto playerID = user->GetObjectID(); - for (const auto mission : tPlayerOnMissions) - { - if (missionComponent->GetMissionState(mission) != MissionState::MISSION_STATE_ACTIVE) - { + for (const auto mission : tPlayerOnMissions) { + if (missionComponent->GetMissionState(mission) != MissionState::MISSION_STATE_ACTIVE) { continue; } - self->AddCallbackTimer(2, [this, self, playerID] () { + self->AddCallbackTimer(2, [this, self, playerID]() { auto* player = EntityManager::Instance()->GetEntity(playerID); - if (player == nullptr) - { + if (player == nullptr) { return; } @@ -36,11 +32,11 @@ void NtParadoxPanelServer::OnUse(Entity* self, Entity* user) player->GetCharacter()->SetPlayerFlag(flag, true); GameMessages::SendPlayAnimation(player, u"rebuild-celebrate"); - + GameMessages::SendNotifyClientObject(self->GetObjectID(), u"SparkStop", 0, 0, player->GetObjectID(), "", player->GetSystemAddress()); GameMessages::SendSetStunned(player->GetObjectID(), eStunState::POP, player->GetSystemAddress(), LWOOBJID_EMPTY, false, false, true, false, true, true, false, false, true); self->SetVar(u"bActive", false); - }); + }); GameMessages::SendPlayAnimation(user, u"nexus-powerpanel", 6.0f); GameMessages::SendSetStunned(user->GetObjectID(), eStunState::PUSH, user->GetSystemAddress(), LWOOBJID_EMPTY, false, false, true, false, true, true, false, false, true); return; @@ -48,17 +44,16 @@ void NtParadoxPanelServer::OnUse(Entity* self, Entity* user) GameMessages::SendPlayAnimation(user, shockAnim); - const auto dir = self->GetRotation().GetRightVector(); + const auto dir = self->GetRotation().GetRightVector(); - GameMessages::SendKnockback(user->GetObjectID(), self->GetObjectID(), self->GetObjectID(), 0, {dir.x * 15, 5, dir.z * 15}); + GameMessages::SendKnockback(user->GetObjectID(), self->GetObjectID(), self->GetObjectID(), 0, { dir.x * 15, 5, dir.z * 15 }); GameMessages::SendPlayFXEffect(self, 6432, u"create", "console_sparks", LWOOBJID_EMPTY, 1.0, 1.0, true); - - self->AddCallbackTimer(2, [this, self, playerID] () { + + self->AddCallbackTimer(2, [this, self, playerID]() { auto* player = EntityManager::Instance()->GetEntity(playerID); - if (player == nullptr) - { + if (player == nullptr) { return; } @@ -67,5 +62,5 @@ void NtParadoxPanelServer::OnUse(Entity* self, Entity* user) GameMessages::SendStopFXEffect(self, true, "console_sparks"); self->SetVar(u"bActive", false); - }); + }); } diff --git a/dScripts/NtParadoxPanelServer.h b/dScripts/NtParadoxPanelServer.h index e966e376..796a599b 100644 --- a/dScripts/NtParadoxPanelServer.h +++ b/dScripts/NtParadoxPanelServer.h @@ -8,6 +8,6 @@ public: private: std::u16string shockAnim = u"knockback-recovery"; float fxTime = 2.0; - std::vector tPlayerOnMissions = {1278, 1279, 1280, 1281}; + std::vector tPlayerOnMissions = { 1278, 1279, 1280, 1281 }; }; diff --git a/dScripts/NtParadoxTeleServer.cpp b/dScripts/NtParadoxTeleServer.cpp index 84222374..8003e93f 100644 --- a/dScripts/NtParadoxTeleServer.cpp +++ b/dScripts/NtParadoxTeleServer.cpp @@ -3,125 +3,111 @@ #include "EntityManager.h" #include "MissionComponent.h" -void NtParadoxTeleServer::OnStartup(Entity* self) -{ - self->SetProximityRadius(5, "teleport"); +void NtParadoxTeleServer::OnStartup(Entity* self) { + self->SetProximityRadius(5, "teleport"); } -void NtParadoxTeleServer::OnPlayerLoaded(Entity* self, Entity* player) -{ - +void NtParadoxTeleServer::OnPlayerLoaded(Entity* self, Entity* player) { + } -void NtParadoxTeleServer::OnProximityUpdate(Entity* self, Entity* entering, std::string name, std::string status) -{ - if (status != "ENTER" || !entering->IsPlayer() || name != "teleport") return; +void NtParadoxTeleServer::OnProximityUpdate(Entity* self, Entity* entering, std::string name, std::string status) { + if (status != "ENTER" || !entering->IsPlayer() || name != "teleport") return; - auto* player = entering; - const auto playerID = player->GetObjectID(); + auto* player = entering; + const auto playerID = player->GetObjectID(); - const auto iter = m_TeleportingPlayerTable.find(playerID); - if (iter == m_TeleportingPlayerTable.end()) m_TeleportingPlayerTable[playerID] = false; - const auto bPlayerBeingTeleported = m_TeleportingPlayerTable[playerID]; + const auto iter = m_TeleportingPlayerTable.find(playerID); + if (iter == m_TeleportingPlayerTable.end()) m_TeleportingPlayerTable[playerID] = false; + const auto bPlayerBeingTeleported = m_TeleportingPlayerTable[playerID]; - if (player->IsPlayer() && !bPlayerBeingTeleported) - { - GameMessages::SendSetStunned(playerID, PUSH, player->GetSystemAddress(), LWOOBJID_EMPTY, - true, true, true, true, true, true, true - ); + if (player->IsPlayer() && !bPlayerBeingTeleported) { + GameMessages::SendSetStunned(playerID, PUSH, player->GetSystemAddress(), LWOOBJID_EMPTY, + true, true, true, true, true, true, true + ); - GameMessages::SendPlayAnimation(player, u"teledeath", 4.0f); + GameMessages::SendPlayAnimation(player, u"teledeath", 4.0f); - const auto animTime = 2; + const auto animTime = 2; - self->AddCallbackTimer(animTime, [this, self, playerID]() { - auto* player = EntityManager::Instance()->GetEntity(playerID); + self->AddCallbackTimer(animTime, [this, self, playerID]() { + auto* player = EntityManager::Instance()->GetEntity(playerID); - if (player == nullptr) - { - return; - } + if (player == nullptr) { + return; + } - TeleportPlayer(self, player); - }); - } + TeleportPlayer(self, player); + }); + } - auto* missionComponent = player->GetComponent(); + auto* missionComponent = player->GetComponent(); - if (missionComponent != nullptr) - { - missionComponent->Progress(MissionTaskType::MISSION_TASK_TYPE_SCRIPT, self->GetLOT()); - } + if (missionComponent != nullptr) { + missionComponent->Progress(MissionTaskType::MISSION_TASK_TYPE_SCRIPT, self->GetLOT()); + } } -void NtParadoxTeleServer::TeleportPlayer(Entity* self, Entity* player) -{ - auto destinationGroup = self->GetVar(u"teleGroup"); - auto* destination = self; +void NtParadoxTeleServer::TeleportPlayer(Entity* self, Entity* player) { + auto destinationGroup = self->GetVar(u"teleGroup"); + auto* destination = self; - if (!destinationGroup.empty()) - { - const auto& groupObjs = EntityManager::Instance()->GetEntitiesInGroup(GeneralUtils::UTF16ToWTF8(destinationGroup)); + if (!destinationGroup.empty()) { + const auto& groupObjs = EntityManager::Instance()->GetEntitiesInGroup(GeneralUtils::UTF16ToWTF8(destinationGroup)); - if (!groupObjs.empty()) - { - destination = groupObjs[0]; - } - } + if (!groupObjs.empty()) { + destination = groupObjs[0]; + } + } - const auto destPosition = destination->GetPosition(); - const auto destRotation = destination->GetRotation(); + const auto destPosition = destination->GetPosition(); + const auto destRotation = destination->GetRotation(); - auto teleCinematic = self->GetVar(u"Cinematic"); + auto teleCinematic = self->GetVar(u"Cinematic"); - if (!teleCinematic.empty()) - { - const auto teleCinematicUname = teleCinematic; - GameMessages::SendPlayCinematic(player->GetObjectID(), teleCinematicUname, player->GetSystemAddress()); - } + if (!teleCinematic.empty()) { + const auto teleCinematicUname = teleCinematic; + GameMessages::SendPlayCinematic(player->GetObjectID(), teleCinematicUname, player->GetSystemAddress()); + } - GameMessages::SendTeleport(player->GetObjectID(), destPosition, destRotation, player->GetSystemAddress(), true); + GameMessages::SendTeleport(player->GetObjectID(), destPosition, destRotation, player->GetSystemAddress(), true); - GameMessages::SendPlayAnimation(player, u"paradox-teleport-in", 4.0f); + GameMessages::SendPlayAnimation(player, u"paradox-teleport-in", 4.0f); - const auto animTime = 2; + const auto animTime = 2; - const auto playerID = player->GetObjectID(); - - self->AddCallbackTimer(animTime, [this, self, playerID]() { - auto* player = EntityManager::Instance()->GetEntity(playerID); + const auto playerID = player->GetObjectID(); - if (player == nullptr) - { - return; - } + self->AddCallbackTimer(animTime, [this, self, playerID]() { + auto* player = EntityManager::Instance()->GetEntity(playerID); - UnlockPlayer(self, player); - }); + if (player == nullptr) { + return; + } - const auto useSound = self->GetVar(u"sound1"); + UnlockPlayer(self, player); + }); - if (!useSound.empty()) - { - GameMessages::SendPlayNDAudioEmitter(player, player->GetSystemAddress(), useSound); - } + const auto useSound = self->GetVar(u"sound1"); + + if (!useSound.empty()) { + GameMessages::SendPlayNDAudioEmitter(player, player->GetSystemAddress(), useSound); + } } -void NtParadoxTeleServer::UnlockPlayer(Entity* self, Entity* player) -{ - const auto playerID = player->GetObjectID(); +void NtParadoxTeleServer::UnlockPlayer(Entity* self, Entity* player) { + const auto playerID = player->GetObjectID(); - m_TeleportingPlayerTable[playerID] = false; + m_TeleportingPlayerTable[playerID] = false; - GameMessages::SendSetStunned(playerID, POP, player->GetSystemAddress(), LWOOBJID_EMPTY, - true, true, true, true, true, true, true - ); + GameMessages::SendSetStunned(playerID, POP, player->GetSystemAddress(), LWOOBJID_EMPTY, + true, true, true, true, true, true, true + ); - auto teleCinematic = self->GetVar(u"Cinematic"); + auto teleCinematic = self->GetVar(u"Cinematic"); - if (!teleCinematic.empty()) - { - const auto teleCinematicUname = teleCinematic; - GameMessages::SendEndCinematic(player->GetObjectID(), teleCinematicUname, player->GetSystemAddress()); - } + if (!teleCinematic.empty()) { + const auto teleCinematicUname = teleCinematic; + GameMessages::SendEndCinematic(player->GetObjectID(), teleCinematicUname, player->GetSystemAddress()); + } } diff --git a/dScripts/NtParadoxTeleServer.h b/dScripts/NtParadoxTeleServer.h index 9f73bd85..b094411a 100644 --- a/dScripts/NtParadoxTeleServer.h +++ b/dScripts/NtParadoxTeleServer.h @@ -5,11 +5,11 @@ class NtParadoxTeleServer : public CppScripts::Script { public: void OnStartup(Entity* self) override; - void OnPlayerLoaded(Entity* self, Entity* player) override; - void OnProximityUpdate(Entity* self, Entity* entering, std::string name, std::string status) override; - void TeleportPlayer(Entity* self, Entity* player); - void UnlockPlayer(Entity* self, Entity* player); + void OnPlayerLoaded(Entity* self, Entity* player) override; + void OnProximityUpdate(Entity* self, Entity* entering, std::string name, std::string status) override; + void TeleportPlayer(Entity* self, Entity* player); + void UnlockPlayer(Entity* self, Entity* player); private: - std::map m_TeleportingPlayerTable; + std::map m_TeleportingPlayerTable; }; diff --git a/dScripts/NtSentinelWalkwayServer.cpp b/dScripts/NtSentinelWalkwayServer.cpp index 3d7c75a3..7b943172 100644 --- a/dScripts/NtSentinelWalkwayServer.cpp +++ b/dScripts/NtSentinelWalkwayServer.cpp @@ -3,47 +3,41 @@ #include "EntityManager.h" #include "MissionComponent.h" -void NtSentinelWalkwayServer::OnStartup(Entity* self) -{ - auto* phantomPhysicsComponent = self->GetComponent(); - - if (phantomPhysicsComponent == nullptr) - { - return; - } +void NtSentinelWalkwayServer::OnStartup(Entity* self) { + auto* phantomPhysicsComponent = self->GetComponent(); - auto force = self->GetVar(u"force"); + if (phantomPhysicsComponent == nullptr) { + return; + } - if (force == 0) - { - force = 115; - } + auto force = self->GetVar(u"force"); - const auto forward = self->GetRotation().GetRightVector() * -1; + if (force == 0) { + force = 115; + } - phantomPhysicsComponent->SetEffectType(0); // PUSH - phantomPhysicsComponent->SetDirectionalMultiplier(force); - phantomPhysicsComponent->SetDirection(forward); - phantomPhysicsComponent->SetPhysicsEffectActive(true); + const auto forward = self->GetRotation().GetRightVector() * -1; - EntityManager::Instance()->SerializeEntity(self); + phantomPhysicsComponent->SetEffectType(0); // PUSH + phantomPhysicsComponent->SetDirectionalMultiplier(force); + phantomPhysicsComponent->SetDirection(forward); + phantomPhysicsComponent->SetPhysicsEffectActive(true); - self->SetProximityRadius(3, "speedboost"); + EntityManager::Instance()->SerializeEntity(self); + + self->SetProximityRadius(3, "speedboost"); } -void NtSentinelWalkwayServer::OnProximityUpdate(Entity* self, Entity* entering, std::string name, std::string status) -{ - if (name != "speedboost" || !entering->IsPlayer() || status != "ENTER") - { - return; - } +void NtSentinelWalkwayServer::OnProximityUpdate(Entity* self, Entity* entering, std::string name, std::string status) { + if (name != "speedboost" || !entering->IsPlayer() || status != "ENTER") { + return; + } - auto* player = entering; + auto* player = entering; - auto* missionComponent = player->GetComponent(); + auto* missionComponent = player->GetComponent(); - if (missionComponent != nullptr) - { - missionComponent->Progress(MissionTaskType::MISSION_TASK_TYPE_SCRIPT, self->GetLOT()); - } + if (missionComponent != nullptr) { + missionComponent->Progress(MissionTaskType::MISSION_TASK_TYPE_SCRIPT, self->GetLOT()); + } } diff --git a/dScripts/NtSleepingGuard.cpp b/dScripts/NtSleepingGuard.cpp index 74bc50f0..597b5997 100644 --- a/dScripts/NtSleepingGuard.cpp +++ b/dScripts/NtSleepingGuard.cpp @@ -2,13 +2,11 @@ #include "GameMessages.h" #include "MissionComponent.h" -void NtSleepingGuard::OnStartup(Entity* self) -{ +void NtSleepingGuard::OnStartup(Entity* self) { self->SetNetworkVar(u"asleep", true); } -void NtSleepingGuard::OnEmoteReceived(Entity* self, const int32_t emote, Entity* target) -{ +void NtSleepingGuard::OnEmoteReceived(Entity* self, const int32_t emote, Entity* target) { if (!self->GetNetworkVar(u"asleep")) return; @@ -23,18 +21,15 @@ void NtSleepingGuard::OnEmoteReceived(Entity* self, const int32_t emote, Entity* auto* missionComponent = target->GetComponent(); - if (missionComponent != nullptr) - { + if (missionComponent != nullptr) { missionComponent->CompleteMission(1346); } self->AddTimer("AsleepAgain", 5.0f); } -void NtSleepingGuard::OnTimerDone(Entity* self, std::string timerName) -{ - if (timerName == "AsleepAgain") - { +void NtSleepingGuard::OnTimerDone(Entity* self, std::string timerName) { + if (timerName == "AsleepAgain") { self->SetNetworkVar(u"asleep", true); } } diff --git a/dScripts/NtVandaServer.cpp b/dScripts/NtVandaServer.cpp index 29750101..bfc35203 100644 --- a/dScripts/NtVandaServer.cpp +++ b/dScripts/NtVandaServer.cpp @@ -1,13 +1,13 @@ #include "NtVandaServer.h" #include "InventoryComponent.h" -void NtVandaServer::OnMissionDialogueOK(Entity *self, Entity *target, int missionID, MissionState missionState) { +void NtVandaServer::OnMissionDialogueOK(Entity* self, Entity* target, int missionID, MissionState missionState) { - // Removes the alien parts after completing the mission - if (missionID == m_AlienPartMissionID && missionState == MissionState::MISSION_STATE_READY_TO_COMPLETE) { - auto* inventoryComponent = target->GetComponent(); - for (const auto& alienPartLot : m_AlienPartLots) { - inventoryComponent->RemoveItem(alienPartLot, 1); - } - } + // Removes the alien parts after completing the mission + if (missionID == m_AlienPartMissionID && missionState == MissionState::MISSION_STATE_READY_TO_COMPLETE) { + auto* inventoryComponent = target->GetComponent(); + for (const auto& alienPartLot : m_AlienPartLots) { + inventoryComponent->RemoveItem(alienPartLot, 1); + } + } } diff --git a/dScripts/NtVandaServer.h b/dScripts/NtVandaServer.h index 84d494fc..69e868f5 100644 --- a/dScripts/NtVandaServer.h +++ b/dScripts/NtVandaServer.h @@ -2,7 +2,7 @@ #include "CppScripts.h" class NtVandaServer : public CppScripts::Script { - void OnMissionDialogueOK(Entity *self, Entity *target, int missionID, MissionState missionState) override; - const uint32_t m_AlienPartMissionID = 1183; - const std::vector m_AlienPartLots = { 12479, 12480, 12481 }; + void OnMissionDialogueOK(Entity* self, Entity* target, int missionID, MissionState missionState) override; + const uint32_t m_AlienPartMissionID = 1183; + const std::vector m_AlienPartLots = { 12479, 12480, 12481 }; }; diff --git a/dScripts/NtVentureCannonServer.cpp b/dScripts/NtVentureCannonServer.cpp index 66172733..d7f4cb99 100644 --- a/dScripts/NtVentureCannonServer.cpp +++ b/dScripts/NtVentureCannonServer.cpp @@ -2,133 +2,121 @@ #include "GameMessages.h" #include "EntityManager.h" -void NtVentureCannonServer::OnUse(Entity* self, Entity* user) -{ - auto* player = user; - const auto playerID = player->GetObjectID(); +void NtVentureCannonServer::OnUse(Entity* self, Entity* user) { + auto* player = user; + const auto playerID = player->GetObjectID(); - auto enterCinematic = self->GetVar(u"EnterCinematic"); + auto enterCinematic = self->GetVar(u"EnterCinematic"); - if (enterCinematic.empty()) - { - return; - } + if (enterCinematic.empty()) { + return; + } - self->SetNetworkVar(u"bIsInUse", true); + self->SetNetworkVar(u"bIsInUse", true); - GameMessages::SendSetStunned(playerID, PUSH, player->GetSystemAddress(), LWOOBJID_EMPTY, - true, true, true, true, true, true, true - ); + GameMessages::SendSetStunned(playerID, PUSH, player->GetSystemAddress(), LWOOBJID_EMPTY, + true, true, true, true, true, true, true + ); - auto destPosition = self->GetPosition(); + auto destPosition = self->GetPosition(); - destPosition.y += 5 - 1.57f; + destPosition.y += 5 - 1.57f; - auto destRotation = self->GetRotation(); - - GameMessages::SendTeleport(playerID, destPosition, destRotation, player->GetSystemAddress(), true); + auto destRotation = self->GetRotation(); - GameMessages::SendPlayAnimation(player, u"scale-down", 4.0f); + GameMessages::SendTeleport(playerID, destPosition, destRotation, player->GetSystemAddress(), true); - const auto enterCinematicUname = enterCinematic; - GameMessages::SendPlayCinematic(player->GetObjectID(), enterCinematicUname, player->GetSystemAddress()); + GameMessages::SendPlayAnimation(player, u"scale-down", 4.0f); - GameMessages::SendPlayNDAudioEmitter(player, player->GetSystemAddress(), "{e8bf79ce-7453-4a7d-b872-fee65e97ff15}"); - - self->AddCallbackTimer(3, [this, self]() { - self->SetNetworkVar(u"bIsInUse", false); - }); + const auto enterCinematicUname = enterCinematic; + GameMessages::SendPlayCinematic(player->GetObjectID(), enterCinematicUname, player->GetSystemAddress()); - self->AddCallbackTimer(1.5f, [this, self, playerID]() { - auto* player = EntityManager::Instance()->GetEntity(playerID); + GameMessages::SendPlayNDAudioEmitter(player, player->GetSystemAddress(), "{e8bf79ce-7453-4a7d-b872-fee65e97ff15}"); - if (player == nullptr) - { - return; - } + self->AddCallbackTimer(3, [this, self]() { + self->SetNetworkVar(u"bIsInUse", false); + }); - EnterCannonEnded(self, player); - }); + self->AddCallbackTimer(1.5f, [this, self, playerID]() { + auto* player = EntityManager::Instance()->GetEntity(playerID); + + if (player == nullptr) { + return; + } + + EnterCannonEnded(self, player); + }); } -void NtVentureCannonServer::EnterCannonEnded(Entity* self, Entity* player) -{ - const auto playerID = player->GetObjectID(); +void NtVentureCannonServer::EnterCannonEnded(Entity* self, Entity* player) { + const auto playerID = player->GetObjectID(); - const auto& cannonEffectGroup = EntityManager::Instance()->GetEntitiesInGroup("cannonEffect"); + const auto& cannonEffectGroup = EntityManager::Instance()->GetEntitiesInGroup("cannonEffect"); - if (!cannonEffectGroup.empty()) - { - auto* cannonEffect = cannonEffectGroup[0]; + if (!cannonEffectGroup.empty()) { + auto* cannonEffect = cannonEffectGroup[0]; - GameMessages::SendPlayFXEffect(cannonEffect, 6036, u"create", "cannon_blast", LWOOBJID_EMPTY, 1, 1, true); - - GameMessages::SendPlayEmbeddedEffectOnAllClientsNearObject(cannonEffect, u"camshake-bridge", cannonEffect->GetObjectID(), 100); - } + GameMessages::SendPlayFXEffect(cannonEffect, 6036, u"create", "cannon_blast", LWOOBJID_EMPTY, 1, 1, true); - FirePlayer(self, player); + GameMessages::SendPlayEmbeddedEffectOnAllClientsNearObject(cannonEffect, u"camshake-bridge", cannonEffect->GetObjectID(), 100); + } - auto exitCinematic = self->GetVar(u"ExitCinematic"); + FirePlayer(self, player); - if (exitCinematic.empty()) - { - UnlockCannonPlayer(self, player); + auto exitCinematic = self->GetVar(u"ExitCinematic"); - return; - } + if (exitCinematic.empty()) { + UnlockCannonPlayer(self, player); - const auto exitCinematicUname = exitCinematic; - GameMessages::SendPlayCinematic(player->GetObjectID(), exitCinematicUname, player->GetSystemAddress(), - true, true, true, false, 0, false, 0, false, false - ); + return; + } - self->AddCallbackTimer(1.5f, [this, self, playerID]() { - auto* player = EntityManager::Instance()->GetEntity(playerID); + const auto exitCinematicUname = exitCinematic; + GameMessages::SendPlayCinematic(player->GetObjectID(), exitCinematicUname, player->GetSystemAddress(), + true, true, true, false, 0, false, 0, false, false + ); - if (player == nullptr) - { - return; - } + self->AddCallbackTimer(1.5f, [this, self, playerID]() { + auto* player = EntityManager::Instance()->GetEntity(playerID); - ExitCannonEnded(self, player); - }); + if (player == nullptr) { + return; + } + + ExitCannonEnded(self, player); + }); } -void NtVentureCannonServer::ExitCannonEnded(Entity* self, Entity* player) -{ - UnlockCannonPlayer(self, player); +void NtVentureCannonServer::ExitCannonEnded(Entity* self, Entity* player) { + UnlockCannonPlayer(self, player); } -void NtVentureCannonServer::UnlockCannonPlayer(Entity* self, Entity* player) -{ - GameMessages::SendSetStunned(player->GetObjectID(), POP, player->GetSystemAddress(), LWOOBJID_EMPTY, - true, true, true, true, true, true, true - ); +void NtVentureCannonServer::UnlockCannonPlayer(Entity* self, Entity* player) { + GameMessages::SendSetStunned(player->GetObjectID(), POP, player->GetSystemAddress(), LWOOBJID_EMPTY, + true, true, true, true, true, true, true + ); - self->SetNetworkVar(u"bIsInUse", false); + self->SetNetworkVar(u"bIsInUse", false); - GameMessages::SendTerminateInteraction(player->GetObjectID(), FROM_INTERACTION, self->GetObjectID()); + GameMessages::SendTerminateInteraction(player->GetObjectID(), FROM_INTERACTION, self->GetObjectID()); } -void NtVentureCannonServer::FirePlayer(Entity* self, Entity* player) -{ - auto destinationGroup = self->GetVar(u"teleGroup"); - auto* destination = self; +void NtVentureCannonServer::FirePlayer(Entity* self, Entity* player) { + auto destinationGroup = self->GetVar(u"teleGroup"); + auto* destination = self; - if (!destinationGroup.empty()) - { - const auto& groupObjs = EntityManager::Instance()->GetEntitiesInGroup(GeneralUtils::UTF16ToWTF8(destinationGroup)); + if (!destinationGroup.empty()) { + const auto& groupObjs = EntityManager::Instance()->GetEntitiesInGroup(GeneralUtils::UTF16ToWTF8(destinationGroup)); - if (!groupObjs.empty()) - { - destination = groupObjs[0]; - } - } + if (!groupObjs.empty()) { + destination = groupObjs[0]; + } + } - const auto destPosition = destination->GetPosition(); - const auto destRotation = destination->GetRotation(); + const auto destPosition = destination->GetPosition(); + const auto destRotation = destination->GetRotation(); - GameMessages::SendTeleport(player->GetObjectID(), destPosition, destRotation, player->GetSystemAddress(), true); + GameMessages::SendTeleport(player->GetObjectID(), destPosition, destRotation, player->GetSystemAddress(), true); - GameMessages::SendPlayAnimation(player, u"venture-cannon-out", 4.0f); + GameMessages::SendPlayAnimation(player, u"venture-cannon-out", 4.0f); } diff --git a/dScripts/NtVentureCannonServer.h b/dScripts/NtVentureCannonServer.h index 5ad6a54e..a5998f14 100644 --- a/dScripts/NtVentureCannonServer.h +++ b/dScripts/NtVentureCannonServer.h @@ -4,9 +4,9 @@ class NtVentureCannonServer : public CppScripts::Script { public: - void OnUse(Entity* self, Entity* user) override; - void EnterCannonEnded(Entity* self, Entity* player); - void ExitCannonEnded(Entity* self, Entity* player); - void UnlockCannonPlayer(Entity* self, Entity* player); - void FirePlayer(Entity* self, Entity* player); + void OnUse(Entity* self, Entity* user) override; + void EnterCannonEnded(Entity* self, Entity* player); + void ExitCannonEnded(Entity* self, Entity* player); + void UnlockCannonPlayer(Entity* self, Entity* player); + void FirePlayer(Entity* self, Entity* player); }; diff --git a/dScripts/NtVentureSpeedPadServer.cpp b/dScripts/NtVentureSpeedPadServer.cpp index 19a752d2..0995d1df 100644 --- a/dScripts/NtVentureSpeedPadServer.cpp +++ b/dScripts/NtVentureSpeedPadServer.cpp @@ -2,32 +2,27 @@ #include "SkillComponent.h" #include "MissionComponent.h" -void NtVentureSpeedPadServer::OnStartup(Entity* self) -{ - self->SetProximityRadius(3, "speedboost"); +void NtVentureSpeedPadServer::OnStartup(Entity* self) { + self->SetProximityRadius(3, "speedboost"); } -void NtVentureSpeedPadServer::OnProximityUpdate(Entity* self, Entity* entering, std::string name, std::string status) -{ - if (name != "speedboost" || !entering->IsPlayer() || status != "ENTER") - { - return; - } +void NtVentureSpeedPadServer::OnProximityUpdate(Entity* self, Entity* entering, std::string name, std::string status) { + if (name != "speedboost" || !entering->IsPlayer() || status != "ENTER") { + return; + } - auto* player = entering; + auto* player = entering; - auto* missionComponent = player->GetComponent(); + auto* missionComponent = player->GetComponent(); - if (missionComponent != nullptr) - { - missionComponent->Progress(MissionTaskType::MISSION_TASK_TYPE_SCRIPT, self->GetLOT()); - } + if (missionComponent != nullptr) { + missionComponent->Progress(MissionTaskType::MISSION_TASK_TYPE_SCRIPT, self->GetLOT()); + } - auto* skillComponent = player->GetComponent(); + auto* skillComponent = player->GetComponent(); - if (skillComponent != nullptr) - { - skillComponent->CalculateBehavior(927, 18913, player->GetObjectID(), true); - } + if (skillComponent != nullptr) { + skillComponent->CalculateBehavior(927, 18913, player->GetObjectID(), true); + } } diff --git a/dScripts/NtXRayServer.cpp b/dScripts/NtXRayServer.cpp index b65cf65b..3b281b79 100644 --- a/dScripts/NtXRayServer.cpp +++ b/dScripts/NtXRayServer.cpp @@ -1,14 +1,12 @@ #include "NtXRayServer.h" #include "SkillComponent.h" -void NtXRayServer::OnCollisionPhantom(Entity* self, Entity* target) -{ - auto* skillComponent = target->GetComponent(); - - if (skillComponent == nullptr) - { - return; - } +void NtXRayServer::OnCollisionPhantom(Entity* self, Entity* target) { + auto* skillComponent = target->GetComponent(); - skillComponent->CalculateBehavior(1220, 27641, target->GetObjectID()); + if (skillComponent == nullptr) { + return; + } + + skillComponent->CalculateBehavior(1220, 27641, target->GetObjectID()); } diff --git a/dScripts/PersonalFortress.cpp b/dScripts/PersonalFortress.cpp index 88ac9163..e7e89e80 100644 --- a/dScripts/PersonalFortress.cpp +++ b/dScripts/PersonalFortress.cpp @@ -4,54 +4,47 @@ #include "DestroyableComponent.h" #include "EntityManager.h" -void PersonalFortress::OnStartup(Entity* self) -{ - auto* owner = self->GetOwner(); - self->AddTimer("FireSkill", 1.5); - GameMessages::SendSetStunned(owner->GetObjectID(), PUSH, owner->GetSystemAddress(), LWOOBJID_EMPTY, - true, true, true, true, true, true, true, true, true - ); - - auto* destroyableComponent = owner->GetComponent(); +void PersonalFortress::OnStartup(Entity* self) { + auto* owner = self->GetOwner(); + self->AddTimer("FireSkill", 1.5); + GameMessages::SendSetStunned(owner->GetObjectID(), PUSH, owner->GetSystemAddress(), LWOOBJID_EMPTY, + true, true, true, true, true, true, true, true, true + ); - if (destroyableComponent != nullptr) - { - destroyableComponent->PushImmunity(); - } + auto* destroyableComponent = owner->GetComponent(); - EntityManager::Instance()->SerializeEntity(owner); + if (destroyableComponent != nullptr) { + destroyableComponent->PushImmunity(); + } + + EntityManager::Instance()->SerializeEntity(owner); } -void PersonalFortress::OnDie(Entity* self, Entity* killer) -{ - auto* owner = self->GetOwner(); - GameMessages::SendSetStunned(owner->GetObjectID(), POP, owner->GetSystemAddress(), LWOOBJID_EMPTY, - true, true, true, true, true, true, true, true, true - ); +void PersonalFortress::OnDie(Entity* self, Entity* killer) { + auto* owner = self->GetOwner(); + GameMessages::SendSetStunned(owner->GetObjectID(), POP, owner->GetSystemAddress(), LWOOBJID_EMPTY, + true, true, true, true, true, true, true, true, true + ); - auto* destroyableComponent = owner->GetComponent(); + auto* destroyableComponent = owner->GetComponent(); - if (destroyableComponent != nullptr) - { - destroyableComponent->PopImmunity(); - } + if (destroyableComponent != nullptr) { + destroyableComponent->PopImmunity(); + } - EntityManager::Instance()->SerializeEntity(owner); + EntityManager::Instance()->SerializeEntity(owner); } -void PersonalFortress::OnTimerDone(Entity* self, std::string timerName) -{ - if (timerName == "FireSkill") - { - auto* owner = self->GetOwner(); +void PersonalFortress::OnTimerDone(Entity* self, std::string timerName) { + if (timerName == "FireSkill") { + auto* owner = self->GetOwner(); - auto* skillComponent = self->GetComponent(); + auto* skillComponent = self->GetComponent(); - if (skillComponent == nullptr) - { - return; - } + if (skillComponent == nullptr) { + return; + } - skillComponent->CalculateBehavior(650, 13364, LWOOBJID_EMPTY, true, false); - } + skillComponent->CalculateBehavior(650, 13364, LWOOBJID_EMPTY, true, false); + } } diff --git a/dScripts/PersonalFortress.h b/dScripts/PersonalFortress.h index 5cae24ba..4d69ba1d 100644 --- a/dScripts/PersonalFortress.h +++ b/dScripts/PersonalFortress.h @@ -6,7 +6,7 @@ class PersonalFortress : public CppScripts::Script public: void OnStartup(Entity* self) override; - void OnDie(Entity* self, Entity* killer) override; + void OnDie(Entity* self, Entity* killer) override; - void OnTimerDone(Entity* self, std::string timerName) override; + void OnTimerDone(Entity* self, std::string timerName) override; }; diff --git a/dScripts/PetDigBuild.cpp b/dScripts/PetDigBuild.cpp index 7ff88fff..ae159575 100644 --- a/dScripts/PetDigBuild.cpp +++ b/dScripts/PetDigBuild.cpp @@ -3,47 +3,47 @@ #include "MissionComponent.h" void PetDigBuild::OnRebuildComplete(Entity* self, Entity* target) { - auto flagNumber = self->GetVar(u"flagNum"); + auto flagNumber = self->GetVar(u"flagNum"); - EntityInfo info {}; - auto pos = self->GetPosition(); - pos.SetY(pos.GetY() + 0.5f); - info.pos = pos; - info.rot = self->GetRotation(); - info.spawnerID = self->GetSpawnerID(); - info.settings = { - new LDFData(u"builder", target->GetObjectID()), - new LDFData(u"X", self->GetObjectID()) - }; + EntityInfo info{}; + auto pos = self->GetPosition(); + pos.SetY(pos.GetY() + 0.5f); + info.pos = pos; + info.rot = self->GetRotation(); + info.spawnerID = self->GetSpawnerID(); + info.settings = { + new LDFData(u"builder", target->GetObjectID()), + new LDFData(u"X", self->GetObjectID()) + }; - if (!flagNumber.empty()) { - info.lot = 7410; // Normal GF treasure - info.settings.push_back(new LDFData(u"groupID", u"Flag" + flagNumber)); - } else { - auto* missionComponent = target->GetComponent(); - if (missionComponent != nullptr && missionComponent->GetMissionState(746) == MissionState::MISSION_STATE_ACTIVE) { - info.lot = 9307; // Special Captain Jack treasure that drops a mission item - } else { - info.lot = 3495; // Normal AG treasure - } - } + if (!flagNumber.empty()) { + info.lot = 7410; // Normal GF treasure + info.settings.push_back(new LDFData(u"groupID", u"Flag" + flagNumber)); + } else { + auto* missionComponent = target->GetComponent(); + if (missionComponent != nullptr && missionComponent->GetMissionState(746) == MissionState::MISSION_STATE_ACTIVE) { + info.lot = 9307; // Special Captain Jack treasure that drops a mission item + } else { + info.lot = 3495; // Normal AG treasure + } + } - auto* treasure = EntityManager::Instance()->CreateEntity(info); - EntityManager::Instance()->ConstructEntity(treasure); - self->SetVar(u"chestObj", treasure->GetObjectID()); + auto* treasure = EntityManager::Instance()->CreateEntity(info); + EntityManager::Instance()->ConstructEntity(treasure); + self->SetVar(u"chestObj", treasure->GetObjectID()); } void PetDigBuild::OnDie(Entity* self, Entity* killer) { - auto treasureID = self->GetVar(u"chestObj"); - if (treasureID == LWOOBJID_EMPTY) - return; + auto treasureID = self->GetVar(u"chestObj"); + if (treasureID == LWOOBJID_EMPTY) + return; - auto treasure = EntityManager::Instance()->GetEntity(treasureID); - if (treasure == nullptr) - return; + auto treasure = EntityManager::Instance()->GetEntity(treasureID); + if (treasure == nullptr) + return; - // If the quick build expired and the treasure was not collected, hide the treasure - if (!treasure->GetIsDead()) { - treasure->Smash(self->GetObjectID(), SILENT); - } + // If the quick build expired and the treasure was not collected, hide the treasure + if (!treasure->GetIsDead()) { + treasure->Smash(self->GetObjectID(), SILENT); + } } diff --git a/dScripts/PetDigBuild.h b/dScripts/PetDigBuild.h index c70d9e84..f342d7bb 100644 --- a/dScripts/PetDigBuild.h +++ b/dScripts/PetDigBuild.h @@ -4,6 +4,6 @@ class PetDigBuild : public CppScripts::Script { public: - void OnRebuildComplete(Entity* self, Entity* target); - void OnDie(Entity* self, Entity* killer); + void OnRebuildComplete(Entity* self, Entity* target); + void OnDie(Entity* self, Entity* killer); }; diff --git a/dScripts/PetDigServer.cpp b/dScripts/PetDigServer.cpp index dc7e85dd..e26b079a 100644 --- a/dScripts/PetDigServer.cpp +++ b/dScripts/PetDigServer.cpp @@ -5,154 +5,151 @@ #include "Character.h" #include "PetComponent.h" -std::vector PetDigServer::treasures {}; +std::vector PetDigServer::treasures{}; -const DigInfo PetDigServer::defaultDigInfo = DigInfo { 3495, -1, -1, false, false, false, false }; +const DigInfo PetDigServer::defaultDigInfo = DigInfo{ 3495, -1, -1, false, false, false, false }; /** * Summary of all the special treasure behaviors, indexed by their lot */ -const std::map PetDigServer::digInfoMap { - // Regular treasures - {3495, defaultDigInfo}, +const std::map PetDigServer::digInfoMap{ + // Regular treasures + {3495, defaultDigInfo}, - // Pet cove treasure - {7612, DigInfo { 7612, -1, -1, false, false, false, false }}, + // Pet cove treasure + {7612, DigInfo { 7612, -1, -1, false, false, false, false }}, - // Gnarled Forest flag treasure - {7410, DigInfo { 7410, -1, -1, false, true, false, false }}, + // Gnarled Forest flag treasure + {7410, DigInfo { 7410, -1, -1, false, true, false, false }}, - // Gnarled Forest crab treasure - {9308, DigInfo { 9308, 7694, -1, false, false, false, false }}, + // Gnarled Forest crab treasure + {9308, DigInfo { 9308, 7694, -1, false, false, false, false }}, - // Avant Gardens mission treasure - {9307, DigInfo { 9307, -1, -1, false, true, false, true }}, + // Avant Gardens mission treasure + {9307, DigInfo { 9307, -1, -1, false, true, false, true }}, - // Avant Gardens bouncer treasure - {7559, DigInfo { 7559, -1, -1, false, false, true, false }}, + // Avant Gardens bouncer treasure + {7559, DigInfo { 7559, -1, -1, false, false, true, false }}, - // Crux Prime dragon treasure - {13098, DigInfo { 13098, 13067, 1298, false, false, false, false }}, + // Crux Prime dragon treasure + {13098, DigInfo { 13098, 13067, 1298, false, false, false, false }}, - // Bone treasure (can only be digged using the dragon) - {12192, DigInfo { 12192, -1, -1, true, false, false, false }}, + // Bone treasure (can only be digged using the dragon) + {12192, DigInfo { 12192, -1, -1, true, false, false, false }}, }; -void PetDigServer::OnStartup(Entity* self) -{ - treasures.push_back(self->GetObjectID()); - const auto digInfoIterator = digInfoMap.find(self->GetLOT()); - const auto digInfo = digInfoIterator != digInfoMap.end() ? digInfoIterator->second : defaultDigInfo; +void PetDigServer::OnStartup(Entity* self) { + treasures.push_back(self->GetObjectID()); + const auto digInfoIterator = digInfoMap.find(self->GetLOT()); + const auto digInfo = digInfoIterator != digInfoMap.end() ? digInfoIterator->second : defaultDigInfo; - // Reset any bouncers that might've been created by the previous dig - if (digInfo.bouncer) { - auto bounceNumber = GeneralUtils::UTF16ToWTF8(self->GetVar(u"BouncerNumber")); - auto bouncerSpawners = dZoneManager::Instance()->GetSpawnersByName("PetBouncer" + bounceNumber); - auto switchSpawners = dZoneManager::Instance()->GetSpawnersByName("PetBouncerSwitch" + bounceNumber); + // Reset any bouncers that might've been created by the previous dig + if (digInfo.bouncer) { + auto bounceNumber = GeneralUtils::UTF16ToWTF8(self->GetVar(u"BouncerNumber")); + auto bouncerSpawners = dZoneManager::Instance()->GetSpawnersByName("PetBouncer" + bounceNumber); + auto switchSpawners = dZoneManager::Instance()->GetSpawnersByName("PetBouncerSwitch" + bounceNumber); - for (auto* bouncerSpawner : bouncerSpawners) { - for (auto* bouncer : bouncerSpawner->m_Info.nodes) - bouncerSpawner->Deactivate(); - bouncerSpawner->Reset(); - } + for (auto* bouncerSpawner : bouncerSpawners) { + for (auto* bouncer : bouncerSpawner->m_Info.nodes) + bouncerSpawner->Deactivate(); + bouncerSpawner->Reset(); + } - for (auto* switchSpawner : switchSpawners) { - switchSpawner->Deactivate(); - switchSpawner->Reset(); - } - } + for (auto* switchSpawner : switchSpawners) { + switchSpawner->Deactivate(); + switchSpawner->Reset(); + } + } } -void PetDigServer::OnDie(Entity* self, Entity* killer) -{ - const auto iterator = std::find(treasures.begin(), treasures.end(), self->GetObjectID()); - if (iterator != treasures.end()) - { - treasures.erase(iterator); - } +void PetDigServer::OnDie(Entity* self, Entity* killer) { + const auto iterator = std::find(treasures.begin(), treasures.end(), self->GetObjectID()); + if (iterator != treasures.end()) { + treasures.erase(iterator); + } - auto* owner = killer->GetOwner(); - const auto digInfoIterator = digInfoMap.find(self->GetLOT()); - const auto digInfo = digInfoIterator != digInfoMap.end() ? digInfoIterator->second : defaultDigInfo; + auto* owner = killer->GetOwner(); + const auto digInfoIterator = digInfoMap.find(self->GetLOT()); + const auto digInfo = digInfoIterator != digInfoMap.end() ? digInfoIterator->second : defaultDigInfo; - if (digInfo.spawnLot >= 0) { - PetDigServer::SpawnPet(self, owner, digInfo); - } else if (digInfo.builderOnly) { + if (digInfo.spawnLot >= 0) { + PetDigServer::SpawnPet(self, owner, digInfo); + } else if (digInfo.builderOnly) { - // Some treasures may only be retrieved by the player that built the diggable - auto builder = self->GetVar(u"builder"); // Set by the pet dig build script - if (builder != owner->GetObjectID()) - return; - } else if (digInfo.xBuild) { - PetDigServer::HandleXBuildDig(self, owner, killer); - return; - } else if (digInfo.bouncer) { - PetDigServer::HandleBouncerDig(self, owner); - } + // Some treasures may only be retrieved by the player that built the diggable + auto builder = self->GetVar(u"builder"); // Set by the pet dig build script + if (builder != owner->GetObjectID()) + return; + } else if (digInfo.xBuild) { + PetDigServer::HandleXBuildDig(self, owner, killer); + return; + } else if (digInfo.bouncer) { + PetDigServer::HandleBouncerDig(self, owner); + } - PetDigServer::ProgressPetDigMissions(owner, self); + PetDigServer::ProgressPetDigMissions(owner, self); - self->SetNetworkVar(u"treasure_dug", true); - // TODO: Reset other pets + self->SetNetworkVar(u"treasure_dug", true); + // TODO: Reset other pets - // Handles smashing leftovers (edge case for the AG X) - auto* xObject = EntityManager::Instance()->GetEntity(self->GetVar(u"X")); - if (xObject != nullptr) { - xObject->Smash(xObject->GetObjectID(), VIOLENT); - } + // Handles smashing leftovers (edge case for the AG X) + auto* xObject = EntityManager::Instance()->GetEntity(self->GetVar(u"X")); + if (xObject != nullptr) { + xObject->Smash(xObject->GetObjectID(), VIOLENT); + } } -void PetDigServer::HandleXBuildDig(const Entity *self, Entity *owner, Entity* pet) { - auto playerID = self->GetVar(u"builder"); - if (playerID == LWOOBJID_EMPTY || playerID != owner->GetObjectID()) - return; +void PetDigServer::HandleXBuildDig(const Entity* self, Entity* owner, Entity* pet) { + auto playerID = self->GetVar(u"builder"); + if (playerID == LWOOBJID_EMPTY || playerID != owner->GetObjectID()) + return; - auto* playerEntity = EntityManager::Instance()->GetEntity(playerID); - if (!playerEntity || !playerEntity->GetParentUser() || !playerEntity->GetParentUser()->GetLastUsedChar()) - return; + auto* playerEntity = EntityManager::Instance()->GetEntity(playerID); + if (!playerEntity || !playerEntity->GetParentUser() || !playerEntity->GetParentUser()->GetLastUsedChar()) + return; - auto* player = playerEntity->GetCharacter(); - const auto groupID = self->GetVar(u"groupID"); - auto playerFlag = 0; + auto* player = playerEntity->GetCharacter(); + const auto groupID = self->GetVar(u"groupID"); + auto playerFlag = 0; - // The flag that the player dug up - if (groupID == u"Flag1") { - playerFlag = 61; - } else if (groupID == u"Flag2") { - playerFlag = 62; - } else if (groupID == u"Flag3") { - playerFlag = 63; - } + // The flag that the player dug up + if (groupID == u"Flag1") { + playerFlag = 61; + } else if (groupID == u"Flag2") { + playerFlag = 62; + } else if (groupID == u"Flag3") { + playerFlag = 63; + } - // If the player doesn't have the flag yet - if (playerFlag != 0 && !player->GetPlayerFlag(playerFlag)) { - auto* petComponent = pet->GetComponent(); - if (petComponent != nullptr) { - // TODO: Pet state = 9 ?? - } + // If the player doesn't have the flag yet + if (playerFlag != 0 && !player->GetPlayerFlag(playerFlag)) { + auto* petComponent = pet->GetComponent(); + if (petComponent != nullptr) { + // TODO: Pet state = 9 ?? + } - // Shows the flag object to the player - player->SetPlayerFlag(playerFlag, true); - } + // Shows the flag object to the player + player->SetPlayerFlag(playerFlag, true); + } - auto* xObject = EntityManager::Instance()->GetEntity(self->GetVar(u"X")); - if (xObject != nullptr) { - xObject->Smash(xObject->GetObjectID(), VIOLENT); - } + auto* xObject = EntityManager::Instance()->GetEntity(self->GetVar(u"X")); + if (xObject != nullptr) { + xObject->Smash(xObject->GetObjectID(), VIOLENT); + } } -void PetDigServer::HandleBouncerDig(const Entity *self, const Entity *owner) { - auto bounceNumber = GeneralUtils::UTF16ToWTF8(self->GetVar(u"BouncerNumber")); - auto bouncerSpawners = dZoneManager::Instance()->GetSpawnersByName("PetBouncer" + bounceNumber); - auto switchSpawners = dZoneManager::Instance()->GetSpawnersByName("PetBouncerSwitch" + bounceNumber); +void PetDigServer::HandleBouncerDig(const Entity* self, const Entity* owner) { + auto bounceNumber = GeneralUtils::UTF16ToWTF8(self->GetVar(u"BouncerNumber")); + auto bouncerSpawners = dZoneManager::Instance()->GetSpawnersByName("PetBouncer" + bounceNumber); + auto switchSpawners = dZoneManager::Instance()->GetSpawnersByName("PetBouncerSwitch" + bounceNumber); - for (auto* bouncerSpawner : bouncerSpawners) { - bouncerSpawner->Activate(); - } + for (auto* bouncerSpawner : bouncerSpawners) { + bouncerSpawner->Activate(); + } - for (auto* switchSpawner : switchSpawners) { - switchSpawner->Activate(); - } + for (auto* switchSpawner : switchSpawners) { + switchSpawner->Activate(); + } } /** @@ -160,33 +157,30 @@ void PetDigServer::HandleBouncerDig(const Entity *self, const Entity *owner) { * \param owner the owner that just made a pet dig something up */ void PetDigServer::ProgressPetDigMissions(const Entity* owner, const Entity* chest) { - auto* missionComponent = owner->GetComponent(); + auto* missionComponent = owner->GetComponent(); - if (missionComponent != nullptr) - { - // Can You Dig It progress - const auto digMissionState = missionComponent->GetMissionState(843); - if (digMissionState == MissionState::MISSION_STATE_ACTIVE) - { - missionComponent->ForceProgress(843, 1216, 1); - } + if (missionComponent != nullptr) { + // Can You Dig It progress + const auto digMissionState = missionComponent->GetMissionState(843); + if (digMissionState == MissionState::MISSION_STATE_ACTIVE) { + missionComponent->ForceProgress(843, 1216, 1); + } - // Pet Excavator progress - const auto excavatorMissionState = missionComponent->GetMissionState(505); - if (excavatorMissionState == MissionState::MISSION_STATE_ACTIVE) - { - if (chest->HasVar(u"PetDig")) { - int32_t playerFlag = 1260 + chest->GetVarAs(u"PetDig"); - Character* player = owner->GetCharacter(); + // Pet Excavator progress + const auto excavatorMissionState = missionComponent->GetMissionState(505); + if (excavatorMissionState == MissionState::MISSION_STATE_ACTIVE) { + if (chest->HasVar(u"PetDig")) { + int32_t playerFlag = 1260 + chest->GetVarAs(u"PetDig"); + Character* player = owner->GetCharacter(); - // check if player flag is set - if (!player->GetPlayerFlag(playerFlag)) { - missionComponent->ForceProgress(505, 767, 1); - player->SetPlayerFlag(playerFlag, 1); - } - } - } - } + // check if player flag is set + if (!player->GetPlayerFlag(playerFlag)) { + missionComponent->ForceProgress(505, 767, 1); + player->SetPlayerFlag(playerFlag, 1); + } + } + } + } } /** @@ -195,45 +189,42 @@ void PetDigServer::ProgressPetDigMissions(const Entity* owner, const Entity* che * \param digInfo information regarding the treasure, will also contain info about the pet to spawn */ void PetDigServer::SpawnPet(Entity* self, const Entity* owner, const DigInfo digInfo) { - // Some treasures require a mission to be active - if (digInfo.requiredMission >= 0) { - auto* missionComponent = owner->GetComponent(); - if (missionComponent != nullptr && missionComponent->GetMissionState(digInfo.requiredMission) < MissionState::MISSION_STATE_ACTIVE) { - return; - } - } + // Some treasures require a mission to be active + if (digInfo.requiredMission >= 0) { + auto* missionComponent = owner->GetComponent(); + if (missionComponent != nullptr && missionComponent->GetMissionState(digInfo.requiredMission) < MissionState::MISSION_STATE_ACTIVE) { + return; + } + } - EntityInfo info {}; - info.lot = digInfo.spawnLot; - info.pos = self->GetPosition(); - info.rot = self->GetRotation(); - info.spawnerID = self->GetSpawnerID(); - info.settings = { - new LDFData(u"tamer", owner->GetObjectID()), - new LDFData(u"group", "pet" + std::to_string(owner->GetObjectID())), - new LDFData(u"spawnAnim", "spawn-pet"), - new LDFData(u"spawnTimer", 1.0) - }; + EntityInfo info{}; + info.lot = digInfo.spawnLot; + info.pos = self->GetPosition(); + info.rot = self->GetRotation(); + info.spawnerID = self->GetSpawnerID(); + info.settings = { + new LDFData(u"tamer", owner->GetObjectID()), + new LDFData(u"group", "pet" + std::to_string(owner->GetObjectID())), + new LDFData(u"spawnAnim", "spawn-pet"), + new LDFData(u"spawnTimer", 1.0) + }; - auto* spawnedPet = EntityManager::Instance()->CreateEntity(info); - EntityManager::Instance()->ConstructEntity(spawnedPet); + auto* spawnedPet = EntityManager::Instance()->CreateEntity(info); + EntityManager::Instance()->ConstructEntity(spawnedPet); } -Entity* PetDigServer::GetClosestTresure(NiPoint3 position) -{ - float closestDistance = 0; +Entity* PetDigServer::GetClosestTresure(NiPoint3 position) { + float closestDistance = 0; Entity* closest = nullptr; - for (const auto tresureId : treasures) - { - auto* tresure = EntityManager::Instance()->GetEntity(tresureId); + for (const auto tresureId : treasures) { + auto* tresure = EntityManager::Instance()->GetEntity(tresureId); - if (tresure == nullptr) continue; + if (tresure == nullptr) continue; float distance = Vector3::DistanceSquared(tresure->GetPosition(), position); - if (closest == nullptr || distance < closestDistance) - { + if (closest == nullptr || distance < closestDistance) { closestDistance = distance; closest = tresure; } diff --git a/dScripts/PetDigServer.h b/dScripts/PetDigServer.h index 968ca50d..1122517b 100644 --- a/dScripts/PetDigServer.h +++ b/dScripts/PetDigServer.h @@ -2,29 +2,29 @@ #include "CppScripts.h" struct DigInfo { - LOT digLot; // The lot of the chest - LOT spawnLot; // Option lot of pet to spawn - int32_t requiredMission; // Optional mission required before pet can be spawned, if < 0 == don't use - bool specificPet; // This treasure requires a specific pet to be dug up - bool xBuild; // This treasure is retrieved from a buildable cross - bool bouncer; // This treasure spawns a bouncer - bool builderOnly; // Only the builder of this diggable may access the rewards, for example with crosses + LOT digLot; // The lot of the chest + LOT spawnLot; // Option lot of pet to spawn + int32_t requiredMission; // Optional mission required before pet can be spawned, if < 0 == don't use + bool specificPet; // This treasure requires a specific pet to be dug up + bool xBuild; // This treasure is retrieved from a buildable cross + bool bouncer; // This treasure spawns a bouncer + bool builderOnly; // Only the builder of this diggable may access the rewards, for example with crosses }; class PetDigServer : public CppScripts::Script { public: - void OnStartup(Entity* self) override; - void OnDie(Entity* self, Entity* killer) override; + void OnStartup(Entity* self) override; + void OnDie(Entity* self, Entity* killer) override; static Entity* GetClosestTresure(NiPoint3 position); private: - static void ProgressPetDigMissions(const Entity* owner, const Entity* chest); - static void SpawnPet(Entity* self, const Entity* owner, DigInfo digInfo); - static void HandleXBuildDig(const Entity* self, Entity* owner, Entity* pet); - static void HandleBouncerDig(const Entity* self, const Entity* owner); - static std::vector treasures; - static const DigInfo defaultDigInfo; - static const std::map digInfoMap; + static void ProgressPetDigMissions(const Entity* owner, const Entity* chest); + static void SpawnPet(Entity* self, const Entity* owner, DigInfo digInfo); + static void HandleXBuildDig(const Entity* self, Entity* owner, Entity* pet); + static void HandleBouncerDig(const Entity* self, const Entity* owner); + static std::vector treasures; + static const DigInfo defaultDigInfo; + static const std::map digInfoMap; }; diff --git a/dScripts/PetFromDigServer.cpp b/dScripts/PetFromDigServer.cpp index 235f6f8b..5aca7486 100644 --- a/dScripts/PetFromDigServer.cpp +++ b/dScripts/PetFromDigServer.cpp @@ -2,43 +2,43 @@ #include "PetComponent.h" void PetFromDigServer::OnStartup(Entity* self) { - auto* petComponent = self->GetComponent(); - if (petComponent == nullptr || petComponent->GetOwner() != nullptr) - return; + auto* petComponent = self->GetComponent(); + if (petComponent == nullptr || petComponent->GetOwner() != nullptr) + return; - // Triggers the local dig pet script for taming etc. - auto tamer = self->GetVar(u"tamer"); + // Triggers the local dig pet script for taming etc. + auto tamer = self->GetVar(u"tamer"); - // Client compares this with player:GetID() which is a string, so we'll have to give it a string - self->SetNetworkVar(u"pettamer", std::to_string(tamer)); + // Client compares this with player:GetID() which is a string, so we'll have to give it a string + self->SetNetworkVar(u"pettamer", std::to_string(tamer)); - // Kill if the player decides that the dig pet is not worthy - self->AddTimer("killself", 45.0f); + // Kill if the player decides that the dig pet is not worthy + self->AddTimer("killself", 45.0f); } void PetFromDigServer::OnTimerDone(Entity* self, std::string timerName) { - if (timerName == "killself") { + if (timerName == "killself") { - // Don't accidentally kill a pet that is already owned - auto* petComponent = self->GetComponent(); - if (petComponent == nullptr || petComponent->GetOwner() != nullptr) - return; + // Don't accidentally kill a pet that is already owned + auto* petComponent = self->GetComponent(); + if (petComponent == nullptr || petComponent->GetOwner() != nullptr) + return; - self->Smash(self->GetObjectID(), SILENT); - } + self->Smash(self->GetObjectID(), SILENT); + } } void PetFromDigServer::OnNotifyPetTamingMinigame(Entity* self, Entity* tamer, eNotifyType type) { - if (type == NOTIFY_TYPE_BEGIN) { - self->CancelTimer("killself"); - } else if (type == NOTIFY_TYPE_QUIT || type == NOTIFY_TYPE_FAILED) { - self->Smash(self->GetObjectID(), SILENT); - } else if (type == NOTIFY_TYPE_SUCCESS) { - auto* petComponent = self->GetComponent(); - if (petComponent == nullptr) - return; - // TODO: Remove custom group? - // Command the pet to the player as it may otherwise go to its spawn point which is non existant - // petComponent->Command(NiPoint3::ZERO, LWOOBJID_EMPTY, 6, 202, true); - } + if (type == NOTIFY_TYPE_BEGIN) { + self->CancelTimer("killself"); + } else if (type == NOTIFY_TYPE_QUIT || type == NOTIFY_TYPE_FAILED) { + self->Smash(self->GetObjectID(), SILENT); + } else if (type == NOTIFY_TYPE_SUCCESS) { + auto* petComponent = self->GetComponent(); + if (petComponent == nullptr) + return; + // TODO: Remove custom group? + // Command the pet to the player as it may otherwise go to its spawn point which is non existant + // petComponent->Command(NiPoint3::ZERO, LWOOBJID_EMPTY, 6, 202, true); + } } diff --git a/dScripts/PetFromDigServer.h b/dScripts/PetFromDigServer.h index e4a69a71..3faf248d 100644 --- a/dScripts/PetFromDigServer.h +++ b/dScripts/PetFromDigServer.h @@ -4,7 +4,7 @@ class PetFromDigServer : public CppScripts::Script { public: - void OnStartup(Entity* self) override; - void OnTimerDone(Entity* self, std::string timerName) override; - void OnNotifyPetTamingMinigame(Entity* self, Entity* tamer, eNotifyType type) override; + void OnStartup(Entity* self) override; + void OnTimerDone(Entity* self, std::string timerName) override; + void OnNotifyPetTamingMinigame(Entity* self, Entity* tamer, eNotifyType type) override; }; diff --git a/dScripts/PetFromObjectServer.cpp b/dScripts/PetFromObjectServer.cpp index 4658fcce..899b394a 100644 --- a/dScripts/PetFromObjectServer.cpp +++ b/dScripts/PetFromObjectServer.cpp @@ -1,34 +1,34 @@ #include "PetFromObjectServer.h" #include "PetComponent.h" -void PetFromObjectServer::OnStartup(Entity *self) { - self->SetNetworkVar(u"pettamer", std::to_string(self->GetVar(u"tamer"))); - self->AddTimer("killSelf", 45.0f); +void PetFromObjectServer::OnStartup(Entity* self) { + self->SetNetworkVar(u"pettamer", std::to_string(self->GetVar(u"tamer"))); + self->AddTimer("killSelf", 45.0f); } -void PetFromObjectServer::OnTimerDone(Entity *self, std::string timerName) { - if (timerName == "killSelf") { - const auto* petComponent = self->GetComponent(); - if (petComponent == nullptr || petComponent->GetOwner() != nullptr) - return; - self->Smash(self->GetObjectID(), SILENT); - } +void PetFromObjectServer::OnTimerDone(Entity* self, std::string timerName) { + if (timerName == "killSelf") { + const auto* petComponent = self->GetComponent(); + if (petComponent == nullptr || petComponent->GetOwner() != nullptr) + return; + self->Smash(self->GetObjectID(), SILENT); + } } -void PetFromObjectServer::OnNotifyPetTamingMinigame(Entity *self, Entity *tamer, eNotifyType type) { - switch (type) { - case NOTIFY_TYPE_BEGIN: - self->CancelAllTimers(); - break; - case NOTIFY_TYPE_QUIT: - case NOTIFY_TYPE_FAILED: - self->Smash(self->GetObjectID(), SILENT); - break; - case NOTIFY_TYPE_SUCCESS: - // TODO: Remove from groups? - GameMessages::SendNotifyClientObject(self->GetObjectID(), u"UpdateSuccessPicking", 0, - 0, tamer->GetObjectID(), "", UNASSIGNED_SYSTEM_ADDRESS); - default: - break; - } +void PetFromObjectServer::OnNotifyPetTamingMinigame(Entity* self, Entity* tamer, eNotifyType type) { + switch (type) { + case NOTIFY_TYPE_BEGIN: + self->CancelAllTimers(); + break; + case NOTIFY_TYPE_QUIT: + case NOTIFY_TYPE_FAILED: + self->Smash(self->GetObjectID(), SILENT); + break; + case NOTIFY_TYPE_SUCCESS: + // TODO: Remove from groups? + GameMessages::SendNotifyClientObject(self->GetObjectID(), u"UpdateSuccessPicking", 0, + 0, tamer->GetObjectID(), "", UNASSIGNED_SYSTEM_ADDRESS); + default: + break; + } } diff --git a/dScripts/PetFromObjectServer.h b/dScripts/PetFromObjectServer.h index 989df880..1a7c244b 100644 --- a/dScripts/PetFromObjectServer.h +++ b/dScripts/PetFromObjectServer.h @@ -3,7 +3,7 @@ class PetFromObjectServer : public CppScripts::Script { public: - void OnStartup(Entity *self) override; - void OnTimerDone(Entity *self, std::string timerName) override; - void OnNotifyPetTamingMinigame(Entity *self, Entity *tamer, eNotifyType type) override; + void OnStartup(Entity* self) override; + void OnTimerDone(Entity* self, std::string timerName) override; + void OnNotifyPetTamingMinigame(Entity* self, Entity* tamer, eNotifyType type) override; }; diff --git a/dScripts/PrSeagullFly.cpp b/dScripts/PrSeagullFly.cpp index a4dd5fcd..5c71f32a 100644 --- a/dScripts/PrSeagullFly.cpp +++ b/dScripts/PrSeagullFly.cpp @@ -1,24 +1,19 @@ #include "PrSeagullFly.h" #include "Entity.h" -void PrSeagullFly::OnStartup(Entity* self) -{ +void PrSeagullFly::OnStartup(Entity* self) { self->SetVar(u"playersNear", 0); - self->SetProximityRadius(15, "birdMonitor"); + self->SetProximityRadius(15, "birdMonitor"); } -void PrSeagullFly::OnProximityUpdate(Entity* self, Entity* entering, std::string name, std::string status) -{ - if (!entering->IsPlayer()) return; +void PrSeagullFly::OnProximityUpdate(Entity* self, Entity* entering, std::string name, std::string status) { + if (!entering->IsPlayer()) return; - if (status == "ENTER") - { + if (status == "ENTER") { self->SetVar(u"playersNear", self->GetVar(u"playersNear") + 1); - } - else if (status == "LEAVE") - { + } else if (status == "LEAVE") { self->SetVar(u"playersNear", self->GetVar(u"playersNear") - 1); - } + } - self->SetNetworkVar(u"BirdLanded", self->GetVar(u"playersNear") == 0); + self->SetNetworkVar(u"BirdLanded", self->GetVar(u"playersNear") == 0); } diff --git a/dScripts/PrWhistle.cpp b/dScripts/PrWhistle.cpp index 4d4d0708..888e1c65 100644 --- a/dScripts/PrWhistle.cpp +++ b/dScripts/PrWhistle.cpp @@ -2,16 +2,13 @@ #include "Character.h" #include "Entity.h" -void PrWhistle::OnFireEventServerSide(Entity *self, Entity *sender, std::string args, int32_t param1, int32_t param2, - int32_t param3) -{ - if (args == "unlockEmote") - { - auto* character = sender->GetCharacter(); +void PrWhistle::OnFireEventServerSide(Entity* self, Entity* sender, std::string args, int32_t param1, int32_t param2, + int32_t param3) { + if (args == "unlockEmote") { + auto* character = sender->GetCharacter(); - if (character != nullptr) - { - character->UnlockEmote(115); - } - } + if (character != nullptr) { + character->UnlockEmote(115); + } + } } diff --git a/dScripts/PrWhistle.h b/dScripts/PrWhistle.h index 58bc0a23..1209ba0d 100644 --- a/dScripts/PrWhistle.h +++ b/dScripts/PrWhistle.h @@ -4,7 +4,7 @@ class PrWhistle : public CppScripts::Script { public: - void OnFireEventServerSide(Entity *self, Entity *sender, std::string args, int32_t param1, int32_t param2, - int32_t param3) override; + void OnFireEventServerSide(Entity* self, Entity* sender, std::string args, int32_t param1, int32_t param2, + int32_t param3) override; }; diff --git a/dScripts/PropertyBankInteract.cpp b/dScripts/PropertyBankInteract.cpp index d564c503..788768ca 100644 --- a/dScripts/PropertyBankInteract.cpp +++ b/dScripts/PropertyBankInteract.cpp @@ -2,42 +2,42 @@ #include "EntityManager.h" #include "GameMessages.h" -void PropertyBankInteract::OnStartup(Entity *self) { - auto* zoneControl = EntityManager::Instance()->GetZoneControlEntity(); - if (zoneControl != nullptr) { - zoneControl->OnFireEventServerSide(self, "CheckForPropertyOwner"); - } +void PropertyBankInteract::OnStartup(Entity* self) { + auto* zoneControl = EntityManager::Instance()->GetZoneControlEntity(); + if (zoneControl != nullptr) { + zoneControl->OnFireEventServerSide(self, "CheckForPropertyOwner"); + } } -void PropertyBankInteract::OnPlayerLoaded(Entity *self, Entity *player) { - auto* zoneControl = EntityManager::Instance()->GetZoneControlEntity(); - if (zoneControl != nullptr) { - zoneControl->OnFireEventServerSide(self, "CheckForPropertyOwner"); - } +void PropertyBankInteract::OnPlayerLoaded(Entity* self, Entity* player) { + auto* zoneControl = EntityManager::Instance()->GetZoneControlEntity(); + if (zoneControl != nullptr) { + zoneControl->OnFireEventServerSide(self, "CheckForPropertyOwner"); + } } -void PropertyBankInteract::OnUse(Entity *self, Entity *user) { +void PropertyBankInteract::OnUse(Entity* self, Entity* user) { - AMFArrayValue args; - auto* value = new AMFStringValue(); - value->SetStringValue("bank"); - args.InsertValue("state", value); + AMFArrayValue args; + auto* value = new AMFStringValue(); + value->SetStringValue("bank"); + args.InsertValue("state", value); - GameMessages::SendUIMessageServerToSingleClient(user, user->GetSystemAddress(), "pushGameState", &args); + GameMessages::SendUIMessageServerToSingleClient(user, user->GetSystemAddress(), "pushGameState", &args); - GameMessages::SendNotifyClientObject(self->GetObjectID(), u"OpenBank", 0, 0, LWOOBJID_EMPTY, - "", user->GetSystemAddress()); + GameMessages::SendNotifyClientObject(self->GetObjectID(), u"OpenBank", 0, 0, LWOOBJID_EMPTY, + "", user->GetSystemAddress()); } -void PropertyBankInteract::OnFireEventServerSide(Entity *self, Entity *sender, std::string args, int32_t param1, - int32_t param2, int32_t param3) { - if (args == "ToggleBank") { - AMFArrayValue amfArgs; +void PropertyBankInteract::OnFireEventServerSide(Entity* self, Entity* sender, std::string args, int32_t param1, + int32_t param2, int32_t param3) { + if (args == "ToggleBank") { + AMFArrayValue amfArgs; amfArgs.InsertValue("visible", new AMFFalseValue()); - GameMessages::SendUIMessageServerToSingleClient(sender, sender->GetSystemAddress(), "ToggleBank", &amfArgs); + GameMessages::SendUIMessageServerToSingleClient(sender, sender->GetSystemAddress(), "ToggleBank", &amfArgs); - GameMessages::SendNotifyClientObject(self->GetObjectID(), u"CloseBank", 0, 0, LWOOBJID_EMPTY, - "", sender->GetSystemAddress()); - } + GameMessages::SendNotifyClientObject(self->GetObjectID(), u"CloseBank", 0, 0, LWOOBJID_EMPTY, + "", sender->GetSystemAddress()); + } } diff --git a/dScripts/PropertyBankInteract.h b/dScripts/PropertyBankInteract.h index 54bc0484..d780e486 100644 --- a/dScripts/PropertyBankInteract.h +++ b/dScripts/PropertyBankInteract.h @@ -2,9 +2,9 @@ #include "CppScripts.h" class PropertyBankInteract : public CppScripts::Script { - void OnStartup(Entity *self) override; - void OnPlayerLoaded(Entity *self, Entity *player) override; - void OnUse(Entity *self, Entity *user) override; - void OnFireEventServerSide(Entity *self, Entity *sender, std::string args, int32_t param1, int32_t param2, - int32_t param3) override; + void OnStartup(Entity* self) override; + void OnPlayerLoaded(Entity* self, Entity* player) override; + void OnUse(Entity* self, Entity* user) override; + void OnFireEventServerSide(Entity* self, Entity* sender, std::string args, int32_t param1, int32_t param2, + int32_t param3) override; }; diff --git a/dScripts/PropertyDeathPlane.cpp b/dScripts/PropertyDeathPlane.cpp index 93981dac..ab659d8a 100644 --- a/dScripts/PropertyDeathPlane.cpp +++ b/dScripts/PropertyDeathPlane.cpp @@ -3,16 +3,14 @@ #include "GameMessages.h" #include "EntityManager.h" -void PropertyDeathPlane::OnCollisionPhantom(Entity* self, Entity* target) -{ - const auto teleportGroup = EntityManager::Instance()->GetEntitiesInGroup("Teleport"); +void PropertyDeathPlane::OnCollisionPhantom(Entity* self, Entity* target) { + const auto teleportGroup = EntityManager::Instance()->GetEntitiesInGroup("Teleport"); - if (teleportGroup.size() == 0) - { - return; - } + if (teleportGroup.size() == 0) { + return; + } - auto* teleport = teleportGroup[0]; + auto* teleport = teleportGroup[0]; - GameMessages::SendTeleport(target->GetObjectID(), teleport->GetPosition(), teleport->GetRotation(), target->GetSystemAddress()); + GameMessages::SendTeleport(target->GetObjectID(), teleport->GetPosition(), teleport->GetRotation(), target->GetSystemAddress()); } diff --git a/dScripts/PropertyDevice.cpp b/dScripts/PropertyDevice.cpp index ed0d7b81..64771de1 100644 --- a/dScripts/PropertyDevice.cpp +++ b/dScripts/PropertyDevice.cpp @@ -3,23 +3,23 @@ #include "EntityManager.h" #include "MissionComponent.h" -void PropertyDevice::OnStartup(Entity *self) { - auto* zoneControl = EntityManager::Instance()->GetZoneControlEntity(); - if (zoneControl != nullptr) { - zoneControl->OnFireEventServerSide(self, "CheckForPropertyOwner"); - } +void PropertyDevice::OnStartup(Entity* self) { + auto* zoneControl = EntityManager::Instance()->GetZoneControlEntity(); + if (zoneControl != nullptr) { + zoneControl->OnFireEventServerSide(self, "CheckForPropertyOwner"); + } } -void PropertyDevice::OnRebuildComplete(Entity *self, Entity *target) { - auto propertyOwnerID = self->GetNetworkVar(m_PropertyOwnerVariable); - if (propertyOwnerID == std::to_string(LWOOBJID_EMPTY)) - return; +void PropertyDevice::OnRebuildComplete(Entity* self, Entity* target) { + auto propertyOwnerID = self->GetNetworkVar(m_PropertyOwnerVariable); + if (propertyOwnerID == std::to_string(LWOOBJID_EMPTY)) + return; - auto* missionComponent = target->GetComponent(); - if (missionComponent != nullptr) { - if (missionComponent->GetMissionState(m_PropertyMissionID) == MissionState::MISSION_STATE_ACTIVE) { - GameMessages::SendPlayFXEffect(self->GetObjectID(), 641, u"create", "callhome"); - missionComponent->ForceProgress(m_PropertyMissionID, 1793, self->GetLOT()); - } - } + auto* missionComponent = target->GetComponent(); + if (missionComponent != nullptr) { + if (missionComponent->GetMissionState(m_PropertyMissionID) == MissionState::MISSION_STATE_ACTIVE) { + GameMessages::SendPlayFXEffect(self->GetObjectID(), 641, u"create", "callhome"); + missionComponent->ForceProgress(m_PropertyMissionID, 1793, self->GetLOT()); + } + } } diff --git a/dScripts/PropertyDevice.h b/dScripts/PropertyDevice.h index 9c97df4d..87ca10ad 100644 --- a/dScripts/PropertyDevice.h +++ b/dScripts/PropertyDevice.h @@ -2,8 +2,8 @@ #include "CppScripts.h" class PropertyDevice : public CppScripts::Script { - void OnStartup(Entity *self) override; - void OnRebuildComplete(Entity *self, Entity *target) override; - const std::u16string m_PropertyOwnerVariable = u"PropertyOwnerID"; - const uint32_t m_PropertyMissionID = 1291; + void OnStartup(Entity* self) override; + void OnRebuildComplete(Entity* self, Entity* target) override; + const std::u16string m_PropertyOwnerVariable = u"PropertyOwnerID"; + const uint32_t m_PropertyMissionID = 1291; }; diff --git a/dScripts/PropertyFXDamage.cpp b/dScripts/PropertyFXDamage.cpp index 2c01ceb1..d12cc9e1 100644 --- a/dScripts/PropertyFXDamage.cpp +++ b/dScripts/PropertyFXDamage.cpp @@ -2,17 +2,17 @@ #include "DestroyableComponent.h" #include "SkillComponent.h" -void PropertyFXDamage::OnCollisionPhantom(Entity *self, Entity *target) { - if (target == nullptr) - return; +void PropertyFXDamage::OnCollisionPhantom(Entity* self, Entity* target) { + if (target == nullptr) + return; - auto* skills = self->GetComponent(); - auto* targetStats = target->GetComponent(); + auto* skills = self->GetComponent(); + auto* targetStats = target->GetComponent(); - if (skills != nullptr && targetStats != nullptr) { - auto targetFactions = targetStats->GetFactionIDs(); - if (std::find(targetFactions.begin(), targetFactions.end(), 1) != targetFactions.end()) { - skills->CalculateBehavior(11386, 692, target->GetObjectID()); - } - } + if (skills != nullptr && targetStats != nullptr) { + auto targetFactions = targetStats->GetFactionIDs(); + if (std::find(targetFactions.begin(), targetFactions.end(), 1) != targetFactions.end()) { + skills->CalculateBehavior(11386, 692, target->GetObjectID()); + } + } } diff --git a/dScripts/PropertyFXDamage.h b/dScripts/PropertyFXDamage.h index b1e67c0a..6973de0c 100644 --- a/dScripts/PropertyFXDamage.h +++ b/dScripts/PropertyFXDamage.h @@ -2,5 +2,5 @@ #include "CppScripts.h" class PropertyFXDamage : public CppScripts::Script { - void OnCollisionPhantom(Entity *self, Entity *target) override; + void OnCollisionPhantom(Entity* self, Entity* target) override; }; diff --git a/dScripts/PropertyPlatform.cpp b/dScripts/PropertyPlatform.cpp index 3b744663..89687ac3 100644 --- a/dScripts/PropertyPlatform.cpp +++ b/dScripts/PropertyPlatform.cpp @@ -2,31 +2,31 @@ #include "RebuildComponent.h" #include "GameMessages.h" -void PropertyPlatform::OnRebuildComplete(Entity *self, Entity *target) { -// auto* movingPlatform = self->GetComponent(); -// if (movingPlatform != nullptr) { -// movingPlatform->StopPathing(); -// movingPlatform->SetNoAutoStart(true); -// } - GameMessages::SendPlatformResync(self, UNASSIGNED_SYSTEM_ADDRESS, true, 0, - 0, 0, MovementPlatformState::Stationary); +void PropertyPlatform::OnRebuildComplete(Entity* self, Entity* target) { + // auto* movingPlatform = self->GetComponent(); + // if (movingPlatform != nullptr) { + // movingPlatform->StopPathing(); + // movingPlatform->SetNoAutoStart(true); + // } + GameMessages::SendPlatformResync(self, UNASSIGNED_SYSTEM_ADDRESS, true, 0, + 0, 0, MovementPlatformState::Stationary); } -void PropertyPlatform::OnUse(Entity *self, Entity *user) { - auto* rebuildComponent = self->GetComponent(); - if (rebuildComponent != nullptr && rebuildComponent->GetState() == REBUILD_COMPLETED) { -// auto* movingPlatform = self->GetComponent(); -// if (movingPlatform != nullptr) { -// movingPlatform->GotoWaypoint(1); -// } - GameMessages::SendPlatformResync(self, UNASSIGNED_SYSTEM_ADDRESS, true, 0, - 1, 1, MovementPlatformState::Moving); +void PropertyPlatform::OnUse(Entity* self, Entity* user) { + auto* rebuildComponent = self->GetComponent(); + if (rebuildComponent != nullptr && rebuildComponent->GetState() == REBUILD_COMPLETED) { + // auto* movingPlatform = self->GetComponent(); + // if (movingPlatform != nullptr) { + // movingPlatform->GotoWaypoint(1); + // } + GameMessages::SendPlatformResync(self, UNASSIGNED_SYSTEM_ADDRESS, true, 0, + 1, 1, MovementPlatformState::Moving); - self->AddCallbackTimer(movementDelay + effectDelay, [self, this]() { - self->SetNetworkVar(u"startEffect", dieDelay); - self->AddCallbackTimer(dieDelay, [self]() { - self->Smash(); - }); - }); - } + self->AddCallbackTimer(movementDelay + effectDelay, [self, this]() { + self->SetNetworkVar(u"startEffect", dieDelay); + self->AddCallbackTimer(dieDelay, [self]() { + self->Smash(); + }); + }); + } } diff --git a/dScripts/PropertyPlatform.h b/dScripts/PropertyPlatform.h index 9a2b3229..ec863ab0 100644 --- a/dScripts/PropertyPlatform.h +++ b/dScripts/PropertyPlatform.h @@ -3,11 +3,11 @@ class PropertyPlatform : public CppScripts::Script { public: - void OnUse(Entity *self, Entity *user) override; - void OnRebuildComplete(Entity *self, Entity *target) override; + void OnUse(Entity* self, Entity* user) override; + void OnRebuildComplete(Entity* self, Entity* target) override; private: - float_t movementDelay = 10.0f; - float_t effectDelay = 5.0f; - float_t dieDelay = 5.0f; - uint32_t desiredWaypoint = 1; + float_t movementDelay = 10.0f; + float_t effectDelay = 5.0f; + float_t dieDelay = 5.0f; + uint32_t desiredWaypoint = 1; }; diff --git a/dScripts/QbEnemyStunner.cpp b/dScripts/QbEnemyStunner.cpp index a3dfa94b..5d31a788 100644 --- a/dScripts/QbEnemyStunner.cpp +++ b/dScripts/QbEnemyStunner.cpp @@ -2,73 +2,64 @@ #include "SkillComponent.h" #include "DestroyableComponent.h" -void QbEnemyStunner::OnRebuildComplete(Entity* self, Entity* target) -{ - auto* destroyable = self->GetComponent(); +void QbEnemyStunner::OnRebuildComplete(Entity* self, Entity* target) { + auto* destroyable = self->GetComponent(); - if (destroyable != nullptr) - { - destroyable->SetFaction(115); - } + if (destroyable != nullptr) { + destroyable->SetFaction(115); + } - auto skillComponent = self->GetComponent(); - if (!skillComponent) return; + auto skillComponent = self->GetComponent(); + if (!skillComponent) return; - // Get the skill IDs of this object. - CDObjectSkillsTable* skillsTable = CDClientManager::Instance()->GetTable("ObjectSkills"); - auto skills = skillsTable->Query([=](CDObjectSkills entry) {return (entry.objectTemplate == self->GetLOT()); }); - std::map skillBehaviorMap; - // For each skill, cast it with the associated behavior ID. - for (auto skill : skills) { - CDSkillBehaviorTable* skillBehaviorTable = CDClientManager::Instance()->GetTable("SkillBehavior"); + // Get the skill IDs of this object. + CDObjectSkillsTable* skillsTable = CDClientManager::Instance()->GetTable("ObjectSkills"); + auto skills = skillsTable->Query([=](CDObjectSkills entry) {return (entry.objectTemplate == self->GetLOT()); }); + std::map skillBehaviorMap; + // For each skill, cast it with the associated behavior ID. + for (auto skill : skills) { + CDSkillBehaviorTable* skillBehaviorTable = CDClientManager::Instance()->GetTable("SkillBehavior"); CDSkillBehavior behaviorData = skillBehaviorTable->GetSkillByID(skill.skillID); - skillBehaviorMap.insert(std::make_pair(skill.skillID, behaviorData.behaviorID)); - } + skillBehaviorMap.insert(std::make_pair(skill.skillID, behaviorData.behaviorID)); + } - // If there are no skills found, insert a default skill to use. - if (skillBehaviorMap.size() == 0) { - skillBehaviorMap.insert(std::make_pair(499U, 6095U)); - } + // If there are no skills found, insert a default skill to use. + if (skillBehaviorMap.size() == 0) { + skillBehaviorMap.insert(std::make_pair(499U, 6095U)); + } - // Start all skills associated with the object next tick - self->AddTimer("TickTime", 0); + // Start all skills associated with the object next tick + self->AddTimer("TickTime", 0); - self->AddTimer("PlayEffect", 20); + self->AddTimer("PlayEffect", 20); - self->SetVar>(u"skillBehaviorMap", skillBehaviorMap); + self->SetVar>(u"skillBehaviorMap", skillBehaviorMap); } -void QbEnemyStunner::OnTimerDone(Entity* self, std::string timerName) -{ - if (timerName == "DieTime") - { - self->Smash(); +void QbEnemyStunner::OnTimerDone(Entity* self, std::string timerName) { + if (timerName == "DieTime") { + self->Smash(); - self->CancelAllTimers(); - } - else if (timerName == "PlayEffect") - { - self->SetNetworkVar(u"startEffect", 5.0f, UNASSIGNED_SYSTEM_ADDRESS); + self->CancelAllTimers(); + } else if (timerName == "PlayEffect") { + self->SetNetworkVar(u"startEffect", 5.0f, UNASSIGNED_SYSTEM_ADDRESS); - self->AddTimer("DieTime", 5.0f); - } - else if (timerName == "TickTime") - { - auto* skillComponent = self->GetComponent(); + self->AddTimer("DieTime", 5.0f); + } else if (timerName == "TickTime") { + auto* skillComponent = self->GetComponent(); - if (skillComponent != nullptr) - { - auto skillBehaviorMap = self->GetVar>(u"skillBehaviorMap"); - if (skillBehaviorMap.size() == 0) { - // Should no skills have been found, default to the mermaid stunner - skillComponent->CalculateBehavior(499U, 6095U, LWOOBJID_EMPTY); - } else { - for (auto pair : skillBehaviorMap) { - skillComponent->CalculateBehavior(pair.first, pair.second, LWOOBJID_EMPTY); - } - } - } - self->AddTimer("TickTime", 1); - } + if (skillComponent != nullptr) { + auto skillBehaviorMap = self->GetVar>(u"skillBehaviorMap"); + if (skillBehaviorMap.size() == 0) { + // Should no skills have been found, default to the mermaid stunner + skillComponent->CalculateBehavior(499U, 6095U, LWOOBJID_EMPTY); + } else { + for (auto pair : skillBehaviorMap) { + skillComponent->CalculateBehavior(pair.first, pair.second, LWOOBJID_EMPTY); + } + } + } + self->AddTimer("TickTime", 1); + } } diff --git a/dScripts/QbEnemyStunner.h b/dScripts/QbEnemyStunner.h index 18c52d4d..fd9033d6 100644 --- a/dScripts/QbEnemyStunner.h +++ b/dScripts/QbEnemyStunner.h @@ -4,6 +4,6 @@ class QbEnemyStunner : public CppScripts::Script { public: - void OnRebuildComplete(Entity* self, Entity* target) override; - void OnTimerDone(Entity* self, std::string timerName) override; + void OnRebuildComplete(Entity* self, Entity* target) override; + void OnTimerDone(Entity* self, std::string timerName) override; }; diff --git a/dScripts/RaceImagineCrateServer.cpp b/dScripts/RaceImagineCrateServer.cpp index 3729004a..a35007b4 100644 --- a/dScripts/RaceImagineCrateServer.cpp +++ b/dScripts/RaceImagineCrateServer.cpp @@ -7,54 +7,49 @@ #include "MissionComponent.h" #include "SkillComponent.h" -void RaceImagineCrateServer::OnDie(Entity* self, Entity* killer) -{ - if (self->GetVar(u"bIsDead")) - { - return; - } +void RaceImagineCrateServer::OnDie(Entity* self, Entity* killer) { + if (self->GetVar(u"bIsDead")) { + return; + } - self->SetVar(u"bIsDead", true); + self->SetVar(u"bIsDead", true); - if (killer == nullptr) - { - return; - } + if (killer == nullptr) { + return; + } - auto* skillComponent = killer->GetComponent(); + auto* skillComponent = killer->GetComponent(); - if (skillComponent == nullptr) - { - return; - } + if (skillComponent == nullptr) { + return; + } - auto* destroyableComponent = killer->GetComponent(); + auto* destroyableComponent = killer->GetComponent(); - if (destroyableComponent != nullptr) - { - destroyableComponent->SetImagination(60); + if (destroyableComponent != nullptr) { + destroyableComponent->SetImagination(60); - EntityManager::Instance()->SerializeEntity(killer); - } + EntityManager::Instance()->SerializeEntity(killer); + } - // Find possessor of race car to progress missions and update stats. - auto* possessableComponent = killer->GetComponent(); - if (possessableComponent != nullptr) { + // Find possessor of race car to progress missions and update stats. + auto* possessableComponent = killer->GetComponent(); + if (possessableComponent != nullptr) { - auto* possessor = EntityManager::Instance()->GetEntity(possessableComponent->GetPossessor()); - if (possessor != nullptr) { + auto* possessor = EntityManager::Instance()->GetEntity(possessableComponent->GetPossessor()); + if (possessor != nullptr) { - auto* missionComponent = possessor->GetComponent(); - auto* characterComponent = possessor->GetComponent(); + auto* missionComponent = possessor->GetComponent(); + auto* characterComponent = possessor->GetComponent(); - if (characterComponent != nullptr) { - characterComponent->UpdatePlayerStatistic(RacingImaginationCratesSmashed); - characterComponent->UpdatePlayerStatistic(RacingSmashablesSmashed); - } + if (characterComponent != nullptr) { + characterComponent->UpdatePlayerStatistic(RacingImaginationCratesSmashed); + characterComponent->UpdatePlayerStatistic(RacingSmashablesSmashed); + } - // Progress racing smashable missions - if(missionComponent == nullptr) return; - missionComponent->Progress(MissionTaskType::MISSION_TASK_TYPE_RACING, 0, (LWOOBJID)RacingTaskParam::RACING_TASK_PARAM_SMASHABLES); - } - } + // Progress racing smashable missions + if (missionComponent == nullptr) return; + missionComponent->Progress(MissionTaskType::MISSION_TASK_TYPE_RACING, 0, (LWOOBJID)RacingTaskParam::RACING_TASK_PARAM_SMASHABLES); + } + } } diff --git a/dScripts/RaceImagineCrateServer.h b/dScripts/RaceImagineCrateServer.h index 42f36b30..92020925 100644 --- a/dScripts/RaceImagineCrateServer.h +++ b/dScripts/RaceImagineCrateServer.h @@ -4,11 +4,11 @@ class RaceImagineCrateServer : public CppScripts::Script { public: -/** - * @brief When a boost smashable has been smashed, this function is called - * - * @param self The Entity that called this function. - * @param killer The Entity that killed this Entity. - */ - void OnDie(Entity* self, Entity* killer) override; + /** + * @brief When a boost smashable has been smashed, this function is called + * + * @param self The Entity that called this function. + * @param killer The Entity that killed this Entity. + */ + void OnDie(Entity* self, Entity* killer) override; }; diff --git a/dScripts/RaceImaginePowerup.cpp b/dScripts/RaceImaginePowerup.cpp index a940b88d..9bdd0813 100644 --- a/dScripts/RaceImaginePowerup.cpp +++ b/dScripts/RaceImaginePowerup.cpp @@ -5,37 +5,32 @@ #include "RacingTaskParam.h" #include "MissionComponent.h" -void RaceImaginePowerup::OnFireEventServerSide(Entity *self, Entity *sender, std::string args, int32_t param1, - int32_t param2, int32_t param3) -{ - if (sender->IsPlayer() && args == "powerup") - { - auto* possessorComponent = sender->GetComponent(); +void RaceImaginePowerup::OnFireEventServerSide(Entity* self, Entity* sender, std::string args, int32_t param1, + int32_t param2, int32_t param3) { + if (sender->IsPlayer() && args == "powerup") { + auto* possessorComponent = sender->GetComponent(); - if (possessorComponent == nullptr) - { - return; - } + if (possessorComponent == nullptr) { + return; + } - auto* vehicle = EntityManager::Instance()->GetEntity(possessorComponent->GetPossessable()); + auto* vehicle = EntityManager::Instance()->GetEntity(possessorComponent->GetPossessable()); - if (vehicle == nullptr) - { - return; - } + if (vehicle == nullptr) { + return; + } - auto* destroyableComponent = vehicle->GetComponent(); + auto* destroyableComponent = vehicle->GetComponent(); - if (destroyableComponent == nullptr) - { - return; - } + if (destroyableComponent == nullptr) { + return; + } - destroyableComponent->Imagine(10); + destroyableComponent->Imagine(10); - auto* missionComponent = sender->GetComponent(); + auto* missionComponent = sender->GetComponent(); - if (missionComponent == nullptr) return; - missionComponent->Progress(MissionTaskType::MISSION_TASK_TYPE_RACING, self->GetLOT(), (LWOOBJID)RacingTaskParam::RACING_TASK_PARAM_COLLECT_IMAGINATION); - } + if (missionComponent == nullptr) return; + missionComponent->Progress(MissionTaskType::MISSION_TASK_TYPE_RACING, self->GetLOT(), (LWOOBJID)RacingTaskParam::RACING_TASK_PARAM_COLLECT_IMAGINATION); + } } diff --git a/dScripts/RaceImaginePowerup.h b/dScripts/RaceImaginePowerup.h index c9d7be2d..2df2e060 100644 --- a/dScripts/RaceImaginePowerup.h +++ b/dScripts/RaceImaginePowerup.h @@ -4,6 +4,6 @@ class RaceImaginePowerup : public CppScripts::Script { public: - void OnFireEventServerSide(Entity *self, Entity *sender, std::string args, int32_t param1, int32_t param2, - int32_t param3) override; + void OnFireEventServerSide(Entity* self, Entity* sender, std::string args, int32_t param1, int32_t param2, + int32_t param3) override; }; diff --git a/dScripts/RaceMaelstromGeiser.cpp b/dScripts/RaceMaelstromGeiser.cpp index 88a45bbd..b737d449 100644 --- a/dScripts/RaceMaelstromGeiser.cpp +++ b/dScripts/RaceMaelstromGeiser.cpp @@ -6,99 +6,80 @@ #include "RacingControlComponent.h" #include "dZoneManager.h" -void RaceMaelstromGeiser::OnStartup(Entity* self) -{ - self->SetVar(u"AmFiring", false); - - self->AddTimer("downTime", self->GetVar(u"startTime")); +void RaceMaelstromGeiser::OnStartup(Entity* self) { + self->SetVar(u"AmFiring", false); - self->SetProximityRadius(15, "deathZone"); + self->AddTimer("downTime", self->GetVar(u"startTime")); + + self->SetProximityRadius(15, "deathZone"); } -void RaceMaelstromGeiser::OnProximityUpdate(Entity* self, Entity* entering, std::string name, std::string status) -{ - if (!entering->IsPlayer() || name != "deathZone" || status != "ENTER") - { - return; - } +void RaceMaelstromGeiser::OnProximityUpdate(Entity* self, Entity* entering, std::string name, std::string status) { + if (!entering->IsPlayer() || name != "deathZone" || status != "ENTER") { + return; + } - if (!self->GetVar(u"AmFiring")) - { - return; - } + if (!self->GetVar(u"AmFiring")) { + return; + } - auto* possessableComponent = entering->GetComponent(); + auto* possessableComponent = entering->GetComponent(); - Entity* vehicle; - Entity* player; + Entity* vehicle; + Entity* player; - if (possessableComponent != nullptr) - { - player = EntityManager::Instance()->GetEntity(possessableComponent->GetPossessor()); + if (possessableComponent != nullptr) { + player = EntityManager::Instance()->GetEntity(possessableComponent->GetPossessor()); - if (player == nullptr) - { - return; - } + if (player == nullptr) { + return; + } - vehicle = entering; - } - else if (entering->IsPlayer()) - { - auto* possessorComponent = entering->GetComponent(); + vehicle = entering; + } else if (entering->IsPlayer()) { + auto* possessorComponent = entering->GetComponent(); - if (possessorComponent == nullptr) - { - return; - } + if (possessorComponent == nullptr) { + return; + } - vehicle = EntityManager::Instance()->GetEntity(possessorComponent->GetPossessable()); + vehicle = EntityManager::Instance()->GetEntity(possessorComponent->GetPossessable()); - if (vehicle == nullptr) - { - return; - } + if (vehicle == nullptr) { + return; + } - player = entering; - } - else - { - return; - } - + player = entering; + } else { + return; + } - GameMessages::SendDie(vehicle, self->GetObjectID(), LWOOBJID_EMPTY, true, VIOLENT, u"", 0, 0, 0, true, false, 0); - auto* zoneController = dZoneManager::Instance()->GetZoneControlObject(); + GameMessages::SendDie(vehicle, self->GetObjectID(), LWOOBJID_EMPTY, true, VIOLENT, u"", 0, 0, 0, true, false, 0); - auto* racingControlComponent = zoneController->GetComponent(); + auto* zoneController = dZoneManager::Instance()->GetZoneControlObject(); - if (racingControlComponent != nullptr) - { - racingControlComponent->OnRequestDie(player); - } + auto* racingControlComponent = zoneController->GetComponent(); + + if (racingControlComponent != nullptr) { + racingControlComponent->OnRequestDie(player); + } } -void RaceMaelstromGeiser::OnTimerDone(Entity* self, std::string timerName) -{ - if (timerName == "downTime") - { - GameMessages::SendPlayFXEffect(self->GetObjectID(), 4048, u"rebuild_medium", "geiser", LWOOBJID_EMPTY, 1, 1, true); +void RaceMaelstromGeiser::OnTimerDone(Entity* self, std::string timerName) { + if (timerName == "downTime") { + GameMessages::SendPlayFXEffect(self->GetObjectID(), 4048, u"rebuild_medium", "geiser", LWOOBJID_EMPTY, 1, 1, true); - self->AddTimer("buildUpTime", 1); - } - else if (timerName == "buildUpTime") - { - self->SetVar(u"AmFiring", true); + self->AddTimer("buildUpTime", 1); + } else if (timerName == "buildUpTime") { + self->SetVar(u"AmFiring", true); - self->AddTimer("killTime", 1.5f); - } - else if (timerName == "killTime") - { - GameMessages::SendStopFXEffect(self, true, "geiser"); + self->AddTimer("killTime", 1.5f); + } else if (timerName == "killTime") { + GameMessages::SendStopFXEffect(self, true, "geiser"); - self->SetVar(u"AmFiring", false); + self->SetVar(u"AmFiring", false); - self->AddTimer("downTime", 3.0); - } + self->AddTimer("downTime", 3.0); + } } diff --git a/dScripts/RaceMaelstromGeiser.h b/dScripts/RaceMaelstromGeiser.h index 79cc384c..3ca0953b 100644 --- a/dScripts/RaceMaelstromGeiser.h +++ b/dScripts/RaceMaelstromGeiser.h @@ -4,7 +4,7 @@ class RaceMaelstromGeiser : public CppScripts::Script { public: - void OnStartup(Entity* self) override; - void OnTimerDone(Entity* self, std::string timerName) override; + void OnStartup(Entity* self) override; + void OnTimerDone(Entity* self, std::string timerName) override; void OnProximityUpdate(Entity* self, Entity* entering, std::string name, std::string status) override; }; diff --git a/dScripts/RaceSmashServer.cpp b/dScripts/RaceSmashServer.cpp index 8c8b3f79..d0dc3d78 100644 --- a/dScripts/RaceSmashServer.cpp +++ b/dScripts/RaceSmashServer.cpp @@ -5,26 +5,26 @@ #include "RacingTaskParam.h" #include "MissionComponent.h" -void RaceSmashServer::OnDie(Entity *self, Entity *killer) { - // Crate is smashed by the car - auto* possessableComponent = killer->GetComponent(); - if (possessableComponent != nullptr) { +void RaceSmashServer::OnDie(Entity* self, Entity* killer) { + // Crate is smashed by the car + auto* possessableComponent = killer->GetComponent(); + if (possessableComponent != nullptr) { - auto* possessor = EntityManager::Instance()->GetEntity(possessableComponent->GetPossessor()); - if (possessor != nullptr) { + auto* possessor = EntityManager::Instance()->GetEntity(possessableComponent->GetPossessor()); + if (possessor != nullptr) { - auto* missionComponent = possessor->GetComponent(); - auto* characterComponent = possessor->GetComponent(); + auto* missionComponent = possessor->GetComponent(); + auto* characterComponent = possessor->GetComponent(); - if (characterComponent != nullptr) { - characterComponent->UpdatePlayerStatistic(RacingSmashablesSmashed); - } + if (characterComponent != nullptr) { + characterComponent->UpdatePlayerStatistic(RacingSmashablesSmashed); + } - // Progress racing smashable missions - if(missionComponent == nullptr) return; - missionComponent->Progress(MissionTaskType::MISSION_TASK_TYPE_RACING, 0, (LWOOBJID)RacingTaskParam::RACING_TASK_PARAM_SMASHABLES); - // Progress missions that ask us to smash a specific smashable. - missionComponent->Progress(MissionTaskType::MISSION_TASK_TYPE_RACING, self->GetLOT(), (LWOOBJID)RacingTaskParam::RACING_TASK_PARAM_SMASH_SPECIFIC_SMASHABLE); - } - } + // Progress racing smashable missions + if (missionComponent == nullptr) return; + missionComponent->Progress(MissionTaskType::MISSION_TASK_TYPE_RACING, 0, (LWOOBJID)RacingTaskParam::RACING_TASK_PARAM_SMASHABLES); + // Progress missions that ask us to smash a specific smashable. + missionComponent->Progress(MissionTaskType::MISSION_TASK_TYPE_RACING, self->GetLOT(), (LWOOBJID)RacingTaskParam::RACING_TASK_PARAM_SMASH_SPECIFIC_SMASHABLE); + } + } } diff --git a/dScripts/RaceSmashServer.h b/dScripts/RaceSmashServer.h index 7fa1441d..096092bd 100644 --- a/dScripts/RaceSmashServer.h +++ b/dScripts/RaceSmashServer.h @@ -2,11 +2,11 @@ #include "CppScripts.h" class RaceSmashServer : public CppScripts::Script { - /** - * @brief When a smashable has been destroyed, this function is called. - * - * @param self The Entity that called this function. - * @param killer The Entity that killed this Entity. - */ - void OnDie(Entity *self, Entity *killer) override; + /** + * @brief When a smashable has been destroyed, this function is called. + * + * @param self The Entity that called this function. + * @param killer The Entity that killed this Entity. + */ + void OnDie(Entity* self, Entity* killer) override; }; diff --git a/dScripts/RainOfArrows.cpp b/dScripts/RainOfArrows.cpp index d9a7ba42..141cd3ab 100644 --- a/dScripts/RainOfArrows.cpp +++ b/dScripts/RainOfArrows.cpp @@ -3,79 +3,68 @@ #include "SkillComponent.h" #include "GameMessages.h" -void RainOfArrows::OnStartup(Entity* self) -{ - +void RainOfArrows::OnStartup(Entity* self) { + } -void RainOfArrows::OnRebuildComplete(Entity* self, Entity* target) -{ - auto myPos = self->GetPosition(); - auto myRot = self->GetRotation(); +void RainOfArrows::OnRebuildComplete(Entity* self, Entity* target) { + auto myPos = self->GetPosition(); + auto myRot = self->GetRotation(); - EntityInfo info; - info.lot = m_ArrowFXObject; - info.pos = myPos; - info.rot = myRot; - info.spawnerID = self->GetObjectID(); + EntityInfo info; + info.lot = m_ArrowFXObject; + info.pos = myPos; + info.rot = myRot; + info.spawnerID = self->GetObjectID(); - auto* entity = EntityManager::Instance()->CreateEntity(info); + auto* entity = EntityManager::Instance()->CreateEntity(info); - EntityManager::Instance()->ConstructEntity(entity); - - self->SetVar(u"ChildFX", entity->GetObjectID()); - self->SetVar(u"playerID", target->GetObjectID()); + EntityManager::Instance()->ConstructEntity(entity); - self->AddTimer("ArrowsIncoming", m_ArrowDelay); - self->AddTimer("PlayArrowSound", m_ArrowDelay - 4); + self->SetVar(u"ChildFX", entity->GetObjectID()); + self->SetVar(u"playerID", target->GetObjectID()); + + self->AddTimer("ArrowsIncoming", m_ArrowDelay); + self->AddTimer("PlayArrowSound", m_ArrowDelay - 4); } -void RainOfArrows::OnTimerDone(Entity* self, std::string timerName) -{ - auto* child = EntityManager::Instance()->GetEntity( - self->GetVar(u"ChildFX") - ); - - auto* player = EntityManager::Instance()->GetEntity( - self->GetVar(u"playerID") - ); +void RainOfArrows::OnTimerDone(Entity* self, std::string timerName) { + auto* child = EntityManager::Instance()->GetEntity( + self->GetVar(u"ChildFX") + ); - if (timerName == "ArrowsIncoming") - { - if (child == nullptr) - { - return; - } + auto* player = EntityManager::Instance()->GetEntity( + self->GetVar(u"playerID") + ); - auto* skillComponent = child->GetComponent(); + if (timerName == "ArrowsIncoming") { + if (child == nullptr) { + return; + } - if (skillComponent == nullptr) - { - return; - } + auto* skillComponent = child->GetComponent(); - skillComponent->CalculateBehavior( - m_ArrowSkill, - m_ArrowBehavior, - LWOOBJID_EMPTY, - true, - false, - player != nullptr ? player->GetObjectID() : LWOOBJID_EMPTY - ); - - self->AddTimer("FireSkill", 0.7f); - } - else if (timerName == "PlayArrowSound") - { - GameMessages::SendPlayNDAudioEmitter(self, UNASSIGNED_SYSTEM_ADDRESS, m_ArrowsGUID); - } - else if (timerName == "FireSkill") - { - if (child != nullptr) - { - child->Smash(); - } + if (skillComponent == nullptr) { + return; + } - self->Smash(player != nullptr ? player->GetObjectID() : LWOOBJID_EMPTY); - } + skillComponent->CalculateBehavior( + m_ArrowSkill, + m_ArrowBehavior, + LWOOBJID_EMPTY, + true, + false, + player != nullptr ? player->GetObjectID() : LWOOBJID_EMPTY + ); + + self->AddTimer("FireSkill", 0.7f); + } else if (timerName == "PlayArrowSound") { + GameMessages::SendPlayNDAudioEmitter(self, UNASSIGNED_SYSTEM_ADDRESS, m_ArrowsGUID); + } else if (timerName == "FireSkill") { + if (child != nullptr) { + child->Smash(); + } + + self->Smash(player != nullptr ? player->GetObjectID() : LWOOBJID_EMPTY); + } } diff --git a/dScripts/RainOfArrows.h b/dScripts/RainOfArrows.h index 5b997251..778ddfea 100644 --- a/dScripts/RainOfArrows.h +++ b/dScripts/RainOfArrows.h @@ -5,13 +5,13 @@ class RainOfArrows : public CppScripts::Script { public: void OnStartup(Entity* self) override; - void OnRebuildComplete(Entity* self, Entity* target) override; - void OnTimerDone(Entity* self, std::string timerName) override; + void OnRebuildComplete(Entity* self, Entity* target) override; + void OnTimerDone(Entity* self, std::string timerName) override; private: - LOT m_ArrowFXObject = 15850; - int32_t m_ArrowSkill = 1482; - int32_t m_ArrowBehavior = 36680; - int32_t m_ArrowDelay = 6; - std::string m_ArrowsGUID = "{532cba3c-54da-446c-986b-128af9647bdb}"; -}; \ No newline at end of file + LOT m_ArrowFXObject = 15850; + int32_t m_ArrowSkill = 1482; + int32_t m_ArrowBehavior = 36680; + int32_t m_ArrowDelay = 6; + std::string m_ArrowsGUID = "{532cba3c-54da-446c-986b-128af9647bdb}"; +}; diff --git a/dScripts/RandomSpawnerFin.cpp b/dScripts/RandomSpawnerFin.cpp index da0b655e..57793511 100644 --- a/dScripts/RandomSpawnerFin.cpp +++ b/dScripts/RandomSpawnerFin.cpp @@ -1,9 +1,8 @@ #include "RandomSpawnerFin.h" -void RandomSpawnerFin::OnStartup(Entity* self) -{ - zones = { - { //-- ** Load 1 -------------------------- ** +void RandomSpawnerFin::OnStartup(Entity* self) { + zones = { + { //-- ** Load 1 -------------------------- ** {{mobs.pirate, 3, "type1",}, {mobs.ronin, 3, "type2",}, {mobs.spider, 2, "type3",}}, @@ -63,25 +62,24 @@ void RandomSpawnerFin::OnStartup(Entity* self) {mobs.horse, 1, "type3",}}, 10 }, - }; - - sectionMultipliers = { - {"secA", 1}, - {"secB", 1}, - {"secC", 1.2f}, - {"secD", 1.3f}, - {"secE", 1.6f}, - {"secF", 1}, - {"secG", 1}, - {"secH", 1.2f}, - }; + }; - zoneName = "fin"; + sectionMultipliers = { + {"secA", 1}, + {"secB", 1}, + {"secC", 1.2f}, + {"secD", 1.3f}, + {"secE", 1.6f}, + {"secF", 1}, + {"secG", 1}, + {"secH", 1.2f}, + }; - BaseStartup(self); + zoneName = "fin"; + + BaseStartup(self); } -void RandomSpawnerFin::OnTimerDone(Entity* self, std::string timerName) -{ - BaseOnTimerDone(self, timerName); +void RandomSpawnerFin::OnTimerDone(Entity* self, std::string timerName) { + BaseOnTimerDone(self, timerName); } diff --git a/dScripts/RandomSpawnerFin.h b/dScripts/RandomSpawnerFin.h index 174b90f0..30416858 100644 --- a/dScripts/RandomSpawnerFin.h +++ b/dScripts/RandomSpawnerFin.h @@ -5,22 +5,22 @@ class RandomSpawnerFin : public CppScripts::Script, BaseRandomServer { void OnStartup(Entity* self) override; - void OnTimerDone(Entity* self, std::string timerName) override; + void OnTimerDone(Entity* self, std::string timerName) override; private: - struct Mobs - { - static const LOT stromb = 11212; - static const LOT mech = 11213; - static const LOT spider = 11214; - static const LOT pirate = 11215; - static const LOT admiral = 11216; - static const LOT gorilla = 11217; - static const LOT ronin = 11218; - static const LOT horse = 11219; - static const LOT dragon = 112201; - }; + struct Mobs + { + static const LOT stromb = 11212; + static const LOT mech = 11213; + static const LOT spider = 11214; + static const LOT pirate = 11215; + static const LOT admiral = 11216; + static const LOT gorilla = 11217; + static const LOT ronin = 11218; + static const LOT horse = 11219; + static const LOT dragon = 112201; + }; - Mobs mobs; + Mobs mobs; }; diff --git a/dScripts/RandomSpawnerPit.cpp b/dScripts/RandomSpawnerPit.cpp index 8dfa61b0..ceea9412 100644 --- a/dScripts/RandomSpawnerPit.cpp +++ b/dScripts/RandomSpawnerPit.cpp @@ -1,9 +1,8 @@ #include "RandomSpawnerPit.h" -void RandomSpawnerPit::OnStartup(Entity* self) -{ - zones = { - { //-- ** Load 1 -------------------------- ** +void RandomSpawnerPit::OnStartup(Entity* self) { + zones = { + { //-- ** Load 1 -------------------------- ** {{mobs.admiral, 4, "type1",}, {mobs.spider, 3, "type2",}}, 5 @@ -63,23 +62,22 @@ void RandomSpawnerPit::OnStartup(Entity* self) {mobs.pirate, 5, "type2",}}, 15 }, - }; + }; - sectionMultipliers = { - {"secA", 1}, - {"secB", 1.2f}, - {"secC", 1.2f}, - {"secD", 1}, - }; + sectionMultipliers = { + {"secA", 1}, + {"secB", 1.2f}, + {"secC", 1.2f}, + {"secD", 1}, + }; - zoneName = "pit"; + zoneName = "pit"; mobDeathResetNumber = 20; changeNum = 18; - BaseStartup(self); + BaseStartup(self); } -void RandomSpawnerPit::OnTimerDone(Entity* self, std::string timerName) -{ - BaseOnTimerDone(self, timerName); +void RandomSpawnerPit::OnTimerDone(Entity* self, std::string timerName) { + BaseOnTimerDone(self, timerName); } diff --git a/dScripts/RandomSpawnerPit.h b/dScripts/RandomSpawnerPit.h index 8346ec37..5ffceec5 100644 --- a/dScripts/RandomSpawnerPit.h +++ b/dScripts/RandomSpawnerPit.h @@ -5,22 +5,22 @@ class RandomSpawnerPit : public CppScripts::Script, BaseRandomServer { void OnStartup(Entity* self) override; - void OnTimerDone(Entity* self, std::string timerName) override; + void OnTimerDone(Entity* self, std::string timerName) override; private: - struct Mobs - { - static const LOT stromb = 11212; - static const LOT mech = 11213; - static const LOT spider = 11214; - static const LOT pirate = 11215; - static const LOT admiral = 11216; - static const LOT gorilla = 11217; - static const LOT ronin = 11218; - static const LOT horse = 11219; - static const LOT dragon = 112200; - }; + struct Mobs + { + static const LOT stromb = 11212; + static const LOT mech = 11213; + static const LOT spider = 11214; + static const LOT pirate = 11215; + static const LOT admiral = 11216; + static const LOT gorilla = 11217; + static const LOT ronin = 11218; + static const LOT horse = 11219; + static const LOT dragon = 112200; + }; - Mobs mobs; + Mobs mobs; }; diff --git a/dScripts/RandomSpawnerStr.cpp b/dScripts/RandomSpawnerStr.cpp index fa6ac117..0f7f5114 100644 --- a/dScripts/RandomSpawnerStr.cpp +++ b/dScripts/RandomSpawnerStr.cpp @@ -1,9 +1,8 @@ #include "RandomSpawnerStr.h" -void RandomSpawnerStr::OnStartup(Entity* self) -{ - zones = { - { //-- ** Load 1 -------------------------- ** +void RandomSpawnerStr::OnStartup(Entity* self) { + zones = { + { //-- ** Load 1 -------------------------- ** {{mobs.stromb, 4, "type1",}, {mobs.pirate, 3, "type2",}, {mobs.ronin, 3, "type3",}}, @@ -63,22 +62,21 @@ void RandomSpawnerStr::OnStartup(Entity* self) {mobs.pirate, 4, "type3",}}, 1 }, - }; + }; - sectionMultipliers = { - {"secA", 1}, - {"secB", 1}, - {"secC", 1.2f}, - }; + sectionMultipliers = { + {"secA", 1}, + {"secB", 1}, + {"secC", 1.2f}, + }; - zoneName = "str"; + zoneName = "str"; mobDeathResetNumber = 20; changeNum = 15; - BaseStartup(self); + BaseStartup(self); } -void RandomSpawnerStr::OnTimerDone(Entity* self, std::string timerName) -{ - BaseOnTimerDone(self, timerName); +void RandomSpawnerStr::OnTimerDone(Entity* self, std::string timerName) { + BaseOnTimerDone(self, timerName); } diff --git a/dScripts/RandomSpawnerStr.h b/dScripts/RandomSpawnerStr.h index a3ee920e..b6f0bbea 100644 --- a/dScripts/RandomSpawnerStr.h +++ b/dScripts/RandomSpawnerStr.h @@ -5,22 +5,22 @@ class RandomSpawnerStr : public CppScripts::Script, BaseRandomServer { void OnStartup(Entity* self) override; - void OnTimerDone(Entity* self, std::string timerName) override; + void OnTimerDone(Entity* self, std::string timerName) override; private: - struct Mobs - { - static const LOT stromb = 11212; - static const LOT mech = 11213; - static const LOT spider = 11214; - static const LOT pirate = 11215; - static const LOT admiral = 11216; - static const LOT gorilla = 11217; - static const LOT ronin = 11218; - static const LOT horse = 11219; - static const LOT dragon = 112200; - }; + struct Mobs + { + static const LOT stromb = 11212; + static const LOT mech = 11213; + static const LOT spider = 11214; + static const LOT pirate = 11215; + static const LOT admiral = 11216; + static const LOT gorilla = 11217; + static const LOT ronin = 11218; + static const LOT horse = 11219; + static const LOT dragon = 112200; + }; - Mobs mobs; + Mobs mobs; }; diff --git a/dScripts/RandomSpawnerZip.cpp b/dScripts/RandomSpawnerZip.cpp index 083d4ae7..3f45a784 100644 --- a/dScripts/RandomSpawnerZip.cpp +++ b/dScripts/RandomSpawnerZip.cpp @@ -1,9 +1,8 @@ #include "RandomSpawnerZip.h" -void RandomSpawnerZip::OnStartup(Entity* self) -{ - zones = { - { //-- ** Load 1 -------------------------- ** +void RandomSpawnerZip::OnStartup(Entity* self) { + zones = { + { //-- ** Load 1 -------------------------- ** {{mobs.stromb, 3, "type1",}, {mobs.pirate, 2, "type2",}, {mobs.admiral, 2, "type3",}, @@ -73,21 +72,20 @@ void RandomSpawnerZip::OnStartup(Entity* self) {mobs.pirate, 0, "type4",}}, 1 }, - }; + }; - sectionMultipliers = { - {"secA", 1.2f}, - {"secB", 1.2f}, - }; + sectionMultipliers = { + {"secA", 1.2f}, + {"secB", 1.2f}, + }; - zoneName = "zip"; + zoneName = "zip"; mobDeathResetNumber = 20; changeNum = 9; - BaseStartup(self); + BaseStartup(self); } -void RandomSpawnerZip::OnTimerDone(Entity* self, std::string timerName) -{ - BaseOnTimerDone(self, timerName); +void RandomSpawnerZip::OnTimerDone(Entity* self, std::string timerName) { + BaseOnTimerDone(self, timerName); } diff --git a/dScripts/RandomSpawnerZip.h b/dScripts/RandomSpawnerZip.h index 6c0cf511..f2aa6635 100644 --- a/dScripts/RandomSpawnerZip.h +++ b/dScripts/RandomSpawnerZip.h @@ -5,22 +5,22 @@ class RandomSpawnerZip : public CppScripts::Script, BaseRandomServer { void OnStartup(Entity* self) override; - void OnTimerDone(Entity* self, std::string timerName) override; + void OnTimerDone(Entity* self, std::string timerName) override; private: - struct Mobs - { - static const LOT stromb = 11212; - static const LOT mech = 11213; - static const LOT spider = 11214; - static const LOT pirate = 11215; - static const LOT admiral = 11216; - static const LOT gorilla = 11217; - static const LOT ronin = 11218; - static const LOT horse = 11219; - static const LOT dragon = 112200; - }; + struct Mobs + { + static const LOT stromb = 11212; + static const LOT mech = 11213; + static const LOT spider = 11214; + static const LOT pirate = 11215; + static const LOT admiral = 11216; + static const LOT gorilla = 11217; + static const LOT ronin = 11218; + static const LOT horse = 11219; + static const LOT dragon = 112200; + }; - Mobs mobs; + Mobs mobs; }; diff --git a/dScripts/RockHydrantBroken.cpp b/dScripts/RockHydrantBroken.cpp index 50e3c88d..835d52f6 100644 --- a/dScripts/RockHydrantBroken.cpp +++ b/dScripts/RockHydrantBroken.cpp @@ -2,16 +2,14 @@ #include "EntityManager.h" #include "GameMessages.h" -void RockHydrantBroken::OnStartup(Entity* self) -{ +void RockHydrantBroken::OnStartup(Entity* self) { self->AddTimer("playEffect", 1); const auto hydrant = "hydrant" + self->GetVar(u"hydrant"); const auto bouncers = EntityManager::Instance()->GetEntitiesInGroup(hydrant); - for (auto* bouncer : bouncers) - { + for (auto* bouncer : bouncers) { self->SetVar(u"bouncer", bouncer->GetObjectID()); @@ -23,23 +21,18 @@ void RockHydrantBroken::OnStartup(Entity* self) self->AddTimer("KillBroken", 10); } -void RockHydrantBroken::OnTimerDone(Entity* self, std::string timerName) -{ - if (timerName == "KillBroken") - { +void RockHydrantBroken::OnTimerDone(Entity* self, std::string timerName) { + if (timerName == "KillBroken") { auto* bouncer = EntityManager::Instance()->GetEntity(self->GetVar(u"bouncer")); - if (bouncer != nullptr) - { + if (bouncer != nullptr) { GameMessages::SendBouncerActiveStatus(bouncer->GetObjectID(), false, UNASSIGNED_SYSTEM_ADDRESS); GameMessages::SendNotifyObject(bouncer->GetObjectID(), self->GetObjectID(), u"disableCollision", UNASSIGNED_SYSTEM_ADDRESS); } self->Kill(); - } - else if (timerName == "playEffect") - { + } else if (timerName == "playEffect") { GameMessages::SendPlayFXEffect(self->GetObjectID(), 4737, u"water", "water", LWOOBJID_EMPTY, 1, 1, true); } } diff --git a/dScripts/RockHydrantSmashable.cpp b/dScripts/RockHydrantSmashable.cpp index 8d5b5861..d76eca8d 100644 --- a/dScripts/RockHydrantSmashable.cpp +++ b/dScripts/RockHydrantSmashable.cpp @@ -2,17 +2,16 @@ #include "EntityManager.h" #include "GeneralUtils.h" -void RockHydrantSmashable::OnDie(Entity* self, Entity* killer) -{ +void RockHydrantSmashable::OnDie(Entity* self, Entity* killer) { const auto hydrantName = self->GetVar(u"hydrant"); LDFBaseData* data = new LDFData(u"hydrant", GeneralUtils::UTF16ToWTF8(hydrantName)); - EntityInfo info {}; + EntityInfo info{}; info.lot = ROCK_HYDRANT_BROKEN; info.pos = self->GetPosition(); info.rot = self->GetRotation(); - info.settings = {data}; + info.settings = { data }; info.spawnerID = self->GetSpawnerID(); auto* hydrant = EntityManager::Instance()->CreateEntity(info); diff --git a/dScripts/SGCannon.cpp b/dScripts/SGCannon.cpp index 9f270562..049837a4 100644 --- a/dScripts/SGCannon.cpp +++ b/dScripts/SGCannon.cpp @@ -12,1071 +12,1058 @@ #include "../dWorldServer/ObjectIDManager.h" #include "MissionComponent.h" -void SGCannon::OnStartup(Entity *self) { - Game::logger->Log("SGCannon", "OnStartup"); +void SGCannon::OnStartup(Entity* self) { + Game::logger->Log("SGCannon", "OnStartup"); - m_Waves = GetWaves(); - constants = GetConstants(); + m_Waves = GetWaves(); + constants = GetConstants(); - ResetVars(self); + ResetVars(self); - self->SetVar(GameStartedVariable, false); - self->SetVar(InitialVelocityVariable, {}); - self->SetVar(ImpactSkillVariale, constants.impactSkillID); + self->SetVar(GameStartedVariable, false); + self->SetVar(InitialVelocityVariable, {}); + self->SetVar(ImpactSkillVariale, constants.impactSkillID); - auto* shootingGalleryComponent = self->GetComponent(); - if (shootingGalleryComponent != nullptr) { - shootingGalleryComponent->SetStaticParams({ - Vector3 { -327.8609924316406, 256.8999938964844, 1.6482199430465698 }, - Vector3 { -181.4320068359375, 212.39999389648438, 2.5182199478149414 } - }); + auto* shootingGalleryComponent = self->GetComponent(); + if (shootingGalleryComponent != nullptr) { + shootingGalleryComponent->SetStaticParams({ + Vector3 { -327.8609924316406, 256.8999938964844, 1.6482199430465698 }, + Vector3 { -181.4320068359375, 212.39999389648438, 2.5182199478149414 } + }); - shootingGalleryComponent->SetDynamicParams({ - Vector3 { 0.0, 4.3, 9.0 }, - Vector3 { }, - 129.0, - 800.0, - 30.0, - 0.0, - -1.0, - 58.6 - }); - } + shootingGalleryComponent->SetDynamicParams({ + Vector3 { 0.0, 4.3, 9.0 }, + Vector3 { }, + 129.0, + 800.0, + 30.0, + 0.0, + -1.0, + 58.6 + }); + } - self->SetVar(TimeLimitVariable, 30); - self->SetVar>(ValidActorsVariable, {3109, 3110, 3111, 3112, 3125, 3126}); - self->SetVar>(ValidEffectsVariable, {3122}); - self->SetVar>(StreakBonusVariable, {1, 2, 5, 10}); - self->SetVar(SuperChargeActiveVariable, false); - self->SetVar(MatrixVariable, 1); - self->SetVar(InitVariable, true); + self->SetVar(TimeLimitVariable, 30); + self->SetVar>(ValidActorsVariable, { 3109, 3110, 3111, 3112, 3125, 3126 }); + self->SetVar>(ValidEffectsVariable, { 3122 }); + self->SetVar>(StreakBonusVariable, { 1, 2, 5, 10 }); + self->SetVar(SuperChargeActiveVariable, false); + self->SetVar(MatrixVariable, 1); + self->SetVar(InitVariable, true); - auto* simplePhysicsComponent = self->GetComponent(); + auto* simplePhysicsComponent = self->GetComponent(); - if (simplePhysicsComponent != nullptr) { - simplePhysicsComponent->SetPhysicsMotionState(5); - } + if (simplePhysicsComponent != nullptr) { + simplePhysicsComponent->SetPhysicsMotionState(5); + } } -void SGCannon::OnPlayerLoaded(Entity *self, Entity *player) { - Game::logger->Log("SGCannon", "Player loaded"); - self->SetVar(PlayerIDVariable, player->GetObjectID()); +void SGCannon::OnPlayerLoaded(Entity* self, Entity* player) { + Game::logger->Log("SGCannon", "Player loaded"); + self->SetVar(PlayerIDVariable, player->GetObjectID()); } -void SGCannon::OnFireEventServerSide(Entity *self, Entity *sender, std::string args, int32_t param1, int32_t param2, - int32_t param3) { - Script::OnFireEventServerSide(self, sender, args, param1, param2, param3); +void SGCannon::OnFireEventServerSide(Entity* self, Entity* sender, std::string args, int32_t param1, int32_t param2, + int32_t param3) { + Script::OnFireEventServerSide(self, sender, args, param1, param2, param3); } -void SGCannon::OnActivityStateChangeRequest(Entity *self, LWOOBJID senderID, int32_t value1, int32_t value2, - const std::u16string &stringValue) { - Game::logger->Log("SGCannon", "Got activity state change request: %s", GeneralUtils::UTF16ToWTF8(stringValue).c_str()); - if (stringValue == u"clientready") { - auto* player = EntityManager::Instance()->GetEntity(self->GetVar(PlayerIDVariable)); - if (player != nullptr) { - Game::logger->Log("SGCannon", "Player is ready"); - /*GameMessages::SendSetStunned(player->GetObjectID(), PUSH, player->GetSystemAddress(), LWOOBJID_EMPTY, - true, true, true, true, true, true, true);*/ +void SGCannon::OnActivityStateChangeRequest(Entity* self, LWOOBJID senderID, int32_t value1, int32_t value2, + const std::u16string& stringValue) { + Game::logger->Log("SGCannon", "Got activity state change request: %s", GeneralUtils::UTF16ToWTF8(stringValue).c_str()); + if (stringValue == u"clientready") { + auto* player = EntityManager::Instance()->GetEntity(self->GetVar(PlayerIDVariable)); + if (player != nullptr) { + Game::logger->Log("SGCannon", "Player is ready"); + /*GameMessages::SendSetStunned(player->GetObjectID(), PUSH, player->GetSystemAddress(), LWOOBJID_EMPTY, + true, true, true, true, true, true, true);*/ - Game::logger->Log("SGCannon", "Sending ActivityEnter"); + Game::logger->Log("SGCannon", "Sending ActivityEnter"); - GameMessages::SendActivityEnter(self->GetObjectID(), player->GetSystemAddress()); + GameMessages::SendActivityEnter(self->GetObjectID(), player->GetSystemAddress()); - auto* shootingGalleryComponent = self->GetComponent(); + auto* shootingGalleryComponent = self->GetComponent(); - if (shootingGalleryComponent != nullptr) { - shootingGalleryComponent->SetCurrentPlayerID(player->GetObjectID()); + if (shootingGalleryComponent != nullptr) { + shootingGalleryComponent->SetCurrentPlayerID(player->GetObjectID()); - Game::logger->Log("SGCannon", "Setting player ID"); + Game::logger->Log("SGCannon", "Setting player ID"); - EntityManager::Instance()->SerializeEntity(self); - } - else { - Game::logger->Log("SGCannon", "Shooting gallery component is null"); - } + EntityManager::Instance()->SerializeEntity(self); + } else { + Game::logger->Log("SGCannon", "Shooting gallery component is null"); + } - auto* characterComponent = player->GetComponent(); + auto* characterComponent = player->GetComponent(); - if (characterComponent != nullptr) { - characterComponent->SetIsRacing(true); - characterComponent->SetCurrentActivity(2); - auto possessor = player->GetComponent(); - if(possessor) { - possessor->SetPossessable(self->GetObjectID()); - possessor->SetPossessableType(ePossessionType::NO_POSSESSION); - } + if (characterComponent != nullptr) { + characterComponent->SetIsRacing(true); + characterComponent->SetCurrentActivity(2); + auto possessor = player->GetComponent(); + if (possessor) { + possessor->SetPossessable(self->GetObjectID()); + possessor->SetPossessableType(ePossessionType::NO_POSSESSION); + } - EntityManager::Instance()->SerializeEntity(player); - } + EntityManager::Instance()->SerializeEntity(player); + } - self->SetNetworkVar(HideScoreBoardVariable, true); - self->SetNetworkVar(ReSetSuperChargeVariable, true); - self->SetNetworkVar(ShowLoadingUI, true); + self->SetNetworkVar(HideScoreBoardVariable, true); + self->SetNetworkVar(ReSetSuperChargeVariable, true); + self->SetNetworkVar(ShowLoadingUI, true); - /* - GameMessages::SendTeleport( - player->GetObjectID(), - {-292.6415710449219, 230.20237731933594, -3.9090466499328613}, - {0.7067984342575073, -6.527870573336259e-05, 0.707414984703064, 0.00021762956748716533}, - player->GetSystemAddress(), true - ); - */ + /* + GameMessages::SendTeleport( + player->GetObjectID(), + {-292.6415710449219, 230.20237731933594, -3.9090466499328613}, + {0.7067984342575073, -6.527870573336259e-05, 0.707414984703064, 0.00021762956748716533}, + player->GetSystemAddress(), true + ); + */ - //GameMessages::SendRequestActivityEnter(self->GetObjectID(), player->GetSystemAddress(), false, player->GetObjectID()); - } - else { - Game::logger->Log("SGCannon", "Player not found"); - } - } - else if (value1 == 1200) { - StartGame(self); - } + //GameMessages::SendRequestActivityEnter(self->GetObjectID(), player->GetSystemAddress(), false, player->GetObjectID()); + } else { + Game::logger->Log("SGCannon", "Player not found"); + } + } else if (value1 == 1200) { + StartGame(self); + } } -void SGCannon::OnMessageBoxResponse(Entity *self, Entity *sender, int32_t button, const std::u16string &identifier, - const std::u16string &userData) { - auto * player = EntityManager::Instance()->GetEntity(self->GetVar(PlayerIDVariable)); - if (player != nullptr) { - if (button == 1 && identifier == u"Shooting_Gallery_Stop") - { - UpdatePlayer(self, player->GetObjectID(), true); - RemovePlayer(player->GetObjectID()); - StopGame(self, true); - return; - } +void SGCannon::OnMessageBoxResponse(Entity* self, Entity* sender, int32_t button, const std::u16string& identifier, + const std::u16string& userData) { + auto* player = EntityManager::Instance()->GetEntity(self->GetVar(PlayerIDVariable)); + if (player != nullptr) { + if (button == 1 && identifier == u"Shooting_Gallery_Stop") { + UpdatePlayer(self, player->GetObjectID(), true); + RemovePlayer(player->GetObjectID()); + StopGame(self, true); + return; + } - if (identifier == u"Scoreboardinfo") { - GameMessages::SendDisplayMessageBox(player->GetObjectID(), true, - dZoneManager::Instance()->GetZoneControlObject()->GetObjectID(), - u"Shooting_Gallery_Retry?", 2, u"Retry?", - u"", player->GetSystemAddress()); - } else { - if ((button == 1 && (identifier == u"Shooting_Gallery_Retry" || identifier == u"RePlay")) - || identifier == u"SG1" || button == 0) { + if (identifier == u"Scoreboardinfo") { + GameMessages::SendDisplayMessageBox(player->GetObjectID(), true, + dZoneManager::Instance()->GetZoneControlObject()->GetObjectID(), + u"Shooting_Gallery_Retry?", 2, u"Retry?", + u"", player->GetSystemAddress()); + } else { + if ((button == 1 && (identifier == u"Shooting_Gallery_Retry" || identifier == u"RePlay")) + || identifier == u"SG1" || button == 0) { - if (identifier == u"RePlay") { - static_cast(player)->SendToZone(1300); + if (identifier == u"RePlay") { + static_cast(player)->SendToZone(1300); - return; - } + return; + } - self->SetNetworkVar(ClearVariable, true); - StartGame(self); - } else if (button == 1 && identifier == u"Shooting_Gallery_Exit") { - UpdatePlayer(self, player->GetObjectID(), true); - RemovePlayer(player->GetObjectID()); - } - } - } + self->SetNetworkVar(ClearVariable, true); + StartGame(self); + } else if (button == 1 && identifier == u"Shooting_Gallery_Exit") { + UpdatePlayer(self, player->GetObjectID(), true); + RemovePlayer(player->GetObjectID()); + } + } + } } -void SGCannon::OnActivityTimerDone(Entity *self, const std::string &name) { - if (name == SuperChargeTimer && !self->GetVar(SuperChargePausedVariable)) { - if (self->GetVar(WaveStatusVariable) || self->GetVar(CurrentSuperChargedTimeVariable) < 1) { - self->SetNetworkVar(ChargeCountingVariable, 99); - self->SetNetworkVar(SuperChargeBarVariable, 0); - ToggleSuperCharge(self, false); - } - } else if (name == SpawnWaveTimer) { - if (self->GetVar(GameStartedVariable)) { - self->SetVar(WaveStatusVariable, true); - const auto wave = (int32_t) self->GetVar(ThisWaveVariable); +void SGCannon::OnActivityTimerDone(Entity* self, const std::string& name) { + if (name == SuperChargeTimer && !self->GetVar(SuperChargePausedVariable)) { + if (self->GetVar(WaveStatusVariable) || self->GetVar(CurrentSuperChargedTimeVariable) < 1) { + self->SetNetworkVar(ChargeCountingVariable, 99); + self->SetNetworkVar(SuperChargeBarVariable, 0); + ToggleSuperCharge(self, false); + } + } else if (name == SpawnWaveTimer) { + if (self->GetVar(GameStartedVariable)) { + self->SetVar(WaveStatusVariable, true); + const auto wave = (int32_t)self->GetVar(ThisWaveVariable); - if (wave != 0 && self->GetVar(SuperChargePausedVariable)) { - StartChargedCannon(self, self->GetVar(CurrentSuperChargedTimeVariable)); - self->SetVar(CurrentSuperChargedTimeVariable, 0); - } + if (wave != 0 && self->GetVar(SuperChargePausedVariable)) { + StartChargedCannon(self, self->GetVar(CurrentSuperChargedTimeVariable)); + self->SetVar(CurrentSuperChargedTimeVariable, 0); + } - TimerToggle(self, true); + TimerToggle(self, true); - for (const auto& enemyToSpawn : m_Waves.at(self->GetVar(ThisWaveVariable))) { - SpawnObject(self, enemyToSpawn, true); - } + for (const auto& enemyToSpawn : m_Waves.at(self->GetVar(ThisWaveVariable))) { + SpawnObject(self, enemyToSpawn, true); + } - Game::logger->Log("SGCannon", "Current wave spawn: %i/%i", wave, m_Waves.size()); + Game::logger->Log("SGCannon", "Current wave spawn: %i/%i", wave, m_Waves.size()); - // All waves completed - const auto timeLimit = (float_t) self->GetVar(TimeLimitVariable); - if (wave >= m_Waves.size()) { - ActivityTimerStart(self, GameOverTimer, timeLimit, timeLimit); - } else { - ActivityTimerStart(self, EndWaveTimer, timeLimit, timeLimit); - } + // All waves completed + const auto timeLimit = (float_t)self->GetVar(TimeLimitVariable); + if (wave >= m_Waves.size()) { + ActivityTimerStart(self, GameOverTimer, timeLimit, timeLimit); + } else { + ActivityTimerStart(self, EndWaveTimer, timeLimit, timeLimit); + } - const auto* player = EntityManager::Instance()->GetEntity(self->GetVar(PlayerIDVariable)); - if (player != nullptr) { - GameMessages::SendPlayFXEffect(player->GetObjectID(), -1, u"SG-start", ""); + const auto* player = EntityManager::Instance()->GetEntity(self->GetVar(PlayerIDVariable)); + if (player != nullptr) { + GameMessages::SendPlayFXEffect(player->GetObjectID(), -1, u"SG-start", ""); - GameMessages::SendStartActivityTime(self->GetObjectID(), timeLimit, player->GetSystemAddress()); - Game::logger->Log("SGCannon", "Sending ActivityPause false"); + GameMessages::SendStartActivityTime(self->GetObjectID(), timeLimit, player->GetSystemAddress()); + Game::logger->Log("SGCannon", "Sending ActivityPause false"); - GameMessages::SendActivityPause(self->GetObjectID(), false, player->GetSystemAddress()); - } - } - } else if (name == EndWaveTimer) { - self->SetVar(WaveStatusVariable, false); - TimerToggle(self); - RecordPlayerScore(self); + GameMessages::SendActivityPause(self->GetObjectID(), false, player->GetSystemAddress()); + } + } + } else if (name == EndWaveTimer) { + self->SetVar(WaveStatusVariable, false); + TimerToggle(self); + RecordPlayerScore(self); - if (self->GetVar(ThisWaveVariable) >= 2) { - GameMessages::SendActivityPause(self->GetObjectID(), true); - ActivityTimerStart(self, GameOverTimer, 0.1, 0.1); - return; - } + if (self->GetVar(ThisWaveVariable) >= 2) { + GameMessages::SendActivityPause(self->GetObjectID(), true); + ActivityTimerStart(self, GameOverTimer, 0.1, 0.1); + return; + } - self->SetVar(ThisWaveVariable, self->GetVar(ThisWaveVariable) + 1); - PlaySceneAnimation(self, u"wave" + GeneralUtils::to_u16string(self->GetVar(ThisWaveVariable)), true, true, 1.7f); - self->SetNetworkVar(WaveNumVariable, self->GetVar(ThisWaveVariable) + 1); - self->SetNetworkVar(WaveStrVariable, self->GetVar(TimeLimitVariable)); + self->SetVar(ThisWaveVariable, self->GetVar(ThisWaveVariable) + 1); + PlaySceneAnimation(self, u"wave" + GeneralUtils::to_u16string(self->GetVar(ThisWaveVariable)), true, true, 1.7f); + self->SetNetworkVar(WaveNumVariable, self->GetVar(ThisWaveVariable) + 1); + self->SetNetworkVar(WaveStrVariable, self->GetVar(TimeLimitVariable)); - Game::logger->Log("SGCannon", "Current wave: %i/%i", self->GetVar(ThisWaveVariable), m_Waves.size()); + Game::logger->Log("SGCannon", "Current wave: %i/%i", self->GetVar(ThisWaveVariable), m_Waves.size()); - if (self->GetVar(ThisWaveVariable) >= m_Waves.size()) { - ActivityTimerStart(self, GameOverTimer, 0.1, 0.1); - } else { - ActivityTimerStart(self, SpawnWaveTimer, constants.inBetweenWavePause, constants.inBetweenWavePause); - } + if (self->GetVar(ThisWaveVariable) >= m_Waves.size()) { + ActivityTimerStart(self, GameOverTimer, 0.1, 0.1); + } else { + ActivityTimerStart(self, SpawnWaveTimer, constants.inBetweenWavePause, constants.inBetweenWavePause); + } - Game::logger->Log("SGCannon", "Sending ActivityPause true"); + Game::logger->Log("SGCannon", "Sending ActivityPause true"); - GameMessages::SendActivityPause(self->GetObjectID(), true); - if (self->GetVar(SuperChargeActiveVariable) && !self->GetVar(SuperChargePausedVariable)) { - PauseChargeCannon(self); - } - } else if (name == GameOverTimer) { - auto* player = EntityManager::Instance()->GetEntity(self->GetVar(PlayerIDVariable)); - if (player != nullptr) { - Game::logger->Log("SGCannon", "Sending ActivityPause true"); + GameMessages::SendActivityPause(self->GetObjectID(), true); + if (self->GetVar(SuperChargeActiveVariable) && !self->GetVar(SuperChargePausedVariable)) { + PauseChargeCannon(self); + } + } else if (name == GameOverTimer) { + auto* player = EntityManager::Instance()->GetEntity(self->GetVar(PlayerIDVariable)); + if (player != nullptr) { + Game::logger->Log("SGCannon", "Sending ActivityPause true"); - GameMessages::SendActivityPause(self->GetObjectID(), true, player->GetSystemAddress()); + GameMessages::SendActivityPause(self->GetObjectID(), true, player->GetSystemAddress()); - /*const auto leftoverCannonballs = EntityManager::Instance()->GetEntitiesInGroup("cannonball"); - if (leftoverCannonballs.empty()) { - RecordPlayerScore(self); + /*const auto leftoverCannonballs = EntityManager::Instance()->GetEntitiesInGroup("cannonball"); + if (leftoverCannonballs.empty()) { + RecordPlayerScore(self); - } else { - ActivityTimerStart(self, EndGameBufferTimer, 1, leftoverCannonballs.size()); - }*/ + } else { + ActivityTimerStart(self, EndGameBufferTimer, 1, leftoverCannonballs.size()); + }*/ - ActivityTimerStart(self, EndGameBufferTimer, 1, 1); + ActivityTimerStart(self, EndGameBufferTimer, 1, 1); - TimerToggle(self); - } - } else if (name.rfind(DoSpawnTimer, 0) == 0) { - if (self->GetVar(GameStartedVariable)) { - const auto spawnNumber = (uint32_t) std::stoi(name.substr(7)); - const auto& activeSpawns = self->GetVar>(ActiveSpawnsVariable); - const auto& toSpawn = activeSpawns.at(spawnNumber); + TimerToggle(self); + } + } else if (name.rfind(DoSpawnTimer, 0) == 0) { + if (self->GetVar(GameStartedVariable)) { + const auto spawnNumber = (uint32_t)std::stoi(name.substr(7)); + const auto& activeSpawns = self->GetVar>(ActiveSpawnsVariable); + const auto& toSpawn = activeSpawns.at(spawnNumber); - const auto pathIndex = GeneralUtils::GenerateRandomNumber(0, toSpawn.spawnPaths.size() - 1); + const auto pathIndex = GeneralUtils::GenerateRandomNumber(0, toSpawn.spawnPaths.size() - 1); - const auto* path = dZoneManager::Instance()->GetZone()->GetPath( - toSpawn.spawnPaths.at(pathIndex) - ); + const auto* path = dZoneManager::Instance()->GetZone()->GetPath( + toSpawn.spawnPaths.at(pathIndex) + ); - auto info = EntityInfo {}; - info.lot = toSpawn.lot; - info.spawnerID = self->GetObjectID(); - info.pos = path->pathWaypoints.at(0).position; + auto info = EntityInfo{}; + info.lot = toSpawn.lot; + info.spawnerID = self->GetObjectID(); + info.pos = path->pathWaypoints.at(0).position; - info.settings = { - new LDFData(u"SpawnData", toSpawn), - new LDFData(u"custom_script_server", "scripts/ai/ACT/SG_TARGET.lua"), - new LDFData(u"custom_script_client", "scripts/client/ai/SG_TARGET_CLIENT.lua"), - new LDFData(u"attached_path", path->pathName), - new LDFData(u"attached_path_start", 0), - new LDFData(u"groupID", u"SGEnemy") - }; + info.settings = { + new LDFData(u"SpawnData", toSpawn), + new LDFData(u"custom_script_server", "scripts/ai/ACT/SG_TARGET.lua"), + new LDFData(u"custom_script_client", "scripts/client/ai/SG_TARGET_CLIENT.lua"), + new LDFData(u"attached_path", path->pathName), + new LDFData(u"attached_path_start", 0), + new LDFData(u"groupID", u"SGEnemy") + }; - Game::logger->Log("SGCannon", "Spawning enemy %i on path %s", toSpawn.lot, path->pathName.c_str()); + Game::logger->Log("SGCannon", "Spawning enemy %i on path %s", toSpawn.lot, path->pathName.c_str()); - auto* enemy = EntityManager::Instance()->CreateEntity(info, nullptr, self); - EntityManager::Instance()->ConstructEntity(enemy); + auto* enemy = EntityManager::Instance()->CreateEntity(info, nullptr, self); + EntityManager::Instance()->ConstructEntity(enemy); - if (true) { - auto* movementAI = new MovementAIComponent(enemy, {}); + if (true) { + auto* movementAI = new MovementAIComponent(enemy, {}); - enemy->AddComponent(COMPONENT_TYPE_MOVEMENT_AI, movementAI); + enemy->AddComponent(COMPONENT_TYPE_MOVEMENT_AI, movementAI); - movementAI->SetSpeed(toSpawn.initialSpeed); - movementAI->SetCurrentSpeed(toSpawn.initialSpeed); - movementAI->SetHaltDistance(0.0f); + movementAI->SetSpeed(toSpawn.initialSpeed); + movementAI->SetCurrentSpeed(toSpawn.initialSpeed); + movementAI->SetHaltDistance(0.0f); - std::vector pathWaypoints; + std::vector pathWaypoints; - for (const auto& waypoint : path->pathWaypoints) { - pathWaypoints.push_back(waypoint.position); - } + for (const auto& waypoint : path->pathWaypoints) { + pathWaypoints.push_back(waypoint.position); + } - if (GeneralUtils::GenerateRandomNumber(0, 1) < 0.5f) { - std::reverse(pathWaypoints.begin(), pathWaypoints.end()); - } + if (GeneralUtils::GenerateRandomNumber(0, 1) < 0.5f) { + std::reverse(pathWaypoints.begin(), pathWaypoints.end()); + } - movementAI->SetPath(pathWaypoints); + movementAI->SetPath(pathWaypoints); - enemy->AddDieCallback([this, self, enemy, name] () { - RegisterHit(self, enemy, name); - }); - } + enemy->AddDieCallback([this, self, enemy, name]() { + RegisterHit(self, enemy, name); + }); + } - // Save the enemy and tell it to start pathing - if (enemy != nullptr) { - const_cast&>(self->GetVar>(SpawnedObjects)).push_back(enemy->GetObjectID()); - GameMessages::SendPlatformResync(enemy, UNASSIGNED_SYSTEM_ADDRESS); - } - } - } else if (name == EndGameBufferTimer) { - RecordPlayerScore(self); - StopGame(self, false); - } + // Save the enemy and tell it to start pathing + if (enemy != nullptr) { + const_cast&>(self->GetVar>(SpawnedObjects)).push_back(enemy->GetObjectID()); + GameMessages::SendPlatformResync(enemy, UNASSIGNED_SYSTEM_ADDRESS); + } + } + } else if (name == EndGameBufferTimer) { + RecordPlayerScore(self); + StopGame(self, false); + } } void -SGCannon::OnActivityTimerUpdate(Entity *self, const std::string &name, float_t timeRemaining, float_t elapsedTime) { - ActivityManager::OnActivityTimerUpdate(self, name, timeRemaining, elapsedTime); +SGCannon::OnActivityTimerUpdate(Entity* self, const std::string& name, float_t timeRemaining, float_t elapsedTime) { + ActivityManager::OnActivityTimerUpdate(self, name, timeRemaining, elapsedTime); } -void SGCannon::StartGame(Entity *self) { - self->SetNetworkVar(TimeLimitVariable, self->GetVar(TimeLimitVariable)); - self->SetNetworkVar(AudioStartIntroVariable, true); - self->SetVar(CurrentRewardVariable, LOT_NULL); +void SGCannon::StartGame(Entity* self) { + self->SetNetworkVar(TimeLimitVariable, self->GetVar(TimeLimitVariable)); + self->SetNetworkVar(AudioStartIntroVariable, true); + self->SetVar(CurrentRewardVariable, LOT_NULL); - auto rewardObjects = EntityManager::Instance()->GetEntitiesInGroup(constants.rewardModelGroup); - for (auto* reward : rewardObjects) { - reward->OnFireEventServerSide(self, ModelToBuildEvent); - } + auto rewardObjects = EntityManager::Instance()->GetEntitiesInGroup(constants.rewardModelGroup); + for (auto* reward : rewardObjects) { + reward->OnFireEventServerSide(self, ModelToBuildEvent); + } - auto* player = EntityManager::Instance()->GetEntity(self->GetVar(PlayerIDVariable)); - if (player != nullptr) { - GetLeaderboardData(self, player->GetObjectID(), GetActivityID(self)); - Game::logger->Log("SGCannon", "Sending ActivityStart"); - GameMessages::SendActivityStart(self->GetObjectID(), player->GetSystemAddress()); + auto* player = EntityManager::Instance()->GetEntity(self->GetVar(PlayerIDVariable)); + if (player != nullptr) { + GetLeaderboardData(self, player->GetObjectID(), GetActivityID(self)); + Game::logger->Log("SGCannon", "Sending ActivityStart"); + GameMessages::SendActivityStart(self->GetObjectID(), player->GetSystemAddress()); - GameMessages::SendPlayFXEffect(self->GetObjectID(), -1, u"start", ""); + GameMessages::SendPlayFXEffect(self->GetObjectID(), -1, u"start", ""); - self->SetNetworkVar(ClearVariable, true); - DoGameStartup(self); + self->SetNetworkVar(ClearVariable, true); + DoGameStartup(self); - if (!self->GetVar(FirstTimeDoneVariable)) { - TakeActivityCost(self, player->GetObjectID()); - } + if (!self->GetVar(FirstTimeDoneVariable)) { + TakeActivityCost(self, player->GetObjectID()); + } - self->SetVar(FirstTimeDoneVariable, true); - } + self->SetVar(FirstTimeDoneVariable, true); + } - SpawnNewModel(self); + SpawnNewModel(self); } -void SGCannon::DoGameStartup(Entity *self) { - ResetVars(self); - self->SetVar(GameStartedVariable, true); - self->SetNetworkVar(ClearVariable, true); - self->SetVar(ThisWaveVariable, 0); +void SGCannon::DoGameStartup(Entity* self) { + ResetVars(self); + self->SetVar(GameStartedVariable, true); + self->SetNetworkVar(ClearVariable, true); + self->SetVar(ThisWaveVariable, 0); - if (constants.firstWaveStartTime < 1) { - constants.firstWaveStartTime = 1; - } + if (constants.firstWaveStartTime < 1) { + constants.firstWaveStartTime = 1; + } - ActivityTimerStart(self, SpawnWaveTimer, constants.firstWaveStartTime, - constants.firstWaveStartTime); + ActivityTimerStart(self, SpawnWaveTimer, constants.firstWaveStartTime, + constants.firstWaveStartTime); } -void SGCannon::SpawnNewModel(Entity *self) { +void SGCannon::SpawnNewModel(Entity* self) { - // Add a new reward to the existing rewards - const auto currentReward = self->GetVar(CurrentRewardVariable); - if (currentReward != -1) { - auto rewards = self->GetVar>(RewardsVariable); - rewards.push_back(currentReward); - self->SetNetworkVar(RewardAddedVariable, currentReward); - } + // Add a new reward to the existing rewards + const auto currentReward = self->GetVar(CurrentRewardVariable); + if (currentReward != -1) { + auto rewards = self->GetVar>(RewardsVariable); + rewards.push_back(currentReward); + self->SetNetworkVar(RewardAddedVariable, currentReward); + } - auto* player = EntityManager::Instance()->GetEntity(self->GetVar(PlayerIDVariable)); - if (player != nullptr) { - for (auto* rewardModel : EntityManager::Instance()->GetEntitiesInGroup(constants.rewardModelGroup)) { - uint32_t lootMatrix; - switch (self->GetVar(MatrixVariable)) { - case 1: - lootMatrix = constants.scoreLootMatrix1; - break; - case 2: - lootMatrix = constants.scoreLootMatrix2; - break; - case 3: - lootMatrix = constants.scoreLootMatrix3; - break; - case 4: - lootMatrix = constants.scoreLootMatrix4; - break; - case 5: - lootMatrix = constants.scoreLootMatrix5; - break; - default: - lootMatrix = 0; - } + auto* player = EntityManager::Instance()->GetEntity(self->GetVar(PlayerIDVariable)); + if (player != nullptr) { + for (auto* rewardModel : EntityManager::Instance()->GetEntitiesInGroup(constants.rewardModelGroup)) { + uint32_t lootMatrix; + switch (self->GetVar(MatrixVariable)) { + case 1: + lootMatrix = constants.scoreLootMatrix1; + break; + case 2: + lootMatrix = constants.scoreLootMatrix2; + break; + case 3: + lootMatrix = constants.scoreLootMatrix3; + break; + case 4: + lootMatrix = constants.scoreLootMatrix4; + break; + case 5: + lootMatrix = constants.scoreLootMatrix5; + break; + default: + lootMatrix = 0; + } - if (lootMatrix != 0) { - std::unordered_map toDrop = {}; - toDrop = LootGenerator::Instance().RollLootMatrix(player, lootMatrix); + if (lootMatrix != 0) { + std::unordered_map toDrop = {}; + toDrop = LootGenerator::Instance().RollLootMatrix(player, lootMatrix); - for (auto drop : toDrop) { - rewardModel->OnFireEventServerSide(self, ModelToBuildEvent, drop.first); - self->SetVar(CurrentRewardVariable, drop.first); - } - } - } - } + for (auto drop : toDrop) { + rewardModel->OnFireEventServerSide(self, ModelToBuildEvent, drop.first); + self->SetVar(CurrentRewardVariable, drop.first); + } + } + } + } } void SGCannon::RemovePlayer(LWOOBJID playerID) { - auto* player = EntityManager::Instance()->GetEntity(playerID); - if (player == nullptr) - return; + auto* player = EntityManager::Instance()->GetEntity(playerID); + if (player == nullptr) + return; - auto* playerObject = dynamic_cast(player); - if (playerObject == nullptr) - return; + auto* playerObject = dynamic_cast(player); + if (playerObject == nullptr) + return; - auto* character = playerObject->GetCharacter(); - if (character != nullptr) { - playerObject->SendToZone(character->GetLastNonInstanceZoneID()); - } + auto* character = playerObject->GetCharacter(); + if (character != nullptr) { + playerObject->SendToZone(character->GetLastNonInstanceZoneID()); + } } -void SGCannon::StartChargedCannon(Entity *self, uint32_t optionalTime) { - optionalTime = optionalTime == 0 ? constants.chargedTime : optionalTime; - self->SetVar(SuperChargePausedVariable, false); - ToggleSuperCharge(self, true); - ActivityTimerStart(self, SuperChargeTimer, 1, optionalTime); +void SGCannon::StartChargedCannon(Entity* self, uint32_t optionalTime) { + optionalTime = optionalTime == 0 ? constants.chargedTime : optionalTime; + self->SetVar(SuperChargePausedVariable, false); + ToggleSuperCharge(self, true); + ActivityTimerStart(self, SuperChargeTimer, 1, optionalTime); - if (!self->GetVar(WaveStatusVariable)) { - PauseChargeCannon(self); - } + if (!self->GetVar(WaveStatusVariable)) { + PauseChargeCannon(self); + } } -void SGCannon::TimerToggle(Entity *self, bool start) { - if (start) { - self->SetNetworkVar(CountVariable, self->GetVar(TimeLimitVariable)); - self->SetVar(GameStartedVariable, true); - } else { - self->SetNetworkVar(StopVariable, true); - } +void SGCannon::TimerToggle(Entity* self, bool start) { + if (start) { + self->SetNetworkVar(CountVariable, self->GetVar(TimeLimitVariable)); + self->SetVar(GameStartedVariable, true); + } else { + self->SetNetworkVar(StopVariable, true); + } } void SGCannon::SpawnObject(Entity* self, const SGEnemy& toSpawn, bool spawnNow) { - auto activeSpawns = self->GetVar>(ActiveSpawnsVariable); - activeSpawns.push_back(toSpawn); - self->SetVar>(ActiveSpawnsVariable, activeSpawns); + auto activeSpawns = self->GetVar>(ActiveSpawnsVariable); + activeSpawns.push_back(toSpawn); + self->SetVar>(ActiveSpawnsVariable, activeSpawns); - self->SetVar(SpawnNumberVariable, activeSpawns.size() - 1); - const auto timerName = DoSpawnTimer + std::to_string(activeSpawns.size() - 1); + self->SetVar(SpawnNumberVariable, activeSpawns.size() - 1); + const auto timerName = DoSpawnTimer + std::to_string(activeSpawns.size() - 1); - if (spawnNow) { - if (toSpawn.minSpawnTime > 0 && toSpawn.maxSpawnTime > 0) { - const auto spawnTime = GeneralUtils::GenerateRandomNumber(toSpawn.minSpawnTime, toSpawn.maxSpawnTime); + if (spawnNow) { + if (toSpawn.minSpawnTime > 0 && toSpawn.maxSpawnTime > 0) { + const auto spawnTime = GeneralUtils::GenerateRandomNumber(toSpawn.minSpawnTime, toSpawn.maxSpawnTime); - ActivityTimerStart(self, timerName, spawnTime, spawnTime); - } else { - ActivityTimerStart(self, timerName, 1, 1); - } - } else if (toSpawn.respawns) { - const auto spawnTime = GeneralUtils::GenerateRandomNumber(toSpawn.minRespawnTime, toSpawn.maxRespawnTime); + ActivityTimerStart(self, timerName, spawnTime, spawnTime); + } else { + ActivityTimerStart(self, timerName, 1, 1); + } + } else if (toSpawn.respawns) { + const auto spawnTime = GeneralUtils::GenerateRandomNumber(toSpawn.minRespawnTime, toSpawn.maxRespawnTime); - ActivityTimerStart(self, timerName, spawnTime, spawnTime); - } + ActivityTimerStart(self, timerName, spawnTime, spawnTime); + } } -void SGCannon::RecordPlayerScore(Entity *self) { - const auto totalScore = self->GetVar(TotalScoreVariable); - const auto currentWave = self->GetVar(ThisWaveVariable); +void SGCannon::RecordPlayerScore(Entity* self) { + const auto totalScore = self->GetVar(TotalScoreVariable); + const auto currentWave = self->GetVar(ThisWaveVariable); - if (currentWave > 0) { - auto totalWaveScore = 0; - auto playerScores = self->GetVar>(PlayerScoresVariable); + if (currentWave > 0) { + auto totalWaveScore = 0; + auto playerScores = self->GetVar>(PlayerScoresVariable); - for (const auto& waveScore : playerScores) { - totalWaveScore += waveScore; - } + for (const auto& waveScore : playerScores) { + totalWaveScore += waveScore; + } - if (currentWave >= playerScores.size()) { - playerScores.push_back(totalWaveScore); - } else { - playerScores[currentWave] = totalWaveScore; - } - } + if (currentWave >= playerScores.size()) { + playerScores.push_back(totalWaveScore); + } else { + playerScores[currentWave] = totalWaveScore; + } + } } void SGCannon::PlaySceneAnimation(Entity* self, const std::u16string& animationName, bool onCannon, bool onPlayer, float_t priority) { - for (auto* cannon : EntityManager::Instance()->GetEntitiesInGroup("cannongroup")) { - GameMessages::SendPlayAnimation(cannon, animationName, priority); - } + for (auto* cannon : EntityManager::Instance()->GetEntitiesInGroup("cannongroup")) { + GameMessages::SendPlayAnimation(cannon, animationName, priority); + } - if (onCannon) { - GameMessages::SendPlayAnimation(self, animationName, priority); - } + if (onCannon) { + GameMessages::SendPlayAnimation(self, animationName, priority); + } - if (onPlayer) { - auto* player = EntityManager::Instance()->GetEntity(self->GetVar(PlayerIDVariable)); - if (player != nullptr) { - GameMessages::SendPlayAnimation(player, animationName, priority); - } - } + if (onPlayer) { + auto* player = EntityManager::Instance()->GetEntity(self->GetVar(PlayerIDVariable)); + if (player != nullptr) { + GameMessages::SendPlayAnimation(player, animationName, priority); + } + } } -void SGCannon::PauseChargeCannon(Entity *self) { - const auto time = std::max((uint32_t) std::ceil(ActivityTimerGetCurrentTime(self, SuperChargeTimer)), (uint32_t) 1); +void SGCannon::PauseChargeCannon(Entity* self) { + const auto time = std::max((uint32_t)std::ceil(ActivityTimerGetCurrentTime(self, SuperChargeTimer)), (uint32_t)1); - self->SetVar(SuperChargePausedVariable, true); - self->SetVar(CurrentSuperChargedTimeVariable, time); - self->SetNetworkVar(ChargeCountingVariable, time); + self->SetVar(SuperChargePausedVariable, true); + self->SetVar(CurrentSuperChargedTimeVariable, time); + self->SetNetworkVar(ChargeCountingVariable, time); - ActivityTimerStop(self, SuperChargeTimer); + ActivityTimerStop(self, SuperChargeTimer); } -void SGCannon::StopGame(Entity *self, bool cancel) { - self->SetNetworkVar(ReSetSuperChargeVariable, true); - self->SetNetworkVar(HideSuperChargeVariable, true); +void SGCannon::StopGame(Entity* self, bool cancel) { + self->SetNetworkVar(ReSetSuperChargeVariable, true); + self->SetNetworkVar(HideSuperChargeVariable, true); - auto* player = EntityManager::Instance()->GetEntity(self->GetVar(PlayerIDVariable)); - if (player == nullptr) - return; + auto* player = EntityManager::Instance()->GetEntity(self->GetVar(PlayerIDVariable)); + if (player == nullptr) + return; - ToggleSuperCharge(self, false); + ToggleSuperCharge(self, false); - // The player won, store all the score and send rewards - if (!cancel) { - auto percentage = 0; - auto misses = self->GetVar(MissesVariable); - auto fired = self->GetVar(ShotsFiredVariable); + // The player won, store all the score and send rewards + if (!cancel) { + auto percentage = 0; + auto misses = self->GetVar(MissesVariable); + auto fired = self->GetVar(ShotsFiredVariable); - if (fired > 0) { - percentage = misses / fired; - } + if (fired > 0) { + percentage = misses / fired; + } - auto* missionComponent = player->GetComponent(); + auto* missionComponent = player->GetComponent(); - if (missionComponent != nullptr) { - missionComponent->Progress(MissionTaskType::MISSION_TASK_TYPE_MINIGAME, self->GetVar(TotalScoreVariable), self->GetObjectID(), "performact_score"); - missionComponent->Progress(MissionTaskType::MISSION_TASK_TYPE_MINIGAME, self->GetVar(MaxStreakVariable), self->GetObjectID(), "performact_streak"); - missionComponent->Progress(MissionTaskType::MISSION_TASK_TYPE_ACTIVITY, m_CannonLot, 0, "", self->GetVar(TotalScoreVariable)); - } + if (missionComponent != nullptr) { + missionComponent->Progress(MissionTaskType::MISSION_TASK_TYPE_MINIGAME, self->GetVar(TotalScoreVariable), self->GetObjectID(), "performact_score"); + missionComponent->Progress(MissionTaskType::MISSION_TASK_TYPE_MINIGAME, self->GetVar(MaxStreakVariable), self->GetObjectID(), "performact_streak"); + missionComponent->Progress(MissionTaskType::MISSION_TASK_TYPE_ACTIVITY, m_CannonLot, 0, "", self->GetVar(TotalScoreVariable)); + } - LootGenerator::Instance().GiveActivityLoot(player, self, GetGameID(self), self->GetVar(TotalScoreVariable)); + LootGenerator::Instance().GiveActivityLoot(player, self, GetGameID(self), self->GetVar(TotalScoreVariable)); - StopActivity(self, player->GetObjectID(), self->GetVar(TotalScoreVariable), self->GetVar(MaxStreakVariable), percentage); - self->SetNetworkVar(AudioFinalWaveDoneVariable, true); + StopActivity(self, player->GetObjectID(), self->GetVar(TotalScoreVariable), self->GetVar(MaxStreakVariable), percentage); + self->SetNetworkVar(AudioFinalWaveDoneVariable, true); - // Give the player the model rewards they earned - auto* inventory = player->GetComponent(); - if (inventory != nullptr) { - for (const auto rewardLot : self->GetVar>(RewardsVariable)) { - inventory->AddItem(rewardLot, 1, eLootSourceType::LOOT_SOURCE_ACTIVITY, eInventoryType::MODELS); - } - } + // Give the player the model rewards they earned + auto* inventory = player->GetComponent(); + if (inventory != nullptr) { + for (const auto rewardLot : self->GetVar>(RewardsVariable)) { + inventory->AddItem(rewardLot, 1, eLootSourceType::LOOT_SOURCE_ACTIVITY, eInventoryType::MODELS); + } + } - self->SetNetworkVar(u"UI_Rewards", - GeneralUtils::to_u16string(self->GetVar(TotalScoreVariable)) + u"_0_0_0_0_0_0" - ); + self->SetNetworkVar(u"UI_Rewards", + GeneralUtils::to_u16string(self->GetVar(TotalScoreVariable)) + u"_0_0_0_0_0_0" + ); - GameMessages::SendRequestActivitySummaryLeaderboardData( - player->GetObjectID(), - self->GetObjectID(), - player->GetSystemAddress(), - GetGameID(self), - 1, - 10, - 0, - false - ); - } + GameMessages::SendRequestActivitySummaryLeaderboardData( + player->GetObjectID(), + self->GetObjectID(), + player->GetSystemAddress(), + GetGameID(self), + 1, + 10, + 0, + false + ); + } - GameMessages::SendActivityStop(self->GetObjectID(), false, cancel, player->GetSystemAddress()); - self->SetVar(GameStartedVariable, false); - ActivityTimerStopAllTimers(self); + GameMessages::SendActivityStop(self->GetObjectID(), false, cancel, player->GetSystemAddress()); + self->SetVar(GameStartedVariable, false); + ActivityTimerStopAllTimers(self); - // Destroy all spawners - for (auto* entity : EntityManager::Instance()->GetEntitiesInGroup("SGEnemy")) { - entity->Kill(); - } + // Destroy all spawners + for (auto* entity : EntityManager::Instance()->GetEntitiesInGroup("SGEnemy")) { + entity->Kill(); + } - ResetVars(self); + ResetVars(self); } -void SGCannon::RegisterHit(Entity* self, Entity* target, const std::string& timerName) -{ - const auto& spawnInfo = target->GetVar(u"SpawnData"); +void SGCannon::RegisterHit(Entity* self, Entity* target, const std::string& timerName) { + const auto& spawnInfo = target->GetVar(u"SpawnData"); - if (spawnInfo.respawns) - { - const auto respawnTime = GeneralUtils::GenerateRandomNumber(spawnInfo.minRespawnTime, spawnInfo.maxRespawnTime); + if (spawnInfo.respawns) { + const auto respawnTime = GeneralUtils::GenerateRandomNumber(spawnInfo.minRespawnTime, spawnInfo.maxRespawnTime); - ActivityTimerStart(self, timerName, respawnTime, respawnTime); - } + ActivityTimerStart(self, timerName, respawnTime, respawnTime); + } - int score = spawnInfo.score; + int score = spawnInfo.score; - if (score > 0) { - score += score * GetCurrentBonus(self); + if (score > 0) { + score += score * GetCurrentBonus(self); - if (!self->GetVar(SuperChargeActiveVariable)) { - self->SetVar(u"m_curStreak", self->GetVar(u"m_curStreak") + 1); - } - } - else { - if (!self->GetVar(SuperChargeActiveVariable)) { - self->SetVar(u"m_curStreak", 0); - } + if (!self->GetVar(SuperChargeActiveVariable)) { + self->SetVar(u"m_curStreak", self->GetVar(u"m_curStreak") + 1); + } + } else { + if (!self->GetVar(SuperChargeActiveVariable)) { + self->SetVar(u"m_curStreak", 0); + } - self->SetNetworkVar(u"hitFriend", true); - } + self->SetNetworkVar(u"hitFriend", true); + } - auto lastSuperTotal = self->GetVar(u"LastSuperTotal"); + auto lastSuperTotal = self->GetVar(u"LastSuperTotal"); - auto scScore = self->GetVar(TotalScoreVariable) - lastSuperTotal; + auto scScore = self->GetVar(TotalScoreVariable) - lastSuperTotal; - Game::logger->Log("SGCannon", "LastSuperTotal: %i, scScore: %i, constants.chargedPoints: %i", - lastSuperTotal, scScore, constants.chargedPoints - ); + Game::logger->Log("SGCannon", "LastSuperTotal: %i, scScore: %i, constants.chargedPoints: %i", + lastSuperTotal, scScore, constants.chargedPoints + ); - if (!self->GetVar(SuperChargeActiveVariable) && scScore >= constants.chargedPoints && score >= 0) { - StartChargedCannon(self); - self->SetNetworkVar(u"SuperChargeBar", 100.0f); - self->SetVar(u"LastSuperTotal", self->GetVar(TotalScoreVariable)); - } + if (!self->GetVar(SuperChargeActiveVariable) && scScore >= constants.chargedPoints && score >= 0) { + StartChargedCannon(self); + self->SetNetworkVar(u"SuperChargeBar", 100.0f); + self->SetVar(u"LastSuperTotal", self->GetVar(TotalScoreVariable)); + } - UpdateStreak(self); + UpdateStreak(self); - GameMessages::SendNotifyClientShootingGalleryScore(self->GetObjectID(), UNASSIGNED_SYSTEM_ADDRESS, - 0.0f, - score, - target->GetObjectID(), - target->GetPosition() - ); + GameMessages::SendNotifyClientShootingGalleryScore(self->GetObjectID(), UNASSIGNED_SYSTEM_ADDRESS, + 0.0f, + score, + target->GetObjectID(), + target->GetPosition() + ); - auto newScore = (int) self->GetVar(TotalScoreVariable) + score; + auto newScore = (int)self->GetVar(TotalScoreVariable) + score; - if (newScore < 0) { - newScore = 0; - } + if (newScore < 0) { + newScore = 0; + } - self->SetVar(TotalScoreVariable, newScore); + self->SetVar(TotalScoreVariable, newScore); - self->SetNetworkVar(u"updateScore", newScore); + self->SetNetworkVar(u"updateScore", newScore); - self->SetNetworkVar(u"beatHighScore", GeneralUtils::to_u16string(newScore)); + self->SetNetworkVar(u"beatHighScore", GeneralUtils::to_u16string(newScore)); - auto* player = EntityManager::Instance()->GetEntity(self->GetVar(PlayerIDVariable)); - if (player == nullptr) return; + auto* player = EntityManager::Instance()->GetEntity(self->GetVar(PlayerIDVariable)); + if (player == nullptr) return; - auto missionComponent = player->GetComponent(); - if (missionComponent == nullptr) return; + auto missionComponent = player->GetComponent(); + if (missionComponent == nullptr) return; - missionComponent->Progress(MissionTaskType::MISSION_TASK_TYPE_SMASH, spawnInfo.lot, self->GetObjectID()); + missionComponent->Progress(MissionTaskType::MISSION_TASK_TYPE_SMASH, spawnInfo.lot, self->GetObjectID()); } -void SGCannon::UpdateStreak(Entity* self) -{ - const auto streakBonus = GetCurrentBonus(self); +void SGCannon::UpdateStreak(Entity* self) { + const auto streakBonus = GetCurrentBonus(self); - const auto curStreak = self->GetVar(u"m_curStreak"); + const auto curStreak = self->GetVar(u"m_curStreak"); - const auto marks = curStreak % 3; + const auto marks = curStreak % 3; - self->SetNetworkVar(u"cStreak", curStreak); + self->SetNetworkVar(u"cStreak", curStreak); - if (curStreak >= 0 && curStreak < 13) { - if (marks == 1) { - self->SetNetworkVar(u"Mark1", true); - } - else if (marks == 2) { - self->SetNetworkVar(u"Mark2", true); - } - else if (marks == 0 && curStreak > 0) { - self->SetVar(u"StreakBonus", streakBonus); - self->SetNetworkVar(u"ShowStreak", streakBonus + 1); - self->SetNetworkVar(u"Mark3", true); - } - else { - self->SetVar(u"StreakBonus", streakBonus); - self->SetNetworkVar(u"UnMarkAll", true); - } - } - auto maxStreak = self->GetVar(MaxStreakVariable); - if (maxStreak < curStreak) self->SetVar(MaxStreakVariable, curStreak); + if (curStreak >= 0 && curStreak < 13) { + if (marks == 1) { + self->SetNetworkVar(u"Mark1", true); + } else if (marks == 2) { + self->SetNetworkVar(u"Mark2", true); + } else if (marks == 0 && curStreak > 0) { + self->SetVar(u"StreakBonus", streakBonus); + self->SetNetworkVar(u"ShowStreak", streakBonus + 1); + self->SetNetworkVar(u"Mark3", true); + } else { + self->SetVar(u"StreakBonus", streakBonus); + self->SetNetworkVar(u"UnMarkAll", true); + } + } + auto maxStreak = self->GetVar(MaxStreakVariable); + if (maxStreak < curStreak) self->SetVar(MaxStreakVariable, curStreak); } -float_t SGCannon::GetCurrentBonus(Entity* self) -{ - auto streak = self->GetVar(u"m_curStreak"); +float_t SGCannon::GetCurrentBonus(Entity* self) { + auto streak = self->GetVar(u"m_curStreak"); - if (streak > 12) { - streak = 12; - } + if (streak > 12) { + streak = 12; + } - return streak / 3; + return streak / 3; } -void SGCannon::ToggleSuperCharge(Entity *self, bool enable) { - if (enable && self->GetVar(SuperChargeActiveVariable)) - return; +void SGCannon::ToggleSuperCharge(Entity* self, bool enable) { + if (enable && self->GetVar(SuperChargeActiveVariable)) + return; - auto* player = EntityManager::Instance()->GetEntity(self->GetVar(PlayerIDVariable)); + auto* player = EntityManager::Instance()->GetEntity(self->GetVar(PlayerIDVariable)); - if (player == nullptr) { - Game::logger->Log("SGCannon", "Player not found in toggle super charge"); - return; - } + if (player == nullptr) { + Game::logger->Log("SGCannon", "Player not found in toggle super charge"); + return; + } - auto* inventoryComponent = player->GetComponent(); + auto* inventoryComponent = player->GetComponent(); - auto equippedItems = inventoryComponent->GetEquippedItems(); + auto equippedItems = inventoryComponent->GetEquippedItems(); - Game::logger->Log("SGCannon", "Player has %d equipped items", equippedItems.size()); + Game::logger->Log("SGCannon", "Player has %d equipped items", equippedItems.size()); - auto skillID = constants.cannonSkill; - auto coolDown = constants.cannonRefireRate; + auto skillID = constants.cannonSkill; + auto coolDown = constants.cannonRefireRate; - auto* selfInventoryComponent = self->GetComponent(); + auto* selfInventoryComponent = self->GetComponent(); - if (inventoryComponent == nullptr) { - Game::logger->Log("SGCannon", "Inventory component not found"); - return; - } + if (inventoryComponent == nullptr) { + Game::logger->Log("SGCannon", "Inventory component not found"); + return; + } - if (enable) { - Game::logger->Log("SGCannon", "Player is activating super charge"); - selfInventoryComponent->UpdateSlot("greeble_r", { ObjectIDManager::GenerateRandomObjectID(), 6505, 1, 0 }); - selfInventoryComponent->UpdateSlot("greeble_l", { ObjectIDManager::GenerateRandomObjectID(), 6506, 1, 0 }); + if (enable) { + Game::logger->Log("SGCannon", "Player is activating super charge"); + selfInventoryComponent->UpdateSlot("greeble_r", { ObjectIDManager::GenerateRandomObjectID(), 6505, 1, 0 }); + selfInventoryComponent->UpdateSlot("greeble_l", { ObjectIDManager::GenerateRandomObjectID(), 6506, 1, 0 }); - // TODO: Equip items - skillID = constants.cannonSuperChargeSkill; - coolDown = 400; - } else { - selfInventoryComponent->UpdateSlot("greeble_r", { ObjectIDManager::GenerateRandomObjectID(), 0, 0, 0 }); - selfInventoryComponent->UpdateSlot("greeble_l", { ObjectIDManager::GenerateRandomObjectID(), 0, 0, 0 }); + // TODO: Equip items + skillID = constants.cannonSuperChargeSkill; + coolDown = 400; + } else { + selfInventoryComponent->UpdateSlot("greeble_r", { ObjectIDManager::GenerateRandomObjectID(), 0, 0, 0 }); + selfInventoryComponent->UpdateSlot("greeble_l", { ObjectIDManager::GenerateRandomObjectID(), 0, 0, 0 }); - self->SetNetworkVar(u"SuperChargeBar", 0); + self->SetNetworkVar(u"SuperChargeBar", 0); - Game::logger->Log("SGCannon", "Player disables super charge"); + Game::logger->Log("SGCannon", "Player disables super charge"); - // TODO: Unequip items - for (const auto& equipped : equippedItems) { - if (equipped.first == "special_r" || equipped.first == "special_l") { - Game::logger->Log("SGCannon", "Trying to unequip a weapon, %i", equipped.second.lot); + // TODO: Unequip items + for (const auto& equipped : equippedItems) { + if (equipped.first == "special_r" || equipped.first == "special_l") { + Game::logger->Log("SGCannon", "Trying to unequip a weapon, %i", equipped.second.lot); - auto* item = inventoryComponent->FindItemById(equipped.second.id); + auto* item = inventoryComponent->FindItemById(equipped.second.id); - if (item != nullptr) { - inventoryComponent->UnEquipItem(item); - } - else { - Game::logger->Log("SGCannon", "Item not found, %i", equipped.second.lot); - } - } - } + if (item != nullptr) { + inventoryComponent->UnEquipItem(item); + } else { + Game::logger->Log("SGCannon", "Item not found, %i", equipped.second.lot); + } + } + } - self->SetVar(NumberOfChargesVariable, 0); - } + self->SetVar(NumberOfChargesVariable, 0); + } - const auto& constants = GetConstants(); + const auto& constants = GetConstants(); - auto* shootingGalleryComponent = self->GetComponent(); + auto* shootingGalleryComponent = self->GetComponent(); - if (shootingGalleryComponent == nullptr) { - return; - } + if (shootingGalleryComponent == nullptr) { + return; + } - DynamicShootingGalleryParams properties = shootingGalleryComponent->GetDynamicParams(); + DynamicShootingGalleryParams properties = shootingGalleryComponent->GetDynamicParams(); - properties.cannonFOV = 58.6f; - properties.cannonVelocity = 129.0; - properties.cannonRefireRate = 800; - properties.cannonMinDistance = 30; - properties.cannonTimeout = -1; + properties.cannonFOV = 58.6f; + properties.cannonVelocity = 129.0; + properties.cannonRefireRate = 800; + properties.cannonMinDistance = 30; + properties.cannonTimeout = -1; - shootingGalleryComponent->SetDynamicParams(properties); + shootingGalleryComponent->SetDynamicParams(properties); - EntityManager::Instance()->SerializeEntity(self); - EntityManager::Instance()->SerializeEntity(player); + EntityManager::Instance()->SerializeEntity(self); + EntityManager::Instance()->SerializeEntity(player); - self->SetNetworkVar(CannonBallSkillIDVariable, skillID); - self->SetVar(SuperChargeActiveVariable, enable); + self->SetNetworkVar(CannonBallSkillIDVariable, skillID); + self->SetVar(SuperChargeActiveVariable, enable); } std::vector> SGCannon::GetWaves() { - return { - // Wave 1 - { - // Ship 1 - { - std::vector { "Wave_1_Ship_1", "Wave_1_Ship_3" }, - 6015, 0.0, 2.0, true, 0.0, 2.0, - 2.0, 1500, false, 0.0, 1.0, - 1.0, false, true - }, + return { + // Wave 1 + { + // Ship 1 + { + std::vector { "Wave_1_Ship_1", "Wave_1_Ship_3" }, + 6015, 0.0, 2.0, true, 0.0, 2.0, + 2.0, 1500, false, 0.0, 1.0, + 1.0, false, true + }, - // Ship 2 - { - std::vector { "Wave_1_Ship_2", "Wave_1_Ship_4" }, - 6300, 0.0, 2.0, true, 0.0, 2.0, - 2.0, 500, false, 0.0, 1.0, - 1.0, false, true - }, + // Ship 2 + { + std::vector { "Wave_1_Ship_2", "Wave_1_Ship_4" }, + 6300, 0.0, 2.0, true, 0.0, 2.0, + 2.0, 500, false, 0.0, 1.0, + 1.0, false, true + }, - // Sub 1 - { - std::vector { "Wave_1_Sub_1", "Wave_1_Sub_2" }, - 6016, 0.0, 2.0, true, 0.0, 2.0, - 10.0, 1000, false, 0.0, 1.0, - 1.0, true, true - }, + // Sub 1 + { + std::vector { "Wave_1_Sub_1", "Wave_1_Sub_2" }, + 6016, 0.0, 2.0, true, 0.0, 2.0, + 10.0, 1000, false, 0.0, 1.0, + 1.0, true, true + }, - // Sub 2 - { - std::vector { "Wave_2_Sub_1", "Wave_2_Sub_2" }, - 6016, 0.0, 2.0, true, 0.0, 2.0, - 2.0, 1000, false, 0.0, 1.0, - 1.0, true, true - }, + // Sub 2 + { + std::vector { "Wave_2_Sub_1", "Wave_2_Sub_2" }, + 6016, 0.0, 2.0, true, 0.0, 2.0, + 2.0, 1000, false, 0.0, 1.0, + 1.0, true, true + }, - // Friendly - { - std::vector { "Wave_3_FShip_1", "Wave_3_FShip_2" }, - 2168,0.0,5.0,true, 2.0, 5.0, - 1.0, -1000, false, 0.0, 1.0, - 1.0, false,true - } - }, + // Friendly + { + std::vector { "Wave_3_FShip_1", "Wave_3_FShip_2" }, + 2168,0.0,5.0,true, 2.0, 5.0, + 1.0, -1000, false, 0.0, 1.0, + 1.0, false,true + } + }, - // Wave 2 - { - // Ship 1 - { - std::vector { "Wave_1_Ship_1", "Wave_1_Ship_3" }, - 6015, 0.0, 2.0, true, 0.0, 2.0, - 2.0, 1500, false, 0.0, 1.0, - 1.0, false, true - }, + // Wave 2 + { + // Ship 1 + { + std::vector { "Wave_1_Ship_1", "Wave_1_Ship_3" }, + 6015, 0.0, 2.0, true, 0.0, 2.0, + 2.0, 1500, false, 0.0, 1.0, + 1.0, false, true + }, - // Ship 2 - { - std::vector { "Wave_1_Ship_2", "Wave_1_Ship_4" }, - 6300, 0.0, 2.0, true, 0.0, 2.0, - 2.0, 500, false, 0.0, 1.0, - 1.0, false, true - }, + // Ship 2 + { + std::vector { "Wave_1_Ship_2", "Wave_1_Ship_4" }, + 6300, 0.0, 2.0, true, 0.0, 2.0, + 2.0, 500, false, 0.0, 1.0, + 1.0, false, true + }, - // Ship 3 - { - std::vector { "Wave_2_Ship_1" }, - 6300, 0.0, 2.0, true, 0.0, 2.0, - 2.0, 500, false, 0.0, 1.0, - 1.0, false, true - }, + // Ship 3 + { + std::vector { "Wave_2_Ship_1" }, + 6300, 0.0, 2.0, true, 0.0, 2.0, + 2.0, 500, false, 0.0, 1.0, + 1.0, false, true + }, - // Ship 4 - { - std::vector { "Wave_2_Ship_2" }, - 6015, 0.0, 2.0, true, 0.0, 2.0, - 2.0, 500, false, 0.0, 1.0, - 1.0, false, true - }, + // Ship 4 + { + std::vector { "Wave_2_Ship_2" }, + 6015, 0.0, 2.0, true, 0.0, 2.0, + 2.0, 500, false, 0.0, 1.0, + 1.0, false, true + }, - // Sub 1 - { - std::vector { "Wave_1_Sub_1", "Wave_1_Sub_2" }, - 6016, 0.0, 2.0, true, 0.0, 2.0, - 2.0, 1000, false, 0.0, 1.0, - 1.0, true, true - }, + // Sub 1 + { + std::vector { "Wave_1_Sub_1", "Wave_1_Sub_2" }, + 6016, 0.0, 2.0, true, 0.0, 2.0, + 2.0, 1000, false, 0.0, 1.0, + 1.0, true, true + }, - // Sub 2 - { - std::vector { "Wave_2_Sub_1", "Wave_2_Sub_2" }, - 6016, 0.0, 2.0, true, 0.0, 2.0, - 2.0, 1000, false, 0.0, 1.0, - 1.0, true, true - }, + // Sub 2 + { + std::vector { "Wave_2_Sub_1", "Wave_2_Sub_2" }, + 6016, 0.0, 2.0, true, 0.0, 2.0, + 2.0, 1000, false, 0.0, 1.0, + 1.0, true, true + }, - // Duck - { - std::vector { "Wave_1_Duck_1", "Wave_1_Duck_2" }, - 5946, 5.0, 10.0, true, 5.0, 10.0, - 4.0, 5000, false, 0.0, 1.0, - 1.0, false, true - }, + // Duck + { + std::vector { "Wave_1_Duck_1", "Wave_1_Duck_2" }, + 5946, 5.0, 10.0, true, 5.0, 10.0, + 4.0, 5000, false, 0.0, 1.0, + 1.0, false, true + }, - // Friendly - { - std::vector { "Wave_3_FShip_1", "Wave_3_FShip_2" }, - 2168,0.0,5.0,true, 2.0, 5.0, - 1.0, -1000, false, 0.0, 1.0, - 1.0, false,true - } - }, + // Friendly + { + std::vector { "Wave_3_FShip_1", "Wave_3_FShip_2" }, + 2168,0.0,5.0,true, 2.0, 5.0, + 1.0, -1000, false, 0.0, 1.0, + 1.0, false,true + } + }, - // Wave 3 - { - // Ship 1 - { - std::vector { "Wave_1_Ship_1", "Wave_1_Ship_3" }, - 6015, 0.0, 2.0, true, 0.0, 2.0, - 2.0, 1500, false, 0.0, 1.0, - 1.0, false, true - }, + // Wave 3 + { + // Ship 1 + { + std::vector { "Wave_1_Ship_1", "Wave_1_Ship_3" }, + 6015, 0.0, 2.0, true, 0.0, 2.0, + 2.0, 1500, false, 0.0, 1.0, + 1.0, false, true + }, - // Ship 2 - { - std::vector { "Wave_1_Ship_2", "Wave_1_Ship_4" }, - 6300, 0.0, 2.0, true, 0.0, 2.0, - 2.0, 500, false, 0.0, 1.0, - 1.0, false, true - }, + // Ship 2 + { + std::vector { "Wave_1_Ship_2", "Wave_1_Ship_4" }, + 6300, 0.0, 2.0, true, 0.0, 2.0, + 2.0, 500, false, 0.0, 1.0, + 1.0, false, true + }, - // Ship 3 - { - std::vector { "Wave_2_Ship_1", "Wave_2_Ship_2" }, - 6015, 0.0, 2.0, true, 0.0, 2.0, - 2.0, 500, false, 0.0, 1.0, - 1.0, false, true - }, + // Ship 3 + { + std::vector { "Wave_2_Ship_1", "Wave_2_Ship_2" }, + 6015, 0.0, 2.0, true, 0.0, 2.0, + 2.0, 500, false, 0.0, 1.0, + 1.0, false, true + }, - // Ship 4 - { - std::vector { "Wave_3_Ship_1", "Wave_3_Ship_2" }, - 6300, 0.0, 2.0, true, 0.0, 2.0, - 2.0, 1500, false, 0.0, 1.0, - 1.0, false, true - }, + // Ship 4 + { + std::vector { "Wave_3_Ship_1", "Wave_3_Ship_2" }, + 6300, 0.0, 2.0, true, 0.0, 2.0, + 2.0, 1500, false, 0.0, 1.0, + 1.0, false, true + }, - // Sub 1 - { - std::vector { "Wave_1_Sub_1", "Wave_1_Sub_2" }, - 6016, 0.0, 2.0, true, 0.0, 2.0, - 2.0, 1000, false, 0.0, 1.0, - 1.0, true, true - }, + // Sub 1 + { + std::vector { "Wave_1_Sub_1", "Wave_1_Sub_2" }, + 6016, 0.0, 2.0, true, 0.0, 2.0, + 2.0, 1000, false, 0.0, 1.0, + 1.0, true, true + }, - // Sub 2 - { - std::vector { "Wave_2_Sub_1", "Wave_2_Sub_2" }, - 6016, 0.0, 2.0, true, 0.0, 2.0, - 2.0, 1000, false, 0.0, 1.0, - 1.0, true, true - }, + // Sub 2 + { + std::vector { "Wave_2_Sub_1", "Wave_2_Sub_2" }, + 6016, 0.0, 2.0, true, 0.0, 2.0, + 2.0, 1000, false, 0.0, 1.0, + 1.0, true, true + }, - // Sub 3 - { - std::vector { "Wave_3_Sub_1", "Wave_3_Sub_2" }, - 6016, 0.0, 2.0, true, 0.0, 2.0, - 2.0, 1000, false, 0.0, 1.0, - 1.0, true, true - }, + // Sub 3 + { + std::vector { "Wave_3_Sub_1", "Wave_3_Sub_2" }, + 6016, 0.0, 2.0, true, 0.0, 2.0, + 2.0, 1000, false, 0.0, 1.0, + 1.0, true, true + }, - // Duck - { - std::vector { "Wave_1_Duck_1", "Wave_1_Duck_2" }, - 5946, 5.0, 10.0, true, 5.0, 10.0, - 4.0, 5000, false, 0.0, 1.0, - 1.0, false, true - }, + // Duck + { + std::vector { "Wave_1_Duck_1", "Wave_1_Duck_2" }, + 5946, 5.0, 10.0, true, 5.0, 10.0, + 4.0, 5000, false, 0.0, 1.0, + 1.0, false, true + }, - // Ness - { - std::vector { "Wave_1_Ness_1", "Wave_1_Ness_2", "Wave_2_Ness_1" }, - 2565, 10.0, 15.0, true, 10.0, 15.0, - 2.0, 10000, false, 0.0, 1.0, - 1.0, true, true - }, + // Ness + { + std::vector { "Wave_1_Ness_1", "Wave_1_Ness_2", "Wave_2_Ness_1" }, + 2565, 10.0, 15.0, true, 10.0, 15.0, + 2.0, 10000, false, 0.0, 1.0, + 1.0, true, true + }, - // Friendly 1 - { - std::vector { "Wave_3_FShip_1", "Wave_3_FShip_2" }, - 2168,0.0,5.0,true, 2.0, 5.0, - 1.0, -1000, false, 0.0, 1.0, - 1.0, false,true - }, + // Friendly 1 + { + std::vector { "Wave_3_FShip_1", "Wave_3_FShip_2" }, + 2168,0.0,5.0,true, 2.0, 5.0, + 1.0, -1000, false, 0.0, 1.0, + 1.0, false,true + }, - // Friendly 2 - { - std::vector { "Wave_3_FShip_1", "Wave_3_FShip_2" }, - 2168,0.0,5.0,true, 2.0, 5.0, - 1.0, -1000, false, 0.0, 1.0, - 1.0, false,true - } - } - }; + // Friendly 2 + { + std::vector { "Wave_3_FShip_1", "Wave_3_FShip_2" }, + 2168,0.0,5.0,true, 2.0, 5.0, + 1.0, -1000, false, 0.0, 1.0, + 1.0, false,true + } + } + }; } -void SGCannon::ResetVars(Entity *self) { - self->SetVar(SpawnNumberVariable, 0); - self->SetVar(CurrentSpawnNumberVariable, 0); - self->SetVar(ThisWaveVariable, 0); - self->SetVar(GameScoreVariable, 0); - self->SetVar(GameTimeVariable, 0); - self->SetVar(GameStartedVariable, false); - self->SetVar(ShotsFiredVariable, 0); - self->SetVar(MaxStreakVariable, 0); - self->SetVar(MissesVariable, 0); - self->SetVar(CurrentStreakVariable, 0); - self->SetVar(CurrentSuperChargedTimeVariable, 0); - self->SetVar>(StreakBonusVariable, {}); - self->SetVar(LastSuperTotalVariable, 0); - self->SetVar(CurrentRewardVariable, LOT_NULL); - self->SetVar>(RewardsVariable, {}); - self->SetVar(TotalScoreVariable, 0); +void SGCannon::ResetVars(Entity* self) { + self->SetVar(SpawnNumberVariable, 0); + self->SetVar(CurrentSpawnNumberVariable, 0); + self->SetVar(ThisWaveVariable, 0); + self->SetVar(GameScoreVariable, 0); + self->SetVar(GameTimeVariable, 0); + self->SetVar(GameStartedVariable, false); + self->SetVar(ShotsFiredVariable, 0); + self->SetVar(MaxStreakVariable, 0); + self->SetVar(MissesVariable, 0); + self->SetVar(CurrentStreakVariable, 0); + self->SetVar(CurrentSuperChargedTimeVariable, 0); + self->SetVar>(StreakBonusVariable, {}); + self->SetVar(LastSuperTotalVariable, 0); + self->SetVar(CurrentRewardVariable, LOT_NULL); + self->SetVar>(RewardsVariable, {}); + self->SetVar(TotalScoreVariable, 0); - const_cast&>(self->GetVar>(ActiveSpawnsVariable)).clear(); - self->SetVar>(ActiveSpawnsVariable, {}); + const_cast&>(self->GetVar>(ActiveSpawnsVariable)).clear(); + self->SetVar>(ActiveSpawnsVariable, {}); - const_cast&>(self->GetVar>(SpawnedObjects)).clear(); - self->SetVar>(SpawnedObjects, {}); + const_cast&>(self->GetVar>(SpawnedObjects)).clear(); + self->SetVar>(SpawnedObjects, {}); - if (self->GetVar(InitVariable)) { - ToggleSuperCharge(self, false); - } + if (self->GetVar(InitVariable)) { + ToggleSuperCharge(self, false); + } - self->SetVar(ImpactSkillVariale, constants.impactSkillID); - self->SetVar>(PlayerScoresVariable, {}); - ActivityTimerStopAllTimers(self); + self->SetVar(ImpactSkillVariale, constants.impactSkillID); + self->SetVar>(PlayerScoresVariable, {}); + ActivityTimerStopAllTimers(self); } SGConstants SGCannon::GetConstants() { - return { - Vector3 { -908.542480, 229.773178, -908.542480 }, - Quaternion { 0.91913521289825, 0, 0.39394217729568, 0 }, - 1864, - 34, - 1822, - Vector3 { 6.652, -2, 1.5 }, - 157, - 129.0, - 30.0, - 800.0, - Vector3 { 0, 4.3, 9 }, - 6297, - 1822, - 249, - 228, - -1, - 58.6, - true, - 2, - 10, - 25000, - "QBRewardGroup", - 1864, - 50000, - 157, - 100000, - 187, - 200000, - 188, - 400000, - 189, - 800000, - 190, - 4.0, - 7.0 - }; + return { + Vector3 { -908.542480, 229.773178, -908.542480 }, + Quaternion { 0.91913521289825, 0, 0.39394217729568, 0 }, + 1864, + 34, + 1822, + Vector3 { 6.652, -2, 1.5 }, + 157, + 129.0, + 30.0, + 800.0, + Vector3 { 0, 4.3, 9 }, + 6297, + 1822, + 249, + 228, + -1, + 58.6, + true, + 2, + 10, + 25000, + "QBRewardGroup", + 1864, + 50000, + 157, + 100000, + 187, + 200000, + 188, + 400000, + 189, + 800000, + 190, + 4.0, + 7.0 + }; } diff --git a/dScripts/SGCannon.h b/dScripts/SGCannon.h index 56db4c81..df9831ad 100644 --- a/dScripts/SGCannon.h +++ b/dScripts/SGCannon.h @@ -3,151 +3,151 @@ #include "ActivityManager.h" struct SGEnemy { - std::vector spawnPaths {}; - LOT lot; - float_t minSpawnTime; - float_t maxSpawnTime; - bool respawns; - float_t minRespawnTime; - float_t maxRespawnTime; - float_t initialSpeed; - int32_t score; - bool changeSpeedAtWaypoint; - float_t speedChangeChance; - float_t minSpeed; - float_t maxSpeed; - bool isMovingPlatform; - bool despawnOnLastWaypoint; + std::vector spawnPaths{}; + LOT lot; + float_t minSpawnTime; + float_t maxSpawnTime; + bool respawns; + float_t minRespawnTime; + float_t maxRespawnTime; + float_t initialSpeed; + int32_t score; + bool changeSpeedAtWaypoint; + float_t speedChangeChance; + float_t minSpeed; + float_t maxSpeed; + bool isMovingPlatform; + bool despawnOnLastWaypoint; }; struct SGConstants { - Vector3 playerStartPosition; - Quaternion playerStartRotation; - LOT cannonLot; - uint32_t impactSkillID; - LOT projectileLot; - Vector3 playerOffset; - uint32_t rewardModelMatrix; - float_t cannonVelocity; - float_t cannonMinDistance; - float_t cannonRefireRate; - Vector3 cannonBarrelOffset; - LOT cannonSuperchargedProjectileLot; - LOT cannonProjectileLot; - uint32_t cannonSuperChargeSkill; - uint32_t cannonSkill; - int32_t cannonTimeout; - float_t cannonFOV; - bool useLeaderboards; - uint32_t streakModifier; - uint32_t chargedTime; - uint32_t chargedPoints; - std::string rewardModelGroup; - uint32_t activityID; - uint32_t scoreReward1; - uint32_t scoreLootMatrix1; - uint32_t scoreReward2; - uint32_t scoreLootMatrix2; - uint32_t scoreReward3; - uint32_t scoreLootMatrix3; - uint32_t scoreReward4; - uint32_t scoreLootMatrix4; - uint32_t scoreReward5; - uint32_t scoreLootMatrix5; - float_t firstWaveStartTime; - float_t inBetweenWavePause; + Vector3 playerStartPosition; + Quaternion playerStartRotation; + LOT cannonLot; + uint32_t impactSkillID; + LOT projectileLot; + Vector3 playerOffset; + uint32_t rewardModelMatrix; + float_t cannonVelocity; + float_t cannonMinDistance; + float_t cannonRefireRate; + Vector3 cannonBarrelOffset; + LOT cannonSuperchargedProjectileLot; + LOT cannonProjectileLot; + uint32_t cannonSuperChargeSkill; + uint32_t cannonSkill; + int32_t cannonTimeout; + float_t cannonFOV; + bool useLeaderboards; + uint32_t streakModifier; + uint32_t chargedTime; + uint32_t chargedPoints; + std::string rewardModelGroup; + uint32_t activityID; + uint32_t scoreReward1; + uint32_t scoreLootMatrix1; + uint32_t scoreReward2; + uint32_t scoreLootMatrix2; + uint32_t scoreReward3; + uint32_t scoreLootMatrix3; + uint32_t scoreReward4; + uint32_t scoreLootMatrix4; + uint32_t scoreReward5; + uint32_t scoreLootMatrix5; + float_t firstWaveStartTime; + float_t inBetweenWavePause; }; class SGCannon : public ActivityManager { public: - void OnStartup(Entity *self) override; - void OnPlayerLoaded(Entity *self, Entity *player) override; - void OnFireEventServerSide(Entity *self, Entity *sender, std::string args, int32_t param1, int32_t param2, int32_t param3) override; - void OnActivityStateChangeRequest(Entity* self, LWOOBJID senderID, int32_t value1, - int32_t value2, const std::u16string& stringValue) override; - void OnMessageBoxResponse(Entity* self, Entity* sender, int32_t button, const std::u16string& identifier, - const std::u16string& userData) override; - void OnActivityTimerDone(Entity *self, const std::string &name) override; - void OnActivityTimerUpdate(Entity *self, const std::string &name, float_t timeRemaining, float_t elapsedTime) override; + void OnStartup(Entity* self) override; + void OnPlayerLoaded(Entity* self, Entity* player) override; + void OnFireEventServerSide(Entity* self, Entity* sender, std::string args, int32_t param1, int32_t param2, int32_t param3) override; + void OnActivityStateChangeRequest(Entity* self, LWOOBJID senderID, int32_t value1, + int32_t value2, const std::u16string& stringValue) override; + void OnMessageBoxResponse(Entity* self, Entity* sender, int32_t button, const std::u16string& identifier, + const std::u16string& userData) override; + void OnActivityTimerDone(Entity* self, const std::string& name) override; + void OnActivityTimerUpdate(Entity* self, const std::string& name, float_t timeRemaining, float_t elapsedTime) override; private: - static std::vector> GetWaves(); - static SGConstants GetConstants(); - void ResetVars(Entity* self); - void StartGame(Entity* self); - void DoGameStartup(Entity* self); - void SpawnNewModel(Entity* self); - void TimerToggle(Entity* self, bool start = false); - void SpawnObject(Entity* self, const SGEnemy& toSpawn, bool spawnNow = false); - void StartChargedCannon(Entity* self, uint32_t optionalTime = 0); - void ToggleSuperCharge(Entity* self, bool enable); - void RecordPlayerScore(Entity* self); - void PlaySceneAnimation(Entity* self, const std::u16string& animationName, bool onCannon, bool onPlayer, float_t priority); - static void RemovePlayer(LWOOBJID playerID); - void PauseChargeCannon(Entity* self); - void StopGame(Entity* self, bool cancel = false); - void RegisterHit(Entity* self, Entity* target, const std::string& timerName); - void UpdateStreak(Entity* self); - float_t GetCurrentBonus(Entity* self); + static std::vector> GetWaves(); + static SGConstants GetConstants(); + void ResetVars(Entity* self); + void StartGame(Entity* self); + void DoGameStartup(Entity* self); + void SpawnNewModel(Entity* self); + void TimerToggle(Entity* self, bool start = false); + void SpawnObject(Entity* self, const SGEnemy& toSpawn, bool spawnNow = false); + void StartChargedCannon(Entity* self, uint32_t optionalTime = 0); + void ToggleSuperCharge(Entity* self, bool enable); + void RecordPlayerScore(Entity* self); + void PlaySceneAnimation(Entity* self, const std::u16string& animationName, bool onCannon, bool onPlayer, float_t priority); + static void RemovePlayer(LWOOBJID playerID); + void PauseChargeCannon(Entity* self); + void StopGame(Entity* self, bool cancel = false); + void RegisterHit(Entity* self, Entity* target, const std::string& timerName); + void UpdateStreak(Entity* self); + float_t GetCurrentBonus(Entity* self); - LOT m_CannonLot = 1864; - std::u16string PlayerIDVariable = u"PlayerID"; - std::u16string HideScoreBoardVariable = u"HideScoreBoard"; - std::u16string ReSetSuperChargeVariable = u"ReSetSuperCharge"; - std::u16string ShowLoadingUI = u"showLoadingUI"; - std::u16string SpawnNumberVariable = u"SpawnNum"; - std::u16string CurrentSpawnNumberVariable = u"CurSpawnNum"; - std::u16string ThisWaveVariable = u"ThisWave"; - std::u16string GameScoreVariable = u"GameScore"; - std::u16string GameTimeVariable = u"GameTime"; - std::u16string GameStartedVariable = u"GameStarted"; - std::u16string ShotsFiredVariable = u"ShotsFired"; - std::u16string MaxStreakVariable = u"MaxStreak"; - std::u16string MissesVariable = u"Misses"; - std::u16string CurrentStreakVariable = u"CurrentStreak"; - std::u16string CurrentSuperChargedTimeVariable = u"CurrentSuperChargedTime"; - std::u16string StreakBonusVariable = u"StreakBonus"; - std::u16string LastSuperTotalVariable = u"LastSuperTotal"; - std::u16string CurrentRewardVariable = u"CurrentReward"; - std::u16string RewardsVariable = u"Rewards"; - std::u16string TotalScoreVariable = u"TotalScore"; - std::u16string InitVariable = u"Init"; - std::u16string ImpactSkillVariale = u"ImpactSkill"; - std::u16string PlayerScoresVariable = u"PlayerScores"; - std::u16string InitialVelocityVariable = u"InitialVelocity"; - std::u16string ValidActorsVariable = u"ValidActors"; - std::u16string ValidEffectsVariable = u"ValidEffects"; - std::u16string SuperChargeActiveVariable = u"SuperChargeActive"; - std::u16string MatrixVariable = u"Matrix"; - std::u16string TimeLimitVariable = u"game_timelimit"; - std::u16string AudioStartIntroVariable = u"Audio_Start_Intro"; - std::u16string ClearVariable = u"Clear"; - std::u16string FirstTimeDoneVariable = u"FirstTimeDone"; - std::u16string RewardAddedVariable = u"rewardAdded"; - std::u16string SuperChargePausedVariable = u"Super_Charge_Paused"; - std::u16string WaveStatusVariable = u"WaveStatus"; - std::u16string CountVariable = u"count"; - std::u16string StopVariable = u"Stop"; - std::u16string ActiveSpawnsVariable = u"ActiveSpawns"; - std::u16string SpawnedObjects = u"SpawnedObjects"; - std::u16string WaveNumVariable = u"wave.waveNum"; - std::u16string WaveStrVariable = u"wave.waveStr"; - std::u16string ChargeCountingVariable = u"charge_counting"; - std::u16string SuperChargeBarVariable = u"SuperChargeBar"; - std::u16string NumberOfChargesVariable = u"NumberOfCharges"; - std::u16string CannonBallSkillIDVariable = u"cbskill"; - std::u16string HideSuperChargeVariable = u"HideSuper"; - std::u16string AudioFinalWaveDoneVariable = u"Audio_Final_Wave_Done"; + LOT m_CannonLot = 1864; + std::u16string PlayerIDVariable = u"PlayerID"; + std::u16string HideScoreBoardVariable = u"HideScoreBoard"; + std::u16string ReSetSuperChargeVariable = u"ReSetSuperCharge"; + std::u16string ShowLoadingUI = u"showLoadingUI"; + std::u16string SpawnNumberVariable = u"SpawnNum"; + std::u16string CurrentSpawnNumberVariable = u"CurSpawnNum"; + std::u16string ThisWaveVariable = u"ThisWave"; + std::u16string GameScoreVariable = u"GameScore"; + std::u16string GameTimeVariable = u"GameTime"; + std::u16string GameStartedVariable = u"GameStarted"; + std::u16string ShotsFiredVariable = u"ShotsFired"; + std::u16string MaxStreakVariable = u"MaxStreak"; + std::u16string MissesVariable = u"Misses"; + std::u16string CurrentStreakVariable = u"CurrentStreak"; + std::u16string CurrentSuperChargedTimeVariable = u"CurrentSuperChargedTime"; + std::u16string StreakBonusVariable = u"StreakBonus"; + std::u16string LastSuperTotalVariable = u"LastSuperTotal"; + std::u16string CurrentRewardVariable = u"CurrentReward"; + std::u16string RewardsVariable = u"Rewards"; + std::u16string TotalScoreVariable = u"TotalScore"; + std::u16string InitVariable = u"Init"; + std::u16string ImpactSkillVariale = u"ImpactSkill"; + std::u16string PlayerScoresVariable = u"PlayerScores"; + std::u16string InitialVelocityVariable = u"InitialVelocity"; + std::u16string ValidActorsVariable = u"ValidActors"; + std::u16string ValidEffectsVariable = u"ValidEffects"; + std::u16string SuperChargeActiveVariable = u"SuperChargeActive"; + std::u16string MatrixVariable = u"Matrix"; + std::u16string TimeLimitVariable = u"game_timelimit"; + std::u16string AudioStartIntroVariable = u"Audio_Start_Intro"; + std::u16string ClearVariable = u"Clear"; + std::u16string FirstTimeDoneVariable = u"FirstTimeDone"; + std::u16string RewardAddedVariable = u"rewardAdded"; + std::u16string SuperChargePausedVariable = u"Super_Charge_Paused"; + std::u16string WaveStatusVariable = u"WaveStatus"; + std::u16string CountVariable = u"count"; + std::u16string StopVariable = u"Stop"; + std::u16string ActiveSpawnsVariable = u"ActiveSpawns"; + std::u16string SpawnedObjects = u"SpawnedObjects"; + std::u16string WaveNumVariable = u"wave.waveNum"; + std::u16string WaveStrVariable = u"wave.waveStr"; + std::u16string ChargeCountingVariable = u"charge_counting"; + std::u16string SuperChargeBarVariable = u"SuperChargeBar"; + std::u16string NumberOfChargesVariable = u"NumberOfCharges"; + std::u16string CannonBallSkillIDVariable = u"cbskill"; + std::u16string HideSuperChargeVariable = u"HideSuper"; + std::u16string AudioFinalWaveDoneVariable = u"Audio_Final_Wave_Done"; - std::string SpawnWaveTimer = "SpawnWave"; - std::string EndWaveTimer = "EndWave"; - std::string GameOverTimer = "GameOver"; - std::string DoSpawnTimer = "DoSpawn"; - std::string EndGameBufferTimer = "endGameBuffer"; - std::string SuperChargeTimer = "SuperChargeTimer"; + std::string SpawnWaveTimer = "SpawnWave"; + std::string EndWaveTimer = "EndWave"; + std::string GameOverTimer = "GameOver"; + std::string DoSpawnTimer = "DoSpawn"; + std::string EndGameBufferTimer = "endGameBuffer"; + std::string SuperChargeTimer = "SuperChargeTimer"; - std::string ModelToBuildEvent = "modelToBuild"; + std::string ModelToBuildEvent = "modelToBuild"; - std::regex DoSpawnRegex = std::regex("\\d*"); - SGConstants constants {}; - std::vector> m_Waves {}; + std::regex DoSpawnRegex = std::regex("\\d*"); + SGConstants constants{}; + std::vector> m_Waves{}; }; diff --git a/dScripts/ScriptComponent.cpp b/dScripts/ScriptComponent.cpp index 3c5c2584..272de5ab 100644 --- a/dScripts/ScriptComponent.cpp +++ b/dScripts/ScriptComponent.cpp @@ -18,27 +18,27 @@ ScriptComponent::~ScriptComponent() { } void ScriptComponent::Serialize(RakNet::BitStream* outBitStream, bool bIsInitialUpdate, unsigned int& flags) { - if (bIsInitialUpdate) { - const auto& networkSettings = m_Parent->GetNetworkSettings(); - auto hasNetworkSettings = !networkSettings.empty(); - outBitStream->Write(hasNetworkSettings); + if (bIsInitialUpdate) { + const auto& networkSettings = m_Parent->GetNetworkSettings(); + auto hasNetworkSettings = !networkSettings.empty(); + outBitStream->Write(hasNetworkSettings); - if (hasNetworkSettings) { + if (hasNetworkSettings) { - // First write the most inner LDF data - RakNet::BitStream ldfData; - ldfData.Write(0); - ldfData.Write(networkSettings.size()); + // First write the most inner LDF data + RakNet::BitStream ldfData; + ldfData.Write(0); + ldfData.Write(networkSettings.size()); - for (auto* networkSetting : networkSettings) { - networkSetting->WriteToPacket(&ldfData); - } + for (auto* networkSetting : networkSettings) { + networkSetting->WriteToPacket(&ldfData); + } - // Finally write everything to the stream - outBitStream->Write(ldfData.GetNumberOfBytesUsed()); - outBitStream->Write(ldfData); - } - } + // Finally write everything to the stream + outBitStream->Write(ldfData.GetNumberOfBytesUsed()); + outBitStream->Write(ldfData); + } + } } CppScripts::Script* ScriptComponent::GetScript() { @@ -46,7 +46,7 @@ CppScripts::Script* ScriptComponent::GetScript() { } void ScriptComponent::SetScript(const std::string& scriptName) { - //we don't need to delete the script because others may be using it :) + //we don't need to delete the script because others may be using it :) /*if (m_Client) { m_Script = new InvalidScript(); return; diff --git a/dScripts/ScriptComponent.h b/dScripts/ScriptComponent.h index 82d1f648..94226627 100644 --- a/dScripts/ScriptComponent.h +++ b/dScripts/ScriptComponent.h @@ -19,45 +19,45 @@ class Entity; class ScriptComponent : public Component { public: static const uint32_t ComponentType = COMPONENT_TYPE_SCRIPT; - - ScriptComponent(Entity* parent, std::string scriptName, bool serialized, bool client = false); - ~ScriptComponent() override; - void Serialize(RakNet::BitStream* outBitStream, bool bIsInitialUpdate, unsigned int& flags); + ScriptComponent(Entity* parent, std::string scriptName, bool serialized, bool client = false); + ~ScriptComponent() override; - /** - * Returns the script that's attached to this entity - * @return the script that's attached to this entity - */ + void Serialize(RakNet::BitStream* outBitStream, bool bIsInitialUpdate, unsigned int& flags); + + /** + * Returns the script that's attached to this entity + * @return the script that's attached to this entity + */ CppScripts::Script* GetScript(); - /** - * Sets whether the entity should be serialized, unused - * @param var whether the entity should be serialized - */ + /** + * Sets whether the entity should be serialized, unused + * @param var whether the entity should be serialized + */ void SetSerialized(const bool var) { m_Serialized = var; } - /** - * Sets the script using a path by looking through dScripts for a script that matches - * @param scriptName the name of the script to find - */ + /** + * Sets the script using a path by looking through dScripts for a script that matches + * @param scriptName the name of the script to find + */ void SetScript(const std::string& scriptName); private: - /** - * The script attached to this entity - */ + /** + * The script attached to this entity + */ CppScripts::Script* m_Script; - /** - * Whether or not the comp should be serialized, unused - */ + /** + * Whether or not the comp should be serialized, unused + */ bool m_Serialized; - /** - * Whether or not this script is a client script - */ + /** + * Whether or not this script is a client script + */ bool m_Client; }; diff --git a/dScripts/ScriptedPowerupSpawner.cpp b/dScripts/ScriptedPowerupSpawner.cpp index 91c25856..730e65ba 100644 --- a/dScripts/ScriptedPowerupSpawner.cpp +++ b/dScripts/ScriptedPowerupSpawner.cpp @@ -2,45 +2,45 @@ #include "RenderComponent.h" #include "EntityManager.h" -void ScriptedPowerupSpawner::OnTemplateStartup(Entity *self) { - self->SetVar(u"currentCycle", 1); - self->AddTimer("timeToSpawn", self->GetVar(u"delayToFirstCycle")); +void ScriptedPowerupSpawner::OnTemplateStartup(Entity* self) { + self->SetVar(u"currentCycle", 1); + self->AddTimer("timeToSpawn", self->GetVar(u"delayToFirstCycle")); } -void ScriptedPowerupSpawner::OnTimerDone(Entity *self, std::string message) { - if (message == "die") { - self->Smash(); - } else if (message == "timeToSpawn") { +void ScriptedPowerupSpawner::OnTimerDone(Entity* self, std::string message) { + if (message == "die") { + self->Smash(); + } else if (message == "timeToSpawn") { - const auto itemLOT = self->GetVar(u"lootLOT"); + const auto itemLOT = self->GetVar(u"lootLOT"); - // Build drop table - std::unordered_map drops; + // Build drop table + std::unordered_map drops; - drops.emplace(itemLOT, 1); + drops.emplace(itemLOT, 1); - // Spawn the required number of powerups - auto* owner = EntityManager::Instance()->GetEntity(self->GetSpawnerID()); - if (owner != nullptr) { - auto* renderComponent = self->GetComponent(); - for (auto i = 0; i < self->GetVar(u"numberOfPowerups"); i++) { - if (renderComponent != nullptr) { - renderComponent->PlayEffect(0, u"cast", "N_cast"); - } + // Spawn the required number of powerups + auto* owner = EntityManager::Instance()->GetEntity(self->GetSpawnerID()); + if (owner != nullptr) { + auto* renderComponent = self->GetComponent(); + for (auto i = 0; i < self->GetVar(u"numberOfPowerups"); i++) { + if (renderComponent != nullptr) { + renderComponent->PlayEffect(0, u"cast", "N_cast"); + } - LootGenerator::Instance().DropLoot(owner, self, drops, 0, 0); - } + LootGenerator::Instance().DropLoot(owner, self, drops, 0, 0); + } - // Increment the current cycle - if (self->GetVar(u"currentCycle") < self->GetVar(u"numCycles")) { - self->AddTimer("timeToSpawn", self->GetVar(u"secPerCycle")); - self->SetVar(u"currentCycle", self->GetVar(u"currentCycle") + 1); - } + // Increment the current cycle + if (self->GetVar(u"currentCycle") < self->GetVar(u"numCycles")) { + self->AddTimer("timeToSpawn", self->GetVar(u"secPerCycle")); + self->SetVar(u"currentCycle", self->GetVar(u"currentCycle") + 1); + } - // Kill if this was the last cycle - if (self->GetVar(u"currentCycle") >= self->GetVar(u"numCycles")) { - self->AddTimer("die", self->GetVar(u"deathDelay")); - } - } - } + // Kill if this was the last cycle + if (self->GetVar(u"currentCycle") >= self->GetVar(u"numCycles")) { + self->AddTimer("die", self->GetVar(u"deathDelay")); + } + } + } } diff --git a/dScripts/ScriptedPowerupSpawner.h b/dScripts/ScriptedPowerupSpawner.h index 597e8673..1fa57d90 100644 --- a/dScripts/ScriptedPowerupSpawner.h +++ b/dScripts/ScriptedPowerupSpawner.h @@ -13,11 +13,11 @@ */ class ScriptedPowerupSpawner : public CppScripts::Script { public: - /** - * Called by the child script after on startup - * \param self the object this script belongs to - */ - static void OnTemplateStartup(Entity* self); - void OnTimerDone(Entity* self, std::string message) override; + /** + * Called by the child script after on startup + * \param self the object this script belongs to + */ + static void OnTemplateStartup(Entity* self); + void OnTimerDone(Entity* self, std::string message) override; }; diff --git a/dScripts/SpawnGryphonServer.cpp b/dScripts/SpawnGryphonServer.cpp index d411569c..22e5ff59 100644 --- a/dScripts/SpawnGryphonServer.cpp +++ b/dScripts/SpawnGryphonServer.cpp @@ -3,25 +3,25 @@ #include "GameMessages.h" #include "MissionComponent.h" -void SpawnGryphonServer::SetVariables(Entity *self) { - self->SetVar(u"petLOT", 12433); - self->SetVar(u"petType", "gryphon"); - self->SetVar(u"maxPets", 2); - self->SetVar(u"spawnAnim", u"spawn"); - self->SetVar(u"spawnCinematic", u"SentinelPet"); +void SpawnGryphonServer::SetVariables(Entity* self) { + self->SetVar(u"petLOT", 12433); + self->SetVar(u"petType", "gryphon"); + self->SetVar(u"maxPets", 2); + self->SetVar(u"spawnAnim", u"spawn"); + self->SetVar(u"spawnCinematic", u"SentinelPet"); } -void SpawnGryphonServer::OnUse(Entity *self, Entity *user) { - auto* missionComponent = user->GetComponent(); - auto* inventoryComponent = user->GetComponent(); +void SpawnGryphonServer::OnUse(Entity* self, Entity* user) { + auto* missionComponent = user->GetComponent(); + auto* inventoryComponent = user->GetComponent(); - // Little extra for handling the case of the egg being placed the first time - if (missionComponent != nullptr && inventoryComponent != nullptr - && missionComponent->GetMissionState(1391) == MissionState::MISSION_STATE_ACTIVE) { - inventoryComponent->RemoveItem(12483, inventoryComponent->GetLotCount(12483)); - GameMessages::SendTerminateInteraction(user->GetObjectID(), FROM_INTERACTION, self->GetObjectID()); - return; - } + // Little extra for handling the case of the egg being placed the first time + if (missionComponent != nullptr && inventoryComponent != nullptr + && missionComponent->GetMissionState(1391) == MissionState::MISSION_STATE_ACTIVE) { + inventoryComponent->RemoveItem(12483, inventoryComponent->GetLotCount(12483)); + GameMessages::SendTerminateInteraction(user->GetObjectID(), FROM_INTERACTION, self->GetObjectID()); + return; + } - SpawnPetBaseServer::OnUse(self, user); + SpawnPetBaseServer::OnUse(self, user); } diff --git a/dScripts/SpawnGryphonServer.h b/dScripts/SpawnGryphonServer.h index 8f76e1dc..eacf93e4 100644 --- a/dScripts/SpawnGryphonServer.h +++ b/dScripts/SpawnGryphonServer.h @@ -2,6 +2,6 @@ #include "SpawnPetBaseServer.h" class SpawnGryphonServer : public SpawnPetBaseServer { - void SetVariables(Entity *self) override; - void OnUse(Entity *self, Entity *user) override; + void SetVariables(Entity* self) override; + void OnUse(Entity* self, Entity* user) override; }; diff --git a/dScripts/SpawnLionServer.cpp b/dScripts/SpawnLionServer.cpp index b19531a4..622985b1 100644 --- a/dScripts/SpawnLionServer.cpp +++ b/dScripts/SpawnLionServer.cpp @@ -1,10 +1,10 @@ #include "SpawnLionServer.h" #include "Entity.h" -void SpawnLionServer::SetVariables(Entity *self) { - self->SetVar(u"petLOT", 3520); - self->SetVar(u"petType", "lion"); - self->SetVar(u"maxPets", 5); - self->SetVar(u"spawnAnim", u"spawn-lion"); - self->SetVar(u"spawnCinematic", u"Lion_spawn"); +void SpawnLionServer::SetVariables(Entity* self) { + self->SetVar(u"petLOT", 3520); + self->SetVar(u"petType", "lion"); + self->SetVar(u"maxPets", 5); + self->SetVar(u"spawnAnim", u"spawn-lion"); + self->SetVar(u"spawnCinematic", u"Lion_spawn"); } diff --git a/dScripts/SpawnLionServer.h b/dScripts/SpawnLionServer.h index b4cd208c..2c8e7f0f 100644 --- a/dScripts/SpawnLionServer.h +++ b/dScripts/SpawnLionServer.h @@ -2,5 +2,5 @@ #include "SpawnPetBaseServer.h" class SpawnLionServer : public SpawnPetBaseServer { - void SetVariables(Entity *self) override; + void SetVariables(Entity* self) override; }; diff --git a/dScripts/SpawnPetBaseServer.cpp b/dScripts/SpawnPetBaseServer.cpp index d23e371a..1d73a5b8 100644 --- a/dScripts/SpawnPetBaseServer.cpp +++ b/dScripts/SpawnPetBaseServer.cpp @@ -3,80 +3,80 @@ #include "EntityManager.h" #include "PetComponent.h" -void SpawnPetBaseServer::OnStartup(Entity *self) { - SetVariables(self); - self->SetVar(u"spawnedPets", ""); +void SpawnPetBaseServer::OnStartup(Entity* self) { + SetVariables(self); + self->SetVar(u"spawnedPets", ""); } -void SpawnPetBaseServer::OnUse(Entity *self, Entity *user) { - auto possibleSpawners = EntityManager::Instance()->GetEntitiesInGroup(self->GetVar(u"petType") + "Spawner"); - if (possibleSpawners.empty()) - return; +void SpawnPetBaseServer::OnUse(Entity* self, Entity* user) { + auto possibleSpawners = EntityManager::Instance()->GetEntitiesInGroup(self->GetVar(u"petType") + "Spawner"); + if (possibleSpawners.empty()) + return; - if (!CheckNumberOfPets(self, user)) - return; + if (!CheckNumberOfPets(self, user)) + return; - auto* spawner = possibleSpawners.at(0); - auto petType = GeneralUtils::ASCIIToUTF16(self->GetVar(u"petType")); + auto* spawner = possibleSpawners.at(0); + auto petType = GeneralUtils::ASCIIToUTF16(self->GetVar(u"petType")); - EntityInfo info {}; - info.pos = spawner->GetPosition(); - info.rot = spawner->GetRotation(); - info.lot = self->GetVar(u"petLOT"); - info.spawnerID = self->GetObjectID(); - info.settings = { - new LDFData(u"tamer", user->GetObjectID()), - new LDFData(u"groupID", petType + (GeneralUtils::to_u16string(user->GetObjectID())) + u";" + petType + u"s"), - new LDFData(u"spawnAnim", self->GetVar(u"spawnAnim")), - new LDFData(u"spawnTimer", 1.0f) - }; + EntityInfo info{}; + info.pos = spawner->GetPosition(); + info.rot = spawner->GetRotation(); + info.lot = self->GetVar(u"petLOT"); + info.spawnerID = self->GetObjectID(); + info.settings = { + new LDFData(u"tamer", user->GetObjectID()), + new LDFData(u"groupID", petType + (GeneralUtils::to_u16string(user->GetObjectID())) + u";" + petType + u"s"), + new LDFData(u"spawnAnim", self->GetVar(u"spawnAnim")), + new LDFData(u"spawnTimer", 1.0f) + }; - auto* pet = EntityManager::Instance()->CreateEntity(info); - EntityManager::Instance()->ConstructEntity(pet); + auto* pet = EntityManager::Instance()->CreateEntity(info); + EntityManager::Instance()->ConstructEntity(pet); - self->SetVar(u"spawnedPets", self->GetVar(u"spawnedPets") + "," - + std::to_string(pet->GetObjectID())); + self->SetVar(u"spawnedPets", self->GetVar(u"spawnedPets") + "," + + std::to_string(pet->GetObjectID())); - auto spawnCinematic = self->GetVar(u"spawnCinematic"); - if (!spawnCinematic.empty()) { - GameMessages::SendPlayCinematic(user->GetObjectID(), spawnCinematic, UNASSIGNED_SYSTEM_ADDRESS); - } + auto spawnCinematic = self->GetVar(u"spawnCinematic"); + if (!spawnCinematic.empty()) { + GameMessages::SendPlayCinematic(user->GetObjectID(), spawnCinematic, UNASSIGNED_SYSTEM_ADDRESS); + } - GameMessages::SendTerminateInteraction(user->GetObjectID(), FROM_INTERACTION, self->GetObjectID()); + GameMessages::SendTerminateInteraction(user->GetObjectID(), FROM_INTERACTION, self->GetObjectID()); } -bool SpawnPetBaseServer::CheckNumberOfPets(Entity *self, Entity* user) { - auto petIDString = self->GetVar(u"spawnedPets"); - auto petIDs = GeneralUtils::SplitString(petIDString, ','); +bool SpawnPetBaseServer::CheckNumberOfPets(Entity* self, Entity* user) { + auto petIDString = self->GetVar(u"spawnedPets"); + auto petIDs = GeneralUtils::SplitString(petIDString, ','); - // Check all the pets that were tamed in the process or were smashed - std::vector petsToKeep {}; - for (const auto& petID : petIDs) { - if (petID.empty()) - continue; + // Check all the pets that were tamed in the process or were smashed + std::vector petsToKeep{}; + for (const auto& petID : petIDs) { + if (petID.empty()) + continue; - const auto* spawnedPet = EntityManager::Instance()->GetEntity(std::stoull(petID)); - if (spawnedPet == nullptr) - continue; + const auto* spawnedPet = EntityManager::Instance()->GetEntity(std::stoull(petID)); + if (spawnedPet == nullptr) + continue; - const auto* petComponent = spawnedPet->GetComponent(); - if (petComponent == nullptr || petComponent->GetOwner() != nullptr) - continue; + const auto* petComponent = spawnedPet->GetComponent(); + if (petComponent == nullptr || petComponent->GetOwner() != nullptr) + continue; - // Each user can only spawn one pet - if (spawnedPet->GetVar(u"tamer") == user->GetObjectID()) - return false; + // Each user can only spawn one pet + if (spawnedPet->GetVar(u"tamer") == user->GetObjectID()) + return false; - petsToKeep.push_back(spawnedPet->GetObjectID()); - } + petsToKeep.push_back(spawnedPet->GetObjectID()); + } - self->SetNetworkVar(u"TooManyPets", petsToKeep.size() >= self->GetVar(u"maxPets")); + self->SetNetworkVar(u"TooManyPets", petsToKeep.size() >= self->GetVar(u"maxPets")); - std::string newPetIDs; - for (const auto petID : petsToKeep) { - newPetIDs += (std::to_string(petID) + ","); - } - self->SetVar(u"spawnedPets", newPetIDs); + std::string newPetIDs; + for (const auto petID : petsToKeep) { + newPetIDs += (std::to_string(petID) + ","); + } + self->SetVar(u"spawnedPets", newPetIDs); - return petsToKeep.size() < self->GetVar(u"maxPets"); + return petsToKeep.size() < self->GetVar(u"maxPets"); } diff --git a/dScripts/SpawnPetBaseServer.h b/dScripts/SpawnPetBaseServer.h index 80412b13..9ae51084 100644 --- a/dScripts/SpawnPetBaseServer.h +++ b/dScripts/SpawnPetBaseServer.h @@ -11,9 +11,9 @@ */ class SpawnPetBaseServer : public CppScripts::Script { public: - void OnStartup(Entity *self) override; - void OnUse(Entity *self, Entity *user) override; - virtual void SetVariables(Entity* self) {}; + void OnStartup(Entity* self) override; + void OnUse(Entity* self, Entity* user) override; + virtual void SetVariables(Entity* self) {}; private: - static bool CheckNumberOfPets(Entity* self, Entity* user); + static bool CheckNumberOfPets(Entity* self, Entity* user); }; diff --git a/dScripts/SpawnSaberCatServer.cpp b/dScripts/SpawnSaberCatServer.cpp index e89d9df7..3307c522 100644 --- a/dScripts/SpawnSaberCatServer.cpp +++ b/dScripts/SpawnSaberCatServer.cpp @@ -1,10 +1,10 @@ #include "SpawnSaberCatServer.h" #include "Entity.h" -void SpawnSaberCatServer::SetVariables(Entity *self) { - self->SetVar(u"petLOT", 12432); - self->SetVar(u"petType", "sabercat"); - self->SetVar(u"maxPets", 3); - self->SetVar(u"spawnAnim", u"pq_m_drop-down"); - self->SetVar(u"spawnCinematic", u"AssemblyPet"); +void SpawnSaberCatServer::SetVariables(Entity* self) { + self->SetVar(u"petLOT", 12432); + self->SetVar(u"petType", "sabercat"); + self->SetVar(u"maxPets", 3); + self->SetVar(u"spawnAnim", u"pq_m_drop-down"); + self->SetVar(u"spawnCinematic", u"AssemblyPet"); } diff --git a/dScripts/SpawnSaberCatServer.h b/dScripts/SpawnSaberCatServer.h index 6be6ff5b..a4d1874c 100644 --- a/dScripts/SpawnSaberCatServer.h +++ b/dScripts/SpawnSaberCatServer.h @@ -2,5 +2,5 @@ #include "SpawnPetBaseServer.h" class SpawnSaberCatServer : public SpawnPetBaseServer { - void SetVariables(Entity *self) override; + void SetVariables(Entity* self) override; }; diff --git a/dScripts/SpawnShrakeServer.cpp b/dScripts/SpawnShrakeServer.cpp index 5be55ebc..cf388ad0 100644 --- a/dScripts/SpawnShrakeServer.cpp +++ b/dScripts/SpawnShrakeServer.cpp @@ -1,10 +1,10 @@ #include "SpawnShrakeServer.h" #include "Entity.h" -void SpawnShrakeServer::SetVariables(Entity *self) { - self->SetVar(u"petLOT", 12434); - self->SetVar(u"petType", "shrake"); - self->SetVar(u"maxPets", 3); - self->SetVar(u"spawnAnim", u"mf_u_g_TT_spawn-1"); - self->SetVar(u"spawnCinematic", u"ParadoxPet"); +void SpawnShrakeServer::SetVariables(Entity* self) { + self->SetVar(u"petLOT", 12434); + self->SetVar(u"petType", "shrake"); + self->SetVar(u"maxPets", 3); + self->SetVar(u"spawnAnim", u"mf_u_g_TT_spawn-1"); + self->SetVar(u"spawnCinematic", u"ParadoxPet"); } diff --git a/dScripts/SpawnShrakeServer.h b/dScripts/SpawnShrakeServer.h index 9d7e86bc..de8c7405 100644 --- a/dScripts/SpawnShrakeServer.h +++ b/dScripts/SpawnShrakeServer.h @@ -2,5 +2,5 @@ #include "SpawnPetBaseServer.h" class SpawnShrakeServer : public SpawnPetBaseServer { - void SetVariables(Entity *self) override; + void SetVariables(Entity* self) override; }; diff --git a/dScripts/SpawnStegoServer.cpp b/dScripts/SpawnStegoServer.cpp index d845ff45..9fddeae5 100644 --- a/dScripts/SpawnStegoServer.cpp +++ b/dScripts/SpawnStegoServer.cpp @@ -1,10 +1,10 @@ #include "SpawnStegoServer.h" #include "Entity.h" -void SpawnStegoServer::SetVariables(Entity *self) { - self->SetVar(u"petLOT", 12431); - self->SetVar(u"petType", "stego"); - self->SetVar(u"maxPets", 3); - self->SetVar(u"spawnAnim", u"spawn"); - self->SetVar(u"spawnCinematic", u"VenturePet"); +void SpawnStegoServer::SetVariables(Entity* self) { + self->SetVar(u"petLOT", 12431); + self->SetVar(u"petType", "stego"); + self->SetVar(u"maxPets", 3); + self->SetVar(u"spawnAnim", u"spawn"); + self->SetVar(u"spawnCinematic", u"VenturePet"); } diff --git a/dScripts/SpawnStegoServer.h b/dScripts/SpawnStegoServer.h index d5bbd20b..955fd119 100644 --- a/dScripts/SpawnStegoServer.h +++ b/dScripts/SpawnStegoServer.h @@ -2,5 +2,5 @@ #include "SpawnPetBaseServer.h" class SpawnStegoServer : public SpawnPetBaseServer { - void SetVariables(Entity *self) override; + void SetVariables(Entity* self) override; }; diff --git a/dScripts/SpecialImaginePowerupSpawner.cpp b/dScripts/SpecialImaginePowerupSpawner.cpp index 8417efa2..0a13fc2b 100644 --- a/dScripts/SpecialImaginePowerupSpawner.cpp +++ b/dScripts/SpecialImaginePowerupSpawner.cpp @@ -5,34 +5,28 @@ #include "DestroyableComponent.h" #include "EntityManager.h" -void SpecialImaginePowerupSpawner::OnStartup(Entity* self) -{ +void SpecialImaginePowerupSpawner::OnStartup(Entity* self) { self->SetProximityRadius(1.5f, "powerupEnter"); self->SetVar(u"bIsDead", false); } -void SpecialImaginePowerupSpawner::OnProximityUpdate(Entity* self, Entity* entering, const std::string name, const std::string status) -{ - if (name != "powerupEnter" && status != "ENTER") - { +void SpecialImaginePowerupSpawner::OnProximityUpdate(Entity* self, Entity* entering, const std::string name, const std::string status) { + if (name != "powerupEnter" && status != "ENTER") { return; } - if (entering->GetLOT() != 1) - { + if (entering->GetLOT() != 1) { return; } - if (self->GetVar(u"bIsDead")) - { + if (self->GetVar(u"bIsDead")) { return; } GameMessages::SendPlayFXEffect(self, -1, u"pickup", "", LWOOBJID_EMPTY, 1, 1, true); SkillComponent* skillComponent; - if (!self->TryGetComponent(COMPONENT_TYPE_SKILL, skillComponent)) - { + if (!self->TryGetComponent(COMPONENT_TYPE_SKILL, skillComponent)) { return; } @@ -41,14 +35,13 @@ void SpecialImaginePowerupSpawner::OnProximityUpdate(Entity* self, Entity* enter skillComponent->CalculateBehavior(13, 20, source); DestroyableComponent* destroyableComponent; - if (!self->TryGetComponent(COMPONENT_TYPE_DESTROYABLE, destroyableComponent)) - { + if (!self->TryGetComponent(COMPONENT_TYPE_DESTROYABLE, destroyableComponent)) { return; } - + self->SetVar(u"bIsDead", true); self->AddCallbackTimer(1.0f, [self]() { EntityManager::Instance()->ScheduleForKill(self); - }); + }); } diff --git a/dScripts/SsModularBuildServer.cpp b/dScripts/SsModularBuildServer.cpp index 33f8db47..d5b6da50 100644 --- a/dScripts/SsModularBuildServer.cpp +++ b/dScripts/SsModularBuildServer.cpp @@ -7,7 +7,7 @@ void SsModularBuildServer::OnModularBuildExit(Entity* self, Entity* player, bool if (bCompleted) { MissionComponent* mission = static_cast(player->GetComponent(COMPONENT_TYPE_MISSION)); Mission* rocketMission = mission->GetMission(missionNum); - + if (rocketMission->GetMissionState() == MissionState::MISSION_STATE_ACTIVE) { mission->ForceProgress(missionNum, 2478, 1); } diff --git a/dScripts/StinkyFishTarget.cpp b/dScripts/StinkyFishTarget.cpp index 57256b6b..19dbce88 100644 --- a/dScripts/StinkyFishTarget.cpp +++ b/dScripts/StinkyFishTarget.cpp @@ -1,42 +1,42 @@ #include "StinkyFishTarget.h" #include "EntityManager.h" -void StinkyFishTarget::OnStartup(Entity *self) { - auto position = self->GetPosition(); - position.SetY(position.GetY() - 0.5f); - self->SetPosition(position); +void StinkyFishTarget::OnStartup(Entity* self) { + auto position = self->GetPosition(); + position.SetY(position.GetY() - 0.5f); + self->SetPosition(position); } -void StinkyFishTarget::OnSkillEventFired(Entity *self, Entity *caster, const std::string &message) { - if (message != "stinkfish" || self->GetVar(u"used")) - return; +void StinkyFishTarget::OnSkillEventFired(Entity* self, Entity* caster, const std::string& message) { + if (message != "stinkfish" || self->GetVar(u"used")) + return; - self->SetVar(u"used", true); - self->SetVar(u"player", caster->GetObjectID()); + self->SetVar(u"used", true); + self->SetVar(u"player", caster->GetObjectID()); - EntityInfo entityInfo {}; - entityInfo.pos = self->GetPosition(); - entityInfo.rot = self->GetRotation(); - entityInfo.spawnerID = self->GetObjectID(); - entityInfo.settings = { - new LDFData(u"no_timed_spawn", true) - }; + EntityInfo entityInfo{}; + entityInfo.pos = self->GetPosition(); + entityInfo.rot = self->GetRotation(); + entityInfo.spawnerID = self->GetObjectID(); + entityInfo.settings = { + new LDFData(u"no_timed_spawn", true) + }; - auto* fish = EntityManager::Instance()->CreateEntity(entityInfo); - EntityManager::Instance()->ConstructEntity(fish); + auto* fish = EntityManager::Instance()->CreateEntity(entityInfo); + EntityManager::Instance()->ConstructEntity(fish); - self->SetVar(u"fish", fish->GetObjectID()); - self->AddTimer("smash", 5.0f); + self->SetVar(u"fish", fish->GetObjectID()); + self->AddTimer("smash", 5.0f); } -void StinkyFishTarget::OnTimerDone(Entity *self, std::string timerName) { - if (timerName == "smash") { - const auto playerID = self->GetVar(u"player"); - auto* fish = EntityManager::Instance()->GetEntity(self->GetVar(u"fish")); +void StinkyFishTarget::OnTimerDone(Entity* self, std::string timerName) { + if (timerName == "smash") { + const auto playerID = self->GetVar(u"player"); + auto* fish = EntityManager::Instance()->GetEntity(self->GetVar(u"fish")); - if (fish != nullptr) { - fish->Smash(playerID); - self->Smash(playerID); - } - } + if (fish != nullptr) { + fish->Smash(playerID); + self->Smash(playerID); + } + } } diff --git a/dScripts/StinkyFishTarget.h b/dScripts/StinkyFishTarget.h index d88ce35e..6c52171d 100644 --- a/dScripts/StinkyFishTarget.h +++ b/dScripts/StinkyFishTarget.h @@ -2,7 +2,7 @@ #include "CppScripts.h" class StinkyFishTarget : public CppScripts::Script { - void OnStartup(Entity *self) override; - void OnSkillEventFired(Entity *self, Entity *caster, const std::string &message) override; - void OnTimerDone(Entity *self, std::string timerName) override; + void OnStartup(Entity* self) override; + void OnSkillEventFired(Entity* self, Entity* caster, const std::string& message) override; + void OnTimerDone(Entity* self, std::string timerName) override; }; diff --git a/dScripts/StoryBoxInteractServer.cpp b/dScripts/StoryBoxInteractServer.cpp index 187d05a2..2683ddd4 100644 --- a/dScripts/StoryBoxInteractServer.cpp +++ b/dScripts/StoryBoxInteractServer.cpp @@ -5,8 +5,7 @@ #include "AMFFormat.h" void StoryBoxInteractServer::OnUse(Entity* self, Entity* user) { - if (self->GetVar(u"hasCustomText")) - { + if (self->GetVar(u"hasCustomText")) { const auto& customText = self->GetVar(u"customText"); { @@ -20,7 +19,7 @@ void StoryBoxInteractServer::OnUse(Entity* self, Entity* user) { GameMessages::SendUIMessageServerToSingleClient(user, user->GetSystemAddress(), "pushGameState", &args); } - user->AddCallbackTimer(0.1f, [user, customText] () { + user->AddCallbackTimer(0.1f, [user, customText]() { AMFArrayValue args; auto* text = new AMFStringValue(); @@ -30,21 +29,20 @@ void StoryBoxInteractServer::OnUse(Entity* self, Entity* user) { args.InsertValue("text", text); GameMessages::SendUIMessageServerToSingleClient(user, user->GetSystemAddress(), "ToggleStoryBox", &args); - }); + }); return; } - + const auto storyText = self->GetVarAsString(u"storyText"); - + int32_t boxFlag = self->GetVar(u"altFlagID"); - if (boxFlag <= 0) - { - boxFlag = (10000 + Game::server->GetZoneID() +std::stoi(storyText.substr(storyText.length() - 2))); + if (boxFlag <= 0) { + boxFlag = (10000 + Game::server->GetZoneID() + std::stoi(storyText.substr(storyText.length() - 2))); } if (user->GetCharacter()->GetPlayerFlag(boxFlag) == false) { user->GetCharacter()->SetPlayerFlag(boxFlag, true); GameMessages::SendFireEventClientSide(self->GetObjectID(), user->GetSystemAddress(), u"achieve", LWOOBJID_EMPTY, 0, -1, LWOOBJID_EMPTY); } -} \ No newline at end of file +} diff --git a/dScripts/StoryBoxInteractServer.h b/dScripts/StoryBoxInteractServer.h index caa6fd92..913e5185 100644 --- a/dScripts/StoryBoxInteractServer.h +++ b/dScripts/StoryBoxInteractServer.h @@ -4,4 +4,4 @@ class StoryBoxInteractServer : public CppScripts::Script { public: void OnUse(Entity* self, Entity* user); -}; \ No newline at end of file +}; diff --git a/dScripts/Sunflower.cpp b/dScripts/Sunflower.cpp index 436ca5f4..11923e23 100644 --- a/dScripts/Sunflower.cpp +++ b/dScripts/Sunflower.cpp @@ -1,14 +1,14 @@ #include "Sunflower.h" #include "Entity.h" -void Sunflower::OnStartup(Entity *self) { - self->SetVar(u"numCycles", 6); - self->SetVar(u"secPerCycle", 5.0f); - self->SetVar(u"delayToFirstCycle", 1.5f); - self->SetVar(u"deathDelay", 30.0f); - self->SetVar(u"numberOfPowerups", 4); - self->SetVar(u"lootLOT", 11910); +void Sunflower::OnStartup(Entity* self) { + self->SetVar(u"numCycles", 6); + self->SetVar(u"secPerCycle", 5.0f); + self->SetVar(u"delayToFirstCycle", 1.5f); + self->SetVar(u"deathDelay", 30.0f); + self->SetVar(u"numberOfPowerups", 4); + self->SetVar(u"lootLOT", 11910); - // Initiate the actual script - OnTemplateStartup(self); + // Initiate the actual script + OnTemplateStartup(self); } diff --git a/dScripts/Sunflower.h b/dScripts/Sunflower.h index f779d31c..560332c2 100644 --- a/dScripts/Sunflower.h +++ b/dScripts/Sunflower.h @@ -2,5 +2,5 @@ #include "ScriptedPowerupSpawner.h" class Sunflower : public ScriptedPowerupSpawner { - void OnStartup(Entity* self) override; + void OnStartup(Entity* self) override; }; diff --git a/dScripts/TokenConsoleServer.cpp b/dScripts/TokenConsoleServer.cpp index 378cc17f..f21938d1 100644 --- a/dScripts/TokenConsoleServer.cpp +++ b/dScripts/TokenConsoleServer.cpp @@ -19,7 +19,7 @@ void TokenConsoleServer::OnUse(Entity* self, Entity* user) { //figure out which faction the player belongs to: auto character = user->GetCharacter(); if (!character) return; - // At this point the player has to be in a faction. + // At this point the player has to be in a faction. LOT tokenLOT = 0; if (character->GetPlayerFlag(ePlayerFlags::VENTURE_FACTION)) //venture tokenLOT = 8321; @@ -33,4 +33,4 @@ void TokenConsoleServer::OnUse(Entity* self, Entity* user) { } GameMessages::SendTerminateInteraction(user->GetObjectID(), eTerminateType::FROM_INTERACTION, self->GetObjectID()); -} \ No newline at end of file +} diff --git a/dScripts/TokenConsoleServer.h b/dScripts/TokenConsoleServer.h index b6bf8010..ef57287c 100644 --- a/dScripts/TokenConsoleServer.h +++ b/dScripts/TokenConsoleServer.h @@ -7,4 +7,4 @@ class TokenConsoleServer : public CppScripts::Script { private: int bricksToTake = 25; int tokensToGive = 5; -}; \ No newline at end of file +}; diff --git a/dScripts/TouchMissionUpdateServer.cpp b/dScripts/TouchMissionUpdateServer.cpp index baa448af..f732305e 100644 --- a/dScripts/TouchMissionUpdateServer.cpp +++ b/dScripts/TouchMissionUpdateServer.cpp @@ -4,45 +4,37 @@ #include "GameMessages.h" #include "MissionComponent.h" -void TouchMissionUpdateServer::OnStartup(Entity* self) -{ +void TouchMissionUpdateServer::OnStartup(Entity* self) { self->SetProximityRadius(20, "touchCheck"); // Those does not have a collider for some reason? } -void TouchMissionUpdateServer::OnCollisionPhantom(Entity* self, Entity* target) -{ +void TouchMissionUpdateServer::OnCollisionPhantom(Entity* self, Entity* target) { int32_t missionId = self->GetVar(u"TouchCompleteID"); - if (missionId == 0) - { + if (missionId == 0) { return; } - + auto* missionComponent = static_cast(target->GetComponent(COMPONENT_TYPE_MISSION)); - if (missionComponent == nullptr) - { + if (missionComponent == nullptr) { return; } auto* mission = missionComponent->GetMission(missionId); - if (mission == nullptr) - { + if (mission == nullptr) { return; } const auto state = mission->GetMissionState(); - if (state >= MissionState::MISSION_STATE_COMPLETE || mission->GetCompletions() > 1) - { + if (state >= MissionState::MISSION_STATE_COMPLETE || mission->GetCompletions() > 1) { return; } - for (auto* task : mission->GetTasks()) - { - if (!task->IsComplete()) - { + for (auto* task : mission->GetTasks()) { + if (!task->IsComplete()) { task->Complete(); } } @@ -50,10 +42,8 @@ void TouchMissionUpdateServer::OnCollisionPhantom(Entity* self, Entity* target) mission->CheckCompletion(); } -void TouchMissionUpdateServer::OnProximityUpdate(Entity* self, Entity* entering, const std::string name, const std::string status) -{ - if (name != "touchCheck" || status != "ENTER") - { +void TouchMissionUpdateServer::OnProximityUpdate(Entity* self, Entity* entering, const std::string name, const std::string status) { + if (name != "touchCheck" || status != "ENTER") { return; } diff --git a/dScripts/TreasureChestDragonServer.cpp b/dScripts/TreasureChestDragonServer.cpp index 80f8aa48..15f0709c 100644 --- a/dScripts/TreasureChestDragonServer.cpp +++ b/dScripts/TreasureChestDragonServer.cpp @@ -3,48 +3,40 @@ #include "TeamManager.h" #include "EntityManager.h" -void TreasureChestDragonServer::OnStartup(Entity* self) -{ - +void TreasureChestDragonServer::OnStartup(Entity* self) { + } -void TreasureChestDragonServer::OnUse(Entity* self, Entity* user) -{ - if (self->GetVar(u"bUsed")) - { - return; - } +void TreasureChestDragonServer::OnUse(Entity* self, Entity* user) { + if (self->GetVar(u"bUsed")) { + return; + } - self->SetVar(u"bUsed", true); + self->SetVar(u"bUsed", true); - auto* scriptedActivityComponent = self->GetComponent(); + auto* scriptedActivityComponent = self->GetComponent(); - if (scriptedActivityComponent == nullptr) - { - return; - } + if (scriptedActivityComponent == nullptr) { + return; + } - auto rating = 1; + auto rating = 1; - auto* team = TeamManager::Instance()->GetTeam(user->GetObjectID()); + auto* team = TeamManager::Instance()->GetTeam(user->GetObjectID()); - if (team != nullptr) - { - rating = team->members.size(); + if (team != nullptr) { + rating = team->members.size(); - for (const auto member : team->members) - { - auto* memberObject = EntityManager::Instance()->GetEntity(member); + for (const auto member : team->members) { + auto* memberObject = EntityManager::Instance()->GetEntity(member); - if (memberObject == nullptr) continue; + if (memberObject == nullptr) continue; - LootGenerator::Instance().DropActivityLoot(memberObject, self, scriptedActivityComponent->GetActivityID(), rating); - } - } - else - { - LootGenerator::Instance().DropActivityLoot(user, self, scriptedActivityComponent->GetActivityID(), rating); - } + LootGenerator::Instance().DropActivityLoot(memberObject, self, scriptedActivityComponent->GetActivityID(), rating); + } + } else { + LootGenerator::Instance().DropActivityLoot(user, self, scriptedActivityComponent->GetActivityID(), rating); + } - self->Smash(self->GetObjectID()); + self->Smash(self->GetObjectID()); } diff --git a/dScripts/TriggerAmbush.cpp b/dScripts/TriggerAmbush.cpp index f9fb8cf7..8c408b32 100644 --- a/dScripts/TriggerAmbush.cpp +++ b/dScripts/TriggerAmbush.cpp @@ -2,13 +2,11 @@ #include "dZoneManager.h" -void TriggerAmbush::OnStartup(Entity* self) -{ +void TriggerAmbush::OnStartup(Entity* self) { self->SetProximityRadius(20, "ambush"); } -void TriggerAmbush::OnProximityUpdate(Entity* self, Entity* entering, std::string name, std::string status) -{ +void TriggerAmbush::OnProximityUpdate(Entity* self, Entity* entering, std::string name, std::string status) { if (name != "ambush" || status != "ENTER" || !entering->IsPlayer()) return; if (self->GetVar(u"triggered")) return; @@ -17,26 +15,23 @@ void TriggerAmbush::OnProximityUpdate(Entity* self, Entity* entering, std::strin const auto spawners = dZoneManager::Instance()->GetSpawnersByName("Ambush"); - for (auto* spawner : spawners) - { + for (auto* spawner : spawners) { spawner->Activate(); } self->AddTimer("TriggeredTimer", 45); } -void TriggerAmbush::OnTimerDone(Entity* self, std::string timerName) -{ +void TriggerAmbush::OnTimerDone(Entity* self, std::string timerName) { if (timerName != "TriggeredTimer") return; self->SetVar(u"triggered", false); const auto spawners = dZoneManager::Instance()->GetSpawnersByName("Ambush"); - for (auto* spawner : spawners) - { + for (auto* spawner : spawners) { spawner->Reset(); - + spawner->Deactivate(); } } diff --git a/dScripts/TriggerAmbush.h b/dScripts/TriggerAmbush.h index 2ca7cd36..0544f3cb 100644 --- a/dScripts/TriggerAmbush.h +++ b/dScripts/TriggerAmbush.h @@ -5,8 +5,8 @@ class TriggerAmbush : public CppScripts::Script { public: void OnStartup(Entity* self) override; - + void OnProximityUpdate(Entity* self, Entity* entering, std::string name, std::string status) override; - + void OnTimerDone(Entity* self, std::string timerName) override; }; diff --git a/dScripts/VeBricksampleServer.cpp b/dScripts/VeBricksampleServer.cpp index 76486d78..5166d0c3 100644 --- a/dScripts/VeBricksampleServer.cpp +++ b/dScripts/VeBricksampleServer.cpp @@ -4,18 +4,18 @@ #include "MissionComponent.h" #include "GameMessages.h" -void VeBricksampleServer::OnUse(Entity *self, Entity *user) { - auto* missionComponent = user->GetComponent(); - if (missionComponent != nullptr && missionComponent->GetMissionState(1183) == MissionState::MISSION_STATE_ACTIVE) { - const auto loot = self->GetVar(m_LootVariable); - auto* inventoryComponent = user->GetComponent(); +void VeBricksampleServer::OnUse(Entity* self, Entity* user) { + auto* missionComponent = user->GetComponent(); + if (missionComponent != nullptr && missionComponent->GetMissionState(1183) == MissionState::MISSION_STATE_ACTIVE) { + const auto loot = self->GetVar(m_LootVariable); + auto* inventoryComponent = user->GetComponent(); - if (loot && inventoryComponent != nullptr && inventoryComponent->GetLotCount(loot) == 0) { - inventoryComponent->AddItem(loot, 1, eLootSourceType::LOOT_SOURCE_ACTIVITY); + if (loot && inventoryComponent != nullptr && inventoryComponent->GetLotCount(loot) == 0) { + inventoryComponent->AddItem(loot, 1, eLootSourceType::LOOT_SOURCE_ACTIVITY); - for (auto* brickEntity : EntityManager::Instance()->GetEntitiesInGroup("Bricks")) { - GameMessages::SendNotifyClientObject(brickEntity->GetObjectID(), u"Pickedup"); - } - } - } + for (auto* brickEntity : EntityManager::Instance()->GetEntitiesInGroup("Bricks")) { + GameMessages::SendNotifyClientObject(brickEntity->GetObjectID(), u"Pickedup"); + } + } + } } diff --git a/dScripts/VeBricksampleServer.h b/dScripts/VeBricksampleServer.h index c983a962..d9d37133 100644 --- a/dScripts/VeBricksampleServer.h +++ b/dScripts/VeBricksampleServer.h @@ -2,6 +2,6 @@ #include "CppScripts.h" class VeBricksampleServer : public CppScripts::Script { - void OnUse(Entity *self, Entity *user) override; - const std::u16string m_LootVariable = u"Loot"; + void OnUse(Entity* self, Entity* user) override; + const std::u16string m_LootVariable = u"Loot"; }; diff --git a/dScripts/VeEpsilonServer.cpp b/dScripts/VeEpsilonServer.cpp index b3e24cf4..cc6ecafe 100644 --- a/dScripts/VeEpsilonServer.cpp +++ b/dScripts/VeEpsilonServer.cpp @@ -3,24 +3,24 @@ #include "EntityManager.h" #include "GameMessages.h" -void VeEpsilonServer::OnMissionDialogueOK(Entity *self, Entity *target, int missionID, MissionState missionState) { - auto* character = target->GetCharacter(); - if (character == nullptr) - return; +void VeEpsilonServer::OnMissionDialogueOK(Entity* self, Entity* target, int missionID, MissionState missionState) { + auto* character = target->GetCharacter(); + if (character == nullptr) + return; - // Resets the player flags that track which consoles they've used - if ((missionID == m_ConsoleMissionID || missionID == m_ConsoleRepeatMissionID) - && (missionState == MissionState::MISSION_STATE_AVAILABLE || missionState == MissionState::MISSION_STATE_COMPLETE_AVAILABLE)) { + // Resets the player flags that track which consoles they've used + if ((missionID == m_ConsoleMissionID || missionID == m_ConsoleRepeatMissionID) + && (missionState == MissionState::MISSION_STATE_AVAILABLE || missionState == MissionState::MISSION_STATE_COMPLETE_AVAILABLE)) { - for (auto i = 0; i < 10; i++) { - character->SetPlayerFlag(m_ConsoleBaseFlag + i, false); - } - } + for (auto i = 0; i < 10; i++) { + character->SetPlayerFlag(m_ConsoleBaseFlag + i, false); + } + } - // Notify the client that all objects have updated - self->AddCallbackTimer(3.0f, [this]() { - for (const auto* console : EntityManager::Instance()->GetEntitiesInGroup(m_ConsoleGroup)) { - GameMessages::SendNotifyClientObject(console->GetObjectID(), u""); - } - }); + // Notify the client that all objects have updated + self->AddCallbackTimer(3.0f, [this]() { + for (const auto* console : EntityManager::Instance()->GetEntitiesInGroup(m_ConsoleGroup)) { + GameMessages::SendNotifyClientObject(console->GetObjectID(), u""); + } + }); } diff --git a/dScripts/VeEpsilonServer.h b/dScripts/VeEpsilonServer.h index d89f378f..d1236e96 100644 --- a/dScripts/VeEpsilonServer.h +++ b/dScripts/VeEpsilonServer.h @@ -2,9 +2,9 @@ #include "CppScripts.h" class VeEpsilonServer : public CppScripts::Script { - void OnMissionDialogueOK(Entity *self, Entity *target, int missionID, MissionState missionState) override; - const uint32_t m_ConsoleMissionID = 1220; - const uint32_t m_ConsoleRepeatMissionID = 1225; - const uint32_t m_ConsoleBaseFlag = 1010; - const std::string m_ConsoleGroup = "Consoles"; + void OnMissionDialogueOK(Entity* self, Entity* target, int missionID, MissionState missionState) override; + const uint32_t m_ConsoleMissionID = 1220; + const uint32_t m_ConsoleRepeatMissionID = 1225; + const uint32_t m_ConsoleBaseFlag = 1010; + const std::string m_ConsoleGroup = "Consoles"; }; diff --git a/dScripts/VeMech.cpp b/dScripts/VeMech.cpp index 87f2e88f..e1ec5674 100644 --- a/dScripts/VeMech.cpp +++ b/dScripts/VeMech.cpp @@ -1,6 +1,6 @@ #include "VeMech.h" -void VeMech::OnStartup(Entity *self) { - BaseEnemyMech::OnStartup(self); - qbTurretLOT = 8432; +void VeMech::OnStartup(Entity* self) { + BaseEnemyMech::OnStartup(self); + qbTurretLOT = 8432; } diff --git a/dScripts/VeMech.h b/dScripts/VeMech.h index 5fde6610..0f7c8836 100644 --- a/dScripts/VeMech.h +++ b/dScripts/VeMech.h @@ -3,5 +3,5 @@ class VeMech : public BaseEnemyMech { public: - void OnStartup(Entity *self) override; + void OnStartup(Entity* self) override; }; diff --git a/dScripts/VeMissionConsole.cpp b/dScripts/VeMissionConsole.cpp index f815ebdc..2a424c4d 100644 --- a/dScripts/VeMissionConsole.cpp +++ b/dScripts/VeMissionConsole.cpp @@ -3,23 +3,23 @@ #include "Character.h" #include "GameMessages.h" -void VeMissionConsole::OnUse(Entity *self, Entity *user) { - LootGenerator::Instance().DropActivityLoot(user, self, 12551); +void VeMissionConsole::OnUse(Entity* self, Entity* user) { + LootGenerator::Instance().DropActivityLoot(user, self, 12551); - auto* inventoryComponent = user->GetComponent(); - if (inventoryComponent != nullptr) { - inventoryComponent->AddItem(12547, 1, eLootSourceType::LOOT_SOURCE_ACTIVITY); // Add the panel required for pickup - } + auto* inventoryComponent = user->GetComponent(); + if (inventoryComponent != nullptr) { + inventoryComponent->AddItem(12547, 1, eLootSourceType::LOOT_SOURCE_ACTIVITY); // Add the panel required for pickup + } - // The flag to set is 101 - const auto flagNumber = self->GetVar(m_NumberVariable); - const auto flag = std::stoi("101" + GeneralUtils::UTF16ToWTF8(flagNumber)); + // The flag to set is 101 + const auto flagNumber = self->GetVar(m_NumberVariable); + const auto flag = std::stoi("101" + GeneralUtils::UTF16ToWTF8(flagNumber)); - auto* character = user->GetCharacter(); - if (character != nullptr) { - character->SetPlayerFlag(flag, true); - } + auto* character = user->GetCharacter(); + if (character != nullptr) { + character->SetPlayerFlag(flag, true); + } - GameMessages::SendNotifyClientObject(self->GetObjectID(), u""); - GameMessages::SendTerminateInteraction(user->GetObjectID(), FROM_INTERACTION, self->GetObjectID()); + GameMessages::SendNotifyClientObject(self->GetObjectID(), u""); + GameMessages::SendTerminateInteraction(user->GetObjectID(), FROM_INTERACTION, self->GetObjectID()); } diff --git a/dScripts/VeMissionConsole.h b/dScripts/VeMissionConsole.h index aecabdaa..8a12964f 100644 --- a/dScripts/VeMissionConsole.h +++ b/dScripts/VeMissionConsole.h @@ -3,7 +3,7 @@ class VeMissionConsole : public CppScripts::Script { public: - void OnUse(Entity *self, Entity *user) override; + void OnUse(Entity* self, Entity* user) override; private: - const std::u16string m_NumberVariable = u"num"; + const std::u16string m_NumberVariable = u"num"; }; diff --git a/dScripts/WaveBossApe.cpp b/dScripts/WaveBossApe.cpp index f4d8a132..7c26cec1 100644 --- a/dScripts/WaveBossApe.cpp +++ b/dScripts/WaveBossApe.cpp @@ -2,40 +2,40 @@ #include "BaseCombatAIComponent.h" #include "Entity.h" -void WaveBossApe::OnStartup(Entity *self) { - BaseWavesGenericEnemy::OnStartup(self); +void WaveBossApe::OnStartup(Entity* self) { + BaseWavesGenericEnemy::OnStartup(self); - self->SetVar(u"QuickbuildAnchorLOT", 12900); - self->SetVar(u"GroundPoundSkill", 725); - self->SetVar(u"reviveTime", 12); - self->SetVar(u"AnchorDamageDelayTime", 0.5f); - self->SetVar(u"spawnQBTime", 5.0f); + self->SetVar(u"QuickbuildAnchorLOT", 12900); + self->SetVar(u"GroundPoundSkill", 725); + self->SetVar(u"reviveTime", 12); + self->SetVar(u"AnchorDamageDelayTime", 0.5f); + self->SetVar(u"spawnQBTime", 5.0f); - auto* combatAIComponent = self->GetComponent(); - if (combatAIComponent != nullptr) { - combatAIComponent->SetDisabled(true); - combatAIComponent->SetStunImmune(true); - } + auto* combatAIComponent = self->GetComponent(); + if (combatAIComponent != nullptr) { + combatAIComponent->SetDisabled(true); + combatAIComponent->SetStunImmune(true); + } - self->AddToGroup("boss"); + self->AddToGroup("boss"); - BaseEnemyApe::OnStartup(self); + BaseEnemyApe::OnStartup(self); } -void WaveBossApe::OnDie(Entity *self, Entity *killer) { - BaseWavesGenericEnemy::OnDie(self, killer); - BaseEnemyApe::OnDie(self, killer); +void WaveBossApe::OnDie(Entity* self, Entity* killer) { + BaseWavesGenericEnemy::OnDie(self, killer); + BaseEnemyApe::OnDie(self, killer); } -void WaveBossApe::OnFireEventServerSide(Entity *self, Entity *sender, std::string args, int32_t param1, int32_t param2, - int32_t param3) { - if (args == "startAI") { - auto* combatAIComponent = self->GetComponent(); - if (combatAIComponent != nullptr) { - combatAIComponent->SetDisabled(false); - combatAIComponent->SetStunImmune(false); - } - } else { - BaseEnemyApe::OnFireEventServerSide(self, sender, args, param1, param2, param3); - } +void WaveBossApe::OnFireEventServerSide(Entity* self, Entity* sender, std::string args, int32_t param1, int32_t param2, + int32_t param3) { + if (args == "startAI") { + auto* combatAIComponent = self->GetComponent(); + if (combatAIComponent != nullptr) { + combatAIComponent->SetDisabled(false); + combatAIComponent->SetStunImmune(false); + } + } else { + BaseEnemyApe::OnFireEventServerSide(self, sender, args, param1, param2, param3); + } } diff --git a/dScripts/WaveBossApe.h b/dScripts/WaveBossApe.h index 321a24b2..57f07402 100644 --- a/dScripts/WaveBossApe.h +++ b/dScripts/WaveBossApe.h @@ -1,10 +1,10 @@ #include "BaseWavesGenericEnemy.h" #include "BaseEnemyApe.h" -class WaveBossApe : public BaseEnemyApe, public BaseWavesGenericEnemy { - uint32_t GetPoints() override { return 5000; } - void OnStartup(Entity* self) override; - void OnDie(Entity* self, Entity *killer) override; - void OnFireEventServerSide(Entity *self, Entity *sender, std::string args, int32_t param1, int32_t param2, - int32_t param3) override; +class WaveBossApe : public BaseEnemyApe, public BaseWavesGenericEnemy { + uint32_t GetPoints() override { return 5000; } + void OnStartup(Entity* self) override; + void OnDie(Entity* self, Entity* killer) override; + void OnFireEventServerSide(Entity* self, Entity* sender, std::string args, int32_t param1, int32_t param2, + int32_t param3) override; }; diff --git a/dScripts/WaveBossHammerling.cpp b/dScripts/WaveBossHammerling.cpp index 4775bf42..4fa78087 100644 --- a/dScripts/WaveBossHammerling.cpp +++ b/dScripts/WaveBossHammerling.cpp @@ -2,24 +2,24 @@ #include "BaseCombatAIComponent.h" #include "Entity.h" -void WaveBossHammerling::OnStartup(Entity *self) { - BaseWavesGenericEnemy::OnStartup(self); +void WaveBossHammerling::OnStartup(Entity* self) { + BaseWavesGenericEnemy::OnStartup(self); - auto* combatAIComponent = self->GetComponent(); - if (combatAIComponent != nullptr) { - combatAIComponent->SetDisabled(true); - combatAIComponent->SetStunImmune(true); - } + auto* combatAIComponent = self->GetComponent(); + if (combatAIComponent != nullptr) { + combatAIComponent->SetDisabled(true); + combatAIComponent->SetStunImmune(true); + } - self->AddToGroup("boss"); + self->AddToGroup("boss"); } -void WaveBossHammerling::OnFireEventServerSide(Entity *self, Entity *sender, std::string args, int32_t param1, - int32_t param2, int32_t param3) { - if (args == "startAI") { - auto* combatAIComponent = self->GetComponent(); - if (combatAIComponent != nullptr) { - combatAIComponent->SetDisabled(false); - } - } +void WaveBossHammerling::OnFireEventServerSide(Entity* self, Entity* sender, std::string args, int32_t param1, + int32_t param2, int32_t param3) { + if (args == "startAI") { + auto* combatAIComponent = self->GetComponent(); + if (combatAIComponent != nullptr) { + combatAIComponent->SetDisabled(false); + } + } } diff --git a/dScripts/WaveBossHammerling.h b/dScripts/WaveBossHammerling.h index 3ce22252..64da3647 100644 --- a/dScripts/WaveBossHammerling.h +++ b/dScripts/WaveBossHammerling.h @@ -2,8 +2,8 @@ #include "BaseWavesGenericEnemy.h" class WaveBossHammerling : public BaseWavesGenericEnemy { - void OnStartup(Entity* self) override; - uint32_t GetPoints() override { return 1000; } - void OnFireEventServerSide(Entity *self, Entity *sender, std::string args, int32_t param1, int32_t param2, - int32_t param3) override; + void OnStartup(Entity* self) override; + uint32_t GetPoints() override { return 1000; } + void OnFireEventServerSide(Entity* self, Entity* sender, std::string args, int32_t param1, int32_t param2, + int32_t param3) override; }; diff --git a/dScripts/WaveBossHorsemen.cpp b/dScripts/WaveBossHorsemen.cpp index c129d654..238544ab 100644 --- a/dScripts/WaveBossHorsemen.cpp +++ b/dScripts/WaveBossHorsemen.cpp @@ -2,25 +2,25 @@ #include "BaseCombatAIComponent.h" #include "Entity.h" -void WaveBossHorsemen::OnStartup(Entity *self) { - BaseWavesGenericEnemy::OnStartup(self); +void WaveBossHorsemen::OnStartup(Entity* self) { + BaseWavesGenericEnemy::OnStartup(self); - auto* combatAIComponent = self->GetComponent(); - if (combatAIComponent != nullptr) { - combatAIComponent->SetDisabled(true); - combatAIComponent->SetStunImmune(true); - } + auto* combatAIComponent = self->GetComponent(); + if (combatAIComponent != nullptr) { + combatAIComponent->SetDisabled(true); + combatAIComponent->SetStunImmune(true); + } - self->AddToGroup("boss"); + self->AddToGroup("boss"); } void -WaveBossHorsemen::OnFireEventServerSide(Entity *self, Entity *sender, std::string args, int32_t param1, int32_t param2, - int32_t param3) { - if (args == "startAI") { - auto* combatAIComponent = self->GetComponent(); - if (combatAIComponent != nullptr) { - combatAIComponent->SetDisabled(false); - } - } +WaveBossHorsemen::OnFireEventServerSide(Entity* self, Entity* sender, std::string args, int32_t param1, int32_t param2, + int32_t param3) { + if (args == "startAI") { + auto* combatAIComponent = self->GetComponent(); + if (combatAIComponent != nullptr) { + combatAIComponent->SetDisabled(false); + } + } } diff --git a/dScripts/WaveBossHorsemen.h b/dScripts/WaveBossHorsemen.h index f6160034..e490ffe4 100644 --- a/dScripts/WaveBossHorsemen.h +++ b/dScripts/WaveBossHorsemen.h @@ -2,8 +2,8 @@ #include "BaseWavesGenericEnemy.h" class WaveBossHorsemen : public BaseWavesGenericEnemy { - uint32_t GetPoints() override { return 5000; } - void OnStartup(Entity* self) override; - void OnFireEventServerSide(Entity *self, Entity *sender, std::string args, int32_t param1, int32_t param2, - int32_t param3) override; + uint32_t GetPoints() override { return 5000; } + void OnStartup(Entity* self) override; + void OnFireEventServerSide(Entity* self, Entity* sender, std::string args, int32_t param1, int32_t param2, + int32_t param3) override; }; diff --git a/dScripts/WaveBossSpiderling.cpp b/dScripts/WaveBossSpiderling.cpp index 5c8f8766..ec282ff4 100644 --- a/dScripts/WaveBossSpiderling.cpp +++ b/dScripts/WaveBossSpiderling.cpp @@ -2,25 +2,25 @@ #include "BaseCombatAIComponent.h" #include "Entity.h" -void WaveBossSpiderling::OnStartup(Entity *self) { - BaseWavesGenericEnemy::OnStartup(self); +void WaveBossSpiderling::OnStartup(Entity* self) { + BaseWavesGenericEnemy::OnStartup(self); - auto* combatAIComponent = self->GetComponent(); - if (combatAIComponent != nullptr) { - combatAIComponent->SetDisabled(true); - combatAIComponent->SetStunImmune(true); - } + auto* combatAIComponent = self->GetComponent(); + if (combatAIComponent != nullptr) { + combatAIComponent->SetDisabled(true); + combatAIComponent->SetStunImmune(true); + } - self->AddToGroup("boss"); + self->AddToGroup("boss"); } -void WaveBossSpiderling::OnFireEventServerSide(Entity *self, Entity *sender, std::string args, int32_t param1, - int32_t param2, int32_t param3) { - if (args == "startAI") { - auto* combatAIComponent = self->GetComponent(); - if (combatAIComponent != nullptr) { - combatAIComponent->SetDisabled(false); - combatAIComponent->SetStunImmune(false); - } - } +void WaveBossSpiderling::OnFireEventServerSide(Entity* self, Entity* sender, std::string args, int32_t param1, + int32_t param2, int32_t param3) { + if (args == "startAI") { + auto* combatAIComponent = self->GetComponent(); + if (combatAIComponent != nullptr) { + combatAIComponent->SetDisabled(false); + combatAIComponent->SetStunImmune(false); + } + } } diff --git a/dScripts/WaveBossSpiderling.h b/dScripts/WaveBossSpiderling.h index 23229efc..906b9d37 100644 --- a/dScripts/WaveBossSpiderling.h +++ b/dScripts/WaveBossSpiderling.h @@ -2,8 +2,8 @@ #include "BaseWavesGenericEnemy.h" class WaveBossSpiderling : public BaseWavesGenericEnemy { - uint32_t GetPoints() override { return 5000; } - void OnStartup(Entity* self) override; - void OnFireEventServerSide(Entity *self, Entity *sender, std::string args, int32_t param1, int32_t param2, - int32_t param3) override; + uint32_t GetPoints() override { return 5000; } + void OnStartup(Entity* self) override; + void OnFireEventServerSide(Entity* self, Entity* sender, std::string args, int32_t param1, int32_t param2, + int32_t param3) override; }; diff --git a/dScripts/WhFans.cpp b/dScripts/WhFans.cpp index f71383cf..44354127 100644 --- a/dScripts/WhFans.cpp +++ b/dScripts/WhFans.cpp @@ -41,8 +41,7 @@ void WhFans::ToggleFX(Entity* self, bool hit) { volumePhys->SetPhysicsEffectActive(false); EntityManager::Instance()->SerializeEntity(volume); } - } - else if (!self->GetVar(u"on") && self->GetVar(u"alive")) { + } else if (!self->GetVar(u"on") && self->GetVar(u"alive")) { GameMessages::SendPlayAnimation(self, u"fan-on"); self->SetVar(u"on", true); @@ -56,8 +55,8 @@ void WhFans::ToggleFX(Entity* self, bool hit) { } } -void WhFans::OnFireEventServerSide(Entity *self, Entity *sender, std::string args, int32_t param1, int32_t param2, - int32_t param3) { +void WhFans::OnFireEventServerSide(Entity* self, Entity* sender, std::string args, int32_t param1, int32_t param2, + int32_t param3) { if (args.length() == 0 || !self->GetVar(u"alive")) return; if ((args == "turnOn" && self->GetVar(u"on")) || (args == "turnOff" && !self->GetVar(u"on"))) return; diff --git a/dScripts/WhFans.h b/dScripts/WhFans.h index d41eed5b..0762395b 100644 --- a/dScripts/WhFans.h +++ b/dScripts/WhFans.h @@ -6,8 +6,8 @@ public: void OnStartup(Entity* self) override; void OnDie(Entity* self, Entity* killer) override; void OnFireEventServerSide( - Entity *self, - Entity *sender, + Entity* self, + Entity* sender, std::string args, int32_t param1, int32_t param2, diff --git a/dScripts/WildAmbients.cpp b/dScripts/WildAmbients.cpp index f6414ee8..16dfa043 100644 --- a/dScripts/WildAmbients.cpp +++ b/dScripts/WildAmbients.cpp @@ -1,7 +1,6 @@ #include "WildAmbients.h" #include "GameMessages.h" -void WildAmbients::OnUse(Entity* self, Entity* user) -{ +void WildAmbients::OnUse(Entity* self, Entity* user) { GameMessages::SendPlayAnimation(self, u"interact"); } diff --git a/dScripts/WishingWellServer.cpp b/dScripts/WishingWellServer.cpp index 09e953ac..8ac9e0b2 100644 --- a/dScripts/WishingWellServer.cpp +++ b/dScripts/WishingWellServer.cpp @@ -2,48 +2,43 @@ #include "ScriptedActivityComponent.h" #include "GameMessages.h" -void WishingWellServer::OnStartup(Entity* self) -{ +void WishingWellServer::OnStartup(Entity* self) { } -void WishingWellServer::OnUse(Entity* self, Entity* user) -{ - auto* scriptedActivity = self->GetComponent(); +void WishingWellServer::OnUse(Entity* self, Entity* user) { + auto* scriptedActivity = self->GetComponent(); - if (!scriptedActivity->TakeCost(user)) - { - return; - } + if (!scriptedActivity->TakeCost(user)) { + return; + } - const auto audio = self->GetVar(u"sound1"); + const auto audio = self->GetVar(u"sound1"); - if (!audio.empty()) - { - GameMessages::SendPlayNDAudioEmitter(self, user->GetSystemAddress(), audio); - } + if (!audio.empty()) { + GameMessages::SendPlayNDAudioEmitter(self, user->GetSystemAddress(), audio); + } - LootGenerator::Instance().DropActivityLoot( - user, - self, - static_cast(scriptedActivity->GetActivityID()), - GeneralUtils::GenerateRandomNumber(1, 1000) - ); + LootGenerator::Instance().DropActivityLoot( + user, + self, + static_cast(scriptedActivity->GetActivityID()), + GeneralUtils::GenerateRandomNumber(1, 1000) + ); - GameMessages::SendNotifyClientObject(self->GetObjectID(), u"StartCooldown", 0, 0, LWOOBJID_EMPTY, "", user->GetSystemAddress()); + GameMessages::SendNotifyClientObject(self->GetObjectID(), u"StartCooldown", 0, 0, LWOOBJID_EMPTY, "", user->GetSystemAddress()); - const auto userID = user->GetObjectID(); + const auto userID = user->GetObjectID(); - self->AddCallbackTimer(10, [self, userID] () { - auto* user = EntityManager::Instance()->GetEntity(userID); + self->AddCallbackTimer(10, [self, userID]() { + auto* user = EntityManager::Instance()->GetEntity(userID); - if (user == nullptr) return; - - GameMessages::SendNotifyClientObject(self->GetObjectID(), u"StopCooldown", 0, 0, LWOOBJID_EMPTY, "", user->GetSystemAddress()); - }); + if (user == nullptr) return; - GameMessages::SendTerminateInteraction(user->GetObjectID(), eTerminateType::FROM_INTERACTION, self->GetObjectID()); + GameMessages::SendNotifyClientObject(self->GetObjectID(), u"StopCooldown", 0, 0, LWOOBJID_EMPTY, "", user->GetSystemAddress()); + }); + + GameMessages::SendTerminateInteraction(user->GetObjectID(), eTerminateType::FROM_INTERACTION, self->GetObjectID()); } -void WishingWellServer::OnTimerDone(Entity* self, std::string timerName) -{ +void WishingWellServer::OnTimerDone(Entity* self, std::string timerName) { } diff --git a/dScripts/WishingWellServer.h b/dScripts/WishingWellServer.h index 3660c31e..856fa8a8 100644 --- a/dScripts/WishingWellServer.h +++ b/dScripts/WishingWellServer.h @@ -6,6 +6,6 @@ class WishingWellServer : public CppScripts::Script public: void OnStartup(Entity* self) override; void OnUse(Entity* self, Entity* user) override; - void OnTimerDone(Entity* self, std::string timerName) override; + void OnTimerDone(Entity* self, std::string timerName) override; }; diff --git a/dScripts/ZoneAgMedProperty.cpp b/dScripts/ZoneAgMedProperty.cpp index da8214b1..db1c4c4b 100644 --- a/dScripts/ZoneAgMedProperty.cpp +++ b/dScripts/ZoneAgMedProperty.cpp @@ -1,42 +1,42 @@ #include "ZoneAgMedProperty.h" #include "Entity.h" -void ZoneAgMedProperty::SetGameVariables(Entity *self) { +void ZoneAgMedProperty::SetGameVariables(Entity* self) { - self->SetVar(ClaimMarkerGroup, "ClaimMarker"); - self->SetVar(GeneratorGroup, "Generator"); - self->SetVar(GuardGroup, "Guard"); - self->SetVar(PropertyPlaqueGroup, "PropertyPlaque"); - self->SetVar(PropertyVendorGroup, "PropertyVendor"); - self->SetVar(SpotsGroup, "Spots"); - self->SetVar(MSCloudsGroup, "maelstrom"); - self->SetVar(EnemiesGroup, "Enemies"); - self->SetVar(FXManagerGroup, "FXObject"); - self->SetVar(ImagOrbGroup, "Orb"); - self->SetVar(GeneratorFXGroup, "GeneratorFX"); + self->SetVar(ClaimMarkerGroup, "ClaimMarker"); + self->SetVar(GeneratorGroup, "Generator"); + self->SetVar(GuardGroup, "Guard"); + self->SetVar(PropertyPlaqueGroup, "PropertyPlaque"); + self->SetVar(PropertyVendorGroup, "PropertyVendor"); + self->SetVar(SpotsGroup, "Spots"); + self->SetVar(MSCloudsGroup, "maelstrom"); + self->SetVar(EnemiesGroup, "Enemies"); + self->SetVar(FXManagerGroup, "FXObject"); + self->SetVar(ImagOrbGroup, "Orb"); + self->SetVar(GeneratorFXGroup, "GeneratorFX"); - self->SetVar>(EnemiesSpawner, { - "StrombieWander", "Strombies", "Mechs", "OtherEnemy" - }); - self->SetVar(ClaimMarkerSpawner, "ClaimMarker"); - self->SetVar(GeneratorSpawner, "Generator"); - self->SetVar(DamageFXSpawner, "MaelstromFX"); - self->SetVar(FXSpotsSpawner, "MaelstromSpots"); - self->SetVar(PropertyMGSpawner, "PropertyGuard"); - self->SetVar(ImageOrbSpawner, "Orb"); - self->SetVar(GeneratorFXSpawner, "GeneratorFX"); - self->SetVar(SmashablesSpawner, "Smashables"); - self->SetVar(FXManagerSpawner, "FXObject"); - self->SetVar(PropObjsSpawner, "BankObj"); - self->SetVar>(AmbientFXSpawner, { "BirdFX", "SunBeam" }); - self->SetVar>(BehaviorObjsSpawner, {}); + self->SetVar>(EnemiesSpawner, { + "StrombieWander", "Strombies", "Mechs", "OtherEnemy" + }); + self->SetVar(ClaimMarkerSpawner, "ClaimMarker"); + self->SetVar(GeneratorSpawner, "Generator"); + self->SetVar(DamageFXSpawner, "MaelstromFX"); + self->SetVar(FXSpotsSpawner, "MaelstromSpots"); + self->SetVar(PropertyMGSpawner, "PropertyGuard"); + self->SetVar(ImageOrbSpawner, "Orb"); + self->SetVar(GeneratorFXSpawner, "GeneratorFX"); + self->SetVar(SmashablesSpawner, "Smashables"); + self->SetVar(FXManagerSpawner, "FXObject"); + self->SetVar(PropObjsSpawner, "BankObj"); + self->SetVar>(AmbientFXSpawner, { "BirdFX", "SunBeam" }); + self->SetVar>(BehaviorObjsSpawner, {}); - self->SetVar(defeatedProperyFlag, 118); - self->SetVar(placedModelFlag, 119); - self->SetVar(guardMissionFlag, 1293); - self->SetVar(brickLinkMissionIDFlag, 1294); - self->SetVar(passwordFlag, "s3kratK1ttN"); - self->SetVar(generatorIdFlag, 10118); - self->SetVar(orbIDFlag, 10226); - self->SetVar(behaviorQBID, 10445); + self->SetVar(defeatedProperyFlag, 118); + self->SetVar(placedModelFlag, 119); + self->SetVar(guardMissionFlag, 1293); + self->SetVar(brickLinkMissionIDFlag, 1294); + self->SetVar(passwordFlag, "s3kratK1ttN"); + self->SetVar(generatorIdFlag, 10118); + self->SetVar(orbIDFlag, 10226); + self->SetVar(behaviorQBID, 10445); } diff --git a/dScripts/ZoneAgMedProperty.h b/dScripts/ZoneAgMedProperty.h index 83b365fd..95597699 100644 --- a/dScripts/ZoneAgMedProperty.h +++ b/dScripts/ZoneAgMedProperty.h @@ -2,5 +2,5 @@ #include "BasePropertyServer.h" class ZoneAgMedProperty : public BasePropertyServer { - void SetGameVariables(Entity *self) override; + void SetGameVariables(Entity* self) override; }; diff --git a/dScripts/ZoneAgProperty.cpp b/dScripts/ZoneAgProperty.cpp index 44650a35..db2bb78a 100644 --- a/dScripts/ZoneAgProperty.cpp +++ b/dScripts/ZoneAgProperty.cpp @@ -7,45 +7,45 @@ #include "RenderComponent.h" #include "MissionComponent.h" -void ZoneAgProperty::SetGameVariables(Entity *self) { - self->SetVar(GuardGroup, "Guard"); - self->SetVar(PropertyPlaqueGroup, "PropertyPlaque"); - self->SetVar(PropertyVendorGroup, "PropertyVendor"); - self->SetVar(PropertyBorderGroup, "PropertyBorder"); - self->SetVar(LandTargetGroup, "Land_Target"); - self->SetVar(SpiderScreamGroup, "Spider_Scream"); - self->SetVar>(ROFTargetsGroup, { "ROF_Targets_00", "ROF_Targets_01", "ROF_Targets_02", "ROF_Targets_03", "ROF_Targets_04" }); - self->SetVar(SpiderEggsGroup, "SpiderEggs"); - self->SetVar(RocksGroup, "Rocks"); - self->SetVar(EnemiesGroup, "SpiderBoss"); - self->SetVar>(ZoneVolumesGroup, { "Zone1Vol", "Zone2Vol", "Zone3Vol", "Zone4Vol", "Zone5Vol", "Zone6Vol", "Zone7Vol", "Zone8Vol", "AggroVol", "TeleVol" }); - self->SetVar(FXManagerGroup, "FXObject"); +void ZoneAgProperty::SetGameVariables(Entity* self) { + self->SetVar(GuardGroup, "Guard"); + self->SetVar(PropertyPlaqueGroup, "PropertyPlaque"); + self->SetVar(PropertyVendorGroup, "PropertyVendor"); + self->SetVar(PropertyBorderGroup, "PropertyBorder"); + self->SetVar(LandTargetGroup, "Land_Target"); + self->SetVar(SpiderScreamGroup, "Spider_Scream"); + self->SetVar>(ROFTargetsGroup, { "ROF_Targets_00", "ROF_Targets_01", "ROF_Targets_02", "ROF_Targets_03", "ROF_Targets_04" }); + self->SetVar(SpiderEggsGroup, "SpiderEggs"); + self->SetVar(RocksGroup, "Rocks"); + self->SetVar(EnemiesGroup, "SpiderBoss"); + self->SetVar>(ZoneVolumesGroup, { "Zone1Vol", "Zone2Vol", "Zone3Vol", "Zone4Vol", "Zone5Vol", "Zone6Vol", "Zone7Vol", "Zone8Vol", "AggroVol", "TeleVol" }); + self->SetVar(FXManagerGroup, "FXObject"); - self->SetVar(EnemiesSpawner, "SpiderBoss"); - self->SetVar>(BossSensorSpawner, { "Zone1Vol", "Zone2Vol", "Zone3Vol", "Zone4Vol", "Zone5Vol", "Zone6Vol", "Zone7Vol", "Zone8Vol", "RFS_Targets", "AggroVol", "TeleVol" }); - self->SetVar(LandTargetSpawner, "Land_Target"); - self->SetVar(SpiderScreamSpawner, "Spider_Scream"); - self->SetVar>(ROFTargetsSpawner,{ "ROF_Targets_00", "ROF_Targets_01", "ROF_Targets_02", "ROF_Targets_03", "ROF_Targets_04" }); - self->SetVar(PropertyMGSpawner, "PropertyGuard"); - self->SetVar(FXManagerSpawner, "FXObject"); - self->SetVar(PropObjsSpawner, "BankObj"); - self->SetVar(SpiderEggsSpawner, "SpiderEggs"); - self->SetVar(RocksSpawner, "Rocks"); - self->SetVar>(AmbientFXSpawner, { "BirdFX", "SunBeam" }); - self->SetVar>(SpiderRocketSpawner, { "SpiderRocket_Bot", "SpiderRocket_Mid", "SpiderRocket_Top" }); - self->SetVar(MailboxSpawner, "Mailbox"); - self->SetVar(LauncherSpawner, "Launcher"); - self->SetVar(InstancerSpawner, "Instancer"); + self->SetVar(EnemiesSpawner, "SpiderBoss"); + self->SetVar>(BossSensorSpawner, { "Zone1Vol", "Zone2Vol", "Zone3Vol", "Zone4Vol", "Zone5Vol", "Zone6Vol", "Zone7Vol", "Zone8Vol", "RFS_Targets", "AggroVol", "TeleVol" }); + self->SetVar(LandTargetSpawner, "Land_Target"); + self->SetVar(SpiderScreamSpawner, "Spider_Scream"); + self->SetVar>(ROFTargetsSpawner, { "ROF_Targets_00", "ROF_Targets_01", "ROF_Targets_02", "ROF_Targets_03", "ROF_Targets_04" }); + self->SetVar(PropertyMGSpawner, "PropertyGuard"); + self->SetVar(FXManagerSpawner, "FXObject"); + self->SetVar(PropObjsSpawner, "BankObj"); + self->SetVar(SpiderEggsSpawner, "SpiderEggs"); + self->SetVar(RocksSpawner, "Rocks"); + self->SetVar>(AmbientFXSpawner, { "BirdFX", "SunBeam" }); + self->SetVar>(SpiderRocketSpawner, { "SpiderRocket_Bot", "SpiderRocket_Mid", "SpiderRocket_Top" }); + self->SetVar(MailboxSpawner, "Mailbox"); + self->SetVar(LauncherSpawner, "Launcher"); + self->SetVar(InstancerSpawner, "Instancer"); - self->SetVar(defeatedProperyFlag, 71); - self->SetVar(placedModelFlag, 73); - self->SetVar(guardFirstMissionFlag, 891); - self->SetVar(guardMissionFlag, 320); - self->SetVar(brickLinkMissionIDFlag, 951); + self->SetVar(defeatedProperyFlag, 71); + self->SetVar(placedModelFlag, 73); + self->SetVar(guardFirstMissionFlag, 891); + self->SetVar(guardMissionFlag, 320); + self->SetVar(brickLinkMissionIDFlag, 951); } -void ZoneAgProperty::OnStartup(Entity *self) { - LoadProperty(self); +void ZoneAgProperty::OnStartup(Entity* self) { + LoadProperty(self); } void ZoneAgProperty::OnPlayerLoaded(Entity* self, Entity* player) { @@ -59,15 +59,15 @@ void ZoneAgProperty::OnPlayerLoaded(Entity* self, Entity* player) { self->SetVar(u"numberOfPlayers", numberOfPlayers + 1); } - if (dZoneManager::Instance()->GetZone()->GetZoneID().GetMapID() == 1102) { - GameMessages::SendPlay2DAmbientSound(player, GUIDMaelstrom); - GameMessages::SendNotifyClientObject(self->GetObjectID(), u"maelstromSkyOn", 0, 0, - LWOOBJID_EMPTY, "", player->GetSystemAddress()); - - self->SetNetworkVar(u"unclaimed", true); + if (dZoneManager::Instance()->GetZone()->GetZoneID().GetMapID() == 1102) { + GameMessages::SendPlay2DAmbientSound(player, GUIDMaelstrom); + GameMessages::SendNotifyClientObject(self->GetObjectID(), u"maelstromSkyOn", 0, 0, + LWOOBJID_EMPTY, "", player->GetSystemAddress()); - return; - } + self->SetNetworkVar(u"unclaimed", true); + + return; + } BasePlayerLoaded(self, player); } @@ -75,13 +75,13 @@ void ZoneAgProperty::OnPlayerLoaded(Entity* self, Entity* player) { void ZoneAgProperty::PropGuardCheck(Entity* self, Entity* player) { auto* missionComponent = player->GetComponent(); if (missionComponent == nullptr) - return; + return; const auto state = missionComponent->GetMissionState(self->GetVar(guardMissionFlag)); const auto firstState = missionComponent->GetMissionState(self->GetVar(guardFirstMissionFlag)); if (firstState < MissionState::MISSION_STATE_COMPLETE || (state != MissionState::MISSION_STATE_COMPLETE && state != MissionState::MISSION_STATE_COMPLETE_READY_TO_COMPLETE)) - ActivateSpawner(self->GetVar(PropertyMGSpawner)); + ActivateSpawner(self->GetVar(PropertyMGSpawner)); } void ZoneAgProperty::OnZoneLoadedInfo(Entity* self) { @@ -89,24 +89,24 @@ void ZoneAgProperty::OnZoneLoadedInfo(Entity* self) { } void ZoneAgProperty::LoadInstance(Entity* self) { - SetGameVariables(self); + SetGameVariables(self); - for (auto* spawner : dZoneManager::Instance()->GetSpawnersByName(self->GetVar(InstancerSpawner))) { - for (auto* spawnerNode : spawner->m_Info.nodes) { - spawnerNode->config.push_back( - new LDFData(u"custom_script_server", - R"(scripts\ai\GENERAL\L_INSTANCE_EXIT_TRANSFER_PLAYER_TO_LAST_NON_INSTANCE.lua)")); - spawnerNode->config.push_back(new LDFData(u"transferText", u"SPIDER_QUEEN_EXIT_QUESTION")); - } - } + for (auto* spawner : dZoneManager::Instance()->GetSpawnersByName(self->GetVar(InstancerSpawner))) { + for (auto* spawnerNode : spawner->m_Info.nodes) { + spawnerNode->config.push_back( + new LDFData(u"custom_script_server", + R"(scripts\ai\GENERAL\L_INSTANCE_EXIT_TRANSFER_PLAYER_TO_LAST_NON_INSTANCE.lua)")); + spawnerNode->config.push_back(new LDFData(u"transferText", u"SPIDER_QUEEN_EXIT_QUESTION")); + } + } - ActivateSpawner(self->GetVar(InstancerSpawner)); + ActivateSpawner(self->GetVar(InstancerSpawner)); } void ZoneAgProperty::LoadProperty(Entity* self) { - SetGameVariables(self); - ActivateSpawner(self->GetVar(LauncherSpawner)); - ActivateSpawner(self->GetVar(MailboxSpawner)); + SetGameVariables(self); + ActivateSpawner(self->GetVar(LauncherSpawner)); + ActivateSpawner(self->GetVar(MailboxSpawner)); } void ZoneAgProperty::ProcessGroupObjects(Entity* self, std::string group) { @@ -114,7 +114,7 @@ void ZoneAgProperty::ProcessGroupObjects(Entity* self, std::string group) { void ZoneAgProperty::SpawnSpots(Entity* self) { for (const auto& spot : self->GetVar>(ROFTargetsSpawner)) { - ActivateSpawner(spot); + ActivateSpawner(spot); } ActivateSpawner(self->GetVar(LandTargetSpawner)); @@ -122,18 +122,18 @@ void ZoneAgProperty::SpawnSpots(Entity* self) { void ZoneAgProperty::KillSpots(Entity* self) { for (const auto& spot : self->GetVar>(ROFTargetsSpawner)) { - DeactivateSpawner(spot); + DeactivateSpawner(spot); } for (const auto& groupName : self->GetVar>(ROFTargetsGroup)) { - for (auto* spot : EntityManager::Instance()->GetEntitiesInGroup(groupName)) { - spot->Kill(); - } + for (auto* spot : EntityManager::Instance()->GetEntitiesInGroup(groupName)) { + spot->Kill(); + } } DeactivateSpawner(self->GetVar(LandTargetSpawner)); for (auto* landTarget : EntityManager::Instance()->GetEntitiesInGroup(self->GetVar(LandTargetSpawner))) { - landTarget->Kill(); + landTarget->Kill(); } } @@ -145,13 +145,12 @@ void ZoneAgProperty::SpawnCrashedRocket(Entity* self) { void ZoneAgProperty::KillCrashedRocket(Entity* self) { for (const auto& rocket : self->GetVar>(SpiderRocketSpawner)) { - DeactivateSpawner(rocket); + DeactivateSpawner(rocket); DestroySpawner(rocket); } } -void ZoneAgProperty::StartMaelstrom(Entity* self, Entity* player) -{ +void ZoneAgProperty::StartMaelstrom(Entity* self, Entity* player) { ActivateSpawner(self->GetVar(EnemiesSpawner)); for (const auto& sensor : self->GetVar>(BossSensorSpawner)) { ActivateSpawner(sensor); @@ -163,18 +162,18 @@ void ZoneAgProperty::StartMaelstrom(Entity* self, Entity* player) ActivateSpawner(self->GetVar(RocksSpawner)); SpawnCrashedRocket(self); - + for (const auto& ambient : self->GetVar>(AmbientFXSpawner)) { - DeactivateSpawner(ambient); + DeactivateSpawner(ambient); DestroySpawner(ambient); ResetSpawner(ambient); } - StartTornadoFx(self); + StartTornadoFx(self); if (player != nullptr) { - GameMessages::SendNotifyClientObject(self->GetObjectID(), u"maelstromSkyOn", 0, 0, LWOOBJID_EMPTY, - "", player->GetSystemAddress()); + GameMessages::SendNotifyClientObject(self->GetObjectID(), u"maelstromSkyOn", 0, 0, LWOOBJID_EMPTY, + "", player->GetSystemAddress()); } } @@ -186,111 +185,111 @@ uint32_t ZoneAgProperty::RetrieveSpawnerId(Entity* self, const std::string& spaw return spawnerIDs[0]->m_Info.spawnerID; } -void ZoneAgProperty::OnTimerDone(Entity *self, std::string timerName) { - BaseTimerDone(self, timerName); +void ZoneAgProperty::OnTimerDone(Entity* self, std::string timerName) { + BaseTimerDone(self, timerName); } -void ZoneAgProperty::BaseTimerDone(Entity *self, const std::string &timerName) { - if (timerName == "GuardFlyAway") { - const auto zoneId = dZoneManager::Instance()->GetZone()->GetWorldID(); - if (zoneId != 1150) - return; +void ZoneAgProperty::BaseTimerDone(Entity* self, const std::string& timerName) { + if (timerName == "GuardFlyAway") { + const auto zoneId = dZoneManager::Instance()->GetZone()->GetWorldID(); + if (zoneId != 1150) + return; - const auto entities = EntityManager::Instance()->GetEntitiesInGroup(self->GetVar(GuardGroup)); - if (entities.empty()) - return; + const auto entities = EntityManager::Instance()->GetEntitiesInGroup(self->GetVar(GuardGroup)); + if (entities.empty()) + return; - auto* entity = entities[0]; + auto* entity = entities[0]; - GameMessages::SendNotifyClientObject(EntityManager::Instance()->GetZoneControlEntity()->GetObjectID(), u"GuardChat", 0, 0, entity->GetObjectID(), "", UNASSIGNED_SYSTEM_ADDRESS); - LoadProperty(self); + GameMessages::SendNotifyClientObject(EntityManager::Instance()->GetZoneControlEntity()->GetObjectID(), u"GuardChat", 0, 0, entity->GetObjectID(), "", UNASSIGNED_SYSTEM_ADDRESS); + LoadProperty(self); - self->AddTimer("KillGuard", 5); - } else if (timerName == "KillGuard") { - KillGuard(self); - } else if (timerName == "tornadoOff") { - for (auto* entity : EntityManager::Instance()->GetEntitiesInGroup(self->GetVar(FXManagerGroup))) { - auto* renderComponent = entity->GetComponent(); - if (renderComponent != nullptr) { - renderComponent->StopEffect("TornadoDebris", false); - renderComponent->StopEffect("TornadoVortex", false); - renderComponent->StopEffect("silhouette", false); - } - } + self->AddTimer("KillGuard", 5); + } else if (timerName == "KillGuard") { + KillGuard(self); + } else if (timerName == "tornadoOff") { + for (auto* entity : EntityManager::Instance()->GetEntitiesInGroup(self->GetVar(FXManagerGroup))) { + auto* renderComponent = entity->GetComponent(); + if (renderComponent != nullptr) { + renderComponent->StopEffect("TornadoDebris", false); + renderComponent->StopEffect("TornadoVortex", false); + renderComponent->StopEffect("silhouette", false); + } + } - self->AddTimer("ShowVendor", 1.2f); - self->AddTimer("ShowClearEffects", 2); - } else if (timerName == "ShowClearEffects") { - for (auto* entity : EntityManager::Instance()->GetEntitiesInGroup(self->GetVar(FXManagerGroup))) { - auto* renderComponent = entity->GetComponent(); - if (renderComponent != nullptr) { - renderComponent->PlayEffect(-1, u"beamOn", "beam"); - } - } + self->AddTimer("ShowVendor", 1.2f); + self->AddTimer("ShowClearEffects", 2); + } else if (timerName == "ShowClearEffects") { + for (auto* entity : EntityManager::Instance()->GetEntitiesInGroup(self->GetVar(FXManagerGroup))) { + auto* renderComponent = entity->GetComponent(); + if (renderComponent != nullptr) { + renderComponent->PlayEffect(-1, u"beamOn", "beam"); + } + } - self->AddTimer("killSpider", 2); - self->AddTimer("turnSkyOff", 1.5f); - self->AddTimer("killFXObject", 8); - } else if (timerName == "turnSkyOff") { - GameMessages::SendNotifyClientObject(self->GetObjectID(), u"SkyOff", 0, 0, LWOOBJID_EMPTY, - "", UNASSIGNED_SYSTEM_ADDRESS); - } else if (timerName == "killSpider") { - for (auto* entity : EntityManager::Instance()->GetEntitiesInGroup(self->GetVar(EnemiesGroup))) { - entity->Kill(); - } + self->AddTimer("killSpider", 2); + self->AddTimer("turnSkyOff", 1.5f); + self->AddTimer("killFXObject", 8); + } else if (timerName == "turnSkyOff") { + GameMessages::SendNotifyClientObject(self->GetObjectID(), u"SkyOff", 0, 0, LWOOBJID_EMPTY, + "", UNASSIGNED_SYSTEM_ADDRESS); + } else if (timerName == "killSpider") { + for (auto* entity : EntityManager::Instance()->GetEntitiesInGroup(self->GetVar(EnemiesGroup))) { + entity->Kill(); + } - for (const auto& sensor : self->GetVar>(BossSensorSpawner)) { - DeactivateSpawner(sensor); - DestroySpawner(sensor); - } + for (const auto& sensor : self->GetVar>(BossSensorSpawner)) { + DeactivateSpawner(sensor); + DestroySpawner(sensor); + } - DeactivateSpawner(self->GetVar(SpiderEggsSpawner)); - DestroySpawner(self->GetVar(SpiderEggsSpawner)); + DeactivateSpawner(self->GetVar(SpiderEggsSpawner)); + DestroySpawner(self->GetVar(SpiderEggsSpawner)); - DeactivateSpawner(self->GetVar(RocksSpawner)); - DestroySpawner(self->GetVar(RocksSpawner)); + DeactivateSpawner(self->GetVar(RocksSpawner)); + DestroySpawner(self->GetVar(RocksSpawner)); - KillSpots(self); - KillCrashedRocket(self); + KillSpots(self); + KillCrashedRocket(self); - DeactivateSpawner(self->GetVar(SpiderScreamSpawner)); - DestroySpawner(self->GetVar(SpiderScreamSpawner)); + DeactivateSpawner(self->GetVar(SpiderScreamSpawner)); + DestroySpawner(self->GetVar(SpiderScreamSpawner)); - for (auto* player : EntityManager::Instance()->GetEntitiesByComponent(COMPONENT_TYPE_CHARACTER)) { - GameMessages::SendStop2DAmbientSound(player, true, GUIDMaelstrom); - GameMessages::SendPlay2DAmbientSound(player, GUIDPeaceful); - } - } else if (timerName == "ShowVendor") { - GameMessages::SendNotifyClientObject(self->GetObjectID(), u"vendorOn", 0, 0, LWOOBJID_EMPTY, "", UNASSIGNED_SYSTEM_ADDRESS); - for (const auto& ambient : self->GetVar>(AmbientFXSpawner)) { - ActivateSpawner(ambient); - } - } else if (timerName == "BoundsVisOn") { - GameMessages::SendNotifyClientObject(self->GetObjectID(), u"boundsAnim", 0, 0, - LWOOBJID_EMPTY, "", UNASSIGNED_SYSTEM_ADDRESS); - } else if (timerName == "runPlayerLoadedAgain") { - CheckForOwner(self); - } else if (timerName == "pollTornadoFX") { - StartTornadoFx(self); - } else if (timerName == "killFXObject") { - for (auto* entity : EntityManager::Instance()->GetEntitiesInGroup(self->GetVar(FXManagerGroup))) { - auto* renderComponent = entity->GetComponent(); - if (renderComponent != nullptr) { - renderComponent->StopEffect("beam"); - } - } + for (auto* player : EntityManager::Instance()->GetEntitiesByComponent(COMPONENT_TYPE_CHARACTER)) { + GameMessages::SendStop2DAmbientSound(player, true, GUIDMaelstrom); + GameMessages::SendPlay2DAmbientSound(player, GUIDPeaceful); + } + } else if (timerName == "ShowVendor") { + GameMessages::SendNotifyClientObject(self->GetObjectID(), u"vendorOn", 0, 0, LWOOBJID_EMPTY, "", UNASSIGNED_SYSTEM_ADDRESS); + for (const auto& ambient : self->GetVar>(AmbientFXSpawner)) { + ActivateSpawner(ambient); + } + } else if (timerName == "BoundsVisOn") { + GameMessages::SendNotifyClientObject(self->GetObjectID(), u"boundsAnim", 0, 0, + LWOOBJID_EMPTY, "", UNASSIGNED_SYSTEM_ADDRESS); + } else if (timerName == "runPlayerLoadedAgain") { + CheckForOwner(self); + } else if (timerName == "pollTornadoFX") { + StartTornadoFx(self); + } else if (timerName == "killFXObject") { + for (auto* entity : EntityManager::Instance()->GetEntitiesInGroup(self->GetVar(FXManagerGroup))) { + auto* renderComponent = entity->GetComponent(); + if (renderComponent != nullptr) { + renderComponent->StopEffect("beam"); + } + } - DestroySpawner(self->GetVar(FXManagerSpawner)); + DestroySpawner(self->GetVar(FXManagerSpawner)); - self->SetVar(u"FXObjectGone", true); - } else if (timerName == "ProcessGroupObj") { - // TODO - } + self->SetVar(u"FXObjectGone", true); + } else if (timerName == "ProcessGroupObj") { + // TODO + } } void ZoneAgProperty::OnZonePropertyRented(Entity* self, Entity* player) { BaseZonePropertyRented(self, player); - + auto* character = player->GetCharacter(); if (character == nullptr) return; @@ -303,7 +302,7 @@ void ZoneAgProperty::OnZonePropertyModelPlaced(Entity* self, Entity* player) { auto* missionComponent = player->GetComponent(); if (!character->GetPlayerFlag(101)) { - BaseZonePropertyModelPlaced(self, player); + BaseZonePropertyModelPlaced(self, player); character->SetPlayerFlag(101, true); if (missionComponent->GetMissionState(871) == MissionState::MISSION_STATE_ACTIVE) { self->SetNetworkVar(u"Tooltip", u"AnotherModel"); @@ -374,52 +373,52 @@ void ZoneAgProperty::OnZonePropertyEditEnd(Entity* self) { } void ZoneAgProperty::OnPlayerExit(Entity* self) { - // TODO: Destroy stuff + // TODO: Destroy stuff } void ZoneAgProperty::RemovePlayerRef(Entity* self) { - // TODO: Destroy stuff + // TODO: Destroy stuff } -void ZoneAgProperty::BaseOnFireEventServerSide(Entity *self, Entity *sender, std::string args) { - if (args == "propertyRented") { - const auto playerId = self->GetVar(u"playerID"); - auto* player = EntityManager::Instance()->GetEntity(playerId); - if (player == nullptr) - return; +void ZoneAgProperty::BaseOnFireEventServerSide(Entity* self, Entity* sender, std::string args) { + if (args == "propertyRented") { + const auto playerId = self->GetVar(u"playerID"); + auto* player = EntityManager::Instance()->GetEntity(playerId); + if (player == nullptr) + return; - OnZonePropertyRented(self, player); - } else if (args == "RetrieveZoneData") { - self->SetVar(u"SpiderBossID", sender->GetObjectID()); - sender->SetVar(u"SpiderEggNetworkID", RetrieveSpawnerId(self, self->GetVar(SpiderEggsSpawner))); + OnZonePropertyRented(self, player); + } else if (args == "RetrieveZoneData") { + self->SetVar(u"SpiderBossID", sender->GetObjectID()); + sender->SetVar(u"SpiderEggNetworkID", RetrieveSpawnerId(self, self->GetVar(SpiderEggsSpawner))); - std::vector table; + std::vector table; - for (const auto& target : self->GetVar>(ROFTargetsSpawner)) { - table.push_back(RetrieveSpawnerId(self, target)); - } + for (const auto& target : self->GetVar>(ROFTargetsSpawner)) { + table.push_back(RetrieveSpawnerId(self, target)); + } - ROFTargetGroupIdTable = table; + ROFTargetGroupIdTable = table; - ProcessGroupObjects(self, self->GetVar(LandTargetGroup)); - ProcessGroupObjects(self, self->GetVar(SpiderScreamGroup)); -// ProcessGroupObjects(self, groups.ZoneVolumes); - } else if (args == "CheckForPropertyOwner") { - sender->SetNetworkVar(u"PropertyOwnerID", std::to_string(self->GetVar(u"PropertyOwner"))); - } else if (args == "ClearProperty") { - const auto playerId = self->GetVar(u"playerID"); - auto* player = EntityManager::Instance()->GetEntity(playerId); - if (player == nullptr) - return; + ProcessGroupObjects(self, self->GetVar(LandTargetGroup)); + ProcessGroupObjects(self, self->GetVar(SpiderScreamGroup)); + // ProcessGroupObjects(self, groups.ZoneVolumes); + } else if (args == "CheckForPropertyOwner") { + sender->SetNetworkVar(u"PropertyOwnerID", std::to_string(self->GetVar(u"PropertyOwner"))); + } else if (args == "ClearProperty") { + const auto playerId = self->GetVar(u"playerID"); + auto* player = EntityManager::Instance()->GetEntity(playerId); + if (player == nullptr) + return; - player->GetCharacter()->SetPlayerFlag(self->GetVar(defeatedProperyFlag), true); - GameMessages::SendNotifyClientObject(self->GetObjectID(), u"PlayCinematic", 0, 0, - LWOOBJID_EMPTY,destroyedCinematic, UNASSIGNED_SYSTEM_ADDRESS); + player->GetCharacter()->SetPlayerFlag(self->GetVar(defeatedProperyFlag), true); + GameMessages::SendNotifyClientObject(self->GetObjectID(), u"PlayCinematic", 0, 0, + LWOOBJID_EMPTY, destroyedCinematic, UNASSIGNED_SYSTEM_ADDRESS); - self->AddTimer("tornadoOff", 0.5f); - } + self->AddTimer("tornadoOff", 0.5f); + } } -void ZoneAgProperty::NotifyDie(Entity *self) { - // TODO +void ZoneAgProperty::NotifyDie(Entity* self) { + // TODO } diff --git a/dScripts/ZoneAgProperty.h b/dScripts/ZoneAgProperty.h index 4044be57..b1720783 100644 --- a/dScripts/ZoneAgProperty.h +++ b/dScripts/ZoneAgProperty.h @@ -3,26 +3,28 @@ class ZoneAgProperty : public BasePropertyServer { public: - void SetGameVariables(Entity *self) override; - void OnStartup(Entity* self) override; + void SetGameVariables(Entity* self) override; + void OnStartup(Entity* self) override; void OnPlayerLoaded(Entity* self, Entity* player) override; void OnZoneLoadedInfo(Entity* self); - void OnZonePropertyRented(Entity* self, Entity* player) override; - void OnZonePropertyModelPlaced(Entity* self, Entity* player) override; - void OnZonePropertyModelPickedUp(Entity* self, Entity* player) override; - void OnZonePropertyModelRemoved(Entity* self, Entity* player) override; - void OnZonePropertyModelRemovedWhileEquipped(Entity* self, Entity* player) override; - void OnZonePropertyModelRotated(Entity* self, Entity* player) override; - void OnZonePropertyEditBegin(Entity* self) override; - void OnZonePropertyModelEquipped(Entity* self) override; - void OnZonePropertyEditEnd(Entity* self) override; - void OnPlayerExit(Entity* self); - void OnFireEventServerSide(Entity *self, Entity *sender, std::string args, int32_t param1, int32_t param2, - int32_t param3) override { BaseOnFireEventServerSide(self, sender, args); } - virtual void BaseOnFireEventServerSide(Entity* self, Entity* sender, std::string args); - void OnTimerDone(Entity* self, std::string timerName) override; + void OnZonePropertyRented(Entity* self, Entity* player) override; + void OnZonePropertyModelPlaced(Entity* self, Entity* player) override; + void OnZonePropertyModelPickedUp(Entity* self, Entity* player) override; + void OnZonePropertyModelRemoved(Entity* self, Entity* player) override; + void OnZonePropertyModelRemovedWhileEquipped(Entity* self, Entity* player) override; + void OnZonePropertyModelRotated(Entity* self, Entity* player) override; + void OnZonePropertyEditBegin(Entity* self) override; + void OnZonePropertyModelEquipped(Entity* self) override; + void OnZonePropertyEditEnd(Entity* self) override; + void OnPlayerExit(Entity* self); + void OnFireEventServerSide(Entity* self, Entity* sender, std::string args, int32_t param1, int32_t param2, + int32_t param3) override { + BaseOnFireEventServerSide(self, sender, args); + } + virtual void BaseOnFireEventServerSide(Entity* self, Entity* sender, std::string args); + void OnTimerDone(Entity* self, std::string timerName) override; - void BaseTimerDone(Entity *self, const std::string &timerName) override; + void BaseTimerDone(Entity* self, const std::string& timerName) override; void PropGuardCheck(Entity* self, Entity* player) override; void LoadInstance(Entity* self); @@ -42,23 +44,23 @@ public: void RemovePlayerRef(Entity* self); protected: std::string destroyedCinematic = "DestroyMaelstrom"; - std::vector ROFTargetGroupIdTable {}; - std::u16string LandTargetGroup = u"LandTargetGroup"; - std::u16string SpiderScreamGroup = u"SpiderScreamGroup"; - std::u16string ROFTargetsGroup = u"ROFTargetsGroup"; - std::u16string SpiderEggsGroup = u"SpiderEggsGroup"; - std::u16string RocksGroup = u"RocksGroup"; - std::u16string ZoneVolumesGroup = u"ZoneVolumesGroup"; + std::vector ROFTargetGroupIdTable{}; + std::u16string LandTargetGroup = u"LandTargetGroup"; + std::u16string SpiderScreamGroup = u"SpiderScreamGroup"; + std::u16string ROFTargetsGroup = u"ROFTargetsGroup"; + std::u16string SpiderEggsGroup = u"SpiderEggsGroup"; + std::u16string RocksGroup = u"RocksGroup"; + std::u16string ZoneVolumesGroup = u"ZoneVolumesGroup"; - std::u16string EnemiesSpawner = u"EnemiesSpawner"; - std::u16string BossSensorSpawner = u"BossSensorSpawner"; - std::u16string LandTargetSpawner = u"LandTargetSpawner"; - std::u16string SpiderScreamSpawner = u"SpiderScreamSpawner"; - std::u16string ROFTargetsSpawner = u"ROFTargetsSpawner"; - std::u16string SpiderEggsSpawner = u"SpiderEggsSpawner"; - std::u16string RocksSpawner = u"RocksSpawner"; - std::u16string SpiderRocketSpawner = u"SpiderRocketSpawner"; - std::u16string MailboxSpawner = u"MailboxSpawner"; - std::u16string LauncherSpawner = u"LauncherSpawner"; - std::u16string InstancerSpawner = u"InstancerSpawner"; + std::u16string EnemiesSpawner = u"EnemiesSpawner"; + std::u16string BossSensorSpawner = u"BossSensorSpawner"; + std::u16string LandTargetSpawner = u"LandTargetSpawner"; + std::u16string SpiderScreamSpawner = u"SpiderScreamSpawner"; + std::u16string ROFTargetsSpawner = u"ROFTargetsSpawner"; + std::u16string SpiderEggsSpawner = u"SpiderEggsSpawner"; + std::u16string RocksSpawner = u"RocksSpawner"; + std::u16string SpiderRocketSpawner = u"SpiderRocketSpawner"; + std::u16string MailboxSpawner = u"MailboxSpawner"; + std::u16string LauncherSpawner = u"LauncherSpawner"; + std::u16string InstancerSpawner = u"InstancerSpawner"; }; diff --git a/dScripts/ZoneAgSpiderQueen.cpp b/dScripts/ZoneAgSpiderQueen.cpp index 27c11aa7..ea517448 100644 --- a/dScripts/ZoneAgSpiderQueen.cpp +++ b/dScripts/ZoneAgSpiderQueen.cpp @@ -4,80 +4,80 @@ #include "ZoneAgProperty.h" #include "DestroyableComponent.h" -void ZoneAgSpiderQueen::SetGameVariables(Entity *self) { - ZoneAgProperty::SetGameVariables(self); +void ZoneAgSpiderQueen::SetGameVariables(Entity* self) { + ZoneAgProperty::SetGameVariables(self); - // Disable property flags - self->SetVar(defeatedProperyFlag, 0); - self->SetVar(placedModelFlag, 0); - self->SetVar(guardFirstMissionFlag, 0); - self->SetVar(guardMissionFlag, 0); - self->SetVar(brickLinkMissionIDFlag, 0); + // Disable property flags + self->SetVar(defeatedProperyFlag, 0); + self->SetVar(placedModelFlag, 0); + self->SetVar(guardFirstMissionFlag, 0); + self->SetVar(guardMissionFlag, 0); + self->SetVar(brickLinkMissionIDFlag, 0); } -void ZoneAgSpiderQueen::OnStartup(Entity *self) { - LoadInstance(self); +void ZoneAgSpiderQueen::OnStartup(Entity* self) { + LoadInstance(self); - SpawnSpots(self); - StartMaelstrom(self, nullptr); + SpawnSpots(self); + StartMaelstrom(self, nullptr); } -void ZoneAgSpiderQueen::BasePlayerLoaded(Entity *self, Entity *player) { - ActivityManager::UpdatePlayer(self, player->GetObjectID()); - ActivityManager::TakeActivityCost(self, player->GetObjectID()); +void ZoneAgSpiderQueen::BasePlayerLoaded(Entity* self, Entity* player) { + ActivityManager::UpdatePlayer(self, player->GetObjectID()); + ActivityManager::TakeActivityCost(self, player->GetObjectID()); - // Make sure the player has full stats when they join - auto* playerDestroyableComponent = player->GetComponent(); - if (playerDestroyableComponent != nullptr) { - playerDestroyableComponent->SetImagination(playerDestroyableComponent->GetMaxImagination()); - playerDestroyableComponent->SetArmor(playerDestroyableComponent->GetMaxArmor()); - playerDestroyableComponent->SetHealth(playerDestroyableComponent->GetMaxHealth()); - } + // Make sure the player has full stats when they join + auto* playerDestroyableComponent = player->GetComponent(); + if (playerDestroyableComponent != nullptr) { + playerDestroyableComponent->SetImagination(playerDestroyableComponent->GetMaxImagination()); + playerDestroyableComponent->SetArmor(playerDestroyableComponent->GetMaxArmor()); + playerDestroyableComponent->SetHealth(playerDestroyableComponent->GetMaxHealth()); + } - self->SetNetworkVar(u"unclaimed", true); - GameMessages::SendNotifyClientObject(self->GetObjectID(), u"maelstromSkyOn", 0, 0, LWOOBJID_EMPTY, - "", player->GetSystemAddress()); + self->SetNetworkVar(u"unclaimed", true); + GameMessages::SendNotifyClientObject(self->GetObjectID(), u"maelstromSkyOn", 0, 0, LWOOBJID_EMPTY, + "", player->GetSystemAddress()); } void -ZoneAgSpiderQueen::OnFireEventServerSide(Entity *self, Entity *sender, std::string args, int32_t param1, int32_t param2, - int32_t param3) { - if (args == "ClearProperty") { - GameMessages::SendNotifyClientObject(self->GetObjectID(), u"PlayCinematic", 0, 0, - LWOOBJID_EMPTY, destroyedCinematic, UNASSIGNED_SYSTEM_ADDRESS); - self->AddTimer("tornadoOff", 0.5f); - } else { - ZoneAgProperty::BaseOnFireEventServerSide(self, sender, args); - } +ZoneAgSpiderQueen::OnFireEventServerSide(Entity* self, Entity* sender, std::string args, int32_t param1, int32_t param2, + int32_t param3) { + if (args == "ClearProperty") { + GameMessages::SendNotifyClientObject(self->GetObjectID(), u"PlayCinematic", 0, 0, + LWOOBJID_EMPTY, destroyedCinematic, UNASSIGNED_SYSTEM_ADDRESS); + self->AddTimer("tornadoOff", 0.5f); + } else { + ZoneAgProperty::BaseOnFireEventServerSide(self, sender, args); + } } -void ZoneAgSpiderQueen::OnPlayerExit(Entity *self, Entity *player) { - UpdatePlayer(self, player->GetObjectID(), true); +void ZoneAgSpiderQueen::OnPlayerExit(Entity* self, Entity* player) { + UpdatePlayer(self, player->GetObjectID(), true); } -void ZoneAgSpiderQueen::OnTimerDone(Entity *self, std::string timerName) { +void ZoneAgSpiderQueen::OnTimerDone(Entity* self, std::string timerName) { - // Disable some stuff from the regular property - if (timerName == "BoundsVisOn" || timerName == "GuardFlyAway" || timerName == "ShowVendor") - return; + // Disable some stuff from the regular property + if (timerName == "BoundsVisOn" || timerName == "GuardFlyAway" || timerName == "ShowVendor") + return; - if (timerName == "killSpider") { - auto spawnTargets = EntityManager::Instance()->GetEntitiesInGroup(self->GetVar(LandTargetGroup)); - for (auto* spawnTarget : spawnTargets) { - EntityInfo info{}; + if (timerName == "killSpider") { + auto spawnTargets = EntityManager::Instance()->GetEntitiesInGroup(self->GetVar(LandTargetGroup)); + for (auto* spawnTarget : spawnTargets) { + EntityInfo info{}; - info.spawnerID = spawnTarget->GetObjectID(); - info.pos = spawnTarget->GetPosition(); - info.rot = spawnTarget->GetRotation(); - info.lot = chestObject; - info.settings = { - new LDFData(u"parent_tag", self->GetObjectID()) - }; + info.spawnerID = spawnTarget->GetObjectID(); + info.pos = spawnTarget->GetPosition(); + info.rot = spawnTarget->GetRotation(); + info.lot = chestObject; + info.settings = { + new LDFData(u"parent_tag", self->GetObjectID()) + }; - auto* chest = EntityManager::Instance()->CreateEntity(info); - EntityManager::Instance()->ConstructEntity(chest); - } - } + auto* chest = EntityManager::Instance()->CreateEntity(info); + EntityManager::Instance()->ConstructEntity(chest); + } + } - ZoneAgProperty::BaseTimerDone(self, timerName); -} \ No newline at end of file + ZoneAgProperty::BaseTimerDone(self, timerName); +} diff --git a/dScripts/ZoneAgSpiderQueen.h b/dScripts/ZoneAgSpiderQueen.h index 5536f47a..d7ab1d71 100644 --- a/dScripts/ZoneAgSpiderQueen.h +++ b/dScripts/ZoneAgSpiderQueen.h @@ -4,14 +4,14 @@ class ZoneAgSpiderQueen : ZoneAgProperty, ActivityManager { public: - void OnStartup(Entity* self) override; - void OnFireEventServerSide(Entity *self, Entity *sender, std::string args, int32_t param1, int32_t param2, - int32_t param3) override; - void OnTimerDone(Entity *self, std::string timerName) override; - void OnPlayerExit(Entity* self, Entity* player) override; - void BasePlayerLoaded(Entity* self, Entity* player) override; - void SetGameVariables(Entity *self) override; + void OnStartup(Entity* self) override; + void OnFireEventServerSide(Entity* self, Entity* sender, std::string args, int32_t param1, int32_t param2, + int32_t param3) override; + void OnTimerDone(Entity* self, std::string timerName) override; + void OnPlayerExit(Entity* self, Entity* player) override; + void BasePlayerLoaded(Entity* self, Entity* player) override; + void SetGameVariables(Entity* self) override; protected: - std::string destroyedCinematic = "DesMaelstromInstance"; - const LOT chestObject = 16318; + std::string destroyedCinematic = "DesMaelstromInstance"; + const LOT chestObject = 16318; }; diff --git a/dScripts/ZoneAgSurvival.cpp b/dScripts/ZoneAgSurvival.cpp index 5be11f99..79f54c06 100644 --- a/dScripts/ZoneAgSurvival.cpp +++ b/dScripts/ZoneAgSurvival.cpp @@ -1,127 +1,127 @@ #include "ZoneAgSurvival.h" Constants ZoneAgSurvival::GetConstants() { - return Constants { - 60, - 2, - 7, - 5, - 10, - 5, - 15, - 10, - 0, - true, - std::vector {8, 13, 18, 23, 28, 32}, - std::vector {2, 10, 15, 20, 25, 30} - }; + return Constants{ + 60, + 2, + 7, + 5, + 10, + 5, + 15, + 10, + 0, + true, + std::vector {8, 13, 18, 23, 28, 32}, + std::vector {2, 10, 15, 20, 25, 30} + }; } MobSets ZoneAgSurvival::GetMobSets() { - return MobSets { - std::map> { - {"MobA", {6351, 8088, 8089} }, - {"MobB", {6668, 8090, 8091} }, - {"MobC", {6454, 8096, 8097} }, - }, - std::map>>> { - { BaseMobSet, { - { {3, 0, 0}, }, - { {2, 1, 0}, }, - { {4, 1, 0}, }, - { {1, 2, 0}, }, - { {0, 1, 1}, }, - { {0, 2, 2}, } - }}, - { RandMobSet, { - { {4, 0, 0}, {4, 0, 0}, {4, 0, 0}, {4, 0, 0}, {3, 1, 0} }, - { {4, 1, 0}, {4, 1, 0}, {4, 1, 0}, {4, 1, 0}, {2, 1, 1} }, - { {1, 2, 0}, {1, 2, 0}, {1, 2, 0}, {1, 2, 0}, {0, 1, 1} }, - { {1, 2, 1}, {1, 2, 1}, {1, 2, 1}, {0, 2, 1}, {0, 2, 2} }, - { {0, 1, 2}, {0, 1, 2}, {0, 1, 2}, {0, 1, 3}, {0, 1, 3} }, - { {0, 2, 3}, {0, 2, 3}, {0, 2, 3}, {0, 2, 3}, {0, 2, 3} }, - }} - } - }; + return MobSets{ + std::map> { + {"MobA", {6351, 8088, 8089} }, + {"MobB", {6668, 8090, 8091} }, + {"MobC", {6454, 8096, 8097} }, + }, + std::map>>> { + { BaseMobSet, { + { {3, 0, 0}, }, + { {2, 1, 0}, }, + { {4, 1, 0}, }, + { {1, 2, 0}, }, + { {0, 1, 1}, }, + { {0, 2, 2}, } + }}, + { RandMobSet, { + { {4, 0, 0}, {4, 0, 0}, {4, 0, 0}, {4, 0, 0}, {3, 1, 0} }, + { {4, 1, 0}, {4, 1, 0}, {4, 1, 0}, {4, 1, 0}, {2, 1, 1} }, + { {1, 2, 0}, {1, 2, 0}, {1, 2, 0}, {1, 2, 0}, {0, 1, 1} }, + { {1, 2, 1}, {1, 2, 1}, {1, 2, 1}, {0, 2, 1}, {0, 2, 2} }, + { {0, 1, 2}, {0, 1, 2}, {0, 1, 2}, {0, 1, 3}, {0, 1, 3} }, + { {0, 2, 3}, {0, 2, 3}, {0, 2, 3}, {0, 2, 3}, {0, 2, 3} }, + }} + } + }; } SpawnerNetworks ZoneAgSurvival::GetSpawnerNetworks() { - return SpawnerNetworks { - SpawnerNetworkCollection { - BaseMobSet, - { - SpawnerNetwork { - std::vector { "Base_MobA", "Base_MobB", "Base_MobC" }, - "", - false, - false - }, - } - }, - SpawnerNetworkCollection { - RandMobSet, - { - SpawnerNetwork { - std::vector {"MobA_", "MobB_", "MobC_"}, - "01", - false, - false - }, - SpawnerNetwork { - std::vector {"MobA_", "MobB_", "MobC_"}, - "02", - false, - false - }, - SpawnerNetwork { - std::vector {"MobA_", "MobB_", "MobC_"}, - "03", - true, - false - }, - } - }, - SpawnerNetworkCollection { - "", - { - SpawnerNetwork { - std::vector { "Rewards_" }, - "01", - false, - false - }, - } - }, - SpawnerNetworkCollection { - "", - { - SpawnerNetwork { - std::vector { "Smash_" }, - "01", - false, - false - }, - } - } - }; + return SpawnerNetworks{ + SpawnerNetworkCollection { + BaseMobSet, + { + SpawnerNetwork { + std::vector { "Base_MobA", "Base_MobB", "Base_MobC" }, + "", + false, + false + }, + } + }, + SpawnerNetworkCollection { + RandMobSet, + { + SpawnerNetwork { + std::vector {"MobA_", "MobB_", "MobC_"}, + "01", + false, + false + }, + SpawnerNetwork { + std::vector {"MobA_", "MobB_", "MobC_"}, + "02", + false, + false + }, + SpawnerNetwork { + std::vector {"MobA_", "MobB_", "MobC_"}, + "03", + true, + false + }, + } + }, + SpawnerNetworkCollection { + "", + { + SpawnerNetwork { + std::vector { "Rewards_" }, + "01", + false, + false + }, + } + }, + SpawnerNetworkCollection { + "", + { + SpawnerNetwork { + std::vector { "Smash_" }, + "01", + false, + false + }, + } + } + }; } std::map ZoneAgSurvival::GetMissionsToUpdate() { - return std::map { - { 479, 60 }, - { 1153, 180 }, - { 1618, 420 }, - { 1628, 420 }, - { 1638, 420 }, - { 1648, 420 }, - { 1412, 120 }, - { 1510, 120 }, - { 1547, 120 }, - { 1584, 120 }, - { 1426, 300 }, - { 1524, 300 }, - { 1561, 300 }, - { 1598, 300 }, - { 1865, 180 } - }; + return std::map { + { 479, 60 }, + { 1153, 180 }, + { 1618, 420 }, + { 1628, 420 }, + { 1638, 420 }, + { 1648, 420 }, + { 1412, 120 }, + { 1510, 120 }, + { 1547, 120 }, + { 1584, 120 }, + { 1426, 300 }, + { 1524, 300 }, + { 1561, 300 }, + { 1598, 300 }, + { 1865, 180 } + }; } diff --git a/dScripts/ZoneAgSurvival.h b/dScripts/ZoneAgSurvival.h index c5d803ae..4447b6b8 100644 --- a/dScripts/ZoneAgSurvival.h +++ b/dScripts/ZoneAgSurvival.h @@ -4,8 +4,8 @@ #include class ZoneAgSurvival : public BaseSurvivalServer { - Constants GetConstants() override; - SpawnerNetworks GetSpawnerNetworks() override; - MobSets GetMobSets() override; - std::map GetMissionsToUpdate() override; + Constants GetConstants() override; + SpawnerNetworks GetSpawnerNetworks() override; + MobSets GetMobSets() override; + std::map GetMissionsToUpdate() override; }; diff --git a/dScripts/ZoneFvProperty.cpp b/dScripts/ZoneFvProperty.cpp index 64aaad9e..67ada039 100644 --- a/dScripts/ZoneFvProperty.cpp +++ b/dScripts/ZoneFvProperty.cpp @@ -1,40 +1,40 @@ #include "ZoneFvProperty.h" #include "Entity.h" -void ZoneFvProperty::SetGameVariables(Entity *self) { - self->SetVar(ClaimMarkerGroup, "Platform"); - self->SetVar(GeneratorGroup, "Generator"); - self->SetVar(GuardGroup, "Guard"); - self->SetVar(PropertyPlaqueGroup, "PropertyPlaque"); - self->SetVar(PropertyVendorGroup, "PropertyVendor"); - self->SetVar(SpotsGroup, "Spots"); - self->SetVar(MSCloudsGroup, "Clouds"); - self->SetVar(EnemiesGroup, "Enemies"); - self->SetVar(FXManagerGroup, "FXManager"); - self->SetVar(ImagOrbGroup, "Orb"); - self->SetVar(GeneratorFXGroup, "GeneratorFX"); +void ZoneFvProperty::SetGameVariables(Entity* self) { + self->SetVar(ClaimMarkerGroup, "Platform"); + self->SetVar(GeneratorGroup, "Generator"); + self->SetVar(GuardGroup, "Guard"); + self->SetVar(PropertyPlaqueGroup, "PropertyPlaque"); + self->SetVar(PropertyVendorGroup, "PropertyVendor"); + self->SetVar(SpotsGroup, "Spots"); + self->SetVar(MSCloudsGroup, "Clouds"); + self->SetVar(EnemiesGroup, "Enemies"); + self->SetVar(FXManagerGroup, "FXManager"); + self->SetVar(ImagOrbGroup, "Orb"); + self->SetVar(GeneratorFXGroup, "GeneratorFX"); - self->SetVar>(EnemiesSpawner, - { "RoninWander", "RoninGen", "HorsemenGen" }); - self->SetVar(ClaimMarkerSpawner, "Platform"); - self->SetVar(GeneratorSpawner, "Generator"); - self->SetVar(DamageFXSpawner, "Clouds"); - self->SetVar(FXSpotsSpawner, "Spots"); - self->SetVar(PropertyMGSpawner, "Guard"); - self->SetVar(ImageOrbSpawner, "Orb"); - self->SetVar(GeneratorFXSpawner, "GeneratorFX"); - self->SetVar(SmashablesSpawner, "Smashables"); - self->SetVar(FXManagerSpawner, "FXManager"); - self->SetVar(PropObjsSpawner, "BankObj"); - self->SetVar>(AmbientFXSpawner, { "Ash", "FX", "Fog"}); - self->SetVar>(BehaviorObjsSpawner, {}); + self->SetVar>(EnemiesSpawner, + { "RoninWander", "RoninGen", "HorsemenGen" }); + self->SetVar(ClaimMarkerSpawner, "Platform"); + self->SetVar(GeneratorSpawner, "Generator"); + self->SetVar(DamageFXSpawner, "Clouds"); + self->SetVar(FXSpotsSpawner, "Spots"); + self->SetVar(PropertyMGSpawner, "Guard"); + self->SetVar(ImageOrbSpawner, "Orb"); + self->SetVar(GeneratorFXSpawner, "GeneratorFX"); + self->SetVar(SmashablesSpawner, "Smashables"); + self->SetVar(FXManagerSpawner, "FXManager"); + self->SetVar(PropObjsSpawner, "BankObj"); + self->SetVar>(AmbientFXSpawner, { "Ash", "FX", "Fog" }); + self->SetVar>(BehaviorObjsSpawner, {}); - self->SetVar(defeatedProperyFlag, 99); - self->SetVar(placedModelFlag, 107); - self->SetVar(guardMissionFlag, 874); - self->SetVar(brickLinkMissionIDFlag, 950); - self->SetVar(passwordFlag, "s3kratK1ttN"); - self->SetVar(generatorIdFlag, 11023); - self->SetVar(orbIDFlag, 10226); - self->SetVar(behaviorQBID, 11011); + self->SetVar(defeatedProperyFlag, 99); + self->SetVar(placedModelFlag, 107); + self->SetVar(guardMissionFlag, 874); + self->SetVar(brickLinkMissionIDFlag, 950); + self->SetVar(passwordFlag, "s3kratK1ttN"); + self->SetVar(generatorIdFlag, 11023); + self->SetVar(orbIDFlag, 10226); + self->SetVar(behaviorQBID, 11011); } diff --git a/dScripts/ZoneFvProperty.h b/dScripts/ZoneFvProperty.h index 44ec9f85..d456ef11 100644 --- a/dScripts/ZoneFvProperty.h +++ b/dScripts/ZoneFvProperty.h @@ -2,5 +2,5 @@ #include "BasePropertyServer.h" class ZoneFvProperty : public BasePropertyServer { - void SetGameVariables(Entity *self) override; + void SetGameVariables(Entity* self) override; }; diff --git a/dScripts/ZoneGfProperty.cpp b/dScripts/ZoneGfProperty.cpp index 925320c3..565d8cd6 100644 --- a/dScripts/ZoneGfProperty.cpp +++ b/dScripts/ZoneGfProperty.cpp @@ -1,40 +1,40 @@ #include "ZoneGfProperty.h" #include "Entity.h" -void ZoneGfProperty::SetGameVariables(Entity *self) { - self->SetVar(ClaimMarkerGroup, "BehavQB"); - self->SetVar(GeneratorGroup, "Generator"); - self->SetVar(GuardGroup, "Guard"); - self->SetVar(PropertyPlaqueGroup, "PropertyPlaque"); - self->SetVar(PropertyVendorGroup, "PropertyVendor"); - self->SetVar(SpotsGroup, "Spots"); - self->SetVar(MSCloudsGroup, "Clouds"); - self->SetVar(EnemiesGroup, "Enemies"); - self->SetVar(FXManagerGroup, "FXManager"); - self->SetVar(ImagOrbGroup, "Orb"); - self->SetVar(GeneratorFXGroup, "GeneratorFX"); +void ZoneGfProperty::SetGameVariables(Entity* self) { + self->SetVar(ClaimMarkerGroup, "BehavQB"); + self->SetVar(GeneratorGroup, "Generator"); + self->SetVar(GuardGroup, "Guard"); + self->SetVar(PropertyPlaqueGroup, "PropertyPlaque"); + self->SetVar(PropertyVendorGroup, "PropertyVendor"); + self->SetVar(SpotsGroup, "Spots"); + self->SetVar(MSCloudsGroup, "Clouds"); + self->SetVar(EnemiesGroup, "Enemies"); + self->SetVar(FXManagerGroup, "FXManager"); + self->SetVar(ImagOrbGroup, "Orb"); + self->SetVar(GeneratorFXGroup, "GeneratorFX"); - self->SetVar>(EnemiesSpawner, - { "PiratesWander", "PiratesGen", "AdmiralsWander", "AdmiralsGen" }); - self->SetVar(ClaimMarkerSpawner, "BehavPlat"); - self->SetVar(GeneratorSpawner, "Generator"); - self->SetVar(DamageFXSpawner, "Clouds"); - self->SetVar(FXSpotsSpawner, "Spots"); - self->SetVar(PropertyMGSpawner, "Guard"); - self->SetVar(ImageOrbSpawner, "Orb"); - self->SetVar(GeneratorFXSpawner, "GeneratorFX"); - self->SetVar(SmashablesSpawner, "Smashables"); - self->SetVar(FXManagerSpawner, "FXManager"); - self->SetVar(PropObjsSpawner, "BankObj"); - self->SetVar>(AmbientFXSpawner, { "Birds", "Falls", "Sunbeam" }); - self->SetVar>(BehaviorObjsSpawner, { "TrappedPlatform", "IceBarrier", "FireBeast" }); + self->SetVar>(EnemiesSpawner, + { "PiratesWander", "PiratesGen", "AdmiralsWander", "AdmiralsGen" }); + self->SetVar(ClaimMarkerSpawner, "BehavPlat"); + self->SetVar(GeneratorSpawner, "Generator"); + self->SetVar(DamageFXSpawner, "Clouds"); + self->SetVar(FXSpotsSpawner, "Spots"); + self->SetVar(PropertyMGSpawner, "Guard"); + self->SetVar(ImageOrbSpawner, "Orb"); + self->SetVar(GeneratorFXSpawner, "GeneratorFX"); + self->SetVar(SmashablesSpawner, "Smashables"); + self->SetVar(FXManagerSpawner, "FXManager"); + self->SetVar(PropObjsSpawner, "BankObj"); + self->SetVar>(AmbientFXSpawner, { "Birds", "Falls", "Sunbeam" }); + self->SetVar>(BehaviorObjsSpawner, { "TrappedPlatform", "IceBarrier", "FireBeast" }); - self->SetVar(defeatedProperyFlag, 98); - self->SetVar(placedModelFlag, 106); - self->SetVar(guardMissionFlag, 873); - self->SetVar(brickLinkMissionIDFlag, 949); - self->SetVar(passwordFlag, "s3kratK1ttN"); - self->SetVar(generatorIdFlag, 11109); - self->SetVar(orbIDFlag, 10226); - self->SetVar(behaviorQBID, 11001); + self->SetVar(defeatedProperyFlag, 98); + self->SetVar(placedModelFlag, 106); + self->SetVar(guardMissionFlag, 873); + self->SetVar(brickLinkMissionIDFlag, 949); + self->SetVar(passwordFlag, "s3kratK1ttN"); + self->SetVar(generatorIdFlag, 11109); + self->SetVar(orbIDFlag, 10226); + self->SetVar(behaviorQBID, 11001); } diff --git a/dScripts/ZoneGfProperty.h b/dScripts/ZoneGfProperty.h index 9b3a8a30..74ffd3b6 100644 --- a/dScripts/ZoneGfProperty.h +++ b/dScripts/ZoneGfProperty.h @@ -2,5 +2,5 @@ #include "BasePropertyServer.h" class ZoneGfProperty : public BasePropertyServer { - void SetGameVariables(Entity *self) override; + void SetGameVariables(Entity* self) override; }; diff --git a/dScripts/ZoneNsMedProperty.cpp b/dScripts/ZoneNsMedProperty.cpp index feaadf31..30e597ee 100644 --- a/dScripts/ZoneNsMedProperty.cpp +++ b/dScripts/ZoneNsMedProperty.cpp @@ -1,40 +1,40 @@ #include "ZoneNsMedProperty.h" #include "Entity.h" -void ZoneNsMedProperty::SetGameVariables(Entity *self) { - self->SetVar(ClaimMarkerGroup, "ClaimMarker"); - self->SetVar(GeneratorGroup, "Generator"); - self->SetVar(GuardGroup, "Guard"); - self->SetVar(PropertyPlaqueGroup, "PropertyPlaque"); - self->SetVar(PropertyVendorGroup, "PropertyVendor"); - self->SetVar(SpotsGroup, "Spots"); - self->SetVar(MSCloudsGroup, "maelstrom"); - self->SetVar(EnemiesGroup, "Enemies"); - self->SetVar(FXManagerGroup, "FXObject"); - self->SetVar(ImagOrbGroup, "Orb"); - self->SetVar(GeneratorFXGroup, "GeneratorFX"); +void ZoneNsMedProperty::SetGameVariables(Entity* self) { + self->SetVar(ClaimMarkerGroup, "ClaimMarker"); + self->SetVar(GeneratorGroup, "Generator"); + self->SetVar(GuardGroup, "Guard"); + self->SetVar(PropertyPlaqueGroup, "PropertyPlaque"); + self->SetVar(PropertyVendorGroup, "PropertyVendor"); + self->SetVar(SpotsGroup, "Spots"); + self->SetVar(MSCloudsGroup, "maelstrom"); + self->SetVar(EnemiesGroup, "Enemies"); + self->SetVar(FXManagerGroup, "FXObject"); + self->SetVar(ImagOrbGroup, "Orb"); + self->SetVar(GeneratorFXGroup, "GeneratorFX"); - self->SetVar>(EnemiesSpawner, - { "Admirals", "AdmiralsWander", "Mechs", "Ronin", "RoninWander" }); - self->SetVar(ClaimMarkerSpawner, "ClaimMarker"); - self->SetVar(GeneratorSpawner, "Generator"); - self->SetVar(DamageFXSpawner, "MaelstromFX"); - self->SetVar(FXSpotsSpawner, "MaelstromSpots"); - self->SetVar(PropertyMGSpawner, "PropertyGuard"); - self->SetVar(ImageOrbSpawner, "Orb"); - self->SetVar(GeneratorFXSpawner, "GeneratorFX"); - self->SetVar(SmashablesSpawner, "Smashables"); - self->SetVar(FXManagerSpawner, "FXObject"); - self->SetVar(PropObjsSpawner, "BankObj"); - self->SetVar>(AmbientFXSpawner, { "Rockets" }); - self->SetVar>(BehaviorObjsSpawner, { }); + self->SetVar>(EnemiesSpawner, + { "Admirals", "AdmiralsWander", "Mechs", "Ronin", "RoninWander" }); + self->SetVar(ClaimMarkerSpawner, "ClaimMarker"); + self->SetVar(GeneratorSpawner, "Generator"); + self->SetVar(DamageFXSpawner, "MaelstromFX"); + self->SetVar(FXSpotsSpawner, "MaelstromSpots"); + self->SetVar(PropertyMGSpawner, "PropertyGuard"); + self->SetVar(ImageOrbSpawner, "Orb"); + self->SetVar(GeneratorFXSpawner, "GeneratorFX"); + self->SetVar(SmashablesSpawner, "Smashables"); + self->SetVar(FXManagerSpawner, "FXObject"); + self->SetVar(PropObjsSpawner, "BankObj"); + self->SetVar>(AmbientFXSpawner, { "Rockets" }); + self->SetVar>(BehaviorObjsSpawner, { }); - self->SetVar(defeatedProperyFlag, 122); - self->SetVar(placedModelFlag, 123); - self->SetVar(guardMissionFlag, 1322); - self->SetVar(brickLinkMissionIDFlag, 1294); - self->SetVar(passwordFlag, "s3kratK1ttN"); - self->SetVar(generatorIdFlag, 11031); - self->SetVar(orbIDFlag, 10226); - self->SetVar(behaviorQBID, 10445); + self->SetVar(defeatedProperyFlag, 122); + self->SetVar(placedModelFlag, 123); + self->SetVar(guardMissionFlag, 1322); + self->SetVar(brickLinkMissionIDFlag, 1294); + self->SetVar(passwordFlag, "s3kratK1ttN"); + self->SetVar(generatorIdFlag, 11031); + self->SetVar(orbIDFlag, 10226); + self->SetVar(behaviorQBID, 10445); } diff --git a/dScripts/ZoneNsMedProperty.h b/dScripts/ZoneNsMedProperty.h index d25974e1..3aaf6bd8 100644 --- a/dScripts/ZoneNsMedProperty.h +++ b/dScripts/ZoneNsMedProperty.h @@ -2,5 +2,5 @@ #include "BasePropertyServer.h" class ZoneNsMedProperty : public BasePropertyServer { - void SetGameVariables(Entity *self) override; + void SetGameVariables(Entity* self) override; }; diff --git a/dScripts/ZoneNsProperty.cpp b/dScripts/ZoneNsProperty.cpp index 72eb1ead..49364ee8 100644 --- a/dScripts/ZoneNsProperty.cpp +++ b/dScripts/ZoneNsProperty.cpp @@ -1,41 +1,41 @@ #include "ZoneNsProperty.h" #include "Entity.h" -void ZoneNsProperty::SetGameVariables(Entity *self) { - self->SetVar(ClaimMarkerGroup, "Rhino"); - self->SetVar(GeneratorGroup, "Generator"); - self->SetVar(GuardGroup, "Guard"); - self->SetVar(PropertyPlaqueGroup, "PropertyPlaque"); - self->SetVar(PropertyVendorGroup, "PropertyVendor"); - self->SetVar(SpotsGroup, "Spots"); - self->SetVar(MSCloudsGroup, "Clouds"); - self->SetVar(EnemiesGroup, "Enemies"); - self->SetVar(FXManagerGroup, "FXManager"); - self->SetVar(ImagOrbGroup, "Orb"); - self->SetVar(GeneratorFXGroup, "GeneratorFX"); +void ZoneNsProperty::SetGameVariables(Entity* self) { + self->SetVar(ClaimMarkerGroup, "Rhino"); + self->SetVar(GeneratorGroup, "Generator"); + self->SetVar(GuardGroup, "Guard"); + self->SetVar(PropertyPlaqueGroup, "PropertyPlaque"); + self->SetVar(PropertyVendorGroup, "PropertyVendor"); + self->SetVar(SpotsGroup, "Spots"); + self->SetVar(MSCloudsGroup, "Clouds"); + self->SetVar(EnemiesGroup, "Enemies"); + self->SetVar(FXManagerGroup, "FXManager"); + self->SetVar(ImagOrbGroup, "Orb"); + self->SetVar(GeneratorFXGroup, "GeneratorFX"); - self->SetVar>(EnemiesSpawner, { - "StrombieWander", "StrombieGen", "PirateWander", "PirateGen", "RoninGen" - }); - self->SetVar(ClaimMarkerSpawner, "ClaimMarker"); - self->SetVar(GeneratorSpawner, "Generator"); - self->SetVar(DamageFXSpawner, "MSClouds"); - self->SetVar(FXSpotsSpawner, "Spots"); - self->SetVar(PropertyMGSpawner, "Guard"); - self->SetVar(ImageOrbSpawner, "Orb"); - self->SetVar(GeneratorFXSpawner, "GeneratorFX"); - self->SetVar(SmashablesSpawner, "Smashables"); - self->SetVar(FXManagerSpawner, "FXManager"); - self->SetVar(PropObjsSpawner, "BankObj"); - self->SetVar>(AmbientFXSpawner, { "Rockets" }); - self->SetVar>(BehaviorObjsSpawner,{ "Cage", "Platform", "Door" }); + self->SetVar>(EnemiesSpawner, { + "StrombieWander", "StrombieGen", "PirateWander", "PirateGen", "RoninGen" + }); + self->SetVar(ClaimMarkerSpawner, "ClaimMarker"); + self->SetVar(GeneratorSpawner, "Generator"); + self->SetVar(DamageFXSpawner, "MSClouds"); + self->SetVar(FXSpotsSpawner, "Spots"); + self->SetVar(PropertyMGSpawner, "Guard"); + self->SetVar(ImageOrbSpawner, "Orb"); + self->SetVar(GeneratorFXSpawner, "GeneratorFX"); + self->SetVar(SmashablesSpawner, "Smashables"); + self->SetVar(FXManagerSpawner, "FXManager"); + self->SetVar(PropObjsSpawner, "BankObj"); + self->SetVar>(AmbientFXSpawner, { "Rockets" }); + self->SetVar>(BehaviorObjsSpawner, { "Cage", "Platform", "Door" }); - self->SetVar(defeatedProperyFlag, 97); - self->SetVar(placedModelFlag, 105); - self->SetVar(guardMissionFlag, 872); - self->SetVar(brickLinkMissionIDFlag, 948); - self->SetVar(passwordFlag, "s3kratK1ttN"); - self->SetVar(generatorIdFlag, 11031); - self->SetVar(orbIDFlag, 10226); - self->SetVar(behaviorQBID, 11009); + self->SetVar(defeatedProperyFlag, 97); + self->SetVar(placedModelFlag, 105); + self->SetVar(guardMissionFlag, 872); + self->SetVar(brickLinkMissionIDFlag, 948); + self->SetVar(passwordFlag, "s3kratK1ttN"); + self->SetVar(generatorIdFlag, 11031); + self->SetVar(orbIDFlag, 10226); + self->SetVar(behaviorQBID, 11009); } diff --git a/dScripts/ZoneNsProperty.h b/dScripts/ZoneNsProperty.h index 353f4d72..bee8fd4c 100644 --- a/dScripts/ZoneNsProperty.h +++ b/dScripts/ZoneNsProperty.h @@ -2,5 +2,5 @@ #include "BasePropertyServer.h" class ZoneNsProperty : public BasePropertyServer { - void SetGameVariables(Entity *self) override; + void SetGameVariables(Entity* self) override; }; diff --git a/dScripts/ZoneNsWaves.cpp b/dScripts/ZoneNsWaves.cpp index 9f54ae49..6f78acb6 100644 --- a/dScripts/ZoneNsWaves.cpp +++ b/dScripts/ZoneNsWaves.cpp @@ -1,500 +1,500 @@ #include "ZoneNsWaves.h" WaveConstants ZoneNsWaves::GetConstants() { - return { - 60, - 2, - 6, - 2, - "surprise", - "intro" - }; + return { + 60, + 2, + 6, + 2, + "surprise", + "intro" + }; } std::vector ZoneNsWaves::GetSpawnerNames() { - return { - "Base_MobA", - "Base_MobB", - "Base_MobC", - "MobA_01", - "MobB_01", - "MobC_01", - "MobA_02", - "MobB_02", - "MobC_02", - "MobA_03", - "MobB_03", - "MobC_03", - "Reward_01", - "Base_Reward", - "Obstacle_01", - "Boss", - "Ape_Boss", - "Geyser_01", - "Treasure_01", - "Cavalry_Boss", - "Horseman_01", - "Horseman_02", - "Horseman_03", - "Horseman_04" - }; + return { + "Base_MobA", + "Base_MobB", + "Base_MobC", + "MobA_01", + "MobB_01", + "MobC_01", + "MobA_02", + "MobB_02", + "MobC_02", + "MobA_03", + "MobB_03", + "MobC_03", + "Reward_01", + "Base_Reward", + "Obstacle_01", + "Boss", + "Ape_Boss", + "Geyser_01", + "Treasure_01", + "Cavalry_Boss", + "Horseman_01", + "Horseman_02", + "Horseman_03", + "Horseman_04" + }; } std::vector ZoneNsWaves::GetWaveMissions() { - return { - {190, 7, 1242}, - {240, 7, 1226}, - {450, 15, 1243}, - {600, 15, 1227}, - {720, 22, 1244}, - {840, 22, 1228}, - {1080, 29, 1245}, - {1200, 29, 1229}, - }; + return { + {190, 7, 1242}, + {240, 7, 1226}, + {450, 15, 1243}, + {600, 15, 1227}, + {720, 22, 1244}, + {840, 22, 1228}, + {1080, 29, 1245}, + {1200, 29, 1229}, + }; } std::vector ZoneNsWaves::GetWaves() { - return { - // Wave 1 - Wave { - std::vector { - { SpawnLOTS::stromling_minifig, 8, GetSpawnerName(SpawnerName::interior_A) }, - { SpawnLOTS::stromling_minifig, 2, GetSpawnerName(SpawnerName::ag_A) }, - { SpawnLOTS::stromling_minifig, 2, GetSpawnerName(SpawnerName::concert_A) }, - { SpawnLOTS::stromling_minifig, 2, GetSpawnerName(SpawnerName::gf_A) }, - } - }, + return { + // Wave 1 + Wave { + std::vector { + { SpawnLOTS::stromling_minifig, 8, GetSpawnerName(SpawnerName::interior_A) }, + { SpawnLOTS::stromling_minifig, 2, GetSpawnerName(SpawnerName::ag_A) }, + { SpawnLOTS::stromling_minifig, 2, GetSpawnerName(SpawnerName::concert_A) }, + { SpawnLOTS::stromling_minifig, 2, GetSpawnerName(SpawnerName::gf_A) }, + } + }, - // Wave 2 - Wave { - std::vector { - { SpawnLOTS::stromling, 8, GetSpawnerName(SpawnerName::interior_A) }, - { SpawnLOTS::stromling, 2, GetSpawnerName(SpawnerName::ag_A) }, - { SpawnLOTS::stromling, 2, GetSpawnerName(SpawnerName::concert_A) }, - { SpawnLOTS::stromling, 2, GetSpawnerName(SpawnerName::gf_A) }, - } - }, + // Wave 2 + Wave { + std::vector { + { SpawnLOTS::stromling, 8, GetSpawnerName(SpawnerName::interior_A) }, + { SpawnLOTS::stromling, 2, GetSpawnerName(SpawnerName::ag_A) }, + { SpawnLOTS::stromling, 2, GetSpawnerName(SpawnerName::concert_A) }, + { SpawnLOTS::stromling, 2, GetSpawnerName(SpawnerName::gf_A) }, + } + }, - // Wave 3 - Wave { - std::vector { - { SpawnLOTS::stromling, 4, GetSpawnerName(SpawnerName::interior_A) }, - { SpawnLOTS::mech, 2, GetSpawnerName(SpawnerName::interior_B) }, - { SpawnLOTS::stromling, 3, GetSpawnerName(SpawnerName::ag_A) }, - { SpawnLOTS::stromling, 3, GetSpawnerName(SpawnerName::concert_A) }, - { SpawnLOTS::stromling, 3, GetSpawnerName(SpawnerName::gf_A) }, - }, - }, + // Wave 3 + Wave { + std::vector { + { SpawnLOTS::stromling, 4, GetSpawnerName(SpawnerName::interior_A) }, + { SpawnLOTS::mech, 2, GetSpawnerName(SpawnerName::interior_B) }, + { SpawnLOTS::stromling, 3, GetSpawnerName(SpawnerName::ag_A) }, + { SpawnLOTS::stromling, 3, GetSpawnerName(SpawnerName::concert_A) }, + { SpawnLOTS::stromling, 3, GetSpawnerName(SpawnerName::gf_A) }, + }, + }, - // Wave 4 - Wave { - std::vector { - { SpawnLOTS::stromling, 3, GetSpawnerName(SpawnerName::interior_A) }, - { SpawnLOTS::mech, 1, GetSpawnerName(SpawnerName::interior_B) }, - { SpawnLOTS::stromling, 2, GetSpawnerName(SpawnerName::ag_A) }, - { SpawnLOTS::mech, 1, GetSpawnerName(SpawnerName::ag_B) }, - { SpawnLOTS::stromling, 2, GetSpawnerName(SpawnerName::concert_A) }, - { SpawnLOTS::mech, 1, GetSpawnerName(SpawnerName::concert_B) }, - { SpawnLOTS::stromling, 2, GetSpawnerName(SpawnerName::gf_A) }, - { SpawnLOTS::mech, 1, GetSpawnerName(SpawnerName::gf_B) }, - } - }, + // Wave 4 + Wave { + std::vector { + { SpawnLOTS::stromling, 3, GetSpawnerName(SpawnerName::interior_A) }, + { SpawnLOTS::mech, 1, GetSpawnerName(SpawnerName::interior_B) }, + { SpawnLOTS::stromling, 2, GetSpawnerName(SpawnerName::ag_A) }, + { SpawnLOTS::mech, 1, GetSpawnerName(SpawnerName::ag_B) }, + { SpawnLOTS::stromling, 2, GetSpawnerName(SpawnerName::concert_A) }, + { SpawnLOTS::mech, 1, GetSpawnerName(SpawnerName::concert_B) }, + { SpawnLOTS::stromling, 2, GetSpawnerName(SpawnerName::gf_A) }, + { SpawnLOTS::mech, 1, GetSpawnerName(SpawnerName::gf_B) }, + } + }, - // Wave 5 - Wave { - std::vector { - { SpawnLOTS::stromling, 2, GetSpawnerName(SpawnerName::interior_A) }, - { SpawnLOTS::spiderling, 1, GetSpawnerName(SpawnerName::interior_C) }, - { SpawnLOTS::hammerling_melee, 2, GetSpawnerName(SpawnerName::ag_A) }, - { SpawnLOTS::mech, 1, GetSpawnerName(SpawnerName::ag_B) }, - { SpawnLOTS::stromling, 1, GetSpawnerName(SpawnerName::concert_A) }, - { SpawnLOTS::mech, 1, GetSpawnerName(SpawnerName::concert_B) }, - { SpawnLOTS::stromling, 1, GetSpawnerName(SpawnerName::gf_A) }, - { SpawnLOTS::mech, 1, GetSpawnerName(SpawnerName::gf_B) }, - } - }, + // Wave 5 + Wave { + std::vector { + { SpawnLOTS::stromling, 2, GetSpawnerName(SpawnerName::interior_A) }, + { SpawnLOTS::spiderling, 1, GetSpawnerName(SpawnerName::interior_C) }, + { SpawnLOTS::hammerling_melee, 2, GetSpawnerName(SpawnerName::ag_A) }, + { SpawnLOTS::mech, 1, GetSpawnerName(SpawnerName::ag_B) }, + { SpawnLOTS::stromling, 1, GetSpawnerName(SpawnerName::concert_A) }, + { SpawnLOTS::mech, 1, GetSpawnerName(SpawnerName::concert_B) }, + { SpawnLOTS::stromling, 1, GetSpawnerName(SpawnerName::gf_A) }, + { SpawnLOTS::mech, 1, GetSpawnerName(SpawnerName::gf_B) }, + } + }, - // Wave 6 - Wave { - std::vector { - { SpawnLOTS::hammerling_melee, 1, GetSpawnerName(SpawnerName::interior_A) }, - { SpawnLOTS::mech, 2, GetSpawnerName(SpawnerName::interior_B) }, - { SpawnLOTS::spiderling, 1, GetSpawnerName(SpawnerName::interior_C) }, - { SpawnLOTS::hammerling_melee, 2, GetSpawnerName(SpawnerName::ag_A) }, - { SpawnLOTS::mech, 1, GetSpawnerName(SpawnerName::ag_B) }, - { SpawnLOTS::spiderling, 1, GetSpawnerName(SpawnerName::ag_C) }, - { SpawnLOTS::stromling, 2, GetSpawnerName(SpawnerName::concert_A) }, - { SpawnLOTS::mech, 1, GetSpawnerName(SpawnerName::concert_B) }, - { SpawnLOTS::stromling, 2, GetSpawnerName(SpawnerName::gf_A) }, - { SpawnLOTS::mech, 1, GetSpawnerName(SpawnerName::gf_B) }, - } - }, + // Wave 6 + Wave { + std::vector { + { SpawnLOTS::hammerling_melee, 1, GetSpawnerName(SpawnerName::interior_A) }, + { SpawnLOTS::mech, 2, GetSpawnerName(SpawnerName::interior_B) }, + { SpawnLOTS::spiderling, 1, GetSpawnerName(SpawnerName::interior_C) }, + { SpawnLOTS::hammerling_melee, 2, GetSpawnerName(SpawnerName::ag_A) }, + { SpawnLOTS::mech, 1, GetSpawnerName(SpawnerName::ag_B) }, + { SpawnLOTS::spiderling, 1, GetSpawnerName(SpawnerName::ag_C) }, + { SpawnLOTS::stromling, 2, GetSpawnerName(SpawnerName::concert_A) }, + { SpawnLOTS::mech, 1, GetSpawnerName(SpawnerName::concert_B) }, + { SpawnLOTS::stromling, 2, GetSpawnerName(SpawnerName::gf_A) }, + { SpawnLOTS::mech, 1, GetSpawnerName(SpawnerName::gf_B) }, + } + }, - // Wave 7 - Wave { - std::vector { - { SpawnLOTS::stromling_boss, 1, GetSpawnerName(SpawnerName::Boss) }, - }, - {1885}, - {}, - "Stromling_Boss", - 5.0f - }, + // Wave 7 + Wave { + std::vector { + { SpawnLOTS::stromling_boss, 1, GetSpawnerName(SpawnerName::Boss) }, + }, + {1885}, + {}, + "Stromling_Boss", + 5.0f + }, - // Wave 8 - Wave { - std::vector { - {SpawnLOTS::mushroom, 6, GetSpawnerName(SpawnerName::Reward_01) }, - {SpawnLOTS::mushroom, 3, GetSpawnerName(SpawnerName::interior_Reward) }, - }, {}, {}, "", -1.0f, - 25, - }, + // Wave 8 + Wave { + std::vector { + {SpawnLOTS::mushroom, 6, GetSpawnerName(SpawnerName::Reward_01) }, + {SpawnLOTS::mushroom, 3, GetSpawnerName(SpawnerName::interior_Reward) }, + }, {}, {}, "", -1.0f, + 25, + }, - // Wave 9 - Wave { - std::vector { - { SpawnLOTS::pirate, 4, GetSpawnerName(SpawnerName::interior_A) }, - { SpawnLOTS::pirate, 2, GetSpawnerName(SpawnerName::concert_A) }, - { SpawnLOTS::pirate, 2, GetSpawnerName(SpawnerName::gf_A) }, - { SpawnLOTS::admiral, 1, GetSpawnerName(SpawnerName::gf_B) }, - } - }, + // Wave 9 + Wave { + std::vector { + { SpawnLOTS::pirate, 4, GetSpawnerName(SpawnerName::interior_A) }, + { SpawnLOTS::pirate, 2, GetSpawnerName(SpawnerName::concert_A) }, + { SpawnLOTS::pirate, 2, GetSpawnerName(SpawnerName::gf_A) }, + { SpawnLOTS::admiral, 1, GetSpawnerName(SpawnerName::gf_B) }, + } + }, - // Wave 10 - Wave { - std::vector { - { SpawnLOTS::pirate, 4, GetSpawnerName(SpawnerName::interior_A) }, - { SpawnLOTS::mech, 2, GetSpawnerName(SpawnerName::interior_B) }, - { SpawnLOTS::pirate, 2, GetSpawnerName(SpawnerName::ag_A) }, - { SpawnLOTS::mech, 1, GetSpawnerName(SpawnerName::ag_B) }, - { SpawnLOTS::pirate, 2, GetSpawnerName(SpawnerName::concert_A) }, - { SpawnLOTS::mech, 1, GetSpawnerName(SpawnerName::concert_B) }, - { SpawnLOTS::pirate, 2, GetSpawnerName(SpawnerName::gf_A) }, - { SpawnLOTS::admiral, 2, GetSpawnerName(SpawnerName::gf_B) }, - } - }, + // Wave 10 + Wave { + std::vector { + { SpawnLOTS::pirate, 4, GetSpawnerName(SpawnerName::interior_A) }, + { SpawnLOTS::mech, 2, GetSpawnerName(SpawnerName::interior_B) }, + { SpawnLOTS::pirate, 2, GetSpawnerName(SpawnerName::ag_A) }, + { SpawnLOTS::mech, 1, GetSpawnerName(SpawnerName::ag_B) }, + { SpawnLOTS::pirate, 2, GetSpawnerName(SpawnerName::concert_A) }, + { SpawnLOTS::mech, 1, GetSpawnerName(SpawnerName::concert_B) }, + { SpawnLOTS::pirate, 2, GetSpawnerName(SpawnerName::gf_A) }, + { SpawnLOTS::admiral, 2, GetSpawnerName(SpawnerName::gf_B) }, + } + }, - // Wave 11 - Wave { - std::vector { - { SpawnLOTS::pirate, 4, GetSpawnerName(SpawnerName::interior_A) }, - { SpawnLOTS::spiderling, 2, GetSpawnerName(SpawnerName::interior_C) }, - { SpawnLOTS::pirate, 2, GetSpawnerName(SpawnerName::ag_A) }, - { SpawnLOTS::spiderling, 1, GetSpawnerName(SpawnerName::ag_C) }, - { SpawnLOTS::pirate, 2, GetSpawnerName(SpawnerName::concert_A) }, - { SpawnLOTS::spiderling, 1, GetSpawnerName(SpawnerName::concert_C) }, - { SpawnLOTS::pirate, 2, GetSpawnerName(SpawnerName::gf_A) }, - { SpawnLOTS::spiderling, 1, GetSpawnerName(SpawnerName::gf_C) }, - } - }, + // Wave 11 + Wave { + std::vector { + { SpawnLOTS::pirate, 4, GetSpawnerName(SpawnerName::interior_A) }, + { SpawnLOTS::spiderling, 2, GetSpawnerName(SpawnerName::interior_C) }, + { SpawnLOTS::pirate, 2, GetSpawnerName(SpawnerName::ag_A) }, + { SpawnLOTS::spiderling, 1, GetSpawnerName(SpawnerName::ag_C) }, + { SpawnLOTS::pirate, 2, GetSpawnerName(SpawnerName::concert_A) }, + { SpawnLOTS::spiderling, 1, GetSpawnerName(SpawnerName::concert_C) }, + { SpawnLOTS::pirate, 2, GetSpawnerName(SpawnerName::gf_A) }, + { SpawnLOTS::spiderling, 1, GetSpawnerName(SpawnerName::gf_C) }, + } + }, - // Wave 12 - Wave { - std::vector { - { SpawnLOTS::pirate, 4, GetSpawnerName(SpawnerName::interior_A) }, - { SpawnLOTS::hammerling, 2, GetSpawnerName(SpawnerName::interior_B) }, - { SpawnLOTS::spiderling, 2, GetSpawnerName(SpawnerName::interior_C) }, - { SpawnLOTS::mech, 2, GetSpawnerName(SpawnerName::ag_B) }, - { SpawnLOTS::spiderling, 1, GetSpawnerName(SpawnerName::ag_C) }, - { SpawnLOTS::pirate, 2, GetSpawnerName(SpawnerName::concert_A) }, - { SpawnLOTS::admiral, 1, GetSpawnerName(SpawnerName::concert_C) }, - { SpawnLOTS::pirate, 2, GetSpawnerName(SpawnerName::gf_A) }, - { SpawnLOTS::admiral, 1, GetSpawnerName(SpawnerName::gf_C) }, - } - }, + // Wave 12 + Wave { + std::vector { + { SpawnLOTS::pirate, 4, GetSpawnerName(SpawnerName::interior_A) }, + { SpawnLOTS::hammerling, 2, GetSpawnerName(SpawnerName::interior_B) }, + { SpawnLOTS::spiderling, 2, GetSpawnerName(SpawnerName::interior_C) }, + { SpawnLOTS::mech, 2, GetSpawnerName(SpawnerName::ag_B) }, + { SpawnLOTS::spiderling, 1, GetSpawnerName(SpawnerName::ag_C) }, + { SpawnLOTS::pirate, 2, GetSpawnerName(SpawnerName::concert_A) }, + { SpawnLOTS::admiral, 1, GetSpawnerName(SpawnerName::concert_C) }, + { SpawnLOTS::pirate, 2, GetSpawnerName(SpawnerName::gf_A) }, + { SpawnLOTS::admiral, 1, GetSpawnerName(SpawnerName::gf_C) }, + } + }, - // Wave 13 - Wave { - std::vector { - { SpawnLOTS::pirate, 3, GetSpawnerName(SpawnerName::interior_A) }, - { SpawnLOTS::admiral, 2, GetSpawnerName(SpawnerName::interior_B) }, - { SpawnLOTS::pirate, 2, GetSpawnerName(SpawnerName::ag_A) }, - { SpawnLOTS::admiral, 1, GetSpawnerName(SpawnerName::ag_B) }, - { SpawnLOTS::pirate, 2, GetSpawnerName(SpawnerName::concert_A) }, - { SpawnLOTS::admiral, 1, GetSpawnerName(SpawnerName::concert_B) }, - { SpawnLOTS::pirate, 2, GetSpawnerName(SpawnerName::gf_A) }, - { SpawnLOTS::admiral, 1, GetSpawnerName(SpawnerName::gf_B) }, - } - }, + // Wave 13 + Wave { + std::vector { + { SpawnLOTS::pirate, 3, GetSpawnerName(SpawnerName::interior_A) }, + { SpawnLOTS::admiral, 2, GetSpawnerName(SpawnerName::interior_B) }, + { SpawnLOTS::pirate, 2, GetSpawnerName(SpawnerName::ag_A) }, + { SpawnLOTS::admiral, 1, GetSpawnerName(SpawnerName::ag_B) }, + { SpawnLOTS::pirate, 2, GetSpawnerName(SpawnerName::concert_A) }, + { SpawnLOTS::admiral, 1, GetSpawnerName(SpawnerName::concert_B) }, + { SpawnLOTS::pirate, 2, GetSpawnerName(SpawnerName::gf_A) }, + { SpawnLOTS::admiral, 1, GetSpawnerName(SpawnerName::gf_B) }, + } + }, - // Wave 14 - Wave { - std::vector { - { SpawnLOTS::pirate, 2, GetSpawnerName(SpawnerName::interior_A) }, - { SpawnLOTS::admiral, 2, GetSpawnerName(SpawnerName::interior_B) }, - { SpawnLOTS::mech, 2, GetSpawnerName(SpawnerName::interior_C) }, - { SpawnLOTS::pirate, 2, GetSpawnerName(SpawnerName::ag_A) }, - { SpawnLOTS::admiral, 1, GetSpawnerName(SpawnerName::ag_B) }, - { SpawnLOTS::mech, 1, GetSpawnerName(SpawnerName::ag_C) }, - { SpawnLOTS::pirate, 2, GetSpawnerName(SpawnerName::concert_A) }, - { SpawnLOTS::admiral, 1, GetSpawnerName(SpawnerName::concert_B) }, - { SpawnLOTS::mech, 1, GetSpawnerName(SpawnerName::concert_C) }, - { SpawnLOTS::pirate, 2, GetSpawnerName(SpawnerName::gf_A) }, - { SpawnLOTS::admiral, 1, GetSpawnerName(SpawnerName::gf_B) }, - { SpawnLOTS::mech, 1, GetSpawnerName(SpawnerName::gf_C) }, - } - }, + // Wave 14 + Wave { + std::vector { + { SpawnLOTS::pirate, 2, GetSpawnerName(SpawnerName::interior_A) }, + { SpawnLOTS::admiral, 2, GetSpawnerName(SpawnerName::interior_B) }, + { SpawnLOTS::mech, 2, GetSpawnerName(SpawnerName::interior_C) }, + { SpawnLOTS::pirate, 2, GetSpawnerName(SpawnerName::ag_A) }, + { SpawnLOTS::admiral, 1, GetSpawnerName(SpawnerName::ag_B) }, + { SpawnLOTS::mech, 1, GetSpawnerName(SpawnerName::ag_C) }, + { SpawnLOTS::pirate, 2, GetSpawnerName(SpawnerName::concert_A) }, + { SpawnLOTS::admiral, 1, GetSpawnerName(SpawnerName::concert_B) }, + { SpawnLOTS::mech, 1, GetSpawnerName(SpawnerName::concert_C) }, + { SpawnLOTS::pirate, 2, GetSpawnerName(SpawnerName::gf_A) }, + { SpawnLOTS::admiral, 1, GetSpawnerName(SpawnerName::gf_B) }, + { SpawnLOTS::mech, 1, GetSpawnerName(SpawnerName::gf_C) }, + } + }, - // Wave 15 - Wave { - std::vector { - { SpawnLOTS::ape_boss, 1, GetSpawnerName(SpawnerName::Ape_Boss) }, + // Wave 15 + Wave { + std::vector { + { SpawnLOTS::ape_boss, 1, GetSpawnerName(SpawnerName::Ape_Boss) }, - }, - {1886}, - {}, - "Gorilla_Boss", - 5.0f - }, + }, + {1886}, + {}, + "Gorilla_Boss", + 5.0f + }, - // Wave 16 - Wave { - std::vector { - {SpawnLOTS::outhouse, 3, GetSpawnerName(SpawnerName::interior_Reward) }, - {SpawnLOTS::mushroom, 6, GetSpawnerName(SpawnerName::Reward_01) }, - }, {}, {}, "", -1.0f, - 25, - }, + // Wave 16 + Wave { + std::vector { + {SpawnLOTS::outhouse, 3, GetSpawnerName(SpawnerName::interior_Reward) }, + {SpawnLOTS::mushroom, 6, GetSpawnerName(SpawnerName::Reward_01) }, + }, {}, {}, "", -1.0f, + 25, + }, - // Wave 17 - Wave { - std::vector { - { SpawnLOTS::hammerling_melee, 2, GetSpawnerName(SpawnerName::interior_A) }, - { SpawnLOTS::hammerling_melee, 2, GetSpawnerName(SpawnerName::interior_B) }, - { SpawnLOTS::hammerling_melee, 1, GetSpawnerName(SpawnerName::ag_A) }, - { SpawnLOTS::hammerling_melee, 2, GetSpawnerName(SpawnerName::ag_B) }, - { SpawnLOTS::hammerling_melee, 1, GetSpawnerName(SpawnerName::concert_A) }, - { SpawnLOTS::hammerling_melee, 2, GetSpawnerName(SpawnerName::concert_B) }, - { SpawnLOTS::hammerling_melee, 1, GetSpawnerName(SpawnerName::gf_A) }, - { SpawnLOTS::hammerling_melee, 2, GetSpawnerName(SpawnerName::gf_B) }, - } - }, + // Wave 17 + Wave { + std::vector { + { SpawnLOTS::hammerling_melee, 2, GetSpawnerName(SpawnerName::interior_A) }, + { SpawnLOTS::hammerling_melee, 2, GetSpawnerName(SpawnerName::interior_B) }, + { SpawnLOTS::hammerling_melee, 1, GetSpawnerName(SpawnerName::ag_A) }, + { SpawnLOTS::hammerling_melee, 2, GetSpawnerName(SpawnerName::ag_B) }, + { SpawnLOTS::hammerling_melee, 1, GetSpawnerName(SpawnerName::concert_A) }, + { SpawnLOTS::hammerling_melee, 2, GetSpawnerName(SpawnerName::concert_B) }, + { SpawnLOTS::hammerling_melee, 1, GetSpawnerName(SpawnerName::gf_A) }, + { SpawnLOTS::hammerling_melee, 2, GetSpawnerName(SpawnerName::gf_B) }, + } + }, - // Wave 18 - Wave { - std::vector { - { SpawnLOTS::hammerling_melee, 4, GetSpawnerName(SpawnerName::interior_A) }, - { SpawnLOTS::hammerling, 2, GetSpawnerName(SpawnerName::interior_B) }, - { SpawnLOTS::hammerling_melee, 2, GetSpawnerName(SpawnerName::concert_A) }, - { SpawnLOTS::hammerling, 1, GetSpawnerName(SpawnerName::concert_B) }, - { SpawnLOTS::hammerling_melee, 2, GetSpawnerName(SpawnerName::ag_A) }, - { SpawnLOTS::hammerling, 1, GetSpawnerName(SpawnerName::ag_B) }, - { SpawnLOTS::hammerling_melee, 2, GetSpawnerName(SpawnerName::gf_A) }, - { SpawnLOTS::hammerling, 1, GetSpawnerName(SpawnerName::gf_B) }, - } - }, + // Wave 18 + Wave { + std::vector { + { SpawnLOTS::hammerling_melee, 4, GetSpawnerName(SpawnerName::interior_A) }, + { SpawnLOTS::hammerling, 2, GetSpawnerName(SpawnerName::interior_B) }, + { SpawnLOTS::hammerling_melee, 2, GetSpawnerName(SpawnerName::concert_A) }, + { SpawnLOTS::hammerling, 1, GetSpawnerName(SpawnerName::concert_B) }, + { SpawnLOTS::hammerling_melee, 2, GetSpawnerName(SpawnerName::ag_A) }, + { SpawnLOTS::hammerling, 1, GetSpawnerName(SpawnerName::ag_B) }, + { SpawnLOTS::hammerling_melee, 2, GetSpawnerName(SpawnerName::gf_A) }, + { SpawnLOTS::hammerling, 1, GetSpawnerName(SpawnerName::gf_B) }, + } + }, - // Wave 19 - Wave { - std::vector { - { SpawnLOTS::hammerling, 4, GetSpawnerName(SpawnerName::interior_A) }, - { SpawnLOTS::sentry, 2, GetSpawnerName(SpawnerName::interior_B) }, - { SpawnLOTS::hammerling, 2, GetSpawnerName(SpawnerName::ag_A) }, - { SpawnLOTS::sentry, 1, GetSpawnerName(SpawnerName::ag_B) }, - { SpawnLOTS::hammerling, 2, GetSpawnerName(SpawnerName::concert_A) }, - { SpawnLOTS::sentry, 1, GetSpawnerName(SpawnerName::concert_B) }, - { SpawnLOTS::hammerling, 2, GetSpawnerName(SpawnerName::gf_A) }, - { SpawnLOTS::sentry, 1, GetSpawnerName(SpawnerName::gf_B) }, - } - }, + // Wave 19 + Wave { + std::vector { + { SpawnLOTS::hammerling, 4, GetSpawnerName(SpawnerName::interior_A) }, + { SpawnLOTS::sentry, 2, GetSpawnerName(SpawnerName::interior_B) }, + { SpawnLOTS::hammerling, 2, GetSpawnerName(SpawnerName::ag_A) }, + { SpawnLOTS::sentry, 1, GetSpawnerName(SpawnerName::ag_B) }, + { SpawnLOTS::hammerling, 2, GetSpawnerName(SpawnerName::concert_A) }, + { SpawnLOTS::sentry, 1, GetSpawnerName(SpawnerName::concert_B) }, + { SpawnLOTS::hammerling, 2, GetSpawnerName(SpawnerName::gf_A) }, + { SpawnLOTS::sentry, 1, GetSpawnerName(SpawnerName::gf_B) }, + } + }, - // Wave 20 - Wave { - std::vector { - { SpawnLOTS::ronin, 3, GetSpawnerName(SpawnerName::interior_A) }, - { SpawnLOTS::sentry, 2, GetSpawnerName(SpawnerName::interior_B) }, - { SpawnLOTS::spiderling_ve, 1, GetSpawnerName(SpawnerName::interior_C) }, - { SpawnLOTS::hammerling, 1, GetSpawnerName(SpawnerName::ag_A) }, - { SpawnLOTS::sentry, 1, GetSpawnerName(SpawnerName::ag_B) }, - { SpawnLOTS::spiderling_ve, 1, GetSpawnerName(SpawnerName::ag_C) }, - { SpawnLOTS::hammerling, 1, GetSpawnerName(SpawnerName::concert_A) }, - { SpawnLOTS::sentry, 1, GetSpawnerName(SpawnerName::concert_B) }, - { SpawnLOTS::spiderling_ve, 1, GetSpawnerName(SpawnerName::concert_C) }, - { SpawnLOTS::hammerling, 1, GetSpawnerName(SpawnerName::gf_A) }, - { SpawnLOTS::sentry, 1, GetSpawnerName(SpawnerName::gf_B) }, - { SpawnLOTS::spiderling_ve, 1, GetSpawnerName(SpawnerName::gf_C) }, - } - }, + // Wave 20 + Wave { + std::vector { + { SpawnLOTS::ronin, 3, GetSpawnerName(SpawnerName::interior_A) }, + { SpawnLOTS::sentry, 2, GetSpawnerName(SpawnerName::interior_B) }, + { SpawnLOTS::spiderling_ve, 1, GetSpawnerName(SpawnerName::interior_C) }, + { SpawnLOTS::hammerling, 1, GetSpawnerName(SpawnerName::ag_A) }, + { SpawnLOTS::sentry, 1, GetSpawnerName(SpawnerName::ag_B) }, + { SpawnLOTS::spiderling_ve, 1, GetSpawnerName(SpawnerName::ag_C) }, + { SpawnLOTS::hammerling, 1, GetSpawnerName(SpawnerName::concert_A) }, + { SpawnLOTS::sentry, 1, GetSpawnerName(SpawnerName::concert_B) }, + { SpawnLOTS::spiderling_ve, 1, GetSpawnerName(SpawnerName::concert_C) }, + { SpawnLOTS::hammerling, 1, GetSpawnerName(SpawnerName::gf_A) }, + { SpawnLOTS::sentry, 1, GetSpawnerName(SpawnerName::gf_B) }, + { SpawnLOTS::spiderling_ve, 1, GetSpawnerName(SpawnerName::gf_C) }, + } + }, - // Wave 21 - Wave { - std::vector { - { SpawnLOTS::admiral, 2, GetSpawnerName(SpawnerName::interior_A) }, - { SpawnLOTS::ronin, 2, GetSpawnerName(SpawnerName::interior_B) }, - { SpawnLOTS::spiderling_ve, 2, GetSpawnerName(SpawnerName::interior_C) }, - { SpawnLOTS::admiral, 1, GetSpawnerName(SpawnerName::ag_A) }, - { SpawnLOTS::ronin, 1, GetSpawnerName(SpawnerName::ag_B) }, - { SpawnLOTS::spiderling_ve, 1, GetSpawnerName(SpawnerName::ag_C) }, - { SpawnLOTS::admiral, 1, GetSpawnerName(SpawnerName::concert_A) }, - { SpawnLOTS::ronin, 1, GetSpawnerName(SpawnerName::concert_B) }, - { SpawnLOTS::spiderling_ve, 1, GetSpawnerName(SpawnerName::concert_C) }, - { SpawnLOTS::admiral, 1, GetSpawnerName(SpawnerName::gf_A) }, - { SpawnLOTS::ronin, 1, GetSpawnerName(SpawnerName::gf_B) }, - { SpawnLOTS::spiderling_ve, 1, GetSpawnerName(SpawnerName::gf_C) }, - } - }, + // Wave 21 + Wave { + std::vector { + { SpawnLOTS::admiral, 2, GetSpawnerName(SpawnerName::interior_A) }, + { SpawnLOTS::ronin, 2, GetSpawnerName(SpawnerName::interior_B) }, + { SpawnLOTS::spiderling_ve, 2, GetSpawnerName(SpawnerName::interior_C) }, + { SpawnLOTS::admiral, 1, GetSpawnerName(SpawnerName::ag_A) }, + { SpawnLOTS::ronin, 1, GetSpawnerName(SpawnerName::ag_B) }, + { SpawnLOTS::spiderling_ve, 1, GetSpawnerName(SpawnerName::ag_C) }, + { SpawnLOTS::admiral, 1, GetSpawnerName(SpawnerName::concert_A) }, + { SpawnLOTS::ronin, 1, GetSpawnerName(SpawnerName::concert_B) }, + { SpawnLOTS::spiderling_ve, 1, GetSpawnerName(SpawnerName::concert_C) }, + { SpawnLOTS::admiral, 1, GetSpawnerName(SpawnerName::gf_A) }, + { SpawnLOTS::ronin, 1, GetSpawnerName(SpawnerName::gf_B) }, + { SpawnLOTS::spiderling_ve, 1, GetSpawnerName(SpawnerName::gf_C) }, + } + }, - // Wave 22 - Wave { - std::vector { - { SpawnLOTS::spiderling_boss, 1, GetSpawnerName(SpawnerName::Cavalry_Boss) }, - }, - {1887}, - {}, - "Spiderling_Boss", - 5.0f - }, + // Wave 22 + Wave { + std::vector { + { SpawnLOTS::spiderling_boss, 1, GetSpawnerName(SpawnerName::Cavalry_Boss) }, + }, + {1887}, + {}, + "Spiderling_Boss", + 5.0f + }, - // Wave 23 - Wave { - std::vector { - { SpawnLOTS::outhouse, 6, GetSpawnerName(SpawnerName::Reward_01) }, - { SpawnLOTS::outhouse, 3, GetSpawnerName(SpawnerName::interior_Reward) }, - { SpawnLOTS::maelstrom_chest, 4, GetSpawnerName(SpawnerName::Obstacle) }, - }, {}, {}, "", -1.0f, - 25, - }, + // Wave 23 + Wave { + std::vector { + { SpawnLOTS::outhouse, 6, GetSpawnerName(SpawnerName::Reward_01) }, + { SpawnLOTS::outhouse, 3, GetSpawnerName(SpawnerName::interior_Reward) }, + { SpawnLOTS::maelstrom_chest, 4, GetSpawnerName(SpawnerName::Obstacle) }, + }, {}, {}, "", -1.0f, + 25, + }, - // Wave 24 - Wave { - std::vector { - { SpawnLOTS::pirate, 2, GetSpawnerName(SpawnerName::gf_A) }, - { SpawnLOTS::pirate, 2, GetSpawnerName(SpawnerName::concert_A) }, - { SpawnLOTS::pirate, 3, GetSpawnerName(SpawnerName::ag_A) }, - { SpawnLOTS::ronin, 3, GetSpawnerName(SpawnerName::interior_A) }, - { SpawnLOTS::ronin, 2, GetSpawnerName(SpawnerName::interior_B) }, - } - }, + // Wave 24 + Wave { + std::vector { + { SpawnLOTS::pirate, 2, GetSpawnerName(SpawnerName::gf_A) }, + { SpawnLOTS::pirate, 2, GetSpawnerName(SpawnerName::concert_A) }, + { SpawnLOTS::pirate, 3, GetSpawnerName(SpawnerName::ag_A) }, + { SpawnLOTS::ronin, 3, GetSpawnerName(SpawnerName::interior_A) }, + { SpawnLOTS::ronin, 2, GetSpawnerName(SpawnerName::interior_B) }, + } + }, - // Wave 25 - Wave { - std::vector { - { SpawnLOTS::cavalry, 2, GetSpawnerName(SpawnerName::interior_A) }, - { SpawnLOTS::cavalry, 1, GetSpawnerName(SpawnerName::interior_B) }, - { SpawnLOTS::admiral_cp, 1, GetSpawnerName(SpawnerName::ag_B) }, - { SpawnLOTS::admiral_cp, 1, GetSpawnerName(SpawnerName::gf_B) }, - { SpawnLOTS::admiral_cp, 1, GetSpawnerName(SpawnerName::concert_B) }, - { SpawnLOTS::spiderling, 2, GetSpawnerName(SpawnerName::gf_A) }, - { SpawnLOTS::spiderling, 2, GetSpawnerName(SpawnerName::concert_A) }, - { SpawnLOTS::spiderling, 1, GetSpawnerName(SpawnerName::ag_A) }, - } - }, + // Wave 25 + Wave { + std::vector { + { SpawnLOTS::cavalry, 2, GetSpawnerName(SpawnerName::interior_A) }, + { SpawnLOTS::cavalry, 1, GetSpawnerName(SpawnerName::interior_B) }, + { SpawnLOTS::admiral_cp, 1, GetSpawnerName(SpawnerName::ag_B) }, + { SpawnLOTS::admiral_cp, 1, GetSpawnerName(SpawnerName::gf_B) }, + { SpawnLOTS::admiral_cp, 1, GetSpawnerName(SpawnerName::concert_B) }, + { SpawnLOTS::spiderling, 2, GetSpawnerName(SpawnerName::gf_A) }, + { SpawnLOTS::spiderling, 2, GetSpawnerName(SpawnerName::concert_A) }, + { SpawnLOTS::spiderling, 1, GetSpawnerName(SpawnerName::ag_A) }, + } + }, - // Wave 26 - Wave { - std::vector { - { SpawnLOTS::ronin, 3, GetSpawnerName(SpawnerName::interior_A) }, - { SpawnLOTS::ronin, 3, GetSpawnerName(SpawnerName::interior_B) }, - { SpawnLOTS::spiderling_ve, 1, GetSpawnerName(SpawnerName::ag_B) }, - { SpawnLOTS::spiderling_ve, 1, GetSpawnerName(SpawnerName::gf_B) }, - { SpawnLOTS::spiderling_ve, 1, GetSpawnerName(SpawnerName::concert_B) }, - { SpawnLOTS::admiral_cp, 2, GetSpawnerName(SpawnerName::gf_C) }, - { SpawnLOTS::admiral_cp, 2, GetSpawnerName(SpawnerName::ag_C) }, - { SpawnLOTS::admiral_cp, 1, GetSpawnerName(SpawnerName::concert_C) }, - } - }, + // Wave 26 + Wave { + std::vector { + { SpawnLOTS::ronin, 3, GetSpawnerName(SpawnerName::interior_A) }, + { SpawnLOTS::ronin, 3, GetSpawnerName(SpawnerName::interior_B) }, + { SpawnLOTS::spiderling_ve, 1, GetSpawnerName(SpawnerName::ag_B) }, + { SpawnLOTS::spiderling_ve, 1, GetSpawnerName(SpawnerName::gf_B) }, + { SpawnLOTS::spiderling_ve, 1, GetSpawnerName(SpawnerName::concert_B) }, + { SpawnLOTS::admiral_cp, 2, GetSpawnerName(SpawnerName::gf_C) }, + { SpawnLOTS::admiral_cp, 2, GetSpawnerName(SpawnerName::ag_C) }, + { SpawnLOTS::admiral_cp, 1, GetSpawnerName(SpawnerName::concert_C) }, + } + }, - // Wave 27 - Wave { - std::vector { - { SpawnLOTS::ronin, 5, GetSpawnerName(SpawnerName::interior_A) }, - { SpawnLOTS::ronin, 4, GetSpawnerName(SpawnerName::interior_B) }, - { SpawnLOTS::cavalry, 1, GetSpawnerName(SpawnerName::ag_C) }, - { SpawnLOTS::cavalry, 1, GetSpawnerName(SpawnerName::gf_C) }, - { SpawnLOTS::cavalry, 1, GetSpawnerName(SpawnerName::concert_C) }, - { SpawnLOTS::admiral_cp, 1, GetSpawnerName(SpawnerName::ag_B) }, - { SpawnLOTS::admiral_cp, 1, GetSpawnerName(SpawnerName::gf_B) }, - { SpawnLOTS::admiral_cp, 1, GetSpawnerName(SpawnerName::concert_B) }, - } - }, + // Wave 27 + Wave { + std::vector { + { SpawnLOTS::ronin, 5, GetSpawnerName(SpawnerName::interior_A) }, + { SpawnLOTS::ronin, 4, GetSpawnerName(SpawnerName::interior_B) }, + { SpawnLOTS::cavalry, 1, GetSpawnerName(SpawnerName::ag_C) }, + { SpawnLOTS::cavalry, 1, GetSpawnerName(SpawnerName::gf_C) }, + { SpawnLOTS::cavalry, 1, GetSpawnerName(SpawnerName::concert_C) }, + { SpawnLOTS::admiral_cp, 1, GetSpawnerName(SpawnerName::ag_B) }, + { SpawnLOTS::admiral_cp, 1, GetSpawnerName(SpawnerName::gf_B) }, + { SpawnLOTS::admiral_cp, 1, GetSpawnerName(SpawnerName::concert_B) }, + } + }, - // Wave 28 - Wave { - std::vector { - { SpawnLOTS::dragon_statue, 12, GetSpawnerName(SpawnerName::Reward_01) }, - }, {}, {}, "", -1.0f, - 30, - }, + // Wave 28 + Wave { + std::vector { + { SpawnLOTS::dragon_statue, 12, GetSpawnerName(SpawnerName::Reward_01) }, + }, {}, {}, "", -1.0f, + 30, + }, - // Wave 29 - Wave { - std::vector { - { SpawnLOTS::horseman_boss01, 1, GetSpawnerName(SpawnerName::Horseman_01) }, - { SpawnLOTS::horseman_boss02, 1, GetSpawnerName(SpawnerName::Horseman_02) }, - { SpawnLOTS::horseman_boss03, 1, GetSpawnerName(SpawnerName::Horseman_03) }, - { SpawnLOTS::horseman_boss04, 1, GetSpawnerName(SpawnerName::Horseman_04) }, - }, - {1888}, - {1236, 1237, 1249}, - "Horsemen_Boss", - 5.0f - }, + // Wave 29 + Wave { + std::vector { + { SpawnLOTS::horseman_boss01, 1, GetSpawnerName(SpawnerName::Horseman_01) }, + { SpawnLOTS::horseman_boss02, 1, GetSpawnerName(SpawnerName::Horseman_02) }, + { SpawnLOTS::horseman_boss03, 1, GetSpawnerName(SpawnerName::Horseman_03) }, + { SpawnLOTS::horseman_boss04, 1, GetSpawnerName(SpawnerName::Horseman_04) }, + }, + {1888}, + {1236, 1237, 1249}, + "Horsemen_Boss", + 5.0f + }, - // Wave 30 (treasure) - Wave { - std::vector { - { SpawnLOTS::treasure_chest, 1, GetSpawnerName(SpawnerName::Treasure_01) }, - }, {}, {}, - "Treasure_Camera", - 5.0f, - (uint32_t) -1, - true, - 30, - }, - }; + // Wave 30 (treasure) + Wave { + std::vector { + { SpawnLOTS::treasure_chest, 1, GetSpawnerName(SpawnerName::Treasure_01) }, + }, {}, {}, + "Treasure_Camera", + 5.0f, + (uint32_t)-1, + true, + 30, + }, + }; } std::string ZoneNsWaves::GetSpawnerName(SpawnerName spawnerName) { - switch (spawnerName) { - case interior_A: - return "Base_MobA"; - case interior_B: - return "Base_MobB"; - case interior_C: - return "Base_MobC"; - case gf_A: - return "MobA_01"; - case gf_B: - return "MobB_01"; - case gf_C: - return "MobC_01"; - case concert_A: - return "MobA_02"; - case concert_B: - return "MobB_02"; - case concert_C: - return "MobC_02"; - case ag_A: - return "MobA_03"; - case ag_B: - return "MobB_03"; - case ag_C: - return "MobC_03"; - case Reward_01: - return "Reward_01"; - case interior_Reward: - return "Base_Reward"; - case Obstacle: - return "Obstacle_01"; - case Boss: - return "Boss"; - case Ape_Boss: - return "Ape_Boss"; - case Geyser: - return "Geyser_01"; - case Treasure_01: - return "Treasure_01"; - case Cavalry_Boss: - return "Cavalry_Boss"; - case Horseman_01: - return "Horseman_01"; - case Horseman_02: - return "Horseman_02"; - case Horseman_03: - return "Horseman_03"; - case Horseman_04: - return "Horseman_04"; - default: - return ""; - } + switch (spawnerName) { + case interior_A: + return "Base_MobA"; + case interior_B: + return "Base_MobB"; + case interior_C: + return "Base_MobC"; + case gf_A: + return "MobA_01"; + case gf_B: + return "MobB_01"; + case gf_C: + return "MobC_01"; + case concert_A: + return "MobA_02"; + case concert_B: + return "MobB_02"; + case concert_C: + return "MobC_02"; + case ag_A: + return "MobA_03"; + case ag_B: + return "MobB_03"; + case ag_C: + return "MobC_03"; + case Reward_01: + return "Reward_01"; + case interior_Reward: + return "Base_Reward"; + case Obstacle: + return "Obstacle_01"; + case Boss: + return "Boss"; + case Ape_Boss: + return "Ape_Boss"; + case Geyser: + return "Geyser_01"; + case Treasure_01: + return "Treasure_01"; + case Cavalry_Boss: + return "Cavalry_Boss"; + case Horseman_01: + return "Horseman_01"; + case Horseman_02: + return "Horseman_02"; + case Horseman_03: + return "Horseman_03"; + case Horseman_04: + return "Horseman_04"; + default: + return ""; + } } diff --git a/dScripts/ZoneNsWaves.h b/dScripts/ZoneNsWaves.h index c1a63db6..06503d19 100644 --- a/dScripts/ZoneNsWaves.h +++ b/dScripts/ZoneNsWaves.h @@ -2,68 +2,68 @@ #include "BaseWavesServer.h" enum SpawnerName { - interior_A, - interior_B, - interior_C, - gf_A, - gf_B, - gf_C, - concert_A, - concert_B, - concert_C, - ag_A, - ag_B, - ag_C, - Reward_01, - interior_Reward, - Obstacle, - Boss, - Ape_Boss, - Geyser, - Treasure_01, - Cavalry_Boss, - Horseman_01, - Horseman_02, - Horseman_03, - Horseman_04, + interior_A, + interior_B, + interior_C, + gf_A, + gf_B, + gf_C, + concert_A, + concert_B, + concert_C, + ag_A, + ag_B, + ag_C, + Reward_01, + interior_Reward, + Obstacle, + Boss, + Ape_Boss, + Geyser, + Treasure_01, + Cavalry_Boss, + Horseman_01, + Horseman_02, + Horseman_03, + Horseman_04, }; enum SpawnLOTS : LOT { - stromling = 12586, - mech = 12587, - spiderling = 12588, - pirate = 12589, - admiral = 12590, - ape_boss = 12591, - stromling_boss = 12600, - hammerling = 12602, - sentry = 12604, - spiderling_ve = 12605, - spiderling_boss = 12609, - ronin = 12610, - cavalry = 12611, - dragon_boss = 12612, - stromling_minifig = 12586, - mushroom = 12614, - maelstrom_chest = 4894, - outhouse = 12616, - dragon_statue = 12617, - treasure_chest = 12423, - hammerling_melee = 12653, - maelstrom_geyser = 10314, - ronin_statue = 12611, - horseman_boss01 = 11999, - horseman_boss02 = 12467, - horseman_boss03 = 12468, - horseman_boss04 = 12469, - admiral_cp = 13523, + stromling = 12586, + mech = 12587, + spiderling = 12588, + pirate = 12589, + admiral = 12590, + ape_boss = 12591, + stromling_boss = 12600, + hammerling = 12602, + sentry = 12604, + spiderling_ve = 12605, + spiderling_boss = 12609, + ronin = 12610, + cavalry = 12611, + dragon_boss = 12612, + stromling_minifig = 12586, + mushroom = 12614, + maelstrom_chest = 4894, + outhouse = 12616, + dragon_statue = 12617, + treasure_chest = 12423, + hammerling_melee = 12653, + maelstrom_geyser = 10314, + ronin_statue = 12611, + horseman_boss01 = 11999, + horseman_boss02 = 12467, + horseman_boss03 = 12468, + horseman_boss04 = 12469, + admiral_cp = 13523, }; class ZoneNsWaves : public BaseWavesServer { - WaveConstants GetConstants() override; - std::vector GetSpawnerNames() override; - std::vector GetWaveMissions() override; - std::vector GetWaves() override; + WaveConstants GetConstants() override; + std::vector GetSpawnerNames() override; + std::vector GetWaveMissions() override; + std::vector GetWaves() override; private: - static std::string GetSpawnerName(SpawnerName spawnerName); + static std::string GetSpawnerName(SpawnerName spawnerName); }; diff --git a/dScripts/ZoneSGServer.cpp b/dScripts/ZoneSGServer.cpp index 8149ec55..6822abda 100644 --- a/dScripts/ZoneSGServer.cpp +++ b/dScripts/ZoneSGServer.cpp @@ -1,26 +1,26 @@ #include "ZoneSGServer.h" #include "EntityManager.h" -void ZoneSGServer::OnStartup(Entity *self) { - const auto cannons = EntityManager::Instance()->GetEntitiesByLOT(1864); - for (const auto& cannon : cannons) - self->SetVar(CannonIDVariable, cannon->GetObjectID()); +void ZoneSGServer::OnStartup(Entity* self) { + const auto cannons = EntityManager::Instance()->GetEntitiesByLOT(1864); + for (const auto& cannon : cannons) + self->SetVar(CannonIDVariable, cannon->GetObjectID()); } -void ZoneSGServer::OnActivityStateChangeRequest(Entity *self, const LWOOBJID senderID, const int32_t value1, - const int32_t value2, const std::u16string &stringValue) { +void ZoneSGServer::OnActivityStateChangeRequest(Entity* self, const LWOOBJID senderID, const int32_t value1, + const int32_t value2, const std::u16string& stringValue) { - auto* cannon = EntityManager::Instance()->GetEntity(self->GetVar(CannonIDVariable)); - if (cannon != nullptr) { - cannon->OnActivityStateChangeRequest(senderID, value1, value2, stringValue); - } + auto* cannon = EntityManager::Instance()->GetEntity(self->GetVar(CannonIDVariable)); + if (cannon != nullptr) { + cannon->OnActivityStateChangeRequest(senderID, value1, value2, stringValue); + } } -void ZoneSGServer::OnFireEventServerSide(Entity *self, Entity *sender, std::string args, int32_t param1, int32_t param2, - int32_t param3) { +void ZoneSGServer::OnFireEventServerSide(Entity* self, Entity* sender, std::string args, int32_t param1, int32_t param2, + int32_t param3) { - auto* cannon = EntityManager::Instance()->GetEntity(self->GetVar(CannonIDVariable)); - if (cannon != nullptr) { - cannon->OnFireEventServerSide(sender, args, param1, param2, param3); - } + auto* cannon = EntityManager::Instance()->GetEntity(self->GetVar(CannonIDVariable)); + if (cannon != nullptr) { + cannon->OnFireEventServerSide(sender, args, param1, param2, param3); + } } diff --git a/dScripts/ZoneSGServer.h b/dScripts/ZoneSGServer.h index 4198157f..eaa7c909 100644 --- a/dScripts/ZoneSGServer.h +++ b/dScripts/ZoneSGServer.h @@ -3,11 +3,11 @@ class ZoneSGServer : public CppScripts::Script { public: - void OnStartup(Entity *self) override; - void OnActivityStateChangeRequest(Entity* self, LWOOBJID senderID, int32_t value1, - int32_t value2, const std::u16string& stringValue) override; - void OnFireEventServerSide(Entity *self, Entity *sender, std::string args, int32_t param1, int32_t param2, - int32_t param3) override; + void OnStartup(Entity* self) override; + void OnActivityStateChangeRequest(Entity* self, LWOOBJID senderID, int32_t value1, + int32_t value2, const std::u16string& stringValue) override; + void OnFireEventServerSide(Entity* self, Entity* sender, std::string args, int32_t param1, int32_t param2, + int32_t param3) override; private: - std::u16string CannonIDVariable = u"CannonID"; + std::u16string CannonIDVariable = u"CannonID"; }; diff --git a/dWorldServer/ObjectIDManager.cpp b/dWorldServer/ObjectIDManager.cpp index bf8f770f..ef5fb9a5 100644 --- a/dWorldServer/ObjectIDManager.cpp +++ b/dWorldServer/ObjectIDManager.cpp @@ -10,54 +10,53 @@ #include "Game.h" // Static Variables -ObjectIDManager * ObjectIDManager::m_Address = nullptr; +ObjectIDManager* ObjectIDManager::m_Address = nullptr; static std::uniform_int_distribution uni(10000000, INT32_MAX); //! Initializes the manager void ObjectIDManager::Initialize(void) { - //this->currentRequestID = 0; - this->currentObjectID = uint32_t(1152921508165007067); //Initial value for this server's objectIDs + //this->currentRequestID = 0; + this->currentObjectID = uint32_t(1152921508165007067); //Initial value for this server's objectIDs } //! Requests a persistent ID void ObjectIDManager::RequestPersistentID(std::function callback) { - PersistentIDRequest * request = new PersistentIDRequest(); - request->requestID = ++this->currentRequestID; - request->callback = callback; + PersistentIDRequest* request = new PersistentIDRequest(); + request->requestID = ++this->currentRequestID; + request->callback = callback; - this->requests.push_back(request); + this->requests.push_back(request); - MasterPackets::SendPersistentIDRequest(Game::server, request->requestID); + MasterPackets::SendPersistentIDRequest(Game::server, request->requestID); } //! Handles a persistent ID response void ObjectIDManager::HandleRequestPersistentIDResponse(uint64_t requestID, uint32_t persistentID) { - for (uint32_t i = 0; i < this->requests.size(); ++i) { - if (this->requests[i]->requestID == requestID) { + for (uint32_t i = 0; i < this->requests.size(); ++i) { + if (this->requests[i]->requestID == requestID) { - // Call the callback function - this->requests[i]->callback(persistentID); + // Call the callback function + this->requests[i]->callback(persistentID); - // Then delete the request - delete this->requests[i]; - this->requests.erase(this->requests.begin() + i); - return; - } - } + // Then delete the request + delete this->requests[i]; + this->requests.erase(this->requests.begin() + i); + return; + } + } } //! Handles cases where we have to get a unique object ID synchronously -uint32_t ObjectIDManager::GenerateRandomObjectID() -{ - std::random_device rd; - - std::mt19937 rng(rd()); +uint32_t ObjectIDManager::GenerateRandomObjectID() { + std::random_device rd; - return uni(rng); + std::mt19937 rng(rd()); + + return uni(rng); } //! Generates an object ID server-sided (used for regular entities like smashables) uint32_t ObjectIDManager::GenerateObjectID(void) { - return ++this->currentObjectID; + return ++this->currentObjectID; } diff --git a/dWorldServer/ObjectIDManager.h b/dWorldServer/ObjectIDManager.h index 7bfc1d27..deef89fd 100644 --- a/dWorldServer/ObjectIDManager.h +++ b/dWorldServer/ObjectIDManager.h @@ -10,66 +10,66 @@ \brief A manager for handling object ID generation */ -//! The persistent ID request + //! The persistent ID request struct PersistentIDRequest { - uint64_t requestID; + uint64_t requestID; - std::function callback; + std::function callback; }; //! The Object ID Manager class ObjectIDManager { private: - static ObjectIDManager * m_Address; //!< The singleton instance + static ObjectIDManager* m_Address; //!< The singleton instance - std::vector requests; //!< All outstanding persistent ID requests - uint64_t currentRequestID; //!< The current request ID + std::vector requests; //!< All outstanding persistent ID requests + uint64_t currentRequestID; //!< The current request ID - uint32_t currentObjectID; //!< The current object ID + uint32_t currentObjectID; //!< The current object ID public: - //! The singleton instance - static ObjectIDManager * Instance() { - if (m_Address == 0) { - m_Address = new ObjectIDManager; - } + //! The singleton instance + static ObjectIDManager* Instance() { + if (m_Address == 0) { + m_Address = new ObjectIDManager; + } - return m_Address; - } + return m_Address; + } - //! Initializes the manager - void Initialize(void); + //! Initializes the manager + void Initialize(void); - //! Requests a persistent ID - /*! - \param callback The callback function - */ - void RequestPersistentID(std::function callback); + //! Requests a persistent ID + /*! + \param callback The callback function + */ + void RequestPersistentID(std::function callback); - //! Handles a persistent ID response - /*! - \param requestID The request ID - \param persistentID The persistent ID - */ - void HandleRequestPersistentIDResponse(uint64_t requestID, uint32_t persistentID); + //! Handles a persistent ID response + /*! + \param requestID The request ID + \param persistentID The persistent ID + */ + void HandleRequestPersistentIDResponse(uint64_t requestID, uint32_t persistentID); - //! Generates an object ID server-sided - /*! - \return A generated object ID - */ - uint32_t GenerateObjectID(void); + //! Generates an object ID server-sided + /*! + \return A generated object ID + */ + uint32_t GenerateObjectID(void); //! Generates a random object ID server-sided /*! \return A generated object ID */ - static uint32_t GenerateRandomObjectID(); + static uint32_t GenerateRandomObjectID(); - //! Generates a persistent object ID server-sided - /*! - \return A generated object ID - */ - uint32_t GeneratePersistentObjectID(void); + //! Generates a persistent object ID server-sided + /*! + \return A generated object ID + */ + uint32_t GeneratePersistentObjectID(void); }; diff --git a/dWorldServer/PerformanceManager.cpp b/dWorldServer/PerformanceManager.cpp index 6809fec0..85546f28 100644 --- a/dWorldServer/PerformanceManager.cpp +++ b/dWorldServer/PerformanceManager.cpp @@ -97,4 +97,4 @@ uint32_t PerformanceManager::GetServerFramerate() { } return m_CurrentProfile.serverFramerate; -} \ No newline at end of file +} diff --git a/dWorldServer/WorldServer.cpp b/dWorldServer/WorldServer.cpp index 6d85b2cd..df5484fd 100644 --- a/dWorldServer/WorldServer.cpp +++ b/dWorldServer/WorldServer.cpp @@ -103,8 +103,8 @@ int main(int argc, char** argv) { // Triggers the shutdown sequence at application exit std::atexit(WorldShutdownSequence); - signal(SIGINT, [](int){ WorldShutdownSequence(); }); - signal(SIGTERM, [](int){ WorldShutdownSequence(); }); + signal(SIGINT, [](int) { WorldShutdownSequence(); }); + signal(SIGTERM, [](int) { WorldShutdownSequence(); }); int zoneID = 1000; int cloneID = 0; @@ -143,14 +143,14 @@ int main(int argc, char** argv) { if (config.GetValue("disable_chat") == "1") chatDisabled = true; // Connect to CDClient - try { - CDClientDatabase::Connect("./res/CDServer.sqlite"); - } catch (CppSQLite3Exception& e) { - Game::logger->Log("WorldServer", "Unable to connect to CDServer SQLite Database"); - Game::logger->Log("WorldServer", "Error: %s", e.errorMessage()); - Game::logger->Log("WorldServer", "Error Code: %i", e.errorCode()); - return -1; - } + try { + CDClientDatabase::Connect("./res/CDServer.sqlite"); + } catch (CppSQLite3Exception& e) { + Game::logger->Log("WorldServer", "Unable to connect to CDServer SQLite Database"); + Game::logger->Log("WorldServer", "Error: %s", e.errorMessage()); + Game::logger->Log("WorldServer", "Error Code: %i", e.errorCode()); + return -1; + } CDClientManager::Instance()->Initialize(); @@ -162,17 +162,16 @@ int main(int argc, char** argv) { Diagnostics::SetProduceMemoryDump(config.GetValue("generate_dump") == "1"); - if (!config.GetValue("dump_folder").empty()) - { + if (!config.GetValue("dump_folder").empty()) { Diagnostics::SetOutDirectory(config.GetValue("dump_folder")); } try { - Database::Connect(mysql_host, mysql_database, mysql_username, mysql_password); - } catch (sql::SQLException& ex) { + Database::Connect(mysql_host, mysql_database, mysql_username, mysql_password); + } catch (sql::SQLException& ex) { Game::logger->Log("WorldServer", "Got an error while connecting to the database: %s", ex.what()); return 0; - } + } //Find out the master's IP: std::string masterIP = "localhost"; @@ -241,44 +240,44 @@ int main(int argc, char** argv) { // pre calculate the FDB checksum if (Game::config->GetValue("check_fdb") == "1") { - std::ifstream fileStream; + std::ifstream fileStream; - static const std::vector aliases = { - "res/CDServers.fdb", - "res/cdserver.fdb", - "res/CDClient.fdb", - "res/cdclient.fdb", - }; + static const std::vector aliases = { + "res/CDServers.fdb", + "res/cdserver.fdb", + "res/CDClient.fdb", + "res/cdclient.fdb", + }; - for (const auto& file : aliases) { - fileStream.open(file, std::ios::binary | std::ios::in); - if (fileStream.is_open()) { - break; - } + for (const auto& file : aliases) { + fileStream.open(file, std::ios::binary | std::ios::in); + if (fileStream.is_open()) { + break; } - - const int bufferSize = 1024; - MD5* md5 = new MD5(); - - char fileStreamBuffer[1024] = {}; - - while (!fileStream.eof()) { - memset(fileStreamBuffer, 0, bufferSize); - fileStream.read(fileStreamBuffer, bufferSize); - md5->update(fileStreamBuffer, fileStream.gcount()); - } - - fileStream.close(); - - const char* nullTerminateBuffer = "\0"; - md5->update(nullTerminateBuffer, 1); // null terminate the data - md5->finalize(); - databaseChecksum = md5->hexdigest(); - - delete md5; - - Game::logger->Log("WorldServer", "FDB Checksum calculated as: %s", databaseChecksum.c_str()); } + + const int bufferSize = 1024; + MD5* md5 = new MD5(); + + char fileStreamBuffer[1024] = {}; + + while (!fileStream.eof()) { + memset(fileStreamBuffer, 0, bufferSize); + fileStream.read(fileStreamBuffer, bufferSize); + md5->update(fileStreamBuffer, fileStream.gcount()); + } + + fileStream.close(); + + const char* nullTerminateBuffer = "\0"; + md5->update(nullTerminateBuffer, 1); // null terminate the data + md5->finalize(); + databaseChecksum = md5->hexdigest(); + + delete md5; + + Game::logger->Log("WorldServer", "FDB Checksum calculated as: %s", databaseChecksum.c_str()); + } } while (true) { @@ -293,12 +292,9 @@ int main(int argc, char** argv) { const auto occupied = UserManager::Instance()->GetUserCount() != 0; - if (!ready) - { + if (!ready) { currentFramerate = highFrameRate; - } - else - { + } else { currentFramerate = PerformanceManager::GetServerFramerate(); } @@ -316,8 +312,7 @@ int main(int argc, char** argv) { Game::logger->Log("WorldServer", "Game loop running but no connection to master for %d frames, shutting down", framesToWaitForMaster); worldShutdownSequenceStarted = true; } - } - else framesSinceMasterDisconnect = 0; + } else framesSinceMasterDisconnect = 0; // Check if we're still connected to chat: if (!chatConnected) { @@ -329,8 +324,7 @@ int main(int argc, char** argv) { Game::chatServer->Connect(masterIP.c_str(), chatPort, "3.25 ND1", 8); } - } - else framesSinceChatDisconnect = 0; + } else framesSinceChatDisconnect = 0; //In world we'd update our other systems here. @@ -387,8 +381,7 @@ int main(int argc, char** argv) { timeSpent += std::chrono::duration_cast(t2 - t1).count(); Game::server->DeallocatePacket(packet); packet = nullptr; - } - else { + } else { break; } } @@ -408,18 +401,14 @@ int main(int argc, char** argv) { framesSinceLastFlush = 0; } else framesSinceLastFlush++; - if (zoneID != 0 && !occupied) - { + if (zoneID != 0 && !occupied) { framesSinceLastUser++; //If we haven't had any players for a while, time out and shut down: - if (framesSinceLastUser == (cloneID != 0 ? 4000 : 40000)) - { + if (framesSinceLastUser == (cloneID != 0 ? 4000 : 40000)) { worldShutdownSequenceStarted = true; } - } - else - { + } else { framesSinceLastUser = 0; } @@ -431,8 +420,7 @@ int main(int argc, char** argv) { if (PropertyManagementComponent::Instance() != nullptr) { PropertyManagementComponent::Instance()->Save(); } - } - else framesSinceLastUsersSave++; + } else framesSinceLastUsersSave++; //Every 10 min we ping our sql server to keep it alive hopefully: if (framesSinceLastSQLPing >= 40000) { @@ -450,8 +438,7 @@ int main(int argc, char** argv) { delete stmt; framesSinceLastSQLPing = 0; - } - else framesSinceLastSQLPing++; + } else framesSinceLastSQLPing++; Metrics::EndMeasurement(MetricVariable::GameLoop); @@ -462,14 +449,12 @@ int main(int argc, char** argv) { Metrics::EndMeasurement(MetricVariable::Sleep); - if (!ready && Game::server->GetIsConnectedToMaster()) - { + if (!ready && Game::server->GetIsConnectedToMaster()) { // Some delay is required here or else we crash the client? framesSinceMasterStatus++; - if (framesSinceMasterStatus >= 200) - { + if (framesSinceMasterStatus >= 200) { Game::logger->Log("WorldServer", "Finished loading world with zone (%i), ready up!", Game::server->GetZoneID()); MasterPackets::SendWorldReady(Game::server, Game::server->GetZoneID(), Game::server->GetInstanceID()); @@ -490,7 +475,7 @@ int main(int argc, char** argv) { return EXIT_SUCCESS; } -dLogger * SetupLogger(int zoneID, int instanceID) { +dLogger* SetupLogger(int zoneID, int instanceID) { std::string logPath = "./logs/WorldServer_" + std::to_string(zoneID) + "_" + std::to_string(instanceID) + "_" + std::to_string(time(nullptr)) + ".log"; bool logToConsole = false; bool logDebugStatements = false; @@ -504,13 +489,13 @@ dLogger * SetupLogger(int zoneID, int instanceID) { void HandlePacketChat(Packet* packet) { if (packet->data[0] == ID_DISCONNECTION_NOTIFICATION || packet->data[0] == ID_CONNECTION_LOST) { - Game::logger->Log("WorldServer", "Lost our connection to chat, zone(%i), instance(%i)", Game::server->GetZoneID(), Game::server->GetInstanceID()); + Game::logger->Log("WorldServer", "Lost our connection to chat, zone(%i), instance(%i)", Game::server->GetZoneID(), Game::server->GetInstanceID()); chatConnected = false; } if (packet->data[0] == ID_CONNECTION_REQUEST_ACCEPTED) { - Game::logger->Log("WorldServer", "Established connection to chat, zone(%i), instance (%i)",Game::server -> GetZoneID(), Game::server -> GetInstanceID()); + Game::logger->Log("WorldServer", "Established connection to chat, zone(%i), instance (%i)", Game::server->GetZoneID(), Game::server->GetInstanceID()); Game::chatSysAddr = packet->systemAddress; chatConnected = true; @@ -590,8 +575,7 @@ void HandlePacketChat(Packet* packet) { auto* entity = EntityManager::Instance()->GetEntity(playerId); - if (entity != nullptr) - { + if (entity != nullptr) { entity->GetParentUser()->SetMuteExpire(expire); entity->GetCharacter()->SendMuteNotice(); @@ -613,8 +597,7 @@ void HandlePacketChat(Packet* packet) { inStream.Read(teamID); bool deleteTeam = inStream.ReadBit(); - if (deleteTeam) - { + if (deleteTeam) { TeamManager::Instance()->DeleteTeam(teamID); Game::logger->Log("WorldServer", "Deleting team (%llu)", teamID); @@ -625,8 +608,7 @@ void HandlePacketChat(Packet* packet) { inStream.Read(lootOption); inStream.Read(memberCount); Game::logger->Log("WorldServer", "Updating team (%llu), (%i), (%i)", teamID, lootOption, memberCount); - for (char i = 0; i < memberCount; i++) - { + for (char i = 0; i < memberCount; i++) { LWOOBJID member = LWOOBJID_EMPTY; inStream.Read(member); members.push_back(member); @@ -659,16 +641,14 @@ void HandlePacket(Packet* packet) { auto* entity = EntityManager::Instance()->GetEntity(c->GetObjectID()); - if (!entity) - { + if (!entity) { entity = Player::GetPlayer(packet->systemAddress); } if (entity) { auto* skillComponent = entity->GetComponent(); - if (skillComponent != nullptr) - { + if (skillComponent != nullptr) { skillComponent->Reset(); } @@ -708,139 +688,138 @@ void HandlePacket(Packet* packet) { if (packet->data[1] == MASTER) { switch (packet->data[3]) { - case MSG_MASTER_REQUEST_PERSISTENT_ID_RESPONSE: { - uint64_t requestID = PacketUtils::ReadPacketU64(8, packet); - uint32_t objectID = PacketUtils::ReadPacketU32(16, packet); - ObjectIDManager::Instance()->HandleRequestPersistentIDResponse(requestID, objectID); - break; - } + case MSG_MASTER_REQUEST_PERSISTENT_ID_RESPONSE: { + uint64_t requestID = PacketUtils::ReadPacketU64(8, packet); + uint32_t objectID = PacketUtils::ReadPacketU32(16, packet); + ObjectIDManager::Instance()->HandleRequestPersistentIDResponse(requestID, objectID); + break; + } - case MSG_MASTER_REQUEST_ZONE_TRANSFER_RESPONSE: { - uint64_t requestID = PacketUtils::ReadPacketU64(8, packet); - ZoneInstanceManager::Instance()->HandleRequestZoneTransferResponse(requestID, packet); - break; - } + case MSG_MASTER_REQUEST_ZONE_TRANSFER_RESPONSE: { + uint64_t requestID = PacketUtils::ReadPacketU64(8, packet); + ZoneInstanceManager::Instance()->HandleRequestZoneTransferResponse(requestID, packet); + break; + } - case MSG_MASTER_SESSION_KEY_RESPONSE: { - //Read our session key and to which user it belongs: - RakNet::BitStream inStream(packet->data, packet->length, false); - uint64_t header = inStream.Read(header); - uint32_t sessionKey = 0; - std::string username; + case MSG_MASTER_SESSION_KEY_RESPONSE: { + //Read our session key and to which user it belongs: + RakNet::BitStream inStream(packet->data, packet->length, false); + uint64_t header = inStream.Read(header); + uint32_t sessionKey = 0; + std::string username; - inStream.Read(sessionKey); - username = PacketUtils::ReadString(12, packet, false); + inStream.Read(sessionKey); + username = PacketUtils::ReadString(12, packet, false); - //Find them: - auto it = m_PendingUsers.find(username); - if (it == m_PendingUsers.end()) return; + //Find them: + auto it = m_PendingUsers.find(username); + if (it == m_PendingUsers.end()) return; - //Convert our key: - std::string userHash = std::to_string(sessionKey); - userHash = md5(userHash); + //Convert our key: + std::string userHash = std::to_string(sessionKey); + userHash = md5(userHash); - //Verify it: - if (userHash != it->second.hash) { - Game::logger->Log("WorldServer", "SOMEONE IS TRYING TO HACK? SESSION KEY MISMATCH: ours: %s != master: %s", userHash.c_str(), it->second.hash.c_str()); - Game::server->Disconnect(it->second.sysAddr, SERVER_DISCON_INVALID_SESSION_KEY); - return; - } - else { - Game::logger->Log("WorldServer", "User %s authenticated with correct key.", username.c_str()); + //Verify it: + if (userHash != it->second.hash) { + Game::logger->Log("WorldServer", "SOMEONE IS TRYING TO HACK? SESSION KEY MISMATCH: ours: %s != master: %s", userHash.c_str(), it->second.hash.c_str()); + Game::server->Disconnect(it->second.sysAddr, SERVER_DISCON_INVALID_SESSION_KEY); + return; + } else { + Game::logger->Log("WorldServer", "User %s authenticated with correct key.", username.c_str()); - UserManager::Instance()->DeleteUser(packet->systemAddress); + UserManager::Instance()->DeleteUser(packet->systemAddress); - //Create our user and send them in: - UserManager::Instance()->CreateUser(it->second.sysAddr, username, userHash); + //Create our user and send them in: + UserManager::Instance()->CreateUser(it->second.sysAddr, username, userHash); - auto zone = dZoneManager::Instance()->GetZone(); - if (zone) { - float x = 0.0f; - float y = 0.0f; - float z = 0.0f; + auto zone = dZoneManager::Instance()->GetZone(); + if (zone) { + float x = 0.0f; + float y = 0.0f; + float z = 0.0f; - if (zone->GetZoneID().GetMapID() == 1100) { - auto pos = zone->GetSpawnPos(); - x = pos.x; - y = pos.y; - z = pos.z; - } - - WorldPackets::SendLoadStaticZone(it->second.sysAddr, x, y, z, zone->GetChecksum()); + if (zone->GetZoneID().GetMapID() == 1100) { + auto pos = zone->GetSpawnPos(); + x = pos.x; + y = pos.y; + z = pos.z; } - if (Game::server->GetZoneID() == 0) { - //Since doing this reroute breaks the client's request, we have to call this manually. - UserManager::Instance()->RequestCharacterList(it->second.sysAddr); - } - - m_PendingUsers.erase(username); - - //Notify master: - { - CBITSTREAM; - PacketUtils::WriteHeader(bitStream, MASTER, MSG_MASTER_PLAYER_ADDED); - bitStream.Write((LWOMAPID)Game::server->GetZoneID()); - bitStream.Write((LWOINSTANCEID)instanceID); - Game::server->SendToMaster(&bitStream); - } + WorldPackets::SendLoadStaticZone(it->second.sysAddr, x, y, z, zone->GetChecksum()); } - break; + if (Game::server->GetZoneID() == 0) { + //Since doing this reroute breaks the client's request, we have to call this manually. + UserManager::Instance()->RequestCharacterList(it->second.sysAddr); + } + + m_PendingUsers.erase(username); + + //Notify master: + { + CBITSTREAM; + PacketUtils::WriteHeader(bitStream, MASTER, MSG_MASTER_PLAYER_ADDED); + bitStream.Write((LWOMAPID)Game::server->GetZoneID()); + bitStream.Write((LWOINSTANCEID)instanceID); + Game::server->SendToMaster(&bitStream); + } } - case MSG_MASTER_AFFIRM_TRANSFER_REQUEST: { - const uint64_t requestID = PacketUtils::ReadPacketU64(8, packet); - Game::logger->Log("MasterServer", "Got affirmation request of transfer %llu", requestID); + break; + } + case MSG_MASTER_AFFIRM_TRANSFER_REQUEST: { + const uint64_t requestID = PacketUtils::ReadPacketU64(8, packet); - CBITSTREAM + Game::logger->Log("MasterServer", "Got affirmation request of transfer %llu", requestID); + + CBITSTREAM PacketUtils::WriteHeader(bitStream, MASTER, MSG_MASTER_AFFIRM_TRANSFER_RESPONSE); - bitStream.Write(requestID); - Game::server->SendToMaster(&bitStream); + bitStream.Write(requestID); + Game::server->SendToMaster(&bitStream); - break; + break; + } + + case MSG_MASTER_SHUTDOWN: { + worldShutdownSequenceStarted = true; + Game::logger->Log("WorldServer", "Got shutdown request from master, zone (%i), instance (%i)", Game::server->GetZoneID(), Game::server->GetInstanceID()); + break; + } + + case MSG_MASTER_NEW_SESSION_ALERT: { + RakNet::BitStream inStream(packet->data, packet->length, false); + uint64_t header = inStream.Read(header); + uint32_t sessionKey = inStream.Read(sessionKey); + + std::string username; + + uint32_t len; + inStream.Read(len); + + for (int i = 0; i < len; i++) { + char character; inStream.Read(character); + username += character; } - case MSG_MASTER_SHUTDOWN: { - worldShutdownSequenceStarted = true; - Game::logger->Log("WorldServer", "Got shutdown request from master, zone (%i), instance (%i)", Game::server->GetZoneID(), Game::server->GetInstanceID()); - break; + //Find them: + User* user = UserManager::Instance()->GetUser(username.c_str()); + if (!user) { + Game::logger->Log("WorldServer", "Got new session alert for user %s, but they're not logged in.", username.c_str()); + return; } - case MSG_MASTER_NEW_SESSION_ALERT: { - RakNet::BitStream inStream(packet->data, packet->length, false); - uint64_t header = inStream.Read(header); - uint32_t sessionKey = inStream.Read(sessionKey); - - std::string username; - - uint32_t len; - inStream.Read(len); - - for (int i = 0; i < len; i++) { - char character; inStream.Read(character); - username += character; - } - - //Find them: - User* user = UserManager::Instance()->GetUser(username.c_str()); - if (!user) { - Game::logger->Log("WorldServer", "Got new session alert for user %s, but they're not logged in.", username.c_str()); - return; - } - - //Check the key: - if (sessionKey != std::atoi(user->GetSessionKey().c_str())) { - Game::logger->Log("WorldServer", "Got new session alert for user %s, but the session key is invalid.", username.c_str()); - Game::server->Disconnect(user->GetSystemAddress(), SERVER_DISCON_INVALID_SESSION_KEY); - return; - } - break; + //Check the key: + if (sessionKey != std::atoi(user->GetSessionKey().c_str())) { + Game::logger->Log("WorldServer", "Got new session alert for user %s, but the session key is invalid.", username.c_str()); + Game::server->Disconnect(user->GetSystemAddress(), SERVER_DISCON_INVALID_SESSION_KEY); + return; } + break; + } - default: - Game::logger->Log("WorldServer", "Unknown packet ID from master %i", int(packet->data[3])); + default: + Game::logger->Log("WorldServer", "Unknown packet ID from master %i", int(packet->data[3])); } return; @@ -849,403 +828,397 @@ void HandlePacket(Packet* packet) { if (packet->data[1] != WORLD) return; switch (packet->data[3]) { - case MSG_WORLD_CLIENT_VALIDATION: { - std::string username = PacketUtils::ReadString(0x08, packet, true); - std::string sessionKey = PacketUtils::ReadString(74, packet, true); - std::string clientDatabaseChecksum = PacketUtils::ReadString(packet->length - 33, packet, false); + case MSG_WORLD_CLIENT_VALIDATION: { + std::string username = PacketUtils::ReadString(0x08, packet, true); + std::string sessionKey = PacketUtils::ReadString(74, packet, true); + std::string clientDatabaseChecksum = PacketUtils::ReadString(packet->length - 33, packet, false); - // sometimes client puts a null terminator at the end of the checksum and sometimes doesn't, weird - clientDatabaseChecksum = clientDatabaseChecksum.substr(0, 32); + // sometimes client puts a null terminator at the end of the checksum and sometimes doesn't, weird + clientDatabaseChecksum = clientDatabaseChecksum.substr(0, 32); - // If the check is turned on, validate the client's database checksum. - if (Game::config->GetValue("check_fdb") == "1" && !databaseChecksum.empty()) { - uint32_t gmLevel = 0; - auto* stmt = Database::CreatePreppedStmt("SELECT gm_level FROM accounts WHERE name=? LIMIT 1;"); - stmt->setString(1, username.c_str()); + // If the check is turned on, validate the client's database checksum. + if (Game::config->GetValue("check_fdb") == "1" && !databaseChecksum.empty()) { + uint32_t gmLevel = 0; + auto* stmt = Database::CreatePreppedStmt("SELECT gm_level FROM accounts WHERE name=? LIMIT 1;"); + stmt->setString(1, username.c_str()); - auto* res = stmt->executeQuery(); - while (res->next()) { - gmLevel = res->getInt(1); - } + auto* res = stmt->executeQuery(); + while (res->next()) { + gmLevel = res->getInt(1); + } - delete stmt; - delete res; + delete stmt; + delete res; - // Developers may skip this check - if (gmLevel < 8 && clientDatabaseChecksum != databaseChecksum) { - Game::logger->Log("WorldServer", "Client's database checksum does not match the server's, aborting connection."); - Game::server->Disconnect(packet->systemAddress, SERVER_DISCON_KICK); + // Developers may skip this check + if (gmLevel < 8 && clientDatabaseChecksum != databaseChecksum) { + Game::logger->Log("WorldServer", "Client's database checksum does not match the server's, aborting connection."); + Game::server->Disconnect(packet->systemAddress, SERVER_DISCON_KICK); + return; + } + } + + //Request the session info from Master: + CBITSTREAM; + PacketUtils::WriteHeader(bitStream, MASTER, MSG_MASTER_REQUEST_SESSION_KEY); + PacketUtils::WriteString(bitStream, username, 64); + Game::server->SendToMaster(&bitStream); + + //Insert info into our pending list + tempSessionInfo info; + info.sysAddr = SystemAddress(packet->systemAddress); + info.hash = sessionKey; + m_PendingUsers.insert(std::make_pair(username, info)); + + break; + } + + case MSG_WORLD_CLIENT_CHARACTER_LIST_REQUEST: { + //We need to delete the entity first, otherwise the char list could delete it while it exists in the world! + if (Game::server->GetZoneID() != 0) { + auto user = UserManager::Instance()->GetUser(packet->systemAddress); + if (!user) return; + EntityManager::Instance()->DestroyEntity(user->GetLastUsedChar()->GetEntity()); + } + + //This loops prevents users who aren't authenticated to double-request the char list, which + //would make the login screen freeze sometimes. + if (m_PendingUsers.size() > 0) { + for (auto it : m_PendingUsers) { + if (it.second.sysAddr == packet->systemAddress) { return; } } - - //Request the session info from Master: - CBITSTREAM; - PacketUtils::WriteHeader(bitStream, MASTER, MSG_MASTER_REQUEST_SESSION_KEY); - PacketUtils::WriteString(bitStream, username, 64); - Game::server->SendToMaster(&bitStream); - - //Insert info into our pending list - tempSessionInfo info; - info.sysAddr = SystemAddress(packet->systemAddress); - info.hash = sessionKey; - m_PendingUsers.insert(std::make_pair(username, info)); - - break; } - case MSG_WORLD_CLIENT_CHARACTER_LIST_REQUEST: { - //We need to delete the entity first, otherwise the char list could delete it while it exists in the world! - if (Game::server->GetZoneID() != 0) { - auto user = UserManager::Instance()->GetUser(packet->systemAddress); - if (!user) return; - EntityManager::Instance()->DestroyEntity(user->GetLastUsedChar()->GetEntity()); - } + UserManager::Instance()->RequestCharacterList(packet->systemAddress); + break; + } - //This loops prevents users who aren't authenticated to double-request the char list, which - //would make the login screen freeze sometimes. - if (m_PendingUsers.size() > 0) { - for (auto it : m_PendingUsers) { - if (it.second.sysAddr == packet->systemAddress) { - return; - } + case MSG_WORLD_CLIENT_GAME_MSG: { + RakNet::BitStream bitStream(packet->data, packet->length, false); + + uint64_t header; + LWOOBJID objectID; + uint16_t messageID; + + bitStream.Read(header); + bitStream.Read(objectID); + bitStream.Read(messageID); + + RakNet::BitStream dataStream; + bitStream.Read(dataStream, bitStream.GetNumberOfUnreadBits()); + + GameMessageHandler::HandleMessage(&dataStream, packet->systemAddress, objectID, GAME_MSG(messageID)); + break; + } + + case MSG_WORLD_CLIENT_CHARACTER_CREATE_REQUEST: { + UserManager::Instance()->CreateCharacter(packet->systemAddress, packet); + break; + } + + case MSG_WORLD_CLIENT_LOGIN_REQUEST: { + RakNet::BitStream inStream(packet->data, packet->length, false); + uint64_t header = inStream.Read(header); + + LWOOBJID playerID = 0; + inStream.Read(playerID); + playerID = GeneralUtils::ClearBit(playerID, OBJECT_BIT_CHARACTER); + playerID = GeneralUtils::ClearBit(playerID, OBJECT_BIT_PERSISTENT); + + auto user = UserManager::Instance()->GetUser(packet->systemAddress); + + if (user) { + auto lastCharacter = user->GetLoggedInChar(); + // This means we swapped characters and we need to remove the previous player from the container. + if (static_cast(lastCharacter) != playerID) { + CBITSTREAM; + PacketUtils::WriteHeader(bitStream, CHAT_INTERNAL, MSG_CHAT_INTERNAL_PLAYER_REMOVED_NOTIFICATION); + bitStream.Write(lastCharacter); + Game::chatServer->Send(&bitStream, SYSTEM_PRIORITY, RELIABLE, 0, Game::chatSysAddr, false); + } + } + + UserManager::Instance()->LoginCharacter(packet->systemAddress, static_cast(playerID)); + break; + } + + case MSG_WORLD_CLIENT_CHARACTER_DELETE_REQUEST: { + UserManager::Instance()->DeleteCharacter(packet->systemAddress, packet); + UserManager::Instance()->RequestCharacterList(packet->systemAddress); + break; + } + + case MSG_WORLD_CLIENT_CHARACTER_RENAME_REQUEST: { + UserManager::Instance()->RenameCharacter(packet->systemAddress, packet); + break; + } + + case MSG_WORLD_CLIENT_LEVEL_LOAD_COMPLETE: { + Game::logger->Log("WorldServer", "Received level load complete from user."); + User* user = UserManager::Instance()->GetUser(packet->systemAddress); + if (user) { + Character* c = user->GetLastUsedChar(); + if (c != nullptr) { + std::u16string username = GeneralUtils::ASCIIToUTF16(c->GetName()); + Game::server->GetReplicaManager()->AddParticipant(packet->systemAddress); + + EntityInfo info{}; + info.lot = 1; + Entity* player = EntityManager::Instance()->CreateEntity(info, UserManager::Instance()->GetUser(packet->systemAddress)); + + WorldPackets::SendCreateCharacter(packet->systemAddress, player, c->GetXMLData(), username, c->GetGMLevel()); + WorldPackets::SendServerState(packet->systemAddress); + + const auto respawnPoint = player->GetCharacter()->GetRespawnPoint(dZoneManager::Instance()->GetZone()->GetWorldID()); + + EntityManager::Instance()->ConstructEntity(player, UNASSIGNED_SYSTEM_ADDRESS, true); + + if (respawnPoint != NiPoint3::ZERO) { + GameMessages::SendPlayerReachedRespawnCheckpoint(player, respawnPoint, NiQuaternion::IDENTITY); } - } - UserManager::Instance()->RequestCharacterList(packet->systemAddress); - break; - } + EntityManager::Instance()->ConstructAllEntities(packet->systemAddress); - case MSG_WORLD_CLIENT_GAME_MSG: { - RakNet::BitStream bitStream(packet->data, packet->length, false); + auto* characterComponent = player->GetComponent(); + if (characterComponent) { + player->GetComponent()->RocketUnEquip(player); + } - uint64_t header; - LWOOBJID objectID; - uint16_t messageID; + c->SetRetroactiveFlags(); - bitStream.Read(header); - bitStream.Read(objectID); - bitStream.Read(messageID); + player->RetroactiveVaultSize(); - RakNet::BitStream dataStream; - bitStream.Read(dataStream, bitStream.GetNumberOfUnreadBits()); + player->GetCharacter()->SetTargetScene(""); - GameMessageHandler::HandleMessage(&dataStream, packet->systemAddress, objectID, GAME_MSG(messageID)); - break; - } + // Fix the destroyable component + auto* destroyableComponent = player->GetComponent(); - case MSG_WORLD_CLIENT_CHARACTER_CREATE_REQUEST: { - UserManager::Instance()->CreateCharacter(packet->systemAddress, packet); - break; - } + if (destroyableComponent != nullptr) { + destroyableComponent->FixStats(); + } - case MSG_WORLD_CLIENT_LOGIN_REQUEST: { - RakNet::BitStream inStream(packet->data, packet->length, false); - uint64_t header = inStream.Read(header); + //Tell the player to generate BBB models, if any: + if (g_CloneID != 0) { + const auto& worldId = dZoneManager::Instance()->GetZone()->GetZoneID(); - LWOOBJID playerID = 0; - inStream.Read(playerID); - playerID = GeneralUtils::ClearBit(playerID, OBJECT_BIT_CHARACTER); - playerID = GeneralUtils::ClearBit(playerID, OBJECT_BIT_PERSISTENT); + const auto zoneId = Game::server->GetZoneID(); + const auto cloneId = g_CloneID; - auto user = UserManager::Instance()->GetUser(packet->systemAddress); + auto query = CDClientDatabase::CreatePreppedStmt( + "SELECT id FROM PropertyTemplate WHERE mapID = ?;"); + query.bind(1, (int)zoneId); + + auto result = query.execQuery(); + + if (result.eof() || result.fieldIsNull(0)) { + Game::logger->Log("WorldServer", "No property templates found for zone %d, not sending BBB", zoneId); + goto noBBB; + } + + //Check for BBB models: + auto stmt = Database::CreatePreppedStmt("SELECT ugc_id FROM properties_contents WHERE lot=14 AND property_id=?"); + + int templateId = result.getIntField(0); + + result.finalize(); + + auto* propertyLookup = Database::CreatePreppedStmt("SELECT * FROM properties WHERE template_id = ? AND clone_id = ?;"); + + propertyLookup->setInt(1, templateId); + propertyLookup->setInt64(2, g_CloneID); + + auto* propertyEntry = propertyLookup->executeQuery(); + uint64_t propertyId = 0; + + if (propertyEntry->next()) { + propertyId = propertyEntry->getUInt64(1); + } + + delete propertyLookup; + + stmt->setUInt64(1, propertyId); + auto res = stmt->executeQuery(); + while (res->next()) { + Game::logger->Log("UGC", "Getting lxfml ugcID: %u", res->getUInt(1)); + + //Get lxfml: + auto stmtL = Database::CreatePreppedStmt("SELECT lxfml from ugc where id=?"); + stmtL->setUInt(1, res->getUInt(1)); + + auto lxres = stmtL->executeQuery(); + + while (lxres->next()) { + auto lxfml = lxres->getBlob(1); + + lxfml->seekg(0, std::ios::end); + size_t lxfmlSize = lxfml->tellg(); + lxfml->seekg(0); + + //Send message: + { + LWOOBJID blueprintID = res->getUInt(1); + blueprintID = GeneralUtils::SetBit(blueprintID, OBJECT_BIT_CHARACTER); + blueprintID = GeneralUtils::SetBit(blueprintID, OBJECT_BIT_PERSISTENT); + + CBITSTREAM; + PacketUtils::WriteHeader(bitStream, CLIENT, MSG_CLIENT_BLUEPRINT_SAVE_RESPONSE); + bitStream.Write(0); //always zero so that a check on the client passes + bitStream.Write(0); + bitStream.Write(1); + bitStream.Write(blueprintID); + + bitStream.Write(lxfmlSize + 9); + + //Write a fake sd0 header: + bitStream.Write(0x73); //s + bitStream.Write(0x64); //d + bitStream.Write(0x30); //0 + bitStream.Write(0x01); //1 + bitStream.Write(0xFF); //end magic + + bitStream.Write(lxfmlSize); + + for (size_t i = 0; i < lxfmlSize; ++i) + bitStream.Write(lxfml->get()); + + SystemAddress sysAddr = packet->systemAddress; + SEND_PACKET; + PacketUtils::SavePacket("lxfml packet " + std::to_string(res->getUInt(1)) + ".bin", (char*)bitStream.GetData(), bitStream.GetNumberOfBytesUsed()); + } + } + + delete stmtL; + delete lxres; + } + + delete stmt; + delete res; + } + + noBBB: + + // Tell the client it's done loading: + GameMessages::SendInvalidZoneTransferList(player, packet->systemAddress, GeneralUtils::ASCIIToUTF16(Game::config->GetValue("source")), u"", false, false); + GameMessages::SendServerDoneLoadingAllObjects(player, packet->systemAddress); + + //Send the player it's mail count: + //update: this might not be needed so im going to try disabling this here. + //Mail::HandleNotificationRequest(packet->systemAddress, player->GetObjectID()); + + //Notify chat that a player has loaded: + { + const auto& playerName = player->GetCharacter()->GetName(); + //RakNet::RakString playerName(player->GetCharacter()->GetName().c_str()); - if (user) { - auto lastCharacter = user->GetLoggedInChar(); - // This means we swapped characters and we need to remove the previous player from the container. - if (static_cast(lastCharacter) != playerID) { CBITSTREAM; - PacketUtils::WriteHeader(bitStream, CHAT_INTERNAL, MSG_CHAT_INTERNAL_PLAYER_REMOVED_NOTIFICATION); - bitStream.Write(lastCharacter); + PacketUtils::WriteHeader(bitStream, CHAT_INTERNAL, MSG_CHAT_INTERNAL_PLAYER_ADDED_NOTIFICATION); + bitStream.Write(player->GetObjectID()); + bitStream.Write(playerName.size()); + for (size_t i = 0; i < playerName.size(); i++) { + bitStream.Write(playerName[i]); + } + + auto zone = dZoneManager::Instance()->GetZone()->GetZoneID(); + bitStream.Write(zone.GetMapID()); + bitStream.Write(zone.GetInstanceID()); + bitStream.Write(zone.GetCloneID()); + bitStream.Write(player->GetParentUser()->GetMuteExpire()); + Game::chatServer->Send(&bitStream, SYSTEM_PRIORITY, RELIABLE, 0, Game::chatSysAddr, false); } + } else { + Game::logger->Log("WorldServer", "Couldn't find character to log in with for user %s (%i)!", user->GetUsername().c_str(), user->GetAccountID()); + Game::server->Disconnect(packet->systemAddress, SERVER_DISCON_CHARACTER_NOT_FOUND); } + } else { + Game::logger->Log("WorldServer", "Couldn't get user for level load complete!"); + } + break; + } - UserManager::Instance()->LoginCharacter(packet->systemAddress, static_cast(playerID)); - break; + case MSG_WORLD_CLIENT_POSITION_UPDATE: { + ClientPackets::HandleClientPositionUpdate(packet->systemAddress, packet); + break; + } + + case MSG_WORLD_CLIENT_MAIL: { + RakNet::BitStream bitStream(packet->data, packet->length, false); + LWOOBJID space; + bitStream.Read(space); + Mail::HandleMailStuff(&bitStream, packet->systemAddress, UserManager::Instance()->GetUser(packet->systemAddress)->GetLastUsedChar()->GetEntity()); + break; + } + + case MSG_WORLD_CLIENT_ROUTE_PACKET: { + //Yeet to chat + CINSTREAM; + uint64_t header = 0; + uint32_t size = 0; + inStream.Read(header); + inStream.Read(size); + + if (size > 20000) { + Game::logger->Log("WorldServer", "Tried to route a packet with a read size > 20000, so likely a false packet."); + return; } - case MSG_WORLD_CLIENT_CHARACTER_DELETE_REQUEST: { - UserManager::Instance()->DeleteCharacter(packet->systemAddress, packet); - UserManager::Instance()->RequestCharacterList(packet->systemAddress); - break; + CBITSTREAM; + + PacketUtils::WriteHeader(bitStream, CHAT, packet->data[14]); + + //We need to insert the player's objectID so the chat server can find who originated this request: + LWOOBJID objectID = 0; + auto user = UserManager::Instance()->GetUser(packet->systemAddress); + if (user) { + objectID = user->GetLastUsedChar()->GetObjectID(); } - case MSG_WORLD_CLIENT_CHARACTER_RENAME_REQUEST: { - UserManager::Instance()->RenameCharacter(packet->systemAddress, packet); - break; + bitStream.Write(objectID); + + //Now write the rest of the data: + auto data = inStream.GetData(); + for (uint32_t i = 0; i < size; ++i) { + bitStream.Write(data[i + 23]); } - case MSG_WORLD_CLIENT_LEVEL_LOAD_COMPLETE: { - Game::logger->Log("WorldServer", "Received level load complete from user."); - User* user = UserManager::Instance()->GetUser(packet->systemAddress); - if (user) { - Character* c = user->GetLastUsedChar(); - if (c != nullptr) { - std::u16string username = GeneralUtils::ASCIIToUTF16(c->GetName()); - Game::server->GetReplicaManager()->AddParticipant(packet->systemAddress); + Game::chatServer->Send(&bitStream, SYSTEM_PRIORITY, RELIABLE_ORDERED, 0, Game::chatSysAddr, false); + break; + } - EntityInfo info {}; - info.lot = 1; - Entity* player = EntityManager::Instance()->CreateEntity(info, UserManager::Instance()->GetUser(packet->systemAddress)); + case MSG_WORLD_CLIENT_STRING_CHECK: { + ClientPackets::HandleChatModerationRequest(packet->systemAddress, packet); + break; + } - WorldPackets::SendCreateCharacter(packet->systemAddress, player, c->GetXMLData(), username, c->GetGMLevel()); - WorldPackets::SendServerState(packet->systemAddress); - - const auto respawnPoint = player->GetCharacter()->GetRespawnPoint(dZoneManager::Instance()->GetZone()->GetWorldID()); - - EntityManager::Instance()->ConstructEntity(player, UNASSIGNED_SYSTEM_ADDRESS, true); - - if (respawnPoint != NiPoint3::ZERO) - { - GameMessages::SendPlayerReachedRespawnCheckpoint(player, respawnPoint, NiQuaternion::IDENTITY); - } - - EntityManager::Instance()->ConstructAllEntities(packet->systemAddress); - - auto* characterComponent = player->GetComponent(); - if (characterComponent) { - player->GetComponent()->RocketUnEquip(player); - } - - c->SetRetroactiveFlags(); - - player->RetroactiveVaultSize(); - - player->GetCharacter()->SetTargetScene(""); - - // Fix the destroyable component - auto* destroyableComponent = player->GetComponent(); - - if (destroyableComponent != nullptr) - { - destroyableComponent->FixStats(); - } - - //Tell the player to generate BBB models, if any: - if (g_CloneID != 0) { - const auto& worldId = dZoneManager::Instance()->GetZone()->GetZoneID(); - - const auto zoneId = Game::server->GetZoneID(); - const auto cloneId = g_CloneID; - - auto query = CDClientDatabase::CreatePreppedStmt( - "SELECT id FROM PropertyTemplate WHERE mapID = ?;"); - query.bind(1, (int) zoneId); - - auto result = query.execQuery(); - - if (result.eof() || result.fieldIsNull(0)) { - Game::logger->Log("WorldServer", "No property templates found for zone %d, not sending BBB", zoneId); - goto noBBB; - } - - //Check for BBB models: - auto stmt = Database::CreatePreppedStmt("SELECT ugc_id FROM properties_contents WHERE lot=14 AND property_id=?"); - - int templateId = result.getIntField(0); - - result.finalize(); - - auto* propertyLookup = Database::CreatePreppedStmt("SELECT * FROM properties WHERE template_id = ? AND clone_id = ?;"); - - propertyLookup->setInt(1, templateId); - propertyLookup->setInt64(2, g_CloneID); - - auto* propertyEntry = propertyLookup->executeQuery(); - uint64_t propertyId = 0; - - if (propertyEntry->next()) { - propertyId = propertyEntry->getUInt64(1); - } - - delete propertyLookup; - - stmt->setUInt64(1, propertyId); - auto res = stmt->executeQuery(); - while (res->next()) { - Game::logger->Log("UGC", "Getting lxfml ugcID: %u", res->getUInt(1)); - - //Get lxfml: - auto stmtL = Database::CreatePreppedStmt("SELECT lxfml from ugc where id=?"); - stmtL->setUInt(1, res->getUInt(1)); - - auto lxres = stmtL->executeQuery(); - - while (lxres->next()) { - auto lxfml = lxres->getBlob(1); - - lxfml->seekg(0, std::ios::end); - size_t lxfmlSize = lxfml->tellg(); - lxfml->seekg(0); - - //Send message: - { - LWOOBJID blueprintID = res->getUInt(1); - blueprintID = GeneralUtils::SetBit(blueprintID, OBJECT_BIT_CHARACTER); - blueprintID = GeneralUtils::SetBit(blueprintID, OBJECT_BIT_PERSISTENT); - - CBITSTREAM; - PacketUtils::WriteHeader(bitStream, CLIENT, MSG_CLIENT_BLUEPRINT_SAVE_RESPONSE); - bitStream.Write(0); //always zero so that a check on the client passes - bitStream.Write(0); - bitStream.Write(1); - bitStream.Write(blueprintID); - - bitStream.Write(lxfmlSize + 9); - - //Write a fake sd0 header: - bitStream.Write(0x73); //s - bitStream.Write(0x64); //d - bitStream.Write(0x30); //0 - bitStream.Write(0x01); //1 - bitStream.Write(0xFF); //end magic - - bitStream.Write(lxfmlSize); - - for (size_t i = 0; i < lxfmlSize; ++i) - bitStream.Write(lxfml->get()); - - SystemAddress sysAddr = packet->systemAddress; - SEND_PACKET; - PacketUtils::SavePacket("lxfml packet " + std::to_string(res->getUInt(1)) + ".bin", (char*)bitStream.GetData(), bitStream.GetNumberOfBytesUsed()); - } - } - - delete stmtL; - delete lxres; - } - - delete stmt; - delete res; - } - - noBBB: - - // Tell the client it's done loading: - GameMessages::SendInvalidZoneTransferList(player, packet->systemAddress, GeneralUtils::ASCIIToUTF16(Game::config->GetValue("source")), u"", false, false); - GameMessages::SendServerDoneLoadingAllObjects(player, packet->systemAddress); - - //Send the player it's mail count: - //update: this might not be needed so im going to try disabling this here. - //Mail::HandleNotificationRequest(packet->systemAddress, player->GetObjectID()); - - //Notify chat that a player has loaded: - { - const auto& playerName = player->GetCharacter()->GetName(); - //RakNet::RakString playerName(player->GetCharacter()->GetName().c_str()); - - CBITSTREAM; - PacketUtils::WriteHeader(bitStream, CHAT_INTERNAL, MSG_CHAT_INTERNAL_PLAYER_ADDED_NOTIFICATION); - bitStream.Write(player->GetObjectID()); - bitStream.Write(playerName.size()); - for (size_t i = 0; i < playerName.size(); i++) - { - bitStream.Write(playerName[i]); - } - - auto zone = dZoneManager::Instance()->GetZone()->GetZoneID(); - bitStream.Write(zone.GetMapID()); - bitStream.Write(zone.GetInstanceID()); - bitStream.Write(zone.GetCloneID()); - bitStream.Write(player->GetParentUser()->GetMuteExpire()); - - Game::chatServer->Send(&bitStream, SYSTEM_PRIORITY, RELIABLE, 0, Game::chatSysAddr, false); - } - } - else { - Game::logger->Log("WorldServer", "Couldn't find character to log in with for user %s (%i)!", user->GetUsername().c_str(), user->GetAccountID()); - Game::server->Disconnect(packet->systemAddress, SERVER_DISCON_CHARACTER_NOT_FOUND); - } - } else { - Game::logger->Log("WorldServer", "Couldn't get user for level load complete!"); - } - break; - } - - case MSG_WORLD_CLIENT_POSITION_UPDATE: { - ClientPackets::HandleClientPositionUpdate(packet->systemAddress, packet); - break; + case MSG_WORLD_CLIENT_GENERAL_CHAT_MESSAGE: { + if (chatDisabled) { + ChatPackets::SendMessageFail(packet->systemAddress); + } else { + ClientPackets::HandleChatMessage(packet->systemAddress, packet); } - case MSG_WORLD_CLIENT_MAIL: { - RakNet::BitStream bitStream(packet->data, packet->length, false); - LWOOBJID space; - bitStream.Read(space); - Mail::HandleMailStuff(&bitStream, packet->systemAddress, UserManager::Instance()->GetUser(packet->systemAddress)->GetLastUsedChar()->GetEntity()); - break; + break; + } + + case MSG_WORLD_CLIENT_HANDLE_FUNNESS: { + //This means the client is running slower or faster than it should. + //Could be insane lag, but I'mma just YEET them as it's usually speedhacking. + //This is updated to now count the amount of times we've been caught "speedhacking" to kick with a delay + //This is hopefully going to fix the random disconnects people face sometimes. + if (Game::config->GetValue("disable_anti_speedhack") == "1") { + return; } - case MSG_WORLD_CLIENT_ROUTE_PACKET: { - //Yeet to chat - CINSTREAM; - uint64_t header = 0; - uint32_t size = 0; - inStream.Read(header); - inStream.Read(size); - - if (size > 20000) { - Game::logger->Log("WorldServer", "Tried to route a packet with a read size > 20000, so likely a false packet."); - return; - } - - CBITSTREAM; - - PacketUtils::WriteHeader(bitStream, CHAT, packet->data[14]); - - //We need to insert the player's objectID so the chat server can find who originated this request: - LWOOBJID objectID = 0; - auto user = UserManager::Instance()->GetUser(packet->systemAddress); - if (user) { - objectID = user->GetLastUsedChar()->GetObjectID(); - } - - bitStream.Write(objectID); - - //Now write the rest of the data: - auto data = inStream.GetData(); - for (uint32_t i = 0; i < size; ++i) { - bitStream.Write(data[i+23]); - } - - Game::chatServer->Send(&bitStream, SYSTEM_PRIORITY, RELIABLE_ORDERED, 0, Game::chatSysAddr, false); - break; - } - - case MSG_WORLD_CLIENT_STRING_CHECK: { - ClientPackets::HandleChatModerationRequest(packet->systemAddress, packet); - break; - } - - case MSG_WORLD_CLIENT_GENERAL_CHAT_MESSAGE: { - if (chatDisabled) { - ChatPackets::SendMessageFail(packet->systemAddress); - } - else { - ClientPackets::HandleChatMessage(packet->systemAddress, packet); - } - - break; - } - - case MSG_WORLD_CLIENT_HANDLE_FUNNESS: { - //This means the client is running slower or faster than it should. - //Could be insane lag, but I'mma just YEET them as it's usually speedhacking. - //This is updated to now count the amount of times we've been caught "speedhacking" to kick with a delay - //This is hopefully going to fix the random disconnects people face sometimes. - if (Game::config->GetValue("disable_anti_speedhack") == "1") { - return; - } - - User* user = UserManager::Instance()->GetUser(packet->systemAddress); - if (user) { - user->UserOutOfSync(); - } - else { - Game::server->Disconnect(packet->systemAddress, SERVER_DISCON_KICK); - } - break; + User* user = UserManager::Instance()->GetUser(packet->systemAddress); + if (user) { + user->UserOutOfSync(); + } else { + Game::server->Disconnect(packet->systemAddress, SERVER_DISCON_KICK); } + break; + } default: Game::server->GetLogger()->Log("HandlePacket", "Unknown world packet received: %i", int(packet->data[3])); @@ -1254,48 +1227,48 @@ void HandlePacket(Packet* packet) { void WorldShutdownProcess(uint32_t zoneId) { Game::logger->Log("WorldServer", "Saving map %i instance %i", zoneId, instanceID); - for (auto i = 0; i < Game::server->GetReplicaManager()->GetParticipantCount(); ++i) { - const auto& player = Game::server->GetReplicaManager()->GetParticipantAtIndex(i); + for (auto i = 0; i < Game::server->GetReplicaManager()->GetParticipantCount(); ++i) { + const auto& player = Game::server->GetReplicaManager()->GetParticipantAtIndex(i); - auto* entity = Player::GetPlayer(player); - Game::logger->Log("WorldServer", "Saving data!"); - if (entity != nullptr && entity->GetCharacter() != nullptr) { - auto* skillComponent = entity->GetComponent(); + auto* entity = Player::GetPlayer(player); + Game::logger->Log("WorldServer", "Saving data!"); + if (entity != nullptr && entity->GetCharacter() != nullptr) { + auto* skillComponent = entity->GetComponent(); - if (skillComponent != nullptr) { - skillComponent->Reset(); - } - Game::logger->Log("WorldServer", "Saving character %s...", entity->GetCharacter()->GetName().c_str()); - entity->GetCharacter()->SaveXMLToDatabase(); - Game::logger->Log("WorldServer", "Character data for %s was saved!", entity->GetCharacter()->GetName().c_str()); - } - } + if (skillComponent != nullptr) { + skillComponent->Reset(); + } + Game::logger->Log("WorldServer", "Saving character %s...", entity->GetCharacter()->GetName().c_str()); + entity->GetCharacter()->SaveXMLToDatabase(); + Game::logger->Log("WorldServer", "Character data for %s was saved!", entity->GetCharacter()->GetName().c_str()); + } + } - if (PropertyManagementComponent::Instance() != nullptr) { - Game::logger->Log("WorldServer", "Saving ALL property data for zone %i clone %i!", zoneId, PropertyManagementComponent::Instance()->GetCloneId()); - PropertyManagementComponent::Instance()->Save(); - Game::logger->Log("WorldServer", "ALL property data saved for zone %i clone %i!", zoneId, PropertyManagementComponent::Instance()->GetCloneId()); - } + if (PropertyManagementComponent::Instance() != nullptr) { + Game::logger->Log("WorldServer", "Saving ALL property data for zone %i clone %i!", zoneId, PropertyManagementComponent::Instance()->GetCloneId()); + PropertyManagementComponent::Instance()->Save(); + Game::logger->Log("WorldServer", "ALL property data saved for zone %i clone %i!", zoneId, PropertyManagementComponent::Instance()->GetCloneId()); + } - Game::logger->Log("WorldServer", "ALL DATA HAS BEEN SAVED FOR ZONE %i INSTANCE %i!", zoneId, instanceID); + Game::logger->Log("WorldServer", "ALL DATA HAS BEEN SAVED FOR ZONE %i INSTANCE %i!", zoneId, instanceID); - while (Game::server->GetReplicaManager()->GetParticipantCount() > 0) { - const auto& player = Game::server->GetReplicaManager()->GetParticipantAtIndex(0); + while (Game::server->GetReplicaManager()->GetParticipantCount() > 0) { + const auto& player = Game::server->GetReplicaManager()->GetParticipantAtIndex(0); - Game::server->Disconnect(player, SERVER_DISCON_KICK); - } + Game::server->Disconnect(player, SERVER_DISCON_KICK); + } SendShutdownMessageToMaster(); } void WorldShutdownSequence() { - if (worldShutdownSequenceStarted || worldShutdownSequenceComplete) { - return; - } + if (worldShutdownSequenceStarted || worldShutdownSequenceComplete) { + return; + } - worldShutdownSequenceStarted = true; + worldShutdownSequenceStarted = true; - Game::logger->Log("WorldServer", "Zone (%i) instance (%i) shutting down outside of main loop!", Game::server->GetZoneID(), instanceID); - WorldShutdownProcess(Game::server->GetZoneID()); + Game::logger->Log("WorldServer", "Zone (%i) instance (%i) shutting down outside of main loop!", Game::server->GetZoneID(), instanceID); + WorldShutdownProcess(Game::server->GetZoneID()); FinalizeShutdown(); } diff --git a/dZoneManager/Level.cpp b/dZoneManager/Level.cpp index afd2413e..ebfca4cc 100644 --- a/dZoneManager/Level.cpp +++ b/dZoneManager/Level.cpp @@ -15,12 +15,11 @@ #include "CDClientManager.h" Level::Level(Zone* parentZone, const std::string& filepath) { - m_ParentZone = parentZone; + m_ParentZone = parentZone; std::ifstream file(filepath, std::ios_base::in | std::ios_base::binary); if (file) { ReadChunks(file); - } - else { + } else { Game::logger->Log("Level", "Failed to load %s", filepath.c_str()); } @@ -42,7 +41,7 @@ const void Level::PrintAllObjects() { } } -void Level::ReadChunks(std::ifstream & file) { +void Level::ReadChunks(std::ifstream& file) { const uint32_t CHNK_HEADER = ('C' + ('H' << 8) + ('N' << 16) + ('K' << 24)); while (!file.eof()) { @@ -63,15 +62,13 @@ void Level::ReadChunks(std::ifstream & file) { //We're currently not loading env or particle data if (header.id == ChunkTypeID::FileInfo) { ReadFileInfoChunk(file, header); - } - else if (header.id == ChunkTypeID::SceneObjectData) { + } else if (header.id == ChunkTypeID::SceneObjectData) { ReadSceneObjectDataChunk(file, header); } m_ChunkHeaders.insert(std::make_pair(header.id, header)); file.seekg(target); - } - else { + } else { if (initPos == std::streamoff(0)) { //Really old chunk version file.seekg(0); Header header; @@ -98,8 +95,7 @@ void Level::ReadChunks(std::ifstream & file) { file.ignore(4); } } - } - else { + } else { file.ignore(8); } @@ -143,7 +139,7 @@ void Level::ReadChunks(std::ifstream & file) { } } -void Level::ReadFileInfoChunk(std::ifstream & file, Header & header) { +void Level::ReadFileInfoChunk(std::ifstream& file, Header& header) { FileInfoChunk* fi = new FileInfoChunk; BinaryIO::BinaryRead(file, fi->version); BinaryIO::BinaryRead(file, fi->revision); @@ -156,7 +152,7 @@ void Level::ReadFileInfoChunk(std::ifstream & file, Header & header) { if (header.fileInfo->revision == 3452816845 && m_ParentZone->GetZoneID().GetMapID() == 1100) header.fileInfo->revision = 26; } -void Level::ReadSceneObjectDataChunk(std::ifstream & file, Header & header) { +void Level::ReadSceneObjectDataChunk(std::ifstream& file, Header& header) { SceneObjectDataChunk* chunk = new SceneObjectDataChunk; uint32_t objectsCount = 0; BinaryIO::BinaryRead(file, objectsCount); @@ -182,25 +178,25 @@ void Level::ReadSceneObjectDataChunk(std::ifstream & file, Header & header) { dZoneManager::Instance()->GetZone()->SetSpawnRot(obj.rotation); } - std::u16string ldfString = u""; - uint32_t length = 0; - BinaryIO::BinaryRead(file, length); + std::u16string ldfString = u""; + uint32_t length = 0; + BinaryIO::BinaryRead(file, length); - for (uint32_t i = 0; i < length; ++i) { - uint16_t data; - BinaryIO::BinaryRead(file, data); - ldfString.push_back(data); - } + for (uint32_t i = 0; i < length; ++i) { + uint16_t data; + BinaryIO::BinaryRead(file, data); + ldfString.push_back(data); + } - std::string sData = GeneralUtils::UTF16ToWTF8(ldfString); - std::stringstream ssData(sData); - std::string token; - char deliminator = '\n'; + std::string sData = GeneralUtils::UTF16ToWTF8(ldfString); + std::stringstream ssData(sData); + std::string token; + char deliminator = '\n'; - while (std::getline(ssData, token, deliminator)) { - LDFBaseData * ldfData = LDFBaseData::DataFromString(token); - obj.settings.push_back(ldfData); - } + while (std::getline(ssData, token, deliminator)) { + LDFBaseData* ldfData = LDFBaseData::DataFromString(token); + obj.settings.push_back(ldfData); + } BinaryIO::BinaryRead(file, obj.value3); @@ -228,7 +224,7 @@ void Level::ReadSceneObjectDataChunk(std::ifstream & file, Header & header) { continue; } - if (obj.lot == 176) { //Spawner + if (obj.lot == 176) { //Spawner SpawnerInfo spawnInfo = SpawnerInfo(); SpawnerNode* node = new SpawnerNode(); spawnInfo.templateID = obj.lot; @@ -268,8 +264,7 @@ void Level::ReadSceneObjectDataChunk(std::ifstream & file, Header & header) { if (data->GetValueType() == eLDFType::LDF_TYPE_FLOAT) // Floats are in seconds { spawnInfo.respawnTime = std::stof(data->GetValueAsString()); - } - else if (data->GetValueType() == eLDFType::LDF_TYPE_U32) // Ints are in ms? + } else if (data->GetValueType() == eLDFType::LDF_TYPE_U32) // Ints are in ms? { spawnInfo.respawnTime = std::stoi(data->GetValueAsString()) / 1000; } @@ -296,9 +291,9 @@ void Level::ReadSceneObjectDataChunk(std::ifstream & file, Header & header) { } } } - Spawner* spawner = new Spawner(spawnInfo); - dZoneManager::Instance()->AddSpawner(obj.id, spawner); - } else { //Regular object + Spawner* spawner = new Spawner(spawnInfo); + dZoneManager::Instance()->AddSpawner(obj.id, spawner); + } else { //Regular object EntityInfo info; info.spawnerID = 0; info.id = obj.id; @@ -327,16 +322,14 @@ void Level::ReadSceneObjectDataChunk(std::ifstream & file, Header & header) { if (!clientOnly) { - // We should never have more than 1 zone control object - const auto zoneControlObject = dZoneManager::Instance()->GetZoneControlObject(); + // We should never have more than 1 zone control object + const auto zoneControlObject = dZoneManager::Instance()->GetZoneControlObject(); if (zoneControlObject != nullptr && info.lot == zoneControlObject->GetLOT()) goto deleteSettings; - EntityManager::Instance()->CreateEntity(info, nullptr); - } - else - { - deleteSettings: + EntityManager::Instance()->CreateEntity(info, nullptr); + } else { + deleteSettings: for (auto* setting : info.settings) { delete setting; diff --git a/dZoneManager/Level.h b/dZoneManager/Level.h index 05839759..e724363f 100644 --- a/dZoneManager/Level.h +++ b/dZoneManager/Level.h @@ -29,7 +29,7 @@ public: struct SceneObjectDataChunk { std::map objects; - + SceneObject& GetObject(LWOOBJID id) { for (std::map::iterator it = objects.begin(); it != objects.end(); ++it) { if (it->first == id) return it->second; diff --git a/dZoneManager/Spawner.cpp b/dZoneManager/Spawner.cpp index 3e69d785..57b4e988 100644 --- a/dZoneManager/Spawner.cpp +++ b/dZoneManager/Spawner.cpp @@ -15,8 +15,7 @@ Spawner::Spawner(const SpawnerInfo info) { if (!m_Info.emulated) { m_EntityInfo.spawnerID = m_Info.spawnerID; - } - else { + } else { m_EntityInfo.spawnerID = m_Info.emulator; m_Info.isNetwork = false; } @@ -46,8 +45,7 @@ Spawner::Spawner(const SpawnerInfo info) { m_WaitTimes.push_back(m_Info.respawnTime); } - if (m_Info.spawnOnSmashGroupName != "") - { + if (m_Info.spawnOnSmashGroupName != "") { std::vector spawnSmashEntities = EntityManager::Instance()->GetEntitiesInGroup(m_Info.spawnOnSmashGroupName); std::vector spawnSmashSpawners = dZoneManager::Instance()->GetSpawnersInGroup(m_Info.spawnOnSmashGroupName); std::vector spawnSmashSpawnersN = dZoneManager::Instance()->GetSpawnersByName(m_Info.spawnOnSmashGroupName); @@ -55,20 +53,20 @@ Spawner::Spawner(const SpawnerInfo info) { m_SpawnSmashFoundGroup = true; ssEntity->AddDieCallback([=]() { Spawn(); - }); + }); } for (Spawner* ssSpawner : spawnSmashSpawners) { m_SpawnSmashFoundGroup = true; ssSpawner->AddSpawnedEntityDieCallback([=]() { Spawn(); - }); + }); } for (Spawner* ssSpawner : spawnSmashSpawnersN) { m_SpawnSmashFoundGroup = true; m_SpawnOnSmash = ssSpawner; ssSpawner->AddSpawnedEntityDieCallback([=]() { Spawn(); - }); + }); } } } @@ -77,8 +75,7 @@ Spawner::~Spawner() { } -Entity* Spawner::Spawn() -{ +Entity* Spawner::Spawn() { std::vector freeNodes; for (SpawnerNode* node : m_Info.nodes) { if (node->entities.size() < node->nodeMax) { @@ -131,18 +128,15 @@ void Spawner::AddSpawnedEntityDieCallback(std::function callback) { m_SpawnedEntityDieCallbacks.push_back(callback); } -void Spawner::AddEntitySpawnedCallback(std::function callback) { +void Spawner::AddEntitySpawnedCallback(std::function callback) { m_EntitySpawnedCallbacks.push_back(callback); } -void Spawner::Reset() -{ +void Spawner::Reset() { m_Start = true; - - for (auto* node : m_Info.nodes) - { - for (const auto& spawned : node->entities) - { + + for (auto* node : m_Info.nodes) { + for (const auto& spawned : node->entities) { auto* entity = EntityManager::Instance()->GetEntity(spawned); if (entity == nullptr) continue; @@ -159,9 +153,9 @@ void Spawner::Reset() } void Spawner::SoftReset() { - m_Start = true; - m_AmountSpawned = 0; - m_NeedsUpdate = true; + m_Start = true; + m_AmountSpawned = 0; + m_NeedsUpdate = true; } void Spawner::SetRespawnTime(float time) { @@ -171,8 +165,8 @@ void Spawner::SetRespawnTime(float time) { m_WaitTimes[i] = 0; }; - m_Start = true; - m_NeedsUpdate = true; + m_Start = true; + m_NeedsUpdate = true; } void Spawner::SetNumToMaintain(int32_t value) { @@ -180,21 +174,19 @@ void Spawner::SetNumToMaintain(int32_t value) { } void Spawner::Update(const float deltaTime) { - if (m_Start && m_Active) - { + if (m_Start && m_Active) { m_Start = false; const auto toSpawn = m_Info.amountMaintained - m_AmountSpawned; - for (auto i = 0; i < toSpawn; ++i) - { + for (auto i = 0; i < toSpawn; ++i) { Spawn(); } - + m_WaitTimes.clear(); - + return; } - + if (!m_NeedsUpdate) return; if (!m_Active) return; //if (m_Info.noTimedSpawn) return; @@ -223,7 +215,7 @@ void Spawner::NotifyOfEntityDeath(const LWOOBJID& objectID) { //m_RespawnTime = 10.0f; m_WaitTimes.push_back(0.0f); SpawnerNode* node; - + auto it = m_Entities.find(objectID); if (it != m_Entities.end()) node = it->second; else return; @@ -233,29 +225,26 @@ void Spawner::NotifyOfEntityDeath(const LWOOBJID& objectID) { } for (size_t i = 0; i < node->entities.size(); ++i) { - if (node->entities[i] && node->entities[i] == objectID) + if (node->entities[i] && node->entities[i] == objectID) node->entities.erase(node->entities.begin() + i); } m_Entities.erase(objectID); - if (m_SpawnOnSmash != nullptr) - { + if (m_SpawnOnSmash != nullptr) { m_SpawnOnSmash->Reset(); } } -void Spawner::Activate() -{ +void Spawner::Activate() { m_Active = true; m_NeedsUpdate = true; - for (auto& time : m_WaitTimes) - { + for (auto& time : m_WaitTimes) { time = 0; } } void Spawner::SetSpawnLot(LOT lot) { - m_EntityInfo.lot = lot; + m_EntityInfo.lot = lot; } diff --git a/dZoneManager/Spawner.h b/dZoneManager/Spawner.h index 17e2e126..908bb3a3 100644 --- a/dZoneManager/Spawner.h +++ b/dZoneManager/Spawner.h @@ -37,15 +37,15 @@ struct SpawnerInfo { bool noTimedSpawn = false; std::string grpNameQBShowBricks = ""; bool spawnActivator = true; - + bool emulated = false; LWOOBJID emulator = LWOOBJID_EMPTY; }; class Spawner { public: - Spawner(SpawnerInfo info); - ~Spawner(); + Spawner(SpawnerInfo info); + ~Spawner(); Entity* Spawn(); Entity* Spawn(std::vector freeNodes, bool force = false); @@ -69,7 +69,7 @@ public: bool m_Active = true; private: std::vector> m_SpawnedEntityDieCallbacks = {}; - std::vector> m_EntitySpawnedCallbacks = {}; + std::vector> m_EntitySpawnedCallbacks = {}; bool m_SpawnSmashFoundGroup = false; diff --git a/dZoneManager/Zone.cpp b/dZoneManager/Zone.cpp index 36245df4..54246c28 100644 --- a/dZoneManager/Zone.cpp +++ b/dZoneManager/Zone.cpp @@ -12,9 +12,8 @@ #include "Spawner.h" #include "dZoneManager.h" -Zone::Zone(const LWOMAPID & mapID, const LWOINSTANCEID & instanceID, const LWOCLONEID & cloneID) : - m_ZoneID(mapID, instanceID, cloneID) -{ +Zone::Zone(const LWOMAPID& mapID, const LWOINSTANCEID& instanceID, const LWOCLONEID& cloneID) : + m_ZoneID(mapID, instanceID, cloneID) { m_NumberOfScenesLoaded = 0; m_NumberOfObjectsLoaded = 0; m_NumberOfSceneTransitionsLoaded = 0; @@ -30,8 +29,7 @@ Zone::~Zone() { } } -void Zone::Initalize() -{ +void Zone::Initalize() { LoadZoneIntoMemory(); LoadLevelsIntoMemory(); m_CheckSum = CalculateChecksum(); @@ -63,8 +61,7 @@ void Zone::LoadZoneIntoMemory() { uint8_t sceneCount; BinaryIO::BinaryRead(file, sceneCount); m_SceneCount = sceneCount; - } - else BinaryIO::BinaryRead(file, m_SceneCount); + } else BinaryIO::BinaryRead(file, m_SceneCount); for (uint32_t i = 0; i < m_SceneCount; ++i) { LoadScene(file); @@ -117,23 +114,18 @@ void Zone::LoadZoneIntoMemory() { if (data) { if (data->GetKey() == u"spawner_node_id") { node->nodeID = std::stoi(data->GetValueAsString()); - } - else if (data->GetKey() == u"spawner_max_per_node") { + } else if (data->GetKey() == u"spawner_max_per_node") { node->nodeMax = std::stoi(data->GetValueAsString()); - } - else if (data->GetKey() == u"groupID") { // Load object group + } else if (data->GetKey() == u"groupID") { // Load object group std::string groupStr = data->GetValueAsString(); info.groups = GeneralUtils::SplitString(groupStr, ';'); info.groups.erase(info.groups.end() - 1); - } - else if (data->GetKey() == u"grpNameQBShowBricks") { + } else if (data->GetKey() == u"grpNameQBShowBricks") { if (data->GetValueAsString() == "") continue; /*std::string groupStr = data->GetValueAsString(); info.groups.push_back(groupStr);*/ info.grpNameQBShowBricks = data->GetValueAsString(); - } - else if (data->GetKey() == u"spawner_name") - { + } else if (data->GetKey() == u"spawner_name") { info.name = data->GetValueAsString(); } } @@ -157,8 +149,7 @@ void Zone::LoadZoneIntoMemory() { //m_PathData.resize(m_PathDataLength); //file.read((char*)&m_PathData[0], m_PathDataLength); } - } - else { + } else { Game::logger->Log("Zone", "Failed to open: %s", m_ZoneFilePath.c_str()); } m_ZonePath = m_ZoneFilePath.substr(0, m_ZoneFilePath.rfind('/') + 1); @@ -168,11 +159,11 @@ void Zone::LoadZoneIntoMemory() { std::string Zone::GetFilePathForZoneID() { //We're gonna go ahead and presume we've got the db loaded already: - CDZoneTableTable * zoneTable = CDClientManager::Instance()->GetTable("ZoneTable"); + CDZoneTableTable* zoneTable = CDClientManager::Instance()->GetTable("ZoneTable"); const CDZoneTable* zone = zoneTable->Query(this->GetZoneID().GetMapID()); if (zone != nullptr) { - std::string toReturn = "./res/maps/" + zone->zoneName; - std::transform(toReturn.begin(), toReturn.end(), toReturn.begin(), ::tolower); + std::string toReturn = "./res/maps/" + zone->zoneName; + std::transform(toReturn.begin(), toReturn.end(), toReturn.begin(), ::tolower); return toReturn; } @@ -231,7 +222,7 @@ const void Zone::PrintAllGameObjects() { } } -void Zone::LoadScene(std::ifstream & file) { +void Zone::LoadScene(std::ifstream& file) { SceneRef scene; scene.level = nullptr; LWOSCENEID lwoSceneID(LWOZONEID_INVALID, 0); @@ -284,8 +275,7 @@ std::vector Zone::LoadLUTriggers(std::string triggerFile, if (doc->Parse(data.str().c_str(), data.str().size()) == 0) { //Game::logger->Log("Zone", "Loaded LUTriggers from file %s!", triggerFile.c_str()); - } - else { + } else { Game::logger->Log("Zone", "Failed to load LUTriggers from file %s", triggerFile.c_str()); return lvlTriggers; } @@ -295,7 +285,7 @@ std::vector Zone::LoadLUTriggers(std::string triggerFile, auto currentTrigger = triggers->FirstChildElement("trigger"); while (currentTrigger) { - LUTriggers::Trigger *newTrigger = new LUTriggers::Trigger(); + LUTriggers::Trigger* newTrigger = new LUTriggers::Trigger(); currentTrigger->QueryAttribute("enabled", &newTrigger->enabled); currentTrigger->QueryAttribute("id", &newTrigger->id); @@ -336,12 +326,9 @@ LUTriggers::Trigger* Zone::GetTrigger(uint32_t sceneID, uint32_t triggerID) { return m_Scenes[sceneID].triggers[triggerID]; } -const Path* Zone::GetPath(std::string name) const -{ - for (const auto& path : m_Paths) - { - if (name == path.pathName) - { +const Path* Zone::GetPath(std::string name) const { + for (const auto& path : m_Paths) { + if (name == path.pathName) { return &path; } } @@ -349,7 +336,7 @@ const Path* Zone::GetPath(std::string name) const return nullptr; } -void Zone::LoadSceneTransition(std::ifstream & file) { +void Zone::LoadSceneTransition(std::ifstream& file) { SceneTransition sceneTrans; if (m_ZoneFileFormatVersion < Zone::ZoneFileFormatVersion::LateAlpha) { uint8_t length; @@ -367,14 +354,14 @@ void Zone::LoadSceneTransition(std::ifstream & file) { m_SceneTransitions.push_back(sceneTrans); } -SceneTransitionInfo Zone::LoadSceneTransitionInfo(std::ifstream & file) { +SceneTransitionInfo Zone::LoadSceneTransitionInfo(std::ifstream& file) { SceneTransitionInfo info; BinaryIO::BinaryRead(file, info.sceneID); BinaryIO::BinaryRead(file, info.position); return info; } -void Zone::LoadPath(std::ifstream & file) { +void Zone::LoadPath(std::ifstream& file) { // Currently only spawner (type 4) paths are supported Path path = Path(); @@ -400,8 +387,7 @@ void Zone::LoadPath(std::ifstream & file) { if (path.pathVersion >= 18) { uint8_t unknown; BinaryIO::BinaryRead(file, unknown); - } - else if (path.pathVersion >= 13) { + } else if (path.pathVersion >= 13) { uint8_t count; BinaryIO::BinaryRead(file, count); for (uint8_t i = 0; i < count; ++i) { @@ -410,8 +396,7 @@ void Zone::LoadPath(std::ifstream & file) { path.movingPlatform.platformTravelSound.push_back(character); } } - } - else if (path.pathType == PathType::Property) { + } else if (path.pathType == PathType::Property) { int32_t unknown; BinaryIO::BinaryRead(file, unknown); BinaryIO::BinaryRead(file, path.property.price); @@ -441,8 +426,7 @@ void Zone::LoadPath(std::ifstream & file) { BinaryIO::BinaryRead(file, path.property.playerZoneCoords.y); BinaryIO::BinaryRead(file, path.property.playerZoneCoords.z); BinaryIO::BinaryRead(file, path.property.maxBuildHeight); - } - else if (path.pathType == PathType::Camera) { + } else if (path.pathType == PathType::Camera) { uint8_t count; BinaryIO::BinaryRead(file, count); for (uint8_t i = 0; i < count; ++i) { @@ -503,8 +487,7 @@ void Zone::LoadPath(std::ifstream & file) { waypoint.movingPlatform.arriveSound.push_back(character); } } - } - else if (path.pathType == PathType::Camera) { + } else if (path.pathType == PathType::Camera) { float unknown; BinaryIO::BinaryRead(file, unknown); BinaryIO::BinaryRead(file, unknown); @@ -515,8 +498,7 @@ void Zone::LoadPath(std::ifstream & file) { BinaryIO::BinaryRead(file, waypoint.camera.tension); BinaryIO::BinaryRead(file, waypoint.camera.continuity); BinaryIO::BinaryRead(file, waypoint.camera.bias); - } - else if (path.pathType == PathType::Race) { + } else if (path.pathType == PathType::Race) { uint8_t unknown; BinaryIO::BinaryRead(file, unknown); BinaryIO::BinaryRead(file, unknown); @@ -524,8 +506,7 @@ void Zone::LoadPath(std::ifstream & file) { BinaryIO::BinaryRead(file, unknown1); BinaryIO::BinaryRead(file, unknown1); BinaryIO::BinaryRead(file, unknown1); - } - else if (path.pathType == PathType::Rail) { + } else if (path.pathType == PathType::Rail) { float unknown; BinaryIO::BinaryRead(file, unknown); BinaryIO::BinaryRead(file, unknown); diff --git a/dZoneManager/Zone.h b/dZoneManager/Zone.h index 0d30415d..5d3dc424 100644 --- a/dZoneManager/Zone.h +++ b/dZoneManager/Zone.h @@ -9,7 +9,7 @@ class Level; class LUTriggers { - public: +public: struct Command { std::string id; @@ -89,7 +89,7 @@ enum class PathBehavior : uint32_t { Once = 2 }; -enum class PropertyRentalTimeUnit : int32_t{ +enum class PropertyRentalTimeUnit : int32_t { Forever = 0, Seconds = 1, Minutes = 2, diff --git a/dZoneManager/dZMCommon.h b/dZoneManager/dZMCommon.h index 6ee23a61..635faaae 100644 --- a/dZoneManager/dZMCommon.h +++ b/dZoneManager/dZMCommon.h @@ -19,8 +19,8 @@ struct SceneObject { float scale = 1.0f; //std::string settings; uint32_t value3; - std::vector settings; + std::vector settings; }; #define LOT_MARKER_PLAYER_START 1931 -#define LOT_MARKET_CAMERA_TARGET 2182 \ No newline at end of file +#define LOT_MARKET_CAMERA_TARGET 2182 diff --git a/dZoneManager/dZoneManager.cpp b/dZoneManager/dZoneManager.cpp index 89f4b6f8..52d56f3c 100644 --- a/dZoneManager/dZoneManager.cpp +++ b/dZoneManager/dZoneManager.cpp @@ -17,17 +17,17 @@ dZoneManager* dZoneManager::m_Address = nullptr; void dZoneManager::Initialize(const LWOZONEID& zoneID) { Game::logger->Log("dZoneManager", "Preparing zone: %i/%i/%i", zoneID.GetMapID(), zoneID.GetInstanceID(), zoneID.GetCloneID()); - int64_t startTime = 0; - int64_t endTime = 0; + int64_t startTime = 0; + int64_t endTime = 0; - startTime = std::chrono::duration_cast(std::chrono::steady_clock::now().time_since_epoch()).count(); + startTime = std::chrono::duration_cast(std::chrono::steady_clock::now().time_since_epoch()).count(); - LoadZone(zoneID); + LoadZone(zoneID); LOT zoneControlTemplate = 2365; CDZoneTableTable* zoneTable = CDClientManager::Instance()->GetTable("ZoneTable"); - if (zoneTable != nullptr){ + if (zoneTable != nullptr) { const CDZoneTable* zone = zoneTable->Query(zoneID.GetMapID()); if (zone != nullptr) { @@ -37,7 +37,7 @@ void dZoneManager::Initialize(const LWOZONEID& zoneID) { EntityManager::Instance()->SetGhostDistanceMax(max + min); EntityManager::Instance()->SetGhostDistanceMin(max); m_PlayerLoseCoinsOnDeath = zone->PlayerLoseCoinsOnDeath; - } + } } Game::logger->Log("dZoneManager", "Creating zone control object %i", zoneControlTemplate); @@ -51,9 +51,9 @@ void dZoneManager::Initialize(const LWOZONEID& zoneID) { m_pZone->Initalize(); - endTime = std::chrono::duration_cast(std::chrono::steady_clock::now().time_since_epoch()).count(); + endTime = std::chrono::duration_cast(std::chrono::steady_clock::now().time_since_epoch()).count(); - Game::logger->Log("dZoneManager", "Zone prepared in: %llu ms", (endTime - startTime)); + Game::logger->Log("dZoneManager", "Zone prepared in: %llu ms", (endTime - startTime)); VanityUtilities::SpawnVanity(); } @@ -61,17 +61,17 @@ void dZoneManager::Initialize(const LWOZONEID& zoneID) { dZoneManager::~dZoneManager() { if (m_pZone) delete m_pZone; - for (std::pair p : m_Spawners) { - if (p.second) { - delete p.second; - p.second = nullptr; - } + for (std::pair p : m_Spawners) { + if (p.second) { + delete p.second; + p.second = nullptr; + } - m_Spawners.erase(p.first); - } + m_Spawners.erase(p.first); + } } -Zone * dZoneManager::GetZone() { +Zone* dZoneManager::GetZone() { return m_pZone; } @@ -82,14 +82,14 @@ void dZoneManager::LoadZone(const LWOZONEID& zoneID) { m_pZone = new Zone(zoneID.GetMapID(), zoneID.GetInstanceID(), zoneID.GetCloneID()); } -void dZoneManager::NotifyZone(const dZoneNotifier & notifier, const LWOOBJID& objectID) { +void dZoneManager::NotifyZone(const dZoneNotifier& notifier, const LWOOBJID& objectID) { switch (notifier) { case dZoneNotifier::SpawnedObjectDestroyed: break; case dZoneNotifier::SpawnedChildObjectDestroyed: break; case dZoneNotifier::ReloadZone: - Game::logger->Log("dZoneManager", "Forcing reload of zone %i", m_ZoneID.GetMapID()); + Game::logger->Log("dZoneManager", "Forcing reload of zone %i", m_ZoneID.GetMapID()); LoadZone(m_ZoneID); m_pZone->Initalize(); @@ -109,21 +109,19 @@ void dZoneManager::NotifyZone(const dZoneNotifier & notifier, const LWOOBJID& ob } } -void dZoneManager::AddSpawner(LWOOBJID id, Spawner* spawner) -{ +void dZoneManager::AddSpawner(LWOOBJID id, Spawner* spawner) { m_Spawners.insert_or_assign(id, spawner); } -LWOZONEID dZoneManager::GetZoneID() const -{ +LWOZONEID dZoneManager::GetZoneID() const { return m_ZoneID; } uint32_t dZoneManager::GetMaxLevel() { if (m_MaxLevel == 0) { auto tableData = CDClientDatabase::ExecuteQuery("SELECT LevelCap FROM WorldConfig WHERE WorldConfigID = 1 LIMIT 1;"); - m_MaxLevel = tableData.getIntField(0, -1); - tableData.finalize(); + m_MaxLevel = tableData.getIntField(0, -1); + tableData.finalize(); } return m_MaxLevel; } @@ -131,8 +129,8 @@ uint32_t dZoneManager::GetMaxLevel() { int32_t dZoneManager::GetLevelCapCurrencyConversion() { if (m_CurrencyConversionRate == 0) { auto tableData = CDClientDatabase::ExecuteQuery("SELECT LevelCapCurrencyConversion FROM WorldConfig WHERE WorldConfigID = 1 LIMIT 1;"); - m_CurrencyConversionRate = tableData.getIntField(0, -1); - tableData.finalize(); + m_CurrencyConversionRate = tableData.getIntField(0, -1); + tableData.finalize(); } return m_CurrencyConversionRate; } @@ -143,12 +141,10 @@ void dZoneManager::Update(float deltaTime) { } } -LWOOBJID dZoneManager::MakeSpawner(SpawnerInfo info) -{ +LWOOBJID dZoneManager::MakeSpawner(SpawnerInfo info) { auto objectId = info.spawnerID; - if (objectId == LWOOBJID_EMPTY) - { + if (objectId == LWOOBJID_EMPTY) { objectId = ObjectIDManager::Instance()->GenerateObjectID(); objectId = GeneralUtils::SetBit(objectId, OBJECT_BIT_CLIENT); @@ -172,8 +168,7 @@ LWOOBJID dZoneManager::MakeSpawner(SpawnerInfo info) return objectId; } -Spawner* dZoneManager::GetSpawner(const LWOOBJID id) -{ +Spawner* dZoneManager::GetSpawner(const LWOOBJID id) { const auto& index = m_Spawners.find(id); if (index == m_Spawners.end()) { @@ -183,8 +178,7 @@ Spawner* dZoneManager::GetSpawner(const LWOOBJID id) return index->second; } -void dZoneManager::RemoveSpawner(const LWOOBJID id) -{ +void dZoneManager::RemoveSpawner(const LWOOBJID id) { auto* spawner = GetSpawner(id); if (spawner == nullptr) { @@ -196,16 +190,13 @@ void dZoneManager::RemoveSpawner(const LWOOBJID id) if (entity != nullptr) { entity->Kill(); - } - else { + } else { Game::logger->Log("dZoneManager", "Failed to find spawner entity (%llu)", id); } - for (auto* node : spawner->m_Info.nodes) - { - for (const auto& element : node->entities) - { + for (auto* node : spawner->m_Info.nodes) { + for (const auto& element : node->entities) { auto* nodeEntity = EntityManager::Instance()->GetEntity(element); if (nodeEntity == nullptr) continue; diff --git a/dZoneManager/dZoneManager.h b/dZoneManager/dZoneManager.h index 3171c81f..66e56820 100644 --- a/dZoneManager/dZoneManager.h +++ b/dZoneManager/dZoneManager.h @@ -17,14 +17,14 @@ public: }; public: - static dZoneManager* Instance() { + static dZoneManager* Instance() { if (!m_Address) { m_Address = new dZoneManager(); } - + return m_Address; } - + void Initialize(const LWOZONEID& zoneID); ~dZoneManager(); @@ -54,12 +54,12 @@ private: * The ratio of LEGO Score to currency when the character has hit the max level. */ int32_t m_CurrencyConversionRate = 0; - - static dZoneManager* m_Address; //Singleton + + static dZoneManager* m_Address; //Singleton Zone* m_pZone; LWOZONEID m_ZoneID; - bool m_PlayerLoseCoinsOnDeath; //Do players drop coins in this zone when smashed - std::map m_Spawners; + bool m_PlayerLoseCoinsOnDeath; //Do players drop coins in this zone when smashed + std::map m_Spawners; Entity* m_ZoneControlObject; }; diff --git a/tests/AMFDeserializeTests.cpp b/tests/AMFDeserializeTests.cpp index 58d7eea4..71a0b265 100644 --- a/tests/AMFDeserializeTests.cpp +++ b/tests/AMFDeserializeTests.cpp @@ -15,7 +15,7 @@ std::unique_ptr ReadFromBitStream(RakNet::BitStream* bitStream) { int ReadAMFUndefinedFromBitStream() { CBITSTREAM - bitStream.Write(0x00); + bitStream.Write(0x00); std::unique_ptr res(ReadFromBitStream(&bitStream)); ASSERT_EQ(res->GetValueType(), AMFValueType::AMFUndefined); return 0; @@ -23,7 +23,7 @@ int ReadAMFUndefinedFromBitStream() { int ReadAMFNullFromBitStream() { CBITSTREAM - bitStream.Write(0x01); + bitStream.Write(0x01); std::unique_ptr res(ReadFromBitStream(&bitStream)); ASSERT_EQ(res->GetValueType(), AMFValueType::AMFNull); return 0; @@ -31,7 +31,7 @@ int ReadAMFNullFromBitStream() { int ReadAMFFalseFromBitStream() { CBITSTREAM - bitStream.Write(0x02); + bitStream.Write(0x02); std::unique_ptr res(ReadFromBitStream(&bitStream)); ASSERT_EQ(res->GetValueType(), AMFValueType::AMFFalse); return 0; @@ -39,7 +39,7 @@ int ReadAMFFalseFromBitStream() { int ReadAMFTrueFromBitStream() { CBITSTREAM - bitStream.Write(0x03); + bitStream.Write(0x03); std::unique_ptr res(ReadFromBitStream(&bitStream)); ASSERT_EQ(res->GetValueType(), AMFValueType::AMFTrue); return 0; @@ -49,12 +49,12 @@ int ReadAMFIntegerFromBitStream() { CBITSTREAM { bitStream.Write(0x04); - // 127 == 01111111 - bitStream.Write(127); - std::unique_ptr res(ReadFromBitStream(&bitStream)); - ASSERT_EQ(res->GetValueType(), AMFValueType::AMFInteger); - // Check that the max value of a byte can be read correctly - ASSERT_EQ(static_cast(res.get())->GetIntegerValue(), 127); + // 127 == 01111111 + bitStream.Write(127); + std::unique_ptr res(ReadFromBitStream(&bitStream)); + ASSERT_EQ(res->GetValueType(), AMFValueType::AMFInteger); + // Check that the max value of a byte can be read correctly + ASSERT_EQ(static_cast(res.get())->GetIntegerValue(), 127); } bitStream.Reset(); { @@ -96,7 +96,7 @@ int ReadAMFIntegerFromBitStream() { int ReadAMFDoubleFromBitStream() { CBITSTREAM - bitStream.Write(0x05); + bitStream.Write(0x05); bitStream.Write(25346.4f); std::unique_ptr res(ReadFromBitStream(&bitStream)); ASSERT_EQ(res->GetValueType(), AMFValueType::AMFDouble); @@ -106,7 +106,7 @@ int ReadAMFDoubleFromBitStream() { int ReadAMFStringFromBitStream() { CBITSTREAM - bitStream.Write(0x06); + bitStream.Write(0x06); bitStream.Write(0x0F); std::string toWrite = "stateID"; for (auto e : toWrite) bitStream.Write(e); @@ -118,8 +118,8 @@ int ReadAMFStringFromBitStream() { int ReadAMFArrayFromBitStream() { CBITSTREAM - // Test empty AMFArray - bitStream.Write(0x09); + // Test empty AMFArray + bitStream.Write(0x09); bitStream.Write(0x01); bitStream.Write(0x01); { @@ -154,7 +154,7 @@ int ReadAMFArrayFromBitStream() { } /** - * This test checks that if we recieve an unimplemented AMFValueType + * This test checks that if we recieve an unimplemented AMFValueType * we correctly throw an error and can actch it. */ int TestUnimplementedAMFValues() { @@ -169,7 +169,7 @@ int TestUnimplementedAMFValues() { AMFValueType::AMFVectorDouble, AMFValueType::AMFVectorObject, AMFValueType::AMFDictionary - }; + }; // Run unimplemented tests to check that errors are thrown if // unimplemented AMF values are attempted to be parsed. std::ifstream fileStream; @@ -222,8 +222,8 @@ int TestLiveCapture() { ASSERT_EQ(dynamic_cast(result->FindValue("BehaviorID"))->GetStringValue(), "10447"); ASSERT_EQ(dynamic_cast(result->FindValue("objectID"))->GetStringValue(), "288300744895913279") - // Test the execution state array - auto executionState = dynamic_cast(result->FindValue("executionState")); + // Test the execution state array + auto executionState = dynamic_cast(result->FindValue("executionState")); ASSERT_NE(executionState, nullptr); auto strips = dynamic_cast(executionState->FindValue("strips"))->GetDenseArray(); @@ -268,7 +268,7 @@ int TestLiveCapture() { ASSERT_EQ(actionID->GetDoubleValue(), 0.0f) - auto uiArray = dynamic_cast(firstStrip->FindValue("ui")); + auto uiArray = dynamic_cast(firstStrip->FindValue("ui")); auto xPos = dynamic_cast(uiArray->FindValue("x")); auto yPos = dynamic_cast(uiArray->FindValue("y")); @@ -280,7 +280,7 @@ int TestLiveCapture() { ASSERT_EQ(stripID->GetDoubleValue(), 0.0f) - auto firstAction = dynamic_cast(actionsInFirstStrip[0]); + auto firstAction = dynamic_cast(actionsInFirstStrip[0]); auto firstType = dynamic_cast(firstAction->FindValue("Type")); @@ -348,17 +348,17 @@ int AMFDeserializeTests(int argc, char** const argv) { } /** - * Below is the AMF that is in the AMFBitStreamTest.bin file that we are reading in + * Below is the AMF that is in the AMFBitStreamTest.bin file that we are reading in * from a bitstream to test. args: amf3! { "objectID": "288300744895913279", "BehaviorID": "10447", - "executionState": amf3! + "executionState": amf3! { - "strips": amf3! + "strips": amf3! [ - amf3! + amf3! { "actionIndex": 0.0, "id": 0.0, diff --git a/tests/TestEncoding.cpp b/tests/TestEncoding.cpp index 1e676ec3..c23e2db6 100644 --- a/tests/TestEncoding.cpp +++ b/tests/TestEncoding.cpp @@ -4,49 +4,49 @@ #include "GeneralUtils.h" #include "CommonCxxTests.h" -int TestEncoding(int argc, char* *const argv) { - std::string x = "Hello World!"; - std::string_view v(x); +int TestEncoding(int argc, char** const argv) { + std::string x = "Hello World!"; + std::string_view v(x); - uint32_t out; - GeneralUtils::_NextUTF8Char(v, out); ASSERT_EQ(out, 'H'); - GeneralUtils::_NextUTF8Char(v, out); ASSERT_EQ(out, 'e'); - GeneralUtils::_NextUTF8Char(v, out); ASSERT_EQ(out, 'l'); - GeneralUtils::_NextUTF8Char(v, out); ASSERT_EQ(out, 'l'); - GeneralUtils::_NextUTF8Char(v, out); ASSERT_EQ(out, 'o'); - ASSERT_EQ(GeneralUtils::_NextUTF8Char(v, out), true); + uint32_t out; + GeneralUtils::_NextUTF8Char(v, out); ASSERT_EQ(out, 'H'); + GeneralUtils::_NextUTF8Char(v, out); ASSERT_EQ(out, 'e'); + GeneralUtils::_NextUTF8Char(v, out); ASSERT_EQ(out, 'l'); + GeneralUtils::_NextUTF8Char(v, out); ASSERT_EQ(out, 'l'); + GeneralUtils::_NextUTF8Char(v, out); ASSERT_EQ(out, 'o'); + ASSERT_EQ(GeneralUtils::_NextUTF8Char(v, out), true); - x = u8"Frühling"; - v = x; - GeneralUtils::_NextUTF8Char(v, out); ASSERT_EQ(out, U'F'); - GeneralUtils::_NextUTF8Char(v, out); ASSERT_EQ(out, U'r'); - GeneralUtils::_NextUTF8Char(v, out); ASSERT_EQ(out, U'ü'); - GeneralUtils::_NextUTF8Char(v, out); ASSERT_EQ(out, U'h'); - GeneralUtils::_NextUTF8Char(v, out); ASSERT_EQ(out, U'l'); - GeneralUtils::_NextUTF8Char(v, out); ASSERT_EQ(out, U'i'); - GeneralUtils::_NextUTF8Char(v, out); ASSERT_EQ(out, U'n'); - GeneralUtils::_NextUTF8Char(v, out); ASSERT_EQ(out, U'g'); - ASSERT_EQ(GeneralUtils::_NextUTF8Char(v, out), false); + x = u8"Frühling"; + v = x; + GeneralUtils::_NextUTF8Char(v, out); ASSERT_EQ(out, U'F'); + GeneralUtils::_NextUTF8Char(v, out); ASSERT_EQ(out, U'r'); + GeneralUtils::_NextUTF8Char(v, out); ASSERT_EQ(out, U'ü'); + GeneralUtils::_NextUTF8Char(v, out); ASSERT_EQ(out, U'h'); + GeneralUtils::_NextUTF8Char(v, out); ASSERT_EQ(out, U'l'); + GeneralUtils::_NextUTF8Char(v, out); ASSERT_EQ(out, U'i'); + GeneralUtils::_NextUTF8Char(v, out); ASSERT_EQ(out, U'n'); + GeneralUtils::_NextUTF8Char(v, out); ASSERT_EQ(out, U'g'); + ASSERT_EQ(GeneralUtils::_NextUTF8Char(v, out), false); - x = "中文字"; - v = x; - GeneralUtils::_NextUTF8Char(v, out); ASSERT_EQ(out, U'中'); - GeneralUtils::_NextUTF8Char(v, out); ASSERT_EQ(out, U'文'); - GeneralUtils::_NextUTF8Char(v, out); ASSERT_EQ(out, U'字'); - ASSERT_EQ(GeneralUtils::_NextUTF8Char(v, out), false); + x = "中文字"; + v = x; + GeneralUtils::_NextUTF8Char(v, out); ASSERT_EQ(out, U'中'); + GeneralUtils::_NextUTF8Char(v, out); ASSERT_EQ(out, U'文'); + GeneralUtils::_NextUTF8Char(v, out); ASSERT_EQ(out, U'字'); + ASSERT_EQ(GeneralUtils::_NextUTF8Char(v, out), false); - x = "👨‍⚖️"; - v = x; - GeneralUtils::_NextUTF8Char(v, out); ASSERT_EQ(out, 0x1F468); - GeneralUtils::_NextUTF8Char(v, out); ASSERT_EQ(out, 0x200D); - GeneralUtils::_NextUTF8Char(v, out); ASSERT_EQ(out, 0x2696); - GeneralUtils::_NextUTF8Char(v, out); ASSERT_EQ(out, 0xFE0F); - ASSERT_EQ(GeneralUtils::_NextUTF8Char(v, out), false); + x = "👨‍⚖️"; + v = x; + GeneralUtils::_NextUTF8Char(v, out); ASSERT_EQ(out, 0x1F468); + GeneralUtils::_NextUTF8Char(v, out); ASSERT_EQ(out, 0x200D); + GeneralUtils::_NextUTF8Char(v, out); ASSERT_EQ(out, 0x2696); + GeneralUtils::_NextUTF8Char(v, out); ASSERT_EQ(out, 0xFE0F); + ASSERT_EQ(GeneralUtils::_NextUTF8Char(v, out), false); - ASSERT_EQ(GeneralUtils::UTF8ToUTF16("Hello World!"), u"Hello World!"); - ASSERT_EQ(GeneralUtils::UTF8ToUTF16("Frühling"), u"Frühling"); - ASSERT_EQ(GeneralUtils::UTF8ToUTF16("中文字"), u"中文字"); - ASSERT_EQ(GeneralUtils::UTF8ToUTF16("👨‍⚖️"), u"👨‍⚖️"); + ASSERT_EQ(GeneralUtils::UTF8ToUTF16("Hello World!"), u"Hello World!"); + ASSERT_EQ(GeneralUtils::UTF8ToUTF16("Frühling"), u"Frühling"); + ASSERT_EQ(GeneralUtils::UTF8ToUTF16("中文字"), u"中文字"); + ASSERT_EQ(GeneralUtils::UTF8ToUTF16("👨‍⚖️"), u"👨‍⚖️"); - return 0; + return 0; } diff --git a/tests/TestLDFFormat.cpp b/tests/TestLDFFormat.cpp index 7ba31420..a7433e96 100644 --- a/tests/TestLDFFormat.cpp +++ b/tests/TestLDFFormat.cpp @@ -3,15 +3,15 @@ /** * @brief Test parsing an LDF value - * + * * @param argc Number of command line arguments for this test * @param argv Command line arguments * @return 0 on success, non-zero on failure */ -int TestLDFFormat(int argc, char* *const argv) { +int TestLDFFormat(int argc, char** const argv) { // Create auto* data = LDFBaseData::DataFromString("KEY=0:VALUE"); - + // Check that the data type is correct ASSERT_EQ(data->GetValueType(), eLDFType::LDF_TYPE_UTF_16); @@ -19,7 +19,7 @@ int TestLDFFormat(int argc, char* *const argv) { ASSERT_EQ(data->GetKey(), u"KEY"); // Check that the value is correct - ASSERT_EQ(((LDFData* )data)->GetValue(), u"VALUE"); + ASSERT_EQ(((LDFData*)data)->GetValue(), u"VALUE"); // Check that the serialization is correct ASSERT_EQ(data->GetString(), "KEY=0:VALUE"); diff --git a/tests/TestNiPoint3.cpp b/tests/TestNiPoint3.cpp index 076b186d..d1588b8b 100644 --- a/tests/TestNiPoint3.cpp +++ b/tests/TestNiPoint3.cpp @@ -3,9 +3,9 @@ #include "NiPoint3.h" #include "CommonCxxTests.h" -int TestNiPoint3(int argc, char* *const argv) { +int TestNiPoint3(int argc, char** const argv) { // Check that Unitize works - ASSERT_EQ(NiPoint3(3,0,0).Unitize(), NiPoint3::UNIT_X); + ASSERT_EQ(NiPoint3(3, 0, 0).Unitize(), NiPoint3::UNIT_X); // Check what unitize does to a vector of length 0 ASSERT_EQ(NiPoint3::ZERO.Unitize(), NiPoint3::ZERO); // If we get here, all was successful From 0e46b875a5f318ce6c00ceed780aea647ec7386b Mon Sep 17 00:00:00 2001 From: aronwk-aaron Date: Thu, 28 Jul 2022 08:47:28 -0500 Subject: [PATCH 29/86] blame ignore and contributing update --- .git-blame-ignore-revs.txt | 2 ++ CONTRIBUTING.md | 11 ++++++++++- 2 files changed, 12 insertions(+), 1 deletion(-) create mode 100644 .git-blame-ignore-revs.txt diff --git a/.git-blame-ignore-revs.txt b/.git-blame-ignore-revs.txt new file mode 100644 index 00000000..2fa44c8c --- /dev/null +++ b/.git-blame-ignore-revs.txt @@ -0,0 +1,2 @@ +# format codebase +19e77a38d837ce781ba0ca6ea8e78b67a6e3b5a5 diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 64fcbc9f..a44629f8 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -123,6 +123,15 @@ added, which produced InvalidScript errors. Check out a compiled list of development resources and tools [here](https://lu-dev.net/). + +Please use [.editorconfig](https://editorconfig.org/#pre-installed) with your preferred IDE. + +And run: +```bash +git config blame.ignoreRevsFile .git-blame-ignore-revs +``` +to ignore the gitblame of mass formatting commits + ## Coding Style This project has gone through multiple iterations of coding style. In the code you'll find a number of different coding styles in use. What follows is the preferred style for this project. @@ -154,7 +163,7 @@ if (x) { } ``` -Instead of +Instead of ```cpp if ( x ) { From f284e5a6e169765ed8eaabb01a88b75105c6c4f8 Mon Sep 17 00:00:00 2001 From: Aaron Kimbre Date: Thu, 28 Jul 2022 11:35:57 -0500 Subject: [PATCH 30/86] fix filename --- .git-blame-ignore-revs.txt => .git-blame-ignore-revs | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename .git-blame-ignore-revs.txt => .git-blame-ignore-revs (100%) diff --git a/.git-blame-ignore-revs.txt b/.git-blame-ignore-revs similarity index 100% rename from .git-blame-ignore-revs.txt rename to .git-blame-ignore-revs From 26ddeaa4292b9c01c6a9dbf9f9503f61258c667f Mon Sep 17 00:00:00 2001 From: David Markowitz <39972741+EmosewaMC@users.noreply.github.com> Date: Fri, 29 Jul 2022 17:00:36 -0700 Subject: [PATCH 31/86] Fix NPC Proxy items (#684) * Fix racing lap times * Address NPC proxies NPCs are supposed to equip the sub items of items they equip and were not doing so. This PR adds this functionality and fixes and issue where Neido on Crux Prime was not wearing their sword. Tested that Neido has their sword and that other NPCs that wear proxies also get their proxies equipped. Had no issues with any other world crashing. --- dGame/dComponents/InventoryComponent.cpp | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) diff --git a/dGame/dComponents/InventoryComponent.cpp b/dGame/dComponents/InventoryComponent.cpp index a48173bb..6dbb3bd8 100644 --- a/dGame/dComponents/InventoryComponent.cpp +++ b/dGame/dComponents/InventoryComponent.cpp @@ -62,6 +62,25 @@ InventoryComponent::InventoryComponent(Entity* parent, tinyxml2::XMLDocument* do const auto& info = Inventory::FindItemComponent(item.itemid); UpdateSlot(info.equipLocation, { id, static_cast(item.itemid), item.count, slot++ }); + + // Equip this items proxies. + auto subItems = info.subItems; + + subItems.erase(std::remove_if(subItems.begin(), subItems.end(), ::isspace), subItems.end()); + + if (!subItems.empty()) { + const auto subItemsSplit = GeneralUtils::SplitString(subItems, ','); + + for (auto proxyLotAsString : subItemsSplit) { + const auto proxyLOT = static_cast(std::stoi(proxyLotAsString)); + + const auto& proxyInfo = Inventory::FindItemComponent(proxyLOT); + const LWOOBJID proxyId = ObjectIDManager::Instance()->GenerateObjectID(); + + // Use item.count since we equip item.count number of the item this is a requested proxy of + UpdateSlot(proxyInfo.equipLocation, { proxyId, proxyLOT, item.count, slot++ } ); + } + } } } From f80a26a9448c661453b353d38fe5fe8480b8ed30 Mon Sep 17 00:00:00 2001 From: eddytronpie <55319774+PyEddy@users.noreply.github.com> Date: Sat, 30 Jul 2022 04:41:14 +0100 Subject: [PATCH 32/86] Fix integer issue with BricksCollected (#679) This fixes an issue where BricksCollected goes to an insane number after selling more bricks than you collected in the area --- dGame/dComponents/CharacterComponent.cpp | 3 ++- dGame/dComponents/CharacterComponent.h | 4 ++-- 2 files changed, 4 insertions(+), 3 deletions(-) diff --git a/dGame/dComponents/CharacterComponent.cpp b/dGame/dComponents/CharacterComponent.cpp index 91666014..3b4b8db8 100644 --- a/dGame/dComponents/CharacterComponent.cpp +++ b/dGame/dComponents/CharacterComponent.cpp @@ -211,7 +211,7 @@ void CharacterComponent::LoadFromXml(tinyxml2::XMLDocument* doc) { ZoneStatistics statistics = {}; child->QueryUnsigned64Attribute("ac", &statistics.m_AchievementsCollected); - child->QueryUnsigned64Attribute("bc", &statistics.m_BricksCollected); + child->QueryInt64Attribute("bc", &statistics.m_BricksCollected); child->QueryUnsigned64Attribute("cc", &statistics.m_CoinsCollected); child->QueryUnsigned64Attribute("es", &statistics.m_EnemiesSmashed); child->QueryUnsigned64Attribute("qbc", &statistics.m_QuickBuildsCompleted); @@ -226,6 +226,7 @@ void CharacterComponent::LoadFromXml(tinyxml2::XMLDocument* doc) { } const tinyxml2::XMLAttribute* rocketConfig = character->FindAttribute("lcbp"); + if (rocketConfig) { m_LastRocketConfig = GeneralUtils::ASCIIToUTF16(std::string(rocketConfig->Value())); } else { diff --git a/dGame/dComponents/CharacterComponent.h b/dGame/dComponents/CharacterComponent.h index f6bf1e70..8efb4ef5 100644 --- a/dGame/dComponents/CharacterComponent.h +++ b/dGame/dComponents/CharacterComponent.h @@ -15,7 +15,7 @@ */ struct ZoneStatistics { uint64_t m_AchievementsCollected; - uint64_t m_BricksCollected; + int64_t m_BricksCollected; uint64_t m_CoinsCollected; uint64_t m_EnemiesSmashed; uint64_t m_QuickBuildsCompleted; @@ -431,7 +431,7 @@ private: /** * The total amount of bricks collected by this character */ - uint64_t m_BricksCollected; + int64_t m_BricksCollected; /** * The total amount of entities smashed by this character From d64fa1680d707add7ce2a650e84c525e8dcfb9d4 Mon Sep 17 00:00:00 2001 From: David Markowitz <39972741+EmosewaMC@users.noreply.github.com> Date: Sat, 30 Jul 2022 20:56:21 -0700 Subject: [PATCH 33/86] Fix missions re-ordering on reload (#686) * Fix missions re-ordering on reload Check for success rather than failure * Add a comment * Get base value from database * Update Mission.h --- dGame/dComponents/MissionComponent.cpp | 21 +++++++++++++++++---- dGame/dComponents/MissionComponent.h | 7 +++++++ dGame/dMission/Mission.cpp | 3 +++ dGame/dMission/Mission.h | 17 +++++++++++++++++ dZoneManager/dZoneManager.cpp | 9 +++++++++ dZoneManager/dZoneManager.h | 6 ++++++ 6 files changed, 59 insertions(+), 4 deletions(-) diff --git a/dGame/dComponents/MissionComponent.cpp b/dGame/dComponents/MissionComponent.cpp index ad77cf34..96f213e5 100644 --- a/dGame/dComponents/MissionComponent.cpp +++ b/dGame/dComponents/MissionComponent.cpp @@ -24,6 +24,7 @@ std::unordered_map> MissionComponent::m_Achievemen //! Initializer MissionComponent::MissionComponent(Entity* parent) : Component(parent) { + m_LastUsedMissionOrderUID = dZoneManager::Instance()->GetUniqueMissionIdStartingValue(); } //! Destructor @@ -83,6 +84,7 @@ void MissionComponent::AcceptMission(const uint32_t missionId, const bool skipCh if (mission != nullptr) { if (mission->GetClientInfo().repeatable) { mission->Accept(); + if (mission->IsMission()) mission->SetUniqueMissionOrderID(++m_LastUsedMissionOrderUID); } return; @@ -90,6 +92,8 @@ void MissionComponent::AcceptMission(const uint32_t missionId, const bool skipCh mission = new Mission(this, missionId); + if (mission->IsMission()) mission->SetUniqueMissionOrderID(++m_LastUsedMissionOrderUID); + mission->Accept(); this->m_Missions.insert_or_assign(missionId, mission); @@ -299,6 +303,8 @@ bool MissionComponent::LookForAchievements(MissionTaskType type, int32_t value, m_Missions.insert_or_assign(missionID, instance); + if (instance->IsMission()) instance->SetUniqueMissionOrderID(++m_LastUsedMissionOrderUID); + instance->Accept(); any = true; @@ -368,6 +374,8 @@ bool MissionComponent::LookForAchievements(MissionTaskType type, int32_t value, m_Missions.insert_or_assign(mission.id, instance); + if (instance->IsMission()) instance->SetUniqueMissionOrderID(++m_LastUsedMissionOrderUID); + instance->Accept(); any = true; @@ -523,6 +531,7 @@ void MissionComponent::LoadFromXml(tinyxml2::XMLDocument* doc) { auto* currentM = cur->FirstChildElement(); + uint32_t missionOrder{}; while (currentM) { int missionId; @@ -532,6 +541,11 @@ void MissionComponent::LoadFromXml(tinyxml2::XMLDocument* doc) { mission->LoadFromXml(currentM); + if (currentM->QueryAttribute("o", &missionOrder) == tinyxml2::XML_SUCCESS && mission->IsMission()) { + mission->SetUniqueMissionOrderID(missionOrder); + if (missionOrder > m_LastUsedMissionOrderUID) m_LastUsedMissionOrderUID = missionOrder; + } + currentM = currentM->NextSiblingElement(); m_Missions.insert_or_assign(missionId, mission); @@ -565,17 +579,16 @@ void MissionComponent::UpdateXml(tinyxml2::XMLDocument* doc) { if (mission) { const auto complete = mission->IsComplete(); - if (complete) { - auto* m = doc->NewElement("m"); + auto* m = doc->NewElement("m"); + if (complete) { mission->UpdateXml(m); done->LinkEndChild(m); continue; } - - auto* m = doc->NewElement("m"); + if (mission->IsMission()) m->SetAttribute("o", mission->GetUniqueMissionOrderID()); mission->UpdateXml(m); diff --git a/dGame/dComponents/MissionComponent.h b/dGame/dComponents/MissionComponent.h index b4e53001..58185a68 100644 --- a/dGame/dComponents/MissionComponent.h +++ b/dGame/dComponents/MissionComponent.h @@ -193,6 +193,13 @@ private: * combination of tasks and values, so that they can be easily re-queried later */ static std::unordered_map> m_AchievementCache; + + /** + * Order of missions in the UI. This value is incremented by 1 + * for each mission the Entity that owns this component accepts. + * In live this value started at 745. + */ + uint32_t m_LastUsedMissionOrderUID = 746U; }; #endif // MISSIONCOMPONENT_H diff --git a/dGame/dMission/Mission.cpp b/dGame/dMission/Mission.cpp index bb02c4c8..6020e51c 100644 --- a/dGame/dMission/Mission.cpp +++ b/dGame/dMission/Mission.cpp @@ -26,6 +26,8 @@ Mission::Mission(MissionComponent* missionComponent, const uint32_t missionId) { m_Timestamp = 0; + m_UniqueMissionID = dZoneManager::Instance()->GetUniqueMissionIdStartingValue(); + m_Reward = 0; m_State = MissionState::MISSION_STATE_UNKNOWN; @@ -283,6 +285,7 @@ void Mission::Accept() { void Mission::Complete(const bool yieldRewards) { if (m_State != MissionState::MISSION_STATE_ACTIVE && m_State != MissionState::MISSION_STATE_COMPLETE_ACTIVE) { + // If we are accepting a mission here there is no point to giving it a unique ID since we just complete it immediately. Accept(); } diff --git a/dGame/dMission/Mission.h b/dGame/dMission/Mission.h index 94920cba..43b2a96c 100644 --- a/dGame/dMission/Mission.h +++ b/dGame/dMission/Mission.h @@ -220,6 +220,18 @@ public: * @return true if the mission exists, false otherwise */ static bool IsValidMission(uint32_t missionId, CDMissions& info); + + /** + * @brief Returns the unique mission order ID + * + * @return The unique order ID + */ + uint32_t GetUniqueMissionOrderID() { return m_UniqueMissionID; }; + + /** + * Sets the unique mission order ID of this mission + */ + void SetUniqueMissionOrderID(uint32_t value) { m_UniqueMissionID = value; }; private: /** * Progresses all the newly accepted tasks for this mission after it has been accepted to reflect the state of the @@ -261,6 +273,11 @@ private: * All the tasks that can be progressed for this mission */ std::vector m_Tasks; + + /** + * The unique ID what order this mission was accepted in. + */ + uint32_t m_UniqueMissionID; }; #endif diff --git a/dZoneManager/dZoneManager.cpp b/dZoneManager/dZoneManager.cpp index 52d56f3c..102fb3af 100644 --- a/dZoneManager/dZoneManager.cpp +++ b/dZoneManager/dZoneManager.cpp @@ -240,3 +240,12 @@ std::vector dZoneManager::GetSpawnersInGroup(std::string group) { return spawnersInGroup; } + +uint32_t dZoneManager::GetUniqueMissionIdStartingValue() { + if (m_UniqueMissionIdStart == 0) { + auto tableData = CDClientDatabase::ExecuteQuery("SELECT COUNT(*) FROM Missions WHERE isMission = 0 GROUP BY isMission;"); + m_UniqueMissionIdStart = tableData.getIntField(0, -1); + tableData.finalize(); + } + return m_UniqueMissionIdStart; +} diff --git a/dZoneManager/dZoneManager.h b/dZoneManager/dZoneManager.h index 66e56820..b2fef1e3 100644 --- a/dZoneManager/dZoneManager.h +++ b/dZoneManager/dZoneManager.h @@ -43,6 +43,7 @@ public: void Update(float deltaTime); Entity* GetZoneControlObject() { return m_ZoneControlObject; } bool GetPlayerLoseCoinOnDeath() { return m_PlayerLoseCoinsOnDeath; } + uint32_t GetUniqueMissionIdStartingValue(); private: /** @@ -55,6 +56,11 @@ private: */ int32_t m_CurrencyConversionRate = 0; + /** + * The starting unique mission ID. + */ + uint32_t m_UniqueMissionIdStart = 0; + static dZoneManager* m_Address; //Singleton Zone* m_pZone; LWOZONEID m_ZoneID; From 0b9e97625e0414707cd39e5411758d14de0c25ea Mon Sep 17 00:00:00 2001 From: avery Date: Sat, 30 Jul 2022 22:09:45 -0700 Subject: [PATCH 34/86] Remove parentheses from ADD reporter_id --- migrations/dlu/2_reporter_id.sql | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/migrations/dlu/2_reporter_id.sql b/migrations/dlu/2_reporter_id.sql index dc2a9a7e..26103342 100644 --- a/migrations/dlu/2_reporter_id.sql +++ b/migrations/dlu/2_reporter_id.sql @@ -1 +1 @@ -ALTER TABLE bug_reports ADD (reporter_id) INT NOT NULL DEFAULT 0; +ALTER TABLE bug_reports ADD reporter_id INT NOT NULL DEFAULT 0; From 7ec458421fd917bd617bdf7c3f4ecfc324497d9c Mon Sep 17 00:00:00 2001 From: Daniel Seiler Date: Sun, 31 Jul 2022 13:58:50 +0200 Subject: [PATCH 35/86] Create SECURITY.md --- SECURITY.md | 51 +++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 51 insertions(+) create mode 100644 SECURITY.md diff --git a/SECURITY.md b/SECURITY.md new file mode 100644 index 00000000..c1126dba --- /dev/null +++ b/SECURITY.md @@ -0,0 +1,51 @@ +# Security Policy + +## Supported Versions + +At the moment, only the latest commit on the `main` branch will be supported for security vulnerabilities. Private server operators +should keep their instances up to date and forks should regularily rebase on `main`. + +| Branch | Supported | +| ------- | ------------------ | +| `main` | :white_check_mark: | + +## Reporting a Vulnerability + +If you found a security vulnerability in DLU, please send a message to [darkflame-security@googlegroups.com][darkflame-security]. You should get a +reply within *72 hours* that we have received your report and a tentative [CVSS score](https://nvd.nist.gov/vuln-metrics/cvss/v3-calculator). +We will do a preliminary analysis to confirm that the vulnerability is a plausible claim and decline the report otherwise. + +If possible, please include + +1. reproducible steps on how to trigger the vulnerability +2. a description on why you are convinced that it exists. +3. any information you may have on active exploitation of the vulnerability (zero-day). + +## Security Advisories + +The project will release advisories on resolved vulnerabilities at + +## Receiving Security Updates + +We set up [darkflame-security-announce@googlegroups.com][darkflame-security-announce] for private server operators to receive updates on vulnerabilities +such as the release of [Security Advisories](#security-advisories) or early workarounds and recommendations to mitigate ongoing +vulnerabilities. + +Unfortunately, we cannot guarantee that announcements will be sent for every vulnerability. + +## Embargo + +We propose a 90 day (approx. 3 months) embargo on security vulnerabilities. That is, we ask everyone not to disclose the vulnerabilty +publicly until either: + +1. 90 days have passed from the time the first related email is sent to `darkflame-security@` +2. a security advisory related to the vulnerability has been published by the project. + +if you fail to comply with this embargo, you might be exluded from [receiving security updates](#receiving-security-updates). + +## Bug Bounty + +Unfortunately we cannot provide bug bounties at this time. + +[darkflame-security]: mailto:darkflame-security@googlegroups.com +[darkflame-security-announce]: mailto:darkflame-security-announce@googlegroups.com From e97dc6fbff9dbffd7cfac8f42ab23bc81080e1ec Mon Sep 17 00:00:00 2001 From: Daniel Seiler Date: Sun, 31 Jul 2022 14:06:05 +0200 Subject: [PATCH 36/86] [no ci] update link to darkflame-security-announce --- SECURITY.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/SECURITY.md b/SECURITY.md index c1126dba..aaa3fe07 100644 --- a/SECURITY.md +++ b/SECURITY.md @@ -48,4 +48,4 @@ if you fail to comply with this embargo, you might be exluded from [receiving se Unfortunately we cannot provide bug bounties at this time. [darkflame-security]: mailto:darkflame-security@googlegroups.com -[darkflame-security-announce]: mailto:darkflame-security-announce@googlegroups.com +[darkflame-security-announce]: https://groups.google.com/g/darkflame-security-announce From 17d77db1c63840c59b6e9acf95369baea79fb194 Mon Sep 17 00:00:00 2001 From: "Gie \"Max\" Vanommeslaeghe" Date: Sun, 31 Jul 2022 15:14:16 +0200 Subject: [PATCH 37/86] Update SECURITY.md --- SECURITY.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/SECURITY.md b/SECURITY.md index aaa3fe07..c4b40c5a 100644 --- a/SECURITY.md +++ b/SECURITY.md @@ -41,7 +41,7 @@ publicly until either: 1. 90 days have passed from the time the first related email is sent to `darkflame-security@` 2. a security advisory related to the vulnerability has been published by the project. -if you fail to comply with this embargo, you might be exluded from [receiving security updates](#receiving-security-updates). +If you fail to comply with this embargo, you might be exluded from [receiving security updates](#receiving-security-updates). ## Bug Bounty From c11a4a67d19cc4ce8fa323b281d513fdd455e12d Mon Sep 17 00:00:00 2001 From: Jett <55758076+Jettford@users.noreply.github.com> Date: Mon, 1 Aug 2022 21:23:01 +0100 Subject: [PATCH 38/86] Replace the vsprintf used in the logger with vsnprintf. (#694) --- dCommon/dLogger.cpp | 11 ++--------- 1 file changed, 2 insertions(+), 9 deletions(-) diff --git a/dCommon/dLogger.cpp b/dCommon/dLogger.cpp index 3a91e31d..d4e6a96e 100644 --- a/dCommon/dLogger.cpp +++ b/dCommon/dLogger.cpp @@ -26,13 +26,6 @@ dLogger::~dLogger() { } void dLogger::vLog(const char* format, va_list args) { - const char* tempPtr = format; // strlen_s implementation for Linux and Windows - for (; *tempPtr != '\0'; ++tempPtr) { - size_t size = tempPtr - format; - if (size > 600) { - return; - } - } #ifdef _WIN32 time_t t = time(NULL); struct tm time; @@ -40,7 +33,7 @@ void dLogger::vLog(const char* format, va_list args) { char timeStr[70]; strftime(timeStr, sizeof(timeStr), "%d-%m-%y %H:%M:%S", &time); char message[2048]; - vsprintf_s(message, format, args); + vsnprintf(message, 2048, format, args); if (m_logToConsole) std::cout << "[" << timeStr << "] " << message; mFile << "[" << timeStr << "] " << message; @@ -50,7 +43,7 @@ void dLogger::vLog(const char* format, va_list args) { char timeStr[70]; strftime(timeStr, sizeof(timeStr), "%d-%m-%y %H:%M:%S", time); char message[2048]; - vsprintf(message, format, args); + vsnprintf(message, 2048, format, args); if (m_logToConsole) { fputs("[", stdout); From a0aa8b28544dbd6ac3153caa3060eb7a94637f1a Mon Sep 17 00:00:00 2001 From: Aaron Kimbrell Date: Mon, 1 Aug 2022 22:37:28 -0500 Subject: [PATCH 39/86] standardize line endings (#700) --- .gitattributes | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.gitattributes b/.gitattributes index 8218efdb..6313b56c 100644 --- a/.gitattributes +++ b/.gitattributes @@ -1 +1 @@ -*.sh eol=lf \ No newline at end of file +* text=auto eol=lf From 9ee219ea42403466559b11da883f8ed5de45f2ec Mon Sep 17 00:00:00 2001 From: Jett <55758076+Jettford@users.noreply.github.com> Date: Tue, 2 Aug 2022 06:30:19 +0100 Subject: [PATCH 40/86] Move Navmesh code away from dPhysics (#701) --- CMakeLists.txt | 38 +-- dGame/dComponents/BaseCombatAIComponent.cpp | 2 +- dGame/dComponents/MovementAIComponent.cpp | 8 +- dGame/dComponents/PetComponent.cpp | 6 +- dGame/dUtilities/SlashCommandHandler.cpp | 2 +- dNavigation/CMakeLists.txt | 4 + dNavigation/DetourExtensions.h | 25 ++ dNavigation/dNavMesh.cpp | 228 +++++++++++++++++ dNavigation/dNavMesh.h | 38 +++ dPhysics/dpWorld.cpp | 269 ++------------------ dPhysics/dpWorld.h | 46 +--- dScripts/BaseEnemyMech.cpp | 2 +- dWorldServer/CMakeLists.txt | 4 +- 13 files changed, 349 insertions(+), 323 deletions(-) create mode 100644 dNavigation/CMakeLists.txt create mode 100644 dNavigation/DetourExtensions.h create mode 100644 dNavigation/dNavMesh.cpp create mode 100644 dNavigation/dNavMesh.h diff --git a/CMakeLists.txt b/CMakeLists.txt index 65df9a35..cdc73d69 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -14,7 +14,7 @@ string(REPLACE "\n" ";" variables ${variables}) foreach(variable ${variables}) # If the string contains a #, skip it if(NOT "${variable}" MATCHES "#") - + # Split the variable into name and value string(REPLACE "=" ";" variable ${variable}) @@ -43,7 +43,7 @@ set(PROJECT_VERSION "${PROJECT_VERSION_MAJOR}.${PROJECT_VERSION_MINOR}.${PROJECT message(STATUS "Version: ${PROJECT_VERSION}") # Compiler flags: -# Disabled deprecated warnings as the MySQL includes have deprecated code in them. +# Disabled deprecated warnings as the MySQL includes have deprecated code in them. # Disabled misleading indentation as DL_LinkedList from RakNet has a weird indent. # Disabled no-register # Disabled unknown pragmas because Linux doesn't understand Windows pragmas. @@ -118,17 +118,18 @@ endforeach() set(INCLUDED_DIRECTORIES "dCommon" "dChatFilter" - "dGame" - "dGame/dBehaviors" - "dGame/dComponents" - "dGame/dGameMessages" - "dGame/dInventory" - "dGame/dMission" - "dGame/dEntity" - "dGame/dUtilities" - "dPhysics" - "dZoneManager" - "dDatabase" + "dGame" + "dGame/dBehaviors" + "dGame/dComponents" + "dGame/dGameMessages" + "dGame/dInventory" + "dGame/dMission" + "dGame/dEntity" + "dGame/dUtilities" + "dPhysics" + "dNavigation" + "dZoneManager" + "dDatabase" "dDatabase/Tables" "dNet" "dScripts" @@ -192,7 +193,7 @@ file( file( GLOB HEADERS_DGAME LIST_DIRECTORIES false - ${PROJECT_SOURCE_DIR}/dGame/Entity.h + ${PROJECT_SOURCE_DIR}/dGame/Entity.h ${PROJECT_SOURCE_DIR}/dGame/dGameMessages/GameMessages.h ${PROJECT_SOURCE_DIR}/dGame/EntityManager.h ${PROJECT_SOURCE_DIR}/dScripts/CppScripts.h @@ -206,6 +207,7 @@ add_subdirectory(dNet) add_subdirectory(dScripts) # Add for dGame to use add_subdirectory(dGame) add_subdirectory(dZoneManager) +add_subdirectory(dNavigation) add_subdirectory(dPhysics) # Create a list of common libraries shared between all binaries @@ -230,18 +232,18 @@ add_subdirectory(dMasterServer) # Add MasterServer last so it can rely on the ot # Add our precompiled headers target_precompile_headers( - dGame PRIVATE + dGame PRIVATE ${HEADERS_DGAME} ) target_precompile_headers( - dZoneManager PRIVATE + dZoneManager PRIVATE ${HEADERS_DZONEMANAGER} ) # Need to specify to use the CXX compiler language here or else we get errors including . target_precompile_headers( - dDatabase PRIVATE + dDatabase PRIVATE "$<$:${HEADERS_DDATABASE}>" ) @@ -253,4 +255,4 @@ target_precompile_headers( target_precompile_headers( tinyxml2 PRIVATE "$<$:${PROJECT_SOURCE_DIR}/thirdparty/tinyxml2/tinyxml2.h>" -) \ No newline at end of file +) diff --git a/dGame/dComponents/BaseCombatAIComponent.cpp b/dGame/dComponents/BaseCombatAIComponent.cpp index 2ac2cf04..c035a807 100644 --- a/dGame/dComponents/BaseCombatAIComponent.cpp +++ b/dGame/dComponents/BaseCombatAIComponent.cpp @@ -654,7 +654,7 @@ void BaseCombatAIComponent::Wander() { auto destination = m_StartPosition + delta; if (dpWorld::Instance().IsLoaded()) { - destination.y = dpWorld::Instance().GetHeightAtPoint(destination); + destination.y = dpWorld::Instance().GetNavMesh()->GetHeightAtPoint(destination); } if (Vector3::DistanceSquared(destination, m_MovementAI->GetCurrentPosition()) < 2 * 2) { diff --git a/dGame/dComponents/MovementAIComponent.cpp b/dGame/dComponents/MovementAIComponent.cpp index 9c76b286..43231abf 100644 --- a/dGame/dComponents/MovementAIComponent.cpp +++ b/dGame/dComponents/MovementAIComponent.cpp @@ -196,7 +196,7 @@ NiPoint3 MovementAIComponent::ApproximateLocation() const { NiPoint3 approximation = NiPoint3(x, y, z); if (dpWorld::Instance().IsLoaded()) { - approximation.y = dpWorld::Instance().GetHeightAtPoint(approximation); + approximation.y = dpWorld::Instance().GetNavMesh()->GetHeightAtPoint(approximation); } return approximation; @@ -208,7 +208,7 @@ bool MovementAIComponent::Warp(const NiPoint3& point) { NiPoint3 destination = point; if (dpWorld::Instance().IsLoaded()) { - destination.y = dpWorld::Instance().GetHeightAtPoint(point); + destination.y = dpWorld::Instance().GetNavMesh()->GetHeightAtPoint(point); if (std::abs(destination.y - point.y) > 3) { return false; @@ -387,7 +387,7 @@ void MovementAIComponent::SetDestination(const NiPoint3& value) { std::vector computedPath; if (dpWorld::Instance().IsLoaded()) { - computedPath = dpWorld::Instance().GetPath(GetCurrentPosition(), value, m_Info.wanderSpeed); + computedPath = dpWorld::Instance().GetNavMesh()->GetPath(GetCurrentPosition(), value, m_Info.wanderSpeed); } else { // Than take 10 points between the current position and the destination and make that the path @@ -416,7 +416,7 @@ void MovementAIComponent::SetDestination(const NiPoint3& value) { // Simply path for (auto point : computedPath) { if (dpWorld::Instance().IsLoaded()) { - point.y = dpWorld::Instance().GetHeightAtPoint(point); + point.y = dpWorld::Instance().GetNavMesh()->GetHeightAtPoint(point); } m_CurrentPath.push_back(point); diff --git a/dGame/dComponents/PetComponent.cpp b/dGame/dComponents/PetComponent.cpp index 42aceaf3..7e637ab7 100644 --- a/dGame/dComponents/PetComponent.cpp +++ b/dGame/dComponents/PetComponent.cpp @@ -267,14 +267,14 @@ void PetComponent::OnUse(Entity* originator) { if (dpWorld::Instance().IsLoaded()) { NiPoint3 attempt = petPosition + forward * interactionDistance; - float y = dpWorld::Instance().GetHeightAtPoint(attempt); + float y = dpWorld::Instance().GetNavMesh()->GetHeightAtPoint(attempt); while (std::abs(y - petPosition.y) > 4 && interactionDistance > 10) { const NiPoint3 forward = m_Parent->GetRotation().GetForwardVector(); attempt = originatorPosition + forward * interactionDistance; - y = dpWorld::Instance().GetHeightAtPoint(attempt); + y = dpWorld::Instance().GetNavMesh()->GetHeightAtPoint(attempt); interactionDistance -= 0.5f; } @@ -819,7 +819,7 @@ void PetComponent::Wander() { auto destination = m_StartPosition + delta; if (dpWorld::Instance().IsLoaded()) { - destination.y = dpWorld::Instance().GetHeightAtPoint(destination); + destination.y = dpWorld::Instance().GetNavMesh()->GetHeightAtPoint(destination); } if (Vector3::DistanceSquared(destination, m_MovementAI->GetCurrentPosition()) < 2 * 2) { diff --git a/dGame/dUtilities/SlashCommandHandler.cpp b/dGame/dUtilities/SlashCommandHandler.cpp index 16cdddbb..6ef1632b 100644 --- a/dGame/dUtilities/SlashCommandHandler.cpp +++ b/dGame/dUtilities/SlashCommandHandler.cpp @@ -733,7 +733,7 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit auto control = static_cast(entity->GetComponent(COMPONENT_TYPE_CONTROLLABLE_PHYSICS)); if (!control) return; - float y = dpWorld::Instance().GetHeightAtPoint(control->GetPosition()); + float y = dpWorld::Instance().GetNavMesh()->GetHeightAtPoint(control->GetPosition()); std::u16string msg = u"Navmesh height: " + (GeneralUtils::to_u16string(y)); ChatPackets::SendSystemMessage(sysAddr, msg); } diff --git a/dNavigation/CMakeLists.txt b/dNavigation/CMakeLists.txt new file mode 100644 index 00000000..beb498e3 --- /dev/null +++ b/dNavigation/CMakeLists.txt @@ -0,0 +1,4 @@ +set(DNAVIGATION_SOURCES "dNavMesh.cpp") + +add_library(dNavigation STATIC ${DNAVIGATION_SOURCES}) +target_link_libraries(dNavigation detour recast) diff --git a/dNavigation/DetourExtensions.h b/dNavigation/DetourExtensions.h new file mode 100644 index 00000000..55d3e29c --- /dev/null +++ b/dNavigation/DetourExtensions.h @@ -0,0 +1,25 @@ +#pragma once + +#include "Recast.h" +#include "DetourCommon.h" +#include "DetourNavMesh.h" +#include "DetourNavMeshBuilder.h" +#include "DetourNavMeshQuery.h" + +static const int NAVMESHSET_MAGIC = 'M' << 24 | 'S' << 16 | 'E' << 8 | 'T'; // char[4] of 'MSET' +static const int NAVMESHSET_VERSION = 1; + +struct NavMeshSetHeader { + int magic; + int version; + int numTiles; + dtNavMeshParams params; +}; + +struct NavMeshTileHeader { + dtTileRef tileRef; + int dataSize; +}; + +static const int MAX_POLYS = 256; +static const int MAX_SMOOTH = 2048; diff --git a/dNavigation/dNavMesh.cpp b/dNavigation/dNavMesh.cpp new file mode 100644 index 00000000..da471882 --- /dev/null +++ b/dNavigation/dNavMesh.cpp @@ -0,0 +1,228 @@ +#include "dNavMesh.h" + +#include "Game.h" +#include "dLogger.h" +#include "dPlatforms.h" +#include "NiPoint3.h" +#include "BinaryIO.h" + +dNavMesh::dNavMesh(uint32_t zoneId) { + m_ZoneId = zoneId; + + this->LoadNavmesh(); + + if (m_NavMesh) { + m_NavQuery = dtAllocNavMeshQuery(); + m_NavQuery->init(m_NavMesh, 2048); + + Game::logger->Log("dNavMesh", "Navmesh loaded successfully!"); + } else { + Game::logger->Log("dNavMesh", "Navmesh loading failed (This may be intended)."); + } +} + +dNavMesh::~dNavMesh() { + // Clean up Recast information + + rcFreeHeightField(m_Solid); + rcFreeCompactHeightfield(m_CHF); + rcFreeContourSet(m_CSet); + rcFreePolyMesh(m_PMesh); + rcFreePolyMeshDetail(m_PMDMesh); + dtFreeNavMesh(m_NavMesh); + dtFreeNavMeshQuery(m_NavQuery); + + if (m_Ctx) delete m_Ctx; + if (m_Triareas) delete[] m_Triareas; +} + + +void dNavMesh::LoadNavmesh() { + + std::string path = "./res/maps/navmeshes/" + std::to_string(m_ZoneId) + ".bin"; + + if (!BinaryIO::DoesFileExist(path)) { + return; + } + + FILE* fp; + +#ifdef _WIN32 + fopen_s(&fp, path.c_str(), "rb"); +#elif __APPLE__ + // macOS has 64bit file IO by default + fp = fopen(path.c_str(), "rb"); +#else + fp = fopen64(path.c_str(), "rb"); +#endif + + if (!fp) { + return; + } + + // Read header. + NavMeshSetHeader header; + size_t readLen = fread(&header, sizeof(NavMeshSetHeader), 1, fp); + if (readLen != 1) { + fclose(fp); + return; + } + + if (header.magic != NAVMESHSET_MAGIC) { + fclose(fp); + return; + } + + if (header.version != NAVMESHSET_VERSION) { + fclose(fp); + return; + } + + dtNavMesh* mesh = dtAllocNavMesh(); + if (!mesh) { + fclose(fp); + return; + } + + dtStatus status = mesh->init(&header.params); + if (dtStatusFailed(status)) { + fclose(fp); + return; + } + + // Read tiles. + for (int i = 0; i < header.numTiles; ++i) { + NavMeshTileHeader tileHeader; + readLen = fread(&tileHeader, sizeof(tileHeader), 1, fp); + if (readLen != 1) return; + + if (!tileHeader.tileRef || !tileHeader.dataSize) + break; + + unsigned char* data = (unsigned char*)dtAlloc(tileHeader.dataSize, DT_ALLOC_PERM); + if (!data) break; + memset(data, 0, tileHeader.dataSize); + readLen = fread(data, tileHeader.dataSize, 1, fp); + if (readLen != 1) return; + + mesh->addTile(data, tileHeader.dataSize, DT_TILE_FREE_DATA, tileHeader.tileRef, 0); + } + + fclose(fp); + + m_NavMesh = mesh; +} + +float dNavMesh::GetHeightAtPoint(const NiPoint3& location) { + if (m_NavMesh == nullptr) { + return location.y; + } + + float toReturn = 0.0f; + float pos[3]; + pos[0] = location.x; + pos[1] = location.y; + pos[2] = location.z; + + dtPolyRef nearestRef = 0; + float polyPickExt[3] = { 32.0f, 32.0f, 32.0f }; + dtQueryFilter filter{}; + + m_NavQuery->findNearestPoly(pos, polyPickExt, &filter, &nearestRef, 0); + m_NavQuery->getPolyHeight(nearestRef, pos, &toReturn); + + if (toReturn == 0.0f) { + toReturn = location.y; + } + + return toReturn; +} + +std::vector dNavMesh::GetPath(const NiPoint3& startPos, const NiPoint3& endPos, float speed) { + std::vector path; + + // Allows for non-navmesh maps (like new custom maps) to have "basic" enemies. + if (m_NavMesh == nullptr) { + // How many points to generate between start/end? + // Note: not actually 100% accurate due to rounding, but worst case it causes them to go a tiny bit faster + // than their speed value would normally allow at the end. + int numPoints = startPos.Distance(startPos, endPos) / speed; + + path.push_back(startPos); //insert the start pos + + // Linearly interpolate between these two points: + for (int i = 0; i < numPoints; i++) { + NiPoint3 newPoint{ startPos }; + + newPoint.x += speed; + newPoint.y = newPoint.y + (((endPos.y - startPos.y) / (endPos.x - startPos.x)) * (newPoint.x - startPos.x)); + + path.push_back(newPoint); + } + + path.push_back(endPos); //finally insert our end pos + + return path; + } + + float sPos[3]; + float ePos[3]; + sPos[0] = startPos.x; + sPos[1] = startPos.y; + sPos[2] = startPos.z; + + ePos[0] = endPos.x; + ePos[1] = endPos.y; + ePos[2] = endPos.z; + + dtStatus pathFindStatus; + dtPolyRef startRef; + dtPolyRef endRef; + float polyPickExt[3] = { 32.0f, 32.0f, 32.0f }; + dtQueryFilter filter{}; + + //Find our start poly + m_NavQuery->findNearestPoly(sPos, polyPickExt, &filter, &startRef, 0); + + //Find our end poly + m_NavQuery->findNearestPoly(ePos, polyPickExt, &filter, &endRef, 0); + + pathFindStatus = DT_FAILURE; + int m_nstraightPath = 0; + int m_npolys = 0; + dtPolyRef m_polys[MAX_POLYS]; + float m_straightPath[MAX_POLYS * 3]; + unsigned char m_straightPathFlags[MAX_POLYS]; + dtPolyRef m_straightPathPolys[MAX_POLYS]; + int m_straightPathOptions = 0; + + if (startRef && endRef) { + m_NavQuery->findPath(startRef, endRef, sPos, ePos, &filter, m_polys, &m_npolys, MAX_POLYS); + + if (m_npolys) { + // In case of partial path, make sure the end point is clamped to the last polygon. + float epos[3]; + dtVcopy(epos, ePos); + + if (m_polys[m_npolys - 1] != endRef) { + m_NavQuery->closestPointOnPoly(m_polys[m_npolys - 1], ePos, epos, 0); + } + + m_NavQuery->findStraightPath(sPos, epos, m_polys, m_npolys, + m_straightPath, m_straightPathFlags, + m_straightPathPolys, &m_nstraightPath, MAX_POLYS, m_straightPathOptions); + + // At this point we have our path. Copy it to the path store + int nIndex = 0; + for (int nVert = 0; nVert < m_nstraightPath; nVert++) { + NiPoint3 newPoint{ m_straightPath[nIndex++], m_straightPath[nIndex++], m_straightPath[nIndex++] }; + path.push_back(newPoint); + } + } + } else { + m_npolys = 0; + m_nstraightPath = 0; + } + + return path; +} diff --git a/dNavigation/dNavMesh.h b/dNavigation/dNavMesh.h new file mode 100644 index 00000000..09e9c895 --- /dev/null +++ b/dNavigation/dNavMesh.h @@ -0,0 +1,38 @@ +#pragma once + +#include +#include +#include +#include +#include + +#include "DetourExtensions.h" + +class NiPoint3; + +class dNavMesh { +public: + dNavMesh(uint32_t zoneId); + ~dNavMesh(); + + float GetHeightAtPoint(const NiPoint3& location); + std::vector GetPath(const NiPoint3& startPos, const NiPoint3& endPos, float speed = 10.0f); +private: + void LoadNavmesh(); + + uint32_t m_ZoneId; + + uint8_t* m_Triareas = nullptr; + rcHeightfield* m_Solid = nullptr; + rcCompactHeightfield* m_CHF = nullptr; + rcContourSet* m_CSet = nullptr; + rcPolyMesh* m_PMesh = nullptr; + rcConfig m_Config; + rcPolyMeshDetail* m_PMDMesh = nullptr; + + class InputGeom* m_Geometry = nullptr; + class dtNavMesh* m_NavMesh = nullptr; + class dtNavMeshQuery* m_NavQuery = nullptr; + uint8_t m_NavMeshDrawFlags; + rcContext* m_Ctx = nullptr; +}; diff --git a/dPhysics/dpWorld.cpp b/dPhysics/dpWorld.cpp index 666171c0..0a7e0df0 100644 --- a/dPhysics/dpWorld.cpp +++ b/dPhysics/dpWorld.cpp @@ -21,12 +21,9 @@ void dpWorld::Initialize(unsigned int zoneID) { m_Grid = new dpGrid(phys_sp_tilecount, phys_sp_tilesize); } - Game::logger->Log("dpWorld", "Physics world initialized!"); + m_NavMesh = new dNavMesh(zoneID); - if (ShouldLoadNavmesh(zoneID)) { - if (LoadNavmeshByZoneID(zoneID)) Game::logger->Log("dpWorld", "Loaded navmesh!"); - else Game::logger->Log("dpWorld", "Error(s) occurred during navmesh load."); - } + Game::logger->Log("dpWorld", "Physics world initialized!"); } dpWorld::~dpWorld() { @@ -35,7 +32,9 @@ dpWorld::~dpWorld() { m_Grid = nullptr; } - RecastCleanup(); + m_NavMesh->~dNavMesh(); + delete m_NavMesh; + m_NavMesh = nullptr; } void dpWorld::StepWorld(float deltaTime) { @@ -98,256 +97,20 @@ void dpWorld::RemoveEntity(dpEntity* entity) { } } -void dpWorld::RecastCleanup() { - if (m_triareas) delete[] m_triareas; - m_triareas = 0; - - rcFreeHeightField(m_solid); - m_solid = 0; - rcFreeCompactHeightfield(m_chf); - m_chf = 0; - rcFreeContourSet(m_cset); - m_cset = 0; - rcFreePolyMesh(m_pmesh); - m_pmesh = 0; - rcFreePolyMeshDetail(m_dmesh); - m_dmesh = 0; - dtFreeNavMesh(m_navMesh); - m_navMesh = 0; - - dtFreeNavMeshQuery(m_navQuery); - m_navQuery = 0; - - if (m_ctx) delete m_ctx; -} - -bool dpWorld::LoadNavmeshByZoneID(unsigned int zoneID) { - std::string path = "./res/maps/navmeshes/" + std::to_string(zoneID) + ".bin"; - m_navMesh = LoadNavmesh(path.c_str()); - - if (m_navMesh) { m_navQuery = dtAllocNavMeshQuery(); m_navQuery->init(m_navMesh, 2048); } else return false; - - return true; -} - -dtNavMesh* dpWorld::LoadNavmesh(const char* path) { - FILE* fp; - -#ifdef _WIN32 - fopen_s(&fp, path, "rb"); -#elif __APPLE__ - // macOS has 64bit file IO by default - fp = fopen(path, "rb"); -#else - fp = fopen64(path, "rb"); -#endif - - if (!fp) { - return 0; - } - - // Read header. - NavMeshSetHeader header; - size_t readLen = fread(&header, sizeof(NavMeshSetHeader), 1, fp); - if (readLen != 1) { - fclose(fp); - return 0; - } - - if (header.magic != NAVMESHSET_MAGIC) { - fclose(fp); - return 0; - } - - if (header.version != NAVMESHSET_VERSION) { - fclose(fp); - return 0; - } - - dtNavMesh* mesh = dtAllocNavMesh(); - if (!mesh) { - fclose(fp); - return 0; - } - - dtStatus status = mesh->init(&header.params); - if (dtStatusFailed(status)) { - fclose(fp); - return 0; - } - - // Read tiles. - for (int i = 0; i < header.numTiles; ++i) { - NavMeshTileHeader tileHeader; - readLen = fread(&tileHeader, sizeof(tileHeader), 1, fp); - if (readLen != 1) - return 0; - - if (!tileHeader.tileRef || !tileHeader.dataSize) - break; - - unsigned char* data = (unsigned char*)dtAlloc(tileHeader.dataSize, DT_ALLOC_PERM); - if (!data) break; - memset(data, 0, tileHeader.dataSize); - readLen = fread(data, tileHeader.dataSize, 1, fp); - if (readLen != 1) - return 0; - - mesh->addTile(data, tileHeader.dataSize, DT_TILE_FREE_DATA, tileHeader.tileRef, 0); - } - - fclose(fp); - - return mesh; -} - -bool dpWorld::ShouldLoadNavmesh(unsigned int zoneID) { - return true; //We use default paths now. Might re-tool this function later. - - //TODO: Add to this list as the navmesh folder grows. - switch (zoneID) { - case 1100: - case 1150: - case 1151: - case 1200: - case 1201: - case 1300: - case 1400: - case 1603: - return true; - } - - return false; -} - bool dpWorld::ShouldUseSP(unsigned int zoneID) { - //TODO: Add to this list as needed. Only large maps should be added as tiling likely makes little difference on small maps. + // TODO: Add to this list as needed. + // Only large maps should be added as tiling likely makes little difference on small maps. + switch (zoneID) { - case 1100: //Avant Gardens - case 1200: //Nimbus Station - case 1300: //Gnarled Forest - case 1400: //Forbidden Valley - case 1800: //Crux Prime - case 1900: //Nexus Tower - case 2000: //Ninjago - return true; + case 1100: // Avant Gardens + case 1200: // Nimbus Station + case 1300: // Gnarled Forest + case 1400: // Forbidden Valley + case 1800: // Crux Prime + case 1900: // Nexus Tower + case 2000: // Ninjago + return true; } return false; } - -float dpWorld::GetHeightAtPoint(const NiPoint3& location) { - if (m_navMesh == nullptr) { - return location.y; - } - - float toReturn = 0.0f; - float pos[3]; - pos[0] = location.x; - pos[1] = location.y; - pos[2] = location.z; - - dtPolyRef nearestRef = 0; - float polyPickExt[3] = { 32.0f, 32.0f, 32.0f }; - dtQueryFilter filter{}; - - m_navQuery->findNearestPoly(pos, polyPickExt, &filter, &nearestRef, 0); - m_navQuery->getPolyHeight(nearestRef, pos, &toReturn); - - if (toReturn == 0.0f) { - toReturn = location.y; - } - - return toReturn; -} - -std::vector dpWorld::GetPath(const NiPoint3& startPos, const NiPoint3& endPos, float speed) { - std::vector path; - - //allows for non-navmesh maps (like new custom maps) to have "basic" enemies. - if (m_navMesh == nullptr) { - //how many points to generate between start/end? - //note: not actually 100% accurate due to rounding, but worst case it causes them to go a tiny bit faster - //than their speed value would normally allow at the end. - int numPoints = startPos.Distance(startPos, endPos) / speed; - - path.push_back(startPos); //insert the start pos - - //Linearly interpolate between these two points: - for (int i = 0; i < numPoints; i++) { - NiPoint3 newPoint{ startPos }; - - newPoint.x += speed; - newPoint.y = newPoint.y + (((endPos.y - startPos.y) / (endPos.x - startPos.x)) * (newPoint.x - startPos.x)); - - path.push_back(newPoint); - } - - path.push_back(endPos); //finally insert our end pos - - return path; - } - - float sPos[3]; - float ePos[3]; - sPos[0] = startPos.x; - sPos[1] = startPos.y; - sPos[2] = startPos.z; - - ePos[0] = endPos.x; - ePos[1] = endPos.y; - ePos[2] = endPos.z; - - dtStatus pathFindStatus; - dtPolyRef startRef; - dtPolyRef endRef; - float polyPickExt[3] = { 32.0f, 32.0f, 32.0f }; - dtQueryFilter filter{}; - - //Find our start poly - m_navQuery->findNearestPoly(sPos, polyPickExt, &filter, &startRef, 0); - - //Find our end poly - m_navQuery->findNearestPoly(ePos, polyPickExt, &filter, &endRef, 0); - - pathFindStatus = DT_FAILURE; - int m_nstraightPath = 0; - int m_npolys = 0; - dtPolyRef m_polys[MAX_POLYS]; - float m_straightPath[MAX_POLYS * 3]; - unsigned char m_straightPathFlags[MAX_POLYS]; - dtPolyRef m_straightPathPolys[MAX_POLYS]; - int m_straightPathOptions = 0; - - if (startRef && endRef) { - m_navQuery->findPath(startRef, endRef, sPos, ePos, &filter, m_polys, &m_npolys, MAX_POLYS); - - if (m_npolys) { - // In case of partial path, make sure the end point is clamped to the last polygon. - float epos[3]; - dtVcopy(epos, ePos); - if (m_polys[m_npolys - 1] != endRef) - m_navQuery->closestPointOnPoly(m_polys[m_npolys - 1], ePos, epos, 0); - - m_navQuery->findStraightPath(sPos, epos, m_polys, m_npolys, - m_straightPath, m_straightPathFlags, - m_straightPathPolys, &m_nstraightPath, MAX_POLYS, m_straightPathOptions); - - // At this point we have our path. Copy it to the path store - int nIndex = 0; - for (int nVert = 0; nVert < m_nstraightPath; nVert++) { - /*m_PathStore[nPathSlot].PosX[nVert] = StraightPath[nIndex++]; - m_PathStore[nPathSlot].PosY[nVert] = StraightPath[nIndex++]; - m_PathStore[nPathSlot].PosZ[nVert] = StraightPath[nIndex++];*/ - - NiPoint3 newPoint{ m_straightPath[nIndex++], m_straightPath[nIndex++], m_straightPath[nIndex++] }; - path.push_back(newPoint); - } - } - } else { - m_npolys = 0; - m_nstraightPath = 0; - } - - return path; -} diff --git a/dPhysics/dpWorld.h b/dPhysics/dpWorld.h index 5362803f..9f13f7a9 100644 --- a/dPhysics/dpWorld.h +++ b/dPhysics/dpWorld.h @@ -1,6 +1,6 @@ #pragma once + #include "Singleton.h" -#include //Navmesh includes: #include "Recast.h" @@ -11,23 +11,7 @@ #include #include -static const int NAVMESHSET_MAGIC = 'M' << 24 | 'S' << 16 | 'E' << 8 | 'T'; //'MSET'; -static const int NAVMESHSET_VERSION = 1; - -struct NavMeshSetHeader { - int magic; - int version; - int numTiles; - dtNavMeshParams params; -}; - -struct NavMeshTileHeader { - dtTileRef tileRef; - int dataSize; -}; - -static const int MAX_POLYS = 256; -static const int MAX_SMOOTH = 2048; +#include "dNavMesh.h" class NiPoint3; class dpEntity; @@ -38,22 +22,17 @@ public: void Initialize(unsigned int zoneID); ~dpWorld(); - void RecastCleanup(); - bool LoadNavmeshByZoneID(unsigned int zoneID); - dtNavMesh* LoadNavmesh(const char* path); - bool ShouldLoadNavmesh(unsigned int zoneID); bool ShouldUseSP(unsigned int zoneID); - - float GetHeightAtPoint(const NiPoint3& location); - std::vector GetPath(const NiPoint3& startPos, const NiPoint3& endPos, float speed = 10.0f); - bool IsLoaded() const { return m_navMesh != nullptr; } + bool IsLoaded() const { return m_NavMesh != nullptr; } void StepWorld(float deltaTime); void AddEntity(dpEntity* entity); void RemoveEntity(dpEntity* entity); + dNavMesh* GetNavMesh() { return m_NavMesh; } + private: dpGrid* m_Grid; bool phys_spatial_partitioning = 1; @@ -63,18 +42,5 @@ private: std::vector m_StaticEntities; std::vector m_DynamicEntites; - //Navmesh stuffs: - unsigned char* m_triareas; - rcHeightfield* m_solid; - rcCompactHeightfield* m_chf; - rcContourSet* m_cset; - rcPolyMesh* m_pmesh; - rcConfig m_cfg; - rcPolyMeshDetail* m_dmesh; - - class InputGeom* m_geom; - class dtNavMesh* m_navMesh; - class dtNavMeshQuery* m_navQuery; - unsigned char m_navMeshDrawFlags; - rcContext* m_ctx; + dNavMesh* m_NavMesh; }; diff --git a/dScripts/BaseEnemyMech.cpp b/dScripts/BaseEnemyMech.cpp index 32dc38dd..8017be2c 100644 --- a/dScripts/BaseEnemyMech.cpp +++ b/dScripts/BaseEnemyMech.cpp @@ -17,7 +17,7 @@ void BaseEnemyMech::OnDie(Entity* self, Entity* killer) { ControllablePhysicsComponent* controlPhys = static_cast(self->GetComponent(COMPONENT_TYPE_CONTROLLABLE_PHYSICS)); if (!controlPhys) return; - NiPoint3 newLoc = { controlPhys->GetPosition().x, dpWorld::Instance().GetHeightAtPoint(controlPhys->GetPosition()), controlPhys->GetPosition().z }; + NiPoint3 newLoc = { controlPhys->GetPosition().x, dpWorld::Instance().GetNavMesh()->GetHeightAtPoint(controlPhys->GetPosition()), controlPhys->GetPosition().z }; EntityInfo info = EntityInfo(); std::vector cfg; diff --git a/dWorldServer/CMakeLists.txt b/dWorldServer/CMakeLists.txt index 3df808a2..05338960 100644 --- a/dWorldServer/CMakeLists.txt +++ b/dWorldServer/CMakeLists.txt @@ -1,6 +1,6 @@ set(DWORLDSERVER_SOURCES "ObjectIDManager.cpp" "PerformanceManager.cpp" "WorldServer.cpp") - + add_executable(WorldServer ${DWORLDSERVER_SOURCES}) -target_link_libraries(WorldServer ${COMMON_LIBRARIES} dChatFilter dGame dZoneManager dPhysics detour recast tinyxml2) +target_link_libraries(WorldServer ${COMMON_LIBRARIES} dChatFilter dGame dZoneManager dPhysics detour recast tinyxml2 dNavigation) From a429489846d847c1457f49bbda793da4539357de Mon Sep 17 00:00:00 2001 From: Daniel Seiler Date: Tue, 2 Aug 2022 15:56:20 +0200 Subject: [PATCH 41/86] use UTF8ToUTF16 more (#695) --- dChatServer/ChatPacketHandler.cpp | 4 +- dChatServer/PlayerContainer.cpp | 12 ++--- dCommon/LDFFormat.cpp | 2 +- dDatabase/Tables/CDRailActivatorComponent.cpp | 23 +++------- dGame/LeaderboardManager.cpp | 2 +- dGame/dComponents/CharacterComponent.cpp | 4 +- dGame/dComponents/PetComponent.cpp | 20 ++++---- dGame/dGameMessages/GameMessages.cpp | 7 ++- dGame/dGameMessages/PropertyDataMessage.cpp | 8 ++-- .../PropertySelectQueryProperty.cpp | 6 +-- dGame/dUtilities/Mail.cpp | 6 +-- dGame/dUtilities/SlashCommandHandler.cpp | 46 ++++++++++--------- 12 files changed, 68 insertions(+), 72 deletions(-) diff --git a/dChatServer/ChatPacketHandler.cpp b/dChatServer/ChatPacketHandler.cpp index 83678525..b5db597f 100644 --- a/dChatServer/ChatPacketHandler.cpp +++ b/dChatServer/ChatPacketHandler.cpp @@ -599,7 +599,7 @@ void ChatPacketHandler::HandleTeamKick(Packet* packet) { if (kicked != nullptr) { kickedId = kicked->playerID; } else { - kickedId = playerContainer.GetId(GeneralUtils::ASCIIToUTF16(kickedPlayer)); + kickedId = playerContainer.GetId(GeneralUtils::UTF8ToUTF16(kickedPlayer)); } if (kickedId == LWOOBJID_EMPTY) return; @@ -690,7 +690,7 @@ void ChatPacketHandler::HandleTeamStatusRequest(Packet* packet) { playerContainer.TeamStatusUpdate(team); - const auto leaderName = GeneralUtils::ASCIIToUTF16(std::string(data->playerName.c_str())); + const auto leaderName = GeneralUtils::UTF8ToUTF16(data->playerName); for (const auto memberId : team->memberIDs) { auto* otherMember = playerContainer.GetPlayerData(memberId); diff --git a/dChatServer/PlayerContainer.cpp b/dChatServer/PlayerContainer.cpp index d8c2e067..6bf3ccd1 100644 --- a/dChatServer/PlayerContainer.cpp +++ b/dChatServer/PlayerContainer.cpp @@ -35,7 +35,7 @@ void PlayerContainer::InsertPlayer(Packet* packet) { inStream.Read(data->muteExpire); data->sysAddr = packet->systemAddress; - mNames[data->playerID] = GeneralUtils::ASCIIToUTF16(std::string(data->playerName.c_str())); + mNames[data->playerID] = GeneralUtils::UTF8ToUTF16(data->playerName); mPlayers.insert(std::make_pair(data->playerID, data)); Game::logger->Log("PlayerContainer", "Added user: %s (%llu), zone: %i", data->playerName.c_str(), data->playerID, data->zoneID.GetMapID()); @@ -71,7 +71,7 @@ void PlayerContainer::RemovePlayer(Packet* packet) { auto* team = GetTeam(playerID); if (team != nullptr) { - const auto memberName = GeneralUtils::ASCIIToUTF16(std::string(player->playerName.c_str())); + const auto memberName = GeneralUtils::UTF8ToUTF16(std::string(player->playerName.c_str())); for (const auto memberId : team->memberIDs) { auto* otherMember = GetPlayerData(memberId); @@ -221,8 +221,8 @@ void PlayerContainer::AddMember(TeamData* team, LWOOBJID playerID) { if (leader == nullptr || member == nullptr) return; - const auto leaderName = GeneralUtils::ASCIIToUTF16(std::string(leader->playerName.c_str())); - const auto memberName = GeneralUtils::ASCIIToUTF16(std::string(member->playerName.c_str())); + const auto leaderName = GeneralUtils::UTF8ToUTF16(leader->playerName); + const auto memberName = GeneralUtils::UTF8ToUTF16(member->playerName); ChatPacketHandler::SendTeamInviteConfirm(member, false, leader->playerID, leader->zoneID, team->lootFlag, 0, 0, leaderName); @@ -309,7 +309,7 @@ void PlayerContainer::DisbandTeam(TeamData* team) { if (otherMember == nullptr) continue; - const auto memberName = GeneralUtils::ASCIIToUTF16(std::string(otherMember->playerName.c_str())); + const auto memberName = GeneralUtils::UTF8ToUTF16(otherMember->playerName); ChatPacketHandler::SendTeamSetLeader(otherMember, LWOOBJID_EMPTY); ChatPacketHandler::SendTeamRemovePlayer(otherMember, true, false, false, team->local, team->leaderID, otherMember->playerID, memberName); @@ -331,7 +331,7 @@ void PlayerContainer::TeamStatusUpdate(TeamData* team) { if (leader == nullptr) return; - const auto leaderName = GeneralUtils::ASCIIToUTF16(std::string(leader->playerName.c_str())); + const auto leaderName = GeneralUtils::UTF8ToUTF16(leader->playerName); for (const auto memberId : team->memberIDs) { auto* otherMember = GetPlayerData(memberId); diff --git a/dCommon/LDFFormat.cpp b/dCommon/LDFFormat.cpp index b6ea21a4..767ec81a 100644 --- a/dCommon/LDFFormat.cpp +++ b/dCommon/LDFFormat.cpp @@ -49,7 +49,7 @@ LDFBaseData* LDFBaseData::DataFromString(const std::string& format) { switch (type) { case LDF_TYPE_UTF_16: { - std::u16string data = GeneralUtils::ASCIIToUTF16(dataArray[1]); + std::u16string data = GeneralUtils::UTF8ToUTF16(dataArray[1]); return new LDFData(key, data); } diff --git a/dDatabase/Tables/CDRailActivatorComponent.cpp b/dDatabase/Tables/CDRailActivatorComponent.cpp index ef72859b..4c141256 100644 --- a/dDatabase/Tables/CDRailActivatorComponent.cpp +++ b/dDatabase/Tables/CDRailActivatorComponent.cpp @@ -8,23 +8,12 @@ CDRailActivatorComponentTable::CDRailActivatorComponentTable() { entry.id = tableData.getIntField(0); - std::string startAnimation(tableData.getStringField(1, "")); - entry.startAnimation = GeneralUtils::ASCIIToUTF16(startAnimation); - - std::string loopAnimation(tableData.getStringField(2, "")); - entry.loopAnimation = GeneralUtils::ASCIIToUTF16(loopAnimation); - - std::string stopAnimation(tableData.getStringField(3, "")); - entry.stopAnimation = GeneralUtils::ASCIIToUTF16(stopAnimation); - - std::string startSound(tableData.getStringField(4, "")); - entry.startSound = GeneralUtils::ASCIIToUTF16(startSound); - - std::string loopSound(tableData.getStringField(5, "")); - entry.loopSound = GeneralUtils::ASCIIToUTF16(loopSound); - - std::string stopSound(tableData.getStringField(6, "")); - entry.stopSound = GeneralUtils::ASCIIToUTF16(stopSound); + entry.startAnimation = GeneralUtils::ASCIIToUTF16(tableData.getStringField(1, "")); + entry.loopAnimation = GeneralUtils::ASCIIToUTF16(tableData.getStringField(2, "")); + entry.stopAnimation = GeneralUtils::ASCIIToUTF16(tableData.getStringField(3, "")); + entry.startSound = GeneralUtils::ASCIIToUTF16(tableData.getStringField(4, "")); + entry.loopSound = GeneralUtils::ASCIIToUTF16(tableData.getStringField(5, "")); + entry.stopSound = GeneralUtils::ASCIIToUTF16(tableData.getStringField(6, "")); std::string loopEffectString(tableData.getStringField(7, "")); entry.loopEffectID = EffectPairFromString(loopEffectString); diff --git a/dGame/LeaderboardManager.cpp b/dGame/LeaderboardManager.cpp index 71a154bd..b069e761 100644 --- a/dGame/LeaderboardManager.cpp +++ b/dGame/LeaderboardManager.cpp @@ -45,7 +45,7 @@ std::u16string Leaderboard::ToString() const { index++; } - return GeneralUtils::ASCIIToUTF16(leaderboard); + return GeneralUtils::UTF8ToUTF16(leaderboard); } std::vector Leaderboard::GetEntries() { diff --git a/dGame/dComponents/CharacterComponent.cpp b/dGame/dComponents/CharacterComponent.cpp index 3b4b8db8..42b8ed34 100644 --- a/dGame/dComponents/CharacterComponent.cpp +++ b/dGame/dComponents/CharacterComponent.cpp @@ -228,7 +228,7 @@ void CharacterComponent::LoadFromXml(tinyxml2::XMLDocument* doc) { const tinyxml2::XMLAttribute* rocketConfig = character->FindAttribute("lcbp"); if (rocketConfig) { - m_LastRocketConfig = GeneralUtils::ASCIIToUTF16(std::string(rocketConfig->Value())); + m_LastRocketConfig = GeneralUtils::ASCIIToUTF16(rocketConfig->Value()); } else { m_LastRocketConfig = u""; } @@ -262,7 +262,7 @@ void CharacterComponent::LoadFromXml(tinyxml2::XMLDocument* doc) { character->QueryInt64Attribute("gid", &gid); if (gid != 0) { std::string guildname(gn); - m_GuildName = GeneralUtils::ASCIIToUTF16(guildname); + m_GuildName = GeneralUtils::UTF8ToUTF16(guildname); m_GuildID = gid; m_DirtySocialInfo = true; } diff --git a/dGame/dComponents/PetComponent.cpp b/dGame/dComponents/PetComponent.cpp index 7e637ab7..ef882555 100644 --- a/dGame/dComponents/PetComponent.cpp +++ b/dGame/dComponents/PetComponent.cpp @@ -121,8 +121,8 @@ void PetComponent::Serialize(RakNet::BitStream* outBitStream, bool bIsInitialUpd if (tamed) { outBitStream->Write(m_ModerationStatus); - const auto nameData = GeneralUtils::ASCIIToUTF16(m_Name); - const auto ownerNameData = GeneralUtils::ASCIIToUTF16(m_OwnerName); + const auto nameData = GeneralUtils::UTF8ToUTF16(m_Name); + const auto ownerNameData = GeneralUtils::UTF8ToUTF16(m_OwnerName); outBitStream->Write(static_cast(nameData.size())); for (const auto c : nameData) { @@ -567,7 +567,7 @@ void PetComponent::NotifyTamingBuildSuccess(NiPoint3 position) { std::string petName = tamer->GetCharacter()->GetName(); petName += "'s Pet"; - GameMessages::SendAddPetToPlayer(m_Tamer, 0, GeneralUtils::ASCIIToUTF16(petName), petSubKey, m_Parent->GetLOT(), tamer->GetSystemAddress()); + GameMessages::SendAddPetToPlayer(m_Tamer, 0, GeneralUtils::UTF8ToUTF16(petName), petSubKey, m_Parent->GetLOT(), tamer->GetSystemAddress()); GameMessages::SendRegisterPetID(m_Tamer, m_Parent->GetObjectID(), tamer->GetSystemAddress()); @@ -634,7 +634,7 @@ void PetComponent::RequestSetPetName(std::u16string name) { //Save our pet's new name to the db: SetPetNameForModeration(GeneralUtils::UTF16ToWTF8(name)); - GameMessages::SendSetPetName(m_Owner, GeneralUtils::ASCIIToUTF16(m_Name), m_DatabaseId, owner->GetSystemAddress()); + GameMessages::SendSetPetName(m_Owner, GeneralUtils::UTF8ToUTF16(m_Name), m_DatabaseId, owner->GetSystemAddress()); GameMessages::SendSetPetNameModerated(m_Owner, m_DatabaseId, m_ModerationStatus, owner->GetSystemAddress()); } @@ -665,9 +665,11 @@ void PetComponent::RequestSetPetName(std::u16string name) { EntityManager::Instance()->SerializeEntity(m_Parent); - GameMessages::SendSetPetName(m_Tamer, GeneralUtils::ASCIIToUTF16(m_Name), m_DatabaseId, tamer->GetSystemAddress()); - GameMessages::SendSetPetName(m_Tamer, GeneralUtils::ASCIIToUTF16(m_Name), LWOOBJID_EMPTY, tamer->GetSystemAddress()); - GameMessages::SendPetNameChanged(m_Parent->GetObjectID(), m_ModerationStatus, GeneralUtils::ASCIIToUTF16(m_Name), GeneralUtils::ASCIIToUTF16(m_OwnerName), UNASSIGNED_SYSTEM_ADDRESS); + std::u16string u16name = GeneralUtils::UTF8ToUTF16(m_Name); + std::u16string u16ownerName = GeneralUtils::UTF8ToUTF16(m_OwnerName); + GameMessages::SendSetPetName(m_Tamer, u16name, m_DatabaseId, tamer->GetSystemAddress()); + GameMessages::SendSetPetName(m_Tamer, u16name, LWOOBJID_EMPTY, tamer->GetSystemAddress()); + GameMessages::SendPetNameChanged(m_Parent->GetObjectID(), m_ModerationStatus, u16name, u16ownerName, UNASSIGNED_SYSTEM_ADDRESS); GameMessages::SendSetPetNameModerated(m_Tamer, m_DatabaseId, m_ModerationStatus, tamer->GetSystemAddress()); GameMessages::SendNotifyPetTamingMinigame( @@ -877,7 +879,7 @@ void PetComponent::Activate(Item* item, bool registerPet, bool fromTaming) { m_OwnerName = owner->GetCharacter()->GetName(); if (updatedModerationStatus) { - GameMessages::SendSetPetName(m_Owner, GeneralUtils::ASCIIToUTF16(m_Name), m_DatabaseId, owner->GetSystemAddress()); + GameMessages::SendSetPetName(m_Owner, GeneralUtils::UTF8ToUTF16(m_Name), m_DatabaseId, owner->GetSystemAddress()); GameMessages::SendSetPetNameModerated(m_Owner, m_DatabaseId, m_ModerationStatus, owner->GetSystemAddress()); } @@ -892,7 +894,7 @@ void PetComponent::Activate(Item* item, bool registerPet, bool fromTaming) { owner->GetCharacter()->SetPlayerFlag(69, true); if (registerPet) { - GameMessages::SendAddPetToPlayer(m_Owner, 0, GeneralUtils::ASCIIToUTF16(m_Name), m_DatabaseId, m_Parent->GetLOT(), owner->GetSystemAddress()); + GameMessages::SendAddPetToPlayer(m_Owner, 0, GeneralUtils::UTF8ToUTF16(m_Name), m_DatabaseId, m_Parent->GetLOT(), owner->GetSystemAddress()); GameMessages::SendRegisterPetID(m_Owner, m_Parent->GetObjectID(), owner->GetSystemAddress()); diff --git a/dGame/dGameMessages/GameMessages.cpp b/dGame/dGameMessages/GameMessages.cpp index f4546416..1b98381a 100644 --- a/dGame/dGameMessages/GameMessages.cpp +++ b/dGame/dGameMessages/GameMessages.cpp @@ -978,6 +978,8 @@ void GameMessages::SendSetNetworkScriptVar(Entity* entity, const SystemAddress& bitStream.Write(entity->GetObjectID()); bitStream.Write((uint16_t)GAME_MSG_SET_NETWORK_SCRIPT_VAR); + // FIXME: this is a bad place to need to do a conversion because we have no clue whether data is utf8 or plain ascii + // an this has performance implications const auto u16Data = GeneralUtils::ASCIIToUTF16(data); uint32_t dataSize = static_cast(u16Data.size()); @@ -3188,7 +3190,7 @@ void GameMessages::HandleClientTradeRequest(RakNet::BitStream* inStream, Entity* i64Invitee, bNeedInvitePopUp, entity->GetObjectID(), - GeneralUtils::ASCIIToUTF16(entity->GetCharacter()->GetName()), + GeneralUtils::UTF8ToUTF16(entity->GetCharacter()->GetName()), invitee->GetSystemAddress() ); } @@ -5086,7 +5088,8 @@ void GameMessages::HandleNotifyServerLevelProcessingComplete(RakNet::BitStream* wss << "name=0:"; wss << character->GetName(); - std::u16string attrs = GeneralUtils::ASCIIToUTF16(wss.str()); + // FIXME: only really need utf8 conversion for the name, so move that up? + std::u16string attrs = GeneralUtils::UTF8ToUTF16(wss.str()); std::u16string wsText = u"UI_LEVEL_PROGRESSION_LEVELUP_MESSAGE"; GameMessages::SendBroadcastTextToChatbox(entity, UNASSIGNED_SYSTEM_ADDRESS, attrs, wsText); diff --git a/dGame/dGameMessages/PropertyDataMessage.cpp b/dGame/dGameMessages/PropertyDataMessage.cpp index 853151c9..c30285fd 100644 --- a/dGame/dGameMessages/PropertyDataMessage.cpp +++ b/dGame/dGameMessages/PropertyDataMessage.cpp @@ -14,19 +14,19 @@ void GameMessages::PropertyDataMessage::Serialize(RakNet::BitStream& stream) con stream.Write(VendorMapId); // - vendor map id stream.Write(cloneId); // clone id - const auto& name = GeneralUtils::ASCIIToUTF16(Name); + const auto& name = GeneralUtils::UTF8ToUTF16(Name); stream.Write(uint32_t(name.size())); for (uint32_t i = 0; i < name.size(); ++i) { stream.Write(uint16_t(name[i])); } - const auto& description = GeneralUtils::ASCIIToUTF16(Description); + const auto& description = GeneralUtils::UTF8ToUTF16(Description); stream.Write(uint32_t(description.size())); for (uint32_t i = 0; i < description.size(); ++i) { stream.Write(uint16_t(description[i])); } - const auto& owner = GeneralUtils::ASCIIToUTF16(OwnerName); + const auto& owner = GeneralUtils::UTF8ToUTF16(OwnerName); stream.Write(uint32_t(owner.size())); for (uint32_t i = 0; i < owner.size(); ++i) { stream.Write(uint16_t(owner[i])); @@ -68,7 +68,7 @@ void GameMessages::PropertyDataMessage::Serialize(RakNet::BitStream& stream) con else stream.Write(REJECTION_STATUS_PENDING); // Does this go here??? - // const auto& rejectionReasonConverted = GeneralUtils::ASCIIToUTF16(rejectionReason); + // const auto& rejectionReasonConverted = GeneralUtils::UTF8ToUTF16(rejectionReason); // stream.Write(uint32_t(rejectionReasonConverted.size())); // for (uint32_t i = 0; i < rejectionReasonConverted.size(); ++i) { // stream.Write(uint16_t(rejectionReasonConverted[i])); diff --git a/dGame/dGameMessages/PropertySelectQueryProperty.cpp b/dGame/dGameMessages/PropertySelectQueryProperty.cpp index 18d23d2b..cd17a58b 100644 --- a/dGame/dGameMessages/PropertySelectQueryProperty.cpp +++ b/dGame/dGameMessages/PropertySelectQueryProperty.cpp @@ -3,19 +3,19 @@ void PropertySelectQueryProperty::Serialize(RakNet::BitStream& stream) const { stream.Write(CloneId); - const auto& owner = GeneralUtils::ASCIIToUTF16(OwnerName); + const auto& owner = GeneralUtils::UTF8ToUTF16(OwnerName); stream.Write(uint32_t(owner.size())); for (uint32_t i = 0; i < owner.size(); ++i) { stream.Write(static_cast(owner[i])); } - const auto& name = GeneralUtils::ASCIIToUTF16(Name); + const auto& name = GeneralUtils::UTF8ToUTF16(Name); stream.Write(uint32_t(name.size())); for (uint32_t i = 0; i < name.size(); ++i) { stream.Write(static_cast(name[i])); } - const auto& description = GeneralUtils::ASCIIToUTF16(Description); + const auto& description = GeneralUtils::UTF8ToUTF16(Description); stream.Write(uint32_t(description.size())); for (uint32_t i = 0; i < description.size(); ++i) { stream.Write(static_cast(description[i])); diff --git a/dGame/dUtilities/Mail.cpp b/dGame/dUtilities/Mail.cpp index 59ce8444..8280b627 100644 --- a/dGame/dUtilities/Mail.cpp +++ b/dGame/dUtilities/Mail.cpp @@ -290,9 +290,9 @@ void Mail::HandleDataRequest(RakNet::BitStream* packet, const SystemAddress& sys while (res->next()) { bitStream.Write(res->getUInt64(1)); //MailID - /*std::u16string subject = GeneralUtils::ASCIIToUTF16(res->getString(7)); - std::u16string body = GeneralUtils::ASCIIToUTF16(res->getString(8)); - std::u16string sender = GeneralUtils::ASCIIToUTF16(res->getString(3)); + /*std::u16string subject = GeneralUtils::UTF8ToUTF16(res->getString(7)); + std::u16string body = GeneralUtils::UTF8ToUTF16(res->getString(8)); + std::u16string sender = GeneralUtils::UTF8ToUTF16(res->getString(3)); WriteToPacket(&bitStream, subject, 50); WriteToPacket(&bitStream, body, 400); diff --git a/dGame/dUtilities/SlashCommandHandler.cpp b/dGame/dUtilities/SlashCommandHandler.cpp index 6ef1632b..0bf37288 100644 --- a/dGame/dUtilities/SlashCommandHandler.cpp +++ b/dGame/dUtilities/SlashCommandHandler.cpp @@ -173,7 +173,7 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit std::stringstream message; message << character->GetName() << " changed their PVP flag to " << std::to_string(character->GetPvpEnabled()) << "!"; - ChatPackets::SendSystemMessage(UNASSIGNED_SYSTEM_ADDRESS, GeneralUtils::ASCIIToUTF16(message.str()), true); + ChatPackets::SendSystemMessage(UNASSIGNED_SYSTEM_ADDRESS, GeneralUtils::UTF8ToUTF16(message.str()), true); return; } @@ -189,7 +189,7 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit ChatPackets::SendSystemMessage( sysAddr, - GeneralUtils::ASCIIToUTF16(player == entity ? name + " (you)" : name) + GeneralUtils::UTF8ToUTF16(player == entity ? name + " (you)" : name) ); } } @@ -678,6 +678,7 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit return; } + // FIXME: use fallible ASCIIToUTF16 conversion, because non-ascii isn't valid anyway GameMessages::SendPlayFXEffect(entity->GetObjectID(), effectID, GeneralUtils::ASCIIToUTF16(args[1]), args[2]); } @@ -829,7 +830,7 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit name += arg + " "; } - GameMessages::SendSetName(entity->GetObjectID(), GeneralUtils::ASCIIToUTF16(name), UNASSIGNED_SYSTEM_ADDRESS); + GameMessages::SendSetName(entity->GetObjectID(), GeneralUtils::UTF8ToUTF16(name), UNASSIGNED_SYSTEM_ADDRESS); } if (chatCommand == "title" && entity->GetGMLevel() >= GAME_MASTER_LEVEL_DEVELOPER) { @@ -839,7 +840,7 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit name += arg + " "; } - GameMessages::SendSetName(entity->GetObjectID(), GeneralUtils::ASCIIToUTF16(name), UNASSIGNED_SYSTEM_ADDRESS); + GameMessages::SendSetName(entity->GetObjectID(), GeneralUtils::UTF8ToUTF16(name), UNASSIGNED_SYSTEM_ADDRESS); } if ((chatCommand == "teleport" || chatCommand == "tele") && entity->GetGMLevel() >= GAME_MASTER_LEVEL_JUNIOR_MODERATOR) { @@ -971,7 +972,7 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit delete result; if (accountId == 0) { - ChatPackets::SendSystemMessage(sysAddr, u"Count not find player of name: " + GeneralUtils::ASCIIToUTF16(args[0])); + ChatPackets::SendSystemMessage(sysAddr, u"Count not find player of name: " + GeneralUtils::UTF8ToUTF16(args[0])); return; } @@ -1023,7 +1024,7 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit const auto timeStr = GeneralUtils::ASCIIToUTF16(std::string(buffer)); - ChatPackets::SendSystemMessage(sysAddr, u"Muted: " + GeneralUtils::ASCIIToUTF16(args[0]) + u" until " + timeStr); + ChatPackets::SendSystemMessage(sysAddr, u"Muted: " + GeneralUtils::UTF8ToUTF16(args[0]) + u" until " + timeStr); //Notify chat about it CBITSTREAM; @@ -1042,15 +1043,15 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit if (args.size() == 1) { auto* player = Player::GetPlayer(args[0]); + std::u16string username = GeneralUtils::UTF8ToUTF16(args[0]); if (player == nullptr) { - ChatPackets::SendSystemMessage(sysAddr, u"Count not find player of name: " + GeneralUtils::ASCIIToUTF16(args[0])); - + ChatPackets::SendSystemMessage(sysAddr, u"Count not find player of name: " + username); return; } Game::server->Disconnect(player->GetSystemAddress(), SERVER_DISCON_KICK); - ChatPackets::SendSystemMessage(sysAddr, u"Kicked: " + GeneralUtils::ASCIIToUTF16(args[0])); + ChatPackets::SendSystemMessage(sysAddr, u"Kicked: " + username); } else { ChatPackets::SendSystemMessage(sysAddr, u"Correct usage: /kick "); } @@ -1077,7 +1078,7 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit delete result; if (accountId == 0) { - ChatPackets::SendSystemMessage(sysAddr, u"Count not find player of name: " + GeneralUtils::ASCIIToUTF16(args[0])); + ChatPackets::SendSystemMessage(sysAddr, u"Count not find player of name: " + GeneralUtils::UTF8ToUTF16(args[0])); return; } @@ -1165,7 +1166,7 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit while (!tables.eof()) { std::string message = std::to_string(tables.getIntField(0)) + " - " + tables.getStringField(1); - ChatPackets::SendSystemMessage(sysAddr, GeneralUtils::ASCIIToUTF16(message, message.size())); + ChatPackets::SendSystemMessage(sysAddr, GeneralUtils::UTF8ToUTF16(message, message.size())); tables.nextRow(); } } @@ -1222,12 +1223,12 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit auto requestedPlayer = Player::GetPlayer(requestedPlayerToSetLevelOf); if (!requestedPlayer) { - ChatPackets::SendSystemMessage(sysAddr, u"No player found with username: (" + GeneralUtils::ASCIIToUTF16(requestedPlayerToSetLevelOf) + u")."); + ChatPackets::SendSystemMessage(sysAddr, u"No player found with username: (" + GeneralUtils::UTF8ToUTF16(requestedPlayerToSetLevelOf) + u")."); return; } if (!requestedPlayer->GetOwner()) { - ChatPackets::SendSystemMessage(sysAddr, u"No entity found with username: (" + GeneralUtils::ASCIIToUTF16(requestedPlayerToSetLevelOf) + u")."); + ChatPackets::SendSystemMessage(sysAddr, u"No entity found with username: (" + GeneralUtils::UTF8ToUTF16(requestedPlayerToSetLevelOf) + u")."); return; } @@ -1269,7 +1270,7 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit if (requestedPlayerToSetLevelOf != "") { ChatPackets::SendSystemMessage( - sysAddr, u"Set " + GeneralUtils::ASCIIToUTF16(requestedPlayerToSetLevelOf) + u"'s level to " + GeneralUtils::to_u16string(requestedLevel) + + sysAddr, u"Set " + GeneralUtils::UTF8ToUTF16(requestedPlayerToSetLevelOf) + u"'s level to " + GeneralUtils::to_u16string(requestedLevel) + u" and UScore to " + GeneralUtils::to_u16string(characterComponent->GetUScore()) + u". Relog to see changes."); } else { @@ -1437,8 +1438,8 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit }); } else { std::string msg = "ZoneID not found or allowed: "; - msg.append(args[0]); - ChatPackets::SendSystemMessage(sysAddr, GeneralUtils::ASCIIToUTF16(msg, msg.size())); + msg.append(args[0]); // FIXME: unnecessary utf16 re-encoding just for error + ChatPackets::SendSystemMessage(sysAddr, GeneralUtils::UTF8ToUTF16(msg, msg.size())); } } @@ -1572,17 +1573,18 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit GameConfig::SetValue(args[0], args[1]); ChatPackets::SendSystemMessage( - sysAddr, u"Set config value: " + GeneralUtils::ASCIIToUTF16(args[0]) + u" to " + GeneralUtils::ASCIIToUTF16(args[1]) + sysAddr, u"Set config value: " + GeneralUtils::UTF8ToUTF16(args[0]) + u" to " + GeneralUtils::UTF8ToUTF16(args[1]) ); } if (chatCommand == "config-get" && entity->GetGMLevel() >= GAME_MASTER_LEVEL_DEVELOPER && args.size() >= 1) { const auto& value = GameConfig::GetValue(args[0]); + std::u16string u16key = GeneralUtils::UTF8ToUTF16(args[0]); if (value.empty()) { - ChatPackets::SendSystemMessage(sysAddr, u"No value found for " + GeneralUtils::ASCIIToUTF16(args[0])); + ChatPackets::SendSystemMessage(sysAddr, u"No value found for " + u16key); } else { - ChatPackets::SendSystemMessage(sysAddr, u"Value for " + GeneralUtils::ASCIIToUTF16(args[0]) + u": " + GeneralUtils::ASCIIToUTF16(value)); + ChatPackets::SendSystemMessage(sysAddr, u"Value for " + u16key + u": " + GeneralUtils::UTF8ToUTF16(value)); } } @@ -1672,7 +1674,7 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit if (!GeneralUtils::TryParse(args[0], component)) { component = -1; - ldf = GeneralUtils::ASCIIToUTF16(args[0]); + ldf = GeneralUtils::UTF8ToUTF16(args[0]); isLDF = true; } @@ -1755,10 +1757,10 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit EntityManager::Instance()->SerializeEntity(closest); } else if (args[1] == "-a" && args.size() >= 3) { - GameMessages::SendPlayAnimation(closest, GeneralUtils::ASCIIToUTF16(args[2])); + GameMessages::SendPlayAnimation(closest, GeneralUtils::UTF8ToUTF16(args[2])); } else if (args[1] == "-s") { for (auto* entry : closest->GetSettings()) { - ChatPackets::SendSystemMessage(sysAddr, GeneralUtils::ASCIIToUTF16(entry->GetString())); + ChatPackets::SendSystemMessage(sysAddr, GeneralUtils::UTF8ToUTF16(entry->GetString())); } ChatPackets::SendSystemMessage(sysAddr, u"------"); From d2b05a1ac51f4e11421d92053b476766c4f35d82 Mon Sep 17 00:00:00 2001 From: Daniel Seiler Date: Tue, 2 Aug 2022 15:56:50 +0200 Subject: [PATCH 42/86] Update Diagnostics.cpp (#697) --- dCommon/Diagnostics.cpp | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/dCommon/Diagnostics.cpp b/dCommon/Diagnostics.cpp index bfde2d9a..4c2c8beb 100644 --- a/dCommon/Diagnostics.cpp +++ b/dCommon/Diagnostics.cpp @@ -142,12 +142,12 @@ void CatchUnhandled(int sig) { demangled = demangle(functionName.c_str()); if (demangled.empty()) { - printf("[%02d] %s\n", i, demangled.c_str()); + printf("[%02zu] %s\n", i, demangled.c_str()); } else { - printf("[%02d] %s\n", i, functionName.c_str()); + printf("[%02zu] %s\n", i, functionName.c_str()); } } else { - printf("[%02d] %s\n", i, functionName.c_str()); + printf("[%02zu] %s\n", i, functionName.c_str()); } } #else From e6c7f744b5530ef1bdd50f7ba4548b452efcd676 Mon Sep 17 00:00:00 2001 From: Jett <55758076+Jettford@users.noreply.github.com> Date: Thu, 4 Aug 2022 01:59:47 +0100 Subject: [PATCH 43/86] Implement terrain file reading to generate navmeshes in the future (#703) * Implement terrain file reading to generate navmeshes in the future * Make Emo's suggested changes. --- CMakeLists.txt | 1 + dNavigation/CMakeLists.txt | 6 ++ dNavigation/dNavMesh.cpp | 4 ++ dNavigation/dTerrain/CMakeLists.txt | 3 + dNavigation/dTerrain/RawChunk.cpp | 92 +++++++++++++++++++++++++++ dNavigation/dTerrain/RawChunk.h | 24 +++++++ dNavigation/dTerrain/RawFile.cpp | 82 ++++++++++++++++++++++++ dNavigation/dTerrain/RawFile.h | 27 ++++++++ dNavigation/dTerrain/RawHeightMap.cpp | 27 ++++++++ dNavigation/dTerrain/RawHeightMap.h | 21 ++++++ dNavigation/dTerrain/RawMesh.h | 10 +++ dWorldServer/WorldServer.cpp | 2 +- dZoneManager/Zone.h | 2 + 13 files changed, 300 insertions(+), 1 deletion(-) create mode 100644 dNavigation/dTerrain/CMakeLists.txt create mode 100644 dNavigation/dTerrain/RawChunk.cpp create mode 100644 dNavigation/dTerrain/RawChunk.h create mode 100644 dNavigation/dTerrain/RawFile.cpp create mode 100644 dNavigation/dTerrain/RawFile.h create mode 100644 dNavigation/dTerrain/RawHeightMap.cpp create mode 100644 dNavigation/dTerrain/RawHeightMap.h create mode 100644 dNavigation/dTerrain/RawMesh.h diff --git a/CMakeLists.txt b/CMakeLists.txt index cdc73d69..6acca4d8 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -128,6 +128,7 @@ set(INCLUDED_DIRECTORIES "dGame/dUtilities" "dPhysics" "dNavigation" + "dNavigation/dTerrain" "dZoneManager" "dDatabase" "dDatabase/Tables" diff --git a/dNavigation/CMakeLists.txt b/dNavigation/CMakeLists.txt index beb498e3..5891c77d 100644 --- a/dNavigation/CMakeLists.txt +++ b/dNavigation/CMakeLists.txt @@ -1,4 +1,10 @@ set(DNAVIGATION_SOURCES "dNavMesh.cpp") +add_subdirectory(dTerrain) + +foreach(file ${DNAVIGATIONS_DTERRAIN_SOURCES}) + set(DNAVIGATION_SOURCES ${DNAVIGATION_SOURCES} "dTerrain/${file}") +endforeach() + add_library(dNavigation STATIC ${DNAVIGATION_SOURCES}) target_link_libraries(dNavigation detour recast) diff --git a/dNavigation/dNavMesh.cpp b/dNavigation/dNavMesh.cpp index da471882..c0bbf4b2 100644 --- a/dNavigation/dNavMesh.cpp +++ b/dNavigation/dNavMesh.cpp @@ -1,11 +1,15 @@ #include "dNavMesh.h" +#include "RawFile.h" + #include "Game.h" #include "dLogger.h" #include "dPlatforms.h" #include "NiPoint3.h" #include "BinaryIO.h" +#include "dZoneManager.h" + dNavMesh::dNavMesh(uint32_t zoneId) { m_ZoneId = zoneId; diff --git a/dNavigation/dTerrain/CMakeLists.txt b/dNavigation/dTerrain/CMakeLists.txt new file mode 100644 index 00000000..91d0741b --- /dev/null +++ b/dNavigation/dTerrain/CMakeLists.txt @@ -0,0 +1,3 @@ +set(DNAVIGATIONS_DTERRAIN_SOURCES "RawFile.cpp" + "RawChunk.cpp" + "RawHeightMap.cpp" PARENT_SCOPE) diff --git a/dNavigation/dTerrain/RawChunk.cpp b/dNavigation/dTerrain/RawChunk.cpp new file mode 100644 index 00000000..e4f753cd --- /dev/null +++ b/dNavigation/dTerrain/RawChunk.cpp @@ -0,0 +1,92 @@ +#include "RawChunk.h" + +#include "BinaryIO.h" + +#include "RawMesh.h" +#include "RawHeightMap.h" + +RawChunk::RawChunk(std::ifstream& stream) { + // Read the chunk index and info + + BinaryIO::BinaryRead(stream, m_ChunkIndex); + BinaryIO::BinaryRead(stream, m_Width); + BinaryIO::BinaryRead(stream, m_Height); + BinaryIO::BinaryRead(stream, m_X); + BinaryIO::BinaryRead(stream, m_Z); + + m_HeightMap = new RawHeightMap(stream, m_Height, m_Width); + + // We can just skip the rest of the data so we can read the next chunks, we don't need anymore data + + uint32_t colorMapSize; + BinaryIO::BinaryRead(stream, colorMapSize); + stream.seekg((uint32_t)stream.tellg() + (colorMapSize * colorMapSize * 4)); + + uint32_t lightmapSize; + BinaryIO::BinaryRead(stream, lightmapSize); + stream.seekg((uint32_t)stream.tellg() + (lightmapSize)); + + uint32_t colorMapSize2; + BinaryIO::BinaryRead(stream, colorMapSize2); + stream.seekg((uint32_t)stream.tellg() + (colorMapSize2 * colorMapSize2 * 4)); + + uint8_t unknown; + BinaryIO::BinaryRead(stream, unknown); + + uint32_t blendmapSize; + BinaryIO::BinaryRead(stream, blendmapSize); + stream.seekg((uint32_t)stream.tellg() + (blendmapSize)); + + uint32_t pointSize; + BinaryIO::BinaryRead(stream, pointSize); + stream.seekg((uint32_t)stream.tellg() + (pointSize * 9 * 4)); + + stream.seekg((uint32_t)stream.tellg() + (colorMapSize * colorMapSize)); + + uint32_t endCounter; + BinaryIO::BinaryRead(stream, endCounter); + stream.seekg((uint32_t)stream.tellg() + (endCounter * 2)); + + if (endCounter != 0) { + stream.seekg((uint32_t)stream.tellg() + (32)); + + for (int i = 0; i < 0x10; i++) { + uint16_t finalCountdown; + BinaryIO::BinaryRead(stream, finalCountdown); + stream.seekg((uint32_t)stream.tellg() + (finalCountdown * 2)); + } + } + + // Generate our mesh/geo data for this chunk + + this->GenerateMesh(); +} + +RawChunk::~RawChunk() { + if (m_Mesh) delete m_Mesh; + if (m_HeightMap) delete m_HeightMap; +} + +void RawChunk::GenerateMesh() { + RawMesh* meshData = new RawMesh(); + + for (int i = 0; i < m_Width; ++i) { + for (int j = 0; j < m_Height; ++j) { + float y = *std::next(m_HeightMap->m_FloatMap.begin(), m_Width * i + j); + + meshData->m_Vertices.push_back(NiPoint3(i, y, j)); + + if (i == 0 || j == 0) continue; + + meshData->m_Triangles.push_back(m_Width * i + j); + meshData->m_Triangles.push_back(m_Width * i + j - 1); + meshData->m_Triangles.push_back(m_Width * (i - 1) + j - 1); + + meshData->m_Triangles.push_back(m_Width * (i - 1) + j - 1); + meshData->m_Triangles.push_back(m_Width * (i - 1) + j); + meshData->m_Triangles.push_back(m_Width * i + j); + } + } + + m_Mesh = meshData; +} diff --git a/dNavigation/dTerrain/RawChunk.h b/dNavigation/dTerrain/RawChunk.h new file mode 100644 index 00000000..1e26f11d --- /dev/null +++ b/dNavigation/dTerrain/RawChunk.h @@ -0,0 +1,24 @@ +#pragma once + +#include +#include + +struct RawMesh; +class RawHeightMap; + +class RawChunk { +public: + RawChunk(std::ifstream& stream); + ~RawChunk(); + + void GenerateMesh(); + + uint32_t m_ChunkIndex; + uint32_t m_Width; + uint32_t m_Height; + float m_X; + float m_Z; + + RawHeightMap* m_HeightMap; + RawMesh* m_Mesh; +}; diff --git a/dNavigation/dTerrain/RawFile.cpp b/dNavigation/dTerrain/RawFile.cpp new file mode 100644 index 00000000..d4496b2f --- /dev/null +++ b/dNavigation/dTerrain/RawFile.cpp @@ -0,0 +1,82 @@ +#include "RawFile.h" + +#include "BinaryIO.h" +#include "RawChunk.h" +#include "RawMesh.h" +#include "RawHeightMap.h" + +RawFile::RawFile(std::string fileName) { + if (!BinaryIO::DoesFileExist(fileName)) return; + + std::ifstream file(fileName, std::ios::binary); + + // Read header + + BinaryIO::BinaryRead(file, m_Version); + BinaryIO::BinaryRead(file, m_Padding); + BinaryIO::BinaryRead(file, m_ChunkCount); + BinaryIO::BinaryRead(file, m_Width); + BinaryIO::BinaryRead(file, m_Height); + + + if (m_Version < 0x20) { + return; // Version too crusty to handle + } + + // Read in chunks + + m_Chunks = {}; + + for (uint32_t i = 0; i < m_ChunkCount; i++) { + RawChunk* chunk = new RawChunk(file); + m_Chunks.push_back(chunk); + } + + this->GenerateFinalMeshFromChunks(); +} + +RawFile::~RawFile() { + delete m_FinalMesh; + for (const auto* item : m_Chunks) { + delete item; + } +} + +void RawFile::GenerateFinalMeshFromChunks() { + uint32_t lenOfLastChunk = 0; // index of last vert set in the last chunk + + for (const auto& chunk : m_Chunks) { + for (const auto& vert : chunk->m_Mesh->m_Vertices) { + auto tempVert = vert; + + tempVert.SetX(tempVert.GetX() + (chunk->m_X / 4)); + tempVert.SetZ(tempVert.GetZ() + (chunk->m_Z / 4)); + + tempVert* chunk->m_HeightMap->m_ScaleFactor; + + m_FinalMesh->m_Vertices.push_back(tempVert); + } + + for (const auto& tri : chunk->m_Mesh->m_Triangles) { + m_FinalMesh->m_Triangles.push_back(tri + lenOfLastChunk); + } + + lenOfLastChunk += chunk->m_Mesh->m_Vertices.size(); + } +} + +void RawFile::WriteFinalMeshToOBJ(std::string path) { + std::ofstream file(path); + std::string vertData; + + for (const auto& v : m_FinalMesh->m_Vertices) { + vertData += "v " + std::to_string(v.x) + " " + std::to_string(v.y) + " " + std::to_string(v.z) + "\n"; + } + + for (int i = 0; i < m_FinalMesh->m_Triangles.size(); i += 3) { + vertData += "f " + std::to_string(*std::next(m_FinalMesh->m_Triangles.begin(), i) + 1) + " " + std::to_string(*std::next(m_FinalMesh->m_Triangles.begin(), i + 1) + 1) + " " + std::to_string(*std::next(m_FinalMesh->m_Triangles.begin(), i + 2) + 1) + "\n"; + } + + file.write(vertData.c_str(), vertData.size()); + file.close(); +} diff --git a/dNavigation/dTerrain/RawFile.h b/dNavigation/dTerrain/RawFile.h new file mode 100644 index 00000000..84afae94 --- /dev/null +++ b/dNavigation/dTerrain/RawFile.h @@ -0,0 +1,27 @@ +#pragma once + +#include +#include + +class RawChunk; +struct RawMesh; + +class RawFile { +public: + RawFile(std::string filePath); + ~RawFile(); + +private: + + void GenerateFinalMeshFromChunks(); + void WriteFinalMeshToOBJ(std::string path); + + uint8_t m_Version; + uint16_t m_Padding; + uint32_t m_ChunkCount; + uint32_t m_Width; + uint32_t m_Height; + + std::vector m_Chunks; + RawMesh* m_FinalMesh; +}; diff --git a/dNavigation/dTerrain/RawHeightMap.cpp b/dNavigation/dTerrain/RawHeightMap.cpp new file mode 100644 index 00000000..e1310669 --- /dev/null +++ b/dNavigation/dTerrain/RawHeightMap.cpp @@ -0,0 +1,27 @@ +#include "RawHeightMap.h" + +#include "BinaryIO.h" + +RawHeightMap::RawHeightMap() {} + +RawHeightMap::RawHeightMap(std::ifstream& stream, float height, float width) { + // Read in height map data header and scale + + BinaryIO::BinaryRead(stream, m_Unknown1); + BinaryIO::BinaryRead(stream, m_Unknown2); + BinaryIO::BinaryRead(stream, m_Unknown3); + BinaryIO::BinaryRead(stream, m_Unknown4); + BinaryIO::BinaryRead(stream, m_ScaleFactor); + + // read all vertices in + + for (uint64_t i = 0; i < width * height; i++) { + float value; + BinaryIO::BinaryRead(stream, value); + m_FloatMap.push_back(value); + } +} + +RawHeightMap::~RawHeightMap() { + +} diff --git a/dNavigation/dTerrain/RawHeightMap.h b/dNavigation/dTerrain/RawHeightMap.h new file mode 100644 index 00000000..9a4bda3b --- /dev/null +++ b/dNavigation/dTerrain/RawHeightMap.h @@ -0,0 +1,21 @@ +#pragma once + +#include +#include +#include + +class RawHeightMap { +public: + RawHeightMap(); + RawHeightMap(std::ifstream& stream, float height, float width); + ~RawHeightMap(); + + uint32_t m_Unknown1; + uint32_t m_Unknown2; + uint32_t m_Unknown3; + uint32_t m_Unknown4; + + float m_ScaleFactor; + + std::vector m_FloatMap = {}; +}; diff --git a/dNavigation/dTerrain/RawMesh.h b/dNavigation/dTerrain/RawMesh.h new file mode 100644 index 00000000..ed8eb4f3 --- /dev/null +++ b/dNavigation/dTerrain/RawMesh.h @@ -0,0 +1,10 @@ +#pragma once + +#include + +#include "NiPoint3.h" + +struct RawMesh { + std::vector m_Vertices; + std::vector m_Triangles; +}; diff --git a/dWorldServer/WorldServer.cpp b/dWorldServer/WorldServer.cpp index df5484fd..74c730f6 100644 --- a/dWorldServer/WorldServer.cpp +++ b/dWorldServer/WorldServer.cpp @@ -233,9 +233,9 @@ int main(int argc, char** argv) { //Load our level: if (zoneID != 0) { + dZoneManager::Instance()->Initialize(LWOZONEID(zoneID, instanceID, cloneID)); dpWorld::Instance().Initialize(zoneID); Game::physicsWorld = &dpWorld::Instance(); //just in case some old code references it - dZoneManager::Instance()->Initialize(LWOZONEID(zoneID, instanceID, cloneID)); g_CloneID = cloneID; // pre calculate the FDB checksum diff --git a/dZoneManager/Zone.h b/dZoneManager/Zone.h index 5d3dc424..50530273 100644 --- a/dZoneManager/Zone.h +++ b/dZoneManager/Zone.h @@ -190,6 +190,8 @@ public: uint32_t GetWorldID() const { return m_WorldID; } [[nodiscard]] std::string GetZoneName() const { return m_ZoneName; } + std::string GetZoneRawPath() const { return m_ZoneRawPath;} + std::string GetZonePath() const { return m_ZonePath; } const NiPoint3& GetSpawnPos() const { return m_Spawnpoint; } const NiQuaternion& GetSpawnRot() const { return m_SpawnpointRotation; } From 88f316bf93228a847ddfd03180a63091ef6e01cd Mon Sep 17 00:00:00 2001 From: Jett <55758076+Jettford@users.noreply.github.com> Date: Thu, 4 Aug 2022 14:54:14 +0100 Subject: [PATCH 44/86] Add null checks to all free calls to prevent crash on server close. (#709) --- dNavigation/dNavMesh.cpp | 14 +++++++------- dPhysics/dpWorld.cpp | 7 ++++--- dPhysics/dpWorld.h | 2 +- 3 files changed, 12 insertions(+), 11 deletions(-) diff --git a/dNavigation/dNavMesh.cpp b/dNavigation/dNavMesh.cpp index c0bbf4b2..b3c8a229 100644 --- a/dNavigation/dNavMesh.cpp +++ b/dNavigation/dNavMesh.cpp @@ -28,13 +28,13 @@ dNavMesh::dNavMesh(uint32_t zoneId) { dNavMesh::~dNavMesh() { // Clean up Recast information - rcFreeHeightField(m_Solid); - rcFreeCompactHeightfield(m_CHF); - rcFreeContourSet(m_CSet); - rcFreePolyMesh(m_PMesh); - rcFreePolyMeshDetail(m_PMDMesh); - dtFreeNavMesh(m_NavMesh); - dtFreeNavMeshQuery(m_NavQuery); + if(m_Solid) rcFreeHeightField(m_Solid); + if (m_CHF) rcFreeCompactHeightfield(m_CHF); + if (m_CSet) rcFreeContourSet(m_CSet); + if (m_PMesh) rcFreePolyMesh(m_PMesh); + if (m_PMDMesh) rcFreePolyMeshDetail(m_PMDMesh); + if (m_NavMesh) dtFreeNavMesh(m_NavMesh); + if (m_NavQuery) dtFreeNavMeshQuery(m_NavQuery); if (m_Ctx) delete m_Ctx; if (m_Triareas) delete[] m_Triareas; diff --git a/dPhysics/dpWorld.cpp b/dPhysics/dpWorld.cpp index 0a7e0df0..510da518 100644 --- a/dPhysics/dpWorld.cpp +++ b/dPhysics/dpWorld.cpp @@ -32,9 +32,10 @@ dpWorld::~dpWorld() { m_Grid = nullptr; } - m_NavMesh->~dNavMesh(); - delete m_NavMesh; - m_NavMesh = nullptr; + if (m_NavMesh) { + delete m_NavMesh; + m_NavMesh = nullptr; + } } void dpWorld::StepWorld(float deltaTime) { diff --git a/dPhysics/dpWorld.h b/dPhysics/dpWorld.h index 9f13f7a9..3878cd12 100644 --- a/dPhysics/dpWorld.h +++ b/dPhysics/dpWorld.h @@ -42,5 +42,5 @@ private: std::vector m_StaticEntities; std::vector m_DynamicEntites; - dNavMesh* m_NavMesh; + dNavMesh* m_NavMesh = nullptr; }; From 4556f1347443e227e2b154980271f391a4104957 Mon Sep 17 00:00:00 2001 From: aequabit Date: Fri, 5 Aug 2022 10:04:45 +0200 Subject: [PATCH 45/86] Mention option to use Docker in README.md (#702) --- README.md | 3 +++ 1 file changed, 3 insertions(+) diff --git a/README.md b/README.md index 9acd9abf..403f14a4 100644 --- a/README.md +++ b/README.md @@ -42,6 +42,9 @@ This was done make sure that older and incomplete clients wouldn't produce false If you're using a DLU client you'll have to go into the "CMakeVariables.txt" file and change the NET_VERSION variable to 171023 to match the modified client's version number. +### Using Docker +Refer to [Docker.md](/Docker.md). + ### Linux builds Make sure packages like `gcc`, `cmake`, and `zlib` are installed. Depending on the distribution, these packages might already be installed. Note that on systems like Ubuntu, you will need the `zlib1g-dev` package so that the header files are available. `libssl-dev` will also be required as well as `openssl`. From 408163ed3578a59733fd468192d8b6cca3fd6b54 Mon Sep 17 00:00:00 2001 From: David Markowitz <39972741+EmosewaMC@users.noreply.github.com> Date: Fri, 5 Aug 2022 05:40:27 -0700 Subject: [PATCH 46/86] Add windows docker setup guide to README (#712) * Add docker windows * Update README.md --- README.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/README.md b/README.md index 403f14a4..321e1b36 100644 --- a/README.md +++ b/README.md @@ -45,6 +45,8 @@ If you're using a DLU client you'll have to go into the "CMakeVariables.txt" fil ### Using Docker Refer to [Docker.md](/Docker.md). +For Windows, refer to [Docker_Windows.md](/Docker_Windows.md). + ### Linux builds Make sure packages like `gcc`, `cmake`, and `zlib` are installed. Depending on the distribution, these packages might already be installed. Note that on systems like Ubuntu, you will need the `zlib1g-dev` package so that the header files are available. `libssl-dev` will also be required as well as `openssl`. From 4112a85906f4dc5f55693c0f444a797a2cf80bcb Mon Sep 17 00:00:00 2001 From: Jett <55758076+Jettford@users.noreply.github.com> Date: Fri, 5 Aug 2022 13:41:07 +0100 Subject: [PATCH 47/86] Fix checks for if the physics world is loaded (#711) --- dNavigation/dNavMesh.h | 3 +++ dPhysics/dpWorld.h | 2 +- 2 files changed, 4 insertions(+), 1 deletion(-) diff --git a/dNavigation/dNavMesh.h b/dNavigation/dNavMesh.h index 09e9c895..dc3db854 100644 --- a/dNavigation/dNavMesh.h +++ b/dNavigation/dNavMesh.h @@ -17,6 +17,9 @@ public: float GetHeightAtPoint(const NiPoint3& location); std::vector GetPath(const NiPoint3& startPos, const NiPoint3& endPos, float speed = 10.0f); + + class dtNavMesh* GetdtNavMesh() { return m_NavMesh; } + private: void LoadNavmesh(); diff --git a/dPhysics/dpWorld.h b/dPhysics/dpWorld.h index 3878cd12..45e550cb 100644 --- a/dPhysics/dpWorld.h +++ b/dPhysics/dpWorld.h @@ -24,7 +24,7 @@ public: ~dpWorld(); bool ShouldUseSP(unsigned int zoneID); - bool IsLoaded() const { return m_NavMesh != nullptr; } + bool IsLoaded() const { return m_NavMesh->GetdtNavMesh() != nullptr; } void StepWorld(float deltaTime); From 9e4ce24fd2851e65df776dd9c57bcb0d45f4453a Mon Sep 17 00:00:00 2001 From: Aaron Kimbre Date: Fri, 5 Aug 2022 08:40:12 -0500 Subject: [PATCH 48/86] add semi-colons to macros consistently --- dChatServer/ChatPacketHandler.cpp | 24 +- dGame/dGameMessages/GameMessageHandler.cpp | 6 +- dGame/dGameMessages/GameMessages.cpp | 542 ++++++++++----------- dNet/ChatPackets.cpp | 10 +- dNet/MasterPackets.cpp | 4 +- dNet/WorldPackets.cpp | 30 +- dWorldServer/WorldServer.cpp | 4 +- tests/AMFDeserializeTests.cpp | 44 +- 8 files changed, 332 insertions(+), 332 deletions(-) diff --git a/dChatServer/ChatPacketHandler.cpp b/dChatServer/ChatPacketHandler.cpp index b5db597f..a51716ca 100644 --- a/dChatServer/ChatPacketHandler.cpp +++ b/dChatServer/ChatPacketHandler.cpp @@ -730,9 +730,9 @@ void ChatPacketHandler::SendTeamInviteConfirm(PlayerData* receiver, bool bLeader bitStream.Write(receiver->playerID); //portion that will get routed: - CMSGHEADER + CMSGHEADER; - bitStream.Write(receiver->playerID); + bitStream.Write(receiver->playerID); bitStream.Write(GAME_MSG::GAME_MSG_TEAM_INVITE_CONFIRM); bitStream.Write(bLeaderIsFreeTrial); @@ -757,9 +757,9 @@ void ChatPacketHandler::SendTeamStatus(PlayerData* receiver, LWOOBJID i64LeaderI bitStream.Write(receiver->playerID); //portion that will get routed: - CMSGHEADER + CMSGHEADER; - bitStream.Write(receiver->playerID); + bitStream.Write(receiver->playerID); bitStream.Write(GAME_MSG::GAME_MSG_TEAM_GET_STATUS_RESPONSE); bitStream.Write(i64LeaderID); @@ -782,9 +782,9 @@ void ChatPacketHandler::SendTeamSetLeader(PlayerData* receiver, LWOOBJID i64Play bitStream.Write(receiver->playerID); //portion that will get routed: - CMSGHEADER + CMSGHEADER; - bitStream.Write(receiver->playerID); + bitStream.Write(receiver->playerID); bitStream.Write(GAME_MSG::GAME_MSG_TEAM_SET_LEADER); bitStream.Write(i64PlayerID); @@ -799,9 +799,9 @@ void ChatPacketHandler::SendTeamAddPlayer(PlayerData* receiver, bool bIsFreeTria bitStream.Write(receiver->playerID); //portion that will get routed: - CMSGHEADER + CMSGHEADER; - bitStream.Write(receiver->playerID); + bitStream.Write(receiver->playerID); bitStream.Write(GAME_MSG::GAME_MSG_TEAM_ADD_PLAYER); bitStream.Write(bIsFreeTrial); @@ -828,9 +828,9 @@ void ChatPacketHandler::SendTeamRemovePlayer(PlayerData* receiver, bool bDisband bitStream.Write(receiver->playerID); //portion that will get routed: - CMSGHEADER + CMSGHEADER; - bitStream.Write(receiver->playerID); + bitStream.Write(receiver->playerID); bitStream.Write(GAME_MSG::GAME_MSG_TEAM_REMOVE_PLAYER); bitStream.Write(bDisband); @@ -854,9 +854,9 @@ void ChatPacketHandler::SendTeamSetOffWorldFlag(PlayerData* receiver, LWOOBJID i bitStream.Write(receiver->playerID); //portion that will get routed: - CMSGHEADER + CMSGHEADER; - bitStream.Write(receiver->playerID); + bitStream.Write(receiver->playerID); bitStream.Write(GAME_MSG::GAME_MSG_TEAM_SET_OFF_WORLD_FLAG); bitStream.Write(i64PlayerID); diff --git a/dGame/dGameMessages/GameMessageHandler.cpp b/dGame/dGameMessages/GameMessageHandler.cpp index b9115e50..b3b60fe7 100644 --- a/dGame/dGameMessages/GameMessageHandler.cpp +++ b/dGame/dGameMessages/GameMessageHandler.cpp @@ -31,10 +31,10 @@ using namespace std; void GameMessageHandler::HandleMessage(RakNet::BitStream* inStream, const SystemAddress& sysAddr, LWOOBJID objectID, GAME_MSG messageID) { - CBITSTREAM + CBITSTREAM; - // Get the entity - Entity* entity = EntityManager::Instance()->GetEntity(objectID); + // Get the entity + Entity* entity = EntityManager::Instance()->GetEntity(objectID); User* usr = UserManager::Instance()->GetUser(sysAddr); diff --git a/dGame/dGameMessages/GameMessages.cpp b/dGame/dGameMessages/GameMessages.cpp index 1b98381a..105bb526 100644 --- a/dGame/dGameMessages/GameMessages.cpp +++ b/dGame/dGameMessages/GameMessages.cpp @@ -69,10 +69,10 @@ #include "TradingManager.h" void GameMessages::SendFireEventClientSide(const LWOOBJID& objectID, const SystemAddress& sysAddr, std::u16string args, const LWOOBJID& object, int64_t param1, int param2, const LWOOBJID& sender) { - CBITSTREAM - CMSGHEADER + CBITSTREAM; + CMSGHEADER; - bitStream.Write(objectID); + bitStream.Write(objectID); bitStream.Write(GAME_MSG::GAME_MSG_FIRE_EVENT_CLIENT_SIDE); //bitStream.Write(args); @@ -88,13 +88,13 @@ void GameMessages::SendFireEventClientSide(const LWOOBJID& objectID, const Syste //bitStream.Write(param2); bitStream.Write(sender); - SEND_PACKET + SEND_PACKET; } void GameMessages::SendTeleport(const LWOOBJID& objectID, const NiPoint3& pos, const NiQuaternion& rot, const SystemAddress& sysAddr, bool bSetRotation, bool noGravTeleport) { - CBITSTREAM - CMSGHEADER - bitStream.Write(objectID); + CBITSTREAM; + CMSGHEADER; + bitStream.Write(objectID); bitStream.Write(GAME_MSG::GAME_MSG_TELEPORT); bool bIgnoreY = (pos.y == 0.0f); @@ -121,7 +121,7 @@ void GameMessages::SendTeleport(const LWOOBJID& objectID, const NiPoint3& pos, c bitStream.Write(rot.y); bitStream.Write(rot.z); - SEND_PACKET + SEND_PACKET; } void GameMessages::SendPlayAnimation(Entity* entity, const std::u16string& animationName, float fPriority, float fScale) { @@ -171,8 +171,8 @@ void GameMessages::SendPlayerReady(Entity* entity, const SystemAddress& sysAddr) } void GameMessages::SendPlayerAllowedRespawn(LWOOBJID entityID, bool doNotPromptRespawn, const SystemAddress& sysAddr) { - CBITSTREAM - CMSGHEADER; + CBITSTREAM; + CMSGHEADER; bitStream.Write(entityID); bitStream.Write(GAME_MSG::GAME_MSG_SET_PLAYER_ALLOWED_RESPAWN); @@ -182,10 +182,10 @@ void GameMessages::SendPlayerAllowedRespawn(LWOOBJID entityID, bool doNotPromptR } void GameMessages::SendInvalidZoneTransferList(Entity* entity, const SystemAddress& sysAddr, const std::u16string& feedbackURL, const std::u16string& invalidMapTransferList, bool feedbackOnExit, bool feedbackOnInvalidTransfer) { - CBITSTREAM - CMSGHEADER + CBITSTREAM; + CMSGHEADER; - bitStream.Write(entity->GetObjectID()); + bitStream.Write(entity->GetObjectID()); bitStream.Write(GAME_MSG::GAME_MSG_INVALID_ZONE_TRANSFER_LIST); uint32_t CustomerFeedbackURLLength = feedbackURL.size(); @@ -203,14 +203,14 @@ void GameMessages::SendInvalidZoneTransferList(Entity* entity, const SystemAddre bitStream.Write(feedbackOnExit); bitStream.Write(feedbackOnInvalidTransfer); - SEND_PACKET + SEND_PACKET; } void GameMessages::SendKnockback(const LWOOBJID& objectID, const LWOOBJID& caster, const LWOOBJID& originator, int knockBackTimeMS, const NiPoint3& vector) { - CBITSTREAM - CMSGHEADER + CBITSTREAM; + CMSGHEADER; - bitStream.Write(objectID); + bitStream.Write(objectID); bitStream.Write(GAME_MSG_KNOCKBACK); bool casterFlag = caster != LWOOBJID_EMPTY; @@ -225,7 +225,7 @@ void GameMessages::SendKnockback(const LWOOBJID& objectID, const LWOOBJID& caste if (knockBackTimeMSFlag) bitStream.Write(knockBackTimeMS); bitStream.Write(vector); - SEND_PACKET_BROADCAST + SEND_PACKET_BROADCAST; } void GameMessages::SendStartArrangingWithItem( @@ -243,10 +243,10 @@ void GameMessages::SendStartArrangingWithItem( NiPoint3 targetPOS, int targetTYPE ) { - CBITSTREAM - CMSGHEADER + CBITSTREAM; + CMSGHEADER; - bitStream.Write(entity->GetObjectID()); + bitStream.Write(entity->GetObjectID()); bitStream.Write(GAME_MSG::GAME_MSG_START_ARRANGING_WITH_ITEM); bitStream.Write(bFirstTime); @@ -262,15 +262,15 @@ void GameMessages::SendStartArrangingWithItem( bitStream.Write(targetPOS); bitStream.Write(targetTYPE); - SEND_PACKET + SEND_PACKET; } void GameMessages::SendPlayerSetCameraCyclingMode(const LWOOBJID& objectID, const SystemAddress& sysAddr, bool bAllowCyclingWhileDeadOnly, eCyclingMode cyclingMode) { - CBITSTREAM - CMSGHEADER + CBITSTREAM; + CMSGHEADER; - bitStream.Write(objectID); + bitStream.Write(objectID); bitStream.Write(GAME_MSG_PLAYER_SET_CAMERA_CYCLING_MODE); bitStream.Write(bAllowCyclingWhileDeadOnly); @@ -280,14 +280,14 @@ void GameMessages::SendPlayerSetCameraCyclingMode(const LWOOBJID& objectID, cons bitStream.Write(cyclingMode); } - SEND_PACKET + SEND_PACKET; } void GameMessages::SendPlayNDAudioEmitter(Entity* entity, const SystemAddress& sysAddr, std::string audioGUID) { - CBITSTREAM - CMSGHEADER + CBITSTREAM; + CMSGHEADER; - bitStream.Write(entity->GetObjectID()); + bitStream.Write(entity->GetObjectID()); bitStream.Write((uint16_t)GAME_MSG_PLAY_ND_AUDIO_EMITTER); bitStream.Write0(); bitStream.Write0(); @@ -309,7 +309,7 @@ void GameMessages::SendPlayNDAudioEmitter(Entity* entity, const SystemAddress& s bitStream.Write0(); bitStream.Write0(); - SEND_PACKET_BROADCAST + SEND_PACKET_BROADCAST; } void GameMessages::SendStartPathing(Entity* entity) { @@ -325,10 +325,10 @@ void GameMessages::SendStartPathing(Entity* entity) { void GameMessages::SendPlatformResync(Entity* entity, const SystemAddress& sysAddr, bool bStopAtDesiredWaypoint, int iIndex, int iDesiredWaypointIndex, int nextIndex, MovementPlatformState movementState) { - CBITSTREAM - CMSGHEADER + CBITSTREAM; + CMSGHEADER; - const auto lot = entity->GetLOT(); + const auto lot = entity->GetLOT(); if (lot == 12341 || lot == 5027 || lot == 5028 || lot == 14335 || lot == 14447 || lot == 14449) { iDesiredWaypointIndex = 0; @@ -373,49 +373,49 @@ void GameMessages::SendPlatformResync(Entity* entity, const SystemAddress& sysAd bitStream.Write(qUnexpectedRotation.w); } - SEND_PACKET_BROADCAST + SEND_PACKET_BROADCAST; } void GameMessages::SendRestoreToPostLoadStats(Entity* entity, const SystemAddress& sysAddr) { - CBITSTREAM - CMSGHEADER - bitStream.Write(entity->GetObjectID()); + CBITSTREAM; + CMSGHEADER; + bitStream.Write(entity->GetObjectID()); bitStream.Write(GAME_MSG::GAME_MSG_RESTORE_TO_POST_LOAD_STATS); - SEND_PACKET + SEND_PACKET; } void GameMessages::SendServerDoneLoadingAllObjects(Entity* entity, const SystemAddress& sysAddr) { - CBITSTREAM - CMSGHEADER - bitStream.Write(entity->GetObjectID()); + CBITSTREAM; + CMSGHEADER; + bitStream.Write(entity->GetObjectID()); bitStream.Write(GAME_MSG::GAME_MSG_SERVER_DONE_LOADING_ALL_OBJECTS); - SEND_PACKET + SEND_PACKET; } void GameMessages::SendChatModeUpdate(const LWOOBJID& objectID, uint8_t level) { - CBITSTREAM - CMSGHEADER - bitStream.Write(objectID); + CBITSTREAM; + CMSGHEADER; + bitStream.Write(objectID); bitStream.Write((uint16_t)GAME_MSG_UPDATE_CHAT_MODE); bitStream.Write(level); - SEND_PACKET_BROADCAST + SEND_PACKET_BROADCAST; } void GameMessages::SendGMLevelBroadcast(const LWOOBJID& objectID, uint8_t level) { - CBITSTREAM - CMSGHEADER - bitStream.Write(objectID); + CBITSTREAM; + CMSGHEADER; + bitStream.Write(objectID); bitStream.Write((uint16_t)GAME_MSG_SET_GM_LEVEL); bitStream.Write1(); bitStream.Write(level); - SEND_PACKET_BROADCAST + SEND_PACKET_BROADCAST; } void GameMessages::SendAddItemToInventoryClientSync(Entity* entity, const SystemAddress& sysAddr, Item* item, const LWOOBJID& objectID, bool showFlyingLoot, int itemCount, LWOOBJID subKey, eLootSourceType lootSourceType) { - CBITSTREAM - CMSGHEADER + CBITSTREAM; + CMSGHEADER; - bitStream.Write(entity->GetObjectID()); + bitStream.Write(entity->GetObjectID()); bitStream.Write(static_cast(GAME_MSG_ADD_ITEM_TO_INVENTORY_CLIENT_SYNC)); bitStream.Write(item->GetBound()); bitStream.Write(item->GetInfo().isBOE); @@ -467,31 +467,31 @@ void GameMessages::SendAddItemToInventoryClientSync(Entity* entity, const System bitStream.Write(showFlyingLoot); bitStream.Write(item->GetSlot()); - SEND_PACKET + SEND_PACKET; } void GameMessages::SendNotifyClientFlagChange(const LWOOBJID& objectID, int iFlagID, bool bFlag, const SystemAddress& sysAddr) { - CBITSTREAM - CMSGHEADER + CBITSTREAM; + CMSGHEADER; - bitStream.Write(objectID); + bitStream.Write(objectID); bitStream.Write((uint16_t)GAME_MSG_NOTIFY_CLIENT_FLAG_CHANGE); bitStream.Write(bFlag); bitStream.Write(iFlagID); - SEND_PACKET + SEND_PACKET; } void GameMessages::SendChangeObjectWorldState(const LWOOBJID& objectID, int state, const SystemAddress& sysAddr) { - CBITSTREAM - CMSGHEADER + CBITSTREAM; + CMSGHEADER; - bitStream.Write(objectID); + bitStream.Write(objectID); bitStream.Write((uint16_t)GAME_MSG_CHANGE_OBJECT_WORLD_STATE); bitStream.Write(state); if (sysAddr == UNASSIGNED_SYSTEM_ADDRESS) SEND_PACKET_BROADCAST - SEND_PACKET + SEND_PACKET; } void GameMessages::SendOfferMission(const LWOOBJID& entity, const SystemAddress& sysAddr, int32_t missionID, const LWOOBJID& offererID) { @@ -501,47 +501,47 @@ void GameMessages::SendOfferMission(const LWOOBJID& entity, const SystemAddress& //The second, actually makes the UI pop up so you can be offered the mission. //Why is it like this? Because LU isn't just a clown, it's the entire circus. - CBITSTREAM - CMSGHEADER + CBITSTREAM; + CMSGHEADER; - bitStream.Write(offererID); + bitStream.Write(offererID); bitStream.Write(uint16_t(GAME_MSG_OFFER_MISSION)); bitStream.Write(missionID); bitStream.Write(offererID); - SEND_PACKET + SEND_PACKET; { - CBITSTREAM - CMSGHEADER + CBITSTREAM; + CMSGHEADER; bitStream.Write(entity); bitStream.Write(uint16_t(GAME_MSG_OFFER_MISSION)); bitStream.Write(missionID); bitStream.Write(offererID); - SEND_PACKET + SEND_PACKET; } } void GameMessages::SendNotifyMission(Entity* entity, const SystemAddress& sysAddr, int missionID, int missionState, bool sendingRewards) { - CBITSTREAM - CMSGHEADER + CBITSTREAM; + CMSGHEADER; - bitStream.Write(entity->GetObjectID()); + bitStream.Write(entity->GetObjectID()); bitStream.Write(uint16_t(GAME_MSG_NOTIFY_MISSION)); bitStream.Write(missionID); bitStream.Write(missionState); bitStream.Write(sendingRewards); - SEND_PACKET + SEND_PACKET; } void GameMessages::SendNotifyMissionTask(Entity* entity, const SystemAddress& sysAddr, int missionID, int taskMask, std::vector updates) { - CBITSTREAM - CMSGHEADER + CBITSTREAM; + CMSGHEADER; - bitStream.Write(entity->GetObjectID()); + bitStream.Write(entity->GetObjectID()); bitStream.Write((uint16_t)GAME_MSG_NOTIFY_MISSION_TASK); bitStream.Write(missionID); @@ -552,28 +552,28 @@ void GameMessages::SendNotifyMissionTask(Entity* entity, const SystemAddress& sy bitStream.Write(updates[i]); } - SEND_PACKET + SEND_PACKET; } void GameMessages::SendModifyLEGOScore(Entity* entity, const SystemAddress& sysAddr, int64_t score, eLootSourceType sourceType) { - CBITSTREAM - CMSGHEADER + CBITSTREAM; + CMSGHEADER; - bitStream.Write(entity->GetObjectID()); + bitStream.Write(entity->GetObjectID()); bitStream.Write((uint16_t)GAME_MSG_MODIFY_LEGO_SCORE); bitStream.Write(score); bitStream.Write(sourceType != eLootSourceType::LOOT_SOURCE_NONE); if (sourceType != eLootSourceType::LOOT_SOURCE_NONE) bitStream.Write(sourceType); - SEND_PACKET + SEND_PACKET; } void GameMessages::SendUIMessageServerToSingleClient(Entity* entity, const SystemAddress& sysAddr, const std::string& message, NDGFxValue args) { - CBITSTREAM - CMSGHEADER + CBITSTREAM; + CMSGHEADER; - bitStream.Write(entity->GetObjectID()); + bitStream.Write(entity->GetObjectID()); bitStream.Write((uint16_t)GAME_MSG_UI_MESSAGE_SERVER_TO_SINGLE_CLIENT); bitStream.Write(args); @@ -584,7 +584,7 @@ void GameMessages::SendUIMessageServerToSingleClient(Entity* entity, const Syste bitStream.Write(static_cast(message[k])); } - SEND_PACKET + SEND_PACKET; } void GameMessages::SendUIMessageServerToAllClients(const std::string& message, NDGFxValue args) { @@ -607,10 +607,10 @@ void GameMessages::SendUIMessageServerToAllClients(const std::string& message, N } void GameMessages::SendPlayEmbeddedEffectOnAllClientsNearObject(Entity* entity, std::u16string effectName, const LWOOBJID& fromObjectID, float radius) { - CBITSTREAM - CMSGHEADER + CBITSTREAM; + CMSGHEADER; - bitStream.Write(entity->GetObjectID()); + bitStream.Write(entity->GetObjectID()); bitStream.Write((uint16_t)GAME_MSG_PLAY_EMBEDDED_EFFECT_ON_ALL_CLIENTS_NEAR_OBJECT); bitStream.Write(static_cast(effectName.length())); @@ -620,7 +620,7 @@ void GameMessages::SendPlayEmbeddedEffectOnAllClientsNearObject(Entity* entity, bitStream.Write(fromObjectID); bitStream.Write(radius); - SEND_PACKET_BROADCAST + SEND_PACKET_BROADCAST; } void GameMessages::SendPlayFXEffect(Entity* entity, int32_t effectID, const std::u16string& effectType, const std::string& name, LWOOBJID secondary, float priority, float scale, bool serialize) { @@ -658,28 +658,28 @@ void GameMessages::SendPlayFXEffect(const LWOOBJID& entity, int32_t effectID, co bitStream.Write(serialize); - SEND_PACKET_BROADCAST + SEND_PACKET_BROADCAST; } void GameMessages::SendStopFXEffect(Entity* entity, bool killImmediate, std::string name) { - CBITSTREAM - CMSGHEADER + CBITSTREAM; + CMSGHEADER; - bitStream.Write(entity->GetObjectID()); + bitStream.Write(entity->GetObjectID()); bitStream.Write(GAME_MSG::GAME_MSG_STOP_FX_EFFECT); bitStream.Write(killImmediate); bitStream.Write(name.size()); bitStream.Write(name.c_str(), name.size()); - SEND_PACKET_BROADCAST + SEND_PACKET_BROADCAST; } void GameMessages::SendBroadcastTextToChatbox(Entity* entity, const SystemAddress& sysAddr, const std::u16string& attrs, const std::u16string& wsText) { - CBITSTREAM - CMSGHEADER + CBITSTREAM; + CMSGHEADER; - bitStream.Write(entity->GetObjectID()); + bitStream.Write(entity->GetObjectID()); bitStream.Write((uint16_t)GAME_MSG::GAME_MSG_BROADCAST_TEXT_TO_CHATBOX); LWONameValue attribs; @@ -698,14 +698,14 @@ void GameMessages::SendBroadcastTextToChatbox(Entity* entity, const SystemAddres bitStream.Write(static_cast(wsText[k])); } - SEND_PACKET_BROADCAST + SEND_PACKET_BROADCAST; } void GameMessages::SendSetCurrency(Entity* entity, int64_t currency, int lootType, const LWOOBJID& sourceID, const LOT& sourceLOT, int sourceTradeID, bool overrideCurrent, eLootSourceType sourceType) { - CBITSTREAM - CMSGHEADER + CBITSTREAM; + CMSGHEADER; - bitStream.Write(entity->GetObjectID()); + bitStream.Write(entity->GetObjectID()); bitStream.Write(uint16_t(GAME_MSG_SET_CURRENCY)); bitStream.Write(currency); @@ -728,28 +728,28 @@ void GameMessages::SendSetCurrency(Entity* entity, int64_t currency, int lootTyp if (sourceType != LOOTTYPE_NONE) bitStream.Write(sourceType); SystemAddress sysAddr = entity->GetSystemAddress(); - SEND_PACKET + SEND_PACKET; } void GameMessages::SendRebuildNotifyState(Entity* entity, int prevState, int state, const LWOOBJID& playerID) { - CBITSTREAM - CMSGHEADER + CBITSTREAM; + CMSGHEADER; - bitStream.Write(entity->GetObjectID()); + bitStream.Write(entity->GetObjectID()); bitStream.Write((uint16_t)GAME_MSG_REBUILD_NOTIFY_STATE); bitStream.Write(prevState); bitStream.Write(state); bitStream.Write(playerID); - SEND_PACKET_BROADCAST + SEND_PACKET_BROADCAST; } void GameMessages::SendEnableRebuild(Entity* entity, bool enable, bool fail, bool success, int failReason, float duration, const LWOOBJID& playerID) { - CBITSTREAM - CMSGHEADER + CBITSTREAM; + CMSGHEADER; - bitStream.Write(entity->GetObjectID()); + bitStream.Write(entity->GetObjectID()); bitStream.Write((uint16_t)GAME_MSG_ENABLE_REBUILD); bitStream.Write(enable); @@ -762,27 +762,27 @@ void GameMessages::SendEnableRebuild(Entity* entity, bool enable, bool fail, boo bitStream.Write(duration); bitStream.Write(playerID); - SEND_PACKET_BROADCAST + SEND_PACKET_BROADCAST; } void GameMessages::SendTerminateInteraction(const LWOOBJID& objectID, eTerminateType type, const LWOOBJID& terminator) { - CBITSTREAM - CMSGHEADER + CBITSTREAM; + CMSGHEADER; - bitStream.Write(objectID); + bitStream.Write(objectID); bitStream.Write((uint16_t)GAME_MSG_TERMINATE_INTERACTION); bitStream.Write(terminator); bitStream.Write(type); - SEND_PACKET_BROADCAST + SEND_PACKET_BROADCAST; } void GameMessages::SendDieNoImplCode(Entity* entity, const LWOOBJID& killerID, const LWOOBJID& lootOwnerID, eKillType killType, std::u16string deathType, float directionRelative_AngleY, float directionRelative_AngleXZ, float directionRelative_Force, bool bClientDeath, bool bSpawnLoot) { - CBITSTREAM - CMSGHEADER + CBITSTREAM; + CMSGHEADER; - bitStream.Write(entity->GetObjectID()); + bitStream.Write(entity->GetObjectID()); bitStream.Write(uint16_t(GAME_MSG_DIE)); bitStream.Write(bClientDeath); bitStream.Write(bSpawnLoot); @@ -797,7 +797,7 @@ void GameMessages::SendDieNoImplCode(Entity* entity, const LWOOBJID& killerID, c bitStream.Write(killerID); bitStream.Write(lootOwnerID); - SEND_PACKET_BROADCAST + SEND_PACKET_BROADCAST; } void GameMessages::SendDie(Entity* entity, const LWOOBJID& killerID, const LWOOBJID& lootOwnerID, bool bDieAccepted, eKillType killType, std::u16string deathType, float directionRelative_AngleY, float directionRelative_AngleXZ, float directionRelative_Force, bool bClientDeath, bool bSpawnLoot, float coinSpawnTime) { @@ -838,29 +838,29 @@ void GameMessages::SendDie(Entity* entity, const LWOOBJID& killerID, const LWOOB } void GameMessages::SendSetInventorySize(Entity* entity, int invType, int size) { - CBITSTREAM - CMSGHEADER + CBITSTREAM; + CMSGHEADER; - bitStream.Write(entity->GetObjectID()); + bitStream.Write(entity->GetObjectID()); bitStream.Write(uint16_t(GAME_MSG_SET_INVENTORY_SIZE)); bitStream.Write(invType); bitStream.Write(size); SystemAddress sysAddr = entity->GetSystemAddress(); - SEND_PACKET + SEND_PACKET; } void GameMessages::SendSetEmoteLockState(Entity* entity, bool bLock, int emoteID) { - CBITSTREAM - CMSGHEADER + CBITSTREAM; + CMSGHEADER; - bitStream.Write(entity->GetObjectID()); + bitStream.Write(entity->GetObjectID()); bitStream.Write(uint16_t(GAME_MSG_SET_EMOTE_LOCK_STATE)); bitStream.Write(bLock); bitStream.Write(emoteID); SystemAddress sysAddr = entity->GetSystemAddress(); - SEND_PACKET + SEND_PACKET; } void GameMessages::SendSetJetPackMode(Entity* entity, bool use, bool bypassChecks, bool doHover, int effectID, float airspeed, float maxAirspeed, float verticalVelocity, int warningEffectID) { @@ -872,10 +872,10 @@ void GameMessages::SendSetJetPackMode(Entity* entity, bool use, bool bypassCheck } */ - CBITSTREAM - CMSGHEADER + CBITSTREAM; + CMSGHEADER; - bitStream.Write(entity->GetObjectID()); + bitStream.Write(entity->GetObjectID()); bitStream.Write(uint16_t(GAME_MSG_SET_JET_PACK_MODE)); bitStream.Write(bypassChecks); @@ -897,7 +897,7 @@ void GameMessages::SendSetJetPackMode(Entity* entity, bool use, bool bypassCheck bitStream.Write(warningEffectID != -1); if (warningEffectID != -1) bitStream.Write(warningEffectID); - SEND_PACKET_BROADCAST + SEND_PACKET_BROADCAST; } void GameMessages::SendResurrect(Entity* entity) { @@ -930,10 +930,10 @@ void GameMessages::SendResurrect(Entity* entity) { } void GameMessages::SendStop2DAmbientSound(Entity* entity, bool force, std::string audioGUID, bool result) { - CBITSTREAM - CMSGHEADER + CBITSTREAM; + CMSGHEADER; - bitStream.Write(entity->GetObjectID()); + bitStream.Write(entity->GetObjectID()); bitStream.Write((uint16_t)GAME_MSG_PLAY2_DAMBIENT_SOUND); uint32_t audioGUIDSize = audioGUID.size(); @@ -949,14 +949,14 @@ void GameMessages::SendStop2DAmbientSound(Entity* entity, bool force, std::strin SystemAddress sysAddr = entity->GetSystemAddress(); - SEND_PACKET + SEND_PACKET; } void GameMessages::SendPlay2DAmbientSound(Entity* entity, std::string audioGUID, bool result) { - CBITSTREAM - CMSGHEADER + CBITSTREAM; + CMSGHEADER; - bitStream.Write(entity->GetObjectID()); + bitStream.Write(entity->GetObjectID()); bitStream.Write((uint16_t)GAME_MSG_PLAY2_DAMBIENT_SOUND); uint32_t audioGUIDSize = audioGUID.size(); @@ -968,14 +968,14 @@ void GameMessages::SendPlay2DAmbientSound(Entity* entity, std::string audioGUID, bitStream.Write(result); SystemAddress sysAddr = entity->GetSystemAddress(); - SEND_PACKET + SEND_PACKET; } void GameMessages::SendSetNetworkScriptVar(Entity* entity, const SystemAddress& sysAddr, std::string data) { - CBITSTREAM - CMSGHEADER + CBITSTREAM; + CMSGHEADER; - bitStream.Write(entity->GetObjectID()); + bitStream.Write(entity->GetObjectID()); bitStream.Write((uint16_t)GAME_MSG_SET_NETWORK_SCRIPT_VAR); // FIXME: this is a bad place to need to do a conversion because we have no clue whether data is utf8 or plain ascii @@ -1177,10 +1177,10 @@ void GameMessages::SendRemoveSkill(Entity* entity, TSkillID skillID) { } void GameMessages::SendFinishArrangingWithItem(Entity* entity, const LWOOBJID& buildArea) { - CBITSTREAM - CMSGHEADER + CBITSTREAM; + CMSGHEADER; - bool bFirstTime = true; + bool bFirstTime = true; const LWOOBJID& buildAreaID = buildArea; int newSourceBAG = 0; const LWOOBJID& newSourceID = LWOOBJID_EMPTY; @@ -1215,35 +1215,35 @@ void GameMessages::SendFinishArrangingWithItem(Entity* entity, const LWOOBJID& b bitStream.Write(oldItemTYPE); SystemAddress sysAddr = entity->GetSystemAddress(); - SEND_PACKET + SEND_PACKET; } void GameMessages::SendModularBuildEnd(Entity* entity) { - CBITSTREAM - CMSGHEADER + CBITSTREAM; + CMSGHEADER; - bitStream.Write(entity->GetObjectID()); + bitStream.Write(entity->GetObjectID()); bitStream.Write(GAME_MSG::GAME_MSG_MODULAR_BUILD_END); SystemAddress sysAddr = entity->GetSystemAddress(); - SEND_PACKET + SEND_PACKET; } void GameMessages::SendVendorOpenWindow(Entity* entity, const SystemAddress& sysAddr) { - CBITSTREAM - CMSGHEADER + CBITSTREAM; + CMSGHEADER; - bitStream.Write(entity->GetObjectID()); + bitStream.Write(entity->GetObjectID()); bitStream.Write(GAME_MSG::GAME_MSG_VENDOR_OPEN_WINDOW); - SEND_PACKET + SEND_PACKET; } void GameMessages::SendVendorStatusUpdate(Entity* entity, const SystemAddress& sysAddr, bool bUpdateOnly) { - CBITSTREAM - CMSGHEADER + CBITSTREAM; + CMSGHEADER; - VendorComponent* vendor = static_cast(entity->GetComponent(COMPONENT_TYPE_VENDOR)); + VendorComponent* vendor = static_cast(entity->GetComponent(COMPONENT_TYPE_VENDOR)); if (!vendor) return; std::map vendorItems = vendor->GetInventory(); @@ -1260,27 +1260,27 @@ void GameMessages::SendVendorStatusUpdate(Entity* entity, const SystemAddress& s } if (sysAddr == UNASSIGNED_SYSTEM_ADDRESS) SEND_PACKET_BROADCAST - SEND_PACKET + SEND_PACKET; } void GameMessages::SendVendorTransactionResult(Entity* entity, const SystemAddress& sysAddr) { - CBITSTREAM - CMSGHEADER + CBITSTREAM; + CMSGHEADER; - int iResult = 0x02; // success, seems to be the only relevant one + int iResult = 0x02; // success, seems to be the only relevant one bitStream.Write(entity->GetObjectID()); bitStream.Write(GAME_MSG::GAME_MSG_VENDOR_TRANSACTION_RESULT); bitStream.Write(iResult); - SEND_PACKET + SEND_PACKET; } void GameMessages::SendRemoveItemFromInventory(Entity* entity, const SystemAddress& sysAddr, LWOOBJID objectID, LOT templateID, int inventoryType, uint32_t stackCount, uint32_t stackRemaining) { - CBITSTREAM - CMSGHEADER - // this is used for a lot more than just inventory trashing (trades, vendors, etc.) but for now since it's just used for that, that's all im going to implement - bool bConfirmed = true; + CBITSTREAM; + CMSGHEADER; + // this is used for a lot more than just inventory trashing (trades, vendors, etc.) but for now since it's just used for that, that's all im going to implement + bool bConfirmed = true; bool bDeleteItem = true; bool bOutSuccess = false; int eInvType = inventoryType; @@ -1320,52 +1320,52 @@ void GameMessages::SendRemoveItemFromInventory(Entity* entity, const SystemAddre bitStream.Write0(); bitStream.Write0(); - SEND_PACKET + SEND_PACKET; } void GameMessages::SendConsumeClientItem(Entity* entity, bool bSuccess, LWOOBJID item) { - CBITSTREAM - CMSGHEADER + CBITSTREAM; + CMSGHEADER; - bitStream.Write(entity->GetObjectID()); + bitStream.Write(entity->GetObjectID()); bitStream.Write(GAME_MSG_CONSUME_CLIENT_ITEM); bitStream.Write(bSuccess); bitStream.Write(item); SystemAddress sysAddr = entity->GetSystemAddress(); - SEND_PACKET + SEND_PACKET; } void GameMessages::SendUseItemResult(Entity* entity, LOT templateID, bool useItemResult) { - CBITSTREAM - CMSGHEADER + CBITSTREAM; + CMSGHEADER; - bitStream.Write(entity->GetObjectID()); + bitStream.Write(entity->GetObjectID()); bitStream.Write(GAME_MSG_USE_ITEM_RESULT); bitStream.Write(templateID); bitStream.Write(useItemResult); SystemAddress sysAddr = entity->GetSystemAddress(); - SEND_PACKET + SEND_PACKET; } void GameMessages::SendUseItemRequirementsResponse(LWOOBJID objectID, const SystemAddress& sysAddr, UseItemResponse itemResponse) { - CBITSTREAM - CMSGHEADER + CBITSTREAM; + CMSGHEADER; - bitStream.Write(objectID); + bitStream.Write(objectID); bitStream.Write(GAME_MSG::GAME_MSG_USE_ITEM_REQUIREMENTS_RESPONSE); bitStream.Write(itemResponse); - SEND_PACKET + SEND_PACKET; } void GameMessages::SendMoveInventoryBatch(Entity* entity, uint32_t stackCount, int srcInv, int dstInv, const LWOOBJID& iObjID) { - CBITSTREAM - CMSGHEADER + CBITSTREAM; + CMSGHEADER; - InventoryComponent* inv = static_cast(entity->GetComponent(COMPONENT_TYPE_INVENTORY)); + InventoryComponent* inv = static_cast(entity->GetComponent(COMPONENT_TYPE_INVENTORY)); if (!inv) return; Item* itemStack = inv->FindItemById(iObjID); @@ -1408,25 +1408,25 @@ void GameMessages::SendMoveInventoryBatch(Entity* entity, uint32_t stackCount, i auto sysAddr = entity->GetSystemAddress(); - SEND_PACKET + SEND_PACKET; } void GameMessages::SendMatchResponse(Entity* entity, const SystemAddress& sysAddr, int response) { - CBITSTREAM - CMSGHEADER + CBITSTREAM; + CMSGHEADER; - bitStream.Write(entity->GetObjectID()); + bitStream.Write(entity->GetObjectID()); bitStream.Write(GAME_MSG::GAME_MSG_MATCH_RESPONSE); bitStream.Write(response); - SEND_PACKET + SEND_PACKET; } void GameMessages::SendMatchUpdate(Entity* entity, const SystemAddress& sysAddr, std::string data, int type) { - CBITSTREAM - CMSGHEADER + CBITSTREAM; + CMSGHEADER; - bitStream.Write(entity->GetObjectID()); + bitStream.Write(entity->GetObjectID()); bitStream.Write(GAME_MSG::GAME_MSG_MATCH_UPDATE); bitStream.Write(uint32_t(data.size())); for (char character : data) { @@ -1435,17 +1435,17 @@ void GameMessages::SendMatchUpdate(Entity* entity, const SystemAddress& sysAddr, if (data.size() > 0) bitStream.Write(uint16_t(0)); bitStream.Write(type); - SEND_PACKET + SEND_PACKET; } void GameMessages::SendRequestActivitySummaryLeaderboardData(const LWOOBJID& objectID, const LWOOBJID& targetID, const SystemAddress& sysAddr, const int32_t& gameID, const int32_t& queryType, const int32_t& resultsEnd, const int32_t& resultsStart, bool weekly) { - CBITSTREAM - CMSGHEADER + CBITSTREAM; + CMSGHEADER; - bitStream.Write(objectID); + bitStream.Write(objectID); bitStream.Write(GAME_MSG::GAME_MSG_REQUEST_ACTIVITY_SUMMARY_LEADERBOARD_DATA); bitStream.Write(gameID != 0); @@ -1471,57 +1471,57 @@ void GameMessages::SendRequestActivitySummaryLeaderboardData(const LWOOBJID& obj bitStream.Write(targetID); bitStream.Write(weekly); - SEND_PACKET + SEND_PACKET; } void GameMessages::SendActivityPause(LWOOBJID objectId, bool pause, const SystemAddress& sysAddr) { - CBITSTREAM - CMSGHEADER + CBITSTREAM; + CMSGHEADER; - bitStream.Write(objectId); + bitStream.Write(objectId); bitStream.Write(GAME_MSG::GAME_MSG_ACTIVITY_PAUSE); bitStream.Write(pause); if (sysAddr == UNASSIGNED_SYSTEM_ADDRESS) SEND_PACKET_BROADCAST; - SEND_PACKET + SEND_PACKET; } void GameMessages::SendStartActivityTime(LWOOBJID objectId, float_t startTime, const SystemAddress& sysAddr) { - CBITSTREAM - CMSGHEADER + CBITSTREAM; + CMSGHEADER; - bitStream.Write(objectId); + bitStream.Write(objectId); bitStream.Write(GAME_MSG::GAME_MSG_START_ACTIVITY_TIME); bitStream.Write(startTime); if (sysAddr == UNASSIGNED_SYSTEM_ADDRESS) SEND_PACKET_BROADCAST; - SEND_PACKET + SEND_PACKET; } void GameMessages::SendRequestActivityEnter(LWOOBJID objectId, const SystemAddress& sysAddr, bool bStart, LWOOBJID userID) { - CBITSTREAM - CMSGHEADER + CBITSTREAM; + CMSGHEADER; - bitStream.Write(objectId); + bitStream.Write(objectId); bitStream.Write(GAME_MSG::GAME_MSG_REQUEST_ACTIVITY_ENTER); bitStream.Write(bStart); bitStream.Write(userID); if (sysAddr == UNASSIGNED_SYSTEM_ADDRESS) SEND_PACKET_BROADCAST; - SEND_PACKET + SEND_PACKET; } void GameMessages::NotifyLevelRewards(LWOOBJID objectID, const SystemAddress& sysAddr, int level, bool sending_rewards) { - CBITSTREAM - CMSGHEADER + CBITSTREAM; + CMSGHEADER; - bitStream.Write(objectID); + bitStream.Write(objectID); bitStream.Write((uint16_t)GAME_MSG::GAME_MSG_NOTIFY_LEVEL_REWARDS); bitStream.Write(level); bitStream.Write(sending_rewards); - SEND_PACKET + SEND_PACKET; } void GameMessages::SendSetShootingGalleryParams(LWOOBJID objectId, const SystemAddress& sysAddr, @@ -1533,10 +1533,10 @@ void GameMessages::SendSetShootingGalleryParams(LWOOBJID objectId, const SystemA float projectileVelocity, float timeLimit, bool bUseLeaderboards) { - CBITSTREAM - CMSGHEADER + CBITSTREAM; + CMSGHEADER; - bitStream.Write(objectId); + bitStream.Write(objectId); bitStream.Write(GAME_MSG::GAME_MSG_SET_SHOOTING_GALLERY_PARAMS); /* bitStream.Write(cameraFOV); @@ -1559,7 +1559,7 @@ void GameMessages::SendSetShootingGalleryParams(LWOOBJID objectId, const SystemA bitStream.Write(timeLimit); if (sysAddr == UNASSIGNED_SYSTEM_ADDRESS) SEND_PACKET_BROADCAST; - SEND_PACKET + SEND_PACKET; } @@ -1568,10 +1568,10 @@ void GameMessages::SendNotifyClientShootingGalleryScore(LWOOBJID objectId, const int32_t score, LWOOBJID target, NiPoint3 targetPos) { - CBITSTREAM - CMSGHEADER + CBITSTREAM; + CMSGHEADER; - bitStream.Write(objectId); + bitStream.Write(objectId); bitStream.Write(GAME_MSG::GAME_MSG_NOTIFY_CLIENT_SHOOTING_GALLERY_SCORE); bitStream.Write(addTime); bitStream.Write(score); @@ -1579,7 +1579,7 @@ void GameMessages::SendNotifyClientShootingGalleryScore(LWOOBJID objectId, const bitStream.Write(targetPos); if (sysAddr == UNASSIGNED_SYSTEM_ADDRESS) SEND_PACKET_BROADCAST; - SEND_PACKET + SEND_PACKET; } @@ -1599,10 +1599,10 @@ void GameMessages::HandleActivitySummaryLeaderboardData(RakNet::BitStream* instr } void GameMessages::SendActivitySummaryLeaderboardData(const LWOOBJID& objectID, const Leaderboard* leaderboard, const SystemAddress& sysAddr) { - CBITSTREAM - CMSGHEADER + CBITSTREAM; + CMSGHEADER; - bitStream.Write(objectID); + bitStream.Write(objectID); bitStream.Write(GAME_MSG::GAME_MSG_SEND_ACTIVITY_SUMMARY_LEADERBOARD_DATA); bitStream.Write(leaderboard->GetGameID()); @@ -1619,7 +1619,7 @@ void GameMessages::SendActivitySummaryLeaderboardData(const LWOOBJID& objectID, bitStream.Write0(); bitStream.Write0(); - SEND_PACKET + SEND_PACKET; } void GameMessages::HandleRequestActivitySummaryLeaderboardData(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr) { @@ -1942,10 +1942,10 @@ void GameMessages::SendOpenPropertyVendor(const LWOOBJID objectId, const SystemA } void GameMessages::SendOpenPropertyManagment(const LWOOBJID objectId, const SystemAddress& sysAddr) { - CBITSTREAM - CMSGHEADER + CBITSTREAM; + CMSGHEADER; - bitStream.Write(PropertyManagementComponent::Instance()->GetParent()->GetObjectID()); + bitStream.Write(PropertyManagementComponent::Instance()->GetParent()->GetObjectID()); bitStream.Write(GAME_MSG::GAME_MSG_OPEN_PROPERTY_MANAGEMENT); if (sysAddr == UNASSIGNED_SYSTEM_ADDRESS) SEND_PACKET_BROADCAST; @@ -2364,10 +2364,10 @@ void GameMessages::HandleBBBLoadItemRequest(RakNet::BitStream* inStream, Entity* } void GameMessages::SendSmash(Entity* entity, float force, float ghostOpacity, LWOOBJID killerID, bool ignoreObjectVisibility) { - CBITSTREAM - CMSGHEADER + CBITSTREAM; + CMSGHEADER; - bitStream.Write(entity->GetObjectID()); + bitStream.Write(entity->GetObjectID()); bitStream.Write(GAME_MSG::GAME_MSG_SMASH); bitStream.Write(ignoreObjectVisibility); @@ -2375,14 +2375,14 @@ void GameMessages::SendSmash(Entity* entity, float force, float ghostOpacity, LW bitStream.Write(ghostOpacity); bitStream.Write(killerID); - SEND_PACKET_BROADCAST + SEND_PACKET_BROADCAST; } void GameMessages::SendUnSmash(Entity* entity, LWOOBJID builderID, float duration) { - CBITSTREAM - CMSGHEADER + CBITSTREAM; + CMSGHEADER; - bitStream.Write(entity->GetObjectID()); + bitStream.Write(entity->GetObjectID()); bitStream.Write(GAME_MSG::GAME_MSG_UNSMASH); bitStream.Write(builderID != LWOOBJID_EMPTY); @@ -2391,7 +2391,7 @@ void GameMessages::SendUnSmash(Entity* entity, LWOOBJID builderID, float duratio bitStream.Write(duration != 3.0f); if (duration != 3.0f) bitStream.Write(duration); - SEND_PACKET_BROADCAST + SEND_PACKET_BROADCAST; } void GameMessages::HandleControlBehaviors(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr) { @@ -5723,44 +5723,44 @@ void GameMessages::HandleGetHotPropertyData(RakNet::BitStream* inStream, Entity* } void GameMessages::SendGetHotPropertyData(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr) { - CBITSTREAM - CMSGHEADER - /** - * [u32] - Number of properties - * [objid] - property id - * [objid] - property owner id - * [wstring] - property owner name - * [u64] - total reputation - * [i32] - property template id - * [wstring] - property name - * [wstring] - property description - * [float] - performance cost - * [timestamp] - time last published - * [cloneid] - clone id - * - */ - // TODO This needs to be implemented when reputation is implemented for getting hot properties. - /** - bitStream.Write(entity->GetObjectID()); - bitStream.Write(GAME_MSG::GAME_MSG_SEND_HOT_PROPERTY_DATA); - std::vector t = {25166, 25188, 25191, 25194}; - bitStream.Write(4); - for (uint8_t i = 0; i < 4; i++) { - bitStream.Write(entity->GetObjectID()); - bitStream.Write(entity->GetObjectID()); - bitStream.Write(1); - bitStream.Write('c'); - bitStream.Write(42069); - bitStream.Write(t[i]); - bitStream.Write(1); - bitStream.Write('c'); - bitStream.Write(1); - bitStream.Write('c'); - bitStream.Write(420.69f); - bitStream.Write(1658376385); - bitStream.Write(25166); - } - SEND_PACKET*/ + CBITSTREAM; + CMSGHEADER; + /** + * [u32] - Number of properties + * [objid] - property id + * [objid] - property owner id + * [wstring] - property owner name + * [u64] - total reputation + * [i32] - property template id + * [wstring] - property name + * [wstring] - property description + * [float] - performance cost + * [timestamp] - time last published + * [cloneid] - clone id + * + */ + // TODO This needs to be implemented when reputation is implemented for getting hot properties. + /** + bitStream.Write(entity->GetObjectID()); + bitStream.Write(GAME_MSG::GAME_MSG_SEND_HOT_PROPERTY_DATA); + std::vector t = {25166, 25188, 25191, 25194}; + bitStream.Write(4); + for (uint8_t i = 0; i < 4; i++) { + bitStream.Write(entity->GetObjectID()); + bitStream.Write(entity->GetObjectID()); + bitStream.Write(1); + bitStream.Write('c'); + bitStream.Write(42069); + bitStream.Write(t[i]); + bitStream.Write(1); + bitStream.Write('c'); + bitStream.Write(1); + bitStream.Write('c'); + bitStream.Write(420.69f); + bitStream.Write(1658376385); + bitStream.Write(25166); + } + SEND_PACKET*/ } void GameMessages::HandleReportBug(RakNet::BitStream* inStream, Entity* entity) { diff --git a/dNet/ChatPackets.cpp b/dNet/ChatPackets.cpp index eb3bda71..2d592c9b 100644 --- a/dNet/ChatPackets.cpp +++ b/dNet/ChatPackets.cpp @@ -12,8 +12,8 @@ #include "dServer.h" void ChatPackets::SendChatMessage(const SystemAddress& sysAddr, char chatChannel, const std::string& senderName, LWOOBJID playerObjectID, bool senderMythran, const std::u16string& message) { - CBITSTREAM - PacketUtils::WriteHeader(bitStream, CHAT, MSG_CHAT_GENERAL_CHAT_MESSAGE); + CBITSTREAM; + PacketUtils::WriteHeader(bitStream, CHAT, MSG_CHAT_GENERAL_CHAT_MESSAGE); bitStream.Write(static_cast(0)); bitStream.Write(chatChannel); @@ -30,12 +30,12 @@ void ChatPackets::SendChatMessage(const SystemAddress& sysAddr, char chatChannel } bitStream.Write(static_cast(0)); - SEND_PACKET_BROADCAST + SEND_PACKET_BROADCAST; } void ChatPackets::SendSystemMessage(const SystemAddress& sysAddr, const std::u16string& message, const bool broadcast) { - CBITSTREAM - PacketUtils::WriteHeader(bitStream, CHAT, MSG_CHAT_GENERAL_CHAT_MESSAGE); + CBITSTREAM; + PacketUtils::WriteHeader(bitStream, CHAT, MSG_CHAT_GENERAL_CHAT_MESSAGE); bitStream.Write(static_cast(0)); bitStream.Write(static_cast(4)); diff --git a/dNet/MasterPackets.cpp b/dNet/MasterPackets.cpp index 6c55b7dc..e5b80e05 100644 --- a/dNet/MasterPackets.cpp +++ b/dNet/MasterPackets.cpp @@ -8,8 +8,8 @@ #include void MasterPackets::SendPersistentIDRequest(dServer* server, uint64_t requestID) { - CBITSTREAM - PacketUtils::WriteHeader(bitStream, MASTER, MSG_MASTER_REQUEST_PERSISTENT_ID); + CBITSTREAM; + PacketUtils::WriteHeader(bitStream, MASTER, MSG_MASTER_REQUEST_PERSISTENT_ID); bitStream.Write(requestID); server->SendToMaster(&bitStream); } diff --git a/dNet/WorldPackets.cpp b/dNet/WorldPackets.cpp index 04a7940c..23d2c010 100644 --- a/dNet/WorldPackets.cpp +++ b/dNet/WorldPackets.cpp @@ -34,7 +34,7 @@ void WorldPackets::SendLoadStaticZone(const SystemAddress& sysAddr, float x, flo bitStream.Write(static_cast(0)); // Change this to eventually use 4 on activity worlds - SEND_PACKET + SEND_PACKET; } void WorldPackets::SendCharacterList(const SystemAddress& sysAddr, User* user) { @@ -85,28 +85,28 @@ void WorldPackets::SendCharacterList(const SystemAddress& sysAddr, User* user) { } } - SEND_PACKET + SEND_PACKET; } void WorldPackets::SendCharacterCreationResponse(const SystemAddress& sysAddr, eCreationResponse response) { RakNet::BitStream bitStream; PacketUtils::WriteHeader(bitStream, CLIENT, MSG_CLIENT_CHARACTER_CREATE_RESPONSE); bitStream.Write(response); - SEND_PACKET + SEND_PACKET; } void WorldPackets::SendCharacterRenameResponse(const SystemAddress& sysAddr, eRenameResponse response) { RakNet::BitStream bitStream; PacketUtils::WriteHeader(bitStream, CLIENT, MSG_CLIENT_CHARACTER_RENAME_RESPONSE); bitStream.Write(response); - SEND_PACKET + SEND_PACKET; } void WorldPackets::SendCharacterDeleteResponse(const SystemAddress& sysAddr, bool response) { RakNet::BitStream bitStream; PacketUtils::WriteHeader(bitStream, CLIENT, MSG_CLIENT_DELETE_CHARACTER_RESPONSE); bitStream.Write(static_cast(response)); - SEND_PACKET + SEND_PACKET; } void WorldPackets::SendTransferToWorld(const SystemAddress& sysAddr, const std::string& serverIP, uint32_t serverPort, bool mythranShift) { @@ -117,14 +117,14 @@ void WorldPackets::SendTransferToWorld(const SystemAddress& sysAddr, const std:: bitStream.Write(static_cast(serverPort)); bitStream.Write(static_cast(mythranShift)); - SEND_PACKET + SEND_PACKET; } void WorldPackets::SendServerState(const SystemAddress& sysAddr) { RakNet::BitStream bitStream; PacketUtils::WriteHeader(bitStream, CLIENT, MSG_CLIENT_SERVER_STATES); bitStream.Write(static_cast(1)); //If the server is receiving this request, it probably is ready anyway. - SEND_PACKET + SEND_PACKET; } void WorldPackets::SendCreateCharacter(const SystemAddress& sysAddr, Entity* entity, const std::string& xmlData, const std::u16string& username, int32_t gm) { @@ -184,13 +184,13 @@ void WorldPackets::SendCreateCharacter(const SystemAddress& sysAddr, Entity* ent #endif PacketUtils::SavePacket("chardata.bin", (const char*)bitStream.GetData(), static_cast(bitStream.GetNumberOfBytesUsed())); - SEND_PACKET - Game::logger->Log("WorldPackets", "Sent CreateCharacter for ID: %llu", entity->GetObjectID()); + SEND_PACKET; + Game::logger->Log("WorldPackets", "Sent CreateCharacter for ID: %llu", entity->GetObjectID()); } void WorldPackets::SendChatModerationResponse(const SystemAddress& sysAddr, bool requestAccepted, uint32_t requestID, const std::string& receiver, std::vector> unacceptedItems) { - CBITSTREAM - PacketUtils::WriteHeader(bitStream, CLIENT, MSG_CLIENT_CHAT_MODERATION_STRING); + CBITSTREAM; + PacketUtils::WriteHeader(bitStream, CLIENT, MSG_CLIENT_CHAT_MODERATION_STRING); bitStream.Write(unacceptedItems.empty()); // Is sentence ok? bitStream.Write(0x16); // Source ID, unknown @@ -209,17 +209,17 @@ void WorldPackets::SendChatModerationResponse(const SystemAddress& sysAddr, bool bitStream.Write(0); } - SEND_PACKET + SEND_PACKET; } void WorldPackets::SendGMLevelChange(const SystemAddress& sysAddr, bool success, uint8_t highestLevel, uint8_t prevLevel, uint8_t newLevel) { - CBITSTREAM - PacketUtils::WriteHeader(bitStream, CLIENT, MSG_CLIENT_MAKE_GM_RESPONSE); + CBITSTREAM; + PacketUtils::WriteHeader(bitStream, CLIENT, MSG_CLIENT_MAKE_GM_RESPONSE); bitStream.Write(success); bitStream.Write(highestLevel); bitStream.Write(prevLevel); bitStream.Write(newLevel); - SEND_PACKET + SEND_PACKET; } diff --git a/dWorldServer/WorldServer.cpp b/dWorldServer/WorldServer.cpp index 74c730f6..b4b6c966 100644 --- a/dWorldServer/WorldServer.cpp +++ b/dWorldServer/WorldServer.cpp @@ -772,9 +772,9 @@ void HandlePacket(Packet* packet) { Game::logger->Log("MasterServer", "Got affirmation request of transfer %llu", requestID); - CBITSTREAM + CBITSTREAM; - PacketUtils::WriteHeader(bitStream, MASTER, MSG_MASTER_AFFIRM_TRANSFER_RESPONSE); + PacketUtils::WriteHeader(bitStream, MASTER, MSG_MASTER_AFFIRM_TRANSFER_RESPONSE); bitStream.Write(requestID); Game::server->SendToMaster(&bitStream); diff --git a/tests/AMFDeserializeTests.cpp b/tests/AMFDeserializeTests.cpp index 71a0b265..03941a85 100644 --- a/tests/AMFDeserializeTests.cpp +++ b/tests/AMFDeserializeTests.cpp @@ -14,47 +14,47 @@ std::unique_ptr ReadFromBitStream(RakNet::BitStream* bitStream) { } int ReadAMFUndefinedFromBitStream() { - CBITSTREAM - bitStream.Write(0x00); + CBITSTREAM; + bitStream.Write(0x00); std::unique_ptr res(ReadFromBitStream(&bitStream)); ASSERT_EQ(res->GetValueType(), AMFValueType::AMFUndefined); return 0; } int ReadAMFNullFromBitStream() { - CBITSTREAM - bitStream.Write(0x01); + CBITSTREAM; + bitStream.Write(0x01); std::unique_ptr res(ReadFromBitStream(&bitStream)); ASSERT_EQ(res->GetValueType(), AMFValueType::AMFNull); return 0; } int ReadAMFFalseFromBitStream() { - CBITSTREAM - bitStream.Write(0x02); + CBITSTREAM; + bitStream.Write(0x02); std::unique_ptr res(ReadFromBitStream(&bitStream)); ASSERT_EQ(res->GetValueType(), AMFValueType::AMFFalse); return 0; } int ReadAMFTrueFromBitStream() { - CBITSTREAM - bitStream.Write(0x03); + CBITSTREAM; + bitStream.Write(0x03); std::unique_ptr res(ReadFromBitStream(&bitStream)); ASSERT_EQ(res->GetValueType(), AMFValueType::AMFTrue); return 0; } int ReadAMFIntegerFromBitStream() { - CBITSTREAM + CBITSTREAM; { bitStream.Write(0x04); - // 127 == 01111111 - bitStream.Write(127); - std::unique_ptr res(ReadFromBitStream(&bitStream)); - ASSERT_EQ(res->GetValueType(), AMFValueType::AMFInteger); - // Check that the max value of a byte can be read correctly - ASSERT_EQ(static_cast(res.get())->GetIntegerValue(), 127); + // 127 == 01111111 + bitStream.Write(127); + std::unique_ptr res(ReadFromBitStream(&bitStream)); + ASSERT_EQ(res->GetValueType(), AMFValueType::AMFInteger); + // Check that the max value of a byte can be read correctly + ASSERT_EQ(static_cast(res.get())->GetIntegerValue(), 127); } bitStream.Reset(); { @@ -95,8 +95,8 @@ int ReadAMFIntegerFromBitStream() { } int ReadAMFDoubleFromBitStream() { - CBITSTREAM - bitStream.Write(0x05); + CBITSTREAM; + bitStream.Write(0x05); bitStream.Write(25346.4f); std::unique_ptr res(ReadFromBitStream(&bitStream)); ASSERT_EQ(res->GetValueType(), AMFValueType::AMFDouble); @@ -105,8 +105,8 @@ int ReadAMFDoubleFromBitStream() { } int ReadAMFStringFromBitStream() { - CBITSTREAM - bitStream.Write(0x06); + CBITSTREAM; + bitStream.Write(0x06); bitStream.Write(0x0F); std::string toWrite = "stateID"; for (auto e : toWrite) bitStream.Write(e); @@ -117,9 +117,9 @@ int ReadAMFStringFromBitStream() { } int ReadAMFArrayFromBitStream() { - CBITSTREAM - // Test empty AMFArray - bitStream.Write(0x09); + CBITSTREAM; + // Test empty AMFArray + bitStream.Write(0x09); bitStream.Write(0x01); bitStream.Write(0x01); { From 168f837b94a76ef45b849692131a2b31cc64e639 Mon Sep 17 00:00:00 2001 From: Aaron Kimbre Date: Fri, 5 Aug 2022 08:40:59 -0500 Subject: [PATCH 49/86] add blame ignore --- .git-blame-ignore-revs | 3 +++ 1 file changed, 3 insertions(+) diff --git a/.git-blame-ignore-revs b/.git-blame-ignore-revs index 2fa44c8c..78e9475c 100644 --- a/.git-blame-ignore-revs +++ b/.git-blame-ignore-revs @@ -1,2 +1,5 @@ # format codebase 19e77a38d837ce781ba0ca6ea8e78b67a6e3b5a5 + +# add semi-colons to macros consistently +9e4ce24fd2851e65df776dd9c57bcb0d45f4453a From ea869885214cf621077f3fafe76539f4c705e7be Mon Sep 17 00:00:00 2001 From: David Markowitz <39972741+EmosewaMC@users.noreply.github.com> Date: Fri, 5 Aug 2022 19:20:11 -0700 Subject: [PATCH 50/86] Revert dZoneManager Initialization order (#717) --- dWorldServer/WorldServer.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/dWorldServer/WorldServer.cpp b/dWorldServer/WorldServer.cpp index b4b6c966..495053fa 100644 --- a/dWorldServer/WorldServer.cpp +++ b/dWorldServer/WorldServer.cpp @@ -233,9 +233,9 @@ int main(int argc, char** argv) { //Load our level: if (zoneID != 0) { - dZoneManager::Instance()->Initialize(LWOZONEID(zoneID, instanceID, cloneID)); dpWorld::Instance().Initialize(zoneID); Game::physicsWorld = &dpWorld::Instance(); //just in case some old code references it + dZoneManager::Instance()->Initialize(LWOZONEID(zoneID, instanceID, cloneID)); g_CloneID = cloneID; // pre calculate the FDB checksum From 72477e01e2711e0f61cdb192ee266e5e21b8846f Mon Sep 17 00:00:00 2001 From: Aaron Kimbre Date: Fri, 5 Aug 2022 22:01:59 -0500 Subject: [PATCH 51/86] convert to unix line endings --- dCommon/ZCompression.cpp | 2 +- dCommon/ZCompression.h | 2 +- dGame/Player.cpp | 2 +- dGame/Player.h | 2 +- dGame/dBehaviors/AirMovementBehavior.cpp | 2 +- dGame/dBehaviors/AirMovementBehavior.h | 2 +- dGame/dBehaviors/AndBehavior.cpp | 2 +- dGame/dBehaviors/AndBehavior.h | 2 +- dGame/dBehaviors/AreaOfEffectBehavior.cpp | 2 +- dGame/dBehaviors/AreaOfEffectBehavior.h | 2 +- dGame/dBehaviors/AttackDelayBehavior.cpp | 2 +- dGame/dBehaviors/AttackDelayBehavior.h | 2 +- dGame/dBehaviors/BasicAttackBehavior.cpp | 2 +- dGame/dBehaviors/BasicAttackBehavior.h | 2 +- dGame/dBehaviors/Behavior.cpp | 2 +- dGame/dBehaviors/Behavior.h | 2 +- dGame/dBehaviors/BehaviorBranchContext.cpp | 2 +- dGame/dBehaviors/BehaviorBranchContext.h | 2 +- dGame/dBehaviors/BehaviorContext.cpp | 2 +- dGame/dBehaviors/BehaviorContext.h | 2 +- dGame/dBehaviors/BehaviorSlot.h | 2 +- dGame/dBehaviors/BehaviorTemplates.cpp | 2 +- dGame/dBehaviors/BehaviorTemplates.h | 2 +- dGame/dBehaviors/BlockBehavior.cpp | 2 +- dGame/dBehaviors/BlockBehavior.h | 2 +- dGame/dBehaviors/BuffBehavior.cpp | 2 +- dGame/dBehaviors/BuffBehavior.h | 2 +- dGame/dBehaviors/ChainBehavior.cpp | 2 +- dGame/dBehaviors/ChainBehavior.h | 2 +- dGame/dBehaviors/ChargeUpBehavior.cpp | 2 +- dGame/dBehaviors/ChargeUpBehavior.h | 2 +- dGame/dBehaviors/ClearTargetBehavior.cpp | 2 +- dGame/dBehaviors/ClearTargetBehavior.h | 2 +- dGame/dBehaviors/DamageAbsorptionBehavior.cpp | 2 +- dGame/dBehaviors/DamageAbsorptionBehavior.h | 2 +- dGame/dBehaviors/DurationBehavior.cpp | 2 +- dGame/dBehaviors/DurationBehavior.h | 2 +- dGame/dBehaviors/EmptyBehavior.cpp | 2 +- dGame/dBehaviors/EmptyBehavior.h | 2 +- dGame/dBehaviors/EndBehavior.cpp | 2 +- dGame/dBehaviors/EndBehavior.h | 2 +- dGame/dBehaviors/ForceMovementBehavior.cpp | 2 +- dGame/dBehaviors/ForceMovementBehavior.h | 2 +- dGame/dBehaviors/HealBehavior.cpp | 2 +- dGame/dBehaviors/HealBehavior.h | 2 +- dGame/dBehaviors/ImaginationBehavior.cpp | 2 +- dGame/dBehaviors/ImaginationBehavior.h | 2 +- dGame/dBehaviors/ImmunityBehavior.cpp | 2 +- dGame/dBehaviors/ImmunityBehavior.h | 2 +- dGame/dBehaviors/InterruptBehavior.cpp | 2 +- dGame/dBehaviors/InterruptBehavior.h | 2 +- dGame/dBehaviors/KnockbackBehavior.cpp | 2 +- dGame/dBehaviors/KnockbackBehavior.h | 2 +- dGame/dBehaviors/MovementSwitchBehavior.cpp | 2 +- dGame/dBehaviors/MovementSwitchBehavior.h | 2 +- dGame/dBehaviors/NpcCombatSkillBehavior.cpp | 2 +- dGame/dBehaviors/NpcCombatSkillBehavior.h | 2 +- dGame/dBehaviors/PlayEffectBehavior.cpp | 2 +- dGame/dBehaviors/PlayEffectBehavior.h | 2 +- dGame/dBehaviors/ProjectileAttackBehavior.cpp | 2 +- dGame/dBehaviors/ProjectileAttackBehavior.h | 2 +- dGame/dBehaviors/PullToPointBehavior.cpp | 2 +- dGame/dBehaviors/PullToPointBehavior.h | 2 +- dGame/dBehaviors/RepairBehavior.cpp | 2 +- dGame/dBehaviors/RepairBehavior.h | 2 +- dGame/dBehaviors/SkillCastFailedBehavior.cpp | 2 +- dGame/dBehaviors/SkillCastFailedBehavior.h | 2 +- dGame/dBehaviors/SpawnBehavior.cpp | 2 +- dGame/dBehaviors/SpawnBehavior.h | 2 +- dGame/dBehaviors/SpawnQuickbuildBehavior.cpp | 2 +- dGame/dBehaviors/SpawnQuickbuildBehavior.h | 2 +- dGame/dBehaviors/StartBehavior.cpp | 2 +- dGame/dBehaviors/StartBehavior.h | 2 +- dGame/dBehaviors/StunBehavior.cpp | 2 +- dGame/dBehaviors/StunBehavior.h | 2 +- dGame/dBehaviors/SwitchBehavior.cpp | 2 +- dGame/dBehaviors/SwitchBehavior.h | 2 +- dGame/dBehaviors/SwitchMultipleBehavior.cpp | 2 +- dGame/dBehaviors/SwitchMultipleBehavior.h | 2 +- dGame/dBehaviors/TacArcBehavior.cpp | 2 +- dGame/dBehaviors/TacArcBehavior.h | 2 +- dGame/dBehaviors/TargetCasterBehavior.cpp | 2 +- dGame/dBehaviors/TargetCasterBehavior.h | 2 +- dGame/dBehaviors/VerifyBehavior.cpp | 2 +- dGame/dBehaviors/VerifyBehavior.h | 2 +- dGame/dComponents/MovementAIComponent.cpp | 2 +- dGame/dComponents/PropertyEntranceComponent.h | 2 +- dGame/dComponents/PropertyManagementComponent.cpp | 2 +- dGame/dComponents/PropertyManagementComponent.h | 2 +- dGame/dComponents/PropertyVendorComponent.cpp | 2 +- dGame/dComponents/PropertyVendorComponent.h | 2 +- dGame/dGameMessages/PropertyDataMessage.cpp | 2 +- dGame/dGameMessages/PropertyDataMessage.h | 2 +- dGame/dGameMessages/PropertySelectQueryProperty.cpp | 2 +- dGame/dGameMessages/PropertySelectQueryProperty.h | 2 +- dGame/dInventory/EquippedItem.cpp | 2 +- dGame/dInventory/Inventory.h | 2 +- dGame/dInventory/Item.cpp | 2 +- dGame/dInventory/Item.h | 2 +- dGame/dInventory/ItemSet.cpp | 2 +- dGame/dInventory/ItemSet.h | 2 +- dGame/dMission/Mission.h | 2 +- dGame/dMission/MissionLockState.h | 2 +- dGame/dMission/MissionPrerequisites.cpp | 2 +- dGame/dMission/MissionPrerequisites.h | 2 +- dGame/dMission/MissionState.h | 2 +- dGame/dMission/MissionTask.cpp | 2 +- dGame/dMission/MissionTask.h | 2 +- dGame/dMission/MissionTaskType.h | 2 +- dGame/dUtilities/Preconditions.h | 2 +- dScripts/AgJetEffectServer.cpp | 2 +- dScripts/AgJetEffectServer.h | 2 +- dScripts/AgPropGuard.cpp | 2 +- dScripts/AgPropGuard.h | 2 +- dScripts/AgSalutingNpcs.cpp | 2 +- dScripts/AgSalutingNpcs.h | 2 +- dScripts/BossSpiderQueenEnemyServer.cpp | 2 +- dScripts/BossSpiderQueenEnemyServer.h | 2 +- dScripts/FvNinjaGuard.cpp | 2 +- dScripts/FvNinjaGuard.h | 2 +- dScripts/GfBanana.cpp | 2 +- dScripts/GfBanana.h | 2 +- dScripts/GfBananaCluster.cpp | 2 +- dScripts/GfBananaCluster.h | 2 +- dScripts/GfJailkeepMission.cpp | 2 +- dScripts/GfJailkeepMission.h | 2 +- dScripts/NtSleepingGuard.cpp | 2 +- dScripts/NtSleepingGuard.h | 2 +- dScripts/SpecialImaginePowerupSpawner.cpp | 2 +- dScripts/SpecialImaginePowerupSpawner.h | 2 +- dScripts/TriggerAmbush.cpp | 2 +- dScripts/TriggerAmbush.h | 2 +- 132 files changed, 132 insertions(+), 132 deletions(-) diff --git a/dCommon/ZCompression.cpp b/dCommon/ZCompression.cpp index a82dc3c9..70f23500 100644 --- a/dCommon/ZCompression.cpp +++ b/dCommon/ZCompression.cpp @@ -1,4 +1,4 @@ -#include "ZCompression.h" +#include "ZCompression.h" #ifndef _WIN32 diff --git a/dCommon/ZCompression.h b/dCommon/ZCompression.h index a4ac9193..7b987cfa 100644 --- a/dCommon/ZCompression.h +++ b/dCommon/ZCompression.h @@ -1,4 +1,4 @@ -#pragma once +#pragma once #include diff --git a/dGame/Player.cpp b/dGame/Player.cpp index dd269f95..5306584e 100644 --- a/dGame/Player.cpp +++ b/dGame/Player.cpp @@ -1,4 +1,4 @@ -#include "Player.h" +#include "Player.h" #include diff --git a/dGame/Player.h b/dGame/Player.h index caad5361..287ee613 100644 --- a/dGame/Player.h +++ b/dGame/Player.h @@ -1,4 +1,4 @@ -#pragma once +#pragma once #include "Entity.h" diff --git a/dGame/dBehaviors/AirMovementBehavior.cpp b/dGame/dBehaviors/AirMovementBehavior.cpp index 188d743d..469ac6e4 100644 --- a/dGame/dBehaviors/AirMovementBehavior.cpp +++ b/dGame/dBehaviors/AirMovementBehavior.cpp @@ -1,4 +1,4 @@ -#include "AirMovementBehavior.h" +#include "AirMovementBehavior.h" #include "BehaviorBranchContext.h" #include "BehaviorContext.h" #include "EntityManager.h" diff --git a/dGame/dBehaviors/AirMovementBehavior.h b/dGame/dBehaviors/AirMovementBehavior.h index 6c3a2abf..323edf37 100644 --- a/dGame/dBehaviors/AirMovementBehavior.h +++ b/dGame/dBehaviors/AirMovementBehavior.h @@ -1,4 +1,4 @@ -#pragma once +#pragma once #include "Behavior.h" class AirMovementBehavior final : public Behavior diff --git a/dGame/dBehaviors/AndBehavior.cpp b/dGame/dBehaviors/AndBehavior.cpp index d54d9ec5..67c88679 100644 --- a/dGame/dBehaviors/AndBehavior.cpp +++ b/dGame/dBehaviors/AndBehavior.cpp @@ -1,4 +1,4 @@ -#include "AndBehavior.h" +#include "AndBehavior.h" #include "BehaviorBranchContext.h" #include "Game.h" #include "dLogger.h" diff --git a/dGame/dBehaviors/AndBehavior.h b/dGame/dBehaviors/AndBehavior.h index 17d1e51e..0ef7c0fd 100644 --- a/dGame/dBehaviors/AndBehavior.h +++ b/dGame/dBehaviors/AndBehavior.h @@ -1,4 +1,4 @@ -#pragma once +#pragma once #include diff --git a/dGame/dBehaviors/AreaOfEffectBehavior.cpp b/dGame/dBehaviors/AreaOfEffectBehavior.cpp index ba0f69a5..898d1f99 100644 --- a/dGame/dBehaviors/AreaOfEffectBehavior.cpp +++ b/dGame/dBehaviors/AreaOfEffectBehavior.cpp @@ -1,4 +1,4 @@ -#include "AreaOfEffectBehavior.h" +#include "AreaOfEffectBehavior.h" #include diff --git a/dGame/dBehaviors/AreaOfEffectBehavior.h b/dGame/dBehaviors/AreaOfEffectBehavior.h index 863ce8f7..b5a48ddf 100644 --- a/dGame/dBehaviors/AreaOfEffectBehavior.h +++ b/dGame/dBehaviors/AreaOfEffectBehavior.h @@ -1,4 +1,4 @@ -#pragma once +#pragma once #include "Behavior.h" class AreaOfEffectBehavior final : public Behavior diff --git a/dGame/dBehaviors/AttackDelayBehavior.cpp b/dGame/dBehaviors/AttackDelayBehavior.cpp index 9d1eb872..450741ec 100644 --- a/dGame/dBehaviors/AttackDelayBehavior.cpp +++ b/dGame/dBehaviors/AttackDelayBehavior.cpp @@ -1,4 +1,4 @@ -#include "AttackDelayBehavior.h" +#include "AttackDelayBehavior.h" #include "BehaviorBranchContext.h" #include "BehaviorContext.h" #include "Game.h" diff --git a/dGame/dBehaviors/AttackDelayBehavior.h b/dGame/dBehaviors/AttackDelayBehavior.h index 4223aba4..64271ba5 100644 --- a/dGame/dBehaviors/AttackDelayBehavior.h +++ b/dGame/dBehaviors/AttackDelayBehavior.h @@ -1,4 +1,4 @@ -#pragma once +#pragma once #include "Behavior.h" class AttackDelayBehavior final : public Behavior diff --git a/dGame/dBehaviors/BasicAttackBehavior.cpp b/dGame/dBehaviors/BasicAttackBehavior.cpp index 0c0b0d56..fe773f36 100644 --- a/dGame/dBehaviors/BasicAttackBehavior.cpp +++ b/dGame/dBehaviors/BasicAttackBehavior.cpp @@ -1,4 +1,4 @@ -#include "BasicAttackBehavior.h" +#include "BasicAttackBehavior.h" #include "BehaviorBranchContext.h" #include "Game.h" #include "dLogger.h" diff --git a/dGame/dBehaviors/BasicAttackBehavior.h b/dGame/dBehaviors/BasicAttackBehavior.h index 9e6874b9..8e23d443 100644 --- a/dGame/dBehaviors/BasicAttackBehavior.h +++ b/dGame/dBehaviors/BasicAttackBehavior.h @@ -1,4 +1,4 @@ -#pragma once +#pragma once #include "Behavior.h" class BasicAttackBehavior final : public Behavior diff --git a/dGame/dBehaviors/Behavior.cpp b/dGame/dBehaviors/Behavior.cpp index ed8f2f8c..046df117 100644 --- a/dGame/dBehaviors/Behavior.cpp +++ b/dGame/dBehaviors/Behavior.cpp @@ -1,4 +1,4 @@ -#include +#include #include #include "Behavior.h" diff --git a/dGame/dBehaviors/Behavior.h b/dGame/dBehaviors/Behavior.h index bf656e1b..ca1c23e5 100644 --- a/dGame/dBehaviors/Behavior.h +++ b/dGame/dBehaviors/Behavior.h @@ -1,4 +1,4 @@ -#pragma once +#pragma once #include #include diff --git a/dGame/dBehaviors/BehaviorBranchContext.cpp b/dGame/dBehaviors/BehaviorBranchContext.cpp index 7793eb54..3237997a 100644 --- a/dGame/dBehaviors/BehaviorBranchContext.cpp +++ b/dGame/dBehaviors/BehaviorBranchContext.cpp @@ -1,4 +1,4 @@ -#include "BehaviorBranchContext.h" +#include "BehaviorBranchContext.h" BehaviorBranchContext::BehaviorBranchContext() { diff --git a/dGame/dBehaviors/BehaviorBranchContext.h b/dGame/dBehaviors/BehaviorBranchContext.h index dfd76fad..5b2ec595 100644 --- a/dGame/dBehaviors/BehaviorBranchContext.h +++ b/dGame/dBehaviors/BehaviorBranchContext.h @@ -1,4 +1,4 @@ -#pragma once +#pragma once #include "dCommonVars.h" #include "NiPoint3.h" diff --git a/dGame/dBehaviors/BehaviorContext.cpp b/dGame/dBehaviors/BehaviorContext.cpp index 54325bac..4cd9e415 100644 --- a/dGame/dBehaviors/BehaviorContext.cpp +++ b/dGame/dBehaviors/BehaviorContext.cpp @@ -1,4 +1,4 @@ -#include "BehaviorContext.h" +#include "BehaviorContext.h" #include "Behavior.h" #include "BehaviorBranchContext.h" #include "EntityManager.h" diff --git a/dGame/dBehaviors/BehaviorContext.h b/dGame/dBehaviors/BehaviorContext.h index af8e66b4..0462d97f 100644 --- a/dGame/dBehaviors/BehaviorContext.h +++ b/dGame/dBehaviors/BehaviorContext.h @@ -1,4 +1,4 @@ -#pragma once +#pragma once #include "RakPeerInterface.h" #include "dCommonVars.h" diff --git a/dGame/dBehaviors/BehaviorSlot.h b/dGame/dBehaviors/BehaviorSlot.h index af0d4e03..51219b80 100644 --- a/dGame/dBehaviors/BehaviorSlot.h +++ b/dGame/dBehaviors/BehaviorSlot.h @@ -1,4 +1,4 @@ -#pragma once +#pragma once #ifndef BEHAVIORSLOT_H #define BEHAVIORSLOT_H diff --git a/dGame/dBehaviors/BehaviorTemplates.cpp b/dGame/dBehaviors/BehaviorTemplates.cpp index 85d0074f..8719fbe7 100644 --- a/dGame/dBehaviors/BehaviorTemplates.cpp +++ b/dGame/dBehaviors/BehaviorTemplates.cpp @@ -1 +1 @@ -#include "BehaviorTemplates.h" +#include "BehaviorTemplates.h" diff --git a/dGame/dBehaviors/BehaviorTemplates.h b/dGame/dBehaviors/BehaviorTemplates.h index af7ab376..87cde694 100644 --- a/dGame/dBehaviors/BehaviorTemplates.h +++ b/dGame/dBehaviors/BehaviorTemplates.h @@ -1,4 +1,4 @@ -#pragma once +#pragma once enum class BehaviorTemplates : unsigned int { BEHAVIOR_EMPTY, // Not a real behavior, indicates invalid behaviors diff --git a/dGame/dBehaviors/BlockBehavior.cpp b/dGame/dBehaviors/BlockBehavior.cpp index 25650b2a..cdbb3d80 100644 --- a/dGame/dBehaviors/BlockBehavior.cpp +++ b/dGame/dBehaviors/BlockBehavior.cpp @@ -1,4 +1,4 @@ -#include "BlockBehavior.h" +#include "BlockBehavior.h" #include "BehaviorContext.h" #include "BehaviorBranchContext.h" diff --git a/dGame/dBehaviors/BlockBehavior.h b/dGame/dBehaviors/BlockBehavior.h index 139fa0af..e0d639ed 100644 --- a/dGame/dBehaviors/BlockBehavior.h +++ b/dGame/dBehaviors/BlockBehavior.h @@ -1,4 +1,4 @@ -#pragma once +#pragma once #include "Behavior.h" class BlockBehavior final : public Behavior diff --git a/dGame/dBehaviors/BuffBehavior.cpp b/dGame/dBehaviors/BuffBehavior.cpp index 8bd14529..a39fd165 100644 --- a/dGame/dBehaviors/BuffBehavior.cpp +++ b/dGame/dBehaviors/BuffBehavior.cpp @@ -1,4 +1,4 @@ -#include "BuffBehavior.h" +#include "BuffBehavior.h" #include "BehaviorContext.h" #include "BehaviorBranchContext.h" diff --git a/dGame/dBehaviors/BuffBehavior.h b/dGame/dBehaviors/BuffBehavior.h index ffc853fa..b7c805b3 100644 --- a/dGame/dBehaviors/BuffBehavior.h +++ b/dGame/dBehaviors/BuffBehavior.h @@ -1,4 +1,4 @@ -#pragma once +#pragma once #include "Behavior.h" class BuffBehavior final : public Behavior diff --git a/dGame/dBehaviors/ChainBehavior.cpp b/dGame/dBehaviors/ChainBehavior.cpp index df8b223f..3ef8c15b 100644 --- a/dGame/dBehaviors/ChainBehavior.cpp +++ b/dGame/dBehaviors/ChainBehavior.cpp @@ -1,4 +1,4 @@ -#include "ChainBehavior.h" +#include "ChainBehavior.h" #include "BehaviorBranchContext.h" #include "Game.h" #include "dLogger.h" diff --git a/dGame/dBehaviors/ChainBehavior.h b/dGame/dBehaviors/ChainBehavior.h index 626ecbe3..c31d5358 100644 --- a/dGame/dBehaviors/ChainBehavior.h +++ b/dGame/dBehaviors/ChainBehavior.h @@ -1,4 +1,4 @@ -#pragma once +#pragma once #include "Behavior.h" diff --git a/dGame/dBehaviors/ChargeUpBehavior.cpp b/dGame/dBehaviors/ChargeUpBehavior.cpp index 5fc9822e..fa9fa34b 100644 --- a/dGame/dBehaviors/ChargeUpBehavior.cpp +++ b/dGame/dBehaviors/ChargeUpBehavior.cpp @@ -1,4 +1,4 @@ -#include "ChargeUpBehavior.h" +#include "ChargeUpBehavior.h" #include "BehaviorBranchContext.h" #include "BehaviorContext.h" #include "dLogger.h" diff --git a/dGame/dBehaviors/ChargeUpBehavior.h b/dGame/dBehaviors/ChargeUpBehavior.h index a80026c5..d753895e 100644 --- a/dGame/dBehaviors/ChargeUpBehavior.h +++ b/dGame/dBehaviors/ChargeUpBehavior.h @@ -1,4 +1,4 @@ -#pragma once +#pragma once #include "Behavior.h" class ChargeUpBehavior final : public Behavior diff --git a/dGame/dBehaviors/ClearTargetBehavior.cpp b/dGame/dBehaviors/ClearTargetBehavior.cpp index e37161f3..ec0c0db6 100644 --- a/dGame/dBehaviors/ClearTargetBehavior.cpp +++ b/dGame/dBehaviors/ClearTargetBehavior.cpp @@ -1,4 +1,4 @@ -#include "ClearTargetBehavior.h" +#include "ClearTargetBehavior.h" #include "BehaviorBranchContext.h" #include "BehaviorContext.h" diff --git a/dGame/dBehaviors/ClearTargetBehavior.h b/dGame/dBehaviors/ClearTargetBehavior.h index e1235eea..0ed57fb4 100644 --- a/dGame/dBehaviors/ClearTargetBehavior.h +++ b/dGame/dBehaviors/ClearTargetBehavior.h @@ -1,4 +1,4 @@ -#pragma once +#pragma once #include "Behavior.h" class ClearTargetBehavior final : public Behavior diff --git a/dGame/dBehaviors/DamageAbsorptionBehavior.cpp b/dGame/dBehaviors/DamageAbsorptionBehavior.cpp index 4f4e5b81..48dbf705 100644 --- a/dGame/dBehaviors/DamageAbsorptionBehavior.cpp +++ b/dGame/dBehaviors/DamageAbsorptionBehavior.cpp @@ -1,4 +1,4 @@ -#include "DamageAbsorptionBehavior.h" +#include "DamageAbsorptionBehavior.h" #include "BehaviorBranchContext.h" #include "BehaviorContext.h" diff --git a/dGame/dBehaviors/DamageAbsorptionBehavior.h b/dGame/dBehaviors/DamageAbsorptionBehavior.h index 533fe554..1b865e87 100644 --- a/dGame/dBehaviors/DamageAbsorptionBehavior.h +++ b/dGame/dBehaviors/DamageAbsorptionBehavior.h @@ -1,4 +1,4 @@ -#pragma once +#pragma once #include "Behavior.h" class DamageAbsorptionBehavior final : public Behavior diff --git a/dGame/dBehaviors/DurationBehavior.cpp b/dGame/dBehaviors/DurationBehavior.cpp index 6fc1b4d9..c0bc5585 100644 --- a/dGame/dBehaviors/DurationBehavior.cpp +++ b/dGame/dBehaviors/DurationBehavior.cpp @@ -1,4 +1,4 @@ -#include "DurationBehavior.h" +#include "DurationBehavior.h" #include "BehaviorBranchContext.h" #include "BehaviorContext.h" diff --git a/dGame/dBehaviors/DurationBehavior.h b/dGame/dBehaviors/DurationBehavior.h index b8533700..164754b1 100644 --- a/dGame/dBehaviors/DurationBehavior.h +++ b/dGame/dBehaviors/DurationBehavior.h @@ -1,4 +1,4 @@ -#pragma once +#pragma once #include "Behavior.h" class DurationBehavior final : public Behavior diff --git a/dGame/dBehaviors/EmptyBehavior.cpp b/dGame/dBehaviors/EmptyBehavior.cpp index 4f8a5266..8828f5de 100644 --- a/dGame/dBehaviors/EmptyBehavior.cpp +++ b/dGame/dBehaviors/EmptyBehavior.cpp @@ -1,2 +1,2 @@ -#include "EmptyBehavior.h" +#include "EmptyBehavior.h" diff --git a/dGame/dBehaviors/EmptyBehavior.h b/dGame/dBehaviors/EmptyBehavior.h index 64990ec4..52121f6c 100644 --- a/dGame/dBehaviors/EmptyBehavior.h +++ b/dGame/dBehaviors/EmptyBehavior.h @@ -1,4 +1,4 @@ -#pragma once +#pragma once #include "Behavior.h" diff --git a/dGame/dBehaviors/EndBehavior.cpp b/dGame/dBehaviors/EndBehavior.cpp index bf35932f..c67f3215 100644 --- a/dGame/dBehaviors/EndBehavior.cpp +++ b/dGame/dBehaviors/EndBehavior.cpp @@ -1,4 +1,4 @@ -#include "EndBehavior.h" +#include "EndBehavior.h" #include "BehaviorContext.h" #include "BehaviorBranchContext.h" diff --git a/dGame/dBehaviors/EndBehavior.h b/dGame/dBehaviors/EndBehavior.h index 8503f7ba..e1c06068 100644 --- a/dGame/dBehaviors/EndBehavior.h +++ b/dGame/dBehaviors/EndBehavior.h @@ -1,4 +1,4 @@ -#pragma once +#pragma once #include "Behavior.h" class EndBehavior final : public Behavior diff --git a/dGame/dBehaviors/ForceMovementBehavior.cpp b/dGame/dBehaviors/ForceMovementBehavior.cpp index 8074dbcc..55cda622 100644 --- a/dGame/dBehaviors/ForceMovementBehavior.cpp +++ b/dGame/dBehaviors/ForceMovementBehavior.cpp @@ -1,4 +1,4 @@ -#include "ForceMovementBehavior.h" +#include "ForceMovementBehavior.h" #include "BehaviorBranchContext.h" #include "BehaviorContext.h" #include "ControllablePhysicsComponent.h" diff --git a/dGame/dBehaviors/ForceMovementBehavior.h b/dGame/dBehaviors/ForceMovementBehavior.h index 26b5ce89..8d5fd9f4 100644 --- a/dGame/dBehaviors/ForceMovementBehavior.h +++ b/dGame/dBehaviors/ForceMovementBehavior.h @@ -1,4 +1,4 @@ -#pragma once +#pragma once #include "Behavior.h" class ForceMovementBehavior final : public Behavior diff --git a/dGame/dBehaviors/HealBehavior.cpp b/dGame/dBehaviors/HealBehavior.cpp index da0d4a3b..2799d2e2 100644 --- a/dGame/dBehaviors/HealBehavior.cpp +++ b/dGame/dBehaviors/HealBehavior.cpp @@ -1,4 +1,4 @@ -#include "HealBehavior.h" +#include "HealBehavior.h" #include "BehaviorBranchContext.h" #include "Game.h" #include "dLogger.h" diff --git a/dGame/dBehaviors/HealBehavior.h b/dGame/dBehaviors/HealBehavior.h index 0a719b6c..e967135a 100644 --- a/dGame/dBehaviors/HealBehavior.h +++ b/dGame/dBehaviors/HealBehavior.h @@ -1,4 +1,4 @@ -#pragma once +#pragma once #include "Behavior.h" class HealBehavior final : public Behavior diff --git a/dGame/dBehaviors/ImaginationBehavior.cpp b/dGame/dBehaviors/ImaginationBehavior.cpp index cf2cd757..59b192b0 100644 --- a/dGame/dBehaviors/ImaginationBehavior.cpp +++ b/dGame/dBehaviors/ImaginationBehavior.cpp @@ -1,4 +1,4 @@ -#include "ImaginationBehavior.h" +#include "ImaginationBehavior.h" #include "BehaviorBranchContext.h" #include "DestroyableComponent.h" #include "dpWorld.h" diff --git a/dGame/dBehaviors/ImaginationBehavior.h b/dGame/dBehaviors/ImaginationBehavior.h index 59d864f9..a35c2ddd 100644 --- a/dGame/dBehaviors/ImaginationBehavior.h +++ b/dGame/dBehaviors/ImaginationBehavior.h @@ -1,4 +1,4 @@ -#pragma once +#pragma once #include "Behavior.h" class ImaginationBehavior final : public Behavior diff --git a/dGame/dBehaviors/ImmunityBehavior.cpp b/dGame/dBehaviors/ImmunityBehavior.cpp index 93110cde..69c652f9 100644 --- a/dGame/dBehaviors/ImmunityBehavior.cpp +++ b/dGame/dBehaviors/ImmunityBehavior.cpp @@ -1,4 +1,4 @@ -#include "ImmunityBehavior.h" +#include "ImmunityBehavior.h" #include "BehaviorBranchContext.h" #include "BehaviorContext.h" diff --git a/dGame/dBehaviors/ImmunityBehavior.h b/dGame/dBehaviors/ImmunityBehavior.h index 8a66b3d2..f9409e4c 100644 --- a/dGame/dBehaviors/ImmunityBehavior.h +++ b/dGame/dBehaviors/ImmunityBehavior.h @@ -1,4 +1,4 @@ -#pragma once +#pragma once #include "Behavior.h" class ImmunityBehavior final : public Behavior diff --git a/dGame/dBehaviors/InterruptBehavior.cpp b/dGame/dBehaviors/InterruptBehavior.cpp index b0695430..b42eadb0 100644 --- a/dGame/dBehaviors/InterruptBehavior.cpp +++ b/dGame/dBehaviors/InterruptBehavior.cpp @@ -1,4 +1,4 @@ -#include "InterruptBehavior.h" +#include "InterruptBehavior.h" #include "BehaviorBranchContext.h" #include "BehaviorContext.h" #include "Game.h" diff --git a/dGame/dBehaviors/InterruptBehavior.h b/dGame/dBehaviors/InterruptBehavior.h index 35a2def9..9ba272c7 100644 --- a/dGame/dBehaviors/InterruptBehavior.h +++ b/dGame/dBehaviors/InterruptBehavior.h @@ -1,4 +1,4 @@ -#pragma once +#pragma once #include "Behavior.h" class InterruptBehavior final : public Behavior diff --git a/dGame/dBehaviors/KnockbackBehavior.cpp b/dGame/dBehaviors/KnockbackBehavior.cpp index 0b1fc5d7..83c82010 100644 --- a/dGame/dBehaviors/KnockbackBehavior.cpp +++ b/dGame/dBehaviors/KnockbackBehavior.cpp @@ -1,4 +1,4 @@ -#define _USE_MATH_DEFINES +#define _USE_MATH_DEFINES #include #include "KnockbackBehavior.h" #include "BehaviorBranchContext.h" diff --git a/dGame/dBehaviors/KnockbackBehavior.h b/dGame/dBehaviors/KnockbackBehavior.h index 4feb592c..c952bb41 100644 --- a/dGame/dBehaviors/KnockbackBehavior.h +++ b/dGame/dBehaviors/KnockbackBehavior.h @@ -1,4 +1,4 @@ -#pragma once +#pragma once #include "Behavior.h" class KnockbackBehavior final : public Behavior diff --git a/dGame/dBehaviors/MovementSwitchBehavior.cpp b/dGame/dBehaviors/MovementSwitchBehavior.cpp index de1b0b50..17ed5c40 100644 --- a/dGame/dBehaviors/MovementSwitchBehavior.cpp +++ b/dGame/dBehaviors/MovementSwitchBehavior.cpp @@ -1,4 +1,4 @@ -#include "MovementSwitchBehavior.h" +#include "MovementSwitchBehavior.h" #include "BehaviorBranchContext.h" #include "Game.h" #include "dLogger.h" diff --git a/dGame/dBehaviors/MovementSwitchBehavior.h b/dGame/dBehaviors/MovementSwitchBehavior.h index 8a1e83a3..82e1a9e9 100644 --- a/dGame/dBehaviors/MovementSwitchBehavior.h +++ b/dGame/dBehaviors/MovementSwitchBehavior.h @@ -1,4 +1,4 @@ -#pragma once +#pragma once #include "Behavior.h" class MovementSwitchBehavior final : public Behavior diff --git a/dGame/dBehaviors/NpcCombatSkillBehavior.cpp b/dGame/dBehaviors/NpcCombatSkillBehavior.cpp index d541033c..5a8d03cf 100644 --- a/dGame/dBehaviors/NpcCombatSkillBehavior.cpp +++ b/dGame/dBehaviors/NpcCombatSkillBehavior.cpp @@ -1,4 +1,4 @@ -#include "NpcCombatSkillBehavior.h" +#include "NpcCombatSkillBehavior.h" #include "BehaviorBranchContext.h" #include "BehaviorContext.h" diff --git a/dGame/dBehaviors/NpcCombatSkillBehavior.h b/dGame/dBehaviors/NpcCombatSkillBehavior.h index f2ed60b9..19ff3483 100644 --- a/dGame/dBehaviors/NpcCombatSkillBehavior.h +++ b/dGame/dBehaviors/NpcCombatSkillBehavior.h @@ -1,4 +1,4 @@ -#pragma once +#pragma once #include "Behavior.h" class NpcCombatSkillBehavior final : public Behavior diff --git a/dGame/dBehaviors/PlayEffectBehavior.cpp b/dGame/dBehaviors/PlayEffectBehavior.cpp index 9793c1db..acd606a9 100644 --- a/dGame/dBehaviors/PlayEffectBehavior.cpp +++ b/dGame/dBehaviors/PlayEffectBehavior.cpp @@ -1,4 +1,4 @@ -#include "PlayEffectBehavior.h" +#include "PlayEffectBehavior.h" #include "BehaviorContext.h" #include "BehaviorBranchContext.h" diff --git a/dGame/dBehaviors/PlayEffectBehavior.h b/dGame/dBehaviors/PlayEffectBehavior.h index d6069305..5ef49161 100644 --- a/dGame/dBehaviors/PlayEffectBehavior.h +++ b/dGame/dBehaviors/PlayEffectBehavior.h @@ -1,4 +1,4 @@ -#pragma once +#pragma once #include "Behavior.h" class PlayEffectBehavior final : public Behavior diff --git a/dGame/dBehaviors/ProjectileAttackBehavior.cpp b/dGame/dBehaviors/ProjectileAttackBehavior.cpp index 861837e7..350234e2 100644 --- a/dGame/dBehaviors/ProjectileAttackBehavior.cpp +++ b/dGame/dBehaviors/ProjectileAttackBehavior.cpp @@ -1,4 +1,4 @@ -#include "ProjectileAttackBehavior.h" +#include "ProjectileAttackBehavior.h" #include "BehaviorBranchContext.h" #include "BehaviorContext.h" #include "EntityManager.h" diff --git a/dGame/dBehaviors/ProjectileAttackBehavior.h b/dGame/dBehaviors/ProjectileAttackBehavior.h index 0003c2dc..17353a2a 100644 --- a/dGame/dBehaviors/ProjectileAttackBehavior.h +++ b/dGame/dBehaviors/ProjectileAttackBehavior.h @@ -1,4 +1,4 @@ -#pragma once +#pragma once #include "Behavior.h" #include "NiPoint3.h" diff --git a/dGame/dBehaviors/PullToPointBehavior.cpp b/dGame/dBehaviors/PullToPointBehavior.cpp index 2cdbaa7e..7427ccc4 100644 --- a/dGame/dBehaviors/PullToPointBehavior.cpp +++ b/dGame/dBehaviors/PullToPointBehavior.cpp @@ -1,4 +1,4 @@ -#include "PullToPointBehavior.h" +#include "PullToPointBehavior.h" #include "BehaviorContext.h" #include "BehaviorBranchContext.h" diff --git a/dGame/dBehaviors/PullToPointBehavior.h b/dGame/dBehaviors/PullToPointBehavior.h index 09e4310c..d448ad8d 100644 --- a/dGame/dBehaviors/PullToPointBehavior.h +++ b/dGame/dBehaviors/PullToPointBehavior.h @@ -1,4 +1,4 @@ -#pragma once +#pragma once #include "Behavior.h" class PullToPointBehavior final : public Behavior diff --git a/dGame/dBehaviors/RepairBehavior.cpp b/dGame/dBehaviors/RepairBehavior.cpp index 470fb4d4..a48141d3 100644 --- a/dGame/dBehaviors/RepairBehavior.cpp +++ b/dGame/dBehaviors/RepairBehavior.cpp @@ -1,4 +1,4 @@ -#include "RepairBehavior.h" +#include "RepairBehavior.h" #include "BehaviorBranchContext.h" #include "DestroyableComponent.h" #include "dpWorld.h" diff --git a/dGame/dBehaviors/RepairBehavior.h b/dGame/dBehaviors/RepairBehavior.h index 38f97b05..8d2f14e4 100644 --- a/dGame/dBehaviors/RepairBehavior.h +++ b/dGame/dBehaviors/RepairBehavior.h @@ -1,4 +1,4 @@ -#pragma once +#pragma once #include "Behavior.h" class RepairBehavior final : public Behavior diff --git a/dGame/dBehaviors/SkillCastFailedBehavior.cpp b/dGame/dBehaviors/SkillCastFailedBehavior.cpp index 7a0166f9..a663e709 100644 --- a/dGame/dBehaviors/SkillCastFailedBehavior.cpp +++ b/dGame/dBehaviors/SkillCastFailedBehavior.cpp @@ -1,4 +1,4 @@ -#include "SkillCastFailedBehavior.h" +#include "SkillCastFailedBehavior.h" #include "BehaviorContext.h" #include "BehaviorBranchContext.h" diff --git a/dGame/dBehaviors/SkillCastFailedBehavior.h b/dGame/dBehaviors/SkillCastFailedBehavior.h index 1f414f90..5359cb42 100644 --- a/dGame/dBehaviors/SkillCastFailedBehavior.h +++ b/dGame/dBehaviors/SkillCastFailedBehavior.h @@ -1,4 +1,4 @@ -#pragma once +#pragma once #include "Behavior.h" class SkillCastFailedBehavior final : public Behavior diff --git a/dGame/dBehaviors/SpawnBehavior.cpp b/dGame/dBehaviors/SpawnBehavior.cpp index 592a8a22..ac7bb797 100644 --- a/dGame/dBehaviors/SpawnBehavior.cpp +++ b/dGame/dBehaviors/SpawnBehavior.cpp @@ -1,4 +1,4 @@ -#include "SpawnBehavior.h" +#include "SpawnBehavior.h" #include "BehaviorContext.h" #include "BehaviorBranchContext.h" diff --git a/dGame/dBehaviors/SpawnBehavior.h b/dGame/dBehaviors/SpawnBehavior.h index 0617f781..875e0a2b 100644 --- a/dGame/dBehaviors/SpawnBehavior.h +++ b/dGame/dBehaviors/SpawnBehavior.h @@ -1,4 +1,4 @@ -#pragma once +#pragma once #include "Behavior.h" class SpawnBehavior final : public Behavior diff --git a/dGame/dBehaviors/SpawnQuickbuildBehavior.cpp b/dGame/dBehaviors/SpawnQuickbuildBehavior.cpp index 2b78f12e..514ae27a 100644 --- a/dGame/dBehaviors/SpawnQuickbuildBehavior.cpp +++ b/dGame/dBehaviors/SpawnQuickbuildBehavior.cpp @@ -1,4 +1,4 @@ -#include "SpawnQuickbuildBehavior.h" +#include "SpawnQuickbuildBehavior.h" #include "BehaviorBranchContext.h" #include "BehaviorContext.h" diff --git a/dGame/dBehaviors/SpawnQuickbuildBehavior.h b/dGame/dBehaviors/SpawnQuickbuildBehavior.h index d1ed2e53..653c60e8 100644 --- a/dGame/dBehaviors/SpawnQuickbuildBehavior.h +++ b/dGame/dBehaviors/SpawnQuickbuildBehavior.h @@ -1,4 +1,4 @@ -#pragma once +#pragma once #include "Behavior.h" class SpawnQuickbuildBehavior final : public Behavior diff --git a/dGame/dBehaviors/StartBehavior.cpp b/dGame/dBehaviors/StartBehavior.cpp index 436984d1..2bcaf325 100644 --- a/dGame/dBehaviors/StartBehavior.cpp +++ b/dGame/dBehaviors/StartBehavior.cpp @@ -1,4 +1,4 @@ -#include "StartBehavior.h" +#include "StartBehavior.h" #include "BehaviorBranchContext.h" void StartBehavior::Handle(BehaviorContext* context, RakNet::BitStream* bit_stream, BehaviorBranchContext branch) { diff --git a/dGame/dBehaviors/StartBehavior.h b/dGame/dBehaviors/StartBehavior.h index 9ee461fc..384fe64a 100644 --- a/dGame/dBehaviors/StartBehavior.h +++ b/dGame/dBehaviors/StartBehavior.h @@ -1,4 +1,4 @@ -#pragma once +#pragma once #include "Behavior.h" class StartBehavior final : public Behavior diff --git a/dGame/dBehaviors/StunBehavior.cpp b/dGame/dBehaviors/StunBehavior.cpp index 3cbfe9c4..59a81440 100644 --- a/dGame/dBehaviors/StunBehavior.cpp +++ b/dGame/dBehaviors/StunBehavior.cpp @@ -1,4 +1,4 @@ -#include "StunBehavior.h" +#include "StunBehavior.h" #include "BaseCombatAIComponent.h" #include "BehaviorBranchContext.h" diff --git a/dGame/dBehaviors/StunBehavior.h b/dGame/dBehaviors/StunBehavior.h index a512528d..f4851b47 100644 --- a/dGame/dBehaviors/StunBehavior.h +++ b/dGame/dBehaviors/StunBehavior.h @@ -1,4 +1,4 @@ -#pragma once +#pragma once #include "Behavior.h" class StunBehavior final : public Behavior diff --git a/dGame/dBehaviors/SwitchBehavior.cpp b/dGame/dBehaviors/SwitchBehavior.cpp index ff3d7baf..78271b99 100644 --- a/dGame/dBehaviors/SwitchBehavior.cpp +++ b/dGame/dBehaviors/SwitchBehavior.cpp @@ -1,4 +1,4 @@ -#include "SwitchBehavior.h" +#include "SwitchBehavior.h" #include "BehaviorBranchContext.h" #include "EntityManager.h" #include "dLogger.h" diff --git a/dGame/dBehaviors/SwitchBehavior.h b/dGame/dBehaviors/SwitchBehavior.h index 675c1a35..5e40d659 100644 --- a/dGame/dBehaviors/SwitchBehavior.h +++ b/dGame/dBehaviors/SwitchBehavior.h @@ -1,4 +1,4 @@ -#pragma once +#pragma once #include "Behavior.h" class SwitchBehavior final : public Behavior diff --git a/dGame/dBehaviors/SwitchMultipleBehavior.cpp b/dGame/dBehaviors/SwitchMultipleBehavior.cpp index b34b1144..946e5e0f 100644 --- a/dGame/dBehaviors/SwitchMultipleBehavior.cpp +++ b/dGame/dBehaviors/SwitchMultipleBehavior.cpp @@ -1,4 +1,4 @@ -#include "SwitchMultipleBehavior.h" +#include "SwitchMultipleBehavior.h" #include diff --git a/dGame/dBehaviors/SwitchMultipleBehavior.h b/dGame/dBehaviors/SwitchMultipleBehavior.h index c60fcd6d..1e3dfe64 100644 --- a/dGame/dBehaviors/SwitchMultipleBehavior.h +++ b/dGame/dBehaviors/SwitchMultipleBehavior.h @@ -1,4 +1,4 @@ -#pragma once +#pragma once #include "Behavior.h" #include diff --git a/dGame/dBehaviors/TacArcBehavior.cpp b/dGame/dBehaviors/TacArcBehavior.cpp index 21885624..8789f9b6 100644 --- a/dGame/dBehaviors/TacArcBehavior.cpp +++ b/dGame/dBehaviors/TacArcBehavior.cpp @@ -1,4 +1,4 @@ -#include "TacArcBehavior.h" +#include "TacArcBehavior.h" #include "BehaviorBranchContext.h" #include "Game.h" #include "dLogger.h" diff --git a/dGame/dBehaviors/TacArcBehavior.h b/dGame/dBehaviors/TacArcBehavior.h index 211ed6b7..87a22051 100644 --- a/dGame/dBehaviors/TacArcBehavior.h +++ b/dGame/dBehaviors/TacArcBehavior.h @@ -1,4 +1,4 @@ -#pragma once +#pragma once #include "Behavior.h" #include "dCommonVars.h" #include "NiPoint3.h" diff --git a/dGame/dBehaviors/TargetCasterBehavior.cpp b/dGame/dBehaviors/TargetCasterBehavior.cpp index fb76b90d..ff9cfc03 100644 --- a/dGame/dBehaviors/TargetCasterBehavior.cpp +++ b/dGame/dBehaviors/TargetCasterBehavior.cpp @@ -1,4 +1,4 @@ -#include "TargetCasterBehavior.h" +#include "TargetCasterBehavior.h" #include "BehaviorBranchContext.h" #include "BehaviorContext.h" diff --git a/dGame/dBehaviors/TargetCasterBehavior.h b/dGame/dBehaviors/TargetCasterBehavior.h index 4f2a0f5f..387d2732 100644 --- a/dGame/dBehaviors/TargetCasterBehavior.h +++ b/dGame/dBehaviors/TargetCasterBehavior.h @@ -1,4 +1,4 @@ -#pragma once +#pragma once #include "Behavior.h" class TargetCasterBehavior final : public Behavior diff --git a/dGame/dBehaviors/VerifyBehavior.cpp b/dGame/dBehaviors/VerifyBehavior.cpp index cbc3c6df..608e965b 100644 --- a/dGame/dBehaviors/VerifyBehavior.cpp +++ b/dGame/dBehaviors/VerifyBehavior.cpp @@ -1,4 +1,4 @@ -#include "VerifyBehavior.h" +#include "VerifyBehavior.h" #include "BehaviorBranchContext.h" #include "EntityManager.h" #include "NiPoint3.h" diff --git a/dGame/dBehaviors/VerifyBehavior.h b/dGame/dBehaviors/VerifyBehavior.h index b38d1953..a91ff7cf 100644 --- a/dGame/dBehaviors/VerifyBehavior.h +++ b/dGame/dBehaviors/VerifyBehavior.h @@ -1,4 +1,4 @@ -#pragma once +#pragma once #include "Behavior.h" class VerifyBehavior final : public Behavior diff --git a/dGame/dComponents/MovementAIComponent.cpp b/dGame/dComponents/MovementAIComponent.cpp index 43231abf..ed6ed483 100644 --- a/dGame/dComponents/MovementAIComponent.cpp +++ b/dGame/dComponents/MovementAIComponent.cpp @@ -1,4 +1,4 @@ -#include "MovementAIComponent.h" +#include "MovementAIComponent.h" #include #include diff --git a/dGame/dComponents/PropertyEntranceComponent.h b/dGame/dComponents/PropertyEntranceComponent.h index 6087faf2..4110e7d9 100644 --- a/dGame/dComponents/PropertyEntranceComponent.h +++ b/dGame/dComponents/PropertyEntranceComponent.h @@ -1,4 +1,4 @@ -#pragma once +#pragma once #include diff --git a/dGame/dComponents/PropertyManagementComponent.cpp b/dGame/dComponents/PropertyManagementComponent.cpp index bc3d8395..f6954e4d 100644 --- a/dGame/dComponents/PropertyManagementComponent.cpp +++ b/dGame/dComponents/PropertyManagementComponent.cpp @@ -1,4 +1,4 @@ -#include "PropertyManagementComponent.h" +#include "PropertyManagementComponent.h" #include diff --git a/dGame/dComponents/PropertyManagementComponent.h b/dGame/dComponents/PropertyManagementComponent.h index c22adc21..d9526015 100644 --- a/dGame/dComponents/PropertyManagementComponent.h +++ b/dGame/dComponents/PropertyManagementComponent.h @@ -1,4 +1,4 @@ -#pragma once +#pragma once #include #include "Entity.h" diff --git a/dGame/dComponents/PropertyVendorComponent.cpp b/dGame/dComponents/PropertyVendorComponent.cpp index 4ad24af5..ed89bfc7 100644 --- a/dGame/dComponents/PropertyVendorComponent.cpp +++ b/dGame/dComponents/PropertyVendorComponent.cpp @@ -1,4 +1,4 @@ -#include "PropertyVendorComponent.h" +#include "PropertyVendorComponent.h" #include "PropertyDataMessage.h" #include "GameMessages.h" diff --git a/dGame/dComponents/PropertyVendorComponent.h b/dGame/dComponents/PropertyVendorComponent.h index 4641b38d..f947d745 100644 --- a/dGame/dComponents/PropertyVendorComponent.h +++ b/dGame/dComponents/PropertyVendorComponent.h @@ -1,4 +1,4 @@ -#pragma once +#pragma once #include "Entity.h" #include "Component.h" diff --git a/dGame/dGameMessages/PropertyDataMessage.cpp b/dGame/dGameMessages/PropertyDataMessage.cpp index c30285fd..e0b792ad 100644 --- a/dGame/dGameMessages/PropertyDataMessage.cpp +++ b/dGame/dGameMessages/PropertyDataMessage.cpp @@ -1,4 +1,4 @@ -#include "PropertyDataMessage.h" +#include "PropertyDataMessage.h" #include "GeneralUtils.h" diff --git a/dGame/dGameMessages/PropertyDataMessage.h b/dGame/dGameMessages/PropertyDataMessage.h index 819c5dbb..f7c9e2d5 100644 --- a/dGame/dGameMessages/PropertyDataMessage.h +++ b/dGame/dGameMessages/PropertyDataMessage.h @@ -1,4 +1,4 @@ -#pragma once +#pragma once #include #include diff --git a/dGame/dGameMessages/PropertySelectQueryProperty.cpp b/dGame/dGameMessages/PropertySelectQueryProperty.cpp index cd17a58b..6e975879 100644 --- a/dGame/dGameMessages/PropertySelectQueryProperty.cpp +++ b/dGame/dGameMessages/PropertySelectQueryProperty.cpp @@ -1,4 +1,4 @@ -#include "PropertySelectQueryProperty.h" +#include "PropertySelectQueryProperty.h" void PropertySelectQueryProperty::Serialize(RakNet::BitStream& stream) const { stream.Write(CloneId); diff --git a/dGame/dGameMessages/PropertySelectQueryProperty.h b/dGame/dGameMessages/PropertySelectQueryProperty.h index 7826900d..47d795a7 100644 --- a/dGame/dGameMessages/PropertySelectQueryProperty.h +++ b/dGame/dGameMessages/PropertySelectQueryProperty.h @@ -1,4 +1,4 @@ -#pragma once +#pragma once #ifndef PROPERTYSELECTQUERY_H #define PROPERTYSELECTQUERY_H diff --git a/dGame/dInventory/EquippedItem.cpp b/dGame/dInventory/EquippedItem.cpp index df5639de..9eaed5fc 100644 --- a/dGame/dInventory/EquippedItem.cpp +++ b/dGame/dInventory/EquippedItem.cpp @@ -1 +1 @@ -#include "EquippedItem.h" +#include "EquippedItem.h" diff --git a/dGame/dInventory/Inventory.h b/dGame/dInventory/Inventory.h index 1f7bb425..30f753da 100644 --- a/dGame/dInventory/Inventory.h +++ b/dGame/dInventory/Inventory.h @@ -1,4 +1,4 @@ -#pragma once +#pragma once #ifndef INVENTORY_H #define INVENTORY_H diff --git a/dGame/dInventory/Item.cpp b/dGame/dInventory/Item.cpp index b502d5eb..62e198a3 100644 --- a/dGame/dInventory/Item.cpp +++ b/dGame/dInventory/Item.cpp @@ -1,4 +1,4 @@ -#include "Item.h" +#include "Item.h" #include diff --git a/dGame/dInventory/Item.h b/dGame/dInventory/Item.h index 3987471c..0613ca85 100644 --- a/dGame/dInventory/Item.h +++ b/dGame/dInventory/Item.h @@ -1,4 +1,4 @@ -#pragma once +#pragma once #include "dCommonVars.h" #include "Inventory.h" diff --git a/dGame/dInventory/ItemSet.cpp b/dGame/dInventory/ItemSet.cpp index 5d8ea226..5063139e 100644 --- a/dGame/dInventory/ItemSet.cpp +++ b/dGame/dInventory/ItemSet.cpp @@ -1,4 +1,4 @@ -#include "ItemSet.h" +#include "ItemSet.h" #include "InventoryComponent.h" #include "Entity.h" diff --git a/dGame/dInventory/ItemSet.h b/dGame/dInventory/ItemSet.h index 2ed3be14..7c713f03 100644 --- a/dGame/dInventory/ItemSet.h +++ b/dGame/dInventory/ItemSet.h @@ -1,4 +1,4 @@ -#pragma once +#pragma once #include diff --git a/dGame/dMission/Mission.h b/dGame/dMission/Mission.h index 43b2a96c..b8892f3d 100644 --- a/dGame/dMission/Mission.h +++ b/dGame/dMission/Mission.h @@ -1,4 +1,4 @@ -#pragma once +#pragma once #ifndef MISSION_H #define MISSION_H diff --git a/dGame/dMission/MissionLockState.h b/dGame/dMission/MissionLockState.h index e2dcedd7..9fd2252a 100644 --- a/dGame/dMission/MissionLockState.h +++ b/dGame/dMission/MissionLockState.h @@ -1,4 +1,4 @@ -#pragma once +#pragma once #ifndef MISSIONLOCKSTATE_H #define MISSIONLOCKSTATE_H diff --git a/dGame/dMission/MissionPrerequisites.cpp b/dGame/dMission/MissionPrerequisites.cpp index 3d4e6355..46fa73a6 100644 --- a/dGame/dMission/MissionPrerequisites.cpp +++ b/dGame/dMission/MissionPrerequisites.cpp @@ -1,4 +1,4 @@ -#include "MissionPrerequisites.h" +#include "MissionPrerequisites.h" #include #include diff --git a/dGame/dMission/MissionPrerequisites.h b/dGame/dMission/MissionPrerequisites.h index dd349cb1..13b8e903 100644 --- a/dGame/dMission/MissionPrerequisites.h +++ b/dGame/dMission/MissionPrerequisites.h @@ -1,4 +1,4 @@ -#pragma once +#pragma once #include #include #include diff --git a/dGame/dMission/MissionState.h b/dGame/dMission/MissionState.h index 5ee480da..fb1841d3 100644 --- a/dGame/dMission/MissionState.h +++ b/dGame/dMission/MissionState.h @@ -1,4 +1,4 @@ -#pragma once +#pragma once #ifndef __MISSIONSTATE__H__ #define __MISSIONSTATE__H__ diff --git a/dGame/dMission/MissionTask.cpp b/dGame/dMission/MissionTask.cpp index e08dc146..dc2cb149 100644 --- a/dGame/dMission/MissionTask.cpp +++ b/dGame/dMission/MissionTask.cpp @@ -1,4 +1,4 @@ -#include +#include #include "MissionTask.h" diff --git a/dGame/dMission/MissionTask.h b/dGame/dMission/MissionTask.h index 14d885c3..ea4b8a05 100644 --- a/dGame/dMission/MissionTask.h +++ b/dGame/dMission/MissionTask.h @@ -1,4 +1,4 @@ -#pragma once +#pragma once #ifndef MISSIONTASK_H #define MISSIONTASK_H diff --git a/dGame/dMission/MissionTaskType.h b/dGame/dMission/MissionTaskType.h index 08f1bff9..6c9b2668 100644 --- a/dGame/dMission/MissionTaskType.h +++ b/dGame/dMission/MissionTaskType.h @@ -1,4 +1,4 @@ -#pragma once +#pragma once #ifndef MISSIONTASKTYPE_H #define MISSIONTASKTYPE_H diff --git a/dGame/dUtilities/Preconditions.h b/dGame/dUtilities/Preconditions.h index 08e564bf..2b6e1216 100644 --- a/dGame/dUtilities/Preconditions.h +++ b/dGame/dUtilities/Preconditions.h @@ -1,4 +1,4 @@ -#pragma once +#pragma once #include #include "Entity.h" diff --git a/dScripts/AgJetEffectServer.cpp b/dScripts/AgJetEffectServer.cpp index 748b947b..8c7eca3b 100644 --- a/dScripts/AgJetEffectServer.cpp +++ b/dScripts/AgJetEffectServer.cpp @@ -1,4 +1,4 @@ -#include "AgJetEffectServer.h" +#include "AgJetEffectServer.h" #include "GameMessages.h" #include "EntityManager.h" #include "SkillComponent.h" diff --git a/dScripts/AgJetEffectServer.h b/dScripts/AgJetEffectServer.h index 094c73d2..3cb3bd83 100644 --- a/dScripts/AgJetEffectServer.h +++ b/dScripts/AgJetEffectServer.h @@ -1,4 +1,4 @@ -#pragma once +#pragma once #include "CppScripts.h" class AgJetEffectServer final : public CppScripts::Script diff --git a/dScripts/AgPropGuard.cpp b/dScripts/AgPropGuard.cpp index c8376b3e..51f76a27 100644 --- a/dScripts/AgPropGuard.cpp +++ b/dScripts/AgPropGuard.cpp @@ -1,4 +1,4 @@ -#include "AgPropGuard.h" +#include "AgPropGuard.h" #include "Entity.h" #include "Character.h" #include "EntityManager.h" diff --git a/dScripts/AgPropGuard.h b/dScripts/AgPropGuard.h index 4f6a96d9..f68573dd 100644 --- a/dScripts/AgPropGuard.h +++ b/dScripts/AgPropGuard.h @@ -1,4 +1,4 @@ -#pragma once +#pragma once #include "CppScripts.h" class AgPropGuard final : public CppScripts::Script diff --git a/dScripts/AgSalutingNpcs.cpp b/dScripts/AgSalutingNpcs.cpp index 28495f58..4e4d8b2c 100644 --- a/dScripts/AgSalutingNpcs.cpp +++ b/dScripts/AgSalutingNpcs.cpp @@ -1,4 +1,4 @@ -#include "AgSalutingNpcs.h" +#include "AgSalutingNpcs.h" #include "GameMessages.h" diff --git a/dScripts/AgSalutingNpcs.h b/dScripts/AgSalutingNpcs.h index 7dd20316..c53d03b2 100644 --- a/dScripts/AgSalutingNpcs.h +++ b/dScripts/AgSalutingNpcs.h @@ -1,4 +1,4 @@ -#pragma once +#pragma once #include "CppScripts.h" class AgSalutingNpcs final : public CppScripts::Script diff --git a/dScripts/BossSpiderQueenEnemyServer.cpp b/dScripts/BossSpiderQueenEnemyServer.cpp index 438493fe..ef81c888 100644 --- a/dScripts/BossSpiderQueenEnemyServer.cpp +++ b/dScripts/BossSpiderQueenEnemyServer.cpp @@ -1,4 +1,4 @@ -#include "BossSpiderQueenEnemyServer.h" +#include "BossSpiderQueenEnemyServer.h" #include "GeneralUtils.h" diff --git a/dScripts/BossSpiderQueenEnemyServer.h b/dScripts/BossSpiderQueenEnemyServer.h index e41b878d..8f73d99f 100644 --- a/dScripts/BossSpiderQueenEnemyServer.h +++ b/dScripts/BossSpiderQueenEnemyServer.h @@ -1,4 +1,4 @@ -#pragma once +#pragma once #include "CppScripts.h" /* diff --git a/dScripts/FvNinjaGuard.cpp b/dScripts/FvNinjaGuard.cpp index 0a3cb19c..6a841ccf 100644 --- a/dScripts/FvNinjaGuard.cpp +++ b/dScripts/FvNinjaGuard.cpp @@ -1,4 +1,4 @@ -#include "FvNinjaGuard.h" +#include "FvNinjaGuard.h" #include "GameMessages.h" #include "MissionComponent.h" diff --git a/dScripts/FvNinjaGuard.h b/dScripts/FvNinjaGuard.h index f3deb140..8a87e8bc 100644 --- a/dScripts/FvNinjaGuard.h +++ b/dScripts/FvNinjaGuard.h @@ -1,4 +1,4 @@ -#pragma once +#pragma once #include "CppScripts.h" class FvNinjaGuard final : public CppScripts::Script diff --git a/dScripts/GfBanana.cpp b/dScripts/GfBanana.cpp index d64f1620..3a71eded 100644 --- a/dScripts/GfBanana.cpp +++ b/dScripts/GfBanana.cpp @@ -1,4 +1,4 @@ -#include "GfBanana.h" +#include "GfBanana.h" #include "Entity.h" #include "DestroyableComponent.h" diff --git a/dScripts/GfBanana.h b/dScripts/GfBanana.h index 8deb2396..a33bddf6 100644 --- a/dScripts/GfBanana.h +++ b/dScripts/GfBanana.h @@ -1,4 +1,4 @@ -#pragma once +#pragma once #include "CppScripts.h" class GfBanana final : public CppScripts::Script diff --git a/dScripts/GfBananaCluster.cpp b/dScripts/GfBananaCluster.cpp index 19d1b489..6e5e91db 100644 --- a/dScripts/GfBananaCluster.cpp +++ b/dScripts/GfBananaCluster.cpp @@ -1,4 +1,4 @@ -#include "GfBananaCluster.h" +#include "GfBananaCluster.h" #include "Entity.h" void GfBananaCluster::OnStartup(Entity* self) { diff --git a/dScripts/GfBananaCluster.h b/dScripts/GfBananaCluster.h index 05e5ee0a..81bb8b0b 100644 --- a/dScripts/GfBananaCluster.h +++ b/dScripts/GfBananaCluster.h @@ -1,4 +1,4 @@ -#pragma once +#pragma once #include "CppScripts.h" class GfBananaCluster final : public CppScripts::Script diff --git a/dScripts/GfJailkeepMission.cpp b/dScripts/GfJailkeepMission.cpp index 59f8db0e..eaa8c73d 100644 --- a/dScripts/GfJailkeepMission.cpp +++ b/dScripts/GfJailkeepMission.cpp @@ -1,4 +1,4 @@ -#include "GfJailkeepMission.h" +#include "GfJailkeepMission.h" #include "MissionComponent.h" #include "Character.h" diff --git a/dScripts/GfJailkeepMission.h b/dScripts/GfJailkeepMission.h index f9410032..a120d29b 100644 --- a/dScripts/GfJailkeepMission.h +++ b/dScripts/GfJailkeepMission.h @@ -1,4 +1,4 @@ -#pragma once +#pragma once #include "CppScripts.h" class GfJailkeepMission final : public CppScripts::Script diff --git a/dScripts/NtSleepingGuard.cpp b/dScripts/NtSleepingGuard.cpp index 597b5997..145df6c8 100644 --- a/dScripts/NtSleepingGuard.cpp +++ b/dScripts/NtSleepingGuard.cpp @@ -1,4 +1,4 @@ -#include "NtSleepingGuard.h" +#include "NtSleepingGuard.h" #include "GameMessages.h" #include "MissionComponent.h" diff --git a/dScripts/NtSleepingGuard.h b/dScripts/NtSleepingGuard.h index 42f7391e..5129ae4f 100644 --- a/dScripts/NtSleepingGuard.h +++ b/dScripts/NtSleepingGuard.h @@ -1,4 +1,4 @@ -#pragma once +#pragma once #include "CppScripts.h" class NtSleepingGuard final : public CppScripts::Script diff --git a/dScripts/SpecialImaginePowerupSpawner.cpp b/dScripts/SpecialImaginePowerupSpawner.cpp index 0a13fc2b..c6cab294 100644 --- a/dScripts/SpecialImaginePowerupSpawner.cpp +++ b/dScripts/SpecialImaginePowerupSpawner.cpp @@ -1,4 +1,4 @@ -#include "SpecialImaginePowerupSpawner.h" +#include "SpecialImaginePowerupSpawner.h" #include "GameMessages.h" #include "SkillComponent.h" diff --git a/dScripts/SpecialImaginePowerupSpawner.h b/dScripts/SpecialImaginePowerupSpawner.h index 6cfe2c6e..eb628951 100644 --- a/dScripts/SpecialImaginePowerupSpawner.h +++ b/dScripts/SpecialImaginePowerupSpawner.h @@ -1,4 +1,4 @@ -#pragma once +#pragma once #include "CppScripts.h" class SpecialImaginePowerupSpawner final : public CppScripts::Script diff --git a/dScripts/TriggerAmbush.cpp b/dScripts/TriggerAmbush.cpp index 8c408b32..726b45d7 100644 --- a/dScripts/TriggerAmbush.cpp +++ b/dScripts/TriggerAmbush.cpp @@ -1,4 +1,4 @@ -#include "TriggerAmbush.h" +#include "TriggerAmbush.h" #include "dZoneManager.h" diff --git a/dScripts/TriggerAmbush.h b/dScripts/TriggerAmbush.h index 0544f3cb..e4388fbe 100644 --- a/dScripts/TriggerAmbush.h +++ b/dScripts/TriggerAmbush.h @@ -1,4 +1,4 @@ -#pragma once +#pragma once #include "CppScripts.h" class TriggerAmbush : public CppScripts::Script From 6c97ea820876ce10e4a6197dc1cd3739fef116a5 Mon Sep 17 00:00:00 2001 From: Jett <55758076+Jettford@users.noreply.github.com> Date: Sat, 6 Aug 2022 09:19:34 +0100 Subject: [PATCH 52/86] Implement flying command (#713) * Implement flying command * Add documentation. --- dGame/Character.h | 17 ++++++++++++ dGame/dBehaviors/JetPackBehavior.cpp | 18 +++++++++++++ dGame/dUtilities/SlashCommandHandler.cpp | 34 ++++++++++++++++++++++++ docs/Commands.md | 1 + 4 files changed, 70 insertions(+) diff --git a/dGame/Character.h b/dGame/Character.h index 1a1d4cd0..52bff83d 100644 --- a/dGame/Character.h +++ b/dGame/Character.h @@ -425,6 +425,18 @@ public: */ const std::vector& GetEquippedItems() const { return m_EquippedItems; } + /** + * @brief Get the flying state + * @return value of the flying state + */ + bool GetIsFlying() { return m_IsFlying; } + + /** + * @brief Set the value of the flying state + * @param isFlying the flying state + */ + void SetIsFlying(bool isFlying) { m_IsFlying = isFlying; } + private: /** * The ID of this character. First 32 bits of the ObjectID. @@ -621,6 +633,11 @@ private: */ std::string m_TargetScene; + /** + * Bool that tracks the flying state of the user. + */ + bool m_IsFlying = false; + /** * Queries the character XML and updates all the fields of this object * NOTE: quick as there's no DB lookups diff --git a/dGame/dBehaviors/JetPackBehavior.cpp b/dGame/dBehaviors/JetPackBehavior.cpp index 00900735..e7d76560 100644 --- a/dGame/dBehaviors/JetPackBehavior.cpp +++ b/dGame/dBehaviors/JetPackBehavior.cpp @@ -3,16 +3,34 @@ #include "BehaviorBranchContext.h" #include "GameMessages.h" +#include "Character.h" + void JetPackBehavior::Handle(BehaviorContext* context, RakNet::BitStream* bit_stream, const BehaviorBranchContext branch) { auto* entity = EntityManager::Instance()->GetEntity(branch.target); GameMessages::SendSetJetPackMode(entity, true, this->m_BypassChecks, this->m_EnableHover, this->m_effectId, this->m_Airspeed, this->m_MaxAirspeed, this->m_VerticalVelocity, this->m_WarningEffectID); + + if (entity->IsPlayer()) { + auto* character = entity->GetCharacter(); + + if (character) { + character->SetIsFlying(true); + } + } } void JetPackBehavior::UnCast(BehaviorContext* context, BehaviorBranchContext branch) { auto* entity = EntityManager::Instance()->GetEntity(branch.target); GameMessages::SendSetJetPackMode(entity, false); + + if (entity->IsPlayer()) { + auto* character = entity->GetCharacter(); + + if (character) { + character->SetIsFlying(false); + } + } } void JetPackBehavior::Calculate(BehaviorContext* context, RakNet::BitStream* bit_stream, const BehaviorBranchContext branch) { diff --git a/dGame/dUtilities/SlashCommandHandler.cpp b/dGame/dUtilities/SlashCommandHandler.cpp index 0bf37288..b91021de 100644 --- a/dGame/dUtilities/SlashCommandHandler.cpp +++ b/dGame/dUtilities/SlashCommandHandler.cpp @@ -942,6 +942,40 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit } } + if (chatCommand == "fly" && entity->GetGMLevel() >= GAME_MASTER_LEVEL_JUNIOR_DEVELOPER) { + auto* character = entity->GetCharacter(); + + if (character) { + bool isFlying = character->GetIsFlying(); + + if (isFlying) { + GameMessages::SendSetJetPackMode(entity, false); + + character->SetIsFlying(false); + } else { + float speedScale = 1.0f; + + if (args.size() >= 1) { + float tempScaleStore; + + if (GeneralUtils::TryParse(args[0], tempScaleStore)) { + speedScale = tempScaleStore; + } else { + ChatPackets::SendSystemMessage(sysAddr, u"Failed to parse speed scale argument."); + } + } + + float airSpeed = 20 * speedScale; + float maxAirSpeed = 30 * speedScale; + float verticalVelocity = 1.5 * speedScale; + + GameMessages::SendSetJetPackMode(entity, true, true, false, 167, airSpeed, maxAirSpeed, verticalVelocity); + + character->SetIsFlying(true); + } + } + } + //------- GM COMMANDS TO ACTUALLY MODERATE -------- if (chatCommand == "mute" && entity->GetGMLevel() >= GAME_MASTER_LEVEL_JUNIOR_DEVELOPER) { diff --git a/docs/Commands.md b/docs/Commands.md index b5588f68..8cefaa14 100644 --- a/docs/Commands.md +++ b/docs/Commands.md @@ -32,6 +32,7 @@ Here is a summary of the commands available in-game. All commands are prefixed b |gminvis|`/gminvis`|Toggles invisibility for the character, though it's currently a bit buggy. Requires nonzero GM Level for the character, but the account must have a GM level of 8.|8| |setname|`/setname `|Sets a temporary name for your player. The name resets when you log out.|8| |title|`/title `|Temporarily appends your player's name with " - <title>". This resets when you log out.|8| +|fly|`/fly <speed>`|This toggles your flying state with an optional parameter for the speed scale.|4| ## Server Operation Commands From 7f5ab8b9faf55d03a4f2b99152bfffb537bd811b Mon Sep 17 00:00:00 2001 From: Zac Hayes <zrev2220@gmail.com> Date: Sun, 7 Aug 2022 01:59:27 -0400 Subject: [PATCH 53/86] Dockerfile: Copy dNavigation to build dir (#722) Fixes an issue where new directory was not copied over to the correct folder for Docker --- docker/Dockerfile | 1 + 1 file changed, 1 insertion(+) diff --git a/docker/Dockerfile b/docker/Dockerfile index 27387e22..50f5b083 100644 --- a/docker/Dockerfile +++ b/docker/Dockerfile @@ -21,6 +21,7 @@ COPY dPhysics/ /build/dPhysics COPY dScripts/ /build/dScripts COPY dWorldServer/ /build/dWorldServer COPY dZoneManager/ /build/dZoneManager +COPY dNavigation/ /build/dNavigation COPY migrations/ /build/migrations COPY resources/ /build/resources COPY thirdparty/ /build/thirdparty From 932d8030f0c966592fcc9f8f3105ec86cdea1b07 Mon Sep 17 00:00:00 2001 From: Aaron Kimbre <aronwk.aaron@gmail.com> Date: Mon, 8 Aug 2022 08:31:44 -0500 Subject: [PATCH 54/86] update git blame ignore --- .git-blame-ignore-revs | 3 +++ 1 file changed, 3 insertions(+) diff --git a/.git-blame-ignore-revs b/.git-blame-ignore-revs index 78e9475c..37567a02 100644 --- a/.git-blame-ignore-revs +++ b/.git-blame-ignore-revs @@ -3,3 +3,6 @@ # add semi-colons to macros consistently 9e4ce24fd2851e65df776dd9c57bcb0d45f4453a + +# convert to unix line endings +72477e01e2711e0f61cdb192ee266e5e21b8846f From dc960cb99cf8026a4e8335821ea3f7ed51dd9b32 Mon Sep 17 00:00:00 2001 From: David Markowitz <39972741+EmosewaMC@users.noreply.github.com> Date: Mon, 8 Aug 2022 07:34:33 -0700 Subject: [PATCH 55/86] Fix landing animation (#720) --- dGame/dComponents/CharacterComponent.cpp | 20 +++++++++++--------- 1 file changed, 11 insertions(+), 9 deletions(-) diff --git a/dGame/dComponents/CharacterComponent.cpp b/dGame/dComponents/CharacterComponent.cpp index 42b8ed34..d425c066 100644 --- a/dGame/dComponents/CharacterComponent.cpp +++ b/dGame/dComponents/CharacterComponent.cpp @@ -36,15 +36,6 @@ CharacterComponent::CharacterComponent(Entity* parent, Character* character) : C m_CurrentActivity = 0; m_CountryCode = 0; m_LastUpdateTimestamp = std::time(nullptr); - - //Check to see if we're landing: - if (character->GetZoneID() != Game::server->GetZoneID()) { - m_IsLanding = true; - } - - if (LandingAnimDisabled(character->GetZoneID()) || LandingAnimDisabled(Game::server->GetZoneID()) || m_LastRocketConfig.empty()) { - m_IsLanding = false; //Don't make us land on VE/minigames lol - } } bool CharacterComponent::LandingAnimDisabled(int zoneID) { @@ -273,6 +264,17 @@ void CharacterComponent::LoadFromXml(tinyxml2::XMLDocument* doc) { } else { m_TotalTimePlayed = 0; } + + if (!m_Character) return; + + //Check to see if we're landing: + if (m_Character->GetZoneID() != Game::server->GetZoneID()) { + m_IsLanding = true; + } + + if (LandingAnimDisabled(m_Character->GetZoneID()) || LandingAnimDisabled(Game::server->GetZoneID()) || m_LastRocketConfig.empty()) { + m_IsLanding = false; //Don't make us land on VE/minigames lol + } } void CharacterComponent::UpdateXml(tinyxml2::XMLDocument* doc) { From 008f953003abdf25d23c52c515fcd63272b3efdc Mon Sep 17 00:00:00 2001 From: David Markowitz <39972741+EmosewaMC@users.noreply.github.com> Date: Mon, 8 Aug 2022 07:34:56 -0700 Subject: [PATCH 56/86] Add physics volume for property orb (#718) --- dGame/dComponents/PhantomPhysicsComponent.cpp | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/dGame/dComponents/PhantomPhysicsComponent.cpp b/dGame/dComponents/PhantomPhysicsComponent.cpp index 8cafec52..430acf3c 100644 --- a/dGame/dComponents/PhantomPhysicsComponent.cpp +++ b/dGame/dComponents/PhantomPhysicsComponent.cpp @@ -205,6 +205,12 @@ PhantomPhysicsComponent::PhantomPhysicsComponent(Entity* parent) : Component(par m_dpEntity->SetRotation(m_Rotation); m_dpEntity->SetPosition(m_Position); dpWorld::Instance().AddEntity(m_dpEntity); + } else if (info->physicsAsset == "env\\vfx_propertyImaginationBall.hkx") { + m_dpEntity = new dpEntity(m_Parent->GetObjectID(), 4.5f); + m_dpEntity->SetScale(m_Scale); + m_dpEntity->SetRotation(m_Rotation); + m_dpEntity->SetPosition(m_Position); + dpWorld::Instance().AddEntity(m_dpEntity); } else { //Game::logger->Log("PhantomPhysicsComponent", "This one is supposed to have %s", info->physicsAsset.c_str()); From 1e1b6aaa0befd86c0d3fe1609958699812b3fdc2 Mon Sep 17 00:00:00 2001 From: Emmett <EmmettPeck@gmail.com> Date: Sun, 14 Aug 2022 11:05:07 -0700 Subject: [PATCH 57/86] Update Docker.md submodule note (#730) * Update Docker.md Changed note to recursively update git submodules, otherwise would lead users into #728 --- Docker.md | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/Docker.md b/Docker.md index 7d5f7bc6..54d0ce19 100644 --- a/Docker.md +++ b/Docker.md @@ -25,8 +25,7 @@ **NOTE #4**: Make sure to run the following in the repo root directory after cloning so submodules are also downloaded. ``` -git submodule init -git submodule update +git submodule update --init --recursive ``` **NOTE #5**: If DarkflameSetup fails due to not having cdclient.fdb, rename CDClient.fdb (in the same folder) to cdclient.fdb From 54021458bd807774e2db4e60891abfbeaa30bdf8 Mon Sep 17 00:00:00 2001 From: Demetri Van Sickle <demetriv.s.7@gmail.com> Date: Tue, 16 Aug 2022 01:49:44 -0700 Subject: [PATCH 58/86] Change build command in build script (#729) The script now uses the cmake build as to be compatible with all platforms as opposed to just platforms that supported gnu make. --- build.sh | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/build.sh b/build.sh index 31eaa2c7..e61c1cb4 100755 --- a/build.sh +++ b/build.sh @@ -5,8 +5,8 @@ cd build # Run cmake to generate make files cmake .. -# Run make to build the project. To build utilizing multiple cores, append `-j` and the amount of cores to utilize, for example `make -j8` -make +# To build utilizing multiple cores, append `-j` and the amount of cores to utilize, for example `cmake --build . --config Release -j8' +cmake --build . --config Release # Run migrations ./MasterServer -m From 3b7f1dad5472c8ee52b6890768d87710e8c49bbe Mon Sep 17 00:00:00 2001 From: David Markowitz <39972741+EmosewaMC@users.noreply.github.com> Date: Tue, 16 Aug 2022 18:53:01 -0700 Subject: [PATCH 59/86] Fix death planes (#733) * Correct death plane size The death plane file size is not in units but is actually in 4x2 tiles. * Make it a bit bigger for now --- dGame/dComponents/PhantomPhysicsComponent.cpp | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/dGame/dComponents/PhantomPhysicsComponent.cpp b/dGame/dComponents/PhantomPhysicsComponent.cpp index 430acf3c..ea88c16d 100644 --- a/dGame/dComponents/PhantomPhysicsComponent.cpp +++ b/dGame/dComponents/PhantomPhysicsComponent.cpp @@ -162,7 +162,8 @@ PhantomPhysicsComponent::PhantomPhysicsComponent(Entity* parent) : Component(par dpWorld::Instance().AddEntity(m_dpEntity); } else if (info->physicsAsset == "miscellaneous\\misc_phys_640x640.hkx") { - m_dpEntity = new dpEntity(m_Parent->GetObjectID(), 640.0f, 20.0f, 640.0f); + // TODO Fix physics simulation to do simulation at high velocities due to bullet through paper problem... + m_dpEntity = new dpEntity(m_Parent->GetObjectID(), 1638.4f, 13.521004f * 2.0f, 1638.4f); m_dpEntity->SetScale(m_Scale); m_dpEntity->SetRotation(m_Rotation); From 976bd3c41b7fcd0262db40b010c365449bb9c94e Mon Sep 17 00:00:00 2001 From: Aaron Kimbrell <aronwk.aaron@gmail.com> Date: Tue, 16 Aug 2022 20:53:28 -0500 Subject: [PATCH 60/86] Selective saving for map and location (#732) * Don't save the map and char location info if we are in an instanced * LUP worlds will be handled in a future PR * simplify check --- dGame/Character.cpp | 4 ++-- .../ControllablePhysicsComponent.cpp | 19 ++++++++++++------- 2 files changed, 14 insertions(+), 9 deletions(-) diff --git a/dGame/Character.cpp b/dGame/Character.cpp index 0b92f0aa..440c30c1 100644 --- a/dGame/Character.cpp +++ b/dGame/Character.cpp @@ -301,9 +301,9 @@ void Character::SaveXMLToDatabase() { character->SetAttribute("gm", m_GMLevel); character->SetAttribute("cc", m_Coins); + auto zoneInfo = dZoneManager::Instance()->GetZone()->GetZoneID(); // lzid garbage, binary concat of zoneID, zoneInstance and zoneClone - if (Game::server->GetZoneID() != 0) { - auto zoneInfo = dZoneManager::Instance()->GetZone()->GetZoneID(); + if (zoneInfo.GetMapID() != 0 && zoneInfo.GetCloneID() == 0) { uint64_t lzidConcat = zoneInfo.GetCloneID(); lzidConcat = (lzidConcat << 16) | uint16_t(zoneInfo.GetInstanceID()); lzidConcat = (lzidConcat << 16) | uint16_t(zoneInfo.GetMapID()); diff --git a/dGame/dComponents/ControllablePhysicsComponent.cpp b/dGame/dComponents/ControllablePhysicsComponent.cpp index 19c17035..471b9ca1 100644 --- a/dGame/dComponents/ControllablePhysicsComponent.cpp +++ b/dGame/dComponents/ControllablePhysicsComponent.cpp @@ -11,6 +11,7 @@ #include "CDClientManager.h" #include "EntityManager.h" #include "Character.h" +#include "dZoneManager.h" ControllablePhysicsComponent::ControllablePhysicsComponent(Entity* entity) : Component(entity) { m_Position = {}; @@ -163,13 +164,17 @@ void ControllablePhysicsComponent::UpdateXml(tinyxml2::XMLDocument* doc) { return; } - character->SetAttribute("lzx", m_Position.x); - character->SetAttribute("lzy", m_Position.y); - character->SetAttribute("lzz", m_Position.z); - character->SetAttribute("lzrx", m_Rotation.x); - character->SetAttribute("lzry", m_Rotation.y); - character->SetAttribute("lzrz", m_Rotation.z); - character->SetAttribute("lzrw", m_Rotation.w); + auto zoneInfo = dZoneManager::Instance()->GetZone()->GetZoneID(); + + if (zoneInfo.GetMapID() != 0 && zoneInfo.GetCloneID() == 0) { + character->SetAttribute("lzx", m_Position.x); + character->SetAttribute("lzy", m_Position.y); + character->SetAttribute("lzz", m_Position.z); + character->SetAttribute("lzrx", m_Rotation.x); + character->SetAttribute("lzry", m_Rotation.y); + character->SetAttribute("lzrz", m_Rotation.z); + character->SetAttribute("lzrw", m_Rotation.w); + } } void ControllablePhysicsComponent::SetPosition(const NiPoint3& pos) { From 50b3946548b0279a4316137c894291bc3f58d7a8 Mon Sep 17 00:00:00 2001 From: David Markowitz <39972741+EmosewaMC@users.noreply.github.com> Date: Tue, 16 Aug 2022 20:28:50 -0700 Subject: [PATCH 61/86] Fix death planes (#735) * Correct death plane size The death plane file size is not in units but is actually in 4x2 tiles. * Make it a bit bigger for now * Enjoy your crust "These things add flavor they said" Move the position of the death barrier down 13.521004 units so we effectively only extend its hitbox in the -Y direction as opposed to the +Y direction, resolving an issue in Battle of Nimbus Station where the death plane was too tall --- dGame/dComponents/PhantomPhysicsComponent.cpp | 2 ++ 1 file changed, 2 insertions(+) diff --git a/dGame/dComponents/PhantomPhysicsComponent.cpp b/dGame/dComponents/PhantomPhysicsComponent.cpp index ea88c16d..cef9cc36 100644 --- a/dGame/dComponents/PhantomPhysicsComponent.cpp +++ b/dGame/dComponents/PhantomPhysicsComponent.cpp @@ -162,6 +162,8 @@ PhantomPhysicsComponent::PhantomPhysicsComponent(Entity* parent) : Component(par dpWorld::Instance().AddEntity(m_dpEntity); } else if (info->physicsAsset == "miscellaneous\\misc_phys_640x640.hkx") { + // Move this down by 13.521004 units so it is still effectively at the same height as before + m_Position = m_Position - NiPoint3::UNIT_Y * 13.521004f; // TODO Fix physics simulation to do simulation at high velocities due to bullet through paper problem... m_dpEntity = new dpEntity(m_Parent->GetObjectID(), 1638.4f, 13.521004f * 2.0f, 1638.4f); From dd8091f60e5088e48a2d8487b58033b63b393115 Mon Sep 17 00:00:00 2001 From: Daniel Seiler <me@xiphoseer.de> Date: Wed, 17 Aug 2022 10:43:54 +0200 Subject: [PATCH 62/86] Hide dependency compilation warnings (#696) * Hide raknet compilation warnings * Move out MariaDB Connector/C++ logic * remove mariadb warnings? * hide mariadb cmake warnings? --- thirdparty/CMakeLists.txt | 160 +------------------------------ thirdparty/CMakeMariaDBLists.txt | 149 ++++++++++++++++++++++++++++ thirdparty/raknet/CMakeLists.txt | 27 +++--- 3 files changed, 169 insertions(+), 167 deletions(-) create mode 100644 thirdparty/CMakeMariaDBLists.txt diff --git a/thirdparty/CMakeLists.txt b/thirdparty/CMakeLists.txt index 119ce4fd..c04e418e 100644 --- a/thirdparty/CMakeLists.txt +++ b/thirdparty/CMakeLists.txt @@ -1,11 +1,3 @@ -# Source Code for raknet -file( - GLOB SOURCES_RAKNET - LIST_DIRECTORIES false - RELATIVE "${CMAKE_CURRENT_SOURCE_DIR}" - ${CMAKE_CURRENT_SOURCE_DIR}/raknet/Source/*.cpp -) - # Source Code for recast file( GLOB SOURCES_RECAST @@ -47,167 +39,23 @@ file( ${CMAKE_CURRENT_SOURCE_DIR}/SQLite/*.c ) -# mariadb connector cpp -# On Windows ClangCL can't compile the connector from source but can link to an msvc compiled one, -# so prefer the prebuilt binaries unless MARIADB_BUILD_SOURCE is specified -if(WIN32 AND NOT MARIADB_BUILD_SOURCE) - set(MARIADB_MSI_DIR "${PROJECT_BINARY_DIR}/msi") - set(MARIADB_CONNECTOR_DIR "${PROJECT_BINARY_DIR}/mariadbcpp") - set(MARIADB_C_CONNECTOR_DIR "${MARIADB_CONNECTOR_DIR}/MariaDB/MariaDB Connector C 64-bit") - set(MARIADB_CPP_CONNECTOR_DIR "${MARIADB_CONNECTOR_DIR}/MariaDB/MariaDB C++ Connector 64-bit") - - file(MAKE_DIRECTORY "${MARIADB_MSI_DIR}") - file(MAKE_DIRECTORY "${MARIADB_CONNECTOR_DIR}") - - if(NOT EXISTS "${MARIADB_MSI_DIR}/mariadb-connector-c-3.2.5-win64.msi" ) - message("Downloading mariadb connector/c") - file(DOWNLOAD https://dlm.mariadb.com/1936366/connectors/c/connector-c-3.2.5/mariadb-connector-c-3.2.5-win64.msi - "${MARIADB_MSI_DIR}/mariadb-connector-c-3.2.5-win64.msi" - EXPECTED_HASH MD5=09d418c290109068a5bea136dafca36b) - endif() - - if(NOT EXISTS "${MARIADB_MSI_DIR}/mariadb-connector-cpp-1.0.1-win64.msi" ) - message("Downloading mariadb connector/c++") - file(DOWNLOAD https://dlm.mariadb.com/1683453/connectors/cpp/connector-cpp-1.0.1/mariadb-connector-cpp-1.0.1-win64.msi - "${MARIADB_MSI_DIR}/mariadb-connector-cpp-1.0.1-win64.msi" - EXPECTED_HASH MD5=548e743fbf067d21d42b81d958bf4ed7) - endif() - - - file(TO_NATIVE_PATH "${MARIADB_CONNECTOR_DIR}" MSIEXEC_TARGETDIR) - # extract msi files without installing to users system - if(NOT EXISTS "${MARIADB_C_CONNECTOR_DIR}") - file(TO_NATIVE_PATH "${MARIADB_MSI_DIR}/mariadb-connector-c-3.2.5-win64.msi" MSI_DIR) - execute_process(COMMAND msiexec /a ${MSI_DIR} /qn TARGETDIR=${MSIEXEC_TARGETDIR}) - endif() - - if(NOT EXISTS "${MARIADB_CPP_CONNECTOR_DIR}") - file(TO_NATIVE_PATH "${MARIADB_MSI_DIR}/mariadb-connector-cpp-1.0.1-win64.msi" MSI_DIR) - execute_process(COMMAND msiexec /a ${MSI_DIR} /qn TARGETDIR=${MSIEXEC_TARGETDIR}) - endif() - - set(MARIADB_SHARED_LIBRARY_LOCATION "${MARIADB_CPP_CONNECTOR_DIR}/mariadbcpp.dll") - set(MARIADB_IMPLIB_LOCATION "${MARIADB_CPP_CONNECTOR_DIR}/mariadbcpp.lib") - set(MARIADB_INCLUDE_DIR "${MARIADB_CPP_CONNECTOR_DIR}/include/mariadb") - - add_custom_target(mariadb_connector_cpp) - add_custom_command(TARGET mariadb_connector_cpp POST_BUILD - COMMAND ${CMAKE_COMMAND} -E copy_if_different - "${MARIADB_CPP_CONNECTOR_DIR}/mariadbcpp.dll" - "${MARIADB_C_CONNECTOR_DIR}/lib/libmariadb.dll" - "${PROJECT_BINARY_DIR}") - - # MariaDB uses plugins that the database needs to load, the prebuilt binaries by default will try to find the libraries in system directories, - # so set this define and the servers will set the MARIADB_PLUGIN_DIR environment variable to the appropriate directory. - # Plugin directory is determined at dll load time (this will happen before main()) so we need to delay the dll load so that we can set the environment variable - add_link_options(/DELAYLOAD:${MARIADB_SHARED_LIBRARY_LOCATION}) - add_compile_definitions(MARIADB_PLUGIN_DIR_OVERRIDE="${MARIADB_CPP_CONNECTOR_DIR}/plugin") -else() # Build from source - - include(ExternalProject) - if(WIN32) - set(MARIADB_EXTRA_COMPILE_FLAGS /EHsc) - set(MARIADB_EXTRA_CMAKE_ARGS -DWITH_MSI=OFF) - elseif(APPLE) - set(MARIADB_EXTRA_COMPILE_FLAGS -D_GLIBCXX_USE_CXX11_ABI=0) - set(MARIADB_EXTRA_CMAKE_ARGS -DWITH_EXTERNAL_ZLIB=ON -DOPENSSL_ROOT_DIR=${OPENSSL_ROOT_DIR}) - else() - set(MARIADB_EXTRA_COMPILE_FLAGS -D_GLIBCXX_USE_CXX11_ABI=0) - endif() - - ExternalProject_Add(mariadb_connector_cpp - SOURCE_DIR ${CMAKE_SOURCE_DIR}/thirdparty/mariadb-connector-cpp - CMAKE_ARGS "-DCMAKE_CXX_FLAGS:STRING= ${MARIADB_EXTRA_COMPILE_FLAGS}" - -DCMAKE_BUILD_RPATH_USE_ORIGIN=${CMAKE_BUILD_RPATH_USE_ORIGIN} - -DCMAKE_INSTALL_PREFIX=./mariadbcpp # Points the connector to the correct plugin directory - -DINSTALL_PLUGINDIR=plugin - ${MARIADB_EXTRA_CMAKE_ARGS} - PREFIX "${PROJECT_BINARY_DIR}/mariadbcpp" - BUILD_COMMAND cmake --build . --config RelWithDebInfo -j${__maria_db_connector_compile_jobs__} - INSTALL_COMMAND "") - - ExternalProject_Get_Property(mariadb_connector_cpp BINARY_DIR) - - if(WIN32) - set(MARIADB_SHARED_LIBRARY_NAME mariadbcpp.dll) - set(MARIADB_PLUGIN_SUFFIX .dll) - set(MARIADB_IMPLIB_LOCATION "${BINARY_DIR}/RelWithDebInfo/mariadbcpp.lib") - - # When built from source windows only seems to check same folder as exe instead specified folder, so use - # environment variable to force it - add_link_options(/DELAYLOAD:mariadbcpp.dll) - add_compile_definitions(MARIADB_PLUGIN_DIR_OVERRIDE="${PROJECT_BINARY_DIR}/mariadbcpp/plugin") - else() - set(MARIADB_SHARED_LIBRARY_NAME libmariadbcpp${CMAKE_SHARED_LIBRARY_SUFFIX}) - set(MARIADB_PLUGIN_SUFFIX .so) - endif() - - get_property(isMultiConfig GLOBAL PROPERTY GENERATOR_IS_MULTI_CONFIG) - if(isMultiConfig) - set(MARIADB_SHARED_LIBRARY_LOCATION "${BINARY_DIR}/RelWithDebInfo/${MARIADB_SHARED_LIBRARY_NAME}") - set(MARIADB_SHARED_LIBRARY_COPY_LOCATION "${PROJECT_BINARY_DIR}/$<CONFIG>") - set(MARIADB_PLUGINS_LOCATION "${BINARY_DIR}/libmariadb/RelWithDebInfo") - else() - set(MARIADB_SHARED_LIBRARY_LOCATION "${BINARY_DIR}/${MARIADB_SHARED_LIBRARY_NAME}") - set(MARIADB_SHARED_LIBRARY_COPY_LOCATION "${PROJECT_BINARY_DIR}") - set(MARIADB_PLUGINS_LOCATION "${BINARY_DIR}/libmariadb") - endif() - - set(MARIADB_INCLUDE_DIR "${CMAKE_SOURCE_DIR}/thirdparty/mariadb-connector-cpp/include/") - - add_custom_command(TARGET mariadb_connector_cpp POST_BUILD - COMMAND ${CMAKE_COMMAND} -E make_directory - ${BINARY_DIR}/mariadbcpp/plugin - ${MARIADB_SHARED_LIBRARY_COPY_LOCATION} - - COMMAND ${CMAKE_COMMAND} -E copy_if_different - ${MARIADB_SHARED_LIBRARY_LOCATION} - ${MARIADB_SHARED_LIBRARY_COPY_LOCATION} - - COMMAND ${CMAKE_COMMAND} -E copy_if_different - ${MARIADB_PLUGINS_LOCATION}/caching_sha2_password${MARIADB_PLUGIN_SUFFIX} - ${MARIADB_PLUGINS_LOCATION}/client_ed25519${MARIADB_PLUGIN_SUFFIX} - ${MARIADB_PLUGINS_LOCATION}/dialog${MARIADB_PLUGIN_SUFFIX} - ${MARIADB_PLUGINS_LOCATION}/mysql_clear_password${MARIADB_PLUGIN_SUFFIX} - ${MARIADB_PLUGINS_LOCATION}/sha256_password${MARIADB_PLUGIN_SUFFIX} - ${BINARY_DIR}/mariadbcpp/plugin) -endif() - -# Remove the CMakeLists.txt file from the tests folder for the maria-db-connector so we dont compile the tests. -if(EXISTS "${CMAKE_SOURCE_DIR}/thirdparty/mariadb-connector-cpp/test/CMakeLists.txt") - file(REMOVE "${CMAKE_SOURCE_DIR}/thirdparty/mariadb-connector-cpp/test/CMakeLists.txt") -endif() - -# Create mariadb connector library object -add_library(mariadbConnCpp SHARED IMPORTED GLOBAL) -set_property(TARGET mariadbConnCpp PROPERTY IMPORTED_LOCATION ${MARIADB_SHARED_LIBRARY_LOCATION}) - -if(WIN32) - set_property(TARGET mariadbConnCpp PROPERTY IMPORTED_IMPLIB ${MARIADB_IMPLIB_LOCATION}) -endif() - -# Add directories to include lists -target_include_directories(mariadbConnCpp INTERFACE ${MARIADB_INCLUDE_DIR}) -add_dependencies(mariadbConnCpp mariadb_connector_cpp) +# MariaDB C++ Connector +include(CMakeMariaDBLists.txt) # Create our third party library objects -add_library(raknet ${SOURCES_RAKNET}) +add_subdirectory(raknet) add_library(tinyxml2 ${SOURCES_TINYXML2}) add_library(detour ${SOURCES_DETOUR}) add_library(recast ${SOURCES_RECAST}) add_library(libbcrypt ${SOURCES_LIBBCRYPT}) add_library(sqlite3 ${SOURCES_SQLITE3}) -if(WIN32) - # Link Win Sockets 2 to RakNet - target_link_libraries(raknet ws2_32) -elseif(UNIX) +if(UNIX) # Add warning disable flags and link Unix libraries to sqlite3 target_link_libraries(sqlite3 pthread dl m) # -Wno-unused-result -Wno-unknown-pragmas -fpermissive target_compile_options(sqlite3 PRIVATE "-Wno-return-local-addr" "-Wno-maybe-uninitialized") - target_compile_options(raknet PRIVATE "-Wno-write-strings" "-Wformat-overflow=0" "-Wformat=0") target_compile_options(libbcrypt PRIVATE "-Wno-implicit-function-declaration" "-Wno-int-conversion") endif() diff --git a/thirdparty/CMakeMariaDBLists.txt b/thirdparty/CMakeMariaDBLists.txt new file mode 100644 index 00000000..55e95c4d --- /dev/null +++ b/thirdparty/CMakeMariaDBLists.txt @@ -0,0 +1,149 @@ +# mariadb connector cpp +# On Windows ClangCL can't compile the connector from source but can link to an msvc compiled one, +# so prefer the prebuilt binaries unless MARIADB_BUILD_SOURCE is specified +if(WIN32 AND NOT MARIADB_BUILD_SOURCE) + set(MARIADB_MSI_DIR "${PROJECT_BINARY_DIR}/msi") + set(MARIADB_CONNECTOR_DIR "${PROJECT_BINARY_DIR}/mariadbcpp") + set(MARIADB_C_CONNECTOR_DIR "${MARIADB_CONNECTOR_DIR}/MariaDB/MariaDB Connector C 64-bit") + set(MARIADB_CPP_CONNECTOR_DIR "${MARIADB_CONNECTOR_DIR}/MariaDB/MariaDB C++ Connector 64-bit") + + file(MAKE_DIRECTORY "${MARIADB_MSI_DIR}") + file(MAKE_DIRECTORY "${MARIADB_CONNECTOR_DIR}") + + if(NOT EXISTS "${MARIADB_MSI_DIR}/mariadb-connector-c-3.2.5-win64.msi" ) + message("Downloading mariadb connector/c") + file(DOWNLOAD https://dlm.mariadb.com/1936366/connectors/c/connector-c-3.2.5/mariadb-connector-c-3.2.5-win64.msi + "${MARIADB_MSI_DIR}/mariadb-connector-c-3.2.5-win64.msi" + EXPECTED_HASH MD5=09d418c290109068a5bea136dafca36b) + endif() + + if(NOT EXISTS "${MARIADB_MSI_DIR}/mariadb-connector-cpp-1.0.1-win64.msi" ) + message("Downloading mariadb connector/c++") + file(DOWNLOAD https://dlm.mariadb.com/1683453/connectors/cpp/connector-cpp-1.0.1/mariadb-connector-cpp-1.0.1-win64.msi + "${MARIADB_MSI_DIR}/mariadb-connector-cpp-1.0.1-win64.msi" + EXPECTED_HASH MD5=548e743fbf067d21d42b81d958bf4ed7) + endif() + + + file(TO_NATIVE_PATH "${MARIADB_CONNECTOR_DIR}" MSIEXEC_TARGETDIR) + # extract msi files without installing to users system + if(NOT EXISTS "${MARIADB_C_CONNECTOR_DIR}") + file(TO_NATIVE_PATH "${MARIADB_MSI_DIR}/mariadb-connector-c-3.2.5-win64.msi" MSI_DIR) + execute_process(COMMAND msiexec /a ${MSI_DIR} /qn TARGETDIR=${MSIEXEC_TARGETDIR}) + endif() + + if(NOT EXISTS "${MARIADB_CPP_CONNECTOR_DIR}") + file(TO_NATIVE_PATH "${MARIADB_MSI_DIR}/mariadb-connector-cpp-1.0.1-win64.msi" MSI_DIR) + execute_process(COMMAND msiexec /a ${MSI_DIR} /qn TARGETDIR=${MSIEXEC_TARGETDIR}) + endif() + + set(MARIADB_SHARED_LIBRARY_LOCATION "${MARIADB_CPP_CONNECTOR_DIR}/mariadbcpp.dll") + set(MARIADB_IMPLIB_LOCATION "${MARIADB_CPP_CONNECTOR_DIR}/mariadbcpp.lib") + set(MARIADB_INCLUDE_DIR "${MARIADB_CPP_CONNECTOR_DIR}/include/mariadb") + + add_custom_target(mariadb_connector_cpp) + add_custom_command(TARGET mariadb_connector_cpp POST_BUILD + COMMAND ${CMAKE_COMMAND} -E copy_if_different + "${MARIADB_CPP_CONNECTOR_DIR}/mariadbcpp.dll" + "${MARIADB_C_CONNECTOR_DIR}/lib/libmariadb.dll" + "${PROJECT_BINARY_DIR}") + + # MariaDB uses plugins that the database needs to load, the prebuilt binaries by default will try to find the libraries in system directories, + # so set this define and the servers will set the MARIADB_PLUGIN_DIR environment variable to the appropriate directory. + # Plugin directory is determined at dll load time (this will happen before main()) so we need to delay the dll load so that we can set the environment variable + add_link_options(/DELAYLOAD:${MARIADB_SHARED_LIBRARY_LOCATION}) + add_compile_definitions(MARIADB_PLUGIN_DIR_OVERRIDE="${MARIADB_CPP_CONNECTOR_DIR}/plugin") +else() # Build from source + + include(ExternalProject) + if(WIN32) + set(MARIADB_EXTRA_CMAKE_ARGS + -DCMAKE_C_FLAGS=/w # disable zlib warnings + -DCMAKE_CXX_FLAGS=/EHsc + -DWITH_MSI=OFF) + elseif(APPLE) + set(MARIADB_EXTRA_CMAKE_ARGS + -DWITH_EXTERNAL_ZLIB=ON + -DOPENSSL_ROOT_DIR=${OPENSSL_ROOT_DIR} + -DCMAKE_C_FLAGS=-w # disable zlib warnings + -DCMAKE_CXX_FLAGS=-D_GLIBCXX_USE_CXX11_ABI=0) + else() + set(MARIADB_EXTRA_CMAKE_ARGS + -DCMAKE_C_FLAGS=-w # disable zlib warnings + -DCMAKE_CXX_FLAGS=-D_GLIBCXX_USE_CXX11_ABI=0) + endif() + + ExternalProject_Add(mariadb_connector_cpp + SOURCE_DIR ${CMAKE_SOURCE_DIR}/thirdparty/mariadb-connector-cpp + CMAKE_ARGS -Wno-dev + -DCMAKE_BUILD_RPATH_USE_ORIGIN=${CMAKE_BUILD_RPATH_USE_ORIGIN} + -DCMAKE_INSTALL_PREFIX=./mariadbcpp # Points the connector to the correct plugin directory + -DINSTALL_PLUGINDIR=plugin + ${MARIADB_EXTRA_CMAKE_ARGS} + PREFIX "${PROJECT_BINARY_DIR}/mariadbcpp" + BUILD_COMMAND cmake --build . --config RelWithDebInfo -j${__maria_db_connector_compile_jobs__} + INSTALL_COMMAND "") + + ExternalProject_Get_Property(mariadb_connector_cpp BINARY_DIR) + + if(WIN32) + set(MARIADB_SHARED_LIBRARY_NAME mariadbcpp.dll) + set(MARIADB_PLUGIN_SUFFIX .dll) + set(MARIADB_IMPLIB_LOCATION "${BINARY_DIR}/RelWithDebInfo/mariadbcpp.lib") + + # When built from source windows only seems to check same folder as exe instead specified folder, so use + # environment variable to force it + add_link_options(/DELAYLOAD:mariadbcpp.dll) + add_compile_definitions(MARIADB_PLUGIN_DIR_OVERRIDE="${PROJECT_BINARY_DIR}/mariadbcpp/plugin") + else() + set(MARIADB_SHARED_LIBRARY_NAME libmariadbcpp${CMAKE_SHARED_LIBRARY_SUFFIX}) + set(MARIADB_PLUGIN_SUFFIX .so) + endif() + + get_property(isMultiConfig GLOBAL PROPERTY GENERATOR_IS_MULTI_CONFIG) + if(isMultiConfig) + set(MARIADB_SHARED_LIBRARY_LOCATION "${BINARY_DIR}/RelWithDebInfo/${MARIADB_SHARED_LIBRARY_NAME}") + set(MARIADB_SHARED_LIBRARY_COPY_LOCATION "${PROJECT_BINARY_DIR}/$<CONFIG>") + set(MARIADB_PLUGINS_LOCATION "${BINARY_DIR}/libmariadb/RelWithDebInfo") + else() + set(MARIADB_SHARED_LIBRARY_LOCATION "${BINARY_DIR}/${MARIADB_SHARED_LIBRARY_NAME}") + set(MARIADB_SHARED_LIBRARY_COPY_LOCATION "${PROJECT_BINARY_DIR}") + set(MARIADB_PLUGINS_LOCATION "${BINARY_DIR}/libmariadb") + endif() + + set(MARIADB_INCLUDE_DIR "${CMAKE_SOURCE_DIR}/thirdparty/mariadb-connector-cpp/include/") + + add_custom_command(TARGET mariadb_connector_cpp POST_BUILD + COMMAND ${CMAKE_COMMAND} -E make_directory + ${BINARY_DIR}/mariadbcpp/plugin + ${MARIADB_SHARED_LIBRARY_COPY_LOCATION} + + COMMAND ${CMAKE_COMMAND} -E copy_if_different + ${MARIADB_SHARED_LIBRARY_LOCATION} + ${MARIADB_SHARED_LIBRARY_COPY_LOCATION} + + COMMAND ${CMAKE_COMMAND} -E copy_if_different + ${MARIADB_PLUGINS_LOCATION}/caching_sha2_password${MARIADB_PLUGIN_SUFFIX} + ${MARIADB_PLUGINS_LOCATION}/client_ed25519${MARIADB_PLUGIN_SUFFIX} + ${MARIADB_PLUGINS_LOCATION}/dialog${MARIADB_PLUGIN_SUFFIX} + ${MARIADB_PLUGINS_LOCATION}/mysql_clear_password${MARIADB_PLUGIN_SUFFIX} + ${MARIADB_PLUGINS_LOCATION}/sha256_password${MARIADB_PLUGIN_SUFFIX} + ${BINARY_DIR}/mariadbcpp/plugin) +endif() + +# Remove the CMakeLists.txt file from the tests folder for the maria-db-connector so we dont compile the tests. +if(EXISTS "${CMAKE_SOURCE_DIR}/thirdparty/mariadb-connector-cpp/test/CMakeLists.txt") + file(REMOVE "${CMAKE_SOURCE_DIR}/thirdparty/mariadb-connector-cpp/test/CMakeLists.txt") +endif() + +# Create mariadb connector library object +add_library(mariadbConnCpp SHARED IMPORTED GLOBAL) +set_property(TARGET mariadbConnCpp PROPERTY IMPORTED_LOCATION ${MARIADB_SHARED_LIBRARY_LOCATION}) + +if(WIN32) + set_property(TARGET mariadbConnCpp PROPERTY IMPORTED_IMPLIB ${MARIADB_IMPLIB_LOCATION}) +endif() + +# Add directories to include lists +target_include_directories(mariadbConnCpp INTERFACE ${MARIADB_INCLUDE_DIR}) +add_dependencies(mariadbConnCpp mariadb_connector_cpp) diff --git a/thirdparty/raknet/CMakeLists.txt b/thirdparty/raknet/CMakeLists.txt index 8d90f329..417e24dd 100644 --- a/thirdparty/raknet/CMakeLists.txt +++ b/thirdparty/raknet/CMakeLists.txt @@ -1,6 +1,4 @@ - - -PROJECT(RakNetStaticLib) +project(RakNetStaticLib) SET(RAKNET_SOURCES @@ -27,7 +25,7 @@ Source/FileList.cpp Source/RakMemoryOverride.cpp Source/ Source/FileListTransfer.cpp Source/RakNetCommandParser.cpp Source/TCPInterface.cpp Source/FileOperations.cpp Source/RakNetStatistics.cpp Source/TelnetTransport.cpp Source/_FindFirst.cpp Source/RakNetTransport.cpp Source/ThreadsafePacketLogger.cpp -Source/RakThread.cpp Source/SuperFastHash.cpp Source/Itoa.cpp +Source/RakThread.cpp Source/SuperFastHash.cpp Source/Itoa.cpp Source/HTTPConnection.cpp ) @@ -70,18 +68,25 @@ Source/DS_Tree.h Source/RakNetCommandParser.h S Source/DS_WeightedGraph.h Source/RakNetDefines.h Source/ThreadsafePacketLogger.h Source/EmailSender.h Source/RakNetStatistics.h Source/TransportInterface.h Source/EpochTimeToString.h Source/RakNetTransport.h Source/Types.h -Source/RakThread.h Source/SuperFastHash.h Source/Itoa.h -Source/HTTPConnection.h Kbhit.h\ +Source/RakThread.h Source/SuperFastHash.h Source/Itoa.h +Source/HTTPConnection.h Kbhit.h ) -ADD_LIBRARY(RakNet STATIC ${RAKNET_SOURCES}) +add_library(raknet STATIC ${RAKNET_SOURCES}) +target_compile_options(raknet PRIVATE + $<$<OR:$<CXX_COMPILER_ID:Clang>,$<CXX_COMPILER_ID:AppleClang>,$<CXX_COMPILER_ID:GNU>>: + -w> + $<$<CXX_COMPILER_ID:MSVC>: + /w>) +if(WIN32) + # Link Win Sockets 2 to RakNet + target_link_libraries(raknet ws2_32) +endif() -INSTALL(TARGETS RakNet +install(TARGETS raknet DESTINATION lib) -INSTALL(FILES ${RAKNET_HEADERS} +install(FILES ${RAKNET_HEADERS} DESTINATION include/raknet) - - From e4a15a0f2efcfc7a668e939fc361b30a3b7db5a9 Mon Sep 17 00:00:00 2001 From: Aaron Kimbrell <aronwk.aaron@gmail.com> Date: Thu, 18 Aug 2022 00:09:14 -0500 Subject: [PATCH 63/86] Add imagimeter visibility script (#738) --- dCommon/dCommonVars.h | 1 + dScripts/CMakeLists.txt | 1 + dScripts/CppScripts.cpp | 4 ++++ dScripts/NtImagimeterVisibility.cpp | 11 +++++++++++ dScripts/NtImagimeterVisibility.h | 7 +++++++ 5 files changed, 24 insertions(+) create mode 100644 dScripts/NtImagimeterVisibility.cpp create mode 100644 dScripts/NtImagimeterVisibility.h diff --git a/dCommon/dCommonVars.h b/dCommon/dCommonVars.h index 986f1c18..4c0e15fa 100644 --- a/dCommon/dCommonVars.h +++ b/dCommon/dCommonVars.h @@ -628,6 +628,7 @@ enum ePlayerFlags { GF_BINOC_IN_CROC_AREA = 1308, GF_BINOC_IN_JAIL_AREA = 1309, GF_BINOC_TELESCOPE_NEXT_TO_CAPTAIN_JACK = 1310, + NT_PLINTH_REBUILD = 1919, NT_FACTION_SPY_DUKE = 1974, NT_FACTION_SPY_OVERBUILD = 1976, NT_FACTION_SPY_HAEL = 1977, diff --git a/dScripts/CMakeLists.txt b/dScripts/CMakeLists.txt index 1fa177ba..50b41a14 100644 --- a/dScripts/CMakeLists.txt +++ b/dScripts/CMakeLists.txt @@ -177,6 +177,7 @@ set(DSCRIPT_SOURCES "ActivityManager.cpp" "NtFactionSpyServer.cpp" "NtHaelServer.cpp" "NtImagBeamBuffer.cpp" + "NtImagimeterVisibility.cpp" "NtOverbuildServer.cpp" "NtParadoxPanelServer.cpp" "NtParadoxTeleServer.cpp" diff --git a/dScripts/CppScripts.cpp b/dScripts/CppScripts.cpp index fbcb660a..de39fbb7 100644 --- a/dScripts/CppScripts.cpp +++ b/dScripts/CppScripts.cpp @@ -201,6 +201,7 @@ #include "ForceVolumeServer.h" #include "NtXRayServer.h" #include "NtSleepingGuard.h" +#include "NtImagimeterVisibility.h" // DLU Scripts #include "DLUVanityNPC.h" @@ -661,6 +662,9 @@ CppScripts::Script* CppScripts::GetScript(Entity* parent, const std::string& scr script = new NtXRayServer(); else if (scriptName == "scripts\\02_server\\Map\\NT\\L_NT_SLEEPING_GUARD.lua") script = new NtSleepingGuard(); + else if (scriptName == "scripts\\02_server\\Map\\NT\\L_NT_IMAGIMETER_VISIBILITY_SERVER.lua") { + script = new NTImagimeterVisibility(); + } //AM: else if (scriptName == "scripts\\02_server\\Map\\AM\\L_AM_CONSOLE_TELEPORT_SERVER.lua") diff --git a/dScripts/NtImagimeterVisibility.cpp b/dScripts/NtImagimeterVisibility.cpp new file mode 100644 index 00000000..c0f9bf51 --- /dev/null +++ b/dScripts/NtImagimeterVisibility.cpp @@ -0,0 +1,11 @@ +#include "NtImagimeterVisibility.h" +#include "GameMessages.h" +#include "Entity.h" +#include "Character.h" + +void NTImagimeterVisibility::OnRebuildComplete(Entity* self, Entity* target) { + auto* character = target->GetCharacter(); + if (character) character->SetPlayerFlag(ePlayerFlags::NT_PLINTH_REBUILD, true); + + GameMessages::SendNotifyClientObject(self->GetObjectID(), u"PlinthBuilt", 0, 0, LWOOBJID_EMPTY, "", target->GetSystemAddress()); +} diff --git a/dScripts/NtImagimeterVisibility.h b/dScripts/NtImagimeterVisibility.h new file mode 100644 index 00000000..04669d4b --- /dev/null +++ b/dScripts/NtImagimeterVisibility.h @@ -0,0 +1,7 @@ +#pragma once +#include "CppScripts.h" + +class NTImagimeterVisibility : public CppScripts::Script { +public: + void OnRebuildComplete(Entity* self, Entity* target) override; +}; From f8c1e2fb5298bc45a98c1a0f3deffd9562709b1d Mon Sep 17 00:00:00 2001 From: Aaron Kimbrell <aronwk.aaron@gmail.com> Date: Thu, 18 Aug 2022 15:33:32 -0500 Subject: [PATCH 64/86] Script for when archway rebuild is done (#739) --- dScripts/CMakeLists.txt | 1 + dScripts/CppScripts.cpp | 4 ++++ dScripts/GfArchway.cpp | 8 ++++++++ dScripts/GfArchway.h | 10 ++++++++++ 4 files changed, 23 insertions(+) create mode 100644 dScripts/GfArchway.cpp create mode 100644 dScripts/GfArchway.h diff --git a/dScripts/CMakeLists.txt b/dScripts/CMakeLists.txt index 50b41a14..4476ad7c 100644 --- a/dScripts/CMakeLists.txt +++ b/dScripts/CMakeLists.txt @@ -106,6 +106,7 @@ set(DSCRIPT_SOURCES "ActivityManager.cpp" "FvPassThroughWall.cpp" "FvRaceSmashEggImagineServer.cpp" "GfApeSmashingQB.cpp" + "GfArchway.cpp" "GfBanana.cpp" "GfBananaCluster.cpp" "GfCampfire.cpp" diff --git a/dScripts/CppScripts.cpp b/dScripts/CppScripts.cpp index de39fbb7..82cd2ebc 100644 --- a/dScripts/CppScripts.cpp +++ b/dScripts/CppScripts.cpp @@ -116,6 +116,7 @@ #include "BaseEnemyApe.h" #include "GfApeSmashingQB.h" #include "ZoneGfProperty.h" +#include "GfArchway.h" // SG Scripts #include "SGCannon.h" @@ -494,6 +495,9 @@ CppScripts::Script* CppScripts::GetScript(Entity* parent, const std::string& scr script = new GfApeSmashingQB(); else if (scriptName == "scripts\\zone\\PROPERTY\\GF\\L_ZONE_GF_PROPERTY.lua") script = new ZoneGfProperty(); + else if (scriptName == "scripts\\ai\\GF\\L_GF_ARCHWAY.lua") { + script = new GfArchway(); + } // SG else if (scriptName == "scripts\\ai\\MINIGAME\\SG_GF\\SERVER\\SG_CANNON.lua") diff --git a/dScripts/GfArchway.cpp b/dScripts/GfArchway.cpp new file mode 100644 index 00000000..429f62ae --- /dev/null +++ b/dScripts/GfArchway.cpp @@ -0,0 +1,8 @@ +#include "GfArchway.h" +#include "Entity.h" +#include "SkillComponent.h" + +void GfArchway::OnRebuildComplete(Entity* self, Entity* target) { + auto* skillComponent = target->GetComponent<SkillComponent>(); + if (skillComponent) skillComponent->CalculateBehavior(SHIELDING_SKILL, SHIELDING_BEHAVIOR, target->GetObjectID(), true); +} diff --git a/dScripts/GfArchway.h b/dScripts/GfArchway.h new file mode 100644 index 00000000..b60b2a9f --- /dev/null +++ b/dScripts/GfArchway.h @@ -0,0 +1,10 @@ +#pragma once +#include "CppScripts.h" + +class GfArchway : public CppScripts::Script { +public: + void OnRebuildComplete(Entity* self, Entity* target) override; +private: + const uint32_t SHIELDING_SKILL = 863; + const uint32_t SHIELDING_BEHAVIOR = 3788; +}; From c05562a227eab32f4b613f5f096f7098a416e1f1 Mon Sep 17 00:00:00 2001 From: David Markowitz <39972741+EmosewaMC@users.noreply.github.com> Date: Thu, 18 Aug 2022 19:23:42 -0700 Subject: [PATCH 65/86] Modularize CMakeLists for submodules (#736) * Use RecastNavigation CMakeLists * Use tinyxml2 CMakeLists * Use bcrypt CMakeLists * Move variable init to CMakeLists This has to be done here to prevent missing dependency errors. * General improvements Only link dynamic if on gnu use more thirdparty cmakes * Disable tinyxml2 testing --- CMakeLists.txt | 11 ++++-- dCommon/CMakeLists.txt | 2 +- dGame/CMakeLists.txt | 2 +- dNavigation/CMakeLists.txt | 2 +- dPhysics/CMakeLists.txt | 1 + dWorldServer/CMakeLists.txt | 2 +- thirdparty/CMakeLists.txt | 62 +++++++------------------------- thirdparty/SQLite/CMakeLists.txt | 14 ++++++++ 8 files changed, 40 insertions(+), 56 deletions(-) create mode 100644 thirdparty/SQLite/CMakeLists.txt diff --git a/CMakeLists.txt b/CMakeLists.txt index 6acca4d8..1a977a64 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -42,6 +42,12 @@ set(PROJECT_VERSION "${PROJECT_VERSION_MAJOR}.${PROJECT_VERSION_MINOR}.${PROJECT # Echo the version message(STATUS "Version: ${PROJECT_VERSION}") +# Disable demo, tests and examples for recastNavigation. Turn these to ON if you want to use them +# This has to be done here to prevent a rare build error due to missing dependencies on the initial generations. +set(RECASTNAVIGATION_DEMO OFF CACHE BOOL "" FORCE) +set(RECASTNAVIGATION_TESTS OFF CACHE BOOL "" FORCE) +set(RECASTNAVIGATION_EXAMPLES OFF CACHE BOOL "" FORCE) + # Compiler flags: # Disabled deprecated warnings as the MySQL includes have deprecated code in them. # Disabled misleading indentation as DL_LinkedList from RakNet has a weird indent. @@ -54,7 +60,7 @@ if(UNIX) else() set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=gnu++17 -O2 -Wuninitialized -D_GLIBCXX_USE_CXX11_ABI=0 -D_GLIBCXX_USE_CXX17_ABI=0 -static-libgcc -fPIC") endif() - if (__dynamic) + if (__dynamic AND CMAKE_CXX_COMPILER_ID STREQUAL "GNU") set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -rdynamic") endif() if (__ggdb) @@ -137,8 +143,7 @@ set(INCLUDED_DIRECTORIES "thirdparty/raknet/Source" "thirdparty/tinyxml2" - "thirdparty/recastnavigation/Recast/Include" - "thirdparty/recastnavigation/Detour/Include" + "thirdparty/recastnavigation" "thirdparty/SQLite" "thirdparty/cpplinq" ) diff --git a/dCommon/CMakeLists.txt b/dCommon/CMakeLists.txt index 7262bfef..028eb29f 100644 --- a/dCommon/CMakeLists.txt +++ b/dCommon/CMakeLists.txt @@ -19,7 +19,7 @@ include_directories(${PROJECT_SOURCE_DIR}/dCommon/) add_library(dCommon STATIC ${DCOMMON_SOURCES}) -target_link_libraries(dCommon libbcrypt) +target_link_libraries(dCommon bcrypt) if (UNIX) find_package(ZLIB REQUIRED) diff --git a/dGame/CMakeLists.txt b/dGame/CMakeLists.txt index 5acdba31..6b31802e 100644 --- a/dGame/CMakeLists.txt +++ b/dGame/CMakeLists.txt @@ -56,4 +56,4 @@ endforeach() add_library(dGame STATIC ${DGAME_SOURCES}) -target_link_libraries(dGame dDatabase) +target_link_libraries(dGame dDatabase Recast Detour) diff --git a/dNavigation/CMakeLists.txt b/dNavigation/CMakeLists.txt index 5891c77d..4c03d24b 100644 --- a/dNavigation/CMakeLists.txt +++ b/dNavigation/CMakeLists.txt @@ -7,4 +7,4 @@ foreach(file ${DNAVIGATIONS_DTERRAIN_SOURCES}) endforeach() add_library(dNavigation STATIC ${DNAVIGATION_SOURCES}) -target_link_libraries(dNavigation detour recast) +target_link_libraries(dNavigation Detour Recast) diff --git a/dPhysics/CMakeLists.txt b/dPhysics/CMakeLists.txt index 383393cc..5fe6adaa 100644 --- a/dPhysics/CMakeLists.txt +++ b/dPhysics/CMakeLists.txt @@ -7,3 +7,4 @@ set(DPHYSICS_SOURCES "dpCollisionChecks.cpp" "dpWorld.cpp") add_library(dPhysics STATIC ${DPHYSICS_SOURCES}) +target_link_libraries(dPhysics Recast Detour) diff --git a/dWorldServer/CMakeLists.txt b/dWorldServer/CMakeLists.txt index 05338960..fcf29838 100644 --- a/dWorldServer/CMakeLists.txt +++ b/dWorldServer/CMakeLists.txt @@ -3,4 +3,4 @@ set(DWORLDSERVER_SOURCES "ObjectIDManager.cpp" "WorldServer.cpp") add_executable(WorldServer ${DWORLDSERVER_SOURCES}) -target_link_libraries(WorldServer ${COMMON_LIBRARIES} dChatFilter dGame dZoneManager dPhysics detour recast tinyxml2 dNavigation) +target_link_libraries(WorldServer ${COMMON_LIBRARIES} dChatFilter dGame dZoneManager Detour Recast dPhysics tinyxml2 dNavigation) diff --git a/thirdparty/CMakeLists.txt b/thirdparty/CMakeLists.txt index c04e418e..c7a27510 100644 --- a/thirdparty/CMakeLists.txt +++ b/thirdparty/CMakeLists.txt @@ -1,63 +1,27 @@ # Source Code for recast -file( - GLOB SOURCES_RECAST - LIST_DIRECTORIES false - RELATIVE "${CMAKE_CURRENT_SOURCE_DIR}" - ${CMAKE_CURRENT_SOURCE_DIR}/recastnavigation/Recast/Source/*.cpp -) - -# Source Code for detour -file( - GLOB SOURCES_DETOUR - LIST_DIRECTORIES false - RELATIVE "${CMAKE_CURRENT_SOURCE_DIR}" - ${CMAKE_CURRENT_SOURCE_DIR}/recastnavigation/Detour/Source/*.cpp -) +add_subdirectory(recastnavigation) +# Turn off tinyxml2 testing +set(tinyxml2_BUILD_TESTING OFF) # Source Code for tinyxml2 -file( - GLOB SOURCES_TINYXML2 - LIST_DIRECTORIES false - RELATIVE "${CMAKE_CURRENT_SOURCE_DIR}" - ${CMAKE_CURRENT_SOURCE_DIR}/tinyxml2/tinyxml2.cpp -) +add_subdirectory(tinyxml2) # Source Code for libbcrypt -file( - GLOB SOURCES_LIBBCRYPT - LIST_DIRECTORIES false - RELATIVE "${CMAKE_CURRENT_SOURCE_DIR}" - ${CMAKE_CURRENT_SOURCE_DIR}/libbcrypt/*.c - ${CMAKE_CURRENT_SOURCE_DIR}/libbcrypt/src/*.c -) +# Disable warning about no project version. +set(CMAKE_POLICY_DEFAULT_CMP0048 NEW) +# Disable warning about the minimum version of cmake used for bcrypt being deprecated in the future +set(CMAKE_WARN_DEPRECATED OFF CACHE BOOL "" FORCE) -file( - GLOB SOURCES_SQLITE3 - LIST_DIRECTORIES false - RELATIVE "${CMAKE_CURRENT_SOURCE_DIR}" - ${CMAKE_CURRENT_SOURCE_DIR}/SQLite/*.cpp - ${CMAKE_CURRENT_SOURCE_DIR}/SQLite/*.c -) +add_subdirectory(libbcrypt) + +# Source code for sqlite +add_subdirectory(SQLite) # MariaDB C++ Connector include(CMakeMariaDBLists.txt) # Create our third party library objects add_subdirectory(raknet) -add_library(tinyxml2 ${SOURCES_TINYXML2}) -add_library(detour ${SOURCES_DETOUR}) -add_library(recast ${SOURCES_RECAST}) -add_library(libbcrypt ${SOURCES_LIBBCRYPT}) -add_library(sqlite3 ${SOURCES_SQLITE3}) - -if(UNIX) - # Add warning disable flags and link Unix libraries to sqlite3 - target_link_libraries(sqlite3 pthread dl m) - - # -Wno-unused-result -Wno-unknown-pragmas -fpermissive - target_compile_options(sqlite3 PRIVATE "-Wno-return-local-addr" "-Wno-maybe-uninitialized") - target_compile_options(libbcrypt PRIVATE "-Wno-implicit-function-declaration" "-Wno-int-conversion") -endif() # Download Backtrace if configured if(UNIX AND NOT APPLE) @@ -81,4 +45,4 @@ if(UNIX AND NOT APPLE) link_directories(${backtrace_SOURCE_DIR}/.libs/) include_directories(${backtrace_SOURCE_DIR}) endif() -endif() \ No newline at end of file +endif() diff --git a/thirdparty/SQLite/CMakeLists.txt b/thirdparty/SQLite/CMakeLists.txt new file mode 100644 index 00000000..aa7a6423 --- /dev/null +++ b/thirdparty/SQLite/CMakeLists.txt @@ -0,0 +1,14 @@ +set (SQLITE3_SOURCES + "CppSQLite3.cpp" + "sqlite3.c" +) + +add_library (sqlite3 ${SQLITE3_SOURCES}) + +if(UNIX) + # Add warning disable flags and link Unix libraries to sqlite3 + target_link_libraries(sqlite3 pthread dl m) + + # -Wno-unused-result -Wno-unknown-pragmas -fpermissive + target_compile_options(sqlite3 PRIVATE "-Wno-return-local-addr" "-Wno-maybe-uninitialized") +endif() From ceb374591fbe25eb21ae3db1029e080983d7f806 Mon Sep 17 00:00:00 2001 From: David Markowitz <39972741+EmosewaMC@users.noreply.github.com> Date: Thu, 18 Aug 2022 19:42:52 -0700 Subject: [PATCH 66/86] Move mailbox closing to its script (#740) --- dGame/dGameMessages/GameMessages.cpp | 6 ------ dScripts/MailBoxServer.cpp | 8 ++++++++ dScripts/MailBoxServer.h | 1 + 3 files changed, 9 insertions(+), 6 deletions(-) diff --git a/dGame/dGameMessages/GameMessages.cpp b/dGame/dGameMessages/GameMessages.cpp index 105bb526..1645afc8 100644 --- a/dGame/dGameMessages/GameMessages.cpp +++ b/dGame/dGameMessages/GameMessages.cpp @@ -4745,12 +4745,6 @@ void GameMessages::HandleFireEventServerSide(RakNet::BitStream* inStream, Entity return; } - if (args == u"toggleMail") { - AMFArrayValue args; - args.InsertValue("visible", new AMFFalseValue()); - GameMessages::SendUIMessageServerToSingleClient(entity, sysAddr, "ToggleMail", &args); - } - // This should probably get it's own "ServerEvents" system or something at some point if (args == u"ZonePlayer") { // Should probably check to make sure they're using a launcher at some point before someone makes a hack that lets you testmap diff --git a/dScripts/MailBoxServer.cpp b/dScripts/MailBoxServer.cpp index 81156835..c2534f3e 100644 --- a/dScripts/MailBoxServer.cpp +++ b/dScripts/MailBoxServer.cpp @@ -9,3 +9,11 @@ void MailBoxServer::OnUse(Entity* self, Entity* user) { args.InsertValue("state", value); GameMessages::SendUIMessageServerToSingleClient(user, user->GetSystemAddress(), "pushGameState", &args); } + +void MailBoxServer::OnFireEventServerSide(Entity* self, Entity* sender, std::string args, int32_t param1, int32_t param2, int32_t param3) { + if (args == "toggleMail") { + AMFArrayValue args; + args.InsertValue("visible", new AMFFalseValue()); + GameMessages::SendUIMessageServerToSingleClient(sender, sender->GetSystemAddress(), "ToggleMail", &args); + } +} diff --git a/dScripts/MailBoxServer.h b/dScripts/MailBoxServer.h index f459e8b3..9ada6a0e 100644 --- a/dScripts/MailBoxServer.h +++ b/dScripts/MailBoxServer.h @@ -12,4 +12,5 @@ public: * @param user The user that interacted with this Entity. */ void OnUse(Entity* self, Entity* user) override; + void OnFireEventServerSide(Entity* self, Entity* sender, std::string args, int32_t param1, int32_t param2, int32_t param3) override; }; From e707207ffafcd07682e040a7677c0def01e61d34 Mon Sep 17 00:00:00 2001 From: Aaron Kimbrell <aronwk.aaron@gmail.com> Date: Thu, 25 Aug 2022 15:50:13 -0500 Subject: [PATCH 67/86] Add FV Geyser script (#748) * Add FV Geyser script * remove uneeded include * const --- dScripts/CMakeLists.txt | 1 + dScripts/CppScripts.cpp | 4 ++++ dScripts/FvMaelstromGeyser.cpp | 18 ++++++++++++++++++ dScripts/FvMaelstromGeyser.h | 18 ++++++++++++++++++ 4 files changed, 41 insertions(+) create mode 100644 dScripts/FvMaelstromGeyser.cpp create mode 100644 dScripts/FvMaelstromGeyser.h diff --git a/dScripts/CMakeLists.txt b/dScripts/CMakeLists.txt index 4476ad7c..9bc088cb 100644 --- a/dScripts/CMakeLists.txt +++ b/dScripts/CMakeLists.txt @@ -99,6 +99,7 @@ set(DSCRIPT_SOURCES "ActivityManager.cpp" "FvFreeGfNinjas.cpp" "FvHorsemenTrigger.cpp" "FvMaelstromCavalry.cpp" + "FvMaelstromGeyser.cpp" "FvMaelstromDragon.cpp" "FvNinjaGuard.cpp" "FvPandaServer.cpp" diff --git a/dScripts/CppScripts.cpp b/dScripts/CppScripts.cpp index 82cd2ebc..5f10a2a5 100644 --- a/dScripts/CppScripts.cpp +++ b/dScripts/CppScripts.cpp @@ -147,6 +147,7 @@ #include "FvPassThroughWall.h" #include "FvBounceOverWall.h" #include "FvFong.h" +#include "FvMaelstromGeyser.h" // FB Scripts #include "AgJetEffectServer.h" @@ -576,6 +577,9 @@ CppScripts::Script* CppScripts::GetScript(Entity* parent, const std::string& scr script = new FvBounceOverWall(); else if (scriptName == "scripts\\02_server\\Map\\FV\\L_NPC_FONG.lua") script = new FvFong(); + else if (scriptName == "scripts\\ai\\FV\\L_FV_MAELSTROM_GEYSER.lua") { + script = new FvMaelstromGeyser(); + } //Misc: if (scriptName == "scripts\\02_server\\Map\\General\\L_EXPLODING_ASSET.lua") diff --git a/dScripts/FvMaelstromGeyser.cpp b/dScripts/FvMaelstromGeyser.cpp new file mode 100644 index 00000000..66aa43dc --- /dev/null +++ b/dScripts/FvMaelstromGeyser.cpp @@ -0,0 +1,18 @@ +#include "FvMaelstromGeyser.h" +#include "SkillComponent.h" + +void FvMaelstromGeyser::OnStartup(Entity* self) { + self->AddTimer(m_StartSkillTimerName, m_StartSkillTimerTime); + self->AddTimer(m_KillSelfTimerName, m_KillSelfTimerTime); +} + +void FvMaelstromGeyser::OnTimerDone(Entity* self, std::string timerName) { + if (timerName == m_StartSkillTimerName) { + auto* skillComponent = self->GetComponent<SkillComponent>(); + skillComponent->CalculateBehavior(m_SkillID, m_BehaviorID, LWOOBJID_EMPTY, true); + } + if (timerName == m_KillSelfTimerName) { + self->Smash(LWOOBJID_EMPTY, eKillType::SILENT); + } +} + diff --git a/dScripts/FvMaelstromGeyser.h b/dScripts/FvMaelstromGeyser.h new file mode 100644 index 00000000..245eb56e --- /dev/null +++ b/dScripts/FvMaelstromGeyser.h @@ -0,0 +1,18 @@ +#pragma once +#include "CppScripts.h" + +class FvMaelstromGeyser final : public CppScripts::Script +{ +public: + void OnStartup(Entity* self) override; + void OnTimerDone(Entity* self, std::string timerName) override; + + +private: + const std::string m_StartSkillTimerName = "startSkill"; + const float m_StartSkillTimerTime = 2.0; + const std::string m_KillSelfTimerName = "killSelf"; + const float m_KillSelfTimerTime = 5.5; + const uint32_t m_SkillID = 831; + const uint32_t m_BehaviorID = 15500; +}; From 47f0830483ac1c82cee2ea74b20de7f8b3d7f8f4 Mon Sep 17 00:00:00 2001 From: Aaron Kimbrell <aronwk.aaron@gmail.com> Date: Thu, 25 Aug 2022 15:51:22 -0500 Subject: [PATCH 68/86] Add GF geyser script (#749) * Add GF geyser script * remove uneeeded include * const --- dScripts/CMakeLists.txt | 1 + dScripts/CppScripts.cpp | 6 ++++-- dScripts/GfMaelstromGeyser.cpp | 18 ++++++++++++++++++ dScripts/GfMaelstromGeyser.h | 17 +++++++++++++++++ 4 files changed, 40 insertions(+), 2 deletions(-) create mode 100644 dScripts/GfMaelstromGeyser.cpp create mode 100644 dScripts/GfMaelstromGeyser.h diff --git a/dScripts/CMakeLists.txt b/dScripts/CMakeLists.txt index 9bc088cb..47400891 100644 --- a/dScripts/CMakeLists.txt +++ b/dScripts/CMakeLists.txt @@ -114,6 +114,7 @@ set(DSCRIPT_SOURCES "ActivityManager.cpp" "GfCaptainsCannon.cpp" "GfJailkeepMission.cpp" "GfJailWalls.cpp" + "GfMaelstromGeyser.cpp" "GfOrgan.cpp" "GfTikiTorch.cpp" "GrowingFlower.cpp" diff --git a/dScripts/CppScripts.cpp b/dScripts/CppScripts.cpp index 5f10a2a5..f8481de1 100644 --- a/dScripts/CppScripts.cpp +++ b/dScripts/CppScripts.cpp @@ -117,6 +117,7 @@ #include "GfApeSmashingQB.h" #include "ZoneGfProperty.h" #include "GfArchway.h" +#include "GfMaelstromGeyser.h" // SG Scripts #include "SGCannon.h" @@ -496,9 +497,10 @@ CppScripts::Script* CppScripts::GetScript(Entity* parent, const std::string& scr script = new GfApeSmashingQB(); else if (scriptName == "scripts\\zone\\PROPERTY\\GF\\L_ZONE_GF_PROPERTY.lua") script = new ZoneGfProperty(); - else if (scriptName == "scripts\\ai\\GF\\L_GF_ARCHWAY.lua") { + else if (scriptName == "scripts\\ai\\GF\\L_GF_ARCHWAY.lua") script = new GfArchway(); - } + else if (scriptName == "scripts\\ai\\GF\\L_GF_MAELSTROM_GEYSER.lua") + script = new GfMaelstromGeyser(); // SG else if (scriptName == "scripts\\ai\\MINIGAME\\SG_GF\\SERVER\\SG_CANNON.lua") diff --git a/dScripts/GfMaelstromGeyser.cpp b/dScripts/GfMaelstromGeyser.cpp new file mode 100644 index 00000000..825307a7 --- /dev/null +++ b/dScripts/GfMaelstromGeyser.cpp @@ -0,0 +1,18 @@ +#include "GfMaelstromGeyser.h" +#include "SkillComponent.h" + +void GfMaelstromGeyser::OnStartup(Entity* self) { + self->AddTimer(m_StartSkillTimerName, m_StartSkillTimerTime); + self->AddTimer(m_KillSelfTimerName, m_KillSelfTimerTime); +} + +void GfMaelstromGeyser::OnTimerDone(Entity* self, std::string timerName) { + if (timerName == m_StartSkillTimerName) { + auto* skillComponent = self->GetComponent<SkillComponent>(); + skillComponent->CalculateBehavior(m_SkillID, m_BehaviorID, LWOOBJID_EMPTY, true); + } + if (timerName == m_KillSelfTimerName) { + self->Smash(LWOOBJID_EMPTY, eKillType::SILENT); + } +} + diff --git a/dScripts/GfMaelstromGeyser.h b/dScripts/GfMaelstromGeyser.h new file mode 100644 index 00000000..60e42798 --- /dev/null +++ b/dScripts/GfMaelstromGeyser.h @@ -0,0 +1,17 @@ +#pragma once +#include "CppScripts.h" + +class GfMaelstromGeyser final : public CppScripts::Script +{ +public: + void OnStartup(Entity* self) override; + void OnTimerDone(Entity* self, std::string timerName) override; + +private: + const std::string m_StartSkillTimerName = "startSkill"; + const float m_StartSkillTimerTime = 2.0; + const std::string m_KillSelfTimerName = "killSelf"; + const float m_KillSelfTimerTime = 7.5; + const uint32_t m_SkillID = 607; + const uint32_t m_BehaviorID = 10500; +}; From bc132487e983a45e5374c0a3ce6c0c7670f21819 Mon Sep 17 00:00:00 2001 From: Demetri Van Sickle <demetriv.s.7@gmail.com> Date: Thu, 25 Aug 2022 14:16:20 -0700 Subject: [PATCH 69/86] Updated README (Formatting and flow) (#744) * Updated flow of database section * Changed bolded headers to actual headers Will now allow you to link to them * Updated Linux build command to match build script * Updated database wording --- README.md | 37 ++++++++++++++++++++----------------- 1 file changed, 20 insertions(+), 17 deletions(-) diff --git a/README.md b/README.md index 321e1b36..de20e7ad 100644 --- a/README.md +++ b/README.md @@ -27,11 +27,11 @@ Darkflame Universe is a server emulator and does not distribute any LEGO® Unive Development of the latest iteration of Darkflame Universe has been done primarily in a Unix-like environment and is where it has been tested and designed for deployment. It is therefore highly recommended that Darkflame Universe be built and deployed using a Unix-like environment for the most streamlined experience. ### Prerequisites -**Clone the repository** +#### Clone the repository ```bash git clone --recursive https://github.com/DarkflameUniverse/DarkflameServer ``` -**Python** +#### Python Some tools utilized to streamline the setup process require Python 3, make sure you have it installed. @@ -52,7 +52,7 @@ Make sure packages like `gcc`, `cmake`, and `zlib` are installed. Depending on t CMake must be version 3.14 or higher! -**Build the repository** +#### Build the repository You can either run `build.sh` when in the root folder of the repository: @@ -70,8 +70,8 @@ cd build # Run CMake to generate make files cmake .. -# Run make to build the project. To build utilizing multiple cores, append `-j` and the amount of cores to utilize, for example `make -j8` -make +# To build utilizing multiple cores, append `-j` and the amount of cores to utilize, for example `cmake --build . --config Release -j8' +cmake --build . --config Release ``` ### MacOS builds @@ -93,7 +93,7 @@ cmake --build . --config Release ### Windows builds (native) Ensure that you have either the [MSVC](https://visualstudio.microsoft.com/vs/) or the [Clang](https://github.com/llvm/llvm-project/releases/) (recommended) compiler installed. You will also need to install [CMake](https://cmake.org/download/). Currently on native Windows the server will only work in Release mode. -**Build the repository** +#### Build the repository ```batch :: Create the build directory mkdir build @@ -105,7 +105,7 @@ cmake .. :: Run CMake with build flag to build cmake --build . --config Release ``` -**Windows for ARM** has not been tested but should build by doing the following +#### Windows for ARM has not been tested but should build by doing the following ```batch :: Create the build directory mkdir build @@ -121,13 +121,13 @@ cmake --build . --config Release ### Windows builds (WSL) This section will go through how to install [WSL](https://docs.microsoft.com/en-us/windows/wsl/install) and building in a Linux environment under Windows. WSL requires Windows 10 version 2004 and higher (Build 19041 and higher) or Windows 11. -**Open the Command Prompt application with Administrator permissions and run the following:** +#### Open the Command Prompt application with Administrator permissions and run the following: ```bash # Installing Windows Subsystem for Linux wsl --install ``` -**Open the Ubuntu application and run the following:** +#### Open the Ubuntu application and run the following: ```bash # Make sure the install is up to date apt update && apt upgrade @@ -159,7 +159,7 @@ now follow the build section for your system ### Resources -**LEGO® Universe 1.10.64** +#### LEGO® Universe 1.10.64 This repository does not distribute any LEGO® Universe files. A full install of LEGO® Universe version 1.10.64 (latest) is required to finish setting up Darkflame Universe. @@ -182,20 +182,20 @@ shasum -a 256 <file> certutil -hashfile <file> SHA256 ``` -**Unpacking the client** +#### Unpacking the client * Clone lcdr's utilities repository [here](https://github.com/lcdr/utils) * Use `pkextractor.pyw` to unpack the client files if they are not already unpacked -**Setup resource directory** +#### Setup resource directory * In the `build` directory create a `res` directory if it does not already exist. * Copy over or create symlinks from `macros`, `BrickModels`, `chatplus_en_us.txt`, `names`, and `maps` in your client `res` directory to the server `build/res` directory * Unzip the navmeshes [here](./resources/navmeshes.zip) and place them in `build/res/maps/navmeshes` -**Setup locale** +#### Setup locale * In the `build` directory create a `locale` directory if it does not already exist * Copy over or create symlinks from `locale.xml` in your client `locale` directory to the `build/locale` directory -**Client database** +#### Client database * Use `fdb_to_sqlite.py` in lcdr's utilities on `res/cdclient.fdb` in the unpacked client to convert the client database to `cdclient.sqlite` * Move and rename `cdclient.sqlite` into `build/res/CDServer.sqlite` * Run each SQL file in the order at which they appear [here](migrations/cdserver/) on the SQLite database @@ -205,13 +205,16 @@ Darkflame Universe utilizes a MySQL/MariaDB database for account and character i Initial setup can vary drastically based on which operating system or distribution you are running; there are instructions out there for most setups, follow those and come back here when you have a database up and running. * Create a database for Darkflame Universe to use -* Use the command `./MasterServer -m` to automatically run them. -**Configuration** +#### Configuration After the server has been built there should be four `ini` files in the build director: `authconfig.ini`, `chatconfig.ini`, `masterconfig.ini`, and `worldconfig.ini`. Go through them and fill in the database credentials and configure other settings if necessary. -**Verify** +#### Setup and Migrations + +Use the command `./MasterServer -m` to setup the tables in the database. The first time this command is run on a database, the tables will be up to date with the most recent version. To update your database tables, run this command again. Multiple invocations will not affect any functionality. + +#### Verify Your build directory should now look like this: * AuthServer From 500b7885e25146e6033ca2c3acb6447626162e75 Mon Sep 17 00:00:00 2001 From: Aaron Kimbrell <aronwk.aaron@gmail.com> Date: Thu, 25 Aug 2022 21:09:08 -0500 Subject: [PATCH 70/86] Add pirate rep script (#751) * Add pirate rep script * fix formattimg --- dScripts/CMakeLists.txt | 1 + dScripts/CppScripts.cpp | 3 +++ dScripts/PirateRep.cpp | 11 +++++++++++ dScripts/PirateRep.h | 9 +++++++++ 4 files changed, 24 insertions(+) create mode 100644 dScripts/PirateRep.cpp create mode 100644 dScripts/PirateRep.h diff --git a/dScripts/CMakeLists.txt b/dScripts/CMakeLists.txt index 47400891..13b14ad8 100644 --- a/dScripts/CMakeLists.txt +++ b/dScripts/CMakeLists.txt @@ -195,6 +195,7 @@ set(DSCRIPT_SOURCES "ActivityManager.cpp" "PetDigServer.cpp" "PetFromDigServer.cpp" "PetFromObjectServer.cpp" + "PirateRep.cpp" "PropertyBankInteract.cpp" "PropertyDeathPlane.cpp" "PropertyDevice.cpp" diff --git a/dScripts/CppScripts.cpp b/dScripts/CppScripts.cpp index f8481de1..44b79d9b 100644 --- a/dScripts/CppScripts.cpp +++ b/dScripts/CppScripts.cpp @@ -118,6 +118,7 @@ #include "ZoneGfProperty.h" #include "GfArchway.h" #include "GfMaelstromGeyser.h" +#include "PirateRep.h" // SG Scripts #include "SGCannon.h" @@ -501,6 +502,8 @@ CppScripts::Script* CppScripts::GetScript(Entity* parent, const std::string& scr script = new GfArchway(); else if (scriptName == "scripts\\ai\\GF\\L_GF_MAELSTROM_GEYSER.lua") script = new GfMaelstromGeyser(); + else if (scriptName == "scripts\\ai\\GF\\L_PIRATE_REP.lua") + script = new PirateRep(); // SG else if (scriptName == "scripts\\ai\\MINIGAME\\SG_GF\\SERVER\\SG_CANNON.lua") diff --git a/dScripts/PirateRep.cpp b/dScripts/PirateRep.cpp new file mode 100644 index 00000000..eb4cf510 --- /dev/null +++ b/dScripts/PirateRep.cpp @@ -0,0 +1,11 @@ +#include "PirateRep.h" +#include "Character.h" + +void PirateRep::OnMissionDialogueOK(Entity* self, Entity* target, int missionID, MissionState missionState) { + if (missionID == m_PirateRepMissionID && missionState >= MissionState::MISSION_STATE_READY_TO_COMPLETE) { + auto* character = target->GetCharacter(); + if (character) { + character->SetPlayerFlag(ePlayerFlags::GF_PIRATE_REP, true); + } + } +} diff --git a/dScripts/PirateRep.h b/dScripts/PirateRep.h new file mode 100644 index 00000000..8fc82c5e --- /dev/null +++ b/dScripts/PirateRep.h @@ -0,0 +1,9 @@ +#pragma once +#include "CppScripts.h" + +class PirateRep : public CppScripts::Script { +public: + void OnMissionDialogueOK(Entity* self, Entity* target, int missionID, MissionState missionState) override; +private: + const int m_PirateRepMissionID = 301; +}; From b70e7334e87800330ab549a4e8f653e1a878a594 Mon Sep 17 00:00:00 2001 From: Aaron Kimbrell <aronwk.aaron@gmail.com> Date: Fri, 26 Aug 2022 22:58:41 -0500 Subject: [PATCH 71/86] Parrot crash script to become a sneaky ninja and steal the pirate's booty (#752) --- dScripts/CMakeLists.txt | 1 + dScripts/CppScripts.cpp | 3 +++ dScripts/GfParrotCrash.cpp | 13 +++++++++++++ dScripts/GfParrotCrash.h | 13 +++++++++++++ 4 files changed, 30 insertions(+) create mode 100644 dScripts/GfParrotCrash.cpp create mode 100644 dScripts/GfParrotCrash.h diff --git a/dScripts/CMakeLists.txt b/dScripts/CMakeLists.txt index 13b14ad8..440ca69f 100644 --- a/dScripts/CMakeLists.txt +++ b/dScripts/CMakeLists.txt @@ -116,6 +116,7 @@ set(DSCRIPT_SOURCES "ActivityManager.cpp" "GfJailWalls.cpp" "GfMaelstromGeyser.cpp" "GfOrgan.cpp" + "GfParrotCrash.cpp" "GfTikiTorch.cpp" "GrowingFlower.cpp" "HydrantBroken.cpp" diff --git a/dScripts/CppScripts.cpp b/dScripts/CppScripts.cpp index 44b79d9b..37a0ecf7 100644 --- a/dScripts/CppScripts.cpp +++ b/dScripts/CppScripts.cpp @@ -119,6 +119,7 @@ #include "GfArchway.h" #include "GfMaelstromGeyser.h" #include "PirateRep.h" +#include "GfParrotCrash.h" // SG Scripts #include "SGCannon.h" @@ -504,6 +505,8 @@ CppScripts::Script* CppScripts::GetScript(Entity* parent, const std::string& scr script = new GfMaelstromGeyser(); else if (scriptName == "scripts\\ai\\GF\\L_PIRATE_REP.lua") script = new PirateRep(); + else if (scriptName == "scripts\\ai\\GF\\L_GF_PARROT_CRASH.lua") + script = new GfParrotCrash(); // SG else if (scriptName == "scripts\\ai\\MINIGAME\\SG_GF\\SERVER\\SG_CANNON.lua") diff --git a/dScripts/GfParrotCrash.cpp b/dScripts/GfParrotCrash.cpp new file mode 100644 index 00000000..6b76a51d --- /dev/null +++ b/dScripts/GfParrotCrash.cpp @@ -0,0 +1,13 @@ +#include "GfParrotCrash.h" +#include "SkillComponent.h" +#include "Entity.h" +#include "dLogger.h" + +void GfParrotCrash::OnFireEventServerSide(Entity* self, Entity* sender, std::string args, int32_t param1, int32_t param2, int32_t param3) { + auto* skillComponent = self->GetComponent<SkillComponent>(); + if (args == "Slow") { + skillComponent->CalculateBehavior(m_SlowSkillID, m_SlowBehaviorID, sender->GetObjectID()); + } else if (args == "Unslow") { + skillComponent->CalculateBehavior(m_UnslowSkillID, m_UnslowBehaviorID, sender->GetObjectID()); + } +} diff --git a/dScripts/GfParrotCrash.h b/dScripts/GfParrotCrash.h new file mode 100644 index 00000000..fe70a16c --- /dev/null +++ b/dScripts/GfParrotCrash.h @@ -0,0 +1,13 @@ +#pragma once +#include "CppScripts.h" + +class GfParrotCrash : public CppScripts::Script { +public: + void OnFireEventServerSide(Entity* self, Entity* sender, std::string args, int32_t param1, int32_t param2, int32_t param3) override; +private: + const uint32_t m_SlowSkillID = 795; + const uint32_t m_SlowBehaviorID = 14214; + const uint32_t m_UnslowSkillID = 796; + const uint32_t m_UnslowBehaviorID = 14215; +}; + From 3b75ecc0b431c840f3776ed0d5a936ee6ea94238 Mon Sep 17 00:00:00 2001 From: Aaron Kimbrell <aronwk.aaron@gmail.com> Date: Sat, 27 Aug 2022 21:48:03 -0500 Subject: [PATCH 72/86] Add script to playfx on canisters before consoles are active (#754) * Add script to playfx on canisters before consoles are active * remove debug stuff --- dScripts/CMakeLists.txt | 1 + dScripts/CppScripts.cpp | 3 +++ dScripts/FvFacilityPipes.cpp | 10 ++++++++++ dScripts/FvFacilityPipes.h | 15 +++++++++++++++ 4 files changed, 29 insertions(+) create mode 100644 dScripts/FvFacilityPipes.cpp create mode 100644 dScripts/FvFacilityPipes.h diff --git a/dScripts/CMakeLists.txt b/dScripts/CMakeLists.txt index 440ca69f..ac35b76d 100644 --- a/dScripts/CMakeLists.txt +++ b/dScripts/CMakeLists.txt @@ -94,6 +94,7 @@ set(DSCRIPT_SOURCES "ActivityManager.cpp" "FvConsoleRightQuickbuild.cpp" "FvDragonSmashingGolemQb.cpp" "FvFacilityBrick.cpp" + "FvFacilityPipes.cpp" "FvFlyingCreviceDragon.cpp" "FvFong.cpp" "FvFreeGfNinjas.cpp" diff --git a/dScripts/CppScripts.cpp b/dScripts/CppScripts.cpp index 37a0ecf7..73c50d62 100644 --- a/dScripts/CppScripts.cpp +++ b/dScripts/CppScripts.cpp @@ -144,6 +144,7 @@ #include "FvConsoleLeftQuickbuild.h" #include "FvConsoleRightQuickbuild.h" #include "FvFacilityBrick.h" +#include "FvFacilityPipes.h" #include "ImgBrickConsoleQB.h" #include "ActParadoxPipeFix.h" #include "FvNinjaGuard.h" @@ -573,6 +574,8 @@ CppScripts::Script* CppScripts::GetScript(Entity* parent, const std::string& scr script = new FvConsoleRightQuickbuild(); else if (scriptName == "scripts\\ai\\FV\\L_FV_FACILITY_BRICK.lua") script = new FvFacilityBrick(); + else if (scriptName == "scripts\\ai\\FV\\L_FV_FACILITY_PIPES.lua") + script = new FvFacilityPipes(); else if (scriptName == "scripts\\02_server\\Map\\FV\\L_IMG_BRICK_CONSOLE_QB.lua") script = new ImgBrickConsoleQB(); else if (scriptName == "scripts\\ai\\FV\\L_ACT_PARADOX_PIPE_FIX.lua") diff --git a/dScripts/FvFacilityPipes.cpp b/dScripts/FvFacilityPipes.cpp new file mode 100644 index 00000000..dd35ffe1 --- /dev/null +++ b/dScripts/FvFacilityPipes.cpp @@ -0,0 +1,10 @@ +#include "FvFacilityPipes.h" +#include "GameMessages.h" + +void FvFacilityPipes::OnFireEventServerSide(Entity* self, Entity* sender, std::string args, int32_t param1, int32_t param2, int32_t param3) { + if (args == "startFX") { + GameMessages::SendPlayFXEffect(self->GetObjectID(), m_LeftPipeEffectID, m_EffectType, m_LeftPipeEffectName); + GameMessages::SendPlayFXEffect(self->GetObjectID(), m_RightPipeEffectID, m_EffectType, m_RightPipeEffectName); + GameMessages::SendPlayFXEffect(self->GetObjectID(), m_ImaginationCanisterEffectID, m_EffectType, m_ImaginationCanisterEffectName); + } +} diff --git a/dScripts/FvFacilityPipes.h b/dScripts/FvFacilityPipes.h new file mode 100644 index 00000000..8a33976c --- /dev/null +++ b/dScripts/FvFacilityPipes.h @@ -0,0 +1,15 @@ +#pragma once +#include "CppScripts.h" + +class FvFacilityPipes : public CppScripts::Script { +public: + void OnFireEventServerSide(Entity* self, Entity* sender, std::string args, int32_t param1, int32_t param2, int32_t param3) override; +private: + const std::u16string m_EffectType = u"create"; + const std::string m_LeftPipeEffectName = "LeftPipeOff"; + const int32_t m_LeftPipeEffectID = 2774; + const std::string m_RightPipeEffectName = "RightPipeOff"; + const int32_t m_RightPipeEffectID = 2777; + const std::string m_ImaginationCanisterEffectName = "imagination_canister"; + const int32_t m_ImaginationCanisterEffectID = 2750; +}; From e3077aa4102e5e0254adac7a47b5c3e5f5a6b6f7 Mon Sep 17 00:00:00 2001 From: David Markowitz <39972741+EmosewaMC@users.noreply.github.com> Date: Thu, 1 Sep 2022 19:24:00 -0700 Subject: [PATCH 73/86] Fix Windows not working due to libbcrypt not working on Ninja (#765) --- thirdparty/CMakeLists.txt | 16 +++++++++------- 1 file changed, 9 insertions(+), 7 deletions(-) diff --git a/thirdparty/CMakeLists.txt b/thirdparty/CMakeLists.txt index c7a27510..978c5532 100644 --- a/thirdparty/CMakeLists.txt +++ b/thirdparty/CMakeLists.txt @@ -6,13 +6,15 @@ set(tinyxml2_BUILD_TESTING OFF) # Source Code for tinyxml2 add_subdirectory(tinyxml2) -# Source Code for libbcrypt -# Disable warning about no project version. -set(CMAKE_POLICY_DEFAULT_CMP0048 NEW) -# Disable warning about the minimum version of cmake used for bcrypt being deprecated in the future -set(CMAKE_WARN_DEPRECATED OFF CACHE BOOL "" FORCE) - -add_subdirectory(libbcrypt) +# Source Code for libbcrypt. Uses a file glob instead to get around Windows build issues. +file( + GLOB SOURCES_LIBBCRYPT + LIST_DIRECTORIES false + RELATIVE "${CMAKE_CURRENT_SOURCE_DIR}" + ${CMAKE_CURRENT_SOURCE_DIR}/libbcrypt/*.c + ${CMAKE_CURRENT_SOURCE_DIR}/libbcrypt/src/*.c +) +add_library(bcrypt ${SOURCES_LIBBCRYPT}) # Source code for sqlite add_subdirectory(SQLite) From 1af3e59348c34a74902bafa929a737c7bb6d3cda Mon Sep 17 00:00:00 2001 From: Aaron Kimbrell <aronwk.aaron@gmail.com> Date: Thu, 1 Sep 2022 21:44:26 -0500 Subject: [PATCH 74/86] Scripts for the AG sentinel camp QB wall (#761) * Scripts for the AG sentinel camp QB wall * use lookat * Address feedback * Fix stromling spawner * fix aggro and remove logs Co-authored-by: Jett <55758076+Jettford@users.noreply.github.com> --- dScripts/AgQbWall.cpp | 15 +++++ dScripts/AgQbWall.h | 7 +++ dScripts/CMakeLists.txt | 2 + dScripts/CppScripts.cpp | 6 ++ dScripts/QbSpawner.cpp | 136 ++++++++++++++++++++++++++++++++++++++++ dScripts/QbSpawner.h | 17 +++++ 6 files changed, 183 insertions(+) create mode 100644 dScripts/AgQbWall.cpp create mode 100644 dScripts/AgQbWall.h create mode 100644 dScripts/QbSpawner.cpp create mode 100644 dScripts/QbSpawner.h diff --git a/dScripts/AgQbWall.cpp b/dScripts/AgQbWall.cpp new file mode 100644 index 00000000..d6222419 --- /dev/null +++ b/dScripts/AgQbWall.cpp @@ -0,0 +1,15 @@ +#include "AgQbWall.h" + +void AgQbWall::OnRebuildComplete(Entity* self, Entity* player) { + self->SetVar(u"player", player->GetObjectID()); + auto targetWallSpawners = GeneralUtils::UTF16ToWTF8(self->GetVar<std::u16string>(u"spawner")); + if (targetWallSpawners != "") { + auto groupObjs = EntityManager::Instance()->GetEntitiesInGroup(targetWallSpawners); + for (auto* obj : groupObjs) { + if (obj) { + obj->SetVar(u"player", player->GetObjectID()); + obj->OnFireEventServerSide(self, "spawnMobs"); + } + } + } +} diff --git a/dScripts/AgQbWall.h b/dScripts/AgQbWall.h new file mode 100644 index 00000000..93187e0e --- /dev/null +++ b/dScripts/AgQbWall.h @@ -0,0 +1,7 @@ +#pragma once +#include "CppScripts.h" + +class AgQbWall : public CppScripts::Script { +public: + void OnRebuildComplete(Entity* self, Entity* player) override; +}; diff --git a/dScripts/CMakeLists.txt b/dScripts/CMakeLists.txt index ac35b76d..66e3b65b 100644 --- a/dScripts/CMakeLists.txt +++ b/dScripts/CMakeLists.txt @@ -21,6 +21,7 @@ set(DSCRIPT_SOURCES "ActivityManager.cpp" "AgPropGuard.cpp" "AgPropguards.cpp" "AgQbElevator.cpp" + "AgQbWall.cpp" "AgSalutingNpcs.cpp" "AgShipPlayerDeathTrigger.cpp" "AgShipPlayerShockServer.cpp" @@ -206,6 +207,7 @@ set(DSCRIPT_SOURCES "ActivityManager.cpp" "PrSeagullFly.cpp" "PrWhistle.cpp" "QbEnemyStunner.cpp" + "QbSpawner.cpp" "RaceImagineCrateServer.cpp" "RaceImaginePowerup.cpp" "RaceMaelstromGeiser.cpp" diff --git a/dScripts/CppScripts.cpp b/dScripts/CppScripts.cpp index 73c50d62..7d114cd3 100644 --- a/dScripts/CppScripts.cpp +++ b/dScripts/CppScripts.cpp @@ -61,6 +61,8 @@ #include "VeMissionConsole.h" #include "VeEpsilonServer.h" #include "AgSurvivalBuffStation.h" +#include "QbSpawner.h" +#include "AgQbWall.h" // NS Scripts #include "NsModularBuild.h" @@ -466,6 +468,10 @@ CppScripts::Script* CppScripts::GetScript(Entity* parent, const std::string& scr script = new WildAmbients(); else if (scriptName == "scripts\\ai\\NS\\NS_PP_01\\L_NS_PP_01_TELEPORT.lua") script = new PropertyDeathPlane(); + else if (scriptName == "scripts\\02_server\\Map\\General\\L_QB_SPAWNER.lua") + script = new QbSpawner(); + else if (scriptName == "scripts\\ai\\AG\\L_AG_QB_Wall.lua") + script = new AgQbWall(); //GF: else if (scriptName == "scripts\\02_server\\Map\\GF\\L_GF_TORCH.lua") diff --git a/dScripts/QbSpawner.cpp b/dScripts/QbSpawner.cpp new file mode 100644 index 00000000..edee6148 --- /dev/null +++ b/dScripts/QbSpawner.cpp @@ -0,0 +1,136 @@ +#include "QbSpawner.h" +#include "BaseCombatAIComponent.h" +#include "MovementAIComponent.h" + +void QbSpawner::OnStartup(Entity* self) { + auto mobNum = self->GetVar<int>(u"mobNum"); + auto spawnDist = self->GetVar<float>(u"spawnDist"); + auto mobTemplate = self->GetVar<LWOOBJID>(u"mobTemplate"); + auto spawnTime = self->GetVar<float>(u"spawnTime"); + + if (!mobNum) self->SetVar<int>(u"mobNum", m_DefaultMobNum); + if (!spawnDist) self->SetVar<float>(u"spawnDist", m_DefaultSpawnDist); + if (!mobTemplate) self->SetVar<LWOOBJID>(u"mobTemplate", m_DefaultMobTemplate); + if (!spawnTime) self->SetVar<float>(u"spawnTime", m_DefaultSpawnTime); + + // go ahead and setup the mob table here + std::vector<LWOOBJID> mobTable; + mobTable.assign(self->GetVar<int>(u"mobNum"), LWOOBJID_EMPTY); + + self->SetVar<std::vector<LWOOBJID>>(u"mobTable", mobTable); +} + +void QbSpawner::OnFireEventServerSide(Entity* self, Entity* sender, std::string args, int32_t param1, int32_t param2, int32_t param3) { + auto gateObjID = sender->GetObjectID(); + if (!gateObjID) return; + if (args == "spawnMobs") { + self->SetVar(u"gateObj", gateObjID); + auto spawnTime = self->GetVar<float>(u"spawnTime"); + self->AddTimer("SpawnMobEnemies", spawnTime); + } +} + +void QbSpawner::OnTimerDone(Entity* self, std::string timerName) { + if (timerName == "SpawnMobEnemies") { + auto mobTable = self->GetVar<std::vector<LWOOBJID>>(u"mobTable"); + + auto spawnDist = self->GetVar<float>(u"spawnDist"); + auto mobTemplate = self->GetVar<LWOOBJID>(u"mobTemplate"); + + auto gateObjID = self->GetVar<LWOOBJID>(u"gateObj"); + if (!gateObjID) return; + + auto* gate = EntityManager::Instance()->GetEntity(gateObjID); + if (!gate) return; + + auto oPos = gate->GetPosition(); + auto oDir = gate->GetRotation().GetForwardVector(); + NiPoint3 newPos( + oPos.x + (oDir.x * spawnDist), + oPos.y, + oPos.z + (oDir.z * spawnDist) + ); + auto newRot = NiQuaternion::LookAt(newPos, oPos); + + for (int i = 0; i < mobTable.size(); i++) { + int posOffset = -10; + if (mobTable[i] == LWOOBJID_EMPTY) { + posOffset = posOffset + 5 * i; + auto newOffset = newPos; + newOffset.z = newOffset.z + posOffset; + + EntityInfo info{}; + info.lot = mobTemplate; + info.pos = newOffset; + info.rot = newRot; + info.spawnerID = self->GetObjectID(); + info.spawnerNodeID = 0; + info.settings = { + new LDFData<bool>(u"no_timed_spawn", true), + new LDFData<float>(u"aggroRadius", 70), + new LDFData<float>(u"softtetherRadius", 80), + new LDFData<float>(u"tetherRadius", 90), + new LDFData<float>(u"wanderRadius", 5), + new LDFData<int>(u"mobTableLoc", i) + }; + + auto* child = EntityManager::Instance()->CreateEntity(info, nullptr, self); + EntityManager::Instance()->ConstructEntity(child); + + OnChildLoaded(self, child); + } else { + auto* mob = EntityManager::Instance()->GetEntity(mobTable[i]); + AggroTargetObject(self, mob); + } + } + + } +} + +void QbSpawner::OnChildLoaded(Entity* self, Entity* child) { + auto mobTable = self->GetVar<std::vector<LWOOBJID>>(u"mobTable"); + auto tableLoc = child->GetVar<int>(u"mobTableLoc"); + + mobTable[tableLoc] = child->GetObjectID(); + self->SetVar<std::vector<LWOOBJID>>(u"mobTable", mobTable); + + AggroTargetObject(self, child); + + const auto selfID = self->GetObjectID(); + + child->AddDieCallback([this, selfID, child]() { + auto* self = EntityManager::Instance()->GetEntity(selfID); + OnChildRemoved(self, child); + } + ); +} + +void QbSpawner::OnChildRemoved(Entity* self, Entity* child) { + auto mobTable = self->GetVar<std::vector<LWOOBJID>>(u"mobTable"); + auto tableLoc = child->GetVar<int>(u"mobTableLoc"); + + mobTable[tableLoc] = LWOOBJID_EMPTY; + self->SetVar<std::vector<LWOOBJID>>(u"mobTable", mobTable); +} + +void QbSpawner::AggroTargetObject(Entity* self, Entity* enemy) { + auto* baseCombatAIComponent = enemy->GetComponent<BaseCombatAIComponent>(); + if (!baseCombatAIComponent) return; + + auto gateObjID = self->GetVar<LWOOBJID>(u"gateObj"); + if (gateObjID) { + auto* gate = EntityManager::Instance()->GetEntity(gateObjID); + if (gate) { + auto* movementAIComponent = enemy->GetComponent<MovementAIComponent>(); + if (movementAIComponent) movementAIComponent->SetDestination(gate->GetPosition()); + baseCombatAIComponent->Taunt(gateObjID, 1000); + } + } + + auto playerObjID = self->GetVar<LWOOBJID>(u"player"); + if (playerObjID) { + baseCombatAIComponent->Taunt(playerObjID, 100); + } + +} + diff --git a/dScripts/QbSpawner.h b/dScripts/QbSpawner.h new file mode 100644 index 00000000..105d0835 --- /dev/null +++ b/dScripts/QbSpawner.h @@ -0,0 +1,17 @@ +#pragma once +#include "CppScripts.h" + +class QbSpawner : public CppScripts::Script { +public: + void OnStartup(Entity* self) override; + void OnFireEventServerSide(Entity* self, Entity* sender, std::string args, int32_t param1, int32_t param2, int32_t param3) override; + void OnTimerDone(Entity* self, std::string timerName) override; + void OnChildLoaded(Entity* self, Entity* child); + void OnChildRemoved(Entity* self, Entity* child); + void AggroTargetObject(Entity* self, Entity* enemy); +private: + const int m_DefaultMobNum = 3; + const float m_DefaultSpawnDist = 25.0; + const LWOOBJID m_DefaultMobTemplate = 4712; + const float m_DefaultSpawnTime = 2.0; +}; From 26f2eb409ffb50b011d892bbfc029214f635f8a2 Mon Sep 17 00:00:00 2001 From: Aaron Kimbrell <aronwk.aaron@gmail.com> Date: Fri, 2 Sep 2022 13:49:19 -0500 Subject: [PATCH 75/86] Mounts v2 (#726) * Mounts -v2 * fix stun state and make comments a bit nicer * remove extra serilization * update the char position a bit more correctly * make vehicles face thr player's direction * address feedback * fix compiling for real this time * removed uneeded check --- dCommon/eUnequippableActiveType.h | 14 ++ dDatabase/Tables/CDItemComponentTable.cpp | 4 +- dGame/Entity.cpp | 7 + dGame/dComponents/CharacterComponent.h | 17 -- .../ControllablePhysicsComponent.cpp | 6 +- .../ControllablePhysicsComponent.h | 17 ++ dGame/dComponents/DestroyableComponent.cpp | 20 ++ dGame/dComponents/InventoryComponent.cpp | 194 ++++++++---------- dGame/dComponents/InventoryComponent.h | 7 + dGame/dComponents/PetComponent.cpp | 5 +- dGame/dComponents/PossessableComponent.cpp | 17 +- dGame/dComponents/PossessableComponent.h | 30 ++- dGame/dComponents/PossessorComponent.cpp | 67 +++++- dGame/dComponents/PossessorComponent.h | 59 ++++-- dGame/dGameMessages/GameMessageHandler.cpp | 4 + dGame/dGameMessages/GameMessages.cpp | 53 +++-- dGame/dGameMessages/GameMessages.h | 3 +- dGame/dInventory/Item.cpp | 64 +++--- dGame/dInventory/Item.h | 3 +- dGame/dUtilities/SlashCommandHandler.cpp | 95 ++++++--- dNet/ClientPackets.cpp | 34 ++- docs/Commands.md | 5 +- 22 files changed, 480 insertions(+), 245 deletions(-) create mode 100644 dCommon/eUnequippableActiveType.h diff --git a/dCommon/eUnequippableActiveType.h b/dCommon/eUnequippableActiveType.h new file mode 100644 index 00000000..8a6d29ba --- /dev/null +++ b/dCommon/eUnequippableActiveType.h @@ -0,0 +1,14 @@ +#pragma once + +#ifndef __EUNEQUIPPABLEACTIVETYPE__H__ +#define __EUNEQUIPPABLEACTIVETYPE__H__ + +#include <cstdint> + +enum class eUnequippableActiveType : int32_t { + INVALID = -1, + PET = 0, + MOUNT +}; + +#endif //!__EUNEQUIPPABLEACTIVETYPE__H__ diff --git a/dDatabase/Tables/CDItemComponentTable.cpp b/dDatabase/Tables/CDItemComponentTable.cpp index 703497ff..6ff192fd 100644 --- a/dDatabase/Tables/CDItemComponentTable.cpp +++ b/dDatabase/Tables/CDItemComponentTable.cpp @@ -45,7 +45,7 @@ CDItemComponentTable::CDItemComponentTable(void) { entry.offsetGroupID = tableData.getIntField(19, -1); entry.buildTypes = tableData.getIntField(20, -1); entry.reqPrecondition = tableData.getStringField(21, ""); - entry.animationFlag = tableData.getIntField(22, -1); + entry.animationFlag = tableData.getIntField(22, 0); entry.equipEffects = tableData.getIntField(23, -1); entry.readyForQA = tableData.getIntField(24, -1) == 1 ? true : false; entry.itemRating = tableData.getIntField(25, -1); @@ -123,7 +123,7 @@ const CDItemComponent& CDItemComponentTable::GetItemComponentByID(unsigned int s entry.offsetGroupID = tableData.getIntField(19, -1); entry.buildTypes = tableData.getIntField(20, -1); entry.reqPrecondition = tableData.getStringField(21, ""); - entry.animationFlag = tableData.getIntField(22, -1); + entry.animationFlag = tableData.getIntField(22, 0); entry.equipEffects = tableData.getIntField(23, -1); entry.readyForQA = tableData.getIntField(24, -1) == 1 ? true : false; entry.itemRating = tableData.getIntField(25, -1); diff --git a/dGame/Entity.cpp b/dGame/Entity.cpp index 89289004..52eddd06 100644 --- a/dGame/Entity.cpp +++ b/dGame/Entity.cpp @@ -1454,6 +1454,13 @@ void Entity::Smash(const LWOOBJID source, const eKillType killType, const std::u Kill(EntityManager::Instance()->GetEntity(source)); return; } + auto* possessorComponent = GetComponent<PossessorComponent>(); + if (possessorComponent) { + if (possessorComponent->GetPossessable() != LWOOBJID_EMPTY) { + auto* mount = EntityManager::Instance()->GetEntity(possessorComponent->GetPossessable()); + if (mount) possessorComponent->Dismount(mount, true); + } + } destroyableComponent->Smash(source, killType, deathType); } diff --git a/dGame/dComponents/CharacterComponent.h b/dGame/dComponents/CharacterComponent.h index 8efb4ef5..196dfa01 100644 --- a/dGame/dComponents/CharacterComponent.h +++ b/dGame/dComponents/CharacterComponent.h @@ -167,18 +167,6 @@ public: */ void SetLastRocketItemID(LWOOBJID lastRocketItemID) { m_LastRocketItemID = lastRocketItemID; } - /** - * Gets the object ID of the mount item that is being used - * @return the object ID of the mount item that is being used - */ - LWOOBJID GetMountItemID() const { return m_MountItemID; } - - /** - * Sets the object ID of the mount item that is being used - * @param m_MountItemID the object ID of the mount item that is being used - */ - void SetMountItemID(LWOOBJID mountItemID) { m_MountItemID = mountItemID; } - /** * Gets the name of this character * @return the name of this character @@ -569,11 +557,6 @@ private: * ID of the last rocket used */ LWOOBJID m_LastRocketItemID = LWOOBJID_EMPTY; - - /** - * Mount Item ID - */ - LWOOBJID m_MountItemID = LWOOBJID_EMPTY; }; #endif // CHARACTERCOMPONENT_H diff --git a/dGame/dComponents/ControllablePhysicsComponent.cpp b/dGame/dComponents/ControllablePhysicsComponent.cpp index 471b9ca1..d7caf6a9 100644 --- a/dGame/dComponents/ControllablePhysicsComponent.cpp +++ b/dGame/dComponents/ControllablePhysicsComponent.cpp @@ -32,6 +32,7 @@ ControllablePhysicsComponent::ControllablePhysicsComponent(Entity* entity) : Com m_IgnoreMultipliers = false; m_PickupRadius = 0.0f; m_DirtyPickupRadiusScale = true; + m_IsTeleporting = false; if (entity->GetLOT() != 1) // Other physics entities we care about will be added by BaseCombatAI return; @@ -128,7 +129,10 @@ void ControllablePhysicsComponent::Serialize(RakNet::BitStream* outBitStream, bo outBitStream->Write0(); } - if (!bIsInitialUpdate) outBitStream->Write0(); + if (!bIsInitialUpdate) { + outBitStream->Write(m_IsTeleporting); + m_IsTeleporting = false; + } } void ControllablePhysicsComponent::LoadFromXml(tinyxml2::XMLDocument* doc) { diff --git a/dGame/dComponents/ControllablePhysicsComponent.h b/dGame/dComponents/ControllablePhysicsComponent.h index bc05657c..ac481b9f 100644 --- a/dGame/dComponents/ControllablePhysicsComponent.h +++ b/dGame/dComponents/ControllablePhysicsComponent.h @@ -220,6 +220,18 @@ public: */ bool GetStatic() const { return m_Static; } + /** + * Sets if the entity is Teleporting, + * @param value whether or not the entity is Is Teleporting + */ + void SetIsTeleporting(const bool value) { m_IsTeleporting = value; } + + /** + * Returns whether or not this entity is currently is teleporting + * @return whether or not this entity is currently is teleporting + */ + bool GetIsTeleporting() const { return m_IsTeleporting; } + /** * Returns the Physics entity for the component * @return Physics entity for the component @@ -355,6 +367,11 @@ private: * The active pickup radius for this entity */ float m_PickupRadius; + + /** + * If the entity is teleporting + */ + bool m_IsTeleporting; }; #endif // CONTROLLABLEPHYSICSCOMPONENT_H diff --git a/dGame/dComponents/DestroyableComponent.cpp b/dGame/dComponents/DestroyableComponent.cpp index 1cbf7aad..8b9ae42d 100644 --- a/dGame/dComponents/DestroyableComponent.cpp +++ b/dGame/dComponents/DestroyableComponent.cpp @@ -26,6 +26,8 @@ #include "MissionComponent.h" #include "CharacterComponent.h" +#include "PossessableComponent.h" +#include "PossessorComponent.h" #include "dZoneManager.h" DestroyableComponent::DestroyableComponent(Entity* parent) : Component(parent) { @@ -608,6 +610,24 @@ void DestroyableComponent::Damage(uint32_t damage, const LWOOBJID source, uint32 SetHealth(health); SetIsShielded(absorb > 0); + // Dismount on the possessable hit + auto possessable = m_Parent->GetComponent<PossessableComponent>(); + if (possessable && possessable->GetDepossessOnHit()) { + possessable->Dismount(); + } + + // Dismount on the possessor hit + auto possessor = m_Parent->GetComponent<PossessorComponent>(); + if (possessor) { + auto possessableId = possessor->GetPossessable(); + if (possessableId != LWOOBJID_EMPTY) { + auto possessable = EntityManager::Instance()->GetEntity(possessableId); + if (possessable) { + possessor->Dismount(possessable); + } + } + } + if (m_Parent->GetLOT() != 1) { echo = true; } diff --git a/dGame/dComponents/InventoryComponent.cpp b/dGame/dComponents/InventoryComponent.cpp index 6dbb3bd8..930ace8d 100644 --- a/dGame/dComponents/InventoryComponent.cpp +++ b/dGame/dComponents/InventoryComponent.cpp @@ -26,6 +26,7 @@ #include "DestroyableComponent.h" #include "dConfig.h" #include "eItemType.h" +#include "eUnequippableActiveType.h" InventoryComponent::InventoryComponent(Entity* parent, tinyxml2::XMLDocument* document) : Component(parent) { this->m_Dirty = true; @@ -62,23 +63,23 @@ InventoryComponent::InventoryComponent(Entity* parent, tinyxml2::XMLDocument* do const auto& info = Inventory::FindItemComponent(item.itemid); UpdateSlot(info.equipLocation, { id, static_cast<LOT>(item.itemid), item.count, slot++ }); - + // Equip this items proxies. auto subItems = info.subItems; - + subItems.erase(std::remove_if(subItems.begin(), subItems.end(), ::isspace), subItems.end()); - + if (!subItems.empty()) { const auto subItemsSplit = GeneralUtils::SplitString(subItems, ','); - + for (auto proxyLotAsString : subItemsSplit) { const auto proxyLOT = static_cast<LOT>(std::stoi(proxyLotAsString)); - + const auto& proxyInfo = Inventory::FindItemComponent(proxyLOT); const LWOOBJID proxyId = ObjectIDManager::Instance()->GenerateObjectID(); - + // Use item.count since we equip item.count number of the item this is a requested proxy of - UpdateSlot(proxyInfo.equipLocation, { proxyId, proxyLOT, item.count, slot++ } ); + UpdateSlot(proxyInfo.equipLocation, { proxyId, proxyLOT, item.count, slot++ }); } } } @@ -795,9 +796,7 @@ void InventoryComponent::RemoveSlot(const std::string& location) { } void InventoryComponent::EquipItem(Item* item, const bool skipChecks) { - if (!Inventory::IsValidItem(item->GetLot())) { - return; - } + if (!Inventory::IsValidItem(item->GetLot())) return; // Temp items should be equippable but other transfer items shouldn't be (for example the instruments in RB) if (item->IsEquipped() @@ -820,9 +819,7 @@ void InventoryComponent::EquipItem(Item* item, const bool skipChecks) { auto* characterComponent = m_Parent->GetComponent<CharacterComponent>(); - if (characterComponent != nullptr) { - characterComponent->SetLastRocketItemID(item->GetId()); - } + if (characterComponent != nullptr) characterComponent->SetLastRocketItemID(item->GetId()); lauchPad->OnUse(m_Parent); @@ -836,94 +833,8 @@ void InventoryComponent::EquipItem(Item* item, const bool skipChecks) { const auto type = static_cast<eItemType>(item->GetInfo().itemType); - if (item->GetLot() == 8092 && m_Parent->GetGMLevel() >= GAME_MASTER_LEVEL_OPERATOR && hasCarEquipped == false) { - auto startPosition = m_Parent->GetPosition(); - auto startRotation = NiQuaternion::LookAt(startPosition, startPosition + NiPoint3::UNIT_X); - auto angles = startRotation.GetEulerAngles(); - angles.y -= PI; - startRotation = NiQuaternion::FromEulerAngles(angles); - - GameMessages::SendTeleport(m_Parent->GetObjectID(), startPosition, startRotation, m_Parent->GetSystemAddress(), true, true); - - EntityInfo info{}; - info.lot = 8092; - info.pos = startPosition; - info.rot = startRotation; - info.spawnerID = m_Parent->GetObjectID(); - - auto* carEntity = EntityManager::Instance()->CreateEntity(info, nullptr, m_Parent); - m_Parent->AddChild(carEntity); - - auto* destroyableComponent = carEntity->GetComponent<DestroyableComponent>(); - - // Setup the vehicle stats. - if (destroyableComponent != nullptr) { - destroyableComponent->SetIsSmashable(false); - destroyableComponent->SetIsImmune(true); - } - // #108 - auto* possessableComponent = carEntity->GetComponent<PossessableComponent>(); - - if (possessableComponent != nullptr) { - previousPossessableID = possessableComponent->GetPossessor(); - possessableComponent->SetPossessor(m_Parent->GetObjectID()); - } - - auto* moduleAssemblyComponent = carEntity->GetComponent<ModuleAssemblyComponent>(); - - if (moduleAssemblyComponent != nullptr) { - moduleAssemblyComponent->SetSubKey(item->GetSubKey()); - moduleAssemblyComponent->SetUseOptionalParts(false); - - for (auto* config : item->GetConfig()) { - if (config->GetKey() == u"assemblyPartLOTs") { - moduleAssemblyComponent->SetAssemblyPartsLOTs(GeneralUtils::ASCIIToUTF16(config->GetValueAsString())); - } - } - } - // #107 - auto* possessorComponent = m_Parent->GetComponent<PossessorComponent>(); - - if (possessorComponent) possessorComponent->SetPossessable(carEntity->GetObjectID()); - - auto* characterComponent = m_Parent->GetComponent<CharacterComponent>(); - - if (characterComponent) characterComponent->SetIsRacing(true); - - EntityManager::Instance()->ConstructEntity(carEntity); - EntityManager::Instance()->SerializeEntity(m_Parent); - GameMessages::SendSetJetPackMode(m_Parent, false); - - GameMessages::SendNotifyVehicleOfRacingObject(carEntity->GetObjectID(), m_Parent->GetObjectID(), UNASSIGNED_SYSTEM_ADDRESS); - GameMessages::SendRacingPlayerLoaded(LWOOBJID_EMPTY, m_Parent->GetObjectID(), carEntity->GetObjectID(), UNASSIGNED_SYSTEM_ADDRESS); - GameMessages::SendVehicleUnlockInput(carEntity->GetObjectID(), false, UNASSIGNED_SYSTEM_ADDRESS); - GameMessages::SendTeleport(m_Parent->GetObjectID(), startPosition, startRotation, m_Parent->GetSystemAddress(), true, true); - GameMessages::SendTeleport(carEntity->GetObjectID(), startPosition, startRotation, m_Parent->GetSystemAddress(), true, true); - EntityManager::Instance()->SerializeEntity(m_Parent); - - hasCarEquipped = true; - equippedCarEntity = carEntity; - return; - } else if (item->GetLot() == 8092 && m_Parent->GetGMLevel() >= GAME_MASTER_LEVEL_OPERATOR && hasCarEquipped == true) { - GameMessages::SendNotifyRacingClient(LWOOBJID_EMPTY, 3, 0, LWOOBJID_EMPTY, u"", m_Parent->GetObjectID(), UNASSIGNED_SYSTEM_ADDRESS); - auto player = dynamic_cast<Player*>(m_Parent); - player->SendToZone(player->GetCharacter()->GetZoneID()); - equippedCarEntity->Kill(); - hasCarEquipped = false; - equippedCarEntity = nullptr; - return; - } - - if (!building) { - if (item->GetLot() == 6086) { - return; - } - - if (type == eItemType::ITEM_TYPE_LOOT_MODEL || type == eItemType::ITEM_TYPE_VEHICLE) { - return; - } - } + if (!building && (item->GetLot() == 6086 || type == eItemType::ITEM_TYPE_LOOT_MODEL || type == eItemType::ITEM_TYPE_VEHICLE)) return; if (type != eItemType::ITEM_TYPE_LOOT_MODEL && type != eItemType::ITEM_TYPE_MODEL) { if (!item->GetBound() && !item->GetPreconditionExpression()->Check(m_Parent)) { @@ -940,9 +851,7 @@ void InventoryComponent::EquipItem(Item* item, const bool skipChecks) { set->OnEquip(lot); } - if (item->GetInfo().isBOE) { - item->SetBound(true); - } + if (item->GetInfo().isBOE) item->SetBound(true); GenerateProxies(item); @@ -989,6 +898,85 @@ void InventoryComponent::UnEquipItem(Item* item) { } } +void InventoryComponent::HandlePossession(Item* item) { + auto* characterComponent = m_Parent->GetComponent<CharacterComponent>(); + if (!characterComponent) return; + + auto* possessorComponent = m_Parent->GetComponent<PossessorComponent>(); + if (!possessorComponent) return; + + // Don't do anything if we are busy dismounting + if (possessorComponent->GetIsDismounting()) return; + + // Check to see if we are already mounting something + auto* currentlyPossessedEntity = EntityManager::Instance()->GetEntity(possessorComponent->GetPossessable()); + auto currentlyPossessedItem = possessorComponent->GetMountItemID(); + + if (currentlyPossessedItem) { + if (currentlyPossessedEntity) possessorComponent->Dismount(currentlyPossessedEntity); + return; + } + + GameMessages::SendSetStunned(m_Parent->GetObjectID(), eStunState::PUSH, m_Parent->GetSystemAddress(), LWOOBJID_EMPTY, true, false, true, false, false, false, false, true, true, true, true, true, true, true, true, true); + + // Set the mount Item ID so that we know what were handling + possessorComponent->SetMountItemID(item->GetId()); + GameMessages::SendSetMountInventoryID(m_Parent, item->GetId(), UNASSIGNED_SYSTEM_ADDRESS); + + // Create entity to mount + auto startRotation = m_Parent->GetRotation(); + + EntityInfo info{}; + info.lot = item->GetLot(); + info.pos = m_Parent->GetPosition(); + info.rot = startRotation; + info.spawnerID = m_Parent->GetObjectID(); + + auto* mount = EntityManager::Instance()->CreateEntity(info, nullptr, m_Parent); + + // Check to see if the mount is a vehicle, if so, flip it + auto* vehicleComponent = mount->GetComponent<VehiclePhysicsComponent>(); + if (vehicleComponent) { + auto angles = startRotation.GetEulerAngles(); + // Make it right side up + angles.x -= PI; + // Make it going in the direction of the player + angles.y -= PI; + startRotation = NiQuaternion::FromEulerAngles(angles); + mount->SetRotation(startRotation); + // We're pod racing now + characterComponent->SetIsRacing(true); + } + + // Setup the destroyable stats + auto* destroyableComponent = mount->GetComponent<DestroyableComponent>(); + if (destroyableComponent) { + destroyableComponent->SetIsSmashable(false); + destroyableComponent->SetIsImmune(true); + } + + // Mount it + auto* possessableComponent = mount->GetComponent<PossessableComponent>(); + if (possessableComponent) { + possessableComponent->SetIsItemSpawned(true); + possessableComponent->SetPossessor(m_Parent->GetObjectID()); + // Possess it + possessorComponent->SetPossessable(mount->GetObjectID()); + possessorComponent->SetPossessableType(possessableComponent->GetPossessionType()); + } + + GameMessages::SendSetJetPackMode(m_Parent, false); + + // Make it go to the client + EntityManager::Instance()->ConstructEntity(mount); + // Update the possessor + EntityManager::Instance()->SerializeEntity(m_Parent); + + // have to unlock the input so it vehicle can be driven + if (vehicleComponent) GameMessages::SendVehicleUnlockInput(mount->GetObjectID(), false, m_Parent->GetSystemAddress()); + GameMessages::SendMarkInventoryItemAsActive(m_Parent->GetObjectID(), true, eUnequippableActiveType::MOUNT, item->GetId(), m_Parent->GetSystemAddress()); +} + void InventoryComponent::ApplyBuff(Item* item) const { const auto buffs = FindBuffs(item, true); diff --git a/dGame/dComponents/InventoryComponent.h b/dGame/dComponents/InventoryComponent.h index 01b4ca86..394cb801 100644 --- a/dGame/dComponents/InventoryComponent.h +++ b/dGame/dComponents/InventoryComponent.h @@ -198,6 +198,13 @@ public: */ void UnEquipItem(Item* item); + /** + * Unequips an Item from the inventory + * @param item the Item to unequip + * @return if we were successful + */ + void HandlePossession(Item* item); + /** * Adds a buff related to equipping a lot to the entity * @param item the item to find buffs for diff --git a/dGame/dComponents/PetComponent.cpp b/dGame/dComponents/PetComponent.cpp index ef882555..8863f9be 100644 --- a/dGame/dComponents/PetComponent.cpp +++ b/dGame/dComponents/PetComponent.cpp @@ -14,6 +14,7 @@ #include "dpWorld.h" #include "PetDigServer.h" #include "../dWorldServer/ObjectIDManager.h" +#include "eUnequippableActiveType.h" #include "Game.h" #include "dConfig.h" @@ -883,7 +884,7 @@ void PetComponent::Activate(Item* item, bool registerPet, bool fromTaming) { GameMessages::SendSetPetNameModerated(m_Owner, m_DatabaseId, m_ModerationStatus, owner->GetSystemAddress()); } - GameMessages::SendMarkInventoryItemAsActive(m_Owner, true, 0, m_ItemId, GetOwner()->GetSystemAddress()); + GameMessages::SendMarkInventoryItemAsActive(m_Owner, true, eUnequippableActiveType::PET, m_ItemId, GetOwner()->GetSystemAddress()); activePets[m_Owner] = m_Parent->GetObjectID(); @@ -945,7 +946,7 @@ void PetComponent::AddDrainImaginationTimer(Item* item, bool fromTaming) { void PetComponent::Deactivate() { GameMessages::SendPlayFXEffect(m_Parent->GetObjectID(), -1, u"despawn", "", LWOOBJID_EMPTY, 1, 1, true); - GameMessages::SendMarkInventoryItemAsActive(m_Owner, false, 0, m_ItemId, GetOwner()->GetSystemAddress()); + GameMessages::SendMarkInventoryItemAsActive(m_Owner, false, eUnequippableActiveType::PET, m_ItemId, GetOwner()->GetSystemAddress()); activePets.erase(m_Owner); diff --git a/dGame/dComponents/PossessableComponent.cpp b/dGame/dComponents/PossessableComponent.cpp index be31914b..37591532 100644 --- a/dGame/dComponents/PossessableComponent.cpp +++ b/dGame/dComponents/PossessableComponent.cpp @@ -18,7 +18,7 @@ PossessableComponent::PossessableComponent(Entity* parent, uint32_t componentId) // Should a result not exist for this default to attached visible if (!result.eof()) { - m_PossessionType = static_cast<ePossessionType>(result.getIntField(0, 0)); + m_PossessionType = static_cast<ePossessionType>(result.getIntField(0, 1)); // Default to Attached Visible m_DepossessOnHit = static_cast<bool>(result.getIntField(1, 0)); } else { m_PossessionType = ePossessionType::ATTACHED_VISIBLE; @@ -30,7 +30,7 @@ PossessableComponent::PossessableComponent(Entity* parent, uint32_t componentId) void PossessableComponent::Serialize(RakNet::BitStream* outBitStream, bool bIsInitialUpdate, unsigned int& flags) { outBitStream->Write(m_DirtyPossessable || bIsInitialUpdate); if (m_DirtyPossessable || bIsInitialUpdate) { - m_DirtyPossessable = false; + m_DirtyPossessable = false; // reset flag outBitStream->Write(m_Possessor != LWOOBJID_EMPTY); if (m_Possessor != LWOOBJID_EMPTY) outBitStream->Write(m_Possessor); @@ -38,9 +38,18 @@ void PossessableComponent::Serialize(RakNet::BitStream* outBitStream, bool bIsIn if (m_AnimationFlag != eAnimationFlags::IDLE_INVALID) outBitStream->Write(m_AnimationFlag); outBitStream->Write(m_ImmediatelyDepossess); + m_ImmediatelyDepossess = false; // reset flag } } -void PossessableComponent::OnUse(Entity* originator) { - // TODO: Implement this +void PossessableComponent::Dismount() { + SetPossessor(LWOOBJID_EMPTY); + if (m_ItemSpawned) m_Parent->ScheduleKillAfterUpdate(); +} + +void PossessableComponent::OnUse(Entity* originator) { + auto* possessor = originator->GetComponent<PossessorComponent>(); + if (possessor) { + possessor->Mount(m_Parent); + } } diff --git a/dGame/dComponents/PossessableComponent.h b/dGame/dComponents/PossessableComponent.h index 77905c9c..43ce8610 100644 --- a/dGame/dComponents/PossessableComponent.h +++ b/dGame/dComponents/PossessableComponent.h @@ -20,14 +20,24 @@ public: void Serialize(RakNet::BitStream* outBitStream, bool bIsInitialUpdate, unsigned int& flags); /** - * Sets the possessor of this entity + * @brief mounts the Entity + */ + void Mount(); + + /** + * @brief dismounts the Entity + */ + void Dismount(); + + /** + * Sets the possessor of this Entity * @param value the ID of the possessor to set */ void SetPossessor(LWOOBJID value) { m_Possessor = value; m_DirtyPossessable = true; }; /** - * Returns the possessor of this entity - * @return the possessor of this entity + * Returns the possessor of this Entity + * @return the possessor of this Entity */ LWOOBJID GetPossessor() const { return m_Possessor; }; @@ -38,19 +48,19 @@ public: void SetAnimationFlag(eAnimationFlags value) { m_AnimationFlag = value; m_DirtyPossessable = true; }; /** - * Returns the possession type of this entity - * @return the possession type of this entity + * Returns the possession type of this Entity + * @return the possession type of this Entity */ ePossessionType GetPossessionType() const { return m_PossessionType; }; /** - * Returns if the entity should deposses on hit - * @return if the entity should deposses on hit + * Returns if the Entity should deposses on hit + * @return if the Entity should deposses on hit */ bool GetDepossessOnHit() const { return m_DepossessOnHit; }; /** - * Forcibly depossess the entity + * Forcibly depossess the Entity */ void ForceDepossess() { m_ImmediatelyDepossess = true; m_DirtyPossessable = true; }; @@ -58,13 +68,13 @@ public: * Set if the parent entity was spawned from an item * @param value if the parent entity was spawned from an item */ - void SetItemSpawned(bool value) { m_ItemSpawned = value; }; + void SetIsItemSpawned(bool value) { m_ItemSpawned = value; }; /** * Returns if the parent entity was spawned from an item * @return if the parent entity was spawned from an item */ - LWOOBJID GetItemSpawned() const { return m_ItemSpawned; }; + LWOOBJID GetIsItemSpawned() const { return m_ItemSpawned; }; /** * Handles an OnUsed event by some other entity, if said entity has a Possessor it becomes the possessor diff --git a/dGame/dComponents/PossessorComponent.cpp b/dGame/dComponents/PossessorComponent.cpp index 4ace324b..f0cad5ca 100644 --- a/dGame/dComponents/PossessorComponent.cpp +++ b/dGame/dComponents/PossessorComponent.cpp @@ -1,12 +1,28 @@ #include "PossessorComponent.h" +#include "PossessableComponent.h" +#include "CharacterComponent.h" +#include "EntityManager.h" +#include "GameMessages.h" +#include "eUnequippableActiveType.h" PossessorComponent::PossessorComponent(Entity* parent) : Component(parent) { m_Possessable = LWOOBJID_EMPTY; } -PossessorComponent::~PossessorComponent() {} - - +PossessorComponent::~PossessorComponent() { + if (m_Possessable != LWOOBJID_EMPTY) { + auto* mount = EntityManager::Instance()->GetEntity(m_Possessable); + if (mount) { + auto* possessable = mount->GetComponent<PossessableComponent>(); + if (possessable) { + if (possessable->GetIsItemSpawned()) { + GameMessages::SendMarkInventoryItemAsActive(m_Parent->GetObjectID(), false, eUnequippableActiveType::MOUNT, GetMountItemID(), m_Parent->GetSystemAddress()); + } + possessable->Dismount(); + } + } + } +} void PossessorComponent::Serialize(RakNet::BitStream* outBitStream, bool bIsInitialUpdate, unsigned int& flags) { outBitStream->Write(m_DirtyPossesor || bIsInitialUpdate); @@ -19,3 +35,48 @@ void PossessorComponent::Serialize(RakNet::BitStream* outBitStream, bool bIsInit outBitStream->Write(m_PossessableType); } } + +void PossessorComponent::Mount(Entity* mount) { + // Don't do anything if we are busy dismounting + if (GetIsDismounting() || !mount) return; + + GameMessages::SendSetMountInventoryID(m_Parent, mount->GetObjectID(), UNASSIGNED_SYSTEM_ADDRESS); + auto* possessableComponent = mount->GetComponent<PossessableComponent>(); + if (possessableComponent) { + possessableComponent->SetPossessor(m_Parent->GetObjectID()); + SetPossessable(mount->GetObjectID()); + SetPossessableType(possessableComponent->GetPossessionType()); + } + + auto characterComponent = m_Parent->GetComponent<CharacterComponent>(); + if (characterComponent) characterComponent->SetIsRacing(true); + + // GM's to send + GameMessages::SendSetJetPackMode(m_Parent, false); + GameMessages::SendVehicleUnlockInput(mount->GetObjectID(), false, m_Parent->GetSystemAddress()); + GameMessages::SendSetStunned(m_Parent->GetObjectID(), eStunState::PUSH, m_Parent->GetSystemAddress(), LWOOBJID_EMPTY, true, false, true, false, false, false, false, true, true, true, true, true, true, true, true, true); + + EntityManager::Instance()->SerializeEntity(m_Parent); + EntityManager::Instance()->SerializeEntity(mount); +} + +void PossessorComponent::Dismount(Entity* mount, bool forceDismount) { + // Don't do anything if we are busy dismounting + if (GetIsDismounting() || !mount) return; + SetIsDismounting(true); + + if (mount) { + auto* possessableComponent = mount->GetComponent<PossessableComponent>(); + if (possessableComponent) { + possessableComponent->SetPossessor(LWOOBJID_EMPTY); + if (forceDismount) possessableComponent->ForceDepossess(); + } + EntityManager::Instance()->SerializeEntity(m_Parent); + EntityManager::Instance()->SerializeEntity(mount); + + auto characterComponent = m_Parent->GetComponent<CharacterComponent>(); + if (characterComponent) characterComponent->SetIsRacing(false); + } + // Make sure we don't have wacky controls + GameMessages::SendSetPlayerControlScheme(m_Parent, eControlSceme::SCHEME_A); +} diff --git a/dGame/dComponents/PossessorComponent.h b/dGame/dComponents/PossessorComponent.h index 2735adac..00b24445 100644 --- a/dGame/dComponents/PossessorComponent.h +++ b/dGame/dComponents/PossessorComponent.h @@ -25,35 +25,63 @@ public: void Serialize(RakNet::BitStream* outBitStream, bool bIsInitialUpdate, unsigned int& flags); /** - * Sets the entity that this entity is possessing - * @param value the ID of the entity this ID should posess + * @brief Mounts the entity + * + * @param mount Entity to be mounted + */ + void Mount(Entity* mount); + + /** + * @brief Dismounts the entity + * + * @param mount Entity to be dismounted + * @param forceDismount Should we forcibly dismount the entity + */ + void Dismount(Entity* mount, bool forceDismount = false); + + /** + * Sets the ID that this entity is possessing + * @param value The ID that this entity is possessing */ void SetPossessable(LWOOBJID value) { m_Possessable = value; m_DirtyPossesor = true; } /** * Returns the entity that this entity is currently posessing - * @return the entity that this entity is currently posessing + * @return The entity that this entity is currently posessing */ LWOOBJID GetPossessable() const { return m_Possessable; } /** - * Sets if we are busy mounting or dismounting - * @param value if we are busy mounting or dismounting + * Sets if we are busy dismounting + * @param value If we are busy dismounting */ - void SetIsBusy(bool value) { m_IsBusy = value; } + void SetIsDismounting(bool value) { m_IsDismounting = value; } /** - * Returns if we are busy mounting or dismounting - * @return if we are busy mounting or dismounting + * Returns if we are busy dismounting + * @return If we are busy dismounting */ - bool GetIsBusy() const { return m_IsBusy; } + bool GetIsDismounting() const { return m_IsDismounting; } /** * Sets the possesible type that's currently used, merely used by the shooting gallery if it's 0 - * @param value the possesible type to set + * @param value The possesible type to set */ void SetPossessableType(ePossessionType value) { m_PossessableType = value; m_DirtyPossesor = true; } + + /** + * Gets the object ID of the mount item that is being used + * @return The object ID of the mount item that is being used + */ + LWOOBJID GetMountItemID() const { return m_MountItemID; } + + /** + * Sets the object ID of the mount item that is being used + * @param m_MountItemID The object ID of the mount item that is being used + */ + void SetMountItemID(LWOOBJID mountItemID) { m_MountItemID = mountItemID; } + private: /** @@ -68,14 +96,19 @@ private: ePossessionType m_PossessableType = ePossessionType::NO_POSSESSION; /** - * @brief if the possessor is dirty + * @brief If the possessor is dirty * */ bool m_DirtyPossesor = false; /** - * @brief if the possessor is busy mounting or dismounting + * @brief If the possessor is busy dismounting * */ - bool m_IsBusy = false; + bool m_IsDismounting = false; + + /** + * Mount Item ID + */ + LWOOBJID m_MountItemID = LWOOBJID_EMPTY; }; diff --git a/dGame/dGameMessages/GameMessageHandler.cpp b/dGame/dGameMessages/GameMessageHandler.cpp index b3b60fe7..9cf09bbc 100644 --- a/dGame/dGameMessages/GameMessageHandler.cpp +++ b/dGame/dGameMessages/GameMessageHandler.cpp @@ -653,6 +653,10 @@ void GameMessageHandler::HandleMessage(RakNet::BitStream* inStream, const System GameMessages::HandleUpdatePlayerStatistic(inStream, entity); break; + case GAME_MSG_DISMOUNT_COMPLETE: + GameMessages::HandleDismountComplete(inStream, entity, sysAddr); + break; + default: //Game::logger->Log("GameMessageHandler", "Unknown game message ID: %X", messageID); break; diff --git a/dGame/dGameMessages/GameMessages.cpp b/dGame/dGameMessages/GameMessages.cpp index 1645afc8..772cb691 100644 --- a/dGame/dGameMessages/GameMessages.cpp +++ b/dGame/dGameMessages/GameMessages.cpp @@ -27,6 +27,7 @@ #include "ChatPackets.h" #include "GameConfig.h" #include "RocketLaunchLupComponent.h" +#include "eUnequippableActiveType.h" #include <sstream> #include <future> @@ -3414,7 +3415,7 @@ void GameMessages::SendRegisterPetDBID(LWOOBJID objectId, LWOOBJID petDBID, cons SEND_PACKET; } -void GameMessages::SendMarkInventoryItemAsActive(LWOOBJID objectId, bool bActive, int32_t iType, LWOOBJID itemID, const SystemAddress& sysAddr) { +void GameMessages::SendMarkInventoryItemAsActive(LWOOBJID objectId, bool bActive, eUnequippableActiveType iType, LWOOBJID itemID, const SystemAddress& sysAddr) { CBITSTREAM; CMSGHEADER; @@ -3423,8 +3424,8 @@ void GameMessages::SendMarkInventoryItemAsActive(LWOOBJID objectId, bool bActive bitStream.Write(bActive); - bitStream.Write(iType != 0); - if (iType != 0) bitStream.Write(iType); + bitStream.Write(iType != eUnequippableActiveType::INVALID); + if (iType != eUnequippableActiveType::INVALID) bitStream.Write(iType); bitStream.Write(itemID != LWOOBJID_EMPTY); if (itemID != LWOOBJID_EMPTY) bitStream.Write(itemID); @@ -3861,7 +3862,6 @@ void GameMessages::SendDisplayChatBubble(LWOOBJID objectId, const std::u16string void GameMessages::SendSetMountInventoryID(Entity* entity, const LWOOBJID& objectID, const SystemAddress& sysAddr) { CBITSTREAM; CMSGHEADER; - bitStream.Write(entity->GetObjectID()); bitStream.Write(GAME_MSG::GAME_MSG_SET_MOUNT_INVENTORY_ID); bitStream.Write(objectID); @@ -3871,30 +3871,53 @@ void GameMessages::SendSetMountInventoryID(Entity* entity, const LWOOBJID& objec void GameMessages::HandleDismountComplete(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr) { + // Get the objectID from the bitstream LWOOBJID objectId{}; inStream->Read(objectId); - auto* mount = EntityManager::Instance()->GetEntity(objectId); + // If we aren't possessing somethings, the don't do anything if (objectId != LWOOBJID_EMPTY) { - PossessorComponent* possessor; - if (entity->TryGetComponent(COMPONENT_TYPE_POSSESSOR, possessor)) { - if (mount) { - possessor->SetIsBusy(false); - possessor->SetPossessable(LWOOBJID_EMPTY); - possessor->SetPossessableType(ePossessionType::NO_POSSESSION); + auto* possessorComponent = entity->GetComponent<PossessorComponent>(); + auto* mount = EntityManager::Instance()->GetEntity(objectId); + // make sure we have the things we need and they aren't null + if (possessorComponent && mount) { + if (!possessorComponent->GetIsDismounting()) return; + possessorComponent->SetIsDismounting(false); + possessorComponent->SetPossessable(LWOOBJID_EMPTY); + possessorComponent->SetPossessableType(ePossessionType::NO_POSSESSION); - GameMessages::SendSetStunned(entity->GetObjectID(), eStunState::POP, UNASSIGNED_SYSTEM_ADDRESS, LWOOBJID_EMPTY, true, false, true, false, false, false, false, true, true, true, true, true, true, true, true, true); - - EntityManager::Instance()->SerializeEntity(entity); + // character related things + auto* character = entity->GetComponent<CharacterComponent>(); + if (character) { + // If we had an active item turn it off + if (possessorComponent->GetMountItemID() != LWOOBJID_EMPTY) GameMessages::SendMarkInventoryItemAsActive(entity->GetObjectID(), false, eUnequippableActiveType::MOUNT, possessorComponent->GetMountItemID(), entity->GetSystemAddress()); + possessorComponent->SetMountItemID(LWOOBJID_EMPTY); } + + // Set that the controllabel phsyics comp is teleporting + auto* controllablePhysicsComponent = entity->GetComponent<ControllablePhysicsComponent>(); + if (controllablePhysicsComponent) controllablePhysicsComponent->SetIsTeleporting(true); + + // Call dismoint on the possessable comp to let it handle killing the possessable + auto* possessableComponent = mount->GetComponent<PossessableComponent>(); + if (possessableComponent) possessableComponent->Dismount(); + + // Update the entity that was possessing + EntityManager::Instance()->SerializeEntity(entity); + + // We aren't mounted so remove the stun + GameMessages::SendSetStunned(entity->GetObjectID(), eStunState::POP, UNASSIGNED_SYSTEM_ADDRESS, LWOOBJID_EMPTY, true, false, true, false, false, false, false, true, true, true, true, true, true, true, true, true); } } } void GameMessages::HandleAcknowledgePossession(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr) { - Game::logger->Log("HandleAcknowledgePossession", "Got AcknowledgePossession from %i", entity->GetLOT()); EntityManager::Instance()->SerializeEntity(entity); + LWOOBJID objectId{}; + inStream->Read(objectId); + auto* mount = EntityManager::Instance()->GetEntity(objectId); + if (mount) EntityManager::Instance()->SerializeEntity(mount); } //Racing diff --git a/dGame/dGameMessages/GameMessages.h b/dGame/dGameMessages/GameMessages.h index 47e5f41c..31bdebb3 100644 --- a/dGame/dGameMessages/GameMessages.h +++ b/dGame/dGameMessages/GameMessages.h @@ -19,6 +19,7 @@ class NiQuaternion; class User; class Entity; class NiPoint3; +enum class eUnequippableActiveType; namespace GameMessages { class PropertyDataMessage; @@ -318,7 +319,7 @@ namespace GameMessages { void SendRegisterPetDBID(LWOOBJID objectId, LWOOBJID petDBID, const SystemAddress& sysAddr); - void SendMarkInventoryItemAsActive(LWOOBJID objectId, bool bActive, int32_t iType, LWOOBJID itemID, const SystemAddress& sysAddr); + void SendMarkInventoryItemAsActive(LWOOBJID objectId, bool bActive, eUnequippableActiveType iType, LWOOBJID itemID, const SystemAddress& sysAddr); void SendClientExitTamingMinigame(LWOOBJID objectId, bool bVoluntaryExit, const SystemAddress& sysAddr); diff --git a/dGame/dInventory/Item.cpp b/dGame/dInventory/Item.cpp index 62e198a3..695ab47b 100644 --- a/dGame/dInventory/Item.cpp +++ b/dGame/dInventory/Item.cpp @@ -10,6 +10,9 @@ #include "dLogger.h" #include "EntityManager.h" #include "RenderComponent.h" +#include "PossessableComponent.h" +#include "CharacterComponent.h" +#include "eItemType.h" class Inventory; @@ -71,6 +74,12 @@ Item::Item( id = GeneralUtils::SetBit(id, OBJECT_BIT_CHARACTER); id = GeneralUtils::SetBit(id, OBJECT_BIT_PERSISTENT); + const auto type = static_cast<eItemType>(info->itemType); + + if (type == eItemType::ITEM_TYPE_MOUNT) { + id = GeneralUtils::SetBit(id, OBJECT_BIT_CLIENT); + } + this->id = id; inventory->AddManagedItem(this); @@ -254,49 +263,34 @@ bool Item::Consume() { return success; } -bool Item::UseNonEquip() { - auto* compRegistryTable = CDClientManager::Instance()->GetTable<CDComponentsRegistryTable>("ComponentsRegistry"); - - const auto packageComponentId = compRegistryTable->GetByIDAndType(lot, COMPONENT_TYPE_PACKAGE); - - auto* packCompTable = CDClientManager::Instance()->GetTable<CDPackageComponentTable>("PackageComponent"); - - auto packages = packCompTable->Query([=](const CDPackageComponent entry) {return entry.id == static_cast<uint32_t>(packageComponentId); }); - - const auto success = !packages.empty(); - - auto inventoryComponent = inventory->GetComponent(); - - auto playerEntity = inventoryComponent->GetParent(); - - if (subKey != LWOOBJID_EMPTY) { +void Item::UseNonEquip() { + const auto type = static_cast<eItemType>(info->itemType); + if (type == eItemType::ITEM_TYPE_MOUNT) { + GetInventory()->GetComponent()->HandlePossession(this); + } else if (type == eItemType::ITEM_TYPE_PET_INVENTORY_ITEM && subKey != LWOOBJID_EMPTY) { const auto& databasePet = GetInventory()->GetComponent()->GetDatabasePet(subKey); - if (databasePet.lot != LOT_NULL) { GetInventory()->GetComponent()->SpawnPet(this); - - return true; } - } - if (success && (playerEntity->GetGMLevel() >= eGameMasterLevel::GAME_MASTER_LEVEL_JUNIOR_DEVELOPER || this->GetPreconditionExpression()->Check(playerEntity))) { - auto* entityParent = inventory->GetComponent()->GetParent(); + } else if (type == eItemType::ITEM_TYPE_PACKAGE) { + auto* compRegistryTable = CDClientManager::Instance()->GetTable<CDComponentsRegistryTable>("ComponentsRegistry"); + const auto packageComponentId = compRegistryTable->GetByIDAndType(lot, COMPONENT_TYPE_PACKAGE); + auto* packCompTable = CDClientManager::Instance()->GetTable<CDPackageComponentTable>("PackageComponent"); + auto packages = packCompTable->Query([=](const CDPackageComponent entry) {return entry.id == static_cast<uint32_t>(packageComponentId); }); - for (auto& pack : packages) { - std::unordered_map<LOT, int32_t> result{}; - - result = LootGenerator::Instance().RollLootMatrix(entityParent, pack.LootMatrixIndex); - - if (!inventory->GetComponent()->HasSpaceForLoot(result)) { - return false; + const auto success = !packages.empty(); + if (success) { + auto* entityParent = inventory->GetComponent()->GetParent(); + for (auto& pack : packages) { + std::unordered_map<LOT, int32_t> result{}; + result = LootGenerator::Instance().RollLootMatrix(entityParent, pack.LootMatrixIndex); + if (!inventory->GetComponent()->HasSpaceForLoot(result)) { + } + LootGenerator::Instance().GiveLoot(inventory->GetComponent()->GetParent(), result, eLootSourceType::LOOT_SOURCE_CONSUMPTION); } - - LootGenerator::Instance().GiveLoot(inventory->GetComponent()->GetParent(), result, eLootSourceType::LOOT_SOURCE_CONSUMPTION); + inventory->GetComponent()->RemoveItem(lot, 1); } - Game::logger->Log("Item", "Used (%i)", lot); - inventory->GetComponent()->RemoveItem(lot, 1); } - - return success; } void Item::Disassemble(const eInventoryType inventoryType) { diff --git a/dGame/dInventory/Item.h b/dGame/dInventory/Item.h index 0613ca85..db7e246a 100644 --- a/dGame/dInventory/Item.h +++ b/dGame/dInventory/Item.h @@ -193,9 +193,8 @@ public: /** * Uses this item if its non equip, essentially an interface for the linked GM - * @return whether the use was successful, e.g. the skill was cast */ - bool UseNonEquip(); + void UseNonEquip(); /** * Disassembles the part LOTs of this item back into the inventory, if it has any diff --git a/dGame/dUtilities/SlashCommandHandler.cpp b/dGame/dUtilities/SlashCommandHandler.cpp index b91021de..c6f1da9f 100644 --- a/dGame/dUtilities/SlashCommandHandler.cpp +++ b/dGame/dUtilities/SlashCommandHandler.cpp @@ -419,6 +419,11 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit if ((chatCommand == "playanimation" || chatCommand == "playanim") && args.size() == 1 && entity->GetGMLevel() >= GAME_MASTER_LEVEL_DEVELOPER) { std::u16string anim = GeneralUtils::ASCIIToUTF16(args[0], args[0].size()); GameMessages::SendPlayAnimation(entity, anim); + auto* possessorComponent = entity->GetComponent<PossessorComponent>(); + if (possessorComponent) { + auto* possessedComponent = EntityManager::Instance()->GetEntity(possessorComponent->GetPossessable()); + if (possessedComponent) GameMessages::SendPlayAnimation(possessedComponent, anim); + } } if (chatCommand == "list-spawns" && entity->GetGMLevel() >= GAME_MASTER_LEVEL_DEVELOPER) { @@ -471,12 +476,24 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit auto* controllablePhysicsComponent = entity->GetComponent<ControllablePhysicsComponent>(); - if (controllablePhysicsComponent == nullptr) { - return; - } - + if (!controllablePhysicsComponent) return; controllablePhysicsComponent->SetSpeedMultiplier(boost); + // speedboost possesables + auto possessor = entity->GetComponent<PossessorComponent>(); + if (possessor) { + auto possessedID = possessor->GetPossessable(); + if (possessedID != LWOOBJID_EMPTY) { + auto possessable = EntityManager::Instance()->GetEntity(possessedID); + if (possessable) { + auto* possessControllablePhysicsComponent = possessable->GetComponent<ControllablePhysicsComponent>(); + if (possessControllablePhysicsComponent) { + possessControllablePhysicsComponent->SetSpeedMultiplier(boost); + } + } + } + } + EntityManager::Instance()->SerializeEntity(entity); } @@ -894,21 +911,17 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit ChatPackets::SendSystemMessage(sysAddr, u"Correct usage: /teleport <x> (<y>) <z> - if no Y given, will teleport to the height of the terrain (or any physics object)."); } - auto* possessorComponent = entity->GetComponent<PossessorComponent>(); - if (possessorComponent != nullptr) { + auto* possessorComponent = entity->GetComponent<PossessorComponent>(); + if (possessorComponent) { auto* possassableEntity = EntityManager::Instance()->GetEntity(possessorComponent->GetPossessable()); if (possassableEntity != nullptr) { auto* vehiclePhysicsComponent = possassableEntity->GetComponent<VehiclePhysicsComponent>(); - - if (vehiclePhysicsComponent != nullptr) { + if (vehiclePhysicsComponent) { vehiclePhysicsComponent->SetPosition(pos); - EntityManager::Instance()->SerializeEntity(possassableEntity); - - Game::logger->Log("ClientPackets", "Forced updated vehicle position"); - } + } else GameMessages::SendTeleport(possassableEntity->GetObjectID(), pos, NiQuaternion(), sysAddr); } } } @@ -926,18 +939,12 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit } if (chatCommand == "dismount" && entity->GetGMLevel() >= GAME_MASTER_LEVEL_DEVELOPER) { - PossessorComponent* possessorComponent; - if (entity->TryGetComponent(COMPONENT_TYPE_POSSESSOR, possessorComponent)) { - Entity* vehicle = EntityManager::Instance()->GetEntity(possessorComponent->GetPossessable()); - if (!vehicle) return; - - PossessableComponent* possessableComponent; - if (vehicle->TryGetComponent(COMPONENT_TYPE_POSSESSABLE, possessableComponent)) { - possessableComponent->SetPossessor(LWOOBJID_EMPTY); - possessorComponent->SetPossessable(LWOOBJID_EMPTY); - - EntityManager::Instance()->SerializeEntity(vehicle); - EntityManager::Instance()->SerializeEntity(entity); + auto* possessorComponent = entity->GetComponent<PossessorComponent>(); + if (possessorComponent) { + auto possessableId = possessorComponent->GetPossessable(); + if (possessableId != LWOOBJID_EMPTY) { + auto* possessableEntity = EntityManager::Instance()->GetEntity(possessableId); + if (possessableEntity) possessorComponent->Dismount(possessableEntity, true); } } } @@ -1231,6 +1238,18 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit return; } + auto vehiclePhysicsComponent = newEntity->GetComponent<VehiclePhysicsComponent>(); + if (vehiclePhysicsComponent) { + auto newRot = newEntity->GetRotation(); + auto angles = newRot.GetEulerAngles(); + // make it right side up + angles.x -= PI; + // make it going in the direction of the player + angles.y -= PI; + newRot = NiQuaternion::FromEulerAngles(angles); + newEntity->SetRotation(newRot); + } + EntityManager::Instance()->ConstructEntity(newEntity); } @@ -1520,7 +1539,33 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit return; } - GameMessages::SendVehicleAddPassiveBoostAction(vehicle->GetObjectID(), UNASSIGNED_SYSTEM_ADDRESS); + if (args.size() >= 1) { + float time; + + if (!GeneralUtils::TryParse(args[0], time)) { + ChatPackets::SendSystemMessage(sysAddr, u"Invalid boost time."); + return; + } else { + GameMessages::SendVehicleAddPassiveBoostAction(vehicle->GetObjectID(), UNASSIGNED_SYSTEM_ADDRESS); + entity->AddCallbackTimer(time, [vehicle]() { + if (!vehicle) return; + GameMessages::SendVehicleRemovePassiveBoostAction(vehicle->GetObjectID(), UNASSIGNED_SYSTEM_ADDRESS); + }); + } + } else { + GameMessages::SendVehicleAddPassiveBoostAction(vehicle->GetObjectID(), UNASSIGNED_SYSTEM_ADDRESS); + } + + } + + if ((chatCommand == "unboost") && entity->GetGMLevel() >= GAME_MASTER_LEVEL_DEVELOPER) { + auto* possessorComponent = entity->GetComponent<PossessorComponent>(); + + if (possessorComponent == nullptr) return; + auto* vehicle = EntityManager::Instance()->GetEntity(possessorComponent->GetPossessable()); + + if (vehicle == nullptr) return; + GameMessages::SendVehicleRemovePassiveBoostAction(vehicle->GetObjectID(), UNASSIGNED_SYSTEM_ADDRESS); } if (chatCommand == "activatespawner" && entity->GetGMLevel() >= GAME_MASTER_LEVEL_DEVELOPER && args.size() >= 1) { diff --git a/dNet/ClientPackets.cpp b/dNet/ClientPackets.cpp index b49801cc..39e835d2 100644 --- a/dNet/ClientPackets.cpp +++ b/dNet/ClientPackets.cpp @@ -140,14 +140,19 @@ void ClientPackets::HandleClientPositionUpdate(const SystemAddress& sysAddr, Pac inStream.Read(angVelocity.z); } - bool hasVehicle = false; + bool updateChar = true; if (possessorComponent != nullptr) { auto* possassableEntity = EntityManager::Instance()->GetEntity(possessorComponent->GetPossessable()); if (possassableEntity != nullptr) { - auto* vehiclePhysicsComponent = possassableEntity->GetComponent<VehiclePhysicsComponent>(); + auto* possessableComponent = possassableEntity->GetComponent<PossessableComponent>(); + if (possessableComponent) { + // While possessing something, only update char if we are attached to the thing we are possessing + if (possessableComponent->GetPossessionType() != ePossessionType::ATTACHED_VISIBLE) updateChar = false; + } + auto* vehiclePhysicsComponent = possassableEntity->GetComponent<VehiclePhysicsComponent>(); if (vehiclePhysicsComponent != nullptr) { // This is flipped for whatever reason rotation = NiQuaternion(rotation.z, rotation.y, rotation.x, rotation.w); @@ -160,19 +165,30 @@ void ClientPackets::HandleClientPositionUpdate(const SystemAddress& sysAddr, Pac vehiclePhysicsComponent->SetDirtyVelocity(velocityFlag); vehiclePhysicsComponent->SetAngularVelocity(angVelocity); vehiclePhysicsComponent->SetDirtyAngularVelocity(angVelocityFlag); - - EntityManager::Instance()->SerializeEntity(possassableEntity); - - hasVehicle = true; + } else { + // Need to get the mount's controllable physics + auto* controllablePhysicsComponent = possassableEntity->GetComponent<ControllablePhysicsComponent>(); + if (!controllablePhysicsComponent) return; + controllablePhysicsComponent->SetPosition(position); + controllablePhysicsComponent->SetRotation(rotation); + controllablePhysicsComponent->SetIsOnGround(onGround); + controllablePhysicsComponent->SetIsOnRail(onRail); + controllablePhysicsComponent->SetVelocity(velocity); + controllablePhysicsComponent->SetDirtyVelocity(velocityFlag); + controllablePhysicsComponent->SetAngularVelocity(angVelocity); + controllablePhysicsComponent->SetDirtyAngularVelocity(angVelocityFlag); } + EntityManager::Instance()->SerializeEntity(possassableEntity); } } - if (hasVehicle) { + if (!updateChar) { velocity = NiPoint3::ZERO; angVelocity = NiPoint3::ZERO; } + + // Handle statistics auto* characterComponent = entity->GetComponent<CharacterComponent>(); if (characterComponent != nullptr) { @@ -192,9 +208,7 @@ void ClientPackets::HandleClientPositionUpdate(const SystemAddress& sysAddr, Pac player->SetGhostReferencePoint(position); EntityManager::Instance()->QueueGhostUpdate(player->GetObjectID()); - if (!hasVehicle) { - EntityManager::Instance()->SerializeEntity(entity); - } + if (updateChar) EntityManager::Instance()->SerializeEntity(entity); //TODO: add moving platform stuffs /*bool movingPlatformFlag; diff --git a/docs/Commands.md b/docs/Commands.md index 8cefaa14..95ec28f9 100644 --- a/docs/Commands.md +++ b/docs/Commands.md @@ -63,7 +63,8 @@ These commands are primarily for development and testing. The usage of many of t |teleport|`/teleport <x> (y) <z>`|Teleports you. If no Y is given, you are teleported to the height of the terrain or physics object at (x, z). Alias: `/tele`.|6| |activatespawner|`/activatespawner <spawner name>`|Activates spawner by name.|8| |addmission|`/addmission <mission id>`|Accepts the mission, adding it to your journal.|8| -|boost|`/boost`|Adds a passive boost action if you are in a vehicle.|8| +|boost|`/boost (time)`|Adds a passive boost action if you are in a vehicle. If time is given it will end after that amount of time|8| +|unboost|`/unboost`|Removes a passive vehicle boost|8| |buff|`/buff <id> <duration>`|Applies the buff with the given id for the given number of seconds.|8| |buffme|`/buffme`|Sets health, armor, and imagination to 999.|8| |buffmed|`/buffmed`|Sets health, armor, and imagination to 9.|8| @@ -71,7 +72,7 @@ These commands are primarily for development and testing. The usage of many of t |completemission|`/completemission <mission id>`|Completes the mission, removing it from your journal.|8| |createprivate|`/createprivate <zone id> <clone id> <password>`|Creates a private zone with password.|8| |debugui|`/debugui`|Toggle Debug UI.|8| -|dismount|`/dismount`|Dismounts you from the vehicle.|8| +|dismount|`/dismount`|Dismounts you from the vehicle or mount.|8| |force-save|`/force-save`|While saving to database usually happens on regular intervals and when you disconnect from the server, this command saves your player's data to the database.|8| |freecam|`/freecam`|Toggles freecam mode.|8| |freemoney|`/freemoney <coins>`|Gives coins.|8| From 14d4bf3cc512786eb70ac2553c2f2439221c766c Mon Sep 17 00:00:00 2001 From: Aaron Kimbrell <aronwk.aaron@gmail.com> Date: Fri, 2 Sep 2022 13:49:38 -0500 Subject: [PATCH 76/86] Script for aborting a wbl zone transfer (#766) --- dScripts/CMakeLists.txt | 1 + dScripts/CppScripts.cpp | 8 ++++++++ dScripts/WblGenericZone.cpp | 10 ++++++++++ dScripts/WblGenericZone.h | 10 ++++++++++ 4 files changed, 29 insertions(+) create mode 100644 dScripts/WblGenericZone.cpp create mode 100644 dScripts/WblGenericZone.h diff --git a/dScripts/CMakeLists.txt b/dScripts/CMakeLists.txt index 66e3b65b..0a907a05 100644 --- a/dScripts/CMakeLists.txt +++ b/dScripts/CMakeLists.txt @@ -247,6 +247,7 @@ set(DSCRIPT_SOURCES "ActivityManager.cpp" "WaveBossHammerling.cpp" "WaveBossHorsemen.cpp" "WaveBossSpiderling.cpp" + "WblGenericZone.cpp" "WhFans.cpp" "WildAmbients.cpp" "WishingWellServer.cpp" diff --git a/dScripts/CppScripts.cpp b/dScripts/CppScripts.cpp index 7d114cd3..d313f2f9 100644 --- a/dScripts/CppScripts.cpp +++ b/dScripts/CppScripts.cpp @@ -288,6 +288,9 @@ #include "RockHydrantBroken.h" #include "WhFans.h" +// WBL scripts +#include "WblGenericZone.h" + //Big bad global bc this is a namespace and not a class: InvalidScript* invalidToReturn = new InvalidScript(); std::map<std::string, CppScripts::Script*> m_Scripts; @@ -834,12 +837,17 @@ CppScripts::Script* CppScripts::GetScript(Entity* parent, const std::string& scr script = new BuccaneerValiantShip(); else if (scriptName == "scripts\\EquipmentScripts\\FireFirstSkillonStartup.lua") script = new FireFirstSkillonStartup(); + // FB else if (scriptName == "scripts\\ai\\NS\\WH\\L_ROCKHYDRANT_BROKEN.lua") script = new RockHydrantBroken(); else if (scriptName == "scripts\\ai\\NS\\L_NS_WH_FANS.lua") script = new WhFans(); + // WBL + else if (scriptName == "scripts\\zone\\LUPs\\WBL_generic_zone.lua") + script = new WblGenericZone(); + //Ignore these scripts: else if (scriptName == "scripts\\02_server\\Enemy\\General\\L_SUSPEND_LUA_AI.lua") script = invalidToReturn; diff --git a/dScripts/WblGenericZone.cpp b/dScripts/WblGenericZone.cpp new file mode 100644 index 00000000..5a670d8e --- /dev/null +++ b/dScripts/WblGenericZone.cpp @@ -0,0 +1,10 @@ +#include "WblGenericZone.h" +#include "Player.h" + +void WblGenericZone::OnFireEventServerSide(Entity* self, Entity* sender, std::string args, int32_t param1, int32_t param2, int32_t param3) { + if (args == m_WblAbortMsg) { + if (!sender) return; + auto player = dynamic_cast<Player*>(sender); + if (player) player->SendToZone(m_WblMainZone); + } +} diff --git a/dScripts/WblGenericZone.h b/dScripts/WblGenericZone.h new file mode 100644 index 00000000..55b66e81 --- /dev/null +++ b/dScripts/WblGenericZone.h @@ -0,0 +1,10 @@ +#pragma once +#include "CppScripts.h" +class WblGenericZone : public CppScripts::Script +{ +public: + void OnFireEventServerSide(Entity* self, Entity* sender, std::string args, int32_t param1, int32_t param2, int32_t param3) override; +private: + const LWOMAPID m_WblMainZone = 1600; + const std::string m_WblAbortMsg = "AbortWBLZone"; +}; From c552f46780276ee50e3c632a9b7dbbb9c95f28e4 Mon Sep 17 00:00:00 2001 From: Aaron Kimbrell <aronwk.aaron@gmail.com> Date: Sun, 4 Sep 2022 21:43:16 -0500 Subject: [PATCH 77/86] ignore empty.lua and empty scripts (#769) * ignore empty.lua and empty scripts and return early if it's an ignored script * return it else if logic --- dScripts/CppScripts.cpp | 16 ++++++---------- 1 file changed, 6 insertions(+), 10 deletions(-) diff --git a/dScripts/CppScripts.cpp b/dScripts/CppScripts.cpp index d313f2f9..dce77e4b 100644 --- a/dScripts/CppScripts.cpp +++ b/dScripts/CppScripts.cpp @@ -848,17 +848,13 @@ CppScripts::Script* CppScripts::GetScript(Entity* parent, const std::string& scr else if (scriptName == "scripts\\zone\\LUPs\\WBL_generic_zone.lua") script = new WblGenericZone(); - //Ignore these scripts: - else if (scriptName == "scripts\\02_server\\Enemy\\General\\L_SUSPEND_LUA_AI.lua") - script = invalidToReturn; - else if (scriptName == "scripts\\02_server\\Enemy\\General\\L_BASE_ENEMY_SPIDERLING.lua") - script = invalidToReturn; + // handle invalid script reporting if the path is greater than zero and it's not an ignored script + // information not really needed for sys admins but is for developers else if (script == invalidToReturn) { - if (scriptName.length() > 0) - Game::logger->LogDebug("CppScripts", "Attempted to load CppScript for '%s', but returned InvalidScript.", scriptName.c_str()); - // information not really needed for sys admins but is for developers - - script = invalidToReturn; + if ((scriptName.length() > 0) && !((scriptName == "scripts\\02_server\\Enemy\\General\\L_SUSPEND_LUA_AI.lua") || + (scriptName == "scripts\\02_server\\Enemy\\General\\L_BASE_ENEMY_SPIDERLING.lua") || + (scriptName == "scripts\\empty.lua") + )) Game::logger->LogDebug("CppScripts", "LOT %i attempted to load CppScript for '%s', but returned InvalidScript.", parent->GetLOT(), scriptName.c_str()); } m_Scripts[scriptName] = script; From ce2e6f595b974ce534a695b50657a27d0998a691 Mon Sep 17 00:00:00 2001 From: Jett <55758076+Jettford@users.noreply.github.com> Date: Mon, 5 Sep 2022 23:28:32 +0100 Subject: [PATCH 78/86] Resolve incorrectly marked consumables being unusable (#770) A change was made in the mounts pull request that broke consumables without correctly marked types such as the picnic basket --- dGame/dInventory/Item.cpp | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/dGame/dInventory/Item.cpp b/dGame/dInventory/Item.cpp index 695ab47b..4d4f2686 100644 --- a/dGame/dInventory/Item.cpp +++ b/dGame/dInventory/Item.cpp @@ -272,9 +272,12 @@ void Item::UseNonEquip() { if (databasePet.lot != LOT_NULL) { GetInventory()->GetComponent()->SpawnPet(this); } - } else if (type == eItemType::ITEM_TYPE_PACKAGE) { + } else { auto* compRegistryTable = CDClientManager::Instance()->GetTable<CDComponentsRegistryTable>("ComponentsRegistry"); const auto packageComponentId = compRegistryTable->GetByIDAndType(lot, COMPONENT_TYPE_PACKAGE); + + if (packageComponentId == 0) return; + auto* packCompTable = CDClientManager::Instance()->GetTable<CDPackageComponentTable>("PackageComponent"); auto packages = packCompTable->Query([=](const CDPackageComponent entry) {return entry.id == static_cast<uint32_t>(packageComponentId); }); From 63af2c8da74cbddf5b754fa6ee150c702effadfa Mon Sep 17 00:00:00 2001 From: David Markowitz <39972741+EmosewaMC@users.noreply.github.com> Date: Mon, 5 Sep 2022 20:28:47 -0700 Subject: [PATCH 79/86] Add ZLIB for Windows (#768) Added ZLIB for Windows. Packets for character creation are now compressed on windows before sending and ZCompression can now be used on Windows. --- CMakeLists.txt | 1 - CMakePresets.json | 11 ++++++++--- dCommon/CMakeLists.txt | 30 ++++++++++++++++++++++++++++-- dCommon/ZCompression.cpp | 23 ----------------------- dCommon/ZCompression.h | 5 ----- dNet/WorldPackets.cpp | 26 +++++++++++++++++--------- 6 files changed, 53 insertions(+), 43 deletions(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index 1a977a64..721140a6 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -160,7 +160,6 @@ elseif (UNIX) set(INCLUDED_DIRECTORIES ${INCLUDED_DIRECTORIES} "thirdparty/libbcrypt/include/bcrypt") endif() -include_directories(${ZLIB_INCLUDE_DIRS}) # Add binary directory as an include directory include_directories(${PROJECT_BINARY_DIR}) diff --git a/CMakePresets.json b/CMakePresets.json index 133d6a3c..badb161d 100644 --- a/CMakePresets.json +++ b/CMakePresets.json @@ -115,9 +115,14 @@ "displayName": "CI Tests on windows", "description": "Runs all tests on a windows configuration", "configuration": "RelWithDebInfo", - "execution": { - "jobs": 2 - }, + "execution": { + "jobs": 2 + }, + "filter": { + "exclude": { + "name": "((example)|(minigzip))+" + } + }, "output": { "outputOnFailure": true } diff --git a/dCommon/CMakeLists.txt b/dCommon/CMakeLists.txt index 028eb29f..18fe582c 100644 --- a/dCommon/CMakeLists.txt +++ b/dCommon/CMakeLists.txt @@ -23,5 +23,31 @@ target_link_libraries(dCommon bcrypt) if (UNIX) find_package(ZLIB REQUIRED) - target_link_libraries(dCommon ZLIB::ZLIB) -endif() +elseif (WIN32) + include(FetchContent) + + # TODO Keep an eye on the zlib repository for an update to disable testing. Don't forget to update CMakePresets + FetchContent_Declare( + zlib + URL https://github.com/madler/zlib/archive/refs/tags/v1.2.11.zip + URL_HASH MD5=9d6a627693163bbbf3f26403a3a0b0b1 + ) + + # Disable warning about no project version. + set(CMAKE_POLICY_DEFAULT_CMP0048 NEW) + # Disable warning about the minimum version of cmake used for bcrypt being deprecated in the future + set(CMAKE_WARN_DEPRECATED OFF CACHE BOOL "" FORCE) + + FetchContent_MakeAvailable(zlib) + + set(ZLIB_INCLUDE_DIRS ${zlib_SOURCE_DIR} ${zlib_BINARY_DIR}) + set_target_properties(zlib PROPERTIES INTERFACE_INCLUDE_DIRECTORIES "${ZLIB_INCLUDE_DIRS}") + add_library(ZLIB::ZLIB ALIAS zlib) +else () + message( + FATAL_ERROR + "This platform does not have a way to use zlib.\nCreate an issue on GitHub with your build system so it can be configured." + ) +endif () + +target_link_libraries(dCommon ZLIB::ZLIB) diff --git a/dCommon/ZCompression.cpp b/dCommon/ZCompression.cpp index 70f23500..d5d4c126 100644 --- a/dCommon/ZCompression.cpp +++ b/dCommon/ZCompression.cpp @@ -1,7 +1,5 @@ #include "ZCompression.h" -#ifndef _WIN32 - #include <zlib.h> namespace ZCompression { @@ -27,7 +25,6 @@ namespace ZCompression { } deflateEnd(&zInfo); // zlib function return(nRet); - } int32_t Decompress(const uint8_t* abSrc, int32_t nLenSrc, uint8_t* abDst, int32_t nLenDst, int32_t& nErr) { @@ -48,26 +45,6 @@ namespace ZCompression { } inflateEnd(&zInfo); // zlib function return(nRet); - - /* - z_stream zInfo = { 0 }; - zInfo.total_in = zInfo.avail_in = nLenSrc; - zInfo.total_out = zInfo.avail_out = nLenDst; - zInfo.next_in = const_cast<Bytef*>(abSrc); - zInfo.next_out = const_cast<Bytef*>(abDst); - - int nRet = -1; - nErr = inflateInit(&zInfo); // zlib function - if (nErr == Z_OK) { - nErr = inflate(&zInfo, Z_FINISH); // zlib function - if (nErr == Z_STREAM_END) { - nRet = zInfo.total_out; - } - } - inflateEnd(&zInfo); // zlib function - return(nRet); // -1 or len of output - */ } } -#endif diff --git a/dCommon/ZCompression.h b/dCommon/ZCompression.h index 7b987cfa..22a5ff86 100644 --- a/dCommon/ZCompression.h +++ b/dCommon/ZCompression.h @@ -2,10 +2,6 @@ #include <cstdint> -#include "dPlatforms.h" - -#ifndef DARKFLAME_PLATFORM_WIN32 - namespace ZCompression { int32_t GetMaxCompressedLength(int32_t nLenSrc); @@ -14,4 +10,3 @@ namespace ZCompression { int32_t Decompress(const uint8_t* abSrc, int32_t nLenSrc, uint8_t* abDst, int32_t nLenDst, int32_t& nErr); } -#endif diff --git a/dNet/WorldPackets.cpp b/dNet/WorldPackets.cpp index 23d2c010..f6a8f558 100644 --- a/dNet/WorldPackets.cpp +++ b/dNet/WorldPackets.cpp @@ -164,27 +164,35 @@ void WorldPackets::SendCreateCharacter(const SystemAddress& sysAddr, Entity* ent delete name; delete reputation; -#ifdef _WIN32 - bitStream.Write<uint32_t>(data.GetNumberOfBytesUsed() + 1); - bitStream.Write<uint8_t>(0); - bitStream.Write((char*)data.GetData(), data.GetNumberOfBytesUsed()); -#else //Compress the data before sending: - const int reservedSize = 5 * 1024 * 1024; - uint8_t compressedData[reservedSize]; + const uint32_t reservedSize = ZCompression::GetMaxCompressedLength(data.GetNumberOfBytesUsed()); + uint8_t* compressedData = new uint8_t[reservedSize]; + + // TODO There should be better handling here for not enough memory... + if (!compressedData) return; + size_t size = ZCompression::Compress(data.GetData(), data.GetNumberOfBytesUsed(), compressedData, reservedSize); + assert(size <= reservedSize); + bitStream.Write<uint32_t>(size + 9); //size of data + header bytes (8) bitStream.Write<uint8_t>(1); //compressed boolean, true bitStream.Write<uint32_t>(data.GetNumberOfBytesUsed()); bitStream.Write<uint32_t>(size); + /** + * In practice, this warning serves no purpose for us. We allocate the max memory needed on the heap + * and then compress the data. In the off chance that the compression actually increases the size, + * an assertion is done to prevent bad data from being saved or sent. + */ +#pragma warning(disable:6385) // C6385 Reading invalid data from 'compressedData'. for (size_t i = 0; i < size; i++) bitStream.Write(compressedData[i]); -#endif +#pragma warning(default:6385) - PacketUtils::SavePacket("chardata.bin", (const char*)bitStream.GetData(), static_cast<uint32_t>(bitStream.GetNumberOfBytesUsed())); + // PacketUtils::SavePacket("chardata.bin", (const char*)bitStream.GetData(), static_cast<uint32_t>(bitStream.GetNumberOfBytesUsed())); SEND_PACKET; + delete[] compressedData; Game::logger->Log("WorldPackets", "Sent CreateCharacter for ID: %llu", entity->GetObjectID()); } From 409d682c9d3d43510999f36d213d3f02da9bc456 Mon Sep 17 00:00:00 2001 From: Aaron Kimbrell <aronwk.aaron@gmail.com> Date: Fri, 21 Oct 2022 19:34:38 -0500 Subject: [PATCH 80/86] fix loading scenes in some older formats (#782) This fix is based on lcdr's luzviewer --- dZoneManager/Zone.cpp | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/dZoneManager/Zone.cpp b/dZoneManager/Zone.cpp index 54246c28..9072080a 100644 --- a/dZoneManager/Zone.cpp +++ b/dZoneManager/Zone.cpp @@ -338,10 +338,11 @@ const Path* Zone::GetPath(std::string name) const { void Zone::LoadSceneTransition(std::ifstream& file) { SceneTransition sceneTrans; - if (m_ZoneFileFormatVersion < Zone::ZoneFileFormatVersion::LateAlpha) { + if (m_ZoneFileFormatVersion < Zone::ZoneFileFormatVersion::Auramar) { uint8_t length; BinaryIO::BinaryRead(file, length); sceneTrans.name = BinaryIO::ReadString(file, length); + file.ignore(4); } //BR�THER MAY I HAVE SOME L��PS? From f02e9c0f6a5439ba468a4a6b247d3a2a2a228c7e Mon Sep 17 00:00:00 2001 From: David Markowitz <39972741+EmosewaMC@users.noreply.github.com> Date: Fri, 21 Oct 2022 17:35:12 -0700 Subject: [PATCH 81/86] Address being able to friend yourself (#779) * Address being able to friend yourself Fix an issue where players could friend themselves. Also stops yourself as appearing as a friend on your own friends list. * Send a Response instead Send a MYTHRAN response since the player is attempting to friend a Mythran. --- dChatServer/ChatPacketHandler.cpp | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/dChatServer/ChatPacketHandler.cpp b/dChatServer/ChatPacketHandler.cpp index a51716ca..0f7f6919 100644 --- a/dChatServer/ChatPacketHandler.cpp +++ b/dChatServer/ChatPacketHandler.cpp @@ -33,9 +33,10 @@ void ChatPacketHandler::HandleFriendlistRequest(Packet* packet) { "WHEN friend_id = ? THEN player_id " "END AS requested_player, best_friend FROM friends) AS fr " "JOIN charinfo AS ci ON ci.id = fr.requested_player " - "WHERE fr.requested_player IS NOT NULL;")); + "WHERE fr.requested_player IS NOT NULL AND fr.requested_player != ?;")); stmt->setUInt(1, static_cast<uint32_t>(playerID)); stmt->setUInt(2, static_cast<uint32_t>(playerID)); + stmt->setUInt(3, static_cast<uint32_t>(playerID)); std::vector<FriendData> friends; @@ -113,6 +114,10 @@ void ChatPacketHandler::HandleFriendRequest(Packet* packet) { inStream.Read(isBestFriendRequest); auto requestor = playerContainer.GetPlayerData(requestorPlayerID); + if (requestor->playerName == playerName) { + SendFriendResponse(requestor, requestor, AddFriendResponseType::MYTHRAN); + return; + }; std::unique_ptr<PlayerData> requestee(playerContainer.GetPlayerData(playerName)); // Check if player is online first From 366c3db7fe1b50852df5deebe8cbcec3cacc0bc6 Mon Sep 17 00:00:00 2001 From: Aaron Kimbrell <aronwk.aaron@gmail.com> Date: Sun, 23 Oct 2022 21:54:59 -0500 Subject: [PATCH 82/86] fix reading respawn for older maps (#784) --- dZoneManager/Level.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/dZoneManager/Level.cpp b/dZoneManager/Level.cpp index ebfca4cc..f12adc56 100644 --- a/dZoneManager/Level.cpp +++ b/dZoneManager/Level.cpp @@ -266,7 +266,7 @@ void Level::ReadSceneObjectDataChunk(std::ifstream& file, Header& header) { spawnInfo.respawnTime = std::stof(data->GetValueAsString()); } else if (data->GetValueType() == eLDFType::LDF_TYPE_U32) // Ints are in ms? { - spawnInfo.respawnTime = std::stoi(data->GetValueAsString()) / 1000; + spawnInfo.respawnTime = std::stoul(data->GetValueAsString()) / 1000; } } if (data->GetKey() == u"spawnsGroupOnSmash") { From 8d44f2f5da762b245afcadffbc5c1d6b8ab9fe5d Mon Sep 17 00:00:00 2001 From: Aaron Kimbrell <aronwk.aaron@gmail.com> Date: Mon, 24 Oct 2022 00:54:21 -0500 Subject: [PATCH 83/86] Add missing property path checks for new zones (#783) Co-authored-by: Jett <55758076+Jettford@users.noreply.github.com> --- dZoneManager/Zone.cpp | 56 ++++++++++++++++++++++++++----------------- 1 file changed, 34 insertions(+), 22 deletions(-) diff --git a/dZoneManager/Zone.cpp b/dZoneManager/Zone.cpp index 9072080a..b670849b 100644 --- a/dZoneManager/Zone.cpp +++ b/dZoneManager/Zone.cpp @@ -403,30 +403,42 @@ void Zone::LoadPath(std::ifstream& file) { BinaryIO::BinaryRead(file, path.property.price); BinaryIO::BinaryRead(file, path.property.rentalTime); BinaryIO::BinaryRead(file, path.property.associatedZone); - uint8_t count1; - BinaryIO::BinaryRead(file, count1); - for (uint8_t i = 0; i < count1; ++i) { - uint16_t character; - BinaryIO::BinaryRead(file, character); - path.property.displayName.push_back(character); + + if (path.pathVersion >= 5) { + uint8_t count1; + BinaryIO::BinaryRead(file, count1); + for (uint8_t i = 0; i < count1; ++i) { + uint16_t character; + BinaryIO::BinaryRead(file, character); + path.property.displayName.push_back(character); + } + uint32_t count2; + BinaryIO::BinaryRead(file, count2); + for (uint8_t i = 0; i < count2; ++i) { + uint16_t character; + BinaryIO::BinaryRead(file, character); + path.property.displayDesc.push_back(character); + } } - uint32_t count2; - BinaryIO::BinaryRead(file, count2); - for (uint8_t i = 0; i < count2; ++i) { - uint16_t character; - BinaryIO::BinaryRead(file, character); - path.property.displayDesc.push_back(character); + + if (path.pathVersion >= 6) { + int32_t unknown1; + BinaryIO::BinaryRead(file, unknown1); + } + + if (path.pathVersion >= 7) { + BinaryIO::BinaryRead(file, path.property.cloneLimit); + BinaryIO::BinaryRead(file, path.property.repMultiplier); + BinaryIO::BinaryRead(file, path.property.rentalTimeUnit); + } + + if (path.pathVersion >= 8) { + BinaryIO::BinaryRead(file, path.property.achievementRequired); + BinaryIO::BinaryRead(file, path.property.playerZoneCoords.x); + BinaryIO::BinaryRead(file, path.property.playerZoneCoords.y); + BinaryIO::BinaryRead(file, path.property.playerZoneCoords.z); + BinaryIO::BinaryRead(file, path.property.maxBuildHeight); } - int32_t unknown1; - BinaryIO::BinaryRead(file, unknown1); - BinaryIO::BinaryRead(file, path.property.cloneLimit); - BinaryIO::BinaryRead(file, path.property.repMultiplier); - BinaryIO::BinaryRead(file, path.property.rentalTimeUnit); - BinaryIO::BinaryRead(file, path.property.achievementRequired); - BinaryIO::BinaryRead(file, path.property.playerZoneCoords.x); - BinaryIO::BinaryRead(file, path.property.playerZoneCoords.y); - BinaryIO::BinaryRead(file, path.property.playerZoneCoords.z); - BinaryIO::BinaryRead(file, path.property.maxBuildHeight); } else if (path.pathType == PathType::Camera) { uint8_t count; BinaryIO::BinaryRead(file, count); From c13937bd1f00f1c747b3ba6614bce884a9cc5f9a Mon Sep 17 00:00:00 2001 From: David Markowitz <39972741+EmosewaMC@users.noreply.github.com> Date: Mon, 24 Oct 2022 15:20:36 -0700 Subject: [PATCH 84/86] Address Brick-By-Brick builds not properly saving and make migrations automatic (#725) * Properly store BBB in database Store the BBB data in the database as the received SD0 packet as opposed to just the raw lxfml. Addressed several memory leaks as well. * Add Sd0Conversion Add brick by brick conversion commands with 2 parameters to tell the program what to do with the data. Add zlib -> sd0 conversion. Files look good at a glance but should be tested in game to ensure stability. Tests to come. * moving to laptop ignore this commit. I need to move this to my laptop * Add functionality to delete bad models Adds functionality to delete bad models. Models are batched together and deleted in one commit. More testing is needed to ensure data safety. Positive tests on a live database reveal the broken models were truncated and complete ones were kept around successfully. Tests should be done to ensure larger sd0 models are properly saved and not truncated since this command should be able to be run any time. Valgrind tests need to be run as well to ensure no memory leaks exist. * Delete from query change Changed from delete to delete cascade and instead deleting from properties_contents as opposed to ugc. * Address numerous bugs DELETE CASCADE is not a valid SQL command so this was changed to a better delete statement. Added user confirmation before deleting a broken model. Address appending the string model appending bad data, causing excess deletion. Addressed memory leaks with sql::Blob * Error handling for string * Even more proper handling... * Add bounds check for cli command Output a message if a bad command is used. Update MasterServer.cpp * Remove user interference -Add back in mariadb build jobs so i dont nuke others systems - Remove all user interference and consolidate work into one command since 1 depends on the next. * Add comments test Revert "test" This reverts commit fb831f268b7a2f0ccd20595aff64902ab4f4b4ee. * Update CMakeMariaDBLists.txt Test * Improve migration runner Migration runner now runs automatically. - Resolved an issue where extremely large sql queries caused the database to go into an invalid state. - Made migrations run automatically on server start. - Resolved a tiny memory leak in migration runner? (discarded returned pointer) - Moved sd0 migrations of brick models to be run automatically with migration runner. - Created dummy file to tell when brick migrations have been run. * Update README Updated the README to reflect the new server migration state. * Make model deleter actually delete models My complicated sql actually did nothing... Tested that this new SQL properly gets rid of bad data. * Revert "Update CMakeMariaDBLists.txt" This reverts commit 8b859d8529755d7132cef072b2532589c098f683. --- CMakeVariables.txt | 2 +- README.md | 7 +- dCommon/BrickByBrickFix.cpp | 180 +++++++++++++++++++++++++++ dCommon/BrickByBrickFix.h | 26 ++++ dCommon/CMakeLists.txt | 6 +- dDatabase/Database.cpp | 12 ++ dDatabase/Database.h | 2 + dDatabase/MigrationRunner.cpp | 47 ++++--- dGame/dGameMessages/GameMessages.cpp | 106 ++++------------ dMasterServer/MasterServer.cpp | 110 +++++++--------- dWorldServer/WorldServer.cpp | 9 -- migrations/dlu/5_brick_model_sd0.sql | 1 + 12 files changed, 334 insertions(+), 174 deletions(-) create mode 100644 dCommon/BrickByBrickFix.cpp create mode 100644 dCommon/BrickByBrickFix.h create mode 100644 migrations/dlu/5_brick_model_sd0.sql diff --git a/CMakeVariables.txt b/CMakeVariables.txt index 7a8d6b71..e68e826e 100644 --- a/CMakeVariables.txt +++ b/CMakeVariables.txt @@ -15,6 +15,6 @@ __dynamic=1 # __include_backtrace__=1 # Set __include_backtrace__ to 1 to includes the backtrace library for better crashlogs. # __compile_backtrace__=1 -# Set __compile_backtrace__ to 1 to compile the backtrace library instead of using system libraries. +# Set __compile_backtrace__ to 1 to compile the backtrace library instead of using system libraries. __maria_db_connector_compile_jobs__=1 # Set to the number of jobs (make -j equivalent) to compile the mariadbconn files with. diff --git a/README.md b/README.md index de20e7ad..dfae2bab 100644 --- a/README.md +++ b/README.md @@ -204,15 +204,16 @@ certutil -hashfile <file> SHA256 Darkflame Universe utilizes a MySQL/MariaDB database for account and character information. Initial setup can vary drastically based on which operating system or distribution you are running; there are instructions out there for most setups, follow those and come back here when you have a database up and running. -* Create a database for Darkflame Universe to use + +* All that you need to do is create a database to connect to. As long as the server can connect to the database, the schema will always be kept up to date when you start the server. #### Configuration After the server has been built there should be four `ini` files in the build director: `authconfig.ini`, `chatconfig.ini`, `masterconfig.ini`, and `worldconfig.ini`. Go through them and fill in the database credentials and configure other settings if necessary. -#### Setup and Migrations +#### Migrations -Use the command `./MasterServer -m` to setup the tables in the database. The first time this command is run on a database, the tables will be up to date with the most recent version. To update your database tables, run this command again. Multiple invocations will not affect any functionality. +The database is automatically setup and migrated to what it should look like for the latest commit whenever you start the server. #### Verify diff --git a/dCommon/BrickByBrickFix.cpp b/dCommon/BrickByBrickFix.cpp new file mode 100644 index 00000000..f0c4e824 --- /dev/null +++ b/dCommon/BrickByBrickFix.cpp @@ -0,0 +1,180 @@ +#include "BrickByBrickFix.h" + +#include <memory> +#include <iostream> +#include <sstream> + +#include "tinyxml2.h" + +#include "Database.h" +#include "Game.h" +#include "ZCompression.h" +#include "dLogger.h" + +//! Forward declarations + +std::unique_ptr<sql::ResultSet> GetModelsFromDatabase(); +void WriteSd0Magic(char* input, uint32_t chunkSize); +bool CheckSd0Magic(sql::Blob* streamToCheck); + +/** + * @brief Truncates all models with broken data from the database. + * + * @return The number of models deleted + */ +uint32_t BrickByBrickFix::TruncateBrokenBrickByBrickXml() { + uint32_t modelsTruncated{}; + auto modelsToTruncate = GetModelsFromDatabase(); + bool previousCommitValue = Database::GetAutoCommit(); + Database::SetAutoCommit(false); + while (modelsToTruncate->next()) { + std::unique_ptr<sql::PreparedStatement> ugcModelToDelete(Database::CreatePreppedStmt("DELETE FROM ugc WHERE ugc.id = ?;")); + std::unique_ptr<sql::PreparedStatement> pcModelToDelete(Database::CreatePreppedStmt("DELETE FROM properties_contents WHERE ugc_id = ?;")); + std::string completeUncompressedModel{}; + uint32_t chunkCount{}; + uint64_t modelId = modelsToTruncate->getInt(1); + std::unique_ptr<sql::Blob> modelAsSd0(modelsToTruncate->getBlob(2)); + // Check that header is sd0 by checking for the sd0 magic. + if (CheckSd0Magic(modelAsSd0.get())) { + while (true) { + uint32_t chunkSize{}; + modelAsSd0->read(reinterpret_cast<char*>(&chunkSize), sizeof(uint32_t)); // Extract chunk size from istream + + // Check if good here since if at the end of an sd0 file, this will have eof flagged. + if (!modelAsSd0->good()) break; + + std::unique_ptr<uint8_t[]> compressedChunk(new uint8_t[chunkSize]); + for (uint32_t i = 0; i < chunkSize; i++) { + compressedChunk[i] = modelAsSd0->get(); + } + + // Ignore the valgrind warning about uninitialized values. These are discarded later when we know the actual uncompressed size. + std::unique_ptr<uint8_t[]> uncompressedChunk(new uint8_t[MAX_SD0_CHUNK_SIZE]); + int32_t err{}; + int32_t actualUncompressedSize = ZCompression::Decompress( + compressedChunk.get(), chunkSize, uncompressedChunk.get(), MAX_SD0_CHUNK_SIZE, err); + + if (actualUncompressedSize != -1) { + uint32_t previousSize = completeUncompressedModel.size(); + completeUncompressedModel.append((char*)uncompressedChunk.get()); + completeUncompressedModel.resize(previousSize + actualUncompressedSize); + } else { + Game::logger->Log("BrickByBrickFix", "Failed to inflate chunk %i for model %llu. Error: %i", chunkCount, modelId, err); + break; + } + chunkCount++; + } + std::unique_ptr<tinyxml2::XMLDocument> document = std::make_unique<tinyxml2::XMLDocument>(); + if (!document) { + Game::logger->Log("BrickByBrickFix", "Failed to initialize tinyxml document. Aborting."); + return 0; + } + + if (!(document->Parse(completeUncompressedModel.c_str(), completeUncompressedModel.size()) == tinyxml2::XML_SUCCESS)) { + if (completeUncompressedModel.find( + "</LXFML>", + completeUncompressedModel.length() >= 15 ? completeUncompressedModel.length() - 15 : 0) == std::string::npos + ) { + Game::logger->Log("BrickByBrickFix", + "Brick-by-brick model %llu will be deleted!", modelId); + ugcModelToDelete->setInt64(1, modelsToTruncate->getInt64(1)); + pcModelToDelete->setInt64(1, modelsToTruncate->getInt64(1)); + ugcModelToDelete->execute(); + pcModelToDelete->execute(); + modelsTruncated++; + } + } + } else { + Game::logger->Log("BrickByBrickFix", + "Brick-by-brick model %llu will be deleted!", modelId); + ugcModelToDelete->setInt64(1, modelsToTruncate->getInt64(1)); + pcModelToDelete->setInt64(1, modelsToTruncate->getInt64(1)); + ugcModelToDelete->execute(); + pcModelToDelete->execute(); + modelsTruncated++; + } + } + + Database::Commit(); + Database::SetAutoCommit(previousCommitValue); + return modelsTruncated; +} + +/** + * @brief Updates all current models in the database to have the Segmented Data 0 (SD0) format. + * Any models that do not start with zlib and best compression magic will not be updated. + * + * @return The number of models updated to SD0 + */ +uint32_t BrickByBrickFix::UpdateBrickByBrickModelsToSd0() { + uint32_t updatedModels = 0; + auto modelsToUpdate = GetModelsFromDatabase(); + auto previousAutoCommitState = Database::GetAutoCommit(); + Database::SetAutoCommit(false); + std::unique_ptr<sql::PreparedStatement> insertionStatement(Database::CreatePreppedStmt("UPDATE ugc SET lxfml = ? WHERE id = ?;")); + while (modelsToUpdate->next()) { + int64_t modelId = modelsToUpdate->getInt64(1); + std::unique_ptr<sql::Blob> oldLxfml(modelsToUpdate->getBlob(2)); + // Check if the stored blob starts with zlib magic (0x78 0xDA - best compression of zlib) + // If it does, convert it to sd0. + if (oldLxfml->get() == 0x78 && oldLxfml->get() == 0xDA) { + + // Get and save size of zlib compressed chunk. + oldLxfml->seekg(0, std::ios::end); + uint32_t oldLxfmlSize = static_cast<uint32_t>(oldLxfml->tellg()); + oldLxfml->seekg(0); + + // Allocate 9 extra bytes. 5 for sd0 magic, 4 for the only zlib compressed size. + uint32_t oldLxfmlSizeWithHeader = oldLxfmlSize + 9; + std::unique_ptr<char[]> sd0ConvertedModel(new char[oldLxfmlSizeWithHeader]); + + WriteSd0Magic(sd0ConvertedModel.get(), oldLxfmlSize); + for (uint32_t i = 9; i < oldLxfmlSizeWithHeader; i++) { + sd0ConvertedModel.get()[i] = oldLxfml->get(); + } + + std::string outputString(sd0ConvertedModel.get(), oldLxfmlSizeWithHeader); + std::istringstream outputStringStream(outputString); + + insertionStatement->setBlob(1, static_cast<std::istream*>(&outputStringStream)); + insertionStatement->setInt64(2, modelId); + try { + insertionStatement->executeUpdate(); + Game::logger->Log("BrickByBrickFix", "Updated model %i to sd0", modelId); + updatedModels++; + } catch (sql::SQLException exception) { + Game::logger->Log( + "BrickByBrickFix", + "Failed to update model %i. This model should be inspected manually to see why." + "The database error is %s", modelId, exception.what()); + } + } + } + Database::Commit(); + Database::SetAutoCommit(previousAutoCommitState); + return updatedModels; +} + +std::unique_ptr<sql::ResultSet> GetModelsFromDatabase() { + std::unique_ptr<sql::PreparedStatement> modelsRawDataQuery(Database::CreatePreppedStmt("SELECT id, lxfml FROM ugc;")); + return std::unique_ptr<sql::ResultSet>(modelsRawDataQuery->executeQuery()); +} + +/** + * @brief Writes sd0 magic at the front of a char* + * + * @param input the char* to write at the front of + * @param chunkSize The size of the first chunk to write the size of + */ +void WriteSd0Magic(char* input, uint32_t chunkSize) { + input[0] = 's'; + input[1] = 'd'; + input[2] = '0'; + input[3] = 0x01; + input[4] = 0xFF; + *reinterpret_cast<uint32_t*>(input + 5) = chunkSize; // Write the integer to the character array +} + +bool CheckSd0Magic(sql::Blob* streamToCheck) { + return streamToCheck->get() == 's' && streamToCheck->get() == 'd' && streamToCheck->get() == '0' && streamToCheck->get() == 0x01 && streamToCheck->get() == 0xFF; +} diff --git a/dCommon/BrickByBrickFix.h b/dCommon/BrickByBrickFix.h new file mode 100644 index 00000000..0c7e314c --- /dev/null +++ b/dCommon/BrickByBrickFix.h @@ -0,0 +1,26 @@ +#pragma once + +#include <cstdint> + +namespace BrickByBrickFix { + /** + * @brief Deletes all broken BrickByBrick models that have invalid XML + * + * @return The number of BrickByBrick models that were truncated + */ + uint32_t TruncateBrokenBrickByBrickXml(); + + /** + * @brief Updates all BrickByBrick models in the database to be + * in the sd0 format as opposed to a zlib compressed format. + * + * @return The number of BrickByBrick models that were updated + */ + uint32_t UpdateBrickByBrickModelsToSd0(); + + /** + * @brief Max size of an inflated sd0 zlib chunk + * + */ + constexpr uint32_t MAX_SD0_CHUNK_SIZE = 1024 * 256; +}; diff --git a/dCommon/CMakeLists.txt b/dCommon/CMakeLists.txt index 18fe582c..cb73bf6a 100644 --- a/dCommon/CMakeLists.txt +++ b/dCommon/CMakeLists.txt @@ -13,13 +13,15 @@ set(DCOMMON_SOURCES "AMFFormat.cpp" "NiQuaternion.cpp" "SHA512.cpp" "Type.cpp" - "ZCompression.cpp") + "ZCompression.cpp" + "BrickByBrickFix.cpp" +) include_directories(${PROJECT_SOURCE_DIR}/dCommon/) add_library(dCommon STATIC ${DCOMMON_SOURCES}) -target_link_libraries(dCommon bcrypt) +target_link_libraries(dCommon bcrypt dDatabase tinyxml2) if (UNIX) find_package(ZLIB REQUIRED) diff --git a/dDatabase/Database.cpp b/dDatabase/Database.cpp index f955bd43..c301cbd9 100644 --- a/dDatabase/Database.cpp +++ b/dDatabase/Database.cpp @@ -83,3 +83,15 @@ sql::PreparedStatement* Database::CreatePreppedStmt(const std::string& query) { void Database::Commit() { Database::con->commit(); } + +bool Database::GetAutoCommit() { + // TODO This should not just access a pointer. A future PR should update this + // to check for null and throw an error if the connection is not valid. + return con->getAutoCommit(); +} + +void Database::SetAutoCommit(bool value) { + // TODO This should not just access a pointer. A future PR should update this + // to check for null and throw an error if the connection is not valid. + Database::con->setAutoCommit(value); +} diff --git a/dDatabase/Database.h b/dDatabase/Database.h index a15ba856..f4d13da3 100644 --- a/dDatabase/Database.h +++ b/dDatabase/Database.h @@ -23,6 +23,8 @@ public: static sql::Statement* CreateStmt(); static sql::PreparedStatement* CreatePreppedStmt(const std::string& query); static void Commit(); + static bool GetAutoCommit(); + static void SetAutoCommit(bool value); static std::string GetDatabase() { return database; } static sql::Properties GetProperties() { return props; } diff --git a/dDatabase/MigrationRunner.cpp b/dDatabase/MigrationRunner.cpp index 30a63896..1eb03887 100644 --- a/dDatabase/MigrationRunner.cpp +++ b/dDatabase/MigrationRunner.cpp @@ -1,5 +1,6 @@ #include "MigrationRunner.h" +#include "BrickByBrickFix.h" #include "GeneralUtils.h" #include <fstream> @@ -7,13 +8,13 @@ #include <thread> void MigrationRunner::RunMigrations() { - auto stmt = Database::CreatePreppedStmt("CREATE TABLE IF NOT EXISTS migration_history (name TEXT NOT NULL, date TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP());"); - stmt->executeQuery(); + auto* stmt = Database::CreatePreppedStmt("CREATE TABLE IF NOT EXISTS migration_history (name TEXT NOT NULL, date TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP());"); + stmt->execute(); delete stmt; sql::SQLString finalSQL = ""; Migration checkMigration{}; - + bool runSd0Migrations = false; for (const auto& entry : GeneralUtils::GetFileNamesFromFolder("./migrations/")) { auto migration = LoadMigration(entry); @@ -25,16 +26,18 @@ void MigrationRunner::RunMigrations() { stmt = Database::CreatePreppedStmt("SELECT name FROM migration_history WHERE name = ?;"); stmt->setString(1, migration.name); - auto res = stmt->executeQuery(); + auto* res = stmt->executeQuery(); bool doExit = res->next(); delete res; delete stmt; if (doExit) continue; Game::logger->Log("MigrationRunner", "Running migration: %s", migration.name.c_str()); - - finalSQL.append(migration.data); - finalSQL.append('\n'); + if (migration.name == "5_brick_model_sd0.sql") { + runSd0Migrations = true; + } else { + finalSQL.append(migration.data); + } stmt = Database::CreatePreppedStmt("INSERT INTO migration_history (name) VALUES (?);"); stmt->setString(1, entry); @@ -42,15 +45,31 @@ void MigrationRunner::RunMigrations() { delete stmt; } + if (finalSQL.empty() && !runSd0Migrations) { + Game::logger->Log("MigrationRunner", "Server database is up to date."); + return; + } + if (!finalSQL.empty()) { - try { - auto simpleStatement = Database::CreateStmt(); - simpleStatement->execute(finalSQL); - delete simpleStatement; - } catch (sql::SQLException e) { - Game::logger->Log("MigrationRunner", "Encountered error running migration: %s", e.what()); + auto migration = GeneralUtils::SplitString(static_cast<std::string>(finalSQL), ';'); + std::unique_ptr<sql::Statement> simpleStatement(Database::CreateStmt()); + for (auto& query : migration) { + try { + if (query.empty()) continue; + simpleStatement->execute(query); + } catch (sql::SQLException& e) { + Game::logger->Log("MigrationRunner", "Encountered error running migration: %s", e.what()); + } } } + + // Do this last on the off chance none of the other migrations have been run yet. + if (runSd0Migrations) { + uint32_t numberOfUpdatedModels = BrickByBrickFix::UpdateBrickByBrickModelsToSd0(); + Game::logger->Log("MasterServer", "%i models were updated from zlib to sd0.", numberOfUpdatedModels); + uint32_t numberOfTruncatedModels = BrickByBrickFix::TruncateBrokenBrickByBrickXml(); + Game::logger->Log("MasterServer", "%i models were truncated from the database.", numberOfTruncatedModels); + } } Migration MigrationRunner::LoadMigration(std::string path) { @@ -58,8 +77,6 @@ Migration MigrationRunner::LoadMigration(std::string path) { std::ifstream file("./migrations/" + path); if (file.is_open()) { - std::hash<std::string> hash; - std::string line; std::string total = ""; diff --git a/dGame/dGameMessages/GameMessages.cpp b/dGame/dGameMessages/GameMessages.cpp index 772cb691..48b2a508 100644 --- a/dGame/dGameMessages/GameMessages.cpp +++ b/dGame/dGameMessages/GameMessages.cpp @@ -2401,63 +2401,25 @@ void GameMessages::HandleControlBehaviors(RakNet::BitStream* inStream, Entity* e } void GameMessages::HandleBBBSaveRequest(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr) { - /* - ___ ___ - /\ /\___ _ __ ___ / __\ ___ / \_ __ __ _ __ _ ___ _ __ ___ - / /_/ / _ \ '__/ _ \ /__\/// _ \ / /\ / '__/ _` |/ _` |/ _ \| '_ \/ __| - / __ / __/ | | __/ / \/ \ __/ / /_//| | | (_| | (_| | (_) | | | \__ \ - \/ /_/ \___|_| \___| \_____/\___| /___,' |_| \__,_|\__, |\___/|_| |_|___/ - |___/ - ___ _ - / __\ _____ ____ _ _ __ ___ / \ - /__\/// _ \ \ /\ / / _` | '__/ _ \/ / - / \/ \ __/\ V V / (_| | | | __/\_/ - \_____/\___| \_/\_/ \__,_|_| \___\/ - - <>=======() - (/\___ /|\\ ()==========<>_ - \_/ | \\ //|\ ______/ \) - \_| \\ // | \_/ - \|\/|\_ // /\/ - (oo)\ \_// / - //_/\_\/ / | - @@/ |=\ \ | - \_=\_ \ | - \==\ \|\_ snd - __(\===\( )\ - (((~) __(_/ | - (((~) \ / - ______/ / - '------' - */ - - //First, we have Wincent's clean methods of reading in the data received from the client. LWOOBJID localId; - uint32_t timeTaken; inStream->Read(localId); - uint32_t ld0Size; - inStream->Read(ld0Size); - for (auto i = 0; i < 5; ++i) { - uint8_t c; - inStream->Read(c); - } + uint32_t sd0Size; + inStream->Read(sd0Size); + std::shared_ptr<char[]> sd0Data(new char[sd0Size]); - uint32_t lxfmlSize; - inStream->Read(lxfmlSize); - uint8_t* inData = static_cast<uint8_t*>(std::malloc(lxfmlSize)); - - if (inData == nullptr) { + if (sd0Data == nullptr) { return; } - for (uint32_t i = 0; i < lxfmlSize; ++i) { + for (uint32_t i = 0; i < sd0Size; ++i) { uint8_t c; inStream->Read(c); - inData[i] = c; + sd0Data[i] = c; } + uint32_t timeTaken; inStream->Read(timeTaken); /* @@ -2469,6 +2431,8 @@ void GameMessages::HandleBBBSaveRequest(RakNet::BitStream* inStream, Entity* ent Note, in the live client it'll still display the bricks going out as they're being used, but on relog/world change, they reappear as we didn't take them. + + TODO Apparently the bricks are supposed to be taken via MoveInventoryBatch? */ ////Decompress the SD0 from the client so we can process the lxfml properly @@ -2513,9 +2477,7 @@ void GameMessages::HandleBBBSaveRequest(RakNet::BitStream* inStream, Entity* ent auto result = query.execQuery(); - if (result.eof() || result.fieldIsNull(0)) { - return; - } + if (result.eof() || result.fieldIsNull(0)) return; int templateId = result.getIntField(0); @@ -2533,6 +2495,7 @@ void GameMessages::HandleBBBSaveRequest(RakNet::BitStream* inStream, Entity* ent propertyId = propertyEntry->getUInt64(1); } + delete propertyEntry; delete propertyLookup; //Insert into ugc: @@ -2543,7 +2506,7 @@ void GameMessages::HandleBBBSaveRequest(RakNet::BitStream* inStream, Entity* ent ugcs->setInt(4, 0); //whacky stream biz - std::string s((char*)inData, lxfmlSize); + std::string s(sd0Data.get(), sd0Size); std::istringstream iss(s); std::istream& stream = iss; @@ -2558,14 +2521,14 @@ void GameMessages::HandleBBBSaveRequest(RakNet::BitStream* inStream, Entity* ent stmt->setUInt64(1, newIDL); stmt->setUInt64(2, propertyId); stmt->setUInt(3, blueprintIDSmall); - stmt->setUInt(4, 14); //14 is the lot the BBB models use - stmt->setDouble(5, 0.0f); //x - stmt->setDouble(6, 0.0f); //y - stmt->setDouble(7, 0.0f); //z - stmt->setDouble(8, 0.0f); - stmt->setDouble(9, 0.0f); - stmt->setDouble(10, 0.0f); - stmt->setDouble(11, 0.0f); + stmt->setUInt(4, 14); // 14 is the lot the BBB models use + stmt->setDouble(5, 0.0f); // x + stmt->setDouble(6, 0.0f); // y + stmt->setDouble(7, 0.0f); // z + stmt->setDouble(8, 0.0f); // rx + stmt->setDouble(9, 0.0f); // ry + stmt->setDouble(10, 0.0f); // rz + stmt->setDouble(11, 0.0f); // rw stmt->execute(); delete stmt; @@ -2591,38 +2554,22 @@ void GameMessages::HandleBBBSaveRequest(RakNet::BitStream* inStream, Entity* ent //Tell the client their model is saved: (this causes us to actually pop out of our current state): CBITSTREAM; - PacketUtils::WriteHeader(bitStream, CLIENT, MSG_CLIENT_BLUEPRINT_SAVE_RESPONSE); + PacketUtils::WriteHeader(bitStream, CLIENT, CLIENT::MSG_CLIENT_BLUEPRINT_SAVE_RESPONSE); bitStream.Write(localId); bitStream.Write<unsigned int>(0); bitStream.Write<unsigned int>(1); bitStream.Write(blueprintID); - bitStream.Write(lxfmlSize + 9); + bitStream.Write<uint32_t>(sd0Size); - //Write a fake sd0 header: - bitStream.Write<unsigned char>(0x73); //s - bitStream.Write<unsigned char>(0x64); //d - bitStream.Write<unsigned char>(0x30); //0 - bitStream.Write<unsigned char>(0x01); //1 - bitStream.Write<unsigned char>(0xFF); //end magic - - bitStream.Write(lxfmlSize); - - for (size_t i = 0; i < lxfmlSize; ++i) - bitStream.Write(inData[i]); + for (size_t i = 0; i < sd0Size; ++i) { + bitStream.Write(sd0Data[i]); + } SEND_PACKET; - PacketUtils::SavePacket("MSG_CLIENT_BLUEPRINT_SAVE_RESPONSE.bin", (char*)bitStream.GetData(), bitStream.GetNumberOfBytesUsed()); + // PacketUtils::SavePacket("MSG_CLIENT_BLUEPRINT_SAVE_RESPONSE.bin", (char*)bitStream.GetData(), bitStream.GetNumberOfBytesUsed()); //Now we have to construct this object: - /* - * This needs to be sent as config data, but I don't know how to right now. - 'blueprintid': (9, 1152921508346399522), - 'componentWhitelist': (1, 1), - 'modelType': (1, 2), - 'propertyObjectID': (7, True), - 'userModelID': (9, 1152921510759098799) - */ EntityInfo info; info.lot = 14; @@ -2653,6 +2600,7 @@ void GameMessages::HandleBBBSaveRequest(RakNet::BitStream* inStream, Entity* ent //there was an issue with builds not appearing since it was placed above ConstructEntity. PropertyManagementComponent::Instance()->AddModel(newEntity->GetObjectID(), newIDL); } + }); }); }); diff --git a/dMasterServer/MasterServer.cpp b/dMasterServer/MasterServer.cpp index a692e826..538fb749 100644 --- a/dMasterServer/MasterServer.cpp +++ b/dMasterServer/MasterServer.cpp @@ -85,71 +85,51 @@ int main(int argc, char** argv) { Game::logger->SetLogToConsole(bool(std::stoi(config.GetValue("log_to_console")))); Game::logger->SetLogDebugStatements(config.GetValue("log_debug_statements") == "1"); - if (argc > 1 && (strcmp(argv[1], "-m") == 0 || strcmp(argv[1], "--migrations") == 0)) { - //Connect to the MySQL Database - std::string mysql_host = config.GetValue("mysql_host"); - std::string mysql_database = config.GetValue("mysql_database"); - std::string mysql_username = config.GetValue("mysql_username"); - std::string mysql_password = config.GetValue("mysql_password"); + //Connect to the MySQL Database + std::string mysql_host = config.GetValue("mysql_host"); + std::string mysql_database = config.GetValue("mysql_database"); + std::string mysql_username = config.GetValue("mysql_username"); + std::string mysql_password = config.GetValue("mysql_password"); - try { - Database::Connect(mysql_host, mysql_database, mysql_username, mysql_password); - } catch (sql::SQLException& ex) { - Game::logger->Log("MasterServer", "Got an error while connecting to the database: %s", ex.what()); - Game::logger->Log("MigrationRunner", "Migrations not run"); - return EXIT_FAILURE; - } - - MigrationRunner::RunMigrations(); - Game::logger->Log("MigrationRunner", "Finished running migrations"); - - return EXIT_SUCCESS; - } else { - - //Check CDClient exists - const std::string cdclient_path = "./res/CDServer.sqlite"; - std::ifstream cdclient_fd(cdclient_path); - if (!cdclient_fd.good()) { - Game::logger->Log("WorldServer", "%s could not be opened", cdclient_path.c_str()); - return EXIT_FAILURE; - } - cdclient_fd.close(); - - //Connect to CDClient - try { - CDClientDatabase::Connect(cdclient_path); - } catch (CppSQLite3Exception& e) { - Game::logger->Log("WorldServer", "Unable to connect to CDServer SQLite Database"); - Game::logger->Log("WorldServer", "Error: %s", e.errorMessage()); - Game::logger->Log("WorldServer", "Error Code: %i", e.errorCode()); - return EXIT_FAILURE; - } - - //Get CDClient initial information - try { - CDClientManager::Instance()->Initialize(); - } catch (CppSQLite3Exception& e) { - Game::logger->Log("WorldServer", "Failed to initialize CDServer SQLite Database"); - Game::logger->Log("WorldServer", "May be caused by corrupted file: %s", cdclient_path.c_str()); - Game::logger->Log("WorldServer", "Error: %s", e.errorMessage()); - Game::logger->Log("WorldServer", "Error Code: %i", e.errorCode()); - return EXIT_FAILURE; - } - - //Connect to the MySQL Database - std::string mysql_host = config.GetValue("mysql_host"); - std::string mysql_database = config.GetValue("mysql_database"); - std::string mysql_username = config.GetValue("mysql_username"); - std::string mysql_password = config.GetValue("mysql_password"); - - try { - Database::Connect(mysql_host, mysql_database, mysql_username, mysql_password); - } catch (sql::SQLException& ex) { - Game::logger->Log("MasterServer", "Got an error while connecting to the database: %s", ex.what()); - return EXIT_FAILURE; - } + try { + Database::Connect(mysql_host, mysql_database, mysql_username, mysql_password); + } catch (sql::SQLException& ex) { + Game::logger->Log("MasterServer", "Got an error while connecting to the database: %s", ex.what()); + Game::logger->Log("MigrationRunner", "Migrations not run"); + return EXIT_FAILURE; } + MigrationRunner::RunMigrations(); + + //Check CDClient exists + const std::string cdclient_path = "./res/CDServer.sqlite"; + std::ifstream cdclient_fd(cdclient_path); + if (!cdclient_fd.good()) { + Game::logger->Log("WorldServer", "%s could not be opened", cdclient_path.c_str()); + return EXIT_FAILURE; + } + cdclient_fd.close(); + + //Connect to CDClient + try { + CDClientDatabase::Connect(cdclient_path); + } catch (CppSQLite3Exception& e) { + Game::logger->Log("WorldServer", "Unable to connect to CDServer SQLite Database"); + Game::logger->Log("WorldServer", "Error: %s", e.errorMessage()); + Game::logger->Log("WorldServer", "Error Code: %i", e.errorCode()); + return EXIT_FAILURE; + } + + //Get CDClient initial information + try { + CDClientManager::Instance()->Initialize(); + } catch (CppSQLite3Exception& e) { + Game::logger->Log("WorldServer", "Failed to initialize CDServer SQLite Database"); + Game::logger->Log("WorldServer", "May be caused by corrupted file: %s", cdclient_path.c_str()); + Game::logger->Log("WorldServer", "Error: %s", e.errorMessage()); + Game::logger->Log("WorldServer", "Error Code: %i", e.errorCode()); + return EXIT_FAILURE; + } //If the first command line argument is -a or --account then make the user //input a username and password, with the password being hidden. @@ -825,9 +805,9 @@ void ShutdownSequence() { int FinalizeShutdown() { //Delete our objects here: Database::Destroy("MasterServer"); - delete Game::im; - delete Game::server; - delete Game::logger; + if (Game::im) delete Game::im; + if (Game::server) delete Game::server; + if (Game::logger) delete Game::logger; exit(EXIT_SUCCESS); return EXIT_SUCCESS; diff --git a/dWorldServer/WorldServer.cpp b/dWorldServer/WorldServer.cpp index 495053fa..89243d59 100644 --- a/dWorldServer/WorldServer.cpp +++ b/dWorldServer/WorldServer.cpp @@ -1069,15 +1069,6 @@ void HandlePacket(Packet* packet) { bitStream.Write<unsigned int>(1); bitStream.Write(blueprintID); - bitStream.Write<uint32_t>(lxfmlSize + 9); - - //Write a fake sd0 header: - bitStream.Write<unsigned char>(0x73); //s - bitStream.Write<unsigned char>(0x64); //d - bitStream.Write<unsigned char>(0x30); //0 - bitStream.Write<unsigned char>(0x01); //1 - bitStream.Write<unsigned char>(0xFF); //end magic - bitStream.Write<uint32_t>(lxfmlSize); for (size_t i = 0; i < lxfmlSize; ++i) diff --git a/migrations/dlu/5_brick_model_sd0.sql b/migrations/dlu/5_brick_model_sd0.sql new file mode 100644 index 00000000..895f8b34 --- /dev/null +++ b/migrations/dlu/5_brick_model_sd0.sql @@ -0,0 +1 @@ +# This file is here as a mock. The real migration is located in BrickByBrickFix.cpp From 2bdbf129cf6b801d4e95892103b83778d3bcd91b Mon Sep 17 00:00:00 2001 From: Demetri Van Sickle <demetriv.s.7@gmail.com> Date: Tue, 25 Oct 2022 13:32:46 -0700 Subject: [PATCH 85/86] removed migration runner from build script (#788) --- build.sh | 2 -- 1 file changed, 2 deletions(-) diff --git a/build.sh b/build.sh index e61c1cb4..4a476cc1 100755 --- a/build.sh +++ b/build.sh @@ -8,5 +8,3 @@ cmake .. # To build utilizing multiple cores, append `-j` and the amount of cores to utilize, for example `cmake --build . --config Release -j8' cmake --build . --config Release -# Run migrations -./MasterServer -m From d8e73def9dad6b130de9dec2c09fbdfa7b356d37 Mon Sep 17 00:00:00 2001 From: David Markowitz <39972741+EmosewaMC@users.noreply.github.com> Date: Sat, 29 Oct 2022 01:12:29 -0700 Subject: [PATCH 86/86] Update GameMessages.cpp (#793) --- dGame/dGameMessages/GameMessages.cpp | 28 ++++++++++++++++++++++++++++ 1 file changed, 28 insertions(+) diff --git a/dGame/dGameMessages/GameMessages.cpp b/dGame/dGameMessages/GameMessages.cpp index 48b2a508..4efbd286 100644 --- a/dGame/dGameMessages/GameMessages.cpp +++ b/dGame/dGameMessages/GameMessages.cpp @@ -2401,6 +2401,34 @@ void GameMessages::HandleControlBehaviors(RakNet::BitStream* inStream, Entity* e } void GameMessages::HandleBBBSaveRequest(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr) { + /* + ___ ___ + /\ /\___ _ __ ___ / __\ ___ / \_ __ __ _ __ _ ___ _ __ ___ + / /_/ / _ \ '__/ _ \ /__\/// _ \ / /\ / '__/ _` |/ _` |/ _ \| '_ \/ __| + / __ / __/ | | __/ / \/ \ __/ / /_//| | | (_| | (_| | (_) | | | \__ \ + \/ /_/ \___|_| \___| \_____/\___| /___,' |_| \__,_|\__, |\___/|_| |_|___/ + |___/ + ___ _ + / __\ _____ ____ _ _ __ ___ / \ + /__\/// _ \ \ /\ / / _` | '__/ _ \/ / + / \/ \ __/\ V V / (_| | | | __/\_/ + \_____/\___| \_/\_/ \__,_|_| \___\/ + <>=======() + (/\___ /|\\ ()==========<>_ + \_/ | \\ //|\ ______/ \) + \_| \\ // | \_/ + \|\/|\_ // /\/ + (oo)\ \_// / + //_/\_\/ / | + @@/ |=\ \ | + \_=\_ \ | + \==\ \|\_ snd + __(\===\( )\ + (((~) __(_/ | + (((~) \ / + ______/ / + '------' + */ LWOOBJID localId; inStream->Read(localId);