火力规则打击规则实现

This commit is contained in:
MHW
2026-03-27 10:27:04 +08:00
parent 3fe32e4ac3
commit 18827cfbe7
54 changed files with 1373 additions and 1715 deletions

View File

@@ -115,15 +115,4 @@ public class BehaviortreeController extends BaseController
return toAjax(behaviortreeService.deleteBehaviortreeByIds(ids));
}
/**
* 获取行为树对应的平台
* @param id
* @return
*/
@PreAuthorize("@ss.hasPermi('system:behaviortree:query')")
@GetMapping("/getPlat/{id}")
@ApiOperation("获取行为树对应的平台")
public AjaxResult getPlat(@PathVariable("id") Integer id) {
return success(behaviortreeService.getPlat(id));
}
}

View File

@@ -3,6 +3,7 @@ package com.solution.web.controller.rule;
import com.solution.common.core.controller.BaseController;
import com.solution.common.core.domain.AjaxResult;
import com.solution.rule.domain.FireRuleExecuteDTO;
import com.solution.rule.domain.simplerulepojo.Task;
import com.solution.rule.service.FireRuleService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
@@ -63,4 +64,15 @@ public class FireRuleController extends BaseController {
public AjaxResult getComponents(@PathVariable Integer platformId){
return success(ruleService.getComponents(platformId));
}
/**
* 开始执行规则匹配
* @param task 敌方参数
* @return
*/
@PostMapping("/rule")
@ApiOperation("开始执行规则匹配")
public AjaxResult execute(@RequestBody Task task){
return success(ruleService.executeTask(task));
}
}

View File

@@ -7,10 +7,10 @@ spring:
# 主库数据源
master:
# url: jdbc:mysql://192.168.166.71:3306/behaviortreedb?useUnicode=true&characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&useSSL=true&serverTimezone=GMT%2B8
url: jdbc:mysql://192.168.166.71:3306/autosolution_db?useUnicode=true&characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&useSSL=true&serverTimezone=GMT%2B8
url: jdbc:mysql://localhost:3306/autosolution_db?useUnicode=true&characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&useSSL=true&serverTimezone=GMT%2B8
username: root
# password: 123456
password: 123456
password: 1234
# 从库数据源
slave:
# 从数据源开关/默认关闭

View File

@@ -59,11 +59,4 @@ public interface BehaviortreeMapper
* @return 结果
*/
public int deleteBehaviortreeByIds(Long[] ids);
/**
* 获取行为树对应的平台
* @param id
* @return
*/
Integer getPlatId(Integer id);
}

View File

@@ -59,11 +59,4 @@ public interface IBehaviortreeService
* @return 结果
*/
public int deleteBehaviortreeById(Long id);
/**
* 获取行为树对应的平台
* @param id
* @return
*/
Integer getPlat(Integer id);
}

View File

@@ -93,17 +93,4 @@ public class BehaviortreeServiceImpl implements IBehaviortreeService
{
return behaviortreeMapper.deleteBehaviortreeById(id);
}
/**
* 获取行为树对应的平台
* @param id
* @return
*/
@Override
public Integer getPlat(Integer id) {
if(null == id){
throw new RuntimeException(ExceptionConstants.PARAMETER_EXCEPTION);
}
return behaviortreeMapper.getPlatId(id);
}
}

View File

@@ -35,12 +35,6 @@ PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
where id = #{id}
</select>
<select id="getPlatId" resultType="java.lang.Integer">
SELECT platform_id
FROM behaviortree
WHERE id = #{id}
</select>
<insert id="insertBehaviortree" parameterType="Behaviortree" useGeneratedKeys="true" keyProperty="id">
insert into behaviortree
<trim prefix="(" suffix=")" suffixOverrides=",">

View File

@@ -16,8 +16,55 @@
rule模块
</description>
<properties>
<!-- Drools 版本,建议使用稳定版,如 7.74.1.Final 或 8.x 系列 -->
<drools.version>7.74.1.Final</drools.version>
</properties>
<dependencies>
<!-- 1. Drools 核心引擎 -->
<dependency>
<groupId>org.drools</groupId>
<artifactId>drools-core</artifactId>
<version>${drools.version}</version>
</dependency>
<dependency>
<groupId>org.drools</groupId>
<artifactId>drools-templates</artifactId>
<version>${drools.version}</version>
</dependency>
<!-- 2. KIE APIDrools 属于 KIE 项目的一部分,此依赖提供核心 API -->
<dependency>
<groupId>org.kie</groupId>
<artifactId>kie-api</artifactId>
<version>${drools.version}</version>
</dependency>
<!-- 3. 规则编译器(用于编译 .drl 等规则文件) -->
<dependency>
<groupId>org.drools</groupId>
<artifactId>drools-compiler</artifactId>
<version>${drools.version}</version>
</dependency>
<!-- 4. Spring 整合(如果需要和 Spring/Spring Boot 深度整合) -->
<dependency>
<groupId>org.kie</groupId>
<artifactId>kie-spring</artifactId>
<version>${drools.version}</version>
</dependency>
<!-- 流式解析工具-->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.15.2</version>
</dependency>
<!-- 通用工具-->
<dependency>
<groupId>com.solution</groupId>

View File

@@ -0,0 +1,68 @@
package com.solution.rule.config;
import org.kie.api.KieBase;
import org.kie.api.KieServices;
import org.kie.api.builder.KieBuilder;
import org.kie.api.builder.KieFileSystem;
import org.kie.api.builder.KieRepository;
import org.springframework.core.io.Resource;
import org.kie.api.runtime.KieContainer;
import org.kie.internal.io.ResourceFactory;
import org.kie.spring.KModuleBeanFactoryPostProcessor;
import org.kie.spring.annotations.KModuleAnnotationPostProcessor;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternResolver;
import java.io.IOException;
@Configuration
public class DroolsConfig {
//规则文件存放目录
private static final String RULE_PATH = "rules/";
private final KieServices kieServices = KieServices.Factory.get();
//扫描规则文件
@Bean
@ConditionalOnMissingBean
public KieFileSystem kieFileSystem() throws IOException {
KieFileSystem kieFileSystem = kieServices.newKieFileSystem();
ResourcePatternResolver resourcePatternResolver =
new PathMatchingResourcePatternResolver();
Resource[] files = resourcePatternResolver.getResources("classpath*:" + RULE_PATH + "*.*");
String path = null;
for (Resource file : files) {
path = RULE_PATH + file.getFilename();
kieFileSystem.write(ResourceFactory.newClassPathResource(path, "UTF-8"));
}
return kieFileSystem;
}
//创建KieContainer
@Bean
@ConditionalOnMissingBean
public KieContainer kieContainer () throws IOException {
KieRepository kieRepository = kieServices.getRepository();
kieRepository.addKieModule(kieRepository::getDefaultReleaseId);
KieBuilder kieBuilder = kieServices.newKieBuilder(kieFileSystem());
kieBuilder.buildAll();
return kieServices.newKieContainer(kieRepository.getDefaultReleaseId());
}
@Bean
@ConditionalOnMissingBean
public KieBase kieBase() throws IOException {
return kieContainer().getKieBase();
}
@Bean
@ConditionalOnMissingBean
public KModuleBeanFactoryPostProcessor kiePostProcessor() throws IOException {
return new KModuleAnnotationPostProcessor();
}
}

View File

@@ -4,6 +4,8 @@ import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import java.util.List;
/**
* 平台挂载的组件实体类
* 对应表 platform_component
@@ -29,4 +31,7 @@ public class PlatformComponent {
@ApiModelProperty(value = "组件数量")
private Long num;
@ApiModelProperty(value = "平台参数List<String>")
private List<String> platformParams;
}

View File

@@ -0,0 +1,18 @@
package com.solution.rule.domain.dto;
import lombok.Data;
import java.util.List;
@Data
public class ComponentJsonDTO {
//组件类型
private String type;
//组件名称
private String name;
//组件参数列表
private List<PlatformJsonDTO> parameters;
}

View File

@@ -0,0 +1,18 @@
package com.solution.rule.domain.dto;
import lombok.Data;
@Data
public class ComponentParamJsonDTO {
// 参数名称
private String name;
private String def;
// 参数值
private String value;
// 参数单位
private String unit;
}

View File

@@ -0,0 +1,21 @@
package com.solution.rule.domain.dto;
import lombok.Data;
import java.util.List;
@Data
public class PlatformJsonDTO {
// 装备ID
private String id;
// 装备名称
private String name;
// 平台类型 (Platform_type)
private String type;
// 子组件列表(武器、传感器、通信等)
private List<ComponentJsonDTO> components;
}

View File

@@ -1,22 +0,0 @@
package com.solution.rule.domain.dto;
import lombok.Data;
/**
* 规则请求参数
*/
@Data
public class RequestDTO {
//编队数量
private Long formationNum;
//武装直升机数量
private Long gunshipNum;
//无人机数量
private Long droneNum;
//单兵武器数量
private Long singleWeaponNum;
}

View File

@@ -0,0 +1,25 @@
package com.solution.rule.domain.dto;
import lombok.Data;
import javax.sound.midi.Track;
import java.util.List;
@Data
public class TaskJsonDTO {
//任务id
private Long attackId;
//任务名称
private String name;
//任务类型
private String dataType;
//任务下的平台
private List<PlatformJsonDTO> platforms;
//任务轨迹
private List<Track> tracks;
}

View File

@@ -0,0 +1,18 @@
package com.solution.rule.domain.dto;
import lombok.Data;
import java.util.List;
@Data
public class TrackJsonDTO {
// 轨迹ID
private String id;
// 轨迹名称
private String name;
// 轨迹点列表
private List<TrackPointJsonDTO> points;
}

View File

@@ -0,0 +1,25 @@
package com.solution.rule.domain.dto;
public class TrackPointJsonDTO {
// 轨迹点索引
private int index;
// 经度
private double longitude;
// 纬度
private double latitude;
// 高度(米)
private double height;
// 速度(米/秒)
private double speed;
// 航向角(度)
private double heading;
// 时间点(秒)
private double time;
}

View File

@@ -20,4 +20,7 @@ public class WeaponModelDTO {
@ApiModelProperty("平台组件")
private List<PlatformComponent> components;
@ApiModelProperty("平台参数List<String>")
private List<String> platformParams;
}

View File

@@ -0,0 +1,52 @@
package com.solution.rule.domain.request;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.solution.common.utils.sign.Md5Utils;
import lombok.Data;
import java.util.List;
/**
* 单个属性的定义
*/
@Data
public class Attribute {
//uuid
@JsonProperty("_uuid")
private String uuid;
/** 属性数据类型float、int、string、bool、enum */
private String attDataType;
/** 属性定义(英文标识) */
private String attDef;
/** 属性默认值 */
private String attDefaultValue;
/** 属性详细信息 */
private Object attDetail;
/** 属性说明(中文描述) */
private String attExplain;
/** 属性ID */
private String attId;
/** 属性名称(中文) */
private String attName;
/** 属性取值范围(格式:最小值|最大值) */
private String attRange;
/** 属性单位 */
private String attUnit;
/** 是否为内置属性 */
private boolean builtIn;
/** 枚举信息 */
private String enumInfo;
/** 是否为关键属性 */
private boolean isKey;
/** 是否为公共属性 */
private boolean isPublic;
/** 是否可搜索 */
private boolean isSearch;
/** 是否为文本域 */
private boolean isTextarea;
/** 模型信息(可以是对象或数组,此处定义为具体对象) */
private List<ModelInfo> mdlInfo;
/** 是否只读0-可编辑1-只读) */
private int readOnly;
}

View File

@@ -0,0 +1,18 @@
package com.solution.rule.domain.request;
import lombok.Data;
/**
* 字典项实体
*/
@Data
public class DictItem {
/** 编码 */
private String code;
/** 说明 */
private String explain;
/** 名称 */
private String name;
/** 唯一标识符 */
private String uuid;
}

View File

@@ -0,0 +1,10 @@
package com.solution.rule.domain.request;
import lombok.Data;
@Data
public class Equipments {
}

View File

@@ -0,0 +1,16 @@
package com.solution.rule.domain.request;
import lombok.Data;
@Data
public class Force {
//对象句柄
private String ObjectHandle;
//类型
private Integer type;
}

View File

@@ -0,0 +1,26 @@
package com.solution.rule.domain.request;
import lombok.Data;
import java.util.List;
/**
* 阵营实体
*/
@Data
public class ForceSides {
//分组类型
private String groupType;
private List<Force> postures;
//对象句柄
private String ObjectHandle;
//阵营名称
private String ForceSideName;
//作战目标
private String warGoal;
}

View File

@@ -0,0 +1,35 @@
package com.solution.rule.domain.request;
import com.fasterxml.jackson.annotation.JsonProperty;
import lombok.Data;
import java.util.List;
/**
* 模型信息实体
*/
@Data
public class ModelInfo {
/** 模型ID */
@JsonProperty("_id")
private String id;
/** 类别 */
private String category;
/** 分类ID */
private String classifyId;
/** 分类名称 */
private String classifyName;
/** 创建时间(时间戳) */
private long createTime;
/** 字典项列表 */
private List<DictItem> dict;
/** 模型系统ID */
private int mxSysId;
/** 名称 */
private String name;
/** 角色ID */
private int roleId;
/** 空间ID */
private int spaceId;
/** 更新时间(时间戳) */
private long updateTime;
}

View File

@@ -0,0 +1,20 @@
package com.solution.rule.domain.request;
import lombok.Data;
import java.util.List;
import java.util.Map;
/**
* 引用属性对象
*/
@Data
public class RefAttributeObject {
//属性列表
private Map<String, List<Attribute>> attributes;
private TrackParam trackParam;
}

View File

@@ -0,0 +1,23 @@
package com.solution.rule.domain.request;
import lombok.Data;
import java.util.List;
/**
* 接收智唐接口实体
*/
@Data
public class RequestDTO {
//引用属性对象(设备属性定义)
private RefAttributeObject refAttributeObject;
//阵营列表
private List<ForceSides> forceSides;
//装备列表
private List<Equipments> equipments;
private List<Tasks> tasks;
}

View File

@@ -0,0 +1,26 @@
package com.solution.rule.domain.request;
import lombok.Data;
import java.util.List;
@Data
public class Track {
//航迹名称
private String name;
//航迹开始时间
private int StartTime;
//航迹结束时间
private int EndTime;
//航迹类型
private String TrackType;
//航迹高度类型
private String HeightType;
//航迹海面类型
private String seaType;
//航迹点集合
private List<TrackPoint> TrackPoints;
//航迹所属阵营
private String Color;
//航迹总点数
private int PointCount;
}

View File

@@ -0,0 +1,13 @@
package com.solution.rule.domain.request;
import javax.sound.midi.Track;
import java.util.List;
import java.util.Map;
/**
* 航迹参数
*/
public class TrackParam {
private Map<String, List<Track>> tracks;
}

View File

@@ -0,0 +1,26 @@
package com.solution.rule.domain.request;
import lombok.Data;
/**
* 航迹节点实体
*/
@Data
public class TrackPoint {
//航迹索引
private String index;
//经度
private String longitude;
//纬度
private String latitude;
//高度
private String height;
//航速
private String speed;
//航向角
private String psia;
//时间
private String time;
//活动
private String active;
}

View File

@@ -0,0 +1,19 @@
package com.solution.rule.domain.simplerulepojo;
import lombok.Data;
@Data
public class ComponentParam {
//唯一标识符
private String uuid;
//组件默认参数
private String attDefaultValue;
//参数单位
private String attExplain;
//组件数量
private Integer number;
}

View File

@@ -0,0 +1,18 @@
package com.solution.rule.domain.simplerulepojo;
import lombok.Data;
import java.math.BigDecimal;
@Data
public class Coordinate {
//经度
private BigDecimal longitude;
//纬度
private BigDecimal latitude;
//高度
private Integer height;
}

View File

@@ -0,0 +1,18 @@
package com.solution.rule.domain.simplerulepojo;
import lombok.Data;
import java.util.List;
@Data
public class SubComponents {
//设备id
private String deviceId;
//设备名称
private String deviceName;
private List<ComponentParam> componentParams;
}

View File

@@ -0,0 +1,36 @@
package com.solution.rule.domain.simplerulepojo;
import lombok.Data;
import java.util.List;
/**
* 简单任务实体
*/
@Data
public class Task {
//任务id
private String id;
//任务名称
private String drawName;
//任务类型
private String dataType;
//任务所属阵营
private String side;
//任务威胁等级(1-3)
private String threatLevel;
//任务航迹
private List<TrackPoints> trackPoints;
//任务武器
private List<Weapon> taskWeapons;
//任务目标id
private String targetId;
}

View File

@@ -0,0 +1,24 @@
package com.solution.rule.domain.simplerulepojo;
import lombok.Data;
import java.math.BigDecimal;
@Data
public class TrackPoints extends Coordinate{
// 轨迹索引
private Integer index;
// // 轨迹点经度
// private BigDecimal longitude;
//
// // 轨迹点纬度
// private BigDecimal latitude;
//
// // 轨迹点高度
// private Integer height;
//速度
private Integer speed;
}

View File

@@ -0,0 +1,30 @@
package com.solution.rule.domain.simplerulepojo;
import lombok.Data;
import java.util.List;
@Data
public class Weapon {
//装备id
private String equipmentId;
//装备名称
private String name;
//装备类型
private String supportType;
//装备组件
private List<SubComponents> components;
//装备部署位置(经纬高)
private Coordinate coordinate;
//武器数量
private Integer number;
//目标id
private String targetId;
}

View File

@@ -7,10 +7,12 @@ import com.solution.common.constant.PlatformAndModuleConstants;
import com.solution.rule.domain.PlatformComponent;
import com.solution.rule.domain.RuleParam;
import com.solution.rule.domain.dto.WeaponModelDTO;
import com.solution.rule.handler.opponent.OpponentParamChain;
import com.solution.rule.domain.vo.ComponentCountVO;
import com.solution.rule.domain.vo.PlatformWeaponAggregateVO;
import org.springframework.stereotype.Component;
import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
@@ -26,6 +28,9 @@ public class WarplaneHandler extends AbstractRuleChainHandler {
// 组件数量增量常量
private static final long COMPONENT_COUNT_INCREMENT = 1;
@Resource
private OpponentParamChain opponentParamChain;
@Override
public RuleParam doHandler(RuleParam ruleParam) {
// 1. 参数校验
@@ -38,8 +43,6 @@ public class WarplaneHandler extends AbstractRuleChainHandler {
List<PlatformWeaponAggregateVO> resultWeapons = new ArrayList<>();
//TODO获取所有组件以及count
Iterator<WeaponModelDTO> iterator = dtoList.iterator();
while (iterator.hasNext()) {
WeaponModelDTO dto = iterator.next();
@@ -54,12 +57,16 @@ public class WarplaneHandler extends AbstractRuleChainHandler {
if(component.getName().equals(databaseWeapon.getComponentName())){
PlatformComponent component1 = new PlatformComponent();
component1.setName(databaseWeapon.getComponentName());
// TODO
component1.setPlatformParams(CollUtil.isNotEmpty(component.getPlatformParams())
? component.getPlatformParams()
: dto.getPlatformParams());
opponentParamChain.apply(ruleParam, dto, componentList);
if(databaseWeapon.getCount() > component.getNum()){
component1.setNum(component.getNum() + COMPONENT_COUNT_INCREMENT);
}else {
component1.setNum(databaseWeapon.getCount());
}
//TODO 补充基本信息 暂未完成
componentList.add(component1);
}
}

View File

@@ -0,0 +1,18 @@
package com.solution.rule.handler.opponent;
public abstract class AbstractOpponentParamHandler {
private AbstractOpponentParamHandler next;
public abstract void handle(OpponentParamContext context);
protected void doNext(OpponentParamContext context) {
if (next == null) return;
next.handle(context);
}
public void setNext(AbstractOpponentParamHandler next) {
this.next = next;
}
}

View File

@@ -0,0 +1,24 @@
package com.solution.rule.handler.opponent;
import com.solution.rule.domain.PlatformComponent;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
@Component
@Order(2)
public class Ammo20Handler extends AbstractOpponentParamHandler {
@Override
public void handle(OpponentParamContext context) {
Long ammo = context.getParamLong("ammo");
if (ammo != null && ammo <= 20) {
PlatformComponent reaction = new PlatformComponent();
reaction.setType("weapon");
reaction.setName("reaction_ammo_le_20");
reaction.setNum(1L);
context.addReactionComponent(reaction);
}
doNext(context);
}
}

View File

@@ -0,0 +1,24 @@
package com.solution.rule.handler.opponent;
import com.solution.rule.domain.PlatformComponent;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
@Component
@Order(3)
public class Distance50Handler extends AbstractOpponentParamHandler {
@Override
public void handle(OpponentParamContext context) {
Long distance = context.getParamLong("distance");
if (distance != null && distance <= 50) {
PlatformComponent reaction = new PlatformComponent();
reaction.setType("weapon");
reaction.setName("reaction_distance_le_50");
reaction.setNum(1L);
context.addReactionComponent(reaction);
}
doNext(context);
}
}

View File

@@ -0,0 +1,21 @@
package com.solution.rule.handler.opponent;
import com.solution.rule.domain.PlatformComponent;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
@Component
@Order(4)
public class FallbackHandler extends AbstractOpponentParamHandler {
@Override
public void handle(OpponentParamContext context) {
PlatformComponent reaction = new PlatformComponent();
reaction.setType("weapon");
reaction.setName("reaction_default");
reaction.setNum(0L);
context.addReactionComponent(reaction);
doNext(context);
}
}

View File

@@ -0,0 +1,40 @@
package com.solution.rule.handler.opponent;
import cn.hutool.core.collection.CollUtil;
import com.solution.rule.domain.PlatformComponent;
import com.solution.rule.domain.RuleParam;
import com.solution.rule.domain.dto.WeaponModelDTO;
import org.springframework.stereotype.Component;
import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.util.List;
@Component
public class OpponentParamChain {
@Resource
private List<AbstractOpponentParamHandler> handlers;
private AbstractOpponentParamHandler first;
@PostConstruct
private void construct() {
if (CollUtil.isEmpty(handlers)) {
return;
}
this.first = handlers.get(0);
for (int i = 0; i < handlers.size(); i++) {
AbstractOpponentParamHandler current = handlers.get(i);
AbstractOpponentParamHandler next = (i == handlers.size() - 1) ? null : handlers.get(i + 1);
current.setNext(next);
}
}
public void apply(RuleParam ruleParam, WeaponModelDTO dto, List<PlatformComponent> resultComponents) {
if (first == null) return;
OpponentParamContext context = new OpponentParamContext(ruleParam, dto, resultComponents);
first.handle(context);
}
}

View File

@@ -0,0 +1,88 @@
package com.solution.rule.handler.opponent;
import com.solution.rule.domain.PlatformComponent;
import com.solution.rule.domain.RuleParam;
import com.solution.rule.domain.dto.WeaponModelDTO;
import lombok.Getter;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
@Getter
public class OpponentParamContext {
private static final Pattern NUMBER_PATTERN = Pattern.compile("(\\d+(?:\\.\\d+)?)");
private final RuleParam ruleParam;
private final WeaponModelDTO weaponModelDTO;
private final List<PlatformComponent> resultComponents;
private final Map<String, String> paramMap;
public OpponentParamContext(RuleParam ruleParam, WeaponModelDTO weaponModelDTO, List<PlatformComponent> resultComponents) {
this.ruleParam = ruleParam;
this.weaponModelDTO = weaponModelDTO;
this.resultComponents = resultComponents;
this.paramMap = parseParams(weaponModelDTO);
}
public String getParamRaw(String key) {
if (key == null) return null;
return paramMap.get(key.toLowerCase(Locale.ROOT));
}
public Long getParamLong(String key) {
String raw = getParamRaw(key);
if (raw == null) return null;
Matcher m = NUMBER_PATTERN.matcher(raw);
if (!m.find()) return null;
try {
return (long) Double.parseDouble(m.group(1));
} catch (Exception e) {
return null;
}
}
public void addReactionComponent(PlatformComponent component) {
if (component == null || component.getName() == null) return;
for (PlatformComponent existing : resultComponents) {
if (component.getName().equals(existing.getName())) {
return;
}
}
resultComponents.add(component);
}
private static Map<String, String> parseParams(WeaponModelDTO dto) {
Map<String, String> map = new HashMap<>();
if (dto == null || dto.getPlatformParams() == null) return map;
for (String item : dto.getPlatformParams()) {
if (item == null) continue;
String s = item.trim();
if (s.isEmpty()) continue;
String[] parts;
if (s.contains("=")) {
parts = s.split("=", 2);
} else if (s.contains(":")) {
parts = s.split(":", 2);
} else if (s.contains("")) {
parts = s.split("", 2);
} else {
continue;
}
if (parts.length != 2) continue;
String key = parts[0].trim().toLowerCase(Locale.ROOT);
String val = parts[1].trim();
if (!key.isEmpty() && !val.isEmpty()) {
map.put(key, val);
}
}
return map;
}
}

View File

@@ -0,0 +1,123 @@
## opponent对方参数嵌套责任链说明
本目录新增了一套**“嵌套责任链”**,用于在已有规则链(`AbstractRuleChainHandler` / `RuleChainHandler`)执行过程中,再额外对“对方传入的平台参数”做二次判断,并把**我方的反应**写入到 `RuleParam.resultWeapons` 对应平台的 `components` 中。
> 你原本已经在用“规则链”处理 `RuleParam`;这里是在 `WarplaneHandler` 内部再次调用一条新的链,因此属于 **责任链嵌套责任链**。
---
### 1. 改动点概览(这个目录配套的改动)
- **`WeaponModelDTO` 增加字段**
- `platformParams: List<String>`
- 用于接收平台维度的参数列表(例如对方速度、弹量、距离等)。
- **`PlatformComponent` 增加字段**
- `platformParams: List<String>`
- 用于在“组件维度”也能承载同样的参数(如果你希望参数挂在组件上)。
- **`WarplaneHandler`第55行 `// TODO` 下方)接入嵌套链**
- 将平台参数透传到结果组件 `component1.platformParams`
- 优先取 `component.platformParams`
- 若组件没传,则取 `dto.platformParams`
- 调用 `OpponentParamChain.apply(ruleParam, dto, componentList)`
- 读取 `dto.platformParams` 中的对方参数
- 按责任链规则生成“反应组件”
- 把反应组件加入当前平台的 `componentList`(最终进入 `RuleParam.resultWeapons`
---
### 2. 对方参数的传参格式约定
目前解析逻辑位于 `OpponentParamContext`,支持以下分隔符:
- `key=value`
- `key:value`
- `keyvalue`(中文冒号)
并会从 `value` 中提取**第一个数字**作为判断依据(例如 `200km` 会提取为 `200`)。
建议前端/调用方传参示例:
```text
["speed=200km", "ammo=20", "distance=50km"]
```
目前内置识别的 key
- `speed`:速度
- `ammo`:弹量
- `distance`:距离
---
### 3. 目录结构与职责(类说明)
- **`OpponentParamChain`**
- 责任链的“组装与入口”。
- Spring `@Component` + `@PostConstruct`:自动获取容器中的 `AbstractOpponentParamHandler` 实现列表并按顺序串起来。
- `apply(ruleParam, dto, resultComponents)`:对外入口,创建上下文并触发链路执行。
- **`AbstractOpponentParamHandler`**
- 对方参数链的抽象 Handler。
- 只负责:
- `handle(context)`:当前节点处理
- `doNext(context)`:传递到下一个节点
- **`OpponentParamContext`**
- 链路执行上下文(把链执行需要的对象集中起来):
- `RuleParam ruleParam`:当前规则执行参数
- `WeaponModelDTO weaponModelDTO`:当前处理的平台 DTO承载 `platformParams`
- `List<PlatformComponent> resultComponents`:本平台最终要返回的组件列表(也就是要写入 `resultWeapons` 的列表)
- 关键能力:
- `getParamLong(key)`:从 `platformParams` 中按 key 取值并解析出数字
- `addReactionComponent(component)`:把“反应组件”加入 `resultComponents`(按 name 做简单去重,避免循环里重复加入)
---
### 4. 当前内置的 4 个链节点(最少四个)
这 4 个节点都实现了 `AbstractOpponentParamHandler`,并通过 `@Order` 控制执行顺序:
- **`Speed200Handler`@Order(1)**
- 条件:`speed >= 200`
- 反应:加入组件
- `name = reaction_speed_ge_200`
- `type = weapon`
- `num = 1`
- **`Ammo20Handler`@Order(2)**
- 条件:`ammo <= 20`
- 反应:加入组件
- `name = reaction_ammo_le_20`
- `type = weapon`
- `num = 1`
- **`Distance50Handler`@Order(3)**
- 条件:`distance <= 50`
- 反应:加入组件
- `name = reaction_distance_le_50`
- `type = weapon`
- `num = 1`
- **`FallbackHandler`@Order(4)**
- 兜底:无论是否命中其它规则,都加入一个默认反应(便于你观察链是否运行)
- 反应:加入组件
- `name = reaction_default`
- `type = weapon`
- `num = 0`
> 注意:这些“反应组件”目前只是用 `PlatformComponent` 承载并加入到返回的 `components` 列表中,保证**一定能落到 `RuleParam.resultWeapons`**。
---
### 5. 如何扩展新规则(你后续要加更多链节点时)
按照下面步骤即可:
1. 在本目录新增一个类,继承 `AbstractOpponentParamHandler`
2. 加上 `@Component``@Order(n)`n 决定执行顺序)
3.`handle` 中从 `context.getParamLong("xxx")` 取值判断
4. 组装一个 `PlatformComponent` 作为“反应”,调用 `context.addReactionComponent(...)`
5. 最后 `doNext(context)` 传递到下一节点

View File

@@ -0,0 +1,24 @@
package com.solution.rule.handler.opponent;
import com.solution.rule.domain.PlatformComponent;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
@Component
@Order(1)
public class Speed200Handler extends AbstractOpponentParamHandler {
@Override
public void handle(OpponentParamContext context) {
Long speed = context.getParamLong("speed");
if (speed != null && speed >= 200) {
PlatformComponent reaction = new PlatformComponent();
reaction.setType("weapon");
reaction.setName("reaction_speed_ge_200");
reaction.setNum(1L);
context.addReactionComponent(reaction);
}
doNext(context);
}
}

View File

@@ -0,0 +1,120 @@
//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 -> 参数】索引MapO(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

@@ -2,6 +2,7 @@ package com.solution.rule.service;
import com.solution.rule.domain.FireRuleExecuteDTO;
import com.solution.rule.domain.PlatformComponent;
import com.solution.rule.domain.simplerulepojo.Task;
import com.solution.rule.domain.vo.PlatformComponentNamesVO;
import com.solution.rule.domain.vo.PlatformWeaponAggregateVO;
@@ -37,4 +38,11 @@ public interface FireRuleService {
* @return
*/
List<PlatformComponent> getComponents(Integer platformId);
/**
* 开始执行规则匹配
* @param task
* @return
*/
Task executeTask(Task task);
}

View File

@@ -7,14 +7,20 @@ import com.solution.rule.domain.FireRuleExecuteDTO;
import com.solution.rule.domain.PlatformComponent;
import com.solution.rule.domain.RuleParam;
import com.solution.rule.domain.dto.WeaponModelDTO;
import com.solution.rule.domain.simplerulepojo.Task;
import com.solution.rule.domain.simplerulepojo.Weapon;
import com.solution.rule.domain.vo.ComponentCountVO;
import com.solution.rule.domain.vo.PlatformComponentNamesVO;
import com.solution.rule.domain.vo.PlatformWeaponAggregateVO;
import com.solution.rule.domain.vo.WeaponModelVO;
import com.solution.rule.mapper.FireRuleMapper;
import com.solution.rule.service.FireRuleService;
import com.solution.rule.simpstrategy.FireRUleType;
import com.solution.rule.simpstrategy.FireRuleStrategy;
import com.solution.rule.simpstrategy.FireRuleStrategyFactory;
import com.solution.rule.strategy.SceneStrategy;
import com.solution.rule.strategy.SceneStrategyFactory;
import org.kie.api.KieBase;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@@ -31,9 +37,15 @@ public class FireRuleServiceImpl implements FireRuleService {
@Autowired
private SceneStrategyFactory strategyFactory;
@Autowired
private FireRuleStrategyFactory fireStrategyFactory;
@Autowired
private FireRuleMapper ruleMapper;
@Autowired
private KieBase kieBase;
/* @Override
public WeaponModelVO execute(Integer sceneType, WeaponModelDTO weaponModelDTO) {
if(ObjectUtil.isNull(sceneType) || ObjectUtil.isEmpty(weaponModelDTO)){
@@ -153,6 +165,28 @@ public class FireRuleServiceImpl implements FireRuleService {
return ruleMapper.getComponents(platformId);
}
/**
* 执行任务
* @param task
* @return
*/
@Override
public Task executeTask(Task task) {
if(ObjectUtil.isEmpty(task)){
throw new RuntimeException(ExceptionConstants.PARAMETER_EXCEPTION);
}
String dataType = task.getDataType();
if("打击".contains(dataType)){
FireRuleStrategy strategy = fireStrategyFactory.getStrategy(0);
task = strategy.mappingTask(task);
} else {
FireRuleStrategy strategy = fireStrategyFactory.getStrategy(1);
task = strategy.mappingTask(task);
}
return task;
}
/**
* 获取所有组件以及数量
* @return

View File

@@ -0,0 +1,40 @@
package com.solution.rule.simpstrategy;
import com.solution.rule.enums.SceneType;
public enum FireRUleType {
HIT(0, "打击"),
DISTURB(2, "干扰");
private final int code;
private final String description;
FireRUleType(int code, String description) {
this.code = code;
this.description = description;
}
public int getCode() {
return code;
}
public String getDescription() {
return description;
}
/**
* 根据数字编码获取对应的枚举
* @param code 前端传递的数字
* @return 枚举实例
* @throws IllegalArgumentException 如果找不到对应枚举
*/
public static FireRUleType fromCode(int code) {
for (FireRUleType type : values()) {
if (type.code == code) {
return type;
}
}
throw new IllegalArgumentException("未知的任务类型编码: " + code);
}
}

View File

@@ -0,0 +1,13 @@
package com.solution.rule.simpstrategy;
import com.solution.rule.domain.FireRuleExecuteDTO;
import com.solution.rule.domain.simplerulepojo.Task;
import com.solution.rule.enums.SceneType;
public interface FireRuleStrategy {
Task mappingTask(Task task);
FireRUleType getFireRuleType();
}

View File

@@ -0,0 +1,45 @@
package com.solution.rule.simpstrategy;
import com.solution.rule.enums.SceneType;
import com.solution.rule.strategy.SceneStrategy;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import javax.annotation.PostConstruct;
import java.util.EnumMap;
import java.util.List;
import java.util.Map;
@Component
public class FireRuleStrategyFactory {
@Autowired
private List<FireRuleStrategy> strategyList;
private final Map<FireRUleType, FireRuleStrategy> strategyMap = new EnumMap<>(FireRUleType.class);
@PostConstruct
public void init() {
for (FireRuleStrategy strategy : strategyList) {
FireRUleType type = strategy.getFireRuleType();
if (strategyMap.containsKey(type)) {
throw new IllegalStateException("重复的场景类型: " + type);
}
strategyMap.put(type, strategy);
}
}
/**
* 根据前端传递的数字编码获取对应的策略
* @param code 前端传递的数字
* @return 策略实现
* @throws IllegalArgumentException 如果编码无效或策略未注册
*/
public FireRuleStrategy getStrategy(int code) {
SceneType type = SceneType.fromCode(code);
FireRuleStrategy strategy = strategyMap.get(type);
if (strategy == null) {
throw new IllegalArgumentException("未找到任务 " + code + " 对应的策略实现");
}
return strategy;
}
}

View File

@@ -0,0 +1,40 @@
package com.solution.rule.simpstrategy.impl;
import com.solution.rule.domain.simplerulepojo.Task;
import com.solution.rule.simpstrategy.FireRUleType;
import com.solution.rule.simpstrategy.FireRuleStrategy;
import org.kie.api.KieBase;
import org.kie.api.runtime.KieSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
@Component
public class BlowStrategy implements FireRuleStrategy {
private static final String TASK_TYPE = "打击任务";
@Autowired
private KieBase kieBase;
@Override
public Task mappingTask(Task task) {
KieSession kieSession = kieBase.newKieSession();
Task redTask = new Task();
redTask.setTargetId(task.getId());
kieSession.insert(redTask);
kieSession.insert(task);
// 👇 核心:根据策略选择规则组
kieSession.getAgenda()
.getAgendaGroup(TASK_TYPE)
.setFocus();
kieSession.fireAllRules();
return redTask;
}
@Override
public FireRUleType getFireRuleType() {
return FireRUleType.HIT;
}
}

View File

@@ -0,0 +1,15 @@
<?xml version="1.0" encoding="UTF-8" ?>
<kmodule xmlns="http://www.drools.org/xsd/kmodule">
<!--
name:指定kbase的名称可以任意但是需要唯一
packages:指定规则文件的目录,需要根据实际情况填写,否则无法加载到规则文件
default:指定当前kbase是否为默认
-->
<kbase name="myKbase1" packages="rules" default="true">
<!--
name:指定ksession名称可以任意但是需要唯一
default:指定当前session是否为默认
-->
<ksession name="ksession-rule" default="true"/>
</kbase>
</kmodule>

View File

@@ -0,0 +1,14 @@
package rules;
import com.solution.rule.domain.simplerulepojo.Task
rule "任务入口"
agenda-group "打击任务"
when
$task : Task(dataType == "A")
then
kcontext.getKieRuntime().getAgenda()
.getAgendaGroup("MATCH")
.setFocus();
end

File diff suppressed because it is too large Load Diff