-
Notifications
You must be signed in to change notification settings - Fork 45
/
lib.rs
2208 lines (2104 loc) · 82.1 KB
/
lib.rs
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
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//! # Tiny OBJ Loader
//!
//! A tiny OBJ loader, inspired by Syoyo's excellent [`tinyobjloader`](https://github.com/syoyo/tinyobjloader).
//! Aims to be a simple and lightweight option for loading `OBJ` files.
//!
//! Just returns two `Vec`s containing loaded models and materials.
//!
//! ## Triangulation
//!
//! Meshes can be triangulated on the fly or left as-is.
//!
//! Only polygons that are trivially convertible to triangle fans are supported.
//! Arbitrary polygons may not behave as expected. The best solution would be to
//! convert your mesh to solely consist of triangles in your modeling software.
//!
//! ## Optional – Normals & Texture Coordinates
//!
//! It is assumed that all meshes will at least have positions, but normals and
//! texture coordinates are optional.
//!
//! If no normals or texture coordinates are found then the corresponding
//! [`Vec`](Mesh::normals)s for the [`Mesh`] will be empty.
//!
//! ## Flat Data
//!
//! Values are stored packed as [`f32`]s (or [`f64`]s with the use_f64 feature)
//! in flat `Vec`s.
//!
//! For example, the `positions` member of a `Mesh` will contain `[x, y, z, x,
//! y, z, ...]` which you can then use however you like.
//!
//! ## Indices
//!
//! Indices are also loaded and may re-use vertices already existing in the
//! mesh, this data is stored in the [`indices`](Mesh::indices) member.
//!
//! When a `Mesh` contains *per vertex per face* normals or texture coordinates,
//! positions can be duplicated to be *per vertex per face* too via the
//! [`single_index`](LoadOptions::single_index) flag. This potentially changes
//! the topology (faces may become disconnected even though their vertices still
//! share a position in space).
//!
//! By default separate indices for normals and texture coordinates are created.
//! This also guarantees that the topology of the `Mesh` does *not* change when
//! either of the latter are specified *per vertex per face*.
//!
//! ## Materials
//!
//! Standard `MTL` attributes are supported too. Any unrecognized parameters
//! will be stored in a `HashMap` containing the key-value pairs of the
//! unrecognized parameter and its value.
//!
//! ## Example
//!
//! In this simple example we load the classic Cornell Box model that only
//! defines positions and print out its attributes. This example is a slightly
//! trimmed down version of `print_model_info` and `print_material_info`
//! combined together, see them for a version that also prints out normals and
//! texture coordinates if the model has them.
//!
//! The [`LoadOptions`] used are typical for the case when the mesh is going to
//! be sent to a realtime rendering context (game engine, GPU etc.).
//!
//! ```
//! use tobj;
//!
//! let cornell_box = tobj::load_obj("obj/cornell_box.obj", &tobj::GPU_LOAD_OPTIONS);
//! assert!(cornell_box.is_ok());
//!
//! let (models, materials) = cornell_box.expect("Failed to load OBJ file");
//!
//! // Materials might report a separate loading error if the MTL file wasn't found.
//! // If you don't need the materials, you can generate a default here and use that
//! // instead.
//! let materials = materials.expect("Failed to load MTL file");
//!
//! println!("# of models: {}", models.len());
//! println!("# of materials: {}", materials.len());
//!
//! for (i, m) in models.iter().enumerate() {
//! let mesh = &m.mesh;
//!
//! println!("model[{}].name = \'{}\'", i, m.name);
//! println!("model[{}].mesh.material_id = {:?}", i, mesh.material_id);
//!
//! println!(
//! "Size of model[{}].face_arities: {}",
//! i,
//! mesh.face_arities.len()
//! );
//!
//! let mut next_face = 0;
//! for f in 0..mesh.face_arities.len() {
//! let end = next_face + mesh.face_arities[f] as usize;
//! let face_indices: Vec<_> = mesh.indices[next_face..end].iter().collect();
//! println!(" face[{}] = {:?}", f, face_indices);
//! next_face = end;
//! }
//!
//! // Normals and texture coordinates are also loaded, but not printed in this example
//! println!("model[{}].vertices: {}", i, mesh.positions.len() / 3);
//!
//! assert!(mesh.positions.len() % 3 == 0);
//! for v in 0..mesh.positions.len() / 3 {
//! println!(
//! " v[{}] = ({}, {}, {})",
//! v,
//! mesh.positions[3 * v],
//! mesh.positions[3 * v + 1],
//! mesh.positions[3 * v + 2]
//! );
//! }
//! }
//!
//! for (i, m) in materials.iter().enumerate() {
//! println!("material[{}].name = \'{}\'", i, m.name);
//! if let Some(ambient) = m.ambient {
//! println!(
//! " material.Ka = ({}, {}, {})",
//! ambient[0], ambient[1], ambient[2]
//! );
//! }
//! if let Some(diffuse) = m.diffuse {
//! println!(
//! " material.Kd = ({}, {}, {})",
//! diffuse[0], diffuse[1], diffuse[2]
//! );
//! }
//! if let Some(specular) = m.specular {
//! println!(
//! " material.Ks = ({}, {}, {})",
//! specular[0], specular[1], specular[2]
//! );
//! }
//! if let Some(shininess) = m.shininess {
//! println!(" material.Ns = {}", shininess);
//! }
//! if let Some(dissolve) = m.dissolve {
//! println!(" material.d = {}", dissolve);
//! }
//! if let Some(ambient_texture) = &m.ambient_texture {
//! println!(" material.map_Ka = {}", ambient_texture);
//! }
//! if let Some(diffuse_texture) = &m.diffuse_texture {
//! println!(" material.map_Kd = {}", diffuse_texture);
//! }
//! if let Some(specular_texture) = &m.specular_texture {
//! println!(" material.map_Ks = {}", specular_texture);
//! }
//! if let Some(shininess_texture) = &m.shininess_texture {
//! println!(" material.map_Ns = {}", shininess_texture);
//! }
//! if let Some(normal_texture) = &m.normal_texture {
//! println!(" material.map_Bump = {}", normal_texture);
//! }
//! if let Some(dissolve_texture) = &m.dissolve_texture {
//! println!(" material.map_d = {}", dissolve_texture);
//! }
//!
//! for (k, v) in &m.unknown_param {
//! println!(" material.{} = {}", k, v);
//! }
//! }
//! ```
//!
//! ## Rendering Examples
//!
//! For an example of integration with [glium](https://github.com/tomaka/glium)
//! to make a simple OBJ viewer, check out [`tobj viewer`](https://github.com/Twinklebear/tobj_viewer).
//! Some more sample images can be found in [this gallery](http://imgur.com/a/xsg6v).
//!
//! The Rungholt model shown below is reasonably large (6.7M triangles, 12.3M
//! vertices) and is loaded in ~7.47s using a peak of ~1.1GB of memory on a
//! Windows 10 machine with an i7-4790k and 16GB of 1600Mhz DDR3 RAM with tobj
//! 0.1.1 on rustc 1.6.0. The model can be found on [Morgan McGuire's](http://graphics.cs.williams.edu/data/meshes.xml)
//! meshes page and was originally built by kescha. Future work will focus on
//! improving performance and memory usage.
//!
//! <img src="http://i.imgur.com/wImyNG4.png" alt="Rungholt"
//! style="display:block; max-width:100%; height:auto">
//!
//! For an example of integration within a ray tracer, check out tray\_rust's
//! [mesh module](https://github.com/Twinklebear/tray_rust/blob/master/src/geometry/mesh.rs).
//! The Stanford Buddha and Dragon from the
//! [Stanford 3D Scanning Repository](http://graphics.stanford.edu/data/3Dscanrep/)
//! both load quite quickly. The Rust logo model was made by [Nylithius on BlenderArtists](http://blenderartists.org/forum/showthread.php?362836-Rust-language-3D-logo).
//! The materials used are from the [MERL BRDF Database](http://www.merl.com/brdf/).
//!
//! <img src="http://i.imgur.com/E1ylrZW.png" alt="Rust logo with friends"
//! style="display:block; max-width:100%; height:auto">
//!
//! ## Features
//!
//! * [`ahash`](https://crates.io/crates/ahash) – On by default. Use [`AHashMap`](https://docs.rs/ahash/latest/ahash/struct.AHashMap.html)
//! for hashing when reading files and merging vertices. To disable and use
//! the slower [`HashMap`](std::collections::HashMap) instead, unset default
//! features in `Cargo.toml`:
//!
//! ```toml
//! [dependencies.tobj]
//! default-features = false
//! ```
//!
//! * [`merging`](LoadOptions::merge_identical_points) – Adds support for
//! merging identical vertex positions on disconnected faces during import.
//!
//! **Warning:** this feature uses *const generics* and thus requires at
//! least a `beta` toolchain to build.
//!
//! * [`reordering`](LoadOptions::reorder_data) – Adds support for reordering
//! the normal- and texture coordinate indices.
//!
//! * [`async`](load_obj_buf_async) – Adds support for async loading of obj
//! files from a buffer, with an async material loader. Useful in environments
//! that do not support blocking IO (e.g. WebAssembly).
//!
//! * ['use_f64'] - Uses double-precision (f64) instead of single-precision
//! (f32) floating point types
#![cfg_attr(feature = "merging", allow(incomplete_features))]
#![cfg_attr(feature = "merging", feature(generic_const_exprs))]
#[cfg(test)]
mod tests;
use std::{
error::Error,
fmt,
fs::File,
io::{prelude::*, BufReader},
path::Path,
str::{FromStr, SplitWhitespace},
};
#[cfg(feature = "use_f64")]
type Float = f64;
#[cfg(not(feature = "use_f64"))]
type Float = f32;
#[cfg(feature = "async")]
use std::future::Future;
#[cfg(feature = "merging")]
use std::mem::size_of;
#[cfg(feature = "ahash")]
type HashMap<K, V> = ahash::AHashMap<K, V>;
#[cfg(not(feature = "ahash"))]
type HashMap<K, V> = std::collections::HashMap<K, V>;
/// Typical [`LoadOptions`] for using meshes in a GPU/relatime context.
///
/// Faces are *triangulated*, a *single index* is generated and *degenerate
/// faces* (points & lines) are *discarded*.
pub const GPU_LOAD_OPTIONS: LoadOptions = LoadOptions {
#[cfg(feature = "merging")]
merge_identical_points: false,
#[cfg(feature = "reordering")]
reorder_data: false,
single_index: true,
triangulate: true,
ignore_points: true,
ignore_lines: true,
};
/// Typical [`LoadOptions`] for using meshes with an offline rendeder.
///
/// Faces are *kept as they are* (e.g. n-gons) and *normal and texture
/// coordinate data is reordered* so only a single index is needed.
/// Topology remains unchanged except for *degenerate faces* (points & lines)
/// which are *discarded*.
pub const OFFLINE_RENDERING_LOAD_OPTIONS: LoadOptions = LoadOptions {
#[cfg(feature = "merging")]
merge_identical_points: true,
#[cfg(feature = "reordering")]
reorder_data: true,
single_index: false,
triangulate: false,
ignore_points: true,
ignore_lines: true,
};
/// A mesh made up of triangles loaded from some `OBJ` file.
///
/// It is assumed that all meshes will at least have positions, but normals and
/// texture coordinates are optional. If no normals or texture coordinates where
/// found then the corresponding `Vec`s in the `Mesh` will be empty. Values are
/// stored packed as [`f32`]s (or [`f64`]s with the use_f64 feature) in flat
/// `Vec`s.
///
/// For examples the `positions` member of a loaded mesh will contain `[x, y, z,
/// x, y, z, ...]` which you can then use however you like. Indices are also
/// loaded and may re-use vertices already existing in the mesh. This data is
/// stored in the `indices` member.
///
/// # Example:
/// Load the Cornell box and get the attributes of the first vertex. It's
/// assumed all meshes will have positions (required), but normals and texture
/// coordinates are optional, in which case the corresponding `Vec` will be
/// empty.
///
/// ```
/// let cornell_box = tobj::load_obj("obj/cornell_box.obj", &tobj::GPU_LOAD_OPTIONS);
/// assert!(cornell_box.is_ok());
///
/// let (models, materials) = cornell_box.unwrap();
///
/// let mesh = &models[0].mesh;
/// let i = mesh.indices[0] as usize;
///
/// // pos = [x, y, z]
/// let pos = [
/// mesh.positions[i * 3],
/// mesh.positions[i * 3 + 1],
/// mesh.positions[i * 3 + 2],
/// ];
///
/// if !mesh.normals.is_empty() {
/// // normal = [x, y, z]
/// let normal = [
/// mesh.normals[i * 3],
/// mesh.normals[i * 3 + 1],
/// mesh.normals[i * 3 + 2],
/// ];
/// }
///
/// if !mesh.texcoords.is_empty() {
/// // texcoord = [u, v];
/// let texcoord = [mesh.texcoords[i * 2], mesh.texcoords[i * 2 + 1]];
/// }
/// ```
#[derive(Debug, Clone, Default)]
pub struct Mesh {
/// Flattened 3 component floating point vectors, storing positions of
/// vertices in the mesh.
pub positions: Vec<Float>,
/// Flattened 3 component floating point vectors, storing the color
/// associated with the vertices in the mesh.
///
/// Most meshes do not have vertex colors. If no vertex colors are specified
/// this will be empty.
pub vertex_color: Vec<Float>,
/// Flattened 3 component floating point vectors, storing normals of
/// vertices in the mesh.
///
/// Not all meshes have normals. If no normals are specified this will
/// be empty.
pub normals: Vec<Float>,
/// Flattened 2 component floating point vectors, storing texture
/// coordinates of vertices in the mesh.
///
/// Not all meshes have texture coordinates. If no texture coordinates are
/// specified this will be empty.
pub texcoords: Vec<Float>,
/// Indices for vertices of each face. If loaded with
/// [`triangulate`](LoadOptions::triangulate) set to `true` each face in the
/// mesh is a triangle.
///
/// Otherwise [`face_arities`](Mesh::face_arities) indicates how many
/// indices are used by each face.
///
/// When [`single_index`](LoadOptions::single_index) is set to `true`,
/// these indices are for *all* of the data in the mesh. Positions,
/// normals and texture coordinaes.
/// Otherwise normals and texture coordinates have *their own* indices,
/// each.
pub indices: Vec<u32>,
/// The number of vertices (arity) of each face. *Empty* if loaded with
/// `triangulate` set to `true` or if the mesh constists *only* of
/// triangles.
///
/// The offset for the starting index of a face can be found by iterating
/// through the `face_arities` until reaching the desired face, accumulating
/// the number of vertices used so far.
pub face_arities: Vec<u32>,
/// The indices for vertex colors. Only present when the
/// [`merging`](LoadOptions::merge_identical_points) feature is enabled, and
/// empty unless the corresponding load option is set to `true`.
#[cfg(feature = "merging")]
pub vertex_color_indices: Vec<u32>,
/// The indices for texture coordinates. Can be omitted by setting
/// `single_index` to `true`.
pub texcoord_indices: Vec<u32>,
/// The indices for normals. Can be omitted by setting `single_index` to
/// `true`.
pub normal_indices: Vec<u32>,
/// Optional material id associated with this mesh. The material id indexes
/// into the Vec of Materials loaded from the associated `MTL` file
pub material_id: Option<usize>,
}
/// Options for processing the mesh during loading.
///
/// Passed to [`load_obj()`], [`load_obj_buf()`] and [`load_obj_buf_async()`].
///
/// By default, all of these are `false`. With those settings, the data you get
/// represents the original data in the input file/buffer as closely as
/// possible.
///
/// Use the [init struct pattern](https://xaeroxe.github.io/init-struct-pattern/) to set individual options:
/// ```ignore
/// LoadOptions {
/// single_index: true,
/// ..Default::default()
/// }
/// ```
///
/// There are convenience `const`s for the most common cases:
///
/// * [`GPU_LOAD_OPTIONS`] – if you display meshes on the GPU/in realtime.
///
/// * [`OFFLINE_RENDERING_LOAD_OPTIONS`] – if you're rendering meshes with e.g.
/// an offline path tracer or the like.
#[cfg_attr(feature = "arbitrary", derive(arbitrary::Arbitrary))]
#[derive(Debug, Default, Clone, Copy)]
pub struct LoadOptions {
/// Merge identical positions.
///
/// This is usually what you want if you intend to use the mesh in an
/// *offline rendering* context or to do further processing with
/// *topological operators*.
///
/// * This flag is *mutually exclusive* with
/// [`single_index`](LoadOptions::single_index) and will lead to a
/// [`InvalidLoadOptionConfig`](LoadError::InvalidLoadOptionConfig) error
/// if both are set to `true`.
///
/// * If adjacent faces share vertices that have separate `indices` but the
/// same position in 3D they will be merged into a single vertex and the
/// resp. `indices` changed.
///
/// * Topolgy may change as a result (faces may become *connected* in the
/// index).
#[cfg(feature = "merging")]
pub merge_identical_points: bool,
/// Normal & texture coordinates will be reordered to allow omitting their
/// indices.
///
/// * This flag is *mutually exclusive* with
/// [`single_index`](LoadOptions::single_index) and will lead to an
/// [`InvalidLoadOptionConfig`](LoadError::InvalidLoadOptionConfig) error
/// if both are set to `true`.
///
/// * The resulting [`Mesh`]'s `normal_indices` and/or `texcoord_indices`
/// will be empty.
///
/// * *Per-vertex* normals and/or texture_coordinates will be reordered to
/// match the `Mesh`'s `indices`.
///
/// * *Per-vertex-per-face* normals and/or texture coordinates indices will
/// be `[0, 1, 2, ..., n]`. I.e.:
///
/// ```ignore
/// // If normals where specified per-vertex-per-face:
/// assert!(mesh.indices.len() == mesh.normals.len() / 3);
///
/// for index in 0..mesh.indices.len() {
/// println!("Normal n is {}, {}, {}",
/// mesh.normals[index * 3 + 0],
/// mesh.normals[index * 3 + 1],
/// mesh.normals[index * 3 + 2]
/// );
/// }
/// ```
#[cfg(feature = "reordering")]
pub reorder_data: bool,
/// Create a single index.
///
/// This is usually what you want if you are loading the mesh to display in
/// a *realtime* (*GPU*) context.
///
/// * This flag is *mutually exclusive* with both
/// [`merge_identical_points`](LoadOptions::merge_identical_points) and
/// [`reorder_data`](LoadOptions::reorder_data) resp. and will lead to a
/// [`InvalidLoadOptionConfig`](LoadError::InvalidLoadOptionConfig) error
/// if both it and either of the two other are set to `true`.
///
/// * Vertices may get duplicated to match the granularity
/// (*per-vertex-per-face*) of normals and/or texture coordinates.
///
/// * Topolgy may change as a result (faces may become *disconnected* in the
/// index).
///
/// * The resulting [`Mesh`]'s [`normal_indices`](Mesh::normal_indices) and
/// [`texcoord_indices`](Mesh::texcoord_indices) will be empty.
pub single_index: bool,
/// Triangulate all faces.
///
/// * Points (one point) and lines (two points) are blown up to zero area
/// triangles via point duplication. Except if `ignore_points` or
/// `ignore_lines` is/are set to `true`, resp.
///
/// * The resulting `Mesh`'s [`face_arities`](Mesh::face_arities) will be
/// empty as all faces are guranteed to have arity `3`.
///
/// * Only polygons that are trivially convertible to triangle fans are
/// supported. Arbitrary polygons may not behave as expected. The best
/// solution would be to convert your mesh to solely consist of triangles
/// in your modeling software.
pub triangulate: bool,
/// Ignore faces containing only a single vertex (points).
///
/// This is usually what you want if you do *not* intend to make special use
/// of the point data (e.g. as particles etc.).
///
/// Polygon meshes that contain faces with one vertex only usually do so
/// because of bad topology.
pub ignore_points: bool,
/// Ignore faces containing only two vertices (lines).
///
/// This is usually what you want if you do *not* intend to make special use
/// of the line data (e.g. as wires/ropes etc.).
///
/// Polygon meshes that contains faces with two vertices only usually do so
/// because of bad topology.
pub ignore_lines: bool,
}
impl LoadOptions {
/// Checks if the given `LoadOptions` do not contain mutually exclusive flag
/// settings.
///
/// This is called by [`load_obj()`]/[`load_obj_buf()`] in any case. This
/// method is only exposed for scenarios where you want to do this check
/// yourself.
pub fn is_valid(&self) -> bool {
// A = single_index, B = merge_identical_points, C = reorder_data
// (A ∧ ¬B) ∨ (A ∧ ¬C) -> A ∧ ¬(B ∨ C)
#[allow(unused_mut)]
let mut other_flags = false;
#[cfg(feature = "merging")]
{
other_flags = other_flags || self.merge_identical_points;
}
#[cfg(feature = "reordering")]
{
other_flags = other_flags || self.reorder_data;
}
(self.single_index != other_flags) || (!self.single_index && !other_flags)
}
}
/// A named model within the file.
///
/// Associates some mesh with a name that was specified with an `o` or `g`
/// keyword in the `OBJ` file.
#[derive(Clone, Debug)]
pub struct Model {
/// [`Mesh`] used by the model containing its geometry.
pub mesh: Mesh,
/// Name assigned to this `Mesh`.
pub name: String,
}
impl Model {
/// Create a new model, associating a name with a [`Mesh`].
pub fn new(mesh: Mesh, name: String) -> Model {
Model { mesh, name }
}
}
/// A material that may be referenced by one or more [`Mesh`]es.
///
/// Standard `MTL` attributes are supported. Any unrecognized parameters will be
/// stored as key-value pairs in the `unknown_param`
/// [`HashMap`](std::collections::HashMap), which maps the unknown parameter to
/// the value set for it.
///
/// No path is pre-pended to the texture file names specified in the `MTL` file.
#[derive(Clone, Debug, Default)]
pub struct Material {
/// Material name as specified in the `MTL` file.
pub name: String,
/// Ambient color of the material.
pub ambient: Option<[Float; 3]>,
/// Diffuse color of the material.
pub diffuse: Option<[Float; 3]>,
/// Specular color of the material.
pub specular: Option<[Float; 3]>,
/// Material shininess attribute. Also called `glossiness`.
pub shininess: Option<Float>,
/// Dissolve attribute is the alpha term for the material. Referred to as
/// dissolve since that's what the `MTL` file format docs refer to it as.
pub dissolve: Option<Float>,
/// Optical density also known as index of refraction. Called
/// `optical_density` in the `MTL` specc. Takes on a value between 0.001
/// and 10.0. 1.0 means light does not bend as it passes through
/// the object.
pub optical_density: Option<Float>,
/// Name of the ambient texture file for the material.
pub ambient_texture: Option<String>,
/// Name of the diffuse texture file for the material.
pub diffuse_texture: Option<String>,
/// Name of the specular texture file for the material.
pub specular_texture: Option<String>,
/// Name of the normal map texture file for the material.
pub normal_texture: Option<String>,
/// Name of the shininess map texture file for the material.
pub shininess_texture: Option<String>,
/// Name of the alpha/opacity map texture file for the material.
///
/// Referred to as `dissolve` to match the `MTL` file format specification.
pub dissolve_texture: Option<String>,
/// The illumnination model to use for this material. The different
/// illumination models are specified in the [`MTL` spec](http://paulbourke.net/dataformats/mtl/).
pub illumination_model: Option<u8>,
/// Key value pairs of any unrecognized parameters encountered while parsing
/// the material.
pub unknown_param: HashMap<String, String>,
}
/// Possible errors that may occur while loading `OBJ` and `MTL` files.
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum LoadError {
OpenFileFailed,
ReadError,
UnrecognizedCharacter,
PositionParseError,
NormalParseError,
TexcoordParseError,
FaceParseError,
MaterialParseError,
InvalidObjectName,
InvalidPolygon,
FaceVertexOutOfBounds,
FaceTexCoordOutOfBounds,
FaceNormalOutOfBounds,
FaceColorOutOfBounds,
InvalidLoadOptionConfig,
GenericFailure,
}
impl fmt::Display for LoadError {
fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
let msg = match *self {
LoadError::OpenFileFailed => "open file failed",
LoadError::ReadError => "read error",
LoadError::UnrecognizedCharacter => "unrecognized character",
LoadError::PositionParseError => "position parse error",
LoadError::NormalParseError => "normal parse error",
LoadError::TexcoordParseError => "texcoord parse error",
LoadError::FaceParseError => "face parse error",
LoadError::MaterialParseError => "material parse error",
LoadError::InvalidObjectName => "invalid object name",
LoadError::InvalidPolygon => "invalid polygon",
LoadError::FaceVertexOutOfBounds => "face vertex index out of bounds",
LoadError::FaceTexCoordOutOfBounds => "face texcoord index out of bounds",
LoadError::FaceNormalOutOfBounds => "face normal index out of bounds",
LoadError::FaceColorOutOfBounds => "face vertex color index out of bounds",
LoadError::InvalidLoadOptionConfig => "mutually exclusive load options",
LoadError::GenericFailure => "generic failure",
};
f.write_str(msg)
}
}
impl Error for LoadError {}
/// A [`Result`] containing all the models loaded from the file and any
/// materials from referenced material libraries. Or an error that occured while
/// loading.
pub type LoadResult = Result<(Vec<Model>, Result<Vec<Material>, LoadError>), LoadError>;
/// A [`Result`] containing all the materials loaded from the file and a map of
/// `MTL` name to index. Or an error that occured while loading.
pub type MTLLoadResult = Result<(Vec<Material>, HashMap<String, usize>), LoadError>;
/// Struct storing indices corresponding to the vertex.
///
/// Some vertices may not have texture coordinates or normals, 0 is used to
/// indicate this as OBJ indices begin at 1
#[derive(Hash, Eq, PartialEq, PartialOrd, Ord, Debug, Copy, Clone)]
struct VertexIndices {
pub v: usize,
pub vt: usize,
pub vn: usize,
}
static MISSING_INDEX: usize = usize::MAX;
impl VertexIndices {
/// Parse the vertex indices from the face string.
///
/// Valid face strings are those that are valid for a Wavefront `OBJ` file.
///
/// Also handles relative face indices (negative values) which is why
/// passing the number of positions, texcoords and normals is required.
///
/// Returns `None` if the face string is invalid.
fn parse(
face_str: &str,
pos_sz: usize,
tex_sz: usize,
norm_sz: usize,
) -> Option<VertexIndices> {
let mut indices = [MISSING_INDEX; 3];
for i in face_str.split('/').enumerate() {
// Catch case of v//vn where we'll find an empty string in one of our splits
// since there are no texcoords for the mesh.
if !i.1.is_empty() {
match isize::from_str(i.1) {
Ok(x) => {
// Handle relative indices
*indices.get_mut(i.0)? = if x < 0 {
match i.0 {
0 => (pos_sz as isize + x) as _,
1 => (tex_sz as isize + x) as _,
2 => (norm_sz as isize + x) as _,
_ => return None, // Invalid number of elements for a face
}
} else {
(x - 1) as _
};
}
Err(_) => return None,
}
}
}
Some(VertexIndices {
v: indices[0],
vt: indices[1],
vn: indices[2],
})
}
}
/// Enum representing a face, storing indices for the face vertices.
#[derive(Debug)]
enum Face {
Point(VertexIndices),
Line(VertexIndices, VertexIndices),
Triangle(VertexIndices, VertexIndices, VertexIndices),
Quad(VertexIndices, VertexIndices, VertexIndices, VertexIndices),
Polygon(Vec<VertexIndices>),
}
/// Parse the float information from the words. Words is an iterator over the
/// float strings. Returns `false` if parsing failed.
fn parse_floatn(val_str: &mut SplitWhitespace, vals: &mut Vec<Float>, n: usize) -> bool {
let sz = vals.len();
for p in val_str.take(n) {
match FromStr::from_str(p) {
Ok(x) => vals.push(x),
Err(_) => return false,
}
}
// Require that we found the desired number of floats.
sz + n == vals.len()
}
/// Parse the a string into a float3 array, returns an error if parsing failed
fn parse_float3(val_str: SplitWhitespace) -> Result<[Float; 3], LoadError> {
let arr: [Float; 3] = val_str
.take(3)
.map(FromStr::from_str)
.collect::<Result<Vec<_>, _>>()
.map_err(|_| LoadError::MaterialParseError)?
.try_into()
.unwrap();
Ok(arr)
}
/// Parse the a string into a float value, returns an error if parsing failed
fn parse_float(val_str: Option<&str>) -> Result<Float, LoadError> {
val_str
.map(FromStr::from_str)
.map_or(Err(LoadError::MaterialParseError), |v| {
v.map_err(|_| LoadError::MaterialParseError)
})
}
/// Parse vertex indices for a face and append it to the list of faces passed.
///
/// Also handles relative face indices (negative values) which is why passing
/// the number of positions, texcoords and normals is required.
///
/// Returns `false` if an error occured parsing the face.
fn parse_face(
face_str: SplitWhitespace,
faces: &mut Vec<Face>,
pos_sz: usize,
tex_sz: usize,
norm_sz: usize,
) -> bool {
let mut indices = Vec::new();
for f in face_str {
match VertexIndices::parse(f, pos_sz, tex_sz, norm_sz) {
Some(v) => indices.push(v),
None => return false,
}
}
// Check what kind face we read and push it on
match indices.len() {
1 => faces.push(Face::Point(indices[0])),
2 => faces.push(Face::Line(indices[0], indices[1])),
3 => faces.push(Face::Triangle(indices[0], indices[1], indices[2])),
4 => faces.push(Face::Quad(indices[0], indices[1], indices[2], indices[3])),
_ => faces.push(Face::Polygon(indices)),
}
true
}
/// Add a vertex to a mesh by either re-using an existing index (e.g. it's in
/// the `index_map`) or appending the position, texcoord and normal as
/// appropriate and creating a new vertex.
fn add_vertex(
mesh: &mut Mesh,
index_map: &mut HashMap<VertexIndices, u32>,
vert: &VertexIndices,
pos: &[Float],
v_color: &[Float],
texcoord: &[Float],
normal: &[Float],
) -> Result<(), LoadError> {
match index_map.get(vert) {
Some(&i) => mesh.indices.push(i),
None => {
let v = vert.v;
if v.saturating_mul(3).saturating_add(2) >= pos.len() {
return Err(LoadError::FaceVertexOutOfBounds);
}
// Add the vertex to the mesh
mesh.positions.push(pos[v * 3]);
mesh.positions.push(pos[v * 3 + 1]);
mesh.positions.push(pos[v * 3 + 2]);
if !texcoord.is_empty() && vert.vt != MISSING_INDEX {
let vt = vert.vt;
if vt * 2 + 1 >= texcoord.len() {
return Err(LoadError::FaceTexCoordOutOfBounds);
}
mesh.texcoords.push(texcoord[vt * 2]);
mesh.texcoords.push(texcoord[vt * 2 + 1]);
}
if !normal.is_empty() && vert.vn != MISSING_INDEX {
let vn = vert.vn;
if vn * 3 + 2 >= normal.len() {
return Err(LoadError::FaceNormalOutOfBounds);
}
mesh.normals.push(normal[vn * 3]);
mesh.normals.push(normal[vn * 3 + 1]);
mesh.normals.push(normal[vn * 3 + 2]);
}
if !v_color.is_empty() {
if v * 3 + 2 >= v_color.len() {
return Err(LoadError::FaceColorOutOfBounds);
}
mesh.vertex_color.push(v_color[v * 3]);
mesh.vertex_color.push(v_color[v * 3 + 1]);
mesh.vertex_color.push(v_color[v * 3 + 2]);
}
let next = index_map.len() as u32;
mesh.indices.push(next);
index_map.insert(*vert, next);
}
}
Ok(())
}
/// Export a list of faces to a mesh and return it, optionally converting quads
/// to tris.
fn export_faces(
pos: &[Float],
v_color: &[Float],
texcoord: &[Float],
normal: &[Float],
faces: &[Face],
mat_id: Option<usize>,
load_options: &LoadOptions,
) -> Result<Mesh, LoadError> {
let mut index_map = HashMap::new();
let mut mesh = Mesh {
material_id: mat_id,
..Default::default()
};
let mut is_all_triangles = true;
for f in faces {
// Optimized paths for Triangles and Quads, Polygon handles the general case of
// an unknown length triangle fan.
match *f {
Face::Point(ref a) => {
if !load_options.ignore_points {
add_vertex(&mut mesh, &mut index_map, a, pos, v_color, texcoord, normal)?;
if load_options.triangulate {
add_vertex(&mut mesh, &mut index_map, a, pos, v_color, texcoord, normal)?;
add_vertex(&mut mesh, &mut index_map, a, pos, v_color, texcoord, normal)?;
} else {
is_all_triangles = false;
mesh.face_arities.push(1);
}
}
}
Face::Line(ref a, ref b) => {
if !load_options.ignore_lines {
add_vertex(&mut mesh, &mut index_map, a, pos, v_color, texcoord, normal)?;
add_vertex(&mut mesh, &mut index_map, b, pos, v_color, texcoord, normal)?;
if load_options.triangulate {
add_vertex(&mut mesh, &mut index_map, b, pos, v_color, texcoord, normal)?;
} else {
is_all_triangles = false;
mesh.face_arities.push(2);
}
}
}
Face::Triangle(ref a, ref b, ref c) => {
add_vertex(&mut mesh, &mut index_map, a, pos, v_color, texcoord, normal)?;
add_vertex(&mut mesh, &mut index_map, b, pos, v_color, texcoord, normal)?;
add_vertex(&mut mesh, &mut index_map, c, pos, v_color, texcoord, normal)?;
if !load_options.triangulate {
mesh.face_arities.push(3);
}
}
Face::Quad(ref a, ref b, ref c, ref d) => {
add_vertex(&mut mesh, &mut index_map, a, pos, v_color, texcoord, normal)?;
add_vertex(&mut mesh, &mut index_map, b, pos, v_color, texcoord, normal)?;
add_vertex(&mut mesh, &mut index_map, c, pos, v_color, texcoord, normal)?;
if load_options.triangulate {
add_vertex(&mut mesh, &mut index_map, a, pos, v_color, texcoord, normal)?;
add_vertex(&mut mesh, &mut index_map, c, pos, v_color, texcoord, normal)?;
add_vertex(&mut mesh, &mut index_map, d, pos, v_color, texcoord, normal)?;
} else {
add_vertex(&mut mesh, &mut index_map, d, pos, v_color, texcoord, normal)?;
is_all_triangles = false;
mesh.face_arities.push(4);
}
}
Face::Polygon(ref indices) => {
if load_options.triangulate {
let a = indices.first().ok_or(LoadError::InvalidPolygon)?;
let mut b = indices.get(1).ok_or(LoadError::InvalidPolygon)?;
for c in indices.iter().skip(2) {
add_vertex(&mut mesh, &mut index_map, a, pos, v_color, texcoord, normal)?;
add_vertex(&mut mesh, &mut index_map, b, pos, v_color, texcoord, normal)?;
add_vertex(&mut mesh, &mut index_map, c, pos, v_color, texcoord, normal)?;
b = c;
}
} else {
for i in indices.iter() {
add_vertex(&mut mesh, &mut index_map, i, pos, v_color, texcoord, normal)?;
}
is_all_triangles = false;
mesh.face_arities.push(indices.len() as u32);
}
}
}
}
if is_all_triangles {
// This is a triangle-only mesh.
mesh.face_arities = Vec::new();
}
Ok(mesh)
}
/// Add a vertex to a mesh by either re-using an existing index (e.g. it's in
/// the `index_map`) or appending the position, texcoord and normal as
/// appropriate and creating a new vertex.
#[allow(clippy::too_many_arguments)]
#[inline]
fn add_vertex_multi_index(
mesh: &mut Mesh,
index_map: &mut HashMap<usize, u32>,
normal_index_map: &mut HashMap<usize, u32>,
texcoord_index_map: &mut HashMap<usize, u32>,
vert: &VertexIndices,
pos: &[Float],
v_color: &[Float],
texcoord: &[Float],
normal: &[Float],
) -> Result<(), LoadError> {
match index_map.get(&vert.v) {
Some(&i) => mesh.indices.push(i),
None => {
let vertex = vert.v;
if vertex.saturating_mul(3).saturating_add(2) >= pos.len() {
return Err(LoadError::FaceVertexOutOfBounds);
}
// Add the vertex to the mesh.
mesh.positions.push(pos[vertex * 3]);
mesh.positions.push(pos[vertex * 3 + 1]);
mesh.positions.push(pos[vertex * 3 + 2]);
let next = index_map.len() as u32;
mesh.indices.push(next);
index_map.insert(vertex, next);
// Also add vertex colors to the mesh if present.
if !v_color.is_empty() {
let vertex = vert.v;
if vertex * 3 + 2 >= v_color.len() {
return Err(LoadError::FaceColorOutOfBounds);