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
//! The crate's error type.
//!
//! Nothing in three.js corresponds to this file: JavaScript throws, and the
//! port's public entry points return `Result` instead (issue #9, and decision 4
//! in `docs/api.md`). One enum covers the whole crate, so a caller writes one
//! `match` — or none, since [`Error`] implements [`std::error::Error`].
//!
//! Panics are kept for invariants the caller cannot reach: a light list that
//! only holds lights, a texture the renderer uploaded a moment earlier. Every
//! such message starts `three-rs:` and names the invariant.
use std::fmt;
use std::path::PathBuf;
use crate::animation::property_binding::ParseTrackNameError;
/// Everything the public API of `three-rs` can fail with.
///
/// Non-exhaustive: new variants are added as more of the port's surface stops
/// panicking, and matching code should carry a `_` arm.
#[derive(Debug)]
#[non_exhaustive]
pub enum Error {
/// A file a loader was pointed at could not be read.
Io {
/// The file that could not be read.
path: PathBuf,
/// What the OS said.
source: std::io::Error,
},
/// A JSON document could not be parsed. `path` is `None` when the caller
/// handed the JSON over directly, as `BufferGeometryLoader::parse` does.
Json {
/// The file the JSON was read from, when there was one.
path: Option<PathBuf>,
/// What `serde_json` said.
source: serde_json::Error,
},
/// An image file the decoder rejected.
Image {
/// The image file.
path: PathBuf,
/// Why the decoder rejected it.
reason: String,
},
/// A Radiance RGBE (`.hdr`) file the decoder rejected. `reason` is
/// three.js' own `rgbe_error()` message, less its `THREE.HDRLoader: `
/// prefix.
Rgbe {
/// The decoder's message.
reason: String,
},
/// A KTX 2.0 file `KTX2Loader` rejected, or one it cannot transcode for
/// this device. `reason` is three.js' own message, less its
/// `THREE.KTX2Loader: ` prefix.
Ktx2 {
/// The decoder's message.
reason: String,
},
/// A colour lookup table `LUTCubeLoader`, `LUT3dlLoader` or
/// `LUTImageLoader` rejected. `loader` is the three.js class name and
/// `reason` its own message, less the `THREE.<loader>: ` prefix.
Lut {
/// The three.js loader class, e.g. `"LUTCubeLoader"`.
loader: &'static str,
/// The loader's message.
reason: String,
},
/// A file names a type, format or encoding this port does not implement.
/// `what` says which field it was read from.
UnsupportedFormat {
/// The field the value was read from.
what: &'static str,
/// The unsupported value.
value: String,
},
/// A texture type that is not a legal depth format (`gpu_format`) or not a
/// legal colour format (`color_gpu_format`).
UnsupportedTextureType {
/// Which check failed (`gpu_format` or `color_gpu_format`).
what: &'static str,
/// The texture type that failed it.
texture_type: crate::textures::TextureType,
},
/// A glTF asset the loader could not make sense of.
Gltf(GltfError),
/// `new KeyframeTrack()` with an empty `times` array.
NoKeyframes {
/// The track's name.
track: String,
},
/// A track type name that no `KeyframeTrack` subclass answers to.
UnsupportedTrackType {
/// The type name that was not recognized.
name: String,
},
/// An interpolation mode this track's value type does not support, where
/// the value type's own default does not support it either.
UnsupportedInterpolation {
/// The track's value type (`"vector"`, `"quaternion"`, …).
value_type: &'static str,
/// The track's name.
track: String,
},
/// A track name `PropertyBinding` cannot parse.
TrackName(ParseTrackNameError),
/// No adapter to render on — no Vulkan device natively, or
/// `navigator.gpu.requestAdapter()` resolving to null in a browser.
/// `wanted` is the `THREE_RS_ADAPTER_NAME` filter, when one was set and
/// matched nothing; it is always `None` on wasm32, where the browser picks
/// the adapter and there is nothing to filter.
NoAdapter {
/// The `THREE_RS_ADAPTER_NAME` filter that matched nothing, if one was set.
wanted: Option<String>,
},
/// `Renderer::new()` on wasm32 with nothing handed to
/// `renderer::adopt_device()` first. Device creation is asynchronous in a
/// browser and the examples' `init()` is not, so the host must create the
/// device and park it before the first `Renderer::new()`; see
/// `renderer::adopt_device`. wasm32 only.
#[cfg(target_arch = "wasm32")]
NoAdoptedDevice,
/// `adapter.request_device()` failed.
Device(wgpu::RequestDeviceError),
/// Reading pixels back off the GPU failed; `reason` is what wgpu said.
Readback {
/// What wgpu said.
reason: String,
},
/// A material field that is set but that no part of the port reads for
/// this kind of material — see
/// [`MeshBasicNodeMaterial::check_supported`](crate::materials::MeshBasicNodeMaterial::check_supported)
/// and the audit in `docs/api.md`. `field` is the three.js name.
Unsupported {
/// The three.js field name.
field: &'static str,
/// The material kind it was set on.
kind: crate::materials::MaterialKind,
},
}
/// What went wrong inside a glTF asset, as far as the loader reads it.
#[derive(Debug)]
#[non_exhaustive]
pub enum GltfError {
/// A JSON chunk, or a `.gltf` file, that is not UTF-8.
NotUtf8,
/// `asset.version` is not 2.x.
UnsupportedVersion(String),
/// The 12-byte GLB header has the wrong magic.
BadHeader,
/// A GLB written against the draft container format.
LegacyBinary,
/// A GLB chunk that runs past the end of the file.
TruncatedChunk,
/// A GLB with no JSON chunk.
NoJsonChunk,
/// A buffer with no `uri` in a GLB that has no BIN chunk.
NoBinChunk,
/// A field a definition cannot be read without (`accessor.type`,
/// `sampler.input`, …). `what` names it.
MissingField {
/// The missing field's name.
what: &'static str,
},
/// An index into one of the asset's arrays that is not there. `kind` is the
/// array (`accessor`, `bufferView`, `buffer`, `mesh`).
MissingIndex {
/// The array the index was into.
kind: &'static str,
/// The index that was not there.
index: usize,
},
/// An accessor `componentType` the port does not read.
UnsupportedComponentType(i64),
/// An accessor `type` the port does not read.
UnsupportedAccessorType(String),
/// A `data:` URI that is not `data:<mime>;base64,<payload>`.
BadDataUri(String),
/// A character that is not in the base64 alphabet.
BadBase64(char),
/// An extension in `extensionsRequired` that the port does not read.
/// three.js only warns here (`'Unknown extension'`) and then decodes
/// nothing, which on this stack is a silent wrong picture, so the port
/// refuses the asset instead.
UnsupportedRequiredExtension(String),
/// A `KHR_draco_mesh_compression` primitive that does not decode. `mesh`
/// and `primitive` locate it; `reason` is the decoder's, or what
/// `DRACOLoader` would have thrown on.
Draco {
/// The mesh index.
mesh: usize,
/// The primitive index within `mesh`.
primitive: usize,
/// The decoder's message.
reason: String,
},
/// A bufferView whose byte range runs past the end of its buffer.
BufferViewOutOfRange {
/// The bufferView's index.
index: usize,
},
/// An `EXT_meshopt_compression` bufferView that does not decode.
/// `reason` is the decoder's, or the extension rule it breaks.
Meshopt {
/// The bufferView's index.
buffer_view: usize,
/// The decoder's message, or the extension rule that was broken.
reason: String,
},
}
impl fmt::Display for Error {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::Io { path, source } => write!(f, "cannot read {}: {source}", path.display()),
Self::Json {
path: Some(path),
source,
} => write!(f, "cannot parse {}: {source}", path.display()),
Self::Json { path: None, source } => write!(f, "cannot parse JSON: {source}"),
Self::Image { path, reason } => {
write!(f, "cannot decode {}: {reason}", path.display())
}
Self::Rgbe { reason } => write!(f, "THREE.HDRLoader: {reason}"),
Self::Ktx2 { reason } => write!(f, "THREE.KTX2Loader: {reason}"),
Self::Lut { loader, reason } => write!(f, "THREE.{loader}: {reason}"),
Self::UnsupportedFormat { what, value } => {
write!(f, "unsupported {what}: {value}")
}
Self::UnsupportedTextureType { what, texture_type } => {
write!(f, "{texture_type:?} is not a {what} texture type")
}
Self::Gltf(error) => write!(f, "THREE.GLTFLoader: {error}"),
Self::NoKeyframes { track } => {
write!(f, "no keyframes in track named {track}")
}
Self::UnsupportedTrackType { name } => write!(f, "unsupported trackType: {name}"),
Self::UnsupportedInterpolation { value_type, track } => write!(
f,
"unsupported interpolation for {value_type} keyframe track named {track}"
),
Self::TrackName(error) => write!(f, "{error}"),
Self::NoAdapter { wanted: Some(name) } => {
write!(f, "no Vulkan adapter matching THREE_RS_ADAPTER_NAME={name}")
}
Self::NoAdapter { wanted: None } => write!(f, "no Vulkan adapter found"),
#[cfg(target_arch = "wasm32")]
Self::NoAdoptedDevice => write!(
f,
"no device was adopted: call three_rs::renderer::adopt_device() \
before Renderer::new()"
),
Self::Device(source) => write!(f, "cannot create the device: {source}"),
Self::Readback { reason } => write!(f, "cannot read pixels back: {reason}"),
Self::Unsupported { field, kind } => {
write!(
f,
"material.{field} is not supported on a {kind:?} material"
)
}
}
}
}
impl fmt::Display for GltfError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::NotUtf8 => write!(f, "not UTF-8 JSON"),
Self::UnsupportedVersion(version) => {
write!(f, "unsupported asset version {version}")
}
Self::BadHeader => write!(f, "unsupported glTF-Binary header"),
Self::LegacyBinary => write!(f, "legacy binary file detected"),
Self::TruncatedChunk => write!(f, "truncated glTF-Binary chunk"),
Self::NoJsonChunk => write!(f, "glTF-Binary without JSON content"),
Self::NoBinChunk => write!(f, "glTF-Binary without BIN chunk"),
Self::MissingField { what } => write!(f, "no {what}"),
Self::MissingIndex { kind, index } => write!(f, "no {kind} {index}"),
Self::UnsupportedComponentType(value) => {
write!(f, "unsupported componentType {value}")
}
Self::UnsupportedAccessorType(name) => write!(f, "unsupported accessor type {name}"),
Self::BadDataUri(uri) => write!(f, "bad data URI {uri}"),
Self::BadBase64(c) => write!(f, "bad base64 character {c:?}"),
Self::UnsupportedRequiredExtension(name) => {
write!(f, "unknown required extension \"{name}\"")
}
Self::Draco {
mesh,
primitive,
reason,
} => write!(
f,
"mesh {mesh} primitive {primitive}: THREE.DRACOLoader: {reason}"
),
Self::BufferViewOutOfRange { index } => {
write!(f, "bufferView {index} runs past the end of its buffer")
}
Self::Meshopt {
buffer_view,
reason,
} => write!(f, "bufferView {buffer_view}: MeshoptDecoder: {reason}"),
}
}
}
impl std::error::Error for Error {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
match self {
Self::Io { source, .. } => Some(source),
Self::Json { source, .. } => Some(source),
Self::Gltf(source) => Some(source),
Self::TrackName(source) => Some(source),
Self::Device(source) => Some(source),
_ => None,
}
}
}
impl std::error::Error for GltfError {}
impl From<GltfError> for Error {
fn from(error: GltfError) -> Self {
Self::Gltf(error)
}
}
impl From<ParseTrackNameError> for Error {
fn from(error: ParseTrackNameError) -> Self {
Self::TrackName(error)
}
}
impl From<wgpu::RequestDeviceError> for Error {
fn from(error: wgpu::RequestDeviceError) -> Self {
Self::Device(error)
}
}
impl Error {
/// `std::fs::read`'s error, with the path that produced it.
pub(crate) fn io(path: impl Into<PathBuf>, source: std::io::Error) -> Self {
Self::Io {
path: path.into(),
source,
}
}
/// A decode failure, with the file that produced it.
pub(crate) fn image(path: impl Into<PathBuf>, reason: impl Into<String>) -> Self {
Self::Image {
path: path.into(),
reason: reason.into(),
}
}
}