Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: added order factory which transform scenario objectives into actionables #5763

Closed
wants to merge 5 commits into from
Closed
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Binary file added MekHQ/data/images/misc/acar_splash_hd.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
20 changes: 12 additions & 8 deletions MekHQ/src/mekhq/MekHQ.java
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,8 @@
import megamek.SuiteConstants;
import megamek.client.Client;
import megamek.client.bot.princess.BehaviorSettings;
import megamek.client.ui.dialogs.AutoResolveChanceDialog;
import megamek.client.ui.dialogs.AutoResolveProgressDialog;
import megamek.client.ui.dialogs.AutoResolveSimulationLogDialog;
import megamek.client.ui.preferences.PreferencesNode;
import megamek.client.ui.preferences.SuitePreferences;
Expand All @@ -37,6 +39,8 @@
import megamek.common.Board;
import megamek.common.annotations.Nullable;
import megamek.common.autoresolve.acar.SimulatedClient;
import megamek.common.autoresolve.acar.order.Orders;
import megamek.common.autoresolve.converter.SingleElementConsolidateForces;
import megamek.common.autoresolve.event.AutoResolveConcludedEvent;
import megamek.common.event.*;
import megamek.common.net.marshalling.SanityInputFilter;
Expand Down Expand Up @@ -645,25 +649,25 @@ public void startAutoResolve(AtBScenario scenario, List<Unit> units) {
this.autosaveService.requestBeforeMissionAutosave(getCampaign());

if (getCampaign().getCampaignOptions().isAutoResolveVictoryChanceEnabled()) {
var proceed = megamek.client.ui.dialogs.AutoResolveChanceDialog
var proceed = AutoResolveChanceDialog
.showDialog(
getCampaigngui().getFrame(),
campaignGUI.getFrame(),
getCampaign().getCampaignOptions().getAutoResolveNumberOfScenarios(),
Runtime.getRuntime().availableProcessors(),
getCampaign().getPlayer().getTeam(),
new AtBSetupForces(getCampaign(), units, scenario),
1,
new AtBSetupForces(getCampaign(), units, scenario, new SingleElementConsolidateForces()),
new Board(scenario.getBaseMapX(), scenario.getBaseMapY())) == JOptionPane.YES_OPTION;
if (!proceed) {
return;
}
}

var event = megamek.client.ui.dialogs.AutoResolveProgressDialog.showDialog(
getCampaigngui().getFrame(),
new AtBSetupForces(getCampaign(), units, scenario),
var event = AutoResolveProgressDialog.showDialog(
campaignGUI.getFrame(),
new AtBSetupForces(getCampaign(), units, scenario, new SingleElementConsolidateForces()),
new Board(scenario.getBaseMapX(), scenario.getBaseMapY()));

var autoResolveBattleReport = new AutoResolveSimulationLogDialog(getCampaigngui().getFrame(), event.getLogFile());
var autoResolveBattleReport = new AutoResolveSimulationLogDialog(campaignGUI.getFrame(), event.getLogFile());
autoResolveBattleReport.setModal(true);
autoResolveBattleReport.setVisible(true);

Expand Down
28 changes: 21 additions & 7 deletions MekHQ/src/mekhq/campaign/autoresolve/AtBSetupForces.java
Original file line number Diff line number Diff line change
Expand Up @@ -19,10 +19,7 @@
import megamek.common.*;
import megamek.common.alphaStrike.conversion.ASConverter;
import megamek.common.autoresolve.acar.SimulationContext;
import megamek.common.autoresolve.converter.ConsolidateForces;
import megamek.common.autoresolve.converter.ForceToFormationConverter;
import megamek.common.autoresolve.converter.SetupForces;
import megamek.common.autoresolve.converter.SingleElementConsolidateForces;
import megamek.common.autoresolve.converter.*;
import megamek.common.copy.CrewRefBreak;
import megamek.common.force.Forces;
import megamek.common.options.OptionsConstants;
Expand Down Expand Up @@ -50,11 +47,20 @@ public class AtBSetupForces extends SetupForces {
private final Campaign campaign;
private final List<Unit> units;
private final AtBScenario scenario;
private final ForceConsolidation forceConsolidationMethod;

public AtBSetupForces(Campaign campaign, List<Unit> units, AtBScenario scenario) {
private final OrderFactory orderFactory;

public AtBSetupForces(Campaign campaign, List<Unit> units, AtBScenario scenario, ForceConsolidation forceConsolidationMethod) {
this(campaign, units, scenario, forceConsolidationMethod, new OrderFactory(campaign, scenario));
}

public AtBSetupForces(Campaign campaign, List<Unit> units, AtBScenario scenario, ForceConsolidation forceConsolidationMethod, OrderFactory orderFactory) {
this.campaign = campaign;
this.units = units;
this.scenario = scenario;
this.forceConsolidationMethod = forceConsolidationMethod;
this.orderFactory = orderFactory;
}

/**
Expand All @@ -64,10 +70,18 @@ public AtBSetupForces(Campaign campaign, List<Unit> units, AtBScenario scenario)
public void createForcesOnSimulation(SimulationContext game) {
setupPlayer(game);
setupBots(game);
ConsolidateForces.consolidateForces(game, new SingleElementConsolidateForces());
forceConsolidationMethod.consolidateForces(game);
convertForcesIntoFormations(game);
}

@Override
public void addOrdersToForces(SimulationContext context) {
var orders = orderFactory.getOrders();
context.getOrders().clear();
context.getOrders().addAll(orders);
context.getOrders().resetOrders();
}

private static class FailedToConvertForceToFormationException extends RuntimeException {
public FailedToConvertForceToFormationException(Throwable cause) {
super(cause);
Expand All @@ -80,7 +94,7 @@ public FailedToConvertForceToFormationException(Throwable cause) {
* and used in the auto resolve in place of the original entities
* @param game The game object to convert the forces in
*/
private static void convertForcesIntoFormations(SimulationContext game) {
private void convertForcesIntoFormations(SimulationContext game) {
for(var force : game.getForces().getTopLevelForces()) {
try {
var formation = new ForceToFormationConverter(force, game).convert();
Expand Down
228 changes: 228 additions & 0 deletions MekHQ/src/mekhq/campaign/autoresolve/OrderFactory.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,228 @@
/*
* Copyright (c) 2024-2025 - The MegaMek Team. All Rights Reserved.
*
* This program 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.
*
* This program 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.
*
*/

package mekhq.campaign.autoresolve;

import megamek.common.Entity;
import megamek.common.OffBoardDirection;
import megamek.common.autoresolve.acar.order.Condition;
import megamek.common.autoresolve.acar.order.Order;
import megamek.common.autoresolve.acar.order.OrderType;
import megamek.common.autoresolve.acar.order.Orders;
import megamek.logging.MMLogger;
import mekhq.campaign.Campaign;
import mekhq.campaign.mission.Scenario;
import mekhq.campaign.mission.ScenarioObjective;

import java.util.Set;

/**
* @author Luana Coppio
*/
public class OrderFactory {
private static final MMLogger logger = MMLogger.create(OrderFactory.class);

private final Campaign campaign;
private final Scenario scenario;
private Orders orders;

public OrderFactory(Campaign campaign, Scenario scenario) {
this.campaign = campaign;
this.scenario = scenario;
}

public Orders getOrders() {
this.orders = new Orders();
var scenarioObjectives = scenario.getScenarioObjectives();
for (var objective : scenarioObjectives) {
createOrderFromObjective(campaign.getPlayer().getId(), objective);
}
return orders;
}

private void addOrder(Order order) {
logger.info("Adding order {}", order);
this.orders.add(order);
}

private void createOrderFromObjective(int ownerId, ScenarioObjective objective) {

switch (objective.getObjectiveCriterion()) {
case Capture: // no capture, only destroy!
case Destroy:
createDestroyOrder(ownerId, objective);
break;
case Preserve:
createPreserveOrder(ownerId, objective);
break;
case ReachMapEdge:
createReachMapEdgeOrder(ownerId, objective);
break;
case ForceWithdraw:
createForceWithdrawOrder(ownerId, objective);
break;
case PreventReachMapEdge:
createPreventReachMapEdgeOrder(ownerId, objective);
break;
case Custom:
default:
// do nothing for custom bc what can be done?
break;
};
}
// Make the enemy withdraw
private void createForceWithdrawOrder(int ownerId, ScenarioObjective objective) {
Fixed Show fixed Hide fixed
var orderBuilder = Order.OrderBuilder.anOrder(ownerId, OrderType.ATTACK_TARGET_NOT_WITHDRAWING)
.withCondition(Condition.alwaysTrue());
addOrder(orderBuilder.build());
}

private void createReachMapEdgeOrder(int ownerId, ScenarioObjective objective) {
if (objective.getDestinationEdge() != null && objective.getDestinationEdge() != OffBoardDirection.NONE) {
var northSide = Set.of(OffBoardDirection.NORTH, OffBoardDirection.EAST);
var orderType = northSide.contains(objective.getDestinationEdge()) ? OrderType.FLEE_NORTH : OrderType.FLEE_SOUTH;
var orderBuilder = Order.OrderBuilder.anOrder(ownerId, orderType)
.withCondition(Condition.alwaysTrue());
orders.add(orderBuilder.build());
} else {
var orderBuilder = Order.OrderBuilder.anOrder(ownerId, scenario.getStartingPos() > 4 ? OrderType.FLEE_NORTH : OrderType.FLEE_SOUTH)
.withCondition(Condition.alwaysTrue());
addOrder(orderBuilder.build());
}
}

private void createPreventReachMapEdgeOrder(int ownerId, ScenarioObjective objective) {
Fixed Show fixed Hide fixed
var orderBuilder = Order.OrderBuilder.anOrder(ownerId, OrderType.ATTACK_TARGET_WITHDRAWING)
.withCondition(Condition.alwaysTrue());
addOrder(orderBuilder.build());
}

private void createPreserveOrder(int ownerId, ScenarioObjective objective) {
if (!objective.getAssociatedForceNames().isEmpty()) {
var order = createOrderForPreserveAssociatedForces(ownerId, objective);
addOrder(order);
}
if (!objective.getAssociatedUnitIDs().isEmpty()) {
var order = createOrderForPreserveAssociatedUnits(ownerId, objective);
addOrder(order);
}
}

private Order createOrderForPreserveAssociatedForces(int ownerId, ScenarioObjective objective) {
Scoppio marked this conversation as resolved.
Show resolved Hide resolved
var orderBuilder = Order.OrderBuilder.anOrder(ownerId, OrderType.WITHDRAW_IF_CONDITION_IS_MET)
.withCondition(context -> {
var attackTypeOrders = Set.of(OrderType.ATTACK_TARGET, OrderType.ATTACK_TARGET_NOT_WITHDRAWING, OrderType.ATTACK_TARGET_WITHDRAWING);
var hasOutstandingAttackOrders = context.getOrders().getOrders(ownerId).stream()
.filter(o -> attackTypeOrders.contains(o.getOrderType())).anyMatch(order -> order.isEligible(context));
int totalUnits = 0;
var currentUnits = 0;
for (var forceName : objective.getAssociatedForceNames()) {
for (var force : context.getForces().getTopLevelForces()) {
if (force.getName().equals(forceName)) {
totalUnits += force.getEntities().size();
for (var entityId : force.getEntities()) {
currentUnits += context.getSelectedEntityCount(entity -> entity.getId() == entityId);
}
}
}
}

if (totalUnits == 0) {
return true;
} else {

var timeLimit = false;
if (objective.getTimeLimitType() != ScenarioObjective.TimeLimitType.None && objective.isTimeLimitAtMost()) {
timeLimit = context.getCurrentRound() >= objective.getTimeLimit();
}
if (!hasOutstandingAttackOrders) {
if (objective.getAmountType().equals(ScenarioObjective.ObjectiveAmountType.Fixed)) {
return currentUnits < objective.getFixedAmount() || timeLimit;
} else {
int percent = (int) ((totalUnits / (double) currentUnits) * 100);
return percent < objective.getPercentage() || timeLimit;
}
} else {
if (timeLimit) {
return context.getCurrentRound() >= objective.getTimeLimit();
} else {
return true;
}
}
}
});
Scoppio marked this conversation as resolved.
Show resolved Hide resolved

return orderBuilder.build();
}

private Order createOrderForPreserveAssociatedUnits(int ownerId, ScenarioObjective objective) {
Scoppio marked this conversation as resolved.
Show resolved Hide resolved
var orderBuilder = Order.OrderBuilder.anOrder(ownerId, OrderType.WITHDRAW_IF_CONDITION_IS_MET)
.withCondition(context -> {
var inGameObjects = context.getInGameObjects();
var unitIds = objective.getAssociatedUnitIDs();
var entitiesOfInterest = inGameObjects.stream().filter(Entity.class::isInstance).map(Entity.class::cast)
.filter(e -> e.getOwnerId() == ownerId).toList();
var currentUnits = 0;
var totalUnits = unitIds.size();
if (totalUnits == 0) {
return true;
}
for (var unit : entitiesOfInterest) {
if (unitIds.contains(unit.getExternalIdAsString())) {
currentUnits++;
}
}
var timeLimit = false;
if (objective.getTimeLimitType() != ScenarioObjective.TimeLimitType.None && objective.isTimeLimitAtMost()) {
timeLimit = context.getCurrentRound() >= objective.getTimeLimit();
}
if (objective.getAmountType().equals(ScenarioObjective.ObjectiveAmountType.Fixed)) {
return currentUnits < objective.getFixedAmount() || timeLimit;
} else {
int percent = (int) ((totalUnits / (double) currentUnits) * 100);
return percent < objective.getPercentage() || timeLimit;
}
});
Scoppio marked this conversation as resolved.
Show resolved Hide resolved
return orderBuilder.build();
}

private void createDestroyOrder(int ownerId, ScenarioObjective objective) {
var orderBuilder = Order.OrderBuilder.anOrder(ownerId, OrderType.ATTACK_TARGET);
if (objective.getPercentage() == 100) {
orderBuilder.withCondition(Condition.alwaysTrue());
} else {
orderBuilder.withCondition(context -> {
var enemyPlayers = context.getPlayersList().stream().filter(p -> p.isEnemyOf(campaign.getPlayer())).toList();
var totalUnits = 0;
var currentUnits = 0;
for (var player: enemyPlayers) {
totalUnits += context.getStartingNumberOfUnits(player.getId());
currentUnits += context.getActiveFormations(player).size();
}

if (totalUnits == 0) {
return true;
}
if (objective.getAmountType().equals(ScenarioObjective.ObjectiveAmountType.Fixed)) {
return (totalUnits - currentUnits) < objective.getFixedAmount();
} else {
var currentPercent = 100 - (int) (currentUnits / (double) totalUnits);
return (objective.getPercentage() - currentPercent) > 0;
}
});
}
addOrder(orderBuilder.build());
}
}
7 changes: 3 additions & 4 deletions MekHQ/unittests/mekhq/campaign/autoresolve/ResolverTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,8 @@
import megamek.common.*;
import megamek.common.autoresolve.Resolver;
import megamek.common.autoresolve.acar.SimulationOptions;
import megamek.common.autoresolve.acar.order.Orders;
import megamek.common.autoresolve.converter.SingleElementConsolidateForces;
import megamek.common.autoresolve.event.AutoResolveConcludedEvent;
import megamek.common.enums.Gender;
import megamek.common.enums.SkillLevel;
Expand Down Expand Up @@ -195,12 +197,9 @@ Campaign createCampaign() {
var reputationController = mock(ReputationController.class);
when(reputationController.getAverageSkillLevel()).thenReturn(SkillLevel.REGULAR);


campaign.setReputation(reputationController);

var force = new Force("Heroes");
campaign.addForce(force, campaign.getForce(0));

return campaign;
}

Expand Down Expand Up @@ -354,7 +353,7 @@ void autoResolve(Consumer<AutoResolveConcludedEvent> autoResolveConcludedEvent)
when(botForce.getTeam()).thenReturn(2);
when(botForce.getFullEntityList(any())).thenReturn(entities);

var resolver = Resolver.simulationRun(new AtBSetupForces(campaign, units, scenario), SimulationOptions.empty(), new Board(30, 30));
var resolver = Resolver.simulationRun(new AtBSetupForces(campaign, units, scenario, new SingleElementConsolidateForces()), SimulationOptions.empty(), new Board(30, 30));
autoResolveConcludedEvent.accept(resolver.resolveSimulation());
}

Expand Down
Loading