! demo_3d.f90 —— Fortran 3D 层：**加载 glTF 立方体并画 20 帧**
! demo_3d.f90 -- Fortran 3D layer: **load a glTF cube and draw 20 frames**
!
! 跑法（桌面 vmlcli）：
! How to run (desktop vmlcli):
!   dotnet scripts/vmlcli/bin/Release/net10.0/vmlcli.dll Examples/fortran/3d/demo_3d.f90
! 同目录的 box.glb 是 CC0 立方体（复制自 Examples/c/3d/models/BoxVertexColors.glb）。
! box.glb next to this file is a CC0 cube (copied from Examples/c/3d/models/BoxVertexColors.glb).
!
! 本前端的写法要求（与 demo_ui.f90 同一套）：
! Coding rules of this frontend (same as demo_ui.f90):
!   ① 库调用写成**函数调用表达式** `k = ui_3d_...(...)`；写成 `call ui_...` 会被编成 `sub_` 前缀，
!   ① write library calls as **function-call expressions** k = ui_3d_...(...); `call ui_...` becomes sub_...
!      而链接器只剥 `func_`/`word_`/`method_`/`var_` 四种前缀 ⇒ 够不到库。
!      and the linker strips only func_/word_/method_/var_ prefixes => it never reaches the library.
!   ② 一个子程序都不要（本子集的内部子程序收不到实参），全部内联。
!   ② no subroutines at all (contained subroutines cannot receive arguments here); everything is inline.
!   ③ 颜色用十进制负数（0xAARRGGBB 作为 32 位有符号整数会溢出），后面标了十六进制。
!   ③ colours are negative decimals (0xAARRGGBB overflows as signed 32-bit); the hex is noted alongside.
!   ④ 3D 的几何量是 float —— 直接写 `0.0` / `1.5` 即可（本前端把浮点实参按 4 字节压栈）。
!   ④ 3D geometry is float -- write 0.0 / 1.5 directly (this frontend pushes float args as 4 bytes).

program demo_3d
  implicit none
  integer :: w, h, vp, sc, k, i

  ! ① 开窗：尺寸传 0 ⇒ 宿主用真实可用区
  ! 1) Open the window: pass size 0 => the host uses the real available area
  k = ui_win_open_ex('demo_3d', 0, 0, 0, 0)

  ! ② 尺寸必须开窗之后问（开窗前只能估算）
  ! 2) Ask for the size after opening (before that it is only an estimate)
  w = ui_scr_get_w()
  h = ui_scr_get_h()

  ! ③ 建视口 + 相机 / 视野 / 背景 / 光
  ! 3) Create the viewport plus camera / fov / background / light
  vp = ui_3d_viewport_create(0, 0, w, h, 0)
  k = ui_3d_viewport_set_camera(vp, 0.0, 1.5, 4.0, 0.0, 0.0, 0.0)
  k = ui_3d_viewport_set_fov(vp, 50.0, 0.1, 100.0)
  k = ui_3d_viewport_set_bg(vp, -15458257)                 ! 0xFF14202F
  k = ui_3d_viewport_set_light(vp, 0.4, 0.9, 0.6, -1, 0.3) ! 光色 0xFFFFFFFF

  ! ④ 2D 层清成透明 —— 3D 视口是透过 2D 层看的
  ! 4) Clear the 2D layer to transparent -- the 3D viewport shows through it
  k = ui_2d_clear(0)

  ! ⑤ 载入同目录的立方体
  ! 5) Load the cube sitting next to this file
  sc = ui_3d_gltf_load(vp, 'box.glb')

  ! ⑥ 画 20 帧（每帧一次 present，再等最多 40ms）
  ! 6) Draw 20 frames (one present per frame, then wait up to 40 ms)
  do i = 1, 20
    k = ui_2d_present()
    k = ui_msg_fetch_wait(40)
  end do

  ! ⑦ 关窗
  ! 7) Close the window
  k = ui_win_close()
  print *, 'Fortran 3D demo: done'
end program demo_3d
