kotlin/3d/demo_3d.kt · 3807 字节 · 下载原文
// demo_3d.kt —— **3D 视口 + GLB 模型最小示例**(Kotlin)
// demo_3d.kt — **minimal 3D viewport + GLB model demo** (Kotlin)
//
// 流程:开窗 → 取画布尺寸 → 建 3D 视口 → 设相机 / 视场 / 背景 / 一盏平行光
// → 清屏 → 装载同目录的 box.glb → 有界呈现 20 帧 → 释放视口并关窗。
// Flow: open window → query the canvas size → create a 3D viewport → camera / FOV / background / one light
// → clear → load box.glb from this directory → present 20 frames → free the viewport and close.
//
// box.glb 与 `Examples/c/3d/models/BoxVertexColors.glb` 是同一份文件(Khronos,CC0)。
// box.glb is the same file as `Examples/c/3d/models/BoxVertexColors.glb` (Khronos, CC0).
// 它必须和本文件放在同一目录:桌面 vmlcli 的文件沙箱根是源文件所在目录。
// It must sit next to this file: the desktop vmlcli file sandbox is rooted at the source file's directory.
//
// 声明来自两行 include(`Lib/kotlin/vml_ui.kt` 与 `Lib/kotlin/vml3d.kt`,均由 GenLib 生成)。
// 两个文件都写着 `package vmlui`,本前端的预处理器接受这种重复(实测编译通过)。
// Declarations come from the two includes (`Lib/kotlin/vml_ui.kt` and `Lib/kotlin/vml3d.kt`,
// both generated by GenLib). Both files carry `package vmlui`; this frontend's preprocessor
// accepts the duplicate (verified: it compiles).
//
// 跑法:手机 `vml run examples/kotlin/3d/demo_3d.kt`;
// 桌面 `dotnet scripts/vmlcli/bin/Release/net10.0/vmlcli.dll Examples/kotlin/3d/demo_3d.kt --frames /tmp/fr`
// How to run: on the phone `vml run examples/kotlin/3d/demo_3d.kt`;
// on the desktop `dotnet scripts/vmlcli/bin/Release/net10.0/vmlcli.dll Examples/kotlin/3d/demo_3d.kt --frames /tmp/fr`
// ⚠ 看画面请用 `--frames <目录>`,不要用 `--frame`:`ui_win_close()` 之后宿主场景已被置空。
// ⚠ Use `--frames <dir>`, not `--frame`: `ui_win_close()` empties the host scene.
#include <vml_ui.kt>
#include <vml3d.kt>
import vmlui.*
fun main() {
// ── 1. 开窗(宽高传 0 ⇒ 宿主用真实可用区)──
// ── 1. Open the window (size 0 ⇒ the host uses the real available area) ──
ui_win_open_ex("demo_3d", 0, 0, 0, 0)
// ── 2. 开窗之后再问尺寸,那时才是真实画布 ──
// ── 2. Query the size after the open, when it is the real canvas ──
var w = ui_scr_get_w()
var h = ui_scr_get_h()
if (w <= 0) { w = 640 }
if (h <= 0) { h = 640 }
// ── 3. 建 3D 视口(失败只关窗返回)──
// ── 3. Create the 3D viewport (on failure just close and return) ──
var vp = ui_3d_viewport_create(0, 0, w, h, 0)
if (vp <= 0) { ui_win_close(); return }
// ── 4. 相机 / 视场 / 背景 / 一盏平行光 ──
// ── 4. Camera / FOV / background / one directional light ──
ui_3d_viewport_set_camera(vp, 0.0f, 1.5f, 4.0f, 0.0f, 0.0f, 0.0f)
ui_3d_viewport_set_fov(vp, 50.0f, 0.1f, 100.0f)
ui_3d_viewport_set_bg(vp, -15458257) // 0xFF14202F
ui_3d_viewport_set_light(vp, 0.4f, 0.9f, 0.6f, -1, 0.3f) // argb -1 = 0xFFFFFFFF
// ── 5. 清屏并装载模型 ──
// ── 5. Clear the canvas and load the model ──
ui_2d_clear(0)
ui_3d_gltf_load(vp, "box.glb")
// ── 6. 有界呈现:20 帧 ──
// ── 6. Bounded presentation: 20 frames ──
var i = 0
while (i < 20) {
ui_2d_present()
ui_msg_fetch_wait(40)
i = i + 1
}
// ── 7. 收尾:先释放视口,再关窗 ──
// ── 7. Clean up: free the viewport first, then close the window ──
ui_3d_viewport_free(vp)
ui_win_close()
}