Compare commits

...

3 Commits

19 changed files with 1488 additions and 260 deletions

View File

@@ -86,16 +86,12 @@ public class FireRuleController extends BaseController {
return success(ruleService.getComponents(platformId));
}
/**
* 开始执行规则匹配
* @param task 敌方参数
* @return
*/
@PostMapping("/rule")
/* @PostMapping("/rule")
@ApiOperation("开始执行规则匹配")
public AjaxResult execute(@RequestBody Task task){
return success(ruleService.executeTask(task));
}
}*/
/**

View File

@@ -0,0 +1,33 @@
package com.solution.rule.config;
import java.util.HashMap;
import java.util.Map;
/**
* 装备匹配规则默认参数,与 {@code resources/rules/rule.drl} 中 {@code buildParam} 键保持一致。
*/
public final class FireRuleMatchDefaultParams {
private FireRuleMatchDefaultParams() {
}
public static Map<String, Object> defaults() {
Map<String, Object> param = new HashMap<>();
param.put("weight", 1);
param.put("minSelectedScore", 1);
param.put("tankScore", 1);
param.put("airScore", 2);
param.put("groundScore", 1);
param.put("missileScore", 1);
param.put("airTaskScore", 10);
param.put("bluePlatformKeywords_air", "F-16,J-10,F-35");
param.put("redPreferredWhenBlueAir", "防空,导弹,无人机,直升机,空空");
param.put("redPreferredWhenGround", "远火,榴弹,炮,火箭");
param.put("airTaskKeywords", "空中,制空,拦截,空战");
param.put("groundTaskKeywords", "地面,突击,登陆");
param.put("tankKeywords", "坦克,装甲");
param.put("missileKeywords", "导弹,火箭弹,巡航");
param.put("tieBreak", "equipmentId");
return param;
}
}

View File

@@ -1,6 +1,7 @@
package com.solution.rule.domain.ultimately.dto;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonProperty;
import lombok.Data;
import java.util.List;
@@ -23,7 +24,14 @@ public class FireRuleInputDTO {
private List<FireRuleTaskInputDTO> tasks;
/**
* 红方侧异构条目列表(武器、场景任务节点、装备、指挥所、防区等)
* 红方装备等条目列表,对应 JSON 键 {@code redWeapons}(当前 {@link FireRuleInputRedWeaponElementDTO} 与装备结构一致)
*/
private List<FireRuleInputRedWeaponElementDTO> redWeapons;
@JsonProperty("equipments")
private List<FireRuleInputRedWeaponElementDTO> equipments;
/**
* 阵营与姿态关系列表,对应 JSON 键 {@code ForceSides}
*/
@JsonProperty("ForceSides")
private List<FireRuleInputForceSideDTO> forceSides;
}

View File

@@ -0,0 +1,19 @@
package com.solution.rule.domain.ultimately.dto;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonProperty;
import lombok.Data;
/**
* 阵营侧一方与其它方的姿态关系项
*/
@Data
@JsonIgnoreProperties(ignoreUnknown = true)
public class FireRuleInputForcePostureDTO {
@JsonProperty("ObjectHandle")
private String objectHandle;
@JsonProperty("Type")
private Integer type;
}

View File

@@ -0,0 +1,26 @@
package com.solution.rule.domain.ultimately.dto;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonProperty;
import lombok.Data;
import java.util.List;
/**
* 阵营侧(ForceSides 数组中的一项)
*/
@Data
@JsonIgnoreProperties(ignoreUnknown = true)
public class FireRuleInputForceSideDTO {
private String groupType;
@JsonProperty("Postures")
private List<FireRuleInputForcePostureDTO> postures;
@JsonProperty("ObjectHandle")
private String objectHandle;
@JsonProperty("ForceSideName")
private String forceSideName;
}

View File

@@ -1,20 +0,0 @@
package com.solution.rule.domain.ultimately.dto;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import lombok.Data;
/**
* 防区圆形条目中 isWing 为对象时的样式字段
*/
@Data
@JsonIgnoreProperties(ignoreUnknown = true)
public class FireRuleInputRedCircleStyleDTO {
private String outlineWidth;
private String lineType;
private String outlineColor;
private String color;
}

View File

@@ -1,34 +0,0 @@
package com.solution.rule.domain.ultimately.dto;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import lombok.Data;
import java.util.List;
/**
* redWeapons 条目中 isLead:可能是长机编队参数,也可能是圆形防区参数(字段并集)
*/
@Data
@JsonIgnoreProperties(ignoreUnknown = true)
public class FireRuleInputRedLeadPayloadDTO {
private String leader;
private String side;
private String supportType;
private List<FireRuleInputRedLeadPositionDTO> positions;
private String drawName;
private String airspaceType;
private String selectLonLat;
private String radius;
private String height;
private String extrudedHeight;
}

View File

@@ -1,18 +0,0 @@
package com.solution.rule.domain.ultimately.dto;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import lombok.Data;
/**
* 长机/圆形等结构中的坐标点(示例中可能为数值或占位字符串)
*/
@Data
@JsonIgnoreProperties(ignoreUnknown = true)
public class FireRuleInputRedLeadPositionDTO {
private String longitude;
private String latitude;
private String height;
}

View File

@@ -4,44 +4,16 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonProperty;
import lombok.Data;
import java.util.List;
import java.util.Map;
/**
* 输入 JSON 中 {@code redWeapons} 数组元素并集:武器摘要、红方装备、营指挥所、防区圆形等形态共用此类。
* <p>
* {@code isWing} 在 JSON 中可能为僚机数组或圆形样式对象,故使用 {@link Object} 承接;可结合
* {@link FireRuleInputRedWingItemDTO}、{@link FireRuleInputRedCircleStyleDTO} 在业务层转型。
* {@code redWeapons} 中红方装备(platform)条目,与 {@code 火力规则输入-无注释.json} 中带
* {@code SubComponents} 的装备对象字段一致。
*/
@Data
@JsonIgnoreProperties(ignoreUnknown = true)
public class FireRuleInputRedWeaponElementDTO {
private String name;
@JsonProperty("Name")
private String displayName;
private String id;
@JsonProperty("EquipmentID")
private String equipmentId;
private List<FireRuleWeaponComponentDTO> components;
private Object number;
private String successTargetRad;
private FireRuleInputRedLeadPayloadDTO isLead;
private Object isWing;
/**
* 装备类条目中为 {@code equipment} 等
*/
private String groupType;
@JsonProperty("SupportType")
private String supportType;
@@ -58,6 +30,16 @@ public class FireRuleInputRedWeaponElementDTO {
private Boolean isInterferenceTarget;
private Boolean isDefendImportantPlace;
//命中率
private Double successTargetRad;
private String groupType;
@JsonProperty("EquipmentID")
private String equipmentId;
@JsonProperty("Name")
private String name;
@JsonProperty("OwnerForceSide")
private String ownerForceSide;

View File

@@ -1,17 +0,0 @@
package com.solution.rule.domain.ultimately.dto;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import lombok.Data;
@Data
@JsonIgnoreProperties(ignoreUnknown = true)
public class FireRuleInputRedWingItemDTO {
private String name;
private String distance;
private String angle;
private String alt;
}

View File

@@ -32,6 +32,11 @@ public class FireRuleTaskInputDTO {
*/
private String side;
/**
* 蓝方任务装备命中率
*/
private Double successTargetRad;
/**
* 航迹所属实体或阵营标识
*/

View File

@@ -1,7 +1,6 @@
/**
* 火力规则输入侧 DTO,与 {@code resources/json/火力规则输入-无注释.json} 对齐。
* <p>
* {@code redWeapons} 数组元素为并集类型 {@link com.solution.rule.domain.ultimately.dto.FireRuleInputRedWeaponElementDTO},
* 常见形态包括:武器摘要、红方装备(含子组件)、营指挥所、防区圆形等。
* {@code redWeapons} 中装备项为 {@link com.solution.rule.domain.ultimately.dto.FireRuleInputRedWeaponElementDTO}(含 {@code SubComponents})。
*/
package com.solution.rule.domain.ultimately.dto;

View File

@@ -29,6 +29,8 @@ public class FireRuleRedWeaponEquipmentVO {
private Boolean isInterferenceTarget;
private Boolean isDefendImportantPlace;
//命中率
private Double successTargetRad;
private String groupType;

View File

@@ -1,120 +0,0 @@
//package com.solution.rule.parser;
//
//import com.fasterxml.jackson.core.JsonParser;
//import com.fasterxml.jackson.core.JsonToken;
//import com.fasterxml.jackson.databind.ObjectMapper;
//import javax.servlet.http.HttpServletRequest;
//import java.io.IOException;
//import java.util.*;
//
//public class JsonStreamParser {
//
// // 核心:解析所有集合 → 内存关联ID → 组装完整数据
// public List<AssembledWeapon> parseAndAssemble(HttpServletRequest request) throws IOException {
// ObjectMapper mapper = new ObjectMapper();
// try (JsonParser parser = mapper.getFactory().createParser(request.getInputStream())) {
//
// // ========== 步骤1:流式解析,把所有关联集合存到内存 ==========
// String version = null;
// // 存储所有集合:key=集合名(weaponList/weaponParams),value=数据列表
// Map<String, List<Map<String, Object>>> allCollections = new HashMap<>();
//
// // 解析状态
// String currentCollection = null;
// Map<String, Object> currentItem = null;
//
// JsonToken token;
// while ((token = parser.nextToken()) != null) {
// switch (token) {
// case START_OBJECT:
// if (currentCollection != null) currentItem = new HashMap<>();
// break;
// case END_OBJECT:
// if (currentCollection != null && currentItem != null) {
// allCollections.get(currentCollection).add(currentItem);
// currentItem = null;
// }
// break;
// case START_ARRAY:
// currentCollection = parser.getCurrentName();
// allCollections.putIfAbsent(currentCollection, new ArrayList<>());
// break;
// case END_ARRAY:
// currentCollection = null;
// break;
// case FIELD_NAME:
// String field = parser.getCurrentName();
// // 解析版本号
// if ("version".equals(field) && isInMeta(parser)) {
// version = parser.nextTextValue();
// break;
// }
// // 解析普通字段
// if (currentItem != null) {
// parser.nextToken();
// currentItem.put(field, getValue(parser));
// }
// break;
// }
// }
//
// // ========== 步骤2:核心!通过ID关联匹配,组装完整数据 ==========
// return assembleFullWeaponData(allCollections);
// }
// }
//
// /**
// * 【核心逻辑】ID关联匹配:武器列表 + 参数列表 → 完整武器
// */
// private List<AssembledWeapon> assembleFullWeaponData(Map<String, List<Map<String, Object>>> allCollections) {
// List<AssembledWeapon> result = new ArrayList<>();
//
// // 1. 获取武器主列表
// List<Map<String, Object>> weaponList = allCollections.getOrDefault("weaponList", Collections.emptyList());
// // 2. 获取武器参数列表
// List<Map<String, Object>> paramList = allCollections.getOrDefault("weaponParams", Collections.emptyList());
//
// // 3. 构建【ID -> 参数】索引Map(O(1)快速匹配,效率最高)
// Map<Long, Map<String, Object>> paramIndex = new HashMap<>();
// for (Map<String, Object> param : paramList) {
// Long weaponId = Long.valueOf(param.get("weaponId").toString());
// paramIndex.put(weaponId, param);
// }
//
// // 4. 遍历武器,通过ID匹配参数,组装完整对象
// for (Map<String, Object> weapon : weaponList) {
// AssembledWeapon fullWeapon = new AssembledWeapon();
// Long weaponId = Long.valueOf(weapon.get("id").toString());
//
// // 填充基础信息
// fullWeapon.setId(weaponId);
// fullWeapon.setName((String) weapon.get("name"));
//
// // 匹配参数(通过ID)
// Map<String, Object> param = paramIndex.get(weaponId);
// if (param != null) {
// fullWeapon.setDamage(Integer.valueOf(param.get("damage").toString()));
// fullWeapon.setMagazine(Integer.valueOf(param.get("magazine").toString()));
// fullWeapon.setType((String) param.get("type"));
// }
//
// result.add(fullWeapon);
// }
//
// return result;
// }
//
// // ---------------- 工具方法 ----------------
// private boolean isInMeta(JsonParser parser) {
// return parser.getParsingContext().getParent() != null
// && "meta".equals(parser.getParsingContext().getParent().getCurrentName());
// }
//
// private Object getValue(JsonParser parser) throws IOException {
// if (parser.getCurrentToken().isNumeric()) return parser.getLongValue();
// if (parser.getCurrentToken() == JsonToken.VALUE_STRING) return parser.getText();
// if (parser.getCurrentToken() == JsonToken.VALUE_TRUE) return true;
// if (parser.getCurrentToken() == JsonToken.VALUE_FALSE) return false;
// return null;
// }
//}

View File

@@ -9,8 +9,10 @@ import com.solution.rule.domain.simplerulepojo.Task;
import com.solution.rule.domain.simplerulepojo.Weapon;
import com.solution.rule.domain.simplerulepojo.fact.FactTask;
import com.solution.rule.domain.ultimately.dto.FireRuleInputDTO;
import com.solution.rule.domain.ultimately.dto.FireRuleInputForceSideDTO;
import com.solution.rule.domain.ultimately.dto.FireRuleInputRedWeaponElementDTO;
import com.solution.rule.domain.ultimately.dto.FireRuleTaskInputDTO;
import com.solution.rule.config.FireRuleMatchDefaultParams;
import com.solution.rule.domain.ultimately.fact.DroolsFact;
import com.solution.rule.domain.ultimately.vo.FireRuleOutputVO;
import com.solution.rule.domain.vo.ComponentCountVO;
@@ -26,6 +28,7 @@ import com.solution.rule.strategy.SceneStrategy;
import com.solution.rule.strategy.SceneStrategyFactory;
import org.kie.api.KieBase;
import org.kie.api.runtime.KieSession;
import org.kie.api.runtime.rule.FactHandle;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@@ -196,7 +199,7 @@ public class FireRuleServiceImpl implements FireRuleService {
* @return
*/
@Override
public FireRuleOutputVO rule(FireRuleInputDTO task) {
public FireRuleOutputVO rule(FireRuleInputDTO task) {
if(ObjectUtil.isEmpty(task)){
throw new RuntimeException(ExceptionConstants.PARAMETER_EXCEPTION);
}
@@ -206,26 +209,46 @@ public class FireRuleServiceImpl implements FireRuleService {
}
//创建KieSession
KieSession kieSession = kieBase.newKieSession();
//设置Drools全局变量
Map<String, Object> globalParams = new HashMap<>();
// globalParams.putAll(FireRuleMatchDefaultParams.defaults());
kieSession.setGlobal("globalParams", globalParams);
//获取红方阵营id
String redObjectHandleId = getObjectHandle(task);
if(ObjectUtil.isEmpty(redObjectHandleId)){
throw new RuntimeException(ExceptionConstants.PARAMETER_EXCEPTION);
}
//获取所有武器库
List<FireRuleInputRedWeaponElementDTO> allWeapons = task.getEquipments();
//获取红方武器库
List<FireRuleInputRedWeaponElementDTO> redWeapons = task.getRedWeapons();
List<FireRuleInputRedWeaponElementDTO> redWeapons = allWeapons.stream()
.filter(weapon -> redObjectHandleId.equals(weapon.getOwnerForceSide()))
.collect(Collectors.toList());
//创建返回数据
FireRuleOutputVO fireRuleOutputVO = new FireRuleOutputVO();
fireRuleOutputVO.setSourceFile(task.getSourceFile());
DroolsFact droolsFact = new DroolsFact();
droolsFact.setRedWeapons(redWeapons);
// droolsFact.getFireRuleOutputVO().setRedWeapons(redWeapons);
droolsFact.setRedWeapons(new ArrayList<>(redWeapons));
droolsFact.setFireRuleOutputVO(fireRuleOutputVO);
for (FireRuleTaskInputDTO fireRuleTaskInputDTO : tasks) {
droolsFact.setTask(fireRuleTaskInputDTO);
kieSession.insert(droolsFact);
FactHandle droolsFactHandle = null;
try {
for (FireRuleTaskInputDTO fireRuleTaskInputDTO : tasks) {
droolsFact.setTask(fireRuleTaskInputDTO);
if (droolsFactHandle == null) {
droolsFactHandle = kieSession.insert(droolsFact);
} else {
kieSession.update(droolsFactHandle, droolsFact);
}
kieSession.fireAllRules();
}
} finally {
kieSession.dispose();
}
return droolsFact.getFireRuleOutputVO();
return fireRuleOutputVO;
}
/**
@@ -259,4 +282,15 @@ public class FireRuleServiceImpl implements FireRuleService {
return ruleMapper.findAllBasicPlatformComponents();
}
/**
* 获取红方阵营id
* @param task
* @return
*/
private String getObjectHandle(FireRuleInputDTO task){
List<FireRuleInputForceSideDTO> forceSides = task.getForceSides();
List<FireRuleInputForceSideDTO> collect = forceSides.stream().filter(f -> "红方".equals(f.getForceSideName())).collect(Collectors.toList());
return collect.get(0).getObjectHandle();
}
}

View File

@@ -0,0 +1,690 @@
package com.solution.rule.utils;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.solution.rule.domain.ultimately.dto.FireRuleInputRedSubComponentsDTO;
import com.solution.rule.domain.ultimately.dto.FireRuleCoordinateDTO;
import com.solution.rule.domain.ultimately.dto.FireRuleTrackPointDTO;
import com.solution.rule.domain.ultimately.dto.FireRuleTaskInputDTO;
import com.solution.rule.domain.ultimately.dto.FireRuleTaskWeaponDTO;
import com.solution.rule.domain.ultimately.dto.FireRuleWeaponComponentDTO;
import com.solution.rule.domain.ultimately.dto.FireRuleComponentParamDTO;
import com.solution.rule.domain.ultimately.vo.FireRuleLauncherConfigurationVO;
import com.solution.rule.domain.ultimately.vo.FireRuleExecuteBlockVO;
import com.solution.rule.domain.ultimately.vo.FireRuleExecuteTargetItemVO;
import com.solution.rule.domain.ultimately.vo.FireRuleMissionListItemVO;
import com.solution.rule.domain.ultimately.vo.FireRuleMountedWeaponRefVO;
import com.solution.rule.domain.ultimately.vo.FireRuleRedSubComponentsVO;
import com.solution.rule.domain.ultimately.vo.FireRuleRedWeaponEquipmentVO;
import com.solution.rule.domain.ultimately.vo.FireRuleRedPlatformSlotVO;
import com.solution.rule.domain.ultimately.vo.FireRuleRedWeaponSlotVO;
import com.solution.rule.domain.ultimately.vo.FireRuleSceneTaskNodeVO;
import com.solution.rule.domain.ultimately.vo.FireRuleSceneTaskPayloadVO;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* 将入参中的红方装备 {@code SubComponents}(DTO)转为输出 VO,保持与原始 JSON 结构一致。
*/
public final class FireRuleRedWeaponOutputFillHelper {
private static final ObjectMapper MAPPER = new ObjectMapper()
.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
private FireRuleRedWeaponOutputFillHelper() {
}
/**
* DTO 与 VO 字段/JsonProperty 对齐,通过 Jackson 树转换实现原样输出。
*/
public static FireRuleRedSubComponentsVO toOutputSubComponents(FireRuleInputRedSubComponentsDTO src) {
if (src == null) {
return null;
}
return MAPPER.convertValue(src, FireRuleRedSubComponentsVO.class);
}
/**
* 将输出 redWeapons 单项映射为 Tasks 节点(一个装备 -> 一个任务节点)。
*
* <p>字段映射约定:</p>
* <ul>
* <li>drawName = Name + \"打击任务\"</li>
* <li>side = OwnerForceSide(按你的要求直接复制)</li>
* <li>id 优先 EquipmentID,其次 PlatID,最后用 index 兜底</li>
* <li>task.payload.weaponId = EquipmentID</li>
* <li>task.payload.sideId = OwnerForceSide</li>
* <li>missionList:尽量从 SubComponents.weapon[*] 中提取 mountedWeapon/name/number/launcherType</li>
* </ul>
*/
public static FireRuleSceneTaskNodeVO toTaskNode(FireRuleRedWeaponEquipmentVO redWeapon, int index) {
FireRuleSceneTaskNodeVO node = new FireRuleSceneTaskNodeVO();
if (redWeapon == null) {
node.setId("redWeaponTask_" + index);
node.setDrawName("打击任务");
return node;
}
String name = nz(redWeapon.getName());
node.setName(name);
node.setDrawName(name + "打击任务");
node.setId(buildNodeId(redWeapon, index));
node.setSide(redWeapon.getOwnerForceSide());
// 按你的要求写死 Tasks 节点的展示字段
node.setColor("rgb(220, 39, 39)");
node.setDataType("taskPlane");
node.setGroupType("tasks");
node.setShow(true);
node.setIsSelected(false);
node.setSort((long) index);
FireRuleSceneTaskPayloadVO payload = new FireRuleSceneTaskPayloadVO();
payload.setName(name);
payload.setWeaponId(redWeapon.getEquipmentId());
payload.setSideId(redWeapon.getOwnerForceSide());
payload.setMissionList(buildMissionList(redWeapon));
node.setTask(payload);
return node;
}
/**
* 批量转换:redWeapons 有几个就生成几个 Tasks。
*/
public static List<FireRuleSceneTaskNodeVO> toTaskNodes(List<FireRuleRedWeaponEquipmentVO> redWeapons) {
if (redWeapons == null || redWeapons.isEmpty()) {
return Collections.emptyList();
}
List<FireRuleSceneTaskNodeVO> list = new ArrayList<>(redWeapons.size());
for (int i = 0; i < redWeapons.size(); i++) {
list.add(toTaskNode(redWeapons.get(i), i));
}
return list;
}
/**
* 阵位填充:写入每个 redWeapon 的 SubComponents.platform[].positions = [lon,lat,height]。
* 混合模式:蓝方武器坐标中心为锚点 + 航迹方位偏移 + 编队偏移 + 作战区约束。
*/
@SuppressWarnings("rawtypes")
public static void fillPlatformPositions(List<FireRuleRedWeaponEquipmentVO> redWeapons, FireRuleTaskInputDTO blueTask, Map params) {
if (redWeapons == null || redWeapons.isEmpty() || blueTask == null) {
return;
}
Coord anchor = computeBlueAnchor(blueTask);
if (anchor == null) {
return;
}
double bearingDeg = computeTrackBearingDeg(blueTask, str(params, "trackPointDirectionMode", "head2next"),
readDouble(params, "fallbackBearingDeg", 0d));
double minKm = readDouble(params, "deployDistanceKmMin", 8d);
double maxKm = readDouble(params, "deployDistanceKmMax", 30d);
double defKm = readDouble(params, "deployDistanceKmDefault", 15d);
String formation = str(params, "formationType", "line");
double spacingM = readDouble(params, "formationSpacingMeters", 300d);
double headingOffset = readDouble(params, "formationHeadingOffsetDeg", 15d);
double minInterM = readDouble(params, "minInterPlatformDistanceMeters", 80d);
if (spacingM < minInterM) {
spacingM = minInterM;
}
double defaultHeight = readDouble(params, "defaultDeployHeight", 30d);
double followRatio = readDouble(params, "heightFollowBlueRatio", 0d);
boolean clamp = Boolean.parseBoolean(String.valueOf(params.getOrDefault("enableWarZoneClamp", true)));
List<Coord> warZone = toWarZonePolygon(blueTask.getWarZoneLocation());
Map<String, Double> distanceByPlatform = parseDistanceByPlatformCsv(str(params, "distanceByPlatformCsv", ""));
for (FireRuleRedWeaponEquipmentVO red : redWeapons) {
if (red == null || red.getSubComponents() == null || red.getSubComponents().getPlatform() == null) {
continue;
}
double distKm = resolveDeployDistanceKm(red, distanceByPlatform, defKm);
distKm = clampDouble(distKm, minKm, maxKm);
List<FireRuleRedPlatformSlotVO> platforms = red.getSubComponents().getPlatform();
for (int i = 0; i < platforms.size(); i++) {
FireRuleRedPlatformSlotVO slot = platforms.get(i);
if (slot == null) {
continue;
}
double extraBearing = formationBearingOffsetDeg(formation, i, headingOffset);
double extraMeters = formationOffsetMeters(formation, i, spacingM);
Coord c = moveByMeters(anchor, distKm * 1000d + extraMeters, bearingDeg + extraBearing);
if (clamp && warZone.size() >= 3 && !isPointInPolygon(c, warZone)) {
c = projectInsidePolygon(c, anchor, warZone);
}
double h = defaultHeight;
if (anchor.height != null) {
h = defaultHeight + anchor.height * followRatio;
}
slot.setPositions(asPosition(c.lon, c.lat, h));
}
}
}
/**
* 目标分配:为每个红方 Tasks 节点写入 task.execute[0].targetList[*].targetId。\n
* targetId 来源:当前蓝方任务 {@link FireRuleTaskInputDTO#getTaskWeapons()} 下每条武器的 equipmentId。\n
* 允许多个红方装备指向同一个蓝方目标(不做去重占用)。\n
* 参数来自 rule.drl buildParam:\n
* - executeTypeDefault\n
* - targetPickMode: roundRobin/random\n
* - minTargetsPerRed / maxTargetsPerRedCap\n
* - radToTargetsCsv\n
* - rangeParseRegex / rangeUnit / minRangeToAllowAssignKm\n
*/
@SuppressWarnings({"rawtypes", "unchecked"})
public static void assignTargetsToTasks(List<FireRuleSceneTaskNodeVO> tasks,
List<FireRuleRedWeaponEquipmentVO> redWeapons,
FireRuleTaskInputDTO blueTask,
Map params) {
if (tasks == null || tasks.isEmpty() || blueTask == null) {
return;
}
List<String> candidates = extractBlueTargetEquipmentIds(blueTask, params);
if (candidates.isEmpty()) {
return;
}
String executeType = str(params, "executeTypeDefault", "assault");
String pickMode = str(params, "targetPickMode", "roundRobin");
for (int i = 0; i < tasks.size(); i++) {
FireRuleSceneTaskNodeVO node = tasks.get(i);
if (node == null) {
continue;
}
if (node.getTask() == null) {
node.setTask(new FireRuleSceneTaskPayloadVO());
}
FireRuleSceneTaskPayloadVO payload = node.getTask();
Double redHitRate = resolveRedWeaponHitRate(payload.getWeaponId(), redWeapons);
int targetsPerRed = resolveTargetsPerRed(redHitRate, params);
FireRuleExecuteBlockVO block = new FireRuleExecuteBlockVO();
block.setType(executeType);
List<FireRuleExecuteTargetItemVO> targetList = new ArrayList<>();
for (int k = 0; k < targetsPerRed; k++) {
String blueEquipmentId = pickBlueTargetId(candidates, pickMode, i, k, node, blueTask);
if (isBlank(blueEquipmentId)) {
continue;
}
FireRuleExecuteTargetItemVO item = new FireRuleExecuteTargetItemVO();
item.setId(UUID.randomUUID().toString());
item.setTargetId(blueEquipmentId);
// weaponId:可填红方装备的 equipmentId(若无则留空)
item.setWeaponId(payload.getWeaponId());
targetList.add(item);
}
block.setTargetList(targetList.isEmpty() ? null : targetList);
List<FireRuleExecuteBlockVO> execute = new ArrayList<>();
execute.add(block);
payload.setExecute(execute);
}
}
private static Double resolveRedWeaponHitRate(String weaponId, List<FireRuleRedWeaponEquipmentVO> redWeapons) {
if (isBlank(weaponId) || redWeapons == null || redWeapons.isEmpty()) {
return null;
}
for (FireRuleRedWeaponEquipmentVO w : redWeapons) {
if (w != null && weaponId.equals(w.getEquipmentId())) {
return w.getSuccessTargetRad();
}
}
return null;
}
private static String pickBlueTargetId(List<String> candidates, String pickMode, int taskIndex, int innerIndex,
FireRuleSceneTaskNodeVO node, FireRuleTaskInputDTO blueTask) {
if (candidates == null || candidates.isEmpty()) {
return null;
}
if ("random".equalsIgnoreCase(pickMode)) {
// 伪随机但稳定:基于 redTask.id + blueTask.id + innerIndex 做 hash
String seed = nz(node != null ? node.getId() : "") + "|" + nz(blueTask.getId()) + "|" + innerIndex;
int h = Math.abs(seed.hashCode());
return candidates.get(h % candidates.size());
}
// 默认 roundRobin:按 Tasks 序号与目标序号轮询
int idx = Math.abs(taskIndex + innerIndex) % candidates.size();
return candidates.get(idx);
}
private static int resolveTargetsPerRed(Double successTargetRad, Map params) {
int min = readInt(params, "minTargetsPerRed", 1);
int max = readInt(params, "maxTargetsPerRedCap", 3);
if (max <= 0) {
max = 1;
}
if (min < 0) {
min = 0;
}
if (min > max) {
min = max;
}
int byRad = parseRadToTargets(successTargetRad, str(params, "radToTargetsCsv", ""));
int v = byRad > 0 ? byRad : min;
if (v < min) {
v = min;
}
if (v > max) {
v = max;
}
return v;
}
private static int parseRadToTargets(Double rad, String csv) {
if (rad == null || csv == null || csv.trim().isEmpty()) {
return 0;
}
double r = rad.doubleValue();
// 允许无序输入:找所有 threshold<=r 的最大 threshold 对应的 targets
double bestTh = -1;
int bestTargets = 0;
for (String part : csv.split(",")) {
String p = part.trim();
if (p.isEmpty() || !p.contains(":")) {
continue;
}
String[] kv = p.split(":");
if (kv.length != 2) {
continue;
}
try {
double th = Double.parseDouble(kv[0].trim());
int t = Integer.parseInt(kv[1].trim());
if (r >= th && th > bestTh) {
bestTh = th;
bestTargets = t;
}
} catch (Exception ignore) {
}
}
return bestTargets;
}
private static List<String> extractBlueTargetEquipmentIds(FireRuleTaskInputDTO blueTask, Map params) {
List<String> all = new ArrayList<>();
if (blueTask == null || blueTask.getTaskWeapons() == null) {
return all;
}
// 射程过滤参数
String regex = str(params, "rangeParseRegex", "(\\d+(?:\\.\\d+)?)");
String unit = str(params, "rangeUnit", "km");
double minKm = readDouble(params, "minRangeToAllowAssignKm", 0d);
Pattern pattern = safePattern(regex);
for (FireRuleTaskWeaponDTO w : blueTask.getTaskWeapons()) {
if (w == null || isBlank(w.getEquipmentId())) {
continue;
}
Double km = tryParseRangeKm(w, pattern, unit);
if (km != null && km.doubleValue() < minKm) {
continue;
}
all.add(w.getEquipmentId());
}
return all;
}
private static Double tryParseRangeKm(FireRuleTaskWeaponDTO w, Pattern pattern, String unit) {
if (w == null || w.getComponents() == null || w.getComponents().isEmpty() || pattern == null) {
return null;
}
for (FireRuleWeaponComponentDTO c : w.getComponents()) {
if (c == null || c.getComponentParams() == null) {
continue;
}
for (FireRuleComponentParamDTO p : c.getComponentParams()) {
if (p == null) {
continue;
}
Double km = parseNumberToKm(p.getAttDefaultValue(), pattern, unit);
if (km != null) {
return km;
}
km = parseNumberToKm(p.getAttExplain(), pattern, unit);
if (km != null) {
return km;
}
}
}
return null;
}
private static Double parseNumberToKm(String text, Pattern pattern, String unit) {
if (text == null || text.trim().isEmpty() || pattern == null) {
return null;
}
Matcher m = pattern.matcher(text);
if (!m.find()) {
return null;
}
try {
double v = Double.parseDouble(m.group(1));
if ("m".equalsIgnoreCase(unit)) {
return v / 1000.0d;
}
return v;
} catch (Exception e) {
return null;
}
}
private static Pattern safePattern(String regex) {
try {
return Pattern.compile(regex);
} catch (Exception e) {
return null;
}
}
private static double readDouble(Map params, String key, double def) {
Object v = params != null ? params.get(key) : null;
if (v == null) {
return def;
}
if (v instanceof Number) {
return ((Number) v).doubleValue();
}
try {
return Double.parseDouble(String.valueOf(v).trim());
} catch (Exception e) {
return def;
}
}
private static int readInt(Map params, String key, int def) {
Object v = params != null ? params.get(key) : null;
if (v == null) {
return def;
}
if (v instanceof Number) {
return ((Number) v).intValue();
}
try {
return Integer.parseInt(String.valueOf(v).trim());
} catch (Exception e) {
return def;
}
}
private static String str(Map params, String key, String def) {
Object v = params != null ? params.get(key) : null;
return v == null ? def : String.valueOf(v);
}
private static List<FireRuleMissionListItemVO> buildMissionList(FireRuleRedWeaponEquipmentVO redWeapon) {
if (redWeapon == null || redWeapon.getSubComponents() == null || redWeapon.getSubComponents().getWeapon() == null) {
return null;
}
List<FireRuleMissionListItemVO> result = new ArrayList<>();
for (FireRuleRedWeaponSlotVO slot : redWeapon.getSubComponents().getWeapon()) {
if (slot == null) {
continue;
}
FireRuleLauncherConfigurationVO cfg = slot.getConfiguration();
FireRuleMountedWeaponRefVO mounted = cfg != null ? cfg.getMountedWeapon() : null;
FireRuleMissionListItemVO item = new FireRuleMissionListItemVO();
// label:优先挂载武器名,其次 deviceName
String label = mounted != null ? mounted.getName() : null;
if (isBlank(label)) {
label = slot.getDeviceName();
}
item.setLabel(label);
item.setNumber(cfg != null ? cfg.getNumber() : null);
item.setValue(mounted != null ? mounted.getName() : null);
item.setLauncherType(extractLauncherType(slot.getTwiceModified()));
result.add(item);
}
return result.isEmpty() ? null : result;
}
private static String extractLauncherType(Map<String, Object> twiceModified) {
if (twiceModified == null || twiceModified.isEmpty()) {
return null;
}
Object v = twiceModified.get("launcherType");
return v == null ? null : String.valueOf(v);
}
private static String buildNodeId(FireRuleRedWeaponEquipmentVO redWeapon, int index) {
String id = nz(redWeapon.getEquipmentId());
if (!id.isEmpty()) {
return id;
}
id = nz(redWeapon.getPlatId());
if (!id.isEmpty()) {
return id;
}
return "redWeaponTask_" + index;
}
private static String nz(String s) {
return s == null ? "" : s;
}
private static boolean isBlank(String s) {
return s == null || s.trim().isEmpty();
}
// ------------------ 阵位几何辅助 ------------------
private static class Coord {
final double lon;
final double lat;
final Double height;
Coord(double lon, double lat, Double height) {
this.lon = lon;
this.lat = lat;
this.height = height;
}
}
private static Coord computeBlueAnchor(FireRuleTaskInputDTO blueTask) {
if (blueTask == null || blueTask.getTaskWeapons() == null || blueTask.getTaskWeapons().isEmpty()) {
return null;
}
double sumLon = 0d, sumLat = 0d, sumH = 0d;
int count = 0, hc = 0;
for (FireRuleTaskWeaponDTO w : blueTask.getTaskWeapons()) {
if (w == null || w.getCoordinate() == null || w.getCoordinate().getLongitude() == null || w.getCoordinate().getLatitude() == null) {
continue;
}
sumLon += w.getCoordinate().getLongitude();
sumLat += w.getCoordinate().getLatitude();
count++;
if (w.getCoordinate().getHeight() != null) {
sumH += w.getCoordinate().getHeight();
hc++;
}
}
if (count == 0) {
return null;
}
return new Coord(sumLon / count, sumLat / count, hc > 0 ? sumH / hc : null);
}
private static double computeTrackBearingDeg(FireRuleTaskInputDTO blueTask, String mode, double fallbackDeg) {
if (blueTask == null || blueTask.getTrackPoints() == null || blueTask.getTrackPoints().size() < 2) {
return fallbackDeg;
}
FireRuleTrackPointDTO a;
FireRuleTrackPointDTO b;
if ("tail2prev".equalsIgnoreCase(mode)) {
int n = blueTask.getTrackPoints().size();
a = blueTask.getTrackPoints().get(n - 2);
b = blueTask.getTrackPoints().get(n - 1);
} else {
a = blueTask.getTrackPoints().get(0);
b = blueTask.getTrackPoints().get(1);
}
if (a == null || b == null || a.getLongitude() == null || a.getLatitude() == null || b.getLongitude() == null || b.getLatitude() == null) {
return fallbackDeg;
}
return bearingDeg(a.getLongitude(), a.getLatitude(), b.getLongitude(), b.getLatitude());
}
private static List<Coord> toWarZonePolygon(List<FireRuleCoordinateDTO> warZone) {
List<Coord> list = new ArrayList<>();
if (warZone == null) {
return list;
}
for (FireRuleCoordinateDTO c : warZone) {
if (c != null && c.getLongitude() != null && c.getLatitude() != null) {
list.add(new Coord(c.getLongitude(), c.getLatitude(), c.getHeight()));
}
}
return list;
}
private static Map<String, Double> parseDistanceByPlatformCsv(String csv) {
Map<String, Double> map = new HashMap<>();
if (isBlank(csv)) {
return map;
}
for (String part : csv.split(",")) {
String p = part.trim();
if (!p.contains(":")) {
continue;
}
String[] kv = p.split(":");
if (kv.length != 2) {
continue;
}
try {
map.put(kv[0].trim(), Double.parseDouble(kv[1].trim()));
} catch (Exception ignore) {
}
}
return map;
}
private static double resolveDeployDistanceKm(FireRuleRedWeaponEquipmentVO red, Map<String, Double> byPlatform, double defKm) {
String name = red != null ? nz(red.getName()) : "";
String platform = red != null ? nz(red.getPlatformType()) : "";
for (Map.Entry<String, Double> e : byPlatform.entrySet()) {
String k = e.getKey();
if (!isBlank(k) && (name.contains(k) || platform.contains(k))) {
return e.getValue();
}
}
return defKm;
}
private static double formationBearingOffsetDeg(String formation, int index, double headingOffset) {
if ("line".equalsIgnoreCase(formation)) {
return 90d;
}
if ("wedge".equalsIgnoreCase(formation)) {
return (index % 2 == 0 ? 1 : -1) * headingOffset;
}
if ("circle".equalsIgnoreCase(formation)) {
return index * 45d;
}
return 0d;
}
private static double formationOffsetMeters(String formation, int index, double spacingM) {
if ("line".equalsIgnoreCase(formation)) {
return (index - 0.5d) * spacingM;
}
if ("wedge".equalsIgnoreCase(formation)) {
return (index + 1) * spacingM * 0.5d;
}
if ("circle".equalsIgnoreCase(formation)) {
return spacingM;
}
return index * spacingM;
}
private static Coord moveByMeters(Coord anchor, double meters, double bearingDeg) {
double R = 6378137.0d;
double brng = Math.toRadians(bearingDeg);
double lat1 = Math.toRadians(anchor.lat);
double lon1 = Math.toRadians(anchor.lon);
double dR = meters / R;
double lat2 = Math.asin(Math.sin(lat1) * Math.cos(dR) + Math.cos(lat1) * Math.sin(dR) * Math.cos(brng));
double lon2 = lon1 + Math.atan2(Math.sin(brng) * Math.sin(dR) * Math.cos(lat1),
Math.cos(dR) - Math.sin(lat1) * Math.sin(lat2));
return new Coord(Math.toDegrees(lon2), Math.toDegrees(lat2), anchor.height);
}
private static double bearingDeg(double lon1, double lat1, double lon2, double lat2) {
double phi1 = Math.toRadians(lat1);
double phi2 = Math.toRadians(lat2);
double dLon = Math.toRadians(lon2 - lon1);
double y = Math.sin(dLon) * Math.cos(phi2);
double x = Math.cos(phi1) * Math.sin(phi2) - Math.sin(phi1) * Math.cos(phi2) * Math.cos(dLon);
double brng = Math.toDegrees(Math.atan2(y, x));
return (brng + 360d) % 360d;
}
private static boolean isPointInPolygon(Coord p, List<Coord> poly) {
boolean inside = false;
for (int i = 0, j = poly.size() - 1; i < poly.size(); j = i++) {
double xi = poly.get(i).lon, yi = poly.get(i).lat;
double xj = poly.get(j).lon, yj = poly.get(j).lat;
boolean intersect = ((yi > p.lat) != (yj > p.lat))
&& (p.lon < (xj - xi) * (p.lat - yi) / (yj - yi + 1e-12) + xi);
if (intersect) {
inside = !inside;
}
}
return inside;
}
private static Coord projectInsidePolygon(Coord out, Coord anchor, List<Coord> poly) {
if (isPointInPolygon(out, poly)) {
return out;
}
// 二分逼近:沿 anchor -> out 连线回退到多边形内部
Coord in = anchor;
if (!isPointInPolygon(in, poly)) {
// anchor 不在区内时,退化为原点不处理
return out;
}
Coord lo = in;
Coord hi = out;
for (int i = 0; i < 24; i++) {
Coord mid = new Coord((lo.lon + hi.lon) / 2d, (lo.lat + hi.lat) / 2d, out.height);
if (isPointInPolygon(mid, poly)) {
lo = mid;
} else {
hi = mid;
}
}
return lo;
}
private static List<Double> asPosition(double lon, double lat, double height) {
List<Double> p = new ArrayList<>(3);
p.add(lon);
p.add(lat);
p.add(height);
return p;
}
private static double clampDouble(double v, double min, double max) {
if (v < min) {
return min;
}
if (v > max) {
return max;
}
return v;
}
}

View File

@@ -0,0 +1,462 @@
package com.solution.rule.utils;
import com.solution.rule.domain.ultimately.dto.FireRuleInputRedWeaponElementDTO;
import com.solution.rule.domain.ultimately.dto.FireRuleTaskInputDTO;
import com.solution.rule.domain.ultimately.dto.FireRuleTaskWeaponDTO;
import com.solution.rule.domain.ultimately.dto.FireRuleWeaponComponentDTO;
import com.solution.rule.domain.ultimately.fact.DroolsFact;
import com.solution.rule.domain.ultimately.vo.FireRuleOutputVO;
import com.solution.rule.domain.ultimately.vo.FireRuleRedWeaponEquipmentVO;
import com.solution.rule.domain.ultimately.vo.FireRuleTaskInputVO;
import com.solution.rule.domain.ultimately.vo.FireRuleTaskWeaponVO;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
/**
* Drools 规则调用的装备匹配逻辑。所有业务词均来自 globalParams(由 rule.drl 的 buildParam 注入),本类不写死中文业务词。
* <p>
* <b>总分公式(每件候选红装)</b>
* <pre>
* score(red) = scoreRuleSlots(...) + scoreLegacyLayer(...)
*
* scoreRuleSlots = Σ(i=1..ruleSlotCount) [ containsAny(blueBlob, blueRuleKeywords_i)
* ∧ containsAny(redBlob, redRuleKeywords_i)
* ? ruleScore_i * weight : 0 ]
*
* scoreLegacyLayer = ①空中平台 + ②空中任务 + ③地面任务 + ④坦克 + ⑤导弹 五段条件之和,每段若满足均为「对应 *Score * weight」
* (五段含义见 scoreLegacyLayer 方法注释与 rule.drl 中各键说明)。
* </pre>
* <p>
* <b>文本串定义</b>
* <ul>
* <li>blueBlob:{@link #buildBlueTextBlob} — 蓝方任务 drawName、dataType、taskWeapons 及组件名拼接成一大串,用于关键词包含判断。</li>
* <li>redBlob:{@link #buildRedTextBlob} — 红装 name、platformType、supportType 拼接。</li>
* </ul>
* <p>
* <b>选优与输出</b>
* <ul>
* <li>在 redWeapons 池中对每件算 score,取最大值;若并列,{@link #compareRedForTieBreak}(由 tieBreak 参数控制,默认 equipmentId 小者优先)。</li>
* <li>若 maxScore &lt; minSelectedScore:不追加 fireRuleInputs;仍将当前池映射到 FireRuleOutputVO.redWeapons。</li>
* <li>否则:池中 remove 选中项;fireRuleInputs 追加一行,drawName += outputDrawNameSuffix,taskWeapons 一条映射自选中红装;redWeapons 为剩余池。</li>
* </ul>
*/
public final class RuleFunction {
private RuleFunction() {
}
/**
* 单轮规则执行:对当前 DroolsFact 的一条蓝方任务,从 redWeapons 中选一件装备并写回输出。
* <p>
* 参数 p(globalParams)中各键含义与运算见 {@link RuleFunction} 类注释及 resources/rules/rule.drl 内 buildParam 行内注释。
*/
@SuppressWarnings("rawtypes")
public static void equipmentRule(DroolsFact fact, Map globalParams) {
if (fact == null || fact.getTask() == null) {
return;
}
Map<String, Object> p = castParams(globalParams);
FireRuleTaskInputDTO blue = fact.getTask();
List<FireRuleInputRedWeaponElementDTO> pool = fact.getRedWeapons();
if (pool == null) {
pool = new ArrayList<>();
fact.setRedWeapons(pool);
}
// weight、minSelectedScore:见 rule.drl 注释
String blueBlob = buildBlueTextBlob(blue);
int weight = readInt(p, "weight", 1);
int minScore = readInt(p, "minSelectedScore", 1);
int bestIndex = -1;
int bestScore = Integer.MIN_VALUE;
for (int i = 0; i < pool.size(); i++) {
FireRuleInputRedWeaponElementDTO red = pool.get(i);
String redBlob = buildRedTextBlob(red);
int score = scoreRuleSlots(blueBlob, redBlob, p, weight)
+ scoreLegacyLayer(blueBlob, redBlob, p, weight);
if (score > bestScore) {
bestScore = score;
bestIndex = i;
} else if (score == bestScore && bestIndex >= 0) {
// 并列:compareRedForTieBreak(a,b)>0 表示当前 best 的 equipmentId 比候选 red 大,应换成更小的 id
if (compareRedForTieBreak(pool.get(bestIndex), red, p) > 0) {
bestIndex = i;
}
}
}
FireRuleOutputVO out = fact.getFireRuleOutputVO();
if (out == null) {
out = new FireRuleOutputVO();
fact.setFireRuleOutputVO(out);
}
// 未达门槛或池空:不写 fireRuleInputs,仅同步「剩余池」到输出 redWeapons
if (bestIndex < 0 || pool.isEmpty() || bestScore < minScore) {
out.setRedWeapons(convertPoolToEquipmentVoList(pool));
// Tasks 由最终输出 redWeapons 一一生成(一个装备 -> 一个任务)
out.setTasks(FireRuleRedWeaponOutputFillHelper.toTaskNodes(out.getRedWeapons()));
return;
}
pool.remove(bestIndex);
out.setRedWeapons(convertPoolToEquipmentVoList(pool));
// Tasks 由最终输出 redWeapons 一一生成(一个装备 -> 一个任务)
out.setTasks(FireRuleRedWeaponOutputFillHelper.toTaskNodes(out.getRedWeapons()));
}
/**
* 目标规则:显式为 Tasks 填 targetId,并按红方命中率不足时补拿装备(出池,带上限)。
*/
@SuppressWarnings("rawtypes")
public static void target(DroolsFact fact, Map globalParams){
if (fact == null || fact.getTask() == null || fact.getFireRuleOutputVO() == null) {
return;
}
Map<String, Object> p = castParams(globalParams);
FireRuleTaskInputDTO blue = fact.getTask();
FireRuleOutputVO out = fact.getFireRuleOutputVO();
List<FireRuleInputRedWeaponElementDTO> pool = fact.getRedWeapons();
if (pool == null) {
pool = new ArrayList<>();
fact.setRedWeapons(pool);
}
if (out.getRedWeapons() == null) {
out.setRedWeapons(convertPoolToEquipmentVoList(pool));
}
if (out.getTasks() == null || out.getTasks().size() != out.getRedWeapons().size()) {
out.setTasks(FireRuleRedWeaponOutputFillHelper.toTaskNodes(out.getRedWeapons()));
}
double threshold = readDouble(p, "redHitRateThreshold", 0.6d);
int maxExtra = readInt(p, "maxExtraWeaponsPerTask", 2);
int maxRounds = readInt(p, "maxSupplementRounds", 5);
int extraMinScore = readInt(p, "extraPickMinScore", 1);
int weight = readInt(p, "weight", 1);
String blueBlob = buildBlueTextBlob(blue);
if (maxExtra > 0 && maxRounds > 0 && !pool.isEmpty()) {
Set<String> selectedIds = new HashSet<>();
for (FireRuleRedWeaponEquipmentVO w : out.getRedWeapons()) {
if (w != null && !isBlank(w.getEquipmentId())) {
selectedIds.add(w.getEquipmentId());
}
}
int extraCount = 0;
int rounds = 0;
while (rounds < maxRounds && extraCount < maxExtra && !pool.isEmpty()) {
rounds++;
boolean needExtra = false;
for (FireRuleRedWeaponEquipmentVO w : out.getRedWeapons()) {
Double rad = w != null ? w.getSuccessTargetRad() : null;
if (rad == null || rad.doubleValue() < threshold) {
needExtra = true;
break;
}
}
if (!needExtra) {
break;
}
int bestIdx = -1;
int bestScore = Integer.MIN_VALUE;
for (int i = 0; i < pool.size(); i++) {
FireRuleInputRedWeaponElementDTO red = pool.get(i);
if (red == null) {
continue;
}
if (!isBlank(red.getEquipmentId()) && selectedIds.contains(red.getEquipmentId())) {
continue;
}
String redBlob = buildRedTextBlob(red);
int s = scoreRuleSlots(blueBlob, redBlob, p, weight)
+ scoreLegacyLayer(blueBlob, redBlob, p, weight);
if (s > bestScore) {
bestScore = s;
bestIdx = i;
} else if (s == bestScore && bestIdx >= 0) {
if (compareRedForTieBreak(pool.get(bestIdx), red, p) > 0) {
bestIdx = i;
}
}
}
if (bestIdx < 0 || bestScore < extraMinScore) {
break;
}
FireRuleInputRedWeaponElementDTO extra = pool.remove(bestIdx);
FireRuleRedWeaponEquipmentVO vo = toRedEquipmentVo(extra);
out.getRedWeapons().add(vo);
if (!isBlank(vo.getEquipmentId())) {
selectedIds.add(vo.getEquipmentId());
}
extraCount++;
}
}
out.setTasks(FireRuleRedWeaponOutputFillHelper.toTaskNodes(out.getRedWeapons()));
FireRuleRedWeaponOutputFillHelper.assignTargetsToTasks(out.getTasks(), out.getRedWeapons(), blue, p);
}
/**
* 阵位规则:根据蓝方武器 coordinate + trackPoints + warZone 计算红方平台 positions。
*/
@SuppressWarnings("rawtypes")
public static void position(DroolsFact fact, Map globalParams) {
if (fact == null || fact.getTask() == null || fact.getFireRuleOutputVO() == null) {
return;
}
Map<String, Object> p = castParams(globalParams);
boolean enabled = Boolean.parseBoolean(String.valueOf(p.getOrDefault("positionRuleEnabled", true)));
if (!enabled) {
return;
}
FireRuleOutputVO out = fact.getFireRuleOutputVO();
if (out.getRedWeapons() == null || out.getRedWeapons().isEmpty()) {
return;
}
FireRuleRedWeaponOutputFillHelper.fillPlatformPositions(out.getRedWeapons(), fact.getTask(), p);
}
@SuppressWarnings("unchecked")
private static Map<String, Object> castParams(Map raw) {
return raw == null ? new java.util.HashMap<>() : (Map<String, Object>) raw;
}
/**
* 蓝方侧用于「关键词包含」判断的合并文本(空格分隔各字段)。
*/
private static String buildBlueTextBlob(FireRuleTaskInputDTO task) {
StringBuilder sb = new StringBuilder();
append(sb, task.getDrawName());
append(sb, task.getDataType());
if (task.getTaskWeapons() != null) {
for (FireRuleTaskWeaponDTO w : task.getTaskWeapons()) {
if (w == null) {
continue;
}
append(sb, w.getName());
append(sb, w.getSupportType());
append(sb, w.getEquipmentId());
if (w.getComponents() != null) {
for (FireRuleWeaponComponentDTO c : w.getComponents()) {
if (c == null) {
continue;
}
append(sb, c.getDeviceName());
}
}
}
}
return sb.toString();
}
/**
* 红方侧用于「关键词包含」判断的合并文本。
*/
private static String buildRedTextBlob(FireRuleInputRedWeaponElementDTO red) {
if (red == null) {
return "";
}
StringBuilder sb = new StringBuilder();
append(sb, red.getName());
append(sb, red.getPlatformType());
append(sb, red.getSupportType());
return sb.toString();
}
private static void append(StringBuilder sb, String s) {
if (s != null && !s.isEmpty()) {
sb.append(s).append(' ');
}
}
/**
* 规则槽得分:对 i=1..ruleSlotCount,若 blueBlob 命中 blueRuleKeywords_i 且 redBlob 命中 redRuleKeywords_i,
* 则累加 ruleScore_i * weight。关键词为英文逗号分隔,任一词作为子串出现在文本中即命中。
*/
private static int scoreRuleSlots(String blueBlob, String redBlob, Map<String, Object> p, int weight) {
int n = readInt(p, "ruleSlotCount", 0);
int sum = 0;
for (int i = 1; i <= n; i++) {
String bk = str(p, "blueRuleKeywords_" + i, "");
String rk = str(p, "redRuleKeywords_" + i, "");
if (bk.isEmpty() || rk.isEmpty()) {
continue;
}
if (containsAny(blueBlob, bk) && containsAny(redBlob, rk)) {
sum += readInt(p, "ruleScore_" + i, 0) * weight;
}
}
return sum;
}
/**
* 兼容层得分:五段独立条件,可叠加。每段均为「蓝关键词命中 ∧ 红关键词命中 → 加 对应分数 * weight」。
* <ul>
* <li>① bluePlatformKeywords_air + redPreferredWhenBlueAir → airScore</li>
* <li>② airTaskKeywords + redPreferredWhenBlueAir → airTaskScore</li>
* <li>③ groundTaskKeywords + redPreferredWhenGround → groundScore</li>
* <li>④ tankKeywords + redMatchKeywords_tank → tankScore</li>
* <li>⑤ missileKeywords + redMatchKeywords_missile → missileScore</li>
* </ul>
* 键名与 rule.drl 中 param.put 一致。
*/
private static int scoreLegacyLayer(String blueBlob, String redBlob, Map<String, Object> p, int weight) {
int s = 0;
if (containsAny(blueBlob, str(p, "bluePlatformKeywords_air", ""))
&& containsAny(redBlob, str(p, "redPreferredWhenBlueAir", ""))) {
s += readInt(p, "airScore", 0) * weight;
}
if (containsAny(blueBlob, str(p, "airTaskKeywords", ""))
&& containsAny(redBlob, str(p, "redPreferredWhenBlueAir", ""))) {
s += readInt(p, "airTaskScore", 0) * weight;
}
if (containsAny(blueBlob, str(p, "groundTaskKeywords", ""))
&& containsAny(redBlob, str(p, "redPreferredWhenGround", ""))) {
s += readInt(p, "groundScore", 0) * weight;
}
if (containsAny(blueBlob, str(p, "tankKeywords", ""))
&& containsAny(redBlob, str(p, "redMatchKeywords_tank", ""))) {
s += readInt(p, "tankScore", 0) * weight;
}
if (containsAny(blueBlob, str(p, "missileKeywords", ""))
&& containsAny(redBlob, str(p, "redMatchKeywords_missile", ""))) {
s += readInt(p, "missileScore", 0) * weight;
}
return s;
}
/**
* 并列时比较两件红装:tieBreak=equipmentId 时返回 id 字典序比较结果(&gt;0 表示 a 的 id 大于 b,应选 b)。
*/
private static int compareRedForTieBreak(
FireRuleInputRedWeaponElementDTO a,
FireRuleInputRedWeaponElementDTO b,
Map<String, Object> p) {
if (a == null) {
return b == null ? 0 : 1;
}
if (b == null) {
return -1;
}
String mode = str(p, "tieBreak", "equipmentId");
if ("equipmentId".equals(mode)) {
String ida = nz(a.getEquipmentId());
String idb = nz(b.getEquipmentId());
return ida.compareTo(idb);
}
return 0;
}
/**
* commaKeywords:英文逗号分隔;若 text 包含其中任一词(trim 后非空)则命中。
*/
private static boolean containsAny(String text, String commaKeywords) {
if (text == null || text.isEmpty() || commaKeywords == null || commaKeywords.isEmpty()) {
return false;
}
for (String part : commaKeywords.split(",")) {
String k = part.trim();
if (!k.isEmpty() && text.contains(k)) {
return true;
}
}
return false;
}
private static String str(Map<String, Object> p, String key, String def) {
Object v = p.get(key);
return v == null ? def : String.valueOf(v);
}
private static int readInt(Map<String, Object> p, String key, int def) {
Object v = p.get(key);
if (v == null) {
return def;
}
if (v instanceof Number) {
return ((Number) v).intValue();
}
try {
return Integer.parseInt(String.valueOf(v).trim());
} catch (NumberFormatException e) {
return def;
}
}
private static double readDouble(Map<String, Object> p, String key, double def) {
Object v = p.get(key);
if (v == null) {
return def;
}
if (v instanceof Number) {
return ((Number) v).doubleValue();
}
try {
return Double.parseDouble(String.valueOf(v).trim());
} catch (NumberFormatException e) {
return def;
}
}
private static String nz(String s) {
return s == null ? "" : s;
}
private static boolean isBlank(String s) {
return s == null || s.trim().isEmpty();
}
private static FireRuleTaskWeaponVO toTaskWeaponVo(FireRuleInputRedWeaponElementDTO r) {
FireRuleTaskWeaponVO w = new FireRuleTaskWeaponVO();
if (r != null) {
w.setEquipmentId(r.getEquipmentId());
w.setName(r.getName());
w.setSupportType(r.getSupportType());
}
return w;
}
private static List<FireRuleRedWeaponEquipmentVO> convertPoolToEquipmentVoList(
List<FireRuleInputRedWeaponElementDTO> pool) {
List<FireRuleRedWeaponEquipmentVO> list = new ArrayList<>();
if (pool == null) {
return list;
}
for (FireRuleInputRedWeaponElementDTO e : pool) {
list.add(toRedEquipmentVo(e));
}
return list;
}
private static FireRuleRedWeaponEquipmentVO toRedEquipmentVo(FireRuleInputRedWeaponElementDTO src) {
if (src == null) {
return null;
}
FireRuleRedWeaponEquipmentVO vo = new FireRuleRedWeaponEquipmentVO();
vo.setSupportType(src.getSupportType());
vo.setTroopsDetail(src.getTroopsDetail());
vo.setPlatformType(src.getPlatformType());
vo.setIsStrikeTarget(src.getIsStrikeTarget());
vo.setIsReconTarget(src.getIsReconTarget());
vo.setIsInterferenceTarget(src.getIsInterferenceTarget());
vo.setIsDefendImportantPlace(src.getIsDefendImportantPlace());
vo.setSuccessTargetRad(src.getSuccessTargetRad());
vo.setGroupType(src.getGroupType());
vo.setEquipmentId(src.getEquipmentId());
vo.setName(src.getName());
vo.setOwnerForceSide(src.getOwnerForceSide());
vo.setPlatId(src.getPlatId());
vo.setSubComponents(FireRuleRedWeaponOutputFillHelper.toOutputSubComponents(src.getSubComponents()));
return vo;
}
}

View File

@@ -0,0 +1,181 @@
package rules;
import com.solution.rule.domain.ultimately.fact.DroolsFact;
import java.util.Map;
import static com.solution.rule.utils.RuleFunction.equipmentRule;
import static com.solution.rule.utils.RuleFunction.target;
import static com.solution.rule.utils.RuleFunction.position;
global java.util.Map globalParams;
/**
* 构建装备匹配所需的全部可调参数(会 merge 进 globalParams,覆盖 Java 侧同名默认值)。
*
* ========== 总体运算逻辑(与 RuleFunction.equipmentRule 一致)==========
* 1)先拼「蓝方文本串」blueBlob:任务 drawName、dataType、taskWeapons 下各武器的 name/supportType/equipmentId、组件 deviceName。
* 2)对每个红方装备拼「红方文本串」redBlob:name、platform_type、SupportType。
* 3)每件红装得分 score = 规则槽得分(scoreRuleSlots) + 兼容层得分(scoreLegacyLayer),均为整数。
* - 规则槽:对 i=1..ruleSlotCount,若 blueBlob 命中 blueRuleKeywords_i 且 redBlob 命中 redRuleKeywords_i,
* 则加上 ruleScore_i * weight。
* - 兼容层:多组「蓝关键词 + 红关键词 + 对应分数」,见下方各键说明;每组条件同时满足则加上 对应Score * weight。
* 4)在池中取 score 最大者;若多人并列,由 tieBreak 决定(见 tieBreak)。
* 5)若 maxScore < minSelectedScore,视为未匹配:不往 fireRuleInputs 追加行,redWeapons 输出仍为当前池。
* 6)若匹配成功:从池中 remove 该件;fireRuleInputs 追加一行,drawName 后接 outputDrawNameSuffix;taskWeapons 填选中红装映射。
*
* 关键词格式:英文逗号分隔,子串包含即算命中(contains),不要求整词匹配。
*/
function Map buildParam(){
Map param = new java.util.HashMap();
// ---------- 全局倍率与门槛 ----------
// weight:对上述所有「基础分数」的统一乘数(规则槽的 ruleScore_i、兼容层的 *Score 都会乘 weight)。
param.put("weight", 1);
// minSelectedScore:单件红装总分达到该值及以上才会被选中并写入 fireRuleInputs;否则本任务视为未匹配到装备。
param.put("minSelectedScore", 1);
// tieBreak:并列最高分时的决胜方式。当前实现仅支持 "equipmentId":装备 ID 字典序更小的优先。
param.put("tieBreak", "equipmentId");
// outputDrawNameSuffix:匹配成功写入 fireRuleInputs 时,在蓝方原 drawName 后面拼接的后缀(如「打击任务」)。
param.put("outputDrawNameSuffix", "打击任务");
// ---------- 规则槽(可配置条数,便于只改本文件而不改 Java)----------
// ruleSlotCount:启用几条槽规则;第 i 条使用 blueRuleKeywords_i、redRuleKeywords_i、ruleScore_i。
param.put("ruleSlotCount", 3);
// 槽1:蓝方文本中出现任一子串 且 红方文本中出现任一子串 → 加 ruleScore_1 * weight。
param.put("blueRuleKeywords_1", "F-16,F-35");
param.put("redRuleKeywords_1", "防空,导弹,无人机");
param.put("ruleScore_1", 5);
param.put("blueRuleKeywords_2", "坦克,装甲");
param.put("redRuleKeywords_2", "反坦克");
param.put("ruleScore_2", 4);
param.put("blueRuleKeywords_3", "地面,突击");
param.put("redRuleKeywords_3", "远火,榴弹,炮");
param.put("ruleScore_3", 2);
// ---------- 兼容层:按「场景关键词」配对加分(与 RuleFunction.scoreLegacyLayer 一一对应)----------
// 以下每组均为:蓝方文本命中第一列关键词 且 红方文本命中第二列关键词 → 加 第三列分数 * weight。
//
// ① 空中平台类:蓝方像「对空/机型」且红方像对空装备 → + airScore * weight
param.put("bluePlatformKeywords_air", "F-16,J-10,F-35");
param.put("redPreferredWhenBlueAir", "防空,导弹,无人机,直升机,空空");
param.put("airScore", 2);
// ② 任务文案像空中任务 且 红方偏好对空 → + airTaskScore * weight(可与①叠加)
param.put("airTaskKeywords", "空中,制空,拦截,空战");
param.put("airTaskScore", 10);
// ③ 任务文案像地面任务 且 红方偏好地面火力 → + groundScore * weight
param.put("groundTaskKeywords", "地面,突击,登陆");
param.put("redPreferredWhenGround", "远火,榴弹,炮,火箭");
param.put("groundScore", 1);
// ④ 蓝方像坦克/装甲目标 且 红方文本命中 redMatchKeywords_tank → + tankScore * weight
param.put("tankKeywords", "坦克,装甲");
param.put("redMatchKeywords_tank", "反坦克");
param.put("tankScore", 1);
// ⑤ 蓝方像导弹类 且 红方文本命中 redMatchKeywords_missile → + missileScore * weight
param.put("missileKeywords", "导弹,火箭弹,巡航");
param.put("redMatchKeywords_missile", "防空,导弹,导弹发射");
param.put("missileScore", 1);
// ===================== 目标分配参数(写入 Tasks.task.execute) =====================
// executeTypeDefault:生成 execute[0] 的类型字段
param.put("executeTypeDefault", "assault");
// targetPickMode:roundRobin(稳定轮询) / random(伪随机但同输入稳定)
param.put("targetPickMode", "roundRobin");
// minTargetsPerRed / maxTargetsPerRedCap:每个红方任务最少/最多分配的目标数
param.put("minTargetsPerRed", 1);
param.put("maxTargetsPerRedCap", 3);
// radToTargetsCsv:successTargetRad(命中率) -> 每红装目标数 的映射(阈值:目标数),按阈值从大到小匹配
// 例:0.8:1,0.5:2,0.2:3 表示 successTargetRad>=0.8 分1个;>=0.5 分2个;>=0.2 分3个
param.put("radToTargetsCsv", "0.8:1,0.5:2,0.2:3");
// rangeParseRegex:从 attDefaultValue/attExplain 中提取射程数值的正则(取第1个数字)
param.put("rangeParseRegex", "(\\\\d+(?:\\\\.\\\\d+)?)");
// rangeUnit:提取数值的单位,km/m(二选一)
param.put("rangeUnit", "km");
// minRangeToAllowAssignKm:若解析到的蓝方射程小于该值,则该蓝方装备不参与被分配(无法解析则忽略此过滤)
param.put("minRangeToAllowAssignKm", 0);
// ===================== 低命中率补拿装备参数 =====================
// redHitRateThreshold:红方装备命中率阈值(低于该值时触发补拿)
param.put("redHitRateThreshold", 0.6);
// maxExtraWeaponsPerTask:每条蓝方任务最多补拿几件红装
param.put("maxExtraWeaponsPerTask", 2);
// maxSupplementRounds:补拿循环最大轮次(防死循环)
param.put("maxSupplementRounds", 2);
// extraPickMinScore:补拿时红装最低匹配分
param.put("extraPickMinScore", 1);
// ===================== 阵位规则参数(写入 SubComponents.platform[].positions) =====================
// positionRuleEnabled:是否启用阵位规则。true=执行阵位生成;false=跳过,不改 platform.positions。
param.put("positionRuleEnabled", true);
// positionAnchorMode:锚点模式。当前实现使用 hybrid(蓝方 taskWeapons.coordinate 的中心点作为主锚点)。
param.put("positionAnchorMode", "hybrid");
// trackPointDirectionMode:航向计算模式。
// - head2next:取 trackPoints[0] -> trackPoints[1] 作为方向(默认)
// - tail2prev:取倒数第二个 -> 最后一个点作为方向
param.put("trackPointDirectionMode", "head2next");
// fallbackBearingDeg:当 trackPoints 缺失或无法计算方位时,使用该默认方位角(度,0-360)。
param.put("fallbackBearingDeg", 0);
// deployDistanceKmMin:部署距离下限(km)。最终距离不会小于该值。
param.put("deployDistanceKmMin", 8);
// deployDistanceKmMax:部署距离上限(km)。最终距离不会大于该值。
param.put("deployDistanceKmMax", 30);
// deployDistanceKmDefault:默认部署距离(km)。
// 当 distanceByPlatformCsv 未命中任何关键词时,使用该值。
param.put("deployDistanceKmDefault", 15);
// distanceByPlatformCsv:按“关键词”覆盖部署距离(km),不写死具体类型,完全由业务配置。
// 格式:关键词:距离,关键词:距离(示例:防空:18,反坦克:10,迫击炮:8)
// 匹配范围:红方装备 Name / Platform_type 文本包含关键词即命中。
// 优先级:命中后覆盖 deployDistanceKmDefault;但最终仍受 deployDistanceKmMin 与 deployDistanceKmMax 约束。
param.put("distanceByPlatformCsv", "");
// formationType:编队样式,可选 line / wedge / circle。
param.put("formationType", "line");
// formationSpacingMeters:编队间距(米),影响同一红装下 platform[] 点位离散程度。
// 说明:Java 侧会与 minInterPlatformDistanceMeters 比较,取更大值,避免平台重叠过近。
param.put("formationSpacingMeters", 300);
// formationHeadingOffsetDeg:编队相对主航向的偏转角(度),主要用于 wedge/circle 的分散方向。
param.put("formationHeadingOffsetDeg", 15);
// defaultDeployHeight:默认部署高度(米),用于 positions 第3位高度值基线。
param.put("defaultDeployHeight", 30);
// heightFollowBlueRatio:高度跟随蓝方比例(>=0)。
// 计算方式:高度 = defaultDeployHeight + 蓝方锚点平均高度 * heightFollowBlueRatio。
// 0 表示不跟随蓝方高度,仅使用默认高度。
param.put("heightFollowBlueRatio", 0.0);
// enableWarZoneClamp:是否启用作战区约束。true=超出 warZoneLocation 时回拉到区内。
param.put("enableWarZoneClamp", true);
// warZoneClampMode:作战区约束模式。当前实现使用 nearestInside(沿锚点到目标点方向二分回拉到区内)。
param.put("warZoneClampMode", "nearestInside");
// minInterPlatformDistanceMeters:平台最小间距(米)下限,用于抑制平台点位过度重叠。
param.put("minInterPlatformDistanceMeters", 80);
return param;
}
rule "装备匹配"
salience 100
when
$fact : DroolsFact(task != null)
then
// 以本文件 buildParam 为真源覆盖同名键,再执行 Java 侧匹配逻辑
globalParams.putAll(buildParam());
equipmentRule($fact, globalParams);
end
rule "目标匹配"
salience 90
when
$fact : DroolsFact(task != null)
then
// 显式目标分配规则:填充 Tasks.task.execute.targetList[*].targetId
globalParams.putAll(buildParam());
target($fact, globalParams);
end
rule "阵位匹配"
salience 80
when
$fact : DroolsFact(task != null)
then
// 显式阵位规则:填充 redWeapons.SubComponents.platform[].positions
globalParams.putAll(buildParam());
position($fact, globalParams);
end