← 都来码 / Dolaima← 例程索引cpp/3d/demo_3d.cpp 原文

cpp/3d/demo_3d.cpp · 3201 字节 · 下载原文

// demo_3d.cpp —— 3D 视口 + GLB 模型最小示例(C++)
// demo_3d.cpp — minimal 3D viewport + GLB model demo (C++)
//
// 流程:开窗 → 取画布尺寸 → 建 3D 视口 → 设相机/视场/背景/光 → 载入 box.glb
// Flow: open window → query canvas size → create a 3D viewport → camera/FOV/background/light → load box.glb
//       → 呈现 20 帧 → 释放视口、关窗。
//       → present 20 frames → free the viewport, close the window.
//
// 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.
//
// 跑法 / How to run:
//   dotnet scripts/vmlcli/bin/Release/net10.0/vmlcli.dll Examples/cpp/3d/demo_3d.cpp --frames /tmp/fr
// ⚠ 看画面请用 --frames <目录>,不要用 --frame:ui_win_close() 之后宿主场景已被置空。
// ⚠ Use --frames <dir>, not --frame: ui_win_close() empties the host scene.

#include <vml_ui.h>
#include <vml_3d.h>

int main()
{
    int w;
    int h;
    int vp;
    int i;

    // ── 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 ──
    w = ui_scr_get_w();
    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, no silent black screen) ──
    vp = ui_3d_viewport_create(0, 0, w, h, 0);
    if (vp <= 0) {
        ui_win_close();
        return 0;
    }

    // ── 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 / deep blue-grey
    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, waiting for the next display tick each time ──
    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();
    return 0;
}