diff --git a/README.md b/README.md index d40f71ce2..71c4cea9e 100644 --- a/README.md +++ b/README.md @@ -164,7 +164,17 @@ locally. See [docs/UgcServer.md](docs/UgcServer.md). * `bind_ip` for the server sockets (empty: chat, dashboard and UGC listen on loopback when master is local); servers master starts no longer inherit its sockets; login steps timed from auth through master to the world. * **Audit round 5:** mission/item preconditions read as AND-groups of OR-alternatives, waypoint delay, bounce and start - fixes, and the property browser friends flag. + fixes, and the property browser friends flag. Then, as the client expects them: + * the property browser's friends list holds every friend's property and those of the account's other characters + (closed ones show locked and still cannot be entered), and its search finds properties without a name or + description by the default text; + * a model can only be put down inside the plot (boundary path and build height); models already placed are never + touched; + * GM invisibility is kept in the character save; a client `SetFlag` for a server-only flag is ignored; + * handlers for `BuildExitConfirmation`, `PropertyModerationAction` and `RequestLeaveProperty`, and cancelling a + property launch takes the rocket off again; + * preconditions apply only in the contexts their row names, the racing licence and no-interaction types work, and + items sold to a vendor no longer count as held. * **Build identifier:** every server logs its version, branch and commit at startup and sends it in its handshake reply, after the bytes the client reads. * **CDClient:** the hot lookup tables (ComponentsRegistry, ItemComponent, Objects) are read straight from the client's diff --git a/dDatabase/GameDatabase/ITables/IProperty.h b/dDatabase/GameDatabase/ITables/IProperty.h index 5674024e1..c77e0fca0 100644 --- a/dDatabase/GameDatabase/ITables/IProperty.h +++ b/dDatabase/GameDatabase/ITables/IProperty.h @@ -34,6 +34,9 @@ public: uint32_t numResults{}; uint32_t startIndex{}; uint32_t playerSort{}; + // Also match properties with no name / no description of their own, whatever the search text + bool includeNullName{}; + bool includeNullDescription{}; }; struct PropertyEntranceResult { diff --git a/dDatabase/GameDatabase/MySQL/Tables/Property.cpp b/dDatabase/GameDatabase/MySQL/Tables/Property.cpp index 4278c6c34..f640c50eb 100644 --- a/dDatabase/GameDatabase/MySQL/Tables/Property.cpp +++ b/dDatabase/GameDatabase/MySQL/Tables/Property.cpp @@ -25,6 +25,11 @@ IProperty::PropertyEntranceResult MySQLDatabase::GetProperties(const IProperty:: std::string query; PreparedStmtResultSet properties; + // The client sets these when the search text is part of the map's default property name / description, which it + // shows for a property with none of its own (LWOPropertyEntranceComponent::onRequestPropertyInfo) + const uint32_t includeNullName = params.includeNullName ? 1 : 0; + const uint32_t includeNullDescription = params.includeNullDescription ? 1 : 0; + if (params.sortChoice == SORT_TYPE_FEATURED || params.sortChoice == SORT_TYPE_FRIENDS) { query = R"QUERY( FROM properties as p @@ -35,17 +40,26 @@ IProperty::PropertyEntranceResult MySQLDatabase::GetProperties(const IProperty:: p.description LIKE ? OR p.name LIKE ? OR ci.name LIKE ? + OR (? != 0 AND p.name = '') + OR (? != 0 AND p.description = '') ) AND p.privacy_option >= ? - AND p.owner_id IN ( - SELECT fr.requested_player AS player FROM ( - SELECT CASE - WHEN player_id = ? THEN friend_id - WHEN friend_id = ? THEN player_id - END AS requested_player FROM friends - ) AS fr - JOIN charinfo AS ci ON ci.id = fr.requested_player - WHERE fr.requested_player IS NOT NULL AND fr.requested_player != ? + AND ( + p.owner_id IN ( + SELECT fr.requested_player AS player FROM ( + SELECT CASE + WHEN player_id = ? THEN friend_id + WHEN friend_id = ? THEN player_id + END AS requested_player FROM friends + ) AS fr + JOIN charinfo AS ci ON ci.id = fr.requested_player + WHERE fr.requested_player IS NOT NULL AND fr.requested_player != ? + ) + OR p.owner_id IN ( + SELECT alt.id FROM charinfo AS alt + WHERE alt.id != ? + AND alt.account_id = (SELECT me.account_id FROM charinfo AS me WHERE me.id = ?) + ) ) ORDER BY ci.name ASC )QUERY"; const auto completeQuery = "SELECT p.* " + query + " LIMIT ? OFFSET ?;"; @@ -55,10 +69,14 @@ IProperty::PropertyEntranceResult MySQLDatabase::GetProperties(const IProperty:: "%" + params.searchString + "%", "%" + params.searchString + "%", "%" + params.searchString + "%", + includeNullName, + includeNullDescription, params.playerSort, params.playerId, params.playerId, params.playerId, + params.playerId, + params.playerId, params.numResults, params.startIndex ); @@ -69,9 +87,13 @@ IProperty::PropertyEntranceResult MySQLDatabase::GetProperties(const IProperty:: "%" + params.searchString + "%", "%" + params.searchString + "%", "%" + params.searchString + "%", + includeNullName, + includeNullDescription, params.playerSort, params.playerId, params.playerId, + params.playerId, + params.playerId, params.playerId ); if (count->next()) { @@ -88,6 +110,8 @@ IProperty::PropertyEntranceResult MySQLDatabase::GetProperties(const IProperty:: p.description LIKE ? OR p.name LIKE ? OR ci.name LIKE ? + OR (? != 0 AND p.name = '') + OR (? != 0 AND p.description = '') ) AND p.privacy_option >= ? ORDER BY p.reputation DESC, p.last_updated DESC @@ -102,6 +126,8 @@ IProperty::PropertyEntranceResult MySQLDatabase::GetProperties(const IProperty:: p.description LIKE ? OR p.name LIKE ? OR ci.name LIKE ? + OR (? != 0 AND p.name = '') + OR (? != 0 AND p.description = '') ) AND p.privacy_option >= ? ORDER BY p.last_updated DESC @@ -114,6 +140,8 @@ IProperty::PropertyEntranceResult MySQLDatabase::GetProperties(const IProperty:: "%" + params.searchString + "%", "%" + params.searchString + "%", "%" + params.searchString + "%", + includeNullName, + includeNullDescription, params.playerSort, params.numResults, params.startIndex @@ -125,6 +153,8 @@ IProperty::PropertyEntranceResult MySQLDatabase::GetProperties(const IProperty:: "%" + params.searchString + "%", "%" + params.searchString + "%", "%" + params.searchString + "%", + includeNullName, + includeNullDescription, params.playerSort ); if (count->next()) { diff --git a/dDatabase/GameDatabase/SQLite/Tables/Property.cpp b/dDatabase/GameDatabase/SQLite/Tables/Property.cpp index 68526fc65..035beda67 100644 --- a/dDatabase/GameDatabase/SQLite/Tables/Property.cpp +++ b/dDatabase/GameDatabase/SQLite/Tables/Property.cpp @@ -25,6 +25,11 @@ IProperty::PropertyEntranceResult SQLiteDatabase::GetProperties(const IProperty: std::string query; std::pair propertiesRes; + // The client sets these when the search text is part of the map's default property name / description, which it + // shows for a property with none of its own (LWOPropertyEntranceComponent::onRequestPropertyInfo) + const uint32_t includeNullName = params.includeNullName ? 1 : 0; + const uint32_t includeNullDescription = params.includeNullDescription ? 1 : 0; + if (params.sortChoice == SORT_TYPE_FEATURED || params.sortChoice == SORT_TYPE_FRIENDS) { query = R"QUERY( FROM properties as p @@ -35,17 +40,26 @@ IProperty::PropertyEntranceResult SQLiteDatabase::GetProperties(const IProperty: p.description LIKE ? OR p.name LIKE ? OR ci.name LIKE ? + OR (? != 0 AND p.name = '') + OR (? != 0 AND p.description = '') ) AND p.privacy_option >= ? - AND p.owner_id IN ( - SELECT fr.requested_player AS player FROM ( - SELECT CASE - WHEN player_id = ? THEN friend_id - WHEN friend_id = ? THEN player_id - END AS requested_player FROM friends - ) AS fr - JOIN charinfo AS ci ON ci.id = fr.requested_player - WHERE fr.requested_player IS NOT NULL AND fr.requested_player != ? + AND ( + p.owner_id IN ( + SELECT fr.requested_player AS player FROM ( + SELECT CASE + WHEN player_id = ? THEN friend_id + WHEN friend_id = ? THEN player_id + END AS requested_player FROM friends + ) AS fr + JOIN charinfo AS ci ON ci.id = fr.requested_player + WHERE fr.requested_player IS NOT NULL AND fr.requested_player != ? + ) + OR p.owner_id IN ( + SELECT alt.id FROM charinfo AS alt + WHERE alt.id != ? + AND alt.account_id = (SELECT me.account_id FROM charinfo AS me WHERE me.id = ?) + ) ) ORDER BY ci.name ASC )QUERY"; const auto completeQuery = "SELECT p.* " + query + " LIMIT ? OFFSET ?;"; @@ -55,10 +69,14 @@ IProperty::PropertyEntranceResult SQLiteDatabase::GetProperties(const IProperty: "%" + params.searchString + "%", "%" + params.searchString + "%", "%" + params.searchString + "%", + includeNullName, + includeNullDescription, params.playerSort, params.playerId, params.playerId, params.playerId, + params.playerId, + params.playerId, params.numResults, params.startIndex ); @@ -69,9 +87,13 @@ IProperty::PropertyEntranceResult SQLiteDatabase::GetProperties(const IProperty: "%" + params.searchString + "%", "%" + params.searchString + "%", "%" + params.searchString + "%", + includeNullName, + includeNullDescription, params.playerSort, params.playerId, params.playerId, + params.playerId, + params.playerId, params.playerId ); if (!count.eof()) { @@ -88,6 +110,8 @@ IProperty::PropertyEntranceResult SQLiteDatabase::GetProperties(const IProperty: p.description LIKE ? OR p.name LIKE ? OR ci.name LIKE ? + OR (? != 0 AND p.name = '') + OR (? != 0 AND p.description = '') ) AND p.privacy_option >= ? ORDER BY p.reputation DESC, p.last_updated DESC @@ -102,6 +126,8 @@ IProperty::PropertyEntranceResult SQLiteDatabase::GetProperties(const IProperty: p.description LIKE ? OR p.name LIKE ? OR ci.name LIKE ? + OR (? != 0 AND p.name = '') + OR (? != 0 AND p.description = '') ) AND p.privacy_option >= ? ORDER BY p.last_updated DESC @@ -114,6 +140,8 @@ IProperty::PropertyEntranceResult SQLiteDatabase::GetProperties(const IProperty: "%" + params.searchString + "%", "%" + params.searchString + "%", "%" + params.searchString + "%", + includeNullName, + includeNullDescription, params.playerSort, params.numResults, params.startIndex @@ -125,6 +153,8 @@ IProperty::PropertyEntranceResult SQLiteDatabase::GetProperties(const IProperty: "%" + params.searchString + "%", "%" + params.searchString + "%", "%" + params.searchString + "%", + includeNullName, + includeNullDescription, params.playerSort ); if (!count.eof()) { diff --git a/dGame/dComponents/Character/GhostComponent.cpp b/dGame/dComponents/Character/GhostComponent.cpp index c202ff87f..0a2d93ec1 100644 --- a/dGame/dComponents/Character/GhostComponent.cpp +++ b/dGame/dComponents/Character/GhostComponent.cpp @@ -6,6 +6,7 @@ #include "User.h" #include "Amf3.h" +#include "tinyxml2.h" #include "GameMessages.h" #include "PlayerMessages.h" @@ -69,6 +70,33 @@ void GhostComponent::GhostEntity(LWOOBJID id) { m_ObservedEntities.erase(id); } +void GhostComponent::LoadFromSaveData(const tinyxml2::XMLDocument& doc) { + const auto* const obj = doc.FirstChildElement("obj"); + const auto* const ghost = obj ? obj->FirstChildElement("ghst") : nullptr; + // A save without the element, or with an i that is not a boolean, is a visible character + if (ghost) ghost->QueryBoolAttribute("i", &m_IsGMInvisible); +} + +void GhostComponent::WriteSaveData(tinyxml2::XMLDocument& doc) { + auto* const obj = doc.FirstChildElement("obj"); + if (!obj) return; + + auto* ghost = obj->FirstChildElement("ghst"); + if (!ghost) { + if (!m_IsGMInvisible) return; + ghost = obj->InsertNewChildElement("ghst"); + } + + // Only a value that says something else is rewritten + bool saved = false; + const bool readable = ghost->QueryBoolAttribute("i", &saved) == tinyxml2::XML_SUCCESS; + if (m_IsGMInvisible) { + if (!readable || !saved) ghost->SetAttribute("i", 1); + } else if (readable && saved) { + ghost->SetAttribute("i", 0); + } +} + bool GhostComponent::OnToggleGMInvis(GameMessages::ToggleGMInvisEvent& event) { auto& gmInvisMsg = event.msg; gmInvisMsg.target = event.target; // the wire message goes out with the target the event was delivered to diff --git a/dGame/dComponents/Character/GhostComponent.h b/dGame/dComponents/Character/GhostComponent.h index d61893e19..c90627416 100644 --- a/dGame/dComponents/Character/GhostComponent.h +++ b/dGame/dComponents/Character/GhostComponent.h @@ -47,6 +47,15 @@ public: // The client dropped every object it had (it reloaded the zone in place): nothing counts as sent to it any more void ForgetObservedEntities() { m_ObservedEntities.clear(); m_LimboConstructions.clear(); } + // LWOGhostComponent::LoadFromSaveData: , whether the GM was invisible when the save was + // written. The client reads the same element and hides its own character again once the scene has loaded. + void LoadFromSaveData(const tinyxml2::XMLDocument& doc) override; + + // Writes while invisible. A visible character only has an element it already had set back to 0. + void WriteSaveData(tinyxml2::XMLDocument& doc) override; + + bool IsGMInvisible() const { return m_IsGMInvisible; } + bool OnToggleGMInvis(GameMessages::ToggleGMInvisEvent& event); bool OnGetGMInvis(GameMessages::GetGMInvis& msg); diff --git a/dGame/dComponents/InventoryComponent.cpp b/dGame/dComponents/InventoryComponent.cpp index 1291b8602..12c9ed842 100644 --- a/dGame/dComponents/InventoryComponent.cpp +++ b/dGame/dComponents/InventoryComponent.cpp @@ -203,6 +203,18 @@ uint32_t InventoryComponent::GetLotCount(const LOT lot) const { return count; } +uint32_t InventoryComponent::GetLotCountWithoutBuyBack(const LOT lot) const { + uint32_t count = 0; + + for (const auto& inventory : m_Inventories) { + if (inventory.second->GetType() == eInventoryType::VENDOR_BUYBACK) continue; + + count += inventory.second->GetLotCount(lot); + } + + return count; +} + uint32_t InventoryComponent::GetLotCountNonTransfer(LOT lot, bool includeVault) const { uint32_t count = 0; @@ -1179,7 +1191,10 @@ void InventoryComponent::EquipItem(Item* item, const bool skipChecks) { if (!building && (item->GetLot() == 6086 || type == eItemType::LOOT_MODEL || type == eItemType::VEHICLE)) return; if (type != eItemType::LOOT_MODEL && type != eItemType::MODEL) { - if (!item->GetBound() && !item->GetPreconditionExpression()->Check(m_Parent)) { + // A bound item is checked in its own context (LWOItemComponent, IsItemEquippable): the requirements that + // are not for it, the level ones, no longer count once the item is the player's + const auto context = item->GetBound() ? PreconditionContext::BoundItem : PreconditionContext::None; + if (!item->GetPreconditionExpression()->Check(m_Parent, context)) { return; } } diff --git a/dGame/dComponents/InventoryComponent.h b/dGame/dComponents/InventoryComponent.h index 02cb71f3a..6ac068444 100644 --- a/dGame/dComponents/InventoryComponent.h +++ b/dGame/dComponents/InventoryComponent.h @@ -142,6 +142,14 @@ public: */ uint32_t GetLotCount(LOT lot) const; + /** + * Returns the amount of items this entity possesses of a certain LOT, leaving out what it sold to a vendor and + * can still buy back: the count the client's precondition check asks for (GetInvItemCount with ignoreBuyBack) + * @param lot the lot to search for + * @return the amount of items of the LOT outside the vendor buy back inventory + */ + uint32_t GetLotCountWithoutBuyBack(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). diff --git a/dGame/dComponents/Property/PropertyEntranceComponent.cpp b/dGame/dComponents/Property/PropertyEntranceComponent.cpp index 6106a081d..50b2da67c 100644 --- a/dGame/dComponents/Property/PropertyEntranceComponent.cpp +++ b/dGame/dComponents/Property/PropertyEntranceComponent.cpp @@ -58,10 +58,20 @@ bool PropertyEntranceComponent::OnRequestUse(GameMessages::RequestUseEvent& even return true; } +void PropertyEntranceComponent::CancelLaunch(Entity& player) { + auto* const characterComponent = player.GetComponent(); + if (characterComponent) characterComponent->RocketUnEquip(&player); +} + bool PropertyEntranceComponent::IsFriendsSort(const int32_t sortMethod) { return sortMethod == SORT_TYPE_FEATURED || sortMethod == SORT_TYPE_FRIENDS; } +bool PropertyEntranceComponent::CanVisit(const uint32_t accessType, const bool isFriend) { + if (accessType >= static_cast(PropertyPrivacyOption::Public)) return true; + return isFriend && accessType >= static_cast(PropertyPrivacyOption::Friends); +} + void PropertyEntranceComponent::OnEnterProperty(Entity* entity, uint32_t index, bool returnToZone, const SystemAddress& sysAddr) { LWOCLONEID cloneId = 0; @@ -81,6 +91,13 @@ void PropertyEntranceComponent::OnEnterProperty(Entity* entity, uint32_t index, if (index >= query.size()) return; + // The friends list also holds properties the player may not visit (private ones, and those of the account's + // other characters); the client draws a lock on them. Selecting one anyway goes nowhere. + if (!CanVisit(query[index].accessType, query[index].isFriend)) { + LOG("Player %llu selected property clone %u, which is not open to them", entity->GetObjectID(), query[index].cloneId); + return; + } + cloneId = query[index].cloneId; } @@ -142,8 +159,13 @@ void PropertyEntranceComponent::OnPropertyEntranceSync(Entity* entity, bool incl IProperty::PropertyLookup propertyLookup; propertyLookup.mapId = m_MapID; propertyLookup.searchString = filterText; + propertyLookup.includeNullName = includeNullAddress; + propertyLookup.includeNullDescription = includeNullDescription; propertyLookup.sortChoice = static_cast(sortMethod); - propertyLookup.playerSort = static_cast(IsFriendsSort(sortMethod) ? PropertyPrivacyOption::Friends : PropertyPrivacyOption::Public); + // Live listed every property of the player's friends and of the account's other characters in the friends list, + // whatever its access type (64 friend entries with accessType 0 in the captured replies); the client locks the + // ones that are closed. The other lists only hold public properties. + propertyLookup.playerSort = static_cast(IsFriendsSort(sortMethod) ? PropertyPrivacyOption::Private : PropertyPrivacyOption::Public); propertyLookup.playerId = character->GetID(); propertyLookup.numResults = numResults; propertyLookup.startIndex = startIndex; @@ -159,7 +181,8 @@ void PropertyEntranceComponent::OnPropertyEntranceSync(Entity* entity, bool incl } auto& entry = entries.emplace_back(); - entry.isOwned = entry.cloneId == otherCharacter->cloneId; + // Live: only the first entry (the player's own property) is ever marked as owned + entry.isOwned = false; entry.ownerName = GeneralUtils::UTF8ToUTF16(otherCharacter->name); entry.cloneId = propertyEntry.cloneId; entry.name = GeneralUtils::UTF8ToUTF16(propertyEntry.name); diff --git a/dGame/dComponents/Property/PropertyEntranceComponent.h b/dGame/dComponents/Property/PropertyEntranceComponent.h index 7a0c218c7..5e112cfc8 100644 --- a/dGame/dComponents/Property/PropertyEntranceComponent.h +++ b/dGame/dComponents/Property/PropertyEntranceComponent.h @@ -34,9 +34,17 @@ public: */ void OnEnterProperty(Entity* entity, uint32_t index, bool returnToZone, const SystemAddress& sysAddr); + // The player left the property browser without launching (FireEventServerSide "CancelLaunch"): the rocket that + // OnRequestUse put in their hands is taken off again + static void CancelLaunch(Entity& player); + // True when the property browser asked for the friends list (the reply's wasFriends says so) static bool IsFriendsSort(int32_t sortMethod); + // Whether a listed property may be entered: public ones by everybody, friends-only ones by the owner's friends. + // The friends list also shows the closed ones (the client draws their lock), so the selection is checked here. + static bool CanVisit(uint32_t accessType, bool isFriend); + /** * Handles a request for information on available properties when an entity lands on the property * @param entity the entity that triggered the event diff --git a/dGame/dComponents/Property/PropertyManagementComponent.cpp b/dGame/dComponents/Property/PropertyManagementComponent.cpp index 4012f006a..42591987b 100644 --- a/dGame/dComponents/Property/PropertyManagementComponent.cpp +++ b/dGame/dComponents/Property/PropertyManagementComponent.cpp @@ -36,6 +36,7 @@ #include "BrickByBrick.h" #include "eLootSourceType.h" #include "eKillType.h" +#include "PropertyBounds.h" #include "PropertyBuilders.h" #include "BuildingMessages.h" @@ -211,6 +212,13 @@ std::vector PropertyManagementComponent::GetPaths() const { return paths; } +bool PropertyManagementComponent::IsInsidePlot(const NiPoint3& position) const { + // The same path and height DownloadPropertyData gives the client + const auto zoneId = Game::zoneManager->GetZone()->GetWorldID(); + const auto propertyTemplate = CDClientManager::GetTable()->GetByMapID(zoneId); + return PropertyBounds::IsPositionInside(position, GetPaths(), propertyTemplate.maxBuildHeight); +} + PropertyPrivacyOption PropertyManagementComponent::GetPrivacyOption() const { return privacyOption; } @@ -328,6 +336,30 @@ bool PropertyManagementComponent::Claim(const LWOOBJID playerId) { return true; } +LWOMAPID PropertyManagementComponent::GetReturnZone() const { + LWOMAPID zoneId = 1100; + + const auto entrance = Game::entityManager->GetEntitiesByComponent(eReplicaComponentType::PROPERTY_ENTRANCE); + if (!entrance.empty()) { + auto* rocketPad = entrance[0]->GetComponent(); + + if (rocketPad != nullptr) { + zoneId = rocketPad->GetDefaultZone(); + } + } + + return zoneId; +} + +void PropertyManagementComponent::OnRequestLeaveProperty(Entity& player) const { + auto* const characterComponent = player.GetComponent(); + if (!characterComponent) return; + + const auto zoneId = GetReturnZone(); + LOG("Player %llu asked to leave the property, sending them to zone %u", player.GetObjectID(), static_cast(zoneId)); + characterComponent->SendToZone(zoneId); +} + void PropertyManagementComponent::OnStartBuilding(Entity& builder) { const bool first = builders.empty(); if (!builders.insert(builder.GetObjectID()).second) return; @@ -345,21 +377,11 @@ void PropertyManagementComponent::OnStartBuilding(Entity& builder) { const auto players = PlayerManager::GetAllPlayers(); - LWOMAPID zoneId = 1100; - - const auto entrance = Game::entityManager->GetEntitiesByComponent(eReplicaComponentType::PROPERTY_ENTRANCE); - originalPrivacyOption = privacyOption; SetPrivacyOption(PropertyPrivacyOption::Private); // Cant visit player which is building - if (!entrance.empty()) { - auto* rocketPad = entrance[0]->GetComponent(); - - if (rocketPad != nullptr) { - zoneId = rocketPad->GetDefaultZone(); - } - } + const LWOMAPID zoneId = GetReturnZone(); // Everyone who can't build here leaves for (auto* player : players) { @@ -538,6 +560,20 @@ void PropertyManagementComponent::UpdateModelPosition(Entity& builder, const LWO return; } + // Outside the plot: nothing is placed and the item stays where it is. The client shows its "outside the property + // bounds" message for this answer and lets go of the placement. + if (!IsInsidePlot(position)) { + LOG("Player %llu tried to place model %llu at <%f, %f, %f>, outside the plot", builder.GetObjectID(), id, position.x, position.y, position.z); + GameMessages::PlaceModelResponse msg; + msg.target = entity->GetObjectID(); + msg.position = position; + msg.propertyPlaqueID = m_Parent->GetObjectID(); + msg.response = BrickByBrick::PLACE_MODEL_OUT_OF_BOUNDS; + msg.rotation = rotation; + msg.Send(entity->GetSystemAddress()); + return; + } + const NiQuaternion originalRotation = rotation; if (rotation != QuatUtils::IDENTITY) { rotation = { rotation.w, rotation.z, rotation.y, rotation.x }; diff --git a/dGame/dComponents/Property/PropertyManagementComponent.h b/dGame/dComponents/Property/PropertyManagementComponent.h index 661100c59..2b685551c 100644 --- a/dGame/dComponents/Property/PropertyManagementComponent.h +++ b/dGame/dComponents/Property/PropertyManagementComponent.h @@ -82,8 +82,24 @@ public: * Returns the paths that this property has * @return the paths that this property has */ + /** + * The world a player who leaves the property goes to: the one its launch pad launches to + */ + LWOMAPID GetReturnZone() const; + + /** + * A player asked to leave the property (RequestLeaveProperty): they go to the return zone + */ + void OnRequestLeaveProperty(Entity& player) const; + std::vector GetPaths() const; + /** + * Whether a model may be put down at this position: inside the plot's boundary path and under its build height, as + * the client tests a box against the same data (PropertyBounds). Models already placed are never tested. + */ + bool IsInsidePlot(const NiPoint3& position) const; + /** * Returns the privacy options for this property * @return the privacy options for this property diff --git a/dGame/dGameMessages/BuildingMessages.cpp b/dGame/dGameMessages/BuildingMessages.cpp index e062e1857..4d8ecd197 100644 --- a/dGame/dGameMessages/BuildingMessages.cpp +++ b/dGame/dGameMessages/BuildingMessages.cpp @@ -500,6 +500,28 @@ namespace GameMessages { } } + void BuildExitConfirmation::Serialize(RakNet::BitStream& bitStream) const { + bitStream.Write(playerID); + } + + bool BuildExitConfirmation::Deserialize(RakNet::BitStream& bitStream) { + VALIDATE_READ(bitStream.Read(playerID)); + return true; + } + + void BuildExitConfirmation::Handle(Entity& entity, const SystemAddress& sysAddr) { + const auto* const player = PlayerManager::GetPlayer(sysAddr); + if (!player) return; + if (playerID != player->GetObjectID()) { + LOG("Ignored BuildExitConfirmation from %llu for %llu", player->GetObjectID(), playerID); + return; + } + + // The mode itself was already ended by the messages before this one (BuildModeSet, PropertyEditorEnd, + // DoneArrangingWithItem); live answered nothing here, so there is nothing more to do. + LOG_DEBUG("Player %llu confirmed leaving build mode", playerID); + } + void UnUseBBBModel::Serialize(RakNet::BitStream& bitStream) const { bitStream.Write(bHasWorldTransform); bitStream.Write(modelID); diff --git a/dGame/dGameMessages/BuildingMessages.h b/dGame/dGameMessages/BuildingMessages.h index 10c7fde41..60639316a 100644 --- a/dGame/dGameMessages/BuildingMessages.h +++ b/dGame/dGameMessages/BuildingMessages.h @@ -171,6 +171,19 @@ namespace GameMessages { NiPoint3 startPos{ NiPoint3Constant::ZERO }; // optional }; + // Client -> server. The client left a build mode (a modular build or the property editor) and says so after its + // last message of that mode (LWOPropertyManagementComponent::DoSetBuildMode). It is addressed to the + // thinking hat the player wears (the item in the hair slot, when it starts builds) or to no object, + // and carries the player. Live sent no answer to it (10 in the captures). + struct BuildExitConfirmation : public NetGameMsg { + BuildExitConfirmation() : NetGameMsg(MessageType::Game::BUILD_EXIT_CONFIRMATION) {} + void Serialize(RakNet::BitStream& bitStream) const override; + bool Deserialize(RakNet::BitStream& bitStream) override; + void Handle(Entity& entity, const SystemAddress& sysAddr) override; + + LWOOBJID playerID{ LWOOBJID_EMPTY }; + }; + // Client -> server. The player put a model back from brick by brick building. struct UnUseBBBModel : public NetGameMsg { UnUseBBBModel() : NetGameMsg(MessageType::Game::UN_USE_BBB_MODEL) {} diff --git a/dGame/dGameMessages/GameMessageFields.inc b/dGame/dGameMessages/GameMessageFields.inc index f63fc5538..f086c5a35 100644 --- a/dGame/dGameMessages/GameMessageFields.inc +++ b/dGame/dGameMessages/GameMessageFields.inc @@ -30,6 +30,7 @@ json ToJson(const GameMessages::ModularBuildConvertModel& m); json ToJson(const GameMessages::SetBuildMode& m); json ToJson(const GameMessages::SetBuildModeConfirmed& m); json ToJson(const GameMessages::BuildModeSet& m); +json ToJson(const GameMessages::BuildExitConfirmation& m); json ToJson(const GameMessages::UnUseBBBModel& m); json ToJson(const GameMessages::BBBLoadItemRequest& m); json ToJson(const GameMessages::BBBSaveRequest& m); @@ -222,6 +223,8 @@ json ToJson(const GameMessages::UpdatePropertyOrModelForFilterCheck& m); json ToJson(const GameMessages::QueryPropertyData& m); json ToJson(const GameMessages::PropertyEditorBegin& m); json ToJson(const GameMessages::PropertyEditorEnd& m); +json ToJson(const GameMessages::PropertyModerationAction& m); +json ToJson(const GameMessages::RequestLeaveProperty& m); json ToJson(const GameMessages::PropertyContentsFromClient& m); json ToJson(const GameMessages::ZonePropertyModelEquipped& m); json ToJson(const GameMessages::ZonePropertyModelRotated& m); @@ -531,6 +534,11 @@ json ToJson(const GameMessages::BuildModeSet& m) { j["startPos"] = ToJson(m.startPos); return j; } +json ToJson(const GameMessages::BuildExitConfirmation& m) { + json j = json::object(); + j["playerID"] = ToJson(m.playerID); + return j; +} json ToJson(const GameMessages::UnUseBBBModel& m) { json j = json::object(); j["bHasWorldTransform"] = ToJson(m.bHasWorldTransform); @@ -1959,6 +1967,17 @@ json ToJson(const GameMessages::PropertyEditorEnd& m) { json j = json::object(); return j; } +json ToJson(const GameMessages::PropertyModerationAction& m) { + json j = json::object(); + j["characterID"] = ToJson(m.characterID); + j["info"] = ToJson(m.info); + j["newModerationStatus"] = ToJson(m.newModerationStatus); + return j; +} +json ToJson(const GameMessages::RequestLeaveProperty& m) { + json j = json::object(); + return j; +} json ToJson(const GameMessages::PropertyContentsFromClient& m) { json j = json::object(); j["queryDB"] = ToJson(m.queryDB); @@ -2559,6 +2578,7 @@ const std::vector& Entries() { { MessageType::Game::SET_BUILD_MODE, eDirection::TO_SERVER, "SetBuildMode", &ReadWith }, { MessageType::Game::SET_BUILD_MODE_CONFIRMED, eDirection::TO_CLIENT, "SetBuildModeConfirmed", &ReadWith }, { MessageType::Game::BUILD_MODE_SET, eDirection::TO_SERVER, "BuildModeSet", &ReadWith }, + { MessageType::Game::BUILD_EXIT_CONFIRMATION, eDirection::TO_SERVER, "BuildExitConfirmation", &ReadWith }, { MessageType::Game::UN_USE_BBB_MODEL, eDirection::TO_SERVER, "UnUseBBBModel", &ReadWith }, { MessageType::Game::BBB_LOAD_ITEM_REQUEST, eDirection::TO_SERVER, "BBBLoadItemRequest", &ReadWith }, { MessageType::Game::BBB_SAVE_REQUEST, eDirection::TO_SERVER, "BBBSaveRequest", &ReadWith }, @@ -2748,6 +2768,8 @@ const std::vector& Entries() { { MessageType::Game::QUERY_PROPERTY_DATA, eDirection::TO_SERVER, "QueryPropertyData", &ReadWith }, { MessageType::Game::PROPERTY_EDITOR_BEGIN, eDirection::TO_SERVER, "PropertyEditorBegin", &ReadWith }, { MessageType::Game::PROPERTY_EDITOR_END, eDirection::TO_SERVER, "PropertyEditorEnd", &ReadWith }, + { MessageType::Game::PROPERTY_MODERATION_ACTION, eDirection::TO_SERVER, "PropertyModerationAction", &ReadWith }, + { MessageType::Game::REQUEST_LEAVE_PROPERTY, eDirection::TO_SERVER, "RequestLeaveProperty", &ReadWith }, { MessageType::Game::PROPERTY_CONTENTS_FROM_CLIENT, eDirection::TO_SERVER, "PropertyContentsFromClient", &ReadWith }, { MessageType::Game::ZONE_PROPERTY_MODEL_EQUIPPED, eDirection::TO_SERVER, "ZonePropertyModelEquipped", &ReadWith }, { MessageType::Game::ZONE_PROPERTY_MODEL_ROTATED, eDirection::TO_SERVER, "ZonePropertyModelRotated", &ReadWith }, diff --git a/dGame/dGameMessages/GameMessageHandler.cpp b/dGame/dGameMessages/GameMessageHandler.cpp index 53516f4e9..c75e059ad 100644 --- a/dGame/dGameMessages/GameMessageHandler.cpp +++ b/dGame/dGameMessages/GameMessageHandler.cpp @@ -122,6 +122,8 @@ namespace { { PROPERTY_EDITOR_BEGIN, []() { return std::make_unique(); } }, { PROPERTY_EDITOR_END, []() { return std::make_unique(); } }, { PROPERTY_CONTENTS_FROM_CLIENT, []() { return std::make_unique(); } }, + { PROPERTY_MODERATION_ACTION, []() { return std::make_unique(); } }, + { REQUEST_LEAVE_PROPERTY, []() { return std::make_unique(); } }, { ZONE_PROPERTY_MODEL_EQUIPPED, []() { return std::make_unique(); } }, { ZONE_PROPERTY_MODEL_ROTATED, []() { return std::make_unique(); } }, { PLACE_PROPERTY_MODEL, []() { return std::make_unique(); } }, @@ -143,6 +145,7 @@ namespace { { MODULAR_BUILD_CONVERT_MODEL, []() { return std::make_unique(); } }, { SET_BUILD_MODE, []() { return std::make_unique(); } }, { BUILD_MODE_SET, []() { return std::make_unique(); } }, + { BUILD_EXIT_CONFIRMATION, []() { return std::make_unique(); } }, { UN_USE_BBB_MODEL, []() { return std::make_unique(); } }, { FETCH_MODEL_METADATA_REQUEST, []() { return std::make_unique(); } }, { BBB_LOAD_ITEM_REQUEST, []() { return std::make_unique(); } }, @@ -240,6 +243,10 @@ void GameMessageHandler::HandleMessage(RakNet::BitStream& inStream, const System return; } + // BuildExitConfirmation is addressed to the thinking hat the player wears, or to no object: an item is not an + // entity here, so the player who sent it takes it + if (!entity && messageID == MessageType::Game::BUILD_EXIT_CONFIRMATION) entity = Game::entityManager->GetEntity(usr->GetLoggedInChar()); + if (!entity) { LOG("Failed to find associated entity (%llu), aborting GM: %4i, %s!", objectID, messageID, StringifiedEnum::ToString(messageID).data()); return; diff --git a/dGame/dGameMessages/MissionMessages.cpp b/dGame/dGameMessages/MissionMessages.cpp index c3be670e2..be448f52d 100644 --- a/dGame/dGameMessages/MissionMessages.cpp +++ b/dGame/dGameMessages/MissionMessages.cpp @@ -1,6 +1,7 @@ #include "MissionMessages.h" #include "BitStreamUtils.h" +#include "CDPlayerFlagsTable.h" #include "Character.h" #include "CppScripts.h" #include "dConfig.h" @@ -248,6 +249,15 @@ namespace GameMessages { } void SetFlag::Handle(Entity& entity, const SystemAddress& sysAddr) { + // PlayerFlags.OnlySetByServer: the client's flag component refuses to set these itself and logs "Attempted to + // set a flag from the client side that can only be set from the server" (LWOFlagComponent::SendMessage + // ), and no live client SetFlag named one (205 looked at). The saved flags are left as they are. + const auto flagEntry = CDPlayerFlagsTable::GetEntry(iFlagID); + if (flagEntry && flagEntry->onlySetByServer) { + LOG_DEBUG("Ignored SetFlag %i = %d from %llu: the flag can only be set by the server", iFlagID, bFlag, entity.GetObjectID()); + return; + } + auto character = entity.GetCharacter(); if (character) character->SetPlayerFlag(iFlagID, bFlag); diff --git a/dGame/dGameMessages/ObjectMessages.cpp b/dGame/dGameMessages/ObjectMessages.cpp index e4afc7def..fc6f75a0e 100644 --- a/dGame/dGameMessages/ObjectMessages.cpp +++ b/dGame/dGameMessages/ObjectMessages.cpp @@ -13,6 +13,7 @@ #include "MissionComponent.h" #include "MissionOfferComponent.h" #include "PlayerManager.h" +#include "PropertyEntranceComponent.h" #include "RocketLaunchpadControlComponent.h" #include "ZoneMessages.h" #include "ZoneInstanceManager.h" @@ -127,6 +128,12 @@ namespace GameMessages { }); } + // The property browser was closed without a launch, or the player died with it open + // (LWOPropertyEntranceComponent::onPropertyEntranceSelected) + if (args == u"CancelLaunch" && entity.HasComponent(eReplicaComponentType::PROPERTY_ENTRANCE)) { + PropertyEntranceComponent::CancelLaunch(*player); + } + entity.OnFireEventServerSide(sender, GeneralUtils::UTF16ToWTF8(args), param1, param2, param3); } diff --git a/dGame/dGameMessages/PropertyMessages.cpp b/dGame/dGameMessages/PropertyMessages.cpp index b4a13576d..91f89f10a 100644 --- a/dGame/dGameMessages/PropertyMessages.cpp +++ b/dGame/dGameMessages/PropertyMessages.cpp @@ -434,6 +434,42 @@ namespace GameMessages { Game::zoneManager->GetZoneControlObject()->OnZonePropertyEditEnd(); } + void PropertyModerationAction::Serialize(RakNet::BitStream& bitStream) const { + BitStreamUtils::WriteOptional(bitStream, characterID, LWOOBJID_EMPTY); + BitStreamUtils::WriteLengthPrefixed(bitStream, info); + BitStreamUtils::WriteOptional(bitStream, newModerationStatus, -1); + } + + bool PropertyModerationAction::Deserialize(RakNet::BitStream& bitStream) { + VALIDATE_READ(BitStreamUtils::ReadOptional(bitStream, characterID, LWOOBJID_EMPTY)); + VALIDATE_READ(BitStreamUtils::ReadLengthPrefixed(bitStream, info)); + VALIDATE_READ(BitStreamUtils::ReadOptional(bitStream, newModerationStatus, -1)); + return true; + } + + void PropertyModerationAction::Handle(Entity& entity, const SystemAddress& sysAddr) { + auto* property = PropertyManagementComponent::Instance(); + auto* player = PlayerManager::GetPlayer(sysAddr); + if (!property || !player) return; + + // The client only sends it for its own character, on a property it may edit, to ask for status 0 + if (characterID != player->GetObjectID() || !property->CanBuild(*player) || newModerationStatus != 0) { + LOG("Ignored PropertyModerationAction from %llu (character %llu, status %i)", player->GetObjectID(), characterID, newModerationStatus); + return; + } + + // Nothing is stored here and nothing is answered: the approval of an edited property is taken back when the + // edit ends (PropertyManagementComponent::EndBuilding), and live sent no PropertyModerationActionResponse. + LOG_DEBUG("Player %llu started editing a moderated property", player->GetObjectID()); + } + + void RequestLeaveProperty::Handle(Entity& entity, const SystemAddress& sysAddr) { + auto* property = PropertyManagementComponent::Instance(); + auto* player = PlayerManager::GetPlayer(sysAddr); + if (!property || !player) return; + property->OnRequestLeaveProperty(*player); + } + void PropertyContentsFromClient::Serialize(RakNet::BitStream& bitStream) const { bitStream.Write(queryDB); } diff --git a/dGame/dGameMessages/PropertyMessages.h b/dGame/dGameMessages/PropertyMessages.h index 0f686199b..dab11a474 100644 --- a/dGame/dGameMessages/PropertyMessages.h +++ b/dGame/dGameMessages/PropertyMessages.h @@ -227,6 +227,27 @@ namespace GameMessages { void Handle(Entity& entity, const SystemAddress& sysAddr) override; }; + // Client -> server, to the property plaque. The owner started editing a property whose moderation status is not + // 0 and asks for it to be 0 again (LWOPropertyManagementComponent). Laid out as the client writes it + // (PropertyModerationAction::Serialize). Live sent no answer to it (3 in the captures). + struct PropertyModerationAction : public NetGameMsg { + PropertyModerationAction() : NetGameMsg(MessageType::Game::PROPERTY_MODERATION_ACTION) {} + void Serialize(RakNet::BitStream& bitStream) const override; + bool Deserialize(RakNet::BitStream& bitStream) override; + void Handle(Entity& entity, const SystemAddress& sysAddr) override; + + LWOOBJID characterID{ LWOOBJID_EMPTY }; // optional + std::u16string info; + int32_t newModerationStatus{ -1 }; // optional + }; + + // Client -> server, to the property plaque, with no payload. A visitor answered the "the owner is starting to + // build" dialog by leaving (LWOPropertyManagementComponent::onBuildModeVisitorConfirm). + struct RequestLeaveProperty : public NetGameMsg { + RequestLeaveProperty() : NetGameMsg(MessageType::Game::REQUEST_LEAVE_PROPERTY) {} + void Handle(Entity& entity, const SystemAddress& sysAddr) override; + }; + // Client -> server. struct PropertyContentsFromClient : public NetGameMsg { PropertyContentsFromClient() : NetGameMsg(MessageType::Game::PROPERTY_CONTENTS_FROM_CLIENT) {} diff --git a/dGame/dUtilities/BrickByBrick.h b/dGame/dUtilities/BrickByBrick.h index 5a2ae7beb..e94cd7a74 100644 --- a/dGame/dUtilities/BrickByBrick.h +++ b/dGame/dUtilities/BrickByBrick.h @@ -41,6 +41,7 @@ namespace BrickByBrick { }; // PlaceModelResponse's response + constexpr int32_t PLACE_MODEL_OUT_OF_BOUNDS = 12; // the client's "placement bounds" refusal constexpr int32_t PLACE_MODEL_PLACED = 14; constexpr int32_t PLACE_MODEL_REMOVED = 16; diff --git a/dGame/dUtilities/CMakeLists.txt b/dGame/dUtilities/CMakeLists.txt index bf157e3da..da9584f08 100644 --- a/dGame/dUtilities/CMakeLists.txt +++ b/dGame/dUtilities/CMakeLists.txt @@ -11,6 +11,7 @@ set(DGAME_DUTILITIES_SOURCES "BrickDatabase.cpp" "HolidayEvents.cpp" "Contraband.cpp" "ZoneEditor.cpp" + "PropertyBounds.cpp" "PropertyBuilders.cpp" "PropertyRent.cpp" "PropertyReputation.cpp" diff --git a/dGame/dUtilities/Preconditions.cpp b/dGame/dUtilities/Preconditions.cpp index 6b4c34cef..6ce7984a8 100644 --- a/dGame/dUtilities/Preconditions.cpp +++ b/dGame/dUtilities/Preconditions.cpp @@ -20,7 +20,7 @@ std::map Preconditions::cache = {}; Precondition::Precondition(const uint32_t condition) { auto query = CDClientDatabase::CreatePreppedStmt( - "SELECT type, targetLOT, targetCount FROM Preconditions WHERE id = ?;"); + "SELECT type, targetLOT, targetCount, validContexts FROM Preconditions WHERE id = ?;"); query.bind(1, static_cast(condition)); auto result = query.execQuery(); @@ -50,11 +50,28 @@ Precondition::Precondition(const uint32_t condition) { this->count = result.fieldIsNull("targetCount") ? 1 : result.getIntField("targetCount"); + // The client reads a missing value as 0, which fails the precondition + this->validContexts = static_cast(result.getInt64Field("validContexts", 0)); + result.finalize(); } -bool Precondition::Check(Entity* player) const { +bool Precondition::AppliesIn(const uint64_t validContexts, const PreconditionContext context) { + const auto value = static_cast(context); + if (value < 0) return validContexts == ~0ULL || validContexts >= 5; + + // The client tests a 32 bit flag against the 64 bit value, sign extended + const auto flag = static_cast(1U << (value & 31)); + return (validContexts & static_cast(static_cast(flag))) != 0; +} + +bool Precondition::Check(Entity* player, const PreconditionContext context) const { + // LWOPreconditionComponent::CheckPrecondition: a row with no context at all fails ("Must be set + // greater than zero"), and a row that is not for this context passes without being looked at + if (validContexts == 0) return false; + if (!AppliesIn(validContexts, context)) return true; + if (values.empty()) { return true; // There are very few of these } @@ -98,6 +115,13 @@ bool Precondition::MetByAnyValue(const PreconditionType type) { } } +uint32_t Precondition::RacingLicenceLevel(const eMissionState licenceMission) { + // The state's COMPLETE bit (UNKNOWN, -1, is no state) + const auto state = static_cast(licenceMission); + const bool completed = state > 0 && (state & static_cast(eMissionState::COMPLETE)) != 0; + return completed ? 1 : 0; +} + bool Precondition::ItemCountPasses(const PreconditionType type, const uint32_t held, const uint32_t count) { // LWOPreconditionComponent::CheckPrecondition: type 3 is the opposite of type 2's count check return type == PreconditionType::DoesNotHaveItem ? held < count : held >= count; @@ -121,7 +145,8 @@ bool Precondition::CheckValue(Entity* player, const uint32_t value) const { return !inventoryComponent->IsEquipped(value); case PreconditionType::HasItem: case PreconditionType::DoesNotHaveItem: - return ItemCountPasses(type, inventoryComponent->GetLotCount(value), count); + // an unnamed client function counts with ignoreBuyBack set: an item sold to a vendor is no longer held + return ItemCountPasses(type, inventoryComponent->GetLotCountWithoutBuyBack(value), count); case PreconditionType::HasAchievement: if (missionComponent == nullptr) return false; return missionComponent->GetMissionState(value) >= eMissionState::COMPLETE; @@ -166,13 +191,16 @@ bool Precondition::CheckValue(Entity* player, const uint32_t value) const { return true; case PreconditionType::HasRacingLicence: - return false; // TODO: requires a racing licence level on the player; DLU does not track this + return RacingLicenceLevel(missionComponent->GetMissionState(RACING_LICENCE_MISSION)) >= value; case PreconditionType::DoesNotHaveRacingLicence: - return false; // TODO: requires a racing licence level on the player; DLU does not track this + return RacingLicenceLevel(missionComponent->GetMissionState(RACING_LICENCE_MISSION)) < value; case PreconditionType::LegoClubMember: return true; // Live LU opened LEGO CLUB to All players at some point, so always return true case PreconditionType::NoInteraction: - return false; // TODO: requires tracking the player's currently active interaction object; DLU does not track this + // Passes while the player is not interacting with anything (GetPlayerInteraction answers no object). The + // client keeps that itself and does not tell the server when most interactions end; taming a pet is the + // one the server follows from start to end. + return PetComponent::GetTamingPet(player->GetObjectID()) == nullptr; case PreconditionType::HasLevel: return levelComponent->GetLevel() >= value; case PreconditionType::NotFreeTrial: @@ -244,7 +272,7 @@ std::optional Precondition::GetItemCost(Entity* player) const { if (type != PreconditionType::HasItem || count == 0) return std::nullopt; auto* const inventoryComponent = player->GetComponent(); if (!inventoryComponent) return std::nullopt; - return PickItemCost(values, count, [inventoryComponent](const LOT lot) { return inventoryComponent->GetLotCount(lot); }); + return PickItemCost(values, count, [inventoryComponent](const LOT lot) { return inventoryComponent->GetLotCountWithoutBuyBack(lot); }); } std::vector PreconditionExpression::GetItemCosts(Entity* player) const { @@ -258,14 +286,14 @@ std::vector PreconditionExpression::GetItemCosts(Entity* player) const return costs; } -bool PreconditionExpression::Check(Entity* player) const { +bool PreconditionExpression::Check(Entity* player, const PreconditionContext context) const { // LWOPreconditionComponent::msgCheckAllPreconditions: every group has to pass, a group passes with // any of its alternatives, and only the alternatives of a failed group are reported bool pass = true; for (const auto& group : m_Groups) { bool groupPasses = false; for (const auto condition : group) { - if (Preconditions::Check(player, condition)) groupPasses = true; + if (Preconditions::Check(player, condition, context)) groupPasses = true; } if (groupPasses) continue; @@ -291,8 +319,8 @@ const Precondition& Preconditions::Get(const uint32_t condition) { return *precondition; } -bool Preconditions::Check(Entity* player, const uint32_t condition) { - return Get(condition).Check(player); +bool Preconditions::Check(Entity* player, const uint32_t condition, const PreconditionContext context) { + return Get(condition).Check(player, context); } diff --git a/dGame/dUtilities/Preconditions.h b/dGame/dUtilities/Preconditions.h index 7eaf500f3..ac4551282 100644 --- a/dGame/dUtilities/Preconditions.h +++ b/dGame/dUtilities/Preconditions.h @@ -4,6 +4,7 @@ #include #include "Entity.h" +#include "eMissionState.h" enum class PreconditionType @@ -35,6 +36,15 @@ enum class PreconditionType }; +// The situation a precondition is checked in. A Preconditions row's validContexts has one bit for each context it +// applies in (LWOPreconditionComponent::CheckPrecondition). +enum class PreconditionContext : int32_t { + None = -1, // using or equipping an item, and every check that is not about an item + VendorBuy = 0, + VendorList = 1, + BoundItem = 2 // equipping an item that is bound to the player +}; + struct ItemCost { LOT lot{ LOT_NULL }; uint32_t count{ 0 }; @@ -46,7 +56,12 @@ class Precondition final public: explicit Precondition(uint32_t condition); - bool Check(Entity* player) const; + bool Check(Entity* player, PreconditionContext context = PreconditionContext::None) const; + + // Whether a row with these validContexts is checked in a context; where it is not, the precondition passes. + // With a context, its bit has to be set. Without one, rows that only name the two vendor contexts or the bound + // item one (a value under 5) are left out. + static bool AppliesIn(uint64_t validContexts, PreconditionContext context); // The items a HasItem precondition takes as a cost (a quickbuild's): the first of its LOTs the player has enough // of, and how many. Nothing for other types or when the player has none of them. @@ -58,6 +73,13 @@ public: // Whether a precondition listing several values is met by any one of them (true) or needs every one (false) static bool MetByAnyValue(PreconditionType type); + // The racing licence level the HasRacingLicence types compare their value with: 1 once the mission that makes + // the player a licensed racer has been completed, 0 before (LWORacingMissions::SendMessage) + static uint32_t RacingLicenceLevel(eMissionState licenceMission); + + // That mission + static constexpr uint32_t RACING_LICENCE_MISSION = 637; + // Whether holding this many of a LOT meets a HasItem (enough) or a DoesNotHaveItem (fewer) precondition static bool ItemCountPasses(PreconditionType type, uint32_t held, uint32_t count); @@ -69,6 +91,9 @@ private: std::vector values; uint32_t count; + + // Every context, for a row that does not say + uint64_t validContexts{ ~0ULL }; }; @@ -77,7 +102,7 @@ class PreconditionExpression final public: explicit PreconditionExpression(const std::string& conditions); - bool Check(Entity* player) const; + bool Check(Entity* player, PreconditionContext context = PreconditionContext::None) const; // The item costs of the HasItem preconditions in this expression that the player meets std::vector GetItemCosts(Entity* player) const; @@ -95,7 +120,7 @@ private: class Preconditions final { public: - static bool Check(Entity* player, uint32_t condition); + static bool Check(Entity* player, uint32_t condition, PreconditionContext context = PreconditionContext::None); static const Precondition& Get(uint32_t condition); diff --git a/dGame/dUtilities/PropertyBounds.cpp b/dGame/dUtilities/PropertyBounds.cpp new file mode 100644 index 000000000..a483253ff --- /dev/null +++ b/dGame/dUtilities/PropertyBounds.cpp @@ -0,0 +1,175 @@ +#include "PropertyBounds.h" + +#include +#include +#include + +namespace { + // The margin of the side test, and how much taller than the build space a box may be + constexpr float SIDE_MARGIN = 0.05f; + constexpr float HEIGHT_MARGIN = 0.32f; + + struct Flat { + float x{}; + float z{}; + }; + + Flat Flatten(const NiPoint3& point) { + return { point.x, point.z }; + } + + float Length(const float x, const float z) { + return std::sqrt(x * x + z * z); + } + + // y of (b - a) x (c - b): positive where the path turns towards its inside + float Turn(const Flat& a, const Flat& b, const Flat& c) { + return (b.x - a.x) * (c.z - b.z) - (b.z - a.z) * (c.x - b.x); + } + + // What one edge says about the point (an unnamed client function). distanceToEdge keeps its last value when the point is not + // beside the edge, as the client's does. + struct EdgeTest { + bool inside{}; + float distanceToStart{}; + float distanceToEnd{}; + float distanceToEdge{}; + float along{}; + + void Run(const Flat& point, const Flat& start, const Flat& end) { + const Flat edge{ end.x - start.x, end.z - start.z }; + const Flat offset{ point.x - start.x, point.z - start.z }; + distanceToStart = Length(offset.x, offset.z); + distanceToEnd = Length(point.x - end.x, point.z - end.z); + const float side = edge.x * offset.z - edge.z * offset.x; + inside = distanceToStart < SIDE_MARGIN || distanceToEnd < SIDE_MARGIN || SIDE_MARGIN < side || -SIDE_MARGIN < side; + const float lengthSquared = edge.x * edge.x + edge.z * edge.z; + along = lengthSquared <= SIDE_MARGIN ? 0.0f : (offset.x * edge.x + offset.z * edge.z) / lengthSquared; + if (along >= 0.0f && along <= 1.0f) { + distanceToEdge = Length(edge.x * along - offset.x, edge.z * along - offset.z); + } + } + }; +} + +bool PropertyBounds::PointInPolygonXZ(const NiPoint3& point, const std::vector& path, float* const distance) { + if (path.empty()) return false; + + const Flat flatPoint = Flatten(point); + Flat start = Flatten(path.back()); + Flat end = Flatten(path.front()); + // The start of the edge before the corner the point may turn out to be nearest to, and that edge's answer + Flat cornerFrom{}; + bool cornerInside = false; + // The closing edge's answer when the point lies before its start: the last corner is judged with it + bool firstInside = false; + bool result = false; + float nearest = std::numeric_limits::max(); + + EdgeTest test; + test.Run(flatPoint, start, end); + if (test.along >= 0.0f) { + if (test.along > 1.0f) { + cornerFrom = start; + cornerInside = test.inside; + } else { + result = test.inside; + nearest = test.distanceToEdge; + if (test.distanceToEdge == 0.0f) { + if (distance) *distance = std::numeric_limits::max(); + return test.inside; + } + } + } else { + firstInside = test.inside; + } + + for (size_t i = 1; i < path.size(); i++) { + start = end; + end = Flatten(path[i]); + test.Run(flatPoint, start, end); + if (distance) *distance = test.distanceToEdge; + + if (test.along >= 0.0f || nearest <= test.distanceToStart) { + if (test.along < 0.0f || test.along > 1.0f || nearest <= test.distanceToEdge) { + if (test.along > 1.0f && test.distanceToEnd < nearest) { + cornerFrom = start; + cornerInside = test.inside; + } + } else { + // Beside this edge and nearer to it than to anything before + result = test.inside; + nearest = test.distanceToEdge; + if (test.distanceToEdge == 0.0f) break; + } + } else { + // Nearest to the corner at this edge's start: inside both edges at a corner that points out, either at one + // that points in + result = Turn(cornerFrom, start, end) > 0.0f ? (cornerInside && test.inside) : (cornerInside || test.inside); + nearest = test.distanceToStart; + } + } + + // Past the last edge's end and nearest to it: the corner the path closes at + if (test.along > 1.0f && test.distanceToEnd < nearest) { + result = Turn(start, end, Flatten(path.front())) <= 0.0f ? (firstInside || test.inside) : (firstInside && test.inside); + nearest = test.distanceToEnd; + } + + if (distance) *distance = nearest; + return result; +} + +int32_t PropertyBounds::CheckBoxAgainstPath(const NiPoint3& boxMin, const NiPoint3& boxMax, const std::vector& path, const bool checkHeight, const float maxBuildHeight, float* distance) { + if (path.empty()) return NoPath; + + float unused = 0.0f; + if (!distance) distance = &unused; + + NiPoint3 plotMin = path.front(); + NiPoint3 plotMax = path.front(); + for (const auto& point : path) { + plotMin = { std::min(plotMin.x, point.x), std::min(plotMin.y, point.y), std::min(plotMin.z, point.z) }; + plotMax = { std::max(plotMax.x, point.x), std::max(plotMax.y, point.y), std::max(plotMax.z, point.z) }; + } + // The build space reaches maxBuildHeight above the lowest point of the path + if (checkHeight && maxBuildHeight > 0.0f) plotMax.y = std::max(plotMax.y, plotMin.y + maxBuildHeight); + + const NiPoint3 plotSize = plotMax - plotMin; + const NiPoint3 boxSize = boxMax - boxMin; + int32_t result = Inside; + if (plotSize.x < boxSize.x) result |= TooWide; + if (plotSize.z < boxSize.z) result |= TooLong; + if (checkHeight && plotSize.y + HEIGHT_MARGIN <= boxSize.y) result |= TooTall; + if (result != Inside) return result; + + if (boxMin.x < plotMin.x) { + *distance = plotMin.x - boxMin.x; + result = Outside; + } + if (plotMax.x < boxMax.x) { + *distance = boxMax.x - plotMax.x; + result = Outside; + } + if (boxMin.z < plotMin.z) { + *distance = plotMin.z - boxMin.z; + result = Outside; + } + if (plotMax.z < boxMax.z) { + *distance = boxMax.z - plotMax.z; + result = Outside; + } + if (checkHeight && plotMax.y < boxMax.y) { + *distance = boxMax.y - plotMax.y; + result = Outside; + } + if (result != Inside) return result; + + const NiPoint3 centre = (boxMin + boxMax) * 0.5f; + if (!PointInPolygonXZ(centre, path, distance)) return CentreOutside; + if (!PointInPolygonXZ(boxMin, path, distance)) return Outside; + if (!PointInPolygonXZ(boxMax, path, distance)) return Outside; + if (!PointInPolygonXZ({ boxMin.x, boxMin.y, boxMax.z }, path, distance)) return Outside; + if (!PointInPolygonXZ({ boxMax.x, boxMin.y, boxMin.z }, path, distance)) return Outside; + return Inside; +} diff --git a/dGame/dUtilities/PropertyBounds.h b/dGame/dUtilities/PropertyBounds.h new file mode 100644 index 000000000..42dd13653 --- /dev/null +++ b/dGame/dUtilities/PropertyBounds.h @@ -0,0 +1,39 @@ +#pragma once + +#include +#include + +#include "NiPoint3.h" + +// Whether a box is inside a property plot, as the client decides it from the boundary path and build height that +// DownloadPropertyData gives it. +namespace PropertyBounds { + // What the check answers (the client's values) + enum Result : int32_t { + NoPath = -1, // the property has no boundary path + Inside = 0, + TooWide = 1, // the box is wider than the plot (3 when it is too long as well, or instead) + TooTall = 2, // the box is taller than the plot's build space + TooLong = 3, + CentreOutside = 4, // the box's centre is outside the boundary polygon + Outside = 5 // a side of the box is outside the plot's box, or a bottom corner outside the polygon + }; + + // The point's side of the boundary edge nearest to it, heights ignored. + // The path is a closed polygon whose points run so that the inside is on the positive side of every edge; distance, + // when given, receives the distance to that nearest edge. + bool PointInPolygonXZ(const NiPoint3& point, const std::vector& path, float* distance = nullptr); + + // The plot is the box around the path's points; with checkHeight + // and a build height it reaches up to the path's lowest point plus maxBuildHeight (there is no floor). The box must + // fit in it, and its centre and four bottom corners must be inside the polygon. + int32_t CheckBoxAgainstPath(const NiPoint3& boxMin, const NiPoint3& boxMax, const std::vector& path, bool checkHeight, float maxBuildHeight, float* distance = nullptr); + + // A placed model's position against the plot. The server does not hold a model's box, so only the point is tested: + // this never refuses what the box test would allow for a model that stands on its position. + inline bool IsPositionInside(const NiPoint3& position, const std::vector& path, const float maxBuildHeight) { + const auto result = CheckBoxAgainstPath(position, position, path, true, maxBuildHeight); + // Nothing to test against is not a refusal + return result == Inside || result == NoPath; + } +} diff --git a/tests/dDatabaseTests/CMakeLists.txt b/tests/dDatabaseTests/CMakeLists.txt index 39d5543a9..3e8047723 100644 --- a/tests/dDatabaseTests/CMakeLists.txt +++ b/tests/dDatabaseTests/CMakeLists.txt @@ -16,7 +16,7 @@ target_link_libraries(dDatabaseTests ${COMMON_LIBRARIES} MariaDB::ConnCpp sqlite gtest_discover_tests(dDatabaseTests) # The chat history and chat flag tables on SQLite alone (no MariaDB/MySQL needed), so they always run. -add_executable(dDatabaseSqliteTests "ChatHistorySqliteTests.cpp") +add_executable(dDatabaseSqliteTests "ChatHistorySqliteTests.cpp" "PropertyListSqliteTests.cpp") target_include_directories(dDatabaseSqliteTests PRIVATE "${PROJECT_SOURCE_DIR}/dDatabase/GameDatabase/MySQL" diff --git a/tests/dDatabaseTests/PropertyListSqliteTests.cpp b/tests/dDatabaseTests/PropertyListSqliteTests.cpp new file mode 100644 index 000000000..e4f0db756 --- /dev/null +++ b/tests/dDatabaseTests/PropertyListSqliteTests.cpp @@ -0,0 +1,136 @@ +/** + * The property browser's list query (IProperty::GetProperties) on SQLite. Uses the database file that + * ChatHistorySqliteTests.cpp's environment creates and migrates. + */ +#include + +#include +#include +#include + +#include "eGameMasterLevel.h" +#include "ePropertySortType.h" +#include "SQLiteDatabase.h" + +namespace { + constexpr LWOOBJID P_ALICE = 1152921510000100001; + constexpr LWOOBJID P_ALICE_TWO = 1152921510000100002; + constexpr LWOOBJID P_BOB = 1152921510000100003; + constexpr LWOOBJID P_CAROL = 1152921510000100004; + constexpr LWOOBJID P_DAVE = 1152921510000100005; + constexpr LWOOBJID PROPERTY_BASE = 1152921510000200000; + constexpr uint32_t MAP = 1150; + + // Alice and AliceTwo share an account; Bob is Alice's friend; Carol and Dave are strangers. + // Everybody owns a property on the map: Carol's is public and named, the others are private and unnamed. + class PropertyListSqlite : public ::testing::Test { + protected: + static inline std::unique_ptr db; + + static void SetUpTestSuite() { + db = std::make_unique(); + db->Connect(); + db->InsertNewAccount("propAlice", "$2a$12$hash", eGameMasterLevel::CIVILIAN); + db->InsertNewAccount("propBob", "$2a$12$hash", eGameMasterLevel::CIVILIAN); + db->InsertNewAccount("propCarol", "$2a$12$hash", eGameMasterLevel::CIVILIAN); + db->InsertNewAccount("propDave", "$2a$12$hash", eGameMasterLevel::CIVILIAN); + const auto account = [](const char* name) { return db->GetAccountInfo(name)->id; }; + const auto character = [](const std::string& name, const LWOOBJID id, const uint32_t accountId) { + db->InsertNewCharacter(ICharInfo::Info{ name, "", id, accountId, false, 0, static_cast(0) }); + }; + character("PropAlice", P_ALICE, account("propAlice")); + character("PropAliceTwo", P_ALICE_TWO, account("propAlice")); + character("PropBob", P_BOB, account("propBob")); + character("PropCarol", P_CAROL, account("propCarol")); + character("PropDave", P_DAVE, account("propDave")); + db->AddFriend(P_ALICE, P_BOB); + + uint32_t index = 0; + const auto property = [&index](const LWOOBJID owner, const std::string& name, const std::string& description, const int32_t privacy) { + IProperty::Info info{}; + info.id = PROPERTY_BASE + ++index; + info.ownerId = owner; + info.cloneId = db->GetCharacterInfo(owner)->cloneId; + info.name = name; + info.description = description; + db->InsertNewProperty(info, 1, LWOZONEID(MAP, 0, info.cloneId)); + db->SetPropertyPrivacy(info.id, privacy); + }; + property(P_ALICE, "", "", 0); + property(P_ALICE_TWO, "", "", 0); + property(P_BOB, "", "", 0); + property(P_CAROL, "Carol's Keep", "A tall tower", 2); + property(P_DAVE, "", "", 2); + } + + static void TearDownTestSuite() { + if (db) db->Destroy("PropertyListSqliteTests"); + db.reset(); + } + + static IProperty::PropertyLookup Lookup(const ePropertySortType sort, const uint32_t minimumPrivacy, const std::string& search = "") { + IProperty::PropertyLookup lookup; + lookup.mapId = MAP; + lookup.searchString = search; + lookup.sortChoice = sort; + lookup.playerId = P_ALICE; + lookup.numResults = 12; + lookup.startIndex = 0; + lookup.playerSort = minimumPrivacy; + return lookup; + } + + static std::set Owners(const IProperty::PropertyEntranceResult& result) { + std::set owners; + for (const auto& entry : result.entries) owners.insert(entry.ownerId); + EXPECT_EQ(owners.size(), result.entries.size()); + EXPECT_EQ(result.totalEntriesMatchingQuery, static_cast(result.entries.size())); + return owners; + } + }; +} + +// Live friends lists held the friends' properties whatever their access type and the properties of the account's other +// characters, and never the player's own property or a stranger's. +TEST_F(PropertyListSqlite, FriendsListHoldsFriendsAndTheAccountsOtherCharacters) { + const auto owners = Owners(db->GetProperties(Lookup(SORT_TYPE_FRIENDS, 0))); + EXPECT_EQ(owners, (std::set{ P_ALICE_TWO, P_BOB })); +} + +// With a minimum access type the same query still filters (the caller passes 0 for the friends list) +TEST_F(PropertyListSqlite, FriendsListStillHonoursTheMinimumAccessType) { + EXPECT_TRUE(Owners(db->GetProperties(Lookup(SORT_TYPE_FRIENDS, 1))).empty()); +} + +// The other lists are unchanged: public properties only +TEST_F(PropertyListSqlite, PublicListsHoldPublicPropertiesOnly) { + EXPECT_EQ(Owners(db->GetProperties(Lookup(SORT_TYPE_RECENT, 2))), (std::set{ P_CAROL, P_DAVE })); + EXPECT_EQ(Owners(db->GetProperties(Lookup(SORT_TYPE_REPUTATION, 2))), (std::set{ P_CAROL, P_DAVE })); +} + +// The client shows the map's default name and description for a property with none of its own, and sets +// bIncludeNullAddress / bIncludeNullDescription when the search text is part of that default, so these are found. +TEST_F(PropertyListSqlite, SearchFindsUnnamedPropertiesWhenAskedTo) { + auto lookup = Lookup(SORT_TYPE_RECENT, 2, "Avant"); + EXPECT_TRUE(Owners(db->GetProperties(lookup)).empty()); + + lookup.includeNullName = true; + EXPECT_EQ(Owners(db->GetProperties(lookup)), (std::set{ P_DAVE })); + + lookup.includeNullName = false; + lookup.includeNullDescription = true; + EXPECT_EQ(Owners(db->GetProperties(lookup)), (std::set{ P_DAVE })); + + // A named property is still only found by its own text + lookup.searchString = "Keep"; + EXPECT_EQ(Owners(db->GetProperties(lookup)), (std::set{ P_CAROL, P_DAVE })); + lookup.includeNullDescription = false; + EXPECT_EQ(Owners(db->GetProperties(lookup)), (std::set{ P_CAROL })); +} + +TEST_F(PropertyListSqlite, FriendsSearchFindsUnnamedPropertiesWhenAskedTo) { + auto lookup = Lookup(SORT_TYPE_FRIENDS, 0, "Avant"); + EXPECT_TRUE(Owners(db->GetProperties(lookup)).empty()); + lookup.includeNullName = true; + EXPECT_EQ(Owners(db->GetProperties(lookup)), (std::set{ P_ALICE_TWO, P_BOB })); +} diff --git a/tests/dGameTests/CMakeLists.txt b/tests/dGameTests/CMakeLists.txt index a2e925f81..1a53c7689 100644 --- a/tests/dGameTests/CMakeLists.txt +++ b/tests/dGameTests/CMakeLists.txt @@ -18,6 +18,7 @@ set(DGAMETEST_SOURCES "PowerUpStatisticTests.cpp" "PlayerStatisticTests.cpp" "BrickByBrickTests.cpp" + "PropertyBoundsTests.cpp" "PropertyBuildersTests.cpp" "ModularBuildTableTests.cpp" "ModularBuildIdMigrationTests.cpp" @@ -27,6 +28,7 @@ set(DGAMETEST_SOURCES "SetCurrencySourceTests.cpp" "LootDropPositionTests.cpp" "LootActivityCoinsTests.cpp" + "PreconditionCheckTests.cpp" "PreconditionItemCostTests.cpp" "SpiderQueenTests.cpp" "TacArcTests.cpp" diff --git a/tests/dGameTests/PreconditionCheckTests.cpp b/tests/dGameTests/PreconditionCheckTests.cpp new file mode 100644 index 000000000..fb77f2904 --- /dev/null +++ b/tests/dGameTests/PreconditionCheckTests.cpp @@ -0,0 +1,137 @@ +// Preconditions checked against a player, as LWOPreconditionComponent::CheckPrecondition checks them +#include "GameDependencies.h" + +#include "CDClientDatabase.h" +#include "CDComponentsRegistryTable.h" +#include "CDItemComponentTable.h" +#include "Character.h" +#include "DestroyableComponent.h" +#include "Entity.h" +#include "InventoryComponent.h" +#include "Item.h" +#include "LevelProgressionComponent.h" +#include "MissionComponent.h" +#include "Preconditions.h" +#include "eReplicaComponentType.h" + +#include +#include +#include + +class PreconditionCheckTests : public GameDependenciesTest { +protected: + static constexpr LOT BRICK = 6194; + + std::unique_ptr player; + std::unique_ptr character; + InventoryComponent* inventory{}; + LWOOBJID nextId = 0x1000000000008000LL; + // Preconditions are cached by id for the life of the process: every test takes ids of its own + static inline uint32_t nextPrecondition = 91000; + + void SetUp() override { + SetUpDependencies(); + CDClientDatabase::Connect(":memory:"); + CDClientDatabase::ExecuteDML("CREATE TABLE Preconditions (id INTEGER, type INTEGER, targetLOT TEXT, targetCount INTEGER, validContexts INTEGER);"); + CDClientDatabase::ExecuteDML("CREATE TABLE ItemSets (setID INTEGER, itemIDs TEXT);"); + CDClientDatabase::ExecuteDML("CREATE TABLE Missions (id INTEGER, isMission INTEGER);"); + CDClientDatabase::ExecuteDML("CREATE TABLE PlayerFlags (id INTEGER, SessionOnly INTEGER, OnlySetByServer INTEGER, SessionZoneOnly INTEGER);"); + + const auto componentID = static_cast(96000 + BRICK); + auto& registry = CDClientManager::GetEntriesMutable(); + registry.insert_or_assign(static_cast(BRICK), componentID); + registry.insert_or_assign(static_cast(eReplicaComponentType::ITEM) << 32 | static_cast(BRICK), componentID); + CDItemComponent component{}; + component.id = componentID; + component.stackSize = 100; + CDClientManager::GetEntriesMutable().insert_or_assign(componentID, component); + + info.lot = 1; + registry.insert_or_assign(static_cast(info.lot), 0); + player = std::make_unique(0x1000000000000002LL, info); + inventory = player->AddComponent(-1); // before the character, so it doesn't load a save + player->AddComponent(-1); + player->AddComponent(-1); + player->AddComponent(-1); + character = std::make_unique(1, nullptr); + player->SetCharacter(character.get()); + } + + void TearDown() override { + player->SetCharacter(nullptr); + player.reset(); + character.reset(); + TearDownDependencies(); + } + + uint32_t Row(const PreconditionType type, const std::string& values, const uint32_t count, const uint64_t validContexts) { + const auto id = nextPrecondition++; + CDClientDatabase::ExecuteDML("INSERT INTO Preconditions VALUES (" + std::to_string(id) + ", " + std::to_string(static_cast(type)) + + ", '" + values + "', " + std::to_string(count) + ", " + std::to_string(validContexts) + ");"); + return id; + } + + Item* Give(const eInventoryType type, const uint32_t count) { + auto* const bag = inventory->GetInventory(type); + return new Item(nextId++, BRICK, bag, static_cast(bag->GetItems().size()), count, false, {}, LWOOBJID_EMPTY, LWOOBJID_EMPTY, eLootSourceType::NONE); + } +}; + +// A row is only looked at in the contexts it names; elsewhere the precondition passes. With no context at all it fails. +TEST_F(PreconditionCheckTests, ARowOutsideItsContextsPasses) { + // The player holds none of the item, so each of these fails wherever it is looked at + const auto everywhere = Row(PreconditionType::HasItem, "6194", 1, 255); + const auto vendorsOnly = Row(PreconditionType::HasItem, "6194", 1, 3); + const auto notWhenBound = Row(PreconditionType::HasItem, "6194", 1, 249); + const auto nowhere = Row(PreconditionType::HasItem, "6194", 1, 0); + + EXPECT_FALSE(Preconditions::Check(player.get(), everywhere)); + EXPECT_FALSE(Preconditions::Check(player.get(), everywhere, PreconditionContext::BoundItem)); + + EXPECT_TRUE(Preconditions::Check(player.get(), vendorsOnly)); + EXPECT_TRUE(Preconditions::Check(player.get(), vendorsOnly, PreconditionContext::BoundItem)); + EXPECT_FALSE(Preconditions::Check(player.get(), vendorsOnly, PreconditionContext::VendorBuy)); + + EXPECT_FALSE(Preconditions::Check(player.get(), notWhenBound)); + EXPECT_TRUE(Preconditions::Check(player.get(), notWhenBound, PreconditionContext::BoundItem)); + + EXPECT_FALSE(Preconditions::Check(player.get(), nowhere)); + EXPECT_FALSE(Preconditions::Check(player.get(), nowhere, PreconditionContext::VendorBuy)); + + // A list takes the context to each of its rows + const auto list = std::to_string(notWhenBound) + ";" + std::to_string(vendorsOnly); + EXPECT_FALSE(PreconditionExpression(list).Check(player.get())); + EXPECT_TRUE(PreconditionExpression(list).Check(player.get(), PreconditionContext::BoundItem)); +} + +// Type 19 passes while the player interacts with nothing +TEST_F(PreconditionCheckTests, NoInteractionPassesWhenNothingIsGoingOn) { + EXPECT_TRUE(Preconditions::Check(player.get(), Row(PreconditionType::NoInteraction, "1", 1, 253))); +} + +// Types 16 and 17: a player who has not done the licence mission has licence level 0 +TEST_F(PreconditionCheckTests, RacingLicenceOfAPlayerWithoutTheMission) { + EXPECT_FALSE(Preconditions::Check(player.get(), Row(PreconditionType::HasRacingLicence, "1", 1, 253))); + EXPECT_TRUE(Preconditions::Check(player.get(), Row(PreconditionType::DoesNotHaveRacingLicence, "1", 1, 253))); +} + +// Types 2 and 3 count the item everywhere but in the vendor buy back inventory (the client's count sets ignoreBuyBack) +TEST_F(PreconditionCheckTests, ItemsSoldToAVendorAreNotHeld) { + const auto hasFive = Row(PreconditionType::HasItem, "6194", 5, 255); + const auto hasNone = Row(PreconditionType::DoesNotHaveItem, "6194", 1, 255); + + Give(eInventoryType::VENDOR_BUYBACK, 5); + EXPECT_EQ(inventory->GetLotCount(BRICK), 5u); + EXPECT_EQ(inventory->GetLotCountWithoutBuyBack(BRICK), 0u); + EXPECT_FALSE(Preconditions::Check(player.get(), hasFive)); + EXPECT_TRUE(Preconditions::Check(player.get(), hasNone)); + // Nothing is taken as a cost from what the player no longer holds + EXPECT_FALSE(Preconditions::Get(hasFive).GetItemCost(player.get()).has_value()); + + Give(eInventoryType::ITEMS, 3); + Give(eInventoryType::VAULT_ITEMS, 2); + EXPECT_EQ(inventory->GetLotCountWithoutBuyBack(BRICK), 5u); + EXPECT_TRUE(Preconditions::Check(player.get(), hasFive)); + EXPECT_FALSE(Preconditions::Check(player.get(), hasNone)); + EXPECT_EQ(Preconditions::Get(hasFive).GetItemCost(player.get()), (ItemCost{ BRICK, 5 })); +} diff --git a/tests/dGameTests/PreconditionItemCostTests.cpp b/tests/dGameTests/PreconditionItemCostTests.cpp index 015a31a4b..63e25ed93 100644 --- a/tests/dGameTests/PreconditionItemCostTests.cpp +++ b/tests/dGameTests/PreconditionItemCostTests.cpp @@ -72,3 +72,55 @@ TEST(PreconditionItemCostTests, ListIsGroupsOfAlternatives) { EXPECT_EQ(PreconditionExpression::Parse("1,2:3 ; 4"), (Groups{ { 1 }, { 2 }, { 3 }, { 4 } })); EXPECT_EQ(PreconditionExpression::Parse(";5;"), (Groups{ { 5 } })); } + +// LWOPreconditionComponent::CheckPrecondition: with a context, a row is checked when its validContexts +// has the context's bit; where it is not checked, the precondition passes. The table holds 255, 253, 252, 249 and 3. +TEST(PreconditionItemCostTests, ValidContextsWithAContext) { + using enum PreconditionContext; + for (const auto context : { VendorBuy, VendorList, BoundItem }) EXPECT_TRUE(Precondition::AppliesIn(255, context)); + // 253: not while a vendor lists its items + EXPECT_TRUE(Precondition::AppliesIn(253, VendorBuy)); + EXPECT_FALSE(Precondition::AppliesIn(253, VendorList)); + EXPECT_TRUE(Precondition::AppliesIn(253, BoundItem)); + // 252: not at a vendor (the thinking hat and build mode requirements of bricks and models) + EXPECT_FALSE(Precondition::AppliesIn(252, VendorBuy)); + EXPECT_FALSE(Precondition::AppliesIn(252, VendorList)); + EXPECT_TRUE(Precondition::AppliesIn(252, BoundItem)); + // 249: the level requirements, which a vendor's list and an item bound to the player leave out + EXPECT_TRUE(Precondition::AppliesIn(249, VendorBuy)); + EXPECT_FALSE(Precondition::AppliesIn(249, VendorList)); + EXPECT_FALSE(Precondition::AppliesIn(249, BoundItem)); + // 3: at a vendor only + EXPECT_TRUE(Precondition::AppliesIn(3, VendorBuy)); + EXPECT_TRUE(Precondition::AppliesIn(3, VendorList)); + EXPECT_FALSE(Precondition::AppliesIn(3, BoundItem)); + // Every bit set + EXPECT_TRUE(Precondition::AppliesIn(~0ULL, BoundItem)); + EXPECT_TRUE(Precondition::AppliesIn(~0ULL, static_cast(40))); + // The flag is 32 bits wide, taken from the context's low 5 bits and sign extended + EXPECT_TRUE(Precondition::AppliesIn(1ULL << 31, static_cast(31))); + EXPECT_TRUE(Precondition::AppliesIn(1ULL << 40, static_cast(31))); + EXPECT_FALSE(Precondition::AppliesIn(1ULL << 40, static_cast(8))); + EXPECT_TRUE(Precondition::AppliesIn(1ULL << 8, static_cast(40))); +} + +// Without a context every row is checked, except those that only name the vendor or bound item contexts (under 5): +// preconditions 338 and 339 (a mission completed, validContexts 3) do not stop an item from being used +TEST(PreconditionItemCostTests, ValidContextsWithoutAContext) { + using enum PreconditionContext; + for (const uint64_t all : { 255ULL, 253ULL, 252ULL, 249ULL, 5ULL, 8ULL, ~0ULL }) EXPECT_TRUE(Precondition::AppliesIn(all, None)) << all; + for (const uint64_t few : { 1ULL, 2ULL, 3ULL, 4ULL }) EXPECT_FALSE(Precondition::AppliesIn(few, None)) << few; +} + +// Types 16 and 17 compare their value with the player's racing licence level, which the client's mission component +// answers (LWORacingMissions::SendMessage): 1 once mission 637 has been completed, repeatable or not +TEST(PreconditionItemCostTests, RacingLicenceLevelFollowsTheLicenceMission) { + EXPECT_EQ(Precondition::RACING_LICENCE_MISSION, 637u); + for (const auto state : { eMissionState::UNKNOWN, eMissionState::AVAILABLE, eMissionState::ACTIVE, eMissionState::READY_TO_COMPLETE }) { + EXPECT_EQ(Precondition::RacingLicenceLevel(state), 0u) << static_cast(state); + } + for (const auto state : { eMissionState::COMPLETE, eMissionState::COMPLETE_AVAILABLE, eMissionState::COMPLETE_ACTIVE, + eMissionState::COMPLETE_READY_TO_COMPLETE }) { + EXPECT_EQ(Precondition::RacingLicenceLevel(state), 1u) << static_cast(state); + } +} diff --git a/tests/dGameTests/PropertyBoundsTests.cpp b/tests/dGameTests/PropertyBoundsTests.cpp new file mode 100644 index 000000000..210ecbd86 --- /dev/null +++ b/tests/dGameTests/PropertyBoundsTests.cpp @@ -0,0 +1,132 @@ +// The plot test a placed model's position goes through: the client's box against the boundary path and build height. +#include "PropertyBounds.h" + +#include +#include +#include + +namespace { + constexpr float GROUND = 400.0f; + + std::vector Path(const std::vector>& points) { + std::vector path; + for (const auto& [x, z] : points) path.emplace_back(x, GROUND, z); + return path; + } + + // The inside is on the positive side of every edge, as on every property map + const auto SQUARE = Path({ { 0, 0 }, { 10, 0 }, { 10, 10 }, { 0, 10 } }); + // An L: the square from (10, 10) to (20, 20) is cut out + const auto ELL = Path({ { 0, 0 }, { 20, 0 }, { 20, 10 }, { 10, 10 }, { 10, 20 }, { 0, 20 } }); + + bool InPolygon(const std::vector& path, const float x, const float z) { + return PropertyBounds::PointInPolygonXZ({ x, GROUND, z }, path); + } +} + +TEST(PropertyBoundsTests, PointsInsideAndOutsideASquare) { + EXPECT_TRUE(InPolygon(SQUARE, 5, 5)); + EXPECT_TRUE(InPolygon(SQUARE, 0.01f, 0.01f)); + // On an edge and on a corner counts as inside + EXPECT_TRUE(InPolygon(SQUARE, 5, 0)); + EXPECT_TRUE(InPolygon(SQUARE, 0, 0)); + EXPECT_TRUE(InPolygon(SQUARE, 10, 10)); + // Beside each edge + EXPECT_FALSE(InPolygon(SQUARE, -1, 5)); + EXPECT_FALSE(InPolygon(SQUARE, 11, 5)); + EXPECT_FALSE(InPolygon(SQUARE, 5, -1)); + EXPECT_FALSE(InPolygon(SQUARE, 5, 11)); + // Past each corner, where no edge is beside the point + EXPECT_FALSE(InPolygon(SQUARE, -1, -1)); + EXPECT_FALSE(InPolygon(SQUARE, 11, 11)); + EXPECT_FALSE(InPolygon(SQUARE, 11, -1)); + EXPECT_FALSE(InPolygon(SQUARE, -1, 11)); + EXPECT_FALSE(InPolygon(SQUARE, -3, -0.5f)); + EXPECT_FALSE(InPolygon(SQUARE, 13, 10.5f)); +} + +TEST(PropertyBoundsTests, TheHeightOfThePointAndOfThePathIsIgnoredByThePolygon) { + auto path = SQUARE; + path[2].y = GROUND + 30.0f; + EXPECT_TRUE(PropertyBounds::PointInPolygonXZ({ 5, -1000, 5 }, path)); + EXPECT_FALSE(PropertyBounds::PointInPolygonXZ({ 11, GROUND, 5 }, path)); +} + +TEST(PropertyBoundsTests, TheCornerThatPointsInwardsOfAnEll) { + EXPECT_TRUE(InPolygon(ELL, 5, 5)); + EXPECT_TRUE(InPolygon(ELL, 15, 5)); + EXPECT_TRUE(InPolygon(ELL, 5, 15)); + EXPECT_TRUE(InPolygon(ELL, 9, 9)); + EXPECT_TRUE(InPolygon(ELL, 10, 10)); + // In the part that is cut out + EXPECT_FALSE(InPolygon(ELL, 15, 15)); + EXPECT_FALSE(InPolygon(ELL, 11, 11)); + EXPECT_FALSE(InPolygon(ELL, 10.5f, 10.5f)); + EXPECT_FALSE(InPolygon(ELL, 12, 10.2f)); + EXPECT_FALSE(InPolygon(ELL, 10.2f, 12)); + EXPECT_FALSE(InPolygon(ELL, 25, 5)); + EXPECT_FALSE(InPolygon(ELL, 5, 25)); + EXPECT_FALSE(InPolygon(ELL, 21, 11)); +} + +// The client's test depends on the direction the path runs in: the other way round, inside and outside swap +TEST(PropertyBoundsTests, APathTheOtherWayRoundReadsInsideOut) { + auto reversed = SQUARE; + std::reverse(reversed.begin(), reversed.end()); + EXPECT_FALSE(InPolygon(reversed, 5, 5)); + EXPECT_TRUE(InPolygon(reversed, -1, 5)); +} + +TEST(PropertyBoundsTests, ThePositionOfAModel) { + EXPECT_TRUE(PropertyBounds::IsPositionInside({ 5, GROUND, 5 }, ELL, 128.0f)); + EXPECT_TRUE(PropertyBounds::IsPositionInside({ 15, GROUND + 3, 5 }, ELL, 128.0f)); + // Outside the box around the path, and inside it but outside the path + EXPECT_FALSE(PropertyBounds::IsPositionInside({ -5, GROUND, 5 }, ELL, 128.0f)); + EXPECT_FALSE(PropertyBounds::IsPositionInside({ 5, GROUND, 21 }, ELL, 128.0f)); + EXPECT_FALSE(PropertyBounds::IsPositionInside({ 15, GROUND, 15 }, ELL, 128.0f)); +} + +// The build space ends maxBuildHeight above the path's lowest point; there is no floor +TEST(PropertyBoundsTests, TheBuildHeight) { + EXPECT_TRUE(PropertyBounds::IsPositionInside({ 5, GROUND + 128.0f, 5 }, SQUARE, 128.0f)); + EXPECT_FALSE(PropertyBounds::IsPositionInside({ 5, GROUND + 128.5f, 5 }, SQUARE, 128.0f)); + EXPECT_TRUE(PropertyBounds::IsPositionInside({ 5, GROUND - 50.0f, 5 }, SQUARE, 128.0f)); + + // Counted from the lowest point; a path point above that height raises the ceiling to itself + auto sloped = SQUARE; + sloped[0].y = GROUND - 10.0f; + EXPECT_TRUE(PropertyBounds::IsPositionInside({ 5, GROUND + 6.0f, 5 }, sloped, 16.0f)); + EXPECT_FALSE(PropertyBounds::IsPositionInside({ 5, GROUND + 6.5f, 5 }, sloped, 16.0f)); + sloped[1].y = GROUND + 20.0f; + EXPECT_TRUE(PropertyBounds::IsPositionInside({ 5, GROUND + 20.0f, 5 }, sloped, 16.0f)); + EXPECT_FALSE(PropertyBounds::IsPositionInside({ 5, GROUND + 20.5f, 5 }, sloped, 16.0f)); + + // No build height: the path's own heights are the space + EXPECT_FALSE(PropertyBounds::IsPositionInside({ 5, GROUND + 1.0f, 5 }, SQUARE, 0.0f)); + EXPECT_TRUE(PropertyBounds::IsPositionInside({ 5, GROUND, 5 }, SQUARE, 0.0f)); +} + +// A property without a boundary path has nothing to refuse a placement with +TEST(PropertyBoundsTests, NoPathRefusesNothing) { + EXPECT_EQ(PropertyBounds::CheckBoxAgainstPath({ 1, 2, 3 }, { 1, 2, 3 }, {}, true, 128.0f), PropertyBounds::NoPath); + EXPECT_TRUE(PropertyBounds::IsPositionInside({ 1, 2, 3 }, {}, 128.0f)); + EXPECT_FALSE(PropertyBounds::PointInPolygonXZ({ 1, 2, 3 }, {})); +} + +TEST(PropertyBoundsTests, ABoxAgainstThePlot) { + using namespace PropertyBounds; + EXPECT_EQ(CheckBoxAgainstPath({ 2, GROUND, 2 }, { 8, GROUND + 5, 8 }, SQUARE, true, 128.0f), Inside); + // Larger than the plot + EXPECT_EQ(CheckBoxAgainstPath({ -1, GROUND, 2 }, { 12, GROUND + 5, 8 }, SQUARE, true, 128.0f), TooWide); + EXPECT_EQ(CheckBoxAgainstPath({ 2, GROUND, -1 }, { 8, GROUND + 5, 12 }, SQUARE, true, 128.0f), TooLong); + EXPECT_EQ(CheckBoxAgainstPath({ 2, GROUND, 2 }, { 8, GROUND + 129, 8 }, SQUARE, true, 128.0f), TooTall); + EXPECT_EQ(CheckBoxAgainstPath({ 2, GROUND, 2 }, { 8, GROUND + 129, 8 }, SQUARE, false, 128.0f), Inside); + // Sticking out of a side, and out of the top + EXPECT_EQ(CheckBoxAgainstPath({ 6, GROUND, 2 }, { 12, GROUND + 5, 8 }, SQUARE, true, 128.0f), Outside); + EXPECT_EQ(CheckBoxAgainstPath({ 2, GROUND + 125, 2 }, { 8, GROUND + 130, 8 }, SQUARE, true, 128.0f), Outside); + EXPECT_EQ(CheckBoxAgainstPath({ 2, GROUND + 125, 2 }, { 8, GROUND + 130, 8 }, SQUARE, false, 128.0f), Inside); + // Inside the box around the path, with the centre or one bottom corner in the part of the L that is cut out + EXPECT_EQ(CheckBoxAgainstPath({ 12, GROUND, 12 }, { 18, GROUND + 5, 18 }, ELL, true, 128.0f), CentreOutside); + EXPECT_EQ(CheckBoxAgainstPath({ 4, GROUND, 4 }, { 12, GROUND + 5, 12 }, ELL, true, 128.0f), Outside); + EXPECT_EQ(CheckBoxAgainstPath({ 2, GROUND, 2 }, { 9, GROUND + 5, 9 }, ELL, true, 128.0f), Inside); +} diff --git a/tests/dGameTests/dComponentsTests/CMakeLists.txt b/tests/dGameTests/dComponentsTests/CMakeLists.txt index a4a15cadd..d5c8fe3fa 100644 --- a/tests/dGameTests/dComponentsTests/CMakeLists.txt +++ b/tests/dGameTests/dComponentsTests/CMakeLists.txt @@ -6,6 +6,7 @@ set(DCOMPONENTS_TESTS "DestroyableLevelConfigTests.cpp" "ProximityMonitorComponentTests.cpp" "RailActivatorComponentTests.cpp" + "GhostComponentSaveTests.cpp" "MountControlComponentTests.cpp" "ConstructionOnlyComponentTests.cpp" "PropertyEntranceComponentTests.cpp" diff --git a/tests/dGameTests/dComponentsTests/DestroyableComponentTests.cpp b/tests/dGameTests/dComponentsTests/DestroyableComponentTests.cpp index 63382366b..347e893a1 100644 --- a/tests/dGameTests/dComponentsTests/DestroyableComponentTests.cpp +++ b/tests/dGameTests/dComponentsTests/DestroyableComponentTests.cpp @@ -793,9 +793,9 @@ TEST_F(DestroyableTest, RequestResurrectOnlyWhenDead) { // whatever its factions TEST_F(DestroyableTest, EnemyPreconditionDecidesEnemies) { if (!CDClientDatabase::isConnected) CDClientDatabase::Connect(":memory:"); - CDClientDatabase::ExecuteDML("CREATE TABLE IF NOT EXISTS Preconditions (id INTEGER, type INTEGER, targetLOT TEXT, targetCount INTEGER);"); - CDClientDatabase::ExecuteDML("INSERT INTO Preconditions VALUES (90201, 2, '6194', 1);"); // has an item the asker lacks - CDClientDatabase::ExecuteDML("INSERT INTO Preconditions VALUES (90202, 2, '', 1);"); // always met + CDClientDatabase::ExecuteDML("CREATE TABLE IF NOT EXISTS Preconditions (id INTEGER, type INTEGER, targetLOT TEXT, targetCount INTEGER, validContexts INTEGER);"); + CDClientDatabase::ExecuteDML("INSERT INTO Preconditions VALUES (90201, 2, '6194', 1, 255);"); // has an item the asker lacks + CDClientDatabase::ExecuteDML("INSERT INTO Preconditions VALUES (90202, 2, '', 1, 255);"); // always met Entity target(0x0102030405060709LL, info); auto* targetDestroyable = target.AddComponent(-1); diff --git a/tests/dGameTests/dComponentsTests/EquipMessagesTests.cpp b/tests/dGameTests/dComponentsTests/EquipMessagesTests.cpp index f129a79a8..1448261a4 100644 --- a/tests/dGameTests/dComponentsTests/EquipMessagesTests.cpp +++ b/tests/dGameTests/dComponentsTests/EquipMessagesTests.cpp @@ -17,6 +17,7 @@ #include "InventoryComponent.h" #include "InventoryMessages.h" #include "Item.h" +#include "PropertyEntranceComponent.h" #include "SkillMessages.h" #include "ZoneMessages.h" #include "eReplicaComponentType.h" @@ -217,6 +218,27 @@ TEST_F(EquipMessagesTests, UnequippingAndSlotsWithoutAnEffect) { // A worn jetpack is found again after a world load, so jetpack mode can be sent again: live sent SetJetPackMode (use, // bypass checks, effect 167) about 100 packets after the player's own construction in 12 of 28 world loads of a player // with a jetpack, and constructed the player in jetpack mode in the other 16. +// Opening a property launch pad puts the rocket in the player's hands; leaving the browser without launching (the +// client's "CancelLaunch" event) takes it off again +TEST_F(EquipMessagesTests, CancellingAPropertyLaunchTakesTheRocketOff) { + auto* const rocket = Give(ROCKET); + auto* const sword = Give(SWORD); + sword->Equip(true); + auto* const characterComponent = entity->GetComponent(); + characterComponent->SetLastRocketItemID(rocket->GetId()); + ASSERT_EQ(characterComponent->RocketEquip(entity.get()), rocket); + ASSERT_TRUE(rocket->IsEquipped()); + + PropertyEntranceComponent::CancelLaunch(*entity); + EXPECT_FALSE(rocket->IsEquipped()); + EXPECT_TRUE(sword->IsEquipped()); + + // Cancelling with nothing in hand changes nothing + PropertyEntranceComponent::CancelLaunch(*entity); + EXPECT_FALSE(rocket->IsEquipped()); + EXPECT_TRUE(sword->IsEquipped()); +} + TEST_F(EquipMessagesTests, AWornJetPackIsFoundAfterAWorldLoad) { constexpr LOT JETPACK = 1727; // skill 306, behavior 3569 on equip RegisterLot(JETPACK, "back"); diff --git a/tests/dGameTests/dComponentsTests/GhostComponentSaveTests.cpp b/tests/dGameTests/dComponentsTests/GhostComponentSaveTests.cpp new file mode 100644 index 000000000..d3cdc84e2 --- /dev/null +++ b/tests/dGameTests/dComponentsTests/GhostComponentSaveTests.cpp @@ -0,0 +1,92 @@ +// GM invisibility in a character's save: LWOGhostComponent::LoadFromSaveData reads under , +// and the client hides its own character again after loading when it is set. +#include "GameDependencies.h" + +#include "Entity.h" +#include "GhostComponent.h" + +#include "tinyxml2.h" + +#include +#include + +class GhostComponentSaveTests : public GameDependenciesTest { +protected: + void SetUp() override { SetUpDependencies(); } + void TearDown() override { TearDownDependencies(); } + + static std::string Print(const tinyxml2::XMLDocument& doc) { + tinyxml2::XMLPrinter printer(nullptr, true); + doc.Print(&printer); + return printer.CStr(); + } + + static void SetInvisible(GhostComponent& ghost, const tinyxml2::XMLDocument& from) { + ghost.LoadFromSaveData(from); + } +}; + +// A save from before the element was written loads as visible and stays byte for byte what it was +TEST_F(GhostComponentSaveTests, OldSaveLoadsVisibleAndIsNotChanged) { + tinyxml2::XMLDocument doc; + ASSERT_EQ(doc.Parse(R"()"), tinyxml2::XML_SUCCESS); + Entity player(80, info); + auto* const ghost = player.AddComponent(-1); + ghost->LoadFromSaveData(doc); + EXPECT_FALSE(ghost->IsGMInvisible()); + ghost->WriteSaveData(doc); + EXPECT_EQ(Print(doc), R"()"); +} + +// An invisible GM's save gains the element, and it reads back as invisible on the next world +TEST_F(GhostComponentSaveTests, InvisibilitySurvivesASaveAndALoad) { + tinyxml2::XMLDocument invisible; + ASSERT_EQ(invisible.Parse(R"()"), tinyxml2::XML_SUCCESS); + + tinyxml2::XMLDocument doc; + ASSERT_EQ(doc.Parse(R"()"), tinyxml2::XML_SUCCESS); + Entity player(81, info); + auto* const ghost = player.AddComponent(-1); + SetInvisible(*ghost, invisible); + ASSERT_TRUE(ghost->IsGMInvisible()); + ghost->WriteSaveData(doc); + EXPECT_EQ(Print(doc), R"()"); + // Saving again changes nothing + ghost->WriteSaveData(doc); + EXPECT_EQ(Print(doc), R"()"); + + Entity nextWorld(82, info); + auto* const loaded = nextWorld.AddComponent(-1); + loaded->LoadFromSaveData(doc); + EXPECT_TRUE(loaded->IsGMInvisible()); +} + +// Becoming visible again sets the element back to 0, in place +TEST_F(GhostComponentSaveTests, AVisibleCharacterWritesZeroOverASetElement) { + tinyxml2::XMLDocument doc; + ASSERT_EQ(doc.Parse(R"()"), tinyxml2::XML_SUCCESS); + Entity player(83, info); + auto* const ghost = player.AddComponent(-1); + ASSERT_FALSE(ghost->IsGMInvisible()); + ghost->WriteSaveData(doc); + EXPECT_EQ(Print(doc), R"()"); + + Entity nextWorld(84, info); + auto* const loaded = nextWorld.AddComponent(-1); + loaded->LoadFromSaveData(doc); + EXPECT_FALSE(loaded->IsGMInvisible()); +} + +// An element without i, or with an i that is not a boolean, is a visible character and is left as it is +TEST_F(GhostComponentSaveTests, AnUnreadableValueIsVisibleAndKept) { + for (const auto* const xml : { R"()", R"()" }) { + tinyxml2::XMLDocument doc; + ASSERT_EQ(doc.Parse(xml), tinyxml2::XML_SUCCESS); + Entity player(85, info); + auto* const ghost = player.AddComponent(-1); + ghost->LoadFromSaveData(doc); + EXPECT_FALSE(ghost->IsGMInvisible()); + ghost->WriteSaveData(doc); + EXPECT_EQ(Print(doc), xml); + } +} diff --git a/tests/dGameTests/dComponentsTests/LootMetricsTests.cpp b/tests/dGameTests/dComponentsTests/LootMetricsTests.cpp index c552b55ab..a425a7ead 100644 --- a/tests/dGameTests/dComponentsTests/LootMetricsTests.cpp +++ b/tests/dGameTests/dComponentsTests/LootMetricsTests.cpp @@ -217,8 +217,8 @@ TEST_F(LootMetricsTests, QuickbuildTakesItsCostAsTheSource) { constexpr LOT BRICK = 6194; constexpr int32_t PRECONDITION = 90099; // stands in for 99: have 5 of LOT 6194 RegisterLot(BRICK); - CDClientDatabase::ExecuteDML("CREATE TABLE IF NOT EXISTS Preconditions (id INTEGER, type INTEGER, targetLOT TEXT, targetCount INTEGER);"); - CDClientDatabase::ExecuteDML("INSERT INTO Preconditions VALUES (" + std::to_string(PRECONDITION) + ", 2, '6194', 5);"); + CDClientDatabase::ExecuteDML("CREATE TABLE IF NOT EXISTS Preconditions (id INTEGER, type INTEGER, targetLOT TEXT, targetCount INTEGER, validContexts INTEGER);"); + CDClientDatabase::ExecuteDML("INSERT INTO Preconditions VALUES (" + std::to_string(PRECONDITION) + ", 2, '6194', 5, 255);"); inventory->AddItem(BRICK, 7, eLootSourceType::NONE); // What the precondition check looks at besides the inventory entity->AddComponent(-1); diff --git a/tests/dGameTests/dComponentsTests/PropertyEntranceComponentTests.cpp b/tests/dGameTests/dComponentsTests/PropertyEntranceComponentTests.cpp index a92ce5b40..a87f91bd4 100644 --- a/tests/dGameTests/dComponentsTests/PropertyEntranceComponentTests.cpp +++ b/tests/dGameTests/dComponentsTests/PropertyEntranceComponentTests.cpp @@ -13,3 +13,14 @@ TEST(PropertyEntranceComponentTests, WasFriendsFollowsTheSortMethod) { EXPECT_FALSE(PropertyEntranceComponent::IsFriendsSort(SORT_TYPE_REPUTATION)); EXPECT_FALSE(PropertyEntranceComponent::IsFriendsSort(SORT_TYPE_RECENT)); } + +// The friends list shows closed properties too (the client draws a lock on them); selecting one must still go nowhere. +// Access types: 0 private, 1 friends, 2 public. +TEST(PropertyEntranceComponentTests, ClosedPropertiesInTheListCannotBeVisited) { + EXPECT_FALSE(PropertyEntranceComponent::CanVisit(0, false)); + EXPECT_FALSE(PropertyEntranceComponent::CanVisit(0, true)); + EXPECT_FALSE(PropertyEntranceComponent::CanVisit(1, false)); + EXPECT_TRUE(PropertyEntranceComponent::CanVisit(1, true)); + EXPECT_TRUE(PropertyEntranceComponent::CanVisit(2, false)); + EXPECT_TRUE(PropertyEntranceComponent::CanVisit(2, true)); +} diff --git a/tests/dGameTests/dGameMessagesTests/BuildingMessagesTests.cpp b/tests/dGameTests/dGameMessagesTests/BuildingMessagesTests.cpp index 64c52f923..22bb16487 100644 --- a/tests/dGameTests/dGameMessagesTests/BuildingMessagesTests.cpp +++ b/tests/dGameTests/dGameMessagesTests/BuildingMessagesTests.cpp @@ -506,3 +506,11 @@ TEST_F(BuildingMessagesTests, NotifyClientUGCModelReadyWire) { ready.WritePacket(bitStream); EXPECT_PACKET_EQ(FromHex("53 05 00 0c 00 00 00 00 88 77 66 55 44 33 22 11 8d 03 08 07 06 05 04 03 02 01"), FromBitStream(bitStream)); } + +// A live client's BuildExitConfirmation after leaving the property editor: sent to the thinking hat the player wears, +// with the player's id +TEST_F(BuildingMessagesTests, BuildExitConfirmationReadsLiveCapture) { + const auto confirmation = FromLiveClientCapture("53 04 00 05 00 00 00 00 43 b4 a8 91 00 00 00 10 30 04 54 db b6 91 00 00 00 10"); + EXPECT_EQ(confirmation.target, 1152921507050599491LL); + EXPECT_EQ(confirmation.playerID, 1152921507051526996LL); +} diff --git a/tests/dGameTests/dGameMessagesTests/CMakeLists.txt b/tests/dGameTests/dGameMessagesTests/CMakeLists.txt index f71cdb16b..6dab3280a 100644 --- a/tests/dGameTests/dGameMessagesTests/CMakeLists.txt +++ b/tests/dGameTests/dGameMessagesTests/CMakeLists.txt @@ -7,6 +7,7 @@ SET(DGAMEMESSAGES_TESTS "EffectsMessagesTests.cpp" "InventoryMessagesTests.cpp" "MissionMessagesTests.cpp" + "SetFlagServerOnlyTests.cpp" "PetMessagesTests.cpp" "PropertyMessagesTests.cpp" "RacingMessagesTests.cpp" diff --git a/tests/dGameTests/dGameMessagesTests/PropertyMessagesTests.cpp b/tests/dGameTests/dGameMessagesTests/PropertyMessagesTests.cpp index 238c1291e..2011892da 100644 --- a/tests/dGameTests/dGameMessagesTests/PropertyMessagesTests.cpp +++ b/tests/dGameTests/dGameMessagesTests/PropertyMessagesTests.cpp @@ -651,3 +651,25 @@ TEST_F(PropertyMessagesTests, RequeryPropertyModelsHasNoPayload) { GameMessages::RequeryPropertyModels requery; EXPECT_EQ(Payload(requery).bits, 0u); } + +// A live client's PropertyModerationAction, sent to the property plaque when its owner started editing: the character, +// no text and status 0 +TEST_F(PropertyMessagesTests, PropertyModerationActionReadsLiveCapture) { + const auto action = FromLiveClientCapture("53 04 00 05 00 00 00 00 8a 4e 00 00 00 40 00 04 93 03 aa 6d db 48 80 00 00 08 00 00 00 00 40 00 00 00 00"); + EXPECT_EQ(action.target, 288300744895909514LL); + EXPECT_EQ(action.characterID, 1152921507051526996LL); + EXPECT_TRUE(action.info.empty()); + EXPECT_EQ(action.newModerationStatus, 0); + + // Left at their defaults, the character and the status are one bit each + GameMessages::PropertyModerationAction empty; + EXPECT_PACKET_EQ(FromHex("00 00 00 00 00", 34), Payload(empty)); +} + +// RequestLeaveProperty carries nothing (RequestLeaveProperty::Deserialize reads nothing) +TEST_F(PropertyMessagesTests, RequestLeavePropertyHasNoPayload) { + GameMessages::RequestLeaveProperty leave; + EXPECT_EQ(Payload(leave).bits, 0u); + RakNet::BitStream bitStream; + EXPECT_TRUE(leave.Deserialize(bitStream)); +} diff --git a/tests/dGameTests/dGameMessagesTests/SetFlagServerOnlyTests.cpp b/tests/dGameTests/dGameMessagesTests/SetFlagServerOnlyTests.cpp new file mode 100644 index 000000000..210ca5b96 --- /dev/null +++ b/tests/dGameTests/dGameMessagesTests/SetFlagServerOnlyTests.cpp @@ -0,0 +1,74 @@ +// A client SetFlag for a flag marked PlayerFlags.OnlySetByServer is ignored: the client's own flag component refuses +// to set these (LWOFlagComponent::SendMessage), and none of the 205 live client SetFlag messages named one. +#include "GameDependencies.h" + +#include "CDClientDatabase.h" +#include "Character.h" +#include "Entity.h" +#include "MissionMessages.h" +#include "User.h" + +#include +#include + +namespace { + constexpr int32_t SERVER_ONLY_FLAG = 1110; + constexpr int32_t CLIENT_FLAG = 1111; + constexpr int32_t UNLISTED_FLAG = 1112; +} + +class SetFlagServerOnlyTests : public GameDependenciesTest { +protected: + void SetUp() override { + SetUpDependencies(); + CDClientDatabase::Connect(":memory:"); + CDClientDatabase::ExecuteDML("CREATE TABLE PlayerFlags (id INTEGER, SessionOnly INTEGER, OnlySetByServer INTEGER, SessionZoneOnly INTEGER);"); + CDClientDatabase::ExecuteDML("INSERT INTO PlayerFlags VALUES (1110, 0, 1, 0), (1111, 0, 0, 0);"); + user = std::make_unique(UNASSIGNED_SYSTEM_ADDRESS, "tester", "key"); + character = std::make_unique(1, user.get()); + entity = std::make_unique(1, info); + entity->SetCharacter(character.get()); + character->SetEntity(entity.get()); + } + + void TearDown() override { + entity->SetCharacter(nullptr); + entity.reset(); + character.reset(); + user.reset(); + TearDownDependencies(); + } + + void ClientSetsFlag(const int32_t flag, const bool value) { + GameMessages::SetFlag setFlag; + setFlag.iFlagID = flag; + setFlag.bFlag = value; + setFlag.Handle(*entity, UNASSIGNED_SYSTEM_ADDRESS); + } + + std::unique_ptr user; + std::unique_ptr character; + std::unique_ptr entity; +}; + +TEST_F(SetFlagServerOnlyTests, ClientCannotSetAServerOnlyFlag) { + ClientSetsFlag(SERVER_ONLY_FLAG, true); + EXPECT_FALSE(character->GetPlayerFlag(SERVER_ONLY_FLAG)); +} + +// A flag the server set stays set: the client cannot clear it either, and nothing saved is dropped +TEST_F(SetFlagServerOnlyTests, ClientCannotClearAServerOnlyFlag) { + character->SetPlayerFlag(SERVER_ONLY_FLAG, true); + ClientSetsFlag(SERVER_ONLY_FLAG, false); + EXPECT_TRUE(character->GetPlayerFlag(SERVER_ONLY_FLAG)); +} + +// Every other flag is set and cleared as before, with or without a PlayerFlags row +TEST_F(SetFlagServerOnlyTests, OtherFlagsAreStillSetByTheClient) { + for (const auto flag : { CLIENT_FLAG, UNLISTED_FLAG }) { + ClientSetsFlag(flag, true); + EXPECT_TRUE(character->GetPlayerFlag(flag)); + ClientSetsFlag(flag, false); + EXPECT_FALSE(character->GetPlayerFlag(flag)); + } +}