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.FireRuleOutputVO; import com.solution.rule.domain.ultimately.vo.FireRuleRouteTrackPointVO; import com.solution.rule.domain.ultimately.vo.FireRuleSceneTaskNodeVO; import com.solution.rule.domain.ultimately.vo.FireRuleSceneTaskPayloadVO; import com.solution.rule.domain.ultimately.vo.FireRuleTrackParamVO; import com.solution.rule.domain.ultimately.vo.FireRuleTrackRouteVO; 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 节点(一个装备 -> 一个任务节点)。 * *

字段映射约定:

* */ 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 toTaskNodes(List redWeapons) { if (redWeapons == null || redWeapons.isEmpty()) { return Collections.emptyList(); } List 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 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 warZone = toWarZonePolygon(blueTask.getWarZoneLocation()); Map 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 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)); } } } /** * 航迹规则:按蓝方 trackPoints 生成 {@link FireRuleTrackParamVO#routeMap} 条目(JSON 顶层 key=航迹 id), * 并将同一 id 写入对应红方任务 {@code execute[0].targetList[*].moveRouteId}。多蓝方任务循环时 merge,不覆盖已有 id。 */ @SuppressWarnings("rawtypes") public static void fillTrackParamAndBindMoveRoute(FireRuleOutputVO out, FireRuleTaskInputDTO blueTask, Map params) { if (out == null || blueTask == null || out.getTasks() == null || out.getTasks().isEmpty()) { return; } ensureTrackParam(out); List tasks = out.getTasks(); List reds = out.getRedWeapons(); if (reds == null) { reds = Collections.emptyList(); } List warPoly = toWarZonePolygon(blueTask.getWarZoneLocation()); Coord blueAnchor = computeBlueAnchor(blueTask); Coord clampAnchor = resolveClampAnchor(blueAnchor, warPoly); boolean zoneClamp = Boolean.parseBoolean(String.valueOf(params.getOrDefault("enableTrackWarZoneClamp", true))); String dirMode = str(params, "trackPointDirectionMode", "head2next"); double fallbackBrg = readDouble(params, "trackFallbackBearingDeg", readDouble(params, "fallbackBearingDeg", 0d)); double mainBearing = computeTrackBearingDeg(blueTask, dirMode, fallbackBrg); String algo = str(params, "trackRouteAlgorithm", "followBlue"); String nameSuffix = str(params, "trackRouteNameSuffix", "航迹"); String groundType = str(params, "trackGroundTrackType", "routeLineGround"); String blueIdSeg = sanitizeRouteIdSegment(nz(blueTask.getId())); for (int i = 0; i < tasks.size(); i++) { FireRuleSceneTaskNodeVO node = tasks.get(i); if (node == null) { continue; } FireRuleRedWeaponEquipmentVO red = i < reds.size() ? reds.get(i) : null; List nodes = extractSortedBlueTrackNodes(blueTask); if (nodes.isEmpty()) { continue; } List transformed = applyTrackRouteAlgorithm(nodes, algo, params, mainBearing, i); int extraMax = readInt(params, "trackExtraNodesMax", 0); if (extraMax > 0) { transformed = injectExtraTrackNodes(transformed, extraMax); } if (zoneClamp && warPoly.size() >= 3) { transformed = clampTrackNodesToWarZone(transformed, warPoly, clampAnchor); } boolean air = resolveAirTrack(blueTask, red, params); String routeName = nz(node.getDrawName()) + nameSuffix; String routeId = buildUniqueRouteId(out.getTrackParam().getRouteMap(), blueIdSeg, sanitizeRouteIdSegment(nz(node.getId())), i); FireRuleTrackRouteVO route = buildTrackRouteVo(transformed, routeName, air, groundType); out.getTrackParam().getRouteMap().put(routeId, route); bindMoveRouteIdToFirstExecute(node, routeId); } } private static void ensureTrackParam(FireRuleOutputVO out) { if (out.getTrackParam() == null) { out.setTrackParam(new FireRuleTrackParamVO()); } } private static String buildUniqueRouteId(Map existing, String blueSeg, String nodeSeg, int index) { String base = "route_" + blueSeg + "_" + nodeSeg + "_" + index; if (existing == null || !existing.containsKey(base)) { return base; } int k = 1; while (existing.containsKey(base + "_" + k)) { k++; } return base + "_" + k; } private static void bindMoveRouteIdToFirstExecute(FireRuleSceneTaskNodeVO node, String routeId) { if (node == null || isBlank(routeId)) { return; } FireRuleSceneTaskPayloadVO payload = node.getTask(); if (payload == null || payload.getExecute() == null || payload.getExecute().isEmpty()) { return; } FireRuleExecuteBlockVO block = payload.getExecute().get(0); if (block == null || block.getTargetList() == null) { return; } for (FireRuleExecuteTargetItemVO item : block.getTargetList()) { if (item != null) { item.setMoveRouteId(routeId); } } } private static FireRuleTrackRouteVO buildTrackRouteVo(List nodes, String name, boolean air, String groundType) { FireRuleTrackRouteVO vo = new FireRuleTrackRouteVO(); vo.setName(name); vo.setStartTime(null); vo.setEndTime(null); vo.setTrackType(air ? "routeLineAir" : groundType); vo.setHeightType("msl"); vo.setSeaType("seaLevel"); List pts = new ArrayList<>(nodes.size()); for (int j = 0; j < nodes.size(); j++) { TrackNode tn = nodes.get(j); FireRuleRouteTrackPointVO p = new FireRuleRouteTrackPointVO(); p.setIndex(String.valueOf(j + 1)); p.setLongitude(formatCoordNumber(tn.coord.lon)); p.setLatitude(formatCoordNumber(tn.coord.lat)); p.setHeight(tn.coord.height != null ? formatCoordNumber(tn.coord.height) : "0"); p.setSpeed(tn.speed != null ? formatCoordNumber(tn.speed) : null); pts.add(p); } vo.setTrackPoints(pts); vo.setPointCount(pts.size()); return vo; } private static String formatCoordNumber(double v) { return String.valueOf(v); } private static boolean resolveAirTrack(FireRuleTaskInputDTO blue, FireRuleRedWeaponEquipmentVO red, Map params) { String dt = blue != null ? nz(blue.getDataType()) : ""; if (csvContainsAny(str(params, "trackAirDataTypeCsv", ""), dt, false)) { return true; } String blob = nz(blue != null ? blue.getDrawName() : ""); if (red != null) { blob += " " + nz(red.getName()) + " " + nz(red.getPlatformType()); } return csvContainsAny(str(params, "trackAirKeywordsCsv", ""), blob, false); } private static boolean csvContainsAny(String csv, String text, boolean tokenAsEquals) { if (isBlank(csv) || text == null) { return false; } String t = text.toLowerCase(); for (String part : csv.split(",")) { String k = part.trim(); if (k.isEmpty()) { continue; } if (tokenAsEquals) { if (t.equalsIgnoreCase(k)) { return true; } } else if (text.contains(k) || t.contains(k.toLowerCase())) { return true; } } return false; } private static String sanitizeRouteIdSegment(String raw) { if (raw == null || raw.isEmpty()) { return "x"; } String s = raw.replaceAll("[^a-zA-Z0-9_-]", "_"); return s.isEmpty() ? "x" : s; } private static class TrackNode { Coord coord; Double speed; TrackNode(Coord coord, Double speed) { this.coord = coord; this.speed = speed; } } private static List extractSortedBlueTrackNodes(FireRuleTaskInputDTO blueTask) { List list = new ArrayList<>(); if (blueTask == null || blueTask.getTrackPoints() == null) { return list; } List pts = new ArrayList<>(blueTask.getTrackPoints()); pts.sort((a, b) -> { int ia = a != null && a.getIndex() != null ? a.getIndex() : 0; int ib = b != null && b.getIndex() != null ? b.getIndex() : 0; return Integer.compare(ia, ib); }); for (FireRuleTrackPointDTO p : pts) { if (p == null || p.getLongitude() == null || p.getLatitude() == null) { continue; } list.add(new TrackNode(new Coord(p.getLongitude(), p.getLatitude(), p.getHeight()), p.getSpeed())); } return list; } private static List applyTrackRouteAlgorithm(List nodes, String algo, Map params, double mainBearing, int taskIndex) { if (nodes == null || nodes.isEmpty()) { return nodes; } String a = algo == null ? "followBlue" : algo.trim(); if ("shortestPath".equalsIgnoreCase(a)) { return applyShortestPath(nodes, params); } if ("flank".equalsIgnoreCase(a)) { return applyFlank(nodes, params, taskIndex); } if ("jam".equalsIgnoreCase(a)) { return applyJam(nodes, params, mainBearing); } return copyTrackNodes(nodes); } private static List copyTrackNodes(List nodes) { List out = new ArrayList<>(nodes.size()); for (TrackNode n : nodes) { out.add(new TrackNode(new Coord(n.coord.lon, n.coord.lat, n.coord.height), n.speed)); } return out; } private static List applyShortestPath(List nodes, Map params) { int segN = readInt(params, "trackShortPathSegments", 3); if (segN < 1) { segN = 1; } List out = new ArrayList<>(); for (int i = 0; i < nodes.size(); i++) { if (i == 0) { out.add(copyNode(nodes.get(i))); continue; } Coord a = nodes.get(i - 1).coord; Coord b = nodes.get(i).coord; Double spPrev = nodes.get(i - 1).speed; Double spNext = nodes.get(i).speed; for (int s = 1; s < segN; s++) { double t = (double) s / (double) segN; double lon = a.lon + (b.lon - a.lon) * t; double lat = a.lat + (b.lat - a.lat) * t; Double h = null; if (a.height != null && b.height != null) { h = a.height + (b.height - a.height) * t; } else if (b.height != null) { h = b.height; } else { h = a.height; } Double spd = null; if (spPrev != null && spNext != null) { spd = spPrev + (spNext - spPrev) * t; } else if (spNext != null) { spd = spNext; } else { spd = spPrev; } out.add(new TrackNode(new Coord(lon, lat, h), spd)); } out.add(copyNode(nodes.get(i))); } return out; } private static TrackNode copyNode(TrackNode n) { return new TrackNode(new Coord(n.coord.lon, n.coord.lat, n.coord.height), n.speed); } private static List applyFlank(List nodes, Map params, int taskIndex) { double offsetM = readDouble(params, "trackFlankOffsetMeters", 800d); String sideMode = str(params, "trackFlankSideMode", "alternate"); List out = new ArrayList<>(nodes.size()); for (int i = 0; i < nodes.size(); i++) { Coord c = nodes.get(i).coord; double brg; if (i < nodes.size() - 1) { Coord nxt = nodes.get(i + 1).coord; brg = bearingDeg(c.lon, c.lat, nxt.lon, nxt.lat); } else if (i > 0) { Coord prev = nodes.get(i - 1).coord; brg = bearingDeg(prev.lon, prev.lat, c.lon, c.lat); } else { brg = 0d; } int sign = flankSign(sideMode, i, taskIndex); Coord moved = moveByMeters(c, sign * offsetM, brg + 90d); out.add(new TrackNode(moved, nodes.get(i).speed)); } return out; } private static int flankSign(String mode, int pointIndex, int taskIndex) { if ("left".equalsIgnoreCase(mode)) { return 1; } if ("right".equalsIgnoreCase(mode)) { return -1; } return (pointIndex + taskIndex) % 2 == 0 ? 1 : -1; } private static List applyJam(List nodes, Map params, double mainBearing) { double wobble = readDouble(params, "trackJamWobbleMeters", 400d); double periods = readDouble(params, "trackJamSegments", 4d); if (periods < 0.5d) { periods = 0.5d; } int n = nodes.size(); List out = new ArrayList<>(n); for (int i = 0; i < n; i++) { double frac = n <= 1 ? 0d : (double) i / (double) (n - 1); double lateral = wobble * Math.sin(2d * Math.PI * periods * frac); Coord c = moveByMeters(nodes.get(i).coord, lateral, mainBearing + 90d); out.add(new TrackNode(c, nodes.get(i).speed)); } return out; } private static List injectExtraTrackNodes(List nodes, int extraMax) { if (nodes == null || nodes.size() < 2 || extraMax <= 0) { return nodes; } int segs = nodes.size() - 1; List perSeg = new ArrayList<>(Collections.nCopies(segs, 0)); int base = extraMax / segs; int rem = extraMax % segs; for (int s = 0; s < segs; s++) { perSeg.set(s, base + (s < rem ? 1 : 0)); } List out = new ArrayList<>(); for (int i = 0; i < nodes.size(); i++) { out.add(copyNode(nodes.get(i))); if (i >= nodes.size() - 1) { break; } int ins = perSeg.get(i); Coord a = nodes.get(i).coord; Coord b = nodes.get(i + 1).coord; Double sa = nodes.get(i).speed; Double sb = nodes.get(i + 1).speed; for (int k = 1; k <= ins; k++) { double t = (double) k / (double) (ins + 1); double lon = a.lon + (b.lon - a.lon) * t; double lat = a.lat + (b.lat - a.lat) * t; Double h = null; if (a.height != null && b.height != null) { h = a.height + (b.height - a.height) * t; } else if (b.height != null) { h = b.height; } else { h = a.height; } Double spd = null; if (sa != null && sb != null) { spd = sa + (sb - sa) * t; } else if (sb != null) { spd = sb; } else { spd = sa; } out.add(new TrackNode(new Coord(lon, lat, h), spd)); } } return out; } private static List clampTrackNodesToWarZone(List nodes, List poly, Coord anchor) { List out = new ArrayList<>(nodes.size()); for (TrackNode n : nodes) { Coord c = n.coord; if (!isPointInPolygon(c, poly)) { c = projectInsidePolygon(c, anchor, poly); } out.add(new TrackNode(c, n.speed)); } return out; } private static Coord resolveClampAnchor(Coord blueAnchor, List poly) { if (poly.size() >= 3) { if (blueAnchor != null && isPointInPolygon(blueAnchor, poly)) { return blueAnchor; } return polygonCentroid(poly); } return blueAnchor != null ? blueAnchor : new Coord(0d, 0d, null); } private static Coord polygonCentroid(List poly) { double sx = 0, sy = 0; for (Coord c : poly) { sx += c.lon; sy += c.lat; } int n = poly.size(); return new Coord(sx / n, sy / n, null); } /** * 目标分配:为每个红方 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 tasks, List redWeapons, FireRuleTaskInputDTO blueTask, Map params) { if (tasks == null || tasks.isEmpty() || blueTask == null) { return; } List 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 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 execute = new ArrayList<>(); execute.add(block); payload.setExecute(execute); } } private static Double resolveRedWeaponHitRate(String weaponId, List 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 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 extractBlueTargetEquipmentIds(FireRuleTaskInputDTO blueTask, Map params) { List 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 buildMissionList(FireRuleRedWeaponEquipmentVO redWeapon) { if (redWeapon == null || redWeapon.getSubComponents() == null || redWeapon.getSubComponents().getWeapon() == null) { return null; } List 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 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 toWarZonePolygon(List warZone) { List 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 parseDistanceByPlatformCsv(String csv) { Map 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 byPlatform, double defKm) { String name = red != null ? nz(red.getName()) : ""; String platform = red != null ? nz(red.getPlatformType()) : ""; for (Map.Entry 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 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 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 asPosition(double lon, double lat, double height) { List 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; } }