From ab9456de186b6391cedd877da34d365df9f48d50 Mon Sep 17 00:00:00 2001 From: twodreams Date: Sun, 1 Mar 2026 21:58:34 -0300 Subject: [PATCH 1/8] docs: add Rust migration plan Comprehensive plan for converting OTClient from C++ to Rust: - 4 Bevy crates as dependencies (bevy_ecs, bevy_app, bevy_tasks, bevy_reflect) - Other Bevy modules copied into project (render, shader, sprite, asset, etc.) - Custom code for protocol, networking, game logic, OTML, Lua, audio - Open-source crates (wgpu, tokio, mlua, kira, etc.) for remaining subsystems - 7-phase migration plan with ~27 week timeline Co-Authored-By: Claude Opus 4.6 --- docs/rust-migration-plan.md | 418 ++++++++++++++++++++++++++++++++++++ 1 file changed, 418 insertions(+) create mode 100644 docs/rust-migration-plan.md diff --git a/docs/rust-migration-plan.md b/docs/rust-migration-plan.md new file mode 100644 index 0000000000..635418fa46 --- /dev/null +++ b/docs/rust-migration-plan.md @@ -0,0 +1,418 @@ +# Plano de Migração: OTClient C++ → Rust + +## Visão Geral + +Reescrever o OTClient (~86.000 LOC C++) em Rust. Construir nosso **próprio framework** usando módulos do Bevy de 3 formas: + +**1. Dependência direta (4 crates no Cargo.toml, usados como estão)**: +- `bevy_ecs` — ECS: World, Entity, Component, Resource, Query, System, Schedule, Events +- `bevy_app` — App builder, Plugin trait, Schedules +- `bevy_tasks` — Async task pools +- `bevy_reflect` — Reflection (útil para Lua interop) + +**2. Código copiado do Bevy para dentro do projeto (modificado ou não)**: +- Render pipeline, shader system, sprite batching, asset system, input, window, time, transforms, UI layout, etc. +- Se o módulo funcionar como está → copiar sem modificar +- Se precisar de adaptação → copiar e modificar + +**3. Código 100% nosso** + crates open-source standalone (wgpu, tokio, mlua, kira, etc.): +- Protocolo Tibia, networking, game logic, OTML, Lua bridge, áudio, UI widgets, map rendering + +--- + +## Estrutura de Crates + +``` +otclient-rs/ +├── Cargo.toml # Workspace +├── crates/ +│ │ +│ │ ═══════════ COPIADO DO BEVY (modificado ou não) ═══════════ +│ │ +│ ├── otc_render/ # De bevy_render — render pipeline +│ │ └── src/ +│ │ ├── lib.rs # RenderPlugin +│ │ ├── renderer.rs # wgpu device/queue/surface +│ │ ├── render_phase.rs # Extract/Prepare/Queue/Render +│ │ ├── render_resource.rs # GPU buffers, bind groups, pipelines +│ │ └── view.rs # Camera/viewport 2D +│ │ +│ ├── otc_shader/ # De bevy_shader — shader system +│ │ └── src/ # Shader loading, preprocessing, naga +│ │ +│ ├── otc_sprite/ # De bevy_sprite — 2D sprite + batching +│ │ └── src/ # Sprite, SpriteBatch, TextureAtlas +│ │ +│ ├── otc_text/ # De bevy_text — text rendering +│ │ └── src/ # cosmic-text, font atlas +│ │ +│ ├── otc_image/ # De bevy_image — image loading +│ │ └── src/ # PNG, BMP, APNG +│ │ +│ ├── otc_asset/ # De bevy_asset — asset system +│ │ └── src/ # AssetServer, AssetLoader, Handle, cache +│ │ +│ ├── otc_window/ # De bevy_window — window abstraction +│ │ └── src/ +│ │ +│ ├── otc_winit/ # De bevy_winit — winit backend +│ │ └── src/ +│ │ +│ ├── otc_input/ # De bevy_input — keyboard/mouse +│ │ └── src/ +│ │ +│ ├── otc_time/ # De bevy_time — Time, Timer, Stopwatch +│ │ └── src/ +│ │ +│ ├── otc_transform/ # De bevy_transform — Transform, GlobalTransform +│ │ └── src/ +│ │ +│ ├── otc_hierarchy/ # De bevy_hierarchy — Parent/Children +│ │ └── src/ +│ │ +│ ├── otc_color/ # De bevy_color — Color types +│ │ └── src/ +│ │ +│ ├── otc_log/ # De bevy_log — tracing setup +│ │ └── src/ +│ │ +│ ├── otc_diagnostic/ # De bevy_diagnostic — FPS, diagnostics +│ │ └── src/ +│ │ +│ │ ═══════════ UI (nosso, inspirado em bevy_ui + fyrox-ui) ═══════════ +│ │ +│ ├── otc_ui/ # UI framework retained-mode +│ │ └── src/ +│ │ ├── lib.rs # UiPlugin +│ │ ├── widget.rs # Widget base +│ │ ├── layout.rs # taffy Flexbox/Grid (de bevy_ui) +│ │ ├── style.rs # OTML → widget style bridge +│ │ ├── manager.rs # UiManager — API unificada create() +│ │ ├── text_edit.rs # Widget de texto editável +│ │ ├── html.rs # Rich text (scraper + lightningcss) +│ │ └── draw.rs # Draw command buffer → render +│ │ +│ ├── otc_ui_widgets/ # Widgets game-specific +│ │ └── src/ # UIMap, UIMinimap, UIItem, UICreature, etc. +│ │ +│ │ ═══════════ PLATFORM (nosso) ═══════════ +│ │ +│ ├── otc_platform/ # Platform utils (clipboard, crash handler) +│ │ └── src/ +│ │ +│ │ ═══════════ NETWORKING (nosso) ═══════════ +│ │ +│ ├── otc_net/ # Networking core (tokio) +│ │ └── src/ +│ │ ├── lib.rs # NetPlugin +│ │ ├── connection.rs # TCP async +│ │ ├── web_connection.rs # WebSocket +│ │ ├── protocol.rs # XTEA, zlib, checksum +│ │ ├── message.rs # InputMessage / OutputMessage +│ │ ├── http.rs # HTTP client (reqwest) +│ │ └── encryption.rs # XTEA cipher +│ │ +│ ├── otc_protocol/ # Protocolo Tibia +│ │ └── src/ +│ │ ├── lib.rs # ProtocolPlugin +│ │ ├── opcodes.rs # Constantes +│ │ ├── packets.rs # Structs tipados (~200 packets) +│ │ ├── parse.rs # Server → Client +│ │ └── send.rs # Client → Server +│ │ +│ │ ═══════════ SCRIPTING (nosso) ═══════════ +│ │ +│ ├── otc_lua/ # Lua scripting (mlua) +│ │ └── src/ +│ │ ├── lib.rs # LuaPlugin +│ │ ├── engine.rs # mlua runtime como Resource +│ │ ├── bindings_framework.rs # Bindings do framework +│ │ ├── bindings_client.rs # Bindings do client +│ │ ├── module_loader.rs # Carrega .otmod +│ │ └── value_casts.rs # Conversões Rust ↔ Lua +│ │ +│ ├── otc_lua_derive/ # Proc macros para Lua +│ │ └── src/ # #[derive(LuaBindable)] +│ │ +│ │ ═══════════ DATA FORMATS (nosso) ═══════════ +│ │ +│ ├── otc_otml/ # Parser OTML (lib pura) +│ │ └── src/ +│ │ +│ ├── otc_protobuf/ # Protobuf (prost) +│ │ └── src/ +│ │ +│ │ ═══════════ GAME CLIENT (nosso, portado do C++) ═══════════ +│ │ +│ ├── otc_game/ # Game state & logic +│ │ └── src/ +│ │ ├── lib.rs # GamePlugin +│ │ ├── components.rs # ECS Components +│ │ ├── bundles.rs # CreatureBundle, ItemBundle, etc. +│ │ ├── resources.rs # GameState, ContainerManager, VipList, etc. +│ │ ├── map.rs # TileMap + TileBlock +│ │ ├── creature.rs # Creature systems +│ │ ├── item.rs # Item systems +│ │ ├── effect.rs # Effect/missile systems +│ │ ├── container.rs # Inventory/container +│ │ └── config.rs # GameConfig +│ │ +│ ├── otc_thing/ # ThingType, SpriteManager (AssetLoaders) +│ │ └── src/ +│ │ +│ ├── otc_map_render/ # Renderização do mapa +│ │ └── src/ +│ │ ├── lib.rs # MapRenderPlugin +│ │ ├── map_view.rs # Tile map render +│ │ ├── light_view.rs # 2D lighting +│ │ ├── creature_render.rs # Creature/outfit rendering +│ │ ├── minimap.rs # Minimap +│ │ ├── draw_pool.rs # Hash change detection +│ │ └── shaders/ # WGSL (map, light, creature, effect) +│ │ +│ │ ═══════════ ÁUDIO (nosso) ═══════════ +│ │ +│ ├── otc_audio/ # Audio (kira) +│ │ └── src/ +│ │ +│ │ ═══════════ EXTRAS ═══════════ +│ │ +│ └── otc_discord/ # Discord RPC (feature flag) +│ └── src/ +│ +├── src/main.rs # Entry point +├── modules/ # 71 módulos Lua (atualizados) +├── data/ # Assets +└── proto/ # .proto files +``` + +--- + +## Dependências + +```toml +# ── Bevy (apenas 4 crates) ── +bevy_ecs = "0.15" +bevy_app = "0.15" +bevy_tasks = "0.15" +bevy_reflect = "0.15" + +# ── GPU & Windowing ── +wgpu = "24" +winit = "0.30" +glam = "0.29" # Math (vetores, matrizes) +taffy = "0.7" # Layout (Flexbox/Grid) + +# ── Networking ── +tokio = { version = "1", features = ["full"] } +tokio-tungstenite = "0.26" +reqwest = "0.12" + +# ── Scripting ── +mlua = { version = "0.10", features = ["luajit"] } + +# ── Serialization ── +prost = "0.13" +serde = { version = "1", features = ["derive"] } +serde_json = "1" +quick-xml = "0.37" + +# ── Rendering ── +cosmic-text = "0.12" # Fontes +image = "0.25" # Imagens + +# ── HTML/CSS ── +scraper = "0.22" +lightningcss = "1" + +# ── Compression/Crypto ── +flate2 = "1" +lzma-rs = "0.3" +rustls = "0.23" + +# ── Audio ── +kira = "0.9" + +# ── Utilities ── +tracing = "0.1" +tracing-subscriber = "0.3" +thiserror = "2" +anyhow = "1" +uuid = "1" +dashmap = "6" +rayon = "1" +``` + +--- + +## Mapeamento C++ → Rust ECS + +| C++ (atual) | Rust (novo) | +|---|---| +| `g_game`, `g_map`, `g_ui`, etc. (30+ singletons) | `Resource` no ECS World | +| `Creature`, `Item`, `Effect`, `Missile` (classes OOP) | Entities + Components (bundles) | +| `Thing` (base class) | Trait + query filters | +| `EventDispatcher` + callbacks | `Events` + `EventReader`/`EventWriter` | +| `UIWidget` hierarchy | Entity tree com `otc_ui` Components | +| `ProtocolGame::parse*()` (236.9KB) | Systems que lêem `Events` → emitem `Events` | +| `SoundManager` | Resource no ECS, systems para playback | +| `ModuleManager` (Lua) | Resource + system de carregamento | +| `MapView::render()`, `LightView` | Render systems (Extract/Prepare/Queue) | +| Game flow (login, char select, in-game) | `States` via `bevy_app` | + +--- + +## Simplificações + +### 1. UI: 3 métodos de criação → 1 +```rust +pub fn create(source: WidgetSource, parent: Option) -> WidgetId +``` + +### 2. Layout: 6 engines → taffy (Flexbox + Grid) +- UIHorizontalLayout → `FlexDirection::Row` +- UIVerticalLayout → `FlexDirection::Column` +- UIGridLayout → CSS Grid +- UIAnchorLayout → `Position::Absolute` +- UIBoxLayout / UIFlexbox → Flexbox + +### 3. 30+ singletons → ECS Resources + +### 4. Game monolítico (62KB) → Systems + Resources decompostos + +### 5. HTML/CSS parser: 95KB custom → scraper + lightningcss + +### 6. OTML: Manter formato, reimplementar em Rust + +### 7. Lua: API redesenhada para Rust, scripts atualizados +- Nova API modelada sobre o ECS +- 71 módulos Lua portados para nova API +- `.otmod` lifecycle mantido +- Proc macros `#[derive(LuaBindable)]` para bindings automáticos + +--- + +## Fases + +### Fase 0: Fundação (3-4 semanas) +- Setup workspace Cargo com bevy_ecs + bevy_app + bevy_tasks + bevy_reflect como dependências +- Copiar do Bevy: otc_window (bevy_window), otc_winit (bevy_winit), otc_input (bevy_input), otc_time (bevy_time), otc_log (bevy_log), otc_color (bevy_color) +- `otc_otml`: implementar parser OTML +- Setup CI + +**Entregável**: App abre janela, plugins rodam, states funcionam. + +### Fase 1: Render Pipeline (4-6 semanas) — PARALELA com Fase 2 +- Copiar do Bevy: otc_render (bevy_render), otc_shader (bevy_shader), otc_sprite (bevy_sprite), otc_text (bevy_text), otc_image (bevy_image), otc_transform (bevy_transform) +- Modificar otc_render para pipeline 2D (remover 3D) +- Modificar otc_sprite para tile map + atlas do Tibia +- DrawPool com hash change detection (portado do C++) +- Converter shaders GLSL → WGSL + +**Entregável**: Renderiza sprites, texto, shapes com batching. + +### Fase 2: Networking + Protocolo (4-5 semanas) — PARALELA com Fase 1 +- `otc_net`: TCP (tokio), WebSocket, XTEA, zlib, HTTP (reqwest) +- `otc_protocol`: ~200 packets tipados, parse systems, send systems +- Portar protocolgameparse.cpp (236.9KB) e protocolgamesend.cpp (51.5KB) + +**Entregável**: Conecta a servidor, parseia packets, emite Events. + +### Fase 3: Game State (4-5 semanas) +- Copiar do Bevy: otc_asset (bevy_asset), otc_hierarchy (bevy_hierarchy) +- `otc_thing`: ThingType + SpriteManager como AssetLoaders custom +- `otc_game`: Components, Bundles, Resources, TileMap, systems +- `otc_protobuf`: prost para appearances/sounds/staticdata +- Decompor Game (62KB) em sub-Resources + Systems + +**Entregável**: Game state completo no ECS. + +### Fase 4: Map Render (3-4 semanas) +- `otc_map_render`: tiles, criaturas, iluminação, minimap +- WGSL shaders do cliente + +**Entregável**: Mapa renderiza com criaturas e luz. + +### Fase 5: UI (4-5 semanas) +- `otc_ui`: widgets retained-mode, taffy layout, OTML bridge, HTML rich text +- `otc_ui_widgets`: UIMap, UIItem, UICreature, UIMinimap, etc. +- API unificada create() + +**Entregável**: UI carregada de .otui. + +### Fase 6: Lua (3-4 semanas) +- `otc_lua`: mlua runtime, bindings, module loader +- `otc_lua_derive`: proc macros +- Portar 71 módulos Lua para nova API + +**Entregável**: Módulos Lua funcionam. + +### Fase 7: Áudio + Polish (2-3 semanas) +- `otc_audio`: kira +- Discord RPC, WASM build, profiling + +**Entregável**: Cliente feature-complete. + +--- + +## Cronograma + +``` +Semana: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 + ├───Fase 0────┤ + ├─────Fase 1──────┤ (PARALELA) + ├────Fase 2─────┤ (PARALELA) + ├────Fase 3─────┤ + ├───Fase 4────┤ + ├────Fase 5─────┤ + ├───Fase 6────┤ + ├──Fase 7──┤ +``` + +--- + +## Riscos + +| Risco | Severidade | Mitigação | +|---|---|---| +| Protocolo: 236.9KB parsing byte-compatible | ALTO | Packet dumps como fixtures; strong typing | +| Lua: portar 71 módulos para nova API | ALTO | Portar incrementalmente; testar por módulo | +| Render performance | MÉDIO | DrawPool hash detection; benchmark contínuo | +| UI com OTML | MÉDIO | Widget system próprio; testar com .otui existentes | + +--- + +## Módulos Bevy copiados para o projeto + +| Bevy source | Nosso crate | Modificação | +|---|---|---| +| `bevy_render/` | `otc_render/` | Adaptar para 2D, remover 3D | +| `bevy_shader/` | `otc_shader/` | Adaptar defines para nossos shaders | +| `bevy_sprite/` | `otc_sprite/` | Adaptar para tile map do Tibia | +| `bevy_text/` | `otc_text/` | Copiar, avaliar se modifica | +| `bevy_image/` | `otc_image/` | Copiar, adicionar APNG | +| `bevy_asset/` | `otc_asset/` | Copiar, avaliar se modifica | +| `bevy_window/` | `otc_window/` | Copiar, avaliar se modifica | +| `bevy_winit/` | `otc_winit/` | Copiar, avaliar se modifica | +| `bevy_input/` | `otc_input/` | Copiar, avaliar se modifica | +| `bevy_time/` | `otc_time/` | Copiar sem modificar | +| `bevy_transform/` | `otc_transform/` | Copiar sem modificar | +| `bevy_hierarchy/` | `otc_hierarchy/` | Copiar sem modificar | +| `bevy_color/` | `otc_color/` | Copiar sem modificar | +| `bevy_log/` | `otc_log/` | Copiar sem modificar | +| `bevy_diagnostic/` | `otc_diagnostic/` | Copiar sem modificar | +| `bevy_ui/src/layout/` | `otc_ui/layout.rs` | Copiar integração taffy, adaptar para OTML | + +## Referências C++ (para portar) + +| Arquivo | O que portar | +|---|---| +| `protocolgameparse.cpp` (236.9KB) | ~200 packet parsers | +| `protocolgamesend.cpp` (51.5KB) | ~100 send commands | +| `drawpool.h` (365 LOC) | Hash change detection | +| `uiwidget.h` (2.532 LOC) | Sistema de widgets | +| `otmlparser.h` | Parser OTML | +| `mapview.cpp` (38.8KB) | Render do mapa | +| `creature.cpp` (50.3KB) | Lógica de criatura → Components | +| `game.cpp` (62KB) | Game state → Resources + Systems | +| `luafunctions.cpp` (95KB + 87KB) | Referência para API Lua | From 5f8742150c9a61e36e215ad426b8400834d95b7d Mon Sep 17 00:00:00 2001 From: twodreams Date: Sun, 1 Mar 2026 22:06:59 -0300 Subject: [PATCH 2/8] feat: add initial Rust workspace and crate configurations --- .claude/settings.local.json | 65 +++++++++++++ rust/Cargo.toml | 131 ++++++++++++++++++++++++++ rust/crates/otc_asset/Cargo.toml | 13 +++ rust/crates/otc_audio/Cargo.toml | 12 +++ rust/crates/otc_color/Cargo.toml | 8 ++ rust/crates/otc_diagnostic/Cargo.toml | 10 ++ rust/crates/otc_discord/Cargo.toml | 13 +++ rust/crates/otc_game/Cargo.toml | 15 +++ rust/crates/otc_hierarchy/Cargo.toml | 10 ++ rust/crates/otc_image/Cargo.toml | 10 ++ rust/crates/otc_input/Cargo.toml | 11 +++ rust/crates/otc_log/Cargo.toml | 9 ++ rust/crates/otc_lua/Cargo.toml | 13 +++ rust/crates/otc_lua_derive/Cargo.toml | 13 +++ rust/crates/otc_map_render/Cargo.toml | 17 ++++ rust/crates/otc_net/Cargo.toml | 14 +++ rust/crates/otc_otml/Cargo.toml | 7 ++ rust/crates/otc_platform/Cargo.toml | 7 ++ rust/crates/otc_protobuf/Cargo.toml | 11 +++ rust/crates/otc_protocol/Cargo.toml | 13 +++ rust/crates/otc_render/Cargo.toml | 16 ++++ rust/crates/otc_shader/Cargo.toml | 13 +++ rust/crates/otc_sprite/Cargo.toml | 14 +++ rust/crates/otc_text/Cargo.toml | 13 +++ rust/crates/otc_thing/Cargo.toml | 14 +++ rust/crates/otc_time/Cargo.toml | 10 ++ rust/crates/otc_transform/Cargo.toml | 11 +++ rust/crates/otc_ui/Cargo.toml | 19 ++++ rust/crates/otc_ui_widgets/Cargo.toml | 12 +++ rust/crates/otc_window/Cargo.toml | 11 +++ rust/crates/otc_winit/Cargo.toml | 13 +++ rust/otclient/Cargo.toml | 45 +++++++++ 32 files changed, 593 insertions(+) create mode 100644 .claude/settings.local.json create mode 100644 rust/Cargo.toml create mode 100644 rust/crates/otc_asset/Cargo.toml create mode 100644 rust/crates/otc_audio/Cargo.toml create mode 100644 rust/crates/otc_color/Cargo.toml create mode 100644 rust/crates/otc_diagnostic/Cargo.toml create mode 100644 rust/crates/otc_discord/Cargo.toml create mode 100644 rust/crates/otc_game/Cargo.toml create mode 100644 rust/crates/otc_hierarchy/Cargo.toml create mode 100644 rust/crates/otc_image/Cargo.toml create mode 100644 rust/crates/otc_input/Cargo.toml create mode 100644 rust/crates/otc_log/Cargo.toml create mode 100644 rust/crates/otc_lua/Cargo.toml create mode 100644 rust/crates/otc_lua_derive/Cargo.toml create mode 100644 rust/crates/otc_map_render/Cargo.toml create mode 100644 rust/crates/otc_net/Cargo.toml create mode 100644 rust/crates/otc_otml/Cargo.toml create mode 100644 rust/crates/otc_platform/Cargo.toml create mode 100644 rust/crates/otc_protobuf/Cargo.toml create mode 100644 rust/crates/otc_protocol/Cargo.toml create mode 100644 rust/crates/otc_render/Cargo.toml create mode 100644 rust/crates/otc_shader/Cargo.toml create mode 100644 rust/crates/otc_sprite/Cargo.toml create mode 100644 rust/crates/otc_text/Cargo.toml create mode 100644 rust/crates/otc_thing/Cargo.toml create mode 100644 rust/crates/otc_time/Cargo.toml create mode 100644 rust/crates/otc_transform/Cargo.toml create mode 100644 rust/crates/otc_ui/Cargo.toml create mode 100644 rust/crates/otc_ui_widgets/Cargo.toml create mode 100644 rust/crates/otc_window/Cargo.toml create mode 100644 rust/crates/otc_winit/Cargo.toml create mode 100644 rust/otclient/Cargo.toml diff --git a/.claude/settings.local.json b/.claude/settings.local.json new file mode 100644 index 0000000000..766abc82ab --- /dev/null +++ b/.claude/settings.local.json @@ -0,0 +1,65 @@ +{ + "permissions": { + "allow": [ + "WebFetch(domain:github.com)", + "WebFetch(domain:www.nicbarker.com)", + "Bash(xargs wc -l)", + "Bash(find /c/Users/Pedro/Documents/otclient/src/protobuf -name \"*.proto\" -exec head -20 {} ;)", + "WebFetch(domain:raw.githubusercontent.com)", + "Bash(curl -sL \"https://raw.githubusercontent.com/nicbarker/clay/main/clay.h\" -o /c/Users/Pedro/Documents/otclient/src/framework/ui/clay/clay.h)", + "Bash(echo $VCPKG_ROOT)", + "Bash(cmake --preset windows-release -DTOGGLE_FRAMEWORK_CLAY=ON)", + "Bash(CMAKE=\"/c/Program Files/Microsoft Visual Studio/2022/Community/Common7/IDE/CommonExtensions/Microsoft/CMake/CMake/bin/cmake.exe\")", + "Bash(\"$CMAKE\" -S src -B build/clay-test -G Ninja -DCMAKE_TOOLCHAIN_FILE=\"$VCPKG_ROOT/scripts/buildsystems/vcpkg.cmake\" -DVCPKG_TARGET_TRIPLET=x64-windows-static -DBUILD_STATIC_LIBRARY=ON -DCMAKE_BUILD_TYPE=RelWithDebInfo -DTOGGLE_FRAMEWORK_CLAY=ON)", + "Bash(CMAKE_EXE=\"/c/Program Files/Microsoft Visual Studio/2022/Community/Common7/IDE/CommonExtensions/Microsoft/CMake/CMake/bin/cmake.exe\")", + "Bash(echo \"Testing: $CMAKE_EXE\")", + "Bash(\"$CMAKE_EXE\" --version)", + "Bash(git checkout -b feat/clay-ui-layout)", + "Bash(git add src/framework/ui/clay/clay.h src/framework/ui/uiclaylayout.h src/framework/ui/uiclaylayout.cpp src/CMakeLists.txt src/framework/ui/declarations.h src/framework/ui/uilayout.h src/framework/ui/ui.h src/framework/ui/uiwidgetbasestyle.cpp src/framework/luafunctions.cpp modules/client_claydemo/claydemo.otmod modules/client_claydemo/claydemo.otui modules/client_claydemo/claydemo.lua modules/client/client.otmod)", + "Bash(git commit:*)", + "Bash(ls -la /c/Users/Pedro/Documents/otclient/src/framework/ui/uilayout*)", + "Bash(find \"C:\\\\Users\\\\Pedro\\\\Documents\\\\otclient\\\\modules\" -name \"*.lua\" -type f -exec grep -l \"loadHtml\\\\|unloadHtml\" {} ;)", + "Bash(git add src/framework/ui/uiwidget.h src/framework/ui/uiwidgetbasestyle.cpp src/framework/ui/uiwidgethtml.cpp src/framework/ui/uiclaylayout.h src/framework/ui/uiclaylayout.cpp modules/game_htmlclaydemo/ modules/game_interface/interface.otmod)", + "Bash(git push -u origin feat/clay-ui-layout)", + "Bash(xargs grep -l \"applyDimension\")", + "Bash(xargs grep -l \"flex-direction\\\\|justify-content\\\\|align-items\")", + "Bash(xargs grep -l \"screen\\\\|window\")", + "Bash(wc -l /c/Users/Pedro/Documents/otclient/src/framework/ui/*.cpp /c/Users/Pedro/Documents/otclient/src/framework/graphics/*.cpp)", + "Bash(done)", + "WebFetch(domain:docs.rs)", + "Bash(git add docs/rust-migration-plan.md)", + "Bash(\"C:/Users/Pedro/Documents/otclient/rust/crates/otc_otml/Cargo.toml\":*)", + "Bash(\"C:/Users/Pedro/Documents/otclient/rust/crates/otc_log/Cargo.toml\":*)", + "Bash(\"C:/Users/Pedro/Documents/otclient/rust/crates/otc_color/Cargo.toml\":*)", + "Bash(\"C:/Users/Pedro/Documents/otclient/rust/crates/otc_time/Cargo.toml\":*)", + "Bash(\"C:/Users/Pedro/Documents/otclient/rust/crates/otc_input/Cargo.toml\":*)", + "Bash(\"C:/Users/Pedro/Documents/otclient/rust/crates/otc_window/Cargo.toml\":*)", + "Bash(\"C:/Users/Pedro/Documents/otclient/rust/crates/otc_winit/Cargo.toml\":*)", + "Bash(\"C:/Users/Pedro/Documents/otclient/rust/crates/otc_transform/Cargo.toml\":*)", + "Bash(\"C:/Users/Pedro/Documents/otclient/rust/crates/otc_hierarchy/Cargo.toml\":*)", + "Bash(\"C:/Users/Pedro/Documents/otclient/rust/crates/otc_asset/Cargo.toml\":*)", + "Bash(\"C:/Users/Pedro/Documents/otclient/rust/crates/otc_image/Cargo.toml\":*)", + "Bash(\"C:/Users/Pedro/Documents/otclient/rust/crates/otc_render/Cargo.toml\":*)", + "Bash(\"C:/Users/Pedro/Documents/otclient/rust/crates/otc_shader/Cargo.toml\":*)", + "Bash(\"C:/Users/Pedro/Documents/otclient/rust/crates/otc_sprite/Cargo.toml\":*)", + "Bash(\"C:/Users/Pedro/Documents/otclient/rust/crates/otc_text/Cargo.toml\":*)", + "Bash(\"C:/Users/Pedro/Documents/otclient/rust/crates/otc_diagnostic/Cargo.toml\":*)", + "Bash(\"C:/Users/Pedro/Documents/otclient/rust/crates/otc_platform/Cargo.toml\":*)", + "Bash(\"C:/Users/Pedro/Documents/otclient/rust/crates/otc_ui/Cargo.toml\":*)", + "Bash(\"C:/Users/Pedro/Documents/otclient/rust/crates/otc_ui_widgets/Cargo.toml\":*)", + "Bash(\"C:/Users/Pedro/Documents/otclient/rust/crates/otc_net/Cargo.toml\":*)", + "Bash(\"C:/Users/Pedro/Documents/otclient/rust/crates/otc_protocol/Cargo.toml\":*)", + "Bash(\"C:/Users/Pedro/Documents/otclient/rust/crates/otc_protobuf/Cargo.toml\":*)", + "Bash(\"C:/Users/Pedro/Documents/otclient/rust/crates/otc_lua/Cargo.toml\":*)", + "Bash(\"C:/Users/Pedro/Documents/otclient/rust/crates/otc_lua_derive/Cargo.toml\":*)", + "Bash(\"C:/Users/Pedro/Documents/otclient/rust/crates/otc_game/Cargo.toml\":*)", + "Bash(\"C:/Users/Pedro/Documents/otclient/rust/crates/otc_thing/Cargo.toml\":*)", + "Bash(\"C:/Users/Pedro/Documents/otclient/rust/crates/otc_map_render/Cargo.toml\":*)", + "Bash(\"C:/Users/Pedro/Documents/otclient/rust/crates/otc_audio/Cargo.toml\":*)", + "Bash(\"C:/Users/Pedro/Documents/otclient/rust/crates/otc_discord/Cargo.toml\":*)", + "Bash(\"C:/Users/Pedro/Documents/otclient/rust/otclient/Cargo.toml\":*)", + "Bash(for d in otc_otml otc_log otc_color otc_time otc_input otc_window otc_winit otc_transform otc_hierarchy otc_asset otc_image otc_render otc_shader otc_sprite otc_text otc_diagnostic otc_platform otc_ui otc_ui_widgets otc_net otc_protocol otc_protobuf otc_lua otc_lua_derive otc_game otc_thing otc_map_render otc_audio otc_discord)", + "Bash(do mkdir -p \"C:/Users/Pedro/Documents/otclient/rust/crates/$d/src\")" + ] + } +} diff --git a/rust/Cargo.toml b/rust/Cargo.toml new file mode 100644 index 0000000000..4fa0c655e7 --- /dev/null +++ b/rust/Cargo.toml @@ -0,0 +1,131 @@ +[workspace] +resolver = "2" +members = [ + "crates/otc_render", + "crates/otc_shader", + "crates/otc_sprite", + "crates/otc_text", + "crates/otc_image", + "crates/otc_asset", + "crates/otc_window", + "crates/otc_winit", + "crates/otc_input", + "crates/otc_time", + "crates/otc_transform", + "crates/otc_hierarchy", + "crates/otc_color", + "crates/otc_log", + "crates/otc_diagnostic", + "crates/otc_ui", + "crates/otc_ui_widgets", + "crates/otc_platform", + "crates/otc_net", + "crates/otc_protocol", + "crates/otc_lua", + "crates/otc_lua_derive", + "crates/otc_otml", + "crates/otc_protobuf", + "crates/otc_game", + "crates/otc_thing", + "crates/otc_map_render", + "crates/otc_audio", + "crates/otc_discord", + "otclient", +] + +[workspace.package] +version = "0.1.0" +edition = "2024" +license = "MIT" +repository = "https://github.com/mehah/otclient" + +[workspace.dependencies] +# Bevy crates (dependência direta) +bevy_ecs = "0.15" +bevy_app = "0.15" +bevy_tasks = "0.15" +bevy_reflect = "0.15" + +# GPU & Windowing +wgpu = "24" +winit = "0.30" +raw-window-handle = "0.6" + +# Math +glam = "0.29" + +# Layout +taffy = "0.7" + +# Networking +tokio = { version = "1", features = ["full"] } +tokio-tungstenite = "0.26" +reqwest = { version = "0.12", features = ["json"] } + +# Scripting +mlua = { version = "0.10", features = ["luajit", "vendored"] } + +# Serialization +prost = "0.13" +prost-build = "0.13" +serde = { version = "1", features = ["derive"] } +serde_json = "1" +quick-xml = "0.37" + +# Rendering +cosmic-text = "0.12" +image = { version = "0.25", default-features = false, features = ["png", "bmp"] } + +# HTML/CSS +scraper = "0.22" +lightningcss = "1" + +# Compression/Crypto +flate2 = "1" +lzma-rs = "0.3" +rustls = "0.23" + +# Audio +kira = "0.9" + +# Utilities +tracing = "0.1" +tracing-subscriber = "0.3" +thiserror = "2" +anyhow = "1" +uuid = { version = "1", features = ["v4"] } +dashmap = "6" +rayon = "1" +bytemuck = { version = "1", features = ["derive"] } +byteorder = "1" + +# Internal crates +otc_render = { path = "crates/otc_render" } +otc_shader = { path = "crates/otc_shader" } +otc_sprite = { path = "crates/otc_sprite" } +otc_text = { path = "crates/otc_text" } +otc_image = { path = "crates/otc_image" } +otc_asset = { path = "crates/otc_asset" } +otc_window = { path = "crates/otc_window" } +otc_winit = { path = "crates/otc_winit" } +otc_input = { path = "crates/otc_input" } +otc_time = { path = "crates/otc_time" } +otc_transform = { path = "crates/otc_transform" } +otc_hierarchy = { path = "crates/otc_hierarchy" } +otc_color = { path = "crates/otc_color" } +otc_log = { path = "crates/otc_log" } +otc_diagnostic = { path = "crates/otc_diagnostic" } +otc_ui = { path = "crates/otc_ui" } +otc_ui_widgets = { path = "crates/otc_ui_widgets" } +otc_platform = { path = "crates/otc_platform" } +otc_net = { path = "crates/otc_net" } +otc_protocol = { path = "crates/otc_protocol" } +otc_lua = { path = "crates/otc_lua" } +otc_lua_derive = { path = "crates/otc_lua_derive" } +otc_otml = { path = "crates/otc_otml" } +otc_protobuf = { path = "crates/otc_protobuf" } +otc_game = { path = "crates/otc_game" } +otc_thing = { path = "crates/otc_thing" } +otc_map_render = { path = "crates/otc_map_render" } +otc_audio = { path = "crates/otc_audio" } +otc_discord = { path = "crates/otc_discord" } diff --git a/rust/crates/otc_asset/Cargo.toml b/rust/crates/otc_asset/Cargo.toml new file mode 100644 index 0000000000..b1f6a74e5d --- /dev/null +++ b/rust/crates/otc_asset/Cargo.toml @@ -0,0 +1,13 @@ +[package] +name = "otc_asset" +version.workspace = true +edition.workspace = true +license.workspace = true + +[dependencies] +bevy_ecs = { workspace = true } +bevy_app = { workspace = true } +bevy_tasks = { workspace = true } +bevy_reflect = { workspace = true } +thiserror = { workspace = true } +tracing = { workspace = true } diff --git a/rust/crates/otc_audio/Cargo.toml b/rust/crates/otc_audio/Cargo.toml new file mode 100644 index 0000000000..855962a945 --- /dev/null +++ b/rust/crates/otc_audio/Cargo.toml @@ -0,0 +1,12 @@ +[package] +name = "otc_audio" +version.workspace = true +edition.workspace = true +license.workspace = true + +[dependencies] +bevy_ecs = { workspace = true } +bevy_app = { workspace = true } +kira = { workspace = true } +otc_asset = { workspace = true } +tracing = { workspace = true } diff --git a/rust/crates/otc_color/Cargo.toml b/rust/crates/otc_color/Cargo.toml new file mode 100644 index 0000000000..19e945b39b --- /dev/null +++ b/rust/crates/otc_color/Cargo.toml @@ -0,0 +1,8 @@ +[package] +name = "otc_color" +version.workspace = true +edition.workspace = true +license.workspace = true + +[dependencies] +bevy_reflect = { workspace = true } diff --git a/rust/crates/otc_diagnostic/Cargo.toml b/rust/crates/otc_diagnostic/Cargo.toml new file mode 100644 index 0000000000..e40a27136a --- /dev/null +++ b/rust/crates/otc_diagnostic/Cargo.toml @@ -0,0 +1,10 @@ +[package] +name = "otc_diagnostic" +version.workspace = true +edition.workspace = true +license.workspace = true + +[dependencies] +bevy_ecs = { workspace = true } +bevy_app = { workspace = true } +tracing = { workspace = true } diff --git a/rust/crates/otc_discord/Cargo.toml b/rust/crates/otc_discord/Cargo.toml new file mode 100644 index 0000000000..bdb4f40871 --- /dev/null +++ b/rust/crates/otc_discord/Cargo.toml @@ -0,0 +1,13 @@ +[package] +name = "otc_discord" +version.workspace = true +edition.workspace = true +license.workspace = true + +[features] +discord_rpc = [] + +[dependencies] +bevy_ecs = { workspace = true } +bevy_app = { workspace = true } +tracing = { workspace = true } diff --git a/rust/crates/otc_game/Cargo.toml b/rust/crates/otc_game/Cargo.toml new file mode 100644 index 0000000000..9020fa1edd --- /dev/null +++ b/rust/crates/otc_game/Cargo.toml @@ -0,0 +1,15 @@ +[package] +name = "otc_game" +version.workspace = true +edition.workspace = true +license.workspace = true + +[dependencies] +bevy_ecs = { workspace = true } +bevy_app = { workspace = true } +bevy_reflect = { workspace = true } +otc_protocol = { workspace = true } +otc_asset = { workspace = true } +otc_transform = { workspace = true } +glam = { workspace = true } +tracing = { workspace = true } diff --git a/rust/crates/otc_hierarchy/Cargo.toml b/rust/crates/otc_hierarchy/Cargo.toml new file mode 100644 index 0000000000..5fff4f3fe8 --- /dev/null +++ b/rust/crates/otc_hierarchy/Cargo.toml @@ -0,0 +1,10 @@ +[package] +name = "otc_hierarchy" +version.workspace = true +edition.workspace = true +license.workspace = true + +[dependencies] +bevy_ecs = { workspace = true } +bevy_app = { workspace = true } +bevy_reflect = { workspace = true } diff --git a/rust/crates/otc_image/Cargo.toml b/rust/crates/otc_image/Cargo.toml new file mode 100644 index 0000000000..6bd7c662f1 --- /dev/null +++ b/rust/crates/otc_image/Cargo.toml @@ -0,0 +1,10 @@ +[package] +name = "otc_image" +version.workspace = true +edition.workspace = true +license.workspace = true + +[dependencies] +image = { workspace = true } +otc_asset = { workspace = true } +bevy_reflect = { workspace = true } diff --git a/rust/crates/otc_input/Cargo.toml b/rust/crates/otc_input/Cargo.toml new file mode 100644 index 0000000000..67ce800b13 --- /dev/null +++ b/rust/crates/otc_input/Cargo.toml @@ -0,0 +1,11 @@ +[package] +name = "otc_input" +version.workspace = true +edition.workspace = true +license.workspace = true + +[dependencies] +bevy_ecs = { workspace = true } +bevy_app = { workspace = true } +bevy_reflect = { workspace = true } +winit = { workspace = true } diff --git a/rust/crates/otc_log/Cargo.toml b/rust/crates/otc_log/Cargo.toml new file mode 100644 index 0000000000..261b201901 --- /dev/null +++ b/rust/crates/otc_log/Cargo.toml @@ -0,0 +1,9 @@ +[package] +name = "otc_log" +version.workspace = true +edition.workspace = true +license.workspace = true + +[dependencies] +tracing = { workspace = true } +tracing-subscriber = { workspace = true } diff --git a/rust/crates/otc_lua/Cargo.toml b/rust/crates/otc_lua/Cargo.toml new file mode 100644 index 0000000000..135fae5f01 --- /dev/null +++ b/rust/crates/otc_lua/Cargo.toml @@ -0,0 +1,13 @@ +[package] +name = "otc_lua" +version.workspace = true +edition.workspace = true +license.workspace = true + +[dependencies] +bevy_ecs = { workspace = true } +bevy_app = { workspace = true } +bevy_reflect = { workspace = true } +mlua = { workspace = true } +otc_otml = { workspace = true } +tracing = { workspace = true } diff --git a/rust/crates/otc_lua_derive/Cargo.toml b/rust/crates/otc_lua_derive/Cargo.toml new file mode 100644 index 0000000000..28b21b3206 --- /dev/null +++ b/rust/crates/otc_lua_derive/Cargo.toml @@ -0,0 +1,13 @@ +[package] +name = "otc_lua_derive" +version.workspace = true +edition.workspace = true +license.workspace = true + +[lib] +proc-macro = true + +[dependencies] +syn = { version = "2", features = ["full"] } +quote = "1" +proc-macro2 = "1" diff --git a/rust/crates/otc_map_render/Cargo.toml b/rust/crates/otc_map_render/Cargo.toml new file mode 100644 index 0000000000..688fa4ac5b --- /dev/null +++ b/rust/crates/otc_map_render/Cargo.toml @@ -0,0 +1,17 @@ +[package] +name = "otc_map_render" +version.workspace = true +edition.workspace = true +license.workspace = true + +[dependencies] +bevy_ecs = { workspace = true } +bevy_app = { workspace = true } +otc_render = { workspace = true } +otc_sprite = { workspace = true } +otc_game = { workspace = true } +otc_thing = { workspace = true } +otc_transform = { workspace = true } +glam = { workspace = true } +wgpu = { workspace = true } +tracing = { workspace = true } diff --git a/rust/crates/otc_net/Cargo.toml b/rust/crates/otc_net/Cargo.toml new file mode 100644 index 0000000000..60978def97 --- /dev/null +++ b/rust/crates/otc_net/Cargo.toml @@ -0,0 +1,14 @@ +[package] +name = "otc_net" +version.workspace = true +edition.workspace = true +license.workspace = true + +[dependencies] +tokio = { workspace = true } +tokio-tungstenite = { workspace = true } +reqwest = { workspace = true } +flate2 = { workspace = true } +byteorder = { workspace = true } +thiserror = { workspace = true } +tracing = { workspace = true } diff --git a/rust/crates/otc_otml/Cargo.toml b/rust/crates/otc_otml/Cargo.toml new file mode 100644 index 0000000000..a8a38e279c --- /dev/null +++ b/rust/crates/otc_otml/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "otc_otml" +version.workspace = true +edition.workspace = true +license.workspace = true + +[dependencies] diff --git a/rust/crates/otc_platform/Cargo.toml b/rust/crates/otc_platform/Cargo.toml new file mode 100644 index 0000000000..037f84be5d --- /dev/null +++ b/rust/crates/otc_platform/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "otc_platform" +version.workspace = true +edition.workspace = true +license.workspace = true + +[dependencies] diff --git a/rust/crates/otc_protobuf/Cargo.toml b/rust/crates/otc_protobuf/Cargo.toml new file mode 100644 index 0000000000..868c82c695 --- /dev/null +++ b/rust/crates/otc_protobuf/Cargo.toml @@ -0,0 +1,11 @@ +[package] +name = "otc_protobuf" +version.workspace = true +edition.workspace = true +license.workspace = true + +[dependencies] +prost = { workspace = true } + +[build-dependencies] +prost-build = { workspace = true } diff --git a/rust/crates/otc_protocol/Cargo.toml b/rust/crates/otc_protocol/Cargo.toml new file mode 100644 index 0000000000..791391936b --- /dev/null +++ b/rust/crates/otc_protocol/Cargo.toml @@ -0,0 +1,13 @@ +[package] +name = "otc_protocol" +version.workspace = true +edition.workspace = true +license.workspace = true + +[dependencies] +bevy_ecs = { workspace = true } +bevy_app = { workspace = true } +otc_net = { workspace = true } +thiserror = { workspace = true } +tracing = { workspace = true } +byteorder = { workspace = true } diff --git a/rust/crates/otc_render/Cargo.toml b/rust/crates/otc_render/Cargo.toml new file mode 100644 index 0000000000..771818b7e1 --- /dev/null +++ b/rust/crates/otc_render/Cargo.toml @@ -0,0 +1,16 @@ +[package] +name = "otc_render" +version.workspace = true +edition.workspace = true +license.workspace = true + +[dependencies] +bevy_ecs = { workspace = true } +bevy_app = { workspace = true } +wgpu = { workspace = true } +otc_asset = { workspace = true } +otc_window = { workspace = true } +otc_transform = { workspace = true } +otc_color = { workspace = true } +bytemuck = { workspace = true } +tracing = { workspace = true } diff --git a/rust/crates/otc_shader/Cargo.toml b/rust/crates/otc_shader/Cargo.toml new file mode 100644 index 0000000000..d613cc0726 --- /dev/null +++ b/rust/crates/otc_shader/Cargo.toml @@ -0,0 +1,13 @@ +[package] +name = "otc_shader" +version.workspace = true +edition.workspace = true +license.workspace = true + +[dependencies] +bevy_ecs = { workspace = true } +bevy_app = { workspace = true } +wgpu = { workspace = true } +otc_asset = { workspace = true } +otc_render = { workspace = true } +tracing = { workspace = true } diff --git a/rust/crates/otc_sprite/Cargo.toml b/rust/crates/otc_sprite/Cargo.toml new file mode 100644 index 0000000000..046edb0102 --- /dev/null +++ b/rust/crates/otc_sprite/Cargo.toml @@ -0,0 +1,14 @@ +[package] +name = "otc_sprite" +version.workspace = true +edition.workspace = true +license.workspace = true + +[dependencies] +bevy_ecs = { workspace = true } +bevy_app = { workspace = true } +otc_render = { workspace = true } +otc_asset = { workspace = true } +otc_transform = { workspace = true } +glam = { workspace = true } +bytemuck = { workspace = true } diff --git a/rust/crates/otc_text/Cargo.toml b/rust/crates/otc_text/Cargo.toml new file mode 100644 index 0000000000..918fc23dab --- /dev/null +++ b/rust/crates/otc_text/Cargo.toml @@ -0,0 +1,13 @@ +[package] +name = "otc_text" +version.workspace = true +edition.workspace = true +license.workspace = true + +[dependencies] +bevy_ecs = { workspace = true } +bevy_app = { workspace = true } +cosmic-text = { workspace = true } +otc_render = { workspace = true } +otc_asset = { workspace = true } +otc_color = { workspace = true } diff --git a/rust/crates/otc_thing/Cargo.toml b/rust/crates/otc_thing/Cargo.toml new file mode 100644 index 0000000000..24250fcafa --- /dev/null +++ b/rust/crates/otc_thing/Cargo.toml @@ -0,0 +1,14 @@ +[package] +name = "otc_thing" +version.workspace = true +edition.workspace = true +license.workspace = true + +[dependencies] +bevy_ecs = { workspace = true } +bevy_app = { workspace = true } +bevy_reflect = { workspace = true } +otc_asset = { workspace = true } +otc_protobuf = { workspace = true } +otc_render = { workspace = true } +tracing = { workspace = true } diff --git a/rust/crates/otc_time/Cargo.toml b/rust/crates/otc_time/Cargo.toml new file mode 100644 index 0000000000..54f80bdc9f --- /dev/null +++ b/rust/crates/otc_time/Cargo.toml @@ -0,0 +1,10 @@ +[package] +name = "otc_time" +version.workspace = true +edition.workspace = true +license.workspace = true + +[dependencies] +bevy_ecs = { workspace = true } +bevy_app = { workspace = true } +bevy_reflect = { workspace = true } diff --git a/rust/crates/otc_transform/Cargo.toml b/rust/crates/otc_transform/Cargo.toml new file mode 100644 index 0000000000..cf81847370 --- /dev/null +++ b/rust/crates/otc_transform/Cargo.toml @@ -0,0 +1,11 @@ +[package] +name = "otc_transform" +version.workspace = true +edition.workspace = true +license.workspace = true + +[dependencies] +bevy_ecs = { workspace = true } +bevy_app = { workspace = true } +bevy_reflect = { workspace = true } +glam = { workspace = true } diff --git a/rust/crates/otc_ui/Cargo.toml b/rust/crates/otc_ui/Cargo.toml new file mode 100644 index 0000000000..7ccb1faca1 --- /dev/null +++ b/rust/crates/otc_ui/Cargo.toml @@ -0,0 +1,19 @@ +[package] +name = "otc_ui" +version.workspace = true +edition.workspace = true +license.workspace = true + +[dependencies] +bevy_ecs = { workspace = true } +bevy_app = { workspace = true } +bevy_reflect = { workspace = true } +taffy = { workspace = true } +otc_render = { workspace = true } +otc_otml = { workspace = true } +otc_input = { workspace = true } +otc_color = { workspace = true } +otc_hierarchy = { workspace = true } +scraper = { workspace = true } +lightningcss = { workspace = true } +tracing = { workspace = true } diff --git a/rust/crates/otc_ui_widgets/Cargo.toml b/rust/crates/otc_ui_widgets/Cargo.toml new file mode 100644 index 0000000000..a1fdd1e8fc --- /dev/null +++ b/rust/crates/otc_ui_widgets/Cargo.toml @@ -0,0 +1,12 @@ +[package] +name = "otc_ui_widgets" +version.workspace = true +edition.workspace = true +license.workspace = true + +[dependencies] +bevy_ecs = { workspace = true } +bevy_app = { workspace = true } +otc_ui = { workspace = true } +otc_render = { workspace = true } +otc_game = { workspace = true } diff --git a/rust/crates/otc_window/Cargo.toml b/rust/crates/otc_window/Cargo.toml new file mode 100644 index 0000000000..bdb83d1043 --- /dev/null +++ b/rust/crates/otc_window/Cargo.toml @@ -0,0 +1,11 @@ +[package] +name = "otc_window" +version.workspace = true +edition.workspace = true +license.workspace = true + +[dependencies] +bevy_ecs = { workspace = true } +bevy_app = { workspace = true } +bevy_reflect = { workspace = true } +raw-window-handle = { workspace = true } diff --git a/rust/crates/otc_winit/Cargo.toml b/rust/crates/otc_winit/Cargo.toml new file mode 100644 index 0000000000..c410d33e2d --- /dev/null +++ b/rust/crates/otc_winit/Cargo.toml @@ -0,0 +1,13 @@ +[package] +name = "otc_winit" +version.workspace = true +edition.workspace = true +license.workspace = true + +[dependencies] +bevy_ecs = { workspace = true } +bevy_app = { workspace = true } +winit = { workspace = true } +raw-window-handle = { workspace = true } +otc_window = { workspace = true } +otc_input = { workspace = true } diff --git a/rust/otclient/Cargo.toml b/rust/otclient/Cargo.toml new file mode 100644 index 0000000000..330746d951 --- /dev/null +++ b/rust/otclient/Cargo.toml @@ -0,0 +1,45 @@ +[package] +name = "otclient" +version.workspace = true +edition.workspace = true +license.workspace = true + +[[bin]] +name = "otclient" +path = "src/main.rs" + +[features] +discord_rpc = ["otc_discord"] + +[dependencies] +bevy_ecs = { workspace = true } +bevy_app = { workspace = true } +otc_log = { workspace = true } +otc_window = { workspace = true } +otc_winit = { workspace = true } +otc_input = { workspace = true } +otc_time = { workspace = true } +otc_transform = { workspace = true } +otc_hierarchy = { workspace = true } +otc_color = { workspace = true } +otc_render = { workspace = true } +otc_shader = { workspace = true } +otc_sprite = { workspace = true } +otc_text = { workspace = true } +otc_image = { workspace = true } +otc_asset = { workspace = true } +otc_ui = { workspace = true } +otc_ui_widgets = { workspace = true } +otc_net = { workspace = true } +otc_protocol = { workspace = true } +otc_game = { workspace = true } +otc_thing = { workspace = true } +otc_map_render = { workspace = true } +otc_audio = { workspace = true } +otc_lua = { workspace = true } +otc_otml = { workspace = true } +otc_protobuf = { workspace = true } +otc_platform = { workspace = true } +otc_diagnostic = { workspace = true } +tracing = { workspace = true } +otc_discord = { workspace = true, optional = true } From 274c1c1df0d0a95a921c70a6cf535e9a2b02e96d Mon Sep 17 00:00:00 2001 From: twodreams Date: Sun, 1 Mar 2026 22:07:04 -0300 Subject: [PATCH 3/8] feat: add migration plan for OTClient C++ to Rust --- rust.md | 434 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 434 insertions(+) create mode 100644 rust.md diff --git a/rust.md b/rust.md new file mode 100644 index 0000000000..2ea78e30f1 --- /dev/null +++ b/rust.md @@ -0,0 +1,434 @@ +# Plano de Migração: OTClient C++ → Rust + +## Visão Geral + +Reescrever o OTClient (~86.000 LOC C++) em Rust. Construir nosso **próprio framework** usando módulos do Bevy de 3 formas: + +**1. Dependência direta (4 crates no Cargo.toml, usados como estão)**: +- `bevy_ecs` — ECS: World, Entity, Component, Resource, Query, System, Schedule, Events +- `bevy_app` — App builder, Plugin trait, Schedules +- `bevy_tasks` — Async task pools +- `bevy_reflect` — Reflection (útil para Lua interop) + +**2. Código copiado do Bevy para dentro do projeto (modificado ou não)**: +- Render pipeline, shader system, sprite batching, asset system, input, window, time, transforms, UI layout, etc. +- Se o módulo funcionar como está → copiar sem modificar +- Se precisar de adaptação → copiar e modificar + +**3. Código 100% nosso** + crates open-source standalone (wgpu, tokio, mlua, kira, etc.): +- Protocolo Tibia, networking, game logic, OTML, Lua bridge, áudio, UI widgets, map rendering + +--- + +## Estrutura de Crates + +``` +otclient-rs/ +├── Cargo.toml # Workspace +├── crates/ +│ │ +│ │ ═══════════ COPIADO DO BEVY (modificado ou não) ═══════════ +│ │ +│ ├── otc_render/ # De bevy_render — render pipeline +│ │ └── src/ +│ │ ├── lib.rs # RenderPlugin +│ │ ├── renderer.rs # wgpu device/queue/surface +│ │ ├── render_phase.rs # Extract/Prepare/Queue/Render +│ │ ├── render_resource.rs # GPU buffers, bind groups, pipelines +│ │ └── view.rs # Camera/viewport 2D +│ │ +│ ├── otc_shader/ # De bevy_shader — shader system +│ │ └── src/ # Shader loading, preprocessing, naga +│ │ +│ ├── otc_sprite/ # De bevy_sprite — 2D sprite + batching +│ │ └── src/ # Sprite, SpriteBatch, TextureAtlas +│ │ +│ ├── otc_text/ # De bevy_text — text rendering +│ │ └── src/ # cosmic-text, font atlas +│ │ +│ ├── otc_image/ # De bevy_image — image loading +│ │ └── src/ # PNG, BMP, APNG +│ │ +│ ├── otc_asset/ # De bevy_asset — asset system +│ │ └── src/ # AssetServer, AssetLoader, Handle, cache +│ │ +│ ├── otc_window/ # De bevy_window — window abstraction +│ │ └── src/ +│ │ +│ ├── otc_winit/ # De bevy_winit — winit backend +│ │ └── src/ +│ │ +│ ├── otc_input/ # De bevy_input — keyboard/mouse +│ │ └── src/ +│ │ +│ ├── otc_time/ # De bevy_time — Time, Timer, Stopwatch +│ │ └── src/ +│ │ +│ ├── otc_transform/ # De bevy_transform — Transform, GlobalTransform +│ │ └── src/ +│ │ +│ ├── otc_hierarchy/ # De bevy_hierarchy — Parent/Children +│ │ └── src/ +│ │ +│ ├── otc_color/ # De bevy_color — Color types +│ │ └── src/ +│ │ +│ ├── otc_log/ # De bevy_log — tracing setup +│ │ └── src/ +│ │ +│ ├── otc_diagnostic/ # De bevy_diagnostic — FPS, diagnostics +│ │ └── src/ +│ │ +│ │ ═══════════ UI (nosso, inspirado em bevy_ui + fyrox-ui) ═══════════ +│ │ +│ ├── otc_ui/ # UI framework retained-mode +│ │ └── src/ +│ │ ├── lib.rs # UiPlugin +│ │ ├── widget.rs # Widget base +│ │ ├── layout.rs # taffy Flexbox/Grid (de bevy_ui) +│ │ ├── style.rs # OTML → widget style bridge +│ │ ├── manager.rs # UiManager — API unificada create() +│ │ ├── text_edit.rs # Widget de texto editável +│ │ ├── html.rs # Rich text (scraper + lightningcss) +│ │ └── draw.rs # Draw command buffer → render +│ │ +│ ├── otc_ui_widgets/ # Widgets game-specific +│ │ └── src/ # UIMap, UIMinimap, UIItem, UICreature, etc. +│ │ +│ │ ═══════════ PLATFORM (nosso) ═══════════ +│ │ +│ ├── otc_platform/ # Platform utils (clipboard, crash handler) +│ │ └── src/ +│ │ +│ │ ═══════════ NETWORKING (nosso) ═══════════ +│ │ +│ ├── otc_net/ # Networking core (tokio) +│ │ └── src/ +│ │ ├── lib.rs # NetPlugin +│ │ ├── connection.rs # TCP async +│ │ ├── web_connection.rs # WebSocket +│ │ ├── protocol.rs # XTEA, zlib, checksum +│ │ ├── message.rs # InputMessage / OutputMessage +│ │ ├── http.rs # HTTP client (reqwest) +│ │ └── encryption.rs # XTEA cipher +│ │ +│ ├── otc_protocol/ # Protocolo Tibia +│ │ └── src/ +│ │ ├── lib.rs # ProtocolPlugin +│ │ ├── opcodes.rs # Constantes +│ │ ├── packets.rs # Structs tipados (~200 packets) +│ │ ├── parse.rs # Server → Client +│ │ └── send.rs # Client → Server +│ │ +│ │ ═══════════ SCRIPTING (nosso) ═══════════ +│ │ +│ ├── otc_lua/ # Lua scripting (mlua) +│ │ └── src/ +│ │ ├── lib.rs # LuaPlugin +│ │ ├── engine.rs # mlua runtime como Resource +│ │ ├── bindings_framework.rs # Bindings do framework +│ │ ├── bindings_client.rs # Bindings do client +│ │ ├── module_loader.rs # Carrega .otmod +│ │ └── value_casts.rs # Conversões Rust ↔ Lua +│ │ +│ ├── otc_lua_derive/ # Proc macros para Lua +│ │ └── src/ # #[derive(LuaBindable)] +│ │ +│ │ ═══════════ DATA FORMATS (nosso) ═══════════ +│ │ +│ ├── otc_otml/ # Parser OTML (lib pura) +│ │ └── src/ +│ │ +│ ├── otc_protobuf/ # Protobuf (prost) +│ │ └── src/ +│ │ +│ │ ═══════════ GAME CLIENT (nosso, portado do C++) ═══════════ +│ │ +│ ├── otc_game/ # Game state & logic +│ │ └── src/ +│ │ ├── lib.rs # GamePlugin +│ │ ├── components.rs # ECS Components +│ │ ├── bundles.rs # CreatureBundle, ItemBundle, etc. +│ │ ├── resources.rs # GameState, ContainerManager, VipList, etc. +│ │ ├── map.rs # TileMap + TileBlock +│ │ ├── creature.rs # Creature systems +│ │ ├── item.rs # Item systems +│ │ ├── effect.rs # Effect/missile systems +│ │ ├── container.rs # Inventory/container +│ │ └── config.rs # GameConfig +│ │ +│ ├── otc_thing/ # ThingType, SpriteManager (AssetLoaders) +│ │ └── src/ +│ │ +│ ├── otc_map_render/ # Renderização do mapa +│ │ └── src/ +│ │ ├── lib.rs # MapRenderPlugin +│ │ ├── map_view.rs # Tile map render +│ │ ├── light_view.rs # 2D lighting +│ │ ├── creature_render.rs # Creature/outfit rendering +│ │ ├── minimap.rs # Minimap +│ │ ├── draw_pool.rs # Hash change detection +│ │ └── shaders/ # WGSL (map, light, creature, effect) +│ │ +│ │ ═══════════ ÁUDIO (nosso) ═══════════ +│ │ +│ ├── otc_audio/ # Audio (kira) +│ │ └── src/ +│ │ +│ │ ═══════════ EXTRAS ═══════════ +│ │ +│ └── otc_discord/ # Discord RPC (feature flag) +│ └── src/ +│ +├── src/main.rs # Entry point +├── modules/ # 71 módulos Lua (atualizados) +├── data/ # Assets +└── proto/ # .proto files +``` + +--- + +## Dependências + +```toml +# ── Bevy (apenas 4 crates) ── +bevy_ecs = "0.15" +bevy_app = "0.15" +bevy_tasks = "0.15" +bevy_reflect = "0.15" + +# ── GPU & Windowing ── +wgpu = "24" +winit = "0.30" +glam = "0.29" # Math (vetores, matrizes) +taffy = "0.7" # Layout (Flexbox/Grid) + +# ── Networking ── +tokio = { version = "1", features = ["full"] } +tokio-tungstenite = "0.26" +reqwest = "0.12" + +# ── Scripting ── +mlua = { version = "0.10", features = ["luajit"] } + +# ── Serialization ── +prost = "0.13" +serde = { version = "1", features = ["derive"] } +serde_json = "1" +quick-xml = "0.37" + +# ── Rendering ── +cosmic-text = "0.12" # Fontes +image = "0.25" # Imagens + +# ── HTML/CSS ── +scraper = "0.22" +lightningcss = "1" + +# ── Compression/Crypto ── +flate2 = "1" +lzma-rs = "0.3" +rustls = "0.23" + +# ── Audio ── +kira = "0.9" + +# ── Utilities ── +tracing = "0.1" +tracing-subscriber = "0.3" +thiserror = "2" +anyhow = "1" +uuid = "1" +dashmap = "6" +rayon = "1" +``` + +--- + +## Mapeamento C++ → Rust ECS + +| C++ (atual) | Rust (novo) | +|---|---| +| `g_game`, `g_map`, `g_ui`, etc. (30+ singletons) | `Resource` no ECS World | +| `Creature`, `Item`, `Effect`, `Missile` (classes OOP) | Entities + Components (bundles) | +| `Thing` (base class) | Trait + query filters | +| `EventDispatcher` + callbacks | `Events` + `EventReader`/`EventWriter` | +| `UIWidget` hierarchy | Entity tree com `otc_ui` Components | +| `ProtocolGame::parse*()` (236.9KB) | Systems que lêem `Events` → emitem `Events` | +| `SoundManager` | Resource no ECS, systems para playback | +| `ModuleManager` (Lua) | Resource + system de carregamento | +| `MapView::render()`, `LightView` | Render systems (Extract/Prepare/Queue) | +| Game flow (login, char select, in-game) | `States` via `bevy_app` | + +--- + +## Simplificações + +### 1. UI: 3 métodos de criação → 1 +```rust +pub fn create(source: WidgetSource, parent: Option) -> WidgetId +``` + +### 2. Layout: 6 engines → taffy (Flexbox + Grid) +- UIHorizontalLayout → `FlexDirection::Row` +- UIVerticalLayout → `FlexDirection::Column` +- UIGridLayout → CSS Grid +- UIAnchorLayout → `Position::Absolute` +- UIBoxLayout / UIFlexbox → Flexbox + +### 3. 30+ singletons → ECS Resources + +### 4. Game monolítico (62KB) → Systems + Resources decompostos + +### 5. HTML/CSS parser: 95KB custom → scraper + lightningcss + +### 6. OTML: Manter formato, reimplementar em Rust + +### 7. Lua: API redesenhada para Rust, scripts atualizados +- Nova API modelada sobre o ECS +- 71 módulos Lua portados para nova API +- `.otmod` lifecycle mantido +- Proc macros `#[derive(LuaBindable)]` para bindings automáticos + +--- + +## Fases + +### Fase 0: Fundação (3-4 semanas) +- Setup workspace Cargo com bevy_ecs + bevy_app + bevy_tasks + bevy_reflect como dependências +- Copiar do Bevy: otc_window (bevy_window), otc_winit (bevy_winit), otc_input (bevy_input), otc_time (bevy_time), otc_log (bevy_log), otc_color (bevy_color) +- `otc_otml`: implementar parser OTML +- Setup CI + +**Entregável**: App abre janela, plugins rodam, states funcionam. + +### Fase 1: Render Pipeline (4-6 semanas) — PARALELA com Fase 2 +- Copiar do Bevy: otc_render (bevy_render), otc_shader (bevy_shader), otc_sprite (bevy_sprite), otc_text (bevy_text), otc_image (bevy_image), otc_transform (bevy_transform) +- Modificar otc_render para pipeline 2D (remover 3D) +- Modificar otc_sprite para tile map + atlas do Tibia +- DrawPool com hash change detection (portado do C++) +- Converter shaders GLSL → WGSL + +**Entregável**: Renderiza sprites, texto, shapes com batching. + +### Fase 2: Networking + Protocolo (4-5 semanas) — PARALELA com Fase 1 +- `otc_net`: TCP (tokio), WebSocket, XTEA, zlib, HTTP (reqwest) +- `otc_protocol`: ~200 packets tipados, parse systems, send systems +- Portar protocolgameparse.cpp (236.9KB) e protocolgamesend.cpp (51.5KB) + +**Entregável**: Conecta a servidor, parseia packets, emite Events. + +### Fase 3: Game State (4-5 semanas) +- Copiar do Bevy: otc_asset (bevy_asset), otc_hierarchy (bevy_hierarchy) +- `otc_thing`: ThingType + SpriteManager como AssetLoaders custom +- `otc_game`: Components, Bundles, Resources, TileMap, systems +- `otc_protobuf`: prost para appearances/sounds/staticdata +- Decompor Game (62KB) em sub-Resources + Systems + +**Entregável**: Game state completo no ECS. + +### Fase 4: Map Render (3-4 semanas) +- `otc_map_render`: tiles, criaturas, iluminação, minimap +- WGSL shaders do cliente + +**Entregável**: Mapa renderiza com criaturas e luz. + +### Fase 5: UI (4-5 semanas) +- `otc_ui`: widgets retained-mode, taffy layout, OTML bridge, HTML rich text +- `otc_ui_widgets`: UIMap, UIItem, UICreature, UIMinimap, etc. +- API unificada create() + +**Entregável**: UI carregada de .otui. + +### Fase 6: Lua (3-4 semanas) +- `otc_lua`: mlua runtime, bindings, module loader +- `otc_lua_derive`: proc macros +- Portar 71 módulos Lua para nova API + +**Entregável**: Módulos Lua funcionam. + +### Fase 7: Áudio + Polish (2-3 semanas) +- `otc_audio`: kira +- Discord RPC, WASM build, profiling + +**Entregável**: Cliente feature-complete. + +--- + +## Cronograma + +``` +Semana: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 + ├───Fase 0────┤ + ├─────Fase 1──────┤ (PARALELA) + ├────Fase 2─────┤ (PARALELA) + ├────Fase 3─────┤ + ├───Fase 4────┤ + ├────Fase 5─────┤ + ├───Fase 6────┤ + ├──Fase 7──┤ +``` + +--- + +## Riscos + +| Risco | Severidade | Mitigação | +|---|---|---| +| Protocolo: 236.9KB parsing byte-compatible | ALTO | Packet dumps como fixtures; strong typing | +| Lua: portar 71 módulos para nova API | ALTO | Portar incrementalmente; testar por módulo | +| Render performance | MÉDIO | DrawPool hash detection; benchmark contínuo | +| UI com OTML | MÉDIO | Widget system próprio; testar com .otui existentes | + +--- + +## Módulos Bevy copiados para o projeto + +| Bevy source | Nosso crate | Modificação | +|---|---|---| +| `bevy_render/` | `otc_render/` | Adaptar para 2D, remover 3D | +| `bevy_shader/` | `otc_shader/` | Adaptar defines para nossos shaders | +| `bevy_sprite/` | `otc_sprite/` | Adaptar para tile map do Tibia | +| `bevy_text/` | `otc_text/` | Copiar, avaliar se modifica | +| `bevy_image/` | `otc_image/` | Copiar, adicionar APNG | +| `bevy_asset/` | `otc_asset/` | Copiar, avaliar se modifica | +| `bevy_window/` | `otc_window/` | Copiar, avaliar se modifica | +| `bevy_winit/` | `otc_winit/` | Copiar, avaliar se modifica | +| `bevy_input/` | `otc_input/` | Copiar, avaliar se modifica | +| `bevy_time/` | `otc_time/` | Copiar sem modificar | +| `bevy_transform/` | `otc_transform/` | Copiar sem modificar | +| `bevy_hierarchy/` | `otc_hierarchy/` | Copiar sem modificar | +| `bevy_color/` | `otc_color/` | Copiar sem modificar | +| `bevy_log/` | `otc_log/` | Copiar sem modificar | +| `bevy_diagnostic/` | `otc_diagnostic/` | Copiar sem modificar | +| `bevy_ui/src/layout/` | `otc_ui/layout.rs` | Copiar integração taffy, adaptar para OTML | + +## Referências C++ (para portar) + +| Arquivo | O que portar | +|---|---| +| `protocolgameparse.cpp` (236.9KB) | ~200 packet parsers | +| `protocolgamesend.cpp` (51.5KB) | ~100 send commands | +| `drawpool.h` (365 LOC) | Hash change detection | +| `uiwidget.h` (2.532 LOC) | Sistema de widgets | +| `otmlparser.h` | Parser OTML | +| `mapview.cpp` (38.8KB) | Render do mapa | +| `creature.cpp` (50.3KB) | Lógica de criatura → Components | +| `game.cpp` (62KB) | Game state → Resources + Systems | +| `luafunctions.cpp` (95KB + 87KB) | Referência para API Lua | + +--- + +## Progresso + +### Feito +- Workspace Cargo.toml criado em `rust/` com todos os 30 crates + workspace dependencies +- Diretórios `crates/*/src/` criados para todos os 30 crates +- Cargo.toml individual de cada crate criado com dependências corretas (usando `workspace = true`) +- Plano salvo em `docs/rust-migration-plan.md` e commitado +- Binary crate `otclient/` criado com dependência em todos os crates + +### Próximo +- Criar `lib.rs` stub em cada crate para que o workspace compile +- Copiar código do Bevy para os crates que vêm dele (começando pela Fase 0: window, winit, input, time, log, color) +- Implementar `otc_otml` parser From 5301002e862d53380682c66ad1cc0a635a8a52b3 Mon Sep 17 00:00:00 2001 From: twodreams Date: Mon, 2 Mar 2026 07:09:27 -0300 Subject: [PATCH 4/8] feat: update Rust migration plan with clear crate structure and progress details --- docs/rust-migration-plan.md | 82 ++++--- rust.md | 434 ------------------------------------ 2 files changed, 55 insertions(+), 461 deletions(-) delete mode 100644 rust.md diff --git a/docs/rust-migration-plan.md b/docs/rust-migration-plan.md index 635418fa46..c527389c18 100644 --- a/docs/rust-migration-plan.md +++ b/docs/rust-migration-plan.md @@ -22,12 +22,15 @@ Reescrever o OTClient (~86.000 LOC C++) em Rust. Construir nosso **próprio fram ## Estrutura de Crates +Separação clara entre **engine** (framework reutilizável, genérico) e **client** (específico do Tibia/OTClient). + ``` otclient-rs/ ├── Cargo.toml # Workspace -├── crates/ +│ +├── engine/ # ═══ ENGINE (framework genérico) ═══ │ │ -│ │ ═══════════ COPIADO DO BEVY (modificado ou não) ═══════════ +│ │ ── Copiado do Bevy (modificado ou não) ── │ │ │ ├── otc_render/ # De bevy_render — render pipeline │ │ └── src/ @@ -79,7 +82,7 @@ otclient-rs/ │ ├── otc_diagnostic/ # De bevy_diagnostic — FPS, diagnostics │ │ └── src/ │ │ -│ │ ═══════════ UI (nosso, inspirado em bevy_ui + fyrox-ui) ═══════════ +│ │ ── UI (nosso, inspirado em bevy_ui + fyrox-ui) ── │ │ │ ├── otc_ui/ # UI framework retained-mode │ │ └── src/ @@ -92,15 +95,12 @@ otclient-rs/ │ │ ├── html.rs # Rich text (scraper + lightningcss) │ │ └── draw.rs # Draw command buffer → render │ │ -│ ├── otc_ui_widgets/ # Widgets game-specific -│ │ └── src/ # UIMap, UIMinimap, UIItem, UICreature, etc. -│ │ -│ │ ═══════════ PLATFORM (nosso) ═══════════ +│ │ ── Platform ── │ │ │ ├── otc_platform/ # Platform utils (clipboard, crash handler) │ │ └── src/ │ │ -│ │ ═══════════ NETWORKING (nosso) ═══════════ +│ │ ── Networking (core genérico) ── │ │ │ ├── otc_net/ # Networking core (tokio) │ │ └── src/ @@ -112,37 +112,45 @@ otclient-rs/ │ │ ├── http.rs # HTTP client (reqwest) │ │ └── encryption.rs # XTEA cipher │ │ -│ ├── otc_protocol/ # Protocolo Tibia -│ │ └── src/ -│ │ ├── lib.rs # ProtocolPlugin -│ │ ├── opcodes.rs # Constantes -│ │ ├── packets.rs # Structs tipados (~200 packets) -│ │ ├── parse.rs # Server → Client -│ │ └── send.rs # Client → Server -│ │ -│ │ ═══════════ SCRIPTING (nosso) ═══════════ +│ │ ── Scripting (core genérico) ── │ │ │ ├── otc_lua/ # Lua scripting (mlua) │ │ └── src/ │ │ ├── lib.rs # LuaPlugin │ │ ├── engine.rs # mlua runtime como Resource -│ │ ├── bindings_framework.rs # Bindings do framework -│ │ ├── bindings_client.rs # Bindings do client +│ │ ├── bindings.rs # Bindings do framework │ │ ├── module_loader.rs # Carrega .otmod │ │ └── value_casts.rs # Conversões Rust ↔ Lua │ │ │ ├── otc_lua_derive/ # Proc macros para Lua │ │ └── src/ # #[derive(LuaBindable)] │ │ -│ │ ═══════════ DATA FORMATS (nosso) ═══════════ +│ │ ── Data Formats ── │ │ │ ├── otc_otml/ # Parser OTML (lib pura) │ │ └── src/ │ │ -│ ├── otc_protobuf/ # Protobuf (prost) +│ │ ── Áudio ── +│ │ +│ └── otc_audio/ # Audio (kira) +│ └── src/ +│ +├── client/ # ═══ CLIENT (específico Tibia/OTClient) ═══ +│ │ +│ │ ── Protocolo Tibia ── +│ │ +│ ├── otc_protocol/ # Protocolo Tibia │ │ └── src/ +│ │ ├── lib.rs # ProtocolPlugin +│ │ ├── opcodes.rs # Constantes +│ │ ├── packets.rs # Structs tipados (~200 packets) +│ │ ├── parse.rs # Server → Client +│ │ └── send.rs # Client → Server +│ │ +│ ├── otc_protobuf/ # Protobuf Tibia (prost) +│ │ └── src/ # appearances, sounds, staticdata │ │ -│ │ ═══════════ GAME CLIENT (nosso, portado do C++) ═══════════ +│ │ ── Game Logic ── │ │ │ ├── otc_game/ # Game state & logic │ │ └── src/ @@ -155,11 +163,14 @@ otclient-rs/ │ │ ├── item.rs # Item systems │ │ ├── effect.rs # Effect/missile systems │ │ ├── container.rs # Inventory/container +│ │ ├── lua_bindings.rs # Bindings Lua do client │ │ └── config.rs # GameConfig │ │ │ ├── otc_thing/ # ThingType, SpriteManager (AssetLoaders) │ │ └── src/ │ │ +│ │ ── Rendering game-specific ── +│ │ │ ├── otc_map_render/ # Renderização do mapa │ │ └── src/ │ │ ├── lib.rs # MapRenderPlugin @@ -170,17 +181,20 @@ otclient-rs/ │ │ ├── draw_pool.rs # Hash change detection │ │ └── shaders/ # WGSL (map, light, creature, effect) │ │ -│ │ ═══════════ ÁUDIO (nosso) ═══════════ +│ │ ── UI game-specific ── │ │ -│ ├── otc_audio/ # Audio (kira) -│ │ └── src/ +│ ├── otc_ui_widgets/ # Widgets game-specific +│ │ └── src/ # UIMap, UIMinimap, UIItem, UICreature, etc. │ │ -│ │ ═══════════ EXTRAS ═══════════ +│ │ ── Extras ── │ │ │ └── otc_discord/ # Discord RPC (feature flag) │ └── src/ │ -├── src/main.rs # Entry point +├── otclient/ # ═══ BINARY ═══ +│ ├── Cargo.toml +│ └── src/main.rs # Entry point +│ ├── modules/ # 71 módulos Lua (atualizados) ├── data/ # Assets └── proto/ # .proto files @@ -416,3 +430,17 @@ Semana: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 | `creature.cpp` (50.3KB) | Lógica de criatura → Components | | `game.cpp` (62KB) | Game state → Resources + Systems | | `luafunctions.cpp` (95KB + 87KB) | Referência para API Lua | + +## Progresso + +### Feito +- Workspace Cargo.toml criado em `rust/` com todos os 30 crates + workspace dependencies +- Diretórios `crates/*/src/` criados para todos os 30 crates +- Cargo.toml individual de cada crate criado com dependências corretas (usando `workspace = true`) +- Plano salvo em `docs/rust-migration-plan.md` e commitado +- Binary crate `otclient/` criado com dependência em todos os crates + +### Próximo +- Criar `lib.rs` stub em cada crate para que o workspace compile +- Copiar código do Bevy para os crates que vêm dele (começando pela Fase 0: window, winit, input, time, log, color) +- Implementar `otc_otml` parser diff --git a/rust.md b/rust.md deleted file mode 100644 index 2ea78e30f1..0000000000 --- a/rust.md +++ /dev/null @@ -1,434 +0,0 @@ -# Plano de Migração: OTClient C++ → Rust - -## Visão Geral - -Reescrever o OTClient (~86.000 LOC C++) em Rust. Construir nosso **próprio framework** usando módulos do Bevy de 3 formas: - -**1. Dependência direta (4 crates no Cargo.toml, usados como estão)**: -- `bevy_ecs` — ECS: World, Entity, Component, Resource, Query, System, Schedule, Events -- `bevy_app` — App builder, Plugin trait, Schedules -- `bevy_tasks` — Async task pools -- `bevy_reflect` — Reflection (útil para Lua interop) - -**2. Código copiado do Bevy para dentro do projeto (modificado ou não)**: -- Render pipeline, shader system, sprite batching, asset system, input, window, time, transforms, UI layout, etc. -- Se o módulo funcionar como está → copiar sem modificar -- Se precisar de adaptação → copiar e modificar - -**3. Código 100% nosso** + crates open-source standalone (wgpu, tokio, mlua, kira, etc.): -- Protocolo Tibia, networking, game logic, OTML, Lua bridge, áudio, UI widgets, map rendering - ---- - -## Estrutura de Crates - -``` -otclient-rs/ -├── Cargo.toml # Workspace -├── crates/ -│ │ -│ │ ═══════════ COPIADO DO BEVY (modificado ou não) ═══════════ -│ │ -│ ├── otc_render/ # De bevy_render — render pipeline -│ │ └── src/ -│ │ ├── lib.rs # RenderPlugin -│ │ ├── renderer.rs # wgpu device/queue/surface -│ │ ├── render_phase.rs # Extract/Prepare/Queue/Render -│ │ ├── render_resource.rs # GPU buffers, bind groups, pipelines -│ │ └── view.rs # Camera/viewport 2D -│ │ -│ ├── otc_shader/ # De bevy_shader — shader system -│ │ └── src/ # Shader loading, preprocessing, naga -│ │ -│ ├── otc_sprite/ # De bevy_sprite — 2D sprite + batching -│ │ └── src/ # Sprite, SpriteBatch, TextureAtlas -│ │ -│ ├── otc_text/ # De bevy_text — text rendering -│ │ └── src/ # cosmic-text, font atlas -│ │ -│ ├── otc_image/ # De bevy_image — image loading -│ │ └── src/ # PNG, BMP, APNG -│ │ -│ ├── otc_asset/ # De bevy_asset — asset system -│ │ └── src/ # AssetServer, AssetLoader, Handle, cache -│ │ -│ ├── otc_window/ # De bevy_window — window abstraction -│ │ └── src/ -│ │ -│ ├── otc_winit/ # De bevy_winit — winit backend -│ │ └── src/ -│ │ -│ ├── otc_input/ # De bevy_input — keyboard/mouse -│ │ └── src/ -│ │ -│ ├── otc_time/ # De bevy_time — Time, Timer, Stopwatch -│ │ └── src/ -│ │ -│ ├── otc_transform/ # De bevy_transform — Transform, GlobalTransform -│ │ └── src/ -│ │ -│ ├── otc_hierarchy/ # De bevy_hierarchy — Parent/Children -│ │ └── src/ -│ │ -│ ├── otc_color/ # De bevy_color — Color types -│ │ └── src/ -│ │ -│ ├── otc_log/ # De bevy_log — tracing setup -│ │ └── src/ -│ │ -│ ├── otc_diagnostic/ # De bevy_diagnostic — FPS, diagnostics -│ │ └── src/ -│ │ -│ │ ═══════════ UI (nosso, inspirado em bevy_ui + fyrox-ui) ═══════════ -│ │ -│ ├── otc_ui/ # UI framework retained-mode -│ │ └── src/ -│ │ ├── lib.rs # UiPlugin -│ │ ├── widget.rs # Widget base -│ │ ├── layout.rs # taffy Flexbox/Grid (de bevy_ui) -│ │ ├── style.rs # OTML → widget style bridge -│ │ ├── manager.rs # UiManager — API unificada create() -│ │ ├── text_edit.rs # Widget de texto editável -│ │ ├── html.rs # Rich text (scraper + lightningcss) -│ │ └── draw.rs # Draw command buffer → render -│ │ -│ ├── otc_ui_widgets/ # Widgets game-specific -│ │ └── src/ # UIMap, UIMinimap, UIItem, UICreature, etc. -│ │ -│ │ ═══════════ PLATFORM (nosso) ═══════════ -│ │ -│ ├── otc_platform/ # Platform utils (clipboard, crash handler) -│ │ └── src/ -│ │ -│ │ ═══════════ NETWORKING (nosso) ═══════════ -│ │ -│ ├── otc_net/ # Networking core (tokio) -│ │ └── src/ -│ │ ├── lib.rs # NetPlugin -│ │ ├── connection.rs # TCP async -│ │ ├── web_connection.rs # WebSocket -│ │ ├── protocol.rs # XTEA, zlib, checksum -│ │ ├── message.rs # InputMessage / OutputMessage -│ │ ├── http.rs # HTTP client (reqwest) -│ │ └── encryption.rs # XTEA cipher -│ │ -│ ├── otc_protocol/ # Protocolo Tibia -│ │ └── src/ -│ │ ├── lib.rs # ProtocolPlugin -│ │ ├── opcodes.rs # Constantes -│ │ ├── packets.rs # Structs tipados (~200 packets) -│ │ ├── parse.rs # Server → Client -│ │ └── send.rs # Client → Server -│ │ -│ │ ═══════════ SCRIPTING (nosso) ═══════════ -│ │ -│ ├── otc_lua/ # Lua scripting (mlua) -│ │ └── src/ -│ │ ├── lib.rs # LuaPlugin -│ │ ├── engine.rs # mlua runtime como Resource -│ │ ├── bindings_framework.rs # Bindings do framework -│ │ ├── bindings_client.rs # Bindings do client -│ │ ├── module_loader.rs # Carrega .otmod -│ │ └── value_casts.rs # Conversões Rust ↔ Lua -│ │ -│ ├── otc_lua_derive/ # Proc macros para Lua -│ │ └── src/ # #[derive(LuaBindable)] -│ │ -│ │ ═══════════ DATA FORMATS (nosso) ═══════════ -│ │ -│ ├── otc_otml/ # Parser OTML (lib pura) -│ │ └── src/ -│ │ -│ ├── otc_protobuf/ # Protobuf (prost) -│ │ └── src/ -│ │ -│ │ ═══════════ GAME CLIENT (nosso, portado do C++) ═══════════ -│ │ -│ ├── otc_game/ # Game state & logic -│ │ └── src/ -│ │ ├── lib.rs # GamePlugin -│ │ ├── components.rs # ECS Components -│ │ ├── bundles.rs # CreatureBundle, ItemBundle, etc. -│ │ ├── resources.rs # GameState, ContainerManager, VipList, etc. -│ │ ├── map.rs # TileMap + TileBlock -│ │ ├── creature.rs # Creature systems -│ │ ├── item.rs # Item systems -│ │ ├── effect.rs # Effect/missile systems -│ │ ├── container.rs # Inventory/container -│ │ └── config.rs # GameConfig -│ │ -│ ├── otc_thing/ # ThingType, SpriteManager (AssetLoaders) -│ │ └── src/ -│ │ -│ ├── otc_map_render/ # Renderização do mapa -│ │ └── src/ -│ │ ├── lib.rs # MapRenderPlugin -│ │ ├── map_view.rs # Tile map render -│ │ ├── light_view.rs # 2D lighting -│ │ ├── creature_render.rs # Creature/outfit rendering -│ │ ├── minimap.rs # Minimap -│ │ ├── draw_pool.rs # Hash change detection -│ │ └── shaders/ # WGSL (map, light, creature, effect) -│ │ -│ │ ═══════════ ÁUDIO (nosso) ═══════════ -│ │ -│ ├── otc_audio/ # Audio (kira) -│ │ └── src/ -│ │ -│ │ ═══════════ EXTRAS ═══════════ -│ │ -│ └── otc_discord/ # Discord RPC (feature flag) -│ └── src/ -│ -├── src/main.rs # Entry point -├── modules/ # 71 módulos Lua (atualizados) -├── data/ # Assets -└── proto/ # .proto files -``` - ---- - -## Dependências - -```toml -# ── Bevy (apenas 4 crates) ── -bevy_ecs = "0.15" -bevy_app = "0.15" -bevy_tasks = "0.15" -bevy_reflect = "0.15" - -# ── GPU & Windowing ── -wgpu = "24" -winit = "0.30" -glam = "0.29" # Math (vetores, matrizes) -taffy = "0.7" # Layout (Flexbox/Grid) - -# ── Networking ── -tokio = { version = "1", features = ["full"] } -tokio-tungstenite = "0.26" -reqwest = "0.12" - -# ── Scripting ── -mlua = { version = "0.10", features = ["luajit"] } - -# ── Serialization ── -prost = "0.13" -serde = { version = "1", features = ["derive"] } -serde_json = "1" -quick-xml = "0.37" - -# ── Rendering ── -cosmic-text = "0.12" # Fontes -image = "0.25" # Imagens - -# ── HTML/CSS ── -scraper = "0.22" -lightningcss = "1" - -# ── Compression/Crypto ── -flate2 = "1" -lzma-rs = "0.3" -rustls = "0.23" - -# ── Audio ── -kira = "0.9" - -# ── Utilities ── -tracing = "0.1" -tracing-subscriber = "0.3" -thiserror = "2" -anyhow = "1" -uuid = "1" -dashmap = "6" -rayon = "1" -``` - ---- - -## Mapeamento C++ → Rust ECS - -| C++ (atual) | Rust (novo) | -|---|---| -| `g_game`, `g_map`, `g_ui`, etc. (30+ singletons) | `Resource` no ECS World | -| `Creature`, `Item`, `Effect`, `Missile` (classes OOP) | Entities + Components (bundles) | -| `Thing` (base class) | Trait + query filters | -| `EventDispatcher` + callbacks | `Events` + `EventReader`/`EventWriter` | -| `UIWidget` hierarchy | Entity tree com `otc_ui` Components | -| `ProtocolGame::parse*()` (236.9KB) | Systems que lêem `Events` → emitem `Events` | -| `SoundManager` | Resource no ECS, systems para playback | -| `ModuleManager` (Lua) | Resource + system de carregamento | -| `MapView::render()`, `LightView` | Render systems (Extract/Prepare/Queue) | -| Game flow (login, char select, in-game) | `States` via `bevy_app` | - ---- - -## Simplificações - -### 1. UI: 3 métodos de criação → 1 -```rust -pub fn create(source: WidgetSource, parent: Option) -> WidgetId -``` - -### 2. Layout: 6 engines → taffy (Flexbox + Grid) -- UIHorizontalLayout → `FlexDirection::Row` -- UIVerticalLayout → `FlexDirection::Column` -- UIGridLayout → CSS Grid -- UIAnchorLayout → `Position::Absolute` -- UIBoxLayout / UIFlexbox → Flexbox - -### 3. 30+ singletons → ECS Resources - -### 4. Game monolítico (62KB) → Systems + Resources decompostos - -### 5. HTML/CSS parser: 95KB custom → scraper + lightningcss - -### 6. OTML: Manter formato, reimplementar em Rust - -### 7. Lua: API redesenhada para Rust, scripts atualizados -- Nova API modelada sobre o ECS -- 71 módulos Lua portados para nova API -- `.otmod` lifecycle mantido -- Proc macros `#[derive(LuaBindable)]` para bindings automáticos - ---- - -## Fases - -### Fase 0: Fundação (3-4 semanas) -- Setup workspace Cargo com bevy_ecs + bevy_app + bevy_tasks + bevy_reflect como dependências -- Copiar do Bevy: otc_window (bevy_window), otc_winit (bevy_winit), otc_input (bevy_input), otc_time (bevy_time), otc_log (bevy_log), otc_color (bevy_color) -- `otc_otml`: implementar parser OTML -- Setup CI - -**Entregável**: App abre janela, plugins rodam, states funcionam. - -### Fase 1: Render Pipeline (4-6 semanas) — PARALELA com Fase 2 -- Copiar do Bevy: otc_render (bevy_render), otc_shader (bevy_shader), otc_sprite (bevy_sprite), otc_text (bevy_text), otc_image (bevy_image), otc_transform (bevy_transform) -- Modificar otc_render para pipeline 2D (remover 3D) -- Modificar otc_sprite para tile map + atlas do Tibia -- DrawPool com hash change detection (portado do C++) -- Converter shaders GLSL → WGSL - -**Entregável**: Renderiza sprites, texto, shapes com batching. - -### Fase 2: Networking + Protocolo (4-5 semanas) — PARALELA com Fase 1 -- `otc_net`: TCP (tokio), WebSocket, XTEA, zlib, HTTP (reqwest) -- `otc_protocol`: ~200 packets tipados, parse systems, send systems -- Portar protocolgameparse.cpp (236.9KB) e protocolgamesend.cpp (51.5KB) - -**Entregável**: Conecta a servidor, parseia packets, emite Events. - -### Fase 3: Game State (4-5 semanas) -- Copiar do Bevy: otc_asset (bevy_asset), otc_hierarchy (bevy_hierarchy) -- `otc_thing`: ThingType + SpriteManager como AssetLoaders custom -- `otc_game`: Components, Bundles, Resources, TileMap, systems -- `otc_protobuf`: prost para appearances/sounds/staticdata -- Decompor Game (62KB) em sub-Resources + Systems - -**Entregável**: Game state completo no ECS. - -### Fase 4: Map Render (3-4 semanas) -- `otc_map_render`: tiles, criaturas, iluminação, minimap -- WGSL shaders do cliente - -**Entregável**: Mapa renderiza com criaturas e luz. - -### Fase 5: UI (4-5 semanas) -- `otc_ui`: widgets retained-mode, taffy layout, OTML bridge, HTML rich text -- `otc_ui_widgets`: UIMap, UIItem, UICreature, UIMinimap, etc. -- API unificada create() - -**Entregável**: UI carregada de .otui. - -### Fase 6: Lua (3-4 semanas) -- `otc_lua`: mlua runtime, bindings, module loader -- `otc_lua_derive`: proc macros -- Portar 71 módulos Lua para nova API - -**Entregável**: Módulos Lua funcionam. - -### Fase 7: Áudio + Polish (2-3 semanas) -- `otc_audio`: kira -- Discord RPC, WASM build, profiling - -**Entregável**: Cliente feature-complete. - ---- - -## Cronograma - -``` -Semana: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 - ├───Fase 0────┤ - ├─────Fase 1──────┤ (PARALELA) - ├────Fase 2─────┤ (PARALELA) - ├────Fase 3─────┤ - ├───Fase 4────┤ - ├────Fase 5─────┤ - ├───Fase 6────┤ - ├──Fase 7──┤ -``` - ---- - -## Riscos - -| Risco | Severidade | Mitigação | -|---|---|---| -| Protocolo: 236.9KB parsing byte-compatible | ALTO | Packet dumps como fixtures; strong typing | -| Lua: portar 71 módulos para nova API | ALTO | Portar incrementalmente; testar por módulo | -| Render performance | MÉDIO | DrawPool hash detection; benchmark contínuo | -| UI com OTML | MÉDIO | Widget system próprio; testar com .otui existentes | - ---- - -## Módulos Bevy copiados para o projeto - -| Bevy source | Nosso crate | Modificação | -|---|---|---| -| `bevy_render/` | `otc_render/` | Adaptar para 2D, remover 3D | -| `bevy_shader/` | `otc_shader/` | Adaptar defines para nossos shaders | -| `bevy_sprite/` | `otc_sprite/` | Adaptar para tile map do Tibia | -| `bevy_text/` | `otc_text/` | Copiar, avaliar se modifica | -| `bevy_image/` | `otc_image/` | Copiar, adicionar APNG | -| `bevy_asset/` | `otc_asset/` | Copiar, avaliar se modifica | -| `bevy_window/` | `otc_window/` | Copiar, avaliar se modifica | -| `bevy_winit/` | `otc_winit/` | Copiar, avaliar se modifica | -| `bevy_input/` | `otc_input/` | Copiar, avaliar se modifica | -| `bevy_time/` | `otc_time/` | Copiar sem modificar | -| `bevy_transform/` | `otc_transform/` | Copiar sem modificar | -| `bevy_hierarchy/` | `otc_hierarchy/` | Copiar sem modificar | -| `bevy_color/` | `otc_color/` | Copiar sem modificar | -| `bevy_log/` | `otc_log/` | Copiar sem modificar | -| `bevy_diagnostic/` | `otc_diagnostic/` | Copiar sem modificar | -| `bevy_ui/src/layout/` | `otc_ui/layout.rs` | Copiar integração taffy, adaptar para OTML | - -## Referências C++ (para portar) - -| Arquivo | O que portar | -|---|---| -| `protocolgameparse.cpp` (236.9KB) | ~200 packet parsers | -| `protocolgamesend.cpp` (51.5KB) | ~100 send commands | -| `drawpool.h` (365 LOC) | Hash change detection | -| `uiwidget.h` (2.532 LOC) | Sistema de widgets | -| `otmlparser.h` | Parser OTML | -| `mapview.cpp` (38.8KB) | Render do mapa | -| `creature.cpp` (50.3KB) | Lógica de criatura → Components | -| `game.cpp` (62KB) | Game state → Resources + Systems | -| `luafunctions.cpp` (95KB + 87KB) | Referência para API Lua | - ---- - -## Progresso - -### Feito -- Workspace Cargo.toml criado em `rust/` com todos os 30 crates + workspace dependencies -- Diretórios `crates/*/src/` criados para todos os 30 crates -- Cargo.toml individual de cada crate criado com dependências corretas (usando `workspace = true`) -- Plano salvo em `docs/rust-migration-plan.md` e commitado -- Binary crate `otclient/` criado com dependência em todos os crates - -### Próximo -- Criar `lib.rs` stub em cada crate para que o workspace compile -- Copiar código do Bevy para os crates que vêm dele (começando pela Fase 0: window, winit, input, time, log, color) -- Implementar `otc_otml` parser From a54329ed8e58ac06bbdeba8a7c6c7b79b5663f9a Mon Sep 17 00:00:00 2001 From: twodreams Date: Mon, 2 Mar 2026 07:11:45 -0300 Subject: [PATCH 5/8] feat: add Dockerfile, devcontainer configuration, and firewall script for Claude Code environment --- .devcontainer/Dockerfile | 91 +++++++++++++++++++++ .devcontainer/devcontainer.json | 57 +++++++++++++ .devcontainer/init-firewall.sh | 137 ++++++++++++++++++++++++++++++++ scripts/ralph/CLAUDE.md | 104 ++++++++++++++++++++++++ scripts/ralph/ralph.sh | 113 ++++++++++++++++++++++++++ 5 files changed, 502 insertions(+) create mode 100644 .devcontainer/Dockerfile create mode 100644 .devcontainer/devcontainer.json create mode 100644 .devcontainer/init-firewall.sh create mode 100644 scripts/ralph/CLAUDE.md create mode 100644 scripts/ralph/ralph.sh diff --git a/.devcontainer/Dockerfile b/.devcontainer/Dockerfile new file mode 100644 index 0000000000..8b48f6ad72 --- /dev/null +++ b/.devcontainer/Dockerfile @@ -0,0 +1,91 @@ +FROM node:20 + +ARG TZ +ENV TZ="$TZ" + +ARG CLAUDE_CODE_VERSION=latest + +# Install basic development tools and iptables/ipset +RUN apt-get update && apt-get install -y --no-install-recommends \ + less \ + git \ + procps \ + sudo \ + fzf \ + zsh \ + man-db \ + unzip \ + gnupg2 \ + gh \ + iptables \ + ipset \ + iproute2 \ + dnsutils \ + aggregate \ + jq \ + nano \ + vim \ + && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Ensure default node user has access to /usr/local/share +RUN mkdir -p /usr/local/share/npm-global && \ + chown -R node:node /usr/local/share + +ARG USERNAME=node + +# Persist bash history. +RUN SNIPPET="export PROMPT_COMMAND='history -a' && export HISTFILE=/commandhistory/.bash_history" \ + && mkdir /commandhistory \ + && touch /commandhistory/.bash_history \ + && chown -R $USERNAME /commandhistory + +# Set `DEVCONTAINER` environment variable to help with orientation +ENV DEVCONTAINER=true + +# Create workspace and config directories and set permissions +RUN mkdir -p /workspace /home/node/.claude && \ + chown -R node:node /workspace /home/node/.claude + +WORKDIR /workspace + +ARG GIT_DELTA_VERSION=0.18.2 +RUN ARCH=$(dpkg --print-architecture) && \ + wget "https://github.com/dandavison/delta/releases/download/${GIT_DELTA_VERSION}/git-delta_${GIT_DELTA_VERSION}_${ARCH}.deb" && \ + sudo dpkg -i "git-delta_${GIT_DELTA_VERSION}_${ARCH}.deb" && \ + rm "git-delta_${GIT_DELTA_VERSION}_${ARCH}.deb" + +# Set up non-root user +USER node + +# Install global packages +ENV NPM_CONFIG_PREFIX=/usr/local/share/npm-global +ENV PATH=$PATH:/usr/local/share/npm-global/bin + +# Set the default shell to zsh rather than sh +ENV SHELL=/bin/zsh + +# Set the default editor and visual +ENV EDITOR=nano +ENV VISUAL=nano + +# Default powerline10k theme +ARG ZSH_IN_DOCKER_VERSION=1.2.0 +RUN sh -c "$(wget -O- https://github.com/deluan/zsh-in-docker/releases/download/v${ZSH_IN_DOCKER_VERSION}/zsh-in-docker.sh)" -- \ + -p git \ + -p fzf \ + -a "source /usr/share/doc/fzf/examples/key-bindings.zsh" \ + -a "source /usr/share/doc/fzf/examples/completion.zsh" \ + -a "export PROMPT_COMMAND='history -a' && export HISTFILE=/commandhistory/.bash_history" \ + -x + +# Install Claude +RUN npm install -g @anthropic-ai/claude-code@${CLAUDE_CODE_VERSION} + + +# Copy and set up firewall script +COPY init-firewall.sh /usr/local/bin/ +USER root +RUN chmod +x /usr/local/bin/init-firewall.sh && \ + echo "node ALL=(root) NOPASSWD: /usr/local/bin/init-firewall.sh" > /etc/sudoers.d/node-firewall && \ + chmod 0440 /etc/sudoers.d/node-firewall +USER node diff --git a/.devcontainer/devcontainer.json b/.devcontainer/devcontainer.json new file mode 100644 index 0000000000..7f6a172d1c --- /dev/null +++ b/.devcontainer/devcontainer.json @@ -0,0 +1,57 @@ +{ + "name": "Claude Code Sandbox", + "build": { + "dockerfile": "Dockerfile", + "args": { + "TZ": "${localEnv:TZ:America/Los_Angeles}", + "CLAUDE_CODE_VERSION": "latest", + "GIT_DELTA_VERSION": "0.18.2", + "ZSH_IN_DOCKER_VERSION": "1.2.0" + } + }, + "runArgs": [ + "--cap-add=NET_ADMIN", + "--cap-add=NET_RAW" + ], + "customizations": { + "vscode": { + "extensions": [ + "anthropic.claude-code", + "dbaeumer.vscode-eslint", + "esbenp.prettier-vscode", + "eamodio.gitlens" + ], + "settings": { + "editor.formatOnSave": true, + "editor.defaultFormatter": "esbenp.prettier-vscode", + "editor.codeActionsOnSave": { + "source.fixAll.eslint": "explicit" + }, + "terminal.integrated.defaultProfile.linux": "zsh", + "terminal.integrated.profiles.linux": { + "bash": { + "path": "bash", + "icon": "terminal-bash" + }, + "zsh": { + "path": "zsh" + } + } + } + } + }, + "remoteUser": "node", + "mounts": [ + "source=claude-code-bashhistory-${devcontainerId},target=/commandhistory,type=volume", + "source=claude-code-config-${devcontainerId},target=/home/node/.claude,type=volume" + ], + "containerEnv": { + "NODE_OPTIONS": "--max-old-space-size=4096", + "CLAUDE_CONFIG_DIR": "/home/node/.claude", + "POWERLEVEL9K_DISABLE_GITSTATUS": "true" + }, + "workspaceMount": "source=${localWorkspaceFolder},target=/workspace,type=bind,consistency=delegated", + "workspaceFolder": "/workspace", + "postStartCommand": "sudo /usr/local/bin/init-firewall.sh", + "waitFor": "postStartCommand" +} diff --git a/.devcontainer/init-firewall.sh b/.devcontainer/init-firewall.sh new file mode 100644 index 0000000000..16d492dd26 --- /dev/null +++ b/.devcontainer/init-firewall.sh @@ -0,0 +1,137 @@ +#!/bin/bash +set -euo pipefail # Exit on error, undefined vars, and pipeline failures +IFS=$'\n\t' # Stricter word splitting + +# 1. Extract Docker DNS info BEFORE any flushing +DOCKER_DNS_RULES=$(iptables-save -t nat | grep "127\.0\.0\.11" || true) + +# Flush existing rules and delete existing ipsets +iptables -F +iptables -X +iptables -t nat -F +iptables -t nat -X +iptables -t mangle -F +iptables -t mangle -X +ipset destroy allowed-domains 2>/dev/null || true + +# 2. Selectively restore ONLY internal Docker DNS resolution +if [ -n "$DOCKER_DNS_RULES" ]; then + echo "Restoring Docker DNS rules..." + iptables -t nat -N DOCKER_OUTPUT 2>/dev/null || true + iptables -t nat -N DOCKER_POSTROUTING 2>/dev/null || true + echo "$DOCKER_DNS_RULES" | xargs -L 1 iptables -t nat +else + echo "No Docker DNS rules to restore" +fi + +# First allow DNS and localhost before any restrictions +# Allow outbound DNS +iptables -A OUTPUT -p udp --dport 53 -j ACCEPT +# Allow inbound DNS responses +iptables -A INPUT -p udp --sport 53 -j ACCEPT +# Allow outbound SSH +iptables -A OUTPUT -p tcp --dport 22 -j ACCEPT +# Allow inbound SSH responses +iptables -A INPUT -p tcp --sport 22 -m state --state ESTABLISHED -j ACCEPT +# Allow localhost +iptables -A INPUT -i lo -j ACCEPT +iptables -A OUTPUT -o lo -j ACCEPT + +# Create ipset with CIDR support +ipset create allowed-domains hash:net + +# Fetch GitHub meta information and aggregate + add their IP ranges +echo "Fetching GitHub IP ranges..." +gh_ranges=$(curl -s https://api.github.com/meta) +if [ -z "$gh_ranges" ]; then + echo "ERROR: Failed to fetch GitHub IP ranges" + exit 1 +fi + +if ! echo "$gh_ranges" | jq -e '.web and .api and .git' >/dev/null; then + echo "ERROR: GitHub API response missing required fields" + exit 1 +fi + +echo "Processing GitHub IPs..." +while read -r cidr; do + if [[ ! "$cidr" =~ ^[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}/[0-9]{1,2}$ ]]; then + echo "ERROR: Invalid CIDR range from GitHub meta: $cidr" + exit 1 + fi + echo "Adding GitHub range $cidr" + ipset add allowed-domains "$cidr" +done < <(echo "$gh_ranges" | jq -r '(.web + .api + .git)[]' | aggregate -q) + +# Resolve and add other allowed domains +for domain in \ + "registry.npmjs.org" \ + "api.anthropic.com" \ + "sentry.io" \ + "statsig.anthropic.com" \ + "statsig.com" \ + "marketplace.visualstudio.com" \ + "vscode.blob.core.windows.net" \ + "update.code.visualstudio.com"; do + echo "Resolving $domain..." + ips=$(dig +noall +answer A "$domain" | awk '$4 == "A" {print $5}') + if [ -z "$ips" ]; then + echo "ERROR: Failed to resolve $domain" + exit 1 + fi + + while read -r ip; do + if [[ ! "$ip" =~ ^[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}$ ]]; then + echo "ERROR: Invalid IP from DNS for $domain: $ip" + exit 1 + fi + echo "Adding $ip for $domain" + ipset add allowed-domains "$ip" + done < <(echo "$ips") +done + +# Get host IP from default route +HOST_IP=$(ip route | grep default | cut -d" " -f3) +if [ -z "$HOST_IP" ]; then + echo "ERROR: Failed to detect host IP" + exit 1 +fi + +HOST_NETWORK=$(echo "$HOST_IP" | sed "s/\.[0-9]*$/.0\/24/") +echo "Host network detected as: $HOST_NETWORK" + +# Set up remaining iptables rules +iptables -A INPUT -s "$HOST_NETWORK" -j ACCEPT +iptables -A OUTPUT -d "$HOST_NETWORK" -j ACCEPT + +# Set default policies to DROP first +iptables -P INPUT DROP +iptables -P FORWARD DROP +iptables -P OUTPUT DROP + +# First allow established connections for already approved traffic +iptables -A INPUT -m state --state ESTABLISHED,RELATED -j ACCEPT +iptables -A OUTPUT -m state --state ESTABLISHED,RELATED -j ACCEPT + +# Then allow only specific outbound traffic to allowed domains +iptables -A OUTPUT -m set --match-set allowed-domains dst -j ACCEPT + +# Explicitly REJECT all other outbound traffic for immediate feedback +iptables -A OUTPUT -j REJECT --reject-with icmp-admin-prohibited + +echo "Firewall configuration complete" +echo "Verifying firewall rules..." +if curl --connect-timeout 5 https://example.com >/dev/null 2>&1; then + echo "ERROR: Firewall verification failed - was able to reach https://example.com" + exit 1 +else + echo "Firewall verification passed - unable to reach https://example.com as expected" +fi + +# Verify GitHub API access +if ! curl --connect-timeout 5 https://api.github.com/zen >/dev/null 2>&1; then + echo "ERROR: Firewall verification failed - unable to reach https://api.github.com" + exit 1 +else + echo "Firewall verification passed - able to reach https://api.github.com as expected" +fi diff --git a/scripts/ralph/CLAUDE.md b/scripts/ralph/CLAUDE.md new file mode 100644 index 0000000000..f95bb927e1 --- /dev/null +++ b/scripts/ralph/CLAUDE.md @@ -0,0 +1,104 @@ +# Ralph Agent Instructions + +You are an autonomous coding agent working on a software project. + +## Your Task + +1. Read the PRD at `prd.json` (in the same directory as this file) +2. Read the progress log at `progress.txt` (check Codebase Patterns section first) +3. Check you're on the correct branch from PRD `branchName`. If not, check it out or create from main. +4. Pick the **highest priority** user story where `passes: false` +5. Implement that single user story +6. Run quality checks (e.g., typecheck, lint, test - use whatever your project requires) +7. Update CLAUDE.md files if you discover reusable patterns (see below) +8. If checks pass, commit ALL changes with message: `feat: [Story ID] - [Story Title]` +9. Update the PRD to set `passes: true` for the completed story +10. Append your progress to `progress.txt` + +## Progress Report Format + +APPEND to progress.txt (never replace, always append): +``` +## [Date/Time] - [Story ID] +- What was implemented +- Files changed +- **Learnings for future iterations:** + - Patterns discovered (e.g., "this codebase uses X for Y") + - Gotchas encountered (e.g., "don't forget to update Z when changing W") + - Useful context (e.g., "the evaluation panel is in component X") +--- +``` + +The learnings section is critical - it helps future iterations avoid repeating mistakes and understand the codebase better. + +## Consolidate Patterns + +If you discover a **reusable pattern** that future iterations should know, add it to the `## Codebase Patterns` section at the TOP of progress.txt (create it if it doesn't exist). This section should consolidate the most important learnings: + +``` +## Codebase Patterns +- Example: Use `sql` template for aggregations +- Example: Always use `IF NOT EXISTS` for migrations +- Example: Export types from actions.ts for UI components +``` + +Only add patterns that are **general and reusable**, not story-specific details. + +## Update CLAUDE.md Files + +Before committing, check if any edited files have learnings worth preserving in nearby CLAUDE.md files: + +1. **Identify directories with edited files** - Look at which directories you modified +2. **Check for existing CLAUDE.md** - Look for CLAUDE.md in those directories or parent directories +3. **Add valuable learnings** - If you discovered something future developers/agents should know: + - API patterns or conventions specific to that module + - Gotchas or non-obvious requirements + - Dependencies between files + - Testing approaches for that area + - Configuration or environment requirements + +**Examples of good CLAUDE.md additions:** +- "When modifying X, also update Y to keep them in sync" +- "This module uses pattern Z for all API calls" +- "Tests require the dev server running on PORT 3000" +- "Field names must match the template exactly" + +**Do NOT add:** +- Story-specific implementation details +- Temporary debugging notes +- Information already in progress.txt + +Only update CLAUDE.md if you have **genuinely reusable knowledge** that would help future work in that directory. + +## Quality Requirements + +- ALL commits must pass your project's quality checks (typecheck, lint, test) +- Do NOT commit broken code +- Keep changes focused and minimal +- Follow existing code patterns + +## Browser Testing (If Available) + +For any story that changes UI, verify it works in the browser if you have browser testing tools configured (e.g., via MCP): + +1. Navigate to the relevant page +2. Verify the UI changes work as expected +3. Take a screenshot if helpful for the progress log + +If no browser tools are available, note in your progress report that manual browser verification is needed. + +## Stop Condition + +After completing a user story, check if ALL stories have `passes: true`. + +If ALL stories are complete and passing, reply with: +COMPLETE + +If there are still stories with `passes: false`, end your response normally (another iteration will pick up the next story). + +## Important + +- Work on ONE story per iteration +- Commit frequently +- Keep CI green +- Read the Codebase Patterns section in progress.txt before starting diff --git a/scripts/ralph/ralph.sh b/scripts/ralph/ralph.sh new file mode 100644 index 0000000000..baff052ac3 --- /dev/null +++ b/scripts/ralph/ralph.sh @@ -0,0 +1,113 @@ +#!/bin/bash +# Ralph Wiggum - Long-running AI agent loop +# Usage: ./ralph.sh [--tool amp|claude] [max_iterations] + +set -e + +# Parse arguments +TOOL="amp" # Default to amp for backwards compatibility +MAX_ITERATIONS=10 + +while [[ $# -gt 0 ]]; do + case $1 in + --tool) + TOOL="$2" + shift 2 + ;; + --tool=*) + TOOL="${1#*=}" + shift + ;; + *) + # Assume it's max_iterations if it's a number + if [[ "$1" =~ ^[0-9]+$ ]]; then + MAX_ITERATIONS="$1" + fi + shift + ;; + esac +done + +# Validate tool choice +if [[ "$TOOL" != "amp" && "$TOOL" != "claude" ]]; then + echo "Error: Invalid tool '$TOOL'. Must be 'amp' or 'claude'." + exit 1 +fi +SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +PRD_FILE="$SCRIPT_DIR/prd.json" +PROGRESS_FILE="$SCRIPT_DIR/progress.txt" +ARCHIVE_DIR="$SCRIPT_DIR/archive" +LAST_BRANCH_FILE="$SCRIPT_DIR/.last-branch" + +# Archive previous run if branch changed +if [ -f "$PRD_FILE" ] && [ -f "$LAST_BRANCH_FILE" ]; then + CURRENT_BRANCH=$(jq -r '.branchName // empty' "$PRD_FILE" 2>/dev/null || echo "") + LAST_BRANCH=$(cat "$LAST_BRANCH_FILE" 2>/dev/null || echo "") + + if [ -n "$CURRENT_BRANCH" ] && [ -n "$LAST_BRANCH" ] && [ "$CURRENT_BRANCH" != "$LAST_BRANCH" ]; then + # Archive the previous run + DATE=$(date +%Y-%m-%d) + # Strip "ralph/" prefix from branch name for folder + FOLDER_NAME=$(echo "$LAST_BRANCH" | sed 's|^ralph/||') + ARCHIVE_FOLDER="$ARCHIVE_DIR/$DATE-$FOLDER_NAME" + + echo "Archiving previous run: $LAST_BRANCH" + mkdir -p "$ARCHIVE_FOLDER" + [ -f "$PRD_FILE" ] && cp "$PRD_FILE" "$ARCHIVE_FOLDER/" + [ -f "$PROGRESS_FILE" ] && cp "$PROGRESS_FILE" "$ARCHIVE_FOLDER/" + echo " Archived to: $ARCHIVE_FOLDER" + + # Reset progress file for new run + echo "# Ralph Progress Log" > "$PROGRESS_FILE" + echo "Started: $(date)" >> "$PROGRESS_FILE" + echo "---" >> "$PROGRESS_FILE" + fi +fi + +# Track current branch +if [ -f "$PRD_FILE" ]; then + CURRENT_BRANCH=$(jq -r '.branchName // empty' "$PRD_FILE" 2>/dev/null || echo "") + if [ -n "$CURRENT_BRANCH" ]; then + echo "$CURRENT_BRANCH" > "$LAST_BRANCH_FILE" + fi +fi + +# Initialize progress file if it doesn't exist +if [ ! -f "$PROGRESS_FILE" ]; then + echo "# Ralph Progress Log" > "$PROGRESS_FILE" + echo "Started: $(date)" >> "$PROGRESS_FILE" + echo "---" >> "$PROGRESS_FILE" +fi + +echo "Starting Ralph - Tool: $TOOL - Max iterations: $MAX_ITERATIONS" + +for i in $(seq 1 $MAX_ITERATIONS); do + echo "" + echo "===============================================================" + echo " Ralph Iteration $i of $MAX_ITERATIONS ($TOOL)" + echo "===============================================================" + + # Run the selected tool with the ralph prompt + if [[ "$TOOL" == "amp" ]]; then + OUTPUT=$(cat "$SCRIPT_DIR/prompt.md" | amp --dangerously-allow-all 2>&1 | tee /dev/stderr) || true + else + # Claude Code: use --dangerously-skip-permissions for autonomous operation, --print for output + OUTPUT=$(claude --dangerously-skip-permissions --print < "$SCRIPT_DIR/CLAUDE.md" 2>&1 | tee /dev/stderr) || true + fi + + # Check for completion signal + if echo "$OUTPUT" | grep -q "COMPLETE"; then + echo "" + echo "Ralph completed all tasks!" + echo "Completed at iteration $i of $MAX_ITERATIONS" + exit 0 + fi + + echo "Iteration $i complete. Continuing..." + sleep 2 +done + +echo "" +echo "Ralph reached max iterations ($MAX_ITERATIONS) without completing all tasks." +echo "Check $PROGRESS_FILE for status." +exit 1 From e0c4be83650ba888e83457d6bf6484ae36313a29 Mon Sep 17 00:00:00 2001 From: twodreams Date: Mon, 2 Mar 2026 02:38:15 -0800 Subject: [PATCH 6/8] fix: normalize line endings to LF to prevent phantom diffs in devcontainers The WSL2 bind mount was causing CRLF line endings in the working tree. The old .gitattributes only covered a few file types, leaving most files unnormalized. Now all text files are normalized to LF and common binary formats are explicitly marked. Co-Authored-By: Claude Opus 4.6 --- .devcontainer/devcontainer.json | 1 + .gitattributes | 24 ++++++++++++++++++------ 2 files changed, 19 insertions(+), 6 deletions(-) diff --git a/.devcontainer/devcontainer.json b/.devcontainer/devcontainer.json index 7f6a172d1c..828828ac0c 100644 --- a/.devcontainer/devcontainer.json +++ b/.devcontainer/devcontainer.json @@ -52,6 +52,7 @@ }, "workspaceMount": "source=${localWorkspaceFolder},target=/workspace,type=bind,consistency=delegated", "workspaceFolder": "/workspace", + "postCreateCommand": "git config core.autocrlf input", "postStartCommand": "sudo /usr/local/bin/init-firewall.sh", "waitFor": "postStartCommand" } diff --git a/.gitattributes b/.gitattributes index c7413510c2..a2d3c8876d 100644 --- a/.gitattributes +++ b/.gitattributes @@ -1,6 +1,18 @@ -# Normalize source code before commits -*.lua eol=lf -*.txt eol=lf -*.ot* eol=lf -*.cpp eol=lf -*.h eol=lf +# Normalize all text files to LF +* text=auto eol=lf + +# Explicitly mark binary files +*.png binary +*.jpg binary +*.jpeg binary +*.gif binary +*.ico binary +*.bmp binary +*.cam binary +*.dat binary +*.spr binary +*.dll binary +*.so binary +*.dylib binary +*.exe binary +*.pem binary From 6519d2178dbb1781390f64a7f6e15ab154d1d78c Mon Sep 17 00:00:00 2001 From: twodreams Date: Mon, 2 Mar 2026 02:39:46 -0800 Subject: [PATCH 7/8] feat: add PRD and Ralph converter skills for generating structured documentation --- .claude/settings.local.json | 65 --------- .claude/skills/prd/SKILL.md | 241 +++++++++++++++++++++++++++++++ .claude/skills/ralph/SKILL.md | 258 ++++++++++++++++++++++++++++++++++ 3 files changed, 499 insertions(+), 65 deletions(-) delete mode 100644 .claude/settings.local.json create mode 100644 .claude/skills/prd/SKILL.md create mode 100644 .claude/skills/ralph/SKILL.md diff --git a/.claude/settings.local.json b/.claude/settings.local.json deleted file mode 100644 index 766abc82ab..0000000000 --- a/.claude/settings.local.json +++ /dev/null @@ -1,65 +0,0 @@ -{ - "permissions": { - "allow": [ - "WebFetch(domain:github.com)", - "WebFetch(domain:www.nicbarker.com)", - "Bash(xargs wc -l)", - "Bash(find /c/Users/Pedro/Documents/otclient/src/protobuf -name \"*.proto\" -exec head -20 {} ;)", - "WebFetch(domain:raw.githubusercontent.com)", - "Bash(curl -sL \"https://raw.githubusercontent.com/nicbarker/clay/main/clay.h\" -o /c/Users/Pedro/Documents/otclient/src/framework/ui/clay/clay.h)", - "Bash(echo $VCPKG_ROOT)", - "Bash(cmake --preset windows-release -DTOGGLE_FRAMEWORK_CLAY=ON)", - "Bash(CMAKE=\"/c/Program Files/Microsoft Visual Studio/2022/Community/Common7/IDE/CommonExtensions/Microsoft/CMake/CMake/bin/cmake.exe\")", - "Bash(\"$CMAKE\" -S src -B build/clay-test -G Ninja -DCMAKE_TOOLCHAIN_FILE=\"$VCPKG_ROOT/scripts/buildsystems/vcpkg.cmake\" -DVCPKG_TARGET_TRIPLET=x64-windows-static -DBUILD_STATIC_LIBRARY=ON -DCMAKE_BUILD_TYPE=RelWithDebInfo -DTOGGLE_FRAMEWORK_CLAY=ON)", - "Bash(CMAKE_EXE=\"/c/Program Files/Microsoft Visual Studio/2022/Community/Common7/IDE/CommonExtensions/Microsoft/CMake/CMake/bin/cmake.exe\")", - "Bash(echo \"Testing: $CMAKE_EXE\")", - "Bash(\"$CMAKE_EXE\" --version)", - "Bash(git checkout -b feat/clay-ui-layout)", - "Bash(git add src/framework/ui/clay/clay.h src/framework/ui/uiclaylayout.h src/framework/ui/uiclaylayout.cpp src/CMakeLists.txt src/framework/ui/declarations.h src/framework/ui/uilayout.h src/framework/ui/ui.h src/framework/ui/uiwidgetbasestyle.cpp src/framework/luafunctions.cpp modules/client_claydemo/claydemo.otmod modules/client_claydemo/claydemo.otui modules/client_claydemo/claydemo.lua modules/client/client.otmod)", - "Bash(git commit:*)", - "Bash(ls -la /c/Users/Pedro/Documents/otclient/src/framework/ui/uilayout*)", - "Bash(find \"C:\\\\Users\\\\Pedro\\\\Documents\\\\otclient\\\\modules\" -name \"*.lua\" -type f -exec grep -l \"loadHtml\\\\|unloadHtml\" {} ;)", - "Bash(git add src/framework/ui/uiwidget.h src/framework/ui/uiwidgetbasestyle.cpp src/framework/ui/uiwidgethtml.cpp src/framework/ui/uiclaylayout.h src/framework/ui/uiclaylayout.cpp modules/game_htmlclaydemo/ modules/game_interface/interface.otmod)", - "Bash(git push -u origin feat/clay-ui-layout)", - "Bash(xargs grep -l \"applyDimension\")", - "Bash(xargs grep -l \"flex-direction\\\\|justify-content\\\\|align-items\")", - "Bash(xargs grep -l \"screen\\\\|window\")", - "Bash(wc -l /c/Users/Pedro/Documents/otclient/src/framework/ui/*.cpp /c/Users/Pedro/Documents/otclient/src/framework/graphics/*.cpp)", - "Bash(done)", - "WebFetch(domain:docs.rs)", - "Bash(git add docs/rust-migration-plan.md)", - "Bash(\"C:/Users/Pedro/Documents/otclient/rust/crates/otc_otml/Cargo.toml\":*)", - "Bash(\"C:/Users/Pedro/Documents/otclient/rust/crates/otc_log/Cargo.toml\":*)", - "Bash(\"C:/Users/Pedro/Documents/otclient/rust/crates/otc_color/Cargo.toml\":*)", - "Bash(\"C:/Users/Pedro/Documents/otclient/rust/crates/otc_time/Cargo.toml\":*)", - "Bash(\"C:/Users/Pedro/Documents/otclient/rust/crates/otc_input/Cargo.toml\":*)", - "Bash(\"C:/Users/Pedro/Documents/otclient/rust/crates/otc_window/Cargo.toml\":*)", - "Bash(\"C:/Users/Pedro/Documents/otclient/rust/crates/otc_winit/Cargo.toml\":*)", - "Bash(\"C:/Users/Pedro/Documents/otclient/rust/crates/otc_transform/Cargo.toml\":*)", - "Bash(\"C:/Users/Pedro/Documents/otclient/rust/crates/otc_hierarchy/Cargo.toml\":*)", - "Bash(\"C:/Users/Pedro/Documents/otclient/rust/crates/otc_asset/Cargo.toml\":*)", - "Bash(\"C:/Users/Pedro/Documents/otclient/rust/crates/otc_image/Cargo.toml\":*)", - "Bash(\"C:/Users/Pedro/Documents/otclient/rust/crates/otc_render/Cargo.toml\":*)", - "Bash(\"C:/Users/Pedro/Documents/otclient/rust/crates/otc_shader/Cargo.toml\":*)", - "Bash(\"C:/Users/Pedro/Documents/otclient/rust/crates/otc_sprite/Cargo.toml\":*)", - "Bash(\"C:/Users/Pedro/Documents/otclient/rust/crates/otc_text/Cargo.toml\":*)", - "Bash(\"C:/Users/Pedro/Documents/otclient/rust/crates/otc_diagnostic/Cargo.toml\":*)", - "Bash(\"C:/Users/Pedro/Documents/otclient/rust/crates/otc_platform/Cargo.toml\":*)", - "Bash(\"C:/Users/Pedro/Documents/otclient/rust/crates/otc_ui/Cargo.toml\":*)", - "Bash(\"C:/Users/Pedro/Documents/otclient/rust/crates/otc_ui_widgets/Cargo.toml\":*)", - "Bash(\"C:/Users/Pedro/Documents/otclient/rust/crates/otc_net/Cargo.toml\":*)", - "Bash(\"C:/Users/Pedro/Documents/otclient/rust/crates/otc_protocol/Cargo.toml\":*)", - "Bash(\"C:/Users/Pedro/Documents/otclient/rust/crates/otc_protobuf/Cargo.toml\":*)", - "Bash(\"C:/Users/Pedro/Documents/otclient/rust/crates/otc_lua/Cargo.toml\":*)", - "Bash(\"C:/Users/Pedro/Documents/otclient/rust/crates/otc_lua_derive/Cargo.toml\":*)", - "Bash(\"C:/Users/Pedro/Documents/otclient/rust/crates/otc_game/Cargo.toml\":*)", - "Bash(\"C:/Users/Pedro/Documents/otclient/rust/crates/otc_thing/Cargo.toml\":*)", - "Bash(\"C:/Users/Pedro/Documents/otclient/rust/crates/otc_map_render/Cargo.toml\":*)", - "Bash(\"C:/Users/Pedro/Documents/otclient/rust/crates/otc_audio/Cargo.toml\":*)", - "Bash(\"C:/Users/Pedro/Documents/otclient/rust/crates/otc_discord/Cargo.toml\":*)", - "Bash(\"C:/Users/Pedro/Documents/otclient/rust/otclient/Cargo.toml\":*)", - "Bash(for d in otc_otml otc_log otc_color otc_time otc_input otc_window otc_winit otc_transform otc_hierarchy otc_asset otc_image otc_render otc_shader otc_sprite otc_text otc_diagnostic otc_platform otc_ui otc_ui_widgets otc_net otc_protocol otc_protobuf otc_lua otc_lua_derive otc_game otc_thing otc_map_render otc_audio otc_discord)", - "Bash(do mkdir -p \"C:/Users/Pedro/Documents/otclient/rust/crates/$d/src\")" - ] - } -} diff --git a/.claude/skills/prd/SKILL.md b/.claude/skills/prd/SKILL.md new file mode 100644 index 0000000000..3c2f7acf88 --- /dev/null +++ b/.claude/skills/prd/SKILL.md @@ -0,0 +1,241 @@ +--- +name: prd +description: "Generate a Product Requirements Document (PRD) for a new feature. Use when planning a feature, starting a new project, or when asked to create a PRD. Triggers on: create a prd, write prd for, plan this feature, requirements for, spec out." +user-invocable: true +--- + +# PRD Generator + +Create detailed Product Requirements Documents that are clear, actionable, and suitable for implementation. + +--- + +## The Job + +1. Receive a feature description from the user +2. Ask 3-5 essential clarifying questions (with lettered options) +3. Generate a structured PRD based on answers +4. Save to `tasks/prd-[feature-name].md` + +**Important:** Do NOT start implementing. Just create the PRD. + +--- + +## Step 1: Clarifying Questions + +Ask only critical questions where the initial prompt is ambiguous. Focus on: + +- **Problem/Goal:** What problem does this solve? +- **Core Functionality:** What are the key actions? +- **Scope/Boundaries:** What should it NOT do? +- **Success Criteria:** How do we know it's done? + +### Format Questions Like This: + +``` +1. What is the primary goal of this feature? + A. Improve user onboarding experience + B. Increase user retention + C. Reduce support burden + D. Other: [please specify] + +2. Who is the target user? + A. New users only + B. Existing users only + C. All users + D. Admin users only + +3. What is the scope? + A. Minimal viable version + B. Full-featured implementation + C. Just the backend/API + D. Just the UI +``` + +This lets users respond with "1A, 2C, 3B" for quick iteration. Remember to indent the options. + +--- + +## Step 2: PRD Structure + +Generate the PRD with these sections: + +### 1. Introduction/Overview +Brief description of the feature and the problem it solves. + +### 2. Goals +Specific, measurable objectives (bullet list). + +### 3. User Stories +Each story needs: +- **Title:** Short descriptive name +- **Description:** "As a [user], I want [feature] so that [benefit]" +- **Acceptance Criteria:** Verifiable checklist of what "done" means + +Each story should be small enough to implement in one focused session. + +**Format:** +```markdown +### US-001: [Title] +**Description:** As a [user], I want [feature] so that [benefit]. + +**Acceptance Criteria:** +- [ ] Specific verifiable criterion +- [ ] Another criterion +- [ ] Typecheck/lint passes +- [ ] **[UI stories only]** Verify in browser using dev-browser skill +``` + +**Important:** +- Acceptance criteria must be verifiable, not vague. "Works correctly" is bad. "Button shows confirmation dialog before deleting" is good. +- **For any story with UI changes:** Always include "Verify in browser using dev-browser skill" as acceptance criteria. This ensures visual verification of frontend work. + +### 4. Functional Requirements +Numbered list of specific functionalities: +- "FR-1: The system must allow users to..." +- "FR-2: When a user clicks X, the system must..." + +Be explicit and unambiguous. + +### 5. Non-Goals (Out of Scope) +What this feature will NOT include. Critical for managing scope. + +### 6. Design Considerations (Optional) +- UI/UX requirements +- Link to mockups if available +- Relevant existing components to reuse + +### 7. Technical Considerations (Optional) +- Known constraints or dependencies +- Integration points with existing systems +- Performance requirements + +### 8. Success Metrics +How will success be measured? +- "Reduce time to complete X by 50%" +- "Increase conversion rate by 10%" + +### 9. Open Questions +Remaining questions or areas needing clarification. + +--- + +## Writing for Junior Developers + +The PRD reader may be a junior developer or AI agent. Therefore: + +- Be explicit and unambiguous +- Avoid jargon or explain it +- Provide enough detail to understand purpose and core logic +- Number requirements for easy reference +- Use concrete examples where helpful + +--- + +## Output + +- **Format:** Markdown (`.md`) +- **Location:** `tasks/` +- **Filename:** `prd-[feature-name].md` (kebab-case) + +--- + +## Example PRD + +```markdown +# PRD: Task Priority System + +## Introduction + +Add priority levels to tasks so users can focus on what matters most. Tasks can be marked as high, medium, or low priority, with visual indicators and filtering to help users manage their workload effectively. + +## Goals + +- Allow assigning priority (high/medium/low) to any task +- Provide clear visual differentiation between priority levels +- Enable filtering and sorting by priority +- Default new tasks to medium priority + +## User Stories + +### US-001: Add priority field to database +**Description:** As a developer, I need to store task priority so it persists across sessions. + +**Acceptance Criteria:** +- [ ] Add priority column to tasks table: 'high' | 'medium' | 'low' (default 'medium') +- [ ] Generate and run migration successfully +- [ ] Typecheck passes + +### US-002: Display priority indicator on task cards +**Description:** As a user, I want to see task priority at a glance so I know what needs attention first. + +**Acceptance Criteria:** +- [ ] Each task card shows colored priority badge (red=high, yellow=medium, gray=low) +- [ ] Priority visible without hovering or clicking +- [ ] Typecheck passes +- [ ] Verify in browser using dev-browser skill + +### US-003: Add priority selector to task edit +**Description:** As a user, I want to change a task's priority when editing it. + +**Acceptance Criteria:** +- [ ] Priority dropdown in task edit modal +- [ ] Shows current priority as selected +- [ ] Saves immediately on selection change +- [ ] Typecheck passes +- [ ] Verify in browser using dev-browser skill + +### US-004: Filter tasks by priority +**Description:** As a user, I want to filter the task list to see only high-priority items when I'm focused. + +**Acceptance Criteria:** +- [ ] Filter dropdown with options: All | High | Medium | Low +- [ ] Filter persists in URL params +- [ ] Empty state message when no tasks match filter +- [ ] Typecheck passes +- [ ] Verify in browser using dev-browser skill + +## Functional Requirements + +- FR-1: Add `priority` field to tasks table ('high' | 'medium' | 'low', default 'medium') +- FR-2: Display colored priority badge on each task card +- FR-3: Include priority selector in task edit modal +- FR-4: Add priority filter dropdown to task list header +- FR-5: Sort by priority within each status column (high to medium to low) + +## Non-Goals + +- No priority-based notifications or reminders +- No automatic priority assignment based on due date +- No priority inheritance for subtasks + +## Technical Considerations + +- Reuse existing badge component with color variants +- Filter state managed via URL search params +- Priority stored in database, not computed + +## Success Metrics + +- Users can change priority in under 2 clicks +- High-priority tasks immediately visible at top of lists +- No regression in task list performance + +## Open Questions + +- Should priority affect task ordering within a column? +- Should we add keyboard shortcuts for priority changes? +``` + +--- + +## Checklist + +Before saving the PRD: + +- [ ] Asked clarifying questions with lettered options +- [ ] Incorporated user's answers +- [ ] User stories are small and specific +- [ ] Functional requirements are numbered and unambiguous +- [ ] Non-goals section defines clear boundaries +- [ ] Saved to `tasks/prd-[feature-name].md` diff --git a/.claude/skills/ralph/SKILL.md b/.claude/skills/ralph/SKILL.md new file mode 100644 index 0000000000..e402ab8d36 --- /dev/null +++ b/.claude/skills/ralph/SKILL.md @@ -0,0 +1,258 @@ +--- +name: ralph +description: "Convert PRDs to prd.json format for the Ralph autonomous agent system. Use when you have an existing PRD and need to convert it to Ralph's JSON format. Triggers on: convert this prd, turn this into ralph format, create prd.json from this, ralph json." +user-invocable: true +--- + +# Ralph PRD Converter + +Converts existing PRDs to the prd.json format that Ralph uses for autonomous execution. + +--- + +## The Job + +Take a PRD (markdown file or text) and convert it to `prd.json` in your ralph directory. + +--- + +## Output Format + +```json +{ + "project": "[Project Name]", + "branchName": "ralph/[feature-name-kebab-case]", + "description": "[Feature description from PRD title/intro]", + "userStories": [ + { + "id": "US-001", + "title": "[Story title]", + "description": "As a [user], I want [feature] so that [benefit]", + "acceptanceCriteria": [ + "Criterion 1", + "Criterion 2", + "Typecheck passes" + ], + "priority": 1, + "passes": false, + "notes": "" + } + ] +} +``` + +--- + +## Story Size: The Number One Rule + +**Each story must be completable in ONE Ralph iteration (one context window).** + +Ralph spawns a fresh Amp instance per iteration with no memory of previous work. If a story is too big, the LLM runs out of context before finishing and produces broken code. + +### Right-sized stories: +- Add a database column and migration +- Add a UI component to an existing page +- Update a server action with new logic +- Add a filter dropdown to a list + +### Too big (split these): +- "Build the entire dashboard" - Split into: schema, queries, UI components, filters +- "Add authentication" - Split into: schema, middleware, login UI, session handling +- "Refactor the API" - Split into one story per endpoint or pattern + +**Rule of thumb:** If you cannot describe the change in 2-3 sentences, it is too big. + +--- + +## Story Ordering: Dependencies First + +Stories execute in priority order. Earlier stories must not depend on later ones. + +**Correct order:** +1. Schema/database changes (migrations) +2. Server actions / backend logic +3. UI components that use the backend +4. Dashboard/summary views that aggregate data + +**Wrong order:** +1. UI component (depends on schema that does not exist yet) +2. Schema change + +--- + +## Acceptance Criteria: Must Be Verifiable + +Each criterion must be something Ralph can CHECK, not something vague. + +### Good criteria (verifiable): +- "Add `status` column to tasks table with default 'pending'" +- "Filter dropdown has options: All, Active, Completed" +- "Clicking delete shows confirmation dialog" +- "Typecheck passes" +- "Tests pass" + +### Bad criteria (vague): +- "Works correctly" +- "User can do X easily" +- "Good UX" +- "Handles edge cases" + +### Always include as final criterion: +``` +"Typecheck passes" +``` + +For stories with testable logic, also include: +``` +"Tests pass" +``` + +### For stories that change UI, also include: +``` +"Verify in browser using dev-browser skill" +``` + +Frontend stories are NOT complete until visually verified. Ralph will use the dev-browser skill to navigate to the page, interact with the UI, and confirm changes work. + +--- + +## Conversion Rules + +1. **Each user story becomes one JSON entry** +2. **IDs**: Sequential (US-001, US-002, etc.) +3. **Priority**: Based on dependency order, then document order +4. **All stories**: `passes: false` and empty `notes` +5. **branchName**: Derive from feature name, kebab-case, prefixed with `ralph/` +6. **Always add**: "Typecheck passes" to every story's acceptance criteria + +--- + +## Splitting Large PRDs + +If a PRD has big features, split them: + +**Original:** +> "Add user notification system" + +**Split into:** +1. US-001: Add notifications table to database +2. US-002: Create notification service for sending notifications +3. US-003: Add notification bell icon to header +4. US-004: Create notification dropdown panel +5. US-005: Add mark-as-read functionality +6. US-006: Add notification preferences page + +Each is one focused change that can be completed and verified independently. + +--- + +## Example + +**Input PRD:** +```markdown +# Task Status Feature + +Add ability to mark tasks with different statuses. + +## Requirements +- Toggle between pending/in-progress/done on task list +- Filter list by status +- Show status badge on each task +- Persist status in database +``` + +**Output prd.json:** +```json +{ + "project": "TaskApp", + "branchName": "ralph/task-status", + "description": "Task Status Feature - Track task progress with status indicators", + "userStories": [ + { + "id": "US-001", + "title": "Add status field to tasks table", + "description": "As a developer, I need to store task status in the database.", + "acceptanceCriteria": [ + "Add status column: 'pending' | 'in_progress' | 'done' (default 'pending')", + "Generate and run migration successfully", + "Typecheck passes" + ], + "priority": 1, + "passes": false, + "notes": "" + }, + { + "id": "US-002", + "title": "Display status badge on task cards", + "description": "As a user, I want to see task status at a glance.", + "acceptanceCriteria": [ + "Each task card shows colored status badge", + "Badge colors: gray=pending, blue=in_progress, green=done", + "Typecheck passes", + "Verify in browser using dev-browser skill" + ], + "priority": 2, + "passes": false, + "notes": "" + }, + { + "id": "US-003", + "title": "Add status toggle to task list rows", + "description": "As a user, I want to change task status directly from the list.", + "acceptanceCriteria": [ + "Each row has status dropdown or toggle", + "Changing status saves immediately", + "UI updates without page refresh", + "Typecheck passes", + "Verify in browser using dev-browser skill" + ], + "priority": 3, + "passes": false, + "notes": "" + }, + { + "id": "US-004", + "title": "Filter tasks by status", + "description": "As a user, I want to filter the list to see only certain statuses.", + "acceptanceCriteria": [ + "Filter dropdown: All | Pending | In Progress | Done", + "Filter persists in URL params", + "Typecheck passes", + "Verify in browser using dev-browser skill" + ], + "priority": 4, + "passes": false, + "notes": "" + } + ] +} +``` + +--- + +## Archiving Previous Runs + +**Before writing a new prd.json, check if there is an existing one from a different feature:** + +1. Read the current `prd.json` if it exists +2. Check if `branchName` differs from the new feature's branch name +3. If different AND `progress.txt` has content beyond the header: + - Create archive folder: `archive/YYYY-MM-DD-feature-name/` + - Copy current `prd.json` and `progress.txt` to archive + - Reset `progress.txt` with fresh header + +**The ralph.sh script handles this automatically** when you run it, but if you are manually updating prd.json between runs, archive first. + +--- + +## Checklist Before Saving + +Before writing prd.json, verify: + +- [ ] **Previous run archived** (if prd.json exists with different branchName, archive it first) +- [ ] Each story is completable in one iteration (small enough) +- [ ] Stories are ordered by dependency (schema to backend to UI) +- [ ] Every story has "Typecheck passes" as criterion +- [ ] UI stories have "Verify in browser using dev-browser skill" as criterion +- [ ] Acceptance criteria are verifiable (not vague) +- [ ] No story depends on a later story From 6a1751fd0f1ca83fd5236430430a841832dc33a9 Mon Sep 17 00:00:00 2001 From: twodreams Date: Mon, 2 Mar 2026 02:42:19 -0800 Subject: [PATCH 8/8] fix: remove incorrect binary marker for .pem files in .gitattributes PEM files are text and should be normalized like other text files. The binary marker was preventing proper CRLF normalization. Co-Authored-By: Claude Opus 4.6 --- .gitattributes | 1 - 1 file changed, 1 deletion(-) diff --git a/.gitattributes b/.gitattributes index a2d3c8876d..6bf2bc7ba6 100644 --- a/.gitattributes +++ b/.gitattributes @@ -15,4 +15,3 @@ *.so binary *.dylib binary *.exe binary -*.pem binary