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

python/3d/demo_3d.py · 3321 字节 · 下载原文

# demo_3d.py —— 第 5 层:**3D 视口**(`ui_3d_*`,独立库 vml3d)
# demo_3d.py — Layer 5: **3D viewport** (`ui_3d_*`, the separate vml3d library)
#
# 这一层画在 2D 画布之上:视口自带相机 / 视场角 / 背景色 / 一盏方向光,
# 模型从同目录的 `box.glb`(CC0,glTF 2.0)装载;2D 那层只负责清屏。
# This layer draws on top of the 2D canvas: the viewport owns a camera, field of view,
# background colour and one directional light; the model comes from `box.glb` (CC0,
# glTF 2.0) next to this file, while the 2D layer only clears the canvas.
#
# 跑法 / How to run:
#   手机  vml run examples/python/3d/demo_3d.py
#   桌面  vmlcli Examples/python/3d/demo_3d.py --screen 640x480 --frames /tmp/f3d
#
# ⚠ 两条实测要求 / Two measured requirements:
#   ① 3D 是**透过** 2D 层显示的 ⇒ 必须 `ui_2d_clear(0)`;不透明底会把 3D 整片盖住。
#      The 3D output shows **through** the 2D layer, so `ui_2d_clear(0)` is mandatory;
#      an opaque 2D background would cover the whole 3D image.
#   ② `box.glb` 用**相对路径**——宿主沙箱根就是源文件所在目录。
#      `box.glb` uses a **relative** path: the host sandbox root is the source-file directory.
import vml_ui
import vml3d

FRAMES = 20                 # 20 帧 × 40ms ≈ 0.8 秒 / 20 frames x 40ms ~ 0.8s

# ① 开窗:宽高传 0 = 交给宿主用真实可用区(开窗前问尺寸只是估算)
# ① Open the window: size 0 = the host picks the real usable area (querying before the open is only an estimate)
ui_win_open_ex("demo_3d (Python)", 0, 0, 0, 0)
w = ui_scr_get_w()
h = ui_scr_get_h()

# ② 建视口:整块画布一个,flags = 0(默认)
# ② Create the viewport: one for the whole canvas, flags = 0 (default)
vp = ui_3d_viewport_create(0, 0, w, h, 0)

# 相机:眼睛在 (0, 1.5, 4),看向原点 —— 立方体正好落在画面中间
# Camera: eye at (0, 1.5, 4) looking at the origin, so the cube sits mid-screen
ui_3d_viewport_set_camera(vp, 0.0, 1.5, 4.0, 0.0, 0.0, 0.0)
# 视场角 50°、近裁剪 0.1、远裁剪 100 / FOV 50 deg, near 0.1, far 100
ui_3d_viewport_set_fov(vp, 50.0, 0.1, 100.0)
# 背景 0xFF14202F;灯光方向 (0.4, 0.9, 0.6)、白色、环境光 0.3
# Background 0xFF14202F; light direction (0.4, 0.9, 0.6), white, ambient 0.3
ui_3d_viewport_set_bg(vp, 0xFF14202F)
ui_3d_viewport_set_light(vp, 0.4, 0.9, 0.6, 0xFFFFFFFF, 0.3)

# ③ 2D 层清成**透明**(0 = 全透明)——3D 从这里透出来
# ③ Clear the 2D layer to **transparent** (0 = fully transparent) so the 3D shows through
ui_2d_clear(0)

# ④ 装载 glTF/GLB:返回场景句柄(>0 成功,<0 是错误码)
# ④ Load the glTF/GLB: returns a scene handle (>0 on success, <0 is an error code)
scene = ui_3d_gltf_load(vp, "box.glb")

# ⑤ 有界渲染循环:交帧 + 等一条消息(40ms 让宿主合成一帧)
# ⑤ Bounded render loop: present + wait for a message (40ms lets the host composite one frame)
i = 0
while i < FRAMES:
    ui_2d_present()
    ui_msg_fetch_wait(40)
    i = i + 1

# ⑥ 收尾:先释放场景与视口,再关窗
# ⑥ Wrap-up: free the scene and the viewport first, then close the window
ui_3d_gltf_free(scene)
ui_3d_viewport_free(vp)
ui_win_close()
print("demo_3d done (Python)")