Index: ps/trunk/binaries/data/mods/public/maps/scenarios/unit_pushing_test.js =================================================================== --- ps/trunk/binaries/data/mods/public/maps/scenarios/unit_pushing_test.js (nonexistent) +++ ps/trunk/binaries/data/mods/public/maps/scenarios/unit_pushing_test.js (revision 25182) @@ -0,0 +1,380 @@ +const REG_UNIT_TEMPLATE = "units/athen/infantry_spearman_b"; +const FAST_UNIT_TEMPLATE = "units/athen/cavalry_swordsman_b"; +const LARGE_UNIT_TEMPLATE = "units/brit/siege_ram"; +const ELE_TEMPLATE = "units/cart/champion_elephant"; + +const ATTACKER = 2; + +var QuickSpawn = function(x, z, template, owner = 1) +{ + let ent = Engine.AddEntity(template); + + let cmpEntOwnership = Engine.QueryInterface(ent, IID_Ownership); + if (cmpEntOwnership) + cmpEntOwnership.SetOwner(owner); + + let cmpEntPosition = Engine.QueryInterface(ent, IID_Position); + cmpEntPosition.JumpTo(x, z); + return ent; +}; + +var Rotate = function(angle, ent) +{ + let cmpEntPosition = Engine.QueryInterface(ent, IID_Position); + cmpEntPosition.SetYRotation(angle); + return ent; +}; + +var WalkTo = function(x, z, queued, ent, owner=1) +{ + ProcessCommand(owner, { + "type": "walk", + "entities": Array.isArray(ent) ? ent : [ent], + "x": x, + "z": z, + "queued": queued, + "force": true, + }); + return ent; +}; + +var FormationWalkTo = function(x, z, queued, ent, owner=1) +{ + ProcessCommand(owner, { + "type": "walk", + "entities": Array.isArray(ent) ? ent : [ent], + "x": x, + "z": z, + "queued": queued, + "force": true, + "formation": "special/formations/box" + }); + return ent; +}; + +var Attack = function(target, ent) +{ + let comm = { + "type": "attack", + "entities": Array.isArray(ent) ? ent : [ent], + "target": target, + "queued": true, + "force": true, + }; + ProcessCommand(ATTACKER, comm); + return ent; +}; + +var Do = function(name, data, ent, owner = 1) +{ + let comm = { + "type": name, + "entities": Array.isArray(ent) ? ent : [ent], + "queued": false + }; + for (let k in data) + comm[k] = data[k]; + ProcessCommand(owner, comm); +}; + + +var experiments = {}; + +experiments.units_sparse_forest_of_units = { + "spawn": (gx, gy) => { + for (let i = -16; i <= 16; i += 8) + for (let j = -16; j <= 16; j += 8) + QuickSpawn(gx + i, gy + 50 + j, REG_UNIT_TEMPLATE); + WalkTo(gx, gy + 100, true, QuickSpawn(gx, gy, REG_UNIT_TEMPLATE)); + WalkTo(gx, gy + 100, true, QuickSpawn(gx, gy-10, LARGE_UNIT_TEMPLATE)); + } +}; + +experiments.units_dense_forest_of_units = { + "spawn": (gx, gy) => { + for (let i = -16; i <= 16; i += 4) + for (let j = -16; j <= 16; j += 4) + QuickSpawn(gx + i, gy + 50 + j, REG_UNIT_TEMPLATE); + WalkTo(gx, gy + 100, true, QuickSpawn(gx, gy, REG_UNIT_TEMPLATE)); + WalkTo(gx, gy + 100, true, QuickSpawn(gx, gy-10, LARGE_UNIT_TEMPLATE)); + } +}; + +experiments.units_superdense_forest_of_units = { + "spawn": (gx, gy) => { + for (let i = -6; i <= 6; i += 2) + for (let j = -6; j <= 6; j += 2) + QuickSpawn(gx + i, gy + 50 + j, REG_UNIT_TEMPLATE); + WalkTo(gx, gy + 100, true, QuickSpawn(gx, gy, REG_UNIT_TEMPLATE)); + WalkTo(gx, gy + 100, true, QuickSpawn(gx, gy-10, LARGE_UNIT_TEMPLATE)); + } +}; + +experiments.building = { + "spawn": (gx, gy) => { + let target = QuickSpawn(gx + 20, gy + 20, "foundation|structures/athen/storehouse"); + for (let i = 0; i < 8; ++i) + Do("repair", { "target": target }, QuickSpawn(gx + i, gy, REG_UNIT_TEMPLATE)); + + let cmpFoundation = Engine.QueryInterface(target, IID_Foundation); + cmpFoundation.InitialiseConstruction(1, "structures/athen/storehouse"); + } +}; + +experiments.collecting_tree = { + "spawn": (gx, gy) => { + let target = QuickSpawn(gx + 10, gy + 10, "gaia/tree/acacia"); + let storehouse = QuickSpawn(gx - 10, gy - 10, "structures/athen/storehouse"); + for (let i = 0; i < 8; ++i) + Do("gather", { "target": target }, QuickSpawn(gx + i, gy, REG_UNIT_TEMPLATE)); + + let cmpModifiersManager = Engine.QueryInterface(SYSTEM_ENTITY, IID_ModifiersManager); + // Make that tree essentially infinite. + cmpModifiersManager.AddModifiers("inf_tree", { + "ResourceSupply/Max": [{ "affects": ["Tree"], "replace": 50000 }], + }, target); + let cmpSupply = Engine.QueryInterface(target, IID_ResourceSupply); + cmpSupply.SetAmount(50000); + // Make the storehouse a territory root + cmpModifiersManager.AddModifiers("root", { + "TerritoryInfluence/Root": [{ "affects": ["Structure"], "replace": true }], + }, storehouse); + // Make units gather instantly + cmpModifiersManager.AddModifiers("gatherrate", { + "ResourceGatherer/BaseSpeed": [{ "affects": ["Unit"], "replace": 100 }], + }, 3); // Player 1 is ent 3 + } +}; + +experiments.sep1 = { + "spawn": (gx, gy) => {} +}; + +experiments.battle = { + "spawn": (gx, gy) => { + for (let i = 0; i < 4; ++i) + for (let j = 0; j < 8; ++j) + { + QuickSpawn(gx + i, gy + j, REG_UNIT_TEMPLATE); + QuickSpawn(gx + i, gy + 50 + j, REG_UNIT_TEMPLATE, ATTACKER); + } + } +}; + +experiments.sep2 = { + "spawn": (gx, gy) => {} +}; + + +experiments.overlapping = { + "spawn": (gx, gy) => { + for (let i = 0; i < 20; ++i) + QuickSpawn(gx, gy, REG_UNIT_TEMPLATE); + } +}; + +experiments.multicrossing = { + "spawn": (gx, gy) => { + for (let i = 0; i < 20; i += 2) + for (let j = 0; j < 20; j += 2) + WalkTo(gx+10, gy+70, false, QuickSpawn(gx + i, gy + j, REG_UNIT_TEMPLATE)); + for (let i = 0; i < 20; i += 2) + for (let j = 0; j < 20; j += 2) + WalkTo(gx+10, gy, false, QuickSpawn(gx + i, gy + j + 70, REG_UNIT_TEMPLATE)); + } +}; + +experiments.elephant_formation = { + "spawn": (gx, gy) => { + let ents = []; + for (let i = 0; i < 20; i += 4) + for (let j = 0; j < 20; j += 4) + ents.push(QuickSpawn(gx + i, gy + j, ELE_TEMPLATE)); + FormationWalkTo(gx, gy+10, false, ents); + } +}; + +var perf_experiments = {}; + +// Perf check: put units everywhere, not moving. +perf_experiments.Idle = { + "spawn": () => { + const spacing = 12; + for (let x = 0; x < 20*16*4 - 20; x += spacing) + for (let z = 0; z < 20*16*4 - 20; z += spacing) + QuickSpawn(x, z, REG_UNIT_TEMPLATE); + } +}; + +// Perf check: put units everywhere, moving. +perf_experiments.MovingAround = { + "spawn": () => { + const spacing = 24; + for (let x = 0; x < 20*16*4 - 20; x += spacing) + for (let z = 0; z < 20*16*4 - 20; z += spacing) + { + let ent = QuickSpawn(x, z, REG_UNIT_TEMPLATE); + for (let i = 0; i < 5; ++i) + { + WalkTo(x + 4, z, true, ent); + WalkTo(x + 4, z + 4, true, ent); + WalkTo(x, z + 4, true, ent); + WalkTo(x, z, true, ent); + } + } + } +}; +// Perf check: fewer units moving more. +perf_experiments.LighterMovingAround = { + "spawn": () => { + const spacing = 48; + for (let x = 0; x < 20*16*4 - 20; x += spacing) + for (let z = 0; z < 20*16*4 - 20; z += spacing) + { + let ent = QuickSpawn(x, z, REG_UNIT_TEMPLATE); + for (let i = 0; i < 5; ++i) + { + WalkTo(x + 20, z, true, ent); + WalkTo(x + 20, z + 20, true, ent); + WalkTo(x, z + 20, true, ent); + WalkTo(x, z, true, ent); + } + } + } +}; + +// Perf check: rows of units crossing each other. +perf_experiments.BunchaCollisions = { + "spawn": () => { + const spacing = 64; + for (let x = 0; x < 20*16*4 - 20; x += spacing) + for (let z = 0; z < 20*16*4 - 20; z += spacing) + { + for (let i = 0; i < 10; ++i) + { + // Add a little variation to the spawning, or all clusters end up identical. + let ent = QuickSpawn(x + i + randFloat(-0.5, 0.5), z + 20 * (i%2) + randFloat(-0.5, 0.5), REG_UNIT_TEMPLATE); + for (let ii = 0; ii < 5; ++ii) + { + WalkTo(x + i, z + 20, true, ent); + WalkTo(x + i, z, true, ent); + } + } + } + } +}; + +// Massive moshpit of pushing. +perf_experiments.LotsaLocalCollisions = { + "spawn": () => { + const spacing = 3; + for (let x = 100; x < 200; x += spacing) + for (let z = 100; z < 200; z += spacing) + { + let ent = QuickSpawn(x, z, REG_UNIT_TEMPLATE); + for (let ii = 0; ii < 20; ++ii) + WalkTo(randFloat(100, 200), randFloat(100, 200), true, ent); + } + } +}; + +var woodcutting = (gx, gy) => { + let dropsite = QuickSpawn(gx + 50, gy, "structures/athen/storehouse"); + let cmpModifiersManager = Engine.QueryInterface(SYSTEM_ENTITY, IID_ModifiersManager); + cmpModifiersManager.AddModifiers("root", { + "TerritoryInfluence/Root": [{ "affects": ["Structure"], "replace": true }], + }, dropsite); + // Make units gather faster + cmpModifiersManager.AddModifiers("gatherrate", { + "ResourceGatherer/BaseSpeed": [{ "affects": ["Unit"], "multiply": 3 }], + }, 3); // Player 1 is ent 3 + for (let i = 20; i <= 80; i += 10) + for (let j = 20; j <= 50; j += 10) + QuickSpawn(gx + i, gy + j, "gaia/tree/acacia"); + for (let i = 10; i <= 90; i += 5) + Do("gather-near-position", { "x": gx + i, "z": gy + 10, "resourceType": { "generic": "wood", "specific": "tree" }, "resourceTemplate": "gaia/tree/acacia" }, + QuickSpawn(gx + i, gy, REG_UNIT_TEMPLATE)); +}; + +perf_experiments.WoodCutting = { + "spawn": () => { + for (let i = 0; i < 8; i++) + for (let j = 0; j < 8; j++) + { + woodcutting(20 + i*100, 20 + j*100); + } + } +}; + +var cmpTrigger = Engine.QueryInterface(SYSTEM_ENTITY, IID_Trigger); + +Trigger.prototype.Setup = function() +{ + let start = Engine.QueryInterface(SYSTEM_ENTITY, IID_Timer).GetTime(); + + // /* + let gx = 100; + let gy = 100; + for (let key in experiments) + { + experiments[key].spawn(gx, gy); + gx += 60; + if (gx > 20*16*4-20) + { + gx = 20; + gy += 100; + } + } + /**/ + /* + let time = 0; + for (let key in perf_experiments) + { + cmpTrigger.DoAfterDelay(1000 + time * 10000, "RunExperiment", { "exp": key }); + time++; + } + /**/ +}; + +Trigger.prototype.Cleanup = function() +{ + warn("cleanup"); + let cmpRangeManager = Engine.QueryInterface(SYSTEM_ENTITY, IID_RangeManager); + let ents = cmpRangeManager.GetEntitiesByPlayer(1).concat(cmpRangeManager.GetEntitiesByPlayer(2)); + for (let ent of ents) + Engine.DestroyEntity(ent); +}; + +Trigger.prototype.RunExperiment = function(data) +{ + warn("Start of " + data.exp); + perf_experiments[data.exp].spawn(); + cmpTrigger.DoAfterDelay(9500, "Cleanup", {}); +}; + +Trigger.prototype.EndGame = function() +{ + Engine.QueryInterface(4, IID_Player).SetState("defeated", "trigger"); + Engine.QueryInterface(3, IID_Player).SetState("won", "trigger"); +}; + +/* +var cmpModifiersManager = Engine.QueryInterface(SYSTEM_ENTITY, IID_ModifiersManager); + +// Reduce player 1 vision range (or patrolling units reacct) +cmpModifiersManager.AddModifiers("no_promotion", { + "Vision/Range": [{ "affects": ["Unit"], "replace": 5 }], +}, 3); // player 1 is ent 3 + +// Prevent promotions, messes up things. +cmpModifiersManager.AddModifiers("no_promotion_A", { + "Promotion/RequiredXp": [{ "affects": ["Unit"], "replace": 50000 }], +}, 3); +cmpModifiersManager.AddModifiers("no_promotion_B", { + "Promotion/RequiredXp": [{ "affects": ["Unit"], "replace": 50000 }], +}, 4); // player 2 is ent 4 +*/ + +cmpTrigger.DoAfterDelay(4000, "Setup", {}); + +cmpTrigger.DoAfterDelay(300000, "EndGame", {}); Property changes on: ps/trunk/binaries/data/mods/public/maps/scenarios/unit_pushing_test.js ___________________________________________________________________ Added: svn:eol-style ## -0,0 +1 ## +native \ No newline at end of property Index: ps/trunk/binaries/data/mods/public/maps/scenarios/unit_pushing_test.xml =================================================================== --- ps/trunk/binaries/data/mods/public/maps/scenarios/unit_pushing_test.xml (nonexistent) +++ ps/trunk/binaries/data/mods/public/maps/scenarios/unit_pushing_test.xml (revision 25182) @@ -0,0 +1,66 @@ + + + + + + default + + + + + + 0 + 0.5 + + + + + ocean + + + 5 + 4 + 0.45 + 0 + + + + 0 + 1 + 0.99 + 0.1999 + default + + + + + + + + + + + + Property changes on: ps/trunk/binaries/data/mods/public/maps/scenarios/unit_pushing_test.xml ___________________________________________________________________ Added: svn:eol-style ## -0,0 +1 ## +native \ No newline at end of property Index: ps/trunk/binaries/data/mods/public/simulation/components/Foundation.js =================================================================== --- ps/trunk/binaries/data/mods/public/simulation/components/Foundation.js (revision 25181) +++ ps/trunk/binaries/data/mods/public/simulation/components/Foundation.js (revision 25182) @@ -1,553 +1,553 @@ function Foundation() {} Foundation.prototype.Schema = ""; Foundation.prototype.Init = function() { // Foundations are initially 'uncommitted' and do not block unit movement at all // (to prevent players exploiting free foundations to confuse enemy units). // The first builder to reach the uncommitted foundation will tell friendly units // and animals to move out of the way, then will commit the foundation and enable // its obstruction once there's nothing in the way. this.committed = false; this.builders = new Map(); // Map of builder entities to their work per second this.totalBuilderRate = 0; // Total amount of work the builders do each second this.buildMultiplier = 1; // Multiplier for the amount of work builders do this.buildTimePenalty = 0.7; // Penalty for having multiple builders this.previewEntity = INVALID_ENTITY; }; Foundation.prototype.Serialize = function() { let ret = Object.assign({}, this); ret.previewEntity = INVALID_ENTITY; return ret; }; Foundation.prototype.Deserialize = function(data) { this.Init(); Object.assign(this, data); }; Foundation.prototype.OnDeserialized = function() { this.CreateConstructionPreview(); }; Foundation.prototype.InitialiseConstruction = function(owner, template) { this.finalTemplateName = template; // We need to know the owner in OnDestroy, but at that point the entity has already been // decoupled from its owner, so we need to remember it in here (and assume it won't change) this.owner = owner; // Remember the cost here, so if it changes after construction begins (from auras or technologies) // we will use the correct values to refund partial construction costs let cmpCost = Engine.QueryInterface(this.entity, IID_Cost); if (!cmpCost) error("A foundation must have a cost component to know the build time"); this.costs = cmpCost.GetResourceCosts(owner); this.maxProgress = 0; this.initialised = true; }; /** * Moving the revelation logic from Build to here makes the building sink if * it is attacked. */ Foundation.prototype.OnHealthChanged = function(msg) { // Gradually reveal the final building preview let cmpPosition = Engine.QueryInterface(this.previewEntity, IID_Position); if (cmpPosition) cmpPosition.SetConstructionProgress(this.GetBuildProgress()); Engine.PostMessage(this.entity, MT_FoundationProgressChanged, { "to": this.GetBuildPercentage() }); }; /** * Returns the current build progress in a [0,1] range. */ Foundation.prototype.GetBuildProgress = function() { var cmpHealth = Engine.QueryInterface(this.entity, IID_Health); if (!cmpHealth) return 0; var hitpoints = cmpHealth.GetHitpoints(); var maxHitpoints = cmpHealth.GetMaxHitpoints(); return hitpoints / maxHitpoints; }; Foundation.prototype.GetBuildPercentage = function() { return Math.floor(this.GetBuildProgress() * 100); }; /** * Returns the current builders. * * @return {number[]} - An array containing the entity IDs of assigned builders. */ Foundation.prototype.GetBuilders = function() { return Array.from(this.builders.keys()); }; Foundation.prototype.GetNumBuilders = function() { return this.builders.size; }; Foundation.prototype.IsFinished = function() { return (this.GetBuildProgress() == 1.0); }; Foundation.prototype.OnOwnershipChanged = function(msg) { if (msg.to != INVALID_PLAYER && this.previewEntity != INVALID_ENTITY) { let cmpPreviewOwnership = Engine.QueryInterface(this.previewEntity, IID_Ownership); if (cmpPreviewOwnership) cmpPreviewOwnership.SetOwner(msg.to); return; } if (msg.to != INVALID_PLAYER) return; // Refund a portion of the construction cost, proportional to the amount of build progress remaining if (!this.initialised) // this happens if the foundation was destroyed because the player had insufficient resources return; if (this.previewEntity != INVALID_ENTITY) { Engine.DestroyEntity(this.previewEntity); this.previewEntity = INVALID_ENTITY; } if (this.IsFinished()) return; let cmpPlayer = QueryPlayerIDInterface(this.owner); for (var r in this.costs) { var scaled = Math.ceil(this.costs[r] * (1.0 - this.maxProgress)); if (scaled) { cmpPlayer.AddResource(r, scaled); var cmpStatisticsTracker = QueryPlayerIDInterface(this.owner, IID_StatisticsTracker); if (cmpStatisticsTracker) cmpStatisticsTracker.IncreaseResourceUsedCounter(r, -scaled); } } }; /** * Adds an array of builders. * * @param {number[]} builders - An array containing the entity IDs of builders to assign. */ Foundation.prototype.AddBuilders = function(builders) { let changed = false; for (let builder of builders) changed = this.AddBuilderHelper(builder) || changed; if (changed) this.HandleBuildersChanged(); }; /** * Adds a single builder to this entity. * * @param {number} builderEnt - The entity to add. * @return {boolean} - Whether the addition was successful. */ Foundation.prototype.AddBuilderHelper = function(builderEnt) { if (this.builders.has(builderEnt)) return false; let cmpBuilder = Engine.QueryInterface(builderEnt, IID_Builder) || Engine.QueryInterface(this.entity, IID_AutoBuildable); if (!cmpBuilder) return false; let buildRate = cmpBuilder.GetRate(); this.builders.set(builderEnt, buildRate); this.totalBuilderRate += buildRate; return true; }; /** * Adds a builder to the counter. * * @param {number} builderEnt - The entity to add. */ Foundation.prototype.AddBuilder = function(builderEnt) { if (this.AddBuilderHelper(builderEnt)) this.HandleBuildersChanged(); }; Foundation.prototype.RemoveBuilder = function(builderEnt) { if (!this.builders.has(builderEnt)) return; this.totalBuilderRate -= this.builders.get(builderEnt); this.builders.delete(builderEnt); this.HandleBuildersChanged(); }; /** * This has to be called whenever the number of builders change. */ Foundation.prototype.HandleBuildersChanged = function() { this.SetBuildMultiplier(); let cmpVisual = Engine.QueryInterface(this.entity, IID_Visual); if (cmpVisual) cmpVisual.SetVariable("numbuilders", this.builders.size); Engine.PostMessage(this.entity, MT_FoundationBuildersChanged, { "to": this.GetBuilders() }); }; /** * The build multiplier is a penalty that is applied to each builder. * For example, ten women build at a combined rate of 10^0.7 = 5.01 instead of 10. */ Foundation.prototype.CalculateBuildMultiplier = function(num) { // Avoid division by zero, in particular 0/0 = NaN which isn't reliably serialized return num < 2 ? 1 : Math.pow(num, this.buildTimePenalty) / num; }; Foundation.prototype.SetBuildMultiplier = function() { this.buildMultiplier = this.CalculateBuildMultiplier(this.GetNumBuilders()); }; Foundation.prototype.GetBuildTime = function() { let timeLeft = (1 - this.GetBuildProgress()) * Engine.QueryInterface(this.entity, IID_Cost).GetBuildTime(); let rate = this.totalBuilderRate * this.buildMultiplier; // The rate if we add another woman to the foundation. let rateNew = (this.totalBuilderRate + 1) * this.CalculateBuildMultiplier(this.GetNumBuilders() + 1); return { // Avoid division by zero, in particular 0/0 = NaN which isn't reliably serialized "timeRemaining": rate ? timeLeft / rate : 0, "timeRemainingNew": timeLeft / rateNew }; }; /** * Perform some number of seconds of construction work. * Returns true if the construction is completed. */ Foundation.prototype.Build = function(builderEnt, work) { // Do nothing if we've already finished building // (The entity will be destroyed soon after completion so // this won't happen much) if (this.GetBuildProgress() == 1.0) return; var cmpObstruction = Engine.QueryInterface(this.entity, IID_Obstruction); // If there are any units in the way, ask them to move away and return early from this method. if (cmpObstruction && cmpObstruction.GetBlockMovementFlag()) { // Remove animal corpses for (let ent of cmpObstruction.GetEntitiesDeletedUponConstruction()) Engine.DestroyEntity(ent); let collisions = cmpObstruction.GetEntitiesBlockingConstruction(); if (collisions.length) { for (var ent of collisions) { var cmpUnitAI = Engine.QueryInterface(ent, IID_UnitAI); if (cmpUnitAI) cmpUnitAI.LeaveFoundation(this.entity); // TODO: What if an obstruction has no UnitAI? } // TODO: maybe we should tell the builder to use a special // animation to indicate they're waiting for people to get // out the way return; } } // Handle the initial 'committing' of the foundation if (!this.committed) { // The obstruction always blocks new foundations/construction, // but we've temporarily allowed units to walk all over it // (via CCmpTemplateManager). Now we need to remove that temporary // blocker-disabling, so that we'll perform standard unit blocking instead. - if (cmpObstruction && cmpObstruction.GetBlockMovementFlag()) + if (cmpObstruction) cmpObstruction.SetDisableBlockMovementPathfinding(false, false, -1); // Call the related trigger event var cmpTrigger = Engine.QueryInterface(SYSTEM_ENTITY, IID_Trigger); cmpTrigger.CallEvent("ConstructionStarted", { "foundation": this.entity, "template": this.finalTemplateName }); // Switch foundation to scaffold variant var cmpFoundationVisual = Engine.QueryInterface(this.entity, IID_Visual); if (cmpFoundationVisual) cmpFoundationVisual.SelectAnimation("scaffold", false, 1.0); this.committed = true; this.CreateConstructionPreview(); } // Add an appropriate proportion of hitpoints var cmpHealth = Engine.QueryInterface(this.entity, IID_Health); if (!cmpHealth) { error("Foundation " + this.entity + " does not have a health component."); return; } var deltaHP = work * this.GetBuildRate() * this.buildMultiplier; if (deltaHP > 0) cmpHealth.Increase(deltaHP); // Update the total builder rate this.totalBuilderRate += work - this.builders.get(builderEnt); this.builders.set(builderEnt, work); var progress = this.GetBuildProgress(); // Remember our max progress for partial refund in case of destruction this.maxProgress = Math.max(this.maxProgress, progress); if (progress >= 1.0) { // Finished construction // Create the real entity var building = Engine.AddEntity(this.finalTemplateName); // Copy various parameters from the foundation var cmpVisual = Engine.QueryInterface(this.entity, IID_Visual); var cmpBuildingVisual = Engine.QueryInterface(building, IID_Visual); if (cmpVisual && cmpBuildingVisual) cmpBuildingVisual.SetActorSeed(cmpVisual.GetActorSeed()); var cmpPosition = Engine.QueryInterface(this.entity, IID_Position); if (!cmpPosition || !cmpPosition.IsInWorld()) { error("Foundation " + this.entity + " does not have a position in-world."); Engine.DestroyEntity(building); return; } var cmpBuildingPosition = Engine.QueryInterface(building, IID_Position); if (!cmpBuildingPosition) { error("New building " + building + " has no position component."); Engine.DestroyEntity(building); return; } var pos = cmpPosition.GetPosition2D(); cmpBuildingPosition.JumpTo(pos.x, pos.y); var rot = cmpPosition.GetRotation(); cmpBuildingPosition.SetYRotation(rot.y); cmpBuildingPosition.SetXZRotation(rot.x, rot.z); // TODO: should add a ICmpPosition::CopyFrom() instead of all this var cmpRallyPoint = Engine.QueryInterface(this.entity, IID_RallyPoint); var cmpBuildingRallyPoint = Engine.QueryInterface(building, IID_RallyPoint); if(cmpRallyPoint && cmpBuildingRallyPoint) { var rallyCoords = cmpRallyPoint.GetPositions(); var rallyData = cmpRallyPoint.GetData(); for (var i = 0; i < rallyCoords.length; ++i) { cmpBuildingRallyPoint.AddPosition(rallyCoords[i].x, rallyCoords[i].z); cmpBuildingRallyPoint.AddData(rallyData[i]); } } // ---------------------------------------------------------------------- var owner; var cmpTerritoryDecay = Engine.QueryInterface(building, IID_TerritoryDecay); if (cmpTerritoryDecay && cmpTerritoryDecay.HasTerritoryOwnership()) { let cmpTerritoryManager = Engine.QueryInterface(SYSTEM_ENTITY, IID_TerritoryManager); owner = cmpTerritoryManager.GetOwner(pos.x, pos.y); } else { let cmpOwnership = Engine.QueryInterface(this.entity, IID_Ownership); if (!cmpOwnership) { error("Foundation " + this.entity + " has no ownership."); Engine.DestroyEntity(building); return; } owner = cmpOwnership.GetOwner(); } var cmpBuildingOwnership = Engine.QueryInterface(building, IID_Ownership); if (!cmpBuildingOwnership) { error("New Building " + building + " has no ownership."); Engine.DestroyEntity(building); return; } cmpBuildingOwnership.SetOwner(owner); /* Copy over the obstruction control group IDs from the foundation entities. This is needed to ensure that when a foundation is completed and replaced by a new entity, it remains in the same control group(s) as any other foundation entities that may surround it. This is the mechanism that is used to e.g. enable wall pieces to be built closely together, ignoring their mutual obstruction shapes (since they would otherwise be prevented from being built so closely together). If the control groups are not copied over, the new entity will default to a new control group containing only itself, and will hence block construction of any surrounding foundations that it was previously in the same control group with. Note that this will result in the completed building entities having control group IDs that equal entity IDs of old (and soon to be deleted) foundation entities. This should not have any consequences, however, since the control group IDs are only meant to be unique identifiers, which is still true when reusing the old ones. */ var cmpBuildingObstruction = Engine.QueryInterface(building, IID_Obstruction); if (cmpObstruction && cmpBuildingObstruction) { cmpBuildingObstruction.SetControlGroup(cmpObstruction.GetControlGroup()); cmpBuildingObstruction.SetControlGroup2(cmpObstruction.GetControlGroup2()); } var cmpPlayerStatisticsTracker = QueryOwnerInterface(this.entity, IID_StatisticsTracker); if (cmpPlayerStatisticsTracker) cmpPlayerStatisticsTracker.IncreaseConstructedBuildingsCounter(building); var cmpBuildingHealth = Engine.QueryInterface(building, IID_Health); if (cmpBuildingHealth) cmpBuildingHealth.SetHitpoints(progress * cmpBuildingHealth.GetMaxHitpoints()); PlaySound("constructed", building); Engine.PostMessage(this.entity, MT_ConstructionFinished, { "entity": this.entity, "newentity": building }); Engine.PostMessage(this.entity, MT_EntityRenamed, { "entity": this.entity, "newentity": building }); // Inform the builders that repairing has finished. // This not done by listening to a global message due to performance. for (let builder of this.GetBuilders()) { let cmpUnitAIBuilder = Engine.QueryInterface(builder, IID_UnitAI); if (cmpUnitAIBuilder) cmpUnitAIBuilder.ConstructionFinished({ "entity": this.entity, "newentity": building }); } Engine.DestroyEntity(this.entity); } }; Foundation.prototype.GetBuildRate = function() { let cmpHealth = Engine.QueryInterface(this.entity, IID_Health); let cmpCost = Engine.QueryInterface(this.entity, IID_Cost); // Return infinity for instant structure conversion return cmpHealth.GetMaxHitpoints() / cmpCost.GetBuildTime(); }; /** * Create preview entity and copy various parameters from the foundation. */ Foundation.prototype.CreateConstructionPreview = function() { if (this.previewEntity) { Engine.DestroyEntity(this.previewEntity); this.previewEntity = INVALID_ENTITY; } if (!this.committed) return; let cmpFoundationVisual = Engine.QueryInterface(this.entity, IID_Visual); if (!cmpFoundationVisual || !cmpFoundationVisual.HasConstructionPreview()) return; this.previewEntity = Engine.AddLocalEntity("construction|"+this.finalTemplateName); let cmpFoundationOwnership = Engine.QueryInterface(this.entity, IID_Ownership); let cmpPreviewOwnership = Engine.QueryInterface(this.previewEntity, IID_Ownership); if (cmpFoundationOwnership && cmpPreviewOwnership) cmpPreviewOwnership.SetOwner(cmpFoundationOwnership.GetOwner()); // TODO: the 'preview' would be invisible if it doesn't have the below component, // Maybe it makes more sense to simply delete it then? // Initially hide the preview underground let cmpPreviewPosition = Engine.QueryInterface(this.previewEntity, IID_Position); let cmpFoundationPosition = Engine.QueryInterface(this.entity, IID_Position); if (cmpPreviewPosition && cmpFoundationPosition) { let rot = cmpFoundationPosition.GetRotation(); cmpPreviewPosition.SetYRotation(rot.y); cmpPreviewPosition.SetXZRotation(rot.x, rot.z); let pos = cmpFoundationPosition.GetPosition2D(); cmpPreviewPosition.JumpTo(pos.x, pos.y); cmpPreviewPosition.SetConstructionProgress(this.GetBuildProgress()); } let cmpPreviewVisual = Engine.QueryInterface(this.previewEntity, IID_Visual); if (cmpPreviewVisual && cmpFoundationVisual) { cmpPreviewVisual.SetActorSeed(cmpFoundationVisual.GetActorSeed()); cmpPreviewVisual.SelectAnimation("scaffold", false, 1.0); } }; function FoundationMirage() {} FoundationMirage.prototype.Init = function(cmpFoundation) { this.numBuilders = cmpFoundation.GetNumBuilders(); this.buildTime = cmpFoundation.GetBuildTime(); }; FoundationMirage.prototype.GetNumBuilders = function() { return this.numBuilders; }; FoundationMirage.prototype.GetBuildTime = function() { return this.buildTime; }; Engine.RegisterGlobal("FoundationMirage", FoundationMirage); Foundation.prototype.Mirage = function() { let mirage = new FoundationMirage(); mirage.Init(this); return mirage; }; Engine.RegisterComponentType(IID_Foundation, "Foundation", Foundation); Index: ps/trunk/binaries/data/mods/public/simulation/templates/special/formations/testudo.xml =================================================================== --- ps/trunk/binaries/data/mods/public/simulation/templates/special/formations/testudo.xml (revision 25181) +++ ps/trunk/binaries/data/mods/public/simulation/templates/special/formations/testudo.xml (revision 25182) @@ -1,70 +1,70 @@ formations/testudo.png 16 Melee Infantry only, requires at least 16. Hero Champion Elite Advanced Basic Testudo square 0.50 - 0.35 + 0.4 fillFromTheSides 0.8 8 8 1..1,2..7: testudo_front; 1..1,1..1: testudo_front_left; 1..1,8..8: testudo_front_right; 2..2,2..7: testudo_top; 2..2,8..8: testudo_right; 2..2,1..1: testudo_left; 3..3,1..1: testudo_top; 3..3,8..8: testudo_top; 3..3,2..7: testudo_front; 4..4,8..8: testudo_right; 4..4,2..7: testudo_top; 4..4,1..1: testudo_left; 5..5,1..1: testudo_top; 5..5,8..8: testudo_top; 5..5,2..7: testudo_front; 6..6,8..8: testudo_right; 6..6,2..7: testudo_top; 6..6,1..1: testudo_left; 7..7,1..1: testudo_top; 7..7,8..8: testudo_top; 7..7,2..7: testudo_front; 8..8,8..8: testudo_right; 8..8,2..7: testudo_top; 8..8,1..1: testudo_left; 9..9,1..1: testudo_top; 9..9,8..8: testudo_top; 9..9,2..7: testudo_front; 10..10,8..8: testudo_right; 10..10,2..7: testudo_top; 10..10,1..1: testudo_left; 11..11,1..1: testudo_top; 11..11,8..8: testudo_top; 11..11,2..7: testudo_front; 12..12,8..8: testudo_right; 12..12,2..7: testudo_top; 12..12,1..1: testudo_left; 13..13,1..1: testudo_top; 13..13,8..8: testudo_top; 13..13,2..7: testudo_front; 14..14,8..8: testudo_right; 14..14,2..7: testudo_top; 14..14,1..1: testudo_left: 15..15,1..1: testudo_top; 15..15,8..8: testudo_top; 15..15,2..7: testudo_front; 16..16,8..8: testudo_right; 16..16,2..7: testudo_top; 16..16,1..1: testudo_left false Index: ps/trunk/source/simulation2/MessageTypes.h =================================================================== --- ps/trunk/source/simulation2/MessageTypes.h (revision 25181) +++ ps/trunk/source/simulation2/MessageTypes.h (revision 25182) @@ -1,607 +1,621 @@ -/* Copyright (C) 2019 Wildfire Games. +/* Copyright (C) 2021 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_MESSAGETYPES #define INCLUDED_MESSAGETYPES #include "simulation2/system/Components.h" #include "simulation2/system/Entity.h" #include "simulation2/system/Message.h" #include "simulation2/helpers/Player.h" #include "simulation2/helpers/Position.h" #include "simulation2/components/ICmpPathfinder.h" #include "maths/Vector3D.h" #include "ps/CStr.h" #define DEFAULT_MESSAGE_IMPL(name) \ virtual int GetType() const { return MT_##name; } \ virtual const char* GetScriptHandlerName() const { return "On" #name; } \ virtual const char* GetScriptGlobalHandlerName() const { return "OnGlobal" #name; } \ virtual JS::Value ToJSVal(const ScriptInterface& scriptInterface) const; \ static CMessage* FromJSVal(const ScriptInterface&, JS::HandleValue val); class SceneCollector; class CFrustum; class CMessageTurnStart : public CMessage { public: DEFAULT_MESSAGE_IMPL(TurnStart) CMessageTurnStart() { } }; // The update process is split into a number of phases, in an attempt // to cope with dependencies between components. Each phase is implemented // as a separate message. Simulation2.cpp sends them in sequence. /** * Generic per-turn update message, for things that don't care much about ordering. */ class CMessageUpdate : public CMessage { public: DEFAULT_MESSAGE_IMPL(Update) CMessageUpdate(fixed turnLength) : turnLength(turnLength) { } fixed turnLength; }; /** * Update phase for formation controller movement (must happen before individual * units move to follow their formation). */ class CMessageUpdate_MotionFormation : public CMessage { public: DEFAULT_MESSAGE_IMPL(Update_MotionFormation) CMessageUpdate_MotionFormation(fixed turnLength) : turnLength(turnLength) { } fixed turnLength; }; /** * Update phase for non-formation-controller unit movement. */ class CMessageUpdate_MotionUnit : public CMessage { public: DEFAULT_MESSAGE_IMPL(Update_MotionUnit) CMessageUpdate_MotionUnit(fixed turnLength) : turnLength(turnLength) { } fixed turnLength; }; /** * Final update phase, after all other updates. */ class CMessageUpdate_Final : public CMessage { public: DEFAULT_MESSAGE_IMPL(Update_Final) CMessageUpdate_Final(fixed turnLength) : turnLength(turnLength) { } fixed turnLength; }; /** * Prepare for rendering a new frame (set up model positions etc). */ class CMessageInterpolate : public CMessage { public: DEFAULT_MESSAGE_IMPL(Interpolate) CMessageInterpolate(float deltaSimTime, float offset, float deltaRealTime) : deltaSimTime(deltaSimTime), offset(offset), deltaRealTime(deltaRealTime) { } /// Elapsed simulation time since previous interpolate, in seconds. This is similar to the elapsed real time, except /// it is scaled by the current simulation rate (and might indeed be zero). float deltaSimTime; /// Range [0, 1] (inclusive); fractional time of current frame between previous/next simulation turns. float offset; /// Elapsed real time since previous interpolate, in seconds. float deltaRealTime; }; /** * Add renderable objects to the scene collector. * Called after CMessageInterpolate. */ class CMessageRenderSubmit : public CMessage { public: DEFAULT_MESSAGE_IMPL(RenderSubmit) CMessageRenderSubmit(SceneCollector& collector, const CFrustum& frustum, bool culling) : collector(collector), frustum(frustum), culling(culling) { } SceneCollector& collector; const CFrustum& frustum; bool culling; }; /** * Handle progressive loading of resources. * A component that listens to this message must do the following: * - Increase *msg.total by the non-zero number of loading tasks this component can perform. * - If *msg.progressed == true, return and do nothing. * - If you've loaded everything, increase *msg.progress by the value you added to .total * - Otherwise do some loading, set *msg.progressed = true, and increase *msg.progress by a * value indicating how much progress you've made in total (0 <= p <= what you added to .total) * In some situations these messages will never be sent - components must ensure they * load all their data themselves before using it in that case. */ class CMessageProgressiveLoad : public CMessage { public: DEFAULT_MESSAGE_IMPL(ProgressiveLoad) CMessageProgressiveLoad(bool* progressed, int* total, int* progress) : progressed(progressed), total(total), progress(progress) { } bool* progressed; int* total; int* progress; }; /** * Broadcast after the entire simulation state has been deserialized. * Components should do all their self-contained work in their Deserialize * function when possible. But any reinitialisation that depends on other * components or other entities, that might not be constructed until later * in the deserialization process, may be done in response to this message * instead. */ class CMessageDeserialized : public CMessage { public: DEFAULT_MESSAGE_IMPL(Deserialized) CMessageDeserialized() { } }; /** * This is sent immediately after a new entity's components have all been created * and initialised. */ class CMessageCreate : public CMessage { public: DEFAULT_MESSAGE_IMPL(Create) CMessageCreate(entity_id_t entity) : entity(entity) { } entity_id_t entity; }; /** * This is sent immediately before a destroyed entity is flushed and really destroyed. * (That is, after CComponentManager::DestroyComponentsSoon and inside FlushDestroyedComponents). * The entity will still exist at the time this message is sent. * It's possible for this message to be sent multiple times for one entity, but all its components * will have been deleted after the first time. */ class CMessageDestroy : public CMessage { public: DEFAULT_MESSAGE_IMPL(Destroy) CMessageDestroy(entity_id_t entity) : entity(entity) { } entity_id_t entity; }; class CMessageOwnershipChanged : public CMessage { public: DEFAULT_MESSAGE_IMPL(OwnershipChanged) CMessageOwnershipChanged(entity_id_t entity, player_id_t from, player_id_t to) : entity(entity), from(from), to(to) { } entity_id_t entity; player_id_t from; player_id_t to; }; /** * Sent by CCmpPosition whenever anything has changed that will affect the * return value of GetPosition2D() or GetRotation().Y * * If @c inWorld is false, then the other fields are invalid and meaningless. * Otherwise they represent the current position. */ class CMessagePositionChanged : public CMessage { public: DEFAULT_MESSAGE_IMPL(PositionChanged) CMessagePositionChanged(entity_id_t entity, bool inWorld, entity_pos_t x, entity_pos_t z, entity_angle_t a) : entity(entity), inWorld(inWorld), x(x), z(z), a(a) { } entity_id_t entity; bool inWorld; entity_pos_t x, z; entity_angle_t a; }; /** * Sent by CCmpPosition whenever anything has changed that will affect the * return value of GetInterpolatedTransform() */ class CMessageInterpolatedPositionChanged : public CMessage { public: DEFAULT_MESSAGE_IMPL(InterpolatedPositionChanged) CMessageInterpolatedPositionChanged(entity_id_t entity, bool inWorld, const CVector3D& pos0, const CVector3D& pos1) : entity(entity), inWorld(inWorld), pos0(pos0), pos1(pos1) { } entity_id_t entity; bool inWorld; CVector3D pos0; CVector3D pos1; }; /*Sent whenever the territory type (neutral,own,enemy) differs from the former type*/ class CMessageTerritoryPositionChanged : public CMessage { public: DEFAULT_MESSAGE_IMPL(TerritoryPositionChanged) CMessageTerritoryPositionChanged(entity_id_t entity, player_id_t newTerritory) : entity(entity), newTerritory(newTerritory) { } entity_id_t entity; player_id_t newTerritory; }; /** * Sent by CCmpUnitMotion during Update if an event happened that might interest other components. */ class CMessageMotionUpdate : public CMessage { public: DEFAULT_MESSAGE_IMPL(MotionUpdate) enum UpdateType { LIKELY_SUCCESS, // UnitMotion considers it is arrived at destination. LIKELY_FAILURE, // UnitMotion says it cannot reach the destination. OBSTRUCTED, // UnitMotion was obstructed. This does not mean stuck, but can be a hint to run range checks. VERY_OBSTRUCTED, // Sent when obstructed several time in a row. LENGTH }; static const std::array UpdateTypeStr; CMessageMotionUpdate(UpdateType ut) : updateType(ut) { } UpdateType updateType; }; /** * Sent when water height has been changed. */ class CMessageWaterChanged : public CMessage { public: DEFAULT_MESSAGE_IMPL(WaterChanged) CMessageWaterChanged() { } }; /** * Sent when terrain (texture or elevation) has been changed. */ class CMessageTerrainChanged : public CMessage { public: DEFAULT_MESSAGE_IMPL(TerrainChanged) CMessageTerrainChanged(int32_t i0, int32_t j0, int32_t i1, int32_t j1) : i0(i0), j0(j0), i1(i1), j1(j1) { } int32_t i0, j0, i1, j1; // inclusive lower bound, exclusive upper bound, in tiles }; /** * Sent, at most once per turn, when the visibility of an entity changed */ class CMessageVisibilityChanged : public CMessage { public: DEFAULT_MESSAGE_IMPL(VisibilityChanged) CMessageVisibilityChanged(player_id_t player, entity_id_t ent, int oldVisibility, int newVisibility) : player(player), ent(ent), oldVisibility(oldVisibility), newVisibility(newVisibility) { } player_id_t player; entity_id_t ent; int oldVisibility; int newVisibility; }; /** + * Sent when then obstruction of an entity has changed in a manner + * that changes 'block movement' properties. + */ +class CMessageMovementObstructionChanged : public CMessage +{ +public: + DEFAULT_MESSAGE_IMPL(MovementObstructionChanged) + + CMessageMovementObstructionChanged() + { + } +}; + +/** * Sent when ObstructionManager's view of the shape of the world has changed * (changing the TILE_OUTOFBOUNDS tiles returned by Rasterise). */ class CMessageObstructionMapShapeChanged : public CMessage { public: DEFAULT_MESSAGE_IMPL(ObstructionMapShapeChanged) CMessageObstructionMapShapeChanged() { } }; /** * Sent when territory assignments have changed. */ class CMessageTerritoriesChanged : public CMessage { public: DEFAULT_MESSAGE_IMPL(TerritoriesChanged) CMessageTerritoriesChanged() { } }; /** * Sent by CCmpRangeManager at most once per turn, when an active range query * has had matching units enter/leave the range since the last RangeUpdate. */ class CMessageRangeUpdate : public CMessage { public: DEFAULT_MESSAGE_IMPL(RangeUpdate) u32 tag; std::vector added; std::vector removed; // CCmpRangeManager wants to store a vector of messages and wants to // swap vectors instead of copying (to save on memory allocations), // so add some constructors for it: // don't init tag in empty ctor CMessageRangeUpdate() { } CMessageRangeUpdate(u32 tag) : tag(tag) { } CMessageRangeUpdate(u32 tag, const std::vector& added, const std::vector& removed) : tag(tag), added(added), removed(removed) { } CMessageRangeUpdate(const CMessageRangeUpdate& other) : CMessage(), tag(other.tag), added(other.added), removed(other.removed) { } CMessageRangeUpdate& operator=(const CMessageRangeUpdate& other) { tag = other.tag; added = other.added; removed = other.removed; return *this; } }; /** * Sent by CCmpPathfinder after async path requests. */ class CMessagePathResult : public CMessage { public: DEFAULT_MESSAGE_IMPL(PathResult) CMessagePathResult(u32 ticket, const WaypointPath& path) : ticket(ticket), path(path) { } u32 ticket; WaypointPath path; }; /** * Sent by aura manager when a value of a certain entity's component is changed */ class CMessageValueModification : public CMessage { public: DEFAULT_MESSAGE_IMPL(ValueModification) CMessageValueModification(const std::vector& entities, std::wstring component, const std::vector& valueNames) : entities(entities), component(component), valueNames(valueNames) { } std::vector entities; std::wstring component; std::vector valueNames; }; /** * Sent by atlas if the playercolor has been changed. */ class CMessagePlayerColorChanged : public CMessage { public: DEFAULT_MESSAGE_IMPL(PlayerColorChanged) CMessagePlayerColorChanged(player_id_t player) : player(player) { } player_id_t player; }; /** * Sent by aura and tech managers when a value of a certain template's component is changed */ class CMessageTemplateModification : public CMessage { public: DEFAULT_MESSAGE_IMPL(TemplateModification) CMessageTemplateModification(player_id_t player, std::wstring component, const std::vector& valueNames) : player(player), component(component), valueNames(valueNames) { } player_id_t player; std::wstring component; std::vector valueNames; }; /** * Sent by CCmpVision when an entity's vision range changes. */ class CMessageVisionRangeChanged : public CMessage { public: DEFAULT_MESSAGE_IMPL(VisionRangeChanged) CMessageVisionRangeChanged(entity_id_t entity, entity_pos_t oldRange, entity_pos_t newRange) : entity(entity), oldRange(oldRange), newRange(newRange) { } entity_id_t entity; entity_pos_t oldRange; entity_pos_t newRange; }; /** * Sent by CCmpVision when an entity's vision sharing changes. */ class CMessageVisionSharingChanged : public CMessage { public: DEFAULT_MESSAGE_IMPL(VisionSharingChanged) CMessageVisionSharingChanged(entity_id_t entity, player_id_t player, bool add) : entity(entity), player(player), add(add) { } entity_id_t entity; player_id_t player; bool add; }; /** * Sent when an entity pings the minimap */ class CMessageMinimapPing : public CMessage { public: DEFAULT_MESSAGE_IMPL(MinimapPing) CMessageMinimapPing() { } }; /** * Cinematics events */ class CMessageCinemaPathEnded : public CMessage { public: DEFAULT_MESSAGE_IMPL(CinemaPathEnded) CMessageCinemaPathEnded(CStrW name) : name(name) { } CStrW name; }; class CMessageCinemaQueueEnded : public CMessage { public: DEFAULT_MESSAGE_IMPL(CinemaQueueEnded) }; #endif // INCLUDED_MESSAGETYPES Index: ps/trunk/source/simulation2/TypeList.h =================================================================== --- ps/trunk/source/simulation2/TypeList.h (revision 25181) +++ ps/trunk/source/simulation2/TypeList.h (revision 25182) @@ -1,217 +1,218 @@ /* Copyright (C) 2021 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 . */ // MESSAGE: message types // INTERFACE: component interface types // COMPONENT: component types // Components intended only for use in test cases: // (The tests rely on the enum IDs, so don't change the order of these) INTERFACE(Test1) COMPONENT(Test1A) COMPONENT(Test1B) COMPONENT(Test1Scripted) INTERFACE(Test2) COMPONENT(Test2A) COMPONENT(Test2Scripted) // Message types: MESSAGE(TurnStart) MESSAGE(Update) MESSAGE(Update_MotionFormation) MESSAGE(Update_MotionUnit) MESSAGE(Update_Final) MESSAGE(Interpolate) // non-deterministic (use with caution) MESSAGE(RenderSubmit) // non-deterministic (use with caution) MESSAGE(ProgressiveLoad) // non-deterministic (use with caution) MESSAGE(Deserialized) // non-deterministic (use with caution) MESSAGE(Create) MESSAGE(Destroy) MESSAGE(OwnershipChanged) MESSAGE(PositionChanged) MESSAGE(InterpolatedPositionChanged) MESSAGE(TerritoryPositionChanged) MESSAGE(MotionUpdate) MESSAGE(RangeUpdate) MESSAGE(TerrainChanged) MESSAGE(VisibilityChanged) MESSAGE(WaterChanged) +MESSAGE(MovementObstructionChanged) MESSAGE(ObstructionMapShapeChanged) MESSAGE(TerritoriesChanged) MESSAGE(PathResult) MESSAGE(ValueModification) MESSAGE(TemplateModification) MESSAGE(VisionRangeChanged) MESSAGE(VisionSharingChanged) MESSAGE(MinimapPing) MESSAGE(CinemaPathEnded) MESSAGE(CinemaQueueEnded) MESSAGE(PlayerColorChanged) // TemplateManager must come before all other (non-test) components, // so that it is the first to be (de)serialized INTERFACE(TemplateManager) COMPONENT(TemplateManager) // Special component for script component types with no native interface INTERFACE(UnknownScript) COMPONENT(UnknownScript) // In alphabetical order: INTERFACE(AIInterface) COMPONENT(AIInterfaceScripted) INTERFACE(AIManager) COMPONENT(AIManager) INTERFACE(Attack) COMPONENT(AttackScripted) INTERFACE(CinemaManager) COMPONENT(CinemaManager) INTERFACE(CommandQueue) COMPONENT(CommandQueue) INTERFACE(Decay) COMPONENT(Decay) INTERFACE(Fogging) COMPONENT(FoggingScripted) // Note: The VisualActor component relies on this component being initialized before itself, in order to support using // an entity's footprint shape for the selection boxes. This dependency is not strictly necessary, but it does avoid // some extra plumbing code to set up on-demand initialization. If you find yourself forced to break this dependency, // see VisualActor's Init method for a description of how you can avoid it. INTERFACE(Footprint) COMPONENT(Footprint) INTERFACE(GarrisonHolder) COMPONENT(GarrisonHolderScripted) INTERFACE(GuiInterface) COMPONENT(GuiInterfaceScripted) INTERFACE(Identity) COMPONENT(IdentityScripted) INTERFACE(Minimap) COMPONENT(Minimap) INTERFACE(Mirage) COMPONENT(MirageScripted) INTERFACE(Motion) COMPONENT(MotionBall) COMPONENT(MotionScripted) INTERFACE(Obstruction) COMPONENT(Obstruction) INTERFACE(ObstructionManager) COMPONENT(ObstructionManager) INTERFACE(OverlayRenderer) COMPONENT(OverlayRenderer) INTERFACE(Ownership) COMPONENT(Ownership) INTERFACE(ParticleManager) COMPONENT(ParticleManager) INTERFACE(Pathfinder) COMPONENT(Pathfinder) INTERFACE(Player) COMPONENT(PlayerScripted) INTERFACE(PlayerManager) COMPONENT(PlayerManagerScripted) INTERFACE(Position) COMPONENT(Position) // must be before VisualActor INTERFACE(ProjectileManager) COMPONENT(ProjectileManager) INTERFACE(RallyPoint) COMPONENT(RallyPointScripted) INTERFACE(RallyPointRenderer) COMPONENT(RallyPointRenderer) INTERFACE(RangeManager) COMPONENT(RangeManager) INTERFACE(RangeOverlayRenderer) COMPONENT(RangeOverlayRenderer) INTERFACE(Selectable) COMPONENT(Selectable) INTERFACE(Settlement) COMPONENT(SettlementScripted) INTERFACE(Sound) COMPONENT(SoundScripted) INTERFACE(SoundManager) COMPONENT(SoundManager) INTERFACE(ValueModificationManager) COMPONENT(ValueModificationManagerScripted) INTERFACE(Terrain) COMPONENT(Terrain) INTERFACE(TerritoryDecayManager) COMPONENT(TerritoryDecayManagerScripted) INTERFACE(TerritoryInfluence) COMPONENT(TerritoryInfluence) INTERFACE(TerritoryManager) COMPONENT(TerritoryManager) INTERFACE(TurretHolder) COMPONENT(TurretHolderScripted) INTERFACE(UnitMotion) COMPONENT(UnitMotion) // must be after Obstruction COMPONENT(UnitMotionScripted) INTERFACE(UnitMotionManager) COMPONENT(UnitMotionManager) INTERFACE(UnitRenderer) COMPONENT(UnitRenderer) INTERFACE(Visibility) COMPONENT(VisibilityScripted) INTERFACE(Vision) COMPONENT(Vision) // Note: this component relies on the Footprint component being initialized before itself. See the comments above for // the Footprint component to find out why. INTERFACE(Visual) COMPONENT(VisualActor) // must be after Ownership (dependency in Deserialize) and Vision (dependency in Init) INTERFACE(WaterManager) COMPONENT(WaterManager) Index: ps/trunk/source/simulation2/components/CCmpObstruction.cpp =================================================================== --- ps/trunk/source/simulation2/components/CCmpObstruction.cpp (revision 25181) +++ ps/trunk/source/simulation2/components/CCmpObstruction.cpp (revision 25182) @@ -1,845 +1,861 @@ -/* Copyright (C) 2020 Wildfire Games. +/* Copyright (C) 2021 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 "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/SerializedTypes.h" #include "ps/CLogger.h" template<> struct SerializeHelper { template void operator()(S& serialize, const char* UNUSED(name), Serialize::qualify value) { serialize.NumberU32_Unbounded("tag", value.n); } }; /** * 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: 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; // WORKAROUND: While processing Destroy messages, the obstruction component may receive messages // that make it re-enable the obstruction, thus leaving behind dangling obstructions. // To avoid that, if this is true, _never_ reactivate the obstruction. bool m_IsDestroyed = false; /** * 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() { } 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) Serializer(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 || m_IsDestroyed) 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: { // Mark the obstruction as destroyed to prevent reactivating it after this point m_IsDestroyed = true; m_Active = false; if (m_Tag.valid()) { CmpPtr cmpObstructionManager(GetSystemEntity()); if (!cmpObstructionManager) break; // error cmpObstructionManager->RemoveShape(m_Tag); m_Tag = tag_t(); if(m_Type == CLUSTER) RemoveClusterShapes(); } break; } } } virtual void SetActive(bool active) { if (active && !m_Active && !m_IsDestroyed) { 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); + + // Used by UnitMotion to activate/deactivate pushing + if (m_TemplateFlags & ICmpObstructionManager::FLAG_BLOCK_MOVEMENT) + { + CMessageMovementObstructionChanged msg; + GetSimContext().GetComponentManager().PostMessage(GetEntityId(), msg); + } } 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(); } + + // Used by UnitMotion to activate/deactivate pushing + if (m_TemplateFlags & ICmpObstructionManager::FLAG_BLOCK_MOVEMENT) + { + CMessageMovementObstructionChanged msg; + GetSimContext().GetComponentManager().PostMessage(GetEntityId(), msg); + } } // 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 + virtual bool GetBlockMovementFlag(bool templateOnly) const { - return (m_TemplateFlags & ICmpObstructionManager::FLAG_BLOCK_MOVEMENT) != 0; + return m_Active && ((templateOnly ? m_TemplateFlags : m_Flags) & 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 GetSize() const { if (m_Type == UNIT) return m_Clearance; else return CFixedVector2D(m_Size0 / 2, m_Size1 / 2).Length(); } virtual CFixedVector2D GetStaticSize() const { return m_Type == STATIC ? CFixedVector2D(m_Size0, m_Size1) : CFixedVector2D(); } virtual void SetUnitClearance(const entity_pos_t& clearance) { + // This doesn't send a MovementObstructionChanged message + // because it's a just a workaround init order, and used in UnitMotion directly. 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 GetEntitiesBlockingMovement() const { return GetEntitiesByFlags(ICmpObstructionManager::FLAG_BLOCK_MOVEMENT); } 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 (const entity_id_t normalEnt : normalEnts) { CmpPtr cmpObstruction(GetSimContext(), normalEnt); for (const entity_id_t persistent : normalEnts) { entity_id_t group = cmpObstruction->GetControlGroup(); // Only clobber 'default' control groups. if (group == normalEnt) 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/CCmpUnitMotion.h =================================================================== --- ps/trunk/source/simulation2/components/CCmpUnitMotion.h (revision 25181) +++ ps/trunk/source/simulation2/components/CCmpUnitMotion.h (revision 25182) @@ -1,1730 +1,1757 @@ /* Copyright (C) 2021 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_CCMPUNITMOTION #define INCLUDED_CCMPUNITMOTION #include "simulation2/system/Component.h" #include "ICmpUnitMotion.h" #include "simulation2/components/CCmpUnitMotionManager.h" #include "simulation2/components/ICmpObstruction.h" #include "simulation2/components/ICmpObstructionManager.h" #include "simulation2/components/ICmpOwnership.h" #include "simulation2/components/ICmpPosition.h" #include "simulation2/components/ICmpPathfinder.h" #include "simulation2/components/ICmpRangeManager.h" #include "simulation2/components/ICmpValueModificationManager.h" #include "simulation2/components/ICmpVisual.h" #include "simulation2/helpers/Geometry.h" #include "simulation2/helpers/Render.h" #include "simulation2/MessageTypes.h" #include "simulation2/serialization/SerializedPathfinder.h" #include "simulation2/serialization/SerializedTypes.h" #include "graphics/Overlay.h" #include "graphics/Terrain.h" #include "maths/FixedVector2D.h" #include "ps/CLogger.h" #include "ps/Profile.h" #include "renderer/Scene.h" // NB: this implementation of ICmpUnitMotion is very tightly coupled with UnitMotionManager. // As such, both are compiled in the same TU. // For debugging; units will start going straight to the target // instead of calling the pathfinder #define DISABLE_PATHFINDER 0 /** * Min/Max range to restrict short path queries to. (Larger ranges are (much) slower, * smaller ranges might miss some legitimate routes around large obstacles.) * NB: keep the max-range in sync with the vertex pathfinder "move the search space" heuristic. */ -static const entity_pos_t SHORT_PATH_MIN_SEARCH_RANGE = entity_pos_t::FromInt(TERRAIN_TILE_SIZE*3)/2; +static const entity_pos_t SHORT_PATH_MIN_SEARCH_RANGE = entity_pos_t::FromInt(TERRAIN_TILE_SIZE*3); static const entity_pos_t SHORT_PATH_MAX_SEARCH_RANGE = entity_pos_t::FromInt(TERRAIN_TILE_SIZE*14); static const entity_pos_t SHORT_PATH_SEARCH_RANGE_INCREMENT = entity_pos_t::FromInt(TERRAIN_TILE_SIZE*1); -static const u8 SHORT_PATH_SEARCH_RANGE_INCREASE_DELAY = 2; +static const u8 SHORT_PATH_SEARCH_RANGE_INCREASE_DELAY = 1; /** * When using the short-pathfinder to rejoin a long-path waypoint, aim for a circle of this radius around the waypoint. */ static const entity_pos_t SHORT_PATH_LONG_WAYPOINT_RANGE = entity_pos_t::FromInt(TERRAIN_TILE_SIZE*1); /** * Minimum distance to goal for a long path request */ static const entity_pos_t LONG_PATH_MIN_DIST = entity_pos_t::FromInt(TERRAIN_TILE_SIZE*4); /** * If we are this close to our target entity/point, then think about heading * for it in a straight line instead of pathfinding. */ static const entity_pos_t DIRECT_PATH_RANGE = entity_pos_t::FromInt(TERRAIN_TILE_SIZE*6); /** * To avoid recomputing paths too often, have some leeway for target range checks * based on our distance to the target. Increase that incertainty by one navcell * for every this many tiles of distance. */ static const entity_pos_t TARGET_UNCERTAINTY_MULTIPLIER = entity_pos_t::FromInt(TERRAIN_TILE_SIZE*2); /** * When following a known imperfect path (i.e. a path that won't take us in range of our goal * we still recompute a new path every N turn to adapt to moving targets (for example, ships that must pickup * units may easily end up in this state, they still need to adjust to moving units). * This is rather arbitrary and mostly for simplicity & optimisation (a better recomputing algorithm * would not need this). */ static const u8 KNOWN_IMPERFECT_PATH_RESET_COUNTDOWN = 12; /** * When we fail to move this many turns in a row, inform other components that the move will fail. * Experimentally, this number needs to be somewhat high or moving groups of units will lead to stuck units. * However, too high means units will look idle for a long time when they are failing to move. * TODO: if UnitMotion could send differentiated "unreachable" and "currently stuck" failing messages, * this could probably be lowered. * TODO: when unit pushing is implemented, this number can probably be lowered. */ -static const u8 MAX_FAILED_MOVEMENTS = 40; +static const u8 MAX_FAILED_MOVEMENTS = 35; /** * When computing paths but failing to move, we want to occasionally alternate pathfinder systems * to avoid getting stuck (the short pathfinder can unstuck the long-range one and vice-versa, depending). */ static const u8 ALTERNATE_PATH_TYPE_DELAY = 3; static const u8 ALTERNATE_PATH_TYPE_EVERY = 6; /** * After this many failed computations, start sending "VERY_OBSTRUCTED" messages instead. * Should probably be larger than ALTERNATE_PATH_TYPE_DELAY. */ static const u8 VERY_OBSTRUCTED_THRESHOLD = 10; static const CColor OVERLAY_COLOR_LONG_PATH(1, 1, 1, 1); static const CColor OVERLAY_COLOR_SHORT_PATH(1, 0, 0, 1); class CCmpUnitMotion final : public ICmpUnitMotion { friend class CCmpUnitMotionManager; public: static void ClassInit(CComponentManager& componentManager) { componentManager.SubscribeToMessageType(MT_Create); componentManager.SubscribeToMessageType(MT_Destroy); componentManager.SubscribeToMessageType(MT_PathResult); componentManager.SubscribeToMessageType(MT_OwnershipChanged); componentManager.SubscribeToMessageType(MT_ValueModification); + componentManager.SubscribeToMessageType(MT_MovementObstructionChanged); componentManager.SubscribeToMessageType(MT_Deserialized); } DEFAULT_COMPONENT_ALLOCATOR(UnitMotion) bool m_DebugOverlayEnabled; std::vector m_DebugOverlayLongPathLines; std::vector m_DebugOverlayShortPathLines; // Template state: bool m_FormationController; fixed m_TemplateWalkSpeed, m_TemplateRunMultiplier; pass_class_t m_PassClass; std::string m_PassClassName; // Dynamic state: entity_pos_t m_Clearance; // cached for efficiency fixed m_WalkSpeed, m_RunMultiplier; bool m_FacePointAfterMove; - // Number of turns since we last managed to move successfully. + // Whether the unit participates in pushing. + bool m_Pushing = true; + + // Internal counter used when recovering from obstructed movement. + // Most notably, increases the search range of the vertex pathfinder. // See HandleObstructedMove() for more details. u8 m_FailedMovements = 0; // If > 0, PathingUpdateNeeded returns false always. // This exists because the goal may be unreachable to the short/long pathfinder. // In such cases, we would compute inacceptable paths and PathingUpdateNeeded would trigger every turn, // which would be quite bad for performance. // To avoid that, when we know the new path is imperfect, treat it as OK and follow it anyways. // When reaching the end, we'll go through HandleObstructedMove and reset regardless. // To still recompute now and then (the target may be moving), this is a countdown decremented on each frame. u8 m_FollowKnownImperfectPathCountdown = 0; struct Ticket { u32 m_Ticket = 0; // asynchronous request ID we're waiting for, or 0 if none enum Type { SHORT_PATH, LONG_PATH } m_Type = SHORT_PATH; // Pick some default value to avoid UB. void clear() { m_Ticket = 0; } } m_ExpectedPathTicket; struct MoveRequest { enum Type { NONE, POINT, ENTITY, OFFSET } m_Type = NONE; entity_id_t m_Entity = INVALID_ENTITY; CFixedVector2D m_Position; entity_pos_t m_MinRange, m_MaxRange; // For readability CFixedVector2D GetOffset() const { return m_Position; }; MoveRequest() = default; MoveRequest(CFixedVector2D pos, entity_pos_t minRange, entity_pos_t maxRange) : m_Type(POINT), m_Position(pos), m_MinRange(minRange), m_MaxRange(maxRange) {}; MoveRequest(entity_id_t target, entity_pos_t minRange, entity_pos_t maxRange) : m_Type(ENTITY), m_Entity(target), m_MinRange(minRange), m_MaxRange(maxRange) {}; MoveRequest(entity_id_t target, CFixedVector2D offset) : m_Type(OFFSET), m_Entity(target), m_Position(offset) {}; } m_MoveRequest; // If the entity moves, it will do so at m_WalkSpeed * m_SpeedMultiplier. fixed m_SpeedMultiplier; // This caches the resulting speed from m_WalkSpeed * m_SpeedMultiplier for convenience. fixed m_Speed; // Current mean speed (over the last turn). fixed m_CurSpeed; // Currently active paths (storing waypoints in reverse order). // The last item in each path is the point we're currently heading towards. WaypointPath m_LongPath; WaypointPath m_ShortPath; static std::string GetSchema() { return "Provides the unit with the ability to move around the world by itself." "" "7.0" "default" "" "" "" "" "" "" "" "" "" "" "" "" "" "" ""; } virtual void Init(const CParamNode& paramNode) { m_FormationController = paramNode.GetChild("FormationController").ToBool(); m_FacePointAfterMove = true; m_WalkSpeed = m_TemplateWalkSpeed = m_Speed = paramNode.GetChild("WalkSpeed").ToFixed(); m_SpeedMultiplier = fixed::FromInt(1); m_CurSpeed = fixed::Zero(); m_RunMultiplier = m_TemplateRunMultiplier = fixed::FromInt(1); if (paramNode.GetChild("RunMultiplier").IsOk()) m_RunMultiplier = m_TemplateRunMultiplier = paramNode.GetChild("RunMultiplier").ToFixed(); CmpPtr cmpPathfinder(GetSystemEntity()); if (cmpPathfinder) { m_PassClassName = paramNode.GetChild("PassabilityClass").ToUTF8(); m_PassClass = cmpPathfinder->GetPassabilityClass(m_PassClassName); m_Clearance = cmpPathfinder->GetClearance(m_PassClass); CmpPtr cmpObstruction(GetEntityHandle()); if (cmpObstruction) + { cmpObstruction->SetUnitClearance(m_Clearance); + if (!cmpObstruction->GetBlockMovementFlag(true)) + m_Pushing = false; + } } m_DebugOverlayEnabled = false; } virtual void Deinit() { } template void SerializeCommon(S& serialize) { serialize.StringASCII("pass class", m_PassClassName, 0, 64); serialize.NumberU32_Unbounded("ticket", m_ExpectedPathTicket.m_Ticket); Serializer(serialize, "ticket type", m_ExpectedPathTicket.m_Type, Ticket::Type::LONG_PATH); serialize.NumberU8_Unbounded("failed movements", m_FailedMovements); serialize.NumberU8_Unbounded("followknownimperfectpath", m_FollowKnownImperfectPathCountdown); Serializer(serialize, "target type", m_MoveRequest.m_Type, MoveRequest::Type::OFFSET); serialize.NumberU32_Unbounded("target entity", m_MoveRequest.m_Entity); serialize.NumberFixed_Unbounded("target pos x", m_MoveRequest.m_Position.X); serialize.NumberFixed_Unbounded("target pos y", m_MoveRequest.m_Position.Y); serialize.NumberFixed_Unbounded("target min range", m_MoveRequest.m_MinRange); serialize.NumberFixed_Unbounded("target max range", m_MoveRequest.m_MaxRange); serialize.NumberFixed_Unbounded("speed multiplier", m_SpeedMultiplier); serialize.NumberFixed_Unbounded("current speed", m_CurSpeed); serialize.Bool("facePointAfterMove", m_FacePointAfterMove); + serialize.Bool("pushing", m_Pushing); Serializer(serialize, "long path", m_LongPath.m_Waypoints); Serializer(serialize, "short path", m_ShortPath.m_Waypoints); } virtual void Serialize(ISerializer& serialize) { SerializeCommon(serialize); } virtual void Deserialize(const CParamNode& paramNode, IDeserializer& deserialize) { Init(paramNode); SerializeCommon(deserialize); CmpPtr cmpPathfinder(GetSystemEntity()); if (cmpPathfinder) m_PassClass = cmpPathfinder->GetPassabilityClass(m_PassClassName); } virtual void HandleMessage(const CMessage& msg, bool UNUSED(global)) { switch (msg.GetType()) { case MT_RenderSubmit: { PROFILE("UnitMotion::RenderSubmit"); const CMessageRenderSubmit& msgData = static_cast (msg); RenderSubmit(msgData.collector); break; } case MT_PathResult: { const CMessagePathResult& msgData = static_cast (msg); PathResult(msgData.ticket, msgData.path); break; } case MT_Create: { if (!ENTITY_IS_LOCAL(GetEntityId())) CmpPtr(GetSystemEntity())->Register(this, GetEntityId(), m_FormationController); break; } case MT_Destroy: { if (!ENTITY_IS_LOCAL(GetEntityId())) CmpPtr(GetSystemEntity())->Unregister(GetEntityId()); break; } + case MT_MovementObstructionChanged: + { + CmpPtr cmpObstruction(GetEntityHandle()); + if (cmpObstruction) + m_Pushing = cmpObstruction->GetBlockMovementFlag(false); + break; + } case MT_ValueModification: { const CMessageValueModification& msgData = static_cast (msg); if (msgData.component != L"UnitMotion") break; FALLTHROUGH; } case MT_OwnershipChanged: { OnValueModification(); break; } case MT_Deserialized: { OnValueModification(); if (!ENTITY_IS_LOCAL(GetEntityId())) CmpPtr(GetSystemEntity())->Register(this, GetEntityId(), m_FormationController); break; } } } void UpdateMessageSubscriptions() { bool needRender = m_DebugOverlayEnabled; GetSimContext().GetComponentManager().DynamicSubscriptionNonsync(MT_RenderSubmit, this, needRender); } virtual bool IsMoveRequested() const { return m_MoveRequest.m_Type != MoveRequest::NONE; } virtual fixed GetSpeedMultiplier() const { return m_SpeedMultiplier; } virtual void SetSpeedMultiplier(fixed multiplier) { m_SpeedMultiplier = std::min(multiplier, m_RunMultiplier); m_Speed = m_SpeedMultiplier.Multiply(GetWalkSpeed()); } virtual fixed GetSpeed() const { return m_Speed; } virtual fixed GetWalkSpeed() const { return m_WalkSpeed; } virtual fixed GetRunMultiplier() const { return m_RunMultiplier; } virtual CFixedVector2D EstimateFuturePosition(const fixed dt) const { CmpPtr cmpPosition(GetEntityHandle()); if (!cmpPosition || !cmpPosition->IsInWorld()) return CFixedVector2D(); // TODO: formation members should perhaps try to use the controller's position. CFixedVector2D pos = cmpPosition->GetPosition2D(); entity_angle_t angle = cmpPosition->GetRotation().Y; // Copy the path so we don't change it. WaypointPath shortPath = m_ShortPath; WaypointPath longPath = m_LongPath; PerformMove(dt, cmpPosition->GetTurnRate(), shortPath, longPath, pos, angle); return pos; } virtual pass_class_t GetPassabilityClass() const { return m_PassClass; } virtual std::string GetPassabilityClassName() const { return m_PassClassName; } virtual void SetPassabilityClassName(const std::string& passClassName) { m_PassClassName = passClassName; CmpPtr cmpPathfinder(GetSystemEntity()); if (cmpPathfinder) m_PassClass = cmpPathfinder->GetPassabilityClass(passClassName); } virtual fixed GetCurrentSpeed() const { return m_CurSpeed; } virtual void SetFacePointAfterMove(bool facePointAfterMove) { m_FacePointAfterMove = facePointAfterMove; } virtual bool GetFacePointAfterMove() const { return m_FacePointAfterMove; } virtual void SetDebugOverlay(bool enabled) { m_DebugOverlayEnabled = enabled; UpdateMessageSubscriptions(); } virtual bool MoveToPointRange(entity_pos_t x, entity_pos_t z, entity_pos_t minRange, entity_pos_t maxRange) { return MoveTo(MoveRequest(CFixedVector2D(x, z), minRange, maxRange)); } virtual bool MoveToTargetRange(entity_id_t target, entity_pos_t minRange, entity_pos_t maxRange) { return MoveTo(MoveRequest(target, minRange, maxRange)); } virtual void MoveToFormationOffset(entity_id_t target, entity_pos_t x, entity_pos_t z) { MoveTo(MoveRequest(target, CFixedVector2D(x, z))); } virtual bool IsTargetRangeReachable(entity_id_t target, entity_pos_t minRange, entity_pos_t maxRange); virtual void FaceTowardsPoint(entity_pos_t x, entity_pos_t z); /** * Clears the current MoveRequest - the unit will stop and no longer try and move. * This should never be called from UnitMotion, since MoveToX orders are given * by other components - these components should also decide when to stop. */ virtual void StopMoving() { if (m_FacePointAfterMove) { CmpPtr cmpPosition(GetEntityHandle()); if (cmpPosition && cmpPosition->IsInWorld()) { CFixedVector2D targetPos; if (ComputeTargetPosition(targetPos)) FaceTowardsPointFromPos(cmpPosition->GetPosition2D(), targetPos.X, targetPos.Y); } } m_MoveRequest = MoveRequest(); m_ExpectedPathTicket.clear(); m_LongPath.m_Waypoints.clear(); m_ShortPath.m_Waypoints.clear(); } virtual entity_pos_t GetUnitClearance() const { return m_Clearance; } private: - bool ShouldAvoidMovingUnits() const - { - return !m_FormationController; - } - bool IsFormationMember() const { // TODO: this really shouldn't be what we are checking for. return m_MoveRequest.m_Type == MoveRequest::OFFSET; } bool IsFormationControllerMoving() const { CmpPtr cmpControllerMotion(GetSimContext(), m_MoveRequest.m_Entity); return cmpControllerMotion && cmpControllerMotion->IsMoveRequested(); } entity_id_t GetGroup() const { return IsFormationMember() ? m_MoveRequest.m_Entity : GetEntityId(); } /** * Warns other components that our current movement will likely fail (e.g. we won't be able to reach our target) * This should only be called before the actual movement in a given turn, or units might both move and try to do things * on the same turn, leading to gliding units. */ void MoveFailed() { // Don't notify if we are a formation member in a moving formation - we can occasionally be stuck for a long time // if our current offset is unreachable, but we don't want to end up stuck. // (If the formation controller has stopped moving however, we can safely message). if (IsFormationMember() && IsFormationControllerMoving()) return; CMessageMotionUpdate msg(CMessageMotionUpdate::LIKELY_FAILURE); GetSimContext().GetComponentManager().PostMessage(GetEntityId(), msg); } /** * Warns other components that our current movement is likely over (i.e. we probably reached our destination) * This should only be called before the actual movement in a given turn, or units might both move and try to do things * on the same turn, leading to gliding units. */ void MoveSucceeded() { // Don't notify if we are a formation member in a moving formation - we can occasionally be stuck for a long time // if our current offset is unreachable, but we don't want to end up stuck. // (If the formation controller has stopped moving however, we can safely message). if (IsFormationMember() && IsFormationControllerMoving()) return; CMessageMotionUpdate msg(CMessageMotionUpdate::LIKELY_SUCCESS); GetSimContext().GetComponentManager().PostMessage(GetEntityId(), msg); } /** * Warns other components that our current movement was obstructed (i.e. we failed to move this turn). * This should only be called before the actual movement in a given turn, or units might both move and try to do things * on the same turn, leading to gliding units. */ void MoveObstructed() { // Don't notify if we are a formation member in a moving formation - we can occasionally be stuck for a long time // if our current offset is unreachable, but we don't want to end up stuck. // (If the formation controller has stopped moving however, we can safely message). if (IsFormationMember() && IsFormationControllerMoving()) return; CMessageMotionUpdate msg(m_FailedMovements >= VERY_OBSTRUCTED_THRESHOLD ? CMessageMotionUpdate::VERY_OBSTRUCTED : CMessageMotionUpdate::OBSTRUCTED); GetSimContext().GetComponentManager().PostMessage(GetEntityId(), msg); } /** * Increment the number of failed movements and notify other components if required. * @returns true if the failure was notified, false otherwise. */ bool IncrementFailedMovementsAndMaybeNotify() { m_FailedMovements++; if (m_FailedMovements >= MAX_FAILED_MOVEMENTS) { MoveFailed(); m_FailedMovements = 0; return true; } return false; } /** * If path would take us farther away from the goal than pos currently is, return false, else return true. */ bool RejectFartherPaths(const PathGoal& goal, const WaypointPath& path, const CFixedVector2D& pos) const; bool ShouldAlternatePathfinder() const { return (m_FailedMovements == ALTERNATE_PATH_TYPE_DELAY) || ((MAX_FAILED_MOVEMENTS - ALTERNATE_PATH_TYPE_DELAY) % ALTERNATE_PATH_TYPE_EVERY == 0); } bool InShortPathRange(const PathGoal& goal, const CFixedVector2D& pos) const { return goal.DistanceToPoint(pos) < LONG_PATH_MIN_DIST; } entity_pos_t ShortPathSearchRange() const { u8 multiple = m_FailedMovements < SHORT_PATH_SEARCH_RANGE_INCREASE_DELAY ? 0 : m_FailedMovements - SHORT_PATH_SEARCH_RANGE_INCREASE_DELAY; fixed searchRange = SHORT_PATH_MIN_SEARCH_RANGE + SHORT_PATH_SEARCH_RANGE_INCREMENT * multiple; if (searchRange > SHORT_PATH_MAX_SEARCH_RANGE) searchRange = SHORT_PATH_MAX_SEARCH_RANGE; return searchRange; } /** * Handle the result of an asynchronous path query. */ void PathResult(u32 ticket, const WaypointPath& path); void OnValueModification() { CmpPtr cmpValueModificationManager(GetSystemEntity()); if (!cmpValueModificationManager) return; m_WalkSpeed = cmpValueModificationManager->ApplyModifications(L"UnitMotion/WalkSpeed", m_TemplateWalkSpeed, GetEntityId()); m_RunMultiplier = cmpValueModificationManager->ApplyModifications(L"UnitMotion/RunMultiplier", m_TemplateRunMultiplier, GetEntityId()); // For MT_Deserialize compute m_Speed from the serialized m_SpeedMultiplier. // For MT_ValueModification and MT_OwnershipChanged, adjust m_SpeedMultiplier if needed // (in case then new m_RunMultiplier value is lower than the old). SetSpeedMultiplier(m_SpeedMultiplier); } /** * Check if we are at destination early in the turn, this both lets units react faster * and ensure that distance comparisons are done while units are not being moved * (otherwise they won't be commutative). */ void OnTurnStart(); void PreMove(CCmpUnitMotionManager::MotionState& state); void Move(CCmpUnitMotionManager::MotionState& state, fixed dt); void PostMove(CCmpUnitMotionManager::MotionState& state, fixed dt); /** * Returns true if we are possibly at our destination. * Since the concept of being at destination is dependent on why the move was requested, * UnitMotion can only ever hint about this, hence the conditional tone. */ bool PossiblyAtDestination() const; /** * Process the move the unit will do this turn. * This does not send actually change the position. * @returns true if the move was obstructed. */ bool PerformMove(fixed dt, const fixed& turnRate, WaypointPath& shortPath, WaypointPath& longPath, CFixedVector2D& pos, entity_angle_t& angle) const; /** * Update other components on our speed. * (For performance, this should try to avoid sending messages). */ void UpdateMovementState(entity_pos_t speed); /** * React if our move was obstructed. * @param moved - true if the unit still managed to move. * @returns true if the obstruction required handling, false otherwise. */ bool HandleObstructedMove(bool moved); /** * Returns true if the target position is valid. False otherwise. * (this may indicate that the target is e.g. out of the world/dead). * NB: for code-writing convenience, if we have no target, this returns true. */ bool TargetHasValidPosition(const MoveRequest& moveRequest) const; bool TargetHasValidPosition() const { return TargetHasValidPosition(m_MoveRequest); } /** * Computes the current location of our target entity (plus offset). * Returns false if no target entity or no valid position. */ bool ComputeTargetPosition(CFixedVector2D& out, const MoveRequest& moveRequest) const; bool ComputeTargetPosition(CFixedVector2D& out) const { return ComputeTargetPosition(out, m_MoveRequest); } /** * Attempts to replace the current path with a straight line to the target, * if it's close enough and the route is not obstructed. */ bool TryGoingStraightToTarget(const CFixedVector2D& from); /** * Returns whether our we need to recompute a path to reach our target. */ bool PathingUpdateNeeded(const CFixedVector2D& from) const; /** * Rotate to face towards the target point, given the current pos */ void FaceTowardsPointFromPos(const CFixedVector2D& pos, entity_pos_t x, entity_pos_t z); /** * Returns an appropriate obstruction filter for use with path requests. */ ControlGroupMovementObstructionFilter GetObstructionFilter() const { - return ControlGroupMovementObstructionFilter(ShouldAvoidMovingUnits(), GetGroup()); + return ControlGroupMovementObstructionFilter(false, GetGroup()); } /** * Filter a specific tag on top of the existing control groups. */ - SkipMovingTagAndControlGroupObstructionFilter GetObstructionFilter(const ICmpObstructionManager::tag_t& tag) const + SkipTagAndControlGroupObstructionFilter GetObstructionFilter(const ICmpObstructionManager::tag_t& tag) const { - return SkipMovingTagAndControlGroupObstructionFilter(tag, GetGroup()); + return SkipTagAndControlGroupObstructionFilter(tag, false, GetGroup()); } /** * Decide whether to approximate the given range from a square target as a circle, * rather than as a square. */ bool ShouldTreatTargetAsCircle(entity_pos_t range, entity_pos_t circleRadius) const; /** * Create a PathGoal from a move request. * @returns true if the goal was successfully created. */ bool ComputeGoal(PathGoal& out, const MoveRequest& moveRequest) const; /** * Compute a path to the given goal from the given position. * Might go in a straight line immediately, or might start an asynchronous path request. */ void ComputePathToGoal(const CFixedVector2D& from, const PathGoal& goal); /** * Start an asynchronous long path query. */ void RequestLongPath(const CFixedVector2D& from, const PathGoal& goal); /** * Start an asynchronous short path query. * @param extendRange - if true, extend the search range to at least the distance to the goal. */ void RequestShortPath(const CFixedVector2D& from, const PathGoal& goal, bool extendRange); /** * General handler for MoveTo interface functions. */ bool MoveTo(MoveRequest request); /** * Convert a path into a renderable list of lines */ void RenderPath(const WaypointPath& path, std::vector& lines, CColor color); void RenderSubmit(SceneCollector& collector); }; REGISTER_COMPONENT_TYPE(UnitMotion) bool CCmpUnitMotion::RejectFartherPaths(const PathGoal& goal, const WaypointPath& path, const CFixedVector2D& pos) const { if (path.m_Waypoints.empty()) return false; // Reject the new path if it does not lead us closer to the target's position. if (goal.DistanceToPoint(pos) <= goal.DistanceToPoint(CFixedVector2D(path.m_Waypoints.front().x, path.m_Waypoints.front().z))) return true; return false; } void CCmpUnitMotion::PathResult(u32 ticket, const WaypointPath& path) { // Ignore obsolete path requests if (ticket != m_ExpectedPathTicket.m_Ticket || m_MoveRequest.m_Type == MoveRequest::NONE) return; Ticket::Type ticketType = m_ExpectedPathTicket.m_Type; m_ExpectedPathTicket.clear(); // If we not longer have a position, we won't be able to do much. // Fail in the next Move() call. CmpPtr cmpPosition(GetEntityHandle()); if (!cmpPosition || !cmpPosition->IsInWorld()) return; CFixedVector2D pos = cmpPosition->GetPosition2D(); // Assume all long paths were towards the goal, and assume short paths were if there are no long waypoints. bool pathedTowardsGoal = ticketType == Ticket::LONG_PATH || m_LongPath.m_Waypoints.empty(); // Check if we need to run the short-path hack (warning: tricky control flow). bool shortPathHack = false; if (path.m_Waypoints.empty()) { // No waypoints means pathing failed. If this was a long-path, try the short-path hack. if (!pathedTowardsGoal) return; shortPathHack = ticketType == Ticket::LONG_PATH; } else if (PathGoal goal; pathedTowardsGoal && ComputeGoal(goal, m_MoveRequest) && RejectFartherPaths(goal, path, pos)) { // Reject paths that would take the unit further away from the goal. // This assumes that we prefer being closer 'as the crow flies' to unreachable goals. // This is a hack of sorts around units 'dancing' between two positions (see e.g. #3144), // but never actually failing to move, ergo never actually informing unitAI that it succeeds/fails. // (for short paths, only do so if aiming directly for the goal // as sub-goals may be farther than we are). // If this was a long-path and we no longer have waypoints, try the short-path hack. if (!m_LongPath.m_Waypoints.empty()) return; shortPathHack = ticketType == Ticket::LONG_PATH; } // Short-path hack: if the long-range pathfinder doesn't find an acceptable path, push a fake waypoint at the goal. // This means HandleObstructedMove will use the short-pathfinder to try and reach it, // and that may find a path as the vertex pathfinder is more precise. if (shortPathHack) { // If we're resorting to the short-path hack, the situation is dire. Most likely, the goal is unreachable. // We want to find a path or fail fast. Bump failed movements so the short pathfinder will run at max-range // right away. This is safe from a performance PoV because it can only happen if the target is unreachable to // the long-range pathfinder, which is rare, and since the entity will fail to move if the goal is actually unreachable, // the failed movements will be increased to MAX anyways, so just shortcut. m_FailedMovements = MAX_FAILED_MOVEMENTS - 2; CFixedVector2D targetPos; if (ComputeTargetPosition(targetPos)) m_LongPath.m_Waypoints.emplace_back(Waypoint{ targetPos.X, targetPos.Y }); return; } if (ticketType == Ticket::LONG_PATH) { m_LongPath = path; // Long paths don't properly follow diagonals because of JPS/the grid. Since units now take time turning, // they can actually slow down substantially if they have to do a one navcell diagonal movement, // which is somewhat common at the beginning of a new path. // For that reason, if the first waypoint is really close, check if we can't go directly to the second. if (m_LongPath.m_Waypoints.size() >= 2) { const Waypoint& firstWpt = m_LongPath.m_Waypoints.back(); if (CFixedVector2D(firstWpt.x - pos.X, firstWpt.z - pos.Y).CompareLength(fixed::FromInt(TERRAIN_TILE_SIZE)) <= 0) { CmpPtr cmpPathfinder(GetSystemEntity()); ENSURE(cmpPathfinder); const Waypoint& secondWpt = m_LongPath.m_Waypoints[m_LongPath.m_Waypoints.size() - 2]; if (cmpPathfinder->CheckMovement(GetObstructionFilter(), pos.X, pos.Y, secondWpt.x, secondWpt.z, m_Clearance, m_PassClass)) m_LongPath.m_Waypoints.pop_back(); } } } else m_ShortPath = path; m_FollowKnownImperfectPathCountdown = 0; if (!pathedTowardsGoal) return; // Performance hack: If we were pathing towards the goal and this new path won't put us in range, // it's highly likely that we are going somewhere unreachable. // However, Move() will try to recompute the path every turn, which can be quite slow. // To avoid this, act as if our current path leads us to the correct destination. // NB: for short-paths, the problem might be that the search space is too small // but we'll still follow this path until the en and try again then. // Because we reject farther paths, it works out. if (PathingUpdateNeeded(pos)) { // Inform other components early, as they might have better behaviour than waiting for the path to carry out. // Send OBSTRUCTED at first - moveFailed is likely to trigger path recomputation and we might end up // recomputing too often for nothing. if (!IncrementFailedMovementsAndMaybeNotify()) MoveObstructed(); // We'll automatically recompute a path when this reaches 0, as a way to improve behaviour. // (See D665 - this is needed because the target may be moving, and we should adjust to that). m_FollowKnownImperfectPathCountdown = KNOWN_IMPERFECT_PATH_RESET_COUNTDOWN; } } void CCmpUnitMotion::OnTurnStart() { if (PossiblyAtDestination()) MoveSucceeded(); else if (!TargetHasValidPosition()) { // Scrap waypoints - we don't know where to go. // If the move request remains unchanged and the target again has a valid position later on, // moving will be resumed. // Units may want to move to move to the target's last known position, // but that should be decided by UnitAI (handling MoveFailed), not UnitMotion. m_LongPath.m_Waypoints.clear(); m_ShortPath.m_Waypoints.clear(); MoveFailed(); } } void CCmpUnitMotion::PreMove(CCmpUnitMotionManager::MotionState& state) { + state.ignore = !m_Pushing; + // If we were idle and will still be, no need for an update. state.needUpdate = state.cmpPosition->IsInWorld() && (m_CurSpeed != fixed::Zero() || m_MoveRequest.m_Type != MoveRequest::NONE); + + if (state.ignore) + return; + + state.controlGroup = IsFormationMember() ? m_MoveRequest.m_Entity : INVALID_ENTITY; + + // Update moving flag, this is an internal construct used for pushing, + // so it does not really reflect whether the unit is actually moving or not. + state.isMoving = m_MoveRequest.m_Type != MoveRequest::NONE; + CmpPtr cmpObstruction(GetEntityHandle()); + if (cmpObstruction) + cmpObstruction->SetMovingFlag(state.isMoving); } void CCmpUnitMotion::Move(CCmpUnitMotionManager::MotionState& state, fixed dt) { PROFILE("Move"); // If we're chasing a potentially-moving unit and are currently close // enough to its current position, and we can head in a straight line // to it, then throw away our current path and go straight to it. state.wentStraight = TryGoingStraightToTarget(state.initialPos); state.wasObstructed = PerformMove(dt, state.cmpPosition->GetTurnRate(), m_ShortPath, m_LongPath, state.pos, state.angle); } void CCmpUnitMotion::PostMove(CCmpUnitMotionManager::MotionState& state, fixed dt) { // Update our speed over this turn so that the visual actor shows the correct animation. if (state.pos == state.initialPos) { if (state.angle != state.initialAngle) state.cmpPosition->TurnTo(state.angle); UpdateMovementState(fixed::Zero()); } else { // Update the Position component after our movement (if we actually moved anywhere) - // When moving always set the angle in the direction of the movement. CFixedVector2D offset = state.pos - state.initialPos; - state.angle = atan2_approx(offset.X, offset.Y); + // When moving always set the angle in the direction of the movement, + // if we are not trying to move, assume this is pushing-related movement, + // and maintain the current angle instead. + if (IsMoveRequested()) + state.angle = atan2_approx(offset.X, offset.Y); state.cmpPosition->MoveAndTurnTo(state.pos.X, state.pos.Y, state.angle); // Calculate the mean speed over this past turn. UpdateMovementState(offset.Length() / dt); } if (state.wasObstructed && HandleObstructedMove(state.pos != state.initialPos)) return; else if (!state.wasObstructed && state.pos != state.initialPos) m_FailedMovements = 0; + // If we moved straight, and didn't quite finish the path, reset - we'll update it next turn if still OK. + if (state.wentStraight && !state.wasObstructed) + m_ShortPath.m_Waypoints.clear(); + // We may need to recompute our path sometimes (e.g. if our target moves). // Since we request paths asynchronously anyways, this does not need to be done before moving. if (!state.wentStraight && PathingUpdateNeeded(state.pos)) { PathGoal goal; if (ComputeGoal(goal, m_MoveRequest)) ComputePathToGoal(state.pos, goal); } else if (m_FollowKnownImperfectPathCountdown > 0) --m_FollowKnownImperfectPathCountdown; } bool CCmpUnitMotion::PossiblyAtDestination() const { if (m_MoveRequest.m_Type == MoveRequest::NONE) return false; CmpPtr cmpObstructionManager(GetSystemEntity()); ENSURE(cmpObstructionManager); if (m_MoveRequest.m_Type == MoveRequest::POINT) return cmpObstructionManager->IsInPointRange(GetEntityId(), m_MoveRequest.m_Position.X, m_MoveRequest.m_Position.Y, m_MoveRequest.m_MinRange, m_MoveRequest.m_MaxRange, false); if (m_MoveRequest.m_Type == MoveRequest::ENTITY) return cmpObstructionManager->IsInTargetRange(GetEntityId(), m_MoveRequest.m_Entity, m_MoveRequest.m_MinRange, m_MoveRequest.m_MaxRange, false); if (m_MoveRequest.m_Type == MoveRequest::OFFSET) { CmpPtr cmpControllerMotion(GetSimContext(), m_MoveRequest.m_Entity); if (cmpControllerMotion && cmpControllerMotion->IsMoveRequested()) return false; // In formation, return a match only if we are exactly at the target position. // Otherwise, units can go in an infinite "walzting" loop when the Idle formation timer // reforms them. CFixedVector2D targetPos; ComputeTargetPosition(targetPos); CmpPtr cmpPosition(GetEntityHandle()); return (targetPos-cmpPosition->GetPosition2D()).CompareLength(fixed::Zero()) <= 0; } return false; } bool CCmpUnitMotion::PerformMove(fixed dt, const fixed& turnRate, WaypointPath& shortPath, WaypointPath& longPath, CFixedVector2D& pos, entity_angle_t& angle) const { // If there are no waypoint, behave as though we were obstructed and let HandleObstructedMove handle it. if (shortPath.m_Waypoints.empty() && longPath.m_Waypoints.empty()) return true; // Wrap the angle to (-Pi, Pi]. while (angle > entity_angle_t::Pi()) angle -= entity_angle_t::Pi() * 2; while (angle < -entity_angle_t::Pi()) angle += entity_angle_t::Pi() * 2; // TODO: there's some asymmetry here when units look at other // units' positions - the result will depend on the order of execution. // Maybe we should split the updates into multiple phases to minimise // that problem. CmpPtr cmpPathfinder(GetSystemEntity()); ENSURE(cmpPathfinder); fixed basicSpeed = m_Speed; // If in formation, run to keep up; otherwise just walk. if (IsFormationMember()) basicSpeed = m_Speed.Multiply(m_RunMultiplier); // Find the speed factor of the underlying terrain. // (We only care about the tile we start on - it doesn't matter if we're moving // partially onto a much slower/faster tile). // TODO: Terrain-dependent speeds are not currently supported. fixed terrainSpeed = fixed::FromInt(1); fixed maxSpeed = basicSpeed.Multiply(terrainSpeed); fixed timeLeft = dt; fixed zero = fixed::Zero(); ICmpObstructionManager::tag_t specificIgnore; if (m_MoveRequest.m_Type == MoveRequest::ENTITY) { CmpPtr cmpTargetObstruction(GetSimContext(), m_MoveRequest.m_Entity); if (cmpTargetObstruction) specificIgnore = cmpTargetObstruction->GetObstruction(); } while (timeLeft > zero) { // If we ran out of path, we have to stop. if (shortPath.m_Waypoints.empty() && longPath.m_Waypoints.empty()) break; CFixedVector2D target; if (shortPath.m_Waypoints.empty()) target = CFixedVector2D(longPath.m_Waypoints.back().x, longPath.m_Waypoints.back().z); else target = CFixedVector2D(shortPath.m_Waypoints.back().x, shortPath.m_Waypoints.back().z); CFixedVector2D offset = target - pos; if (turnRate > zero && !offset.IsZero()) { fixed maxRotation = turnRate.Multiply(timeLeft); fixed angleDiff = angle - atan2_approx(offset.X, offset.Y); if (angleDiff != zero) { fixed absoluteAngleDiff = angleDiff.Absolute(); if (absoluteAngleDiff > entity_angle_t::Pi()) absoluteAngleDiff = entity_angle_t::Pi() * 2 - absoluteAngleDiff; // Figure out whether rotating will increase or decrease the angle, and how far we need to rotate in that direction. int direction = (entity_angle_t::Zero() < angleDiff && angleDiff <= entity_angle_t::Pi()) || angleDiff < -entity_angle_t::Pi() ? -1 : 1; // Can't rotate far enough, just rotate in the correct direction. if (absoluteAngleDiff > maxRotation) { angle += maxRotation * direction; if (angle * direction > entity_angle_t::Pi()) angle -= entity_angle_t::Pi() * 2 * direction; break; } // Rotate towards the next waypoint and continue moving. angle = atan2_approx(offset.X, offset.Y); // Give some 'free' rotation for angles below 0.5 radians. timeLeft = (std::min(maxRotation, maxRotation - absoluteAngleDiff + fixed::FromInt(1)/2)) / turnRate; } } // Work out how far we can travel in timeLeft. fixed maxdist = maxSpeed.Multiply(timeLeft); // If the target is close, we can move there directly. fixed offsetLength = offset.Length(); if (offsetLength <= maxdist) { if (cmpPathfinder->CheckMovement(GetObstructionFilter(specificIgnore), pos.X, pos.Y, target.X, target.Y, m_Clearance, m_PassClass)) { pos = target; // Spend the rest of the time heading towards the next waypoint. timeLeft = (maxdist - offsetLength) / maxSpeed; if (shortPath.m_Waypoints.empty()) longPath.m_Waypoints.pop_back(); else shortPath.m_Waypoints.pop_back(); continue; } else { // Error - path was obstructed. return true; } } else { // Not close enough, so just move in the right direction. offset.Normalize(maxdist); target = pos + offset; if (cmpPathfinder->CheckMovement(GetObstructionFilter(specificIgnore), pos.X, pos.Y, target.X, target.Y, m_Clearance, m_PassClass)) pos = target; else return true; break; } } return false; } void CCmpUnitMotion::UpdateMovementState(entity_pos_t speed) { - CmpPtr cmpObstruction(GetEntityHandle()); CmpPtr cmpVisual(GetEntityHandle()); - // Idle this turn. - if (speed == fixed::Zero()) + if (cmpVisual) { - // Update moving flag if we moved last turn. - if (m_CurSpeed > fixed::Zero() && cmpObstruction) - cmpObstruction->SetMovingFlag(false); - if (cmpVisual) + if (speed == fixed::Zero()) cmpVisual->SelectMovementAnimation("idle", fixed::FromInt(1)); - } - // Moved this turn - else - { - // Update moving flag if we didn't move last turn. - if (m_CurSpeed == fixed::Zero() && cmpObstruction) - cmpObstruction->SetMovingFlag(true); - if (cmpVisual) + else cmpVisual->SelectMovementAnimation(speed > (m_WalkSpeed / 2).Multiply(m_RunMultiplier + fixed::FromInt(1)) ? "run" : "walk", speed); } m_CurSpeed = speed; } bool CCmpUnitMotion::HandleObstructedMove(bool moved) { CmpPtr cmpPosition(GetEntityHandle()); if (!cmpPosition || !cmpPosition->IsInWorld()) return false; // We failed to move, inform other components as they might handle it. // (don't send messages on the first failure, as that would be too noisy). // Also don't increment above the initial MoveObstructed message if we actually manage to move a little. if (!moved || m_FailedMovements < 2) { if (!IncrementFailedMovementsAndMaybeNotify() && m_FailedMovements >= 2) MoveObstructed(); } PathGoal goal; if (!ComputeGoal(goal, m_MoveRequest)) return false; // At this point we have a position in the world since ComputeGoal checked for that. CFixedVector2D pos = cmpPosition->GetPosition2D(); // Assume that we are merely obstructed and the long path is salvageable, so try going around the obstruction. // This could be a separate function, but it doesn't really make sense to call it outside of here, and I can't find a name. // I use an IIFE to have nice 'return' semantics still. if ([&]() -> bool { // If the goal is close enough, we should ignore any remaining long waypoint and just // short path there directly, as that improves behaviour in general - see D2095). if (InShortPathRange(goal, pos)) return false; // Delete the next waypoint if it's reasonably close, // because it might be blocked by units and thus unreachable. // NB: this number is tricky. Make it too high, and units start going down dead ends, which looks odd (#5795) // Make it too low, and they might get stuck behind other obstructed entities. // It also has performance implications because it calls the short-pathfinder. fixed skipbeyond = std::max(ShortPathSearchRange() / 3, fixed::FromInt(TERRAIN_TILE_SIZE*2)); if (m_LongPath.m_Waypoints.size() > 1 && (pos - CFixedVector2D(m_LongPath.m_Waypoints.back().x, m_LongPath.m_Waypoints.back().z)).CompareLength(skipbeyond) < 0) { m_LongPath.m_Waypoints.pop_back(); } else if (ShouldAlternatePathfinder()) { // Recompute the whole thing occasionally, in case we got stuck in a dead end from removing long waypoints. RequestLongPath(pos, goal); return true; } if (m_LongPath.m_Waypoints.empty()) return false; // Compute a short path in the general vicinity of the next waypoint, to help pathfinding in crowds. // The goal here is to manage to move in the general direction of our target, not to be super accurate. fixed radius = Clamp(skipbeyond/3, fixed::FromInt(TERRAIN_TILE_SIZE), fixed::FromInt(TERRAIN_TILE_SIZE*3)); PathGoal subgoal = { PathGoal::CIRCLE, m_LongPath.m_Waypoints.back().x, m_LongPath.m_Waypoints.back().z, radius }; RequestShortPath(pos, subgoal, false); return true; }()) return true; // If we couldn't use a workaround, try recomputing the entire path. ComputePathToGoal(pos, goal); return true; } bool CCmpUnitMotion::TargetHasValidPosition(const MoveRequest& moveRequest) const { if (moveRequest.m_Type != MoveRequest::ENTITY) return true; CmpPtr cmpPosition(GetSimContext(), moveRequest.m_Entity); return cmpPosition && cmpPosition->IsInWorld(); } bool CCmpUnitMotion::ComputeTargetPosition(CFixedVector2D& out, const MoveRequest& moveRequest) const { if (moveRequest.m_Type == MoveRequest::POINT) { out = moveRequest.m_Position; return true; } CmpPtr cmpTargetPosition(GetSimContext(), moveRequest.m_Entity); if (!cmpTargetPosition || !cmpTargetPosition->IsInWorld()) return false; if (moveRequest.m_Type == MoveRequest::OFFSET) { // There is an offset, so compute it relative to orientation entity_angle_t angle = cmpTargetPosition->GetRotation().Y; CFixedVector2D offset = moveRequest.GetOffset().Rotate(angle); out = cmpTargetPosition->GetPosition2D() + offset; } else { out = cmpTargetPosition->GetPosition2D(); // Because units move one-at-a-time and pathing is asynchronous, we need to account for target movement, // if we are computing this during the MT_Motion* part of the turn. // If our entity ID is lower, we move first, and so we need to add a predicted movement to compute a path for next turn. // If our entity ID is higher, the target has already moved, so we can just use the position directly. // TODO: This does not really aim many turns in advance, with orthogonal trajectories it probably should. CmpPtr cmpUnitMotion(GetSimContext(), moveRequest.m_Entity); CmpPtr cmpUnitMotionManager(GetSystemEntity()); bool needInterpolation = cmpUnitMotion && cmpUnitMotion->IsMoveRequested() && cmpUnitMotionManager->ComputingMotion(); if (needInterpolation && GetEntityId() < moveRequest.m_Entity) { // Add predicted movement. CFixedVector2D tempPos = out + (out - cmpTargetPosition->GetPreviousPosition2D()); CmpPtr cmpPosition(GetEntityHandle()); if (!cmpPosition || !cmpPosition->IsInWorld()) return true; // Still return true since we don't need a position for the target to have one. // Fleeing fix: if we anticipate the target to go through us, we'll suddenly turn around, which is bad. // Pretend that the target is still behind us in those cases. if (m_MoveRequest.m_MinRange > fixed::Zero()) { if ((out - cmpPosition->GetPosition2D()).RelativeOrientation(tempPos - cmpPosition->GetPosition2D()) >= 0) out = tempPos; } else out = tempPos; } else if (needInterpolation && GetEntityId() > moveRequest.m_Entity) { CmpPtr cmpPosition(GetEntityHandle()); if (!cmpPosition || !cmpPosition->IsInWorld()) return true; // Still return true since we don't need a position for the target to have one. // Fleeing fix: opposite to above, check if our target has travelled through us already this turn. CFixedVector2D tempPos = out - (out - cmpTargetPosition->GetPreviousPosition2D()); if (m_MoveRequest.m_MinRange > fixed::Zero() && (out - cmpPosition->GetPosition2D()).RelativeOrientation(tempPos - cmpPosition->GetPosition2D()) < 0) out = tempPos; } } return true; } bool CCmpUnitMotion::TryGoingStraightToTarget(const CFixedVector2D& from) { + // Assume if we have short paths we want to follow them. + // Exception: offset movement (formations) generally have very short deltas + // and to look good we need them to walk-straight most of the time. + if (!IsFormationMember() && !m_ShortPath.m_Waypoints.empty()) + return false; + CFixedVector2D targetPos; if (!ComputeTargetPosition(targetPos)) return false; CmpPtr cmpPathfinder(GetSystemEntity()); if (!cmpPathfinder) return false; // Move the goal to match the target entity's new position PathGoal goal; if (!ComputeGoal(goal, m_MoveRequest)) return false; goal.x = targetPos.X; goal.z = targetPos.Y; // (we ignore changes to the target's rotation, since only buildings are // square and buildings don't move) // Find the point on the goal shape that we should head towards CFixedVector2D goalPos = goal.NearestPointOnGoal(from); // Fail if the target is too far away if ((goalPos - from).CompareLength(DIRECT_PATH_RANGE) > 0) return false; // Check if there's any collisions on that route. // For entity goals, skip only the specific obstruction tag or with e.g. walls we might ignore too many entities. ICmpObstructionManager::tag_t specificIgnore; if (m_MoveRequest.m_Type == MoveRequest::ENTITY) { CmpPtr cmpTargetObstruction(GetSimContext(), m_MoveRequest.m_Entity); if (cmpTargetObstruction) specificIgnore = cmpTargetObstruction->GetObstruction(); } + // Check movement against units - we want to use the short pathfinder to walk around those if needed. if (specificIgnore.valid()) { - if (!cmpPathfinder->CheckMovement(SkipTagObstructionFilter(specificIgnore), from.X, from.Y, goalPos.X, goalPos.Y, m_Clearance, m_PassClass)) + if (!cmpPathfinder->CheckMovement(GetObstructionFilter(specificIgnore), from.X, from.Y, goalPos.X, goalPos.Y, m_Clearance, m_PassClass)) return false; } else if (!cmpPathfinder->CheckMovement(GetObstructionFilter(), from.X, from.Y, goalPos.X, goalPos.Y, m_Clearance, m_PassClass)) return false; - // That route is okay, so update our path m_LongPath.m_Waypoints.clear(); m_ShortPath.m_Waypoints.clear(); m_ShortPath.m_Waypoints.emplace_back(Waypoint{ goalPos.X, goalPos.Y }); return true; } bool CCmpUnitMotion::PathingUpdateNeeded(const CFixedVector2D& from) const { if (m_MoveRequest.m_Type == MoveRequest::NONE) return false; CFixedVector2D targetPos; if (!ComputeTargetPosition(targetPos)) return false; if (m_FollowKnownImperfectPathCountdown > 0 && (!m_LongPath.m_Waypoints.empty() || !m_ShortPath.m_Waypoints.empty())) return false; if (PossiblyAtDestination()) return false; // Get the obstruction shape and translate it where we estimate the target to be. ICmpObstructionManager::ObstructionSquare estimatedTargetShape; if (m_MoveRequest.m_Type == MoveRequest::ENTITY) { CmpPtr cmpTargetObstruction(GetSimContext(), m_MoveRequest.m_Entity); if (cmpTargetObstruction) cmpTargetObstruction->GetObstructionSquare(estimatedTargetShape); } estimatedTargetShape.x = targetPos.X; estimatedTargetShape.z = targetPos.Y; CmpPtr cmpObstruction(GetEntityHandle()); ICmpObstructionManager::ObstructionSquare shape; if (cmpObstruction) cmpObstruction->GetObstructionSquare(shape); // Translate our own obstruction shape to our last waypoint or our current position, lacking that. if (m_LongPath.m_Waypoints.empty() && m_ShortPath.m_Waypoints.empty()) { shape.x = from.X; shape.z = from.Y; } else { const Waypoint& lastWaypoint = m_LongPath.m_Waypoints.empty() ? m_ShortPath.m_Waypoints.front() : m_LongPath.m_Waypoints.front(); shape.x = lastWaypoint.x; shape.z = lastWaypoint.z; } CmpPtr cmpObstructionManager(GetSystemEntity()); ENSURE(cmpObstructionManager); // Increase the ranges with distance, to avoid recomputing every turn against units that are moving and far-away for example. entity_pos_t distance = (from - CFixedVector2D(estimatedTargetShape.x, estimatedTargetShape.z)).Length(); // TODO: it could be worth computing this based on time to collision instead of linear distance. entity_pos_t minRange = std::max(m_MoveRequest.m_MinRange - distance / TARGET_UNCERTAINTY_MULTIPLIER, entity_pos_t::Zero()); entity_pos_t maxRange = m_MoveRequest.m_MaxRange < entity_pos_t::Zero() ? m_MoveRequest.m_MaxRange : m_MoveRequest.m_MaxRange + distance / TARGET_UNCERTAINTY_MULTIPLIER; if (cmpObstructionManager->AreShapesInRange(shape, estimatedTargetShape, minRange, maxRange, false)) return false; return true; } void CCmpUnitMotion::FaceTowardsPoint(entity_pos_t x, entity_pos_t z) { CmpPtr cmpPosition(GetEntityHandle()); if (!cmpPosition || !cmpPosition->IsInWorld()) return; CFixedVector2D pos = cmpPosition->GetPosition2D(); FaceTowardsPointFromPos(pos, x, z); } void CCmpUnitMotion::FaceTowardsPointFromPos(const CFixedVector2D& pos, entity_pos_t x, entity_pos_t z) { CFixedVector2D target(x, z); CFixedVector2D offset = target - pos; if (!offset.IsZero()) { entity_angle_t angle = atan2_approx(offset.X, offset.Y); CmpPtr cmpPosition(GetEntityHandle()); if (!cmpPosition) return; cmpPosition->TurnTo(angle); } } // The pathfinder cannot go to "rounded rectangles" goals, which are what happens with square targets and a non-null range. // Depending on what the best approximation is, we either pretend the target is a circle or a square. // One needs to be careful that the approximated geometry will be in the range. bool CCmpUnitMotion::ShouldTreatTargetAsCircle(entity_pos_t range, entity_pos_t circleRadius) const { // Given a square, plus a target range we should reach, the shape at that distance // is a round-cornered square which we can approximate as either a circle or as a square. // Previously, we used the shape that minimized the worst-case error. // However that is unsage in some situations. So let's be less clever and // just check if our range is at least three times bigger than the circleradius return (range > circleRadius*3); } bool CCmpUnitMotion::ComputeGoal(PathGoal& out, const MoveRequest& moveRequest) const { if (moveRequest.m_Type == MoveRequest::NONE) return false; CmpPtr cmpPosition(GetEntityHandle()); if (!cmpPosition || !cmpPosition->IsInWorld()) return false; CFixedVector2D pos = cmpPosition->GetPosition2D(); CFixedVector2D targetPosition; if (!ComputeTargetPosition(targetPosition, moveRequest)) return false; ICmpObstructionManager::ObstructionSquare targetObstruction; if (moveRequest.m_Type == MoveRequest::ENTITY) { CmpPtr cmpTargetObstruction(GetSimContext(), moveRequest.m_Entity); if (cmpTargetObstruction) cmpTargetObstruction->GetObstructionSquare(targetObstruction); } targetObstruction.x = targetPosition.X; targetObstruction.z = targetPosition.Y; ICmpObstructionManager::ObstructionSquare obstruction; CmpPtr cmpObstruction(GetEntityHandle()); if (cmpObstruction) cmpObstruction->GetObstructionSquare(obstruction); else { obstruction.x = pos.X; obstruction.z = pos.Y; } CmpPtr cmpObstructionManager(GetSystemEntity()); ENSURE(cmpObstructionManager); entity_pos_t distance = cmpObstructionManager->DistanceBetweenShapes(obstruction, targetObstruction); out.x = targetObstruction.x; out.z = targetObstruction.z; out.hw = targetObstruction.hw; out.hh = targetObstruction.hh; out.u = targetObstruction.u; out.v = targetObstruction.v; if (moveRequest.m_MinRange > fixed::Zero() || moveRequest.m_MaxRange > fixed::Zero() || targetObstruction.hw > fixed::Zero()) out.type = PathGoal::SQUARE; else { out.type = PathGoal::POINT; return true; } entity_pos_t circleRadius = CFixedVector2D(targetObstruction.hw, targetObstruction.hh).Length(); // TODO: because we cannot move to rounded rectangles, we have to make conservative approximations. // This means we might end up in a situation where cons(max-range) < min range < max range < cons(min-range) // When going outside of the min-range or inside the max-range, the unit will still go through the correct range // but if it moves fast enough, this might not be picked up by PossiblyAtDestination(). // Fixing this involves moving to rounded rectangles, or checking more often in PerformMove(). // In the meantime, one should avoid that 'Speed over a turn' > MaxRange - MinRange, in case where // min-range is not 0 and max-range is not infinity. if (distance < moveRequest.m_MinRange) { // Distance checks are nearest edge to nearest edge, so we need to account for our clearance // and we must make sure diagonals also fit so multiply by slightly more than sqrt(2) entity_pos_t goalDistance = moveRequest.m_MinRange + m_Clearance * 3 / 2; if (ShouldTreatTargetAsCircle(moveRequest.m_MinRange, circleRadius)) { // We are safely away from the obstruction itself if we are away from the circumscribing circle out.type = PathGoal::INVERTED_CIRCLE; out.hw = circleRadius + goalDistance; } else { out.type = PathGoal::INVERTED_SQUARE; out.hw = targetObstruction.hw + goalDistance; out.hh = targetObstruction.hh + goalDistance; } } else if (moveRequest.m_MaxRange >= fixed::Zero() && distance > moveRequest.m_MaxRange) { if (ShouldTreatTargetAsCircle(moveRequest.m_MaxRange, circleRadius)) { entity_pos_t goalDistance = moveRequest.m_MaxRange; // We must go in-range of the inscribed circle, not the circumscribing circle. circleRadius = std::min(targetObstruction.hw, targetObstruction.hh); out.type = PathGoal::CIRCLE; out.hw = circleRadius + goalDistance; } else { // The target is large relative to our range, so treat it as a square and // get close enough that the diagonals come within range entity_pos_t goalDistance = moveRequest.m_MaxRange * 2 / 3; // multiply by slightly less than 1/sqrt(2) out.type = PathGoal::SQUARE; entity_pos_t delta = std::max(goalDistance, m_Clearance + entity_pos_t::FromInt(TERRAIN_TILE_SIZE)/16); // ensure it's far enough to not intersect the building itself out.hw = targetObstruction.hw + delta; out.hh = targetObstruction.hh + delta; } } // Do nothing in particular in case we are already in range. return true; } void CCmpUnitMotion::ComputePathToGoal(const CFixedVector2D& from, const PathGoal& goal) { #if DISABLE_PATHFINDER { CmpPtr cmpPathfinder (GetSimContext(), SYSTEM_ENTITY); CFixedVector2D goalPos = m_FinalGoal.NearestPointOnGoal(from); m_LongPath.m_Waypoints.clear(); m_ShortPath.m_Waypoints.clear(); m_ShortPath.m_Waypoints.emplace_back(Waypoint{ goalPos.X, goalPos.Y }); return; } #endif // If the target is close and we can reach it in a straight line, // then we'll just go along the straight line instead of computing a path. if (!ShouldAlternatePathfinder() && TryGoingStraightToTarget(from)) return; // Otherwise we need to compute a path. // If it's close then just do a short path, not a long path // TODO: If it's close on the opposite side of a river then we really // need a long path, so we shouldn't simply check linear distance // the check is arbitrary but should be a reasonably small distance. // We want to occasionally compute a long path if we're computing short-paths, because the short path domain // is bounded and thus it can't around very large static obstacles. // Likewise, we want to compile a short-path occasionally when the target is far because we might be stuck // on a navcell surrounded by impassable navcells, but the short-pathfinder could move us out of there. bool shortPath = InShortPathRange(goal, from); if (ShouldAlternatePathfinder()) shortPath = !shortPath; if (shortPath) { m_LongPath.m_Waypoints.clear(); // Extend the range so that our first path is probably valid. RequestShortPath(from, goal, true); } else { m_ShortPath.m_Waypoints.clear(); RequestLongPath(from, goal); } } void CCmpUnitMotion::RequestLongPath(const CFixedVector2D& from, const PathGoal& goal) { CmpPtr cmpPathfinder(GetSystemEntity()); if (!cmpPathfinder) return; // this is by how much our waypoints will be apart at most. // this value here seems sensible enough. PathGoal improvedGoal = goal; improvedGoal.maxdist = SHORT_PATH_MIN_SEARCH_RANGE - entity_pos_t::FromInt(1); cmpPathfinder->SetDebugPath(from.X, from.Y, improvedGoal, m_PassClass); m_ExpectedPathTicket.m_Type = Ticket::LONG_PATH; m_ExpectedPathTicket.m_Ticket = cmpPathfinder->ComputePathAsync(from.X, from.Y, improvedGoal, m_PassClass, GetEntityId()); } void CCmpUnitMotion::RequestShortPath(const CFixedVector2D &from, const PathGoal& goal, bool extendRange) { CmpPtr cmpPathfinder(GetSystemEntity()); if (!cmpPathfinder) return; entity_pos_t searchRange = ShortPathSearchRange(); if (extendRange) { CFixedVector2D dist(from.X - goal.x, from.Y - goal.z); if (dist.CompareLength(searchRange - entity_pos_t::FromInt(1)) >= 0) { searchRange = dist.Length() + fixed::FromInt(1); if (searchRange > SHORT_PATH_MAX_SEARCH_RANGE) searchRange = SHORT_PATH_MAX_SEARCH_RANGE; } } m_ExpectedPathTicket.m_Type = Ticket::SHORT_PATH; m_ExpectedPathTicket.m_Ticket = cmpPathfinder->ComputeShortPathAsync(from.X, from.Y, m_Clearance, searchRange, goal, m_PassClass, true, GetGroup(), GetEntityId()); } bool CCmpUnitMotion::MoveTo(MoveRequest request) { PROFILE("MoveTo"); if (request.m_MinRange == request.m_MaxRange && !request.m_MinRange.IsZero()) LOGWARNING("MaxRange must be larger than MinRange; See CCmpUnitMotion.cpp for more information"); CmpPtr cmpPosition(GetEntityHandle()); if (!cmpPosition || !cmpPosition->IsInWorld()) return false; PathGoal goal; if (!ComputeGoal(goal, request)) return false; m_MoveRequest = request; m_FailedMovements = 0; m_FollowKnownImperfectPathCountdown = 0; ComputePathToGoal(cmpPosition->GetPosition2D(), goal); return true; } bool CCmpUnitMotion::IsTargetRangeReachable(entity_id_t target, entity_pos_t minRange, entity_pos_t maxRange) { CmpPtr cmpPosition(GetEntityHandle()); if (!cmpPosition || !cmpPosition->IsInWorld()) return false; MoveRequest request(target, minRange, maxRange); PathGoal goal; if (!ComputeGoal(goal, request)) return false; CmpPtr cmpPathfinder(GetSimContext(), SYSTEM_ENTITY); CFixedVector2D pos = cmpPosition->GetPosition2D(); return cmpPathfinder->IsGoalReachable(pos.X, pos.Y, goal, m_PassClass); } void CCmpUnitMotion::RenderPath(const WaypointPath& path, std::vector& lines, CColor color) { bool floating = false; CmpPtr cmpPosition(GetEntityHandle()); if (cmpPosition) floating = cmpPosition->CanFloat(); lines.clear(); std::vector waypointCoords; for (size_t i = 0; i < path.m_Waypoints.size(); ++i) { float x = path.m_Waypoints[i].x.ToFloat(); float z = path.m_Waypoints[i].z.ToFloat(); waypointCoords.push_back(x); waypointCoords.push_back(z); lines.push_back(SOverlayLine()); lines.back().m_Color = color; SimRender::ConstructSquareOnGround(GetSimContext(), x, z, 1.0f, 1.0f, 0.0f, lines.back(), floating); } float x = cmpPosition->GetPosition2D().X.ToFloat(); float z = cmpPosition->GetPosition2D().Y.ToFloat(); waypointCoords.push_back(x); waypointCoords.push_back(z); lines.push_back(SOverlayLine()); lines.back().m_Color = color; SimRender::ConstructLineOnGround(GetSimContext(), waypointCoords, lines.back(), floating); } void CCmpUnitMotion::RenderSubmit(SceneCollector& collector) { if (!m_DebugOverlayEnabled) return; RenderPath(m_LongPath, m_DebugOverlayLongPathLines, OVERLAY_COLOR_LONG_PATH); RenderPath(m_ShortPath, m_DebugOverlayShortPathLines, OVERLAY_COLOR_SHORT_PATH); for (size_t i = 0; i < m_DebugOverlayLongPathLines.size(); ++i) collector.Submit(&m_DebugOverlayLongPathLines[i]); for (size_t i = 0; i < m_DebugOverlayShortPathLines.size(); ++i) collector.Submit(&m_DebugOverlayShortPathLines[i]); } #endif // INCLUDED_CCMPUNITMOTION Index: ps/trunk/source/simulation2/components/CCmpUnitMotionManager.h =================================================================== --- ps/trunk/source/simulation2/components/CCmpUnitMotionManager.h (revision 25181) +++ ps/trunk/source/simulation2/components/CCmpUnitMotionManager.h (revision 25182) @@ -1,142 +1,181 @@ /* Copyright (C) 2021 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_CCMPUNITMOTIONMANAGER #define INCLUDED_CCMPUNITMOTIONMANAGER #include "simulation2/system/Component.h" #include "ICmpUnitMotionManager.h" #include "simulation2/MessageTypes.h" +#include "simulation2/components/ICmpTerrain.h" +#include "simulation2/helpers/Grid.h" #include "simulation2/system/EntityMap.h" class CCmpUnitMotion; class CCmpUnitMotionManager : public ICmpUnitMotionManager { public: static void ClassInit(CComponentManager& componentManager) { + componentManager.SubscribeToMessageType(MT_TerrainChanged); componentManager.SubscribeToMessageType(MT_TurnStart); componentManager.SubscribeToMessageType(MT_Update_Final); componentManager.SubscribeToMessageType(MT_Update_MotionUnit); componentManager.SubscribeToMessageType(MT_Update_MotionFormation); } DEFAULT_COMPONENT_ALLOCATOR(UnitMotionManager) // Persisted state for each unit. struct MotionState { + MotionState(CmpPtr cmpPos, CCmpUnitMotion* cmpMotion); + // Component references - these must be kept alive for the duration of motion. // NB: this is generally not something one should do, but because of the tight coupling here it's doable. CmpPtr cmpPosition; CCmpUnitMotion* cmpUnitMotion; // Position before units start moving CFixedVector2D initialPos; // Transient position during the movement. CFixedVector2D pos; + // Accumulated "pushing" from nearby units. + CFixedVector2D push; + fixed initialAngle; fixed angle; + // Used for formations - units with the same control group won't push at a distance. + // (this is required because formations may be tight and large units may end up never settling. + entity_id_t controlGroup = INVALID_ENTITY; + + // Meta-flag -> this entity won't push nor be pushed. + // (used for entities that have their obstruction disabled). + bool ignore = false; + // If true, the entity needs to be handled during movement. - bool needUpdate; + bool needUpdate = false; - // 'Leak' from UnitMotion. - bool wentStraight; - bool wasObstructed; + bool wentStraight = false; + bool wasObstructed = false; + + // Clone of the obstruction manager flag for efficiency + bool isMoving = false; }; EntityMap m_Units; EntityMap m_FormationControllers; - // Temporary vector, reconstructed each turn (stored here to avoid memory reallocations). - std::vector::iterator> m_MovingUnits; + // The vectors are cleared each frame. + Grid::iterator>> m_MovingUnits; bool m_ComputingMotion; static std::string GetSchema() { return ""; } virtual void Init(const CParamNode& UNUSED(paramNode)) { - m_MovingUnits.reserve(40); } virtual void Deinit() { } virtual void Serialize(ISerializer& UNUSED(serialize)) { } virtual void Deserialize(const CParamNode& paramNode, IDeserializer& UNUSED(deserialize)) { Init(paramNode); + ResetSubdivisions(); } virtual void HandleMessage(const CMessage& msg, bool UNUSED(global)) { switch (msg.GetType()) { + case MT_TerrainChanged: + { + CmpPtr cmpTerrain(GetSystemEntity()); + if (cmpTerrain->GetVerticesPerSide() != m_MovingUnits.width()) + ResetSubdivisions(); + break; + } case MT_TurnStart: { OnTurnStart(); break; } case MT_Update_MotionFormation: { fixed dt = static_cast(msg).turnLength; m_ComputingMotion = true; MoveFormations(dt); m_ComputingMotion = false; break; } case MT_Update_MotionUnit: { fixed dt = static_cast(msg).turnLength; m_ComputingMotion = true; MoveUnits(dt); m_ComputingMotion = false; break; } } } virtual void Register(CCmpUnitMotion* component, entity_id_t ent, bool formationController); virtual void Unregister(entity_id_t ent); virtual bool ComputingMotion() const { return m_ComputingMotion; } +private: + void ResetSubdivisions(); void OnTurnStart(); void MoveUnits(fixed dt); void MoveFormations(fixed dt); void Move(EntityMap& ents, fixed dt); + + void Push(EntityMap::value_type& a, EntityMap::value_type& b, fixed dt); }; +void CCmpUnitMotionManager::ResetSubdivisions() +{ + CmpPtr cmpTerrain(GetSystemEntity()); + if (!cmpTerrain) + return; + + size_t size = cmpTerrain->GetVerticesPerSide() - 1; + m_MovingUnits.resize(size * TERRAIN_TILE_SIZE / 20 + 1, size * TERRAIN_TILE_SIZE / 20 + 1); +} + REGISTER_COMPONENT_TYPE(UnitMotionManager) #endif // INCLUDED_CCMPUNITMOTIONMANAGER Index: ps/trunk/source/simulation2/components/CCmpUnitMotion_System.cpp =================================================================== --- ps/trunk/source/simulation2/components/CCmpUnitMotion_System.cpp (revision 25181) +++ ps/trunk/source/simulation2/components/CCmpUnitMotion_System.cpp (revision 25182) @@ -1,101 +1,289 @@ /* Copyright (C) 2021 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 "CCmpUnitMotion.h" #include "CCmpUnitMotionManager.h" +#include "maths/MathUtil.h" #include "ps/CLogger.h" #include "ps/Profile.h" +#include + // NB: this TU contains the CCmpUnitMotion/CCmpUnitMotionManager couple. // In practice, UnitMotionManager functions need access to the full implementation of UnitMotion, // but UnitMotion needs access to MotionState (defined in UnitMotionManager). // To avoid inclusion issues, implementation of UnitMotionManager that uses UnitMotion is here. +namespace { + /** + * Units push only within their own grid square. This is the size of each square (in arbitrary units). + * TODO: check other values. + */ + static const int PUSHING_GRID_SIZE = 20; + + /** + * Pushing is ignored if the combined push force has lower magnitude than this. + */ + static const entity_pos_t MINIMAL_PUSHING = entity_pos_t::FromInt(1)/10; + + /** + * When moving, units extert a pushing influence at a greater distance. + */ + static const entity_pos_t PUSHING_MOVING_INFLUENCE_EXTENSION = entity_pos_t::FromInt(1); + + /** + * Arbitrary constant used to reduce pushing to levels that won't break physics for our turn length. + */ + static const int PUSHING_REDUCTION_FACTOR = 2; +} + +CCmpUnitMotionManager::MotionState::MotionState(CmpPtr cmpPos, CCmpUnitMotion* cmpMotion) + : cmpPosition(cmpPos), cmpUnitMotion(cmpMotion) +{ +} + void CCmpUnitMotionManager::Register(CCmpUnitMotion* component, entity_id_t ent, bool formationController) { - MotionState state = { - CmpPtr(GetSimContext(), ent), - component, - CFixedVector2D(), - CFixedVector2D(), - fixed::Zero(), - fixed::Zero(), - false, - false - }; + MotionState state(CmpPtr(GetSimContext(), ent), component); if (!formationController) m_Units.insert(ent, state); else m_FormationControllers.insert(ent, state); } void CCmpUnitMotionManager::Unregister(entity_id_t ent) { EntityMap::iterator it = m_Units.find(ent); if (it != m_Units.end()) { m_Units.erase(it); return; } it = m_FormationControllers.find(ent); if (it != m_FormationControllers.end()) m_FormationControllers.erase(it); } void CCmpUnitMotionManager::OnTurnStart() { for (EntityMap::value_type& data : m_FormationControllers) data.second.cmpUnitMotion->OnTurnStart(); for (EntityMap::value_type& data : m_Units) data.second.cmpUnitMotion->OnTurnStart(); } void CCmpUnitMotionManager::MoveUnits(fixed dt) { Move(m_Units, dt); } void CCmpUnitMotionManager::MoveFormations(fixed dt) { Move(m_FormationControllers, dt); } void CCmpUnitMotionManager::Move(EntityMap& ents, fixed dt) { - m_MovingUnits.clear(); + PROFILE2("MotionMgr_Move"); + std::unordered_set::iterator>*> assigned; for (EntityMap::iterator it = ents.begin(); it != ents.end(); ++it) { - it->second.cmpUnitMotion->PreMove(it->second); - if (!it->second.needUpdate) + if (!it->second.cmpPosition->IsInWorld()) + { + it->second.needUpdate = false; continue; - m_MovingUnits.push_back(it); + } + else + it->second.cmpUnitMotion->PreMove(it->second); it->second.initialPos = it->second.cmpPosition->GetPosition2D(); it->second.initialAngle = it->second.cmpPosition->GetRotation().Y; it->second.pos = it->second.initialPos; it->second.angle = it->second.initialAngle; + ENSURE(it->second.pos.X.ToInt_RoundToZero() / PUSHING_GRID_SIZE < m_MovingUnits.width() && + it->second.pos.Y.ToInt_RoundToZero() / PUSHING_GRID_SIZE < m_MovingUnits.height()); + std::vector::iterator>& subdiv = m_MovingUnits.get( + it->second.pos.X.ToInt_RoundToZero() / PUSHING_GRID_SIZE, + it->second.pos.Y.ToInt_RoundToZero() / PUSHING_GRID_SIZE + ); + subdiv.emplace_back(it); + assigned.emplace(&subdiv); + } + + for (std::vector::iterator>* vec : assigned) + for (EntityMap::iterator& it : *vec) + if (it->second.needUpdate) + it->second.cmpUnitMotion->Move(it->second, dt); + + if (&ents == &m_Units) + { + PROFILE2("MotionMgr_Pushing"); + for (std::vector::iterator>* vec : assigned) + { + ENSURE(!vec->empty()); + + std::vector::iterator>::iterator cit1 = vec->begin(); + do + { + if ((*cit1)->second.ignore) + continue; + std::vector::iterator>::iterator cit2 = cit1; + while(++cit2 != vec->end()) + if (!(*cit2)->second.ignore) + Push(**cit1, **cit2, dt); + } + while(++cit1 != vec->end()); + } + } + + { + PROFILE2("MotionMgr_PushAdjust"); + CmpPtr cmpPathfinder(GetSystemEntity()); + for (std::vector::iterator>* vec : assigned) + { + for (EntityMap::iterator& it : *vec) + { + + if (!it->second.needUpdate || it->second.ignore) + continue; + + // Prevent pushed units from crossing uncrossable boundaries + // (we can assume that normal movement didn't push units into impassable terrain). + if ((it->second.push.X != entity_pos_t::Zero() || it->second.push.Y != entity_pos_t::Zero()) && + !cmpPathfinder->CheckMovement(it->second.cmpUnitMotion->GetObstructionFilter(), + it->second.pos.X, it->second.pos.Y, + it->second.pos.X + it->second.push.X, it->second.pos.Y + it->second.push.Y, + it->second.cmpUnitMotion->m_Clearance, + it->second.cmpUnitMotion->m_PassClass)) + { + // Mark them as obstructed - this could possibly be optimised + // perhaps it'd make more sense to mark the pushers as blocked. + it->second.wasObstructed = true; + it->second.wentStraight = false; + it->second.push = CFixedVector2D(); + } + // Only apply pushing if the effect is significant enough. + if (it->second.push.CompareLength(MINIMAL_PUSHING) > 0) + { + // If there was an attempt at movement, and the pushed movement is in a sufficiently different direction + // (measured by an extremely arbitrary dot product) + // then mark the unit as obstructed still. + if (it->second.pos != it->second.initialPos && + (it->second.pos - it->second.initialPos).Dot(it->second.pos + it->second.push - it->second.initialPos) < entity_pos_t::FromInt(1)/2) + { + it->second.wasObstructed = true; + it->second.wentStraight = false; + // Push anyways. + } + it->second.pos += it->second.push; + } + it->second.push = CFixedVector2D(); + } + } + } + { + PROFILE2("MotionMgr_PostMove"); + for (EntityMap::value_type& data : ents) + { + if (!data.second.needUpdate) + continue; + data.second.cmpUnitMotion->PostMove(data.second, dt); + } } + for (std::vector::iterator>* vec : assigned) + vec->clear(); +} + +// TODO: ought to better simulate in-flight pushing, e.g. if units would cross in-between turns. +void CCmpUnitMotionManager::Push(EntityMap::value_type& a, EntityMap::value_type& b, fixed dt) +{ + // The hard problem for pushing is knowing when to actually use the pathfinder to go around unpushable obstacles. + // For simplicitly, the current logic separates moving & stopped entities: + // moving entities will push moving entities, but not stopped ones, and vice-versa. + // this still delivers most of the value of pushing, without a lot of the complexity. + int movingPush = a.second.isMoving + b.second.isMoving; + + // Exception: units in the same control group (i.e. the same formation) never push farther than themselves + // and are also allowed to push idle units (obstructions are ignored within formations, + // so pushing idle units makes one member crossing the formation look better). + if (a.second.controlGroup != INVALID_ENTITY && a.second.controlGroup == b.second.controlGroup) + movingPush = 0; + + if (movingPush == 1) + return; + + // Treat the clearances as a circle - they're defined as squares, so we'll slightly overcompensate the diagonal + // (they're also full-width instead of half, so we want to divide by two. sqrt(2)/2 is about 0.71 < 5/7). + entity_pos_t combinedClearance = (a.second.cmpUnitMotion->m_Clearance + b.second.cmpUnitMotion->m_Clearance) * 5 / 7; + entity_pos_t maxDist = combinedClearance; + if (movingPush) + maxDist += PUSHING_MOVING_INFLUENCE_EXTENSION; + + CFixedVector2D offset = a.second.pos - b.second.pos; + if (offset.CompareLength(maxDist) > 0) + return; - for (EntityMap::iterator& it : m_MovingUnits) + entity_pos_t offsetLength = offset.Length(); + // If the offset is small enough that precision would be problematic, pick an arbitrary vector instead. + if (offsetLength <= entity_pos_t::Epsilon() * 10) { - it->second.cmpUnitMotion->Move(it->second, dt); - it->second.cmpUnitMotion->PostMove(it->second, dt); + // Throw in some 'randomness' so that clumped units unclump more naturally. + bool dir = a.first % 2; + offset.X = entity_pos_t::FromInt(dir ? 1 : 0); + offset.Y = entity_pos_t::FromInt(dir ? 0 : 1); + offsetLength = entity_pos_t::FromInt(1); } + else + { + offset.X = offset.X / offsetLength; + offset.Y = offset.Y / offsetLength; + } + + // If the units are moving in opposite direction, check if they might have phased through each other. + // If it looks like yes, move them perpendicularily so it looks like they avoid each other. + // NB: this isn't very precise, nor will it catch 100% of intersections - it's meant as a cheap improvement. + if (movingPush && (a.second.pos - a.second.initialPos).Dot(b.second.pos - b.second.initialPos) < entity_pos_t::Zero()) + // Perform some finer checking. + if (Geometry::TestRayAASquare(a.second.initialPos - b.second.initialPos, a.second.pos - b.second.initialPos, + CFixedVector2D(combinedClearance, combinedClearance)) + || + Geometry::TestRayAASquare(a.second.initialPos - b.second.pos, a.second.pos - b.second.pos, + CFixedVector2D(combinedClearance, combinedClearance))) + { + offset = offset.Perpendicular(); + offsetLength = fixed::Zero(); + } + + + + // The formula expects 'normal' pushing if the two entities edges are touching. + entity_pos_t distanceFactor = movingPush ? (maxDist - offsetLength) / (maxDist - combinedClearance) : combinedClearance - offsetLength + entity_pos_t::FromInt(1); + distanceFactor = Clamp(distanceFactor, entity_pos_t::Zero(), entity_pos_t::FromInt(2)); + + // Mark both as needing an update so they actually get moved. + a.second.needUpdate = true; + b.second.needUpdate = true; + + CFixedVector2D pushingDir = offset.Multiply(distanceFactor); + + // Divide by an arbitrary constant to avoid pushing too much. + a.second.push += pushingDir.Multiply(movingPush ? dt : dt / PUSHING_REDUCTION_FACTOR); + b.second.push -= pushingDir.Multiply(movingPush ? dt : dt / PUSHING_REDUCTION_FACTOR); } Index: ps/trunk/source/simulation2/components/ICmpObstruction.cpp =================================================================== --- ps/trunk/source/simulation2/components/ICmpObstruction.cpp (revision 25181) +++ ps/trunk/source/simulation2/components/ICmpObstruction.cpp (revision 25182) @@ -1,63 +1,63 @@ -/* Copyright (C) 2020 Wildfire Games. +/* Copyright (C) 2021 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 "ICmpObstruction.h" #include "simulation2/system/InterfaceScripted.h" #include "simulation2/system/SimContext.h" std::string ICmpObstruction::CheckFoundation_wrapper(const std::string& className, bool onlyCenterPoint) const { EFoundationCheck check = CheckFoundation(className, onlyCenterPoint); switch (check) { case FOUNDATION_CHECK_SUCCESS: return "success"; case FOUNDATION_CHECK_FAIL_ERROR: return "fail_error"; case FOUNDATION_CHECK_FAIL_NO_OBSTRUCTION: return "fail_no_obstruction"; case FOUNDATION_CHECK_FAIL_OBSTRUCTS_FOUNDATION: return "fail_obstructs_foundation"; case FOUNDATION_CHECK_FAIL_TERRAIN_CLASS: return "fail_terrain_class"; default: debug_warn(L"Unexpected result from CheckFoundation"); return ""; } } BEGIN_INTERFACE_WRAPPER(Obstruction) DEFINE_INTERFACE_METHOD_CONST_0("GetSize", entity_pos_t, ICmpObstruction, GetSize) DEFINE_INTERFACE_METHOD_CONST_0("CheckShorePlacement", bool, ICmpObstruction, CheckShorePlacement) DEFINE_INTERFACE_METHOD_CONST_2("CheckFoundation", std::string, ICmpObstruction, CheckFoundation_wrapper, std::string, bool) DEFINE_INTERFACE_METHOD_CONST_0("CheckDuplicateFoundation", bool, ICmpObstruction, CheckDuplicateFoundation) DEFINE_INTERFACE_METHOD_CONST_0("GetEntitiesBlockingMovement", std::vector, ICmpObstruction, GetEntitiesBlockingMovement) DEFINE_INTERFACE_METHOD_CONST_0("GetEntitiesBlockingConstruction", std::vector, ICmpObstruction, GetEntitiesBlockingConstruction) DEFINE_INTERFACE_METHOD_CONST_0("GetEntitiesDeletedUponConstruction", std::vector, ICmpObstruction, GetEntitiesDeletedUponConstruction) DEFINE_INTERFACE_METHOD_1("SetActive", void, ICmpObstruction, SetActive, bool) DEFINE_INTERFACE_METHOD_3("SetDisableBlockMovementPathfinding", void, ICmpObstruction, SetDisableBlockMovementPathfinding, bool, bool, int32_t) -DEFINE_INTERFACE_METHOD_CONST_0("GetBlockMovementFlag", bool, ICmpObstruction, GetBlockMovementFlag) +DEFINE_INTERFACE_METHOD_CONST_1("GetBlockMovementFlag", bool, ICmpObstruction, GetBlockMovementFlag, bool) DEFINE_INTERFACE_METHOD_1("SetControlGroup", void, ICmpObstruction, SetControlGroup, entity_id_t) DEFINE_INTERFACE_METHOD_CONST_0("GetControlGroup", entity_id_t, ICmpObstruction, GetControlGroup) DEFINE_INTERFACE_METHOD_1("SetControlGroup2", void, ICmpObstruction, SetControlGroup2, entity_id_t) DEFINE_INTERFACE_METHOD_CONST_0("GetControlGroup2", entity_id_t, ICmpObstruction, GetControlGroup2) END_INTERFACE_WRAPPER(Obstruction) Index: ps/trunk/source/simulation2/components/ICmpObstruction.h =================================================================== --- ps/trunk/source/simulation2/components/ICmpObstruction.h (revision 25181) +++ ps/trunk/source/simulation2/components/ICmpObstruction.h (revision 25182) @@ -1,159 +1,162 @@ -/* Copyright (C) 2020 Wildfire Games. +/* Copyright (C) 2021 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; /** * @return the size of the obstruction (either the clearance or a circumscribed circle). */ virtual entity_pos_t GetSize() const = 0; /** * @return the size of the static obstruction or (0,0) for a unit shape. */ virtual CFixedVector2D GetStaticSize() 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 movement. * @return vector of blocking entities */ virtual std::vector GetEntitiesBlockingMovement() 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; + /** + * @param templateOnly - whether to return the raw template value or the current value. + */ + virtual bool GetBlockMovementFlag(bool templateOnly) 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/ICmpObstructionManager.h =================================================================== --- ps/trunk/source/simulation2/components/ICmpObstructionManager.h (revision 25181) +++ ps/trunk/source/simulation2/components/ICmpObstructionManager.h (revision 25182) @@ -1,582 +1,585 @@ -/* Copyright (C) 2020 Wildfire Games. +/* Copyright (C) 2021 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_ICMPOBSTRUCTIONMANAGER #define INCLUDED_ICMPOBSTRUCTIONMANAGER #include "simulation2/system/Interface.h" #include "maths/FixedVector2D.h" #include "simulation2/helpers/Position.h" #include class IObstructionTestFilter; template class Grid; struct GridUpdateInformation; using NavcellData = u16; class PathfinderPassability; /** * Obstruction manager: provides efficient spatial queries over objects in the world. * * The class deals with two types of shape: * "static" shapes, typically representing buildings, which are rectangles with a given * width and height and angle; * and "unit" shapes, representing units that can move around the world, which have a * radius and no rotation. (Units sometimes act as axis-aligned squares, sometimes * as approximately circles, due to the algorithm used by the short pathfinder.) * * Other classes (particularly ICmpObstruction) register shapes with this interface * and keep them updated. * * The @c Test functions provide exact collision tests. * The edge of a shape counts as 'inside' the shape, for the purpose of collisions. * The functions accept an IObstructionTestFilter argument, which can restrict the * set of shapes that are counted as collisions. * * Units can be marked as either moving or stationary, which simply determines whether * certain filters include or exclude them. * * The @c Rasterize function approximates the current set of shapes onto a 2D grid, * for use with tile-based pathfinding. */ class ICmpObstructionManager : public IComponent { public: /** * Standard representation for all types of shapes, for use with geometry processing code. */ struct ObstructionSquare { entity_pos_t x, z; // position of center CFixedVector2D u, v; // 'horizontal' and 'vertical' orthogonal unit vectors, representing orientation entity_pos_t hw, hh; // half width, half height of square }; /** * External identifiers for shapes. * (This is a struct rather than a raw u32 for type-safety.) */ struct tag_t { tag_t() : n(0) {} explicit tag_t(u32 n) : n(n) {} bool valid() const { return n != 0; } u32 n; }; /** * Boolean flags affecting the obstruction behaviour of a shape. */ enum EFlags { FLAG_BLOCK_MOVEMENT = (1 << 0), // prevents units moving through this shape FLAG_BLOCK_FOUNDATION = (1 << 1), // prevents foundations being placed on this shape FLAG_BLOCK_CONSTRUCTION = (1 << 2), // prevents buildings being constructed on this shape FLAG_BLOCK_PATHFINDING = (1 << 3), // prevents the tile pathfinder choosing paths through this shape - FLAG_MOVING = (1 << 4), // indicates this unit is currently moving + FLAG_MOVING = (1 << 4), // reserved for unitMotion - see usage there. FLAG_DELETE_UPON_CONSTRUCTION = (1 << 5) // this entity is deleted when construction of a building placed on top of this entity starts }; /** * Bitmask of EFlag values. */ typedef u8 flags_t; /** * Set the bounds of the world. * Any point outside the bounds is considered obstructed. * @param x0,z0,x1,z1 Coordinates of the corners of the world */ virtual void SetBounds(entity_pos_t x0, entity_pos_t z0, entity_pos_t x1, entity_pos_t z1) = 0; /** * Register a static shape. * * @param ent entity ID associated with this shape (or INVALID_ENTITY if none) * @param x,z coordinates of center, in world space * @param a angle of rotation (clockwise from +Z direction) * @param w width (size along X axis) * @param h height (size along Z axis) * @param flags a set of EFlags values * @param group primary control group of the shape. Must be a valid control group ID. * @param group2 Optional; secondary control group of the shape. Defaults to INVALID_ENTITY. * @return a valid tag for manipulating the shape * @see StaticShape */ virtual tag_t AddStaticShape(entity_id_t ent, entity_pos_t x, entity_pos_t z, entity_angle_t a, entity_pos_t w, entity_pos_t h, flags_t flags, entity_id_t group, entity_id_t group2 = INVALID_ENTITY) = 0; /** * Register a unit shape. * * @param ent entity ID associated with this shape (or INVALID_ENTITY if none) * @param x,z coordinates of center, in world space * @param clearance pathfinding clearance of the unit (works as a radius) * @param flags a set of EFlags values * @param group control group (typically the owner entity, or a formation controller entity * - units ignore collisions with others in the same group) * @return a valid tag for manipulating the shape * @see UnitShape */ virtual tag_t AddUnitShape(entity_id_t ent, entity_pos_t x, entity_pos_t z, entity_pos_t clearance, flags_t flags, entity_id_t group) = 0; /** * Adjust the position and angle of an existing shape. * @param tag tag of shape (must be valid) * @param x X coordinate of center, in world space * @param z Z coordinate of center, in world space * @param a angle of rotation (clockwise from +Z direction); ignored for unit shapes */ virtual void MoveShape(tag_t tag, entity_pos_t x, entity_pos_t z, entity_angle_t a) = 0; /** * Set whether a unit shape is moving or stationary. * @param tag tag of shape (must be valid and a unit shape) * @param moving whether the unit is currently moving through the world or is stationary */ virtual void SetUnitMovingFlag(tag_t tag, bool moving) = 0; /** * Set the control group of a unit shape. * @param tag tag of shape (must be valid and a unit shape) * @param group control group entity ID */ virtual void SetUnitControlGroup(tag_t tag, entity_id_t group) = 0; /** * Sets the control group of a static shape. * @param tag Tag of the shape to set the control group for. Must be a valid and static shape tag. * @param group Control group entity ID. */ virtual void SetStaticControlGroup(tag_t tag, entity_id_t group, entity_id_t group2) = 0; /** * Remove an existing shape. The tag will be made invalid and must not be used after this. * @param tag tag of shape (must be valid) */ virtual void RemoveShape(tag_t tag) = 0; /** * Returns the distance from the obstruction to the point (px, pz), or -1 if the entity is out of the world. */ virtual fixed DistanceToPoint(entity_id_t ent, entity_pos_t px, entity_pos_t pz) const = 0; /** * Calculate the largest straight line distance between the entity and the point. */ virtual fixed MaxDistanceToPoint(entity_id_t ent, entity_pos_t px, entity_pos_t pz) const = 0; /** * Calculate the shortest distance between the entity and the target. */ virtual fixed DistanceToTarget(entity_id_t ent, entity_id_t target) const = 0; /** * Calculate the largest straight line distance between the entity and the target. */ virtual fixed MaxDistanceToTarget(entity_id_t ent, entity_id_t target) const = 0; /** * Calculate the shortest straight line distance between the source and the target */ virtual fixed DistanceBetweenShapes(const ObstructionSquare& source, const ObstructionSquare& target) const = 0; /** * Calculate the largest straight line distance between the source and the target */ virtual fixed MaxDistanceBetweenShapes(const ObstructionSquare& source, const ObstructionSquare& target) const = 0; /** * Check if the given entity is in range of the other point given those parameters. * @param maxRange - if -1, treated as infinite. */ virtual bool IsInPointRange(entity_id_t ent, entity_pos_t px, entity_pos_t pz, entity_pos_t minRange, entity_pos_t maxRange, bool opposite) const = 0; /** * Check if the given entity is in range of the target given those parameters. * @param maxRange - if -1, treated as infinite. */ virtual bool IsInTargetRange(entity_id_t ent, entity_id_t target, entity_pos_t minRange, entity_pos_t maxRange, bool opposite) const = 0; /** * Check if the given point is in range of the other point given those parameters. * @param maxRange - if -1, treated as infinite. */ virtual bool IsPointInPointRange(entity_pos_t x, entity_pos_t z, entity_pos_t px, entity_pos_t pz, entity_pos_t minRange, entity_pos_t maxRange) const = 0; /** * Check if the given shape is in range of the target shape given those parameters. * @param maxRange - if -1, treated as infinite. */ virtual bool AreShapesInRange(const ObstructionSquare& source, const ObstructionSquare& target, entity_pos_t minRange, entity_pos_t maxRange, bool opposite) const = 0; /** * Collision test a flat-ended thick line against the current set of shapes. * The line caps extend by @p r beyond the end points. * Only intersections going from outside to inside a shape are counted. * @param filter filter to restrict the shapes that are counted * @param x0 X coordinate of line's first point * @param z0 Z coordinate of line's first point * @param x1 X coordinate of line's second point * @param z1 Z coordinate of line's second point * @param r radius (half width) of line * @param relaxClearanceForUnits whether unit-unit collisions should be more permissive. * @return true if there is a collision */ virtual bool TestLine(const IObstructionTestFilter& filter, entity_pos_t x0, entity_pos_t z0, entity_pos_t x1, entity_pos_t z1, entity_pos_t r, bool relaxClearanceForUnits) const = 0; /** * Collision test a static square shape against the current set of shapes. * @param filter filter to restrict the shapes that are being tested against * @param x X coordinate of center * @param z Z coordinate of center * @param a angle of rotation (clockwise from +Z direction) * @param w width (size along X axis) * @param h height (size along Z axis) * @param out if non-NULL, all colliding shapes' entities will be added to this list * @return true if there is a collision */ virtual bool TestStaticShape(const IObstructionTestFilter& filter, entity_pos_t x, entity_pos_t z, entity_pos_t a, entity_pos_t w, entity_pos_t h, std::vector* out) const = 0; /** * Collision test a unit shape against the current set of registered shapes, and optionally writes a list of the colliding * shapes' entities to an output list. * * @param filter filter to restrict the shapes that are being tested against * @param x X coordinate of shape's center * @param z Z coordinate of shape's center * @param clearance clearance of the shape's unit * @param out if non-NULL, all colliding shapes' entities will be added to this list * * @return true if there is a collision */ virtual bool TestUnitShape(const IObstructionTestFilter& filter, entity_pos_t x, entity_pos_t z, entity_pos_t clearance, std::vector* out) const = 0; /** * Convert the current set of shapes onto a navcell grid, for all passability classes contained in @p passClasses. * If @p fullUpdate is false, the function will only go through dirty shapes. * Shapes are expanded by the @p passClasses clearances, by ORing their masks onto the @p grid. */ virtual void Rasterize(Grid& grid, const std::vector& passClasses, bool fullUpdate) = 0; /** * Gets dirtiness information and resets it afterwards. Then it's the role of CCmpPathfinder * to pass the information to other components if needed. (AIs, etc.) * The return value is false if an update is unnecessary. */ virtual void UpdateInformations(GridUpdateInformation& informations) = 0; /** * Find all the obstructions that are inside (or partially inside) the given range. * @param filter filter to restrict the shapes that are counted * @param x0 X coordinate of left edge of range * @param z0 Z coordinate of bottom edge of range * @param x1 X coordinate of right edge of range * @param z1 Z coordinate of top edge of range * @param squares output list of obstructions */ virtual void GetObstructionsInRange(const IObstructionTestFilter& filter, entity_pos_t x0, entity_pos_t z0, entity_pos_t x1, entity_pos_t z1, std::vector& squares) const = 0; virtual void GetStaticObstructionsInRange(const IObstructionTestFilter& filter, entity_pos_t x0, entity_pos_t z0, entity_pos_t x1, entity_pos_t z1, std::vector& squares) const = 0; virtual void GetUnitObstructionsInRange(const IObstructionTestFilter& filter, entity_pos_t x0, entity_pos_t z0, entity_pos_t x1, entity_pos_t z1, std::vector& squares) const = 0; virtual void GetStaticObstructionsOnObstruction(const ObstructionSquare& square, std::vector& out, const IObstructionTestFilter& filter) const = 0; /** * Returns the entity IDs of all unit shapes that intersect the given * obstruction square, filtering out using the given filter. * @param square the Obstruction squre we want to compare with. * @param out output list of obstructions * @param filter filter for the obstructing units * @param strict whether to be strict in the check or more permissive (ie rasterize more or less). Default false. */ virtual void GetUnitsOnObstruction(const ObstructionSquare& square, std::vector& out, const IObstructionTestFilter& filter, bool strict = false) const = 0; /** * Get the obstruction square representing the given shape. * @param tag tag of shape (must be valid) */ virtual ObstructionSquare GetObstruction(tag_t tag) const = 0; virtual ObstructionSquare GetUnitShapeObstruction(entity_pos_t x, entity_pos_t z, entity_pos_t clearance) const = 0; virtual ObstructionSquare GetStaticShapeObstruction(entity_pos_t x, entity_pos_t z, entity_angle_t a, entity_pos_t w, entity_pos_t h) const = 0; /** * Set the passability to be restricted to a circular map. */ virtual void SetPassabilityCircular(bool enabled) = 0; virtual bool GetPassabilityCircular() const = 0; /** * Toggle the rendering of debug info. */ virtual void SetDebugOverlay(bool enabled) = 0; DECLARE_INTERFACE_TYPE(ObstructionManager) }; /** * Interface for ICmpObstructionManager @c Test functions to filter out unwanted shapes. */ class IObstructionTestFilter { public: typedef ICmpObstructionManager::tag_t tag_t; typedef ICmpObstructionManager::flags_t flags_t; virtual ~IObstructionTestFilter() {} /** * Return true if the shape with the specified parameters should be tested for collisions. * This is called for all shapes that would collide, and also for some that wouldn't. * * @param tag tag of shape being tested * @param flags set of EFlags for the shape * @param group the control group of the shape (typically the shape's unit, or the unit's formation controller, or 0) * @param group2 an optional secondary control group of the shape, or INVALID_ENTITY if none specified. Currently * exists only for static shapes. */ virtual bool TestShape(tag_t tag, flags_t flags, entity_id_t group, entity_id_t group2) const = 0; }; /** * Obstruction test filter that will test against all shapes. */ class NullObstructionFilter : public IObstructionTestFilter { public: virtual bool TestShape(tag_t UNUSED(tag), flags_t UNUSED(flags), entity_id_t UNUSED(group), entity_id_t UNUSED(group2)) const { return true; } }; /** * Obstruction test filter that will test only against stationary (i.e. non-moving) shapes. */ class StationaryOnlyObstructionFilter : public IObstructionTestFilter { public: virtual bool TestShape(tag_t UNUSED(tag), flags_t flags, entity_id_t UNUSED(group), entity_id_t UNUSED(group2)) const { return !(flags & ICmpObstructionManager::FLAG_MOVING); } }; /** * Obstruction test filter that reject shapes in a given control group, * and rejects shapes that don't block unit movement, and optionally rejects moving shapes. */ class ControlGroupMovementObstructionFilter : public IObstructionTestFilter { bool m_AvoidMoving; entity_id_t m_Group; public: ControlGroupMovementObstructionFilter(bool avoidMoving, entity_id_t group) : m_AvoidMoving(avoidMoving), m_Group(group) {} virtual bool TestShape(tag_t UNUSED(tag), flags_t flags, entity_id_t group, entity_id_t group2) const { if (group == m_Group || (group2 != INVALID_ENTITY && group2 == m_Group)) return false; if (!(flags & ICmpObstructionManager::FLAG_BLOCK_MOVEMENT)) return false; if ((flags & ICmpObstructionManager::FLAG_MOVING) && !m_AvoidMoving) return false; return true; } }; /** * Obstruction test filter that will test only against shapes that: * - are part of neither one of the specified control groups * - AND, depending on the value of the 'exclude' argument: * - have at least one of the specified flags set. * - OR have none of the specified flags set. * * The first (primary) control group to reject shapes from must be specified and valid. The secondary * control group to reject entities from may be set to INVALID_ENTITY to not use it. * * This filter is useful to e.g. allow foundations within the same control group to be placed and * constructed arbitrarily close together (e.g. for wall pieces that need to link up tightly). */ class SkipControlGroupsRequireFlagObstructionFilter : public IObstructionTestFilter { bool m_Exclude; entity_id_t m_Group; entity_id_t m_Group2; flags_t m_Mask; public: SkipControlGroupsRequireFlagObstructionFilter(bool exclude, entity_id_t group1, entity_id_t group2, flags_t mask) : m_Exclude(exclude), m_Group(group1), m_Group2(group2), m_Mask(mask) { Init(); } SkipControlGroupsRequireFlagObstructionFilter(entity_id_t group1, entity_id_t group2, flags_t mask) : m_Exclude(false), m_Group(group1), m_Group2(group2), m_Mask(mask) { Init(); } virtual bool TestShape(tag_t UNUSED(tag), flags_t flags, entity_id_t group, entity_id_t group2) const { // Don't test shapes that share one or more of our control groups. if (group == m_Group || group == m_Group2 || (group2 != INVALID_ENTITY && (group2 == m_Group || group2 == m_Group2))) return false; // If m_Exclude is true, don't test against shapes that have any of the // obstruction flags specified in m_Mask. if (m_Exclude) return (flags & m_Mask) == 0; // Otherwise, only include shapes that match at least one flag in m_Mask. return (flags & m_Mask) != 0; } private: void Init() { // the primary control group to filter out must be valid ENSURE(m_Group != INVALID_ENTITY); // for simplicity, if m_Group2 is INVALID_ENTITY (i.e. not used), then set it equal to m_Group // so that we have fewer special cases to consider in TestShape(). if (m_Group2 == INVALID_ENTITY) m_Group2 = m_Group; } }; /** * Obstruction test filter that will test only against shapes that: * - are part of both of the specified control groups * - AND have at least one of the specified flags set. * * The first (primary) control group to include shapes from must be specified and valid. * * This filter is useful for preventing entities with identical control groups * from colliding e.g. building a new wall segment on top of an existing wall) * * @todo This filter needs test cases. */ class SkipTagRequireControlGroupsAndFlagObstructionFilter : public IObstructionTestFilter { tag_t m_Tag; entity_id_t m_Group; entity_id_t m_Group2; flags_t m_Mask; public: SkipTagRequireControlGroupsAndFlagObstructionFilter(tag_t tag, entity_id_t group1, entity_id_t group2, flags_t mask) : m_Tag(tag), m_Group(group1), m_Group2(group2), m_Mask(mask) { ENSURE(m_Group != INVALID_ENTITY); } virtual bool TestShape(tag_t tag, flags_t flags, entity_id_t group, entity_id_t group2) const { // To be included in testing, a shape must not have the specified tag, and must // match at least one of the flags in m_Mask, as well as both control groups. return (tag.n != m_Tag.n && (flags & m_Mask) != 0 && ((group == m_Group && group2 == m_Group2) || (group2 == m_Group && group == m_Group2))); } }; /** * Obstruction test filter that will test only against shapes that do not have the specified tag set. */ class SkipTagObstructionFilter : public IObstructionTestFilter { tag_t m_Tag; public: SkipTagObstructionFilter(tag_t tag) : m_Tag(tag) { } virtual bool TestShape(tag_t tag, flags_t UNUSED(flags), entity_id_t UNUSED(group), entity_id_t UNUSED(group2)) const { return tag.n != m_Tag.n; } }; /** - * Obstruction test filter that reject shapes in a given control group or with the given tag (if that tag is moving), - * and rejects shapes that don't block unit movement. See D3482 for why this exists. + * Similar to ControlGroupMovementObstructionFilter, but also ignoring a specific tag. See D3482 for why this exists. */ -class SkipMovingTagAndControlGroupObstructionFilter : public IObstructionTestFilter +class SkipTagAndControlGroupObstructionFilter : public IObstructionTestFilter { entity_id_t m_Group; tag_t m_Tag; + bool m_AvoidMoving; public: - SkipMovingTagAndControlGroupObstructionFilter(tag_t tag, entity_id_t group) : - m_Tag(tag), m_Group(group) + SkipTagAndControlGroupObstructionFilter(tag_t tag, bool avoidMoving, entity_id_t group) : + m_Tag(tag), m_Group(group), m_AvoidMoving(avoidMoving) {} virtual bool TestShape(tag_t tag, flags_t flags, entity_id_t group, entity_id_t group2) const { - if (tag.n == m_Tag.n && (flags & ICmpObstructionManager::FLAG_MOVING)) + if (tag.n == m_Tag.n) return false; if (group == m_Group || (group2 != INVALID_ENTITY && group2 == m_Group)) return false; + if ((flags & ICmpObstructionManager::FLAG_MOVING) && !m_AvoidMoving) + return false; + if (!(flags & ICmpObstructionManager::FLAG_BLOCK_MOVEMENT)) return false; return true; } }; /** * Obstruction test filter that will test only against shapes that: * - do not have the specified tag * - AND have at least one of the specified flags set. */ class SkipTagRequireFlagsObstructionFilter : public IObstructionTestFilter { tag_t m_Tag; flags_t m_Mask; public: SkipTagRequireFlagsObstructionFilter(tag_t tag, flags_t mask) : m_Tag(tag), m_Mask(mask) { } virtual bool TestShape(tag_t tag, flags_t flags, entity_id_t UNUSED(group), entity_id_t UNUSED(group2)) const { return (tag.n != m_Tag.n && (flags & m_Mask) != 0); } }; #endif // INCLUDED_ICMPOBSTRUCTIONMANAGER Index: ps/trunk/source/simulation2/components/tests/test_ObstructionManager.h =================================================================== --- ps/trunk/source/simulation2/components/tests/test_ObstructionManager.h (revision 25181) +++ ps/trunk/source/simulation2/components/tests/test_ObstructionManager.h (revision 25182) @@ -1,593 +1,593 @@ -/* Copyright (C) 2020 Wildfire Games. +/* Copyright (C) 2021 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 CFixedVector2D GetStaticSize() const { return CFixedVector2D(); } 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 GetEntitiesBlockingMovement() 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 bool GetBlockMovementFlag(bool) 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_ScriptContext); 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.0001f)); TS_ASSERT_DELTA(fixed::FromFloat(std::sqrt(80)), cmp->MaxDistanceToTarget(ent3, ent2), fixed::FromFloat(0.0001f)); 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.0001f)); TS_ASSERT_DELTA(fixed::FromFloat(std::sqrt(125) + 3), cmp->MaxDistanceToTarget(ent4, ent1), fixed::FromFloat(0.0001f)); 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.0001f)); TS_ASSERT_DELTA(fixed::FromFloat(std::sqrt(178)), cmp->MaxDistanceToTarget(ent5, ent1), fixed::FromFloat(0.0001f)); 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/components/tests/test_RangeManager.h =================================================================== --- ps/trunk/source/simulation2/components/tests/test_RangeManager.h (revision 25181) +++ ps/trunk/source/simulation2/components/tests/test_RangeManager.h (revision 25182) @@ -1,271 +1,271 @@ -/* Copyright (C) 2020 Wildfire Games. +/* Copyright (C) 2021 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 "maths/Matrix3D.h" #include "simulation2/system/ComponentTest.h" #include "simulation2/components/ICmpRangeManager.h" #include "simulation2/components/ICmpObstruction.h" #include "simulation2/components/ICmpPosition.h" #include "simulation2/components/ICmpVision.h" #include #include class MockVisionRgm : public ICmpVision { public: DEFAULT_MOCK_COMPONENT() virtual entity_pos_t GetRange() const { return entity_pos_t::FromInt(66); } virtual bool GetRevealShore() const { return false; } }; class MockPositionRgm : public ICmpPosition { public: DEFAULT_MOCK_COMPONENT() virtual void SetTurretParent(entity_id_t UNUSED(id), const CFixedVector3D& UNUSED(pos)) {} virtual entity_id_t GetTurretParent() const {return INVALID_ENTITY;} virtual void UpdateTurretPosition() {} virtual std::set* GetTurrets() { return NULL; } virtual bool IsInWorld() const { return true; } virtual void MoveOutOfWorld() { } virtual void MoveTo(entity_pos_t UNUSED(x), entity_pos_t UNUSED(z)) { } virtual void MoveAndTurnTo(entity_pos_t UNUSED(x), entity_pos_t UNUSED(z), entity_angle_t UNUSED(a)) { } virtual void JumpTo(entity_pos_t UNUSED(x), entity_pos_t UNUSED(z)) { } virtual void SetHeightOffset(entity_pos_t UNUSED(dy)) { } virtual entity_pos_t GetHeightOffset() const { return entity_pos_t::Zero(); } virtual void SetHeightFixed(entity_pos_t UNUSED(y)) { } virtual entity_pos_t GetHeightFixed() const { return entity_pos_t::Zero(); } virtual entity_pos_t GetHeightAtFixed(entity_pos_t, entity_pos_t) const { return entity_pos_t::Zero(); } virtual bool IsHeightRelative() const { return true; } virtual void SetHeightRelative(bool UNUSED(relative)) { } virtual bool CanFloat() const { return false; } virtual void SetFloating(bool UNUSED(flag)) { } virtual void SetActorFloating(bool UNUSED(flag)) { } virtual void SetConstructionProgress(fixed UNUSED(progress)) { } virtual CFixedVector3D GetPosition() const { return m_Pos; } virtual CFixedVector2D GetPosition2D() const { return CFixedVector2D(m_Pos.X, m_Pos.Z); } virtual CFixedVector3D GetPreviousPosition() const { return CFixedVector3D(); } virtual CFixedVector2D GetPreviousPosition2D() const { return CFixedVector2D(); } virtual fixed GetTurnRate() const { return fixed::Zero(); } virtual void TurnTo(entity_angle_t UNUSED(y)) { } virtual void SetYRotation(entity_angle_t UNUSED(y)) { } virtual void SetXZRotation(entity_angle_t UNUSED(x), entity_angle_t UNUSED(z)) { } virtual CFixedVector3D GetRotation() const { return CFixedVector3D(); } virtual fixed GetDistanceTravelled() const { return fixed::Zero(); } virtual void GetInterpolatedPosition2D(float UNUSED(frameOffset), float& x, float& z, float& rotY) const { x = z = rotY = 0; } virtual CMatrix3D GetInterpolatedTransform(float UNUSED(frameOffset)) const { return CMatrix3D(); } CFixedVector3D m_Pos; }; class MockObstructionRgm : public ICmpObstruction { public: DEFAULT_MOCK_COMPONENT(); MockObstructionRgm(entity_pos_t s) : m_Size(s) {}; virtual ICmpObstructionManager::tag_t GetObstruction() const { return {}; }; virtual bool GetObstructionSquare(ICmpObstructionManager::ObstructionSquare&) const { return false; }; virtual bool GetPreviousObstructionSquare(ICmpObstructionManager::ObstructionSquare&) const { return false; }; virtual entity_pos_t GetSize() const { return m_Size; }; virtual CFixedVector2D GetStaticSize() const { return {}; }; virtual EObstructionType GetObstructionType() const { return {}; }; virtual void SetUnitClearance(const entity_pos_t&) {}; virtual bool IsControlPersistent() const { return {}; }; virtual bool CheckShorePlacement() const { return {}; }; virtual EFoundationCheck CheckFoundation(const std::string&) const { return {}; }; virtual EFoundationCheck CheckFoundation(const std::string& , bool) const { return {}; }; virtual std::string CheckFoundation_wrapper(const std::string&, bool) const { return {}; }; virtual bool CheckDuplicateFoundation() const { return {}; }; virtual std::vector GetEntitiesByFlags(ICmpObstructionManager::flags_t) const { return {}; }; virtual std::vector GetEntitiesBlockingMovement() const { return {}; }; virtual std::vector GetEntitiesBlockingConstruction() const { return {}; }; virtual std::vector GetEntitiesDeletedUponConstruction() const { return {}; }; virtual void ResolveFoundationCollisions() const {}; virtual void SetActive(bool) {}; virtual void SetMovingFlag(bool) {}; virtual void SetDisableBlockMovementPathfinding(bool, bool, int32_t) {}; - virtual bool GetBlockMovementFlag() const { return {}; }; + virtual bool GetBlockMovementFlag(bool) const { return {}; }; virtual void SetControlGroup(entity_id_t) {}; virtual entity_id_t GetControlGroup() const { return {}; }; virtual void SetControlGroup2(entity_id_t) {}; virtual entity_id_t GetControlGroup2() const { return {}; }; private: entity_pos_t m_Size; }; class TestCmpRangeManager : public CxxTest::TestSuite { public: void setUp() { CXeromyces::Startup(); } void tearDown() { CXeromyces::Terminate(); } // TODO It would be nice to call Verify() with the shore revealing system // but that means testing on an actual map, with water and land. void test_basic() { ComponentTestHelper test(g_ScriptContext); ICmpRangeManager* cmp = test.Add(CID_RangeManager, "", SYSTEM_ENTITY); MockVisionRgm vision; test.AddMock(100, IID_Vision, vision); MockPositionRgm position; test.AddMock(100, IID_Position, position); // This tests that the incremental computation produces the correct result // in various edge cases cmp->SetBounds(entity_pos_t::FromInt(0), entity_pos_t::FromInt(0), entity_pos_t::FromInt(512), entity_pos_t::FromInt(512)); cmp->Verify(); { CMessageCreate msg(100); cmp->HandleMessage(msg, false); } cmp->Verify(); { CMessageOwnershipChanged msg(100, -1, 1); cmp->HandleMessage(msg, false); } cmp->Verify(); { CMessagePositionChanged msg(100, true, entity_pos_t::FromInt(247), entity_pos_t::FromDouble(257.95), entity_angle_t::Zero()); cmp->HandleMessage(msg, false); } cmp->Verify(); { CMessagePositionChanged msg(100, true, entity_pos_t::FromInt(247), entity_pos_t::FromInt(253), entity_angle_t::Zero()); cmp->HandleMessage(msg, false); } cmp->Verify(); { CMessagePositionChanged msg(100, true, entity_pos_t::FromInt(256), entity_pos_t::FromInt(256), entity_angle_t::Zero()); cmp->HandleMessage(msg, false); } cmp->Verify(); { CMessagePositionChanged msg(100, true, entity_pos_t::FromInt(256)+entity_pos_t::Epsilon(), entity_pos_t::FromInt(256), entity_angle_t::Zero()); cmp->HandleMessage(msg, false); } cmp->Verify(); { CMessagePositionChanged msg(100, true, entity_pos_t::FromInt(256)-entity_pos_t::Epsilon(), entity_pos_t::FromInt(256), entity_angle_t::Zero()); cmp->HandleMessage(msg, false); } cmp->Verify(); { CMessagePositionChanged msg(100, true, entity_pos_t::FromInt(256), entity_pos_t::FromInt(256)+entity_pos_t::Epsilon(), entity_angle_t::Zero()); cmp->HandleMessage(msg, false); } cmp->Verify(); { CMessagePositionChanged msg(100, true, entity_pos_t::FromInt(256), entity_pos_t::FromInt(256)-entity_pos_t::Epsilon(), entity_angle_t::Zero()); cmp->HandleMessage(msg, false); } cmp->Verify(); { CMessagePositionChanged msg(100, true, entity_pos_t::FromInt(383), entity_pos_t::FromInt(84), entity_angle_t::Zero()); cmp->HandleMessage(msg, false); } cmp->Verify(); { CMessagePositionChanged msg(100, true, entity_pos_t::FromInt(348), entity_pos_t::FromInt(83), entity_angle_t::Zero()); cmp->HandleMessage(msg, false); } cmp->Verify(); boost::mt19937 rng; for (size_t i = 0; i < 1024; ++i) { double x = boost::random::uniform_real_distribution(0.0, 512.0)(rng); double z = boost::random::uniform_real_distribution(0.0, 512.0)(rng); { CMessagePositionChanged msg(100, true, entity_pos_t::FromDouble(x), entity_pos_t::FromDouble(z), entity_angle_t::Zero()); cmp->HandleMessage(msg, false); } cmp->Verify(); } // Test OwnershipChange, GetEntitiesByPlayer, GetNonGaiaEntities { player_id_t previousOwner = -1; for (player_id_t newOwner = 0; newOwner < 8; ++newOwner) { CMessageOwnershipChanged msg(100, previousOwner, newOwner); cmp->HandleMessage(msg, false); for (player_id_t i = 0; i < 8; ++i) TS_ASSERT_EQUALS(cmp->GetEntitiesByPlayer(i).size(), i == newOwner ? 1 : 0); TS_ASSERT_EQUALS(cmp->GetNonGaiaEntities().size(), newOwner > 0 ? 1 : 0); previousOwner = newOwner; } } } void test_queries() { ComponentTestHelper test(g_ScriptContext); ICmpRangeManager* cmp = test.Add(CID_RangeManager, "", SYSTEM_ENTITY); MockVisionRgm vision, vision2; MockPositionRgm position, position2; MockObstructionRgm obs(fixed::FromInt(2)), obs2(fixed::Zero()); test.AddMock(100, IID_Vision, vision); test.AddMock(100, IID_Position, position); test.AddMock(100, IID_Obstruction, obs); test.AddMock(101, IID_Vision, vision2); test.AddMock(101, IID_Position, position2); test.AddMock(101, IID_Obstruction, obs2); cmp->SetBounds(entity_pos_t::FromInt(0), entity_pos_t::FromInt(0), entity_pos_t::FromInt(512), entity_pos_t::FromInt(512)); cmp->Verify(); { CMessageCreate msg(100); cmp->HandleMessage(msg, false); } { CMessageCreate msg(101); cmp->HandleMessage(msg, false); } { CMessageOwnershipChanged msg(100, -1, 1); cmp->HandleMessage(msg, false); } { CMessageOwnershipChanged msg(101, -1, 1); cmp->HandleMessage(msg, false); } auto move = [&cmp](entity_id_t ent, MockPositionRgm& pos, fixed x, fixed z) { pos.m_Pos = CFixedVector3D(x, fixed::Zero(), z); { CMessagePositionChanged msg(ent, true, x, z, entity_angle_t::Zero()); cmp->HandleMessage(msg, false); } }; move(100, position, fixed::FromInt(10), fixed::FromInt(10)); move(101, position2, fixed::FromInt(10), fixed::FromInt(20)); std::vector nearby = cmp->ExecuteQuery(100, fixed::FromInt(0), fixed::FromInt(4), {1}, 0, true); TS_ASSERT_EQUALS(nearby, std::vector{}); nearby = cmp->ExecuteQuery(100, fixed::FromInt(4), fixed::FromInt(50), {1}, 0, true); TS_ASSERT_EQUALS(nearby, std::vector{101}); move(101, position2, fixed::FromInt(10), fixed::FromInt(10)); nearby = cmp->ExecuteQuery(100, fixed::FromInt(0), fixed::FromInt(4), {1}, 0, true); TS_ASSERT_EQUALS(nearby, std::vector{101}); nearby = cmp->ExecuteQuery(100, fixed::FromInt(4), fixed::FromInt(50), {1}, 0, true); TS_ASSERT_EQUALS(nearby, std::vector{}); move(101, position2, fixed::FromInt(10), fixed::FromInt(13)); nearby = cmp->ExecuteQuery(100, fixed::FromInt(0), fixed::FromInt(4), {1}, 0, true); TS_ASSERT_EQUALS(nearby, std::vector{101}); nearby = cmp->ExecuteQuery(100, fixed::FromInt(4), fixed::FromInt(50), {1}, 0, true); TS_ASSERT_EQUALS(nearby, std::vector{}); move(101, position2, fixed::FromInt(10), fixed::FromInt(15)); // In range thanks to self obstruction size. nearby = cmp->ExecuteQuery(100, fixed::FromInt(0), fixed::FromInt(4), {1}, 0, true); TS_ASSERT_EQUALS(nearby, std::vector{101}); // In range thanks to target obstruction size. nearby = cmp->ExecuteQuery(101, fixed::FromInt(0), fixed::FromInt(4), {1}, 0, true); TS_ASSERT_EQUALS(nearby, std::vector{100}); // Trickier: min-range is closest-to-closest, but rotation may change the real distance. nearby = cmp->ExecuteQuery(100, fixed::FromInt(2), fixed::FromInt(50), {1}, 0, true); TS_ASSERT_EQUALS(nearby, std::vector{101}); nearby = cmp->ExecuteQuery(100, fixed::FromInt(5), fixed::FromInt(50), {1}, 0, true); TS_ASSERT_EQUALS(nearby, std::vector{101}); nearby = cmp->ExecuteQuery(100, fixed::FromInt(6), fixed::FromInt(50), {1}, 0, true); TS_ASSERT_EQUALS(nearby, std::vector{}); nearby = cmp->ExecuteQuery(101, fixed::FromInt(5), fixed::FromInt(50), {1}, 0, true); TS_ASSERT_EQUALS(nearby, std::vector{100}); nearby = cmp->ExecuteQuery(101, fixed::FromInt(6), fixed::FromInt(50), {1}, 0, true); TS_ASSERT_EQUALS(nearby, std::vector{}); } }; Index: ps/trunk/source/simulation2/helpers/LongPathfinder.h =================================================================== --- ps/trunk/source/simulation2/helpers/LongPathfinder.h (revision 25181) +++ ps/trunk/source/simulation2/helpers/LongPathfinder.h (revision 25182) @@ -1,374 +1,372 @@ -/* Copyright (C) 2020 Wildfire Games. +/* Copyright (C) 2021 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_LONGPATHFINDER #define INCLUDED_LONGPATHFINDER #include "Pathfinding.h" #include "graphics/Overlay.h" #include "renderer/Scene.h" #include "renderer/TerrainOverlay.h" #include "simulation2/helpers/Grid.h" #include "simulation2/helpers/PriorityQueue.h" #include /** * Represents the 2D coordinates of a tile. * The i/j components are packed into a single u32, since we usually use these * objects for equality comparisons and the VC2010 optimizer doesn't seem to automatically * compare two u16s in a single operation. * TODO: maybe VC2012 will? */ struct TileID { TileID() { } TileID(u16 i, u16 j) : data((i << 16) | j) { } bool operator==(const TileID& b) const { return data == b.data; } /// Returns lexicographic order over (i,j) bool operator<(const TileID& b) const { return data < b.data; } u16 i() const { return data >> 16; } u16 j() const { return data & 0xFFFF; } private: u32 data; }; /** * Tile data for A* computation. * (We store an array of one of these per terrain tile, so it ought to be optimised for size) */ struct PathfindTile { public: enum { STATUS_UNEXPLORED = 0, STATUS_OPEN = 1, STATUS_CLOSED = 2 }; bool IsUnexplored() const { return GetStatus() == STATUS_UNEXPLORED; } bool IsOpen() const { return GetStatus() == STATUS_OPEN; } bool IsClosed() const { return GetStatus() == STATUS_CLOSED; } void SetStatusOpen() { SetStatus(STATUS_OPEN); } void SetStatusClosed() { SetStatus(STATUS_CLOSED); } // Get pi,pj coords of predecessor to this tile on best path, given i,j coords of this tile inline int GetPredI(int i) const { return i + GetPredDI(); } inline int GetPredJ(int j) const { return j + GetPredDJ(); } inline PathCost GetCost() const { return g; } inline void SetCost(PathCost cost) { g = cost; } private: PathCost g; // cost to reach this tile u32 data; // 2-bit status; 15-bit PredI; 15-bit PredJ; packed for storage efficiency public: inline u8 GetStatus() const { return data & 3; } inline void SetStatus(u8 s) { ASSERT(s < 4); data &= ~3; data |= (s & 3); } int GetPredDI() const { return (i32)data >> 17; } int GetPredDJ() const { return ((i32)data << 15) >> 17; } // Set the pi,pj coords of predecessor, given i,j coords of this tile inline void SetPred(int pi, int pj, int i, int j) { int di = pi - i; int dj = pj - j; ASSERT(-16384 <= di && di < 16384); ASSERT(-16384 <= dj && dj < 16384); data &= 3; data |= (((u32)di & 0x7FFF) << 17) | (((u32)dj & 0x7FFF) << 2); } }; struct CircularRegion { CircularRegion(entity_pos_t x, entity_pos_t z, entity_pos_t r) : x(x), z(z), r(r) {} entity_pos_t x, z, r; }; typedef PriorityQueueHeap PriorityQueue; typedef SparseGrid PathfindTileGrid; class JumpPointCache; struct PathfinderState { u32 steps; // number of algorithm iterations PathGoal goal; u16 iGoal, jGoal; // goal tile pass_class_t passClass; PriorityQueue open; // (there's no explicit closed list; it's encoded in PathfindTile) PathfindTileGrid* tiles; Grid* terrain; PathCost hBest; // heuristic of closest discovered tile to goal u16 iBest, jBest; // closest tile JumpPointCache* jpc; }; class LongOverlay; class HierarchicalPathfinder; class LongPathfinder { public: LongPathfinder(); ~LongPathfinder(); void SetDebugOverlay(bool enabled); void SetDebugPath(const HierarchicalPathfinder& hierPath, entity_pos_t x0, entity_pos_t z0, const PathGoal& goal, pass_class_t passClass) { if (!m_DebugOverlay) return; SAFE_DELETE(m_DebugGrid); delete m_DebugPath; m_DebugPath = new WaypointPath(); ComputePath(hierPath, x0, z0, goal, passClass, *m_DebugPath); m_DebugPassClass = passClass; } void Reload(Grid* passabilityGrid) { m_Grid = passabilityGrid; ASSERT(passabilityGrid->m_H == passabilityGrid->m_W); m_GridSize = passabilityGrid->m_W; m_JumpPointCache.clear(); } void Update(Grid* passabilityGrid) { m_Grid = passabilityGrid; ASSERT(passabilityGrid->m_H == passabilityGrid->m_W); ASSERT(m_GridSize == passabilityGrid->m_H); m_JumpPointCache.clear(); } /** * Compute a tile-based path from the given point to the goal, and return the set of waypoints. * The waypoints correspond to the centers of horizontally/vertically adjacent tiles * along the path. */ void ComputePath(const HierarchicalPathfinder& hierPath, entity_pos_t x0, entity_pos_t z0, const PathGoal& origGoal, pass_class_t passClass, WaypointPath& path) const; /** * Compute a tile-based path from the given point to the goal, excluding the regions * specified in excludedRegions (which are treated as impassable) and return the set of waypoints. * The waypoints correspond to the centers of horizontally/vertically adjacent tiles * along the path. */ void ComputePath(const HierarchicalPathfinder& hierPath, entity_pos_t x0, entity_pos_t z0, const PathGoal& origGoal, pass_class_t passClass, std::vector excludedRegions, WaypointPath& path); void GetDebugData(u32& steps, double& time, Grid& grid) const { GetDebugDataJPS(steps, time, grid); } Grid* m_Grid; u16 m_GridSize; // Debugging - output from last pathfind operation. // mutable as making these const would require a lot of boilerplate code // and they do not change the behavioural const-ness of the pathfinder. mutable LongOverlay* m_DebugOverlay; mutable PathfindTileGrid* m_DebugGrid; mutable u32 m_DebugSteps; mutable double m_DebugTime; mutable PathGoal m_DebugGoal; mutable WaypointPath* m_DebugPath; mutable pass_class_t m_DebugPassClass; private: PathCost CalculateHeuristic(int i, int j, int iGoal, int jGoal) const; void ProcessNeighbour(int pi, int pj, int i, int j, PathCost pg, PathfinderState& state) const; /** * JPS algorithm helper functions * @param detectGoal is not used if m_UseJPSCache is true */ void AddJumpedHoriz(int i, int j, int di, PathCost g, PathfinderState& state, bool detectGoal) const; int HasJumpedHoriz(int i, int j, int di, PathfinderState& state, bool detectGoal) const; void AddJumpedVert(int i, int j, int dj, PathCost g, PathfinderState& state, bool detectGoal) const; int HasJumpedVert(int i, int j, int dj, PathfinderState& state, bool detectGoal) const; void AddJumpedDiag(int i, int j, int di, int dj, PathCost g, PathfinderState& state) const; /** * See LongPathfinder.cpp for implementation details * TODO: cleanup documentation */ void ComputeJPSPath(const HierarchicalPathfinder& hierPath, entity_pos_t x0, entity_pos_t z0, const PathGoal& origGoal, pass_class_t passClass, WaypointPath& path) const; void GetDebugDataJPS(u32& steps, double& time, Grid& grid) const; // Helper functions for ComputePath /** * Given a path with an arbitrary collection of waypoints, updates the - * waypoints to be nicer. Calls "Testline" between waypoints - * so that bended paths can become straight if there's nothing in between - * (this happens because A* is 8-direction, and the map isn't actually a grid). + * waypoints to be nicer. * If @param maxDist is non-zero, path waypoints will be espaced by at most @param maxDist. * In that case the distance between (x0, z0) and the first waypoint will also be made less than maxDist. */ void ImprovePathWaypoints(WaypointPath& path, pass_class_t passClass, entity_pos_t maxDist, entity_pos_t x0, entity_pos_t z0) const; /** * Generate a passability map, stored in the 16th bit of navcells, based on passClass, * but with a set of impassable circular regions. */ void GenerateSpecialMap(pass_class_t passClass, std::vector excludedRegions); bool m_UseJPSCache; // Mutable may be used here as caching does not change the external const-ness of the Long Range pathfinder. // This is thread-safe as it is order independent (no change in the output of the function for a given set of params). // Obviously, this means that the cache should actually be a cache and not return different results // from what would happen if things hadn't been cached. mutable std::map > m_JumpPointCache; }; /** * Terrain overlay for pathfinder debugging. * Renders a representation of the most recent pathfinding operation. */ class LongOverlay : public TerrainTextureOverlay { public: LongPathfinder& m_Pathfinder; LongOverlay(LongPathfinder& pathfinder) : TerrainTextureOverlay(Pathfinding::NAVCELLS_PER_TILE), m_Pathfinder(pathfinder) { } virtual void BuildTextureRGBA(u8* data, size_t w, size_t h) { // Grab the debug data for the most recently generated path u32 steps; double time; Grid debugGrid; m_Pathfinder.GetDebugData(steps, time, debugGrid); // Render navcell passability u8* p = data; for (size_t j = 0; j < h; ++j) { for (size_t i = 0; i < w; ++i) { SColor4ub color(0, 0, 0, 0); if (!IS_PASSABLE(m_Pathfinder.m_Grid->get((int)i, (int)j), m_Pathfinder.m_DebugPassClass)) color = SColor4ub(255, 0, 0, 127); if (debugGrid.m_W && debugGrid.m_H) { u8 n = debugGrid.get((int)i, (int)j); if (n == 1) color = SColor4ub(255, 255, 0, 127); else if (n == 2) color = SColor4ub(0, 255, 0, 127); if (m_Pathfinder.m_DebugGoal.NavcellContainsGoal(i, j)) color = SColor4ub(0, 0, 255, 127); } *p++ = color.R; *p++ = color.G; *p++ = color.B; *p++ = color.A; } } // Render the most recently generated path if (m_Pathfinder.m_DebugPath && !m_Pathfinder.m_DebugPath->m_Waypoints.empty()) { std::vector& waypoints = m_Pathfinder.m_DebugPath->m_Waypoints; u16 ip = 0, jp = 0; for (size_t k = 0; k < waypoints.size(); ++k) { u16 i, j; Pathfinding::NearestNavcell(waypoints[k].x, waypoints[k].z, i, j, m_Pathfinder.m_GridSize, m_Pathfinder.m_GridSize); if (k == 0) { ip = i; jp = j; } else { bool firstCell = true; do { if (data[(jp*w + ip)*4+3] == 0) { data[(jp*w + ip)*4+0] = 0xFF; data[(jp*w + ip)*4+1] = 0xFF; data[(jp*w + ip)*4+2] = 0xFF; data[(jp*w + ip)*4+3] = firstCell ? 0xA0 : 0x60; } ip = ip < i ? ip+1 : ip > i ? ip-1 : ip; jp = jp < j ? jp+1 : jp > j ? jp-1 : jp; firstCell = false; } while (ip != i || jp != j); } } } } }; #endif // INCLUDED_LONGPATHFINDER Index: ps/trunk/source/simulation2/scripting/MessageTypeConversions.cpp =================================================================== --- ps/trunk/source/simulation2/scripting/MessageTypeConversions.cpp (revision 25181) +++ ps/trunk/source/simulation2/scripting/MessageTypeConversions.cpp (revision 25182) @@ -1,567 +1,580 @@ -/* Copyright (C) 2020 Wildfire Games. +/* Copyright (C) 2021 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 "ps/CLogger.h" #include "scriptinterface/ScriptInterface.h" #include "simulation2/MessageTypes.h" #define TOJSVAL_SETUP() \ ScriptRequest rq(scriptInterface); \ JS::RootedObject obj(rq.cx, JS_NewPlainObject(rq.cx)); \ if (!obj) \ return JS::UndefinedValue(); #define SET_MSG_PROPERTY(name) \ do { \ JS::RootedValue prop(rq.cx);\ ScriptInterface::ToJSVal(rq, &prop, this->name); \ if (! JS_SetProperty(rq.cx, obj, #name, prop)) \ return JS::UndefinedValue(); \ } while (0); #define FROMJSVAL_SETUP() \ ScriptRequest rq(scriptInterface); \ if (val.isPrimitive()) \ return NULL; \ JS::RootedObject obj(rq.cx, &val.toObject()); \ JS::RootedValue prop(rq.cx); #define GET_MSG_PROPERTY(type, name) \ type name; \ { \ if (! JS_GetProperty(rq.cx, obj, #name, &prop)) \ return NULL; \ if (! ScriptInterface::FromJSVal(rq, prop, name)) \ return NULL; \ } JS::Value CMessage::ToJSValCached(const ScriptInterface& scriptInterface) const { if (!m_Cached) m_Cached.reset(new JS::PersistentRootedValue(scriptInterface.GetGeneralJSContext(), ToJSVal(scriptInterface))); return m_Cached->get(); } //////////////////////////////// JS::Value CMessageTurnStart::ToJSVal(const ScriptInterface& scriptInterface) const { TOJSVAL_SETUP(); return JS::ObjectValue(*obj); } CMessage* CMessageTurnStart::FromJSVal(const ScriptInterface& UNUSED(scriptInterface), JS::HandleValue UNUSED(val)) { return new CMessageTurnStart(); } //////////////////////////////// #define MESSAGE_1(name, t0, a0) \ JS::Value CMessage##name::ToJSVal(const ScriptInterface& scriptInterface) const \ { \ TOJSVAL_SETUP(); \ SET_MSG_PROPERTY(a0); \ return JS::ObjectValue(*obj); \ } \ CMessage* CMessage##name::FromJSVal(const ScriptInterface& scriptInterface, JS::HandleValue val) \ { \ FROMJSVAL_SETUP(); \ GET_MSG_PROPERTY(t0, a0); \ return new CMessage##name(a0); \ } MESSAGE_1(Update, fixed, turnLength) MESSAGE_1(Update_MotionFormation, fixed, turnLength) MESSAGE_1(Update_MotionUnit, fixed, turnLength) MESSAGE_1(Update_Final, fixed, turnLength) //////////////////////////////// JS::Value CMessageInterpolate::ToJSVal(const ScriptInterface& scriptInterface) const { TOJSVAL_SETUP(); SET_MSG_PROPERTY(deltaSimTime); SET_MSG_PROPERTY(offset); SET_MSG_PROPERTY(deltaRealTime); return JS::ObjectValue(*obj); } CMessage* CMessageInterpolate::FromJSVal(const ScriptInterface& scriptInterface, JS::HandleValue val) { FROMJSVAL_SETUP(); GET_MSG_PROPERTY(float, deltaSimTime); GET_MSG_PROPERTY(float, offset); GET_MSG_PROPERTY(float, deltaRealTime); return new CMessageInterpolate(deltaSimTime, offset, deltaRealTime); } //////////////////////////////// JS::Value CMessageRenderSubmit::ToJSVal(const ScriptInterface& UNUSED(scriptInterface)) const { LOGWARNING("CMessageRenderSubmit::ToJSVal not implemented"); return JS::UndefinedValue(); } CMessage* CMessageRenderSubmit::FromJSVal(const ScriptInterface& UNUSED(scriptInterface), JS::HandleValue UNUSED(val)) { LOGWARNING("CMessageRenderSubmit::FromJSVal not implemented"); return NULL; } //////////////////////////////// JS::Value CMessageProgressiveLoad::ToJSVal(const ScriptInterface& UNUSED(scriptInterface)) const { LOGWARNING("CMessageProgressiveLoad::ToJSVal not implemented"); return JS::UndefinedValue(); } CMessage* CMessageProgressiveLoad::FromJSVal(const ScriptInterface& UNUSED(scriptInterface), JS::HandleValue UNUSED(val)) { LOGWARNING("CMessageProgressiveLoad::FromJSVal not implemented"); return NULL; } //////////////////////////////// JS::Value CMessageDeserialized::ToJSVal(const ScriptInterface& scriptInterface) const { TOJSVAL_SETUP(); return JS::ObjectValue(*obj); } CMessage* CMessageDeserialized::FromJSVal(const ScriptInterface& scriptInterface, JS::HandleValue val) { FROMJSVAL_SETUP(); return new CMessageDeserialized(); } //////////////////////////////// JS::Value CMessageCreate::ToJSVal(const ScriptInterface& scriptInterface) const { TOJSVAL_SETUP(); SET_MSG_PROPERTY(entity); return JS::ObjectValue(*obj); } CMessage* CMessageCreate::FromJSVal(const ScriptInterface& scriptInterface, JS::HandleValue val) { FROMJSVAL_SETUP(); GET_MSG_PROPERTY(entity_id_t, entity); return new CMessageCreate(entity); } //////////////////////////////// JS::Value CMessageDestroy::ToJSVal(const ScriptInterface& scriptInterface) const { TOJSVAL_SETUP(); SET_MSG_PROPERTY(entity); return JS::ObjectValue(*obj); } CMessage* CMessageDestroy::FromJSVal(const ScriptInterface& scriptInterface, JS::HandleValue val) { FROMJSVAL_SETUP(); GET_MSG_PROPERTY(entity_id_t, entity); return new CMessageDestroy(entity); } //////////////////////////////// JS::Value CMessageOwnershipChanged::ToJSVal(const ScriptInterface& scriptInterface) const { TOJSVAL_SETUP(); SET_MSG_PROPERTY(entity); SET_MSG_PROPERTY(from); SET_MSG_PROPERTY(to); return JS::ObjectValue(*obj); } CMessage* CMessageOwnershipChanged::FromJSVal(const ScriptInterface& scriptInterface, JS::HandleValue val) { FROMJSVAL_SETUP(); GET_MSG_PROPERTY(entity_id_t, entity); GET_MSG_PROPERTY(player_id_t, from); GET_MSG_PROPERTY(player_id_t, to); return new CMessageOwnershipChanged(entity, from, to); } //////////////////////////////// JS::Value CMessagePositionChanged::ToJSVal(const ScriptInterface& scriptInterface) const { TOJSVAL_SETUP(); SET_MSG_PROPERTY(entity); SET_MSG_PROPERTY(inWorld); SET_MSG_PROPERTY(x); SET_MSG_PROPERTY(z); SET_MSG_PROPERTY(a); return JS::ObjectValue(*obj); } CMessage* CMessagePositionChanged::FromJSVal(const ScriptInterface& scriptInterface, JS::HandleValue val) { FROMJSVAL_SETUP(); GET_MSG_PROPERTY(entity_id_t, entity); GET_MSG_PROPERTY(bool, inWorld); GET_MSG_PROPERTY(entity_pos_t, x); GET_MSG_PROPERTY(entity_pos_t, z); GET_MSG_PROPERTY(entity_angle_t, a); return new CMessagePositionChanged(entity, inWorld, x, z, a); } //////////////////////////////// JS::Value CMessageInterpolatedPositionChanged::ToJSVal(const ScriptInterface& UNUSED(scriptInterface)) const { LOGWARNING("CMessageInterpolatedPositionChanged::ToJSVal not implemented"); return JS::UndefinedValue(); } CMessage* CMessageInterpolatedPositionChanged::FromJSVal(const ScriptInterface& UNUSED(scriptInterface), JS::HandleValue UNUSED(val)) { LOGWARNING("CMessageInterpolatedPositionChanged::FromJSVal not implemented"); return NULL; } //////////////////////////////// JS::Value CMessageTerritoryPositionChanged::ToJSVal(const ScriptInterface& scriptInterface) const { TOJSVAL_SETUP(); SET_MSG_PROPERTY(entity); SET_MSG_PROPERTY(newTerritory); return JS::ObjectValue(*obj); } CMessage* CMessageTerritoryPositionChanged::FromJSVal(const ScriptInterface& scriptInterface, JS::HandleValue val) { FROMJSVAL_SETUP(); GET_MSG_PROPERTY(entity_id_t, entity); GET_MSG_PROPERTY(player_id_t, newTerritory); return new CMessageTerritoryPositionChanged(entity, newTerritory); } //////////////////////////////// const std::array CMessageMotionUpdate::UpdateTypeStr = { { "likelySuccess", "likelyFailure", "obstructed", "veryObstructed" } }; JS::Value CMessageMotionUpdate::ToJSVal(const ScriptInterface& scriptInterface) const { TOJSVAL_SETUP(); JS::RootedValue prop(rq.cx); if (!JS_SetProperty(rq.cx, obj, UpdateTypeStr[updateType], JS::TrueHandleValue)) return JS::UndefinedValue(); return JS::ObjectValue(*obj); } CMessage* CMessageMotionUpdate::FromJSVal(const ScriptInterface& scriptInterface, JS::HandleValue val) { FROMJSVAL_SETUP(); GET_MSG_PROPERTY(std::wstring, updateString); if (updateString == L"likelySuccess") return new CMessageMotionUpdate(CMessageMotionUpdate::LIKELY_SUCCESS); if (updateString == L"likelyFailure") return new CMessageMotionUpdate(CMessageMotionUpdate::LIKELY_FAILURE); if (updateString == L"obstructed") return new CMessageMotionUpdate(CMessageMotionUpdate::OBSTRUCTED); if (updateString == L"veryObstructed") return new CMessageMotionUpdate(CMessageMotionUpdate::VERY_OBSTRUCTED); LOGWARNING("CMessageMotionUpdate::FromJSVal passed wrong updateString"); return NULL; } //////////////////////////////// JS::Value CMessageTerrainChanged::ToJSVal(const ScriptInterface& scriptInterface) const { TOJSVAL_SETUP(); SET_MSG_PROPERTY(i0); SET_MSG_PROPERTY(j0); SET_MSG_PROPERTY(i1); SET_MSG_PROPERTY(j1); return JS::ObjectValue(*obj); } CMessage* CMessageTerrainChanged::FromJSVal(const ScriptInterface& scriptInterface, JS::HandleValue val) { FROMJSVAL_SETUP(); GET_MSG_PROPERTY(int32_t, i0); GET_MSG_PROPERTY(int32_t, j0); GET_MSG_PROPERTY(int32_t, i1); GET_MSG_PROPERTY(int32_t, j1); return new CMessageTerrainChanged(i0, i1, j0, j1); } //////////////////////////////// JS::Value CMessageVisibilityChanged::ToJSVal(const ScriptInterface& scriptInterface) const { TOJSVAL_SETUP(); SET_MSG_PROPERTY(player); SET_MSG_PROPERTY(ent); SET_MSG_PROPERTY(oldVisibility); SET_MSG_PROPERTY(newVisibility); return JS::ObjectValue(*obj); } CMessage* CMessageVisibilityChanged::FromJSVal(const ScriptInterface& scriptInterface, JS::HandleValue val) { FROMJSVAL_SETUP(); GET_MSG_PROPERTY(player_id_t, player); GET_MSG_PROPERTY(entity_id_t, ent); GET_MSG_PROPERTY(int, oldVisibility); GET_MSG_PROPERTY(int, newVisibility); return new CMessageVisibilityChanged(player, ent, oldVisibility, newVisibility); } //////////////////////////////// JS::Value CMessageWaterChanged::ToJSVal(const ScriptInterface& scriptInterface) const { TOJSVAL_SETUP(); return JS::ObjectValue(*obj); } CMessage* CMessageWaterChanged::FromJSVal(const ScriptInterface& UNUSED(scriptInterface), JS::HandleValue UNUSED(val)) { return new CMessageWaterChanged(); } //////////////////////////////// +JS::Value CMessageMovementObstructionChanged::ToJSVal(const ScriptInterface& scriptInterface) const +{ + TOJSVAL_SETUP(); + return JS::ObjectValue(*obj); +} + +CMessage* CMessageMovementObstructionChanged::FromJSVal(const ScriptInterface& UNUSED(scriptInterface), JS::HandleValue UNUSED(val)) +{ + return new CMessageMovementObstructionChanged(); +} + +//////////////////////////////// + JS::Value CMessageObstructionMapShapeChanged::ToJSVal(const ScriptInterface& scriptInterface) const { TOJSVAL_SETUP(); return JS::ObjectValue(*obj); } CMessage* CMessageObstructionMapShapeChanged::FromJSVal(const ScriptInterface& UNUSED(scriptInterface), JS::HandleValue UNUSED(val)) { return new CMessageObstructionMapShapeChanged(); } //////////////////////////////// JS::Value CMessageTerritoriesChanged::ToJSVal(const ScriptInterface& scriptInterface) const { TOJSVAL_SETUP(); return JS::ObjectValue(*obj); } CMessage* CMessageTerritoriesChanged::FromJSVal(const ScriptInterface& UNUSED(scriptInterface), JS::HandleValue UNUSED(val)) { return new CMessageTerritoriesChanged(); } //////////////////////////////// JS::Value CMessageRangeUpdate::ToJSVal(const ScriptInterface& scriptInterface) const { TOJSVAL_SETUP(); SET_MSG_PROPERTY(tag); SET_MSG_PROPERTY(added); SET_MSG_PROPERTY(removed); return JS::ObjectValue(*obj); } CMessage* CMessageRangeUpdate::FromJSVal(const ScriptInterface& UNUSED(scriptInterface), JS::HandleValue UNUSED(val)) { LOGWARNING("CMessageRangeUpdate::FromJSVal not implemented"); return NULL; } //////////////////////////////// JS::Value CMessagePathResult::ToJSVal(const ScriptInterface& UNUSED(scriptInterface)) const { LOGWARNING("CMessagePathResult::ToJSVal not implemented"); return JS::UndefinedValue(); } CMessage* CMessagePathResult::FromJSVal(const ScriptInterface& UNUSED(scriptInterface), JS::HandleValue UNUSED(val)) { LOGWARNING("CMessagePathResult::FromJSVal not implemented"); return NULL; } //////////////////////////////// JS::Value CMessageValueModification::ToJSVal(const ScriptInterface& scriptInterface) const { TOJSVAL_SETUP(); SET_MSG_PROPERTY(entities); SET_MSG_PROPERTY(component); SET_MSG_PROPERTY(valueNames); return JS::ObjectValue(*obj); } CMessage* CMessageValueModification::FromJSVal(const ScriptInterface& scriptInterface, JS::HandleValue val) { FROMJSVAL_SETUP(); GET_MSG_PROPERTY(std::vector, entities); GET_MSG_PROPERTY(std::wstring, component); GET_MSG_PROPERTY(std::vector, valueNames); return new CMessageValueModification(entities, component, valueNames); } //////////////////////////////// JS::Value CMessageTemplateModification::ToJSVal(const ScriptInterface& scriptInterface) const { TOJSVAL_SETUP(); SET_MSG_PROPERTY(player); SET_MSG_PROPERTY(component); SET_MSG_PROPERTY(valueNames); return JS::ObjectValue(*obj); } CMessage* CMessageTemplateModification::FromJSVal(const ScriptInterface& scriptInterface, JS::HandleValue val) { FROMJSVAL_SETUP(); GET_MSG_PROPERTY(player_id_t, player); GET_MSG_PROPERTY(std::wstring, component); GET_MSG_PROPERTY(std::vector, valueNames); return new CMessageTemplateModification(player, component, valueNames); } //////////////////////////////// JS::Value CMessageVisionRangeChanged::ToJSVal(const ScriptInterface& scriptInterface) const { TOJSVAL_SETUP(); SET_MSG_PROPERTY(entity); SET_MSG_PROPERTY(oldRange); SET_MSG_PROPERTY(newRange); return JS::ObjectValue(*obj); } CMessage* CMessageVisionRangeChanged::FromJSVal(const ScriptInterface& scriptInterface, JS::HandleValue val) { FROMJSVAL_SETUP(); GET_MSG_PROPERTY(entity_id_t, entity); GET_MSG_PROPERTY(entity_pos_t, oldRange); GET_MSG_PROPERTY(entity_pos_t, newRange); return new CMessageVisionRangeChanged(entity, oldRange, newRange); } JS::Value CMessageVisionSharingChanged::ToJSVal(const ScriptInterface& scriptInterface) const { TOJSVAL_SETUP(); SET_MSG_PROPERTY(entity); SET_MSG_PROPERTY(player); SET_MSG_PROPERTY(add); return JS::ObjectValue(*obj); } CMessage* CMessageVisionSharingChanged::FromJSVal(const ScriptInterface& scriptInterface, JS::HandleValue val) { FROMJSVAL_SETUP(); GET_MSG_PROPERTY(entity_id_t, entity); GET_MSG_PROPERTY(player_id_t, player); GET_MSG_PROPERTY(bool, add); return new CMessageVisionSharingChanged(entity, player, add); } //////////////////////////////// JS::Value CMessageMinimapPing::ToJSVal(const ScriptInterface& scriptInterface) const { TOJSVAL_SETUP(); return JS::ObjectValue(*obj); } CMessage* CMessageMinimapPing::FromJSVal(const ScriptInterface& UNUSED(scriptInterface), JS::HandleValue UNUSED(val)) { return new CMessageMinimapPing(); } //////////////////////////////// JS::Value CMessageCinemaPathEnded::ToJSVal(const ScriptInterface& scriptInterface) const { TOJSVAL_SETUP(); SET_MSG_PROPERTY(name); return JS::ObjectValue(*obj); } CMessage* CMessageCinemaPathEnded::FromJSVal(const ScriptInterface& scriptInterface, JS::HandleValue val) { FROMJSVAL_SETUP(); GET_MSG_PROPERTY(CStrW, name); return new CMessageCinemaPathEnded(name); } //////////////////////////////// JS::Value CMessageCinemaQueueEnded::ToJSVal(const ScriptInterface& scriptInterface) const { TOJSVAL_SETUP(); return JS::ObjectValue(*obj); } CMessage* CMessageCinemaQueueEnded::FromJSVal(const ScriptInterface& scriptInterface, JS::HandleValue val) { FROMJSVAL_SETUP(); return new CMessageCinemaQueueEnded(); } //////////////////////////////////////////////////////////////// JS::Value CMessagePlayerColorChanged::ToJSVal(const ScriptInterface& scriptInterface) const { TOJSVAL_SETUP(); SET_MSG_PROPERTY(player); return JS::ObjectValue(*obj); } CMessage* CMessagePlayerColorChanged::FromJSVal(const ScriptInterface& scriptInterface, JS::HandleValue val) { FROMJSVAL_SETUP(); GET_MSG_PROPERTY(player_id_t, player); return new CMessagePlayerColorChanged(player); } //////////////////////////////////////////////////////////////// CMessage* CMessageFromJSVal(int mtid, const ScriptInterface& scriptingInterface, JS::HandleValue val) { switch (mtid) { #define MESSAGE(name) case MT_##name: return CMessage##name::FromJSVal(scriptingInterface, val); #define INTERFACE(name) #define COMPONENT(name) #include "simulation2/TypeList.h" #undef COMPONENT #undef INTERFACE #undef MESSAGE } return NULL; }