Skip to content

Import a 3D Model and automatically assign and export animations

TypeScript

Break apart GLTF loading a bit more

Scott Petrovic76e68b70f8a8
diff --git a/src/lib/processes/load-model/StepLoadModel.ts b/src/lib/processes/load-model/StepLoadModel.ts
index dedcd66..0a718d8 100644
--- a/src/lib/processes/load-model/StepLoadModel.ts
+++ b/src/lib/processes/load-model/StepLoadModel.ts
@@ -161,33 +161,38 @@ export class StepLoadModel extends EventTarget {
this.process_loaded_scene(loaded_scene)
})
} else if (file_extension === 'zip') {
- // Use ZipGLTFLoader for ZIP files
- const handle_zip = (buffer: ArrayBuffer): void => {
- const zip_loader = new ZipGLTFLoader(this.gltf_loader)
-
- zip_loader.loadFromZip(buffer, (scene) => {
- this.process_loaded_scene(scene)
- }, (err) => {
- console.error('Failed to load GLTF from ZIP:', err)
- }).catch((err) => { console.error('Error loading ZIP:', err) })
- }
-
- if (typeof model_file_path === 'string' && model_file_path.startsWith('data:')) {
- fetch(model_file_path)
- .then(async res => await res.arrayBuffer())
- .then(buffer => { handle_zip(buffer) })
- .catch(err => { console.error('Failed to fetch ZIP data:', err) })
- } else if (model_file_path instanceof ArrayBuffer) {
- handle_zip(model_file_path)
- } else {
- console.error('ZIP file data is not in a supported format')
- }
- // end logic for handing zip
+ this.handle_zip_file(model_file_path)
} else {
console.error('Unsupported file format to load. Only acccepts FBX, (ZIP)GLTF+BIN, GLB:', model_file_path)
}
}
+ /**
+ * Handles loading a model from a ZIP file with GLTF data
+ * supporting both data URLs and ArrayBuffer input.
+ */
+ private handle_zip_file (model_file_path: string | ArrayBuffer | null): void {
+ // Handle loading a ZIP file with GLTF data inside it
+ const handle_zip = (buffer: ArrayBuffer): void => {
+ const zip_loader = new ZipGLTFLoader(this.gltf_loader)
+ zip_loader.load_from_zip(buffer, (scene) => {
+ this.process_loaded_scene(scene) // loaded successfully...continue
+ }, (err) => {
+ console.error('Failed to load GLTF from ZIP:', err)
+ }).catch((err) => { console.error('Error loading ZIP:', err) })
+ }
+
+ // support both data URLs
+ if (typeof model_file_path === 'string' && model_file_path.startsWith('data:')) {
+ fetch(model_file_path)
+ .then(async res => await res.arrayBuffer())
+ .then(buffer => { handle_zip(buffer) })
+ .catch(err => { console.error('Failed to fetch ZIP data:', err) })
+ } else {
+ console.error('ZIP file data is not in a supported format')
+ }
+ }
+
private process_loaded_scene (loaded_scene: Scene): void {
this.original_model_data = loaded_scene.clone()
this.original_model_data.name = 'Cloned Scene'
diff --git a/src/lib/processes/load-model/ZipGLTFLoader.ts b/src/lib/processes/load-model/ZipGLTFLoader.ts
index abba55d..131c2f4 100644
--- a/src/lib/processes/load-model/ZipGLTFLoader.ts
+++ b/src/lib/processes/load-model/ZipGLTFLoader.ts
@@ -13,85 +13,37 @@ export class ZipGLTFLoader {
this.loader = loader
}
- async loadFromZip (zipData: ArrayBuffer, onLoad: (scene: Scene) => void, onError?: (err: any) => void): Promise<void> {
+ /**
+ * Main entry: Loads a GLTF (with BIN and textures) from a ZIP file buffer, using in-memory URLs for all assets.
+ */
+ async load_from_zip (zipData: ArrayBuffer,
+ onLoad: (scene: Scene) => void,
+ onError?: (err: any) => void
+ ): Promise<void> {
try {
+ // 1. Load and scan the ZIP for GLTF and BIN files
const zip = await JSZip.loadAsync(zipData)
- let gltf_file: any = null
- let bin_file: any = null
- let gltf_filename = ''
- let bin_filename = ''
- zip.forEach((relativePath, file) => {
- const lower = relativePath.toLowerCase()
- if (lower.endsWith('.gltf')) {
- gltf_file = file
- gltf_filename = relativePath
- } else if (lower.endsWith('.bin')) {
- bin_file = file
- bin_filename = relativePath
- }
- })
- if (!gltf_file) {
- throw new Error('No GLTF file found in ZIP')
- }
- const gltf_text = await gltf_file.async('text')
- const gltf_json = JSON.parse(gltf_text)
- if (bin_file && gltf_json.buffers && gltf_json.buffers[0]) {
- const binNameOnly = bin_filename.split('/').pop()
- gltf_json.buffers[0].uri = binNameOnly
- }
- // Map all relevant files by filename only (case-insensitive, handle spaces)
- const fileMap: Record<string, Uint8Array> = {}
- const filePromises = Object.keys(zip.files).map(async (filename) => {
- const file = zip.files[filename]
- if (!file.dir) {
- const nameOnly = filename.split('/').pop() ?? filename
- if (/\.(bin|gltf|png|jpg|jpeg|webp)$/i.test(nameOnly)) {
- // Map by original, lowercased, and decoded name
- const buffer = new Uint8Array(await file.async('arraybuffer'))
- fileMap[nameOnly] = buffer
- fileMap[nameOnly.toLowerCase()] = buffer
- try {
- const decoded = decodeURIComponent(nameOnly)
- fileMap[decoded] = buffer
- fileMap[decoded.toLowerCase()] = buffer
- } catch {}
- }
- }
- })
- await Promise.all(filePromises)
- // Patch loader to use in-memory blobs for all referenced files
- this.loader.manager.setURLModifier((url: string) => {
- const cleanUrl = url.split(/[?#]/)[0]
- let nameOnly = cleanUrl.split('/').pop() ?? cleanUrl
- // Try original, lowercased, and decoded
- let buffer = fileMap[nameOnly]
- if (!buffer) buffer = fileMap[nameOnly.toLowerCase()]
- if (!buffer) {
- try {
- const decoded = decodeURIComponent(nameOnly)
- buffer = fileMap[decoded] || fileMap[decoded.toLowerCase()]
- } catch {}
- }
- if (buffer) {
- let mime = 'application/octet-stream'
- if (/\.png$/i.test(nameOnly)) mime = 'image/png'
- else if (/\.jpe?g$/i.test(nameOnly)) mime = 'image/jpeg'
- else if (/\.webp$/i.test(nameOnly)) mime = 'image/webp'
- else if (/\.gltf$/i.test(nameOnly)) mime = 'application/json'
- const blob = new Blob([buffer], { type: mime })
- return URL.createObjectURL(blob)
- }
- return url
- })
- // Load the GLTF from the in-memory JSON
- const gltfBlob = new Blob([JSON.stringify(gltf_json)], { type: 'application/json' })
- const gltfUrl = URL.createObjectURL(gltfBlob)
+ const { gltfFile, binFile, gltfFilename, binFilename } = this.find_gltf_files(zip)
+ if (!gltfFile) throw new Error('No GLTF file found in ZIP')
+
+ // 2. Parse GLTF JSON and patch buffer URI if needed
+ const gltf_json: any = await this.parse_gltf_json(gltfFile, binFile, binFilename)
+
+ // 3. Build a map of all relevant files (textures, bin, gltf) by filename
+ const file_map: Record<string, Uint8Array> = await this.build_file_map(zip)
+
+ // 4. Patch loader to use in-memory blobs for all referenced files
+ this.loader.manager.setURLModifier(this.make_url_modifier(file_map))
+
+ // 5. Load the GLTF from the in-memory JSON blob
+ const gltf_blob = new Blob([JSON.stringify(gltf_json)], { type: 'application/json' })
+ const gltf_url = URL.createObjectURL(gltf_blob)
this.loader.load(
- gltfUrl,
+ gltf_url,
(gltf) => {
const loaded_scene: Scene = gltf.scene
onLoad(loaded_scene)
- URL.revokeObjectURL(gltfUrl)
+ URL.revokeObjectURL(gltf_url)
},
undefined,
(err) => {
@@ -102,4 +54,100 @@ export class ZipGLTFLoader {
if (onError != null) onError(err)
}
}
+
+ /**
+ * Scans the ZIP for .gltf and .bin files and returns their file objects and names.
+ */
+ private find_gltf_files (zip: JSZip): {
+ gltfFile: any, binFile: any, gltfFilename: string, binFilename: string
+ } {
+ let gltfFile: any = null
+ let binFile: any = null
+ let gltfFilename = ''
+ let binFilename = ''
+ zip.forEach((relativePath, file) => {
+ const lower = relativePath.toLowerCase()
+ if (lower.endsWith('.gltf')) {
+ gltfFile = file
+ gltfFilename = relativePath
+ } else if (lower.endsWith('.bin')) {
+ binFile = file
+ binFilename = relativePath
+ }
+ })
+ return { gltfFile, binFile, gltfFilename, binFilename }
+ }
+
+ /**
+ * Reads and parses the GLTF JSON, patching the buffer URI if a BIN file is present.
+ */
+ private async parse_gltf_json (gltfFile: any, binFile: any, binFilename: string): Promise<any> {
+ const gltf_text = await gltfFile.async('text')
+ const gltf_json = JSON.parse(gltf_text)
+ if (binFile && gltf_json.buffers && gltf_json.buffers[0]) {
+ const binNameOnly = binFilename.split('/').pop()
+ gltf_json.buffers[0].uri = binNameOnly
+ }
+ return gltf_json
+ }
+
+ /**
+ * Builds a map of all relevant files (textures, bin, gltf) by filename (case-insensitive, handles spaces).
+ */
+ private async build_file_map (zip: JSZip): Promise<Record<string, Uint8Array>> {
+ const fileMap: Record<string, Uint8Array> = {}
+ const filePromises = Object.keys(zip.files).map(async (filename) => {
+ const file = zip.files[filename]
+ if (!file.dir) {
+ const nameOnly = filename.split('/').pop() ?? filename
+ if (/\.(bin|gltf|png|jpg|jpeg|webp)$/i.test(nameOnly)) {
+ const buffer = new Uint8Array(await file.async('arraybuffer'))
+ // Map by original, lowercased, and decoded name
+ fileMap[nameOnly] = buffer
+ fileMap[nameOnly.toLowerCase()] = buffer
+ try {
+ const decoded = decodeURIComponent(nameOnly)
+ fileMap[decoded] = buffer
+ fileMap[decoded.toLowerCase()] = buffer
+ } catch {}
+ }
+ }
+ })
+ await Promise.all(filePromises)
+ return fileMap
+ }
+
+ /**
+ * Returns a URL modifier function for the loader, serving in-memory blobs for referenced files.
+ */
+ private make_url_modifier (file_map: Record<string, Uint8Array>): (url: string) => string {
+ return (url: string) => {
+ // Remove query/hash, get filename
+ const clean_url = url.split(/[?#]/)[0]
+ const name_only: string = clean_url.split('/').pop() ?? clean_url
+ // Try original, lowercased, and decoded
+ let buffer: Uint8Array | undefined = file_map[name_only]
+
+ if (!buffer) buffer = file_map[name_only.toLowerCase()]
+ if (!buffer) {
+ try {
+ const decoded = decodeURIComponent(name_only)
+ buffer = file_map[decoded] || file_map[decoded.toLowerCase()]
+ } catch {}
+ }
+
+ if (buffer) {
+ // Guess MIME type
+ let mime = 'application/octet-stream'
+ if (/\.png$/i.test(name_only)) mime = 'image/png'
+ else if (/\.jpe?g$/i.test(name_only)) mime = 'image/jpeg'
+ else if (/\.webp$/i.test(name_only)) mime = 'image/webp'
+ else if (/\.gltf$/i.test(name_only)) mime = 'application/json'
+ const blob = new Blob([buffer], { type: mime })
+ return URL.createObjectURL(blob)
+ }
+
+ return url
+ }
+ }
}