Index: ps/trunk/source/simulation2/components/CCmpObstruction.cpp =================================================================== --- ps/trunk/source/simulation2/components/CCmpObstruction.cpp (revision 22938) +++ ps/trunk/source/simulation2/components/CCmpObstruction.cpp (revision 22939) @@ -1,836 +1,837 @@ -/* Copyright (C) 2018 Wildfire Games. +/* Copyright (C) 2019 Wildfire Games. * This file is part of 0 A.D. * * 0 A.D. is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 2 of the License, or * (at your option) any later version. * * 0 A.D. is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with 0 A.D. If not, see . */ #include "precompiled.h" #include "simulation2/system/Component.h" #include "ICmpObstruction.h" #include "ps/CLogger.h" #include "simulation2/MessageTypes.h" #include "simulation2/components/ICmpObstructionManager.h" #include "simulation2/components/ICmpTerrain.h" #include "simulation2/components/ICmpUnitMotion.h" #include "simulation2/components/ICmpWaterManager.h" #include "simulation2/serialization/SerializeTemplates.h" /** * Obstruction implementation. This keeps the ICmpPathfinder's model of the world updated when the * entities move and die, with shapes derived from ICmpFootprint. */ class CCmpObstruction : public ICmpObstruction { public: static void ClassInit(CComponentManager& componentManager) { componentManager.SubscribeToMessageType(MT_PositionChanged); componentManager.SubscribeToMessageType(MT_Destroy); } DEFAULT_COMPONENT_ALLOCATOR(Obstruction) typedef ICmpObstructionManager::tag_t tag_t; typedef ICmpObstructionManager::flags_t flags_t; // Template state: - enum { - STATIC, - UNIT, - CLUSTER - } m_Type; + EObstructionType m_Type; entity_pos_t m_Size0; // radius or width entity_pos_t m_Size1; // radius or depth flags_t m_TemplateFlags; entity_pos_t m_Clearance; typedef struct { entity_pos_t dx, dz; entity_angle_t da; entity_pos_t size0, size1; flags_t flags; } Shape; std::vector m_Shapes; // Dynamic state: /// Whether the obstruction is actively obstructing or just an inactive placeholder. bool m_Active; /// Whether the entity associated with this obstruction is currently moving. Only applicable for /// UNIT-type obstructions. bool m_Moving; /// Whether an obstruction's control group should be kept consistent and /// used to set control groups for entities that collide with it. bool m_ControlPersist; /** * Primary control group identifier. Indicates to which control group this entity's shape belongs. * Typically used in combination with obstruction test filters to have member shapes ignore each * other during obstruction tests. Defaults to the entity's ID. Must never be set to INVALID_ENTITY. */ entity_id_t m_ControlGroup; /** * Optional secondary control group identifier. Similar to m_ControlGroup; if set to a valid value, * then this field identifies an additional, secondary control group to which this entity's shape * belongs. Set to INVALID_ENTITY to not assign any secondary group. Defaults to INVALID_ENTITY. * * These are only necessary in case it is not sufficient for an entity to belong to only one control * group. Otherwise, they can be ignored. */ entity_id_t m_ControlGroup2; /// Identifier of this entity's obstruction shape, as registered in the obstruction manager. Contains /// structure, but should be treated as opaque here. tag_t m_Tag; std::vector m_ClusterTags; /// Set of flags affecting the behaviour of this entity's obstruction shape. flags_t m_Flags; static std::string GetSchema() { return "" "Causes this entity to obstruct the motion of other units." "" "" "" "" "1.5" "" "" "" "" "1.5" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "1.5" "" "" "" "" "1.5" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" ""; } virtual void Init(const CParamNode& paramNode) { // The minimum obstruction size is the navcell size * sqrt(2) // This is enforced in the schema as a minimum of 1.5 fixed minObstruction = (Pathfinding::NAVCELL_SIZE.Square() * 2).Sqrt(); m_TemplateFlags = 0; if (paramNode.GetChild("BlockMovement").ToBool()) m_TemplateFlags |= ICmpObstructionManager::FLAG_BLOCK_MOVEMENT; if (paramNode.GetChild("BlockPathfinding").ToBool()) m_TemplateFlags |= ICmpObstructionManager::FLAG_BLOCK_PATHFINDING; if (paramNode.GetChild("BlockFoundation").ToBool()) m_TemplateFlags |= ICmpObstructionManager::FLAG_BLOCK_FOUNDATION; if (paramNode.GetChild("BlockConstruction").ToBool()) m_TemplateFlags |= ICmpObstructionManager::FLAG_BLOCK_CONSTRUCTION; if (paramNode.GetChild("DeleteUponConstruction").ToBool()) m_TemplateFlags |= ICmpObstructionManager::FLAG_DELETE_UPON_CONSTRUCTION; m_Flags = m_TemplateFlags; if (paramNode.GetChild("DisableBlockMovement").ToBool()) m_Flags &= (flags_t)(~ICmpObstructionManager::FLAG_BLOCK_MOVEMENT); if (paramNode.GetChild("DisableBlockPathfinding").ToBool()) m_Flags &= (flags_t)(~ICmpObstructionManager::FLAG_BLOCK_PATHFINDING); if (paramNode.GetChild("Unit").IsOk()) { m_Type = UNIT; CmpPtr cmpUnitMotion(GetEntityHandle()); if (cmpUnitMotion) m_Clearance = cmpUnitMotion->GetUnitClearance(); } else if (paramNode.GetChild("Static").IsOk()) { m_Type = STATIC; m_Size0 = paramNode.GetChild("Static").GetChild("@width").ToFixed(); m_Size1 = paramNode.GetChild("Static").GetChild("@depth").ToFixed(); ENSURE(m_Size0 > minObstruction); ENSURE(m_Size1 > minObstruction); } else { m_Type = CLUSTER; CFixedVector2D max = CFixedVector2D(fixed::FromInt(0), fixed::FromInt(0)); CFixedVector2D min = CFixedVector2D(fixed::FromInt(0), fixed::FromInt(0)); const CParamNode::ChildrenMap& clusterMap = paramNode.GetChild("Obstructions").GetChildren(); for(CParamNode::ChildrenMap::const_iterator it = clusterMap.begin(); it != clusterMap.end(); ++it) { Shape b; b.size0 = it->second.GetChild("@width").ToFixed(); b.size1 = it->second.GetChild("@depth").ToFixed(); ENSURE(b.size0 > minObstruction); ENSURE(b.size1 > minObstruction); b.dx = it->second.GetChild("@x").ToFixed(); b.dz = it->second.GetChild("@z").ToFixed(); b.da = entity_angle_t::FromInt(0); b.flags = m_Flags; m_Shapes.push_back(b); max.X = std::max(max.X, b.dx + b.size0/2); max.Y = std::max(max.Y, b.dz + b.size1/2); min.X = std::min(min.X, b.dx - b.size0/2); min.Y = std::min(min.Y, b.dz - b.size1/2); } m_Size0 = fixed::FromInt(2).Multiply(std::max(max.X, -min.X)); m_Size1 = fixed::FromInt(2).Multiply(std::max(max.Y, -min.Y)); } m_Active = paramNode.GetChild("Active").ToBool(); m_ControlPersist = paramNode.GetChild("ControlPersist").IsOk(); m_Tag = tag_t(); if (m_Type == CLUSTER) m_ClusterTags.clear(); m_Moving = false; m_ControlGroup = GetEntityId(); m_ControlGroup2 = INVALID_ENTITY; } virtual void Deinit() { } struct SerializeTag { template void operator()(S& serialize, const char* UNUSED(name), tag_t& value) { serialize.NumberU32_Unbounded("tag", value.n); } }; template void SerializeCommon(S& serialize) { serialize.Bool("active", m_Active); serialize.Bool("moving", m_Moving); serialize.NumberU32_Unbounded("control group", m_ControlGroup); serialize.NumberU32_Unbounded("control group 2", m_ControlGroup2); serialize.NumberU32_Unbounded("tag", m_Tag.n); serialize.NumberU8_Unbounded("flags", m_Flags); if (m_Type == CLUSTER) SerializeVector()(serialize, "cluster tags", m_ClusterTags); if (m_Type == UNIT) serialize.NumberFixed_Unbounded("clearance", m_Clearance); } virtual void Serialize(ISerializer& serialize) { SerializeCommon(serialize); } virtual void Deserialize(const CParamNode& paramNode, IDeserializer& deserialize) { Init(paramNode); SerializeCommon(deserialize); } virtual void HandleMessage(const CMessage& msg, bool UNUSED(global)) { switch (msg.GetType()) { case MT_PositionChanged: { if (!m_Active) break; const CMessagePositionChanged& data = static_cast (msg); if (!data.inWorld && !m_Tag.valid()) break; // nothing needs to change CmpPtr cmpObstructionManager(GetSystemEntity()); if (!cmpObstructionManager) break; // error if (data.inWorld && m_Tag.valid()) { cmpObstructionManager->MoveShape(m_Tag, data.x, data.z, data.a); if (m_Type == CLUSTER) { for (size_t i = 0; i < m_Shapes.size(); ++i) { Shape& b = m_Shapes[i]; fixed s, c; sincos_approx(data.a, s, c); cmpObstructionManager->MoveShape(m_ClusterTags[i], data.x + b.dx.Multiply(c) + b.dz.Multiply(s), data.z + b.dz.Multiply(c) - b.dx.Multiply(s), data.a + b.da); } } } else if (data.inWorld && !m_Tag.valid()) { // Need to create a new pathfinder shape: if (m_Type == STATIC) m_Tag = cmpObstructionManager->AddStaticShape(GetEntityId(), data.x, data.z, data.a, m_Size0, m_Size1, m_Flags, m_ControlGroup, m_ControlGroup2); else if (m_Type == UNIT) m_Tag = cmpObstructionManager->AddUnitShape(GetEntityId(), data.x, data.z, m_Clearance, (flags_t)(m_Flags | (m_Moving ? ICmpObstructionManager::FLAG_MOVING : 0)), m_ControlGroup); else AddClusterShapes(data.x, data.x, data.a); } else if (!data.inWorld && m_Tag.valid()) { cmpObstructionManager->RemoveShape(m_Tag); m_Tag = tag_t(); if(m_Type == CLUSTER) RemoveClusterShapes(); } break; } case MT_Destroy: { if (m_Tag.valid()) { CmpPtr cmpObstructionManager(GetSystemEntity()); if (!cmpObstructionManager) break; // error // Deactivate the obstruction in case PositionChanged messages are sent after this. m_Active = false; cmpObstructionManager->RemoveShape(m_Tag); m_Tag = tag_t(); if(m_Type == CLUSTER) RemoveClusterShapes(); } break; } } } virtual void SetActive(bool active) { if (active && !m_Active) { m_Active = true; // Construct the obstruction shape CmpPtr cmpObstructionManager(GetSystemEntity()); if (!cmpObstructionManager) return; // error CmpPtr cmpPosition(GetEntityHandle()); if (!cmpPosition) return; // error if (!cmpPosition->IsInWorld()) return; // don't need an obstruction // TODO: code duplication from message handlers CFixedVector2D pos = cmpPosition->GetPosition2D(); if (m_Type == STATIC) m_Tag = cmpObstructionManager->AddStaticShape(GetEntityId(), pos.X, pos.Y, cmpPosition->GetRotation().Y, m_Size0, m_Size1, m_Flags, m_ControlGroup, m_ControlGroup2); else if (m_Type == UNIT) m_Tag = cmpObstructionManager->AddUnitShape(GetEntityId(), pos.X, pos.Y, m_Clearance, (flags_t)(m_Flags | (m_Moving ? ICmpObstructionManager::FLAG_MOVING : 0)), m_ControlGroup); else AddClusterShapes(pos.X, pos.Y, cmpPosition->GetRotation().Y); } else if (!active && m_Active) { m_Active = false; // Delete the obstruction shape // TODO: code duplication from message handlers if (m_Tag.valid()) { CmpPtr cmpObstructionManager(GetSystemEntity()); if (!cmpObstructionManager) return; // error cmpObstructionManager->RemoveShape(m_Tag); m_Tag = tag_t(); if (m_Type == CLUSTER) RemoveClusterShapes(); } } // else we didn't change the active status } virtual void SetDisableBlockMovementPathfinding(bool movementDisabled, bool pathfindingDisabled, int32_t shape) { flags_t *flags = NULL; if (shape == -1) flags = &m_Flags; else if (m_Type == CLUSTER && shape < (int32_t)m_Shapes.size()) flags = &m_Shapes[shape].flags; else return; // error // Remove the blocking / pathfinding flags or // Add the blocking / pathfinding flags if the template had enabled them if (movementDisabled) *flags &= (flags_t)(~ICmpObstructionManager::FLAG_BLOCK_MOVEMENT); else *flags |= (flags_t)(m_TemplateFlags & ICmpObstructionManager::FLAG_BLOCK_MOVEMENT); if (pathfindingDisabled) *flags &= (flags_t)(~ICmpObstructionManager::FLAG_BLOCK_PATHFINDING); else *flags |= (flags_t)(m_TemplateFlags & ICmpObstructionManager::FLAG_BLOCK_PATHFINDING); // Reset the shape with the new flags (kind of inefficiently - we // should have a ICmpObstructionManager::SetFlags function or something) if (m_Active) { SetActive(false); SetActive(true); } } virtual bool GetBlockMovementFlag() const { return (m_TemplateFlags & ICmpObstructionManager::FLAG_BLOCK_MOVEMENT) != 0; } + virtual EObstructionType GetObstructionType() const + { + return m_Type; + } + virtual ICmpObstructionManager::tag_t GetObstruction() const { return m_Tag; } virtual bool GetPreviousObstructionSquare(ICmpObstructionManager::ObstructionSquare& out) const { return GetObstructionSquare(out, true); } virtual bool GetObstructionSquare(ICmpObstructionManager::ObstructionSquare& out) const { return GetObstructionSquare(out, false); } virtual bool GetObstructionSquare(ICmpObstructionManager::ObstructionSquare& out, bool previousPosition) const { CmpPtr cmpPosition(GetEntityHandle()); if (!cmpPosition) return false; // error CmpPtr cmpObstructionManager(GetSystemEntity()); if (!cmpObstructionManager) return false; // error if (!cmpPosition->IsInWorld()) return false; // no obstruction square CFixedVector2D pos; if (previousPosition) pos = cmpPosition->GetPreviousPosition2D(); else pos = cmpPosition->GetPosition2D(); if (m_Type == UNIT) out = cmpObstructionManager->GetUnitShapeObstruction(pos.X, pos.Y, m_Clearance); else out = cmpObstructionManager->GetStaticShapeObstruction(pos.X, pos.Y, cmpPosition->GetRotation().Y, m_Size0, m_Size1); return true; } virtual entity_pos_t GetUnitRadius() const { if (m_Type == UNIT) return m_Clearance; else return entity_pos_t::Zero(); } virtual entity_pos_t GetSize() const { if (m_Type == UNIT) return m_Clearance; else return CFixedVector2D(m_Size0 / 2, m_Size1 / 2).Length(); } virtual void SetUnitClearance(const entity_pos_t& clearance) { if (m_Type == UNIT) m_Clearance = clearance; } virtual bool IsControlPersistent() const { return m_ControlPersist; } virtual bool CheckShorePlacement() const { ICmpObstructionManager::ObstructionSquare s; if (!GetObstructionSquare(s)) return false; CFixedVector2D front = CFixedVector2D(s.x, s.z) + s.v.Multiply(s.hh); CFixedVector2D back = CFixedVector2D(s.x, s.z) - s.v.Multiply(s.hh); CmpPtr cmpTerrain(GetSystemEntity()); CmpPtr cmpWaterManager(GetSystemEntity()); if (!cmpTerrain || !cmpWaterManager) return false; // Keep these constants in agreement with the pathfinder. return cmpWaterManager->GetWaterLevel(front.X, front.Y) - cmpTerrain->GetGroundLevel(front.X, front.Y) > fixed::FromInt(1) && cmpWaterManager->GetWaterLevel( back.X, back.Y) - cmpTerrain->GetGroundLevel( back.X, back.Y) < fixed::FromInt(2); } virtual EFoundationCheck CheckFoundation(const std::string& className) const { return CheckFoundation(className, false); } virtual EFoundationCheck CheckFoundation(const std::string& className, bool onlyCenterPoint) const { CmpPtr cmpPosition(GetEntityHandle()); if (!cmpPosition) return FOUNDATION_CHECK_FAIL_ERROR; // error if (!cmpPosition->IsInWorld()) return FOUNDATION_CHECK_FAIL_NO_OBSTRUCTION; // no obstruction CFixedVector2D pos = cmpPosition->GetPosition2D(); CmpPtr cmpPathfinder(GetSystemEntity()); if (!cmpPathfinder) return FOUNDATION_CHECK_FAIL_ERROR; // error // required precondition to use SkipControlGroupsRequireFlagObstructionFilter if (m_ControlGroup == INVALID_ENTITY) { LOGERROR("[CmpObstruction] Cannot test for foundation obstructions; primary control group must be valid"); return FOUNDATION_CHECK_FAIL_ERROR; } // Get passability class pass_class_t passClass = cmpPathfinder->GetPassabilityClass(className); // Ignore collisions within the same control group, or with other non-foundation-blocking shapes. // Note that, since the control group for each entity defaults to the entity's ID, this is typically // equivalent to only ignoring the entity's own shape and other non-foundation-blocking shapes. SkipControlGroupsRequireFlagObstructionFilter filter(m_ControlGroup, m_ControlGroup2, ICmpObstructionManager::FLAG_BLOCK_FOUNDATION); if (m_Type == UNIT) return cmpPathfinder->CheckUnitPlacement(filter, pos.X, pos.Y, m_Clearance, passClass, onlyCenterPoint); else return cmpPathfinder->CheckBuildingPlacement(filter, pos.X, pos.Y, cmpPosition->GetRotation().Y, m_Size0, m_Size1, GetEntityId(), passClass, onlyCenterPoint); } virtual bool CheckDuplicateFoundation() const { CmpPtr cmpPosition(GetEntityHandle()); if (!cmpPosition) return false; // error if (!cmpPosition->IsInWorld()) return false; // no obstruction CFixedVector2D pos = cmpPosition->GetPosition2D(); CmpPtr cmpObstructionManager(GetSystemEntity()); if (!cmpObstructionManager) return false; // error // required precondition to use SkipControlGroupsRequireFlagObstructionFilter if (m_ControlGroup == INVALID_ENTITY) { LOGERROR("[CmpObstruction] Cannot test for foundation obstructions; primary control group must be valid"); return false; } // Ignore collisions with entities unless they block foundations and match both control groups. SkipTagRequireControlGroupsAndFlagObstructionFilter filter(m_Tag, m_ControlGroup, m_ControlGroup2, ICmpObstructionManager::FLAG_BLOCK_FOUNDATION); if (m_Type == UNIT) return !cmpObstructionManager->TestUnitShape(filter, pos.X, pos.Y, m_Clearance, NULL); else return !cmpObstructionManager->TestStaticShape(filter, pos.X, pos.Y, cmpPosition->GetRotation().Y, m_Size0, m_Size1, NULL ); } virtual std::vector GetEntitiesByFlags(flags_t flags) const { std::vector ret; CmpPtr cmpObstructionManager(GetSystemEntity()); if (!cmpObstructionManager) return ret; // error // Ignore collisions within the same control group, or with other shapes that don't match the filter. // Note that, since the control group for each entity defaults to the entity's ID, this is typically // equivalent to only ignoring the entity's own shape and other shapes that don't match the filter. SkipControlGroupsRequireFlagObstructionFilter filter(false, m_ControlGroup, m_ControlGroup2, flags); ICmpObstructionManager::ObstructionSquare square; if (!GetObstructionSquare(square)) return ret; // error cmpObstructionManager->GetUnitsOnObstruction(square, ret, filter, false); cmpObstructionManager->GetStaticObstructionsOnObstruction(square, ret, filter); return ret; } virtual std::vector GetEntitiesBlockingConstruction() const { return GetEntitiesByFlags(ICmpObstructionManager::FLAG_BLOCK_CONSTRUCTION); } virtual std::vector GetEntitiesDeletedUponConstruction() const { return GetEntitiesByFlags(ICmpObstructionManager::FLAG_DELETE_UPON_CONSTRUCTION); } virtual void SetMovingFlag(bool enabled) { m_Moving = enabled; if (m_Tag.valid() && m_Type == UNIT) { CmpPtr cmpObstructionManager(GetSystemEntity()); if (cmpObstructionManager) cmpObstructionManager->SetUnitMovingFlag(m_Tag, m_Moving); } } virtual void SetControlGroup(entity_id_t group) { m_ControlGroup = group; UpdateControlGroups(); } virtual void SetControlGroup2(entity_id_t group2) { m_ControlGroup2 = group2; UpdateControlGroups(); } virtual entity_id_t GetControlGroup() const { return m_ControlGroup; } virtual entity_id_t GetControlGroup2() const { return m_ControlGroup2; } void UpdateControlGroups() { if (m_Tag.valid()) { CmpPtr cmpObstructionManager(GetSystemEntity()); if (cmpObstructionManager) { if (m_Type == UNIT) { cmpObstructionManager->SetUnitControlGroup(m_Tag, m_ControlGroup); } else if (m_Type == STATIC) { cmpObstructionManager->SetStaticControlGroup(m_Tag, m_ControlGroup, m_ControlGroup2); } else { cmpObstructionManager->SetStaticControlGroup(m_Tag, m_ControlGroup, m_ControlGroup2); for (size_t i = 0; i < m_ClusterTags.size(); ++i) { cmpObstructionManager->SetStaticControlGroup(m_ClusterTags[i], m_ControlGroup, m_ControlGroup2); } } } } } void ResolveFoundationCollisions() const { if (m_Type == UNIT) return; CmpPtr cmpObstructionManager(GetSystemEntity()); if (!cmpObstructionManager) return; CmpPtr cmpPosition(GetEntityHandle()); if (!cmpPosition) return; // error if (!cmpPosition->IsInWorld()) return; // no obstruction CFixedVector2D pos = cmpPosition->GetPosition2D(); // Ignore collisions within the same control group, or with other non-foundation-blocking shapes. // Note that, since the control group for each entity defaults to the entity's ID, this is typically // equivalent to only ignoring the entity's own shape and other non-foundation-blocking shapes. SkipControlGroupsRequireFlagObstructionFilter filter(m_ControlGroup, m_ControlGroup2, ICmpObstructionManager::FLAG_BLOCK_FOUNDATION); std::vector collisions; if (cmpObstructionManager->TestStaticShape(filter, pos.X, pos.Y, cmpPosition->GetRotation().Y, m_Size0, m_Size1, &collisions)) { std::vector persistentEnts, normalEnts; if (m_ControlPersist) persistentEnts.push_back(m_ControlGroup); else normalEnts.push_back(GetEntityId()); for (std::vector::iterator it = collisions.begin(); it != collisions.end(); ++it) { entity_id_t ent = *it; if (ent == INVALID_ENTITY) continue; CmpPtr cmpObstruction(GetSimContext(), ent); if (!cmpObstruction->IsControlPersistent()) normalEnts.push_back(ent); else persistentEnts.push_back(cmpObstruction->GetControlGroup()); } // The collision can't be resolved without usable persistent control groups. if (persistentEnts.empty()) return; // Attempt to replace colliding entities' control groups with a persistent one. for (std::vector::iterator it = normalEnts.begin(); it != normalEnts.end(); ++it) { entity_id_t ent = *it; CmpPtr cmpObstruction(GetSimContext(), ent); for (std::vector::iterator it = persistentEnts.begin(); it != persistentEnts.end(); ++it) { entity_id_t persistent = *it; entity_id_t group = cmpObstruction->GetControlGroup(); // Only clobber 'default' control groups. if (group == ent) cmpObstruction->SetControlGroup(persistent); else if (cmpObstruction->GetControlGroup2() == INVALID_ENTITY && group != persistent) cmpObstruction->SetControlGroup2(persistent); } } } } protected: inline void AddClusterShapes(entity_pos_t x, entity_pos_t z, entity_angle_t a) { CmpPtr cmpObstructionManager(GetSystemEntity()); if (!cmpObstructionManager) return; // error flags_t flags = m_Flags; // Disable block movement and block pathfinding for the obstruction shape flags &= (flags_t)(~ICmpObstructionManager::FLAG_BLOCK_MOVEMENT); flags &= (flags_t)(~ICmpObstructionManager::FLAG_BLOCK_PATHFINDING); m_Tag = cmpObstructionManager->AddStaticShape(GetEntityId(), x, z, a, m_Size0, m_Size1, flags, m_ControlGroup, m_ControlGroup2); fixed s, c; sincos_approx(a, s, c); for (size_t i = 0; i < m_Shapes.size(); ++i) { Shape& b = m_Shapes[i]; tag_t tag = cmpObstructionManager->AddStaticShape(GetEntityId(), x + b.dx.Multiply(c) + b.dz.Multiply(s), z + b.dz.Multiply(c) - b.dx.Multiply(s), a + b.da, b.size0, b.size1, b.flags, m_ControlGroup, m_ControlGroup2); m_ClusterTags.push_back(tag); } } inline void RemoveClusterShapes() { CmpPtr cmpObstructionManager(GetSystemEntity()); if (!cmpObstructionManager) return; // error for (size_t i = 0; i < m_ClusterTags.size(); ++i) { if (m_ClusterTags[i].valid()) { cmpObstructionManager->RemoveShape(m_ClusterTags[i]); } } m_ClusterTags.clear(); } }; REGISTER_COMPONENT_TYPE(Obstruction) Index: ps/trunk/source/simulation2/components/ICmpObstruction.h =================================================================== --- ps/trunk/source/simulation2/components/ICmpObstruction.h (revision 22938) +++ ps/trunk/source/simulation2/components/ICmpObstruction.h (revision 22939) @@ -1,139 +1,147 @@ -/* Copyright (C) 2018 Wildfire Games. +/* Copyright (C) 2019 Wildfire Games. * This file is part of 0 A.D. * * 0 A.D. is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 2 of the License, or * (at your option) any later version. * * 0 A.D. is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with 0 A.D. If not, see . */ #ifndef INCLUDED_ICMPOBSTRUCTION #define INCLUDED_ICMPOBSTRUCTION #include "simulation2/system/Interface.h" #include "simulation2/components/ICmpObstructionManager.h" /** * Flags an entity as obstructing movement for other units, * and handles the processing of collision queries. */ class ICmpObstruction : public IComponent { public: enum EFoundationCheck { FOUNDATION_CHECK_SUCCESS, FOUNDATION_CHECK_FAIL_ERROR, FOUNDATION_CHECK_FAIL_NO_OBSTRUCTION, FOUNDATION_CHECK_FAIL_OBSTRUCTS_FOUNDATION, FOUNDATION_CHECK_FAIL_TERRAIN_CLASS }; + enum EObstructionType { + STATIC, + UNIT, + CLUSTER + }; + virtual ICmpObstructionManager::tag_t GetObstruction() const = 0; /** * Gets the square corresponding to this obstruction shape. * @return true and updates @p out on success; * false on failure (e.g. object not in the world). */ virtual bool GetObstructionSquare(ICmpObstructionManager::ObstructionSquare& out) const = 0; /** * Same as the method above, but returns an obstruction shape for the previous turn */ virtual bool GetPreviousObstructionSquare(ICmpObstructionManager::ObstructionSquare& out) const = 0; virtual entity_pos_t GetSize() const = 0; virtual entity_pos_t GetUnitRadius() const = 0; + virtual EObstructionType GetObstructionType() const = 0; + virtual void SetUnitClearance(const entity_pos_t& clearance) = 0; virtual bool IsControlPersistent() const = 0; /** * Test whether the front of the obstruction square is in the water and the back is on the shore. */ virtual bool CheckShorePlacement() const = 0; /** * Test whether this entity is colliding with any obstruction that are set to * block the creation of foundations. * @param ignoredEntities List of entities to ignore during the test. * @return FOUNDATION_CHECK_SUCCESS if check passes, else an EFoundationCheck * value describing the type of failure. */ virtual EFoundationCheck CheckFoundation(const std::string& className) const = 0; virtual EFoundationCheck CheckFoundation(const std::string& className, bool onlyCenterPoint) const = 0; /** * CheckFoundation wrapper for script calls, to return friendly strings instead of an EFoundationCheck. * @return "success" if check passes, else a string describing the type of failure. */ virtual std::string CheckFoundation_wrapper(const std::string& className, bool onlyCenterPoint) const; /** * Test whether this entity is colliding with any obstructions that share its * control groups and block the creation of foundations. * @return true if foundation is valid (not obstructed) */ virtual bool CheckDuplicateFoundation() const = 0; /** * Returns a list of entities that have an obstruction matching the given flag and intersect the current obstruction. * @return vector of blocking entities */ virtual std::vector GetEntitiesByFlags(ICmpObstructionManager::flags_t flags) const = 0; /** * Returns a list of entities that are blocking construction of a foundation. * @return vector of blocking entities */ virtual std::vector GetEntitiesBlockingConstruction() const = 0; /** * Returns a list of entities that shall be deleted when a construction on this obstruction starts, * for example sheep carcasses. */ virtual std::vector GetEntitiesDeletedUponConstruction() const = 0; /** * Detects collisions between foundation-blocking entities and * tries to fix them by setting control groups, if appropriate. */ virtual void ResolveFoundationCollisions() const = 0; virtual void SetActive(bool active) = 0; virtual void SetMovingFlag(bool enabled) = 0; virtual void SetDisableBlockMovementPathfinding(bool movementDisabled, bool pathfindingDisabled, int32_t shape) = 0; virtual bool GetBlockMovementFlag() const = 0; /** * Change the control group that the entity belongs to. * Control groups are used to let units ignore collisions with other units from * the same group. Default is the entity's own ID. */ virtual void SetControlGroup(entity_id_t group) = 0; /// See SetControlGroup. virtual entity_id_t GetControlGroup() const = 0; virtual void SetControlGroup2(entity_id_t group2) = 0; virtual entity_id_t GetControlGroup2() const = 0; DECLARE_INTERFACE_TYPE(Obstruction) }; #endif // INCLUDED_ICMPOBSTRUCTION Index: ps/trunk/source/simulation2/components/tests/test_ObstructionManager.h =================================================================== --- ps/trunk/source/simulation2/components/tests/test_ObstructionManager.h (revision 22938) +++ ps/trunk/source/simulation2/components/tests/test_ObstructionManager.h (revision 22939) @@ -1,591 +1,592 @@ /* Copyright (C) 2019 Wildfire Games. * This file is part of 0 A.D. * * 0 A.D. is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 2 of the License, or * (at your option) any later version. * * 0 A.D. is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with 0 A.D. If not, see . */ #include "simulation2/system/ComponentTest.h" #include "simulation2/components/ICmpObstructionManager.h" #include "simulation2/components/ICmpObstruction.h" class MockObstruction : public ICmpObstruction { public: DEFAULT_MOCK_COMPONENT() ICmpObstructionManager::ObstructionSquare obstruction; virtual ICmpObstructionManager::tag_t GetObstruction() const { return ICmpObstructionManager::tag_t(); } virtual bool GetObstructionSquare(ICmpObstructionManager::ObstructionSquare& out) const { out = obstruction; return true; } virtual bool GetPreviousObstructionSquare(ICmpObstructionManager::ObstructionSquare& UNUSED(out)) const { return true; } virtual entity_pos_t GetSize() const { return entity_pos_t::Zero(); } virtual entity_pos_t GetUnitRadius() const { return entity_pos_t::Zero(); } + virtual EObstructionType GetObstructionType() const { return ICmpObstruction::STATIC; } virtual void SetUnitClearance(const entity_pos_t& UNUSED(clearance)) { } virtual bool IsControlPersistent() const { return true; } virtual bool CheckShorePlacement() const { return true; } virtual EFoundationCheck CheckFoundation(const std::string& UNUSED(className)) const { return EFoundationCheck(); } virtual EFoundationCheck CheckFoundation(const std::string& UNUSED(className), bool UNUSED(onlyCenterPoint)) const { return EFoundationCheck(); } virtual std::string CheckFoundation_wrapper(const std::string& UNUSED(className), bool UNUSED(onlyCenterPoint)) const { return std::string(); } virtual bool CheckDuplicateFoundation() const { return true; } virtual std::vector GetEntitiesByFlags(ICmpObstructionManager::flags_t UNUSED(flags)) const { return std::vector(); } virtual std::vector GetEntitiesBlockingConstruction() const { return std::vector(); } virtual std::vector GetEntitiesDeletedUponConstruction() const { return std::vector(); } virtual void ResolveFoundationCollisions() const { } virtual void SetActive(bool UNUSED(active)) { } virtual void SetMovingFlag(bool UNUSED(enabled)) { } virtual void SetDisableBlockMovementPathfinding(bool UNUSED(movementDisabled), bool UNUSED(pathfindingDisabled), int32_t UNUSED(shape)) { } virtual bool GetBlockMovementFlag() const { return true; } virtual void SetControlGroup(entity_id_t UNUSED(group)) { } virtual entity_id_t GetControlGroup() const { return INVALID_ENTITY; } virtual void SetControlGroup2(entity_id_t UNUSED(group2)) { } virtual entity_id_t GetControlGroup2() const { return INVALID_ENTITY; } }; class TestCmpObstructionManager : public CxxTest::TestSuite { typedef ICmpObstructionManager::tag_t tag_t; typedef ICmpObstructionManager::ObstructionSquare ObstructionSquare; // some variables for setting up a scene with 3 shapes entity_id_t ent1, ent2, ent3; // entity IDs entity_angle_t ent1a; // angles entity_pos_t ent1x, ent1z, ent1w, ent1h, // positions/dimensions ent2x, ent2z, ent2c, ent3x, ent3z, ent3c; entity_id_t ent1g1, ent1g2, ent2g, ent3g; // control groups tag_t shape1, shape2, shape3; ICmpObstructionManager* cmp; ComponentTestHelper* testHelper; public: void setUp() { CXeromyces::Startup(); CxxTest::setAbortTestOnFail(true); // set up a simple scene with some predefined obstruction shapes // (we can't position shapes on the origin because the world bounds must range // from 0 to X, so instead we'll offset things by, say, 10). ent1 = 1; ent1a = fixed::Zero(); ent1w = fixed::FromFloat(4); ent1h = fixed::FromFloat(2); ent1x = fixed::FromInt(10); ent1z = fixed::FromInt(10); ent1g1 = ent1; ent1g2 = INVALID_ENTITY; ent2 = 2; ent2c = fixed::FromFloat(1); ent2x = ent1x; ent2z = ent1z; ent2g = ent1g1; ent3 = 3; ent3c = fixed::FromFloat(3); ent3x = ent2x; ent3z = ent2z + ent2c + ent3c; // ensure it just touches the border of ent2 ent3g = ent3; testHelper = new ComponentTestHelper(g_ScriptRuntime); cmp = testHelper->Add(CID_ObstructionManager, "", SYSTEM_ENTITY); cmp->SetBounds(fixed::FromInt(0), fixed::FromInt(0), fixed::FromInt(1000), fixed::FromInt(1000)); shape1 = cmp->AddStaticShape(ent1, ent1x, ent1z, ent1a, ent1w, ent1h, ICmpObstructionManager::FLAG_BLOCK_CONSTRUCTION | ICmpObstructionManager::FLAG_BLOCK_MOVEMENT | ICmpObstructionManager::FLAG_MOVING, ent1g1, ent1g2); shape2 = cmp->AddUnitShape(ent2, ent2x, ent2z, ent2c, ICmpObstructionManager::FLAG_BLOCK_CONSTRUCTION | ICmpObstructionManager::FLAG_BLOCK_FOUNDATION, ent2g); shape3 = cmp->AddUnitShape(ent3, ent3x, ent3z, ent3c, ICmpObstructionManager::FLAG_BLOCK_MOVEMENT | ICmpObstructionManager::FLAG_BLOCK_FOUNDATION, ent3g); } void tearDown() { delete testHelper; cmp = NULL; // not our responsibility to deallocate CXeromyces::Terminate(); } /** * Verifies the collision testing procedure. Collision-tests some simple shapes against the shapes registered in * the scene, and verifies the result of the test against the expected value. */ void test_simple_collisions() { std::vector out; NullObstructionFilter nullFilter; // Collision-test a simple shape nested inside shape3 against all shapes in the scene. Since the tested shape // overlaps only with shape 3, we should find only shape 3 in the result. cmp->TestUnitShape(nullFilter, ent3x, ent3z, fixed::FromInt(1), &out); TS_ASSERT_EQUALS(1U, out.size()); TS_ASSERT_EQUALS(ent3, out[0]); out.clear(); cmp->TestStaticShape(nullFilter, ent3x, ent3z, fixed::Zero(), fixed::FromInt(1), fixed::FromInt(1), &out); TS_ASSERT_EQUALS(1U, out.size()); TS_ASSERT_EQUALS(ent3, out[0]); out.clear(); // Similarly, collision-test a simple shape nested inside both shape1 and shape2. Since the tested shape overlaps // only with shapes 1 and 2, those are the only ones we should find in the result. cmp->TestUnitShape(nullFilter, ent2x, ent2z, ent2c/2, &out); TS_ASSERT_EQUALS(2U, out.size()); TS_ASSERT_VECTOR_CONTAINS(out, ent1); TS_ASSERT_VECTOR_CONTAINS(out, ent2); out.clear(); cmp->TestStaticShape(nullFilter, ent2x, ent2z, fixed::Zero(), ent2c, ent2c, &out); TS_ASSERT_EQUALS(2U, out.size()); TS_ASSERT_VECTOR_CONTAINS(out, ent1); TS_ASSERT_VECTOR_CONTAINS(out, ent2); out.clear(); } /** * Verifies the behaviour of the null obstruction filter. Tests with this filter will be performed against all * registered shapes. */ void test_filter_null() { std::vector out; // Collision test a scene-covering shape against all shapes in the scene. We should find all registered shapes // in the result. NullObstructionFilter nullFilter; cmp->TestUnitShape(nullFilter, ent1x, ent1z, fixed::FromInt(10), &out); TS_ASSERT_EQUALS(3U, out.size()); TS_ASSERT_VECTOR_CONTAINS(out, ent1); TS_ASSERT_VECTOR_CONTAINS(out, ent2); TS_ASSERT_VECTOR_CONTAINS(out, ent3); out.clear(); cmp->TestStaticShape(nullFilter, ent1x, ent1z, fixed::Zero(), fixed::FromInt(10), fixed::FromInt(10), &out); TS_ASSERT_EQUALS(3U, out.size()); TS_ASSERT_VECTOR_CONTAINS(out, ent1); TS_ASSERT_VECTOR_CONTAINS(out, ent2); TS_ASSERT_VECTOR_CONTAINS(out, ent3); out.clear(); } /** * Verifies the behaviour of the StationaryOnlyObstructionFilter. Tests with this filter will be performed only * against non-moving (stationary) shapes. */ void test_filter_stationary_only() { std::vector out; // Collision test a scene-covering shape against all shapes in the scene, but skipping shapes that are moving, // i.e. shapes that have the MOVING flag. Since only shape 1 is flagged as moving, we should find // shapes 2 and 3 in each case. StationaryOnlyObstructionFilter ignoreMoving; cmp->TestUnitShape(ignoreMoving, ent1x, ent1z, fixed::FromInt(10), &out); TS_ASSERT_EQUALS(2U, out.size()); TS_ASSERT_VECTOR_CONTAINS(out, ent2); TS_ASSERT_VECTOR_CONTAINS(out, ent3); out.clear(); cmp->TestStaticShape(ignoreMoving, ent1x, ent1z, fixed::Zero(), fixed::FromInt(10), fixed::FromInt(10), &out); TS_ASSERT_EQUALS(2U, out.size()); TS_ASSERT_VECTOR_CONTAINS(out, ent2); TS_ASSERT_VECTOR_CONTAINS(out, ent3); out.clear(); } /** * Verifies the behaviour of the SkipTagObstructionFilter. Tests with this filter will be performed against * all registered shapes that do not have the specified tag set. */ void test_filter_skip_tag() { std::vector out; // Collision-test shape 2's obstruction shape against all shapes in the scene, but skipping tests against // shape 2. Since shape 2 overlaps only with shape 1, we should find only shape 1's entity ID in the result. SkipTagObstructionFilter ignoreShape2(shape2); cmp->TestUnitShape(ignoreShape2, ent2x, ent2z, ent2c/2, &out); TS_ASSERT_EQUALS(1U, out.size()); TS_ASSERT_EQUALS(ent1, out[0]); out.clear(); cmp->TestStaticShape(ignoreShape2, ent2x, ent2z, fixed::Zero(), ent2c, ent2c, &out); TS_ASSERT_EQUALS(1U, out.size()); TS_ASSERT_EQUALS(ent1, out[0]); out.clear(); } /** * Verifies the behaviour of the SkipTagFlagsObstructionFilter. Tests with this filter will be performed against * all registered shapes that do not have the specified tag set, and that have at least one of required flags set. */ void test_filter_skip_tag_require_flag() { std::vector out; // Collision-test a scene-covering shape against all shapes in the scene, but skipping tests against shape 1 // and requiring the BLOCK_MOVEMENT flag. Since shape 1 is being ignored and shape 2 does not have the required // flag, we should find only shape 3 in the results. SkipTagRequireFlagsObstructionFilter skipShape1RequireBlockMovement(shape1, ICmpObstructionManager::FLAG_BLOCK_MOVEMENT); cmp->TestUnitShape(skipShape1RequireBlockMovement, ent1x, ent1z, fixed::FromInt(10), &out); TS_ASSERT_EQUALS(1U, out.size()); TS_ASSERT_EQUALS(ent3, out[0]); out.clear(); cmp->TestStaticShape(skipShape1RequireBlockMovement, ent1x, ent1z, fixed::Zero(), fixed::FromInt(10), fixed::FromInt(10), &out); TS_ASSERT_EQUALS(1U, out.size()); TS_ASSERT_EQUALS(ent3, out[0]); out.clear(); // If we now do the same test, but require at least one of the entire set of available filters, we should find // all shapes that are not shape 1 and that have at least one flag set. Since all shapes in our testing scene // have at least one flag set, we should find shape 2 and shape 3 in the results. SkipTagRequireFlagsObstructionFilter skipShape1RequireAnyFlag(shape1, (ICmpObstructionManager::flags_t) -1); cmp->TestUnitShape(skipShape1RequireAnyFlag, ent1x, ent1z, fixed::FromInt(10), &out); TS_ASSERT_EQUALS(2U, out.size()); TS_ASSERT_VECTOR_CONTAINS(out, ent2); TS_ASSERT_VECTOR_CONTAINS(out, ent3); out.clear(); cmp->TestStaticShape(skipShape1RequireAnyFlag, ent1x, ent1z, fixed::Zero(), fixed::FromInt(10), fixed::FromInt(10), &out); TS_ASSERT_EQUALS(2U, out.size()); TS_ASSERT_VECTOR_CONTAINS(out, ent2); TS_ASSERT_VECTOR_CONTAINS(out, ent3); out.clear(); // And if we now do the same test yet again, but specify an empty set of flags, then it becomes impossible for // any shape to have at least one of the required flags, and we should hence find no shapes in the result. SkipTagRequireFlagsObstructionFilter skipShape1RejectAll(shape1, 0U); cmp->TestUnitShape(skipShape1RejectAll, ent1x, ent1z, fixed::FromInt(10), &out); TS_ASSERT_EQUALS(0U, out.size()); out.clear(); cmp->TestStaticShape(skipShape1RejectAll, ent1x, ent1z, fixed::Zero(), fixed::FromInt(10), fixed::FromInt(10), &out); TS_ASSERT_EQUALS(0U, out.size()); out.clear(); } /** * Verifies the behaviour of SkipControlGroupsRequireFlagObstructionFilter. Tests with this filter will be performed * against all registered shapes that are members of neither specified control groups, and that have at least one of * the specified flags set. */ void test_filter_skip_controlgroups_require_flag() { std::vector out; // Collision-test a shape that overlaps the entire scene, but ignoring shapes from shape1's control group // (which also includes shape 2), and requiring that either the BLOCK_FOUNDATION or the // BLOCK_CONSTRUCTION flag is set, or both. Since shape 1 and shape 2 both belong to shape 1's control // group, and shape 3 has the BLOCK_FOUNDATION flag (but not BLOCK_CONSTRUCTION), we should find only // shape 3 in the result. SkipControlGroupsRequireFlagObstructionFilter skipGroup1ReqFoundConstr(ent1g1, INVALID_ENTITY, ICmpObstructionManager::FLAG_BLOCK_FOUNDATION | ICmpObstructionManager::FLAG_BLOCK_CONSTRUCTION); cmp->TestUnitShape(skipGroup1ReqFoundConstr, ent1x, ent1z, fixed::FromInt(10), &out); TS_ASSERT_EQUALS(1U, out.size()); TS_ASSERT_EQUALS(ent3, out[0]); out.clear(); cmp->TestStaticShape(skipGroup1ReqFoundConstr, ent1x, ent1z, fixed::Zero(), fixed::FromInt(10), fixed::FromInt(10), &out); TS_ASSERT_EQUALS(1U, out.size()); TS_ASSERT_EQUALS(ent3, out[0]); out.clear(); // Perform the same test, but now also exclude shape 3's control group (in addition to shape 1's control // group). Despite shape 3 having at least one of the required flags set, it should now also be ignored, // yielding an empty result set. SkipControlGroupsRequireFlagObstructionFilter skipGroup1And3ReqFoundConstr(ent1g1, ent3g, ICmpObstructionManager::FLAG_BLOCK_FOUNDATION | ICmpObstructionManager::FLAG_BLOCK_CONSTRUCTION); cmp->TestUnitShape(skipGroup1And3ReqFoundConstr, ent1x, ent1z, fixed::FromInt(10), &out); TS_ASSERT_EQUALS(0U, out.size()); out.clear(); cmp->TestStaticShape(skipGroup1And3ReqFoundConstr, ent1x, ent1z, fixed::Zero(), fixed::FromInt(10), fixed::FromInt(10), &out); TS_ASSERT_EQUALS(0U, out.size()); out.clear(); // Same test, but this time excluding only shape 3's control group, and requiring any of the available flags // to be set. Since both shape 1 and shape 2 have at least one flag set and are both in a different control // group, we should find them in the result. SkipControlGroupsRequireFlagObstructionFilter skipGroup3RequireAnyFlag(ent3g, INVALID_ENTITY, (ICmpObstructionManager::flags_t) -1); cmp->TestUnitShape(skipGroup3RequireAnyFlag, ent1x, ent1z, fixed::FromInt(10), &out); TS_ASSERT_EQUALS(2U, out.size()); TS_ASSERT_VECTOR_CONTAINS(out, ent1); TS_ASSERT_VECTOR_CONTAINS(out, ent2); out.clear(); cmp->TestStaticShape(skipGroup3RequireAnyFlag, ent1x, ent1z, fixed::Zero(), fixed::FromInt(10), fixed::FromInt(10), &out); TS_ASSERT_EQUALS(2U, out.size()); TS_ASSERT_VECTOR_CONTAINS(out, ent1); TS_ASSERT_VECTOR_CONTAINS(out, ent2); out.clear(); // Finally, the same test as the one directly above, now with an empty set of required flags. Since it now becomes // impossible for shape 1 and shape 2 to have at least one of the required flags set, and shape 3 is excluded by // virtue of the control group filtering, we should find an empty result. SkipControlGroupsRequireFlagObstructionFilter skipGroup3RequireNoFlags(ent3g, INVALID_ENTITY, 0U); cmp->TestUnitShape(skipGroup3RequireNoFlags, ent1x, ent1z, fixed::FromInt(10), &out); TS_ASSERT_EQUALS(0U, out.size()); out.clear(); cmp->TestStaticShape(skipGroup3RequireNoFlags, ent1x, ent1z, fixed::Zero(), fixed::FromInt(10), fixed::FromInt(10), &out); TS_ASSERT_EQUALS(0U, out.size()); out.clear(); // ------------------------------------------------------------------------------------ // In the tests up until this point, the shapes have all been filtered out based on their primary control group. // Now, to verify that shapes are also filtered out based on their secondary control groups, add a fourth shape // with arbitrarily-chosen dual control groups, and also change shape 1's secondary control group to another // arbitrarily-chosen control group. Then, do a scene-covering collision test while filtering out a combination // of shape 1's secondary control group, and one of shape 4's control groups. We should find neither ent1 nor ent4 // in the result. entity_id_t ent4 = 4, ent4g1 = 17, ent4g2 = 19, ent1g2_new = 18; // new secondary control group for entity 1 entity_pos_t ent4x = fixed::FromInt(4), ent4z = fixed::Zero(), ent4w = fixed::FromInt(1), ent4h = fixed::FromInt(1); entity_angle_t ent4a = fixed::FromDouble(M_PI/3); cmp->AddStaticShape(ent4, ent4x, ent4z, ent4a, ent4w, ent4h, ICmpObstructionManager::FLAG_BLOCK_PATHFINDING, ent4g1, ent4g2); cmp->SetStaticControlGroup(shape1, ent1g1, ent1g2_new); // Exclude shape 1's and shape 4's secondary control groups from testing, and require any available flag to be set. // Since neither shape 2 nor shape 3 are part of those control groups and both have at least one available flag set, // the results should only those two shapes' entities. SkipControlGroupsRequireFlagObstructionFilter skipGroup1SecAnd4SecRequireAny(ent1g2_new, ent4g2, (ICmpObstructionManager::flags_t) -1); cmp->TestUnitShape(skipGroup1SecAnd4SecRequireAny, ent1x, ent1z, fixed::FromInt(10), &out); TS_ASSERT_EQUALS(2U, out.size()); TS_ASSERT_VECTOR_CONTAINS(out, ent2); TS_ASSERT_VECTOR_CONTAINS(out, ent3); out.clear(); cmp->TestStaticShape(skipGroup1SecAnd4SecRequireAny, ent1x, ent1z, fixed::Zero(), fixed::FromInt(10), fixed::FromInt(10), &out); TS_ASSERT_EQUALS(2U, out.size()); TS_ASSERT_VECTOR_CONTAINS(out, ent2); TS_ASSERT_VECTOR_CONTAINS(out, ent3); out.clear(); // Same as the above, but now exclude shape 1's secondary and shape 4's primary control group, while still requiring // any available flag to be set. (Note that the test above used shape 4's secondary control group). Results should // remain the same. SkipControlGroupsRequireFlagObstructionFilter skipGroup1SecAnd4PrimRequireAny(ent1g2_new, ent4g1, (ICmpObstructionManager::flags_t) -1); cmp->TestUnitShape(skipGroup1SecAnd4PrimRequireAny, ent1x, ent1z, fixed::FromInt(10), &out); TS_ASSERT_EQUALS(2U, out.size()); TS_ASSERT_VECTOR_CONTAINS(out, ent2); TS_ASSERT_VECTOR_CONTAINS(out, ent3); out.clear(); cmp->TestStaticShape(skipGroup1SecAnd4PrimRequireAny, ent1x, ent1z, fixed::Zero(), fixed::FromInt(10), fixed::FromInt(10), &out); TS_ASSERT_EQUALS(2U, out.size()); TS_ASSERT_VECTOR_CONTAINS(out, ent2); TS_ASSERT_VECTOR_CONTAINS(out, ent3); out.clear(); cmp->SetStaticControlGroup(shape1, ent1g1, ent1g2); // restore shape 1's original secondary control group } void test_adjacent_shapes() { std::vector out; NullObstructionFilter nullFilter; SkipTagObstructionFilter ignoreShape1(shape1); SkipTagObstructionFilter ignoreShape2(shape2); SkipTagObstructionFilter ignoreShape3(shape3); // Collision-test a shape that is perfectly adjacent to shape3. This should be counted as a hit according to // the code at the time of writing. entity_angle_t ent4a = fixed::FromDouble(M_PI); // rotated 180 degrees, should not affect collision test entity_pos_t ent4w = fixed::FromInt(2), ent4h = fixed::FromInt(1), ent4x = ent3x + ent3c + ent4w/2, // make ent4 adjacent to ent3 ent4z = ent3z; cmp->TestStaticShape(nullFilter, ent4x, ent4z, ent4a, ent4w, ent4h, &out); TS_ASSERT_EQUALS(1U, out.size()); TS_ASSERT_EQUALS(ent3, out[0]); out.clear(); cmp->TestUnitShape(nullFilter, ent4x, ent4z, ent4w/2, &out); TS_ASSERT_EQUALS(1U, out.size()); TS_ASSERT_EQUALS(ent3, out[0]); out.clear(); // now do the same tests, but move the shape a little bit to the right so that it doesn't touch anymore cmp->TestStaticShape(nullFilter, ent4x + fixed::FromFloat(1e-5f), ent4z, ent4a, ent4w, ent4h, &out); TS_ASSERT_EQUALS(0U, out.size()); out.clear(); cmp->TestUnitShape(nullFilter, ent4x + fixed::FromFloat(1e-5f), ent4z, ent4w/2, &out); TS_ASSERT_EQUALS(0U, out.size()); out.clear(); } /** * Verifies that fetching the registered shapes from the obstruction manager yields the correct results. */ void test_get_obstruction() { ObstructionSquare obSquare1 = cmp->GetObstruction(shape1); ObstructionSquare obSquare2 = cmp->GetObstruction(shape2); ObstructionSquare obSquare3 = cmp->GetObstruction(shape3); TS_ASSERT_EQUALS(obSquare1.hh, ent1h/2); TS_ASSERT_EQUALS(obSquare1.hw, ent1w/2); TS_ASSERT_EQUALS(obSquare1.x, ent1x); TS_ASSERT_EQUALS(obSquare1.z, ent1z); TS_ASSERT_EQUALS(obSquare1.u, CFixedVector2D(fixed::FromInt(1), fixed::FromInt(0))); TS_ASSERT_EQUALS(obSquare1.v, CFixedVector2D(fixed::FromInt(0), fixed::FromInt(1))); TS_ASSERT_EQUALS(obSquare2.hh, ent2c); TS_ASSERT_EQUALS(obSquare2.hw, ent2c); TS_ASSERT_EQUALS(obSquare2.x, ent2x); TS_ASSERT_EQUALS(obSquare2.z, ent2z); TS_ASSERT_EQUALS(obSquare2.u, CFixedVector2D(fixed::FromInt(1), fixed::FromInt(0))); TS_ASSERT_EQUALS(obSquare2.v, CFixedVector2D(fixed::FromInt(0), fixed::FromInt(1))); TS_ASSERT_EQUALS(obSquare3.hh, ent3c); TS_ASSERT_EQUALS(obSquare3.hw, ent3c); TS_ASSERT_EQUALS(obSquare3.x, ent3x); TS_ASSERT_EQUALS(obSquare3.z, ent3z); TS_ASSERT_EQUALS(obSquare3.u, CFixedVector2D(fixed::FromInt(1), fixed::FromInt(0))); TS_ASSERT_EQUALS(obSquare3.v, CFixedVector2D(fixed::FromInt(0), fixed::FromInt(1))); } /** * Verifies the calculations of distances between shapes. */ void test_distance_to() { // Create two more entities to have non-zero distances entity_id_t ent4 = 4, ent4g1 = ent4, ent4g2 = INVALID_ENTITY, ent5 = 5, ent5g1 = ent5, ent5g2 = INVALID_ENTITY; entity_pos_t ent4a = fixed::Zero(), ent4w = fixed::FromInt(6), ent4h = fixed::Zero(), ent4x = ent1x, ent4z = fixed::FromInt(20), ent5a = fixed::Zero(), ent5w = fixed::FromInt(2), ent5h = fixed::FromInt(4), ent5x = fixed::FromInt(20), ent5z = ent1z; tag_t shape4 = cmp->AddStaticShape(ent4, ent4x, ent4z, ent4a, ent4w, ent4h, ICmpObstructionManager::FLAG_BLOCK_CONSTRUCTION | ICmpObstructionManager::FLAG_BLOCK_MOVEMENT | ICmpObstructionManager::FLAG_MOVING, ent4g1, ent4g2); tag_t shape5 = cmp->AddStaticShape(ent5, ent5x, ent5z, ent5a, ent5w, ent5h, ICmpObstructionManager::FLAG_BLOCK_CONSTRUCTION | ICmpObstructionManager::FLAG_BLOCK_MOVEMENT | ICmpObstructionManager::FLAG_MOVING, ent5g1, ent5g2); MockObstruction obstruction1, obstruction2, obstruction3, obstruction4, obstruction5; testHelper->AddMock(ent1, IID_Obstruction, obstruction1); testHelper->AddMock(ent2, IID_Obstruction, obstruction2); testHelper->AddMock(ent3, IID_Obstruction, obstruction3); testHelper->AddMock(ent4, IID_Obstruction, obstruction4); testHelper->AddMock(ent5, IID_Obstruction, obstruction5); obstruction1.obstruction = cmp->GetObstruction(shape1); obstruction2.obstruction = cmp->GetObstruction(shape2); obstruction3.obstruction = cmp->GetObstruction(shape3); obstruction4.obstruction = cmp->GetObstruction(shape4); obstruction5.obstruction = cmp->GetObstruction(shape5); TS_ASSERT_EQUALS(fixed::Zero(), cmp->DistanceToTarget(ent1, ent2)); TS_ASSERT_EQUALS(fixed::Zero(), cmp->DistanceToTarget(ent2, ent1)); TS_ASSERT_EQUALS(fixed::Zero(), cmp->DistanceToTarget(ent2, ent3)); TS_ASSERT_EQUALS(fixed::Zero(), cmp->DistanceToTarget(ent3, ent2)); // Due to rounding errors we need to use some leeway TS_ASSERT_DELTA(fixed::FromFloat(std::sqrt(80)), cmp->MaxDistanceToTarget(ent2, ent3), fixed::FromFloat(0.0001)); TS_ASSERT_DELTA(fixed::FromFloat(std::sqrt(80)), cmp->MaxDistanceToTarget(ent3, ent2), fixed::FromFloat(0.0001)); TS_ASSERT_EQUALS(fixed::Zero(), cmp->DistanceToTarget(ent1, ent3)); TS_ASSERT_EQUALS(fixed::Zero(), cmp->DistanceToTarget(ent3, ent1)); TS_ASSERT_EQUALS(fixed::FromInt(6), cmp->DistanceToTarget(ent1, ent4)); TS_ASSERT_EQUALS(fixed::FromInt(6), cmp->DistanceToTarget(ent4, ent1)); TS_ASSERT_DELTA(fixed::FromFloat(std::sqrt(125) + 3), cmp->MaxDistanceToTarget(ent1, ent4), fixed::FromFloat(0.0001)); TS_ASSERT_DELTA(fixed::FromFloat(std::sqrt(125) + 3), cmp->MaxDistanceToTarget(ent4, ent1), fixed::FromFloat(0.0001)); TS_ASSERT_EQUALS(fixed::FromInt(7), cmp->DistanceToTarget(ent1, ent5)); TS_ASSERT_EQUALS(fixed::FromInt(7), cmp->DistanceToTarget(ent5, ent1)); TS_ASSERT_DELTA(fixed::FromFloat(std::sqrt(178)), cmp->MaxDistanceToTarget(ent1, ent5), fixed::FromFloat(0.0001)); TS_ASSERT_DELTA(fixed::FromFloat(std::sqrt(178)), cmp->MaxDistanceToTarget(ent5, ent1), fixed::FromFloat(0.0001)); TS_ASSERT(cmp->IsInTargetRange(ent1, ent2, fixed::Zero(), fixed::FromInt(1), true)); TS_ASSERT(cmp->IsInTargetRange(ent1, ent2, fixed::Zero(), fixed::FromInt(1), false)); TS_ASSERT(cmp->IsInTargetRange(ent1, ent2, fixed::FromInt(1), fixed::FromInt(1), true)); TS_ASSERT(!cmp->IsInTargetRange(ent1, ent2, fixed::FromInt(1), fixed::FromInt(1), false)); TS_ASSERT(cmp->IsInTargetRange(ent1, ent5, fixed::Zero(), fixed::FromInt(10), true)); TS_ASSERT(cmp->IsInTargetRange(ent1, ent5, fixed::Zero(), fixed::FromInt(10), false)); TS_ASSERT(cmp->IsInTargetRange(ent1, ent5, fixed::FromInt(1), fixed::FromInt(10), true)); TS_ASSERT(!cmp->IsInTargetRange(ent1, ent5, fixed::FromInt(1), fixed::FromInt(5), false)); TS_ASSERT(!cmp->IsInTargetRange(ent1, ent5, fixed::FromInt(10), fixed::FromInt(10), false)); TS_ASSERT(cmp->IsInTargetRange(ent1, ent5, fixed::FromInt(10), fixed::FromInt(10), true)); } }; Index: ps/trunk/source/simulation2/helpers/Selection.cpp =================================================================== --- ps/trunk/source/simulation2/helpers/Selection.cpp (revision 22938) +++ ps/trunk/source/simulation2/helpers/Selection.cpp (revision 22939) @@ -1,263 +1,262 @@ -/* Copyright (C) 2017 Wildfire Games. +/* Copyright (C) 2019 Wildfire Games. * This file is part of 0 A.D. * * 0 A.D. is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 2 of the License, or * (at your option) any later version. * * 0 A.D. is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with 0 A.D. If not, see . */ #include "precompiled.h" #include "Selection.h" #include "graphics/Camera.h" -#include "simulation2/Simulation2.h" +#include "ps/CLogger.h" +#include "ps/Profiler2.h" #include "simulation2/components/ICmpIdentity.h" #include "simulation2/components/ICmpOwnership.h" #include "simulation2/components/ICmpRangeManager.h" #include "simulation2/components/ICmpTemplateManager.h" #include "simulation2/components/ICmpSelectable.h" #include "simulation2/components/ICmpVisual.h" #include "simulation2/components/ICmpUnitRenderer.h" #include "simulation2/system/ComponentManager.h" -#include "ps/CLogger.h" -#include "ps/Profiler2.h" entity_id_t EntitySelection::PickEntityAtPoint(CSimulation2& simulation, const CCamera& camera, int screenX, int screenY, player_id_t player, bool allowEditorSelectables) { PROFILE2("PickEntityAtPoint"); CVector3D origin, dir; camera.BuildCameraRay(screenX, screenY, origin, dir); CmpPtr cmpUnitRenderer(simulation.GetSimContext().GetSystemEntity()); ENSURE(cmpUnitRenderer); std::vector > entities; cmpUnitRenderer->PickAllEntitiesAtPoint(entities, origin, dir, allowEditorSelectables); if (entities.empty()) return INVALID_ENTITY; // Filter for relevent entities in the list of candidates (all entities below the mouse) std::vector > hits; // (dist^2, entity) pairs for (size_t i = 0; i < entities.size(); ++i) { // Find the perpendicular distance from the object's centre to the picker ray float dist2; const CVector3D center = entities[i].second; CVector3D closest = origin + dir * (center - origin).Dot(dir); dist2 = (closest - center).LengthSquared(); hits.emplace_back(dist2, entities[i].first); } // Sort hits by distance std::sort(hits.begin(), hits.end(), [](const std::pair& a, const std::pair& b) { return a.first < b.first; }); CmpPtr cmpRangeManager(simulation, SYSTEM_ENTITY); ENSURE(cmpRangeManager); for (size_t i = 0; i < hits.size(); ++i) { const CEntityHandle& handle = hits[i].second; CmpPtr cmpSelectable(handle); if (!cmpSelectable) continue; // Check if this entity is only selectable in Atlas if (!allowEditorSelectables && cmpSelectable->IsEditorOnly()) continue; // Ignore entities hidden by LOS (or otherwise hidden, e.g. when not IsInWorld) if (cmpRangeManager->GetLosVisibility(handle, player) == ICmpRangeManager::VIS_HIDDEN) continue; return handle.GetId(); } return INVALID_ENTITY; } /** * Returns true if the given entity is visible in the given screen area. * If the entity is a decorative, the function will only return true if allowEditorSelectables. */ -static bool CheckEntityInRect(CEntityHandle handle, const CCamera& camera, int sx0, int sy0, int sx1, int sy1, bool allowEditorSelectables) +bool CheckEntityInRect(CEntityHandle handle, const CCamera& camera, int sx0, int sy0, int sx1, int sy1, bool allowEditorSelectables) { // Check if this entity is only selectable in Atlas CmpPtr cmpSelectable(handle); if (!cmpSelectable || (!allowEditorSelectables && cmpSelectable->IsEditorOnly())) return false; // Find the current interpolated model position. // (We just use the centre position and not the whole bounding box, because maybe // that's better for users trying to select objects in busy areas) CmpPtr cmpVisual(handle); if (!cmpVisual) return false; CVector3D position = cmpVisual->GetPosition(); // Reject if it's not on-screen (e.g. it's behind the camera) if (!camera.GetFrustum().IsPointVisible(position)) return false; // Compare screen-space coordinates float x, y; camera.GetScreenCoordinates(position, x, y); int ix = (int)x; int iy = (int)y; return sx0 <= ix && ix <= sx1 && sy0 <= iy && iy <= sy1; } /** * Returns true if the given entity is visible to the given player and visible in the given screen area. */ static bool CheckEntityVisibleAndInRect(CEntityHandle handle, CmpPtr cmpRangeManager, const CCamera& camera, int sx0, int sy0, int sx1, int sy1, player_id_t player, bool allowEditorSelectables) { // Ignore entities hidden by LOS (or otherwise hidden, e.g. when not IsInWorld) if (cmpRangeManager->GetLosVisibility(handle, player) == ICmpRangeManager::VIS_HIDDEN) return false; return CheckEntityInRect(handle, camera, sx0, sy0, sx1, sy1, allowEditorSelectables); } std::vector EntitySelection::PickEntitiesInRect(CSimulation2& simulation, const CCamera& camera, int sx0, int sy0, int sx1, int sy1, player_id_t owner, bool allowEditorSelectables) { PROFILE2("PickEntitiesInRect"); // Make sure sx0 <= sx1, and sy0 <= sy1 if (sx0 > sx1) std::swap(sx0, sx1); if (sy0 > sy1) std::swap(sy0, sy1); CmpPtr cmpRangeManager(simulation, SYSTEM_ENTITY); ENSURE(cmpRangeManager); std::vector hitEnts; if (owner != INVALID_PLAYER) { CComponentManager& componentManager = simulation.GetSimContext().GetComponentManager(); std::vector ents = cmpRangeManager->GetEntitiesByPlayer(owner); for (std::vector::iterator it = ents.begin(); it != ents.end(); ++it) { if (CheckEntityVisibleAndInRect(componentManager.LookupEntityHandle(*it), cmpRangeManager, camera, sx0, sy0, sx1, sy1, owner, allowEditorSelectables)) hitEnts.push_back(*it); } } else // owner == INVALID_PLAYER; Used when selecting units in Atlas or other mods that allow all kinds of selectables to be selected. { const CSimulation2::InterfaceListUnordered& selectableEnts = simulation.GetEntitiesWithInterfaceUnordered(IID_Selectable); for (CSimulation2::InterfaceListUnordered::const_iterator it = selectableEnts.begin(); it != selectableEnts.end(); ++it) { if (CheckEntityVisibleAndInRect(it->second->GetEntityHandle(), cmpRangeManager, camera, sx0, sy0, sx1, sy1, owner, allowEditorSelectables)) hitEnts.push_back(it->first); } } return hitEnts; } std::vector EntitySelection::PickNonGaiaEntitiesInRect(CSimulation2& simulation, const CCamera& camera, int sx0, int sy0, int sx1, int sy1, bool allowEditorSelectables) { PROFILE2("PickNonGaiaEntitiesInRect"); // Make sure sx0 <= sx1, and sy0 <= sy1 if (sx0 > sx1) std::swap(sx0, sx1); if (sy0 > sy1) std::swap(sy0, sy1); CmpPtr cmpRangeManager(simulation, SYSTEM_ENTITY); ENSURE(cmpRangeManager); std::vector hitEnts; CComponentManager& componentManager = simulation.GetSimContext().GetComponentManager(); for (entity_id_t ent : cmpRangeManager->GetNonGaiaEntities()) if (CheckEntityInRect(componentManager.LookupEntityHandle(ent), camera, sx0, sy0, sx1, sy1, allowEditorSelectables)) hitEnts.push_back(ent); return hitEnts; } std::vector EntitySelection::PickSimilarEntities(CSimulation2& simulation, const CCamera& camera, const std::string& templateName, player_id_t owner, bool includeOffScreen, bool matchRank, bool allowEditorSelectables, bool allowFoundations) { PROFILE2("PickSimilarEntities"); CmpPtr cmpTemplateManager(simulation, SYSTEM_ENTITY); CmpPtr cmpRangeManager(simulation, SYSTEM_ENTITY); std::vector hitEnts; const CSimulation2::InterfaceListUnordered& ents = simulation.GetEntitiesWithInterfaceUnordered(IID_Selectable); for (CSimulation2::InterfaceListUnordered::const_iterator it = ents.begin(); it != ents.end(); ++it) { entity_id_t ent = it->first; CEntityHandle handle = it->second->GetEntityHandle(); // Check if this entity is only selectable in Atlas if (static_cast(it->second)->IsEditorOnly() && !allowEditorSelectables) continue; if (matchRank) { // Exact template name matching, optionally also allowing foundations std::string curTemplateName = cmpTemplateManager->GetCurrentTemplateName(ent); bool matches = (curTemplateName == templateName || (allowFoundations && curTemplateName.substr(0, 11) == "foundation|" && curTemplateName.substr(11) == templateName)); if (!matches) continue; } // Ignore entities hidden by LOS (or otherwise hidden, e.g. when not IsInWorld) // In this case, the checking is done to avoid selecting garrisoned units if (cmpRangeManager->GetLosVisibility(handle, owner) == ICmpRangeManager::VIS_HIDDEN) continue; // Ignore entities not owned by 'owner' CmpPtr cmpOwnership(simulation.GetSimContext(), ent); if (owner != INVALID_PLAYER && (!cmpOwnership || cmpOwnership->GetOwner() != owner)) continue; // Ignore off screen entities if (!includeOffScreen) { // Find the current interpolated model position. CmpPtr cmpVisual(simulation.GetSimContext(), ent); if (!cmpVisual) continue; CVector3D position = cmpVisual->GetPosition(); // Reject if it's not on-screen (e.g. it's behind the camera) if (!camera.GetFrustum().IsPointVisible(position)) continue; } if (!matchRank) { // Match by selection group name // (This is relatively expensive since it involves script calls, so do it after all other tests) CmpPtr cmpIdentity(simulation.GetSimContext(), ent); if (!cmpIdentity || cmpIdentity->GetSelectionGroupName() != templateName) continue; } hitEnts.push_back(ent); } return hitEnts; } Index: ps/trunk/source/simulation2/helpers/Selection.h =================================================================== --- ps/trunk/source/simulation2/helpers/Selection.h (revision 22938) +++ ps/trunk/source/simulation2/helpers/Selection.h (revision 22939) @@ -1,98 +1,133 @@ -/* Copyright (C) 2017 Wildfire Games. +/* Copyright (C) 2019 Wildfire Games. * This file is part of 0 A.D. * * 0 A.D. is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 2 of the License, or * (at your option) any later version. * * 0 A.D. is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with 0 A.D. If not, see . */ #ifndef INCLUDED_SELECTION #define INCLUDED_SELECTION -/** - * @file - * Helper functions related to entity selection - */ - +#include "simulation2/components/ICmpObstruction.h" +#include "simulation2/helpers/Player.h" +#include "simulation2/Simulation2.h" #include "simulation2/system/Entity.h" -#include "Player.h" #include class CSimulation2; class CCamera; +bool CheckEntityInRect(CEntityHandle handle, const CCamera& camera, int sx0, int sy0, int sx1, int sy1, bool allowEditorSelectables); + namespace EntitySelection { /** * Finds all selectable entities under the given screen coordinates. * * @param camera use this view to convert screen to world coordinates. * @param screenX,screenY 2D screen coordinates. * @param player player whose LOS will be used when selecting entities. In Atlas * this value is ignored as the whole map is revealed. * @param allowEditorSelectables if true, all entities with the ICmpSelectable interface * will be selected (including decorative actors), else only those selectable ingame. * @param range Approximate range to check for entity in. * * @return ordered list of selected entities with the closest first. */ entity_id_t PickEntityAtPoint(CSimulation2& simulation, const CCamera& camera, int screenX, int screenY, player_id_t player, bool allowEditorSelectables); /** * Finds all selectable entities within the given screen coordinate rectangle, * belonging to the given player. Used for bandboxing. * * @param camera use this view to convert screen to world coordinates. * @param sx0,sy0,sx1,sy1 diagonally opposite corners of the rectangle in 2D screen coordinates. * @param owner player whose entities we are selecting. Ownership is ignored if * INVALID_PLAYER is used. * @param allowEditorSelectables if true, all entities with the ICmpSelectable interface * will be selected (including decorative actors), else only those selectable ingame. * * @return unordered list of selected entities. */ std::vector PickEntitiesInRect(CSimulation2& simulation, const CCamera& camera, int sx0, int sy0, int sx1, int sy1, player_id_t owner, bool allowEditorSelectables); /** * Finds all selectable entities within the given screen coordinate rectangle, * belonging to any given player (excluding Gaia). Used for status bars. */ std::vector PickNonGaiaEntitiesInRect(CSimulation2& simulation, const CCamera& camera, int sx0, int sy0, int sx1, int sy1, bool allowEditorSelectables); /** + * Finds all entities with a given component belonging to any given player. + */ +struct DefaultComponentFilter +{ + bool operator()(IComponent* UNUSED(cmp)) + { + return true; + } +}; +template +std::vector GetEntitiesWithComponentInRect(CSimulation2& simulation, int cid, const CCamera& camera, int sx0, int sy0, int sx1, int sy1) +{ + PROFILE2("GetEntitiesWithObstructionInRect"); + + // Make sure sx0 <= sx1, and sy0 <= sy1 + if (sx0 > sx1) + std::swap(sx0, sx1); + if (sy0 > sy1) + std::swap(sy0, sy1); + + std::vector hitEnts; + + Filter filter; + const CSimulation2::InterfaceListUnordered& entities = simulation.GetEntitiesWithInterfaceUnordered(cid); + for (const std::pair& item : entities) + { + if (!filter(item.second)) + continue; + if (CheckEntityInRect(item.second->GetEntityHandle(), camera, sx0, sy0, sx1, sy1, false)) + hitEnts.push_back(item.first); + } + + return hitEnts; +} + +/** * Finds all entities with the given entity template name, belonging to the given player. * * @param camera use this view to convert screen to world coordinates. * @param templateName the name of the template to match, or the selection group name * for similar matching. * @param owner player whose entities we are selecting. Ownership is ignored if * INVALID_PLAYER is used. * @param includeOffScreen if true, then all entities visible in the world will be selected, * else only entities visible to the camera will be selected. * @param matchRank if true, only entities that exactly match templateName will be selected, * else entities with matching SelectionGroupName will be selected. * @param allowEditorSelectables if true, all entities with the ICmpSelectable interface * will be selected (including decorative actors), else only those selectable in-game. * @param allowFoundations if true, foundations are also included in the results. Only takes * effect when matchRank = true. * * @return unordered list of selected entities. * @see ICmpIdentity */ std::vector PickSimilarEntities(CSimulation2& simulation, const CCamera& camera, const std::string& templateName, player_id_t owner, bool includeOffScreen, bool matchRank, bool allowEditorSelectables, bool allowFoundations); } // namespace #endif // INCLUDED_SELECTION Index: ps/trunk/source/simulation2/scripting/JSInterface_Simulation.cpp =================================================================== --- ps/trunk/source/simulation2/scripting/JSInterface_Simulation.cpp (revision 22938) +++ ps/trunk/source/simulation2/scripting/JSInterface_Simulation.cpp (revision 22939) @@ -1,148 +1,162 @@ -/* Copyright (C) 2017 Wildfire Games. +/* Copyright (C) 2019 Wildfire Games. * This file is part of 0 A.D. * * 0 A.D. is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 2 of the License, or * (at your option) any later version. * * 0 A.D. is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with 0 A.D. If not, see . */ #include "precompiled.h" #include "JSInterface_Simulation.h" #include "graphics/GameView.h" #include "ps/Game.h" #include "ps/GameSetup/Config.h" #include "ps/Pyrogenesis.h" #include "scriptinterface/ScriptInterface.h" #include "simulation2/Simulation2.h" #include "simulation2/system/Entity.h" #include "simulation2/components/ICmpAIManager.h" #include "simulation2/components/ICmpCommandQueue.h" #include "simulation2/components/ICmpGuiInterface.h" #include "simulation2/components/ICmpSelectable.h" #include "simulation2/helpers/Selection.h" #include JS::Value JSI_Simulation::GetInitAttributes(ScriptInterface::CxPrivate* pCxPrivate) { if (!g_Game) return JS::UndefinedValue(); JSContext* cx = g_Game->GetSimulation2()->GetScriptInterface().GetContext(); JSAutoRequest rq(cx); JS::RootedValue initAttribs(cx); g_Game->GetSimulation2()->GetInitAttributes(&initAttribs); return pCxPrivate->pScriptInterface->CloneValueFromOtherContext( g_Game->GetSimulation2()->GetScriptInterface(), initAttribs); } JS::Value JSI_Simulation::GuiInterfaceCall(ScriptInterface::CxPrivate* pCxPrivate, const std::wstring& name, JS::HandleValue data) { if (!g_Game) return JS::UndefinedValue(); CSimulation2* sim = g_Game->GetSimulation2(); ENSURE(sim); CmpPtr cmpGuiInterface(*sim, SYSTEM_ENTITY); if (!cmpGuiInterface) return JS::UndefinedValue(); JSContext* cxSim = sim->GetScriptInterface().GetContext(); JSAutoRequest rqSim(cxSim); JS::RootedValue arg(cxSim, sim->GetScriptInterface().CloneValueFromOtherContext(*(pCxPrivate->pScriptInterface), data)); JS::RootedValue ret(cxSim); cmpGuiInterface->ScriptCall(g_Game->GetViewedPlayerID(), name, arg, &ret); return pCxPrivate->pScriptInterface->CloneValueFromOtherContext(sim->GetScriptInterface(), ret); } void JSI_Simulation::PostNetworkCommand(ScriptInterface::CxPrivate* pCxPrivate, JS::HandleValue cmd) { if (!g_Game) return; CSimulation2* sim = g_Game->GetSimulation2(); ENSURE(sim); CmpPtr cmpCommandQueue(*sim, SYSTEM_ENTITY); if (!cmpCommandQueue) return; JSContext* cxSim = sim->GetScriptInterface().GetContext(); JSAutoRequest rqSim(cxSim); JS::RootedValue cmd2(cxSim, sim->GetScriptInterface().CloneValueFromOtherContext(*(pCxPrivate->pScriptInterface), cmd)); cmpCommandQueue->PostNetworkCommand(cmd2); } void JSI_Simulation::DumpSimState(ScriptInterface::CxPrivate* UNUSED(pCxPrivate)) { OsPath path = psLogDir()/"sim_dump.txt"; std::ofstream file (OsString(path).c_str(), std::ofstream::out | std::ofstream::trunc); g_Game->GetSimulation2()->DumpDebugState(file); } entity_id_t JSI_Simulation::PickEntityAtPoint(ScriptInterface::CxPrivate* UNUSED(pCxPrivate), int x, int y) { return EntitySelection::PickEntityAtPoint(*g_Game->GetSimulation2(), *g_Game->GetView()->GetCamera(), x, y, g_Game->GetViewedPlayerID(), false); } std::vector JSI_Simulation::PickPlayerEntitiesInRect(ScriptInterface::CxPrivate* UNUSED(pCxPrivate), int x0, int y0, int x1, int y1, int player) { return EntitySelection::PickEntitiesInRect(*g_Game->GetSimulation2(), *g_Game->GetView()->GetCamera(), x0, y0, x1, y1, player, false); } std::vector JSI_Simulation::PickPlayerEntitiesOnScreen(ScriptInterface::CxPrivate* UNUSED(pCxPrivate), int player) { return EntitySelection::PickEntitiesInRect(*g_Game->GetSimulation2(), *g_Game->GetView()->GetCamera(), 0, 0, g_xres, g_yres, player, false); } std::vector JSI_Simulation::PickNonGaiaEntitiesOnScreen(ScriptInterface::CxPrivate* UNUSED(pCxPrivate)) { return EntitySelection::PickNonGaiaEntitiesInRect(*g_Game->GetSimulation2(), *g_Game->GetView()->GetCamera(), 0, 0, g_xres, g_yres, false); } +std::vector JSI_Simulation::GetEntitiesWithStaticObstructionOnScreen(ScriptInterface::CxPrivate* pCxPrivate) +{ + struct StaticObstructionFilter + { + bool operator()(IComponent* cmp) + { + ICmpObstruction* cmpObstruction = static_cast(cmp); + return cmpObstruction->GetObstructionType() == ICmpObstruction::STATIC; + } + }; + return EntitySelection::GetEntitiesWithComponentInRect(*g_Game->GetSimulation2(), IID_Obstruction, *g_Game->GetView()->GetCamera(), 0, 0, g_xres, g_yres); +} + std::vector JSI_Simulation::PickSimilarPlayerEntities(ScriptInterface::CxPrivate* UNUSED(pCxPrivate), const std::string& templateName, bool includeOffScreen, bool matchRank, bool allowFoundations) { return EntitySelection::PickSimilarEntities(*g_Game->GetSimulation2(), *g_Game->GetView()->GetCamera(), templateName, g_Game->GetViewedPlayerID(), includeOffScreen, matchRank, false, allowFoundations); } JS::Value JSI_Simulation::GetAIs(ScriptInterface::CxPrivate* pCxPrivate) { return ICmpAIManager::GetAIs(*(pCxPrivate->pScriptInterface)); } void JSI_Simulation::SetBoundingBoxDebugOverlay(ScriptInterface::CxPrivate* UNUSED(pCxPrivate), bool enabled) { ICmpSelectable::ms_EnableDebugOverlays = enabled; } void JSI_Simulation::RegisterScriptFunctions(const ScriptInterface& scriptInterface) { scriptInterface.RegisterFunction("GetInitAttributes"); scriptInterface.RegisterFunction("GuiInterfaceCall"); scriptInterface.RegisterFunction("PostNetworkCommand"); scriptInterface.RegisterFunction("DumpSimState"); scriptInterface.RegisterFunction("GetAIs"); scriptInterface.RegisterFunction("PickEntityAtPoint"); scriptInterface.RegisterFunction, int, int, int, int, int, &PickPlayerEntitiesInRect>("PickPlayerEntitiesInRect"); scriptInterface.RegisterFunction, int, &PickPlayerEntitiesOnScreen>("PickPlayerEntitiesOnScreen"); scriptInterface.RegisterFunction, &PickNonGaiaEntitiesOnScreen>("PickNonGaiaEntitiesOnScreen"); + scriptInterface.RegisterFunction, &GetEntitiesWithStaticObstructionOnScreen>("GetEntitiesWithStaticObstructionOnScreen"); scriptInterface.RegisterFunction, std::string, bool, bool, bool, &PickSimilarPlayerEntities>("PickSimilarPlayerEntities"); scriptInterface.RegisterFunction("SetBoundingBoxDebugOverlay"); } Index: ps/trunk/source/simulation2/scripting/JSInterface_Simulation.h =================================================================== --- ps/trunk/source/simulation2/scripting/JSInterface_Simulation.h (revision 22938) +++ ps/trunk/source/simulation2/scripting/JSInterface_Simulation.h (revision 22939) @@ -1,41 +1,42 @@ -/* Copyright (C) 2017 Wildfire Games. +/* Copyright (C) 2019 Wildfire Games. * This file is part of 0 A.D. * * 0 A.D. is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 2 of the License, or * (at your option) any later version. * * 0 A.D. is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with 0 A.D. If not, see . */ #ifndef INCLUDED_JSI_SIMULATION #define INCLUDED_JSI_SIMULATION #include "scriptinterface/ScriptInterface.h" #include "simulation2/system/Entity.h" namespace JSI_Simulation { JS::Value GetInitAttributes(ScriptInterface::CxPrivate* pCxPrivate); JS::Value GuiInterfaceCall(ScriptInterface::CxPrivate* pCxPrivate, const std::wstring& name, JS::HandleValue data); void PostNetworkCommand(ScriptInterface::CxPrivate* pCxPrivate, JS::HandleValue cmd); entity_id_t PickEntityAtPoint(ScriptInterface::CxPrivate* pCxPrivate, int x, int y); void DumpSimState(ScriptInterface::CxPrivate* pCxPrivate); std::vector PickPlayerEntitiesInRect(ScriptInterface::CxPrivate* pCxPrivate, int x0, int y0, int x1, int y1, int player); std::vector PickPlayerEntitiesOnScreen(ScriptInterface::CxPrivate* pCxPrivate, int player); std::vector PickNonGaiaEntitiesOnScreen(ScriptInterface::CxPrivate* pCxPrivate); + std::vector GetEntitiesWithStaticObstructionOnScreen(ScriptInterface::CxPrivate* pCxPrivate); std::vector PickSimilarPlayerEntities(ScriptInterface::CxPrivate* pCxPrivate, const std::string& templateName, bool includeOffScreen, bool matchRank, bool allowFoundations); JS::Value GetAIs(ScriptInterface::CxPrivate* pCxPrivate); void SetBoundingBoxDebugOverlay(ScriptInterface::CxPrivate* pCxPrivate, bool enabled); void RegisterScriptFunctions(const ScriptInterface& ScriptInterface); } #endif // INCLUDED_JSI_SIMULATION