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
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561

/*
 * Copyright (c) 2016 David Harvey-Macaulay <alteous@outlook.com>
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */

#![feature(proc_macro, custom_attribute)]

extern crate gl;
extern crate serde;
#[macro_use]
extern crate serde_derive;
extern crate serde_json;

use std::fs::File;
use std::io::Read;
use std::path::Path;

use serde_json::from_str;

pub use serde_json::value::{Map, Value};

/// Untyped glTF top-level object identifier
pub type Id = String;

/// Helper trait for looking up top-level objects by their identifier
pub trait Find<T> {
    /// Attempts to find the object of type `T` with identifer `id`
    fn find(&self, id: &str) -> Option<&T>;
}

/// Run time error encountered when loading a glTF asset
#[derive(Debug)]
pub enum Error {
    /// Standard input / output error
    Io(std::io::Error),
    /// Failure when parsing a .gltf metadata file
    Parse(serde_json::error::Error),
}

/// [The root object for a glTF asset]
/// (https://github.com/KhronosGroup/glTF/blob/master/specification/README.md#gltf)
#[derive(Debug, Deserialize, Serialize)]
pub struct Gltf {
    #[serde(default)]
    pub accessors: Map<Id, Accessor>,
    #[serde(default)]
    pub asset: Asset,
    #[serde(default)]
    pub buffers: Map<Id, Buffer>,
    #[serde(default)]
    #[serde(rename = "bufferViews")]
    pub buffer_views: Map<Id, BufferView>,
    #[serde(default)]
    pub materials: Map<Id, Material>,
    #[serde(default)]
    pub meshes: Map<Id, Mesh>,
    #[serde(default)]
    pub programs: Map<Id, Program>,
    #[serde(default)]
    pub shaders: Map<Id, Shader>,
    #[serde(default)]
    pub techniques: Map<Id, Technique>,
    // Incomplete
}

/// [Defines a method for retrieving data from within a `BufferView`]
/// (https://github.com/KhronosGroup/glTF/blob/master/specification/README.md#accessors)
#[derive(Debug, Default, Deserialize, Serialize)]
#[serde(deny_unknown_fields)]
pub struct Accessor {
    /// The identifier of the `BufferView` this accessor reads from.
    #[serde(rename = "bufferView")]
    pub buffer_view: Id,
    /// Where the data items begin from in the `BufferView`
    #[serde(rename = "byteOffset")]
    pub byte_offset: u32,
    /// The size of each data item in the `BufferView`
    #[serde(rename = "byteStride")]
    #[serde(default)]
    pub byte_stride: u32,
    /// Possible values: `GL_BYTE`, `GL_FLOAT`, `GL_SHORT`, `GL_UNSIGNED_BYTE`, or `GL_UNSIGNED_SHORT`
    #[serde(rename = "componentType")]
    pub component_type: u32,
    /// The number of attributes within the `BufferView` (N.B. not number of bytes)
    pub count: u32,
    /// Possible values: `"SCALAR"`, `"VEC2"`, `"VEC3"`, `"VEC4"`, `"MAT2"`, `"MAT3"`, or `"MAT4"`
    #[serde(rename = "type")]
    pub component_width: String,
    /// Optional data targeting official extensions
    pub extensions: Option<Map<String, Value>>,
    /// Optional application specific data
    pub extras: Option<Map<String, Value>>,
    /// Maximum value of each component in the attribute
    pub max: Option<Vec<f32>>,
    /// Minimum value of each component in the attribtue
    pub min: Option<Vec<f32>>,
}

/// [Contains metadata about the glTF asset]
/// (https://github.com/KhronosGroup/glTF/blob/master/specification/README.md#asset)
#[derive(Debug, Default, Deserialize, Serialize)]
#[serde(deny_unknown_fields)]
pub struct Asset {
    /// A copyright message suitable for display to credit the content creator
    pub copyright: Option<String>,
    /// Optional data targeting official extensions
    pub extensions: Option<Map<String, Value>>,
    /// Optional application specific data
    pub extras: Option<Map<String, Value>>,
    /// Tool that generated this glTF model
    pub generator: Option<String>,
    /// Specifies if shaders were generated with pre-multiplied alpha
    #[serde(default)]
    #[serde(rename = "premultipliedAlpha")]
    pub pre_multiplied_alpha: bool,
    /// Specifies the target rendering API and version
    pub profile: Option<AssetProfile>,
    /// glTF version
    pub version: String,
}

/// [Specifies the target rendering API and version]
/// (https://github.com/KhronosGroup/glTF/blob/master/specification/README.md#assetprofile-1)
#[derive(Debug, Default, Deserialize, Serialize)]
#[serde(deny_unknown_fields)]
pub struct AssetProfile {
    /// Specifies the target rendering API
    #[serde(default = "asset_profile_api_default")]
    pub api: String,
    /// Optional data targeting official extensions
    pub extensions: Option<Map<String, Value>>,
    /// Optional application specific data
    pub extras: Option<Map<String, Value>>,
    /// Specifies the target rendering API version
    #[serde(default = "asset_profile_version_default")]
    pub version: String,
}

fn asset_profile_api_default() -> String {
    "WebGL".to_string()
}

fn asset_profile_version_default() -> String {
    "1.0.3".to_string()
}

/// The identifier of the `BufferView` this accessor reads from.
/// [Describes the location, type, and size of a binary blob included with the asset]
/// (https://github.com/KhronosGroup/glTF/blob/master/specification/README.md#buffer)
#[derive(Debug, Default, Deserialize, Serialize)]
#[serde(deny_unknown_fields)]
pub struct Buffer {
    /// The length of the buffer in bytes
    #[serde(default)]
    #[serde(rename = "byteLength")]
    pub byte_length: u32,
    /// Optional data targeting official extensions
    pub extensions: Option<Map<String, Value>>,
    /// Optional application specific data
    pub extras: Option<Map<String, Value>>,
    /// Optional user-defined name for this object
    pub name: Option<String>,
    /// XMLHttpRequest `responseType`
    #[serde(default = "buffer_response_type_default")]
    #[serde(rename = "type")]
    pub response_type: String,
    /// Uniform resource locator for the buffer data
    pub uri: String,
}

fn buffer_response_type_default() -> String {
    "arraybuffer".to_string()
}

/// [Represents a subset of a `Buffer`]
/// (https://github.com/KhronosGroup/glTF/blob/master/specification/README.md#buffers-and-buffer-views)  
#[derive(Debug, Default, Deserialize, Serialize)]
#[serde(deny_unknown_fields)]
pub struct BufferView {
    /// The identifier of the parent `Buffer`
    pub buffer: Id,
    /// The length of the buffer view in bytes
    #[serde(default)]
    #[serde(rename = "byteLength")]
    pub byte_length: u32,
    /// Offset into the buffer in bytes
    #[serde(rename = "byteOffset")]
    pub byte_offset: u32,
    /// Optional data targeting official extensions
    pub extensions: Option<Map<String, Value>>,
    /// Optional application specific data
    pub extras: Option<Map<String, Value>>,
    /// Optional user-defined name for this object
    pub name: Option<String>,
    /// Optional target the buffer should be bound to (for example
    /// `GL_ARRAY_BUFFER` or `GL_ELEMENT_ARRAY_BUFFER`)
    pub target: Option<u32>,
}
/// [Describes the material appearance of a primitive]
/// (https://github.com/KhronosGroup/glTF/blob/master/specification/README.md#material)
#[derive(Debug, Default, Deserialize, Serialize)]
#[serde(deny_unknown_fields)]
pub struct Material {
    /// Optional data targeting official extensions
    pub extensions: Option<Map<String, Value>>,
    /// Optional application specific data
    pub extras: Option<Map<String, Value>>,
    /// Optional user-defined name for this object
    pub name: Option<String>,
    /// ID of the shading technique to be used
    pub technique: Option<Id>,
    /// Parameter values
    #[serde(default)]
    pub values: Map<String, Value>,
}

/// [A set of primitives to be rendered]
/// (https://github.com/KhronosGroup/glTF/blob/master/specification/README.md#mesh)
#[derive(Debug, Default, Deserialize, Serialize)]
#[serde(deny_unknown_fields)]
pub struct Mesh {
    /// Optional data targeting official extensions
    pub extensions: Option<Map<String, Value>>,
    /// Optional application specific data
    pub extras: Option<Map<String, Value>>,
    /// Optional user-defined name for this object
    pub name: Option<String>,
    #[serde(default)]
    pub primitives: Vec<MeshPrimitive>,
}

/// [Geometry to be rendered with the given material]
/// (https://github.com/KhronosGroup/glTF/blob/master/specification/README.md#meshprimitive)
#[derive(Debug, Default, Deserialize, Serialize)]
#[serde(deny_unknown_fields)]
pub struct MeshPrimitive {
    /// Mapping of attribute names to `Accessor` IDs
    #[serde(default)]
    pub attributes: Map<String, Id>,
    /// Optional data targeting official extensions
    pub extensions: Option<Map<String, Value>>,
    /// Optional application specific data
    pub extras: Option<Map<String, Value>>,
    /// Optional ID of the `Accessor` containing index data
    pub indices: Option<Id>,
    /// ID of the material to apply to this primitive when rendering
    pub material: Id,
    /// The type of primitives to render (for example `GL_TRIANGLES`)
    #[serde(default = "mesh_primitive_mode_default")]
    pub mode: u32,
}

fn mesh_primitive_mode_default() -> u32 {
    gl::TRIANGLES
}

/// [A single member of the glTF scene hierarchy]
/// (https://github.com/KhronosGroup/glTF/blob/master/specification/README.md#scenes)
#[derive(Debug, Default, Deserialize, Serialize)]
pub struct Node {
    /// Optional data targeting official extensions
    pub extensions: Option<Map<String, Value>>,
    /// Optional application specific data
    pub extras: Option<Map<String, Value>>,
    /// The IDs of the `Mesh` objects in this node
    pub meshes: Option<Vec<Id>>,
    /// Optional user-defined name for this object
    pub name: Option<String>,
    // Incomplete
}

/// [Describes a GLSL shader program]
/// (https://github.com/KhronosGroup/glTF/blob/master/specification/README.md#programs)
#[derive(Debug, Default, Deserialize, Serialize)]
#[serde(deny_unknown_fields)]
pub struct Program {
    /// Vertex attribute bindings (e.g. `"u_ModelView"`) that will be passed to the shader
    #[serde(default)]
    pub attributes: Vec<String>,
    /// Optional data targeting official extensions
    pub extensions: Option<Map<String, Value>>,
    /// Optional application specific data
    pub extras: Option<Map<String, Value>>,
    /// ID of the fragment shader component
    #[serde(rename = "fragmentShader")]
    pub fragment_shader: String,
    /// Optional user-defined name for this object
    pub name: Option<String>,
    /// ID of the vertex shader component
    #[serde(rename = "vertexShader")]
    pub vertex_shader: String,
}

/// [Describes a GLSL shader component]
/// (https://github.com/KhronosGroup/glTF/blob/master/specification/README.md#shaders)
#[derive(Debug, Default, Deserialize, Serialize)]
#[serde(deny_unknown_fields)]
pub struct Shader {
    /// Optional data targeting official extensions
    pub extensions: Option<Map<String, Value>>,
    /// Optional application specific data
    pub extras: Option<Map<String, Value>>,
    /// Optional user-defined name for this object
    pub name: Option<String>,
    /// The shader stage (for example `GL_VERTEX_SHADER` or `GL_FRAGMENT_SHADER`)
    #[serde(rename = "type")]
    pub type_id: u32,
    /// Uniform resource identifier of the GLSL source code
    pub uri: String,
}

/// [Describes the shading technqiue used for a material]
/// (https://github.com/KhronosGroup/glTF/blob/master/specification/README.md#technique)
#[derive(Debug, Default, Deserialize, Serialize)]
#[serde(deny_unknown_fields)]
pub struct Technique {
    /// Maps GLSL attribute names to technique parameter IDs
    #[serde(default)]
    pub attributes: Map<String, String>,
    /// Optional data targeting official extensions
    pub extensions: Option<Map<String, Value>>,
    /// Optional application specific data
    pub extras: Option<Map<String, Value>>,
    /// Optional user-defined name for this object
    pub name: Option<String>,
    #[serde(default)]
    pub parameters: Map<String, TechniqueParameter>,
    /// ID of the GLSL shader program to render with
    pub program: Id,
    /// Fixed-function rendering states
    #[serde(default)]
    pub states: TechniqueStates,
    /// Maps uniform names to technqiue parameter IDs
    #[serde(default)]
    pub uniforms: Map<String, String>,
}

/// [Describes an attribute or uniform input to a `Technique`]
/// (https://github.com/KhronosGroup/glTF/blob/master/specification/README.md#techniqueparameters-1)
/// If `semantic` is not `None` then this parameter describes a [built-in uniform value]
/// (https://github.com/KhronosGroup/glTF/blob/master/specification/README.md#semantics)
#[derive(Debug, Default, Deserialize, Serialize)]
#[serde(deny_unknown_fields)]
pub struct TechniqueParameter {
    /// Defines the number of elements if the parameter is an array
    pub count: Option<u32>,
    /// Optional data targeting official extensions
    pub extensions: Option<Map<String, Value>>,
    /// Optional application specific data
    pub extras: Option<Map<String, Value>>,
    /// ID of the `Node` whose transform is used as the parameter's value
    pub node: Option<Id>,
    /// `"MODELVIEW"`, `"PROJECTION"`, etc.
    pub semantic: Option<String>,
    /// The data type (for example `GL_FLOAT`, or `GL_FLOAT_VEC4`)
    #[serde(rename = "type")]
    pub type_id: u32,
    /// The value of the parameter
    pub value: Option<Value>,
}

/// [Optional arguments to OpenGL state functions]
/// (https://github.com/KhronosGroup/glTF/blob/master/specification/README.md#render-states)
#[derive(Debug, Default, Deserialize, Serialize)]
#[serde(deny_unknown_fields)]
pub struct TechniqueStateFunctions {
    /// Arguments `[red, green, blue, alpha]` for `glBlendColor()`
    #[serde(default)]
    #[serde(rename = "blendColor")]
    pub blend_color: [f64; 4],
    /// Arguments `[mode_rgb, mode_alpha]` for `glBlendEquationSeparate()`
    #[serde(default = "technique_state_functions_blend_equation_default")]
    #[serde(rename = "blendEquationSeparate")]
    pub blend_equation: [u32; 2],
    /// Arguments `[src_rgb, dst_rgb, src_alpha, dst_alpha]` for `glBlendFuncSeparate()`
    #[serde(default = "technique_state_functions_blend_function_default")]
    #[serde(rename = "blendFuncSeparate")]
    pub blend_function: [u32; 4],
    /// Arguments `[red, green, blue, alpha]` for `glColorMask()`
    #[serde(default = "technique_state_functions_color_mask_default")]
    #[serde(rename = "colorMask")]
    pub color_mask: [bool; 4],
    /// Argument `[mode]` for `glCullFace()`
    #[serde(default = "technique_state_functions_cull_face_default")]
    #[serde(rename = "cullFace")]
    pub cull_face: [u32; 1],
    /// Argument `[func]` for `glDepthFunc()`
    #[serde(default = "technique_state_functions_depth_func_default")]
    #[serde(rename = "depthFunc")]
    pub depth_function: [u32; 1],
    /// Argument `[flag]` for `glDepthMask()`
    #[serde(default = "technique_state_functions_depth_mask_default")]
    #[serde(rename = "depthMask")]
    pub depth_mask: [bool; 1],
    /// Arguments `[z_near, z_far]` for `glDepthRange()`
    #[serde(default = "technique_state_functions_depth_range_default")]
    #[serde(rename = "depthRange")]
    pub depth_range: [f64; 2],
    /// Optional data targeting official extensions
    pub extensions: Option<Map<String, Value>>,
    /// Optional application specific data
    pub extras: Option<Map<String, Value>>,
    /// Argument `[mode]` for `glFrontFace()`
    #[serde(default = "technique_state_functions_front_face_default")]
    #[serde(rename = "frontFace")]
    pub front_face: [u32; 1],
    /// Argument `[width]` for `glLineWidth()`
    #[serde(default = "technique_state_functions_line_width_default")]
    #[serde(rename = "lineWidth")]
    pub line_width: [f32; 1],
    /// Arguments `[factor, units]` for `glPolygonOffset()`
    #[serde(default)]
    #[serde(rename = "polygonOffset")]
    pub polygon_offset: [f32; 2],
    /// Arguments `[x, y, width, height]` for `glScissor()`
    #[serde(default)]
    pub scissor: [i32; 4],
}

fn technique_state_functions_blend_equation_default() -> [u32; 2] {
    [gl::FUNC_ADD, gl::FUNC_ADD]
}

fn technique_state_functions_blend_function_default() -> [u32; 4] {
    [gl::ONE, gl::ZERO, gl::ONE, gl::ZERO]
}

fn technique_state_functions_color_mask_default() -> [bool; 4] {
    [true, true, true, true]
}

fn technique_state_functions_cull_face_default() -> [u32; 1] {
    [gl::BACK]
}

fn technique_state_functions_depth_func_default() -> [u32; 1] {
    [gl::LESS]
}

fn technique_state_functions_depth_mask_default() -> [bool; 1] {
    [true]
}

fn technique_state_functions_depth_range_default() -> [f64; 2] {
    [0.0, 1.0]
}

fn technique_state_functions_front_face_default() -> [u32; 1] {
    [gl::CCW]
}

fn technique_state_functions_line_width_default() -> [f32; 1] {
    [1.0]
}

/// [Required OpenGL render states to be enabled]
/// (https://github.com/KhronosGroup/glTF/blob/master/specification/README.md#render-states)
#[derive(Debug, Default, Deserialize, Serialize)]
#[serde(deny_unknown_fields)]
pub struct TechniqueStates {
    /// OpenGL states to be enabled
    #[serde(default)]
    pub enable: Vec<u32>,
    /// Optional data targeting official extensions
    pub extensions: Option<Map<String, Value>>,
    /// Optional application specific data
    pub extras: Option<Map<String, Value>>,
    /// Arguments for fixed-function rendering state functions
    pub functions: Option<TechniqueStateFunctions>, 
}

impl Gltf {
    /// Loads a glTF asset
    ///
    /// # Examples
    ///
    /// Basic usage:
    ///
    /// ```
    /// let gltf = gltf::Gltf::new("./examples/box/Box.gltf")
    ///     .expect("Error loading glTF asset");
    /// ```
    pub fn new<P: AsRef<Path>>(path: P) -> Result<Self, Error> {
        let mut file = try!(File::open(path));
        let mut json = String::new();
        try!(file.read_to_string(&mut json));
        from_str(&json)
            .map_err(|cause| Error::Parse(cause))
    }

    /// Looks up a top-level object by its identifier
    ///
    /// # Examples
    ///
    /// Finding a buffer view:
    ///
    /// ```
    /// let gltf = gltf::Gltf::new("./examples/box/Box.gltf").unwrap();
    /// let buffer_view = gltf
    ///     .find::<gltf::BufferView>("bufferView_29")
    ///     .expect("Buffer view not found");
    /// ```
    pub fn find<T>(&self, id: &str) -> Option<&T>
        where Self: Find<T>
    {
        (self as &Find<T>).find(id)
    }
}

macro_rules! impl_find {
    ($ident:ident, $ty:ty) => (
        impl Find<$ty> for Gltf {
            fn find(&self, id: &str) -> Option<&$ty> {
                self.$ident
                    .iter()
                    .find(|&(entry_id, _)| entry_id == id)
                    .map(|(_, entry)| entry)
            }
        }
    )
}

impl_find!(accessors, Accessor);
impl_find!(buffers, Buffer);
impl_find!(buffer_views, BufferView);
impl_find!(materials, Material);
impl_find!(meshes, Mesh);
impl_find!(programs, Program);
impl_find!(shaders, Shader);
impl_find!(techniques, Technique);

impl From<std::io::Error> for Error {
    fn from(err: std::io::Error) -> Error {
        Error::Io(err)
    }
}

impl From<serde_json::error::Error> for Error {
    fn from(err: serde_json::error::Error) -> Error {
        Error::Parse(err)
    }
}