commit 86759bb726af6d40a7f16ff2f896d62ecc0f11c6 Author: shen <> Date: Sun Oct 11 17:52:55 2026 -0700 Initialize shared Metin2 SDK with rendering optimizations and tests diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..eae0f46 --- /dev/null +++ b/.gitignore @@ -0,0 +1,6 @@ +build/ +cmake-build-*/ +.DS_Store +__pycache__/ +*.pyc +/check_skel diff --git a/CMakeLists.txt b/CMakeLists.txt new file mode 100644 index 0000000..d9e5f65 --- /dev/null +++ b/CMakeLists.txt @@ -0,0 +1,21 @@ +cmake_minimum_required(VERSION 3.20) +project(metin2_crossplatform_sdk LANGUAGES C CXX) + +set(CMAKE_CXX_STANDARD 20) +set(CMAKE_CXX_STANDARD_REQUIRED ON) + +enable_testing() + +add_subdirectory(eterpack) +add_subdirectory(proto) +add_subdirectory(effect) +add_subdirectory(speedtree) +add_subdirectory(gr2) +add_subdirectory(terrain) +add_subdirectory(character) +add_subdirectory(property) +add_subdirectory(texture) +add_subdirectory(network) +add_subdirectory(spatial) +add_subdirectory(ui_core) +add_subdirectory(examples) diff --git a/README.md b/README.md new file mode 100644 index 0000000..8676cc3 --- /dev/null +++ b/README.md @@ -0,0 +1,208 @@ +# Metin2 Cross-Platform SDK Suite + +独立、零图形 API 绑定、高复用度的现代 C++20 渲染前置算法、物理模拟、网络协议、空间剔除与 UI 核心 SDK 套件,服务于跨平台游戏客户端与自研引擎开发。 + +--- + +## 📦 SDK 模块矩阵 (12 大独立核心库) + +| 模块 | 目录 | 核心职责 | 特性与技术突破 | +| :--- | :--- | :--- | :--- | +| **SpeedTree SDK** | `sdk/speedtree` | 植被生成、分层风场动力学、森林管理 | • **3 级分层风场动力学**(主干弯曲/树枝摇曳/叶片局部轴自转翻滚与颤动)
• **树冠球形法线混合**(消除纸片感,打造浑厚饱满的立体树冠)
• **次表面透射与半兰伯特环绕光**(逆光透亮,自然飘逸)
• **跨平台 GPU Foliage Shader + CPU 备用双管线** | +| **GR2 Core SDK** | `sdk/gr2` (`libgr2`) | 官方 Granny2 资产解密与解算 | • **全压缩算法支持**:Oodle0/1 + BitKnit2(Granny 2.11)
• **19 种曲线解算**(覆盖所有 curve2 / B-spline)
• 纯 C++ 实现,32/64 位无缝兼容,彻底移除闭源 Windows DLL 依赖 | +| **GR2 Render SDK** | `sdk/gr2` (`libgr2_render`) | 骨骼蒙皮、换装、武器/发型挂接 | • **`Gr2ModelInstance`**:零图形 API 绑定的高阶模型实例
• 骨骼姿态插值与调色板生成(Palette Matrices)
• 武器/发型骨骼挂接(`AttachModel` / `GetBoneWorldTransform`)
• 动态换装与部位替换(`AttachPart` / `SetSkin`) | +| **Terrain & Water SDK** | `sdk/terrain` | 地形采样、高度图法线、四叉树视锥剔除、水体网格 | • **131x131 raw 高度图**双线性世界高度插值与表面法线计算
• **258x258 tile.raw** 纹理 Splatting 映射与 Dominant 贴图判定
• **256x256 attr.atr** 阻挡/水体/安全区属性碰撞查询
• **8x8 Patch 四叉树视锥剔除**与连续 LOD 分层网格生成
• **water.wtr** 水体动态波动网格算法 | +| **Character & MSM SDK** | `sdk/character` | 角色体态、RaceData/MSM 脚本解析、多部位装配 | • 官方 `.msm` 脚本语法深度解析(BaseActorData, ShapeData, HairData, AttachingData)
• 身体部件装配(Main, Hair, Weapon, Sash)与换装换色(`SetArmorShape`, `SetHair`, `SetWeapon`)
• 骨骼插槽世界变换矩阵计算(`ComputeSocketWorldTransform`) | +| **Property & Object SDK** | `sdk/property` | 场景物件属性 (YPRT)、CRC 索引、OBB 碰撞物理 | • FourCC `YPRT` 文本属性解析(.prb 建筑, .prt 树木, .pre 特效, .prd 地牢)
• 大小写不敏感 CRC32 快速索引字典与统一对象管理器
• **OBB 定向包围盒 2D/3D 穿透判定**与分离轴碰撞法线推开计算 | +| **Texture & SubImage SDK** | `sdk/texture` | 软解纹理、DDS/DXT、TGA 解码、图集子图与九宫格 | • **纯 C++ DXT1/DXT3/DXT5 软解码**为 RGBA8888 像素缓冲(移动端与预览无依赖跨平台)
• **TGA 格式**(未压缩与 RLE 压缩 24/32 位)解码
• 官方 `.sub` 坐标裁剪与图集 UV 计算
• **9-Slice (九宫格) UI 渲染网格生成**(16 顶点、18 三角形标准流) | +| **Network SDK** | `sdk/network` | 连接状态机、TEA/Rolling XOR 加解密、分包解包重组 | • **客户端严格阶段状态机**(Handshake → Auth → CharacterSelect → GameLoading → InGame)
• **零 Socket 依赖架构**:宿主负责原始 I/O,SDK 负责安全加解密与变长封包重组
• **TEA 32 轮块加密 + 线性反馈 Rolling XOR 混淆**双重防重放与防篡改
• **强类型协议事件回调**(Handshake, AuthResult, CharacterList, GameStart, Chat, Move 等) | +| **Spatial Octree SDK** | `sdk/spatial` | 动态松散八叉树、相机视锥剔除、距离排序、射线拾取 | • **Loose Octree (扩展系数 $k=2.0$)**:杜绝跨分割面物件堆积在顶层
• **Gribb-Hartmann 视锥平面提取**与 P/N-Vertex 极速 AABB 相交测试
• 视距升序排序(支持从近到远不透明绘制与从远到近半透明排序)
• **球形 AOE 范围索敌查询**与 **Ray-AABB Slab 射线拾取/碰撞检测** | +| **UI Core SDK** | `sdk/ui_core` | 响应式 UI 节点树、9 点弹性锚点、布局排版、容器网格 | • **纯 C++20 彻底剥离 Python 2.7 运行时依赖**
• **9 点弹性锚点与弹性伸缩排版**(TopLeft, Center, Stretch 等多分辨率自适应)
• **递归命中判定与父级事件冒泡机制**(MouseDown, MouseUp, Click, Move, Hover, Drag)
• **全功能控件族**:Window (可拖拽), Button (四态), Text, Slot (CD 冷却遮罩/多格判定), Grid (背包 5x9 槽位与拖拽转移)
• 2D 顶点批次输出(DrawBatch 顶点流生成) | +| **EterPack SDK** | `sdk/eterpack` | 虚拟文件系统 (VFS) 与包解密 | • **EPK / EIX 双文件资产归档解析**
• TEA 32 轮加密 / 解密算法
• MiniLZO 内存压缩与 MCOZ 格式解包
• IEEE 802.3 与大小写不敏感 CRC32 哈希表快速索引 | +| **Proto SDK** | `sdk/proto` | 游戏元数据解密与结构体加载 | • **`item_proto` / `mob_proto` 二进制与文本双向解析**
• FourCC 头部校验 (`MIPX`, `MCPX`)
• 32 位 / 64 位平台结构体对齐与跨架构安全读取 | +| **Effect SDK** | `sdk/effect` | 粒子特效系统与寻的飞行道具 | • **MSE 特效脚本解析**(发射器、粒子生命周期、时间曲线关键帧插值)
• **MSF 寻的飞行物 (Homing Missile)** 物理轨迹仿真(重力、推力、最大角速度追踪、命中检测)
• 面向相机的公告板朝向计算 (Billboard Facing) 与顶点批次构建 | + +--- + +## 🌲 SpeedTree 真实飘逸渲染核心原理 + +为了在跨平台渲染器中达到与商业级 SpeedTree 完全一致的真实飘逸质感,SDK 落地了四大渲染与物理核心: + +1. **三级分层风场动力学 (3-Tier Wind Dynamics)**: + - **Level 1 主干弯曲**:基于高度的二次曲线响应,具备保长修正(Length-Preserving),模拟主干低频受力。 + - **Level 2 树枝摇曳**:带相位差与空间阻尼的中频振动,消除整体一致的机械感。 + - **Level 3 叶片自转微颤与翻滚 (Leaf Flutter & Tumble)**:每个叶片卡片顶点携带其局部的中心锚点(`leaf_pivot_offset`)。在风中,叶片以自身局部中心为轴高频摆动和翻转,光影鳞鳞闪烁,彻底消除僵硬片状感。 + - **空间阵风波 (Spatial Gust Waves)**:风浪以正弦波结合空间坐标传递,形成阵阵风浪席卷森林的宏观视觉效果。 + +2. **树冠球形法线混合 (Spherical Normal Blending)**: + - 将叶片几何法线与以树冠重心为起点的虚拟外向球形法线以动态权重加权混合,消除面片法线琐碎杂乱带来的硬边与黑斑,呈现浑厚饱满的树冠整体体积感。 + +3. **次表面透射与半兰伯特环绕光 (Subsurface Transmission & Wrap Lighting)**: + - 逆光观察树木时,背光透射算法实时解算穿透叶片的翠绿光晕(`pow(max(0.0, dot(-L, V)), 3.5)`)。 + - 漫反射采用半兰伯特环绕光,避免背光面死黑。 + - 结合基于树冠中心的内部环境遮挡(Canopy AO),打造外层透亮、内部深邃的层次感。 + +4. **双模渲染管线**: + - 提供 `foliage_shaders.h`(GLSL 450 / Vulkan SPIR-V / Metal / D3D11-12 兼容),GPU 端硬件级解算风力与球形法线。 + - 提供 `EvaluateCpuTransformedVertices()`,在 CPU 端实时解算几何形变,适配轻量级或老旧设备。 + +--- + +## 🎯 新增三大模块集成与调用示例 + +### 1. `sdk/network` 网络封包与协议状态机 + +```cpp +#include + +metin2::network::NetworkClient client; + +// 1. 设置业务事件回调 +client.SetOnHandshake([](uint32_t server_time) { + std::cout << "Handshake synced: " << server_time << std::endl; +}); +client.SetOnAuthResult([](bool success, uint32_t err, const std::string& msg) { + if (success) std::cout << "Auth succeeded!\n"; +}); + +// 2. 状态机推进与封包发送 +client.SetPhase(metin2::network::ConnectionPhase::Handshake); +// 宿主 Socket 收到数据后送入 SDK +client.PushReceivedData(socket_data, data_len); + +// 3. 进入验证并发送加密登录包 +client.SetPhase(metin2::network::ConnectionPhase::Auth); +client.SendLogin("HeroPlayer", "Password123"); + +// 4. 获取待发送的安全加密字节流 +std::vector outgoing = client.PopSendData(); +::send(socket_fd, outgoing.data(), outgoing.size(), 0); +``` + +### 2. `sdk/spatial` 八叉树空间划分与视锥剔除 + +```cpp +#include + +// 1. 创建场景松散八叉树 (边界: [-50000, 50000], 松散系数: 2.0) +metin2::spatial::AABB world_box({-50000, -5000, -50000}, {50000, 10000, 50000}); +metin2::spatial::LooseOctree octree(world_box, 2.0f); + +// 2. 动态注册世界实体 (建筑、树木、角色、怪物) +octree.Insert(101, metin2::spatial::SpatialObjectType::Building, building_aabb); +octree.Insert(202, metin2::spatial::SpatialObjectType::Tree, tree_aabb); + +// 3. 每帧视锥剔除与按视距升序排序 +metin2::spatial::Frustum frustum = metin2::spatial::Frustum::CreatePerspective( + camera_pos, look_dir, up_dir, 60.0f, aspect_ratio, 1.0f, 3000.0f +); +std::vector visible_list = octree.QueryFrustum(frustum, camera_pos, true); + +for (const auto& obj : visible_list) { + // 按距离从近到远依次提交渲染队列 + SubmitRenderCommand(obj.id, obj.type, obj.distance); +} +``` + +### 3. `sdk/ui_core` 响应式 UI 节点树与排版 + +```cpp +#include + +metin2::ui_core::UIManager ui_mgr(1920.0f, 1080.0f); + +// 1. 创建窗口容器 +auto window = std::make_shared(); +window->SetName("Inventory"); +window->SetSize(220.0f, 340.0f); +window->SetAnchor(metin2::ui_core::UIAnchor::Center); + +// 2. 创建背包网格 (5列 x 9行,格子 32px,间距 2px) +auto grid = std::make_shared(5, 9, 32.0f, 2.0f); +grid->SetPosition(10.0f, 30.0f); +grid->SetItemAt(0, 0, 10, 1); // 0号槽位放置屠龙刀 (vnum=10) + +window->AddChild(grid); +ui_mgr.AddElement(window); + +// 3. 事件派发 (鼠标点击自动冒泡与穿透检测) +ui_mgr.DispatchEvent(metin2::ui_core::UIEvent::MakeMouseDown(960.0f, 540.0f, 0)); + +// 4. 构建当前帧纯 2D 渲染批次 (包含九宫格网格与顶点颜色) +auto batches = ui_mgr.GenerateRenderBatches(); +for (const auto& b : batches) { + Render2DBatch(b.vertices, b.indices, b.texture_id); +} +``` + +--- + +## 🎯 跨平台项目接入指南 + +### 1. `CMakeLists.txt` 引入与构建 + +在项目的 `CMakeLists.txt` 中引入 SDK 模块: + +```cmake +# 引入统一 SDK 模块 +add_subdirectory(${CMAKE_CURRENT_SOURCE_DIR}/../sdk/speedtree ${CMAKE_CURRENT_BINARY_DIR}/sdk_speedtree) +add_subdirectory(${CMAKE_CURRENT_SOURCE_DIR}/../sdk/gr2 ${CMAKE_CURRENT_BINARY_DIR}/sdk_gr2) +add_subdirectory(${CMAKE_CURRENT_SOURCE_DIR}/../sdk/terrain ${CMAKE_CURRENT_BINARY_DIR}/sdk_terrain) +add_subdirectory(${CMAKE_CURRENT_SOURCE_DIR}/../sdk/character ${CMAKE_CURRENT_BINARY_DIR}/sdk_character) +add_subdirectory(${CMAKE_CURRENT_SOURCE_DIR}/../sdk/property ${CMAKE_CURRENT_BINARY_DIR}/sdk_property) +add_subdirectory(${CMAKE_CURRENT_SOURCE_DIR}/../sdk/texture ${CMAKE_CURRENT_BINARY_DIR}/sdk_texture) +add_subdirectory(${CMAKE_CURRENT_SOURCE_DIR}/../sdk/network ${CMAKE_CURRENT_BINARY_DIR}/sdk_network) +add_subdirectory(${CMAKE_CURRENT_SOURCE_DIR}/../sdk/spatial ${CMAKE_CURRENT_BINARY_DIR}/sdk_spatial) +add_subdirectory(${CMAKE_CURRENT_SOURCE_DIR}/../sdk/ui_core ${CMAKE_CURRENT_BINARY_DIR}/sdk_ui_core) +add_subdirectory(${CMAKE_CURRENT_SOURCE_DIR}/../sdk/eterpack ${CMAKE_CURRENT_BINARY_DIR}/sdk_eterpack) +add_subdirectory(${CMAKE_CURRENT_SOURCE_DIR}/../sdk/proto ${CMAKE_CURRENT_BINARY_DIR}/sdk_proto) +add_subdirectory(${CMAKE_CURRENT_SOURCE_DIR}/../sdk/effect ${CMAKE_CURRENT_BINARY_DIR}/sdk_effect) + +# 目标客户端直接链接 +target_link_libraries(my_game_client PRIVATE + speedtree + libgr2 + libgr2_render + terrain + character + property + texture + network + spatial + ui_core + eterpack + proto + effect +) +``` + +--- + +## 🛠️ SDK 编译与全量测试 + +在 `sdk` 根目录下执行: + +```bash +cd sdk +mkdir -p build && cd build +cmake .. +cmake --build . +ctest --output-on-failure +./examples/sdk_demo +``` + +当前全套 14 项自动化单元测试全部 100% 通过: +- `eterpack_test` +- `proto_test` +- `effect_test` +- `speedtree_test` +- `libgr2.loader_errors` +- `libgr2.animation` +- `libgr2.render_test` +- `terrain_test` +- `character_test` +- `property_test` +- `texture_test` +- `network_test` +- `spatial_test` +- `ui_core_test` diff --git a/character/CMakeLists.txt b/character/CMakeLists.txt new file mode 100644 index 0000000..1eedfcd --- /dev/null +++ b/character/CMakeLists.txt @@ -0,0 +1,24 @@ +cmake_minimum_required(VERSION 3.20) +project(character LANGUAGES CXX) + +set(CMAKE_CXX_STANDARD 20) +set(CMAKE_CXX_STANDARD_REQUIRED ON) + +add_library(character STATIC + src/msm_data.cpp + src/character_assembly.cpp +) + +target_include_directories(character PUBLIC + $ + $ +) + +add_library(character::character ALIAS character) + +option(CHARACTER_BUILD_TESTS "Build character SDK tests" ON) +if(CHARACTER_BUILD_TESTS) + add_executable(character_test tests/character_test.cpp) + target_link_libraries(character_test PRIVATE character) + add_test(NAME character_test COMMAND character_test) +endif() diff --git a/character/include/character/character.h b/character/include/character/character.h new file mode 100644 index 0000000..74a6ae0 --- /dev/null +++ b/character/include/character/character.h @@ -0,0 +1,5 @@ +#pragma once + +#include "types.h" +#include "msm_data.h" +#include "character_assembly.h" diff --git a/character/include/character/character_assembly.h b/character/include/character/character_assembly.h new file mode 100644 index 0000000..e9d0ccc --- /dev/null +++ b/character/include/character/character_assembly.h @@ -0,0 +1,54 @@ +#pragma once + +#include "types.h" +#include "msm_data.h" +#include +#include +#include +#include + +namespace metin2::character { + +struct AssembledPart { + uint32_t part_id = PART_MAIN; + std::string model_path; + std::vector skin_overrides; + std::string socket_bone; + float local_matrix[16] = { + 1,0,0,0, + 0,1,0,0, + 0,0,1,0, + 0,0,0,1 + }; +}; + +class CharacterAssembly { +public: + CharacterAssembly(std::shared_ptr msm); + ~CharacterAssembly() = default; + + // Equip / Appearance changes + bool SetArmorShape(uint32_t shape_index); + bool SetHair(uint32_t hair_index); + void SetWeapon(uint32_t part_id, const std::string& weapon_model, const std::string& custom_socket = ""); + + // Query active visual composition + const std::vector& GetAssembledParts() const { return m_parts; } + const AssembledPart* GetPart(uint32_t part_id) const; + + // Calculate socket world matrix: out_world = bone_world * local_transform + static void ComputeSocketWorldTransform(const float bone_world[16], const float local_offset[3], float out_world[16]); + + std::shared_ptr GetMsm() const { return m_msm; } + +private: + void RebuildAssembly(); + + std::shared_ptr m_msm; + uint32_t m_current_shape_index = 0; + uint32_t m_current_hair_index = 0; + std::unordered_map m_custom_weapons; + std::vector m_parts; +}; + +} // namespace metin2::character diff --git a/character/include/character/msm_data.h b/character/include/character/msm_data.h new file mode 100644 index 0000000..8e74a33 --- /dev/null +++ b/character/include/character/msm_data.h @@ -0,0 +1,60 @@ +#pragma once + +#include "types.h" +#include +#include +#include +#include + +namespace metin2::character { + +class MsmData { +public: + explicit MsmData(uint32_t race_id = 0); + ~MsmData() = default; + + // Load from official Metin2 .msm file or raw string content + bool LoadMsmFile(const std::string& file_path); + bool LoadMsmFromString(const std::string& content); + + uint32_t GetRaceId() const { return m_race_id; } + const std::string& GetBaseModelFile() const { return m_base_model_file; } + const std::string& GetTreeFile() const { return m_tree_file; } + bool IsTree() const { return !m_tree_file.empty(); } + const std::string& GetMotionListFile() const { return m_motion_list_file; } + + // Shape / Armor data query + const ShapeData* FindShape(uint32_t shape_index) const; + void SetShape(uint32_t shape_index, const ShapeData& shape); + + // Hair data query + const HairData* FindHair(uint32_t hair_index) const; + void SetHair(uint32_t hair_index, const HairData& hair); + + // Attaching sockets & bones + void RegisterAttachingBone(uint32_t part_id, const std::string& bone_name); + bool GetAttachingBone(uint32_t part_id, std::string& out_bone_name) const; + + const std::vector& GetAttachingDataList() const { return m_attaching_list; } + void AddAttachingData(const AttachingData& data) { m_attaching_list.push_back(data); } + + // Motion registry + void RegisterMotion(uint16_t mode, uint16_t motion_name, const std::string& file_name, int percent = 100); + const std::vector* GetMotions(uint16_t mode, uint16_t motion_name) const; + +private: + uint32_t m_race_id = 0; + std::string m_base_model_file; + std::string m_tree_file; + std::string m_motion_list_file; + + std::unordered_map m_shapes; + std::unordered_map m_hairs; + std::unordered_map m_attaching_bones; + std::vector m_attaching_list; + + // mode -> (motion_name -> vector of motions) + std::map>> m_motions; +}; + +} // namespace metin2::character diff --git a/character/include/character/types.h b/character/include/character/types.h new file mode 100644 index 0000000..b672968 --- /dev/null +++ b/character/include/character/types.h @@ -0,0 +1,91 @@ +#pragma once + +#include +#include +#include + +namespace metin2::character { + +enum EParts { + PART_MAIN = 0, + PART_WEAPON = 1, + PART_HEAD = 2, + PART_WEAPON_LEFT = 3, + PART_HAIR = 4, + PART_SASH = 5, + PART_ARROW_TYPE = 6, + PART_MAX_NUM +}; + +enum EMotion { + NAME_NONE = 0, + NAME_WAIT = 1, + NAME_WALK = 2, + NAME_RUN = 3, + NAME_CHANGE_WEAPON = 4, + NAME_DAMAGE = 5, + NAME_DAMAGE_FLYING = 6, + NAME_STAND_UP = 7, + NAME_DAMAGE_BACK = 8, + NAME_DAMAGE_FLYING_BACK = 9, + NAME_STAND_UP_BACK = 10, + NAME_DEAD = 11, + NAME_DEAD_BACK = 12, + NAME_NORMAL_ATTACK = 13, + NAME_COMBO_ATTACK_1 = 14, + NAME_COMBO_ATTACK_2 = 15, + NAME_COMBO_ATTACK_3 = 16, + NAME_COMBO_ATTACK_4 = 17, + NAME_INTRO_WAIT = 22, + NAME_INTRO_SELECTED = 23, + NAME_INTRO_NOT_SELECTED = 24, + NAME_SPAWN = 25, + NAME_STOP = 32, + NAME_SKILL = 50, + NAME_MAX_NUM = 150 +}; + +enum EAttachingDataType { + ATTACHING_DATA_TYPE_NONE = 0, + ATTACHING_DATA_TYPE_COLLISION_DATA = 1, + ATTACHING_DATA_TYPE_EFFECT = 2, + ATTACHING_DATA_TYPE_OBJECT = 3, +}; + +struct SkinMapping { + std::string src_file; + std::string dst_file; +}; + +struct ShapeData { + uint32_t shape_index = 0; + std::string model_file; + std::vector skins; +}; + +struct HairData { + uint32_t hair_index = 0; + std::string model_file; + std::vector skins; +}; + +struct AttachingData { + uint32_t type = ATTACHING_DATA_TYPE_NONE; + bool is_attaching = false; + uint32_t model_index = 0; + std::string bone_name; + // Local transform offset + float offset_x = 0.0f; + float offset_y = 0.0f; + float offset_z = 0.0f; + // Attached effect / collision data + std::string effect_file; + float collision_sphere_radius = 0.0f; +}; + +struct MotionEntry { + std::string file_name; + int percentage = 100; +}; + +} // namespace metin2::character diff --git a/character/src/character_assembly.cpp b/character/src/character_assembly.cpp new file mode 100644 index 0000000..463410e --- /dev/null +++ b/character/src/character_assembly.cpp @@ -0,0 +1,95 @@ +#include "character/character_assembly.h" +#include + +namespace metin2::character { + +CharacterAssembly::CharacterAssembly(std::shared_ptr msm) + : m_msm(std::move(msm)) { + RebuildAssembly(); +} + +bool CharacterAssembly::SetArmorShape(uint32_t shape_index) { + m_current_shape_index = shape_index; + RebuildAssembly(); + return true; +} + +bool CharacterAssembly::SetHair(uint32_t hair_index) { + m_current_hair_index = hair_index; + RebuildAssembly(); + return true; +} + +void CharacterAssembly::SetWeapon(uint32_t part_id, const std::string& weapon_model, const std::string& custom_socket) { + if (weapon_model.empty()) { + m_custom_weapons.erase(part_id); + } else { + m_custom_weapons[part_id] = weapon_model; + } + RebuildAssembly(); +} + +const AssembledPart* CharacterAssembly::GetPart(uint32_t part_id) const { + for (const auto& part : m_parts) { + if (part.part_id == part_id) return ∂ + } + return nullptr; +} + +void CharacterAssembly::ComputeSocketWorldTransform(const float bone_world[16], const float local_offset[3], float out_world[16]) { + // Copy bone matrix + std::copy(bone_world, bone_world + 16, out_world); + // Apply local translation along bone world axes + out_world[12] += bone_world[0] * local_offset[0] + bone_world[4] * local_offset[1] + bone_world[8] * local_offset[2]; + out_world[13] += bone_world[1] * local_offset[0] + bone_world[5] * local_offset[1] + bone_world[9] * local_offset[2]; + out_world[14] += bone_world[2] * local_offset[0] + bone_world[6] * local_offset[1] + bone_world[10] * local_offset[2]; +} + +void CharacterAssembly::RebuildAssembly() { + m_parts.clear(); + if (!m_msm) return; + + // 1. Base Body / Armor Part + AssembledPart body; + body.part_id = PART_MAIN; + body.model_path = m_msm->GetBaseModelFile(); + + const ShapeData* shape = m_msm->FindShape(m_current_shape_index); + if (shape) { + if (!shape->model_file.empty()) { + body.model_path = shape->model_file; + } + body.skin_overrides = shape->skins; + } + m_parts.push_back(std::move(body)); + + // 2. Hair Part + if (m_current_hair_index > 0) { + const HairData* hair = m_msm->FindHair(m_current_hair_index); + if (hair && !hair->model_file.empty()) { + AssembledPart hair_part; + hair_part.part_id = PART_HAIR; + hair_part.model_path = hair->model_file; + hair_part.skin_overrides = hair->skins; + std::string bone; + if (m_msm->GetAttachingBone(PART_HAIR, bone)) { + hair_part.socket_bone = bone; + } + m_parts.push_back(std::move(hair_part)); + } + } + + // 3. Weapons + for (const auto& [part_id, model] : m_custom_weapons) { + AssembledPart weapon_part; + weapon_part.part_id = part_id; + weapon_part.model_path = model; + std::string bone; + if (m_msm->GetAttachingBone(part_id, bone)) { + weapon_part.socket_bone = bone; + } + m_parts.push_back(std::move(weapon_part)); + } +} + +} // namespace metin2::character diff --git a/character/src/msm_data.cpp b/character/src/msm_data.cpp new file mode 100644 index 0000000..7fa09dd --- /dev/null +++ b/character/src/msm_data.cpp @@ -0,0 +1,231 @@ +#include "character/msm_data.h" +#include +#include +#include +#include + +namespace metin2::character { + +namespace { + +inline std::string Trim(const std::string& str) { + size_t first = str.find_first_not_of(" \t\r\n"); + if (first == std::string::npos) return ""; + size_t last = str.find_last_not_of(" \t\r\n"); + return str.substr(first, (last - first + 1)); +} + +inline std::string ToLower(std::string str) { + std::transform(str.begin(), str.end(), str.begin(), [](unsigned char c) { + return static_cast(std::tolower(c)); + }); + return str; +} + +inline std::string NormalizePath(std::string path) { + for (char& c : path) { + if (c == '\\') c = '/'; + else if (static_cast(c) < 128) c = static_cast(std::tolower(static_cast(c))); + } + return path; +} + +inline std::string ResolvePath(const std::string& path, const std::string& base_path) { + std::string norm = NormalizePath(path); + if (norm.empty()) return norm; + if (norm.find(':') != std::string::npos || norm.front() == '/') { + return norm; // Already absolute + } + if (!base_path.empty()) { + std::string base = NormalizePath(base_path); + if (!base.empty() && base.back() != '/') base += '/'; + return base + norm; + } + return norm; +} + +} // namespace + +MsmData::MsmData(uint32_t race_id) : m_race_id(race_id) { + // Default standard attaching bone names (Warrior/Assassin/Sura/Shaman convention) + m_attaching_bones[PART_WEAPON] = "equip_right"; + m_attaching_bones[PART_WEAPON_LEFT] = "equip_left"; + m_attaching_bones[PART_HEAD] = "Bip01 Head"; + m_attaching_bones[PART_HAIR] = "Bip01 Head"; + m_attaching_bones[PART_SASH] = "Bip01 Spine2"; +} + +bool MsmData::LoadMsmFile(const std::string& file_path) { + std::ifstream file(file_path); + if (!file.is_open()) return false; + std::stringstream buffer; + buffer << file.rdbuf(); + return LoadMsmFromString(buffer.str()); +} + +bool MsmData::LoadMsmFromString(const std::string& content) { + std::istringstream stream(content); + std::string raw_line; + + std::vector lines; + while (std::getline(stream, raw_line)) { + std::string trimmed = Trim(raw_line); + if (trimmed.empty() || trimmed[0] == '#') continue; + lines.push_back(trimmed); + } + + std::vector group_stack; + std::string current_base_path; + ShapeData current_shape; + HairData current_hair; + AttachingData current_attaching; + + for (size_t i = 0; i < lines.size(); ++i) { + const std::string& l = lines[i]; + + if (l.find("Group ") == 0 || l.find("group ") == 0) { + std::string grp = ToLower(Trim(l.substr(6))); + group_stack.push_back(grp); + + if (grp.find("shapedata") == 0 && grp != "shapedata") { + current_shape = ShapeData(); + } else if (grp.find("hairdata") == 0 && grp != "hairdata") { + current_hair = HairData(); + } else if (grp.find("attachingdata") == 0 && grp != "attachingdata") { + current_attaching = AttachingData(); + } + continue; + } + + if (l == "}") { + if (!group_stack.empty()) { + std::string top = group_stack.back(); + group_stack.pop_back(); + + if (top.find("shapedata") == 0 && top != "shapedata") { + m_shapes[current_shape.shape_index] = current_shape; + } else if (top.find("hairdata") == 0 && top != "hairdata") { + m_hairs[current_hair.hair_index] = current_hair; + } else if (top.find("attachingdata") == 0 && top != "attachingdata") { + m_attaching_list.push_back(current_attaching); + } else if (top == "shapedata" || top == "hairdata") { + current_base_path.clear(); + } + } + continue; + } + + std::istringstream line_stream(l); + std::string key; + line_stream >> key; + key = ToLower(key); + + std::string val; + line_stream >> std::ws; + std::getline(line_stream, val); + val = Trim(val); + if (val.size() >= 2 && val.front() == '"' && val.back() == '"') { + val = val.substr(1, val.size() - 2); + } + + std::string active_group = group_stack.empty() ? "" : group_stack.back(); + + if (key == "basemodelfilename") { + m_base_model_file = NormalizePath(val); + } else if (key == "treefilename") { + m_tree_file = NormalizePath(val); + } else if (key == "motionlistfilename") { + m_motion_list_file = NormalizePath(val); + } else if (key == "specialpath" || key == "pathname") { + current_base_path = NormalizePath(val); + if (!current_base_path.empty() && current_base_path.back() != '/') current_base_path += '/'; + } else if (key == "shapeindex") { + current_shape.shape_index = std::stoul(val); + } else if (key == "model" || key == "local_model") { + std::string resolved = (key == "local_model") ? NormalizePath(val) : ResolvePath(val, current_base_path); + if (active_group.find("shapedata") == 0) current_shape.model_file = resolved; + else if (active_group.find("hairdata") == 0) current_hair.model_file = resolved; + } else if (key == "sourceskin" || key == "local_sourceskin") { + std::string src = (key == "local_sourceskin") ? NormalizePath(val) : ResolvePath(val, current_base_path); + std::string dst; + if (i + 1 < lines.size()) { + std::istringstream next_stream(lines[i + 1]); + std::string next_key; + next_stream >> next_key; + std::string lower_next = ToLower(next_key); + if (lower_next == "targetskin" || lower_next == "local_targetskin") { + next_stream >> std::ws; + std::getline(next_stream, dst); + dst = Trim(dst); + if (dst.size() >= 2 && dst.front() == '"' && dst.back() == '"') { + dst = dst.substr(1, dst.size() - 2); + } + dst = (lower_next == "local_targetskin") ? NormalizePath(dst) : ResolvePath(dst, current_base_path); + i++; + } + } + if (active_group.find("shapedata") == 0) { + current_shape.skins.push_back({src, dst}); + } else if (active_group.find("hairdata") == 0) { + current_hair.skins.push_back({src, dst}); + } + } else if (key == "hairindex") { + current_hair.hair_index = std::stoul(val); + } else if (key == "attachingdatatype") { + current_attaching.type = std::stoul(val); + } else if (key == "isattaching") { + current_attaching.is_attaching = (std::stoi(val) != 0); + } else if (key == "attachingmodelindex") { + current_attaching.model_index = std::stoul(val); + } else if (key == "attachingbonename") { + current_attaching.bone_name = val; + } + } + + return !m_base_model_file.empty() || !m_tree_file.empty(); +} + +const ShapeData* MsmData::FindShape(uint32_t shape_index) const { + auto it = m_shapes.find(shape_index); + return (it != m_shapes.end()) ? &it->second : nullptr; +} + +void MsmData::SetShape(uint32_t shape_index, const ShapeData& shape) { + m_shapes[shape_index] = shape; +} + +const HairData* MsmData::FindHair(uint32_t hair_index) const { + auto it = m_hairs.find(hair_index); + return (it != m_hairs.end()) ? &it->second : nullptr; +} + +void MsmData::SetHair(uint32_t hair_index, const HairData& hair) { + m_hairs[hair_index] = hair; +} + +void MsmData::RegisterAttachingBone(uint32_t part_id, const std::string& bone_name) { + m_attaching_bones[part_id] = bone_name; +} + +bool MsmData::GetAttachingBone(uint32_t part_id, std::string& out_bone_name) const { + auto it = m_attaching_bones.find(part_id); + if (it != m_attaching_bones.end()) { + out_bone_name = it->second; + return true; + } + return false; +} + +void MsmData::RegisterMotion(uint16_t mode, uint16_t motion_name, const std::string& file_name, int percent) { + m_motions[mode][motion_name].push_back({file_name, percent}); +} + +const std::vector* MsmData::GetMotions(uint16_t mode, uint16_t motion_name) const { + auto mode_it = m_motions.find(mode); + if (mode_it == m_motions.end()) return nullptr; + auto motion_it = mode_it->second.find(motion_name); + if (motion_it == mode_it->second.end()) return nullptr; + return &motion_it->second; +} + +} // namespace metin2::character diff --git a/character/tests/character_test.cpp b/character/tests/character_test.cpp new file mode 100644 index 0000000..b042cd8 --- /dev/null +++ b/character/tests/character_test.cpp @@ -0,0 +1,129 @@ +#include "character/character.h" +#include +#include +#include + +using namespace metin2::character; + +int main() { + std::cout << "[Test 1] Parse official MSM character script..." << std::endl; + const std::string sample_msm = R"( +ScriptType RaceDataFile + +BaseActorData +{ + BaseModelFileName "d:/ymir work/pc/warrior/warrior_novice.gr2" + MotionListFileName "d:/ymir work/pc/warrior/motlist.txt" +} + +Group ShapeData +{ + PathName "d:/ymir work/pc/warrior/" + ShapeDataCount 2 + + Group ShapeData00 + { + ShapeIndex 0 + Model "warrior_novice.gr2" + SourceSkin "warrior_novice.dds" + TargetSkin "warrior_novice_blue.dds" + } + + Group ShapeData01 + { + ShapeIndex 1 + Model "warrior_4-1.gr2" + SourceSkin "warrior_4-1.dds" + TargetSkin "warrior_4-1_gold.dds" + } +} + +Group HairData +{ + PathName "d:/ymir work/pc/warrior/hair/" + HairDataCount 1 + + Group HairData01 + { + HairIndex 101 + Model "hair_01.gr2" + SourceSkin "hair_01.dds" + TargetSkin "hair_01_red.dds" + } +} + +Group AttachingData +{ + AttachingDataCount 1 + + Group AttachingData00 + { + AttachingDataType 2 + isAttaching 1 + AttachingModelIndex 0 + AttachingBoneName "equip_right" + } +} +)"; + + auto msm = std::make_shared(0); + bool ok = msm->LoadMsmFromString(sample_msm); + assert(ok); + assert(msm->GetBaseModelFile() == "d:/ymir work/pc/warrior/warrior_novice.gr2"); + + const ShapeData* s0 = msm->FindShape(0); + assert(s0 != nullptr); + assert(!s0->skins.empty()); + assert(s0->skins[0].dst_file == "d:/ymir work/pc/warrior/warrior_novice_blue.dds"); + + const ShapeData* s1 = msm->FindShape(1); + assert(s1 != nullptr); + assert(s1->model_file == "d:/ymir work/pc/warrior/warrior_4-1.gr2"); + + const HairData* h = msm->FindHair(101); + assert(h != nullptr); + assert(h->model_file == "d:/ymir work/pc/warrior/hair/hair_01.gr2"); + + std::cout << "[Test 2] Character dynamic assembly & skin replacement..." << std::endl; + CharacterAssembly char_assembly(msm); + + // Initial novice state + assert(char_assembly.GetAssembledParts().size() == 1); + assert(char_assembly.GetAssembledParts()[0].part_id == PART_MAIN); + + // Equip armor shape 1 + char_assembly.SetArmorShape(1); + assert(char_assembly.GetPart(PART_MAIN)->model_path == "d:/ymir work/pc/warrior/warrior_4-1.gr2"); + + // Equip hair 101 + char_assembly.SetHair(101); + assert(char_assembly.GetPart(PART_HAIR) != nullptr); + assert(char_assembly.GetPart(PART_HAIR)->socket_bone == "Bip01 Head"); + + // Equip main weapon (sword) + char_assembly.SetWeapon(PART_WEAPON, "d:/ymir work/weapon/weapon_sword_01.gr2"); + assert(char_assembly.GetPart(PART_WEAPON) != nullptr); + assert(char_assembly.GetPart(PART_WEAPON)->socket_bone == "equip_right"); + + std::cout << " Assembled part count: " << char_assembly.GetAssembledParts().size() << std::endl; + + std::cout << "[Test 3] Socket world transform calculation..." << std::endl; + float bone_world[16] = { + 1, 0, 0, 0, + 0, 1, 0, 0, + 0, 0, 1, 0, + 100.0f, 150.0f, 200.0f, 1.0f + }; + float offset[3] = { 10.0f, 5.0f, -2.0f }; + float socket_world[16]; + CharacterAssembly::ComputeSocketWorldTransform(bone_world, offset, socket_world); + + assert(std::abs(socket_world[12] - 110.0f) < 1e-4f); + assert(std::abs(socket_world[13] - 155.0f) < 1e-4f); + assert(std::abs(socket_world[14] - 198.0f) < 1e-4f); + std::cout << " Socket translation computed: (" + << socket_world[12] << ", " << socket_world[13] << ", " << socket_world[14] << ")" << std::endl; + + std::cout << "All Character SDK tests passed successfully!" << std::endl; + return 0; +} diff --git a/check_skel.cpp b/check_skel.cpp new file mode 100644 index 0000000..1efba8c --- /dev/null +++ b/check_skel.cpp @@ -0,0 +1,41 @@ +#include +#include + +int main() { + gr2::LoadError err; + auto file = gr2::File::load_path("ava2-client/ymir work/pc/warrior/warrior_novice.GR2", &err); + const auto& sk = file->file_info().skeletons[0]; + auto anim = gr2::File::load_path("ava2-client/ymir work/pc/warrior/intro/wait.gr2", &err); + const auto& an = anim->file_info().animations[0]; + + const gr2::Mat4 I{1,0,0,0, 0,1,0,0, 0,0,1,0, 0,0,0,1}; + std::vector world_anim, skin_anim; + gr2::sample_pose(sk, an, 0.0f, world_anim, skin_anim, &I); + std::cout << "WITH IDENTITY ROOT_OFFSET: ANIM POSE BONE 0 world pos: (" + << world_anim[0][12] << ", " << world_anim[0][13] << ", " << world_anim[0][14] << ")" << std::endl; + + // Check skinned mesh vertices! + const auto& mesh = file->file_info().meshes[2]; // warrior_body02 + float minZ = 1e9, maxZ = -1e9; + for (const auto& v : mesh.vertices) { + float pz = 0.0f; + float total_w = 0.0f; + if (v.bone_weight[0] > 0) { + for (int b = 0; b < 4; ++b) { + if (v.bone_weight[b] == 0) continue; + float w = v.bone_weight[b] / 255.0f; + int local_slot = v.bone_index[b]; + int sk_bone = mesh.bone_bindings[local_slot]; + const auto& M = skin_anim[sk_bone]; + pz += (v.pos[0] * M[2] + v.pos[1] * M[6] + v.pos[2] * M[10] + M[14]) * w; + total_w += w; + } + } + if (total_w > 1e-4f) { + minZ = std::min(minZ, pz); + maxZ = std::max(maxZ, pz); + } + } + std::cout << "Skinned warrior_body02 Z range: [" << minZ << ", " << maxZ << "]" << std::endl; + return 0; +} diff --git a/effect/CMakeLists.txt b/effect/CMakeLists.txt new file mode 100644 index 0000000..659d15c --- /dev/null +++ b/effect/CMakeLists.txt @@ -0,0 +1,28 @@ +cmake_minimum_required(VERSION 3.20) +project(effect LANGUAGES CXX) + +set(CMAKE_CXX_STANDARD 20) +set(CMAKE_CXX_STANDARD_REQUIRED ON) + +add_library(effect STATIC + src/time_event.cpp + src/effect_data.cpp + src/effect_instance.cpp + src/flying_data.cpp + src/flying_instance.cpp + src/effect_manager.cpp +) + +target_include_directories(effect PUBLIC + $ + $ +) + +add_library(effect::effect ALIAS effect) + +option(EFFECT_BUILD_TESTS "Build effect SDK tests" ON) +if(EFFECT_BUILD_TESTS) + add_executable(effect_test tests/effect_test.cpp) + target_link_libraries(effect_test PRIVATE effect) + add_test(NAME effect_test COMMAND effect_test) +endif() diff --git a/effect/include/effect/effect.h b/effect/include/effect/effect.h new file mode 100644 index 0000000..3d22ff7 --- /dev/null +++ b/effect/include/effect/effect.h @@ -0,0 +1,9 @@ +#pragma once + +#include "effect/types.h" +#include "effect/time_event.h" +#include "effect/effect_data.h" +#include "effect/effect_instance.h" +#include "effect/flying_data.h" +#include "effect/flying_instance.h" +#include "effect/effect_manager.h" diff --git a/effect/include/effect/effect_data.h b/effect/include/effect/effect_data.h new file mode 100644 index 0000000..aebde28 --- /dev/null +++ b/effect/include/effect/effect_data.h @@ -0,0 +1,92 @@ +#pragma once + +#include "effect/types.h" +#include "effect/time_event.h" +#include +#include +#include +#include + +namespace effect { + +struct EmitterProperty { + uint32_t max_emission_count = 1; + float cycle_length = 0.5f; + bool cycle_loop_enable = true; + int loop_count = 0; + + uint8_t emitter_shape = 0; // 0: Point, 1: Ellipse, 2: Box + uint8_t emitter_advanced_type = 0; + bool emit_from_edge_flag = false; + float emitting_radius = 0.0f; + Vec3 emitting_direction{0.0f, 0.0f, 0.0f}; + + std::vector time_emitting_velocity; + std::vector time_emission_count_per_second; + std::vector time_life_time; + std::vector time_size_x; + std::vector time_size_y; + std::vector time_emitting_dir_x; + std::vector time_emitting_dir_y; + std::vector time_emitting_dir_z; + std::vector time_emitting_angular_velocity; +}; + +struct ParticleProperty { + uint8_t src_blend_type = 5; // D3DBLEND_SRCALPHA + uint8_t dest_blend_type = 2; // D3DBLEND_ONE (Additive) or 6 (D3DBLEND_INVSRCALPHA) + uint8_t color_op_type = 4; // D3DTOP_MODULATE + + uint8_t billboard_type = 1; // 0: None, 1: Camera, 2: Y-axis, 3: Flat + uint8_t rotation_type = 0; + float rotation_speed = 0.0f; + int rotation_random_begin = 0; + int rotation_random_end = 0; + + bool attach_enable = false; + bool stretch_enable = false; + + uint8_t tex_ani_type = 0; + float tex_ani_delay = 0.03f; + bool tex_ani_random_start_frame = false; + + std::vector time_gravity; + std::vector time_air_resistance; + std::vector time_scale_x; + std::vector time_scale_y; + std::vector time_color_r; + std::vector time_color_g; + std::vector time_color_b; + std::vector time_alpha; + std::vector time_rotation; + + std::vector texture_files; +}; + +struct ParticleElement { + float start_time = 0.0f; + Vec3 position{0.0f, 0.0f, 0.0f}; + EmitterProperty emitter; + ParticleProperty particle; +}; + +class EffectData { +public: + EffectData() = default; + + bool load_from_string(const std::string& script_content); + bool load_file(const std::filesystem::path& filepath); + + const std::string& get_filename() const { return m_filename; } + float get_bounding_sphere_radius() const { return m_bounding_sphere_radius; } + const Vec3& get_bounding_sphere_position() const { return m_bounding_sphere_pos; } + const std::vector& get_particles() const { return m_particles; } + +private: + std::string m_filename; + float m_bounding_sphere_radius = 50.0f; + Vec3 m_bounding_sphere_pos{0.0f, 0.0f, 0.0f}; + std::vector m_particles; +}; + +} // namespace effect diff --git a/effect/include/effect/effect_instance.h b/effect/include/effect/effect_instance.h new file mode 100644 index 0000000..b08432d --- /dev/null +++ b/effect/include/effect/effect_instance.h @@ -0,0 +1,65 @@ +#pragma once + +#include "effect/effect_data.h" +#include +#include + +namespace effect { + +struct ParticleState { + Vec3 pos{0.0f, 0.0f, 0.0f}; + Vec3 vel{0.0f, 0.0f, 0.0f}; + float life = 0.0f; + float max_life = 1.0f; + float rot = 0.0f; + float rot_speed = 0.0f; + float base_size_x = 1.0f; + float base_size_y = 1.0f; + uint8_t frame_index = 0; +}; + +struct EmitterInstance { + float local_time = 0.0f; + uint32_t emitted_count = 0; + float emission_accumulator = 0.0f; + std::vector particles; +}; + +class EffectInstance { +public: + explicit EffectInstance(std::shared_ptr data); + ~EffectInstance() = default; + + void set_position(float x, float y, float z) { m_position = {x, y, z}; } + void set_position(const Vec3& p) { m_position = p; } + const Vec3& get_position() const { return m_position; } + + void set_world_matrix(const Mat4& mat) { + m_world_matrix = mat; + m_has_custom_matrix = true; + } + + void update(float dt); + void build_draw_batches(const Vec3& camera_pos, + const Vec3& camera_dir, + const Vec3& camera_up, + std::vector& out_batches); + + bool is_alive() const { return m_is_alive; } + void kill() { m_is_alive = false; } + size_t get_active_particle_count() const; + + std::shared_ptr get_data() const { return m_data; } + +private: + std::shared_ptr m_data; + bool m_is_alive = true; + float m_age = 0.0f; + Vec3 m_position{0.0f, 0.0f, 0.0f}; + Mat4 m_world_matrix = Mat4::identity(); + bool m_has_custom_matrix = false; + + std::vector m_emitters; +}; + +} // namespace effect diff --git a/effect/include/effect/effect_manager.h b/effect/include/effect/effect_manager.h new file mode 100644 index 0000000..b7397ff --- /dev/null +++ b/effect/include/effect/effect_manager.h @@ -0,0 +1,43 @@ +#pragma once + +#include "effect/effect_data.h" +#include "effect/effect_instance.h" +#include "effect/flying_data.h" +#include "effect/flying_instance.h" +#include +#include +#include + +namespace effect { + +class EffectManager { +public: + EffectManager() = default; + ~EffectManager() = default; + + std::shared_ptr get_or_load_effect(const std::string& filepath); + std::shared_ptr get_or_load_flying(const std::string& filepath); + + std::shared_ptr spawn_effect(const std::string& filepath, const Vec3& pos); + std::shared_ptr spawn_flying(const std::string& filepath, const Vec3& start, const Vec3& target); + + void update(float dt); + void build_draw_batches(const Vec3& camera_pos, + const Vec3& camera_dir, + const Vec3& camera_up, + std::vector& out_batches); + + size_t get_active_effects_count() const { return m_effects.size(); } + size_t get_active_flying_count() const { return m_flying.size(); } + + void clear(); + +private: + std::unordered_map> m_effect_cache; + std::unordered_map> m_flying_cache; + + std::vector> m_effects; + std::vector> m_flying; +}; + +} // namespace effect diff --git a/effect/include/effect/flying_data.h b/effect/include/effect/flying_data.h new file mode 100644 index 0000000..0799fe4 --- /dev/null +++ b/effect/include/effect/flying_data.h @@ -0,0 +1,40 @@ +#pragma once + +#include "effect/types.h" +#include +#include + +namespace effect { + +struct FlyingAttachData { + int type = 1; + int fly_type = 1; + std::string attach_file; + bool has_tail = false; + uint32_t tail_color = 0xFFFFFFFF; + float tail_length = 0.2f; + float tail_size = 8.0f; + bool rect_shape = false; +}; + +class FlyingData { +public: + FlyingData() = default; + + bool load_from_string(const std::string& content); + bool load_file(const std::filesystem::path& filepath); + + float initial_velocity = 2000.0f; + float gravity = 0.0f; + Vec3 acceleration{0.0f, 0.0f, 0.0f}; + float bomb_range = 10.0f; + std::string bomb_effect; + bool homing_flag = false; + float homing_start_time = 0.0f; + float homing_max_angle = 3.0f; + float range = 10000.0f; + + FlyingAttachData attach; +}; + +} // namespace effect diff --git a/effect/include/effect/flying_instance.h b/effect/include/effect/flying_instance.h new file mode 100644 index 0000000..6daf50e --- /dev/null +++ b/effect/include/effect/flying_instance.h @@ -0,0 +1,50 @@ +#pragma once + +#include "effect/flying_data.h" +#include +#include +#include + +namespace effect { + +struct TrailPoint { + Vec3 pos; + float time = 0.0f; +}; + +class FlyingInstance { +public: + FlyingInstance(std::shared_ptr data, const Vec3& start_pos, const Vec3& target_pos); + ~FlyingInstance() = default; + + bool update(float dt); + + bool is_alive() const { return m_is_alive; } + void kill() { m_is_alive = false; } + + const Vec3& get_position() const { return m_position; } + const Vec3& get_velocity() const { return m_velocity; } + const Vec3& get_target() const { return m_target; } + const std::vector& get_trail() const { return m_trail; } + + void set_hit_callback(std::function cb) { + m_hit_cb = std::move(cb); + } + + std::shared_ptr get_data() const { return m_data; } + +private: + std::shared_ptr m_data; + bool m_is_alive = true; + float m_age = 0.0f; + float m_distance_traveled = 0.0f; + + Vec3 m_position{0.0f, 0.0f, 0.0f}; + Vec3 m_velocity{0.0f, 0.0f, 0.0f}; + Vec3 m_target{0.0f, 0.0f, 0.0f}; + + std::vector m_trail; + std::function m_hit_cb; +}; + +} // namespace effect diff --git a/effect/include/effect/time_event.h b/effect/include/effect/time_event.h new file mode 100644 index 0000000..ed66323 --- /dev/null +++ b/effect/include/effect/time_event.h @@ -0,0 +1,15 @@ +#pragma once + +#include +#include + +namespace effect { + +struct TimeEvent { + float time = 0.0f; + float value = 0.0f; +}; + +float interpolate_time_event(const std::vector& events, float time, float default_val = 0.0f); + +} // namespace effect diff --git a/effect/include/effect/types.h b/effect/include/effect/types.h new file mode 100644 index 0000000..3898ab8 --- /dev/null +++ b/effect/include/effect/types.h @@ -0,0 +1,115 @@ +#pragma once + +#include +#include +#include +#include +#include + +namespace effect { + +struct Vec3 { + float x = 0.0f; + float y = 0.0f; + float z = 0.0f; + + constexpr Vec3() = default; + constexpr Vec3(float x_, float y_, float z_) : x(x_), y(y_), z(z_) {} + + constexpr Vec3 operator+(const Vec3& o) const { return {x + o.x, y + o.y, z + o.z}; } + constexpr Vec3 operator-(const Vec3& o) const { return {x - o.x, y - o.y, z - o.z}; } + constexpr Vec3 operator*(float s) const { return {x * s, y * s, z * s}; } + constexpr Vec3 operator/(float s) const { return {x / s, y / s, z / s}; } + + Vec3& operator+=(const Vec3& o) { x += o.x; y += o.y; z += o.z; return *this; } + Vec3& operator-=(const Vec3& o) { x -= o.x; y -= o.y; z -= o.z; return *this; } + Vec3& operator*=(float s) { x *= s; y *= s; z *= s; return *this; } + + float length_sq() const { return x * x + y * y + z * z; } + float length() const { return std::sqrt(length_sq()); } + + Vec3 normalized() const { + float l = length(); + if (l < 1e-6f) return {0.0f, 0.0f, 0.0f}; + return {x / l, y / l, z / l}; + } + + static float dot(const Vec3& a, const Vec3& b) { + return a.x * b.x + a.y * b.y + a.z * b.z; + } + + static Vec3 cross(const Vec3& a, const Vec3& b) { + return { + a.y * b.z - a.z * b.y, + a.z * b.x - a.x * b.z, + a.x * b.y - a.y * b.x + }; + } + + static Vec3 lerp(const Vec3& a, const Vec3& b, float t) { + return a + (b - a) * t; + } +}; + +struct Mat4 { + // Column-major 4x4 matrix + std::array m = { + 1.0f, 0.0f, 0.0f, 0.0f, + 0.0f, 1.0f, 0.0f, 0.0f, + 0.0f, 0.0f, 1.0f, 0.0f, + 0.0f, 0.0f, 0.0f, 1.0f + }; + + static Mat4 identity() { + return Mat4{}; + } + + static Mat4 translation(float tx, float ty, float tz) { + Mat4 res; + res.m[12] = tx; + res.m[13] = ty; + res.m[14] = tz; + return res; + } + + Vec3 transform_point(const Vec3& p) const { + return { + m[0] * p.x + m[4] * p.y + m[8] * p.z + m[12], + m[1] * p.x + m[5] * p.y + m[9] * p.z + m[13], + m[2] * p.x + m[6] * p.y + m[10] * p.z + m[14] + }; + } + + Vec3 transform_vector(const Vec3& v) const { + return { + m[0] * v.x + m[4] * v.y + m[8] * v.z, + m[1] * v.x + m[5] * v.y + m[9] * v.z, + m[2] * v.x + m[6] * v.y + m[10] * v.z + }; + } +}; + +struct Color4 { + float r = 1.0f; + float g = 1.0f; + float b = 1.0f; + float a = 1.0f; +}; + +struct ParticleVertex { + Vec3 pos; + Color4 color; + float u = 0.0f; + float v = 0.0f; +}; + +struct ParticleDrawBatch { + std::string texture; + uint8_t src_blend = 5; // D3DBLEND_SRCALPHA + uint8_t dest_blend = 2; // D3DBLEND_ONE (Additive) + uint8_t color_op = 4; // D3DTOP_MODULATE + std::vector vertices; + std::vector indices; +}; + +} // namespace effect diff --git a/effect/src/effect_data.cpp b/effect/src/effect_data.cpp new file mode 100644 index 0000000..743b259 --- /dev/null +++ b/effect/src/effect_data.cpp @@ -0,0 +1,284 @@ +#include "effect/effect_data.h" +#include +#include +#include +#include + +namespace effect { + +namespace { + +float to_float(const std::string& s) { + return std::strtof(s.c_str(), nullptr); +} + +int to_int(const std::string& s) { + return std::atoi(s.c_str()); +} + +std::string to_lower(std::string s) { + std::transform(s.begin(), s.end(), s.begin(), [](unsigned char c) { + return std::tolower(c); + }); + return s; +} + +std::vector tokenize(const std::string& content) { + std::vector tokens; + size_t i = 0; + size_t n = content.size(); + + while (i < n) { + while (i < n && (content[i] == ' ' || content[i] == '\t' || content[i] == '\r' || content[i] == '\n')) { + ++i; + } + if (i >= n) break; + + // Comments + if (i + 1 < n && content[i] == '/' && content[i + 1] == '/') { + while (i < n && content[i] != '\n') ++i; + continue; + } + if (content[i] == '#') { + while (i < n && content[i] != '\n') ++i; + continue; + } + + // Bracket tokens + if (content[i] == '{' || content[i] == '}') { + tokens.push_back(std::string(1, content[i])); + ++i; + continue; + } + + // Quoted string + if (content[i] == '"') { + ++i; + size_t start = i; + while (i < n && content[i] != '"') ++i; + tokens.push_back(content.substr(start, i - start)); + if (i < n && content[i] == '"') ++i; + continue; + } + + // Normal word + size_t start = i; + while (i < n && content[i] != ' ' && content[i] != '\t' && content[i] != '\r' && content[i] != '\n' && + content[i] != '{' && content[i] != '}' && content[i] != '"') { + ++i; + } + tokens.push_back(content.substr(start, i - start)); + } + return tokens; +} + +} // anonymous namespace + +bool EffectData::load_file(const std::filesystem::path& filepath) { + std::ifstream file(filepath, std::ios::binary); + if (!file.is_open()) return false; + + std::stringstream buf; + buf << file.rdbuf(); + m_filename = filepath.string(); + return load_from_string(buf.str()); +} + +bool EffectData::load_from_string(const std::string& content) { + m_particles.clear(); + auto tokens = tokenize(content); + size_t idx = 0; + size_t total = tokens.size(); + + auto read_time_events = [&](std::vector& out) { + if (idx < total && tokens[idx] == "{") { + ++idx; + while (idx < total && tokens[idx] != "}") { + float t = to_float(tokens[idx++]); + if (idx < total && tokens[idx] != "}") { + float v = to_float(tokens[idx++]); + out.push_back({t, v}); + } + } + if (idx < total && tokens[idx] == "}") ++idx; + } + }; + + while (idx < total) { + std::string token = to_lower(tokens[idx]); + + if (token == "boundingsphereradius" && idx + 1 < total) { + ++idx; + m_bounding_sphere_radius = to_float(tokens[idx++]); + } else if (token == "boundingsphereposition" && idx + 3 < total) { + ++idx; + m_bounding_sphere_pos.x = to_float(tokens[idx++]); + m_bounding_sphere_pos.y = to_float(tokens[idx++]); + m_bounding_sphere_pos.z = to_float(tokens[idx++]); + } else if (token == "group" && idx + 1 < total && to_lower(tokens[idx + 1]) == "particle") { + idx += 2; + if (idx < total && tokens[idx] == "{") ++idx; + + ParticleElement pe; + int depth = 1; + + while (idx < total && depth > 0) { + std::string p_tok = to_lower(tokens[idx]); + + if (tokens[idx] == "{") { + ++depth; + ++idx; + continue; + } + if (tokens[idx] == "}") { + --depth; + ++idx; + continue; + } + + if (p_tok == "starttime" && idx + 1 < total) { + ++idx; + pe.start_time = to_float(tokens[idx++]); + } else if (p_tok == "position" && idx + 3 < total) { + ++idx; + pe.position.x = to_float(tokens[idx++]); + pe.position.y = to_float(tokens[idx++]); + pe.position.z = to_float(tokens[idx++]); + } else if (p_tok == "list" && idx + 1 < total && to_lower(tokens[idx + 1]) == "timeeventposition") { + idx += 2; + if (idx < total && tokens[idx] == "{") { + ++idx; + while (idx < total && tokens[idx] != "}") { + // Can contain moving type and coordinates + float t = to_float(tokens[idx++]); + (void)t; + if (idx < total && tokens[idx] != "}") { + std::string mov_type = tokens[idx++]; + (void)mov_type; + if (idx + 2 < total && tokens[idx] != "}") { + pe.position.x = to_float(tokens[idx++]); + pe.position.y = to_float(tokens[idx++]); + pe.position.z = to_float(tokens[idx++]); + } + } + } + if (idx < total && tokens[idx] == "}") ++idx; + } + } else if (p_tok == "group" && idx + 1 < total && to_lower(tokens[idx + 1]) == "emitterproperty") { + idx += 2; + if (idx < total && tokens[idx] == "{") ++idx; + int edepth = 1; + while (idx < total && edepth > 0) { + std::string e_tok = to_lower(tokens[idx]); + if (tokens[idx] == "{") { ++edepth; ++idx; continue; } + if (tokens[idx] == "}") { --edepth; ++idx; continue; } + + if (e_tok == "maxemissioncount" && idx + 1 < total) { + ++idx; pe.emitter.max_emission_count = to_int(tokens[idx++]); + } else if (e_tok == "cyclelength" && idx + 1 < total) { + ++idx; pe.emitter.cycle_length = to_float(tokens[idx++]); + } else if (e_tok == "cycleloopenable" && idx + 1 < total) { + ++idx; pe.emitter.cycle_loop_enable = (to_int(tokens[idx++]) != 0); + } else if (e_tok == "loopcount" && idx + 1 < total) { + ++idx; pe.emitter.loop_count = to_int(tokens[idx++]); + } else if (e_tok == "emittershape" && idx + 1 < total) { + ++idx; pe.emitter.emitter_shape = static_cast(to_int(tokens[idx++])); + } else if (e_tok == "emittingdirection" && idx + 3 < total) { + ++idx; + pe.emitter.emitting_direction.x = to_float(tokens[idx++]); + pe.emitter.emitting_direction.y = to_float(tokens[idx++]); + pe.emitter.emitting_direction.z = to_float(tokens[idx++]); + } else if (e_tok == "list" && idx + 1 < total) { + std::string list_name = to_lower(tokens[idx + 1]); + idx += 2; + if (list_name == "timeeventemittingvelocity") read_time_events(pe.emitter.time_emitting_velocity); + else if (list_name == "timeeventemissioncountpersecond") read_time_events(pe.emitter.time_emission_count_per_second); + else if (list_name == "timeeventlifetime") read_time_events(pe.emitter.time_life_time); + else if (list_name == "timeeventsizex") read_time_events(pe.emitter.time_size_x); + else if (list_name == "timeeventsizey") read_time_events(pe.emitter.time_size_y); + else if (list_name == "timeeventemittingdirectionx") read_time_events(pe.emitter.time_emitting_dir_x); + else if (list_name == "timeeventemittingdirectiony") read_time_events(pe.emitter.time_emitting_dir_y); + else if (list_name == "timeeventemittingdirectionz") read_time_events(pe.emitter.time_emitting_dir_z); + else if (list_name == "timeeventemittingangularvelocity") read_time_events(pe.emitter.time_emitting_angular_velocity); + else { + // Skip unknown list + if (idx < total && tokens[idx] == "{") { + ++idx; + while (idx < total && tokens[idx] != "}") ++idx; + if (idx < total && tokens[idx] == "}") ++idx; + } + } + } else { + ++idx; + } + } + } else if (p_tok == "group" && idx + 1 < total && to_lower(tokens[idx + 1]) == "particleproperty") { + idx += 2; + if (idx < total && tokens[idx] == "{") ++idx; + int pdepth = 1; + while (idx < total && pdepth > 0) { + std::string pp_tok = to_lower(tokens[idx]); + if (tokens[idx] == "{") { ++pdepth; ++idx; continue; } + if (tokens[idx] == "}") { --pdepth; ++idx; continue; } + + if (pp_tok == "srcblendtype" && idx + 1 < total) { + ++idx; pe.particle.src_blend_type = static_cast(to_int(tokens[idx++])); + } else if (pp_tok == "destblendtype" && idx + 1 < total) { + ++idx; pe.particle.dest_blend_type = static_cast(to_int(tokens[idx++])); + } else if (pp_tok == "coloroperationtype" && idx + 1 < total) { + ++idx; pe.particle.color_op_type = static_cast(to_int(tokens[idx++])); + } else if (pp_tok == "billboardtype" && idx + 1 < total) { + ++idx; pe.particle.billboard_type = static_cast(to_int(tokens[idx++])); + } else if (pp_tok == "rotationtype" && idx + 1 < total) { + ++idx; pe.particle.rotation_type = static_cast(to_int(tokens[idx++])); + } else if (pp_tok == "rotationspeed" && idx + 1 < total) { + ++idx; pe.particle.rotation_speed = to_float(tokens[idx++]); + } else if (pp_tok == "attachenable" && idx + 1 < total) { + ++idx; pe.particle.attach_enable = (to_int(tokens[idx++]) != 0); + } else if (pp_tok == "stretchenable" && idx + 1 < total) { + ++idx; pe.particle.stretch_enable = (to_int(tokens[idx++]) != 0); + } else if (pp_tok == "list" && idx + 1 < total) { + std::string list_name = to_lower(tokens[idx + 1]); + idx += 2; + if (list_name == "timeeventgravity") read_time_events(pe.particle.time_gravity); + else if (list_name == "timeeventairresistance") read_time_events(pe.particle.time_air_resistance); + else if (list_name == "timeeventscalex") read_time_events(pe.particle.time_scale_x); + else if (list_name == "timeeventscaley") read_time_events(pe.particle.time_scale_y); + else if (list_name == "timeeventcolorred") read_time_events(pe.particle.time_color_r); + else if (list_name == "timeeventcolorgreen") read_time_events(pe.particle.time_color_g); + else if (list_name == "timeeventcolorblue") read_time_events(pe.particle.time_color_b); + else if (list_name == "timeeventalpha") read_time_events(pe.particle.time_alpha); + else if (list_name == "timeeventrotation") read_time_events(pe.particle.time_rotation); + else if (list_name == "texturefiles") { + if (idx < total && tokens[idx] == "{") { + ++idx; + while (idx < total && tokens[idx] != "}") { + pe.particle.texture_files.push_back(tokens[idx++]); + } + if (idx < total && tokens[idx] == "}") ++idx; + } + } else { + if (idx < total && tokens[idx] == "{") { + ++idx; + while (idx < total && tokens[idx] != "}") ++idx; + if (idx < total && tokens[idx] == "}") ++idx; + } + } + } else { + ++idx; + } + } + } else { + ++idx; + } + } + m_particles.push_back(std::move(pe)); + } else { + ++idx; + } + } + + return !m_particles.empty() || m_bounding_sphere_radius > 0.0f; +} + +} // namespace effect diff --git a/effect/src/effect_instance.cpp b/effect/src/effect_instance.cpp new file mode 100644 index 0000000..3b40858 --- /dev/null +++ b/effect/src/effect_instance.cpp @@ -0,0 +1,214 @@ +#include "effect/effect_instance.h" +#include +#include + +namespace effect { + +EffectInstance::EffectInstance(std::shared_ptr data) + : m_data(std::move(data)) { + if (m_data) { + m_emitters.resize(m_data->get_particles().size()); + } +} + +size_t EffectInstance::get_active_particle_count() const { + size_t count = 0; + for (const auto& emitter : m_emitters) { + count += emitter.particles.size(); + } + return count; +} + +void EffectInstance::update(float dt) { + if (!m_is_alive || !m_data) return; + + m_age += dt; + const auto& particles_def = m_data->get_particles(); + bool any_active = false; + + for (size_t i = 0; i < particles_def.size(); ++i) { + const auto& p_def = particles_def[i]; + auto& emitter_inst = m_emitters[i]; + + if (m_age < p_def.start_time) { + any_active = true; + continue; + } + + emitter_inst.local_time += dt; + float cycle_len = p_def.emitter.cycle_length > 0.0f ? p_def.emitter.cycle_length : 1.0f; + float current_cycle_time = emitter_inst.local_time; + + if (p_def.emitter.cycle_loop_enable) { + current_cycle_time = std::fmod(emitter_inst.local_time, cycle_len); + } else if (emitter_inst.local_time > cycle_len) { + // cycle finished + } + + // 1. Spawning new particles + float emission_rate = interpolate_time_event( + p_def.emitter.time_emission_count_per_second, current_cycle_time, 10.0f + ); + + bool can_emit = p_def.emitter.cycle_loop_enable || (emitter_inst.local_time <= cycle_len); + if (p_def.emitter.max_emission_count > 0 && + emitter_inst.emitted_count >= p_def.emitter.max_emission_count && + !p_def.emitter.cycle_loop_enable) { + can_emit = false; + } + + if (can_emit) { + emitter_inst.emission_accumulator += emission_rate * dt; + while (emitter_inst.emission_accumulator >= 1.0f) { + emitter_inst.emission_accumulator -= 1.0f; + if (p_def.emitter.max_emission_count > 0 && + emitter_inst.emitted_count >= p_def.emitter.max_emission_count && + !p_def.emitter.cycle_loop_enable) { + break; + } + + ParticleState p; + p.pos = p_def.position; + if (!m_has_custom_matrix) { + p.pos += m_position; + } else { + p.pos = m_world_matrix.transform_point(p.pos); + } + + float vel_mag = interpolate_time_event(p_def.emitter.time_emitting_velocity, current_cycle_time, 50.0f); + Vec3 dir = p_def.emitter.emitting_direction; + if (dir.length_sq() < 1e-4f) { + dir = {0.0f, 0.0f, 1.0f}; + } else { + dir = dir.normalized(); + } + + p.vel = dir * vel_mag; + p.max_life = interpolate_time_event(p_def.emitter.time_life_time, current_cycle_time, 1.5f); + if (p.max_life <= 0.0f) p.max_life = 0.1f; + p.life = 0.0f; + p.base_size_x = interpolate_time_event(p_def.emitter.time_size_x, current_cycle_time, 32.0f); + p.base_size_y = interpolate_time_event(p_def.emitter.time_size_y, current_cycle_time, 32.0f); + p.rot_speed = p_def.particle.rotation_speed; + + emitter_inst.particles.push_back(p); + emitter_inst.emitted_count++; + } + } + + // 2. Update active particles + for (auto it = emitter_inst.particles.begin(); it != emitter_inst.particles.end();) { + it->life += dt; + if (it->life >= it->max_life) { + it = emitter_inst.particles.erase(it); + continue; + } + + float norm_life = it->life / it->max_life; + float grav = interpolate_time_event(p_def.particle.time_gravity, norm_life, 0.0f); + float air_res = interpolate_time_event(p_def.particle.time_air_resistance, norm_life, 0.0f); + + it->vel.z -= grav * dt; + if (air_res > 0.0f) { + float drag = std::max(0.0f, 1.0f - air_res * dt); + it->vel *= drag; + } + + it->pos += it->vel * dt; + it->rot += it->rot_speed * dt; + ++it; + } + + if (!emitter_inst.particles.empty() || can_emit) { + any_active = true; + } + } + + if (!any_active) { + m_is_alive = false; + } +} + +void EffectInstance::build_draw_batches(const Vec3& camera_pos, + const Vec3& camera_dir, + const Vec3& camera_up, + std::vector& out_batches) { + if (!m_data) return; + + Vec3 cam_fwd = camera_dir.normalized(); + Vec3 cam_up = camera_up.normalized(); + Vec3 cam_right = Vec3::cross(cam_fwd, cam_up).normalized(); + + const auto& particles_def = m_data->get_particles(); + + for (size_t i = 0; i < particles_def.size(); ++i) { + const auto& p_def = particles_def[i]; + const auto& emitter_inst = m_emitters[i]; + if (emitter_inst.particles.empty()) continue; + + ParticleDrawBatch batch; + if (!p_def.particle.texture_files.empty()) { + batch.texture = p_def.particle.texture_files[0]; + } + batch.src_blend = p_def.particle.src_blend_type; + batch.dest_blend = p_def.particle.dest_blend_type; + batch.color_op = p_def.particle.color_op_type; + + for (const auto& p : emitter_inst.particles) { + float norm_life = p.life / p.max_life; + + float scale_x = interpolate_time_event(p_def.particle.time_scale_x, norm_life, 1.0f); + float scale_y = interpolate_time_event(p_def.particle.time_scale_y, norm_life, 1.0f); + float half_w = (p.base_size_x * scale_x) * 0.5f; + float half_h = (p.base_size_y * scale_y) * 0.5f; + + Color4 col; + col.r = interpolate_time_event(p_def.particle.time_color_r, norm_life, 1.0f); + col.g = interpolate_time_event(p_def.particle.time_color_g, norm_life, 1.0f); + col.b = interpolate_time_event(p_def.particle.time_color_b, norm_life, 1.0f); + col.a = interpolate_time_event(p_def.particle.time_alpha, norm_life, 1.0f); + + Vec3 right_vec = cam_right; + Vec3 up_vec = cam_up; + + if (p_def.particle.billboard_type == 2) { + // Cylindrical Y/Z billboard + Vec3 to_cam = (camera_pos - p.pos).normalized(); + to_cam.z = 0.0f; + to_cam = to_cam.normalized(); + right_vec = Vec3::cross({0.0f, 0.0f, 1.0f}, to_cam).normalized(); + up_vec = {0.0f, 0.0f, 1.0f}; + } else if (p_def.particle.billboard_type == 3) { + // Flat horizontal billboard + right_vec = {1.0f, 0.0f, 0.0f}; + up_vec = {0.0f, 1.0f, 0.0f}; + } + + uint32_t base_idx = static_cast(batch.vertices.size()); + + // 4 Quad vertices + Vec3 p0 = p.pos - right_vec * half_w - up_vec * half_h; + Vec3 p1 = p.pos + right_vec * half_w - up_vec * half_h; + Vec3 p2 = p.pos + right_vec * half_w + up_vec * half_h; + Vec3 p3 = p.pos - right_vec * half_w + up_vec * half_h; + + batch.vertices.push_back({p0, col, 0.0f, 0.0f}); + batch.vertices.push_back({p1, col, 1.0f, 0.0f}); + batch.vertices.push_back({p2, col, 1.0f, 1.0f}); + batch.vertices.push_back({p3, col, 0.0f, 1.0f}); + + batch.indices.push_back(base_idx + 0); + batch.indices.push_back(base_idx + 1); + batch.indices.push_back(base_idx + 2); + batch.indices.push_back(base_idx + 0); + batch.indices.push_back(base_idx + 2); + batch.indices.push_back(base_idx + 3); + } + + if (!batch.vertices.empty()) { + out_batches.push_back(std::move(batch)); + } + } +} + +} // namespace effect diff --git a/effect/src/effect_manager.cpp b/effect/src/effect_manager.cpp new file mode 100644 index 0000000..72b8a5e --- /dev/null +++ b/effect/src/effect_manager.cpp @@ -0,0 +1,88 @@ +#include "effect/effect_manager.h" + +namespace effect { + +void EffectManager::clear() { + m_effects.clear(); + m_flying.clear(); + m_effect_cache.clear(); + m_flying_cache.clear(); +} + +std::shared_ptr EffectManager::get_or_load_effect(const std::string& filepath) { + auto it = m_effect_cache.find(filepath); + if (it != m_effect_cache.end()) { + return it->second; + } + + auto data = std::make_shared(); + if (data->load_file(filepath)) { + m_effect_cache[filepath] = data; + return data; + } + return nullptr; +} + +std::shared_ptr EffectManager::get_or_load_flying(const std::string& filepath) { + auto it = m_flying_cache.find(filepath); + if (it != m_flying_cache.end()) { + return it->second; + } + + auto data = std::make_shared(); + if (data->load_file(filepath)) { + m_flying_cache[filepath] = data; + return data; + } + return nullptr; +} + +std::shared_ptr EffectManager::spawn_effect(const std::string& filepath, const Vec3& pos) { + auto data = get_or_load_effect(filepath); + if (!data) return nullptr; + + auto inst = std::make_shared(data); + inst->set_position(pos); + m_effects.push_back(inst); + return inst; +} + +std::shared_ptr EffectManager::spawn_flying(const std::string& filepath, const Vec3& start, const Vec3& target) { + auto data = get_or_load_flying(filepath); + if (!data) return nullptr; + + auto inst = std::make_shared(data, start, target); + m_flying.push_back(inst); + return inst; +} + +void EffectManager::update(float dt) { + for (auto it = m_effects.begin(); it != m_effects.end();) { + (*it)->update(dt); + if (!(*it)->is_alive()) { + it = m_effects.erase(it); + } else { + ++it; + } + } + + for (auto it = m_flying.begin(); it != m_flying.end();) { + bool alive = (*it)->update(dt); + if (!alive || !(*it)->is_alive()) { + it = m_flying.erase(it); + } else { + ++it; + } + } +} + +void EffectManager::build_draw_batches(const Vec3& camera_pos, + const Vec3& camera_dir, + const Vec3& camera_up, + std::vector& out_batches) { + for (auto& eff : m_effects) { + eff->build_draw_batches(camera_pos, camera_dir, camera_up, out_batches); + } +} + +} // namespace effect diff --git a/effect/src/flying_data.cpp b/effect/src/flying_data.cpp new file mode 100644 index 0000000..e379a7a --- /dev/null +++ b/effect/src/flying_data.cpp @@ -0,0 +1,142 @@ +#include "effect/flying_data.h" +#include +#include +#include +#include + +namespace effect { + +namespace { + +float to_float(const std::string& s) { + return std::strtof(s.c_str(), nullptr); +} + +int to_int(const std::string& s) { + return std::atoi(s.c_str()); +} + +std::string to_lower(std::string s) { + std::transform(s.begin(), s.end(), s.begin(), [](unsigned char c) { + return std::tolower(c); + }); + return s; +} + +std::vector tokenize(const std::string& content) { + std::vector tokens; + size_t i = 0; + size_t n = content.size(); + + while (i < n) { + while (i < n && (content[i] == ' ' || content[i] == '\t' || content[i] == '\r' || content[i] == '\n')) { + ++i; + } + if (i >= n) break; + + if (i + 1 < n && content[i] == '/' && content[i + 1] == '/') { + while (i < n && content[i] != '\n') ++i; + continue; + } + + if (content[i] == '{' || content[i] == '}') { + tokens.push_back(std::string(1, content[i])); + ++i; + continue; + } + + if (content[i] == '"') { + ++i; + size_t start = i; + while (i < n && content[i] != '"') ++i; + tokens.push_back(content.substr(start, i - start)); + if (i < n && content[i] == '"') ++i; + continue; + } + + size_t start = i; + while (i < n && content[i] != ' ' && content[i] != '\t' && content[i] != '\r' && content[i] != '\n' && + content[i] != '{' && content[i] != '}' && content[i] != '"') { + ++i; + } + tokens.push_back(content.substr(start, i - start)); + } + return tokens; +} + +} // anonymous namespace + +bool FlyingData::load_file(const std::filesystem::path& filepath) { + std::ifstream file(filepath, std::ios::binary); + if (!file.is_open()) return false; + + std::stringstream buf; + buf << file.rdbuf(); + return load_from_string(buf.str()); +} + +bool FlyingData::load_from_string(const std::string& content) { + auto tokens = tokenize(content); + size_t idx = 0; + size_t total = tokens.size(); + + while (idx < total) { + std::string tok = to_lower(tokens[idx]); + + if (tok == "initialvelocity" && idx + 1 < total) { + ++idx; initial_velocity = to_float(tokens[idx++]); + } else if (tok == "gravity" && idx + 1 < total) { + ++idx; gravity = to_float(tokens[idx++]); + } else if (tok == "bombrange" && idx + 1 < total) { + ++idx; bomb_range = to_float(tokens[idx++]); + } else if (tok == "bombeffect" && idx + 1 < total) { + ++idx; bomb_effect = tokens[idx++]; + } else if (tok == "homingflag" && idx + 1 < total) { + ++idx; homing_flag = (to_int(tokens[idx++]) != 0); + } else if (tok == "homingstarttime" && idx + 1 < total) { + ++idx; homing_start_time = to_float(tokens[idx++]); + } else if (tok == "homingmaxangle" && idx + 1 < total) { + ++idx; homing_max_angle = to_float(tokens[idx++]); + } else if (tok == "range" && idx + 1 < total) { + ++idx; range = to_float(tokens[idx++]); + } else if (tok == "acceleration" && idx + 3 < total) { + ++idx; + acceleration.x = to_float(tokens[idx++]); + acceleration.y = to_float(tokens[idx++]); + acceleration.z = to_float(tokens[idx++]); + } else if (tok == "group" && idx + 1 < total && to_lower(tokens[idx + 1]) == "attachdata") { + idx += 2; + if (idx < total && tokens[idx] == "{") ++idx; + int depth = 1; + while (idx < total && depth > 0) { + std::string a_tok = to_lower(tokens[idx]); + if (tokens[idx] == "{") { ++depth; ++idx; continue; } + if (tokens[idx] == "}") { --depth; ++idx; continue; } + + if (a_tok == "type" && idx + 1 < total) { + ++idx; attach.type = to_int(tokens[idx++]); + } else if (a_tok == "flytype" && idx + 1 < total) { + ++idx; attach.fly_type = to_int(tokens[idx++]); + } else if (a_tok == "attachfile" && idx + 1 < total) { + ++idx; attach.attach_file = tokens[idx++]; + } else if (a_tok == "tailflag" && idx + 1 < total) { + ++idx; attach.has_tail = (to_int(tokens[idx++]) != 0); + } else if (a_tok == "taillength" && idx + 1 < total) { + ++idx; attach.tail_length = to_float(tokens[idx++]); + } else if (a_tok == "tailsize" && idx + 1 < total) { + ++idx; attach.tail_size = to_float(tokens[idx++]); + } else if (a_tok == "tailshaperect" && idx + 1 < total) { + ++idx; attach.rect_shape = (to_int(tokens[idx++]) != 0); + } else { + ++idx; + } + } + } else { + ++idx; + } + } + + return true; +} + +} // namespace effect diff --git a/effect/src/flying_instance.cpp b/effect/src/flying_instance.cpp new file mode 100644 index 0000000..6152686 --- /dev/null +++ b/effect/src/flying_instance.cpp @@ -0,0 +1,79 @@ +#include "effect/flying_instance.h" +#include +#include + +namespace effect { + +FlyingInstance::FlyingInstance(std::shared_ptr data, const Vec3& start_pos, const Vec3& target_pos) + : m_data(std::move(data)), m_position(start_pos), m_target(target_pos) { + Vec3 dir = (m_target - m_position).normalized(); + float speed = m_data ? m_data->initial_velocity : 2000.0f; + m_velocity = dir * speed; + m_trail.push_back({m_position, 0.0f}); +} + +bool FlyingInstance::update(float dt) { + if (!m_is_alive || !m_data) return false; + + m_age += dt; + + // Check hit condition + Vec3 to_target = m_target - m_position; + float dist = to_target.length(); + if (dist <= m_data->bomb_range) { + m_is_alive = false; + if (m_hit_cb) { + m_hit_cb(m_position); + } + return false; + } + + // Homing steering + if (m_data->homing_flag && m_age >= m_data->homing_start_time && dist > 1e-4f) { + Vec3 desired_dir = to_target.normalized(); + float current_speed = m_velocity.length(); + if (current_speed > 1e-4f) { + Vec3 current_dir = m_velocity / current_speed; + float dot_val = std::clamp(Vec3::dot(current_dir, desired_dir), -1.0f, 1.0f); + float angle = std::acos(dot_val); + + // Maximum turn angle this frame (homing_max_angle in radians or degrees) + float max_turn = m_data->homing_max_angle * dt; + if (angle <= max_turn) { + current_dir = desired_dir; + } else { + // Slerp towards desired direction + float t = max_turn / angle; + current_dir = Vec3::lerp(current_dir, desired_dir, t).normalized(); + } + m_velocity = current_dir * current_speed; + } + } + + // Ballistic physics: acceleration & gravity + m_velocity += m_data->acceleration * dt; + m_velocity.z -= m_data->gravity * dt; + + Vec3 step = m_velocity * dt; + m_position += step; + m_distance_traveled += step.length(); + + // Check range limit + if (m_distance_traveled >= m_data->range) { + m_is_alive = false; + return false; + } + + // Update trail + if (m_data->attach.has_tail) { + m_trail.push_back({m_position, m_age}); + float max_tail_time = m_data->attach.tail_length > 0.0f ? m_data->attach.tail_length : 0.2f; + while (!m_trail.empty() && (m_age - m_trail.front().time) > max_tail_time) { + m_trail.erase(m_trail.begin()); + } + } + + return true; +} + +} // namespace effect diff --git a/effect/src/time_event.cpp b/effect/src/time_event.cpp new file mode 100644 index 0000000..6dd1c37 --- /dev/null +++ b/effect/src/time_event.cpp @@ -0,0 +1,21 @@ +#include "effect/time_event.h" + +namespace effect { + +float interpolate_time_event(const std::vector& events, float time, float default_val) { + if (events.empty()) return default_val; + if (events.size() == 1 || time <= events.front().time) return events.front().value; + if (time >= events.back().time) return events.back().value; + + for (size_t i = 0; i + 1 < events.size(); ++i) { + if (time >= events[i].time && time <= events[i + 1].time) { + float dt = events[i + 1].time - events[i].time; + if (dt < 1e-6f) return events[i].value; + float t = (time - events[i].time) / dt; + return events[i].value + t * (events[i + 1].value - events[i].value); + } + } + return events.back().value; +} + +} // namespace effect diff --git a/effect/tests/effect_test.cpp b/effect/tests/effect_test.cpp new file mode 100644 index 0000000..adab1ad --- /dev/null +++ b/effect/tests/effect_test.cpp @@ -0,0 +1,251 @@ +#include "effect/effect.h" +#include +#include +#include +#include + +namespace fs = std::filesystem; + +static int g_failures = 0; +#define TEST_CHECK(cond) \ + do { \ + if (!(cond)) { \ + std::cerr << "FAIL [" << __FILE__ << ":" << __LINE__ << "]: " #cond << std::endl; \ + ++g_failures; \ + } \ + } while(0) + +void test_math_and_time_events() { + std::cout << "[Test] Math & TimeEvent interpolation..." << std::endl; + + effect::Vec3 v1{1.0f, 2.0f, 3.0f}; + effect::Vec3 v2{4.0f, 5.0f, 6.0f}; + effect::Vec3 v3 = v1 + v2; + TEST_CHECK(v3.x == 5.0f && v3.y == 7.0f && v3.z == 9.0f); + + float d = effect::Vec3::dot({1, 0, 0}, {0, 1, 0}); + TEST_CHECK(std::abs(d) < 1e-5f); + + effect::Vec3 c = effect::Vec3::cross({1, 0, 0}, {0, 1, 0}); + TEST_CHECK(std::abs(c.x) < 1e-5f && std::abs(c.y) < 1e-5f && std::abs(c.z - 1.0f) < 1e-5f); + + std::vector events = { + {0.0f, 10.0f}, + {1.0f, 20.0f}, + {3.0f, 40.0f} + }; + + TEST_CHECK(effect::interpolate_time_event(events, -0.5f) == 10.0f); + TEST_CHECK(effect::interpolate_time_event(events, 0.0f) == 10.0f); + TEST_CHECK(effect::interpolate_time_event(events, 0.5f) == 15.0f); + TEST_CHECK(effect::interpolate_time_event(events, 1.0f) == 20.0f); + TEST_CHECK(effect::interpolate_time_event(events, 2.0f) == 30.0f); + TEST_CHECK(effect::interpolate_time_event(events, 3.0f) == 40.0f); + TEST_CHECK(effect::interpolate_time_event(events, 5.0f) == 40.0f); +} + +void test_effect_data_and_simulation() { + std::cout << "[Test] Effect script parsing & particle simulation..." << std::endl; + + std::string script = R"( +BoundingSphereRadius 120.000000 +BoundingSpherePosition 10.000000 20.000000 30.000000 + +Group Particle +{ + StartTime 0.000000 + Position 0.000000 0.000000 50.000000 + + Group EmitterProperty + { + MaxEmissionCount 10 + CycleLength 1.000000 + CycleLoopEnable 1 + EmittingDirection 0.000000 0.000000 1.000000 + + List TimeEventEmittingVelocity + { + 0.000000 100.000000 + } + List TimeEventEmissionCountPerSecond + { + 0.000000 50.000000 + } + List TimeEventLifeTime + { + 0.000000 1.000000 + } + List TimeEventSizeX + { + 0.000000 20.000000 + } + List TimeEventSizeY + { + 0.000000 20.000000 + } + } + + Group ParticleProperty + { + SrcBlendType 5 + DestBlendType 2 + BillboardType 1 + RotationSpeed 2.000000 + + List TimeEventGravity + { + 0.000000 9.800000 + } + List TimeEventAlpha + { + 0.000000 0.000000 + 0.500000 1.000000 + 1.000000 0.000000 + } + List TextureFiles + { + "d:/ymir work/effect/flare.dds" + } + } +} +)"; + + auto eff_data = std::make_shared(); + TEST_CHECK(eff_data->load_from_string(script)); + TEST_CHECK(eff_data->get_bounding_sphere_radius() == 120.0f); + TEST_CHECK(eff_data->get_bounding_sphere_position().x == 10.0f); + TEST_CHECK(eff_data->get_particles().size() == 1); + + const auto& p0 = eff_data->get_particles()[0]; + TEST_CHECK(p0.particle.texture_files.size() == 1); + TEST_CHECK(p0.particle.texture_files[0] == "d:/ymir work/effect/flare.dds"); + TEST_CHECK(p0.particle.billboard_type == 1); + TEST_CHECK(p0.particle.rotation_speed == 2.0f); + + // Test simulation + effect::EffectInstance instance(eff_data); + instance.set_position(0.0f, 0.0f, 0.0f); + TEST_CHECK(instance.is_alive()); + TEST_CHECK(instance.get_active_particle_count() == 0); + + // Step simulation by 0.1s -> should emit particles + instance.update(0.1f); + TEST_CHECK(instance.get_active_particle_count() > 0); + + // Verify drawing commands / billboards + std::vector batches; + instance.build_draw_batches({0.0f, -100.0f, 50.0f}, {0.0f, 1.0f, 0.0f}, {0.0f, 0.0f, 1.0f}, batches); + TEST_CHECK(!batches.empty()); + if (!batches.empty()) { + TEST_CHECK(batches[0].texture == "d:/ymir work/effect/flare.dds"); + TEST_CHECK(batches[0].vertices.size() >= 4); + TEST_CHECK(batches[0].indices.size() >= 6); + } +} + +void test_flying_homing_missile() { + std::cout << "[Test] Flying homing missile physics & hit..." << std::endl; + + std::string fly_script = R"( +InitialVelocity 1000.000000 +Gravity 0.000000 +BombRange 15.000000 +HomingFlag 1 +HomingMaxAngle 10.000000 +Range 5000.000000 +Group AttachData +{ + Type 1 + AttachFile "arrow.mse" + TailFlag 1 + TailLength 0.200000 +} +)"; + + auto fly_data = std::make_shared(); + TEST_CHECK(fly_data->load_from_string(fly_script)); + TEST_CHECK(fly_data->initial_velocity == 1000.0f); + TEST_CHECK(fly_data->bomb_range == 15.0f); + TEST_CHECK(fly_data->homing_flag == true); + TEST_CHECK(fly_data->attach.has_tail == true); + + effect::Vec3 start{0.0f, 0.0f, 0.0f}; + effect::Vec3 target{100.0f, 20.0f, 0.0f}; + + bool hit_called = false; + effect::Vec3 hit_location; + + effect::FlyingInstance fly_inst(fly_data, start, target); + fly_inst.set_hit_callback([&](const effect::Vec3& loc) { + hit_called = true; + hit_location = loc; + }); + + // Step physics towards target + float dt = 0.02f; + for (int step = 0; step < 50; ++step) { + if (!fly_inst.is_alive()) break; + fly_inst.update(dt); + } + + TEST_CHECK(hit_called); + TEST_CHECK((hit_location - target).length() <= fly_data->bomb_range); +} + +void test_real_effect_files_if_present() { + std::cout << "[Test] Real effect files check..." << std::endl; + std::vector mse_paths = { + "metin2-client/build/zh-locale/locale-src/zh/effect/gm.mse", + "../../metin2-client/build/zh-locale/locale-src/zh/effect/gm.mse", + "ava2-client/ymir work/pc/warrior/effect/geom_4_badak.mse", + "../../ava2-client/ymir work/pc/warrior/effect/geom_4_badak.mse" + }; + + for (const auto& path : mse_paths) { + if (fs::exists(path)) { + effect::EffectData data; + bool ok = data.load_file(path); + TEST_CHECK(ok); + if (ok) { + std::cout << " -> Loaded real MSE (" << path << "), particles count: " + << data.get_particles().size() << std::endl; + } + break; + } + } + + std::vector msf_paths = { + "ava2-client/ymir work/pc/warrior/effect/geompung.msf", + "../../ava2-client/ymir work/pc/warrior/effect/geompung.msf" + }; + + for (const auto& path : msf_paths) { + if (fs::exists(path)) { + effect::FlyingData data; + bool ok = data.load_file(path); + TEST_CHECK(ok); + if (ok) { + std::cout << " -> Loaded real MSF (" << path << "), init velocity: " + << data.initial_velocity << ", homing: " + << data.homing_flag << std::endl; + } + break; + } + } +} + +int main() { + std::cout << "=== Running effect Unit Tests ===" << std::endl; + test_math_and_time_events(); + test_effect_data_and_simulation(); + test_flying_homing_missile(); + test_real_effect_files_if_present(); + + if (g_failures == 0) { + std::cout << "=== ALL effect TESTS PASSED ===" << std::endl; + return 0; + } else { + std::cerr << "=== " << g_failures << " effect TESTS FAILED ===" << std::endl; + return 1; + } +} diff --git a/eterpack/CMakeLists.txt b/eterpack/CMakeLists.txt new file mode 100644 index 0000000..1a0ed15 --- /dev/null +++ b/eterpack/CMakeLists.txt @@ -0,0 +1,33 @@ +cmake_minimum_required(VERSION 3.20) +project(eterpack LANGUAGES C CXX) + +set(CMAKE_CXX_STANDARD 20) +set(CMAKE_CXX_STANDARD_REQUIRED ON) + +add_library(minilzo STATIC src/minilzo/minilzo.c) +target_include_directories(minilzo PUBLIC src/minilzo) +set_target_properties(minilzo PROPERTIES C_STANDARD 99) + +add_library(eterpack STATIC + src/tea.cpp + src/crc32.cpp + src/lzo.cpp + src/archive.cpp + src/vfs.cpp +) + +target_include_directories(eterpack PUBLIC + $ + $ +) + +target_link_libraries(eterpack PUBLIC minilzo) + +add_library(eterpack::eterpack ALIAS eterpack) + +option(ETERPACK_BUILD_TESTS "Build eterpack SDK tests" ON) +if(ETERPACK_BUILD_TESTS) + add_executable(eterpack_test tests/eterpack_test.cpp) + target_link_libraries(eterpack_test PRIVATE eterpack) + add_test(NAME eterpack_test COMMAND eterpack_test) +endif() diff --git a/eterpack/include/eterpack/archive.h b/eterpack/include/eterpack/archive.h new file mode 100644 index 0000000..4f3856b --- /dev/null +++ b/eterpack/include/eterpack/archive.h @@ -0,0 +1,71 @@ +#pragma once + +#include "eterpack/types.h" +#include +#include +#include +#include +#include +#include + +namespace eterpack { + +class EterPackArchive { +public: + EterPackArchive(); + ~EterPackArchive(); + + // Open from file path (e.g., "pack/root" or "root.eix") + bool open(const std::string& base_or_eix_path, + const uint32_t index_key[4] = DEFAULT_ETERPACK_KEY, + const uint32_t security_key[4] = DEFAULT_SECURITY_KEY); + + // Open from memory buffers (for tests and embedded use) + bool open_memory(std::span eix_data, + std::span epk_data, + const uint32_t index_key[4] = DEFAULT_ETERPACK_KEY, + const uint32_t security_key[4] = DEFAULT_SECURITY_KEY); + + void close(); + + bool is_open() const { return m_is_open; } + const std::string& get_name() const { return m_archive_name; } + size_t get_entry_count() const { return m_entries.size(); } + const std::vector& get_entries() const { return m_entries; } + + bool has_file(std::string_view filename) const; + bool has_file(uint32_t crc) const; + + const EterPackIndexEntry* find_entry(std::string_view filename) const; + const EterPackIndexEntry* find_entry(uint32_t crc) const; + + bool extract(std::string_view filename, std::vector& out_data) const; + bool extract(const EterPackIndexEntry& entry, std::vector& out_data) const; + + // Pack creator / writer helper (writes .eix and .epk pair) + static bool create_archive(const std::string& base_path, + const std::vector>>& files, + bool encrypt_index = true, + const uint32_t index_key[4] = DEFAULT_ETERPACK_KEY, + CompressionType comp_type = CompressionType::Compress, + const uint32_t security_key[4] = DEFAULT_SECURITY_KEY); + +private: + bool parse_index_buffer(std::span eix_bytes, const uint32_t index_key[4]); + std::string resolve_case_insensitive(const std::string& path); + + std::string m_archive_name; + std::string m_epk_path; + bool m_is_open = false; + uint32_t m_security_key[4] = {0}; + + // Stored either as file or in-memory buffer + std::vector m_epk_memory; + mutable std::ifstream m_epk_file; + + std::vector m_entries; + std::unordered_map m_crc_map; + std::unordered_map m_name_map; +}; + +} // namespace eterpack diff --git a/eterpack/include/eterpack/crc32.h b/eterpack/include/eterpack/crc32.h new file mode 100644 index 0000000..31d3193 --- /dev/null +++ b/eterpack/include/eterpack/crc32.h @@ -0,0 +1,26 @@ +#pragma once + +#include +#include +#include +#include + +namespace eterpack { + +// Standard Metin2 / IEEE 802.3 CRC32 (polynomial 0xEDB88320) +uint32_t GetCRC32(const char* buf, size_t len); +uint32_t GetCaseCRC32(const char* buf, size_t len); + +inline uint32_t GetCRC32(std::string_view str) { + return GetCRC32(str.data(), str.size()); +} + +inline uint32_t GetCaseCRC32(std::string_view str) { + return GetCaseCRC32(str.data(), str.size()); +} + +inline uint32_t GetCRC32(std::span data) { + return GetCRC32(reinterpret_cast(data.data()), data.size()); +} + +} // namespace eterpack diff --git a/eterpack/include/eterpack/eterpack.h b/eterpack/include/eterpack/eterpack.h new file mode 100644 index 0000000..6700d4a --- /dev/null +++ b/eterpack/include/eterpack/eterpack.h @@ -0,0 +1,8 @@ +#pragma once + +#include "eterpack/types.h" +#include "eterpack/tea.h" +#include "eterpack/crc32.h" +#include "eterpack/lzo.h" +#include "eterpack/archive.h" +#include "eterpack/vfs.h" diff --git a/eterpack/include/eterpack/lzo.h b/eterpack/include/eterpack/lzo.h new file mode 100644 index 0000000..ff37638 --- /dev/null +++ b/eterpack/include/eterpack/lzo.h @@ -0,0 +1,39 @@ +#pragma once + +#include "eterpack/types.h" +#include +#include +#include +#include + +namespace eterpack { + +class LZO { +public: + static LZO& instance(); + + // Decompress an MCOZ formatted buffer (with optional TEA decryption) + bool decompress_mcoz(std::span input, + std::vector& output, + const uint32_t key[4] = nullptr); + + // Compress data into MCOZ format (with optional TEA encryption) + bool compress_mcoz(std::span input, + std::vector& output, + const uint32_t key[4] = nullptr); + + // Raw LZO1X decompression + bool raw_decompress(const uint8_t* in, size_t in_len, + uint8_t* out, size_t out_len); + + // Raw LZO1X-1 compression + bool raw_compress(const uint8_t* in, size_t in_len, + std::vector& out); + +private: + LZO(); + ~LZO(); + void* m_workmem = nullptr; +}; + +} // namespace eterpack diff --git a/eterpack/include/eterpack/tea.h b/eterpack/include/eterpack/tea.h new file mode 100644 index 0000000..75b467e --- /dev/null +++ b/eterpack/include/eterpack/tea.h @@ -0,0 +1,22 @@ +#pragma once + +#include +#include +#include +#include + +namespace eterpack { + +// Low-level TEA word routines (32 rounds, 128-bit key) +void tea_code(uint32_t sz, uint32_t sy, const uint32_t key[4], uint32_t dest[2]); +void tea_decode(uint32_t sz, uint32_t sy, const uint32_t key[4], uint32_t dest[2]); + +// Encrypt/decrypt buffer of 32-bit words with 8-byte alignment padding +int tea_encrypt(uint32_t* dest, const uint32_t* src, const uint32_t key[4], int size); +int tea_decrypt(uint32_t* dest, const uint32_t* src, const uint32_t key[4], int size); + +// Modern C++ span/vector helpers +std::vector tea_encrypt_bytes(std::span data, const uint32_t key[4]); +std::vector tea_decrypt_bytes(std::span data, const uint32_t key[4]); + +} // namespace eterpack diff --git a/eterpack/include/eterpack/types.h b/eterpack/include/eterpack/types.h new file mode 100644 index 0000000..1a423fa --- /dev/null +++ b/eterpack/include/eterpack/types.h @@ -0,0 +1,67 @@ +#pragma once + +#include +#include +#include + +namespace eterpack { + +inline constexpr uint32_t FOURCC_EPKD = 0x444b5045; // 'E', 'P', 'K', 'D' +inline constexpr uint32_t FOURCC_MCOZ = 0x5a4f434d; // 'M', 'C', 'O', 'Z' +inline constexpr uint32_t ETERPACK_VERSION = 2; +inline constexpr size_t ETERPACK_HEADER_SIZE = 12; + +inline constexpr size_t FILENAME_MAX_LEN = 160; + +// Standard Metin2 encryption keys +inline constexpr uint32_t DEFAULT_ETERPACK_KEY[4] = { + 45129401, 92367215, 681285731, 1710201 +}; + +inline constexpr uint32_t DEFAULT_SECURITY_KEY[4] = { + 78952482, 527348324, 1632942, 486274726 +}; + +inline constexpr uint32_t DEFAULT_ITEM_PROTO_KEY[4] = { + 173217, 72619434, 408587239, 27973291 +}; + +inline constexpr uint32_t DEFAULT_MOB_PROTO_KEY[4] = { + 4813894, 18955, 552631, 6822045 +}; + +enum class CompressionType : uint8_t { + None = 0, + Compress = 1, + Security = 2, + Panama = 3, + HybridCrypt = 4, + HybridCryptWithSDB = 5 +}; + +#pragma pack(push, 4) +struct EterPackIndexEntry { + int32_t id = 0; // 0..3 + char filename[FILENAME_MAX_LEN + 1]; // 4..164 (161 bytes) + // 3 bytes padding (165..167) + uint32_t filename_crc = 0; // 168..171 + int32_t real_data_size = 0; // 172..175 + int32_t data_size = 0; // 176..179 + uint32_t data_crc = 0; // 180..183 + int32_t data_position = 0; // 184..187 + uint8_t compressed_type = 0; // 188 + // 3 bytes padding (189..191) +}; + +struct LZHeader { + uint32_t fourcc = FOURCC_MCOZ; + uint32_t encrypt_size = 0; + uint32_t compressed_size = 0; + uint32_t real_size = 0; +}; +#pragma pack(pop) + +static_assert(sizeof(EterPackIndexEntry) == 192, "EterPackIndexEntry must be 192 bytes"); +static_assert(sizeof(LZHeader) == 16, "LZHeader must be 16 bytes"); + +} // namespace eterpack diff --git a/eterpack/include/eterpack/vfs.h b/eterpack/include/eterpack/vfs.h new file mode 100644 index 0000000..0e276c6 --- /dev/null +++ b/eterpack/include/eterpack/vfs.h @@ -0,0 +1,66 @@ +#pragma once + +#include "eterpack/archive.h" +#include +#include +#include +#include +#include +#include + +namespace eterpack { + +enum class VFSSearchMode { + PackFirst, + DiskFirst +}; + +class EterPackVFS { +public: + EterPackVFS(); + ~EterPackVFS(); + + void set_search_mode(VFSSearchMode mode) { m_search_mode = mode; } + VFSSearchMode get_search_mode() const { return m_search_mode; } + + // Mount an individual archive (e.g., "pack/root") + bool mount(const std::string& base_path, + const uint32_t index_key[4] = DEFAULT_ETERPACK_KEY, + const uint32_t security_key[4] = DEFAULT_SECURITY_KEY, + bool override_existing = false); + + // Mount all packs listed in a pack index file (e.g., "pack/Index") + bool mount_index_file(const std::string& index_file_path, + const std::string& pack_dir = "pack"); + + // Clear all mounted archives + void clear(); + + size_t get_archive_count() const; + size_t get_total_entry_count() const; + + bool exists(std::string_view path) const; + bool read_file(std::string_view path, std::vector& out_data) const; + + // Direct lookup by CRC32 + bool exists_crc(uint32_t crc) const; + bool read_file_crc(uint32_t crc, std::vector& out_data) const; + + std::vector list_files() const; + +private: + struct FileLocation { + size_t archive_index = 0; + const EterPackIndexEntry* entry = nullptr; + }; + + mutable std::mutex m_mutex; + VFSSearchMode m_search_mode = VFSSearchMode::PackFirst; + std::vector> m_archives; + std::unordered_map m_file_map; + std::unordered_map m_crc_map; +}; + +using VFS = EterPackVFS; + +} // namespace eterpack diff --git a/eterpack/src/archive.cpp b/eterpack/src/archive.cpp new file mode 100644 index 0000000..934744a --- /dev/null +++ b/eterpack/src/archive.cpp @@ -0,0 +1,338 @@ +#include "eterpack/archive.h" +#include "eterpack/crc32.h" +#include "eterpack/lzo.h" +#include +#include +#include +#include +#include + +namespace fs = std::filesystem; + +namespace eterpack { + +static std::string normalize_path(std::string_view p) { + std::string s(p); + for (char& c : s) { + if (c == '\\') c = '/'; + else c = static_cast(std::tolower(static_cast(c))); + } + return s; +} + +EterPackArchive::EterPackArchive() { + std::memcpy(m_security_key, DEFAULT_SECURITY_KEY, sizeof(m_security_key)); +} + +EterPackArchive::~EterPackArchive() { + close(); +} + +void EterPackArchive::close() { + if (m_epk_file.is_open()) { + m_epk_file.close(); + } + m_epk_memory.clear(); + m_entries.clear(); + m_crc_map.clear(); + m_name_map.clear(); + m_is_open = false; + m_archive_name.clear(); + m_epk_path.clear(); +} + +std::string EterPackArchive::resolve_case_insensitive(const std::string& path_str) { + fs::path p(path_str); + if (fs::exists(p)) return p.string(); + + fs::path parent = p.parent_path(); + if (parent.empty()) parent = "."; + if (!fs::exists(parent)) return path_str; + + std::string target_name = p.filename().string(); + for (const auto& entry : fs::directory_iterator(parent)) { + std::string name = entry.path().filename().string(); + if (name.size() == target_name.size()) { + bool match = true; + for (size_t i = 0; i < name.size(); ++i) { + if (std::tolower(static_cast(name[i])) != + std::tolower(static_cast(target_name[i]))) { + match = false; + break; + } + } + if (match) return entry.path().string(); + } + } + return path_str; +} + +bool EterPackArchive::open(const std::string& base_or_eix_path, + const uint32_t index_key[4], + const uint32_t security_key[4]) { + close(); + + if (security_key) { + std::memcpy(m_security_key, security_key, sizeof(m_security_key)); + } + + std::string base = base_or_eix_path; + if (base.size() >= 4 && base.substr(base.size() - 4) == ".eix") { + base = base.substr(0, base.size() - 4); + } + + std::string eix_path = resolve_case_insensitive(base + ".eix"); + m_epk_path = resolve_case_insensitive(base + ".epk"); + + std::ifstream eix_file(eix_path, std::ios::binary); + if (!eix_file.is_open()) { + return false; + } + + eix_file.seekg(0, std::ios::end); + size_t eix_size = static_cast(eix_file.tellg()); + eix_file.seekg(0, std::ios::beg); + + std::vector eix_bytes(eix_size); + if (!eix_file.read(reinterpret_cast(eix_bytes.data()), eix_size)) { + return false; + } + eix_file.close(); + + if (!parse_index_buffer(eix_bytes, index_key)) { + return false; + } + + m_epk_file.open(m_epk_path, std::ios::binary); + if (!m_epk_file.is_open()) { + close(); + return false; + } + + m_archive_name = base; + m_is_open = true; + return true; +} + +bool EterPackArchive::open_memory(std::span eix_data, + std::span epk_data, + const uint32_t index_key[4], + const uint32_t security_key[4]) { + close(); + + if (security_key) { + std::memcpy(m_security_key, security_key, sizeof(m_security_key)); + } + + if (!parse_index_buffer(eix_data, index_key)) { + return false; + } + + m_epk_memory.assign(epk_data.begin(), epk_data.end()); + m_archive_name = "memory"; + m_is_open = true; + return true; +} + +bool EterPackArchive::parse_index_buffer(std::span eix_bytes, + const uint32_t index_key[4]) { + if (eix_bytes.size() < ETERPACK_HEADER_SIZE) { + return false; + } + + uint32_t fourcc = *reinterpret_cast(eix_bytes.data()); + std::vector decompressed_eix; + std::span payload = eix_bytes; + + if (fourcc == FOURCC_MCOZ) { + if (!LZO::instance().decompress_mcoz(eix_bytes, decompressed_eix, index_key)) { + return false; + } + payload = decompressed_eix; + } else if (fourcc != FOURCC_EPKD) { + return false; + } + + if (payload.size() < ETERPACK_HEADER_SIZE) { + return false; + } + + const uint8_t* ptr = payload.data(); + uint32_t inner_fourcc = *reinterpret_cast(ptr); + uint32_t version = *reinterpret_cast(ptr + 4); + int32_t count = *reinterpret_cast(ptr + 8); + + if (inner_fourcc != FOURCC_EPKD || version != ETERPACK_VERSION || count < 0) { + return false; + } + + size_t expected_size = ETERPACK_HEADER_SIZE + static_cast(count) * sizeof(EterPackIndexEntry); + if (payload.size() < expected_size) { + return false; + } + + const auto* entries_ptr = reinterpret_cast(ptr + ETERPACK_HEADER_SIZE); + m_entries.assign(entries_ptr, entries_ptr + count); + + for (size_t i = 0; i < m_entries.size(); ++i) { + const auto& entry = m_entries[i]; + if (entry.filename_crc != 0) { + m_crc_map[entry.filename_crc] = i; + m_name_map[normalize_path(entry.filename)] = i; + } + } + + return true; +} + +bool EterPackArchive::has_file(std::string_view filename) const { + if (find_entry(filename)) return true; + uint32_t crc = GetCRC32(filename); + return has_file(crc); +} + +bool EterPackArchive::has_file(uint32_t crc) const { + return m_crc_map.find(crc) != m_crc_map.end(); +} + +const EterPackIndexEntry* EterPackArchive::find_entry(std::string_view filename) const { + auto it = m_name_map.find(normalize_path(filename)); + if (it != m_name_map.end()) { + return &m_entries[it->second]; + } + uint32_t crc = GetCRC32(filename); + return find_entry(crc); +} + +const EterPackIndexEntry* EterPackArchive::find_entry(uint32_t crc) const { + auto it = m_crc_map.find(crc); + if (it != m_crc_map.end()) { + return &m_entries[it->second]; + } + return nullptr; +} + +bool EterPackArchive::extract(std::string_view filename, std::vector& out_data) const { + const auto* entry = find_entry(filename); + if (!entry) return false; + return extract(*entry, out_data); +} + +bool EterPackArchive::extract(const EterPackIndexEntry& entry, std::vector& out_data) const { + if (!m_is_open) return false; + + std::vector raw_bytes(entry.data_size); + if (!m_epk_memory.empty()) { + if (entry.data_position < 0 || + static_cast(entry.data_position + entry.data_size) > m_epk_memory.size()) { + return false; + } + std::memcpy(raw_bytes.data(), m_epk_memory.data() + entry.data_position, entry.data_size); + } else if (m_epk_file.is_open()) { + m_epk_file.seekg(entry.data_position, std::ios::beg); + if (!m_epk_file.read(reinterpret_cast(raw_bytes.data()), entry.data_size)) { + return false; + } + } else { + return false; + } + + // CRC validation for security types + if (entry.compressed_type == static_cast(CompressionType::Security) || + entry.compressed_type == static_cast(CompressionType::Panama)) { + if (GetCRC32(raw_bytes) != entry.data_crc) { + return false; + } + } + + if (entry.compressed_type == static_cast(CompressionType::None)) { + out_data = std::move(raw_bytes); + return true; + } else if (entry.compressed_type == static_cast(CompressionType::Compress)) { + return LZO::instance().decompress_mcoz(raw_bytes, out_data, nullptr); + } else if (entry.compressed_type == static_cast(CompressionType::Security)) { + return LZO::instance().decompress_mcoz(raw_bytes, out_data, m_security_key); + } + + return false; +} + +bool EterPackArchive::create_archive( + const std::string& base_path, + const std::vector>>& files, + bool encrypt_index, + const uint32_t index_key[4], + CompressionType comp_type, + const uint32_t security_key[4]) { + + std::string epk_path = base_path + ".epk"; + std::string eix_path = base_path + ".eix"; + + std::ofstream epk_out(epk_path, std::ios::binary); + if (!epk_out.is_open()) return false; + + std::vector entries; + entries.reserve(files.size()); + + int32_t current_pos = 0; + for (int32_t i = 0; i < static_cast(files.size()); ++i) { + const auto& [name, content] = files[i]; + EterPackIndexEntry entry{}; + entry.id = i; + std::strncpy(entry.filename, name.c_str(), FILENAME_MAX_LEN); + entry.filename_crc = GetCRC32(name); + entry.real_data_size = static_cast(content.size()); + + std::vector payload; + if (comp_type == CompressionType::Compress) { + if (!LZO::instance().compress_mcoz(content, payload, nullptr)) return false; + entry.compressed_type = static_cast(CompressionType::Compress); + } else if (comp_type == CompressionType::Security) { + if (!LZO::instance().compress_mcoz(content, payload, security_key)) return false; + entry.compressed_type = static_cast(CompressionType::Security); + } else { + payload = content; + entry.compressed_type = static_cast(CompressionType::None); + } + + entry.data_size = static_cast(payload.size()); + entry.data_crc = GetCRC32(payload); + entry.data_position = current_pos; + + epk_out.write(reinterpret_cast(payload.data()), payload.size()); + current_pos += entry.data_size; + entries.push_back(entry); + } + epk_out.close(); + + // Construct index payload + size_t index_payload_size = ETERPACK_HEADER_SIZE + entries.size() * sizeof(EterPackIndexEntry); + std::vector plain_index(index_payload_size); + + uint32_t fourcc = FOURCC_EPKD; + uint32_t version = ETERPACK_VERSION; + int32_t count = static_cast(entries.size()); + + std::memcpy(plain_index.data(), &fourcc, 4); + std::memcpy(plain_index.data() + 4, &version, 4); + std::memcpy(plain_index.data() + 8, &count, 4); + std::memcpy(plain_index.data() + ETERPACK_HEADER_SIZE, entries.data(), entries.size() * sizeof(EterPackIndexEntry)); + + std::vector final_eix; + if (encrypt_index) { + if (!LZO::instance().compress_mcoz(plain_index, final_eix, index_key)) { + return false; + } + } else { + final_eix = std::move(plain_index); + } + + std::ofstream eix_out(eix_path, std::ios::binary); + if (!eix_out.is_open()) return false; + eix_out.write(reinterpret_cast(final_eix.data()), final_eix.size()); + eix_out.close(); + + return true; +} + +} // namespace eterpack diff --git a/eterpack/src/crc32.cpp b/eterpack/src/crc32.cpp new file mode 100644 index 0000000..8e40390 --- /dev/null +++ b/eterpack/src/crc32.cpp @@ -0,0 +1,85 @@ +#include "eterpack/crc32.h" + +namespace eterpack { + +namespace { +struct CrcTable { + uint32_t v[256]; + constexpr CrcTable() : v{} { + for (uint32_t n = 0; n < 256; ++n) { + uint32_t c = n; + for (int k = 0; k < 8; ++k) { + c = (c & 1) ? (0xEDB88320u ^ (c >> 1)) : (c >> 1); + } + v[n] = c; + } + } +}; + +static constexpr CrcTable s_crcTable{}; +static const uint32_t* const CRCTable = s_crcTable.v; +} // namespace + +#define DO1(buf, i) crc = CRCTable[(crc ^ static_cast(buf[i])) & 0xff] ^ (crc >> 8) +#define DO2(buf, i) DO1(buf, i); DO1(buf, i + 1) +#define DO4(buf, i) DO2(buf, i); DO2(buf, i + 2) +#define DO8(buf, i) DO4(buf, i); DO4(buf, i + 4) +#define DO16(buf, i) DO8(buf, i); DO8(buf, i + 8) + +uint32_t GetCRC32(const char* buf, size_t len) { + uint32_t crc = 0xffffffff; + + if (len >= 16) { + do { + DO16(buf, 0); + buf += 16; + len -= 16; + } while (len >= 16); + } + + if (len != 0) { + do { + DO1(buf, 0); + ++buf; + --len; + } while (len > 0); + } + + crc ^= 0xffffffff; + return crc; +} + +#ifndef UPPER +#define UPPER(c) (((c) >= 'a' && (c) <= 'z') ? ((c) + ('A' - 'a')) : (c)) +#endif + +#define DO1CI(buf, i) crc = CRCTable[(crc ^ static_cast(UPPER(buf[i]))) & 0xff] ^ (crc >> 8) +#define DO2CI(buf, i) DO1CI(buf, i); DO1CI(buf, i + 1) +#define DO4CI(buf, i) DO2CI(buf, i); DO2CI(buf, i + 2) +#define DO8CI(buf, i) DO4CI(buf, i); DO4CI(buf, i + 4) +#define DO16CI(buf, i) DO8CI(buf, i); DO8CI(buf, i + 8) + +uint32_t GetCaseCRC32(const char* buf, size_t len) { + uint32_t crc = 0xffffffff; + + if (16 <= len) { + do { + DO16CI(buf, 0); + buf += 16; + len -= 16; + } while (len >= 16); + } + + if (0 != len) { + do { + DO1CI(buf, 0); + ++buf; + --len; + } while (len > 0); + } + + crc ^= 0xffffffff; + return crc; +} + +} // namespace eterpack diff --git a/eterpack/src/lzo.cpp b/eterpack/src/lzo.cpp new file mode 100644 index 0000000..c6ae966 --- /dev/null +++ b/eterpack/src/lzo.cpp @@ -0,0 +1,149 @@ +#include "eterpack/lzo.h" +#include "eterpack/tea.h" +#include "minilzo/minilzo.h" +#include +#include +#include + +namespace eterpack { + +LZO& LZO::instance() { + static LZO s_instance; + return s_instance; +} + +LZO::LZO() { + if (lzo_init() != LZO_E_OK) { + // init failed + } + m_workmem = std::malloc(LZO1X_1_MEM_COMPRESS); +} + +LZO::~LZO() { + if (m_workmem) { + std::free(m_workmem); + m_workmem = nullptr; + } +} + +bool LZO::raw_decompress(const uint8_t* in, size_t in_len, uint8_t* out, size_t out_len) { + lzo_uint actual_out = out_len; + int r = lzo1x_decompress(in, static_cast(in_len), out, &actual_out, nullptr); + return (r == LZO_E_OK && actual_out == out_len); +} + +bool LZO::raw_compress(const uint8_t* in, size_t in_len, std::vector& out) { + lzo_uint max_out = in_len + in_len / 16 + 64 + 3; + out.resize(max_out); + lzo_uint actual_out = 0; + int r = lzo1x_1_compress(in, static_cast(in_len), out.data(), &actual_out, m_workmem); + if (r != LZO_E_OK) { + return false; + } + out.resize(actual_out); + return true; +} + +bool LZO::decompress_mcoz(std::span input, + std::vector& output, + const uint32_t key[4]) { + if (input.size() < sizeof(LZHeader)) { + return false; + } + + const auto* hdr = reinterpret_cast(input.data()); + if (hdr->fourcc != FOURCC_MCOZ) { + return false; + } + + if (hdr->real_size == 0) { + output.clear(); + return true; + } + + output.resize(hdr->real_size); + + if (hdr->encrypt_size > 0) { + if (!key) { + return false; + } + if (input.size() < sizeof(LZHeader) + hdr->encrypt_size) { + return false; + } + + std::vector decrypted(hdr->encrypt_size); + tea_decrypt(reinterpret_cast(decrypted.data()), + reinterpret_cast(input.data() + sizeof(LZHeader)), + key, static_cast(hdr->encrypt_size)); + + if (decrypted.size() < 4) { + return false; + } + uint32_t inner_fourcc = *reinterpret_cast(decrypted.data()); + if (inner_fourcc != FOURCC_MCOZ) { + return false; + } + + if (hdr->compressed_size > decrypted.size() - 4) { + return false; + } + + const uint8_t* comp_data = decrypted.data() + 4; + return raw_decompress(comp_data, hdr->compressed_size, output.data(), hdr->real_size); + } else { + if (input.size() < sizeof(LZHeader) + 4 + hdr->compressed_size) { + return false; + } + + uint32_t inner_fourcc = *reinterpret_cast(input.data() + sizeof(LZHeader)); + if (inner_fourcc != FOURCC_MCOZ) { + return false; + } + + const uint8_t* comp_data = input.data() + sizeof(LZHeader) + 4; + return raw_decompress(comp_data, hdr->compressed_size, output.data(), hdr->real_size); + } +} + +bool LZO::compress_mcoz(std::span input, + std::vector& output, + const uint32_t key[4]) { + std::vector comp; + if (!raw_compress(input.data(), input.size(), comp)) { + return false; + } + + LZHeader hdr; + hdr.fourcc = FOURCC_MCOZ; + hdr.compressed_size = static_cast(comp.size()); + hdr.real_size = static_cast(input.size()); + + if (key) { + size_t plain_payload = 4 + comp.size(); + size_t enc_size = (plain_payload % 8 != 0) ? (plain_payload + 8 - (plain_payload % 8)) : plain_payload; + hdr.encrypt_size = static_cast(enc_size); + + output.resize(sizeof(LZHeader) + enc_size); + std::memcpy(output.data(), &hdr, sizeof(LZHeader)); + + std::vector plain(enc_size, 0); + uint32_t fourcc = FOURCC_MCOZ; + std::memcpy(plain.data(), &fourcc, 4); + std::memcpy(plain.data() + 4, comp.data(), comp.size()); + + tea_encrypt(reinterpret_cast(output.data() + sizeof(LZHeader)), + reinterpret_cast(plain.data()), + key, static_cast(plain_payload)); + } else { + hdr.encrypt_size = 0; + output.resize(sizeof(LZHeader) + 4 + comp.size()); + std::memcpy(output.data(), &hdr, sizeof(LZHeader)); + uint32_t fourcc = FOURCC_MCOZ; + std::memcpy(output.data() + sizeof(LZHeader), &fourcc, 4); + std::memcpy(output.data() + sizeof(LZHeader) + 4, comp.data(), comp.size()); + } + + return true; +} + +} // namespace eterpack diff --git a/eterpack/src/minilzo/lzoconf.h b/eterpack/src/minilzo/lzoconf.h new file mode 100644 index 0000000..f9a8bdb --- /dev/null +++ b/eterpack/src/minilzo/lzoconf.h @@ -0,0 +1,453 @@ +/* lzoconf.h -- configuration of the LZO data compression library + + This file is part of the LZO real-time data compression library. + + Copyright (C) 1996-2017 Markus Franz Xaver Johannes Oberhumer + All Rights Reserved. + + The LZO library is free software; you can redistribute it and/or + modify it under the terms of the GNU General Public License as + published by the Free Software Foundation; either version 2 of + the License, or (at your option) any later version. + + The LZO library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with the LZO library; see the file COPYING. + If not, write to the Free Software Foundation, Inc., + 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. + + Markus F.X.J. Oberhumer + + http://www.oberhumer.com/opensource/lzo/ + */ + + +#ifndef __LZOCONF_H_INCLUDED +#define __LZOCONF_H_INCLUDED 1 + +#define LZO_VERSION 0x20a0 /* 2.10 */ +#define LZO_VERSION_STRING "2.10" +#define LZO_VERSION_DATE "Mar 01 2017" + +/* internal Autoconf configuration file - only used when building LZO */ +#if defined(LZO_HAVE_CONFIG_H) +# include +#endif +#include +#include + + +/*********************************************************************** +// LZO requires a conforming +************************************************************************/ + +#if !defined(CHAR_BIT) || (CHAR_BIT != 8) +# error "invalid CHAR_BIT" +#endif +#if !defined(UCHAR_MAX) || !defined(USHRT_MAX) || !defined(UINT_MAX) || !defined(ULONG_MAX) +# error "check your compiler installation" +#endif +#if (USHRT_MAX < 1) || (UINT_MAX < 1) || (ULONG_MAX < 1) +# error "your limits.h macros are broken" +#endif + +/* get OS and architecture defines */ +#ifndef __LZODEFS_H_INCLUDED +#include +#endif + + +#ifdef __cplusplus +extern "C" { +#endif + + +/*********************************************************************** +// some core defines +************************************************************************/ + +/* memory checkers */ +#if !defined(__LZO_CHECKER) +# if defined(__BOUNDS_CHECKING_ON) +# define __LZO_CHECKER 1 +# elif defined(__CHECKER__) +# define __LZO_CHECKER 1 +# elif defined(__INSURE__) +# define __LZO_CHECKER 1 +# elif defined(__PURIFY__) +# define __LZO_CHECKER 1 +# endif +#endif + + +/*********************************************************************** +// integral and pointer types +************************************************************************/ + +/* lzo_uint must match size_t */ +#if !defined(LZO_UINT_MAX) +# if (LZO_ABI_LLP64) +# if (LZO_OS_WIN64) + typedef unsigned __int64 lzo_uint; + typedef __int64 lzo_int; +# define LZO_TYPEOF_LZO_INT LZO_TYPEOF___INT64 +# else + typedef lzo_ullong_t lzo_uint; + typedef lzo_llong_t lzo_int; +# define LZO_TYPEOF_LZO_INT LZO_TYPEOF_LONG_LONG +# endif +# define LZO_SIZEOF_LZO_INT 8 +# define LZO_UINT_MAX 0xffffffffffffffffull +# define LZO_INT_MAX 9223372036854775807LL +# define LZO_INT_MIN (-1LL - LZO_INT_MAX) +# elif (LZO_ABI_IP32L64) /* MIPS R5900 */ + typedef unsigned int lzo_uint; + typedef int lzo_int; +# define LZO_SIZEOF_LZO_INT LZO_SIZEOF_INT +# define LZO_TYPEOF_LZO_INT LZO_TYPEOF_INT +# define LZO_UINT_MAX UINT_MAX +# define LZO_INT_MAX INT_MAX +# define LZO_INT_MIN INT_MIN +# elif (ULONG_MAX >= LZO_0xffffffffL) + typedef unsigned long lzo_uint; + typedef long lzo_int; +# define LZO_SIZEOF_LZO_INT LZO_SIZEOF_LONG +# define LZO_TYPEOF_LZO_INT LZO_TYPEOF_LONG +# define LZO_UINT_MAX ULONG_MAX +# define LZO_INT_MAX LONG_MAX +# define LZO_INT_MIN LONG_MIN +# else +# error "lzo_uint" +# endif +#endif + +/* The larger type of lzo_uint and lzo_uint32_t. */ +#if (LZO_SIZEOF_LZO_INT >= 4) +# define lzo_xint lzo_uint +#else +# define lzo_xint lzo_uint32_t +#endif + +typedef int lzo_bool; + +/* sanity checks */ +LZO_COMPILE_TIME_ASSERT_HEADER(sizeof(lzo_int) == LZO_SIZEOF_LZO_INT) +LZO_COMPILE_TIME_ASSERT_HEADER(sizeof(lzo_uint) == LZO_SIZEOF_LZO_INT) +LZO_COMPILE_TIME_ASSERT_HEADER(sizeof(lzo_xint) >= sizeof(lzo_uint)) +LZO_COMPILE_TIME_ASSERT_HEADER(sizeof(lzo_xint) >= sizeof(lzo_uint32_t)) + +#ifndef __LZO_MMODEL +#define __LZO_MMODEL /*empty*/ +#endif + +/* no typedef here because of const-pointer issues */ +#define lzo_bytep unsigned char __LZO_MMODEL * +#define lzo_charp char __LZO_MMODEL * +#define lzo_voidp void __LZO_MMODEL * +#define lzo_shortp short __LZO_MMODEL * +#define lzo_ushortp unsigned short __LZO_MMODEL * +#define lzo_intp lzo_int __LZO_MMODEL * +#define lzo_uintp lzo_uint __LZO_MMODEL * +#define lzo_xintp lzo_xint __LZO_MMODEL * +#define lzo_voidpp lzo_voidp __LZO_MMODEL * +#define lzo_bytepp lzo_bytep __LZO_MMODEL * + +#define lzo_int8_tp lzo_int8_t __LZO_MMODEL * +#define lzo_uint8_tp lzo_uint8_t __LZO_MMODEL * +#define lzo_int16_tp lzo_int16_t __LZO_MMODEL * +#define lzo_uint16_tp lzo_uint16_t __LZO_MMODEL * +#define lzo_int32_tp lzo_int32_t __LZO_MMODEL * +#define lzo_uint32_tp lzo_uint32_t __LZO_MMODEL * +#if defined(lzo_int64_t) +#define lzo_int64_tp lzo_int64_t __LZO_MMODEL * +#define lzo_uint64_tp lzo_uint64_t __LZO_MMODEL * +#endif + +/* Older LZO versions used to support ancient systems and memory models + * such as 16-bit MSDOS with __huge pointers or Cray PVP, but these + * obsolete configurations are not supported any longer. + */ +#if defined(__LZO_MMODEL_HUGE) +#error "__LZO_MMODEL_HUGE memory model is unsupported" +#endif +#if (LZO_MM_PVP) +#error "LZO_MM_PVP memory model is unsupported" +#endif +#if (LZO_SIZEOF_INT < 4) +#error "LZO_SIZEOF_INT < 4 is unsupported" +#endif +#if (__LZO_UINTPTR_T_IS_POINTER) +#error "__LZO_UINTPTR_T_IS_POINTER is unsupported" +#endif +LZO_COMPILE_TIME_ASSERT_HEADER(sizeof(int) >= 4) +LZO_COMPILE_TIME_ASSERT_HEADER(sizeof(lzo_uint) >= 4) +/* Strange configurations where sizeof(lzo_uint) != sizeof(size_t) should + * work but have not received much testing lately, so be strict here. + */ +LZO_COMPILE_TIME_ASSERT_HEADER(sizeof(lzo_uint) == sizeof(size_t)) +LZO_COMPILE_TIME_ASSERT_HEADER(sizeof(lzo_uint) == sizeof(ptrdiff_t)) +LZO_COMPILE_TIME_ASSERT_HEADER(sizeof(lzo_uint) == sizeof(lzo_uintptr_t)) +LZO_COMPILE_TIME_ASSERT_HEADER(sizeof(void *) == sizeof(lzo_uintptr_t)) +LZO_COMPILE_TIME_ASSERT_HEADER(sizeof(char *) == sizeof(lzo_uintptr_t)) +LZO_COMPILE_TIME_ASSERT_HEADER(sizeof(long *) == sizeof(lzo_uintptr_t)) +LZO_COMPILE_TIME_ASSERT_HEADER(sizeof(void *) == sizeof(lzo_voidp)) +LZO_COMPILE_TIME_ASSERT_HEADER(sizeof(char *) == sizeof(lzo_bytep)) + + +/*********************************************************************** +// function types +************************************************************************/ + +/* name mangling */ +#if !defined(__LZO_EXTERN_C) +# ifdef __cplusplus +# define __LZO_EXTERN_C extern "C" +# else +# define __LZO_EXTERN_C extern +# endif +#endif + +/* calling convention */ +#if !defined(__LZO_CDECL) +# define __LZO_CDECL __lzo_cdecl +#endif + +/* DLL export information */ +#if !defined(__LZO_EXPORT1) +# define __LZO_EXPORT1 /*empty*/ +#endif +#if !defined(__LZO_EXPORT2) +# define __LZO_EXPORT2 /*empty*/ +#endif + +/* __cdecl calling convention for public C and assembly functions */ +#if !defined(LZO_PUBLIC) +# define LZO_PUBLIC(r) __LZO_EXPORT1 r __LZO_EXPORT2 __LZO_CDECL +#endif +#if !defined(LZO_EXTERN) +# define LZO_EXTERN(r) __LZO_EXTERN_C LZO_PUBLIC(r) +#endif +#if !defined(LZO_PRIVATE) +# define LZO_PRIVATE(r) static r __LZO_CDECL +#endif + +/* function types */ +typedef int +(__LZO_CDECL *lzo_compress_t) ( const lzo_bytep src, lzo_uint src_len, + lzo_bytep dst, lzo_uintp dst_len, + lzo_voidp wrkmem ); + +typedef int +(__LZO_CDECL *lzo_decompress_t) ( const lzo_bytep src, lzo_uint src_len, + lzo_bytep dst, lzo_uintp dst_len, + lzo_voidp wrkmem ); + +typedef int +(__LZO_CDECL *lzo_optimize_t) ( lzo_bytep src, lzo_uint src_len, + lzo_bytep dst, lzo_uintp dst_len, + lzo_voidp wrkmem ); + +typedef int +(__LZO_CDECL *lzo_compress_dict_t)(const lzo_bytep src, lzo_uint src_len, + lzo_bytep dst, lzo_uintp dst_len, + lzo_voidp wrkmem, + const lzo_bytep dict, lzo_uint dict_len ); + +typedef int +(__LZO_CDECL *lzo_decompress_dict_t)(const lzo_bytep src, lzo_uint src_len, + lzo_bytep dst, lzo_uintp dst_len, + lzo_voidp wrkmem, + const lzo_bytep dict, lzo_uint dict_len ); + + +/* Callback interface. Currently only the progress indicator ("nprogress") + * is used, but this may change in a future release. */ + +struct lzo_callback_t; +typedef struct lzo_callback_t lzo_callback_t; +#define lzo_callback_p lzo_callback_t __LZO_MMODEL * + +/* malloc & free function types */ +typedef lzo_voidp (__LZO_CDECL *lzo_alloc_func_t) + (lzo_callback_p self, lzo_uint items, lzo_uint size); +typedef void (__LZO_CDECL *lzo_free_func_t) + (lzo_callback_p self, lzo_voidp ptr); + +/* a progress indicator callback function */ +typedef void (__LZO_CDECL *lzo_progress_func_t) + (lzo_callback_p, lzo_uint, lzo_uint, int); + +struct lzo_callback_t +{ + /* custom allocators (set to 0 to disable) */ + lzo_alloc_func_t nalloc; /* [not used right now] */ + lzo_free_func_t nfree; /* [not used right now] */ + + /* a progress indicator callback function (set to 0 to disable) */ + lzo_progress_func_t nprogress; + + /* INFO: the first parameter "self" of the nalloc/nfree/nprogress + * callbacks points back to this struct, so you are free to store + * some extra info in the following variables. */ + lzo_voidp user1; + lzo_xint user2; + lzo_xint user3; +}; + + +/*********************************************************************** +// error codes and prototypes +************************************************************************/ + +/* Error codes for the compression/decompression functions. Negative + * values are errors, positive values will be used for special but + * normal events. + */ +#define LZO_E_OK 0 +#define LZO_E_ERROR (-1) +#define LZO_E_OUT_OF_MEMORY (-2) /* [lzo_alloc_func_t failure] */ +#define LZO_E_NOT_COMPRESSIBLE (-3) /* [not used right now] */ +#define LZO_E_INPUT_OVERRUN (-4) +#define LZO_E_OUTPUT_OVERRUN (-5) +#define LZO_E_LOOKBEHIND_OVERRUN (-6) +#define LZO_E_EOF_NOT_FOUND (-7) +#define LZO_E_INPUT_NOT_CONSUMED (-8) +#define LZO_E_NOT_YET_IMPLEMENTED (-9) /* [not used right now] */ +#define LZO_E_INVALID_ARGUMENT (-10) +#define LZO_E_INVALID_ALIGNMENT (-11) /* pointer argument is not properly aligned */ +#define LZO_E_OUTPUT_NOT_CONSUMED (-12) +#define LZO_E_INTERNAL_ERROR (-99) + + +#ifndef lzo_sizeof_dict_t +# define lzo_sizeof_dict_t ((unsigned)sizeof(lzo_bytep)) +#endif + +/* lzo_init() should be the first function you call. + * Check the return code ! + * + * lzo_init() is a macro to allow checking that the library and the + * compiler's view of various types are consistent. + */ +#define lzo_init() __lzo_init_v2(LZO_VERSION,(int)sizeof(short),(int)sizeof(int),\ + (int)sizeof(long),(int)sizeof(lzo_uint32_t),(int)sizeof(lzo_uint),\ + (int)lzo_sizeof_dict_t,(int)sizeof(char *),(int)sizeof(lzo_voidp),\ + (int)sizeof(lzo_callback_t)) +LZO_EXTERN(int) __lzo_init_v2(unsigned,int,int,int,int,int,int,int,int,int); + +/* version functions (useful for shared libraries) */ +LZO_EXTERN(unsigned) lzo_version(void); +LZO_EXTERN(const char *) lzo_version_string(void); +LZO_EXTERN(const char *) lzo_version_date(void); +LZO_EXTERN(const lzo_charp) _lzo_version_string(void); +LZO_EXTERN(const lzo_charp) _lzo_version_date(void); + +/* string functions */ +LZO_EXTERN(int) + lzo_memcmp(const lzo_voidp a, const lzo_voidp b, lzo_uint len); +LZO_EXTERN(lzo_voidp) + lzo_memcpy(lzo_voidp dst, const lzo_voidp src, lzo_uint len); +LZO_EXTERN(lzo_voidp) + lzo_memmove(lzo_voidp dst, const lzo_voidp src, lzo_uint len); +LZO_EXTERN(lzo_voidp) + lzo_memset(lzo_voidp buf, int c, lzo_uint len); + +/* checksum functions */ +LZO_EXTERN(lzo_uint32_t) + lzo_adler32(lzo_uint32_t c, const lzo_bytep buf, lzo_uint len); +LZO_EXTERN(lzo_uint32_t) + lzo_crc32(lzo_uint32_t c, const lzo_bytep buf, lzo_uint len); +LZO_EXTERN(const lzo_uint32_tp) + lzo_get_crc32_table(void); + +/* misc. */ +LZO_EXTERN(int) _lzo_config_check(void); +typedef union { + lzo_voidp a00; lzo_bytep a01; lzo_uint a02; lzo_xint a03; lzo_uintptr_t a04; + void *a05; unsigned char *a06; unsigned long a07; size_t a08; ptrdiff_t a09; +#if defined(lzo_int64_t) + lzo_uint64_t a10; +#endif +} lzo_align_t; + +/* align a char pointer on a boundary that is a multiple of 'size' */ +LZO_EXTERN(unsigned) __lzo_align_gap(const lzo_voidp p, lzo_uint size); +#define LZO_PTR_ALIGN_UP(p,size) \ + ((p) + (lzo_uint) __lzo_align_gap((const lzo_voidp)(p),(lzo_uint)(size))) + + +/*********************************************************************** +// deprecated macros - only for backward compatibility +************************************************************************/ + +/* deprecated - use 'lzo_bytep' instead of 'lzo_byte *' */ +#define lzo_byte unsigned char +/* deprecated type names */ +#define lzo_int32 lzo_int32_t +#define lzo_uint32 lzo_uint32_t +#define lzo_int32p lzo_int32_t __LZO_MMODEL * +#define lzo_uint32p lzo_uint32_t __LZO_MMODEL * +#define LZO_INT32_MAX LZO_INT32_C(2147483647) +#define LZO_UINT32_MAX LZO_UINT32_C(4294967295) +#if defined(lzo_int64_t) +#define lzo_int64 lzo_int64_t +#define lzo_uint64 lzo_uint64_t +#define lzo_int64p lzo_int64_t __LZO_MMODEL * +#define lzo_uint64p lzo_uint64_t __LZO_MMODEL * +#define LZO_INT64_MAX LZO_INT64_C(9223372036854775807) +#define LZO_UINT64_MAX LZO_UINT64_C(18446744073709551615) +#endif +/* deprecated types */ +typedef union { lzo_bytep a; lzo_uint b; } __lzo_pu_u; +typedef union { lzo_bytep a; lzo_uint32_t b; } __lzo_pu32_u; +/* deprecated defines */ +#if !defined(LZO_SIZEOF_LZO_UINT) +# define LZO_SIZEOF_LZO_UINT LZO_SIZEOF_LZO_INT +#endif + +#if defined(LZO_CFG_COMPAT) + +#define __LZOCONF_H 1 + +#if defined(LZO_ARCH_I086) +# define __LZO_i386 1 +#elif defined(LZO_ARCH_I386) +# define __LZO_i386 1 +#endif + +#if defined(LZO_OS_DOS16) +# define __LZO_DOS 1 +# define __LZO_DOS16 1 +#elif defined(LZO_OS_DOS32) +# define __LZO_DOS 1 +#elif defined(LZO_OS_WIN16) +# define __LZO_WIN 1 +# define __LZO_WIN16 1 +#elif defined(LZO_OS_WIN32) +# define __LZO_WIN 1 +#endif + +#define __LZO_CMODEL /*empty*/ +#define __LZO_DMODEL /*empty*/ +#define __LZO_ENTRY __LZO_CDECL +#define LZO_EXTERN_CDECL LZO_EXTERN +#define LZO_ALIGN LZO_PTR_ALIGN_UP + +#define lzo_compress_asm_t lzo_compress_t +#define lzo_decompress_asm_t lzo_decompress_t + +#endif /* LZO_CFG_COMPAT */ + + +#ifdef __cplusplus +} /* extern "C" */ +#endif + +#endif /* already included */ + + +/* vim:set ts=4 sw=4 et: */ diff --git a/eterpack/src/minilzo/lzodefs.h b/eterpack/src/minilzo/lzodefs.h new file mode 100644 index 0000000..c3e2bcf --- /dev/null +++ b/eterpack/src/minilzo/lzodefs.h @@ -0,0 +1,3268 @@ +/* lzodefs.h -- architecture, OS and compiler specific defines + + This file is part of the LZO real-time data compression library. + + Copyright (C) 1996-2017 Markus Franz Xaver Johannes Oberhumer + All Rights Reserved. + + The LZO library is free software; you can redistribute it and/or + modify it under the terms of the GNU General Public License as + published by the Free Software Foundation; either version 2 of + the License, or (at your option) any later version. + + The LZO library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with the LZO library; see the file COPYING. + If not, write to the Free Software Foundation, Inc., + 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. + + Markus F.X.J. Oberhumer + + http://www.oberhumer.com/opensource/lzo/ + */ + + +#ifndef __LZODEFS_H_INCLUDED +#define __LZODEFS_H_INCLUDED 1 + +#if defined(__CYGWIN32__) && !defined(__CYGWIN__) +# define __CYGWIN__ __CYGWIN32__ +#endif +#if 1 && defined(__INTERIX) && defined(__GNUC__) && !defined(_ALL_SOURCE) +# define _ALL_SOURCE 1 +#endif +#if defined(__mips__) && defined(__R5900__) +# if !defined(__LONG_MAX__) +# define __LONG_MAX__ 9223372036854775807L +# endif +#endif +#if 0 +#elif !defined(__LZO_LANG_OVERRIDE) +#if (defined(__clang__) || defined(__GNUC__)) && defined(__ASSEMBLER__) +# if (__ASSEMBLER__+0) <= 0 +# error "__ASSEMBLER__" +# else +# define LZO_LANG_ASSEMBLER 1 +# endif +#elif defined(__cplusplus) +# if (__cplusplus+0) <= 0 +# error "__cplusplus" +# elif (__cplusplus < 199711L) +# define LZO_LANG_CXX 1 +# elif defined(_MSC_VER) && defined(_MSVC_LANG) && (_MSVC_LANG+0 >= 201402L) && 1 +# define LZO_LANG_CXX _MSVC_LANG +# else +# define LZO_LANG_CXX __cplusplus +# endif +# define LZO_LANG_CPLUSPLUS LZO_LANG_CXX +#else +# if defined(__STDC_VERSION__) && (__STDC_VERSION__+0 >= 199409L) +# define LZO_LANG_C __STDC_VERSION__ +# else +# define LZO_LANG_C 1 +# endif +#endif +#endif +#if !defined(LZO_CFG_NO_DISABLE_WUNDEF) +#if defined(__ARMCC_VERSION) +# pragma diag_suppress 193 +#elif defined(__clang__) && defined(__clang_minor__) +# pragma clang diagnostic ignored "-Wundef" +#elif defined(__INTEL_COMPILER) +# pragma warning(disable: 193) +#elif defined(__KEIL__) && defined(__C166__) +# pragma warning disable = 322 +#elif defined(__GNUC__) && defined(__GNUC_MINOR__) && !defined(__PATHSCALE__) +# if ((__GNUC__-0) >= 5 || ((__GNUC__-0) == 4 && (__GNUC_MINOR__-0) >= 2)) +# pragma GCC diagnostic ignored "-Wundef" +# endif +#elif defined(_MSC_VER) && !defined(__clang__) && !defined(__INTEL_COMPILER) && !defined(__MWERKS__) +# if ((_MSC_VER-0) >= 1300) +# pragma warning(disable: 4668) +# endif +#endif +#endif +#if 0 && defined(__POCC__) && defined(_WIN32) +# if (__POCC__ >= 400) +# pragma warn(disable: 2216) +# endif +#endif +#if 0 && defined(__WATCOMC__) +# if (__WATCOMC__ >= 1050) && (__WATCOMC__ < 1060) +# pragma warning 203 9 +# endif +#endif +#if defined(__BORLANDC__) && defined(__MSDOS__) && !defined(__FLAT__) +# pragma option -h +#endif +#if !(LZO_CFG_NO_DISABLE_WCRTNONSTDC) +#ifndef _CRT_NONSTDC_NO_DEPRECATE +#define _CRT_NONSTDC_NO_DEPRECATE 1 +#endif +#ifndef _CRT_NONSTDC_NO_WARNINGS +#define _CRT_NONSTDC_NO_WARNINGS 1 +#endif +#ifndef _CRT_SECURE_NO_DEPRECATE +#define _CRT_SECURE_NO_DEPRECATE 1 +#endif +#ifndef _CRT_SECURE_NO_WARNINGS +#define _CRT_SECURE_NO_WARNINGS 1 +#endif +#endif +#if 0 +#define LZO_0xffffUL 0xfffful +#define LZO_0xffffffffUL 0xfffffffful +#else +#define LZO_0xffffUL 65535ul +#define LZO_0xffffffffUL 4294967295ul +#endif +#define LZO_0xffffL LZO_0xffffUL +#define LZO_0xffffffffL LZO_0xffffffffUL +#if (LZO_0xffffL == LZO_0xffffffffL) +# error "your preprocessor is broken 1" +#endif +#if (16ul * 16384ul != 262144ul) +# error "your preprocessor is broken 2" +#endif +#if 0 +#if (32767 >= 4294967295ul) +# error "your preprocessor is broken 3" +#endif +#if (65535u >= 4294967295ul) +# error "your preprocessor is broken 4" +#endif +#endif +#if defined(__COUNTER__) +# ifndef LZO_CFG_USE_COUNTER +# define LZO_CFG_USE_COUNTER 1 +# endif +#else +# undef LZO_CFG_USE_COUNTER +#endif +#if (UINT_MAX == LZO_0xffffL) +#if defined(__ZTC__) && defined(__I86__) && !defined(__OS2__) +# if !defined(MSDOS) +# define MSDOS 1 +# endif +# if !defined(_MSDOS) +# define _MSDOS 1 +# endif +#elif 0 && defined(__VERSION) && defined(MB_LEN_MAX) +# if (__VERSION == 520) && (MB_LEN_MAX == 1) +# if !defined(__AZTEC_C__) +# define __AZTEC_C__ __VERSION +# endif +# if !defined(__DOS__) +# define __DOS__ 1 +# endif +# endif +#endif +#endif +#if (UINT_MAX == LZO_0xffffL) +#if defined(_MSC_VER) && defined(M_I86HM) +# define ptrdiff_t long +# define _PTRDIFF_T_DEFINED 1 +#endif +#endif +#if (UINT_MAX == LZO_0xffffL) +# undef __LZO_RENAME_A +# undef __LZO_RENAME_B +# if defined(__AZTEC_C__) && defined(__DOS__) +# define __LZO_RENAME_A 1 +# elif defined(_MSC_VER) && defined(MSDOS) +# if (_MSC_VER < 600) +# define __LZO_RENAME_A 1 +# elif (_MSC_VER < 700) +# define __LZO_RENAME_B 1 +# endif +# elif defined(__TSC__) && defined(__OS2__) +# define __LZO_RENAME_A 1 +# elif defined(__MSDOS__) && defined(__TURBOC__) && (__TURBOC__ < 0x0410) +# define __LZO_RENAME_A 1 +# elif defined(__PACIFIC__) && defined(DOS) +# if !defined(__far) +# define __far far +# endif +# if !defined(__near) +# define __near near +# endif +# endif +# if defined(__LZO_RENAME_A) +# if !defined(__cdecl) +# define __cdecl cdecl +# endif +# if !defined(__far) +# define __far far +# endif +# if !defined(__huge) +# define __huge huge +# endif +# if !defined(__near) +# define __near near +# endif +# if !defined(__pascal) +# define __pascal pascal +# endif +# if !defined(__huge) +# define __huge huge +# endif +# elif defined(__LZO_RENAME_B) +# if !defined(__cdecl) +# define __cdecl _cdecl +# endif +# if !defined(__far) +# define __far _far +# endif +# if !defined(__huge) +# define __huge _huge +# endif +# if !defined(__near) +# define __near _near +# endif +# if !defined(__pascal) +# define __pascal _pascal +# endif +# elif (defined(__PUREC__) || defined(__TURBOC__)) && defined(__TOS__) +# if !defined(__cdecl) +# define __cdecl cdecl +# endif +# if !defined(__pascal) +# define __pascal pascal +# endif +# endif +# undef __LZO_RENAME_A +# undef __LZO_RENAME_B +#endif +#if (UINT_MAX == LZO_0xffffL) +#if defined(__AZTEC_C__) && defined(__DOS__) +# define LZO_BROKEN_CDECL_ALT_SYNTAX 1 +#elif defined(_MSC_VER) && defined(MSDOS) +# if (_MSC_VER < 600) +# define LZO_BROKEN_INTEGRAL_CONSTANTS 1 +# endif +# if (_MSC_VER < 700) +# define LZO_BROKEN_INTEGRAL_PROMOTION 1 +# define LZO_BROKEN_SIZEOF 1 +# endif +#elif defined(__PACIFIC__) && defined(DOS) +# define LZO_BROKEN_INTEGRAL_CONSTANTS 1 +#elif defined(__TURBOC__) && defined(__MSDOS__) +# if (__TURBOC__ < 0x0150) +# define LZO_BROKEN_CDECL_ALT_SYNTAX 1 +# define LZO_BROKEN_INTEGRAL_CONSTANTS 1 +# define LZO_BROKEN_INTEGRAL_PROMOTION 1 +# endif +# if (__TURBOC__ < 0x0200) +# define LZO_BROKEN_SIZEOF 1 +# endif +# if (__TURBOC__ < 0x0400) && defined(__cplusplus) +# define LZO_BROKEN_CDECL_ALT_SYNTAX 1 +# endif +#elif (defined(__PUREC__) || defined(__TURBOC__)) && defined(__TOS__) +# define LZO_BROKEN_CDECL_ALT_SYNTAX 1 +# define LZO_BROKEN_SIZEOF 1 +#endif +#endif +#if defined(__WATCOMC__) && (__WATCOMC__ < 900) +# define LZO_BROKEN_INTEGRAL_CONSTANTS 1 +#endif +#if defined(_CRAY) && defined(_CRAY1) +# define LZO_BROKEN_SIGNED_RIGHT_SHIFT 1 +#endif +#define LZO_PP_STRINGIZE(x) #x +#define LZO_PP_MACRO_EXPAND(x) LZO_PP_STRINGIZE(x) +#define LZO_PP_CONCAT0() /*empty*/ +#define LZO_PP_CONCAT1(a) a +#define LZO_PP_CONCAT2(a,b) a ## b +#define LZO_PP_CONCAT3(a,b,c) a ## b ## c +#define LZO_PP_CONCAT4(a,b,c,d) a ## b ## c ## d +#define LZO_PP_CONCAT5(a,b,c,d,e) a ## b ## c ## d ## e +#define LZO_PP_CONCAT6(a,b,c,d,e,f) a ## b ## c ## d ## e ## f +#define LZO_PP_CONCAT7(a,b,c,d,e,f,g) a ## b ## c ## d ## e ## f ## g +#define LZO_PP_ECONCAT0() LZO_PP_CONCAT0() +#define LZO_PP_ECONCAT1(a) LZO_PP_CONCAT1(a) +#define LZO_PP_ECONCAT2(a,b) LZO_PP_CONCAT2(a,b) +#define LZO_PP_ECONCAT3(a,b,c) LZO_PP_CONCAT3(a,b,c) +#define LZO_PP_ECONCAT4(a,b,c,d) LZO_PP_CONCAT4(a,b,c,d) +#define LZO_PP_ECONCAT5(a,b,c,d,e) LZO_PP_CONCAT5(a,b,c,d,e) +#define LZO_PP_ECONCAT6(a,b,c,d,e,f) LZO_PP_CONCAT6(a,b,c,d,e,f) +#define LZO_PP_ECONCAT7(a,b,c,d,e,f,g) LZO_PP_CONCAT7(a,b,c,d,e,f,g) +#define LZO_PP_EMPTY /*empty*/ +#define LZO_PP_EMPTY0() /*empty*/ +#define LZO_PP_EMPTY1(a) /*empty*/ +#define LZO_PP_EMPTY2(a,b) /*empty*/ +#define LZO_PP_EMPTY3(a,b,c) /*empty*/ +#define LZO_PP_EMPTY4(a,b,c,d) /*empty*/ +#define LZO_PP_EMPTY5(a,b,c,d,e) /*empty*/ +#define LZO_PP_EMPTY6(a,b,c,d,e,f) /*empty*/ +#define LZO_PP_EMPTY7(a,b,c,d,e,f,g) /*empty*/ +#if 1 +#define LZO_CPP_STRINGIZE(x) #x +#define LZO_CPP_MACRO_EXPAND(x) LZO_CPP_STRINGIZE(x) +#define LZO_CPP_CONCAT2(a,b) a ## b +#define LZO_CPP_CONCAT3(a,b,c) a ## b ## c +#define LZO_CPP_CONCAT4(a,b,c,d) a ## b ## c ## d +#define LZO_CPP_CONCAT5(a,b,c,d,e) a ## b ## c ## d ## e +#define LZO_CPP_CONCAT6(a,b,c,d,e,f) a ## b ## c ## d ## e ## f +#define LZO_CPP_CONCAT7(a,b,c,d,e,f,g) a ## b ## c ## d ## e ## f ## g +#define LZO_CPP_ECONCAT2(a,b) LZO_CPP_CONCAT2(a,b) +#define LZO_CPP_ECONCAT3(a,b,c) LZO_CPP_CONCAT3(a,b,c) +#define LZO_CPP_ECONCAT4(a,b,c,d) LZO_CPP_CONCAT4(a,b,c,d) +#define LZO_CPP_ECONCAT5(a,b,c,d,e) LZO_CPP_CONCAT5(a,b,c,d,e) +#define LZO_CPP_ECONCAT6(a,b,c,d,e,f) LZO_CPP_CONCAT6(a,b,c,d,e,f) +#define LZO_CPP_ECONCAT7(a,b,c,d,e,f,g) LZO_CPP_CONCAT7(a,b,c,d,e,f,g) +#endif +#define __LZO_MASK_GEN(o,b) (((((o) << ((b)-((b)!=0))) - (o)) << 1) + (o)*((b)!=0)) +#if 1 && defined(__cplusplus) +# if !defined(__STDC_CONSTANT_MACROS) +# define __STDC_CONSTANT_MACROS 1 +# endif +# if !defined(__STDC_LIMIT_MACROS) +# define __STDC_LIMIT_MACROS 1 +# endif +#endif +#if defined(__cplusplus) +# define LZO_EXTERN_C extern "C" +# define LZO_EXTERN_C_BEGIN extern "C" { +# define LZO_EXTERN_C_END } +#else +# define LZO_EXTERN_C extern +# define LZO_EXTERN_C_BEGIN /*empty*/ +# define LZO_EXTERN_C_END /*empty*/ +#endif +#if !defined(__LZO_OS_OVERRIDE) +#if (LZO_OS_FREESTANDING) +# define LZO_INFO_OS "freestanding" +#elif (LZO_OS_EMBEDDED) +# define LZO_INFO_OS "embedded" +#elif 1 && defined(__IAR_SYSTEMS_ICC__) +# define LZO_OS_EMBEDDED 1 +# define LZO_INFO_OS "embedded" +#elif defined(__CYGWIN__) && defined(__GNUC__) +# define LZO_OS_CYGWIN 1 +# define LZO_INFO_OS "cygwin" +#elif defined(__EMX__) && defined(__GNUC__) +# define LZO_OS_EMX 1 +# define LZO_INFO_OS "emx" +#elif defined(__BEOS__) +# define LZO_OS_BEOS 1 +# define LZO_INFO_OS "beos" +#elif defined(__Lynx__) +# define LZO_OS_LYNXOS 1 +# define LZO_INFO_OS "lynxos" +#elif defined(__OS400__) +# define LZO_OS_OS400 1 +# define LZO_INFO_OS "os400" +#elif defined(__QNX__) +# define LZO_OS_QNX 1 +# define LZO_INFO_OS "qnx" +#elif defined(__BORLANDC__) && defined(__DPMI32__) && (__BORLANDC__ >= 0x0460) +# define LZO_OS_DOS32 1 +# define LZO_INFO_OS "dos32" +#elif defined(__BORLANDC__) && defined(__DPMI16__) +# define LZO_OS_DOS16 1 +# define LZO_INFO_OS "dos16" +#elif defined(__ZTC__) && defined(DOS386) +# define LZO_OS_DOS32 1 +# define LZO_INFO_OS "dos32" +#elif defined(__OS2__) || defined(__OS2V2__) +# if (UINT_MAX == LZO_0xffffL) +# define LZO_OS_OS216 1 +# define LZO_INFO_OS "os216" +# elif (UINT_MAX == LZO_0xffffffffL) +# define LZO_OS_OS2 1 +# define LZO_INFO_OS "os2" +# else +# error "check your limits.h header" +# endif +#elif defined(__WIN64__) || defined(_WIN64) || defined(WIN64) +# define LZO_OS_WIN64 1 +# define LZO_INFO_OS "win64" +#elif defined(__WIN32__) || defined(_WIN32) || defined(WIN32) || defined(__WINDOWS_386__) +# define LZO_OS_WIN32 1 +# define LZO_INFO_OS "win32" +#elif defined(__MWERKS__) && defined(__INTEL__) +# define LZO_OS_WIN32 1 +# define LZO_INFO_OS "win32" +#elif defined(__WINDOWS__) || defined(_WINDOWS) || defined(_Windows) +# if (UINT_MAX == LZO_0xffffL) +# define LZO_OS_WIN16 1 +# define LZO_INFO_OS "win16" +# elif (UINT_MAX == LZO_0xffffffffL) +# define LZO_OS_WIN32 1 +# define LZO_INFO_OS "win32" +# else +# error "check your limits.h header" +# endif +#elif defined(__DOS__) || defined(__MSDOS__) || defined(_MSDOS) || defined(MSDOS) || (defined(__PACIFIC__) && defined(DOS)) +# if (UINT_MAX == LZO_0xffffL) +# define LZO_OS_DOS16 1 +# define LZO_INFO_OS "dos16" +# elif (UINT_MAX == LZO_0xffffffffL) +# define LZO_OS_DOS32 1 +# define LZO_INFO_OS "dos32" +# else +# error "check your limits.h header" +# endif +#elif defined(__WATCOMC__) +# if defined(__NT__) && (UINT_MAX == LZO_0xffffL) +# define LZO_OS_DOS16 1 +# define LZO_INFO_OS "dos16" +# elif defined(__NT__) && (__WATCOMC__ < 1100) +# define LZO_OS_WIN32 1 +# define LZO_INFO_OS "win32" +# elif defined(__linux__) || defined(__LINUX__) +# define LZO_OS_POSIX 1 +# define LZO_INFO_OS "posix" +# else +# error "please specify a target using the -bt compiler option" +# endif +#elif defined(__palmos__) +# define LZO_OS_PALMOS 1 +# define LZO_INFO_OS "palmos" +#elif defined(__TOS__) || defined(__atarist__) +# define LZO_OS_TOS 1 +# define LZO_INFO_OS "tos" +#elif defined(macintosh) && !defined(__arm__) && !defined(__i386__) && !defined(__ppc__) && !defined(__x64_64__) +# define LZO_OS_MACCLASSIC 1 +# define LZO_INFO_OS "macclassic" +#elif defined(__VMS) +# define LZO_OS_VMS 1 +# define LZO_INFO_OS "vms" +#elif (defined(__mips__) && defined(__R5900__)) || defined(__MIPS_PSX2__) +# define LZO_OS_CONSOLE 1 +# define LZO_OS_CONSOLE_PS2 1 +# define LZO_INFO_OS "console" +# define LZO_INFO_OS_CONSOLE "ps2" +#elif defined(__mips__) && defined(__psp__) +# define LZO_OS_CONSOLE 1 +# define LZO_OS_CONSOLE_PSP 1 +# define LZO_INFO_OS "console" +# define LZO_INFO_OS_CONSOLE "psp" +#else +# define LZO_OS_POSIX 1 +# define LZO_INFO_OS "posix" +#endif +#if (LZO_OS_POSIX) +# if defined(_AIX) || defined(__AIX__) || defined(__aix__) +# define LZO_OS_POSIX_AIX 1 +# define LZO_INFO_OS_POSIX "aix" +# elif defined(__FreeBSD__) +# define LZO_OS_POSIX_FREEBSD 1 +# define LZO_INFO_OS_POSIX "freebsd" +# elif defined(__hpux__) || defined(__hpux) +# define LZO_OS_POSIX_HPUX 1 +# define LZO_INFO_OS_POSIX "hpux" +# elif defined(__INTERIX) +# define LZO_OS_POSIX_INTERIX 1 +# define LZO_INFO_OS_POSIX "interix" +# elif defined(__IRIX__) || defined(__irix__) +# define LZO_OS_POSIX_IRIX 1 +# define LZO_INFO_OS_POSIX "irix" +# elif defined(__linux__) || defined(__linux) || defined(__LINUX__) +# define LZO_OS_POSIX_LINUX 1 +# define LZO_INFO_OS_POSIX "linux" +# elif defined(__APPLE__) && defined(__MACH__) +# if ((__ENVIRONMENT_IPHONE_OS_VERSION_MIN_REQUIRED__-0) >= 20000) +# define LZO_OS_POSIX_DARWIN 1040 +# define LZO_INFO_OS_POSIX "darwin_iphone" +# elif ((__ENVIRONMENT_MAC_OS_X_VERSION_MIN_REQUIRED__-0) >= 1040) +# define LZO_OS_POSIX_DARWIN __ENVIRONMENT_MAC_OS_X_VERSION_MIN_REQUIRED__ +# define LZO_INFO_OS_POSIX "darwin" +# else +# define LZO_OS_POSIX_DARWIN 1 +# define LZO_INFO_OS_POSIX "darwin" +# endif +# define LZO_OS_POSIX_MACOSX LZO_OS_POSIX_DARWIN +# elif defined(__minix__) || defined(__minix) +# define LZO_OS_POSIX_MINIX 1 +# define LZO_INFO_OS_POSIX "minix" +# elif defined(__NetBSD__) +# define LZO_OS_POSIX_NETBSD 1 +# define LZO_INFO_OS_POSIX "netbsd" +# elif defined(__OpenBSD__) +# define LZO_OS_POSIX_OPENBSD 1 +# define LZO_INFO_OS_POSIX "openbsd" +# elif defined(__osf__) +# define LZO_OS_POSIX_OSF 1 +# define LZO_INFO_OS_POSIX "osf" +# elif defined(__solaris__) || defined(__sun) +# if defined(__SVR4) || defined(__svr4__) +# define LZO_OS_POSIX_SOLARIS 1 +# define LZO_INFO_OS_POSIX "solaris" +# else +# define LZO_OS_POSIX_SUNOS 1 +# define LZO_INFO_OS_POSIX "sunos" +# endif +# elif defined(__ultrix__) || defined(__ultrix) +# define LZO_OS_POSIX_ULTRIX 1 +# define LZO_INFO_OS_POSIX "ultrix" +# elif defined(_UNICOS) +# define LZO_OS_POSIX_UNICOS 1 +# define LZO_INFO_OS_POSIX "unicos" +# else +# define LZO_OS_POSIX_UNKNOWN 1 +# define LZO_INFO_OS_POSIX "unknown" +# endif +#endif +#endif +#if (LZO_OS_DOS16 || LZO_OS_OS216 || LZO_OS_WIN16) +# if (UINT_MAX != LZO_0xffffL) +# error "unexpected configuration - check your compiler defines" +# endif +# if (ULONG_MAX != LZO_0xffffffffL) +# error "unexpected configuration - check your compiler defines" +# endif +#endif +#if (LZO_OS_DOS32 || LZO_OS_OS2 || LZO_OS_WIN32 || LZO_OS_WIN64) +# if (UINT_MAX != LZO_0xffffffffL) +# error "unexpected configuration - check your compiler defines" +# endif +# if (ULONG_MAX != LZO_0xffffffffL) +# error "unexpected configuration - check your compiler defines" +# endif +#endif +#if defined(CIL) && defined(_GNUCC) && defined(__GNUC__) +# define LZO_CC_CILLY 1 +# define LZO_INFO_CC "Cilly" +# if defined(__CILLY__) +# define LZO_INFO_CCVER LZO_PP_MACRO_EXPAND(__CILLY__) +# else +# define LZO_INFO_CCVER "unknown" +# endif +#elif 0 && defined(SDCC) && defined(__VERSION__) && !defined(__GNUC__) +# define LZO_CC_SDCC 1 +# define LZO_INFO_CC "sdcc" +# define LZO_INFO_CCVER LZO_PP_MACRO_EXPAND(SDCC) +#elif defined(__PATHSCALE__) && defined(__PATHCC_PATCHLEVEL__) +# define LZO_CC_PATHSCALE (__PATHCC__ * 0x10000L + (__PATHCC_MINOR__-0) * 0x100 + (__PATHCC_PATCHLEVEL__-0)) +# define LZO_INFO_CC "Pathscale C" +# define LZO_INFO_CCVER __PATHSCALE__ +# if defined(__GNUC__) && defined(__GNUC_MINOR__) && defined(__VERSION__) +# define LZO_CC_PATHSCALE_GNUC (__GNUC__ * 0x10000L + (__GNUC_MINOR__-0) * 0x100 + (__GNUC_PATCHLEVEL__-0)) +# endif +#elif defined(__INTEL_COMPILER) && ((__INTEL_COMPILER-0) > 0) +# define LZO_CC_INTELC __INTEL_COMPILER +# define LZO_INFO_CC "Intel C" +# define LZO_INFO_CCVER LZO_PP_MACRO_EXPAND(__INTEL_COMPILER) +# if defined(_MSC_VER) && ((_MSC_VER-0) > 0) +# define LZO_CC_INTELC_MSC _MSC_VER +# elif defined(__GNUC__) && defined(__GNUC_MINOR__) && defined(__VERSION__) +# define LZO_CC_INTELC_GNUC (__GNUC__ * 0x10000L + (__GNUC_MINOR__-0) * 0x100 + (__GNUC_PATCHLEVEL__-0)) +# endif +#elif defined(__POCC__) && defined(_WIN32) +# define LZO_CC_PELLESC 1 +# define LZO_INFO_CC "Pelles C" +# define LZO_INFO_CCVER LZO_PP_MACRO_EXPAND(__POCC__) +#elif defined(__ARMCC_VERSION) && defined(__GNUC__) && defined(__GNUC_MINOR__) && defined(__VERSION__) +# if defined(__GNUC_PATCHLEVEL__) +# define LZO_CC_ARMCC_GNUC (__GNUC__ * 0x10000L + (__GNUC_MINOR__-0) * 0x100 + (__GNUC_PATCHLEVEL__-0)) +# else +# define LZO_CC_ARMCC_GNUC (__GNUC__ * 0x10000L + (__GNUC_MINOR__-0) * 0x100) +# endif +# define LZO_CC_ARMCC __ARMCC_VERSION +# define LZO_INFO_CC "ARM C Compiler" +# define LZO_INFO_CCVER __VERSION__ +#elif defined(__clang__) && defined(__c2__) && defined(__c2_version__) && defined(_MSC_VER) +# define LZO_CC_CLANG (__clang_major__ * 0x10000L + (__clang_minor__-0) * 0x100 + (__clang_patchlevel__-0)) +# define LZO_CC_CLANG_C2 _MSC_VER +# define LZO_CC_CLANG_VENDOR_MICROSOFT 1 +# define LZO_INFO_CC "clang/c2" +# define LZO_INFO_CCVER LZO_PP_MACRO_EXPAND(__c2_version__) +#elif defined(__clang__) && defined(__llvm__) && defined(__VERSION__) +# if defined(__clang_major__) && defined(__clang_minor__) && defined(__clang_patchlevel__) +# define LZO_CC_CLANG (__clang_major__ * 0x10000L + (__clang_minor__-0) * 0x100 + (__clang_patchlevel__-0)) +# else +# define LZO_CC_CLANG 0x010000L +# endif +# if defined(_MSC_VER) && ((_MSC_VER-0) > 0) +# define LZO_CC_CLANG_MSC _MSC_VER +# elif defined(__GNUC__) && defined(__GNUC_MINOR__) && defined(__VERSION__) +# define LZO_CC_CLANG_GNUC (__GNUC__ * 0x10000L + (__GNUC_MINOR__-0) * 0x100 + (__GNUC_PATCHLEVEL__-0)) +# endif +# if defined(__APPLE_CC__) +# define LZO_CC_CLANG_VENDOR_APPLE 1 +# define LZO_INFO_CC "clang/apple" +# else +# define LZO_CC_CLANG_VENDOR_LLVM 1 +# define LZO_INFO_CC "clang" +# endif +# if defined(__clang_version__) +# define LZO_INFO_CCVER __clang_version__ +# else +# define LZO_INFO_CCVER __VERSION__ +# endif +#elif defined(__llvm__) && defined(__GNUC__) && defined(__GNUC_MINOR__) && defined(__VERSION__) +# if defined(__GNUC_PATCHLEVEL__) +# define LZO_CC_LLVM_GNUC (__GNUC__ * 0x10000L + (__GNUC_MINOR__-0) * 0x100 + (__GNUC_PATCHLEVEL__-0)) +# else +# define LZO_CC_LLVM_GNUC (__GNUC__ * 0x10000L + (__GNUC_MINOR__-0) * 0x100) +# endif +# define LZO_CC_LLVM LZO_CC_LLVM_GNUC +# define LZO_INFO_CC "llvm-gcc" +# define LZO_INFO_CCVER __VERSION__ +#elif defined(__ACK__) && defined(_ACK) +# define LZO_CC_ACK 1 +# define LZO_INFO_CC "Amsterdam Compiler Kit C" +# define LZO_INFO_CCVER "unknown" +#elif defined(__ARMCC_VERSION) && !defined(__GNUC__) +# define LZO_CC_ARMCC __ARMCC_VERSION +# define LZO_CC_ARMCC_ARMCC __ARMCC_VERSION +# define LZO_INFO_CC "ARM C Compiler" +# define LZO_INFO_CCVER LZO_PP_MACRO_EXPAND(__ARMCC_VERSION) +#elif defined(__AZTEC_C__) +# define LZO_CC_AZTECC 1 +# define LZO_INFO_CC "Aztec C" +# define LZO_INFO_CCVER LZO_PP_MACRO_EXPAND(__AZTEC_C__) +#elif defined(__CODEGEARC__) +# define LZO_CC_CODEGEARC 1 +# define LZO_INFO_CC "CodeGear C" +# define LZO_INFO_CCVER LZO_PP_MACRO_EXPAND(__CODEGEARC__) +#elif defined(__BORLANDC__) +# define LZO_CC_BORLANDC 1 +# define LZO_INFO_CC "Borland C" +# define LZO_INFO_CCVER LZO_PP_MACRO_EXPAND(__BORLANDC__) +#elif defined(_CRAYC) && defined(_RELEASE) +# define LZO_CC_CRAYC 1 +# define LZO_INFO_CC "Cray C" +# define LZO_INFO_CCVER LZO_PP_MACRO_EXPAND(_RELEASE) +#elif defined(__DMC__) && defined(__SC__) +# define LZO_CC_DMC 1 +# define LZO_INFO_CC "Digital Mars C" +# define LZO_INFO_CCVER LZO_PP_MACRO_EXPAND(__DMC__) +#elif defined(__DECC) +# define LZO_CC_DECC 1 +# define LZO_INFO_CC "DEC C" +# define LZO_INFO_CCVER LZO_PP_MACRO_EXPAND(__DECC) +#elif (defined(__ghs) || defined(__ghs__)) && defined(__GHS_VERSION_NUMBER) && ((__GHS_VERSION_NUMBER-0) > 0) +# define LZO_CC_GHS 1 +# define LZO_INFO_CC "Green Hills C" +# define LZO_INFO_CCVER LZO_PP_MACRO_EXPAND(__GHS_VERSION_NUMBER) +# if defined(_MSC_VER) && ((_MSC_VER-0) > 0) +# define LZO_CC_GHS_MSC _MSC_VER +# elif defined(__GNUC__) && defined(__GNUC_MINOR__) && defined(__VERSION__) +# define LZO_CC_GHS_GNUC (__GNUC__ * 0x10000L + (__GNUC_MINOR__-0) * 0x100 + (__GNUC_PATCHLEVEL__-0)) +# endif +#elif defined(__HIGHC__) +# define LZO_CC_HIGHC 1 +# define LZO_INFO_CC "MetaWare High C" +# define LZO_INFO_CCVER "unknown" +#elif defined(__HP_aCC) && ((__HP_aCC-0) > 0) +# define LZO_CC_HPACC __HP_aCC +# define LZO_INFO_CC "HP aCC" +# define LZO_INFO_CCVER LZO_PP_MACRO_EXPAND(__HP_aCC) +#elif defined(__IAR_SYSTEMS_ICC__) +# define LZO_CC_IARC 1 +# define LZO_INFO_CC "IAR C" +# if defined(__VER__) +# define LZO_INFO_CCVER LZO_PP_MACRO_EXPAND(__VER__) +# else +# define LZO_INFO_CCVER "unknown" +# endif +#elif defined(__IBMC__) && ((__IBMC__-0) > 0) +# define LZO_CC_IBMC __IBMC__ +# define LZO_INFO_CC "IBM C" +# define LZO_INFO_CCVER LZO_PP_MACRO_EXPAND(__IBMC__) +#elif defined(__IBMCPP__) && ((__IBMCPP__-0) > 0) +# define LZO_CC_IBMC __IBMCPP__ +# define LZO_INFO_CC "IBM C" +# define LZO_INFO_CCVER LZO_PP_MACRO_EXPAND(__IBMCPP__) +#elif defined(__KEIL__) && defined(__C166__) +# define LZO_CC_KEILC 1 +# define LZO_INFO_CC "Keil C" +# define LZO_INFO_CCVER LZO_PP_MACRO_EXPAND(__C166__) +#elif defined(__LCC__) && defined(_WIN32) && defined(__LCCOPTIMLEVEL) +# define LZO_CC_LCCWIN32 1 +# define LZO_INFO_CC "lcc-win32" +# define LZO_INFO_CCVER "unknown" +#elif defined(__LCC__) +# define LZO_CC_LCC 1 +# define LZO_INFO_CC "lcc" +# if defined(__LCC_VERSION__) +# define LZO_INFO_CCVER LZO_PP_MACRO_EXPAND(__LCC_VERSION__) +# else +# define LZO_INFO_CCVER "unknown" +# endif +#elif defined(__MWERKS__) && ((__MWERKS__-0) > 0) +# define LZO_CC_MWERKS __MWERKS__ +# define LZO_INFO_CC "Metrowerks C" +# define LZO_INFO_CCVER LZO_PP_MACRO_EXPAND(__MWERKS__) +#elif (defined(__NDPC__) || defined(__NDPX__)) && defined(__i386) +# define LZO_CC_NDPC 1 +# define LZO_INFO_CC "Microway NDP C" +# define LZO_INFO_CCVER "unknown" +#elif defined(__PACIFIC__) +# define LZO_CC_PACIFICC 1 +# define LZO_INFO_CC "Pacific C" +# define LZO_INFO_CCVER LZO_PP_MACRO_EXPAND(__PACIFIC__) +#elif defined(__PGI) && defined(__PGIC__) && defined(__PGIC_MINOR__) +# if defined(__PGIC_PATCHLEVEL__) +# define LZO_CC_PGI (__PGIC__ * 0x10000L + (__PGIC_MINOR__-0) * 0x100 + (__PGIC_PATCHLEVEL__-0)) +# define LZO_INFO_CCVER LZO_PP_MACRO_EXPAND(__PGIC__) "." LZO_PP_MACRO_EXPAND(__PGIC_MINOR__) "." LZO_PP_MACRO_EXPAND(__PGIC_PATCHLEVEL__) +# else +# define LZO_CC_PGI (__PGIC__ * 0x10000L + (__PGIC_MINOR__-0) * 0x100) +# define LZO_INFO_CCVER LZO_PP_MACRO_EXPAND(__PGIC__) "." LZO_PP_MACRO_EXPAND(__PGIC_MINOR__) ".0" +# endif +# define LZO_INFO_CC "Portland Group PGI C" +#elif defined(__PGI) && (defined(__linux__) || defined(__WIN32__)) +# define LZO_CC_PGI 1 +# define LZO_INFO_CC "Portland Group PGI C" +# define LZO_INFO_CCVER "unknown" +#elif defined(__PUREC__) && defined(__TOS__) +# define LZO_CC_PUREC 1 +# define LZO_INFO_CC "Pure C" +# define LZO_INFO_CCVER LZO_PP_MACRO_EXPAND(__PUREC__) +#elif defined(__SC__) && defined(__ZTC__) +# define LZO_CC_SYMANTECC 1 +# define LZO_INFO_CC "Symantec C" +# define LZO_INFO_CCVER LZO_PP_MACRO_EXPAND(__SC__) +#elif defined(__SUNPRO_C) +# define LZO_INFO_CC "SunPro C" +# if ((__SUNPRO_C-0) > 0) +# define LZO_CC_SUNPROC __SUNPRO_C +# define LZO_INFO_CCVER LZO_PP_MACRO_EXPAND(__SUNPRO_C) +# else +# define LZO_CC_SUNPROC 1 +# define LZO_INFO_CCVER "unknown" +# endif +#elif defined(__SUNPRO_CC) +# define LZO_INFO_CC "SunPro C" +# if ((__SUNPRO_CC-0) > 0) +# define LZO_CC_SUNPROC __SUNPRO_CC +# define LZO_INFO_CCVER LZO_PP_MACRO_EXPAND(__SUNPRO_CC) +# else +# define LZO_CC_SUNPROC 1 +# define LZO_INFO_CCVER "unknown" +# endif +#elif defined(__TINYC__) +# define LZO_CC_TINYC 1 +# define LZO_INFO_CC "Tiny C" +# define LZO_INFO_CCVER LZO_PP_MACRO_EXPAND(__TINYC__) +#elif defined(__TSC__) +# define LZO_CC_TOPSPEEDC 1 +# define LZO_INFO_CC "TopSpeed C" +# define LZO_INFO_CCVER LZO_PP_MACRO_EXPAND(__TSC__) +#elif defined(__WATCOMC__) +# define LZO_CC_WATCOMC 1 +# define LZO_INFO_CC "Watcom C" +# define LZO_INFO_CCVER LZO_PP_MACRO_EXPAND(__WATCOMC__) +#elif defined(__TURBOC__) +# define LZO_CC_TURBOC 1 +# define LZO_INFO_CC "Turbo C" +# define LZO_INFO_CCVER LZO_PP_MACRO_EXPAND(__TURBOC__) +#elif defined(__ZTC__) +# define LZO_CC_ZORTECHC 1 +# define LZO_INFO_CC "Zortech C" +# if ((__ZTC__-0) == 0x310) +# define LZO_INFO_CCVER "0x310" +# else +# define LZO_INFO_CCVER LZO_PP_MACRO_EXPAND(__ZTC__) +# endif +#elif defined(__GNUC__) && defined(__VERSION__) +# if defined(__GNUC_MINOR__) && defined(__GNUC_PATCHLEVEL__) +# define LZO_CC_GNUC (__GNUC__ * 0x10000L + (__GNUC_MINOR__-0) * 0x100 + (__GNUC_PATCHLEVEL__-0)) +# elif defined(__GNUC_MINOR__) +# define LZO_CC_GNUC (__GNUC__ * 0x10000L + (__GNUC_MINOR__-0) * 0x100) +# else +# define LZO_CC_GNUC (__GNUC__ * 0x10000L) +# endif +# define LZO_INFO_CC "gcc" +# define LZO_INFO_CCVER __VERSION__ +#elif defined(_MSC_VER) && ((_MSC_VER-0) > 0) +# define LZO_CC_MSC _MSC_VER +# define LZO_INFO_CC "Microsoft C" +# if defined(_MSC_FULL_VER) +# define LZO_INFO_CCVER LZO_PP_MACRO_EXPAND(_MSC_VER) "." LZO_PP_MACRO_EXPAND(_MSC_FULL_VER) +# else +# define LZO_INFO_CCVER LZO_PP_MACRO_EXPAND(_MSC_VER) +# endif +#else +# define LZO_CC_UNKNOWN 1 +# define LZO_INFO_CC "unknown" +# define LZO_INFO_CCVER "unknown" +#endif +#if (LZO_CC_GNUC) && defined(__OPEN64__) +# if defined(__OPENCC__) && defined(__OPENCC_MINOR__) && defined(__OPENCC_PATCHLEVEL__) +# define LZO_CC_OPEN64 (__OPENCC__ * 0x10000L + (__OPENCC_MINOR__-0) * 0x100 + (__OPENCC_PATCHLEVEL__-0)) +# define LZO_CC_OPEN64_GNUC LZO_CC_GNUC +# endif +#endif +#if (LZO_CC_GNUC) && defined(__PCC__) +# if defined(__PCC__) && defined(__PCC_MINOR__) && defined(__PCC_MINORMINOR__) +# define LZO_CC_PCC (__PCC__ * 0x10000L + (__PCC_MINOR__-0) * 0x100 + (__PCC_MINORMINOR__-0)) +# define LZO_CC_PCC_GNUC LZO_CC_GNUC +# endif +#endif +#if 0 && (LZO_CC_MSC && (_MSC_VER >= 1200)) && !defined(_MSC_FULL_VER) +# error "LZO_CC_MSC: _MSC_FULL_VER is not defined" +#endif +#if !defined(__LZO_ARCH_OVERRIDE) && !(LZO_ARCH_GENERIC) && defined(_CRAY) +# if (UINT_MAX > LZO_0xffffffffL) && defined(_CRAY) +# if defined(_CRAYMPP) || defined(_CRAYT3D) || defined(_CRAYT3E) +# define LZO_ARCH_CRAY_MPP 1 +# elif defined(_CRAY1) +# define LZO_ARCH_CRAY_PVP 1 +# endif +# endif +#endif +#if !defined(__LZO_ARCH_OVERRIDE) +#if (LZO_ARCH_GENERIC) +# define LZO_INFO_ARCH "generic" +#elif (LZO_OS_DOS16 || LZO_OS_OS216 || LZO_OS_WIN16) +# define LZO_ARCH_I086 1 +# define LZO_INFO_ARCH "i086" +#elif defined(__aarch64__) || defined(_M_ARM64) +# define LZO_ARCH_ARM64 1 +# define LZO_INFO_ARCH "arm64" +#elif defined(__alpha__) || defined(__alpha) || defined(_M_ALPHA) +# define LZO_ARCH_ALPHA 1 +# define LZO_INFO_ARCH "alpha" +#elif (LZO_ARCH_CRAY_MPP) && (defined(_CRAYT3D) || defined(_CRAYT3E)) +# define LZO_ARCH_ALPHA 1 +# define LZO_INFO_ARCH "alpha" +#elif defined(__amd64__) || defined(__x86_64__) || defined(_M_AMD64) +# define LZO_ARCH_AMD64 1 +# define LZO_INFO_ARCH "amd64" +#elif defined(__arm__) || defined(_M_ARM) +# define LZO_ARCH_ARM 1 +# define LZO_INFO_ARCH "arm" +#elif defined(__IAR_SYSTEMS_ICC__) && defined(__ICCARM__) +# define LZO_ARCH_ARM 1 +# define LZO_INFO_ARCH "arm" +#elif (UINT_MAX <= LZO_0xffffL) && defined(__AVR__) +# define LZO_ARCH_AVR 1 +# define LZO_INFO_ARCH "avr" +#elif defined(__avr32__) || defined(__AVR32__) +# define LZO_ARCH_AVR32 1 +# define LZO_INFO_ARCH "avr32" +#elif defined(__bfin__) +# define LZO_ARCH_BLACKFIN 1 +# define LZO_INFO_ARCH "blackfin" +#elif (UINT_MAX == LZO_0xffffL) && defined(__C166__) +# define LZO_ARCH_C166 1 +# define LZO_INFO_ARCH "c166" +#elif defined(__cris__) +# define LZO_ARCH_CRIS 1 +# define LZO_INFO_ARCH "cris" +#elif defined(__IAR_SYSTEMS_ICC__) && defined(__ICCEZ80__) +# define LZO_ARCH_EZ80 1 +# define LZO_INFO_ARCH "ez80" +#elif defined(__H8300__) || defined(__H8300H__) || defined(__H8300S__) || defined(__H8300SX__) +# define LZO_ARCH_H8300 1 +# define LZO_INFO_ARCH "h8300" +#elif defined(__hppa__) || defined(__hppa) +# define LZO_ARCH_HPPA 1 +# define LZO_INFO_ARCH "hppa" +#elif defined(__386__) || defined(__i386__) || defined(__i386) || defined(_M_IX86) || defined(_M_I386) +# define LZO_ARCH_I386 1 +# define LZO_ARCH_IA32 1 +# define LZO_INFO_ARCH "i386" +#elif (LZO_CC_ZORTECHC && defined(__I86__)) +# define LZO_ARCH_I386 1 +# define LZO_ARCH_IA32 1 +# define LZO_INFO_ARCH "i386" +#elif (LZO_OS_DOS32 && LZO_CC_HIGHC) && defined(_I386) +# define LZO_ARCH_I386 1 +# define LZO_ARCH_IA32 1 +# define LZO_INFO_ARCH "i386" +#elif defined(__ia64__) || defined(__ia64) || defined(_M_IA64) +# define LZO_ARCH_IA64 1 +# define LZO_INFO_ARCH "ia64" +#elif (UINT_MAX == LZO_0xffffL) && defined(__m32c__) +# define LZO_ARCH_M16C 1 +# define LZO_INFO_ARCH "m16c" +#elif defined(__IAR_SYSTEMS_ICC__) && defined(__ICCM16C__) +# define LZO_ARCH_M16C 1 +# define LZO_INFO_ARCH "m16c" +#elif defined(__m32r__) +# define LZO_ARCH_M32R 1 +# define LZO_INFO_ARCH "m32r" +#elif (LZO_OS_TOS) || defined(__m68k__) || defined(__m68000__) || defined(__mc68000__) || defined(__mc68020__) || defined(_M_M68K) +# define LZO_ARCH_M68K 1 +# define LZO_INFO_ARCH "m68k" +#elif (UINT_MAX == LZO_0xffffL) && defined(__C251__) +# define LZO_ARCH_MCS251 1 +# define LZO_INFO_ARCH "mcs251" +#elif (UINT_MAX == LZO_0xffffL) && defined(__C51__) +# define LZO_ARCH_MCS51 1 +# define LZO_INFO_ARCH "mcs51" +#elif defined(__IAR_SYSTEMS_ICC__) && defined(__ICC8051__) +# define LZO_ARCH_MCS51 1 +# define LZO_INFO_ARCH "mcs51" +#elif defined(__mips__) || defined(__mips) || defined(_MIPS_ARCH) || defined(_M_MRX000) +# define LZO_ARCH_MIPS 1 +# define LZO_INFO_ARCH "mips" +#elif (UINT_MAX == LZO_0xffffL) && defined(__MSP430__) +# define LZO_ARCH_MSP430 1 +# define LZO_INFO_ARCH "msp430" +#elif defined(__IAR_SYSTEMS_ICC__) && defined(__ICC430__) +# define LZO_ARCH_MSP430 1 +# define LZO_INFO_ARCH "msp430" +#elif defined(__powerpc__) || defined(__powerpc) || defined(__ppc__) || defined(__PPC__) || defined(_M_PPC) || defined(_ARCH_PPC) || defined(_ARCH_PWR) +# define LZO_ARCH_POWERPC 1 +# define LZO_INFO_ARCH "powerpc" +#elif defined(__powerpc64__) || defined(__powerpc64) || defined(__ppc64__) || defined(__PPC64__) +# define LZO_ARCH_POWERPC 1 +# define LZO_INFO_ARCH "powerpc" +#elif defined(__powerpc64le__) || defined(__powerpc64le) || defined(__ppc64le__) || defined(__PPC64LE__) +# define LZO_ARCH_POWERPC 1 +# define LZO_INFO_ARCH "powerpc" +#elif defined(__riscv) +# define LZO_ARCH_RISCV 1 +# define LZO_INFO_ARCH "riscv" +#elif defined(__s390__) || defined(__s390) || defined(__s390x__) || defined(__s390x) +# define LZO_ARCH_S390 1 +# define LZO_INFO_ARCH "s390" +#elif defined(__sh__) || defined(_M_SH) +# define LZO_ARCH_SH 1 +# define LZO_INFO_ARCH "sh" +#elif defined(__sparc__) || defined(__sparc) || defined(__sparcv8) +# define LZO_ARCH_SPARC 1 +# define LZO_INFO_ARCH "sparc" +#elif defined(__SPU__) +# define LZO_ARCH_SPU 1 +# define LZO_INFO_ARCH "spu" +#elif (UINT_MAX == LZO_0xffffL) && defined(__z80) +# define LZO_ARCH_Z80 1 +# define LZO_INFO_ARCH "z80" +#elif (LZO_ARCH_CRAY_PVP) +# if defined(_CRAYSV1) +# define LZO_ARCH_CRAY_SV1 1 +# define LZO_INFO_ARCH "cray_sv1" +# elif (_ADDR64) +# define LZO_ARCH_CRAY_T90 1 +# define LZO_INFO_ARCH "cray_t90" +# elif (_ADDR32) +# define LZO_ARCH_CRAY_YMP 1 +# define LZO_INFO_ARCH "cray_ymp" +# else +# define LZO_ARCH_CRAY_XMP 1 +# define LZO_INFO_ARCH "cray_xmp" +# endif +#else +# define LZO_ARCH_UNKNOWN 1 +# define LZO_INFO_ARCH "unknown" +#endif +#endif +#if !defined(LZO_ARCH_ARM_THUMB2) +#if (LZO_ARCH_ARM) +# if defined(__thumb__) || defined(__thumb) || defined(_M_THUMB) +# if defined(__thumb2__) +# define LZO_ARCH_ARM_THUMB2 1 +# elif 1 && defined(__TARGET_ARCH_THUMB) && ((__TARGET_ARCH_THUMB)+0 >= 4) +# define LZO_ARCH_ARM_THUMB2 1 +# elif 1 && defined(_MSC_VER) && defined(_M_THUMB) && ((_M_THUMB)+0 >= 7) +# define LZO_ARCH_ARM_THUMB2 1 +# endif +# endif +#endif +#endif +#if (LZO_ARCH_ARM_THUMB2) +# undef LZO_INFO_ARCH +# define LZO_INFO_ARCH "arm_thumb2" +#endif +#if 1 && (LZO_ARCH_UNKNOWN) && (LZO_OS_DOS32 || LZO_OS_OS2) +# error "FIXME - missing define for CPU architecture" +#endif +#if 1 && (LZO_ARCH_UNKNOWN) && (LZO_OS_WIN32) +# error "FIXME - missing LZO_OS_WIN32 define for CPU architecture" +#endif +#if 1 && (LZO_ARCH_UNKNOWN) && (LZO_OS_WIN64) +# error "FIXME - missing LZO_OS_WIN64 define for CPU architecture" +#endif +#if (LZO_OS_OS216 || LZO_OS_WIN16) +# define LZO_ARCH_I086PM 1 +#elif 1 && (LZO_OS_DOS16 && defined(BLX286)) +# define LZO_ARCH_I086PM 1 +#elif 1 && (LZO_OS_DOS16 && defined(DOSX286)) +# define LZO_ARCH_I086PM 1 +#elif 1 && (LZO_OS_DOS16 && LZO_CC_BORLANDC && defined(__DPMI16__)) +# define LZO_ARCH_I086PM 1 +#endif +#if (LZO_ARCH_AMD64 && !LZO_ARCH_X64) +# define LZO_ARCH_X64 1 +#elif (!LZO_ARCH_AMD64 && LZO_ARCH_X64) && defined(__LZO_ARCH_OVERRIDE) +# define LZO_ARCH_AMD64 1 +#endif +#if (LZO_ARCH_ARM64 && !LZO_ARCH_AARCH64) +# define LZO_ARCH_AARCH64 1 +#elif (!LZO_ARCH_ARM64 && LZO_ARCH_AARCH64) && defined(__LZO_ARCH_OVERRIDE) +# define LZO_ARCH_ARM64 1 +#endif +#if (LZO_ARCH_I386 && !LZO_ARCH_X86) +# define LZO_ARCH_X86 1 +#elif (!LZO_ARCH_I386 && LZO_ARCH_X86) && defined(__LZO_ARCH_OVERRIDE) +# define LZO_ARCH_I386 1 +#endif +#if (LZO_ARCH_AMD64 && !LZO_ARCH_X64) || (!LZO_ARCH_AMD64 && LZO_ARCH_X64) +# error "unexpected configuration - check your compiler defines" +#endif +#if (LZO_ARCH_ARM64 && !LZO_ARCH_AARCH64) || (!LZO_ARCH_ARM64 && LZO_ARCH_AARCH64) +# error "unexpected configuration - check your compiler defines" +#endif +#if (LZO_ARCH_I386 && !LZO_ARCH_X86) || (!LZO_ARCH_I386 && LZO_ARCH_X86) +# error "unexpected configuration - check your compiler defines" +#endif +#if (LZO_ARCH_ARM_THUMB1 && !LZO_ARCH_ARM) +# error "unexpected configuration - check your compiler defines" +#endif +#if (LZO_ARCH_ARM_THUMB2 && !LZO_ARCH_ARM) +# error "unexpected configuration - check your compiler defines" +#endif +#if (LZO_ARCH_ARM_THUMB1 && LZO_ARCH_ARM_THUMB2) +# error "unexpected configuration - check your compiler defines" +#endif +#if (LZO_ARCH_I086PM && !LZO_ARCH_I086) +# error "unexpected configuration - check your compiler defines" +#endif +#if (LZO_ARCH_I086) +# if (UINT_MAX != LZO_0xffffL) +# error "unexpected configuration - check your compiler defines" +# endif +# if (ULONG_MAX != LZO_0xffffffffL) +# error "unexpected configuration - check your compiler defines" +# endif +#endif +#if (LZO_ARCH_I386) +# if (UINT_MAX != LZO_0xffffL) && defined(__i386_int16__) +# error "unexpected configuration - check your compiler defines" +# endif +# if (UINT_MAX != LZO_0xffffffffL) && !defined(__i386_int16__) +# error "unexpected configuration - check your compiler defines" +# endif +# if (ULONG_MAX != LZO_0xffffffffL) +# error "unexpected configuration - check your compiler defines" +# endif +#endif +#if (LZO_ARCH_AMD64 || LZO_ARCH_I386) +# if !defined(LZO_TARGET_FEATURE_SSE2) +# if defined(__SSE2__) +# define LZO_TARGET_FEATURE_SSE2 1 +# elif defined(_MSC_VER) && (defined(_M_IX86_FP) && ((_M_IX86_FP)+0 >= 2)) +# define LZO_TARGET_FEATURE_SSE2 1 +# elif (LZO_CC_INTELC_MSC || LZO_CC_MSC) && defined(_M_AMD64) +# define LZO_TARGET_FEATURE_SSE2 1 +# endif +# endif +# if !defined(LZO_TARGET_FEATURE_SSSE3) +# if (LZO_TARGET_FEATURE_SSE2) +# if defined(__SSSE3__) +# define LZO_TARGET_FEATURE_SSSE3 1 +# elif defined(_MSC_VER) && defined(__AVX__) +# define LZO_TARGET_FEATURE_SSSE3 1 +# endif +# endif +# endif +# if !defined(LZO_TARGET_FEATURE_SSE4_2) +# if (LZO_TARGET_FEATURE_SSSE3) +# if defined(__SSE4_2__) +# define LZO_TARGET_FEATURE_SSE4_2 1 +# endif +# endif +# endif +# if !defined(LZO_TARGET_FEATURE_AVX) +# if (LZO_TARGET_FEATURE_SSSE3) +# if defined(__AVX__) +# define LZO_TARGET_FEATURE_AVX 1 +# endif +# endif +# endif +# if !defined(LZO_TARGET_FEATURE_AVX2) +# if (LZO_TARGET_FEATURE_AVX) +# if defined(__AVX2__) +# define LZO_TARGET_FEATURE_AVX2 1 +# endif +# endif +# endif +#endif +#if (LZO_TARGET_FEATURE_SSSE3 && !(LZO_TARGET_FEATURE_SSE2)) +# error "unexpected configuration - check your compiler defines" +#endif +#if (LZO_TARGET_FEATURE_SSE4_2 && !(LZO_TARGET_FEATURE_SSSE3)) +# error "unexpected configuration - check your compiler defines" +#endif +#if (LZO_TARGET_FEATURE_AVX && !(LZO_TARGET_FEATURE_SSSE3)) +# error "unexpected configuration - check your compiler defines" +#endif +#if (LZO_TARGET_FEATURE_AVX2 && !(LZO_TARGET_FEATURE_AVX)) +# error "unexpected configuration - check your compiler defines" +#endif +#if (LZO_ARCH_ARM) +# if !defined(LZO_TARGET_FEATURE_NEON) +# if defined(__ARM_NEON) && ((__ARM_NEON)+0) +# define LZO_TARGET_FEATURE_NEON 1 +# elif 1 && defined(__ARM_NEON__) && ((__ARM_NEON__)+0) +# define LZO_TARGET_FEATURE_NEON 1 +# elif 1 && defined(__TARGET_FEATURE_NEON) && ((__TARGET_FEATURE_NEON)+0) +# define LZO_TARGET_FEATURE_NEON 1 +# endif +# endif +#elif (LZO_ARCH_ARM64) +# if !defined(LZO_TARGET_FEATURE_NEON) +# if 1 +# define LZO_TARGET_FEATURE_NEON 1 +# endif +# endif +#endif +#if 0 +#elif !defined(__LZO_MM_OVERRIDE) +#if (LZO_ARCH_I086) +#if (UINT_MAX != LZO_0xffffL) +# error "unexpected configuration - check your compiler defines" +#endif +#if defined(__TINY__) || defined(M_I86TM) || defined(_M_I86TM) +# define LZO_MM_TINY 1 +#elif defined(__HUGE__) || defined(_HUGE_) || defined(M_I86HM) || defined(_M_I86HM) +# define LZO_MM_HUGE 1 +#elif defined(__SMALL__) || defined(M_I86SM) || defined(_M_I86SM) || defined(SMALL_MODEL) +# define LZO_MM_SMALL 1 +#elif defined(__MEDIUM__) || defined(M_I86MM) || defined(_M_I86MM) +# define LZO_MM_MEDIUM 1 +#elif defined(__COMPACT__) || defined(M_I86CM) || defined(_M_I86CM) +# define LZO_MM_COMPACT 1 +#elif defined(__LARGE__) || defined(M_I86LM) || defined(_M_I86LM) || defined(LARGE_MODEL) +# define LZO_MM_LARGE 1 +#elif (LZO_CC_AZTECC) +# if defined(_LARGE_CODE) && defined(_LARGE_DATA) +# define LZO_MM_LARGE 1 +# elif defined(_LARGE_CODE) +# define LZO_MM_MEDIUM 1 +# elif defined(_LARGE_DATA) +# define LZO_MM_COMPACT 1 +# else +# define LZO_MM_SMALL 1 +# endif +#elif (LZO_CC_ZORTECHC && defined(__VCM__)) +# define LZO_MM_LARGE 1 +#else +# error "unknown LZO_ARCH_I086 memory model" +#endif +#if (LZO_OS_DOS16 || LZO_OS_OS216 || LZO_OS_WIN16) +#define LZO_HAVE_MM_HUGE_PTR 1 +#define LZO_HAVE_MM_HUGE_ARRAY 1 +#if (LZO_MM_TINY) +# undef LZO_HAVE_MM_HUGE_ARRAY +#endif +#if (LZO_CC_AZTECC || LZO_CC_PACIFICC || LZO_CC_ZORTECHC) +# undef LZO_HAVE_MM_HUGE_PTR +# undef LZO_HAVE_MM_HUGE_ARRAY +#elif (LZO_CC_DMC || LZO_CC_SYMANTECC) +# undef LZO_HAVE_MM_HUGE_ARRAY +#elif (LZO_CC_MSC && defined(_QC)) +# undef LZO_HAVE_MM_HUGE_ARRAY +# if (_MSC_VER < 600) +# undef LZO_HAVE_MM_HUGE_PTR +# endif +#elif (LZO_CC_TURBOC && (__TURBOC__ < 0x0295)) +# undef LZO_HAVE_MM_HUGE_ARRAY +#endif +#if (LZO_ARCH_I086PM) && !(LZO_HAVE_MM_HUGE_PTR) +# if (LZO_OS_DOS16) +# error "unexpected configuration - check your compiler defines" +# elif (LZO_CC_ZORTECHC) +# else +# error "unexpected configuration - check your compiler defines" +# endif +#endif +#if defined(__cplusplus) +extern "C" { +#endif +#if (LZO_CC_BORLANDC && (__BORLANDC__ >= 0x0200)) + extern void __near __cdecl _AHSHIFT(void); +# define LZO_MM_AHSHIFT ((unsigned) _AHSHIFT) +#elif (LZO_CC_DMC || LZO_CC_SYMANTECC || LZO_CC_ZORTECHC) + extern void __near __cdecl _AHSHIFT(void); +# define LZO_MM_AHSHIFT ((unsigned) _AHSHIFT) +#elif (LZO_CC_MSC || LZO_CC_TOPSPEEDC) + extern void __near __cdecl _AHSHIFT(void); +# define LZO_MM_AHSHIFT ((unsigned) _AHSHIFT) +#elif (LZO_CC_TURBOC && (__TURBOC__ >= 0x0295)) + extern void __near __cdecl _AHSHIFT(void); +# define LZO_MM_AHSHIFT ((unsigned) _AHSHIFT) +#elif ((LZO_CC_AZTECC || LZO_CC_PACIFICC || LZO_CC_TURBOC) && LZO_OS_DOS16) +# define LZO_MM_AHSHIFT 12 +#elif (LZO_CC_WATCOMC) + extern unsigned char _HShift; +# define LZO_MM_AHSHIFT ((unsigned) _HShift) +#else +# error "FIXME - implement LZO_MM_AHSHIFT" +#endif +#if defined(__cplusplus) +} +#endif +#endif +#elif (LZO_ARCH_C166) +#if !defined(__MODEL__) +# error "FIXME - LZO_ARCH_C166 __MODEL__" +#elif ((__MODEL__) == 0) +# define LZO_MM_SMALL 1 +#elif ((__MODEL__) == 1) +# define LZO_MM_SMALL 1 +#elif ((__MODEL__) == 2) +# define LZO_MM_LARGE 1 +#elif ((__MODEL__) == 3) +# define LZO_MM_TINY 1 +#elif ((__MODEL__) == 4) +# define LZO_MM_XTINY 1 +#elif ((__MODEL__) == 5) +# define LZO_MM_XSMALL 1 +#else +# error "FIXME - LZO_ARCH_C166 __MODEL__" +#endif +#elif (LZO_ARCH_MCS251) +#if !defined(__MODEL__) +# error "FIXME - LZO_ARCH_MCS251 __MODEL__" +#elif ((__MODEL__) == 0) +# define LZO_MM_SMALL 1 +#elif ((__MODEL__) == 2) +# define LZO_MM_LARGE 1 +#elif ((__MODEL__) == 3) +# define LZO_MM_TINY 1 +#elif ((__MODEL__) == 4) +# define LZO_MM_XTINY 1 +#elif ((__MODEL__) == 5) +# define LZO_MM_XSMALL 1 +#else +# error "FIXME - LZO_ARCH_MCS251 __MODEL__" +#endif +#elif (LZO_ARCH_MCS51) +#if !defined(__MODEL__) +# error "FIXME - LZO_ARCH_MCS51 __MODEL__" +#elif ((__MODEL__) == 1) +# define LZO_MM_SMALL 1 +#elif ((__MODEL__) == 2) +# define LZO_MM_LARGE 1 +#elif ((__MODEL__) == 3) +# define LZO_MM_TINY 1 +#elif ((__MODEL__) == 4) +# define LZO_MM_XTINY 1 +#elif ((__MODEL__) == 5) +# define LZO_MM_XSMALL 1 +#else +# error "FIXME - LZO_ARCH_MCS51 __MODEL__" +#endif +#elif (LZO_ARCH_CRAY_PVP) +# define LZO_MM_PVP 1 +#else +# define LZO_MM_FLAT 1 +#endif +#if (LZO_MM_COMPACT) +# define LZO_INFO_MM "compact" +#elif (LZO_MM_FLAT) +# define LZO_INFO_MM "flat" +#elif (LZO_MM_HUGE) +# define LZO_INFO_MM "huge" +#elif (LZO_MM_LARGE) +# define LZO_INFO_MM "large" +#elif (LZO_MM_MEDIUM) +# define LZO_INFO_MM "medium" +#elif (LZO_MM_PVP) +# define LZO_INFO_MM "pvp" +#elif (LZO_MM_SMALL) +# define LZO_INFO_MM "small" +#elif (LZO_MM_TINY) +# define LZO_INFO_MM "tiny" +#else +# error "unknown memory model" +#endif +#endif +#if !defined(__lzo_gnuc_extension__) +#if (LZO_CC_GNUC >= 0x020800ul) +# define __lzo_gnuc_extension__ __extension__ +#elif (LZO_CC_ARMCC_GNUC || LZO_CC_CLANG || LZO_CC_LLVM || LZO_CC_PATHSCALE) +# define __lzo_gnuc_extension__ __extension__ +#elif (LZO_CC_IBMC >= 600) +# define __lzo_gnuc_extension__ __extension__ +#endif +#endif +#if !defined(__lzo_gnuc_extension__) +# define __lzo_gnuc_extension__ /*empty*/ +#endif +#if !defined(lzo_has_builtin) +#if (LZO_CC_CLANG) && defined(__has_builtin) +# define lzo_has_builtin __has_builtin +#endif +#endif +#if !defined(lzo_has_builtin) +# define lzo_has_builtin(x) 0 +#endif +#if !defined(lzo_has_attribute) +#if (LZO_CC_CLANG) && defined(__has_attribute) +# define lzo_has_attribute __has_attribute +#endif +#endif +#if !defined(lzo_has_attribute) +# define lzo_has_attribute(x) 0 +#endif +#if !defined(lzo_has_declspec_attribute) +#if (LZO_CC_CLANG) && defined(__has_declspec_attribute) +# define lzo_has_declspec_attribute __has_declspec_attribute +#endif +#endif +#if !defined(lzo_has_declspec_attribute) +# define lzo_has_declspec_attribute(x) 0 +#endif +#if !defined(lzo_has_feature) +#if (LZO_CC_CLANG) && defined(__has_feature) +# define lzo_has_feature __has_feature +#endif +#endif +#if !defined(lzo_has_feature) +# define lzo_has_feature(x) 0 +#endif +#if !defined(lzo_has_extension) +#if (LZO_CC_CLANG) && defined(__has_extension) +# define lzo_has_extension __has_extension +#elif (LZO_CC_CLANG) && defined(__has_feature) +# define lzo_has_extension __has_feature +#endif +#endif +#if !defined(lzo_has_extension) +# define lzo_has_extension(x) 0 +#endif +#if !defined(LZO_CFG_USE_NEW_STYLE_CASTS) && defined(__cplusplus) && 0 +# if (LZO_CC_GNUC && (LZO_CC_GNUC < 0x020800ul)) +# define LZO_CFG_USE_NEW_STYLE_CASTS 0 +# elif (LZO_CC_INTELC && (__INTEL_COMPILER < 1200)) +# define LZO_CFG_USE_NEW_STYLE_CASTS 0 +# else +# define LZO_CFG_USE_NEW_STYLE_CASTS 1 +# endif +#endif +#if !defined(LZO_CFG_USE_NEW_STYLE_CASTS) +# define LZO_CFG_USE_NEW_STYLE_CASTS 0 +#endif +#if !defined(__cplusplus) +# if defined(LZO_CFG_USE_NEW_STYLE_CASTS) +# undef LZO_CFG_USE_NEW_STYLE_CASTS +# endif +# define LZO_CFG_USE_NEW_STYLE_CASTS 0 +#endif +#if !defined(LZO_REINTERPRET_CAST) +# if (LZO_CFG_USE_NEW_STYLE_CASTS) +# define LZO_REINTERPRET_CAST(t,e) (reinterpret_cast (e)) +# endif +#endif +#if !defined(LZO_REINTERPRET_CAST) +# define LZO_REINTERPRET_CAST(t,e) ((t) (e)) +#endif +#if !defined(LZO_STATIC_CAST) +# if (LZO_CFG_USE_NEW_STYLE_CASTS) +# define LZO_STATIC_CAST(t,e) (static_cast (e)) +# endif +#endif +#if !defined(LZO_STATIC_CAST) +# define LZO_STATIC_CAST(t,e) ((t) (e)) +#endif +#if !defined(LZO_STATIC_CAST2) +# define LZO_STATIC_CAST2(t1,t2,e) LZO_STATIC_CAST(t1, LZO_STATIC_CAST(t2, e)) +#endif +#if !defined(LZO_UNCONST_CAST) +# if (LZO_CFG_USE_NEW_STYLE_CASTS) +# define LZO_UNCONST_CAST(t,e) (const_cast (e)) +# elif (LZO_HAVE_MM_HUGE_PTR) +# define LZO_UNCONST_CAST(t,e) ((t) (e)) +# elif (LZO_CC_ARMCC_GNUC || LZO_CC_CLANG || LZO_CC_GNUC || LZO_CC_LLVM || LZO_CC_PATHSCALE) +# define LZO_UNCONST_CAST(t,e) ((t) ((void *) ((lzo_uintptr_t) ((const void *) (e))))) +# endif +#endif +#if !defined(LZO_UNCONST_CAST) +# define LZO_UNCONST_CAST(t,e) ((t) ((void *) ((const void *) (e)))) +#endif +#if !defined(LZO_UNCONST_VOLATILE_CAST) +# if (LZO_CFG_USE_NEW_STYLE_CASTS) +# define LZO_UNCONST_VOLATILE_CAST(t,e) (const_cast (e)) +# elif (LZO_HAVE_MM_HUGE_PTR) +# define LZO_UNCONST_VOLATILE_CAST(t,e) ((t) (e)) +# elif (LZO_CC_ARMCC_GNUC || LZO_CC_CLANG || LZO_CC_GNUC || LZO_CC_LLVM || LZO_CC_PATHSCALE) +# define LZO_UNCONST_VOLATILE_CAST(t,e) ((t) ((volatile void *) ((lzo_uintptr_t) ((volatile const void *) (e))))) +# endif +#endif +#if !defined(LZO_UNCONST_VOLATILE_CAST) +# define LZO_UNCONST_VOLATILE_CAST(t,e) ((t) ((volatile void *) ((volatile const void *) (e)))) +#endif +#if !defined(LZO_UNVOLATILE_CAST) +# if (LZO_CFG_USE_NEW_STYLE_CASTS) +# define LZO_UNVOLATILE_CAST(t,e) (const_cast (e)) +# elif (LZO_HAVE_MM_HUGE_PTR) +# define LZO_UNVOLATILE_CAST(t,e) ((t) (e)) +# elif (LZO_CC_ARMCC_GNUC || LZO_CC_CLANG || LZO_CC_GNUC || LZO_CC_LLVM || LZO_CC_PATHSCALE) +# define LZO_UNVOLATILE_CAST(t,e) ((t) ((void *) ((lzo_uintptr_t) ((volatile void *) (e))))) +# endif +#endif +#if !defined(LZO_UNVOLATILE_CAST) +# define LZO_UNVOLATILE_CAST(t,e) ((t) ((void *) ((volatile void *) (e)))) +#endif +#if !defined(LZO_UNVOLATILE_CONST_CAST) +# if (LZO_CFG_USE_NEW_STYLE_CASTS) +# define LZO_UNVOLATILE_CONST_CAST(t,e) (const_cast (e)) +# elif (LZO_HAVE_MM_HUGE_PTR) +# define LZO_UNVOLATILE_CONST_CAST(t,e) ((t) (e)) +# elif (LZO_CC_ARMCC_GNUC || LZO_CC_CLANG || LZO_CC_GNUC || LZO_CC_LLVM || LZO_CC_PATHSCALE) +# define LZO_UNVOLATILE_CONST_CAST(t,e) ((t) ((const void *) ((lzo_uintptr_t) ((volatile const void *) (e))))) +# endif +#endif +#if !defined(LZO_UNVOLATILE_CONST_CAST) +# define LZO_UNVOLATILE_CONST_CAST(t,e) ((t) ((const void *) ((volatile const void *) (e)))) +#endif +#if !defined(LZO_PCAST) +# if (LZO_HAVE_MM_HUGE_PTR) +# define LZO_PCAST(t,e) ((t) (e)) +# endif +#endif +#if !defined(LZO_PCAST) +# define LZO_PCAST(t,e) LZO_STATIC_CAST(t, LZO_STATIC_CAST(void *, e)) +#endif +#if !defined(LZO_CCAST) +# if (LZO_HAVE_MM_HUGE_PTR) +# define LZO_CCAST(t,e) ((t) (e)) +# endif +#endif +#if !defined(LZO_CCAST) +# define LZO_CCAST(t,e) LZO_STATIC_CAST(t, LZO_STATIC_CAST(const void *, e)) +#endif +#if !defined(LZO_ICONV) +# define LZO_ICONV(t,e) LZO_STATIC_CAST(t, e) +#endif +#if !defined(LZO_ICAST) +# define LZO_ICAST(t,e) LZO_STATIC_CAST(t, e) +#endif +#if !defined(LZO_ITRUNC) +# define LZO_ITRUNC(t,e) LZO_STATIC_CAST(t, e) +#endif +#if !defined(__lzo_cte) +# if (LZO_CC_MSC || LZO_CC_WATCOMC) +# define __lzo_cte(e) ((void)0,(e)) +# elif 1 +# define __lzo_cte(e) ((void)0,(e)) +# endif +#endif +#if !defined(__lzo_cte) +# define __lzo_cte(e) (e) +#endif +#if !defined(LZO_BLOCK_BEGIN) +# define LZO_BLOCK_BEGIN do { +# define LZO_BLOCK_END } while __lzo_cte(0) +#endif +#if !defined(LZO_UNUSED) +# if (LZO_CC_BORLANDC && (__BORLANDC__ >= 0x0600)) +# define LZO_UNUSED(var) ((void) &var) +# elif (LZO_CC_BORLANDC || LZO_CC_HIGHC || LZO_CC_NDPC || LZO_CC_PELLESC || LZO_CC_TURBOC) +# define LZO_UNUSED(var) if (&var) ; else +# elif (LZO_CC_CLANG && (LZO_CC_CLANG >= 0x030200ul)) +# define LZO_UNUSED(var) ((void) &var) +# elif (LZO_CC_CLANG || LZO_CC_GNUC || LZO_CC_LLVM || LZO_CC_PATHSCALE) +# define LZO_UNUSED(var) ((void) var) +# elif (LZO_CC_MSC && (_MSC_VER < 900)) +# define LZO_UNUSED(var) if (&var) ; else +# elif (LZO_CC_KEILC) +# define LZO_UNUSED(var) {extern int lzo_unused__[1-2*!(sizeof(var)>0)]; (void)lzo_unused__;} +# elif (LZO_CC_PACIFICC) +# define LZO_UNUSED(var) ((void) sizeof(var)) +# elif (LZO_CC_WATCOMC) && defined(__cplusplus) +# define LZO_UNUSED(var) ((void) var) +# else +# define LZO_UNUSED(var) ((void) &var) +# endif +#endif +#if !defined(LZO_UNUSED_RESULT) +# define LZO_UNUSED_RESULT(var) LZO_UNUSED(var) +#endif +#if !defined(LZO_UNUSED_FUNC) +# if (LZO_CC_BORLANDC && (__BORLANDC__ >= 0x0600)) +# define LZO_UNUSED_FUNC(func) ((void) func) +# elif (LZO_CC_BORLANDC || LZO_CC_NDPC || LZO_CC_TURBOC) +# define LZO_UNUSED_FUNC(func) if (func) ; else +# elif (LZO_CC_CLANG || LZO_CC_LLVM) +# define LZO_UNUSED_FUNC(func) ((void) &func) +# elif (LZO_CC_MSC && (_MSC_VER < 900)) +# define LZO_UNUSED_FUNC(func) if (func) ; else +# elif (LZO_CC_MSC) +# define LZO_UNUSED_FUNC(func) ((void) &func) +# elif (LZO_CC_KEILC || LZO_CC_PELLESC) +# define LZO_UNUSED_FUNC(func) {extern int lzo_unused__[1-2*!(sizeof((int)func)>0)]; (void)lzo_unused__;} +# else +# define LZO_UNUSED_FUNC(func) ((void) func) +# endif +#endif +#if !defined(LZO_UNUSED_LABEL) +# if (LZO_CC_CLANG >= 0x020800ul) +# define LZO_UNUSED_LABEL(l) (__lzo_gnuc_extension__ ((void) ((const void *) &&l))) +# elif (LZO_CC_ARMCC || LZO_CC_CLANG || LZO_CC_INTELC || LZO_CC_WATCOMC) +# define LZO_UNUSED_LABEL(l) if __lzo_cte(0) goto l +# else +# define LZO_UNUSED_LABEL(l) switch (0) case 1:goto l +# endif +#endif +#if !defined(LZO_DEFINE_UNINITIALIZED_VAR) +# if 0 +# define LZO_DEFINE_UNINITIALIZED_VAR(type,var,init) type var +# elif 0 && (LZO_CC_GNUC) +# define LZO_DEFINE_UNINITIALIZED_VAR(type,var,init) type var = var +# else +# define LZO_DEFINE_UNINITIALIZED_VAR(type,var,init) type var = init +# endif +#endif +#if !defined(__lzo_inline) +#if (LZO_CC_TURBOC && (__TURBOC__ <= 0x0295)) +#elif defined(__cplusplus) +# define __lzo_inline inline +#elif defined(__STDC_VERSION__) && (__STDC_VERSION__-0 >= 199901L) +# define __lzo_inline inline +#elif (LZO_CC_BORLANDC && (__BORLANDC__ >= 0x0550)) +# define __lzo_inline __inline +#elif (LZO_CC_ARMCC_GNUC || LZO_CC_CILLY || LZO_CC_CLANG || LZO_CC_GNUC || LZO_CC_LLVM || LZO_CC_PATHSCALE || LZO_CC_PGI) +# define __lzo_inline __inline__ +#elif (LZO_CC_DMC) +# define __lzo_inline __inline +#elif (LZO_CC_GHS) +# define __lzo_inline __inline__ +#elif (LZO_CC_IBMC >= 600) +# define __lzo_inline __inline__ +#elif (LZO_CC_INTELC) +# define __lzo_inline __inline +#elif (LZO_CC_MWERKS && (__MWERKS__ >= 0x2405)) +# define __lzo_inline __inline +#elif (LZO_CC_MSC && (_MSC_VER >= 900)) +# define __lzo_inline __inline +#elif (LZO_CC_SUNPROC >= 0x5100) +# define __lzo_inline __inline__ +#endif +#endif +#if defined(__lzo_inline) +# ifndef __lzo_HAVE_inline +# define __lzo_HAVE_inline 1 +# endif +#else +# define __lzo_inline /*empty*/ +#endif +#if !defined(__lzo_forceinline) +#if (LZO_CC_GNUC >= 0x030200ul) +# define __lzo_forceinline __inline__ __attribute__((__always_inline__)) +#elif (LZO_CC_IBMC >= 700) +# define __lzo_forceinline __inline__ __attribute__((__always_inline__)) +#elif (LZO_CC_INTELC_MSC && (__INTEL_COMPILER >= 450)) +# define __lzo_forceinline __forceinline +#elif (LZO_CC_INTELC_GNUC && (__INTEL_COMPILER >= 800)) +# define __lzo_forceinline __inline__ __attribute__((__always_inline__)) +#elif (LZO_CC_ARMCC_GNUC || LZO_CC_CLANG || LZO_CC_LLVM || LZO_CC_PATHSCALE) +# define __lzo_forceinline __inline__ __attribute__((__always_inline__)) +#elif (LZO_CC_MSC && (_MSC_VER >= 1200)) +# define __lzo_forceinline __forceinline +#elif (LZO_CC_PGI >= 0x0d0a00ul) +# define __lzo_forceinline __inline__ __attribute__((__always_inline__)) +#elif (LZO_CC_SUNPROC >= 0x5100) +# define __lzo_forceinline __inline__ __attribute__((__always_inline__)) +#endif +#endif +#if defined(__lzo_forceinline) +# ifndef __lzo_HAVE_forceinline +# define __lzo_HAVE_forceinline 1 +# endif +#else +# define __lzo_forceinline __lzo_inline +#endif +#if !defined(__lzo_noinline) +#if 1 && (LZO_ARCH_I386) && (LZO_CC_GNUC >= 0x040000ul) && (LZO_CC_GNUC < 0x040003ul) +# define __lzo_noinline __attribute__((__noinline__,__used__)) +#elif (LZO_CC_GNUC >= 0x030200ul) +# define __lzo_noinline __attribute__((__noinline__)) +#elif (LZO_CC_IBMC >= 700) +# define __lzo_noinline __attribute__((__noinline__)) +#elif (LZO_CC_INTELC_MSC && (__INTEL_COMPILER >= 600)) +# define __lzo_noinline __declspec(noinline) +#elif (LZO_CC_INTELC_GNUC && (__INTEL_COMPILER >= 800)) +# define __lzo_noinline __attribute__((__noinline__)) +#elif (LZO_CC_ARMCC_GNUC || LZO_CC_CLANG || LZO_CC_LLVM || LZO_CC_PATHSCALE) +# define __lzo_noinline __attribute__((__noinline__)) +#elif (LZO_CC_MSC && (_MSC_VER >= 1300)) +# define __lzo_noinline __declspec(noinline) +#elif (LZO_CC_MWERKS && (__MWERKS__ >= 0x3200) && (LZO_OS_WIN32 || LZO_OS_WIN64)) +# if defined(__cplusplus) +# else +# define __lzo_noinline __declspec(noinline) +# endif +#elif (LZO_CC_PGI >= 0x0d0a00ul) +# define __lzo_noinline __attribute__((__noinline__)) +#elif (LZO_CC_SUNPROC >= 0x5100) +# define __lzo_noinline __attribute__((__noinline__)) +#endif +#endif +#if defined(__lzo_noinline) +# ifndef __lzo_HAVE_noinline +# define __lzo_HAVE_noinline 1 +# endif +#else +# define __lzo_noinline /*empty*/ +#endif +#if (__lzo_HAVE_forceinline || __lzo_HAVE_noinline) && !(__lzo_HAVE_inline) +# error "unexpected configuration - check your compiler defines" +#endif +#if !defined(__lzo_static_inline) +#if (LZO_CC_IBMC) +# define __lzo_static_inline __lzo_gnuc_extension__ static __lzo_inline +#endif +#endif +#if !defined(__lzo_static_inline) +# define __lzo_static_inline static __lzo_inline +#endif +#if !defined(__lzo_static_forceinline) +#if (LZO_CC_IBMC) +# define __lzo_static_forceinline __lzo_gnuc_extension__ static __lzo_forceinline +#endif +#endif +#if !defined(__lzo_static_forceinline) +# define __lzo_static_forceinline static __lzo_forceinline +#endif +#if !defined(__lzo_static_noinline) +#if (LZO_CC_IBMC) +# define __lzo_static_noinline __lzo_gnuc_extension__ static __lzo_noinline +#endif +#endif +#if !defined(__lzo_static_noinline) +# define __lzo_static_noinline static __lzo_noinline +#endif +#if !defined(__lzo_c99_extern_inline) +#if defined(__GNUC_GNU_INLINE__) +# define __lzo_c99_extern_inline __lzo_inline +#elif defined(__GNUC_STDC_INLINE__) +# define __lzo_c99_extern_inline extern __lzo_inline +#elif defined(__STDC_VERSION__) && (__STDC_VERSION__-0 >= 199901L) +# define __lzo_c99_extern_inline extern __lzo_inline +#endif +#if !defined(__lzo_c99_extern_inline) && (__lzo_HAVE_inline) +# define __lzo_c99_extern_inline __lzo_inline +#endif +#endif +#if defined(__lzo_c99_extern_inline) +# ifndef __lzo_HAVE_c99_extern_inline +# define __lzo_HAVE_c99_extern_inline 1 +# endif +#else +# define __lzo_c99_extern_inline /*empty*/ +#endif +#if !defined(__lzo_may_alias) +#if (LZO_CC_GNUC >= 0x030400ul) +# define __lzo_may_alias __attribute__((__may_alias__)) +#elif (LZO_CC_CLANG >= 0x020900ul) +# define __lzo_may_alias __attribute__((__may_alias__)) +#elif (LZO_CC_INTELC_GNUC && (__INTEL_COMPILER >= 1210)) && 0 +# define __lzo_may_alias __attribute__((__may_alias__)) +#elif (LZO_CC_PGI >= 0x0d0a00ul) && 0 +# define __lzo_may_alias __attribute__((__may_alias__)) +#endif +#endif +#if defined(__lzo_may_alias) +# ifndef __lzo_HAVE_may_alias +# define __lzo_HAVE_may_alias 1 +# endif +#else +# define __lzo_may_alias /*empty*/ +#endif +#if !defined(__lzo_noreturn) +#if (LZO_CC_GNUC >= 0x020700ul) +# define __lzo_noreturn __attribute__((__noreturn__)) +#elif (LZO_CC_IBMC >= 700) +# define __lzo_noreturn __attribute__((__noreturn__)) +#elif (LZO_CC_INTELC_MSC && (__INTEL_COMPILER >= 450)) +# define __lzo_noreturn __declspec(noreturn) +#elif (LZO_CC_INTELC_GNUC && (__INTEL_COMPILER >= 600)) +# define __lzo_noreturn __attribute__((__noreturn__)) +#elif (LZO_CC_ARMCC_GNUC || LZO_CC_CLANG || LZO_CC_LLVM || LZO_CC_PATHSCALE) +# define __lzo_noreturn __attribute__((__noreturn__)) +#elif (LZO_CC_MSC && (_MSC_VER >= 1200)) +# define __lzo_noreturn __declspec(noreturn) +#elif (LZO_CC_PGI >= 0x0d0a00ul) +# define __lzo_noreturn __attribute__((__noreturn__)) +#endif +#endif +#if defined(__lzo_noreturn) +# ifndef __lzo_HAVE_noreturn +# define __lzo_HAVE_noreturn 1 +# endif +#else +# define __lzo_noreturn /*empty*/ +#endif +#if !defined(__lzo_nothrow) +#if (LZO_CC_GNUC >= 0x030300ul) +# define __lzo_nothrow __attribute__((__nothrow__)) +#elif (LZO_CC_INTELC_MSC && (__INTEL_COMPILER >= 450)) && defined(__cplusplus) +# define __lzo_nothrow __declspec(nothrow) +#elif (LZO_CC_INTELC_GNUC && (__INTEL_COMPILER >= 900)) +# define __lzo_nothrow __attribute__((__nothrow__)) +#elif (LZO_CC_ARMCC_GNUC || LZO_CC_CLANG || LZO_CC_LLVM || LZO_CC_PATHSCALE) +# define __lzo_nothrow __attribute__((__nothrow__)) +#elif (LZO_CC_MSC && (_MSC_VER >= 1200)) && defined(__cplusplus) +# define __lzo_nothrow __declspec(nothrow) +#endif +#endif +#if defined(__lzo_nothrow) +# ifndef __lzo_HAVE_nothrow +# define __lzo_HAVE_nothrow 1 +# endif +#else +# define __lzo_nothrow /*empty*/ +#endif +#if !defined(__lzo_restrict) +#if (LZO_CC_GNUC >= 0x030400ul) +# define __lzo_restrict __restrict__ +#elif (LZO_CC_IBMC >= 800) && !defined(__cplusplus) +# define __lzo_restrict __restrict__ +#elif (LZO_CC_IBMC >= 1210) +# define __lzo_restrict __restrict__ +#elif (LZO_CC_INTELC_MSC && (__INTEL_COMPILER >= 600)) +#elif (LZO_CC_INTELC_GNUC && (__INTEL_COMPILER >= 600)) +# define __lzo_restrict __restrict__ +#elif (LZO_CC_ARMCC_GNUC || LZO_CC_CLANG || LZO_CC_LLVM) +# define __lzo_restrict __restrict__ +#elif (LZO_CC_MSC && (_MSC_VER >= 1400)) +# define __lzo_restrict __restrict +#elif (LZO_CC_PGI >= 0x0d0a00ul) +# define __lzo_restrict __restrict__ +#endif +#endif +#if defined(__lzo_restrict) +# ifndef __lzo_HAVE_restrict +# define __lzo_HAVE_restrict 1 +# endif +#else +# define __lzo_restrict /*empty*/ +#endif +#if !defined(__lzo_alignof) +#if (LZO_CC_ARMCC || LZO_CC_CILLY || LZO_CC_CLANG || LZO_CC_GNUC || LZO_CC_LLVM || LZO_CC_PATHSCALE || LZO_CC_PGI) +# define __lzo_alignof(e) __alignof__(e) +#elif (LZO_CC_GHS) && !defined(__cplusplus) +# define __lzo_alignof(e) __alignof__(e) +#elif (LZO_CC_IBMC >= 600) +# define __lzo_alignof(e) (__lzo_gnuc_extension__ __alignof__(e)) +#elif (LZO_CC_INTELC && (__INTEL_COMPILER >= 700)) +# define __lzo_alignof(e) __alignof__(e) +#elif (LZO_CC_MSC && (_MSC_VER >= 1300)) +# define __lzo_alignof(e) __alignof(e) +#elif (LZO_CC_SUNPROC >= 0x5100) +# define __lzo_alignof(e) __alignof__(e) +#endif +#endif +#if defined(__lzo_alignof) +# ifndef __lzo_HAVE_alignof +# define __lzo_HAVE_alignof 1 +# endif +#endif +#if !defined(__lzo_struct_packed) +#if (LZO_CC_CLANG && (LZO_CC_CLANG < 0x020800ul)) && defined(__cplusplus) +#elif (LZO_CC_GNUC && (LZO_CC_GNUC < 0x020700ul)) +#elif (LZO_CC_GNUC && (LZO_CC_GNUC < 0x020800ul)) && defined(__cplusplus) +#elif (LZO_CC_PCC && (LZO_CC_PCC < 0x010100ul)) +#elif (LZO_CC_SUNPROC && (LZO_CC_SUNPROC < 0x5110)) && !defined(__cplusplus) +#elif (LZO_CC_GNUC >= 0x030400ul) && !(LZO_CC_PCC_GNUC) && (LZO_ARCH_AMD64 || LZO_ARCH_I386) +# define __lzo_struct_packed(s) struct s { +# define __lzo_struct_packed_end() } __attribute__((__gcc_struct__,__packed__)); +# define __lzo_struct_packed_ma_end() } __lzo_may_alias __attribute__((__gcc_struct__,__packed__)); +#elif (LZO_CC_ARMCC || LZO_CC_CLANG || LZO_CC_GNUC || LZO_CC_INTELC_GNUC || LZO_CC_LLVM || LZO_CC_PATHSCALE || (LZO_CC_PGI >= 0x0d0a00ul) || (LZO_CC_SUNPROC >= 0x5100)) +# define __lzo_struct_packed(s) struct s { +# define __lzo_struct_packed_end() } __attribute__((__packed__)); +# define __lzo_struct_packed_ma_end() } __lzo_may_alias __attribute__((__packed__)); +#elif (LZO_CC_IBMC >= 700) +# define __lzo_struct_packed(s) __lzo_gnuc_extension__ struct s { +# define __lzo_struct_packed_end() } __attribute__((__packed__)); +# define __lzo_struct_packed_ma_end() } __lzo_may_alias __attribute__((__packed__)); +#elif (LZO_CC_INTELC_MSC) || (LZO_CC_MSC && (_MSC_VER >= 1300)) +# define __lzo_struct_packed(s) __pragma(pack(push,1)) struct s { +# define __lzo_struct_packed_end() } __pragma(pack(pop)); +#elif (LZO_CC_WATCOMC && (__WATCOMC__ >= 900)) +# define __lzo_struct_packed(s) _Packed struct s { +# define __lzo_struct_packed_end() }; +#endif +#endif +#if defined(__lzo_struct_packed) && !defined(__lzo_struct_packed_ma) +# define __lzo_struct_packed_ma(s) __lzo_struct_packed(s) +#endif +#if defined(__lzo_struct_packed_end) && !defined(__lzo_struct_packed_ma_end) +# define __lzo_struct_packed_ma_end() __lzo_struct_packed_end() +#endif +#if !defined(__lzo_byte_struct) +#if defined(__lzo_struct_packed) +# define __lzo_byte_struct(s,n) __lzo_struct_packed(s) unsigned char a[n]; __lzo_struct_packed_end() +# define __lzo_byte_struct_ma(s,n) __lzo_struct_packed_ma(s) unsigned char a[n]; __lzo_struct_packed_ma_end() +#elif (LZO_CC_CILLY || LZO_CC_CLANG || LZO_CC_PGI || (LZO_CC_SUNPROC >= 0x5100)) +# define __lzo_byte_struct(s,n) struct s { unsigned char a[n]; } __attribute__((__packed__)); +# define __lzo_byte_struct_ma(s,n) struct s { unsigned char a[n]; } __lzo_may_alias __attribute__((__packed__)); +#endif +#endif +#if defined(__lzo_byte_struct) && !defined(__lzo_byte_struct_ma) +# define __lzo_byte_struct_ma(s,n) __lzo_byte_struct(s,n) +#endif +#if !defined(__lzo_struct_align16) && (__lzo_HAVE_alignof) +#if (LZO_CC_GNUC && (LZO_CC_GNUC < 0x030000ul)) +#elif (LZO_CC_CLANG && (LZO_CC_CLANG < 0x020800ul)) && defined(__cplusplus) +#elif (LZO_CC_CILLY || LZO_CC_PCC) +#elif (LZO_CC_INTELC_MSC) || (LZO_CC_MSC && (_MSC_VER >= 1300)) +# define __lzo_struct_align16(s) struct __declspec(align(16)) s { +# define __lzo_struct_align16_end() }; +# define __lzo_struct_align32(s) struct __declspec(align(32)) s { +# define __lzo_struct_align32_end() }; +# define __lzo_struct_align64(s) struct __declspec(align(64)) s { +# define __lzo_struct_align64_end() }; +#elif (LZO_CC_ARMCC || LZO_CC_CLANG || LZO_CC_GNUC || (LZO_CC_IBMC >= 700) || LZO_CC_INTELC_GNUC || LZO_CC_LLVM || LZO_CC_PATHSCALE) +# define __lzo_struct_align16(s) struct s { +# define __lzo_struct_align16_end() } __attribute__((__aligned__(16))); +# define __lzo_struct_align32(s) struct s { +# define __lzo_struct_align32_end() } __attribute__((__aligned__(32))); +# define __lzo_struct_align64(s) struct s { +# define __lzo_struct_align64_end() } __attribute__((__aligned__(64))); +#endif +#endif +#if !defined(__lzo_union_um) +#if (LZO_CC_CLANG && (LZO_CC_CLANG < 0x020800ul)) && defined(__cplusplus) +#elif (LZO_CC_GNUC && (LZO_CC_GNUC < 0x020700ul)) +#elif (LZO_CC_GNUC && (LZO_CC_GNUC < 0x020800ul)) && defined(__cplusplus) +#elif (LZO_CC_INTELC_GNUC && (__INTEL_COMPILER < 810)) +#elif (LZO_CC_PCC && (LZO_CC_PCC < 0x010100ul)) +#elif (LZO_CC_SUNPROC && (LZO_CC_SUNPROC < 0x5110)) && !defined(__cplusplus) +#elif (LZO_CC_ARMCC || LZO_CC_CLANG || LZO_CC_GNUC || LZO_CC_INTELC_GNUC || LZO_CC_LLVM || LZO_CC_PATHSCALE || (LZO_CC_PGI >= 0x0d0a00ul) || (LZO_CC_SUNPROC >= 0x5100)) +# define __lzo_union_am(s) union s { +# define __lzo_union_am_end() } __lzo_may_alias; +# define __lzo_union_um(s) union s { +# define __lzo_union_um_end() } __lzo_may_alias __attribute__((__packed__)); +#elif (LZO_CC_IBMC >= 700) +# define __lzo_union_am(s) __lzo_gnuc_extension__ union s { +# define __lzo_union_am_end() } __lzo_may_alias; +# define __lzo_union_um(s) __lzo_gnuc_extension__ union s { +# define __lzo_union_um_end() } __lzo_may_alias __attribute__((__packed__)); +#elif (LZO_CC_INTELC_MSC) || (LZO_CC_MSC && (_MSC_VER >= 1300)) +# define __lzo_union_um(s) __pragma(pack(push,1)) union s { +# define __lzo_union_um_end() } __pragma(pack(pop)); +#elif (LZO_CC_WATCOMC && (__WATCOMC__ >= 900)) +# define __lzo_union_um(s) _Packed union s { +# define __lzo_union_um_end() }; +#endif +#endif +#if !defined(__lzo_union_am) +# define __lzo_union_am(s) union s { +# define __lzo_union_am_end() }; +#endif +#if !defined(__lzo_constructor) +#if (LZO_CC_GNUC >= 0x030400ul) +# define __lzo_constructor __attribute__((__constructor__,__used__)) +#elif (LZO_CC_GNUC >= 0x020700ul) +# define __lzo_constructor __attribute__((__constructor__)) +#elif (LZO_CC_INTELC_GNUC && (__INTEL_COMPILER >= 800)) +# define __lzo_constructor __attribute__((__constructor__,__used__)) +#elif (LZO_CC_ARMCC_GNUC || LZO_CC_CLANG || LZO_CC_LLVM || LZO_CC_PATHSCALE) +# define __lzo_constructor __attribute__((__constructor__)) +#endif +#endif +#if defined(__lzo_constructor) +# ifndef __lzo_HAVE_constructor +# define __lzo_HAVE_constructor 1 +# endif +#endif +#if !defined(__lzo_destructor) +#if (LZO_CC_GNUC >= 0x030400ul) +# define __lzo_destructor __attribute__((__destructor__,__used__)) +#elif (LZO_CC_GNUC >= 0x020700ul) +# define __lzo_destructor __attribute__((__destructor__)) +#elif (LZO_CC_INTELC_GNUC && (__INTEL_COMPILER >= 800)) +# define __lzo_destructor __attribute__((__destructor__,__used__)) +#elif (LZO_CC_ARMCC_GNUC || LZO_CC_CLANG || LZO_CC_LLVM || LZO_CC_PATHSCALE) +# define __lzo_destructor __attribute__((__destructor__)) +#endif +#endif +#if defined(__lzo_destructor) +# ifndef __lzo_HAVE_destructor +# define __lzo_HAVE_destructor 1 +# endif +#endif +#if (__lzo_HAVE_destructor) && !(__lzo_HAVE_constructor) +# error "unexpected configuration - check your compiler defines" +#endif +#if !defined(__lzo_likely) && !defined(__lzo_unlikely) +#if (LZO_CC_GNUC >= 0x030200ul) +# define __lzo_likely(e) (__builtin_expect(!!(e),1)) +# define __lzo_unlikely(e) (__builtin_expect(!!(e),0)) +#elif (LZO_CC_IBMC >= 1010) +# define __lzo_likely(e) (__builtin_expect(!!(e),1)) +# define __lzo_unlikely(e) (__builtin_expect(!!(e),0)) +#elif (LZO_CC_INTELC && (__INTEL_COMPILER >= 800)) +# define __lzo_likely(e) (__builtin_expect(!!(e),1)) +# define __lzo_unlikely(e) (__builtin_expect(!!(e),0)) +#elif (LZO_CC_CLANG && LZO_CC_CLANG_C2) +#elif (LZO_CC_ARMCC_GNUC || LZO_CC_CLANG || LZO_CC_LLVM || LZO_CC_PATHSCALE) +# define __lzo_likely(e) (__builtin_expect(!!(e),1)) +# define __lzo_unlikely(e) (__builtin_expect(!!(e),0)) +#endif +#endif +#if defined(__lzo_likely) +# ifndef __lzo_HAVE_likely +# define __lzo_HAVE_likely 1 +# endif +#else +# define __lzo_likely(e) (e) +#endif +#if defined(__lzo_very_likely) +# ifndef __lzo_HAVE_very_likely +# define __lzo_HAVE_very_likely 1 +# endif +#else +# define __lzo_very_likely(e) __lzo_likely(e) +#endif +#if defined(__lzo_unlikely) +# ifndef __lzo_HAVE_unlikely +# define __lzo_HAVE_unlikely 1 +# endif +#else +# define __lzo_unlikely(e) (e) +#endif +#if defined(__lzo_very_unlikely) +# ifndef __lzo_HAVE_very_unlikely +# define __lzo_HAVE_very_unlikely 1 +# endif +#else +# define __lzo_very_unlikely(e) __lzo_unlikely(e) +#endif +#if !defined(__lzo_loop_forever) +# if (LZO_CC_IBMC) +# define __lzo_loop_forever() LZO_BLOCK_BEGIN for (;;) { ; } LZO_BLOCK_END +# else +# define __lzo_loop_forever() do { ; } while __lzo_cte(1) +# endif +#endif +#if !defined(__lzo_unreachable) +#if (LZO_CC_CLANG && (LZO_CC_CLANG >= 0x020800ul)) && lzo_has_builtin(__builtin_unreachable) +# define __lzo_unreachable() __builtin_unreachable(); +#elif (LZO_CC_GNUC >= 0x040500ul) +# define __lzo_unreachable() __builtin_unreachable(); +#elif (LZO_CC_INTELC_GNUC && (__INTEL_COMPILER >= 1300)) && 1 +# define __lzo_unreachable() __builtin_unreachable(); +#endif +#endif +#if defined(__lzo_unreachable) +# ifndef __lzo_HAVE_unreachable +# define __lzo_HAVE_unreachable 1 +# endif +#else +# if 0 +# define __lzo_unreachable() ((void)0); +# else +# define __lzo_unreachable() __lzo_loop_forever(); +# endif +#endif +#if !defined(lzo_unused_funcs_impl) +# if 1 && (LZO_CC_ARMCC_GNUC || LZO_CC_CLANG || (LZO_CC_GNUC >= 0x020700ul) || LZO_CC_INTELC_GNUC || LZO_CC_LLVM || LZO_CC_PATHSCALE || LZO_CC_PGI) +# define lzo_unused_funcs_impl(r,f) static r __attribute__((__unused__)) f +# elif 1 && (LZO_CC_BORLANDC || LZO_CC_GNUC) +# define lzo_unused_funcs_impl(r,f) static r f +# else +# define lzo_unused_funcs_impl(r,f) __lzo_static_forceinline r f +# endif +#endif +#ifndef __LZO_CTA_NAME +#if (LZO_CFG_USE_COUNTER) +# define __LZO_CTA_NAME(a) LZO_PP_ECONCAT2(a,__COUNTER__) +#else +# define __LZO_CTA_NAME(a) LZO_PP_ECONCAT2(a,__LINE__) +#endif +#endif +#if !defined(LZO_COMPILE_TIME_ASSERT_HEADER) +# if (LZO_CC_AZTECC || LZO_CC_ZORTECHC) +# define LZO_COMPILE_TIME_ASSERT_HEADER(e) LZO_EXTERN_C_BEGIN extern int __LZO_CTA_NAME(lzo_cta__)[1-!(e)]; LZO_EXTERN_C_END +# elif (LZO_CC_DMC || LZO_CC_SYMANTECC) +# define LZO_COMPILE_TIME_ASSERT_HEADER(e) LZO_EXTERN_C_BEGIN extern int __LZO_CTA_NAME(lzo_cta__)[1u-2*!(e)]; LZO_EXTERN_C_END +# elif (LZO_CC_TURBOC && (__TURBOC__ == 0x0295)) +# define LZO_COMPILE_TIME_ASSERT_HEADER(e) LZO_EXTERN_C_BEGIN extern int __LZO_CTA_NAME(lzo_cta__)[1-!(e)]; LZO_EXTERN_C_END +# elif (LZO_CC_CLANG && (LZO_CC_CLANG < 0x020900ul)) && defined(__cplusplus) +# define LZO_COMPILE_TIME_ASSERT_HEADER(e) LZO_EXTERN_C_BEGIN int __LZO_CTA_NAME(lzo_cta_f__)(int [1-2*!(e)]); LZO_EXTERN_C_END +# elif (LZO_CC_GNUC) && defined(__CHECKER__) && defined(__SPARSE_CHECKER__) +# define LZO_COMPILE_TIME_ASSERT_HEADER(e) LZO_EXTERN_C_BEGIN enum {__LZO_CTA_NAME(lzo_cta_e__)=1/!!(e)} __attribute__((__unused__)); LZO_EXTERN_C_END +# else +# define LZO_COMPILE_TIME_ASSERT_HEADER(e) LZO_EXTERN_C_BEGIN extern int __LZO_CTA_NAME(lzo_cta__)[1-2*!(e)]; LZO_EXTERN_C_END +# endif +#endif +#if !defined(LZO_COMPILE_TIME_ASSERT) +# if (LZO_CC_AZTECC) +# define LZO_COMPILE_TIME_ASSERT(e) {typedef int __LZO_CTA_NAME(lzo_cta_t__)[1-!(e)];} +# elif (LZO_CC_CLANG && (LZO_CC_CLANG >= 0x030000ul)) +# define LZO_COMPILE_TIME_ASSERT(e) {typedef int __LZO_CTA_NAME(lzo_cta_t__)[1-2*!(e)] __attribute__((__unused__));} +# elif (LZO_CC_DMC || LZO_CC_PACIFICC || LZO_CC_SYMANTECC || LZO_CC_ZORTECHC) +# define LZO_COMPILE_TIME_ASSERT(e) switch(0) case 1:case !(e):break; +# elif (LZO_CC_GNUC) && defined(__CHECKER__) && defined(__SPARSE_CHECKER__) +# define LZO_COMPILE_TIME_ASSERT(e) {(void) (0/!!(e));} +# elif (LZO_CC_GNUC >= 0x040700ul) && (LZO_CFG_USE_COUNTER) && defined(__cplusplus) +# define LZO_COMPILE_TIME_ASSERT(e) {enum {__LZO_CTA_NAME(lzo_cta_e__)=1/!!(e)} __attribute__((__unused__));} +# elif (LZO_CC_GNUC >= 0x040700ul) +# define LZO_COMPILE_TIME_ASSERT(e) {typedef int __LZO_CTA_NAME(lzo_cta_t__)[1-2*!(e)] __attribute__((__unused__));} +# elif (LZO_CC_MSC && (_MSC_VER < 900)) +# define LZO_COMPILE_TIME_ASSERT(e) switch(0) case 1:case !(e):break; +# elif (LZO_CC_TURBOC && (__TURBOC__ == 0x0295)) +# define LZO_COMPILE_TIME_ASSERT(e) switch(0) case 1:case !(e):break; +# else +# define LZO_COMPILE_TIME_ASSERT(e) {typedef int __LZO_CTA_NAME(lzo_cta_t__)[1-2*!(e)];} +# endif +#endif +#if (LZO_LANG_ASSEMBLER) +# undef LZO_COMPILE_TIME_ASSERT_HEADER +# define LZO_COMPILE_TIME_ASSERT_HEADER(e) /*empty*/ +#else +LZO_COMPILE_TIME_ASSERT_HEADER(1 == 1) +#if defined(__cplusplus) +extern "C" { LZO_COMPILE_TIME_ASSERT_HEADER(2 == 2) } +#endif +LZO_COMPILE_TIME_ASSERT_HEADER(3 == 3) +#endif +#if (LZO_ARCH_I086 || LZO_ARCH_I386) && (LZO_OS_DOS16 || LZO_OS_DOS32 || LZO_OS_OS2 || LZO_OS_OS216 || LZO_OS_WIN16 || LZO_OS_WIN32 || LZO_OS_WIN64) +# if (LZO_CC_GNUC || LZO_CC_HIGHC || LZO_CC_NDPC || LZO_CC_PACIFICC) +# elif (LZO_CC_DMC || LZO_CC_SYMANTECC || LZO_CC_ZORTECHC) +# define __lzo_cdecl __cdecl +# define __lzo_cdecl_atexit /*empty*/ +# define __lzo_cdecl_main __cdecl +# if (LZO_OS_OS2 && (LZO_CC_DMC || LZO_CC_SYMANTECC)) +# define __lzo_cdecl_qsort __pascal +# elif (LZO_OS_OS2 && (LZO_CC_ZORTECHC)) +# define __lzo_cdecl_qsort _stdcall +# else +# define __lzo_cdecl_qsort __cdecl +# endif +# elif (LZO_CC_WATCOMC) +# define __lzo_cdecl __cdecl +# else +# define __lzo_cdecl __cdecl +# define __lzo_cdecl_atexit __cdecl +# define __lzo_cdecl_main __cdecl +# define __lzo_cdecl_qsort __cdecl +# endif +# if (LZO_CC_GNUC || LZO_CC_HIGHC || LZO_CC_NDPC || LZO_CC_PACIFICC || LZO_CC_WATCOMC) +# elif (LZO_OS_OS2 && (LZO_CC_DMC || LZO_CC_SYMANTECC)) +# define __lzo_cdecl_sighandler __pascal +# elif (LZO_OS_OS2 && (LZO_CC_ZORTECHC)) +# define __lzo_cdecl_sighandler _stdcall +# elif (LZO_CC_MSC && (_MSC_VER >= 1400)) && defined(_M_CEE_PURE) +# define __lzo_cdecl_sighandler __clrcall +# elif (LZO_CC_MSC && (_MSC_VER >= 600 && _MSC_VER < 700)) +# if defined(_DLL) +# define __lzo_cdecl_sighandler _far _cdecl _loadds +# elif defined(_MT) +# define __lzo_cdecl_sighandler _far _cdecl +# else +# define __lzo_cdecl_sighandler _cdecl +# endif +# else +# define __lzo_cdecl_sighandler __cdecl +# endif +#elif (LZO_ARCH_I386) && (LZO_CC_WATCOMC) +# define __lzo_cdecl __cdecl +#elif (LZO_ARCH_M68K && LZO_OS_TOS && (LZO_CC_PUREC || LZO_CC_TURBOC)) +# define __lzo_cdecl cdecl +#endif +#if !defined(__lzo_cdecl) +# define __lzo_cdecl /*empty*/ +#endif +#if !defined(__lzo_cdecl_atexit) +# define __lzo_cdecl_atexit /*empty*/ +#endif +#if !defined(__lzo_cdecl_main) +# define __lzo_cdecl_main /*empty*/ +#endif +#if !defined(__lzo_cdecl_qsort) +# define __lzo_cdecl_qsort /*empty*/ +#endif +#if !defined(__lzo_cdecl_sighandler) +# define __lzo_cdecl_sighandler /*empty*/ +#endif +#if !defined(__lzo_cdecl_va) +# define __lzo_cdecl_va __lzo_cdecl +#endif +#if !(LZO_CFG_NO_WINDOWS_H) +#if !defined(LZO_HAVE_WINDOWS_H) +#if (LZO_OS_CYGWIN || (LZO_OS_EMX && defined(__RSXNT__)) || LZO_OS_WIN32 || LZO_OS_WIN64) +# if (LZO_CC_WATCOMC && (__WATCOMC__ < 1000)) +# elif ((LZO_OS_WIN32 && defined(__PW32__)) && (LZO_CC_GNUC && (LZO_CC_GNUC < 0x030000ul))) +# elif ((LZO_OS_CYGWIN || defined(__MINGW32__)) && (LZO_CC_GNUC && (LZO_CC_GNUC < 0x025f00ul))) +# else +# define LZO_HAVE_WINDOWS_H 1 +# endif +#endif +#endif +#endif +#define LZO_SIZEOF_CHAR 1 +#ifndef LZO_SIZEOF_SHORT +#if defined(SIZEOF_SHORT) +# define LZO_SIZEOF_SHORT (SIZEOF_SHORT) +#elif defined(__SIZEOF_SHORT__) +# define LZO_SIZEOF_SHORT (__SIZEOF_SHORT__) +#endif +#endif +#ifndef LZO_SIZEOF_INT +#if defined(SIZEOF_INT) +# define LZO_SIZEOF_INT (SIZEOF_INT) +#elif defined(__SIZEOF_INT__) +# define LZO_SIZEOF_INT (__SIZEOF_INT__) +#endif +#endif +#ifndef LZO_SIZEOF_LONG +#if defined(SIZEOF_LONG) +# define LZO_SIZEOF_LONG (SIZEOF_LONG) +#elif defined(__SIZEOF_LONG__) +# define LZO_SIZEOF_LONG (__SIZEOF_LONG__) +#endif +#endif +#ifndef LZO_SIZEOF_LONG_LONG +#if defined(SIZEOF_LONG_LONG) +# define LZO_SIZEOF_LONG_LONG (SIZEOF_LONG_LONG) +#elif defined(__SIZEOF_LONG_LONG__) +# define LZO_SIZEOF_LONG_LONG (__SIZEOF_LONG_LONG__) +#endif +#endif +#ifndef LZO_SIZEOF___INT16 +#if defined(SIZEOF___INT16) +# define LZO_SIZEOF___INT16 (SIZEOF___INT16) +#endif +#endif +#ifndef LZO_SIZEOF___INT32 +#if defined(SIZEOF___INT32) +# define LZO_SIZEOF___INT32 (SIZEOF___INT32) +#endif +#endif +#ifndef LZO_SIZEOF___INT64 +#if defined(SIZEOF___INT64) +# define LZO_SIZEOF___INT64 (SIZEOF___INT64) +#endif +#endif +#ifndef LZO_SIZEOF_VOID_P +#if defined(SIZEOF_VOID_P) +# define LZO_SIZEOF_VOID_P (SIZEOF_VOID_P) +#elif defined(__SIZEOF_POINTER__) +# define LZO_SIZEOF_VOID_P (__SIZEOF_POINTER__) +#endif +#endif +#ifndef LZO_SIZEOF_SIZE_T +#if defined(SIZEOF_SIZE_T) +# define LZO_SIZEOF_SIZE_T (SIZEOF_SIZE_T) +#elif defined(__SIZEOF_SIZE_T__) +# define LZO_SIZEOF_SIZE_T (__SIZEOF_SIZE_T__) +#endif +#endif +#ifndef LZO_SIZEOF_PTRDIFF_T +#if defined(SIZEOF_PTRDIFF_T) +# define LZO_SIZEOF_PTRDIFF_T (SIZEOF_PTRDIFF_T) +#elif defined(__SIZEOF_PTRDIFF_T__) +# define LZO_SIZEOF_PTRDIFF_T (__SIZEOF_PTRDIFF_T__) +#endif +#endif +#define __LZO_LSR(x,b) (((x)+0ul) >> (b)) +#if !defined(LZO_SIZEOF_SHORT) +# if (LZO_ARCH_CRAY_PVP) +# define LZO_SIZEOF_SHORT 8 +# elif (USHRT_MAX == LZO_0xffffL) +# define LZO_SIZEOF_SHORT 2 +# elif (__LZO_LSR(USHRT_MAX,7) == 1) +# define LZO_SIZEOF_SHORT 1 +# elif (__LZO_LSR(USHRT_MAX,15) == 1) +# define LZO_SIZEOF_SHORT 2 +# elif (__LZO_LSR(USHRT_MAX,31) == 1) +# define LZO_SIZEOF_SHORT 4 +# elif (__LZO_LSR(USHRT_MAX,63) == 1) +# define LZO_SIZEOF_SHORT 8 +# elif (__LZO_LSR(USHRT_MAX,127) == 1) +# define LZO_SIZEOF_SHORT 16 +# else +# error "LZO_SIZEOF_SHORT" +# endif +#endif +LZO_COMPILE_TIME_ASSERT_HEADER(LZO_SIZEOF_SHORT == sizeof(short)) +#if !defined(LZO_SIZEOF_INT) +# if (LZO_ARCH_CRAY_PVP) +# define LZO_SIZEOF_INT 8 +# elif (UINT_MAX == LZO_0xffffL) +# define LZO_SIZEOF_INT 2 +# elif (UINT_MAX == LZO_0xffffffffL) +# define LZO_SIZEOF_INT 4 +# elif (__LZO_LSR(UINT_MAX,7) == 1) +# define LZO_SIZEOF_INT 1 +# elif (__LZO_LSR(UINT_MAX,15) == 1) +# define LZO_SIZEOF_INT 2 +# elif (__LZO_LSR(UINT_MAX,31) == 1) +# define LZO_SIZEOF_INT 4 +# elif (__LZO_LSR(UINT_MAX,63) == 1) +# define LZO_SIZEOF_INT 8 +# elif (__LZO_LSR(UINT_MAX,127) == 1) +# define LZO_SIZEOF_INT 16 +# else +# error "LZO_SIZEOF_INT" +# endif +#endif +LZO_COMPILE_TIME_ASSERT_HEADER(LZO_SIZEOF_INT == sizeof(int)) +#if !defined(LZO_SIZEOF_LONG) +# if (ULONG_MAX == LZO_0xffffffffL) +# define LZO_SIZEOF_LONG 4 +# elif (__LZO_LSR(ULONG_MAX,7) == 1) +# define LZO_SIZEOF_LONG 1 +# elif (__LZO_LSR(ULONG_MAX,15) == 1) +# define LZO_SIZEOF_LONG 2 +# elif (__LZO_LSR(ULONG_MAX,31) == 1) +# define LZO_SIZEOF_LONG 4 +# elif (__LZO_LSR(ULONG_MAX,39) == 1) +# define LZO_SIZEOF_LONG 5 +# elif (__LZO_LSR(ULONG_MAX,63) == 1) +# define LZO_SIZEOF_LONG 8 +# elif (__LZO_LSR(ULONG_MAX,127) == 1) +# define LZO_SIZEOF_LONG 16 +# else +# error "LZO_SIZEOF_LONG" +# endif +#endif +LZO_COMPILE_TIME_ASSERT_HEADER(LZO_SIZEOF_LONG == sizeof(long)) +#if !defined(LZO_SIZEOF_LONG_LONG) && !defined(LZO_SIZEOF___INT64) +#if (LZO_SIZEOF_LONG > 0 && LZO_SIZEOF_LONG < 8) +# if defined(__LONG_MAX__) && defined(__LONG_LONG_MAX__) +# if (LZO_CC_GNUC >= 0x030300ul) +# if ((__LONG_MAX__-0) == (__LONG_LONG_MAX__-0)) +# define LZO_SIZEOF_LONG_LONG LZO_SIZEOF_LONG +# elif (__LZO_LSR(__LONG_LONG_MAX__,30) == 1) +# define LZO_SIZEOF_LONG_LONG 4 +# endif +# endif +# endif +#endif +#endif +#if !defined(LZO_SIZEOF_LONG_LONG) && !defined(LZO_SIZEOF___INT64) +#if (LZO_SIZEOF_LONG > 0 && LZO_SIZEOF_LONG < 8) +#if (LZO_ARCH_I086 && LZO_CC_DMC) +#elif (LZO_CC_CILLY) && defined(__GNUC__) +# define LZO_SIZEOF_LONG_LONG 8 +#elif (LZO_CC_ARMCC_GNUC || LZO_CC_CLANG || LZO_CC_GNUC || LZO_CC_LLVM || LZO_CC_PATHSCALE) +# define LZO_SIZEOF_LONG_LONG 8 +#elif ((LZO_OS_WIN32 || LZO_OS_WIN64 || defined(_WIN32)) && LZO_CC_MSC && (_MSC_VER >= 1400)) +# define LZO_SIZEOF_LONG_LONG 8 +#elif (LZO_OS_WIN64 || defined(_WIN64)) +# define LZO_SIZEOF___INT64 8 +#elif (LZO_ARCH_I386 && (LZO_CC_DMC)) +# define LZO_SIZEOF_LONG_LONG 8 +#elif (LZO_ARCH_I386 && (LZO_CC_SYMANTECC && (__SC__ >= 0x700))) +# define LZO_SIZEOF_LONG_LONG 8 +#elif (LZO_ARCH_I386 && (LZO_CC_INTELC && defined(__linux__))) +# define LZO_SIZEOF_LONG_LONG 8 +#elif (LZO_ARCH_I386 && (LZO_CC_MWERKS || LZO_CC_PELLESC || LZO_CC_PGI || LZO_CC_SUNPROC)) +# define LZO_SIZEOF_LONG_LONG 8 +#elif (LZO_ARCH_I386 && (LZO_CC_INTELC || LZO_CC_MSC)) +# define LZO_SIZEOF___INT64 8 +#elif ((LZO_OS_WIN32 || defined(_WIN32)) && (LZO_CC_MSC)) +# define LZO_SIZEOF___INT64 8 +#elif (LZO_ARCH_I386 && (LZO_CC_BORLANDC && (__BORLANDC__ >= 0x0520))) +# define LZO_SIZEOF___INT64 8 +#elif (LZO_ARCH_I386 && (LZO_CC_WATCOMC && (__WATCOMC__ >= 1100))) +# define LZO_SIZEOF___INT64 8 +#elif (LZO_CC_GHS && defined(__LLONG_BIT) && ((__LLONG_BIT-0) == 64)) +# define LZO_SIZEOF_LONG_LONG 8 +#elif (LZO_CC_WATCOMC && defined(_INTEGRAL_MAX_BITS) && ((_INTEGRAL_MAX_BITS-0) == 64)) +# define LZO_SIZEOF___INT64 8 +#elif (LZO_OS_OS400 || defined(__OS400__)) && defined(__LLP64_IFC__) +# define LZO_SIZEOF_LONG_LONG 8 +#elif (defined(__vms) || defined(__VMS)) && ((__INITIAL_POINTER_SIZE-0) == 64) +# define LZO_SIZEOF_LONG_LONG 8 +#elif (LZO_CC_SDCC) && (LZO_SIZEOF_INT == 2) +#elif 1 && defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L) +# define LZO_SIZEOF_LONG_LONG 8 +#endif +#endif +#endif +#if defined(__cplusplus) && (LZO_CC_GNUC) +# if (LZO_CC_GNUC < 0x020800ul) +# undef LZO_SIZEOF_LONG_LONG +# endif +#endif +#if (LZO_CFG_NO_LONG_LONG) +# undef LZO_SIZEOF_LONG_LONG +#elif defined(__NO_LONG_LONG) +# undef LZO_SIZEOF_LONG_LONG +#elif defined(_NO_LONGLONG) +# undef LZO_SIZEOF_LONG_LONG +#endif +#if !defined(LZO_WORDSIZE) +#if (LZO_ARCH_ALPHA) +# define LZO_WORDSIZE 8 +#elif (LZO_ARCH_AMD64) +# define LZO_WORDSIZE 8 +#elif (LZO_ARCH_ARM64) +# define LZO_WORDSIZE 8 +#elif (LZO_ARCH_AVR) +# define LZO_WORDSIZE 1 +#elif (LZO_ARCH_H8300) +# if defined(__H8300H__) || defined(__H8300S__) || defined(__H8300SX__) +# define LZO_WORDSIZE 4 +# else +# define LZO_WORDSIZE 2 +# endif +#elif (LZO_ARCH_I086) +# define LZO_WORDSIZE 2 +#elif (LZO_ARCH_IA64) +# define LZO_WORDSIZE 8 +#elif (LZO_ARCH_M16C) +# define LZO_WORDSIZE 2 +#elif (LZO_ARCH_SPU) +# define LZO_WORDSIZE 4 +#elif (LZO_ARCH_Z80) +# define LZO_WORDSIZE 1 +#elif (LZO_SIZEOF_LONG == 8) && ((defined(__mips__) && defined(__R5900__)) || defined(__MIPS_PSX2__)) +# define LZO_WORDSIZE 8 +#elif (LZO_OS_OS400 || defined(__OS400__)) +# define LZO_WORDSIZE 8 +#elif (defined(__vms) || defined(__VMS)) && (__INITIAL_POINTER_SIZE+0 == 64) +# define LZO_WORDSIZE 8 +#endif +#endif +#if !defined(LZO_SIZEOF_VOID_P) +#if defined(__ILP32__) || defined(__ILP32) || defined(_ILP32) +LZO_COMPILE_TIME_ASSERT_HEADER(sizeof(int) == 4) +LZO_COMPILE_TIME_ASSERT_HEADER(sizeof(long) == 4) +# define LZO_SIZEOF_VOID_P 4 +#elif defined(__ILP64__) || defined(__ILP64) || defined(_ILP64) +LZO_COMPILE_TIME_ASSERT_HEADER(sizeof(int) == 8) +LZO_COMPILE_TIME_ASSERT_HEADER(sizeof(long) == 8) +# define LZO_SIZEOF_VOID_P 8 +#elif defined(__LLP64__) || defined(__LLP64) || defined(_LLP64) || defined(_WIN64) +LZO_COMPILE_TIME_ASSERT_HEADER(sizeof(long) == 4) +# define LZO_SIZEOF_VOID_P 8 +#elif defined(__LP64__) || defined(__LP64) || defined(_LP64) +LZO_COMPILE_TIME_ASSERT_HEADER(sizeof(long) == 8) +# define LZO_SIZEOF_VOID_P 8 +#elif (LZO_ARCH_AVR) +# define LZO_SIZEOF_VOID_P 2 +#elif (LZO_ARCH_C166 || LZO_ARCH_MCS51 || LZO_ARCH_MCS251 || LZO_ARCH_MSP430) +# define LZO_SIZEOF_VOID_P 2 +#elif (LZO_ARCH_H8300) +# if defined(__H8300H__) || defined(__H8300S__) || defined(__H8300SX__) + LZO_COMPILE_TIME_ASSERT_HEADER(LZO_WORDSIZE == 4) +# if defined(__NORMAL_MODE__) +# define LZO_SIZEOF_VOID_P 2 +# else +# define LZO_SIZEOF_VOID_P 4 +# endif +# else + LZO_COMPILE_TIME_ASSERT_HEADER(LZO_WORDSIZE == 2) +# define LZO_SIZEOF_VOID_P 2 +# endif +# if (LZO_CC_GNUC && (LZO_CC_GNUC < 0x040000ul)) && (LZO_SIZEOF_INT == 4) +# define LZO_SIZEOF_SIZE_T LZO_SIZEOF_INT +# define LZO_SIZEOF_PTRDIFF_T LZO_SIZEOF_INT +# endif +#elif (LZO_ARCH_I086) +# if (LZO_MM_TINY || LZO_MM_SMALL || LZO_MM_MEDIUM) +# define LZO_SIZEOF_VOID_P 2 +# elif (LZO_MM_COMPACT || LZO_MM_LARGE || LZO_MM_HUGE) +# define LZO_SIZEOF_VOID_P 4 +# else +# error "invalid LZO_ARCH_I086 memory model" +# endif +#elif (LZO_ARCH_M16C) +# if defined(__m32c_cpu__) || defined(__m32cm_cpu__) +# define LZO_SIZEOF_VOID_P 4 +# else +# define LZO_SIZEOF_VOID_P 2 +# endif +#elif (LZO_ARCH_SPU) +# define LZO_SIZEOF_VOID_P 4 +#elif (LZO_ARCH_Z80) +# define LZO_SIZEOF_VOID_P 2 +#elif (LZO_SIZEOF_LONG == 8) && ((defined(__mips__) && defined(__R5900__)) || defined(__MIPS_PSX2__)) +# define LZO_SIZEOF_VOID_P 4 +#elif (LZO_OS_OS400 || defined(__OS400__)) +# if defined(__LLP64_IFC__) +# define LZO_SIZEOF_VOID_P 8 +# define LZO_SIZEOF_SIZE_T LZO_SIZEOF_LONG +# define LZO_SIZEOF_PTRDIFF_T LZO_SIZEOF_LONG +# else +# define LZO_SIZEOF_VOID_P 16 +# define LZO_SIZEOF_SIZE_T LZO_SIZEOF_LONG +# define LZO_SIZEOF_PTRDIFF_T LZO_SIZEOF_LONG +# endif +#elif (defined(__vms) || defined(__VMS)) && (__INITIAL_POINTER_SIZE+0 == 64) +# define LZO_SIZEOF_VOID_P 8 +# define LZO_SIZEOF_SIZE_T LZO_SIZEOF_LONG +# define LZO_SIZEOF_PTRDIFF_T LZO_SIZEOF_LONG +#endif +#endif +#if !defined(LZO_SIZEOF_VOID_P) +# define LZO_SIZEOF_VOID_P LZO_SIZEOF_LONG +#endif +LZO_COMPILE_TIME_ASSERT_HEADER(LZO_SIZEOF_VOID_P == sizeof(void *)) +#if !defined(LZO_SIZEOF_SIZE_T) +#if (LZO_ARCH_I086 || LZO_ARCH_M16C) +# define LZO_SIZEOF_SIZE_T 2 +#endif +#endif +#if !defined(LZO_SIZEOF_SIZE_T) +# define LZO_SIZEOF_SIZE_T LZO_SIZEOF_VOID_P +#endif +#if defined(offsetof) +LZO_COMPILE_TIME_ASSERT_HEADER(LZO_SIZEOF_SIZE_T == sizeof(size_t)) +#endif +#if !defined(LZO_SIZEOF_PTRDIFF_T) +#if (LZO_ARCH_I086) +# if (LZO_MM_TINY || LZO_MM_SMALL || LZO_MM_MEDIUM || LZO_MM_HUGE) +# define LZO_SIZEOF_PTRDIFF_T LZO_SIZEOF_VOID_P +# elif (LZO_MM_COMPACT || LZO_MM_LARGE) +# if (LZO_CC_BORLANDC || LZO_CC_TURBOC) +# define LZO_SIZEOF_PTRDIFF_T 4 +# else +# define LZO_SIZEOF_PTRDIFF_T 2 +# endif +# else +# error "invalid LZO_ARCH_I086 memory model" +# endif +#endif +#endif +#if !defined(LZO_SIZEOF_PTRDIFF_T) +# define LZO_SIZEOF_PTRDIFF_T LZO_SIZEOF_SIZE_T +#endif +#if defined(offsetof) +LZO_COMPILE_TIME_ASSERT_HEADER(LZO_SIZEOF_PTRDIFF_T == sizeof(ptrdiff_t)) +#endif +#if !defined(LZO_WORDSIZE) +# define LZO_WORDSIZE LZO_SIZEOF_VOID_P +#endif +#if (LZO_ABI_NEUTRAL_ENDIAN) +# undef LZO_ABI_BIG_ENDIAN +# undef LZO_ABI_LITTLE_ENDIAN +#elif !(LZO_ABI_BIG_ENDIAN) && !(LZO_ABI_LITTLE_ENDIAN) +#if (LZO_ARCH_ALPHA) && (LZO_ARCH_CRAY_MPP) +# define LZO_ABI_BIG_ENDIAN 1 +#elif (LZO_ARCH_IA64) && (LZO_OS_POSIX_LINUX || LZO_OS_WIN64) +# define LZO_ABI_LITTLE_ENDIAN 1 +#elif (LZO_ARCH_ALPHA || LZO_ARCH_AMD64 || LZO_ARCH_BLACKFIN || LZO_ARCH_CRIS || LZO_ARCH_I086 || LZO_ARCH_I386 || LZO_ARCH_MSP430 || LZO_ARCH_RISCV) +# define LZO_ABI_LITTLE_ENDIAN 1 +#elif (LZO_ARCH_AVR32 || LZO_ARCH_M68K || LZO_ARCH_S390 || LZO_ARCH_SPU) +# define LZO_ABI_BIG_ENDIAN 1 +#elif 1 && defined(__IAR_SYSTEMS_ICC__) && defined(__LITTLE_ENDIAN__) +# if (__LITTLE_ENDIAN__ == 1) +# define LZO_ABI_LITTLE_ENDIAN 1 +# else +# define LZO_ABI_BIG_ENDIAN 1 +# endif +#elif 1 && defined(__BIG_ENDIAN__) && !defined(__LITTLE_ENDIAN__) +# define LZO_ABI_BIG_ENDIAN 1 +#elif 1 && defined(__LITTLE_ENDIAN__) && !defined(__BIG_ENDIAN__) +# define LZO_ABI_LITTLE_ENDIAN 1 +#elif 1 && (LZO_ARCH_ARM) && defined(__ARM_BIG_ENDIAN) && ((__ARM_BIG_ENDIAN)+0) +# define LZO_ABI_BIG_ENDIAN 1 +#elif 1 && (LZO_ARCH_ARM) && defined(__ARMEB__) && !defined(__ARMEL__) +# define LZO_ABI_BIG_ENDIAN 1 +#elif 1 && (LZO_ARCH_ARM) && defined(__ARMEL__) && !defined(__ARMEB__) +# define LZO_ABI_LITTLE_ENDIAN 1 +#elif 1 && (LZO_ARCH_ARM) && defined(_MSC_VER) && defined(_WIN32) +# define LZO_ABI_LITTLE_ENDIAN 1 +#elif 1 && (LZO_ARCH_ARM && LZO_CC_ARMCC_ARMCC) +# if defined(__BIG_ENDIAN) && defined(__LITTLE_ENDIAN) +# error "unexpected configuration - check your compiler defines" +# elif defined(__BIG_ENDIAN) +# define LZO_ABI_BIG_ENDIAN 1 +# else +# define LZO_ABI_LITTLE_ENDIAN 1 +# endif +# define LZO_ABI_LITTLE_ENDIAN 1 +#elif 1 && (LZO_ARCH_ARM64) && defined(__ARM_BIG_ENDIAN) && ((__ARM_BIG_ENDIAN)+0) +# define LZO_ABI_BIG_ENDIAN 1 +#elif 1 && (LZO_ARCH_ARM64) && defined(__AARCH64EB__) && !defined(__AARCH64EL__) +# define LZO_ABI_BIG_ENDIAN 1 +#elif 1 && (LZO_ARCH_ARM64) && defined(__AARCH64EL__) && !defined(__AARCH64EB__) +# define LZO_ABI_LITTLE_ENDIAN 1 +#elif 1 && (LZO_ARCH_ARM64) && defined(_MSC_VER) && defined(_WIN32) +# define LZO_ABI_LITTLE_ENDIAN 1 +#elif 1 && (LZO_ARCH_MIPS) && defined(__MIPSEB__) && !defined(__MIPSEL__) +# define LZO_ABI_BIG_ENDIAN 1 +#elif 1 && (LZO_ARCH_MIPS) && defined(__MIPSEL__) && !defined(__MIPSEB__) +# define LZO_ABI_LITTLE_ENDIAN 1 +#endif +#endif +#if (LZO_ABI_BIG_ENDIAN) && (LZO_ABI_LITTLE_ENDIAN) +# error "unexpected configuration - check your compiler defines" +#endif +#if (LZO_ABI_BIG_ENDIAN) +# define LZO_INFO_ABI_ENDIAN "be" +#elif (LZO_ABI_LITTLE_ENDIAN) +# define LZO_INFO_ABI_ENDIAN "le" +#elif (LZO_ABI_NEUTRAL_ENDIAN) +# define LZO_INFO_ABI_ENDIAN "neutral" +#endif +#if (LZO_SIZEOF_INT == 1 && LZO_SIZEOF_LONG == 2 && LZO_SIZEOF_VOID_P == 2) +# define LZO_ABI_I8LP16 1 +# define LZO_INFO_ABI_PM "i8lp16" +#elif (LZO_SIZEOF_INT == 2 && LZO_SIZEOF_LONG == 2 && LZO_SIZEOF_VOID_P == 2) +# define LZO_ABI_ILP16 1 +# define LZO_INFO_ABI_PM "ilp16" +#elif (LZO_SIZEOF_INT == 2 && LZO_SIZEOF_LONG == 4 && LZO_SIZEOF_VOID_P == 4) +# define LZO_ABI_LP32 1 +# define LZO_INFO_ABI_PM "lp32" +#elif (LZO_SIZEOF_INT == 4 && LZO_SIZEOF_LONG == 4 && LZO_SIZEOF_VOID_P == 4) +# define LZO_ABI_ILP32 1 +# define LZO_INFO_ABI_PM "ilp32" +#elif (LZO_SIZEOF_INT == 4 && LZO_SIZEOF_LONG == 4 && LZO_SIZEOF_VOID_P == 8 && LZO_SIZEOF_SIZE_T == 8) +# define LZO_ABI_LLP64 1 +# define LZO_INFO_ABI_PM "llp64" +#elif (LZO_SIZEOF_INT == 4 && LZO_SIZEOF_LONG == 8 && LZO_SIZEOF_VOID_P == 8) +# define LZO_ABI_LP64 1 +# define LZO_INFO_ABI_PM "lp64" +#elif (LZO_SIZEOF_INT == 8 && LZO_SIZEOF_LONG == 8 && LZO_SIZEOF_VOID_P == 8) +# define LZO_ABI_ILP64 1 +# define LZO_INFO_ABI_PM "ilp64" +#elif (LZO_SIZEOF_INT == 4 && LZO_SIZEOF_LONG == 8 && LZO_SIZEOF_VOID_P == 4) +# define LZO_ABI_IP32L64 1 +# define LZO_INFO_ABI_PM "ip32l64" +#endif +#if (LZO_SIZEOF_INT == 4 && LZO_SIZEOF_VOID_P == 4 && LZO_WORDSIZE == 8) +# define LZO_ABI_IP32W64 1 +# ifndef LZO_INFO_ABI_PM +# define LZO_INFO_ABI_PM "ip32w64" +# endif +#endif +#if 0 +#elif !defined(__LZO_LIBC_OVERRIDE) +#if (LZO_LIBC_NAKED) +# define LZO_INFO_LIBC "naked" +#elif (LZO_LIBC_FREESTANDING) +# define LZO_INFO_LIBC "freestanding" +#elif (LZO_LIBC_MOSTLY_FREESTANDING) +# define LZO_INFO_LIBC "mfreestanding" +#elif (LZO_LIBC_ISOC90) +# define LZO_INFO_LIBC "isoc90" +#elif (LZO_LIBC_ISOC99) +# define LZO_INFO_LIBC "isoc99" +#elif (LZO_CC_ARMCC_ARMCC) && defined(__ARMCLIB_VERSION) +# define LZO_LIBC_ISOC90 1 +# define LZO_INFO_LIBC "isoc90" +#elif defined(__dietlibc__) +# define LZO_LIBC_DIETLIBC 1 +# define LZO_INFO_LIBC "dietlibc" +#elif defined(_NEWLIB_VERSION) +# define LZO_LIBC_NEWLIB 1 +# define LZO_INFO_LIBC "newlib" +#elif defined(__UCLIBC__) && defined(__UCLIBC_MAJOR__) && defined(__UCLIBC_MINOR__) +# if defined(__UCLIBC_SUBLEVEL__) +# define LZO_LIBC_UCLIBC (__UCLIBC_MAJOR__ * 0x10000L + (__UCLIBC_MINOR__-0) * 0x100 + (__UCLIBC_SUBLEVEL__-0)) +# else +# define LZO_LIBC_UCLIBC 0x00090bL +# endif +# define LZO_INFO_LIBC "uc" "libc" +#elif defined(__GLIBC__) && defined(__GLIBC_MINOR__) +# define LZO_LIBC_GLIBC (__GLIBC__ * 0x10000L + (__GLIBC_MINOR__-0) * 0x100) +# define LZO_INFO_LIBC "glibc" +#elif (LZO_CC_MWERKS) && defined(__MSL__) +# define LZO_LIBC_MSL __MSL__ +# define LZO_INFO_LIBC "msl" +#elif 1 && defined(__IAR_SYSTEMS_ICC__) +# define LZO_LIBC_ISOC90 1 +# define LZO_INFO_LIBC "isoc90" +#else +# define LZO_LIBC_DEFAULT 1 +# define LZO_INFO_LIBC "default" +#endif +#endif +#if (LZO_ARCH_I386 && (LZO_OS_DOS32 || LZO_OS_WIN32) && (LZO_CC_DMC || LZO_CC_INTELC || LZO_CC_MSC || LZO_CC_PELLESC)) +# define LZO_ASM_SYNTAX_MSC 1 +#elif (LZO_OS_WIN64 && (LZO_CC_DMC || LZO_CC_INTELC || LZO_CC_MSC || LZO_CC_PELLESC)) +#elif (LZO_ARCH_I386 && LZO_CC_GNUC && (LZO_CC_GNUC == 0x011f00ul)) +#elif (LZO_ARCH_I386 && (LZO_CC_CLANG || LZO_CC_GNUC || LZO_CC_INTELC || LZO_CC_PATHSCALE)) +# define LZO_ASM_SYNTAX_GNUC 1 +#elif (LZO_ARCH_AMD64 && (LZO_CC_CLANG || LZO_CC_GNUC || LZO_CC_INTELC || LZO_CC_PATHSCALE)) +# define LZO_ASM_SYNTAX_GNUC 1 +#elif (LZO_CC_GNUC) +# define LZO_ASM_SYNTAX_GNUC 1 +#endif +#if (LZO_ASM_SYNTAX_GNUC) +#if (LZO_ARCH_I386 && LZO_CC_GNUC && (LZO_CC_GNUC < 0x020000ul)) +# define __LZO_ASM_CLOBBER "ax" +# define __LZO_ASM_CLOBBER_LIST_CC /*empty*/ +# define __LZO_ASM_CLOBBER_LIST_CC_MEMORY /*empty*/ +# define __LZO_ASM_CLOBBER_LIST_EMPTY /*empty*/ +#elif (LZO_CC_INTELC && (__INTEL_COMPILER < 1000)) +# define __LZO_ASM_CLOBBER "memory" +# define __LZO_ASM_CLOBBER_LIST_CC /*empty*/ +# define __LZO_ASM_CLOBBER_LIST_CC_MEMORY : "memory" +# define __LZO_ASM_CLOBBER_LIST_EMPTY /*empty*/ +#else +# define __LZO_ASM_CLOBBER "cc", "memory" +# define __LZO_ASM_CLOBBER_LIST_CC : "cc" +# define __LZO_ASM_CLOBBER_LIST_CC_MEMORY : "cc", "memory" +# define __LZO_ASM_CLOBBER_LIST_EMPTY /*empty*/ +#endif +#endif +#if (LZO_ARCH_ALPHA) +# define LZO_OPT_AVOID_UINT_INDEX 1 +#elif (LZO_ARCH_AMD64) +# define LZO_OPT_AVOID_INT_INDEX 1 +# define LZO_OPT_AVOID_UINT_INDEX 1 +# ifndef LZO_OPT_UNALIGNED16 +# define LZO_OPT_UNALIGNED16 1 +# endif +# ifndef LZO_OPT_UNALIGNED32 +# define LZO_OPT_UNALIGNED32 1 +# endif +# ifndef LZO_OPT_UNALIGNED64 +# define LZO_OPT_UNALIGNED64 1 +# endif +#elif (LZO_ARCH_ARM) +# if defined(__ARM_FEATURE_UNALIGNED) +# if ((__ARM_FEATURE_UNALIGNED)+0) +# ifndef LZO_OPT_UNALIGNED16 +# define LZO_OPT_UNALIGNED16 1 +# endif +# ifndef LZO_OPT_UNALIGNED32 +# define LZO_OPT_UNALIGNED32 1 +# endif +# endif +# elif 1 && (LZO_ARCH_ARM_THUMB2) +# ifndef LZO_OPT_UNALIGNED16 +# define LZO_OPT_UNALIGNED16 1 +# endif +# ifndef LZO_OPT_UNALIGNED32 +# define LZO_OPT_UNALIGNED32 1 +# endif +# elif 1 && defined(__ARM_ARCH) && ((__ARM_ARCH)+0 >= 7) +# ifndef LZO_OPT_UNALIGNED16 +# define LZO_OPT_UNALIGNED16 1 +# endif +# ifndef LZO_OPT_UNALIGNED32 +# define LZO_OPT_UNALIGNED32 1 +# endif +# elif 1 && defined(__TARGET_ARCH_ARM) && ((__TARGET_ARCH_ARM)+0 >= 7) +# ifndef LZO_OPT_UNALIGNED16 +# define LZO_OPT_UNALIGNED16 1 +# endif +# ifndef LZO_OPT_UNALIGNED32 +# define LZO_OPT_UNALIGNED32 1 +# endif +# elif 1 && defined(__TARGET_ARCH_ARM) && ((__TARGET_ARCH_ARM)+0 >= 6) && (defined(__TARGET_PROFILE_A) || defined(__TARGET_PROFILE_R)) +# ifndef LZO_OPT_UNALIGNED16 +# define LZO_OPT_UNALIGNED16 1 +# endif +# ifndef LZO_OPT_UNALIGNED32 +# define LZO_OPT_UNALIGNED32 1 +# endif +# elif 1 && defined(_MSC_VER) && defined(_M_ARM) && ((_M_ARM)+0 >= 7) +# ifndef LZO_OPT_UNALIGNED16 +# define LZO_OPT_UNALIGNED16 1 +# endif +# ifndef LZO_OPT_UNALIGNED32 +# define LZO_OPT_UNALIGNED32 1 +# endif +# endif +#elif (LZO_ARCH_ARM64) +# ifndef LZO_OPT_UNALIGNED16 +# define LZO_OPT_UNALIGNED16 1 +# endif +# ifndef LZO_OPT_UNALIGNED32 +# define LZO_OPT_UNALIGNED32 1 +# endif +# ifndef LZO_OPT_UNALIGNED64 +# define LZO_OPT_UNALIGNED64 1 +# endif +#elif (LZO_ARCH_CRIS) +# ifndef LZO_OPT_UNALIGNED16 +# define LZO_OPT_UNALIGNED16 1 +# endif +# ifndef LZO_OPT_UNALIGNED32 +# define LZO_OPT_UNALIGNED32 1 +# endif +#elif (LZO_ARCH_I386) +# ifndef LZO_OPT_UNALIGNED16 +# define LZO_OPT_UNALIGNED16 1 +# endif +# ifndef LZO_OPT_UNALIGNED32 +# define LZO_OPT_UNALIGNED32 1 +# endif +#elif (LZO_ARCH_IA64) +# define LZO_OPT_AVOID_INT_INDEX 1 +# define LZO_OPT_AVOID_UINT_INDEX 1 +# define LZO_OPT_PREFER_POSTINC 1 +#elif (LZO_ARCH_M68K) +# define LZO_OPT_PREFER_POSTINC 1 +# define LZO_OPT_PREFER_PREDEC 1 +# if defined(__mc68020__) && !defined(__mcoldfire__) +# ifndef LZO_OPT_UNALIGNED16 +# define LZO_OPT_UNALIGNED16 1 +# endif +# ifndef LZO_OPT_UNALIGNED32 +# define LZO_OPT_UNALIGNED32 1 +# endif +# endif +#elif (LZO_ARCH_MIPS) +# define LZO_OPT_AVOID_UINT_INDEX 1 +#elif (LZO_ARCH_POWERPC) +# define LZO_OPT_PREFER_PREINC 1 +# define LZO_OPT_PREFER_PREDEC 1 +# if (LZO_ABI_BIG_ENDIAN) || (LZO_WORDSIZE == 8) +# ifndef LZO_OPT_UNALIGNED16 +# define LZO_OPT_UNALIGNED16 1 +# endif +# ifndef LZO_OPT_UNALIGNED32 +# define LZO_OPT_UNALIGNED32 1 +# endif +# if (LZO_WORDSIZE == 8) +# ifndef LZO_OPT_UNALIGNED64 +# define LZO_OPT_UNALIGNED64 1 +# endif +# endif +# endif +#elif (LZO_ARCH_RISCV) +# define LZO_OPT_AVOID_UINT_INDEX 1 +# ifndef LZO_OPT_UNALIGNED16 +# define LZO_OPT_UNALIGNED16 1 +# endif +# ifndef LZO_OPT_UNALIGNED32 +# define LZO_OPT_UNALIGNED32 1 +# endif +# if (LZO_WORDSIZE == 8) +# ifndef LZO_OPT_UNALIGNED64 +# define LZO_OPT_UNALIGNED64 1 +# endif +# endif +#elif (LZO_ARCH_S390) +# ifndef LZO_OPT_UNALIGNED16 +# define LZO_OPT_UNALIGNED16 1 +# endif +# ifndef LZO_OPT_UNALIGNED32 +# define LZO_OPT_UNALIGNED32 1 +# endif +# if (LZO_WORDSIZE == 8) +# ifndef LZO_OPT_UNALIGNED64 +# define LZO_OPT_UNALIGNED64 1 +# endif +# endif +#elif (LZO_ARCH_SH) +# define LZO_OPT_PREFER_POSTINC 1 +# define LZO_OPT_PREFER_PREDEC 1 +#endif +#ifndef LZO_CFG_NO_INLINE_ASM +#if (LZO_ABI_NEUTRAL_ENDIAN) || (LZO_ARCH_GENERIC) +# define LZO_CFG_NO_INLINE_ASM 1 +#elif (LZO_CC_LLVM) +# define LZO_CFG_NO_INLINE_ASM 1 +#endif +#endif +#if (LZO_CFG_NO_INLINE_ASM) +# undef LZO_ASM_SYNTAX_MSC +# undef LZO_ASM_SYNTAX_GNUC +# undef __LZO_ASM_CLOBBER +# undef __LZO_ASM_CLOBBER_LIST_CC +# undef __LZO_ASM_CLOBBER_LIST_CC_MEMORY +# undef __LZO_ASM_CLOBBER_LIST_EMPTY +#endif +#ifndef LZO_CFG_NO_UNALIGNED +#if (LZO_ABI_NEUTRAL_ENDIAN) || (LZO_ARCH_GENERIC) +# define LZO_CFG_NO_UNALIGNED 1 +#endif +#endif +#if (LZO_CFG_NO_UNALIGNED) +# undef LZO_OPT_UNALIGNED16 +# undef LZO_OPT_UNALIGNED32 +# undef LZO_OPT_UNALIGNED64 +#endif +#if defined(__LZO_INFOSTR_MM) +#elif (LZO_MM_FLAT) && (defined(__LZO_INFOSTR_PM) || defined(LZO_INFO_ABI_PM)) +# define __LZO_INFOSTR_MM "" +#elif defined(LZO_INFO_MM) +# define __LZO_INFOSTR_MM "." LZO_INFO_MM +#else +# define __LZO_INFOSTR_MM "" +#endif +#if defined(__LZO_INFOSTR_PM) +#elif defined(LZO_INFO_ABI_PM) +# define __LZO_INFOSTR_PM "." LZO_INFO_ABI_PM +#else +# define __LZO_INFOSTR_PM "" +#endif +#if defined(__LZO_INFOSTR_ENDIAN) +#elif defined(LZO_INFO_ABI_ENDIAN) +# define __LZO_INFOSTR_ENDIAN "." LZO_INFO_ABI_ENDIAN +#else +# define __LZO_INFOSTR_ENDIAN "" +#endif +#if defined(__LZO_INFOSTR_OSNAME) +#elif defined(LZO_INFO_OS_CONSOLE) +# define __LZO_INFOSTR_OSNAME LZO_INFO_OS "." LZO_INFO_OS_CONSOLE +#elif defined(LZO_INFO_OS_POSIX) +# define __LZO_INFOSTR_OSNAME LZO_INFO_OS "." LZO_INFO_OS_POSIX +#else +# define __LZO_INFOSTR_OSNAME LZO_INFO_OS +#endif +#if defined(__LZO_INFOSTR_LIBC) +#elif defined(LZO_INFO_LIBC) +# define __LZO_INFOSTR_LIBC "." LZO_INFO_LIBC +#else +# define __LZO_INFOSTR_LIBC "" +#endif +#if defined(__LZO_INFOSTR_CCVER) +#elif defined(LZO_INFO_CCVER) +# define __LZO_INFOSTR_CCVER " " LZO_INFO_CCVER +#else +# define __LZO_INFOSTR_CCVER "" +#endif +#define LZO_INFO_STRING \ + LZO_INFO_ARCH __LZO_INFOSTR_MM __LZO_INFOSTR_PM __LZO_INFOSTR_ENDIAN \ + " " __LZO_INFOSTR_OSNAME __LZO_INFOSTR_LIBC " " LZO_INFO_CC __LZO_INFOSTR_CCVER +#if !(LZO_CFG_SKIP_LZO_TYPES) +#if (!(LZO_SIZEOF_SHORT+0 > 0 && LZO_SIZEOF_INT+0 > 0 && LZO_SIZEOF_LONG+0 > 0)) +# error "missing defines for sizes" +#endif +#if (!(LZO_SIZEOF_PTRDIFF_T+0 > 0 && LZO_SIZEOF_SIZE_T+0 > 0 && LZO_SIZEOF_VOID_P+0 > 0)) +# error "missing defines for sizes" +#endif +#define LZO_TYPEOF_CHAR 1u +#define LZO_TYPEOF_SHORT 2u +#define LZO_TYPEOF_INT 3u +#define LZO_TYPEOF_LONG 4u +#define LZO_TYPEOF_LONG_LONG 5u +#define LZO_TYPEOF___INT8 17u +#define LZO_TYPEOF___INT16 18u +#define LZO_TYPEOF___INT32 19u +#define LZO_TYPEOF___INT64 20u +#define LZO_TYPEOF___INT128 21u +#define LZO_TYPEOF___INT256 22u +#define LZO_TYPEOF___MODE_QI 33u +#define LZO_TYPEOF___MODE_HI 34u +#define LZO_TYPEOF___MODE_SI 35u +#define LZO_TYPEOF___MODE_DI 36u +#define LZO_TYPEOF___MODE_TI 37u +#define LZO_TYPEOF_CHAR_P 129u +#if !defined(lzo_llong_t) +#if (LZO_SIZEOF_LONG_LONG+0 > 0) +# if !(LZO_LANG_ASSEMBLER) + __lzo_gnuc_extension__ typedef long long lzo_llong_t__; + __lzo_gnuc_extension__ typedef unsigned long long lzo_ullong_t__; +# endif +# define lzo_llong_t lzo_llong_t__ +# define lzo_ullong_t lzo_ullong_t__ +#endif +#endif +#if !defined(lzo_int16e_t) +#if (LZO_CFG_PREFER_TYPEOF_ACC_INT16E_T == LZO_TYPEOF_SHORT) && (LZO_SIZEOF_SHORT != 2) +# undef LZO_CFG_PREFER_TYPEOF_ACC_INT16E_T +#endif +#if (LZO_SIZEOF_LONG == 2) && !(LZO_CFG_PREFER_TYPEOF_ACC_INT16E_T == LZO_TYPEOF_SHORT) +# define lzo_int16e_t long +# define lzo_uint16e_t unsigned long +# define LZO_TYPEOF_LZO_INT16E_T LZO_TYPEOF_LONG +#elif (LZO_SIZEOF_INT == 2) && !(LZO_CFG_PREFER_TYPEOF_ACC_INT16E_T == LZO_TYPEOF_SHORT) +# define lzo_int16e_t int +# define lzo_uint16e_t unsigned int +# define LZO_TYPEOF_LZO_INT16E_T LZO_TYPEOF_INT +#elif (LZO_SIZEOF_SHORT == 2) +# define lzo_int16e_t short int +# define lzo_uint16e_t unsigned short int +# define LZO_TYPEOF_LZO_INT16E_T LZO_TYPEOF_SHORT +#elif 1 && !(LZO_CFG_TYPE_NO_MODE_HI) && (LZO_CC_CLANG || (LZO_CC_GNUC >= 0x025f00ul) || LZO_CC_LLVM) +# if !(LZO_LANG_ASSEMBLER) + typedef int lzo_int16e_hi_t__ __attribute__((__mode__(__HI__))); + typedef unsigned int lzo_uint16e_hi_t__ __attribute__((__mode__(__HI__))); +# endif +# define lzo_int16e_t lzo_int16e_hi_t__ +# define lzo_uint16e_t lzo_uint16e_hi_t__ +# define LZO_TYPEOF_LZO_INT16E_T LZO_TYPEOF___MODE_HI +#elif (LZO_SIZEOF___INT16 == 2) +# define lzo_int16e_t __int16 +# define lzo_uint16e_t unsigned __int16 +# define LZO_TYPEOF_LZO_INT16E_T LZO_TYPEOF___INT16 +#else +#endif +#endif +#if defined(lzo_int16e_t) +# define LZO_SIZEOF_LZO_INT16E_T 2 + LZO_COMPILE_TIME_ASSERT_HEADER(sizeof(lzo_int16e_t) == 2) + LZO_COMPILE_TIME_ASSERT_HEADER(sizeof(lzo_int16e_t) == LZO_SIZEOF_LZO_INT16E_T) +#endif +#if !defined(lzo_int32e_t) +#if (LZO_CFG_PREFER_TYPEOF_ACC_INT32E_T == LZO_TYPEOF_INT) && (LZO_SIZEOF_INT != 4) +# undef LZO_CFG_PREFER_TYPEOF_ACC_INT32E_T +#endif +#if (LZO_SIZEOF_LONG == 4) && !(LZO_CFG_PREFER_TYPEOF_ACC_INT32E_T == LZO_TYPEOF_INT) +# define lzo_int32e_t long int +# define lzo_uint32e_t unsigned long int +# define LZO_TYPEOF_LZO_INT32E_T LZO_TYPEOF_LONG +#elif (LZO_SIZEOF_INT == 4) +# define lzo_int32e_t int +# define lzo_uint32e_t unsigned int +# define LZO_TYPEOF_LZO_INT32E_T LZO_TYPEOF_INT +#elif (LZO_SIZEOF_SHORT == 4) +# define lzo_int32e_t short int +# define lzo_uint32e_t unsigned short int +# define LZO_TYPEOF_LZO_INT32E_T LZO_TYPEOF_SHORT +#elif (LZO_SIZEOF_LONG_LONG == 4) +# define lzo_int32e_t lzo_llong_t +# define lzo_uint32e_t lzo_ullong_t +# define LZO_TYPEOF_LZO_INT32E_T LZO_TYPEOF_LONG_LONG +#elif 1 && !(LZO_CFG_TYPE_NO_MODE_SI) && (LZO_CC_CLANG || (LZO_CC_GNUC >= 0x025f00ul) || LZO_CC_LLVM) && (__INT_MAX__+0 > 2147483647L) +# if !(LZO_LANG_ASSEMBLER) + typedef int lzo_int32e_si_t__ __attribute__((__mode__(__SI__))); + typedef unsigned int lzo_uint32e_si_t__ __attribute__((__mode__(__SI__))); +# endif +# define lzo_int32e_t lzo_int32e_si_t__ +# define lzo_uint32e_t lzo_uint32e_si_t__ +# define LZO_TYPEOF_LZO_INT32E_T LZO_TYPEOF___MODE_SI +#elif 1 && !(LZO_CFG_TYPE_NO_MODE_SI) && (LZO_CC_GNUC >= 0x025f00ul) && defined(__AVR__) && (__LONG_MAX__+0 == 32767L) +# if !(LZO_LANG_ASSEMBLER) + typedef int lzo_int32e_si_t__ __attribute__((__mode__(__SI__))); + typedef unsigned int lzo_uint32e_si_t__ __attribute__((__mode__(__SI__))); +# endif +# define lzo_int32e_t lzo_int32e_si_t__ +# define lzo_uint32e_t lzo_uint32e_si_t__ +# define LZO_INT32_C(c) (c##LL) +# define LZO_UINT32_C(c) (c##ULL) +# define LZO_TYPEOF_LZO_INT32E_T LZO_TYPEOF___MODE_SI +#elif (LZO_SIZEOF___INT32 == 4) +# define lzo_int32e_t __int32 +# define lzo_uint32e_t unsigned __int32 +# define LZO_TYPEOF_LZO_INT32E_T LZO_TYPEOF___INT32 +#else +#endif +#endif +#if defined(lzo_int32e_t) +# define LZO_SIZEOF_LZO_INT32E_T 4 + LZO_COMPILE_TIME_ASSERT_HEADER(sizeof(lzo_int32e_t) == 4) + LZO_COMPILE_TIME_ASSERT_HEADER(sizeof(lzo_int32e_t) == LZO_SIZEOF_LZO_INT32E_T) +#endif +#if !defined(lzo_int64e_t) +#if (LZO_SIZEOF___INT64 == 8) +# if (LZO_CC_BORLANDC) && !defined(LZO_CFG_PREFER_TYPEOF_ACC_INT64E_T) +# define LZO_CFG_PREFER_TYPEOF_ACC_INT64E_T LZO_TYPEOF___INT64 +# endif +#endif +#if (LZO_CFG_PREFER_TYPEOF_ACC_INT64E_T == LZO_TYPEOF_LONG_LONG) && (LZO_SIZEOF_LONG_LONG != 8) +# undef LZO_CFG_PREFER_TYPEOF_ACC_INT64E_T +#endif +#if (LZO_CFG_PREFER_TYPEOF_ACC_INT64E_T == LZO_TYPEOF___INT64) && (LZO_SIZEOF___INT64 != 8) +# undef LZO_CFG_PREFER_TYPEOF_ACC_INT64E_T +#endif +#if (LZO_SIZEOF_INT == 8) && (LZO_SIZEOF_INT < LZO_SIZEOF_LONG) +# define lzo_int64e_t int +# define lzo_uint64e_t unsigned int +# define LZO_TYPEOF_LZO_INT64E_T LZO_TYPEOF_INT +#elif (LZO_SIZEOF_LONG == 8) && !(LZO_CFG_PREFER_TYPEOF_ACC_INT64E_T == LZO_TYPEOF_LONG_LONG) && !(LZO_CFG_PREFER_TYPEOF_ACC_INT64E_T == LZO_TYPEOF___INT64) +# define lzo_int64e_t long int +# define lzo_uint64e_t unsigned long int +# define LZO_TYPEOF_LZO_INT64E_T LZO_TYPEOF_LONG +#elif (LZO_SIZEOF_LONG_LONG == 8) && !(LZO_CFG_PREFER_TYPEOF_ACC_INT64E_T == LZO_TYPEOF___INT64) +# define lzo_int64e_t lzo_llong_t +# define lzo_uint64e_t lzo_ullong_t +# define LZO_TYPEOF_LZO_INT64E_T LZO_TYPEOF_LONG_LONG +# if (LZO_CC_BORLANDC) +# define LZO_INT64_C(c) ((c) + 0ll) +# define LZO_UINT64_C(c) ((c) + 0ull) +# elif 0 +# define LZO_INT64_C(c) (__lzo_gnuc_extension__ (c##LL)) +# define LZO_UINT64_C(c) (__lzo_gnuc_extension__ (c##ULL)) +# else +# define LZO_INT64_C(c) (c##LL) +# define LZO_UINT64_C(c) (c##ULL) +# endif +#elif (LZO_SIZEOF___INT64 == 8) +# define lzo_int64e_t __int64 +# define lzo_uint64e_t unsigned __int64 +# define LZO_TYPEOF_LZO_INT64E_T LZO_TYPEOF___INT64 +# if (LZO_CC_BORLANDC) +# define LZO_INT64_C(c) ((c) + 0i64) +# define LZO_UINT64_C(c) ((c) + 0ui64) +# else +# define LZO_INT64_C(c) (c##i64) +# define LZO_UINT64_C(c) (c##ui64) +# endif +#else +#endif +#endif +#if defined(lzo_int64e_t) +# define LZO_SIZEOF_LZO_INT64E_T 8 + LZO_COMPILE_TIME_ASSERT_HEADER(sizeof(lzo_int64e_t) == 8) + LZO_COMPILE_TIME_ASSERT_HEADER(sizeof(lzo_int64e_t) == LZO_SIZEOF_LZO_INT64E_T) +#endif +#if !defined(lzo_int32l_t) +#if defined(lzo_int32e_t) +# define lzo_int32l_t lzo_int32e_t +# define lzo_uint32l_t lzo_uint32e_t +# define LZO_SIZEOF_LZO_INT32L_T LZO_SIZEOF_LZO_INT32E_T +# define LZO_TYPEOF_LZO_INT32L_T LZO_TYPEOF_LZO_INT32E_T +#elif (LZO_SIZEOF_INT >= 4) && (LZO_SIZEOF_INT < LZO_SIZEOF_LONG) +# define lzo_int32l_t int +# define lzo_uint32l_t unsigned int +# define LZO_SIZEOF_LZO_INT32L_T LZO_SIZEOF_INT +# define LZO_TYPEOF_LZO_INT32L_T LZO_SIZEOF_INT +#elif (LZO_SIZEOF_LONG >= 4) +# define lzo_int32l_t long int +# define lzo_uint32l_t unsigned long int +# define LZO_SIZEOF_LZO_INT32L_T LZO_SIZEOF_LONG +# define LZO_TYPEOF_LZO_INT32L_T LZO_SIZEOF_LONG +#else +# error "lzo_int32l_t" +#endif +#endif +#if 1 + LZO_COMPILE_TIME_ASSERT_HEADER(sizeof(lzo_int32l_t) >= 4) + LZO_COMPILE_TIME_ASSERT_HEADER(sizeof(lzo_int32l_t) == LZO_SIZEOF_LZO_INT32L_T) +#endif +#if !defined(lzo_int64l_t) +#if defined(lzo_int64e_t) +# define lzo_int64l_t lzo_int64e_t +# define lzo_uint64l_t lzo_uint64e_t +# define LZO_SIZEOF_LZO_INT64L_T LZO_SIZEOF_LZO_INT64E_T +# define LZO_TYPEOF_LZO_INT64L_T LZO_TYPEOF_LZO_INT64E_T +#else +#endif +#endif +#if defined(lzo_int64l_t) + LZO_COMPILE_TIME_ASSERT_HEADER(sizeof(lzo_int64l_t) >= 8) + LZO_COMPILE_TIME_ASSERT_HEADER(sizeof(lzo_int64l_t) == LZO_SIZEOF_LZO_INT64L_T) +#endif +#if !defined(lzo_int32f_t) +#if (LZO_SIZEOF_SIZE_T >= 8) +# define lzo_int32f_t lzo_int64l_t +# define lzo_uint32f_t lzo_uint64l_t +# define LZO_SIZEOF_LZO_INT32F_T LZO_SIZEOF_LZO_INT64L_T +# define LZO_TYPEOF_LZO_INT32F_T LZO_TYPEOF_LZO_INT64L_T +#else +# define lzo_int32f_t lzo_int32l_t +# define lzo_uint32f_t lzo_uint32l_t +# define LZO_SIZEOF_LZO_INT32F_T LZO_SIZEOF_LZO_INT32L_T +# define LZO_TYPEOF_LZO_INT32F_T LZO_TYPEOF_LZO_INT32L_T +#endif +#endif +#if 1 + LZO_COMPILE_TIME_ASSERT_HEADER(sizeof(lzo_int32f_t) >= 4) + LZO_COMPILE_TIME_ASSERT_HEADER(sizeof(lzo_int32f_t) == LZO_SIZEOF_LZO_INT32F_T) +#endif +#if !defined(lzo_int64f_t) +#if defined(lzo_int64l_t) +# define lzo_int64f_t lzo_int64l_t +# define lzo_uint64f_t lzo_uint64l_t +# define LZO_SIZEOF_LZO_INT64F_T LZO_SIZEOF_LZO_INT64L_T +# define LZO_TYPEOF_LZO_INT64F_T LZO_TYPEOF_LZO_INT64L_T +#else +#endif +#endif +#if defined(lzo_int64f_t) + LZO_COMPILE_TIME_ASSERT_HEADER(sizeof(lzo_int64f_t) >= 8) + LZO_COMPILE_TIME_ASSERT_HEADER(sizeof(lzo_int64f_t) == LZO_SIZEOF_LZO_INT64F_T) +#endif +#if !defined(lzo_intptr_t) +#if 1 && (LZO_OS_OS400 && (LZO_SIZEOF_VOID_P == 16)) +# define __LZO_INTPTR_T_IS_POINTER 1 +# if !(LZO_LANG_ASSEMBLER) + typedef char * lzo_intptr_t; + typedef char * lzo_uintptr_t; +# endif +# define lzo_intptr_t lzo_intptr_t +# define lzo_uintptr_t lzo_uintptr_t +# define LZO_SIZEOF_LZO_INTPTR_T LZO_SIZEOF_VOID_P +# define LZO_TYPEOF_LZO_INTPTR_T LZO_TYPEOF_CHAR_P +#elif (LZO_CC_MSC && (_MSC_VER >= 1300) && (LZO_SIZEOF_VOID_P == 4) && (LZO_SIZEOF_INT == 4)) +# if !(LZO_LANG_ASSEMBLER) + typedef __w64 int lzo_intptr_t; + typedef __w64 unsigned int lzo_uintptr_t; +# endif +# define lzo_intptr_t lzo_intptr_t +# define lzo_uintptr_t lzo_uintptr_t +# define LZO_SIZEOF_LZO_INTPTR_T LZO_SIZEOF_INT +# define LZO_TYPEOF_LZO_INTPTR_T LZO_TYPEOF_INT +#elif (LZO_SIZEOF_SHORT == LZO_SIZEOF_VOID_P) && (LZO_SIZEOF_INT > LZO_SIZEOF_VOID_P) +# define lzo_intptr_t short +# define lzo_uintptr_t unsigned short +# define LZO_SIZEOF_LZO_INTPTR_T LZO_SIZEOF_SHORT +# define LZO_TYPEOF_LZO_INTPTR_T LZO_TYPEOF_SHORT +#elif (LZO_SIZEOF_INT >= LZO_SIZEOF_VOID_P) && (LZO_SIZEOF_INT < LZO_SIZEOF_LONG) +# define lzo_intptr_t int +# define lzo_uintptr_t unsigned int +# define LZO_SIZEOF_LZO_INTPTR_T LZO_SIZEOF_INT +# define LZO_TYPEOF_LZO_INTPTR_T LZO_TYPEOF_INT +#elif (LZO_SIZEOF_LONG >= LZO_SIZEOF_VOID_P) +# define lzo_intptr_t long +# define lzo_uintptr_t unsigned long +# define LZO_SIZEOF_LZO_INTPTR_T LZO_SIZEOF_LONG +# define LZO_TYPEOF_LZO_INTPTR_T LZO_TYPEOF_LONG +#elif (LZO_SIZEOF_LZO_INT64L_T >= LZO_SIZEOF_VOID_P) +# define lzo_intptr_t lzo_int64l_t +# define lzo_uintptr_t lzo_uint64l_t +# define LZO_SIZEOF_LZO_INTPTR_T LZO_SIZEOF_LZO_INT64L_T +# define LZO_TYPEOF_LZO_INTPTR_T LZO_TYPEOF_LZO_INT64L_T +#else +# error "lzo_intptr_t" +#endif +#endif +#if 1 + LZO_COMPILE_TIME_ASSERT_HEADER(sizeof(lzo_intptr_t) >= sizeof(void *)) + LZO_COMPILE_TIME_ASSERT_HEADER(sizeof(lzo_intptr_t) == sizeof(lzo_uintptr_t)) +#endif +#if !defined(lzo_word_t) +#if defined(LZO_WORDSIZE) && (LZO_WORDSIZE+0 > 0) +#if (LZO_WORDSIZE == LZO_SIZEOF_LZO_INTPTR_T) && !(__LZO_INTPTR_T_IS_POINTER) +# define lzo_word_t lzo_uintptr_t +# define lzo_sword_t lzo_intptr_t +# define LZO_SIZEOF_LZO_WORD_T LZO_SIZEOF_LZO_INTPTR_T +# define LZO_TYPEOF_LZO_WORD_T LZO_TYPEOF_LZO_INTPTR_T +#elif (LZO_WORDSIZE == LZO_SIZEOF_LONG) +# define lzo_word_t unsigned long +# define lzo_sword_t long +# define LZO_SIZEOF_LZO_WORD_T LZO_SIZEOF_LONG +# define LZO_TYPEOF_LZO_WORD_T LZO_TYPEOF_LONG +#elif (LZO_WORDSIZE == LZO_SIZEOF_INT) +# define lzo_word_t unsigned int +# define lzo_sword_t int +# define LZO_SIZEOF_LZO_WORD_T LZO_SIZEOF_INT +# define LZO_TYPEOF_LZO_WORD_T LZO_TYPEOF_INT +#elif (LZO_WORDSIZE == LZO_SIZEOF_SHORT) +# define lzo_word_t unsigned short +# define lzo_sword_t short +# define LZO_SIZEOF_LZO_WORD_T LZO_SIZEOF_SHORT +# define LZO_TYPEOF_LZO_WORD_T LZO_TYPEOF_SHORT +#elif (LZO_WORDSIZE == 1) +# define lzo_word_t unsigned char +# define lzo_sword_t signed char +# define LZO_SIZEOF_LZO_WORD_T 1 +# define LZO_TYPEOF_LZO_WORD_T LZO_TYPEOF_CHAR +#elif (LZO_WORDSIZE == LZO_SIZEOF_LZO_INT64L_T) +# define lzo_word_t lzo_uint64l_t +# define lzo_sword_t lzo_int64l_t +# define LZO_SIZEOF_LZO_WORD_T LZO_SIZEOF_LZO_INT64L_T +# define LZO_TYPEOF_LZO_WORD_T LZO_SIZEOF_LZO_INT64L_T +#elif (LZO_ARCH_SPU) && (LZO_CC_GNUC) +#if 0 +# if !(LZO_LANG_ASSEMBLER) + typedef unsigned lzo_word_t __attribute__((__mode__(__V16QI__))); + typedef int lzo_sword_t __attribute__((__mode__(__V16QI__))); +# endif +# define lzo_word_t lzo_word_t +# define lzo_sword_t lzo_sword_t +# define LZO_SIZEOF_LZO_WORD_T 16 +# define LZO_TYPEOF_LZO_WORD_T LZO_TYPEOF___MODE_V16QI +#endif +#else +# error "lzo_word_t" +#endif +#endif +#endif +#if 1 && defined(lzo_word_t) + LZO_COMPILE_TIME_ASSERT_HEADER(sizeof(lzo_word_t) == LZO_WORDSIZE) + LZO_COMPILE_TIME_ASSERT_HEADER(sizeof(lzo_sword_t) == LZO_WORDSIZE) +#endif +#if 1 +#define lzo_int8_t signed char +#define lzo_uint8_t unsigned char +#define LZO_SIZEOF_LZO_INT8_T 1 +#define LZO_TYPEOF_LZO_INT8_T LZO_TYPEOF_CHAR +LZO_COMPILE_TIME_ASSERT_HEADER(sizeof(lzo_int8_t) == 1) +LZO_COMPILE_TIME_ASSERT_HEADER(sizeof(lzo_int8_t) == sizeof(lzo_uint8_t)) +#endif +#if defined(lzo_int16e_t) +#define lzo_int16_t lzo_int16e_t +#define lzo_uint16_t lzo_uint16e_t +#define LZO_SIZEOF_LZO_INT16_T LZO_SIZEOF_LZO_INT16E_T +#define LZO_TYPEOF_LZO_INT16_T LZO_TYPEOF_LZO_INT16E_T +LZO_COMPILE_TIME_ASSERT_HEADER(sizeof(lzo_int16_t) == 2) +LZO_COMPILE_TIME_ASSERT_HEADER(sizeof(lzo_int16_t) == sizeof(lzo_uint16_t)) +#endif +#if defined(lzo_int32e_t) +#define lzo_int32_t lzo_int32e_t +#define lzo_uint32_t lzo_uint32e_t +#define LZO_SIZEOF_LZO_INT32_T LZO_SIZEOF_LZO_INT32E_T +#define LZO_TYPEOF_LZO_INT32_T LZO_TYPEOF_LZO_INT32E_T +LZO_COMPILE_TIME_ASSERT_HEADER(sizeof(lzo_int32_t) == 4) +LZO_COMPILE_TIME_ASSERT_HEADER(sizeof(lzo_int32_t) == sizeof(lzo_uint32_t)) +#endif +#if defined(lzo_int64e_t) +#define lzo_int64_t lzo_int64e_t +#define lzo_uint64_t lzo_uint64e_t +#define LZO_SIZEOF_LZO_INT64_T LZO_SIZEOF_LZO_INT64E_T +#define LZO_TYPEOF_LZO_INT64_T LZO_TYPEOF_LZO_INT64E_T +LZO_COMPILE_TIME_ASSERT_HEADER(sizeof(lzo_int64_t) == 8) +LZO_COMPILE_TIME_ASSERT_HEADER(sizeof(lzo_int64_t) == sizeof(lzo_uint64_t)) +#endif +#if 1 +#define lzo_int_least32_t lzo_int32l_t +#define lzo_uint_least32_t lzo_uint32l_t +#define LZO_SIZEOF_LZO_INT_LEAST32_T LZO_SIZEOF_LZO_INT32L_T +#define LZO_TYPEOF_LZO_INT_LEAST32_T LZO_TYPEOF_LZO_INT32L_T +LZO_COMPILE_TIME_ASSERT_HEADER(sizeof(lzo_int_least32_t) >= 4) +LZO_COMPILE_TIME_ASSERT_HEADER(sizeof(lzo_int_least32_t) == sizeof(lzo_uint_least32_t)) +#endif +#if defined(lzo_int64l_t) +#define lzo_int_least64_t lzo_int64l_t +#define lzo_uint_least64_t lzo_uint64l_t +#define LZO_SIZEOF_LZO_INT_LEAST64_T LZO_SIZEOF_LZO_INT64L_T +#define LZO_TYPEOF_LZO_INT_LEAST64_T LZO_TYPEOF_LZO_INT64L_T +LZO_COMPILE_TIME_ASSERT_HEADER(sizeof(lzo_int_least64_t) >= 8) +LZO_COMPILE_TIME_ASSERT_HEADER(sizeof(lzo_int_least64_t) == sizeof(lzo_uint_least64_t)) +#endif +#if 1 +#define lzo_int_fast32_t lzo_int32f_t +#define lzo_uint_fast32_t lzo_uint32f_t +#define LZO_SIZEOF_LZO_INT_FAST32_T LZO_SIZEOF_LZO_INT32F_T +#define LZO_TYPEOF_LZO_INT_FAST32_T LZO_TYPEOF_LZO_INT32F_T +LZO_COMPILE_TIME_ASSERT_HEADER(sizeof(lzo_int_fast32_t) >= 4) +LZO_COMPILE_TIME_ASSERT_HEADER(sizeof(lzo_int_fast32_t) == sizeof(lzo_uint_fast32_t)) +#endif +#if defined(lzo_int64f_t) +#define lzo_int_fast64_t lzo_int64f_t +#define lzo_uint_fast64_t lzo_uint64f_t +#define LZO_SIZEOF_LZO_INT_FAST64_T LZO_SIZEOF_LZO_INT64F_T +#define LZO_TYPEOF_LZO_INT_FAST64_T LZO_TYPEOF_LZO_INT64F_T +LZO_COMPILE_TIME_ASSERT_HEADER(sizeof(lzo_int_fast64_t) >= 8) +LZO_COMPILE_TIME_ASSERT_HEADER(sizeof(lzo_int_fast64_t) == sizeof(lzo_uint_fast64_t)) +#endif +#if !defined(LZO_INT16_C) +# if (LZO_BROKEN_INTEGRAL_CONSTANTS) && (LZO_SIZEOF_INT >= 2) +# define LZO_INT16_C(c) ((c) + 0) +# define LZO_UINT16_C(c) ((c) + 0U) +# elif (LZO_BROKEN_INTEGRAL_CONSTANTS) && (LZO_SIZEOF_LONG >= 2) +# define LZO_INT16_C(c) ((c) + 0L) +# define LZO_UINT16_C(c) ((c) + 0UL) +# elif (LZO_SIZEOF_INT >= 2) +# define LZO_INT16_C(c) (c) +# define LZO_UINT16_C(c) (c##U) +# elif (LZO_SIZEOF_LONG >= 2) +# define LZO_INT16_C(c) (c##L) +# define LZO_UINT16_C(c) (c##UL) +# else +# error "LZO_INT16_C" +# endif +#endif +#if !defined(LZO_INT32_C) +# if (LZO_BROKEN_INTEGRAL_CONSTANTS) && (LZO_SIZEOF_INT >= 4) +# define LZO_INT32_C(c) ((c) + 0) +# define LZO_UINT32_C(c) ((c) + 0U) +# elif (LZO_BROKEN_INTEGRAL_CONSTANTS) && (LZO_SIZEOF_LONG >= 4) +# define LZO_INT32_C(c) ((c) + 0L) +# define LZO_UINT32_C(c) ((c) + 0UL) +# elif (LZO_SIZEOF_INT >= 4) +# define LZO_INT32_C(c) (c) +# define LZO_UINT32_C(c) (c##U) +# elif (LZO_SIZEOF_LONG >= 4) +# define LZO_INT32_C(c) (c##L) +# define LZO_UINT32_C(c) (c##UL) +# elif (LZO_SIZEOF_LONG_LONG >= 4) +# define LZO_INT32_C(c) (c##LL) +# define LZO_UINT32_C(c) (c##ULL) +# else +# error "LZO_INT32_C" +# endif +#endif +#if !defined(LZO_INT64_C) && defined(lzo_int64l_t) +# if (LZO_BROKEN_INTEGRAL_CONSTANTS) && (LZO_SIZEOF_INT >= 8) +# define LZO_INT64_C(c) ((c) + 0) +# define LZO_UINT64_C(c) ((c) + 0U) +# elif (LZO_BROKEN_INTEGRAL_CONSTANTS) && (LZO_SIZEOF_LONG >= 8) +# define LZO_INT64_C(c) ((c) + 0L) +# define LZO_UINT64_C(c) ((c) + 0UL) +# elif (LZO_SIZEOF_INT >= 8) +# define LZO_INT64_C(c) (c) +# define LZO_UINT64_C(c) (c##U) +# elif (LZO_SIZEOF_LONG >= 8) +# define LZO_INT64_C(c) (c##L) +# define LZO_UINT64_C(c) (c##UL) +# else +# error "LZO_INT64_C" +# endif +#endif +#endif + +#endif /* already included */ + +/* vim:set ts=4 sw=4 et: */ diff --git a/eterpack/src/minilzo/minilzo.c b/eterpack/src/minilzo/minilzo.c new file mode 100644 index 0000000..8fd8664 --- /dev/null +++ b/eterpack/src/minilzo/minilzo.c @@ -0,0 +1,6365 @@ +/* minilzo.c -- mini subset of the LZO real-time data compression library + + This file is part of the LZO real-time data compression library. + + Copyright (C) 1996-2017 Markus Franz Xaver Johannes Oberhumer + All Rights Reserved. + + The LZO library is free software; you can redistribute it and/or + modify it under the terms of the GNU General Public License as + published by the Free Software Foundation; either version 2 of + the License, or (at your option) any later version. + + The LZO library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with the LZO library; see the file COPYING. + If not, write to the Free Software Foundation, Inc., + 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. + + Markus F.X.J. Oberhumer + + http://www.oberhumer.com/opensource/lzo/ + */ + +/* + * NOTE: + * the full LZO package can be found at + * http://www.oberhumer.com/opensource/lzo/ + */ + +#define __LZO_IN_MINILZO 1 + +#if defined(LZO_CFG_FREESTANDING) +# undef MINILZO_HAVE_CONFIG_H +# define LZO_LIBC_FREESTANDING 1 +# define LZO_OS_FREESTANDING 1 +#endif + +#ifdef MINILZO_HAVE_CONFIG_H +# include +#endif +#include +#include +#if defined(MINILZO_CFG_USE_INTERNAL_LZODEFS) + +#ifndef __LZODEFS_H_INCLUDED +#define __LZODEFS_H_INCLUDED 1 + +#if defined(__CYGWIN32__) && !defined(__CYGWIN__) +# define __CYGWIN__ __CYGWIN32__ +#endif +#if 1 && defined(__INTERIX) && defined(__GNUC__) && !defined(_ALL_SOURCE) +# define _ALL_SOURCE 1 +#endif +#if defined(__mips__) && defined(__R5900__) +# if !defined(__LONG_MAX__) +# define __LONG_MAX__ 9223372036854775807L +# endif +#endif +#if 0 +#elif !defined(__LZO_LANG_OVERRIDE) +#if (defined(__clang__) || defined(__GNUC__)) && defined(__ASSEMBLER__) +# if (__ASSEMBLER__+0) <= 0 +# error "__ASSEMBLER__" +# else +# define LZO_LANG_ASSEMBLER 1 +# endif +#elif defined(__cplusplus) +# if (__cplusplus+0) <= 0 +# error "__cplusplus" +# elif (__cplusplus < 199711L) +# define LZO_LANG_CXX 1 +# elif defined(_MSC_VER) && defined(_MSVC_LANG) && (_MSVC_LANG+0 >= 201402L) && 1 +# define LZO_LANG_CXX _MSVC_LANG +# else +# define LZO_LANG_CXX __cplusplus +# endif +# define LZO_LANG_CPLUSPLUS LZO_LANG_CXX +#else +# if defined(__STDC_VERSION__) && (__STDC_VERSION__+0 >= 199409L) +# define LZO_LANG_C __STDC_VERSION__ +# else +# define LZO_LANG_C 1 +# endif +#endif +#endif +#if !defined(LZO_CFG_NO_DISABLE_WUNDEF) +#if defined(__ARMCC_VERSION) +# pragma diag_suppress 193 +#elif defined(__clang__) && defined(__clang_minor__) +# pragma clang diagnostic ignored "-Wundef" +#elif defined(__INTEL_COMPILER) +# pragma warning(disable: 193) +#elif defined(__KEIL__) && defined(__C166__) +# pragma warning disable = 322 +#elif defined(__GNUC__) && defined(__GNUC_MINOR__) && !defined(__PATHSCALE__) +# if ((__GNUC__-0) >= 5 || ((__GNUC__-0) == 4 && (__GNUC_MINOR__-0) >= 2)) +# pragma GCC diagnostic ignored "-Wundef" +# endif +#elif defined(_MSC_VER) && !defined(__clang__) && !defined(__INTEL_COMPILER) && !defined(__MWERKS__) +# if ((_MSC_VER-0) >= 1300) +# pragma warning(disable: 4668) +# endif +#endif +#endif +#if 0 && defined(__POCC__) && defined(_WIN32) +# if (__POCC__ >= 400) +# pragma warn(disable: 2216) +# endif +#endif +#if 0 && defined(__WATCOMC__) +# if (__WATCOMC__ >= 1050) && (__WATCOMC__ < 1060) +# pragma warning 203 9 +# endif +#endif +#if defined(__BORLANDC__) && defined(__MSDOS__) && !defined(__FLAT__) +# pragma option -h +#endif +#if !(LZO_CFG_NO_DISABLE_WCRTNONSTDC) +#ifndef _CRT_NONSTDC_NO_DEPRECATE +#define _CRT_NONSTDC_NO_DEPRECATE 1 +#endif +#ifndef _CRT_NONSTDC_NO_WARNINGS +#define _CRT_NONSTDC_NO_WARNINGS 1 +#endif +#ifndef _CRT_SECURE_NO_DEPRECATE +#define _CRT_SECURE_NO_DEPRECATE 1 +#endif +#ifndef _CRT_SECURE_NO_WARNINGS +#define _CRT_SECURE_NO_WARNINGS 1 +#endif +#endif +#if 0 +#define LZO_0xffffUL 0xfffful +#define LZO_0xffffffffUL 0xfffffffful +#else +#define LZO_0xffffUL 65535ul +#define LZO_0xffffffffUL 4294967295ul +#endif +#define LZO_0xffffL LZO_0xffffUL +#define LZO_0xffffffffL LZO_0xffffffffUL +#if (LZO_0xffffL == LZO_0xffffffffL) +# error "your preprocessor is broken 1" +#endif +#if (16ul * 16384ul != 262144ul) +# error "your preprocessor is broken 2" +#endif +#if 0 +#if (32767 >= 4294967295ul) +# error "your preprocessor is broken 3" +#endif +#if (65535u >= 4294967295ul) +# error "your preprocessor is broken 4" +#endif +#endif +#if defined(__COUNTER__) +# ifndef LZO_CFG_USE_COUNTER +# define LZO_CFG_USE_COUNTER 1 +# endif +#else +# undef LZO_CFG_USE_COUNTER +#endif +#if (UINT_MAX == LZO_0xffffL) +#if defined(__ZTC__) && defined(__I86__) && !defined(__OS2__) +# if !defined(MSDOS) +# define MSDOS 1 +# endif +# if !defined(_MSDOS) +# define _MSDOS 1 +# endif +#elif 0 && defined(__VERSION) && defined(MB_LEN_MAX) +# if (__VERSION == 520) && (MB_LEN_MAX == 1) +# if !defined(__AZTEC_C__) +# define __AZTEC_C__ __VERSION +# endif +# if !defined(__DOS__) +# define __DOS__ 1 +# endif +# endif +#endif +#endif +#if (UINT_MAX == LZO_0xffffL) +#if defined(_MSC_VER) && defined(M_I86HM) +# define ptrdiff_t long +# define _PTRDIFF_T_DEFINED 1 +#endif +#endif +#if (UINT_MAX == LZO_0xffffL) +# undef __LZO_RENAME_A +# undef __LZO_RENAME_B +# if defined(__AZTEC_C__) && defined(__DOS__) +# define __LZO_RENAME_A 1 +# elif defined(_MSC_VER) && defined(MSDOS) +# if (_MSC_VER < 600) +# define __LZO_RENAME_A 1 +# elif (_MSC_VER < 700) +# define __LZO_RENAME_B 1 +# endif +# elif defined(__TSC__) && defined(__OS2__) +# define __LZO_RENAME_A 1 +# elif defined(__MSDOS__) && defined(__TURBOC__) && (__TURBOC__ < 0x0410) +# define __LZO_RENAME_A 1 +# elif defined(__PACIFIC__) && defined(DOS) +# if !defined(__far) +# define __far far +# endif +# if !defined(__near) +# define __near near +# endif +# endif +# if defined(__LZO_RENAME_A) +# if !defined(__cdecl) +# define __cdecl cdecl +# endif +# if !defined(__far) +# define __far far +# endif +# if !defined(__huge) +# define __huge huge +# endif +# if !defined(__near) +# define __near near +# endif +# if !defined(__pascal) +# define __pascal pascal +# endif +# if !defined(__huge) +# define __huge huge +# endif +# elif defined(__LZO_RENAME_B) +# if !defined(__cdecl) +# define __cdecl _cdecl +# endif +# if !defined(__far) +# define __far _far +# endif +# if !defined(__huge) +# define __huge _huge +# endif +# if !defined(__near) +# define __near _near +# endif +# if !defined(__pascal) +# define __pascal _pascal +# endif +# elif (defined(__PUREC__) || defined(__TURBOC__)) && defined(__TOS__) +# if !defined(__cdecl) +# define __cdecl cdecl +# endif +# if !defined(__pascal) +# define __pascal pascal +# endif +# endif +# undef __LZO_RENAME_A +# undef __LZO_RENAME_B +#endif +#if (UINT_MAX == LZO_0xffffL) +#if defined(__AZTEC_C__) && defined(__DOS__) +# define LZO_BROKEN_CDECL_ALT_SYNTAX 1 +#elif defined(_MSC_VER) && defined(MSDOS) +# if (_MSC_VER < 600) +# define LZO_BROKEN_INTEGRAL_CONSTANTS 1 +# endif +# if (_MSC_VER < 700) +# define LZO_BROKEN_INTEGRAL_PROMOTION 1 +# define LZO_BROKEN_SIZEOF 1 +# endif +#elif defined(__PACIFIC__) && defined(DOS) +# define LZO_BROKEN_INTEGRAL_CONSTANTS 1 +#elif defined(__TURBOC__) && defined(__MSDOS__) +# if (__TURBOC__ < 0x0150) +# define LZO_BROKEN_CDECL_ALT_SYNTAX 1 +# define LZO_BROKEN_INTEGRAL_CONSTANTS 1 +# define LZO_BROKEN_INTEGRAL_PROMOTION 1 +# endif +# if (__TURBOC__ < 0x0200) +# define LZO_BROKEN_SIZEOF 1 +# endif +# if (__TURBOC__ < 0x0400) && defined(__cplusplus) +# define LZO_BROKEN_CDECL_ALT_SYNTAX 1 +# endif +#elif (defined(__PUREC__) || defined(__TURBOC__)) && defined(__TOS__) +# define LZO_BROKEN_CDECL_ALT_SYNTAX 1 +# define LZO_BROKEN_SIZEOF 1 +#endif +#endif +#if defined(__WATCOMC__) && (__WATCOMC__ < 900) +# define LZO_BROKEN_INTEGRAL_CONSTANTS 1 +#endif +#if defined(_CRAY) && defined(_CRAY1) +# define LZO_BROKEN_SIGNED_RIGHT_SHIFT 1 +#endif +#define LZO_PP_STRINGIZE(x) #x +#define LZO_PP_MACRO_EXPAND(x) LZO_PP_STRINGIZE(x) +#define LZO_PP_CONCAT0() /*empty*/ +#define LZO_PP_CONCAT1(a) a +#define LZO_PP_CONCAT2(a,b) a ## b +#define LZO_PP_CONCAT3(a,b,c) a ## b ## c +#define LZO_PP_CONCAT4(a,b,c,d) a ## b ## c ## d +#define LZO_PP_CONCAT5(a,b,c,d,e) a ## b ## c ## d ## e +#define LZO_PP_CONCAT6(a,b,c,d,e,f) a ## b ## c ## d ## e ## f +#define LZO_PP_CONCAT7(a,b,c,d,e,f,g) a ## b ## c ## d ## e ## f ## g +#define LZO_PP_ECONCAT0() LZO_PP_CONCAT0() +#define LZO_PP_ECONCAT1(a) LZO_PP_CONCAT1(a) +#define LZO_PP_ECONCAT2(a,b) LZO_PP_CONCAT2(a,b) +#define LZO_PP_ECONCAT3(a,b,c) LZO_PP_CONCAT3(a,b,c) +#define LZO_PP_ECONCAT4(a,b,c,d) LZO_PP_CONCAT4(a,b,c,d) +#define LZO_PP_ECONCAT5(a,b,c,d,e) LZO_PP_CONCAT5(a,b,c,d,e) +#define LZO_PP_ECONCAT6(a,b,c,d,e,f) LZO_PP_CONCAT6(a,b,c,d,e,f) +#define LZO_PP_ECONCAT7(a,b,c,d,e,f,g) LZO_PP_CONCAT7(a,b,c,d,e,f,g) +#define LZO_PP_EMPTY /*empty*/ +#define LZO_PP_EMPTY0() /*empty*/ +#define LZO_PP_EMPTY1(a) /*empty*/ +#define LZO_PP_EMPTY2(a,b) /*empty*/ +#define LZO_PP_EMPTY3(a,b,c) /*empty*/ +#define LZO_PP_EMPTY4(a,b,c,d) /*empty*/ +#define LZO_PP_EMPTY5(a,b,c,d,e) /*empty*/ +#define LZO_PP_EMPTY6(a,b,c,d,e,f) /*empty*/ +#define LZO_PP_EMPTY7(a,b,c,d,e,f,g) /*empty*/ +#if 1 +#define LZO_CPP_STRINGIZE(x) #x +#define LZO_CPP_MACRO_EXPAND(x) LZO_CPP_STRINGIZE(x) +#define LZO_CPP_CONCAT2(a,b) a ## b +#define LZO_CPP_CONCAT3(a,b,c) a ## b ## c +#define LZO_CPP_CONCAT4(a,b,c,d) a ## b ## c ## d +#define LZO_CPP_CONCAT5(a,b,c,d,e) a ## b ## c ## d ## e +#define LZO_CPP_CONCAT6(a,b,c,d,e,f) a ## b ## c ## d ## e ## f +#define LZO_CPP_CONCAT7(a,b,c,d,e,f,g) a ## b ## c ## d ## e ## f ## g +#define LZO_CPP_ECONCAT2(a,b) LZO_CPP_CONCAT2(a,b) +#define LZO_CPP_ECONCAT3(a,b,c) LZO_CPP_CONCAT3(a,b,c) +#define LZO_CPP_ECONCAT4(a,b,c,d) LZO_CPP_CONCAT4(a,b,c,d) +#define LZO_CPP_ECONCAT5(a,b,c,d,e) LZO_CPP_CONCAT5(a,b,c,d,e) +#define LZO_CPP_ECONCAT6(a,b,c,d,e,f) LZO_CPP_CONCAT6(a,b,c,d,e,f) +#define LZO_CPP_ECONCAT7(a,b,c,d,e,f,g) LZO_CPP_CONCAT7(a,b,c,d,e,f,g) +#endif +#define __LZO_MASK_GEN(o,b) (((((o) << ((b)-((b)!=0))) - (o)) << 1) + (o)*((b)!=0)) +#if 1 && defined(__cplusplus) +# if !defined(__STDC_CONSTANT_MACROS) +# define __STDC_CONSTANT_MACROS 1 +# endif +# if !defined(__STDC_LIMIT_MACROS) +# define __STDC_LIMIT_MACROS 1 +# endif +#endif +#if defined(__cplusplus) +# define LZO_EXTERN_C extern "C" +# define LZO_EXTERN_C_BEGIN extern "C" { +# define LZO_EXTERN_C_END } +#else +# define LZO_EXTERN_C extern +# define LZO_EXTERN_C_BEGIN /*empty*/ +# define LZO_EXTERN_C_END /*empty*/ +#endif +#if !defined(__LZO_OS_OVERRIDE) +#if (LZO_OS_FREESTANDING) +# define LZO_INFO_OS "freestanding" +#elif (LZO_OS_EMBEDDED) +# define LZO_INFO_OS "embedded" +#elif 1 && defined(__IAR_SYSTEMS_ICC__) +# define LZO_OS_EMBEDDED 1 +# define LZO_INFO_OS "embedded" +#elif defined(__CYGWIN__) && defined(__GNUC__) +# define LZO_OS_CYGWIN 1 +# define LZO_INFO_OS "cygwin" +#elif defined(__EMX__) && defined(__GNUC__) +# define LZO_OS_EMX 1 +# define LZO_INFO_OS "emx" +#elif defined(__BEOS__) +# define LZO_OS_BEOS 1 +# define LZO_INFO_OS "beos" +#elif defined(__Lynx__) +# define LZO_OS_LYNXOS 1 +# define LZO_INFO_OS "lynxos" +#elif defined(__OS400__) +# define LZO_OS_OS400 1 +# define LZO_INFO_OS "os400" +#elif defined(__QNX__) +# define LZO_OS_QNX 1 +# define LZO_INFO_OS "qnx" +#elif defined(__BORLANDC__) && defined(__DPMI32__) && (__BORLANDC__ >= 0x0460) +# define LZO_OS_DOS32 1 +# define LZO_INFO_OS "dos32" +#elif defined(__BORLANDC__) && defined(__DPMI16__) +# define LZO_OS_DOS16 1 +# define LZO_INFO_OS "dos16" +#elif defined(__ZTC__) && defined(DOS386) +# define LZO_OS_DOS32 1 +# define LZO_INFO_OS "dos32" +#elif defined(__OS2__) || defined(__OS2V2__) +# if (UINT_MAX == LZO_0xffffL) +# define LZO_OS_OS216 1 +# define LZO_INFO_OS "os216" +# elif (UINT_MAX == LZO_0xffffffffL) +# define LZO_OS_OS2 1 +# define LZO_INFO_OS "os2" +# else +# error "check your limits.h header" +# endif +#elif defined(__WIN64__) || defined(_WIN64) || defined(WIN64) +# define LZO_OS_WIN64 1 +# define LZO_INFO_OS "win64" +#elif defined(__WIN32__) || defined(_WIN32) || defined(WIN32) || defined(__WINDOWS_386__) +# define LZO_OS_WIN32 1 +# define LZO_INFO_OS "win32" +#elif defined(__MWERKS__) && defined(__INTEL__) +# define LZO_OS_WIN32 1 +# define LZO_INFO_OS "win32" +#elif defined(__WINDOWS__) || defined(_WINDOWS) || defined(_Windows) +# if (UINT_MAX == LZO_0xffffL) +# define LZO_OS_WIN16 1 +# define LZO_INFO_OS "win16" +# elif (UINT_MAX == LZO_0xffffffffL) +# define LZO_OS_WIN32 1 +# define LZO_INFO_OS "win32" +# else +# error "check your limits.h header" +# endif +#elif defined(__DOS__) || defined(__MSDOS__) || defined(_MSDOS) || defined(MSDOS) || (defined(__PACIFIC__) && defined(DOS)) +# if (UINT_MAX == LZO_0xffffL) +# define LZO_OS_DOS16 1 +# define LZO_INFO_OS "dos16" +# elif (UINT_MAX == LZO_0xffffffffL) +# define LZO_OS_DOS32 1 +# define LZO_INFO_OS "dos32" +# else +# error "check your limits.h header" +# endif +#elif defined(__WATCOMC__) +# if defined(__NT__) && (UINT_MAX == LZO_0xffffL) +# define LZO_OS_DOS16 1 +# define LZO_INFO_OS "dos16" +# elif defined(__NT__) && (__WATCOMC__ < 1100) +# define LZO_OS_WIN32 1 +# define LZO_INFO_OS "win32" +# elif defined(__linux__) || defined(__LINUX__) +# define LZO_OS_POSIX 1 +# define LZO_INFO_OS "posix" +# else +# error "please specify a target using the -bt compiler option" +# endif +#elif defined(__palmos__) +# define LZO_OS_PALMOS 1 +# define LZO_INFO_OS "palmos" +#elif defined(__TOS__) || defined(__atarist__) +# define LZO_OS_TOS 1 +# define LZO_INFO_OS "tos" +#elif defined(macintosh) && !defined(__arm__) && !defined(__i386__) && !defined(__ppc__) && !defined(__x64_64__) +# define LZO_OS_MACCLASSIC 1 +# define LZO_INFO_OS "macclassic" +#elif defined(__VMS) +# define LZO_OS_VMS 1 +# define LZO_INFO_OS "vms" +#elif (defined(__mips__) && defined(__R5900__)) || defined(__MIPS_PSX2__) +# define LZO_OS_CONSOLE 1 +# define LZO_OS_CONSOLE_PS2 1 +# define LZO_INFO_OS "console" +# define LZO_INFO_OS_CONSOLE "ps2" +#elif defined(__mips__) && defined(__psp__) +# define LZO_OS_CONSOLE 1 +# define LZO_OS_CONSOLE_PSP 1 +# define LZO_INFO_OS "console" +# define LZO_INFO_OS_CONSOLE "psp" +#else +# define LZO_OS_POSIX 1 +# define LZO_INFO_OS "posix" +#endif +#if (LZO_OS_POSIX) +# if defined(_AIX) || defined(__AIX__) || defined(__aix__) +# define LZO_OS_POSIX_AIX 1 +# define LZO_INFO_OS_POSIX "aix" +# elif defined(__FreeBSD__) +# define LZO_OS_POSIX_FREEBSD 1 +# define LZO_INFO_OS_POSIX "freebsd" +# elif defined(__hpux__) || defined(__hpux) +# define LZO_OS_POSIX_HPUX 1 +# define LZO_INFO_OS_POSIX "hpux" +# elif defined(__INTERIX) +# define LZO_OS_POSIX_INTERIX 1 +# define LZO_INFO_OS_POSIX "interix" +# elif defined(__IRIX__) || defined(__irix__) +# define LZO_OS_POSIX_IRIX 1 +# define LZO_INFO_OS_POSIX "irix" +# elif defined(__linux__) || defined(__linux) || defined(__LINUX__) +# define LZO_OS_POSIX_LINUX 1 +# define LZO_INFO_OS_POSIX "linux" +# elif defined(__APPLE__) && defined(__MACH__) +# if ((__ENVIRONMENT_IPHONE_OS_VERSION_MIN_REQUIRED__-0) >= 20000) +# define LZO_OS_POSIX_DARWIN 1040 +# define LZO_INFO_OS_POSIX "darwin_iphone" +# elif ((__ENVIRONMENT_MAC_OS_X_VERSION_MIN_REQUIRED__-0) >= 1040) +# define LZO_OS_POSIX_DARWIN __ENVIRONMENT_MAC_OS_X_VERSION_MIN_REQUIRED__ +# define LZO_INFO_OS_POSIX "darwin" +# else +# define LZO_OS_POSIX_DARWIN 1 +# define LZO_INFO_OS_POSIX "darwin" +# endif +# define LZO_OS_POSIX_MACOSX LZO_OS_POSIX_DARWIN +# elif defined(__minix__) || defined(__minix) +# define LZO_OS_POSIX_MINIX 1 +# define LZO_INFO_OS_POSIX "minix" +# elif defined(__NetBSD__) +# define LZO_OS_POSIX_NETBSD 1 +# define LZO_INFO_OS_POSIX "netbsd" +# elif defined(__OpenBSD__) +# define LZO_OS_POSIX_OPENBSD 1 +# define LZO_INFO_OS_POSIX "openbsd" +# elif defined(__osf__) +# define LZO_OS_POSIX_OSF 1 +# define LZO_INFO_OS_POSIX "osf" +# elif defined(__solaris__) || defined(__sun) +# if defined(__SVR4) || defined(__svr4__) +# define LZO_OS_POSIX_SOLARIS 1 +# define LZO_INFO_OS_POSIX "solaris" +# else +# define LZO_OS_POSIX_SUNOS 1 +# define LZO_INFO_OS_POSIX "sunos" +# endif +# elif defined(__ultrix__) || defined(__ultrix) +# define LZO_OS_POSIX_ULTRIX 1 +# define LZO_INFO_OS_POSIX "ultrix" +# elif defined(_UNICOS) +# define LZO_OS_POSIX_UNICOS 1 +# define LZO_INFO_OS_POSIX "unicos" +# else +# define LZO_OS_POSIX_UNKNOWN 1 +# define LZO_INFO_OS_POSIX "unknown" +# endif +#endif +#endif +#if (LZO_OS_DOS16 || LZO_OS_OS216 || LZO_OS_WIN16) +# if (UINT_MAX != LZO_0xffffL) +# error "unexpected configuration - check your compiler defines" +# endif +# if (ULONG_MAX != LZO_0xffffffffL) +# error "unexpected configuration - check your compiler defines" +# endif +#endif +#if (LZO_OS_DOS32 || LZO_OS_OS2 || LZO_OS_WIN32 || LZO_OS_WIN64) +# if (UINT_MAX != LZO_0xffffffffL) +# error "unexpected configuration - check your compiler defines" +# endif +# if (ULONG_MAX != LZO_0xffffffffL) +# error "unexpected configuration - check your compiler defines" +# endif +#endif +#if defined(CIL) && defined(_GNUCC) && defined(__GNUC__) +# define LZO_CC_CILLY 1 +# define LZO_INFO_CC "Cilly" +# if defined(__CILLY__) +# define LZO_INFO_CCVER LZO_PP_MACRO_EXPAND(__CILLY__) +# else +# define LZO_INFO_CCVER "unknown" +# endif +#elif 0 && defined(SDCC) && defined(__VERSION__) && !defined(__GNUC__) +# define LZO_CC_SDCC 1 +# define LZO_INFO_CC "sdcc" +# define LZO_INFO_CCVER LZO_PP_MACRO_EXPAND(SDCC) +#elif defined(__PATHSCALE__) && defined(__PATHCC_PATCHLEVEL__) +# define LZO_CC_PATHSCALE (__PATHCC__ * 0x10000L + (__PATHCC_MINOR__-0) * 0x100 + (__PATHCC_PATCHLEVEL__-0)) +# define LZO_INFO_CC "Pathscale C" +# define LZO_INFO_CCVER __PATHSCALE__ +# if defined(__GNUC__) && defined(__GNUC_MINOR__) && defined(__VERSION__) +# define LZO_CC_PATHSCALE_GNUC (__GNUC__ * 0x10000L + (__GNUC_MINOR__-0) * 0x100 + (__GNUC_PATCHLEVEL__-0)) +# endif +#elif defined(__INTEL_COMPILER) && ((__INTEL_COMPILER-0) > 0) +# define LZO_CC_INTELC __INTEL_COMPILER +# define LZO_INFO_CC "Intel C" +# define LZO_INFO_CCVER LZO_PP_MACRO_EXPAND(__INTEL_COMPILER) +# if defined(_MSC_VER) && ((_MSC_VER-0) > 0) +# define LZO_CC_INTELC_MSC _MSC_VER +# elif defined(__GNUC__) && defined(__GNUC_MINOR__) && defined(__VERSION__) +# define LZO_CC_INTELC_GNUC (__GNUC__ * 0x10000L + (__GNUC_MINOR__-0) * 0x100 + (__GNUC_PATCHLEVEL__-0)) +# endif +#elif defined(__POCC__) && defined(_WIN32) +# define LZO_CC_PELLESC 1 +# define LZO_INFO_CC "Pelles C" +# define LZO_INFO_CCVER LZO_PP_MACRO_EXPAND(__POCC__) +#elif defined(__ARMCC_VERSION) && defined(__GNUC__) && defined(__GNUC_MINOR__) && defined(__VERSION__) +# if defined(__GNUC_PATCHLEVEL__) +# define LZO_CC_ARMCC_GNUC (__GNUC__ * 0x10000L + (__GNUC_MINOR__-0) * 0x100 + (__GNUC_PATCHLEVEL__-0)) +# else +# define LZO_CC_ARMCC_GNUC (__GNUC__ * 0x10000L + (__GNUC_MINOR__-0) * 0x100) +# endif +# define LZO_CC_ARMCC __ARMCC_VERSION +# define LZO_INFO_CC "ARM C Compiler" +# define LZO_INFO_CCVER __VERSION__ +#elif defined(__clang__) && defined(__c2__) && defined(__c2_version__) && defined(_MSC_VER) +# define LZO_CC_CLANG (__clang_major__ * 0x10000L + (__clang_minor__-0) * 0x100 + (__clang_patchlevel__-0)) +# define LZO_CC_CLANG_C2 _MSC_VER +# define LZO_CC_CLANG_VENDOR_MICROSOFT 1 +# define LZO_INFO_CC "clang/c2" +# define LZO_INFO_CCVER LZO_PP_MACRO_EXPAND(__c2_version__) +#elif defined(__clang__) && defined(__llvm__) && defined(__VERSION__) +# if defined(__clang_major__) && defined(__clang_minor__) && defined(__clang_patchlevel__) +# define LZO_CC_CLANG (__clang_major__ * 0x10000L + (__clang_minor__-0) * 0x100 + (__clang_patchlevel__-0)) +# else +# define LZO_CC_CLANG 0x010000L +# endif +# if defined(_MSC_VER) && ((_MSC_VER-0) > 0) +# define LZO_CC_CLANG_MSC _MSC_VER +# elif defined(__GNUC__) && defined(__GNUC_MINOR__) && defined(__VERSION__) +# define LZO_CC_CLANG_GNUC (__GNUC__ * 0x10000L + (__GNUC_MINOR__-0) * 0x100 + (__GNUC_PATCHLEVEL__-0)) +# endif +# if defined(__APPLE_CC__) +# define LZO_CC_CLANG_VENDOR_APPLE 1 +# define LZO_INFO_CC "clang/apple" +# else +# define LZO_CC_CLANG_VENDOR_LLVM 1 +# define LZO_INFO_CC "clang" +# endif +# if defined(__clang_version__) +# define LZO_INFO_CCVER __clang_version__ +# else +# define LZO_INFO_CCVER __VERSION__ +# endif +#elif defined(__llvm__) && defined(__GNUC__) && defined(__GNUC_MINOR__) && defined(__VERSION__) +# if defined(__GNUC_PATCHLEVEL__) +# define LZO_CC_LLVM_GNUC (__GNUC__ * 0x10000L + (__GNUC_MINOR__-0) * 0x100 + (__GNUC_PATCHLEVEL__-0)) +# else +# define LZO_CC_LLVM_GNUC (__GNUC__ * 0x10000L + (__GNUC_MINOR__-0) * 0x100) +# endif +# define LZO_CC_LLVM LZO_CC_LLVM_GNUC +# define LZO_INFO_CC "llvm-gcc" +# define LZO_INFO_CCVER __VERSION__ +#elif defined(__ACK__) && defined(_ACK) +# define LZO_CC_ACK 1 +# define LZO_INFO_CC "Amsterdam Compiler Kit C" +# define LZO_INFO_CCVER "unknown" +#elif defined(__ARMCC_VERSION) && !defined(__GNUC__) +# define LZO_CC_ARMCC __ARMCC_VERSION +# define LZO_CC_ARMCC_ARMCC __ARMCC_VERSION +# define LZO_INFO_CC "ARM C Compiler" +# define LZO_INFO_CCVER LZO_PP_MACRO_EXPAND(__ARMCC_VERSION) +#elif defined(__AZTEC_C__) +# define LZO_CC_AZTECC 1 +# define LZO_INFO_CC "Aztec C" +# define LZO_INFO_CCVER LZO_PP_MACRO_EXPAND(__AZTEC_C__) +#elif defined(__CODEGEARC__) +# define LZO_CC_CODEGEARC 1 +# define LZO_INFO_CC "CodeGear C" +# define LZO_INFO_CCVER LZO_PP_MACRO_EXPAND(__CODEGEARC__) +#elif defined(__BORLANDC__) +# define LZO_CC_BORLANDC 1 +# define LZO_INFO_CC "Borland C" +# define LZO_INFO_CCVER LZO_PP_MACRO_EXPAND(__BORLANDC__) +#elif defined(_CRAYC) && defined(_RELEASE) +# define LZO_CC_CRAYC 1 +# define LZO_INFO_CC "Cray C" +# define LZO_INFO_CCVER LZO_PP_MACRO_EXPAND(_RELEASE) +#elif defined(__DMC__) && defined(__SC__) +# define LZO_CC_DMC 1 +# define LZO_INFO_CC "Digital Mars C" +# define LZO_INFO_CCVER LZO_PP_MACRO_EXPAND(__DMC__) +#elif defined(__DECC) +# define LZO_CC_DECC 1 +# define LZO_INFO_CC "DEC C" +# define LZO_INFO_CCVER LZO_PP_MACRO_EXPAND(__DECC) +#elif (defined(__ghs) || defined(__ghs__)) && defined(__GHS_VERSION_NUMBER) && ((__GHS_VERSION_NUMBER-0) > 0) +# define LZO_CC_GHS 1 +# define LZO_INFO_CC "Green Hills C" +# define LZO_INFO_CCVER LZO_PP_MACRO_EXPAND(__GHS_VERSION_NUMBER) +# if defined(_MSC_VER) && ((_MSC_VER-0) > 0) +# define LZO_CC_GHS_MSC _MSC_VER +# elif defined(__GNUC__) && defined(__GNUC_MINOR__) && defined(__VERSION__) +# define LZO_CC_GHS_GNUC (__GNUC__ * 0x10000L + (__GNUC_MINOR__-0) * 0x100 + (__GNUC_PATCHLEVEL__-0)) +# endif +#elif defined(__HIGHC__) +# define LZO_CC_HIGHC 1 +# define LZO_INFO_CC "MetaWare High C" +# define LZO_INFO_CCVER "unknown" +#elif defined(__HP_aCC) && ((__HP_aCC-0) > 0) +# define LZO_CC_HPACC __HP_aCC +# define LZO_INFO_CC "HP aCC" +# define LZO_INFO_CCVER LZO_PP_MACRO_EXPAND(__HP_aCC) +#elif defined(__IAR_SYSTEMS_ICC__) +# define LZO_CC_IARC 1 +# define LZO_INFO_CC "IAR C" +# if defined(__VER__) +# define LZO_INFO_CCVER LZO_PP_MACRO_EXPAND(__VER__) +# else +# define LZO_INFO_CCVER "unknown" +# endif +#elif defined(__IBMC__) && ((__IBMC__-0) > 0) +# define LZO_CC_IBMC __IBMC__ +# define LZO_INFO_CC "IBM C" +# define LZO_INFO_CCVER LZO_PP_MACRO_EXPAND(__IBMC__) +#elif defined(__IBMCPP__) && ((__IBMCPP__-0) > 0) +# define LZO_CC_IBMC __IBMCPP__ +# define LZO_INFO_CC "IBM C" +# define LZO_INFO_CCVER LZO_PP_MACRO_EXPAND(__IBMCPP__) +#elif defined(__KEIL__) && defined(__C166__) +# define LZO_CC_KEILC 1 +# define LZO_INFO_CC "Keil C" +# define LZO_INFO_CCVER LZO_PP_MACRO_EXPAND(__C166__) +#elif defined(__LCC__) && defined(_WIN32) && defined(__LCCOPTIMLEVEL) +# define LZO_CC_LCCWIN32 1 +# define LZO_INFO_CC "lcc-win32" +# define LZO_INFO_CCVER "unknown" +#elif defined(__LCC__) +# define LZO_CC_LCC 1 +# define LZO_INFO_CC "lcc" +# if defined(__LCC_VERSION__) +# define LZO_INFO_CCVER LZO_PP_MACRO_EXPAND(__LCC_VERSION__) +# else +# define LZO_INFO_CCVER "unknown" +# endif +#elif defined(__MWERKS__) && ((__MWERKS__-0) > 0) +# define LZO_CC_MWERKS __MWERKS__ +# define LZO_INFO_CC "Metrowerks C" +# define LZO_INFO_CCVER LZO_PP_MACRO_EXPAND(__MWERKS__) +#elif (defined(__NDPC__) || defined(__NDPX__)) && defined(__i386) +# define LZO_CC_NDPC 1 +# define LZO_INFO_CC "Microway NDP C" +# define LZO_INFO_CCVER "unknown" +#elif defined(__PACIFIC__) +# define LZO_CC_PACIFICC 1 +# define LZO_INFO_CC "Pacific C" +# define LZO_INFO_CCVER LZO_PP_MACRO_EXPAND(__PACIFIC__) +#elif defined(__PGI) && defined(__PGIC__) && defined(__PGIC_MINOR__) +# if defined(__PGIC_PATCHLEVEL__) +# define LZO_CC_PGI (__PGIC__ * 0x10000L + (__PGIC_MINOR__-0) * 0x100 + (__PGIC_PATCHLEVEL__-0)) +# define LZO_INFO_CCVER LZO_PP_MACRO_EXPAND(__PGIC__) "." LZO_PP_MACRO_EXPAND(__PGIC_MINOR__) "." LZO_PP_MACRO_EXPAND(__PGIC_PATCHLEVEL__) +# else +# define LZO_CC_PGI (__PGIC__ * 0x10000L + (__PGIC_MINOR__-0) * 0x100) +# define LZO_INFO_CCVER LZO_PP_MACRO_EXPAND(__PGIC__) "." LZO_PP_MACRO_EXPAND(__PGIC_MINOR__) ".0" +# endif +# define LZO_INFO_CC "Portland Group PGI C" +#elif defined(__PGI) && (defined(__linux__) || defined(__WIN32__)) +# define LZO_CC_PGI 1 +# define LZO_INFO_CC "Portland Group PGI C" +# define LZO_INFO_CCVER "unknown" +#elif defined(__PUREC__) && defined(__TOS__) +# define LZO_CC_PUREC 1 +# define LZO_INFO_CC "Pure C" +# define LZO_INFO_CCVER LZO_PP_MACRO_EXPAND(__PUREC__) +#elif defined(__SC__) && defined(__ZTC__) +# define LZO_CC_SYMANTECC 1 +# define LZO_INFO_CC "Symantec C" +# define LZO_INFO_CCVER LZO_PP_MACRO_EXPAND(__SC__) +#elif defined(__SUNPRO_C) +# define LZO_INFO_CC "SunPro C" +# if ((__SUNPRO_C-0) > 0) +# define LZO_CC_SUNPROC __SUNPRO_C +# define LZO_INFO_CCVER LZO_PP_MACRO_EXPAND(__SUNPRO_C) +# else +# define LZO_CC_SUNPROC 1 +# define LZO_INFO_CCVER "unknown" +# endif +#elif defined(__SUNPRO_CC) +# define LZO_INFO_CC "SunPro C" +# if ((__SUNPRO_CC-0) > 0) +# define LZO_CC_SUNPROC __SUNPRO_CC +# define LZO_INFO_CCVER LZO_PP_MACRO_EXPAND(__SUNPRO_CC) +# else +# define LZO_CC_SUNPROC 1 +# define LZO_INFO_CCVER "unknown" +# endif +#elif defined(__TINYC__) +# define LZO_CC_TINYC 1 +# define LZO_INFO_CC "Tiny C" +# define LZO_INFO_CCVER LZO_PP_MACRO_EXPAND(__TINYC__) +#elif defined(__TSC__) +# define LZO_CC_TOPSPEEDC 1 +# define LZO_INFO_CC "TopSpeed C" +# define LZO_INFO_CCVER LZO_PP_MACRO_EXPAND(__TSC__) +#elif defined(__WATCOMC__) +# define LZO_CC_WATCOMC 1 +# define LZO_INFO_CC "Watcom C" +# define LZO_INFO_CCVER LZO_PP_MACRO_EXPAND(__WATCOMC__) +#elif defined(__TURBOC__) +# define LZO_CC_TURBOC 1 +# define LZO_INFO_CC "Turbo C" +# define LZO_INFO_CCVER LZO_PP_MACRO_EXPAND(__TURBOC__) +#elif defined(__ZTC__) +# define LZO_CC_ZORTECHC 1 +# define LZO_INFO_CC "Zortech C" +# if ((__ZTC__-0) == 0x310) +# define LZO_INFO_CCVER "0x310" +# else +# define LZO_INFO_CCVER LZO_PP_MACRO_EXPAND(__ZTC__) +# endif +#elif defined(__GNUC__) && defined(__VERSION__) +# if defined(__GNUC_MINOR__) && defined(__GNUC_PATCHLEVEL__) +# define LZO_CC_GNUC (__GNUC__ * 0x10000L + (__GNUC_MINOR__-0) * 0x100 + (__GNUC_PATCHLEVEL__-0)) +# elif defined(__GNUC_MINOR__) +# define LZO_CC_GNUC (__GNUC__ * 0x10000L + (__GNUC_MINOR__-0) * 0x100) +# else +# define LZO_CC_GNUC (__GNUC__ * 0x10000L) +# endif +# define LZO_INFO_CC "gcc" +# define LZO_INFO_CCVER __VERSION__ +#elif defined(_MSC_VER) && ((_MSC_VER-0) > 0) +# define LZO_CC_MSC _MSC_VER +# define LZO_INFO_CC "Microsoft C" +# if defined(_MSC_FULL_VER) +# define LZO_INFO_CCVER LZO_PP_MACRO_EXPAND(_MSC_VER) "." LZO_PP_MACRO_EXPAND(_MSC_FULL_VER) +# else +# define LZO_INFO_CCVER LZO_PP_MACRO_EXPAND(_MSC_VER) +# endif +#else +# define LZO_CC_UNKNOWN 1 +# define LZO_INFO_CC "unknown" +# define LZO_INFO_CCVER "unknown" +#endif +#if (LZO_CC_GNUC) && defined(__OPEN64__) +# if defined(__OPENCC__) && defined(__OPENCC_MINOR__) && defined(__OPENCC_PATCHLEVEL__) +# define LZO_CC_OPEN64 (__OPENCC__ * 0x10000L + (__OPENCC_MINOR__-0) * 0x100 + (__OPENCC_PATCHLEVEL__-0)) +# define LZO_CC_OPEN64_GNUC LZO_CC_GNUC +# endif +#endif +#if (LZO_CC_GNUC) && defined(__PCC__) +# if defined(__PCC__) && defined(__PCC_MINOR__) && defined(__PCC_MINORMINOR__) +# define LZO_CC_PCC (__PCC__ * 0x10000L + (__PCC_MINOR__-0) * 0x100 + (__PCC_MINORMINOR__-0)) +# define LZO_CC_PCC_GNUC LZO_CC_GNUC +# endif +#endif +#if 0 && (LZO_CC_MSC && (_MSC_VER >= 1200)) && !defined(_MSC_FULL_VER) +# error "LZO_CC_MSC: _MSC_FULL_VER is not defined" +#endif +#if !defined(__LZO_ARCH_OVERRIDE) && !(LZO_ARCH_GENERIC) && defined(_CRAY) +# if (UINT_MAX > LZO_0xffffffffL) && defined(_CRAY) +# if defined(_CRAYMPP) || defined(_CRAYT3D) || defined(_CRAYT3E) +# define LZO_ARCH_CRAY_MPP 1 +# elif defined(_CRAY1) +# define LZO_ARCH_CRAY_PVP 1 +# endif +# endif +#endif +#if !defined(__LZO_ARCH_OVERRIDE) +#if (LZO_ARCH_GENERIC) +# define LZO_INFO_ARCH "generic" +#elif (LZO_OS_DOS16 || LZO_OS_OS216 || LZO_OS_WIN16) +# define LZO_ARCH_I086 1 +# define LZO_INFO_ARCH "i086" +#elif defined(__aarch64__) || defined(_M_ARM64) +# define LZO_ARCH_ARM64 1 +# define LZO_INFO_ARCH "arm64" +#elif defined(__alpha__) || defined(__alpha) || defined(_M_ALPHA) +# define LZO_ARCH_ALPHA 1 +# define LZO_INFO_ARCH "alpha" +#elif (LZO_ARCH_CRAY_MPP) && (defined(_CRAYT3D) || defined(_CRAYT3E)) +# define LZO_ARCH_ALPHA 1 +# define LZO_INFO_ARCH "alpha" +#elif defined(__amd64__) || defined(__x86_64__) || defined(_M_AMD64) +# define LZO_ARCH_AMD64 1 +# define LZO_INFO_ARCH "amd64" +#elif defined(__arm__) || defined(_M_ARM) +# define LZO_ARCH_ARM 1 +# define LZO_INFO_ARCH "arm" +#elif defined(__IAR_SYSTEMS_ICC__) && defined(__ICCARM__) +# define LZO_ARCH_ARM 1 +# define LZO_INFO_ARCH "arm" +#elif (UINT_MAX <= LZO_0xffffL) && defined(__AVR__) +# define LZO_ARCH_AVR 1 +# define LZO_INFO_ARCH "avr" +#elif defined(__avr32__) || defined(__AVR32__) +# define LZO_ARCH_AVR32 1 +# define LZO_INFO_ARCH "avr32" +#elif defined(__bfin__) +# define LZO_ARCH_BLACKFIN 1 +# define LZO_INFO_ARCH "blackfin" +#elif (UINT_MAX == LZO_0xffffL) && defined(__C166__) +# define LZO_ARCH_C166 1 +# define LZO_INFO_ARCH "c166" +#elif defined(__cris__) +# define LZO_ARCH_CRIS 1 +# define LZO_INFO_ARCH "cris" +#elif defined(__IAR_SYSTEMS_ICC__) && defined(__ICCEZ80__) +# define LZO_ARCH_EZ80 1 +# define LZO_INFO_ARCH "ez80" +#elif defined(__H8300__) || defined(__H8300H__) || defined(__H8300S__) || defined(__H8300SX__) +# define LZO_ARCH_H8300 1 +# define LZO_INFO_ARCH "h8300" +#elif defined(__hppa__) || defined(__hppa) +# define LZO_ARCH_HPPA 1 +# define LZO_INFO_ARCH "hppa" +#elif defined(__386__) || defined(__i386__) || defined(__i386) || defined(_M_IX86) || defined(_M_I386) +# define LZO_ARCH_I386 1 +# define LZO_ARCH_IA32 1 +# define LZO_INFO_ARCH "i386" +#elif (LZO_CC_ZORTECHC && defined(__I86__)) +# define LZO_ARCH_I386 1 +# define LZO_ARCH_IA32 1 +# define LZO_INFO_ARCH "i386" +#elif (LZO_OS_DOS32 && LZO_CC_HIGHC) && defined(_I386) +# define LZO_ARCH_I386 1 +# define LZO_ARCH_IA32 1 +# define LZO_INFO_ARCH "i386" +#elif defined(__ia64__) || defined(__ia64) || defined(_M_IA64) +# define LZO_ARCH_IA64 1 +# define LZO_INFO_ARCH "ia64" +#elif (UINT_MAX == LZO_0xffffL) && defined(__m32c__) +# define LZO_ARCH_M16C 1 +# define LZO_INFO_ARCH "m16c" +#elif defined(__IAR_SYSTEMS_ICC__) && defined(__ICCM16C__) +# define LZO_ARCH_M16C 1 +# define LZO_INFO_ARCH "m16c" +#elif defined(__m32r__) +# define LZO_ARCH_M32R 1 +# define LZO_INFO_ARCH "m32r" +#elif (LZO_OS_TOS) || defined(__m68k__) || defined(__m68000__) || defined(__mc68000__) || defined(__mc68020__) || defined(_M_M68K) +# define LZO_ARCH_M68K 1 +# define LZO_INFO_ARCH "m68k" +#elif (UINT_MAX == LZO_0xffffL) && defined(__C251__) +# define LZO_ARCH_MCS251 1 +# define LZO_INFO_ARCH "mcs251" +#elif (UINT_MAX == LZO_0xffffL) && defined(__C51__) +# define LZO_ARCH_MCS51 1 +# define LZO_INFO_ARCH "mcs51" +#elif defined(__IAR_SYSTEMS_ICC__) && defined(__ICC8051__) +# define LZO_ARCH_MCS51 1 +# define LZO_INFO_ARCH "mcs51" +#elif defined(__mips__) || defined(__mips) || defined(_MIPS_ARCH) || defined(_M_MRX000) +# define LZO_ARCH_MIPS 1 +# define LZO_INFO_ARCH "mips" +#elif (UINT_MAX == LZO_0xffffL) && defined(__MSP430__) +# define LZO_ARCH_MSP430 1 +# define LZO_INFO_ARCH "msp430" +#elif defined(__IAR_SYSTEMS_ICC__) && defined(__ICC430__) +# define LZO_ARCH_MSP430 1 +# define LZO_INFO_ARCH "msp430" +#elif defined(__powerpc__) || defined(__powerpc) || defined(__ppc__) || defined(__PPC__) || defined(_M_PPC) || defined(_ARCH_PPC) || defined(_ARCH_PWR) +# define LZO_ARCH_POWERPC 1 +# define LZO_INFO_ARCH "powerpc" +#elif defined(__powerpc64__) || defined(__powerpc64) || defined(__ppc64__) || defined(__PPC64__) +# define LZO_ARCH_POWERPC 1 +# define LZO_INFO_ARCH "powerpc" +#elif defined(__powerpc64le__) || defined(__powerpc64le) || defined(__ppc64le__) || defined(__PPC64LE__) +# define LZO_ARCH_POWERPC 1 +# define LZO_INFO_ARCH "powerpc" +#elif defined(__riscv) +# define LZO_ARCH_RISCV 1 +# define LZO_INFO_ARCH "riscv" +#elif defined(__s390__) || defined(__s390) || defined(__s390x__) || defined(__s390x) +# define LZO_ARCH_S390 1 +# define LZO_INFO_ARCH "s390" +#elif defined(__sh__) || defined(_M_SH) +# define LZO_ARCH_SH 1 +# define LZO_INFO_ARCH "sh" +#elif defined(__sparc__) || defined(__sparc) || defined(__sparcv8) +# define LZO_ARCH_SPARC 1 +# define LZO_INFO_ARCH "sparc" +#elif defined(__SPU__) +# define LZO_ARCH_SPU 1 +# define LZO_INFO_ARCH "spu" +#elif (UINT_MAX == LZO_0xffffL) && defined(__z80) +# define LZO_ARCH_Z80 1 +# define LZO_INFO_ARCH "z80" +#elif (LZO_ARCH_CRAY_PVP) +# if defined(_CRAYSV1) +# define LZO_ARCH_CRAY_SV1 1 +# define LZO_INFO_ARCH "cray_sv1" +# elif (_ADDR64) +# define LZO_ARCH_CRAY_T90 1 +# define LZO_INFO_ARCH "cray_t90" +# elif (_ADDR32) +# define LZO_ARCH_CRAY_YMP 1 +# define LZO_INFO_ARCH "cray_ymp" +# else +# define LZO_ARCH_CRAY_XMP 1 +# define LZO_INFO_ARCH "cray_xmp" +# endif +#else +# define LZO_ARCH_UNKNOWN 1 +# define LZO_INFO_ARCH "unknown" +#endif +#endif +#if !defined(LZO_ARCH_ARM_THUMB2) +#if (LZO_ARCH_ARM) +# if defined(__thumb__) || defined(__thumb) || defined(_M_THUMB) +# if defined(__thumb2__) +# define LZO_ARCH_ARM_THUMB2 1 +# elif 1 && defined(__TARGET_ARCH_THUMB) && ((__TARGET_ARCH_THUMB)+0 >= 4) +# define LZO_ARCH_ARM_THUMB2 1 +# elif 1 && defined(_MSC_VER) && defined(_M_THUMB) && ((_M_THUMB)+0 >= 7) +# define LZO_ARCH_ARM_THUMB2 1 +# endif +# endif +#endif +#endif +#if (LZO_ARCH_ARM_THUMB2) +# undef LZO_INFO_ARCH +# define LZO_INFO_ARCH "arm_thumb2" +#endif +#if 1 && (LZO_ARCH_UNKNOWN) && (LZO_OS_DOS32 || LZO_OS_OS2) +# error "FIXME - missing define for CPU architecture" +#endif +#if 1 && (LZO_ARCH_UNKNOWN) && (LZO_OS_WIN32) +# error "FIXME - missing LZO_OS_WIN32 define for CPU architecture" +#endif +#if 1 && (LZO_ARCH_UNKNOWN) && (LZO_OS_WIN64) +# error "FIXME - missing LZO_OS_WIN64 define for CPU architecture" +#endif +#if (LZO_OS_OS216 || LZO_OS_WIN16) +# define LZO_ARCH_I086PM 1 +#elif 1 && (LZO_OS_DOS16 && defined(BLX286)) +# define LZO_ARCH_I086PM 1 +#elif 1 && (LZO_OS_DOS16 && defined(DOSX286)) +# define LZO_ARCH_I086PM 1 +#elif 1 && (LZO_OS_DOS16 && LZO_CC_BORLANDC && defined(__DPMI16__)) +# define LZO_ARCH_I086PM 1 +#endif +#if (LZO_ARCH_AMD64 && !LZO_ARCH_X64) +# define LZO_ARCH_X64 1 +#elif (!LZO_ARCH_AMD64 && LZO_ARCH_X64) && defined(__LZO_ARCH_OVERRIDE) +# define LZO_ARCH_AMD64 1 +#endif +#if (LZO_ARCH_ARM64 && !LZO_ARCH_AARCH64) +# define LZO_ARCH_AARCH64 1 +#elif (!LZO_ARCH_ARM64 && LZO_ARCH_AARCH64) && defined(__LZO_ARCH_OVERRIDE) +# define LZO_ARCH_ARM64 1 +#endif +#if (LZO_ARCH_I386 && !LZO_ARCH_X86) +# define LZO_ARCH_X86 1 +#elif (!LZO_ARCH_I386 && LZO_ARCH_X86) && defined(__LZO_ARCH_OVERRIDE) +# define LZO_ARCH_I386 1 +#endif +#if (LZO_ARCH_AMD64 && !LZO_ARCH_X64) || (!LZO_ARCH_AMD64 && LZO_ARCH_X64) +# error "unexpected configuration - check your compiler defines" +#endif +#if (LZO_ARCH_ARM64 && !LZO_ARCH_AARCH64) || (!LZO_ARCH_ARM64 && LZO_ARCH_AARCH64) +# error "unexpected configuration - check your compiler defines" +#endif +#if (LZO_ARCH_I386 && !LZO_ARCH_X86) || (!LZO_ARCH_I386 && LZO_ARCH_X86) +# error "unexpected configuration - check your compiler defines" +#endif +#if (LZO_ARCH_ARM_THUMB1 && !LZO_ARCH_ARM) +# error "unexpected configuration - check your compiler defines" +#endif +#if (LZO_ARCH_ARM_THUMB2 && !LZO_ARCH_ARM) +# error "unexpected configuration - check your compiler defines" +#endif +#if (LZO_ARCH_ARM_THUMB1 && LZO_ARCH_ARM_THUMB2) +# error "unexpected configuration - check your compiler defines" +#endif +#if (LZO_ARCH_I086PM && !LZO_ARCH_I086) +# error "unexpected configuration - check your compiler defines" +#endif +#if (LZO_ARCH_I086) +# if (UINT_MAX != LZO_0xffffL) +# error "unexpected configuration - check your compiler defines" +# endif +# if (ULONG_MAX != LZO_0xffffffffL) +# error "unexpected configuration - check your compiler defines" +# endif +#endif +#if (LZO_ARCH_I386) +# if (UINT_MAX != LZO_0xffffL) && defined(__i386_int16__) +# error "unexpected configuration - check your compiler defines" +# endif +# if (UINT_MAX != LZO_0xffffffffL) && !defined(__i386_int16__) +# error "unexpected configuration - check your compiler defines" +# endif +# if (ULONG_MAX != LZO_0xffffffffL) +# error "unexpected configuration - check your compiler defines" +# endif +#endif +#if (LZO_ARCH_AMD64 || LZO_ARCH_I386) +# if !defined(LZO_TARGET_FEATURE_SSE2) +# if defined(__SSE2__) +# define LZO_TARGET_FEATURE_SSE2 1 +# elif defined(_MSC_VER) && (defined(_M_IX86_FP) && ((_M_IX86_FP)+0 >= 2)) +# define LZO_TARGET_FEATURE_SSE2 1 +# elif (LZO_CC_INTELC_MSC || LZO_CC_MSC) && defined(_M_AMD64) +# define LZO_TARGET_FEATURE_SSE2 1 +# endif +# endif +# if !defined(LZO_TARGET_FEATURE_SSSE3) +# if (LZO_TARGET_FEATURE_SSE2) +# if defined(__SSSE3__) +# define LZO_TARGET_FEATURE_SSSE3 1 +# elif defined(_MSC_VER) && defined(__AVX__) +# define LZO_TARGET_FEATURE_SSSE3 1 +# endif +# endif +# endif +# if !defined(LZO_TARGET_FEATURE_SSE4_2) +# if (LZO_TARGET_FEATURE_SSSE3) +# if defined(__SSE4_2__) +# define LZO_TARGET_FEATURE_SSE4_2 1 +# endif +# endif +# endif +# if !defined(LZO_TARGET_FEATURE_AVX) +# if (LZO_TARGET_FEATURE_SSSE3) +# if defined(__AVX__) +# define LZO_TARGET_FEATURE_AVX 1 +# endif +# endif +# endif +# if !defined(LZO_TARGET_FEATURE_AVX2) +# if (LZO_TARGET_FEATURE_AVX) +# if defined(__AVX2__) +# define LZO_TARGET_FEATURE_AVX2 1 +# endif +# endif +# endif +#endif +#if (LZO_TARGET_FEATURE_SSSE3 && !(LZO_TARGET_FEATURE_SSE2)) +# error "unexpected configuration - check your compiler defines" +#endif +#if (LZO_TARGET_FEATURE_SSE4_2 && !(LZO_TARGET_FEATURE_SSSE3)) +# error "unexpected configuration - check your compiler defines" +#endif +#if (LZO_TARGET_FEATURE_AVX && !(LZO_TARGET_FEATURE_SSSE3)) +# error "unexpected configuration - check your compiler defines" +#endif +#if (LZO_TARGET_FEATURE_AVX2 && !(LZO_TARGET_FEATURE_AVX)) +# error "unexpected configuration - check your compiler defines" +#endif +#if (LZO_ARCH_ARM) +# if !defined(LZO_TARGET_FEATURE_NEON) +# if defined(__ARM_NEON) && ((__ARM_NEON)+0) +# define LZO_TARGET_FEATURE_NEON 1 +# elif 1 && defined(__ARM_NEON__) && ((__ARM_NEON__)+0) +# define LZO_TARGET_FEATURE_NEON 1 +# elif 1 && defined(__TARGET_FEATURE_NEON) && ((__TARGET_FEATURE_NEON)+0) +# define LZO_TARGET_FEATURE_NEON 1 +# endif +# endif +#elif (LZO_ARCH_ARM64) +# if !defined(LZO_TARGET_FEATURE_NEON) +# if 1 +# define LZO_TARGET_FEATURE_NEON 1 +# endif +# endif +#endif +#if 0 +#elif !defined(__LZO_MM_OVERRIDE) +#if (LZO_ARCH_I086) +#if (UINT_MAX != LZO_0xffffL) +# error "unexpected configuration - check your compiler defines" +#endif +#if defined(__TINY__) || defined(M_I86TM) || defined(_M_I86TM) +# define LZO_MM_TINY 1 +#elif defined(__HUGE__) || defined(_HUGE_) || defined(M_I86HM) || defined(_M_I86HM) +# define LZO_MM_HUGE 1 +#elif defined(__SMALL__) || defined(M_I86SM) || defined(_M_I86SM) || defined(SMALL_MODEL) +# define LZO_MM_SMALL 1 +#elif defined(__MEDIUM__) || defined(M_I86MM) || defined(_M_I86MM) +# define LZO_MM_MEDIUM 1 +#elif defined(__COMPACT__) || defined(M_I86CM) || defined(_M_I86CM) +# define LZO_MM_COMPACT 1 +#elif defined(__LARGE__) || defined(M_I86LM) || defined(_M_I86LM) || defined(LARGE_MODEL) +# define LZO_MM_LARGE 1 +#elif (LZO_CC_AZTECC) +# if defined(_LARGE_CODE) && defined(_LARGE_DATA) +# define LZO_MM_LARGE 1 +# elif defined(_LARGE_CODE) +# define LZO_MM_MEDIUM 1 +# elif defined(_LARGE_DATA) +# define LZO_MM_COMPACT 1 +# else +# define LZO_MM_SMALL 1 +# endif +#elif (LZO_CC_ZORTECHC && defined(__VCM__)) +# define LZO_MM_LARGE 1 +#else +# error "unknown LZO_ARCH_I086 memory model" +#endif +#if (LZO_OS_DOS16 || LZO_OS_OS216 || LZO_OS_WIN16) +#define LZO_HAVE_MM_HUGE_PTR 1 +#define LZO_HAVE_MM_HUGE_ARRAY 1 +#if (LZO_MM_TINY) +# undef LZO_HAVE_MM_HUGE_ARRAY +#endif +#if (LZO_CC_AZTECC || LZO_CC_PACIFICC || LZO_CC_ZORTECHC) +# undef LZO_HAVE_MM_HUGE_PTR +# undef LZO_HAVE_MM_HUGE_ARRAY +#elif (LZO_CC_DMC || LZO_CC_SYMANTECC) +# undef LZO_HAVE_MM_HUGE_ARRAY +#elif (LZO_CC_MSC && defined(_QC)) +# undef LZO_HAVE_MM_HUGE_ARRAY +# if (_MSC_VER < 600) +# undef LZO_HAVE_MM_HUGE_PTR +# endif +#elif (LZO_CC_TURBOC && (__TURBOC__ < 0x0295)) +# undef LZO_HAVE_MM_HUGE_ARRAY +#endif +#if (LZO_ARCH_I086PM) && !(LZO_HAVE_MM_HUGE_PTR) +# if (LZO_OS_DOS16) +# error "unexpected configuration - check your compiler defines" +# elif (LZO_CC_ZORTECHC) +# else +# error "unexpected configuration - check your compiler defines" +# endif +#endif +#if defined(__cplusplus) +extern "C" { +#endif +#if (LZO_CC_BORLANDC && (__BORLANDC__ >= 0x0200)) + extern void __near __cdecl _AHSHIFT(void); +# define LZO_MM_AHSHIFT ((unsigned) _AHSHIFT) +#elif (LZO_CC_DMC || LZO_CC_SYMANTECC || LZO_CC_ZORTECHC) + extern void __near __cdecl _AHSHIFT(void); +# define LZO_MM_AHSHIFT ((unsigned) _AHSHIFT) +#elif (LZO_CC_MSC || LZO_CC_TOPSPEEDC) + extern void __near __cdecl _AHSHIFT(void); +# define LZO_MM_AHSHIFT ((unsigned) _AHSHIFT) +#elif (LZO_CC_TURBOC && (__TURBOC__ >= 0x0295)) + extern void __near __cdecl _AHSHIFT(void); +# define LZO_MM_AHSHIFT ((unsigned) _AHSHIFT) +#elif ((LZO_CC_AZTECC || LZO_CC_PACIFICC || LZO_CC_TURBOC) && LZO_OS_DOS16) +# define LZO_MM_AHSHIFT 12 +#elif (LZO_CC_WATCOMC) + extern unsigned char _HShift; +# define LZO_MM_AHSHIFT ((unsigned) _HShift) +#else +# error "FIXME - implement LZO_MM_AHSHIFT" +#endif +#if defined(__cplusplus) +} +#endif +#endif +#elif (LZO_ARCH_C166) +#if !defined(__MODEL__) +# error "FIXME - LZO_ARCH_C166 __MODEL__" +#elif ((__MODEL__) == 0) +# define LZO_MM_SMALL 1 +#elif ((__MODEL__) == 1) +# define LZO_MM_SMALL 1 +#elif ((__MODEL__) == 2) +# define LZO_MM_LARGE 1 +#elif ((__MODEL__) == 3) +# define LZO_MM_TINY 1 +#elif ((__MODEL__) == 4) +# define LZO_MM_XTINY 1 +#elif ((__MODEL__) == 5) +# define LZO_MM_XSMALL 1 +#else +# error "FIXME - LZO_ARCH_C166 __MODEL__" +#endif +#elif (LZO_ARCH_MCS251) +#if !defined(__MODEL__) +# error "FIXME - LZO_ARCH_MCS251 __MODEL__" +#elif ((__MODEL__) == 0) +# define LZO_MM_SMALL 1 +#elif ((__MODEL__) == 2) +# define LZO_MM_LARGE 1 +#elif ((__MODEL__) == 3) +# define LZO_MM_TINY 1 +#elif ((__MODEL__) == 4) +# define LZO_MM_XTINY 1 +#elif ((__MODEL__) == 5) +# define LZO_MM_XSMALL 1 +#else +# error "FIXME - LZO_ARCH_MCS251 __MODEL__" +#endif +#elif (LZO_ARCH_MCS51) +#if !defined(__MODEL__) +# error "FIXME - LZO_ARCH_MCS51 __MODEL__" +#elif ((__MODEL__) == 1) +# define LZO_MM_SMALL 1 +#elif ((__MODEL__) == 2) +# define LZO_MM_LARGE 1 +#elif ((__MODEL__) == 3) +# define LZO_MM_TINY 1 +#elif ((__MODEL__) == 4) +# define LZO_MM_XTINY 1 +#elif ((__MODEL__) == 5) +# define LZO_MM_XSMALL 1 +#else +# error "FIXME - LZO_ARCH_MCS51 __MODEL__" +#endif +#elif (LZO_ARCH_CRAY_PVP) +# define LZO_MM_PVP 1 +#else +# define LZO_MM_FLAT 1 +#endif +#if (LZO_MM_COMPACT) +# define LZO_INFO_MM "compact" +#elif (LZO_MM_FLAT) +# define LZO_INFO_MM "flat" +#elif (LZO_MM_HUGE) +# define LZO_INFO_MM "huge" +#elif (LZO_MM_LARGE) +# define LZO_INFO_MM "large" +#elif (LZO_MM_MEDIUM) +# define LZO_INFO_MM "medium" +#elif (LZO_MM_PVP) +# define LZO_INFO_MM "pvp" +#elif (LZO_MM_SMALL) +# define LZO_INFO_MM "small" +#elif (LZO_MM_TINY) +# define LZO_INFO_MM "tiny" +#else +# error "unknown memory model" +#endif +#endif +#if !defined(__lzo_gnuc_extension__) +#if (LZO_CC_GNUC >= 0x020800ul) +# define __lzo_gnuc_extension__ __extension__ +#elif (LZO_CC_ARMCC_GNUC || LZO_CC_CLANG || LZO_CC_LLVM || LZO_CC_PATHSCALE) +# define __lzo_gnuc_extension__ __extension__ +#elif (LZO_CC_IBMC >= 600) +# define __lzo_gnuc_extension__ __extension__ +#endif +#endif +#if !defined(__lzo_gnuc_extension__) +# define __lzo_gnuc_extension__ /*empty*/ +#endif +#if !defined(lzo_has_builtin) +#if (LZO_CC_CLANG) && defined(__has_builtin) +# define lzo_has_builtin __has_builtin +#endif +#endif +#if !defined(lzo_has_builtin) +# define lzo_has_builtin(x) 0 +#endif +#if !defined(lzo_has_attribute) +#if (LZO_CC_CLANG) && defined(__has_attribute) +# define lzo_has_attribute __has_attribute +#endif +#endif +#if !defined(lzo_has_attribute) +# define lzo_has_attribute(x) 0 +#endif +#if !defined(lzo_has_declspec_attribute) +#if (LZO_CC_CLANG) && defined(__has_declspec_attribute) +# define lzo_has_declspec_attribute __has_declspec_attribute +#endif +#endif +#if !defined(lzo_has_declspec_attribute) +# define lzo_has_declspec_attribute(x) 0 +#endif +#if !defined(lzo_has_feature) +#if (LZO_CC_CLANG) && defined(__has_feature) +# define lzo_has_feature __has_feature +#endif +#endif +#if !defined(lzo_has_feature) +# define lzo_has_feature(x) 0 +#endif +#if !defined(lzo_has_extension) +#if (LZO_CC_CLANG) && defined(__has_extension) +# define lzo_has_extension __has_extension +#elif (LZO_CC_CLANG) && defined(__has_feature) +# define lzo_has_extension __has_feature +#endif +#endif +#if !defined(lzo_has_extension) +# define lzo_has_extension(x) 0 +#endif +#if !defined(LZO_CFG_USE_NEW_STYLE_CASTS) && defined(__cplusplus) && 0 +# if (LZO_CC_GNUC && (LZO_CC_GNUC < 0x020800ul)) +# define LZO_CFG_USE_NEW_STYLE_CASTS 0 +# elif (LZO_CC_INTELC && (__INTEL_COMPILER < 1200)) +# define LZO_CFG_USE_NEW_STYLE_CASTS 0 +# else +# define LZO_CFG_USE_NEW_STYLE_CASTS 1 +# endif +#endif +#if !defined(LZO_CFG_USE_NEW_STYLE_CASTS) +# define LZO_CFG_USE_NEW_STYLE_CASTS 0 +#endif +#if !defined(__cplusplus) +# if defined(LZO_CFG_USE_NEW_STYLE_CASTS) +# undef LZO_CFG_USE_NEW_STYLE_CASTS +# endif +# define LZO_CFG_USE_NEW_STYLE_CASTS 0 +#endif +#if !defined(LZO_REINTERPRET_CAST) +# if (LZO_CFG_USE_NEW_STYLE_CASTS) +# define LZO_REINTERPRET_CAST(t,e) (reinterpret_cast (e)) +# endif +#endif +#if !defined(LZO_REINTERPRET_CAST) +# define LZO_REINTERPRET_CAST(t,e) ((t) (e)) +#endif +#if !defined(LZO_STATIC_CAST) +# if (LZO_CFG_USE_NEW_STYLE_CASTS) +# define LZO_STATIC_CAST(t,e) (static_cast (e)) +# endif +#endif +#if !defined(LZO_STATIC_CAST) +# define LZO_STATIC_CAST(t,e) ((t) (e)) +#endif +#if !defined(LZO_STATIC_CAST2) +# define LZO_STATIC_CAST2(t1,t2,e) LZO_STATIC_CAST(t1, LZO_STATIC_CAST(t2, e)) +#endif +#if !defined(LZO_UNCONST_CAST) +# if (LZO_CFG_USE_NEW_STYLE_CASTS) +# define LZO_UNCONST_CAST(t,e) (const_cast (e)) +# elif (LZO_HAVE_MM_HUGE_PTR) +# define LZO_UNCONST_CAST(t,e) ((t) (e)) +# elif (LZO_CC_ARMCC_GNUC || LZO_CC_CLANG || LZO_CC_GNUC || LZO_CC_LLVM || LZO_CC_PATHSCALE) +# define LZO_UNCONST_CAST(t,e) ((t) ((void *) ((lzo_uintptr_t) ((const void *) (e))))) +# endif +#endif +#if !defined(LZO_UNCONST_CAST) +# define LZO_UNCONST_CAST(t,e) ((t) ((void *) ((const void *) (e)))) +#endif +#if !defined(LZO_UNCONST_VOLATILE_CAST) +# if (LZO_CFG_USE_NEW_STYLE_CASTS) +# define LZO_UNCONST_VOLATILE_CAST(t,e) (const_cast (e)) +# elif (LZO_HAVE_MM_HUGE_PTR) +# define LZO_UNCONST_VOLATILE_CAST(t,e) ((t) (e)) +# elif (LZO_CC_ARMCC_GNUC || LZO_CC_CLANG || LZO_CC_GNUC || LZO_CC_LLVM || LZO_CC_PATHSCALE) +# define LZO_UNCONST_VOLATILE_CAST(t,e) ((t) ((volatile void *) ((lzo_uintptr_t) ((volatile const void *) (e))))) +# endif +#endif +#if !defined(LZO_UNCONST_VOLATILE_CAST) +# define LZO_UNCONST_VOLATILE_CAST(t,e) ((t) ((volatile void *) ((volatile const void *) (e)))) +#endif +#if !defined(LZO_UNVOLATILE_CAST) +# if (LZO_CFG_USE_NEW_STYLE_CASTS) +# define LZO_UNVOLATILE_CAST(t,e) (const_cast (e)) +# elif (LZO_HAVE_MM_HUGE_PTR) +# define LZO_UNVOLATILE_CAST(t,e) ((t) (e)) +# elif (LZO_CC_ARMCC_GNUC || LZO_CC_CLANG || LZO_CC_GNUC || LZO_CC_LLVM || LZO_CC_PATHSCALE) +# define LZO_UNVOLATILE_CAST(t,e) ((t) ((void *) ((lzo_uintptr_t) ((volatile void *) (e))))) +# endif +#endif +#if !defined(LZO_UNVOLATILE_CAST) +# define LZO_UNVOLATILE_CAST(t,e) ((t) ((void *) ((volatile void *) (e)))) +#endif +#if !defined(LZO_UNVOLATILE_CONST_CAST) +# if (LZO_CFG_USE_NEW_STYLE_CASTS) +# define LZO_UNVOLATILE_CONST_CAST(t,e) (const_cast (e)) +# elif (LZO_HAVE_MM_HUGE_PTR) +# define LZO_UNVOLATILE_CONST_CAST(t,e) ((t) (e)) +# elif (LZO_CC_ARMCC_GNUC || LZO_CC_CLANG || LZO_CC_GNUC || LZO_CC_LLVM || LZO_CC_PATHSCALE) +# define LZO_UNVOLATILE_CONST_CAST(t,e) ((t) ((const void *) ((lzo_uintptr_t) ((volatile const void *) (e))))) +# endif +#endif +#if !defined(LZO_UNVOLATILE_CONST_CAST) +# define LZO_UNVOLATILE_CONST_CAST(t,e) ((t) ((const void *) ((volatile const void *) (e)))) +#endif +#if !defined(LZO_PCAST) +# if (LZO_HAVE_MM_HUGE_PTR) +# define LZO_PCAST(t,e) ((t) (e)) +# endif +#endif +#if !defined(LZO_PCAST) +# define LZO_PCAST(t,e) LZO_STATIC_CAST(t, LZO_STATIC_CAST(void *, e)) +#endif +#if !defined(LZO_CCAST) +# if (LZO_HAVE_MM_HUGE_PTR) +# define LZO_CCAST(t,e) ((t) (e)) +# endif +#endif +#if !defined(LZO_CCAST) +# define LZO_CCAST(t,e) LZO_STATIC_CAST(t, LZO_STATIC_CAST(const void *, e)) +#endif +#if !defined(LZO_ICONV) +# define LZO_ICONV(t,e) LZO_STATIC_CAST(t, e) +#endif +#if !defined(LZO_ICAST) +# define LZO_ICAST(t,e) LZO_STATIC_CAST(t, e) +#endif +#if !defined(LZO_ITRUNC) +# define LZO_ITRUNC(t,e) LZO_STATIC_CAST(t, e) +#endif +#if !defined(__lzo_cte) +# if (LZO_CC_MSC || LZO_CC_WATCOMC) +# define __lzo_cte(e) ((void)0,(e)) +# elif 1 +# define __lzo_cte(e) ((void)0,(e)) +# endif +#endif +#if !defined(__lzo_cte) +# define __lzo_cte(e) (e) +#endif +#if !defined(LZO_BLOCK_BEGIN) +# define LZO_BLOCK_BEGIN do { +# define LZO_BLOCK_END } while __lzo_cte(0) +#endif +#if !defined(LZO_UNUSED) +# if (LZO_CC_BORLANDC && (__BORLANDC__ >= 0x0600)) +# define LZO_UNUSED(var) ((void) &var) +# elif (LZO_CC_BORLANDC || LZO_CC_HIGHC || LZO_CC_NDPC || LZO_CC_PELLESC || LZO_CC_TURBOC) +# define LZO_UNUSED(var) if (&var) ; else +# elif (LZO_CC_CLANG && (LZO_CC_CLANG >= 0x030200ul)) +# define LZO_UNUSED(var) ((void) &var) +# elif (LZO_CC_CLANG || LZO_CC_GNUC || LZO_CC_LLVM || LZO_CC_PATHSCALE) +# define LZO_UNUSED(var) ((void) var) +# elif (LZO_CC_MSC && (_MSC_VER < 900)) +# define LZO_UNUSED(var) if (&var) ; else +# elif (LZO_CC_KEILC) +# define LZO_UNUSED(var) {extern int lzo_unused__[1-2*!(sizeof(var)>0)]; (void)lzo_unused__;} +# elif (LZO_CC_PACIFICC) +# define LZO_UNUSED(var) ((void) sizeof(var)) +# elif (LZO_CC_WATCOMC) && defined(__cplusplus) +# define LZO_UNUSED(var) ((void) var) +# else +# define LZO_UNUSED(var) ((void) &var) +# endif +#endif +#if !defined(LZO_UNUSED_RESULT) +# define LZO_UNUSED_RESULT(var) LZO_UNUSED(var) +#endif +#if !defined(LZO_UNUSED_FUNC) +# if (LZO_CC_BORLANDC && (__BORLANDC__ >= 0x0600)) +# define LZO_UNUSED_FUNC(func) ((void) func) +# elif (LZO_CC_BORLANDC || LZO_CC_NDPC || LZO_CC_TURBOC) +# define LZO_UNUSED_FUNC(func) if (func) ; else +# elif (LZO_CC_CLANG || LZO_CC_LLVM) +# define LZO_UNUSED_FUNC(func) ((void) &func) +# elif (LZO_CC_MSC && (_MSC_VER < 900)) +# define LZO_UNUSED_FUNC(func) if (func) ; else +# elif (LZO_CC_MSC) +# define LZO_UNUSED_FUNC(func) ((void) &func) +# elif (LZO_CC_KEILC || LZO_CC_PELLESC) +# define LZO_UNUSED_FUNC(func) {extern int lzo_unused__[1-2*!(sizeof((int)func)>0)]; (void)lzo_unused__;} +# else +# define LZO_UNUSED_FUNC(func) ((void) func) +# endif +#endif +#if !defined(LZO_UNUSED_LABEL) +# if (LZO_CC_CLANG >= 0x020800ul) +# define LZO_UNUSED_LABEL(l) (__lzo_gnuc_extension__ ((void) ((const void *) &&l))) +# elif (LZO_CC_ARMCC || LZO_CC_CLANG || LZO_CC_INTELC || LZO_CC_WATCOMC) +# define LZO_UNUSED_LABEL(l) if __lzo_cte(0) goto l +# else +# define LZO_UNUSED_LABEL(l) switch (0) case 1:goto l +# endif +#endif +#if !defined(LZO_DEFINE_UNINITIALIZED_VAR) +# if 0 +# define LZO_DEFINE_UNINITIALIZED_VAR(type,var,init) type var +# elif 0 && (LZO_CC_GNUC) +# define LZO_DEFINE_UNINITIALIZED_VAR(type,var,init) type var = var +# else +# define LZO_DEFINE_UNINITIALIZED_VAR(type,var,init) type var = init +# endif +#endif +#if !defined(__lzo_inline) +#if (LZO_CC_TURBOC && (__TURBOC__ <= 0x0295)) +#elif defined(__cplusplus) +# define __lzo_inline inline +#elif defined(__STDC_VERSION__) && (__STDC_VERSION__-0 >= 199901L) +# define __lzo_inline inline +#elif (LZO_CC_BORLANDC && (__BORLANDC__ >= 0x0550)) +# define __lzo_inline __inline +#elif (LZO_CC_ARMCC_GNUC || LZO_CC_CILLY || LZO_CC_CLANG || LZO_CC_GNUC || LZO_CC_LLVM || LZO_CC_PATHSCALE || LZO_CC_PGI) +# define __lzo_inline __inline__ +#elif (LZO_CC_DMC) +# define __lzo_inline __inline +#elif (LZO_CC_GHS) +# define __lzo_inline __inline__ +#elif (LZO_CC_IBMC >= 600) +# define __lzo_inline __inline__ +#elif (LZO_CC_INTELC) +# define __lzo_inline __inline +#elif (LZO_CC_MWERKS && (__MWERKS__ >= 0x2405)) +# define __lzo_inline __inline +#elif (LZO_CC_MSC && (_MSC_VER >= 900)) +# define __lzo_inline __inline +#elif (LZO_CC_SUNPROC >= 0x5100) +# define __lzo_inline __inline__ +#endif +#endif +#if defined(__lzo_inline) +# ifndef __lzo_HAVE_inline +# define __lzo_HAVE_inline 1 +# endif +#else +# define __lzo_inline /*empty*/ +#endif +#if !defined(__lzo_forceinline) +#if (LZO_CC_GNUC >= 0x030200ul) +# define __lzo_forceinline __inline__ __attribute__((__always_inline__)) +#elif (LZO_CC_IBMC >= 700) +# define __lzo_forceinline __inline__ __attribute__((__always_inline__)) +#elif (LZO_CC_INTELC_MSC && (__INTEL_COMPILER >= 450)) +# define __lzo_forceinline __forceinline +#elif (LZO_CC_INTELC_GNUC && (__INTEL_COMPILER >= 800)) +# define __lzo_forceinline __inline__ __attribute__((__always_inline__)) +#elif (LZO_CC_ARMCC_GNUC || LZO_CC_CLANG || LZO_CC_LLVM || LZO_CC_PATHSCALE) +# define __lzo_forceinline __inline__ __attribute__((__always_inline__)) +#elif (LZO_CC_MSC && (_MSC_VER >= 1200)) +# define __lzo_forceinline __forceinline +#elif (LZO_CC_PGI >= 0x0d0a00ul) +# define __lzo_forceinline __inline__ __attribute__((__always_inline__)) +#elif (LZO_CC_SUNPROC >= 0x5100) +# define __lzo_forceinline __inline__ __attribute__((__always_inline__)) +#endif +#endif +#if defined(__lzo_forceinline) +# ifndef __lzo_HAVE_forceinline +# define __lzo_HAVE_forceinline 1 +# endif +#else +# define __lzo_forceinline __lzo_inline +#endif +#if !defined(__lzo_noinline) +#if 1 && (LZO_ARCH_I386) && (LZO_CC_GNUC >= 0x040000ul) && (LZO_CC_GNUC < 0x040003ul) +# define __lzo_noinline __attribute__((__noinline__,__used__)) +#elif (LZO_CC_GNUC >= 0x030200ul) +# define __lzo_noinline __attribute__((__noinline__)) +#elif (LZO_CC_IBMC >= 700) +# define __lzo_noinline __attribute__((__noinline__)) +#elif (LZO_CC_INTELC_MSC && (__INTEL_COMPILER >= 600)) +# define __lzo_noinline __declspec(noinline) +#elif (LZO_CC_INTELC_GNUC && (__INTEL_COMPILER >= 800)) +# define __lzo_noinline __attribute__((__noinline__)) +#elif (LZO_CC_ARMCC_GNUC || LZO_CC_CLANG || LZO_CC_LLVM || LZO_CC_PATHSCALE) +# define __lzo_noinline __attribute__((__noinline__)) +#elif (LZO_CC_MSC && (_MSC_VER >= 1300)) +# define __lzo_noinline __declspec(noinline) +#elif (LZO_CC_MWERKS && (__MWERKS__ >= 0x3200) && (LZO_OS_WIN32 || LZO_OS_WIN64)) +# if defined(__cplusplus) +# else +# define __lzo_noinline __declspec(noinline) +# endif +#elif (LZO_CC_PGI >= 0x0d0a00ul) +# define __lzo_noinline __attribute__((__noinline__)) +#elif (LZO_CC_SUNPROC >= 0x5100) +# define __lzo_noinline __attribute__((__noinline__)) +#endif +#endif +#if defined(__lzo_noinline) +# ifndef __lzo_HAVE_noinline +# define __lzo_HAVE_noinline 1 +# endif +#else +# define __lzo_noinline /*empty*/ +#endif +#if (__lzo_HAVE_forceinline || __lzo_HAVE_noinline) && !(__lzo_HAVE_inline) +# error "unexpected configuration - check your compiler defines" +#endif +#if !defined(__lzo_static_inline) +#if (LZO_CC_IBMC) +# define __lzo_static_inline __lzo_gnuc_extension__ static __lzo_inline +#endif +#endif +#if !defined(__lzo_static_inline) +# define __lzo_static_inline static __lzo_inline +#endif +#if !defined(__lzo_static_forceinline) +#if (LZO_CC_IBMC) +# define __lzo_static_forceinline __lzo_gnuc_extension__ static __lzo_forceinline +#endif +#endif +#if !defined(__lzo_static_forceinline) +# define __lzo_static_forceinline static __lzo_forceinline +#endif +#if !defined(__lzo_static_noinline) +#if (LZO_CC_IBMC) +# define __lzo_static_noinline __lzo_gnuc_extension__ static __lzo_noinline +#endif +#endif +#if !defined(__lzo_static_noinline) +# define __lzo_static_noinline static __lzo_noinline +#endif +#if !defined(__lzo_c99_extern_inline) +#if defined(__GNUC_GNU_INLINE__) +# define __lzo_c99_extern_inline __lzo_inline +#elif defined(__GNUC_STDC_INLINE__) +# define __lzo_c99_extern_inline extern __lzo_inline +#elif defined(__STDC_VERSION__) && (__STDC_VERSION__-0 >= 199901L) +# define __lzo_c99_extern_inline extern __lzo_inline +#endif +#if !defined(__lzo_c99_extern_inline) && (__lzo_HAVE_inline) +# define __lzo_c99_extern_inline __lzo_inline +#endif +#endif +#if defined(__lzo_c99_extern_inline) +# ifndef __lzo_HAVE_c99_extern_inline +# define __lzo_HAVE_c99_extern_inline 1 +# endif +#else +# define __lzo_c99_extern_inline /*empty*/ +#endif +#if !defined(__lzo_may_alias) +#if (LZO_CC_GNUC >= 0x030400ul) +# define __lzo_may_alias __attribute__((__may_alias__)) +#elif (LZO_CC_CLANG >= 0x020900ul) +# define __lzo_may_alias __attribute__((__may_alias__)) +#elif (LZO_CC_INTELC_GNUC && (__INTEL_COMPILER >= 1210)) && 0 +# define __lzo_may_alias __attribute__((__may_alias__)) +#elif (LZO_CC_PGI >= 0x0d0a00ul) && 0 +# define __lzo_may_alias __attribute__((__may_alias__)) +#endif +#endif +#if defined(__lzo_may_alias) +# ifndef __lzo_HAVE_may_alias +# define __lzo_HAVE_may_alias 1 +# endif +#else +# define __lzo_may_alias /*empty*/ +#endif +#if !defined(__lzo_noreturn) +#if (LZO_CC_GNUC >= 0x020700ul) +# define __lzo_noreturn __attribute__((__noreturn__)) +#elif (LZO_CC_IBMC >= 700) +# define __lzo_noreturn __attribute__((__noreturn__)) +#elif (LZO_CC_INTELC_MSC && (__INTEL_COMPILER >= 450)) +# define __lzo_noreturn __declspec(noreturn) +#elif (LZO_CC_INTELC_GNUC && (__INTEL_COMPILER >= 600)) +# define __lzo_noreturn __attribute__((__noreturn__)) +#elif (LZO_CC_ARMCC_GNUC || LZO_CC_CLANG || LZO_CC_LLVM || LZO_CC_PATHSCALE) +# define __lzo_noreturn __attribute__((__noreturn__)) +#elif (LZO_CC_MSC && (_MSC_VER >= 1200)) +# define __lzo_noreturn __declspec(noreturn) +#elif (LZO_CC_PGI >= 0x0d0a00ul) +# define __lzo_noreturn __attribute__((__noreturn__)) +#endif +#endif +#if defined(__lzo_noreturn) +# ifndef __lzo_HAVE_noreturn +# define __lzo_HAVE_noreturn 1 +# endif +#else +# define __lzo_noreturn /*empty*/ +#endif +#if !defined(__lzo_nothrow) +#if (LZO_CC_GNUC >= 0x030300ul) +# define __lzo_nothrow __attribute__((__nothrow__)) +#elif (LZO_CC_INTELC_MSC && (__INTEL_COMPILER >= 450)) && defined(__cplusplus) +# define __lzo_nothrow __declspec(nothrow) +#elif (LZO_CC_INTELC_GNUC && (__INTEL_COMPILER >= 900)) +# define __lzo_nothrow __attribute__((__nothrow__)) +#elif (LZO_CC_ARMCC_GNUC || LZO_CC_CLANG || LZO_CC_LLVM || LZO_CC_PATHSCALE) +# define __lzo_nothrow __attribute__((__nothrow__)) +#elif (LZO_CC_MSC && (_MSC_VER >= 1200)) && defined(__cplusplus) +# define __lzo_nothrow __declspec(nothrow) +#endif +#endif +#if defined(__lzo_nothrow) +# ifndef __lzo_HAVE_nothrow +# define __lzo_HAVE_nothrow 1 +# endif +#else +# define __lzo_nothrow /*empty*/ +#endif +#if !defined(__lzo_restrict) +#if (LZO_CC_GNUC >= 0x030400ul) +# define __lzo_restrict __restrict__ +#elif (LZO_CC_IBMC >= 800) && !defined(__cplusplus) +# define __lzo_restrict __restrict__ +#elif (LZO_CC_IBMC >= 1210) +# define __lzo_restrict __restrict__ +#elif (LZO_CC_INTELC_MSC && (__INTEL_COMPILER >= 600)) +#elif (LZO_CC_INTELC_GNUC && (__INTEL_COMPILER >= 600)) +# define __lzo_restrict __restrict__ +#elif (LZO_CC_ARMCC_GNUC || LZO_CC_CLANG || LZO_CC_LLVM) +# define __lzo_restrict __restrict__ +#elif (LZO_CC_MSC && (_MSC_VER >= 1400)) +# define __lzo_restrict __restrict +#elif (LZO_CC_PGI >= 0x0d0a00ul) +# define __lzo_restrict __restrict__ +#endif +#endif +#if defined(__lzo_restrict) +# ifndef __lzo_HAVE_restrict +# define __lzo_HAVE_restrict 1 +# endif +#else +# define __lzo_restrict /*empty*/ +#endif +#if !defined(__lzo_alignof) +#if (LZO_CC_ARMCC || LZO_CC_CILLY || LZO_CC_CLANG || LZO_CC_GNUC || LZO_CC_LLVM || LZO_CC_PATHSCALE || LZO_CC_PGI) +# define __lzo_alignof(e) __alignof__(e) +#elif (LZO_CC_GHS) && !defined(__cplusplus) +# define __lzo_alignof(e) __alignof__(e) +#elif (LZO_CC_IBMC >= 600) +# define __lzo_alignof(e) (__lzo_gnuc_extension__ __alignof__(e)) +#elif (LZO_CC_INTELC && (__INTEL_COMPILER >= 700)) +# define __lzo_alignof(e) __alignof__(e) +#elif (LZO_CC_MSC && (_MSC_VER >= 1300)) +# define __lzo_alignof(e) __alignof(e) +#elif (LZO_CC_SUNPROC >= 0x5100) +# define __lzo_alignof(e) __alignof__(e) +#endif +#endif +#if defined(__lzo_alignof) +# ifndef __lzo_HAVE_alignof +# define __lzo_HAVE_alignof 1 +# endif +#endif +#if !defined(__lzo_struct_packed) +#if (LZO_CC_CLANG && (LZO_CC_CLANG < 0x020800ul)) && defined(__cplusplus) +#elif (LZO_CC_GNUC && (LZO_CC_GNUC < 0x020700ul)) +#elif (LZO_CC_GNUC && (LZO_CC_GNUC < 0x020800ul)) && defined(__cplusplus) +#elif (LZO_CC_PCC && (LZO_CC_PCC < 0x010100ul)) +#elif (LZO_CC_SUNPROC && (LZO_CC_SUNPROC < 0x5110)) && !defined(__cplusplus) +#elif (LZO_CC_GNUC >= 0x030400ul) && !(LZO_CC_PCC_GNUC) && (LZO_ARCH_AMD64 || LZO_ARCH_I386) +# define __lzo_struct_packed(s) struct s { +# define __lzo_struct_packed_end() } __attribute__((__gcc_struct__,__packed__)); +# define __lzo_struct_packed_ma_end() } __lzo_may_alias __attribute__((__gcc_struct__,__packed__)); +#elif (LZO_CC_ARMCC || LZO_CC_CLANG || LZO_CC_GNUC || LZO_CC_INTELC_GNUC || LZO_CC_LLVM || LZO_CC_PATHSCALE || (LZO_CC_PGI >= 0x0d0a00ul) || (LZO_CC_SUNPROC >= 0x5100)) +# define __lzo_struct_packed(s) struct s { +# define __lzo_struct_packed_end() } __attribute__((__packed__)); +# define __lzo_struct_packed_ma_end() } __lzo_may_alias __attribute__((__packed__)); +#elif (LZO_CC_IBMC >= 700) +# define __lzo_struct_packed(s) __lzo_gnuc_extension__ struct s { +# define __lzo_struct_packed_end() } __attribute__((__packed__)); +# define __lzo_struct_packed_ma_end() } __lzo_may_alias __attribute__((__packed__)); +#elif (LZO_CC_INTELC_MSC) || (LZO_CC_MSC && (_MSC_VER >= 1300)) +# define __lzo_struct_packed(s) __pragma(pack(push,1)) struct s { +# define __lzo_struct_packed_end() } __pragma(pack(pop)); +#elif (LZO_CC_WATCOMC && (__WATCOMC__ >= 900)) +# define __lzo_struct_packed(s) _Packed struct s { +# define __lzo_struct_packed_end() }; +#endif +#endif +#if defined(__lzo_struct_packed) && !defined(__lzo_struct_packed_ma) +# define __lzo_struct_packed_ma(s) __lzo_struct_packed(s) +#endif +#if defined(__lzo_struct_packed_end) && !defined(__lzo_struct_packed_ma_end) +# define __lzo_struct_packed_ma_end() __lzo_struct_packed_end() +#endif +#if !defined(__lzo_byte_struct) +#if defined(__lzo_struct_packed) +# define __lzo_byte_struct(s,n) __lzo_struct_packed(s) unsigned char a[n]; __lzo_struct_packed_end() +# define __lzo_byte_struct_ma(s,n) __lzo_struct_packed_ma(s) unsigned char a[n]; __lzo_struct_packed_ma_end() +#elif (LZO_CC_CILLY || LZO_CC_CLANG || LZO_CC_PGI || (LZO_CC_SUNPROC >= 0x5100)) +# define __lzo_byte_struct(s,n) struct s { unsigned char a[n]; } __attribute__((__packed__)); +# define __lzo_byte_struct_ma(s,n) struct s { unsigned char a[n]; } __lzo_may_alias __attribute__((__packed__)); +#endif +#endif +#if defined(__lzo_byte_struct) && !defined(__lzo_byte_struct_ma) +# define __lzo_byte_struct_ma(s,n) __lzo_byte_struct(s,n) +#endif +#if !defined(__lzo_struct_align16) && (__lzo_HAVE_alignof) +#if (LZO_CC_GNUC && (LZO_CC_GNUC < 0x030000ul)) +#elif (LZO_CC_CLANG && (LZO_CC_CLANG < 0x020800ul)) && defined(__cplusplus) +#elif (LZO_CC_CILLY || LZO_CC_PCC) +#elif (LZO_CC_INTELC_MSC) || (LZO_CC_MSC && (_MSC_VER >= 1300)) +# define __lzo_struct_align16(s) struct __declspec(align(16)) s { +# define __lzo_struct_align16_end() }; +# define __lzo_struct_align32(s) struct __declspec(align(32)) s { +# define __lzo_struct_align32_end() }; +# define __lzo_struct_align64(s) struct __declspec(align(64)) s { +# define __lzo_struct_align64_end() }; +#elif (LZO_CC_ARMCC || LZO_CC_CLANG || LZO_CC_GNUC || (LZO_CC_IBMC >= 700) || LZO_CC_INTELC_GNUC || LZO_CC_LLVM || LZO_CC_PATHSCALE) +# define __lzo_struct_align16(s) struct s { +# define __lzo_struct_align16_end() } __attribute__((__aligned__(16))); +# define __lzo_struct_align32(s) struct s { +# define __lzo_struct_align32_end() } __attribute__((__aligned__(32))); +# define __lzo_struct_align64(s) struct s { +# define __lzo_struct_align64_end() } __attribute__((__aligned__(64))); +#endif +#endif +#if !defined(__lzo_union_um) +#if (LZO_CC_CLANG && (LZO_CC_CLANG < 0x020800ul)) && defined(__cplusplus) +#elif (LZO_CC_GNUC && (LZO_CC_GNUC < 0x020700ul)) +#elif (LZO_CC_GNUC && (LZO_CC_GNUC < 0x020800ul)) && defined(__cplusplus) +#elif (LZO_CC_INTELC_GNUC && (__INTEL_COMPILER < 810)) +#elif (LZO_CC_PCC && (LZO_CC_PCC < 0x010100ul)) +#elif (LZO_CC_SUNPROC && (LZO_CC_SUNPROC < 0x5110)) && !defined(__cplusplus) +#elif (LZO_CC_ARMCC || LZO_CC_CLANG || LZO_CC_GNUC || LZO_CC_INTELC_GNUC || LZO_CC_LLVM || LZO_CC_PATHSCALE || (LZO_CC_PGI >= 0x0d0a00ul) || (LZO_CC_SUNPROC >= 0x5100)) +# define __lzo_union_am(s) union s { +# define __lzo_union_am_end() } __lzo_may_alias; +# define __lzo_union_um(s) union s { +# define __lzo_union_um_end() } __lzo_may_alias __attribute__((__packed__)); +#elif (LZO_CC_IBMC >= 700) +# define __lzo_union_am(s) __lzo_gnuc_extension__ union s { +# define __lzo_union_am_end() } __lzo_may_alias; +# define __lzo_union_um(s) __lzo_gnuc_extension__ union s { +# define __lzo_union_um_end() } __lzo_may_alias __attribute__((__packed__)); +#elif (LZO_CC_INTELC_MSC) || (LZO_CC_MSC && (_MSC_VER >= 1300)) +# define __lzo_union_um(s) __pragma(pack(push,1)) union s { +# define __lzo_union_um_end() } __pragma(pack(pop)); +#elif (LZO_CC_WATCOMC && (__WATCOMC__ >= 900)) +# define __lzo_union_um(s) _Packed union s { +# define __lzo_union_um_end() }; +#endif +#endif +#if !defined(__lzo_union_am) +# define __lzo_union_am(s) union s { +# define __lzo_union_am_end() }; +#endif +#if !defined(__lzo_constructor) +#if (LZO_CC_GNUC >= 0x030400ul) +# define __lzo_constructor __attribute__((__constructor__,__used__)) +#elif (LZO_CC_GNUC >= 0x020700ul) +# define __lzo_constructor __attribute__((__constructor__)) +#elif (LZO_CC_INTELC_GNUC && (__INTEL_COMPILER >= 800)) +# define __lzo_constructor __attribute__((__constructor__,__used__)) +#elif (LZO_CC_ARMCC_GNUC || LZO_CC_CLANG || LZO_CC_LLVM || LZO_CC_PATHSCALE) +# define __lzo_constructor __attribute__((__constructor__)) +#endif +#endif +#if defined(__lzo_constructor) +# ifndef __lzo_HAVE_constructor +# define __lzo_HAVE_constructor 1 +# endif +#endif +#if !defined(__lzo_destructor) +#if (LZO_CC_GNUC >= 0x030400ul) +# define __lzo_destructor __attribute__((__destructor__,__used__)) +#elif (LZO_CC_GNUC >= 0x020700ul) +# define __lzo_destructor __attribute__((__destructor__)) +#elif (LZO_CC_INTELC_GNUC && (__INTEL_COMPILER >= 800)) +# define __lzo_destructor __attribute__((__destructor__,__used__)) +#elif (LZO_CC_ARMCC_GNUC || LZO_CC_CLANG || LZO_CC_LLVM || LZO_CC_PATHSCALE) +# define __lzo_destructor __attribute__((__destructor__)) +#endif +#endif +#if defined(__lzo_destructor) +# ifndef __lzo_HAVE_destructor +# define __lzo_HAVE_destructor 1 +# endif +#endif +#if (__lzo_HAVE_destructor) && !(__lzo_HAVE_constructor) +# error "unexpected configuration - check your compiler defines" +#endif +#if !defined(__lzo_likely) && !defined(__lzo_unlikely) +#if (LZO_CC_GNUC >= 0x030200ul) +# define __lzo_likely(e) (__builtin_expect(!!(e),1)) +# define __lzo_unlikely(e) (__builtin_expect(!!(e),0)) +#elif (LZO_CC_IBMC >= 1010) +# define __lzo_likely(e) (__builtin_expect(!!(e),1)) +# define __lzo_unlikely(e) (__builtin_expect(!!(e),0)) +#elif (LZO_CC_INTELC && (__INTEL_COMPILER >= 800)) +# define __lzo_likely(e) (__builtin_expect(!!(e),1)) +# define __lzo_unlikely(e) (__builtin_expect(!!(e),0)) +#elif (LZO_CC_CLANG && LZO_CC_CLANG_C2) +#elif (LZO_CC_ARMCC_GNUC || LZO_CC_CLANG || LZO_CC_LLVM || LZO_CC_PATHSCALE) +# define __lzo_likely(e) (__builtin_expect(!!(e),1)) +# define __lzo_unlikely(e) (__builtin_expect(!!(e),0)) +#endif +#endif +#if defined(__lzo_likely) +# ifndef __lzo_HAVE_likely +# define __lzo_HAVE_likely 1 +# endif +#else +# define __lzo_likely(e) (e) +#endif +#if defined(__lzo_very_likely) +# ifndef __lzo_HAVE_very_likely +# define __lzo_HAVE_very_likely 1 +# endif +#else +# define __lzo_very_likely(e) __lzo_likely(e) +#endif +#if defined(__lzo_unlikely) +# ifndef __lzo_HAVE_unlikely +# define __lzo_HAVE_unlikely 1 +# endif +#else +# define __lzo_unlikely(e) (e) +#endif +#if defined(__lzo_very_unlikely) +# ifndef __lzo_HAVE_very_unlikely +# define __lzo_HAVE_very_unlikely 1 +# endif +#else +# define __lzo_very_unlikely(e) __lzo_unlikely(e) +#endif +#if !defined(__lzo_loop_forever) +# if (LZO_CC_IBMC) +# define __lzo_loop_forever() LZO_BLOCK_BEGIN for (;;) { ; } LZO_BLOCK_END +# else +# define __lzo_loop_forever() do { ; } while __lzo_cte(1) +# endif +#endif +#if !defined(__lzo_unreachable) +#if (LZO_CC_CLANG && (LZO_CC_CLANG >= 0x020800ul)) && lzo_has_builtin(__builtin_unreachable) +# define __lzo_unreachable() __builtin_unreachable(); +#elif (LZO_CC_GNUC >= 0x040500ul) +# define __lzo_unreachable() __builtin_unreachable(); +#elif (LZO_CC_INTELC_GNUC && (__INTEL_COMPILER >= 1300)) && 1 +# define __lzo_unreachable() __builtin_unreachable(); +#endif +#endif +#if defined(__lzo_unreachable) +# ifndef __lzo_HAVE_unreachable +# define __lzo_HAVE_unreachable 1 +# endif +#else +# if 0 +# define __lzo_unreachable() ((void)0); +# else +# define __lzo_unreachable() __lzo_loop_forever(); +# endif +#endif +#if !defined(lzo_unused_funcs_impl) +# if 1 && (LZO_CC_ARMCC_GNUC || LZO_CC_CLANG || (LZO_CC_GNUC >= 0x020700ul) || LZO_CC_INTELC_GNUC || LZO_CC_LLVM || LZO_CC_PATHSCALE || LZO_CC_PGI) +# define lzo_unused_funcs_impl(r,f) static r __attribute__((__unused__)) f +# elif 1 && (LZO_CC_BORLANDC || LZO_CC_GNUC) +# define lzo_unused_funcs_impl(r,f) static r f +# else +# define lzo_unused_funcs_impl(r,f) __lzo_static_forceinline r f +# endif +#endif +#ifndef __LZO_CTA_NAME +#if (LZO_CFG_USE_COUNTER) +# define __LZO_CTA_NAME(a) LZO_PP_ECONCAT2(a,__COUNTER__) +#else +# define __LZO_CTA_NAME(a) LZO_PP_ECONCAT2(a,__LINE__) +#endif +#endif +#if !defined(LZO_COMPILE_TIME_ASSERT_HEADER) +# if (LZO_CC_AZTECC || LZO_CC_ZORTECHC) +# define LZO_COMPILE_TIME_ASSERT_HEADER(e) LZO_EXTERN_C_BEGIN extern int __LZO_CTA_NAME(lzo_cta__)[1-!(e)]; LZO_EXTERN_C_END +# elif (LZO_CC_DMC || LZO_CC_SYMANTECC) +# define LZO_COMPILE_TIME_ASSERT_HEADER(e) LZO_EXTERN_C_BEGIN extern int __LZO_CTA_NAME(lzo_cta__)[1u-2*!(e)]; LZO_EXTERN_C_END +# elif (LZO_CC_TURBOC && (__TURBOC__ == 0x0295)) +# define LZO_COMPILE_TIME_ASSERT_HEADER(e) LZO_EXTERN_C_BEGIN extern int __LZO_CTA_NAME(lzo_cta__)[1-!(e)]; LZO_EXTERN_C_END +# elif (LZO_CC_CLANG && (LZO_CC_CLANG < 0x020900ul)) && defined(__cplusplus) +# define LZO_COMPILE_TIME_ASSERT_HEADER(e) LZO_EXTERN_C_BEGIN int __LZO_CTA_NAME(lzo_cta_f__)(int [1-2*!(e)]); LZO_EXTERN_C_END +# elif (LZO_CC_GNUC) && defined(__CHECKER__) && defined(__SPARSE_CHECKER__) +# define LZO_COMPILE_TIME_ASSERT_HEADER(e) LZO_EXTERN_C_BEGIN enum {__LZO_CTA_NAME(lzo_cta_e__)=1/!!(e)} __attribute__((__unused__)); LZO_EXTERN_C_END +# else +# define LZO_COMPILE_TIME_ASSERT_HEADER(e) LZO_EXTERN_C_BEGIN extern int __LZO_CTA_NAME(lzo_cta__)[1-2*!(e)]; LZO_EXTERN_C_END +# endif +#endif +#if !defined(LZO_COMPILE_TIME_ASSERT) +# if (LZO_CC_AZTECC) +# define LZO_COMPILE_TIME_ASSERT(e) {typedef int __LZO_CTA_NAME(lzo_cta_t__)[1-!(e)];} +# elif (LZO_CC_CLANG && (LZO_CC_CLANG >= 0x030000ul)) +# define LZO_COMPILE_TIME_ASSERT(e) {typedef int __LZO_CTA_NAME(lzo_cta_t__)[1-2*!(e)] __attribute__((__unused__));} +# elif (LZO_CC_DMC || LZO_CC_PACIFICC || LZO_CC_SYMANTECC || LZO_CC_ZORTECHC) +# define LZO_COMPILE_TIME_ASSERT(e) switch(0) case 1:case !(e):break; +# elif (LZO_CC_GNUC) && defined(__CHECKER__) && defined(__SPARSE_CHECKER__) +# define LZO_COMPILE_TIME_ASSERT(e) {(void) (0/!!(e));} +# elif (LZO_CC_GNUC >= 0x040700ul) && (LZO_CFG_USE_COUNTER) && defined(__cplusplus) +# define LZO_COMPILE_TIME_ASSERT(e) {enum {__LZO_CTA_NAME(lzo_cta_e__)=1/!!(e)} __attribute__((__unused__));} +# elif (LZO_CC_GNUC >= 0x040700ul) +# define LZO_COMPILE_TIME_ASSERT(e) {typedef int __LZO_CTA_NAME(lzo_cta_t__)[1-2*!(e)] __attribute__((__unused__));} +# elif (LZO_CC_MSC && (_MSC_VER < 900)) +# define LZO_COMPILE_TIME_ASSERT(e) switch(0) case 1:case !(e):break; +# elif (LZO_CC_TURBOC && (__TURBOC__ == 0x0295)) +# define LZO_COMPILE_TIME_ASSERT(e) switch(0) case 1:case !(e):break; +# else +# define LZO_COMPILE_TIME_ASSERT(e) {typedef int __LZO_CTA_NAME(lzo_cta_t__)[1-2*!(e)];} +# endif +#endif +#if (LZO_LANG_ASSEMBLER) +# undef LZO_COMPILE_TIME_ASSERT_HEADER +# define LZO_COMPILE_TIME_ASSERT_HEADER(e) /*empty*/ +#else +LZO_COMPILE_TIME_ASSERT_HEADER(1 == 1) +#if defined(__cplusplus) +extern "C" { LZO_COMPILE_TIME_ASSERT_HEADER(2 == 2) } +#endif +LZO_COMPILE_TIME_ASSERT_HEADER(3 == 3) +#endif +#if (LZO_ARCH_I086 || LZO_ARCH_I386) && (LZO_OS_DOS16 || LZO_OS_DOS32 || LZO_OS_OS2 || LZO_OS_OS216 || LZO_OS_WIN16 || LZO_OS_WIN32 || LZO_OS_WIN64) +# if (LZO_CC_GNUC || LZO_CC_HIGHC || LZO_CC_NDPC || LZO_CC_PACIFICC) +# elif (LZO_CC_DMC || LZO_CC_SYMANTECC || LZO_CC_ZORTECHC) +# define __lzo_cdecl __cdecl +# define __lzo_cdecl_atexit /*empty*/ +# define __lzo_cdecl_main __cdecl +# if (LZO_OS_OS2 && (LZO_CC_DMC || LZO_CC_SYMANTECC)) +# define __lzo_cdecl_qsort __pascal +# elif (LZO_OS_OS2 && (LZO_CC_ZORTECHC)) +# define __lzo_cdecl_qsort _stdcall +# else +# define __lzo_cdecl_qsort __cdecl +# endif +# elif (LZO_CC_WATCOMC) +# define __lzo_cdecl __cdecl +# else +# define __lzo_cdecl __cdecl +# define __lzo_cdecl_atexit __cdecl +# define __lzo_cdecl_main __cdecl +# define __lzo_cdecl_qsort __cdecl +# endif +# if (LZO_CC_GNUC || LZO_CC_HIGHC || LZO_CC_NDPC || LZO_CC_PACIFICC || LZO_CC_WATCOMC) +# elif (LZO_OS_OS2 && (LZO_CC_DMC || LZO_CC_SYMANTECC)) +# define __lzo_cdecl_sighandler __pascal +# elif (LZO_OS_OS2 && (LZO_CC_ZORTECHC)) +# define __lzo_cdecl_sighandler _stdcall +# elif (LZO_CC_MSC && (_MSC_VER >= 1400)) && defined(_M_CEE_PURE) +# define __lzo_cdecl_sighandler __clrcall +# elif (LZO_CC_MSC && (_MSC_VER >= 600 && _MSC_VER < 700)) +# if defined(_DLL) +# define __lzo_cdecl_sighandler _far _cdecl _loadds +# elif defined(_MT) +# define __lzo_cdecl_sighandler _far _cdecl +# else +# define __lzo_cdecl_sighandler _cdecl +# endif +# else +# define __lzo_cdecl_sighandler __cdecl +# endif +#elif (LZO_ARCH_I386) && (LZO_CC_WATCOMC) +# define __lzo_cdecl __cdecl +#elif (LZO_ARCH_M68K && LZO_OS_TOS && (LZO_CC_PUREC || LZO_CC_TURBOC)) +# define __lzo_cdecl cdecl +#endif +#if !defined(__lzo_cdecl) +# define __lzo_cdecl /*empty*/ +#endif +#if !defined(__lzo_cdecl_atexit) +# define __lzo_cdecl_atexit /*empty*/ +#endif +#if !defined(__lzo_cdecl_main) +# define __lzo_cdecl_main /*empty*/ +#endif +#if !defined(__lzo_cdecl_qsort) +# define __lzo_cdecl_qsort /*empty*/ +#endif +#if !defined(__lzo_cdecl_sighandler) +# define __lzo_cdecl_sighandler /*empty*/ +#endif +#if !defined(__lzo_cdecl_va) +# define __lzo_cdecl_va __lzo_cdecl +#endif +#if !(LZO_CFG_NO_WINDOWS_H) +#if !defined(LZO_HAVE_WINDOWS_H) +#if (LZO_OS_CYGWIN || (LZO_OS_EMX && defined(__RSXNT__)) || LZO_OS_WIN32 || LZO_OS_WIN64) +# if (LZO_CC_WATCOMC && (__WATCOMC__ < 1000)) +# elif ((LZO_OS_WIN32 && defined(__PW32__)) && (LZO_CC_GNUC && (LZO_CC_GNUC < 0x030000ul))) +# elif ((LZO_OS_CYGWIN || defined(__MINGW32__)) && (LZO_CC_GNUC && (LZO_CC_GNUC < 0x025f00ul))) +# else +# define LZO_HAVE_WINDOWS_H 1 +# endif +#endif +#endif +#endif +#define LZO_SIZEOF_CHAR 1 +#ifndef LZO_SIZEOF_SHORT +#if defined(SIZEOF_SHORT) +# define LZO_SIZEOF_SHORT (SIZEOF_SHORT) +#elif defined(__SIZEOF_SHORT__) +# define LZO_SIZEOF_SHORT (__SIZEOF_SHORT__) +#endif +#endif +#ifndef LZO_SIZEOF_INT +#if defined(SIZEOF_INT) +# define LZO_SIZEOF_INT (SIZEOF_INT) +#elif defined(__SIZEOF_INT__) +# define LZO_SIZEOF_INT (__SIZEOF_INT__) +#endif +#endif +#ifndef LZO_SIZEOF_LONG +#if defined(SIZEOF_LONG) +# define LZO_SIZEOF_LONG (SIZEOF_LONG) +#elif defined(__SIZEOF_LONG__) +# define LZO_SIZEOF_LONG (__SIZEOF_LONG__) +#endif +#endif +#ifndef LZO_SIZEOF_LONG_LONG +#if defined(SIZEOF_LONG_LONG) +# define LZO_SIZEOF_LONG_LONG (SIZEOF_LONG_LONG) +#elif defined(__SIZEOF_LONG_LONG__) +# define LZO_SIZEOF_LONG_LONG (__SIZEOF_LONG_LONG__) +#endif +#endif +#ifndef LZO_SIZEOF___INT16 +#if defined(SIZEOF___INT16) +# define LZO_SIZEOF___INT16 (SIZEOF___INT16) +#endif +#endif +#ifndef LZO_SIZEOF___INT32 +#if defined(SIZEOF___INT32) +# define LZO_SIZEOF___INT32 (SIZEOF___INT32) +#endif +#endif +#ifndef LZO_SIZEOF___INT64 +#if defined(SIZEOF___INT64) +# define LZO_SIZEOF___INT64 (SIZEOF___INT64) +#endif +#endif +#ifndef LZO_SIZEOF_VOID_P +#if defined(SIZEOF_VOID_P) +# define LZO_SIZEOF_VOID_P (SIZEOF_VOID_P) +#elif defined(__SIZEOF_POINTER__) +# define LZO_SIZEOF_VOID_P (__SIZEOF_POINTER__) +#endif +#endif +#ifndef LZO_SIZEOF_SIZE_T +#if defined(SIZEOF_SIZE_T) +# define LZO_SIZEOF_SIZE_T (SIZEOF_SIZE_T) +#elif defined(__SIZEOF_SIZE_T__) +# define LZO_SIZEOF_SIZE_T (__SIZEOF_SIZE_T__) +#endif +#endif +#ifndef LZO_SIZEOF_PTRDIFF_T +#if defined(SIZEOF_PTRDIFF_T) +# define LZO_SIZEOF_PTRDIFF_T (SIZEOF_PTRDIFF_T) +#elif defined(__SIZEOF_PTRDIFF_T__) +# define LZO_SIZEOF_PTRDIFF_T (__SIZEOF_PTRDIFF_T__) +#endif +#endif +#define __LZO_LSR(x,b) (((x)+0ul) >> (b)) +#if !defined(LZO_SIZEOF_SHORT) +# if (LZO_ARCH_CRAY_PVP) +# define LZO_SIZEOF_SHORT 8 +# elif (USHRT_MAX == LZO_0xffffL) +# define LZO_SIZEOF_SHORT 2 +# elif (__LZO_LSR(USHRT_MAX,7) == 1) +# define LZO_SIZEOF_SHORT 1 +# elif (__LZO_LSR(USHRT_MAX,15) == 1) +# define LZO_SIZEOF_SHORT 2 +# elif (__LZO_LSR(USHRT_MAX,31) == 1) +# define LZO_SIZEOF_SHORT 4 +# elif (__LZO_LSR(USHRT_MAX,63) == 1) +# define LZO_SIZEOF_SHORT 8 +# elif (__LZO_LSR(USHRT_MAX,127) == 1) +# define LZO_SIZEOF_SHORT 16 +# else +# error "LZO_SIZEOF_SHORT" +# endif +#endif +LZO_COMPILE_TIME_ASSERT_HEADER(LZO_SIZEOF_SHORT == sizeof(short)) +#if !defined(LZO_SIZEOF_INT) +# if (LZO_ARCH_CRAY_PVP) +# define LZO_SIZEOF_INT 8 +# elif (UINT_MAX == LZO_0xffffL) +# define LZO_SIZEOF_INT 2 +# elif (UINT_MAX == LZO_0xffffffffL) +# define LZO_SIZEOF_INT 4 +# elif (__LZO_LSR(UINT_MAX,7) == 1) +# define LZO_SIZEOF_INT 1 +# elif (__LZO_LSR(UINT_MAX,15) == 1) +# define LZO_SIZEOF_INT 2 +# elif (__LZO_LSR(UINT_MAX,31) == 1) +# define LZO_SIZEOF_INT 4 +# elif (__LZO_LSR(UINT_MAX,63) == 1) +# define LZO_SIZEOF_INT 8 +# elif (__LZO_LSR(UINT_MAX,127) == 1) +# define LZO_SIZEOF_INT 16 +# else +# error "LZO_SIZEOF_INT" +# endif +#endif +LZO_COMPILE_TIME_ASSERT_HEADER(LZO_SIZEOF_INT == sizeof(int)) +#if !defined(LZO_SIZEOF_LONG) +# if (ULONG_MAX == LZO_0xffffffffL) +# define LZO_SIZEOF_LONG 4 +# elif (__LZO_LSR(ULONG_MAX,7) == 1) +# define LZO_SIZEOF_LONG 1 +# elif (__LZO_LSR(ULONG_MAX,15) == 1) +# define LZO_SIZEOF_LONG 2 +# elif (__LZO_LSR(ULONG_MAX,31) == 1) +# define LZO_SIZEOF_LONG 4 +# elif (__LZO_LSR(ULONG_MAX,39) == 1) +# define LZO_SIZEOF_LONG 5 +# elif (__LZO_LSR(ULONG_MAX,63) == 1) +# define LZO_SIZEOF_LONG 8 +# elif (__LZO_LSR(ULONG_MAX,127) == 1) +# define LZO_SIZEOF_LONG 16 +# else +# error "LZO_SIZEOF_LONG" +# endif +#endif +LZO_COMPILE_TIME_ASSERT_HEADER(LZO_SIZEOF_LONG == sizeof(long)) +#if !defined(LZO_SIZEOF_LONG_LONG) && !defined(LZO_SIZEOF___INT64) +#if (LZO_SIZEOF_LONG > 0 && LZO_SIZEOF_LONG < 8) +# if defined(__LONG_MAX__) && defined(__LONG_LONG_MAX__) +# if (LZO_CC_GNUC >= 0x030300ul) +# if ((__LONG_MAX__-0) == (__LONG_LONG_MAX__-0)) +# define LZO_SIZEOF_LONG_LONG LZO_SIZEOF_LONG +# elif (__LZO_LSR(__LONG_LONG_MAX__,30) == 1) +# define LZO_SIZEOF_LONG_LONG 4 +# endif +# endif +# endif +#endif +#endif +#if !defined(LZO_SIZEOF_LONG_LONG) && !defined(LZO_SIZEOF___INT64) +#if (LZO_SIZEOF_LONG > 0 && LZO_SIZEOF_LONG < 8) +#if (LZO_ARCH_I086 && LZO_CC_DMC) +#elif (LZO_CC_CILLY) && defined(__GNUC__) +# define LZO_SIZEOF_LONG_LONG 8 +#elif (LZO_CC_ARMCC_GNUC || LZO_CC_CLANG || LZO_CC_GNUC || LZO_CC_LLVM || LZO_CC_PATHSCALE) +# define LZO_SIZEOF_LONG_LONG 8 +#elif ((LZO_OS_WIN32 || LZO_OS_WIN64 || defined(_WIN32)) && LZO_CC_MSC && (_MSC_VER >= 1400)) +# define LZO_SIZEOF_LONG_LONG 8 +#elif (LZO_OS_WIN64 || defined(_WIN64)) +# define LZO_SIZEOF___INT64 8 +#elif (LZO_ARCH_I386 && (LZO_CC_DMC)) +# define LZO_SIZEOF_LONG_LONG 8 +#elif (LZO_ARCH_I386 && (LZO_CC_SYMANTECC && (__SC__ >= 0x700))) +# define LZO_SIZEOF_LONG_LONG 8 +#elif (LZO_ARCH_I386 && (LZO_CC_INTELC && defined(__linux__))) +# define LZO_SIZEOF_LONG_LONG 8 +#elif (LZO_ARCH_I386 && (LZO_CC_MWERKS || LZO_CC_PELLESC || LZO_CC_PGI || LZO_CC_SUNPROC)) +# define LZO_SIZEOF_LONG_LONG 8 +#elif (LZO_ARCH_I386 && (LZO_CC_INTELC || LZO_CC_MSC)) +# define LZO_SIZEOF___INT64 8 +#elif ((LZO_OS_WIN32 || defined(_WIN32)) && (LZO_CC_MSC)) +# define LZO_SIZEOF___INT64 8 +#elif (LZO_ARCH_I386 && (LZO_CC_BORLANDC && (__BORLANDC__ >= 0x0520))) +# define LZO_SIZEOF___INT64 8 +#elif (LZO_ARCH_I386 && (LZO_CC_WATCOMC && (__WATCOMC__ >= 1100))) +# define LZO_SIZEOF___INT64 8 +#elif (LZO_CC_GHS && defined(__LLONG_BIT) && ((__LLONG_BIT-0) == 64)) +# define LZO_SIZEOF_LONG_LONG 8 +#elif (LZO_CC_WATCOMC && defined(_INTEGRAL_MAX_BITS) && ((_INTEGRAL_MAX_BITS-0) == 64)) +# define LZO_SIZEOF___INT64 8 +#elif (LZO_OS_OS400 || defined(__OS400__)) && defined(__LLP64_IFC__) +# define LZO_SIZEOF_LONG_LONG 8 +#elif (defined(__vms) || defined(__VMS)) && ((__INITIAL_POINTER_SIZE-0) == 64) +# define LZO_SIZEOF_LONG_LONG 8 +#elif (LZO_CC_SDCC) && (LZO_SIZEOF_INT == 2) +#elif 1 && defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L) +# define LZO_SIZEOF_LONG_LONG 8 +#endif +#endif +#endif +#if defined(__cplusplus) && (LZO_CC_GNUC) +# if (LZO_CC_GNUC < 0x020800ul) +# undef LZO_SIZEOF_LONG_LONG +# endif +#endif +#if (LZO_CFG_NO_LONG_LONG) +# undef LZO_SIZEOF_LONG_LONG +#elif defined(__NO_LONG_LONG) +# undef LZO_SIZEOF_LONG_LONG +#elif defined(_NO_LONGLONG) +# undef LZO_SIZEOF_LONG_LONG +#endif +#if !defined(LZO_WORDSIZE) +#if (LZO_ARCH_ALPHA) +# define LZO_WORDSIZE 8 +#elif (LZO_ARCH_AMD64) +# define LZO_WORDSIZE 8 +#elif (LZO_ARCH_ARM64) +# define LZO_WORDSIZE 8 +#elif (LZO_ARCH_AVR) +# define LZO_WORDSIZE 1 +#elif (LZO_ARCH_H8300) +# if defined(__H8300H__) || defined(__H8300S__) || defined(__H8300SX__) +# define LZO_WORDSIZE 4 +# else +# define LZO_WORDSIZE 2 +# endif +#elif (LZO_ARCH_I086) +# define LZO_WORDSIZE 2 +#elif (LZO_ARCH_IA64) +# define LZO_WORDSIZE 8 +#elif (LZO_ARCH_M16C) +# define LZO_WORDSIZE 2 +#elif (LZO_ARCH_SPU) +# define LZO_WORDSIZE 4 +#elif (LZO_ARCH_Z80) +# define LZO_WORDSIZE 1 +#elif (LZO_SIZEOF_LONG == 8) && ((defined(__mips__) && defined(__R5900__)) || defined(__MIPS_PSX2__)) +# define LZO_WORDSIZE 8 +#elif (LZO_OS_OS400 || defined(__OS400__)) +# define LZO_WORDSIZE 8 +#elif (defined(__vms) || defined(__VMS)) && (__INITIAL_POINTER_SIZE+0 == 64) +# define LZO_WORDSIZE 8 +#endif +#endif +#if !defined(LZO_SIZEOF_VOID_P) +#if defined(__ILP32__) || defined(__ILP32) || defined(_ILP32) +LZO_COMPILE_TIME_ASSERT_HEADER(sizeof(int) == 4) +LZO_COMPILE_TIME_ASSERT_HEADER(sizeof(long) == 4) +# define LZO_SIZEOF_VOID_P 4 +#elif defined(__ILP64__) || defined(__ILP64) || defined(_ILP64) +LZO_COMPILE_TIME_ASSERT_HEADER(sizeof(int) == 8) +LZO_COMPILE_TIME_ASSERT_HEADER(sizeof(long) == 8) +# define LZO_SIZEOF_VOID_P 8 +#elif defined(__LLP64__) || defined(__LLP64) || defined(_LLP64) || defined(_WIN64) +LZO_COMPILE_TIME_ASSERT_HEADER(sizeof(long) == 4) +# define LZO_SIZEOF_VOID_P 8 +#elif defined(__LP64__) || defined(__LP64) || defined(_LP64) +LZO_COMPILE_TIME_ASSERT_HEADER(sizeof(long) == 8) +# define LZO_SIZEOF_VOID_P 8 +#elif (LZO_ARCH_AVR) +# define LZO_SIZEOF_VOID_P 2 +#elif (LZO_ARCH_C166 || LZO_ARCH_MCS51 || LZO_ARCH_MCS251 || LZO_ARCH_MSP430) +# define LZO_SIZEOF_VOID_P 2 +#elif (LZO_ARCH_H8300) +# if defined(__H8300H__) || defined(__H8300S__) || defined(__H8300SX__) + LZO_COMPILE_TIME_ASSERT_HEADER(LZO_WORDSIZE == 4) +# if defined(__NORMAL_MODE__) +# define LZO_SIZEOF_VOID_P 2 +# else +# define LZO_SIZEOF_VOID_P 4 +# endif +# else + LZO_COMPILE_TIME_ASSERT_HEADER(LZO_WORDSIZE == 2) +# define LZO_SIZEOF_VOID_P 2 +# endif +# if (LZO_CC_GNUC && (LZO_CC_GNUC < 0x040000ul)) && (LZO_SIZEOF_INT == 4) +# define LZO_SIZEOF_SIZE_T LZO_SIZEOF_INT +# define LZO_SIZEOF_PTRDIFF_T LZO_SIZEOF_INT +# endif +#elif (LZO_ARCH_I086) +# if (LZO_MM_TINY || LZO_MM_SMALL || LZO_MM_MEDIUM) +# define LZO_SIZEOF_VOID_P 2 +# elif (LZO_MM_COMPACT || LZO_MM_LARGE || LZO_MM_HUGE) +# define LZO_SIZEOF_VOID_P 4 +# else +# error "invalid LZO_ARCH_I086 memory model" +# endif +#elif (LZO_ARCH_M16C) +# if defined(__m32c_cpu__) || defined(__m32cm_cpu__) +# define LZO_SIZEOF_VOID_P 4 +# else +# define LZO_SIZEOF_VOID_P 2 +# endif +#elif (LZO_ARCH_SPU) +# define LZO_SIZEOF_VOID_P 4 +#elif (LZO_ARCH_Z80) +# define LZO_SIZEOF_VOID_P 2 +#elif (LZO_SIZEOF_LONG == 8) && ((defined(__mips__) && defined(__R5900__)) || defined(__MIPS_PSX2__)) +# define LZO_SIZEOF_VOID_P 4 +#elif (LZO_OS_OS400 || defined(__OS400__)) +# if defined(__LLP64_IFC__) +# define LZO_SIZEOF_VOID_P 8 +# define LZO_SIZEOF_SIZE_T LZO_SIZEOF_LONG +# define LZO_SIZEOF_PTRDIFF_T LZO_SIZEOF_LONG +# else +# define LZO_SIZEOF_VOID_P 16 +# define LZO_SIZEOF_SIZE_T LZO_SIZEOF_LONG +# define LZO_SIZEOF_PTRDIFF_T LZO_SIZEOF_LONG +# endif +#elif (defined(__vms) || defined(__VMS)) && (__INITIAL_POINTER_SIZE+0 == 64) +# define LZO_SIZEOF_VOID_P 8 +# define LZO_SIZEOF_SIZE_T LZO_SIZEOF_LONG +# define LZO_SIZEOF_PTRDIFF_T LZO_SIZEOF_LONG +#endif +#endif +#if !defined(LZO_SIZEOF_VOID_P) +# define LZO_SIZEOF_VOID_P LZO_SIZEOF_LONG +#endif +LZO_COMPILE_TIME_ASSERT_HEADER(LZO_SIZEOF_VOID_P == sizeof(void *)) +#if !defined(LZO_SIZEOF_SIZE_T) +#if (LZO_ARCH_I086 || LZO_ARCH_M16C) +# define LZO_SIZEOF_SIZE_T 2 +#endif +#endif +#if !defined(LZO_SIZEOF_SIZE_T) +# define LZO_SIZEOF_SIZE_T LZO_SIZEOF_VOID_P +#endif +#if defined(offsetof) +LZO_COMPILE_TIME_ASSERT_HEADER(LZO_SIZEOF_SIZE_T == sizeof(size_t)) +#endif +#if !defined(LZO_SIZEOF_PTRDIFF_T) +#if (LZO_ARCH_I086) +# if (LZO_MM_TINY || LZO_MM_SMALL || LZO_MM_MEDIUM || LZO_MM_HUGE) +# define LZO_SIZEOF_PTRDIFF_T LZO_SIZEOF_VOID_P +# elif (LZO_MM_COMPACT || LZO_MM_LARGE) +# if (LZO_CC_BORLANDC || LZO_CC_TURBOC) +# define LZO_SIZEOF_PTRDIFF_T 4 +# else +# define LZO_SIZEOF_PTRDIFF_T 2 +# endif +# else +# error "invalid LZO_ARCH_I086 memory model" +# endif +#endif +#endif +#if !defined(LZO_SIZEOF_PTRDIFF_T) +# define LZO_SIZEOF_PTRDIFF_T LZO_SIZEOF_SIZE_T +#endif +#if defined(offsetof) +LZO_COMPILE_TIME_ASSERT_HEADER(LZO_SIZEOF_PTRDIFF_T == sizeof(ptrdiff_t)) +#endif +#if !defined(LZO_WORDSIZE) +# define LZO_WORDSIZE LZO_SIZEOF_VOID_P +#endif +#if (LZO_ABI_NEUTRAL_ENDIAN) +# undef LZO_ABI_BIG_ENDIAN +# undef LZO_ABI_LITTLE_ENDIAN +#elif !(LZO_ABI_BIG_ENDIAN) && !(LZO_ABI_LITTLE_ENDIAN) +#if (LZO_ARCH_ALPHA) && (LZO_ARCH_CRAY_MPP) +# define LZO_ABI_BIG_ENDIAN 1 +#elif (LZO_ARCH_IA64) && (LZO_OS_POSIX_LINUX || LZO_OS_WIN64) +# define LZO_ABI_LITTLE_ENDIAN 1 +#elif (LZO_ARCH_ALPHA || LZO_ARCH_AMD64 || LZO_ARCH_BLACKFIN || LZO_ARCH_CRIS || LZO_ARCH_I086 || LZO_ARCH_I386 || LZO_ARCH_MSP430 || LZO_ARCH_RISCV) +# define LZO_ABI_LITTLE_ENDIAN 1 +#elif (LZO_ARCH_AVR32 || LZO_ARCH_M68K || LZO_ARCH_S390 || LZO_ARCH_SPU) +# define LZO_ABI_BIG_ENDIAN 1 +#elif 1 && defined(__IAR_SYSTEMS_ICC__) && defined(__LITTLE_ENDIAN__) +# if (__LITTLE_ENDIAN__ == 1) +# define LZO_ABI_LITTLE_ENDIAN 1 +# else +# define LZO_ABI_BIG_ENDIAN 1 +# endif +#elif 1 && defined(__BIG_ENDIAN__) && !defined(__LITTLE_ENDIAN__) +# define LZO_ABI_BIG_ENDIAN 1 +#elif 1 && defined(__LITTLE_ENDIAN__) && !defined(__BIG_ENDIAN__) +# define LZO_ABI_LITTLE_ENDIAN 1 +#elif 1 && (LZO_ARCH_ARM) && defined(__ARM_BIG_ENDIAN) && ((__ARM_BIG_ENDIAN)+0) +# define LZO_ABI_BIG_ENDIAN 1 +#elif 1 && (LZO_ARCH_ARM) && defined(__ARMEB__) && !defined(__ARMEL__) +# define LZO_ABI_BIG_ENDIAN 1 +#elif 1 && (LZO_ARCH_ARM) && defined(__ARMEL__) && !defined(__ARMEB__) +# define LZO_ABI_LITTLE_ENDIAN 1 +#elif 1 && (LZO_ARCH_ARM) && defined(_MSC_VER) && defined(_WIN32) +# define LZO_ABI_LITTLE_ENDIAN 1 +#elif 1 && (LZO_ARCH_ARM && LZO_CC_ARMCC_ARMCC) +# if defined(__BIG_ENDIAN) && defined(__LITTLE_ENDIAN) +# error "unexpected configuration - check your compiler defines" +# elif defined(__BIG_ENDIAN) +# define LZO_ABI_BIG_ENDIAN 1 +# else +# define LZO_ABI_LITTLE_ENDIAN 1 +# endif +# define LZO_ABI_LITTLE_ENDIAN 1 +#elif 1 && (LZO_ARCH_ARM64) && defined(__ARM_BIG_ENDIAN) && ((__ARM_BIG_ENDIAN)+0) +# define LZO_ABI_BIG_ENDIAN 1 +#elif 1 && (LZO_ARCH_ARM64) && defined(__AARCH64EB__) && !defined(__AARCH64EL__) +# define LZO_ABI_BIG_ENDIAN 1 +#elif 1 && (LZO_ARCH_ARM64) && defined(__AARCH64EL__) && !defined(__AARCH64EB__) +# define LZO_ABI_LITTLE_ENDIAN 1 +#elif 1 && (LZO_ARCH_ARM64) && defined(_MSC_VER) && defined(_WIN32) +# define LZO_ABI_LITTLE_ENDIAN 1 +#elif 1 && (LZO_ARCH_MIPS) && defined(__MIPSEB__) && !defined(__MIPSEL__) +# define LZO_ABI_BIG_ENDIAN 1 +#elif 1 && (LZO_ARCH_MIPS) && defined(__MIPSEL__) && !defined(__MIPSEB__) +# define LZO_ABI_LITTLE_ENDIAN 1 +#endif +#endif +#if (LZO_ABI_BIG_ENDIAN) && (LZO_ABI_LITTLE_ENDIAN) +# error "unexpected configuration - check your compiler defines" +#endif +#if (LZO_ABI_BIG_ENDIAN) +# define LZO_INFO_ABI_ENDIAN "be" +#elif (LZO_ABI_LITTLE_ENDIAN) +# define LZO_INFO_ABI_ENDIAN "le" +#elif (LZO_ABI_NEUTRAL_ENDIAN) +# define LZO_INFO_ABI_ENDIAN "neutral" +#endif +#if (LZO_SIZEOF_INT == 1 && LZO_SIZEOF_LONG == 2 && LZO_SIZEOF_VOID_P == 2) +# define LZO_ABI_I8LP16 1 +# define LZO_INFO_ABI_PM "i8lp16" +#elif (LZO_SIZEOF_INT == 2 && LZO_SIZEOF_LONG == 2 && LZO_SIZEOF_VOID_P == 2) +# define LZO_ABI_ILP16 1 +# define LZO_INFO_ABI_PM "ilp16" +#elif (LZO_SIZEOF_INT == 2 && LZO_SIZEOF_LONG == 4 && LZO_SIZEOF_VOID_P == 4) +# define LZO_ABI_LP32 1 +# define LZO_INFO_ABI_PM "lp32" +#elif (LZO_SIZEOF_INT == 4 && LZO_SIZEOF_LONG == 4 && LZO_SIZEOF_VOID_P == 4) +# define LZO_ABI_ILP32 1 +# define LZO_INFO_ABI_PM "ilp32" +#elif (LZO_SIZEOF_INT == 4 && LZO_SIZEOF_LONG == 4 && LZO_SIZEOF_VOID_P == 8 && LZO_SIZEOF_SIZE_T == 8) +# define LZO_ABI_LLP64 1 +# define LZO_INFO_ABI_PM "llp64" +#elif (LZO_SIZEOF_INT == 4 && LZO_SIZEOF_LONG == 8 && LZO_SIZEOF_VOID_P == 8) +# define LZO_ABI_LP64 1 +# define LZO_INFO_ABI_PM "lp64" +#elif (LZO_SIZEOF_INT == 8 && LZO_SIZEOF_LONG == 8 && LZO_SIZEOF_VOID_P == 8) +# define LZO_ABI_ILP64 1 +# define LZO_INFO_ABI_PM "ilp64" +#elif (LZO_SIZEOF_INT == 4 && LZO_SIZEOF_LONG == 8 && LZO_SIZEOF_VOID_P == 4) +# define LZO_ABI_IP32L64 1 +# define LZO_INFO_ABI_PM "ip32l64" +#endif +#if (LZO_SIZEOF_INT == 4 && LZO_SIZEOF_VOID_P == 4 && LZO_WORDSIZE == 8) +# define LZO_ABI_IP32W64 1 +# ifndef LZO_INFO_ABI_PM +# define LZO_INFO_ABI_PM "ip32w64" +# endif +#endif +#if 0 +#elif !defined(__LZO_LIBC_OVERRIDE) +#if (LZO_LIBC_NAKED) +# define LZO_INFO_LIBC "naked" +#elif (LZO_LIBC_FREESTANDING) +# define LZO_INFO_LIBC "freestanding" +#elif (LZO_LIBC_MOSTLY_FREESTANDING) +# define LZO_INFO_LIBC "mfreestanding" +#elif (LZO_LIBC_ISOC90) +# define LZO_INFO_LIBC "isoc90" +#elif (LZO_LIBC_ISOC99) +# define LZO_INFO_LIBC "isoc99" +#elif (LZO_CC_ARMCC_ARMCC) && defined(__ARMCLIB_VERSION) +# define LZO_LIBC_ISOC90 1 +# define LZO_INFO_LIBC "isoc90" +#elif defined(__dietlibc__) +# define LZO_LIBC_DIETLIBC 1 +# define LZO_INFO_LIBC "dietlibc" +#elif defined(_NEWLIB_VERSION) +# define LZO_LIBC_NEWLIB 1 +# define LZO_INFO_LIBC "newlib" +#elif defined(__UCLIBC__) && defined(__UCLIBC_MAJOR__) && defined(__UCLIBC_MINOR__) +# if defined(__UCLIBC_SUBLEVEL__) +# define LZO_LIBC_UCLIBC (__UCLIBC_MAJOR__ * 0x10000L + (__UCLIBC_MINOR__-0) * 0x100 + (__UCLIBC_SUBLEVEL__-0)) +# else +# define LZO_LIBC_UCLIBC 0x00090bL +# endif +# define LZO_INFO_LIBC "uc" "libc" +#elif defined(__GLIBC__) && defined(__GLIBC_MINOR__) +# define LZO_LIBC_GLIBC (__GLIBC__ * 0x10000L + (__GLIBC_MINOR__-0) * 0x100) +# define LZO_INFO_LIBC "glibc" +#elif (LZO_CC_MWERKS) && defined(__MSL__) +# define LZO_LIBC_MSL __MSL__ +# define LZO_INFO_LIBC "msl" +#elif 1 && defined(__IAR_SYSTEMS_ICC__) +# define LZO_LIBC_ISOC90 1 +# define LZO_INFO_LIBC "isoc90" +#else +# define LZO_LIBC_DEFAULT 1 +# define LZO_INFO_LIBC "default" +#endif +#endif +#if (LZO_ARCH_I386 && (LZO_OS_DOS32 || LZO_OS_WIN32) && (LZO_CC_DMC || LZO_CC_INTELC || LZO_CC_MSC || LZO_CC_PELLESC)) +# define LZO_ASM_SYNTAX_MSC 1 +#elif (LZO_OS_WIN64 && (LZO_CC_DMC || LZO_CC_INTELC || LZO_CC_MSC || LZO_CC_PELLESC)) +#elif (LZO_ARCH_I386 && LZO_CC_GNUC && (LZO_CC_GNUC == 0x011f00ul)) +#elif (LZO_ARCH_I386 && (LZO_CC_CLANG || LZO_CC_GNUC || LZO_CC_INTELC || LZO_CC_PATHSCALE)) +# define LZO_ASM_SYNTAX_GNUC 1 +#elif (LZO_ARCH_AMD64 && (LZO_CC_CLANG || LZO_CC_GNUC || LZO_CC_INTELC || LZO_CC_PATHSCALE)) +# define LZO_ASM_SYNTAX_GNUC 1 +#elif (LZO_CC_GNUC) +# define LZO_ASM_SYNTAX_GNUC 1 +#endif +#if (LZO_ASM_SYNTAX_GNUC) +#if (LZO_ARCH_I386 && LZO_CC_GNUC && (LZO_CC_GNUC < 0x020000ul)) +# define __LZO_ASM_CLOBBER "ax" +# define __LZO_ASM_CLOBBER_LIST_CC /*empty*/ +# define __LZO_ASM_CLOBBER_LIST_CC_MEMORY /*empty*/ +# define __LZO_ASM_CLOBBER_LIST_EMPTY /*empty*/ +#elif (LZO_CC_INTELC && (__INTEL_COMPILER < 1000)) +# define __LZO_ASM_CLOBBER "memory" +# define __LZO_ASM_CLOBBER_LIST_CC /*empty*/ +# define __LZO_ASM_CLOBBER_LIST_CC_MEMORY : "memory" +# define __LZO_ASM_CLOBBER_LIST_EMPTY /*empty*/ +#else +# define __LZO_ASM_CLOBBER "cc", "memory" +# define __LZO_ASM_CLOBBER_LIST_CC : "cc" +# define __LZO_ASM_CLOBBER_LIST_CC_MEMORY : "cc", "memory" +# define __LZO_ASM_CLOBBER_LIST_EMPTY /*empty*/ +#endif +#endif +#if (LZO_ARCH_ALPHA) +# define LZO_OPT_AVOID_UINT_INDEX 1 +#elif (LZO_ARCH_AMD64) +# define LZO_OPT_AVOID_INT_INDEX 1 +# define LZO_OPT_AVOID_UINT_INDEX 1 +# ifndef LZO_OPT_UNALIGNED16 +# define LZO_OPT_UNALIGNED16 1 +# endif +# ifndef LZO_OPT_UNALIGNED32 +# define LZO_OPT_UNALIGNED32 1 +# endif +# ifndef LZO_OPT_UNALIGNED64 +# define LZO_OPT_UNALIGNED64 1 +# endif +#elif (LZO_ARCH_ARM) +# if defined(__ARM_FEATURE_UNALIGNED) +# if ((__ARM_FEATURE_UNALIGNED)+0) +# ifndef LZO_OPT_UNALIGNED16 +# define LZO_OPT_UNALIGNED16 1 +# endif +# ifndef LZO_OPT_UNALIGNED32 +# define LZO_OPT_UNALIGNED32 1 +# endif +# endif +# elif 1 && (LZO_ARCH_ARM_THUMB2) +# ifndef LZO_OPT_UNALIGNED16 +# define LZO_OPT_UNALIGNED16 1 +# endif +# ifndef LZO_OPT_UNALIGNED32 +# define LZO_OPT_UNALIGNED32 1 +# endif +# elif 1 && defined(__ARM_ARCH) && ((__ARM_ARCH)+0 >= 7) +# ifndef LZO_OPT_UNALIGNED16 +# define LZO_OPT_UNALIGNED16 1 +# endif +# ifndef LZO_OPT_UNALIGNED32 +# define LZO_OPT_UNALIGNED32 1 +# endif +# elif 1 && defined(__TARGET_ARCH_ARM) && ((__TARGET_ARCH_ARM)+0 >= 7) +# ifndef LZO_OPT_UNALIGNED16 +# define LZO_OPT_UNALIGNED16 1 +# endif +# ifndef LZO_OPT_UNALIGNED32 +# define LZO_OPT_UNALIGNED32 1 +# endif +# elif 1 && defined(__TARGET_ARCH_ARM) && ((__TARGET_ARCH_ARM)+0 >= 6) && (defined(__TARGET_PROFILE_A) || defined(__TARGET_PROFILE_R)) +# ifndef LZO_OPT_UNALIGNED16 +# define LZO_OPT_UNALIGNED16 1 +# endif +# ifndef LZO_OPT_UNALIGNED32 +# define LZO_OPT_UNALIGNED32 1 +# endif +# elif 1 && defined(_MSC_VER) && defined(_M_ARM) && ((_M_ARM)+0 >= 7) +# ifndef LZO_OPT_UNALIGNED16 +# define LZO_OPT_UNALIGNED16 1 +# endif +# ifndef LZO_OPT_UNALIGNED32 +# define LZO_OPT_UNALIGNED32 1 +# endif +# endif +#elif (LZO_ARCH_ARM64) +# ifndef LZO_OPT_UNALIGNED16 +# define LZO_OPT_UNALIGNED16 1 +# endif +# ifndef LZO_OPT_UNALIGNED32 +# define LZO_OPT_UNALIGNED32 1 +# endif +# ifndef LZO_OPT_UNALIGNED64 +# define LZO_OPT_UNALIGNED64 1 +# endif +#elif (LZO_ARCH_CRIS) +# ifndef LZO_OPT_UNALIGNED16 +# define LZO_OPT_UNALIGNED16 1 +# endif +# ifndef LZO_OPT_UNALIGNED32 +# define LZO_OPT_UNALIGNED32 1 +# endif +#elif (LZO_ARCH_I386) +# ifndef LZO_OPT_UNALIGNED16 +# define LZO_OPT_UNALIGNED16 1 +# endif +# ifndef LZO_OPT_UNALIGNED32 +# define LZO_OPT_UNALIGNED32 1 +# endif +#elif (LZO_ARCH_IA64) +# define LZO_OPT_AVOID_INT_INDEX 1 +# define LZO_OPT_AVOID_UINT_INDEX 1 +# define LZO_OPT_PREFER_POSTINC 1 +#elif (LZO_ARCH_M68K) +# define LZO_OPT_PREFER_POSTINC 1 +# define LZO_OPT_PREFER_PREDEC 1 +# if defined(__mc68020__) && !defined(__mcoldfire__) +# ifndef LZO_OPT_UNALIGNED16 +# define LZO_OPT_UNALIGNED16 1 +# endif +# ifndef LZO_OPT_UNALIGNED32 +# define LZO_OPT_UNALIGNED32 1 +# endif +# endif +#elif (LZO_ARCH_MIPS) +# define LZO_OPT_AVOID_UINT_INDEX 1 +#elif (LZO_ARCH_POWERPC) +# define LZO_OPT_PREFER_PREINC 1 +# define LZO_OPT_PREFER_PREDEC 1 +# if (LZO_ABI_BIG_ENDIAN) || (LZO_WORDSIZE == 8) +# ifndef LZO_OPT_UNALIGNED16 +# define LZO_OPT_UNALIGNED16 1 +# endif +# ifndef LZO_OPT_UNALIGNED32 +# define LZO_OPT_UNALIGNED32 1 +# endif +# if (LZO_WORDSIZE == 8) +# ifndef LZO_OPT_UNALIGNED64 +# define LZO_OPT_UNALIGNED64 1 +# endif +# endif +# endif +#elif (LZO_ARCH_RISCV) +# define LZO_OPT_AVOID_UINT_INDEX 1 +# ifndef LZO_OPT_UNALIGNED16 +# define LZO_OPT_UNALIGNED16 1 +# endif +# ifndef LZO_OPT_UNALIGNED32 +# define LZO_OPT_UNALIGNED32 1 +# endif +# if (LZO_WORDSIZE == 8) +# ifndef LZO_OPT_UNALIGNED64 +# define LZO_OPT_UNALIGNED64 1 +# endif +# endif +#elif (LZO_ARCH_S390) +# ifndef LZO_OPT_UNALIGNED16 +# define LZO_OPT_UNALIGNED16 1 +# endif +# ifndef LZO_OPT_UNALIGNED32 +# define LZO_OPT_UNALIGNED32 1 +# endif +# if (LZO_WORDSIZE == 8) +# ifndef LZO_OPT_UNALIGNED64 +# define LZO_OPT_UNALIGNED64 1 +# endif +# endif +#elif (LZO_ARCH_SH) +# define LZO_OPT_PREFER_POSTINC 1 +# define LZO_OPT_PREFER_PREDEC 1 +#endif +#ifndef LZO_CFG_NO_INLINE_ASM +#if (LZO_ABI_NEUTRAL_ENDIAN) || (LZO_ARCH_GENERIC) +# define LZO_CFG_NO_INLINE_ASM 1 +#elif (LZO_CC_LLVM) +# define LZO_CFG_NO_INLINE_ASM 1 +#endif +#endif +#if (LZO_CFG_NO_INLINE_ASM) +# undef LZO_ASM_SYNTAX_MSC +# undef LZO_ASM_SYNTAX_GNUC +# undef __LZO_ASM_CLOBBER +# undef __LZO_ASM_CLOBBER_LIST_CC +# undef __LZO_ASM_CLOBBER_LIST_CC_MEMORY +# undef __LZO_ASM_CLOBBER_LIST_EMPTY +#endif +#ifndef LZO_CFG_NO_UNALIGNED +#if (LZO_ABI_NEUTRAL_ENDIAN) || (LZO_ARCH_GENERIC) +# define LZO_CFG_NO_UNALIGNED 1 +#endif +#endif +#if (LZO_CFG_NO_UNALIGNED) +# undef LZO_OPT_UNALIGNED16 +# undef LZO_OPT_UNALIGNED32 +# undef LZO_OPT_UNALIGNED64 +#endif +#if defined(__LZO_INFOSTR_MM) +#elif (LZO_MM_FLAT) && (defined(__LZO_INFOSTR_PM) || defined(LZO_INFO_ABI_PM)) +# define __LZO_INFOSTR_MM "" +#elif defined(LZO_INFO_MM) +# define __LZO_INFOSTR_MM "." LZO_INFO_MM +#else +# define __LZO_INFOSTR_MM "" +#endif +#if defined(__LZO_INFOSTR_PM) +#elif defined(LZO_INFO_ABI_PM) +# define __LZO_INFOSTR_PM "." LZO_INFO_ABI_PM +#else +# define __LZO_INFOSTR_PM "" +#endif +#if defined(__LZO_INFOSTR_ENDIAN) +#elif defined(LZO_INFO_ABI_ENDIAN) +# define __LZO_INFOSTR_ENDIAN "." LZO_INFO_ABI_ENDIAN +#else +# define __LZO_INFOSTR_ENDIAN "" +#endif +#if defined(__LZO_INFOSTR_OSNAME) +#elif defined(LZO_INFO_OS_CONSOLE) +# define __LZO_INFOSTR_OSNAME LZO_INFO_OS "." LZO_INFO_OS_CONSOLE +#elif defined(LZO_INFO_OS_POSIX) +# define __LZO_INFOSTR_OSNAME LZO_INFO_OS "." LZO_INFO_OS_POSIX +#else +# define __LZO_INFOSTR_OSNAME LZO_INFO_OS +#endif +#if defined(__LZO_INFOSTR_LIBC) +#elif defined(LZO_INFO_LIBC) +# define __LZO_INFOSTR_LIBC "." LZO_INFO_LIBC +#else +# define __LZO_INFOSTR_LIBC "" +#endif +#if defined(__LZO_INFOSTR_CCVER) +#elif defined(LZO_INFO_CCVER) +# define __LZO_INFOSTR_CCVER " " LZO_INFO_CCVER +#else +# define __LZO_INFOSTR_CCVER "" +#endif +#define LZO_INFO_STRING \ + LZO_INFO_ARCH __LZO_INFOSTR_MM __LZO_INFOSTR_PM __LZO_INFOSTR_ENDIAN \ + " " __LZO_INFOSTR_OSNAME __LZO_INFOSTR_LIBC " " LZO_INFO_CC __LZO_INFOSTR_CCVER +#if !(LZO_CFG_SKIP_LZO_TYPES) +#if (!(LZO_SIZEOF_SHORT+0 > 0 && LZO_SIZEOF_INT+0 > 0 && LZO_SIZEOF_LONG+0 > 0)) +# error "missing defines for sizes" +#endif +#if (!(LZO_SIZEOF_PTRDIFF_T+0 > 0 && LZO_SIZEOF_SIZE_T+0 > 0 && LZO_SIZEOF_VOID_P+0 > 0)) +# error "missing defines for sizes" +#endif +#define LZO_TYPEOF_CHAR 1u +#define LZO_TYPEOF_SHORT 2u +#define LZO_TYPEOF_INT 3u +#define LZO_TYPEOF_LONG 4u +#define LZO_TYPEOF_LONG_LONG 5u +#define LZO_TYPEOF___INT8 17u +#define LZO_TYPEOF___INT16 18u +#define LZO_TYPEOF___INT32 19u +#define LZO_TYPEOF___INT64 20u +#define LZO_TYPEOF___INT128 21u +#define LZO_TYPEOF___INT256 22u +#define LZO_TYPEOF___MODE_QI 33u +#define LZO_TYPEOF___MODE_HI 34u +#define LZO_TYPEOF___MODE_SI 35u +#define LZO_TYPEOF___MODE_DI 36u +#define LZO_TYPEOF___MODE_TI 37u +#define LZO_TYPEOF_CHAR_P 129u +#if !defined(lzo_llong_t) +#if (LZO_SIZEOF_LONG_LONG+0 > 0) +# if !(LZO_LANG_ASSEMBLER) + __lzo_gnuc_extension__ typedef long long lzo_llong_t__; + __lzo_gnuc_extension__ typedef unsigned long long lzo_ullong_t__; +# endif +# define lzo_llong_t lzo_llong_t__ +# define lzo_ullong_t lzo_ullong_t__ +#endif +#endif +#if !defined(lzo_int16e_t) +#if (LZO_CFG_PREFER_TYPEOF_ACC_INT16E_T == LZO_TYPEOF_SHORT) && (LZO_SIZEOF_SHORT != 2) +# undef LZO_CFG_PREFER_TYPEOF_ACC_INT16E_T +#endif +#if (LZO_SIZEOF_LONG == 2) && !(LZO_CFG_PREFER_TYPEOF_ACC_INT16E_T == LZO_TYPEOF_SHORT) +# define lzo_int16e_t long +# define lzo_uint16e_t unsigned long +# define LZO_TYPEOF_LZO_INT16E_T LZO_TYPEOF_LONG +#elif (LZO_SIZEOF_INT == 2) && !(LZO_CFG_PREFER_TYPEOF_ACC_INT16E_T == LZO_TYPEOF_SHORT) +# define lzo_int16e_t int +# define lzo_uint16e_t unsigned int +# define LZO_TYPEOF_LZO_INT16E_T LZO_TYPEOF_INT +#elif (LZO_SIZEOF_SHORT == 2) +# define lzo_int16e_t short int +# define lzo_uint16e_t unsigned short int +# define LZO_TYPEOF_LZO_INT16E_T LZO_TYPEOF_SHORT +#elif 1 && !(LZO_CFG_TYPE_NO_MODE_HI) && (LZO_CC_CLANG || (LZO_CC_GNUC >= 0x025f00ul) || LZO_CC_LLVM) +# if !(LZO_LANG_ASSEMBLER) + typedef int lzo_int16e_hi_t__ __attribute__((__mode__(__HI__))); + typedef unsigned int lzo_uint16e_hi_t__ __attribute__((__mode__(__HI__))); +# endif +# define lzo_int16e_t lzo_int16e_hi_t__ +# define lzo_uint16e_t lzo_uint16e_hi_t__ +# define LZO_TYPEOF_LZO_INT16E_T LZO_TYPEOF___MODE_HI +#elif (LZO_SIZEOF___INT16 == 2) +# define lzo_int16e_t __int16 +# define lzo_uint16e_t unsigned __int16 +# define LZO_TYPEOF_LZO_INT16E_T LZO_TYPEOF___INT16 +#else +#endif +#endif +#if defined(lzo_int16e_t) +# define LZO_SIZEOF_LZO_INT16E_T 2 + LZO_COMPILE_TIME_ASSERT_HEADER(sizeof(lzo_int16e_t) == 2) + LZO_COMPILE_TIME_ASSERT_HEADER(sizeof(lzo_int16e_t) == LZO_SIZEOF_LZO_INT16E_T) +#endif +#if !defined(lzo_int32e_t) +#if (LZO_CFG_PREFER_TYPEOF_ACC_INT32E_T == LZO_TYPEOF_INT) && (LZO_SIZEOF_INT != 4) +# undef LZO_CFG_PREFER_TYPEOF_ACC_INT32E_T +#endif +#if (LZO_SIZEOF_LONG == 4) && !(LZO_CFG_PREFER_TYPEOF_ACC_INT32E_T == LZO_TYPEOF_INT) +# define lzo_int32e_t long int +# define lzo_uint32e_t unsigned long int +# define LZO_TYPEOF_LZO_INT32E_T LZO_TYPEOF_LONG +#elif (LZO_SIZEOF_INT == 4) +# define lzo_int32e_t int +# define lzo_uint32e_t unsigned int +# define LZO_TYPEOF_LZO_INT32E_T LZO_TYPEOF_INT +#elif (LZO_SIZEOF_SHORT == 4) +# define lzo_int32e_t short int +# define lzo_uint32e_t unsigned short int +# define LZO_TYPEOF_LZO_INT32E_T LZO_TYPEOF_SHORT +#elif (LZO_SIZEOF_LONG_LONG == 4) +# define lzo_int32e_t lzo_llong_t +# define lzo_uint32e_t lzo_ullong_t +# define LZO_TYPEOF_LZO_INT32E_T LZO_TYPEOF_LONG_LONG +#elif 1 && !(LZO_CFG_TYPE_NO_MODE_SI) && (LZO_CC_CLANG || (LZO_CC_GNUC >= 0x025f00ul) || LZO_CC_LLVM) && (__INT_MAX__+0 > 2147483647L) +# if !(LZO_LANG_ASSEMBLER) + typedef int lzo_int32e_si_t__ __attribute__((__mode__(__SI__))); + typedef unsigned int lzo_uint32e_si_t__ __attribute__((__mode__(__SI__))); +# endif +# define lzo_int32e_t lzo_int32e_si_t__ +# define lzo_uint32e_t lzo_uint32e_si_t__ +# define LZO_TYPEOF_LZO_INT32E_T LZO_TYPEOF___MODE_SI +#elif 1 && !(LZO_CFG_TYPE_NO_MODE_SI) && (LZO_CC_GNUC >= 0x025f00ul) && defined(__AVR__) && (__LONG_MAX__+0 == 32767L) +# if !(LZO_LANG_ASSEMBLER) + typedef int lzo_int32e_si_t__ __attribute__((__mode__(__SI__))); + typedef unsigned int lzo_uint32e_si_t__ __attribute__((__mode__(__SI__))); +# endif +# define lzo_int32e_t lzo_int32e_si_t__ +# define lzo_uint32e_t lzo_uint32e_si_t__ +# define LZO_INT32_C(c) (c##LL) +# define LZO_UINT32_C(c) (c##ULL) +# define LZO_TYPEOF_LZO_INT32E_T LZO_TYPEOF___MODE_SI +#elif (LZO_SIZEOF___INT32 == 4) +# define lzo_int32e_t __int32 +# define lzo_uint32e_t unsigned __int32 +# define LZO_TYPEOF_LZO_INT32E_T LZO_TYPEOF___INT32 +#else +#endif +#endif +#if defined(lzo_int32e_t) +# define LZO_SIZEOF_LZO_INT32E_T 4 + LZO_COMPILE_TIME_ASSERT_HEADER(sizeof(lzo_int32e_t) == 4) + LZO_COMPILE_TIME_ASSERT_HEADER(sizeof(lzo_int32e_t) == LZO_SIZEOF_LZO_INT32E_T) +#endif +#if !defined(lzo_int64e_t) +#if (LZO_SIZEOF___INT64 == 8) +# if (LZO_CC_BORLANDC) && !defined(LZO_CFG_PREFER_TYPEOF_ACC_INT64E_T) +# define LZO_CFG_PREFER_TYPEOF_ACC_INT64E_T LZO_TYPEOF___INT64 +# endif +#endif +#if (LZO_CFG_PREFER_TYPEOF_ACC_INT64E_T == LZO_TYPEOF_LONG_LONG) && (LZO_SIZEOF_LONG_LONG != 8) +# undef LZO_CFG_PREFER_TYPEOF_ACC_INT64E_T +#endif +#if (LZO_CFG_PREFER_TYPEOF_ACC_INT64E_T == LZO_TYPEOF___INT64) && (LZO_SIZEOF___INT64 != 8) +# undef LZO_CFG_PREFER_TYPEOF_ACC_INT64E_T +#endif +#if (LZO_SIZEOF_INT == 8) && (LZO_SIZEOF_INT < LZO_SIZEOF_LONG) +# define lzo_int64e_t int +# define lzo_uint64e_t unsigned int +# define LZO_TYPEOF_LZO_INT64E_T LZO_TYPEOF_INT +#elif (LZO_SIZEOF_LONG == 8) && !(LZO_CFG_PREFER_TYPEOF_ACC_INT64E_T == LZO_TYPEOF_LONG_LONG) && !(LZO_CFG_PREFER_TYPEOF_ACC_INT64E_T == LZO_TYPEOF___INT64) +# define lzo_int64e_t long int +# define lzo_uint64e_t unsigned long int +# define LZO_TYPEOF_LZO_INT64E_T LZO_TYPEOF_LONG +#elif (LZO_SIZEOF_LONG_LONG == 8) && !(LZO_CFG_PREFER_TYPEOF_ACC_INT64E_T == LZO_TYPEOF___INT64) +# define lzo_int64e_t lzo_llong_t +# define lzo_uint64e_t lzo_ullong_t +# define LZO_TYPEOF_LZO_INT64E_T LZO_TYPEOF_LONG_LONG +# if (LZO_CC_BORLANDC) +# define LZO_INT64_C(c) ((c) + 0ll) +# define LZO_UINT64_C(c) ((c) + 0ull) +# elif 0 +# define LZO_INT64_C(c) (__lzo_gnuc_extension__ (c##LL)) +# define LZO_UINT64_C(c) (__lzo_gnuc_extension__ (c##ULL)) +# else +# define LZO_INT64_C(c) (c##LL) +# define LZO_UINT64_C(c) (c##ULL) +# endif +#elif (LZO_SIZEOF___INT64 == 8) +# define lzo_int64e_t __int64 +# define lzo_uint64e_t unsigned __int64 +# define LZO_TYPEOF_LZO_INT64E_T LZO_TYPEOF___INT64 +# if (LZO_CC_BORLANDC) +# define LZO_INT64_C(c) ((c) + 0i64) +# define LZO_UINT64_C(c) ((c) + 0ui64) +# else +# define LZO_INT64_C(c) (c##i64) +# define LZO_UINT64_C(c) (c##ui64) +# endif +#else +#endif +#endif +#if defined(lzo_int64e_t) +# define LZO_SIZEOF_LZO_INT64E_T 8 + LZO_COMPILE_TIME_ASSERT_HEADER(sizeof(lzo_int64e_t) == 8) + LZO_COMPILE_TIME_ASSERT_HEADER(sizeof(lzo_int64e_t) == LZO_SIZEOF_LZO_INT64E_T) +#endif +#if !defined(lzo_int32l_t) +#if defined(lzo_int32e_t) +# define lzo_int32l_t lzo_int32e_t +# define lzo_uint32l_t lzo_uint32e_t +# define LZO_SIZEOF_LZO_INT32L_T LZO_SIZEOF_LZO_INT32E_T +# define LZO_TYPEOF_LZO_INT32L_T LZO_TYPEOF_LZO_INT32E_T +#elif (LZO_SIZEOF_INT >= 4) && (LZO_SIZEOF_INT < LZO_SIZEOF_LONG) +# define lzo_int32l_t int +# define lzo_uint32l_t unsigned int +# define LZO_SIZEOF_LZO_INT32L_T LZO_SIZEOF_INT +# define LZO_TYPEOF_LZO_INT32L_T LZO_SIZEOF_INT +#elif (LZO_SIZEOF_LONG >= 4) +# define lzo_int32l_t long int +# define lzo_uint32l_t unsigned long int +# define LZO_SIZEOF_LZO_INT32L_T LZO_SIZEOF_LONG +# define LZO_TYPEOF_LZO_INT32L_T LZO_SIZEOF_LONG +#else +# error "lzo_int32l_t" +#endif +#endif +#if 1 + LZO_COMPILE_TIME_ASSERT_HEADER(sizeof(lzo_int32l_t) >= 4) + LZO_COMPILE_TIME_ASSERT_HEADER(sizeof(lzo_int32l_t) == LZO_SIZEOF_LZO_INT32L_T) +#endif +#if !defined(lzo_int64l_t) +#if defined(lzo_int64e_t) +# define lzo_int64l_t lzo_int64e_t +# define lzo_uint64l_t lzo_uint64e_t +# define LZO_SIZEOF_LZO_INT64L_T LZO_SIZEOF_LZO_INT64E_T +# define LZO_TYPEOF_LZO_INT64L_T LZO_TYPEOF_LZO_INT64E_T +#else +#endif +#endif +#if defined(lzo_int64l_t) + LZO_COMPILE_TIME_ASSERT_HEADER(sizeof(lzo_int64l_t) >= 8) + LZO_COMPILE_TIME_ASSERT_HEADER(sizeof(lzo_int64l_t) == LZO_SIZEOF_LZO_INT64L_T) +#endif +#if !defined(lzo_int32f_t) +#if (LZO_SIZEOF_SIZE_T >= 8) +# define lzo_int32f_t lzo_int64l_t +# define lzo_uint32f_t lzo_uint64l_t +# define LZO_SIZEOF_LZO_INT32F_T LZO_SIZEOF_LZO_INT64L_T +# define LZO_TYPEOF_LZO_INT32F_T LZO_TYPEOF_LZO_INT64L_T +#else +# define lzo_int32f_t lzo_int32l_t +# define lzo_uint32f_t lzo_uint32l_t +# define LZO_SIZEOF_LZO_INT32F_T LZO_SIZEOF_LZO_INT32L_T +# define LZO_TYPEOF_LZO_INT32F_T LZO_TYPEOF_LZO_INT32L_T +#endif +#endif +#if 1 + LZO_COMPILE_TIME_ASSERT_HEADER(sizeof(lzo_int32f_t) >= 4) + LZO_COMPILE_TIME_ASSERT_HEADER(sizeof(lzo_int32f_t) == LZO_SIZEOF_LZO_INT32F_T) +#endif +#if !defined(lzo_int64f_t) +#if defined(lzo_int64l_t) +# define lzo_int64f_t lzo_int64l_t +# define lzo_uint64f_t lzo_uint64l_t +# define LZO_SIZEOF_LZO_INT64F_T LZO_SIZEOF_LZO_INT64L_T +# define LZO_TYPEOF_LZO_INT64F_T LZO_TYPEOF_LZO_INT64L_T +#else +#endif +#endif +#if defined(lzo_int64f_t) + LZO_COMPILE_TIME_ASSERT_HEADER(sizeof(lzo_int64f_t) >= 8) + LZO_COMPILE_TIME_ASSERT_HEADER(sizeof(lzo_int64f_t) == LZO_SIZEOF_LZO_INT64F_T) +#endif +#if !defined(lzo_intptr_t) +#if 1 && (LZO_OS_OS400 && (LZO_SIZEOF_VOID_P == 16)) +# define __LZO_INTPTR_T_IS_POINTER 1 +# if !(LZO_LANG_ASSEMBLER) + typedef char * lzo_intptr_t; + typedef char * lzo_uintptr_t; +# endif +# define lzo_intptr_t lzo_intptr_t +# define lzo_uintptr_t lzo_uintptr_t +# define LZO_SIZEOF_LZO_INTPTR_T LZO_SIZEOF_VOID_P +# define LZO_TYPEOF_LZO_INTPTR_T LZO_TYPEOF_CHAR_P +#elif (LZO_CC_MSC && (_MSC_VER >= 1300) && (LZO_SIZEOF_VOID_P == 4) && (LZO_SIZEOF_INT == 4)) +# if !(LZO_LANG_ASSEMBLER) + typedef __w64 int lzo_intptr_t; + typedef __w64 unsigned int lzo_uintptr_t; +# endif +# define lzo_intptr_t lzo_intptr_t +# define lzo_uintptr_t lzo_uintptr_t +# define LZO_SIZEOF_LZO_INTPTR_T LZO_SIZEOF_INT +# define LZO_TYPEOF_LZO_INTPTR_T LZO_TYPEOF_INT +#elif (LZO_SIZEOF_SHORT == LZO_SIZEOF_VOID_P) && (LZO_SIZEOF_INT > LZO_SIZEOF_VOID_P) +# define lzo_intptr_t short +# define lzo_uintptr_t unsigned short +# define LZO_SIZEOF_LZO_INTPTR_T LZO_SIZEOF_SHORT +# define LZO_TYPEOF_LZO_INTPTR_T LZO_TYPEOF_SHORT +#elif (LZO_SIZEOF_INT >= LZO_SIZEOF_VOID_P) && (LZO_SIZEOF_INT < LZO_SIZEOF_LONG) +# define lzo_intptr_t int +# define lzo_uintptr_t unsigned int +# define LZO_SIZEOF_LZO_INTPTR_T LZO_SIZEOF_INT +# define LZO_TYPEOF_LZO_INTPTR_T LZO_TYPEOF_INT +#elif (LZO_SIZEOF_LONG >= LZO_SIZEOF_VOID_P) +# define lzo_intptr_t long +# define lzo_uintptr_t unsigned long +# define LZO_SIZEOF_LZO_INTPTR_T LZO_SIZEOF_LONG +# define LZO_TYPEOF_LZO_INTPTR_T LZO_TYPEOF_LONG +#elif (LZO_SIZEOF_LZO_INT64L_T >= LZO_SIZEOF_VOID_P) +# define lzo_intptr_t lzo_int64l_t +# define lzo_uintptr_t lzo_uint64l_t +# define LZO_SIZEOF_LZO_INTPTR_T LZO_SIZEOF_LZO_INT64L_T +# define LZO_TYPEOF_LZO_INTPTR_T LZO_TYPEOF_LZO_INT64L_T +#else +# error "lzo_intptr_t" +#endif +#endif +#if 1 + LZO_COMPILE_TIME_ASSERT_HEADER(sizeof(lzo_intptr_t) >= sizeof(void *)) + LZO_COMPILE_TIME_ASSERT_HEADER(sizeof(lzo_intptr_t) == sizeof(lzo_uintptr_t)) +#endif +#if !defined(lzo_word_t) +#if defined(LZO_WORDSIZE) && (LZO_WORDSIZE+0 > 0) +#if (LZO_WORDSIZE == LZO_SIZEOF_LZO_INTPTR_T) && !(__LZO_INTPTR_T_IS_POINTER) +# define lzo_word_t lzo_uintptr_t +# define lzo_sword_t lzo_intptr_t +# define LZO_SIZEOF_LZO_WORD_T LZO_SIZEOF_LZO_INTPTR_T +# define LZO_TYPEOF_LZO_WORD_T LZO_TYPEOF_LZO_INTPTR_T +#elif (LZO_WORDSIZE == LZO_SIZEOF_LONG) +# define lzo_word_t unsigned long +# define lzo_sword_t long +# define LZO_SIZEOF_LZO_WORD_T LZO_SIZEOF_LONG +# define LZO_TYPEOF_LZO_WORD_T LZO_TYPEOF_LONG +#elif (LZO_WORDSIZE == LZO_SIZEOF_INT) +# define lzo_word_t unsigned int +# define lzo_sword_t int +# define LZO_SIZEOF_LZO_WORD_T LZO_SIZEOF_INT +# define LZO_TYPEOF_LZO_WORD_T LZO_TYPEOF_INT +#elif (LZO_WORDSIZE == LZO_SIZEOF_SHORT) +# define lzo_word_t unsigned short +# define lzo_sword_t short +# define LZO_SIZEOF_LZO_WORD_T LZO_SIZEOF_SHORT +# define LZO_TYPEOF_LZO_WORD_T LZO_TYPEOF_SHORT +#elif (LZO_WORDSIZE == 1) +# define lzo_word_t unsigned char +# define lzo_sword_t signed char +# define LZO_SIZEOF_LZO_WORD_T 1 +# define LZO_TYPEOF_LZO_WORD_T LZO_TYPEOF_CHAR +#elif (LZO_WORDSIZE == LZO_SIZEOF_LZO_INT64L_T) +# define lzo_word_t lzo_uint64l_t +# define lzo_sword_t lzo_int64l_t +# define LZO_SIZEOF_LZO_WORD_T LZO_SIZEOF_LZO_INT64L_T +# define LZO_TYPEOF_LZO_WORD_T LZO_SIZEOF_LZO_INT64L_T +#elif (LZO_ARCH_SPU) && (LZO_CC_GNUC) +#if 0 +# if !(LZO_LANG_ASSEMBLER) + typedef unsigned lzo_word_t __attribute__((__mode__(__V16QI__))); + typedef int lzo_sword_t __attribute__((__mode__(__V16QI__))); +# endif +# define lzo_word_t lzo_word_t +# define lzo_sword_t lzo_sword_t +# define LZO_SIZEOF_LZO_WORD_T 16 +# define LZO_TYPEOF_LZO_WORD_T LZO_TYPEOF___MODE_V16QI +#endif +#else +# error "lzo_word_t" +#endif +#endif +#endif +#if 1 && defined(lzo_word_t) + LZO_COMPILE_TIME_ASSERT_HEADER(sizeof(lzo_word_t) == LZO_WORDSIZE) + LZO_COMPILE_TIME_ASSERT_HEADER(sizeof(lzo_sword_t) == LZO_WORDSIZE) +#endif +#if 1 +#define lzo_int8_t signed char +#define lzo_uint8_t unsigned char +#define LZO_SIZEOF_LZO_INT8_T 1 +#define LZO_TYPEOF_LZO_INT8_T LZO_TYPEOF_CHAR +LZO_COMPILE_TIME_ASSERT_HEADER(sizeof(lzo_int8_t) == 1) +LZO_COMPILE_TIME_ASSERT_HEADER(sizeof(lzo_int8_t) == sizeof(lzo_uint8_t)) +#endif +#if defined(lzo_int16e_t) +#define lzo_int16_t lzo_int16e_t +#define lzo_uint16_t lzo_uint16e_t +#define LZO_SIZEOF_LZO_INT16_T LZO_SIZEOF_LZO_INT16E_T +#define LZO_TYPEOF_LZO_INT16_T LZO_TYPEOF_LZO_INT16E_T +LZO_COMPILE_TIME_ASSERT_HEADER(sizeof(lzo_int16_t) == 2) +LZO_COMPILE_TIME_ASSERT_HEADER(sizeof(lzo_int16_t) == sizeof(lzo_uint16_t)) +#endif +#if defined(lzo_int32e_t) +#define lzo_int32_t lzo_int32e_t +#define lzo_uint32_t lzo_uint32e_t +#define LZO_SIZEOF_LZO_INT32_T LZO_SIZEOF_LZO_INT32E_T +#define LZO_TYPEOF_LZO_INT32_T LZO_TYPEOF_LZO_INT32E_T +LZO_COMPILE_TIME_ASSERT_HEADER(sizeof(lzo_int32_t) == 4) +LZO_COMPILE_TIME_ASSERT_HEADER(sizeof(lzo_int32_t) == sizeof(lzo_uint32_t)) +#endif +#if defined(lzo_int64e_t) +#define lzo_int64_t lzo_int64e_t +#define lzo_uint64_t lzo_uint64e_t +#define LZO_SIZEOF_LZO_INT64_T LZO_SIZEOF_LZO_INT64E_T +#define LZO_TYPEOF_LZO_INT64_T LZO_TYPEOF_LZO_INT64E_T +LZO_COMPILE_TIME_ASSERT_HEADER(sizeof(lzo_int64_t) == 8) +LZO_COMPILE_TIME_ASSERT_HEADER(sizeof(lzo_int64_t) == sizeof(lzo_uint64_t)) +#endif +#if 1 +#define lzo_int_least32_t lzo_int32l_t +#define lzo_uint_least32_t lzo_uint32l_t +#define LZO_SIZEOF_LZO_INT_LEAST32_T LZO_SIZEOF_LZO_INT32L_T +#define LZO_TYPEOF_LZO_INT_LEAST32_T LZO_TYPEOF_LZO_INT32L_T +LZO_COMPILE_TIME_ASSERT_HEADER(sizeof(lzo_int_least32_t) >= 4) +LZO_COMPILE_TIME_ASSERT_HEADER(sizeof(lzo_int_least32_t) == sizeof(lzo_uint_least32_t)) +#endif +#if defined(lzo_int64l_t) +#define lzo_int_least64_t lzo_int64l_t +#define lzo_uint_least64_t lzo_uint64l_t +#define LZO_SIZEOF_LZO_INT_LEAST64_T LZO_SIZEOF_LZO_INT64L_T +#define LZO_TYPEOF_LZO_INT_LEAST64_T LZO_TYPEOF_LZO_INT64L_T +LZO_COMPILE_TIME_ASSERT_HEADER(sizeof(lzo_int_least64_t) >= 8) +LZO_COMPILE_TIME_ASSERT_HEADER(sizeof(lzo_int_least64_t) == sizeof(lzo_uint_least64_t)) +#endif +#if 1 +#define lzo_int_fast32_t lzo_int32f_t +#define lzo_uint_fast32_t lzo_uint32f_t +#define LZO_SIZEOF_LZO_INT_FAST32_T LZO_SIZEOF_LZO_INT32F_T +#define LZO_TYPEOF_LZO_INT_FAST32_T LZO_TYPEOF_LZO_INT32F_T +LZO_COMPILE_TIME_ASSERT_HEADER(sizeof(lzo_int_fast32_t) >= 4) +LZO_COMPILE_TIME_ASSERT_HEADER(sizeof(lzo_int_fast32_t) == sizeof(lzo_uint_fast32_t)) +#endif +#if defined(lzo_int64f_t) +#define lzo_int_fast64_t lzo_int64f_t +#define lzo_uint_fast64_t lzo_uint64f_t +#define LZO_SIZEOF_LZO_INT_FAST64_T LZO_SIZEOF_LZO_INT64F_T +#define LZO_TYPEOF_LZO_INT_FAST64_T LZO_TYPEOF_LZO_INT64F_T +LZO_COMPILE_TIME_ASSERT_HEADER(sizeof(lzo_int_fast64_t) >= 8) +LZO_COMPILE_TIME_ASSERT_HEADER(sizeof(lzo_int_fast64_t) == sizeof(lzo_uint_fast64_t)) +#endif +#if !defined(LZO_INT16_C) +# if (LZO_BROKEN_INTEGRAL_CONSTANTS) && (LZO_SIZEOF_INT >= 2) +# define LZO_INT16_C(c) ((c) + 0) +# define LZO_UINT16_C(c) ((c) + 0U) +# elif (LZO_BROKEN_INTEGRAL_CONSTANTS) && (LZO_SIZEOF_LONG >= 2) +# define LZO_INT16_C(c) ((c) + 0L) +# define LZO_UINT16_C(c) ((c) + 0UL) +# elif (LZO_SIZEOF_INT >= 2) +# define LZO_INT16_C(c) (c) +# define LZO_UINT16_C(c) (c##U) +# elif (LZO_SIZEOF_LONG >= 2) +# define LZO_INT16_C(c) (c##L) +# define LZO_UINT16_C(c) (c##UL) +# else +# error "LZO_INT16_C" +# endif +#endif +#if !defined(LZO_INT32_C) +# if (LZO_BROKEN_INTEGRAL_CONSTANTS) && (LZO_SIZEOF_INT >= 4) +# define LZO_INT32_C(c) ((c) + 0) +# define LZO_UINT32_C(c) ((c) + 0U) +# elif (LZO_BROKEN_INTEGRAL_CONSTANTS) && (LZO_SIZEOF_LONG >= 4) +# define LZO_INT32_C(c) ((c) + 0L) +# define LZO_UINT32_C(c) ((c) + 0UL) +# elif (LZO_SIZEOF_INT >= 4) +# define LZO_INT32_C(c) (c) +# define LZO_UINT32_C(c) (c##U) +# elif (LZO_SIZEOF_LONG >= 4) +# define LZO_INT32_C(c) (c##L) +# define LZO_UINT32_C(c) (c##UL) +# elif (LZO_SIZEOF_LONG_LONG >= 4) +# define LZO_INT32_C(c) (c##LL) +# define LZO_UINT32_C(c) (c##ULL) +# else +# error "LZO_INT32_C" +# endif +#endif +#if !defined(LZO_INT64_C) && defined(lzo_int64l_t) +# if (LZO_BROKEN_INTEGRAL_CONSTANTS) && (LZO_SIZEOF_INT >= 8) +# define LZO_INT64_C(c) ((c) + 0) +# define LZO_UINT64_C(c) ((c) + 0U) +# elif (LZO_BROKEN_INTEGRAL_CONSTANTS) && (LZO_SIZEOF_LONG >= 8) +# define LZO_INT64_C(c) ((c) + 0L) +# define LZO_UINT64_C(c) ((c) + 0UL) +# elif (LZO_SIZEOF_INT >= 8) +# define LZO_INT64_C(c) (c) +# define LZO_UINT64_C(c) (c##U) +# elif (LZO_SIZEOF_LONG >= 8) +# define LZO_INT64_C(c) (c##L) +# define LZO_UINT64_C(c) (c##UL) +# else +# error "LZO_INT64_C" +# endif +#endif +#endif + +#endif + +#endif + +#undef LZO_HAVE_CONFIG_H +#include "minilzo.h" + +#if !defined(MINILZO_VERSION) || (MINILZO_VERSION != 0x20a0) +# error "version mismatch in miniLZO source files" +#endif + +#ifdef MINILZO_HAVE_CONFIG_H +# define LZO_HAVE_CONFIG_H 1 +#endif + +#ifndef __LZO_CONF_H +#define __LZO_CONF_H 1 + +#if !defined(__LZO_IN_MINILZO) +#if defined(LZO_CFG_FREESTANDING) && (LZO_CFG_FREESTANDING) +# define LZO_LIBC_FREESTANDING 1 +# define LZO_OS_FREESTANDING 1 +#endif +#if defined(LZO_CFG_EXTRA_CONFIG_HEADER) +# include LZO_CFG_EXTRA_CONFIG_HEADER +#endif +#if defined(__LZOCONF_H) || defined(__LZOCONF_H_INCLUDED) +# error "include this file first" +#endif +#if defined(LZO_CFG_BUILD_DLL) && (LZO_CFG_BUILD_DLL+0) && !defined(__LZO_EXPORT1) && !defined(__LZO_EXPORT2) && 0 +#ifndef __LZODEFS_H_INCLUDED +#if defined(LZO_HAVE_CONFIG_H) +# include +#endif +#include +#include +#include +#endif +#endif +#include +#if defined(LZO_CFG_EXTRA_CONFIG_HEADER2) +# include LZO_CFG_EXTRA_CONFIG_HEADER2 +#endif +#endif + +#if !defined(__LZOCONF_H_INCLUDED) || (LZO_VERSION+0 != 0x20a0) +# error "version mismatch" +#endif + +#if (LZO_CC_MSC && (_MSC_VER >= 1000 && _MSC_VER < 1100)) +# pragma warning(disable: 4702) +#endif +#if (LZO_CC_MSC && (_MSC_VER >= 1000)) +# pragma warning(disable: 4127 4701) +# pragma warning(disable: 4514 4710 4711) +#endif +#if (LZO_CC_MSC && (_MSC_VER >= 1300)) +# pragma warning(disable: 4820) +#endif +#if (LZO_CC_MSC && (_MSC_VER >= 1800)) +# pragma warning(disable: 4746) +#endif +#if (LZO_CC_INTELC && (__INTEL_COMPILER >= 900)) +# pragma warning(disable: 1684) +#endif + +#if (LZO_CC_SUNPROC) +#if !defined(__cplusplus) +# pragma error_messages(off,E_END_OF_LOOP_CODE_NOT_REACHED) +# pragma error_messages(off,E_LOOP_NOT_ENTERED_AT_TOP) +# pragma error_messages(off,E_STATEMENT_NOT_REACHED) +#endif +#endif + +#if !defined(__LZO_NOEXPORT1) +# define __LZO_NOEXPORT1 /*empty*/ +#endif +#if !defined(__LZO_NOEXPORT2) +# define __LZO_NOEXPORT2 /*empty*/ +#endif + +#if 1 +# define LZO_PUBLIC_DECL(r) LZO_EXTERN(r) +#endif +#if 1 +# define LZO_PUBLIC_IMPL(r) LZO_PUBLIC(r) +#endif +#if !defined(LZO_LOCAL_DECL) +# define LZO_LOCAL_DECL(r) __LZO_EXTERN_C LZO_LOCAL_IMPL(r) +#endif +#if !defined(LZO_LOCAL_IMPL) +# define LZO_LOCAL_IMPL(r) __LZO_NOEXPORT1 r __LZO_NOEXPORT2 __LZO_CDECL +#endif +#if 1 +# define LZO_STATIC_DECL(r) LZO_PRIVATE(r) +#endif +#if 1 +# define LZO_STATIC_IMPL(r) LZO_PRIVATE(r) +#endif + +#if defined(__LZO_IN_MINILZO) || (LZO_CFG_FREESTANDING) +#elif 1 +# include +#else +# define LZO_WANT_ACC_INCD_H 1 +#endif +#if defined(LZO_HAVE_CONFIG_H) +# define LZO_CFG_NO_CONFIG_HEADER 1 +#endif + +#if 1 && !defined(LZO_CFG_FREESTANDING) +#if 1 && !defined(HAVE_STRING_H) +#define HAVE_STRING_H 1 +#endif +#if 1 && !defined(HAVE_MEMCMP) +#define HAVE_MEMCMP 1 +#endif +#if 1 && !defined(HAVE_MEMCPY) +#define HAVE_MEMCPY 1 +#endif +#if 1 && !defined(HAVE_MEMMOVE) +#define HAVE_MEMMOVE 1 +#endif +#if 1 && !defined(HAVE_MEMSET) +#define HAVE_MEMSET 1 +#endif +#endif + +#if 1 && defined(HAVE_STRING_H) +#include +#endif + +#if 1 || defined(lzo_int8_t) || defined(lzo_uint8_t) +LZO_COMPILE_TIME_ASSERT_HEADER(sizeof(lzo_int8_t) == 1) +LZO_COMPILE_TIME_ASSERT_HEADER(sizeof(lzo_uint8_t) == 1) +#endif +#if 1 || defined(lzo_int16_t) || defined(lzo_uint16_t) +LZO_COMPILE_TIME_ASSERT_HEADER(sizeof(lzo_int16_t) == 2) +LZO_COMPILE_TIME_ASSERT_HEADER(sizeof(lzo_uint16_t) == 2) +#endif +#if 1 || defined(lzo_int32_t) || defined(lzo_uint32_t) +LZO_COMPILE_TIME_ASSERT_HEADER(sizeof(lzo_int32_t) == 4) +LZO_COMPILE_TIME_ASSERT_HEADER(sizeof(lzo_uint32_t) == 4) +#endif +#if defined(lzo_int64_t) || defined(lzo_uint64_t) +LZO_COMPILE_TIME_ASSERT_HEADER(sizeof(lzo_int64_t) == 8) +LZO_COMPILE_TIME_ASSERT_HEADER(sizeof(lzo_uint64_t) == 8) +#endif + +#if (LZO_CFG_FREESTANDING) +# undef HAVE_MEMCMP +# undef HAVE_MEMCPY +# undef HAVE_MEMMOVE +# undef HAVE_MEMSET +#endif + +#if !(HAVE_MEMCMP) +# undef memcmp +# define memcmp(a,b,c) lzo_memcmp(a,b,c) +#else +# undef lzo_memcmp +# define lzo_memcmp(a,b,c) memcmp(a,b,c) +#endif +#if !(HAVE_MEMCPY) +# undef memcpy +# define memcpy(a,b,c) lzo_memcpy(a,b,c) +#else +# undef lzo_memcpy +# define lzo_memcpy(a,b,c) memcpy(a,b,c) +#endif +#if !(HAVE_MEMMOVE) +# undef memmove +# define memmove(a,b,c) lzo_memmove(a,b,c) +#else +# undef lzo_memmove +# define lzo_memmove(a,b,c) memmove(a,b,c) +#endif +#if !(HAVE_MEMSET) +# undef memset +# define memset(a,b,c) lzo_memset(a,b,c) +#else +# undef lzo_memset +# define lzo_memset(a,b,c) memset(a,b,c) +#endif + +#undef NDEBUG +#if (LZO_CFG_FREESTANDING) +# undef LZO_DEBUG +# define NDEBUG 1 +# undef assert +# define assert(e) ((void)0) +#else +# if !defined(LZO_DEBUG) +# define NDEBUG 1 +# endif +# include +#endif + +#if 0 && defined(__BOUNDS_CHECKING_ON) +# include +#else +# define BOUNDS_CHECKING_OFF_DURING(stmt) stmt +# define BOUNDS_CHECKING_OFF_IN_EXPR(expr) (expr) +#endif + +#if (LZO_CFG_PGO) +# undef __lzo_likely +# undef __lzo_unlikely +# define __lzo_likely(e) (e) +# define __lzo_unlikely(e) (e) +#endif + +#undef _ +#undef __ +#undef ___ +#undef ____ +#undef _p0 +#undef _p1 +#undef _p2 +#undef _p3 +#undef _p4 +#undef _s0 +#undef _s1 +#undef _s2 +#undef _s3 +#undef _s4 +#undef _ww + +#if 1 +# define LZO_BYTE(x) ((unsigned char) (x)) +#else +# define LZO_BYTE(x) ((unsigned char) ((x) & 0xff)) +#endif + +#define LZO_MAX(a,b) ((a) >= (b) ? (a) : (b)) +#define LZO_MIN(a,b) ((a) <= (b) ? (a) : (b)) +#define LZO_MAX3(a,b,c) ((a) >= (b) ? LZO_MAX(a,c) : LZO_MAX(b,c)) +#define LZO_MIN3(a,b,c) ((a) <= (b) ? LZO_MIN(a,c) : LZO_MIN(b,c)) + +#define lzo_sizeof(type) ((lzo_uint) (sizeof(type))) + +#define LZO_HIGH(array) ((lzo_uint) (sizeof(array)/sizeof(*(array)))) + +#define LZO_SIZE(bits) (1u << (bits)) +#define LZO_MASK(bits) (LZO_SIZE(bits) - 1) + +#define LZO_USIZE(bits) ((lzo_uint) 1 << (bits)) +#define LZO_UMASK(bits) (LZO_USIZE(bits) - 1) + +#if !defined(DMUL) +#if 0 + +# define DMUL(a,b) ((lzo_xint) ((lzo_uint32_t)(a) * (lzo_uint32_t)(b))) +#else +# define DMUL(a,b) ((lzo_xint) ((a) * (b))) +#endif +#endif + +#ifndef __LZO_FUNC_H +#define __LZO_FUNC_H 1 + +#if !defined(LZO_BITOPS_USE_ASM_BITSCAN) && !defined(LZO_BITOPS_USE_GNUC_BITSCAN) && !defined(LZO_BITOPS_USE_MSC_BITSCAN) +#if 1 && (LZO_ARCH_AMD64) && (LZO_CC_GNUC && (LZO_CC_GNUC < 0x040000ul)) && (LZO_ASM_SYNTAX_GNUC) +#define LZO_BITOPS_USE_ASM_BITSCAN 1 +#elif (LZO_CC_CLANG || (LZO_CC_GNUC >= 0x030400ul) || (LZO_CC_INTELC_GNUC && (__INTEL_COMPILER >= 1000)) || (LZO_CC_LLVM && (!defined(__llvm_tools_version__) || (__llvm_tools_version__+0 >= 0x010500ul)))) +#define LZO_BITOPS_USE_GNUC_BITSCAN 1 +#elif (LZO_OS_WIN32 || LZO_OS_WIN64) && ((LZO_CC_INTELC_MSC && (__INTEL_COMPILER >= 1010)) || (LZO_CC_MSC && (_MSC_VER >= 1400))) +#define LZO_BITOPS_USE_MSC_BITSCAN 1 +#if (LZO_CC_MSC) && (LZO_ARCH_AMD64 || LZO_ARCH_I386) +#include +#endif +#if (LZO_CC_MSC) && (LZO_ARCH_AMD64 || LZO_ARCH_I386) +#pragma intrinsic(_BitScanReverse) +#pragma intrinsic(_BitScanForward) +#endif +#if (LZO_CC_MSC) && (LZO_ARCH_AMD64) +#pragma intrinsic(_BitScanReverse64) +#pragma intrinsic(_BitScanForward64) +#endif +#endif +#endif + +__lzo_static_forceinline unsigned lzo_bitops_ctlz32_func(lzo_uint32_t v) +{ +#if (LZO_BITOPS_USE_MSC_BITSCAN) && (LZO_ARCH_AMD64 || LZO_ARCH_I386) + unsigned long r; (void) _BitScanReverse(&r, v); return (unsigned) r ^ 31; +#define lzo_bitops_ctlz32(v) lzo_bitops_ctlz32_func(v) +#elif (LZO_BITOPS_USE_ASM_BITSCAN) && (LZO_ARCH_AMD64 || LZO_ARCH_I386) && (LZO_ASM_SYNTAX_GNUC) + lzo_uint32_t r; + __asm__("bsr %1,%0" : "=r" (r) : "rm" (v) __LZO_ASM_CLOBBER_LIST_CC); + return (unsigned) r ^ 31; +#define lzo_bitops_ctlz32(v) lzo_bitops_ctlz32_func(v) +#elif (LZO_BITOPS_USE_GNUC_BITSCAN) && (LZO_SIZEOF_INT == 4) + unsigned r; r = (unsigned) __builtin_clz(v); return r; +#define lzo_bitops_ctlz32(v) ((unsigned) __builtin_clz(v)) +#elif (LZO_BITOPS_USE_GNUC_BITSCAN) && (LZO_SIZEOF_LONG == 8) && (LZO_WORDSIZE >= 8) + unsigned r; r = (unsigned) __builtin_clzl(v); return r ^ 32; +#define lzo_bitops_ctlz32(v) (((unsigned) __builtin_clzl(v)) ^ 32) +#else + LZO_UNUSED(v); return 0; +#endif +} + +#if defined(lzo_uint64_t) +__lzo_static_forceinline unsigned lzo_bitops_ctlz64_func(lzo_uint64_t v) +{ +#if (LZO_BITOPS_USE_MSC_BITSCAN) && (LZO_ARCH_AMD64) + unsigned long r; (void) _BitScanReverse64(&r, v); return (unsigned) r ^ 63; +#define lzo_bitops_ctlz64(v) lzo_bitops_ctlz64_func(v) +#elif (LZO_BITOPS_USE_ASM_BITSCAN) && (LZO_ARCH_AMD64) && (LZO_ASM_SYNTAX_GNUC) + lzo_uint64_t r; + __asm__("bsr %1,%0" : "=r" (r) : "rm" (v) __LZO_ASM_CLOBBER_LIST_CC); + return (unsigned) r ^ 63; +#define lzo_bitops_ctlz64(v) lzo_bitops_ctlz64_func(v) +#elif (LZO_BITOPS_USE_GNUC_BITSCAN) && (LZO_SIZEOF_LONG == 8) && (LZO_WORDSIZE >= 8) + unsigned r; r = (unsigned) __builtin_clzl(v); return r; +#define lzo_bitops_ctlz64(v) ((unsigned) __builtin_clzl(v)) +#elif (LZO_BITOPS_USE_GNUC_BITSCAN) && (LZO_SIZEOF_LONG_LONG == 8) && (LZO_WORDSIZE >= 8) + unsigned r; r = (unsigned) __builtin_clzll(v); return r; +#define lzo_bitops_ctlz64(v) ((unsigned) __builtin_clzll(v)) +#else + LZO_UNUSED(v); return 0; +#endif +} +#endif + +__lzo_static_forceinline unsigned lzo_bitops_cttz32_func(lzo_uint32_t v) +{ +#if (LZO_BITOPS_USE_MSC_BITSCAN) && (LZO_ARCH_AMD64 || LZO_ARCH_I386) + unsigned long r; (void) _BitScanForward(&r, v); return (unsigned) r; +#define lzo_bitops_cttz32(v) lzo_bitops_cttz32_func(v) +#elif (LZO_BITOPS_USE_ASM_BITSCAN) && (LZO_ARCH_AMD64 || LZO_ARCH_I386) && (LZO_ASM_SYNTAX_GNUC) + lzo_uint32_t r; + __asm__("bsf %1,%0" : "=r" (r) : "rm" (v) __LZO_ASM_CLOBBER_LIST_CC); + return (unsigned) r; +#define lzo_bitops_cttz32(v) lzo_bitops_cttz32_func(v) +#elif (LZO_BITOPS_USE_GNUC_BITSCAN) && (LZO_SIZEOF_INT >= 4) + unsigned r; r = (unsigned) __builtin_ctz(v); return r; +#define lzo_bitops_cttz32(v) ((unsigned) __builtin_ctz(v)) +#else + LZO_UNUSED(v); return 0; +#endif +} + +#if defined(lzo_uint64_t) +__lzo_static_forceinline unsigned lzo_bitops_cttz64_func(lzo_uint64_t v) +{ +#if (LZO_BITOPS_USE_MSC_BITSCAN) && (LZO_ARCH_AMD64) + unsigned long r; (void) _BitScanForward64(&r, v); return (unsigned) r; +#define lzo_bitops_cttz64(v) lzo_bitops_cttz64_func(v) +#elif (LZO_BITOPS_USE_ASM_BITSCAN) && (LZO_ARCH_AMD64) && (LZO_ASM_SYNTAX_GNUC) + lzo_uint64_t r; + __asm__("bsf %1,%0" : "=r" (r) : "rm" (v) __LZO_ASM_CLOBBER_LIST_CC); + return (unsigned) r; +#define lzo_bitops_cttz64(v) lzo_bitops_cttz64_func(v) +#elif (LZO_BITOPS_USE_GNUC_BITSCAN) && (LZO_SIZEOF_LONG >= 8) && (LZO_WORDSIZE >= 8) + unsigned r; r = (unsigned) __builtin_ctzl(v); return r; +#define lzo_bitops_cttz64(v) ((unsigned) __builtin_ctzl(v)) +#elif (LZO_BITOPS_USE_GNUC_BITSCAN) && (LZO_SIZEOF_LONG_LONG >= 8) && (LZO_WORDSIZE >= 8) + unsigned r; r = (unsigned) __builtin_ctzll(v); return r; +#define lzo_bitops_cttz64(v) ((unsigned) __builtin_ctzll(v)) +#else + LZO_UNUSED(v); return 0; +#endif +} +#endif + +lzo_unused_funcs_impl(void, lzo_bitops_unused_funcs)(void) +{ + LZO_UNUSED_FUNC(lzo_bitops_unused_funcs); + LZO_UNUSED_FUNC(lzo_bitops_ctlz32_func); + LZO_UNUSED_FUNC(lzo_bitops_cttz32_func); +#if defined(lzo_uint64_t) + LZO_UNUSED_FUNC(lzo_bitops_ctlz64_func); + LZO_UNUSED_FUNC(lzo_bitops_cttz64_func); +#endif +} + +#if defined(__lzo_alignof) && !(LZO_CFG_NO_UNALIGNED) +#if !defined(lzo_memops_tcheck__) && 0 +#define lzo_memops_tcheck__(t,a,b) ((void)0, sizeof(t) == (a) && __lzo_alignof(t) == (b)) +#endif +#endif +#ifndef lzo_memops_TU0p +#define lzo_memops_TU0p void __LZO_MMODEL * +#endif +#ifndef lzo_memops_TU1p +#define lzo_memops_TU1p unsigned char __LZO_MMODEL * +#endif +#ifndef lzo_memops_TU2p +#if (LZO_OPT_UNALIGNED16) +typedef lzo_uint16_t __lzo_may_alias lzo_memops_TU2; +#define lzo_memops_TU2p volatile lzo_memops_TU2 * +#elif defined(__lzo_byte_struct) +__lzo_byte_struct(lzo_memops_TU2_struct,2) +typedef struct lzo_memops_TU2_struct lzo_memops_TU2; +#else +struct lzo_memops_TU2_struct { unsigned char a[2]; } __lzo_may_alias; +typedef struct lzo_memops_TU2_struct lzo_memops_TU2; +#endif +#ifndef lzo_memops_TU2p +#define lzo_memops_TU2p lzo_memops_TU2 * +#endif +#endif +#ifndef lzo_memops_TU4p +#if (LZO_OPT_UNALIGNED32) +typedef lzo_uint32_t __lzo_may_alias lzo_memops_TU4; +#define lzo_memops_TU4p volatile lzo_memops_TU4 __LZO_MMODEL * +#elif defined(__lzo_byte_struct) +__lzo_byte_struct(lzo_memops_TU4_struct,4) +typedef struct lzo_memops_TU4_struct lzo_memops_TU4; +#else +struct lzo_memops_TU4_struct { unsigned char a[4]; } __lzo_may_alias; +typedef struct lzo_memops_TU4_struct lzo_memops_TU4; +#endif +#ifndef lzo_memops_TU4p +#define lzo_memops_TU4p lzo_memops_TU4 __LZO_MMODEL * +#endif +#endif +#ifndef lzo_memops_TU8p +#if (LZO_OPT_UNALIGNED64) +typedef lzo_uint64_t __lzo_may_alias lzo_memops_TU8; +#define lzo_memops_TU8p volatile lzo_memops_TU8 __LZO_MMODEL * +#elif defined(__lzo_byte_struct) +__lzo_byte_struct(lzo_memops_TU8_struct,8) +typedef struct lzo_memops_TU8_struct lzo_memops_TU8; +#else +struct lzo_memops_TU8_struct { unsigned char a[8]; } __lzo_may_alias; +typedef struct lzo_memops_TU8_struct lzo_memops_TU8; +#endif +#ifndef lzo_memops_TU8p +#define lzo_memops_TU8p lzo_memops_TU8 __LZO_MMODEL * +#endif +#endif +#ifndef lzo_memops_set_TU1p +#define lzo_memops_set_TU1p volatile lzo_memops_TU1p +#endif +#ifndef lzo_memops_move_TU1p +#define lzo_memops_move_TU1p lzo_memops_TU1p +#endif +#define LZO_MEMOPS_SET1(dd,cc) \ + LZO_BLOCK_BEGIN \ + lzo_memops_set_TU1p d__1 = (lzo_memops_set_TU1p) (lzo_memops_TU0p) (dd); \ + d__1[0] = LZO_BYTE(cc); \ + LZO_BLOCK_END +#define LZO_MEMOPS_SET2(dd,cc) \ + LZO_BLOCK_BEGIN \ + lzo_memops_set_TU1p d__2 = (lzo_memops_set_TU1p) (lzo_memops_TU0p) (dd); \ + d__2[0] = LZO_BYTE(cc); d__2[1] = LZO_BYTE(cc); \ + LZO_BLOCK_END +#define LZO_MEMOPS_SET3(dd,cc) \ + LZO_BLOCK_BEGIN \ + lzo_memops_set_TU1p d__3 = (lzo_memops_set_TU1p) (lzo_memops_TU0p) (dd); \ + d__3[0] = LZO_BYTE(cc); d__3[1] = LZO_BYTE(cc); d__3[2] = LZO_BYTE(cc); \ + LZO_BLOCK_END +#define LZO_MEMOPS_SET4(dd,cc) \ + LZO_BLOCK_BEGIN \ + lzo_memops_set_TU1p d__4 = (lzo_memops_set_TU1p) (lzo_memops_TU0p) (dd); \ + d__4[0] = LZO_BYTE(cc); d__4[1] = LZO_BYTE(cc); d__4[2] = LZO_BYTE(cc); d__4[3] = LZO_BYTE(cc); \ + LZO_BLOCK_END +#define LZO_MEMOPS_MOVE1(dd,ss) \ + LZO_BLOCK_BEGIN \ + lzo_memops_move_TU1p d__1 = (lzo_memops_move_TU1p) (lzo_memops_TU0p) (dd); \ + const lzo_memops_move_TU1p s__1 = (const lzo_memops_move_TU1p) (const lzo_memops_TU0p) (ss); \ + d__1[0] = s__1[0]; \ + LZO_BLOCK_END +#define LZO_MEMOPS_MOVE2(dd,ss) \ + LZO_BLOCK_BEGIN \ + lzo_memops_move_TU1p d__2 = (lzo_memops_move_TU1p) (lzo_memops_TU0p) (dd); \ + const lzo_memops_move_TU1p s__2 = (const lzo_memops_move_TU1p) (const lzo_memops_TU0p) (ss); \ + d__2[0] = s__2[0]; d__2[1] = s__2[1]; \ + LZO_BLOCK_END +#define LZO_MEMOPS_MOVE3(dd,ss) \ + LZO_BLOCK_BEGIN \ + lzo_memops_move_TU1p d__3 = (lzo_memops_move_TU1p) (lzo_memops_TU0p) (dd); \ + const lzo_memops_move_TU1p s__3 = (const lzo_memops_move_TU1p) (const lzo_memops_TU0p) (ss); \ + d__3[0] = s__3[0]; d__3[1] = s__3[1]; d__3[2] = s__3[2]; \ + LZO_BLOCK_END +#define LZO_MEMOPS_MOVE4(dd,ss) \ + LZO_BLOCK_BEGIN \ + lzo_memops_move_TU1p d__4 = (lzo_memops_move_TU1p) (lzo_memops_TU0p) (dd); \ + const lzo_memops_move_TU1p s__4 = (const lzo_memops_move_TU1p) (const lzo_memops_TU0p) (ss); \ + d__4[0] = s__4[0]; d__4[1] = s__4[1]; d__4[2] = s__4[2]; d__4[3] = s__4[3]; \ + LZO_BLOCK_END +#define LZO_MEMOPS_MOVE8(dd,ss) \ + LZO_BLOCK_BEGIN \ + lzo_memops_move_TU1p d__8 = (lzo_memops_move_TU1p) (lzo_memops_TU0p) (dd); \ + const lzo_memops_move_TU1p s__8 = (const lzo_memops_move_TU1p) (const lzo_memops_TU0p) (ss); \ + d__8[0] = s__8[0]; d__8[1] = s__8[1]; d__8[2] = s__8[2]; d__8[3] = s__8[3]; \ + d__8[4] = s__8[4]; d__8[5] = s__8[5]; d__8[6] = s__8[6]; d__8[7] = s__8[7]; \ + LZO_BLOCK_END +LZO_COMPILE_TIME_ASSERT_HEADER(sizeof(*(lzo_memops_TU1p)0)==1) +#define LZO_MEMOPS_COPY1(dd,ss) LZO_MEMOPS_MOVE1(dd,ss) +#if (LZO_OPT_UNALIGNED16) +LZO_COMPILE_TIME_ASSERT_HEADER(sizeof(*(lzo_memops_TU2p)0)==2) +#define LZO_MEMOPS_COPY2(dd,ss) \ + * (lzo_memops_TU2p) (lzo_memops_TU0p) (dd) = * (const lzo_memops_TU2p) (const lzo_memops_TU0p) (ss) +#elif defined(lzo_memops_tcheck__) +#define LZO_MEMOPS_COPY2(dd,ss) \ + LZO_BLOCK_BEGIN if (lzo_memops_tcheck__(lzo_memops_TU2,2,1)) { \ + * (lzo_memops_TU2p) (lzo_memops_TU0p) (dd) = * (const lzo_memops_TU2p) (const lzo_memops_TU0p) (ss); \ + } else { LZO_MEMOPS_MOVE2(dd,ss); } LZO_BLOCK_END +#else +#define LZO_MEMOPS_COPY2(dd,ss) LZO_MEMOPS_MOVE2(dd,ss) +#endif +#if (LZO_OPT_UNALIGNED32) +LZO_COMPILE_TIME_ASSERT_HEADER(sizeof(*(lzo_memops_TU4p)0)==4) +#define LZO_MEMOPS_COPY4(dd,ss) \ + * (lzo_memops_TU4p) (lzo_memops_TU0p) (dd) = * (const lzo_memops_TU4p) (const lzo_memops_TU0p) (ss) +#elif defined(lzo_memops_tcheck__) +#define LZO_MEMOPS_COPY4(dd,ss) \ + LZO_BLOCK_BEGIN if (lzo_memops_tcheck__(lzo_memops_TU4,4,1)) { \ + * (lzo_memops_TU4p) (lzo_memops_TU0p) (dd) = * (const lzo_memops_TU4p) (const lzo_memops_TU0p) (ss); \ + } else { LZO_MEMOPS_MOVE4(dd,ss); } LZO_BLOCK_END +#else +#define LZO_MEMOPS_COPY4(dd,ss) LZO_MEMOPS_MOVE4(dd,ss) +#endif +#if (LZO_WORDSIZE != 8) +#define LZO_MEMOPS_COPY8(dd,ss) \ + LZO_BLOCK_BEGIN LZO_MEMOPS_COPY4(dd,ss); LZO_MEMOPS_COPY4((lzo_memops_TU1p)(lzo_memops_TU0p)(dd)+4,(const lzo_memops_TU1p)(const lzo_memops_TU0p)(ss)+4); LZO_BLOCK_END +#else +#if (LZO_OPT_UNALIGNED64) +LZO_COMPILE_TIME_ASSERT_HEADER(sizeof(*(lzo_memops_TU8p)0)==8) +#define LZO_MEMOPS_COPY8(dd,ss) \ + * (lzo_memops_TU8p) (lzo_memops_TU0p) (dd) = * (const lzo_memops_TU8p) (const lzo_memops_TU0p) (ss) +#elif (LZO_OPT_UNALIGNED32) +#define LZO_MEMOPS_COPY8(dd,ss) \ + LZO_BLOCK_BEGIN LZO_MEMOPS_COPY4(dd,ss); LZO_MEMOPS_COPY4((lzo_memops_TU1p)(lzo_memops_TU0p)(dd)+4,(const lzo_memops_TU1p)(const lzo_memops_TU0p)(ss)+4); LZO_BLOCK_END +#elif defined(lzo_memops_tcheck__) +#define LZO_MEMOPS_COPY8(dd,ss) \ + LZO_BLOCK_BEGIN if (lzo_memops_tcheck__(lzo_memops_TU8,8,1)) { \ + * (lzo_memops_TU8p) (lzo_memops_TU0p) (dd) = * (const lzo_memops_TU8p) (const lzo_memops_TU0p) (ss); \ + } else { LZO_MEMOPS_MOVE8(dd,ss); } LZO_BLOCK_END +#else +#define LZO_MEMOPS_COPY8(dd,ss) LZO_MEMOPS_MOVE8(dd,ss) +#endif +#endif +#define LZO_MEMOPS_COPYN(dd,ss,nn) \ + LZO_BLOCK_BEGIN \ + lzo_memops_TU1p d__n = (lzo_memops_TU1p) (lzo_memops_TU0p) (dd); \ + const lzo_memops_TU1p s__n = (const lzo_memops_TU1p) (const lzo_memops_TU0p) (ss); \ + lzo_uint n__n = (nn); \ + while ((void)0, n__n >= 8) { LZO_MEMOPS_COPY8(d__n, s__n); d__n += 8; s__n += 8; n__n -= 8; } \ + if ((void)0, n__n >= 4) { LZO_MEMOPS_COPY4(d__n, s__n); d__n += 4; s__n += 4; n__n -= 4; } \ + if ((void)0, n__n > 0) do { *d__n++ = *s__n++; } while (--n__n > 0); \ + LZO_BLOCK_END + +__lzo_static_forceinline lzo_uint16_t lzo_memops_get_le16(const lzo_voidp ss) +{ + lzo_uint16_t v; +#if (LZO_ABI_LITTLE_ENDIAN) + LZO_MEMOPS_COPY2(&v, ss); +#elif (LZO_OPT_UNALIGNED16 && LZO_ARCH_POWERPC && LZO_ABI_BIG_ENDIAN) && (LZO_ASM_SYNTAX_GNUC) + const lzo_memops_TU2p s = (const lzo_memops_TU2p) ss; + unsigned long vv; + __asm__("lhbrx %0,0,%1" : "=r" (vv) : "r" (s), "m" (*s)); + v = (lzo_uint16_t) vv; +#else + const lzo_memops_TU1p s = (const lzo_memops_TU1p) ss; + v = (lzo_uint16_t) (((lzo_uint16_t)s[0]) | ((lzo_uint16_t)s[1] << 8)); +#endif + return v; +} +#if (LZO_OPT_UNALIGNED16) && (LZO_ABI_LITTLE_ENDIAN) +#define LZO_MEMOPS_GET_LE16(ss) (* (const lzo_memops_TU2p) (const lzo_memops_TU0p) (ss)) +#else +#define LZO_MEMOPS_GET_LE16(ss) lzo_memops_get_le16(ss) +#endif + +__lzo_static_forceinline lzo_uint32_t lzo_memops_get_le32(const lzo_voidp ss) +{ + lzo_uint32_t v; +#if (LZO_ABI_LITTLE_ENDIAN) + LZO_MEMOPS_COPY4(&v, ss); +#elif (LZO_OPT_UNALIGNED32 && LZO_ARCH_POWERPC && LZO_ABI_BIG_ENDIAN) && (LZO_ASM_SYNTAX_GNUC) + const lzo_memops_TU4p s = (const lzo_memops_TU4p) ss; + unsigned long vv; + __asm__("lwbrx %0,0,%1" : "=r" (vv) : "r" (s), "m" (*s)); + v = (lzo_uint32_t) vv; +#else + const lzo_memops_TU1p s = (const lzo_memops_TU1p) ss; + v = (lzo_uint32_t) (((lzo_uint32_t)s[0]) | ((lzo_uint32_t)s[1] << 8) | ((lzo_uint32_t)s[2] << 16) | ((lzo_uint32_t)s[3] << 24)); +#endif + return v; +} +#if (LZO_OPT_UNALIGNED32) && (LZO_ABI_LITTLE_ENDIAN) +#define LZO_MEMOPS_GET_LE32(ss) (* (const lzo_memops_TU4p) (const lzo_memops_TU0p) (ss)) +#else +#define LZO_MEMOPS_GET_LE32(ss) lzo_memops_get_le32(ss) +#endif + +#if (LZO_OPT_UNALIGNED64) && (LZO_ABI_LITTLE_ENDIAN) +#define LZO_MEMOPS_GET_LE64(ss) (* (const lzo_memops_TU8p) (const lzo_memops_TU0p) (ss)) +#endif + +__lzo_static_forceinline lzo_uint16_t lzo_memops_get_ne16(const lzo_voidp ss) +{ + lzo_uint16_t v; + LZO_MEMOPS_COPY2(&v, ss); + return v; +} +#if (LZO_OPT_UNALIGNED16) +LZO_COMPILE_TIME_ASSERT_HEADER(sizeof(*(lzo_memops_TU2p)0)==2) +#define LZO_MEMOPS_GET_NE16(ss) (* (const lzo_memops_TU2p) (const lzo_memops_TU0p) (ss)) +#else +#define LZO_MEMOPS_GET_NE16(ss) lzo_memops_get_ne16(ss) +#endif + +__lzo_static_forceinline lzo_uint32_t lzo_memops_get_ne32(const lzo_voidp ss) +{ + lzo_uint32_t v; + LZO_MEMOPS_COPY4(&v, ss); + return v; +} +#if (LZO_OPT_UNALIGNED32) +LZO_COMPILE_TIME_ASSERT_HEADER(sizeof(*(lzo_memops_TU4p)0)==4) +#define LZO_MEMOPS_GET_NE32(ss) (* (const lzo_memops_TU4p) (const lzo_memops_TU0p) (ss)) +#else +#define LZO_MEMOPS_GET_NE32(ss) lzo_memops_get_ne32(ss) +#endif + +#if (LZO_OPT_UNALIGNED64) +LZO_COMPILE_TIME_ASSERT_HEADER(sizeof(*(lzo_memops_TU8p)0)==8) +#define LZO_MEMOPS_GET_NE64(ss) (* (const lzo_memops_TU8p) (const lzo_memops_TU0p) (ss)) +#endif + +__lzo_static_forceinline void lzo_memops_put_le16(lzo_voidp dd, lzo_uint16_t vv) +{ +#if (LZO_ABI_LITTLE_ENDIAN) + LZO_MEMOPS_COPY2(dd, &vv); +#elif (LZO_OPT_UNALIGNED16 && LZO_ARCH_POWERPC && LZO_ABI_BIG_ENDIAN) && (LZO_ASM_SYNTAX_GNUC) + lzo_memops_TU2p d = (lzo_memops_TU2p) dd; + unsigned long v = vv; + __asm__("sthbrx %2,0,%1" : "=m" (*d) : "r" (d), "r" (v)); +#else + lzo_memops_TU1p d = (lzo_memops_TU1p) dd; + d[0] = LZO_BYTE((vv ) & 0xff); + d[1] = LZO_BYTE((vv >> 8) & 0xff); +#endif +} +#if (LZO_OPT_UNALIGNED16) && (LZO_ABI_LITTLE_ENDIAN) +#define LZO_MEMOPS_PUT_LE16(dd,vv) (* (lzo_memops_TU2p) (lzo_memops_TU0p) (dd) = (vv)) +#else +#define LZO_MEMOPS_PUT_LE16(dd,vv) lzo_memops_put_le16(dd,vv) +#endif + +__lzo_static_forceinline void lzo_memops_put_le32(lzo_voidp dd, lzo_uint32_t vv) +{ +#if (LZO_ABI_LITTLE_ENDIAN) + LZO_MEMOPS_COPY4(dd, &vv); +#elif (LZO_OPT_UNALIGNED32 && LZO_ARCH_POWERPC && LZO_ABI_BIG_ENDIAN) && (LZO_ASM_SYNTAX_GNUC) + lzo_memops_TU4p d = (lzo_memops_TU4p) dd; + unsigned long v = vv; + __asm__("stwbrx %2,0,%1" : "=m" (*d) : "r" (d), "r" (v)); +#else + lzo_memops_TU1p d = (lzo_memops_TU1p) dd; + d[0] = LZO_BYTE((vv ) & 0xff); + d[1] = LZO_BYTE((vv >> 8) & 0xff); + d[2] = LZO_BYTE((vv >> 16) & 0xff); + d[3] = LZO_BYTE((vv >> 24) & 0xff); +#endif +} +#if (LZO_OPT_UNALIGNED32) && (LZO_ABI_LITTLE_ENDIAN) +#define LZO_MEMOPS_PUT_LE32(dd,vv) (* (lzo_memops_TU4p) (lzo_memops_TU0p) (dd) = (vv)) +#else +#define LZO_MEMOPS_PUT_LE32(dd,vv) lzo_memops_put_le32(dd,vv) +#endif + +__lzo_static_forceinline void lzo_memops_put_ne16(lzo_voidp dd, lzo_uint16_t vv) +{ + LZO_MEMOPS_COPY2(dd, &vv); +} +#if (LZO_OPT_UNALIGNED16) +#define LZO_MEMOPS_PUT_NE16(dd,vv) (* (lzo_memops_TU2p) (lzo_memops_TU0p) (dd) = (vv)) +#else +#define LZO_MEMOPS_PUT_NE16(dd,vv) lzo_memops_put_ne16(dd,vv) +#endif + +__lzo_static_forceinline void lzo_memops_put_ne32(lzo_voidp dd, lzo_uint32_t vv) +{ + LZO_MEMOPS_COPY4(dd, &vv); +} +#if (LZO_OPT_UNALIGNED32) +#define LZO_MEMOPS_PUT_NE32(dd,vv) (* (lzo_memops_TU4p) (lzo_memops_TU0p) (dd) = (vv)) +#else +#define LZO_MEMOPS_PUT_NE32(dd,vv) lzo_memops_put_ne32(dd,vv) +#endif + +lzo_unused_funcs_impl(void, lzo_memops_unused_funcs)(void) +{ + LZO_UNUSED_FUNC(lzo_memops_unused_funcs); + LZO_UNUSED_FUNC(lzo_memops_get_le16); + LZO_UNUSED_FUNC(lzo_memops_get_le32); + LZO_UNUSED_FUNC(lzo_memops_get_ne16); + LZO_UNUSED_FUNC(lzo_memops_get_ne32); + LZO_UNUSED_FUNC(lzo_memops_put_le16); + LZO_UNUSED_FUNC(lzo_memops_put_le32); + LZO_UNUSED_FUNC(lzo_memops_put_ne16); + LZO_UNUSED_FUNC(lzo_memops_put_ne32); +} + +#endif + +#ifndef UA_SET1 +#define UA_SET1 LZO_MEMOPS_SET1 +#endif +#ifndef UA_SET2 +#define UA_SET2 LZO_MEMOPS_SET2 +#endif +#ifndef UA_SET3 +#define UA_SET3 LZO_MEMOPS_SET3 +#endif +#ifndef UA_SET4 +#define UA_SET4 LZO_MEMOPS_SET4 +#endif +#ifndef UA_MOVE1 +#define UA_MOVE1 LZO_MEMOPS_MOVE1 +#endif +#ifndef UA_MOVE2 +#define UA_MOVE2 LZO_MEMOPS_MOVE2 +#endif +#ifndef UA_MOVE3 +#define UA_MOVE3 LZO_MEMOPS_MOVE3 +#endif +#ifndef UA_MOVE4 +#define UA_MOVE4 LZO_MEMOPS_MOVE4 +#endif +#ifndef UA_MOVE8 +#define UA_MOVE8 LZO_MEMOPS_MOVE8 +#endif +#ifndef UA_COPY1 +#define UA_COPY1 LZO_MEMOPS_COPY1 +#endif +#ifndef UA_COPY2 +#define UA_COPY2 LZO_MEMOPS_COPY2 +#endif +#ifndef UA_COPY3 +#define UA_COPY3 LZO_MEMOPS_COPY3 +#endif +#ifndef UA_COPY4 +#define UA_COPY4 LZO_MEMOPS_COPY4 +#endif +#ifndef UA_COPY8 +#define UA_COPY8 LZO_MEMOPS_COPY8 +#endif +#ifndef UA_COPYN +#define UA_COPYN LZO_MEMOPS_COPYN +#endif +#ifndef UA_COPYN_X +#define UA_COPYN_X LZO_MEMOPS_COPYN +#endif +#ifndef UA_GET_LE16 +#define UA_GET_LE16 LZO_MEMOPS_GET_LE16 +#endif +#ifndef UA_GET_LE32 +#define UA_GET_LE32 LZO_MEMOPS_GET_LE32 +#endif +#ifdef LZO_MEMOPS_GET_LE64 +#ifndef UA_GET_LE64 +#define UA_GET_LE64 LZO_MEMOPS_GET_LE64 +#endif +#endif +#ifndef UA_GET_NE16 +#define UA_GET_NE16 LZO_MEMOPS_GET_NE16 +#endif +#ifndef UA_GET_NE32 +#define UA_GET_NE32 LZO_MEMOPS_GET_NE32 +#endif +#ifdef LZO_MEMOPS_GET_NE64 +#ifndef UA_GET_NE64 +#define UA_GET_NE64 LZO_MEMOPS_GET_NE64 +#endif +#endif +#ifndef UA_PUT_LE16 +#define UA_PUT_LE16 LZO_MEMOPS_PUT_LE16 +#endif +#ifndef UA_PUT_LE32 +#define UA_PUT_LE32 LZO_MEMOPS_PUT_LE32 +#endif +#ifndef UA_PUT_NE16 +#define UA_PUT_NE16 LZO_MEMOPS_PUT_NE16 +#endif +#ifndef UA_PUT_NE32 +#define UA_PUT_NE32 LZO_MEMOPS_PUT_NE32 +#endif + +#define MEMCPY8_DS(dest,src,len) \ + lzo_memcpy(dest,src,len); dest += len; src += len + +#define BZERO8_PTR(s,l,n) \ + lzo_memset((lzo_voidp)(s),0,(lzo_uint)(l)*(n)) + +#define MEMCPY_DS(dest,src,len) \ + do *dest++ = *src++; while (--len > 0) + +LZO_EXTERN(const lzo_bytep) lzo_copyright(void); + +#ifndef __LZO_PTR_H +#define __LZO_PTR_H 1 + +#ifdef __cplusplus +extern "C" { +#endif + +#if (LZO_ARCH_I086) +#error "LZO_ARCH_I086 is unsupported" +#elif (LZO_MM_PVP) +#error "LZO_MM_PVP is unsupported" +#else +#define PTR(a) ((lzo_uintptr_t) (a)) +#define PTR_LINEAR(a) PTR(a) +#define PTR_ALIGNED_4(a) ((PTR_LINEAR(a) & 3) == 0) +#define PTR_ALIGNED_8(a) ((PTR_LINEAR(a) & 7) == 0) +#define PTR_ALIGNED2_4(a,b) (((PTR_LINEAR(a) | PTR_LINEAR(b)) & 3) == 0) +#define PTR_ALIGNED2_8(a,b) (((PTR_LINEAR(a) | PTR_LINEAR(b)) & 7) == 0) +#endif + +#define PTR_LT(a,b) (PTR(a) < PTR(b)) +#define PTR_GE(a,b) (PTR(a) >= PTR(b)) +#define PTR_DIFF(a,b) (PTR(a) - PTR(b)) +#define pd(a,b) ((lzo_uint) ((a)-(b))) + +LZO_EXTERN(lzo_uintptr_t) +__lzo_ptr_linear(const lzo_voidp ptr); + +typedef union +{ + char a_char; + unsigned char a_uchar; + short a_short; + unsigned short a_ushort; + int a_int; + unsigned int a_uint; + long a_long; + unsigned long a_ulong; + lzo_int a_lzo_int; + lzo_uint a_lzo_uint; + lzo_xint a_lzo_xint; + lzo_int16_t a_lzo_int16_t; + lzo_uint16_t a_lzo_uint16_t; + lzo_int32_t a_lzo_int32_t; + lzo_uint32_t a_lzo_uint32_t; +#if defined(lzo_uint64_t) + lzo_int64_t a_lzo_int64_t; + lzo_uint64_t a_lzo_uint64_t; +#endif + size_t a_size_t; + ptrdiff_t a_ptrdiff_t; + lzo_uintptr_t a_lzo_uintptr_t; + void * a_void_p; + char * a_char_p; + unsigned char * a_uchar_p; + const void * a_c_void_p; + const char * a_c_char_p; + const unsigned char * a_c_uchar_p; + lzo_voidp a_lzo_voidp; + lzo_bytep a_lzo_bytep; + const lzo_voidp a_c_lzo_voidp; + const lzo_bytep a_c_lzo_bytep; +} +lzo_full_align_t; + +#ifdef __cplusplus +} +#endif + +#endif + +#ifndef LZO_DETERMINISTIC +#define LZO_DETERMINISTIC 1 +#endif + +#ifndef LZO_DICT_USE_PTR +#define LZO_DICT_USE_PTR 1 +#endif + +#if (LZO_DICT_USE_PTR) +# define lzo_dict_t const lzo_bytep +# define lzo_dict_p lzo_dict_t * +#else +# define lzo_dict_t lzo_uint +# define lzo_dict_p lzo_dict_t * +#endif + +#endif + +#if !defined(MINILZO_CFG_SKIP_LZO_PTR) + +LZO_PUBLIC(lzo_uintptr_t) +__lzo_ptr_linear(const lzo_voidp ptr) +{ + lzo_uintptr_t p; + +#if (LZO_ARCH_I086) +#error "LZO_ARCH_I086 is unsupported" +#elif (LZO_MM_PVP) +#error "LZO_MM_PVP is unsupported" +#else + p = (lzo_uintptr_t) PTR_LINEAR(ptr); +#endif + + return p; +} + +LZO_PUBLIC(unsigned) +__lzo_align_gap(const lzo_voidp ptr, lzo_uint size) +{ +#if (__LZO_UINTPTR_T_IS_POINTER) +#error "__LZO_UINTPTR_T_IS_POINTER is unsupported" +#else + lzo_uintptr_t p, n; + if (size < 2) return 0; + p = __lzo_ptr_linear(ptr); +#if 0 + n = (((p + size - 1) / size) * size) - p; +#else + if ((size & (size - 1)) != 0) + return 0; + n = size; n = ((p + n - 1) & ~(n - 1)) - p; +#endif +#endif + assert((long)n >= 0); + assert(n <= size); + return (unsigned)n; +} + +#endif +#if !defined(MINILZO_CFG_SKIP_LZO_UTIL) + +/* If you use the LZO library in a product, I would appreciate that you + * keep this copyright string in the executable of your product. + */ + +static const char lzo_copyright_[] = +#if !defined(__LZO_IN_MINLZO) + LZO_VERSION_STRING; +#else + "\r\n\n" + "LZO data compression library.\n" + "$Copyright: LZO Copyright (C) 1996-2017 Markus Franz Xaver Johannes Oberhumer\n" + "\n" + "http://www.oberhumer.com $\n\n" + "$Id: LZO version: v" LZO_VERSION_STRING ", " LZO_VERSION_DATE " $\n" + "$Info: " LZO_INFO_STRING " $\n"; +#endif +static const char lzo_version_string_[] = LZO_VERSION_STRING; +static const char lzo_version_date_[] = LZO_VERSION_DATE; + +LZO_PUBLIC(const lzo_bytep) +lzo_copyright(void) +{ + return (const lzo_bytep) lzo_copyright_; +} + +LZO_PUBLIC(unsigned) +lzo_version(void) +{ + return LZO_VERSION; +} + +LZO_PUBLIC(const char *) +lzo_version_string(void) +{ + return lzo_version_string_; +} + +LZO_PUBLIC(const char *) +lzo_version_date(void) +{ + return lzo_version_date_; +} + +LZO_PUBLIC(const lzo_charp) +_lzo_version_string(void) +{ + return lzo_version_string_; +} + +LZO_PUBLIC(const lzo_charp) +_lzo_version_date(void) +{ + return lzo_version_date_; +} + +#define LZO_BASE 65521u +#define LZO_NMAX 5552 + +#define LZO_DO1(buf,i) s1 += buf[i]; s2 += s1 +#define LZO_DO2(buf,i) LZO_DO1(buf,i); LZO_DO1(buf,i+1) +#define LZO_DO4(buf,i) LZO_DO2(buf,i); LZO_DO2(buf,i+2) +#define LZO_DO8(buf,i) LZO_DO4(buf,i); LZO_DO4(buf,i+4) +#define LZO_DO16(buf,i) LZO_DO8(buf,i); LZO_DO8(buf,i+8) + +LZO_PUBLIC(lzo_uint32_t) +lzo_adler32(lzo_uint32_t adler, const lzo_bytep buf, lzo_uint len) +{ + lzo_uint32_t s1 = adler & 0xffff; + lzo_uint32_t s2 = (adler >> 16) & 0xffff; + unsigned k; + + if (buf == NULL) + return 1; + + while (len > 0) + { + k = len < LZO_NMAX ? (unsigned) len : LZO_NMAX; + len -= k; + if (k >= 16) do + { + LZO_DO16(buf,0); + buf += 16; + k -= 16; + } while (k >= 16); + if (k != 0) do + { + s1 += *buf++; + s2 += s1; + } while (--k > 0); + s1 %= LZO_BASE; + s2 %= LZO_BASE; + } + return (s2 << 16) | s1; +} + +#undef LZO_DO1 +#undef LZO_DO2 +#undef LZO_DO4 +#undef LZO_DO8 +#undef LZO_DO16 + +#endif +#if !defined(MINILZO_CFG_SKIP_LZO_STRING) +#undef lzo_memcmp +#undef lzo_memcpy +#undef lzo_memmove +#undef lzo_memset +#if !defined(__LZO_MMODEL_HUGE) +# undef LZO_HAVE_MM_HUGE_PTR +#endif +#define lzo_hsize_t lzo_uint +#define lzo_hvoid_p lzo_voidp +#define lzo_hbyte_p lzo_bytep +#define LZOLIB_PUBLIC(r,f) LZO_PUBLIC(r) f +#define lzo_hmemcmp lzo_memcmp +#define lzo_hmemcpy lzo_memcpy +#define lzo_hmemmove lzo_memmove +#define lzo_hmemset lzo_memset +#define __LZOLIB_HMEMCPY_CH_INCLUDED 1 +#if !defined(LZOLIB_PUBLIC) +# define LZOLIB_PUBLIC(r,f) r __LZOLIB_FUNCNAME(f) +#endif +LZOLIB_PUBLIC(int, lzo_hmemcmp) (const lzo_hvoid_p s1, const lzo_hvoid_p s2, lzo_hsize_t len) +{ +#if (LZO_HAVE_MM_HUGE_PTR) || !(HAVE_MEMCMP) + const lzo_hbyte_p p1 = LZO_STATIC_CAST(const lzo_hbyte_p, s1); + const lzo_hbyte_p p2 = LZO_STATIC_CAST(const lzo_hbyte_p, s2); + if __lzo_likely(len > 0) do + { + int d = *p1 - *p2; + if (d != 0) + return d; + p1++; p2++; + } while __lzo_likely(--len > 0); + return 0; +#else + return memcmp(s1, s2, len); +#endif +} +LZOLIB_PUBLIC(lzo_hvoid_p, lzo_hmemcpy) (lzo_hvoid_p dest, const lzo_hvoid_p src, lzo_hsize_t len) +{ +#if (LZO_HAVE_MM_HUGE_PTR) || !(HAVE_MEMCPY) + lzo_hbyte_p p1 = LZO_STATIC_CAST(lzo_hbyte_p, dest); + const lzo_hbyte_p p2 = LZO_STATIC_CAST(const lzo_hbyte_p, src); + if (!(len > 0) || p1 == p2) + return dest; + do + *p1++ = *p2++; + while __lzo_likely(--len > 0); + return dest; +#else + return memcpy(dest, src, len); +#endif +} +LZOLIB_PUBLIC(lzo_hvoid_p, lzo_hmemmove) (lzo_hvoid_p dest, const lzo_hvoid_p src, lzo_hsize_t len) +{ +#if (LZO_HAVE_MM_HUGE_PTR) || !(HAVE_MEMMOVE) + lzo_hbyte_p p1 = LZO_STATIC_CAST(lzo_hbyte_p, dest); + const lzo_hbyte_p p2 = LZO_STATIC_CAST(const lzo_hbyte_p, src); + if (!(len > 0) || p1 == p2) + return dest; + if (p1 < p2) + { + do + *p1++ = *p2++; + while __lzo_likely(--len > 0); + } + else + { + p1 += len; + p2 += len; + do + *--p1 = *--p2; + while __lzo_likely(--len > 0); + } + return dest; +#else + return memmove(dest, src, len); +#endif +} +LZOLIB_PUBLIC(lzo_hvoid_p, lzo_hmemset) (lzo_hvoid_p s, int cc, lzo_hsize_t len) +{ +#if (LZO_HAVE_MM_HUGE_PTR) || !(HAVE_MEMSET) + lzo_hbyte_p p = LZO_STATIC_CAST(lzo_hbyte_p, s); + unsigned char c = LZO_ITRUNC(unsigned char, cc); + if __lzo_likely(len > 0) do + *p++ = c; + while __lzo_likely(--len > 0); + return s; +#else + return memset(s, cc, len); +#endif +} +#undef LZOLIB_PUBLIC +#endif +#if !defined(MINILZO_CFG_SKIP_LZO_INIT) + +#if !defined(__LZO_IN_MINILZO) + +#define LZO_WANT_ACC_CHK_CH 1 +#undef LZOCHK_ASSERT + + LZOCHK_ASSERT((LZO_UINT32_C(1) << (int)(8*sizeof(LZO_UINT32_C(1))-1)) > 0) + LZOCHK_ASSERT_IS_SIGNED_T(lzo_int) + LZOCHK_ASSERT_IS_UNSIGNED_T(lzo_uint) +#if !(__LZO_UINTPTR_T_IS_POINTER) + LZOCHK_ASSERT_IS_UNSIGNED_T(lzo_uintptr_t) +#endif + LZOCHK_ASSERT(sizeof(lzo_uintptr_t) >= sizeof(lzo_voidp)) + LZOCHK_ASSERT_IS_UNSIGNED_T(lzo_xint) + +#endif +#undef LZOCHK_ASSERT + +union lzo_config_check_union { + lzo_uint a[2]; + unsigned char b[2*LZO_MAX(8,sizeof(lzo_uint))]; +#if defined(lzo_uint64_t) + lzo_uint64_t c[2]; +#endif +}; + +#if 0 +#define u2p(ptr,off) ((lzo_voidp) (((lzo_bytep)(lzo_voidp)(ptr)) + (off))) +#else +static __lzo_noinline lzo_voidp u2p(lzo_voidp ptr, lzo_uint off) +{ + return (lzo_voidp) ((lzo_bytep) ptr + off); +} +#endif + +LZO_PUBLIC(int) +_lzo_config_check(void) +{ +#if (LZO_CC_CLANG && (LZO_CC_CLANG >= 0x030100ul && LZO_CC_CLANG < 0x030300ul)) +# if 0 + volatile +# endif +#endif + union lzo_config_check_union u; + lzo_voidp p; + unsigned r = 1; + + u.a[0] = u.a[1] = 0; + p = u2p(&u, 0); + r &= ((* (lzo_bytep) p) == 0); +#if !(LZO_CFG_NO_CONFIG_CHECK) +#if (LZO_ABI_BIG_ENDIAN) + u.a[0] = u.a[1] = 0; u.b[sizeof(lzo_uint) - 1] = 128; + p = u2p(&u, 0); + r &= ((* (lzo_uintp) p) == 128); +#endif +#if (LZO_ABI_LITTLE_ENDIAN) + u.a[0] = u.a[1] = 0; u.b[0] = 128; + p = u2p(&u, 0); + r &= ((* (lzo_uintp) p) == 128); +#endif + u.a[0] = u.a[1] = 0; + u.b[0] = 1; u.b[3] = 2; + p = u2p(&u, 1); + r &= UA_GET_NE16(p) == 0; + r &= UA_GET_LE16(p) == 0; + u.b[1] = 128; + r &= UA_GET_LE16(p) == 128; + u.b[2] = 129; + r &= UA_GET_LE16(p) == LZO_UINT16_C(0x8180); +#if (LZO_ABI_BIG_ENDIAN) + r &= UA_GET_NE16(p) == LZO_UINT16_C(0x8081); +#endif +#if (LZO_ABI_LITTLE_ENDIAN) + r &= UA_GET_NE16(p) == LZO_UINT16_C(0x8180); +#endif + u.a[0] = u.a[1] = 0; + u.b[0] = 3; u.b[5] = 4; + p = u2p(&u, 1); + r &= UA_GET_NE32(p) == 0; + r &= UA_GET_LE32(p) == 0; + u.b[1] = 128; + r &= UA_GET_LE32(p) == 128; + u.b[2] = 129; u.b[3] = 130; u.b[4] = 131; + r &= UA_GET_LE32(p) == LZO_UINT32_C(0x83828180); +#if (LZO_ABI_BIG_ENDIAN) + r &= UA_GET_NE32(p) == LZO_UINT32_C(0x80818283); +#endif +#if (LZO_ABI_LITTLE_ENDIAN) + r &= UA_GET_NE32(p) == LZO_UINT32_C(0x83828180); +#endif +#if defined(UA_GET_NE64) + u.c[0] = u.c[1] = 0; + u.b[0] = 5; u.b[9] = 6; + p = u2p(&u, 1); + u.c[0] = u.c[1] = 0; + r &= UA_GET_NE64(p) == 0; +#if defined(UA_GET_LE64) + r &= UA_GET_LE64(p) == 0; + u.b[1] = 128; + r &= UA_GET_LE64(p) == 128; +#endif +#endif +#if defined(lzo_bitops_ctlz32) + { unsigned i = 0; lzo_uint32_t v; + for (v = 1; v != 0 && r == 1; v <<= 1, i++) { + r &= lzo_bitops_ctlz32(v) == 31 - i; + r &= lzo_bitops_ctlz32_func(v) == 31 - i; + }} +#endif +#if defined(lzo_bitops_ctlz64) + { unsigned i = 0; lzo_uint64_t v; + for (v = 1; v != 0 && r == 1; v <<= 1, i++) { + r &= lzo_bitops_ctlz64(v) == 63 - i; + r &= lzo_bitops_ctlz64_func(v) == 63 - i; + }} +#endif +#if defined(lzo_bitops_cttz32) + { unsigned i = 0; lzo_uint32_t v; + for (v = 1; v != 0 && r == 1; v <<= 1, i++) { + r &= lzo_bitops_cttz32(v) == i; + r &= lzo_bitops_cttz32_func(v) == i; + }} +#endif +#if defined(lzo_bitops_cttz64) + { unsigned i = 0; lzo_uint64_t v; + for (v = 1; v != 0 && r == 1; v <<= 1, i++) { + r &= lzo_bitops_cttz64(v) == i; + r &= lzo_bitops_cttz64_func(v) == i; + }} +#endif +#endif + LZO_UNUSED_FUNC(lzo_bitops_unused_funcs); + + return r == 1 ? LZO_E_OK : LZO_E_ERROR; +} + +LZO_PUBLIC(int) +__lzo_init_v2(unsigned v, int s1, int s2, int s3, int s4, int s5, + int s6, int s7, int s8, int s9) +{ + int r; + +#if defined(__LZO_IN_MINILZO) +#elif (LZO_CC_MSC && ((_MSC_VER) < 700)) +#else +#define LZO_WANT_ACC_CHK_CH 1 +#undef LZOCHK_ASSERT +#define LZOCHK_ASSERT(expr) LZO_COMPILE_TIME_ASSERT(expr) +#endif +#undef LZOCHK_ASSERT + + if (v == 0) + return LZO_E_ERROR; + + r = (s1 == -1 || s1 == (int) sizeof(short)) && + (s2 == -1 || s2 == (int) sizeof(int)) && + (s3 == -1 || s3 == (int) sizeof(long)) && + (s4 == -1 || s4 == (int) sizeof(lzo_uint32_t)) && + (s5 == -1 || s5 == (int) sizeof(lzo_uint)) && + (s6 == -1 || s6 == (int) lzo_sizeof_dict_t) && + (s7 == -1 || s7 == (int) sizeof(char *)) && + (s8 == -1 || s8 == (int) sizeof(lzo_voidp)) && + (s9 == -1 || s9 == (int) sizeof(lzo_callback_t)); + if (!r) + return LZO_E_ERROR; + + r = _lzo_config_check(); + if (r != LZO_E_OK) + return r; + + return r; +} + +#if !defined(__LZO_IN_MINILZO) + +#if (LZO_OS_WIN16 && LZO_CC_WATCOMC) && defined(__SW_BD) + +#if 0 +BOOL FAR PASCAL LibMain ( HANDLE hInstance, WORD wDataSegment, + WORD wHeapSize, LPSTR lpszCmdLine ) +#else +int __far __pascal LibMain ( int a, short b, short c, long d ) +#endif +{ + LZO_UNUSED(a); LZO_UNUSED(b); LZO_UNUSED(c); LZO_UNUSED(d); + return 1; +} + +#endif + +#endif + +#endif + +#define LZO1X 1 +#define LZO_EOF_CODE 1 +#define M2_MAX_OFFSET 0x0800 + +#if !defined(MINILZO_CFG_SKIP_LZO1X_1_COMPRESS) + +#if 1 && defined(UA_GET_LE32) +#undef LZO_DICT_USE_PTR +#define LZO_DICT_USE_PTR 0 +#undef lzo_dict_t +#define lzo_dict_t lzo_uint16_t +#endif + +#define LZO_NEED_DICT_H 1 +#ifndef D_BITS +#define D_BITS 14 +#endif +#define D_INDEX1(d,p) d = DM(DMUL(0x21,DX3(p,5,5,6)) >> 5) +#define D_INDEX2(d,p) d = (d & (D_MASK & 0x7ff)) ^ (D_HIGH | 0x1f) +#if 1 +#define DINDEX(dv,p) DM(((DMUL(0x1824429d,dv)) >> (32-D_BITS))) +#else +#define DINDEX(dv,p) DM((dv) + ((dv) >> (32-D_BITS))) +#endif + +#ifndef __LZO_CONFIG1X_H +#define __LZO_CONFIG1X_H 1 + +#if !defined(LZO1X) && !defined(LZO1Y) && !defined(LZO1Z) +# define LZO1X 1 +#endif + +#if !defined(__LZO_IN_MINILZO) +#include +#endif + +#ifndef LZO_EOF_CODE +#define LZO_EOF_CODE 1 +#endif +#undef LZO_DETERMINISTIC + +#define M1_MAX_OFFSET 0x0400 +#ifndef M2_MAX_OFFSET +#define M2_MAX_OFFSET 0x0800 +#endif +#define M3_MAX_OFFSET 0x4000 +#define M4_MAX_OFFSET 0xbfff + +#define MX_MAX_OFFSET (M1_MAX_OFFSET + M2_MAX_OFFSET) + +#define M1_MIN_LEN 2 +#define M1_MAX_LEN 2 +#define M2_MIN_LEN 3 +#ifndef M2_MAX_LEN +#define M2_MAX_LEN 8 +#endif +#define M3_MIN_LEN 3 +#define M3_MAX_LEN 33 +#define M4_MIN_LEN 3 +#define M4_MAX_LEN 9 + +#define M1_MARKER 0 +#define M2_MARKER 64 +#define M3_MARKER 32 +#define M4_MARKER 16 + +#ifndef MIN_LOOKAHEAD +#define MIN_LOOKAHEAD (M2_MAX_LEN + 1) +#endif + +#if defined(LZO_NEED_DICT_H) + +#ifndef LZO_HASH +#define LZO_HASH LZO_HASH_LZO_INCREMENTAL_B +#endif +#define DL_MIN_LEN M2_MIN_LEN + +#ifndef __LZO_DICT_H +#define __LZO_DICT_H 1 + +#ifdef __cplusplus +extern "C" { +#endif + +#if !defined(D_BITS) && defined(DBITS) +# define D_BITS DBITS +#endif +#if !defined(D_BITS) +# error "D_BITS is not defined" +#endif +#if (D_BITS < 16) +# define D_SIZE LZO_SIZE(D_BITS) +# define D_MASK LZO_MASK(D_BITS) +#else +# define D_SIZE LZO_USIZE(D_BITS) +# define D_MASK LZO_UMASK(D_BITS) +#endif +#define D_HIGH ((D_MASK >> 1) + 1) + +#if !defined(DD_BITS) +# define DD_BITS 0 +#endif +#define DD_SIZE LZO_SIZE(DD_BITS) +#define DD_MASK LZO_MASK(DD_BITS) + +#if !defined(DL_BITS) +# define DL_BITS (D_BITS - DD_BITS) +#endif +#if (DL_BITS < 16) +# define DL_SIZE LZO_SIZE(DL_BITS) +# define DL_MASK LZO_MASK(DL_BITS) +#else +# define DL_SIZE LZO_USIZE(DL_BITS) +# define DL_MASK LZO_UMASK(DL_BITS) +#endif + +#if (D_BITS != DL_BITS + DD_BITS) +# error "D_BITS does not match" +#endif +#if (D_BITS < 6 || D_BITS > 18) +# error "invalid D_BITS" +#endif +#if (DL_BITS < 6 || DL_BITS > 20) +# error "invalid DL_BITS" +#endif +#if (DD_BITS < 0 || DD_BITS > 6) +# error "invalid DD_BITS" +#endif + +#if !defined(DL_MIN_LEN) +# define DL_MIN_LEN 3 +#endif +#if !defined(DL_SHIFT) +# define DL_SHIFT ((DL_BITS + (DL_MIN_LEN - 1)) / DL_MIN_LEN) +#endif + +#define LZO_HASH_GZIP 1 +#define LZO_HASH_GZIP_INCREMENTAL 2 +#define LZO_HASH_LZO_INCREMENTAL_A 3 +#define LZO_HASH_LZO_INCREMENTAL_B 4 + +#if !defined(LZO_HASH) +# error "choose a hashing strategy" +#endif + +#undef DM +#undef DX + +#if (DL_MIN_LEN == 3) +# define _DV2_A(p,shift1,shift2) \ + (((( (lzo_xint)((p)[0]) << shift1) ^ (p)[1]) << shift2) ^ (p)[2]) +# define _DV2_B(p,shift1,shift2) \ + (((( (lzo_xint)((p)[2]) << shift1) ^ (p)[1]) << shift2) ^ (p)[0]) +# define _DV3_B(p,shift1,shift2,shift3) \ + ((_DV2_B((p)+1,shift1,shift2) << (shift3)) ^ (p)[0]) +#elif (DL_MIN_LEN == 2) +# define _DV2_A(p,shift1,shift2) \ + (( (lzo_xint)(p[0]) << shift1) ^ p[1]) +# define _DV2_B(p,shift1,shift2) \ + (( (lzo_xint)(p[1]) << shift1) ^ p[2]) +#else +# error "invalid DL_MIN_LEN" +#endif +#define _DV_A(p,shift) _DV2_A(p,shift,shift) +#define _DV_B(p,shift) _DV2_B(p,shift,shift) +#define DA2(p,s1,s2) \ + (((((lzo_xint)((p)[2]) << (s2)) + (p)[1]) << (s1)) + (p)[0]) +#define DS2(p,s1,s2) \ + (((((lzo_xint)((p)[2]) << (s2)) - (p)[1]) << (s1)) - (p)[0]) +#define DX2(p,s1,s2) \ + (((((lzo_xint)((p)[2]) << (s2)) ^ (p)[1]) << (s1)) ^ (p)[0]) +#define DA3(p,s1,s2,s3) ((DA2((p)+1,s2,s3) << (s1)) + (p)[0]) +#define DS3(p,s1,s2,s3) ((DS2((p)+1,s2,s3) << (s1)) - (p)[0]) +#define DX3(p,s1,s2,s3) ((DX2((p)+1,s2,s3) << (s1)) ^ (p)[0]) +#define DMS(v,s) ((lzo_uint) (((v) & (D_MASK >> (s))) << (s))) +#define DM(v) DMS(v,0) + +#if (LZO_HASH == LZO_HASH_GZIP) +# define _DINDEX(dv,p) (_DV_A((p),DL_SHIFT)) + +#elif (LZO_HASH == LZO_HASH_GZIP_INCREMENTAL) +# define __LZO_HASH_INCREMENTAL 1 +# define DVAL_FIRST(dv,p) dv = _DV_A((p),DL_SHIFT) +# define DVAL_NEXT(dv,p) dv = (((dv) << DL_SHIFT) ^ p[2]) +# define _DINDEX(dv,p) (dv) +# define DVAL_LOOKAHEAD DL_MIN_LEN + +#elif (LZO_HASH == LZO_HASH_LZO_INCREMENTAL_A) +# define __LZO_HASH_INCREMENTAL 1 +# define DVAL_FIRST(dv,p) dv = _DV_A((p),5) +# define DVAL_NEXT(dv,p) \ + dv ^= (lzo_xint)(p[-1]) << (2*5); dv = (((dv) << 5) ^ p[2]) +# define _DINDEX(dv,p) ((DMUL(0x9f5f,dv)) >> 5) +# define DVAL_LOOKAHEAD DL_MIN_LEN + +#elif (LZO_HASH == LZO_HASH_LZO_INCREMENTAL_B) +# define __LZO_HASH_INCREMENTAL 1 +# define DVAL_FIRST(dv,p) dv = _DV_B((p),5) +# define DVAL_NEXT(dv,p) \ + dv ^= p[-1]; dv = (((dv) >> 5) ^ ((lzo_xint)(p[2]) << (2*5))) +# define _DINDEX(dv,p) ((DMUL(0x9f5f,dv)) >> 5) +# define DVAL_LOOKAHEAD DL_MIN_LEN + +#else +# error "choose a hashing strategy" +#endif + +#ifndef DINDEX +#define DINDEX(dv,p) ((lzo_uint)((_DINDEX(dv,p)) & DL_MASK) << DD_BITS) +#endif +#if !defined(DINDEX1) && defined(D_INDEX1) +#define DINDEX1 D_INDEX1 +#endif +#if !defined(DINDEX2) && defined(D_INDEX2) +#define DINDEX2 D_INDEX2 +#endif + +#if !defined(__LZO_HASH_INCREMENTAL) +# define DVAL_FIRST(dv,p) ((void) 0) +# define DVAL_NEXT(dv,p) ((void) 0) +# define DVAL_LOOKAHEAD 0 +#endif + +#if !defined(DVAL_ASSERT) +#if defined(__LZO_HASH_INCREMENTAL) && !defined(NDEBUG) +#if 1 && (LZO_CC_ARMCC_GNUC || LZO_CC_CLANG || (LZO_CC_GNUC >= 0x020700ul) || LZO_CC_INTELC_GNUC || LZO_CC_LLVM || LZO_CC_PATHSCALE || LZO_CC_PGI) +static void __attribute__((__unused__)) +#else +static void +#endif +DVAL_ASSERT(lzo_xint dv, const lzo_bytep p) +{ + lzo_xint df; + DVAL_FIRST(df,(p)); + assert(DINDEX(dv,p) == DINDEX(df,p)); +} +#else +# define DVAL_ASSERT(dv,p) ((void) 0) +#endif +#endif + +#if (LZO_DICT_USE_PTR) +# define DENTRY(p,in) (p) +# define GINDEX(m_pos,m_off,dict,dindex,in) m_pos = dict[dindex] +#else +# define DENTRY(p,in) ((lzo_dict_t) pd(p, in)) +# define GINDEX(m_pos,m_off,dict,dindex,in) m_off = dict[dindex] +#endif + +#if (DD_BITS == 0) + +# define UPDATE_D(dict,drun,dv,p,in) dict[ DINDEX(dv,p) ] = DENTRY(p,in) +# define UPDATE_I(dict,drun,index,p,in) dict[index] = DENTRY(p,in) +# define UPDATE_P(ptr,drun,p,in) (ptr)[0] = DENTRY(p,in) + +#else + +# define UPDATE_D(dict,drun,dv,p,in) \ + dict[ DINDEX(dv,p) + drun++ ] = DENTRY(p,in); drun &= DD_MASK +# define UPDATE_I(dict,drun,index,p,in) \ + dict[ (index) + drun++ ] = DENTRY(p,in); drun &= DD_MASK +# define UPDATE_P(ptr,drun,p,in) \ + (ptr) [ drun++ ] = DENTRY(p,in); drun &= DD_MASK + +#endif + +#if (LZO_DICT_USE_PTR) + +#define LZO_CHECK_MPOS_DET(m_pos,m_off,in,ip,max_offset) \ + (m_pos == NULL || (m_off = pd(ip, m_pos)) > max_offset) + +#define LZO_CHECK_MPOS_NON_DET(m_pos,m_off,in,ip,max_offset) \ + (BOUNDS_CHECKING_OFF_IN_EXPR(( \ + m_pos = ip - (lzo_uint) PTR_DIFF(ip,m_pos), \ + PTR_LT(m_pos,in) || \ + (m_off = (lzo_uint) PTR_DIFF(ip,m_pos)) == 0 || \ + m_off > max_offset ))) + +#else + +#define LZO_CHECK_MPOS_DET(m_pos,m_off,in,ip,max_offset) \ + (m_off == 0 || \ + ((m_off = pd(ip, in) - m_off) > max_offset) || \ + (m_pos = (ip) - (m_off), 0) ) + +#define LZO_CHECK_MPOS_NON_DET(m_pos,m_off,in,ip,max_offset) \ + (pd(ip, in) <= m_off || \ + ((m_off = pd(ip, in) - m_off) > max_offset) || \ + (m_pos = (ip) - (m_off), 0) ) + +#endif + +#if (LZO_DETERMINISTIC) +# define LZO_CHECK_MPOS LZO_CHECK_MPOS_DET +#else +# define LZO_CHECK_MPOS LZO_CHECK_MPOS_NON_DET +#endif + +#ifdef __cplusplus +} +#endif + +#endif + +#endif + +#endif + +#define LZO_DETERMINISTIC !(LZO_DICT_USE_PTR) + +#ifndef DO_COMPRESS +#define DO_COMPRESS lzo1x_1_compress +#endif + +#if 1 && defined(DO_COMPRESS) && !defined(do_compress) +# define do_compress LZO_PP_ECONCAT2(DO_COMPRESS,_core) +#endif + +static __lzo_noinline lzo_uint +do_compress ( const lzo_bytep in , lzo_uint in_len, + lzo_bytep out, lzo_uintp out_len, + lzo_uint ti, lzo_voidp wrkmem) +{ + const lzo_bytep ip; + lzo_bytep op; + const lzo_bytep const in_end = in + in_len; + const lzo_bytep const ip_end = in + in_len - 20; + const lzo_bytep ii; + lzo_dict_p const dict = (lzo_dict_p) wrkmem; + + op = out; + ip = in; + ii = ip; + + ip += ti < 4 ? 4 - ti : 0; + for (;;) + { + const lzo_bytep m_pos; +#if !(LZO_DETERMINISTIC) + LZO_DEFINE_UNINITIALIZED_VAR(lzo_uint, m_off, 0); + lzo_uint m_len; + lzo_uint dindex; +next: + if __lzo_unlikely(ip >= ip_end) + break; + DINDEX1(dindex,ip); + GINDEX(m_pos,m_off,dict,dindex,in); + if (LZO_CHECK_MPOS_NON_DET(m_pos,m_off,in,ip,M4_MAX_OFFSET)) + goto literal; +#if 1 + if (m_off <= M2_MAX_OFFSET || m_pos[3] == ip[3]) + goto try_match; + DINDEX2(dindex,ip); +#endif + GINDEX(m_pos,m_off,dict,dindex,in); + if (LZO_CHECK_MPOS_NON_DET(m_pos,m_off,in,ip,M4_MAX_OFFSET)) + goto literal; + if (m_off <= M2_MAX_OFFSET || m_pos[3] == ip[3]) + goto try_match; + goto literal; + +try_match: +#if (LZO_OPT_UNALIGNED32) + if (UA_GET_NE32(m_pos) != UA_GET_NE32(ip)) +#else + if (m_pos[0] != ip[0] || m_pos[1] != ip[1] || m_pos[2] != ip[2] || m_pos[3] != ip[3]) +#endif + { +literal: + UPDATE_I(dict,0,dindex,ip,in); + ip += 1 + ((ip - ii) >> 5); + continue; + } + UPDATE_I(dict,0,dindex,ip,in); +#else + lzo_uint m_off; + lzo_uint m_len; + { + lzo_uint32_t dv; + lzo_uint dindex; +literal: + ip += 1 + ((ip - ii) >> 5); +next: + if __lzo_unlikely(ip >= ip_end) + break; + dv = UA_GET_LE32(ip); + dindex = DINDEX(dv,ip); + GINDEX(m_off,m_pos,in+dict,dindex,in); + UPDATE_I(dict,0,dindex,ip,in); + if __lzo_unlikely(dv != UA_GET_LE32(m_pos)) + goto literal; + } +#endif + + ii -= ti; ti = 0; + { + lzo_uint t = pd(ip,ii); + if (t != 0) + { + if (t <= 3) + { + op[-2] = LZO_BYTE(op[-2] | t); +#if (LZO_OPT_UNALIGNED32) + UA_COPY4(op, ii); + op += t; +#else + { do *op++ = *ii++; while (--t > 0); } +#endif + } +#if (LZO_OPT_UNALIGNED32) || (LZO_OPT_UNALIGNED64) + else if (t <= 16) + { + *op++ = LZO_BYTE(t - 3); + UA_COPY8(op, ii); + UA_COPY8(op+8, ii+8); + op += t; + } +#endif + else + { + if (t <= 18) + *op++ = LZO_BYTE(t - 3); + else + { + lzo_uint tt = t - 18; + *op++ = 0; + while __lzo_unlikely(tt > 255) + { + tt -= 255; + UA_SET1(op, 0); + op++; + } + assert(tt > 0); + *op++ = LZO_BYTE(tt); + } +#if (LZO_OPT_UNALIGNED32) || (LZO_OPT_UNALIGNED64) + do { + UA_COPY8(op, ii); + UA_COPY8(op+8, ii+8); + op += 16; ii += 16; t -= 16; + } while (t >= 16); if (t > 0) +#endif + { do *op++ = *ii++; while (--t > 0); } + } + } + } + m_len = 4; + { +#if (LZO_OPT_UNALIGNED64) + lzo_uint64_t v; + v = UA_GET_NE64(ip + m_len) ^ UA_GET_NE64(m_pos + m_len); + if __lzo_unlikely(v == 0) { + do { + m_len += 8; + v = UA_GET_NE64(ip + m_len) ^ UA_GET_NE64(m_pos + m_len); + if __lzo_unlikely(ip + m_len >= ip_end) + goto m_len_done; + } while (v == 0); + } +#if (LZO_ABI_BIG_ENDIAN) && defined(lzo_bitops_ctlz64) + m_len += lzo_bitops_ctlz64(v) / CHAR_BIT; +#elif (LZO_ABI_BIG_ENDIAN) + if ((v >> (64 - CHAR_BIT)) == 0) do { + v <<= CHAR_BIT; + m_len += 1; + } while ((v >> (64 - CHAR_BIT)) == 0); +#elif (LZO_ABI_LITTLE_ENDIAN) && defined(lzo_bitops_cttz64) + m_len += lzo_bitops_cttz64(v) / CHAR_BIT; +#elif (LZO_ABI_LITTLE_ENDIAN) + if ((v & UCHAR_MAX) == 0) do { + v >>= CHAR_BIT; + m_len += 1; + } while ((v & UCHAR_MAX) == 0); +#else + if (ip[m_len] == m_pos[m_len]) do { + m_len += 1; + } while (ip[m_len] == m_pos[m_len]); +#endif +#elif (LZO_OPT_UNALIGNED32) + lzo_uint32_t v; + v = UA_GET_NE32(ip + m_len) ^ UA_GET_NE32(m_pos + m_len); + if __lzo_unlikely(v == 0) { + do { + m_len += 4; + v = UA_GET_NE32(ip + m_len) ^ UA_GET_NE32(m_pos + m_len); + if (v != 0) + break; + m_len += 4; + v = UA_GET_NE32(ip + m_len) ^ UA_GET_NE32(m_pos + m_len); + if __lzo_unlikely(ip + m_len >= ip_end) + goto m_len_done; + } while (v == 0); + } +#if (LZO_ABI_BIG_ENDIAN) && defined(lzo_bitops_ctlz32) + m_len += lzo_bitops_ctlz32(v) / CHAR_BIT; +#elif (LZO_ABI_BIG_ENDIAN) + if ((v >> (32 - CHAR_BIT)) == 0) do { + v <<= CHAR_BIT; + m_len += 1; + } while ((v >> (32 - CHAR_BIT)) == 0); +#elif (LZO_ABI_LITTLE_ENDIAN) && defined(lzo_bitops_cttz32) + m_len += lzo_bitops_cttz32(v) / CHAR_BIT; +#elif (LZO_ABI_LITTLE_ENDIAN) + if ((v & UCHAR_MAX) == 0) do { + v >>= CHAR_BIT; + m_len += 1; + } while ((v & UCHAR_MAX) == 0); +#else + if (ip[m_len] == m_pos[m_len]) do { + m_len += 1; + } while (ip[m_len] == m_pos[m_len]); +#endif +#else + if __lzo_unlikely(ip[m_len] == m_pos[m_len]) { + do { + m_len += 1; + if (ip[m_len] != m_pos[m_len]) + break; + m_len += 1; + if (ip[m_len] != m_pos[m_len]) + break; + m_len += 1; + if (ip[m_len] != m_pos[m_len]) + break; + m_len += 1; + if (ip[m_len] != m_pos[m_len]) + break; + m_len += 1; + if (ip[m_len] != m_pos[m_len]) + break; + m_len += 1; + if (ip[m_len] != m_pos[m_len]) + break; + m_len += 1; + if (ip[m_len] != m_pos[m_len]) + break; + m_len += 1; + if __lzo_unlikely(ip + m_len >= ip_end) + goto m_len_done; + } while (ip[m_len] == m_pos[m_len]); + } +#endif + } +m_len_done: + m_off = pd(ip,m_pos); + ip += m_len; + ii = ip; + if (m_len <= M2_MAX_LEN && m_off <= M2_MAX_OFFSET) + { + m_off -= 1; +#if defined(LZO1X) + *op++ = LZO_BYTE(((m_len - 1) << 5) | ((m_off & 7) << 2)); + *op++ = LZO_BYTE(m_off >> 3); +#elif defined(LZO1Y) + *op++ = LZO_BYTE(((m_len + 1) << 4) | ((m_off & 3) << 2)); + *op++ = LZO_BYTE(m_off >> 2); +#endif + } + else if (m_off <= M3_MAX_OFFSET) + { + m_off -= 1; + if (m_len <= M3_MAX_LEN) + *op++ = LZO_BYTE(M3_MARKER | (m_len - 2)); + else + { + m_len -= M3_MAX_LEN; + *op++ = M3_MARKER | 0; + while __lzo_unlikely(m_len > 255) + { + m_len -= 255; + UA_SET1(op, 0); + op++; + } + *op++ = LZO_BYTE(m_len); + } + *op++ = LZO_BYTE(m_off << 2); + *op++ = LZO_BYTE(m_off >> 6); + } + else + { + m_off -= 0x4000; + if (m_len <= M4_MAX_LEN) + *op++ = LZO_BYTE(M4_MARKER | ((m_off >> 11) & 8) | (m_len - 2)); + else + { + m_len -= M4_MAX_LEN; + *op++ = LZO_BYTE(M4_MARKER | ((m_off >> 11) & 8)); + while __lzo_unlikely(m_len > 255) + { + m_len -= 255; + UA_SET1(op, 0); + op++; + } + *op++ = LZO_BYTE(m_len); + } + *op++ = LZO_BYTE(m_off << 2); + *op++ = LZO_BYTE(m_off >> 6); + } + goto next; + } + + *out_len = pd(op, out); + return pd(in_end,ii-ti); +} + +LZO_PUBLIC(int) +DO_COMPRESS ( const lzo_bytep in , lzo_uint in_len, + lzo_bytep out, lzo_uintp out_len, + lzo_voidp wrkmem ) +{ + const lzo_bytep ip = in; + lzo_bytep op = out; + lzo_uint l = in_len; + lzo_uint t = 0; + + while (l > 20) + { + lzo_uint ll = l; + lzo_uintptr_t ll_end; +#if 0 || (LZO_DETERMINISTIC) + ll = LZO_MIN(ll, 49152); +#endif + ll_end = (lzo_uintptr_t)ip + ll; + if ((ll_end + ((t + ll) >> 5)) <= ll_end || (const lzo_bytep)(ll_end + ((t + ll) >> 5)) <= ip + ll) + break; +#if (LZO_DETERMINISTIC) + lzo_memset(wrkmem, 0, ((lzo_uint)1 << D_BITS) * sizeof(lzo_dict_t)); +#endif + t = do_compress(ip,ll,op,out_len,t,wrkmem); + ip += ll; + op += *out_len; + l -= ll; + } + t += l; + + if (t > 0) + { + const lzo_bytep ii = in + in_len - t; + + if (op == out && t <= 238) + *op++ = LZO_BYTE(17 + t); + else if (t <= 3) + op[-2] = LZO_BYTE(op[-2] | t); + else if (t <= 18) + *op++ = LZO_BYTE(t - 3); + else + { + lzo_uint tt = t - 18; + + *op++ = 0; + while (tt > 255) + { + tt -= 255; + UA_SET1(op, 0); + op++; + } + assert(tt > 0); + *op++ = LZO_BYTE(tt); + } + UA_COPYN(op, ii, t); + op += t; + } + + *op++ = M4_MARKER | 1; + *op++ = 0; + *op++ = 0; + + *out_len = pd(op, out); + return LZO_E_OK; +} + +#endif + +#undef do_compress +#undef DO_COMPRESS +#undef LZO_HASH + +#undef LZO_TEST_OVERRUN +#undef DO_DECOMPRESS +#define DO_DECOMPRESS lzo1x_decompress + +#if !defined(MINILZO_CFG_SKIP_LZO1X_DECOMPRESS) + +#if defined(LZO_TEST_OVERRUN) +# if !defined(LZO_TEST_OVERRUN_INPUT) +# define LZO_TEST_OVERRUN_INPUT 2 +# endif +# if !defined(LZO_TEST_OVERRUN_OUTPUT) +# define LZO_TEST_OVERRUN_OUTPUT 2 +# endif +# if !defined(LZO_TEST_OVERRUN_LOOKBEHIND) +# define LZO_TEST_OVERRUN_LOOKBEHIND 1 +# endif +#endif + +#undef TEST_IP +#undef TEST_OP +#undef TEST_IP_AND_TEST_OP +#undef TEST_LB +#undef TEST_LBO +#undef NEED_IP +#undef NEED_OP +#undef TEST_IV +#undef TEST_OV +#undef HAVE_TEST_IP +#undef HAVE_TEST_OP +#undef HAVE_NEED_IP +#undef HAVE_NEED_OP +#undef HAVE_ANY_IP +#undef HAVE_ANY_OP + +#if defined(LZO_TEST_OVERRUN_INPUT) +# if (LZO_TEST_OVERRUN_INPUT >= 1) +# define TEST_IP (ip < ip_end) +# endif +# if (LZO_TEST_OVERRUN_INPUT >= 2) +# define NEED_IP(x) \ + if ((lzo_uint)(ip_end - ip) < (lzo_uint)(x)) goto input_overrun +# define TEST_IV(x) if ((x) > (lzo_uint)0 - (511)) goto input_overrun +# endif +#endif + +#if defined(LZO_TEST_OVERRUN_OUTPUT) +# if (LZO_TEST_OVERRUN_OUTPUT >= 1) +# define TEST_OP (op <= op_end) +# endif +# if (LZO_TEST_OVERRUN_OUTPUT >= 2) +# undef TEST_OP +# define NEED_OP(x) \ + if ((lzo_uint)(op_end - op) < (lzo_uint)(x)) goto output_overrun +# define TEST_OV(x) if ((x) > (lzo_uint)0 - (511)) goto output_overrun +# endif +#endif + +#if defined(LZO_TEST_OVERRUN_LOOKBEHIND) +# define TEST_LB(m_pos) if (PTR_LT(m_pos,out) || PTR_GE(m_pos,op)) goto lookbehind_overrun +# define TEST_LBO(m_pos,o) if (PTR_LT(m_pos,out) || PTR_GE(m_pos,op-(o))) goto lookbehind_overrun +#else +# define TEST_LB(m_pos) ((void) 0) +# define TEST_LBO(m_pos,o) ((void) 0) +#endif + +#if !defined(LZO_EOF_CODE) && !defined(TEST_IP) +# define TEST_IP (ip < ip_end) +#endif + +#if defined(TEST_IP) +# define HAVE_TEST_IP 1 +#else +# define TEST_IP 1 +#endif +#if defined(TEST_OP) +# define HAVE_TEST_OP 1 +#else +# define TEST_OP 1 +#endif + +#if defined(HAVE_TEST_IP) && defined(HAVE_TEST_OP) +# define TEST_IP_AND_TEST_OP (TEST_IP && TEST_OP) +#elif defined(HAVE_TEST_IP) +# define TEST_IP_AND_TEST_OP TEST_IP +#elif defined(HAVE_TEST_OP) +# define TEST_IP_AND_TEST_OP TEST_OP +#else +# define TEST_IP_AND_TEST_OP 1 +#endif + +#if defined(NEED_IP) +# define HAVE_NEED_IP 1 +#else +# define NEED_IP(x) ((void) 0) +# define TEST_IV(x) ((void) 0) +#endif +#if defined(NEED_OP) +# define HAVE_NEED_OP 1 +#else +# define NEED_OP(x) ((void) 0) +# define TEST_OV(x) ((void) 0) +#endif + +#if defined(HAVE_TEST_IP) || defined(HAVE_NEED_IP) +# define HAVE_ANY_IP 1 +#endif +#if defined(HAVE_TEST_OP) || defined(HAVE_NEED_OP) +# define HAVE_ANY_OP 1 +#endif + +#if defined(DO_DECOMPRESS) +LZO_PUBLIC(int) +DO_DECOMPRESS ( const lzo_bytep in , lzo_uint in_len, + lzo_bytep out, lzo_uintp out_len, + lzo_voidp wrkmem ) +#endif +{ + lzo_bytep op; + const lzo_bytep ip; + lzo_uint t; +#if defined(COPY_DICT) + lzo_uint m_off; + const lzo_bytep dict_end; +#else + const lzo_bytep m_pos; +#endif + + const lzo_bytep const ip_end = in + in_len; +#if defined(HAVE_ANY_OP) + lzo_bytep const op_end = out + *out_len; +#endif +#if defined(LZO1Z) + lzo_uint last_m_off = 0; +#endif + + LZO_UNUSED(wrkmem); + +#if defined(COPY_DICT) + if (dict) + { + if (dict_len > M4_MAX_OFFSET) + { + dict += dict_len - M4_MAX_OFFSET; + dict_len = M4_MAX_OFFSET; + } + dict_end = dict + dict_len; + } + else + { + dict_len = 0; + dict_end = NULL; + } +#endif + + *out_len = 0; + + op = out; + ip = in; + + NEED_IP(1); + if (*ip > 17) + { + t = *ip++ - 17; + if (t < 4) + goto match_next; + assert(t > 0); NEED_OP(t); NEED_IP(t+3); + do *op++ = *ip++; while (--t > 0); + goto first_literal_run; + } + + for (;;) + { + NEED_IP(3); + t = *ip++; + if (t >= 16) + goto match; + if (t == 0) + { + while (*ip == 0) + { + t += 255; + ip++; + TEST_IV(t); + NEED_IP(1); + } + t += 15 + *ip++; + } + assert(t > 0); NEED_OP(t+3); NEED_IP(t+6); +#if (LZO_OPT_UNALIGNED64) && (LZO_OPT_UNALIGNED32) + t += 3; + if (t >= 8) do + { + UA_COPY8(op,ip); + op += 8; ip += 8; t -= 8; + } while (t >= 8); + if (t >= 4) + { + UA_COPY4(op,ip); + op += 4; ip += 4; t -= 4; + } + if (t > 0) + { + *op++ = *ip++; + if (t > 1) { *op++ = *ip++; if (t > 2) { *op++ = *ip++; } } + } +#elif (LZO_OPT_UNALIGNED32) || (LZO_ALIGNED_OK_4) +#if !(LZO_OPT_UNALIGNED32) + if (PTR_ALIGNED2_4(op,ip)) + { +#endif + UA_COPY4(op,ip); + op += 4; ip += 4; + if (--t > 0) + { + if (t >= 4) + { + do { + UA_COPY4(op,ip); + op += 4; ip += 4; t -= 4; + } while (t >= 4); + if (t > 0) do *op++ = *ip++; while (--t > 0); + } + else + do *op++ = *ip++; while (--t > 0); + } +#if !(LZO_OPT_UNALIGNED32) + } + else +#endif +#endif +#if !(LZO_OPT_UNALIGNED32) + { + *op++ = *ip++; *op++ = *ip++; *op++ = *ip++; + do *op++ = *ip++; while (--t > 0); + } +#endif + +first_literal_run: + + t = *ip++; + if (t >= 16) + goto match; +#if defined(COPY_DICT) +#if defined(LZO1Z) + m_off = (1 + M2_MAX_OFFSET) + (t << 6) + (*ip++ >> 2); + last_m_off = m_off; +#else + m_off = (1 + M2_MAX_OFFSET) + (t >> 2) + (*ip++ << 2); +#endif + NEED_OP(3); + t = 3; COPY_DICT(t,m_off) +#else +#if defined(LZO1Z) + t = (1 + M2_MAX_OFFSET) + (t << 6) + (*ip++ >> 2); + m_pos = op - t; + last_m_off = t; +#else + m_pos = op - (1 + M2_MAX_OFFSET); + m_pos -= t >> 2; + m_pos -= *ip++ << 2; +#endif + TEST_LB(m_pos); NEED_OP(3); + *op++ = *m_pos++; *op++ = *m_pos++; *op++ = *m_pos; +#endif + goto match_done; + + for (;;) { +match: + if (t >= 64) + { +#if defined(COPY_DICT) +#if defined(LZO1X) + m_off = 1 + ((t >> 2) & 7) + (*ip++ << 3); + t = (t >> 5) - 1; +#elif defined(LZO1Y) + m_off = 1 + ((t >> 2) & 3) + (*ip++ << 2); + t = (t >> 4) - 3; +#elif defined(LZO1Z) + m_off = t & 0x1f; + if (m_off >= 0x1c) + m_off = last_m_off; + else + { + m_off = 1 + (m_off << 6) + (*ip++ >> 2); + last_m_off = m_off; + } + t = (t >> 5) - 1; +#endif +#else +#if defined(LZO1X) + m_pos = op - 1; + m_pos -= (t >> 2) & 7; + m_pos -= *ip++ << 3; + t = (t >> 5) - 1; +#elif defined(LZO1Y) + m_pos = op - 1; + m_pos -= (t >> 2) & 3; + m_pos -= *ip++ << 2; + t = (t >> 4) - 3; +#elif defined(LZO1Z) + { + lzo_uint off = t & 0x1f; + m_pos = op; + if (off >= 0x1c) + { + assert(last_m_off > 0); + m_pos -= last_m_off; + } + else + { + off = 1 + (off << 6) + (*ip++ >> 2); + m_pos -= off; + last_m_off = off; + } + } + t = (t >> 5) - 1; +#endif + TEST_LB(m_pos); assert(t > 0); NEED_OP(t+3-1); + goto copy_match; +#endif + } + else if (t >= 32) + { + t &= 31; + if (t == 0) + { + while (*ip == 0) + { + t += 255; + ip++; + TEST_OV(t); + NEED_IP(1); + } + t += 31 + *ip++; + NEED_IP(2); + } +#if defined(COPY_DICT) +#if defined(LZO1Z) + m_off = 1 + (ip[0] << 6) + (ip[1] >> 2); + last_m_off = m_off; +#else + m_off = 1 + (ip[0] >> 2) + (ip[1] << 6); +#endif +#else +#if defined(LZO1Z) + { + lzo_uint off = 1 + (ip[0] << 6) + (ip[1] >> 2); + m_pos = op - off; + last_m_off = off; + } +#elif (LZO_OPT_UNALIGNED16) && (LZO_ABI_LITTLE_ENDIAN) + m_pos = op - 1; + m_pos -= UA_GET_LE16(ip) >> 2; +#else + m_pos = op - 1; + m_pos -= (ip[0] >> 2) + (ip[1] << 6); +#endif +#endif + ip += 2; + } + else if (t >= 16) + { +#if defined(COPY_DICT) + m_off = (t & 8) << 11; +#else + m_pos = op; + m_pos -= (t & 8) << 11; +#endif + t &= 7; + if (t == 0) + { + while (*ip == 0) + { + t += 255; + ip++; + TEST_OV(t); + NEED_IP(1); + } + t += 7 + *ip++; + NEED_IP(2); + } +#if defined(COPY_DICT) +#if defined(LZO1Z) + m_off += (ip[0] << 6) + (ip[1] >> 2); +#else + m_off += (ip[0] >> 2) + (ip[1] << 6); +#endif + ip += 2; + if (m_off == 0) + goto eof_found; + m_off += 0x4000; +#if defined(LZO1Z) + last_m_off = m_off; +#endif +#else +#if defined(LZO1Z) + m_pos -= (ip[0] << 6) + (ip[1] >> 2); +#elif (LZO_OPT_UNALIGNED16) && (LZO_ABI_LITTLE_ENDIAN) + m_pos -= UA_GET_LE16(ip) >> 2; +#else + m_pos -= (ip[0] >> 2) + (ip[1] << 6); +#endif + ip += 2; + if (m_pos == op) + goto eof_found; + m_pos -= 0x4000; +#if defined(LZO1Z) + last_m_off = pd((const lzo_bytep)op, m_pos); +#endif +#endif + } + else + { +#if defined(COPY_DICT) +#if defined(LZO1Z) + m_off = 1 + (t << 6) + (*ip++ >> 2); + last_m_off = m_off; +#else + m_off = 1 + (t >> 2) + (*ip++ << 2); +#endif + NEED_OP(2); + t = 2; COPY_DICT(t,m_off) +#else +#if defined(LZO1Z) + t = 1 + (t << 6) + (*ip++ >> 2); + m_pos = op - t; + last_m_off = t; +#else + m_pos = op - 1; + m_pos -= t >> 2; + m_pos -= *ip++ << 2; +#endif + TEST_LB(m_pos); NEED_OP(2); + *op++ = *m_pos++; *op++ = *m_pos; +#endif + goto match_done; + } + +#if defined(COPY_DICT) + + NEED_OP(t+3-1); + t += 3-1; COPY_DICT(t,m_off) + +#else + + TEST_LB(m_pos); assert(t > 0); NEED_OP(t+3-1); +#if (LZO_OPT_UNALIGNED64) && (LZO_OPT_UNALIGNED32) + if (op - m_pos >= 8) + { + t += (3 - 1); + if (t >= 8) do + { + UA_COPY8(op,m_pos); + op += 8; m_pos += 8; t -= 8; + } while (t >= 8); + if (t >= 4) + { + UA_COPY4(op,m_pos); + op += 4; m_pos += 4; t -= 4; + } + if (t > 0) + { + *op++ = m_pos[0]; + if (t > 1) { *op++ = m_pos[1]; if (t > 2) { *op++ = m_pos[2]; } } + } + } + else +#elif (LZO_OPT_UNALIGNED32) || (LZO_ALIGNED_OK_4) +#if !(LZO_OPT_UNALIGNED32) + if (t >= 2 * 4 - (3 - 1) && PTR_ALIGNED2_4(op,m_pos)) + { + assert((op - m_pos) >= 4); +#else + if (t >= 2 * 4 - (3 - 1) && (op - m_pos) >= 4) + { +#endif + UA_COPY4(op,m_pos); + op += 4; m_pos += 4; t -= 4 - (3 - 1); + do { + UA_COPY4(op,m_pos); + op += 4; m_pos += 4; t -= 4; + } while (t >= 4); + if (t > 0) do *op++ = *m_pos++; while (--t > 0); + } + else +#endif + { +copy_match: + *op++ = *m_pos++; *op++ = *m_pos++; + do *op++ = *m_pos++; while (--t > 0); + } + +#endif + +match_done: +#if defined(LZO1Z) + t = ip[-1] & 3; +#else + t = ip[-2] & 3; +#endif + if (t == 0) + break; + +match_next: + assert(t > 0); assert(t < 4); NEED_OP(t); NEED_IP(t+3); +#if 0 + do *op++ = *ip++; while (--t > 0); +#else + *op++ = *ip++; + if (t > 1) { *op++ = *ip++; if (t > 2) { *op++ = *ip++; } } +#endif + t = *ip++; + } + } + +eof_found: + *out_len = pd(op, out); + return (ip == ip_end ? LZO_E_OK : + (ip < ip_end ? LZO_E_INPUT_NOT_CONSUMED : LZO_E_INPUT_OVERRUN)); + +#if defined(HAVE_NEED_IP) +input_overrun: + *out_len = pd(op, out); + return LZO_E_INPUT_OVERRUN; +#endif + +#if defined(HAVE_NEED_OP) +output_overrun: + *out_len = pd(op, out); + return LZO_E_OUTPUT_OVERRUN; +#endif + +#if defined(LZO_TEST_OVERRUN_LOOKBEHIND) +lookbehind_overrun: + *out_len = pd(op, out); + return LZO_E_LOOKBEHIND_OVERRUN; +#endif +} + +#endif + +#define LZO_TEST_OVERRUN 1 +#undef DO_DECOMPRESS +#define DO_DECOMPRESS lzo1x_decompress_safe + +#if !defined(MINILZO_CFG_SKIP_LZO1X_DECOMPRESS_SAFE) + +#if defined(LZO_TEST_OVERRUN) +# if !defined(LZO_TEST_OVERRUN_INPUT) +# define LZO_TEST_OVERRUN_INPUT 2 +# endif +# if !defined(LZO_TEST_OVERRUN_OUTPUT) +# define LZO_TEST_OVERRUN_OUTPUT 2 +# endif +# if !defined(LZO_TEST_OVERRUN_LOOKBEHIND) +# define LZO_TEST_OVERRUN_LOOKBEHIND 1 +# endif +#endif + +#undef TEST_IP +#undef TEST_OP +#undef TEST_IP_AND_TEST_OP +#undef TEST_LB +#undef TEST_LBO +#undef NEED_IP +#undef NEED_OP +#undef TEST_IV +#undef TEST_OV +#undef HAVE_TEST_IP +#undef HAVE_TEST_OP +#undef HAVE_NEED_IP +#undef HAVE_NEED_OP +#undef HAVE_ANY_IP +#undef HAVE_ANY_OP + +#if defined(LZO_TEST_OVERRUN_INPUT) +# if (LZO_TEST_OVERRUN_INPUT >= 1) +# define TEST_IP (ip < ip_end) +# endif +# if (LZO_TEST_OVERRUN_INPUT >= 2) +# define NEED_IP(x) \ + if ((lzo_uint)(ip_end - ip) < (lzo_uint)(x)) goto input_overrun +# define TEST_IV(x) if ((x) > (lzo_uint)0 - (511)) goto input_overrun +# endif +#endif + +#if defined(LZO_TEST_OVERRUN_OUTPUT) +# if (LZO_TEST_OVERRUN_OUTPUT >= 1) +# define TEST_OP (op <= op_end) +# endif +# if (LZO_TEST_OVERRUN_OUTPUT >= 2) +# undef TEST_OP +# define NEED_OP(x) \ + if ((lzo_uint)(op_end - op) < (lzo_uint)(x)) goto output_overrun +# define TEST_OV(x) if ((x) > (lzo_uint)0 - (511)) goto output_overrun +# endif +#endif + +#if defined(LZO_TEST_OVERRUN_LOOKBEHIND) +# define TEST_LB(m_pos) if (PTR_LT(m_pos,out) || PTR_GE(m_pos,op)) goto lookbehind_overrun +# define TEST_LBO(m_pos,o) if (PTR_LT(m_pos,out) || PTR_GE(m_pos,op-(o))) goto lookbehind_overrun +#else +# define TEST_LB(m_pos) ((void) 0) +# define TEST_LBO(m_pos,o) ((void) 0) +#endif + +#if !defined(LZO_EOF_CODE) && !defined(TEST_IP) +# define TEST_IP (ip < ip_end) +#endif + +#if defined(TEST_IP) +# define HAVE_TEST_IP 1 +#else +# define TEST_IP 1 +#endif +#if defined(TEST_OP) +# define HAVE_TEST_OP 1 +#else +# define TEST_OP 1 +#endif + +#if defined(HAVE_TEST_IP) && defined(HAVE_TEST_OP) +# define TEST_IP_AND_TEST_OP (TEST_IP && TEST_OP) +#elif defined(HAVE_TEST_IP) +# define TEST_IP_AND_TEST_OP TEST_IP +#elif defined(HAVE_TEST_OP) +# define TEST_IP_AND_TEST_OP TEST_OP +#else +# define TEST_IP_AND_TEST_OP 1 +#endif + +#if defined(NEED_IP) +# define HAVE_NEED_IP 1 +#else +# define NEED_IP(x) ((void) 0) +# define TEST_IV(x) ((void) 0) +#endif +#if defined(NEED_OP) +# define HAVE_NEED_OP 1 +#else +# define NEED_OP(x) ((void) 0) +# define TEST_OV(x) ((void) 0) +#endif + +#if defined(HAVE_TEST_IP) || defined(HAVE_NEED_IP) +# define HAVE_ANY_IP 1 +#endif +#if defined(HAVE_TEST_OP) || defined(HAVE_NEED_OP) +# define HAVE_ANY_OP 1 +#endif + +#if defined(DO_DECOMPRESS) +LZO_PUBLIC(int) +DO_DECOMPRESS ( const lzo_bytep in , lzo_uint in_len, + lzo_bytep out, lzo_uintp out_len, + lzo_voidp wrkmem ) +#endif +{ + lzo_bytep op; + const lzo_bytep ip; + lzo_uint t; +#if defined(COPY_DICT) + lzo_uint m_off; + const lzo_bytep dict_end; +#else + const lzo_bytep m_pos; +#endif + + const lzo_bytep const ip_end = in + in_len; +#if defined(HAVE_ANY_OP) + lzo_bytep const op_end = out + *out_len; +#endif +#if defined(LZO1Z) + lzo_uint last_m_off = 0; +#endif + + LZO_UNUSED(wrkmem); + +#if defined(COPY_DICT) + if (dict) + { + if (dict_len > M4_MAX_OFFSET) + { + dict += dict_len - M4_MAX_OFFSET; + dict_len = M4_MAX_OFFSET; + } + dict_end = dict + dict_len; + } + else + { + dict_len = 0; + dict_end = NULL; + } +#endif + + *out_len = 0; + + op = out; + ip = in; + + NEED_IP(1); + if (*ip > 17) + { + t = *ip++ - 17; + if (t < 4) + goto match_next; + assert(t > 0); NEED_OP(t); NEED_IP(t+3); + do *op++ = *ip++; while (--t > 0); + goto first_literal_run; + } + + for (;;) + { + NEED_IP(3); + t = *ip++; + if (t >= 16) + goto match; + if (t == 0) + { + while (*ip == 0) + { + t += 255; + ip++; + TEST_IV(t); + NEED_IP(1); + } + t += 15 + *ip++; + } + assert(t > 0); NEED_OP(t+3); NEED_IP(t+6); +#if (LZO_OPT_UNALIGNED64) && (LZO_OPT_UNALIGNED32) + t += 3; + if (t >= 8) do + { + UA_COPY8(op,ip); + op += 8; ip += 8; t -= 8; + } while (t >= 8); + if (t >= 4) + { + UA_COPY4(op,ip); + op += 4; ip += 4; t -= 4; + } + if (t > 0) + { + *op++ = *ip++; + if (t > 1) { *op++ = *ip++; if (t > 2) { *op++ = *ip++; } } + } +#elif (LZO_OPT_UNALIGNED32) || (LZO_ALIGNED_OK_4) +#if !(LZO_OPT_UNALIGNED32) + if (PTR_ALIGNED2_4(op,ip)) + { +#endif + UA_COPY4(op,ip); + op += 4; ip += 4; + if (--t > 0) + { + if (t >= 4) + { + do { + UA_COPY4(op,ip); + op += 4; ip += 4; t -= 4; + } while (t >= 4); + if (t > 0) do *op++ = *ip++; while (--t > 0); + } + else + do *op++ = *ip++; while (--t > 0); + } +#if !(LZO_OPT_UNALIGNED32) + } + else +#endif +#endif +#if !(LZO_OPT_UNALIGNED32) + { + *op++ = *ip++; *op++ = *ip++; *op++ = *ip++; + do *op++ = *ip++; while (--t > 0); + } +#endif + +first_literal_run: + + t = *ip++; + if (t >= 16) + goto match; +#if defined(COPY_DICT) +#if defined(LZO1Z) + m_off = (1 + M2_MAX_OFFSET) + (t << 6) + (*ip++ >> 2); + last_m_off = m_off; +#else + m_off = (1 + M2_MAX_OFFSET) + (t >> 2) + (*ip++ << 2); +#endif + NEED_OP(3); + t = 3; COPY_DICT(t,m_off) +#else +#if defined(LZO1Z) + t = (1 + M2_MAX_OFFSET) + (t << 6) + (*ip++ >> 2); + m_pos = op - t; + last_m_off = t; +#else + m_pos = op - (1 + M2_MAX_OFFSET); + m_pos -= t >> 2; + m_pos -= *ip++ << 2; +#endif + TEST_LB(m_pos); NEED_OP(3); + *op++ = *m_pos++; *op++ = *m_pos++; *op++ = *m_pos; +#endif + goto match_done; + + for (;;) { +match: + if (t >= 64) + { +#if defined(COPY_DICT) +#if defined(LZO1X) + m_off = 1 + ((t >> 2) & 7) + (*ip++ << 3); + t = (t >> 5) - 1; +#elif defined(LZO1Y) + m_off = 1 + ((t >> 2) & 3) + (*ip++ << 2); + t = (t >> 4) - 3; +#elif defined(LZO1Z) + m_off = t & 0x1f; + if (m_off >= 0x1c) + m_off = last_m_off; + else + { + m_off = 1 + (m_off << 6) + (*ip++ >> 2); + last_m_off = m_off; + } + t = (t >> 5) - 1; +#endif +#else +#if defined(LZO1X) + m_pos = op - 1; + m_pos -= (t >> 2) & 7; + m_pos -= *ip++ << 3; + t = (t >> 5) - 1; +#elif defined(LZO1Y) + m_pos = op - 1; + m_pos -= (t >> 2) & 3; + m_pos -= *ip++ << 2; + t = (t >> 4) - 3; +#elif defined(LZO1Z) + { + lzo_uint off = t & 0x1f; + m_pos = op; + if (off >= 0x1c) + { + assert(last_m_off > 0); + m_pos -= last_m_off; + } + else + { + off = 1 + (off << 6) + (*ip++ >> 2); + m_pos -= off; + last_m_off = off; + } + } + t = (t >> 5) - 1; +#endif + TEST_LB(m_pos); assert(t > 0); NEED_OP(t+3-1); + goto copy_match; +#endif + } + else if (t >= 32) + { + t &= 31; + if (t == 0) + { + while (*ip == 0) + { + t += 255; + ip++; + TEST_OV(t); + NEED_IP(1); + } + t += 31 + *ip++; + NEED_IP(2); + } +#if defined(COPY_DICT) +#if defined(LZO1Z) + m_off = 1 + (ip[0] << 6) + (ip[1] >> 2); + last_m_off = m_off; +#else + m_off = 1 + (ip[0] >> 2) + (ip[1] << 6); +#endif +#else +#if defined(LZO1Z) + { + lzo_uint off = 1 + (ip[0] << 6) + (ip[1] >> 2); + m_pos = op - off; + last_m_off = off; + } +#elif (LZO_OPT_UNALIGNED16) && (LZO_ABI_LITTLE_ENDIAN) + m_pos = op - 1; + m_pos -= UA_GET_LE16(ip) >> 2; +#else + m_pos = op - 1; + m_pos -= (ip[0] >> 2) + (ip[1] << 6); +#endif +#endif + ip += 2; + } + else if (t >= 16) + { +#if defined(COPY_DICT) + m_off = (t & 8) << 11; +#else + m_pos = op; + m_pos -= (t & 8) << 11; +#endif + t &= 7; + if (t == 0) + { + while (*ip == 0) + { + t += 255; + ip++; + TEST_OV(t); + NEED_IP(1); + } + t += 7 + *ip++; + NEED_IP(2); + } +#if defined(COPY_DICT) +#if defined(LZO1Z) + m_off += (ip[0] << 6) + (ip[1] >> 2); +#else + m_off += (ip[0] >> 2) + (ip[1] << 6); +#endif + ip += 2; + if (m_off == 0) + goto eof_found; + m_off += 0x4000; +#if defined(LZO1Z) + last_m_off = m_off; +#endif +#else +#if defined(LZO1Z) + m_pos -= (ip[0] << 6) + (ip[1] >> 2); +#elif (LZO_OPT_UNALIGNED16) && (LZO_ABI_LITTLE_ENDIAN) + m_pos -= UA_GET_LE16(ip) >> 2; +#else + m_pos -= (ip[0] >> 2) + (ip[1] << 6); +#endif + ip += 2; + if (m_pos == op) + goto eof_found; + m_pos -= 0x4000; +#if defined(LZO1Z) + last_m_off = pd((const lzo_bytep)op, m_pos); +#endif +#endif + } + else + { +#if defined(COPY_DICT) +#if defined(LZO1Z) + m_off = 1 + (t << 6) + (*ip++ >> 2); + last_m_off = m_off; +#else + m_off = 1 + (t >> 2) + (*ip++ << 2); +#endif + NEED_OP(2); + t = 2; COPY_DICT(t,m_off) +#else +#if defined(LZO1Z) + t = 1 + (t << 6) + (*ip++ >> 2); + m_pos = op - t; + last_m_off = t; +#else + m_pos = op - 1; + m_pos -= t >> 2; + m_pos -= *ip++ << 2; +#endif + TEST_LB(m_pos); NEED_OP(2); + *op++ = *m_pos++; *op++ = *m_pos; +#endif + goto match_done; + } + +#if defined(COPY_DICT) + + NEED_OP(t+3-1); + t += 3-1; COPY_DICT(t,m_off) + +#else + + TEST_LB(m_pos); assert(t > 0); NEED_OP(t+3-1); +#if (LZO_OPT_UNALIGNED64) && (LZO_OPT_UNALIGNED32) + if (op - m_pos >= 8) + { + t += (3 - 1); + if (t >= 8) do + { + UA_COPY8(op,m_pos); + op += 8; m_pos += 8; t -= 8; + } while (t >= 8); + if (t >= 4) + { + UA_COPY4(op,m_pos); + op += 4; m_pos += 4; t -= 4; + } + if (t > 0) + { + *op++ = m_pos[0]; + if (t > 1) { *op++ = m_pos[1]; if (t > 2) { *op++ = m_pos[2]; } } + } + } + else +#elif (LZO_OPT_UNALIGNED32) || (LZO_ALIGNED_OK_4) +#if !(LZO_OPT_UNALIGNED32) + if (t >= 2 * 4 - (3 - 1) && PTR_ALIGNED2_4(op,m_pos)) + { + assert((op - m_pos) >= 4); +#else + if (t >= 2 * 4 - (3 - 1) && (op - m_pos) >= 4) + { +#endif + UA_COPY4(op,m_pos); + op += 4; m_pos += 4; t -= 4 - (3 - 1); + do { + UA_COPY4(op,m_pos); + op += 4; m_pos += 4; t -= 4; + } while (t >= 4); + if (t > 0) do *op++ = *m_pos++; while (--t > 0); + } + else +#endif + { +copy_match: + *op++ = *m_pos++; *op++ = *m_pos++; + do *op++ = *m_pos++; while (--t > 0); + } + +#endif + +match_done: +#if defined(LZO1Z) + t = ip[-1] & 3; +#else + t = ip[-2] & 3; +#endif + if (t == 0) + break; + +match_next: + assert(t > 0); assert(t < 4); NEED_OP(t); NEED_IP(t+3); +#if 0 + do *op++ = *ip++; while (--t > 0); +#else + *op++ = *ip++; + if (t > 1) { *op++ = *ip++; if (t > 2) { *op++ = *ip++; } } +#endif + t = *ip++; + } + } + +eof_found: + *out_len = pd(op, out); + return (ip == ip_end ? LZO_E_OK : + (ip < ip_end ? LZO_E_INPUT_NOT_CONSUMED : LZO_E_INPUT_OVERRUN)); + +#if defined(HAVE_NEED_IP) +input_overrun: + *out_len = pd(op, out); + return LZO_E_INPUT_OVERRUN; +#endif + +#if defined(HAVE_NEED_OP) +output_overrun: + *out_len = pd(op, out); + return LZO_E_OUTPUT_OVERRUN; +#endif + +#if defined(LZO_TEST_OVERRUN_LOOKBEHIND) +lookbehind_overrun: + *out_len = pd(op, out); + return LZO_E_LOOKBEHIND_OVERRUN; +#endif +} + +#endif + +/***** End of minilzo.c *****/ diff --git a/eterpack/src/minilzo/minilzo.h b/eterpack/src/minilzo/minilzo.h new file mode 100644 index 0000000..c1c2297 --- /dev/null +++ b/eterpack/src/minilzo/minilzo.h @@ -0,0 +1,106 @@ +/* minilzo.h -- mini subset of the LZO real-time data compression library + + This file is part of the LZO real-time data compression library. + + Copyright (C) 1996-2017 Markus Franz Xaver Johannes Oberhumer + All Rights Reserved. + + The LZO library is free software; you can redistribute it and/or + modify it under the terms of the GNU General Public License as + published by the Free Software Foundation; either version 2 of + the License, or (at your option) any later version. + + The LZO library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with the LZO library; see the file COPYING. + If not, write to the Free Software Foundation, Inc., + 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. + + Markus F.X.J. Oberhumer + + http://www.oberhumer.com/opensource/lzo/ + */ + +/* + * NOTE: + * the full LZO package can be found at + * http://www.oberhumer.com/opensource/lzo/ + */ + + +#ifndef __MINILZO_H_INCLUDED +#define __MINILZO_H_INCLUDED 1 + +#define MINILZO_VERSION 0x20a0 /* 2.10 */ + +#if defined(__LZOCONF_H_INCLUDED) +# error "you cannot use both LZO and miniLZO" +#endif + +/* internal Autoconf configuration file - only used when building miniLZO */ +#ifdef MINILZO_HAVE_CONFIG_H +# include +#endif +#include +#include + +#ifndef __LZODEFS_H_INCLUDED +#include "lzodefs.h" +#endif +#undef LZO_HAVE_CONFIG_H +#include "lzoconf.h" + +#if !defined(LZO_VERSION) || (LZO_VERSION != MINILZO_VERSION) +# error "version mismatch in header files" +#endif + + +#ifdef __cplusplus +extern "C" { +#endif + + +/*********************************************************************** +// +************************************************************************/ + +/* Memory required for the wrkmem parameter. + * When the required size is 0, you can also pass a NULL pointer. + */ + +#define LZO1X_MEM_COMPRESS LZO1X_1_MEM_COMPRESS +#define LZO1X_1_MEM_COMPRESS ((lzo_uint32_t) (16384L * lzo_sizeof_dict_t)) +#define LZO1X_MEM_DECOMPRESS (0) + + +/* compression */ +LZO_EXTERN(int) +lzo1x_1_compress ( const lzo_bytep src, lzo_uint src_len, + lzo_bytep dst, lzo_uintp dst_len, + lzo_voidp wrkmem ); + +/* decompression */ +LZO_EXTERN(int) +lzo1x_decompress ( const lzo_bytep src, lzo_uint src_len, + lzo_bytep dst, lzo_uintp dst_len, + lzo_voidp wrkmem /* NOT USED */ ); + +/* safe decompression with overrun testing */ +LZO_EXTERN(int) +lzo1x_decompress_safe ( const lzo_bytep src, lzo_uint src_len, + lzo_bytep dst, lzo_uintp dst_len, + lzo_voidp wrkmem /* NOT USED */ ); + + +#ifdef __cplusplus +} /* extern "C" */ +#endif + +#endif /* already included */ + + +/* vim:set ts=4 sw=4 et: */ diff --git a/eterpack/src/tea.cpp b/eterpack/src/tea.cpp new file mode 100644 index 0000000..2c47c67 --- /dev/null +++ b/eterpack/src/tea.cpp @@ -0,0 +1,87 @@ +#include "eterpack/tea.h" +#include + +namespace eterpack { + +static constexpr uint32_t TEA_ROUND = 32; +static constexpr uint32_t DELTA = 0x9E3779B9; + +void tea_code(uint32_t sz, uint32_t sy, const uint32_t key[4], uint32_t dest[2]) { + uint32_t y = sy; + uint32_t z = sz; + uint32_t sum = 0; + uint32_t n = TEA_ROUND; + + while (n-- > 0) { + y += ((z << 4 ^ z >> 5) + z) ^ (sum + key[sum & 3]); + sum += DELTA; + z += ((y << 4 ^ y >> 5) + y) ^ (sum + key[(sum >> 11) & 3]); + } + + dest[0] = y; + dest[1] = z; +} + +void tea_decode(uint32_t sz, uint32_t sy, const uint32_t key[4], uint32_t dest[2]) { + uint32_t y = sy; + uint32_t z = sz; + uint32_t sum = DELTA * TEA_ROUND; + uint32_t n = TEA_ROUND; + + while (n-- > 0) { + z -= ((y << 4 ^ y >> 5) + y) ^ (sum + key[(sum >> 11) & 3]); + sum -= DELTA; + y -= ((z << 4 ^ z >> 5) + z) ^ (sum + key[sum & 3]); + } + + dest[0] = y; + dest[1] = z; +} + +int tea_encrypt(uint32_t* dest, const uint32_t* src, const uint32_t key[4], int size) { + int resize = (size % 8 != 0) ? (size + 8 - (size % 8)) : size; + if (resize > size) { + std::memset(reinterpret_cast(const_cast(src)) + size, 0, resize - size); + } + + for (int i = 0; i < resize >> 3; ++i, dest += 2, src += 2) { + tea_code(*(src + 1), *src, key, dest); + } + return resize; +} + +int tea_decrypt(uint32_t* dest, const uint32_t* src, const uint32_t key[4], int size) { + int resize = (size % 8 != 0) ? (size + 8 - (size % 8)) : size; + for (int i = 0; i < resize >> 3; ++i, dest += 2, src += 2) { + tea_decode(*(src + 1), *src, key, dest); + } + return resize; +} + +std::vector tea_encrypt_bytes(std::span data, const uint32_t key[4]) { + size_t size = data.size(); + size_t padded_size = (size % 8 != 0) ? (size + 8 - (size % 8)) : size; + std::vector out(padded_size, 0); + std::memcpy(out.data(), data.data(), size); + + std::vector result(padded_size); + tea_encrypt(reinterpret_cast(result.data()), + reinterpret_cast(out.data()), + key, static_cast(size)); + return result; +} + +std::vector tea_decrypt_bytes(std::span data, const uint32_t key[4]) { + size_t size = data.size(); + size_t padded_size = (size % 8 != 0) ? (size + 8 - (size % 8)) : size; + std::vector in(padded_size, 0); + std::memcpy(in.data(), data.data(), size); + + std::vector result(padded_size); + tea_decrypt(reinterpret_cast(result.data()), + reinterpret_cast(in.data()), + key, static_cast(size)); + return result; +} + +} // namespace eterpack diff --git a/eterpack/src/vfs.cpp b/eterpack/src/vfs.cpp new file mode 100644 index 0000000..91438c9 --- /dev/null +++ b/eterpack/src/vfs.cpp @@ -0,0 +1,190 @@ +#include "eterpack/vfs.h" +#include "eterpack/crc32.h" +#include +#include +#include + +namespace fs = std::filesystem; + +namespace eterpack { + +static std::string normalize_vfs_path(std::string_view p) { + std::string s(p); + for (char& c : s) { + if (c == '\\') c = '/'; + else c = static_cast(std::tolower(static_cast(c))); + } + return s; +} + +EterPackVFS::EterPackVFS() = default; +EterPackVFS::~EterPackVFS() = default; + +void EterPackVFS::clear() { + std::lock_guard lock(m_mutex); + m_archives.clear(); + m_file_map.clear(); + m_crc_map.clear(); +} + +size_t EterPackVFS::get_archive_count() const { + std::lock_guard lock(m_mutex); + return m_archives.size(); +} + +size_t EterPackVFS::get_total_entry_count() const { + std::lock_guard lock(m_mutex); + return m_file_map.size(); +} + +bool EterPackVFS::mount(const std::string& base_path, + const uint32_t index_key[4], + const uint32_t security_key[4], + bool override_existing) { + auto archive = std::make_unique(); + if (!archive->open(base_path, index_key, security_key)) { + return false; + } + + std::lock_guard lock(m_mutex); + size_t arch_idx = m_archives.size(); + + for (const auto& entry : archive->get_entries()) { + if (entry.filename_crc == 0) continue; + + std::string norm = normalize_vfs_path(entry.filename); + FileLocation loc{arch_idx, &entry}; + + if (override_existing) { + m_file_map[norm] = loc; + m_crc_map[entry.filename_crc] = loc; + } else { + m_file_map.try_emplace(norm, loc); + m_crc_map.try_emplace(entry.filename_crc, loc); + } + } + + m_archives.push_back(std::move(archive)); + return true; +} + +bool EterPackVFS::mount_index_file(const std::string& index_file_path, + const std::string& pack_dir) { + std::ifstream in(index_file_path); + if (!in.is_open()) return false; + + std::vector lines; + std::string line; + while (std::getline(in, line)) { + while (!line.empty() && (line.back() == '\r' || line.back() == ' ' || line.back() == '\t')) { + line.pop_back(); + } + if (!line.empty()) { + lines.push_back(line); + } + } + + if (lines.empty() || lines[0] != "PACK") { + return false; + } + + for (size_t i = 1; i + 1 < lines.size(); i += 2) { + const std::string& pack_name = lines[i + 1]; + for (const std::string& stem : {pack_name, pack_name + "_texcache"}) { + std::string full_path = pack_dir + "/" + stem; + mount(full_path, DEFAULT_ETERPACK_KEY, DEFAULT_SECURITY_KEY, false); + } + } + + return true; +} + +bool EterPackVFS::exists(std::string_view path) const { + if (m_search_mode == VFSSearchMode::DiskFirst) { + if (fs::exists(path)) return true; + } + + std::lock_guard lock(m_mutex); + std::string norm = normalize_vfs_path(path); + if (m_file_map.find(norm) != m_file_map.end()) { + return true; + } + + uint32_t crc = GetCRC32(path); + if (m_crc_map.find(crc) != m_crc_map.end()) { + return true; + } + + if (m_search_mode == VFSSearchMode::PackFirst) { + if (fs::exists(path)) return true; + } + + return false; +} + +bool EterPackVFS::read_file(std::string_view path, std::vector& out_data) const { + auto read_from_disk = [&]() -> bool { + if (!fs::exists(path) || fs::is_directory(path)) return false; + std::ifstream f(std::string(path), std::ios::binary); + if (!f.is_open()) return false; + f.seekg(0, std::ios::end); + size_t sz = static_cast(f.tellg()); + f.seekg(0, std::ios::beg); + out_data.resize(sz); + return static_cast(f.read(reinterpret_cast(out_data.data()), sz)); + }; + + if (m_search_mode == VFSSearchMode::DiskFirst) { + if (read_from_disk()) return true; + } + + { + std::lock_guard lock(m_mutex); + std::string norm = normalize_vfs_path(path); + auto it = m_file_map.find(norm); + if (it == m_file_map.end()) { + uint32_t crc = GetCRC32(path); + it = m_crc_map.find(crc) != m_crc_map.end() ? + m_file_map.find(normalize_vfs_path(m_crc_map.find(crc)->second.entry->filename)) : + m_file_map.end(); + } + + if (it != m_file_map.end()) { + const auto& loc = it->second; + return m_archives[loc.archive_index]->extract(*loc.entry, out_data); + } + } + + if (m_search_mode == VFSSearchMode::PackFirst) { + if (read_from_disk()) return true; + } + + return false; +} + +bool EterPackVFS::exists_crc(uint32_t crc) const { + std::lock_guard lock(m_mutex); + return m_crc_map.find(crc) != m_crc_map.end(); +} + +bool EterPackVFS::read_file_crc(uint32_t crc, std::vector& out_data) const { + std::lock_guard lock(m_mutex); + auto it = m_crc_map.find(crc); + if (it != m_crc_map.end()) { + const auto& loc = it->second; + return m_archives[loc.archive_index]->extract(*loc.entry, out_data); + } + return false; +} + +std::vector EterPackVFS::list_files() const { + std::lock_guard lock(m_mutex); + std::vector result; + result.reserve(m_file_map.size()); + for (const auto& [name, loc] : m_file_map) { + result.push_back(loc.entry->filename); + } + return result; +} + +} // namespace eterpack diff --git a/eterpack/tests/eterpack_test.cpp b/eterpack/tests/eterpack_test.cpp new file mode 100644 index 0000000..fcf1615 --- /dev/null +++ b/eterpack/tests/eterpack_test.cpp @@ -0,0 +1,195 @@ +#include "eterpack/eterpack.h" +#include +#include +#include +#include +#include +#include + +namespace fs = std::filesystem; + +static int g_failures = 0; +#define TEST_CHECK(cond) \ + do { \ + if (!(cond)) { \ + std::cerr << "FAIL [" << __FILE__ << ":" << __LINE__ << "]: " #cond << std::endl; \ + ++g_failures; \ + } \ + } while(0) + +void test_tea() { + std::cout << "[Test] TEA cipher..." << std::endl; + uint32_t key[4] = { 0x12345678, 0x9abcdef0, 0x0fedcba9, 0x87654321 }; + std::string text = "SpeedTree & Metin2 CrossPlatform VFS TEA Test Data!!"; + std::span data(reinterpret_cast(text.data()), text.size()); + + auto encrypted = eterpack::tea_encrypt_bytes(data, key); + TEST_CHECK(encrypted.size() >= text.size()); + TEST_CHECK(encrypted.size() % 8 == 0); + + auto decrypted = eterpack::tea_decrypt_bytes(encrypted, key); + TEST_CHECK(decrypted.size() == encrypted.size()); + std::string recovered(reinterpret_cast(decrypted.data()), text.size()); + TEST_CHECK(recovered == text); +} + +void test_crc32() { + std::cout << "[Test] CRC32..." << std::endl; + // Known IEEE 802.3 CRC32 + const char* str = "123456789"; + uint32_t crc = eterpack::GetCRC32(str, 9); + TEST_CHECK(crc == 0xCBF43926); + + // Case-insensitive CRC + uint32_t crc_lower = eterpack::GetCaseCRC32("d:/ymir work/tree/oak.spt", 24); + uint32_t crc_upper = eterpack::GetCaseCRC32("D:/YMIR WORK/TREE/OAK.SPT", 24); + TEST_CHECK(crc_lower == crc_upper); +} + +void test_lzo_and_mcoz() { + std::cout << "[Test] LZO & MCOZ..." << std::endl; + std::string sample = "Metin2 high performance LZO decompression verification string 1234567890! " + "SpeedTree shaders and GR2 meshes are packed tightly."; + for (int i = 0; i < 5; ++i) { + sample += sample; + } + + std::span input(reinterpret_cast(sample.data()), sample.size()); + + // 1. Raw LZO + std::vector comp; + TEST_CHECK(eterpack::LZO::instance().raw_compress(input.data(), input.size(), comp)); + TEST_CHECK(comp.size() < input.size()); + + std::vector decomp(input.size()); + TEST_CHECK(eterpack::LZO::instance().raw_decompress(comp.data(), comp.size(), decomp.data(), decomp.size())); + TEST_CHECK(std::memcmp(input.data(), decomp.data(), input.size()) == 0); + + // 2. MCOZ Plain + std::vector mcoz_plain; + TEST_CHECK(eterpack::LZO::instance().compress_mcoz(input, mcoz_plain, nullptr)); + std::vector mcoz_plain_out; + TEST_CHECK(eterpack::LZO::instance().decompress_mcoz(mcoz_plain, mcoz_plain_out, nullptr)); + TEST_CHECK(mcoz_plain_out.size() == input.size()); + TEST_CHECK(std::memcmp(input.data(), mcoz_plain_out.data(), input.size()) == 0); + + // 3. MCOZ Encrypted with default key + std::vector mcoz_enc; + TEST_CHECK(eterpack::LZO::instance().compress_mcoz(input, mcoz_enc, eterpack::DEFAULT_ETERPACK_KEY)); + std::vector mcoz_enc_out; + TEST_CHECK(eterpack::LZO::instance().decompress_mcoz(mcoz_enc, mcoz_enc_out, eterpack::DEFAULT_ETERPACK_KEY)); + TEST_CHECK(mcoz_enc_out.size() == input.size()); + TEST_CHECK(std::memcmp(input.data(), mcoz_enc_out.data(), input.size()) == 0); +} + +void test_archive_and_vfs() { + std::cout << "[Test] Archive Creation & VFS..." << std::endl; + std::string temp_dir = "test_pack_tmp"; + fs::create_directories(temp_dir); + + std::vector>> files; + std::string file1_data = "Hello from SpeedTree texture diffuse.dds"; + std::string file2_data = "Gr2 animation motion data frame buffer bytes"; + std::string file3_data = "ItemProto binary table content"; + + files.emplace_back("d:/ymir work/tree/texture.dds", + std::vector(file1_data.begin(), file1_data.end())); + files.emplace_back("d:/ymir work/pc/warrior/run.msa", + std::vector(file2_data.begin(), file2_data.end())); + files.emplace_back("locale/item_proto", + std::vector(file3_data.begin(), file3_data.end())); + + std::string base_path = temp_dir + "/test_pack"; + bool created = eterpack::EterPackArchive::create_archive( + base_path, files, true, eterpack::DEFAULT_ETERPACK_KEY, + eterpack::CompressionType::Compress, eterpack::DEFAULT_SECURITY_KEY + ); + TEST_CHECK(created); + + // Open and extract single archive + eterpack::EterPackArchive archive; + TEST_CHECK(archive.open(base_path)); + TEST_CHECK(archive.get_entry_count() == 3); + TEST_CHECK(archive.has_file("d:/ymir work/tree/texture.dds")); + TEST_CHECK(archive.has_file("d:/ymir work/pc/warrior/run.msa")); + TEST_CHECK(archive.has_file("locale/item_proto")); + + std::vector out1; + TEST_CHECK(archive.extract("d:/ymir work/tree/texture.dds", out1)); + TEST_CHECK(std::string(out1.begin(), out1.end()) == file1_data); + + std::vector out2; + TEST_CHECK(archive.extract("d:/ymir work/pc/warrior/run.msa", out2)); + TEST_CHECK(std::string(out2.begin(), out2.end()) == file2_data); + + // Mount in VFS + eterpack::EterPackVFS vfs; + TEST_CHECK(vfs.mount(base_path)); + TEST_CHECK(vfs.exists("d:/ymir work/tree/texture.dds")); + TEST_CHECK(vfs.exists("D:/Ymir Work/Tree/Texture.dds")); // Case insensitive check + std::vector vfs_out; + TEST_CHECK(vfs.read_file("d:/ymir work/tree/texture.dds", vfs_out)); + TEST_CHECK(vfs_out == out1); + + // Clean up + archive.close(); + fs::remove_all(temp_dir); +} + +void test_real_client_pack_if_present() { + std::cout << "[Test] Real 40250 Client/pack root check..." << std::endl; + std::vector candidates = { + "../../../metin2-client/Client/pack/root", + "../../metin2-client/Client/pack/root", + "metin2-client/Client/pack/root", + "/Users/shen/Work/Code/Metin2/metin2-client/Client/pack/root" + }; + + std::string root_path; + for (const auto& c : candidates) { + if (fs::exists(c + ".eix") && fs::exists(c + ".epk")) { + root_path = c; + break; + } + } + + if (!root_path.empty()) { + eterpack::EterPackArchive real_archive; + bool ok = real_archive.open(root_path); + TEST_CHECK(ok); + if (ok) { + std::cout << " -> Successfully opened real root.eix/.epk with " + << real_archive.get_entry_count() << " entries!" << std::endl; + TEST_CHECK(real_archive.get_entry_count() > 0); + + // Test extracting an item from root.epk + std::vector proto_bytes; + if (real_archive.has_file("20110915_ymir_item_proto")) { + bool ext = real_archive.extract("20110915_ymir_item_proto", proto_bytes); + TEST_CHECK(ext); + std::cout << " -> Extracted 20110915_ymir_item_proto, size = " + << proto_bytes.size() << " bytes" << std::endl; + TEST_CHECK(proto_bytes.size() > 1000); + } + } + } else { + std::cout << " -> (Skipping real pack check: path not found)" << std::endl; + } +} + +int main() { + std::cout << "=== Running eterpack Unit Tests ===" << std::endl; + test_tea(); + test_crc32(); + test_lzo_and_mcoz(); + test_archive_and_vfs(); + test_real_client_pack_if_present(); + + if (g_failures == 0) { + std::cout << "=== ALL eterpack TESTS PASSED ===" << std::endl; + return 0; + } else { + std::cerr << "=== " << g_failures << " eterpack TESTS FAILED ===" << std::endl; + return 1; + } +} diff --git a/examples/CMakeLists.txt b/examples/CMakeLists.txt new file mode 100644 index 0000000..06a12de --- /dev/null +++ b/examples/CMakeLists.txt @@ -0,0 +1,15 @@ +add_executable(sdk_demo tree_and_character_demo.cpp) +target_link_libraries(sdk_demo PRIVATE + speedtree + libgr2_render + eterpack + proto + effect + terrain + character + property + texture + network + spatial + ui_core +) diff --git a/examples/tree_and_character_demo.cpp b/examples/tree_and_character_demo.cpp new file mode 100644 index 0000000..41f38c0 --- /dev/null +++ b/examples/tree_and_character_demo.cpp @@ -0,0 +1,239 @@ +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +int main() { + std::cout << "====================================================================\n"; + std::cout << " Metin2 Cross-Platform Independent SDK Suite (Full Verification)\n"; + std::cout << "====================================================================\n\n"; + + // 1. SpeedTree High-Fidelity Tree & Wind Dynamics + std::cout << "[1] SpeedTree Procedural Foliage Generation & Wind Physics\n"; + auto tree = speedtree::SpeedTreeModel::CreateProcedural( + "AncientOak", 1200.0f, "ymir work/tree/oak_bark.dds", "ymir work/tree/oak_leaf.dds" + ); + + if (tree) { + std::cout << " Tree Created: " << tree->GetName() << "\n"; + std::cout << " Height: " << tree->GetHeight() << " units, Radius: " << tree->GetRadius() << " units\n"; + + const auto& trunk = tree->GetTrunkMesh(); + const auto& canopy = tree->GetLeafMesh(); + std::cout << " Trunk Geometry: " << trunk.vertices.size() << " vertices, " + << trunk.indices.size() / 3 << " triangles\n"; + std::cout << " Canopy Foliage: " << canopy.vertices.size() << " vertices, " + << canopy.indices.size() / 3 << " triangles\n"; + + speedtree::WindParameters wind; + wind.strength = 1.2f; // Gusty breeze + wind.direction[0] = 1.0f; + wind.direction[1] = 0.0f; + wind.direction[2] = 0.5f; + + std::vector anim_pos; + std::vector anim_norm; + tree->EvaluateCpuTransformedVertices(canopy, anim_pos, anim_norm, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, wind); + if (!anim_pos.empty()) { + std::cout << " CPU Evaluated Transformed Canopy Vertices: " << anim_pos.size() / 3 << " points\n"; + } + std::string shader_code = speedtree::GetFoliageVertexShaderGLSL(); + std::cout << " Shader Code Definition: " << shader_code.substr(0, 42) << "...\n\n"; + } + + // 2. Granny2 Mesh & Skeleton Render Instance SDK + std::cout << "[2] Granny2 (GR2) Skeletal Animation & Attachment SDK\n"; + gr2_render::Gr2MeshDraw draw_cmd; + draw_cmd.world[0] = 1.0f; draw_cmd.world[5] = 1.0f; draw_cmd.world[10] = 1.0f; draw_cmd.world[15] = 1.0f; + draw_cmd.texture0 = "d:/ymir work/pc/warrior/warrior_novice.dds"; + std::cout << " Gr2MeshDraw Standard Pipeline Unit: AlphaTest=" << draw_cmd.alpha_test + << ", DoubleSided=" << draw_cmd.double_sided << ", Tex=" << draw_cmd.texture0 << "\n\n"; + + // 3. EterPack VFS + std::cout << "[3] EterPack Virtual File System (TEA + MiniLZO)\n"; + uint32_t tea_key[4] = { 0x12345678, 0x9abcdef0, 0x0fedcba9, 0x87654321 }; + std::string test_data = "SpeedTree & Metin2 CrossPlatform VFS TEA Test Data!!"; + std::span data_span(reinterpret_cast(test_data.data()), test_data.size()); + auto encrypted = eterpack::tea_encrypt_bytes(data_span, tea_key); + auto decrypted = eterpack::tea_decrypt_bytes(encrypted, tea_key); + std::string recovered(reinterpret_cast(decrypted.data()), test_data.size()); + std::cout << " EterPack TEA Encrypt/Decrypt Verified: " << recovered << "\n\n"; + + // 4. Proto SDK + std::cout << "[4] Proto SDK (Item/Mob Binary & Alignment)\n"; + proto::ItemProtoRecord item_sword{}; + item_sword.vnum = 10; + item_sword.name = "Sword+0"; + item_sword.type = 1; + item_sword.size = 2; + std::cout << " Item Proto Loaded: Vnum=" << item_sword.vnum << ", Name=" << item_sword.name + << ", Inventory Size=" << (int)item_sword.size << " grid slots.\n\n"; + + // 5. Effect & Time Events SDK + std::cout << "[5] Effect & Dynamic Particle SDK (MSE / Time Curve Interpolation)\n"; + std::vector events = { {0.0f, 10.0f}, {1.0f, 20.0f}, {3.0f, 40.0f} }; + float val = effect::interpolate_time_event(events, 0.5f); + std::cout << " Time Event Keyframe Interpolated at t=0.5s: " << val << " (Expected 15.0)\n\n"; + + // 6. Terrain & Water SDK + std::cout << "[6] Terrain & Water SDK (Heightmap Sampling & Water Simulation)\n"; + metin2::terrain::TerrainHeightmap terrain_map; + std::vector fake_heights(131 * 131, 2000); // flat 20.00m + fake_heights[65 * 131 + 65] = 5000; // hill peak 50.00m + terrain_map.LoadFromBuffer(fake_heights.data(), fake_heights.size()); + float sample_h = terrain_map.GetHeightAtWorld(12800.0f * 0.5f, 12800.0f * 0.5f); + std::cout << " - Sampled World Center Height: " << sample_h << " meters (Hill Peak=50m)\n"; + + metin2::terrain::WaterManager water; + water.GenerateProceduralWater(10.0f, -1000.0f, 1000.0f, -1000.0f, 1000.0f, 60.0f); + auto water_cmd = water.BuildDrawCommand(0.5f); + std::cout << " - Water Dynamic Mesh: " << water_cmd.positions.size() / 3 << " vertices, " + << water_cmd.indices.size() / 3 << " triangles\n\n"; + + // 7. Character & MSM SDK + std::cout << "[7] Character & MSM SDK (Actor Assembly & Socket Calculation)\n"; + const std::string msm_text = + "ScriptType RaceDataFile\n" + "BaseActorData\n" + "{\n" + " BaseModelFileName \"d:/ymir work/pc/warrior/warrior_novice.gr2\"\n" + "}\n" + "Group ShapeData\n" + "{\n" + " ShapeDataCount 1\n" + " Group ShapeData00\n" + " {\n" + " ShapeIndex 0\n" + " Model \"warrior_novice.gr2\"\n" + " SourceSkin \"warrior_novice.dds\"\n" + " TargetSkin \"warrior_novice_blue.dds\"\n" + " }\n" + "}\n"; + auto race = std::make_shared(0); + race->LoadMsmFromString(msm_text); + metin2::character::CharacterAssembly actor(race); + actor.SetArmorShape(0); + actor.SetWeapon(metin2::character::PART_WEAPON, "d:/ymir work/weapon/sword.gr2"); + std::cout << " - Actor Assembled: Parts=" << actor.GetAssembledParts().size() << ", ArmorShape=0\n\n"; + + + std::cout << "[8] Property & Object SDK (YPRT & OBB SAT Collision)\n"; + const std::string prb_text = + "YPRT\n" + "12345678\n" + "buildingfile \"d:/ymir work/zone/temple.gr2\"\n" + "propertyname \"ancient_temple\"\n" + "propertytype \"Building\"\n"; + metin2::property::PropertyManager prop_mgr; + prop_mgr.RegisterFromMemory("zone/temple.prb", prb_text.data(), prb_text.size()); + auto temple_prop = prop_mgr.GetByCRC(12345678); + std::cout << " - YPRT Property Registered: " << (temple_prop ? temple_prop->GetData().property_name : "None") << "\n"; + + metin2::property::OrientedBoundingBox temple_obb; + temple_obb.center[0] = 500.0f; temple_obb.center[2] = 500.0f; + temple_obb.half_extents[0] = 100.0f; temple_obb.half_extents[2] = 100.0f; + float push_nx = 0.0f, push_nz = 0.0f, pen_dist = 0.0f; + temple_obb.GetPenetrationAndNormal(590.0f, 500.0f, 20.0f, push_nx, push_nz, pen_dist); + std::cout << " - OBB Collision Pushout: Penetration=" << pen_dist << " units, Normal=(" + << push_nx << ", " << push_nz << ")\n\n"; + + // 9. Texture & SubImage SDK + std::cout << "[9] Texture & SubImage SDK (DXT Soft-Decoder & 9-Slice Mesh)\n"; + const std::string sub_text = + "title subImage\n" + "image \"d:/ymir work/ui/public.dds\"\n" + "left 0\n" + "top 0\n" + "right 64\n" + "bottom 64\n"; + metin2::texture::SubImage sub_img; + if (sub_img.LoadFromString(sub_text)) { + auto uv = sub_img.ComputeUV(256, 256); + auto mesh = sub_img.BuildNineSliceMesh(0.0f, 0.0f, 300.0f, 150.0f, 16.0f, 16.0f, 16.0f, 16.0f, 256, 256); + std::cout << " - SubImage UV rect: (" << uv.u0 << ", " << uv.v0 << ") to (" << uv.u1 << ", " << uv.v1 << ")\n"; + std::cout << " - 9-Slice UI Window Mesh: " << mesh.vertices.size() << " vertices, " + << mesh.indices.size() / 3 << " triangles\n\n"; + } + + // 10. Network Protocol & FSM SDK + std::cout << "[10] Network Protocol & State Machine SDK (Phase FSM + Rolling Key + Event Dispatch)\n"; + metin2::network::NetworkClient net_client; + net_client.SetPhase(metin2::network::ConnectionPhase::Handshake); + std::cout << " - Connection State: " << net_client.GetPhaseName() << "\n"; + + // Simulate server Handshake + std::vector hs_packet = { metin2::network::HEADER_GC_HANDSHAKE, 0x78, 0x56, 0x34, 0x12, 0, 0, 0, 0 }; + net_client.SetOnHandshake([](uint32_t s_time) { + std::cout << " - Handshake Synchronized! ServerTime=" << s_time << "\n"; + }); + net_client.PushReceivedData(hs_packet.data(), hs_packet.size()); + net_client.SetPhase(metin2::network::ConnectionPhase::Auth); + net_client.SendLogin("HeroPlayer", "Password123"); + auto login_bytes = net_client.PopSendData(); + std::cout << " - Sent Encrypted Login Packet: " << login_bytes.size() << " bytes\n\n"; + + // 11. Spatial Loose Octree & Frustum Culling SDK + std::cout << "[11] Spatial Loose Octree & Frustum Culling SDK\n"; + metin2::spatial::AABB scene_bounds(metin2::spatial::Vector3(-50000, -5000, -50000), metin2::spatial::Vector3(50000, 10000, 50000)); + metin2::spatial::LooseOctree octree(scene_bounds, 2.0f); + + // Register World Objects + octree.Insert(1001, metin2::spatial::SpatialObjectType::Building, metin2::spatial::AABB(metin2::spatial::Vector3(-200, 0, 500), metin2::spatial::Vector3(200, 400, 900))); + octree.Insert(2001, metin2::spatial::SpatialObjectType::Tree, metin2::spatial::AABB(metin2::spatial::Vector3(-50, 0, 300), metin2::spatial::Vector3(50, 600, 400))); + octree.Insert(3001, metin2::spatial::SpatialObjectType::Monster, metin2::spatial::AABB(metin2::spatial::Vector3(-30, 0, 150), metin2::spatial::Vector3(30, 100, 210))); + octree.Insert(4001, metin2::spatial::SpatialObjectType::Tree, metin2::spatial::AABB(metin2::spatial::Vector3(0, 0, -500), metin2::spatial::Vector3(50, 600, -400))); // Behind camera + + // Camera at (0, 50, 0) looking along +Z + metin2::spatial::Vector3 cam_eye(0.0f, 50.0f, 0.0f); + auto frustum = metin2::spatial::Frustum::CreatePerspective(cam_eye, metin2::spatial::Vector3(0, 0, 1), metin2::spatial::Vector3(0, 1, 0), 60.0f, 16.0f / 9.0f, 1.0f, 3000.0f); + auto visible_objs = octree.QueryFrustum(frustum, cam_eye, true); + + std::cout << " - Registered Scene Objects: " << octree.Size() << "\n"; + std::cout << " - Frustum Query Visible Objects (Sorted by Distance): " << visible_objs.size() << "\n"; + for (const auto& vis : visible_objs) { + std::cout << " * Visible ID=" << vis.id << " (Type=" << (int)vis.type << "), Distance=" << (int)vis.distance << " units\n"; + } + std::cout << "\n"; + + // 12. UI Core Reactive Node Tree & Grid SDK + std::cout << "[12] UI Core Reactive Node Tree & Inventory Grid SDK (No Python Dependency)\n"; + metin2::ui_core::UIManager ui_mgr(1920.0f, 1080.0f); + auto inv_window = std::make_shared(); + inv_window->SetName("Inventory"); + inv_window->SetSize(220.0f, 340.0f); + inv_window->SetAnchor(metin2::ui_core::UIAnchor::Center); + + auto grid = std::make_shared(5, 9, 32.0f, 2.0f); + grid->SetPosition(10.0f, 30.0f); + grid->SetItemAt(0, 0, 10, 1); // Sword in (0, 0) + grid->SetItemAt(2, 4, 50300, 5); // Skill book in (2, 4) + + inv_window->AddChild(grid); + ui_mgr.AddElement(inv_window); + ui_mgr.UpdateLayout(); + + auto ui_batches = ui_mgr.GenerateRenderBatches(); + std::cout << " - Root UI Hierarchy Layout Updated (Window Global Rect: " + << (int)inv_window->GetGlobalRect().x << ", " << (int)inv_window->GetGlobalRect().y << ")\n"; + std::cout << " - Inventory Slot (0,0) HasItem: " << grid->GetSlot(0, 0)->HasItem() + << ", Vnum=" << grid->GetSlot(0, 0)->GetItemVnum() << "\n"; + std::cout << " - UI Render Batches Built: " << ui_batches.size() << " draw calls\n\n"; + + std::cout << "====================================================================\n"; + std::cout << " All 12 Standalone Metin2 C++20 SDKs Operational and Verified!\n"; + std::cout << "====================================================================\n"; + return 0; +} diff --git a/gr2/CMakeLists.txt b/gr2/CMakeLists.txt new file mode 100644 index 0000000..491b267 --- /dev/null +++ b/gr2/CMakeLists.txt @@ -0,0 +1,62 @@ +cmake_minimum_required(VERSION 3.20) +project(libgr2 LANGUAGES C CXX) + +set(CMAKE_CXX_STANDARD 20) +set(CMAKE_CXX_STANDARD_REQUIRED ON) + +# libgr2 —— gr2 v6 只读读取器(M0)。零第三方依赖。 +add_library(libgr2 STATIC + src/gr2_file.cpp # T1 header + section table + fixup + src/gr2_decompress.cpp # T2 section 解压分派 + src/oodle1.c # T2 Granny Oodle1 解码(端口自泄露 SDK) + src/bitknit2.cpp # T2 Granny BitKnit2 解码(MIT,BG3ModStudio) + src/gr2_typetree.cpp # T3 自描述类型树遍历 + src/gr2_fileinfo.cpp # T4 FileInfo 汇总 + src/gr2_skeleton.cpp # T5 骨架 + bind pose 自洽检查 + src/gr2_mesh.cpp # T6 顶点 / 索引 / 三角组 / BoneBindings + src/gr2_anim.cpp # T7a/T7b 曲线分类 + 解码子集 + src/gr2_material.cpp # 材质视图(附加):root.Materials → 贴图文件名 +) +add_library(mt::libgr2 ALIAS libgr2) +add_library(gr2::libgr2 ALIAS libgr2) + +target_include_directories(libgr2 + PUBLIC $ + PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/src) + +target_compile_features(libgr2 PUBLIC cxx_std_20) + +# libgr2_render —— 动画解算、骨骼蒙皮与挂载/换装渲染接口 +add_library(libgr2_render STATIC + src_render/gr2_model_instance.cpp +) +add_library(mt::libgr2_render ALIAS libgr2_render) +add_library(gr2::libgr2_render ALIAS libgr2_render) + +target_include_directories(libgr2_render + PUBLIC $) + +target_link_libraries(libgr2_render PUBLIC libgr2) +target_compile_features(libgr2_render PUBLIC cxx_std_20) + +option(GR2_BUILD_TESTS "Build GR2 SDK tests" ON) +if(GR2_BUILD_TESTS) + enable_testing() + if(EXISTS ${CMAKE_CURRENT_SOURCE_DIR}/tests/loader_errors.cpp) + add_executable(libgr2_loader_errors_test tests/loader_errors.cpp) + target_link_libraries(libgr2_loader_errors_test PRIVATE libgr2) + add_test(NAME libgr2.loader_errors COMMAND libgr2_loader_errors_test) + endif() + + if(EXISTS ${CMAKE_CURRENT_SOURCE_DIR}/tests/animation.cpp) + add_executable(libgr2_animation_test tests/animation.cpp) + target_link_libraries(libgr2_animation_test PRIVATE libgr2) + add_test(NAME libgr2.animation COMMAND libgr2_animation_test) + endif() + + if(EXISTS ${CMAKE_CURRENT_SOURCE_DIR}/tests/gr2_render_test.cpp) + add_executable(libgr2_render_test tests/gr2_render_test.cpp) + target_link_libraries(libgr2_render_test PRIVATE libgr2_render) + add_test(NAME libgr2.render_test COMMAND libgr2_render_test) + endif() +endif() diff --git a/gr2/README.md b/gr2/README.md new file mode 100644 index 0000000..ecdc4a4 --- /dev/null +++ b/gr2/README.md @@ -0,0 +1,46 @@ +# libgr2 + +自研 gr2 v6/v7 **只读**读取器。零第三方依赖。施工文档 [`../docs/reference/steps/M0-gr2-reader.md`](../docs/reference/steps/M0-gr2-reader.md)。 + +## 能做什么 + +- 容器:magic / header / section / pointer-fixup(懒解引用,不物化 32 位指针) +- section 解压:Oodle1(`oodle1.c`)、BitKnit2(`bitknit2.cpp`,Granny 2.11 `Format==4`,含压缩的 fixup 表) +- 32 / 64 位 little-endian(64 位只是 section 数据里的指针宽 8 字节;header / section 表 / fixup 同 32 位) +- 动画曲线:老式 `OldCurveType`(Granny 2.4)+ Granny 2.6+ `curve2` 的 19 种 `CurveData*` 变体(AVA2 语料出现的 17 种全覆盖)(常量 / 关键帧 / `K32f` / `K16u` / `K8u` 量化 / `D4n` 压缩四元数),统一解到 `Curve` 走 B 样条求值 +- 自描述类型树遍历(不硬编码 struct 布局) +- `FileInfo`:skeletons / meshes / materials / textures / models / animations +- 骨架 + `granny_transform` → 4x4 组合(`BuildCompositeTransform4x4` 语义) +- 蒙皮网格:顶点(按顶点格式自描述解)/ 索引 / 三角组 / BoneBindings(多 skeleton 取最优匹配) +- 材质:`granny_material` 链(直接 `.Texture` 或递归 `.Maps[].Map`)→ `granny_texture.FromFileName`; + `Mesh.material_textures` 与 `MaterialBindings` 平行,`tri_group.material_index` 索引它 +- 动画曲线(`OldCurveType` B 样条,degree 0/1/2)解码 + `gr2::sample_pose`(跨文件按骨骼名 retarget) + +## 验证 + +- 全量 9166 个 Metin2 `.gr2`:**0 崩溃、0 非退化谓词失败**(`tools/gr2fuzz`) +- **对拍真 Granny 2.9.12**:骨骼世界矩阵 ≤ 4.6e-5、蒙皮顶点 ≤ 6.5e-5(`tools/oracle_diff`,`tools/granny-oracle/m2-numeric.json`,23 用例含 v7 / 双 root / 刚体 / 多动画帧) +- 坏输入(空 / 错 magic / 截断 / 越界索引)一律干净报错,不崩 + +## 明确不做(Metin2 语料里 0 出现;要「任意 gr2」才需要) + +| 缺口 | 现状 | 补的成本 | +|---|---|---| +| **writer** | 无(设计上只读)| 大,PoC 不需要 | +| Oodle0 解压(`Format==1`)| `decompress_status=1`,不崩 | 中,同族算法变体 | +| BitKnit v1 解压(`Format==3`)| `decompress_status=3`,不崩(AVA2 语料 0 个;`Format==4` 是 BitKnit2,已支持)| 中,与 BitKnit2 同族 | +| B 样条 degree ≥ 3 | `eval` 退化到 degree 2 | 小,加 `CubicCoefficients` | +| big-endian gr2 | `load` 直接拒(`big-endian Granny files not supported`;AVA2 语料 0 个)| 中,全部读取加字节序翻转 | +| 多 skeleton 文件里刚体挂件的 skeleton 归属 | mesh binding 取「悬空最少」的 skeleton;`oracle_diff` 对这种 mesh 会误判(不是 libgr2 的问题)| 需要 FileInfo 暴露 per-model skeleton 索引 | + +## ⚠ 许可 + +`src/bitknit2.cpp` 依据 MIT 许可的 BG3ModStudio `LibLS/Bitknit2Decompressor.cpp`(© 2025 Thomas A. Rieck,https://github.com/trieck/BG3ModStudio)重写,并对照 powzix/ooz `bitknit.cpp`;不含 RAD 代码,可随 MIT 声明发布。 + + +`src/oodle1.c` 是从泄露的 Granny SDK **直接端口**的解码路径(约 450 行)。 + +- **内部研究 / 不发布 / 非商用**:可用(和「拿泄露 SDK 当字节级规格」同一风险类别,全项目都这么做)。 +- **任何对外发布 / 商用**:必须 clean-room 重写(照公开的「granny2 Oodle1」算法描述从零写,不看这份端口)。 + +其余代码(容器 / 类型树 / 骨架 / 网格 / 曲线 / 姿势)是照泄露 SDK **头文件的 struct 定义和公式注释**自己写的,不是复制实现。 diff --git a/gr2/include/gr2/gr2.h b/gr2/include/gr2/gr2.h new file mode 100644 index 0000000..796b25b --- /dev/null +++ b/gr2/include/gr2/gr2.h @@ -0,0 +1,106 @@ +// libgr2 —— gr2 v6 只读读取器(demo 子集)。 +// 施工文档:docs/reference/steps/M0-gr2-reader.md +#pragma once +#include "types.h" +#include +#include +#include +#include +#include +#include +#include + +namespace gr2 { + +enum class Magic { Unknown, Bit32_LE, Bit32_BE, Bit64_LE, Bit64_BE }; + +struct LoadError { + std::string stage; // "header" / "section" / "typetree" / "fileinfo" / ... + std::string message; +}; + +// T3:通用类型树遍历(gr2dump 打印成员用;不硬编码 struct 布局) +struct MemberDump { std::string name; int member_type; int array_width; }; +class File; +std::vector dump_root_members(const File&); + +// 材质视图(类型树遍历 root.Materials → granny_material)。 +// 只读文件名,不解码贴图。diffuse_texture 取 Usage 含 "diffuse" 的 map 的 +// 贴图,退而取第一张;all_textures 是从该材质可达的全部 FromFileName。 +struct MaterialInfo { + std::string name; + std::string diffuse_texture; + std::vector all_textures; + // Metin2/EterGrnLib 渲染态推断(gr2 不带 D3DRS,靠名字 + map 数 + ExtendedData): + int map_count = 0; // granny_material.MapCount(可达子材质的 Texture 数) + bool alpha_blend = false;// Name 以 "Blend" 开头且 map_count>1(EterGrnLib Material.cpp:233) + bool two_sided = false; // 名字含 2side/twoside/double/leaf/tree/ivy/fence(ExtendedData "Two-sided" 的近似) +}; +std::vector dump_materials(const File&); + +// 已解析、fixup 后的文件。析构释放所有 section 缓冲。 +class File { +public: + static std::optional load(const uint8_t* bytes, size_t len, LoadError* err); + static std::optional load_path(const std::string& path, LoadError* err); + + // T1 + Magic magic() const { return magic_; } + uint32_t format_version()const { return version_; } // 期望 6 + uint32_t total_size() const { return total_size_; } + const std::vector& sections() const { return sections_; } + + // T4 —— 完整汇总(内部会按需触发 T5/T6/T7a) + const FileInfo& file_info() const { return info_; } + + // 展开后的 section 字节(T2 产出)。空 section 返回空 span。调试 / 校验用。 + std::span section_bytes(size_t i) const; + + // T5 —— bind pose 自洽检查(不依赖 oracle)。返回 max|world_bind·invBind − I| + // 阈值策略见 M0-gr2-reader.md T5(noise_floor 前用 1e-3) + double bind_pose_self_check(int skeleton = 0) const; + + // M2 便捷封装(同文件内的 skeleton + animation)。跨文件(model gr2 + anim gr2) + // 用自由函数 gr2::sample_pose(skeleton, animation, t, ...)。anim/skeleton 是 file_info() 索引。 + bool sample_pose(int anim, float t, int skeleton, + std::vector& world_pose, std::vector& skin) const; + bool bind_pose(int skeleton, std::vector& world_pose, std::vector& skin) const; + +private: + File() = default; + Magic magic_ = Magic::Unknown; + uint32_t version_ = 0; + uint32_t total_size_ = 0; + std::vector sections_; + FileInfo info_; + // 内部:section 缓冲、root object 指针、类型树 —— 放 .cpp 的 Impl + struct Impl; + std::shared_ptr impl_; + + friend std::vector dump_root_members(const File&); + friend std::vector dump_materials(const File&); +}; + +// ── M2:姿势采样(model 的 skeleton + anim 的 tracks 可来自不同 gr2)────── +// Granny 语义、行主序、平移在 elem 12..14: +// world[i] = Composite(local[i]) · (parent<0 ? root_offset : world[parent]) +// skin[i] = sk.bones[i].inverse_world · world[i] +// tracks 按骨骼名匹配 sk;无匹配的骨骼用 sk 的 bind LocalTransform。 +// +// root_offset = GrannyBuildWorldPose 的 Offset4x4。默认(nullptr)用 +// sk.initial_placement —— 与 tools/granny-oracle/oracle.c 的 GrannyGetModelInitialPlacement4x4 +// 一致,是 bind pose 与 inverse_world 自洽所要求的那一个(bind_pose 只用这一种)。 +// 渲染动画时客户端另有取法:EterGrnLib 对 Offset4x4 传身位矩阵而不是导出期的 +// InitialPlacement,而 Metin2 的 .gr2 动画 track 里根骨的位移已经含了骨盆高度, +// 所以再乘一次 InitialPlacement 会把整个人抬高一个骨盆高。要那条语义就显式传 +// 单位阵(见 extension/src/metin2_anim.cpp 与 test/rendering/README.md 的实测)。 +void sample_pose(const Skeleton& sk, const Animation& an, float t, + std::vector& world, std::vector& skin, + const Mat4* root_offset = nullptr); +void bind_pose(const Skeleton& sk, std::vector& world, std::vector& skin); + +// 打印辅助 +const char* magic_name(Magic); +const char* compression_name(uint32_t section_format); // 0=none 1=Oodle0 2=Oodle1 + +} // namespace gr2 diff --git a/gr2/include/gr2/types.h b/gr2/include/gr2/types.h new file mode 100644 index 0000000..ef60d2d --- /dev/null +++ b/gr2/include/gr2/types.h @@ -0,0 +1,203 @@ +// libgr2 —— 对外 POD 视图。不泄露内部指针 / SDK 类型。 +// 规格来源:MobileSource/Cross Platform/Granny-3D-SDK-main/source/ +// granny_file_format.h / granny_data_type_definition.h / granny_transform.h / granny_file_info.h +#pragma once +#include +#include +#include +#include +#include + +namespace gr2 { + +using Mat4 = std::array; // 行主序,Granny 原生。坐标约定见 docs/reference/steps/M0-gr2-reader.md「约定」 + +// granny_transform(SRT 分量原样;Flags: 1=HasPosition 2=HasOrientation 4=HasScaleShear)。 +// 动画混合要在分量上做(GrannySampleModelAnimations 累加 SRT 再归一),不能在 4x4 上做。 +struct Transform { + uint32_t flags = 0; + float position[3] = {0, 0, 0}; + float orientation[4] = {0, 0, 0, 1}; // x,y,z,w + float scale_shear[9] = {1,0,0, 0,1,0, 0,0,1}; // 行主序 3x3 +}; +// BuildCompositeTransform4x4:上 3x3 = transpose(R3·SS3),平移在 elem 12..14。 +Mat4 compose(const Transform& t); + +// ── 骨架 ────────────────────────────────────────────────────────────── +struct Bone { + std::string name; + int32_t parent = -1; // < 自身索引,或 -1 = 根 + Mat4 local_transform{}; // granny_transform SRT → 4x4(组合顺序照 granny_transform.cpp) + Mat4 inverse_world{}; // InverseWorld4x4,来自文件 + uint32_t lt_flags = 0; // granny_transform.Flags:哪部分非单位 + Transform local; // LocalTransform 的 SRT 分量(local_transform = compose(local)) +}; + +struct Skeleton { + std::vector bones; + Mat4 initial_placement{1,0,0,0, 0,1,0,0, 0,0,1,0, 0,0,0,1}; // 绑定它的 model 的 InitialPlacement +}; + +// ── 网格 ────────────────────────────────────────────────────────────── +enum class VertexKind { PNT332, PNT3322, PNT332_Skinned, PNT3322_Skinned, Unknown }; + +struct Vertex { // demo 统一打包结构 + float pos[3]; + float normal[3]; + float uv0[2]; + float uv1[2]; // PNT3322 才有效 + uint8_t bone_index[4] = {0}; // *_Skinned 才有效 + uint8_t bone_weight[4] = {0}; // 归一 u8 +}; + +struct TriGroup { + int32_t material_index; + int32_t tri_first; // 三角序号 + int32_t tri_count; +}; + +// 顶点类型的一个成员(granny_data_type_definition 的平铺子集;type = granny_member_type 序数)。 +struct VertexMember { + std::string name; + int32_t type = 0; + int32_t array_width = 0; // 0 => 1 + uint32_t offset = 0; // 在顶点里的字节偏移(打包) +}; + +struct Mesh { + struct BoneBounds { + float min[3] = {}, max[3] = {}; + bool valid = false; + }; + std::string name; + VertexKind kind = VertexKind::Unknown; + std::vector vertices; + std::vector indices; // 三角形列表 + std::vector tri_groups; + std::vector bone_bindings; // mesh 局部骨骼槽 → skeleton 骨骼索引 + std::vector bone_bounds; // Parallel source BoneBindings OBBMin/OBBMax. + uint32_t source_bone_weight_slots = 0; // 顶点类型声明值;审计 >4/8 权重 + uint32_t source_bone_index_slots = 0; // packed UInt32 记为 4 + // 与 granny_mesh.MaterialBindings 平行:每项 = 解析出的漫反射贴图文件名 + // (granny_texture.FromFileName 原样,通常是 "D:\Ymir Work\...\x.dds";空 = 未解析)。 + // tri_groups[i].material_index 索引本表。 + std::vector material_textures; + bool rigid = false; // GrannyMeshIsRigid + std::vector bone_binding_names; // granny_bone_binding.BoneName,与 bone_bounds 平行 + std::vector material_bindings; // granny_mesh.MaterialBindings[i].Material → FileInfo::materials 索引(-1 = 空) + // 原始顶点:文件声明的顶点类型 + 按它打包的字节(Granny 运行时按名字做布局转换用) + std::vector vertex_members; + uint32_t vertex_stride = 0; + std::vector raw_vertices; // vertices.size() * vertex_stride +}; + +// ── 动画 ────────────────────────────────────────────────────────────── +// 曲线子类型:T7a 分类。Metin2 = Granny 2.4,全是 OldCurveType(granny_curve.cpp): +// {Int32 Degree; RefToArray Knots(Real32[]); RefToArray Controls(Real32[])} +// label 形如 "Old(d=2,dim=4)"。AVA2 = Granny 2.11 的 curve2 变体 label 是去掉 +// "CurveDataHeader_" 的变体名(D4nK16uC15u、DaK32fC32f…),同样解到 Curve。 +enum class CurveFormat { Keyframes32f, /* T7a 跑 fuzz 后补齐 */ Unknown }; + +// T7b:解出的曲线(B 样条:knots 时间轴 + controls 控制点,行优先 [knot][dim]) +struct Curve { + int32_t degree = 0; + uint32_t dim = 0; // 3=vec, 4=quat, 9=3x3 scaleshear + std::vector knots; // KnotCount 个 + std::vector controls; // KnotCount * dim 个 + bool knots_sorted = true; // 升序 → eval 二分找 knot;否则按原样线性扫 + bool empty() const { return knots.empty() || dim == 0; } + // t 处求值,写 dim 个 float 到 out(identity 由调用方给)。 + void eval(float t, float* out) const; +}; + +struct TextTrackEntry { float time_stamp = 0.0f; std::string text; }; +struct TextTrack { std::string name; std::vector entries; }; + +struct BoneTrack { + std::string bone_name; + int32_t bone_index = -1; // 映射到 skeleton(未映射 = -1) + std::string pos_type = "none"; + std::string rot_type = "none"; + std::string scale_type = "none"; + Curve position; // dim 3 + Curve orientation; // dim 4(四元数 x,y,z,w) + Curve scale_shear; // dim 9(3x3)或 dim 3 + // t 处的 SRT(缺的曲线取单位分量,flags 只标出有曲线的分量)。sample_local 的 4x4 = compose(这个)。 + void sample(float t, Transform& out) const; +}; + +// Preserve group boundaries: an animation can contain an auxiliary object group before its model. +struct AnimationTrackGroup { + std::string name; + Transform initial_placement; + int32_t accumulation_flags = 0; + float loop_translation[3] = {0.0f, 0.0f, 0.0f}; + std::vector text_tracks; + size_t first_track = 0; + size_t track_count = 0; +}; + +struct Animation { + std::string name; + float duration = 0.0f; + float time_step = 0.0f; + float oversampling = 1.0f; + int32_t track_group_count = 0; + std::vector text_tracks; // TrackGroups[0].TextTracks + // TrackGroups[0].AccumulationFlags / LoopTranslation(root motion: + // 1 = AccumulationExtracted,4 = AccumulationIsVDA)。 + int32_t accumulation_flags = 0; + float loop_translation[3] = {0.0f, 0.0f, 0.0f}; + std::vector tracks; + std::vector track_groups; + // t 处每个 track 的局部 4x4(granny_transform 组合语义,行主序)。 + // out 按 tracks 顺序;bone_index 见各 track。 + void sample_local(float t, std::vector& out) const; +}; + +// 顶层 granny_material(driven by root Materials[])。name + 解析出的漫反射贴图。 +// root Materials[] 之外、只经 Maps[] / mesh MaterialBindings 可达的子材质追加在后面。 +struct MaterialMap { + std::string usage; // granny_material_map.Usage("Diffuse Color" 等) + int32_t material = -1; // FileInfo::materials 索引 +}; +struct Material { + std::string name; + std::string diffuse_texture; // granny_texture.FromFileName 原样 + std::string texture; // 本材质自己的 Texture.FromFileName(空 = 无 Texture) + std::vector maps; // granny_material.Maps + int32_t two_sided = 0; // ExtendedData 的 Int32 "Two-sided" + bool has_two_sided = false; +}; + +// granny_model:Skeleton + InitialPlacement + MeshBindings。 +struct Model { + std::string name; + int32_t skeleton = -1; // FileInfo::skeletons 索引 + Transform initial_placement; + std::vector mesh_bindings; // FileInfo::meshes 索引(-1 = 未解析) +}; + +// ── FileInfo 汇总(T4)──────────────────────────────────────────────── +struct FileInfo { + std::string from_file_name; + std::vector skeletons; + std::vector meshes; + std::vector animations; + std::vector materials; + std::vector models; + uint32_t material_count = 0; + uint32_t texture_count = 0; + uint32_t model_count = 0; +}; + +// ── section 表(T1,gr2dump --sections 用)──────────────────────────── +struct SectionInfo { + uint32_t compression; // 0=none 1/2=Oodle0/1 3=BitKnit 4=BitKnit2 + uint32_t data_size; // 压缩后 + uint32_t expanded_size; // 展开后 + uint32_t pointer_fixup_count; + int decompress_status; // 0=ok,非 0=解压失败/未实现(T2) +}; + +} // namespace gr2 diff --git a/gr2/include/gr2_render/gr2_render.h b/gr2/include/gr2_render/gr2_render.h new file mode 100644 index 0000000..fa96e4c --- /dev/null +++ b/gr2/include/gr2_render/gr2_render.h @@ -0,0 +1,117 @@ +#pragma once + +#include +#include +#include +#include +#include +#include + +namespace gr2_render { + +// Engine-agnostic 3D mesh draw data for animated/static Gr2 models +struct Gr2MeshDraw { + std::shared_ptr geometry; + bool gpu_skinning = false; + // D3D/Engine row-vector world transform matrix (translation in elements 12..14) + float world[16] = { + 1.0f, 0.0f, 0.0f, 0.0f, + 0.0f, 1.0f, 0.0f, 0.0f, + 0.0f, 0.0f, 1.0f, 0.0f, + 0.0f, 0.0f, 0.0f, 1.0f + }; + + std::string texture0; + std::string texture1; + + // Per-vertex attributes + std::vector positions; // 3 floats (x, y, z) per vertex + std::vector normals; // 3 floats (nx, ny, nz) per vertex + std::vector uv0; // 2 floats (u, v) per vertex + std::vector diffuse; // 0xAARRGGBB per vertex + std::vector indices; // Triangle indices + + // Skeletal skinning palette & vertex weights (for GPU skinning) + std::vector bone_indices; // 4 uint8 per vertex + std::vector bone_weights; // 4 floats per vertex + std::vector bone_matrices; // 16 floats per bone (palette) + + // Render states + bool alpha_test = false; + uint32_t alpha_ref = 70; + bool double_sided = false; + bool z_write = true; + bool lighting = true; +}; + +class Gr2ModelInstance { +public: + static std::unique_ptr Load(const std::string& filepath); + static std::unique_ptr LoadFromMemory(const uint8_t* data, size_t size, const std::string& name = ""); + + // Load external animation (.gr2) to animate this model + bool LoadExternalAnimation(const std::string& anim_filepath); + bool LoadExternalAnimationFromMemory(const uint8_t* data, size_t size); + float GetAnimationDuration() const; + + // Bone queries & attachments + bool GetBoneWorldTransform(const std::string& bone_name, float* out_matrix, float animation_time = -1.0f) const; + void AttachModel(const std::string& bone_name, std::shared_ptr attachment, const float* offset_matrix = nullptr); + void AttachPart(std::shared_ptr part); + void DetachAll(); + void DetachModel(const std::string& bone_name); + void DetachPart(const std::shared_ptr& part); + + void SetAttachmentAnimated(const std::string& bone_name, bool animated); + void SetAttachmentScale(const std::string& bone_name, float sx, float sy, float sz); + void SetSkin(const std::string& src_file_name, const std::string& dst_file_name); + void ClearSkins() { m_skins.clear(); } + const std::string& GetFilePath() const { return m_filepath; } + + // Build draw commands for this model and all attached components (weapons, hair, armor parts) + std::vector BuildDrawCommands(float animation_time = -1.0f, const float* world_matrix = nullptr, bool hardwareSkinning = false); + + // Build draw commands for a skinned part using an external bone palette + std::vector BuildDrawCommandsWithPalette(const std::vector& skin_matrices, + const float* world_matrix = nullptr, + const gr2::Skeleton* parent_skeleton = nullptr, bool hardwareSkinning = false); + + bool GetLocalBounds(float& minX, float& minY, float& minZ, float& maxX, float& maxY, float& maxZ) const; + + size_t GetPoseEvaluationCount() const { return m_poseEvaluations; } + const gr2::File* GetAnimationResource() const { return m_anim_file.get(); } + const gr2::File& GetFile() const { return *m_file; } + const gr2::FileInfo& GetInfo() const { return m_file->file_info(); } + +private: + struct AttachedModel { + std::string bone_name; + std::shared_ptr model; + float offset[16]; + bool animated = false; + bool scaled = false; + float scale[3] = {1.0f, 1.0f, 1.0f}; + }; + std::vector m_gpuMain, m_gpuParts; + const gr2::Skeleton* m_gpuPartParent = nullptr; + size_t m_gpuPartPaletteSize = 0; + void EvaluatePose(float animation_time) const; + mutable bool m_poseValid = false; + mutable float m_poseTime = -1; + mutable const gr2::Animation* m_poseAnimation = nullptr; + mutable std::vector m_worldPose, m_skinPose, m_trackPose, m_localPose; + mutable std::vector m_trackBones; + mutable size_t m_poseEvaluations = 0; + void ApplySkins(std::vector& draws, size_t first) const; + + std::shared_ptr m_file; + std::string m_filepath; + std::shared_ptr m_anim_file; + std::string m_anim_filepath; + + std::vector m_attached_models; + std::vector> m_attached_parts; + std::unordered_map m_skins; +}; + +} // namespace gr2_render diff --git a/gr2/src/bitknit2.cpp b/gr2/src/bitknit2.cpp new file mode 100644 index 0000000..b37df5a --- /dev/null +++ b/gr2/src/bitknit2.cpp @@ -0,0 +1,256 @@ +// Granny BitKnit2 decoder. Provenance and framing: see bitknit2.h +// (BG3ModStudio Bitknit2Decompressor.cpp, MIT, (c) 2025 Thomas A. Rieck; +// cross-checked against powzix/ooz bitknit.cpp). +#include "bitknit2.h" +#include +#include + +namespace gr2 { +namespace { + +constexpr uint16_t kMagic = 0x75B1; +constexpr size_t kQuantum = 65536; + +// Adaptive frequency model: N symbols over a 15-bit cumulative range, with a +// coarse residue->symbol lookup (residue >> SHIFT) and a rebuild every 1024 symbols. +template +struct Model { + uint16_t lookup[(0x8000u >> SHIFT) + 4]; + uint16_t cdf[N + 1]; + uint16_t freq[N]; + uint32_t adapt; + + void build_lookup() { + uint16_t* p = lookup; + for (unsigned i = 0; i < N; ++i) { + // cdf[i+1] >= 1 always holds (initial table and the smoothed rebuild + // are both strictly increasing), so the index never goes negative. + uint16_t* end = &lookup[(unsigned(cdf[i + 1]) - 1) >> SHIFT]; + do { + p[0] = p[1] = p[2] = p[3] = uint16_t(i); + p += 4; + } while (p <= end); + p = end + 1; + } + } + + void init_uniform() { + for (unsigned i = 0; i <= N; ++i) cdf[i] = uint16_t(0x8000u * i / N); + reset(); + } + + void reset() { + for (auto& f : freq) f = 1; + adapt = 1024; + build_lookup(); + } + + void rebuild(unsigned sym) { + adapt = 1024; + freq[sym] = uint16_t(freq[sym] + BOOST); + uint32_t sum = 0; + for (unsigned i = 0; i < N; ++i) { + sum += freq[i]; + freq[i] = 1; + cdf[i + 1] = uint16_t(cdf[i + 1] + ((sum - cdf[i + 1]) >> 1)); + } + build_lookup(); + } + + unsigned decode(uint32_t& state) { + const uint32_t residue = state & 0x7FFFu; + unsigned sym = lookup[residue >> SHIFT]; + while (sym < N - 1 && residue >= cdf[sym + 1]) ++sym; + const uint32_t lo = cdf[sym]; + state = (state >> 15) * (uint32_t(cdf[sym + 1]) - lo) + (residue - lo); + freq[sym] = uint16_t(freq[sym] + 31); + if (--adapt == 0) rebuild(sym); + return sym; + } +}; + +using LiteralModel = Model<300, 6, 725>; +using DistLsbModel = Model<40, 9, 985>; +using DistBitsModel = Model<21, 9, 1004>; + +struct Decoder { + const uint8_t* src; + const uint8_t* src_end; + uint8_t* dst_start; + uint8_t* dst; + uint8_t* dst_end; + + uint32_t state1 = 0, state2 = 0; + uint32_t last_dist = 1; + uint32_t recent[8] = {1, 1, 1, 1, 1, 1, 1, 1}; + uint32_t recent_mask = (7u << 21) | (6u << 18) | (5u << 15) | (4u << 12) | + (3u << 9) | (2u << 6) | (1u << 3) | 0u; + + LiteralModel lit[4]; + DistLsbModel lsb[4]; + DistBitsModel bits; + + bool read16(uint32_t& v) { + if (src_end - src < 2) return false; + v = uint32_t(src[0]) | (uint32_t(src[1]) << 8); + src += 2; + return true; + } + + // Pull 16 bits into state1 if it dropped below the rANS floor, then swap + // the two interleaved states. + bool renorm() { + if (state1 < 0x10000) { + uint32_t w; + if (!read16(w)) return false; + state1 = (state1 << 16) | w; + } + const uint32_t t = state1; + state1 = state2; + state2 = t; + return true; + } + + bool quantum_header() { + uint32_t lo, hi; + if (!read16(lo) || !read16(hi)) return false; + // The u32 is stored as [low16][high16]; the fields assume [high16][low16]. + const uint32_t v = (lo << 16) | hi; + if (v < 0x10000) return false; + uint32_t a = v >> 4; + const uint32_t n = v & 0xF; + uint32_t w; + if (a < 0x10000) { + if (!read16(w)) return false; + a = (a << 16) | w; + } + uint32_t s1 = a >> n; + if (s1 < 0x10000) { + if (!read16(w)) return false; + s1 = (s1 << 16) | w; + } + if (!read16(w)) return false; + a = (a << 16) | w; + const uint32_t top = 1u << (n + 16); + state1 = s1; + state2 = top | (a & (top - 1)); + return true; + } + + bool decode_quantum(uint8_t* q_end) { + if (!quantum_header()) return false; + + if (dst == dst_start) { // no previous byte to delta against + *dst++ = uint8_t(state1); + state1 >>= 8; + if (!renorm()) return false; + } + + while (dst < q_end) { + unsigned sym = lit[size_t(dst - dst_start) & 3].decode(state1); + if (!renorm()) return false; + if (sym < 256) { + // last_dist <= bytes produced: it is 1 here only after the first + // byte, and every later value passed the match-distance check. + *dst = uint8_t(sym + dst[-ptrdiff_t(last_dist)]); + ++dst; + if (dst >= q_end) break; + sym = lit[size_t(dst - dst_start) & 3].decode(state1); + if (!renorm()) return false; + if (sym < 256) { + *dst = uint8_t(sym + dst[-ptrdiff_t(last_dist)]); + ++dst; + continue; + } + } + + if (sym >= 288) { // long copy length: 1..12 extra bits + const unsigned nb = sym - 287; + sym = (state1 & ((1u << nb) - 1)) + (1u << nb) + 286; + state1 >>= nb; + if (!renorm()) return false; + } + const uint32_t copy_len = sym - 254; + + const unsigned dsym = lsb[size_t(dst - dst_start) & 3].decode(state1); + if (!renorm()) return false; + + uint32_t dist; + if (dsym >= 8) { // explicit distance + const unsigned nb = bits.decode(state1); + if (!renorm()) return false; + dist = state1 & ((1u << (nb & 0xF)) - 1); + state1 >>= (nb & 0xF); + if (!renorm()) return false; + if (nb >= 0x10) { + uint32_t w; + if (!read16(w)) return false; + dist = (dist << 16) | w; + } + dist = (32u << nb) + (dist << 5) + dsym - 39; + recent[(recent_mask >> 21) & 7] = recent[(recent_mask >> 18) & 7]; + recent[(recent_mask >> 18) & 7] = dist; + } else { // recent-distance cache hit: move to front + const unsigned shift = 3 * dsym; + const uint32_t idx = (recent_mask >> shift) & 7; + const uint32_t mask = ~7u << shift; + dist = recent[idx]; + recent_mask = (recent_mask & mask) | ((idx + 8 * recent_mask) & ~mask); + } + + if (dist == 0 || dist > size_t(dst - dst_start)) return false; + if (copy_len > size_t(dst_end - dst)) return false; + const uint8_t* from = dst - dist; + for (uint32_t i = 0; i < copy_len; ++i) dst[i] = from[i]; // overlapping copy + dst += copy_len; + last_dist = dist; + } + + // A well-formed quantum leaves both states at the rANS floor. + return state1 == 0x10000 && state2 == 0x10000; + } + + bool run() { + uint32_t magic; + if (!read16(magic) || magic != kMagic) return false; + while (dst < dst_end) { + const size_t q_start = size_t(dst - dst_start) & ~(kQuantum - 1); + const size_t total = size_t(dst_end - dst_start); + uint8_t* q_end = dst_start + (total - q_start < kQuantum ? total : q_start + kQuantum); + if (src_end - src < 2) return false; + if (src[0] == 0 && src[1] == 0) { // stored quantum + src += 2; + const size_t n = size_t(q_end - dst); + if (size_t(src_end - src) < n) return false; + std::memcpy(dst, src, n); + dst += n; + src += n; + } else if (!decode_quantum(q_end)) { + return false; + } + } + return true; + } +}; + +} // namespace + +bool bitknit2_decompress(const uint8_t* src, size_t src_size, uint8_t* dst, size_t dst_size) { + if (!src || !dst || dst_size == 0) return false; + auto d = std::make_unique(); + d->src = src; + d->src_end = src + src_size; + d->dst_start = d->dst = dst; + d->dst_end = dst + dst_size; + for (auto& m : d->lit) { + // 264 regular symbols share the range; the 36 long-length symbols get one unit each. + for (unsigned i = 0; i < 264; ++i) m.cdf[i] = uint16_t((0x8000u - 300 + 264) * i / 264); + for (unsigned i = 264; i <= 300; ++i) m.cdf[i] = uint16_t(0x8000u - 300 + i); + m.reset(); + } + for (auto& m : d->lsb) m.init_uniform(); + d->bits.init_uniform(); + return d->run(); +} + +} // namespace gr2 diff --git a/gr2/src/bitknit2.h b/gr2/src/bitknit2.h new file mode 100644 index 0000000..d3137db --- /dev/null +++ b/gr2/src/bitknit2.h @@ -0,0 +1,37 @@ +// Granny "BitKnit2" (granny_compression_type 4, Granny 2.11+) decoder. +// +// Provenance: decode path re-implemented from the MIT-licensed BG3ModStudio +// LibLS/Bitknit2Decompressor.cpp (c) 2025 Thomas A. Rieck, +// https://github.com/trieck/BG3ModStudio, cross-checked against the BitKnit +// core of powzix/ooz bitknit.cpp (https://github.com/powzix/ooz). +// Granny framing: u16 magic 0x75B1, then one 64 KB quantum after another +// (u16 0 = stored quantum, otherwise a rANS quantum header). +// +// BG3ModStudio notice (applies to the algorithm this file set derives from): +// Copyright (c) 2025 Thomas A. Rieck +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// The above copyright notice and this permission notice shall be included in all +// copies or substantial portions of the Software. +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +// SOFTWARE. +#pragma once +#include +#include + +namespace gr2 { + +// Decompresses exactly dst_size bytes. Every read and write is bounds-checked. +// Returns false on a malformed or truncated stream. +bool bitknit2_decompress(const uint8_t* src, size_t src_size, uint8_t* dst, size_t dst_size); + +} // namespace gr2 diff --git a/gr2/src/gr2_anim.cpp b/gr2/src/gr2_anim.cpp new file mode 100644 index 0000000..5a0e427 --- /dev/null +++ b/gr2/src/gr2_anim.cpp @@ -0,0 +1,560 @@ +// M0 T7a —— 曲线子类型分类(gr2fuzz 直方图依赖)。T7b(解码)见文末。 +// 见 docs/reference/steps/M0-gr2-reader.md +// 规格:granny_track_group.cpp (TrackGroupType/TransformTrackType/Curve2Type) / +// granny_curve.cpp (CurveData*Type,均以 CurveDataHeaderType 开头) / +// granny_curve.h (curve_data_header{ u8 Format; u8 Degree }) +#include "internal.h" +#include +#include +#include +#include +#include + +#define ADBG(...) do { if (getenv("GR2_DEBUG")) fprintf(stderr, "[anim] " __VA_ARGS__); } while (0) + +namespace gr2 { + +using detail::Ref; +using detail::TypeMember; + +// Metin2 = Granny 2.4:曲线是 OldCurveType(granny_curve.cpp): +// {Int32 Degree; RefToArray Knots(Real32[]); RefToArray Controls(Real32[])} —— 20B,无压缩变体。 +// curve_obj 指向 transform_track 里 inline 的那个 curve 对象本体。 +// 新版(2.6+)是 curve2{variant CurveData},本函数一并识别、打标签。 +std::string File::Impl::classify_curve_obj(Ref curve_obj, Ref curve_type) { + if (!curve_obj.valid() || !curve_type.valid()) return "none"; + const auto& ms = parse_type(curve_type); + if (ms.empty()) return "Unknown"; + + // 老格式:第一个成员是 "Degree" + if (ms[0].name == "Degree") { + const TypeMember* mD = &ms[0]; + const TypeMember* mK = find_member(ms, "Knots"); + const TypeMember* mC = find_member(ms, "Controls"); + int32_t degree = rd_i32(member_slot(curve_obj, *mD)); + uint32_t kn = mK ? uint32_t(std::max(0, rd_i32(member_slot(curve_obj, *mK)))) : 0; + uint32_t cn = mC ? uint32_t(std::max(0, rd_i32(member_slot(curve_obj, *mC)))) : 0; + uint32_t dim = kn ? cn / kn : 0; + char buf[64]; + std::snprintf(buf, sizeof buf, "Old(d=%d,dim=%u)", degree, dim); + return buf; + } + // 新格式:curve2{variant CurveData} + if (ms[0].name == "CurveData") { + Ref type_ref = follow(member_slot(curve_obj, ms[0])); // variant.Type + if (!type_ref.valid()) return "Identity"; + const auto& dm = parse_type(type_ref); + if (dm.empty()) return "Unknown"; + const std::string& n = dm[0].name; + const char* pfx = "CurveDataHeader_"; + return (n.rfind(pfx, 0) == 0) ? n.substr(std::strlen(pfx)) : n; + } + return "Unknown"; +} + +// 读一条 OldCurveType 曲线({Int32 Degree; RefToArray Knots; RefToArray Controls})到 Curve。 +void File::Impl::read_old_curve(Ref curve_obj, Ref curve_type, Curve& out) { + if (!curve_obj.valid() || !curve_type.valid()) return; + const auto& ms = parse_type(curve_type); + if (ms.empty() || ms[0].name != "Degree") return; // 新格式暂不解 + const TypeMember* mD = &ms[0]; + const TypeMember* mK = find_member(ms, "Knots"); + const TypeMember* mC = find_member(ms, "Controls"); + if (!mK || !mC) return; + + out.degree = rd_i32(member_slot(curve_obj, *mD)); + + auto read_farr = [&](const TypeMember& m, std::vector& dst) { + Ref slot = member_slot(curve_obj, m); + int32_t cnt = rd_i32(slot); + if (cnt <= 0 || cnt > (1 << 24)) return; + Ref base = follow({slot.section, slot.offset + 4}); + const uint8_t* p = at(base, size_t(cnt) * 4); + if (!p) return; + dst.resize(cnt); + for (int32_t k = 0; k < cnt; ++k) std::memcpy(&dst[k], p + size_t(k) * 4, 4); + }; + read_farr(*mK, out.knots); + read_farr(*mC, out.controls); + out.knots_sorted = std::is_sorted(out.knots.begin(), out.knots.end()); + out.dim = out.knots.empty() ? 0 : uint32_t(out.controls.size() / out.knots.size()); + if (out.dim && out.knots.size() * out.dim != out.controls.size()) out.dim = 0; // 不一致 → 弃 + + // 有些资产的曲线控制点本身是 NaN(如 redthief_general/*_damage.gr2 的 finger track)。 + // 不 sanitize 会把 NaN 灌进整条蒙皮链。→ 整条曲线弃(eval 返回空,调用方回退到 bind)。 + for (float v : out.knots) if (!std::isfinite(v)) { out.dim = 0; return; } + for (float v : out.controls) if (!std::isfinite(v)) { out.dim = 0; return; } +} + +// ── curve2 压缩曲线(Granny 2.6+,AVA2 = 2.11)──────────────────────── +// curve2{VariantRef CurveData},CurveData 对象都以 inline CurveDataHeader{u8 Format; u8 Degree} +// 开头。各变体统一解成 knots + float controls,求值仍走下面的 Curve::eval(B 样条)。 +// 变体字段名来自文件自带的 type tree(CurveData*Type),反量化公式与 D4n 四元数表参照 +// MIT 许可的 LSLib(Norbyte,https://github.com/Norbyte/lslib)GR2 CurveData 实现重写, +// 未拷贝其代码;用 AVA2 全库 60 万条 curve2 校验(单位四元数、knot 末端 ≈ Duration)。 +// 成员一律按名字找,不硬编码偏移。 +// Da* dimension 来自数据(ControlScaleOffsets/2,或 Controls/Knots) +// D3* / D4n* 固定 3 / 4 维;D3I1 = 一个标量映射到 3 维;D9I1 / D9I3 = 3x3 对角 +// *K16u/*K8u 量化 knot:knot = k / OneOverKnotScale,OneOverKnotScaleTrunc 是 f32 的高 16 位 +// D4nK16uC15u / D4nK8uC7u:每个 knot 3 个分量 + 2 位 swizzle + 符号位,第 4 分量 = sqrt(1-Σ²) +namespace { +const float kQuatScale[16] = { + 1.4142135f, 0.70710677f, 0.35355338f, 0.35355338f, 0.35355338f, 0.17677669f, 0.17677669f, 0.17677669f, + -1.4142135f, -0.70710677f, -0.35355338f, -0.35355338f, -0.35355338f, -0.17677669f, -0.17677669f, -0.17677669f}; +const float kQuatOffset[16] = { + -0.70710677f, -0.35355338f, -0.53033006f, -0.17677669f, 0.17677669f, -0.17677669f, -0.088388346f, 0.0f, + 0.70710677f, 0.35355338f, 0.53033006f, 0.17677669f, -0.17677669f, 0.17677669f, 0.088388346f, -0.0f}; + +float trunc_to_f32(uint16_t hi) { + const uint32_t bits = uint32_t(hi) << 16; + float f; std::memcpy(&f, &bits, 4); + return f; +} +} // namespace + +void File::Impl::read_curve2(Ref curve_obj, Ref curve_type, float keyframe_dt, Curve& out) { + if (!curve_obj.valid() || !curve_type.valid()) return; + const auto& cms = parse_type(curve_type); + if (cms.empty() || cms[0].name != "CurveData") return; + const Ref vslot = member_slot(curve_obj, cms[0]); + const Ref dtype = follow(vslot); + const Ref dobj = follow({vslot.section, vslot.offset + ptr}); + if (!dtype.valid() || !dobj.valid()) return; // DaIdentity 之外的空 variant → identity + const auto& ms = parse_type(dtype); + if (ms.empty()) return; + const char* pfx = "CurveDataHeader_"; + if (ms[0].name.rfind(pfx, 0) != 0) return; + const std::string v = ms[0].name.substr(std::strlen(pfx)); + + const uint8_t* hdr = at(dobj, 2); + if (!hdr) return; + const int32_t degree = hdr[1]; + + auto mem = [&](const char* n) { return find_member(ms, n); }; + auto f32 = [&](const char* n, uint32_t i) -> float { + const TypeMember* m = mem(n); + if (!m) return 0.0f; + return rd_f32({dobj.section, dobj.offset + m->offset + i * 4u}); + }; + auto u16m = [&](const char* n, uint16_t& o) -> bool { + const TypeMember* m = mem(n); + const uint8_t* p = m ? at(member_slot(dobj, *m), 2) : nullptr; + if (!p) return false; + o = uint16_t(p[0] | (p[1] << 8)); + return true; + }; + // RefToArray {int32 count; ptr data} + auto arr = [&](const char* n, uint32_t esz, uint32_t& cnt) -> const uint8_t* { + cnt = 0; + const TypeMember* m = mem(n); + if (!m) return nullptr; + const Ref slot = member_slot(dobj, *m); + const int32_t c = rd_i32(slot); + if (c <= 0 || c > (1 << 24)) return nullptr; + const uint8_t* p = at(follow({slot.section, slot.offset + 4}), size_t(c) * esz); + if (p) cnt = uint32_t(c); + return p; + }; + auto rf = [](const uint8_t* p, size_t i) { float f; std::memcpy(&f, p + i * 4, 4); return f; }; + auto ru = [](const uint8_t* p, size_t i, uint32_t esz) -> uint32_t { + return esz == 1 ? p[i] : uint32_t(p[i * 2] | (p[i * 2 + 1] << 8)); + }; + + auto finish = [&](uint32_t dim) { + out.degree = degree; + out.dim = dim; + out.knots_sorted = std::is_sorted(out.knots.begin(), out.knots.end()); + if (out.knots.empty() || out.controls.size() != out.knots.size() * dim) { out = Curve{}; return; } + for (float x : out.knots) if (!std::isfinite(x)) { out = Curve{}; return; } + for (float x : out.controls) if (!std::isfinite(x)) { out = Curve{}; return; } + }; + + if (v == "DaIdentity") return; // 调用方取单位分量 + + if (v == "DaConstant32f" || v == "D3Constant32f" || v == "D4Constant32f") { + if (v == "DaConstant32f") { + uint32_t n = 0; + const uint8_t* p = arr("Controls", 4, n); + if (!p) return; + for (uint32_t i = 0; i < n; ++i) out.controls.push_back(rf(p, i)); + } else { + const uint32_t n = v[1] == '3' ? 3 : 4; + if (!mem("Controls")) return; + for (uint32_t i = 0; i < n; ++i) out.controls.push_back(f32("Controls", i)); + } + out.knots = {0.0f}; + finish(uint32_t(out.controls.size())); + out.degree = 0; + return; + } + + if (v == "DaK32fC32f") { + uint32_t nk = 0, nc = 0; + const uint8_t* pk = arr("Knots", 4, nk); + const uint8_t* pc = arr("Controls", 4, nc); + if (!pk || !pc || nc % nk) return; // 0 knot = 导出器写的空曲线 → identity + for (uint32_t i = 0; i < nk; ++i) out.knots.push_back(rf(pk, i)); + for (uint32_t i = 0; i < nc; ++i) out.controls.push_back(rf(pc, i)); + return finish(nc / nk); + } + + if (v == "DaKeyframes32f") { + // 关键帧:knot 不存,第 i 帧在 i*TimeStep(AVA2 全库 19045 条都满足 N-1 == Duration/TimeStep)。 + // Degree 0 = 逐帧保持,见 Curve::eval。 + uint16_t dim16 = 0; + uint32_t nc = 0; + const uint8_t* pc = arr("Controls", 4, nc); + if (!u16m("Dimension", dim16) || dim16 == 0 || !pc || nc % dim16) return; + for (uint32_t i = 0; i < nc / dim16; ++i) out.knots.push_back(float(i) * keyframe_dt); + for (uint32_t i = 0; i < nc; ++i) out.controls.push_back(rf(pc, i)); + return finish(dim16); + } + + // 其余都是量化 knot + KnotsControls 一块数组:先 N 个 knot,再 N*每knot分量数 个 control。 + const bool k8 = v.find("K8u") != std::string::npos; + const bool k32 = v.find("K32f") != std::string::npos; + const uint32_t esz = k32 ? 4 : (k8 ? 1 : 2); + uint32_t total = 0; + const uint8_t* kc = arr("KnotsControls", esz, total); + if (!kc) return; + float one_over_knot_scale = 1.0f; + if (!k32) { + uint16_t trunc = 0; + if (u16m("OneOverKnotScaleTrunc", trunc)) one_over_knot_scale = trunc_to_f32(trunc); + else if (mem("OneOverKnotScale")) one_over_knot_scale = f32("OneOverKnotScale", 0); + else return; + if (!(one_over_knot_scale != 0.0f) || !std::isfinite(one_over_knot_scale)) return; + } + auto knot = [&](uint32_t i) { + return k32 ? rf(kc, i) : float(ru(kc, i, esz)) / one_over_knot_scale; + }; + auto ctl = [&](uint32_t i) { return k32 ? rf(kc, i) : float(ru(kc, i, esz)); }; + + if (v == "D4nK16uC15u" || v == "D4nK8uC7u") { + if (total % 4) return; + const uint32_t n = total / 4; + uint16_t sel = 0; + if (!u16m("ScaleOffsetTableEntries", sel)) return; + const float unit = k8 ? (1.0f / 127.0f) : (1.0f / 32767.0f); + float sc[4], of[4]; + for (int i = 0; i < 4; ++i) { + sc[i] = kQuatScale[(sel >> (4 * i)) & 0xF] * unit; + of[i] = kQuatOffset[(sel >> (4 * i)) & 0xF]; + } + const uint32_t sign = k8 ? 0x80u : 0x8000u, mask = sign - 1, sh = k8 ? 7 : 15; + for (uint32_t i = 0; i < n; ++i) out.knots.push_back(knot(i)); + for (uint32_t i = 0; i < n; ++i) { + const uint32_t a = ru(kc, n + i * 3 + 0, esz); + const uint32_t b = ru(kc, n + i * 3 + 1, esz); + const uint32_t c = ru(kc, n + i * 3 + 2, esz); + const uint32_t s1 = (((b & sign) >> sh) << 1) | ((c & sign) >> sh); // 被省略的分量 + const uint32_t s2 = (s1 + 1) & 3, s3 = (s2 + 1) & 3, s4 = (s3 + 1) & 3; + float q[4]; + q[s2] = float(a & mask) * sc[s2] + of[s2]; + q[s3] = float(b & mask) * sc[s3] + of[s3]; + q[s4] = float(c & mask) * sc[s4] + of[s4]; + const float r = 1.0f - (q[s2] * q[s2] + q[s3] * q[s3] + q[s4] * q[s4]); + q[s1] = std::sqrt(r > 0.0f ? r : 0.0f); + if (a & sign) q[s1] = -q[s1]; + out.controls.insert(out.controls.end(), q, q + 4); + } + return finish(4); + } + + if (v == "D3K16uC16u" || v == "D3K8uC8u") { + if (total % 4) return; + const uint32_t n = total / 4; + for (uint32_t i = 0; i < n; ++i) out.knots.push_back(knot(i)); + for (uint32_t i = 0; i < n * 3; ++i) + out.controls.push_back(ctl(n + i) * f32("ControlScales", i % 3) + f32("ControlOffsets", i % 3)); + return finish(3); + } + + if (v == "D3I1K16uC16u" || v == "D3I1K8uC8u" || v == "D3I1K32fC32f") { + if (total % 2) return; + const uint32_t n = total / 2; + for (uint32_t i = 0; i < n; ++i) out.knots.push_back(knot(i)); + for (uint32_t i = 0; i < n; ++i) + for (uint32_t d = 0; d < 3; ++d) + out.controls.push_back(ctl(n + i) * f32("ControlScales", d) + f32("ControlOffsets", d)); + return finish(3); + } + + if (v == "D9I1K16uC16u" || v == "D9I1K8uC8u" || v == "D9I3K16uC16u" || v == "D9I3K8uC8u") { + const bool i3 = v[3] == '3'; + const uint32_t per = i3 ? 3 : 1; + if (total % (per + 1)) return; + const uint32_t n = total / (per + 1); + for (uint32_t i = 0; i < n; ++i) out.knots.push_back(knot(i)); + for (uint32_t i = 0; i < n; ++i) { + float m[9] = {0, 0, 0, 0, 0, 0, 0, 0, 0}; + for (uint32_t d = 0; d < 3; ++d) { + const uint32_t c = i3 ? d : 0; + m[d * 4] = i3 ? ctl(n + i * 3 + c) * f32("ControlScales", d) + f32("ControlOffsets", d) + : ctl(n + i) * f32("ControlScale", 0) + f32("ControlOffset", 0); + } + out.controls.insert(out.controls.end(), m, m + 9); + } + return finish(9); + } + + if (v == "DaK16uC16u" || v == "DaK8uC8u") { + uint32_t nso = 0; + const uint8_t* so = arr("ControlScaleOffsets", 4, nso); + if (!so || nso < 2 || nso % 2) return; + const uint32_t dim = nso / 2; + if (total % (dim + 1)) return; + const uint32_t n = total / (dim + 1); + for (uint32_t i = 0; i < n; ++i) out.knots.push_back(knot(i)); + for (uint32_t i = 0; i < n * dim; ++i) + out.controls.push_back(ctl(n + i) * rf(so, i % dim) + rf(so, dim + i % dim)); + return finish(dim); + } + ADBG("curve2 variant %s not decoded\n", v.c_str()); +} + +// animation: {String Name; Real32 Duration; Real32 TimeStep; Real32 Oversampling; +// ArrayOfRefs TrackGroups; ...} +// track_group: {String Name; RefToArray VectorTracks; RefToArray TransformTracks; ...} +// transform_track: {String Name; Int32 Flags; Inline OrientationCurve(curve2); +// Inline PositionCurve(curve2); Inline ScaleShearCurve(curve2)} +bool File::Impl::extract_animation(Ref anim_obj, Ref anim_type, const Skeleton* skel, Animation& out) { + if (!anim_obj.valid() || !anim_type.valid()) return false; + const auto& ams = parse_type(anim_type); + + if (const TypeMember* m = find_member(ams, "Name")) + out.name = rd_str(member_slot(anim_obj, *m)); + if (const TypeMember* m = find_member(ams, "Duration")) + out.duration = rd_f32(member_slot(anim_obj, *m)); + if (const TypeMember* m = find_member(ams, "TimeStep")) + out.time_step = rd_f32(member_slot(anim_obj, *m)); + if (const TypeMember* m = find_member(ams, "Oversampling")) + out.oversampling = rd_f32(member_slot(anim_obj, *m)); + + const TypeMember* mTG = find_member(ams, "TrackGroups"); + if (!mTG) return true; + auto groups = read_array_of_refs(anim_obj, *mTG); + out.track_group_count = int32_t(groups.size()); + const auto& tgms = parse_type(mTG->ref_type); + + for (Ref group : groups) { + AnimationTrackGroup data; + if (group.valid()) { + if (const auto* m = find_member(tgms, "Name")) data.name = rd_str(member_slot(group, *m)); + if (const auto* m = find_member(tgms, "InitialPlacement")) read_transform(member_slot(group, *m), data.initial_placement); + if (const auto* m = find_member(tgms, "AccumulationFlags")) data.accumulation_flags = rd_i32(member_slot(group, *m)); + if (const auto* m = find_member(tgms, "LoopTranslation")) { + Ref r = member_slot(group, *m); + for (int i = 0; i < 3; ++i) data.loop_translation[i] = rd_f32({r.section, r.offset + uint32_t(i) * 4u}); + } + if (const auto* mTx = find_member(tgms, "TextTracks")) { + Ref xb; uint32_t xc = 0, xs = 0; + if (read_ref_to_array(group, *mTx, xb, xc, xs) && xc && xs) { + const auto& xms = parse_type(mTx->ref_type); + const auto* mXN = find_member(xms, "Name"); + const auto* mXE = find_member(xms, "Entries"); + for (uint32_t i = 0; i < xc && i < 4096; ++i) { + Ref x = {xb.section, xb.offset + i * xs}; + TextTrack tt; + if (mXN) tt.name = rd_str(member_slot(x, *mXN)); + Ref eb; uint32_t ec = 0, es = 0; + if (mXE && read_ref_to_array(x, *mXE, eb, ec, es) && ec && es) { + const auto& ems = parse_type(mXE->ref_type); + const auto* mTS = find_member(ems, "TimeStamp"); + const auto* mTT = find_member(ems, "Text"); + for (uint32_t k = 0; k < ec && k < 65536; ++k) { + Ref e = {eb.section, eb.offset + k * es}; + TextTrackEntry te; + if (mTS) te.time_stamp = rd_f32(member_slot(e, *mTS)); + if (mTT) te.text = rd_str(member_slot(e, *mTT)); + tt.entries.push_back(std::move(te)); + } + } + data.text_tracks.push_back(std::move(tt)); + } + } + } + } + out.track_groups.push_back(std::move(data)); + } + // Existing inspection API exposes the first group; runtime binding uses track_groups by name. + if (!out.track_groups.empty()) { + const auto& first = out.track_groups.front(); + out.accumulation_flags = first.accumulation_flags; + std::copy_n(first.loop_translation, 3, out.loop_translation); + out.text_tracks = first.text_tracks; + } + const TypeMember* mTT = find_member(tgms, "TransformTracks"); + if (!mTT) return true; + + const auto& ttms = parse_type(mTT->ref_type); + if (getenv("GR2_DEBUG")) { + fprintf(stderr, "[anim] transform_track type members=%zu:\n", ttms.size()); + for (auto& m : ttms) + fprintf(stderr, "[anim] %-20s type=%d aw=%d off=%u size=%u reftype=(%d,%u)\n", + m.name.c_str(), m.type, m.array_width, m.offset, m.size, + m.ref_type.section, m.ref_type.offset); + } + const TypeMember* mName = find_member(ttms, "Name"); + const TypeMember* mOri = find_member(ttms, "OrientationCurve"); + const TypeMember* mPos = find_member(ttms, "PositionCurve"); + const TypeMember* mScl = find_member(ttms, "ScaleShearCurve"); + + for (size_t group_index = 0; group_index < groups.size(); ++group_index) { + Ref g = groups[group_index]; + auto& group_data = out.track_groups[group_index]; + group_data.first_track = out.tracks.size(); + if (!g.valid()) continue; + Ref base; uint32_t count = 0, stride = 0; + if (!read_ref_to_array(g, *mTT, base, count, stride) || count == 0) continue; + for (uint32_t i = 0; i < count; ++i) { + Ref t = {base.section, base.offset + i * stride}; + BoneTrack bt; + if (mName) bt.bone_name = rd_str(member_slot(t, *mName)); + if (mPos) { + bt.pos_type = classify_curve_obj(member_slot(t, *mPos), mPos->ref_type); + read_old_curve(member_slot(t, *mPos), mPos->ref_type, bt.position); + read_curve2(member_slot(t, *mPos), mPos->ref_type, out.time_step, bt.position); + } + if (mOri) { + bt.rot_type = classify_curve_obj(member_slot(t, *mOri), mOri->ref_type); + read_old_curve(member_slot(t, *mOri), mOri->ref_type, bt.orientation); + read_curve2(member_slot(t, *mOri), mOri->ref_type, out.time_step, bt.orientation); + } + if (mScl) { + bt.scale_type = classify_curve_obj(member_slot(t, *mScl), mScl->ref_type); + read_old_curve(member_slot(t, *mScl), mScl->ref_type, bt.scale_shear); + read_curve2(member_slot(t, *mScl), mScl->ref_type, out.time_step, bt.scale_shear); + } + if (skel) for (size_t k = 0; k < skel->bones.size(); ++k) + if (skel->bones[k].name == bt.bone_name) { bt.bone_index = int32_t(k); break; } + out.tracks.push_back(std::move(bt)); + } + group_data.track_count = out.tracks.size() - group_data.first_track; + } + return true; +} + +// ── T7b:曲线解码 ───────────────────────────────────────────────────── +// Metin2 曲线全是 OldCurveType(B 样条:Degree + Knots[] + Controls[knot*dim]); +// AVA2 的 curve2 变体由 read_curve2 解成同样的 knots/controls。 +// 求值照 granny_bspline.cpp SampleBSpline{0,1,2}xN + granny_bspline_inlines.h +// {Linear,Quadratic}Coefficients。degree 0=常量/阶梯,1=线性,2=二次 B 样条。 +// KnotIndex = "第一个 > t 的 knot"(granny CurveFindKnot),窗口越界按端点 clamp。 +// +// dim==4(四元数):blend 之前对本 span 参与的 degree+1 个控制点做 +// EnsureQuaternionContinuity(granny_math.cpp)—— 逐点若与前一点点积 < 0 则整体取反。 +// 少了这一步,跨半球(q vs -q)的控制点线性混合会收缩到近零,归一后得到一个 +// 合法但方向错约 180° 的旋转(表情动作里脖子/头会折叠塌陷)。 +void Curve::eval(float t, float* out) const { + const uint32_t n = (uint32_t)knots.size(); + if (n == 0 || dim == 0) return; + auto Kc = [&](int i) -> float { + i = i < 0 ? 0 : (i >= (int)n ? (int)n - 1 : i); + return knots[(uint32_t)i]; + }; + + if (n == 1) { // 常量 + for (uint32_t d = 0; d < dim; ++d) out[d] = controls[d]; + return; + } + if (degree <= 0) { // 阶梯(granny SampleBSpline0:最后一个 <= t 的 knot) + uint32_t k = 0; + if (knots_sorted) { + const auto it = std::upper_bound(knots.begin(), knots.end(), t); + k = it == knots.begin() ? 0 : uint32_t(it - knots.begin()) - 1; + } else { + for (uint32_t j = 0; j < n; ++j) if (knots[j] <= t) k = j; + } + for (uint32_t d = 0; d < dim; ++d) out[d] = controls[k * dim + d]; + return; + } + if (t <= knots[0]) t = knots[0]; + if (t >= knots[n - 1]) t = knots[n - 1]; + // 第一个 > t 的 knot(找不到 → n-1);升序时二分 + int i = (int)n - 1; + if (knots_sorted) { + const int k = int(std::upper_bound(knots.begin(), knots.end(), t) - knots.begin()); + if (k < (int)n) i = k; + } else { + for (uint32_t k = 0; k < n; ++k) if (knots[k] > t) { i = (int)k; break; } + } + if (i < 1) i = 1; + + const int span = (degree == 1) ? 2 : 3; // 本 span 的控制点数 = degree+1 + const int first = (degree == 1) ? (i - 1) : (i - 2); + + // 拷本 span 的控制点(越界按端点 clamp),四元数做半球连续化 + // Metin2 的 ScaleShearCurve 是 9 维;旧的 3*4 缓冲区会在这里发生 + // 栈溢出(degree=2 时写入 27 个 float),随后被 __stack_chk_fail 终止。 + // 目前支持的曲线维度为 position=3、orientation=4、scale/shear=9。 + if (dim > 9) return; + float cp[3 * 9]; + for (int s = 0; s < span; ++s) { + int ci = first + s; + ci = ci < 0 ? 0 : (ci >= (int)n ? (int)n - 1 : ci); + for (uint32_t d = 0; d < dim; ++d) cp[s * dim + d] = controls[(uint32_t)ci * dim + d]; + } + if (dim == 4) { + for (int s = 1; s < span; ++s) { + const float* p = &cp[(s - 1) * 4]; + float* q = &cp[s * 4]; + if (p[0]*q[0] + p[1]*q[1] + p[2]*q[2] + p[3]*q[3] < 0.0f) + for (int d = 0; d < 4; ++d) q[d] = -q[d]; + } + } + + if (degree == 1) { + float denom = Kc(i) - Kc(i - 1); + float c0 = denom != 0.0f ? (t - Kc(i - 1)) / denom : 0.0f; + c0 = c0 < 0 ? 0 : (c0 > 1 ? 1 : c0); + float c1 = 1.0f - c0; + for (uint32_t d = 0; d < dim; ++d) + out[d] = c1 * cp[0 * dim + d] + c0 * cp[1 * dim + d]; + } else { // degree >= 2 → 二次(Metin2 无 degree 3) + float ti_2 = Kc(i - 2), ti_1 = Kc(i - 1), ti = Kc(i), ti1 = Kc(i + 1); + auto fdiv = [](float a, float b) { return b != 0.0f ? a / b : 0.0f; }; + float L0 = fdiv(t - ti_1, ti - ti_1); + float L1_1 = fdiv(t - ti_2, ti - ti_2); + float L1_2 = fdiv(t - ti_1, ti1 - ti_1); + float tmp = (L1_1 + L0) - L0 * L1_1; + float c0 = L0 * L1_2; // ci + float c1 = tmp - c0; // ci_1 + float c2 = 1.0f - tmp; // ci_2 + for (uint32_t d = 0; d < dim; ++d) + out[d] = c2 * cp[0 * dim + d] + c1 * cp[1 * dim + d] + c0 * cp[2 * dim + d]; + } + + if (dim == 4) { // 四元数:归一 + float m = std::sqrt(out[0]*out[0] + out[1]*out[1] + out[2]*out[2] + out[3]*out[3]); + if (m > 1e-12f) for (int d = 0; d < 4; ++d) out[d] /= m; + } +} + +// t 处的 SRT。position 缺省 (0,0,0),orientation 缺省单位四元数,scaleshear 缺省 I。 +void BoneTrack::sample(float t, Transform& out) const { + out = Transform{}; + if (!position.empty()) { position.eval(t, out.position); out.flags |= 0x1; } + if (!orientation.empty()) { orientation.eval(t, out.orientation); out.flags |= 0x2; } + if (!scale_shear.empty()) { + if (scale_shear.dim == 9) { scale_shear.eval(t, out.scale_shear); out.flags |= 0x4; } + else if (scale_shear.dim == 3) { + float s[3]; scale_shear.eval(t, s); + out.scale_shear[0] = s[0]; out.scale_shear[4] = s[1]; out.scale_shear[8] = s[2]; + out.flags |= 0x4; + } + } +} + +// t 处每个 track 的局部 4x4(BuildCompositeTransform4x4 语义:C 上 3x3 = transpose(R3*SS3), +// 平移在 elem 12..14)。 +void Animation::sample_local(float t, std::vector& out) const { + out.resize(tracks.size()); + Transform x; + for (size_t ti = 0; ti < tracks.size(); ++ti) { + tracks[ti].sample(t, x); + out[ti] = compose(x); + } +} + +} // namespace gr2 diff --git a/gr2/src/gr2_decompress.cpp b/gr2/src/gr2_decompress.cpp new file mode 100644 index 0000000..3a1a4c7 --- /dev/null +++ b/gr2/src/gr2_decompress.cpp @@ -0,0 +1,68 @@ +// M0 T2 —— section 解压分派。见 docs/reference/steps/M0-gr2-reader.md +#include "internal.h" +#include "oodle1.h" +#include "bitknit2.h" +#include + +namespace gr2 { + +// src 指向文件里该 section 的压缩字节(长度 s.data_size)。 +// 本函数会做一份可写的、尾部留 32B 零的副本(Oodle1 解码器会写它、读过界)。 +bool File::Impl::decompress_section(const detail::GrnSection& s, const uint8_t* src, + detail::Section& out, LoadError* err) { + out.info = {s.compression, s.data_size, s.expanded_data_size, s.pointer_fixup_count, 0}; + + if (s.expanded_data_size == 0) { // 空 section + out.data.clear(); + return true; + } + + switch (s.compression) { + case 0: { // NoCompression + out.data.assign(src, src + s.data_size); + out.data.resize(s.expanded_data_size); + return true; + } + case 1: // Oodle0 —— 同一族解码器的变体,暂未实现(T2 后续;样本里极少) + out.info.decompress_status = 1; + if (err) *err = {"section", "Oodle0 not implemented (M0 T2)"}; + return false; + case 2: { // Oodle1 + // 4 字节对齐的可写副本 + 32B 零尾 + std::vector buf; + buf.reserve(s.data_size + 32); + buf.assign(src, src + s.data_size); + buf.resize(s.data_size + 32, 0); + out.data.assign(s.expanded_data_size, 0); + int rc = gr2_oodle1_decompress(/*byte_reversed=*/0, + s.data_size, buf.data(), + s.first16bit, s.first8bit, s.expanded_data_size, + out.data.data()); + out.info.decompress_status = rc; + if (rc != 0) { + if (err) *err = {"section", "Oodle1 decompress failed"}; + return false; + } + return true; + } + case 3: // BitKnit(v1)—— Granny 2.11 之前的旧格式,AVA2 语料未出现 + out.info.decompress_status = 3; + if (err) *err = {"section", "BitKnit (v1) not implemented"}; + return false; + case 4: { // BitKnit2(Granny 2.11+;AVA2 pc/item 约 90% 的 gr2) + out.data.assign(s.expanded_data_size, 0); + if (!bitknit2_decompress(src, s.data_size, out.data.data(), out.data.size())) { + out.info.decompress_status = 4; + if (err) *err = {"section", "BitKnit2 decompress failed"}; + return false; + } + return true; + } + default: + out.info.decompress_status = -1; + if (err) *err = {"section", "unknown compression format"}; + return false; + } +} + +} // namespace gr2 diff --git a/gr2/src/gr2_file.cpp b/gr2/src/gr2_file.cpp new file mode 100644 index 0000000..8e548ed --- /dev/null +++ b/gr2/src/gr2_file.cpp @@ -0,0 +1,209 @@ +// M0 T1 —— header + section table + fixup。见 docs/reference/steps/M0-gr2-reader.md +// 规格:MobileSource/Cross Platform/Granny-3D-SDK-main/source/granny_file_format.h + .cpp +// +// 本次实现范围:magic 识别 + grn_file_header + section 表解析(--sections 用)。 +// section 解压(Oodle0/1)是 T2;类型树 / FileInfo 是 T3/T4 —— 仍是 stub。 +#include "internal.h" +#include +#include +#include + +namespace gr2 { +namespace { + +// 小端读取 + 边界检查 +inline bool rd32(const uint8_t* p, size_t len, size_t off, uint32_t& out) { + if (off + 4 > len) return false; + out = uint32_t(p[off]) | (uint32_t(p[off + 1]) << 8) | + (uint32_t(p[off + 2]) << 16) | (uint32_t(p[off + 3]) << 24); + return true; +} + +// granny_file_format.cpp 里的 5 个已知 magic(LE u32 序列) +struct KnownMagic { uint32_t v[4]; Magic tag; const char* name; }; +constexpr KnownMagic kMagics[] = { + // GRNFileMV_Old —— Metin2 的 gr2(v6 era)用这个 + {{0xCAB067B8, 0x0FB16DF8, 0x7E8C7284, 0x1E00195E}, Magic::Bit32_LE, "Old(32LE)"}, + {{0xC06CDE29, 0x2B53A4BA, 0xA5B7F525, 0xEEE266F6}, Magic::Bit32_LE, "32Bit_LittleEndian"}, + {{0xB595110E, 0x4BB5A56A, 0x502828EB, 0x04B37825}, Magic::Bit32_BE, "32Bit_BigEndian"}, + {{0x5E499BE5, 0x141F636F, 0xA9EB131E, 0xC4EDBE90}, Magic::Bit64_LE, "64Bit_LittleEndian"}, + {{0xE3D49531, 0x624FDC20, 0x3AD036CC, 0x89FF82B1}, Magic::Bit64_BE, "64Bit_BigEndian"}, +}; + +constexpr size_t kMagicStructSize = 32; // grn_file_magic_value:4*u32 magic + HeaderSize + HeaderFormat + 2*u32 reserved +constexpr size_t kSectionSize = 44; // grn_section:11 * u32 + +} // namespace + +const char* magic_name(Magic m) { + switch (m) { + case Magic::Bit32_LE: return "32-bit LE"; + case Magic::Bit32_BE: return "32-bit BE"; + case Magic::Bit64_LE: return "64-bit LE"; + case Magic::Bit64_BE: return "64-bit BE"; + default: return "unknown"; + } +} +const char* compression_name(uint32_t f) { + switch (f) { + case 0: return "none"; + case 1: return "Oodle0"; + case 2: return "Oodle1"; + default: return "?"; + } +} + +std::optional File::load(const uint8_t* bytes, size_t len, LoadError* err) { + if (err) *err = {}; + auto fail = [&](const char* stage, const char* msg) { + if (err) *err = {stage, msg}; + return std::nullopt; + }; + + if (!bytes || len < kMagicStructSize + 32) + return fail("header", "file too small"); + + // ── magic ──────────────────────────────────────────────────────────── + uint32_t m[4]; + for (int i = 0; i < 4; ++i) rd32(bytes, len, size_t(i) * 4, m[i]); + Magic magic = Magic::Unknown; + for (const auto& k : kMagics) { + if (m[0] == k.v[0] && m[1] == k.v[1] && m[2] == k.v[2] && m[3] == k.v[3]) { + magic = k.tag; + break; + } + } + if (magic == Magic::Unknown) + return fail("header", "not a Granny file (unknown magic)"); + // 64 位 LE(Granny 64 位导出器,如 AVA2 plechi_* 资源):头 / section 表 / fixup 与 + // 32 位相同,只有 section 数据里的指针槽是 8 字节(Impl::ptr)。 + if (magic != Magic::Bit32_LE && magic != Magic::Bit64_LE) + return fail("header", "big-endian Granny files not supported"); + + uint32_t header_size = 0, header_format = 0; + rd32(bytes, len, 16, header_size); + rd32(bytes, len, 20, header_format); // 注意:这不是 section 压缩,section 压缩看每段 Format + + // ── grn_file_header(在 magic 结构之后)───────────────────────────── + const size_t H = kMagicStructSize; // header 起点 + // grn_file_header: Version(0) TotalSize(4) CRC(8) SectionArrayOffset(12) + // SectionArrayCount(16) RootObjectTypeDefinition{Section(20) Offset(24)} + // RootObject{Section(28) Offset(32)} TypeTag(36) ... + uint32_t version = 0, total_size = 0, sec_off = 0, sec_count = 0; + uint32_t rt_sec = 0, rt_off = 0, ro_sec = 0, ro_off = 0; + if (!rd32(bytes, len, H + 0, version) || + !rd32(bytes, len, H + 4, total_size) || + !rd32(bytes, len, H + 12, sec_off) || + !rd32(bytes, len, H + 16, sec_count) || + !rd32(bytes, len, H + 20, rt_sec) || + !rd32(bytes, len, H + 24, rt_off) || + !rd32(bytes, len, H + 28, ro_sec) || + !rd32(bytes, len, H + 32, ro_off)) + return fail("header", "truncated grn_file_header"); + + // ── section 表 ────────────────────────────────────────────────────── + // SectionArrayOffset 相对 grn_file_header 起点(H) + const size_t sec_base = H + sec_off; + if (sec_count > 64) + return fail("section", "implausible section count"); + if (sec_base + size_t(sec_count) * kSectionSize > len) + return fail("section", "section array out of range"); + + // ── AC 自检(不致命,仅 GR2_DEBUG 打日志)────────────────────────── + if (std::getenv("GR2_DEBUG")) { + if (version != 6 && version != 7) + std::fprintf(stderr, "gr2: warn: format_version=%u (期望 6/7)\n", version); + if (total_size != len) + std::fprintf(stderr, "gr2: warn: total_size=%u != file size %zu\n", total_size, len); + } + + File out; + out.magic_ = magic; + out.version_ = version; + out.total_size_ = total_size; + out.impl_ = std::make_shared(); + out.impl_->ptr = (magic == Magic::Bit64_LE) ? 8 : 4; + out.impl_->sections.resize(sec_count); + out.impl_->raw.resize(sec_count); + out.sections_.reserve(sec_count); + + // ── 逐 section:读头 + T2 展开 ───────────────────────────────────── + for (uint32_t i = 0; i < sec_count; ++i) { + const size_t s = sec_base + size_t(i) * kSectionSize; + uint32_t f[11]; + for (int j = 0; j < 11; ++j) rd32(bytes, len, s + size_t(j) * 4, f[j]); + // f: Format DataOffset DataSize ExpandedDataSize InternalAlignment + // First16Bit First8Bit PtrFixupOff PtrFixupCount MixedFixupOff MixedFixupCount + detail::GrnSection gs{}; + gs.compression = f[0]; + gs.data_offset = f[1]; + gs.data_size = f[2]; + gs.expanded_data_size = f[3]; + gs.internal_alignment = f[4]; + gs.first16bit = f[5]; + gs.first8bit = f[6]; + gs.pointer_fixup_off = f[7]; + gs.pointer_fixup_count= f[8]; + gs.mixed_fixup_off = f[9]; + gs.mixed_fixup_count = f[10]; + + if (size_t(gs.data_offset) > len || size_t(gs.data_size) > len - size_t(gs.data_offset)) + return fail("section", "section data out of range"); + + out.impl_->raw[i] = gs; + LoadError sec_err; + if (!out.impl_->decompress_section(gs, bytes + gs.data_offset, + out.impl_->sections[i], &sec_err)) { + if (err) { + *err = sec_err; + err->message += " (section " + std::to_string(i) + ")"; + } + return std::nullopt; + } + out.sections_.push_back(out.impl_->sections[i].info); + } + + // ── T1:fixup 索引(需要展开后的 section 数据 + 原始 section 头)────── + if (!out.impl_->build_fixups(bytes, len, err)) + return std::nullopt; + out.impl_->root_type = { int32_t(rt_sec), rt_off }; + out.impl_->root_obj = { int32_t(ro_sec), ro_off }; + + // ── T3/T4:类型树 + FileInfo 汇总。失败必须传播;返回一个看似成功但 + // FileInfo 为空的对象会让上层把损坏文件误判成合法的空模型。 + LoadError fi_err; + if (!out.impl_->build_fileinfo(out.info_, &fi_err)) { + if (err) *err = fi_err; + return std::nullopt; + } + + (void)header_size; (void)header_format; + return out; +} + +std::optional File::load_path(const std::string& path, LoadError* err) { + FILE* f = std::fopen(path.c_str(), "rb"); + if (!f) { if (err) *err = {"open", "cannot open " + path}; return std::nullopt; } + std::fseek(f, 0, SEEK_END); + long n = std::ftell(f); + std::fseek(f, 0, SEEK_SET); + std::vector buf(n > 0 ? size_t(n) : 0); + if (!buf.empty()) { + size_t rd = std::fread(buf.data(), 1, buf.size(), f); + if (rd != buf.size()) { std::fclose(f); if (err) *err = {"open", "short read"}; return std::nullopt; } + } + std::fclose(f); + return load(buf.data(), buf.size(), err); +} + +double File::bind_pose_self_check(int skeleton) const { + return impl_ ? impl_->skeleton_self_check(skeleton) : 1e9; +} + +std::span File::section_bytes(size_t i) const { + if (!impl_ || i >= impl_->sections.size()) return {}; + const auto& d = impl_->sections[i].data; + return {d.data(), d.size()}; +} + +} // namespace gr2 diff --git a/gr2/src/gr2_fileinfo.cpp b/gr2/src/gr2_fileinfo.cpp new file mode 100644 index 0000000..47e0f3b --- /dev/null +++ b/gr2/src/gr2_fileinfo.cpp @@ -0,0 +1,153 @@ +// M0 T4 —— FileInfo 汇总(驱动 T5 骨架 / T6 网格 / T7a 曲线分类)。 +// 见 docs/reference/steps/M0-gr2-reader.md +// 规格:granny_file_info.cpp (FileInfoType) / granny_animation.cpp (AnimationType) +#include "internal.h" +#include +#include + +namespace gr2 { + +using detail::Ref; +using detail::TypeMember; + +bool File::Impl::build_fileinfo(FileInfo& out, LoadError* err) { + if (!root_obj.valid() || !root_type.valid()) { + if (err) *err = {"fileinfo", "no root object / type"}; + return false; + } + const auto& rms = parse_type(root_type); + if (rms.empty()) { + if (err) *err = {"fileinfo", "root type has no members"}; + return false; + } + + auto count_of = [&](const char* name) -> uint32_t { + const TypeMember* m = find_member(rms, name); + if (!m) return 0; + int32_t c = rd_i32(member_slot(root_obj, *m)); + return (c > 0 && c < (1 << 24)) ? uint32_t(c) : 0; + }; + + if (const TypeMember* m = find_member(rms, "FromFileName")) + out.from_file_name = rd_str(member_slot(root_obj, *m)); + + out.texture_count = count_of("Textures"); + out.material_count = count_of("Materials"); + out.model_count = count_of("Models"); + + // ── 材质图:root Materials[] 先入表(索引 = 文件顺序),子材质 / 只经 mesh 可达的追加 ── + mats_out = &out.materials; + mat_refs.clear(); + if (const TypeMember* mMa = find_member(rms, "Materials")) { + auto refs = read_array_of_refs(root_obj, *mMa); + for (Ref r : refs) intern_material(r, mMa->ref_type); + } + + // ── 骨架(T5)──────────────────────────────────────────────────── + skels_cache.clear(); + skel_refs.clear(); + if (const TypeMember* mSk = find_member(rms, "Skeletons")) { + auto refs = read_array_of_refs(root_obj, *mSk); + for (Ref r : refs) { + Skeleton sk; + if (extract_skeleton(r, mSk->ref_type, sk)) { + skels_cache.push_back(std::move(sk)); + skel_refs.push_back(r); + } + } + } + + // ── 模型 → 骨架关联:把 model.InitialPlacement 写进对应 skeleton ───── + // (很多 Metin2 骨架把 model 空间偏移放在 InitialPlacement 而非 root 骨骼的 + // LocalTransform;不带上它,bind pose 自洽检查会对这些文件失败) + if (const TypeMember* mMo = find_member(rms, "Models")) { + auto refs = read_array_of_refs(root_obj, *mMo); + const auto& moms = parse_type(mMo->ref_type); + const TypeMember* mSkRef = find_member(moms, "Skeleton"); + const TypeMember* mIP = find_member(moms, "InitialPlacement"); + for (Ref r : refs) { + if (!r.valid() || !mSkRef) continue; + Ref sref = read_reference(r, *mSkRef); + for (size_t k = 0; k < skel_refs.size(); ++k) { + if (skel_refs[k].section == sref.section && skel_refs[k].offset == sref.offset) { + if (mIP) { + uint32_t fl = 0; + transform_to_composite(member_slot(r, *mIP), skels_cache[k].initial_placement, fl); + } + break; + } + } + } + } + out.skeletons = skels_cache; + + // ── 网格(T6)──────────────────────────────────────────────────── + std::vector mesh_refs; // 与 out.meshes 平行(model.MeshBindings 关联用) + if (const TypeMember* mMe = find_member(rms, "Meshes")) { + auto refs = read_array_of_refs(root_obj, *mMe); + for (Ref r : refs) { + Mesh me; + bool ok = extract_mesh(r, mMe->ref_type, skels_cache, me); + if (getenv("GR2_DEBUG")) + fprintf(stderr, "[gr2] mesh ref (%d,%u) -> %s name=%s verts=%zu idx=%zu\n", + r.section, r.offset, ok ? "OK" : "FAIL", me.name.c_str(), + me.vertices.size(), me.indices.size()); + if (ok) { out.meshes.push_back(std::move(me)); mesh_refs.push_back(r); } + } + } + + // ── 模型:granny_model{String Name; Reference Skeleton; Transform InitialPlacement; + // RefToArray MeshBindings(model_mesh_binding{Reference Mesh}); VariantRef ExtendedData} + if (const TypeMember* mMo = find_member(rms, "Models")) { + auto refs = read_array_of_refs(root_obj, *mMo); + const auto& moms = parse_type(mMo->ref_type); + const TypeMember* mN = find_member(moms, "Name"); + const TypeMember* mSk = find_member(moms, "Skeleton"); + const TypeMember* mIP = find_member(moms, "InitialPlacement"); + const TypeMember* mMB = find_member(moms, "MeshBindings"); + auto same = [](Ref a, Ref b) { return a.section == b.section && a.offset == b.offset; }; + for (Ref r : refs) { + if (!r.valid()) continue; + Model mo; + if (mN) mo.name = rd_str(member_slot(r, *mN)); + if (mSk) { + Ref sref = read_reference(r, *mSk); + for (size_t k = 0; k < skel_refs.size(); ++k) + if (same(skel_refs[k], sref)) { mo.skeleton = int32_t(k); break; } + } + if (mIP) read_transform(member_slot(r, *mIP), mo.initial_placement); + Ref bb; uint32_t bc = 0, bs = 0; + if (mMB && read_ref_to_array(r, *mMB, bb, bc, bs) && bc && bs) { + const auto& bms = parse_type(mMB->ref_type); + const TypeMember* mMesh = find_member(bms, "Mesh"); + for (uint32_t i = 0; i < bc && i < 4096; ++i) { + int32_t idx = -1; + if (mMesh) { + Ref me = read_reference({bb.section, bb.offset + i * bs}, *mMesh); + for (size_t k = 0; k < mesh_refs.size(); ++k) + if (same(mesh_refs[k], me)) { idx = int32_t(k); break; } + } + mo.mesh_bindings.push_back(idx); + } + } + out.models.push_back(std::move(mo)); + } + } + + // ── 动画(T7a:名字 + 时长 + 每 track 的曲线子类型)───────────────── + if (const TypeMember* mAn = find_member(rms, "Animations")) { + auto refs = read_array_of_refs(root_obj, *mAn); + const Skeleton* sk0 = skels_cache.empty() ? nullptr : &skels_cache[0]; + for (Ref r : refs) { + if (!r.valid()) continue; + Animation an; + if (extract_animation(r, mAn->ref_type, sk0, an)) + out.animations.push_back(std::move(an)); + } + } + + mats_out = nullptr; + return true; +} + +} // namespace gr2 diff --git a/gr2/src/gr2_material.cpp b/gr2/src/gr2_material.cpp new file mode 100644 index 0000000..e500436 --- /dev/null +++ b/gr2/src/gr2_material.cpp @@ -0,0 +1,123 @@ +// libgr2 —— 材质视图(附加,不改动既有解析)。 +// root.Materials (ArrayOfReferences) → granny_material: +// Name (String) +// Texture (Reference → granny_texture{ FromFileName (String) }) +// Maps (RefToArray → granny_material_map{ Usage (String); Material (Reference → granny_material) }) +// diffuse 取 Usage 含 "diffuse" 的 map,退而取第一张贴图。 +#include "gr2/gr2.h" +#include "internal.h" + +#include +#include + +namespace gr2 { + +using detail::TypeMember; +using Ref = detail::Ref; + +namespace { + +std::string lower(std::string s) { + for (auto& c : s) c = char(std::tolower((unsigned char)c)); + return s; +} + +// helpers 用 `auto&` 模板参数,避免命名私有的 File::Impl(只有 dump_materials 是 friend)。 + +// 从一个 granny_texture 对象读 FromFileName。 +std::string read_texture_name(auto& im, Ref tex_obj, Ref tex_type) { + if (!tex_obj.valid() || !tex_type.valid()) return {}; + const auto& ms = im.parse_type(tex_type); + if (const TypeMember* m = im.find_member(ms, "FromFileName")) + return im.rd_str(im.member_slot(tex_obj, *m)); + return {}; +} + +struct WalkState { + MaterialInfo* out; + std::vector encounter; // 按遇到顺序 + std::string diffuse; // 首个 Usage~=diffuse 的贴图 +}; + +// 递归遍历一个 granny_material,收集 FromFileName。 +void walk_material(auto& im, Ref mat_obj, Ref mat_type, int depth, + WalkState& st, bool parent_is_diffuse) { + if (depth > 4 || !mat_obj.valid() || !mat_type.valid()) return; + const auto& ms = im.parse_type(mat_type); + + if (st.out->name.empty()) { + if (const TypeMember* mn = im.find_member(ms, "Name")) + st.out->name = im.rd_str(im.member_slot(mat_obj, *mn)); + } + + if (const TypeMember* mt = im.find_member(ms, "Texture")) { + Ref tex = im.read_reference(mat_obj, *mt); + std::string fn = read_texture_name(im, tex, mt->ref_type); + if (!fn.empty()) { + st.encounter.push_back(fn); + if (parent_is_diffuse && st.diffuse.empty()) st.diffuse = fn; + } + } + + if (const TypeMember* mm = im.find_member(ms, "Maps")) { + Ref base; + uint32_t count = 0, stride = 0; + if (im.read_ref_to_array(mat_obj, *mm, base, count, stride) && count && stride) { + const auto& map_ms = im.parse_type(mm->ref_type); + const TypeMember* mu = im.find_member(map_ms, "Usage"); + const TypeMember* msub = im.find_member(map_ms, "Material"); + for (uint32_t i = 0; i < count && i < 64; ++i) { + Ref map_obj{ base.section, base.offset + i * stride }; + bool is_diffuse = parent_is_diffuse; + if (mu) { + std::string u = lower(im.rd_str(im.member_slot(map_obj, *mu))); + is_diffuse = u.find("diffuse") != std::string::npos || u.empty(); + } + if (msub) { + Ref sub = im.read_reference(map_obj, *msub); + walk_material(im, sub, msub->ref_type, depth + 1, st, is_diffuse); + } + } + } + } +} + +} // namespace + +std::vector dump_materials(const File& f) { + std::vector out; + if (!f.impl_ || !f.impl_->root_type.valid() || !f.impl_->root_obj.valid()) return out; + + File::Impl& im = *f.impl_; + const auto& root_ms = im.parse_type(im.root_type); + const TypeMember* mats = im.find_member(root_ms, "Materials"); + if (!mats) return out; + + std::vector mat_refs = im.read_array_of_refs(im.root_obj, *mats); + out.reserve(mat_refs.size()); + for (Ref mr : mat_refs) { + MaterialInfo mi; + WalkState st{ &mi, {}, {} }; + walk_material(im, mr, mats->ref_type, 0, st, /*parent_is_diffuse=*/true); + + mi.diffuse_texture = !st.diffuse.empty() ? st.diffuse + : (st.encounter.empty() ? std::string{} : st.encounter.front()); + mi.map_count = (int)st.encounter.size(); + mi.all_textures = st.encounter; + std::sort(mi.all_textures.begin(), mi.all_textures.end()); + mi.all_textures.erase(std::unique(mi.all_textures.begin(), mi.all_textures.end()), + mi.all_textures.end()); + + // 渲染态推断(EterGrnLib Material.cpp 的名字/map 逻辑) + std::string ln = lower(mi.name); + mi.alpha_blend = ln.rfind("blend", 0) == 0 && mi.map_count > 1; + for (const char* kw : {"2side", "twoside", "two_side", "double", "leaf", "tree", + "ivy", "fence", "grass", "branch", "flag"}) + if (ln.find(kw) != std::string::npos) { mi.two_sided = true; break; } + + out.push_back(std::move(mi)); + } + return out; +} + +} // namespace gr2 diff --git a/gr2/src/gr2_mesh.cpp b/gr2/src/gr2_mesh.cpp new file mode 100644 index 0000000..5dd2e3d --- /dev/null +++ b/gr2/src/gr2_mesh.cpp @@ -0,0 +1,379 @@ +// M0 T6 —— 顶点 / 索引 / 三角组 / BoneBindings。见 docs/reference/steps/M0-gr2-reader.md +// 规格:granny_mesh.cpp (MeshType/BoneBindingType) / granny_vertex_data.cpp (VertexDataType +// + 各顶点格式) / granny_tri_topology.cpp (TriTopologyType/TriMaterialGroupType) +// 顶点格式是自描述的(Vertices 是 ReferenceToVariantArray,带 data_type_definition*), +// 按成员名(Position/Normal/TextureCoordinates0/1/BoneWeights/BoneIndices)取分量,不硬编码布局。 +#include "internal.h" +#include +#include +#include +#include + +#define MDBG(...) do { if (getenv("GR2_DEBUG")) fprintf(stderr, "[mesh] " __VA_ARGS__); } while (0) + +namespace gr2 { + +using detail::Ref; +using detail::TypeMember; + +namespace { + +// member_type → (元素是浮点?, 元素字节数, 是否归一化整型) +struct Elem { bool is_float; int bytes; bool normalized; bool is_signed; }; +Elem elem_of(int mt) { + switch (mt) { + case detail::MT_Real32: return {true, 4, false, true}; + case detail::MT_Real16: return {false, 2, false, true}; // 半精度,少见,按需扩展 + case detail::MT_Int8: return {false, 1, false, true}; + case detail::MT_UInt8: return {false, 1, false, false}; + case detail::MT_BinormInt8: return {false, 1, true, true}; + case detail::MT_NormUInt8: return {false, 1, true, false}; + case detail::MT_Int16: return {false, 2, false, true}; + case detail::MT_UInt16: return {false, 2, false, false}; + case detail::MT_BinormInt16: return {false, 2, true, true}; + case detail::MT_NormUInt16: return {false, 2, true, false}; + case detail::MT_Int32: return {false, 4, false, true}; + case detail::MT_UInt32: return {false, 4, false, false}; + default: return {false, 0, false, false}; + } +} + +float read_scalar(const uint8_t* p, const Elem& e) { + switch (e.bytes) { + case 4: + if (e.is_float) { float v; std::memcpy(&v, p, 4); return v; } + if (e.is_signed) { int32_t v; std::memcpy(&v, p, 4); return float(v); } + { uint32_t v; std::memcpy(&v, p, 4); return float(v); } + case 2: { + if (e.is_signed) { int16_t v; std::memcpy(&v, p, 2); return e.normalized ? v / 32767.0f : float(v); } + uint16_t v; std::memcpy(&v, p, 2); return e.normalized ? v / 65535.0f : float(v); + } + case 1: { + if (e.is_signed) { int8_t v = (int8_t)p[0]; return e.normalized ? v / 127.0f : float(v); } + return e.normalized ? p[0] / 255.0f : float(p[0]); + } + default: return 0.0f; + } +} + +} // namespace + +// mesh: {String Name; Reference PrimaryVertexData; RefToArray MorphTargets; +// Reference PrimaryTopology; RefToArray MaterialBindings; RefToArray BoneBindings; ...} +bool File::Impl::extract_mesh(Ref mesh_obj, Ref mesh_type, + const std::vector& skels, Mesh& out) { + if (!mesh_obj.valid() || !mesh_type.valid()) return false; + const auto& mms = parse_type(mesh_type); + if (getenv("GR2_DEBUG")) { + fprintf(stderr, "[mesh] mesh_type=(%d,%u) members=%zu:\n", + mesh_type.section, mesh_type.offset, mms.size()); + for (auto& m : mms) + fprintf(stderr, "[mesh] %-20s type=%d aw=%d off=%u size=%u reftype=(%d,%u)\n", + m.name.c_str(), m.type, m.array_width, m.offset, m.size, + m.ref_type.section, m.ref_type.offset); + } + + if (const TypeMember* mName = find_member(mms, "Name")) + out.name = rd_str(member_slot(mesh_obj, *mName)); + + // ── 顶点 ────────────────────────────────────────────────────────── + const TypeMember* mVD = find_member(mms, "PrimaryVertexData"); + if (!mVD) { MDBG("no PrimaryVertexData member\n"); return false; } + MDBG("PrimaryVertexData m.offset=%u ref_type=(%d,%u)\n", + mVD->offset, mVD->ref_type.section, mVD->ref_type.offset); + Ref vd = read_reference(mesh_obj, *mVD); + if (!vd.valid()) { MDBG("PrimaryVertexData ref -> NULL (slot %d,%u)\n", + member_slot(mesh_obj, *mVD).section, member_slot(mesh_obj, *mVD).offset); return false; } + + const auto& vdms = parse_type(mVD->ref_type); + const TypeMember* mVerts = find_member(vdms, "Vertices"); + if (!mVerts) { MDBG("no Vertices member (vdms=%zu)\n", vdms.size()); return false; } + // ReferenceToVariantArray on-disk: {def* Type; int32 Count; void* Ptr}, packed + // (granny_data_type_definition.cpp: Ptr + int32 + Ptr; ptr = 4 or 8 bytes) + Ref vslot = member_slot(vd, *mVerts); + Ref vtype = follow({vslot.section, vslot.offset + 0}); + int32_t vcount = rd_i32({vslot.section, vslot.offset + ptr}); + Ref vdata = follow({vslot.section, vslot.offset + ptr + 4}); + MDBG("Vertices count=%d vtype=(%d,%u) vdata=(%d,%u)\n", + vcount, vtype.section, vtype.offset, vdata.section, vdata.offset); + if (vcount <= 0 || vcount > (1 << 24) || !vtype.valid() || !vdata.valid()) return false; + + const auto& vfmt = parse_type(vtype); + uint32_t stride = 0; + for (const auto& m : vfmt) stride += m.size; + MDBG("vfmt members=%zu stride=%u\n", vfmt.size(), stride); + if (stride == 0) return false; + + struct Comp { const TypeMember* m; Elem e; }; + auto comp = [&](const char* n) -> Comp { + const TypeMember* m = find_member(vfmt, n); + if (!m) return {nullptr, {}}; + return {m, elem_of(m->type)}; + }; + Comp cPos = comp("Position"); + Comp cNrm = comp("Normal"); + Comp cUv0 = comp("TextureCoordinates0"); + Comp cUv1 = comp("TextureCoordinates1"); + Comp cBW = comp("BoneWeights"); + Comp cBI = comp("BoneIndices"); + + const bool skinned = (cBW.m && cBI.m); + out.rigid = !skinned; + if (skinned) { + out.source_bone_weight_slots = uint32_t(cBW.m->array_width > 0 ? cBW.m->array_width : 1); + out.source_bone_index_slots = (cBI.e.bytes == 4 && cBI.m->array_width <= 1) + ? 4u + : uint32_t(cBI.m->array_width > 0 ? cBI.m->array_width : 1); + } + if (skinned && cUv1.m) out.kind = VertexKind::PNT3322_Skinned; + else if (skinned) out.kind = VertexKind::PNT332_Skinned; + else if (cUv1.m) out.kind = VertexKind::PNT3322; + else if (cPos.m && cNrm.m) out.kind = VertexKind::PNT332; + else out.kind = VertexKind::Unknown; + + if ((uint64_t)vdata.offset + (uint64_t)vcount * stride > sections[vdata.section].data.size()) + return false; + + out.vertex_stride = stride; + for (const auto& m : vfmt) + out.vertex_members.push_back({m.name, m.type, m.array_width, m.offset}); + { + const uint8_t* vb = sections[vdata.section].data.data() + vdata.offset; + out.raw_vertices.assign(vb, vb + size_t(vcount) * stride); + } + out.vertices.resize(vcount); + for (int32_t i = 0; i < vcount; ++i) { + const uint8_t* base = sections[vdata.section].data.data() + vdata.offset + size_t(i) * stride; + Vertex& v = out.vertices[i]; + auto rd = [&](const Comp& c, float* dst, int n) { + if (!c.m || !c.e.bytes) return; + int aw = c.m->array_width <= 0 ? 1 : c.m->array_width; + n = n < aw ? n : aw; + for (int k = 0; k < n; ++k) + dst[k] = read_scalar(base + c.m->offset + size_t(k) * c.e.bytes, c.e); + }; + rd(cPos, v.pos, 3); + rd(cNrm, v.normal, 3); + rd(cUv0, v.uv0, 2); + rd(cUv1, v.uv1, 2); + if (skinned) { + float w[4] = {0,0,0,0}, bi[4] = {0,0,0,0}; + rd(cBW, w, 4); + // BoneIndices 可能是 UInt8[4] 或 UInt32[N](PWN* 系列是单 uint32 packed 4×u8) + if (cBI.e.bytes == 1) { + rd(cBI, bi, 4); + } else if (cBI.e.bytes == 4 && cBI.e.is_float == false) { + uint32_t packed; + std::memcpy(&packed, base + cBI.m->offset, 4); + for (int k = 0; k < 4; ++k) bi[k] = float((packed >> (k * 8)) & 0xff); + } + for (int k = 0; k < 4; ++k) { + v.bone_index[k] = uint8_t(std::lround(bi[k])); + float wn = cBW.e.normalized ? w[k] : w[k]; // 已在 read_scalar 归一 + v.bone_weight[k] = uint8_t(std::lround(std::fmin(std::fmax(wn, 0.0f), 1.0f) * 255.0f)); + } + } + } + + // ── 索引 + 三角组 ──────────────────────────────────────────────── + const TypeMember* mTopo = find_member(mms, "PrimaryTopology"); + if (mTopo) { + Ref tt = read_reference(mesh_obj, *mTopo); + if (tt.valid()) { + const auto& tms = parse_type(mTopo->ref_type); + if (const TypeMember* mG = find_member(tms, "Groups")) { + Ref gb; uint32_t gc = 0, gs = 0; + if (read_ref_to_array(tt, *mG, gb, gc, gs) && gc) { + const auto& gmT = parse_type(mG->ref_type); + const TypeMember* mMI = find_member(gmT, "MaterialIndex"); + const TypeMember* mTF = find_member(gmT, "TriFirst"); + const TypeMember* mTC = find_member(gmT, "TriCount"); + for (uint32_t i = 0; i < gc; ++i) { + Ref g = {gb.section, gb.offset + i * gs}; + TriGroup tg{}; + if (mMI) tg.material_index = rd_i32(member_slot(g, *mMI)); + if (mTF) tg.tri_first = rd_i32(member_slot(g, *mTF)); + if (mTC) tg.tri_count = rd_i32(member_slot(g, *mTC)); + out.tri_groups.push_back(tg); + } + } + } + auto load_idx = [&](const char* name, int elem_bytes) -> bool { + const TypeMember* mI = find_member(tms, name); + if (!mI) return false; + Ref ib; uint32_t ic = 0, is = 0; + if (!read_ref_to_array(tt, *mI, ib, ic, is) || ic == 0) return false; + const uint8_t* p = at(ib, size_t(ic) * elem_bytes); + if (!p) return false; + out.indices.resize(ic); + for (uint32_t i = 0; i < ic; ++i) { + if (elem_bytes == 2) { uint16_t v; std::memcpy(&v, p + i*2, 2); out.indices[i] = v; } + else { uint32_t v; std::memcpy(&v, p + i*4, 4); out.indices[i] = v; } + } + return true; + }; + if (!load_idx("Indices", 4)) load_idx("Indices16", 2); + } + } + + // ── MaterialBindings:与 tri_group.material_index 平行的贴图名表 ─── + // granny_mesh.MaterialBindings = RefToArray of {Reference Material}。 + if (const TypeMember* mMB = find_member(mms, "MaterialBindings")) { + Ref mb; uint32_t mc = 0, ms = 0; + if (read_ref_to_array(mesh_obj, *mMB, mb, mc, ms) && mc) { + const auto& bT = parse_type(mMB->ref_type); + const TypeMember* mMat = find_member(bT, "Material"); + out.material_textures.reserve(mc); + for (uint32_t i = 0; i < mc; ++i) { + Ref e = {mb.section, mb.offset + i * ms}; + std::string tn; + int32_t mi = -1; + if (mMat) { + Ref mat = read_reference(e, *mMat); + tn = material_texture_name(mat, mMat->ref_type, 0); + mi = intern_material(mat, mMat->ref_type); + } + out.material_textures.push_back(std::move(tn)); + out.material_bindings.push_back(mi); + } + } + } + + // ── BoneBindings:mesh 局部骨骼槽 → skeleton 骨骼索引 ───────────── + // 文件可能带多个 skeleton(本体 + 武器挂点等)。对每个 skeleton 试解析, + // 取"悬空最少"的那个。 + if (const TypeMember* mBB = find_member(mms, "BoneBindings")) { + Ref bb; uint32_t bc = 0, bs = 0; + if (read_ref_to_array(mesh_obj, *mBB, bb, bc, bs) && bc) { + const auto& bbT = parse_type(mBB->ref_type); + const TypeMember* mBN = find_member(bbT, "BoneName"); + const TypeMember* mMin = find_member(bbT, "OBBMin"); + const TypeMember* mMax = find_member(bbT, "OBBMax"); + out.bone_bounds.resize(bc); + std::vector names(bc); + for (uint32_t i = 0; i < bc; ++i) { + Ref e = {bb.section, bb.offset + i * bs}; + names[i] = mBN ? rd_str(member_slot(e, *mBN)) : std::string(); + auto &bounds = out.bone_bounds[i]; + if (mMin && mMax && mMin->type == detail::MT_Real32 && mMax->type == detail::MT_Real32 && mMin->array_width == 3 && mMax->array_width == 3) { + Ref lo = member_slot(e, *mMin), hi = member_slot(e, *mMax); + bounds.valid = true; + for (int axis = 0; axis < 3; ++axis) { + bounds.min[axis] = rd_f32({lo.section, lo.offset + uint32_t(axis * 4)}); + bounds.max[axis] = rd_f32({hi.section, hi.offset + uint32_t(axis * 4)}); + bounds.valid &= std::isfinite(bounds.min[axis]) && std::isfinite(bounds.max[axis]) && bounds.min[axis] <= bounds.max[axis]; + } + } + } + std::vector best(bc, -1); + int best_dangling = int(bc) + 1; + for (const auto& sk : skels) { + std::vector cur(bc, -1); + int dangling = 0; + for (uint32_t i = 0; i < bc; ++i) { + for (size_t k = 0; k < sk.bones.size(); ++k) + if (sk.bones[k].name == names[i]) { cur[i] = int32_t(k); break; } + if (cur[i] < 0) ++dangling; + } + if (dangling < best_dangling) { best_dangling = dangling; best = cur; } + if (dangling == 0) break; + } + out.bone_bindings = std::move(best); + out.bone_binding_names = std::move(names); + } + } + return true; +} + +// granny_material {String Name; int MapCount; material_map* Maps; texture* Texture; ...} +// granny_material_map {String Usage; material* Material} +// granny_texture {String FromFileName; ...} +std::string File::Impl::material_texture_name(Ref mat_obj, Ref mat_type, int depth) { + if (!mat_obj.valid() || !mat_type.valid() || depth > 8) return {}; + const auto& mms = parse_type(mat_type); + + // 1) 直接挂 texture + if (const TypeMember* mTex = find_member(mms, "Texture")) { + Ref tex = read_reference(mat_obj, *mTex); + if (tex.valid()) { + const auto& tms = parse_type(mTex->ref_type); + if (const TypeMember* mFN = find_member(tms, "FromFileName")) { + std::string s = rd_str(member_slot(tex, *mFN)); + if (!s.empty()) return s; + } + } + } + // 2) 递归 Maps[].Map(复合材质:granny_material_map = {String Usage; material* Map}) + if (const TypeMember* mMaps = find_member(mms, "Maps")) { + Ref b; uint32_t c = 0, s = 0; + if (read_ref_to_array(mat_obj, *mMaps, b, c, s) && c) { + const auto& mapT = parse_type(mMaps->ref_type); + const TypeMember* mSub = find_member(mapT, "Map"); + if (!mSub) mSub = find_member(mapT, "Material"); + for (uint32_t i = 0; i < c && mSub; ++i) { + Ref e = {b.section, b.offset + i * s}; + Ref sub = read_reference(e, *mSub); + std::string r = material_texture_name(sub, mSub->ref_type, depth + 1); + if (!r.empty()) return r; + } + } + } + return {}; +} + +// granny_material {String Name; RefToArray Maps(material_map{String Usage; Reference Material}); +// Reference Texture; VariantRef ExtendedData} +int32_t File::Impl::intern_material(Ref mat_obj, Ref mat_type, int depth) { + if (!mats_out || !mat_obj.valid() || !mat_type.valid() || depth > 8) return -1; + for (size_t k = 0; k < mat_refs.size(); ++k) + if (mat_refs[k].section == mat_obj.section && mat_refs[k].offset == mat_obj.offset) + return int32_t(k); + + const int32_t idx = int32_t(mats_out->size()); + mats_out->emplace_back(); + mat_refs.push_back(mat_obj); + + const auto& mms = parse_type(mat_type); + Material mat; + if (const TypeMember* m = find_member(mms, "Name")) mat.name = rd_str(member_slot(mat_obj, *m)); + mat.diffuse_texture = material_texture_name(mat_obj, mat_type, 0); + if (const TypeMember* mTex = find_member(mms, "Texture")) { + Ref tex = read_reference(mat_obj, *mTex); + if (tex.valid()) + if (const TypeMember* mFN = find_member(parse_type(mTex->ref_type), "FromFileName")) + mat.texture = rd_str(member_slot(tex, *mFN)); + } + if (const TypeMember* mE = find_member(mms, "ExtendedData")) + mat.has_two_sided = extended_i32(member_slot(mat_obj, *mE), "Two-sided", mat.two_sided); + if (const TypeMember* mMaps = find_member(mms, "Maps")) { + Ref b; uint32_t c = 0, s = 0; + if (read_ref_to_array(mat_obj, *mMaps, b, c, s) && c && s) { + const auto& mapT = parse_type(mMaps->ref_type); + const TypeMember* mU = find_member(mapT, "Usage"); + const TypeMember* mSub = find_member(mapT, "Material"); + if (!mSub) mSub = find_member(mapT, "Map"); + for (uint32_t i = 0; i < c && i < 64; ++i) { + Ref e = {b.section, b.offset + i * s}; + MaterialMap mm; + if (mU) mm.usage = rd_str(member_slot(e, *mU)); + if (mSub) mm.material = intern_material(read_reference(e, *mSub), mSub->ref_type, depth + 1); + mat.maps.push_back(std::move(mm)); + } + } + } + (*mats_out)[idx] = std::move(mat); + return idx; +} + +// VariantRef = {ptr Type; ptr Object}(ptr = 4 或 8 字节)。 +bool File::Impl::extended_i32(Ref slot, const char* name, int32_t& out) { + Ref type = follow(slot); + Ref obj = follow({slot.section, slot.offset + ptr}); + if (!type.valid() || !obj.valid()) return false; + const TypeMember* m = find_member(parse_type(type), name); + if (!m || (m->type != detail::MT_Int32 && m->type != detail::MT_UInt32)) return false; + out = rd_i32(member_slot(obj, *m)); + return true; +} + +} // namespace gr2 diff --git a/gr2/src/gr2_skeleton.cpp b/gr2/src/gr2_skeleton.cpp new file mode 100644 index 0000000..6cca011 --- /dev/null +++ b/gr2/src/gr2_skeleton.cpp @@ -0,0 +1,238 @@ +// M0 T5 —— 骨架提取 + bind pose 自洽检查。见 docs/reference/steps/M0-gr2-reader.md +// 规格:granny_transform.cpp BuildCompositeTransform4x4 / granny_math.cpp +// MatrixEqualsQuaternion3x3 + MatrixMultiply3x3 / +// granny_matrix_operations.cpp ColumnMatrixMultiply4x3Impl / +// granny_world_pose.cpp BuildWorldPoseNoCompositeLOD + granny_bone_operations.cpp +// BuildFullWorldPoseOnly_Generic +#include "internal.h" +#include +#include +#include +#include + +namespace gr2 { + +using detail::Ref; +using detail::TypeMember; + +namespace { + +// 行主序 4x4:R = A * B(ColumnMatrixMultiply4x3Impl 语义,平移在第 3 行 elem 12..14) +Mat4 mul4x3(const Mat4& A, const Mat4& B) { + Mat4 R{}; + for (int i = 0; i < 3; ++i) { + for (int k = 0; k < 3; ++k) + R[i * 4 + k] = A[i * 4 + 0] * B[0 * 4 + k] + + A[i * 4 + 1] * B[1 * 4 + k] + + A[i * 4 + 2] * B[2 * 4 + k]; + R[i * 4 + 3] = 0.0f; + } + for (int k = 0; k < 3; ++k) + R[12 + k] = A[12] * B[0 * 4 + k] + + A[13] * B[1 * 4 + k] + + A[14] * B[2 * 4 + k] + + B[12 + k]; + R[15] = 1.0f; + return R; +} + +// granny_math.cpp MatrixEqualsQuaternion3x3(行主序 3x3) +void quat_to_m3(const float q[4], float d[9]) { + const float xx = q[0] * q[0], yy = q[1] * q[1], zz = q[2] * q[2]; + const float xy = q[0] * q[1], xz = q[0] * q[2], yz = q[1] * q[2]; + const float wx = q[3] * q[0], wy = q[3] * q[1], wz = q[3] * q[2]; + d[0] = 1 - 2 * (yy + zz); d[1] = 2 * (xy - wz); d[2] = 2 * (xz + wy); + d[3] = 2 * (xy + wz); d[4] = 1 - 2 * (xx + zz); d[5] = 2 * (yz - wx); + d[6] = 2 * (xz - wy); d[7] = 2 * (yz + wx); d[8] = 1 - 2 * (xx + yy); +} + +void m3_mul(const float a[9], const float b[9], float r[9]) { + for (int i = 0; i < 3; ++i) + for (int j = 0; j < 3; ++j) + r[i * 3 + j] = a[i * 3 + 0] * b[0 * 3 + j] + + a[i * 3 + 1] * b[1 * 3 + j] + + a[i * 3 + 2] * b[2 * 3 + j]; +} + +} // namespace + +// granny_transform (68B: u32 Flags; f32 Position[3]; f32 Orientation[4]; f32 ScaleShear[3][3]) +void File::Impl::read_transform(Ref tf, Transform& out) const { + out = Transform{}; + const uint8_t* p = at(tf, 68); + if (!p) return; + std::memcpy(&out.flags, p, 4); + std::memcpy(out.position, p + 4, 12); + std::memcpy(out.orientation, p + 16, 16); + std::memcpy(out.scale_shear, p + 32, 36); +} + +// → 行主序 4x4,上 3x3 = transpose(U3),平移在 elem 12..14。BuildCompositeTransform4x4 语义。 +Mat4 compose(const Transform& t) { + float q3[9]; + quat_to_m3(t.orientation, q3); + float u3[9]; + if (t.flags & 0x4 /* HasScaleShear */) m3_mul(q3, t.scale_shear, u3); + else std::memcpy(u3, q3, sizeof u3); + + Mat4 out{}; + // C 的上 3x3 = transpose(U3) + out[0] = u3[0]; out[1] = u3[3]; out[2] = u3[6]; out[3] = 0; + out[4] = u3[1]; out[5] = u3[4]; out[6] = u3[7]; out[7] = 0; + out[8] = u3[2]; out[9] = u3[5]; out[10] = u3[8]; out[11] = 0; + out[12] = t.position[0]; out[13] = t.position[1]; out[14] = t.position[2]; out[15] = 1; + return out; +} + +void File::Impl::transform_to_composite(Ref tf, Mat4& out, uint32_t& flags) const { + Transform t; + read_transform(tf, t); + if (!at(tf, 68)) { + out = Mat4{1,0,0,0, 0,1,0,0, 0,0,1,0, 0,0,0,1}; + flags = 0; + return; + } + out = compose(t); + flags = t.flags; +} + +// skeleton: {String Name; RefToArray Bones(bone[]); int32 LODType; VariantRef ExtendedData} +// bone: {String Name; int32 ParentIndex; Transform LocalTransform; +// Real32[16] InverseWorldTransform; Real32 LODError; VariantRef ExtendedData} +// 全程按类型树取偏移,不硬编码。 +bool File::Impl::extract_skeleton(Ref skel_obj, Ref skel_type, Skeleton& out) { + out.bones.clear(); + if (!skel_obj.valid() || !skel_type.valid()) return false; + + const auto& sms = parse_type(skel_type); + const TypeMember* mBones = find_member(sms, "Bones"); + if (!mBones) return false; + + Ref bones_base; + uint32_t bone_count = 0, stride = 0; + if (!read_ref_to_array(skel_obj, *mBones, bones_base, bone_count, stride)) return false; + if (bone_count == 0) return false; + if (bone_count > 8192 || stride == 0) return false; + + const auto& bms = parse_type(mBones->ref_type); + const TypeMember* mName = find_member(bms, "Name"); + const TypeMember* mParent = find_member(bms, "ParentIndex"); + const TypeMember* mLocal = find_member(bms, "LocalTransform"); + if (!mLocal) mLocal = find_member(bms, "Transform"); + const TypeMember* mInvW = find_member(bms, "InverseWorldTransform"); + if (!mInvW) mInvW = find_member(bms, "InverseWorld4x4"); + if (!mLocal || !mInvW) return false; + + out.bones.resize(bone_count); + for (uint32_t i = 0; i < bone_count; ++i) { + Ref b = { bones_base.section, bones_base.offset + i * stride }; + Bone& bo = out.bones[i]; + if (mName) bo.name = rd_str(member_slot(b, *mName)); + if (mParent) bo.parent = rd_i32(member_slot(b, *mParent)); + read_transform(member_slot(b, *mLocal), bo.local); + bo.local_transform = compose(bo.local); + bo.lt_flags = bo.local.flags; + const uint8_t* iw = at(member_slot(b, *mInvW), 64); + if (iw) for (int k = 0; k < 16; ++k) std::memcpy(&bo.inverse_world[k], iw + k * 4, 4); + else bo.inverse_world = Mat4{}; + } + return true; +} + +// ── M2:姿势采样(自由函数 = 主 primitive;File::* 是便捷封装)────────── +namespace { +void accumulate_world(const Skeleton& sk, const std::vector& local, + std::vector& world, std::vector& skin, + const Mat4& root_offset) { + const size_t n = sk.bones.size(); + const Mat4 I{1,0,0,0, 0,1,0,0, 0,0,1,0, 0,0,0,1}; + world.assign(n, I); + skin.assign(n, I); + for (size_t i = 0; i < n; ++i) { + int32_t par = sk.bones[i].parent; + const Mat4& parent_w = (par < 0 || (size_t)par >= i) ? root_offset : world[par]; + world[i] = mul4x3((i < local.size()) ? local[i] : sk.bones[i].local_transform, parent_w); + skin[i] = mul4x3(sk.bones[i].inverse_world, world[i]); + } +} +} // namespace + +void bind_pose(const Skeleton& sk, std::vector& world, std::vector& skin) { + std::vector local(sk.bones.size()); + for (size_t i = 0; i < sk.bones.size(); ++i) local[i] = sk.bones[i].local_transform; + accumulate_world(sk, local, world, skin, sk.initial_placement); +} + +void sample_pose(const Skeleton& sk, const Animation& an, float t, + std::vector& world, std::vector& skin, + const Mat4* root_offset) { + std::vector track_local; + an.sample_local(t, track_local); + + std::vector local(sk.bones.size()); + for (size_t i = 0; i < sk.bones.size(); ++i) local[i] = sk.bones[i].local_transform; // 默认 = bind + + // track 按骨骼名匹配(bone_index 若已在 anim 提取时对某个 skeleton 映射过,可能不是这个 sk) + for (size_t ti = 0; ti < an.tracks.size() && ti < track_local.size(); ++ti) { + const BoneTrack& tr = an.tracks[ti]; + int bi = -1; + for (size_t k = 0; k < sk.bones.size(); ++k) + if (sk.bones[k].name == tr.bone_name) { bi = int(k); break; } + if (bi >= 0) local[bi] = track_local[ti]; + } + accumulate_world(sk, local, world, skin, root_offset ? *root_offset : sk.initial_placement); +} + +bool File::bind_pose(int skeleton, std::vector& world, std::vector& skin) const { + if (!impl_ || skeleton < 0 || (size_t)skeleton >= impl_->skels_cache.size()) return false; + gr2::bind_pose(impl_->skels_cache[skeleton], world, skin); + return true; +} + +bool File::sample_pose(int anim, float t, int skeleton, + std::vector& world, std::vector& skin) const { + if (!impl_ || skeleton < 0 || (size_t)skeleton >= impl_->skels_cache.size()) return false; + if (anim < 0 || (size_t)anim >= info_.animations.size()) + return bind_pose(skeleton, world, skin); + gr2::sample_pose(impl_->skels_cache[skeleton], info_.animations[anim], t, world, skin); + return true; +} + +double File::Impl::skeleton_self_check(int skeleton) const { + if (skeleton < 0 || (size_t)skeleton >= skels_cache.size()) return 1e9; + const auto& sk = skels_cache[skeleton]; + const size_t n = sk.bones.size(); + if (n == 0) return 1e9; + + std::vector world(n); + double dev = 0.0; + size_t worst = 0; + for (size_t i = 0; i < n; ++i) { + int32_t par = sk.bones[i].parent; + if (par < 0 || (size_t)par >= i) { + // 根:world = local * InitialPlacement(BuildWorldPose 的 Offset4x4) + world[i] = mul4x3(sk.bones[i].local_transform, sk.initial_placement); + } else { + world[i] = mul4x3(sk.bones[i].local_transform, world[par]); + } + // E = InverseWorld * world ≈ I + Mat4 E = mul4x3(sk.bones[i].inverse_world, world[i]); + double bd = 0.0; + for (int k = 0; k < 16; ++k) { + float want = (k % 5 == 0) ? 1.0f : 0.0f; + bd = std::max(bd, (double)std::fabs(E[k] - want)); + } + if (bd > dev) { dev = bd; worst = i; } + } + if (getenv("GR2_DEBUG")) { + fprintf(stderr, "[skel] self-check dev=%.5f worst bone %zu '%s' parent=%d\n", + dev, worst, sk.bones[worst].name.c_str(), sk.bones[worst].parent); + const Mat4& E = mul4x3(sk.bones[worst].inverse_world, world[worst]); + fprintf(stderr, "[skel] E[worst]:"); + for (float x : E) fprintf(stderr, " %.3f", x); + fprintf(stderr, "\n"); + } + return dev; +} + +} // namespace gr2 diff --git a/gr2/src/gr2_typetree.cpp b/gr2/src/gr2_typetree.cpp new file mode 100644 index 0000000..bb31be2 --- /dev/null +++ b/gr2/src/gr2_typetree.cpp @@ -0,0 +1,242 @@ +// M0 T1(fixup 索引)+ T3(自描述类型树遍历)。见 docs/reference/steps/M0-gr2-reader.md +// 规格:granny_file_format.h(fixup)+ granny_data_type_definition.h/.cpp(成员类型 + stride) +#include "internal.h" +#include "bitknit2.h" +#include +#include +#include +#include + +namespace gr2 { + +using detail::Ref; +using detail::TypeMember; + +// ── member_type → 文件里的单元字节数 ────────────────────────────────── +// 序数见 internal.h MemberType。InlineMember 需递归(这里在 member_unit_size 处理)。 +// 表里是 32 位文件的值;含指针的类型按 kPtrSlots 个指针加宽(64 位文件每个指针 +4)。 +static const int8_t kUnit32[detail::MT_OnePastLast] = { + /* End */ 0, + /* Inline */ 0, /* 特判 */ + /* Reference */ 4, + /* RefToArray */ 8, /* int32 + ptr */ + /* ArrayOfRefs */ 8, + /* VariantRef */ 8, /* ptr + ptr */ + /* Removed */ 0, + /* RefToVariantArr*/ 12, /* ptr + int32 + ptr */ + /* String */ 4, + /* Transform */ 68, /* u32 flags + f32[3] + f32[4] + f32[3][3] */ + /* Real32 */ 4, + /* Int8 */ 1, + /* UInt8 */ 1, + /* BinormInt8 */ 1, + /* NormUInt8 */ 1, + /* Int16 */ 2, + /* UInt16 */ 2, + /* BinormInt16 */ 2, + /* NormUInt16 */ 2, + /* Int32 */ 4, + /* UInt32 */ 4, + /* Real16 */ 2, + /* EmptyRef */ 4, +}; +static const int8_t kPtrSlots[detail::MT_OnePastLast] = { + 0, 0, /*Reference*/ 1, /*RefToArray*/ 1, /*ArrayOfRefs*/ 1, /*VariantRef*/ 2, 0, + /*RefToVariantArray*/ 2, /*String*/ 1, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /*EmptyRef*/ 1, +}; + +// ── section 内指针 + 边界检查 ──────────────────────────────────────── +const uint8_t* File::Impl::at(Ref r, size_t need) const { + if (r.section < 0 || (size_t)r.section >= sections.size()) return nullptr; + const auto& d = sections[r.section].data; + if ((size_t)r.offset + need > d.size()) return nullptr; + return d.data() + r.offset; +} + +uint32_t File::Impl::rd_u32(Ref r) const { + const uint8_t* p = at(r, 4); + if (!p) return 0; + return uint32_t(p[0]) | (uint32_t(p[1]) << 8) | (uint32_t(p[2]) << 16) | (uint32_t(p[3]) << 24); +} +float File::Impl::rd_f32(Ref r) const { + uint32_t u = rd_u32(r); + float f; + std::memcpy(&f, &u, 4); + return f; +} + +// 解一个"指针槽":查 fixup 表;查不到 => NULL(返回 invalid Ref) +Ref File::Impl::follow(Ref slot) const { + if (slot.section < 0) return {}; + auto it = fixups.find((uint64_t(uint32_t(slot.section)) << 32) | slot.offset); + if (it == fixups.end()) return {}; + return it->second; +} + +std::string File::Impl::rd_str(Ref slot) const { + Ref s = follow(slot); + const uint8_t* p = at(s, 1); + if (!p) return {}; + const auto& d = sections[s.section].data; + size_t maxn = d.size() - s.offset; + size_t n = 0; + while (n < maxn && p[n]) ++n; + return std::string((const char*)p, n); +} + +// ── T1:建 fixup 索引 ──────────────────────────────────────────────── +// grn_pointer_fixup 数组在文件里(PointerFixupArrayOffset 从文件起点算,Count 项,每 12B)。 +// 每项 { u32 FromOffset(本 section 展开数据内偏移); u32 DestSection; u32 DestOffset }。 +// BitKnit2 section(Format==4)的 fixup 表也被压缩:偏移处是 u32 压缩长度 + BitKnit2 流, +// 解出 Count*12 字节(Granny 2.11 changelog「fixup metadata is compressed」; +// BG3ModStudio GR2Reader 同样处理)。MixedMarshalling fixup 本读取器不用,不展开。 +bool File::Impl::build_fixups(const uint8_t* file, size_t file_len, LoadError* err) { + auto le32 = [](const uint8_t* p) -> uint32_t { + return uint32_t(p[0]) | (uint32_t(p[1]) << 8) | + (uint32_t(p[2]) << 16) | (uint32_t(p[3]) << 24); + }; + fixups.clear(); + std::vector unpacked; + for (size_t si = 0; si < raw.size(); ++si) { + const GrnSection& gs = raw[si]; + if (gs.pointer_fixup_count == 0) continue; + const uint8_t* table = nullptr; + size_t count = gs.pointer_fixup_count; + size_t base = gs.pointer_fixup_off; + if (gs.compression == 4) { + if (base > file_len || file_len - base < 4) { + if (err) *err = {"fixup", "compressed fixup header out of range (section " + std::to_string(si) + ")"}; + return false; + } + const size_t csize = le32(file + base); + if (csize > file_len - base - 4 || count > SIZE_MAX / 12) { + if (err) *err = {"fixup", "compressed fixup data out of range (section " + std::to_string(si) + ")"}; + return false; + } + unpacked.assign(count * 12, 0); + if (!bitknit2_decompress(file + base + 4, csize, unpacked.data(), unpacked.size())) { + if (err) *err = {"fixup", "BitKnit2 fixup decompress failed (section " + std::to_string(si) + ")"}; + return false; + } + table = unpacked.data(); + } else { + // 未压缩:保持旧行为,越界的尾部项丢弃 + if (base > file_len) continue; + count = std::min(count, (file_len - base) / 12); + table = file + base; + } + for (size_t k = 0; k < count; ++k) { + const uint8_t* p = table + k * 12; + uint32_t from = le32(p + 0); + uint32_t dsec = le32(p + 4); + uint32_t doff = le32(p + 8); + if (dsec >= sections.size()) continue; + fixups[(uint64_t(uint32_t(si)) << 32) | from] = + Ref{int32_t(dsec), doff}; + } + } + return true; +} + +// ── T3:走 data_type_definition 数组 ───────────────────────────────── +uint32_t File::Impl::member_unit_size(const TypeMember& m) { + if (m.type == detail::MT_Inline) return object_size(m.ref_type); + if (m.type <= 0 || m.type >= detail::MT_OnePastLast) return 0; + return uint32_t(kUnit32[m.type]) + uint32_t(kPtrSlots[m.type]) * (ptr - 4); +} + +uint32_t File::Impl::object_size(Ref type_ref) { + const auto& ms = parse_type(type_ref); + uint32_t sz = 0; + for (const auto& m : ms) sz += m.size; + return sz; +} + +const std::vector& File::Impl::parse_type(Ref type_ref) { + uint64_t key = (uint64_t(uint32_t(type_ref.section)) << 32) | type_ref.offset; + auto it = type_cache.find(key); + if (it != type_cache.end()) return it->second; + + std::vector out; + // 先占位(防递归 Inline 死循环) + auto& slot = type_cache[key]; + + Ref cur = type_ref; + uint32_t inst_off = 0; + const uint32_t entry = detail::type_def_entry_size(ptr); + for (int guard = 0; guard < 4096; ++guard) { + const uint8_t* e = at(cur, entry); + if (!e) break; + int32_t type = (int32_t)rd_u32(cur); + if (type == detail::MT_End) break; + + TypeMember m; + m.type = type; + // Name @ +4(指针槽) + m.name = rd_str({cur.section, cur.offset + 4}); + // ReferenceType @ +4+ptr(指针槽 → data_type_definition 数组) + m.ref_type = follow({cur.section, cur.offset + 4 + ptr}); + // ArrayWidth @ +4+2*ptr + m.array_width = (int32_t)rd_u32({cur.section, cur.offset + 4 + 2 * ptr}); + + uint32_t width = (m.array_width <= 0) ? 1u : (uint32_t)m.array_width; + m.offset = inst_off; + m.size = member_unit_size(m) * width; + inst_off += m.size; + + out.push_back(std::move(m)); + cur.offset += entry; + } + slot = std::move(out); + return slot; +} + +const TypeMember* File::Impl::find_member(const std::vector& ms, const char* name) const { + for (const auto& m : ms) if (m.name == name) return &m; + return nullptr; +} + +// ArrayOfReferences 成员:{int32 count; ptr → count 个指针槽} +std::vector File::Impl::read_array_of_refs(Ref obj, const TypeMember& m) const { + std::vector out; + Ref slot = member_slot(obj, m); + int32_t count = rd_i32(slot); + if (count <= 0 || count > (1 << 24)) return out; + Ref arr = follow({slot.section, slot.offset + 4}); // 指针槽在 count 之后 + if (!arr.valid()) return out; + out.reserve(count); + for (int32_t i = 0; i < count; ++i) { + Ref elem = follow({arr.section, arr.offset + uint32_t(i) * ptr}); + out.push_back(elem); // 可能 invalid(NULL 项) + } + return out; +} + +// ReferenceToArray 成员:{int32 count; ptr → count 个连续对象} +bool File::Impl::read_ref_to_array(Ref obj, const TypeMember& m, + Ref& base, uint32_t& count, uint32_t& stride) { + Ref slot = member_slot(obj, m); + int32_t c = rd_i32(slot); + base = {}; + count = 0; + stride = m.ref_type.valid() ? object_size(m.ref_type) : 0; + if (c <= 0 || c > (1 << 24)) return c == 0; // 空数组不算错 + base = follow({slot.section, slot.offset + 4}); + if (!base.valid()) return false; + count = uint32_t(c); + return true; +} + +// ── gr2dump 用:打印 root object 的类型成员(不硬编码 struct 布局)───── +std::vector dump_root_members(const File& f) { + std::vector out; + if (!f.impl_ || !f.impl_->root_type.valid()) return out; + const auto& ms = f.impl_->parse_type(f.impl_->root_type); + out.reserve(ms.size()); + for (const auto& m : ms) + out.push_back({m.name, m.type, m.array_width}); + return out; +} + +} // namespace gr2 diff --git a/gr2/src/internal.h b/gr2/src/internal.h new file mode 100644 index 0000000..07c326d --- /dev/null +++ b/gr2/src/internal.h @@ -0,0 +1,151 @@ +// libgr2 内部。SDK struct 镜像从 granny_file_format.h / granny_data_type_definition.h 抄。 +#pragma once +#include "gr2/gr2.h" +#include +#include +#include +#include + +namespace gr2 { + +namespace detail { + +// ── granny_file_format.h 镜像 ────────────────────────────────────────── +#pragma pack(push, 1) +struct GrnFileMagic { // grn_file_magic_value + uint32_t magic[4]; + uint32_t header_size; + uint32_t header_format; + uint32_t reserved[2]; +}; +struct GrnReference { uint32_t section; uint32_t offset; }; +struct GrnPointerFixup { uint32_t from_offset; GrnReference to; }; // 12B +struct GrnSection { // grn_section —— 44B + uint32_t compression; + uint32_t data_offset, data_size; + uint32_t expanded_data_size; + uint32_t internal_alignment; + uint32_t first16bit, first8bit; + uint32_t pointer_fixup_off, pointer_fixup_count; + uint32_t mixed_fixup_off, mixed_fixup_count; +}; +#pragma pack(pop) + +struct Section { + std::vector data; // 展开后 + SectionInfo info; +}; + +// section 内的位置。不物化指针(文件是 32 或 64 位指针), +// 全程用 (section, offset) + fixup 表按需解引用。 +struct Ref { + int32_t section = -1; + uint32_t offset = 0; + bool valid() const { return section >= 0; } +}; + +// ── granny_data_type_definition.h:member_type 枚举(序数不可变)──────── +enum MemberType { + MT_End = 0, MT_Inline, MT_Reference, MT_RefToArray, MT_ArrayOfRefs, + MT_VariantRef, MT_Removed, MT_RefToVariantArray, MT_String, MT_Transform, + MT_Real32, MT_Int8, MT_UInt8, MT_BinormInt8, MT_NormUInt8, + MT_Int16, MT_UInt16, MT_BinormInt16, MT_NormUInt16, + MT_Int32, MT_UInt32, MT_Real16, MT_EmptyRef, MT_OnePastLast +}; + +// data_type_definition 在文件里的字节数(结构紧排,指针宽度随文件 magic): +// Type(4) Name(ptr) ReferenceType(ptr) ArrayWidth(4) Extra[3](12) Ignored(ptr) +// 32 位文件 = 32B,64 位文件 = 44B(与 BG3ModStudio GR2TypeNode pack(1) 一致) +constexpr uint32_t type_def_entry_size(uint32_t ptr) { return 4 + ptr + ptr + 4 + 12 + ptr; } + +struct TypeMember { + std::string name; + int32_t type = MT_End; + int32_t array_width = 0; // 0 => 1 + Ref ref_type; // Inline/Reference/... 的元素类型 + uint32_t offset = 0; // 在对象实例里的字节偏移(打包,无对齐 pad) + uint32_t size = 0; // 本 member 的总字节数 +}; + +} // namespace detail + +struct File::Impl { + std::vector sections; // 展开后数据 + info + std::vector raw; // 原始 section 头(fixup 用) + using Ref = detail::Ref; + using TypeMember = detail::TypeMember; + using GrnSection = detail::GrnSection; + + // (section<<32 | from_offset) -> 目标 Ref + std::unordered_map fixups; + + Ref root_obj; // grn_file_header.RootObject + Ref root_type; // grn_file_header.RootObjectTypeDefinition + bool typetree_ready = false; + // 文件指针宽度:32 位 magic = 4,64 位 magic = 8。指针槽都靠 fixup 表解引用, + // 只有成员大小 / 复合成员内部偏移随它变化。 + uint32_t ptr = 4; + + // 类型解析缓存:typedef 的 Ref -> 成员列表 + std::unordered_map> type_cache; + + // ── T2 / T1 ── + bool decompress_section(const GrnSection&, const uint8_t* src, detail::Section& out, LoadError*); + bool build_fixups(const uint8_t* file, size_t file_len, LoadError* err); // T1 + + // ── T3 ── + const uint8_t* at(Ref r, size_t need = 0) const; // section 内指针 + 边界检查 + Ref follow(Ref slot) const; // 解一个"指针槽" + const std::vector& parse_type(Ref type_ref); // 走 data_type_definition 数组 + uint32_t object_size(Ref type_ref); + uint32_t member_unit_size(const TypeMember&); + const TypeMember* find_member(const std::vector& ms, const char* name) const; + + // 便捷读取 + uint32_t rd_u32(Ref r) const; + int32_t rd_i32(Ref r) const { return (int32_t)rd_u32(r); } + float rd_f32(Ref r) const; + std::string rd_str(Ref slot) const; // 解引用一个 String 槽 + + // 成员访问(obj = 对象实例的 Ref,m = 其类型的某个成员) + Ref member_slot(Ref obj, const TypeMember& m) const { return {obj.section, obj.offset + m.offset}; } + Ref read_reference(Ref obj, const TypeMember& m) const { return follow(member_slot(obj, m)); } + // ArrayOfReferences: {int32 count; ptr → [count] 个指针槽(各 ptr 字节)→ 各自的对象} + std::vector read_array_of_refs(Ref obj, const TypeMember& m) const; + // ReferenceToArray: {int32 count; ptr → [count] 个连续对象(elem_type)} + bool read_ref_to_array(Ref obj, const TypeMember& m, Ref& base, uint32_t& count, uint32_t& stride); + + // ── T4/T5/T6/T7a ── + bool build_fileinfo(FileInfo& out, LoadError*); + bool extract_skeleton(Ref skel_obj, Ref skel_type, Skeleton& out); + bool extract_mesh(Ref mesh_obj, Ref mesh_type, const std::vector& skels, Mesh& out); + // granny_material 链:直接 .Texture.FromFileName,或递归 .Maps[].Material。返回 dds 文件名(原样)。 + std::string material_texture_name(Ref mat_obj, Ref mat_type, int depth); + bool extract_animation(Ref anim_obj, Ref anim_type, const Skeleton* skel, Animation& out); + // 曲线子类型分类(T7a)。curve_obj 指向 inline 曲线对象本体,curve_type 是它的类型。 + std::string classify_curve_obj(Ref curve_obj, Ref curve_type); + void read_old_curve(Ref curve_obj, Ref curve_type, Curve& out); // T7b + // curve2{variant CurveData}:各 CurveData* 压缩变体解到同一 Curve(knots + float controls)。 + // keyframe_dt = 所在 animation 的 TimeStep(DaKeyframes32f 的隐含 knot 间距)。 + void read_curve2(Ref curve_obj, Ref curve_type, float keyframe_dt, Curve& out); + double skeleton_self_check(int skeleton) const; + + // granny_transform (68B) → 行主序 4x4(BuildCompositeTransform4x4 语义) + void transform_to_composite(Ref tf, Mat4& out, uint32_t& flags) const; + void read_transform(Ref tf, Transform& out) const; // 68B → SRT 分量 + + // granny_material 图:按对象 Ref 去重,缺的追加到 mats_out(子材质 / 只经 mesh 可达的材质)。 + // 返回 FileInfo::materials 索引;无效 / 递归太深 = -1。 + int32_t intern_material(Ref mat_obj, Ref mat_type, int depth = 0); + std::vector* mats_out = nullptr; + std::vector mat_refs; // 与 *mats_out 平行 + // ExtendedData(VariantRef = {type ptr; object ptr})里取名为 name 的 Int32。 + bool extended_i32(Ref variant_slot, const char* name, int32_t& out); + + std::vector skels_cache; // self-check 复用 + std::vector skel_refs; // 与 skels_cache 平行:各 skeleton 对象的 Ref(model 关联用) + + mutable FileInfo* info_cache = nullptr; // 指向 File::info_ +}; + +} // namespace gr2 diff --git a/gr2/src/oodle1.c b/gr2/src/oodle1.c new file mode 100644 index 0000000..417d933 --- /dev/null +++ b/gr2/src/oodle1.c @@ -0,0 +1,611 @@ +/* Granny "Oodle1" section decompressor (M0 T2). + * + * Ported (decode path only) from the leaked Granny 2.9.12 SDK: + * granny_oodle1_compression.cpp + radlz.c + radarith.c + arithbit.c + * Used as algorithm spec; RAD's build machinery / compressor are NOT included. + * See docs/reference/steps/M0-gr2-reader.md T2. + */ +#include "oodle1.h" +#include +#include + +typedef uint8_t U8; +typedef uint16_t U16; +typedef uint32_t U32; +typedef int32_t S32; +typedef uintptr_t UINTa; + +#define radassert(x) ((void)0) + +/* ================================================================= */ +/* arithbit.c — byte-aligned range decoder */ +/* ================================================================= */ + +typedef struct ARITHBITS { + U32 low; + U32 range; + U8 *ptr; + U32 underflow; /* temp between Get()/Remove() to skip re-divide */ + U8 *start; /* low bit used as scratch */ +} ARITHBITS; + +static void ArithBitsGetStart(ARITHBITS *ab, const void *ptr) { + U32 buf; + ab->ptr = (U8 *)ptr + 1; + buf = ((const U8 *)ptr)[0]; + ab->start = (U8 *)((UINTa)ptr + (buf & 1)); + ab->low = buf >> 1; + ab->range = 1u << 7; +} + +static void ArithBitsDecRenorm(ARITHBITS *ab) { + U32 range = ab->range; + if (range <= 0x800000u) { + U32 low = ab->low; + U32 buf = (U32)((UINTa)ab->start & 1u); + U8 *ptr = ab->ptr; + do { + low = (low + low + buf) << 7; + buf = *ptr++; + low |= (buf >> 1); + buf &= 1u; + range <<= 8; + } while (range <= 0x800000u); + ab->low = low; + ab->start = (U8 *)(((UINTa)ab->start & ~(UINTa)1) + buf); + ab->range = range; + ab->ptr = ptr; + } +} + +static U32 ArithBitsGet(ARITHBITS *ab, U32 scale) { + U32 tmp; + ArithBitsDecRenorm(ab); + ab->underflow = ab->range / scale; + tmp = ab->low / ab->underflow; + return (tmp >= scale) ? (scale - 1) : tmp; +} + +static void ArithBitsRemove(ARITHBITS *ab, U32 start, U32 range, U32 scale) { + U32 tmp = ab->underflow * start; + ab->low -= tmp; + if ((start + range) < scale) ab->range = ab->underflow * range; + else ab->range -= tmp; +} + +static U32 ArithBitsGetValue(ARITHBITS *ab, U32 scale) { + U32 tmp, div, start; + ArithBitsDecRenorm(ab); + div = ab->range / scale; + start = ab->low / div; + if (start >= scale) start = scale - 1; + tmp = div * start; + ab->low -= tmp; + if ((start + 1) < scale) ab->range = div; + else ab->range -= tmp; + return start; +} + +static U32 ArithBitsGetBits(ARITHBITS *ab, U32 bits, U32 scale) { + U32 tmp; + ArithBitsDecRenorm(ab); + ab->underflow = ab->range >> bits; + tmp = ab->low / ab->underflow; + return (tmp >= scale) ? (scale - 1) : tmp; +} + +static U32 ArithBitsGetBitsValue(ARITHBITS *ab, U32 bits, U32 scale) { + U32 tmp, div, start; + ArithBitsDecRenorm(ab); + div = ab->range >> bits; + start = ab->low / div; + if (start >= scale) start = scale - 1; + tmp = div * start; + ab->low -= tmp; + if ((start + 1) < scale) ab->range = div; + else ab->range -= tmp; + return start; +} + +/* ================================================================= */ +/* radarith.c — adaptive arithmetic modeller (decode path) */ +/* ================================================================= */ + +#define NORM_BITS 14 +#define NORM_COUNT (1 << NORM_BITS) +#define ADJ_SUMS (NORM_COUNT << 1) +#define OVERFLOW_COUNT ((NORM_BITS / 2) - 1) /* 6 */ +#define COUNTTYPE U16 + +#define COUNTS_SIZE(v) (sizeof(COUNTTYPE) * (((v) + 1 + 1 + 3) & ~3u)) +#define VALUES_SIZE(v) COUNTS_SIZE(v) + +typedef struct ARITHDATA { + COUNTTYPE singles_tot; + COUNTTYPE update_tot; + COUNTTYPE update_max; + COUNTTYPE update_range; + COUNTTYPE rescale_tot; + COUNTTYPE singles_length; + COUNTTYPE summed_length; + COUNTTYPE unique_count; + COUNTTYPE *values; + COUNTTYPE *single_counts; + U32 table_walks[NORM_BITS]; + COUNTTYPE summed_counts[OVERFLOW_COUNT]; /* deliberately overflows into the gap before single_counts */ +} ARITHDATA; +typedef ARITHDATA *ARITH; + +#define Arith_was_escaped(val) (((UINTa)(val)) > 65536u) +#define Arith_set_decompressed_symbol(val, v) (*((U16 *)(val)) = (U16)(v)) + +static U32 Arith_decompress_alloc_size(U32 unique_values) { + return (U32)(sizeof(ARITHDATA) + COUNTS_SIZE(unique_values) + + COUNTS_SIZE(unique_values) + VALUES_SIZE(unique_values)); +} + +static ARITH Arith_open(void *ptr, void *compress_temp_buf, U32 max_value, U32 unique_values) { + ARITH a = (ARITH)ptr; + U32 u; + (void)compress_temp_buf; /* always NULL on the decode path */ + if (!a) return a; + memset(a, 0, Arith_decompress_alloc_size(unique_values)); + a->single_counts = (COUNTTYPE *)((char *)a + (sizeof(ARITHDATA) + COUNTS_SIZE(unique_values))); + a->values = (COUNTTYPE *)((char *)a->single_counts + COUNTS_SIZE(unique_values)); + a->unique_count = (COUNTTYPE)unique_values; + a->singles_tot = 4; + a->summed_counts[0] = ADJ_SUMS; + a->summed_counts[1] = NORM_COUNT + ADJ_SUMS; + a->summed_counts[2] = NORM_COUNT + ADJ_SUMS; + a->summed_counts[3] = NORM_COUNT + ADJ_SUMS; + a->summed_counts[4] = NORM_COUNT + ADJ_SUMS; + a->summed_counts[5] = NORM_COUNT + ADJ_SUMS; + a->single_counts[0] = 4; + a->update_tot = 8; + a->update_range = 4; + u = max_value * 32; + if (u < 256) u = 256; + else if (u > 15160) u = 15160; + a->rescale_tot = (COUNTTYPE)u; + u = max_value * 2; + if (u < 128) u = 128; + else if (u >= (((U32)a->rescale_tot >> 1) - 32)) u = (U32)(((U32)a->rescale_tot >> 1) - 32); + a->update_max = (COUNTTYPE)u; + return a; +} + +static void rescale_decompress(ARITH a) { + unsigned long i; + U32 max = 0, pos = (U32)-1; + a->single_counts[0] >>= 1; + a->singles_tot = a->single_counts[0]; + for (i = 1; i <= a->singles_length; i++) { + while (a->single_counts[i] <= 1) { + if (i < a->singles_length) { + a->single_counts[i] = a->single_counts[a->singles_length]; + a->single_counts[a->singles_length] = 0; + a->values[i] = a->values[a->singles_length]; + --a->singles_length; + } else { + a->single_counts[i] = 0; + --a->singles_length; + goto done; + } + } + a->single_counts[i] >>= 1; + a->singles_tot = (COUNTTYPE)(a->singles_tot + a->single_counts[i]); + if (a->single_counts[i] > max) { max = a->single_counts[i]; pos = (U32)i; } + } +done: + if (max && a->singles_length) { + U32 j = a->singles_length; + if (pos != j) { + U32 t; + t = a->single_counts[j]; a->single_counts[j] = a->single_counts[pos]; a->single_counts[pos] = (COUNTTYPE)t; + t = a->values[j]; a->values[j] = a->values[pos]; a->values[pos] = (COUNTTYPE)t; + } + } + if ((a->singles_length != a->unique_count) && (a->single_counts[0] == 0)) { + ++a->single_counts[0]; + ++a->singles_tot; + } +} + +static void update_counts(ARITH a) { + U32 i, tot, adj; + adj = (NORM_COUNT * 8) / a->singles_tot; + tot = ((((U32)a->single_counts[0]) * adj) >> 3) + ADJ_SUMS; + a->summed_counts[0] = ADJ_SUMS; + i = 1; + for (;;) { + a->summed_counts[i] = (COUNTTYPE)tot; + if (i > a->singles_length) break; + tot += (((U32)a->single_counts[i]) * adj) >> 3; + ++i; + } + tot = (U32)a->update_range << 1; + if (tot > a->update_max) { + a->update_tot = (COUNTTYPE)(a->singles_tot + a->update_max); + } else { + a->update_range = (COUNTTYPE)tot; + a->update_tot = (COUNTTYPE)(a->singles_tot + tot); + } + a->summed_length = a->singles_length; + a->summed_counts[a->summed_length + 1] = NORM_COUNT + ADJ_SUMS; +} + +static void build_walk_table(U32 *wtable, U32 v) { + U32 num = 0, *m = wtable; + ++v; + do { + v = (v + 1) >> 1; + ++num; + *m++ = v; + } while (v > 4); + num -= 1; + if (num) { + memmove(wtable + NORM_BITS - 1 - num + 1, wtable + 1, num * sizeof(wtable[0])); + } + wtable[1] = wtable[0]; + wtable[0] = num; +} + +static UINTa Arith_decompress(ARITH a, ARITHBITS *ab) { + U32 offset; + S32 index; + + if (a->singles_tot >= a->update_tot) { + if (a->update_tot >= a->rescale_tot) rescale_decompress(a); + update_counts(a); + a->summed_counts[a->summed_length + 2] = NORM_COUNT + ADJ_SUMS; + a->summed_counts[a->summed_length + 3] = NORM_COUNT + ADJ_SUMS; + a->summed_counts[a->summed_length + 4] = NORM_COUNT + ADJ_SUMS; + a->summed_counts[a->summed_length + 5] = NORM_COUNT + ADJ_SUMS; + a->summed_counts[a->summed_length + 6] = NORM_COUNT + ADJ_SUMS; + build_walk_table(a->table_walks, a->summed_length); + } + + offset = ArithBitsGetBits(ab, NORM_BITS, NORM_COUNT) + ADJ_SUMS; + + { + index = (S32)a->table_walks[1]; + #define check_level(lev) \ + if (a->summed_counts[index] > (COUNTTYPE)offset) \ + index -= (S32)a->table_walks[NORM_BITS - 1 - (lev)]; \ + else \ + index += (S32)a->table_walks[NORM_BITS - 1 - (lev)]; + switch (a->table_walks[0]) { + case 11: check_level(10) /* fallthrough */ + case 10: check_level(9) /* fallthrough */ + case 9: check_level(8) /* fallthrough */ + case 8: check_level(7) /* fallthrough */ + case 7: check_level(6) /* fallthrough */ + case 6: check_level(5) /* fallthrough */ + case 5: check_level(4) /* fallthrough */ + case 4: check_level(3) /* fallthrough */ + case 3: check_level(2) /* fallthrough */ + case 2: check_level(1) /* fallthrough */ + case 1: check_level(0) /* fallthrough */ + case 0: break; + default: break; + } + #undef check_level + + if (a->summed_counts[index] > (COUNTTYPE)offset) index -= 2; + else index += 2; + + if (a->summed_counts[index] > (COUNTTYPE)offset) { + if (a->summed_counts[index - 1] > (COUNTTYPE)offset) index -= 2; + else --index; + } else { + if (a->summed_counts[index + 1] <= (COUNTTYPE)offset) ++index; + } + } + + ArithBitsRemove(ab, a->summed_counts[index] - ADJ_SUMS, + a->summed_counts[index + 1] - a->summed_counts[index], NORM_COUNT); + + ++a->single_counts[index]; + ++a->singles_tot; + + if (index <= 0) { + if (a->singles_length == a->summed_length) { + new_index: + index = ++a->singles_length; + a->single_counts[index] += 2; + a->singles_tot += 2; + if (a->singles_length == a->unique_count) { + a->singles_tot = (COUNTTYPE)(a->singles_tot - a->single_counts[0]); + a->single_counts[0] = 0; + } + return (UINTa)&a->values[index]; + } else { + if (ArithBitsGetBitsValue(ab, 1, 2)) { + index = (S32)(ArithBitsGetValue(ab, a->singles_length - a->summed_length) + + a->summed_length + 1); + a->single_counts[index] += 2; + a->singles_tot += 2; + } else { + goto new_index; + } + } + } + + return a->values[index]; +} + +/* ================================================================= */ +/* radlz.c — LZ decoder (decode path) */ +/* ================================================================= */ + +#define LOW_BITS 2 +#define MED_BITS 8 +#define TOP_BITS 8 +#define LARGEST_POSSIBLE_OFFSET ((1 << (LOW_BITS + MED_BITS + TOP_BITS)) - 1) +#define GRANNY_OFFSET LARGEST_POSSIBLE_OFFSET + +#define MAX_LENS 64 +#define LMAX (1 << LOW_BITS) /* 4 */ +#define MMAX (1 << MED_BITS) /* 256 */ +#define GETT(v) ((v) >> (LOW_BITS + MED_BITS)) +#define ADDRESS_MASK 3 + +static const U32 long_lengths[4] = { MAX_LENS * 2, MAX_LENS * 3, MAX_LENS * 4, MAX_LENS * 8 }; + +typedef struct LZ_HEADER { + U32 max_offset_and_byte; + U32 uniq_offset_and_byte; + U32 uniq_lens; +} LZ_HEADER; + +typedef struct LZDDATA { + ARITH bytes[ADDRESS_MASK + 1]; + ARITH lens[MAX_LENS + 1]; + ARITH offsl, offst; + ARITH offsm[256]; + U32 max_bytes, max_offs, max_offsL, max_offsM, max_offsT; + U32 bytes_decompressed; + U32 last_len; +} LZDDATA; +typedef LZDDATA *LZD; + +static void get_max_offsets(U32 max_offset, U32 *low_max, U32 *med_max, U32 *high_max) { + *low_max = (max_offset >= LMAX) ? LMAX : (max_offset + 1); + *med_max = ((max_offset >> LOW_BITS) >= MMAX) ? MMAX : ((max_offset >> LOW_BITS) + 1); + *high_max = GETT(max_offset) + 1; +} + +static void copy_bytes(void *d, const void *s, U32 length) { + U8 *dest = (U8 *)d; + const U8 *src = (const U8 *)s; + /* LZ back-refs always have src < dest, so the fast path never triggers here; + * byte copy is required for correct RLE-style overlap. */ + if (length >= 4 && (src - dest) >= 4) { + do { + length -= 4; + ((U32 *)dest)[0] = ((const U32 *)src)[0]; + dest += 4; src += 4; + } while (length > 4); + if (length == 0) return; + } + do { length--; *dest++ = *src++; } while (length); +} + +static U32 LZ_decompress_alloc_size(U32 max_byte_value, U32 uniq_byte_values, U32 max_offset) { + U32 size, h, low_max, med_max, high_max; + (void)max_byte_value; + size = (U32)sizeof(LZDDATA); + get_max_offsets(max_offset, &low_max, &med_max, &high_max); + h = Arith_decompress_alloc_size(uniq_byte_values); + size += h * (ADDRESS_MASK + 1); + size += Arith_decompress_alloc_size(MAX_LENS + 1) * (MAX_LENS + 1); + size += Arith_decompress_alloc_size(low_max); + size += high_max * Arith_decompress_alloc_size(med_max); + size += Arith_decompress_alloc_size(high_max); + return size; +} + +static LZD LZ_decompress_open_from_header(void *ptr, const LZ_HEADER *h) { + U32 i, j, size, uniq = 0; + U8 *addr; + LZD l = (LZD)ptr; + + l->max_bytes = h->max_offset_and_byte & 511; + l->max_offs = h->max_offset_and_byte >> 9; + get_max_offsets(l->max_offs, &l->max_offsL, &l->max_offsM, &l->max_offsT); + l->last_len = 0; + l->bytes_decompressed = 0; + + j = h->uniq_offset_and_byte & 511; + addr = (U8 *)(l + 1); + size = Arith_decompress_alloc_size(j); + for (i = 0; i <= ADDRESS_MASK; i++) { + l->bytes[i] = Arith_open(addr, 0, l->max_bytes - 1, j); + addr += size; + } + + for (j = 0; j < 4; j++) { + uniq = (h->uniq_lens >> ((3 - j) * 8)) & 255; + size = Arith_decompress_alloc_size(uniq); + for (i = 0; i < (MAX_LENS / 4); i++) { + l->lens[(j * (MAX_LENS / 4)) + i] = Arith_open(addr, 0, MAX_LENS, uniq); + addr += size; + } + } + for (i = (MAX_LENS / 4) * 4; i <= MAX_LENS; i++) { + l->lens[i] = Arith_open(addr, 0, MAX_LENS, uniq); /* inherits last uniq/size */ + addr += size; + } + + size = Arith_decompress_alloc_size(l->max_offsM); + for (i = 0; i < l->max_offsT; i++) { + l->offsm[i] = Arith_open(addr, 0, l->max_offsM - 1, l->max_offsM); + addr += size; + } + + l->offsl = Arith_open(addr, 0, l->max_offsL - 1, l->max_offsL); + l->offst = Arith_open(addr + Arith_decompress_alloc_size(l->max_offsL), + 0, l->max_offsT - 1, GETT(h->uniq_offset_and_byte >> 9) + 1); + return l; +} + +static U32 LZ_decompress(LZD l, ARITHBITS *ab, U8 *output) { + UINTa v; + U32 escaped; + + v = Arith_decompress(l->lens[l->last_len], ab); + if (Arith_was_escaped(v)) { + escaped = ArithBitsGetValue(ab, MAX_LENS + 1); + Arith_set_decompressed_symbol(v, escaped); + v = escaped; + } + l->last_len = (U32)v; + + if (v) { + U32 len, off, max_ofs; + UINTa m; + + max_ofs = l->max_offs; + if (max_ofs > l->bytes_decompressed) max_ofs = l->bytes_decompressed; + + len = (v >= (MAX_LENS - 3)) ? long_lengths[v - (MAX_LENS - 3)] : (U32)(v + 1); + + v = Arith_decompress(l->offsl, ab); + if (Arith_was_escaped(v)) { + escaped = ArithBitsGetValue(ab, l->max_offsL); + Arith_set_decompressed_symbol(v, escaped); + v = escaped; + } + off = (U32)(v + 1); + + v = Arith_decompress(l->offst, ab); + if (Arith_was_escaped(v)) { + escaped = ArithBitsGetValue(ab, GETT(max_ofs) + 1); + Arith_set_decompressed_symbol(v, escaped); + v = escaped; + } + + m = Arith_decompress(l->offsm[v], ab); + if (Arith_was_escaped(m)) { + U32 offsm_used; + if (max_ofs >= (MMAX << LOW_BITS)) offsm_used = MMAX; + else offsm_used = (max_ofs >> LOW_BITS) + 1; + escaped = ArithBitsGetValue(ab, offsm_used); + Arith_set_decompressed_symbol(m, escaped); + m = escaped; + } + + off = (U32)(off + ((U32)m << LOW_BITS) + ((U32)v << (LOW_BITS + MED_BITS))); + l->bytes_decompressed += len; + copy_bytes(output, output - off, len); + return len; + } else { + v = Arith_decompress(l->bytes[((UINTa)output) & ADDRESS_MASK], ab); + if (Arith_was_escaped(v)) { + escaped = ArithBitsGetValue(ab, l->max_bytes); + Arith_set_decompressed_symbol(v, escaped); + v = escaped; + } + *output = (U8)v; + ++l->bytes_decompressed; + return 1; + } +} + +/* ================================================================= */ +/* granny_oodle1_compression.cpp — the wrapper */ +/* ================================================================= */ + +#define ALIGN32(x) (((x) + 3u) & ~3u) + +static void reverse32(void *p, U32 nbytes) { + U8 *b = (U8 *)p; + U32 i; + for (i = 0; i + 4 <= nbytes; i += 4) { + U8 t0 = b[i], t1 = b[i + 1]; + b[i] = b[i + 3]; + b[i + 1] = b[i + 2]; + b[i + 2] = t1; + b[i + 3] = t0; + } +} + +int gr2_oodle1_decompress(int file_is_byte_reversed, + U32 comp_size, void *comp_bytes, + U32 stop0, U32 stop1, U32 stop2, void *out) { + LZ_HEADER headers[3]; + ARITHBITS ab; + U32 temp_size, size, b; + U32 stops[3]; + void *temp; + U8 *to; + + /* hanging-bit fix: zero-pad up to 32-bit alignment (caller also over-allocates). */ + { + U32 rounded = ALIGN32(comp_size) - comp_size; + while (rounded--) ((U8 *)comp_bytes)[comp_size + rounded] = 0; + } + + if (comp_size < sizeof(headers)) return -1; + memcpy(headers, comp_bytes, sizeof(headers)); + if (file_is_byte_reversed) reverse32(headers, sizeof(headers)); + + ArithBitsGetStart(&ab, (const U8 *)comp_bytes + sizeof(headers)); + + temp_size = LZ_decompress_alloc_size(255, 256, GRANNY_OFFSET); + temp = malloc(temp_size); + if (!temp) return -2; + + size = 0; + stops[0] = stop0; stops[1] = stop1; stops[2] = stop2; + to = (U8 *)out; + for (b = 0; b < 3; ++b) { + U32 stop = stops[b]; + LZD lz = LZ_decompress_open_from_header(temp, &headers[b]); + U32 guard = 0; + while (size < stop) { + U32 len = LZ_decompress(lz, &ab, to); + if (len == 0 || size + len > stop2 + 512) { free(temp); return -3; } /* corruption guard */ + size += len; + to += len; + if (++guard > stop2 + 16) { free(temp); return -4; } + } + if (size != stop) { free(temp); return -5; } + } + + free(temp); + return 0; +} + +int gr2_oodle1_decompress_chunk(int file_is_byte_reversed, + U32 comp_size, void *comp_bytes, + U32 decompressed_size, void *out) { + LZ_HEADER header; + ARITHBITS ab; + U32 temp_size, size; + void *temp; + U8 *to; + + if (comp_size < sizeof(header)) return -1; + memcpy(&header, comp_bytes, sizeof(header)); + if (file_is_byte_reversed) reverse32(&header, sizeof(header)); + + ArithBitsGetStart(&ab, (const U8 *)comp_bytes + sizeof(header)); + temp_size = LZ_decompress_alloc_size(255, 256, GRANNY_OFFSET); + temp = malloc(temp_size); + if (!temp) return -2; + + size = 0; + to = (U8 *)out; + { + LZD lz = LZ_decompress_open_from_header(temp, &header); + while (size < decompressed_size) { + U32 len = LZ_decompress(lz, &ab, to); + if (len == 0) { free(temp); return -3; } + size += len; + to += len; + } + } + free(temp); + return (size == decompressed_size) ? 0 : -5; +} diff --git a/gr2/src/oodle1.h b/gr2/src/oodle1.h new file mode 100644 index 0000000..c267db5 --- /dev/null +++ b/gr2/src/oodle1.h @@ -0,0 +1,31 @@ +// Granny "Oodle1" section 解压(M0 T2)。 +// 端口自泄露 SDK 的 granny_oodle1_compression.cpp + radlz.c + radarith.c + arithbit.c +// (只移植解码路径,作算法规格 —— 不含压缩,不含 RAD 的构建机制)。 +#pragma once +#include + +#ifdef __cplusplus +extern "C" { +#endif + +// comp_bytes:可写缓冲,长度 >= comp_size + 32,尾部已清零(解码器会读过界)。 +// 起始地址必须 4 字节对齐。 +// stop0/1/2 :section 的 First16Bit / First8Bit / ExpandedDataSize(累积边界)。 +// out :至少 stop2 字节。 +// 返回 0 成功,非 0 失败。 +int gr2_oodle1_decompress(int file_is_byte_reversed, + uint32_t comp_size, + void* comp_bytes, + uint32_t stop0, uint32_t stop1, uint32_t stop2, + void* out); + +// 单块版(NoCompression 之外走不到;保留对称) +int gr2_oodle1_decompress_chunk(int file_is_byte_reversed, + uint32_t comp_size, + void* comp_bytes, + uint32_t decompressed_size, + void* out); + +#ifdef __cplusplus +} +#endif diff --git a/gr2/src_render/gr2_model_instance.cpp b/gr2/src_render/gr2_model_instance.cpp new file mode 100644 index 0000000..6921b58 --- /dev/null +++ b/gr2/src_render/gr2_model_instance.cpp @@ -0,0 +1,764 @@ +#include +#include +#include +#include +#include +#include +#include +#include + +namespace gr2_render { + +namespace { + +// Share immutable parsed assets, never mutable animation/attachment instances. +// Bound strong retention by entry count and source bytes; live instances keep ownership. +std::shared_ptr LoadCachedFile(const std::string& path, gr2::LoadError* err) { + struct Entry { std::string key; uintmax_t bytes; std::filesystem::file_time_type stamp; + std::shared_ptr file; }; + static std::list cache; + static std::mutex mutex; + std::error_code ec; + auto canonical = std::filesystem::weakly_canonical(path, ec); + if (ec) return {}; + auto stamp = std::filesystem::last_write_time(canonical, ec); + if (ec) return {}; + auto bytes = std::filesystem::file_size(canonical, ec); + if (ec) return {}; + const auto key = canonical.string(); + std::lock_guard lock(mutex); + for (auto it = cache.begin(); it != cache.end(); ++it) { + if (it->key != key) continue; + if (it->stamp == stamp && it->bytes == bytes) { + auto file = it->file; cache.splice(cache.begin(), cache, it); return file; + } + cache.erase(it); break; + } + auto parsed = gr2::File::load_path(key, err); + if (!parsed) return {}; + auto file = std::make_shared(std::move(*parsed)); + cache.push_front({key, bytes, stamp, file}); + uintmax_t total = 0; for (const auto& entry : cache) total += entry.bytes; + while (cache.size() > 64 || (total > 128u*1024u*1024u && cache.size() > 1)) { + total -= cache.back().bytes; cache.pop_back(); + } + return file; +} + +Gr2MeshDraw ShareGpuMesh(Gr2MeshDraw source) { + Gr2MeshDraw command=source; + command.positions={};command.normals={};command.uv0={};command.diffuse={};command.indices={}; + command.bone_indices={};command.bone_weights={}; + source.bone_matrices={}; + command.geometry=std::make_shared(std::move(source)); + return command; +} +void UpdateGpuDraws(std::vector& draws,const float* world,const std::vector& palette) { + for(auto& draw:draws){std::copy_n(world,16,draw.world);draw.bone_matrices.clear(); + if(draw.gpu_skinning)for(const auto& matrix:palette)draw.bone_matrices.insert(draw.bone_matrices.end(),matrix.begin(),matrix.end()); + } +} + +inline void MultiplyMat4(const float* a, const float* b, float* out) { + float r[16]; + for (int i = 0; i < 4; ++i) { + for (int j = 0; j < 4; ++j) { + r[i * 4 + j] = a[i * 4 + 0] * b[0 * 4 + j] + + a[i * 4 + 1] * b[1 * 4 + j] + + a[i * 4 + 2] * b[2 * 4 + j] + + a[i * 4 + 3] * b[3 * 4 + j]; + } + } + for (int k = 0; k < 16; ++k) out[k] = r[k]; +} + +// Basis change from Granny (Z-up, Y-forward) to Engine (Y-up, Z-forward): (x, y, z) -> (x, z, -y) +const float R_GRANNY_TO_ENGINE[16] = { + 1.0f, 0.0f, 0.0f, 0.0f, + 0.0f, 0.0f, -1.0f, 0.0f, + 0.0f, 1.0f, 0.0f, 0.0f, + 0.0f, 0.0f, 0.0f, 1.0f +}; + +std::string SkinKey(std::string path) { + for (auto& c : path) { + if (c == '\\') c = '/'; + else if (static_cast(c) < 128) c = static_cast(std::tolower(static_cast(c))); + } + return path; +} + +} // namespace + +std::unique_ptr Gr2ModelInstance::Load(const std::string& filepath) { + gr2::LoadError err; + auto file_opt = LoadCachedFile(filepath, &err); + if (!file_opt) { + std::cerr << "Gr2ModelInstance::Load failed: [" << err.stage << "] " << err.message << " for " << filepath << std::endl; + return nullptr; + } + + auto instance = std::make_unique(); + instance->m_file = file_opt; + instance->m_filepath = filepath; + return instance; +} + +std::unique_ptr Gr2ModelInstance::LoadFromMemory(const uint8_t* data, size_t size, const std::string& name) { + if (!data || size == 0) return nullptr; + gr2::LoadError err; + auto file_opt = gr2::File::load(data, size, &err); + if (!file_opt) { + std::cerr << "Gr2ModelInstance::LoadFromMemory failed: [" << err.stage << "] " << err.message << std::endl; + return nullptr; + } + + auto instance = std::make_unique(); + instance->m_file = std::make_shared(std::move(*file_opt)); + instance->m_filepath = name; + return instance; +} + +bool Gr2ModelInstance::LoadExternalAnimation(const std::string& anim_filepath) { + gr2::LoadError err; + auto file_opt = LoadCachedFile(anim_filepath, &err); + if (!file_opt) { + std::cerr << "Gr2ModelInstance::LoadExternalAnimation failed: [" << err.stage << "] " << err.message << " for " << anim_filepath << std::endl; + return false; + } + if (file_opt->file_info().animations.empty()) { + std::cerr << "Gr2ModelInstance::LoadExternalAnimation: no animations in " << anim_filepath << std::endl; + return false; + } + m_anim_file = file_opt; + m_poseValid = false; + m_anim_filepath = anim_filepath; + return true; +} + +bool Gr2ModelInstance::LoadExternalAnimationFromMemory(const uint8_t* data, size_t size) { + if (!data || size == 0) return false; + gr2::LoadError err; + auto file_opt = gr2::File::load(data, size, &err); + if (!file_opt) { + std::cerr << "Gr2ModelInstance::LoadExternalAnimationFromMemory failed: [" << err.stage << "] " << err.message << std::endl; + return false; + } + if (file_opt->file_info().animations.empty()) { + std::cerr << "Gr2ModelInstance::LoadExternalAnimationFromMemory: no animations in buffer" << std::endl; + return false; + } + m_anim_file = std::make_shared(std::move(*file_opt)); + m_poseValid = false; + m_anim_filepath = "memory"; + return true; +} + +float Gr2ModelInstance::GetAnimationDuration() const { + if (m_anim_file && !m_anim_file->file_info().animations.empty()) { + return m_anim_file->file_info().animations[0].duration; + } + if (m_file && !m_file->file_info().animations.empty()) { + return m_file->file_info().animations[0].duration; + } + return 0.0f; +} + +void Gr2ModelInstance::EvaluatePose(float time) const { + if (!m_file || m_file->file_info().skeletons.empty()) return; + const auto& sk = m_file->file_info().skeletons[0]; + const gr2::Animation* anim = nullptr; + if (m_anim_file && !m_anim_file->file_info().animations.empty()) anim = &m_anim_file->file_info().animations[0]; + else if (!m_file->file_info().animations.empty()) anim = &m_file->file_info().animations[0]; + const float keyTime = time >= 0 && anim ? time : -1; + if (m_poseValid && keyTime == m_poseTime && anim == m_poseAnimation) return; + if (anim != m_poseAnimation || !m_poseValid) { + m_trackBones.clear(); + if (anim) { + std::unordered_map bones; + for (size_t i=0; itracks) { + auto it=bones.find(track.bone_name); + m_trackBones.push_back(it==bones.end() ? -1 : it->second); + } + } + } + m_localPose.resize(sk.bones.size()); + for (size_t i=0; i= 0) { + anim->sample_local(time, m_trackPose); + for (size_t i=0; i=0) m_localPose[m_trackBones[i]]=m_trackPose[i]; + } + m_worldPose.resize(sk.bones.size()); m_skinPose.resize(sk.bones.size()); + const gr2::Mat4 identity{1,0,0,0, 0,1,0,0, 0,0,1,0, 0,0,0,1}; + for (size_t i=0; i= 0 ? identity : sk.initial_placement; + const auto& parentWorld=parent<0 || size_t(parent)>=i ? root : m_worldPose[parent]; + MultiplyMat4(m_localPose[i].data(), parentWorld.data(), m_worldPose[i].data()); + MultiplyMat4(sk.bones[i].inverse_world.data(), m_worldPose[i].data(), m_skinPose[i].data()); + } + m_poseAnimation=anim; m_poseTime=keyTime; m_poseValid=true; ++m_poseEvaluations; +} + +bool Gr2ModelInstance::GetBoneWorldTransform(const std::string& bone_name, float* out_matrix, float animation_time) const { + if (!m_file || m_file->file_info().skeletons.empty() || !out_matrix) return false; + const auto& sk = m_file->file_info().skeletons[0]; + int target_bone = -1; + for (size_t i = 0; i < sk.bones.size(); ++i) { + if (sk.bones[i].name == bone_name) { + target_bone = static_cast(i); + break; + } + } + if (target_bone < 0) return false; + + EvaluatePose(animation_time); + const auto& world_pose = m_worldPose; + + if (target_bone >= 0 && target_bone < static_cast(world_pose.size())) { + std::copy(world_pose[target_bone].data(), world_pose[target_bone].data() + 16, out_matrix); + return true; + } + return false; +} + +void Gr2ModelInstance::AttachModel(const std::string& bone_name, std::shared_ptr attachment, const float* offset_matrix) { + if (!attachment) return; + for (auto& existing : m_attached_models) { + if (existing.bone_name == bone_name) { + existing.model = attachment; + if (offset_matrix) { + std::copy(offset_matrix, offset_matrix + 16, existing.offset); + } else { + for (int i = 0; i < 16; ++i) existing.offset[i] = (i % 5 == 0) ? 1.0f : 0.0f; + } + return; + } + } + AttachedModel am; + am.bone_name = bone_name; + am.model = attachment; + if (offset_matrix) { + std::copy(offset_matrix, offset_matrix + 16, am.offset); + } else { + for (int i = 0; i < 16; ++i) am.offset[i] = (i % 5 == 0) ? 1.0f : 0.0f; + } + m_attached_models.push_back(std::move(am)); +} + +void Gr2ModelInstance::AttachPart(std::shared_ptr part) { + if (part) m_attached_parts.push_back(part); +} + +void Gr2ModelInstance::DetachAll() { + m_attached_models.clear(); + m_attached_parts.clear(); +} + +void Gr2ModelInstance::DetachModel(const std::string& bone_name) { + m_attached_models.erase(std::remove_if(m_attached_models.begin(), m_attached_models.end(), + [&](const AttachedModel& am) { return am.bone_name == bone_name; }), m_attached_models.end()); +} + +void Gr2ModelInstance::DetachPart(const std::shared_ptr& part) { + m_attached_parts.erase(std::remove(m_attached_parts.begin(), m_attached_parts.end(), part), m_attached_parts.end()); +} + +void Gr2ModelInstance::SetAttachmentAnimated(const std::string& bone_name, bool animated) { + for (auto& am : m_attached_models) { + if (am.bone_name == bone_name) am.animated = animated; + } +} + +void Gr2ModelInstance::SetAttachmentScale(const std::string& bone_name, float sx, float sy, float sz) { + for (auto& am : m_attached_models) { + if (am.bone_name != bone_name) continue; + am.scaled = true; + am.scale[0] = sx; am.scale[1] = sy; am.scale[2] = sz; + } +} + +void Gr2ModelInstance::SetSkin(const std::string& src_file_name, const std::string& dst_file_name) { + m_skins[SkinKey(src_file_name)] = dst_file_name; +} + +void Gr2ModelInstance::ApplySkins(std::vector& draws, size_t first) const { + if (m_skins.empty()) return; + for (size_t i = first; i < draws.size(); ++i) { + auto it = m_skins.find(SkinKey(draws[i].texture0)); + if (it != m_skins.end()) draws[i].texture0 = it->second; + } +} + +std::vector Gr2ModelInstance::BuildDrawCommandsWithPalette(const std::vector& skin_matrices, + const float* world_matrix, + const gr2::Skeleton* parent_skeleton, bool hardwareSkinning) { + std::vector draws; + if (!m_file) return draws; + + const auto& info = m_file->file_info(); + bool has_skin = !skin_matrices.empty(); + std::vector part_skin_matrices = skin_matrices; + + // Map this model's skeleton bones to parent skeleton bones by name if a parent skeleton is provided + std::vector part_to_parent_bone_map; + if (parent_skeleton && !info.skeletons.empty()) { + const auto& my_skel = info.skeletons[0]; + std::vector parent_bind_world, parent_bind_skin; + gr2::bind_pose(*parent_skeleton, parent_bind_world, parent_bind_skin); + part_to_parent_bone_map.resize(my_skel.bones.size(), -1); + for (size_t b = 0; b < my_skel.bones.size(); ++b) { + const std::string& bname = my_skel.bones[b].name; + for (size_t pb = 0; pb < parent_skeleton->bones.size(); ++pb) { + if (parent_skeleton->bones[pb].name == bname) { + part_to_parent_bone_map[b] = static_cast(pb); + // A shared animation pose does not imply shared inverse bind matrices. + // Recover the parent's animated world pose, then skin with THIS part's + // inverse bind pose (hair exports can have a different rest skeleton). + if (pb < skin_matrices.size()) { + gr2::Mat4 animated_world; + MultiplyMat4(parent_bind_world[pb].data(), skin_matrices[pb].data(), animated_world.data()); + MultiplyMat4(my_skel.bones[b].inverse_world.data(), animated_world.data(), part_skin_matrices[pb].data()); + } + break; + } + } + } + } + + hardwareSkinning = hardwareSkinning && part_skin_matrices.size()<=128; + float cachedWorld[16]; + if(world_matrix)MultiplyMat4(R_GRANNY_TO_ENGINE,world_matrix,cachedWorld); + else std::copy_n(R_GRANNY_TO_ENGINE,16,cachedWorld); + if(m_gpuPartParent!=parent_skeleton || m_gpuPartPaletteSize!=part_skin_matrices.size()){m_gpuParts.clear();m_gpuPartParent=parent_skeleton;m_gpuPartPaletteSize=part_skin_matrices.size();} + if(hardwareSkinning && !m_gpuParts.empty()) { + draws=m_gpuParts;UpdateGpuDraws(draws,cachedWorld,part_skin_matrices); + } else { + for (const auto& mesh : info.meshes) { + std::vector skinned_positions; + std::vector skinned_normals; + std::vector uvs; + std::vector bone_indices; + std::vector bone_weights; + + skinned_positions.reserve(mesh.vertices.size() * 3); + skinned_normals.reserve(mesh.vertices.size() * 3); + uvs.reserve(mesh.vertices.size() * 2); + bone_indices.reserve(mesh.vertices.size() * 4); + bone_weights.reserve(mesh.vertices.size() * 4); + + // Precompute mapped bone bindings for this mesh + std::vector effective_bone_bindings(mesh.bone_bindings.size()); + for (size_t i = 0; i < mesh.bone_bindings.size(); ++i) { + int raw_bone = mesh.bone_bindings[i]; + if (!part_to_parent_bone_map.empty() && raw_bone >= 0 && raw_bone < static_cast(part_to_parent_bone_map.size())) { + effective_bone_bindings[i] = part_to_parent_bone_map[raw_bone]; + } else { + effective_bone_bindings[i] = raw_bone; + } + } + + bool is_rigid_single_bone = (mesh.bone_bindings.size() == 1); + int single_bone_target = is_rigid_single_bone ? effective_bone_bindings[0] : -1; + + for (const auto& v : mesh.vertices) { + float px = 0.0f, py = 0.0f, pz = 0.0f; + float nx = 0.0f, ny = 0.0f, nz = 0.0f; + float total_w = 0.0f; + + if (has_skin) { + if (is_rigid_single_bone && v.bone_weight[0] == 0) { + // Rigid mesh attached 100% to a single bone (e.g. warrior face, hair, helmet) + if (single_bone_target >= 0 && single_bone_target < static_cast(skin_matrices.size())) { + const auto& M = part_skin_matrices[single_bone_target]; + px = v.pos[0] * M[0] + v.pos[1] * M[4] + v.pos[2] * M[8] + M[12]; + py = v.pos[0] * M[1] + v.pos[1] * M[5] + v.pos[2] * M[9] + M[13]; + pz = v.pos[0] * M[2] + v.pos[1] * M[6] + v.pos[2] * M[10] + M[14]; + + nx = v.normal[0] * M[0] + v.normal[1] * M[4] + v.normal[2] * M[8]; + ny = v.normal[0] * M[1] + v.normal[1] * M[5] + v.normal[2] * M[9]; + nz = v.normal[0] * M[2] + v.normal[1] * M[6] + v.normal[2] * M[10]; + total_w = 1.0f; + + bone_indices.push_back(static_cast(single_bone_target)); + bone_indices.push_back(0); bone_indices.push_back(0); bone_indices.push_back(0); + bone_weights.push_back(1.0f); + bone_weights.push_back(0.0f); bone_weights.push_back(0.0f); bone_weights.push_back(0.0f); + } + } else if (v.bone_weight[0] > 0) { + float w0 = v.bone_weight[0] / 255.0f; + float w1 = v.bone_weight[1] / 255.0f; + float w2 = v.bone_weight[2] / 255.0f; + float w3 = v.bone_weight[3] / 255.0f; + + for (int b = 0; b < 4; ++b) { + if (v.bone_weight[b] == 0) continue; + float w = v.bone_weight[b] / 255.0f; + int local_slot = v.bone_index[b]; + int sk_bone = (local_slot < static_cast(effective_bone_bindings.size())) ? effective_bone_bindings[local_slot] : local_slot; + if (sk_bone >= 0 && sk_bone < static_cast(skin_matrices.size())) { + if(hardwareSkinning){total_w+=w;continue;} + const auto& M = part_skin_matrices[sk_bone]; + px += (v.pos[0] * M[0] + v.pos[1] * M[4] + v.pos[2] * M[8] + M[12]) * w; + py += (v.pos[0] * M[1] + v.pos[1] * M[5] + v.pos[2] * M[9] + M[13]) * w; + pz += (v.pos[0] * M[2] + v.pos[1] * M[6] + v.pos[2] * M[10] + M[14]) * w; + + nx += (v.normal[0] * M[0] + v.normal[1] * M[4] + v.normal[2] * M[8]) * w; + ny += (v.normal[0] * M[1] + v.normal[1] * M[5] + v.normal[2] * M[9]) * w; + nz += (v.normal[0] * M[2] + v.normal[1] * M[6] + v.normal[2] * M[10]) * w; + total_w += w; + } + } + + int b0 = v.bone_index[0] < effective_bone_bindings.size() ? effective_bone_bindings[v.bone_index[0]] : v.bone_index[0]; + int b1 = v.bone_index[1] < effective_bone_bindings.size() ? effective_bone_bindings[v.bone_index[1]] : v.bone_index[1]; + int b2 = v.bone_index[2] < effective_bone_bindings.size() ? effective_bone_bindings[v.bone_index[2]] : v.bone_index[2]; + int b3 = v.bone_index[3] < effective_bone_bindings.size() ? effective_bone_bindings[v.bone_index[3]] : v.bone_index[3]; + bone_indices.push_back(hardwareSkinning && (b0<0 || size_t(b0)>=skin_matrices.size()) ? uint8_t(255) : static_cast(b0)); + bone_indices.push_back(hardwareSkinning && (b1<0 || size_t(b1)>=skin_matrices.size()) ? uint8_t(255) : static_cast(b1)); + bone_indices.push_back(hardwareSkinning && (b2<0 || size_t(b2)>=skin_matrices.size()) ? uint8_t(255) : static_cast(b2)); + bone_indices.push_back(hardwareSkinning && (b3<0 || size_t(b3)>=skin_matrices.size()) ? uint8_t(255) : static_cast(b3)); + bone_weights.push_back(w0); bone_weights.push_back(w1); bone_weights.push_back(w2); bone_weights.push_back(w3); + } + } + + if (total_w < 1e-4f) { + px = v.pos[0]; py = v.pos[1]; pz = v.pos[2]; + nx = v.normal[0]; ny = v.normal[1]; nz = v.normal[2]; + if (bone_indices.size() < (skinned_positions.size() / 3 + 1) * 4) { + bone_indices.push_back(0); bone_indices.push_back(0); bone_indices.push_back(0); bone_indices.push_back(0); + bone_weights.push_back(hardwareSkinning ? 0.f : 1.f); bone_weights.push_back(0.0f); bone_weights.push_back(0.0f); bone_weights.push_back(0.0f); + } + } + + if(hardwareSkinning){px=v.pos[0];py=v.pos[1];pz=v.pos[2];nx=v.normal[0];ny=v.normal[1];nz=v.normal[2];} + skinned_positions.push_back(px); + skinned_positions.push_back(py); + skinned_positions.push_back(pz); + + skinned_normals.push_back(nx); + skinned_normals.push_back(ny); + skinned_normals.push_back(nz); + + uvs.push_back(v.uv0[0]); + uvs.push_back(v.uv0[1]); + } + + float effective_world[16]; + if (world_matrix) { + MultiplyMat4(R_GRANNY_TO_ENGINE, world_matrix, effective_world); + } else { + std::copy(R_GRANNY_TO_ENGINE, R_GRANNY_TO_ENGINE + 16, effective_world); + } + + // Pack skin matrices for GPU skinning + std::vector bone_mats_flat; + bone_mats_flat.reserve(skin_matrices.size() * 16); + for (const auto& sm : part_skin_matrices) { + for (int k = 0; k < 16; ++k) bone_mats_flat.push_back(sm[k]); + } + + if (mesh.tri_groups.empty()) { + Gr2MeshDraw draw; + std::copy(effective_world, effective_world + 16, draw.world); + draw.positions = skinned_positions; + draw.normals = skinned_normals; + draw.uv0 = uvs; + draw.indices = mesh.indices; + draw.bone_indices = bone_indices; + draw.bone_weights = bone_weights; + draw.bone_matrices = bone_mats_flat; + if (!mesh.material_textures.empty()) + draw.texture0 = mesh.material_textures[0]; + if (draw.texture0.find("hair") != std::string::npos || mesh.name.find("hair") != std::string::npos || + draw.texture0.find("leaf") != std::string::npos || draw.texture0.find("tree") != std::string::npos) { + draw.alpha_test = true; + draw.alpha_ref = 70; + } + draws.push_back(std::move(draw)); + } else { + for (const auto& group : mesh.tri_groups) { + Gr2MeshDraw draw; + std::copy(effective_world, effective_world + 16, draw.world); + draw.positions = skinned_positions; + draw.normals = skinned_normals; + draw.uv0 = uvs; + draw.bone_indices = bone_indices; + draw.bone_weights = bone_weights; + draw.bone_matrices = bone_mats_flat; + + std::size_t start_idx = static_cast(group.tri_first * 3); + std::size_t count_idx = static_cast(group.tri_count * 3); + if (start_idx + count_idx <= mesh.indices.size()) { + draw.indices.assign(mesh.indices.begin() + start_idx, + mesh.indices.begin() + start_idx + count_idx); + } + + if (group.material_index >= 0 && group.material_index < static_cast(mesh.material_textures.size())) { + draw.texture0 = mesh.material_textures[group.material_index]; + } + if (draw.texture0.find("hair") != std::string::npos || mesh.name.find("hair") != std::string::npos || + draw.texture0.find("leaf") != std::string::npos || draw.texture0.find("tree") != std::string::npos) { + draw.alpha_test = true; + draw.alpha_ref = 70; + } + draws.push_back(std::move(draw)); + } + } + } + if(hardwareSkinning) { + for(auto& draw:draws){draw.gpu_skinning=!part_skin_matrices.empty();draw=ShareGpuMesh(std::move(draw));} + m_gpuParts=draws; + } + } + ApplySkins(draws, 0); + return draws; +} + +std::vector Gr2ModelInstance::BuildDrawCommands(float animation_time, const float* world_matrix, bool hardwareSkinning) { + std::vector draws; + if (!m_file) return draws; + + const auto& info = m_file->file_info(); + EvaluatePose(animation_time); + const auto& world_pose = m_worldPose; + const auto& skin_matrices = m_skinPose; + bool has_skeleton = !info.skeletons.empty(); + + // 1. Build main model draw commands + hardwareSkinning = hardwareSkinning && skin_matrices.size()<=128; + float cachedWorld[16]; + if(world_matrix)MultiplyMat4(R_GRANNY_TO_ENGINE,world_matrix,cachedWorld); + else std::copy_n(R_GRANNY_TO_ENGINE,16,cachedWorld); + if(hardwareSkinning && !m_gpuMain.empty()) { + draws=m_gpuMain;UpdateGpuDraws(draws,cachedWorld,skin_matrices); + } else { + for (const auto& mesh : info.meshes) { + std::vector skinned_positions; + std::vector skinned_normals; + std::vector uvs; + std::vector bone_indices; + std::vector bone_weights; + + skinned_positions.reserve(mesh.vertices.size() * 3); + skinned_normals.reserve(mesh.vertices.size() * 3); + uvs.reserve(mesh.vertices.size() * 2); + bone_indices.reserve(mesh.vertices.size() * 4); + bone_weights.reserve(mesh.vertices.size() * 4); + + for (const auto& v : mesh.vertices) { + float px = 0.0f, py = 0.0f, pz = 0.0f; + float nx = 0.0f, ny = 0.0f, nz = 0.0f; + float total_w = 0.0f; + + if (has_skeleton && !skin_matrices.empty() && (v.bone_weight[0] > 0)) { + float w0 = v.bone_weight[0] / 255.0f; + float w1 = v.bone_weight[1] / 255.0f; + float w2 = v.bone_weight[2] / 255.0f; + float w3 = v.bone_weight[3] / 255.0f; + + for (int b = 0; b < 4; ++b) { + if (v.bone_weight[b] == 0) continue; + float w = v.bone_weight[b] / 255.0f; + int local_slot = v.bone_index[b]; + int sk_bone = (local_slot < static_cast(mesh.bone_bindings.size())) ? mesh.bone_bindings[local_slot] : local_slot; + if (sk_bone >= 0 && sk_bone < static_cast(skin_matrices.size())) { + if(hardwareSkinning){total_w+=w;continue;} + const auto& M = skin_matrices[sk_bone]; + px += (v.pos[0] * M[0] + v.pos[1] * M[4] + v.pos[2] * M[8] + M[12]) * w; + py += (v.pos[0] * M[1] + v.pos[1] * M[5] + v.pos[2] * M[9] + M[13]) * w; + pz += (v.pos[0] * M[2] + v.pos[1] * M[6] + v.pos[2] * M[10] + M[14]) * w; + + nx += (v.normal[0] * M[0] + v.normal[1] * M[4] + v.normal[2] * M[8]) * w; + ny += (v.normal[0] * M[1] + v.normal[1] * M[5] + v.normal[2] * M[9]) * w; + nz += (v.normal[0] * M[2] + v.normal[1] * M[6] + v.normal[2] * M[10]) * w; + total_w += w; + } + } + + int b0 = v.bone_index[0] < mesh.bone_bindings.size() ? mesh.bone_bindings[v.bone_index[0]] : v.bone_index[0]; + int b1 = v.bone_index[1] < mesh.bone_bindings.size() ? mesh.bone_bindings[v.bone_index[1]] : v.bone_index[1]; + int b2 = v.bone_index[2] < mesh.bone_bindings.size() ? mesh.bone_bindings[v.bone_index[2]] : v.bone_index[2]; + int b3 = v.bone_index[3] < mesh.bone_bindings.size() ? mesh.bone_bindings[v.bone_index[3]] : v.bone_index[3]; + bone_indices.push_back(hardwareSkinning && (b0<0 || size_t(b0)>=skin_matrices.size()) ? uint8_t(255) : static_cast(b0)); + bone_indices.push_back(hardwareSkinning && (b1<0 || size_t(b1)>=skin_matrices.size()) ? uint8_t(255) : static_cast(b1)); + bone_indices.push_back(hardwareSkinning && (b2<0 || size_t(b2)>=skin_matrices.size()) ? uint8_t(255) : static_cast(b2)); + bone_indices.push_back(hardwareSkinning && (b3<0 || size_t(b3)>=skin_matrices.size()) ? uint8_t(255) : static_cast(b3)); + bone_weights.push_back(w0); bone_weights.push_back(w1); bone_weights.push_back(w2); bone_weights.push_back(w3); + } + + if (total_w < 1e-4f) { + px = v.pos[0]; py = v.pos[1]; pz = v.pos[2]; + nx = v.normal[0]; ny = v.normal[1]; nz = v.normal[2]; + if (bone_indices.size() < (skinned_positions.size() / 3 + 1) * 4) { + bone_indices.push_back(0); bone_indices.push_back(0); bone_indices.push_back(0); bone_indices.push_back(0); + bone_weights.push_back(hardwareSkinning ? 0.f : 1.f); bone_weights.push_back(0.0f); bone_weights.push_back(0.0f); bone_weights.push_back(0.0f); + } + } + + if(hardwareSkinning){px=v.pos[0];py=v.pos[1];pz=v.pos[2];nx=v.normal[0];ny=v.normal[1];nz=v.normal[2];} + skinned_positions.push_back(px); + skinned_positions.push_back(py); + skinned_positions.push_back(pz); + + skinned_normals.push_back(nx); + skinned_normals.push_back(ny); + skinned_normals.push_back(nz); + + uvs.push_back(v.uv0[0]); + uvs.push_back(v.uv0[1]); + } + + float effective_world[16]; + if (world_matrix) { + MultiplyMat4(R_GRANNY_TO_ENGINE, world_matrix, effective_world); + } else { + std::copy(R_GRANNY_TO_ENGINE, R_GRANNY_TO_ENGINE + 16, effective_world); + } + + std::vector bone_mats_flat; + bone_mats_flat.reserve(skin_matrices.size() * 16); + for (const auto& sm : skin_matrices) { + for (int k = 0; k < 16; ++k) bone_mats_flat.push_back(sm[k]); + } + + if (mesh.tri_groups.empty()) { + Gr2MeshDraw draw; + std::copy(effective_world, effective_world + 16, draw.world); + draw.positions = skinned_positions; + draw.normals = skinned_normals; + draw.uv0 = uvs; + draw.indices = mesh.indices; + draw.bone_indices = bone_indices; + draw.bone_weights = bone_weights; + draw.bone_matrices = bone_mats_flat; + if (!mesh.material_textures.empty()) + draw.texture0 = mesh.material_textures[0]; + if (draw.texture0.find("hair") != std::string::npos || mesh.name.find("hair") != std::string::npos || + draw.texture0.find("leaf") != std::string::npos || draw.texture0.find("tree") != std::string::npos) { + draw.alpha_test = true; + draw.alpha_ref = 70; + } + draws.push_back(std::move(draw)); + } else { + for (const auto& group : mesh.tri_groups) { + Gr2MeshDraw draw; + std::copy(effective_world, effective_world + 16, draw.world); + draw.positions = skinned_positions; + draw.normals = skinned_normals; + draw.uv0 = uvs; + draw.bone_indices = bone_indices; + draw.bone_weights = bone_weights; + draw.bone_matrices = bone_mats_flat; + + std::size_t start_idx = static_cast(group.tri_first * 3); + std::size_t count_idx = static_cast(group.tri_count * 3); + if (start_idx + count_idx <= mesh.indices.size()) { + draw.indices.assign(mesh.indices.begin() + start_idx, + mesh.indices.begin() + start_idx + count_idx); + } + + if (group.material_index >= 0 && group.material_index < static_cast(mesh.material_textures.size())) { + draw.texture0 = mesh.material_textures[group.material_index]; + } + if (draw.texture0.find("hair") != std::string::npos || mesh.name.find("hair") != std::string::npos || + draw.texture0.find("leaf") != std::string::npos || draw.texture0.find("tree") != std::string::npos) { + draw.alpha_test = true; + draw.alpha_ref = 70; + } + draws.push_back(std::move(draw)); + } + } + } + + if(hardwareSkinning) { + for(auto& draw:draws){draw.gpu_skinning=!skin_matrices.empty();draw=ShareGpuMesh(std::move(draw));} + m_gpuMain=draws; + } + } + ApplySkins(draws, 0); + + // 2. Build attached skinning parts (e.g. hair, armor) using current skin matrices + for (const auto& part : m_attached_parts) { + if (!part) continue; + auto part_draws = part->BuildDrawCommandsWithPalette(skin_matrices, world_matrix, has_skeleton ? &info.skeletons[0] : nullptr, hardwareSkinning); + for (auto& pd : part_draws) { + draws.push_back(std::move(pd)); + } + } + + // 3. Build attached bone models (e.g. weapon in right hand, shield in left hand) + if (has_skeleton && !world_pose.empty()) { + const auto& sk = info.skeletons[0]; + for (const auto& am : m_attached_models) { + if (!am.model) continue; + int bone_idx = -1; + for (size_t b = 0; b < sk.bones.size(); ++b) { + if (sk.bones[b].name == am.bone_name) { + bone_idx = static_cast(b); + break; + } + } + if (bone_idx < 0) continue; + + const auto& B = world_pose[bone_idx]; + float attached_local[16]; + MultiplyMat4(am.offset, B.data(), attached_local); + if (am.scaled) { + const float S[16] = {am.scale[0], 0, 0, 0, 0, am.scale[1], 0, 0, 0, 0, am.scale[2], 0, 0, 0, 0, 1}; + MultiplyMat4(attached_local, S, attached_local); + } + float attached_engine[16]; + MultiplyMat4(attached_local, R_GRANNY_TO_ENGINE, attached_engine); + float final_world[16]; + if (world_matrix) { + MultiplyMat4(attached_engine, world_matrix, final_world); + } else { + std::copy(attached_engine, attached_engine + 16, final_world); + } + + float attach_time = -1.0f; + if (am.animated && animation_time >= 0.0f) { + float duration = am.model->GetAnimationDuration(); + attach_time = duration > 0.0f ? std::fmod(animation_time, duration) : 0.0f; + } + auto attach_draws = am.model->BuildDrawCommands(attach_time, nullptr, hardwareSkinning); + for (auto& ad : attach_draws) { + std::copy(final_world, final_world + 16, ad.world); + draws.push_back(std::move(ad)); + } + } + } + + return draws; +} + +bool Gr2ModelInstance::GetLocalBounds(float& minX, float& minY, float& minZ, float& maxX, float& maxY, float& maxZ) const { + if (!m_file) return false; + const auto& info = m_file->file_info(); + if (info.meshes.empty()) return false; + + minX = 1e9f; minY = 1e9f; minZ = 1e9f; + maxX = -1e9f; maxY = -1e9f; maxZ = -1e9f; + + bool found = false; + for (const auto& mesh : info.meshes) { + for (const auto& v : mesh.vertices) { + float ex = v.pos[0]; + float ey = v.pos[2]; + float ez = -v.pos[1]; + minX = std::min(minX, ex); + minY = std::min(minY, ey); + minZ = std::min(minZ, ez); + maxX = std::max(maxX, ex); + maxY = std::max(maxY, ey); + maxZ = std::max(maxZ, ez); + found = true; + } + } + return found; +} + +} // namespace gr2_render diff --git a/gr2/tests/animation.cpp b/gr2/tests/animation.cpp new file mode 100644 index 0000000..68eba9e --- /dev/null +++ b/gr2/tests/animation.cpp @@ -0,0 +1,73 @@ +#include + +#include +#include +#include + +int main() { + // ScaleShearCurve uses 9 values per control point. A quadratic span reads + // three control points, so this is the regression case for the former 3*4 + // stack buffer in Curve::eval(). + gr2::Curve curve; + curve.degree = 2; + curve.dim = 9; + curve.knots = {0.0f, 1.0f, 2.0f}; + curve.controls.resize(27); + for (size_t i = 0; i < curve.controls.size(); ++i) { + curve.controls[i] = 1.0f + static_cast(i) * 0.01f; + } + + float out[9] = {}; + curve.eval(0.5f, out); + for (float value : out) { + if (!std::isfinite(value)) { + std::fprintf(stderr, "non-finite 9D curve output\n"); + return 1; + } + } + + // Degree 0 with several knots (AVA2 DaKeyframes32f) holds the last knot <= t. + gr2::Curve steps; + steps.degree = 0; + steps.dim = 1; + steps.knots = {0.0f, 0.5f, 1.0f}; + steps.controls = {10.0f, 20.0f, 30.0f}; + const float step_t[] = {-1.0f, 0.0f, 0.49f, 0.5f, 0.99f, 1.0f, 2.0f}; + const float step_v[] = {10.0f, 10.0f, 10.0f, 20.0f, 20.0f, 30.0f, 30.0f}; + for (size_t i = 0; i < sizeof step_t / sizeof step_t[0]; ++i) { + float v = 0.0f; + steps.eval(step_t[i], &v); + if (v != step_v[i]) { + std::fprintf(stderr, "degree-0 step t=%f got %f want %f\n", step_t[i], v, step_v[i]); + return 1; + } + } + + // BoneTrack::sample fills SRT components and flags; sample_local = compose(sample). + gr2::BoneTrack track; + track.position.degree = 1; + track.position.dim = 3; + track.position.knots = {0.0f, 1.0f}; + track.position.controls = {0.0f, 0.0f, 0.0f, 2.0f, 4.0f, 6.0f}; + track.orientation.degree = 0; + track.orientation.dim = 4; + track.orientation.knots = {0.0f}; + track.orientation.controls = {0.0f, 0.0f, 0.70710678f, 0.70710678f}; // 90 deg about Z + gr2::Transform x; + track.sample(0.5f, x); + if (x.flags != 3 || std::fabs(x.position[0] - 1.0f) > 1e-5f || std::fabs(x.position[2] - 3.0f) > 1e-5f) { + std::fprintf(stderr, "BoneTrack::sample flags=%u pos=%f,%f,%f\n", x.flags, x.position[0], x.position[1], x.position[2]); + return 1; + } + gr2::Animation anim; + anim.tracks.push_back(track); + std::vector local; + anim.sample_local(0.5f, local); + const gr2::Mat4 m = gr2::compose(x); + // Row-major composite: row 0 is the rotated X axis (0,1,0); translation in 12..14. + if (local.size() != 1 || local[0] != m || std::fabs(m[1] - 1.0f) > 1e-5f || std::fabs(m[12] - 1.0f) > 1e-5f) { + std::fprintf(stderr, "compose mismatch m[1]=%f m[12]=%f\n", m[1], m[12]); + return 1; + } + return 0; +} diff --git a/gr2/tests/gr2_render_test.cpp b/gr2/tests/gr2_render_test.cpp new file mode 100644 index 0000000..e504925 --- /dev/null +++ b/gr2/tests/gr2_render_test.cpp @@ -0,0 +1,41 @@ +#include +#include +#include +#include + +int main() { + std::cout << "[Test] Running Gr2Render unit tests..." << std::endl; + + // Test 1: Null/empty load + { + auto inst = gr2_render::Gr2ModelInstance::Load("non_existent_file.gr2"); + assert(!inst && "Expected nullptr for non-existent file"); + + auto inst_mem = gr2_render::Gr2ModelInstance::LoadFromMemory(nullptr, 0); + assert(!inst_mem && "Expected nullptr for empty memory buffer"); + std::cout << " PASS: Null/invalid input handles gracefully." << std::endl; + } + + // Test 2: Gr2MeshDraw layout and defaults + { + gr2_render::Gr2MeshDraw draw; + assert(draw.world[0] == 1.0f && draw.world[5] == 1.0f && draw.world[10] == 1.0f && draw.world[15] == 1.0f); + assert(draw.alpha_ref == 70); + assert(!draw.alpha_test); + assert(!draw.double_sided); + assert(draw.z_write); + assert(draw.lighting); + std::cout << " PASS: Gr2MeshDraw default values valid." << std::endl; + } + + // Test 3: Load corrupt GR2 header into LoadFromMemory + { + std::vector bogus(128, 0xAA); + auto inst = gr2_render::Gr2ModelInstance::LoadFromMemory(bogus.data(), bogus.size(), "bogus"); + assert(!inst && "Expected failed load for corrupt data"); + std::cout << " PASS: Corrupt GR2 data safely rejected by LoadFromMemory." << std::endl; + } + + std::cout << "[Test] All Gr2Render tests passed successfully!" << std::endl; + return 0; +} diff --git a/gr2/tests/loader_errors.cpp b/gr2/tests/loader_errors.cpp new file mode 100644 index 0000000..2df7726 --- /dev/null +++ b/gr2/tests/loader_errors.cpp @@ -0,0 +1,105 @@ +#include + +#include +#include +#include +#include + +namespace { + +void wr32(std::vector &bytes, size_t off, uint32_t value) { + bytes[off + 0] = uint8_t(value); + bytes[off + 1] = uint8_t(value >> 8); + bytes[off + 2] = uint8_t(value >> 16); + bytes[off + 3] = uint8_t(value >> 24); +} + +constexpr uint32_t kMagic32LE[] = { 0xCAB067B8, 0x0FB16DF8, 0x7E8C7284, 0x1E00195E }; +constexpr uint32_t kMagic64LE[] = { 0x5E499BE5, 0x141F636F, 0xA9EB131E, 0xC4EDBE90 }; +constexpr uint32_t kMagic32BE[] = { 0xB595110E, 0x4BB5A56A, 0x502828EB, 0x04B37825 }; + +std::vector granny_header(size_t size, uint32_t section_count, const uint32_t *magic = kMagic32LE) { + std::vector bytes(size, 0); + for (int i = 0; i < 4; ++i) { + wr32(bytes, size_t(i) * 4, magic[i]); + } + constexpr size_t h = 32; + wr32(bytes, h + 0, 6); // Version + wr32(bytes, h + 4, uint32_t(size)); + wr32(bytes, h + 12, 40); // section table starts at byte 72 + wr32(bytes, h + 16, section_count); + // Root type/object remain section 0, offset 0. With no section this must be + // rejected by the FileInfo stage rather than returned as an empty File. + return bytes; +} + +bool expect_failure(const std::vector &bytes, const char *stage) { + gr2::LoadError err; + auto file = gr2::File::load(bytes.data(), bytes.size(), &err); + if (file || err.stage != stage) { + std::fprintf(stderr, "expected failure stage '%s', got file=%d stage='%s' message='%s'\n", + stage, file.has_value(), err.stage.c_str(), err.message.c_str()); + return false; + } + return true; +} + +} // namespace + +int main() { + bool ok = true; + ok &= expect_failure(std::vector(80, 0), "header"); + ok &= expect_failure(granny_header(80, 0), "fileinfo"); + // 64-bit little-endian Granny (AVA2 plechi_* assets) passes the header stage; + // big-endian is still rejected there. + ok &= expect_failure(granny_header(80, 0, kMagic64LE), "fileinfo"); + ok &= expect_failure(granny_header(80, 0, kMagic32BE), "header"); + + auto unsupported = granny_header(160, 1); + constexpr size_t section = 72; + wr32(unsupported, section + 0, 3); // BitKnit v1 is not implemented + wr32(unsupported, section + 4, uint32_t(unsupported.size())); + wr32(unsupported, section + 12, 1); // non-empty expanded section + ok &= expect_failure(unsupported, "section"); + + // BitKnit2 (Format 4) with an empty stream: no 0x75B1 magic -> clean section failure. + auto bitknit_empty = unsupported; + wr32(bitknit_empty, section + 0, 4); + ok &= expect_failure(bitknit_empty, "section"); + + // BitKnit2 stored quantum: magic 0x75B1, u16 0 marker, 8 raw bytes. The section + // decodes, so loading proceeds to the (empty) type tree instead of failing in "section". + auto bitknit_stored = granny_header(160, 1); + const uint8_t stream[] = { 0xB1, 0x75, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; + for (size_t i = 0; i < sizeof(stream); ++i) bitknit_stored[120 + i] = stream[i]; + wr32(bitknit_stored, section + 0, 4); + wr32(bitknit_stored, section + 4, 120); + wr32(bitknit_stored, section + 8, uint32_t(sizeof(stream))); + wr32(bitknit_stored, section + 12, 8); + { + gr2::LoadError err; + auto file = gr2::File::load(bitknit_stored.data(), bitknit_stored.size(), &err); + if (!file && err.stage == "section") { + std::fprintf(stderr, "BitKnit2 stored quantum rejected: %s\n", err.message.c_str()); + ok = false; + } + } + + // Truncated stored quantum (claims 8 bytes, carries 4) must fail cleanly. + auto bitknit_short = bitknit_stored; + wr32(bitknit_short, section + 8, 8); + ok &= expect_failure(bitknit_short, "section"); + + // BitKnit2 fixup table: u32 compressed size pointing past EOF -> clean "fixup" failure. + auto bitknit_fixup = bitknit_stored; + wr32(bitknit_fixup, section + 28, 150); // PointerFixupArrayOffset + wr32(bitknit_fixup, section + 32, 1); // PointerFixupArrayCount + wr32(bitknit_fixup, 150, 1000); + ok &= expect_failure(bitknit_fixup, "fixup"); + + auto bad_offset = granny_header(160, 1); + wr32(bad_offset, section + 4, UINT32_MAX); + ok &= expect_failure(bad_offset, "section"); + + return ok ? 0 : 1; +} diff --git a/network/CMakeLists.txt b/network/CMakeLists.txt new file mode 100644 index 0000000..2ff6608 --- /dev/null +++ b/network/CMakeLists.txt @@ -0,0 +1,26 @@ +cmake_minimum_required(VERSION 3.20) +project(network LANGUAGES CXX) + +set(CMAKE_CXX_STANDARD 20) +set(CMAKE_CXX_STANDARD_REQUIRED ON) + +add_library(network STATIC + src/connection_phase.cpp + src/cipher.cpp + src/packet.cpp + src/network_client.cpp +) + +target_include_directories(network PUBLIC + $ + $ +) + +add_library(network::network ALIAS network) + +option(NETWORK_BUILD_TESTS "Build network SDK tests" ON) +if(NETWORK_BUILD_TESTS) + add_executable(network_test tests/network_test.cpp) + target_link_libraries(network_test PRIVATE network) + add_test(NAME network_test COMMAND network_test) +endif() diff --git a/network/include/network/cipher.h b/network/include/network/cipher.h new file mode 100644 index 0000000..c5ec3bb --- /dev/null +++ b/network/include/network/cipher.h @@ -0,0 +1,67 @@ +#pragma once + +#include "types.h" +#include +#include +#include +#include + +namespace metin2::network { + +using TeaKey = std::array; + +class TeaCipher { +public: + TeaCipher() = default; + explicit TeaCipher(const TeaKey& key); + + void SetKey(const TeaKey& key); + const TeaKey& GetKey() const { return m_key; } + + void EncryptBlock(uint32_t& y, uint32_t& z) const; + void DecryptBlock(uint32_t& y, uint32_t& z) const; + + std::vector Encrypt(std::span input) const; + std::vector Decrypt(std::span input) const; + +private: + TeaKey m_key{0, 0, 0, 0}; +}; + +class RollingXorCipher { +public: + RollingXorCipher() = default; + explicit RollingXorCipher(uint32_t seed_key); + + void Reset(uint32_t seed_key); + void Process(uint8_t* data, size_t size); + +private: + uint32_t m_key = 0; + uint32_t m_state = 0; +}; + +class CipherContext { +public: + CipherContext() = default; + + void SetEnabled(bool enabled) { m_enabled = enabled; } + bool IsEnabled() const { return m_enabled; } + + void InitializeKeys(const TeaKey& tea_key, uint32_t xor_seed); + + void EncryptSend(uint8_t* data, size_t size); + void DecryptRecv(uint8_t* data, size_t size); + + TeaCipher& GetSendTea() { return m_send_tea; } + TeaCipher& GetRecvTea() { return m_recv_tea; } + +private: + bool m_enabled = false; + TeaCipher m_send_tea; + TeaCipher m_recv_tea; + RollingXorCipher m_send_xor; + RollingXorCipher m_recv_xor; +}; + +} // namespace metin2::network diff --git a/network/include/network/connection_phase.h b/network/include/network/connection_phase.h new file mode 100644 index 0000000..9b94a08 --- /dev/null +++ b/network/include/network/connection_phase.h @@ -0,0 +1,32 @@ +#pragma once + +#include "types.h" +#include + +namespace metin2::network { + +class PhaseStateMachine { +public: + using PhaseChangeCallback = std::function; + + PhaseStateMachine(); + explicit PhaseStateMachine(ConnectionPhase initial_phase); + + ConnectionPhase GetCurrentPhase() const { return m_current_phase; } + const char* GetPhaseName() const { return ToString(m_current_phase); } + + bool CanTransitionTo(ConnectionPhase target_phase) const; + bool TransitionTo(ConnectionPhase target_phase); + void ForcePhase(ConnectionPhase phase); + + void SetPhaseChangeCallback(PhaseChangeCallback cb) { m_callback = std::move(cb); } + + bool IsConnected() const { return m_current_phase != ConnectionPhase::Disconnected; } + bool IsInGame() const { return m_current_phase == ConnectionPhase::InGame; } + +private: + ConnectionPhase m_current_phase = ConnectionPhase::Disconnected; + PhaseChangeCallback m_callback; +}; + +} // namespace metin2::network diff --git a/network/include/network/network.h b/network/include/network/network.h new file mode 100644 index 0000000..b4d870a --- /dev/null +++ b/network/include/network/network.h @@ -0,0 +1,7 @@ +#pragma once + +#include "types.h" +#include "connection_phase.h" +#include "cipher.h" +#include "packet.h" +#include "network_client.h" diff --git a/network/include/network/network_client.h b/network/include/network/network_client.h new file mode 100644 index 0000000..7457fb6 --- /dev/null +++ b/network/include/network/network_client.h @@ -0,0 +1,87 @@ +#pragma once + +#include "types.h" +#include "connection_phase.h" +#include "cipher.h" +#include "packet.h" +#include +#include + +namespace metin2::network { + +class NetworkClient { +public: + using HandshakeCallback = std::function; + using AuthResultCallback = std::function; + using CharacterListCallback = std::function& characters)>; + using GameStartCallback = std::function; + using ChatCallback = std::function; + using ActorMoveCallback = std::function; + using GenericPacketCallback = std::function; + + NetworkClient(); + + // Transport Interface (zero socket binding) + void PushReceivedData(const uint8_t* data, size_t size); + std::vector PopSendData(); + bool HasPendingSendData() const { return !m_send_buffer.empty(); } + + // Phase and State + ConnectionPhase GetPhase() const { return m_phase_fsm.GetCurrentPhase(); } + const char* GetPhaseName() const { return m_phase_fsm.GetPhaseName(); } + bool SetPhase(ConnectionPhase phase) { return m_phase_fsm.TransitionTo(phase); } + void ForcePhase(ConnectionPhase phase) { m_phase_fsm.ForcePhase(phase); } + bool IsConnected() const { return m_phase_fsm.IsConnected(); } + bool IsInGame() const { return m_phase_fsm.IsInGame(); } + + // Cipher Control + CipherContext& GetCipher() { return m_cipher; } + void EnableCipher(bool enable) { m_cipher.SetEnabled(enable); } + void SetEncryptionKeys(const TeaKey& tea_key, uint32_t xor_seed) { + m_cipher.InitializeKeys(tea_key, xor_seed); + } + + // Packet Registry + PacketRegistry& GetRegistry() { return m_registry; } + + // Callback Setup + void SetPhaseCallback(PhaseStateMachine::PhaseChangeCallback cb) { m_phase_fsm.SetPhaseChangeCallback(std::move(cb)); } + void SetOnHandshake(HandshakeCallback cb) { m_on_handshake = std::move(cb); } + void SetOnAuthResult(AuthResultCallback cb) { m_on_auth_result = std::move(cb); } + void SetOnCharacterList(CharacterListCallback cb) { m_on_character_list = std::move(cb); } + void SetOnGameStart(GameStartCallback cb) { m_on_game_start = std::move(cb); } + void SetOnChat(ChatCallback cb) { m_on_chat = std::move(cb); } + void SetOnActorMove(ActorMoveCallback cb) { m_on_actor_move = std::move(cb); } + void SetOnGenericPacket(GenericPacketCallback cb) { m_on_generic_packet = std::move(cb); } + + // High-Level Sending Methods + void SendHandshakeAck(uint32_t client_time); + void SendLogin(const std::string& username, const std::string& password); + void SendSelectCharacter(uint8_t slot_index); + void SendEnterGame(); + void SendChat(uint8_t chat_type, const std::string& text); + void SendMove(float x, float y, float z, float rotation, uint32_t move_type); + void SendRawPacket(uint8_t header, const void* payload, size_t payload_size); + void SendDynamicPacket(uint8_t header, const void* payload, size_t payload_size); + + void Reset(); + +private: + void ProcessPacket(const Packet& packet); + + PhaseStateMachine m_phase_fsm; + CipherContext m_cipher; + PacketRegistry m_registry; + PacketBuffer m_recv_buffer; + std::vector m_send_buffer; + + HandshakeCallback m_on_handshake; + AuthResultCallback m_on_auth_result; + CharacterListCallback m_on_character_list; + GameStartCallback m_on_game_start; + ChatCallback m_on_chat; + ActorMoveCallback m_on_actor_move; + GenericPacketCallback m_on_generic_packet; +}; + +} // namespace metin2::network diff --git a/network/include/network/packet.h b/network/include/network/packet.h new file mode 100644 index 0000000..de3f849 --- /dev/null +++ b/network/include/network/packet.h @@ -0,0 +1,65 @@ +#pragma once + +#include "types.h" +#include +#include +#include +#include +#include + +namespace metin2::network { + +struct Packet { + uint8_t header = 0; + std::vector payload; + + size_t TotalSize() const { return 1 + payload.size(); } +}; + +enum class PacketSizeMode { + Fixed, // Fixed payload size (header + payload) + Dynamic // Header (1 byte) + uint16_t size (2 bytes) + payload +}; + +struct PacketDescriptor { + uint8_t header = 0; + PacketSizeMode mode = PacketSizeMode::Fixed; + size_t fixed_payload_size = 0; +}; + +class PacketRegistry { +public: + PacketRegistry(); + + void Register(uint8_t header, size_t fixed_payload_size); + void RegisterDynamic(uint8_t header); + + const PacketDescriptor* Find(uint8_t header) const; + bool HasHeader(uint8_t header) const; + +private: + void RegisterDefaultPackets(); + std::unordered_map m_descriptors; +}; + +class PacketBuffer { +public: + PacketBuffer() = default; + + void Append(const uint8_t* data, size_t size); + void Append(const std::vector& data); + + // Extracts all full frames available in buffer according to registry + std::vector ExtractPackets(const PacketRegistry& registry); + + size_t AvailableBytes() const { return m_buffer.size() - m_read_offset; } + void Clear(); + +private: + std::vector m_buffer; + size_t m_read_offset = 0; + + void Compact(); +}; + +} // namespace metin2::network diff --git a/network/include/network/types.h b/network/include/network/types.h new file mode 100644 index 0000000..a3ea842 --- /dev/null +++ b/network/include/network/types.h @@ -0,0 +1,77 @@ +#pragma once + +#include +#include +#include +#include +#include + +namespace metin2::network { + +enum class ConnectionPhase { + Disconnected = 0, + Handshake, + Auth, + CharacterSelect, + GameLoading, + InGame +}; + +const char* ToString(ConnectionPhase phase); + +enum EPacketHeader : uint8_t { + HEADER_NONE = 0, + HEADER_CG_LOGIN = 1, + HEADER_CG_ATTACK = 2, + HEADER_CG_CHAT = 3, + HEADER_CG_CHARACTER_CREATE = 4, + HEADER_CG_CHARACTER_DELETE = 5, + HEADER_CG_CHARACTER_SELECT = 6, + HEADER_CG_MOVE = 7, + HEADER_CG_SYNC_POSITION = 8, + HEADER_CG_ENTERGAME = 10, + HEADER_CG_ITEM_USE = 11, + HEADER_CG_ITEM_MOVE = 12, + HEADER_CG_PONG = 254, + HEADER_CG_HANDSHAKE = 255, + + HEADER_GC_AUTH_SUCCESS = 101, + HEADER_GC_AUTH_FAILURE = 102, + HEADER_GC_CHARACTER_INFO = 103, + HEADER_GC_CHARACTER_LIST = 104, + HEADER_GC_GAME_START = 105, + HEADER_GC_CHAT = 106, + HEADER_GC_ACTOR_ADD = 107, + HEADER_GC_ACTOR_REMOVE = 108, + HEADER_GC_ACTOR_MOVE = 109, + HEADER_GC_ACTOR_ATTACK = 110, + HEADER_GC_ITEM_SET = 111, + HEADER_GC_PING = 253, + HEADER_GC_HANDSHAKE = 255 +}; + +struct CharacterSummary { + uint32_t id = 0; + std::string name; + uint8_t job = 0; // Warrior, Assassin, Sura, Shaman + uint8_t level = 1; + uint32_t play_time = 0; + uint16_t body_armor = 0; + uint16_t weapon = 0; + uint16_t hair = 0; +}; + +struct PlayerInfo { + uint32_t player_id = 0; + std::string name; + float x = 0.0f; + float y = 0.0f; + float z = 0.0f; + float rotation = 0.0f; + uint32_t hp = 100; + uint32_t max_hp = 100; + uint32_t sp = 100; + uint32_t max_sp = 100; +}; + +} // namespace metin2::network diff --git a/network/src/cipher.cpp b/network/src/cipher.cpp new file mode 100644 index 0000000..d6fe306 --- /dev/null +++ b/network/src/cipher.cpp @@ -0,0 +1,133 @@ +#include "network/cipher.h" +#include + +namespace metin2::network { + +TeaCipher::TeaCipher(const TeaKey& key) + : m_key(key) {} + +void TeaCipher::SetKey(const TeaKey& key) { + m_key = key; +} + +void TeaCipher::EncryptBlock(uint32_t& y, uint32_t& z) const { + uint32_t sum = 0; + constexpr uint32_t delta = 0x9e3779b9u; + for (int i = 0; i < 32; ++i) { + y += ((z << 4 ^ z >> 5) + z) ^ (sum + m_key[sum & 3]); + sum += delta; + z += ((y << 4 ^ y >> 5) + y) ^ (sum + m_key[(sum >> 11) & 3]); + } +} + +void TeaCipher::DecryptBlock(uint32_t& y, uint32_t& z) const { + uint32_t sum = 0xc6ef3720u; // 32 * 0x9e3779b9 + constexpr uint32_t delta = 0x9e3779b9u; + for (int i = 0; i < 32; ++i) { + z -= ((y << 4 ^ y >> 5) + y) ^ (sum + m_key[(sum >> 11) & 3]); + sum -= delta; + y -= ((z << 4 ^ z >> 5) + z) ^ (sum + m_key[sum & 3]); + } +} + +static uint32_t ReadU32LE(const uint8_t* p) { + return static_cast(p[0]) | + (static_cast(p[1]) << 8) | + (static_cast(p[2]) << 16) | + (static_cast(p[3]) << 24); +} + +static void WriteU32LE(uint8_t* p, uint32_t v) { + p[0] = static_cast(v & 0xFF); + p[1] = static_cast((v >> 8) & 0xFF); + p[2] = static_cast((v >> 16) & 0xFF); + p[3] = static_cast((v >> 24) & 0xFF); +} + +std::vector TeaCipher::Encrypt(std::span input) const { + size_t padded_size = (input.size() + 7) / 8 * 8; + std::vector out(padded_size, 0); + std::memcpy(out.data(), input.data(), input.size()); + + for (size_t i = 0; i < padded_size; i += 8) { + uint32_t y = ReadU32LE(out.data() + i); + uint32_t z = ReadU32LE(out.data() + i + 4); + EncryptBlock(y, z); + WriteU32LE(out.data() + i, y); + WriteU32LE(out.data() + i + 4, z); + } + return out; +} + +std::vector TeaCipher::Decrypt(std::span input) const { + size_t full_blocks = (input.size() / 8) * 8; + std::vector out(input.begin(), input.begin() + full_blocks); + + for (size_t i = 0; i < full_blocks; i += 8) { + uint32_t y = ReadU32LE(out.data() + i); + uint32_t z = ReadU32LE(out.data() + i + 4); + DecryptBlock(y, z); + WriteU32LE(out.data() + i, y); + WriteU32LE(out.data() + i + 4, z); + } + return out; +} + +// RollingXorCipher +RollingXorCipher::RollingXorCipher(uint32_t seed_key) { + Reset(seed_key); +} + +void RollingXorCipher::Reset(uint32_t seed_key) { + m_key = seed_key; + m_state = seed_key; +} + +void RollingXorCipher::Process(uint8_t* data, size_t size) { + for (size_t i = 0; i < size; ++i) { + // Linear feedback shift rolling key + m_state = (m_state * 1103515245u + 12345u); + uint8_t mask = static_cast((m_state >> 16) & 0xFF); + data[i] ^= mask; + } +} + +// CipherContext +void CipherContext::InitializeKeys(const TeaKey& tea_key, uint32_t xor_seed) { + m_send_tea.SetKey(tea_key); + m_recv_tea.SetKey(tea_key); + m_send_xor.Reset(xor_seed); + m_recv_xor.Reset(xor_seed); +} + +void CipherContext::EncryptSend(uint8_t* data, size_t size) { + if (!m_enabled || size == 0) return; + // Fast block TEA if multiple of 8, else rolling XOR + size_t tea_len = (size / 8) * 8; + for (size_t i = 0; i < tea_len; i += 8) { + uint32_t y = ReadU32LE(data + i); + uint32_t z = ReadU32LE(data + i + 4); + m_send_tea.EncryptBlock(y, z); + WriteU32LE(data + i, y); + WriteU32LE(data + i + 4, z); + } + // Apply rolling XOR for streaming confidentiality & anti-replay + m_send_xor.Process(data, size); +} + +void CipherContext::DecryptRecv(uint8_t* data, size_t size) { + if (!m_enabled || size == 0) return; + // Reverse rolling XOR first + m_recv_xor.Process(data, size); + // Reverse TEA blocks + size_t tea_len = (size / 8) * 8; + for (size_t i = 0; i < tea_len; i += 8) { + uint32_t y = ReadU32LE(data + i); + uint32_t z = ReadU32LE(data + i + 4); + m_recv_tea.DecryptBlock(y, z); + WriteU32LE(data + i, y); + WriteU32LE(data + i + 4, z); + } +} + +} // namespace metin2::network diff --git a/network/src/connection_phase.cpp b/network/src/connection_phase.cpp new file mode 100644 index 0000000..8477524 --- /dev/null +++ b/network/src/connection_phase.cpp @@ -0,0 +1,76 @@ +#include "network/connection_phase.h" + +namespace metin2::network { + +const char* ToString(ConnectionPhase phase) { + switch (phase) { + case ConnectionPhase::Disconnected: return "Disconnected"; + case ConnectionPhase::Handshake: return "Handshake"; + case ConnectionPhase::Auth: return "Auth"; + case ConnectionPhase::CharacterSelect: return "CharacterSelect"; + case ConnectionPhase::GameLoading: return "GameLoading"; + case ConnectionPhase::InGame: return "InGame"; + default: return "Unknown"; + } +} + +PhaseStateMachine::PhaseStateMachine() + : m_current_phase(ConnectionPhase::Disconnected) {} + +PhaseStateMachine::PhaseStateMachine(ConnectionPhase initial_phase) + : m_current_phase(initial_phase) {} + +bool PhaseStateMachine::CanTransitionTo(ConnectionPhase target_phase) const { + if (m_current_phase == target_phase) { + return true; + } + + // Always allowed to disconnect + if (target_phase == ConnectionPhase::Disconnected) { + return true; + } + + switch (m_current_phase) { + case ConnectionPhase::Disconnected: + return target_phase == ConnectionPhase::Handshake || target_phase == ConnectionPhase::Auth; + case ConnectionPhase::Handshake: + return target_phase == ConnectionPhase::Auth; + case ConnectionPhase::Auth: + return target_phase == ConnectionPhase::CharacterSelect; + case ConnectionPhase::CharacterSelect: + return target_phase == ConnectionPhase::GameLoading || target_phase == ConnectionPhase::Auth; + case ConnectionPhase::GameLoading: + return target_phase == ConnectionPhase::InGame || target_phase == ConnectionPhase::CharacterSelect; + case ConnectionPhase::InGame: + return target_phase == ConnectionPhase::CharacterSelect || target_phase == ConnectionPhase::GameLoading; + default: + return false; + } +} + +bool PhaseStateMachine::TransitionTo(ConnectionPhase target_phase) { + if (!CanTransitionTo(target_phase)) { + return false; + } + + if (m_current_phase != target_phase) { + ConnectionPhase old = m_current_phase; + m_current_phase = target_phase; + if (m_callback) { + m_callback(old, target_phase); + } + } + return true; +} + +void PhaseStateMachine::ForcePhase(ConnectionPhase phase) { + if (m_current_phase != phase) { + ConnectionPhase old = m_current_phase; + m_current_phase = phase; + if (m_callback) { + m_callback(old, phase); + } + } +} + +} // namespace metin2::network diff --git a/network/src/network_client.cpp b/network/src/network_client.cpp new file mode 100644 index 0000000..b5f7fb3 --- /dev/null +++ b/network/src/network_client.cpp @@ -0,0 +1,221 @@ +#include "network/network_client.h" +#include + +namespace metin2::network { + +NetworkClient::NetworkClient() + : m_phase_fsm(ConnectionPhase::Disconnected) { +} + +void NetworkClient::Reset() { + m_phase_fsm.ForcePhase(ConnectionPhase::Disconnected); + m_cipher.SetEnabled(false); + m_recv_buffer.Clear(); + m_send_buffer.clear(); +} + +void NetworkClient::PushReceivedData(const uint8_t* data, size_t size) { + if (!data || size == 0) return; + + std::vector decrypted(data, data + size); + if (m_cipher.IsEnabled()) { + m_cipher.DecryptRecv(decrypted.data(), decrypted.size()); + } + + m_recv_buffer.Append(decrypted); + + auto packets = m_recv_buffer.ExtractPackets(m_registry); + for (const auto& pkt : packets) { + ProcessPacket(pkt); + } +} + +std::vector NetworkClient::PopSendData() { + std::vector result; + if (!m_send_buffer.empty()) { + result = std::move(m_send_buffer); + m_send_buffer.clear(); + } + return result; +} + +void NetworkClient::SendRawPacket(uint8_t header, const void* payload, size_t payload_size) { + std::vector raw; + raw.reserve(1 + payload_size); + raw.push_back(header); + if (payload && payload_size > 0) { + const uint8_t* bytes = static_cast(payload); + raw.insert(raw.end(), bytes, bytes + payload_size); + } + + if (m_cipher.IsEnabled()) { + m_cipher.EncryptSend(raw.data(), raw.size()); + } + + m_send_buffer.insert(m_send_buffer.end(), raw.begin(), raw.end()); +} + +void NetworkClient::SendDynamicPacket(uint8_t header, const void* payload, size_t payload_size) { + std::vector raw; + raw.reserve(3 + payload_size); + raw.push_back(header); + + uint16_t sz = static_cast(payload_size); + raw.push_back(static_cast(sz & 0xFF)); + raw.push_back(static_cast((sz >> 8) & 0xFF)); + + if (payload && payload_size > 0) { + const uint8_t* bytes = static_cast(payload); + raw.insert(raw.end(), bytes, bytes + payload_size); + } + + if (m_cipher.IsEnabled()) { + m_cipher.EncryptSend(raw.data(), raw.size()); + } + + m_send_buffer.insert(m_send_buffer.end(), raw.begin(), raw.end()); +} + +void NetworkClient::SendHandshakeAck(uint32_t client_time) { + SendRawPacket(HEADER_CG_HANDSHAKE, &client_time, sizeof(client_time)); +} + +void NetworkClient::SendLogin(const std::string& username, const std::string& password) { + char buf[64]; + std::memset(buf, 0, sizeof(buf)); + std::strncpy(buf, username.c_str(), 31); + std::strncpy(buf + 32, password.c_str(), 31); + SendRawPacket(HEADER_CG_LOGIN, buf, sizeof(buf)); +} + +void NetworkClient::SendSelectCharacter(uint8_t slot_index) { + SendRawPacket(HEADER_CG_CHARACTER_SELECT, &slot_index, 1); +} + +void NetworkClient::SendEnterGame() { + SendRawPacket(HEADER_CG_ENTERGAME, nullptr, 0); +} + +void NetworkClient::SendChat(uint8_t chat_type, const std::string& text) { + std::vector payload; + payload.reserve(1 + text.size()); + payload.push_back(chat_type); + payload.insert(payload.end(), text.begin(), text.end()); + SendDynamicPacket(HEADER_CG_CHAT, payload.data(), payload.size()); +} + +void NetworkClient::SendMove(float x, float y, float z, float rotation, uint32_t move_type) { + struct MovePacketPayload { + float x, y, z, rot; + uint32_t type; + } p{x, y, z, rotation, move_type}; + SendRawPacket(HEADER_CG_MOVE, &p, sizeof(p)); +} + +void NetworkClient::ProcessPacket(const Packet& packet) { + switch (packet.header) { + case HEADER_GC_HANDSHAKE: { + if (packet.payload.size() >= 4) { + uint32_t server_time = *reinterpret_cast(packet.payload.data()); + if (m_on_handshake) { + m_on_handshake(server_time); + } + } + break; + } + case HEADER_GC_AUTH_SUCCESS: { + SetPhase(ConnectionPhase::CharacterSelect); + if (m_on_auth_result) { + m_on_auth_result(true, 0, "Authentication successful"); + } + break; + } + case HEADER_GC_AUTH_FAILURE: { + uint32_t error_code = 0; + std::string msg; + if (packet.payload.size() >= 4) { + error_code = *reinterpret_cast(packet.payload.data()); + } + if (packet.payload.size() > 4) { + const char* str = reinterpret_cast(packet.payload.data() + 4); + size_t str_len = strnlen(str, packet.payload.size() - 4); + msg.assign(str, str_len); + } + if (m_on_auth_result) { + m_on_auth_result(false, error_code, msg); + } + break; + } + case HEADER_GC_CHARACTER_LIST: { + // Parse character summary list + // Layout per character: id(4), job(1), level(1), name(24) = 30 bytes + std::vector characters; + size_t offset = 0; + while (offset + 30 <= packet.payload.size()) { + CharacterSummary c; + c.id = *reinterpret_cast(packet.payload.data() + offset); + c.job = packet.payload[offset + 4]; + c.level = packet.payload[offset + 5]; + const char* name_ptr = reinterpret_cast(packet.payload.data() + offset + 6); + size_t nlen = strnlen(name_ptr, 24); + c.name.assign(name_ptr, nlen); + characters.push_back(c); + offset += 30; + } + if (m_on_character_list) { + m_on_character_list(characters); + } + break; + } + case HEADER_GC_GAME_START: { + SetPhase(ConnectionPhase::InGame); + PlayerInfo info; + if (packet.payload.size() >= 4 + 32 + 16) { + info.player_id = *reinterpret_cast(packet.payload.data()); + const char* name_ptr = reinterpret_cast(packet.payload.data() + 4); + info.name.assign(name_ptr, strnlen(name_ptr, 32)); + const float* coords = reinterpret_cast(packet.payload.data() + 36); + info.x = coords[0]; + info.y = coords[1]; + info.z = coords[2]; + info.rotation = coords[3]; + } + if (m_on_game_start) { + m_on_game_start(info); + } + break; + } + case HEADER_GC_CHAT: { + if (!packet.payload.empty()) { + uint8_t chat_type = packet.payload[0]; + std::string msg; + if (packet.payload.size() > 1) { + msg.assign(reinterpret_cast(packet.payload.data() + 1), packet.payload.size() - 1); + } + if (m_on_chat) { + m_on_chat(0, chat_type, msg); + } + } + break; + } + case HEADER_GC_ACTOR_MOVE: { + if (packet.payload.size() >= 4 + 16 + 1) { + uint32_t vid = *reinterpret_cast(packet.payload.data()); + const float* coords = reinterpret_cast(packet.payload.data() + 4); + uint8_t move_type = packet.payload[20]; + if (m_on_actor_move) { + m_on_actor_move(vid, coords[0], coords[1], coords[2], coords[3], move_type); + } + } + break; + } + default: + break; + } + + if (m_on_generic_packet) { + m_on_generic_packet(packet); + } +} + +} // namespace metin2::network diff --git a/network/src/packet.cpp b/network/src/packet.cpp new file mode 100644 index 0000000..ac60d07 --- /dev/null +++ b/network/src/packet.cpp @@ -0,0 +1,149 @@ +#include "network/packet.h" +#include +#include + +namespace metin2::network { + +PacketRegistry::PacketRegistry() { + RegisterDefaultPackets(); +} + +void PacketRegistry::Register(uint8_t header, size_t fixed_payload_size) { + PacketDescriptor desc; + desc.header = header; + desc.mode = PacketSizeMode::Fixed; + desc.fixed_payload_size = fixed_payload_size; + m_descriptors[header] = desc; +} + +void PacketRegistry::RegisterDynamic(uint8_t header) { + PacketDescriptor desc; + desc.header = header; + desc.mode = PacketSizeMode::Dynamic; + desc.fixed_payload_size = 0; + m_descriptors[header] = desc; +} + +const PacketDescriptor* PacketRegistry::Find(uint8_t header) const { + auto it = m_descriptors.find(header); + if (it != m_descriptors.end()) { + return &it->second; + } + return nullptr; +} + +bool PacketRegistry::HasHeader(uint8_t header) const { + return m_descriptors.find(header) != m_descriptors.end(); +} + +void PacketRegistry::RegisterDefaultPackets() { + // Client -> Server default headers + Register(HEADER_CG_HANDSHAKE, 4); // uint32_t handshake_time + Register(HEADER_CG_PONG, 4); // uint32_t ping_id + Register(HEADER_CG_LOGIN, 32 + 32); // username (32) + password (32) + Register(HEADER_CG_CHARACTER_SELECT, 1); // slot_index (1) + Register(HEADER_CG_CHARACTER_DELETE, 1); // slot_index (1) + Register(HEADER_CG_ENTERGAME, 0); // empty payload + Register(HEADER_CG_MOVE, 4 * 4 + 1); // x, y, z, rot, type + Register(HEADER_CG_ATTACK, 4 + 1); // target_vid, type + RegisterDynamic(HEADER_CG_CHAT); // dynamic chat message + + // Server -> Client default headers + Register(HEADER_GC_HANDSHAKE, 8); // server_time (4) + delta (4) + Register(HEADER_GC_PING, 4); // ping_id (4) + Register(HEADER_GC_AUTH_SUCCESS, 4); // account_id (4) + Register(HEADER_GC_AUTH_FAILURE, 4 + 64); // error_code (4) + error_msg (64) + Register(HEADER_GC_GAME_START, 4 + 32 + 4 * 4); // vid + name + x, y, z, rot + Register(HEADER_GC_ACTOR_MOVE, 4 + 4 * 4 + 1); // vid + x, y, z, rot + type + Register(HEADER_GC_ACTOR_REMOVE, 4); // vid + RegisterDynamic(HEADER_GC_CHARACTER_LIST); // dynamic list + RegisterDynamic(HEADER_GC_CHAT); // dynamic chat +} + +// PacketBuffer +void PacketBuffer::Append(const uint8_t* data, size_t size) { + if (data && size > 0) { + m_buffer.insert(m_buffer.end(), data, data + size); + } +} + +void PacketBuffer::Append(const std::vector& data) { + Append(data.data(), data.size()); +} + +void PacketBuffer::Clear() { + m_buffer.clear(); + m_read_offset = 0; +} + +void PacketBuffer::Compact() { + if (m_read_offset > 0) { + if (m_read_offset < m_buffer.size()) { + m_buffer.erase(m_buffer.begin(), m_buffer.begin() + m_read_offset); + } else { + m_buffer.clear(); + } + m_read_offset = 0; + } +} + +std::vector PacketBuffer::ExtractPackets(const PacketRegistry& registry) { + std::vector packets; + + while (m_read_offset < m_buffer.size()) { + uint8_t header = m_buffer[m_read_offset]; + const PacketDescriptor* desc = registry.Find(header); + + if (!desc) { + // Unknown packet header: skip 1 byte to attempt re-synchronization + m_read_offset++; + continue; + } + + if (desc->mode == PacketSizeMode::Fixed) { + size_t total_packet_size = 1 + desc->fixed_payload_size; + if (m_buffer.size() - m_read_offset < total_packet_size) { + // Incomplete frame, wait for more data + break; + } + + Packet pkt; + pkt.header = header; + if (desc->fixed_payload_size > 0) { + pkt.payload.resize(desc->fixed_payload_size); + std::memcpy(pkt.payload.data(), m_buffer.data() + m_read_offset + 1, desc->fixed_payload_size); + } + packets.push_back(std::move(pkt)); + m_read_offset += total_packet_size; + } else { + // Dynamic packet: Header (1) + Size (2 bytes LE) + Payload + if (m_buffer.size() - m_read_offset < 3) { + // Incomplete header, wait for more data + break; + } + + uint16_t payload_len = static_cast(m_buffer[m_read_offset + 1]) | + (static_cast(m_buffer[m_read_offset + 2]) << 8); + + size_t total_packet_size = 3 + payload_len; + if (m_buffer.size() - m_read_offset < total_packet_size) { + // Incomplete body, wait for more data + break; + } + + Packet pkt; + pkt.header = header; + if (payload_len > 0) { + pkt.payload.resize(payload_len); + std::memcpy(pkt.payload.data(), m_buffer.data() + m_read_offset + 3, payload_len); + } + packets.push_back(std::move(pkt)); + m_read_offset += total_packet_size; + } + } + + Compact(); + return packets; +} + +} // namespace metin2::network diff --git a/network/tests/network_test.cpp b/network/tests/network_test.cpp new file mode 100644 index 0000000..8dbdf91 --- /dev/null +++ b/network/tests/network_test.cpp @@ -0,0 +1,202 @@ +#include "network/network.h" +#include +#include +#include + +using namespace metin2::network; + +void TestPhaseStateMachine() { + std::cout << "[Test] Phase State Machine...\n"; + PhaseStateMachine fsm; + assert(fsm.GetCurrentPhase() == ConnectionPhase::Disconnected); + assert(!fsm.IsConnected()); + + // Invalid transition + assert(!fsm.CanTransitionTo(ConnectionPhase::InGame)); + + // Valid flow: Disconnected -> Handshake -> Auth -> CharacterSelect -> GameLoading -> InGame + assert(fsm.TransitionTo(ConnectionPhase::Handshake)); + assert(fsm.GetCurrentPhase() == ConnectionPhase::Handshake); + assert(fsm.IsConnected()); + + assert(fsm.TransitionTo(ConnectionPhase::Auth)); + assert(fsm.TransitionTo(ConnectionPhase::CharacterSelect)); + assert(fsm.TransitionTo(ConnectionPhase::GameLoading)); + assert(fsm.TransitionTo(ConnectionPhase::InGame)); + assert(fsm.IsInGame()); + + // Disconnect from anywhere + assert(fsm.TransitionTo(ConnectionPhase::Disconnected)); + assert(!fsm.IsConnected()); + std::cout << " -> Phase transitions passed!\n"; +} + +void TestCipher() { + std::cout << "[Test] TEA & Rolling XOR Cipher...\n"; + TeaKey key = { 0x12345678, 0x9ABCDEF0, 0x0FEDCBA9, 0x87654321 }; + TeaCipher tea(key); + + std::string text = "Metin2 cross-platform network packet payload encryption!"; + std::vector plain(text.begin(), text.end()); + + auto encrypted = tea.Encrypt(plain); + assert(encrypted.size() >= plain.size()); + assert(encrypted.size() % 8 == 0); + + auto decrypted = tea.Decrypt(encrypted); + assert(std::memcmp(plain.data(), decrypted.data(), plain.size()) == 0); + + // Rolling XOR + RollingXorCipher xor_cipher1(0xA5A55A5A); + RollingXorCipher xor_cipher2(0xA5A55A5A); + std::vector xor_buf(plain.begin(), plain.end()); + + xor_cipher1.Process(xor_buf.data(), xor_buf.size()); + assert(std::memcmp(plain.data(), xor_buf.data(), plain.size()) != 0); + + xor_cipher2.Process(xor_buf.data(), xor_buf.size()); + assert(std::memcmp(plain.data(), xor_buf.data(), plain.size()) == 0); + + std::cout << " -> Cipher encryption and decryption passed!\n"; +} + +void TestPacketSegmentationAndReassembly() { + std::cout << "[Test] Packet Buffer Fragmentation & Reassembly...\n"; + PacketRegistry registry; + PacketBuffer buffer; + + // 1. Pack multiple packets into one stream (Sticky packets / 粘包) + // Packet A: HEADER_GC_PING (header=253, 4 bytes payload) + // Packet B: HEADER_CG_CHARACTER_SELECT (header=6, 1 byte payload) + uint32_t ping_id = 9999; + uint8_t char_slot = 2; + + std::vector sticky_stream; + sticky_stream.push_back(HEADER_GC_PING); + const uint8_t* p_ping = reinterpret_cast(&ping_id); + sticky_stream.insert(sticky_stream.end(), p_ping, p_ping + 4); + + sticky_stream.push_back(HEADER_CG_CHARACTER_SELECT); + sticky_stream.push_back(char_slot); + + buffer.Append(sticky_stream); + auto packets = buffer.ExtractPackets(registry); + assert(packets.size() == 2); + assert(packets[0].header == HEADER_GC_PING); + assert(packets[0].payload.size() == 4); + assert(*reinterpret_cast(packets[0].payload.data()) == 9999); + assert(packets[1].header == HEADER_CG_CHARACTER_SELECT); + assert(packets[1].payload[0] == 2); + + // 2. Partial packets (半包) + // Send 1st half of a packet + std::vector half1; + half1.push_back(HEADER_GC_PING); + half1.push_back(0x11); + half1.push_back(0x22); + buffer.Append(half1); + + auto partial = buffer.ExtractPackets(registry); + assert(partial.empty()); // Not complete yet + + // Send 2nd half + std::vector half2; + half2.push_back(0x33); + half2.push_back(0x44); + buffer.Append(half2); + + auto completed = buffer.ExtractPackets(registry); + assert(completed.size() == 1); + assert(completed[0].header == HEADER_GC_PING); + assert(completed[0].payload[0] == 0x11 && completed[0].payload[3] == 0x44); + + std::cout << " -> Packet segmentation and reassembly passed!\n"; +} + +void TestNetworkClientEndToEnd() { + std::cout << "[Test] NetworkClient Full Protocol Pipeline...\n"; + NetworkClient client; + + bool handshake_called = false; + bool auth_called = false; + std::string received_chat; + + client.SetOnHandshake([&](uint32_t s_time) { + handshake_called = true; + assert(s_time == 12345678); + }); + + client.SetOnAuthResult([&](bool success, uint32_t err, const std::string& msg) { + auth_called = true; + assert(success); + }); + + client.SetOnChat([&](uint32_t sender, uint8_t type, const std::string& msg) { + received_chat = msg; + }); + + // Client connects -> Handshake phase + client.SetPhase(ConnectionPhase::Handshake); + assert(client.GetPhase() == ConnectionPhase::Handshake); + + // Server sends GC_HANDSHAKE (header 255, 8 bytes: time=12345678, delta=0) + std::vector server_handshake; + server_handshake.push_back(HEADER_GC_HANDSHAKE); + uint32_t s_time = 12345678; + uint32_t delta = 0; + const uint8_t* p_st = reinterpret_cast(&s_time); + const uint8_t* p_dt = reinterpret_cast(&delta); + server_handshake.insert(server_handshake.end(), p_st, p_st + 4); + server_handshake.insert(server_handshake.end(), p_dt, p_dt + 4); + + client.PushReceivedData(server_handshake.data(), server_handshake.size()); + assert(handshake_called); + + // Client responds with Handshake Ack + client.SendHandshakeAck(87654321); + assert(client.HasPendingSendData()); + auto out_data = client.PopSendData(); + assert(!out_data.empty()); + assert(out_data[0] == HEADER_CG_HANDSHAKE); + + // Move to Auth phase & authenticate + client.SetPhase(ConnectionPhase::Auth); + client.SendLogin("player_tester", "secret_pass"); + auto login_send = client.PopSendData(); + assert(login_send[0] == HEADER_CG_LOGIN); + + // Server sends Auth success (HEADER_GC_AUTH_SUCCESS: header 101, account_id 42) + std::vector auth_resp; + auth_resp.push_back(HEADER_GC_AUTH_SUCCESS); + uint32_t account_id = 42; + const uint8_t* p_acc = reinterpret_cast(&account_id); + auth_resp.insert(auth_resp.end(), p_acc, p_acc + 4); + client.PushReceivedData(auth_resp.data(), auth_resp.size()); + assert(auth_called); + assert(client.GetPhase() == ConnectionPhase::CharacterSelect); + + // Server sends Chat dynamic packet + std::string test_msg = "Welcome to Metin2 World!"; + std::vector chat_pkt; + chat_pkt.push_back(HEADER_GC_CHAT); + uint16_t chat_len = static_cast(1 + test_msg.size()); + chat_pkt.push_back(chat_len & 0xFF); + chat_pkt.push_back((chat_len >> 8) & 0xFF); + chat_pkt.push_back(1); // chat type + chat_pkt.insert(chat_pkt.end(), test_msg.begin(), test_msg.end()); + + client.PushReceivedData(chat_pkt.data(), chat_pkt.size()); + assert(received_chat == test_msg); + + std::cout << " -> NetworkClient pipeline passed!\n"; +} + +int main() { + std::cout << "=== Running Metin2 Network SDK Tests ===\n"; + TestPhaseStateMachine(); + TestCipher(); + TestPacketSegmentationAndReassembly(); + TestNetworkClientEndToEnd(); + std::cout << "All Network SDK Tests PASSED!\n"; + return 0; +} diff --git a/property/CMakeLists.txt b/property/CMakeLists.txt new file mode 100644 index 0000000..8f5a6c9 --- /dev/null +++ b/property/CMakeLists.txt @@ -0,0 +1,25 @@ +cmake_minimum_required(VERSION 3.20) +project(property LANGUAGES CXX) + +set(CMAKE_CXX_STANDARD 20) +set(CMAKE_CXX_STANDARD_REQUIRED ON) + +add_library(property STATIC + src/property.cpp + src/property_manager.cpp + src/map_object.cpp +) + +target_include_directories(property PUBLIC + $ + $ +) + +add_library(property::property ALIAS property) + +option(PROPERTY_BUILD_TESTS "Build property SDK tests" ON) +if(PROPERTY_BUILD_TESTS) + add_executable(property_test tests/property_test.cpp) + target_link_libraries(property_test PRIVATE property) + add_test(NAME property_test COMMAND property_test) +endif() diff --git a/property/include/property/property.h b/property/include/property/property.h new file mode 100644 index 0000000..05f7a7b --- /dev/null +++ b/property/include/property/property.h @@ -0,0 +1,37 @@ +#pragma once + +#include "types.h" +#include +#include +#include +#include + +namespace metin2::property { + +class Property { +public: + Property() = default; + explicit Property(const std::string& file_path); + ~Property() = default; + + // Load from memory buffer (expects FourCC 'YPRT' header) + bool ReadFromMemory(const void* data, size_t size, const std::string& file_name = ""); + bool ReadFromFile(const std::string& file_path); + + uint32_t GetCRC() const { return m_crc; } + const std::string& GetFileName() const { return m_file_name; } + const PropertyData& GetData() const { return m_data; } + + bool GetString(const std::string& key, std::string& out_value) const; + bool GetVector(const std::string& key, std::vector& out_vector) const; + + static constexpr uint32_t FOURCC_YPRT = 0x54525059; // 'YPRT' in little-endian + +private: + uint32_t m_crc = 0; + std::string m_file_name; + PropertyData m_data; + std::unordered_map> m_token_map; +}; + +} // namespace metin2::property diff --git a/property/include/property/property_manager.h b/property/include/property/property_manager.h new file mode 100644 index 0000000..fbb1478 --- /dev/null +++ b/property/include/property/property_manager.h @@ -0,0 +1,29 @@ +#pragma once + +#include "property.h" +#include +#include +#include + +namespace metin2::property { + +class PropertyManager { +public: + PropertyManager() = default; + ~PropertyManager() = default; + + bool Register(const std::string& file_path, std::shared_ptr* out_property = nullptr); + bool RegisterFromMemory(const std::string& file_path, const void* data, size_t size, std::shared_ptr* out_property = nullptr); + + std::shared_ptr GetByCRC(uint32_t crc) const; + std::shared_ptr GetByPath(const std::string& file_path) const; + + size_t GetCount() const { return m_crc_map.size(); } + void Clear(); + +private: + std::unordered_map> m_crc_map; + std::unordered_map> m_path_map; +}; + +} // namespace metin2::property diff --git a/property/include/property/types.h b/property/include/property/types.h new file mode 100644 index 0000000..3972a6d --- /dev/null +++ b/property/include/property/types.h @@ -0,0 +1,37 @@ +#pragma once + +#include +#include +#include + +namespace metin2::property { + +enum EPropertyType { + PROPERTY_TYPE_NONE = 0, + PROPERTY_TYPE_TREE = 1, // .prt (SpeedTree reference) + PROPERTY_TYPE_BUILDING = 2, // .prb (Granny2 building model) + PROPERTY_TYPE_EFFECT = 3, // .pre (Particle / MSE effect) + PROPERTY_TYPE_DUNGEON = 4, // .prd (Dungeon block) + PROPERTY_TYPE_MAX +}; + +struct PropertyData { + uint32_t crc = 0; + std::string file_path; + std::string property_name; + EPropertyType property_type = PROPERTY_TYPE_NONE; + std::string model_file; // buildingfile / treefile / effectfile + std::string shadow_flag; + bool has_collision = true; +}; + +struct OrientedBoundingBox { + float center[3] = {0.0f, 0.0f, 0.0f}; + float half_extents[3] = {0.0f, 0.0f, 0.0f}; + float yaw_rad = 0.0f; + + bool IntersectsCircle2D(float circle_x, float circle_z, float radius) const; + bool GetPenetrationAndNormal(float circle_x, float circle_z, float radius, float& out_nx, float& out_nz, float& out_penetration) const; +}; + +} // namespace metin2::property diff --git a/property/src/map_object.cpp b/property/src/map_object.cpp new file mode 100644 index 0000000..832701e --- /dev/null +++ b/property/src/map_object.cpp @@ -0,0 +1,96 @@ +#include "property/types.h" +#include +#include + +namespace metin2::property { + +bool OrientedBoundingBox::IntersectsCircle2D(float circle_x, float circle_z, float radius) const { + float dx = circle_x - center[0]; + float dz = circle_z - center[2]; + + float cos_y = std::cos(-yaw_rad); + float sin_y = std::sin(-yaw_rad); + + float local_x = dx * cos_y - dz * sin_y; + float local_z = dx * sin_y + dz * cos_y; + + float clamped_x = std::clamp(local_x, -half_extents[0], half_extents[0]); + float clamped_z = std::clamp(local_z, -half_extents[2], half_extents[2]); + + float diff_x = local_x - clamped_x; + float diff_z = local_z - clamped_z; + + return (diff_x * diff_x + diff_z * diff_z) <= (radius * radius); +} + +bool OrientedBoundingBox::GetPenetrationAndNormal(float circle_x, float circle_z, float radius, + float& out_nx, float& out_nz, float& out_penetration) const { + float dx = circle_x - center[0]; + float dz = circle_z - center[2]; + + float cos_y = std::cos(-yaw_rad); + float sin_y = std::sin(-yaw_rad); + + float local_x = dx * cos_y - dz * sin_y; + float local_z = dx * sin_y + dz * cos_y; + + float hx = half_extents[0]; + float hz = half_extents[2]; + + float clamped_x = std::clamp(local_x, -hx, hx); + float clamped_z = std::clamp(local_z, -hz, hz); + + float diff_x = local_x - clamped_x; + float diff_z = local_z - clamped_z; + float dist_sq = diff_x * diff_x + diff_z * diff_z; + + float n_lx = 0.0f; + float n_lz = 0.0f; + + if (dist_sq > 1e-8f) { + // Outside OBB + float dist = std::sqrt(dist_sq); + if (dist > radius) { + out_penetration = 0.0f; + return false; + } + out_penetration = radius - dist; + n_lx = diff_x / dist; + n_lz = diff_z / dist; + } else { + // Center is inside OBB + float d_right = hx - local_x; + float d_left = local_x - (-hx); + float d_top = hz - local_z; + float d_bottom = local_z - (-hz); + + float min_d = d_right; + n_lx = 1.0f; n_lz = 0.0f; + + if (d_left < min_d) { + min_d = d_left; + n_lx = -1.0f; n_lz = 0.0f; + } + if (d_top < min_d) { + min_d = d_top; + n_lx = 0.0f; n_lz = 1.0f; + } + if (d_bottom < min_d) { + min_d = d_bottom; + n_lx = 0.0f; n_lz = -1.0f; + } + + out_penetration = radius + min_d; + } + + // Transform local normal back to world coordinates + float cos_pos = std::cos(yaw_rad); + float sin_pos = std::sin(yaw_rad); + + out_nx = n_lx * cos_pos - n_lz * sin_pos; + out_nz = n_lx * sin_pos + n_lz * cos_pos; + + return true; +} + +} // namespace metin2::property diff --git a/property/src/property.cpp b/property/src/property.cpp new file mode 100644 index 0000000..7c63786 --- /dev/null +++ b/property/src/property.cpp @@ -0,0 +1,219 @@ +#include "property/property.h" +#include +#include +#include +#include + +namespace metin2::property { + +namespace { + +inline std::string Trim(const std::string& str) { + size_t first = str.find_first_not_of(" \t\r\n"); + if (first == std::string::npos) return ""; + size_t last = str.find_last_not_of(" \t\r\n"); + return str.substr(first, (last - first + 1)); +} + +inline std::string ToLower(std::string str) { + std::transform(str.begin(), str.end(), str.begin(), [](unsigned char c) { + return static_cast(std::tolower(c)); + }); + return str; +} + +uint32_t CalculateCRC32(const std::string& str) { + static uint32_t table[256]; + static bool table_init = false; + if (!table_init) { + for (uint32_t i = 0; i < 256; ++i) { + uint32_t c = i; + for (int j = 0; j < 8; ++j) { + c = (c & 1) ? (0xEDB88320L ^ (c >> 1)) : (c >> 1); + } + table[i] = c; + } + table_init = true; + } + + uint32_t crc = 0xFFFFFFFF; + for (char ch : str) { + char lower_ch = static_cast(std::tolower(static_cast(ch))); + if (lower_ch == '\\') lower_ch = '/'; + crc = table[(crc ^ static_cast(lower_ch)) & 0xFF] ^ (crc >> 8); + } + return ~crc; +} + +} // namespace + +Property::Property(const std::string& file_path) { + ReadFromFile(file_path); +} + +bool Property::ReadFromFile(const std::string& file_path) { + std::ifstream file(file_path, std::ios::binary); + if (!file.is_open()) return false; + + file.seekg(0, std::ios::end); + size_t size = static_cast(file.tellg()); + file.seekg(0, std::ios::beg); + + std::vector buffer(size); + file.read(buffer.data(), size); + if (!file) return false; + + return ReadFromMemory(buffer.data(), size, file_path); +} + +bool Property::ReadFromMemory(const void* data, size_t size, const std::string& file_name) { + if (!data || size < 4) return false; + + m_file_name = file_name; + m_token_map.clear(); + m_data = PropertyData(); + m_data.file_path = file_name; + + const char* char_data = static_cast(data); + + // Verify FourCC or text header 'YPRT' + if (std::memcmp(char_data, "YPRT", 4) != 0) { + return false; + } + + std::string text(char_data, size); + std::istringstream stream(text); + std::string line; + + // Line 1: Header "YPRT" + if (!std::getline(stream, line)) return false; + + // Line 2: CRC32 string or key + if (std::getline(stream, line)) { + std::string trimmed = Trim(line); + char* end = nullptr; + unsigned long parsed_crc = std::strtoul(trimmed.c_str(), &end, 10); + if (end != trimmed.c_str() && *end == '\0') { + m_crc = static_cast(parsed_crc); + } else { + // It's a key-value line, rewind or process + stream.seekg(4); // Seek back right after "YPRT" + } + } + + if (m_crc == 0 && !file_name.empty()) { + m_crc = CalculateCRC32(file_name); + } + m_data.crc = m_crc; + + while (std::getline(stream, line)) { + std::string trimmed = Trim(line); + if (trimmed.empty() || trimmed[0] == '#') continue; + + std::string key; + std::vector values; + + // Split key and remainder + size_t sep_pos = trimmed.find_first_of(" \t"); + if (sep_pos == std::string::npos) { + key = ToLower(trimmed); + } else { + key = ToLower(Trim(trimmed.substr(0, sep_pos))); + std::string remainder = Trim(trimmed.substr(sep_pos + 1)); + + // Extract tokens (handling quoted strings) + size_t idx = 0; + while (idx < remainder.size()) { + while (idx < remainder.size() && (remainder[idx] == ' ' || remainder[idx] == '\t')) { + idx++; + } + if (idx >= remainder.size()) break; + + if (remainder[idx] == '"') { + size_t quote_end = remainder.find('"', idx + 1); + if (quote_end != std::string::npos) { + values.push_back(remainder.substr(idx + 1, quote_end - idx - 1)); + idx = quote_end + 1; + } else { + values.push_back(remainder.substr(idx + 1)); + break; + } + } else { + size_t next_space = remainder.find_first_of(" \t", idx); + if (next_space != std::string::npos) { + values.push_back(remainder.substr(idx, next_space - idx)); + idx = next_space + 1; + } else { + values.push_back(remainder.substr(idx)); + break; + } + } + } + } + + m_token_map[key] = values; + } + + // Populate PropertyData + std::string val; + if (GetString("propertyname", val)) { + m_data.property_name = val; + } + + if (GetString("propertytype", val)) { + std::string lower_type = ToLower(val); + if (lower_type == "tree" || lower_type == "1") { + m_data.property_type = PROPERTY_TYPE_TREE; + } else if (lower_type == "building" || lower_type == "2") { + m_data.property_type = PROPERTY_TYPE_BUILDING; + } else if (lower_type == "effect" || lower_type == "3") { + m_data.property_type = PROPERTY_TYPE_EFFECT; + } else if (lower_type == "dungeonblock" || lower_type == "dungeon" || lower_type == "4") { + m_data.property_type = PROPERTY_TYPE_DUNGEON; + } + } + + if (GetString("treefile", val)) { + m_data.model_file = val; + if (m_data.property_type == PROPERTY_TYPE_NONE) m_data.property_type = PROPERTY_TYPE_TREE; + } else if (GetString("buildingfile", val)) { + m_data.model_file = val; + if (m_data.property_type == PROPERTY_TYPE_NONE) m_data.property_type = PROPERTY_TYPE_BUILDING; + } else if (GetString("effectfile", val)) { + m_data.model_file = val; + if (m_data.property_type == PROPERTY_TYPE_NONE) m_data.property_type = PROPERTY_TYPE_EFFECT; + } else if (GetString("dungeonblockfile", val)) { + m_data.model_file = val; + if (m_data.property_type == PROPERTY_TYPE_NONE) m_data.property_type = PROPERTY_TYPE_DUNGEON; + } + + if (GetString("shadowflag", val)) { + m_data.shadow_flag = val; + } + + if (GetString("isbuilding", val)) { + m_data.has_collision = (val != "0"); + } + + return true; +} + +bool Property::GetString(const std::string& key, std::string& out_value) const { + auto it = m_token_map.find(ToLower(key)); + if (it != m_token_map.end() && !it->second.empty()) { + out_value = it->second[0]; + return true; + } + return false; +} + +bool Property::GetVector(const std::string& key, std::vector& out_vector) const { + auto it = m_token_map.find(ToLower(key)); + if (it != m_token_map.end()) { + out_vector = it->second; + return true; + } + return false; +} + +} // namespace metin2::property diff --git a/property/src/property_manager.cpp b/property/src/property_manager.cpp new file mode 100644 index 0000000..6a7fab7 --- /dev/null +++ b/property/src/property_manager.cpp @@ -0,0 +1,77 @@ +#include "property/property_manager.h" +#include + +namespace metin2::property { + +namespace { + +inline std::string NormalizePath(std::string path) { + for (char& c : path) { + if (c == '\\') c = '/'; + else if (static_cast(c) < 128) c = static_cast(std::tolower(static_cast(c))); + } + return path; +} + +} // namespace + +bool PropertyManager::Register(const std::string& file_path, std::shared_ptr* out_property) { + auto prop = std::make_shared(); + if (!prop->ReadFromFile(file_path)) { + return false; + } + + uint32_t crc = prop->GetCRC(); + std::string norm_path = NormalizePath(file_path); + + m_crc_map[crc] = prop; + m_path_map[norm_path] = prop; + + if (out_property) { + *out_property = prop; + } + return true; +} + +bool PropertyManager::RegisterFromMemory(const std::string& file_path, const void* data, size_t size, + std::shared_ptr* out_property) { + auto prop = std::make_shared(); + if (!prop->ReadFromMemory(data, size, file_path)) { + return false; + } + + uint32_t crc = prop->GetCRC(); + std::string norm_path = NormalizePath(file_path); + + m_crc_map[crc] = prop; + m_path_map[norm_path] = prop; + + if (out_property) { + *out_property = prop; + } + return true; +} + +std::shared_ptr PropertyManager::GetByCRC(uint32_t crc) const { + auto it = m_crc_map.find(crc); + if (it != m_crc_map.end()) { + return it->second; + } + return nullptr; +} + +std::shared_ptr PropertyManager::GetByPath(const std::string& file_path) const { + std::string norm_path = NormalizePath(file_path); + auto it = m_path_map.find(norm_path); + if (it != m_path_map.end()) { + return it->second; + } + return nullptr; +} + +void PropertyManager::Clear() { + m_crc_map.clear(); + m_path_map.clear(); +} + +} // namespace metin2::property diff --git a/property/tests/property_test.cpp b/property/tests/property_test.cpp new file mode 100644 index 0000000..6a10877 --- /dev/null +++ b/property/tests/property_test.cpp @@ -0,0 +1,92 @@ +#include "property/property.h" +#include "property/property_manager.h" +#include +#include +#include + +using namespace metin2::property; + +int main() { + std::cout << "[Test 1] Parse YPRT Building Property..." << std::endl; + const std::string sample_prb = + "YPRT\r\n" + "2847291832\r\n" + "buildingfile\t\"d:/ymir work/zone/b/building01.gr2\"\r\n" + "isbuilding\t\"1\"\r\n" + "propertyname\t\"building_temple\"\r\n" + "propertytype\t\"Building\"\r\n" + "shadowflag\t\"1\"\r\n"; + + Property prb; + bool ok_prb = prb.ReadFromMemory(sample_prb.data(), sample_prb.size(), "property/b/temple.prb"); + assert(ok_prb); + assert(prb.GetCRC() == 2847291832); + assert(prb.GetData().property_type == PROPERTY_TYPE_BUILDING); + assert(prb.GetData().property_name == "building_temple"); + assert(prb.GetData().model_file == "d:/ymir work/zone/b/building01.gr2"); + assert(prb.GetData().has_collision == true); + + std::string shadow_val; + assert(prb.GetString("shadowflag", shadow_val)); + assert(shadow_val == "1"); + + std::cout << "[Test 2] Parse YPRT Tree Property (.prt)..." << std::endl; + const std::string sample_prt = + "YPRT\n" + "1048576293\n" + "propertyname\t\"tree_pine_01\"\n" + "propertytype\t\"Tree\"\n" + "treefile\t\"d:/ymir work/tree/pine_01.spt\"\n" + "treesize\t\"1200\"\n" + "treevariance\t\"250\"\n"; + + Property prt; + bool ok_prt = prt.ReadFromMemory(sample_prt.data(), sample_prt.size(), "property/tree/pine.prt"); + assert(ok_prt); + assert(prt.GetCRC() == 1048576293); + assert(prt.GetData().property_type == PROPERTY_TYPE_TREE); + assert(prt.GetData().model_file == "d:/ymir work/tree/pine_01.spt"); + + std::cout << "[Test 3] PropertyManager caching & lookup..." << std::endl; + PropertyManager mgr; + assert(mgr.RegisterFromMemory("property/b/temple.prb", sample_prb.data(), sample_prb.size())); + assert(mgr.RegisterFromMemory("property/tree/pine.prt", sample_prt.data(), sample_prt.size())); + assert(mgr.GetCount() == 2); + + auto prop1 = mgr.GetByCRC(2847291832); + assert(prop1 != nullptr); + assert(prop1->GetData().property_name == "building_temple"); + + auto prop2 = mgr.GetByPath("property/tree/pine.prt"); + assert(prop2 != nullptr); + assert(prop2->GetCRC() == 1048576293); + + std::cout << "[Test 4] Oriented Bounding Box (OBB) 2D collision & penetration..." << std::endl; + OrientedBoundingBox obb; + obb.center[0] = 100.0f; + obb.center[1] = 0.0f; + obb.center[2] = 200.0f; + obb.half_extents[0] = 50.0f; // Width 100 + obb.half_extents[1] = 50.0f; + obb.half_extents[2] = 100.0f; // Length 200 + obb.yaw_rad = 0.0f; // Axis-aligned + + // Test a point clearly outside + assert(!obb.IntersectsCircle2D(300.0f, 200.0f, 20.0f)); + + // Test a point colliding with the right edge (x = 150) + // Circle at (160, 200) with radius 20 -> penetrates edge by 10 + float nx = 0.0f, nz = 0.0f, pen = 0.0f; + bool col = obb.GetPenetrationAndNormal(160.0f, 200.0f, 20.0f, nx, nz, pen); + assert(col); + assert(std::abs(pen - 10.0f) < 1e-4f); + assert(std::abs(nx - 1.0f) < 1e-4f); // Pushes towards +X + assert(std::abs(nz - 0.0f) < 1e-4f); + + // Test rotated OBB (45 degrees = PI/4) + obb.yaw_rad = 3.14159265f * 0.25f; + assert(obb.IntersectsCircle2D(100.0f, 200.0f, 10.0f)); // Center point always intersects + + std::cout << "All Property SDK tests passed successfully!" << std::endl; + return 0; +} diff --git a/proto/CMakeLists.txt b/proto/CMakeLists.txt new file mode 100644 index 0000000..cc96fab --- /dev/null +++ b/proto/CMakeLists.txt @@ -0,0 +1,26 @@ +cmake_minimum_required(VERSION 3.20) +project(proto LANGUAGES CXX) + +set(CMAKE_CXX_STANDARD 20) +set(CMAKE_CXX_STANDARD_REQUIRED ON) + +add_library(proto STATIC + src/item_proto.cpp + src/mob_proto.cpp +) + +target_include_directories(proto PUBLIC + $ + $ +) + +target_link_libraries(proto PUBLIC eterpack) + +add_library(proto::proto ALIAS proto) + +option(PROTO_BUILD_TESTS "Build proto SDK tests" ON) +if(PROTO_BUILD_TESTS) + add_executable(proto_test tests/proto_test.cpp) + target_link_libraries(proto_test PRIVATE proto) + add_test(NAME proto_test COMMAND proto_test) +endif() diff --git a/proto/include/proto/item_proto.h b/proto/include/proto/item_proto.h new file mode 100644 index 0000000..bb7480a --- /dev/null +++ b/proto/include/proto/item_proto.h @@ -0,0 +1,66 @@ +#pragma once + +#include +#include +#include +#include +#include +#include +#include +#include +#include "eterpack/types.h" + +namespace proto { + +struct ItemProtoRecord { + uint32_t vnum = 0; + uint32_t range = 0; // vnum range for grouped items + std::string name; + std::string locale_name; + + uint8_t type = 0; + uint8_t subtype = 0; + uint8_t weight = 0; + uint8_t size = 1; + + uint32_t anti_flags = 0; + uint32_t flags = 0; + uint32_t wear_flags = 0; + uint32_t immune_flags = 0; + + uint32_t buy_price = 0; + uint32_t sell_price = 0; + + std::array, 2> limits{}; + std::array, 3> applies{}; + std::array values{}; + std::array sockets{}; + + uint32_t refined_vnum = 0; + uint16_t refine_set = 0; + uint8_t alter_to_magic_percent = 0; + uint8_t specular = 0; + uint8_t gain_socket_percent = 0; +}; + +class ItemProto { +public: + ItemProto() = default; + + bool load(std::span data, const uint32_t key[4] = eterpack::DEFAULT_ITEM_PROTO_KEY); + bool load_file(const std::filesystem::path& filepath, const uint32_t key[4] = eterpack::DEFAULT_ITEM_PROTO_KEY); + + const ItemProtoRecord* find(uint32_t vnum) const; + const std::vector& get_records() const { return m_records; } + size_t size() const { return m_records.size(); } + bool empty() const { return m_records.empty(); } + + void clear(); + +private: + std::vector m_records; + std::unordered_map m_vnum_map; + std::vector m_ranged_indices; +}; + +} // namespace proto diff --git a/proto/include/proto/mob_proto.h b/proto/include/proto/mob_proto.h new file mode 100644 index 0000000..0f1fa6e --- /dev/null +++ b/proto/include/proto/mob_proto.h @@ -0,0 +1,99 @@ +#pragma once + +#include +#include +#include +#include +#include +#include +#include +#include "eterpack/types.h" + +namespace proto { + +struct MobSkillLevel { + uint32_t vnum = 0; + uint8_t level = 0; +}; + +struct MobRecord { + uint32_t vnum = 0; + std::string name; + std::string locale_name; + + uint8_t type = 0; + uint8_t rank = 0; + uint8_t battle_type = 0; + uint8_t level = 1; + uint8_t size = 0; + + uint32_t gold_min = 0; + uint32_t gold_max = 0; + uint32_t exp = 0; + uint32_t max_hp = 0; + uint8_t regen_cycle = 0; + uint8_t regen_percent = 0; + uint16_t def = 0; + + uint32_t ai_flag = 0; + uint32_t race_flag = 0; + uint32_t immune_flag = 0; + + uint8_t str = 0; + uint8_t dex = 0; + uint8_t con = 0; + uint8_t intel = 0; + + uint32_t damage_min = 0; + uint32_t damage_max = 0; + + int16_t attack_speed = 0; + int16_t moving_speed = 0; + uint8_t aggressive_hp_pct = 0; + uint16_t aggressive_sight = 0; + uint16_t attack_range = 0; + + std::array enchants{}; + std::array resists{}; + + uint32_t resurrection_vnum = 0; + uint32_t drop_item_vnum = 0; + + uint8_t mount_capacity = 0; + uint8_t on_click_type = 0; + uint8_t empire = 0; + std::string folder; + float damage_multiply = 1.0f; + uint32_t summon_vnum = 0; + uint32_t drain_sp = 0; + uint32_t monster_color = 0; + uint32_t polymorph_item_vnum = 0; + + std::array skills{}; + uint8_t berserk_point = 0; + uint8_t stone_skin_point = 0; + uint8_t god_speed_point = 0; + uint8_t death_blow_point = 0; + uint8_t revive_point = 0; +}; + +class MobProto { +public: + MobProto() = default; + + bool load(std::span data, const uint32_t key[4] = eterpack::DEFAULT_MOB_PROTO_KEY); + bool load_file(const std::filesystem::path& filepath, const uint32_t key[4] = eterpack::DEFAULT_MOB_PROTO_KEY); + + const MobRecord* find(uint32_t vnum) const; + const std::vector& get_records() const { return m_records; } + size_t size() const { return m_records.size(); } + bool empty() const { return m_records.empty(); } + + void clear(); + +private: + std::vector m_records; + std::unordered_map m_vnum_map; +}; + +} // namespace proto diff --git a/proto/include/proto/proto.h b/proto/include/proto/proto.h new file mode 100644 index 0000000..c0effa9 --- /dev/null +++ b/proto/include/proto/proto.h @@ -0,0 +1,4 @@ +#pragma once + +#include "proto/item_proto.h" +#include "proto/mob_proto.h" diff --git a/proto/src/item_proto.cpp b/proto/src/item_proto.cpp new file mode 100644 index 0000000..287194f --- /dev/null +++ b/proto/src/item_proto.cpp @@ -0,0 +1,210 @@ +#include "proto/item_proto.h" +#include "eterpack/lzo.h" +#include +#include +#include + +namespace proto { + +namespace { + +inline uint16_t read16(std::span data, size_t offset) { + if (offset + 2 > data.size()) return 0; + return static_cast(data[offset]) | + (static_cast(data[offset + 1]) << 8); +} + +inline uint32_t read32(std::span data, size_t offset) { + if (offset + 4 > data.size()) return 0; + return static_cast(data[offset]) | + (static_cast(data[offset + 1]) << 8) | + (static_cast(data[offset + 2]) << 16) | + (static_cast(data[offset + 3]) << 24); +} + +inline int32_t read32_signed(std::span data, size_t offset) { + return std::bit_cast(read32(data, offset)); +} + +inline std::string read_str(std::span data, size_t offset, size_t max_len) { + if (offset >= data.size()) return {}; + size_t len = 0; + while (offset + len < data.size() && len < max_len && data[offset + len] != 0) { + ++len; + } + return std::string(reinterpret_cast(data.data() + offset), len); +} + +} // anonymous namespace + +void ItemProto::clear() { + m_records.clear(); + m_vnum_map.clear(); + m_ranged_indices.clear(); +} + +bool ItemProto::load_file(const std::filesystem::path& filepath, const uint32_t key[4]) { + std::ifstream file(filepath, std::ios::binary); + if (!file.is_open()) return false; + + file.seekg(0, std::ios::end); + size_t size = static_cast(file.tellg()); + file.seekg(0, std::ios::beg); + + std::vector buffer(size); + if (!file.read(reinterpret_cast(buffer.data()), size)) { + return false; + } + + return load(buffer, key); +} + +bool ItemProto::load(std::span input, const uint32_t key[4]) { + clear(); + if (input.size() < 12) return false; + + uint32_t fourcc = read32(input, 0); + size_t mcoz_offset = 0; + uint32_t count = 0; + uint32_t stride = 0; + + if (fourcc == 0x5850494d) { // 'M', 'I', 'P', 'X' + if (input.size() < 20) return false; + uint32_t version = read32(input, 4); + if (version != 1) return false; + stride = read32(input, 8); + count = read32(input, 12); + // data_size at input[16] + mcoz_offset = 20; + } else if (fourcc == 0x5450494d) { // 'M', 'I', 'P', 'T' + count = read32(input, 4); + // data_size at input[8] + mcoz_offset = 12; + } else if (fourcc == eterpack::FOURCC_MCOZ) { + // Raw MCOZ container without outer MIPX/MIPT header + mcoz_offset = 0; + } else { + return false; + } + + if (mcoz_offset > input.size()) return false; + + std::vector raw; + if (!eterpack::LZO::instance().decompress_mcoz(input.subspan(mcoz_offset), raw, key)) { + return false; + } + + if (raw.empty()) return false; + + if (stride == 0) { + if (count > 0 && raw.size() % count == 0) { + stride = static_cast(raw.size() / count); + } else { + // Try standard strides + for (uint32_t s : {156, 152, 176, 172, 178}) { + if (raw.size() % s == 0) { + stride = s; + count = static_cast(raw.size() / s); + break; + } + } + } + } else if (count == 0 && stride > 0) { + count = static_cast(raw.size() / stride); + } + + if (stride != 152 && stride != 156 && stride != 172 && stride != 176 && stride != 178) { + return false; + } + + if (count == 0 || raw.size() < static_cast(count) * stride) { + return false; + } + + m_records.reserve(count); + size_t shift = (stride == 156 || stride == 176 || stride == 178) ? 4 : 0; + bool has_8_sockets = (stride == 172 || stride == 176 || stride == 178); + + for (uint32_t i = 0; i < count; ++i) { + auto row = std::span(raw).subspan(static_cast(i) * stride, stride); + ItemProtoRecord item; + + item.vnum = read32(row, 0); + if (shift) { + item.range = read32(row, 4); + } + + item.name = read_str(row, 4 + shift, 24); + item.locale_name = read_str(row, 29 + shift, 24); + + item.type = row[54 + shift]; + item.subtype = row[55 + shift]; + item.weight = row[56 + shift]; + item.size = row[57 + shift]; + + item.anti_flags = read32(row, 58 + shift); + item.flags = read32(row, 62 + shift); + item.wear_flags = read32(row, 66 + shift); + item.immune_flags = read32(row, 70 + shift); + + item.buy_price = read32(row, 74 + shift); + item.sell_price = read32(row, 78 + shift); + + for (size_t j = 0; j < 2; ++j) { + item.limits[j] = { + row[82 + shift + 5 * j], + read32_signed(row, 83 + shift + 5 * j) + }; + } + + for (size_t j = 0; j < 3; ++j) { + item.applies[j] = { + row[92 + shift + 5 * j], + read32_signed(row, 93 + shift + 5 * j) + }; + } + + for (size_t j = 0; j < 6; ++j) { + item.values[j] = read32_signed(row, 107 + shift + 4 * j); + } + + size_t socket_count = has_8_sockets ? 8 : 3; + for (size_t j = 0; j < socket_count; ++j) { + item.sockets[j] = read32_signed(row, 131 + shift + 4 * j); + } + + size_t tail_offset = 131 + shift + socket_count * 4; + item.refined_vnum = read32(row, tail_offset); + item.refine_set = read16(row, tail_offset + 4); + item.alter_to_magic_percent = row[tail_offset + 6]; + item.specular = row[tail_offset + 7]; + item.gain_socket_percent = row[tail_offset + 8]; + + size_t idx = m_records.size(); + if (item.range > 0) { + m_ranged_indices.push_back(idx); + } + m_vnum_map[item.vnum] = idx; + m_records.push_back(std::move(item)); + } + + return true; +} + +const ItemProtoRecord* ItemProto::find(uint32_t vnum) const { + auto it = m_vnum_map.find(vnum); + if (it != m_vnum_map.end()) { + return &m_records[it->second]; + } + + for (size_t idx : m_ranged_indices) { + const auto& rec = m_records[idx]; + if (vnum > rec.vnum && vnum < rec.vnum + rec.range) { + return &rec; + } + } + + return nullptr; +} + +} // namespace proto diff --git a/proto/src/mob_proto.cpp b/proto/src/mob_proto.cpp new file mode 100644 index 0000000..ecd5886 --- /dev/null +++ b/proto/src/mob_proto.cpp @@ -0,0 +1,210 @@ +#include "proto/mob_proto.h" +#include "eterpack/lzo.h" +#include +#include +#include + +namespace proto { + +namespace { + +inline uint16_t read16(std::span data, size_t offset) { + if (offset + 2 > data.size()) return 0; + return static_cast(data[offset]) | + (static_cast(data[offset + 1]) << 8); +} + +inline int16_t read16_signed(std::span data, size_t offset) { + return std::bit_cast(read16(data, offset)); +} + +inline uint32_t read32(std::span data, size_t offset) { + if (offset + 4 > data.size()) return 0; + return static_cast(data[offset]) | + (static_cast(data[offset + 1]) << 8) | + (static_cast(data[offset + 2]) << 16) | + (static_cast(data[offset + 3]) << 24); +} + +inline float read_float(std::span data, size_t offset) { + uint32_t val = read32(data, offset); + return std::bit_cast(val); +} + +inline std::string read_str(std::span data, size_t offset, size_t max_len) { + if (offset >= data.size()) return {}; + size_t len = 0; + while (offset + len < data.size() && len < max_len && data[offset + len] != 0) { + ++len; + } + return std::string(reinterpret_cast(data.data() + offset), len); +} + +} // anonymous namespace + +void MobProto::clear() { + m_records.clear(); + m_vnum_map.clear(); +} + +bool MobProto::load_file(const std::filesystem::path& filepath, const uint32_t key[4]) { + std::ifstream file(filepath, std::ios::binary); + if (!file.is_open()) return false; + + file.seekg(0, std::ios::end); + size_t size = static_cast(file.tellg()); + file.seekg(0, std::ios::beg); + + std::vector buffer(size); + if (!file.read(reinterpret_cast(buffer.data()), size)) { + return false; + } + + return load(buffer, key); +} + +bool MobProto::load(std::span input, const uint32_t key[4]) { + clear(); + if (input.size() < 12) return false; + + uint32_t fourcc = read32(input, 0); + size_t mcoz_offset = 0; + uint32_t count = 0; + + if (fourcc == 0x54504d4d) { // 'M', 'M', 'P', 'T' + count = read32(input, 4); + mcoz_offset = 12; + } else if (fourcc == eterpack::FOURCC_MCOZ) { + mcoz_offset = 0; + } else { + return false; + } + + if (mcoz_offset > input.size()) return false; + + std::vector raw; + if (!eterpack::LZO::instance().decompress_mcoz(input.subspan(mcoz_offset), raw, key)) { + return false; + } + + if (raw.empty()) return false; + + uint32_t stride = 0; + if (count > 0 && raw.size() % count == 0) { + stride = static_cast(raw.size() / count); + } else { + for (uint32_t s : {255, 256, 262, 263, 235}) { + if (raw.size() % s == 0) { + stride = s; + count = static_cast(raw.size() / s); + break; + } + } + } + + if (stride != 235 && stride != 255 && stride != 256 && stride != 262 && stride != 263) { + return false; + } + + if (count == 0 || raw.size() < static_cast(count) * stride) { + return false; + } + + size_t prefix_shift = (stride >= 262) ? 1 : 0; + size_t resist_shift = (stride >= 262) ? 2 : ((stride == 256) ? 1 : 0); + + m_records.reserve(count); + + for (uint32_t i = 0; i < count; ++i) { + auto row = std::span(raw).subspan(static_cast(i) * stride, stride); + MobRecord m; + + m.vnum = read32(row, 0); + m.name = read_str(row, 4, 24); + m.locale_name = read_str(row, 29, 24); + + m.type = row[54]; + m.rank = row[55]; + m.battle_type = row[56]; + m.level = row[57]; + m.size = row[58 + prefix_shift]; + + m.gold_min = read32(row, 59 + prefix_shift); + m.gold_max = read32(row, 63 + prefix_shift); + m.exp = read32(row, 67 + prefix_shift); + m.max_hp = read32(row, 71 + prefix_shift); + m.regen_cycle = row[75 + prefix_shift]; + m.regen_percent = row[76 + prefix_shift]; + m.def = read16(row, 77 + prefix_shift); + + m.ai_flag = read32(row, 79 + prefix_shift); + m.race_flag = read32(row, 83 + prefix_shift); + m.immune_flag = read32(row, 87 + prefix_shift); + + m.str = row[91 + prefix_shift]; + m.dex = row[92 + prefix_shift]; + m.con = row[93 + prefix_shift]; + m.intel = row[94 + prefix_shift]; + + m.damage_min = read32(row, 95 + prefix_shift); + m.damage_max = read32(row, 99 + prefix_shift); + + m.attack_speed = read16_signed(row, 103 + prefix_shift); + m.moving_speed = read16_signed(row, 105 + prefix_shift); + m.aggressive_hp_pct = row[107 + prefix_shift]; + m.aggressive_sight = read16(row, 108 + prefix_shift); + m.attack_range = read16(row, 110 + prefix_shift); + + for (size_t j = 0; j < 6; ++j) { + m.enchants[j] = static_cast(row[112 + prefix_shift + j]); + } + for (size_t j = 0; j < 11; ++j) { + m.resists[j] = static_cast(row[118 + prefix_shift + j]); + } + + m.resurrection_vnum = read32(row, 129 + prefix_shift + resist_shift); + m.drop_item_vnum = read32(row, 133 + prefix_shift + resist_shift); + m.mount_capacity = row[137 + prefix_shift + resist_shift]; + m.on_click_type = row[138 + prefix_shift + resist_shift]; + m.empire = row[139 + prefix_shift + resist_shift]; + + m.folder = read_str(row, 140 + prefix_shift + resist_shift, 64); + m.damage_multiply = read_float(row, 205 + prefix_shift + resist_shift); + m.summon_vnum = read32(row, 209 + prefix_shift + resist_shift); + m.drain_sp = read32(row, 213 + prefix_shift + resist_shift); + m.monster_color = read32(row, 217 + prefix_shift + resist_shift); + m.polymorph_item_vnum = read32(row, 221 + prefix_shift + resist_shift); + + if (stride >= 255) { + for (size_t j = 0; j < 5; ++j) { + size_t off = 225 + prefix_shift + resist_shift + j * 5; + m.skills[j].vnum = read32(row, off); + m.skills[j].level = row[off + 4]; + } + size_t pt_off = 250 + prefix_shift + resist_shift; + if (pt_off + 5 <= stride) { + m.berserk_point = row[pt_off]; + m.stone_skin_point = row[pt_off + 1]; + m.god_speed_point = row[pt_off + 2]; + m.death_blow_point = row[pt_off + 3]; + m.revive_point = row[pt_off + 4]; + } + } + + size_t idx = m_records.size(); + m_vnum_map[m.vnum] = idx; + m_records.push_back(std::move(m)); + } + + return true; +} + +const MobRecord* MobProto::find(uint32_t vnum) const { + auto it = m_vnum_map.find(vnum); + if (it != m_vnum_map.end()) { + return &m_records[it->second]; + } + return nullptr; +} + +} // namespace proto diff --git a/proto/tests/proto_test.cpp b/proto/tests/proto_test.cpp new file mode 100644 index 0000000..a363c5e --- /dev/null +++ b/proto/tests/proto_test.cpp @@ -0,0 +1,255 @@ +#include "proto/proto.h" +#include "eterpack/lzo.h" +#include +#include +#include +#include +#include + +namespace fs = std::filesystem; + +static int g_failures = 0; +#define TEST_CHECK(cond) \ + do { \ + if (!(cond)) { \ + std::cerr << "FAIL [" << __FILE__ << ":" << __LINE__ << "]: " #cond << std::endl; \ + ++g_failures; \ + } \ + } while(0) + +void append32(std::vector& buf, uint32_t val) { + buf.push_back(val & 0xFF); + buf.push_back((val >> 8) & 0xFF); + buf.push_back((val >> 16) & 0xFF); + buf.push_back((val >> 24) & 0xFF); +} + +void test_synthetic_item_proto_156() { + std::cout << "[Test] Synthetic item_proto (stride 156)..." << std::endl; + // Create 2 records with stride 156 + uint32_t stride = 156; + std::vector raw(stride * 2, 0); + + // Record 0: vnum 100, range 5, name "TestSword", price 1500 + auto r0 = raw.data(); + *reinterpret_cast(r0 + 0) = 100; + *reinterpret_cast(r0 + 4) = 5; // range + std::memcpy(r0 + 8, "SwordInternal", 13); + std::memcpy(r0 + 33, "Test Sword", 10); + r0[58] = 1; // type WEAPON + r0[59] = 0; // subtype SWORD + r0[60] = 5; // weight + r0[61] = 2; // size + *reinterpret_cast(r0 + 78) = 1500; // buyPrice + *reinterpret_cast(r0 + 82) = 750; // sellPrice + // Limits + r0[86] = 1; *reinterpret_cast(r0 + 87) = 30; // Level 30 + // Applies + r0[96] = 7; *reinterpret_cast(r0 + 97) = 15; // Attack speed +15 + // Sockets + *reinterpret_cast(r0 + 135) = 1; + *reinterpret_cast(r0 + 139) = 2; + *reinterpret_cast(r0 + 143) = -1; + + // Record 1: vnum 200, range 0, name "TestArmor" + auto r1 = raw.data() + stride; + *reinterpret_cast(r1 + 0) = 200; + *reinterpret_cast(r1 + 4) = 0; + std::memcpy(r1 + 8, "ArmorInternal", 13); + std::memcpy(r1 + 33, "Test Armor", 10); + r1[58] = 2; // type ARMOR + *reinterpret_cast(r1 + 78) = 3000; + + // Compress with MCOZ + TEA + std::vector mcoz_blob; + bool comp = eterpack::LZO::instance().compress_mcoz(raw, mcoz_blob, eterpack::DEFAULT_ITEM_PROTO_KEY); + TEST_CHECK(comp); + + // Build container MIPX + std::vector file_bytes; + append32(file_bytes, 0x5850494d); // 'M', 'I', 'P', 'X' + append32(file_bytes, 1); // version + append32(file_bytes, stride); // stride 156 + append32(file_bytes, 2); // elements + append32(file_bytes, static_cast(mcoz_blob.size())); + file_bytes.insert(file_bytes.end(), mcoz_blob.begin(), mcoz_blob.end()); + + proto::ItemProto proto; + TEST_CHECK(proto.load(file_bytes)); + TEST_CHECK(proto.size() == 2); + + const auto* it100 = proto.find(100); + TEST_CHECK(it100 != nullptr); + if (it100) { + TEST_CHECK(it100->vnum == 100); + TEST_CHECK(it100->range == 5); + TEST_CHECK(it100->name == "SwordInternal"); + TEST_CHECK(it100->locale_name == "Test Sword"); + TEST_CHECK(it100->type == 1); + TEST_CHECK(it100->subtype == 0); + TEST_CHECK(it100->buy_price == 1500); + TEST_CHECK(it100->sell_price == 750); + TEST_CHECK(it100->limits[0].first == 1); + TEST_CHECK(it100->limits[0].second == 30); + TEST_CHECK(it100->applies[0].first == 7); + TEST_CHECK(it100->applies[0].second == 15); + TEST_CHECK(it100->sockets[0] == 1); + TEST_CHECK(it100->sockets[1] == 2); + TEST_CHECK(it100->sockets[2] == -1); + } + + // Test range lookup: vnum 102 should resolve to base 100 + const auto* it102 = proto.find(102); + TEST_CHECK(it102 == it100); + + const auto* it200 = proto.find(200); + TEST_CHECK(it200 != nullptr); + if (it200) { + TEST_CHECK(it200->vnum == 200); + TEST_CHECK(it200->name == "ArmorInternal"); + } + + // 106 is out of range 100..105 + TEST_CHECK(proto.find(106) == nullptr); +} + +void test_synthetic_mob_proto_255() { + std::cout << "[Test] Synthetic mob_proto (stride 255)..." << std::endl; + uint32_t stride = 255; + std::vector raw(stride, 0); + + auto r = raw.data(); + *reinterpret_cast(r + 0) = 101; // Wild Dog + std::memcpy(r + 4, "WildDogInternal", 15); + std::memcpy(r + 29, "Wild Dog", 8); + r[54] = 0; // type MONSTER + r[55] = 0; // rank PAWN + r[56] = 0; // battleType MELEE + r[57] = 1; // level 1 + r[58] = 0; // size + *reinterpret_cast(r + 59) = 10; // goldMin + *reinterpret_cast(r + 63) = 25; // goldMax + *reinterpret_cast(r + 67) = 15; // exp + *reinterpret_cast(r + 71) = 120; // maxHP + r[75] = 12; // regenCycle + r[76] = 5; // regenPercent + *reinterpret_cast(r + 77) = 8; // def + *reinterpret_cast(r + 79) = 0; // aiFlag + *reinterpret_cast(r + 83) = 1; // raceFlag ANIMAL + r[91] = 5; // str + r[92] = 3; // dex + *reinterpret_cast(r + 95) = 12; // damageMin + *reinterpret_cast(r + 99) = 18; // damageMax + + std::vector mcoz_blob; + bool comp = eterpack::LZO::instance().compress_mcoz(raw, mcoz_blob, eterpack::DEFAULT_MOB_PROTO_KEY); + TEST_CHECK(comp); + + std::vector file_bytes; + append32(file_bytes, 0x54504d4d); // 'M', 'M', 'P', 'T' + append32(file_bytes, 1); // elements + append32(file_bytes, static_cast(mcoz_blob.size())); + file_bytes.insert(file_bytes.end(), mcoz_blob.begin(), mcoz_blob.end()); + + proto::MobProto proto; + TEST_CHECK(proto.load(file_bytes)); + TEST_CHECK(proto.size() == 1); + + const auto* m101 = proto.find(101); + TEST_CHECK(m101 != nullptr); + if (m101) { + TEST_CHECK(m101->vnum == 101); + TEST_CHECK(m101->name == "WildDogInternal"); + TEST_CHECK(m101->locale_name == "Wild Dog"); + TEST_CHECK(m101->level == 1); + TEST_CHECK(m101->gold_min == 10); + TEST_CHECK(m101->gold_max == 25); + TEST_CHECK(m101->exp == 15); + TEST_CHECK(m101->max_hp == 120); + TEST_CHECK(m101->def == 8); + TEST_CHECK(m101->damage_min == 12); + TEST_CHECK(m101->damage_max == 18); + } +} + +void test_real_item_and_mob_proto_if_present() { + std::cout << "[Test] Real asset files verification..." << std::endl; + std::vector item_candidates = { + "40250/Server Client TMP4/Client/Eternexus/root/20110915_ymir_item_proto", + "../../40250/Server Client TMP4/Client/Eternexus/root/20110915_ymir_item_proto", + "../../../40250/Server Client TMP4/Client/Eternexus/root/20110915_ymir_item_proto", + "/Users/shen/Work/Code/Metin2/40250/Server Client TMP4/Client/Eternexus/root/20110915_ymir_item_proto" + }; + + for (const auto& path : item_candidates) { + if (fs::exists(path)) { + proto::ItemProto proto; + bool ok = proto.load_file(path); + TEST_CHECK(ok); + if (ok) { + std::cout << " -> Loaded real item_proto (" << path << ") with " + << proto.size() << " records!" << std::endl; + TEST_CHECK(proto.size() >= 5000); + + // Check vnum 10 (Sword+0 in Metin2) + const auto* sword = proto.find(10); + TEST_CHECK(sword != nullptr); + if (sword) { + std::cout << " Vnum 10: name='" << sword->name + << "', locale='" << sword->locale_name + << "', type=" << (int)sword->type + << ", buyPrice=" << sword->buy_price << std::endl; + TEST_CHECK(sword->vnum == 10); + } + } + break; + } + } + + std::vector mob_candidates = { + "40250/Server Client TMP4/Client/Eternexus/locale_pl/locale/pl/mob_proto", + "../../40250/Server Client TMP4/Client/Eternexus/locale_pl/locale/pl/mob_proto", + "../../../40250/Server Client TMP4/Client/Eternexus/locale_pl/locale/pl/mob_proto", + "/Users/shen/Work/Code/Metin2/40250/Server Client TMP4/Client/Eternexus/locale_pl/locale/pl/mob_proto" + }; + + for (const auto& path : mob_candidates) { + if (fs::exists(path)) { + proto::MobProto proto; + bool ok = proto.load_file(path); + TEST_CHECK(ok); + if (ok) { + std::cout << " -> Loaded real mob_proto (" << path << ") with " + << proto.size() << " records!" << std::endl; + TEST_CHECK(proto.size() >= 1000); + + // Check vnum 101 (Wild Dog) + const auto* mob = proto.find(101); + TEST_CHECK(mob != nullptr); + if (mob) { + std::cout << " Vnum 101: name='" << mob->name + << "', locale='" << mob->locale_name + << "', level=" << (int)mob->level + << ", maxHP=" << mob->max_hp << std::endl; + TEST_CHECK(mob->vnum == 101); + } + } + break; + } + } +} + +int main() { + std::cout << "=== Running proto Unit Tests ===" << std::endl; + test_synthetic_item_proto_156(); + test_synthetic_mob_proto_255(); + test_real_item_and_mob_proto_if_present(); + + if (g_failures == 0) { + std::cout << "=== ALL proto TESTS PASSED ===" << std::endl; + return 0; + } else { + std::cerr << "=== " << g_failures << " proto TESTS FAILED ===" << std::endl; + return 1; + } +} diff --git a/spatial/CMakeLists.txt b/spatial/CMakeLists.txt new file mode 100644 index 0000000..ae954bf --- /dev/null +++ b/spatial/CMakeLists.txt @@ -0,0 +1,23 @@ +cmake_minimum_required(VERSION 3.20) +project(spatial LANGUAGES CXX) + +set(CMAKE_CXX_STANDARD 20) +set(CMAKE_CXX_STANDARD_REQUIRED ON) + +add_library(spatial STATIC + src/loose_octree.cpp +) + +target_include_directories(spatial PUBLIC + $ + $ +) + +add_library(spatial::spatial ALIAS spatial) + +option(SPATIAL_BUILD_TESTS "Build spatial SDK tests" ON) +if(SPATIAL_BUILD_TESTS) + add_executable(spatial_test tests/spatial_test.cpp) + target_link_libraries(spatial_test PRIVATE spatial) + add_test(NAME spatial_test COMMAND spatial_test) +endif() diff --git a/spatial/include/spatial/loose_octree.h b/spatial/include/spatial/loose_octree.h new file mode 100644 index 0000000..fa269fa --- /dev/null +++ b/spatial/include/spatial/loose_octree.h @@ -0,0 +1,69 @@ +#pragma once + +#include "types.h" +#include +#include +#include + +namespace metin2::spatial { + +class LooseOctree { +public: + struct Node { + AABB base_bounds; // Strict bounds of this octree cell + AABB loose_bounds; // Expanded bounds (by looseness factor, default 2.0) + int depth = 0; + std::array, 8> children; + std::vector objects; + + bool IsLeaf() const { + for (const auto& c : children) { + if (c) return false; + } + return true; + } + }; + + LooseOctree(const AABB& world_bounds, float looseness = 2.0f, int max_depth = 6, int max_objects_per_node = 16); + ~LooseOctree() = default; + + // Core Dynamic Operations + bool Insert(uint64_t id, SpatialObjectType type, const AABB& bounds, void* user_data = nullptr); + bool Update(uint64_t id, const AABB& new_bounds); + bool Remove(uint64_t id); + void Clear(); + + size_t Size() const { return m_object_map.size(); } + bool Contains(uint64_t id) const { return m_object_map.find(id) != m_object_map.end(); } + const AABB& GetWorldBounds() const { return m_world_bounds; } + + // Acceleration Queries + std::vector QueryFrustum(const Frustum& frustum, const Vector3& camera_pos, bool sort_by_distance = true) const; + std::vector QueryAABB(const AABB& query_box) const; + std::vector QuerySphere(const Vector3& center, float radius) const; + + bool Raycast(const Ray& ray, RaycastHit& out_hit) const; + std::vector RaycastAll(const Ray& ray) const; + +private: + void Subdivide(Node* node); + Node* FindBestNodeForBounds(Node* current, const AABB& bounds); + void QueryFrustumRecursive(const Node* node, const Frustum& frustum, const Vector3& camera_pos, + FrustumIntersection parent_status, std::vector& out_visible) const; + void CollectAllRecursive(const Node* node, const Vector3& camera_pos, std::vector& out_visible) const; + void QueryAABBRecursive(const Node* node, const AABB& query_box, std::vector& out_ids) const; + void QuerySphereRecursive(const Node* node, const Vector3& center, float radius_sq, std::vector& out_ids) const; + void RaycastRecursive(const Node* node, const Ray& ray, std::vector& hits) const; + + bool RemoveRecursive(Node* node, uint64_t id); + + AABB m_world_bounds; + float m_looseness = 2.0f; + int m_max_depth = 6; + int m_max_objects_per_node = 16; + + std::unique_ptr m_root; + std::unordered_map m_object_map; +}; + +} // namespace metin2::spatial diff --git a/spatial/include/spatial/spatial.h b/spatial/include/spatial/spatial.h new file mode 100644 index 0000000..87c84b9 --- /dev/null +++ b/spatial/include/spatial/spatial.h @@ -0,0 +1,4 @@ +#pragma once + +#include "types.h" +#include "loose_octree.h" diff --git a/spatial/include/spatial/types.h b/spatial/include/spatial/types.h new file mode 100644 index 0000000..2834f10 --- /dev/null +++ b/spatial/include/spatial/types.h @@ -0,0 +1,187 @@ +#pragma once + +#include +#include +#include +#include +#include + +namespace metin2::spatial { + +struct Vector3 { + float x = 0.0f; + float y = 0.0f; + float z = 0.0f; + + constexpr Vector3() = default; + constexpr Vector3(float in_x, float in_y, float in_z) : x(in_x), y(in_y), z(in_z) {} + + Vector3 operator+(const Vector3& o) const { return {x + o.x, y + o.y, z + o.z}; } + Vector3 operator-(const Vector3& o) const { return {x - o.x, y - o.y, z - o.z}; } + Vector3 operator*(float s) const { return {x * s, y * s, z * s}; } + Vector3 operator/(float s) const { float inv = 1.0f / s; return {x * inv, y * inv, z * inv}; } + Vector3& operator+=(const Vector3& o) { x += o.x; y += o.y; z += o.z; return *this; } + Vector3& operator-=(const Vector3& o) { x -= o.x; y -= o.y; z -= o.z; return *this; } + + float Dot(const Vector3& o) const { return x * o.x + y * o.y + z * o.z; } + Vector3 Cross(const Vector3& o) const { + return { + y * o.z - z * o.y, + z * o.x - x * o.z, + x * o.y - y * o.x + }; + } + + float LengthSq() const { return x * x + y * y + z * z; } + float Length() const { return std::sqrt(LengthSq()); } + float Distance(const Vector3& o) const { return (*this - o).Length(); } + float DistanceSq(const Vector3& o) const { return (*this - o).LengthSq(); } + + Vector3 Normalized() const { + float len = Length(); + if (len > 1e-6f) return *this / len; + return {0.0f, 0.0f, 0.0f}; + } +}; + +struct AABB { + Vector3 min_point{0.0f, 0.0f, 0.0f}; + Vector3 max_point{0.0f, 0.0f, 0.0f}; + + constexpr AABB() = default; + constexpr AABB(const Vector3& min_p, const Vector3& max_p) : min_point(min_p), max_point(max_p) {} + + Vector3 GetCenter() const { return (min_point + max_point) * 0.5f; } + Vector3 GetExtents() const { return (max_point - min_point) * 0.5f; } + Vector3 GetSize() const { return max_point - min_point; } + + bool Contains(const Vector3& p) const { + return (p.x >= min_point.x && p.x <= max_point.x) && + (p.y >= min_point.y && p.y <= max_point.y) && + (p.z >= min_point.z && p.z <= max_point.z); + } + + bool Contains(const AABB& o) const { + return (o.min_point.x >= min_point.x && o.max_point.x <= max_point.x) && + (o.min_point.y >= min_point.y && o.max_point.y <= max_point.y) && + (o.min_point.z >= min_point.z && o.max_point.z <= max_point.z); + } + + bool Intersects(const AABB& o) const { + return (min_point.x <= o.max_point.x && max_point.x >= o.min_point.x) && + (min_point.y <= o.max_point.y && max_point.y >= o.min_point.y) && + (min_point.z <= o.max_point.z && max_point.z >= o.min_point.z); + } + + AABB Expanded(float factor) const { + Vector3 c = GetCenter(); + Vector3 e = GetExtents() * factor; + return {c - e, c + e}; + } +}; + +struct Plane { + Vector3 normal{0.0f, 1.0f, 0.0f}; + float d = 0.0f; // ax + by + cz + d = 0 + + constexpr Plane() = default; + constexpr Plane(const Vector3& n, float in_d) : normal(n), d(in_d) {} + + void Normalize() { + float len = normal.Length(); + if (len > 1e-6f) { + normal = normal / len; + d /= len; + } + } + + float DistanceTo(const Vector3& p) const { + return normal.Dot(p) + d; + } +}; + +enum class FrustumIntersection { + Outside = 0, + Inside, + Intersects +}; + +class Frustum { +public: + enum PlaneIndex { + PlaneLeft = 0, + PlaneRight, + PlaneBottom, + PlaneTop, + PlaneNear, + PlaneFar, + NumPlanes = 6 + }; + + Frustum() = default; + + void SetPlane(PlaneIndex idx, const Plane& plane) { + m_planes[idx] = plane; + m_planes[idx].Normalize(); + } + + const Plane& GetPlane(PlaneIndex idx) const { return m_planes[idx]; } + + static Frustum CreateFromViewProj(const float m[16]); + static Frustum CreatePerspective(const Vector3& eye, const Vector3& look_dir, const Vector3& up, + float fov_deg, float aspect, float near_z, float far_z); + + FrustumIntersection TestAABB(const AABB& aabb) const; + bool Intersects(const AABB& aabb) const { + return TestAABB(aabb) != FrustumIntersection::Outside; + } + +private: + std::array m_planes; +}; + +struct Ray { + Vector3 origin; + Vector3 direction; // should be normalized + + bool IntersectAABB(const AABB& aabb, float& out_t) const; +}; + +enum class SpatialObjectType : uint8_t { + Unknown = 0, + Building, + Tree, + Character, + Monster, + NPC, + Effect, + ItemDrop +}; + +struct SpatialObject { + uint64_t id = 0; + SpatialObjectType type = SpatialObjectType::Unknown; + AABB bounds; + void* user_data = nullptr; +}; + +struct VisibleObject { + uint64_t id = 0; + SpatialObjectType type = SpatialObjectType::Unknown; + AABB bounds; + float distance_sq = 0.0f; + float distance = 0.0f; + void* user_data = nullptr; +}; + +struct RaycastHit { + bool hit = false; + uint64_t object_id = 0; + SpatialObjectType type = SpatialObjectType::Unknown; + float distance = 0.0f; + Vector3 point; + Vector3 normal; + void* user_data = nullptr; +}; + +} // namespace metin2::spatial diff --git a/spatial/src/loose_octree.cpp b/spatial/src/loose_octree.cpp new file mode 100644 index 0000000..b58049f --- /dev/null +++ b/spatial/src/loose_octree.cpp @@ -0,0 +1,439 @@ +#include "spatial/loose_octree.h" +#include +#include +#include + +namespace metin2::spatial { + +// Frustum Helpers +Frustum Frustum::CreateFromViewProj(const float m[16]) { + // Gribb-Hartmann Matrix Frustum Extraction + // Assuming column-major or row-major standard layout + Frustum f; + + // Left plane: row 4 + row 1 + f.SetPlane(PlaneLeft, Plane({m[3] + m[0], m[7] + m[4], m[11] + m[8]}, m[15] + m[12])); + // Right plane: row 4 - row 1 + f.SetPlane(PlaneRight, Plane({m[3] - m[0], m[7] - m[4], m[11] - m[8]}, m[15] - m[12])); + // Bottom plane: row 4 + row 2 + f.SetPlane(PlaneBottom, Plane({m[3] + m[1], m[7] + m[5], m[11] + m[9]}, m[15] + m[13])); + // Top plane: row 4 - row 2 + f.SetPlane(PlaneTop, Plane({m[3] - m[1], m[7] - m[5], m[11] - m[9]}, m[15] - m[13])); + // Near plane: row 4 + row 3 + f.SetPlane(PlaneNear, Plane({m[3] + m[2], m[7] + m[6], m[11] + m[10]}, m[15] + m[14])); + // Far plane: row 4 - row 3 + f.SetPlane(PlaneFar, Plane({m[3] - m[2], m[7] - m[6], m[11] - m[10]}, m[15] - m[14])); + + return f; +} + +Frustum Frustum::CreatePerspective(const Vector3& eye, const Vector3& look_dir, const Vector3& up, + float fov_deg, float aspect, float near_z, float far_z) { + Vector3 fwd = look_dir.Normalized(); + Vector3 cam_right = up.Cross(fwd).Normalized(); + Vector3 cam_up = fwd.Cross(cam_right).Normalized(); + + float half_fov_rad = (fov_deg * 0.5f) * (3.1415926535f / 180.0f); + float tan_half_fov = std::tan(half_fov_rad); + + float near_h = near_z * tan_half_fov; + float near_w = near_h * aspect; + + Vector3 near_center = eye + fwd * near_z; + Vector3 far_center = eye + fwd * far_z; + + Frustum f; + // Near & Far (normals point inward into frustum) + f.SetPlane(PlaneNear, Plane(fwd, -fwd.Dot(near_center))); + f.SetPlane(PlaneFar, Plane(fwd * -1.0f, fwd.Dot(far_center))); + + // Left & Right + Vector3 left_normal = (cam_right * near_z + fwd * near_w).Normalized(); + Vector3 right_normal = (cam_right * -near_z + fwd * near_w).Normalized(); + f.SetPlane(PlaneLeft, Plane(left_normal, -left_normal.Dot(eye))); + f.SetPlane(PlaneRight, Plane(right_normal, -right_normal.Dot(eye))); + + // Top & Bottom + Vector3 top_normal = (cam_up * -near_z + fwd * near_h).Normalized(); + Vector3 bottom_normal = (cam_up * near_z + fwd * near_h).Normalized(); + f.SetPlane(PlaneTop, Plane(top_normal, -top_normal.Dot(eye))); + f.SetPlane(PlaneBottom, Plane(bottom_normal, -bottom_normal.Dot(eye))); + + return f; +} + +FrustumIntersection Frustum::TestAABB(const AABB& aabb) const { + bool fully_inside = true; + + for (int i = 0; i < 6; ++i) { + const auto& p = m_planes[i]; + + // p-vertex (most positive in plane normal direction) + Vector3 p_vertex{ + p.normal.x >= 0 ? aabb.max_point.x : aabb.min_point.x, + p.normal.y >= 0 ? aabb.max_point.y : aabb.min_point.y, + p.normal.z >= 0 ? aabb.max_point.z : aabb.min_point.z + }; + + // If p-vertex is outside, entire AABB is outside + if (p.DistanceTo(p_vertex) < 0.0f) { + return FrustumIntersection::Outside; + } + + // n-vertex (most negative in plane normal direction) + Vector3 n_vertex{ + p.normal.x >= 0 ? aabb.min_point.x : aabb.max_point.x, + p.normal.y >= 0 ? aabb.min_point.y : aabb.max_point.y, + p.normal.z >= 0 ? aabb.min_point.z : aabb.max_point.z + }; + + if (p.DistanceTo(n_vertex) < 0.0f) { + fully_inside = false; + } + } + + return fully_inside ? FrustumIntersection::Inside : FrustumIntersection::Intersects; +} + +// Ray-AABB Slab intersection +bool Ray::IntersectAABB(const AABB& aabb, float& out_t) const { + float tmin = 0.0f; + float tmax = std::numeric_limits::max(); + + for (int i = 0; i < 3; ++i) { + float origin_val = (i == 0) ? origin.x : (i == 1 ? origin.y : origin.z); + float dir_val = (i == 0) ? direction.x : (i == 1 ? direction.y : direction.z); + float min_val = (i == 0) ? aabb.min_point.x : (i == 1 ? aabb.min_point.y : aabb.min_point.z); + float max_val = (i == 0) ? aabb.max_point.x : (i == 1 ? aabb.max_point.y : aabb.max_point.z); + + if (std::abs(dir_val) < 1e-8f) { + if (origin_val < min_val || origin_val > max_val) return false; + } else { + float inv_d = 1.0f / dir_val; + float t1 = (min_val - origin_val) * inv_d; + float t2 = (max_val - origin_val) * inv_d; + if (t1 > t2) std::swap(t1, t2); + tmin = std::max(tmin, t1); + tmax = std::min(tmax, t2); + if (tmin > tmax) return false; + } + } + + out_t = tmin; + return true; +} + +// LooseOctree +LooseOctree::LooseOctree(const AABB& world_bounds, float looseness, int max_depth, int max_objects_per_node) + : m_world_bounds(world_bounds) + , m_looseness(looseness) + , m_max_depth(max_depth) + , m_max_objects_per_node(max_objects_per_node) { + m_root = std::make_unique(); + m_root->base_bounds = world_bounds; + m_root->loose_bounds = world_bounds.Expanded(looseness); + m_root->depth = 0; +} + +void LooseOctree::Subdivide(Node* node) { + Vector3 center = node->base_bounds.GetCenter(); + Vector3 min_p = node->base_bounds.min_point; + Vector3 max_p = node->base_bounds.max_point; + + for (int i = 0; i < 8; ++i) { + Vector3 child_min{ + (i & 1) ? center.x : min_p.x, + (i & 2) ? center.y : min_p.y, + (i & 4) ? center.z : min_p.z + }; + Vector3 child_max{ + (i & 1) ? max_p.x : center.x, + (i & 2) ? max_p.y : center.y, + (i & 4) ? max_p.z : center.z + }; + + auto child = std::make_unique(); + child->base_bounds = AABB(child_min, child_max); + child->loose_bounds = child->base_bounds.Expanded(m_looseness); + child->depth = node->depth + 1; + node->children[i] = std::move(child); + } +} + +LooseOctree::Node* LooseOctree::FindBestNodeForBounds(Node* current, const AABB& bounds) { + if (current->depth >= m_max_depth) { + return current; + } + + if (current->IsLeaf()) { + if (current->objects.size() >= static_cast(m_max_objects_per_node)) { + Subdivide(current); + } else { + return current; + } + } + + // Check if bounds completely fit inside any child's loose bounds + for (int i = 0; i < 8; ++i) { + if (current->children[i] && current->children[i]->loose_bounds.Contains(bounds)) { + return FindBestNodeForBounds(current->children[i].get(), bounds); + } + } + + return current; +} + +bool LooseOctree::Insert(uint64_t id, SpatialObjectType type, const AABB& bounds, void* user_data) { + if (m_object_map.find(id) != m_object_map.end()) { + return false; + } + + SpatialObject obj; + obj.id = id; + obj.type = type; + obj.bounds = bounds; + obj.user_data = user_data; + + Node* target = FindBestNodeForBounds(m_root.get(), bounds); + target->objects.push_back(obj); + m_object_map[id] = obj; + return true; +} + +bool LooseOctree::RemoveRecursive(Node* node, uint64_t id) { + auto it = std::remove_if(node->objects.begin(), node->objects.end(), + [id](const SpatialObject& o) { return o.id == id; }); + if (it != node->objects.end()) { + node->objects.erase(it, node->objects.end()); + return true; + } + + for (auto& child : node->children) { + if (child && RemoveRecursive(child.get(), id)) { + return true; + } + } + return false; +} + +bool LooseOctree::Remove(uint64_t id) { + auto it = m_object_map.find(id); + if (it == m_object_map.end()) { + return false; + } + + RemoveRecursive(m_root.get(), id); + m_object_map.erase(it); + return true; +} + +bool LooseOctree::Update(uint64_t id, const AABB& new_bounds) { + auto it = m_object_map.find(id); + if (it == m_object_map.end()) { + return false; + } + + SpatialObjectType type = it->second.type; + void* user_data = it->second.user_data; + + Remove(id); + return Insert(id, type, new_bounds, user_data); +} + +void LooseOctree::Clear() { + m_object_map.clear(); + m_root = std::make_unique(); + m_root->base_bounds = m_world_bounds; + m_root->loose_bounds = m_world_bounds.Expanded(m_looseness); + m_root->depth = 0; +} + +void LooseOctree::CollectAllRecursive(const Node* node, const Vector3& camera_pos, std::vector& out_visible) const { + for (const auto& obj : node->objects) { + VisibleObject vis; + vis.id = obj.id; + vis.type = obj.type; + vis.bounds = obj.bounds; + vis.user_data = obj.user_data; + vis.distance_sq = camera_pos.DistanceSq(obj.bounds.GetCenter()); + vis.distance = std::sqrt(vis.distance_sq); + out_visible.push_back(vis); + } + + for (const auto& child : node->children) { + if (child) { + CollectAllRecursive(child.get(), camera_pos, out_visible); + } + } +} + +void LooseOctree::QueryFrustumRecursive(const Node* node, const Frustum& frustum, const Vector3& camera_pos, + FrustumIntersection parent_status, std::vector& out_visible) const { + FrustumIntersection status = parent_status; + if (status != FrustumIntersection::Inside) { + status = frustum.TestAABB(node->loose_bounds); + } + + if (status == FrustumIntersection::Outside) { + return; // Culling entire node and children! + } + + if (status == FrustumIntersection::Inside) { + // Entire subtree visible + CollectAllRecursive(node, camera_pos, out_visible); + return; + } + + // Intersects: test each object individually + for (const auto& obj : node->objects) { + if (frustum.Intersects(obj.bounds)) { + VisibleObject vis; + vis.id = obj.id; + vis.type = obj.type; + vis.bounds = obj.bounds; + vis.user_data = obj.user_data; + vis.distance_sq = camera_pos.DistanceSq(obj.bounds.GetCenter()); + vis.distance = std::sqrt(vis.distance_sq); + out_visible.push_back(vis); + } + } + + for (const auto& child : node->children) { + if (child) { + QueryFrustumRecursive(child.get(), frustum, camera_pos, status, out_visible); + } + } +} + +std::vector LooseOctree::QueryFrustum(const Frustum& frustum, const Vector3& camera_pos, bool sort_by_distance) const { + std::vector visible; + if (m_root) { + QueryFrustumRecursive(m_root.get(), frustum, camera_pos, FrustumIntersection::Intersects, visible); + } + + if (sort_by_distance && !visible.empty()) { + std::sort(visible.begin(), visible.end(), [](const VisibleObject& a, const VisibleObject& b) { + return a.distance_sq < b.distance_sq; + }); + } + + return visible; +} + +void LooseOctree::QueryAABBRecursive(const Node* node, const AABB& query_box, std::vector& out_ids) const { + if (!node->loose_bounds.Intersects(query_box)) { + return; + } + + for (const auto& obj : node->objects) { + if (obj.bounds.Intersects(query_box)) { + out_ids.push_back(obj.id); + } + } + + for (const auto& child : node->children) { + if (child) { + QueryAABBRecursive(child.get(), query_box, out_ids); + } + } +} + +std::vector LooseOctree::QueryAABB(const AABB& query_box) const { + std::vector result; + if (m_root) { + QueryAABBRecursive(m_root.get(), query_box, result); + } + return result; +} + +void LooseOctree::QuerySphereRecursive(const Node* node, const Vector3& center, float radius_sq, std::vector& out_ids) const { + // AABB-Sphere test for node loose bounds + Vector3 clamped{ + std::clamp(center.x, node->loose_bounds.min_point.x, node->loose_bounds.max_point.x), + std::clamp(center.y, node->loose_bounds.min_point.y, node->loose_bounds.max_point.y), + std::clamp(center.z, node->loose_bounds.min_point.z, node->loose_bounds.max_point.z) + }; + if (center.DistanceSq(clamped) > radius_sq) { + return; + } + + for (const auto& obj : node->objects) { + Vector3 obj_clamped{ + std::clamp(center.x, obj.bounds.min_point.x, obj.bounds.max_point.x), + std::clamp(center.y, obj.bounds.min_point.y, obj.bounds.max_point.y), + std::clamp(center.z, obj.bounds.min_point.z, obj.bounds.max_point.z) + }; + if (center.DistanceSq(obj_clamped) <= radius_sq) { + out_ids.push_back(obj.id); + } + } + + for (const auto& child : node->children) { + if (child) { + QuerySphereRecursive(child.get(), center, radius_sq, out_ids); + } + } +} + +std::vector LooseOctree::QuerySphere(const Vector3& center, float radius) const { + std::vector result; + if (m_root && radius > 0.0f) { + QuerySphereRecursive(m_root.get(), center, radius * radius, result); + } + return result; +} + +void LooseOctree::RaycastRecursive(const Node* node, const Ray& ray, std::vector& hits) const { + float node_t = 0.0f; + if (!ray.IntersectAABB(node->loose_bounds, node_t)) { + return; + } + + for (const auto& obj : node->objects) { + float obj_t = 0.0f; + if (ray.IntersectAABB(obj.bounds, obj_t)) { + RaycastHit hit; + hit.hit = true; + hit.object_id = obj.id; + hit.type = obj.type; + hit.distance = obj_t; + hit.point = ray.origin + ray.direction * obj_t; + hit.user_data = obj.user_data; + hits.push_back(hit); + } + } + + for (const auto& child : node->children) { + if (child) { + RaycastRecursive(child.get(), ray, hits); + } + } +} + +bool LooseOctree::Raycast(const Ray& ray, RaycastHit& out_hit) const { + auto hits = RaycastAll(ray); + if (hits.empty()) { + out_hit.hit = false; + return false; + } + + out_hit = hits[0]; // Already sorted by distance ascending + return true; +} + +std::vector LooseOctree::RaycastAll(const Ray& ray) const { + std::vector hits; + if (m_root) { + RaycastRecursive(m_root.get(), ray, hits); + } + + if (!hits.empty()) { + std::sort(hits.begin(), hits.end(), [](const RaycastHit& a, const RaycastHit& b) { + return a.distance < b.distance; + }); + } + + return hits; +} + +} // namespace metin2::spatial diff --git a/spatial/tests/spatial_test.cpp b/spatial/tests/spatial_test.cpp new file mode 100644 index 0000000..b668ba7 --- /dev/null +++ b/spatial/tests/spatial_test.cpp @@ -0,0 +1,134 @@ +#include "spatial/spatial.h" +#include +#include +#include + +using namespace metin2::spatial; + +void TestMathPrimitives() { + std::cout << "[Test] Vector3 & AABB & Frustum Primitives...\n"; + Vector3 a(1, 2, 3); + Vector3 b(4, 5, 6); + assert(a.Dot(b) == 32.0f); + + Vector3 cross = Vector3(1, 0, 0).Cross(Vector3(0, 1, 0)); + assert(std::abs(cross.z - 1.0f) < 1e-5f); + + AABB box(Vector3(-10, -10, -10), Vector3(10, 10, 10)); + assert(box.Contains(Vector3(0, 0, 0))); + assert(!box.Contains(Vector3(20, 0, 0))); + + AABB other(Vector3(5, 5, 5), Vector3(15, 15, 15)); + assert(box.Intersects(other)); + + // Perspective Frustum + Vector3 eye(0, 100, -500); + Vector3 look(0, 0, 1); + Vector3 up(0, 1, 0); + Frustum frustum = Frustum::CreatePerspective(eye, look, up, 60.0f, 16.0f / 9.0f, 1.0f, 2000.0f); + + AABB in_front(Vector3(-50, 50, 200), Vector3(50, 150, 300)); + assert(frustum.Intersects(in_front)); + + AABB behind_camera(Vector3(-50, 50, -1000), Vector3(50, 150, -800)); + assert(!frustum.Intersects(behind_camera)); + + std::cout << " -> Math primitives passed!\n"; +} + +void TestLooseOctreeDynamicOperations() { + std::cout << "[Test] Loose Octree Dynamic Insertion, Update & Removal...\n"; + AABB world(Vector3(-50000, -5000, -50000), Vector3(50000, 10000, 50000)); + LooseOctree octree(world, 2.0f, 5, 8); + + // Insert 3 objects: Building (1), Tree (2), Monster (3) + assert(octree.Insert(1, SpatialObjectType::Building, AABB(Vector3(100, 0, 100), Vector3(300, 400, 300)))); + assert(octree.Insert(2, SpatialObjectType::Tree, AABB(Vector3(-200, 0, 500), Vector3(-150, 600, 550)))); + assert(octree.Insert(3, SpatialObjectType::Monster, AABB(Vector3(10, 0, 10), Vector3(30, 80, 30)))); + + assert(octree.Size() == 3); + assert(octree.Contains(1)); + assert(octree.Contains(2)); + assert(octree.Contains(3)); + + // Cannot insert duplicate ID + assert(!octree.Insert(1, SpatialObjectType::Building, AABB(Vector3(0, 0, 0), Vector3(10, 10, 10)))); + + // Update object 3 position + assert(octree.Update(3, AABB(Vector3(500, 0, 500), Vector3(520, 80, 520)))); + assert(octree.Size() == 3); + + // Remove object 2 + assert(octree.Remove(2)); + assert(!octree.Contains(2)); + assert(octree.Size() == 2); + + std::cout << " -> Loose Octree operations passed!\n"; +} + +void TestFrustumCullingAndDistanceSort() { + std::cout << "[Test] Frustum Culling & Distance Sorting...\n"; + AABB world(Vector3(-10000, -1000, -10000), Vector3(10000, 2000, 10000)); + LooseOctree octree(world); + + // Insert objects along the Z-axis + // Camera is at (0, 0, 0), looking forward (0, 0, 1) + octree.Insert(10, SpatialObjectType::Tree, AABB(Vector3(-10, 0, 500), Vector3(10, 200, 520))); // In front (500 units) + octree.Insert(20, SpatialObjectType::Tree, AABB(Vector3(-10, 0, 100), Vector3(10, 200, 120))); // In front (100 units, closer) + octree.Insert(30, SpatialObjectType::Tree, AABB(Vector3(-10, 0, 1500), Vector3(10, 200, 1520)));// In front (1500 units, farther) + octree.Insert(40, SpatialObjectType::Building, AABB(Vector3(-10, 0, -500), Vector3(10, 200, -480))); // Behind camera + octree.Insert(50, SpatialObjectType::Building, AABB(Vector3(3000, 0, 200), Vector3(3200, 200, 220))); // Way off to the right + + Vector3 cam_pos(0, 10, 0); + Frustum frustum = Frustum::CreatePerspective(cam_pos, Vector3(0, 0, 1), Vector3(0, 1, 0), 60.0f, 1.0f, 10.0f, 2000.0f); + + auto visible = octree.QueryFrustum(frustum, cam_pos, true); + + // Expected: 20, 10, 30 are visible in order of distance; 40 and 50 are culled! + assert(visible.size() == 3); + assert(visible[0].id == 20); // ~110 units + assert(visible[1].id == 10); // ~510 units + assert(visible[2].id == 30); // ~1510 units + assert(visible[0].distance < visible[1].distance); + assert(visible[1].distance < visible[2].distance); + + std::cout << " -> Frustum culling and distance sort verified!\n"; +} + +void TestSphereQueryAndRaycast() { + std::cout << "[Test] Sphere AOE Query & Raycast...\n"; + AABB world(Vector3(-10000, -1000, -10000), Vector3(10000, 2000, 10000)); + LooseOctree octree(world); + + octree.Insert(100, SpatialObjectType::Monster, AABB(Vector3(0, 0, 100), Vector3(20, 50, 120))); + octree.Insert(200, SpatialObjectType::Monster, AABB(Vector3(0, 0, 300), Vector3(20, 50, 320))); + octree.Insert(300, SpatialObjectType::Building, AABB(Vector3(500, 0, 500), Vector3(600, 300, 600))); + + // Sphere query around (0, 0, 100) with radius 150 + auto sphere_hits = octree.QuerySphere(Vector3(10, 25, 110), 100.0f); + assert(sphere_hits.size() == 1); + assert(sphere_hits[0] == 100); + + // Raycast: shoot ray straight down Z axis from (10, 25, 0) towards +Z + Ray ray; + ray.origin = Vector3(10, 25, 0); + ray.direction = Vector3(0, 0, 1); + + RaycastHit hit; + bool found = octree.Raycast(ray, hit); + assert(found); + assert(hit.object_id == 100); + assert(hit.distance >= 99.0f && hit.distance <= 101.0f); + + std::cout << " -> Sphere query and Raycast verified!\n"; +} + +int main() { + std::cout << "=== Running Metin2 Spatial Octree SDK Tests ===\n"; + TestMathPrimitives(); + TestLooseOctreeDynamicOperations(); + TestFrustumCullingAndDistanceSort(); + TestSphereQueryAndRaycast(); + std::cout << "All Spatial Octree SDK Tests PASSED!\n"; + return 0; +} diff --git a/speedtree/CMakeLists.txt b/speedtree/CMakeLists.txt new file mode 100644 index 0000000..2bee597 --- /dev/null +++ b/speedtree/CMakeLists.txt @@ -0,0 +1,37 @@ +cmake_minimum_required(VERSION 3.20) +project(libspeedtree CXX) + +set(CMAKE_CXX_STANDARD 20) +set(CMAKE_CXX_STANDARD_REQUIRED ON) + +set(SPEEDTREE_SOURCES + src/spt_parser.cpp + src/tree_generator.cpp + src/forest.cpp +) + +set(SPEEDTREE_HEADERS + include/speedtree/speedtree.h + include/speedtree/foliage_shaders.h +) + +add_library(speedtree STATIC + ${SPEEDTREE_SOURCES} + ${SPEEDTREE_HEADERS} +) + +add_library(speedtree::speedtree ALIAS speedtree) + +target_include_directories(speedtree PUBLIC + $ + $ +) + +# Standalone Unit Test +option(SPEEDTREE_BUILD_TESTS "Build SpeedTree SDK tests" ON) +if(SPEEDTREE_BUILD_TESTS) + enable_testing() + add_executable(speedtree_test tests/speedtree_test.cpp) + target_link_libraries(speedtree_test PRIVATE speedtree) + add_test(NAME speedtree_test COMMAND speedtree_test) +endif() diff --git a/speedtree/README.md b/speedtree/README.md new file mode 100644 index 0000000..e6f28b0 --- /dev/null +++ b/speedtree/README.md @@ -0,0 +1,63 @@ +# SpeedTree Cross-Platform Foliage SDK + +A pure C++20, graphics-API-agnostic implementation of SpeedTree foliage rendering and wind dynamics for cross-platform game engines. + +## 🌟 核心特性与渲染真实度突破(Realism & Shading) + +为了达到与商业版 SpeedTree 同样真实、飘逸自然的渲染质感,本 SDK 实现了以下四大核心技术管线: + +### 1. 三级分层风场动力学 (3-Tier Hierarchical Wind Dynamics) +- **Level 1 树干弯曲 (Trunk Bending)**: 基于树高的二次曲线响应,具备长度保持(Length-Preserving)算法,模拟主干在阵风下的柔韧弯曲。 +- **Level 2 树枝摇曳 (Branch Sway)**: 引入大分支相对主干的摆动阻尼与相位差(Phase Offset),营造起伏有致的林间韵律。 +- **Level 3 叶片自转翻滚与颤动 (Leaf Flutter & Tumble)**: **这是“飘逸感”的最关键核心**。每个树叶卡片顶点都绑定了叶片局部中心锚点(`leaf_pivot_offset`)。在微风与阵风下,叶片围绕自身锚点高频翻滚微颤,光影鳞鳞闪烁,彻底消除僵硬片状感。 +- **空间阵风波 (Spatial Gust Waves)**: 风场跨越坐标系传递低频起伏波,使森林呈现一波波风浪拂过的生动波纹。 + +### 2. 树冠球形法线混合 (Canopy Spherical Normal Blending) +- 传统 Billboard/插片树叶最大的痛点是“纸片感”与法线杂乱破碎。 +- 本 SDK 在几何生成和 Shader 中自动计算以树冠重心为起点的**虚拟球形法线(Spherical Normal)**,并与叶片原始朝向做柔和加权混合。即使是由十字交叉面片组成的树冠,在阳光下也能呈现出浑厚、饱满的体积感。 + +### 3. 次表面透射与半兰伯特环绕光 (Subsurface Scattering & Wrap Lighting) +- **背光透射 (Subsurface Transmission)**: 逆光观察树木时,阳光穿透薄叶片,Shader 自动产生透光的翠绿光晕(`viewThrough = pow(dot(-L, V), 3.5)`)。 +- **半兰伯特环绕光 (Wrap Lighting)**: 漫反射平滑过渡,背光区域不会死黑。 +- **树冠内部自遮挡 (Canopy Interior AO)**: 依据叶片距树冠中心的距离衰减环境光,外层明亮透光、内部深邃幽暗。 + +### 4. 跨平台双管线支持 (Modern GPU Shader + CPU Fallback) +- **现代 GPU 管线**: 提供标准的 `foliage_shaders.h`(GLSL 450 / Vulkan SPIR-V / Metal / D3D11-12 兼容),顶点着色器硬件级高帧率解算风力与球形法线。 +- **CPU Fallback 管线**: 提供 `EvaluateCpuTransformedVertices()`,在老旧驱动或无自定义 Shader 环境下依然能实时计算风力变形。 + +--- + +## 📁 模块架构 + +```text +sdk/speedtree/ +├── include/speedtree/ +│ ├── speedtree.h # 核心模型、顶点布局、SPT 信息、森林实例管理 +│ └── foliage_shaders.h # 现代 GPU 植被顶点/片元着色器源码(含 3 级风力与次表面透光) +├── src/ +│ ├── spt_parser.cpp # 官方 .spt 二进制解析(Token 2000/2001/10000/10002/12000 等) +│ ├── tree_generator.cpp # 树木骨架圆柱网格、树冠卡片、风力权重生成与 CPU 变形求值 +│ └── forest.cpp # 森林多实例生命周期、视锥剔除基础、风向风力统一控制 +└── tests/ + └── speedtree_test.cpp # 单元测试(生成、Token 嗅探、风力位移) +``` + +--- + +## 🚀 集成与使用示例 + +```cpp +#include + +// 1. 创建树木模板(可从 .spt 文件或通过参数化生成) +auto model = speedtree::SpeedTreeModel::CreateFromSpt("ymir work/tree/b1_baobab_rt.spt"); + +// 2. 森林多实例管理 +speedtree::SpeedTreeForest forest; +forest.RegisterProperty(crc, "d:/ymir work/tree/b1_baobab.prt"); +auto* instance = forest.CreateInstance(150.0f, 0.0f, 320.0f, crc, 45.0f, 1.0f); + +// 3. 帧循环更新风力 +forest.SetWindStrength(1.5f); +forest.Update(deltaTime); +``` diff --git a/speedtree/include/speedtree/foliage_shaders.h b/speedtree/include/speedtree/foliage_shaders.h new file mode 100644 index 0000000..6df45a8 --- /dev/null +++ b/speedtree/include/speedtree/foliage_shaders.h @@ -0,0 +1,161 @@ +#pragma once + +namespace speedtree { + +// Reference GLSL / Vulkan / Metal / OpenGL 4.5+ shader sources for high-fidelity foliage rendering. +// Can be embedded or compiled into SPIR-V. + +inline const char* GetFoliageVertexShaderGLSL() { + return R"glsl( +#version 450 core + +layout(location = 0) in vec3 in_Position; +layout(location = 1) in vec3 in_Normal; +layout(location = 2) in vec2 in_TexCoord; +layout(location = 3) in vec4 in_WindWeights; // [0]:Trunk, [1]:Branch, [2]:Leaf, [3]:Phase +layout(location = 4) in vec3 in_LeafPivotOffset; // Leaf center to vertex +layout(location = 5) in uint in_Diffuse; + +layout(std140, binding = 0) uniform FrameBlock { + mat4 u_ViewProj; + vec3 u_CameraPos; + float u_Time; + vec3 u_WindDir; + float u_WindStrength; +}; + +layout(std140, binding = 1) uniform InstanceBlock { + mat4 u_ModelMatrix; + vec3 u_TreeOrigin; + float u_TreeHeight; +}; + +layout(location = 0) out vec3 v_WorldPos; +layout(location = 1) out vec3 v_WorldNormal; +layout(location = 2) out vec2 v_TexCoord; +layout(location = 3) out float v_CanopyAO; + +vec3 RotateAngleAxis(vec3 v, vec3 axis, float angle) { + float cosTheta = cos(angle); + float sinTheta = sin(angle); + return v * cosTheta + cross(axis, v) * sinTheta + axis * dot(axis, v) * (1.0 - cosTheta); +} + +void main() { + vec3 localPos = in_Position; + vec3 localNormal = in_Normal; + + float trunkW = in_WindWeights.r; + float branchW = in_WindWeights.g; + float leafW = in_WindWeights.b; + float phase = in_WindWeights.a; + + // Level 0: Global Wind Gust Wave + float gustSpatial = dot(u_TreeOrigin.xz, u_WindDir.xz * 0.04); + float gust = sin(u_Time * 0.8 + gustSpatial) * 0.5 + 0.5; + float effectiveWind = u_WindStrength * (0.8 + 0.4 * gust); + + vec3 windCrossAxis = normalize(cross(vec3(0.0, 1.0, 0.0), u_WindDir)); + + // Level 1: Trunk bending (quadratic height response, length-preserving) + float trunkAngle = (trunkW * trunkW) * effectiveWind * 0.12 * sin(u_Time * 1.2 + gustSpatial); + localPos = RotateAngleAxis(localPos, windCrossAxis, trunkAngle); + localNormal = RotateAngleAxis(localNormal, windCrossAxis, trunkAngle); + + // Level 2: Branch sway + if (branchW > 0.01) { + float branchOsc = sin(u_Time * 2.5 + phase * 6.28 + gustSpatial * 2.0); + float branchAngle = branchW * effectiveWind * 0.15 * branchOsc; + localPos = RotateAngleAxis(localPos, windCrossAxis, branchAngle); + localNormal = RotateAngleAxis(localNormal, windCrossAxis, branchAngle); + } + + // Level 3: Leaf flutter and tumble around leaf pivot (Leaf Shimmering!) + if (leafW > 0.01) { + float leafOsc = sin(u_Time * 8.0 + phase * 15.0 + dot(localPos, vec3(1.0))); + float leafAngle = leafW * (0.2 + 0.2 * gust) * leafOsc; + + vec3 leafRel = in_LeafPivotOffset; + vec3 rotatedOffset = RotateAngleAxis(leafRel, u_WindDir, leafAngle); + localPos += (rotatedOffset - leafRel); + localNormal = RotateAngleAxis(localNormal, u_WindDir, leafAngle); + } + + vec3 worldPos = (u_ModelMatrix * vec4(localPos, 1.0)).xyz; + vec3 worldNormal = normalize((u_ModelMatrix * vec4(localNormal, 0.0)).xyz); + + // Spherical / Canopy Normal Blending (removes paper-thin leaf look) + vec3 crownCenter = u_TreeOrigin + vec3(0.0, u_TreeHeight * 0.65, 0.0); + vec3 sphericalNormal = normalize(worldPos - crownCenter); + worldNormal = normalize(mix(worldNormal, sphericalNormal, leafW * 0.65)); + + // Canopy interior AO + float distToCenter = length(worldPos - crownCenter); + v_CanopyAO = clamp(distToCenter / (u_TreeHeight * 0.45), 0.35, 1.0); + + v_WorldPos = worldPos; + v_WorldNormal = worldNormal; + v_TexCoord = in_TexCoord; + + gl_Position = u_ViewProj * vec4(worldPos, 1.0); +} +)glsl"; +} + +inline const char* GetFoliageFragmentShaderGLSL() { + return R"glsl( +#version 450 core + +layout(location = 0) in vec3 v_WorldPos; +layout(location = 1) in vec3 v_WorldNormal; +layout(location = 2) in vec2 v_TexCoord; +layout(location = 3) in float v_CanopyAO; + +layout(binding = 0) uniform sampler2D u_DiffuseAtlas; + +layout(std140, binding = 2) uniform LightBlock { + vec3 u_SunDir; + vec3 u_SunColor; + vec3 u_AmbientSky; + vec3 u_CameraPos; +}; + +layout(location = 0) out vec4 out_Color; + +void main() { + vec4 texColor = texture(u_DiffuseAtlas, v_TexCoord); + + // Alpha Cutoff + if (texColor.a < 0.45) { + discard; + } + + vec3 N = normalize(v_WorldNormal); + vec3 L = normalize(u_SunDir); + vec3 V = normalize(u_CameraPos - v_WorldPos); + vec3 H = normalize(L + V); + + // Wrap Lighting (Half-Lambert) + float NdotL = dot(N, L); + float wrapNdotL = max(0.0, (NdotL + 0.35) / 1.35); + vec3 diffuse = texColor.rgb * u_SunColor * wrapNdotL; + + // Subsurface Transmission (Sunlight penetrating leaf) + float viewThrough = max(0.0, dot(-L, V)); + float transIntensity = pow(viewThrough, 3.5) * 0.85; + vec3 transColor = texColor.rgb * vec3(1.1, 1.3, 0.7) * u_SunColor * transIntensity; + + // Specular Highlight + float NdotH = max(0.0, dot(N, H)); + float specular = pow(NdotH, 32.0) * 0.25; + + // Canopy AO & Ambient + vec3 ambient = u_AmbientSky * texColor.rgb * v_CanopyAO; + + vec3 finalRGB = (diffuse + transColor + specular) * v_CanopyAO + ambient; + out_Color = vec4(finalRGB, 1.0); +} +)glsl"; +} + +} // namespace speedtree diff --git a/speedtree/include/speedtree/speedtree.h b/speedtree/include/speedtree/speedtree.h new file mode 100644 index 0000000..842a791 --- /dev/null +++ b/speedtree/include/speedtree/speedtree.h @@ -0,0 +1,181 @@ +#pragma once + +#include +#include +#include +#include +#include + +namespace speedtree { + +constexpr float kPI = 3.14159265358979323846f; +constexpr float kTAU = 2.0f * kPI; + +struct UVRect { + float u0 = 0.0f; + float v0 = 0.0f; + float u1 = 1.0f; + float v1 = 1.0f; +}; + +// Unified vertex layout for modern GPU foliage rendering +// Compatible with Vulkan, Metal, DX11/12, OpenGL +struct SpeedTreeVertex { + float position[3]; // Local space (Z-forward / Y-up) + float normal[3]; // Blended spherical / canopy normal + float uv[2]; // Texture atlas coordinates + float wind_weights[4]; // [0]: Trunk bend, [1]: Branch sway, [2]: Leaf flutter, [3]: Phase + float leaf_pivot_offset[3]; // Vector from leaf cluster pivot to vertex (for rotation/tumble) + uint32_t diffuse; // RGBA8 (Canopy AO in alpha/rgb, default 0xFFFFFFFF) +}; + +// Represents a submesh (Trunk or Leaf/Canopy) +struct SpeedTreeMesh { + std::string name; + std::vector vertices; + std::vector indices; + std::string texture; + bool is_leaf = false; + bool is_double_sided = false; + bool alpha_test = false; + float alpha_ref = 0.45f; +}; + +struct SpeedTreeSptInfo { + bool ok = false; + float size = 1000.0f; + float variance = 0.0f; + std::string bark_texture; + std::string leaf_texture; + std::string shadow_texture; + std::vector leaf_uvs; + std::vector frond_uvs; + std::vector billboard_uvs; + + static bool SniffFile(const std::string& filepath, SpeedTreeSptInfo& out); + static bool SniffMemory(const uint8_t* data, size_t size, SpeedTreeSptInfo& out); + static bool SniffSpt(const std::string& filepath, SpeedTreeSptInfo& out) { return SniffFile(filepath, out); } +}; + +struct SpeedTreeProperty { + uint32_t crc = 0; + std::string property_name; + std::string tree_file; + float tree_size = 1000.0f; + float tree_variance = 0.0f; + + static bool LoadFromFile(const std::string& filename, SpeedTreeProperty& out); +}; + +// Wind configuration and evaluation parameters +struct WindParameters { + float time = 0.0f; + float strength = 1.0f; // 0.0: calm, 1.0: gentle breeze, 2.5: storm + float direction[3] = {1.0f, 0.0f, 0.0f}; // Normalized wind direction + float gust_frequency = 0.8f; + float gust_strength = 0.5f; +}; + +// Core Model class representing a unique species/variant of tree +class SpeedTreeModel { +public: + SpeedTreeModel(); + ~SpeedTreeModel() = default; + + static std::shared_ptr Create(const std::string& sptPath, float treeSize = 1000.0f) { return CreateFromSpt(sptPath, treeSize); } + static std::shared_ptr CreateFromSpt(const std::string& sptPath, float treeSize = 1000.0f); + static std::shared_ptr CreateFromMemory(const uint8_t* data, size_t size, + const std::string& name = "", float treeSize = 1000.0f); + static std::shared_ptr CreateProcedural(const std::string& species_name, float height = 1000.0f, + const std::string& bark_tex = "", + const std::string& leaf_tex = ""); + + const SpeedTreeMesh& GetTrunkMesh() const { return m_trunk; } + const SpeedTreeMesh& GetLeafMesh() const { return m_leaf; } + + float GetHeight() const { return m_height; } + float GetRadius() const { return m_radius; } + bool IsGrassOrShrub() const { return m_is_grass_or_shrub; } + const std::string& GetName() const { return m_name; } + const std::string& GetBarkTexture() const { return m_bark_texture; } + const std::string& GetLeafTexture() const { return m_leaf_texture; } + const SpeedTreeSptInfo& GetSptInfo() const { return m_info; } + + // CPU fallback vertex deformer for legacy clients/renderers without custom foliage vertex shaders + void EvaluateCpuTransformedVertices(const SpeedTreeMesh& src_mesh, + std::vector& out_positions, + std::vector& out_normals, + float worldX, float worldY, float worldZ, + float yawDeg, float scale, + const WindParameters& wind) const; + +private: + void BuildGeometry(const SpeedTreeSptInfo& info); + void BuildTreeGeometry(float H, const SpeedTreeSptInfo& info); + void BuildGrassShrubGeometry(float H, const SpeedTreeSptInfo& info); + + std::string m_name; + std::string m_spt_path; + float m_height = 1000.0f; + float m_radius = 350.0f; + bool m_is_grass_or_shrub = false; + + std::string m_bark_texture; + std::string m_leaf_texture; + SpeedTreeSptInfo m_info; + + SpeedTreeMesh m_trunk; + SpeedTreeMesh m_leaf; +}; + +// Forest management and batched instance tracking +class SpeedTreeForest { +public: + struct Instance { + float x = 0.0f; + float y = 0.0f; + float z = 0.0f; + uint32_t crc = 0; + float yaw = 0.0f; + float scale = 1.0f; + std::string name; + std::shared_ptr model; + }; + + SpeedTreeForest(); + ~SpeedTreeForest(); + + void Clear(); + void ClearMainTree(); + + bool RegisterProperty(uint32_t crc, const std::string& prtPath); + bool RegisterPropertyData(const SpeedTreeProperty& prop); + void ScanPropertyDirectory(const std::string& dirPath); + + Instance* CreateInstance(float x, float y, float z, uint32_t crc, + float yaw = 0.0f, float scale = 1.0f, const char* name = nullptr); + void DeleteInstance(Instance* pTree); + + void Update(float dt); + + size_t GetInstanceCount() const { return m_instances.size(); } + size_t GetMainTreeCount() const { return m_tree_templates.size(); } + const std::vector>& GetInstances() const { return m_instances; } + + std::shared_ptr GetMainTree(uint32_t crc); + bool HasMainTree(uint32_t crc) const; + + void SetWindStrength(float strength) { m_wind.strength = strength; } + float GetWindStrength() const { return m_wind.strength; } + + void SetWindDirection(float x, float y, float z); + const WindParameters& GetWindParams() const { return m_wind; } + +private: + WindParameters m_wind; + std::map m_properties; + std::map> m_tree_templates; + std::vector> m_instances; +}; + +} // namespace speedtree diff --git a/speedtree/src/forest.cpp b/speedtree/src/forest.cpp new file mode 100644 index 0000000..327e8b3 --- /dev/null +++ b/speedtree/src/forest.cpp @@ -0,0 +1,123 @@ +#include "speedtree/speedtree.h" +#include +#include +#include + +namespace speedtree { + +SpeedTreeForest::SpeedTreeForest() { + m_wind.time = 0.0f; + m_wind.strength = 1.0f; + m_wind.direction[0] = 0.8f; + m_wind.direction[1] = 0.0f; + m_wind.direction[2] = 0.6f; +} + +SpeedTreeForest::~SpeedTreeForest() { + Clear(); +} + +void SpeedTreeForest::Clear() { + m_instances.clear(); +} + +void SpeedTreeForest::ClearMainTree() { + m_instances.clear(); + m_tree_templates.clear(); + m_properties.clear(); +} + +void SpeedTreeForest::SetWindDirection(float x, float y, float z) { + float len = std::sqrt(x * x + y * y + z * z); + if (len > 1e-5f) { + m_wind.direction[0] = x / len; + m_wind.direction[1] = y / len; + m_wind.direction[2] = z / len; + } +} + +bool SpeedTreeForest::RegisterProperty(uint32_t crc, const std::string& prtPath) { + SpeedTreeProperty prop; + if (!SpeedTreeProperty::LoadFromFile(prtPath, prop)) { + return false; + } + if (crc != 0) prop.crc = crc; + return RegisterPropertyData(prop); +} + +bool SpeedTreeForest::RegisterPropertyData(const SpeedTreeProperty& prop) { + if (prop.crc == 0) return false; + m_properties[prop.crc] = prop; + auto model = SpeedTreeModel::CreateFromSpt(prop.tree_file, prop.tree_size); + m_tree_templates[prop.crc] = model; + return true; +} + +void SpeedTreeForest::ScanPropertyDirectory(const std::string& dirPath) { + if (!std::filesystem::exists(dirPath)) return; + for (const auto& entry : std::filesystem::recursive_directory_iterator(dirPath)) { + if (!entry.is_regular_file()) continue; + auto path = entry.path().string(); + if (path.size() >= 4 && path.substr(path.size() - 4) == ".prt") { + SpeedTreeProperty prop; + if (SpeedTreeProperty::LoadFromFile(path, prop)) { + // Compute hash for crc + uint32_t hash = 5381; + for (char c : prop.tree_file) hash = ((hash << 5) + hash) + static_cast(c); + prop.crc = hash; + RegisterPropertyData(prop); + } + } + } +} + +SpeedTreeForest::Instance* SpeedTreeForest::CreateInstance(float x, float y, float z, uint32_t crc, + float yaw, float scale, const char* name) { + auto model = GetMainTree(crc); + if (!model) { + // Fallback procedural model + model = SpeedTreeModel::CreateProcedural(name ? name : "tree", 1000.0f); + m_tree_templates[crc] = model; + } + + auto inst = std::make_unique(); + inst->x = x; + inst->y = y; + inst->z = z; + inst->crc = crc; + inst->yaw = yaw; + inst->scale = (scale > 0.01f) ? scale : 1.0f; + inst->name = name ? name : model->GetName(); + inst->model = model; + + Instance* ptr = inst.get(); + m_instances.push_back(std::move(inst)); + return ptr; +} + +void SpeedTreeForest::DeleteInstance(Instance* pTree) { + auto it = std::remove_if(m_instances.begin(), m_instances.end(), + [pTree](const std::unique_ptr& inst) { + return inst.get() == pTree; + }); + m_instances.erase(it, m_instances.end()); +} + +void SpeedTreeForest::Update(float dt) { + m_wind.time += dt; +} + +std::shared_ptr SpeedTreeModel_GetMainTree(std::map>& map, uint32_t crc) { + auto it = map.find(crc); + return (it != map.end()) ? it->second : nullptr; +} + +std::shared_ptr SpeedTreeForest::GetMainTree(uint32_t crc) { + return SpeedTreeModel_GetMainTree(m_tree_templates, crc); +} + +bool SpeedTreeForest::HasMainTree(uint32_t crc) const { + return m_tree_templates.find(crc) != m_tree_templates.end(); +} + +} // namespace speedtree diff --git a/speedtree/src/spt_parser.cpp b/speedtree/src/spt_parser.cpp new file mode 100644 index 0000000..5736131 --- /dev/null +++ b/speedtree/src/spt_parser.cpp @@ -0,0 +1,232 @@ +#include "speedtree/speedtree.h" +#include +#include +#include +#include +#include + +namespace speedtree { + +namespace { + +std::string ToLower(std::string s) { + std::transform(s.begin(), s.end(), s.begin(), [](unsigned char c) { + return static_cast(std::tolower(c)); + }); + return s; +} + +std::string BaseName(std::string p) { + for (char& c : p) if (c == '\\') c = '/'; + size_t s = p.find_last_of('/'); + return (s == std::string::npos) ? p : p.substr(s + 1); +} + +std::string StripQuotes(const std::string& s) { + size_t start = s.find_first_not_of(" \t\r\n\""); + if (start == std::string::npos) return ""; + size_t end = s.find_last_not_of(" \t\r\n\""); + return s.substr(start, end - start + 1); +} + +bool EndsWithCI(const std::string& s, const char* suf) { + size_t n = std::strlen(suf); + if (s.size() < n) return false; + for (size_t i = 0; i < n; ++i) { + if (std::tolower((unsigned char)s[s.size() - n + i]) != std::tolower((unsigned char)suf[i])) + return false; + } + return true; +} + +std::string AsDds(std::string s) { + if (s.empty()) return s; + size_t dot = s.find_last_of('.'); + if (dot != std::string::npos) s.resize(dot); + return s + ".dds"; +} + +std::string ResolvePath(const std::string& raw) { + if (raw.empty()) return raw; + std::string clean = raw; + for (char& c : clean) { + if (c == '\\') c = '/'; + } + if (clean.size() > 2 && clean[1] == ':') { + clean = clean.substr(2); + while (!clean.empty() && clean[0] == '/') clean = clean.substr(1); + } + std::vector roots = { + "", + "build/dev/", + "build/dev/ymir work/", + "/Users/shen/Work/Code/Metin2/AVA2/1. Client DEV/pack_maker/", + "/Users/shen/Work/Code/Metin2/AVA2/1. Client DEV/pack_maker/property/", + "/Users/shen/Work/Code/Metin2/ava2-client/" + }; + for (const auto& r : roots) { + std::string cand = r + clean; + std::ifstream f(cand, std::ios::binary); + if (f.good()) return cand; + } + return clean; +} +} // namespace + +bool SpeedTreeProperty::LoadFromFile(const std::string& filename, SpeedTreeProperty& out) { + std::string resolved = ResolvePath(filename); + std::ifstream f(resolved); + if (!f.is_open()) return false; + std::string line; + bool has_yprt = false; + while (std::getline(f, line)) { + std::istringstream iss(line); + std::string key; + if (!(iss >> key)) continue; + if (key == "YPRT" || key == "yprt") { + has_yprt = true; + uint32_t val = 0; + if (iss >> val) { + out.crc = val; + } else if (f >> out.crc) { + std::string rem; + std::getline(f, rem); + } + } else if (key == "propertyname" || key == "PropertyName") { + std::string rem; + std::getline(iss, rem); + out.property_name = StripQuotes(rem); + } else if (key == "propertytype") { + // "Tree" + } else if (key == "TreeFile" || key == "treefile" || key == "TreeName") { + std::string val; + std::getline(iss, val); + out.tree_file = StripQuotes(val); + } else if (key == "TreeSize" || key == "treesize") { + std::string rem; + std::getline(iss, rem); + try { out.tree_size = std::stof(StripQuotes(rem)); } catch (...) {} + } else if (key == "TreeVariance" || key == "treevariance") { + std::string rem; + std::getline(iss, rem); + try { out.tree_variance = std::stof(StripQuotes(rem)); } catch (...) {} + } + } + return !out.tree_file.empty() && (!has_yprt || out.crc != 0); +} + +bool SpeedTreeSptInfo::SniffFile(const std::string& filepath, SpeedTreeSptInfo& out) { + std::string resolved = ResolvePath(filepath); + std::ifstream f(resolved, std::ios::binary); + if (!f.is_open()) return false; + f.seekg(0, std::ios::end); + size_t size = static_cast(f.tellg()); + f.seekg(0, std::ios::beg); + if (size < 16) return false; + + std::vector data(size); + f.read(reinterpret_cast(data.data()), size); + return SniffMemory(data.data(), size, out); +} + +bool SpeedTreeSptInfo::SniffMemory(const uint8_t* p, size_t n, SpeedTreeSptInfo& out) { + if (!p || n < 16) return false; + out.ok = true; + out.size = 1000.0f; + out.variance = 0.0f; + out.bark_texture.clear(); + out.leaf_texture.clear(); + out.shadow_texture.clear(); + out.leaf_uvs.clear(); + out.frond_uvs.clear(); + out.billboard_uvs.clear(); + + auto i32_at = [p, n](size_t o) -> int32_t { + if (o + 4 > n) return 0; + int32_t val = 0; + std::memcpy(&val, p + o, 4); + return val; + }; + + // Parse tokens + for (size_t o = 0; o + 8 <= n; ++o) { + int32_t token = i32_at(o); + if (token == 2000) { + // Branch texture name + int32_t len = i32_at(o + 4); + if (len > 0 && len < 256 && o + 8 + len <= n) { + std::string s(reinterpret_cast(p + o + 8), len); + out.bark_texture = BaseName(s); + } + } else if (token == 2001) { + float sz = 0.0f; + std::memcpy(&sz, p + o + 4, 4); + if (sz > 1.0f && sz < 50000.0f) out.size = sz; + } else if (token == 2002) { + float var = 0.0f; + std::memcpy(&var, p + o + 4, 4); + out.variance = var; + } else if (token == 10000 && i32_at(o + 4) == 10002) { + size_t c = o + 4; + for (int32_t section : {10002, 10003, 10004}) { + if (c + 8 > n || i32_at(c) != section) break; + int32_t count = i32_at(c + 4); + c += 8; + if (count <= 0 || count > 64 || c + count * 32 > n) break; + auto& target = (section == 10002) ? out.leaf_uvs : (section == 10003 ? out.frond_uvs : out.billboard_uvs); + for (int32_t i = 0; i < count; ++i, c += 32) { + float f[8]; + std::memcpy(f, p + c, sizeof(f)); + target.push_back({f[2], 1.0f - f[1], f[0], 1.0f - f[5]}); + } + } + } + } + + // String scan fallback for bark & composite maps + std::string cur; + std::vector str_refs; + for (size_t i = 0; i < n; ++i) { + unsigned char c = p[i]; + if (c >= 0x20 && c < 0x7F) { + cur += static_cast(c); + } else { + if (cur.size() >= 4 && (EndsWithCI(cur, ".tga") || EndsWithCI(cur, ".dds"))) { + str_refs.push_back(BaseName(cur)); + } + cur.clear(); + } + } + + for (const auto& r : str_refs) { + std::string low = ToLower(r); + if (out.bark_texture.empty() && low.find("bark") != std::string::npos) { + out.bark_texture = AsDds(r); + } else if (out.leaf_texture.empty() && (low.find("leaf") != std::string::npos || low.find("leaves") != std::string::npos || low.find("grass") != std::string::npos)) { + out.leaf_texture = AsDds(r); + } + } + + std::string bytes(reinterpret_cast(p), n); + auto find_token = [&](const char* needle) -> std::string { + size_t pos = bytes.find(needle); + if (pos == std::string::npos) return ""; + size_t end = pos + std::strlen(needle); + while (end < bytes.size() && (std::isalnum((unsigned char)bytes[end]) || bytes[end] == '_' || bytes[end] == '-')) { + ++end; + } + return bytes.substr(pos, end - pos); + }; + + std::string comp = find_token("CompositeMap"); + if (!comp.empty()) out.leaf_texture = AsDds(comp); + std::string shadow = find_token("CompositeShadowMap"); + if (!shadow.empty()) out.shadow_texture = AsDds(shadow); + + if (out.bark_texture.empty()) out.bark_texture = "beechbark.dds"; + if (out.leaf_texture.empty()) out.leaf_texture = "compositemap.dds"; + + return true; +} + +} // namespace speedtree diff --git a/speedtree/src/tree_generator.cpp b/speedtree/src/tree_generator.cpp new file mode 100644 index 0000000..7667aa9 --- /dev/null +++ b/speedtree/src/tree_generator.cpp @@ -0,0 +1,461 @@ +#include "speedtree/speedtree.h" +#include +#include +#include +#include + +namespace speedtree { + +namespace { + +bool IsConifer(const std::string& name) { + std::string s = name; + std::transform(s.begin(), s.end(), s.begin(), [](unsigned char c) { return std::tolower(c); }); + return s.find("pine") != std::string::npos || s.find("cypress") != std::string::npos || + s.find("fir") != std::string::npos || s.find("spruce") != std::string::npos || + s.find("cedar") != std::string::npos || s.find("conifer") != std::string::npos || + s.find("tanne") != std::string::npos; +} + +inline void RotateY(float x, float z, float cos_a, float sin_a, float& out_x, float& out_z) { + out_x = x * cos_a + z * sin_a; + out_z = -x * sin_a + z * cos_a; +} + +inline void Normalize3(float v[3]) { + float len = std::sqrt(v[0] * v[0] + v[1] * v[1] + v[2] * v[2]); + if (len > 1e-6f) { + float inv = 1.0f / len; + v[0] *= inv; + v[1] *= inv; + v[2] *= inv; + } +} + +} // namespace + +SpeedTreeModel::SpeedTreeModel() { + m_trunk.name = "trunk"; + m_trunk.is_leaf = false; + m_trunk.is_double_sided = false; + m_trunk.alpha_test = false; + + m_leaf.name = "leaf"; + m_leaf.is_leaf = true; + m_leaf.is_double_sided = true; + m_leaf.alpha_test = true; + m_leaf.alpha_ref = 0.45f; +} + +std::shared_ptr SpeedTreeModel::CreateFromSpt(const std::string& sptPath, float treeSize) { + auto model = std::make_shared(); + model->m_spt_path = sptPath; + + // Extract base name + size_t last_slash = sptPath.find_last_of("/\\"); + model->m_name = (last_slash == std::string::npos) ? sptPath : sptPath.substr(last_slash + 1); + + SpeedTreeSptInfo info; + if (SpeedTreeSptInfo::SniffFile(sptPath, info)) { + if (info.size > 1.0f) model->m_height = info.size; + else model->m_height = treeSize; + model->BuildGeometry(info); + } else { + model->m_height = treeSize; + info.size = treeSize; + info.bark_texture = "beechbark.dds"; + info.leaf_texture = "compositemap.dds"; + model->BuildGeometry(info); + } + return model; +} + +std::shared_ptr SpeedTreeModel::CreateFromMemory(const uint8_t* data, size_t size, + const std::string& name, float treeSize) { + auto model = std::make_shared(); + model->m_name = name.empty() ? "tree" : name; + + SpeedTreeSptInfo info; + if (SpeedTreeSptInfo::SniffMemory(data, size, info)) { + if (info.size > 1.0f) model->m_height = info.size; + else model->m_height = treeSize; + model->BuildGeometry(info); + } else { + model->m_height = treeSize; + info.size = treeSize; + info.bark_texture = "beechbark.dds"; + info.leaf_texture = "compositemap.dds"; + model->BuildGeometry(info); + } + return model; +} + +std::shared_ptr SpeedTreeModel::CreateProcedural(const std::string& species_name, float height, + const std::string& bark_tex, const std::string& leaf_tex) { + auto model = std::make_shared(); + model->m_name = species_name; + model->m_height = height; + + SpeedTreeSptInfo info; + info.ok = true; + info.size = height; + info.bark_texture = bark_tex.empty() ? "beechbark.dds" : bark_tex; + info.leaf_texture = leaf_tex.empty() ? "compositemap.dds" : leaf_tex; + model->BuildGeometry(info); + return model; +} + +void SpeedTreeModel::BuildGeometry(const SpeedTreeSptInfo& info) { + m_info = info; + m_bark_texture = info.bark_texture; + m_leaf_texture = info.leaf_texture; + + std::string lowerName = m_name; + std::transform(lowerName.begin(), lowerName.end(), lowerName.begin(), [](unsigned char c) { return std::tolower(c); }); + m_is_grass_or_shrub = (lowerName.find("grass") != std::string::npos || + lowerName.find("shrub") != std::string::npos || + lowerName.find("bush") != std::string::npos || + lowerName.find("flower") != std::string::npos || + m_height < 150.0f); + + float H = m_height; + if (m_is_grass_or_shrub) { + BuildGrassShrubGeometry(H, info); + } else { + BuildTreeGeometry(H, info); + } +} + +void SpeedTreeModel::BuildGrassShrubGeometry(float H, const SpeedTreeSptInfo& info) { + m_trunk.vertices.clear(); + m_trunk.indices.clear(); + m_leaf.vertices.clear(); + m_leaf.indices.clear(); + + m_leaf.texture = m_leaf_texture; + float W = H * 0.85f; + float hW = W * 0.5f; + + UVRect uv{0.0f, 0.0f, 1.0f, 1.0f}; + if (!info.leaf_uvs.empty()) uv = info.leaf_uvs[0]; + + // 3 intersecting vertical planes (0, 60, 120 degrees star pattern) + float angles[] = {0.0f, kPI / 3.0f, 2.0f * kPI / 3.0f}; + for (int p = 0; p < 3; ++p) { + float a = angles[p]; + float dx = std::cos(a) * hW; + float dz = std::sin(a) * hW; + float nx = -std::sin(a); + float nz = std::cos(a); + + uint32_t base_idx = static_cast(m_leaf.vertices.size()); + + float corners[4][3] = { + {-dx, 0.0f, -dz}, + { dx, 0.0f, dz}, + { dx, H, dz}, + {-dx, H, -dz} + }; + + float uvs[4][2] = { + {uv.u0, uv.v1}, + {uv.u1, uv.v1}, + {uv.u1, uv.v0}, + {uv.u0, uv.v0} + }; + + for (int c = 0; c < 4; ++c) { + SpeedTreeVertex vert{}; + vert.position[0] = corners[c][0]; + vert.position[1] = corners[c][1]; + vert.position[2] = corners[c][2]; + + // Spherical up-tilted normal + vert.normal[0] = nx * 0.7f; + vert.normal[1] = 0.5f; + vert.normal[2] = nz * 0.7f; + Normalize3(vert.normal); + + vert.uv[0] = uvs[c][0]; + vert.uv[1] = uvs[c][1]; + + // Wind weights: grass bends with height^1.5 + float norm_h = corners[c][1] / (H > 0.0f ? H : 1.0f); + vert.wind_weights[0] = std::pow(norm_h, 1.5f); // Trunk bend + vert.wind_weights[1] = norm_h * 0.5f; // Branch sway + vert.wind_weights[2] = norm_h; // High-freq flutter + vert.wind_weights[3] = static_cast(p) * 0.33f; // Phase + + vert.leaf_pivot_offset[0] = corners[c][0]; + vert.leaf_pivot_offset[1] = 0.0f; + vert.leaf_pivot_offset[2] = corners[c][2]; + vert.diffuse = 0xFFFFFFFF; + + m_leaf.vertices.push_back(vert); + } + + m_leaf.indices.push_back(base_idx + 0); + m_leaf.indices.push_back(base_idx + 1); + m_leaf.indices.push_back(base_idx + 2); + m_leaf.indices.push_back(base_idx + 0); + m_leaf.indices.push_back(base_idx + 2); + m_leaf.indices.push_back(base_idx + 3); + } +} + +void SpeedTreeModel::BuildTreeGeometry(float H, const SpeedTreeSptInfo& info) { + bool conifer = IsConifer(m_name); + + m_trunk.vertices.clear(); + m_trunk.indices.clear(); + m_trunk.texture = m_bark_texture; + + m_leaf.vertices.clear(); + m_leaf.indices.clear(); + m_leaf.texture = m_leaf_texture; + + // 1. Build Trunk Cylindrical Tube + constexpr int SEGS = 8; + constexpr int LEVELS = 5; + float trunk_top = H * (conifer ? 0.90f : 0.72f); + float r_base = H * 0.040f; + float r_top = H * 0.012f; + + for (int l = 0; l <= LEVELS; ++l) { + float f = static_cast(l) / LEVELS; + float y = f * trunk_top; + float r = r_base * (1.0f - f) + r_top * f; + float v = f * 3.5f; + + for (int s = 0; s <= SEGS; ++s) { + float a = static_cast(s) / SEGS * kTAU; + float cos_a = std::cos(a); + float sin_a = std::sin(a); + + SpeedTreeVertex vert{}; + vert.position[0] = cos_a * r; + vert.position[1] = y; + vert.position[2] = sin_a * r; + + vert.normal[0] = cos_a; + vert.normal[1] = 0.05f; + vert.normal[2] = sin_a; + Normalize3(vert.normal); + + vert.uv[0] = static_cast(s) / SEGS; + vert.uv[1] = v; + + // Trunk bend weight is (y / H)^2 + float norm_y = y / H; + vert.wind_weights[0] = norm_y * norm_y; + vert.wind_weights[1] = 0.0f; + vert.wind_weights[2] = 0.0f; + vert.wind_weights[3] = 0.0f; + + vert.leaf_pivot_offset[0] = 0.0f; + vert.leaf_pivot_offset[1] = 0.0f; + vert.leaf_pivot_offset[2] = 0.0f; + vert.diffuse = 0xFFFFFFFF; + + m_trunk.vertices.push_back(vert); + } + } + + for (int l = 0; l < LEVELS; ++l) { + uint32_t row_a = l * (SEGS + 1); + uint32_t row_b = (l + 1) * (SEGS + 1); + for (int s = 0; s < SEGS; ++s) { + uint32_t i0 = row_a + s; + uint32_t i1 = row_b + s; + uint32_t i2 = row_b + s + 1; + uint32_t i3 = row_a + s + 1; + + m_trunk.indices.push_back(i0); + m_trunk.indices.push_back(i1); + m_trunk.indices.push_back(i2); + + m_trunk.indices.push_back(i0); + m_trunk.indices.push_back(i2); + m_trunk.indices.push_back(i3); + } + } + + // 2. Build Canopy Leaf Clusters + std::vector uv_pool = info.leaf_uvs; + if (uv_pool.empty()) uv_pool = info.frond_uvs; + if (uv_pool.empty()) uv_pool.push_back({0.0f, 0.0f, 1.0f, 1.0f}); + + int cluster_count = conifer ? 16 : 14; + float crown_center_y = H * (conifer ? 0.60f : 0.65f); + + for (int k = 0; k < cluster_count; ++k) { + float f = static_cast(k) / cluster_count; + float y = H * (conifer ? (0.25f + f * 0.68f) : (0.40f + f * 0.50f)); + float spread = H * (conifer ? (0.26f * (1.0f - f * 0.72f)) : (0.30f * std::sin(f * kPI))); + float angle = f * kTAU * 1.61803398875f; // Golden ratio spiral + + float cx = (k == cluster_count - 1) ? 0.0f : (std::cos(angle) * spread); + float cz = (k == cluster_count - 1) ? 0.0f : (std::sin(angle) * spread); + + float quad_w = H * (conifer ? 0.28f : 0.38f); + float quad_h = H * (conifer ? 0.24f : 0.32f); + float hw = quad_w * 0.5f; + float hh = quad_h * 0.5f; + + UVRect uv = uv_pool[k % uv_pool.size()]; + float cluster_phase = std::fmod(static_cast(k) * 0.237f + 0.1f, 1.0f); + + // 2 perpendicular planes per cluster (Cross-quad pattern) + for (int p = 0; p < 2; ++p) { + float pa = angle + p * (kPI * 0.5f); + float dx = std::cos(pa) * hw; + float dz = std::sin(pa) * hw; + + // Geometry face normal + float fnx = std::cos(pa + kPI * 0.5f); + float fnz = std::sin(pa + kPI * 0.5f); + + uint32_t bidx = static_cast(m_leaf.vertices.size()); + + float pts[4][3] = { + {cx - dx, y - hh, cz - dz}, + {cx + dx, y - hh, cz + dz}, + {cx + dx, y + hh, cz + dz}, + {cx - dx, y + hh, cz - dz} + }; + + float uvs[4][2] = { + {uv.u0, uv.v1}, + {uv.u1, uv.v1}, + {uv.u1, uv.v0}, + {uv.u0, uv.v0} + }; + + for (int i = 0; i < 4; ++i) { + SpeedTreeVertex vert{}; + vert.position[0] = pts[i][0]; + vert.position[1] = pts[i][1]; + vert.position[2] = pts[i][2]; + + // --- Spherical Canopy Normal Calculation --- + // Vector from tree crown center to this vertex + float scx = pts[i][0]; + float scy = pts[i][1] - crown_center_y; + float scz = pts[i][2]; + float s_norm[3] = {scx, scy, scz}; + Normalize3(s_norm); + + // Blend 65% spherical volume normal + 35% geometric quad normal + vert.normal[0] = s_norm[0] * 0.65f + fnx * 0.35f; + vert.normal[1] = s_norm[1] * 0.65f + 0.25f * 0.35f; + vert.normal[2] = s_norm[2] * 0.65f + fnz * 0.35f; + Normalize3(vert.normal); + + vert.uv[0] = uvs[i][0]; + vert.uv[1] = uvs[i][1]; + + // --- 4-Tier Wind Weights --- + float norm_y = pts[i][1] / H; + vert.wind_weights[0] = norm_y * norm_y; // Level 1: Trunk bend (H^2) + vert.wind_weights[1] = std::clamp(spread / (H * 0.3f), 0.0f, 1.0f); // Level 2: Branch sway + vert.wind_weights[2] = (i >= 2) ? 1.0f : 0.6f; // Level 3: Leaf flutter + vert.wind_weights[3] = cluster_phase; // Phase offset + + // Leaf Pivot Offset: Relative vector from cluster center to this vertex + vert.leaf_pivot_offset[0] = pts[i][0] - cx; + vert.leaf_pivot_offset[1] = pts[i][1] - y; + vert.leaf_pivot_offset[2] = pts[i][2] - cz; + + // Canopy contact AO: inner leaves darker + float dist_from_crown = std::sqrt(scx * scx + scy * scy + scz * scz); + float ao = std::clamp(dist_from_crown / (H * 0.35f), 0.4f, 1.0f); + uint8_t ao_byte = static_cast(ao * 255.0f); + vert.diffuse = (0xFF << 24) | (ao_byte << 16) | (ao_byte << 8) | ao_byte; + + m_leaf.vertices.push_back(vert); + } + + m_leaf.indices.push_back(bidx + 0); + m_leaf.indices.push_back(bidx + 1); + m_leaf.indices.push_back(bidx + 2); + m_leaf.indices.push_back(bidx + 0); + m_leaf.indices.push_back(bidx + 2); + m_leaf.indices.push_back(bidx + 3); + } + } +} + +void SpeedTreeModel::EvaluateCpuTransformedVertices(const SpeedTreeMesh& src_mesh, + std::vector& out_positions, + std::vector& out_normals, + float worldX, float worldY, float worldZ, + float yawDeg, float scale, + const WindParameters& wind) const { + size_t nverts = src_mesh.vertices.size(); + out_positions.resize(nverts * 3); + out_normals.resize(nverts * 3); + + float rad = yawDeg * (kPI / 180.0f); + float cos_y = std::cos(rad); + float sin_y = std::sin(rad); + + float gust_spatial = (worldX + worldZ) * 0.005f; + float gust = std::sin(wind.time * wind.gust_frequency + gust_spatial) * 0.5f + 0.5f; + float eff_wind = wind.strength * (0.8f + 0.4f * gust); + + for (size_t i = 0; i < nverts; ++i) { + const auto& v = src_mesh.vertices[i]; + + // 1. Scale + float lx = v.position[0] * scale; + float ly = v.position[1] * scale; + float lz = v.position[2] * scale; + + // 2. Leaf tumble around pivot (Level 3 wind) + if (src_mesh.is_leaf && v.wind_weights[2] > 0.01f) { + float leaf_osc = std::sin(wind.time * 8.0f + v.wind_weights[3] * 15.0f + lx + lz); + float leaf_angle = v.wind_weights[2] * 0.25f * leaf_osc * eff_wind; + float cos_l = std::cos(leaf_angle); + float sin_l = std::sin(leaf_angle); + + // Rotate pivot offset around wind axis + float rel_x = v.leaf_pivot_offset[0] * scale; + float rel_z = v.leaf_pivot_offset[2] * scale; + float rot_rel_x, rot_rel_z; + RotateY(rel_x, rel_z, cos_l, sin_l, rot_rel_x, rot_rel_z); + + lx += (rot_rel_x - rel_x); + lz += (rot_rel_z - rel_z); + } + + // 3. Trunk & Branch sway (Level 1 & 2 wind) + float trunk_flex = v.wind_weights[0] * 0.08f * eff_wind; + float branch_flex = v.wind_weights[1] * 0.05f * eff_wind; + float sway = std::sin(wind.time * 1.5f + gust_spatial) * trunk_flex + + std::cos(wind.time * 2.8f + v.wind_weights[3] * 6.28f) * branch_flex; + + lx += wind.direction[0] * sway * (m_height * scale); + lz += wind.direction[2] * sway * (m_height * scale); + + // 4. World Yaw Rotation + float rx, rz; + RotateY(lx, lz, cos_y, sin_y, rx, rz); + + out_positions[i * 3 + 0] = worldX + rx; + out_positions[i * 3 + 1] = worldY + ly; + out_positions[i * 3 + 2] = worldZ + rz; + + // Rotate normal + float nx = v.normal[0]; + float ny = v.normal[1]; + float nz = v.normal[2]; + float rnx, rnz; + RotateY(nx, nz, cos_y, sin_y, rnx, rnz); + + out_normals[i * 3 + 0] = rnx; + out_normals[i * 3 + 1] = ny; + out_normals[i * 3 + 2] = rnz; + } +} + +} // namespace speedtree diff --git a/speedtree/tests/speedtree_test.cpp b/speedtree/tests/speedtree_test.cpp new file mode 100644 index 0000000..28bcae3 --- /dev/null +++ b/speedtree/tests/speedtree_test.cpp @@ -0,0 +1,122 @@ +#include "speedtree/speedtree.h" +#include +#include +#include + +void TestProceduralTree() { + std::cout << "[Test] Procedural Tree Generation..." << std::endl; + auto model = speedtree::SpeedTreeModel::CreateProcedural("TestOak", 1200.0f, "bark.dds", "leaf.dds"); + assert(model != nullptr); + assert(model->GetHeight() == 1200.0f); + assert(model->GetBarkTexture() == "bark.dds"); + assert(model->GetLeafTexture() == "leaf.dds"); + + const auto& trunk = model->GetTrunkMesh(); + assert(!trunk.vertices.empty()); + assert(!trunk.indices.empty()); + assert(trunk.indices.size() % 3 == 0); + + const auto& leaf = model->GetLeafMesh(); + assert(!leaf.vertices.empty()); + assert(!leaf.indices.empty()); + assert(leaf.indices.size() % 6 == 0); // Quads = 2 triangles + + std::cout << " Trunk vertices: " << trunk.vertices.size() + << ", indices: " << trunk.indices.size() << std::endl; + std::cout << " Leaf vertices: " << leaf.vertices.size() + << ", indices: " << leaf.indices.size() << std::endl; + + // Verify Spherical Normals and Leaf Pivot Offsets + for (size_t i = 0; i < leaf.vertices.size(); ++i) { + const auto& v = leaf.vertices[i]; + // Normal must be normalized + float len = std::sqrt(v.normal[0]*v.normal[0] + v.normal[1]*v.normal[1] + v.normal[2]*v.normal[2]); + assert(std::fabs(len - 1.0f) < 0.05f); + + // Wind weights must be valid [0, 1] + assert(v.wind_weights[0] >= 0.0f && v.wind_weights[0] <= 1.5f); + assert(v.wind_weights[1] >= 0.0f && v.wind_weights[1] <= 1.5f); + assert(v.wind_weights[2] >= 0.0f && v.wind_weights[2] <= 1.5f); + assert(v.wind_weights[3] >= 0.0f && v.wind_weights[3] <= 1.0f); + + // Leaf pivot offset must be bounded by quad size + float pivot_dist = std::sqrt(v.leaf_pivot_offset[0]*v.leaf_pivot_offset[0] + + v.leaf_pivot_offset[1]*v.leaf_pivot_offset[1] + + v.leaf_pivot_offset[2]*v.leaf_pivot_offset[2]); + assert(pivot_dist < 1200.0f * 0.5f); + } + std::cout << " [PASS] Procedural Tree verified!" << std::endl; +} + +void TestSptTokenSniffing() { + std::cout << "[Test] SPT Binary Token Sniffer..." << std::endl; + // Build synthetic .spt token stream + std::vector buffer; + auto push_i32 = [&](int32_t val) { + uint8_t b[4]; + std::memcpy(b, &val, 4); + buffer.insert(buffer.end(), b, b + 4); + }; + auto push_f32 = [&](float val) { + uint8_t b[4]; + std::memcpy(b, &val, 4); + buffer.insert(buffer.end(), b, b + 4); + }; + + // Token 2000: bark name "custom_bark.dds" + std::string bark_str = "custom_bark.dds"; + push_i32(2000); + push_i32(static_cast(bark_str.size())); + buffer.insert(buffer.end(), bark_str.begin(), bark_str.end()); + + // Token 2001: size 850.0f + push_i32(2001); + push_f32(850.0f); + + // Token 2002: variance 50.0f + push_i32(2002); + push_f32(50.0f); + + speedtree::SpeedTreeSptInfo info; + bool ok = speedtree::SpeedTreeSptInfo::SniffMemory(buffer.data(), buffer.size(), info); + assert(ok); + assert(info.bark_texture == "custom_bark.dds"); + assert(info.size == 850.0f); + assert(info.variance == 50.0f); + + std::cout << " [PASS] SPT Sniff verified!" << std::endl; +} + +void TestForestManagement() { + std::cout << "[Test] SpeedTree Forest Management..." << std::endl; + speedtree::SpeedTreeForest forest; + assert(forest.GetInstanceCount() == 0); + + forest.RegisterPropertyData(speedtree::SpeedTreeProperty{1, "Pine", "pine.spt", 1000.0f, 0.0f}); + assert(forest.HasMainTree(1)); + + auto* inst1 = forest.CreateInstance(100.0f, 0.0f, 200.0f, 1, 45.0f, 1.2f, "ForestPine1"); + auto* inst2 = forest.CreateInstance(300.0f, 0.0f, 400.0f, 1, 90.0f, 0.9f, "ForestPine2"); + assert(inst1 != nullptr && inst2 != nullptr); + assert(forest.GetInstanceCount() == 2); + + forest.Update(0.016f); + assert(forest.GetWindParams().time > 0.01f); + + forest.DeleteInstance(inst1); + assert(forest.GetInstanceCount() == 1); + + forest.Clear(); + assert(forest.GetInstanceCount() == 0); + + std::cout << " [PASS] Forest Management verified!" << std::endl; +} + +int main() { + std::cout << "=== Running SpeedTree SDK Unit Tests ===" << std::endl; + TestProceduralTree(); + TestSptTokenSniffing(); + TestForestManagement(); + std::cout << "=== All SpeedTree SDK Tests Passed! ===" << std::endl; + return 0; +} diff --git a/terrain/CMakeLists.txt b/terrain/CMakeLists.txt new file mode 100644 index 0000000..b65fdc4 --- /dev/null +++ b/terrain/CMakeLists.txt @@ -0,0 +1,24 @@ +cmake_minimum_required(VERSION 3.20) +project(terrain LANGUAGES CXX) + +set(CMAKE_CXX_STANDARD 20) +set(CMAKE_CXX_STANDARD_REQUIRED ON) + +add_library(terrain STATIC + src/heightmap.cpp + src/water.cpp +) + +target_include_directories(terrain PUBLIC + $ + $ +) + +add_library(terrain::terrain ALIAS terrain) + +option(TERRAIN_BUILD_TESTS "Build terrain SDK tests" ON) +if(TERRAIN_BUILD_TESTS) + add_executable(terrain_test tests/terrain_test.cpp) + target_link_libraries(terrain_test PRIVATE terrain) + add_test(NAME terrain_test COMMAND terrain_test) +endif() diff --git a/terrain/include/terrain/heightmap.h b/terrain/include/terrain/heightmap.h new file mode 100644 index 0000000..85b9a23 --- /dev/null +++ b/terrain/include/terrain/heightmap.h @@ -0,0 +1,125 @@ +#pragma once + +#include "types.h" +#include +#include +#include +#include +#include + +namespace metin2::terrain { + +class TerrainHeightmap { +public: + static constexpr int RAW_XSIZE = 131; + static constexpr int RAW_YSIZE = 131; + static constexpr int MAP_XSIZE = 128; + static constexpr int MAP_YSIZE = 128; + static constexpr int TILEMAP_RAW_XSIZE = 258; + static constexpr int TILEMAP_RAW_YSIZE = 258; + static constexpr int ATTRMAP_XSIZE = 256; + static constexpr int ATTRMAP_YSIZE = 256; + static constexpr int PATCH_SIZE = 16; + static constexpr int PATCH_COUNT = MAP_XSIZE / PATCH_SIZE; // 8x8 = 64 + static constexpr float DEFAULT_CELL_SCALE = 200.0f; + static constexpr float DEFAULT_HEIGHT_SCALE = 0.5f; + + TerrainHeightmap(); + ~TerrainHeightmap() = default; + + // Load from Metin2 height.raw file (131x131 uint16_t, 34322 bytes) or memory buffer + bool LoadRaw(const std::string& raw_path, float height_scale = DEFAULT_HEIGHT_SCALE, float cell_scale = DEFAULT_CELL_SCALE); + bool LoadFromBuffer(const uint16_t* raw_data, size_t count, float height_scale = DEFAULT_HEIGHT_SCALE, float cell_scale = DEFAULT_CELL_SCALE); + + // Load from Metin2 tile.raw file (258x258 uint8_t, 66564 bytes) or memory buffer + bool LoadTileRaw(const std::string& tile_path); + bool LoadTileFromBuffer(const uint8_t* tile_data, size_t count); + + // Load from Metin2 attr.atr file (65542 bytes = 6 bytes header + 256*256 bytes) or raw 65536 bytes + bool LoadAttr(const std::string& attr_path); + bool LoadAttrFromBuffer(const uint8_t* attr_data, size_t count); + + // Load TextureSet file (e.g. textureset/metin2_map1.txt) + bool LoadTextureSet(const std::string& textureset_path); + bool LoadTextureSetFromString(const std::string& content); + + // Procedural terrain generation for testing & headless environments + void GenerateProcedural(int width = 64, int height = 64, float cell_scale = 100.0f, float hill_amplitude = 80.0f); + + // Query height at continuous world coordinates (bilinear interpolation) + float GetHeightAtWorld(float world_x, float world_z) const; + float GetHeightAtGrid(int x, int y) const; + + // Query normal at continuous world coordinates (normalized, Y-up) + void GetNormalAtWorld(float world_x, float world_z, float out_normal[3]) const; + + // Query tile type at grid or world coordinates + uint8_t GetTileAtGrid(int x, int y) const; + uint8_t GetTileAtWorld(float world_x, float world_z) const; + std::string GetTexturePathForTile(uint8_t tile_id) const; + + // Query attribute flag (ATTR_BLOCK, ATTR_WATER, ATTR_BANPK, ATTR_OBJECT) + bool HasAttrMap() const { return !m_attr.empty(); } + uint8_t GetAttrAtGrid(int x, int y) const; + uint8_t GetAttrAtWorld(float world_x, float world_z) const; + bool IsAttrOn(float world_x, float world_z, uint8_t flag) const; + + // CTerrain block placement world origin + void SetWorldOrigin(float min_x, float min_z); + float GetWorldMinX() const { return m_world_min_x; } + float GetWorldMaxX() const { return m_world_max_x; } + float GetWorldMinZ() const { return m_world_min_z; } + float GetWorldMaxZ() const { return m_world_max_z; } + float GetMinHeight() const { return m_min_height; } + float GetMaxHeight() const { return m_max_height; } + int GetWidth() const { return m_width; } + int GetHeight() const { return m_height; } + + // Build unified 3D draw command without host graphic API bindings + TerrainDrawCommand BuildDrawCommand(const float world[16] = nullptr, int step = 1) const; + + // Quadtree frustum culling query + std::vector BuildCulledDraws(const float view[16], const float proj[16], float max_distance = 15000.0f) const; + + // Direct access to patches & quadtree + const std::vector& GetPatches() const { return m_patches; } + const TerrainQuadNode* GetQuadtreeRoot() const { return m_quadtreeRoot.get(); } + +private: + void UpdateBounds(); + void CalculateNormals(); + void BuildPatchesAndQuadtree(); + std::unique_ptr BuildQuadtreeNode(float min_x, float max_x, float min_z, float max_z, int depth); + void QueryQuadtree(const TerrainQuadNode* node, const float planes[6][4], const float eye[3], float max_distance, std::vector& out_visible_patches) const; + + int m_width = 0; + int m_height = 0; + float m_cell_scale = DEFAULT_CELL_SCALE; + float m_height_scale = DEFAULT_HEIGHT_SCALE; + float m_world_min_x = 0.0f; + float m_world_max_x = 0.0f; + float m_world_min_z = 0.0f; + float m_world_max_z = 0.0f; + float m_min_height = 0.0f; + float m_max_height = 0.0f; + bool m_has_origin = false; + float m_origin_x = 0.0f; + float m_origin_z = 0.0f; + + std::vector m_heights; + std::vector m_normals; // 3 floats per vertex + + int m_tile_width = 0; + int m_tile_height = 0; + std::vector m_tiles; + std::unordered_map m_textureSet; + + int m_attr_width = 0; + int m_attr_height = 0; + std::vector m_attr; + + std::vector m_patches; + std::unique_ptr m_quadtreeRoot; +}; + +} // namespace metin2::terrain diff --git a/terrain/include/terrain/terrain.h b/terrain/include/terrain/terrain.h new file mode 100644 index 0000000..2672265 --- /dev/null +++ b/terrain/include/terrain/terrain.h @@ -0,0 +1,5 @@ +#pragma once + +#include "types.h" +#include "heightmap.h" +#include "water.h" diff --git a/terrain/include/terrain/types.h b/terrain/include/terrain/types.h new file mode 100644 index 0000000..ecb84aa --- /dev/null +++ b/terrain/include/terrain/types.h @@ -0,0 +1,47 @@ +#pragma once + +#include +#include +#include +#include + +namespace metin2::terrain { + +// Metin2 collision and map attribute flags (aligned with CTerrainImpl) +enum TerrainAttr : uint8_t { + ATTR_NONE = 0, + ATTR_BLOCK = (1 << 0), // Movement collision blocking (cannot walk) + ATTR_WATER = (1 << 1), // Water surface / swimming + ATTR_BANPK = (1 << 2), // Safe zone / peace zone (PvP disabled) + ATTR_OBJECT = (1 << 3), // Occupied by static world object +}; + +struct TerrainPatch { + int patch_x = 0; // 0..7 + int patch_y = 0; // 0..7 + float aabb_min[3] = {0.0f, 0.0f, 0.0f}; + float aabb_max[3] = {0.0f, 0.0f, 0.0f}; + uint8_t dominant_tile = 0; +}; + +struct TerrainQuadNode { + float aabb_min[3] = {0.0f, 0.0f, 0.0f}; + float aabb_max[3] = {0.0f, 0.0f, 0.0f}; + int depth = 0; + int patch_idx = -1; // -1 if internal, >=0 if leaf (0..63) + std::unique_ptr children[4]; +}; + +struct TerrainDrawCommand { + std::vector positions; // x, y, z + std::vector normals; // nx, ny, nz + std::vector uv0; // u, v + std::vector diffuse;// RGBA8888 packed + std::vector indices;// 3 indices per triangle + uint8_t dominant_tile = 0; + std::string texture_path; + float aabb_min[3] = {0.0f, 0.0f, 0.0f}; + float aabb_max[3] = {0.0f, 0.0f, 0.0f}; +}; + +} // namespace metin2::terrain diff --git a/terrain/include/terrain/water.h b/terrain/include/terrain/water.h new file mode 100644 index 0000000..699bf3e --- /dev/null +++ b/terrain/include/terrain/water.h @@ -0,0 +1,58 @@ +#pragma once + +#include "types.h" +#include +#include +#include + +namespace metin2::terrain { + +class WaterManager { +public: + WaterManager(); + ~WaterManager() = default; + + // Load Metin2 binary water.wtr file (Magic: 5426) + bool LoadWater(const std::string& filepath, float cell_scale = 40.0f, float height_scale = 0.5f, float height_bias = 0.0f, + float world_min_x = -2560.0f, float world_min_z = -2560.0f); + bool LoadWaterFromBuffer(const uint8_t* data, size_t size, float cell_scale = 40.0f, float height_scale = 0.5f, float height_bias = 0.0f, + float world_min_x = -2560.0f, float world_min_z = -2560.0f); + + // Generate procedural water plane (for valleys, rivers, or lakes) + void GenerateProceduralWater(float water_level, float min_x, float max_x, float min_z, float max_z, float cell_size = 60.0f); + + // Build unified 3D draw command for water rasterization + TerrainDrawCommand BuildDrawCommand(float anim_time = 0.0f) const; + + bool HasWater() const { return m_has_water; } + size_t GetWaterFaceCount() const { return m_face_count; } + float GetWaterLevel(size_t layer = 0) const; + + void SetWaterColor(uint32_t color) { m_water_color = color; } + uint32_t GetWaterColor() const { return m_water_color; } + +private: + bool m_has_water = false; + uint16_t m_width = 0; + uint16_t m_height = 0; + std::vector m_water_grid; + std::vector m_water_heights; + float m_cell_scale = 40.0f; + float m_height_scale = 0.5f; + float m_height_bias = 0.0f; + float m_world_min_x = 0.0f; + float m_world_min_z = 0.0f; + size_t m_face_count = 0; + uint32_t m_water_color = 0xAA2C7CA3; // translucent aqua cyan + + struct ProceduralWaterPlane { + float water_level = 0.0f; + float min_x = 0.0f, max_x = 0.0f; + float min_z = 0.0f, max_z = 0.0f; + float cell_size = 60.0f; + }; + ProceduralWaterPlane m_proc_plane; + bool m_procedural = false; +}; + +} // namespace metin2::terrain diff --git a/terrain/src/heightmap.cpp b/terrain/src/heightmap.cpp new file mode 100644 index 0000000..03e53d7 --- /dev/null +++ b/terrain/src/heightmap.cpp @@ -0,0 +1,707 @@ +#include "terrain/heightmap.h" +#include +#include +#include +#include +#include + +namespace metin2::terrain { + +namespace { + +inline void Normalize3(float v[3]) { + float len = std::sqrt(v[0] * v[0] + v[1] * v[1] + v[2] * v[2]); + if (len > 1e-6f) { + float inv = 1.0f / len; + v[0] *= inv; + v[1] *= inv; + v[2] *= inv; + } else { + v[0] = 0.0f; v[1] = 1.0f; v[2] = 0.0f; + } +} + +inline void ExtractFrustumPlanes(const float view[16], const float proj[16], float planes[6][4]) { + float vp[16]; + for (int i = 0; i < 4; ++i) { + for (int j = 0; j < 4; ++j) { + vp[i * 4 + j] = view[i * 4 + 0] * proj[0 * 4 + j] + + view[i * 4 + 1] * proj[1 * 4 + j] + + view[i * 4 + 2] * proj[2 * 4 + j] + + view[i * 4 + 3] * proj[3 * 4 + j]; + } + } + + // Left, Right, Bottom, Top, Near, Far + planes[0][0] = vp[3] + vp[0]; planes[0][1] = vp[7] + vp[4]; planes[0][2] = vp[11] + vp[8]; planes[0][3] = vp[15] + vp[12]; + planes[1][0] = vp[3] - vp[0]; planes[1][1] = vp[7] - vp[4]; planes[1][2] = vp[11] - vp[8]; planes[1][3] = vp[15] - vp[12]; + planes[2][0] = vp[3] + vp[1]; planes[2][1] = vp[7] + vp[5]; planes[2][2] = vp[11] + vp[9]; planes[2][3] = vp[15] + vp[13]; + planes[3][0] = vp[3] - vp[1]; planes[3][1] = vp[7] - vp[5]; planes[3][2] = vp[11] - vp[9]; planes[3][3] = vp[15] - vp[13]; + planes[4][0] = vp[2]; planes[4][1] = vp[6]; planes[4][2] = vp[10]; planes[4][3] = vp[14]; + planes[5][0] = vp[3] - vp[2]; planes[5][1] = vp[7] - vp[6]; planes[5][2] = vp[11] - vp[10]; planes[5][3] = vp[15] - vp[14]; + + for (int p = 0; p < 6; ++p) { + float len = std::sqrt(planes[p][0] * planes[p][0] + planes[p][1] * planes[p][1] + planes[p][2] * planes[p][2]); + if (len > 1e-6f) { + float inv = 1.0f / len; + planes[p][0] *= inv; + planes[p][1] *= inv; + planes[p][2] *= inv; + planes[p][3] *= inv; + } + } +} + +inline bool IsBoxInFrustum(const float aabb_min[3], const float aabb_max[3], const float planes[6][4]) { + for (int i = 0; i < 6; ++i) { + float px = (planes[i][0] > 0.0f) ? aabb_max[0] : aabb_min[0]; + float py = (planes[i][1] > 0.0f) ? aabb_max[1] : aabb_min[1]; + float pz = (planes[i][2] > 0.0f) ? aabb_max[2] : aabb_min[2]; + + if (planes[i][0] * px + planes[i][1] * py + planes[i][2] * pz + planes[i][3] < 0.0f) { + return false; + } + } + return true; +} + +} // namespace + +TerrainHeightmap::TerrainHeightmap() = default; + +bool TerrainHeightmap::LoadRaw(const std::string& raw_path, float height_scale, float cell_scale) { + std::ifstream file(raw_path, std::ios::binary); + if (!file.is_open()) return false; + + file.seekg(0, std::ios::end); + size_t file_size = static_cast(file.tellg()); + file.seekg(0, std::ios::beg); + + if (file_size < sizeof(uint16_t) * RAW_XSIZE * RAW_YSIZE) return false; + + std::vector buffer(RAW_XSIZE * RAW_YSIZE); + file.read(reinterpret_cast(buffer.data()), buffer.size() * sizeof(uint16_t)); + if (!file) return false; + + return LoadFromBuffer(buffer.data(), buffer.size(), height_scale, cell_scale); +} + +bool TerrainHeightmap::LoadFromBuffer(const uint16_t* raw_data, size_t count, float height_scale, float cell_scale) { + if (!raw_data || count < static_cast(RAW_XSIZE * RAW_YSIZE)) return false; + + m_width = RAW_XSIZE; + m_height = RAW_YSIZE; + m_cell_scale = cell_scale; + m_height_scale = height_scale; + + m_heights.resize(m_width * m_height); + m_min_height = 1e9f; + m_max_height = -1e9f; + + for (size_t i = 0; i < m_heights.size(); ++i) { + float h = static_cast(raw_data[i]) * m_height_scale; + m_heights[i] = h; + if (h < m_min_height) m_min_height = h; + if (h > m_max_height) m_max_height = h; + } + + UpdateBounds(); + CalculateNormals(); + BuildPatchesAndQuadtree(); + return true; +} + +bool TerrainHeightmap::LoadTileRaw(const std::string& tile_path) { + std::ifstream file(tile_path, std::ios::binary); + if (!file.is_open()) return false; + + file.seekg(0, std::ios::end); + size_t file_size = static_cast(file.tellg()); + file.seekg(0, std::ios::beg); + + if (file_size < static_cast(TILEMAP_RAW_XSIZE * TILEMAP_RAW_YSIZE)) return false; + + std::vector buffer(TILEMAP_RAW_XSIZE * TILEMAP_RAW_YSIZE); + file.read(reinterpret_cast(buffer.data()), buffer.size()); + if (!file) return false; + + return LoadTileFromBuffer(buffer.data(), buffer.size()); +} + +bool TerrainHeightmap::LoadTileFromBuffer(const uint8_t* tile_data, size_t count) { + if (!tile_data || count < static_cast(TILEMAP_RAW_XSIZE * TILEMAP_RAW_YSIZE)) return false; + + m_tile_width = TILEMAP_RAW_XSIZE; + m_tile_height = TILEMAP_RAW_YSIZE; + m_tiles.assign(tile_data, tile_data + count); + + if (!m_heights.empty()) { + BuildPatchesAndQuadtree(); + } + return true; +} + +bool TerrainHeightmap::LoadAttr(const std::string& attr_path) { + std::ifstream file(attr_path, std::ios::binary); + if (!file.is_open()) return false; + + file.seekg(0, std::ios::end); + size_t file_size = static_cast(file.tellg()); + file.seekg(0, std::ios::beg); + + std::vector buffer(file_size); + file.read(reinterpret_cast(buffer.data()), file_size); + if (!file) return false; + + return LoadAttrFromBuffer(buffer.data(), buffer.size()); +} + +bool TerrainHeightmap::LoadAttrFromBuffer(const uint8_t* attr_data, size_t count) { + if (!attr_data || count < static_cast(ATTRMAP_XSIZE * ATTRMAP_YSIZE)) return false; + + m_attr_width = ATTRMAP_XSIZE; + m_attr_height = ATTRMAP_YSIZE; + +#pragma pack(push, 1) + struct SAttrMapHeader { + uint16_t m_wMagic; + uint16_t m_wWidth; + uint16_t m_wHeight; + }; +#pragma pack(pop) + + const size_t expected_data_size = ATTRMAP_XSIZE * ATTRMAP_YSIZE; + if (count >= sizeof(SAttrMapHeader) + expected_data_size) { + const auto* hdr = reinterpret_cast(attr_data); + if (hdr->m_wMagic == 2634 && hdr->m_wWidth == ATTRMAP_XSIZE && hdr->m_wHeight == ATTRMAP_YSIZE) { + const uint8_t* src = attr_data + sizeof(SAttrMapHeader); + m_attr.assign(src, src + expected_data_size); + return true; + } + } + + m_attr.assign(attr_data, attr_data + expected_data_size); + return true; +} + +bool TerrainHeightmap::LoadTextureSet(const std::string& textureset_path) { + std::ifstream file(textureset_path); + if (!file.is_open()) return false; + std::stringstream buffer; + buffer << file.rdbuf(); + return LoadTextureSetFromString(buffer.str()); +} + +bool TerrainHeightmap::LoadTextureSetFromString(const std::string& content) { + std::istringstream file(content); + std::string line; + int current_id = 0; + bool in_texture = false; + + while (std::getline(file, line)) { + while (!line.empty() && (line.back() == '\r' || line.back() == ' ' || line.back() == '\t')) { + line.pop_back(); + } + size_t start = line.find_first_not_of(" \t"); + if (start == std::string::npos) continue; + std::string trim = line.substr(start); + + if (trim.rfind("Start Texture", 0) == 0) { + std::string id_str = trim.substr(13); + current_id = std::atoi(id_str.c_str()); + in_texture = true; + } else if (trim.rfind("End Texture", 0) == 0) { + in_texture = false; + current_id = 0; + } else if (in_texture && current_id > 0) { + if (trim.front() == '"' || trim.find(".dds") != std::string::npos || trim.find(".tga") != std::string::npos) { + std::string path = trim; + if (path.front() == '"' && path.back() == '"') { + path = path.substr(1, path.size() - 2); + } + if (path.size() >= 3 && (path[0] == 'd' || path[0] == 'D') && path[1] == ':') { + path = path.substr(3); + } + for (char& c : path) { + if (c == '\\') c = '/'; + } + while (!path.empty() && path.front() == '/') { + path = path.substr(1); + } + m_textureSet[static_cast(current_id)] = path; + in_texture = false; + } + } + } + return !m_textureSet.empty(); +} + +void TerrainHeightmap::GenerateProcedural(int width, int height, float cell_scale, float hill_amplitude) { + m_width = std::max(width, 16); + m_height = std::max(height, 16); + m_cell_scale = cell_scale; + m_height_scale = 1.0f; + + m_heights.resize(m_width * m_height); + m_min_height = 1e9f; + m_max_height = -1e9f; + + for (int j = 0; j < m_height; ++j) { + for (int i = 0; i < m_width; ++i) { + float fx = static_cast(i); + float fz = static_cast(j); + + float h1 = std::sin(fx * 0.12f) * std::cos(fz * 0.12f) * (hill_amplitude * 0.6f); + float h2 = std::sin(fx * 0.05f + 1.2f) * std::cos(fz * 0.06f + 0.8f) * (hill_amplitude * 0.4f); + float h3 = std::sin(fx * 0.25f) * (hill_amplitude * 0.1f); + float h = h1 + h2 + h3; + + int idx = j * m_width + i; + m_heights[idx] = h; + if (h < m_min_height) m_min_height = h; + if (h > m_max_height) m_max_height = h; + } + } + + UpdateBounds(); + CalculateNormals(); + BuildPatchesAndQuadtree(); +} + +void TerrainHeightmap::UpdateBounds() { + float total_w = static_cast(m_width - 1) * m_cell_scale; + float total_h = static_cast(m_height - 1) * m_cell_scale; + m_world_min_x = m_has_origin ? m_origin_x : -total_w * 0.5f; + m_world_max_x = m_world_min_x + total_w; + m_world_min_z = m_has_origin ? m_origin_z : -total_h * 0.5f; + m_world_max_z = m_world_min_z + total_h; +} + +void TerrainHeightmap::SetWorldOrigin(float min_x, float min_z) { + m_has_origin = true; + m_origin_x = min_x; + m_origin_z = min_z; + if (m_heights.empty()) return; + UpdateBounds(); + BuildPatchesAndQuadtree(); +} + +void TerrainHeightmap::CalculateNormals() { + m_normals.resize(m_width * m_height * 3); + + for (int j = 0; j < m_height; ++j) { + for (int i = 0; i < m_width; ++i) { + int x_prev = std::max(0, i - 1); + int x_next = std::min(m_width - 1, i + 1); + int z_prev = std::max(0, j - 1); + int z_next = std::min(m_height - 1, j + 1); + + float h_left = m_heights[j * m_width + x_prev]; + float h_right = m_heights[j * m_width + x_next]; + float h_down = m_heights[z_prev * m_width + i]; + float h_up = m_heights[z_next * m_width + i]; + + float dx = (h_right - h_left); + float dz = (h_up - h_down); + float scale_x = static_cast(x_next - x_prev) * m_cell_scale; + float scale_z = static_cast(z_next - z_prev) * m_cell_scale; + + float norm[3] = { -dx / scale_x, 1.0f, -dz / scale_z }; + Normalize3(norm); + + int n_idx = (j * m_width + i) * 3; + m_normals[n_idx + 0] = norm[0]; + m_normals[n_idx + 1] = norm[1]; + m_normals[n_idx + 2] = norm[2]; + } + } +} + +float TerrainHeightmap::GetHeightAtGrid(int x, int y) const { + if (m_heights.empty()) return 0.0f; + x = std::clamp(x, 0, m_width - 1); + y = std::clamp(y, 0, m_height - 1); + return m_heights[y * m_width + x]; +} + +float TerrainHeightmap::GetHeightAtWorld(float world_x, float world_z) const { + if (m_heights.empty() || m_width < 2 || m_height < 2) return 0.0f; + + float grid_x = (world_x - m_world_min_x) / m_cell_scale; + float grid_z = (world_z - m_world_min_z) / m_cell_scale; + + grid_x = std::clamp(grid_x, 0.0f, static_cast(m_width - 1)); + grid_z = std::clamp(grid_z, 0.0f, static_cast(m_height - 1)); + + int x0 = static_cast(std::floor(grid_x)); + int z0 = static_cast(std::floor(grid_z)); + int x1 = std::min(x0 + 1, m_width - 1); + int z1 = std::min(z0 + 1, m_height - 1); + + float tx = grid_x - static_cast(x0); + float tz = grid_z - static_cast(z0); + + float h00 = m_heights[z0 * m_width + x0]; + float h10 = m_heights[z0 * m_width + x1]; + float h01 = m_heights[z1 * m_width + x0]; + float h11 = m_heights[z1 * m_width + x1]; + + float h0 = h00 * (1.0f - tx) + h10 * tx; + float h1 = h01 * (1.0f - tx) + h11 * tx; + return h0 * (1.0f - tz) + h1 * tz; +} + +void TerrainHeightmap::GetNormalAtWorld(float world_x, float world_z, float out_normal[3]) const { + if (m_normals.empty() || m_width < 2 || m_height < 2) { + out_normal[0] = 0.0f; out_normal[1] = 1.0f; out_normal[2] = 0.0f; + return; + } + + float grid_x = (world_x - m_world_min_x) / m_cell_scale; + float grid_z = (world_z - m_world_min_z) / m_cell_scale; + + grid_x = std::clamp(grid_x, 0.0f, static_cast(m_width - 1)); + grid_z = std::clamp(grid_z, 0.0f, static_cast(m_height - 1)); + + int x0 = static_cast(std::round(grid_x)); + int z0 = static_cast(std::round(grid_z)); + x0 = std::clamp(x0, 0, m_width - 1); + z0 = std::clamp(z0, 0, m_height - 1); + + int idx = (z0 * m_width + x0) * 3; + out_normal[0] = m_normals[idx + 0]; + out_normal[1] = m_normals[idx + 1]; + out_normal[2] = m_normals[idx + 2]; +} + +uint8_t TerrainHeightmap::GetTileAtGrid(int x, int y) const { + if (m_tiles.empty() || m_tile_width <= 0 || m_tile_height <= 0) return 0; + x = std::clamp(x, 0, m_tile_width - 1); + y = std::clamp(y, 0, m_tile_height - 1); + return m_tiles[y * m_tile_width + x]; +} + +uint8_t TerrainHeightmap::GetTileAtWorld(float world_x, float world_z) const { + if (m_tiles.empty() || m_tile_width <= 0 || m_tile_height <= 0) return 0; + float grid_x = (world_x - m_world_min_x) / (static_cast(m_width - 1) * m_cell_scale) * static_cast(m_tile_width - 1); + float grid_z = (world_z - m_world_min_z) / (static_cast(m_height - 1) * m_cell_scale) * static_cast(m_tile_height - 1); + int tx = std::clamp(static_cast(std::round(grid_x)), 0, m_tile_width - 1); + int tz = std::clamp(static_cast(std::round(grid_z)), 0, m_tile_height - 1); + return m_tiles[tz * m_tile_width + tx]; +} + +std::string TerrainHeightmap::GetTexturePathForTile(uint8_t tile_id) const { + auto it = m_textureSet.find(tile_id); + if (it != m_textureSet.end()) return it->second; + return "ymir work/terrainmaps/map1/grass/grass 01.dds"; +} + +uint8_t TerrainHeightmap::GetAttrAtGrid(int x, int y) const { + if (m_attr.empty() || m_attr_width <= 0 || m_attr_height <= 0) return 0; + x = std::clamp(x, 0, m_attr_width - 1); + y = std::clamp(y, 0, m_attr_height - 1); + return m_attr[y * m_attr_width + x]; +} + +uint8_t TerrainHeightmap::GetAttrAtWorld(float world_x, float world_z) const { + if (m_attr.empty() || m_attr_width <= 0 || m_attr_height <= 0 || m_width < 2 || m_height < 2) return 0; + float grid_x = (world_x - m_world_min_x) / (static_cast(m_width - 1) * m_cell_scale) * static_cast(m_attr_width - 1); + float grid_z = (world_z - m_world_min_z) / (static_cast(m_height - 1) * m_cell_scale) * static_cast(m_attr_height - 1); + int ax = std::clamp(static_cast(std::round(grid_x)), 0, m_attr_width - 1); + int az = std::clamp(static_cast(std::round(grid_z)), 0, m_attr_height - 1); + return m_attr[az * m_attr_width + ax]; +} + +bool TerrainHeightmap::IsAttrOn(float world_x, float world_z, uint8_t flag) const { + return (GetAttrAtWorld(world_x, world_z) & flag) != 0; +} + +void TerrainHeightmap::BuildPatchesAndQuadtree() { + if (m_width < 16 || m_height < 16) return; + + m_patches.resize(PATCH_COUNT * PATCH_COUNT); + int patch_cells_x = (m_width - 1) / PATCH_COUNT; + int patch_cells_z = (m_height - 1) / PATCH_COUNT; + + for (int py = 0; py < PATCH_COUNT; ++py) { + for (int px = 0; px < PATCH_COUNT; ++px) { + int p_idx = py * PATCH_COUNT + px; + auto& patch = m_patches[p_idx]; + patch.patch_x = px; + patch.patch_y = py; + + int x0 = px * patch_cells_x; + int x1 = (px + 1) * patch_cells_x; + int z0 = py * patch_cells_z; + int z1 = (py + 1) * patch_cells_z; + + patch.aabb_min[0] = m_world_min_x + static_cast(x0) * m_cell_scale; + patch.aabb_max[0] = m_world_min_x + static_cast(x1) * m_cell_scale; + patch.aabb_min[2] = m_world_min_z + static_cast(z0) * m_cell_scale; + patch.aabb_max[2] = m_world_min_z + static_cast(z1) * m_cell_scale; + + float min_y = 1e9f, max_y = -1e9f; + std::unordered_map tile_freq; + + for (int j = z0; j <= z1 && j < m_height; ++j) { + for (int i = x0; i <= x1 && i < m_width; ++i) { + float h = m_heights[j * m_width + i]; + if (h < min_y) min_y = h; + if (h > max_y) max_y = h; + + if (!m_tiles.empty() && m_tile_width > 0 && m_tile_height > 0) { + int tx = (i * (m_tile_width - 1)) / (m_width - 1); + int tz = (j * (m_tile_height - 1)) / (m_height - 1); + uint8_t t = m_tiles[tz * m_tile_width + tx]; + tile_freq[t]++; + } + } + } + + patch.aabb_min[1] = min_y; + patch.aabb_max[1] = max_y; + + uint8_t dom_tile = 4; // default grass + int max_c = 0; + for (const auto& [t, c] : tile_freq) { + if (c > max_c) { + max_c = c; + dom_tile = t; + } + } + patch.dominant_tile = dom_tile; + } + } + + m_quadtreeRoot = BuildQuadtreeNode(m_world_min_x, m_world_max_x, m_world_min_z, m_world_max_z, 0); +} + +std::unique_ptr TerrainHeightmap::BuildQuadtreeNode(float min_x, float max_x, float min_z, float max_z, int depth) { + auto node = std::make_unique(); + node->depth = depth; + node->aabb_min[0] = min_x; + node->aabb_max[0] = max_x; + node->aabb_min[2] = min_z; + node->aabb_max[2] = max_z; + node->aabb_min[1] = m_min_height; + node->aabb_max[1] = m_max_height; + + if (depth >= 3) { + float cx = (min_x + max_x) * 0.5f; + float cz = (min_z + max_z) * 0.5f; + + float u = (cx - m_world_min_x) / (m_world_max_x - m_world_min_x); + float v = (cz - m_world_min_z) / (m_world_max_z - m_world_min_z); + int px = std::clamp(static_cast(u * static_cast(PATCH_COUNT)), 0, PATCH_COUNT - 1); + int py = std::clamp(static_cast(v * static_cast(PATCH_COUNT)), 0, PATCH_COUNT - 1); + int idx = py * PATCH_COUNT + px; + + node->patch_idx = idx; + if (idx < static_cast(m_patches.size())) { + node->aabb_min[1] = m_patches[idx].aabb_min[1]; + node->aabb_max[1] = m_patches[idx].aabb_max[1]; + } + return node; + } + + float mid_x = (min_x + max_x) * 0.5f; + float mid_z = (min_z + max_z) * 0.5f; + + node->children[0] = BuildQuadtreeNode(min_x, mid_x, min_z, mid_z, depth + 1); + node->children[1] = BuildQuadtreeNode(mid_x, max_x, min_z, mid_z, depth + 1); + node->children[2] = BuildQuadtreeNode(min_x, mid_x, mid_z, max_z, depth + 1); + node->children[3] = BuildQuadtreeNode(mid_x, max_x, mid_z, max_z, depth + 1); + + float cmin_y = 1e9f, cmax_y = -1e9f; + for (int k = 0; k < 4; ++k) { + if (node->children[k]) { + cmin_y = std::min(cmin_y, node->children[k]->aabb_min[1]); + cmax_y = std::max(cmax_y, node->children[k]->aabb_max[1]); + } + } + node->aabb_min[1] = cmin_y; + node->aabb_max[1] = cmax_y; + + return node; +} + +void TerrainHeightmap::QueryQuadtree(const TerrainQuadNode* node, const float planes[6][4], const float eye[3], float max_distance, std::vector& out_visible_patches) const { + if (!node) return; + + if (!IsBoxInFrustum(node->aabb_min, node->aabb_max, planes)) return; + + if (node->patch_idx >= 0) { + float cx = (node->aabb_min[0] + node->aabb_max[0]) * 0.5f; + float cy = (node->aabb_min[1] + node->aabb_max[1]) * 0.5f; + float cz = (node->aabb_min[2] + node->aabb_max[2]) * 0.5f; + float dx = cx - eye[0]; + float dy = cy - eye[1]; + float dz = cz - eye[2]; + float dist_sq = dx * dx + dy * dy + dz * dz; + + if (dist_sq <= max_distance * max_distance) { + out_visible_patches.push_back(node->patch_idx); + } + return; + } + + for (int k = 0; k < 4; ++k) { + if (node->children[k]) { + QueryQuadtree(node->children[k].get(), planes, eye, max_distance, out_visible_patches); + } + } +} + +TerrainDrawCommand TerrainHeightmap::BuildDrawCommand(const float /*world*/[16], int step) const { + TerrainDrawCommand cmd; + if (m_heights.empty() || m_width < 2 || m_height < 2) return cmd; + + step = std::max(1, step); + int verts_x = (m_width - 1) / step + 1; + int verts_z = (m_height - 1) / step + 1; + + cmd.positions.reserve(verts_x * verts_z * 3); + cmd.normals.reserve(verts_x * verts_z * 3); + cmd.uv0.reserve(verts_x * verts_z * 2); + cmd.diffuse.reserve(verts_x * verts_z); + cmd.indices.reserve((verts_x - 1) * (verts_z - 1) * 6); + + for (int j = 0; j < m_height; j += step) { + for (int i = 0; i < m_width; i += step) { + float x = m_world_min_x + static_cast(i) * m_cell_scale; + float z = m_world_min_z + static_cast(j) * m_cell_scale; + float y = m_heights[j * m_width + i]; + + cmd.positions.push_back(x); + cmd.positions.push_back(y); + cmd.positions.push_back(z); + + if (!m_normals.empty()) { + int n_idx = (j * m_width + i) * 3; + cmd.normals.push_back(m_normals[n_idx + 0]); + cmd.normals.push_back(m_normals[n_idx + 1]); + cmd.normals.push_back(m_normals[n_idx + 2]); + } else { + cmd.normals.push_back(0.0f); + cmd.normals.push_back(1.0f); + cmd.normals.push_back(0.0f); + } + + cmd.uv0.push_back(static_cast(i) * 0.125f); + cmd.uv0.push_back(static_cast(j) * 0.125f); + cmd.diffuse.push_back(0xFFFFFFFF); + } + } + + for (int j = 0; j < verts_z - 1; ++j) { + for (int i = 0; i < verts_x - 1; ++i) { + uint32_t i0 = j * verts_x + i; + uint32_t i1 = j * verts_x + (i + 1); + uint32_t i2 = (j + 1) * verts_x + i; + uint32_t i3 = (j + 1) * verts_x + (i + 1); + + cmd.indices.push_back(i0); + cmd.indices.push_back(i2); + cmd.indices.push_back(i1); + + cmd.indices.push_back(i1); + cmd.indices.push_back(i2); + cmd.indices.push_back(i3); + } + } + + cmd.aabb_min[0] = m_world_min_x; cmd.aabb_min[1] = m_min_height; cmd.aabb_min[2] = m_world_min_z; + cmd.aabb_max[0] = m_world_max_x; cmd.aabb_max[1] = m_max_height; cmd.aabb_max[2] = m_world_max_z; + return cmd; +} + +std::vector TerrainHeightmap::BuildCulledDraws(const float view[16], const float proj[16], float max_distance) const { + std::vector draws; + if (m_heights.empty() || m_patches.empty() || !m_quadtreeRoot) return draws; + + float planes[6][4]; + ExtractFrustumPlanes(view, proj, planes); + + float eye[3] = { + -(view[0] * view[12] + view[1] * view[13] + view[2] * view[14]), + -(view[4] * view[12] + view[5] * view[13] + view[6] * view[14]), + -(view[8] * view[12] + view[9] * view[13] + view[10] * view[14]) + }; + + std::vector visible_patches; + visible_patches.reserve(64); + QueryQuadtree(m_quadtreeRoot.get(), planes, eye, max_distance, visible_patches); + + int patch_cells_x = (m_width - 1) / PATCH_COUNT; + int patch_cells_z = (m_height - 1) / PATCH_COUNT; + + for (int p_idx : visible_patches) { + if (p_idx < 0 || p_idx >= static_cast(m_patches.size())) continue; + const auto& patch = m_patches[p_idx]; + + TerrainDrawCommand cmd; + cmd.dominant_tile = patch.dominant_tile; + cmd.texture_path = GetTexturePathForTile(patch.dominant_tile); + cmd.aabb_min[0] = patch.aabb_min[0]; cmd.aabb_min[1] = patch.aabb_min[1]; cmd.aabb_min[2] = patch.aabb_min[2]; + cmd.aabb_max[0] = patch.aabb_max[0]; cmd.aabb_max[1] = patch.aabb_max[1]; cmd.aabb_max[2] = patch.aabb_max[2]; + + int x0 = patch.patch_x * patch_cells_x; + int x1 = (patch.patch_x + 1) * patch_cells_x; + int z0 = patch.patch_y * patch_cells_z; + int z1 = (patch.patch_y + 1) * patch_cells_z; + + int step = 1; + int verts_x = (x1 - x0) / step + 1; + int verts_z = (z1 - z0) / step + 1; + + cmd.positions.reserve(verts_x * verts_z * 3); + cmd.normals.reserve(verts_x * verts_z * 3); + cmd.uv0.reserve(verts_x * verts_z * 2); + cmd.diffuse.reserve(verts_x * verts_z); + cmd.indices.reserve((verts_x - 1) * (verts_z - 1) * 6); + + for (int j = z0; j <= z1; j += step) { + for (int i = x0; i <= x1; i += step) { + float x = m_world_min_x + static_cast(i) * m_cell_scale; + float z = m_world_min_z + static_cast(j) * m_cell_scale; + float y = m_heights[j * m_width + i]; + + cmd.positions.push_back(x); + cmd.positions.push_back(y); + cmd.positions.push_back(z); + + int n_idx = (j * m_width + i) * 3; + cmd.normals.push_back(m_normals[n_idx + 0]); + cmd.normals.push_back(m_normals[n_idx + 1]); + cmd.normals.push_back(m_normals[n_idx + 2]); + + cmd.uv0.push_back(static_cast(i) * 0.125f); + cmd.uv0.push_back(static_cast(j) * 0.125f); + cmd.diffuse.push_back(0xFFFFFFFF); + } + } + + for (int j = 0; j < verts_z - 1; ++j) { + for (int i = 0; i < verts_x - 1; ++i) { + uint32_t i0 = j * verts_x + i; + uint32_t i1 = j * verts_x + (i + 1); + uint32_t i2 = (j + 1) * verts_x + i; + uint32_t i3 = (j + 1) * verts_x + (i + 1); + + cmd.indices.push_back(i0); + cmd.indices.push_back(i2); + cmd.indices.push_back(i1); + + cmd.indices.push_back(i1); + cmd.indices.push_back(i2); + cmd.indices.push_back(i3); + } + } + + draws.push_back(std::move(cmd)); + } + + return draws; +} + +} // namespace metin2::terrain diff --git a/terrain/src/water.cpp b/terrain/src/water.cpp new file mode 100644 index 0000000..38de5fa --- /dev/null +++ b/terrain/src/water.cpp @@ -0,0 +1,213 @@ +#include "terrain/water.h" +#include +#include +#include + +namespace metin2::terrain { + +#pragma pack(push, 1) +struct SWaterMapHeader { + uint16_t magic; // 5426 + uint16_t width; // 128 + uint16_t height; // 128 + uint8_t layer_count; +}; +#pragma pack(pop) + +WaterManager::WaterManager() = default; + +bool WaterManager::LoadWater(const std::string& filepath, float cell_scale, float height_scale, float height_bias, + float world_min_x, float world_min_z) { + std::ifstream file(filepath, std::ios::binary); + if (!file) return false; + + file.seekg(0, std::ios::end); + std::streamsize file_size = file.tellg(); + file.seekg(0, std::ios::beg); + + std::vector buffer(file_size); + file.read(reinterpret_cast(buffer.data()), file_size); + if (!file) return false; + + return LoadWaterFromBuffer(buffer.data(), buffer.size(), cell_scale, height_scale, height_bias, world_min_x, world_min_z); +} + +bool WaterManager::LoadWaterFromBuffer(const uint8_t* data, size_t size, float cell_scale, float height_scale, float height_bias, + float world_min_x, float world_min_z) { + if (!data || size < sizeof(SWaterMapHeader)) return false; + + const auto* header = reinterpret_cast(data); + constexpr uint16_t WATER_MAGIC = 5426; + if (header->magic != WATER_MAGIC || header->width == 0 || header->height == 0) return false; + + m_width = header->width; + m_height = header->height; + size_t grid_size = static_cast(m_width) * m_height; + + if (size < sizeof(SWaterMapHeader) + grid_size) return false; + + const uint8_t* grid_ptr = data + sizeof(SWaterMapHeader); + m_water_grid.assign(grid_ptr, grid_ptr + grid_size); + + size_t rest_bytes = size - sizeof(SWaterMapHeader) - grid_size; + m_water_heights.clear(); + + const uint8_t* rest_ptr = grid_ptr + grid_size; + if (header->layer_count > 0) { + if (rest_bytes == header->layer_count * sizeof(int32_t)) { + m_water_heights.resize(header->layer_count); + std::copy(reinterpret_cast(rest_ptr), + reinterpret_cast(rest_ptr) + header->layer_count, + m_water_heights.begin()); + } else if (rest_bytes == header->layer_count * sizeof(uint16_t)) { + const auto* h16 = reinterpret_cast(rest_ptr); + for (size_t l = 0; l < header->layer_count; ++l) { + m_water_heights.push_back(static_cast(h16[l])); + } + } + } + + m_cell_scale = cell_scale; + m_height_scale = height_scale; + m_height_bias = height_bias; + m_world_min_x = world_min_x; + m_world_min_z = world_min_z; + + size_t valid_cells = 0; + for (uint8_t b : m_water_grid) { + if (b != 0xFF && b < m_water_heights.size()) { + valid_cells++; + } + } + + m_face_count = valid_cells * 2; + m_has_water = (valid_cells > 0); + m_procedural = false; + return m_has_water; +} + +void WaterManager::GenerateProceduralWater(float water_level, float min_x, float max_x, float min_z, float max_z, float cell_size) { + m_procedural = true; + m_proc_plane.water_level = water_level; + m_proc_plane.min_x = min_x; + m_proc_plane.max_x = max_x; + m_proc_plane.min_z = min_z; + m_proc_plane.max_z = max_z; + m_proc_plane.cell_size = std::max(10.0f, cell_size); + + int count_x = static_cast(std::ceil((max_x - min_x) / m_proc_plane.cell_size)); + int count_z = static_cast(std::ceil((max_z - min_z) / m_proc_plane.cell_size)); + m_face_count = static_cast(count_x * count_z * 2); + m_has_water = true; +} + +float WaterManager::GetWaterLevel(size_t layer) const { + if (m_procedural) return m_proc_plane.water_level; + if (layer < m_water_heights.size()) { + return static_cast(m_water_heights[layer]) * m_height_scale - m_height_bias; + } + return 0.0f; +} + +TerrainDrawCommand WaterManager::BuildDrawCommand(float anim_time) const { + TerrainDrawCommand draw; + if (!m_has_water) return draw; + + float wave_offset = std::sin(anim_time * 2.0f) * 1.5f; + + if (m_procedural) { + int nx = static_cast(std::ceil((m_proc_plane.max_x - m_proc_plane.min_x) / m_proc_plane.cell_size)); + int nz = static_cast(std::ceil((m_proc_plane.max_z - m_proc_plane.min_z) / m_proc_plane.cell_size)); + int verts_x = nx + 1; + int verts_z = nz + 1; + + draw.positions.reserve(verts_x * verts_z * 3); + draw.normals.reserve(verts_x * verts_z * 3); + draw.uv0.reserve(verts_x * verts_z * 2); + draw.diffuse.reserve(verts_x * verts_z); + draw.indices.reserve(nx * nz * 6); + + for (int j = 0; j <= nz; ++j) { + float z = m_proc_plane.min_z + static_cast(j) * m_proc_plane.cell_size; + for (int i = 0; i <= nx; ++i) { + float x = m_proc_plane.min_x + static_cast(i) * m_proc_plane.cell_size; + float y = m_proc_plane.water_level + wave_offset; + + draw.positions.push_back(x); + draw.positions.push_back(y); + draw.positions.push_back(z); + + draw.normals.push_back(0.0f); + draw.normals.push_back(1.0f); + draw.normals.push_back(0.0f); + + draw.uv0.push_back(x * 0.005f + anim_time * 0.02f); + draw.uv0.push_back(z * 0.005f + anim_time * 0.02f); + draw.diffuse.push_back(m_water_color); + } + } + + for (int j = 0; j < nz; ++j) { + for (int i = 0; i < nx; ++i) { + uint32_t i0 = j * verts_x + i; + uint32_t i1 = j * verts_x + (i + 1); + uint32_t i2 = (j + 1) * verts_x + i; + uint32_t i3 = (j + 1) * verts_x + (i + 1); + + draw.indices.push_back(i0); + draw.indices.push_back(i2); + draw.indices.push_back(i1); + + draw.indices.push_back(i1); + draw.indices.push_back(i2); + draw.indices.push_back(i3); + } + } + return draw; + } + + const int step = 2; + for (int j = 0; j < m_height; j += step) { + for (int i = 0; i < m_width; i += step) { + uint8_t layer = m_water_grid[j * m_width + i]; + if (layer == 0xFF || layer >= m_water_heights.size()) continue; + + float base_y = static_cast(m_water_heights[layer]) * m_height_scale - m_height_bias + wave_offset; + float x0 = m_world_min_x + static_cast(i) * m_cell_scale; + float x1 = x0 + m_cell_scale * static_cast(step); + float z0 = m_world_min_z + static_cast(j) * m_cell_scale; + float z1 = z0 + m_cell_scale * static_cast(step); + + uint32_t start_idx = static_cast(draw.positions.size() / 3); + + draw.positions.push_back(x0); draw.positions.push_back(base_y); draw.positions.push_back(z0); + draw.positions.push_back(x1); draw.positions.push_back(base_y); draw.positions.push_back(z0); + draw.positions.push_back(x0); draw.positions.push_back(base_y); draw.positions.push_back(z1); + draw.positions.push_back(x1); draw.positions.push_back(base_y); draw.positions.push_back(z1); + + for (int k = 0; k < 4; ++k) { + draw.normals.push_back(0.0f); + draw.normals.push_back(1.0f); + draw.normals.push_back(0.0f); + draw.diffuse.push_back(m_water_color); + } + + draw.uv0.push_back(x0 * 0.005f); draw.uv0.push_back(z0 * 0.005f); + draw.uv0.push_back(x1 * 0.005f); draw.uv0.push_back(z0 * 0.005f); + draw.uv0.push_back(x0 * 0.005f); draw.uv0.push_back(z1 * 0.005f); + draw.uv0.push_back(x1 * 0.005f); draw.uv0.push_back(z1 * 0.005f); + + draw.indices.push_back(start_idx + 0); + draw.indices.push_back(start_idx + 2); + draw.indices.push_back(start_idx + 1); + + draw.indices.push_back(start_idx + 1); + draw.indices.push_back(start_idx + 2); + draw.indices.push_back(start_idx + 3); + } + } + + return draw; +} + +} // namespace metin2::terrain diff --git a/terrain/tests/terrain_test.cpp b/terrain/tests/terrain_test.cpp new file mode 100644 index 0000000..332f01a --- /dev/null +++ b/terrain/tests/terrain_test.cpp @@ -0,0 +1,79 @@ +#include "terrain/terrain.h" +#include +#include +#include + +using namespace metin2::terrain; + +int main() { + std::cout << "[Test 1] Procedural terrain generation & bilinear height sampling..." << std::endl; + TerrainHeightmap heightmap; + heightmap.GenerateProcedural(64, 64, 100.0f, 120.0f); + + assert(heightmap.GetWidth() == 64); + assert(heightmap.GetHeight() == 64); + assert(heightmap.GetMaxHeight() > heightmap.GetMinHeight()); + + // Continuous world height query + float h_center = heightmap.GetHeightAtWorld(0.0f, 0.0f); + std::cout << " Height at world origin (0, 0): " << h_center << std::endl; + + float normal[3]; + heightmap.GetNormalAtWorld(0.0f, 0.0f, normal); + float norm_len = std::sqrt(normal[0]*normal[0] + normal[1]*normal[1] + normal[2]*normal[2]); + assert(std::abs(norm_len - 1.0f) < 1e-4f); + assert(normal[1] > 0.0f); // Y-up + std::cout << " Normal at world origin: (" << normal[0] << ", " << normal[1] << ", " << normal[2] << ")" << std::endl; + + std::cout << "[Test 2] Quadtree & Frustum Culling..." << std::endl; + assert(heightmap.GetQuadtreeRoot() != nullptr); + assert(!heightmap.GetPatches().empty()); + + // Standard DirectX LookAt View matrix: Eye=(0, 500, -1000), Target=(0, 0, 0), Up=(0, 1, 0) + float view[16] = { + 1.0f, 0.0f, 0.0f, 0.0f, + 0.0f, 0.894427f, -0.447214f, 0.0f, + 0.0f, 0.447214f, 0.894427f, 0.0f, + 0.0f, 0.0f, 1118.034f, 1.0f + }; + // Standard perspective projection matrix (FOV ~60 deg, near 1.0, far 10000.0) + float proj[16] = { + 1.732f, 0.0f, 0.0f, 0.0f, + 0.0f, 1.732f, 0.0f, 0.0f, + 0.0f, 0.0f, 1.0001f, 1.0f, + 0.0f, 0.0f, -1.0001f, 0.0f + }; + + auto culled_draws = heightmap.BuildCulledDraws(view, proj, 10000.0f); + std::cout << " Visible patches culled by frustum: " << culled_draws.size() << " / " << heightmap.GetPatches().size() << std::endl; + assert(!culled_draws.empty()); + + std::cout << "[Test 3] Attribute Map loading & querying..." << std::endl; + // Create dummy 256x256 attribute map with ATTR_BLOCK and ATTR_WATER + std::vector dummy_attr(TerrainHeightmap::ATTRMAP_XSIZE * TerrainHeightmap::ATTRMAP_YSIZE, 0); + // Mark center cell as blocked + dummy_attr[128 * TerrainHeightmap::ATTRMAP_XSIZE + 128] = TerrainAttr::ATTR_BLOCK | TerrainAttr::ATTR_BANPK; + bool attr_ok = heightmap.LoadAttrFromBuffer(dummy_attr.data(), dummy_attr.size()); + assert(attr_ok); + assert(heightmap.HasAttrMap()); + assert(heightmap.GetAttrAtGrid(128, 128) == (TerrainAttr::ATTR_BLOCK | TerrainAttr::ATTR_BANPK)); + assert(heightmap.IsAttrOn(0.0f, 0.0f, TerrainAttr::ATTR_BLOCK)); + assert(heightmap.IsAttrOn(0.0f, 0.0f, TerrainAttr::ATTR_BANPK)); + assert(!heightmap.IsAttrOn(0.0f, 0.0f, TerrainAttr::ATTR_WATER)); + + std::cout << "[Test 4] WaterManager & procedural wave generation..." << std::endl; + WaterManager water; + water.GenerateProceduralWater(25.0f, -1000.0f, 1000.0f, -1000.0f, 1000.0f, 100.0f); + assert(water.HasWater()); + assert(water.GetWaterFaceCount() > 0); + + TerrainDrawCommand water_draw = water.BuildDrawCommand(0.5f); + assert(!water_draw.positions.empty()); + assert(!water_draw.indices.empty()); + assert(water_draw.positions.size() == water_draw.normals.size()); + std::cout << " Water mesh generated: " << water_draw.positions.size() / 3 << " vertices, " + << water_draw.indices.size() / 3 << " triangles" << std::endl; + + std::cout << "All Terrain SDK tests passed successfully!" << std::endl; + return 0; +} diff --git a/texture/CMakeLists.txt b/texture/CMakeLists.txt new file mode 100644 index 0000000..ac69f38 --- /dev/null +++ b/texture/CMakeLists.txt @@ -0,0 +1,25 @@ +cmake_minimum_required(VERSION 3.20) +project(texture LANGUAGES CXX) + +set(CMAKE_CXX_STANDARD 20) +set(CMAKE_CXX_STANDARD_REQUIRED ON) + +add_library(texture STATIC + src/dxt.cpp + src/tga.cpp + src/sub_image.cpp +) + +target_include_directories(texture PUBLIC + $ + $ +) + +add_library(texture::texture ALIAS texture) + +option(TEXTURE_BUILD_TESTS "Build texture SDK tests" ON) +if(TEXTURE_BUILD_TESTS) + add_executable(texture_test tests/texture_test.cpp) + target_link_libraries(texture_test PRIVATE texture) + add_test(NAME texture_test COMMAND texture_test) +endif() diff --git a/texture/include/texture/dxt.h b/texture/include/texture/dxt.h new file mode 100644 index 0000000..b3a8108 --- /dev/null +++ b/texture/include/texture/dxt.h @@ -0,0 +1,19 @@ +#pragma once + +#include "types.h" +#include +#include + +namespace metin2::texture { + +class DxtDecoder { +public: + static bool DecompressDXT1(const uint8_t* src, uint32_t width, uint32_t height, uint8_t* dst_rgba); + static bool DecompressDXT3(const uint8_t* src, uint32_t width, uint32_t height, uint8_t* dst_rgba); + static bool DecompressDXT5(const uint8_t* src, uint32_t width, uint32_t height, uint8_t* dst_rgba); + + // Parse complete DDS file header (Magic 'DDS ', DDS_HEADER, pixel format) and decode to RGBA8888 + static bool DecodeDDS(const uint8_t* dds_data, size_t size, ImageBuffer& out_image); +}; + +} // namespace metin2::texture diff --git a/texture/include/texture/sub_image.h b/texture/include/texture/sub_image.h new file mode 100644 index 0000000..80126f7 --- /dev/null +++ b/texture/include/texture/sub_image.h @@ -0,0 +1,34 @@ +#pragma once + +#include "types.h" +#include + +namespace metin2::texture { + +class SubImage { +public: + SubImage() = default; + ~SubImage() = default; + + bool LoadFromString(const std::string& content); + bool LoadFromFile(const std::string& file_path); + + const std::string& GetImagePath() const { return m_image_path; } + const Rect2D& GetRect() const { return m_rect; } + int32_t GetWidth() const { return m_rect.GetWidth(); } + int32_t GetHeight() const { return m_rect.GetHeight(); } + + UVRect ComputeUV(uint32_t atlas_width, uint32_t atlas_height) const; + + // Generate 9-Slice mesh for UI window / button rendering + NineSliceMesh BuildNineSliceMesh(float x, float y, float width, float height, + float border_l, float border_t, float border_r, float border_b, + uint32_t atlas_width, uint32_t atlas_height, + uint32_t color = 0xFFFFFFFF) const; + +private: + std::string m_image_path; + Rect2D m_rect; +}; + +} // namespace metin2::texture diff --git a/texture/include/texture/texture.h b/texture/include/texture/texture.h new file mode 100644 index 0000000..9729161 --- /dev/null +++ b/texture/include/texture/texture.h @@ -0,0 +1,6 @@ +#pragma once + +#include "types.h" +#include "dxt.h" +#include "tga.h" +#include "sub_image.h" diff --git a/texture/include/texture/tga.h b/texture/include/texture/tga.h new file mode 100644 index 0000000..5c99b03 --- /dev/null +++ b/texture/include/texture/tga.h @@ -0,0 +1,15 @@ +#pragma once + +#include "types.h" +#include +#include + +namespace metin2::texture { + +class TgaDecoder { +public: + // Decodes uncompressed and RLE-compressed 24-bit/32-bit TGA to RGBA8888 + static bool DecodeTGA(const uint8_t* tga_data, size_t size, ImageBuffer& out_image); +}; + +} // namespace metin2::texture diff --git a/texture/include/texture/types.h b/texture/include/texture/types.h new file mode 100644 index 0000000..57cc3aa --- /dev/null +++ b/texture/include/texture/types.h @@ -0,0 +1,58 @@ +#pragma once + +#include +#include +#include + +namespace metin2::texture { + +enum class EPixelFormat { + Unknown = 0, + RGBA8888, + RGB888, + DXT1, + DXT3, + DXT5, + BGRA8888 +}; + +struct ImageBuffer { + uint32_t width = 0; + uint32_t height = 0; + EPixelFormat format = EPixelFormat::RGBA8888; + std::vector pixels; + + bool IsValid() const { return width > 0 && height > 0 && !pixels.empty(); } +}; + +struct Rect2D { + int32_t left = 0; + int32_t top = 0; + int32_t right = 0; + int32_t bottom = 0; + + int32_t GetWidth() const { return right - left; } + int32_t GetHeight() const { return bottom - top; } +}; + +struct UVRect { + float u0 = 0.0f; + float v0 = 0.0f; + float u1 = 1.0f; + float v1 = 1.0f; +}; + +struct NineSliceVertex { + float x = 0.0f; + float y = 0.0f; + float u = 0.0f; + float v = 0.0f; + uint32_t color = 0xFFFFFFFF; +}; + +struct NineSliceMesh { + std::vector vertices; + std::vector indices; +}; + +} // namespace metin2::texture diff --git a/texture/src/dxt.cpp b/texture/src/dxt.cpp new file mode 100644 index 0000000..2948adc --- /dev/null +++ b/texture/src/dxt.cpp @@ -0,0 +1,253 @@ +#include "texture/dxt.h" +#include +#include + +namespace metin2::texture { + +namespace { + +inline uint16_t ReadU16(const uint8_t* p) { + return static_cast(p[0]) | (static_cast(p[1]) << 8); +} + +inline uint32_t ReadU32(const uint8_t* p) { + return static_cast(p[0]) | + (static_cast(p[1]) << 8) | + (static_cast(p[2]) << 16) | + (static_cast(p[3]) << 24); +} + +inline void DecodeRGB565(uint16_t c, uint8_t& r, uint8_t& g, uint8_t& b) { + r = static_cast(((c >> 11) & 0x1F) * 255 / 31); + g = static_cast(((c >> 5) & 0x3F) * 255 / 63); + b = static_cast((c & 0x1F) * 255 / 31); +} + +void DecodeDXT1Block(const uint8_t* block, uint32_t x, uint32_t y, uint32_t width, uint32_t height, uint8_t* dst_rgba) { + uint16_t c0 = ReadU16(block); + uint16_t c1 = ReadU16(block + 2); + uint32_t code = ReadU32(block + 4); + + uint8_t colors[4][4]; + DecodeRGB565(c0, colors[0][0], colors[0][1], colors[0][2]); + colors[0][3] = 255; + + DecodeRGB565(c1, colors[1][0], colors[1][1], colors[1][2]); + colors[1][3] = 255; + + if (c0 > c1) { + colors[2][0] = (2 * colors[0][0] + colors[1][0]) / 3; + colors[2][1] = (2 * colors[0][1] + colors[1][1]) / 3; + colors[2][2] = (2 * colors[0][2] + colors[1][2]) / 3; + colors[2][3] = 255; + + colors[3][0] = (colors[0][0] + 2 * colors[1][0]) / 3; + colors[3][1] = (colors[0][1] + 2 * colors[1][1]) / 3; + colors[3][2] = (colors[0][2] + 2 * colors[1][2]) / 3; + colors[3][3] = 255; + } else { + colors[2][0] = (colors[0][0] + colors[1][0]) / 2; + colors[2][1] = (colors[0][1] + colors[1][1]) / 2; + colors[2][2] = (colors[0][2] + colors[1][2]) / 2; + colors[2][3] = 255; + + colors[3][0] = 0; + colors[3][1] = 0; + colors[3][2] = 0; + colors[3][3] = 0; + } + + for (int py = 0; py < 4; ++py) { + if (y + py >= height) continue; + for (int px = 0; px < 4; ++px) { + if (x + px >= width) continue; + int bit_idx = (py * 4 + px) * 2; + int color_idx = (code >> bit_idx) & 3; + + size_t dst_offset = ((y + py) * width + (x + px)) * 4; + dst_rgba[dst_offset + 0] = colors[color_idx][0]; + dst_rgba[dst_offset + 1] = colors[color_idx][1]; + dst_rgba[dst_offset + 2] = colors[color_idx][2]; + dst_rgba[dst_offset + 3] = colors[color_idx][3]; + } + } +} + +} // namespace + +bool DxtDecoder::DecompressDXT1(const uint8_t* src, uint32_t width, uint32_t height, uint8_t* dst_rgba) { + if (!src || !dst_rgba || width == 0 || height == 0) return false; + + uint32_t block_x = (width + 3) / 4; + uint32_t block_y = (height + 3) / 4; + + size_t src_offset = 0; + for (uint32_t by = 0; by < block_y; ++by) { + for (uint32_t bx = 0; bx < block_x; ++bx) { + DecodeDXT1Block(src + src_offset, bx * 4, by * 4, width, height, dst_rgba); + src_offset += 8; + } + } + return true; +} + +bool DxtDecoder::DecompressDXT3(const uint8_t* src, uint32_t width, uint32_t height, uint8_t* dst_rgba) { + if (!src || !dst_rgba || width == 0 || height == 0) return false; + + uint32_t block_x = (width + 3) / 4; + uint32_t block_y = (height + 3) / 4; + + size_t src_offset = 0; + for (uint32_t by = 0; by < block_y; ++by) { + for (uint32_t bx = 0; bx < block_x; ++bx) { + const uint8_t* alpha_block = src + src_offset; + const uint8_t* color_block = src + src_offset + 8; + + uint16_t c0 = ReadU16(color_block); + uint16_t c1 = ReadU16(color_block + 2); + uint32_t code = ReadU32(color_block + 4); + + uint8_t colors[4][3]; + DecodeRGB565(c0, colors[0][0], colors[0][1], colors[0][2]); + DecodeRGB565(c1, colors[1][0], colors[1][1], colors[1][2]); + + colors[2][0] = (2 * colors[0][0] + colors[1][0]) / 3; + colors[2][1] = (2 * colors[0][1] + colors[1][1]) / 3; + colors[2][2] = (2 * colors[0][2] + colors[1][2]) / 3; + + colors[3][0] = (colors[0][0] + 2 * colors[1][0]) / 3; + colors[3][1] = (colors[0][1] + 2 * colors[1][1]) / 3; + colors[3][2] = (colors[0][2] + 2 * colors[1][2]) / 3; + + for (int py = 0; py < 4; ++py) { + if (by * 4 + py >= height) continue; + uint16_t row_alpha = ReadU16(alpha_block + py * 2); + + for (int px = 0; px < 4; ++px) { + if (bx * 4 + px >= width) continue; + int color_idx = (code >> ((py * 4 + px) * 2)) & 3; + uint8_t a4 = (row_alpha >> (px * 4)) & 0x0F; + uint8_t alpha = a4 * 17; + + size_t dst_offset = ((by * 4 + py) * width + (bx * 4 + px)) * 4; + dst_rgba[dst_offset + 0] = colors[color_idx][0]; + dst_rgba[dst_offset + 1] = colors[color_idx][1]; + dst_rgba[dst_offset + 2] = colors[color_idx][2]; + dst_rgba[dst_offset + 3] = alpha; + } + } + + src_offset += 16; + } + } + return true; +} + +bool DxtDecoder::DecompressDXT5(const uint8_t* src, uint32_t width, uint32_t height, uint8_t* dst_rgba) { + if (!src || !dst_rgba || width == 0 || height == 0) return false; + + uint32_t block_x = (width + 3) / 4; + uint32_t block_y = (height + 3) / 4; + + size_t src_offset = 0; + for (uint32_t by = 0; by < block_y; ++by) { + for (uint32_t bx = 0; bx < block_x; ++bx) { + uint8_t a0 = src[src_offset + 0]; + uint8_t a1 = src[src_offset + 1]; + + uint64_t a_bits = 0; + for (int k = 0; k < 6; ++k) { + a_bits |= (static_cast(src[src_offset + 2 + k]) << (k * 8)); + } + + uint8_t alphas[8]; + alphas[0] = a0; + alphas[1] = a1; + if (a0 > a1) { + alphas[2] = (6 * a0 + 1 * a1) / 7; + alphas[3] = (5 * a0 + 2 * a1) / 7; + alphas[4] = (4 * a0 + 3 * a1) / 7; + alphas[5] = (3 * a0 + 4 * a1) / 7; + alphas[6] = (2 * a0 + 5 * a1) / 7; + alphas[7] = (1 * a0 + 6 * a1) / 7; + } else { + alphas[2] = (4 * a0 + 1 * a1) / 5; + alphas[3] = (3 * a0 + 2 * a1) / 5; + alphas[4] = (2 * a0 + 3 * a1) / 5; + alphas[5] = (1 * a0 + 4 * a1) / 5; + alphas[6] = 0; + alphas[7] = 255; + } + + const uint8_t* color_block = src + src_offset + 8; + uint16_t c0 = ReadU16(color_block); + uint16_t c1 = ReadU16(color_block + 2); + uint32_t code = ReadU32(color_block + 4); + + uint8_t colors[4][3]; + DecodeRGB565(c0, colors[0][0], colors[0][1], colors[0][2]); + DecodeRGB565(c1, colors[1][0], colors[1][1], colors[1][2]); + + colors[2][0] = (2 * colors[0][0] + colors[1][0]) / 3; + colors[2][1] = (2 * colors[0][1] + colors[1][1]) / 3; + colors[2][2] = (2 * colors[0][2] + colors[1][2]) / 3; + + colors[3][0] = (colors[0][0] + 2 * colors[1][0]) / 3; + colors[3][1] = (colors[0][1] + 2 * colors[1][1]) / 3; + colors[3][2] = (colors[0][2] + 2 * colors[1][2]) / 3; + + for (int py = 0; py < 4; ++py) { + if (by * 4 + py >= height) continue; + for (int px = 0; px < 4; ++px) { + if (bx * 4 + px >= width) continue; + int p_idx = py * 4 + px; + int color_idx = (code >> (p_idx * 2)) & 3; + int alpha_idx = (a_bits >> (p_idx * 3)) & 7; + + size_t dst_offset = ((by * 4 + py) * width + (bx * 4 + px)) * 4; + dst_rgba[dst_offset + 0] = colors[color_idx][0]; + dst_rgba[dst_offset + 1] = colors[color_idx][1]; + dst_rgba[dst_offset + 2] = colors[color_idx][2]; + dst_rgba[dst_offset + 3] = alphas[alpha_idx]; + } + } + + src_offset += 16; + } + } + return true; +} + +bool DxtDecoder::DecodeDDS(const uint8_t* dds_data, size_t size, ImageBuffer& out_image) { + if (!dds_data || size < 128) return false; + + // Magic 'DDS ' + if (dds_data[0] != 'D' || dds_data[1] != 'D' || dds_data[2] != 'S' || dds_data[3] != ' ') { + return false; + } + + uint32_t height = ReadU32(dds_data + 12); + uint32_t width = ReadU32(dds_data + 16); + uint32_t fourcc = ReadU32(dds_data + 84); + + if (width == 0 || height == 0) return false; + + out_image.width = width; + out_image.height = height; + out_image.format = EPixelFormat::RGBA8888; + out_image.pixels.resize(width * height * 4); + + const uint8_t* pixel_data = dds_data + 128; + + if (fourcc == 0x31545844) { // DXT1 + return DecompressDXT1(pixel_data, width, height, out_image.pixels.data()); + } else if (fourcc == 0x33545844) { // DXT3 + return DecompressDXT3(pixel_data, width, height, out_image.pixels.data()); + } else if (fourcc == 0x35545844) { // DXT5 + return DecompressDXT5(pixel_data, width, height, out_image.pixels.data()); + } + + return false; +} + +} // namespace metin2::texture diff --git a/texture/src/sub_image.cpp b/texture/src/sub_image.cpp new file mode 100644 index 0000000..44b30db --- /dev/null +++ b/texture/src/sub_image.cpp @@ -0,0 +1,144 @@ +#include "texture/sub_image.h" +#include +#include +#include + +namespace metin2::texture { + +namespace { + +inline std::string Trim(const std::string& str) { + size_t first = str.find_first_not_of(" \t\r\n"); + if (first == std::string::npos) return ""; + size_t last = str.find_last_not_of(" \t\r\n"); + return str.substr(first, (last - first + 1)); +} + +inline std::string ToLower(std::string str) { + std::transform(str.begin(), str.end(), str.begin(), [](unsigned char c) { + return static_cast(std::tolower(c)); + }); + return str; +} + +} // namespace + +bool SubImage::LoadFromFile(const std::string& file_path) { + std::ifstream file(file_path); + if (!file.is_open()) return false; + std::stringstream buffer; + buffer << file.rdbuf(); + return LoadFromString(buffer.str()); +} + +bool SubImage::LoadFromString(const std::string& content) { + std::istringstream stream(content); + std::string line; + + m_image_path.clear(); + m_rect = Rect2D(); + + while (std::getline(stream, line)) { + std::string trimmed = Trim(line); + if (trimmed.empty() || trimmed[0] == '#') continue; + + std::istringstream ls(trimmed); + std::string key; + ls >> key; + key = ToLower(key); + + std::string val; + ls >> std::ws; + std::getline(ls, val); + val = Trim(val); + if (val.size() >= 2 && val.front() == '"' && val.back() == '"') { + val = val.substr(1, val.size() - 2); + } + + if (key == "image") { + m_image_path = val; + } else if (key == "left") { + m_rect.left = std::stoi(val); + } else if (key == "top") { + m_rect.top = std::stoi(val); + } else if (key == "right") { + m_rect.right = std::stoi(val); + } else if (key == "bottom") { + m_rect.bottom = std::stoi(val); + } + } + + return !m_image_path.empty() && m_rect.GetWidth() > 0 && m_rect.GetHeight() > 0; +} + +UVRect SubImage::ComputeUV(uint32_t atlas_width, uint32_t atlas_height) const { + UVRect uv; + if (atlas_width == 0 || atlas_height == 0) return uv; + + float inv_w = 1.0f / static_cast(atlas_width); + float inv_h = 1.0f / static_cast(atlas_height); + + uv.u0 = static_cast(m_rect.left) * inv_w; + uv.v0 = static_cast(m_rect.top) * inv_h; + uv.u1 = static_cast(m_rect.right) * inv_w; + uv.v1 = static_cast(m_rect.bottom) * inv_h; + + return uv; +} + +NineSliceMesh SubImage::BuildNineSliceMesh(float x, float y, float width, float height, + float border_l, float border_t, float border_r, float border_b, + uint32_t atlas_width, uint32_t atlas_height, + uint32_t color) const { + NineSliceMesh mesh; + if (atlas_width == 0 || atlas_height == 0) return mesh; + + float inv_w = 1.0f / static_cast(atlas_width); + float inv_h = 1.0f / static_cast(atlas_height); + + float xs[4] = { x, x + border_l, x + width - border_r, x + width }; + float ys[4] = { y, y + border_t, y + height - border_b, y + height }; + + float us[4] = { + static_cast(m_rect.left) * inv_w, + static_cast(m_rect.left + border_l) * inv_w, + static_cast(m_rect.right - border_r) * inv_w, + static_cast(m_rect.right) * inv_w + }; + + float vs[4] = { + static_cast(m_rect.top) * inv_h, + static_cast(m_rect.top + border_t) * inv_h, + static_cast(m_rect.bottom - border_b) * inv_h, + static_cast(m_rect.bottom) * inv_h + }; + + mesh.vertices.reserve(16); + for (int r = 0; r < 4; ++r) { + for (int c = 0; c < 4; ++c) { + mesh.vertices.push_back({xs[c], ys[r], us[c], vs[r], color}); + } + } + + mesh.indices.reserve(54); // 9 quads * 6 indices + for (int r = 0; r < 3; ++r) { + for (int c = 0; c < 3; ++c) { + uint32_t i0 = r * 4 + c; + uint32_t i1 = r * 4 + (c + 1); + uint32_t i2 = (r + 1) * 4 + c; + uint32_t i3 = (r + 1) * 4 + (c + 1); + + mesh.indices.push_back(i0); + mesh.indices.push_back(i2); + mesh.indices.push_back(i1); + + mesh.indices.push_back(i1); + mesh.indices.push_back(i2); + mesh.indices.push_back(i3); + } + } + + return mesh; +} + +} // namespace metin2::texture diff --git a/texture/src/tga.cpp b/texture/src/tga.cpp new file mode 100644 index 0000000..ce7f4ec --- /dev/null +++ b/texture/src/tga.cpp @@ -0,0 +1,88 @@ +#include "texture/tga.h" +#include +#include + +namespace metin2::texture { + +bool TgaDecoder::DecodeTGA(const uint8_t* data, size_t size, ImageBuffer& out_image) { + if (!data || size < 18) return false; + + uint8_t id_length = data[0]; + uint8_t image_type = data[2]; + uint16_t width = static_cast(data[12]) | (static_cast(data[13]) << 8); + uint16_t height = static_cast(data[14]) | (static_cast(data[15]) << 8); + uint8_t bpp = data[16]; + uint8_t descriptor = data[17]; + + if (width == 0 || height == 0) return false; + if (bpp != 24 && bpp != 32) return false; + if (image_type != 2 && image_type != 10) return false; // Only uncompressed or RLE truecolor + + bool is_rle = (image_type == 10); + bool flip_vertically = !(descriptor & 0x20); // Bit 5: 0 means origin is bottom-left + + size_t pixel_bytes = bpp / 8; + size_t offset = 18 + id_length; + + out_image.width = width; + out_image.height = height; + out_image.format = EPixelFormat::RGBA8888; + out_image.pixels.resize(width * height * 4); + + std::vector raw_pixels(width * height * pixel_bytes); + + if (!is_rle) { + if (size < offset + width * height * pixel_bytes) return false; + std::memcpy(raw_pixels.data(), data + offset, width * height * pixel_bytes); + } else { + size_t current_pixel = 0; + size_t total_pixels = width * height; + + while (current_pixel < total_pixels && offset < size) { + uint8_t header = data[offset++]; + int count = (header & 0x7F) + 1; + + if (header & 0x80) { // RLE packet + if (offset + pixel_bytes > size) return false; + const uint8_t* p = data + offset; + offset += pixel_bytes; + + for (int i = 0; i < count && current_pixel < total_pixels; ++i) { + std::memcpy(raw_pixels.data() + current_pixel * pixel_bytes, p, pixel_bytes); + current_pixel++; + } + } else { // Raw packet + for (int i = 0; i < count && current_pixel < total_pixels; ++i) { + if (offset + pixel_bytes > size) return false; + std::memcpy(raw_pixels.data() + current_pixel * pixel_bytes, data + offset, pixel_bytes); + offset += pixel_bytes; + current_pixel++; + } + } + } + } + + // Convert BGR/BGRA to RGBA with vertical flip consideration + for (uint32_t y = 0; y < height; ++y) { + uint32_t src_y = flip_vertically ? (height - 1 - y) : y; + + for (uint32_t x = 0; x < width; ++x) { + size_t src_idx = (src_y * width + x) * pixel_bytes; + size_t dst_idx = (y * width + x) * 4; + + uint8_t b = raw_pixels[src_idx + 0]; + uint8_t g = raw_pixels[src_idx + 1]; + uint8_t r = raw_pixels[src_idx + 2]; + uint8_t a = (bpp == 32) ? raw_pixels[src_idx + 3] : 255; + + out_image.pixels[dst_idx + 0] = r; + out_image.pixels[dst_idx + 1] = g; + out_image.pixels[dst_idx + 2] = b; + out_image.pixels[dst_idx + 3] = a; + } + } + + return true; +} + +} // namespace metin2::texture diff --git a/texture/tests/texture_test.cpp b/texture/tests/texture_test.cpp new file mode 100644 index 0000000..fd76dbe --- /dev/null +++ b/texture/tests/texture_test.cpp @@ -0,0 +1,117 @@ +#include "texture/texture.h" +#include +#include +#include +#include + +using namespace metin2::texture; + +int main() { + std::cout << "[Test 1] DXT1 Decompression..." << std::endl; + // 4x4 block of DXT1: + // Color 0: Pure Red (0xF800 in RGB565) + // Color 1: Pure Blue (0x001F in RGB565) + // Color codes: 0x00000000 (all 16 pixels use Color 0) + uint8_t dxt1_block[8] = { + 0x00, 0xF8, // c0 = 0xF800 (Red) + 0x1F, 0x00, // c1 = 0x001F (Blue) + 0x00, 0x00, 0x00, 0x00 // all pixel indices = 0 (c0) + }; + + std::vector dst_rgba(4 * 4 * 4, 0); + bool ok_dxt1 = DxtDecoder::DecompressDXT1(dxt1_block, 4, 4, dst_rgba.data()); + assert(ok_dxt1); + + // Verify first pixel is Red + assert(dst_rgba[0] == 255); // R + assert(dst_rgba[1] == 0); // G + assert(dst_rgba[2] == 0); // B + assert(dst_rgba[3] == 255); // A + + std::cout << "[Test 2] DXT5 Decompression..." << std::endl; + // 4x4 block of DXT5: + // Alpha 0: 255, Alpha 1: 0, Indices: all 0 (Alpha 0) + // Color 0: Pure Green (0x07E0), Color 1: Black (0x0000), Indices: all 0 + uint8_t dxt5_block[16] = { + 255, 0, // a0 = 255, a1 = 0 + 0, 0, 0, 0, 0, 0, // alpha indices = 0 + 0xE0, 0x07, // c0 = 0x07E0 (Green) + 0x00, 0x00, // c1 = 0x0000 (Black) + 0x00, 0x00, 0x00, 0x00 // color indices = 0 + }; + std::vector dst_dxt5(4 * 4 * 4, 0); + bool ok_dxt5 = DxtDecoder::DecompressDXT5(dxt5_block, 4, 4, dst_dxt5.data()); + assert(ok_dxt5); + assert(dst_dxt5[0] == 0); // R + assert(dst_dxt5[1] == 255); // G + assert(dst_dxt5[2] == 0); // B + assert(dst_dxt5[3] == 255); // A + + std::cout << "[Test 3] TGA Uncompressed 24-bit Decompression..." << std::endl; + // 2x2 uncompressed 24-bit TGA: + // Header 18 bytes: width=2, height=2, bpp=24, image_type=2, descriptor=0x20 (top-left) + uint8_t tga_header[18] = { + 0, 0, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 2, 0, // width = 2 + 2, 0, // height = 2 + 24, // bpp = 24 + 0x20 // top-to-bottom + }; + // 4 pixels BGR: all yellow (B=0, G=255, R=255) + uint8_t tga_pixels[12] = { + 0, 255, 255, + 0, 255, 255, + 0, 255, 255, + 0, 255, 255 + }; + std::vector tga_data(18 + 12); + std::memcpy(tga_data.data(), tga_header, 18); + std::memcpy(tga_data.data() + 18, tga_pixels, 12); + + ImageBuffer tga_img; + bool ok_tga = TgaDecoder::DecodeTGA(tga_data.data(), tga_data.size(), tga_img); + assert(ok_tga); + assert(tga_img.width == 2); + assert(tga_img.height == 2); + assert(tga_img.pixels[0] == 255); // R + assert(tga_img.pixels[1] == 255); // G + assert(tga_img.pixels[2] == 0); // B + assert(tga_img.pixels[3] == 255); // A + + std::cout << "[Test 4] SubImage (.sub) parsing and Atlas UV computation..." << std::endl; + const std::string sample_sub = + "title subImage\r\n" + "version 0.1\r\n" + "image \"d:/ymir work/ui/public.dds\"\r\n" + "left 64\r\n" + "top 128\r\n" + "right 128\r\n" + "bottom 192\r\n"; + + SubImage sub; + bool ok_sub = sub.LoadFromString(sample_sub); + assert(ok_sub); + assert(sub.GetImagePath() == "d:/ymir work/ui/public.dds"); + assert(sub.GetWidth() == 64); + assert(sub.GetHeight() == 64); + + UVRect uv = sub.ComputeUV(256, 256); + assert(std::abs(uv.u0 - 0.25f) < 1e-4f); + assert(std::abs(uv.v0 - 0.50f) < 1e-4f); + assert(std::abs(uv.u1 - 0.50f) < 1e-4f); + assert(std::abs(uv.v1 - 0.75f) < 1e-4f); + + std::cout << "[Test 5] 9-Slice Mesh Generation..." << std::endl; + NineSliceMesh mesh = sub.BuildNineSliceMesh(100.0f, 100.0f, 200.0f, 200.0f, 10.0f, 10.0f, 10.0f, 10.0f, 256, 256); + assert(mesh.vertices.size() == 16); + assert(mesh.indices.size() == 54); + // Check top-left corner vertex + assert(mesh.vertices[0].x == 100.0f); + assert(mesh.vertices[0].y == 100.0f); + // Check bottom-right corner vertex + assert(mesh.vertices[15].x == 300.0f); + assert(mesh.vertices[15].y == 300.0f); + + std::cout << "All Texture SDK tests passed successfully!" << std::endl; + return 0; +} diff --git a/ui_core/CMakeLists.txt b/ui_core/CMakeLists.txt new file mode 100644 index 0000000..f0f8c83 --- /dev/null +++ b/ui_core/CMakeLists.txt @@ -0,0 +1,31 @@ +cmake_minimum_required(VERSION 3.20) +project(ui_core LANGUAGES CXX) + +set(CMAKE_CXX_STANDARD 20) +set(CMAKE_CXX_STANDARD_REQUIRED ON) + +add_library(ui_core STATIC + src/ui_element.cpp + src/ui_window.cpp + src/ui_button.cpp + src/ui_text.cpp + src/ui_slot.cpp + src/ui_grid.cpp + src/ui_manager.cpp +) + +target_include_directories(ui_core PUBLIC + $ + $ +) + +target_link_libraries(ui_core PUBLIC texture) + +add_library(ui_core::ui_core ALIAS ui_core) + +option(UI_CORE_BUILD_TESTS "Build UI Core SDK tests" ON) +if(UI_CORE_BUILD_TESTS) + add_executable(ui_core_test tests/ui_core_test.cpp) + target_link_libraries(ui_core_test PRIVATE ui_core) + add_test(NAME ui_core_test COMMAND ui_core_test) +endif() diff --git a/ui_core/include/ui_core/types.h b/ui_core/include/ui_core/types.h new file mode 100644 index 0000000..e46f661 --- /dev/null +++ b/ui_core/include/ui_core/types.h @@ -0,0 +1,106 @@ +#pragma once + +#include +#include +#include +#include +#include + +namespace metin2::ui_core { + +struct Vec2 { + float x = 0.0f; + float y = 0.0f; + + constexpr Vec2() = default; + constexpr Vec2(float in_x, float in_y) : x(in_x), y(in_y) {} + + Vec2 operator+(const Vec2& o) const { return {x + o.x, y + o.y}; } + Vec2 operator-(const Vec2& o) const { return {x - o.x, y - o.y}; } + Vec2 operator*(float s) const { return {x * s, y * s}; } + Vec2& operator+=(const Vec2& o) { x += o.x; y += o.y; return *this; } + Vec2& operator-=(const Vec2& o) { x -= o.x; y -= o.y; return *this; } +}; + +struct Rect { + float x = 0.0f; + float y = 0.0f; + float width = 0.0f; + float height = 0.0f; + + constexpr Rect() = default; + constexpr Rect(float in_x, float in_y, float in_w, float in_h) + : x(in_x), y(in_y), width(in_w), height(in_h) {} + + float GetLeft() const { return x; } + float GetTop() const { return y; } + float GetRight() const { return x + width; } + float GetBottom() const { return y + height; } + + bool Contains(float px, float py) const { + return px >= x && px <= (x + width) && py >= y && py <= (y + height); + } + bool Contains(const Vec2& p) const { return Contains(p.x, p.y); } + + bool Intersects(const Rect& o) const { + return !(x + width < o.x || o.x + o.width < x || + y + height < o.y || o.y + o.height < y); + } +}; + +enum class UIAnchor : uint8_t { + TopLeft = 0, + TopCenter, + TopRight, + CenterLeft, + Center, + CenterRight, + BottomLeft, + BottomCenter, + BottomRight, + StretchHorizontal, + StretchVertical, + StretchAll +}; + +enum class UIEventType : uint8_t { + MouseDown = 0, + MouseUp, + MouseMove, + MouseEnter, + MouseLeave, + Click, + DoubleClick, + DragBegin, + DragUpdate, + DragEnd, + Drop, + KeyDown, + KeyUp +}; + +struct UIEvent { + UIEventType type = UIEventType::MouseMove; + Vec2 mouse_pos{0.0f, 0.0f}; + Vec2 delta_pos{0.0f, 0.0f}; + int mouse_button = 0; // 0: Left, 1: Right, 2: Middle + int key_code = 0; + void* payload = nullptr; + bool handled = false; +}; + +struct UIVertex { + float x = 0.0f; + float y = 0.0f; + float u = 0.0f; + float v = 0.0f; + uint32_t color = 0xFFFFFFFF; +}; + +struct UIRenderBatch { + std::string texture_path; + std::vector vertices; + std::vector indices; +}; + +} // namespace metin2::ui_core diff --git a/ui_core/include/ui_core/ui_button.h b/ui_core/include/ui_core/ui_button.h new file mode 100644 index 0000000..d7c9f0a --- /dev/null +++ b/ui_core/include/ui_core/ui_button.h @@ -0,0 +1,41 @@ +#pragma once + +#include "ui_element.h" +#include + +namespace metin2::ui_core { + +enum class ButtonState : uint8_t { + Normal = 0, + Hovered, + Pressed, + Disabled +}; + +class UIButton : public UIElement { +public: + using ClickCallback = std::function; + + UIButton(); + + void SetText(const std::string& text) { m_text = text; } + const std::string& GetText() const { return m_text; } + + void SetOnClick(ClickCallback cb) { m_on_click = std::move(cb); } + + ButtonState GetButtonState() const; + + void OnMouseDown(UIEvent& event) override; + void OnMouseUp(UIEvent& event) override; + void OnMouseEnter(UIEvent& event) override; + void OnMouseLeave(UIEvent& event) override; + void OnClick(UIEvent& event) override; + + void GenerateRenderBatches(std::vector& out_batches) override; + +private: + std::string m_text; + ClickCallback m_on_click; +}; + +} // namespace metin2::ui_core diff --git a/ui_core/include/ui_core/ui_core.h b/ui_core/include/ui_core/ui_core.h new file mode 100644 index 0000000..fef4917 --- /dev/null +++ b/ui_core/include/ui_core/ui_core.h @@ -0,0 +1,10 @@ +#pragma once + +#include "types.h" +#include "ui_element.h" +#include "ui_window.h" +#include "ui_button.h" +#include "ui_text.h" +#include "ui_slot.h" +#include "ui_grid.h" +#include "ui_manager.h" diff --git a/ui_core/include/ui_core/ui_element.h b/ui_core/include/ui_core/ui_element.h new file mode 100644 index 0000000..56b043a --- /dev/null +++ b/ui_core/include/ui_core/ui_element.h @@ -0,0 +1,114 @@ +#pragma once + +#include "types.h" +#include +#include +#include +#include + +namespace metin2::ui_core { + +class UIElement : public std::enable_shared_from_this { +public: + using EventHandler = std::function; + + UIElement(); + virtual ~UIElement() = default; + + // Hierarchy + void AddChild(std::shared_ptr child); + void RemoveChild(std::shared_ptr child); + void RemoveFromParent(); + UIElement* GetParent() const { return m_parent; } + const std::vector>& GetChildren() const { return m_children; } + + // Identification & Tagging + void SetName(const std::string& name) { m_name = name; } + const std::string& GetName() const { return m_name; } + void SetId(uint32_t id) { m_id = id; } + uint32_t GetId() const { return m_id; } + + // Transform & Layout + void SetPosition(float x, float y) { m_local_rect.x = x; m_local_rect.y = y; } + void SetSize(float w, float h) { m_local_rect.width = w; m_local_rect.height = h; } + void SetAnchor(UIAnchor anchor) { m_anchor = anchor; } + UIAnchor GetAnchor() const { return m_anchor; } + + const Rect& GetLocalRect() const { return m_local_rect; } + const Rect& GetGlobalRect() const { return m_global_rect; } + + virtual void UpdateLayout(const Rect& parent_rect); + + // Visibility & Interaction + void SetVisible(bool visible) { m_visible = visible; } + bool IsVisible() const { return m_visible; } + void SetEnabled(bool enabled) { m_enabled = enabled; } + bool IsEnabled() const { return m_enabled; } + + // State Tracking + bool IsHovered() const { return m_is_hovered; } + bool IsPressed() const { return m_is_pressed; } + bool IsFocused() const { return m_is_focused; } + bool IsDragging() const { return m_is_dragging; } + + void SetHovered(bool hovered) { m_is_hovered = hovered; } + void SetPressed(bool pressed) { m_is_pressed = pressed; } + void SetFocused(bool focused) { m_is_focused = focused; } + void SetDragging(bool dragging) { m_is_dragging = dragging; } + + // Nine-Slice Background Support + void SetNineSlice(const std::string& texture, float border_l, float border_t, float border_r, float border_b); + void SetBackgroundColor(uint32_t color) { m_bg_color = color; } + + // Hit Testing & Event Dispatch with Bubbling + virtual std::shared_ptr HitTest(float px, float py); + virtual void DispatchEvent(UIEvent& event); + + // Event Hooks for Subclasses + virtual void OnMouseDown(UIEvent& event) {} + virtual void OnMouseUp(UIEvent& event) {} + virtual void OnMouseMove(UIEvent& event) {} + virtual void OnMouseEnter(UIEvent& event) {} + virtual void OnMouseLeave(UIEvent& event) {} + virtual void OnClick(UIEvent& event) {} + virtual void OnDragBegin(UIEvent& event) {} + virtual void OnDragUpdate(UIEvent& event) {} + virtual void OnDragEnd(UIEvent& event) {} + virtual void OnDrop(UIEvent& event) {} + + // Event Handler Registration + void SetOnEvent(EventHandler handler) { m_event_handler = std::move(handler); } + + // Rendering Batch Generation + virtual void GenerateRenderBatches(std::vector& out_batches); + +protected: + void AppendQuad(UIRenderBatch& batch, float x, float y, float w, float h, + float u0, float v0, float u1, float v1, uint32_t color); + + std::string m_name; + uint32_t m_id = 0; + UIElement* m_parent = nullptr; + std::vector> m_children; + + Rect m_local_rect{0.0f, 0.0f, 0.0f, 0.0f}; + Rect m_global_rect{0.0f, 0.0f, 0.0f, 0.0f}; + UIAnchor m_anchor = UIAnchor::TopLeft; + + bool m_visible = true; + bool m_enabled = true; + bool m_is_hovered = false; + bool m_is_pressed = false; + bool m_is_focused = false; + bool m_is_dragging = false; + + // Nine-Slice properties + bool m_has_nine_slice = false; + std::string m_nine_slice_texture; + float m_border_l = 0.0f, m_border_t = 0.0f, m_border_r = 0.0f, m_border_b = 0.0f; + uint32_t m_bg_color = 0xFFFFFFFF; + + EventHandler m_event_handler; +}; + +} // namespace metin2::ui_core diff --git a/ui_core/include/ui_core/ui_grid.h b/ui_core/include/ui_core/ui_grid.h new file mode 100644 index 0000000..5118206 --- /dev/null +++ b/ui_core/include/ui_core/ui_grid.h @@ -0,0 +1,39 @@ +#pragma once + +#include "ui_element.h" +#include "ui_slot.h" +#include + +namespace metin2::ui_core { + +class UIGrid : public UIElement { +public: + UIGrid(uint32_t cols = 5, uint32_t rows = 9, float slot_size = 32.0f, float slot_spacing = 2.0f); + + uint32_t GetCols() const { return m_cols; } + uint32_t GetRows() const { return m_rows; } + float GetSlotSize() const { return m_slot_size; } + float GetSlotSpacing() const { return m_slot_spacing; } + + std::shared_ptr GetSlot(uint32_t col, uint32_t row) const; + std::shared_ptr GetSlotByIndex(uint32_t index) const; + + bool SetItemAt(uint32_t col, uint32_t row, uint32_t item_vnum, uint32_t count = 1); + void ClearItemAt(uint32_t col, uint32_t row); + + // Multi-cell footprint check (e.g. 1x2 dagger, 1x3 greatsword) + bool CanPlaceItem(uint32_t col, uint32_t row, uint32_t cell_width, uint32_t cell_height) const; + + void UpdateLayout(const Rect& parent_rect) override; + +private: + void RebuildSlots(); + + uint32_t m_cols = 5; + uint32_t m_rows = 9; + float m_slot_size = 32.0f; + float m_slot_spacing = 2.0f; + std::vector> m_slots; +}; + +} // namespace metin2::ui_core diff --git a/ui_core/include/ui_core/ui_manager.h b/ui_core/include/ui_core/ui_manager.h new file mode 100644 index 0000000..c35cae9 --- /dev/null +++ b/ui_core/include/ui_core/ui_manager.h @@ -0,0 +1,55 @@ +#pragma once + +#include "ui_element.h" +#include +#include + +namespace metin2::ui_core { + +class UIManager { +public: + UIManager(float screen_width = 1920.0f, float screen_height = 1080.0f); + + void SetScreenSize(float width, float height); + Vec2 GetScreenSize() const { return {m_screen_rect.width, m_screen_rect.height}; } + + std::shared_ptr GetRoot() const { return m_root; } + + // Child Management on Root + void AddElement(std::shared_ptr element); + void RemoveElement(std::shared_ptr element); + + // Layout Resolution + void UpdateLayout(); + + // Input Injection + bool InjectMouseDown(float x, float y, int button); + bool InjectMouseUp(float x, float y, int button); + bool InjectMouseMove(float x, float y); + bool InjectKeyDown(int key_code); + bool InjectKeyUp(int key_code); + + // Drag & Drop State + bool IsDragging() const { return m_dragged_element != nullptr; } + std::shared_ptr GetDraggedElement() const { return m_dragged_element; } + void CancelDrag(); + + // Rendering Pipeline Output + std::vector GenerateRenderBatches(); + +private: + Rect m_screen_rect{0.0f, 0.0f, 1920.0f, 1080.0f}; + std::shared_ptr m_root; + + std::shared_ptr m_hovered_element; + std::shared_ptr m_focused_element; + std::shared_ptr m_pressed_element; + std::shared_ptr m_dragged_element; + + Vec2 m_last_mouse_pos{0.0f, 0.0f}; + Vec2 m_drag_start_pos{0.0f, 0.0f}; + bool m_mouse_down = false; + int m_active_button = 0; +}; + +} // namespace metin2::ui_core diff --git a/ui_core/include/ui_core/ui_slot.h b/ui_core/include/ui_core/ui_slot.h new file mode 100644 index 0000000..5a68359 --- /dev/null +++ b/ui_core/include/ui_core/ui_slot.h @@ -0,0 +1,49 @@ +#pragma once + +#include "ui_element.h" + +namespace metin2::ui_core { + +class UISlot : public UIElement { +public: + using SlotDropCallback = std::function; + + UISlot(); + explicit UISlot(uint32_t slot_index); + + void SetSlotIndex(uint32_t idx) { m_slot_index = idx; } + uint32_t GetSlotIndex() const { return m_slot_index; } + + void SetItem(uint32_t item_vnum, uint32_t count = 1); + void ClearItem(); + bool HasItem() const { return m_item_vnum > 0 && m_item_count > 0; } + + uint32_t GetItemVnum() const { return m_item_vnum; } + uint32_t GetItemCount() const { return m_item_count; } + + // Cooldown progress [0.0f, 1.0f] (0.0: ready, 1.0: full cooldown) + void SetCooldown(float progress) { m_cooldown_progress = std::clamp(progress, 0.0f, 1.0f); } + float GetCooldown() const { return m_cooldown_progress; } + + void SetSelected(bool selected) { m_is_selected = selected; } + bool IsSelected() const { return m_is_selected; } + + void SetOnDrop(SlotDropCallback cb) { m_on_drop = std::move(cb); } + + // Drag and Drop + void OnMouseDown(UIEvent& event) override; + void OnDragBegin(UIEvent& event) override; + void OnDrop(UIEvent& event) override; + + void GenerateRenderBatches(std::vector& out_batches) override; + +private: + uint32_t m_slot_index = 0; + uint32_t m_item_vnum = 0; + uint32_t m_item_count = 0; + float m_cooldown_progress = 0.0f; + bool m_is_selected = false; + SlotDropCallback m_on_drop; +}; + +} // namespace metin2::ui_core diff --git a/ui_core/include/ui_core/ui_text.h b/ui_core/include/ui_core/ui_text.h new file mode 100644 index 0000000..446ddc5 --- /dev/null +++ b/ui_core/include/ui_core/ui_text.h @@ -0,0 +1,39 @@ +#pragma once + +#include "ui_element.h" + +namespace metin2::ui_core { + +enum class TextAlignment : uint8_t { + Left = 0, + Center, + Right +}; + +class UIText : public UIElement { +public: + UIText(); + explicit UIText(const std::string& text); + + void SetText(const std::string& text) { m_text = text; } + const std::string& GetText() const { return m_text; } + + void SetTextColor(uint32_t color) { m_text_color = color; } + uint32_t GetTextColor() const { return m_text_color; } + + void SetAlignment(TextAlignment align) { m_alignment = align; } + TextAlignment GetAlignment() const { return m_alignment; } + + void SetFontSize(float size) { m_font_size = size; } + float GetFontSize() const { return m_font_size; } + + void GenerateRenderBatches(std::vector& out_batches) override; + +private: + std::string m_text; + uint32_t m_text_color = 0xFFFFFFFF; + TextAlignment m_alignment = TextAlignment::Left; + float m_font_size = 14.0f; +}; + +} // namespace metin2::ui_core diff --git a/ui_core/include/ui_core/ui_window.h b/ui_core/include/ui_core/ui_window.h new file mode 100644 index 0000000..370988c --- /dev/null +++ b/ui_core/include/ui_core/ui_window.h @@ -0,0 +1,35 @@ +#pragma once + +#include "ui_element.h" + +namespace metin2::ui_core { + +class UIWindow : public UIElement { +public: + UIWindow(); + + void SetTitle(const std::string& title) { m_title = title; } + const std::string& GetTitle() const { return m_title; } + + void SetTitleBarHeight(float height) { m_title_bar_height = height; } + float GetTitleBarHeight() const { return m_title_bar_height; } + + void SetMovable(bool movable) { m_is_movable = movable; } + bool IsMovable() const { return m_is_movable; } + + void OnMouseDown(UIEvent& event) override; + void OnMouseMove(UIEvent& event) override; + void OnMouseUp(UIEvent& event) override; + + void GenerateRenderBatches(std::vector& out_batches) override; + +private: + std::string m_title; + float m_title_bar_height = 24.0f; + bool m_is_movable = true; + bool m_dragging_title_bar = false; + Vec2 m_drag_start_mouse{0.0f, 0.0f}; + Vec2 m_drag_start_pos{0.0f, 0.0f}; +}; + +} // namespace metin2::ui_core diff --git a/ui_core/src/ui_button.cpp b/ui_core/src/ui_button.cpp new file mode 100644 index 0000000..a4dfeb1 --- /dev/null +++ b/ui_core/src/ui_button.cpp @@ -0,0 +1,73 @@ +#include "ui_core/ui_button.h" + +namespace metin2::ui_core { + +UIButton::UIButton() { + m_bg_color = 0xFF3D3D3D; + m_local_rect.width = 80.0f; + m_local_rect.height = 28.0f; +} + +ButtonState UIButton::GetButtonState() const { + if (!m_enabled) return ButtonState::Disabled; + if (m_is_pressed) return ButtonState::Pressed; + if (m_is_hovered) return ButtonState::Hovered; + return ButtonState::Normal; +} + +void UIButton::OnMouseEnter(UIEvent& event) { + m_is_hovered = true; +} + +void UIButton::OnMouseLeave(UIEvent& event) { + m_is_hovered = false; + m_is_pressed = false; +} + +void UIButton::OnMouseDown(UIEvent& event) { + if (event.mouse_button == 0 && m_enabled) { + m_is_pressed = true; + event.handled = true; + } +} + +void UIButton::OnMouseUp(UIEvent& event) { + if (event.mouse_button == 0 && m_is_pressed) { + m_is_pressed = false; + if (m_global_rect.Contains(event.mouse_pos.x, event.mouse_pos.y)) { + OnClick(event); + } + event.handled = true; + } +} + +void UIButton::OnClick(UIEvent& event) { + if (m_enabled && m_on_click) { + m_on_click(); + event.handled = true; + } +} + +void UIButton::GenerateRenderBatches(std::vector& out_batches) { + if (!m_visible) return; + + uint32_t current_color = m_bg_color; + switch (GetButtonState()) { + case ButtonState::Normal: current_color = 0xFF4A4A4A; break; + case ButtonState::Hovered: current_color = 0xFF606060; break; + case ButtonState::Pressed: current_color = 0xFF2A2A2A; break; + case ButtonState::Disabled: current_color = 0xFF252525; break; + } + + UIRenderBatch batch; + AppendQuad(batch, m_global_rect.x, m_global_rect.y, m_global_rect.width, m_global_rect.height, + 0.0f, 0.0f, 1.0f, 1.0f, current_color); + out_batches.push_back(std::move(batch)); + + // Base children + for (auto& child : m_children) { + if (child) child->GenerateRenderBatches(out_batches); + } +} + +} // namespace metin2::ui_core diff --git a/ui_core/src/ui_element.cpp b/ui_core/src/ui_element.cpp new file mode 100644 index 0000000..f62c953 --- /dev/null +++ b/ui_core/src/ui_element.cpp @@ -0,0 +1,236 @@ +#include "ui_core/ui_element.h" +#include + +namespace metin2::ui_core { + +UIElement::UIElement() = default; + +void UIElement::AddChild(std::shared_ptr child) { + if (!child || child.get() == this) return; + + if (child->m_parent) { + child->RemoveFromParent(); + } + + child->m_parent = this; + m_children.push_back(child); +} + +void UIElement::RemoveChild(std::shared_ptr child) { + auto it = std::find(m_children.begin(), m_children.end(), child); + if (it != m_children.end()) { + (*it)->m_parent = nullptr; + m_children.erase(it); + } +} + +void UIElement::RemoveFromParent() { + if (m_parent) { + auto shared_this = shared_from_this(); + m_parent->RemoveChild(shared_this); + } +} + +void UIElement::SetNineSlice(const std::string& texture, float border_l, float border_t, float border_r, float border_b) { + m_has_nine_slice = true; + m_nine_slice_texture = texture; + m_border_l = border_l; + m_border_t = border_t; + m_border_r = border_r; + m_border_b = border_b; +} + +void UIElement::UpdateLayout(const Rect& parent_rect) { + float gx = 0.0f; + float gy = 0.0f; + float gw = m_local_rect.width; + float gh = m_local_rect.height; + + switch (m_anchor) { + case UIAnchor::TopLeft: + gx = parent_rect.x + m_local_rect.x; + gy = parent_rect.y + m_local_rect.y; + break; + case UIAnchor::TopCenter: + gx = parent_rect.x + (parent_rect.width - gw) * 0.5f + m_local_rect.x; + gy = parent_rect.y + m_local_rect.y; + break; + case UIAnchor::TopRight: + gx = parent_rect.x + parent_rect.width - gw + m_local_rect.x; + gy = parent_rect.y + m_local_rect.y; + break; + case UIAnchor::CenterLeft: + gx = parent_rect.x + m_local_rect.x; + gy = parent_rect.y + (parent_rect.height - gh) * 0.5f + m_local_rect.y; + break; + case UIAnchor::Center: + gx = parent_rect.x + (parent_rect.width - gw) * 0.5f + m_local_rect.x; + gy = parent_rect.y + (parent_rect.height - gh) * 0.5f + m_local_rect.y; + break; + case UIAnchor::CenterRight: + gx = parent_rect.x + parent_rect.width - gw + m_local_rect.x; + gy = parent_rect.y + (parent_rect.height - gh) * 0.5f + m_local_rect.y; + break; + case UIAnchor::BottomLeft: + gx = parent_rect.x + m_local_rect.x; + gy = parent_rect.y + parent_rect.height - gh + m_local_rect.y; + break; + case UIAnchor::BottomCenter: + gx = parent_rect.x + (parent_rect.width - gw) * 0.5f + m_local_rect.x; + gy = parent_rect.y + parent_rect.height - gh + m_local_rect.y; + break; + case UIAnchor::BottomRight: + gx = parent_rect.x + parent_rect.width - gw + m_local_rect.x; + gy = parent_rect.y + parent_rect.height - gh + m_local_rect.y; + break; + case UIAnchor::StretchHorizontal: + gx = parent_rect.x + m_local_rect.x; + gy = parent_rect.y + m_local_rect.y; + gw = parent_rect.width - m_local_rect.x * 2.0f; + break; + case UIAnchor::StretchVertical: + gx = parent_rect.x + m_local_rect.x; + gy = parent_rect.y + m_local_rect.y; + gh = parent_rect.height - m_local_rect.y * 2.0f; + break; + case UIAnchor::StretchAll: + gx = parent_rect.x + m_local_rect.x; + gy = parent_rect.y + m_local_rect.y; + gw = parent_rect.width - m_local_rect.x * 2.0f; + gh = parent_rect.height - m_local_rect.y * 2.0f; + break; + } + + m_global_rect = Rect(gx, gy, gw, gh); + + // Recursively update all children + for (auto& child : m_children) { + if (child) { + child->UpdateLayout(m_global_rect); + } + } +} + +std::shared_ptr UIElement::HitTest(float px, float py) { + if (!m_visible || !m_enabled) { + return nullptr; + } + + if (!m_global_rect.Contains(px, py)) { + return nullptr; + } + + // Children tested in reverse order (topmost first) + for (auto it = m_children.rbegin(); it != m_children.rend(); ++it) { + if (*it) { + auto hit = (*it)->HitTest(px, py); + if (hit) { + return hit; + } + } + } + + return shared_from_this(); +} + +void UIElement::DispatchEvent(UIEvent& event) { + // 1. Invoke element specific virtual hook + switch (event.type) { + case UIEventType::MouseDown: OnMouseDown(event); break; + case UIEventType::MouseUp: OnMouseUp(event); break; + case UIEventType::MouseMove: OnMouseMove(event); break; + case UIEventType::MouseEnter: OnMouseEnter(event); break; + case UIEventType::MouseLeave: OnMouseLeave(event); break; + case UIEventType::Click: OnClick(event); break; + case UIEventType::DragBegin: OnDragBegin(event); break; + case UIEventType::DragUpdate: OnDragUpdate(event); break; + case UIEventType::DragEnd: OnDragEnd(event); break; + case UIEventType::Drop: OnDrop(event); break; + default: break; + } + + // 2. Invoke custom event callback + if (m_event_handler) { + m_event_handler(event); + } + + // 3. Event Bubbling: if unhandled, bubble up to parent + if (!event.handled && m_parent) { + m_parent->DispatchEvent(event); + } +} + +void UIElement::AppendQuad(UIRenderBatch& batch, float x, float y, float w, float h, + float u0, float v0, float u1, float v1, uint32_t color) { + uint32_t base_index = static_cast(batch.vertices.size()); + + batch.vertices.push_back({x, y, u0, v0, color}); + batch.vertices.push_back({x + w, y, u1, v0, color}); + batch.vertices.push_back({x + w, y + h, u1, v1, color}); + batch.vertices.push_back({x, y + h, u0, v1, color}); + + batch.indices.push_back(base_index + 0); + batch.indices.push_back(base_index + 1); + batch.indices.push_back(base_index + 2); + batch.indices.push_back(base_index + 0); + batch.indices.push_back(base_index + 2); + batch.indices.push_back(base_index + 3); +} + +void UIElement::GenerateRenderBatches(std::vector& out_batches) { + if (!m_visible) return; + + if (m_has_nine_slice && !m_nine_slice_texture.empty()) { + UIRenderBatch batch; + batch.texture_path = m_nine_slice_texture; + + float x = m_global_rect.x; + float y = m_global_rect.y; + float w = m_global_rect.width; + float h = m_global_rect.height; + + float bl = m_border_l; + float bt = m_border_t; + float br = m_border_r; + float bb = m_border_b; + + float center_w = std::max(0.0f, w - bl - br); + float center_h = std::max(0.0f, h - bt - bb); + + // UV borders (assuming normalized 1.0 atlas or 9-slice) + float u_l = 0.25f, u_r = 0.75f; + float v_t = 0.25f, v_b = 0.75f; + + // 3x3 Grid patches: + // Top row + AppendQuad(batch, x, y, bl, bt, 0.0f, 0.0f, u_l, v_t, m_bg_color); + AppendQuad(batch, x + bl, y, center_w, bt, u_l, 0.0f, u_r, v_t, m_bg_color); + AppendQuad(batch, x + bl + center_w, y, br, bt, u_r, 0.0f, 1.0f, v_t, m_bg_color); + + // Middle row + AppendQuad(batch, x, y + bt, bl, center_h, 0.0f, v_t, u_l, v_b, m_bg_color); + AppendQuad(batch, x + bl, y + bt, center_w, center_h, u_l, v_t, u_r, v_b, m_bg_color); + AppendQuad(batch, x + bl + center_w, y + bt, br, center_h, u_r, v_t, 1.0f, v_b, m_bg_color); + + // Bottom row + AppendQuad(batch, x, y + bt + center_h, bl, bb, 0.0f, v_b, u_l, 1.0f, m_bg_color); + AppendQuad(batch, x + bl, y + bt + center_h, center_w, bb, u_l, v_b, u_r, 1.0f, m_bg_color); + AppendQuad(batch, x + bl + center_w, y + bt + center_h, br, bb, u_r, v_b, 1.0f, 1.0f, m_bg_color); + + out_batches.push_back(std::move(batch)); + } else if (m_bg_color != 0) { + UIRenderBatch batch; + AppendQuad(batch, m_global_rect.x, m_global_rect.y, m_global_rect.width, m_global_rect.height, + 0.0f, 0.0f, 1.0f, 1.0f, m_bg_color); + out_batches.push_back(std::move(batch)); + } + + // Children batches + for (auto& child : m_children) { + if (child) { + child->GenerateRenderBatches(out_batches); + } + } +} + +} // namespace metin2::ui_core diff --git a/ui_core/src/ui_grid.cpp b/ui_core/src/ui_grid.cpp new file mode 100644 index 0000000..785d691 --- /dev/null +++ b/ui_core/src/ui_grid.cpp @@ -0,0 +1,82 @@ +#include "ui_core/ui_grid.h" + +namespace metin2::ui_core { + +UIGrid::UIGrid(uint32_t cols, uint32_t rows, float slot_size, float slot_spacing) + : m_cols(cols) + , m_rows(rows) + , m_slot_size(slot_size) + , m_slot_spacing(slot_spacing) { + m_local_rect.width = m_cols * m_slot_size + (m_cols > 1 ? (m_cols - 1) * m_slot_spacing : 0); + m_local_rect.height = m_rows * m_slot_size + (m_rows > 1 ? (m_rows - 1) * m_slot_spacing : 0); + RebuildSlots(); +} + +void UIGrid::RebuildSlots() { + m_slots.clear(); + m_children.clear(); + + uint32_t total = m_cols * m_rows; + m_slots.reserve(total); + + for (uint32_t r = 0; r < m_rows; ++r) { + for (uint32_t c = 0; c < m_cols; ++c) { + uint32_t idx = r * m_cols + c; + auto slot = std::make_shared(idx); + float lx = c * (m_slot_size + m_slot_spacing); + float ly = r * (m_slot_size + m_slot_spacing); + slot->SetPosition(lx, ly); + slot->SetSize(m_slot_size, m_slot_size); + m_slots.push_back(slot); + AddChild(slot); + } + } +} + +std::shared_ptr UIGrid::GetSlot(uint32_t col, uint32_t row) const { + if (col >= m_cols || row >= m_rows) return nullptr; + uint32_t idx = row * m_cols + col; + return m_slots[idx]; +} + +std::shared_ptr UIGrid::GetSlotByIndex(uint32_t index) const { + if (index >= m_slots.size()) return nullptr; + return m_slots[index]; +} + +bool UIGrid::SetItemAt(uint32_t col, uint32_t row, uint32_t item_vnum, uint32_t count) { + auto slot = GetSlot(col, row); + if (!slot) return false; + slot->SetItem(item_vnum, count); + return true; +} + +void UIGrid::ClearItemAt(uint32_t col, uint32_t row) { + auto slot = GetSlot(col, row); + if (slot) { + slot->ClearItem(); + } +} + +bool UIGrid::CanPlaceItem(uint32_t col, uint32_t row, uint32_t cell_width, uint32_t cell_height) const { + if (col + cell_width > m_cols || row + cell_height > m_rows) { + return false; // Out of bounds + } + + for (uint32_t r = 0; r < cell_height; ++r) { + for (uint32_t c = 0; c < cell_width; ++c) { + auto s = GetSlot(col + c, row + r); + if (!s || s->HasItem()) { + return false; // Collides with occupied slot + } + } + } + return true; +} + +void UIGrid::UpdateLayout(const Rect& parent_rect) { + UIElement::UpdateLayout(parent_rect); + // Children positions were set relative to grid local origin +} + +} // namespace metin2::ui_core diff --git a/ui_core/src/ui_manager.cpp b/ui_core/src/ui_manager.cpp new file mode 100644 index 0000000..fa6e290 --- /dev/null +++ b/ui_core/src/ui_manager.cpp @@ -0,0 +1,201 @@ +#include "ui_core/ui_manager.h" +#include + +namespace metin2::ui_core { + +UIManager::UIManager(float screen_width, float screen_height) + : m_screen_rect(0.0f, 0.0f, screen_width, screen_height) { + m_root = std::make_shared(); + m_root->SetName("Root"); + m_root->SetPosition(0.0f, 0.0f); + m_root->SetSize(screen_width, screen_height); + m_root->SetBackgroundColor(0); // Transparent root +} + +void UIManager::SetScreenSize(float width, float height) { + m_screen_rect = Rect(0.0f, 0.0f, width, height); + if (m_root) { + m_root->SetSize(width, height); + UpdateLayout(); + } +} + +void UIManager::AddElement(std::shared_ptr element) { + if (m_root && element) { + m_root->AddChild(element); + UpdateLayout(); + } +} + +void UIManager::RemoveElement(std::shared_ptr element) { + if (m_root && element) { + m_root->RemoveChild(element); + } +} + +void UIManager::UpdateLayout() { + if (m_root) { + m_root->UpdateLayout(m_screen_rect); + } +} + +bool UIManager::InjectMouseMove(float x, float y) { + Vec2 current_pos{x, y}; + Vec2 delta = current_pos - m_last_mouse_pos; + m_last_mouse_pos = current_pos; + + // Check Drag threshold (e.g., > 4 pixels) + if (m_mouse_down && !m_dragged_element && m_pressed_element) { + if ((current_pos - m_drag_start_pos).x * (current_pos - m_drag_start_pos).x + + (current_pos - m_drag_start_pos).y * (current_pos - m_drag_start_pos).y > 16.0f) { + UIEvent drag_event; + drag_event.type = UIEventType::DragBegin; + drag_event.mouse_pos = current_pos; + drag_event.delta_pos = delta; + drag_event.mouse_button = m_active_button; + + m_pressed_element->DispatchEvent(drag_event); + if (drag_event.handled) { + m_dragged_element = m_pressed_element; + } + } + } + + if (m_dragged_element) { + UIEvent drag_update; + drag_update.type = UIEventType::DragUpdate; + drag_update.mouse_pos = current_pos; + drag_update.delta_pos = delta; + drag_update.mouse_button = m_active_button; + m_dragged_element->DispatchEvent(drag_update); + return true; + } + + // Hover state management + auto hit = m_root ? m_root->HitTest(x, y) : nullptr; + if (hit != m_hovered_element) { + if (m_hovered_element) { + UIEvent leave_event; + leave_event.type = UIEventType::MouseLeave; + leave_event.mouse_pos = current_pos; + m_hovered_element->DispatchEvent(leave_event); + } + m_hovered_element = hit; + if (m_hovered_element) { + UIEvent enter_event; + enter_event.type = UIEventType::MouseEnter; + enter_event.mouse_pos = current_pos; + m_hovered_element->DispatchEvent(enter_event); + } + } + + if (m_hovered_element) { + UIEvent move_event; + move_event.type = UIEventType::MouseMove; + move_event.mouse_pos = current_pos; + move_event.delta_pos = delta; + m_hovered_element->DispatchEvent(move_event); + return move_event.handled; + } + + return false; +} + +bool UIManager::InjectMouseDown(float x, float y, int button) { + m_mouse_down = true; + m_active_button = button; + m_drag_start_pos = {x, y}; + m_last_mouse_pos = {x, y}; + + auto hit = m_root ? m_root->HitTest(x, y) : nullptr; + m_pressed_element = hit; + m_focused_element = hit; + + if (hit) { + UIEvent down_event; + down_event.type = UIEventType::MouseDown; + down_event.mouse_pos = {x, y}; + down_event.mouse_button = button; + hit->DispatchEvent(down_event); + return down_event.handled; + } + return false; +} + +bool UIManager::InjectMouseUp(float x, float y, int button) { + m_mouse_down = false; + Vec2 pos{x, y}; + + if (m_dragged_element) { + auto drop_target = m_root ? m_root->HitTest(x, y) : nullptr; + if (drop_target && drop_target != m_dragged_element) { + UIEvent drop_event; + drop_event.type = UIEventType::Drop; + drop_event.mouse_pos = pos; + drop_event.mouse_button = button; + drop_event.payload = m_dragged_element.get(); + drop_target->DispatchEvent(drop_event); + } + + UIEvent end_event; + end_event.type = UIEventType::DragEnd; + end_event.mouse_pos = pos; + end_event.mouse_button = button; + m_dragged_element->DispatchEvent(end_event); + m_dragged_element->SetDragging(false); + m_dragged_element = nullptr; + m_pressed_element = nullptr; + return true; + } + + if (m_pressed_element) { + UIEvent up_event; + up_event.type = UIEventType::MouseUp; + up_event.mouse_pos = pos; + up_event.mouse_button = button; + m_pressed_element->DispatchEvent(up_event); + m_pressed_element = nullptr; + return up_event.handled; + } + + return false; +} + +bool UIManager::InjectKeyDown(int key_code) { + if (m_focused_element) { + UIEvent event; + event.type = UIEventType::KeyDown; + event.key_code = key_code; + m_focused_element->DispatchEvent(event); + return event.handled; + } + return false; +} + +bool UIManager::InjectKeyUp(int key_code) { + if (m_focused_element) { + UIEvent event; + event.type = UIEventType::KeyUp; + event.key_code = key_code; + m_focused_element->DispatchEvent(event); + return event.handled; + } + return false; +} + +void UIManager::CancelDrag() { + if (m_dragged_element) { + m_dragged_element->SetDragging(false); + m_dragged_element = nullptr; + } +} + +std::vector UIManager::GenerateRenderBatches() { + std::vector batches; + if (m_root) { + m_root->GenerateRenderBatches(batches); + } + return batches; +} + +} // namespace metin2::ui_core diff --git a/ui_core/src/ui_slot.cpp b/ui_core/src/ui_slot.cpp new file mode 100644 index 0000000..2cabdd4 --- /dev/null +++ b/ui_core/src/ui_slot.cpp @@ -0,0 +1,103 @@ +#include "ui_core/ui_slot.h" + +namespace metin2::ui_core { + +UISlot::UISlot() { + m_local_rect.width = 32.0f; + m_local_rect.height = 32.0f; + m_bg_color = 0xFF1E1E1E; +} + +UISlot::UISlot(uint32_t slot_index) + : m_slot_index(slot_index) { + m_local_rect.width = 32.0f; + m_local_rect.height = 32.0f; + m_bg_color = 0xFF1E1E1E; +} + +void UISlot::SetItem(uint32_t item_vnum, uint32_t count) { + m_item_vnum = item_vnum; + m_item_count = count; +} + +void UISlot::ClearItem() { + m_item_vnum = 0; + m_item_count = 0; + m_cooldown_progress = 0.0f; + m_is_selected = false; +} + +void UISlot::OnMouseDown(UIEvent& event) { + if (event.mouse_button == 0 && HasItem()) { + m_is_pressed = true; + event.handled = true; + } +} + +void UISlot::OnDragBegin(UIEvent& event) { + if (HasItem()) { + m_is_dragging = true; + event.payload = this; + event.handled = true; + } +} + +void UISlot::OnDrop(UIEvent& event) { + if (event.payload) { + auto* src_slot = static_cast(event.payload); + if (src_slot && src_slot != this) { + if (m_on_drop) { + m_on_drop(src_slot->GetSlotIndex(), src_slot->GetItemVnum(), src_slot->GetItemCount()); + } + // Swap / Transfer + uint32_t old_vnum = m_item_vnum; + uint32_t old_cnt = m_item_count; + + SetItem(src_slot->GetItemVnum(), src_slot->GetItemCount()); + if (old_vnum > 0) { + src_slot->SetItem(old_vnum, old_cnt); + } else { + src_slot->ClearItem(); + } + event.handled = true; + } + } +} + +void UISlot::GenerateRenderBatches(std::vector& out_batches) { + if (!m_visible) return; + + // 1. Slot frame + uint32_t frame_color = m_is_selected ? 0xFFFFD700 : (m_is_hovered ? 0xFF888888 : 0xFF333333); + UIRenderBatch batch; + AppendQuad(batch, m_global_rect.x, m_global_rect.y, m_global_rect.width, m_global_rect.height, + 0.0f, 0.0f, 1.0f, 1.0f, frame_color); + + // Inner background + AppendQuad(batch, m_global_rect.x + 1, m_global_rect.y + 1, m_global_rect.width - 2, m_global_rect.height - 2, + 0.0f, 0.0f, 1.0f, 1.0f, m_bg_color); + out_batches.push_back(std::move(batch)); + + // 2. Item Icon (if item exists) + if (HasItem()) { + UIRenderBatch icon_batch; + icon_batch.texture_path = "icon/item_" + std::to_string(m_item_vnum) + ".tga"; + AppendQuad(icon_batch, m_global_rect.x + 2, m_global_rect.y + 2, + m_global_rect.width - 4, m_global_rect.height - 4, + 0.0f, 0.0f, 1.0f, 1.0f, 0xFFFFFFFF); + out_batches.push_back(std::move(icon_batch)); + } + + // 3. Cooldown Sweep Mask (if cooling down) + if (m_cooldown_progress > 0.001f) { + UIRenderBatch cd_batch; + float cd_height = m_global_rect.height * m_cooldown_progress; + // Semi-transparent dark overlay sweep + AppendQuad(cd_batch, m_global_rect.x, m_global_rect.y + (m_global_rect.height - cd_height), + m_global_rect.width, cd_height, + 0.0f, 0.0f, 1.0f, 1.0f, 0xAA000000); + out_batches.push_back(std::move(cd_batch)); + } +} + +} // namespace metin2::ui_core diff --git a/ui_core/src/ui_text.cpp b/ui_core/src/ui_text.cpp new file mode 100644 index 0000000..4cc7281 --- /dev/null +++ b/ui_core/src/ui_text.cpp @@ -0,0 +1,42 @@ +#include "ui_core/ui_text.h" + +namespace metin2::ui_core { + +UIText::UIText() { + m_bg_color = 0; // Transparent +} + +UIText::UIText(const std::string& text) + : m_text(text) { + m_bg_color = 0; +} + +void UIText::GenerateRenderBatches(std::vector& out_batches) { + if (!m_visible || m_text.empty()) return; + + // In zero-API core, Text emits placeholder glyph quads or metadata batch + UIRenderBatch batch; + batch.texture_path = "font/default.fnt"; + + float char_w = m_font_size * 0.6f; + float char_h = m_font_size; + float total_w = char_w * m_text.size(); + + float start_x = m_global_rect.x; + if (m_alignment == TextAlignment::Center) { + start_x += (m_global_rect.width - total_w) * 0.5f; + } else if (m_alignment == TextAlignment::Right) { + start_x += m_global_rect.width - total_w; + } + + float start_y = m_global_rect.y + (m_global_rect.height - char_h) * 0.5f; + + for (size_t i = 0; i < m_text.size(); ++i) { + AppendQuad(batch, start_x + i * char_w, start_y, char_w, char_h, + 0.0f, 0.0f, 1.0f, 1.0f, m_text_color); + } + + out_batches.push_back(std::move(batch)); +} + +} // namespace metin2::ui_core diff --git a/ui_core/src/ui_window.cpp b/ui_core/src/ui_window.cpp new file mode 100644 index 0000000..42cb71e --- /dev/null +++ b/ui_core/src/ui_window.cpp @@ -0,0 +1,61 @@ +#include "ui_core/ui_window.h" + +namespace metin2::ui_core { + +UIWindow::UIWindow() { + m_bg_color = 0xEE1A1A1A; // Dark translucent default +} + +void UIWindow::OnMouseDown(UIEvent& event) { + if (event.mouse_button == 0 && m_is_movable) { + // Check if mouse clicked inside title bar + Rect title_rect(m_global_rect.x, m_global_rect.y, m_global_rect.width, m_title_bar_height); + if (title_rect.Contains(event.mouse_pos.x, event.mouse_pos.y)) { + m_dragging_title_bar = true; + m_drag_start_mouse = event.mouse_pos; + m_drag_start_pos = {m_local_rect.x, m_local_rect.y}; + event.handled = true; + return; + } + } +} + +void UIWindow::OnMouseMove(UIEvent& event) { + if (m_dragging_title_bar) { + float dx = event.mouse_pos.x - m_drag_start_mouse.x; + float dy = event.mouse_pos.y - m_drag_start_mouse.y; + m_local_rect.x = m_drag_start_pos.x + dx; + m_local_rect.y = m_drag_start_pos.y + dy; + + // If has parent, trigger update + if (m_parent) { + UpdateLayout(m_parent->GetGlobalRect()); + } + event.handled = true; + } +} + +void UIWindow::OnMouseUp(UIEvent& event) { + if (m_dragging_title_bar && event.mouse_button == 0) { + m_dragging_title_bar = false; + event.handled = true; + } +} + +void UIWindow::GenerateRenderBatches(std::vector& out_batches) { + if (!m_visible) return; + + // 1. Draw base window background (Nine-Slice or quad) + UIElement::GenerateRenderBatches(out_batches); + + // 2. Draw Title Bar Header + if (m_title_bar_height > 0.0f) { + UIRenderBatch title_batch; + uint32_t header_color = 0xFF2A2A2A; + AppendQuad(title_batch, m_global_rect.x, m_global_rect.y, m_global_rect.width, m_title_bar_height, + 0.0f, 0.0f, 1.0f, 1.0f, header_color); + out_batches.push_back(std::move(title_batch)); + } +} + +} // namespace metin2::ui_core diff --git a/ui_core/tests/ui_core_test.cpp b/ui_core/tests/ui_core_test.cpp new file mode 100644 index 0000000..2dddce3 --- /dev/null +++ b/ui_core/tests/ui_core_test.cpp @@ -0,0 +1,180 @@ +#include "ui_core/ui_core.h" +#include +#include + +using namespace metin2::ui_core; + +void TestHierarchyAndLayout() { + std::cout << "[Test] UI Hierarchy & Anchor Layout...\n"; + UIManager mgr(1920.0f, 1080.0f); + + // Create a centered window (400x300) + auto window = std::make_shared(); + window->SetName("InventoryWindow"); + window->SetSize(400.0f, 300.0f); + window->SetAnchor(UIAnchor::Center); + window->SetPosition(0.0f, 0.0f); // Exactly centered + + // Add a child button inside window anchored at BottomCenter + auto btn = std::make_shared(); + btn->SetName("CloseButton"); + btn->SetSize(100.0f, 30.0f); + btn->SetAnchor(UIAnchor::BottomCenter); + btn->SetPosition(0.0f, -10.0f); // 10 px above bottom + + window->AddChild(btn); + mgr.AddElement(window); + + // Initial Layout check + mgr.UpdateLayout(); + const auto& win_rect = window->GetGlobalRect(); + assert(win_rect.x == (1920.0f - 400.0f) * 0.5f); + assert(win_rect.y == (1080.0f - 300.0f) * 0.5f); + assert(win_rect.width == 400.0f && win_rect.height == 300.0f); + + const auto& btn_rect = btn->GetGlobalRect(); + assert(btn_rect.x == win_rect.x + (400.0f - 100.0f) * 0.5f); + assert(btn_rect.y == win_rect.y + 300.0f - 30.0f - 10.0f); + + // Resize screen to 1280x720 and verify responsive recalculation + mgr.SetScreenSize(1280.0f, 720.0f); + const auto& win_rect2 = window->GetGlobalRect(); + assert(win_rect2.x == (1280.0f - 400.0f) * 0.5f); + assert(win_rect2.y == (720.0f - 300.0f) * 0.5f); + + std::cout << " -> UI Hierarchy and responsive layout passed!\n"; +} + +void TestEventBubblingAndButton() { + std::cout << "[Test] Event Bubbling & Button Interaction...\n"; + UIManager mgr(800.0f, 600.0f); + + auto window = std::make_shared(); + window->SetPosition(100.0f, 100.0f); + window->SetSize(300.0f, 200.0f); + + bool window_caught_event = false; + window->SetOnEvent([&](UIEvent& ev) { + if (ev.type == UIEventType::MouseDown) { + window_caught_event = true; + } + }); + + auto button = std::make_shared(); + button->SetPosition(20.0f, 50.0f); + button->SetSize(80.0f, 30.0f); + + bool clicked = false; + button->SetOnClick([&]() { + clicked = true; + }); + + window->AddChild(button); + mgr.AddElement(window); + mgr.UpdateLayout(); + + // 1. Click button inside window (global coords: 100+20=120, 100+50=150) + mgr.InjectMouseMove(130.0f, 160.0f); + assert(button->GetButtonState() == ButtonState::Hovered); + + mgr.InjectMouseDown(130.0f, 160.0f, 0); + assert(button->GetButtonState() == ButtonState::Pressed); + + mgr.InjectMouseUp(130.0f, 160.0f, 0); + assert(clicked); + + // 2. Click outside button but inside window: verify event bubbling to window + mgr.InjectMouseDown(250.0f, 180.0f, 0); + assert(window_caught_event); + + std::cout << " -> Event bubbling and button click passed!\n"; +} + +void TestInventoryGridAndDragDrop() { + std::cout << "[Test] Inventory Grid & Slot Drag-and-Drop...\n"; + UIManager mgr(1000.0f, 800.0f); + + // 5 cols x 9 rows grid (Metin2 standard inventory page) + auto grid = std::make_shared(5, 9, 32.0f, 2.0f); + grid->SetPosition(50.0f, 50.0f); + mgr.AddElement(grid); + mgr.UpdateLayout(); + + // Put a sword (vnum 10) in slot (0, 0) + assert(grid->SetItemAt(0, 0, 10, 1)); + auto slot0 = grid->GetSlot(0, 0); + assert(slot0->HasItem()); + assert(slot0->GetItemVnum() == 10); + + // Multi-cell footprint check + // Weapon takes 1x3 cells; can we place at (1, 0)? Yes, empty! + assert(grid->CanPlaceItem(1, 0, 1, 3)); + // At (0, 0) it is already occupied, should fail + assert(!grid->CanPlaceItem(0, 0, 1, 3)); + // Out of bound check (at col 4, width 2 exceeds cols=5) + assert(!grid->CanPlaceItem(4, 0, 2, 1)); + + // Drag-and-drop: drag item from Slot (0,0) to Slot (1,1) + auto slot_target = grid->GetSlot(1, 1); + assert(!slot_target->HasItem()); + + const auto& s0_rect = slot0->GetGlobalRect(); + const auto& st_rect = slot_target->GetGlobalRect(); + + // Mouse down at slot0 center + mgr.InjectMouseDown(s0_rect.x + 16.0f, s0_rect.y + 16.0f, 0); + // Move mouse > 4px to initiate drag + mgr.InjectMouseMove(s0_rect.x + 25.0f, s0_rect.y + 25.0f); + assert(mgr.IsDragging()); + + // Drag towards target slot and release + mgr.InjectMouseMove(st_rect.x + 16.0f, st_rect.y + 16.0f); + mgr.InjectMouseUp(st_rect.x + 16.0f, st_rect.y + 16.0f, 0); + + assert(!mgr.IsDragging()); + assert(!slot0->HasItem()); // Moved from slot 0 + assert(slot_target->HasItem()); // Landed in slot target + assert(slot_target->GetItemVnum() == 10); + + std::cout << " -> Inventory grid and drag-drop transfer passed!\n"; +} + +void TestNineSliceRenderBatches() { + std::cout << "[Test] Nine-Slice UI Render Batches Output...\n"; + UIManager mgr(800.0f, 600.0f); + + auto window = std::make_shared(); + window->SetPosition(50.0f, 50.0f); + window->SetSize(200.0f, 150.0f); + window->SetNineSlice("ui/frame_skin.sub", 10.0f, 10.0f, 10.0f, 10.0f); + + mgr.AddElement(window); + mgr.UpdateLayout(); + + auto batches = mgr.GenerateRenderBatches(); + assert(!batches.empty()); + + // Nine slice produces 9 quads (36 vertices, 54 indices) + bool found_nine_slice = false; + for (const auto& b : batches) { + if (b.texture_path == "ui/frame_skin.sub") { + assert(b.vertices.size() == 36); + assert(b.indices.size() == 54); + found_nine_slice = true; + break; + } + } + assert(found_nine_slice); + + std::cout << " -> Nine-slice batch generation verified!\n"; +} + +int main() { + std::cout << "=== Running Metin2 UI Core SDK Tests ===\n"; + TestHierarchyAndLayout(); + TestEventBubblingAndButton(); + TestInventoryGridAndDragDrop(); + TestNineSliceRenderBatches(); + std::cout << "All UI Core SDK Tests PASSED!\n"; + return 0; +}