model.rasm

includes/learn/model.rasm · 598 lines

; model: loading models from Wavefront .obj files
;
; What Assimp and LearnOpenGL's Model and Mesh classes are to LearnOpenGL. Only
; the part of the format the lessons' models use:
;
;   v  x y z        a position
;   vt u v          a texture coordinate
;   vn x y z        a normal
;   f  a/b/c ...    a face: position/uv/normal indices, counted from 1
;   mtllib x.mtl    the material file, which names the textures
;
; Faces with more than three corners are split into a fan. Every corner
; becomes its own vertex, so nothing is shared between triangles; that costs
; memory, not correctness.
;
; OBJ's v normally runs up the image and D3D's runs down, so v usually needs
; flipping. Whether it does depends on how the model's textures were saved:
; the backpack's already suit top-down v. Hence `flip_v`, chosen per model.
;
;     invoke(model_load, backpack&, "resources/objects/backpack/", "backpack.obj", 0)
;     invoke(shader_create, s&, "src/.../x.hlsl", model_layout&, MODEL_LAYOUT_COUNT)
;     ...
;     invoke(model_draw, backpack&)
;
; model_draw binds the textures to fixed slots: diffuse t0, specular t1,
; normal t2. Everything read (the .obj's text, the arrays, the vertices) is
; pushed onto `arena` and kept.

import "../d3d11.rin"
import "../calls.rasm"
import "../macros.rasm"
import "../math.rasm"
import "../cstr.rasm"
import "../print.rasm"
import "../saha.rasm"
import "window.rasm"
import "filesystem.rasm"
import "gpu.rasm"

#define MODEL_LAYOUT_COUNT 3

model_vertex: struct = {
    position: vec3
    normal: vec3
    uv: vec2
}

model: struct = {
    vertices: *ID3D11Buffer                ; of model_vertex
    vertex_count: u32
    pad: u32
    diffuse: *ID3D11ShaderResourceView     ; map_Kd
    specular: *ID3D11ShaderResourceView    ; map_Ks
    normal: *ID3D11ShaderResourceView      ; map_Bump
}

; One `a/b/c` corner of a face. Missing parts (`a//c`, `a/b`, `a`) are 0.
obj_corner: struct = {
    position: u32
    uv: u32
    normal: u32
}

model_layout: [MODEL_LAYOUT_COUNT]const D3D11_INPUT_ELEMENT_DESC = {
    { .SemanticName = "POSITION", .Format = DXGI_FORMAT.DXGI_FORMAT_R32G32B32_FLOAT, .AlignedByteOffset = 0 },
    { .SemanticName = "NORMAL", .Format = DXGI_FORMAT.DXGI_FORMAT_R32G32B32_FLOAT, .AlignedByteOffset = 12 },
    { .SemanticName = "TEXCOORD", .Format = DXGI_FORMAT.DXGI_FORMAT_R32G32_FLOAT, .AlignedByteOffset = 24 },
}

; reading text ------------------------------------------------------------------
;
; rcx is the cursor going in, rax the cursor coming out. These are leaves of
; this file that touch neither the stack nor aligned memory, so the procs
; below call them without lining rsp up first.

; rcx: cursor -> rax: past spaces and tabs (touching only rax and r9: callers
; keep pointers in rdx)
obj_skip_spaces: proc(cursor: *const c8) -> *const c8 = {
    mov rax, rcx
  skip:
    mov r9b, [rax]
    cmp r9b, ' '
    je next
    cmp r9b, 9
    jne done
  next:
    inc rax
    jmp skip
  done:
    ret
}

; rcx: cursor -> rax: the start of the next line
obj_next_line: proc(cursor: *const c8) -> *const c8 = {
    mov rax, rcx
  scan:
    mov r9b, [rax]
    test r9b, r9b
    jz done
    inc rax
    cmp r9b, 10
    jne scan
  done:
    ret
}

; rcx: cursor, rdx: keyword -> eax: 1 when the line starts with the keyword
; and a space or tab
obj_starts: proc(cursor: *const c8, keyword: *const c8) -> b32 = {
  compare:
    mov al, [rdx]
    test al, al
    jz word_ended
    cmp al, [rcx]
    jne no
    inc rcx
    inc rdx
    jmp compare
  word_ended:
    mov al, [rcx]
    cmp al, ' '
    je yes
    cmp al, 9
    je yes
  no:
    xor eax, eax
    ret
  yes:
    mov eax, 1
    ret
}

; rcx: cursor, rdx: where to write the word (128 bytes at most) -> rax: the
; cursor after it
obj_word: proc(cursor: *const c8, out: *c8) -> *const c8 = {
    call obj_skip_spaces                   ; a leaf of this file, which leaves rdx alone
    mov r8d, 127
  copy:
    mov cl, [rax]
    test cl, cl
    jz done
    cmp cl, 10
    je done
    cmp cl, 13
    je done
    cmp cl, ' '
    je done
    cmp cl, 9
    je done
    mov [rdx], cl
    inc rax
    inc rdx
    dec r8d
    jnz copy
  done:
    mov byte ptr [rdx], 0
    ret
}

; rcx: cursor -> eax: 1 if a face corner (a number) comes next, rdx: the
; cursor at it
obj_at_corner: proc(cursor: *const c8) -> b32 = {
    call obj_skip_spaces                   ; a leaf of this file
    mov rdx, rax
    movzx ecx, byte ptr [rax]
    xor eax, eax
    cmp ecx, '-'
    je yes
    sub ecx, '0'
    cmp ecx, 9
    ja no
  yes:
    mov eax, 1
  no:
    ret
}

; rcx: cursor at a corner, rdx: obj_corner -> rax: the cursor after it
;
; parse_int returns the cursor past the number in rdx, which is where the
; next `/` is looked for.
obj_read_corner: proc(cursor: *const c8, corner: *obj_corner) -> *const c8 = {
    push rbx
    sub rsp, 32                            ; 32 shadow; entry 8 + push 8 + 32 lands on 16
    mov rbx, rdx                           ; the corner
    mov qword ptr [rbx], 0                 ; position and uv
    mov [rbx].obj_corner.normal, 0
    call parse_int                         ; rcx is the cursor already
    mov [rbx].obj_corner.position, eax
    cmp byte ptr [rdx], '/'
    jne done
    inc rdx
    cmp byte ptr [rdx], '/'
    je no_uv                               ; `a//c`
    mov rcx, rdx
    call parse_int
    mov [rbx].obj_corner.uv, eax
  no_uv:
    cmp byte ptr [rdx], '/'
    jne done
    inc rdx
    mov rcx, rdx
    call parse_int
    mov [rbx].obj_corner.normal, eax
  done:
    mov rax, rdx
    add rsp, 32
    pop rbx
    ret
}

; rcx: cursor -> xmm0: the float after any spaces, rax: the cursor after it
obj_float: proc(cursor: *const c8) -> f32 = {
    call obj_skip_spaces                   ; a leaf of this file
    mov rcx, rax
    jmp parse_float                        ; a tail call: parse_float returns to our caller
}

; materials ---------------------------------------------------------------------

; obj_load_material's: MASM's locals
obj_load_material_path: [260]c8 = {}
obj_load_material_word: [128]c8 = {}

; rcx: the model's directory (full path, ending in a slash), rdx: the .mtl's
; name, r8: model. Reads the .mtl and loads the textures it names.
obj_load_material: proc(dir: *const c8, mtl_name: *const c8, out: *model) = {
    push rbx
    push rsi
    push rdi
    push r12
    sub rsp, 40                            ; 32 shadow; entry 8 + four pushes 32 + 40 lands on 16
    mov rbx, rcx                           ; dir
    mov rdi, r8                            ; the model
    mov rsi, rdx                           ; the .mtl's name, until the text is read
    invoke(cstr_copy, obj_load_material_path&, rbx)
    invoke(cstr_append, obj_load_material_path&, rsi)
    invoke(filesystem_read, obj_load_material_path&, 0)
    test rax, rax
    jz done
    mov rsi, rax                           ; the cursor
  lines:
    cmp byte ptr [rsi], 0
    je done
    mov rcx, rsi
    call obj_skip_spaces
    mov rsi, rax
    ; r12: where in the model the texture goes, 0 for a line that names none
    xor r12d, r12d
    invoke(obj_starts, rsi, "map_Kd")
    test eax, eax
    jz not_diffuse
    mov r12d, offsetof(model.diffuse)
  not_diffuse:
    invoke(obj_starts, rsi, "map_Ks")
    test eax, eax
    jz not_specular
    mov r12d, offsetof(model.specular)
  not_specular:
    invoke(obj_starts, rsi, "map_Bump")
    test eax, eax
    jz not_normal
    mov r12d, offsetof(model.normal)
  not_normal:
    test r12d, r12d
    jz next_line
    ; the keyword, then the file name
    lea rdx, obj_load_material_word
    mov rcx, rsi
    call obj_word
    lea rdx, obj_load_material_word
    mov rcx, rax
    call obj_word
    mov rsi, rax
    invoke(cstr_copy, obj_load_material_path&, rbx)
    invoke(cstr_append, obj_load_material_path&, obj_load_material_word&)
    ; Colours are drawn as stored, as LearnOpenGL's model loader does; the
    ; normal map is data either way.
    invoke(load_texture, obj_load_material_path&, 0)
    mov [rdi + r12], rax
  next_line:
    mov rcx, rsi
    call obj_next_line
    mov rsi, rax
    jmp lines
  done:
    add rsp, 40
    pop r12
    pop rdi
    pop rsi
    pop rbx
    ret
}

; models ------------------------------------------------------------------------

; model_load's: MASM's locals
model_load_out: *model = {}
model_load_flip_v: u32 = 0
model_load_dir: *c8 = {}                   ; the model's directory, a full path
model_load_path: [260]c8 = {}
model_load_word: [128]c8 = {}
; what the first pass counted, kept for the debugger
model_load_positions: u64 = 0
model_load_uvs: u64 = 0
model_load_normals: u64 = 0
model_load_corners: u64 = 0
; the arrays, each with the "missing" entry 0 first
model_load_p: *vec3 = {}
model_load_t: *vec2 = {}
model_load_n: *vec3 = {}
model_load_vertices: *model_vertex = {}
; the corners of the face being read: its first, the one before, this one
model_load_first: obj_corner = {}
model_load_previous: obj_corner = {}
model_load_corner: obj_corner = {}

; One corner of a face, written as the vertex at r15: what its three indices
; point at, in model_load_p, model_load_n and model_load_t. c is an
; obj_corner global. Through rax, rcx and xmm0.
fan_vertex: macro(c) = {
    mov eax, c.position
    lea rax, [rax + rax * 2]               ; 12 bytes a vec3: index * 3 * 4
    mov rcx, model_load_p
    lea rcx, [rcx + rax * 4]
    v3load(xmm0, rcx)
    v3store(r15, xmm0)                     ; .position is at 0
    mov eax, c.normal
    lea rax, [rax + rax * 2]
    mov rcx, model_load_n
    lea rcx, [rcx + rax * 4]
    v3load(xmm0, rcx)
    lea rax, [r15].model_vertex.normal
    v3store(rax, xmm0)
    mov eax, c.uv
    mov rcx, model_load_t
    mov rax, [rcx + rax * 8]               ; both floats of the vec2 at once
    mov qword ptr [r15].model_vertex.uv, rax
    add r15, sizeof(model_vertex)
}

; rcx: model, rdx: directory relative to the repository root (ending in a
; slash), r8: the .obj inside it, r9d: 1 to flip v
model_load: proc(out: *model, relative_dir: *const c8, file: *const c8, flip_v: u32) = {
    push rbx
    push rsi
    push rdi
    push r12
    push r13
    push r14
    push r15
    sub rsp, 32                            ; 32 shadow; entry 8 + seven pushes 56 + 32 lands on 16
    mov model_load_out, rcx
    mov model_load_flip_v, r9d
    mov rsi, rdx                           ; the directory
    mov rdi, r8                            ; the file

    invoke(mem_zero, model_load_out, sizeof(model))
    invoke(filesystem_path, rsi)
    mov model_load_dir, rax
    invoke(cstr_copy, model_load_path&, model_load_dir)
    invoke(cstr_append, model_load_path&, rdi)
    invoke(filesystem_read, model_load_path&, 0)
    test rax, rax
    jnz have_text
    invoke(print, "model: cannot read %s\n", model_load_path&)
    invoke(ExitProcess, 1)
  have_text:
    mov rbx, rax                           ; the text, kept for the second pass

    ; First pass: count, so every array is allocated once at its final size.
    xor r12, r12                           ; positions
    xor r13, r13                           ; uvs
    xor r14, r14                           ; normals
    xor r15, r15                           ; corners
    mov rsi, rbx
  count_lines:
    cmp byte ptr [rsi], 0
    je counted
    invoke(obj_starts, rsi, "v")
    add r12, rax
    invoke(obj_starts, rsi, "vt")
    add r13, rax
    invoke(obj_starts, rsi, "vn")
    add r14, rax
    invoke(obj_starts, rsi, "f")
    test eax, eax
    jz count_next
    inc rsi
    xor edi, edi                           ; corners on this face
  count_corners:
    mov rcx, rsi
    call obj_at_corner
    mov rsi, rdx
    test eax, eax
    jz corners_counted
    invoke(obj_read_corner, rsi, model_load_corner&)
    mov rsi, rax
    inc edi
    jmp count_corners
  corners_counted:
    cmp edi, 3
    jb count_next
    lea rax, [rdi - 2]
    lea rax, [rax + rax * 2]               ; (n - 2) * 3
    add r15, rax
  count_next:
    mov rcx, rsi
    call obj_next_line
    mov rsi, rax
    jmp count_lines
  counted:
    mov model_load_positions, r12
    mov model_load_uvs, r13
    mov model_load_normals, r14
    mov model_load_corners, r15

    ; Index 0 is the "missing" entry, so 1-based indices need no adjusting.
    lea rax, [r12 + 1]
    arenaPushArrayZero(arena&, vec3, rax, 16)
    mov model_load_p, rax
    lea rax, [r13 + 1]
    arenaPushArrayZero(arena&, vec2, rax, 16)
    mov model_load_t, rax
    lea rax, [r14 + 1]
    arenaPushArrayZero(arena&, vec3, rax, 16)
    mov model_load_n, rax
    mov [rax].vec3.y, 0x3F800000           ; the missing normal is up: 1.0
    arenaPushArray(arena&, model_vertex, r15, 16)
    mov model_load_vertices, rax

    ; Second pass: fill them in.
    mov r12, model_load_p
    add r12, sizeof(vec3)                  ; next position
    mov r13, model_load_t
    add r13, sizeof(vec2)                  ; next uv
    mov r14, model_load_n
    add r14, sizeof(vec3)                  ; next normal
    mov r15, model_load_vertices           ; next vertex
    mov rsi, rbx
  lines:
    cmp byte ptr [rsi], 0
    je read
    invoke(obj_starts, rsi, "v")
    test eax, eax
    jz not_position
    lea rcx, [rsi + 1]
    call obj_float
    movss [r12].vec3.x, xmm0
    mov rcx, rax
    call obj_float
    movss [r12].vec3.y, xmm0
    mov rcx, rax
    call obj_float
    movss [r12].vec3.z, xmm0
    mov rsi, rax
    add r12, sizeof(vec3)
    jmp next_line
  not_position:
    invoke(obj_starts, rsi, "vt")
    test eax, eax
    jz not_uv
    lea rcx, [rsi + 2]
    call obj_float
    movss [r13].vec2.x, xmm0
    mov rcx, rax
    call obj_float
    mov rsi, rax
    cmp model_load_flip_v, 0
    je no_flip
    movss xmm1, 1.0
    subss xmm1, xmm0
    movss xmm0, xmm1                       ; v = 1 - v
  no_flip:
    movss [r13].vec2.y, xmm0
    add r13, sizeof(vec2)
    jmp next_line
  not_uv:
    invoke(obj_starts, rsi, "vn")
    test eax, eax
    jz not_normal
    lea rcx, [rsi + 2]
    call obj_float
    movss [r14].vec3.x, xmm0
    mov rcx, rax
    call obj_float
    movss [r14].vec3.y, xmm0
    mov rcx, rax
    call obj_float
    movss [r14].vec3.z, xmm0
    mov rsi, rax
    add r14, sizeof(vec3)
    jmp next_line
  not_normal:
    invoke(obj_starts, rsi, "f")
    test eax, eax
    jz not_face
    inc rsi
    xor edi, edi                           ; corners of this face read so far
  face_corners:
    mov rcx, rsi
    call obj_at_corner
    mov rsi, rdx
    test eax, eax
    jz next_line
    invoke(obj_read_corner, rsi, model_load_corner&)
    mov rsi, rax
    test edi, edi
    jnz not_first
    invoke(mem_copy, model_load_first&, model_load_corner&, sizeof(obj_corner))
  not_first:
    cmp edi, 2
    jb fan_later
    ; a triangle of the fan: the first corner, the previous one and this one
    fan_vertex(model_load_first)
    fan_vertex(model_load_previous)
    fan_vertex(model_load_corner)
  fan_later:
    invoke(mem_copy, model_load_previous&, model_load_corner&, sizeof(obj_corner))
    inc edi
    jmp face_corners
  not_face:
    invoke(obj_starts, rsi, "mtllib")
    test eax, eax
    jz next_line
    lea rdx, model_load_word
    mov rcx, rsi
    call obj_word
    lea rdx, model_load_word
    mov rcx, rax
    call obj_word
    mov rsi, rax
    invoke(obj_load_material, model_load_dir, model_load_word&, model_load_out)
  next_line:
    mov rcx, rsi
    call obj_next_line
    mov rsi, rax
    jmp lines

  read:
    ; one immutable vertex buffer
    mov r12, r15
    sub r12, model_load_vertices           ; bytes
    mov rax, r12
    xor edx, edx
    mov ecx, sizeof(model_vertex)
    div rcx
    mov rbx, model_load_out
    mov [rbx].model.vertex_count, eax
    invoke(create_buffer, D3D11_BIND_FLAG.D3D11_BIND_VERTEX_BUFFER, model_load_vertices, r12)
    mov [rbx].model.vertices, rax

    add rsp, 32
    pop r15
    pop r14
    pop r13
    pop r12
    pop rdi
    pop rsi
    pop rbx
    ret
}

; model_draw_instanced's: the arrays the Set calls take
model_draw_stride: u32 = sizeof(model_vertex)
model_draw_offset: u32 = 0
model_draw_views: [3]*ID3D11ShaderResourceView = {}

; rcx: model, edx: how many instances
model_draw_instanced: proc(m: *const model, instances: u32) = {
    push rbx
    push rsi
    sub rsp, 56                            ; IASetVertexBuffers: 5 past `this`, 2 on the stack: 32 + 16; entry 8 + 16 + 56 lands on 16
    mov rbx, rcx                           ; the model
    mov esi, edx                           ; instances
    mov rax, [rbx].model.diffuse
    mov model_draw_views[0], rax
    mov rax, [rbx].model.specular
    mov model_draw_views[1], rax
    mov rax, [rbx].model.normal
    mov model_draw_views[2], rax
    vcall(context, ID3D11DeviceContextVtbl.PSSetShaderResources, 0, 3, model_draw_views&)
    vcall(context, ID3D11DeviceContextVtbl.IASetPrimitiveTopology, D3D11_PRIMITIVE_TOPOLOGY.D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST)
    lea rax, [rbx].model.vertices
    vcall(context, ID3D11DeviceContextVtbl.IASetVertexBuffers, 0, 1, rax, model_draw_stride&, model_draw_offset&)
    mov edx, [rbx].model.vertex_count      ; a u32: into its argument register first
    vcall(context, ID3D11DeviceContextVtbl.DrawInstanced, rdx, rsi, 0, 0)
    add rsp, 56
    pop rsi
    pop rbx
    ret
}

; rcx: model
model_draw: proc(m: *const model) = {
    mov edx, 1
    jmp model_draw_instanced               ; a tail call, rcx still the model
}
Part of rasm-dx11, LearnOpenGL's lessons rewritten for Direct3D 11 in rasm. Licensed CC BY-NC 4.0, after LearnOpenGL by Joey de Vries.