Compare commits
20 Commits
e63ae56021
..
main
| Author | SHA1 | Date | |
|---|---|---|---|
| bc1cd45c38 | |||
| 2342b63fc2 | |||
| ac7a3abda9 | |||
| 3b851a195e | |||
| 39a34577da | |||
| fd40217ab8 | |||
| 85c2062318 | |||
| 5df451011c | |||
| 00ca7044c7 | |||
| a4fd3d3092 | |||
| 8ee21e5e80 | |||
| c4ea51b7e6 | |||
| caadd87d8f | |||
| 82fb409a9e | |||
| 0b060b0a74 | |||
| 91b390d577 | |||
| 6f8b599629 | |||
| 3d0b835593 | |||
| f86ffb511e | |||
| 7d0bfc123b |
@@ -2,3 +2,4 @@
|
||||
- [UE5.7 Python API](ue57-python-api.md) — 实测 API 差异(set_actor_rotation、new_level、CWD、import 路径、Rotator 关键字参数)
|
||||
- [V01 Bugfix](level-builder-bugfix-v01.md) — 8个白模关卡问题诊断修复(搭建指南6+解析器双重解析+构建器静默fallback)
|
||||
- [BSP Pivot Types](bsp-pivot-types.md) — 38种 BSP 资产实测锚点+自动补偿机制(角落/底边中心/底面中心)
|
||||
- [交互系统架构](interaction-effect-architecture.md) — v1.0 Effect/Action 数据驱动架构(Manager在GI、AInfo Tick、门派生、Prompt独立)
|
||||
|
||||
@@ -0,0 +1,31 @@
|
||||
---
|
||||
name: interaction-effect-architecture
|
||||
description: 交互系统 v1.0 Effect/Action 数据驱动架构决策记录
|
||||
metadata:
|
||||
type: project
|
||||
---
|
||||
|
||||
## 交互系统架构决策(v1.0 重构,2026-06-11)
|
||||
|
||||
### 核心架构:Effect/Action 数据驱动
|
||||
|
||||
交互物不关心"交互后发生什么",只配置 Effect(由 Action 组成)交给 EffectManager 执行。
|
||||
|
||||
**Why:** v0.1 用 switch(Type) 硬编码,新增交互类型需改代码。v1.0 配数据即可。
|
||||
|
||||
### Manager 归属
|
||||
- FInteractionManager / FEffectManager 是普通 C++ 类,不是 UObject
|
||||
- 由 ASystemDriver (AInfo) 持有,随 World 生灭
|
||||
- 不依赖 UE Subsystem 生命周期,显式控制创建顺序和 Tick 顺序
|
||||
- 所有 UObject 引用用 TWeakObjectPtr,回调用 TFunction
|
||||
- GameInstance 不持有任何交互系统对象,只有 UPersistenceSubsystem 跨 World
|
||||
|
||||
### 分层规则
|
||||
- 表现层只读 Manager 缓存(getter),不碰 Component
|
||||
- Manager 在选择变化时从 Component 读一次并缓存
|
||||
- 逻辑事件仅用于 "A 影响 B"(如 Consume → Persistence)
|
||||
|
||||
### 协调方式
|
||||
- Character 输入回调通过 ASystemDriver::Get(World) 访问两个 Manager
|
||||
- Driver::BeginPlay 中 TFunction 连线 EffectManager.OnEffectComplete → Manager.OnInteractionFinished
|
||||
- PromptComponent 通过 Driver 获取 Manager,只读缓存
|
||||
@@ -2,3 +2,4 @@
|
||||
|
||||
- [Gitea Token Permission](gitea-token-permission.md) — reviewer token 仅可评论,标签操作需用 PM token
|
||||
- [P-006 Review](p006-review-note.md) — Issue #17 白模搭建审查通过记录
|
||||
- [P-009 Review](p009-review-note.md) — Issue #20 收集系统程序设计审查通过记录
|
||||
|
||||
@@ -0,0 +1,19 @@
|
||||
---
|
||||
name: p009-review-note
|
||||
description: Issue #20 P-009 收集系统程序设计审查通过记录
|
||||
metadata:
|
||||
type: project
|
||||
---
|
||||
|
||||
## P-009 收集系统程序设计审查 (2026-06-10)
|
||||
|
||||
- Issue: #20
|
||||
- 审查类型: 程序设计(质量门 2)
|
||||
- 产出文件: `docs/technical/收集系统-技术方案.md`
|
||||
- 结果: **通过**
|
||||
|
||||
### 审查要点
|
||||
- 技术方案文档路径实际为中文文件名 `收集系统-技术方案.md`(非 Issue 中标注的 `collection-system-tech.md`)
|
||||
- 执行案文件名也是中文:`收集系统-执行案.md`(非 `collection-system-execution.md`)
|
||||
- 6 个检查维度全部通过:执行案覆盖度、美术资源需求、架构清晰度、数据流、技术风险、工作量与拆分建议
|
||||
- 标签操作:移除了 gate:art-fail(30) 和 status:in-review(14),添加了 review:pass(33)
|
||||
@@ -243,6 +243,34 @@ GameConfig/ # 数值配置表
|
||||
|
||||
---
|
||||
|
||||
## Git 工作流(develop 分支模型)
|
||||
|
||||
项目使用 `develop` 长期开发分支。所有 agent 在 develop 上工作,迭代结束时由 PM 发起 PR 合并回 main。
|
||||
|
||||
### 开始工作
|
||||
```bash
|
||||
bash .claude/scripts/git-workflow.sh ready
|
||||
```
|
||||
|
||||
### 提交文档
|
||||
```bash
|
||||
bash .claude/scripts/git-workflow.sh commit docs <scope> "中文描述"
|
||||
```
|
||||
示例:`bash .claude/scripts/git-workflow.sh commit docs design "交互系统执行案"`
|
||||
|
||||
### 推送
|
||||
```bash
|
||||
bash .claude/scripts/git-workflow.sh push
|
||||
```
|
||||
|
||||
### 完成工作后
|
||||
1. 推送文档到 develop
|
||||
2. 通过 gitea-collab 在对应 Issue 下评论汇报进度
|
||||
3. 更新 Issue 标签为 `status:in-review`
|
||||
4. 启动 `game-reviewer` 子代理
|
||||
|
||||
---
|
||||
|
||||
## 审查交接
|
||||
|
||||
完成工作并发布 Issue 评论后,启动审查流程:
|
||||
|
||||
@@ -221,6 +221,42 @@ skills:
|
||||
|
||||
---
|
||||
|
||||
## Git 工作流(develop 分支模型)
|
||||
|
||||
项目使用 `develop` 长期开发分支。所有 agent 在 develop 上工作,迭代结束时由 PM 发起 PR 合并回 main。
|
||||
|
||||
### 开始开发
|
||||
```bash
|
||||
bash .claude/scripts/git-workflow.sh ready
|
||||
```
|
||||
确认在 develop 分支上且代码最新。
|
||||
|
||||
### 提交代码
|
||||
```bash
|
||||
bash .claude/scripts/git-workflow.sh commit <type> <scope> "中文描述"
|
||||
```
|
||||
- ⚠️ 只提交自己修改的文件,避免提交其他 agent 的 WIP
|
||||
- 蓝图(.uasset)和 C++ 分开提交
|
||||
- commit message subject ≤ 50 字符
|
||||
|
||||
### 推送
|
||||
```bash
|
||||
bash .claude/scripts/git-workflow.sh push
|
||||
```
|
||||
|
||||
### 完成开发后
|
||||
1. 推送代码到 develop
|
||||
2. 通过 gitea-collab 在对应 Issue 下评论汇报进度
|
||||
3. 更新 Issue 标签为 `status:in-review`
|
||||
4. 启动 `game-reviewer` 子代理
|
||||
|
||||
### 开发中发现 main 有更新
|
||||
```bash
|
||||
bash .claude/scripts/git-workflow.sh catchup
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 代码规范
|
||||
|
||||
- C++ 和蓝图遵循 UE5 编码规范
|
||||
|
||||
@@ -103,6 +103,36 @@ skills:
|
||||
|
||||
---
|
||||
|
||||
## Git 工作流(develop 分支模型)
|
||||
|
||||
项目使用 `develop` 长期开发分支,所有 agent 在 develop 上工作。
|
||||
|
||||
### PM 日常
|
||||
```bash
|
||||
# 会话开始时同步
|
||||
bash .claude/scripts/git-workflow.sh ready
|
||||
```
|
||||
|
||||
### 迭代完成 → 发布
|
||||
当所有 Issue 都 review:pass 且用户确认发布时:
|
||||
|
||||
```bash
|
||||
# 创建 develop → main 的 PR
|
||||
bash .claude/scripts/git-workflow.sh release "迭代名称"
|
||||
# 或手动:
|
||||
# node .claude/skills/gitea-pm/gitea.js --role pm pr create --base main --head develop --title "标题" --body "描述"
|
||||
```
|
||||
|
||||
通知用户在 Gitea 审查并合并 PR。
|
||||
|
||||
### 用户合并后同步
|
||||
```bash
|
||||
bash .claude/scripts/git-workflow.sh post-release
|
||||
```
|
||||
自动同步 main 并将 merge commit 同步回 develop。
|
||||
|
||||
---
|
||||
|
||||
## 决策框架
|
||||
|
||||
### 你可以自主决定:
|
||||
|
||||
@@ -6,23 +6,30 @@
|
||||
|
||||
## 分支策略
|
||||
|
||||
**轻量 Feature Branch** — 单人开发,`main` 永远可玩可编译。
|
||||
**develop 长期开发分支模型** — 单人开发 + 多 Agent 协作。
|
||||
|
||||
```
|
||||
main ─────────── 永远可玩可编译,受保护,禁止直接推送
|
||||
│
|
||||
│ PR (Gitea) ← 里程碑/迭代结束时,PM 发起
|
||||
│
|
||||
└── develop ──── 长期分支,所有 agent 在此工作
|
||||
```
|
||||
|
||||
| 分支 | 生命期 | 说明 |
|
||||
|---|---|---|
|
||||
| `main` | 永久 | 稳定版本,受保护 |
|
||||
| `develop` | 永久 | 日常开发分支,所有 agent 共用 |
|
||||
|
||||
**辅助分支(可选,用于实验):**
|
||||
|
||||
| 分支 | 前缀 | 生命期 | 说明 |
|
||||
|---|---|---|---|
|
||||
| 主线 | `main` | 永久 | 稳定版本,不直接在上面开发 |
|
||||
| 功能 | `feature/` | 合并后删 | 新系统、新功能 |
|
||||
| 修复 | `fix/` | 合并后删 | Bug 修复 |
|
||||
| 原型 | `prototype/` | 实验完即删 | 技术验证,随便写 |
|
||||
| 发布 | `release/` | 永久 | 从 main 切出,版本标记 |
|
||||
|
||||
**命名规则:** `<类型>/<小写连字符描述>`
|
||||
```
|
||||
feature/player-movement fix/camera-clipping release/v0.1
|
||||
```
|
||||
|
||||
**流程:**
|
||||
1. 从 `main` 拉分支 → 2. 开发并提交 → 3. 测试通过后合并回 `main` → 4. 删除分支
|
||||
1. 所有开发在 `develop` 上进行 → 2. 迭代完成时创建 PR → 3. 审查通过后合并回 `main`
|
||||
|
||||
---
|
||||
|
||||
@@ -100,3 +107,33 @@ Host gitea micecola.top
|
||||
**内网地址**(家里用):`ssh://sc-gitea@192.168.1.22:2223/starmen1265/ChildHood.git`
|
||||
|
||||
完整规范见 → [GIT-GUIDE.md](GIT-GUIDE.md)
|
||||
|
||||
---
|
||||
|
||||
## 自动化工作流
|
||||
|
||||
`git-workflow.sh` 脚本封装了常用 git 操作:
|
||||
|
||||
```bash
|
||||
# 开始工作:确保在 develop 上且最新
|
||||
bash .claude/scripts/git-workflow.sh ready
|
||||
|
||||
# 提交修改
|
||||
bash .claude/scripts/git-workflow.sh commit <type> <scope> "中文描述"
|
||||
|
||||
# 推送到远程
|
||||
bash .claude/scripts/git-workflow.sh push
|
||||
|
||||
# 查看状态
|
||||
bash .claude/scripts/git-workflow.sh status
|
||||
```
|
||||
|
||||
### PM 发布流程
|
||||
|
||||
```bash
|
||||
# 创建 develop → main PR
|
||||
bash .claude/scripts/git-workflow.sh release "迭代名称"
|
||||
|
||||
# 用户在 Gitea 合并后同步
|
||||
bash .claude/scripts/git-workflow.sh post-release
|
||||
```
|
||||
|
||||
+36
-60
@@ -7,81 +7,57 @@
|
||||
|
||||
## 一、分支策略
|
||||
|
||||
采用**轻量级 Feature Branch 模型**,避免企业级复杂流程,保持 `main` 分支随时可玩。
|
||||
采用 **develop 长期开发分支模型**,适合单人开发 + 多 AI Agent 协作场景。所有 agent 在 `develop` 上工作,迭代结束时通过 PR 合并回 `main`。
|
||||
|
||||
### 1.1 分支总览
|
||||
|
||||
```
|
||||
main ──────────────────────────────────────── 稳定主线
|
||||
│
|
||||
├── feature/player-movement ───→ 合并后删除
|
||||
├── feature/inventory-system ──→ 合并后删除
|
||||
├── fix/camera-clipping ───────→ 合并后删除
|
||||
├── prototype/procedural-gen ──→ 实验完即删
|
||||
└── release/v0.1 ──────────────→ 永久保留
|
||||
main ──────────── 永远可玩可编译,受保护,禁止直接推送
|
||||
│
|
||||
│ PR (Gitea) ← 里程碑/迭代结束时,PM 发起
|
||||
│
|
||||
└── develop ──── 长期分支,所有 agent 的日常工作分支
|
||||
│
|
||||
├── 程序1 提交代码
|
||||
├── 策划 提交文档
|
||||
├── 程序2 提交代码
|
||||
└── 迭代就绪 → PR develop→main
|
||||
```
|
||||
|
||||
### 1.2 分支类型
|
||||
|
||||
| 分支 | 前缀 | 用途 | 合并目标 | 生命周期 |
|
||||
|---|---|---|---|---|
|
||||
| 主线 | `main` | 稳定可玩版本,每次提交都能编译运行 | — | 永久 |
|
||||
| 功能 | `feature/` | 新系统、新功能开发 | `main` | 完成后删除 |
|
||||
| 修复 | `fix/` | Bug 修复 | `main` | 完成后删除 |
|
||||
| 原型 | `prototype/` | 技术验证、玩法实验 | 合并或丢弃 | 实验完即删 |
|
||||
| 发布 | `release/` | 版本发布标记,只从 `main` 切出 | — | 永久保留 |
|
||||
| 分支 | 用途 | 生命周期 |
|
||||
|---|---|---|
|
||||
| `main` | 稳定可玩版本,受保护 | 永久 |
|
||||
| `develop` | 日常开发,所有 agent 共用 | 永久 |
|
||||
| `prototype/` | 技术验证、玩法实验 | 实验完即删 |
|
||||
| `release/` | 版本发布标记,只从 main 切出 | 永久保留 |
|
||||
|
||||
### 1.3 命名规范
|
||||
|
||||
格式:`<类型>/<简短描述>`,全小写,用连字符分隔单词。
|
||||
### 1.3 工作流程
|
||||
|
||||
```
|
||||
# ✅ 好的命名
|
||||
feature/player-movement
|
||||
feature/inventory-system
|
||||
feature/dialogue-tree
|
||||
fix/camera-clipping-through-walls
|
||||
fix/enemy-ai-stuck-on-navmesh
|
||||
prototype/procedural-dungeon
|
||||
release/v0.1
|
||||
1. 开始工作(agent 自动执行)
|
||||
bash .claude/scripts/git-workflow.sh ready
|
||||
|
||||
# ❌ 不好的命名
|
||||
my-new-feature
|
||||
fix-bug
|
||||
test
|
||||
feature/AddPlayerMovement
|
||||
2. 开发并提交
|
||||
bash .claude/scripts/git-workflow.sh commit <type> <scope> "描述"
|
||||
|
||||
3. 推送到远程
|
||||
bash .claude/scripts/git-workflow.sh push
|
||||
|
||||
4. 迭代完成,PM 创建 PR
|
||||
bash .claude/scripts/git-workflow.sh release "迭代名称"
|
||||
|
||||
5. 用户在 Gitea 合并后同步
|
||||
bash .claude/scripts/git-workflow.sh post-release
|
||||
```
|
||||
|
||||
### 1.4 工作流程
|
||||
### 1.4 核心原则
|
||||
|
||||
```
|
||||
1. 开始新功能
|
||||
git checkout main
|
||||
git pull
|
||||
git checkout -b feature/xxx
|
||||
|
||||
2. 开发过程中(随时提交)
|
||||
git add .
|
||||
git commit -m "wip(xxx): 进度描述"
|
||||
|
||||
3. 功能完成,测试通过
|
||||
git checkout main
|
||||
git merge feature/xxx
|
||||
git branch -d feature/xxx # 删除已合并分支
|
||||
|
||||
4. 到达里程碑
|
||||
git checkout main
|
||||
git tag -a v0.1.0 -m "第一个可玩原型"
|
||||
git checkout -b release/v0.1
|
||||
git push origin release/v0.1
|
||||
```
|
||||
|
||||
### 1.5 核心原则
|
||||
|
||||
- **`main` 永远可玩**:坏了就留在 feature 分支继续改,不要合并进 main
|
||||
- **功能分支粒度**:一个分支做一件事,不要在一个分支里同时做多个系统
|
||||
- **原型不怕乱**:`prototype/` 分支随便写,验证完再决定合并还是丢弃
|
||||
- **定期清理**:已合并的 feature/fix 分支及时删除,避免分支堆积
|
||||
- **`main` 永远可玩**:通过 develop → main PR 合并,不直接推送
|
||||
- **develop 是工作台**:所有 agent 在 develop 上并行工作
|
||||
- **不同文件不冲突**:各 agent 修改不同文件,可真正并行
|
||||
- **同一文件需协调**:两个 agent 修改同一文件时需顺序执行
|
||||
|
||||
---
|
||||
|
||||
|
||||
@@ -2,6 +2,8 @@
|
||||
|
||||
> 本模板供策划产出关卡执行案时使用。关卡执行案是场景设计案的"空间精度版本"——将氛围描述转化为带有坐标、尺寸和资产建议的结构化搭建指南,供程序在 UE5 编辑器中搭建白模。
|
||||
>
|
||||
> **注意**:交互物和收集品的放置**不在本模板范围内**,由交互系统/收集系统后续在白盒关卡上叠加。
|
||||
>
|
||||
> 文件命名:`关卡-v<XX>-<名称>-执行案.md`(如 `关卡-v01-城郊街区-执行案.md`)
|
||||
> 存放位置:`docs/design/<阶段>/`(与其他执行案同目录)
|
||||
|
||||
@@ -131,30 +133,18 @@
|
||||
| Zx-P02 | | | | | |
|
||||
| ... | | | | | |
|
||||
|
||||
#### 3.x.4 可交互物体标记
|
||||
#### 3.x.4 组合资产标记
|
||||
|
||||
<!-- 引用交互系统执行案中的交互物,此处只标注空间位置 -->
|
||||
<!-- 需要多个 Primitives 拼搭的物件(无直接 BSP 匹配)。如无此类物件可删除本节。 -->
|
||||
|
||||
| 交互编号 | 物件名称 | 交互类型 | 相对原点偏移 (ΔX,ΔY,ΔZ) | 触发半径 (cm) | 引用 |
|
||||
|---------|---------|---------|----------------------|-------------|------|
|
||||
| Zx-I01 | <!-- 如 旧冰箱 --> | <!-- 如 观察 --> | (200,400,10) | <!-- 如 150 --> | 交互系统-执行案 #n |
|
||||
| Zx-I02 | | | | | |
|
||||
| ... | | | | | |
|
||||
|
||||
> 交互类型参照交互系统执行案中的分类(观察/拾取/操作/对话等)。
|
||||
> "引用"列填写交互系统执行案中对应交互物的编号,确保跨文档一致。
|
||||
|
||||
#### 3.x.5 收集品标记
|
||||
|
||||
<!-- 引用收集系统执行案中的收集品,此处只标注空间位置 -->
|
||||
|
||||
| 收集编号 | 物品名称 | 稀有度 | 相对原点偏移 (ΔX,ΔY,ΔZ) | 引用 |
|
||||
|---------|---------|--------|----------------------|------|
|
||||
| Zx-C01 | <!-- 如 彩色弹珠 --> | <!-- 如 普通/稀有 --> | (500,200,0) | 收集系统-执行案 #n |
|
||||
| 编号 | 物件名称 | 期望尺寸 (约, cm) | 推荐拼搭方案 | 说明 |
|
||||
|------|---------|-----------------|-------------|------|
|
||||
| Zx-C01 | <!-- 如 旧收音机 --> | <!-- 如 20x15x12 --> | <!-- 如 Cube(0.2,0.15,0.12) + Cylinder天线 --> | <!-- 如 放在柜台上 --> |
|
||||
| Zx-C02 | | | | |
|
||||
| ... | | | | | |
|
||||
|
||||
> 稀有度影响拾取物的视觉效果标识(普通=白色光,稀有=金色光),具体表现由收集系统技术方案定义。
|
||||
> 组合资产将在搭建指南生成阶段展开为多个 Primitive Actor,并在组合资产清单中记录拼搭方案。
|
||||
> 用户确认后的组合资产方案将回馈到 asset-catalog 模板库,供后续关卡直接引用。
|
||||
|
||||
---
|
||||
|
||||
@@ -183,14 +173,6 @@
|
||||
| G-E02 | | | | | |
|
||||
| ... | | | | | |
|
||||
|
||||
### 4.3 收集品位置汇总
|
||||
|
||||
| # | 物品名称 | 所在区域 | 绝对坐标 (X,Y,Z) | 稀有度 | 引用 |
|
||||
|---|---------|---------|-----------------|--------|------|
|
||||
| 1 | | | | | 收集系统-执行案 #n |
|
||||
| 2 | | | | | |
|
||||
| ... | | | | | |
|
||||
|
||||
---
|
||||
|
||||
## 五、场景边界与遮挡
|
||||
@@ -225,10 +207,10 @@
|
||||
### 策划填写要点
|
||||
|
||||
1. **先确定区域坐标布局**(第二章),确保所有区域在总尺寸内不重叠、流线合理
|
||||
2. **逐区域填写**(第三章),按"结构体 → 布景 → 交互物 → 收集品"的顺序
|
||||
2. **逐区域填写**(第三章),按"结构体 → 布景 → 组合资产"的顺序
|
||||
3. **BSP 资产建议是方向性指引**:写资产类别名和组合方式即可(如 "Wall_400x300 × 2"),不需要写文件路径
|
||||
4. **尺寸以 cm 为单位**,对应 UE5 的 1 uu = 1 cm
|
||||
5. **交叉引用**:交互物和收集品必须引用对应系统执行案中的编号,保持跨文档一致
|
||||
5. **组合资产**:无法用单个 BSP 资产匹配的物件,在 3.x.4 中记录拼搭方案
|
||||
|
||||
### 不要填写的内容
|
||||
|
||||
@@ -237,6 +219,7 @@
|
||||
- ❌ Blueprint 类名
|
||||
- ❌ 精确的硬编码参数值(标注"建议值,可调"并附范围)
|
||||
- ❌ 代码或脚本
|
||||
- ❌ 交互物和收集品位置(由系统后续叠加)
|
||||
|
||||
### 与场景设计案的关系
|
||||
|
||||
|
||||
@@ -0,0 +1,326 @@
|
||||
#!/usr/bin/env bash
|
||||
# ═══════════════════════════════════════════════════════════════
|
||||
# git-workflow.sh — ChildHood 项目 Git 工作流自动化
|
||||
#
|
||||
# 基于 develop 长期开发分支模型。
|
||||
# 所有 agent 在 develop 上工作,迭代结束时通过 PR 合并回 main。
|
||||
#
|
||||
# 用法: bash .claude/scripts/git-workflow.sh <command> [args...]
|
||||
#
|
||||
# 命令:
|
||||
# ready 确保在 develop 上且最新
|
||||
# commit <type> <scope> "<msg>" 格式化提交
|
||||
# push 推送 develop 到远程
|
||||
# submit <issue-number> 一键 commit + push(从 Issue 拉取信息)
|
||||
# release [milestone-name] 创建 develop→main 的 PR
|
||||
# post-release 合并后同步 main 和 develop
|
||||
# catchup 将 develop 合并最新 main 的内容
|
||||
# status 显示当前分支和状态
|
||||
# ═══════════════════════════════════════════════════════════════
|
||||
|
||||
set -euo pipefail
|
||||
|
||||
# ─── 配置 ───
|
||||
DEVELOP_BRANCH="develop"
|
||||
MAIN_BRANCH="main"
|
||||
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
|
||||
PROJECT_ROOT="$(cd "$SCRIPT_DIR/../.." && pwd)"
|
||||
GITEA_PM_CLI="node $PROJECT_ROOT/.claude/skills/gitea-pm/gitea.js"
|
||||
GITEA_COLLAB_CLI="node $PROJECT_ROOT/.claude/skills/gitea-collab/gitea.js"
|
||||
|
||||
# ─── 颜色 ───
|
||||
RED='\033[0;31m'
|
||||
GREEN='\033[0;32m'
|
||||
YELLOW='\033[1;33m'
|
||||
BLUE='\033[0;34m'
|
||||
NC='\033[0m' # No Color
|
||||
|
||||
info() { echo -e "${BLUE}ℹ️ $*${NC}"; }
|
||||
ok() { echo -e "${GREEN}✅ $*${NC}"; }
|
||||
warn() { echo -e "${YELLOW}⚠️ $*${NC}"; }
|
||||
fail() { echo -e "${RED}❌ $*${NC}"; exit 1; }
|
||||
|
||||
# ─── 当前分支 ───
|
||||
current_branch() { git rev-parse --abbrev-ref HEAD; }
|
||||
|
||||
# ─── 检查是否有未提交的修改 ───
|
||||
has_changes() { [ -n "$(git status --porcelain)" ]; }
|
||||
|
||||
# ─── 检测 UE5 二进制文件 ───
|
||||
has_ue5_binaries() {
|
||||
git diff --cached --name-only 2>/dev/null | grep -qE '\.(uasset|umap)$'
|
||||
}
|
||||
|
||||
# ═══════════════════════════════════════════════════════════════
|
||||
# 命令实现
|
||||
# ═══════════════════════════════════════════════════════════════
|
||||
|
||||
cmd_ready() {
|
||||
info "准备工作环境..."
|
||||
|
||||
local branch
|
||||
branch=$(current_branch)
|
||||
|
||||
# 如果不在 develop 上,切换过去
|
||||
if [ "$branch" != "$DEVELOP_BRANCH" ]; then
|
||||
if has_changes; then
|
||||
warn "有未提交的修改,暂存中..."
|
||||
git stash push --include-untracked -m "auto-stash-$(date +%s)"
|
||||
fi
|
||||
git checkout "$DEVELOP_BRANCH" 2>/dev/null || {
|
||||
# 本地没有 develop 分支,从 main 创建
|
||||
info "本地没有 $DEVELOP_BRANCH 分支,从 $MAIN_BRANCH 创建..."
|
||||
git checkout "$MAIN_BRANCH"
|
||||
git pull origin "$MAIN_BRANCH"
|
||||
git checkout -b "$DEVELOP_BRANCH"
|
||||
}
|
||||
fi
|
||||
|
||||
# 拉取最新 develop
|
||||
if git remote get-url origin &>/dev/null; then
|
||||
info "拉取远程 $DEVELOP_BRANCH..."
|
||||
git pull origin "$DEVELOP_BRANCH" 2>/dev/null || {
|
||||
# 远程没有 develop,首次推送
|
||||
warn "远程没有 $DEVELOP_BRANCH 分支,将首次推送"
|
||||
}
|
||||
fi
|
||||
|
||||
local commit_hash
|
||||
commit_hash=$(git rev-parse --short HEAD)
|
||||
ok "已在 $DEVELOP_BRANCH 分支上 (${commit_hash})"
|
||||
}
|
||||
|
||||
cmd_commit() {
|
||||
local type="${1:-}"
|
||||
local scope="${2:-}"
|
||||
local message="${3:-}"
|
||||
|
||||
if [ -z "$type" ] || [ -z "$scope" ] || [ -z "$message" ]; then
|
||||
fail "用法: git-workflow.sh commit <type> <scope> \"<message>\"\n 示例: git-workflow.sh commit feat player \"实现角色跳跃\""
|
||||
fi
|
||||
|
||||
# 校验分支
|
||||
if [ "$(current_branch)" != "$DEVELOP_BRANCH" ]; then
|
||||
warn "当前不在 $DEVELOP_BRANCH 分支上 (当前: $(current_branch))"
|
||||
read -rp "继续提交? [y/N] " confirm
|
||||
[[ "$confirm" != [yY] ]] && { info "已取消"; return; }
|
||||
fi
|
||||
|
||||
# 暂存所有修改
|
||||
if ! has_changes; then
|
||||
warn "没有检测到修改"
|
||||
return
|
||||
fi
|
||||
|
||||
git add -A
|
||||
|
||||
# UE5 二进制文件检测
|
||||
if has_ue5_binaries; then
|
||||
warn "检测到 .uasset/.umap 文件,请确保 commit message 清楚描述了变更内容"
|
||||
fi
|
||||
|
||||
# 格式化 commit message
|
||||
local commit_msg="${type}(${scope}): ${message}"
|
||||
|
||||
# subject ≤ 50 字符检查(仅消息部分)
|
||||
local msg_len=${#commit_msg}
|
||||
if [ "$msg_len" -gt 72 ]; then
|
||||
warn "提交消息较长 ($msg_len 字符),建议精简"
|
||||
fi
|
||||
|
||||
git commit -m "$commit_msg"
|
||||
ok "已提交: $commit_msg"
|
||||
}
|
||||
|
||||
cmd_push() {
|
||||
local branch
|
||||
branch=$(current_branch)
|
||||
|
||||
info "推送 $branch 到远程..."
|
||||
|
||||
# 设置上游分支(首次)
|
||||
if ! git rev-parse --abbrev-ref "@{upstream}" &>/dev/null; then
|
||||
git push -u origin "$branch"
|
||||
else
|
||||
git push origin "$branch"
|
||||
fi
|
||||
|
||||
ok "已推送 $branch 到远程"
|
||||
}
|
||||
|
||||
cmd_submit() {
|
||||
local issue_number="${1:-}"
|
||||
if [ -z "$issue_number" ]; then
|
||||
fail "用法: git-workflow.sh submit <issue-number>"
|
||||
fi
|
||||
|
||||
info "提交工作 (Issue #$issue_number)..."
|
||||
|
||||
# 从 Issue 拉取标题作为 commit 参考
|
||||
local issue_title=""
|
||||
issue_title=$($GITEA_COLLAB_CLI --role dev issue get "$issue_number" --json 2>/dev/null | grep -o '"title":"[^"]*"' | head -1 | sed 's/"title":"//;s/"//') || true
|
||||
|
||||
# 提交
|
||||
if has_changes; then
|
||||
if [ -n "$issue_title" ]; then
|
||||
info "Issue 标题: $issue_title"
|
||||
fi
|
||||
warn "有未提交的修改,请先运行: git-workflow.sh commit <type> <scope> \"<message>\""
|
||||
return
|
||||
fi
|
||||
|
||||
# 推送
|
||||
cmd_push
|
||||
|
||||
ok "工作已提交到 $DEVELOP_BRANCH (关联 Issue #$issue_number)"
|
||||
}
|
||||
|
||||
cmd_release() {
|
||||
local milestone_name="${1:-}"
|
||||
|
||||
info "准备发布 PR ($DEVELOP_BRANCH → $MAIN_BRANCH)..."
|
||||
|
||||
# 确保在 develop 上
|
||||
if [ "$(current_branch)" != "$DEVELOP_BRANCH" ]; then
|
||||
fail "请先切换到 $DEVELOP_BRANCH 分支"
|
||||
fi
|
||||
|
||||
# 确保本地最新
|
||||
git pull origin "$DEVELOP_BRANCH"
|
||||
|
||||
# 获取里程碑名称
|
||||
if [ -z "$milestone_name" ]; then
|
||||
# 尝试从当前里程碑获取
|
||||
milestone_name=$($GITEA_PM_CLI --role pm milestone list --state open --json 2>/dev/null | grep -o '"title":"[^"]*"' | head -1 | sed 's/"title":"//;s/"//') || "迭代发布"
|
||||
if [ -z "$milestone_name" ]; then
|
||||
milestone_name="迭代发布"
|
||||
fi
|
||||
fi
|
||||
|
||||
local pr_title="Merge develop → main: ${milestone_name}"
|
||||
|
||||
# 构造 PR body(汇总已关闭的 Issue)
|
||||
local pr_body="## 发布合并\n\n将 \`${DEVELOP_BRANCH}\` 分支的成果合并到 \`${MAIN_BRANCH}\`。\n\n### 里程碑\n${milestone_name}"
|
||||
|
||||
# 创建 PR
|
||||
info "创建 PR: $pr_title"
|
||||
local pr_result
|
||||
pr_result=$($GITEA_PM_CLI --role pm pr create \
|
||||
--base "$MAIN_BRANCH" \
|
||||
--head "$DEVELOP_BRANCH" \
|
||||
--title "$pr_title" \
|
||||
--body "$(echo -e "$pr_body")" \
|
||||
--json 2>&1) || {
|
||||
fail "创建 PR 失败: $pr_result"
|
||||
}
|
||||
|
||||
local pr_number
|
||||
pr_number=$(echo "$pr_result" | grep -o '"number":[0-9]*' | head -1 | sed 's/"number"://') || true
|
||||
|
||||
if [ -n "$pr_number" ]; then
|
||||
ok "PR #$pr_number 已创建: $pr_title"
|
||||
info "请在 Gitea 审查并合并: http://micecola.top:8418/starmen1265/ChildHood/pulls/$pr_number"
|
||||
else
|
||||
ok "PR 已创建,请查看 Gitea"
|
||||
fi
|
||||
}
|
||||
|
||||
cmd_post_release() {
|
||||
info "合并后同步..."
|
||||
|
||||
# 同步 main
|
||||
info "同步 $MAIN_BRANCH..."
|
||||
git checkout "$MAIN_BRANCH"
|
||||
git pull origin "$MAIN_BRANCH"
|
||||
ok "$MAIN_BRANCH 已更新"
|
||||
|
||||
# 切回 develop 并合并 main(保持 develop 包含 merge commit)
|
||||
info "同步 $DEVELOP_BRANCH..."
|
||||
git checkout "$DEVELOP_BRANCH"
|
||||
git merge "$MAIN_BRANCH" --no-edit
|
||||
git push origin "$DEVELOP_BRANCH"
|
||||
ok "$DEVELOP_BRANCH 已同步(包含 $MAIN_BRANCH 的 merge commit)"
|
||||
|
||||
local commit_hash
|
||||
commit_hash=$(git rev-parse --short HEAD)
|
||||
ok "完成,当前在 $DEVELOP_BRANCH (${commit_hash})"
|
||||
}
|
||||
|
||||
cmd_catchup() {
|
||||
info "将 develop 跟上最新的 $MAIN_BRANCH..."
|
||||
|
||||
if [ "$(current_branch)" != "$DEVELOP_BRANCH" ]; then
|
||||
fail "请先切换到 $DEVELOP_BRANCH 分支"
|
||||
fi
|
||||
|
||||
git fetch origin
|
||||
git merge "origin/$MAIN_BRANCH" --no-edit
|
||||
ok "$DEVELOP_BRANCH 已合并最新 $MAIN_BRANCH"
|
||||
}
|
||||
|
||||
cmd_status() {
|
||||
local branch
|
||||
branch=$(current_branch)
|
||||
local commit_hash
|
||||
commit_hash=$(git rev-parse --short HEAD)
|
||||
local changed
|
||||
changed=$(git status --porcelain | wc -l | tr -d ' ')
|
||||
|
||||
echo -e "${BLUE}═══ Git 工作流状态 ═══${NC}"
|
||||
echo " 当前分支: ${branch} (${commit_hash})"
|
||||
|
||||
if [ "$branch" = "$DEVELOP_BRANCH" ]; then
|
||||
echo -e " ${GREEN}✓ 在 develop 开发分支上${NC}"
|
||||
elif [ "$branch" = "$MAIN_BRANCH" ]; then
|
||||
echo -e " ${YELLOW}⚠ 在 main 分支上,请切换到 develop 开始工作${NC}"
|
||||
else
|
||||
echo -e " ${YELLOW}⚠ 在非标准分支上: $branch${NC}"
|
||||
fi
|
||||
|
||||
echo " 未提交修改: ${changed} 个文件"
|
||||
|
||||
if [ "$changed" -gt 0 ]; then
|
||||
echo ""
|
||||
git status --short
|
||||
fi
|
||||
|
||||
# 远程同步状态
|
||||
if git rev-parse "@{upstream}" &>/dev/null; then
|
||||
local ahead behind
|
||||
ahead=$(git rev-list --count "@{upstream}..HEAD" 2>/dev/null || echo "0")
|
||||
behind=$(git rev-list --count "HEAD..@{upstream}" 2>/dev/null || echo "0")
|
||||
echo " 远程状态: ahead ${ahead}, behind ${behind}"
|
||||
fi
|
||||
}
|
||||
|
||||
# ═══════════════════════════════════════════════════════════════
|
||||
# 入口
|
||||
# ═══════════════════════════════════════════════════════════════
|
||||
|
||||
case "${1:-}" in
|
||||
ready) cmd_ready ;;
|
||||
commit) shift; cmd_commit "$@" ;;
|
||||
push) cmd_push ;;
|
||||
submit) shift; cmd_submit "$@" ;;
|
||||
release) shift; cmd_release "$@" ;;
|
||||
post-release) cmd_post_release ;;
|
||||
catchup) cmd_catchup ;;
|
||||
status) cmd_status ;;
|
||||
*)
|
||||
echo "git-workflow.sh — ChildHood 项目 Git 工作流自动化"
|
||||
echo ""
|
||||
echo "用法: bash .claude/scripts/git-workflow.sh <command> [args...]"
|
||||
echo ""
|
||||
echo "命令:"
|
||||
echo " ready 确保在 develop 上且最新"
|
||||
echo " commit <type> <scope> \"<msg>\" 格式化提交"
|
||||
echo " push 推送 develop 到远程"
|
||||
echo " submit <issue-number> 推送并关联 Issue"
|
||||
echo " release [milestone-name] 创建 develop→main PR"
|
||||
echo " post-release 合并后同步 main 和 develop"
|
||||
echo " catchup 将 develop 合并最新 main"
|
||||
echo " status 显示当前分支和状态"
|
||||
echo ""
|
||||
echo "工作流模型: develop 长期开发分支 → 迭代完成时 PR 合并回 main"
|
||||
;;
|
||||
esac
|
||||
@@ -148,7 +148,43 @@ node .claude/skills/gitea-collab/gitea.js --role reviewer issue labels <number>
|
||||
|
||||
---
|
||||
|
||||
## 7. 汇报模板
|
||||
## 7. PR 查询
|
||||
|
||||
非 PM 角色可以查看 PR 状态(创建和合并由 PM 负责):
|
||||
|
||||
```bash
|
||||
# 列出 PR
|
||||
node .claude/skills/gitea-collab/gitea.js --role <角色名> pr list
|
||||
|
||||
# 查看 PR 详情
|
||||
node .claude/skills/gitea-collab/gitea.js --role <角色名> pr get <number>
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 8. Git 工作流
|
||||
|
||||
所有 agent 在 `develop` 长期开发分支上工作:
|
||||
|
||||
```bash
|
||||
# 开始工作时:确保在 develop 上
|
||||
bash .claude/scripts/git-workflow.sh ready
|
||||
|
||||
# 提交代码/文档
|
||||
bash .claude/scripts/git-workflow.sh commit <type> <scope> "中文描述"
|
||||
|
||||
# 推送到远程
|
||||
bash .claude/scripts/git-workflow.sh push
|
||||
|
||||
# 查看当前状态
|
||||
bash .claude/scripts/git-workflow.sh status
|
||||
```
|
||||
|
||||
详见 `.claude/refs/GIT-GUIDE-LITE.md` 的"自动化工作流"章节。
|
||||
|
||||
---
|
||||
|
||||
## 9. 汇报模板
|
||||
|
||||
### 策划汇报
|
||||
|
||||
|
||||
@@ -222,6 +222,27 @@ class GiteaAPI {
|
||||
});
|
||||
}
|
||||
|
||||
// ====== Pull Requests ======
|
||||
|
||||
listPullRequests(params = {}) {
|
||||
return this.request('GET', '/pulls', null, { state: 'open', limit: 50, ...params });
|
||||
}
|
||||
|
||||
getPullRequest(number) {
|
||||
return this.request('GET', `/pulls/${number}`);
|
||||
}
|
||||
|
||||
createPullRequest(data) {
|
||||
return this.request('POST', '/pulls', data);
|
||||
}
|
||||
|
||||
mergePullRequest(number, data = {}) {
|
||||
return this.request('POST', `/pulls/${number}/merge`, {
|
||||
Do: data.style || 'merge',
|
||||
...data,
|
||||
});
|
||||
}
|
||||
|
||||
// ====== 辅助方法 ======
|
||||
|
||||
/** 通过名称查找标签,返回 ID(不存在则返回 null) */
|
||||
|
||||
@@ -520,6 +520,84 @@ cmd.pipeline = {
|
||||
},
|
||||
};
|
||||
|
||||
// ──────── pr ────────
|
||||
|
||||
cmd.pr = {
|
||||
async list(api, opts) {
|
||||
const params = {};
|
||||
if (opts.options.state) params.state = opts.options.state;
|
||||
if (opts.options.base) params.base = opts.options.base;
|
||||
if (opts.options.head) params.head = opts.options.head;
|
||||
|
||||
const prs = await api.listPullRequests(params);
|
||||
out(prs);
|
||||
if (!opts.options.json) {
|
||||
outText(`\n🔀 Pull Requests (${prs.length || 0})\n`);
|
||||
if (!prs || !prs.length) { outText(' (无)'); return; }
|
||||
table(
|
||||
['#', '标题', '状态', 'Base', 'Head', '合并'],
|
||||
prs.map(p => [
|
||||
p.number,
|
||||
truncate(p.title, 35),
|
||||
p.state,
|
||||
p.base?.ref || '—',
|
||||
p.head?.ref || '—',
|
||||
p.merged ? '✅' : '—',
|
||||
])
|
||||
);
|
||||
}
|
||||
},
|
||||
|
||||
async get(api, opts) {
|
||||
const num = opts.rest[0];
|
||||
if (!num) { fail('用法: pr get <number>'); return; }
|
||||
const pr = await api.getPullRequest(num);
|
||||
out(pr);
|
||||
if (!opts.options.json) {
|
||||
outText(`\n🔀 PR #${pr.number}: ${pr.title}`);
|
||||
outText(` 状态: ${pr.state}`);
|
||||
outText(` ${pr.base?.ref} ← ${pr.head?.ref}`);
|
||||
outText(` 合并: ${pr.merged ? '✅ 已合并' : '❌ 未合并'}`);
|
||||
if (pr.body) {
|
||||
outText(`\n--- Body ---\n${pr.body.slice(0, 500)}${pr.body.length > 500 ? '…' : ''}`);
|
||||
}
|
||||
}
|
||||
},
|
||||
|
||||
async create(api, opts) {
|
||||
const base = opts.options.base || 'main';
|
||||
const head = opts.options.head;
|
||||
const title = opts.options.title;
|
||||
const body = opts.options.body || '';
|
||||
|
||||
if (!head || !title) {
|
||||
fail('用法: pr create --head <分支> --title "标题" [--base main] [--body "描述"]');
|
||||
return;
|
||||
}
|
||||
|
||||
const pr = await api.createPullRequest({ base, head, title, body });
|
||||
out(pr);
|
||||
if (!opts.options.json) {
|
||||
ok(`PR #${pr.number} 已创建: ${pr.title}`);
|
||||
outText(` ${pr.html_url}`);
|
||||
}
|
||||
},
|
||||
|
||||
async merge(api, opts) {
|
||||
const num = opts.rest[0];
|
||||
if (!num) { fail('用法: pr merge <number> [--style merge|squash|rebase]'); return; }
|
||||
const style = opts.options.style || 'merge';
|
||||
|
||||
const pr = await api.getPullRequest(num);
|
||||
if (pr.merged) { fail(`PR #${num} 已合并,无需重复操作`); return; }
|
||||
if (pr.mergeable === false) { fail(`PR #${num} 存在冲突,无法自动合并。请先解决冲突。`); return; }
|
||||
|
||||
const result = await api.mergePullRequest(num, { style });
|
||||
out(result);
|
||||
if (!opts.options.json) ok(`PR #${num} 已合并 (${style})`);
|
||||
},
|
||||
};
|
||||
|
||||
// ──────── test ────────
|
||||
|
||||
cmd.test = {
|
||||
@@ -682,6 +760,11 @@ Gitea CLI — 项目管理工具
|
||||
pipeline status 查看当前流水线进度
|
||||
pipeline update <#> 更新 Pipeline 字段 --field <阶段|当前迭代> --value <值>
|
||||
|
||||
pr list 列出 Pull Requests [--state open|closed|all] [--base <分支>] [--head <分支>]
|
||||
pr get <#> 查看 PR 详情
|
||||
pr create 创建 PR --head <分支> --title "标题" [--base main] [--body "描述"]
|
||||
pr merge <#> 合并 PR [--style merge|squash|rebase]
|
||||
|
||||
test 验证所有 API 接口
|
||||
|
||||
角色自动映射:
|
||||
|
||||
@@ -218,7 +218,36 @@ Pipeline Tracker 是一个 Meta Issue,仅记录**无法从 Issue/Milestone 推
|
||||
|
||||
---
|
||||
|
||||
## 8. 标签体系
|
||||
## 8. PR 操作(发布合并)
|
||||
|
||||
迭代完成时,PM 负责创建 develop → main 的 PR:
|
||||
|
||||
```bash
|
||||
# 列出当前 PR
|
||||
node .claude/skills/gitea-pm/gitea.js --role pm pr list
|
||||
|
||||
# 创建发布 PR
|
||||
bash .claude/scripts/git-workflow.sh release "迭代名称"
|
||||
|
||||
# 或手动创建
|
||||
node .claude/skills/gitea-pm/gitea.js --role pm pr create \
|
||||
--base main --head develop \
|
||||
--title "Merge develop → main: 迭代名称" \
|
||||
--body "发布描述"
|
||||
|
||||
# 查看 PR 详情
|
||||
node .claude/skills/gitea-pm/gitea.js --role pm pr get <number>
|
||||
|
||||
# 合并 PR(用户审查确认后)
|
||||
node .claude/skills/gitea-pm/gitea.js --role pm pr merge <number> --style merge
|
||||
|
||||
# 合并后同步
|
||||
bash .claude/scripts/git-workflow.sh post-release
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 9. 标签体系
|
||||
|
||||
从 `gitea-config.json` 的 `labels` 字段定义。`label init` 命令从此配置创建标签。
|
||||
|
||||
|
||||
@@ -222,6 +222,27 @@ class GiteaAPI {
|
||||
});
|
||||
}
|
||||
|
||||
// ====== Pull Requests ======
|
||||
|
||||
listPullRequests(params = {}) {
|
||||
return this.request('GET', '/pulls', null, { state: 'open', limit: 50, ...params });
|
||||
}
|
||||
|
||||
getPullRequest(number) {
|
||||
return this.request('GET', `/pulls/${number}`);
|
||||
}
|
||||
|
||||
createPullRequest(data) {
|
||||
return this.request('POST', '/pulls', data);
|
||||
}
|
||||
|
||||
mergePullRequest(number, data = {}) {
|
||||
return this.request('POST', `/pulls/${number}/merge`, {
|
||||
Do: data.style || 'merge', // merge | squash | rebase
|
||||
...data,
|
||||
});
|
||||
}
|
||||
|
||||
// ====== 辅助方法 ======
|
||||
|
||||
/** 通过名称查找标签,返回 ID(不存在则返回 null) */
|
||||
|
||||
@@ -520,6 +520,87 @@ cmd.pipeline = {
|
||||
},
|
||||
};
|
||||
|
||||
// ──────── pr ────────
|
||||
|
||||
cmd.pr = {
|
||||
async list(api, opts) {
|
||||
const params = {};
|
||||
if (opts.options.state) params.state = opts.options.state;
|
||||
if (opts.options.base) params.base = opts.options.base;
|
||||
if (opts.options.head) params.head = opts.options.head;
|
||||
|
||||
const prs = await api.listPullRequests(params);
|
||||
out(prs);
|
||||
if (!opts.options.json) {
|
||||
outText(`\n🔀 Pull Requests (${prs.length || 0})\n`);
|
||||
if (!prs || !prs.length) { outText(' (无)'); return; }
|
||||
table(
|
||||
['#', '标题', '状态', 'Base', 'Head', '合并'],
|
||||
prs.map(p => [
|
||||
p.number,
|
||||
truncate(p.title, 35),
|
||||
p.state,
|
||||
p.base?.ref || '—',
|
||||
p.head?.ref || '—',
|
||||
p.merged ? '✅' : '—',
|
||||
])
|
||||
);
|
||||
}
|
||||
},
|
||||
|
||||
async get(api, opts) {
|
||||
const num = opts.rest[0];
|
||||
if (!num) { fail('用法: pr get <number>'); return; }
|
||||
const pr = await api.getPullRequest(num);
|
||||
out(pr);
|
||||
if (!opts.options.json) {
|
||||
outText(`\n🔀 PR #${pr.number}: ${pr.title}`);
|
||||
outText(` 状态: ${pr.state}`);
|
||||
outText(` ${pr.base?.ref} ← ${pr.head?.ref}`);
|
||||
outText(` 合并: ${pr.merged ? '✅ 已合并' : '❌ 未合并'}`);
|
||||
outText(` 创建: ${pr.created_at?.slice(0, 10)}`);
|
||||
outText(` 更新: ${pr.updated_at?.slice(0, 10)}`);
|
||||
if (pr.body) {
|
||||
outText(`\n--- Body ---\n${pr.body.slice(0, 500)}${pr.body.length > 500 ? '…' : ''}`);
|
||||
}
|
||||
}
|
||||
},
|
||||
|
||||
async create(api, opts) {
|
||||
const base = opts.options.base || 'main';
|
||||
const head = opts.options.head;
|
||||
const title = opts.options.title;
|
||||
const body = opts.options.body || '';
|
||||
|
||||
if (!head || !title) {
|
||||
fail('用法: pr create --head <分支> --title "标题" [--base main] [--body "描述"]');
|
||||
return;
|
||||
}
|
||||
|
||||
const pr = await api.createPullRequest({ base, head, title, body });
|
||||
out(pr);
|
||||
if (!opts.options.json) {
|
||||
ok(`PR #${pr.number} 已创建: ${pr.title}`);
|
||||
outText(` ${pr.html_url}`);
|
||||
}
|
||||
},
|
||||
|
||||
async merge(api, opts) {
|
||||
const num = opts.rest[0];
|
||||
if (!num) { fail('用法: pr merge <number> [--style merge|squash|rebase]'); return; }
|
||||
const style = opts.options.style || 'merge';
|
||||
|
||||
// 先检查 PR 状态
|
||||
const pr = await api.getPullRequest(num);
|
||||
if (pr.merged) { fail(`PR #${num} 已合并,无需重复操作`); return; }
|
||||
if (pr.mergeable === false) { fail(`PR #${num} 存在冲突,无法自动合并。请先解决冲突。`); return; }
|
||||
|
||||
const result = await api.mergePullRequest(num, { style });
|
||||
out(result);
|
||||
if (!opts.options.json) ok(`PR #${num} 已合并 (${style})`);
|
||||
},
|
||||
};
|
||||
|
||||
// ──────── test ────────
|
||||
|
||||
cmd.test = {
|
||||
@@ -682,6 +763,11 @@ Gitea CLI — 项目管理工具
|
||||
pipeline status 查看当前流水线进度
|
||||
pipeline update <#> 更新 Pipeline 字段 --field <阶段|当前迭代> --value <值>
|
||||
|
||||
pr list 列出 Pull Requests [--state open|closed|all] [--base <分支>] [--head <分支>]
|
||||
pr get <#> 查看 PR 详情
|
||||
pr create 创建 PR --head <分支> --title "标题" [--base main] [--body "描述"]
|
||||
pr merge <#> 合并 PR [--style merge|squash|rebase]
|
||||
|
||||
test 验证所有 API 接口
|
||||
|
||||
角色自动映射:
|
||||
|
||||
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
@@ -25,6 +25,7 @@ public class ChildHood : ModuleRules
|
||||
|
||||
PublicIncludePaths.AddRange(new string[] {
|
||||
"ChildHood",
|
||||
"ChildHood/Interaction",
|
||||
"ChildHood/Variant_Platforming",
|
||||
"ChildHood/Variant_Platforming/Animation",
|
||||
"ChildHood/Variant_Combat",
|
||||
|
||||
@@ -11,6 +11,7 @@
|
||||
#include "EnhancedInputSubsystems.h"
|
||||
#include "InputActionValue.h"
|
||||
#include "ChildHood.h"
|
||||
#include "Interaction/InteractionManager.h"
|
||||
|
||||
AChildHoodCharacter::AChildHoodCharacter()
|
||||
{
|
||||
@@ -31,8 +32,6 @@ AChildHoodCharacter::AChildHoodCharacter()
|
||||
CMC->BrakingDecelerationWalking = 1500.0f; // 停止减速 0.3s (450/0.3)
|
||||
CMC->BrakingDecelerationFalling = 1500.0f;
|
||||
CMC->MinAnalogWalkSpeed = 20.f;
|
||||
// WalkableFloorAngle 默认 45°,无需修改
|
||||
// v0.1 不跳跃,不设置 JumpZVelocity / AirControl
|
||||
|
||||
// Create a camera boom (pulls in towards the player if there is a collision)
|
||||
CameraBoom = CreateDefaultSubobject<USpringArmComponent>(TEXT("CameraBoom"));
|
||||
@@ -42,19 +41,22 @@ AChildHoodCharacter::AChildHoodCharacter()
|
||||
CameraBoom->bUsePawnControlRotation = true;
|
||||
|
||||
// 摄像机软跟随
|
||||
CameraBoom->bEnableCameraLag = true; // 启用位置延迟跟随
|
||||
CameraBoom->CameraLagSpeed = 6.0f; // 跟随速度(可调 2-8)
|
||||
CameraBoom->bEnableCameraRotationLag = false; // v0.1 不启用旋转延迟
|
||||
CameraBoom->bEnableCameraLag = true;
|
||||
CameraBoom->CameraLagSpeed = 6.0f;
|
||||
CameraBoom->bEnableCameraRotationLag = false;
|
||||
|
||||
// 摄像机碰撞处理
|
||||
CameraBoom->bDoCollisionTest = true; // 启用碰撞检测
|
||||
CameraBoom->ProbeSize = 12.0f; // 碰撞探针半径
|
||||
CameraBoom->ProbeChannel = ECC_Camera; // 使用 Camera 碰撞通道
|
||||
CameraBoom->bDoCollisionTest = true;
|
||||
CameraBoom->ProbeSize = 12.0f;
|
||||
CameraBoom->ProbeChannel = ECC_Camera;
|
||||
|
||||
// Create a follow camera
|
||||
FollowCamera = CreateDefaultSubobject<UCameraComponent>(TEXT("FollowCamera"));
|
||||
FollowCamera->SetupAttachment(CameraBoom, USpringArmComponent::SocketName);
|
||||
FollowCamera->bUsePawnControlRotation = false;
|
||||
|
||||
// 创建交互管理器组件
|
||||
InteractionManager = CreateDefaultSubobject<UInteractionManager>(TEXT("InteractionManager"));
|
||||
}
|
||||
|
||||
void AChildHoodCharacter::SetupPlayerInputComponent(UInputComponent* PlayerInputComponent)
|
||||
@@ -69,7 +71,7 @@ void AChildHoodCharacter::SetupPlayerInputComponent(UInputComponent* PlayerInput
|
||||
EnhancedInputComponent->BindAction(LookAction, ETriggerEvent::Triggered, this, &AChildHoodCharacter::Look);
|
||||
EnhancedInputComponent->BindAction(MouseLookAction, ETriggerEvent::Triggered, this, &AChildHoodCharacter::Look);
|
||||
|
||||
// Interaction IAs — bind to placeholder callbacks; interaction system will hook into these
|
||||
// Interaction — delegates to InteractionManager
|
||||
if (InteractAction)
|
||||
{
|
||||
EnhancedInputComponent->BindAction(InteractAction, ETriggerEvent::Started, this, &AChildHoodCharacter::OnInteract);
|
||||
@@ -109,23 +111,35 @@ void AChildHoodCharacter::Look(const FInputActionValue& Value)
|
||||
|
||||
void AChildHoodCharacter::OnInteract(const FInputActionValue& Value)
|
||||
{
|
||||
// v0.1 placeholder — interaction system will provide implementation
|
||||
// Interaction system hooks in via blueprint or future C++ delegate
|
||||
if (UInteractionManager* IM = GetInteractionManager())
|
||||
{
|
||||
// E 键双重功能:Free 发起交互,Active 结束交互
|
||||
IM->BeginInteract();
|
||||
IM->CancelInteract();
|
||||
}
|
||||
}
|
||||
|
||||
void AChildHoodCharacter::OnCancel(const FInputActionValue& Value)
|
||||
{
|
||||
// v0.1 placeholder — interaction system will provide implementation
|
||||
if (UInteractionManager* IM = GetInteractionManager())
|
||||
{
|
||||
IM->CancelInteract();
|
||||
}
|
||||
}
|
||||
|
||||
void AChildHoodCharacter::OnSwitchInteract(const FInputActionValue& Value)
|
||||
{
|
||||
// v0.1 placeholder — interaction system will provide implementation
|
||||
if (UInteractionManager* IM = GetInteractionManager())
|
||||
{
|
||||
float DirectionValue = Value.Get<float>();
|
||||
int32 Direction = (DirectionValue >= 0.f) ? 1 : -1;
|
||||
IM->SwitchTarget(Direction);
|
||||
}
|
||||
}
|
||||
|
||||
void AChildHoodCharacter::DoMove(float Right, float Forward)
|
||||
{
|
||||
// P1: 交互中忽略移动输入
|
||||
// 交互中屏蔽移动
|
||||
if (bIsInteracting)
|
||||
{
|
||||
return;
|
||||
@@ -159,6 +173,15 @@ void AChildHoodCharacter::DoLook(float Yaw, float Pitch)
|
||||
}
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
// 交互系统方法
|
||||
// ============================================================================
|
||||
|
||||
UInteractionManager* AChildHoodCharacter::GetInteractionManager() const
|
||||
{
|
||||
return InteractionManager;
|
||||
}
|
||||
|
||||
void AChildHoodCharacter::SetInteracting(bool bValue)
|
||||
{
|
||||
bIsInteracting = bValue;
|
||||
|
||||
@@ -10,6 +10,7 @@
|
||||
class USpringArmComponent;
|
||||
class UCameraComponent;
|
||||
class UInputAction;
|
||||
class UInteractionManager;
|
||||
struct FInputActionValue;
|
||||
|
||||
DECLARE_LOG_CATEGORY_EXTERN(LogTemplateCharacter, Log, All);
|
||||
@@ -57,6 +58,10 @@ protected:
|
||||
UPROPERTY(EditAnywhere, Category="Input")
|
||||
UInputAction* SwitchInteractAction;
|
||||
|
||||
/** 交互管理器组件 */
|
||||
UPROPERTY(VisibleAnywhere, BlueprintReadOnly, Category = "Interaction", meta = (AllowPrivateAccess = "true"))
|
||||
UInteractionManager* InteractionManager;
|
||||
|
||||
/** Whether the character is currently in an interaction */
|
||||
bool bIsInteracting = false;
|
||||
|
||||
@@ -65,6 +70,22 @@ public:
|
||||
/** Constructor */
|
||||
AChildHoodCharacter();
|
||||
|
||||
/** 获取交互管理器组件 */
|
||||
UFUNCTION(BlueprintCallable, BlueprintPure, Category = "Interaction")
|
||||
UInteractionManager* GetInteractionManager() const;
|
||||
|
||||
/** Set interaction state — called by interaction system */
|
||||
UFUNCTION(BlueprintCallable, Category = "Interaction")
|
||||
void SetInteracting(bool bValue);
|
||||
|
||||
/** Query: is the character currently interacting? */
|
||||
UFUNCTION(BlueprintCallable, BlueprintPure, Category="Interaction")
|
||||
bool IsInteracting() const;
|
||||
|
||||
/** Query: is the character currently running (moving on ground)? */
|
||||
UFUNCTION(BlueprintCallable, BlueprintPure, Category="Interaction")
|
||||
bool IsRunning() const;
|
||||
|
||||
protected:
|
||||
|
||||
/** Initialize input action bindings */
|
||||
@@ -78,13 +99,13 @@ protected:
|
||||
/** Called for looking input */
|
||||
void Look(const FInputActionValue& Value);
|
||||
|
||||
/** Called for interact input (E) — placeholder, delegates to interaction system */
|
||||
/** Called for interact input (E) — delegates to InteractionManager */
|
||||
void OnInteract(const FInputActionValue& Value);
|
||||
|
||||
/** Called for cancel input (ESC) — placeholder, delegates to interaction system */
|
||||
/** Called for cancel input (ESC) — delegates to InteractionManager */
|
||||
void OnCancel(const FInputActionValue& Value);
|
||||
|
||||
/** Called for switch interact target input (Tab/Wheel) — placeholder, delegates to interaction system */
|
||||
/** Called for switch interact target input (Tab/Wheel) — delegates to InteractionManager */
|
||||
void OnSwitchInteract(const FInputActionValue& Value);
|
||||
|
||||
public:
|
||||
@@ -97,18 +118,6 @@ public:
|
||||
UFUNCTION(BlueprintCallable, Category="Input")
|
||||
virtual void DoLook(float Yaw, float Pitch);
|
||||
|
||||
/** Set interaction state — called by interaction system */
|
||||
UFUNCTION(BlueprintCallable, Category="Interaction")
|
||||
void SetInteracting(bool bValue);
|
||||
|
||||
/** Query: is the character currently interacting? */
|
||||
UFUNCTION(BlueprintCallable, BlueprintPure, Category="Interaction")
|
||||
bool IsInteracting() const;
|
||||
|
||||
/** Query: is the character currently running (moving on ground)? */
|
||||
UFUNCTION(BlueprintCallable, BlueprintPure, Category="Interaction")
|
||||
bool IsRunning() const;
|
||||
|
||||
public:
|
||||
|
||||
/** Returns CameraBoom subobject **/
|
||||
|
||||
@@ -0,0 +1,30 @@
|
||||
// ChildHood Project - 跨关卡持久数据持有者 实现
|
||||
|
||||
#include "ChildHoodGameInstance.h"
|
||||
|
||||
bool UChildHoodGameInstance::IsItemCollected(FName ItemId) const
|
||||
{
|
||||
return CollectedItemIDs.Contains(ItemId);
|
||||
}
|
||||
|
||||
void UChildHoodGameInstance::MarkItemCollected(FName ItemId)
|
||||
{
|
||||
CollectedItemIDs.Add(ItemId);
|
||||
}
|
||||
|
||||
bool UChildHoodGameInstance::IsDoorOpen(FName DoorId) const
|
||||
{
|
||||
const bool* Found = DoorStates.Find(DoorId);
|
||||
return Found ? *Found : false;
|
||||
}
|
||||
|
||||
void UChildHoodGameInstance::SetDoorOpen(FName DoorId, bool bIsOpen)
|
||||
{
|
||||
DoorStates.Add(DoorId, bIsOpen);
|
||||
}
|
||||
|
||||
void UChildHoodGameInstance::ResetAll()
|
||||
{
|
||||
CollectedItemIDs.Empty();
|
||||
DoorStates.Empty();
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
// ChildHood Project - 跨关卡持久数据持有者
|
||||
// 对应技术方案: docs/technical/交互系统-技术方案.md 第12节(跨场景持久化设计)
|
||||
|
||||
#pragma once
|
||||
|
||||
#include "CoreMinimal.h"
|
||||
#include "Engine/GameInstance.h"
|
||||
#include "ChildHoodGameInstance.generated.h"
|
||||
|
||||
/**
|
||||
* UChildHoodGameInstance
|
||||
*
|
||||
* 跨关卡持久数据持有者。UE5 的 OpenLevel() 会销毁整个旧 World(包括
|
||||
* Character 及其所有 UActorComponent),因此需要将持久数据与运行时行为分离。
|
||||
*
|
||||
* v0.1 为单场景原型,此 GameInstance 以空数据初始化。
|
||||
* 后续多场景版本只需在 Project Settings 中将 GameInstance Class 设为此类即可。
|
||||
*/
|
||||
UCLASS()
|
||||
class UChildHoodGameInstance : public UGameInstance
|
||||
{
|
||||
GENERATED_BODY()
|
||||
|
||||
public:
|
||||
|
||||
// === 物品消耗状态 ===
|
||||
|
||||
/** 查询指定物品是否已被收集(跨场景持久) */
|
||||
bool IsItemCollected(FName ItemId) const;
|
||||
|
||||
/** 标记指定物品为已收集(写入持久层) */
|
||||
void MarkItemCollected(FName ItemId);
|
||||
|
||||
// === 门状态 ===
|
||||
|
||||
/** 查询指定门的开关状态(跨场景持久),未记录的门默认为关闭 */
|
||||
bool IsDoorOpen(FName DoorId) const;
|
||||
|
||||
/** 设置指定门的开关状态(写入持久层) */
|
||||
void SetDoorOpen(FName DoorId, bool bIsOpen);
|
||||
|
||||
// === 重置 ===
|
||||
|
||||
/** 重置所有持久数据(新游戏时调用) */
|
||||
void ResetAll();
|
||||
|
||||
private:
|
||||
|
||||
/** 已收集物品ID集合 */
|
||||
UPROPERTY()
|
||||
TSet<FName> CollectedItemIDs;
|
||||
|
||||
/** 门开关状态映射(true=打开,false=关闭) */
|
||||
UPROPERTY()
|
||||
TMap<FName, bool> DoorStates;
|
||||
};
|
||||
@@ -0,0 +1,47 @@
|
||||
// ChildHood Project - 通用交互物 Actor 基类 实现
|
||||
|
||||
#include "Interaction/InteractableActor.h"
|
||||
#include "Interaction/InteractableComponent.h"
|
||||
|
||||
#include "Components/StaticMeshComponent.h"
|
||||
|
||||
// ============================================================================
|
||||
// 构造函数
|
||||
// ============================================================================
|
||||
|
||||
AInteractableActor::AInteractableActor()
|
||||
{
|
||||
PrimaryActorTick.bCanEverTick = false;
|
||||
|
||||
// 创建 Mesh 为根组件
|
||||
MeshComp = CreateDefaultSubobject<UStaticMeshComponent>(TEXT("MeshComp"));
|
||||
RootComponent = MeshComp;
|
||||
MeshComp->SetCollisionProfileName(TEXT("BlockAll"));
|
||||
|
||||
// 创建交互组件(UActorComponent 不需要 SetupAttachment,数据驱动型组件)
|
||||
InteractableComp = CreateDefaultSubobject<UInteractableComponent>(TEXT("InteractableComp"));
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
// 交互回调
|
||||
// ============================================================================
|
||||
|
||||
void AInteractableActor::OnInteractStarted_Implementation(UInteractableComponent* Comp)
|
||||
{
|
||||
if (!Comp || !MeshComp) return;
|
||||
|
||||
const FInteractableData& Data = Comp->GetInteractableData();
|
||||
|
||||
// 门类型:根据开关状态旋转 Mesh
|
||||
if (Data.Type == EInteractType::Operate && Data.OperateSubType == EOperateSubType::Door)
|
||||
{
|
||||
FRotator CurrentRot = MeshComp->GetRelativeRotation();
|
||||
float TargetYaw = Comp->IsDoorOpen() ? 90.0f : 0.0f;
|
||||
MeshComp->SetRelativeRotation(FRotator(CurrentRot.Pitch, TargetYaw, CurrentRot.Roll));
|
||||
}
|
||||
}
|
||||
|
||||
void AInteractableActor::OnInteractEnded_Implementation(UInteractableComponent* Comp)
|
||||
{
|
||||
// 默认空实现,子类可覆盖
|
||||
}
|
||||
@@ -0,0 +1,69 @@
|
||||
// ChildHood Project - 通用交互物 Actor 基类
|
||||
// 对应技术方案: docs/technical/交互系统-技术方案.md 第3节(类设计)
|
||||
// 职责:持有 Mesh + InteractableComponent,提供可被子类覆盖的交互回调
|
||||
|
||||
#pragma once
|
||||
|
||||
#include "CoreMinimal.h"
|
||||
#include "GameFramework/Actor.h"
|
||||
#include "InteractableActor.generated.h"
|
||||
|
||||
class UInteractableComponent;
|
||||
|
||||
/**
|
||||
* AInteractableActor
|
||||
*
|
||||
* 通用交互物 Actor 基类。场景中的每个交互物(冰箱、门、NPC 等)
|
||||
* 均为该类的实例或其子类的实例。
|
||||
*
|
||||
* 组成:
|
||||
* - UStaticMeshComponent* MeshComp(根组件,承载可视模型)
|
||||
* - UInteractableComponent* InteractableComp(交互逻辑与数据)
|
||||
*
|
||||
* 子类可覆盖 OnInteractStarted / OnInteractEnded 以实现类型特定行为,
|
||||
* 如门开关时的 Mesh 旋转、拾取物的消失效果等。
|
||||
*/
|
||||
UCLASS()
|
||||
class AInteractableActor : public AActor
|
||||
{
|
||||
GENERATED_BODY()
|
||||
|
||||
public:
|
||||
|
||||
AInteractableActor();
|
||||
|
||||
// === 组件访问 ===
|
||||
|
||||
/** 获取静态网格组件 */
|
||||
UFUNCTION(BlueprintCallable, Category = "Interact")
|
||||
UStaticMeshComponent* GetMeshComp() const { return MeshComp; }
|
||||
|
||||
/** 获取交互组件 */
|
||||
UFUNCTION(BlueprintCallable, Category = "Interact")
|
||||
UInteractableComponent* GetInteractableComp() const { return InteractableComp; }
|
||||
|
||||
// === 可被子类覆盖的交互回调 ===
|
||||
|
||||
/**
|
||||
* 交互开始时调用(门开关切换、状态恢复时也调用)。
|
||||
* 默认实现:门类型根据开关状态对 Mesh 做 Yaw 旋转(开门+90度/关门0度)。
|
||||
*/
|
||||
UFUNCTION(BlueprintNativeEvent, Category = "Interact")
|
||||
void OnInteractStarted(UInteractableComponent* Comp);
|
||||
virtual void OnInteractStarted_Implementation(UInteractableComponent* Comp);
|
||||
|
||||
/** 交互结束时调用。默认为空实现,子类可覆盖。 */
|
||||
UFUNCTION(BlueprintNativeEvent, Category = "Interact")
|
||||
void OnInteractEnded(UInteractableComponent* Comp);
|
||||
virtual void OnInteractEnded_Implementation(UInteractableComponent* Comp);
|
||||
|
||||
protected:
|
||||
|
||||
/** 交互物的可视模型 */
|
||||
UPROPERTY(VisibleAnywhere, BlueprintReadOnly, Category = "Components", meta = (AllowPrivateAccess = "true"))
|
||||
UStaticMeshComponent* MeshComp;
|
||||
|
||||
/** 交互物的交互组件(数据 + 检测 + 状态) */
|
||||
UPROPERTY(VisibleAnywhere, BlueprintReadOnly, Category = "Components", meta = (AllowPrivateAccess = "true"))
|
||||
UInteractableComponent* InteractableComp;
|
||||
};
|
||||
@@ -0,0 +1,221 @@
|
||||
// ChildHood Project - 可交互物组件 实现
|
||||
|
||||
#include "Interaction/InteractableComponent.h"
|
||||
#include "Interaction/InteractableActor.h"
|
||||
#include "Interaction/InteractionManager.h"
|
||||
#include "ChildHoodGameInstance.h"
|
||||
#include "ChildHood.h"
|
||||
|
||||
#include "Components/SphereComponent.h"
|
||||
#include "Engine/World.h"
|
||||
#include "GameFramework/Character.h"
|
||||
#include "Kismet/GameplayStatics.h"
|
||||
|
||||
// ============================================================================
|
||||
// 构造函数
|
||||
// ============================================================================
|
||||
|
||||
UInteractableComponent::UInteractableComponent()
|
||||
{
|
||||
// 不需要 Tick,检测由碰撞事件驱动
|
||||
PrimaryComponentTick.bCanEverTick = false;
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
// 生命周期
|
||||
// ============================================================================
|
||||
|
||||
void UInteractableComponent::BeginPlay()
|
||||
{
|
||||
Super::BeginPlay();
|
||||
|
||||
AActor* Owner = GetOwner();
|
||||
if (!Owner)
|
||||
{
|
||||
UE_LOG(LogChildHood, Warning, TEXT("InteractableComponent: 无 Owner,跳过初始化"));
|
||||
return;
|
||||
}
|
||||
|
||||
// --- 创建检测球 ---
|
||||
DetectionSphere = NewObject<USphereComponent>(this, USphereComponent::StaticClass(), TEXT("DetectionSphere"));
|
||||
if (DetectionSphere)
|
||||
{
|
||||
DetectionSphere->SetupAttachment(Owner->GetRootComponent());
|
||||
DetectionSphere->RegisterComponent();
|
||||
DetectionSphere->SetSphereRadius(Data.TriggerRadius);
|
||||
DetectionSphere->SetCollisionProfileName(TEXT("OverlapAllDynamic"));
|
||||
// 关闭物理模拟,仅用于 Overlap 检测
|
||||
DetectionSphere->SetGenerateOverlapEvents(true);
|
||||
DetectionSphere->SetCanEverAffectNavigation(false);
|
||||
|
||||
// 绑定碰撞事件
|
||||
DetectionSphere->OnComponentBeginOverlap.AddDynamic(this, &UInteractableComponent::OnDetectionOverlapBegin);
|
||||
DetectionSphere->OnComponentEndOverlap.AddDynamic(this, &UInteractableComponent::OnDetectionOverlapEnd);
|
||||
}
|
||||
else
|
||||
{
|
||||
UE_LOG(LogChildHood, Error, TEXT("InteractableComponent: DetectionSphere 创建失败"));
|
||||
}
|
||||
|
||||
// --- 恢复跨场景持久状态 ---
|
||||
if (UChildHoodGameInstance* GI = GetWorld()->GetGameInstance<UChildHoodGameInstance>())
|
||||
{
|
||||
RestorePersistentState(GI);
|
||||
}
|
||||
|
||||
UE_LOG(LogChildHood, Log, TEXT("InteractableComponent Init: %s (Type=%s, Radius=%f)"),
|
||||
Data.DisplayName.IsEmpty() ? TEXT("(unnamed)") : *Data.DisplayName,
|
||||
*UEnum::GetValueAsString(Data.Type),
|
||||
Data.TriggerRadius);
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
// 提示文本
|
||||
// ============================================================================
|
||||
|
||||
FString UInteractableComponent::GetPromptText() const
|
||||
{
|
||||
FString Verb = Data.InteractVerb;
|
||||
// 门类型:根据当前开关状态选择动词
|
||||
if (Data.Type == EInteractType::Operate && Data.OperateSubType == EOperateSubType::Door)
|
||||
{
|
||||
Verb = bDoorIsOpen ? Data.InteractVerbAlt : Data.InteractVerb;
|
||||
}
|
||||
return FString::Printf(TEXT("[E] %s %s"), *Verb, *Data.DisplayName);
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
// 消耗管理
|
||||
// ============================================================================
|
||||
|
||||
void UInteractableComponent::Consume()
|
||||
{
|
||||
bIsConsumed = true;
|
||||
|
||||
// 禁用检测球,不再触发 Overlap
|
||||
if (DetectionSphere)
|
||||
{
|
||||
DetectionSphere->SetCollisionEnabled(ECollisionEnabled::NoCollision);
|
||||
}
|
||||
|
||||
// 写入持久层
|
||||
if (UWorld* World = GetWorld())
|
||||
{
|
||||
if (UChildHoodGameInstance* GI = World->GetGameInstance<UChildHoodGameInstance>())
|
||||
{
|
||||
GI->MarkItemCollected(Data.ItemId);
|
||||
}
|
||||
}
|
||||
|
||||
UE_LOG(LogChildHood, Log, TEXT("InteractableComponent 已消耗: %s"), *Data.ItemId.ToString());
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
// 门状态管理
|
||||
// ============================================================================
|
||||
|
||||
void UInteractableComponent::ToggleDoor()
|
||||
{
|
||||
bDoorIsOpen = !bDoorIsOpen;
|
||||
UE_LOG(LogChildHood, Log, TEXT("InteractableComponent 门状态切换: %s → %s"),
|
||||
*Data.ItemId.ToString(),
|
||||
bDoorIsOpen ? TEXT("开") : TEXT("关"));
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
// 位置查询
|
||||
// ============================================================================
|
||||
|
||||
FVector UInteractableComponent::GetWorldLocation() const
|
||||
{
|
||||
AActor* Owner = GetOwner();
|
||||
return Owner ? Owner->GetActorLocation() : FVector::ZeroVector;
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
// 跨场景持久状态恢复
|
||||
// ============================================================================
|
||||
|
||||
void UInteractableComponent::RestorePersistentState(UChildHoodGameInstance* GI)
|
||||
{
|
||||
if (!GI) return;
|
||||
|
||||
// oneShot 物品:已消耗 → 隐藏 + 禁用检测
|
||||
if (Data.bOneShot && GI->IsItemCollected(Data.ItemId))
|
||||
{
|
||||
bIsConsumed = true;
|
||||
if (DetectionSphere)
|
||||
{
|
||||
DetectionSphere->SetCollisionEnabled(ECollisionEnabled::NoCollision);
|
||||
}
|
||||
if (AInteractableActor* Owner = Cast<AInteractableActor>(GetOwner()))
|
||||
{
|
||||
Owner->SetActorHiddenInGame(true);
|
||||
}
|
||||
UE_LOG(LogChildHood, Log, TEXT("RestorePersistentState: 已消耗物品隐藏: %s"), *Data.ItemId.ToString());
|
||||
}
|
||||
|
||||
// 门:恢复开关状态
|
||||
if (Data.Type == EInteractType::Operate && Data.OperateSubType == EOperateSubType::Door)
|
||||
{
|
||||
bDoorIsOpen = GI->IsDoorOpen(Data.ItemId);
|
||||
// 通知 Actor 应用视觉状态(Mesh 旋转)
|
||||
if (AInteractableActor* Owner = Cast<AInteractableActor>(GetOwner()))
|
||||
{
|
||||
Owner->OnInteractStarted(this);
|
||||
}
|
||||
UE_LOG(LogChildHood, Log, TEXT("RestorePersistentState: 门状态恢复: %s → %s"),
|
||||
*Data.ItemId.ToString(),
|
||||
bDoorIsOpen ? TEXT("开") : TEXT("关"));
|
||||
}
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
// 碰撞回调
|
||||
// ============================================================================
|
||||
|
||||
void UInteractableComponent::OnDetectionOverlapBegin(UPrimitiveComponent* OverlappedComponent,
|
||||
AActor* OtherActor,
|
||||
UPrimitiveComponent* OtherComp,
|
||||
int32 OtherBodyIndex,
|
||||
bool bFromSweep,
|
||||
const FHitResult& SweepResult)
|
||||
{
|
||||
if (!OtherActor) return;
|
||||
|
||||
// 只响应 Character(玩家)的进入
|
||||
ACharacter* Character = Cast<ACharacter>(OtherActor);
|
||||
if (!Character) return;
|
||||
|
||||
// 已消耗的交互物不再注册
|
||||
if (bIsConsumed) return;
|
||||
|
||||
UE_LOG(LogChildHood, Verbose, TEXT("检测到角色进入范围: %s ← %s"),
|
||||
*Data.DisplayName, *OtherActor->GetName());
|
||||
|
||||
// 获取角色的 InteractionManager 并注册自己
|
||||
if (UInteractionManager* IM = Character->FindComponentByClass<UInteractionManager>())
|
||||
{
|
||||
IM->RegisterInteractable(this);
|
||||
}
|
||||
}
|
||||
|
||||
void UInteractableComponent::OnDetectionOverlapEnd(UPrimitiveComponent* OverlappedComponent,
|
||||
AActor* OtherActor,
|
||||
UPrimitiveComponent* OtherComp,
|
||||
int32 OtherBodyIndex)
|
||||
{
|
||||
if (!OtherActor) return;
|
||||
|
||||
ACharacter* Character = Cast<ACharacter>(OtherActor);
|
||||
if (!Character) return;
|
||||
|
||||
UE_LOG(LogChildHood, Verbose, TEXT("角色离开范围: %s ← %s"),
|
||||
*Data.DisplayName, *OtherActor->GetName());
|
||||
|
||||
// 获取角色的 InteractionManager 并注销自己
|
||||
if (UInteractionManager* IM = Character->FindComponentByClass<UInteractionManager>())
|
||||
{
|
||||
IM->UnregisterInteractable(this);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,101 @@
|
||||
// ChildHood Project - 可交互物组件
|
||||
// 对应技术方案: docs/technical/交互系统-技术方案.md 第3节(类设计)+ 第12节(跨场景持久化)
|
||||
// 职责:单个交互物配置数据、触发区域、运行时状态、跨场景持久状态恢复
|
||||
|
||||
#pragma once
|
||||
|
||||
#include "CoreMinimal.h"
|
||||
#include "Components/ActorComponent.h"
|
||||
#include "InteractionTypes.h"
|
||||
#include "InteractableComponent.generated.h"
|
||||
|
||||
class UChildHoodGameInstance;
|
||||
class USphereComponent;
|
||||
|
||||
/**
|
||||
* UInteractableComponent
|
||||
*
|
||||
* 挂载在 AInteractableActor(或其子类)上的组件。
|
||||
* 持有该交互物的全部配置数据(FInteractableData)、运行时触发检测球、
|
||||
* 消耗/门状态管理,以及跨场景持久状态恢复。
|
||||
*/
|
||||
UCLASS(ClassGroup=(Interaction), meta=(BlueprintSpawnableComponent))
|
||||
class UInteractableComponent : public UActorComponent
|
||||
{
|
||||
GENERATED_BODY()
|
||||
|
||||
public:
|
||||
|
||||
UInteractableComponent();
|
||||
|
||||
// === 配置数据 ===
|
||||
|
||||
/** 该交互物的全部配置数据,编辑器中按实例独立配置 */
|
||||
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "Interact")
|
||||
FInteractableData Data;
|
||||
|
||||
// === 查询接口 ===
|
||||
|
||||
/** 获取配置数据引用(只读) */
|
||||
const FInteractableData& GetInteractableData() const { return Data; }
|
||||
|
||||
/**
|
||||
* 获取提示文本,格式:"[E] 动作词 名称"
|
||||
* 门类型根据当前开关状态选择动词
|
||||
*/
|
||||
FString GetPromptText() const;
|
||||
|
||||
/** 该交互物是否已被消耗(oneShot 模式) */
|
||||
bool IsConsumed() const { return bIsConsumed; }
|
||||
|
||||
/** 标记为已消耗,禁用检测球,写入持久层 */
|
||||
void Consume();
|
||||
|
||||
// === 门状态管理 ===
|
||||
|
||||
/** 切换门开关状态 */
|
||||
void ToggleDoor();
|
||||
|
||||
/** 门是否处于打开状态 */
|
||||
bool IsDoorOpen() const { return bDoorIsOpen; }
|
||||
|
||||
/** 获取交互物在世界空间的位置 */
|
||||
FVector GetWorldLocation() const;
|
||||
|
||||
/** 从 GameInstance 恢复跨场景持久状态(BeginPlay 中调用) */
|
||||
void RestorePersistentState(UChildHoodGameInstance* GI);
|
||||
|
||||
protected:
|
||||
|
||||
virtual void BeginPlay() override;
|
||||
|
||||
private:
|
||||
|
||||
/** 运行时创建的检测球,用于触发玩家进入/离开交互范围 */
|
||||
UPROPERTY()
|
||||
USphereComponent* DetectionSphere;
|
||||
|
||||
/** oneShot 物品是否已被消耗 */
|
||||
bool bIsConsumed = false;
|
||||
|
||||
/** 门是否处于打开状态(仅 Operate+Door 类型使用) */
|
||||
bool bDoorIsOpen = false;
|
||||
|
||||
// === 碰撞回调 ===
|
||||
|
||||
/** 玩家进入检测范围 */
|
||||
UFUNCTION()
|
||||
void OnDetectionOverlapBegin(UPrimitiveComponent* OverlappedComponent,
|
||||
AActor* OtherActor,
|
||||
UPrimitiveComponent* OtherComp,
|
||||
int32 OtherBodyIndex,
|
||||
bool bFromSweep,
|
||||
const FHitResult& SweepResult);
|
||||
|
||||
/** 玩家离开检测范围 */
|
||||
UFUNCTION()
|
||||
void OnDetectionOverlapEnd(UPrimitiveComponent* OverlappedComponent,
|
||||
AActor* OtherActor,
|
||||
UPrimitiveComponent* OtherComp,
|
||||
int32 OtherBodyIndex);
|
||||
};
|
||||
@@ -0,0 +1,897 @@
|
||||
// ChildHood Project - 交互管理器核心组件 实现
|
||||
// 对应技术方案: docs/technical/交互系统-技术方案.md 第6节(行为规则实现)
|
||||
|
||||
#include "Interaction/InteractionManager.h"
|
||||
#include "Interaction/InteractableComponent.h"
|
||||
#include "Interaction/InteractableActor.h"
|
||||
#include "Interaction/PushCameraActor.h"
|
||||
#include "Interaction/InteractionPromptWidget.h"
|
||||
#include "Interaction/NarrativeTextWidget.h"
|
||||
#include "ChildHoodCharacter.h"
|
||||
#include "ChildHoodGameInstance.h"
|
||||
#include "ChildHood.h"
|
||||
|
||||
#include "GameFramework/Character.h"
|
||||
#include "GameFramework/PlayerController.h"
|
||||
#include "GameFramework/SpringArmComponent.h"
|
||||
#include "Camera/CameraComponent.h"
|
||||
#include "Components/SphereComponent.h"
|
||||
#include "Engine/World.h"
|
||||
#include "TimerManager.h"
|
||||
#include "Kismet/GameplayStatics.h"
|
||||
#include "Blueprint/WidgetBlueprintLibrary.h"
|
||||
|
||||
// 定义交互系统日志类别
|
||||
DECLARE_LOG_CATEGORY_EXTERN(LogInteraction, Log, All);
|
||||
DEFINE_LOG_CATEGORY(LogInteraction);
|
||||
|
||||
// ============================================================================
|
||||
// 构造函数
|
||||
// ============================================================================
|
||||
|
||||
UInteractionManager::UInteractionManager()
|
||||
{
|
||||
// 默认关闭 Tick,首个交互物注册时开启
|
||||
PrimaryComponentTick.bCanEverTick = true;
|
||||
PrimaryComponentTick.bStartWithTickEnabled = false;
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
// 生命周期
|
||||
// ============================================================================
|
||||
|
||||
void UInteractionManager::BeginPlay()
|
||||
{
|
||||
Super::BeginPlay();
|
||||
|
||||
// Spawn 推镜用临时摄像机 Actor(使用专用的 APushCameraActor)
|
||||
// 随 Character 生命周期,不反复创建/销毁
|
||||
FActorSpawnParameters SpawnParams;
|
||||
SpawnParams.Owner = GetOwner();
|
||||
SpawnParams.SpawnCollisionHandlingOverride = ESpawnActorCollisionHandlingMethod::AlwaysSpawn;
|
||||
|
||||
APushCameraActor* SpawnedCamera = GetWorld()->SpawnActor<APushCameraActor>(APushCameraActor::StaticClass(), FVector::ZeroVector, FRotator::ZeroRotator, SpawnParams);
|
||||
PushCameraActor = SpawnedCamera;
|
||||
if (PushCameraActor)
|
||||
{
|
||||
PushCameraActor->SetActorHiddenInGame(true);
|
||||
}
|
||||
|
||||
UE_LOG(LogInteraction, Log, TEXT("InteractionManager: BeginPlay 完成, PushCameraActor=%s"),
|
||||
PushCameraActor ? *PushCameraActor->GetName() : TEXT("nullptr"));
|
||||
|
||||
// --- 创建 UI Widget ---
|
||||
APlayerController* PC = GetWorld()->GetFirstPlayerController();
|
||||
if (PC)
|
||||
{
|
||||
// 创建提示 UI
|
||||
if (PromptWidgetClass)
|
||||
{
|
||||
PromptWidget = CreateWidget<UInteractionPromptWidget>(PC, PromptWidgetClass);
|
||||
if (PromptWidget)
|
||||
{
|
||||
PromptWidget->AddToViewport(10);
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
UE_LOG(LogInteraction, Warning, TEXT("InteractionManager: PromptWidgetClass 未设置,提示 UI 不可用"));
|
||||
}
|
||||
|
||||
// 创建文本底框 UI
|
||||
if (NarrativeWidgetClass)
|
||||
{
|
||||
NarrativeWidget = CreateWidget<UNarrativeTextWidget>(PC, NarrativeWidgetClass);
|
||||
if (NarrativeWidget)
|
||||
{
|
||||
NarrativeWidget->AddToViewport(20);
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
UE_LOG(LogInteraction, Warning, TEXT("InteractionManager: NarrativeWidgetClass 未设置,文本 UI 不可用"));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
// Tick 驱动
|
||||
// ============================================================================
|
||||
|
||||
void UInteractionManager::TickComponent(float DeltaTime, ELevelTick TickType, FActorComponentTickFunction* ThisTickFunction)
|
||||
{
|
||||
Super::TickComponent(DeltaTime, TickType, ThisTickFunction);
|
||||
|
||||
if (State == EInteractionState::Free)
|
||||
{
|
||||
// Free 状态下更新提示 UI 的屏幕位置
|
||||
if (PromptWidget && PromptWidget->IsVisible() &&
|
||||
NearbyInteractables.Num() > 0 && NearbyInteractables.IsValidIndex(SelectedIndex))
|
||||
{
|
||||
UInteractableComponent* Selected = NearbyInteractables[SelectedIndex];
|
||||
if (Selected)
|
||||
{
|
||||
UpdatePromptScreenPosition(Selected);
|
||||
}
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
switch (Phase)
|
||||
{
|
||||
case EInteractPhase::Enter:
|
||||
TickEnterPhase(DeltaTime);
|
||||
break;
|
||||
|
||||
case EInteractPhase::AnimLock:
|
||||
TickAnimLockPhase(DeltaTime);
|
||||
break;
|
||||
|
||||
case EInteractPhase::Active:
|
||||
// 等待玩家输入,无需 Tick 处理
|
||||
break;
|
||||
|
||||
case EInteractPhase::Exit:
|
||||
TickExitPhase(DeltaTime);
|
||||
break;
|
||||
|
||||
case EInteractPhase::None:
|
||||
default:
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
// 公开方法
|
||||
// ============================================================================
|
||||
|
||||
void UInteractionManager::BeginInteract()
|
||||
{
|
||||
// 前置检查:必须 Free 状态
|
||||
if (State != EInteractionState::Free)
|
||||
{
|
||||
UE_LOG(LogInteraction, Verbose, TEXT("BeginInteract: 拒绝,当前状态不是 Free (State=%d)"),
|
||||
static_cast<int32>(State));
|
||||
return;
|
||||
}
|
||||
|
||||
// 前置检查:必须有选中的交互物
|
||||
if (NearbyInteractables.Num() == 0 || !NearbyInteractables.IsValidIndex(SelectedIndex))
|
||||
{
|
||||
UE_LOG(LogInteraction, Verbose, TEXT("BeginInteract: 拒绝,没有选中的交互物"));
|
||||
return;
|
||||
}
|
||||
|
||||
UInteractableComponent* Target = NearbyInteractables[SelectedIndex];
|
||||
|
||||
// 前置检查:交互物不能已被消耗
|
||||
if (!Target || Target->IsConsumed())
|
||||
{
|
||||
UE_LOG(LogInteraction, Verbose, TEXT("BeginInteract: 拒绝,交互物已被消耗"));
|
||||
return;
|
||||
}
|
||||
|
||||
// 进入交互
|
||||
State = EInteractionState::Interacting;
|
||||
Phase = EInteractPhase::Enter;
|
||||
CurrentInteractable = Target;
|
||||
|
||||
// 通知 Character 进入交互状态(屏蔽移动)
|
||||
AChildHoodCharacter* Char = Cast<AChildHoodCharacter>(GetOwner());
|
||||
if (Char)
|
||||
{
|
||||
Char->SetInteracting(true);
|
||||
}
|
||||
|
||||
// 隐藏提示 UI
|
||||
HidePrompt();
|
||||
|
||||
// 重置 Enter 阶段计时器
|
||||
TurnElapsed = 0.0f;
|
||||
WaitElapsed = 0.0f;
|
||||
bPushStarted = false;
|
||||
|
||||
const FInteractableData& Data = Target->GetInteractableData();
|
||||
UE_LOG(LogInteraction, Log, TEXT("BeginInteract: 开始交互 '%s' (Type=%d)"),
|
||||
*Data.DisplayName, static_cast<int32>(Data.Type));
|
||||
}
|
||||
|
||||
void UInteractionManager::CancelInteract()
|
||||
{
|
||||
// 前置检查:必须 Interacting 状态
|
||||
if (State != EInteractionState::Interacting)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
// AnimLock 期间不可取消
|
||||
if (Phase == EInteractPhase::AnimLock)
|
||||
{
|
||||
UE_LOG(LogInteraction, Verbose, TEXT("CancelInteract: 拒绝,AnimLock 阶段不可取消"));
|
||||
return;
|
||||
}
|
||||
|
||||
UE_LOG(LogInteraction, Log, TEXT("CancelInteract: 取消/结束交互"));
|
||||
|
||||
// 隐藏叙事文本
|
||||
HideNarrativeText();
|
||||
|
||||
// 进入 Exit 阶段
|
||||
Phase = EInteractPhase::Exit;
|
||||
|
||||
// 相机回位
|
||||
const FInteractableData* Data = CurrentInteractable ? &CurrentInteractable->GetInteractableData() : nullptr;
|
||||
float ReturnDuration = (Data && Data->bUseCameraPush) ? Data->CameraReturnDuration : 0.3f;
|
||||
ReturnCamera(ReturnDuration);
|
||||
|
||||
// 清除可能残留的计时器
|
||||
GetWorld()->GetTimerManager().ClearTimer(AnimEventTimerHandle);
|
||||
GetWorld()->GetTimerManager().ClearTimer(AnimEndTimerHandle);
|
||||
|
||||
// 设置退出定时器,回位动画播完后回到 Free
|
||||
GetWorld()->GetTimerManager().SetTimer(ExitTimerHandle, this, &UInteractionManager::OnExitTimerComplete, ReturnDuration, false);
|
||||
}
|
||||
|
||||
void UInteractionManager::SwitchTarget(int32 Direction)
|
||||
{
|
||||
int32 Num = NearbyInteractables.Num();
|
||||
if (Num == 0)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
// Interacting 状态下忽略切换
|
||||
if (State != EInteractionState::Free)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
SelectedIndex = (SelectedIndex + Direction + Num) % Num;
|
||||
UpdatePromptUI();
|
||||
|
||||
UE_LOG(LogInteraction, Log, TEXT("SwitchTarget: 切换到 %d/%d"), SelectedIndex, Num);
|
||||
}
|
||||
|
||||
void UInteractionManager::RegisterInteractable(UInteractableComponent* Interactable)
|
||||
{
|
||||
if (!Interactable)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
// 去重检查
|
||||
if (NearbyInteractables.Contains(Interactable))
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
NearbyInteractables.Add(Interactable);
|
||||
|
||||
// 按水平距离排序(DistSquared2D,避免 sqrt)
|
||||
AActor* Owner = GetOwner();
|
||||
if (Owner)
|
||||
{
|
||||
FVector OwnerLoc = Owner->GetActorLocation();
|
||||
NearbyInteractables.Sort([OwnerLoc](const UInteractableComponent& A, const UInteractableComponent& B)
|
||||
{
|
||||
float DistA = FVector::DistSquared2D(OwnerLoc, A.GetWorldLocation());
|
||||
float DistB = FVector::DistSquared2D(OwnerLoc, B.GetWorldLocation());
|
||||
return DistA < DistB;
|
||||
});
|
||||
}
|
||||
|
||||
UpdateSelection();
|
||||
UpdatePromptUI();
|
||||
|
||||
// 首个交互物注册时开启 Tick
|
||||
if (NearbyInteractables.Num() == 1)
|
||||
{
|
||||
SetComponentTickEnabled(true);
|
||||
}
|
||||
|
||||
UE_LOG(LogInteraction, Log, TEXT("RegisterInteractable: 注册 '%s', 列表大小=%d"),
|
||||
*Interactable->GetInteractableData().DisplayName, NearbyInteractables.Num());
|
||||
}
|
||||
|
||||
void UInteractionManager::UnregisterInteractable(UInteractableComponent* Interactable)
|
||||
{
|
||||
if (!Interactable)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
bool bRemoved = NearbyInteractables.Remove(Interactable) > 0;
|
||||
if (!bRemoved)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
// 如果移除的是当前正在交互的交互物,清空引用
|
||||
if (CurrentInteractable == Interactable)
|
||||
{
|
||||
CurrentInteractable = nullptr;
|
||||
}
|
||||
|
||||
if (NearbyInteractables.Num() > 0)
|
||||
{
|
||||
UpdateSelection();
|
||||
UpdatePromptUI();
|
||||
}
|
||||
else
|
||||
{
|
||||
// 列表为空,隐藏提示
|
||||
HidePrompt();
|
||||
// 最后一个注销时关闭 Tick
|
||||
SetComponentTickEnabled(false);
|
||||
}
|
||||
|
||||
UE_LOG(LogInteraction, Log, TEXT("UnregisterInteractable: 注销 '%s', 列表大小=%d"),
|
||||
*Interactable->GetInteractableData().DisplayName, NearbyInteractables.Num());
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
// Enter 阶段 Tick
|
||||
// ============================================================================
|
||||
|
||||
void UInteractionManager::TickEnterPhase(float DeltaTime)
|
||||
{
|
||||
if (!CurrentInteractable)
|
||||
{
|
||||
UE_LOG(LogInteraction, Warning, TEXT("TickEnterPhase: CurrentInteractable 为空,强制取消"));
|
||||
CancelInteract();
|
||||
return;
|
||||
}
|
||||
|
||||
ACharacter* Char = Cast<ACharacter>(GetOwner());
|
||||
if (!Char)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
const FInteractableData& Data = CurrentInteractable->GetInteractableData();
|
||||
|
||||
// --- 1. 转向插值 ---
|
||||
TurnElapsed += DeltaTime;
|
||||
|
||||
FVector CharLoc = Char->GetActorLocation();
|
||||
FVector TargetLoc = CurrentInteractable->GetWorldLocation();
|
||||
FVector DirToTarget = (TargetLoc - CharLoc);
|
||||
DirToTarget.Z = 0.0f;
|
||||
FRotator TargetRot = DirToTarget.Rotation();
|
||||
|
||||
// 使用 RInterpTo 进行平滑插值,InterpSpeed = 1/TurnDuration
|
||||
float InterpSpeed = (TurnDuration > 0.f) ? (1.f / TurnDuration) : 10.f;
|
||||
FRotator NewRot = FMath::RInterpTo(Char->GetActorRotation(), TargetRot, DeltaTime, InterpSpeed);
|
||||
Char->SetActorRotation(NewRot);
|
||||
|
||||
// --- 2. 推镜(一次性发起) ---
|
||||
if (Data.bUseCameraPush && !bPushStarted)
|
||||
{
|
||||
FVector PushPos = CalculatePushPosition(CurrentInteractable);
|
||||
PushCamera(PushPos, Data.CameraPushDuration);
|
||||
bPushStarted = true;
|
||||
}
|
||||
|
||||
// --- 3. 判断完成 ---
|
||||
bool bTurnComplete = TurnElapsed >= TurnDuration;
|
||||
bool bPushComplete = !Data.bUseCameraPush || bPushStarted;
|
||||
|
||||
if (bTurnComplete && bPushComplete)
|
||||
{
|
||||
// 推镜后需要额外等待 PushWaitDelay
|
||||
if (Data.bUseCameraPush && Data.PushWaitDelay > 0.f)
|
||||
{
|
||||
WaitElapsed += DeltaTime;
|
||||
if (WaitElapsed >= Data.PushWaitDelay)
|
||||
{
|
||||
TransitionFromEnter();
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
TransitionFromEnter();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
// AnimLock 阶段 Tick(v0.1 由计时器驱动,此处为空)
|
||||
// ============================================================================
|
||||
|
||||
void UInteractionManager::TickAnimLockPhase(float DeltaTime)
|
||||
{
|
||||
// v0.1: AnimLock 由 AnimEventTimer 和 AnimEndTimer 驱动,无需 Tick 处理
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
// Exit 阶段 Tick(v0.1 由定时器驱动回 Free)
|
||||
// ============================================================================
|
||||
|
||||
void UInteractionManager::TickExitPhase(float DeltaTime)
|
||||
{
|
||||
// v0.1: Exit 阶段由 ExitTimerHandle 定时器驱动回到 Free
|
||||
// 此处可做相机回位进度检查等,简单方案留空
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
// Enter 完成后类型分发
|
||||
// ============================================================================
|
||||
|
||||
void UInteractionManager::TransitionFromEnter()
|
||||
{
|
||||
if (!CurrentInteractable)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
const FInteractableData& Data = CurrentInteractable->GetInteractableData();
|
||||
|
||||
UE_LOG(LogInteraction, Log, TEXT("TransitionFromEnter: 类型=%d 分发"), static_cast<int32>(Data.Type));
|
||||
|
||||
switch (Data.Type)
|
||||
{
|
||||
case EInteractType::Examine:
|
||||
Phase = EInteractPhase::Active;
|
||||
ShowNarrativeText(PickRandomNarrative(Data.NarrativeTexts));
|
||||
break;
|
||||
|
||||
case EInteractType::Pickup:
|
||||
Phase = EInteractPhase::AnimLock;
|
||||
EnterAnimLockPhase();
|
||||
break;
|
||||
|
||||
case EInteractType::Operate:
|
||||
if (Data.OperateSubType == EOperateSubType::Door)
|
||||
{
|
||||
Phase = EInteractPhase::AnimLock;
|
||||
EnterAnimLockPhase();
|
||||
}
|
||||
else if (Data.OperateSubType == EOperateSubType::Search)
|
||||
{
|
||||
Phase = EInteractPhase::AnimLock;
|
||||
EnterAnimLockPhase();
|
||||
}
|
||||
break;
|
||||
|
||||
case EInteractType::Talk:
|
||||
Phase = EInteractPhase::Active;
|
||||
ShowNarrativeText(PickRandomNarrative(Data.NarrativeTexts));
|
||||
break;
|
||||
|
||||
default:
|
||||
UE_LOG(LogInteraction, Warning, TEXT("TransitionFromEnter: 未知交互类型 %d"), static_cast<int32>(Data.Type));
|
||||
// 未知类型直接回 Free
|
||||
CancelInteract();
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
// AnimLock 阶段
|
||||
// ============================================================================
|
||||
|
||||
void UInteractionManager::EnterAnimLockPhase()
|
||||
{
|
||||
if (!CurrentInteractable)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
const FInteractableData& Data = CurrentInteractable->GetInteractableData();
|
||||
|
||||
// 计算总动画时长:有蒙太奇用蒙太奇长度,否则用配置的 AnimDuration
|
||||
float TotalAnimTime = Data.AnimDuration;
|
||||
if (Data.InteractMontage)
|
||||
{
|
||||
TotalAnimTime = Data.InteractMontage->GetPlayLength();
|
||||
if (TotalAnimTime <= 0.f)
|
||||
{
|
||||
TotalAnimTime = Data.AnimDuration;
|
||||
}
|
||||
|
||||
// 播放蒙太奇
|
||||
ACharacter* Char = Cast<ACharacter>(GetOwner());
|
||||
if (Char && Char->GetMesh())
|
||||
{
|
||||
Char->GetMesh()->GetAnimInstance()->Montage_Play(Data.InteractMontage);
|
||||
UE_LOG(LogInteraction, Log, TEXT("EnterAnimLockPhase: 播放蒙太奇, 时长=%.2f"), TotalAnimTime);
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
UE_LOG(LogInteraction, Log, TEXT("EnterAnimLockPhase: 无蒙太奇,使用计时器, 时长=%.2f"), TotalAnimTime);
|
||||
}
|
||||
|
||||
// 动画事件触发计时器(如 60% 时物品消失)
|
||||
float EventTime = TotalAnimTime * Data.AnimEventTimepoint;
|
||||
GetWorld()->GetTimerManager().SetTimer(AnimEventTimerHandle, this, &UInteractionManager::ExecuteAnimEvent, EventTime, false);
|
||||
|
||||
// 动画结束计时器
|
||||
GetWorld()->GetTimerManager().SetTimer(AnimEndTimerHandle, this, &UInteractionManager::OnAnimLockComplete, TotalAnimTime, false);
|
||||
|
||||
bAnimEventFired = false;
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
// 动画事件触发回调
|
||||
// ============================================================================
|
||||
|
||||
void UInteractionManager::ExecuteAnimEvent()
|
||||
{
|
||||
if (!CurrentInteractable)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
bAnimEventFired = true;
|
||||
const FInteractableData& Data = CurrentInteractable->GetInteractableData();
|
||||
|
||||
UE_LOG(LogInteraction, Log, TEXT("ExecuteAnimEvent: 类型=%d, 名称='%s'"),
|
||||
static_cast<int32>(Data.Type), *Data.DisplayName);
|
||||
|
||||
switch (Data.Type)
|
||||
{
|
||||
case EInteractType::Pickup:
|
||||
{
|
||||
// 标记消耗 → 隐藏 Actor → 通知物品系统
|
||||
CurrentInteractable->Consume();
|
||||
|
||||
// 隐藏交互物 Actor
|
||||
if (AInteractableActor* OwnerActor = Cast<AInteractableActor>(CurrentInteractable->GetOwner()))
|
||||
{
|
||||
OwnerActor->SetActorHiddenInGame(true);
|
||||
}
|
||||
|
||||
// 广播拾取事件
|
||||
OnItemPickedUp.Broadcast(Data.ItemId, Data.DisplayName, FName(TEXT("杂物")));
|
||||
UE_LOG(LogInteraction, Log, TEXT("ExecuteAnimEvent: Pickup 拾取完成 '%s'"), *Data.DisplayName);
|
||||
}
|
||||
break;
|
||||
|
||||
case EInteractType::Operate:
|
||||
{
|
||||
if (Data.OperateSubType == EOperateSubType::Door)
|
||||
{
|
||||
// 切换门状态
|
||||
CurrentInteractable->ToggleDoor();
|
||||
|
||||
// 持久化门状态到 GameInstance
|
||||
if (UChildHoodGameInstance* GI = GetWorld()->GetGameInstance<UChildHoodGameInstance>())
|
||||
{
|
||||
GI->SetDoorOpen(Data.ItemId, CurrentInteractable->IsDoorOpen());
|
||||
}
|
||||
|
||||
// 通知 Actor 处理 Mesh 旋转等视觉反馈
|
||||
if (AInteractableActor* OwnerActor = Cast<AInteractableActor>(CurrentInteractable->GetOwner()))
|
||||
{
|
||||
OwnerActor->OnInteractStarted(CurrentInteractable);
|
||||
}
|
||||
|
||||
UE_LOG(LogInteraction, Log, TEXT("ExecuteAnimEvent: Door 门状态切换, 开=%s"),
|
||||
CurrentInteractable->IsDoorOpen() ? TEXT("true") : TEXT("false"));
|
||||
}
|
||||
// Search 类型的结果判定在 OnAnimLockComplete 中处理
|
||||
}
|
||||
break;
|
||||
|
||||
default:
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
// 动画结束回调
|
||||
// ============================================================================
|
||||
|
||||
void UInteractionManager::OnAnimLockComplete()
|
||||
{
|
||||
if (!CurrentInteractable)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
const FInteractableData& Data = CurrentInteractable->GetInteractableData();
|
||||
|
||||
UE_LOG(LogInteraction, Log, TEXT("OnAnimLockComplete: 类型=%d, 名称='%s'"),
|
||||
static_cast<int32>(Data.Type), *Data.DisplayName);
|
||||
|
||||
switch (Data.Type)
|
||||
{
|
||||
case EInteractType::Pickup:
|
||||
{
|
||||
// 直接回到 Free(无 Active/Exit,无相机/UI 需清理)
|
||||
AChildHoodCharacter* Char = Cast<AChildHoodCharacter>(GetOwner());
|
||||
if (Char)
|
||||
{
|
||||
Char->SetInteracting(false);
|
||||
}
|
||||
State = EInteractionState::Free;
|
||||
Phase = EInteractPhase::None;
|
||||
CurrentInteractable = nullptr;
|
||||
|
||||
// 从检测列表移除已消耗的交互物
|
||||
// Consume 已在 ExecuteAnimEvent 中调用,但 UnregisterInteractable 应由 DetectionSphere 禁用触发
|
||||
// 这里主动从列表移除,确保提示 UI 正确更新
|
||||
if (NearbyInteractables.Num() > 0)
|
||||
{
|
||||
UpdateSelection();
|
||||
UpdatePromptUI();
|
||||
}
|
||||
|
||||
UE_LOG(LogInteraction, Log, TEXT("OnAnimLockComplete: Pickup 完成,回到 Free"));
|
||||
}
|
||||
break;
|
||||
|
||||
case EInteractType::Operate:
|
||||
{
|
||||
if (Data.OperateSubType == EOperateSubType::Door)
|
||||
{
|
||||
// 直接回到 Free
|
||||
AChildHoodCharacter* Char = Cast<AChildHoodCharacter>(GetOwner());
|
||||
if (Char)
|
||||
{
|
||||
Char->SetInteracting(false);
|
||||
}
|
||||
State = EInteractionState::Free;
|
||||
Phase = EInteractPhase::None;
|
||||
CurrentInteractable = nullptr;
|
||||
|
||||
// 更新提示(门动词可能变化)
|
||||
UpdateSelection();
|
||||
UpdatePromptUI();
|
||||
|
||||
UE_LOG(LogInteraction, Log, TEXT("OnAnimLockComplete: Door 完成,回到 Free"));
|
||||
}
|
||||
else if (Data.OperateSubType == EOperateSubType::Search)
|
||||
{
|
||||
// 翻找结果判定:v0.1 必定有物品
|
||||
CurrentInteractable->Consume();
|
||||
OnItemFound.Broadcast(Data.ItemId, Data.DisplayName, FName(TEXT("杂物")));
|
||||
UE_LOG(LogInteraction, Log, TEXT("OnAnimLockComplete: Search 翻找完成,获得物品 '%s'"), *Data.DisplayName);
|
||||
|
||||
// 进入 Active 阶段等待玩家按 E/ESC 关闭
|
||||
Phase = EInteractPhase::Active;
|
||||
// 有物品时不显示文本底框(架构预留)
|
||||
}
|
||||
}
|
||||
break;
|
||||
|
||||
default:
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
// UI 方法(v0.1 用日志替代)
|
||||
// ============================================================================
|
||||
|
||||
void UInteractionManager::UpdateSelection()
|
||||
{
|
||||
// 排序后选中索引重置为 0(最近的)
|
||||
if (AActor* Owner = GetOwner())
|
||||
{
|
||||
FVector OwnerLoc = Owner->GetActorLocation();
|
||||
NearbyInteractables.Sort([OwnerLoc](const UInteractableComponent& A, const UInteractableComponent& B)
|
||||
{
|
||||
float DistA = FVector::DistSquared2D(OwnerLoc, A.GetWorldLocation());
|
||||
float DistB = FVector::DistSquared2D(OwnerLoc, B.GetWorldLocation());
|
||||
return DistA < DistB;
|
||||
});
|
||||
}
|
||||
SelectedIndex = 0;
|
||||
}
|
||||
|
||||
void UInteractionManager::UpdatePromptUI()
|
||||
{
|
||||
if (NearbyInteractables.Num() == 0 || !NearbyInteractables.IsValidIndex(SelectedIndex))
|
||||
{
|
||||
HidePrompt();
|
||||
return;
|
||||
}
|
||||
|
||||
UInteractableComponent* Selected = NearbyInteractables[SelectedIndex];
|
||||
if (!Selected)
|
||||
{
|
||||
HidePrompt();
|
||||
return;
|
||||
}
|
||||
|
||||
FString PromptText = Selected->GetPromptText();
|
||||
|
||||
if (PromptWidget)
|
||||
{
|
||||
PromptWidget->SetPromptText(PromptText);
|
||||
PromptWidget->Show();
|
||||
UpdatePromptScreenPosition(Selected);
|
||||
}
|
||||
|
||||
UE_LOG(LogInteraction, Verbose, TEXT("UpdatePromptUI: %s"), *PromptText);
|
||||
}
|
||||
|
||||
void UInteractionManager::HidePrompt()
|
||||
{
|
||||
if (PromptWidget)
|
||||
{
|
||||
PromptWidget->Hide();
|
||||
}
|
||||
}
|
||||
|
||||
void UInteractionManager::ShowNarrativeText(const FString& Text)
|
||||
{
|
||||
if (Text.IsEmpty())
|
||||
{
|
||||
UE_LOG(LogInteraction, Warning, TEXT("ShowNarrativeText: text is empty"));
|
||||
return;
|
||||
}
|
||||
|
||||
if (NarrativeWidget)
|
||||
{
|
||||
NarrativeWidget->SetNarrativeText(Text);
|
||||
NarrativeWidget->Show();
|
||||
}
|
||||
|
||||
UE_LOG(LogInteraction, Verbose, TEXT("ShowNarrativeText: %s"), *Text);
|
||||
}
|
||||
|
||||
void UInteractionManager::HideNarrativeText()
|
||||
{
|
||||
if (NarrativeWidget)
|
||||
{
|
||||
NarrativeWidget->Hide();
|
||||
}
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
// 摄像机控制
|
||||
// ============================================================================
|
||||
|
||||
void UInteractionManager::PushCamera(FVector Target, float Duration)
|
||||
{
|
||||
if (!PushCameraActor)
|
||||
{
|
||||
UE_LOG(LogInteraction, Warning, TEXT("PushCamera: PushCameraActor 为空"));
|
||||
return;
|
||||
}
|
||||
|
||||
// 计算朝向交互物的旋转
|
||||
FVector LookTarget = CurrentInteractable ? CurrentInteractable->GetWorldLocation() : Target;
|
||||
FRotator LookAtRot = (LookTarget - Target).Rotation();
|
||||
|
||||
PushCameraActor->SetActorHiddenInGame(false);
|
||||
PushCameraActor->SetActorLocationAndRotation(Target, LookAtRot);
|
||||
|
||||
// 切换 ViewTarget
|
||||
APlayerController* PC = GetWorld()->GetFirstPlayerController();
|
||||
if (PC)
|
||||
{
|
||||
PC->SetViewTargetWithBlend(PushCameraActor, Duration, VTBlend_EaseOut);
|
||||
UE_LOG(LogInteraction, Log, TEXT("PushCamera: 推镜到 %s, 时长=%.2f"), *Target.ToString(), Duration);
|
||||
}
|
||||
}
|
||||
|
||||
void UInteractionManager::ReturnCamera(float Duration)
|
||||
{
|
||||
AActor* Owner = GetOwner();
|
||||
if (!Owner)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
APlayerController* PC = GetWorld()->GetFirstPlayerController();
|
||||
if (PC)
|
||||
{
|
||||
// 回位到 Character
|
||||
PC->SetViewTargetWithBlend(Owner, Duration, VTBlend_EaseIn);
|
||||
UE_LOG(LogInteraction, Log, TEXT("ReturnCamera: 相机回位, 时长=%.2f"), Duration);
|
||||
}
|
||||
|
||||
// 隐藏推镜 Actor
|
||||
if (PushCameraActor)
|
||||
{
|
||||
PushCameraActor->SetActorHiddenInGame(true);
|
||||
}
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
// 推镜位置计算
|
||||
// ============================================================================
|
||||
|
||||
FVector UInteractionManager::CalculatePushPosition(UInteractableComponent* Interactable)
|
||||
{
|
||||
if (!Interactable)
|
||||
{
|
||||
return FVector::ZeroVector;
|
||||
}
|
||||
|
||||
const FInteractableData& Data = Interactable->GetInteractableData();
|
||||
FVector InteractPos = Interactable->GetWorldLocation();
|
||||
FVector CharPos = GetOwner() ? GetOwner()->GetActorLocation() : FVector::ZeroVector;
|
||||
|
||||
FVector Dir = (InteractPos - CharPos);
|
||||
Dir.Z = 0.0f;
|
||||
Dir.Normalize();
|
||||
|
||||
// 交互物前方(面向角色的一侧),推镜距离偏移
|
||||
FVector TargetPos = InteractPos - Dir * Data.CameraPushDistance;
|
||||
// 高度略低于交互物中心(微仰视)
|
||||
TargetPos.Z = InteractPos.Z * 0.8f;
|
||||
|
||||
return TargetPos;
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
// 叙事文本随机选取
|
||||
// ============================================================================
|
||||
|
||||
FString UInteractionManager::PickRandomNarrative(const TArray<FString>& Texts)
|
||||
{
|
||||
if (Texts.Num() == 0)
|
||||
{
|
||||
return TEXT("");
|
||||
}
|
||||
|
||||
if (Texts.Num() == 1)
|
||||
{
|
||||
LastNarrativeText = Texts[0];
|
||||
return Texts[0];
|
||||
}
|
||||
|
||||
FString Candidate;
|
||||
int32 Attempts = 0;
|
||||
do
|
||||
{
|
||||
Candidate = Texts[FMath::RandRange(0, Texts.Num() - 1)];
|
||||
Attempts++;
|
||||
} while (Candidate == LastNarrativeText && Attempts < 10);
|
||||
|
||||
LastNarrativeText = Candidate;
|
||||
return Candidate;
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
// Exit 阶段定时器回调
|
||||
// ============================================================================
|
||||
|
||||
void UInteractionManager::OnExitTimerComplete()
|
||||
{
|
||||
UE_LOG(LogInteraction, Log, TEXT("OnExitTimerComplete: Exit 阶段结束,回到 Free"));
|
||||
|
||||
// 通知 Character 解除交互状态
|
||||
AChildHoodCharacter* Char = Cast<AChildHoodCharacter>(GetOwner());
|
||||
if (Char)
|
||||
{
|
||||
Char->SetInteracting(false);
|
||||
}
|
||||
|
||||
// 回到 Free 状态
|
||||
State = EInteractionState::Free;
|
||||
Phase = EInteractPhase::None;
|
||||
CurrentInteractable = nullptr;
|
||||
|
||||
// 如果仍在检测范围内,重新显示提示
|
||||
if (NearbyInteractables.Num() > 0)
|
||||
{
|
||||
UpdateSelection();
|
||||
UpdatePromptUI();
|
||||
}
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
// 提示 UI 屏幕位置更新
|
||||
// ============================================================================
|
||||
|
||||
void UInteractionManager::UpdatePromptScreenPosition(UInteractableComponent* Interactable)
|
||||
{
|
||||
if (!Interactable || !PromptWidget) return;
|
||||
|
||||
APlayerController* PC = GetWorld()->GetFirstPlayerController();
|
||||
if (!PC) return;
|
||||
|
||||
// 交互物世界位置 + 高度偏移 → 屏幕坐标
|
||||
FVector WorldLoc = Interactable->GetWorldLocation() + FVector(0.f, 0.f, PromptHeightOffset);
|
||||
FVector2D ScreenPos;
|
||||
if (UGameplayStatics::ProjectWorldToScreen(PC, WorldLoc, ScreenPos, true))
|
||||
{
|
||||
PromptWidget->SetScreenPosition(ScreenPos);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,225 @@
|
||||
// ChildHood Project - 交互管理器核心组件
|
||||
// 对应技术方案: docs/technical/交互系统-技术方案.md 第3节(类设计)+ 第6节(行为规则实现)
|
||||
// 职责:交互全流程状态机、检测选择、类型分发、摄像机/转向/UI 控制
|
||||
|
||||
#pragma once
|
||||
|
||||
#include "CoreMinimal.h"
|
||||
#include "Components/ActorComponent.h"
|
||||
#include "InteractionTypes.h"
|
||||
#include "InteractionManager.generated.h"
|
||||
|
||||
class UInteractableComponent;
|
||||
class APushCameraActor;
|
||||
class AChildHoodCharacter;
|
||||
class UInteractionPromptWidget;
|
||||
class UNarrativeTextWidget;
|
||||
|
||||
/**
|
||||
* UInteractionManager
|
||||
*
|
||||
* 挂载在 AChildHoodCharacter 上的组件,负责交互全流程管理:
|
||||
* - 层级状态机驱动(Free / Interacting + 子阶段)
|
||||
* - 附近交互物检测列表排序与选中管理
|
||||
* - 四种交互类型分发(观察/拾取/操作/对话)
|
||||
* - 角色自动转向插值
|
||||
* - 摄像机推镜/回位控制
|
||||
* - UI 提示与文本显示控制(v0.1 先用日志)
|
||||
*/
|
||||
UCLASS(ClassGroup=(Interaction), meta=(BlueprintSpawnableComponent))
|
||||
class UInteractionManager : public UActorComponent
|
||||
{
|
||||
GENERATED_BODY()
|
||||
|
||||
public:
|
||||
|
||||
UInteractionManager();
|
||||
|
||||
// === 公开方法 ===
|
||||
|
||||
/** 发起交互(E键触发),前置检查通过后进入 Enter 阶段 */
|
||||
UFUNCTION(BlueprintCallable, Category = "Interaction")
|
||||
void BeginInteract();
|
||||
|
||||
/** 取消/结束交互(ESC/E键在Active阶段触发),AnimLock期间不可取消 */
|
||||
UFUNCTION(BlueprintCallable, Category = "Interaction")
|
||||
void CancelInteract();
|
||||
|
||||
/** 切换选中交互物(Tab/滚轮),Direction: +1下一个 / -1上一个 */
|
||||
UFUNCTION(BlueprintCallable, Category = "Interaction")
|
||||
void SwitchTarget(int32 Direction);
|
||||
|
||||
/** 注册交互物到检测列表(由 InteractableComponent 的碰撞回调触发) */
|
||||
UFUNCTION(BlueprintCallable, Category = "Interaction")
|
||||
void RegisterInteractable(UInteractableComponent* Interactable);
|
||||
|
||||
/** 从检测列表注销交互物(离开范围或消耗时触发) */
|
||||
UFUNCTION(BlueprintCallable, Category = "Interaction")
|
||||
void UnregisterInteractable(UInteractableComponent* Interactable);
|
||||
|
||||
// === 委托 ===
|
||||
|
||||
/** 物品拾取事件 — 通知物品系统(Pickup 类型 ExecuteAnimEvent 中广播) */
|
||||
UPROPERTY(BlueprintAssignable, Category = "Interaction|Events")
|
||||
FMLocalItemEvent OnItemPickedUp;
|
||||
|
||||
/** 物品获得事件 — 通知收集系统(Search 类型 OnAnimLockComplete 中广播) */
|
||||
UPROPERTY(BlueprintAssignable, Category = "Interaction|Events")
|
||||
FMLocalItemEvent OnItemFound;
|
||||
|
||||
// === 可调参数 ===
|
||||
|
||||
/** 角色转向时长(秒) */
|
||||
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "Interaction|Tuning")
|
||||
float TurnDuration = 0.2f;
|
||||
|
||||
/** 提示 UI 淡入时长(秒) */
|
||||
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "Interaction|Tuning")
|
||||
float PromptFadeInDuration = 0.2f;
|
||||
|
||||
/** 提示 UI 淡出时长(秒) */
|
||||
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "Interaction|Tuning")
|
||||
float PromptFadeOutDuration = 0.2f;
|
||||
|
||||
protected:
|
||||
|
||||
virtual void BeginPlay() override;
|
||||
virtual void TickComponent(float DeltaTime, ELevelTick TickType, FActorComponentTickFunction* ThisTickFunction) override;
|
||||
|
||||
private:
|
||||
|
||||
// === 状态机 ===
|
||||
|
||||
/** 交互系统顶层状态 */
|
||||
EInteractionState State = EInteractionState::Free;
|
||||
|
||||
/** Interacting 子阶段 */
|
||||
EInteractPhase Phase = EInteractPhase::None;
|
||||
|
||||
// === 检测与选择 ===
|
||||
|
||||
/** 当前附近的交互物列表,按水平距离排序 */
|
||||
UPROPERTY()
|
||||
TArray<UInteractableComponent*> NearbyInteractables;
|
||||
|
||||
/** 当前选中的交互物索引 */
|
||||
int32 SelectedIndex = 0;
|
||||
|
||||
/** 当前正在交互的交互物(交互过程中锁定) */
|
||||
UPROPERTY()
|
||||
UInteractableComponent* CurrentInteractable = nullptr;
|
||||
|
||||
// === 摄像机控制 ===
|
||||
|
||||
/** 推镜用临时摄像机 Actor(BeginPlay 中 Spawn) */
|
||||
UPROPERTY()
|
||||
TObjectPtr<APushCameraActor> PushCameraActor;
|
||||
|
||||
/** 推镜是否已发起(Enter阶段一次性标志) */
|
||||
bool bPushStarted = false;
|
||||
|
||||
// === 计时器 ===
|
||||
|
||||
/** 转向已用时间 */
|
||||
float TurnElapsed = 0.0f;
|
||||
|
||||
/** 推镜后等待已用时间 */
|
||||
float WaitElapsed = 0.0f;
|
||||
|
||||
/** 动画事件计时器(如60%时物品消失) */
|
||||
FTimerHandle AnimEventTimerHandle;
|
||||
|
||||
/** 动画结束计时器 */
|
||||
FTimerHandle AnimEndTimerHandle;
|
||||
|
||||
/** 退出阶段回位计时器 */
|
||||
FTimerHandle ExitTimerHandle;
|
||||
|
||||
/** 动画事件是否已触发 */
|
||||
bool bAnimEventFired = false;
|
||||
|
||||
// === UI 配置 ===
|
||||
|
||||
/** 提示 UI 蓝图类(需在编辑器中指定为 WBP_InteractionPrompt) */
|
||||
UPROPERTY(EditAnywhere, Category = "Interaction|UI")
|
||||
TSubclassOf<UInteractionPromptWidget> PromptWidgetClass;
|
||||
|
||||
/** 文本底框 UI 蓝图类(需在编辑器中指定为 WBP_NarrativeText) */
|
||||
UPROPERTY(EditAnywhere, Category = "Interaction|UI")
|
||||
TSubclassOf<UNarrativeTextWidget> NarrativeWidgetClass;
|
||||
|
||||
/** 提示 UI 高度偏移(交互物上方的世界空间 Z 偏移,cm) */
|
||||
UPROPERTY(EditAnywhere, Category = "Interaction|UI")
|
||||
float PromptHeightOffset = 80.0f;
|
||||
|
||||
// === UI 实例 ===
|
||||
|
||||
/** 交互提示 Widget 实例 */
|
||||
UPROPERTY()
|
||||
TObjectPtr<UInteractionPromptWidget> PromptWidget;
|
||||
|
||||
/** 文本底框 Widget 实例 */
|
||||
UPROPERTY()
|
||||
TObjectPtr<UNarrativeTextWidget> NarrativeWidget;
|
||||
|
||||
// === 文本选择 ===
|
||||
|
||||
/** 上次显示的叙事文本(用于不重复选取) */
|
||||
FString LastNarrativeText;
|
||||
|
||||
// === 内部方法 ===
|
||||
|
||||
/** 更新选中交互物(排序后 SelectedIndex = 0) */
|
||||
void UpdateSelection();
|
||||
|
||||
/** 更新提示 UI 内容和位置 */
|
||||
void UpdatePromptUI();
|
||||
|
||||
/** 隐藏提示 UI */
|
||||
void HidePrompt();
|
||||
|
||||
/** 更新提示 UI 的屏幕空间位置(跟随交互物世界位置投影) */
|
||||
void UpdatePromptScreenPosition(UInteractableComponent* Interactable);
|
||||
|
||||
/** Enter 阶段 Tick:转向插值 + 推镜 + 等待 */
|
||||
void TickEnterPhase(float DeltaTime);
|
||||
|
||||
/** AnimLock 阶段 Tick(v0.1 由计时器驱动,此处可为空) */
|
||||
void TickAnimLockPhase(float DeltaTime);
|
||||
|
||||
/** Exit 阶段 Tick(v0.1 由定时器驱动回 Free) */
|
||||
void TickExitPhase(float DeltaTime);
|
||||
|
||||
/** Enter 阶段完成后,根据交互类型分发到下一阶段 */
|
||||
void TransitionFromEnter();
|
||||
|
||||
/** 进入 AnimLock 阶段:播放蒙太奇或启动计时器 */
|
||||
void EnterAnimLockPhase();
|
||||
|
||||
/** 动画事件触发点回调(如拾取物消失、门状态切换) */
|
||||
void ExecuteAnimEvent();
|
||||
|
||||
/** 动画结束回调 */
|
||||
void OnAnimLockComplete();
|
||||
|
||||
/** 显示叙事文本(v0.1 用日志输出) */
|
||||
void ShowNarrativeText(const FString& Text);
|
||||
|
||||
/** 隐藏叙事文本(v0.1 用日志输出) */
|
||||
void HideNarrativeText();
|
||||
|
||||
/** 推镜:移动 PushCameraActor 并切换 ViewTarget */
|
||||
void PushCamera(FVector Target, float Duration);
|
||||
|
||||
/** 相机回位:切换回 Character 的 FollowCamera */
|
||||
void ReturnCamera(float Duration);
|
||||
|
||||
/** 计算推镜目标位置 */
|
||||
FVector CalculatePushPosition(UInteractableComponent* Interactable);
|
||||
|
||||
/** 随机选取叙事文本,排除上次 */
|
||||
FString PickRandomNarrative(const TArray<FString>& Texts);
|
||||
|
||||
/** Exit 阶段定时器回调:回到 Free 状态 */
|
||||
void OnExitTimerComplete();
|
||||
};
|
||||
@@ -0,0 +1,67 @@
|
||||
// ChildHood Project - 交互提示 UI 基类 实现
|
||||
|
||||
#include "Interaction/InteractionPromptWidget.h"
|
||||
#include "Components/TextBlock.h"
|
||||
|
||||
void UInteractionPromptWidget::NativeOnInitialized()
|
||||
{
|
||||
Super::NativeOnInitialized();
|
||||
|
||||
// 初始隐藏
|
||||
SetVisibility(ESlateVisibility::Hidden);
|
||||
}
|
||||
|
||||
void UInteractionPromptWidget::SetPromptText(const FString& Text)
|
||||
{
|
||||
if (PromptTextBlock)
|
||||
{
|
||||
PromptTextBlock->SetText(FText::FromString(Text));
|
||||
}
|
||||
}
|
||||
|
||||
void UInteractionPromptWidget::SetScreenPosition(const FVector2D& Position)
|
||||
{
|
||||
// 使用 RenderTranslation 偏移 Widget 位置
|
||||
// 蓝图中 CanvasPanel 的 Anchors 应设置为屏幕左上角
|
||||
// 此处直接设置 RenderTranslation 来移动位置
|
||||
SetRenderTranslation(Position);
|
||||
}
|
||||
|
||||
void UInteractionPromptWidget::Show()
|
||||
{
|
||||
if (bIsVisible) return;
|
||||
bIsVisible = true;
|
||||
|
||||
SetVisibility(ESlateVisibility::HitTestInvisible);
|
||||
|
||||
if (FadeInAnim)
|
||||
{
|
||||
PlayAnimation(FadeInAnim, 0.0f, 1, EUMGSequencePlayMode::Forward, 1.0f);
|
||||
}
|
||||
}
|
||||
|
||||
void UInteractionPromptWidget::Hide()
|
||||
{
|
||||
if (!bIsVisible) return;
|
||||
|
||||
if (FadeOutAnim)
|
||||
{
|
||||
PlayAnimation(FadeOutAnim, 0.0f, 1, EUMGSequencePlayMode::Forward, 1.0f);
|
||||
// 动画播完后隐藏(简单方案:直接设置定时器隐藏)
|
||||
// 动画时长由蓝图中的 FadeOutAnim 决定,这里用固定 0.2s
|
||||
FTimerHandle TempHandle;
|
||||
if (UWorld* World = GetWorld())
|
||||
{
|
||||
World->GetTimerManager().SetTimer(TempHandle, [this]()
|
||||
{
|
||||
bIsVisible = false;
|
||||
SetVisibility(ESlateVisibility::Hidden);
|
||||
}, 0.2f, false);
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
bIsVisible = false;
|
||||
SetVisibility(ESlateVisibility::Hidden);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,65 @@
|
||||
// ChildHood Project - 交互提示 UI 基类
|
||||
// 对应技术方案: docs/technical/交互系统-技术方案.md 第6节(提示UI显示/隐藏)
|
||||
// 职责:屏幕空间悬浮提示 "[E] 动作词 名称",跟随交互物位置
|
||||
|
||||
#pragma once
|
||||
|
||||
#include "CoreMinimal.h"
|
||||
#include "Blueprint/UserWidget.h"
|
||||
#include "InteractionPromptWidget.generated.h"
|
||||
|
||||
class UTextBlock;
|
||||
|
||||
/**
|
||||
* UInteractionPromptWidget
|
||||
*
|
||||
* 交互提示 UI 的 C++ 基类。蓝图子类(WBP_InteractionPrompt)继承此类,
|
||||
* 在 UMG 编辑器中布局可视组件,并确保组件名与 BindWidget 匹配。
|
||||
*
|
||||
* 绑定要求:
|
||||
* - TextBlock 名为 "PromptTextBlock" — 显示提示文字
|
||||
* - WidgetAnimation 名为 "FadeInAnim" — 淡入动画(0.2s)
|
||||
* - WidgetAnimation 名为 "FadeOutAnim" — 淡出动画(0.2s)
|
||||
*/
|
||||
UCLASS(Abstract, Blueprintable)
|
||||
class UInteractionPromptWidget : public UUserWidget
|
||||
{
|
||||
GENERATED_BODY()
|
||||
|
||||
public:
|
||||
|
||||
/** 设置提示文字内容 */
|
||||
UFUNCTION(BlueprintCallable, Category = "Interaction|Prompt")
|
||||
void SetPromptText(const FString& Text);
|
||||
|
||||
/** 设置屏幕空间位置(由 InteractionManager 每帧调用) */
|
||||
UFUNCTION(BlueprintCallable, Category = "Interaction|Prompt")
|
||||
void SetScreenPosition(const FVector2D& Position);
|
||||
|
||||
/** 显示提示(播放淡入动画) */
|
||||
UFUNCTION(BlueprintCallable, Category = "Interaction|Prompt")
|
||||
void Show();
|
||||
|
||||
/** 隐藏提示(播放淡出动画) */
|
||||
UFUNCTION(BlueprintCallable, Category = "Interaction|Prompt")
|
||||
void Hide();
|
||||
|
||||
protected:
|
||||
|
||||
/** 提示文字 TextBlock,蓝图子类必须有一个同名 TextBlock */
|
||||
UPROPERTY(meta = (BindWidget))
|
||||
UTextBlock* PromptTextBlock;
|
||||
|
||||
/** 淡入动画(0.2s Opacity 0→1),蓝图子类必须有同名 WidgetAnimation */
|
||||
UPROPERTY(meta = (BindWidgetAnim), Transient)
|
||||
UWidgetAnimation* FadeInAnim;
|
||||
|
||||
/** 淡出动画(0.2s Opacity 1→0),蓝图子类必须有同名 WidgetAnimation */
|
||||
UPROPERTY(meta = (BindWidgetAnim), Transient)
|
||||
UWidgetAnimation* FadeOutAnim;
|
||||
|
||||
/** 是否正在显示中 */
|
||||
bool bIsVisible = false;
|
||||
|
||||
virtual void NativeOnInitialized() override;
|
||||
};
|
||||
@@ -0,0 +1,178 @@
|
||||
// ChildHood Project - 交互系统数据类型定义
|
||||
// 对应技术方案: docs/technical/交互系统-技术方案.md 第5节(核心数据结构)+ 第12节(跨场景持久化)
|
||||
|
||||
#pragma once
|
||||
|
||||
#include "CoreMinimal.h"
|
||||
#include "InteractionTypes.generated.h"
|
||||
|
||||
// ============================================================================
|
||||
// 枚举
|
||||
// ============================================================================
|
||||
|
||||
/** 交互类型 */
|
||||
UENUM(BlueprintType)
|
||||
enum class EInteractType : uint8
|
||||
{
|
||||
Examine UMETA(DisplayName = "观察"),
|
||||
Pickup UMETA(DisplayName = "拾取"),
|
||||
Operate UMETA(DisplayName = "操作"),
|
||||
Talk UMETA(DisplayName = "对话")
|
||||
};
|
||||
|
||||
/** 操作子类型(仅 Operate 类型有效) */
|
||||
UENUM(BlueprintType)
|
||||
enum class EOperateSubType : uint8
|
||||
{
|
||||
Door UMETA(DisplayName = "门(开关切换)"),
|
||||
Search UMETA(DisplayName = "翻找")
|
||||
};
|
||||
|
||||
/** 交互系统顶层状态 */
|
||||
UENUM(BlueprintType)
|
||||
enum class EInteractionState : uint8
|
||||
{
|
||||
Free UMETA(DisplayName = "自由状态"),
|
||||
Interacting UMETA(DisplayName = "交互中"),
|
||||
SubSystem UMETA(DisplayName = "子系统(v0.1预留)"),
|
||||
Cutscene UMETA(DisplayName = "过场(v0.1预留)")
|
||||
};
|
||||
|
||||
/** Interacting 子阶段 */
|
||||
UENUM(BlueprintType)
|
||||
enum class EInteractPhase : uint8
|
||||
{
|
||||
None UMETA(DisplayName = "无"),
|
||||
Enter UMETA(DisplayName = "进入(转向+推镜)"),
|
||||
AnimLock UMETA(DisplayName = "动画锁定"),
|
||||
Active UMETA(DisplayName = "活跃(等待输入)"),
|
||||
Exit UMETA(DisplayName = "退出(回位)")
|
||||
};
|
||||
|
||||
/** 交互结束后动作 */
|
||||
UENUM(BlueprintType)
|
||||
enum class EPostAction : uint8
|
||||
{
|
||||
Return UMETA(DisplayName = "回到Free"),
|
||||
Minigame UMETA(DisplayName = "小游戏(v0.1预留)"),
|
||||
Dialogue UMETA(DisplayName = "对话(v0.1预留)"),
|
||||
SceneChange UMETA(DisplayName = "场景切换(v0.1预留)")
|
||||
};
|
||||
|
||||
// ============================================================================
|
||||
// 配置数据结构
|
||||
// ============================================================================
|
||||
|
||||
/** 可交互物配置数据 — 每个交互物实例独立配置 */
|
||||
USTRUCT(BlueprintType)
|
||||
struct FInteractableData
|
||||
{
|
||||
GENERATED_BODY()
|
||||
|
||||
// === 基本信息 ===
|
||||
|
||||
/** 唯一ID(如 "fridge_home"),用于持久化存储和物品系统对接 */
|
||||
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "Interact|Basic")
|
||||
FName ItemId;
|
||||
|
||||
/** 显示名称(如 "旧冰箱"),用于提示UI */
|
||||
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "Interact|Basic")
|
||||
FString DisplayName;
|
||||
|
||||
/** 交互类型 */
|
||||
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "Interact|Basic")
|
||||
EInteractType Type = EInteractType::Examine;
|
||||
|
||||
/** 操作子类型,仅 Type==Operate 时可见可编辑 */
|
||||
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "Interact|Basic",
|
||||
meta = (EditCondition = "Type == EInteractType::Operate", EditConditionHides))
|
||||
EOperateSubType OperateSubType = EOperateSubType::Door;
|
||||
|
||||
// === 触发 ===
|
||||
|
||||
/** 触发半径(cm),默认1.5m */
|
||||
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "Interact|Trigger",
|
||||
meta = (ClampMin = "50.0", ClampMax = "500.0"))
|
||||
float TriggerRadius = 150.0f;
|
||||
|
||||
/** 是否一次性消耗(消耗后不再可交互) */
|
||||
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "Interact|Trigger")
|
||||
bool bOneShot = false;
|
||||
|
||||
// === 提示文本 ===
|
||||
|
||||
/** 动作词(如 "查看"、"拾取"、"打开") */
|
||||
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "Interact|Prompt")
|
||||
FString InteractVerb;
|
||||
|
||||
/** 备选动词(如 "关上"),门打开时使用,仅 Operate+Door 时可见 */
|
||||
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "Interact|Prompt",
|
||||
meta = (EditCondition = "Type == EInteractType::Operate && OperateSubType == EOperateSubType::Door"))
|
||||
FString InteractVerbAlt;
|
||||
|
||||
// === 叙事/对话文本 ===
|
||||
|
||||
/** 文本列表,随机选取,不重复上次 */
|
||||
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "Interact|Text")
|
||||
TArray<FString> NarrativeTexts;
|
||||
|
||||
// === 摄像机推镜 ===
|
||||
|
||||
/** 是否使用摄像机推镜 */
|
||||
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "Interact|Camera")
|
||||
bool bUseCameraPush = false;
|
||||
|
||||
/** 推镜距离(cm),仅 bUseCameraPush 时可编辑 */
|
||||
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "Interact|Camera",
|
||||
meta = (EditCondition = "bUseCameraPush", ClampMin = "10.0", ClampMax = "300.0"))
|
||||
float CameraPushDistance = 80.0f;
|
||||
|
||||
/** 推镜过渡时长(秒),仅 bUseCameraPush 时可编辑 */
|
||||
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "Interact|Camera",
|
||||
meta = (EditCondition = "bUseCameraPush", ClampMin = "0.1", ClampMax = "2.0"))
|
||||
float CameraPushDuration = 0.5f;
|
||||
|
||||
/** 相机回位时长(秒),仅 bUseCameraPush 时可编辑 */
|
||||
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "Interact|Camera",
|
||||
meta = (EditCondition = "bUseCameraPush", ClampMin = "0.1", ClampMax = "2.0"))
|
||||
float CameraReturnDuration = 0.3f;
|
||||
|
||||
/** 推镜完成后到文本显示的等待时间(秒),仅 bUseCameraPush 时可编辑 */
|
||||
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "Interact|Camera",
|
||||
meta = (EditCondition = "bUseCameraPush", ClampMin = "0.0", ClampMax = "1.0"))
|
||||
float PushWaitDelay = 0.2f;
|
||||
|
||||
// === 动画 ===
|
||||
|
||||
/** 交互动画蒙太奇(可选,为空时用计时器模拟) */
|
||||
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "Interact|Anim")
|
||||
TObjectPtr<UAnimMontage> InteractMontage;
|
||||
|
||||
/** 无蒙太奇时的动画持续时间(秒) */
|
||||
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "Interact|Anim",
|
||||
meta = (ClampMin = "0.1", ClampMax = "5.0"))
|
||||
float AnimDuration = 1.0f;
|
||||
|
||||
/** 动画事件触发点(0-1比例),如0.6表示动画播放至60%时触发物品消失 */
|
||||
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "Interact|Anim",
|
||||
meta = (ClampMin = "0.0", ClampMax = "1.0"))
|
||||
float AnimEventTimepoint = 0.6f;
|
||||
|
||||
// === 结束动作 ===
|
||||
|
||||
/** 交互结束后的动作 */
|
||||
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "Interact|Post")
|
||||
EPostAction PostAction = EPostAction::Return;
|
||||
};
|
||||
|
||||
// ============================================================================
|
||||
// 委托
|
||||
// ============================================================================
|
||||
|
||||
/** 物品拾取/获得事件 — 通知物品系统和收集系统 */
|
||||
DECLARE_DYNAMIC_MULTICAST_DELEGATE_ThreeParams(
|
||||
FMLocalItemEvent,
|
||||
FName, ItemId,
|
||||
const FString&, DisplayName,
|
||||
const FName&, Category
|
||||
);
|
||||
@@ -0,0 +1,57 @@
|
||||
// ChildHood Project - 文本底框 UI 基类 实现
|
||||
|
||||
#include "Interaction/NarrativeTextWidget.h"
|
||||
#include "Components/TextBlock.h"
|
||||
|
||||
void UNarrativeTextWidget::NativeOnInitialized()
|
||||
{
|
||||
Super::NativeOnInitialized();
|
||||
|
||||
// 初始隐藏
|
||||
SetVisibility(ESlateVisibility::Hidden);
|
||||
}
|
||||
|
||||
void UNarrativeTextWidget::SetNarrativeText(const FString& Text)
|
||||
{
|
||||
if (NarrativeTextBlock)
|
||||
{
|
||||
NarrativeTextBlock->SetText(FText::FromString(Text));
|
||||
}
|
||||
}
|
||||
|
||||
void UNarrativeTextWidget::Show()
|
||||
{
|
||||
if (bIsVisible) return;
|
||||
bIsVisible = true;
|
||||
|
||||
SetVisibility(ESlateVisibility::HitTestInvisible);
|
||||
|
||||
if (FadeInAnim)
|
||||
{
|
||||
PlayAnimation(FadeInAnim, 0.0f, 1, EUMGSequencePlayMode::Forward, 1.0f);
|
||||
}
|
||||
}
|
||||
|
||||
void UNarrativeTextWidget::Hide()
|
||||
{
|
||||
if (!bIsVisible) return;
|
||||
|
||||
if (FadeOutAnim)
|
||||
{
|
||||
PlayAnimation(FadeOutAnim, 0.0f, 1, EUMGSequencePlayMode::Forward, 1.0f);
|
||||
FTimerHandle TempHandle;
|
||||
if (UWorld* World = GetWorld())
|
||||
{
|
||||
World->GetTimerManager().SetTimer(TempHandle, [this]()
|
||||
{
|
||||
bIsVisible = false;
|
||||
SetVisibility(ESlateVisibility::Hidden);
|
||||
}, 0.2f, false);
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
bIsVisible = false;
|
||||
SetVisibility(ESlateVisibility::Hidden);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,66 @@
|
||||
// ChildHood Project - 文本底框 UI 基类
|
||||
// 对应技术方案: docs/technical/交互系统-技术方案.md 第6节(通用文本显示UI)
|
||||
// 职责:半透明底框 + 一句话叙事/对话文本,带淡入淡出
|
||||
|
||||
#pragma once
|
||||
|
||||
#include "CoreMinimal.h"
|
||||
#include "Blueprint/UserWidget.h"
|
||||
#include "NarrativeTextWidget.generated.h"
|
||||
|
||||
class UTextBlock;
|
||||
|
||||
/**
|
||||
* UNarrativeTextWidget
|
||||
*
|
||||
* 文本底框 UI 的 C++ 基类。蓝图子类(WBP_NarrativeText)继承此类,
|
||||
* 在 UMG 编辑器中布局可视组件,并确保组件名与 BindWidget 匹配。
|
||||
*
|
||||
* 绑定要求:
|
||||
* - TextBlock 名为 "NarrativeTextBlock" — 显示叙事/对话文字
|
||||
* - WidgetAnimation 名为 "FadeInAnim" — 淡入动画(0.2s)
|
||||
* - WidgetAnimation 名为 "FadeOutAnim" — 淡出动画(0.2s)
|
||||
*
|
||||
* 布局要求:
|
||||
* - Anchors: Horizontal Center, Vertical ~0.6(屏幕中心偏下)
|
||||
* - Border: 半透明黑色背景(~60%),圆角,SizeToContent
|
||||
* - TextBlock: 白色文字,居中,自动换行
|
||||
*/
|
||||
UCLASS(Abstract, Blueprintable)
|
||||
class UNarrativeTextWidget : public UUserWidget
|
||||
{
|
||||
GENERATED_BODY()
|
||||
|
||||
public:
|
||||
|
||||
/** 设置叙事文本内容 */
|
||||
UFUNCTION(BlueprintCallable, Category = "Interaction|Narrative")
|
||||
void SetNarrativeText(const FString& Text);
|
||||
|
||||
/** 显示文本(播放淡入动画) */
|
||||
UFUNCTION(BlueprintCallable, Category = "Interaction|Narrative")
|
||||
void Show();
|
||||
|
||||
/** 隐藏文本(播放淡出动画) */
|
||||
UFUNCTION(BlueprintCallable, Category = "Interaction|Narrative")
|
||||
void Hide();
|
||||
|
||||
protected:
|
||||
|
||||
/** 叙事文字 TextBlock,蓝图子类必须有一个同名 TextBlock */
|
||||
UPROPERTY(meta = (BindWidget))
|
||||
UTextBlock* NarrativeTextBlock;
|
||||
|
||||
/** 淡入动画(0.2s),蓝图子类必须有同名 WidgetAnimation */
|
||||
UPROPERTY(meta = (BindWidgetAnim), Transient)
|
||||
UWidgetAnimation* FadeInAnim;
|
||||
|
||||
/** 淡出动画(0.2s),蓝图子类必须有同名 WidgetAnimation */
|
||||
UPROPERTY(meta = (BindWidgetAnim), Transient)
|
||||
UWidgetAnimation* FadeOutAnim;
|
||||
|
||||
/** 是否正在显示中 */
|
||||
bool bIsVisible = false;
|
||||
|
||||
virtual void NativeOnInitialized() override;
|
||||
};
|
||||
@@ -0,0 +1,19 @@
|
||||
// ChildHood Project - 推镜用临时摄像机 实现
|
||||
|
||||
#include "Interaction/PushCameraActor.h"
|
||||
|
||||
#include "Camera/CameraComponent.h"
|
||||
|
||||
// ============================================================================
|
||||
// 构造函数
|
||||
// ============================================================================
|
||||
|
||||
APushCameraActor::APushCameraActor()
|
||||
{
|
||||
PrimaryActorTick.bCanEverTick = false;
|
||||
|
||||
// 创建摄像机组件
|
||||
CameraComp = CreateDefaultSubobject<UCameraComponent>(TEXT("CameraComp"));
|
||||
// 不需要根组件的碰撞
|
||||
SetRootComponent(CameraComp);
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
// ChildHood Project - 推镜用临时摄像机
|
||||
// 对应技术方案: docs/technical/交互系统-技术方案.md 第3节(类设计)
|
||||
// 职责:极简 Actor,仅持有一个 UCameraComponent,供 SetViewTargetWithBlend 使用
|
||||
|
||||
#pragma once
|
||||
|
||||
#include "CoreMinimal.h"
|
||||
#include "GameFramework/Actor.h"
|
||||
#include "PushCameraActor.generated.h"
|
||||
|
||||
class UCameraComponent;
|
||||
|
||||
/**
|
||||
* APushCameraActor
|
||||
*
|
||||
* 交互系统推镜时使用的临时摄像机 Actor。
|
||||
* 由 InteractionManager 在 BeginPlay 中 Spawn,随 Character 生命周期。
|
||||
* InteractionManager 在推镜时设置其 Location/Rotation,
|
||||
* 然后通过 PlayerController::SetViewTargetWithBlend 切换 ViewTarget。
|
||||
*/
|
||||
UCLASS()
|
||||
class APushCameraActor : public AActor
|
||||
{
|
||||
GENERATED_BODY()
|
||||
|
||||
public:
|
||||
|
||||
APushCameraActor();
|
||||
|
||||
/** 推镜摄像机组件 */
|
||||
UPROPERTY(VisibleAnywhere, BlueprintReadOnly, Category = "Components")
|
||||
UCameraComponent* CameraComp;
|
||||
};
|
||||
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
+767
-784
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,224 @@
|
||||
# 交互系统 · 拾取流程时序图(v1.0 Effect 驱动版)
|
||||
|
||||
## 场景
|
||||
|
||||
玩家进入地上某个交互物的交互范围,按 E 交互后,人物做动作,交互物消失,背包加一个新物品,UI 显示捡到一个物品。
|
||||
|
||||
## 架构层级
|
||||
|
||||
| 层级 | 实体 | 所在位置 |
|
||||
|------|------|---------|
|
||||
| **Logic** | `FInteractionManager` | ASystemDriver 持有 (普通C++, 纯事件驱动, 缓存 Presentation 数据) |
|
||||
| **Logic** | `FEffectManager` | ASystemDriver 持有 (普通C++, Driver 提供Tick) |
|
||||
| **World** | `ASystemDriver` | AInfo 全局唯一 (持有所有Manager, 显式控制创建/Tick顺序) |
|
||||
| **Data** | `UInteractableComponent` | 关卡实例 |
|
||||
| **Data** | `UPersistenceSubsystem` | GameInstanceSubsystem |
|
||||
| **Data** | `BackpackSystem` | GameInstance |
|
||||
| **Presentation** | `UInteractionPromptComponent` | Character |
|
||||
|
||||
## 数据流规则
|
||||
|
||||
- 表现层直接读数据层(Manager state / Component data / Backpack data)
|
||||
- 逻辑事件仅在 A 影响 B 时使用(如 Consume Action → Persistence 写入)
|
||||
- 两个表现实体之间不直接访问
|
||||
|
||||
---
|
||||
|
||||
## Effect 配置
|
||||
|
||||
```
|
||||
Effect: "拾取地面物品"
|
||||
TotalDuration: 1.5s, Cancellable: false
|
||||
|
||||
TriggerTime | Action | 说明
|
||||
----------- | --------------------- | ----
|
||||
0.0s | TurnToTarget | TurnDuration=0.2,转向交互物
|
||||
0.0s | PlayMontage | Montage=AM_Pickup,弯腰拾取动画
|
||||
0.6s | Consume | 标记消耗,禁用检测球
|
||||
0.6s | HideActor | 隐藏交互物 Actor
|
||||
0.6s | AddToBackpack | 物品进背包 + 持久化
|
||||
1.0s | ShowPickupNotification| 显示 "捡到了 [旧橡皮]!"
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 时序图
|
||||
|
||||
```mermaid
|
||||
sequenceDiagram
|
||||
autonumber
|
||||
|
||||
actor Player as 玩家
|
||||
participant Char as AChildHoodCharacter
|
||||
participant Mgr as FInteractionManager<br/>(普通C++ · ASystemDriver持有)
|
||||
participant Comp as UInteractableComponent<br/>(Data · 关卡实例)
|
||||
participant Actor as AInteractableActor
|
||||
participant EFM as FEffectManager<br/>(普通C++ · ASystemDriver持有)
|
||||
participant Persist as UPersistenceSubsystem<br/>(Data · GameInstance)
|
||||
participant Bag as BackpackSystem
|
||||
participant Pres as UInteractionPromptComponent<br/>(Presentation · Character)
|
||||
participant Driver as ASystemDriver<br/>(AInfo · 持有所有Manager)
|
||||
|
||||
rect rgb(230, 245, 255)
|
||||
Note over Player,Driver: ═══ Phase 0 · 进入检测范围 ═══
|
||||
Player->>Char: WASD 移动进入 TriggerRadius
|
||||
Comp->>Mgr: DetectionSphere OnOverlapBegin<br/>ASystemDriver::Get(World)->GetInteractionManager().RegisterInteractable(this)
|
||||
Mgr->>Mgr: NearbyInteractables.Add(Comp)<br/>Sort by Dist2D → SelectedIndex = 0
|
||||
Mgr->>Mgr: RefreshCachedSelection()<br/>缓存 PromptText + WorldPosition
|
||||
end
|
||||
|
||||
rect rgb(255, 250, 230)
|
||||
Note over Player,Driver: ═══ Phase 1 · Prompt 显示(Pres 每帧读 Manager 缓存)═══
|
||||
loop 每帧 Pres TickComponent
|
||||
Pres->>Mgr: GetState() → Free
|
||||
Pres->>Mgr: HasSelection() → true
|
||||
Pres->>Mgr: GetSelectedPromptText() → "[E] 拾取 旧橡皮"
|
||||
Pres->>Mgr: GetSelectedWorldPosition() → FVector
|
||||
Pres->>Pres: PromptWidget.SetText + SetScreenPosition
|
||||
end
|
||||
Note right of Pres: Pres 不碰 Component<br/>只读 Manager 缓存
|
||||
end
|
||||
|
||||
rect rgb(230, 255, 230)
|
||||
Note over Player,Driver: ═══ Phase 2 · 按 E,Character 通过 Driver 协调两个 Manager ═══
|
||||
Player->>Char: 按 E (IA_Interact)
|
||||
Char->>Mgr: Driver->GetInteractionManager().BeginInteract() → 返回 Comp
|
||||
Mgr->>Mgr: State = Executing, CurrentInteractable = Comp
|
||||
Char->>Char: SetInteracting(true) → 屏蔽移动
|
||||
|
||||
Char->>EFM: Driver->GetEffectManager().PlayEffect(Comp.Data.InteractEffect, Context)<br/>Context = {Char, Comp, Actor}
|
||||
Note right of EFM: Effect "拾取地面物品"<br/>T=0.0 TurnToTarget + PlayMontage<br/>T=0.6 Consume+Hide+Backpack<br/>T=1.0 PickupNotification<br/>Total=1.5s
|
||||
end
|
||||
|
||||
rect rgb(255, 240, 245)
|
||||
Note over Player,Driver: ═══ Phase 3 · Presentation 检测状态变化 ═══
|
||||
Pres->>Mgr: Tick: GetState() → Executing (变化!)
|
||||
Pres->>Pres: PromptWidget.Hide()
|
||||
end
|
||||
|
||||
rect rgb(240, 240, 255)
|
||||
Note over Player,Driver: ═══ Phase 4 · Effect 执行(ASystemDriver Tick → EffectManager)═══
|
||||
|
||||
Note over Driver: T=0.0: TurnToTarget + PlayMontage
|
||||
Driver->>EFM: Driver::Tick → EffectManager.Update(DeltaTime)
|
||||
EFM->>EFM: ElapsedTime=0.0 → 触发 TurnToTarget Action
|
||||
EFM->>Char: RInterpTo 转向 Comp(持续帧)
|
||||
EFM->>EFM: 触发 PlayMontage Action
|
||||
EFM->>Char: GetMesh()->GetAnimInstance()->Montage_Play(AM_Pickup)
|
||||
Note right of Char: 播放弯腰拾取动画
|
||||
|
||||
Note over Driver: T=0.0→0.6: 持续转向 + 动画播放
|
||||
loop 每帧 Driver Tick
|
||||
Driver->>EFM: Tick → Update(DeltaTime)
|
||||
EFM->>EFM: ElapsedTime += DeltaTime
|
||||
EFM->>Char: TurnToTarget: RInterpTo 插值
|
||||
end
|
||||
|
||||
Note over Driver: T=0.6: Consume + HideActor + AddToBackpack
|
||||
Driver->>EFM: Tick → Update → ElapsedTime=0.6 触发
|
||||
EFM->>Comp: Consume() — 数据变更
|
||||
Comp-->>Comp: bIsConsumed=true<br/>DetectionSphere → NoCollision
|
||||
Note right of Comp: 禁用碰撞同步触发 EndOverlap<br/>→ UnregisterInteractable<br/>Manager 标记延迟清理
|
||||
|
||||
EFM->>Persist: MarkItemCollected("rubber_01")
|
||||
Persist-->>Persist: CollectedItemIDs.Add("rubber_01")
|
||||
|
||||
EFM->>Actor: SetActorHiddenInGame(true)
|
||||
|
||||
EFM->>Bag: AddItem("rubber_01", "旧橡皮")
|
||||
Bag-->>Bag: Items.Add({Id:"rubber_01", Name:"旧橡皮"})
|
||||
|
||||
Pres->>Comp: Tick: IsConsumed() → true (变化!)
|
||||
Pres->>Actor: SetActorHiddenInGame(true)
|
||||
|
||||
Note over Driver: T=1.0: ShowPickupNotification
|
||||
Driver->>EFM: Tick → Update → ElapsedTime=1.0 触发
|
||||
EFM->>Pres: 显示拾取通知 "捡到了 [旧橡皮]!"
|
||||
end
|
||||
|
||||
rect rgb(230, 255, 255)
|
||||
Note over Player,Driver: ═══ Phase 5 · Effect 完成,回到 Free ═══
|
||||
Driver->>EFM: Tick → Update → ElapsedTime >= TotalDuration(1.5s)
|
||||
EFM->>EFM: FinishEffect()
|
||||
EFM->>Mgr: OnEffectComplete 回调
|
||||
Mgr->>Mgr: State = Free, CurrentInteractable = nullptr
|
||||
Mgr->>Char: SetInteracting(false) → 恢复移动
|
||||
|
||||
Pres->>Mgr: Tick: GetState() → Free (变化!)
|
||||
Pres->>Mgr: GetSelectedInteractable() → null (已注销)
|
||||
Note over Pres: 无其他交互物在范围,不显示 Prompt
|
||||
|
||||
Player->>Char: WASD 继续移动
|
||||
end
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 关键数据流说明
|
||||
|
||||
### 表现层读数据(只读 Manager 缓存,不碰 Component)
|
||||
|
||||
| 读取时机 | PromptComponent 读谁 | 读什么 |
|
||||
|----------|---------------------|--------|
|
||||
| 每帧 Tick | Manager | `GetState()` |
|
||||
| Free 状态 | Manager | `HasSelection()` |
|
||||
| Free 状态 | Manager | `GetSelectedPromptText()` |
|
||||
| Free 状态 | Manager | `GetSelectedWorldPosition()` |
|
||||
|
||||
### Manager 缓存更新(选择变化时从 Component 读一次)
|
||||
|
||||
| 触发时机 | Manager 方法 | 缓存内容 |
|
||||
|----------|-------------|---------|
|
||||
| RegisterInteractable | RefreshCachedSelection() | PromptText + WorldPosition |
|
||||
| UnregisterInteractable | RefreshCachedSelection() | PromptText + WorldPosition |
|
||||
| SwitchTarget | RefreshCachedSelection() | PromptText + WorldPosition |
|
||||
|
||||
### Effect 内 Action 执行(直接操作)
|
||||
|
||||
| Action | 操作对象 | 说明 |
|
||||
|--------|---------|------|
|
||||
| TurnToTarget | Char->SetActorRotation | RInterpTo 跨帧插值 |
|
||||
| PlayMontage | Char->GetMesh()->GetAnimInstance() | 播放蒙太奇 |
|
||||
| Consume | Component->Consume() | 标记消耗+禁用检测 |
|
||||
| HideActor | Actor->SetActorHiddenInGame(true) | 隐藏 |
|
||||
| AddToBackpack | PersistenceSubsystem + BackpackSystem | 写入持久层+背包 |
|
||||
| ShowPickupNotification | PromptComponent / Widget | 显示通知 |
|
||||
|
||||
### 逻辑事件(仅 A 影响 B)
|
||||
|
||||
| 事件 | 触发者 | 订阅者 |
|
||||
|------|--------|--------|
|
||||
| OnItemConsumed | Manager(由 Consume Action 触发) | PersistenceSubsystem |
|
||||
| OnDoorToggled | Manager(由 ToggleDoor Action 触发) | PersistenceSubsystem + DoorComponent |
|
||||
|
||||
---
|
||||
|
||||
## 注意事项
|
||||
|
||||
### EndOverlap 时序问题
|
||||
|
||||
Phase 4 中 `Consume()` 禁用 DetectionSphere 会**同步触发** `EndOverlap`,进而调用 `Manager->UnregisterInteractable()`。此时 Manager 处于 Executing 状态且 Effect 仍在使用 CurrentInteractable。
|
||||
|
||||
**解决方案**:Manager 的 `UnregisterInteractable` 中,当 `State == Executing` 且移除的正是 `CurrentInteractable` 时,仅从 NearbyInteractables 列表移除,**不清除 CurrentInteractable 引用**,等 Effect 完成回调中统一清理。
|
||||
|
||||
### ASystemDriver 生命周期
|
||||
|
||||
- `ASystemDriver` 是 AInfo 全局唯一,持有所有 World 级 Manager(普通 C++ 对象)
|
||||
- 关卡加载完成 → `GameInstance` Spawn `ASystemDriver`
|
||||
- `Driver::BeginPlay` 显式创建 `FInteractionManager` + `FEffectManager`,控制顺序
|
||||
- `Driver::BeginPlay` 中用 `TFunction` 连线 `EffectManager.OnEffectComplete → Manager.OnInteractionFinished`
|
||||
- `Driver::Tick` 显式调用 `EffectManager.Update(Delta)`,控制 Tick 顺序
|
||||
- 关卡卸载 → World 销毁 → Driver 自动销毁 → Manager 随 Driver 析构
|
||||
- 新关卡加载 → 重新 Spawn + 创建
|
||||
|
||||
### 系统协调关系
|
||||
|
||||
- `FInteractionManager` 和 `FEffectManager` 是普通 C++ 类,由 `ASystemDriver` 持有
|
||||
- `AChildHoodCharacter` 输入回调通过 `ASystemDriver::Get(World)` 访问两个 Manager
|
||||
- `Driver::BeginPlay` 中通过 `TFunction<void()>` 连接 EffectManager 完成回调到 Manager
|
||||
- `FInteractionManager` 纯事件驱动,无 Tick/Update
|
||||
- `UChildHoodGameInstance` 不持有任何交互系统对象,仅 `UPersistenceSubsystem` 跨 World 存活
|
||||
|
||||
### TurnToTarget 跨帧插值
|
||||
|
||||
TurnToTarget Action 不是瞬时完成的。EffectManager 在 Update 中维护 `FTurnState`(起始旋转、目标旋转、已用时间),每帧调用 `FMath::RInterpTo` 直到转向完成。多个 Action 可以并行执行。
|
||||
+162
-17
@@ -2,8 +2,8 @@
|
||||
|
||||
> 任务ID: P-009
|
||||
> 对应执行案: `docs/design/收集系统-执行案.md` (v0.1.1)
|
||||
> 关联系统: 物品系统(上游单向接收)、交互系统(间接,通过物品系统委托)
|
||||
> 日期: 2026-06-07
|
||||
> 关联系统: 物品系统(上游单向接收)、交互系统(间接,通过物品系统委托)、GameInstance 持久化层
|
||||
> 日期: 2026-06-07(2026-06-11 更新:加入多场景持久化架构)
|
||||
|
||||
---
|
||||
|
||||
@@ -15,6 +15,16 @@
|
||||
**预估工期**:2-3 天
|
||||
**新增/修改代码量**:约 250-350 行 C++ + 3 个 UMG 蓝图
|
||||
|
||||
### 跨场景持久化架构
|
||||
|
||||
> 收集进度是玩家核心持久数据。当前设计中 `UCollectionManager` 将「行为控制」(UI、通知、动画)和「持久数据」(CollectedIDs、Progress)混在同一组件,随 Character 销毁而丢失。需要通过数据层分离解决:
|
||||
|
||||
- **持久数据层**:收集状态(CollectedIDs、Progress、bIsComplete)存储在 `UChildHoodGameInstance` 中(跨关卡存活)
|
||||
- **行为层**:`UCollectionManager` 仅负责运行时 UI 控制和委托监听,BeginPlay 时从 GameInstance 恢复状态
|
||||
- **交互物恢复**:场景中的已收集物品由交互系统通过 `InteractableComponent::RestorePersistentState()` 处理(见交互系统技术方案第 12 节)
|
||||
|
||||
v0.1 为单场景原型,此架构以接口预留形式存在,不影响当前功能。详见 [第 12 节:跨场景持久化设计](#12-跨场景持久化设计)。
|
||||
|
||||
---
|
||||
|
||||
## 1. 需求功能点罗列
|
||||
@@ -123,6 +133,17 @@ classDiagram
|
||||
-CheckCompletion() void
|
||||
-ShowCompletionPrompt() void
|
||||
-UpdateProgressUI() void
|
||||
-LoadStateFromGameInstance() void
|
||||
-SaveStateToGameInstance() void
|
||||
}
|
||||
|
||||
class UChildHoodGameInstance {
|
||||
-TSet~FName~ CollectedItemIDs
|
||||
-int32 CollectionProgress
|
||||
-bool bCollectionComplete
|
||||
+GetCollectionState(TSet_FName_&, int32&, bool&) void
|
||||
+SetCollectionState(TSet_FName_&, int32, bool) void
|
||||
+ResetAll() void
|
||||
}
|
||||
|
||||
class UCollectionNotifWidget {
|
||||
@@ -175,6 +196,7 @@ classDiagram
|
||||
|
||||
AChildHoodCharacter *-- UCollectionManager : 组合
|
||||
UCollectionManager --> UInteractionManager : 关联(绑定委托)
|
||||
UCollectionManager ..> UChildHoodGameInstance : 读取/写入持久状态
|
||||
UCollectionManager o-- UCollectionNotifWidget : 聚合(管理生命周期)
|
||||
UCollectionManager o-- UCollectionProgressWidget : 聚合(管理生命周期)
|
||||
UCollectionManager ..> UCollectionCompleteWidget : 按需创建
|
||||
@@ -188,7 +210,7 @@ classDiagram
|
||||
| 组合 `*--` | 生命周期绑定 | Character 持有 CollectionManager;CollectionManager 内含 Config |
|
||||
| 聚合 `o--` | 引用但非拥有 | CollectionManager 管理通知/进度 Widget 的创建和销毁 |
|
||||
| 关联 `-->` | 持久引用 | CollectionManager 绑定 InteractionManager 的委托 |
|
||||
| 依赖 `..>` | 临时使用 | CollectionManager 按需创建完成提示 Widget |
|
||||
| 依赖 `..>` | 临时使用 | CollectionManager 从 GameInstance 读取/写入持久状态;按需创建完成提示 Widget |
|
||||
|
||||
### 新增类
|
||||
|
||||
@@ -489,6 +511,8 @@ void UCollectionManager::ProcessNewCollection(FName ItemId)
|
||||
// 步骤 3: 记录
|
||||
CollectedIDs.Add(ItemId);
|
||||
Progress = CollectedIDs.Num(); // 用 Set 大小作为权威进度值,避免状态不一致
|
||||
// 持久化到 GameInstance
|
||||
SaveStateToGameInstance();
|
||||
```
|
||||
|
||||
---
|
||||
@@ -519,6 +543,7 @@ void UCollectionManager::ProcessNewCollection(FName ItemId)
|
||||
if (Progress >= Config.TotalCount && !bIsComplete)
|
||||
{
|
||||
bIsComplete = true;
|
||||
SaveStateToGameInstance(); // 持久化完成状态
|
||||
CheckCompletion(); // 触发完成表现
|
||||
}
|
||||
}
|
||||
@@ -637,10 +662,8 @@ void UCollectionManager::BeginPlay()
|
||||
{
|
||||
Super::BeginPlay();
|
||||
|
||||
// 初始化状态
|
||||
Progress = 0;
|
||||
CollectedIDs.Empty();
|
||||
bIsComplete = false;
|
||||
// 从 GameInstance 恢复持久状态(v0.1 单场景等效于空数据初始化)
|
||||
LoadStateFromGameInstance();
|
||||
|
||||
// 创建进度 UI
|
||||
if (ProgressWidgetClass)
|
||||
@@ -652,7 +675,12 @@ void UCollectionManager::BeginPlay()
|
||||
if (ProgressWidget)
|
||||
{
|
||||
ProgressWidget->AddToViewport(5);
|
||||
ProgressWidget->UpdateProgress(0, Config.TotalCount);
|
||||
ProgressWidget->UpdateProgress(Progress, Config.TotalCount);
|
||||
// 已完成时恢复完成样式
|
||||
if (bIsComplete)
|
||||
{
|
||||
ProgressWidget->SetCompleteStyle();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -772,20 +800,34 @@ void UCollectionManager::ShowCompletionPrompt()
|
||||
|
||||
#### 重启状态处理
|
||||
|
||||
**实现**:v0.1 无持久化。CollectionManager::BeginPlay() 中完全重置:
|
||||
**实现**:收集状态通过 `UChildHoodGameInstance` 跨场景持久化。CollectionManager::BeginPlay() 中从 GameInstance 恢复:
|
||||
|
||||
```cpp
|
||||
void UCollectionManager::BeginPlay()
|
||||
void UCollectionManager::LoadStateFromGameInstance()
|
||||
{
|
||||
Super::BeginPlay();
|
||||
Progress = 0;
|
||||
CollectedIDs.Empty();
|
||||
bIsComplete = false;
|
||||
// ... 创建 UI、绑定委托
|
||||
if (UChildHoodGameInstance* GI = GetWorld()->GetGameInstance<UChildHoodGameInstance>())
|
||||
{
|
||||
GI->GetCollectionState(CollectedIDs, Progress, bIsComplete);
|
||||
}
|
||||
else
|
||||
{
|
||||
// 回退:无 GameInstance 时初始化为空(编辑器预览等场景)
|
||||
Progress = 0;
|
||||
CollectedIDs.Empty();
|
||||
bIsComplete = false;
|
||||
}
|
||||
}
|
||||
|
||||
void UCollectionManager::SaveStateToGameInstance()
|
||||
{
|
||||
if (UChildHoodGameInstance* GI = GetWorld()->GetGameInstance<UChildHoodGameInstance>())
|
||||
{
|
||||
GI->SetCollectionState(CollectedIDs, Progress, bIsComplete);
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
重启后进度 UI 恢复显示 `📦 杂物 0/10`。
|
||||
v0.1 单场景下:GameInstance 以空数据初始化,等效于 `📦 杂物 0/10`。场景内正常收集后状态写入 GameInstance,若通过 Seamless Travel 切换关卡则自动恢复。非无缝跳转(OpenLevel)时 GameInstance 仍存活,新场景的 CollectionManager 可读取之前的数据。
|
||||
|
||||
#### 收集通知与拾取通知时序
|
||||
|
||||
@@ -819,6 +861,7 @@ void UCollectionManager::BeginPlay()
|
||||
### 注意事项
|
||||
|
||||
1. **委托绑定时机**:CollectionManager 在 BeginPlay() 中通过 `GetOwner()->GetComponentByClass<UInteractionManager>()` 获取引用并绑定。需确保 InteractionManager 已初始化。若为 nullptr 则在 Tick 中延迟绑定(最多重试 N 帧后报错)。
|
||||
2. **持久化读写时机**:`SaveStateToGameInstance()` 在每次 ProcessNewCollection 记录后和完成判定后调用,保证 GameInstance 中的数据始终最新。`LoadStateFromGameInstance()` 仅在 BeginPlay 中调用一次。
|
||||
2. **v0.1 无拾取通知 UI**:执行文档中拾取通知由物品系统负责,但 v0.1 物品系统仅为委托层(InteractionManager 上的委托)。收集通知的 0.3s 延迟仍按设计实现(为拾取通知预留时间窗口),即使拾取通知 UI 暂未实现。
|
||||
3. **通知移除回调**:UCollectionNotifWidget 淡出完成后需通知 CollectionManager 从 ActiveNotifications 中移除自身引用。使用委托或弱引用回调实现,避免循环引用。
|
||||
4. **FName 作为 ID**:收集系统使用 FName(ItemId)作为去重键,与 InteractionManager 委托广播的 ItemId 类型一致。
|
||||
@@ -847,14 +890,33 @@ InteractionManager (ExecuteAnimEvent)
|
||||
├─ 查品类 (Category == TrackedCategory?) → 不匹配则忽略
|
||||
├─ 查重复 (CollectedIDs.Contains?) → 已存在则忽略
|
||||
├─ 记录 (CollectedIDs.Add + Progress = Num())
|
||||
├─ SaveStateToGameInstance() → UChildHoodGameInstance (持久化)
|
||||
├─ UpdateProgressUI() → WBP_CollectionProgress (文本 + 弹性动画)
|
||||
├─ SetTimer(NotifDelay) → ShowCollectionNotification() → WBP_CollectionNotification
|
||||
└─ 完成判定 (Progress >= TotalCount)
|
||||
→ bIsComplete = true
|
||||
→ SaveStateToGameInstance() (持久化完成状态)
|
||||
→ SetCompleteStyle() → WBP_CollectionProgress (金色)
|
||||
→ SetTimer(TotalDelay) → ShowCompletionPrompt() → WBP_CollectionComplete
|
||||
```
|
||||
|
||||
### 跨场景恢复流
|
||||
|
||||
```
|
||||
场景切换 (OpenLevel / Seamless Travel)
|
||||
→ 新场景加载
|
||||
→ AChildHoodCharacter::BeginPlay()
|
||||
→ UCollectionManager::BeginPlay()
|
||||
→ LoadStateFromGameInstance()
|
||||
→ UChildHoodGameInstance::GetCollectionState(OutIDs, OutProgress, OutComplete)
|
||||
→ 恢复 CollectedIDs / Progress / bIsComplete
|
||||
→ 创建进度 UI(显示已恢复的进度值)
|
||||
→ 若 bIsComplete → 恢复完成样式
|
||||
→ 场景中 AInteractableActor::BeginPlay()
|
||||
→ UInteractableComponent::RestorePersistentState(GI)
|
||||
→ GI->IsItemCollected(ItemId) → 已收集则隐藏 + 禁用
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 10. 可调参数汇总
|
||||
@@ -886,10 +948,11 @@ InteractionManager (ExecuteAnimEvent)
|
||||
Source/ChildHood/
|
||||
├── Collection/
|
||||
│ ├── CollectionTypes.h # FCollectionConfig 结构体定义
|
||||
│ ├── CollectionManager.h/.cpp # 收集系统核心组件
|
||||
│ ├── CollectionManager.h/.cpp # 收集系统核心组件(含 GameInstance 读写)
|
||||
│ ├── CollectionNotifWidget.h/.cpp # 收集通知 UI 基类
|
||||
│ ├── CollectionProgressWidget.h/.cpp # 收集进度 UI 基类
|
||||
│ └── CollectionCompleteWidget.h/.cpp # 完成提示 UI 基类
|
||||
├── ChildHoodGameInstance.h/.cpp # 新增:跨关卡持久数据持有者(收集状态在此持久化)
|
||||
├── ChildHoodCharacter.h/.cpp # 修改:添加 CollectionManager 成员和访问器
|
||||
|
||||
Content/
|
||||
@@ -928,3 +991,85 @@ Content/
|
||||
|
||||
> **关键路径**:6b-1 → 6b-2 → 6b-4 → 6b-5 → 6b-6。6b-3(进度 UI)可在 6b-1 完成后并行。总关键路径约 3 天。
|
||||
> **前置依赖**:交互系统的 InteractionManager 组件需已完成(特别是 OnItemPickedUp/OnItemFound 委托),方可进行 6b-2 的委托绑定测试。
|
||||
|
||||
---
|
||||
|
||||
## 12. 跨场景持久化设计
|
||||
|
||||
> 收集进度是玩家的核心持久数据,必须在场景切换时保留。本节定义收集系统如何通过 `UChildHoodGameInstance` 实现跨场景数据持久化。
|
||||
|
||||
### 架构原则
|
||||
|
||||
```
|
||||
┌──────────────────────────────────────────────────┐
|
||||
│ UChildHoodGameInstance │ ← 跨关卡存活
|
||||
│ ├── CollectedItemIDs: TSet<FName> │ 所有场景共享
|
||||
│ ├── CollectionProgress: int32 │
|
||||
│ └── bCollectionComplete: bool │
|
||||
└──────────────────────────────────────────────────┘
|
||||
↕ BeginPlay 加载 / 收集时回写
|
||||
┌──────────────────────────────────────────────────┐
|
||||
│ UCollectionManager (每个场景重建) │ ← 行为层
|
||||
│ ├── 从 GameInstance 读取恢复进度 │ 不持有持久数据所有权
|
||||
│ ├── 收集时写入 GameInstance │
|
||||
│ └── 控制 UI / 通知 / 动画 │
|
||||
└──────────────────────────────────────────────────┘
|
||||
↕ 场景恢复
|
||||
┌──────────────────────────────────────────────────┐
|
||||
│ 场景中的 AInteractableActor │ ← 由交互系统负责恢复
|
||||
│ └── RestorePersistentState() │ (见交互系统技术方案第 12 节)
|
||||
└──────────────────────────────────────────────────┘
|
||||
```
|
||||
|
||||
### UChildHoodGameInstance 收集相关接口
|
||||
|
||||
```cpp
|
||||
UCLASS()
|
||||
class UChildHoodGameInstance : public UGameInstance
|
||||
{
|
||||
GENERATED_BODY()
|
||||
|
||||
public:
|
||||
// === 收集状态 ===
|
||||
void GetCollectionState(TSet<FName>& OutIDs, int32& OutProgress, bool& OutComplete) const;
|
||||
void SetCollectionState(const TSet<FName>& IDs, int32 Progress, bool bComplete);
|
||||
|
||||
// === 物品消耗状态(交互系统也使用)===
|
||||
bool IsItemCollected(FName ItemId) const;
|
||||
void MarkItemCollected(FName ItemId);
|
||||
|
||||
// === 门状态(交互系统也使用)===
|
||||
bool IsDoorOpen(FName DoorId) const;
|
||||
void SetDoorOpen(FName DoorId, bool bIsOpen);
|
||||
|
||||
// === 重置 ===
|
||||
void ResetAll();
|
||||
|
||||
private:
|
||||
// 收集系统
|
||||
TSet<FName> CollectedItemIDs;
|
||||
int32 CollectionProgress = 0;
|
||||
bool bCollectionComplete = false;
|
||||
// 交互系统
|
||||
TMap<FName, bool> DoorStates;
|
||||
};
|
||||
```
|
||||
|
||||
> **注意**:`CollectedItemIDs` 同时被 `IsItemCollected()`(交互物恢复)和 `GetCollectionState()`(收集进度恢复)使用,确保两系统数据一致性。
|
||||
|
||||
### 读写时机
|
||||
|
||||
| 时机 | 方法 | 说明 |
|
||||
|------|------|------|
|
||||
| CollectionManager::BeginPlay | `LoadStateFromGameInstance()` | 场景加载时恢复进度 |
|
||||
| ProcessNewCollection 记录后 | `SaveStateToGameInstance()` | 每次新收集时同步写入 |
|
||||
| 完成判定后 | `SaveStateToGameInstance()` | 完成状态立即持久化 |
|
||||
| InteractableComponent::Consume | `GI->MarkItemCollected()` | 交互物消耗状态写入(由交互系统调用) |
|
||||
|
||||
### v0.1 行为
|
||||
|
||||
- v0.1 为单场景原型,不存在跨场景切换
|
||||
- `UChildHoodGameInstance` 在 v0.1 中以空数据初始化,所有查询返回默认值
|
||||
- `LoadStateFromGameInstance()` 等效于初始化为 0
|
||||
- 后续多场景版本只需在 Project Settings 中将 GameInstance Class 设为 `UChildHoodGameInstance`,收集系统代码无需修改
|
||||
- 后续版本可通过 USaveGame 将 GameInstance 数据序列化到磁盘,实现跨会话持久化
|
||||
|
||||
@@ -0,0 +1,607 @@
|
||||
# v0.1 白模搭建操作指南 — 城郊小街
|
||||
|
||||
> 本文档由 execution-to-guide 工具自动生成,供 level-builder 搭建白模关卡使用。
|
||||
> 基于: 关卡-v0.1-城郊小街-执行案.md
|
||||
|
||||
---
|
||||
|
||||
## 〇、全局信息
|
||||
|
||||
### 场景参数
|
||||
|
||||
| 参数 | 值 |
|
||||
|------|-----|
|
||||
| 场景总尺寸 | 8000cm × 6000cm(80m × 60m) |
|
||||
| 地面高度基准 | Z = 0 |
|
||||
| 主角身高 | ~120cm |
|
||||
| 摄像机高度 | ~100cm |
|
||||
| 时间设定 | 夏日午后 15:00 |
|
||||
| 坐标原点 | 场景西南角地平面 |
|
||||
|
||||
### UE5 路径前缀
|
||||
|
||||
- **Mesh**: `Content/BlockingStarterPack/Meshes/`
|
||||
- **Material**: `Content/BlockingStarterPack/Materials/`
|
||||
- **Material (Basics)**: `Content/BlockingStarterPack/Materials/Blocking/Basics/`
|
||||
|
||||
### 命名规范
|
||||
|
||||
```
|
||||
LVL_<ZoneID>_<Category>_<Description>
|
||||
Category: STR | PROP | COMP | BND | LGT
|
||||
```
|
||||
|
||||
### Outliner 文件夹结构
|
||||
|
||||
```
|
||||
LVL_城郊小街/
|
||||
Z1_家/
|
||||
Structure/ Props/
|
||||
Z2_小卖部/
|
||||
Structure/ Props/
|
||||
Z3_主街道/
|
||||
Structure/ Props/
|
||||
Z4_空地/
|
||||
Structure/ Props/
|
||||
Z5_巷子/
|
||||
Structure/ Props/
|
||||
Z6_水塘边/
|
||||
Structure/ Props/
|
||||
Z7_老居民楼/
|
||||
Structure/ Props/
|
||||
Global/
|
||||
Boundaries/ Lighting/ PlayerStart/
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 一、BSP 资产映射表
|
||||
|
||||
### 建筑 — 墙体
|
||||
|
||||
| 设计文档引用 | UE5 资产路径 | 实际尺寸 (cm) |
|
||||
|-------------|-------------|--------------|
|
||||
| Wall_400x300 | `Architecture/Walls/SM_Wall_400x300` | 400×20×300 |
|
||||
| Wall_200x300 | `Architecture/Walls/SM_Wall_200x300` | 200×20×300 |
|
||||
| Wall_400x100 | `Architecture/Walls/SM_Wall_400x100` | 400×20×100 |
|
||||
| Wall_100x300 | `Architecture/Walls/SM_Wall_100x300` | 100×20×300 |
|
||||
|
||||
### 建筑 — 门墙
|
||||
|
||||
| 设计文档引用 | UE5 资产路径 | 实际尺寸 (cm) |
|
||||
|-------------|-------------|--------------|
|
||||
| WallDoor_200x300 | `Architecture/Walls/SM_WallDoor_200x300` | 200×20×300 |
|
||||
|
||||
### 建筑 — 窗墙
|
||||
|
||||
| 设计文档引用 | UE5 资产路径 | 实际尺寸 (cm) |
|
||||
|-------------|-------------|--------------|
|
||||
| WallWindow_400x300 | `Architecture/Walls/SM_WallWindow_400x300` | 400×20×300 |
|
||||
| WallWindowSmall_200x300 | `Architecture/Walls/SM_WallWindowSmall_200x300` | 200×20×300 |
|
||||
|
||||
### 建筑 — 地板
|
||||
|
||||
| 设计文档引用 | UE5 资产路径 | 实际尺寸 (cm) |
|
||||
|-------------|-------------|--------------|
|
||||
| Floor_300x400 | `Architecture/Floors/SM_Floor_300x400` | 300×400×22 |
|
||||
| Floor_1000x1000 | `Architecture/Floors/SM_Floor_1000x1000` | 1000×1000×22 |
|
||||
| Floor_200x300 | `Architecture/Floors/SM_Floor_200x300` | 200×300×22 |
|
||||
|
||||
### 建筑 — 窗户
|
||||
|
||||
| 设计文档引用 | UE5 资产路径 | 实际尺寸 (cm) |
|
||||
|-------------|-------------|--------------|
|
||||
| FakeWindowsFrame | `Architecture/WindowsSet/SM_FakeWindowsFrame` | 140×14×164 |
|
||||
|
||||
### 建筑 — 围挡
|
||||
|
||||
| 设计文档引用 | UE5 资产路径 | 实际尺寸 (cm) |
|
||||
|-------------|-------------|--------------|
|
||||
| BarrierWall_600 | `Architecture/Barriers/SM_BarrierWall_600` | 600×60×210 |
|
||||
| BarrierWall_200 | `Architecture/Barriers/SM_BarrierWall_200` | 200×60×210 |
|
||||
|
||||
### 建筑 — 围栏
|
||||
|
||||
| 设计文档引用 | UE5 资产路径 | 实际尺寸 (cm) |
|
||||
|-------------|-------------|--------------|
|
||||
| Fence_Small_400 | `Industrials/SM_Fence_Small_400` | 404×6×112 |
|
||||
|
||||
### 建筑 — 横梁
|
||||
|
||||
| 设计文档引用 | UE5 资产路径 | 实际尺寸 (cm) |
|
||||
|-------------|-------------|--------------|
|
||||
| Beam_300 | `Architecture/Beams/SM_Beam_300` | 40×40×300 |
|
||||
|
||||
### 建筑 — 大型建筑
|
||||
|
||||
| 设计文档引用 | UE5 资产路径 | 实际尺寸 (cm) |
|
||||
|-------------|-------------|--------------|
|
||||
| Building_01 | `BigBuildings/SM_Building_01` | 1950×1450×4010 |
|
||||
|
||||
### 家具
|
||||
|
||||
| 设计文档引用 | UE5 资产路径 | 实际尺寸 (cm) |
|
||||
|-------------|-------------|--------------|
|
||||
| Monitor_01 | `Furnitures/SM_Monitor_01` | 54×18×37 |
|
||||
| SimpleTable_01 | `Furnitures/SM_SimpleTable_01` | 161×87×74 |
|
||||
| BedSingle | `Bedroom/SM_BedSingle` | 116×216×68 |
|
||||
| SimpleTable_02 | `Furnitures/SM_SimpleTable_02` | 239×99×74 |
|
||||
|
||||
### 工业/装饰
|
||||
|
||||
| 设计文档引用 | UE5 资产路径 | 实际尺寸 (cm) |
|
||||
|-------------|-------------|--------------|
|
||||
| WoodenBox_Small | `Industrials/SM_WoodenBox_Small` | 70×70×70 |
|
||||
| Bucket_01 | `Decorations/SM_Bucket_01` | 30×27×26 |
|
||||
| Barrel | `Industrials/SM_Barrel` | 73×73×111 |
|
||||
| TrashCans_01 | `Trashs/SM_TrashCans_01` | 53×71×118 |
|
||||
| WoodenPallet_01 | `Industrials/SM_WoodenPallet_01` | 188×188×20 |
|
||||
| WoodenBox_Normal | `Industrials/SM_WoodenBox_Normal` | 90×90×90 |
|
||||
|
||||
### 载具
|
||||
|
||||
| 设计文档引用 | UE5 资产路径 | 实际尺寸 (cm) |
|
||||
|-------------|-------------|--------------|
|
||||
| Car01 | `Vehicles/SM_Car01` | 160×420×180 |
|
||||
|
||||
### 植被
|
||||
|
||||
| 设计文档引用 | UE5 资产路径 | 实际尺寸 (cm) |
|
||||
|-------------|-------------|--------------|
|
||||
| Tree_01 | `Vegetations/SM_Tree_01` | 762×803×845 |
|
||||
|
||||
### 灯具
|
||||
|
||||
| 设计文档引用 | UE5 资产路径 | 实际尺寸 (cm) |
|
||||
|-------------|-------------|--------------|
|
||||
| RoadLamp_01 | `Lights/SM_RoadLamp_01` | 40×244×850 |
|
||||
|
||||
### 装饰
|
||||
|
||||
| 设计文档引用 | UE5 资产路径 | 实际尺寸 (cm) |
|
||||
|-------------|-------------|--------------|
|
||||
| DisplayPanels_400x200 | `DisplayPanels/SM_DisplayPanels_400x200` | 400×8×200 |
|
||||
|
||||
### 其他
|
||||
|
||||
| 设计文档引用 | UE5 资产路径 | 实际尺寸 (cm) |
|
||||
|-------------|-------------|--------------|
|
||||
| WallDoorGarage_400x400 | `` | 0×0×0 |
|
||||
| _composite | `` | 0×0×0 |
|
||||
| Wheel | `` | 0×0×0 |
|
||||
| MI_DevGlassWhite | `` | 0×0×0 |
|
||||
| MI_DevGray | `` | 0×0×0 |
|
||||
| MI_DevWhite | `` | 0×0×0 |
|
||||
| MI_DevBlue | `` | 0×0×0 |
|
||||
| MI_DevYellow | `` | 0×0×0 |
|
||||
| MI_DevGlassBlue | `` | 0×0×0 |
|
||||
| MI_DevFoliage | `` | 0×0×0 |
|
||||
| MI_DevGreen | `` | 0×0×0 |
|
||||
|
||||
|
||||
---
|
||||
|
||||
## 二、Phase B — 地面与边界
|
||||
|
||||
### B1. 铺设地面
|
||||
|
||||
#### 全局地面(MI_DevGray)
|
||||
|
||||
| # | Actor 名称 | 资产 | 位置 (X,Y,Z) | 缩放 | 材质 |
|
||||
|---|-----------|------|-------------|------|------|
|
||||
| 1 | LVL_Global_STR_GroundFloor_01 | Floor_1000x1000 | (500,500,0) | — | MI_DevGray |
|
||||
| 2 | LVL_Global_STR_GroundFloor_02 | Floor_1000x1000 | (500,1500,0) | — | MI_DevGray |
|
||||
| 3 | LVL_Global_STR_GroundFloor_03 | Floor_1000x1000 | (500,2500,0) | — | MI_DevGray |
|
||||
| 4 | LVL_Global_STR_GroundFloor_04 | Floor_1000x1000 | (500,3500,0) | — | MI_DevGray |
|
||||
| 5 | LVL_Global_STR_GroundFloor_05 | Floor_1000x1000 | (500,4500,0) | — | MI_DevGray |
|
||||
| 6 | LVL_Global_STR_GroundFloor_06 | Floor_1000x1000 | (500,5500,0) | — | MI_DevGray |
|
||||
| 7 | LVL_Global_STR_GroundFloor_07 | Floor_1000x1000 | (1500,500,0) | — | MI_DevGray |
|
||||
| 8 | LVL_Global_STR_GroundFloor_08 | Floor_1000x1000 | (1500,1500,0) | — | MI_DevGray |
|
||||
| 9 | LVL_Global_STR_GroundFloor_09 | Floor_1000x1000 | (1500,2500,0) | — | MI_DevGray |
|
||||
| 10 | LVL_Global_STR_GroundFloor_10 | Floor_1000x1000 | (1500,3500,0) | — | MI_DevGray |
|
||||
| 11 | LVL_Global_STR_GroundFloor_11 | Floor_1000x1000 | (1500,4500,0) | — | MI_DevGray |
|
||||
| 12 | LVL_Global_STR_GroundFloor_12 | Floor_1000x1000 | (1500,5500,0) | — | MI_DevGray |
|
||||
| 13 | LVL_Global_STR_GroundFloor_13 | Floor_1000x1000 | (2500,500,0) | — | MI_DevGray |
|
||||
| 14 | LVL_Global_STR_GroundFloor_14 | Floor_1000x1000 | (2500,1500,0) | — | MI_DevGray |
|
||||
| 15 | LVL_Global_STR_GroundFloor_15 | Floor_1000x1000 | (2500,2500,0) | — | MI_DevGray |
|
||||
| 16 | LVL_Global_STR_GroundFloor_16 | Floor_1000x1000 | (2500,3500,0) | — | MI_DevGray |
|
||||
| 17 | LVL_Global_STR_GroundFloor_17 | Floor_1000x1000 | (2500,4500,0) | — | MI_DevGray |
|
||||
| 18 | LVL_Global_STR_GroundFloor_18 | Floor_1000x1000 | (2500,5500,0) | — | MI_DevGray |
|
||||
| 19 | LVL_Global_STR_GroundFloor_19 | Floor_1000x1000 | (3500,500,0) | — | MI_DevGray |
|
||||
| 20 | LVL_Global_STR_GroundFloor_20 | Floor_1000x1000 | (3500,1500,0) | — | MI_DevGray |
|
||||
| 21 | LVL_Global_STR_GroundFloor_21 | Floor_1000x1000 | (3500,2500,0) | — | MI_DevGray |
|
||||
| 22 | LVL_Global_STR_GroundFloor_22 | Floor_1000x1000 | (3500,3500,0) | — | MI_DevGray |
|
||||
| 23 | LVL_Global_STR_GroundFloor_23 | Floor_1000x1000 | (3500,4500,0) | — | MI_DevGray |
|
||||
| 24 | LVL_Global_STR_GroundFloor_24 | Floor_1000x1000 | (3500,5500,0) | — | MI_DevGray |
|
||||
| 25 | LVL_Global_STR_GroundFloor_25 | Floor_1000x1000 | (4500,500,0) | — | MI_DevGray |
|
||||
| 26 | LVL_Global_STR_GroundFloor_26 | Floor_1000x1000 | (4500,1500,0) | — | MI_DevGray |
|
||||
| 27 | LVL_Global_STR_GroundFloor_27 | Floor_1000x1000 | (4500,2500,0) | — | MI_DevGray |
|
||||
| 28 | LVL_Global_STR_GroundFloor_28 | Floor_1000x1000 | (4500,3500,0) | — | MI_DevGray |
|
||||
| 29 | LVL_Global_STR_GroundFloor_29 | Floor_1000x1000 | (4500,4500,0) | — | MI_DevGray |
|
||||
| 30 | LVL_Global_STR_GroundFloor_30 | Floor_1000x1000 | (4500,5500,0) | — | MI_DevGray |
|
||||
| 31 | LVL_Global_STR_GroundFloor_31 | Floor_1000x1000 | (5500,500,0) | — | MI_DevGray |
|
||||
| 32 | LVL_Global_STR_GroundFloor_32 | Floor_1000x1000 | (5500,1500,0) | — | MI_DevGray |
|
||||
| 33 | LVL_Global_STR_GroundFloor_33 | Floor_1000x1000 | (5500,2500,0) | — | MI_DevGray |
|
||||
| 34 | LVL_Global_STR_GroundFloor_34 | Floor_1000x1000 | (5500,3500,0) | — | MI_DevGray |
|
||||
| 35 | LVL_Global_STR_GroundFloor_35 | Floor_1000x1000 | (5500,4500,0) | — | MI_DevGray |
|
||||
| 36 | LVL_Global_STR_GroundFloor_36 | Floor_1000x1000 | (5500,5500,0) | — | MI_DevGray |
|
||||
| 37 | LVL_Global_STR_GroundFloor_37 | Floor_1000x1000 | (6500,500,0) | — | MI_DevGray |
|
||||
| 38 | LVL_Global_STR_GroundFloor_38 | Floor_1000x1000 | (6500,1500,0) | — | MI_DevGray |
|
||||
| 39 | LVL_Global_STR_GroundFloor_39 | Floor_1000x1000 | (6500,2500,0) | — | MI_DevGray |
|
||||
| 40 | LVL_Global_STR_GroundFloor_40 | Floor_1000x1000 | (6500,3500,0) | — | MI_DevGray |
|
||||
| 41 | LVL_Global_STR_GroundFloor_41 | Floor_1000x1000 | (6500,4500,0) | — | MI_DevGray |
|
||||
| 42 | LVL_Global_STR_GroundFloor_42 | Floor_1000x1000 | (6500,5500,0) | — | MI_DevGray |
|
||||
| 43 | LVL_Global_STR_GroundFloor_43 | Floor_1000x1000 | (7500,500,0) | — | MI_DevGray |
|
||||
| 44 | LVL_Global_STR_GroundFloor_44 | Floor_1000x1000 | (7500,1500,0) | — | MI_DevGray |
|
||||
| 45 | LVL_Global_STR_GroundFloor_45 | Floor_1000x1000 | (7500,2500,0) | — | MI_DevGray |
|
||||
| 46 | LVL_Global_STR_GroundFloor_46 | Floor_1000x1000 | (7500,3500,0) | — | MI_DevGray |
|
||||
| 47 | LVL_Global_STR_GroundFloor_47 | Floor_1000x1000 | (7500,4500,0) | — | MI_DevGray |
|
||||
| 48 | LVL_Global_STR_GroundFloor_48 | Floor_1000x1000 | (7500,5500,0) | — | MI_DevGray |
|
||||
|
||||
### B2. 放置边界围挡
|
||||
|
||||
#### 西边界
|
||||
|
||||
| # | Actor 名称 | 资产 | 位置 (X,Y,Z) | 旋转 (P,Y,R) | 缩放 | 材质 |
|
||||
|---|-----------|------|-------------|-------------|------|------|
|
||||
| 1 | LVL_Global_BND_西边界_01 | BarrierWall_600 | (0,300,105) | (0,90,0) | — | MI_DevRed |
|
||||
| 2 | LVL_Global_BND_西边界_02 | BarrierWall_600 | (0,900,105) | (0,90,0) | — | MI_DevRed |
|
||||
| 3 | LVL_Global_BND_西边界_03 | BarrierWall_600 | (0,1500,105) | (0,90,0) | — | MI_DevRed |
|
||||
| 4 | LVL_Global_BND_西边界_04 | BarrierWall_600 | (0,2100,105) | (0,90,0) | — | MI_DevRed |
|
||||
| 5 | LVL_Global_BND_西边界_05 | BarrierWall_600 | (0,2700,105) | (0,90,0) | — | MI_DevRed |
|
||||
| 6 | LVL_Global_BND_西边界_06 | BarrierWall_600 | (0,3300,105) | (0,90,0) | — | MI_DevRed |
|
||||
| 7 | LVL_Global_BND_西边界_07 | BarrierWall_600 | (0,3900,105) | (0,90,0) | — | MI_DevRed |
|
||||
| 8 | LVL_Global_BND_西边界_08 | BarrierWall_600 | (0,4500,105) | (0,90,0) | — | MI_DevRed |
|
||||
| 9 | LVL_Global_BND_西边界_09 | BarrierWall_600 | (0,5100,105) | (0,90,0) | — | MI_DevRed |
|
||||
| 10 | LVL_Global_BND_西边界_10 | BarrierWall_600 | (0,5700,105) | (0,90,0) | — | MI_DevRed |
|
||||
|
||||
#### 南边界
|
||||
|
||||
| # | Actor 名称 | 资产 | 位置 (X,Y,Z) | 旋转 (P,Y,R) | 缩放 | 材质 |
|
||||
|---|-----------|------|-------------|-------------|------|------|
|
||||
| 1 | LVL_Global_BND_南边界_01 | BarrierWall_600 | (300,0,105) | — | — | 各段标识色 |
|
||||
| 2 | LVL_Global_BND_南边界_02 | BarrierWall_600 | (900,0,105) | — | — | 各段标识色 |
|
||||
| 3 | LVL_Global_BND_南边界_03 | BarrierWall_600 | (1500,0,105) | — | — | 各段标识色 |
|
||||
| 4 | LVL_Global_BND_南边界_04 | BarrierWall_600 | (2100,0,105) | — | — | 各段标识色 |
|
||||
| 5 | LVL_Global_BND_南边界_05 | BarrierWall_600 | (2700,0,105) | — | — | 各段标识色 |
|
||||
| 6 | LVL_Global_BND_南边界_06 | BarrierWall_600 | (3300,0,105) | — | — | 各段标识色 |
|
||||
| 7 | LVL_Global_BND_南边界_07 | BarrierWall_600 | (3900,0,105) | — | — | 各段标识色 |
|
||||
| 8 | LVL_Global_BND_南边界_08 | BarrierWall_600 | (4500,0,105) | — | — | 各段标识色 |
|
||||
| 9 | LVL_Global_BND_南边界_09 | BarrierWall_600 | (5100,0,105) | — | — | 各段标识色 |
|
||||
| 10 | LVL_Global_BND_南边界_10 | BarrierWall_600 | (5700,0,105) | — | — | 各段标识色 |
|
||||
| 11 | LVL_Global_BND_南边界_11 | BarrierWall_600 | (6300,0,105) | — | — | 各段标识色 |
|
||||
| 12 | LVL_Global_BND_南边界_12 | BarrierWall_600 | (6900,0,105) | — | — | 各段标识色 |
|
||||
| 13 | LVL_Global_BND_南边界_13 | BarrierWall_600 | (7500,0,105) | — | — | 各段标识色 |
|
||||
|
||||
#### 东边界
|
||||
|
||||
| # | Actor 名称 | 资产 | 位置 (X,Y,Z) | 旋转 (P,Y,R) | 缩放 | 材质 |
|
||||
|---|-----------|------|-------------|-------------|------|------|
|
||||
| 1 | LVL_Global_BND_东边界_01 | BarrierWall_600 | (8000,300,105) | (0,90,0) | — | MI_DevBlue |
|
||||
| 2 | LVL_Global_BND_东边界_02 | BarrierWall_600 | (8000,900,105) | (0,90,0) | — | MI_DevBlue |
|
||||
| 3 | LVL_Global_BND_东边界_03 | BarrierWall_600 | (8000,1500,105) | (0,90,0) | — | MI_DevBlue |
|
||||
| 4 | LVL_Global_BND_东边界_04 | BarrierWall_600 | (8000,2100,105) | (0,90,0) | — | MI_DevBlue |
|
||||
| 5 | LVL_Global_BND_东边界_05 | BarrierWall_600 | (8000,2700,105) | (0,90,0) | — | MI_DevBlue |
|
||||
| 6 | LVL_Global_BND_东边界_06 | BarrierWall_600 | (8000,3300,105) | (0,90,0) | — | MI_DevBlue |
|
||||
| 7 | LVL_Global_BND_东边界_07 | BarrierWall_600 | (8000,3900,105) | (0,90,0) | — | MI_DevBlue |
|
||||
| 8 | LVL_Global_BND_东边界_08 | BarrierWall_600 | (8000,4500,105) | (0,90,0) | — | MI_DevBlue |
|
||||
| 9 | LVL_Global_BND_东边界_09 | BarrierWall_600 | (8000,5100,105) | (0,90,0) | — | MI_DevBlue |
|
||||
| 10 | LVL_Global_BND_东边界_10 | BarrierWall_600 | (8000,5700,105) | (0,90,0) | — | MI_DevBlue |
|
||||
|
||||
#### 北边界
|
||||
|
||||
| # | Actor 名称 | 资产 | 位置 (X,Y,Z) | 旋转 (P,Y,R) | 缩放 | 材质 |
|
||||
|---|-----------|------|-------------|-------------|------|------|
|
||||
| 1 | LVL_Global_BND_北边界_01 | BarrierWall_600 | (300,6000,105) | — | — | MI_DevBlue |
|
||||
| 2 | LVL_Global_BND_北边界_02 | BarrierWall_600 | (900,6000,105) | — | — | MI_DevBlue |
|
||||
| 3 | LVL_Global_BND_北边界_03 | BarrierWall_600 | (1500,6000,105) | — | — | MI_DevBlue |
|
||||
| 4 | LVL_Global_BND_北边界_04 | BarrierWall_600 | (2100,6000,105) | — | — | MI_DevBlue |
|
||||
| 5 | LVL_Global_BND_北边界_05 | BarrierWall_600 | (2700,6000,105) | — | — | MI_DevBlue |
|
||||
| 6 | LVL_Global_BND_北边界_06 | BarrierWall_600 | (3300,6000,105) | — | — | MI_DevBlue |
|
||||
| 7 | LVL_Global_BND_北边界_07 | BarrierWall_600 | (3900,6000,105) | — | — | MI_DevBlue |
|
||||
| 8 | LVL_Global_BND_北边界_08 | BarrierWall_600 | (4500,6000,105) | — | — | MI_DevBlue |
|
||||
| 9 | LVL_Global_BND_北边界_09 | BarrierWall_600 | (5100,6000,105) | — | — | MI_DevBlue |
|
||||
| 10 | LVL_Global_BND_北边界_10 | BarrierWall_600 | (5700,6000,105) | — | — | MI_DevBlue |
|
||||
| 11 | LVL_Global_BND_北边界_11 | BarrierWall_600 | (6300,6000,105) | — | — | MI_DevBlue |
|
||||
| 12 | LVL_Global_BND_北边界_12 | BarrierWall_600 | (6900,6000,105) | — | — | MI_DevBlue |
|
||||
| 13 | LVL_Global_BND_北边界_13 | BarrierWall_600 | (7500,6000,105) | — | — | MI_DevBlue |
|
||||
|
||||
#### Z6 水域
|
||||
|
||||
| # | Actor 名称 | 资产 | 位置 (X,Y,Z) | 旋转 (P,Y,R) | 缩放 | 材质 |
|
||||
|---|-----------|------|-------------|-------------|------|------|
|
||||
|
||||
|
||||
---
|
||||
|
||||
## 三、Phase C — 逐区域搭建
|
||||
|
||||
### C1. Z1 — 家
|
||||
|
||||
#### C1.1 结构体(Structure)
|
||||
|
||||
| # | Actor 名称 | 资产 | 位置 (X,Y,Z) | 旋转 (P,Y,R) | 缩放 | 材质 |
|
||||
|---|-----------|------|-------------|-------------|------|------|
|
||||
| | LVL_Z1_STR_South院Wall_01 | Wall_400x300 | (0,0,0) | — | — | MI_DevRed |
|
||||
| | LVL_Z1_STR_South院Wall_02 | Wall_400x300 | (400,0,0) | — | — | MI_DevRed |
|
||||
| | LVL_Z1_STR_South院Wall_03 | Wall_200x300 | (800,0,0) | — | — | MI_DevRed |
|
||||
| | LVL_Z1_STR_West院Wall_01 | Wall_400x300 | (0,0,0) | (0,-90,0) | — | MI_DevRed |
|
||||
| | LVL_Z1_STR_West院Wall_02 | Wall_400x300 | (400,0,0) | (0,-90,0) | — | MI_DevRed |
|
||||
| | LVL_Z1_STR_East院WallTop半段_01 | Wall_400x300 | (980,0,0) | (0,90,0) | — | MI_DevRed |
|
||||
| | LVL_Z1_STR_East院WallTop半段_02 | Wall_400x300 | (1380,0,0) | (0,90,0) | — | MI_DevRed |
|
||||
| | LVL_Z1_STR_North院Wall含院Door_01 | Cube | (0,780,0) | (0,180,0) | — | MI_DevRed |
|
||||
| | LVL_Z1_STR_房屋SouthWall含Window_01 | WallWindow_400x300 | (200,30,0) | — | — | MI_DevWhite |
|
||||
| | LVL_Z1_STR_房屋SouthWall含Window_02 | WallWindowSmall_200x300 | (600,30,0) | — | — | MI_DevWhite |
|
||||
| | LVL_Z1_STR_房屋WestWall_01 | Wall_400x300 | (200,30,0) | (0,-90,0) | — | MI_DevWhite |
|
||||
| | LVL_Z1_STR_房屋WestWall_02 | Wall_400x100 | (600,30,0) | (0,-90,0) | — | MI_DevWhite |
|
||||
| | LVL_Z1_STR_房屋EastWall_01 | Wall_400x300 | (780,30,0) | (0,90,0) | — | MI_DevWhite |
|
||||
| | LVL_Z1_STR_房屋EastWall_02 | Wall_400x100 | (1180,30,0) | (0,90,0) | — | MI_DevWhite |
|
||||
| | LVL_Z1_STR_房屋NorthWall含Door洞_01 | WallDoor_200x300 | (200,410,0) | (0,180,0) | — | MI_DevWhite |
|
||||
| | LVL_Z1_STR_房屋NorthWall含Door洞_02 | Wall_400x300 | (400,410,0) | (0,180,0) | — | MI_DevWhite |
|
||||
| | LVL_Z1_STR_房屋屋Roof_01 | Floor_300x400 | (190,25,280) | — | — | MI_DevBrown |
|
||||
| | LVL_Z1_STR_房屋屋Roof_02 | Floor_300x400 | (490,25,280) | — | — | MI_DevBrown |
|
||||
| | LVL_Z1_STR_院内Floor板_01 | Floor_1000x1000 | (0,0,0) | — | — | MI_DevGray |
|
||||
|
||||
#### C1.2 布景物(Props)
|
||||
|
||||
| # | Actor 名称 | 资产 | 位置 (X,Y,Z) | 缩放 | 材质 | 说明 |
|
||||
|---|-----------|------|-------------|------|------|------|
|
||||
| | LVL_Z1_PROP_旧自行Car_01 | _composite | (100,650,0) | — | | 靠西院墙停放,后座铁丝筐用 Cube 替代 |
|
||||
| | LVL_Z1_PROP_旧自行Car_02 | Wheel | (100,650,0) | — | | 靠西院墙停放,后座铁丝筐用 Cube 替代 |
|
||||
| | LVL_Z1_PROP_晾衣杆_01 | Beam_300 | (500,600,0) | — | | 挂衣服用 Cube 薄片替代 |
|
||||
| | LVL_Z1_PROP_晾衣杆_02 | Cylinder | (500,600,0) | — | | 挂衣服用 Cube 薄片替代 |
|
||||
| | LVL_Z1_PROP_杂物堆_01 | WoodenBox_Small | (850,100,0) | — | | 东南角 |
|
||||
| | LVL_Z1_PROP_杂物堆_02 | WoodenBox_Small | (890,100,0) | — | | 东南角 |
|
||||
| | LVL_Z1_PROP_杂物堆_03 | Bucket_01 | (930,100,0) | — | | 东南角 |
|
||||
| | LVL_Z1_PROP_Door垫_01 | Cube | (480,740,0) | — | | 院门内侧地面 |
|
||||
| | LVL_Z1_PROP_老式冰Box_01 | Barrel | (720,80,0) | — | | 房屋内东南角,靠东墙 |
|
||||
| | LVL_Z1_PROP_大脑袋电视_01 | Monitor_01 | (320,80,45) | — | | 房屋内西半部,放在书桌上 |
|
||||
| | LVL_Z1_PROP_书Table_01 | SimpleTable_01 | (300,70,0) | — | | 房屋内靠西墙 |
|
||||
| | LVL_Z1_PROP_Bed_01 | BedSingle | (350,250,0) | — | | 房屋内中部偏南 |
|
||||
| | LVL_Z1_PROP_日历_01 | Cube | (500,40,180) | — | | 挂在房屋南墙内侧 |
|
||||
| | LVL_Z1_PROP_电视Cabinet_01 | SimpleTable_02 | (320,55,0) | — | | 电视放在其上(v0.1 可与书桌合并) |
|
||||
|
||||
### C2. Z2 — 小卖部
|
||||
|
||||
#### C2.1 结构体(Structure)
|
||||
|
||||
| # | Actor 名称 | 资产 | 位置 (X,Y,Z) | 旋转 (P,Y,R) | 缩放 | 材质 |
|
||||
|---|-----------|------|-------------|-------------|------|------|
|
||||
| | LVL_Z2_STR_SouthWall_01 | Wall_400x300 | (1000,200,0) | — | — | MI_DevOrange |
|
||||
| | LVL_Z2_STR_SouthWall_02 | Wall_200x300 | (1400,200,0) | — | — | MI_DevOrange |
|
||||
| | LVL_Z2_STR_WestWall_01 | Wall_400x300 | (1000,200,0) | (0,-90,0) | — | MI_DevOrange |
|
||||
| | LVL_Z2_STR_WestWall_02 | Wall_400x100 | (1400,200,0) | (0,-90,0) | — | MI_DevOrange |
|
||||
| | LVL_Z2_STR_EastWall_01 | Wall_400x300 | (1580,200,0) | (0,90,0) | — | MI_DevOrange |
|
||||
| | LVL_Z2_STR_EastWall_02 | Wall_400x100 | (1980,200,0) | (0,90,0) | — | MI_DevOrange |
|
||||
| | LVL_Z2_STR_NorthWall含Door洞_01 | WallDoorGarage_400x400 | (1000,580,0) | (0,180,0) | — | MI_DevOrange |
|
||||
| | LVL_Z2_STR_NorthWall含Door洞_02 | Wall_200x300 | (1000,580,0) | (0,180,0) | — | MI_DevOrange |
|
||||
| | LVL_Z2_STR_屋Roof_01 | Floor_300x400 | (990,190,280) | — | — | MI_DevBrown |
|
||||
| | LVL_Z2_STR_屋Roof_02 | Floor_300x400 | (1290,190,280) | — | — | MI_DevBrown |
|
||||
| | LVL_Z2_STR_Floor板_01 | Floor_1000x1000 | (1000,200,0) | — | — | MI_DevGray |
|
||||
| | LVL_Z2_STR_遮阳棚前廊Roof_01 | Floor_200x300 | (1000,600,260) | — | — | MI_DevWhite |
|
||||
| | LVL_Z2_STR_遮阳棚前廊Roof_02 | Floor_200x300 | (1200,600,260) | — | — | MI_DevWhite |
|
||||
|
||||
#### C2.2 布景物(Props)
|
||||
|
||||
| # | Actor 名称 | 资产 | 位置 (X,Y,Z) | 缩放 | 材质 | 说明 |
|
||||
|---|-----------|------|-------------|------|------|------|
|
||||
| | LVL_Z2_PROP_玻璃CabinetCounter_01 | Cube | (1200,500,0) | — | | 店内中偏北,面向门口 |
|
||||
| | LVL_Z2_PROP_玻璃CabinetCounter_02 | MI_DevGlassWhite | (1300,500,0) | — | | 店内中偏北,面向门口 |
|
||||
| | LVL_Z2_PROP_零食货Shelf靠EastWall_01 | Fence_Small_400 | (1520,300,0) | — | | 东墙内侧,多层货架 |
|
||||
| | LVL_Z2_PROP_零食货Shelf靠EastWall_02 | Fence_Small_400 | (1920,300,0) | — | | 东墙内侧,多层货架 |
|
||||
| | LVL_Z2_PROP_零食货Shelf靠EastWall_03 | MI_DevGray | (2320,300,0) | — | | 东墙内侧,多层货架 |
|
||||
| | LVL_Z2_PROP_零食货Shelf靠SouthWall_01 | Fence_Small_400 | (1100,230,0) | — | | 南墙内侧 |
|
||||
| | LVL_Z2_PROP_零食货Shelf靠SouthWall_02 | MI_DevGray | (1500,230,0) | — | | 南墙内侧 |
|
||||
| | LVL_Z2_PROP_老式冰Cabinet_01 | Cube | (1050,400,0) | — | | 西南角,顶盖掀开式 |
|
||||
| | LVL_Z2_PROP_老式冰Cabinet_02 | MI_DevWhite | (1150,400,0) | — | | 西南角,顶盖掀开式 |
|
||||
| | LVL_Z2_PROP_小电视_01 | Monitor_01 | (1350,540,90) | — | | 放在柜台角落 |
|
||||
| | LVL_Z2_PROP_招牌_01 | Cube | (1150,610,280) | — | | 北墙外侧上方,蓝底白字"百货" |
|
||||
| | LVL_Z2_PROP_招牌_02 | MI_DevBlue | (1250,610,280) | — | | 北墙外侧上方,蓝底白字"百货" |
|
||||
| | LVL_Z2_PROP_卡片Shelf_01 | Cube | (1400,550,0) | — | | 柜台旁地面 |
|
||||
|
||||
### C3. Z3 — 主街道
|
||||
|
||||
#### C3.2 布景物(Props)
|
||||
|
||||
| # | Actor 名称 | 资产 | 位置 (X,Y,Z) | 缩放 | 材质 | 说明 |
|
||||
|---|-----------|------|-------------|------|------|------|
|
||||
| | LVL_Z3_PROP_公用电话亭_01 | Cube | (1800,1180,0) | — | | 街道北侧靠墙 |
|
||||
| | LVL_Z3_PROP_公用电话亭_02 | Cylinder | (1900,1180,0) | — | | 街道北侧靠墙 |
|
||||
| | LVL_Z3_PROP_老式自行Car_01 | Car01 | (2800,880,0) | (0.50,0.50,0.50) | | 街道南侧靠墙停放 |
|
||||
| | LVL_Z3_PROP_晾衣杆_01 | Beam_300 | (1200,1250,0) | — | | 街道北侧,伸出墙面的晾衣杆 |
|
||||
| | LVL_Z3_PROP_晾衣杆_02 | Cylinder | (1200,1250,0) | — | | 街道北侧,伸出墙面的晾衣杆 |
|
||||
| | LVL_Z3_PROP_Bottom水道盖_01 | CirclePlatform | (800,1050,0) | — | | 街道路面中央偏西 |
|
||||
| | LVL_Z3_PROP_WallTop涂鸦区域_01 | Cube | (3200,1270,100) | — | | 北墙 C 段墙面中部 |
|
||||
| | LVL_Z3_PROP_WallTop涂鸦区域_02 | MI_DevYellow | (3300,1270,100) | — | | 北墙 C 段墙面中部 |
|
||||
| | LVL_Z3_PROP_广告Wall_01 | DisplayPanels_400x200 | (3800,1270,0) | — | | 北墙 D 段起始处,手绘广告 |
|
||||
| | LVL_Z3_PROP_垃圾Barrel_01 | TrashCans_01 | (4200,880,0) | — | | 街道南侧 |
|
||||
| | LVL_Z3_PROP_电线杆West_01 | Cylinder | (1000,1050,0) | — | | 街道中轴 |
|
||||
| | LVL_Z3_PROP_电线杆East_01 | Cylinder | (3500,1050,0) | — | | 街道中轴 |
|
||||
|
||||
### C4. Z4 — 空地
|
||||
|
||||
#### C4.1 结构体(Structure)
|
||||
|
||||
| # | Actor 名称 | 资产 | 位置 (X,Y,Z) | 旋转 (P,Y,R) | 缩放 | 材质 |
|
||||
|---|-----------|------|-------------|-------------|------|------|
|
||||
| | LVL_Z4_STR_Floor面_01 | Cube | (3500,1300,0) | — | — | MI_DevBrown |
|
||||
| | LVL_Z4_STR_East边界Wall挡_01 | Cube | (4980,1300,0) | (0,90,0) | — | MI_DevBlue |
|
||||
| | LVL_Z4_STR_North边界Wall挡_01 | Cube | (3500,2480,0) | (0,180,0) | — | MI_DevBlue |
|
||||
| | LVL_Z4_STR_West边界矮Wall_01 | Cube | (3500,1300,0) | (0,-90,0) | — | MI_DevGray |
|
||||
|
||||
#### C4.2 布景物(Props)
|
||||
|
||||
| # | Actor 名称 | 资产 | 位置 (X,Y,Z) | 缩放 | 材质 | 说明 |
|
||||
|---|-----------|------|-------------|------|------|------|
|
||||
| | LVL_Z4_PROP_大梧桐Tree_01 | Tree_01 | (4250,1900,0) | — | | 空地偏北中央 |
|
||||
| | LVL_Z4_PROP_散落砖块_01 | WoodenBox_Small | (3700,1600,0) | — | | 空地西半部 |
|
||||
| | LVL_Z4_PROP_散落砖块_02 | WoodenBox_Small | (3708,1600,0) | — | | 空地西半部 |
|
||||
| | LVL_Z4_PROP_散落砖块_03 | WoodenBox_Small | (3716,1600,0) | — | | 空地西半部 |
|
||||
| | LVL_Z4_PROP_散落砖块_04 | WoodenBox_Small | (3724,1600,0) | — | | 空地西半部 |
|
||||
| | LVL_Z4_PROP_散落砖块_05 | WoodenBox_Small | (3732,1600,0) | — | | 空地西半部 |
|
||||
| | LVL_Z4_PROP_积水坑_01 | Cube | (4600,1500,-5) | — | | 空地东南角,嵌入地面 |
|
||||
| | LVL_Z4_PROP_积水坑_02 | MI_DevGlassBlue | (4700,1500,-5) | — | | 空地东南角,嵌入地面 |
|
||||
| | LVL_Z4_PROP_弹珠圈痕迹_01 | CirclePlatform | (4100,1800,0) | — | | 空地中偏北,地面上的圆圈 |
|
||||
| | LVL_Z4_PROP_弹珠圈痕迹_02 | MI_DevGray | (4100,1800,0) | — | | 空地中偏北,地面上的圆圈 |
|
||||
| | LVL_Z4_PROP_废弃建材_01 | WoodenPallet_01 | (4800,2300,0) | — | | 空地东北角 |
|
||||
| | LVL_Z4_PROP_废弃建材_02 | WoodenBox_Normal | (4800,2300,0) | — | | 空地东北角 |
|
||||
|
||||
### C5. Z5 — 巷子
|
||||
|
||||
#### C5.1 结构体(Structure)
|
||||
|
||||
| # | Actor 名称 | 资产 | 位置 (X,Y,Z) | 旋转 (P,Y,R) | 缩放 | 材质 |
|
||||
|---|-----------|------|-------------|-------------|------|------|
|
||||
| | LVL_Z5_STR_WestWall_01 | Wall_400x300 | (2300,1300,0) | (0,-90,0) | — | MI_DevWhite |
|
||||
| | LVL_Z5_STR_WestWall_02 | Wall_400x300 | (2700,1300,0) | (0,-90,0) | — | MI_DevWhite |
|
||||
| | LVL_Z5_STR_WestWall_03 | Wall_400x300 | (3100,1300,0) | (0,-90,0) | — | MI_DevWhite |
|
||||
| | LVL_Z5_STR_WestWall_04 | Wall_400x300 | (3500,1300,0) | (0,-90,0) | — | MI_DevWhite |
|
||||
| | LVL_Z5_STR_WestWall_05 | Wall_400x300 | (3900,1300,0) | (0,-90,0) | — | MI_DevWhite |
|
||||
| | LVL_Z5_STR_EastWall_01 | Wall_400x300 | (2580,1300,0) | (0,90,0) | — | MI_DevWhite |
|
||||
| | LVL_Z5_STR_EastWall_02 | Wall_400x300 | (2980,1300,0) | (0,90,0) | — | MI_DevWhite |
|
||||
| | LVL_Z5_STR_EastWall_03 | Wall_400x300 | (3380,1300,0) | (0,90,0) | — | MI_DevWhite |
|
||||
| | LVL_Z5_STR_EastWall_04 | Wall_400x300 | (3780,1300,0) | (0,90,0) | — | MI_DevWhite |
|
||||
| | LVL_Z5_STR_EastWall_05 | Wall_400x300 | (4180,1300,0) | (0,90,0) | — | MI_DevWhite |
|
||||
| | LVL_Z5_STR_Floor面_01 | Floor_1000x1000 | (2300,1300,0) | — | — | MI_DevGray |
|
||||
| | LVL_Z5_STR_Floor面_02 | Floor_1000x1000 | (3300,1300,0) | — | — | MI_DevGray |
|
||||
|
||||
#### C5.2 布景物(Props)
|
||||
|
||||
| # | Actor 名称 | 资产 | 位置 (X,Y,Z) | 缩放 | 材质 | 说明 |
|
||||
|---|-----------|------|-------------|------|------|------|
|
||||
| | LVL_Z5_PROP_废纸Box_01 | WoodenBox_Small | (2380,2900,0) | — | | 巷子深处(北段)靠西墙 |
|
||||
| | LVL_Z5_PROP_蜘蛛网_01 | Cube | (2305,2300,250) | — | | 西墙高处 |
|
||||
| | LVL_Z5_PROP_老Window户WestWall_01 | FakeWindowsFrame | (2310,2100,150) | — | | 西墙中段,不可交互 |
|
||||
| | LVL_Z5_PROP_花盆WindowCounter_01 | Cylinder | (2340,2100,150) | — | | 窗台上的花盆 |
|
||||
| | LVL_Z5_PROP_青苔Floor面细节_01 | Cube | (2400,2700,0) | — | | 巷子北段地面 |
|
||||
| | LVL_Z5_PROP_青苔Floor面细节_02 | MI_DevFoliage | (2500,2700,0) | — | | 巷子北段地面 |
|
||||
|
||||
### C6. Z6 — 水塘边
|
||||
|
||||
#### C6.1 结构体(Structure)
|
||||
|
||||
| # | Actor 名称 | 资产 | 位置 (X,Y,Z) | 旋转 (P,Y,R) | 缩放 | 材质 |
|
||||
|---|-----------|------|-------------|-------------|------|------|
|
||||
| | LVL_Z6_STR_水面_01 | Floor_1000x1000 | (1750,3650,-20) | — | — | MI_DevSkyBlue |
|
||||
| | LVL_Z6_STR_水面_02 | Floor_200x300 | (2750,3650,-20) | — | — | MI_DevSkyBlue |
|
||||
| | LVL_Z6_STR_岸边Floor面South_01 | Floor_1000x1000 | (1600,3300,0) | — | — | MI_DevBrown |
|
||||
| | LVL_Z6_STR_岸边Floor面South_02 | Floor_200x300 | (2600,3300,0) | — | — | MI_DevBrown |
|
||||
| | LVL_Z6_STR_岸边Floor面East_01 | Floor_1000x1000 | (2950,3650,0) | (0,90,0) | — | MI_DevBrown |
|
||||
| | LVL_Z6_STR_岸边Floor面West_01 | Floor_1000x1000 | (1600,3650,0) | (0,-90,0) | — | MI_DevBrown |
|
||||
| | LVL_Z6_STR_East边界Wall挡_01 | BarrierWall_600 | (3080,3300,0) | (0,90,0) | — | MI_DevBlue |
|
||||
| | LVL_Z6_STR_East边界Wall挡_02 | BarrierWall_600 | (3680,3300,0) | (0,90,0) | — | MI_DevBlue |
|
||||
| | LVL_Z6_STR_North边界Wall挡_01 | BarrierWall_600 | (1600,4680,0) | (0,180,0) | — | MI_DevBlue |
|
||||
| | LVL_Z6_STR_North边界Wall挡_02 | BarrierWall_600 | (2200,4680,0) | (0,180,0) | — | MI_DevBlue |
|
||||
| | LVL_Z6_STR_North边界Wall挡_03 | BarrierWall_200 | (2800,4680,0) | (0,180,0) | — | MI_DevBlue |
|
||||
|
||||
#### C6.2 布景物(Props)
|
||||
|
||||
| # | Actor 名称 | 资产 | 位置 (X,Y,Z) | 缩放 | 材质 | 说明 |
|
||||
|---|-----------|------|-------------|------|------|------|
|
||||
| | LVL_Z6_PROP_芦苇丛South岸Left_01 | Cylinder | (1800,3600,0) | — | | 水塘南岸边 |
|
||||
| | LVL_Z6_PROP_芦苇丛South岸Left_02 | Cylinder | (1900,3600,0) | — | | 水塘南岸边 |
|
||||
| | LVL_Z6_PROP_芦苇丛South岸Left_03 | Cylinder | (2000,3600,0) | — | | 水塘南岸边 |
|
||||
| | LVL_Z6_PROP_芦苇丛South岸Left_04 | Cylinder | (2100,3600,0) | — | | 水塘南岸边 |
|
||||
| | LVL_Z6_PROP_芦苇丛South岸Left_05 | Cylinder | (2200,3600,0) | — | | 水塘南岸边 |
|
||||
| | LVL_Z6_PROP_芦苇丛South岸Left_06 | MI_DevFoliage | (2300,3600,0) | — | | 水塘南岸边 |
|
||||
| | LVL_Z6_PROP_芦苇丛South岸Right_01 | Cylinder | (2700,3600,0) | — | | 水塘南岸边 |
|
||||
| | LVL_Z6_PROP_芦苇丛South岸Right_02 | Cylinder | (2800,3600,0) | — | | 水塘南岸边 |
|
||||
| | LVL_Z6_PROP_芦苇丛South岸Right_03 | Cylinder | (2900,3600,0) | — | | 水塘南岸边 |
|
||||
| | LVL_Z6_PROP_芦苇丛South岸Right_04 | Cylinder | (3000,3600,0) | — | | 水塘南岸边 |
|
||||
| | LVL_Z6_PROP_芦苇丛South岸Right_05 | Cylinder | (3100,3600,0) | — | | 水塘南岸边 |
|
||||
| | LVL_Z6_PROP_芦苇丛South岸Right_06 | MI_DevFoliage | (3200,3600,0) | — | | 水塘南岸边 |
|
||||
| | LVL_Z6_PROP_芦苇丛East岸_01 | Cylinder | (2900,4100,0) | — | | |
|
||||
| | LVL_Z6_PROP_芦苇丛East岸_02 | Cylinder | (3000,4100,0) | — | | |
|
||||
| | LVL_Z6_PROP_芦苇丛East岸_03 | Cylinder | (3100,4100,0) | — | | |
|
||||
| | LVL_Z6_PROP_芦苇丛East岸_04 | MI_DevFoliage | (3200,4100,0) | — | | |
|
||||
| | LVL_Z6_PROP_荷叶_01 | CirclePlatform | (2200,3900,-18) | — | | 水面上 |
|
||||
| | LVL_Z6_PROP_荷叶_02 | CirclePlatform | (2207,3900,-18) | — | | 水面上 |
|
||||
| | LVL_Z6_PROP_荷叶_03 | CirclePlatform | (2215,3900,-18) | — | | 水面上 |
|
||||
| | LVL_Z6_PROP_荷叶_04 | CirclePlatform | (2222,3900,-18) | — | | 水面上 |
|
||||
| | LVL_Z6_PROP_荷叶_05 | MI_DevGreen | (2230,3900,-18) | — | | 水面上 |
|
||||
| | LVL_Z6_PROP_青蛙_01 | Cube | (2100,3680,0) | — | | 南岸石头旁 |
|
||||
| | LVL_Z6_PROP_青蛙_02 | MI_DevGreen | (2200,3680,0) | — | | 南岸石头旁 |
|
||||
|
||||
### C7. Z7 — 老居民楼
|
||||
|
||||
#### C7.1 结构体(Structure)
|
||||
|
||||
| # | Actor 名称 | 资产 | 位置 (X,Y,Z) | 旋转 (P,Y,R) | 缩放 | 材质 |
|
||||
|---|-----------|------|-------------|-------------|------|------|
|
||||
| | LVL_Z7_STR_居民楼主体_01 | Building_01 | (5800,200,0) | — | — | MI_DevGray |
|
||||
| | LVL_Z7_STR_碰撞WallWall_01 | Wall_400x300 | (5750,150,0) | — | — | MI_DevGray |
|
||||
| | LVL_Z7_STR_碰撞WallWall_02 | Wall_400x300 | (6150,150,0) | — | — | MI_DevGray |
|
||||
| | LVL_Z7_STR_碰撞WallWall_03 | Wall_400x300 | (6550,150,0) | — | — | MI_DevGray |
|
||||
| | LVL_Z7_STR_碰撞WallWall_04 | Wall_100x300 | (6950,150,0) | — | — | MI_DevGray |
|
||||
| | LVL_Z7_STR_碰撞WallWall侧_01 | Wall_400x300 | (5750,150,0) | — | — | MI_DevGray |
|
||||
| | LVL_Z7_STR_碰撞WallWall侧_02 | Wall_400x300 | (6150,150,0) | — | — | MI_DevGray |
|
||||
|
||||
#### C7.2 布景物(Props)
|
||||
|
||||
| # | Actor 名称 | 资产 | 位置 (X,Y,Z) | 缩放 | 材质 | 说明 |
|
||||
|---|-----------|------|-------------|------|------|------|
|
||||
| | LVL_Z7_PROP_晾衣杆阳Counter_01 | Beam_300 | (6100,190,800) | — | | 不同楼层阳台外伸 |
|
||||
| | LVL_Z7_PROP_晾衣杆阳Counter_02 | Beam_300 | (6133,190,800) | — | | 不同楼层阳台外伸 |
|
||||
| | LVL_Z7_PROP_晾衣杆阳Counter_03 | Beam_300 | (6166,190,800) | — | | 不同楼层阳台外伸 |
|
||||
| | LVL_Z7_PROP_垃圾Barrel_01 | TrashCans_01 | (6000,140,0) | — | | 楼下地面 |
|
||||
|
||||
|
||||
---
|
||||
|
||||
## 四、Phase C — 全局物件
|
||||
|
||||
| # | Actor 名称 | 资产 | 位置 (X,Y,Z) | 缩放 | 材质 | 说明 |
|
||||
|---|-----------|------|-------------|------|------|------|
|
||||
| | LVL_Global_PROP_路Lamp_01 | RoadLamp_01 | (1500,1050,0) | — | | 街道中轴线偏南 |
|
||||
| | LVL_Global_PROP_路Lamp_02 | RoadLamp_01 | (1500,1050,0) | — | | 街道中轴线偏南 |
|
||||
| | LVL_Global_PROP_路Lamp_03 | RoadLamp_01 | (1500,1050,0) | — | | 街道中轴线偏南 |
|
||||
| | LVL_Global_PROP_垃圾Barrel_01 | TrashCans_01 | (2000,850,0) | — | | 街道南侧靠墙 |
|
||||
| | LVL_Global_PROP_垃圾Barrel_01 | MI_DevGreen | (2000,850,0) | — | | 街道南侧靠墙 |
|
||||
| | LVL_Global_PROP_垃圾Barrel_02 | TrashCans_01 | (2000,850,0) | — | | 街道南侧靠墙 |
|
||||
| | LVL_Global_PROP_垃圾Barrel_02 | MI_DevGreen | (2000,850,0) | — | | 街道南侧靠墙 |
|
||||
| | LVL_Global_PROP_电线杆_01 | Cylinder | (1000,1050,0) | — | | 街道中轴,与路灯交错 |
|
||||
| | LVL_Global_PROP_电线杆_02 | Cylinder | (1000,1050,0) | — | | 街道中轴,与路灯交错 |
|
||||
| | LVL_Global_PROP_施工Wall挡South边界补充_01 | BarrierWall_600 | (0,0,0) | — | | 街道南侧背后的南场景边界 |
|
||||
| | LVL_Global_PROP_施工Wall挡South边界补充_02 | MI_DevBlue | (0,0,0) | — | | 街道南侧背后的南场景边界 |
|
||||
|
||||
---
|
||||
|
||||
## 五、Phase D — 光照
|
||||
|
||||
### D1. 定向光(Directional Light)
|
||||
|
||||
| 类型 | 位置/方向 | 参数 |
|
||||
|------|---------|------|
|
||||
| Directional Light | 从西南方向照射,仰角约 45°(建议值,可调,范围 30°-60°) | 色温:暖白 ~5500K(建议值,可调);强度:中等(建议值,可调) |
|
||||
> 夏日午后主光源
|
||||
|
||||
### D2. 天空光(Sky Light)
|
||||
|
||||
| 类型 | 位置/方向 | 参数 |
|
||||
|------|---------|------|
|
||||
| Sky Light | 全局 | 强度:低-中(建议值,可调) |
|
||||
> 环境补光,避免纯黑阴影
|
||||
|
||||
### D3. 路灯点光源
|
||||
|
||||
> v0.1 为装饰性光源,午后光照下几乎不可见,数量: 3
|
||||
|
||||
|
||||
---
|
||||
|
||||
## 六、Phase E — 验证清单
|
||||
|
||||
| # | 检查项 | 状态 |
|
||||
|---|--------|------|
|
||||
| 1 | 场景尺寸 8000×6000cm 正确 | ⬜ |
|
||||
| 2 | 7 个区域均已搭建 | ⬜ |
|
||||
| 3 | 所有边界围挡无缺口 | ⬜ |
|
||||
| 4 | 玩家起点可到达 | ⬜ |
|
||||
| 5 | 所有区域可通行 | ⬜ |
|
||||
| 6 | 建筑入口与流线对齐 | ⬜ |
|
||||
| 7 | 光照方向与场景一致 | ⬜ |
|
||||
| 8 | Actor 总数: 161 | ⬜ |
|
||||
|
||||
---
|
||||
|
||||
> 搭建指南生成完成。共 7 个区域,161 个 Actor。
|
||||
@@ -0,0 +1,52 @@
|
||||
# execution-to-guide
|
||||
|
||||
关卡执行案 → 搭建指南 转换器。
|
||||
|
||||
将 `docs/design/关卡-vXX-<名称>-执行案.md` 自动转换为 `docs/technical/关卡-vXX-搭建指南.md`,供 `level-builder` 工具解析并在 UE5 中搭建白模关卡。
|
||||
|
||||
## 用法
|
||||
|
||||
```bash
|
||||
# 基本用法(自动推断输出路径到 docs/technical/)
|
||||
cd tools/execution-to-guide
|
||||
python converter.py -i ../../docs/design/关卡-v01-城郊小街-执行案.md
|
||||
|
||||
# 指定输出路径
|
||||
python converter.py -i ../../docs/design/关卡-v01-城郊小街-执行案.md -o ../../docs/technical/关卡-v01-搭建指南.md
|
||||
|
||||
# 详细日志
|
||||
python converter.py -i <执行案.md> -v
|
||||
```
|
||||
|
||||
## 依赖
|
||||
|
||||
- `tools/level-builder/config/` 下的 `asset_mapping.py`、`material_mapping.py`、`substitution_rules.py`
|
||||
- `tools/level-builder/parsers/markdown_table.py`
|
||||
|
||||
工具会自动从上级 `level-builder` 目录加载这些依赖。
|
||||
|
||||
## 模块说明
|
||||
|
||||
| 文件 | 功能 |
|
||||
|------|------|
|
||||
| `converter.py` | 主入口,编排解析→展开→生成流程 |
|
||||
| `execution_parser.py` | 解析执行案 Markdown,提取区域/结构体/布景/组合资产/边界/光照 |
|
||||
| `asset_expander.py` | 将 BSP 资产建议字符串展开为 Actor 规格(坐标计算、旋转推断、资产映射) |
|
||||
| `guide_writer.py` | 生成搭建指南 Markdown(匹配 `build_guide_parser.py` 的格式预期) |
|
||||
| `composite_writer.py` | 生成组合资产清单 + JSON 模板(无直接 BSP 匹配的物件) |
|
||||
|
||||
## 数据流
|
||||
|
||||
```
|
||||
关卡执行案 (.md)
|
||||
│
|
||||
▼
|
||||
execution_parser.py → ExecutionPlanData
|
||||
│
|
||||
▼
|
||||
asset_expander.py → list[ActorSpec] (展开 BSP 建议 + 坐标计算)
|
||||
│
|
||||
▼
|
||||
guide_writer.py → 搭建指南 (.md) (精确匹配 build_guide_parser 格式)
|
||||
composite_writer.py → 组合资产清单 (.md + .json)
|
||||
```
|
||||
@@ -0,0 +1 @@
|
||||
# execution-to-guide 工具包
|
||||
@@ -0,0 +1,423 @@
|
||||
"""BSP 资产建议展开器。
|
||||
|
||||
将执行案中的"BSP 资产建议"字符串拆分为可放置的 Actor 规格。
|
||||
|
||||
核心转换:
|
||||
- "Wall_400x300 × 2" → 2 个 Actor,间隔 400cm
|
||||
- "Wall_400x300 + Wall_200x300" → 2 种资产各 1 个
|
||||
- "Cube 缩放(0.3,0.3,1.6)" → 1 个 Cube,带缩放参数
|
||||
- 区域原点 + 相对偏移 → 绝对坐标
|
||||
- 构件名称/方位 → 旋转推断
|
||||
|
||||
同时复用 level-builder 的 asset_mapping / material_mapping / substitution_rules。
|
||||
"""
|
||||
|
||||
import re
|
||||
import math
|
||||
import logging
|
||||
from dataclasses import dataclass
|
||||
from typing import Optional
|
||||
|
||||
# 允许从包内或直接运行
|
||||
from pathlib import Path
|
||||
try:
|
||||
from config.asset_mapping import MESH_ASSETS, MESH_ROOT, get_pivot_compensation
|
||||
from config.material_mapping import MATERIAL_PATHS
|
||||
from config.substitution_rules import SUBSTITUTION_RULES
|
||||
except ImportError:
|
||||
import sys
|
||||
_lb = str(Path(__file__).resolve().parent.parent / "level-builder")
|
||||
if _lb not in sys.path:
|
||||
sys.path.insert(0, _lb)
|
||||
from config.asset_mapping import MESH_ASSETS, MESH_ROOT, get_pivot_compensation
|
||||
from config.material_mapping import MATERIAL_PATHS
|
||||
from config.substitution_rules import SUBSTITUTION_RULES
|
||||
|
||||
logger = logging.getLogger("execution_to_guide.expander")
|
||||
|
||||
|
||||
# ============================================================
|
||||
# 数据结构
|
||||
# ============================================================
|
||||
|
||||
@dataclass
|
||||
class ActorSpec:
|
||||
"""展开后的单个 Actor 规格。"""
|
||||
actor_name: str # LVL_Z1_STR_SouthWall_01
|
||||
asset_key: str # Wall_400x300
|
||||
asset_path: str # UE5 资产路径
|
||||
location: tuple # (X, Y, Z) 绝对坐标 cm
|
||||
rotation: tuple # (Pitch, Yaw, Roll) 度
|
||||
scale: tuple # (X, Y, Z) 缩放
|
||||
material: str # MI_DevRed
|
||||
material_path: str # UE5 材质路径
|
||||
category: str # STR | PROP | COMP
|
||||
zone_id: str # Z1 | GLOBAL
|
||||
folder: str # Outliner 文件夹路径
|
||||
note: str = ""
|
||||
|
||||
|
||||
# ============================================================
|
||||
# 方向→旋转映射
|
||||
# ============================================================
|
||||
|
||||
# 从构件名称中的方位词推断旋转
|
||||
# UE5: Yaw 绕 Z 轴旋转,沿 X 正方向为 0°
|
||||
# 南墙(沿 X 轴)= Yaw 0°,东墙(沿 Y 轴)= Yaw 90°
|
||||
DIRECTION_YAW = {
|
||||
"南": 0.0, # 沿 X 轴,面朝南(-Y)
|
||||
"东": 90.0, # 沿 Y 轴,面朝东(+X)
|
||||
"西": -90.0, # 沿 Y 轴,面朝西(-X)
|
||||
"北": 180.0, # 沿 X 轴,面朝北(+Y)
|
||||
"左": 90.0,
|
||||
"右": -90.0,
|
||||
"上": 0.0,
|
||||
"下": 0.0,
|
||||
}
|
||||
|
||||
|
||||
def infer_rotation_from_name(name: str) -> tuple:
|
||||
"""从构件名称推断旋转。
|
||||
|
||||
查找名称中的方位词(南/东/西/北),返回对应的 (Pitch, Yaw, Roll)。
|
||||
如果没有方位词,返回 (0, 0, 0)。
|
||||
"""
|
||||
for direction, yaw in DIRECTION_YAW.items():
|
||||
if direction in name:
|
||||
return (0.0, yaw, 0.0)
|
||||
return (0.0, 0.0, 0.0)
|
||||
|
||||
|
||||
def infer_rotation_from_offset(offset: tuple, zone_size: tuple) -> tuple:
|
||||
"""从偏移位置推断旋转(备用方案)。
|
||||
|
||||
根据物件在区域中的位置判断朝向:
|
||||
- 偏移 Y ≈ 0 → 南墙,Y ≈ max → 北墙
|
||||
- 偏移 X ≈ 0 → 西墙,X ≈ max → 东墙
|
||||
"""
|
||||
dx, dy, dz = offset
|
||||
w, d = zone_size[0], zone_size[1] if len(zone_size) > 1 else 0
|
||||
|
||||
if w > 0 and d > 0:
|
||||
# 判断更接近哪条边
|
||||
x_ratio = dx / w if w else 0
|
||||
y_ratio = dy / d if d else 0
|
||||
|
||||
if y_ratio < 0.1:
|
||||
return (0.0, 0.0, 0.0) # 南
|
||||
elif y_ratio > 0.9:
|
||||
return (0.0, 180.0, 0.0) # 北
|
||||
elif x_ratio < 0.1:
|
||||
return (0.0, -90.0, 0.0) # 西
|
||||
elif x_ratio > 0.9:
|
||||
return (0.0, 90.0, 0.0) # 东
|
||||
|
||||
return (0.0, 0.0, 0.0)
|
||||
|
||||
|
||||
# ============================================================
|
||||
# BSP 建议解析
|
||||
# ============================================================
|
||||
|
||||
def parse_bsp_suggestion(bsp_text: str) -> list[dict]:
|
||||
"""解析 BSP 资产建议字符串为资产列表。
|
||||
|
||||
支持的格式:
|
||||
- "Wall_400x300" → [{"key": "Wall_400x300", "count": 1}]
|
||||
- "Wall_400x300 × 2" → [{"key": "Wall_400x300", "count": 2}]
|
||||
- "Wall_400x300 × 2 + Wall_200x300" → [{"key": "Wall_400x300", "count": 2}, {"key": "Wall_200x300", "count": 1}]
|
||||
- "Cube 缩放(0.3,0.3,1.6)" → [{"key": "Cube", "count": 1, "scale": (0.3,0.3,1.6)}]
|
||||
- "Car01 缩放50%" → [{"key": "Car01", "count": 1, "scale": (0.5,0.5,0.5)}]
|
||||
- "Floor_1000x1000 缩放(8,6,1)" → [{"key": "Floor_1000x1000", "count": 1, "scale": (8,6,1)}]
|
||||
- "Primitives 组合" → [{"key": "_composite", "count": 1}]
|
||||
- "BarrierWall_600" → [{"key": "BarrierWall_600", "count": 1}]
|
||||
|
||||
Returns:
|
||||
list of dicts, each with:
|
||||
key: asset key string
|
||||
count: int
|
||||
scale: optional tuple (X, Y, Z)
|
||||
"""
|
||||
if not bsp_text or not bsp_text.strip():
|
||||
return []
|
||||
|
||||
bsp_text = bsp_text.strip()
|
||||
results = []
|
||||
|
||||
# 按 + 分割多个资产段
|
||||
segments = re.split(r'\s*\+\s*', bsp_text)
|
||||
|
||||
for seg in segments:
|
||||
seg = seg.strip()
|
||||
if not seg:
|
||||
continue
|
||||
|
||||
# 检测 Primitives 组合标记
|
||||
if "Primitives 组合" in seg or "组合" in seg and not re.search(r'[A-Z]', seg):
|
||||
results.append({"key": "_composite", "count": 1})
|
||||
continue
|
||||
|
||||
# 提取资产 key
|
||||
key_match = re.match(r'([A-Za-z_]\w*(?:\d+x\d+)?)', seg)
|
||||
if not key_match:
|
||||
continue
|
||||
|
||||
asset_key = key_match.group(1)
|
||||
remaining = seg[key_match.end():]
|
||||
|
||||
# 提取数量:× 2 或 *2 或 x2
|
||||
count = 1
|
||||
count_match = re.search(r'[×x*]\s*(\d+)', remaining)
|
||||
if count_match:
|
||||
count = int(count_match.group(1))
|
||||
|
||||
# 提取缩放:缩放(X,Y,Z) 或 缩放NN%
|
||||
scale = None
|
||||
scale_match = re.search(r'缩放\s*\(([\d.]+)\s*[,,]\s*([\d.]+)\s*[,,]\s*([\d.]+)\)', remaining)
|
||||
if scale_match:
|
||||
scale = (float(scale_match.group(1)), float(scale_match.group(2)), float(scale_match.group(3)))
|
||||
else:
|
||||
pct_match = re.search(r'缩放\s*(\d+)%', remaining)
|
||||
if pct_match:
|
||||
s = int(pct_match.group(1)) / 100.0
|
||||
scale = (s, s, s)
|
||||
|
||||
results.append({"key": asset_key, "count": count, "scale": scale})
|
||||
|
||||
return results
|
||||
|
||||
|
||||
# ============================================================
|
||||
# 资产展开
|
||||
# ============================================================
|
||||
|
||||
class AssetExpander:
|
||||
"""将执行案条目展开为 Actor 规格。"""
|
||||
|
||||
def __init__(self, zones: list):
|
||||
"""
|
||||
Args:
|
||||
zones: list[ZoneInfo] 区域信息列表
|
||||
"""
|
||||
self.zones = {z.zone_id: z for z in zones}
|
||||
self.actor_counters = {} # zone_id -> {category: counter}
|
||||
|
||||
def expand_structure(self, item, zone_id: str) -> list[ActorSpec]:
|
||||
"""展开结构体条目。
|
||||
|
||||
Args:
|
||||
item: StructureItem
|
||||
zone_id: 区域 ID
|
||||
|
||||
Returns:
|
||||
展开后的 ActorSpec 列表
|
||||
"""
|
||||
zone = self.zones.get(zone_id)
|
||||
if not zone:
|
||||
logger.warning(f"未找到区域 {zone_id},跳过结构体 {item.item_id}")
|
||||
return []
|
||||
|
||||
return self._expand_item(
|
||||
item_id=item.item_id,
|
||||
name=item.name,
|
||||
size=item.size,
|
||||
offset=item.offset,
|
||||
bsp_suggestion=item.bsp_suggestion,
|
||||
tag_color=item.tag_color,
|
||||
zone_id=zone_id,
|
||||
zone=zone,
|
||||
category="STR",
|
||||
note="",
|
||||
)
|
||||
|
||||
def expand_prop(self, item, zone_id: str) -> list[ActorSpec]:
|
||||
"""展开布景物条目。"""
|
||||
zone = self.zones.get(zone_id)
|
||||
if not zone:
|
||||
logger.warning(f"未找到区域 {zone_id},跳过布景 {item.item_id}")
|
||||
return []
|
||||
|
||||
return self._expand_item(
|
||||
item_id=item.item_id,
|
||||
name=item.name,
|
||||
size=item.size,
|
||||
offset=item.offset,
|
||||
bsp_suggestion=item.bsp_suggestion,
|
||||
tag_color="",
|
||||
zone_id=zone_id,
|
||||
zone=zone,
|
||||
category="PROP",
|
||||
note=item.note,
|
||||
)
|
||||
|
||||
def expand_global(self, item) -> list[ActorSpec]:
|
||||
"""展开全局物件条目。全局物件使用绝对坐标,不需要区域原点。"""
|
||||
parts = parse_bsp_suggestion(item.bsp_suggestion)
|
||||
if not parts:
|
||||
# 尝试 substitution_rules
|
||||
sub = SUBSTITUTION_RULES.get(item.name)
|
||||
if sub:
|
||||
parts = [{"key": sub["asset"], "count": item.count, "scale": sub.get("scale")}]
|
||||
else:
|
||||
parts = [{"key": "Cube", "count": item.count, "scale": None}]
|
||||
|
||||
actors = []
|
||||
for i in range(item.count):
|
||||
for part in parts:
|
||||
asset_key = part["key"]
|
||||
if asset_key == "_composite":
|
||||
continue
|
||||
|
||||
actor_name = f"LVL_Global_PROP_{self._slugify(item.name)}"
|
||||
if item.count > 1:
|
||||
actor_name += f"_{i + 1:02d}"
|
||||
elif len(parts) > 1:
|
||||
actor_name += f"_{parts.index(part) + 1:02d}"
|
||||
|
||||
scale = part.get("scale")
|
||||
if scale is None:
|
||||
scale = (1.0, 1.0, 1.0)
|
||||
|
||||
asset_path = MESH_ASSETS.get(asset_key, {}).get("path", "")
|
||||
material = ""
|
||||
mat_path = ""
|
||||
|
||||
actors.append(ActorSpec(
|
||||
actor_name=actor_name,
|
||||
asset_key=asset_key,
|
||||
asset_path=asset_path,
|
||||
location=item.location,
|
||||
rotation=(0.0, 0.0, 0.0),
|
||||
scale=scale,
|
||||
material=material,
|
||||
material_path=mat_path,
|
||||
category="PROP",
|
||||
zone_id="GLOBAL",
|
||||
folder=self._get_folder("GLOBAL", "PROP"),
|
||||
note=item.note,
|
||||
))
|
||||
|
||||
return actors
|
||||
|
||||
def _expand_item(self, item_id: str, name: str, size: tuple, offset: tuple,
|
||||
bsp_suggestion: str, tag_color: str, zone_id: str,
|
||||
zone, category: str, note: str) -> list[ActorSpec]:
|
||||
"""通用展开逻辑。"""
|
||||
parts = parse_bsp_suggestion(bsp_suggestion)
|
||||
if not parts:
|
||||
# 尝试 substitution_rules
|
||||
sub = SUBSTITUTION_RULES.get(name)
|
||||
if sub:
|
||||
parts = [{"key": sub["asset"], "count": 1, "scale": sub.get("scale")}]
|
||||
if not tag_color and sub.get("material"):
|
||||
tag_color = sub["material"]
|
||||
else:
|
||||
parts = [{"key": "Cube", "count": 1, "scale": None}]
|
||||
|
||||
actors = []
|
||||
# 跟踪资产段的累积偏移(用于 × N 的资产沿主轴排列)
|
||||
cum_offset_x = 0.0
|
||||
|
||||
for part in parts:
|
||||
asset_key = part["key"]
|
||||
count = part.get("count", 1)
|
||||
part_scale = part.get("scale")
|
||||
|
||||
for idx in range(count):
|
||||
# 计算绝对位置
|
||||
abs_x = zone.origin[0] + offset[0] + cum_offset_x
|
||||
abs_y = zone.origin[1] + offset[1]
|
||||
abs_z = zone.origin[2] + offset[2]
|
||||
|
||||
# 确定缩放
|
||||
if part_scale:
|
||||
scale = part_scale
|
||||
else:
|
||||
scale = (1.0, 1.0, 1.0)
|
||||
|
||||
# 确定旋转
|
||||
rotation = infer_rotation_from_name(name)
|
||||
|
||||
# 确定资产路径
|
||||
asset_info = MESH_ASSETS.get(asset_key, {})
|
||||
asset_path = asset_info.get("path", "")
|
||||
|
||||
# 确定材质
|
||||
material = tag_color
|
||||
mat_path = MATERIAL_PATHS.get(material, "") if material else ""
|
||||
|
||||
# 生成 Actor 名称
|
||||
actor_name = self._make_actor_name(zone_id, category, name, len(actors) + 1)
|
||||
|
||||
actors.append(ActorSpec(
|
||||
actor_name=actor_name,
|
||||
asset_key=asset_key,
|
||||
asset_path=asset_path,
|
||||
location=(abs_x, abs_y, abs_z),
|
||||
rotation=rotation,
|
||||
scale=scale,
|
||||
material=material,
|
||||
material_path=mat_path,
|
||||
category=category,
|
||||
zone_id=zone_id,
|
||||
folder=self._get_folder(zone_id, category),
|
||||
note=note,
|
||||
))
|
||||
|
||||
# 累积偏移:沿资产主轴方向排列
|
||||
if asset_info:
|
||||
default_size = asset_info.get("default_size", (0, 0, 0))
|
||||
if default_size and default_size[0] > 0:
|
||||
cum_offset_x += default_size[0] * scale[0]
|
||||
elif size and size[0] > 0 and count > 1:
|
||||
cum_offset_x += size[0] / count
|
||||
|
||||
return actors
|
||||
|
||||
def _make_actor_name(self, zone_id: str, category: str, name: str, seq: int) -> str:
|
||||
"""生成 Actor 名称:LVL_<ZoneID>_<CAT>_<Slug>_<Seq>"""
|
||||
slug = self._slugify(name)
|
||||
return f"LVL_{zone_id}_{category}_{slug}_{seq:02d}"
|
||||
|
||||
def _slugify(self, name: str) -> str:
|
||||
"""将中文名称转为 Actor 名称用的英文缩写。"""
|
||||
# 中文方位→英文
|
||||
_DIR_MAP = {"南": "South", "北": "North", "东": "East", "西": "West",
|
||||
"左": "Left", "右": "Right", "上": "Top", "下": "Bottom"}
|
||||
_TYPE_MAP = {
|
||||
"墙": "Wall", "围": "Wall", "地": "Floor", "顶": "Roof",
|
||||
"门": "Door", "窗": "Window", "栏": "Rail", "柱": "Pillar",
|
||||
"梁": "Beam", "台": "Counter", "架": "Shelf", "柜": "Cabinet",
|
||||
"桌": "Table", "椅": "Chair", "床": "Bed", "箱": "Box",
|
||||
"树": "Tree", "灯": "Lamp", "车": "Car", "桶": "Barrel",
|
||||
}
|
||||
|
||||
result = ""
|
||||
for ch in name:
|
||||
if ch in _DIR_MAP:
|
||||
result += _DIR_MAP[ch]
|
||||
elif ch in _TYPE_MAP:
|
||||
result += _TYPE_MAP[ch]
|
||||
elif ch.isalnum():
|
||||
result += ch
|
||||
# 跳过其他中文字符
|
||||
|
||||
return result if result else "Item"
|
||||
|
||||
def _get_folder(self, zone_id: str, category: str) -> str:
|
||||
"""获取 Outliner 文件夹路径。"""
|
||||
try:
|
||||
from config.zone_config import get_folder_path
|
||||
return get_folder_path(zone_id, category)
|
||||
except ImportError:
|
||||
zone = self.zones.get(zone_id)
|
||||
zone_name = zone.zone_name if zone else "Unknown"
|
||||
return f"LVL_Level/{zone_id}_{zone_name}/{category}"
|
||||
|
||||
def _next_seq(self, zone_id: str, category: str) -> int:
|
||||
"""获取下一个序号。"""
|
||||
key = f"{zone_id}_{category}"
|
||||
if key not in self.actor_counters:
|
||||
self.actor_counters[key] = 0
|
||||
self.actor_counters[key] += 1
|
||||
return self.actor_counters[key]
|
||||
@@ -0,0 +1,260 @@
|
||||
"""组合资产清单 + 模板生成器。
|
||||
|
||||
将执行案中的组合资产标记展开为:
|
||||
1. 组合资产清单 Markdown(供用户审查)
|
||||
2. 组合资产模板 JSON(确认后回馈到 asset-catalog 模板库)
|
||||
|
||||
组合资产 = 无法用单个 BSP StaticMesh 匹配的物件,需要多个 Primitives 拼搭。
|
||||
"""
|
||||
|
||||
import json
|
||||
import re
|
||||
import logging
|
||||
from pathlib import Path
|
||||
from dataclasses import dataclass, field, asdict
|
||||
from typing import Optional
|
||||
|
||||
from execution_parser import ExecutionPlanData, CompositeItem
|
||||
|
||||
logger = logging.getLogger("execution_to_guide.composite")
|
||||
|
||||
|
||||
# ============================================================
|
||||
# 数据结构
|
||||
# ============================================================
|
||||
|
||||
@dataclass
|
||||
class CompositePart:
|
||||
"""组合资产的一个构件。"""
|
||||
primitive: str # Cube / Cylinder / CirclePlatform
|
||||
scale: tuple # (X, Y, Z)
|
||||
offset: tuple # (X, Y, Z) 相对组合资产原点 cm
|
||||
material: str # MI_DevXxx
|
||||
|
||||
|
||||
@dataclass
|
||||
class CompositeTemplate:
|
||||
"""组合资产模板(确认后回馈到 asset-catalog)。"""
|
||||
template_name: str # 英文标识 OldRadio
|
||||
display_name: str # 中文名 旧收音机
|
||||
source_level: str # 来源版本 v02
|
||||
parts: list # list[CompositePart]
|
||||
total_bounds: dict # {"size": [W, D, H]}
|
||||
tags: list = field(default_factory=list) # ["prop", "electronics"]
|
||||
|
||||
|
||||
# ============================================================
|
||||
# 拼搭方案解析
|
||||
# ============================================================
|
||||
|
||||
def parse_build_plan(plan_text: str, target_size: tuple) -> list[CompositePart]:
|
||||
"""解析拼搭方案字符串为构件列表。
|
||||
|
||||
支持的格式:
|
||||
- "Cube(0.2,0.15,0.12) + Cylinder天线"
|
||||
- "Cube主体 + Cylinder(0.02,0.02,0.15)天线 offset(0.05,0,0.12)"
|
||||
|
||||
如果方案不够具体,生成一个默认的 Cube 占位。
|
||||
"""
|
||||
parts = []
|
||||
if not plan_text:
|
||||
# 默认:单个 Cube
|
||||
w, d, h = target_size if target_size != (0, 0, 0) else (20, 20, 20)
|
||||
parts.append(CompositePart(
|
||||
primitive="Cube",
|
||||
scale=(w / 100, d / 100, h / 100),
|
||||
offset=(0, 0, 0),
|
||||
material="MI_DevBrown",
|
||||
))
|
||||
return parts
|
||||
|
||||
# 按 + 分割
|
||||
segments = re.split(r'\s*\+\s*', plan_text)
|
||||
for seg in segments:
|
||||
seg = seg.strip()
|
||||
if not seg:
|
||||
continue
|
||||
|
||||
# 提取 Primitives 类型
|
||||
prim_match = re.match(r'(Cube|Cylinder|CirclePlatform)', seg)
|
||||
prim = prim_match.group(1) if prim_match else "Cube"
|
||||
remaining = seg[prim_match.end():] if prim_match else seg
|
||||
|
||||
# 提取缩放
|
||||
scale_match = re.search(r'\(([\d.]+)\s*,\s*([\d.]+)\s*,\s*([\d.]+)\)', remaining)
|
||||
if scale_match:
|
||||
scale = (float(scale_match.group(1)), float(scale_match.group(2)), float(scale_match.group(3)))
|
||||
else:
|
||||
scale = (0.1, 0.1, 0.1)
|
||||
|
||||
# 提取偏移
|
||||
offset_match = re.search(r'offset\s*\(([-\d.]+)\s*,\s*([-\d.]+)\s*,\s*([-\d.]+)\)', remaining, re.IGNORECASE)
|
||||
offset = (float(offset_match.group(1)), float(offset_match.group(2)), float(offset_match.group(3))) if offset_match else (0, 0, 0)
|
||||
|
||||
# 确定材质
|
||||
material = "MI_DevBrown"
|
||||
if "天线" in seg:
|
||||
material = "MI_DevGray"
|
||||
elif "玻璃" in seg or "镜" in seg:
|
||||
material = "MI_DevGlassWhite"
|
||||
elif "绿" in seg:
|
||||
material = "MI_DevGreen"
|
||||
elif "红" in seg:
|
||||
material = "MI_DevRed"
|
||||
|
||||
parts.append(CompositePart(
|
||||
primitive=prim,
|
||||
scale=scale,
|
||||
offset=offset,
|
||||
material=material,
|
||||
))
|
||||
|
||||
return parts if parts else [CompositePart(
|
||||
primitive="Cube",
|
||||
scale=(0.1, 0.1, 0.1),
|
||||
offset=(0, 0, 0),
|
||||
material="MI_DevBrown",
|
||||
)]
|
||||
|
||||
|
||||
# ============================================================
|
||||
# 组合资产文档生成
|
||||
# ============================================================
|
||||
|
||||
class CompositeWriter:
|
||||
"""组合资产清单 + 模板生成器。"""
|
||||
|
||||
def __init__(self, plan_data: ExecutionPlanData):
|
||||
self.plan = plan_data
|
||||
self.templates: list[CompositeTemplate] = []
|
||||
|
||||
def has_composites(self) -> bool:
|
||||
"""是否有组合资产。"""
|
||||
return sum(len(v) for v in self.plan.zone_composites.values()) > 0
|
||||
|
||||
def generate_markdown(self) -> str:
|
||||
"""生成组合资产清单 Markdown。"""
|
||||
lines = [
|
||||
f"# v{self.plan.version} 组合资产清单 — {self.plan.scene_name}",
|
||||
"",
|
||||
"> 本文档列出了执行案中需要用 Primitives 拼搭的组合资产。",
|
||||
"> 请审查每个拼搭方案,确认后可回馈到 asset-catalog 模板库。",
|
||||
"",
|
||||
"---",
|
||||
"",
|
||||
]
|
||||
|
||||
for zone_id, composites in self.plan.zone_composites.items():
|
||||
if not composites:
|
||||
continue
|
||||
|
||||
zone_name = self._get_zone_name(zone_id)
|
||||
lines.append(f"## {zone_id} {zone_name}")
|
||||
lines.append("")
|
||||
|
||||
for comp in composites:
|
||||
lines.append(f"### {comp.item_id} {comp.name}")
|
||||
lines.append("")
|
||||
lines.append(f"**期望尺寸**: {comp.target_size[0]:.0f}×{comp.target_size[1]:.0f}×{comp.target_size[2]:.0f} cm")
|
||||
lines.append(f"**说明**: {comp.note}")
|
||||
lines.append("")
|
||||
|
||||
# 解析拼搭方案
|
||||
parts = parse_build_plan(comp.build_plan, comp.target_size)
|
||||
|
||||
lines.append("| 构件 | Primitive | 缩放 (X,Y,Z) | 偏移 (X,Y,Z) | 材质 |")
|
||||
lines.append("|------|-----------|-------------|-------------|------|")
|
||||
|
||||
for i, part in enumerate(parts):
|
||||
lines.append(
|
||||
f"| 构件{i + 1} | {part.primitive} | "
|
||||
f"({part.scale[0]:.3f},{part.scale[1]:.3f},{part.scale[2]:.3f}) | "
|
||||
f"({part.offset[0]:.1f},{part.offset[1]:.1f},{part.offset[2]:.1f}) | "
|
||||
f"{part.material} |"
|
||||
)
|
||||
|
||||
lines.append("")
|
||||
|
||||
# 生成模板
|
||||
template = self._make_template(comp, parts)
|
||||
self.templates.append(template)
|
||||
|
||||
return "\n".join(lines)
|
||||
|
||||
def generate_templates_json(self) -> str:
|
||||
"""生成组合资产模板 JSON(回馈到 asset-catalog)。"""
|
||||
data = {
|
||||
"version": "1.0",
|
||||
"source_level": self.plan.version,
|
||||
"composite_templates": [asdict(t) for t in self.templates],
|
||||
}
|
||||
# 将 tuple 转为 list 以便 JSON 序列化
|
||||
def convert_tuples(obj):
|
||||
if isinstance(obj, dict):
|
||||
return {k: convert_tuples(v) for k, v in obj.items()}
|
||||
elif isinstance(obj, list):
|
||||
return [convert_tuples(i) for i in obj]
|
||||
elif isinstance(obj, tuple):
|
||||
return list(obj)
|
||||
return obj
|
||||
|
||||
data = convert_tuples(data)
|
||||
return json.dumps(data, indent=2, ensure_ascii=False)
|
||||
|
||||
def write_to_files(self, md_path: str, json_path: str = None):
|
||||
"""写入 Markdown 和 JSON 文件。"""
|
||||
# Markdown
|
||||
md_content = self.generate_markdown()
|
||||
md = Path(md_path)
|
||||
md.parent.mkdir(parents=True, exist_ok=True)
|
||||
md.write_text(md_content, encoding="utf-8")
|
||||
logger.info(f"组合资产清单已写入: {md_path}")
|
||||
|
||||
# JSON(可选)
|
||||
if json_path:
|
||||
json_content = self.generate_templates_json()
|
||||
jp = Path(json_path)
|
||||
jp.parent.mkdir(parents=True, exist_ok=True)
|
||||
jp.write_text(json_content, encoding="utf-8")
|
||||
logger.info(f"组合资产模板已写入: {json_path}")
|
||||
|
||||
def _make_template(self, comp: CompositeItem, parts: list[CompositePart]) -> CompositeTemplate:
|
||||
"""从组合资产条目生成模板。"""
|
||||
# 生成英文标识
|
||||
template_name = self._slugify(comp.name)
|
||||
|
||||
# 计算总包围盒
|
||||
max_x = max(p.offset[0] + p.scale[0] * 100 for p in parts) if parts else 0
|
||||
max_y = max(p.offset[1] + p.scale[1] * 100 for p in parts) if parts else 0
|
||||
max_z = max(p.offset[2] + p.scale[2] * 100 for p in parts) if parts else 0
|
||||
|
||||
return CompositeTemplate(
|
||||
template_name=template_name,
|
||||
display_name=comp.name,
|
||||
source_level=self.plan.version,
|
||||
parts=[asdict(p) for p in parts],
|
||||
total_bounds={"size": [max_x, max_y, max_z]},
|
||||
tags=["prop", "composite"],
|
||||
)
|
||||
|
||||
def _get_zone_name(self, zone_id: str) -> str:
|
||||
for z in self.plan.zones:
|
||||
if z.zone_id == zone_id:
|
||||
return z.zone_name
|
||||
return ""
|
||||
|
||||
def _slugify(self, name: str) -> str:
|
||||
"""将中文名称转为英文标识。"""
|
||||
# 简单映射
|
||||
_MAP = {
|
||||
"旧": "Old", "新": "New", "大": "Big", "小": "Small",
|
||||
"收音机": "Radio", "电视": "TV", "冰箱": "Fridge",
|
||||
"空调": "AC", "电话": "Phone", "自行车": "Bicycle",
|
||||
"摩托": "Motorcycle", "柜": "Cabinet", "桌": "Table",
|
||||
"椅": "Chair", "灯": "Lamp", "招牌": "Sign",
|
||||
}
|
||||
result = ""
|
||||
for key, val in sorted(_MAP.items(), key=lambda x: -len(x[0])):
|
||||
if key in name:
|
||||
result += val
|
||||
return result if result else "Composite"
|
||||
@@ -0,0 +1,118 @@
|
||||
"""执行案 → 搭建指南 转换器(主入口)。
|
||||
|
||||
用法:
|
||||
python -m execution_to_guide.converter -i <执行案.md> [-o <搭建指南.md>]
|
||||
|
||||
示例:
|
||||
python converter.py -i docs/design/关卡-v01-城郊小街-执行案.md -o docs/technical/关卡-v01-搭建指南.md
|
||||
python converter.py -i docs/design/关卡-v01-城郊小街-执行案.md # 自动推断输出路径
|
||||
"""
|
||||
|
||||
import argparse
|
||||
import logging
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
from execution_parser import ExecutionPlanParser
|
||||
from guide_writer import GuideWriter
|
||||
|
||||
logging.basicConfig(
|
||||
level=logging.INFO,
|
||||
format="%(name)s: %(message)s",
|
||||
)
|
||||
logger = logging.getLogger("execution_to_guide")
|
||||
|
||||
|
||||
def convert(input_path: str, output_path: str = None) -> str:
|
||||
"""将执行案转换为搭建指南。
|
||||
|
||||
Args:
|
||||
input_path: 执行案 Markdown 文件路径
|
||||
output_path: 搭建指南输出路径(可选,默认自动推断)
|
||||
|
||||
Returns:
|
||||
生成的搭建指南 Markdown 内容
|
||||
"""
|
||||
# 解析执行案
|
||||
logger.info(f"解析执行案: {input_path}")
|
||||
parser = ExecutionPlanParser()
|
||||
plan_data = parser.parse_file(input_path)
|
||||
|
||||
logger.info(f"场景: {plan_data.scene_name} v{plan_data.version}")
|
||||
logger.info(f"尺寸: {plan_data.scene_size[0]}×{plan_data.scene_size[1]}cm")
|
||||
logger.info(f"区域: {len(plan_data.zones)} 个")
|
||||
logger.info(f"结构体: {sum(len(v) for v in plan_data.zone_structures.values())} 条")
|
||||
logger.info(f"布景物: {sum(len(v) for v in plan_data.zone_props.values())} 条")
|
||||
logger.info(f"组合资产: {sum(len(v) for v in plan_data.zone_composites.values())} 条")
|
||||
logger.info(f"全局物件: {len(plan_data.global_objects)} 条")
|
||||
logger.info(f"边界: {len(plan_data.boundaries)} 段")
|
||||
|
||||
# 生成搭建指南
|
||||
writer = GuideWriter(plan_data)
|
||||
content = writer.generate()
|
||||
|
||||
# 输出文件
|
||||
if output_path is None:
|
||||
# 自动推断:docs/design/关卡-v01-xxx-执行案.md → docs/technical/关卡-v01-搭建指南.md
|
||||
in_path = Path(input_path)
|
||||
version = plan_data.version
|
||||
out_dir = in_path.parent.parent / "technical"
|
||||
out_dir.mkdir(parents=True, exist_ok=True)
|
||||
output_path = str(out_dir / f"关卡-{version}-搭建指南.md")
|
||||
|
||||
writer.write_to_file(output_path)
|
||||
logger.info(f"搭建指南已输出: {output_path}")
|
||||
|
||||
# 统计
|
||||
total_actors = len(writer.all_actors)
|
||||
unique_assets = len(writer.asset_refs)
|
||||
logger.info(f"生成 Actor: {total_actors} 个,使用资产: {unique_assets} 种")
|
||||
|
||||
# 如果有组合资产,提示
|
||||
total_composites = sum(len(v) for v in plan_data.zone_composites.values())
|
||||
if total_composites > 0:
|
||||
logger.warning(f"⚠️ 发现 {total_composites} 个组合资产需要手动展开或确认拼搭方案")
|
||||
|
||||
return content
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(
|
||||
description="关卡执行案 → 搭建指南 转换器",
|
||||
formatter_class=argparse.RawDescriptionHelpFormatter,
|
||||
epilog="""
|
||||
示例:
|
||||
python -m execution_to_guide.converter -i docs/design/关卡-v01-城郊小街-执行案.md
|
||||
python converter.py -i docs/design/关卡-v01-城郊小街-执行案.md -o output/指南.md
|
||||
""",
|
||||
)
|
||||
parser.add_argument(
|
||||
"-i", "--input", required=True,
|
||||
help="关卡执行案 Markdown 文件路径"
|
||||
)
|
||||
parser.add_argument(
|
||||
"-o", "--output", default=None,
|
||||
help="搭建指南输出路径(默认自动推断到 docs/technical/)"
|
||||
)
|
||||
parser.add_argument(
|
||||
"-v", "--verbose", action="store_true",
|
||||
help="显示详细日志"
|
||||
)
|
||||
|
||||
args = parser.parse_args()
|
||||
|
||||
if args.verbose:
|
||||
logging.getLogger().setLevel(logging.DEBUG)
|
||||
|
||||
try:
|
||||
convert(args.input, args.output)
|
||||
except FileNotFoundError as e:
|
||||
logger.error(f"文件未找到: {e}")
|
||||
sys.exit(1)
|
||||
except Exception as e:
|
||||
logger.error(f"转换失败: {e}")
|
||||
raise
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,662 @@
|
||||
"""关卡执行案 Markdown 解析器。
|
||||
|
||||
解析 docs/design/关卡-vXX-<名称>-执行案.md,提取结构化数据供后续转换为搭建指南。
|
||||
|
||||
执行案的表格格式(简化版,无交互物/收集品):
|
||||
- 区域总览表: 区域编号 / 区域名称 / 绝对坐标范围 (X,Y) / 尺寸 / 地面材质建议 / 标识色
|
||||
- 交通流线表: 流线路径 / 宽度 / 说明
|
||||
- 结构体表: 编号 / 构件名称 / 尺寸 / 相对原点偏移 / BSP 资产建议 / 标识色
|
||||
- 布景表: 编号 / 物件名称 / 尺寸 / 相对原点偏移 / BSP 资产建议 / 说明
|
||||
- 组合资产表: 编号 / 物件名称 / 期望尺寸 / 推荐拼搭方案 / 说明
|
||||
- 全局物件表: 编号 / 物件名称 / 数量 / 放置位置 / BSP 资产建议 / 说明
|
||||
- 边界表: 边界段 / 位置范围 / 遮挡方式 / BSP 资产建议 / 标识色
|
||||
- 光照表: 光源类型 / 数量 / 位置/方向 / 参数建议 / 说明
|
||||
"""
|
||||
|
||||
import re
|
||||
import logging
|
||||
from pathlib import Path
|
||||
from dataclasses import dataclass, field
|
||||
from typing import Optional
|
||||
|
||||
# 允许从包内或直接运行
|
||||
try:
|
||||
from parsers.markdown_table import parse_table, clean_cell
|
||||
except ImportError:
|
||||
import sys
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parent.parent / "level-builder"))
|
||||
from parsers.markdown_table import parse_table, clean_cell
|
||||
|
||||
logger = logging.getLogger("execution_to_guide.parser")
|
||||
|
||||
|
||||
# ============================================================
|
||||
# 数据结构
|
||||
# ============================================================
|
||||
|
||||
@dataclass
|
||||
class ZoneInfo:
|
||||
"""区域信息。"""
|
||||
zone_id: str # Z1, Z2, ...
|
||||
zone_name: str # 家、小卖部、...
|
||||
origin: tuple # (X, Y, Z) 区域西南角绝对坐标
|
||||
bounds_x: tuple # (X_min, X_max)
|
||||
bounds_y: tuple # (Y_min, Y_max)
|
||||
size_m: tuple # (宽m, 深m)
|
||||
ground_material: str = "" # 地面材质建议
|
||||
tag_color: str = "" # 标识色 MI_DevXxx
|
||||
height: float = 0 # 建筑高度(cm)
|
||||
wall_height: float = 250 # 围墙高度
|
||||
door_width: float = 120 # 门洞宽度
|
||||
door_height: float = 220 # 门洞高度
|
||||
indoor_clear_height: float = 280 # 室内净高
|
||||
eaves_height: float = 300 # 屋檐高度
|
||||
|
||||
|
||||
@dataclass
|
||||
class StructureItem:
|
||||
"""结构体条目(墙/地/顶/门/窗等建筑构件)。"""
|
||||
item_id: str # Z1-S01
|
||||
name: str # 南围墙
|
||||
size: tuple # (宽, 深, 高) cm
|
||||
offset: tuple # (ΔX, ΔY, ΔZ) 相对区域原点
|
||||
bsp_suggestion: str # Wall_400x300 x 2
|
||||
tag_color: str = "" # MI_DevRed
|
||||
|
||||
|
||||
@dataclass
|
||||
class PropItem:
|
||||
"""布景物条目(家具/道具/装饰)。"""
|
||||
item_id: str # Z1-P01
|
||||
name: str # 旧自行车
|
||||
size: tuple # (宽, 深, 高) cm(约)
|
||||
offset: tuple # (ΔX, ΔY, ΔZ) 相对区域原点
|
||||
bsp_suggestion: str # Car01 缩放50%
|
||||
note: str = "" # 靠墙停放
|
||||
|
||||
|
||||
@dataclass
|
||||
class CompositeItem:
|
||||
"""组合资产条目(需 Primitives 拼搭)。"""
|
||||
item_id: str # Z1-C01
|
||||
name: str # 旧收音机
|
||||
target_size: tuple # (宽, 深, 高) cm(约)
|
||||
build_plan: str # Cube(0.2,0.15,0.12) + Cylinder天线
|
||||
note: str = "" # 放在柜台上
|
||||
|
||||
|
||||
@dataclass
|
||||
class GlobalObject:
|
||||
"""全局物件。"""
|
||||
item_id: str # G-01 / G-E01
|
||||
name: str
|
||||
count: int
|
||||
location: tuple # (X, Y, Z) 绝对坐标
|
||||
bsp_suggestion: str
|
||||
note: str = ""
|
||||
|
||||
|
||||
@dataclass
|
||||
class BoundaryItem:
|
||||
"""场景边界。"""
|
||||
segment: str # 西边界/南边界/东边界/北边界
|
||||
location_range: str
|
||||
block_method: str # 围墙/自然遮挡
|
||||
bsp_suggestion: str
|
||||
tag_color: str = ""
|
||||
|
||||
|
||||
@dataclass
|
||||
class LightItem:
|
||||
"""光照建议。"""
|
||||
light_type: str # 定向光/天空光/路灯
|
||||
count: int
|
||||
position: str # 位置/方向描述
|
||||
params: str # 参数建议
|
||||
note: str = ""
|
||||
|
||||
|
||||
@dataclass
|
||||
class TrafficFlow:
|
||||
"""交通流线。"""
|
||||
path: str # Z1 → Z3 家门 → 街道
|
||||
width: float # cm
|
||||
note: str = ""
|
||||
|
||||
|
||||
@dataclass
|
||||
class ExecutionPlanData:
|
||||
"""执行案解析后的完整数据。"""
|
||||
version: str = ""
|
||||
scene_name: str = ""
|
||||
scene_size: tuple = (0, 0) # (宽cm, 深cm)
|
||||
ground_z: float = 0
|
||||
character_height: float = 120
|
||||
camera_height: float = 100
|
||||
time_setting: str = ""
|
||||
zones: list = field(default_factory=list) # list[ZoneInfo]
|
||||
flows: list = field(default_factory=list) # list[TrafficFlow]
|
||||
zone_structures: dict = field(default_factory=dict) # zone_id -> list[StructureItem]
|
||||
zone_props: dict = field(default_factory=dict) # zone_id -> list[PropItem]
|
||||
zone_composites: dict = field(default_factory=dict) # zone_id -> list[CompositeItem]
|
||||
global_objects: list = field(default_factory=list) # list[GlobalObject]
|
||||
boundaries: list = field(default_factory=list) # list[BoundaryItem]
|
||||
lights: list = field(default_factory=list) # list[LightItem]
|
||||
|
||||
|
||||
# ============================================================
|
||||
# 解析逻辑
|
||||
# ============================================================
|
||||
|
||||
class ExecutionPlanParser:
|
||||
"""关卡执行案解析器。"""
|
||||
|
||||
def __init__(self):
|
||||
self.data = ExecutionPlanData()
|
||||
|
||||
def parse_file(self, filepath: str) -> ExecutionPlanData:
|
||||
"""解析执行案文件。"""
|
||||
path = Path(filepath)
|
||||
if not path.exists():
|
||||
raise FileNotFoundError(f"执行案文件不存在: {filepath}")
|
||||
text = path.read_text(encoding="utf-8")
|
||||
return self.parse_text(text)
|
||||
|
||||
def parse_text(self, text: str) -> ExecutionPlanData:
|
||||
"""解析执行案文本。"""
|
||||
lines = text.split("\n")
|
||||
|
||||
# 解析标题 → 版本和场景名
|
||||
self._parse_title(lines)
|
||||
|
||||
# 一、场景参数
|
||||
self._parse_scene_params(lines)
|
||||
|
||||
# 二、区域坐标布局
|
||||
self._parse_zone_layout(lines)
|
||||
|
||||
# 三、逐区域搭建指南
|
||||
self._parse_zone_details(lines)
|
||||
|
||||
# 四、全局物件清单
|
||||
self._parse_global_objects(lines)
|
||||
|
||||
# 五、场景边界与遮挡
|
||||
self._parse_boundaries(lines)
|
||||
|
||||
# 六、光照建议
|
||||
self._parse_lighting(lines)
|
||||
|
||||
return self.data
|
||||
|
||||
# ----------------------------------------------------------
|
||||
# 标题
|
||||
# ----------------------------------------------------------
|
||||
def _parse_title(self, lines: list[str]):
|
||||
"""从标题提取版本号和场景名。如:# v0.1 关卡执行案 — 城郊小街"""
|
||||
for line in lines:
|
||||
m = re.match(r'#\s+v([\d.]+)\s+关卡执行案\s*[—\-–]\s*(.+)', line)
|
||||
if m:
|
||||
self.data.version = m.group(1)
|
||||
self.data.scene_name = m.group(2).strip()
|
||||
break
|
||||
|
||||
# ----------------------------------------------------------
|
||||
# 一、场景参数
|
||||
# ----------------------------------------------------------
|
||||
def _parse_scene_params(self, lines: list[str]):
|
||||
"""解析场景参数表。"""
|
||||
section_start = self._find_section(lines, "一、场景参数")
|
||||
section_end = self._find_section(lines, "二、区域坐标布局")
|
||||
if section_start < 0:
|
||||
return
|
||||
if section_end < 0:
|
||||
section_end = len(lines)
|
||||
|
||||
section_lines = lines[section_start:section_end]
|
||||
tables = self._extract_tables(section_lines)
|
||||
if not tables:
|
||||
return
|
||||
|
||||
for row in tables[0]:
|
||||
param = clean_cell(row.get("参数", ""))
|
||||
value = clean_cell(row.get("值", ""))
|
||||
if not param:
|
||||
continue
|
||||
|
||||
if "场景总尺寸" in param:
|
||||
size_match = re.search(r'(\d+)\s*cm\s*[x×]\s*(\d+)\s*cm', value)
|
||||
if size_match:
|
||||
self.data.scene_size = (int(size_match.group(1)), int(size_match.group(2)))
|
||||
elif "地面高度基准" in param:
|
||||
z_match = re.search(r'Z?\s*=\s*(-?\d+)', value)
|
||||
if z_match:
|
||||
self.data.ground_z = float(z_match.group(1))
|
||||
elif "主角身高" in param:
|
||||
h_match = re.search(r'~?(\d+)', value)
|
||||
if h_match:
|
||||
self.data.character_height = float(h_match.group(1))
|
||||
elif "视角高度" in param:
|
||||
h_match = re.search(r'~?(\d+)', value)
|
||||
if h_match:
|
||||
self.data.camera_height = float(h_match.group(1))
|
||||
elif "时间设定" in param:
|
||||
self.data.time_setting = value
|
||||
|
||||
# ----------------------------------------------------------
|
||||
# 二、区域坐标布局
|
||||
# ----------------------------------------------------------
|
||||
def _parse_zone_layout(self, lines: list[str]):
|
||||
"""解析区域总览表和交通流线表。"""
|
||||
section_start = self._find_section(lines, "二、区域坐标布局")
|
||||
section_end = self._find_section(lines, "三、逐区域搭建指南")
|
||||
if section_start < 0:
|
||||
return
|
||||
if section_end < 0:
|
||||
section_end = len(lines)
|
||||
|
||||
section_lines = lines[section_start:section_end]
|
||||
tables = self._extract_tables(section_lines)
|
||||
|
||||
# 第一个表格 = 区域总览表
|
||||
if tables:
|
||||
for row in tables[0]:
|
||||
zone = self._parse_zone_row(row)
|
||||
if zone:
|
||||
self.data.zones.append(zone)
|
||||
|
||||
# 第二个表格 = 交通流线(如果有)
|
||||
if len(tables) > 1:
|
||||
for row in tables[1]:
|
||||
path = clean_cell(row.get("流线路径", ""))
|
||||
if not path:
|
||||
continue
|
||||
width_str = clean_cell(row.get("宽度", "200"))
|
||||
w_match = re.search(r'(\d+)', width_str)
|
||||
width = float(w_match.group(1)) if w_match else 200.0
|
||||
note = clean_cell(row.get("说明", ""))
|
||||
self.data.flows.append(TrafficFlow(
|
||||
path=path, width=width, note=note
|
||||
))
|
||||
|
||||
def _parse_zone_row(self, row: dict) -> Optional[ZoneInfo]:
|
||||
"""解析区域总览表的一行。"""
|
||||
zone_id = clean_cell(row.get("区域编号", ""))
|
||||
zone_name = clean_cell(row.get("区域名称", ""))
|
||||
coord_str = clean_cell(row.get("绝对坐标范围 (X,Y)", row.get("绝对坐标范围", "")))
|
||||
|
||||
if not zone_id or not zone_name:
|
||||
return None
|
||||
if not re.match(r'Z\d+', zone_id):
|
||||
return None
|
||||
|
||||
# 解析坐标范围:(X1,Y1)→(X2,Y2)
|
||||
coord_match = re.match(
|
||||
r'\((\d+)\s*,\s*(\d+)\)\s*[→\-–]+\s*\((\d+)\s*,\s*(\d+)\)',
|
||||
coord_str
|
||||
)
|
||||
if not coord_match:
|
||||
return None
|
||||
|
||||
x_min, y_min = int(coord_match.group(1)), int(coord_match.group(2))
|
||||
x_max, y_max = int(coord_match.group(3)), int(coord_match.group(4))
|
||||
|
||||
# 解析尺寸
|
||||
size_str = clean_cell(row.get("尺寸 (宽x深)", row.get("尺寸", "")))
|
||||
size_match = re.search(r'(\d+)\s*m?\s*[x×]\s*(\d+)\s*m?', size_str)
|
||||
size_m = (float(size_match.group(1)), float(size_match.group(2))) if size_match else (0, 0)
|
||||
|
||||
ground_mat = clean_cell(row.get("地面材质建议", ""))
|
||||
tag_color = clean_cell(row.get("标识色", ""))
|
||||
|
||||
return ZoneInfo(
|
||||
zone_id=zone_id,
|
||||
zone_name=zone_name,
|
||||
origin=(x_min, y_min, 0),
|
||||
bounds_x=(x_min, x_max),
|
||||
bounds_y=(y_min, y_max),
|
||||
size_m=size_m,
|
||||
ground_material=ground_mat,
|
||||
tag_color=tag_color,
|
||||
)
|
||||
|
||||
# ----------------------------------------------------------
|
||||
# 三、逐区域搭建指南
|
||||
# ----------------------------------------------------------
|
||||
def _parse_zone_details(self, lines: list[str]):
|
||||
"""解析逐区域搭建指南(结构体/布景/组合资产)。"""
|
||||
section_start = self._find_section(lines, "三、逐区域搭建指南")
|
||||
section_end = self._find_section(lines, "四、全局物件清单")
|
||||
if section_start < 0:
|
||||
return
|
||||
if section_end < 0:
|
||||
section_end = len(lines)
|
||||
|
||||
section_lines = lines[section_start:section_end]
|
||||
current_zone = ""
|
||||
current_zone_info = None
|
||||
|
||||
i = 0
|
||||
while i < len(section_lines):
|
||||
line = section_lines[i].strip()
|
||||
|
||||
# 检测区域标题:### Z1:家(Home)或 ### Z1: 家 或 ### Z1:家
|
||||
zm = re.match(r'###\s+(Z\d+)\s*[::]\s*(.+?)(?:\s*[((].+[)])?\s*$', line)
|
||||
if zm:
|
||||
current_zone = zm.group(1)
|
||||
current_zone_info = self._find_zone(current_zone)
|
||||
i += 1
|
||||
continue
|
||||
|
||||
# 检测区域绝对原点行:**区域绝对原点**:(X, Y, Z)
|
||||
if "区域绝对原点" in line and current_zone:
|
||||
origin_match = re.search(r'\((\d+)\s*,\s*(\d+)\s*,\s*(\d+)\)', line)
|
||||
if origin_match and current_zone_info:
|
||||
current_zone_info.origin = (
|
||||
int(origin_match.group(1)),
|
||||
int(origin_match.group(2)),
|
||||
int(origin_match.group(3)),
|
||||
)
|
||||
|
||||
# 检测区域参数子标题
|
||||
if "区域参数" in line:
|
||||
i += 1
|
||||
i = self._skip_blank(section_lines, i)
|
||||
rows = self._read_table(section_lines, i)
|
||||
if rows:
|
||||
i = self._advance_past_table(section_lines, i)
|
||||
if current_zone_info:
|
||||
self._parse_zone_params(rows, current_zone_info)
|
||||
continue
|
||||
|
||||
# 检测结构体子标题
|
||||
if "结构体清单" in line:
|
||||
i += 1
|
||||
i = self._skip_blank(section_lines, i)
|
||||
rows = self._read_table(section_lines, i)
|
||||
if rows and current_zone:
|
||||
items = [self._parse_structure_row(r) for r in rows]
|
||||
items = [it for it in items if it]
|
||||
self.data.zone_structures[current_zone] = items
|
||||
i = self._advance_past_table(section_lines, i)
|
||||
continue
|
||||
|
||||
# 检测布景物子标题
|
||||
if "布景物清单" in line:
|
||||
i += 1
|
||||
i = self._skip_blank(section_lines, i)
|
||||
rows = self._read_table(section_lines, i)
|
||||
if rows and current_zone:
|
||||
items = [self._parse_prop_row(r) for r in rows]
|
||||
items = [it for it in items if it]
|
||||
self.data.zone_props[current_zone] = items
|
||||
i = self._advance_past_table(section_lines, i)
|
||||
continue
|
||||
|
||||
# 检测组合资产子标题
|
||||
if "组合资产标记" in line:
|
||||
i += 1
|
||||
i = self._skip_blank(section_lines, i)
|
||||
rows = self._read_table(section_lines, i)
|
||||
if rows and current_zone:
|
||||
items = [self._parse_composite_row(r) for r in rows]
|
||||
items = [it for it in items if it]
|
||||
self.data.zone_composites[current_zone] = items
|
||||
i = self._advance_past_table(section_lines, i)
|
||||
continue
|
||||
|
||||
i += 1
|
||||
|
||||
def _parse_zone_params(self, rows: list[dict], zone: ZoneInfo):
|
||||
"""解析区域参数表。"""
|
||||
for row in rows:
|
||||
param = clean_cell(row.get("参数", ""))
|
||||
value = clean_cell(row.get("值", ""))
|
||||
if "围墙" in param or "外墙高度" in param:
|
||||
m = re.search(r'(\d+)', value)
|
||||
if m:
|
||||
zone.wall_height = float(m.group(1))
|
||||
elif "门洞宽度" in param:
|
||||
m = re.search(r'(\d+)', value)
|
||||
if m:
|
||||
zone.door_width = float(m.group(1))
|
||||
elif "门洞高度" in param:
|
||||
m = re.search(r'(\d+)', value)
|
||||
if m:
|
||||
zone.door_height = float(m.group(1))
|
||||
elif "室内净高" in param:
|
||||
m = re.search(r'(\d+)', value)
|
||||
if m:
|
||||
zone.indoor_clear_height = float(m.group(1))
|
||||
elif "屋檐高度" in param:
|
||||
m = re.search(r'(\d+)', value)
|
||||
if m:
|
||||
zone.eaves_height = float(m.group(1))
|
||||
|
||||
def _parse_structure_row(self, row: dict) -> Optional[StructureItem]:
|
||||
"""解析结构体表行。"""
|
||||
item_id = clean_cell(row.get("编号", ""))
|
||||
name = clean_cell(row.get("构件名称", ""))
|
||||
if not item_id or not name:
|
||||
return None
|
||||
|
||||
size_str = clean_cell(row.get("尺寸 (宽x深x高, cm)", row.get("尺寸", "")))
|
||||
size = self._parse_size(size_str)
|
||||
|
||||
offset_str = clean_cell(row.get("相对原点偏移 (ΔX,ΔY,ΔZ)", row.get("相对原点偏移", "")))
|
||||
offset = self._parse_xyz(offset_str)
|
||||
|
||||
bsp = clean_cell(row.get("BSP 资产建议", ""))
|
||||
tag = clean_cell(row.get("标识色", ""))
|
||||
|
||||
return StructureItem(
|
||||
item_id=item_id, name=name, size=size,
|
||||
offset=offset, bsp_suggestion=bsp, tag_color=tag
|
||||
)
|
||||
|
||||
def _parse_prop_row(self, row: dict) -> Optional[PropItem]:
|
||||
"""解析布景表行。"""
|
||||
item_id = clean_cell(row.get("编号", ""))
|
||||
name = clean_cell(row.get("物件名称", ""))
|
||||
if not item_id or not name:
|
||||
return None
|
||||
|
||||
size_str = clean_cell(row.get("尺寸 (约, cm)", row.get("尺寸", "")))
|
||||
size = self._parse_size(size_str)
|
||||
|
||||
offset_str = clean_cell(row.get("相对原点偏移 (ΔX,ΔY,ΔZ)", row.get("相对原点偏移", "")))
|
||||
offset = self._parse_xyz(offset_str)
|
||||
|
||||
bsp = clean_cell(row.get("BSP 资产建议", ""))
|
||||
note = clean_cell(row.get("说明", ""))
|
||||
|
||||
return PropItem(
|
||||
item_id=item_id, name=name, size=size,
|
||||
offset=offset, bsp_suggestion=bsp, note=note
|
||||
)
|
||||
|
||||
def _parse_composite_row(self, row: dict) -> Optional[CompositeItem]:
|
||||
"""解析组合资产表行。"""
|
||||
item_id = clean_cell(row.get("编号", ""))
|
||||
name = clean_cell(row.get("物件名称", ""))
|
||||
if not item_id or not name:
|
||||
return None
|
||||
|
||||
size_str = clean_cell(row.get("期望尺寸 (约, cm)", row.get("期望尺寸", "")))
|
||||
size = self._parse_size(size_str)
|
||||
|
||||
plan = clean_cell(row.get("推荐拼搭方案", ""))
|
||||
note = clean_cell(row.get("说明", ""))
|
||||
|
||||
return CompositeItem(
|
||||
item_id=item_id, name=name, target_size=size,
|
||||
build_plan=plan, note=note
|
||||
)
|
||||
|
||||
# ----------------------------------------------------------
|
||||
# 四、全局物件清单
|
||||
# ----------------------------------------------------------
|
||||
def _parse_global_objects(self, lines: list[str]):
|
||||
"""解析全局物件清单。"""
|
||||
section_start = self._find_section(lines, "四、全局物件清单")
|
||||
section_end = self._find_section(lines, "五、场景边界")
|
||||
if section_start < 0:
|
||||
return
|
||||
if section_end < 0:
|
||||
section_end = len(lines)
|
||||
|
||||
section_lines = lines[section_start:section_end]
|
||||
tables = self._extract_tables(section_lines)
|
||||
|
||||
for table in tables:
|
||||
for row in table:
|
||||
item_id = clean_cell(row.get("编号", ""))
|
||||
name = clean_cell(row.get("物件名称", ""))
|
||||
if not item_id or not name:
|
||||
continue
|
||||
|
||||
count_str = clean_cell(row.get("数量", "1"))
|
||||
c_match = re.search(r'(\d+)', count_str)
|
||||
count = int(c_match.group(1)) if c_match else 1
|
||||
|
||||
loc_str = clean_cell(row.get("放置位置 (绝对坐标 X,Y,Z)", row.get("放置位置", "")))
|
||||
location = self._parse_xyz(loc_str)
|
||||
|
||||
bsp = clean_cell(row.get("BSP 资产建议", ""))
|
||||
note = clean_cell(row.get("说明", ""))
|
||||
|
||||
self.data.global_objects.append(GlobalObject(
|
||||
item_id=item_id, name=name, count=count,
|
||||
location=location, bsp_suggestion=bsp, note=note
|
||||
))
|
||||
|
||||
# ----------------------------------------------------------
|
||||
# 五、场景边界与遮挡
|
||||
# ----------------------------------------------------------
|
||||
def _parse_boundaries(self, lines: list[str]):
|
||||
"""解析场景边界表。"""
|
||||
section_start = self._find_section(lines, "五、场景边界")
|
||||
section_end = self._find_section(lines, "六、光照建议")
|
||||
if section_start < 0:
|
||||
return
|
||||
if section_end < 0:
|
||||
section_end = len(lines)
|
||||
|
||||
section_lines = lines[section_start:section_end]
|
||||
tables = self._extract_tables(section_lines)
|
||||
|
||||
if tables:
|
||||
for row in tables[0]:
|
||||
segment = clean_cell(row.get("边界段", ""))
|
||||
if not segment:
|
||||
continue
|
||||
loc_range = clean_cell(row.get("位置范围", ""))
|
||||
method = clean_cell(row.get("遮挡方式", ""))
|
||||
bsp = clean_cell(row.get("BSP 资产建议", ""))
|
||||
tag = clean_cell(row.get("标识色", ""))
|
||||
self.data.boundaries.append(BoundaryItem(
|
||||
segment=segment, location_range=loc_range,
|
||||
block_method=method, bsp_suggestion=bsp, tag_color=tag
|
||||
))
|
||||
|
||||
# ----------------------------------------------------------
|
||||
# 六、光照建议
|
||||
# ----------------------------------------------------------
|
||||
def _parse_lighting(self, lines: list[str]):
|
||||
"""解析光照建议表。"""
|
||||
section_start = self._find_section(lines, "六、光照建议")
|
||||
if section_start < 0:
|
||||
return
|
||||
|
||||
section_lines = lines[section_start:]
|
||||
tables = self._extract_tables(section_lines)
|
||||
|
||||
if tables:
|
||||
for row in tables[0]:
|
||||
light_type = clean_cell(row.get("光源类型", ""))
|
||||
if not light_type:
|
||||
continue
|
||||
count_str = clean_cell(row.get("数量", "1"))
|
||||
c_match = re.search(r'(\d+)', count_str)
|
||||
count = int(c_match.group(1)) if c_match else 1
|
||||
position = clean_cell(row.get("位置/方向", ""))
|
||||
params = clean_cell(row.get("参数建议", ""))
|
||||
note = clean_cell(row.get("说明", ""))
|
||||
self.data.lights.append(LightItem(
|
||||
light_type=light_type, count=count,
|
||||
position=position, params=params, note=note
|
||||
))
|
||||
|
||||
# ----------------------------------------------------------
|
||||
# 辅助方法
|
||||
# ----------------------------------------------------------
|
||||
def _find_section(self, lines: list[str], keyword: str) -> int:
|
||||
"""找到包含关键词的章节标题行。"""
|
||||
for i, line in enumerate(lines):
|
||||
if keyword in line:
|
||||
return i
|
||||
return -1
|
||||
|
||||
def _find_zone(self, zone_id: str) -> Optional[ZoneInfo]:
|
||||
"""查找区域信息。"""
|
||||
for z in self.data.zones:
|
||||
if z.zone_id == zone_id:
|
||||
return z
|
||||
return None
|
||||
|
||||
def _extract_tables(self, lines: list[str]) -> list[list[dict]]:
|
||||
"""从行列表中提取所有表格。"""
|
||||
tables = []
|
||||
i = 0
|
||||
while i < len(lines):
|
||||
if '|' in lines[i]:
|
||||
table_lines = []
|
||||
while i < len(lines) and '|' in lines[i]:
|
||||
table_lines.append(lines[i])
|
||||
i += 1
|
||||
rows = parse_table(table_lines)
|
||||
if rows:
|
||||
tables.append(rows)
|
||||
continue
|
||||
i += 1
|
||||
return tables
|
||||
|
||||
def _skip_blank(self, lines: list[str], i: int) -> int:
|
||||
"""跳过空行,返回第一个非空行的索引。"""
|
||||
while i < len(lines) and not lines[i].strip():
|
||||
i += 1
|
||||
return i
|
||||
|
||||
def _read_table(self, lines: list[str], i: int) -> list[dict]:
|
||||
"""从第 i 行开始读取一个 Markdown 表格。"""
|
||||
table_lines = []
|
||||
while i < len(lines) and '|' in lines[i]:
|
||||
table_lines.append(lines[i])
|
||||
i += 1
|
||||
if not table_lines:
|
||||
return []
|
||||
return parse_table(table_lines)
|
||||
|
||||
def _advance_past_table(self, lines: list[str], i: int) -> int:
|
||||
"""将索引推进到表格之后。"""
|
||||
while i < len(lines) and '|' in lines[i]:
|
||||
i += 1
|
||||
return i
|
||||
|
||||
def _parse_xyz(self, text: str) -> tuple:
|
||||
"""解析 (X,Y,Z) 或 (ΔX,ΔY,ΔZ) 格式。"""
|
||||
if not text:
|
||||
return (0, 0, 0)
|
||||
m = re.search(r'\(([-\d.]+)\s*[,,]\s*([-\d.]+)\s*[,,]\s*([-\d.]+)\)', text)
|
||||
if m:
|
||||
return (float(m.group(1)), float(m.group(2)), float(m.group(3)))
|
||||
return (0, 0, 0)
|
||||
|
||||
def _parse_size(self, text: str) -> tuple:
|
||||
"""解析 尺寸格式:宽x深x高。支持 '800x20x250' 或 '800×20×250'。"""
|
||||
if not text:
|
||||
return (0, 0, 0)
|
||||
m = re.search(r'(\d+(?:\.\d+)?)\s*[x×]\s*(\d+(?:\.\d+)?)\s*[x×]\s*(\d+(?:\.\d+)?)', text)
|
||||
if m:
|
||||
return (float(m.group(1)), float(m.group(2)), float(m.group(3)))
|
||||
return (0, 0, 0)
|
||||
@@ -0,0 +1,596 @@
|
||||
"""搭建指南 Markdown 生成器。
|
||||
|
||||
将 ActorSpec 列表转换为搭建指南 Markdown 文档。
|
||||
输出格式精确匹配 build_guide_parser.py 的解析预期。
|
||||
|
||||
搭建指南结构(8章):
|
||||
〇、全局信息(场景参数、路径前缀、命名规范、Outliner 结构)
|
||||
一、BSP 资产映射表
|
||||
二、Phase B 地面与边界
|
||||
三、Phase C 逐区域搭建
|
||||
四、Phase C 全局物件
|
||||
五、Phase D 光照
|
||||
六、Phase E 验证清单
|
||||
"""
|
||||
|
||||
import logging
|
||||
from dataclasses import asdict
|
||||
from pathlib import Path
|
||||
from typing import Optional
|
||||
|
||||
from execution_parser import (
|
||||
ExecutionPlanData, ZoneInfo, StructureItem, PropItem,
|
||||
CompositeItem, GlobalObject, BoundaryItem, LightItem,
|
||||
)
|
||||
from asset_expander import AssetExpander, ActorSpec
|
||||
|
||||
logger = logging.getLogger("execution_to_guide.writer")
|
||||
|
||||
|
||||
# ============================================================
|
||||
# 搭建指南生成器
|
||||
# ============================================================
|
||||
|
||||
class GuideWriter:
|
||||
"""搭建指南 Markdown 生成器。"""
|
||||
|
||||
def __init__(self, plan_data: ExecutionPlanData):
|
||||
"""
|
||||
Args:
|
||||
plan_data: 解析后的执行案数据
|
||||
"""
|
||||
self.plan = plan_data
|
||||
self.expander = AssetExpander(plan_data.zones)
|
||||
self.all_actors: list[ActorSpec] = []
|
||||
self.asset_refs: dict[str, dict] = {} # 用到的资产 key → info
|
||||
|
||||
def generate(self) -> str:
|
||||
"""生成完整的搭建指南 Markdown。"""
|
||||
sections = []
|
||||
|
||||
# 〇、全局信息
|
||||
sections.append(self._write_global_info())
|
||||
|
||||
# 一、BSP 资产映射表
|
||||
sections.append(self._write_asset_mapping())
|
||||
|
||||
# 二、Phase B — 地面与边界
|
||||
sections.append(self._write_ground_and_boundary())
|
||||
|
||||
# 三、Phase C — 逐区域搭建
|
||||
sections.append(self._write_zone_builds())
|
||||
|
||||
# 四、Phase C — 全局物件
|
||||
sections.append(self._write_global_objects())
|
||||
|
||||
# 五、Phase D — 光照
|
||||
sections.append(self._write_lighting())
|
||||
|
||||
# 六、Phase E — 验证清单
|
||||
sections.append(self._write_checklist())
|
||||
|
||||
return "\n\n".join(sections)
|
||||
|
||||
def write_to_file(self, filepath: str):
|
||||
"""生成并写入文件。"""
|
||||
content = self.generate()
|
||||
path = Path(filepath)
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
path.write_text(content, encoding="utf-8")
|
||||
logger.info(f"搭建指南已写入: {filepath}")
|
||||
|
||||
# ----------------------------------------------------------
|
||||
# 〇、全局信息
|
||||
# ----------------------------------------------------------
|
||||
def _write_global_info(self) -> str:
|
||||
"""生成全局信息章节。"""
|
||||
w, d = self.plan.scene_size
|
||||
lines = [
|
||||
f"# v{self.plan.version} 白模搭建操作指南 — {self.plan.scene_name}",
|
||||
"",
|
||||
f"> 本文档由 execution-to-guide 工具自动生成,供 level-builder 搭建白模关卡使用。",
|
||||
f"> 基于: 关卡-v{self.plan.version}-{self.plan.scene_name}-执行案.md",
|
||||
"",
|
||||
"---",
|
||||
"",
|
||||
"## 〇、全局信息",
|
||||
"",
|
||||
"### 场景参数",
|
||||
"",
|
||||
"| 参数 | 值 |",
|
||||
"|------|-----|",
|
||||
f"| 场景总尺寸 | {w}cm × {d}cm({w // 100}m × {d // 100}m) |",
|
||||
f"| 地面高度基准 | Z = {int(self.plan.ground_z)} |",
|
||||
f"| 主角身高 | ~{int(self.plan.character_height)}cm |",
|
||||
f"| 摄像机高度 | ~{int(self.plan.camera_height)}cm |",
|
||||
f"| 时间设定 | {self.plan.time_setting} |",
|
||||
"| 坐标原点 | 场景西南角地平面 |",
|
||||
"",
|
||||
"### UE5 路径前缀",
|
||||
"",
|
||||
"- **Mesh**: `Content/BlockingStarterPack/Meshes/`",
|
||||
"- **Material**: `Content/BlockingStarterPack/Materials/`",
|
||||
"- **Material (Basics)**: `Content/BlockingStarterPack/Materials/Blocking/Basics/`",
|
||||
"",
|
||||
"### 命名规范",
|
||||
"",
|
||||
"```",
|
||||
"LVL_<ZoneID>_<Category>_<Description>",
|
||||
"Category: STR | PROP | COMP | BND | LGT",
|
||||
"```",
|
||||
"",
|
||||
"### Outliner 文件夹结构",
|
||||
"",
|
||||
"```",
|
||||
f"LVL_{self._level_slug()}/",
|
||||
]
|
||||
|
||||
for zone in self.plan.zones:
|
||||
zone_slug = f"{zone.zone_id}_{zone.zone_name}"
|
||||
lines.append(f" {zone_slug}/")
|
||||
lines.append(" Structure/ Props/")
|
||||
|
||||
lines.append(" Global/")
|
||||
lines.append(" Boundaries/ Lighting/ PlayerStart/")
|
||||
lines.append("```")
|
||||
|
||||
return "\n".join(lines)
|
||||
|
||||
# ----------------------------------------------------------
|
||||
# 一、BSP 资产映射表
|
||||
# ----------------------------------------------------------
|
||||
def _write_asset_mapping(self) -> str:
|
||||
"""收集用到的所有资产,生成映射表。"""
|
||||
# 先展开所有 Actor 以收集资产引用
|
||||
self._collect_all_actors()
|
||||
|
||||
lines = [
|
||||
"---",
|
||||
"",
|
||||
"## 一、BSP 资产映射表",
|
||||
"",
|
||||
]
|
||||
|
||||
# 按类别分组
|
||||
categories = {}
|
||||
for key, info in self.asset_refs.items():
|
||||
cat = info.get("category", "other")
|
||||
if cat not in categories:
|
||||
categories[cat] = []
|
||||
categories[cat].append((key, info))
|
||||
|
||||
# 类别标题映射
|
||||
cat_titles = {
|
||||
"wall": "建筑 — 墙体",
|
||||
"wall_door": "建筑 — 门墙",
|
||||
"wall_window": "建筑 — 窗墙",
|
||||
"floor": "建筑 — 地板",
|
||||
"door": "建筑 — 门",
|
||||
"window": "建筑 — 窗户",
|
||||
"barrier": "建筑 — 围挡",
|
||||
"fence": "建筑 — 围栏",
|
||||
"beam": "建筑 — 横梁",
|
||||
"building": "建筑 — 大型建筑",
|
||||
"furniture": "家具",
|
||||
"industrial": "工业/装饰",
|
||||
"vehicle": "载具",
|
||||
"primitive": "基础体",
|
||||
"vegetation": "植被",
|
||||
"light_fixture": "灯具",
|
||||
"decoration": "装饰",
|
||||
"other": "其他",
|
||||
}
|
||||
|
||||
for cat_key in ["wall", "wall_door", "wall_window", "floor", "door", "window",
|
||||
"barrier", "fence", "beam", "building", "furniture",
|
||||
"industrial", "vehicle", "vegetation", "light_fixture",
|
||||
"decoration", "other"]:
|
||||
if cat_key not in categories:
|
||||
continue
|
||||
items = categories[cat_key]
|
||||
title = cat_titles.get(cat_key, cat_key)
|
||||
|
||||
lines.append(f"### {title}")
|
||||
lines.append("")
|
||||
lines.append("| 设计文档引用 | UE5 资产路径 | 实际尺寸 (cm) |")
|
||||
lines.append("|-------------|-------------|--------------|")
|
||||
|
||||
for key, info in items:
|
||||
path_short = info.get("path", "")
|
||||
# 缩短路径显示
|
||||
if path_short.startswith("/Game/BlockingStarterPack/Meshes/"):
|
||||
path_short = path_short.replace("/Game/BlockingStarterPack/Meshes/", "")
|
||||
path_short = path_short.split(".")[0] # 去掉 .SM_xxx 后缀
|
||||
|
||||
bounds = info.get("actual_bounds", ((0, 0, 0), (0, 0, 0)))
|
||||
size_str = self._format_bounds_size(bounds)
|
||||
|
||||
lines.append(f"| {key} | `{path_short}` | {size_str} |")
|
||||
|
||||
lines.append("")
|
||||
|
||||
return "\n".join(lines)
|
||||
|
||||
# ----------------------------------------------------------
|
||||
# 二、Phase B — 地面与边界
|
||||
# ----------------------------------------------------------
|
||||
def _write_ground_and_boundary(self) -> str:
|
||||
"""生成地面铺设和边界围挡。"""
|
||||
lines = [
|
||||
"---",
|
||||
"",
|
||||
"## 二、Phase B — 地面与边界",
|
||||
"",
|
||||
"### B1. 铺设地面",
|
||||
"",
|
||||
]
|
||||
|
||||
# 全局地面
|
||||
w, d = self.plan.scene_size
|
||||
lines.append("#### 全局地面(MI_DevGray)")
|
||||
lines.append("")
|
||||
lines.append("| # | Actor 名称 | 资产 | 位置 (X,Y,Z) | 缩放 | 材质 |")
|
||||
lines.append("|---|-----------|------|-------------|------|------|")
|
||||
|
||||
# 用 Floor_1000x1000 铺满
|
||||
tiles_x = max(1, w // 1000)
|
||||
tiles_y = max(1, d // 1000)
|
||||
seq = 1
|
||||
for tx in range(tiles_x):
|
||||
for ty in range(tiles_y):
|
||||
cx = tx * 1000 + 500
|
||||
cy = ty * 1000 + 500
|
||||
lines.append(
|
||||
f"| {seq} | LVL_Global_STR_GroundFloor_{seq:02d} | Floor_1000x1000 | "
|
||||
f"({cx},{cy},{int(self.plan.ground_z)}) | — | MI_DevGray |"
|
||||
)
|
||||
seq += 1
|
||||
|
||||
lines.append("")
|
||||
|
||||
# 边界围挡
|
||||
lines.append("### B2. 放置边界围挡")
|
||||
lines.append("")
|
||||
|
||||
for boundary in self.plan.boundaries:
|
||||
seg = boundary.segment
|
||||
lines.append(f"#### {seg}")
|
||||
lines.append("")
|
||||
lines.append("| # | Actor 名称 | 资产 | 位置 (X,Y,Z) | 旋转 (P,Y,R) | 缩放 | 材质 |")
|
||||
lines.append("|---|-----------|------|-------------|-------------|------|------|")
|
||||
|
||||
# 根据边界方向生成围挡
|
||||
bnd_actors = self._generate_boundary_actors(boundary)
|
||||
for i, actor in enumerate(bnd_actors):
|
||||
rot_str = self._fmt_rotation(actor.rotation)
|
||||
scale_str = self._fmt_scale(actor.scale)
|
||||
lines.append(
|
||||
f"| {i + 1} | {actor.actor_name} | {actor.asset_key} | "
|
||||
f"{self._fmt_location(actor.location)} | {rot_str} | {scale_str} | "
|
||||
f"{actor.material} |"
|
||||
)
|
||||
lines.append("")
|
||||
|
||||
return "\n".join(lines)
|
||||
|
||||
def _generate_boundary_actors(self, boundary: BoundaryItem) -> list[ActorSpec]:
|
||||
"""根据边界描述生成围挡 Actor。"""
|
||||
w, d = self.plan.scene_size
|
||||
actors = []
|
||||
|
||||
# 确定边界的起止坐标和方向
|
||||
if "西" in boundary.segment:
|
||||
# X=0, 沿 Y 轴
|
||||
x, y_start, y_end = 0, 0, d
|
||||
yaw = 90.0
|
||||
elif "东" in boundary.segment:
|
||||
x, y_start, y_end = w, 0, d
|
||||
yaw = 90.0
|
||||
elif "南" in boundary.segment:
|
||||
x_start, x_end, y = 0, w, 0
|
||||
yaw = 0.0
|
||||
elif "北" in boundary.segment:
|
||||
x_start, x_end, y = 0, w, d
|
||||
yaw = 0.0
|
||||
else:
|
||||
return []
|
||||
|
||||
# 使用 BarrierWall_600 或 Wall_400x300
|
||||
asset_key = "BarrierWall_600"
|
||||
wall_len = 600 # cm
|
||||
|
||||
seq = 1
|
||||
if "西" in boundary.segment or "东" in boundary.segment:
|
||||
length = y_end - y_start
|
||||
count = max(1, int(length / wall_len))
|
||||
for i in range(count):
|
||||
y_pos = y_start + i * wall_len + wall_len // 2
|
||||
z_pos = 105 # 半高
|
||||
actors.append(ActorSpec(
|
||||
actor_name=f"LVL_Global_BND_{boundary.segment}_{seq:02d}",
|
||||
asset_key=asset_key,
|
||||
asset_path="",
|
||||
location=(x, y_pos, z_pos),
|
||||
rotation=(0.0, yaw, 0.0),
|
||||
scale=(1.0, 1.0, 1.0),
|
||||
material=boundary.tag_color or "MI_DevBrown",
|
||||
material_path="",
|
||||
category="BND",
|
||||
zone_id="GLOBAL",
|
||||
folder="LVL_Level/Global/Boundaries",
|
||||
))
|
||||
seq += 1
|
||||
else:
|
||||
length = x_end - x_start
|
||||
count = max(1, int(length / wall_len))
|
||||
for i in range(count):
|
||||
x_pos = x_start + i * wall_len + wall_len // 2
|
||||
y_pos = y
|
||||
z_pos = 105
|
||||
actors.append(ActorSpec(
|
||||
actor_name=f"LVL_Global_BND_{boundary.segment}_{seq:02d}",
|
||||
asset_key=asset_key,
|
||||
asset_path="",
|
||||
location=(x_pos, y_pos, z_pos),
|
||||
rotation=(0.0, yaw, 0.0),
|
||||
scale=(1.0, 1.0, 1.0),
|
||||
material=boundary.tag_color or "MI_DevBrown",
|
||||
material_path="",
|
||||
category="BND",
|
||||
zone_id="GLOBAL",
|
||||
folder="LVL_Level/Global/Boundaries",
|
||||
))
|
||||
seq += 1
|
||||
|
||||
return actors
|
||||
|
||||
# ----------------------------------------------------------
|
||||
# 三、Phase C — 逐区域搭建
|
||||
# ----------------------------------------------------------
|
||||
def _write_zone_builds(self) -> str:
|
||||
"""生成逐区域搭建章节。"""
|
||||
lines = [
|
||||
"---",
|
||||
"",
|
||||
"## 三、Phase C — 逐区域搭建",
|
||||
"",
|
||||
]
|
||||
|
||||
for idx, zone in enumerate(self.plan.zones, 1):
|
||||
lines.append(f"### C{idx}. {zone.zone_id} — {zone.zone_name}")
|
||||
lines.append("")
|
||||
|
||||
# 结构体
|
||||
structures = self.plan.zone_structures.get(zone.zone_id, [])
|
||||
if structures:
|
||||
lines.append(f"#### C{idx}.1 结构体(Structure)")
|
||||
lines.append("")
|
||||
lines.append("| # | Actor 名称 | 资产 | 位置 (X,Y,Z) | 旋转 (P,Y,R) | 缩放 | 材质 |")
|
||||
lines.append("|---|-----------|------|-------------|-------------|------|------|")
|
||||
|
||||
for item in structures:
|
||||
actors = self.expander.expand_structure(item, zone.zone_id)
|
||||
for actor in actors:
|
||||
rot_str = self._fmt_rotation(actor.rotation)
|
||||
scale_str = self._fmt_scale(actor.scale)
|
||||
lines.append(
|
||||
f"| | {actor.actor_name} | {actor.asset_key} | "
|
||||
f"{self._fmt_location(actor.location)} | {rot_str} | {scale_str} | "
|
||||
f"{actor.material} |"
|
||||
)
|
||||
self._track_asset(actor)
|
||||
lines.append("")
|
||||
|
||||
# 布景
|
||||
props = self.plan.zone_props.get(zone.zone_id, [])
|
||||
if props:
|
||||
lines.append(f"#### C{idx}.2 布景物(Props)")
|
||||
lines.append("")
|
||||
lines.append("| # | Actor 名称 | 资产 | 位置 (X,Y,Z) | 缩放 | 材质 | 说明 |")
|
||||
lines.append("|---|-----------|------|-------------|------|------|------|")
|
||||
|
||||
for item in props:
|
||||
actors = self.expander.expand_prop(item, zone.zone_id)
|
||||
for actor in actors:
|
||||
scale_str = self._fmt_scale(actor.scale)
|
||||
lines.append(
|
||||
f"| | {actor.actor_name} | {actor.asset_key} | "
|
||||
f"{self._fmt_location(actor.location)} | {scale_str} | "
|
||||
f"{actor.material} | {actor.note} |"
|
||||
)
|
||||
self._track_asset(actor)
|
||||
lines.append("")
|
||||
|
||||
# 组合资产(如有)
|
||||
composites = self.plan.zone_composites.get(zone.zone_id, [])
|
||||
if composites:
|
||||
lines.append(f"#### C{idx}.3 组合资产(Composite)")
|
||||
lines.append("")
|
||||
lines.append("| # | Actor 名称 | Primitives | 位置 (X,Y,Z) | 缩放 | 材质 | 说明 |")
|
||||
lines.append("|---|-----------|-----------|-------------|------|------|------|")
|
||||
for comp in composites:
|
||||
lines.append(
|
||||
f"| | ⚠️ {comp.name} | {comp.build_plan} | "
|
||||
f"(待展开) | — | — | {comp.note} |"
|
||||
)
|
||||
lines.append("")
|
||||
|
||||
return "\n".join(lines)
|
||||
|
||||
# ----------------------------------------------------------
|
||||
# 四、全局物件
|
||||
# ----------------------------------------------------------
|
||||
def _write_global_objects(self) -> str:
|
||||
"""生成全局物件章节。"""
|
||||
lines = [
|
||||
"---",
|
||||
"",
|
||||
"## 四、Phase C — 全局物件",
|
||||
"",
|
||||
]
|
||||
|
||||
if not self.plan.global_objects:
|
||||
lines.append("> 无全局物件。")
|
||||
return "\n".join(lines)
|
||||
|
||||
lines.append("| # | Actor 名称 | 资产 | 位置 (X,Y,Z) | 缩放 | 材质 | 说明 |")
|
||||
lines.append("|---|-----------|------|-------------|------|------|------|")
|
||||
|
||||
for item in self.plan.global_objects:
|
||||
actors = self.expander.expand_global(item)
|
||||
for actor in actors:
|
||||
scale_str = self._fmt_scale(actor.scale)
|
||||
lines.append(
|
||||
f"| | {actor.actor_name} | {actor.asset_key} | "
|
||||
f"{self._fmt_location(actor.location)} | {scale_str} | "
|
||||
f"{actor.material} | {actor.note} |"
|
||||
)
|
||||
self._track_asset(actor)
|
||||
|
||||
return "\n".join(lines)
|
||||
|
||||
# ----------------------------------------------------------
|
||||
# 五、光照
|
||||
# ----------------------------------------------------------
|
||||
def _write_lighting(self) -> str:
|
||||
"""生成光照章节。"""
|
||||
lines = [
|
||||
"---",
|
||||
"",
|
||||
"## 五、Phase D — 光照",
|
||||
"",
|
||||
]
|
||||
|
||||
for light in self.plan.lights:
|
||||
if "定向" in light.light_type or "Directional" in light.light_type:
|
||||
lines.append("### D1. 定向光(Directional Light)")
|
||||
lines.append("")
|
||||
lines.append("| 类型 | 位置/方向 | 参数 |")
|
||||
lines.append("|------|---------|------|")
|
||||
lines.append(f"| Directional Light | {light.position} | {light.params} |")
|
||||
lines.append(f"> {light.note}")
|
||||
lines.append("")
|
||||
|
||||
elif "天空" in light.light_type or "Sky" in light.light_type:
|
||||
lines.append("### D2. 天空光(Sky Light)")
|
||||
lines.append("")
|
||||
lines.append("| 类型 | 位置/方向 | 参数 |")
|
||||
lines.append("|------|---------|------|")
|
||||
lines.append(f"| Sky Light | 全局 | {light.params} |")
|
||||
lines.append(f"> {light.note}")
|
||||
lines.append("")
|
||||
|
||||
elif "路灯" in light.light_type or "点光" in light.light_type:
|
||||
lines.append("### D3. 路灯点光源")
|
||||
lines.append("")
|
||||
lines.append(f"> {light.note},数量: {light.count}")
|
||||
lines.append("")
|
||||
|
||||
return "\n".join(lines)
|
||||
|
||||
# ----------------------------------------------------------
|
||||
# 六、验证清单
|
||||
# ----------------------------------------------------------
|
||||
def _write_checklist(self) -> str:
|
||||
"""生成验证清单章节。"""
|
||||
total = len(self.all_actors)
|
||||
zones = len(self.plan.zones)
|
||||
|
||||
lines = [
|
||||
"---",
|
||||
"",
|
||||
"## 六、Phase E — 验证清单",
|
||||
"",
|
||||
"| # | 检查项 | 状态 |",
|
||||
"|---|--------|------|",
|
||||
f"| 1 | 场景尺寸 {self.plan.scene_size[0]}×{self.plan.scene_size[1]}cm 正确 | ⬜ |",
|
||||
f"| 2 | {zones} 个区域均已搭建 | ⬜ |",
|
||||
"| 3 | 所有边界围挡无缺口 | ⬜ |",
|
||||
"| 4 | 玩家起点可到达 | ⬜ |",
|
||||
"| 5 | 所有区域可通行 | ⬜ |",
|
||||
"| 6 | 建筑入口与流线对齐 | ⬜ |",
|
||||
"| 7 | 光照方向与场景一致 | ⬜ |",
|
||||
f"| 8 | Actor 总数: {total} | ⬜ |",
|
||||
"",
|
||||
"---",
|
||||
"",
|
||||
f"> 搭建指南生成完成。共 {zones} 个区域,{total} 个 Actor。",
|
||||
]
|
||||
|
||||
return "\n".join(lines)
|
||||
|
||||
# ----------------------------------------------------------
|
||||
# 辅助方法
|
||||
# ----------------------------------------------------------
|
||||
def _collect_all_actors(self):
|
||||
"""收集所有区域的 Actor(用于资产映射表)。"""
|
||||
if self.all_actors:
|
||||
return # 已收集
|
||||
|
||||
# 结构体
|
||||
for zone_id, items in self.plan.zone_structures.items():
|
||||
for item in items:
|
||||
actors = self.expander.expand_structure(item, zone_id)
|
||||
self.all_actors.extend(actors)
|
||||
for a in actors:
|
||||
self._track_asset(a)
|
||||
|
||||
# 布景
|
||||
for zone_id, items in self.plan.zone_props.items():
|
||||
for item in items:
|
||||
actors = self.expander.expand_prop(item, zone_id)
|
||||
self.all_actors.extend(actors)
|
||||
for a in actors:
|
||||
self._track_asset(a)
|
||||
|
||||
# 全局物件
|
||||
for item in self.plan.global_objects:
|
||||
actors = self.expander.expand_global(item)
|
||||
self.all_actors.extend(actors)
|
||||
for a in actors:
|
||||
self._track_asset(a)
|
||||
|
||||
def _track_asset(self, actor: ActorSpec):
|
||||
"""跟踪用到的资产。"""
|
||||
if actor.asset_key and actor.asset_key not in self.asset_refs:
|
||||
try:
|
||||
from config.asset_mapping import MESH_ASSETS
|
||||
info = MESH_ASSETS.get(actor.asset_key, {})
|
||||
except ImportError:
|
||||
info = {}
|
||||
self.asset_refs[actor.asset_key] = info
|
||||
|
||||
def _level_slug(self) -> str:
|
||||
"""生成关卡标识符。"""
|
||||
name = self.plan.scene_name.replace(" ", "")
|
||||
return name
|
||||
|
||||
@staticmethod
|
||||
def _fmt_location(loc: tuple) -> str:
|
||||
"""格式化位置。"""
|
||||
return f"({int(loc[0])},{int(loc[1])},{int(loc[2])})"
|
||||
|
||||
@staticmethod
|
||||
def _fmt_rotation(rot: tuple) -> str:
|
||||
"""格式化旋转。"""
|
||||
if rot == (0, 0, 0):
|
||||
return "—"
|
||||
return f"({int(rot[0])},{int(rot[1])},{int(rot[2])})"
|
||||
|
||||
@staticmethod
|
||||
def _fmt_scale(scale: tuple) -> str:
|
||||
"""格式化缩放。"""
|
||||
if scale == (1, 1, 1):
|
||||
return "—"
|
||||
return f"({scale[0]:.2f},{scale[1]:.2f},{scale[2]:.2f})"
|
||||
|
||||
@staticmethod
|
||||
def _format_bounds_size(bounds) -> str:
|
||||
"""格式化包围盒尺寸。"""
|
||||
if not bounds or len(bounds) < 2:
|
||||
return "—"
|
||||
mn, mx = bounds[0], bounds[1]
|
||||
w = mx[0] - mn[0] if len(mx) > 0 else 0
|
||||
d = mx[1] - mn[1] if len(mx) > 1 else 0
|
||||
h = mx[2] - mn[2] if len(mx) > 2 else 0
|
||||
return f"{int(w)}×{int(d)}×{int(h)}"
|
||||
@@ -1,20 +1,19 @@
|
||||
"""UE5 编辑器 Python 脚本:创建 v0.1 角色控制所需的 InputAction 资产并更新 IMC。
|
||||
|
||||
由 setup_input.bat 通过 UE5 的 -ExecutePythonScript 参数调用。
|
||||
在 UE5 编辑器 Python 环境中运行。
|
||||
使用方式:
|
||||
方式1 — 在编辑器 Python 控制台运行:
|
||||
py "E:/MiceCola/work/ChildHood/tools/input-setup/setup_input_assets.py"
|
||||
方式2 — 通过 setup_input.bat 启动编辑器执行
|
||||
|
||||
功能:
|
||||
1. 创建 3 个 InputAction 资产:IA_Interact, IA_Cancel, IA_SwitchInteract
|
||||
2. 更新 IMC_Default:添加 E / ESC / Tab 按键映射
|
||||
2. 尝试更新 IMC_Default:添加 E / ESC / Tab 按键映射
|
||||
3. 保存所有修改的资产
|
||||
|
||||
环境变量(由 setup_input.bat 设置):
|
||||
INPUT_PROJECT_ROOT — 项目根目录绝对路径
|
||||
"""
|
||||
|
||||
import os
|
||||
import sys
|
||||
from pathlib import Path
|
||||
import traceback
|
||||
|
||||
# ---- 检查 unreal 模块 ----
|
||||
try:
|
||||
@@ -23,36 +22,54 @@ except ImportError:
|
||||
print("[InputSetup] FATAL: unreal 模块不可用,必须在 UE5 编辑器环境中运行")
|
||||
sys.exit(1)
|
||||
|
||||
# ---- 项目根目录 ----
|
||||
_project_root_str = os.environ.get("INPUT_PROJECT_ROOT", "")
|
||||
if _project_root_str:
|
||||
PROJECT_ROOT = Path(_project_root_str)
|
||||
else:
|
||||
print("[InputSetup] FATAL: INPUT_PROJECT_ROOT 环境变量未设置")
|
||||
sys.exit(1)
|
||||
|
||||
# ---- 资产路径配置 ----
|
||||
IA_PACKAGE = "/Game/Input/Actions"
|
||||
IMC_PATH = "/Game/Input/IMC_Default"
|
||||
TEMPLATE_IA = f"{IA_PACKAGE}/IA_Look" # 用已存在的 IA 作为复制模板
|
||||
|
||||
# 新增 InputAction 定义
|
||||
NEW_INPUT_ACTIONS = {
|
||||
"IA_Interact": {
|
||||
"description": "E 键交互输入动作",
|
||||
"key": unreal.Key.E,
|
||||
"triggers": [unreal.InputTriggerDown()],
|
||||
},
|
||||
"IA_Cancel": {
|
||||
"description": "ESC 取消输入动作",
|
||||
"key": unreal.Key.ESCAPE,
|
||||
"triggers": [unreal.InputTriggerDown()],
|
||||
},
|
||||
"IA_SwitchInteract": {
|
||||
"description": "Tab 切换交互目标输入动作",
|
||||
"key": unreal.Key.TAB,
|
||||
"triggers": [unreal.InputTriggerDown()],
|
||||
},
|
||||
}
|
||||
# 新增 InputAction 定义(key_name 为字符串,运行时解析)
|
||||
NEW_INPUT_ACTIONS = [
|
||||
{"name": "IA_Interact", "desc": "E 键交互输入动作", "key_name": "E"},
|
||||
{"name": "IA_Cancel", "desc": "ESC 取消输入动作", "key_name": "Escape"},
|
||||
{"name": "IA_SwitchInteract", "desc": "Tab 切换交互目标", "key_name": "Tab"},
|
||||
]
|
||||
|
||||
# 按键名 → UE5 Key 对象的多种尝试路径
|
||||
KEY_RESOLVE_ORDER = ["E", "Escape", "Tab"]
|
||||
|
||||
|
||||
def resolve_key(key_name: str):
|
||||
"""尝试多种方式从 UE5 Python API 获取 Key 对象。
|
||||
|
||||
UE5 各版本的 Python 绑定对 Key 的暴露方式不同,
|
||||
这里依次尝试多种路径,找到可用的那一个。
|
||||
"""
|
||||
attempts = [
|
||||
# 方式1: unreal.Key 枚举属性 (如 unreal.Key.E, unreal.Key.Escape)
|
||||
lambda: getattr(unreal.Key, key_name),
|
||||
# 方式2: unreal.Keys 类 (部分版本用这个)
|
||||
lambda: getattr(unreal.Keys, key_name),
|
||||
# 方式3: 全大写 (如 ESCAPE, TAB)
|
||||
lambda: getattr(unreal.Key, key_name.upper()),
|
||||
lambda: getattr(unreal.Keys, key_name.upper()),
|
||||
# 方式4: KEY_ 前缀 (如 KEY_E, KEY_ESCAPE)
|
||||
lambda: getattr(unreal.Key, f"KEY_{key_name.upper()}"),
|
||||
lambda: getattr(unreal.Keys, f"KEY_{key_name.upper()}"),
|
||||
# 方式5: 构造函数 (部分版本支持从字符串构造)
|
||||
lambda: unreal.Key(key_name),
|
||||
]
|
||||
|
||||
for i, attempt in enumerate(attempts, 1):
|
||||
try:
|
||||
key = attempt()
|
||||
if key is not None:
|
||||
print(f"[InputSetup] Key('{key_name}') 解析成功 (方式{i})")
|
||||
return key
|
||||
except Exception:
|
||||
continue
|
||||
|
||||
print(f"[InputSetup] Key('{key_name}') 所有解析方式均失败")
|
||||
return None
|
||||
|
||||
|
||||
def asset_exists(asset_path: str) -> bool:
|
||||
@@ -60,161 +77,249 @@ def asset_exists(asset_path: str) -> bool:
|
||||
return unreal.EditorAssetLibrary.does_asset_exist(asset_path)
|
||||
|
||||
|
||||
def create_input_action(name: str, description: str) -> unreal.InputAction:
|
||||
"""创建 InputAction 资产"""
|
||||
def create_input_action_by_duplicate(name: str, desc: str) -> object:
|
||||
"""通过复制已有 IA 模板创建新 InputAction 资产。
|
||||
|
||||
这是最可靠的方式——不依赖 Factory 类的 Python 绑定。
|
||||
"""
|
||||
asset_path = f"{IA_PACKAGE}/{name}"
|
||||
|
||||
if asset_exists(asset_path):
|
||||
print(f"[InputSetup] 资产已存在,跳过创建: {asset_path}")
|
||||
print(f"[InputSetup] 已存在,跳过: {asset_path}")
|
||||
return unreal.load_asset(asset_path)
|
||||
|
||||
# 确保目录存在
|
||||
unreal.EditorAssetLibrary.make_directory(IA_PACKAGE)
|
||||
# 确保目标目录存在
|
||||
if not unreal.EditorAssetLibrary.does_directory_exist(IA_PACKAGE):
|
||||
unreal.EditorAssetLibrary.make_directory(IA_PACKAGE)
|
||||
|
||||
# 使用 AssetTools 创建
|
||||
asset_tools = unreal.get_editor_subsystem(unreal.EditorAssetSubsystem)
|
||||
if asset_tools:
|
||||
# 尝试通过 EditorAssetSubsystem 创建
|
||||
# 复制模板资产
|
||||
new_asset = unreal.EditorAssetLibrary.duplicate_asset(TEMPLATE_IA, asset_path)
|
||||
if new_asset:
|
||||
print(f"[InputSetup] 复制创建成功: {asset_path} — {desc}")
|
||||
return new_asset
|
||||
|
||||
print(f"[InputSetup] 复制创建失败: {name}")
|
||||
return None
|
||||
|
||||
|
||||
def create_input_action_by_factory(name: str, desc: str) -> object:
|
||||
"""通过 AssetTools + Factory 创建 InputAction(备用方案)。"""
|
||||
asset_path = f"{IA_PACKAGE}/{name}"
|
||||
|
||||
if asset_exists(asset_path):
|
||||
return unreal.load_asset(asset_path)
|
||||
|
||||
try:
|
||||
factory = unreal.InputActionFactory()
|
||||
new_asset = asset_tools.create_asset(name, IA_PACKAGE, unreal.InputAction, factory)
|
||||
if new_asset:
|
||||
print(f"[InputSetup] 创建成功: {asset_path} — {description}")
|
||||
return new_asset
|
||||
except Exception:
|
||||
print("[InputSetup] InputActionFactory 不可用")
|
||||
return None
|
||||
|
||||
# 备用方案:使用 Python BPLib 或直接构造
|
||||
print(f"[InputSetup] 尝试备用方案创建: {name}")
|
||||
factory = unreal.InputActionFactory()
|
||||
new_asset = unreal.AssetToolsHelpers.get_asset_tools().create_asset(
|
||||
name, IA_PACKAGE[5:], # 去掉 /Game/ 前缀
|
||||
asset_tools = unreal.AssetToolsHelpers.get_asset_tools()
|
||||
if not asset_tools:
|
||||
return None
|
||||
|
||||
# create_asset 的 package_path 需要去掉 /Game/ 前缀
|
||||
new_asset = asset_tools.create_asset(
|
||||
name,
|
||||
IA_PACKAGE[5:], # "Input/Actions"
|
||||
unreal.InputAction,
|
||||
factory
|
||||
)
|
||||
if new_asset:
|
||||
print(f"[InputSetup] 备用方案创建成功: {asset_path}")
|
||||
return new_asset
|
||||
print(f"[InputSetup] Factory 创建成功: {asset_path} — {desc}")
|
||||
return new_asset
|
||||
|
||||
print(f"[InputSetup] ERROR: 无法创建 {name}")
|
||||
|
||||
def create_input_action(name: str, desc: str) -> object:
|
||||
"""创建 InputAction 资产,依次尝试多种方法。"""
|
||||
asset_path = f"{IA_PACKAGE}/{name}"
|
||||
|
||||
# 已存在则直接加载
|
||||
if asset_exists(asset_path):
|
||||
print(f"[InputSetup] 已存在: {asset_path}")
|
||||
return unreal.load_asset(asset_path)
|
||||
|
||||
print(f"[InputSetup] 尝试创建: {name} — {desc}")
|
||||
|
||||
# 方法1: 复制已有模板(最可靠)
|
||||
result = create_input_action_by_duplicate(name, desc)
|
||||
if result:
|
||||
return result
|
||||
|
||||
# 方法2: Factory 创建
|
||||
result = create_input_action_by_factory(name, desc)
|
||||
if result:
|
||||
return result
|
||||
|
||||
print(f"[InputSetup] ERROR: 所有创建方法均失败: {name}")
|
||||
return None
|
||||
|
||||
|
||||
def add_key_mapping_to_imc(imc: unreal.InputMappingContext, ia: unreal.InputAction, key: unreal.Key):
|
||||
"""向 IMC 添加按键映射"""
|
||||
mapping = unreal.InputMapping()
|
||||
mapping.set_editor_property("action", ia)
|
||||
def try_update_imc(created_ias: dict) -> bool:
|
||||
"""尝试更新 IMC_Default 添加按键映射。
|
||||
|
||||
key_mapping = unreal.KeyMapping()
|
||||
key_mapping.set_editor_property("key", key)
|
||||
key_mapping.set_editor_property("scale", 1.0)
|
||||
|
||||
# 设置触发器
|
||||
# key_mapping 的 triggers 由 IMC 内部管理
|
||||
|
||||
# 使用 IMC 的 API 添加映射
|
||||
try:
|
||||
# UE5.7: 使用 mappings 属性
|
||||
existing_mappings = imc.get_editor_property("mappings")
|
||||
new_mapping = unreal.InputMapping()
|
||||
new_mapping.set_editor_property("action", ia)
|
||||
|
||||
km = unreal.KeyMapping()
|
||||
km.set_editor_property("key", key)
|
||||
km.set_editor_property("scale", 1.0)
|
||||
|
||||
# 设置 triggers
|
||||
triggers = [unreal.InputTriggerDown()]
|
||||
km.set_editor_property("triggers", triggers)
|
||||
new_mapping.set_editor_property("key_mappings", [km])
|
||||
|
||||
existing_mappings.append(new_mapping)
|
||||
imc.set_editor_property("mappings", existing_mappings)
|
||||
return True
|
||||
except Exception as e:
|
||||
print(f"[InputSetup] 添加映射失败: {e}")
|
||||
return False
|
||||
|
||||
|
||||
def main():
|
||||
print("=" * 50)
|
||||
print("[InputSetup] v0.1 角色控制 Input 资产创建脚本")
|
||||
print(f"[InputSetup] 项目: {PROJECT_ROOT}")
|
||||
print("=" * 50)
|
||||
|
||||
# ---- Step 1: 创建 InputAction 资产 ----
|
||||
print("\n[InputSetup] Step 1: 创建 InputAction 资产")
|
||||
created_ias = {}
|
||||
for name, config in NEW_INPUT_ACTIONS.items():
|
||||
ia = create_input_action(name, config["description"])
|
||||
if ia:
|
||||
created_ias[name] = ia
|
||||
else:
|
||||
print(f"[InputSetup] WARNING: {name} 创建失败,后续 IMC 映射将跳过此 IA")
|
||||
|
||||
if not created_ias:
|
||||
print("[InputSetup] ERROR: 没有成功创建任何 IA,终止")
|
||||
return False
|
||||
|
||||
# ---- Step 2: 保存新创建的 IA 资产 ----
|
||||
print("\n[InputSetup] Step 2: 保存新创建的资产")
|
||||
for name, ia in created_ias.items():
|
||||
asset_path = f"{IA_PACKAGE}/{name}"
|
||||
unreal.EditorAssetLibrary.save_asset(asset_path)
|
||||
print(f"[InputSetup] 已保存: {asset_path}")
|
||||
|
||||
# ---- Step 3: 更新 IMC_Default ----
|
||||
print(f"\n[InputSetup] Step 3: 更新 IMC: {IMC_PATH}")
|
||||
返回 True 表示成功,False 表示需要手动操作。
|
||||
由于 UE5 Python API 对 Enhanced Input 的暴露有限,
|
||||
此功能可能失败——失败时提供手动操作指引。
|
||||
"""
|
||||
print(f"[InputSetup] 加载 IMC: {IMC_PATH}")
|
||||
|
||||
if not asset_exists(IMC_PATH):
|
||||
print(f"[InputSetup] ERROR: IMC 不存在: {IMC_PATH}")
|
||||
print(f"[InputSetup] ERROR: IMC 不存在: {IMC_PATH}")
|
||||
return False
|
||||
|
||||
imc = unreal.load_asset(IMC_PATH)
|
||||
if not imc:
|
||||
print(f"[InputSetup] ERROR: 无法加载 IMC: {IMC_PATH}")
|
||||
print(f"[InputSetup] ERROR: 无法加载 IMC")
|
||||
return False
|
||||
|
||||
# 读取当前映射数量
|
||||
try:
|
||||
current_mappings = imc.get_editor_property("mappings")
|
||||
print(f"[InputSetup] 当前 IMC 映射数: {len(current_mappings)}")
|
||||
print(f"[InputSetup] 当前映射数: {len(current_mappings)}")
|
||||
except Exception as e:
|
||||
print(f"[InputSetup] WARNING: 无法读取映射: {e}")
|
||||
current_mappings = []
|
||||
print(f"[InputSetup] 无法读取 mappings 属性: {e}")
|
||||
return False
|
||||
|
||||
# 添加新映射
|
||||
for name, config in NEW_INPUT_ACTIONS.items():
|
||||
if name not in created_ias:
|
||||
# 解析所有需要的 Key
|
||||
key_map = {}
|
||||
for ia_info in NEW_INPUT_ACTIONS:
|
||||
if ia_info["name"] not in created_ias:
|
||||
continue
|
||||
key = resolve_key(ia_info["key_name"])
|
||||
if key is None:
|
||||
print(f"[InputSetup] 无法解析按键: {ia_info['key_name']},跳过 IMC 自动更新")
|
||||
return False
|
||||
key_map[ia_info["name"]] = key
|
||||
|
||||
# 尝试添加映射
|
||||
success_count = 0
|
||||
for ia_info in NEW_INPUT_ACTIONS:
|
||||
name = ia_info["name"]
|
||||
if name not in created_ias or name not in key_map:
|
||||
continue
|
||||
|
||||
ia = created_ias[name]
|
||||
key = config["key"]
|
||||
success = add_key_mapping_to_imc(imc, ia, key)
|
||||
if success:
|
||||
print(f"[InputSetup] 已添加映射: {name} → {key}")
|
||||
key = key_map[name]
|
||||
|
||||
try:
|
||||
new_mapping = unreal.InputMapping()
|
||||
new_mapping.set_editor_property("action", ia)
|
||||
|
||||
km = unreal.KeyMapping()
|
||||
km.set_editor_property("key", key)
|
||||
|
||||
# 尝试设置触发器(可能不支持)
|
||||
try:
|
||||
km.set_editor_property("triggers", [unreal.InputTriggerDown()])
|
||||
except Exception:
|
||||
pass # 触发器使用默认值
|
||||
|
||||
new_mapping.set_editor_property("key_mappings", [km])
|
||||
|
||||
current_mappings.append(new_mapping)
|
||||
imc.set_editor_property("mappings", current_mappings)
|
||||
success_count += 1
|
||||
print(f"[InputSetup] 映射已添加: {name} → {ia_info['key_name']}")
|
||||
except Exception as e:
|
||||
print(f"[InputSetup] 映射添加失败: {name} — {e}")
|
||||
return False
|
||||
|
||||
if success_count == len(created_ias):
|
||||
# 保存 IMC
|
||||
unreal.EditorAssetLibrary.save_asset(IMC_PATH)
|
||||
print(f"[InputSetup] IMC 已保存")
|
||||
return True
|
||||
|
||||
return False
|
||||
|
||||
|
||||
def main():
|
||||
print("=" * 60)
|
||||
print("[InputSetup] v0.1 角色控制 Input 资产创建脚本")
|
||||
print("=" * 60)
|
||||
|
||||
# ---- Step 1: 创建 InputAction 资产 ----
|
||||
print("\n[InputSetup] Step 1/4: 创建 InputAction 资产")
|
||||
print(f"[InputSetup] 模板: {TEMPLATE_IA}")
|
||||
|
||||
if not asset_exists(TEMPLATE_IA):
|
||||
print(f"[InputSetup] ERROR: 模板 IA 不存在: {TEMPLATE_IA}")
|
||||
print("[InputSetup] 可用 IA 资产:")
|
||||
# 尝试列出 Actions 目录下的资产作为替代
|
||||
try:
|
||||
assets = unreal.EditorAssetLibrary.list_assets(IA_PACKAGE)
|
||||
for a in assets:
|
||||
print(f"[InputSetup] {a}")
|
||||
except Exception:
|
||||
pass
|
||||
return False
|
||||
|
||||
created_ias = {}
|
||||
for ia_info in NEW_INPUT_ACTIONS:
|
||||
ia = create_input_action(ia_info["name"], ia_info["desc"])
|
||||
if ia:
|
||||
created_ias[ia_info["name"]] = ia
|
||||
else:
|
||||
print(f"[InputSetup] WARNING: 映射添加失败: {name}")
|
||||
print(f"[InputSetup] WARNING: {ia_info['name']} 创建失败")
|
||||
|
||||
# ---- Step 4: 保存 IMC ----
|
||||
print("\n[InputSetup] Step 4: 保存 IMC")
|
||||
unreal.EditorAssetLibrary.save_asset(IMC_PATH)
|
||||
print(f"[InputSetup] 已保存: {IMC_PATH}")
|
||||
if not created_ias:
|
||||
print("[InputSetup] ERROR: 没有成功创建任何 IA")
|
||||
return False
|
||||
|
||||
# ---- Step 5: 验证 ----
|
||||
print("\n[InputSetup] Step 5: 验证")
|
||||
try:
|
||||
updated_mappings = imc.get_editor_property("mappings")
|
||||
print(f"[InputSetup] 更新后 IMC 映射数: {len(updated_mappings)}")
|
||||
except:
|
||||
pass
|
||||
|
||||
# 验证 IA 资产
|
||||
for name in NEW_INPUT_ACTIONS:
|
||||
# ---- Step 2: 保存新创建的 IA 资产 ----
|
||||
print(f"\n[InputSetup] Step 2/4: 保存资产 ({len(created_ias)} 个)")
|
||||
for name in created_ias:
|
||||
asset_path = f"{IA_PACKAGE}/{name}"
|
||||
exists = asset_exists(asset_path)
|
||||
print(f"[InputSetup] {name}: {'✅ 存在' if exists else '❌ 不存在'}")
|
||||
unreal.EditorAssetLibrary.save_asset(asset_path)
|
||||
print(f"[InputSetup] 已保存: {asset_path}")
|
||||
|
||||
print("\n" + "=" * 50)
|
||||
print("[InputSetup] 完成!请在 UE5 编辑器中验证。")
|
||||
print("[InputSetup] 注意:需要在 BP_ChildHoodCharacter 中将新增 IA 属性指向对应资产")
|
||||
print("=" * 50)
|
||||
# ---- Step 3: 尝试更新 IMC ----
|
||||
print(f"\n[InputSetup] Step 3/4: 更新 IMC_Default")
|
||||
imc_ok = False
|
||||
try:
|
||||
imc_ok = try_update_imc(created_ias)
|
||||
except Exception as e:
|
||||
print(f"[InputSetup] IMC 更新异常: {e}")
|
||||
traceback.print_exc()
|
||||
|
||||
if not imc_ok:
|
||||
print("[InputSetup] ⚠️ IMC 自动更新未成功,需要手动操作(见下方指引)")
|
||||
|
||||
# ---- Step 4: 验证 ----
|
||||
print(f"\n[InputSetup] Step 4/4: 验证")
|
||||
all_ok = True
|
||||
for ia_info in NEW_INPUT_ACTIONS:
|
||||
asset_path = f"{IA_PACKAGE}/{ia_info['name']}"
|
||||
exists = asset_exists(asset_path)
|
||||
status = "✅" if exists else "❌"
|
||||
print(f"[InputSetup] {status} {ia_info['name']}")
|
||||
if not exists:
|
||||
all_ok = False
|
||||
|
||||
# ---- 总结 ----
|
||||
print("\n" + "=" * 60)
|
||||
if imc_ok:
|
||||
print("[InputSetup] ✅ 全部完成(IA 创建 + IMC 更新)")
|
||||
print("[InputSetup] ⚠️ 仍需手动:BP_ChildHoodCharacter → Details → Input → 绑定 IA 属性")
|
||||
else:
|
||||
print("[InputSetup] ⚠️ IA 资产已创建,IMC 需手动配置")
|
||||
print()
|
||||
print("[InputSetup] === 手动操作指引 ===")
|
||||
print()
|
||||
print("1. 打开 IMC_Default (Content/Input/IMC_Default)")
|
||||
print(" 添加 3 个映射:")
|
||||
for ia_info in NEW_INPUT_ACTIONS:
|
||||
print(f" - {ia_info['key_name']} → {ia_info['name']}")
|
||||
print()
|
||||
print("2. 打开 BP_ChildHoodCharacter (Content/BP/Character/)")
|
||||
print(" Details → Input → 设置以下属性:")
|
||||
print(" - Interact Action → IA_Interact")
|
||||
print(" - Cancel Action → IA_Cancel")
|
||||
print(" - Switch Interact Action → IA_SwitchInteract")
|
||||
print()
|
||||
print("=" * 60)
|
||||
|
||||
return True
|
||||
|
||||
|
||||
Reference in New Issue
Block a user