Files
BladeSmith/CLAUDE.md
T
starmen1265 c787beee89 docs: 完成测试文档和功能文档
- Task 11: 创建测试场景和验证
  - 创建 docs/tests/hammer-deformation-test-results.md
  - 包含4个测试用例模板
  - 包含性能数据表格和调试工具检查清单

- Task 13: 文档更新
  - 更新 CLAUDE.md 添加阶段1核心系统说明
  - 创建 docs/features/hammer-deformation-system.md
  - 更新架构概览、数据流、关键类关系

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2026-01-23 22:50:20 +08:00

260 lines
10 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# CLAUDE.md
This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository.
## Project Overview
BladeSmith is an Unreal Engine 5.6 C++ blacksmith simulation game where players forge bladed weapons through realistic physical processes. The core feature is GPU-accelerated plastic deformation of metal using compute shaders, combined with a voxel-based temperature system that determines material plasticity.
**Engine Version:** UE 5.6
**Language:** C++ with Blueprint integration
**Platform:** Windows (primary development target)
## Build and Development Commands
### Building the Project
From the UE5 engine directory:
```bash
# Build game target
"C:\Program Files\Epic Games\UE_5.6\Engine\Build\BatchFiles\Build.bat" BladeSmith Win64 Development "E:\MiceCola\work\BladeSmith\BladeSmith.uproject"
# Build editor target
"C:\Program Files\Epic Games\UE_5.6\Engine\Build\BatchFiles\Build.bat" BladeSmithEditor Win64 Development "E:\MiceCola\work\BladeSmith\BladeSmith.uproject"
```
Alternatively, open `BladeSmith.sln` in Visual Studio and build from there.
### Running the Project
1. Open `BladeSmith.uproject` in UE5.6 Editor
2. Press Alt+P or click Play to run in editor
3. Use Ctrl+F11 for hot reload after C++ changes
### Testing
Unreal Engine uses the Automation System:
- **In Editor:** Window → Developer Tools → Automation Sessions
- **Command Line:** `UE5Editor.exe BladeSmith.uproject -ExecCmds="Automation RunTests"`
## Architecture Overview
### Core Systems (阶段1更新后)
**1. Dynamic Mesh Deformation System (增强)**
- `ADynamicIronBlock` (Source/BladeSmith/DynamicIronBlock.h/cpp) - 支持各向异性材料流动
- 顶点属性层: 初始位置、累积应变、硬度系数、打磨度
- 边缘检测与约束: 保持刀刃平整锐利
- 表面磨损可视化: 基于打磨度的颜色混合
- 各向异性材料流动(AnisotropyRatio控制方向性)
- 锤击时自动更新打磨度(表面从生锈到光亮)
- Laplacian平滑维护网格质量
- 自适应优化策略
**2. Voxel-Based Temperature System**
- 3D temperature voxel grid (`FTemperatureVoxel`) stores temperature and plasticity coefficients
- Temperature affects material plasticity: 800-1200°C is the forging range
- Heat conduction simulation with surface cooling
- Per-vertex color visualization of temperature (black body radiation approximation)
- GPU-accelerated temperature computation using ping-pong buffers
**3. GPU Compute Pipeline (MiceShaders Plugin)**
- Custom compute shaders for physics simulation
- `FDeformComputeShader` - Plastic deformation calculations
- `FTemperatureComputeShader` - Heat conduction and cooling
- Located in `Plugins/MiceShaders/`
- Shaders written in HLSL (`.usf` files in `Shaders/Private/`)
- Uses RDG (Render Dependency Graph) for GPU dispatch
**4. Hammer Interaction System**
- `UBladeSmithWeaponComponent` (Source/BladeSmith/BladeSmithWeaponComponent.h/cpp) - First-person hammer tool
- Ray-cast based collision detection
- Enhanced Input system integration
- Triggers deformation on `ADynamicIronBlock` via `OnHammerImpact()`
### Key Classes and Their Relationships
```
ABladeSmithCharacter (Player)
└── UBladeSmithWeaponComponent (Hammer Tool)
└── OnHammerImpact()
└── ADynamicIronBlock (Iron Workpiece)
├── Temperature Voxel Grid (CPU/GPU)
├── Vertex Attribute Arrays (CPU)
│ ├── InitialPositionsArray
│ ├── AccumulatedStrainArray
│ ├── HardnessCoefficientArray
│ └── PolishAmountArray
├── Dynamic Mesh (GeometryScripting)
│ ├── Anisotropic Flow Direction
│ ├── Edge Constraint
│ └── Laplacian Smoothing
└── MiceShaders Compute Shaders
```
### Data Flow: Hammer Impact to Deformation (阶段1更新)
1. Player swings hammer (`UBladeSmithWeaponComponent::SwingHammer()`)
2. Ray-cast detects hit on `ADynamicIronBlock`
3. `OnHammerImpact()` receives: location, normal, radius, depth, force
4. **计算材料流动方向** (各向异性)
- `FindNearestFreeEdgeDirection()` - 查找最近边缘
- `CalculatePrimaryFlowDirection()` - 计算主流动方向
- `CalculateSecondaryFlowDirection()` - 计算次流动方向
5. Sample plasticity coefficient from temperature voxels at hit location
6. Apply plastic deformation to mesh vertices via `EditMesh()` lambda
- **各向异性距离计算** - 材料沿主方向更容易流动
- **更新顶点属性** - 累积应变、打磨度
7. **边缘约束** (如果启用) - `ApplyEdgeLinearConstraint()`
8. **Laplacian平滑** - `ApplyLaplacianSmoothing()` (自适应)
9. Recompute mesh normals
10. Update vertex colors (温度 × 打磨度)
11. GPU compute shader updates temperature distribution (如启用)
## Module Dependencies
**BladeSmith Module (Source/BladeSmith/BladeSmith.Build.cs):**
- GeometryScriptingCore, GeometryFramework, DynamicMesh
- GeometryCore, GeometryAlgorithms, ModelingComponents
- RenderCore, RHI, Renderer, PhysicsCore
- EnhancedInput
- AudioExtensions, AudioMixer, AudioPlatformConfiguration
- **MiceShaders** (custom plugin)
**MiceShaders Plugin:**
- Core, RenderCore, RHI
- Projects (for shader path resolution)
## Code Conventions
### File Headers
All source files must start with Epic copyright notice (as required by UE5 licensing).
### Naming Conventions
- **Actors:** `AClassName` (e.g., `ADynamicIronBlock`)
- **Components:** `UClassName` (e.g., `UBladeSmithWeaponComponent`)
- **Structs:** `FStructName` (e.g., `FTemperatureVoxel`)
- **Enums:** `EEnumName`
- **Functions:** PascalCase (e.g., `OnHammerImpact()`)
- **Variables:** PascalCase for properties, camelCase for locals
- **Constants:** PascalCase
### Type Usage
- Use UE5 types: `TArray<T>`, `TMap<K,V>`, `TSet<T>`, `FVector`, `FString`, `int32`, `uint8`
- Use `float` by default (not `double`)
- Smart pointers: rely on UObject garbage collection; use `TSharedPtr<T>` for non-UObjects
- String literals: wrap in `TEXT()` macro
### Indentation and Formatting
- **4 spaces** (no tabs)
- **Allman style braces** (opening brace on new line)
- Line length under 120 characters
### Threading and GPU Operations
```cpp
// Atomic flags for thread-safe GPU buffer status
std::atomic<bool> bGPUBuffersReady{false};
// Render thread commands
ENQUEUE_RENDER_COMMAND(CommandName)(
[Params](FRHICommandListImmediate& RHICmdList)
{
// GPU operations here
}
);
```
### Documentation
Comments use Chinese for domain-specific logic (e.g., "锤子组件", "温度体素结构").
## Important Implementation Details
### Temperature-Plasticity Relationship
- Plasticity = 0 below `ForgeTemperatureMin` (800°C by default)
- Plasticity = 1 above `ForgeTemperatureMax` (1200°C by default)
- Linear interpolation between min and max
- Deformation depth is multiplied by plasticity coefficient
### Deformation Parameters
- `FalloffExponent`: Controls edge transition smoothness (default: 2.0)
- `BulgeRatio`: Bulge radius relative to compression zone (default: 0.8)
- `BulgeStrength`: Bulge height intensity (default: 0.5)
- These simulate realistic plastic flow and volume conservation
### Vertex Color Mapping
- Each vertex samples temperature from voxel grid via trilinear interpolation
- Temperature is converted to color using black body radiation approximation
- Updated every frame when temperature changes occur
### GPU Buffer Management
- Uses ping-pong double buffering for temperature compute shader
- `TemperatureBufferA` and `TemperatureBufferB` alternate as read/write buffers
- Separate `PlasticityBuffer` stores derived plasticity coefficients
- `SurfaceVoxelFlagsBuffer` marks surface voxels for cooling calculations
- Buffers created on render thread, accessed via UAV/SRV
## Performance Targets
- **Frame time budget:** <7ms for deformation calculations
- **Target FPS:** 60 FPS during hammer operations
- **Mesh complexity:** Tested with ~100k vertices using GPU acceleration
- **Voxel resolution:** 50x50x50 typical (configurable via `TemperatureVoxelSize`)
## Adding New Compute Shaders
1. Create `.h` and `.cpp` in `Plugins/MiceShaders/Source/MiceShaders/Public|Private/`
2. Define shader class inheriting from `FGlobalShader`
3. Create corresponding `.usf` HLSL shader in `Plugins/MiceShaders/Shaders/Private/`
4. Use `IMPLEMENT_GLOBAL_SHADER()` macro to register
5. Dispatch via RDG in actor's Tick or specialized function
6. Reference existing shaders: `FDeformComputeShader`, `FTemperatureComputeShader`
## Key UE5 Patterns Used
**Dynamic Mesh Editing:**
```cpp
DynamicMesh->EditMesh([&](FDynamicMesh3& EditMesh)
{
// Modify mesh vertices/triangles here
}, EDynamicMeshChangeType::GeneralEdit);
```
**Material Parameter Updates:**
```cpp
DynamicMaterialInstance->SetScalarParameterValue(TEXT("AvgTemperature"), AvgTemp);
DynamicMaterialInstance->SetVectorParameterValue(TEXT("Color"), FLinearColor(R,G,B,A));
```
**Enhanced Input Binding:**
```cpp
if (UEnhancedInputComponent* EnhancedInput = Cast<UEnhancedInputComponent>(InputComponent))
{
EnhancedInput->BindAction(HammerAction, ETriggerEvent::Triggered, this, &ThisClass::SwingHammer);
}
```
## Plugin Structure
**Enabled Plugins (BladeSmith.uproject):**
- GeometryScripting (UE5 built-in)
- ModelingToolsEditorMode (UE5 built-in)
- HDRIBackdrop (UE5 built-in)
- RiderLink (in repository, for JetBrains Rider integration)
- MiceShaders (custom plugin)
## Content Organization
- `Content/BP/` - Blueprint actors and components
- `Content/Res/` - Game resources (meshes, materials, textures)
- `Content/Maps/` - Level maps
- `Content/Input/` - Enhanced Input assets
- `Content/FirstPersonArms/`, `Content/FPWeapon/` - First-person character assets
## Notes for AI Agents
- The AGENTS.md file contains comprehensive coding style guidelines; refer to it for detailed conventions
- When modifying deformation logic, always consider the temperature-plasticity coupling
- GPU buffer operations must be thread-safe; use atomic flags and render thread commands
- Test deformation with varying temperatures to ensure plasticity affects results correctly
- Voxel resolution trades off between accuracy and performance; adjust `TemperatureVoxelSize` accordingly