xc3_wgpu 0.22.0

Xenoblade Chronicles model rendering library
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
use std::collections::BTreeMap;

use glam::{UVec4, Vec3, Vec4, Vec4Swizzles, vec3};
use wgpu::util::DeviceExt;
use xc3_model::vertex::AttributeData;

use crate::{DeviceBufferExt, shader};

// Buffer loading is expensive, so allow for only loading the needed buffers.
#[derive(Default)]
pub struct ModelBuffers {
    pub vertex_buffers: BTreeMap<usize, VertexBuffer>,
    pub index_buffers: BTreeMap<usize, IndexBuffer>,
}

pub struct VertexBuffer {
    pub vertex_buffer0: wgpu::Buffer,
    pub vertex_buffer1: wgpu::Buffer,
    pub outline_vertex_buffer0: wgpu::Buffer,
    pub outline_vertex_buffer1: wgpu::Buffer,
    pub morph_buffers: Option<MorphBuffers>,
    pub vertex_count: u32,
    pub vector_debug_buffer: VectorDebugBuffer,
}

pub struct MorphBuffers {
    pub vertex_buffer0: wgpu::Buffer,
    pub weights_buffer: wgpu::Buffer,
    pub bind_group0: crate::shader::morph::bind_groups::BindGroup0,
    pub morph_target_controller_indices: Vec<usize>,
}

pub struct VectorDebugBuffer {
    pub vertex_buffer: wgpu::Buffer,
    pub vertex_count: u32,
}

pub struct IndexBuffer {
    pub index_buffer: wgpu::Buffer,
    pub vertex_index_count: u32,
}

impl ModelBuffers {
    #[tracing::instrument(skip_all)]
    pub fn add_vertex_buffer(
        &mut self,
        device: &wgpu::Device,
        buffers: &xc3_model::vertex::ModelBuffers,
        index: usize,
    ) {
        self.vertex_buffers
            .entry(index)
            .or_insert_with(|| VertexBuffer::new(device, buffers, &buffers.vertex_buffers[index]));
    }

    #[tracing::instrument(skip_all)]
    pub fn add_index_buffer(
        &mut self,
        device: &wgpu::Device,
        buffers: &xc3_model::vertex::ModelBuffers,
        index: usize,
    ) {
        self.index_buffers
            .entry(index)
            .or_insert_with(|| IndexBuffer::new(device, &buffers.index_buffers[index]));
    }
}

impl VertexBuffer {
    fn new(
        device: &wgpu::Device,
        buffers: &xc3_model::vertex::ModelBuffers,
        buffer: &xc3_model::vertex::VertexBuffer,
    ) -> Self {
        // Convert the attributes back to an interleaved representation for rendering.
        // Unused attributes will use a default value.
        // Using a single vertex representation reduces shader permutations.
        let vertex_count = buffer.vertex_count();
        let mut buffer0_vertices = vec![
            shader::model::VertexInput0 {
                position: Vec4::ZERO,
                normal: Vec4::ZERO,
                tangent: Vec4::ZERO,
                val_inf: Vec4::ZERO,
            };
            vertex_count
        ];

        let mut buffer1_vertices = vec![
            shader::model::VertexInput1 {
                vertex_color: Vec4::ONE,
                weight_index: UVec4::ZERO,
                tex01: Vec4::ZERO,
                tex23: Vec4::ZERO,
                tex45: Vec4::ZERO,
                tex67: Vec4::ZERO,
                tex8: Vec4::ZERO,
            };
            vertex_count
        ];

        set_attributes(&mut buffer0_vertices, &mut buffer1_vertices, buffer);

        // Avoid overwriting the existing attributes.
        let mut outline_buffer0_vertices = buffer0_vertices.clone();
        let mut outline_buffer1_vertices = buffer1_vertices.clone();
        if let Some(outline_buffer) = buffer
            .outline_buffer_index
            .and_then(|i| buffers.outline_buffers.get(i))
        {
            set_buffer0_attributes(&mut outline_buffer0_vertices, &outline_buffer.attributes);
            set_buffer1_attributes(&mut outline_buffer1_vertices, &outline_buffer.attributes);
        }

        let vertex_buffer0 = device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
            label: Some("vertex buffer 0"),
            contents: bytemuck::cast_slice(&buffer0_vertices),
            usage: wgpu::BufferUsages::VERTEX
                | wgpu::BufferUsages::STORAGE
                | wgpu::BufferUsages::COPY_SRC,
        });

        let vertex_buffer1 = device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
            label: Some("vertex buffer 1"),
            contents: bytemuck::cast_slice(&buffer1_vertices),
            usage: wgpu::BufferUsages::VERTEX,
        });

        let outline_vertex_buffer0 = device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
            label: Some("outline vertex buffer 0"),
            contents: bytemuck::cast_slice(&outline_buffer0_vertices),
            usage: wgpu::BufferUsages::VERTEX,
        });

        let outline_vertex_buffer1 = device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
            label: Some("outline vertex buffer 1"),
            contents: bytemuck::cast_slice(&outline_buffer1_vertices),
            usage: wgpu::BufferUsages::VERTEX,
        });

        // TODO: morph targets?
        let morph_buffers = if !buffer.morph_targets.is_empty() {
            Some(morph_buffers(device, buffer0_vertices, buffer))
        } else {
            None
        };

        let vector_debug_buffer = vector_debug_buffer(device, buffer);

        Self {
            vertex_buffer0,
            vertex_buffer1,
            outline_vertex_buffer0,
            outline_vertex_buffer1,
            morph_buffers,
            vector_debug_buffer,
            vertex_count: vertex_count as u32,
        }
    }
}

impl IndexBuffer {
    pub fn new(device: &wgpu::Device, buffer: &xc3_model::vertex::IndexBuffer) -> Self {
        let index_buffer = device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
            label: Some("index buffer"),
            contents: bytemuck::cast_slice(&buffer.indices),
            usage: wgpu::BufferUsages::INDEX,
        });

        Self {
            index_buffer,
            vertex_index_count: buffer.indices.len() as u32,
        }
    }
}

fn morph_buffers(
    device: &wgpu::Device,
    buffer0_vertices: Vec<shader::model::VertexInput0>,
    buffer: &xc3_model::vertex::VertexBuffer,
) -> MorphBuffers {
    // Initialize to the unmodified vertices.
    let morph_vertex_buffer0 = device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
        label: Some("vertex buffer 0 morph"),
        contents: bytemuck::cast_slice(&buffer0_vertices),
        usage: wgpu::BufferUsages::VERTEX
            | wgpu::BufferUsages::STORAGE
            | wgpu::BufferUsages::COPY_DST,
    });

    // TODO: Optimize this?
    let deltas: Vec<_> = buffer
        .morph_targets
        .iter()
        .flat_map(|target| {
            // Convert from a sparse to a dense representation.
            let vertex_count = buffer.vertex_count();
            let mut position_deltas = vec![Vec4::ZERO; vertex_count];
            let mut normal_deltas = vec![Vec4::ZERO; vertex_count];
            let mut tangent_deltas = vec![Vec4::ZERO; vertex_count];

            for (i, vertex_index) in target.vertex_indices.iter().enumerate() {
                let vertex_index = *vertex_index as usize;

                position_deltas[vertex_index] = target.position_deltas[i].extend(0.0);
                normal_deltas[vertex_index] =
                    target.normals[i] - buffer0_vertices[vertex_index].normal;
                tangent_deltas[vertex_index] =
                    target.tangents[i] - buffer0_vertices[vertex_index].tangent;
            }

            position_deltas
                .iter()
                .zip(normal_deltas.iter())
                .zip(tangent_deltas.iter())
                .map(move |((p, n), t)| crate::shader::morph::MorphVertexDelta {
                    position_delta: *p,
                    normal_delta: *n,
                    tangent_delta: *t,
                })
                .collect::<Vec<_>>()
        })
        .collect();

    let morph_deltas = device.create_storage_buffer("morph deltas", &deltas);

    let weights = vec![0.0f32; buffer.morph_targets.len()];
    let morph_weights = device.create_storage_buffer("morph weights", &weights);

    let bind_group0 = crate::shader::morph::bind_groups::BindGroup0::from_bindings(
        device,
        crate::shader::morph::bind_groups::BindGroupLayout0 {
            vertices: morph_vertex_buffer0.as_entire_buffer_binding(),
            morph_deltas: morph_deltas.as_entire_buffer_binding(),
            morph_weights: morph_weights.as_entire_buffer_binding(),
        },
    );

    let morph_target_controller_indices = buffer
        .morph_targets
        .iter()
        .map(|t| t.morph_controller_index)
        .collect();

    MorphBuffers {
        vertex_buffer0: morph_vertex_buffer0,
        weights_buffer: morph_weights,
        morph_target_controller_indices,
        bind_group0,
    }
}

fn set_attributes(
    buffer0_vertices: &mut [shader::model::VertexInput0],
    buffer1_vertices: &mut [shader::model::VertexInput1],
    buffer: &xc3_model::vertex::VertexBuffer,
) {
    set_buffer0_attributes(buffer0_vertices, &buffer.attributes);
    set_buffer0_attributes(buffer0_vertices, &buffer.morph_blend_target);
    set_buffer1_attributes(buffer1_vertices, &buffer.attributes);
}

fn set_buffer0_attributes(verts: &mut [shader::model::VertexInput0], attributes: &[AttributeData]) {
    for attribute in attributes {
        match attribute {
            AttributeData::Position(vals) => {
                set_attribute0(verts, vals, |v, t| v.position = t.extend(1.0))
            }
            AttributeData::Normal(vals) => set_attribute0(verts, vals, |v, t| v.normal = t),
            AttributeData::Normal2(vals) => set_attribute0(verts, vals, |v, t| v.normal = t),
            AttributeData::Tangent(vals) => set_attribute0(verts, vals, |v, t| v.tangent = t),
            AttributeData::ValInf(vals) => set_attribute0(verts, vals, |v, t| v.val_inf = t),
            // Morph blend target attributes
            AttributeData::Position2(vals) => {
                set_attribute0(verts, vals, |v, t| v.position = t.extend(1.0))
            }
            AttributeData::Normal4(vals) => set_attribute0(verts, vals, |v, t| v.normal = t),
            AttributeData::Tangent2(vals) => set_attribute0(verts, vals, |v, t| v.tangent = t),
            _ => (),
        }
    }
}

fn set_buffer1_attributes(verts: &mut [shader::model::VertexInput1], attributes: &[AttributeData]) {
    for attribute in attributes {
        match attribute {
            AttributeData::TexCoord0(vals) => set_attribute1(verts, vals, |v, t| {
                v.tex01.x = t.x;
                v.tex01.y = t.y;
            }),
            AttributeData::TexCoord1(vals) => set_attribute1(verts, vals, |v, t| {
                v.tex01.z = t.x;
                v.tex01.w = t.y;
            }),
            AttributeData::TexCoord2(vals) => set_attribute1(verts, vals, |v, t| {
                v.tex23.z = t.x;
                v.tex23.w = t.y;
            }),
            AttributeData::TexCoord3(vals) => set_attribute1(verts, vals, |v, t| {
                v.tex23.z = t.x;
                v.tex23.w = t.y;
            }),
            AttributeData::TexCoord4(vals) => set_attribute1(verts, vals, |v, t| {
                v.tex45.x = t.x;
                v.tex45.y = t.y;
            }),
            AttributeData::TexCoord5(vals) => set_attribute1(verts, vals, |v, t| {
                v.tex45.z = t.x;
                v.tex45.w = t.y;
            }),
            AttributeData::TexCoord6(vals) => set_attribute1(verts, vals, |v, t| {
                v.tex67.x = t.x;
                v.tex67.y = t.y;
            }),
            AttributeData::TexCoord7(vals) => set_attribute1(verts, vals, |v, t| {
                v.tex67.z = t.x;
                v.tex67.w = t.y;
            }),
            AttributeData::TexCoord8(vals) => set_attribute1(verts, vals, |v, t| {
                v.tex8.z = t.x;
                v.tex8.w = t.y;
            }),
            AttributeData::VertexColor(vals) => {
                set_attribute1(verts, vals, |v, t| v.vertex_color = t)
            }
            AttributeData::WeightIndex(vals) => {
                // TODO: What does the second index component do?
                set_attribute1(verts, vals, |v, t| {
                    v.weight_index.x = t[0] as u32;
                    v.weight_index.y = t[1] as u32;
                })
            }
            _ => (),
        }
    }
}

fn set_attribute0<T, F>(vertices: &mut [shader::model::VertexInput0], values: &[T], assign: F)
where
    T: Copy,
    F: Fn(&mut shader::model::VertexInput0, T),
{
    for (vertex, value) in vertices.iter_mut().zip(values) {
        assign(vertex, *value);
    }
}

fn set_attribute1<T, F>(vertices: &mut [shader::model::VertexInput1], values: &[T], assign: F)
where
    T: Copy,
    F: Fn(&mut shader::model::VertexInput1, T),
{
    for (vertex, value) in vertices.iter_mut().zip(values) {
        assign(vertex, *value);
    }
}

fn vector_debug_buffer(
    device: &wgpu::Device,
    buffer: &xc3_model::vertex::VertexBuffer,
) -> VectorDebugBuffer {
    let mut vertices = Vec::new();

    let mut positions = Vec::new();
    for attribute in &buffer.attributes {
        if let AttributeData::Position(values) = attribute {
            positions = values.clone();
        }
    }

    // Assume only one tangent attribute and one normal attribute.
    let mut tangents = Vec::new();
    for attribute in &buffer.attributes {
        match attribute {
            AttributeData::Tangent(values) => {
                tangents = values.clone();
            }
            AttributeData::Tangent2(values) => {
                tangents = values.clone();
            }
            _ => (),
        }
    }
    let mut normals = Vec::new();
    for attribute in &buffer.attributes {
        match attribute {
            AttributeData::Normal(values) => {
                normals = values.clone();
            }
            AttributeData::Normal2(values) => {
                normals = values.clone();
            }
            AttributeData::Normal3(values) => {
                normals = values.clone();
            }
            AttributeData::Normal4(values) => {
                normals = values.clone();
            }
            _ => (),
        }
    }

    // Create a line that points in the direction of each vector.
    for attribute in &buffer.attributes {
        if let AttributeData::ValInf(values) = attribute {
            for (((n, p), t), v) in normals.iter().zip(&positions).zip(&tangents).zip(values) {
                // Simulate the bitangents calculated in the fragment shader.
                if n.w < 1.0 {
                    let bitangent = (n.xyz().cross(t.xyz()) * t.w).extend(0.0);
                    add_vector_debug_line(&mut vertices, vec3(1.0, 0.0, 0.0), *p, *t);
                    add_vector_debug_line(&mut vertices, vec3(0.0, 1.0, 0.0), *p, bitangent);
                    add_vector_debug_line(&mut vertices, vec3(0.0, 0.0, 1.0), *p, *n);
                    add_vector_debug_line(&mut vertices, vec3(1.0, 1.0, 1.0), *p, *v);
                }
            }
        }
    }
    let vertex_buffer = device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
        label: Some("Vector Debug vertex buffer"),
        contents: bytemuck::cast_slice(&vertices),
        usage: wgpu::BufferUsages::VERTEX
            | wgpu::BufferUsages::STORAGE
            | wgpu::BufferUsages::COPY_SRC,
    });

    VectorDebugBuffer {
        vertex_buffer,
        vertex_count: vertices.len() as u32,
    }
}

fn add_vector_debug_line(
    vertices: &mut Vec<shader::vector::VertexInput>,
    color: Vec3,
    pos: Vec3,
    value: Vec4,
) {
    // TODO: configure the scale?
    vertices.push(shader::vector::VertexInput {
        position: pos.extend(1.0),
        color: color.extend(0.0),
    });
    vertices.push(shader::vector::VertexInput {
        position: (pos + value.xyz() * 0.025).extend(1.0),
        color: color.extend(0.0),
    });
}