diff --git a/.cursor/environment.json b/.cursor/environment.json new file mode 100644 index 0000000..3b21c2d --- /dev/null +++ b/.cursor/environment.json @@ -0,0 +1,3 @@ +{ + "agentCanUpdateSnapshot": true +} \ No newline at end of file diff --git a/README.md b/README.md index 0e7b903..5ab32ee 100644 --- a/README.md +++ b/README.md @@ -1,8 +1,42 @@ # ThreatSource Library -威胁源仿真库是一个用于模拟和仿真各种威胁源的.NET类库。提供 .NET 和原生 C++ 两种接口。 +威胁源仿真库是一个功能强大的.NET类库,专门用于模拟和仿真各种军事威胁源和导弹系统。项目提供 .NET 核心库和 C++/CLI 包装器两种接口,支持复杂的制导系统、干扰对抗和多传感器融合仿真。 -## 编译和打包 +## 🚀 主要特性 + +### 制导系统 +- **激光制导**:激光半主动、激光驾束、激光编码制导 +- **红外制导**:红外成像、红外指令、红外测角 +- **毫米波制导**:主动雷达、圆锥/螺旋扫描 +- **多模制导**:毫米波/红外双模、激光/红外复合制导 +- **末敏制导**:末敏弹及子弹药制导 + +### 传感器系统 +- 多传感器融合技术 +- 螺旋扫描搜索算法 +- 目标探测和识别 +- RCS特征建模 +- Swerling RCS回波模型 + +### 干扰对抗 +- **激光干扰**:激光诱偏、激光告警 +- **红外干扰**:红外干扰、烟幕弹干扰 +- **毫米波干扰**:毫米波补偿干扰 +- **综合干扰**:多频段同时干扰处理 + +### 仿真环境 +- 大气环境建模(密度、温度、湿度、风速) +- 地形高程影响 +- 实时仿真数据同步 +- 第三方仿真环境适配 + +## 📊 版本信息 + +**当前版本:** 1.1.22 +**发布日期:** 2025-05-26 +**详细变更:** 请参阅 [CHANGELOG.md](CHANGELOG.md) + +## 🏗️ 编译和打包 ### 编译 .NET 库 @@ -18,13 +52,7 @@ dotnet build ThreatSource/ThreatSource.csproj dotnet build ThreatSource/ThreatSource.csproj -c Release ``` -### 编译原生库 - -1. 使用 Visual Studio 2022 打开 ThreatSourceNative/ThreatSourceNative.vcxproj -2. 选择配置:Release,平台:x64 -3. 编译解决方案 - -### 打包 +### 打包脚本 #### 打包 .NET 库 @@ -40,119 +68,253 @@ dotnet build ThreatSource/ThreatSource.csproj -c Release - ThreatSource.dll - 主要的库文件 - ThreatSource.deps.json - 依赖配置文件 - ThreatSource.xml - API 文档文件 +- AirTransmission.dll - 大气传输计算库 +- AirTransmission.xml - 大气传输计算库API文档文件 -#### 打包原生库 +#### 打包完整项目 使用打包脚本生成 zip 包: ```bash -./scripts/pack_native.sh +./scripts/pack_all.sh ``` -生成的文件位于 `publish` 目录下,文件名格式为 `ThreatSourceNative-{version}.zip`。 -包含以下文件: - -- bin/ThreatSourceNative.dll - 原生接口库 -- bin/ThreatSource.dll - 核心库 -- bin/ThreatSource.deps.json - 依赖配置文件 -- include/threat_source.h - C接口头文件 +生成的文件位于 `publish` 目录下: +- `ThreatSourceLibrary-{version}.zip` - .NET库包 +- `ThreatSource-Library.pdf` - API文档文件 ### 生成文档 -生成 PDF 格式的文档: +生成 HTML 和 PDF 格式的文档: ```bash -# 先生成 HTML 文档 +# 生成 HTML 文档 docfx build docfx.json -# 然后生成 PDF +# 生成 PDF 文档 ./scripts/generate_pdf.sh ``` -生成的 PDF 文件位于 `publish` 目录下,文件名为 `ThreatSource-Library.pdf`。 +生成的文档位于: +- HTML: `docs/_site/` +- PDF: `publish/ThreatSource-Library.pdf` -## 项目结构 +## 📁 项目结构 ```text -ThreatSource/ -├── src/ -│ ├── Target/ -│ │ └── Tank.cs -│ ├── Indicator/ -│ │ ├── LaserDesignator.cs -│ │ ├── LaserBeamRider.cs -│ │ └── InfraredTracker.cs -│ └── Missile/ -│ ├── BaseMissile.cs -│ ├── LaserBeamRiderMissile.cs -│ ├── InfraredCommandGuidedMissile.cs -│ ├── LaserSemiActiveGuidedMissile.cs -│ ├── InfraredImagingTerminalGuidedMissile.cs -│ ├── MillimeterWaveTerminalGuidedMissile.cs -│ ├── TerminalSensitiveMissile.cs -│ └── TerminalSensitiveSubmunition.cs -├── docs/ - 文档目录 -├── ThreatSourceNative/ - 原生接口库 +ThreatSourceLibaray/ +├── ThreatSource/ # 核心.NET库 +│ ├── src/ +│ │ ├── Equipment/ # 装备模型(坦克、直升机等) +│ │ ├── Missile/ # 导弹系统 +│ │ ├── Guidance/ # 制导系统 +│ │ ├── Sensor/ # 传感器系统 +│ │ ├── Indicator/ # 指示器(激光指示器、测角仪等) +│ │ ├── Jammer/ # 干扰器系统 +│ │ ├── Jammable/ # 可干扰组件 +│ │ ├── Simulation/ # 仿真框架 +│ │ ├── Data/ # 数据处理 +│ │ └── Utils/ # 工具类 +│ ├── data/ # 配置文件(TOML格式) +│ │ ├── missiles/ # 导弹参数配置 +│ │ ├── equipments/ # 装备参数配置 +│ │ ├── indicators/ # 指示器配置 +│ │ ├── jammers/ # 干扰器配置 +│ │ ├── warners/ # 告警器配置 +│ │ └── weathers/ # 天气环境配置 +│ └── lib/ # 第三方依赖库 +├── ThreatSourceNative/ # C++/CLI包装器(需要CLR支持) │ ├── include/ -│ │ └── threat_source.h - C接口头文件 +│ │ └── threat_source.h # C接口头文件 │ └── src/ -│ └── threat_source.cpp - C接口实现 -└── scripts/ - 工具脚本目录 - ├── pack_dll.sh - .NET库打包脚本 - ├── pack_native.sh - 原生库打包脚本 - └── generate_pdf.sh - PDF生成脚本 +│ └── threat_source.cpp # C++/CLI实现 +├── ThreatSource.Tests/ # 单元测试项目 +├── docs/ # 文档 +│ ├── articles/ # 技术文章 +│ ├── examples/ # 示例代码 +│ │ ├── Integration/ # 集成示例 +│ │ │ └── UnityExample.cs # Unity集成完整示例 +│ │ └── Simulation/ # 仿真示例 +│ └── api/ # API文档 +├── scripts/ # 构建脚本 +│ ├── pack_dll.sh # .NET库打包 +│ ├── pack_all.sh # 完整打包 +│ └── generate_pdf.sh # PDF生成 +└── tools/ # 开发工具 ``` -## 开发环境要求 +## 🔧 开发环境要求 -- .NET 8.0 或更高版本 -- Visual Studio 2022 或更高版本 -- DocFX(用于生成文档) -- wkhtmltopdf(用于生成 PDF) +### 基础要求 +- **.NET 8.0** 或更高版本 +- **Visual Studio 2022** 或更高版本(原生库开发) +- **Git** 版本控制 -## 使用说明 +### 文档生成 +- **DocFX** 3.0+ (API文档生成) +- **wkhtmltopdf** (PDF文档生成) + +### 依赖项 +- **Tomlyn** 0.19.0 - TOML配置文件解析 +- **AirTransmission** - 大气传输计算库 + +## 📖 使用说明 ### C#/.NET 用户 -1. 通过 NuGet 包管理器安装: +#### 通过NuGet安装(推荐) - ```bash - dotnet add package ThreatSource - ``` +```bash +dotnet add package ThreatSource +``` -2. 或直接引用 DLL 文件: - - 下载最新的 zip 包 - - 解压并引用 ThreatSource.dll +#### 直接引用DLL +1. 下载最新的 `ThreatSourceLibrary-{version}.zip` +2. 解压并引用 `ThreatSource.dll` +3. 确保配置文件位于正确路径 -### C++用户 +#### 基本使用示例 -有两种使用方式: +```csharp +using ThreatSource.Missile; +using ThreatSource.Equipment; -#### 方式一:动态加载(推荐) +// 创建目标 +var tank = new Tank("T72", position, orientation); -1. 下载 ThreatSourceNative 包 -2. 将 bin 目录下的所有 DLL 复制到程序目录 -3. 将 include/threat_source.h 添加到项目 -4. 使用 C 风格接口调用库功能 +// 创建导弹 +var missile = new LaserSemiActiveGuidedMissile("Hellfire"); +missile.Launch(launchPosition, targetPosition); -#### 方式二:CLR 集成 +// 仿真循环 +while (missile.IsActive) +{ + missile.Update(deltaTime); + // 处理仿真逻辑 +} +``` -如果需要使用 .NET 的完整功能: +### Unity 集成 -1. 配置项目属性: - - C/C++ -> 常规 -> 公共语言运行时支持:/clr - - 常规 -> 平台工具集:Visual Studio 2022 (v143) - - 常规 -> .NET目标框架:net8.0 +🎮 **Unity引擎完全支持**:项目提供了专门的Unity集成方案,可以直接在Unity项目中使用。 -2. 引用 ThreatSource.dll +#### 快速开始 -## 示例代码 +1. 下载 `ThreatSourceLibrary-{version}.zip` +2. 将 `ThreatSource.dll` 复制到 Unity 项目的 `Assets/Plugins/` 目录 +3. 参考 `docs/examples/Integration/UnityExample.cs` 示例代码 +4. 在Unity脚本中直接使用库的API -请参考 [docs/examples](docs/examples) 目录下的示例代码: +#### 详细集成指导 -- [集成示例](docs/examples/Integration/README.md) -- [仿真示例](docs/examples/Simulation/README.md) +完整的Unity集成教程、示例代码和最佳实践,请参阅: +📖 **[Unity集成指南](docs/examples/Integration/README.md#unity集成)** -## 许可证 +### C++ 用户 -MIT License +⚠️ **重要提醒**:ThreatSourceNative 是 C++/CLI 包装器,**必须在支持 CLR 的环境中运行**,不是传统的原生 C++ 库。 + +#### 使用 C++/CLI 包装器 +1. 下载 `ThreatSourceNative-{version}.zip` +2. 将 `bin/` 目录下所有DLL复制到程序目录 +3. 项目配置要求: + - **CLR 支持**:启用 (`/clr`) + - **平台工具集**:Visual Studio 2022 (v143) + - **.NET 目标框架**:net8.0 或更高 +4. 包含头文件:`#include "threat_source.h"` + +```cpp +#include "threat_source.h" + +int main() { + // 初始化仿真 + TS_CreateSimulation(); + + // 创建导弹实例 + TS_CreateMissile("missile1", 0, 0, 0, 100, 0, 0, + 300, 50, 60, 8000, 45.0); + + // 激活并发射 + TS_ActivateMissile("missile1"); + TS_FireMissile("missile1"); + + return 0; +} +``` + +#### Unity 兼容性说明 +⚠️ **Unity 不支持 C++/CLI 混合模式程序集**。如需在 Unity 中使用,建议: +1. 直接使用 .NET 库:引用 `ThreatSource.dll` +2. 创建 Unity Package 形式分发 +3. 如需原生性能,考虑重新设计为纯 C++ + P/Invoke 架构 + +#### 纯 C++ 环境说明 +如需在不支持 CLR 的纯 C++ 环境中使用,当前的 ThreatSourceNative **无法直接支持**。建议: +1. 通过进程间通信调用 .NET 库 +2. 重新设计为纯 C++ + P/Invoke 接口 +3. 考虑使用其他跨语言调用方案(如 COM) + +### 配置文件使用 + +项目使用TOML格式的配置文件,位于 `data/` 目录: + +```toml +# missiles/hellfire.toml +[basic] +name = "AGM-114 Hellfire" +type = "LaserSemiActive" +mass = 45.0 +length = 1.6 + +[guidance] +max_range = 8000.0 +terminal_guidance = true +proportional_gain = 3.0 +``` + +## 📚 示例和文档 + +- **集成示例**:[docs/examples/Integration/](docs/examples/Integration/) +- **仿真示例**:[docs/examples/Simulation/](docs/examples/Simulation/) +- **API文档**:[在线文档](docs/api/) 或 `docs/_site/` +- **技术文章**:[docs/articles/](docs/articles/) + +## 🔄 持续集成 + +项目支持自动化构建和测试: + +```bash +# 运行所有测试 +dotnet test ThreatSource.Tests/ + +# 代码覆盖率分析 +dotnet test --collect:"XPlat Code Coverage" +``` + +## 🤝 贡献指南 + +1. Fork 项目仓库 +2. 创建功能分支:`git checkout -b feature/amazing-feature` +3. 提交更改:`git commit -m 'Add amazing feature'` +4. 推送分支:`git push origin feature/amazing-feature` +5. 提交 Pull Request + +## 📄 许可证 + +本项目基于 MIT License 开源协议。详情请查看 [LICENSE](LICENSE) 文件。 + +## 📞 技术支持 + +- **问题反馈**:[Issues](../../issues) +- **功能请求**:[Feature Requests](../../issues/new) +- **文档反馈**:[Documentation Issues](../../issues/new) +- **Unity集成支持**:Unity相关问题请在Issues中标注"Unity"标签 +- **架构选择指导**: + - **.NET项目**:直接使用ThreatSource.dll + - **Unity项目**:推荐.NET库 + Unity适配器方案 + - **纯C++项目**:当前C++/CLI包装器需要CLR支持,如需真正原生支持请提交Feature Request + +--- + +**最后更新:** 2025-05-26 +**文档版本:** 1.1.22 diff --git a/ThreatSource/ThreatSource.csproj b/ThreatSource/ThreatSource.csproj index 76ef3c4..edc1465 100644 --- a/ThreatSource/ThreatSource.csproj +++ b/ThreatSource/ThreatSource.csproj @@ -4,7 +4,7 @@ net8.0 enable enable - 1.1.0 + 1.1.22 ThreatSource Library A comprehensive library for missile simulation and threat source modeling. Copyright © 2025 diff --git a/ThreatSourceNative/ThreatSourceNative.vcxproj b/ThreatSourceNative/ThreatSourceNative.vcxproj deleted file mode 100644 index 29fe0ab..0000000 --- a/ThreatSourceNative/ThreatSourceNative.vcxproj +++ /dev/null @@ -1,65 +0,0 @@ - - - - - Debug - x64 - - - Release - x64 - - - - - 16.0 - {12345678-1234-1234-1234-123456789ABC} - Win32Proj - ThreatSourceNative - 10.0 - - - - - - DynamicLibrary - v143 - Unicode - true - - - - - - $(SolutionDir)bin\$(Platform)\$(Configuration)\ - $(SolutionDir)obj\$(Platform)\$(Configuration)\ - - - - - Level3 - THREATSOURCE_EXPORTS;%(PreprocessorDefinitions) - $(ProjectDir)include;%(AdditionalIncludeDirectories) - - - Windows - %(AdditionalDependencies) - - - - - - - - - - - - - - ..\ThreatSource\bin\$(Configuration)\net8.0\ThreatSource.dll - - - - - \ No newline at end of file diff --git a/ThreatSourceNative/include/threat_source.h b/ThreatSourceNative/include/threat_source.h deleted file mode 100644 index 5ce7379..0000000 --- a/ThreatSourceNative/include/threat_source.h +++ /dev/null @@ -1,70 +0,0 @@ -#ifndef THREAT_SOURCE_H -#define THREAT_SOURCE_H - -#ifdef _WIN32 - #ifdef THREATSOURCE_EXPORTS - #define THREATSOURCE_API __declspec(dllexport) - #else - #define THREATSOURCE_API __declspec(dllimport) - #endif -#else - #define THREATSOURCE_API -#endif - -#ifdef __cplusplus -extern "C" { -#endif - -// 错误码定义 -#define THREATSOURCE_SUCCESS 0 -#define THREATSOURCE_ERROR_INVALID_PARAM -1 -#define THREATSOURCE_ERROR_INIT_FAILED -2 -#define THREATSOURCE_ERROR_SIMULATION_FAILED -3 - -// 仿真管理 -THREATSOURCE_API int TS_CreateSimulation(); -THREATSOURCE_API int TS_DestroySimulation(); - -// 导弹相关 -THREATSOURCE_API int TS_CreateMissile( - const char* id, - double x, double y, double z, // 初始位置 - double vx, double vy, double vz, // 初始速度 - double max_speed, // 最大速度 - double max_acceleration, // 最大加速度 - double max_flight_time, // 最大飞行时间 - double max_flight_distance, // 最大飞行距离 - double mass // 质量 -); - -THREATSOURCE_API int TS_ActivateMissile(const char* id); -THREATSOURCE_API int TS_DeactivateMissile(const char* id); -THREATSOURCE_API int TS_FireMissile(const char* id); -THREATSOURCE_API int TS_GetMissilePosition(const char* id, double* x, double* y, double* z); -THREATSOURCE_API int TS_GetMissileVelocity(const char* id, double* vx, double* vy, double* vz); -THREATSOURCE_API int TS_IsMissileActive(const char* id, int* active); - -// 目标相关 -THREATSOURCE_API int TS_CreateTarget( - const char* id, - double x, double y, double z, // 位置 - double orientation // 朝向(弧度) -); - -THREATSOURCE_API int TS_ActivateTarget(const char* id); -THREATSOURCE_API int TS_DeactivateTarget(const char* id); -THREATSOURCE_API int TS_GetTargetPosition(const char* id, double* x, double* y, double* z); -THREATSOURCE_API int TS_GetTargetOrientation(const char* id, double* orientation); - -// 仿真控制 -THREATSOURCE_API int TS_UpdateSimulation(double deltaTime); -THREATSOURCE_API int TS_GetSimulationTime(double* time); - -// 事件查询 -THREATSOURCE_API int TS_GetLastError(char* buffer, int buffer_size); - -#ifdef __cplusplus -} -#endif - -#endif // THREAT_SOURCE_H \ No newline at end of file diff --git a/ThreatSourceNative/src/threat_source.cpp b/ThreatSourceNative/src/threat_source.cpp deleted file mode 100644 index 6d9707e..0000000 --- a/ThreatSourceNative/src/threat_source.cpp +++ /dev/null @@ -1,190 +0,0 @@ -#include "../include/threat_source.h" -#include -#include -#include -#include - -using namespace System; -using namespace ThreatSource::Simulation; - -// 全局变量 -static msclr::auto_gcroot g_manager; -static std::unordered_map> g_missiles; -static std::unordered_map> g_targets; -static std::string g_last_error; - -// 辅助函数:设置错误信息 -void SetLastError(const char* error) { - g_last_error = error; -} - -// 仿真管理 -THREATSOURCE_API int TS_CreateSimulation() { - try { - g_manager = gcnew SimulationManager(); - return THREATSOURCE_SUCCESS; - } - catch (Exception^ e) { - SetLastError(msclr::interop::marshal_as(e->Message).c_str()); - return THREATSOURCE_ERROR_INIT_FAILED; - } -} - -THREATSOURCE_API int TS_DestroySimulation() { - try { - g_manager = nullptr; - g_missiles.clear(); - g_targets.clear(); - return THREATSOURCE_SUCCESS; - } - catch (Exception^ e) { - SetLastError(msclr::interop::marshal_as(e->Message).c_str()); - return THREATSOURCE_ERROR_SIMULATION_FAILED; - } -} - -// 导弹相关 -THREATSOURCE_API int TS_CreateMissile( - const char* id, - double x, double y, double z, - double vx, double vy, double vz, - double max_speed, - double max_acceleration, - double max_flight_time, - double max_flight_distance, - double mass -) { - if (!id) { - SetLastError("Invalid missile ID"); - return THREATSOURCE_ERROR_INVALID_PARAM; - } - - try { - String^ managedId = gcnew String(id); - - auto properties = gcnew MissileProperties(); - properties->Id = managedId; - properties->InitialPosition = Vector3D(x, y, z); - properties->InitialVelocity = Vector3D(vx, vy, vz); - properties->MaxSpeed = max_speed; - properties->MaxAcceleration = max_acceleration; - properties->MaxFlightTime = max_flight_time; - properties->MaxFlightDistance = max_flight_distance; - properties->Mass = mass; - - auto missile = gcnew TerminalSensitiveMissile(managedId, properties, g_manager); - g_manager->RegisterEntity(managedId, missile); - g_missiles[id] = missile; - - return THREATSOURCE_SUCCESS; - } - catch (Exception^ e) { - SetLastError(msclr::interop::marshal_as(e->Message).c_str()); - return THREATSOURCE_ERROR_SIMULATION_FAILED; - } -} - -THREATSOURCE_API int TS_ActivateMissile(const char* id) { - if (!id || g_missiles.find(id) == g_missiles.end()) { - SetLastError("Invalid missile ID"); - return THREATSOURCE_ERROR_INVALID_PARAM; - } - - try { - g_missiles[id]->Activate(); - return THREATSOURCE_SUCCESS; - } - catch (Exception^ e) { - SetLastError(msclr::interop::marshal_as(e->Message).c_str()); - return THREATSOURCE_ERROR_SIMULATION_FAILED; - } -} - -THREATSOURCE_API int TS_DeactivateMissile(const char* id) { - if (!id || g_missiles.find(id) == g_missiles.end()) { - SetLastError("Invalid missile ID"); - return THREATSOURCE_ERROR_INVALID_PARAM; - } - - try { - g_missiles[id]->Deactivate(); - return THREATSOURCE_SUCCESS; - } - catch (Exception^ e) { - SetLastError(msclr::interop::marshal_as(e->Message).c_str()); - return THREATSOURCE_ERROR_SIMULATION_FAILED; - } -} - -THREATSOURCE_API int TS_FireMissile(const char* id) { - if (!id || g_missiles.find(id) == g_missiles.end()) { - SetLastError("Invalid missile ID"); - return THREATSOURCE_ERROR_INVALID_PARAM; - } - - try { - g_missiles[id]->Fire(); - return THREATSOURCE_SUCCESS; - } - catch (Exception^ e) { - SetLastError(msclr::interop::marshal_as(e->Message).c_str()); - return THREATSOURCE_ERROR_SIMULATION_FAILED; - } -} - -// 目标相关 -THREATSOURCE_API int TS_CreateTarget( - const char* id, - double x, double y, double z, - double orientation -) { - if (!id) { - SetLastError("Invalid target ID"); - return THREATSOURCE_ERROR_INVALID_PARAM; - } - - try { - String^ managedId = gcnew String(id); - auto target = gcnew Tank(managedId, Vector3D(x, y, z), orientation, g_manager); - g_manager->RegisterEntity(managedId, target); - g_targets[id] = target; - return THREATSOURCE_SUCCESS; - } - catch (Exception^ e) { - SetLastError(msclr::interop::marshal_as(e->Message).c_str()); - return THREATSOURCE_ERROR_SIMULATION_FAILED; - } -} - -// 仿真控制 -THREATSOURCE_API int TS_UpdateSimulation(double deltaTime) { - try { - for (auto& pair : g_missiles) { - pair.second->Update(deltaTime); - } - for (auto& pair : g_targets) { - pair.second->Update(deltaTime); - } - return THREATSOURCE_SUCCESS; - } - catch (Exception^ e) { - SetLastError(msclr::interop::marshal_as(e->Message).c_str()); - return THREATSOURCE_ERROR_SIMULATION_FAILED; - } -} - -// 错误查询 -THREATSOURCE_API int TS_GetLastError(char* buffer, int buffer_size) { - if (!buffer || buffer_size <= 0) { - return THREATSOURCE_ERROR_INVALID_PARAM; - } - - try { - strncpy(buffer, g_last_error.c_str(), buffer_size - 1); - buffer[buffer_size - 1] = '\0'; - return THREATSOURCE_SUCCESS; - } - catch (...) { - return THREATSOURCE_ERROR_SIMULATION_FAILED; - } -} \ No newline at end of file diff --git a/docs/articles/intro.md b/docs/articles/intro.md index f068828..7b03277 100644 --- a/docs/articles/intro.md +++ b/docs/articles/intro.md @@ -477,8 +477,7 @@ var dataManager = new ThreatSourceDataManager(); 更多详细示例和高级用法请参考: - [仿真示例](../examples/Simulation/README.md) -- [集成示例](../examples/Integration/) -- [配置文件示例](../examples/Configs/) +- [集成示例](../examples/Integration/README.md) ## 故障排除 diff --git a/docs/examples/Integration/README.md b/docs/examples/Integration/README.md index 5650781..3f42263 100644 --- a/docs/examples/Integration/README.md +++ b/docs/examples/Integration/README.md @@ -58,7 +58,9 @@ public class UnrealThreatSourceAdapter } ``` -### [UnityExample.cs](UnityExample.cs) +### [UnityExample.cs](UnityExample.cs) - 方法一示例 + +**适用于:直接引用.NET库方式** Unity引擎集成示例,展示了: @@ -67,6 +69,10 @@ Unity引擎集成示例,展示了: - MonoBehaviour生命周期管理 - 事件系统的使用和视觉效果处理 +**使用前提:** +- 已将 `ThreatSource.dll` 复制到 `Assets/Plugins/` +- 配置文件已放置在 `Assets/StreamingAssets/ThreatSource/` + #### 核心功能 ```csharp @@ -105,6 +111,307 @@ public class UnityThreatSourceAdapter : MonoBehaviour } ``` +### [UnityPackageExample.cs](UnityPackageExample.cs) - 方法二示例 + +**适用于:Unity Package方式** + +Unity Package集成示例,展示了: + +- Package级别的管理和配置 +- ThreatSourceUnity命名空间的使用 +- Package专用的事件系统和API +- Assembly Definition环境下的集成 + +**使用前提:** +- 已按照方法二创建完整的Package结构 +- 配置了正确的package.json和Assembly Definition +- 通过Package Manager安装或本地引用Package + +#### Package核心功能 + +```csharp +using ThreatSourceUnity; + +public class PackageExampleUsage : MonoBehaviour +{ + private void Start() + { + var packageManager = ThreatSourcePackageManager.Instance; + + // 创建目标 + string targetId = packageManager.CreateTarget( + "package_target_001", + new Vector3(1000, 0, 100), + new Vector3(-50, 0, 0) + ); + + // 创建导弹 + string missileId = packageManager.CreateMissile( + "IR_Missile_Example", + Vector3.zero, + targetId + ); + } +} +``` + +## Unity集成方式 + +Unity引擎与ThreatSource仿真库提供两种主要的集成方式,开发者可以根据项目需求和团队情况选择合适的方案。 + +### 方法一:直接引用.NET库(推荐) + +**适用场景:** +- 快速原型开发 +- 单一项目使用 +- 需要完整仿真功能访问 + +**操作步骤:** + +1. **下载并解压库文件** + ```bash + # 下载 ThreatSourceLibrary-{version}.zip + # 解压到临时目录 + ``` + +2. **复制核心库文件** + ``` + # 将以下文件复制到 Unity 项目 + ThreatSource.dll → Assets/Plugins/ + ThreatSource.deps.json → Assets/Plugins/ + ThreatSource.xml → Assets/Plugins/ (可选,用于智能提示) + ``` + +3. **复制配置文件** + ``` + # 将配置目录复制到 StreamingAssets + data/ → Assets/StreamingAssets/ThreatSource/data/ + ``` + +4. **配置Unity项目设置** + ```csharp + // 在 Project Settings 中设置: + // - Api Compatibility Level: .NET Standard 2.1 或更高 + // - Scripting Backend: Mono 或 IL2CPP + ``` + +5. **验证集成** + ```csharp + using ThreatSource.Simulation; + using ThreatSource.Data; + + public class ThreatSourceTest : MonoBehaviour + { + private void Start() + { + // 测试库是否正确加载 + var dataManager = new ThreatSourceDataManager(); + Debug.Log("ThreatSource库加载成功!"); + } + } + ``` + +**优势:** +- ✅ 实现简单,快速上手 +- ✅ 直接访问完整API +- ✅ 性能最优,无额外包装 +- ✅ 易于调试和问题排查 + +**劣势:** +- ❌ 文件管理相对分散 +- ❌ 版本更新需手动替换文件 +- ❌ 难以在多项目间共享 + +### 方法二:创建Unity Package + +**适用场景:** +- 团队协作开发 +- 多项目复用 +- 需要版本管理 +- 计划发布到Package Registry + +**创建步骤:** + +1. **创建Package目录结构** + ``` + Assets/ThreatSourceUnity/ + ├── package.json + ├── README.md + ├── CHANGELOG.md + ├── Runtime/ + │ ├── ThreatSourceUnity.asmdef + │ ├── Scripts/ + │ │ ├── UnityThreatSourceAdapter.cs + │ │ ├── ThreatSourceManager.cs + │ │ └── Utils/ + │ │ ├── CoordinateConverter.cs + │ │ └── ConfigLoader.cs + │ └── Plugins/ + │ ├── ThreatSource.dll + │ └── ThreatSource.deps.json + ├── Editor/ + │ ├── ThreatSourceUnity.Editor.asmdef + │ └── ThreatSourceSetup.cs + └── Samples~/ + └── BasicExample/ + └── ThreatSourceExample.cs + ``` + +2. **配置package.json** + ```json + { + "name": "com.yourcompany.threatsource", + "version": "1.1.22", + "displayName": "ThreatSource Library", + "description": "军事威胁源仿真库Unity集成包", + "unity": "2020.3", + "dependencies": { + "com.unity.mathematics": "1.2.6" + }, + "keywords": ["simulation", "missile", "guidance"], + "author": { + "name": "Your Company", + "email": "support@company.com" + } + } + ``` + +3. **创建Assembly Definition** + ```json + // Runtime/ThreatSourceUnity.asmdef + { + "name": "ThreatSourceUnity", + "rootNamespace": "ThreatSourceUnity", + "references": ["Unity.Mathematics"], + "includePlatforms": [], + "excludePlatforms": [], + "allowUnsafeCode": false + } + ``` + +4. **创建编辑器工具** + ```csharp + // Editor/ThreatSourceSetup.cs + using UnityEngine; + using UnityEditor; + using System.IO; + + public class ThreatSourceSetup : EditorWindow + { + [MenuItem("Tools/ThreatSource/Package Setup")] + static void ShowWindow() + { + GetWindow("ThreatSource Setup"); + } + + private void OnGUI() + { + GUILayout.Label("ThreatSource Package Configuration", EditorStyles.boldLabel); + + if (GUILayout.Button("Setup StreamingAssets")) + { + SetupStreamingAssets(); + } + + if (GUILayout.Button("Validate Configuration")) + { + ValidateSetup(); + } + } + + private void SetupStreamingAssets() + { + string targetPath = "Assets/StreamingAssets/ThreatSource"; + if (!Directory.Exists(targetPath)) + { + Directory.CreateDirectory(targetPath); + Debug.Log($"Created directory: {targetPath}"); + } + } + + private void ValidateSetup() + { + // 验证配置完整性 + bool isValid = File.Exists("Assets/StreamingAssets/ThreatSource/data"); + Debug.Log($"Setup validation: {(isValid ? "PASSED" : "FAILED")}"); + } + } + ``` + +5. **添加示例代码** + ```csharp + // Samples~/BasicExample/ThreatSourceExample.cs + using UnityEngine; + using ThreatSource.Simulation; + using ThreatSource.Data; + + namespace ThreatSourceUnity.Samples + { + public class ThreatSourceExample : MonoBehaviour + { + private UnityThreatSourceAdapter adapter; + + private void Start() + { + adapter = GetComponent(); + if (adapter == null) + { + adapter = gameObject.AddComponent(); + } + + CreateExampleScene(); + } + + private void CreateExampleScene() + { + // 创建示例仿真场景 + adapter.CreateTarget("target1", new Vector3(1000, 0, 0), Vector3.zero); + adapter.CreateMissile("Hellfire", Vector3.zero, "target1"); + } + } + } + ``` + +**优势:** +- ✅ 更好的项目组织和结构 +- ✅ 便于版本管理和更新 +- ✅ 支持团队协作和共享 +- ✅ 可发布到Package Registry +- ✅ 包含完整的文档和示例 + +**劣势:** +- ❌ 初始设置相对复杂 +- ❌ 需要Package管理知识 +- ❌ 可能增加项目复杂度 + +### 集成方式选择指导 + +| 因素 | 直接引用.NET库 | 创建Unity Package | +|------|----------------|-------------------| +| **项目规模** | 小型、原型项目 | 中大型、生产项目 | +| **团队规模** | 个人、小团队 | 多人团队 | +| **版本管理** | 手动管理 | Package Manager | +| **复用需求** | 单项目使用 | 多项目复用 | +| **上手难度** | 简单 | 中等 | +| **维护成本** | 低 | 中等 | + +**推荐选择:** +- 🚀 **快速原型/学习**:选择方法一 +- 🏢 **团队项目/生产环境**:选择方法二 +- 🔄 **从方法一迁移到方法二**:随项目成熟度逐步升级 + +### 示例文件对应关系 + +| 集成方式 | 示例文件 | 主要特点 | +|----------|----------|----------| +| **方法一:直接引用.NET库** | [UnityExample.cs](UnityExample.cs) | 直接使用ThreatSource命名空间,简单直接 | +| **方法二:Unity Package** | [UnityPackageExample.cs](UnityPackageExample.cs) | 使用ThreatSourceUnity命名空间,Package化管理 | + +**使用建议:** +- 初学者或快速验证概念:参考 `UnityExample.cs` +- 正式项目开发:参考 `UnityPackageExample.cs` +- 两个示例文件都包含完整的集成代码,可直接复制使用 + ## 使用说明 ### 基本集成流程 diff --git a/docs/examples/Integration/UnityExample.cs b/docs/examples/Integration/UnityExample.cs index c897174..cf1fbb2 100644 --- a/docs/examples/Integration/UnityExample.cs +++ b/docs/examples/Integration/UnityExample.cs @@ -1,6 +1,17 @@ #if NEVER // 使用编译指令确保此文件永远不会被编译 -// Unity引擎集成示例代码 +// Unity引擎集成示例代码 - 方法一:直接引用.NET库 +// +// 【适用场景】 +// - 快速原型开发和单一项目使用 +// - 直接将 ThreatSource.dll 复制到 Assets/Plugins/ 目录 +// - 不需要复杂的Package管理 +// +// 【前置条件】 +// 1. 将 ThreatSource.dll 放入 Assets/Plugins/ +// 2. 将 data/ 目录复制到 Assets/StreamingAssets/ThreatSource/ +// 3. Unity项目设置 Api Compatibility Level 为 .NET Standard 2.1+ +// // 展示如何将Unity引擎与ThreatSource仿真系统集成 // 需要实现的核心功能: 实体同步、事件处理、状态管理 diff --git a/docs/examples/Integration/UnityPackageExample.cs b/docs/examples/Integration/UnityPackageExample.cs new file mode 100644 index 0000000..20246be --- /dev/null +++ b/docs/examples/Integration/UnityPackageExample.cs @@ -0,0 +1,595 @@ +#if NEVER // 使用编译指令确保此文件永远不会被编译 + +// Unity Package集成示例代码 - 方法二:创建Unity Package +// +// 【适用场景】 +// - 团队协作开发和多项目复用 +// - 需要版本管理和Package Manager支持 +// - 计划发布到Package Registry +// +// 【前置条件】 +// 1. 按照Integration README创建完整的Package结构 +// 2. 配置正确的package.json和Assembly Definition +// 3. 使用Package Manager安装或本地引用Package +// +// 【Package结构】 +// com.yourcompany.threatsource/ +// ├── Runtime/ +// │ ├── Scripts/(本示例文件应放在此处) +// │ └── Plugins/ThreatSource.dll +// └── Samples~/BasicExample/ +// +// 展示如何在Unity Package环境中使用ThreatSource仿真系统 + +using UnityEngine; +using System.Collections.Generic; +using ThreatSource.Simulation; +using ThreatSource.Data; +using ThreatSource.Missile; + +// Package专用命名空间,避免与用户代码冲突 +namespace ThreatSourceUnity +{ + /// + /// ThreatSource Unity Package管理器 + /// 提供Package级别的配置和管理功能 + /// + public class ThreatSourcePackageManager : MonoBehaviour + { + #region 单例模式 + private static ThreatSourcePackageManager _instance; + public static ThreatSourcePackageManager Instance + { + get + { + if (_instance == null) + { + _instance = FindObjectOfType(); + if (_instance == null) + { + GameObject go = new GameObject("ThreatSourcePackageManager"); + _instance = go.AddComponent(); + DontDestroyOnLoad(go); + } + } + return _instance; + } + } + #endregion + + #region 配置属性 + [Header("Package配置")] + [SerializeField] private string packageVersion = "1.1.22"; + [SerializeField] private bool enableDebugLogging = true; + [SerializeField] private float simulationTimeStep = 0.02f; + + [Header("资源路径配置")] + [SerializeField] private string dataPath = "StreamingAssets/ThreatSource/data"; + [SerializeField] private string prefabPath = "Packages/com.yourcompany.threatsource/Runtime/Prefabs"; + #endregion + + #region 核心组件 + private ISimulationManager _simulationManager; + private ThreatSourceDataManager _dataManager; + private Dictionary _entityGameObjects = new Dictionary(); + #endregion + + #region Unity生命周期 + private void Awake() + { + // 确保单例 + if (_instance != null && _instance != this) + { + Destroy(gameObject); + return; + } + _instance = this; + DontDestroyOnLoad(gameObject); + + InitializePackage(); + } + + private void Update() + { + UpdateSimulation(); + } + + private void OnDestroy() + { + CleanupPackage(); + } + #endregion + + #region Package初始化 + /// + /// 初始化Package + /// + private void InitializePackage() + { + try + { + LogDebug($"正在初始化ThreatSource Package v{packageVersion}"); + + // 验证Package环境 + if (!ValidatePackageEnvironment()) + { + LogError("Package环境验证失败"); + return; + } + + // 初始化仿真系统 + _simulationManager = new SimulationManager(); + _dataManager = new ThreatSourceDataManager(); + + // 启动仿真 + _simulationManager.StartSimulation(simulationTimeStep); + + // 订阅事件 + SubscribeToEvents(); + + LogDebug("ThreatSource Package初始化完成"); + } + catch (System.Exception ex) + { + LogError($"Package初始化失败: {ex.Message}"); + } + } + + /// + /// 验证Package环境 + /// + private bool ValidatePackageEnvironment() + { + // 检查数据路径 + string fullDataPath = System.IO.Path.Combine(Application.streamingAssetsPath, "ThreatSource/data"); + if (!System.IO.Directory.Exists(fullDataPath)) + { + LogError($"数据目录不存在: {fullDataPath}"); + return false; + } + + // 检查Assembly Definition + if (!HasValidAssemblyDefinition()) + { + LogError("Assembly Definition配置无效"); + return false; + } + + return true; + } + + /// + /// 检查Assembly Definition配置 + /// + private bool HasValidAssemblyDefinition() + { + // 在实际Package中,这里可以检查Assembly Definition的配置 + // 例如检查引用关系、平台设置等 + return true; // 简化示例 + } + #endregion + + #region 事件系统 + /// + /// 订阅仿真事件 + /// + private void SubscribeToEvents() + { + _simulationManager.Subscribe(OnMissileFireEvent); + _simulationManager.Subscribe(OnMissileExplodeEvent); + _simulationManager.Subscribe(OnFlightPhaseChangeEvent); + } + + private void OnMissileFireEvent(MissileFireEvent evt) + { + LogDebug($"Package事件: 导弹 {evt.SenderId} 向 {evt.TargetId} 发射"); + + // 触发Unity事件 + ThreatSourceEvents.Instance.OnMissileFired?.Invoke(evt.SenderId, evt.TargetId); + } + + private void OnMissileExplodeEvent(MissileExplodeEvent evt) + { + LogDebug($"Package事件: 导弹 {evt.SenderId} 在 {evt.Position} 爆炸"); + + // 清理GameObject + if (_entityGameObjects.TryGetValue(evt.SenderId, out GameObject missileGO)) + { + Destroy(missileGO); + _entityGameObjects.Remove(evt.SenderId); + } + + // 触发Unity事件 + ThreatSourceEvents.Instance.OnMissileExploded?.Invoke(evt.SenderId, + CoordinateConverter.ThreatSourceToUnity(evt.Position)); + } + + private void OnFlightPhaseChangeEvent(FlightPhaseChangeEvent evt) + { + LogDebug($"Package事件: 导弹 {evt.SenderId} 进入 {evt.NewPhase} 阶段"); + + // 触发Unity事件 + ThreatSourceEvents.Instance.OnFlightPhaseChanged?.Invoke(evt.SenderId, evt.NewPhase); + } + #endregion + + #region 仿真管理 + /// + /// 更新仿真 + /// + private void UpdateSimulation() + { + if (_simulationManager != null) + { + _simulationManager.UpdateSimulation(); + SyncEntityStates(); + } + } + + /// + /// 同步实体状态 + /// + private void SyncEntityStates() + { + foreach (var kvp in _entityGameObjects) + { + var entity = _simulationManager.GetEntity(kvp.Key); + if (entity?.KState != null) + { + var gameObject = kvp.Value; + gameObject.transform.position = CoordinateConverter.ThreatSourceToUnity(entity.KState.Position); + gameObject.transform.rotation = CoordinateConverter.OrientationToQuaternion(entity.KState.Orientation); + } + } + } + #endregion + + #region 公共API + /// + /// 创建导弹(Package API) + /// + public string CreateMissile(string missileType, Vector3 position, string targetId) + { + try + { + var missileData = _dataManager.GetMissile(missileType); + string missileId = $"pkg_missile_{System.Guid.NewGuid():N}"; + + var missile = new InfraredImagingTerminalGuidanceMissile(missileId, missileData) + { + KState = new KinematicState + { + Position = CoordinateConverter.UnityToThreatSource(position), + Velocity = new ThreatSource.Simulation.Vector3(0, 0, 0), + Orientation = new Orientation(0, 0, 0) + } + }; + + _simulationManager.RegisterEntity(missile); + + // 使用Package资源加载 + var prefab = LoadPrefabFromPackage("Missile"); + if (prefab != null) + { + var missileGO = Instantiate(prefab, position, Quaternion.identity); + missileGO.name = $"[Package] {missileId}"; + + var controller = missileGO.GetComponent(); + if (controller == null) + { + controller = missileGO.AddComponent(); + } + controller.Initialize(missileId, targetId); + + _entityGameObjects[missileId] = missileGO; + } + + LogDebug($"Package创建导弹: {missileId}"); + return missileId; + } + catch (System.Exception ex) + { + LogError($"Package创建导弹失败: {ex.Message}"); + return null; + } + } + + /// + /// 创建目标(Package API) + /// + public string CreateTarget(string targetId, Vector3 position, Vector3 velocity) + { + try + { + var target = new BaseEquipment(targetId) + { + KState = new KinematicState + { + Position = CoordinateConverter.UnityToThreatSource(position), + Velocity = CoordinateConverter.UnityToThreatSource(velocity), + Orientation = new Orientation(0, 0, 0) + } + }; + + _simulationManager.RegisterEntity(target); + + var prefab = LoadPrefabFromPackage("Target"); + if (prefab != null) + { + var targetGO = Instantiate(prefab, position, Quaternion.identity); + targetGO.name = $"[Package] {targetId}"; + _entityGameObjects[targetId] = targetGO; + } + + LogDebug($"Package创建目标: {targetId}"); + return targetId; + } + catch (System.Exception ex) + { + LogError($"Package创建目标失败: {ex.Message}"); + return null; + } + } + #endregion + + #region 资源管理 + /// + /// 从Package加载预制体 + /// + private GameObject LoadPrefabFromPackage(string prefabName) + { + // 优先从Package路径加载 + string packagePath = $"Packages/com.yourcompany.threatsource/Runtime/Prefabs/{prefabName}"; + var prefab = Resources.Load(packagePath); + + if (prefab == null) + { + // 后备方案:从普通Resources加载 + prefab = Resources.Load($"Prefabs/{prefabName}"); + } + + return prefab; + } + #endregion + + #region 清理 + /// + /// 清理Package + /// + private void CleanupPackage() + { + LogDebug("正在清理ThreatSource Package"); + + _simulationManager?.StopSimulation(); + _simulationManager = null; + + foreach (var gameObject in _entityGameObjects.Values) + { + if (gameObject != null) + { + Destroy(gameObject); + } + } + _entityGameObjects.Clear(); + + LogDebug("ThreatSource Package清理完成"); + } + #endregion + + #region 调试日志 + private void LogDebug(string message) + { + if (enableDebugLogging) + { + Debug.Log($"[ThreatSourcePackage] {message}"); + } + } + + private void LogError(string message) + { + Debug.LogError($"[ThreatSourcePackage] {message}"); + } + #endregion + } + + /// + /// Package专用的导弹控制器 + /// + public class PackageMissileController : MonoBehaviour + { + private string _missileId; + private string _targetId; + private TrailRenderer _trailRenderer; + private ParticleSystem _thrustEffect; + + public void Initialize(string missileId, string targetId) + { + _missileId = missileId; + _targetId = targetId; + + // 初始化组件 + _trailRenderer = GetComponent(); + _thrustEffect = GetComponentInChildren(); + + // 订阅Package事件 + ThreatSourceEvents.Instance.OnFlightPhaseChanged += OnFlightPhaseChanged; + } + + private void OnDestroy() + { + // 取消订阅 + if (ThreatSourceEvents.Instance != null) + { + ThreatSourceEvents.Instance.OnFlightPhaseChanged -= OnFlightPhaseChanged; + } + } + + private void OnFlightPhaseChanged(string missileId, FlightPhase newPhase) + { + if (missileId != _missileId) return; + + switch (newPhase) + { + case FlightPhase.Boost: + if (_thrustEffect != null) _thrustEffect.Play(); + break; + case FlightPhase.Midcourse: + if (_trailRenderer != null) _trailRenderer.enabled = true; + break; + case FlightPhase.Terminal: + if (_trailRenderer != null) _trailRenderer.material.color = Color.red; + break; + } + } + } + + /// + /// Package事件系统 + /// + public class ThreatSourceEvents : MonoBehaviour + { + private static ThreatSourceEvents _instance; + public static ThreatSourceEvents Instance + { + get + { + if (_instance == null) + { + _instance = FindObjectOfType(); + if (_instance == null) + { + GameObject go = new GameObject("ThreatSourceEvents"); + _instance = go.AddComponent(); + DontDestroyOnLoad(go); + } + } + return _instance; + } + } + + // Unity Events for Package users + public System.Action OnMissileFired; + public System.Action OnMissileExploded; + public System.Action OnFlightPhaseChanged; + } + + /// + /// 坐标系转换工具(Package版本) + /// + public static class CoordinateConverter + { + public static Vector3 ThreatSourceToUnity(ThreatSource.Utils.Vector3D position) + { + return new Vector3( + (float)position.X, + (float)position.Z, + (float)position.Y + ); + } + + public static ThreatSource.Utils.Vector3D UnityToThreatSource(Vector3 position) + { + return new ThreatSource.Utils.Vector3D( + position.x, + position.z, + position.y + ); + } + + public static Quaternion OrientationToQuaternion(Orientation orientation) + { + return Quaternion.Euler( + (float)(orientation.Pitch * Mathf.Rad2Deg), + (float)(orientation.Yaw * Mathf.Rad2Deg), + (float)(orientation.Roll * Mathf.Rad2Deg) + ); + } + } +} + +/// +/// Package使用示例脚本 +/// 展示如何在用户项目中使用ThreatSource Package +/// +namespace ThreatSourceUnity.Samples +{ + using ThreatSourceUnity; + + public class PackageExampleUsage : MonoBehaviour + { + [Header("示例配置")] + [SerializeField] private bool autoCreateScene = true; + [SerializeField] private float sceneCreationDelay = 2f; + + private void Start() + { + if (autoCreateScene) + { + Invoke(nameof(CreateExampleScene), sceneCreationDelay); + } + } + + /// + /// 创建示例场景 + /// + public void CreateExampleScene() + { + var packageManager = ThreatSourcePackageManager.Instance; + + // 创建目标 + string targetId = packageManager.CreateTarget( + "package_target_001", + new Vector3(1000, 0, 100), + new Vector3(-50, 0, 0) + ); + + // 创建导弹 + string missileId = packageManager.CreateMissile( + "IR_Missile_Example", + Vector3.zero, + targetId + ); + + Debug.Log($"Package示例场景创建完成: 导弹 {missileId} -> 目标 {targetId}"); + } + + /// + /// 手动创建导弹 + /// + public void CreateMissile() + { + var packageManager = ThreatSourcePackageManager.Instance; + packageManager.CreateMissile("IR_Missile_Example", transform.position, "package_target_001"); + } + + /// + /// 订阅Package事件示例 + /// + private void OnEnable() + { + ThreatSourceEvents.Instance.OnMissileFired += OnMissileFired; + ThreatSourceEvents.Instance.OnMissileExploded += OnMissileExploded; + } + + private void OnDisable() + { + if (ThreatSourceEvents.Instance != null) + { + ThreatSourceEvents.Instance.OnMissileFired -= OnMissileFired; + ThreatSourceEvents.Instance.OnMissileExploded -= OnMissileExploded; + } + } + + private void OnMissileFired(string missileId, string targetId) + { + Debug.Log($"用户项目收到事件: 导弹 {missileId} 向 {targetId} 发射"); + } + + private void OnMissileExploded(string missileId, Vector3 position) + { + Debug.Log($"用户项目收到事件: 导弹 {missileId} 在 {position} 爆炸"); + } + } +} + +#endif // 结束编译指令块 \ No newline at end of file diff --git a/publish/ThreatSource-1.1.22.zip b/publish/ThreatSource-1.1.22.zip new file mode 100644 index 0000000..4b6ed91 Binary files /dev/null and b/publish/ThreatSource-1.1.22.zip differ diff --git a/publish/ThreatSource-Library-1.1.22.pdf b/publish/ThreatSource-Library-1.1.22.pdf new file mode 100644 index 0000000..3fa1670 Binary files /dev/null and b/publish/ThreatSource-Library-1.1.22.pdf differ diff --git a/publish/ThreatSource-Library.pdf b/publish/ThreatSource-Library.pdf deleted file mode 100644 index cc2d224..0000000 Binary files a/publish/ThreatSource-Library.pdf and /dev/null differ diff --git a/scripts/generate_pdf.sh b/scripts/generate_pdf.sh index 32485f2..8529c82 100755 --- a/scripts/generate_pdf.sh +++ b/scripts/generate_pdf.sh @@ -1,5 +1,13 @@ #!/bin/bash +# 获取版本号(从项目文件中) +version=$(grep -o '[^<]*' ThreatSource/ThreatSource.csproj | sed 's/\(.*\)<\/Version>/\1/') + +if [ -z "$version" ]; then + echo "Error: Could not find version number in ThreatSource.csproj" + exit 1 +fi + # 创建临时文件列表 temp_file="html_files.txt" @@ -51,7 +59,7 @@ while IFS= read -r file; do done < "$temp_file" # 添加输出文件名 -cmd="$cmd \"${current_dir}/publish/ThreatSource-Library.pdf\"" +cmd="$cmd \"${current_dir}/publish/ThreatSource-Library-${version}.pdf\"" # 执行命令 eval $cmd @@ -59,4 +67,4 @@ eval $cmd # 删除临时文件 rm $temp_file -echo "PDF generation completed: publish/ThreatSource-Library.pdf" \ No newline at end of file +echo "PDF generation completed: publish/ThreatSource-Library-${version}.pdf" \ No newline at end of file diff --git a/scripts/pack_all.sh b/scripts/pack_all.sh index 96368d4..6296d07 100755 --- a/scripts/pack_all.sh +++ b/scripts/pack_all.sh @@ -31,10 +31,8 @@ echo "正在复制文件..." cp ThreatSource/bin/Release/net8.0/ThreatSource.dll "${package_dir}/lib/" cp ThreatSource/bin/Release/net8.0/ThreatSource.xml "${package_dir}/lib/" cp ThreatSource/bin/Release/net8.0/ThreatSource.deps.json "${package_dir}/lib/" -cp ThreatSourceNative/bin/Release/x64/ThreatSourceNative.dll "${package_dir}/lib/" - -# 复制头文件到 include 目录 -cp ThreatSourceNative/include/threat_source.h "${package_dir}/include/" +cp ThreatSource/bin/Release/net8.0/AirTransmission.dll "${package_dir}/lib/" +cp ThreatSource/bin/Release/net8.0/AirTransmission.xml "${package_dir}/lib/" # 复制文档到 doc 目录 cp "publish/ThreatSource-Library.pdf" "${package_dir}/doc/ThreatSource-API-Doc.pdf" @@ -48,10 +46,8 @@ lib/ 目录: - ThreatSource.dll - .NET 主库文件 - ThreatSource.xml - .NET API 文档(用于 IDE 智能提示) - ThreatSource.deps.json - .NET 依赖配置文件 -- ThreatSourceNative.dll - C++ 接口库 - -include/ 目录: -- threat_source.h - C++ 头文件 +- AirTransmission.dll - 大气传输计算库 +- AirTransmission.xml - 大气传输计算库API文档文件 doc/ 目录: - ThreatSource-API-Doc.pdf - API 文档 @@ -64,8 +60,8 @@ doc/ 目录: 2. C++ 项目: - 将 lib 目录下的所有 DLL 文件复制到程序目录 - - 将 include/threat_source.h 添加到项目中 - - 包含头文件并使用 C 风格接口 + - 在 Visual Studio 中添加对 ThreatSource.dll 的引用 + - 创建 C++/CLI 项目并引用 ThreatSource.dll 详细使用说明请参考 doc 目录下的 API 文档。 EOL diff --git a/scripts/pack_dll.sh b/scripts/pack_dll.sh index 37cc61b..2b752ce 100755 --- a/scripts/pack_dll.sh +++ b/scripts/pack_dll.sh @@ -22,6 +22,8 @@ mkdir -p "${package_dir}" cp ThreatSource/bin/Release/net8.0/ThreatSource.dll "${package_dir}/" cp ThreatSource/bin/Release/net8.0/ThreatSource.deps.json "${package_dir}/" cp ThreatSource/bin/Release/net8.0/ThreatSource.xml "${package_dir}/" +cp ThreatSource/bin/Release/net8.0/AirTransmission.dll "${package_dir}/" +cp ThreatSource/bin/Release/net8.0/AirTransmission.xml "${package_dir}/" # 创建 zip 文件 cd publish diff --git a/scripts/pack_native.sh b/scripts/pack_native.sh deleted file mode 100644 index 7722f16..0000000 --- a/scripts/pack_native.sh +++ /dev/null @@ -1,116 +0,0 @@ -#!/bin/bash - -# 获取版本号(从项目文件中) -version=$(grep -o '[^<]*' ThreatSource/ThreatSource.csproj | sed 's/\(.*\)<\/Version>/\1/') - -if [ -z "$version" ]; then - echo "Error: Could not find version number in ThreatSource.csproj" - exit 1 -fi - -# 创建发布目录(如果不存在) -mkdir -p publish - -# 设置打包文件名 -package_name="ThreatSourceNative-${version}" -package_dir="publish/${package_name}" - -# 创建临时目录 -mkdir -p "${package_dir}/bin" -mkdir -p "${package_dir}/include" - -# 复制文件 -cp ThreatSourceNative/bin/Release/x64/ThreatSourceNative.dll "${package_dir}/bin/" -cp ThreatSource/bin/Release/net8.0/ThreatSource.dll "${package_dir}/bin/" -cp ThreatSource/bin/Release/net8.0/ThreatSource.deps.json "${package_dir}/bin/" -cp ThreatSourceNative/include/threat_source.h "${package_dir}/include/" - -# 创建说明文件 -cat > "${package_dir}/README.md" << EOL -# ThreatSource Native Library - -版本:${version} - -## 文件说明 - -- bin/ThreatSourceNative.dll - 原生接口库 -- bin/ThreatSource.dll - 核心库 -- bin/ThreatSource.deps.json - 依赖配置文件 -- include/threat_source.h - C接口头文件 - -## 使用方法 - -1. 将 bin 目录下的所有 DLL 文件复制到你的程序目录 -2. 将 include 目录下的头文件添加到你的项目中 -3. 在代码中包含头文件: - \`\`\`cpp - #include "threat_source.h" - \`\`\` - -## 示例代码 - -\`\`\`cpp -#include "threat_source.h" -#include - -int main() { - // 初始化仿真 - if (TS_CreateSimulation() != THREATSOURCE_SUCCESS) { - printf("Failed to create simulation\\n"); - return 1; - } - - // 创建导弹 - const char* missile_id = "missile1"; - int result = TS_CreateMissile( - missile_id, - 0, 0, 0, // 初始位置 - 0, 0, 0, // 初始速度 - 1000, // 最大速度 - 10, // 最大加速度 - 30, // 最大飞行时间 - 5000, // 最大飞行距离 - 50 // 质量 - ); - - if (result != THREATSOURCE_SUCCESS) { - char error[256]; - TS_GetLastError(error, sizeof(error)); - printf("Failed to create missile: %s\\n", error); - return 1; - } - - // 激活并发射导弹 - TS_ActivateMissile(missile_id); - TS_FireMissile(missile_id); - - // 仿真主循环 - double deltaTime = 0.01; - int is_active = 1; - - while (is_active) { - TS_UpdateSimulation(deltaTime); - TS_IsMissileActive(missile_id, &is_active); - } - - // 清理 - TS_DestroySimulation(); - return 0; -} -\`\`\` - -## 注意事项 - -1. 确保所有 DLL 文件在运行时可以被找到 -2. 检查每个函数的返回值,确保调用成功 -3. 如果函数返回错误,使用 TS_GetLastError 获取详细信息 -EOL - -# 创建 zip 文件 -cd publish -zip -r "${package_name}.zip" "${package_name}" - -# 清理临时目录 -rm -rf "${package_name}" - -echo "Package created: publish/${package_name}.zip" \ No newline at end of file