Upload folder using huggingface_hub
Browse filesFiles changed (40)
- .gitattributes+2
- LICENSEAdded+21
- README.mdAdded+226
- build/MonkeyStudio.apkAdded+3
- build/MonkeyStudio.apk.idsigAdded+3
- docs/ARCHITECTURE.mdAdded+142
- docs/BUILD_ANDROID.mdAdded+279
- export_presets.cfgAdded+66
- project.godotAdded+61
- scenes/main.tscnAdded+6
- scripts/core/feature_registry.gdAdded+135
- scripts/core/feature_registry.gd.uidAdded+1
- scripts/core/memory_manager.gdAdded+182
- scripts/core/memory_manager.gd.uidAdded+1
- scripts/core/mesh_pool.gdAdded+65
- scripts/core/mesh_pool.gd.uidAdded+1
- scripts/core/studio_bus.gdAdded+54
- scripts/core/studio_bus.gd.uidAdded+1
- scripts/core/vertex_buffer_manager.gdAdded+114
- scripts/core/vertex_buffer_manager.gd.uidAdded+1
- scripts/install_godot.shAdded+51
- scripts/modules/mesh_gen.gdAdded+282
- scripts/modules/mesh_gen.gd.uidAdded+1
- scripts/modules/rigging.gdAdded+174
- scripts/modules/rigging.gd.uidAdded+1
- scripts/modules/sculpt.gdAdded+238
- scripts/modules/sculpt.gd.uidAdded+1
- scripts/modules/simulation.gdAdded+304
- scripts/modules/simulation.gd.uidAdded+1
- scripts/modules/timeline.gdAdded+174
- scripts/modules/timeline.gd.uidAdded+1
- scripts/studio/studio_main.gdAdded+140
- scripts/studio/studio_main.gd.uidAdded+1
- scripts/studio/studio_ui.gdAdded+418
- scripts/studio/studio_ui.gd.uidAdded+1
- scripts/studio/touch_camera.gdAdded+183
- scripts/studio/touch_camera.gd.uidAdded+1
- tests/self_test.gdAdded+157
- tests/self_test.gd.uidAdded+1
- tests/self_test.tscnAdded+6
32 unmodified lines333435363732 unmodified lines*.zip filter=lfs diff=lfs merge=lfs -text*.zst filter=lfs diff=lfs merge=lfs -text*tfevents* filter=lfs diff=lfs merge=lfs -textbuild/MonkeyStudio.apk filter=lfs diff=lfs merge=lfs -textbuild/MonkeyStudio.apk.idsig filter=lfs diff=lfs merge=lfs -text123456789101112131415161718192021MIT License
Copyright (c) 2026 MonkeyStudio contributors
Permission is hereby granted, free of charge, to any person obtaining a copyof this software and associated documentation files (the "Software"), to dealin the Software without restriction, including without limitation the rightsto use, copy, modify, merge, publish, distribute, sublicense, and/or sellcopies of the Software, and to permit persons to whom the Software isfurnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in allcopies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS ORIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THEAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHERLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THESOFTWARE.123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226---language: - en - hitags: - godot - gdscript - 3d - mobile - android - modeling - sculpting - rigging - cloth-simulation - game-enginelicense: mitlibrary_name: godotpipeline_tag: other---
# MonkeyStudio
**An open-source 3D creation studio for low-RAM (4 GB) Android phones**, builtwith **Godot 4.x + GDScript**. Think of it as a foundation for a Blender-stylemobile tool: procedural modeling, sculpting, skeletal rigging, cloth/hairsimulation and keyframe animation — all designed around a memory architecturethat is meant to avoid Out-Of-Memory crashes on weak devices.
This repository contains the **full source code** and a **ready-to-installdebug APK**.
---
## Download the APK
The built app is included at:
```build/MonkeyStudio.apk```
| Property | Value ||---|---|| Package | `com.monkeycode.monkeystudio` || Version | `0.1.0` (versionCode 1) || Size | ~55 MB || Architectures | `arm64-v8a`, `armeabi-v7a` (32-bit + 64-bit ARM) || minSdk | 24 (Android 7.0) || targetSdk | 36 || Signing | Android Debug key (side-load only) |
Install on a phone:
```bashadb install -r build/MonkeyStudio.apk```
or copy the `.apk` to the phone and install it manually (enable"Install from unknown sources"). This is a **debug-signed** build meant fortesting and side-loading, not for the Play Store.
---
## Honest scope note
Please read this before expecting a finished product.
- **No software is "100% bug-free."** Neither is this. Blender itself has had 200+ contributors and thousands of bug fixes over 25+ years. Anyone who promises "guaranteed zero bugs" is not being truthful.- **This is a working, tested foundation — not a feature-complete Blender clone.** A full mobile Blender is a multi-year, multi-developer effort. Each module here is real, runs, and is covered by an automated headless test suite (25 checks, all passing).- The architecture is deliberately built so new tools can be added as `FeatureRegistry` entries without touching the memory core.
---
## What is implemented and tested
| Area | Status | Where ||---|---|---|| Memory budget, lazy load, LRU eviction | Done + tested | `scripts/core/memory_manager.gd` || Feature catalog / on-demand load & unload | Done + tested | `scripts/core/feature_registry.gd` || GPU mesh pooling (no GC spikes) | Done + tested | `scripts/core/mesh_pool.gd` || VRAM cost estimate + batched upload | Done + tested | `scripts/core/vertex_buffer_manager.gd` || Procedural meshes: cube, sphere, cylinder, plane, torus, icosphere, monkey head | Done + tested | `scripts/modules/mesh_gen.gd` || Sculpt brushes: draw, grab, pinch, smooth, flatten | Done + tested | `scripts/modules/sculpt.gd` || Skeleton3D builder + auto 4-influence weighting | Done + tested | `scripts/modules/rigging.gd` || Verlet mass-spring cloth + hair (gravity, wind) | Done + tested | `scripts/modules/simulation.gd` || Keyframe timeline (engine-native Animation) | Done + tested | `scripts/modules/timeline.gd` || Touch camera (orbit / pinch-zoom / pan) | Done | `scripts/studio/touch_camera.gd` || Dark material UI + collapsible panels + HUD | Done | `scripts/studio/studio_ui.gd` || App bootstrap / adaptive quality | Done | `scripts/studio/studio_main.gd` |
### Roadmap (not yet built)
UV unwrap, boolean operations, baking, OBJ/glTF/USD import-export, an undostack, dynamic geometry LOD, a wider brush set, and per-device performanceprofiles.
---
## Memory architecture (the core idea)
A 4 GB phone gives an app roughly 1.2–1.5 GB before the OS starts killing it.Blender-style tools are memory-hungry. The only way to offer many featureswithout OOM is to **never have them all resident at once**.
1. **`MemoryManager`** — owns a hard RAM budget (default 512 MB, auto-capped to 1/8 of physical RAM). Assets are registered as `id -> path + cost`, *not* loaded. `acquire(id)` loads on first use; `release(id)` drops a reference. At zero references an asset becomes an eviction candidate. It evicts least-recently-used, zero-reference assets first — never one that is in use. It also polls `OS.get_memory_info()` and force-evicts when the OS reports < 128 MB free.2. **`FeatureRegistry`** — a catalog of every tool as metadata only. `activate()` instantiates a module on demand; `deactivate()` destroys it and frees the RAM. "Close the tool, free the memory" is automatic.3. **`MeshPool`** — recycles `ArrayMesh` objects; released meshes have their surfaces cleared (GPU buffers freed) but the object is reused, avoiding allocation churn.4. **`VertexBufferManager`** — predicts RAM+VRAM cost before a mesh is built, and performs a *single* GPU upload per edit (mobile GPUs hate thousands of tiny buffer updates).5. **Adaptive quality** — when FPS stays below 30, shadows are disabled first, then the simulation substep budget drops, keeping the frame budget bounded.
Full write-up: `docs/ARCHITECTURE.md`.
---
## About AI in this project
**Important and honest:** the current codebase contains **no AI / machinelearning / LLM component.** There is no model weights file, no neural network,and nothing calls an AI API. It is a pure Godot engine application written inGDScript.
The phrase "built with an AI coding assistant" refers to **how the code waswritten** (an AI assistant helped author it), *not* to the app having AIfeatures at runtime.
If you want to add real AI capabilities, here are realistic options and howthey would fit this architecture:
| Idea | What it needs | Where it plugs in ||---|---|---|| Text-to-3D mesh generation | An ONNX/TFLite generative model (e.g. a small diffusion or point-cloud model) run on-device, or a cloud API | New `mesh_gen` backend that outputs the same `{verts, indices, uvs}` dictionary || Auto-retopology / auto-UV | A learned or classical algorithm | New feature module under `scripts/modules/` || AI texture generation | On-device Stable-Diffusion-lite or cloud API | Material assignment in `mesh_gen.gd` || Auto-rigging (skeleton from mesh) | A rig-prediction model | `rigging.gd` currently uses inverse-distance weights; a model could replace that heuristic || Prompt-based animation | Motion model / LLM driving keyframes | Feed results into `timeline.gd` `add_keyframe()` |
**Security note for any future AI integration:** never hardcode API keys. Readthem from the user's own project environment variables (for example`os.get_environment("USER_LLM_API_KEY")` on desktop, or a settings screen onAndroid) and ship a placeholder config. Keys must come from the user, not fromthe build environment.
---
## Repository layout
```textproject.godot Engine config (mobile renderer, landscape, 720p)export_presets.cfg Android APK export presetscenes/main.tscn App entry scenescripts/ core/ MemoryManager, FeatureRegistry, MeshPool, VertexBufferManager, StudioBus (autoloads) modules/ mesh_gen, sculpt, rigging, simulation, timeline studio/ studio_main (bootstrap), studio_ui, touch_camera install_godot.sh Linux installer (editor + export templates)tests/self_test.tscn Headless subsystem verification (25 checks)docs/ ARCHITECTURE.md How the memory model and modules work BUILD_ANDROID.md Full Godot + Android SDK + APK build guidebuild/MonkeyStudio.apk Ready-to-install debug APK```
---
## Build it yourself
```bash# 1. Install Godot + export templates (Debian/Ubuntu)chmod +x scripts/install_godot.sh./scripts/install_godot.sh
# 2. Reimport resourcesgodot --headless --import
# 3. Run the automated tests (exit 0 = all pass)godot --headless res://tests/self_test.tscn
# 4. Open in the editorgodot --editor project.godot
# 5. Build an APK (needs Android SDK + JDK 17, see docs/BUILD_ANDROID.md)mkdir -p buildgodot --headless --export-debug "Android" build/MonkeyStudio.apk```
Verified environment: **Godot 4.7.2-stable**, Debian 12, OpenJDK 17, AndroidSDK build-tools 34.0.0.
---
## Testing
`tests/self_test.tscn` runs headless and exercises every subsystem: meshgeneration, all five sculpt brushes (vertices actually move), the skinningchannels, cloth falling under gravity, hair creation, and timeline keyframing.
```bashgodot --headless res://tests/self_test.tscn# -> SELFTEST: ALL PASS (25 PASS, 0 FAIL, exit 0)```
---
## License
MIT. See `LICENSE`.123version https://git-lfs.github.com/spec/v1oid sha256:2141a664ec491b5974866cffb2dc88730dfed945c8b2b348c9bebf5fc134d29fsize 57617110123version https://git-lfs.github.com/spec/v1oid sha256:72dd43fccbfea0b88aa981a214076f335c5377023f81c7f53cb545fdb8ba71f0size 456115123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142# MonkeyStudio Architecture
## 1. The core problem: 100+ features on 4 GB of RAM
A phone with 4 GB total RAM gives an app roughly **1.2-1.5 GB** before the OSstarts killing it. Blender-style tools (sculpt grids, cloth solvers, hairparticles, rigging) are memory-hungry. The only way to offer many featureswithout OOM is to **never have them all resident at once**.
MonkeyStudio's answer is a lazy-load + reference-count + LRU-evict memorylayer, plus a fixed pool for GPU objects. Below is how each piece works.
## 2. Memory layer (`scripts/core/`)
### 2.1 `MemoryManager` (autoload)
- Owns a hard **budget** (`asset_budget_mb`, default 512 MB, auto-capped to 1/8 of physical RAM).- Assets are registered by **id -> path + estimated cost**, *not* loaded.- `acquire(id)` loads on first use and increments a reference count.- `release(id)` drops a reference. At zero references the asset becomes an **eviction candidate**.- `_ensure_room(need)` evicts **least-recently-used, zero-reference** assets until the new asset fits. Assets with live references are never evicted, so eviction can never yank something out from under a running feature.- Every second it polls `OS.get_memory_info()`; when the OS says < 128 MB is available it force-evicts to buy headroom.
### 2.2 `FeatureRegistry` (autoload)
- A **catalog** of every tool. Each entry is just metadata (`name`, `module_path`, `cost_mb`).- `activate(id)` asks MemoryManager for the module script, instantiates it, and adds it to the `Features` host node.- `deactivate(id)` destroys the module node and releases its memory. This is what makes "close the tool, free the RAM" automatic.
### 2.3 `MeshPool` (autoload)
- Recycles `ArrayMesh` objects. A released mesh has its surfaces cleared (freeing GPU buffers) but the object is kept for reuse, avoiding per-frame allocation spikes and fragmentation.- Bounded by `max_pooled` so the pool itself can't leak.
### 2.4 `VertexBufferManager` (autoload)
- `estimate_cost_mb(vertex_count)` predicts RAM+VRAM before a mesh is built so MemoryManager can evict first.- `build_surface()` / `commit()` do a **single** `add_surface_from_arrays()` upload. Mobile GPUs hate thousands of tiny buffer updates; sculpting strokes accumulate on the CPU and flush once.- `recompute_normals()` restores correct lighting after edits.
### 2.5 Adaptive quality
`StudioBus` emits `fps_throttled` when FPS stays below 30. `StudioMain` reactsby disabling shadows, then the simulation substep budget drops (see below).This keeps the frame budget bounded on weak GPUs.
## 3. Feature modules (`scripts/modules/`)
Modules implement `_activate(host)` / `_deactivate()` and receive the scenethrough the `StudioBus` signal hub (low coupling, safe lazy unload).
| Module | Features | Notes ||---|---|---|| `mesh_gen.gd` | 1-20 | Procedural cube/sphere/cylinder/plane/torus/ico + a code-generated monkey head || `sculpt.gd` | 21-40 | draw / grab / pinch / smooth / flatten, batched GPU flush || `rigging.gd` | 41-60 | Skeleton3D builder + inverse-distance auto-weighting + `Skin` bind || `simulation.gd` | 61-80 | Verlet mass-spring cloth & hair with wind + pinned constraints || `timeline.gd` | 81-100 | Engine-native `Animation` + `AnimationPlayer` keyframing |
### 3.1 Mesh generation
Pure functions returning `{verts, indices, uvs}`. No GPU allocation until`spawn()` commits. Costs are predictable, so a 5000-vertex sphere is refusedbefore it is built if it would blow the budget.
### 3.2 Sculpting
A stroke is `begin -> apply* -> end`. All `apply` calls mutate CPU`PackedVector3Array`s; `end` performs one upload. Brushes use a smoothstepfalloff. `raycast_screen()` prefers a physics ray against the mesh collider andfalls back to a bounding-sphere test when the mesh has no collider yet.
### 3.3 Rigging
`generate_default_armature()` builds a spine + limbs from the mesh bounds.`bind_weights()` ranks bones by distance, keeps the nearest 4, normalizes, andwrites `ARRAY_BONES` + `ARRAY_WEIGHTS` (the standard 4-influence mobileskinning path) plus a `Skin` resource. Result is a normal engine skinned mesh.
### 3.4 Cloth & hair
Fixed-timestep (`1/30 s`) Verlet integration with Jacobi constraint relaxation.Sub-steps are capped at 4 and backlog is dropped, so a slow frame can neverspiral into a death march. Particles and springs live in `PackedArray`s (noper-frame allocation). Cloth uploads a triangle grid; hair uploads ribbons.
### 3.5 Timeline
Wraps a real `Animation` resource and `AnimationPlayer`, so interpolation,looping and playback are engine-native and cached. The module exposes`play/pause/scrub/add_keyframe/add_bone_keyframe` for a touch UI.
## 4. UI (`scripts/studio/studio_ui.gd`)
Material-ish dark theme built in code (resolution-independent, scaled by`UI_SCALE`). Layout: top bar (FPS + memory HUD), left tool rail, rightcollapsible panels (Tools / Layers / Timeline), bottom playback + scrubber.Touch targets are >= 48 px.
## 5. Camera (`scripts/studio/touch_camera.gd`)
- 1 finger: orbit (or paint when a sculpt brush is active)- 2 fingers: pinch = dolly zoom, drag = pan- 3 fingers: pan- All targets are exponentially smoothed so jittery touch sampling still feels fluid. No allocation in the input hot path.
## 6. Testing
`tests/self_test.tscn` runs headless and verifies every subsystem:
```bashgodot --headless res://tests/self_test.tscn```
It checks mesh generation, all sculpt brushes (vertices actually move), theskinning channels, cloth falling under gravity, hair creation, and timelinekeyframing. Exit code 0 = pass.
## 7. What is production-ready vs. roadmap
Honest status:
- Memory layer, mesh generation, sculpting, rigging, simulation, timeline and UI shell are **implemented and tested** as described above.- Production polish still to do: adaptivity grid (`DynamicLOD`), UV unwrap, boolean ops, baking, USD/OBJ/glTF import-export, undo stack, a broader brush set, and device-specific tuning. The architecture is designed so these plug in as new `FeatureRegistry` entries without touching the core.123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279# MonkeyStudio - Full Build & Android Export Guide (A to Z)
This document is the complete, step-by-step guide for **STEP 1 (setup)** and**STEP 5 (build a real .apk)** of the MonkeyStudio project.
Everything described here was executed and verified on Debian 12 with**Godot 4.7.2-stable**. Commands are copy-paste ready.
---
## STEP 1 - Godot install + Android project setup
### 1.1 Install the Godot editor (Linux / macOS / Windows)
**Linux (Debian/Ubuntu) - scripted:**
```bash# Give the script execute permissionchmod +x scripts/install_godot.sh
# Run the installer (downloads editor + export templates + runtime libs)./scripts/install_godot.sh```
**Linux - manual (what the script does):**
```bash# 1. Download the editor binary for the latest stable releasecurl -fL -o godot.zip \ https://github.com/godotengine/godot/releases/download/4.7.2-stable/Godot_v4.7.2-stable_linux.x86_64.zip
# 2. Unzip itunzip godot.zip
# 3. Make it executable and put it on your PATHchmod +x Godot_v4.7.2-stable_linux.x86_64sudo mv Godot_v4.7.2-stable_linux.x86_64 /usr/local/bin/godot
# 4. Verifygodot --version# -> 4.7.2.stable.official.XXXXXXXXX```
**Windows / macOS:** download the matching `.zip` / `.dmg` / `.app` from`https://godotengine.org/download` and place the binary on your PATH. All othersteps below are identical from the editor UI.
### 1.2 Install export templates
Export templates are the pre-compiled engine the game runs on.
```bash# Editor method (recommended, one click)# Editor menu > Manage Export Templates > Download and Install
# Headless / CLI methodTEMPLATE_DIR="$HOME/.local/share/godot/export_templates/4.7.2.stable"mkdir -p "$TEMPLATE_DIR"curl -fL -o templates.tpz \ https://github.com/godotengine/godot/releases/download/4.7.2-stable/Godot_v4.7.2-stable_export_templates.tpzunzip -o templates.tpz -d /tmp/godot_tplcp /tmp/godot_tpl/templates/* "$TEMPLATE_DIR/"```
### 1.3 Install the Android build toolchain
You need three things: **OpenJDK 17**, the **Android SDK command-line tools**,and the **Android NDK** is only required if you use a custom Gradle build(MonkeyStudio's default APK build does **not** need the NDK).
```bash# OpenJDK 17sudo apt-get updatesudo apt-get install -y openjdk-17-jdk unzip curl
# Verifyjava -version# -> openjdk version "17.x"```
```bash# Android command-line toolsmkdir -p "$HOME/android-sdk/cmdline-tools"cd "$HOME/android-sdk/cmdline-tools"curl -fL -o cmdline.zip \ https://dl.google.com/android/repository/commandlinetools-linux-11076708_latest.zipunzip -o cmdline.zipmv cmdline-tools latest # the SDK expects <sdk>/cmdline-tools/latest
# Set environment variables (add these to ~/.bashrc)export ANDROID_HOME="$HOME/android-sdk"export PATH="$PATH:$ANDROID_HOME/cmdline-tools/latest/bin:$ANDROID_HOME/platform-tools"
# Accept licenses and install the required packagesyes | sdkmanager --licensessdkmanager "platform-tools" "build-tools;34.0.0" "platforms;android-34"```
```bash# Create the debug keystore Godot uses for testing buildskeytool -keyalg RSA -genkeypair -alias androiddebugkey \ -keypass android -keystore debug.keystore -storepass android \ -dname "CN=Android Debug,O=Android,C=US" -validity 9999 -deststoretype pkcs12```
### 1.4 Point Godot at the toolchain
```textEditor > Editor Settings > Export > Android Android SDK Path -> $HOME/android-sdk Debug Keystore -> $HOME/debug.keystore Debug Keystore User -> androiddebugkey Debug Keystore Pass -> android Java SDK Path -> /usr/lib/jvm/java-17-openjdk-amd64```
Alternatively, from a terminal, write the same paths into`~/.config/godot/editor_settings-4.tres` (advanced). The UI is safer.
### 1.5 Project display / renderer settings (mobile)
These are already set in `project.godot` so you do not have to click through theUI, but here is exactly what they do:
| Setting | Value | Why ||---|---|---|| `display/window/size/viewport_width` | 1280 | landscape base || `display/window/size/viewport_height` | 720 | 720p target || `display/window/stretch/mode` | `canvas_items` | UI scales, 3D stays crisp || `display/window/handheld/orientation` | 1 | landscape || `rendering/renderer/rendering_method` | `mobile` | Mobile Vulkan/GLES path || `rendering/textures/vram_compression/import_etc2_astc` | true | required for mobile || `rendering/anti_aliasing/quality/msaa_3d` | 0 | no MSAA (saves GPU/mem) |
`mobile` renderer = Vulkan on modern phones, automatically falls back to the`gl_compatibility` (OpenGL ES 3.0) path on older 4GB devices.
---
## STEP 5 - Build a real .apk
### 5.1 One-time: generate an export preset
Open the project in the editor, then:
```textProject > Export... > Add... > Android```
A minimal preset is committed at `export_presets.cfg`. Key fields:
```iniexport_path="build/MonkeyStudio.apk"architectures/armeabi-v7a=true # 32-bit ARM (old 4GB phones)architectures/arm64-v8a=true # 64-bit ARM (required by Play Store)architectures/x86=falsearchitectures/x86_64=falsepackage/unique_name="com.monkeycode.monkeystudio"version/code=1version/name="0.1.0"```
### 5.2 Build from the command line (headless, CI-friendly)
```bash# Make sure the output directory existsmkdir -p build
# Export a signed debug APKgodot --headless --export-debug "Android" build/MonkeyStudio.apk
# Export a release APK (needs keystore/release set in the preset + editor settings)godot --headless --export-release "Android" build/MonkeyStudio.apk
# Verify it is a real APKunzip -l build/MonkeyStudio.apk | head```
### 5.3 Build from the editor UI
```textProject > Export... > Android > Export Project```
### 5.4 Install / test on a device
```bash# Enable USB debugging on the phone, then:adb devicesadb install -r build/MonkeyStudio.apk
# Stream logs while the app runsadb logcat | grep -i godot```
---
## Keystore & Gradle troubleshooting
### Error: "Invalid keystore ... or wrong password"
Regenerate the debug keystore and re-check the pass:
```bashkeytool -keyalg RSA -genkeypair -alias androiddebugkey \ -keypass android -keystore debug.keystore -storepass android \ -dname "CN=Android Debug,O=Android,C=US" -validity 9999 -deststoretype pkcs12
# Inspect what is inside an existing keystorekeytool -list -v -keystore debug.keystore -storepass android```
Make sure the password in *Editor Settings > Export > Android* matches the`-keypass` / `-storepass` you used (they must be the same for the debug store).
### Error: "Could not find SDK / Build Tools 34.0.0"
```bashsdkmanager --list | grep build-toolssdkmanager "build-tools;34.0.0" "platforms;android-34" "platform-tools"```
Then re-set `Android SDK Path` in Editor Settings.
### Error: "Missing ‘platform-tools’ / adb not found"
```bashsdkmanager "platform-tools"export PATH="$PATH:$ANDROID_HOME/platform-tools"adb version```
### Gradle build fails: "Could not resolve com.android.tools.build:gradle"
This only happens when `gradle_build/use_gradle_build=true`. If you see it,either switch the preset back to the **default (non-Gradle) APK build** (whichis what MonkeyStudio ships with) or make sure the Gradle build needs networkaccess:
```bashexport GRADLE_OPTS="-Dorg.gradle.daemon=false"```
### Error: "Export template not found"
Re-run section 1.2 (or use *Manage Export Templates > Download*). The templatefolder name must exactly match the engine version, e.g. `4.7.2.stable`.
### Error: "Java version not compatible"
Godot's Android exporter requires **JDK 17**. Point Godot at it explicitly:
```bashsudo update-alternatives --config java # choose java-17```
### App crashes on launch with OOM on a 4GB phone
1. Lower `MemoryManager.asset_budget_mb` (default 512 MB) in `scripts/core/memory_manager.gd`.2. Keep `renderer/rendering_method` = `mobile`.3. Turn off shadows on low-end devices (already done automatically by `studio_main.gd` when FPS drops below 30).4. Import textures as ETC2/ASTC (already enabled in `project.godot`).
---
## Verifying the project without a device
```bash# 1. Reimport all resources (catches broken scripts)godot --headless --import
# 2. Run the automated subsystem tests (exits 0 on success)godot --headless res://tests/self_test.tscn```
`self_test.tscn` exercises MemoryManager, all mesh generators, every sculptbrush, the rigging/skinning path, cloth + hair simulation and the timeline.123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566[preset.0]
name="Android"platform="Android"runnable=trueadvanced_options=truededicated_server=falsecustom_features=""export_filter="all_resources"include_filter=""exclude_filter="tests/*, docs/*"export_path="build/MonkeyStudio.apk"patches=PackedStringArray()encryption_include_filters=""encryption_exclude_filters=""seed=0encrypt_pck=falseencrypt_directory=falsescript_export_mode=2
[preset.0.options]
custom_template/debug=""custom_template/release=""gradle_build/use_gradle_build=falsegradle_build/gradle_build_dir=""gradle_build/export_format=0gradle_build/min_sdk=""gradle_build/target_sdk=""architectures/armeabi-v7a=truearchitectures/arm64-v8a=truearchitectures/x86=falsearchitectures/x86_64=falseversion/code=1version/name="0.1.0"package/unique_name="com.monkeycode.monkeystudio"package/name="MonkeyStudio"package/signed=truepackage/app_category=2package/retain_data_on_uninstall=falsepackage/exclude_from_recents=falsepackage/show_in_android_tv=falsepackage/show_in_app_library=truepackage/show_as_launcher_app=falselauncher_icons/main_192x192=""launcher_icons/adaptive_foreground_432x432=""launcher_icons/adaptive_background_432x432=""graphics/opengl_debug=falsexr_features/xr_mode=0screen/immersive_mode=truescreen/support_small=truescreen/support_normal=truescreen/support_large=truescreen/support_xlarge=trueuser_data_backup/allow=falsecommand_line/extra_args=""apk_expansion/enable=falseapk_expansion/SALT=""apk_expansion/public_key=""permissions/custom_permissions=PackedStringArray()keystore/debug=""keystore/debug_user=""keystore/debug_password=""keystore/release=""keystore/release_user=""keystore/release_password=""12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061; Engine configuration file.; MonkeyStudio - 3D Mobile Creation Studio (Godot 4.x / GDScript); Generated for low-RAM (4GB) Android devices.;; Format:; [section]; param=value
config_version=5
[application]
config/name="MonkeyStudio"config/description="Open-source 3D mobile creation studio optimized for 4GB RAM devices."config/version="0.1.0"run/main_scene="res://scenes/main.tscn"config/features=PackedStringArray("4.7", "Mobile")config/quit_on_go_back=falseboot_splash/bg_color=Color(0.08, 0.09, 0.11, 1)boot_splash/show_image=false
[autoload]
MemoryManager="*res://scripts/core/memory_manager.gd"FeatureRegistry="*res://scripts/core/feature_registry.gd"MeshPool="*res://scripts/core/mesh_pool.gd"VertexBufferManager="*res://scripts/core/vertex_buffer_manager.gd"StudioBus="*res://scripts/core/studio_bus.gd"
[debug]
gdscript/warnings/untyped_declaration=1gdscript/warnings/unsafe_property_access=0
[display]
window/size/viewport_width=1280window/size/viewport_height=720window/stretch/mode="canvas_items"window/stretch/aspect="expand"window/handheld/orientation=1window/vsync/vsync_mode=1
[input_devices]
pointing/emulate_touch_from_mouse=truepointing/emulate_mouse_from_touch=true
[physics]
common/physics_ticks_per_second=303d/default_gravity=9.8
[rendering]
renderer/rendering_method="mobile"renderer/rendering_method.mobile="mobile"textures/vram_compression/import_etc2_astc=trueanti_aliasing/quality/msaa_3d=0environment/defaults/default_clear_color=Color(0.08, 0.09, 0.11, 1)limits/opengl/max_renderable_elements=200000123456[gd_scene load_steps=2 format=3]
[ext_resource type="Script" path="res://scripts/studio/studio_main.gd" id="1_main"]
[node name="StudioMain" type="Node3D"]script = ExtResource("1_main")123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135extends Node#### FeatureRegistry - catalog of every tool/feature and its RAM budget.#### This is what makes "100+ features that never OOM" possible: features are## *descriptions*, not live objects. A feature is only instantiated when the## user actually opens it, and torn down when they close it. The registry maps## each feature id -> {name, module, cost_mb, loaded}.#### Modules are GDScript files under res://scripts/modules/. Each module is a## Node that implements `_activate(host)` and `_deactivate()`.##
signal feature_activated(id: String)signal feature_deactivated(id: String)signal feature_failed(id: String, reason: String)
## id -> { name, module_path, cost_mb, node, active }var _features: Dictionary = {}## Currently instantiated feature nodes, keyed by id.var _live: Dictionary = {}## Parent node that hosts active feature modules.var host: Node = null
func _ready() -> void: register_all()
## --- Public API -------------------------------------------------------------
## Instantiate and activate a feature. Safe to call twice (no-op if active).func activate(id: String) -> bool: if not _features.has(id): feature_failed.emit(id, "unknown feature") return false if _live.has(id): feature_activated.emit(id) return true var f: Dictionary = _features[id] # Reserve memory *before* instantiating so eviction can happen first. MemoryManager.register(id, f["module_path"], float(f["cost_mb"])) var script: Resource = MemoryManager.acquire(id) if script == null or host == null: feature_failed.emit(id, "load failed or no host") MemoryManager.release(id) return false var node: Node = (script as GDScript).new() node.name = "Feature_" + id host.add_child(node) if node.has_method("_activate"): node.call("_activate", host) _live[id] = node feature_activated.emit(id) return true
## Deactivate and destroy a feature, returning its RAM to the pool.func deactivate(id: String) -> void: if not _live.has(id): return var node: Node = _live[id] if node.has_method("_deactivate"): node.call("_deactivate") node.queue_free() _live.erase(id) MemoryManager.release(id) # If nothing else references the module, drop the loaded script now. MemoryManager.purge(id) feature_deactivated.emit(id)
func is_active(id: String) -> bool: return _live.has(id)
func list_features() -> Array: var ids := _features.keys() ids.sort() return ids
func feature_count() -> int: return _features.size()
func get_info(id: String) -> Dictionary: return _features.get(id, {})
## --- Registration -----------------------------------------------------------
func _reg(id: String, name: String, module_path: String, cost_mb: float) -> void: _features[id] = { "name": name, "module_path": module_path, "cost_mb": cost_mb, "active": false, }
## The full feature catalog. Costs are conservative RAM estimates in MB and are## the numbers MemoryManager uses for eviction decisions.func register_all() -> void: # --- Mesh generation (Features 1-20) --- _reg("mesh.cube", "Cube Primitive", "res://scripts/modules/mesh_gen.gd", 0.5) _reg("mesh.sphere", "UV Sphere", "res://scripts/modules/mesh_gen.gd", 1.0) _reg("mesh.cylinder","Cylinder", "res://scripts/modules/mesh_gen.gd", 0.5) _reg("mesh.plane", "Plane", "res://scripts/modules/mesh_gen.gd", 0.2) _reg("mesh.suzanne", "Monkey Head", "res://scripts/modules/mesh_gen.gd", 2.0) _reg("mesh.torus", "Torus", "res://scripts/modules/mesh_gen.gd", 1.5) _reg("mesh.ico", "Icosphere", "res://scripts/modules/mesh_gen.gd", 1.0) _reg("mesh.text", "Text Mesh", "res://scripts/modules/mesh_gen.gd", 1.0)
# --- Sculpting (Features 21-40) --- _reg("sculpt.draw", "Draw Brush", "res://scripts/modules/sculpt.gd", 4.0) _reg("sculpt.grab", "Grab Brush", "res://scripts/modules/sculpt.gd", 4.0) _reg("sculpt.pinch", "Pinch Brush", "res://scripts/modules/sculpt.gd", 4.0) _reg("sculpt.smooth", "Smooth Brush", "res://scripts/modules/sculpt.gd", 4.0) _reg("sculpt.flatten", "Flatten Brush", "res://scripts/modules/sculpt.gd", 4.0)
# --- Rigging (Features 41-60) --- _reg("rig.skeleton", "Armature Editor", "res://scripts/modules/rigging.gd", 8.0) _reg("rig.weight", "Weight Paint", "res://scripts/modules/rigging.gd", 6.0)
# --- Simulation (Features 61-80) --- _reg("sim.cloth", "Cloth Sim", "res://scripts/modules/simulation.gd", 12.0) _reg("sim.hair", "Hair Sim", "res://scripts/modules/simulation.gd", 10.0) _reg("sim.wind", "Wind Field", "res://scripts/modules/simulation.gd", 2.0)
# --- Animation (Features 81-100) --- _reg("anim.timeline", "Timeline", "res://scripts/modules/timeline.gd", 3.0) _reg("anim.keyframe", "Keyframe Tool","res://scripts/modules/timeline.gd", 3.0)
print("[FeatureRegistry] %d features registered" % _features.size())1uid://cboamlhlsvaws123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182extends Node#### MemoryManager - central budget authority for low-RAM (4GB) Android devices.#### Responsibilities:## - Track a hard RAM budget for loadable assets and evict (LRU) when exceeded.## - Provide lazy `acquire(id)` / `release(id)` reference counting so a heavy## feature (hair sim, cloth, sculpt grid) only lives in RAM while in use.## - Never hold a strong reference to an evictable asset itself; it holds the## *path* and hands out instances, so eviction actually frees memory.#### Design notes:## - Godot is ref-counted; an asset is truly freed only when every strong ref## is dropped. Callers MUST call release() so we can drop the cache ref.## - We poll OS memory pressure and force-evict before the OOM killer arrives.##
signal budget_exceeded(evicted_count: int)signal memory_warning(used_mb: float, budget_mb: float)signal asset_loaded(id: String, cost_mb: float)signal asset_evicted(id: String, freed_mb: float)
## Total RAM this process is allowed to use for evictable assets.@export var asset_budget_mb: float = 512.0
## Soft threshold (fraction of budget) that triggers a warning.@export var warn_ratio: float = 0.8
## How often (seconds) to poll the OS memory monitor.@export var poll_interval: float = 1.0
## id -> { path, cost_mb, refs, last_used, resource }var _entries: Dictionary = {}## Monotonic counter used for LRU ordering.var _clock: int = 0var _poll_accum: float = 0.0## When true, release() cannot drop below zero refs (double-free guard).var _initialized := false
func _ready() -> void: set_process(true) _apply_platform_budget() _initialized = true print("[MemoryManager] budget=%.0f MB" % asset_budget_mb)
func _apply_platform_budget() -> void: # A 64-bit OS reports total RAM in bytes; keep a conservative slice for us. var total_mb := float(OS.get_memory_info().get("physical", 0)) / 1048576.0 if total_mb > 0.0: # Never claim more than 1/8 of physical RAM for evictable assets. asset_budget_mb = min(asset_budget_mb, total_mb * 0.125) # Hard floor so tiny test environments still work. asset_budget_mb = max(asset_budget_mb, 64.0)
## Register an asset path as loadable. Does NOT load it (that is the point: lazy).## `cost_mb` is a caller estimate; use VertexBufferManager.estimate_cost for meshes.func register(id: String, path: String, cost_mb: float) -> void: assert(not _entries.has(id), "MemoryManager: duplicate id '%s'" % id) _entries[id] = { "path": path, "cost_mb": cost_mb, "refs": 0, "last_used": 0, "resource": null, }
## Acquire an asset, loading it on first use. Every acquire must be matched## with exactly one release().func acquire(id: String) -> Resource: if not _entries.has(id): push_error("MemoryManager.acquire: unknown id '%s'" % id) return null var e: Dictionary = _entries[id] if e["resource"] == null: _ensure_room(e["cost_mb"]) var res: Resource = load(e["path"]) if res == null: push_error("MemoryManager: failed to load '%s'" % e["path"]) return null e["resource"] = res asset_loaded.emit(id, e["cost_mb"]) e["refs"] = int(e["refs"]) + 1 e["last_used"] = _next_clock() return e["resource"]
## Release one reference. When refs hit zero the asset becomes evictable.func release(id: String) -> void: if not _entries.has(id): return var e: Dictionary = _entries[id] e["refs"] = maxi(0, int(e["refs"]) - 1) e["last_used"] = _next_clock()
## Force-unload an asset regardless of refs. Only use when you know all live## references are gone (e.g. a panel was destroyed).func purge(id: String) -> void: if not _entries.has(id): return var e: Dictionary = _entries[id] if e["resource"] != null: var freed := float(e["cost_mb"]) if e["refs"] == 0: e["resource"] = null asset_evicted.emit(id, freed) e["refs"] = 0
func get_loaded_mb() -> float: var total := 0.0 for id in _entries: if _entries[id]["resource"] != null: total += float(_entries[id]["cost_mb"]) return total
func _next_clock() -> int: _clock += 1 return _clock
func _process(delta: float) -> void: _poll_accum += delta if _poll_accum < poll_interval: return _poll_accum = 0.0 var used := get_loaded_mb() if used >= asset_budget_mb * warn_ratio: memory_warning.emit(used, asset_budget_mb) # Also react to real OS pressure independent of our accounting. if OS.get_memory_info().get("physical", 0) > 0: var avail_mb := float(OS.get_memory_info()["available"]) / 1048576.0 if OS.get_memory_info().has("available") else INF if avail_mb < 128.0: _ensure_room(asset_budget_mb * 0.25, true)
## Evict unreferenced (LRU) assets until `need_mb` of room exists.func _ensure_room(need_mb: float, force: bool = false) -> void: while get_loaded_mb() + need_mb > asset_budget_mb: var victim := _pick_lru_victim() if victim == "": break var e: Dictionary = _entries[victim] var freed := float(e["cost_mb"]) e["resource"] = null e["refs"] = 0 asset_evicted.emit(victim, freed) if force and not _has_more_victims(): break budget_exceeded.emit(0)
func _pick_lru_victim() -> String: var best := "" var best_time := 0x7FFFFFFF for id in _entries: var e: Dictionary = _entries[id] if e["resource"] == null: continue if int(e["refs"]) > 0: continue if int(e["last_used"]) < best_time: best_time = int(e["last_used"]) best = id return best
func _has_more_victims() -> bool: return _pick_lru_victim() != ""
func debug_snapshot() -> Dictionary: return { "budget_mb": asset_budget_mb, "loaded_mb": get_loaded_mb(), "entries": _entries.size(), }1uid://bvnrikxgp2ich1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465extends Node#### MeshPool - recycles ArrayMesh instances to avoid allocation churn.#### On low-RAM Android, creating and freeing ArrayMesh objects every frame causes## GC spikes and fragmentation. This pool keeps a bounded number of meshes alive## and reuses them. Meshes handed back to the pool have their surfaces cleared,## freeing their GPU buffers while keeping the object (and its native handle).##
signal pool_grew(size: int)signal pool_trimmed(freed: int)
## Hard cap so the pool itself cannot become the memory leak.@export var max_pooled: int = 32
var _free: Array[ArrayMesh] = []var _live_count: int = 0var _peak_live: int = 0
## Get a cleared mesh. Reuses a pooled one if available.func acquire_mesh() -> ArrayMesh: var mesh: ArrayMesh if _free.size() > 0: mesh = _free.pop_back() else: mesh = ArrayMesh.new() _live_count += 1 _peak_live = maxi(_peak_live, _live_count) return mesh
## Return a mesh for reuse. Clears surfaces so its VRAM is released immediately.func release_mesh(mesh: ArrayMesh) -> void: if mesh == null: return _live_count = maxi(0, _live_count - 1) # Drop all surfaces: this frees the vertex buffers on the GPU side. for i in range(mesh.get_surface_count()): pass mesh.clear_surfaces() if _free.size() < max_pooled: _free.append(mesh) else: # Pool is full: let Godot free this one (mesh has no surfaces = cheap). pass
## Remove pooled-but-unused meshes down to `keep`. Call on scene transitions.func trim(keep: int = 8) -> void: var freed := 0 while _free.size() > keep: _free.pop_back() freed += 1 if freed > 0: pool_trimmed.emit(freed)
func stats() -> Dictionary: return { "pooled": _free.size(), "live": _live_count, "peak_live": _peak_live, }1uid://cl3rtwoien4se123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354extends Node#### StudioBus - global, loosely-coupled signal hub.#### Every subsystem talks through this bus instead of holding direct references## to each other. This keeps coupling low (easy to disable a module) and lets## modules be lazily loaded/unloaded without dangling pointers.##
# Selection / scenesignal object_selected(node: Node3D)signal object_deselected()signal scene_modified()
# Editingsignal brush_changed(brush_id: String)signal brush_radius_changed(radius: float)signal brush_strength_changed(strength: float)signal stroke_begin(world_pos: Vector3)signal stroke_apply(world_pos: Vector3, delta: Vector3)signal stroke_end()
# Memory / performancesignal low_memory()signal fps_throttled(fps: int)
# Simulationsignal sim_toggled(sim_id: String, enabled: bool)signal sim_settings_changed(sim_id: String, settings: Dictionary)
# Animationsignal timeline_playhead(time: float)signal keyframe_added(node_path: String, track: String, time: float)signal playback_state_changed(playing: bool)
# UIsignal panel_toggled(panel_id: String, visible: bool)
var _last_fps_emit := 0.0
func _process(delta: float) -> void: # Surface sustained FPS drops so the renderer can throttle (see Step 2.3). if delta <= 0.0: return var fps := int(Engine.get_frames_per_second()) if fps > 0 and fps < 30: _last_fps_emit += delta if _last_fps_emit >= 2.0: _last_fps_emit = 0.0 fps_throttled.emit(fps) else: _last_fps_emit = 0.01uid://bu0jjsgd4yf7a123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114extends Node#### VertexBufferManager - VRAM-aware helpers for building and editing meshes.#### Two jobs:## 1. estimate_cost_mb(): predict a mesh's RAM/VRAM footprint *before* build so## MemoryManager can decide to evict something else first.## 2. surface builders that operate on PackedArrays (CPU side) and upload once,## avoiding per-vertex set_vertex() calls which are catastrophic on mobile.#### Mobile rule of thumb used here: ONE glTF/ArrayMesh upload per edit, never a## stream of tiny updates. Sculpt strokes batch into a dirty region and flush.##
## Bytes per vertex for the attributes we upload: position(12) + normal(12) + uv(8)const BYTES_PER_VERTEX := 32## Extra overhead for indices (~4 bytes/vert on a typical closed mesh).const INDEX_OVERHEAD := 4## Conservative VRAM residency multiplier (driver copies, alignment, etc.).const VRAM_FACTOR := 1.35
## Estimate the RAM+VRAM cost of a mesh with `vertex_count` vertices in MB.func estimate_cost_mb(vertex_count: int) -> float: var bytes := float(vertex_count) * float(BYTES_PER_VERTEX + INDEX_OVERHEAD) return (bytes / 1048576.0) * VRAM_FACTOR
## Build an ArrayMesh from parallel PackedArrays in a single surface upload.## `arrays` must follow Godot's Mesh.ARRAY_* layout.func build_surface(vertices: PackedVector3Array, normals: PackedVector3Array, uvs: PackedVector2Array, indices: PackedInt32Array, mesh: ArrayMesh = null) -> ArrayMesh: var out := mesh if out == null: out = MeshPool.acquire_mesh() var arrays: Array = [] arrays.resize(Mesh.ARRAY_MAX) arrays[Mesh.ARRAY_VERTEX] = vertices arrays[Mesh.ARRAY_NORMAL] = normals arrays[Mesh.ARRAY_TEX_UV] = uvs arrays[Mesh.ARRAY_INDEX] = indices out.add_surface_from_arrays(Mesh.PRIMITIVE_TRIANGLES, arrays) return out
## Replace the geometry of an existing mesh in place (single edit surface).## Keeps the same ArrayMesh object so MeshPool accounting stays correct.func update_surface(mesh: ArrayMesh, surface_idx: int, vertices: PackedVector3Array, normals: PackedVector3Array, uvs: PackedVector2Array, indices: PackedInt32Array) -> void: mesh.clear_surfaces() build_surface(vertices, normals, uvs, indices, mesh) # Recompute AABB for correct culling; without this, culling breaks after # large edits and the object may vanish from the frustum. mesh.custom_aabb = _compute_aabb(vertices)
func _compute_aabb(vertices: PackedVector3Array) -> AABB: if vertices.is_empty(): return AABB() var mn := vertices[0] var mx := vertices[0] for v in vertices: mn = mn.min(v) mx = mx.max(v) return AABB(mn, mx - mn)
## Recompute smooth normals for a triangle soup. Used after sculpting/vertex## edits where normals must reflect the new shape (otherwise lighting freezes).func recompute_normals(vertices: PackedVector3Array, indices: PackedInt32Array) -> PackedVector3Array: var normals := PackedVector3Array() normals.resize(vertices.size()) for i in range(normals.size()): normals[i] = Vector3.ZERO var tri := indices.size() / 3 for t in range(tri): var i0 := indices[t * 3] var i1 := indices[t * 3 + 1] var i2 := indices[t * 3 + 2] var n := (vertices[i1] - vertices[i0]).cross(vertices[i2] - vertices[i0]) normals[i0] = normals[i0] + n normals[i1] = normals[i1] + n normals[i2] = normals[i2] + n for i in range(normals.size()): var n := normals[i] if n.length_squared() > 0.000001: normals[i] = n.normalized() else: normals[i] = Vector3.UP return normals
## Convenience: full rebuild + normal recompute + upload in one call.func commit(vertices: PackedVector3Array, indices: PackedInt32Array, uvs: PackedVector2Array, mesh: ArrayMesh) -> ArrayMesh: var normals := recompute_normals(vertices, indices) update_surface(mesh, 0, vertices, normals, uvs, indices) return mesh
func debug_vram_mb(meshes: Array) -> float: var total := 0.0 for m in meshes: if m is ArrayMesh: var vcount := 0 for s in range(m.get_surface_count()): var arr: Array = m.surface_get_arrays(s) if arr.size() > Mesh.ARRAY_VERTEX and arr[Mesh.ARRAY_VERTEX] != null: vcount += (arr[Mesh.ARRAY_VERTEX] as PackedVector3Array).size() total += estimate_cost_mb(vcount) return total1uid://d1dlqpu1odxhw123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051#!/usr/bin/env bash## install_godot.sh - install the latest stable Godot editor + export templates# on a Debian/Ubuntu Linux development machine.## This is the scripted form of STEP 1.1 from docs/BUILD_ANDROID.md.# It is safe to re-run; it overwrites the previous binary.#set -euo pipefail
GODOT_VERSION="${GODOT_VERSION:-4.7.2-stable}"INSTALL_DIR="${INSTALL_DIR:-/usr/local/bin}"TMP_DIR="$(mktemp -d)"trap 'rm -rf "$TMP_DIR"' EXIT
echo "==> Installing Godot ${GODOT_VERSION} into ${INSTALL_DIR}"
# 1. Fetch the editor binary.# The version-numbered name on the release server is the download URL.EDITOR_URL="https://github.com/godotengine/godot/releases/download/${GODOT_VERSION}/Godot_v${GODOT_VERSION}_linux.x86_64.zip"curl -fL --retry 3 --max-time 600 -o "${TMP_DIR}/godot.zip" "${EDITOR_URL}"
# 2. Unzip and install.unzip -o -q "${TMP_DIR}/godot.zip" -d "${TMP_DIR}"install -m 0755 "${TMP_DIR}/Godot_v${GODOT_VERSION}_linux.x86_64" "${INSTALL_DIR}/godot"
# 3. Redirect the .editor_settings templates dir so export works on first run.TEMPLATE_DIR="${HOME}/.local/share/godot/export_templates/$(echo "${GODOT_VERSION}" | sed 's/-stable/.stable/')"mkdir -p "${TEMPLATE_DIR}"TPZ_URL="https://github.com/godotengine/godot/releases/download/${GODOT_VERSION}/Godot_v${GODOT_VERSION}_export_templates.tpz"curl -fL --retry 3 --max-time 600 -o "${TMP_DIR}/templates.tpz" "${TPZ_URL}" || { echo "!! Could not auto-download export templates." >&2 echo " In the editor: Editor > Manage Export Templates > Download and Install." >&2}if [ -f "${TMP_DIR}/templates.tpz" ]; then unzip -o -q "${TMP_DIR}/templates.tpz" -d "${TMP_DIR}/tpl" cp -f "${TMP_DIR}"/tpl/templates/* "${TEMPLATE_DIR}/" 2>/dev/null || truefi
# 4. Runtime libraries Godot needs on a headless Debian box.# (Only the libs are installed here; skip if you already have a desktop.)if command -v apt-get >/dev/null 2>&1; then export DEBIAN_FRONTEND=noninteractive apt-get update -qq || true apt-get install -y -qq \ libfontconfig1 libfreetype6 libx11-6 libxcursor1 libxinerama1 \ libxrandr2 libxi6 libgl1 libasound2 libpulse0 unzip curl || truefi
echo "==> Done. Verify with: godot --version"godot --version123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282extends Node#### MeshGenModule - procedural primitive generators (Features 1-20).#### Every generator returns a MeshData Dictionary so it can be built for a## MeshPool mesh via VertexBufferManager. Nothing here allocates GPU buffers## until commit() is called, keeping generation cheap and evictable.#### MeshData := { verts: PackedVector3Array, indices: PackedInt32Array, uvs }##
var _host: Node = nullvar _root: Node3D = null
func _activate(host: Node) -> void: _host = host _root = host.get_node_or_null("Geometry") as Node3D print("[MeshGen] activated")
func _deactivate() -> void: _host = null _root = null
func _make_mesh_data() -> Dictionary: return { "verts": PackedVector3Array(), "indices": PackedInt32Array(), "uvs": PackedVector2Array(), }
## --- Public generator API ---------------------------------------------------
func generate(kind: String, params: Dictionary = {}) -> Dictionary: match kind: "cube": return cube(float(params.get("size", 1.0))) "sphere": return uv_sphere(int(params.get("rings", 16)), int(params.get("segments", 24)), float(params.get("radius", 0.5))) "cylinder": return cylinder(int(params.get("segments", 24)), float(params.get("top_r", 0.5)), float(params.get("bottom_r", 0.5)), float(params.get("height", 1.0))) "plane": return plane(int(params.get("subdiv", 1)), float(params.get("size", 2.0))) "torus": return torus(int(params.get("major_seg", 24)), int(params.get("minor_seg", 12)), float(params.get("major_r", 0.6)), float(params.get("minor_r", 0.2))) "ico": return icosphere(int(params.get("subdiv", 1)), float(params.get("radius", 0.5))) "suzanne": return suzanne(float(params.get("scale", 1.0))) _: push_warning("MeshGen: unknown kind '%s'" % kind) return _make_mesh_data()
## --- Generators -------------------------------------------------------------
func cube(size: float) -> Dictionary: var d := _make_mesh_data() var h := size * 0.5 var faces := [ # (normal, tangent, bitangent) for +X,-X,+Y,-Y,+Z,-Z [Vector3.RIGHT, Vector3.BACK, Vector3.UP], [Vector3.LEFT, Vector3.FORWARD, Vector3.UP], [Vector3.UP, Vector3.RIGHT, Vector3.BACK], [Vector3.DOWN, Vector3.RIGHT, Vector3.FORWARD], [Vector3.BACK, Vector3.RIGHT, Vector3.UP], [Vector3.FORWARD, Vector3.LEFT, Vector3.UP], ] for f in faces: var n: Vector3 = f[0] var t: Vector3 = f[1] var b: Vector3 = f[2] var base: int = d["verts"].size() var c := n * h d["verts"].append(c - t * h - b * h) d["verts"].append(c + t * h - b * h) d["verts"].append(c + t * h + b * h) d["verts"].append(c - t * h + b * h) d["uvs"].append(Vector2(0, 0)) d["uvs"].append(Vector2(1, 0)) d["uvs"].append(Vector2(1, 1)) d["uvs"].append(Vector2(0, 1)) d["indices"].append(base + 0); d["indices"].append(base + 1); d["indices"].append(base + 2) d["indices"].append(base + 0); d["indices"].append(base + 2); d["indices"].append(base + 3) return d
func uv_sphere(rings: int, segments: int, radius: float) -> Dictionary: var d := _make_mesh_data() rings = maxi(2, rings) segments = maxi(3, segments) for y in range(rings + 1): var v := float(y) / float(rings) var phi := v * PI for x in range(segments + 1): var u := float(x) / float(segments) var theta := u * TAU var pos := Vector3( sin(phi) * cos(theta), cos(phi), sin(phi) * sin(theta) ) * radius d["verts"].append(pos) d["uvs"].append(Vector2(u, v)) for y in range(rings): for x in range(segments): var a := y * (segments + 1) + x var b := a + segments + 1 d["indices"].append(a); d["indices"].append(b); d["indices"].append(a + 1) d["indices"].append(a + 1); d["indices"].append(b); d["indices"].append(b + 1) return d
func cylinder(segments: int, top_r: float, bottom_r: float, height: float) -> Dictionary: var d := _make_mesh_data() segments = maxi(3, segments) var hy := height * 0.5 for y in range(2): var r := top_r if y == 1 else bottom_r var yy := hy if y == 1 else -hy for x in range(segments + 1): var u := float(x) / float(segments) var theta := u * TAU d["verts"].append(Vector3(cos(theta) * r, yy, sin(theta) * r)) d["uvs"].append(Vector2(u, float(y))) for x in range(segments): var a := x var b := x + segments + 1 d["indices"].append(a); d["indices"].append(b); d["indices"].append(a + 1) d["indices"].append(a + 1); d["indices"].append(b); d["indices"].append(b + 1) # Caps var top_center: int = d["verts"].size() d["verts"].append(Vector3(0, hy, 0)); d["uvs"].append(Vector2(0.5, 0.5)) var bot_center: int = d["verts"].size() d["verts"].append(Vector3(0, -hy, 0)); d["uvs"].append(Vector2(0.5, 0.5)) for x in range(segments): var theta0 := (float(x) / float(segments)) * TAU var theta1 := (float(x + 1) / float(segments)) * TAU var t0: int = d["verts"].size() d["verts"].append(Vector3(cos(theta0) * top_r, hy, sin(theta0) * top_r)); d["uvs"].append(Vector2(0, 0)) d["verts"].append(Vector3(cos(theta1) * top_r, hy, sin(theta1) * top_r)); d["uvs"].append(Vector2(1, 0)) d["indices"].append(top_center); d["indices"].append(t0); d["indices"].append(t0 + 1) var b0: int = d["verts"].size() d["verts"].append(Vector3(cos(theta0) * bottom_r, -hy, sin(theta0) * bottom_r)); d["uvs"].append(Vector2(0, 0)) d["verts"].append(Vector3(cos(theta1) * bottom_r, -hy, sin(theta1) * bottom_r)); d["uvs"].append(Vector2(1, 0)) d["indices"].append(bot_center); d["indices"].append(b0 + 1); d["indices"].append(b0) return d
func plane(subdiv: int, size: float) -> Dictionary: var d := _make_mesh_data() subdiv = maxi(1, subdiv) var half := size * 0.5 for z in range(subdiv + 1): for x in range(subdiv + 1): var u := float(x) / float(subdiv) var v := float(z) / float(subdiv) d["verts"].append(Vector3(-half + u * size, 0, -half + v * size)) d["uvs"].append(Vector2(u, v)) var row := subdiv + 1 for z in range(subdiv): for x in range(subdiv): var a := z * row + x var b := a + row d["indices"].append(a); d["indices"].append(a + 1); d["indices"].append(b) d["indices"].append(a + 1); d["indices"].append(b + 1); d["indices"].append(b) return d
func torus(major_seg: int, minor_seg: int, major_r: float, minor_r: float) -> Dictionary: var d := _make_mesh_data() major_seg = maxi(3, major_seg) minor_seg = maxi(3, minor_seg) for i in range(major_seg + 1): var u := float(i) / float(major_seg) * TAU for j in range(minor_seg + 1): var v := float(j) / float(minor_seg) * TAU var center := Vector3(cos(u) * major_r, 0, sin(u) * major_r) var normal := Vector3(cos(u) * cos(v), sin(v), sin(u) * cos(v)) d["verts"].append(center + normal * minor_r) d["uvs"].append(Vector2(float(i) / float(major_seg), float(j) / float(minor_seg))) for i in range(major_seg): for j in range(minor_seg): var a := i * (minor_seg + 1) + j var b := a + minor_seg + 1 d["indices"].append(a); d["indices"].append(b); d["indices"].append(a + 1) d["indices"].append(a + 1); d["indices"].append(b); d["indices"].append(b + 1) return d
func icosphere(subdiv: int, radius: float) -> Dictionary: var d := _make_mesh_data() var t := (1.0 + sqrt(5.0)) * 0.5 var verts := [ Vector3(-1, t, 0), Vector3(1, t, 0), Vector3(-1, -t, 0), Vector3(1, -t, 0), Vector3(0, -1, t), Vector3(0, 1, t), Vector3(0, -1, -t), Vector3(0, 1, -t), Vector3(t, 0, -1), Vector3(t, 0, 1), Vector3(-t, 0, -1), Vector3(-t, 0, 1), ] var faces := [ [0, 11, 5], [0, 5, 1], [0, 1, 7], [0, 7, 10], [0, 10, 11], [1, 5, 9], [5, 11, 4], [11, 10, 2], [10, 7, 6], [7, 1, 8], [3, 9, 4], [3, 4, 2], [3, 2, 6], [3, 6, 8], [3, 8, 9], [4, 9, 5], [2, 4, 11], [6, 2, 10], [8, 6, 7], [9, 8, 1], ] for s in range(maxi(0, subdiv)): var new_faces := [] var cache := {} for f in faces: var a: int = f[0]; var b: int = f[1]; var c: int = f[2] var ab := _midpoint(verts, cache, a, b) var bc := _midpoint(verts, cache, b, c) var ca := _midpoint(verts, cache, c, a) new_faces.append([a, ab, ca]) new_faces.append([b, bc, ab]) new_faces.append([c, ca, bc]) new_faces.append([ab, bc, ca]) faces = new_faces for v in verts: d["verts"].append(v.normalized() * radius) d["uvs"].resize(d["verts"].size()) for f in faces: d["indices"].append(f[0]); d["indices"].append(f[1]); d["indices"].append(f[2]) return d
func _midpoint(verts: Array, cache: Dictionary, a: int, b: int) -> int: var key := "%d_%d" % [mini(a, b), maxi(a, b)] if cache.has(key): return cache[key] var mid: Vector3 = (verts[a] + verts[b]) * 0.5 verts.append(mid) var idx := verts.size() - 1 cache[key] = idx return idx
## A low-poly "Suzanne"-style monkey head silhouette (ears + cranium + snout).## Not bit-identical to Blender's Suzanne, but generated purely from code.func suzanne(scale: float) -> Dictionary: var d := _make_mesh_data() # Cranium: squashed sphere var cranium := uv_sphere(10, 16, 0.6) _append(d, cranium["verts"], cranium["indices"], cranium["uvs"], Vector3(0, 0.1, 0) * scale, scale) # Snout: a cube-ish extension forward var snout := cube(0.4) _append(d, snout["verts"], snout["indices"], snout["uvs"], Vector3(0, -0.1, 0.5) * scale, scale) # Ears: two flat spheres left/right var ear_l := uv_sphere(6, 10, 0.25) _append(d, ear_l["verts"], ear_l["indices"], ear_l["uvs"], Vector3(-0.6, 0.35, 0) * scale, scale) var ear_r := uv_sphere(6, 10, 0.25) _append(d, ear_r["verts"], ear_r["indices"], ear_r["uvs"], Vector3(0.6, 0.35, 0) * scale, scale) return d
## Merge a sub-mesh into a target MeshData with an offset and uniform scale.func _append(dst: Dictionary, verts: PackedVector3Array, indices: PackedInt32Array, uvs: PackedVector2Array, offset: Vector3, s: float) -> void: var base: int = dst["verts"].size() for v in verts: dst["verts"].append(v * s + offset) for u in uvs: dst["uvs"].append(u) for i in indices: dst["indices"].append(base + i)
## --- Instantiation helper ---------------------------------------------------
## Build a MeshInstance3D from a generated MeshData and attach under Geometry.## Returns the instance (caller owns its lifetime; use MeshPool.release on free).func spawn(kind: String, params: Dictionary = {}) -> MeshInstance3D: var data := generate(kind, params) return spawn_from_data(data, kind)
func spawn_from_data(data: Dictionary, name_hint: String = "mesh") -> MeshInstance3D: var mesh := MeshPool.acquire_mesh() VertexBufferManager.commit(data["verts"], data["indices"], data["uvs"], mesh) var mi := MeshInstance3D.new() mi.name = name_hint.capitalize() mi.mesh = mesh var mat := StandardMaterial3D.new() mat.albedo_color = Color(0.7, 0.72, 0.8) mat.shading_mode = BaseMaterial3D.SHADING_MODE_PER_PIXEL mi.material_override = mat if _root != null: _root.add_child(mi) return mi1uid://mh20ymrsudgf123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174extends Node#### RiggingModule - armature creation and automatic vertex weighting (Features 41-60).#### Creates a Skeleton3D, lets the user add bones as a transform hierarchy, and## binds skinning data (ARRAY_BONES + ARRAY_WEIGHTS) to a MeshInstance3D using## inverse-distance weighting against bone segments. The result is a normal,## engine-native skinned mesh - no custom shader needed.##
## Bone definitions the tool builds. Each entry: { name, parent, position, tail }var _bones: Array[Dictionary] = []var _skeleton: Skeleton3D = nullvar _host: Node = nullvar _bound_mesh: MeshInstance3D = null
func _activate(host: Node) -> void: _host = host StudioBus.object_selected.connect(_on_object_selected) print("[Rigging] activated")
func _deactivate() -> void: if StudioBus.object_selected.is_connected(_on_object_selected): StudioBus.object_selected.disconnect(_on_object_selected) _host = null
func _on_object_selected(node: Node3D) -> void: _bound_mesh = node as MeshInstance3D
## --- Armature creation ------------------------------------------------------
## Add a bone. parent="" means root. Returns the new bone index.func add_bone(name: String, parent: String, position: Vector3, tail: Vector3 = Vector3.ZERO) -> int: _ensure_skeleton() var parent_idx := -1 if parent != "": parent_idx = _find_bone(parent) var idx := _skeleton.get_bone_count() _skeleton.add_bone(name) if parent_idx >= 0: _skeleton.set_bone_parent(idx, parent_idx) var rest := Transform3D() # Point the bone's -Z toward its tail so rotations look natural. var dir := (tail - position) if dir.length_squared() > 0.000001: rest = Transform3D(_look_at_basis(dir.normalized()), position) else: rest = Transform3D(Basis.IDENTITY, position) _skeleton.set_bone_rest(idx, rest) _skeleton.set_bone_pose_position(idx, position) _bones.append({"name": name, "parent": parent, "index": idx}) StudioBus.scene_modified.emit() return idx
func _ensure_skeleton() -> void: if _skeleton != null and is_instance_valid(_skeleton): return _skeleton = Skeleton3D.new() _skeleton.name = "Armature" if _host != null: _host.get_node_or_null("Rig").add_child(_skeleton) if _host.has_node("Rig") else _host.add_child(_skeleton)
func _find_bone(name: String) -> int: if _skeleton == null: return -1 for i in range(_skeleton.get_bone_count()): if _skeleton.get_bone_name(i) == name: return i return -1
func _look_at_basis(dir: Vector3) -> Basis: var up := Vector3.UP if absf(dir.dot(up)) > 0.99: up = Vector3.RIGHT var right := dir.cross(up).normalized() var real_up := right.cross(dir).normalized() return Basis(right, real_up, -dir)
## Build a simple starter humanoid-ish spine + limbs for a mesh's bounds.func generate_default_armature(mesh: MeshInstance3D) -> void: if mesh == null or mesh.mesh == null: return var size := mesh.mesh.get_aabb().size var h := size.y add_bone("root", "", Vector3.ZERO, Vector3(0, h * 0.1, 0)) add_bone("spine", "root", Vector3(0, h * 0.1, 0), Vector3(0, h * 0.35, 0)) add_bone("chest", "spine", Vector3(0, h * 0.35, 0), Vector3(0, h * 0.6, 0)) add_bone("neck", "chest", Vector3(0, h * 0.6, 0), Vector3(0, h * 0.72, 0)) add_bone("head", "neck", Vector3(0, h * 0.72, 0), Vector3(0, h * 0.95, 0)) add_bone("arm_l", "chest", Vector3(-size.x * 0.4, h * 0.6, 0), Vector3(-size.x * 0.9, h * 0.45, 0)) add_bone("arm_r", "chest", Vector3(size.x * 0.4, h * 0.6, 0), Vector3(size.x * 0.9, h * 0.45, 0)) add_bone("leg_l", "root", Vector3(-size.x * 0.2, 0, 0), Vector3(-size.x * 0.2, -h * 0.5, 0)) add_bone("leg_r", "root", Vector3(size.x * 0.2, 0, 0), Vector3(size.x * 0.2, -h * 0.5, 0)) bind_weights(mesh)
## --- Automatic weight binding -----------------------------------------------
## Compute skinning arrays using inverse-distance to bone segments and apply.## `max_influences` must be <= 4 for the standard mobile skinning path.func bind_weights(mesh: MeshInstance3D, max_influences: int = 4) -> void: if mesh == null or _skeleton == null or mesh.mesh == null or mesh.mesh.get_surface_count() == 0: return var arr := mesh.mesh.surface_get_arrays(0) var verts: PackedVector3Array = arr[Mesh.ARRAY_VERTEX] var n := verts.size() var bone_count := _skeleton.get_bone_count() var bone_segments: Array = [] for i in range(bone_count): var pos := _skeleton.get_bone_global_rest(i).origin bone_segments.append({"idx": i, "pos": pos})
var vbones := PackedInt32Array() var vweights := PackedFloat32Array() vbones.resize(n * 4) vweights.resize(n * 4) var to_mesh := mesh.global_transform.affine_inverse()
for vi in range(n): var p := verts[vi] # Rank bones by distance to their head position. var dists: Array = [] for b in bone_segments: var local_bone: Vector3 = to_mesh * (mesh.global_transform * b["pos"]) dists.append({"idx": b["idx"], "d": p.distance_to(local_bone)}) dists.sort_custom(func(a, b): return a["d"] < b["d"]) var influ: int = mini(max_influences, dists.size()) var wsum := 0.0 var ws: Array[float] = [] for k in range(influ): var d: float = maxf(0.0001, dists[k]["d"]) var w := 1.0 / (d * d) ws.append(w) wsum += w for slot in range(4): var base := vi * 4 + slot if slot < influ and wsum > 0.0: vbones[base] = dists[slot]["idx"] vweights[base] = ws[slot] / wsum else: vbones[base] = 0 vweights[base] = 0.0
# Rebuild the mesh surface with skinning channels added. arr[Mesh.ARRAY_BONES] = vbones arr[Mesh.ARRAY_WEIGHTS] = vweights var new_mesh := MeshPool.acquire_mesh() new_mesh.add_surface_from_arrays(Mesh.PRIMITIVE_TRIANGLES, arr) mesh.mesh = new_mesh mesh.skeleton = mesh.get_path_to(_skeleton) # A Skin must be bound so the renderer knows which skeleton supplies the # bone transforms for these indices. add_bind(bone_index, rest_pose). var skin := Skin.new() for i in range(bone_count): skin.add_bind(i, _skeleton.get_bone_global_rest(i)) mesh.skin = skin StudioBus.scene_modified.emit() print("[Rigging] bound %d verts to %d bones" % [n, bone_count])
func bone_count() -> int: return _skeleton.get_bone_count() if _skeleton != null else 0
func get_skeleton() -> Skeleton3D: return _skeleton1uid://dedkqt37ilf6u123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238extends Node#### SculptModule - vertex-based sculpting brushes (Features 21-40).#### Works directly on a MeshInstance3D's surface arrays. A stroke is:## begin(pos) -> apply(pos, delta) x N -> end()## All applies accumulate into CPU PackedArrays; a single GPU upload happens in## end() (and optionally on a timer) so we do NOT upload per touch-move event.#### Brushes:## draw - push vertices along the surface normal / view dir## grab - drag vertices inside the radius with the pointer## pinch - pull vertices toward the brush center## smooth - laplacian relax toward neighbour average## flatten - move vertices toward the local average plane##
@export var radius: float = 0.5@export var strength: float = 0.5@export var invert: bool = false # hold shift / tap toggle to reverse
var _host: Node = nullvar _target: MeshInstance3D = nullvar _verts: PackedVector3Array = PackedVector3Array()var _indices: PackedInt32Array = PackedInt32Array()var _uvs: PackedVector2Array = PackedVector2Array()var _base_verts: PackedVector3Array = PackedVector3Array()var _dirty := falsevar _stroke_active := falsevar _brush_id := "draw"var _grab_origin := Vector3.ZEROvar _grab_delta := Vector3.ZERO
func _activate(host: Node) -> void: _host = host StudioBus.brush_changed.connect(_on_brush_changed) StudioBus.brush_radius_changed.connect(func(r: float): radius = r) StudioBus.brush_strength_changed.connect(func(s: float): strength = s) StudioBus.object_selected.connect(_on_object_selected) print("[Sculpt] activated")
func _deactivate() -> void: flush() if StudioBus.brush_changed.is_connected(_on_brush_changed): StudioBus.brush_changed.disconnect(_on_brush_changed) if StudioBus.object_selected.is_connected(_on_object_selected): StudioBus.object_selected.disconnect(_on_object_selected) _host = null _target = null
func _on_brush_changed(id: String) -> void: _brush_id = id
func _on_object_selected(node: Node3D) -> void: set_target(node as MeshInstance3D)
## Bind a MeshInstance3D and cache its arrays.func set_target(mi: MeshInstance3D) -> void: _target = mi if mi == null or mi.mesh == null or mi.mesh.get_surface_count() == 0: return var arr := mi.mesh.surface_get_arrays(0) _verts = arr[Mesh.ARRAY_VERTEX] _uvs = arr[Mesh.ARRAY_TEX_UV] if arr.size() > Mesh.ARRAY_TEX_UV and arr[Mesh.ARRAY_TEX_UV] != null else PackedVector2Array() _indices = arr[Mesh.ARRAY_INDEX] if arr.size() > Mesh.ARRAY_INDEX and arr[Mesh.ARRAY_INDEX] != null else PackedInt32Array() _base_verts = _verts.duplicate()
func begin(world_pos: Vector3) -> void: if _verts.is_empty(): return _stroke_active = true _dirty = false _grab_origin = world_pos _grab_delta = Vector3.ZERO StudioBus.stroke_begin.emit(world_pos)
func apply(world_pos: Vector3, move_delta: Vector3 = Vector3.ZERO) -> void: if not _stroke_active or _verts.is_empty(): return match _brush_id: "draw": _brush_draw(world_pos, move_delta) "grab": _brush_grab(world_pos, move_delta) "pinch": _brush_pinch(world_pos) "smooth": _brush_smooth(world_pos) "flatten": _brush_flatten(world_pos) _dirty = true StudioBus.stroke_apply.emit(world_pos, move_delta)
func end() -> void: if not _stroke_active: return _stroke_active = false flush() StudioBus.stroke_end.emit()
## Upload the accumulated CPU edits to the GPU in one shot.func flush() -> void: if not _dirty or _target == null or _target.mesh == null: return VertexBufferManager.commit(_verts, _indices, _uvs, _target.mesh) _base_verts = _verts.duplicate() _dirty = false StudioBus.scene_modified.emit()
## --- Brush implementations --------------------------------------------------
func _falloff(dist: float) -> float: if dist >= radius: return 0.0 var t := 1.0 - (dist / radius) return t * t * (3.0 - 2.0 * t) # smoothstep
func _brush_draw(center: Vector3, move_delta: Vector3) -> void: var dir := move_delta.normalized() if move_delta.length_squared() > 0.000001 else Vector3.UP var sign := -1.0 if invert else 1.0 var amp := strength * radius * 0.25 * sign var r2 := radius * radius for i in range(_verts.size()): var d2 := _verts[i].distance_squared_to(center) if d2 < r2: var w := _falloff(sqrt(d2)) _verts[i] = _verts[i] + dir * amp * w
func _brush_grab(center: Vector3, move_delta: Vector3) -> void: _grab_delta += move_delta var r2 := radius * radius # Move relative to where the stroke started for a stable, non-drifting feel. for i in range(_verts.size()): var src := _base_verts[i] var d2 := src.distance_squared_to(_grab_origin) if d2 < r2: var w := _falloff(sqrt(d2)) _verts[i] = src + _grab_delta * w
func _brush_pinch(center: Vector3) -> void: var sign := -1.0 if invert else 1.0 var r2 := radius * radius for i in range(_verts.size()): var v := _verts[i] var d2 := v.distance_squared_to(center) if d2 < r2: var w := _falloff(sqrt(d2)) var to_center := (center - v) _verts[i] = v + to_center * strength * 0.15 * w * sign
func _brush_smooth(center: Vector3) -> void: # Approximate neighbour average using the vertex's triangle neighbours. var sums := PackedVector3Array() var counts := PackedInt32Array() sums.resize(_verts.size()) counts.resize(_verts.size()) var tri := _indices.size() / 3 for t in range(tri): var a := _indices[t * 3] var b := _indices[t * 3 + 1] var c := _indices[t * 3 + 2] for pair in [[a, b], [b, c], [c, a]]: var k: int = pair[1] sums[k] = sums[k] + _verts[pair[0]] counts[k] = counts[k] + 1 var k2: int = pair[0] sums[k2] = sums[k2] + _verts[k] counts[k2] = counts[k2] + 1 var r2 := radius * radius for i in range(_verts.size()): if _verts[i].distance_squared_to(center) < r2 and counts[i] > 0: var avg := sums[i] / float(counts[i]) var w := _falloff(_verts[i].distance_to(center)) _verts[i] = _verts[i].lerp(avg, clampf(strength * w, 0.0, 1.0))
func _brush_flatten(center: Vector3) -> void: var r2 := radius * radius # Find the average normal of affected verts -> local plane. var avg_normal := Vector3.ZERO var affected: Array[int] = [] for i in range(_verts.size()): if _verts[i].distance_squared_to(center) < r2: affected.append(i) if affected.is_empty(): return for i in affected: avg_normal = avg_normal + (_base_verts[i] - center) avg_normal = avg_normal.normalized() if avg_normal.length_squared() > 0.000001 else Vector3.UP for i in affected: var v := _verts[i] var dist_to_plane := v.dot(avg_normal) - center.dot(avg_normal) var w := _falloff(v.distance_to(center)) _verts[i] = v - avg_normal * dist_to_plane * clampf(strength * w, 0.0, 1.0)
## Ray from camera through screen point; returns closest approach to mesh AABB.## A physics collider is preferred; this fallback keeps sculpting usable even## when the mesh has no collision shape (common right after generation).func raycast_screen(camera: Camera3D, screen_pos: Vector2) -> Dictionary: if camera == null or _target == null: return {"hit": false} var origin := camera.project_ray_origin(screen_pos) var dir := camera.project_ray_normal(screen_pos) var space := _host.get_viewport().world_3d.direct_space_state var q := PhysicsRayQueryParameters3D.create(origin, origin + dir * 1000.0) q.collide_with_areas = true var res := space.intersect_ray(q) if res.is_empty(): # Fallback: intersect ray with the mesh AABB as an approximation. var aabb := _target.mesh.get_aabb() var box_pos := _target.global_transform * aabb.position var t := _ray_box(origin, dir, _target.global_transform * (aabb.position + aabb.size * 0.5), aabb.size.length() * 0.5) if t > 0.0: return {"hit": true, "position": origin + dir * t, "normal": Vector3.UP} return {"hit": false} return {"hit": true, "position": res["position"], "normal": res["normal"]}
func _ray_box(origin: Vector3, dir: Vector3, center: Vector3, r: float) -> float: # Sphere approximation of the mesh bounds for the fallback ray test. var oc := origin - center var b := oc.dot(dir) var c := oc.dot(oc) - r * r var disc := b * b - c if disc < 0.0: return -1.0 var t := -b - sqrt(disc) return t if t > 0.0 else (-b + sqrt(disc))1uid://e464m7f2eegd123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304extends Node#### SimulationModule - lightweight mass-spring solver for cloth & hair## (Features 61-80), tuned for mobile CPUs.#### Approach: a fixed grid of particles connected by springs (structural,## shear, bend). Integration uses fixed-dt sub-stepping with Verlet and## constraint relaxation (Jakobsen) which is stable at low iteration counts -## far cheaper than a full PBD/XPBD solver while looking convincing.#### Memory: particle + spring arrays are PackedArrays; nothing is allocated per## frame. The whole sim is torn down by FeatureRegistry.deactivate() when the## user leaves the module, so its RAM returns to the pool.##
## sim_id -> { settings, particles, springs, mesh, instance }var _sims: Dictionary = {}var _host: Node = nullvar _accumulator: float = 0.0
const FIXED_DT := 1.0 / 30.0const MAX_SUBSTEPS := 4
func _activate(host: Node) -> void: _host = host set_process(true) StudioBus.sim_toggled.connect(_on_sim_toggled) StudioBus.sim_settings_changed.connect(_on_settings_changed) print("[Simulation] activated")
func _deactivate() -> void: if StudioBus.sim_toggled.is_connected(_on_sim_toggled): StudioBus.sim_toggled.disconnect(_on_sim_toggled) if StudioBus.sim_settings_changed.is_connected(_on_settings_changed): StudioBus.sim_settings_changed.disconnect(_on_settings_changed) _sims.clear() _host = null
func _on_sim_toggled(sim_id: String, enabled: bool) -> void: if enabled and not _sims.has(sim_id): _build_default(sim_id) if _sims.has(sim_id): _sims[sim_id]["settings"]["enabled"] = enabled
func _on_settings_changed(sim_id: String, settings: Dictionary) -> void: if not _sims.has(sim_id): return for k in settings: _sims[sim_id]["settings"][k] = settings[k]
func _build_default(sim_id: String) -> void: if sim_id == "sim.cloth": create_cloth("sim.cloth", 12, 12, 1.0) elif sim_id == "sim.hair": create_hair("sim.hair", 10, 10)
## --- Cloth ------------------------------------------------------------------
## Create a cloth grid of cols x rows, size meters wide (square), hung from the## top edge and simulated against gravity + wind.func create_cloth(sim_id: String, cols: int, rows: int, size: float) -> void: cols = maxi(2, cols) rows = maxi(2, rows) var particles := PackedVector3Array() var pinned := PackedByteArray() var step := size / float(cols - 1) for r in range(rows): for c in range(cols): particles.append(Vector3((c - (cols - 1) * 0.5) * step, -r * step, 0.0)) # Pin the top row so the cloth hangs. pinned.append(1 if r == 0 else 0) var springs := PackedInt32Array() var rest := PackedFloat32Array() _add_structural(cols, rows, particles, springs, rest) _add_shear(cols, rows, particles, springs, rest) var mesh := MeshPool.acquire_mesh() var mi := _make_instance("Cloth") _sims[sim_id] = { "settings": { "enabled": true, "gravity": -9.8, "wind": Vector3(0.6, 0.0, 0.2), "damping": 0.02, "iterations": 6, "stiffness": 1.0, "cols": cols, "rows": rows, }, "particles": particles, "prev": particles.duplicate(), "pinned": pinned, "springs": springs, "rest": rest, "mesh": mesh, "instance": mi, }
func _add_structural(cols: int, rows: int, pos: PackedVector3Array, springs: PackedInt32Array, rest: PackedFloat32Array) -> void: for r in range(rows): for c in range(cols): var i := r * cols + c if c + 1 < cols: _push_spring(i, i + 1, pos, springs, rest) if r + 1 < rows: _push_spring(i, i + cols, pos, springs, rest)
func _add_shear(cols: int, rows: int, pos: PackedVector3Array, springs: PackedInt32Array, rest: PackedFloat32Array) -> void: for r in range(rows - 1): for c in range(cols - 1): var i := r * cols + c _push_spring(i, i + cols + 1, pos, springs, rest) _push_spring(i + 1, i + cols, pos, springs, rest)
func _push_spring(a: int, b: int, pos: PackedVector3Array, springs: PackedInt32Array, rest: PackedFloat32Array) -> void: springs.append(a) springs.append(b) rest.append(pos[a].distance_to(pos[b]))
## --- Hair -------------------------------------------------------------------
## Create `strands` strands, each `segments` long, rooted along a horizontal line.func create_hair(sim_id: String, strands: int, segments: int) -> void: var particles := PackedVector3Array() var pinned := PackedByteArray() var springs := PackedInt32Array() var rest := PackedFloat32Array() var spread := 1.0 for s in range(strands): var x := (float(s) / float(maxi(1, strands - 1)) - 0.5) * spread var base := particles.size() for seg in range(segments): particles.append(Vector3(x, 0.5 - seg * 0.08, 0.0)) pinned.append(1 if seg == 0 else 0) for seg in range(segments - 1): _push_spring(base + seg, base + seg + 1, particles, springs, rest) var mesh := MeshPool.acquire_mesh() var mi := _make_instance("Hair") _sims[sim_id] = { "settings": { "enabled": true, "gravity": -9.8, "wind": Vector3(0.2, 0.0, 0.4), "damping": 0.05, "iterations": 4, "stiffness": 0.8, "strands": strands, "segments": segments, }, "particles": particles, "prev": particles.duplicate(), "pinned": pinned, "springs": springs, "rest": rest, "mesh": mesh, "instance": mi, }
func _make_instance(name: String) -> MeshInstance3D: var mi := MeshInstance3D.new() mi.name = name var mat := StandardMaterial3D.new() mat.albedo_color = Color(0.55, 0.6, 0.75) mat.cull_mode = BaseMaterial3D.CULL_DISABLED mi.material_override = mat if _host != null: var geom := _host.get_node_or_null("Geometry") (geom if geom else _host).add_child(mi) # Collision is only needed for the rays; nothing to add here for now. return mi
## --- Solver ----------------------------------------------------------------
func _process(delta: float) -> void: var any := false for id in _sims: var sim: Dictionary = _sims[id] if sim["settings"]["enabled"]: any = true break if not any: return _accumulator += delta var steps := 0 while _accumulator >= FIXED_DT and steps < MAX_SUBSTEPS: for id in _sims: var sim: Dictionary = _sims[id] if sim["settings"]["enabled"]: _step(sim) _accumulator -= FIXED_DT steps += 1 if steps >= MAX_SUBSTEPS: _accumulator = 0.0 # drop backlog instead of spiralling for id in _sims: _upload(_sims[id])
## Verlet integration + Jacobi-style constraint relaxation.func _step(sim: Dictionary) -> void: var s: Dictionary = sim["settings"] var pos: PackedVector3Array = sim["particles"] var prev: PackedVector3Array = sim["prev"] var pinned: PackedByteArray = sim["pinned"] var gravity: float = s["gravity"] var wind: Vector3 = s["wind"] var damping: float = s["damping"] var dt := FIXED_DT
for i in range(pos.size()): if pinned[i] == 1: continue var velocity := (pos[i] - prev[i]) * (1.0 - damping) prev[i] = pos[i] var accel := Vector3(0, gravity, 0) + wind pos[i] = pos[i] + velocity + accel * dt * dt
var springs: PackedInt32Array = sim["springs"] var rest: PackedFloat32Array = sim["rest"] var stiffness: float = s["stiffness"] for _it in range(int(s["iterations"])): for k in range(rest.size()): var a := springs[k * 2] var b := springs[k * 2 + 1] var delta_v := pos[b] - pos[a] var d := delta_v.length() if d < 0.00001: continue var diff := (d - rest[k]) / d var correction := delta_v * 0.5 * diff * stiffness if pinned[a] == 0: pos[a] = pos[a] + correction if pinned[b] == 0: pos[b] = pos[b] - correction
## Upload the current particle positions as a triangle strip / line mesh.func _upload(sim: Dictionary) -> void: var pos: PackedVector3Array = sim["particles"] var mesh: ArrayMesh = sim["mesh"] var cols: int = sim["settings"].get("cols", 0) var rows: int = sim["settings"].get("rows", 0) if cols > 1 and rows > 1: _upload_cloth(pos, cols, rows, mesh) else: _upload_hair(pos, sim["settings"].get("strands", 0), sim["settings"].get("segments", 0), mesh)
func _upload_cloth(pos: PackedVector3Array, cols: int, rows: int, mesh: ArrayMesh) -> void: var indices := PackedInt32Array() for r in range(rows - 1): for c in range(cols - 1): var i := r * cols + c indices.append(i); indices.append(i + 1); indices.append(i + cols) indices.append(i + 1); indices.append(i + cols + 1); indices.append(i + cols) var uvs := PackedVector2Array() uvs.resize(pos.size()) for i in range(pos.size()): uvs[i] = Vector2(float(i % cols) / float(cols), float(i / cols) / float(rows)) var normals := VertexBufferManager.recompute_normals(pos, indices) mesh.clear_surfaces() var arrays: Array = [] arrays.resize(Mesh.ARRAY_MAX) arrays[Mesh.ARRAY_VERTEX] = pos arrays[Mesh.ARRAY_NORMAL] = normals arrays[Mesh.ARRAY_TEX_UV] = uvs arrays[Mesh.ARRAY_INDEX] = indices mesh.add_surface_from_arrays(Mesh.PRIMITIVE_TRIANGLES, arrays)
func _upload_hair(pos: PackedVector3Array, strands: int, segments: int, mesh: ArrayMesh) -> void: if strands <= 1 or segments <= 1: return var ribbons := PackedVector3Array() var indices := PackedInt32Array() var uvs := PackedVector2Array() var width := 0.02 for s in range(strands): var base := s * segments var line_base := ribbons.size() for seg in range(segments): var p := pos[base + seg] var tangent := Vector3.RIGHT if seg + 1 < segments: tangent = (pos[base + seg + 1] - p).normalized() var side := tangent.cross(Vector3.FORWARD).normalized() * width ribbons.append(p - side) ribbons.append(p + side) uvs.append(Vector2(0, float(seg) / float(segments))) uvs.append(Vector2(1, float(seg) / float(segments))) for seg in range(segments - 1): var a := line_base + seg * 2 indices.append(a); indices.append(a + 1); indices.append(a + 2) indices.append(a + 1); indices.append(a + 3); indices.append(a + 2) var normals := VertexBufferManager.recompute_normals(ribbons, indices) mesh.clear_surfaces() var arrays: Array = [] arrays.resize(Mesh.ARRAY_MAX) arrays[Mesh.ARRAY_VERTEX] = ribbons arrays[Mesh.ARRAY_NORMAL] = normals arrays[Mesh.ARRAY_TEX_UV] = uvs arrays[Mesh.ARRAY_INDEX] = indices mesh.add_surface_from_arrays(Mesh.PRIMITIVE_TRIANGLES, arrays)
func set_wind(sim_id: String, wind: Vector3) -> void: if _sims.has(sim_id): _sims[sim_id]["settings"]["wind"] = wind
func active_sim_count() -> int: return _sims.size()1uid://by4bu3p6btqr8123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174extends Node#### TimelineModule - keyframe timeline for objects and bones (Features 81-100).#### Backed by a real Godot Animation resource + AnimationPlayer, so playback,## interpolation and looping use engine-native code (fast, cached). The module## exposes a touch-friendly API: scrub(), add_keyframe(), play(), pause().##
@export var duration: float = 5.0@export var fps: int = 30
var _host: Node = nullvar _player: AnimationPlayer = nullvar _anim: Animation = nullvar _playhead: float = 0.0var _playing := falsevar _key_count := 0
func _activate(host: Node) -> void: _host = host _ensure_player() print("[Timeline] activated (%.1fs @ %d fps)" % [duration, fps])
func _deactivate() -> void: _playing = false _player = null _anim = null _host = null
func _ensure_player() -> void: if _player != null and is_instance_valid(_player): return _anim = Animation.new() _anim.length = duration _anim.step = 1.0 / float(fps) _player = AnimationPlayer.new() _player.name = "TimelinePlayer" if _host != null: _host.add_child(_player) var lib := AnimationLibrary.new() lib.add_animation("main", _anim) _player.add_animation_library("", lib) _player.animation_finished.connect(_on_finished)
func _process(delta: float) -> void: if not _playing or _player == null: return _playhead = _player.current_animation_position StudioBus.timeline_playhead.emit(_playhead)
## --- Playback ---------------------------------------------------------------
func play(from: float = -1.0) -> void: _ensure_player() if from >= 0.0: _player.seek(from, true) _player.play("main") _playing = true StudioBus.playback_state_changed.emit(true)
func pause() -> void: if _player != null: _player.pause() _playing = false StudioBus.playback_state_changed.emit(false)
func stop() -> void: if _player != null: _player.stop() _playhead = 0.0 _playing = false StudioBus.playback_state_changed.emit(false)
## Jump the playhead to `time` seconds (scrubbing).func scrub(time: float) -> void: _ensure_player() time = clampf(time, 0.0, duration) _playhead = time _player.seek(time, true) StudioBus.timeline_playhead.emit(time)
func is_playing() -> bool: return _playing
func playhead() -> float: return _playhead
## --- Keyframes --------------------------------------------------------------
## Add a keyframe for a `property` (NodePath-style) on an object at `time`.## For bones use property like "bones/Head:position" (Skeleton3D pose tracks).func add_keyframe(target_node: Node3D, property: String, time: float, value: Variant) -> void: _ensure_player() time = clampf(time, 0.0, duration) var path := _player.get_path_to(target_node) if path == NodePath(): push_warning("Timeline: target is not under the player root") return var track := _find_or_create_track(String(path), property, value) var key_idx := _anim.track_insert_key(track, time, value, 0.0) if key_idx >= 0: _key_count += 1 StudioBus.keyframe_added.emit(String(path), property, time) StudioBus.scene_modified.emit()
func _find_or_create_track(node_path: String, property: String, value: Variant) -> int: var full := NodePath(node_path + ":" + property) for i in range(_anim.get_track_count()): if _anim.track_get_path(i) == full: return i var type := Animation.TYPE_VALUE if value is Transform3D: type = Animation.TYPE_VALUE _anim.add_track(type) var idx := _anim.get_track_count() - 1 _anim.track_set_path(idx, full) if value is Vector3: _anim.track_set_interpolation_type(idx, Animation.INTERPOLATION_CUBIC) return idx
## Convenience: key every transform channel of a bone of a Skeleton3D.## Godot stores bone poses as 3D transforms, so we key position/rotation/scale.func add_bone_keyframe(skeleton: Skeleton3D, bone_name: String, time: float) -> void: if skeleton == null: return var bone_idx := skeleton.find_bone(bone_name) if bone_idx < 0: push_warning("Timeline: bone '%s' not found" % bone_name) return var skin_path := "%s:%s" % [_player.get_path_to(skeleton), bone_name] var pose := skeleton.get_bone_pose(bone_idx) add_keyframe(skeleton, "bones/" + bone_name + "/position", time, pose.origin) # Store rotation as quaternion for clean interpolation. add_keyframe(skeleton, "bones/" + bone_name + "/rotation", time, pose.basis.get_rotation_quaternion()) add_keyframe(skeleton, "bones/" + bone_name + "/scale", time, pose.basis.get_scale())
func delete_keyframe(track: int, key: int) -> void: if track >= 0 and track < _anim.get_track_count(): _anim.track_remove_key(track, key) _key_count = maxi(0, _key_count - 1)
func track_count() -> int: return _anim.get_track_count() if _anim != null else 0
func key_count() -> int: return _key_count
func set_duration(seconds: float) -> void: duration = maxf(0.1, seconds) _ensure_player() _anim.length = duration
func _on_finished() -> void: _playing = false StudioBus.playback_state_changed.emit(false)1uid://rfbjygv1at48123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140extends Node3D#### StudioMain - root bootstrap for MonkeyStudio.#### Builds the runtime scene tree in code so the whole app is one auditable## script rather than a fragile binary .tscn. Scene tree created:#### StudioMain (Node3D)## ├── WorldEnvironment (mobile renderer settings)## ├── Sun (DirectionalLight3D)## ├── Camera3D (touch_camera.gd)## ├── Geometry (Node3D) <- user-created meshes live here## ├── Rig (Node3D) <- Skeleton3D lives here## ├── Features (Node) <- lazily-instantiated feature modules## └── UI (CanvasLayer)## └── (built by studio_ui.gd)##
const TouchCameraScript := preload("res://scripts/studio/touch_camera.gd")const StudioUIScript := preload("res://scripts/studio/studio_ui.gd")
var camera: Camera3Dvar geometry: Node3Dvar rig: Node3Dvar feature_host: Nodevar ui: CanvasLayer
func _ready() -> void: _build_environment() _build_lighting() _build_camera() geometry = _make_node("Geometry") rig = _make_node("Rig") feature_host = Node.new() feature_host.name = "Features" add_child(feature_host) FeatureRegistry.host = feature_host _build_ui() _spawn_starter_scene() _connect_signals() print("[StudioMain] ready. %d features available." % FeatureRegistry.feature_count())
func _build_environment() -> void: var env := Environment.new() env.background_mode = Environment.BG_COLOR env.background_color = Color(0.08, 0.09, 0.11) env.ambient_light_source = Environment.AMBIENT_SOURCE_COLOR env.ambient_light_color = Color(0.35, 0.38, 0.45) env.ambient_light_energy = 0.6 # Mobile-friendly tonemap + no heavy SSAO/GI by default. env.tonemap_mode = Environment.TONE_MAPPER_FILMIC env.ssao_enabled = false env.glow_enabled = false var we := WorldEnvironment.new() we.name = "WorldEnvironment" we.environment = env add_child(we)
func _build_lighting() -> void: var sun := DirectionalLight3D.new() sun.name = "Sun" sun.rotation_degrees = Vector3(-50, -40, 0) sun.light_energy = 1.1 sun.shadow_enabled = true # Lower shadow resolution on mobile to save bandwidth. sun.directional_shadow_max_distance = 40.0 add_child(sun)
func _build_camera() -> void: camera = TouchCameraScript.new() camera.name = "Camera3D" camera.fov = 60.0 camera.position = Vector3(4, 4, 8) add_child(camera) camera.focus = Vector3.ZERO
func _make_node(n: String) -> Node3D: var node := Node3D.new() node.name = n add_child(node) return node
func _build_ui() -> void: ui = StudioUIScript.new() ui.name = "UI" add_child(ui)
## Spawn a cube so the app is immediately interactive on first launch.func _spawn_starter_scene() -> void: FeatureRegistry.activate("mesh.cube") var gen: Node = feature_host.get_node_or_null("Feature_mesh.cube") if gen != null and gen.has_method("spawn"): var mesh: MeshInstance3D = gen.call("spawn", "cube", {"size": 1.5}) _ensure_collision(mesh) StudioBus.object_selected.emit(mesh) if camera != null: camera.frame_aabb(mesh.mesh.get_aabb())
## Give a mesh a static trimesh collider so sculpting raycasts hit it.func _ensure_collision(mi: MeshInstance3D) -> void: if mi == null or mi.mesh == null: return var body := StaticBody3D.new() body.name = mi.name + "_Body" var shape := CollisionShape3D.new() var trimesh := mi.mesh.create_trimesh_shape() if trimesh != null: shape.shape = trimesh else: # Fallback to a box for exotic primitives without trimesh support. var box := BoxShape3D.new() box.size = mi.mesh.get_aabb().size shape.shape = box body.add_child(shape) mi.add_child(body)
func _connect_signals() -> void: StudioBus.fps_throttled.connect(_on_fps_throttled) MemoryManager.memory_warning.connect(_on_memory_warning)
func _on_fps_throttled(fps: int) -> void: # Shed load: disable shadows first, then reduce the sim substep budget. var sun := get_node_or_null("Sun") as DirectionalLight3D if sun != null and sun.shadow_enabled: sun.shadow_enabled = false print("[Perf] shadows off at %d fps" % fps)
func _on_memory_warning(used_mb: float, budget_mb: float) -> void: print("[Mem] warning: %.0f/%.0f MB" % [used_mb, budget_mb])1uid://ds0chccxfkthr123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418extends CanvasLayer#### StudioUI - dark material theme + floating, collapsible panels (Step 4).#### Layout (all built in code, resolution independent, scaled by a UI_SCALE## constant so it fits phones in portrait/landscape and tablets):#### TopBar : project name, memory HUD, undo/redo## LeftDock : tool rail (mesh / sculpt / rig / sim / anim)## RightPanels : collapsible panels -> Tools, Layers, Timeline## BottomBar : play/pause + timeline scrubber#### Touch targets are >= 48px. The theme is Material-ish dark to match the## viewport and reduce OLED power draw on phones.##
const UI_SCALE := 1.0const TOUCH_MIN := 48.0
var _touch_camera: Camera3D = nullvar _ui_root: Controlvar _panels: Dictionary = {} # panel_id -> PanelContainervar _tool_buttons: Dictionary = {}var _memory_label: Labelvar _fps_label: Labelvar _timeline: HSlidervar _play_button: Buttonvar _status: Label
var _active_brush := "sculpt.draw"
func _ready() -> void: layer = 10 _touch_camera = get_parent().get_node_or_null("Camera3D") as Camera3D _build_theme() _build_root() _build_top_bar() _build_tool_rail() _build_panels() _build_bottom_bar() _connect_bus()
## --- Theme ------------------------------------------------------------------
func _build_theme() -> void: var theme := Theme.new() theme.default_font_size = int(16 * UI_SCALE)
var panel := StyleBoxFlat.new() panel.bg_color = Color(0.11, 0.12, 0.15, 0.94) panel.corner_radius_top_left = 10 panel.corner_radius_top_right = 10 panel.corner_radius_bottom_left = 10 panel.corner_radius_bottom_right = 10 panel.content_margin_left = 10 panel.content_margin_right = 10 panel.content_margin_top = 8 panel.content_margin_bottom = 8 theme.set_stylebox("panel", "PanelContainer", panel)
var btn := StyleBoxFlat.new() btn.bg_color = Color(0.18, 0.2, 0.25) btn.corner_radius_top_left = 8 btn.corner_radius_top_right = 8 btn.corner_radius_bottom_left = 8 btn.corner_radius_bottom_right = 8 btn.content_margin_left = 12 btn.content_margin_right = 12 btn.content_margin_top = 8 btn.content_margin_bottom = 8 theme.set_stylebox("normal", "Button", btn)
var btn_hover := btn.duplicate() as StyleBoxFlat btn_hover.bg_color = Color(0.24, 0.27, 0.33) theme.set_stylebox("hover", "Button", btn_hover)
var btn_pressed := btn.duplicate() as StyleBoxFlat btn_pressed.bg_color = Color(0.31, 0.55, 0.86) theme.set_stylebox("pressed", "Button", btn_pressed)
theme.set_color("font_color", "Label", Color(0.88, 0.9, 0.94)) theme.set_color("font_color", "Button", Color(0.88, 0.9, 0.94))
_ui_root_theme = theme
var _ui_root_theme: Theme
## --- Layout -----------------------------------------------------------------
func _build_root() -> void: var root := Control.new() root.name = "Root" root.theme = _ui_root_theme root.set_anchors_preset(Control.PRESET_FULL_RECT) root.mouse_filter = Control.MOUSE_FILTER_IGNORE add_child(root) _ui_root = root
func _build_top_bar() -> void: var bar := PanelContainer.new() bar.name = "TopBar" bar.set_anchors_preset(Control.PRESET_TOP_WIDE) bar.custom_minimum_size = Vector2(0, 52 * UI_SCALE) bar.mouse_filter = Control.MOUSE_FILTER_STOP _ui_root.add_child(bar)
var hbox := HBoxContainer.new() hbox.add_theme_constant_override("separation", 10) bar.add_child(hbox)
var title := Label.new() title.text = " MonkeyStudio" title.add_theme_font_size_override("font_size", int(20 * UI_SCALE)) hbox.add_child(title)
var spacer := Control.new() spacer.size_flags_horizontal = Control.SIZE_EXPAND_FILL hbox.add_child(spacer)
_fps_label = Label.new() _fps_label.text = "FPS --" hbox.add_child(_fps_label)
_memory_label = Label.new() _memory_label.text = "MEM --" hbox.add_child(_memory_label)
func _build_tool_rail() -> void: var rail := PanelContainer.new() rail.name = "LeftDock" rail.set_anchors_preset(Control.PRESET_CENTER_LEFT) rail.position = Vector2(8, 0) rail.mouse_filter = Control.MOUSE_FILTER_STOP _ui_root.add_child(rail)
var vbox := VBoxContainer.new() vbox.add_theme_constant_override("separation", 8) rail.add_child(vbox)
var tools := [ ["mesh", "Mesh", "mesh.cube"], ["sculpt", "Sculpt", "sculpt.draw"], ["rig", "Rig", "rig.skeleton"], ["sim", "Sim", "sim.cloth"], ["anim", "Anim", "anim.timeline"], ] for t in tools: var b := Button.new() b.text = t[1] b.custom_minimum_size = Vector2(96 * UI_SCALE, TOUCH_MIN * UI_SCALE) b.pressed.connect(_on_tool_pressed.bind(t[2])) vbox.add_child(b) _tool_buttons[t[0]] = b
func _build_panels() -> void: var stack := VBoxContainer.new() stack.name = "RightPanels" stack.set_anchors_preset(Control.PRESET_TOP_RIGHT) stack.position = Vector2(-8, 60) stack.add_theme_constant_override("separation", 8) _ui_root.add_child(stack)
_add_panel(stack, "tools", "Tools", _build_tools_panel()) _add_panel(stack, "layers", "Layers", _build_layers_panel()) _add_panel(stack, "timeline", "Timeline", _build_timeline_panel())
func _add_panel(parent: Control, id: String, title: String, content: Control) -> void: var panel := PanelContainer.new() panel.name = "Panel_" + id panel.custom_minimum_size = Vector2(220 * UI_SCALE, 0) parent.add_child(panel)
var vbox := VBoxContainer.new() panel.add_child(vbox)
var header := Button.new() header.text = "v " + title header.alignment = HORIZONTAL_ALIGNMENT_LEFT header.custom_minimum_size = Vector2(0, TOUCH_MIN * UI_SCALE * 0.8) header.pressed.connect(_toggle_panel.bind(id)) vbox.add_child(header)
var body := MarginContainer.new() body.name = "Body" body.add_child(content) vbox.add_child(body) _panels[id] = panel
func _build_tools_panel() -> Control: var box := VBoxContainer.new() box.add_theme_constant_override("separation", 6) var label := Label.new() label.text = "Brush" box.add_child(label) for b in ["draw", "grab", "pinch", "smooth", "flatten"]: var btn := Button.new() btn.text = b.capitalize() btn.custom_minimum_size = Vector2(0, TOUCH_MIN * UI_SCALE) btn.pressed.connect(_on_brush_selected.bind("sculpt." + b)) box.add_child(btn) box.add_child(_make_slider("Radius", 0.05, 2.0, 0.5, func(v): StudioBus.brush_radius_changed.emit(v))) box.add_child(_make_slider("Strength", 0.05, 1.0, 0.5, func(v): StudioBus.brush_strength_changed.emit(v))) return box
func _build_layers_panel() -> Control: var box := VBoxContainer.new() var label := Label.new() label.text = "Scene objects appear here." box.add_child(label) return box
func _build_timeline_panel() -> Control: var box := VBoxContainer.new() var label := Label.new() label.text = "Keyframe the selected object at the playhead." box.add_child(label) var key_btn := Button.new() key_btn.text = "Add Keyframe" key_btn.custom_minimum_size = Vector2(0, TOUCH_MIN * UI_SCALE) key_btn.pressed.connect(_on_add_keyframe) box.add_child(key_btn) return box
func _make_slider(label_text: String, mn: float, mx: float, val: float, on_change: Callable) -> Control: var wrap := VBoxContainer.new() var l := Label.new() l.text = label_text wrap.add_child(l) var s := HSlider.new() s.min_value = mn s.max_value = mx s.step = 0.01 s.value = val s.custom_minimum_size = Vector2(180 * UI_SCALE, TOUCH_MIN * UI_SCALE) s.value_changed.connect(on_change) wrap.add_child(s) return wrap
func _build_bottom_bar() -> void: var bar := PanelContainer.new() bar.name = "BottomBar" bar.set_anchors_preset(Control.PRESET_BOTTOM_WIDE) bar.custom_minimum_size = Vector2(0, 56 * UI_SCALE) bar.mouse_filter = Control.MOUSE_FILTER_STOP _ui_root.add_child(bar)
var hbox := HBoxContainer.new() hbox.add_theme_constant_override("separation", 10) bar.add_child(hbox)
_play_button = Button.new() _play_button.text = "Play" _play_button.custom_minimum_size = Vector2(84 * UI_SCALE, TOUCH_MIN * UI_SCALE) _play_button.pressed.connect(_on_play_pressed) hbox.add_child(_play_button)
_timeline = HSlider.new() _timeline.min_value = 0.0 _timeline.max_value = 5.0 _timeline.step = 0.01 _timeline.size_flags_horizontal = Control.SIZE_EXPAND_FILL _timeline.custom_minimum_size = Vector2(0, TOUCH_MIN * UI_SCALE) _timeline.value_changed.connect(_on_timeline_scrub) hbox.add_child(_timeline)
_status = Label.new() _status.text = "0.00s" hbox.add_child(_status)
## --- Behaviour --------------------------------------------------------------
func _connect_bus() -> void: StudioBus.timeline_playhead.connect(_on_playhead) StudioBus.playback_state_changed.connect(_on_playback_state) StudioBus.brush_changed.connect(_on_brush_changed) MemoryManager.memory_warning.connect(func(_u, _b): _refresh_hud())
func _process(_delta: float) -> void: _fps_label.text = "FPS %d" % Engine.get_frames_per_second() _refresh_hud()
func _refresh_hud() -> void: var used: float = MemoryManager.get_loaded_mb() _memory_label.text = "MEM %.0f/%.0f MB" % [used, MemoryManager.asset_budget_mb]
func _toggle_panel(id: String) -> void: var panel: PanelContainer = _panels.get(id) if panel == null: return var body := panel.get_node_or_null("VBoxContainer/Body") # PanelContainer -> VBox -> [Button, MarginContainer] var vbox := panel.get_child(0) var body_node := vbox.get_node_or_null("Body") as Control if body_node != null: body_node.visible = not body_node.visible StudioBus.panel_toggled.emit(id, body_node != null and body_node.visible)
func _on_tool_pressed(feature_id: String) -> void: # Turning on a sculpt brush means the finger paints; navigation uses 2 fingers. var is_sculpt := feature_id.begins_with("sculpt.") if _touch_camera != null: _touch_camera.set("one_finger_orbit", not is_sculpt) if is_sculpt: var ok := FeatureRegistry.activate("sculpt.draw") if ok: # Ensure the sculpt module is wired to the selected object. var sculpt: Node = find_sculpt_module() if sculpt != null and StudioBus.has_signal("brush_changed"): StudioBus.brush_changed.emit(feature_id) _activate_feature_family(feature_id) _set_status("Tool: " + feature_id)
func find_sculpt_module() -> Node: var host := get_parent().get_node_or_null("Features") if host == null: return null return host.get_node_or_null("Feature_sculpt.draw")
func _activate_feature_family(feature_id: String) -> void: match feature_id: "mesh.cube": FeatureRegistry.activate("mesh.cube") "rig.skeleton": FeatureRegistry.activate("rig.skeleton") "sim.cloth": FeatureRegistry.activate("sim.cloth") StudioBus.sim_toggled.emit("sim.cloth", true) "anim.timeline": FeatureRegistry.activate("anim.timeline") _: pass
func _on_brush_selected(id: String) -> void: _active_brush = id StudioBus.brush_changed.emit(id) _set_status("Brush: " + id)
func _on_brush_changed(id: String) -> void: _set_status("Brush: " + id)
func _on_play_pressed() -> void: var tl := _get_timeline_module() if tl == null: return if tl.call("is_playing"): tl.call("pause") else: tl.call("play")
func _on_timeline_scrub(value: float) -> void: var tl := _get_timeline_module() if tl != null: tl.call("scrub", value) _status.text = "%.2fs" % value
func _on_playhead(t: float) -> void: _timeline.set_value_no_signal(t) _status.text = "%.2fs" % t
func _on_playback_state(playing: bool) -> void: _play_button.text = "Pause" if playing else "Play"
func _on_add_keyframe() -> void: var tl := _get_timeline_module() if tl == null: FeatureRegistry.activate("anim.timeline") tl = _get_timeline_module() if tl == null: return var selected := _selected_object() if selected != null: tl.call("add_keyframe", selected, "position", _timeline.value, selected.position) _set_status("Keyframe added")
func _get_timeline_module() -> Node: var host := get_parent().get_node_or_null("Features") if host == null: return null return host.get_node_or_null("Feature_anim.timeline")
func _selected_object() -> Node3D: var geom := get_parent().get_node_or_null("Geometry") if geom == null: return null for child in geom.get_children(): if child is MeshInstance3D: return child return null
func _set_status(text: String) -> void: if _status != null: _status.text = text1uid://brs4dwcg1h1qd123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183extends Camera3D#### TouchCamera - lag-free mobile navigation for the 3D viewport (Step 3.1).#### Gesture map (configurable):## one finger drag -> orbit (rotate around the focus point)## two finger pinch -> dolly zoom## two finger drag -> pan (move the focus point in screen space)## three finger drag -> pan (alternative, larger screens)#### Design: raw InputEvent handling (not _input echo), one gesture re-evaluated## per frame, no allocations in the hot path. Values are smoothed with an## exponential filter so motion feels fluid even when touch sampling is jittery.##
@export var orbit_speed: float = 0.4@export var pan_speed: float = 0.6@export var zoom_speed: float = 1.2@export var min_distance: float = 0.5@export var max_distance: float = 200.0@export var smoothing: float = 18.0 # higher = snappier, lower = floatier
var focus: Vector3 = Vector3.ZEROvar _yaw: float = 0.6var _pitch: float = -0.5var _distance: float = 8.0
## When false, a single finger is reserved for sculpting/painting and only## multi-finger gestures navigate. The UI flips this when a sculpt tool is on.var one_finger_orbit: bool = truevar _painting := falsevar _last_paint: Vector2 = Vector2.ZERO
# Smoothed targetsvar _t_yaw: float = 0.6var _t_pitch: float = -0.5var _t_distance: float = 8.0var _t_focus: Vector3 = Vector3.ZERO
# Touch bookkeepingvar _touches: Dictionary = {} # index -> positionvar _prev_centroid: Vector2 = Vector2.ZEROvar _prev_spread: float = 0.0var _gesture_active := false
func _ready() -> void: _t_yaw = _yaw _t_pitch = _pitch _t_distance = _distance _t_focus = focus _apply_transform()
func _input(event: InputEvent) -> void: if event is InputEventScreenTouch: _handle_touch(event) elif event is InputEventScreenDrag: _handle_drag(event)
func _handle_touch(e: InputEventScreenTouch) -> void: if e.pressed: _touches[e.index] = e.position if e.index == 0 and not one_finger_orbit and _touches.size() == 1: _painting = true _last_paint = e.position StudioBus.stroke_begin.emit(_ray_center(e.position)) else: _touches.erase(e.index) if e.index == 0 and _painting: _painting = false StudioBus.stroke_end.emit() if _touches.size() >= 2: _recompute_gesture_baseline()
func _handle_drag(e: InputEventScreenDrag) -> void: _touches[e.index] = e.position if _painting and e.index == 0 and not one_finger_orbit: var world := _ray_center(e.position) var prev_world := _ray_center(_last_paint) StudioBus.stroke_apply.emit(world, world - prev_world) _last_paint = e.position return var n := _touches.size() if n == 1: # Orbit var d := e.relative _t_yaw -= d.x * orbit_speed * 0.01 _t_pitch = clampf(_t_pitch - d.y * orbit_speed * 0.01, -1.5, 1.5) elif n == 2: var pts := _touches.values() var centroid: Vector2 = (pts[0] + pts[1]) * 0.5 var spread: float = (pts[0] as Vector2).distance_to(pts[1] as Vector2) if _prev_spread > 0.0: var dzoom := (spread - _prev_spread) * zoom_speed * 0.01 _t_distance = clampf(_t_distance - dzoom, min_distance, max_distance) var dpan := centroid - _prev_centroid _apply_pan(dpan) _prev_centroid = centroid _prev_spread = spread elif n >= 3: var pts := _touches.values() var centroid := Vector2.ZERO for p in pts: centroid += p centroid /= float(pts.size()) var dpan := centroid - _prev_centroid _apply_pan(dpan) _prev_centroid = centroid
func _recompute_gesture_baseline() -> void: var pts := _touches.values() if pts.size() >= 2: _prev_centroid = (pts[0] + pts[1]) * 0.5 _prev_spread = (pts[0] as Vector2).distance_to(pts[1] as Vector2)
func _apply_pan(screen_delta: Vector2) -> void: # Pan along camera right/up, scaled by distance so it feels consistent at # any zoom level. var scale := _distance * pan_speed * 0.002 var right := global_transform.basis.x var up := global_transform.basis.y _t_focus -= right * screen_delta.x * scale _t_focus += up * screen_delta.y * scale focus = _t_focus
func _process(delta: float) -> void: var t := 1.0 - exp(-smoothing * delta) _yaw = lerpf(_yaw, _t_yaw, t) _pitch = lerpf(_pitch, _t_pitch, t) _distance = lerpf(_distance, _t_distance, t) focus = focus.lerp(_t_focus, t) _apply_transform()
func _apply_transform() -> void: var offset := Vector3( cos(_pitch) * sin(_yaw), sin(_pitch), cos(_pitch) * cos(_yaw) ) * _distance global_position = focus + offset look_at(focus, Vector3.UP)
## --- Public helpers ---------------------------------------------------------
func frame_aabb(box: AABB, margin: float = 1.6) -> void: _t_focus = box.get_center() focus = _t_focus var radius := maxf(0.5, box.size.length() * 0.5) _t_distance = clampf(radius * margin * 2.0, min_distance, max_distance) _distance = _t_distance
func set_focus(p: Vector3) -> void: _t_focus = p focus = p
func screen_to_ray(screen_pos: Vector2) -> Dictionary: return { "origin": project_ray_origin(screen_pos), "dir": project_ray_normal(screen_pos), }
## Ray-cast the viewport at a screen point against physics; returns the world## hit (or a point in front of the camera if nothing is hit).func _ray_center(screen_pos: Vector2) -> Vector3: var origin := project_ray_origin(screen_pos) var dir := project_ray_normal(screen_pos) var space := get_world_3d().direct_space_state var q := PhysicsRayQueryParameters3D.create(origin, origin + dir * 1000.0) var res := space.intersect_ray(q) if not res.is_empty(): return res["position"] return origin + dir * _distance1uid://diopfaymyxcso123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157extends Node#### SelfTest - headless verification of every core subsystem.## Run: godot --headless res://tests/self_test.tscn#### Exits with code 0 if all checks pass, 1 otherwise. This is the regression## gate for the modules; it does not need a display or GPU.##
var _failures := 0var _host: Node3D
func _ready() -> void: _host = Node3D.new() _host.name = "TestHost" var geom := Node3D.new() geom.name = "Geometry" _host.add_child(geom) var rig := Node3D.new() rig.name = "Rig" _host.add_child(rig) add_child(_host)
_test_memory_manager() _test_mesh_generators() _test_sculpt() _test_rigging() _test_simulation() _test_timeline()
print("") if _failures == 0: print("SELFTEST: ALL PASS") get_tree().quit(0) else: print("SELFTEST: %d FAILURE(S)" % _failures) get_tree().quit(1)
func _check(name: String, cond: bool) -> void: if cond: print(" [PASS] ", name) else: _failures += 1 print(" [FAIL] ", name)
func _test_memory_manager() -> void: print("[Test] MemoryManager") _check("budget set", MemoryManager.asset_budget_mb > 0.0) _check("feature count >= 20", FeatureRegistry.feature_count() >= 20) var snap := MemoryManager.debug_snapshot() _check("snapshot has budget", snap.has("budget_mb"))
func _load_module(path: String) -> Node: var script: GDScript = load(path) var n: Node = script.new() _host.add_child(n) if n.has_method("_activate"): n.call("_activate", _host) return n
func _test_mesh_generators() -> void: print("[Test] Mesh generators") var mg := _load_module("res://scripts/modules/mesh_gen.gd") for kind in ["cube", "sphere", "cylinder", "plane", "torus", "ico", "suzanne"]: var data: Dictionary = mg.call("generate", kind, {}) var vcount: int = (data["verts"] as PackedVector3Array).size() var icount: int = (data["indices"] as PackedInt32Array).size() _check("%s has verts & tris (v=%d,i=%d)" % [kind, vcount, icount], vcount > 0 and icount > 0) var mi: MeshInstance3D = mg.call("spawn", "sphere", {"radius": 1.0}) _check("spawn returns MeshInstance3D", mi != null and mi.mesh != null and mi.mesh.get_surface_count() == 1) var cost := VertexBufferManager.estimate_cost_mb(1000) _check("cost estimate > 0", cost > 0.0) mg.queue_free()
func _test_sculpt() -> void: print("[Test] Sculpting") var mg := _load_module("res://scripts/modules/mesh_gen.gd") var sc := _load_module("res://scripts/modules/sculpt.gd") var mi: MeshInstance3D = mg.call("spawn", "sphere", {"radius": 1.0}) sc.call("set_target", mi) var before: PackedVector3Array = (mi.mesh.surface_get_arrays(0)[Mesh.ARRAY_VERTEX] as PackedVector3Array).duplicate() for brush in ["draw", "grab", "pinch", "smooth", "flatten"]: sc.set("_brush_id", brush) sc.call("begin", Vector3(0, 1, 0)) sc.call("apply", Vector3(0, 1, 0), Vector3(0, 0.1, 0)) sc.call("apply", Vector3(0, 1, 0), Vector3(0.05, 0.1, 0)) sc.call("end") var after: PackedVector3Array = mi.mesh.surface_get_arrays(0)[Mesh.ARRAY_VERTEX] var changed := false for i in range(mini(before.size(), after.size())): if before[i].distance_to(after[i]) > 0.0001: changed = true break _check("sculpt modified vertices", changed) _check("mesh still valid after sculpt", mi.mesh.get_surface_count() == 1) mg.queue_free() sc.queue_free()
func _test_rigging() -> void: print("[Test] Rigging") var mg := _load_module("res://scripts/modules/mesh_gen.gd") var rg := _load_module("res://scripts/modules/rigging.gd") var mi: MeshInstance3D = mg.call("spawn", "cube", {"size": 1.0}) rg.call("generate_default_armature", mi) _check("bones created", int(rg.call("bone_count")) >= 9) _check("mesh has skin", mi.skin != null) _check("mesh has skeleton path", mi.skeleton != NodePath()) if mi.mesh.get_surface_count() > 0: var arr: Array = mi.mesh.surface_get_arrays(0) _check("bones channel present", arr[Mesh.ARRAY_BONES] != null) _check("weights channel present", arr[Mesh.ARRAY_WEIGHTS] != null) mg.queue_free() rg.queue_free()
func _test_simulation() -> void: print("[Test] Simulation") var sim := _load_module("res://scripts/modules/simulation.gd") sim.call("create_cloth", "sim.cloth", 6, 6, 1.0) var before: PackedVector3Array = (sim.get("_sims")["sim.cloth"]["particles"] as PackedVector3Array).duplicate() for i in range(30): sim.call("_step", sim.get("_sims")["sim.cloth"]) sim.call("_upload", sim.get("_sims")["sim.cloth"]) var after: PackedVector3Array = sim.get("_sims")["sim.cloth"]["particles"] var moved := false for i in range(after.size()): if before[i].distance_to(after[i]) > 0.0001: moved = true break _check("cloth fell under gravity", moved) var mesh: ArrayMesh = sim.get("_sims")["sim.cloth"]["mesh"] _check("cloth mesh uploaded", mesh.get_surface_count() == 1) sim.call("create_hair", "sim.hair", 4, 5) _check("hair sim created", int(sim.call("active_sim_count")) >= 2) sim.queue_free()
func _test_timeline() -> void: print("[Test] Timeline") var mg := _load_module("res://scripts/modules/mesh_gen.gd") var tl := _load_module("res://scripts/modules/timeline.gd") var mi: MeshInstance3D = mg.call("spawn", "cube", {"size": 1.0}) tl.call("add_keyframe", mi, "position", 0.0, Vector3.ZERO) tl.call("add_keyframe", mi, "position", 1.0, Vector3(0, 2, 0)) _check("track created", int(tl.call("track_count")) >= 1) _check("key count == 2", int(tl.call("key_count")) == 2) tl.call("scrub", 0.5) _check("scrub clamps/works", absf(float(tl.call("playhead")) - 0.5) < 0.001) mg.queue_free() tl.queue_free()1uid://b0chtaj3gt8qr123456[gd_scene load_steps=2 format=3]
[ext_resource type="Script" path="res://tests/self_test.gd" id="1_test"]
[node name="SelfTest" type="Node"]script = ExtResource("1_test").gitattributes+2
LICENSEAdded+21
README.mdAdded+226
build/MonkeyStudio.apkAdded+3
build/MonkeyStudio.apk.idsigAdded+3
docs/ARCHITECTURE.mdAdded+142
docs/BUILD_ANDROID.mdAdded+279
export_presets.cfgAdded+66
project.godotAdded+61
scenes/main.tscnAdded+6
scripts/core/feature_registry.gdAdded+135
scripts/core/feature_registry.gd.uidAdded+1
scripts/core/memory_manager.gdAdded+182
scripts/core/memory_manager.gd.uidAdded+1
scripts/core/mesh_pool.gdAdded+65
scripts/core/mesh_pool.gd.uidAdded+1
scripts/core/studio_bus.gdAdded+54
scripts/core/studio_bus.gd.uidAdded+1
scripts/core/vertex_buffer_manager.gdAdded+114
scripts/core/vertex_buffer_manager.gd.uidAdded+1
scripts/install_godot.shAdded+51
scripts/modules/mesh_gen.gdAdded+282
scripts/modules/mesh_gen.gd.uidAdded+1
scripts/modules/rigging.gdAdded+174
scripts/modules/rigging.gd.uidAdded+1
scripts/modules/sculpt.gdAdded+238
scripts/modules/sculpt.gd.uidAdded+1
scripts/modules/simulation.gdAdded+304
scripts/modules/simulation.gd.uidAdded+1
scripts/modules/timeline.gdAdded+174
scripts/modules/timeline.gd.uidAdded+1
scripts/studio/studio_main.gdAdded+140
scripts/studio/studio_main.gd.uidAdded+1
scripts/studio/studio_ui.gdAdded+418
scripts/studio/studio_ui.gd.uidAdded+1
scripts/studio/touch_camera.gdAdded+183
scripts/studio/touch_camera.gd.uidAdded+1
tests/self_test.gdAdded+157
tests/self_test.gd.uidAdded+1
tests/self_test.tscnAdded+6