Skip to content

Import a 3D Model and automatically assign and export animations

TypeScript

Bake all the transforms on import and start with an analysis report

Scott Petrovica3da53c9abbc
diff --git a/src/create.html b/src/create.html
index 0accb8c..85005f1 100644
--- a/src/create.html
+++ b/src/create.html
@@ -100,6 +100,15 @@
</div>
<div id="load-skeleton-tools">
+
+ <button
+ class="link-button"
+ id="analyze-model-link"
+ >
+ Analyze Model data
+ </button>
+
+
<span>
<span style="max-width: 220px"
>Rotate Model to face front <br />
diff --git a/src/dialog.css b/src/dialog.css
index 1a21c0f..f625d0c 100644
--- a/src/dialog.css
+++ b/src/dialog.css
@@ -198,6 +198,136 @@
margin-top: 1rem;
}
+/* ── Model Analysis Dialog ── */
+
+.model-analysis-dialog .modal-dialog-content {
+ width: 90vw;
+ max-width: 1100px;
+}
+
+.model-analysis-dialog .modal-dialog-body {
+ padding: 1.5rem;
+}
+
+.model-analysis-dialog .model-analysis {
+ display: block;
+ text-align: left;
+}
+
+.model-analysis-dialog h3 {
+ font-size: 1.4rem;
+ margin: 2rem 0 0.5rem 0;
+}
+
+.model-analysis-dialog h3:first-child {
+ margin-top: 0;
+}
+
+.model-analysis-dialog .model-analysis-source {
+ margin: 0 0 1rem 0;
+ font-size: 1.1rem;
+}
+
+.model-analysis-dialog .model-analysis-note {
+ margin: 0 0 0.75rem 0;
+ font-size: 0.95rem;
+ opacity: 0.7;
+}
+
+.model-analysis-dialog .model-analysis-clean {
+ margin: 0;
+ padding: 0.75rem 1rem;
+ border-left: 3px solid var(--button-primary-bg);
+ background: var(--bg-primary);
+}
+
+.model-analysis-dialog .model-analysis-warnings {
+ margin: 0;
+ padding: 0 0 0 1.25rem;
+ display: block;
+}
+
+.model-analysis-dialog .model-analysis-warnings li {
+ display: list-item;
+ margin: 0 0 0.6rem 0;
+ font-size: 1.05rem;
+ line-height: 135%;
+}
+
+.model-analysis-dialog .model-analysis-affected {
+ display: block;
+ margin: 0.15rem 0 0 0;
+ font-size: 0.9rem;
+ opacity: 0.7;
+ font-style: italic;
+}
+
+.model-analysis-dialog .model-analysis-table-scroll {
+ display: block;
+ overflow-x: auto;
+ margin: 0;
+}
+
+.model-analysis-dialog .model-analysis-table {
+ border-collapse: collapse;
+ width: 100%;
+ margin: 0;
+ font-variant-numeric: tabular-nums;
+}
+
+.model-analysis-dialog .model-analysis-table th,
+.model-analysis-dialog .model-analysis-table td {
+ padding: 0.4rem 0.6rem;
+ margin: 0;
+ font-size: 0.95rem;
+ line-height: 130%;
+ text-align: left;
+ white-space: nowrap;
+ border-bottom: 1px solid var(--border-color);
+}
+
+.model-analysis-dialog .model-analysis-table thead th {
+ font-weight: 600;
+ opacity: 0.7;
+ border-bottom: 1px solid var(--text-primary);
+}
+
+.model-analysis-dialog .model-analysis-table tbody th {
+ font-weight: 400;
+ opacity: 0.7;
+}
+
+.model-analysis-dialog .model-analysis-row-flagged td {
+ background: color-mix(in srgb, var(--button-primary-bg) 12%, transparent);
+}
+
+.model-analysis-dialog .model-analysis-name {
+ display: block;
+ margin: 0;
+}
+
+.model-analysis-dialog .model-analysis-parent {
+ display: block;
+ margin: 0;
+ font-size: 0.85rem;
+ opacity: 0.6;
+}
+
+.model-analysis-dialog .model-analysis-chips {
+ display: flex;
+ flex-wrap: wrap;
+ gap: 0.5rem;
+ margin: 0;
+}
+
+.model-analysis-dialog .model-analysis-chip {
+ margin: 0;
+ padding: 0.3rem 0.7rem;
+ border-radius: 1rem;
+ font-size: 0.9rem;
+ background: var(--bg-primary);
+}
+
/* ── Download Success Dialog ── */
.survey-content {
diff --git a/src/lib/EventListeners.ts b/src/lib/EventListeners.ts
index a6261c6..bf4e70b 100644
--- a/src/lib/EventListeners.ts
+++ b/src/lib/EventListeners.ts
@@ -4,6 +4,7 @@ import { ProcessStep } from './enums/ProcessStep'
import { TransformSpace } from './enums/TransformSpace'
import { Utility } from './Utilities'
import { ModelCleanupUtility } from './processes/load-model/ModelCleanupUtility'
+import { ModelAnalysisReport } from './processes/load-model/ModelAnalysisReport'
import { DownloadSuccessDialog } from './components/download-success/DownloadSuccessDialog'
import { type Bone, type Material, type MeshBasicMaterial, type MeshPhongMaterial, type MeshStandardMaterial } from 'three'
@@ -209,6 +210,11 @@ export class EventListeners {
this.bootstrap.load_model_step.rotate_model_geometry('z', 90)
})
+ // show a breakdown of what was found in the imported file
+ this.bootstrap.ui.dom_analyze_model_link?.addEventListener('click', () => {
+ ModelAnalysisReport.show_dialog(this.bootstrap.load_model_step.get_import_analysis())
+ })
+
// Reset model position to import state
this.bootstrap.ui.dom_reset_model_position_button?.addEventListener('click', () => {
this.bootstrap.load_model_step.reset_model_position()
diff --git a/src/lib/UI.ts b/src/lib/UI.ts
index 4ec689d..add70a4 100644
--- a/src/lib/UI.ts
+++ b/src/lib/UI.ts
@@ -21,6 +21,7 @@ export class UI {
dom_rotate_model_z_button: HTMLButtonElement | null = null
dom_reset_model_position_button: HTMLButtonElement | null = null
dom_auto_align_model_button: HTMLButtonElement | null = null
+ dom_analyze_model_link: HTMLButtonElement | null = null
dom_load_skeleton_tools: HTMLElement | null = null
dom_load_skeleton_button: HTMLButtonElement | null = null
@@ -148,6 +149,7 @@ export class UI {
this.dom_rotate_model_z_button = document.querySelector('#rotate-model-z-button')
this.dom_reset_model_position_button = document.querySelector('#reset-model-position-button')
this.dom_auto_align_model_button = document.querySelector('#auto-align-model-button')
+ this.dom_analyze_model_link = document.querySelector('#analyze-model-link')
// UI controls for loading/working with skeleton
this.dom_load_skeleton_tools = document.querySelector('#load-skeleton-tools')
diff --git a/src/lib/processes/load-model/ModelAnalysisReport.test.ts b/src/lib/processes/load-model/ModelAnalysisReport.test.ts
new file mode 100644
index 0000000..38f984e
--- /dev/null
+++ b/src/lib/processes/load-model/ModelAnalysisReport.test.ts
@@ -0,0 +1,166 @@
+import { describe, it, expect } from 'vitest'
+import { BoxGeometry, Group, Mesh, MeshStandardMaterial, Scene } from 'three'
+import { ModelAnalysisReport, type SceneSnapshot } from './ModelAnalysisReport'
+
+/** A 1x1x1 box mesh with a name, so snapshots have something real to measure. */
+function make_mesh (name: string): Mesh {
+ const mesh = new Mesh(new BoxGeometry(1, 1, 1), new MeshStandardMaterial())
+ mesh.name = name
+ return mesh
+}
+
+describe('ModelAnalysisReport.snapshot_scene', () => {
+ it('counts meshes, vertices, and triangles', () => {
+ const scene = new Scene()
+ scene.add(make_mesh('body'))
+ scene.add(make_mesh('head'))
+
+ const snapshot: SceneSnapshot = ModelAnalysisReport.snapshot_scene(scene)
+
+ expect(snapshot.mesh_count).toBe(2)
+ expect(snapshot.skinned_mesh_count).toBe(0)
+ expect(snapshot.objects.map((entry) => entry.name)).toEqual(['body', 'head'])
+ // BoxGeometry is indexed: 36 indices -> 12 triangles per box
+ expect(snapshot.triangle_count).toBe(24)
+ expect(snapshot.vertex_count).toBe(48)
+ })
+
+ it('reports the union of mesh bounds in world space', () => {
+ const scene = new Scene()
+ const first = make_mesh('left')
+ first.position.set(-2, 0, 0)
+ const second = make_mesh('right')
+ second.position.set(2, 0, 0)
+ scene.add(first, second)
+
+ const snapshot: SceneSnapshot = ModelAnalysisReport.snapshot_scene(scene)
+
+ // -2.5 to 2.5 across X, single unit box on the other axes
+ expect(snapshot.world_size.x).toBeCloseTo(5)
+ expect(snapshot.world_size.y).toBeCloseTo(1)
+ expect(snapshot.world_min.x).toBeCloseTo(-2.5)
+ })
+
+ it('includes scale inherited from parent groups in world scale', () => {
+ const scene = new Scene()
+ const group = new Group()
+ group.name = 'rig_root'
+ group.scale.set(2, 2, 2)
+ const mesh = make_mesh('body')
+ mesh.scale.set(3, 3, 3)
+ group.add(mesh)
+ scene.add(group)
+
+ const snapshot: SceneSnapshot = ModelAnalysisReport.snapshot_scene(scene)
+ const analyzed = snapshot.objects[0]
+
+ expect(analyzed.scale.x).toBeCloseTo(3)
+ expect(analyzed.world_scale.x).toBeCloseTo(6)
+ expect(analyzed.parent_name).toBe('rig_root')
+ expect(analyzed.depth).toBe(1)
+ expect(snapshot.type_counts.Group).toBe(1)
+ expect(snapshot.type_counts.Mesh).toBe(1)
+ })
+
+ it('reports transforms without treating position and rotation as problems', () => {
+ const scene = new Scene()
+ const mesh = make_mesh('arm')
+ mesh.position.set(0, 3, 0)
+ mesh.rotation.set(Math.PI / 2, 0, 0)
+ scene.add(mesh)
+
+ const analyzed = ModelAnalysisReport.snapshot_scene(scene).objects[0]
+
+ // import bakes these in now, so they are information rather than warnings
+ expect(analyzed.rotation_degrees.x).toBeCloseTo(90)
+ expect(analyzed.position.y).toBeCloseTo(3)
+ expect(analyzed.warnings).toEqual([])
+ })
+
+ it('still flags a non-uniform scale, which survives baking', () => {
+ const scene = new Scene()
+ const mesh = make_mesh('arm')
+ mesh.scale.set(1, 2, 1)
+ scene.add(mesh)
+
+ const analyzed = ModelAnalysisReport.snapshot_scene(scene).objects[0]
+
+ expect(analyzed.warnings.some((entry) => entry.includes('non-uniform'))).toBe(true)
+ })
+
+ it('treats a straight mirror as mirrored rather than non-uniform', () => {
+ const scene = new Scene()
+ const mesh = make_mesh('sword')
+ mesh.scale.set(-1, 1, 1)
+ scene.add(mesh)
+
+ const analyzed = ModelAnalysisReport.snapshot_scene(scene).objects[0]
+
+ expect(analyzed.warnings).toEqual([
+ 'Object is mirrored (negative scale). Import applies the mirror and reverses the face winding to compensate, so double check this part looks right.'
+ ])
+ })
+
+ it('records which parents a mesh inherits a transform from', () => {
+ const scene = new Scene()
+ const group = new Group()
+ group.name = 'Armature'
+ group.scale.set(100, 100, 100)
+ group.add(make_mesh('body'))
+ scene.add(group)
+
+ const analyzed = ModelAnalysisReport.snapshot_scene(scene).objects[0]
+
+ expect(analyzed.transformed_ancestors).toEqual(['Armature'])
+ expect(analyzed.warnings).toEqual([])
+ })
+
+ it('does not flag a mesh that is already baked at the origin', () => {
+ const scene = new Scene()
+ scene.add(make_mesh('body'))
+
+ const analyzed = ModelAnalysisReport.snapshot_scene(scene).objects[0]
+
+ // BoxGeometry supplies uvs and normals, so nothing should be reported
+ expect(analyzed.warnings).toEqual([])
+ })
+})
+
+describe('ModelAnalysisReport.build_html', () => {
+ it('escapes object names so model files cannot inject markup', () => {
+ const scene = new Scene()
+ scene.add(make_mesh('<img src=x onerror="alert(1)">'))
+ const snapshot: SceneSnapshot = ModelAnalysisReport.snapshot_scene(scene)
+
+ const html: string = ModalAnalysisHtml(snapshot)
+
+ expect(html).not.toContain('<img src=x')
+ expect(html).toContain('&lt;img src=x')
+ })
+})
+
+/** Small helper so the escaping test reads clearly. */
+function ModalAnalysisHtml (snapshot: SceneSnapshot): string {
+ return ModelAnalysisReport.build_html({
+ source_name: 'test.glb',
+ imported: snapshot,
+ processed: snapshot
+ })
+}
+
+describe('ModelAnalysisReport.format_number', () => {
+ it('keeps ordinary numbers short and readable', () => {
+ expect(ModelAnalysisReport.format_number(1)).toBe('1')
+ expect(ModelAnalysisReport.format_number(1.23456)).toBe('1.235')
+ expect(ModelAnalysisReport.format_number(0)).toBe('0')
+ })
+
+ it('falls back to exponents for extreme values instead of rounding them away', () => {
+ expect(ModelAnalysisReport.format_number(0.0004)).toBe('4.00e-4')
+ expect(ModelAnalysisReport.format_number(1234567)).toBe('1.23e+6')
+ })
+
+ it('treats floating point noise as zero', () => {
+ expect(ModelAnalysisReport.format_number(0.0000004)).toBe('0')
+ })
+})
diff --git a/src/lib/processes/load-model/ModelAnalysisReport.ts b/src/lib/processes/load-model/ModelAnalysisReport.ts
new file mode 100644
index 0000000..96e6e62
--- /dev/null
+++ b/src/lib/processes/load-model/ModelAnalysisReport.ts
@@ -0,0 +1,622 @@
+import { Box3, Vector3, type BufferGeometry, type Material, type Mesh, type Object3D } from 'three'
+import { ModalDialog } from '../../ModalDialog.ts'
+
+/**
+ * Snapshot of a single mesh-bearing object, taken at a point in time so later
+ * processing steps cannot change the numbers we are reporting on.
+ */
+export interface AnalyzedObject {
+ name: string
+ type: string
+ parent_name: string
+ depth: number
+ position: Vector3
+ rotation_degrees: Vector3
+ scale: Vector3
+ world_scale: Vector3
+ world_size: Vector3
+ // parent objects between this mesh and the scene root that carry their own transform
+ transformed_ancestors: string[]
+ vertex_count: number
+ triangle_count: number
+ material_summary: string
+ has_uvs: boolean
+ has_normals: boolean
+ has_skin_weights: boolean
+ warnings: string[]
+}
+
+/** Everything we can say about one scene graph at one moment. */
+export interface SceneSnapshot {
+ objects: AnalyzedObject[]
+ type_counts: Record<string, number>
+ mesh_count: number
+ skinned_mesh_count: number
+ vertex_count: number
+ triangle_count: number
+ world_size: Vector3
+ world_min: Vector3
+ world_max: Vector3
+}
+
+/**
+ * Before/after pair for one import. `imported` is what came out of the file
+ * loader and `processed` is the mesh data the rest of the app actually works
+ * with, which makes it possible to see what import processing changed.
+ */
+export interface ModelImportAnalysis {
+ source_name: string
+ imported: SceneSnapshot
+ processed: SceneSnapshot
+}
+
+/** A warning message plus the objects it applies to, for grouped display. */
+interface GroupedWarning {
+ message: string
+ object_names: string[]
+}
+
+/**
+ * Builds a human readable report of what a model file contained and what the
+ * import turned it into. Purely diagnostic - nothing here mutates model data
+ * beyond lazily computing geometry bounding boxes.
+ */
+export class ModelAnalysisReport {
+ // object transforms this far from identity are treated as intentional
+ private static readonly TRANSFORM_EPSILON = 0.0001
+
+ // rotation this far from zero (in degrees) is treated as intentional
+ private static readonly ROTATION_EPSILON_DEGREES = 0.01
+
+ /**
+ * Walk a scene and record everything worth reporting on.
+ * @param scene_object root of the scene graph to inspect
+ */
+ public static snapshot_scene (scene_object: Object3D): SceneSnapshot {
+ // world matrices drive the world scale/size numbers below
+ scene_object.updateMatrixWorld(true)
+
+ const objects: AnalyzedObject[] = []
+ const type_counts: Record<string, number> = {}
+ const scene_box: Box3 = new Box3()
+
+ let vertex_count = 0
+ let triangle_count = 0
+ let mesh_count = 0
+ let skinned_mesh_count = 0
+
+ scene_object.traverse((child: Object3D) => {
+ // the root itself isn't part of the file's contents listing
+ if (child !== scene_object) {
+ type_counts[child.type] = (type_counts[child.type] ?? 0) + 1
+ }
+
+ if (child.type !== 'Mesh' && child.type !== 'SkinnedMesh') {
+ return
+ }
+
+ const analyzed: AnalyzedObject = this.analyze_mesh(child as Mesh, scene_object)
+ objects.push(analyzed)
+
+ vertex_count += analyzed.vertex_count
+ triangle_count += analyzed.triangle_count
+ if (child.type === 'SkinnedMesh') {
+ skinned_mesh_count++
+ } else {
+ mesh_count++
+ }
+
+ const mesh_box: Box3 = this.world_box_for_mesh(child as Mesh)
+ if (!mesh_box.isEmpty()) {
+ scene_box.union(mesh_box)
+ }
+ })
+
+ return {
+ objects,
+ type_counts,
+ mesh_count,
+ skinned_mesh_count,
+ vertex_count,
+ triangle_count,
+ world_size: scene_box.isEmpty() ? new Vector3() : scene_box.getSize(new Vector3()),
+ world_min: scene_box.isEmpty() ? new Vector3() : scene_box.min.clone(),
+ world_max: scene_box.isEmpty() ? new Vector3() : scene_box.max.clone()
+ }
+ }
+
+ private static analyze_mesh (mesh: Mesh, scene_root: Object3D): AnalyzedObject {
+ const geometry: BufferGeometry = mesh.geometry
+ const position_attribute = geometry.getAttribute('position')
+ const world_box: Box3 = this.world_box_for_mesh(mesh)
+
+ const analyzed: AnalyzedObject = {
+ name: mesh.name === '' ? '(unnamed)' : mesh.name,
+ type: mesh.type,
+ parent_name: this.parent_label(mesh, scene_root),
+ depth: this.depth_in_scene(mesh, scene_root),
+ position: mesh.position.clone(),
+ rotation_degrees: new Vector3(
+ this.radians_to_degrees(mesh.rotation.x),
+ this.radians_to_degrees(mesh.rotation.y),
+ this.radians_to_degrees(mesh.rotation.z)
+ ),
+ scale: mesh.scale.clone(),
+ world_scale: mesh.getWorldScale(new Vector3()),
+ world_size: world_box.isEmpty() ? new Vector3() : world_box.getSize(new Vector3()),
+ transformed_ancestors: this.find_transformed_ancestors(mesh, scene_root),
+ vertex_count: position_attribute === undefined ? 0 : position_attribute.count,
+ triangle_count: this.count_triangles(geometry),
+ material_summary: this.describe_material(mesh.material),
+ has_uvs: geometry.getAttribute('uv') !== undefined,
+ has_normals: geometry.getAttribute('normal') !== undefined,
+ has_skin_weights: geometry.getAttribute('skinWeight') !== undefined,
+ warnings: []
+ }
+
+ analyzed.warnings = this.collect_object_warnings(analyzed)
+ return analyzed
+ }
+
+ /**
+ * Bounding box of just this mesh's own geometry in world space. Deliberately
+ * not Box3.setFromObject, which would fold in child meshes as well.
+ */
+ private static world_box_for_mesh (mesh: Mesh): Box3 {
+ const box: Box3 = new Box3()
+ const geometry: BufferGeometry = mesh.geometry
+
+ if (geometry.getAttribute('position') === undefined) {
+ return box
+ }
+
+ if (geometry.boundingBox === null) {
+ geometry.computeBoundingBox()
+ }
+
+ if (geometry.boundingBox !== null) {
+ box.copy(geometry.boundingBox).applyMatrix4(mesh.matrixWorld)
+ }
+
+ return box
+ }
+
+ private static count_triangles (geometry: BufferGeometry): number {
+ const index = geometry.getIndex()
+ if (index !== null) {
+ return Math.floor(index.count / 3)
+ }
+
+ const position_attribute = geometry.getAttribute('position')
+ if (position_attribute === undefined) {
+ return 0
+ }
+
+ return Math.floor(position_attribute.count / 3)
+ }
+
+ private static describe_material (material: Material | Material[]): string {
+ if (Array.isArray(material)) {
+ if (material.length === 0) {
+ return 'none'
+ }
+ return `${material.length} materials: ` + material.map((entry) => this.describe_single_material(entry)).join(', ')
+ }
+
+ if (material === undefined || material === null) {
+ return 'none'
+ }
+
+ return this.describe_single_material(material)
+ }
+
+ private static describe_single_material (material: Material): string {
+ const parts: string[] = [material.type]
+
+ if (material.name !== '') {
+ parts.push(`"${material.name}"`)
+ }
+
+ // a missing texture map is a common reason a model imports looking flat/grey
+ const has_map: boolean = (material as any).map !== undefined && (material as any).map !== null
+ parts.push(has_map ? 'textured' : 'no texture')
+
+ parts.push(this.describe_material_side(material.side))
+
+ return parts.join(' / ')
+ }
+
+ private static describe_material_side (side: number): string {
+ switch (side) {
+ case 1: return 'back faces'
+ case 2: return 'double sided'
+ default: return 'front faces'
+ }
+ }
+
+ /**
+ * Transforms themselves are no longer a problem, since import bakes them into
+ * the vertices. What is left are the transforms that stay visible in the result
+ * either way, plus missing geometry data.
+ */
+ private static collect_object_warnings (analyzed: AnalyzedObject): string[] {
+ const warnings: string[] = []
+
+ if (!this.is_uniform_scale(analyzed.scale)) {
+ warnings.push('Object scale is non-uniform (different per axis). The mesh is stretched on one axis, which carries through to the skinning.')
+ }
+
+ if (analyzed.scale.x < 0 || analyzed.scale.y < 0 || analyzed.scale.z < 0) {
+ warnings.push('Object is mirrored (negative scale). Import applies the mirror and reverses the face winding to compensate, so double check this part looks right.')
+ }
+
+ if (analyzed.vertex_count === 0) {
+ warnings.push('Mesh has no vertex data.')
+ }
+
+ if (!analyzed.has_normals) {
+ warnings.push('Mesh has no normals, so it will shade incorrectly.')
+ }
+
+ if (!analyzed.has_uvs) {
+ warnings.push('Mesh has no UV coordinates, so textures cannot be applied.')
+ }
+
+ if (analyzed.type === 'SkinnedMesh') {
+ warnings.push('Mesh is already rigged. This workflow drops the existing skeleton - use "Use Your Rigged Model" to keep it.')
+ }
+
+ return warnings
+ }
+
+ /** Scene wide observations that no single object can tell us. */
+ private static collect_scene_warnings (analysis: ModelImportAnalysis): string[] {
+ const warnings: string[] = []
+ const imported: SceneSnapshot = analysis.imported
+ const processed: SceneSnapshot = analysis.processed
+
+ if (imported.objects.length === 0) {
+ warnings.push('No meshes were found in the file.')
+ return warnings
+ }
+
+ const imported_size: Vector3 = imported.world_size
+ const largest_dimension: number = Math.max(imported_size.x, imported_size.y, imported_size.z)
+
+ if (largest_dimension <= 0.5 || largest_dimension >= 20) {
+ warnings.push(`Model came in at ${this.format_number(largest_dimension)} units across, so import auto-scaled it to a workable size.`)
+ }
+
+ if (imported_size.z > imported_size.y * 1.25) {
+ warnings.push('Model is deeper than it is tall, which usually means it is Z-up or lying down. Use the rotate buttons to stand it up.')
+ }
+
+ // baking transforms means the model keeps its authored placement, which is
+ // correct but can leave it sitting away from the origin where the skeleton loads
+ const offset_from_origin: number = Math.max(
+ Math.abs(processed.world_min.x + processed.world_max.x) / 2,
+ Math.abs(processed.world_min.z + processed.world_max.z) / 2
+ )
+ const model_height: number = Math.max(processed.world_size.y, 0.001)
+
+ if (offset_from_origin > model_height) {
+ warnings.push(`Model sits about ${this.format_number(offset_from_origin)} units away from the origin, which is where the skeleton loads. Use "Reset position" or the move gizmo to bring it back.`)
+ }
+
+ const imported_mesh_total: number = imported.mesh_count + imported.skinned_mesh_count
+ if (processed.mesh_count !== imported_mesh_total) {
+ warnings.push(`File contained ${imported_mesh_total} meshes but ${processed.mesh_count} made it through import.`)
+ }
+
+ return warnings
+ }
+
+ /**
+ * Show the report in a dialog.
+ * @param analysis report data, or null when nothing has been imported yet
+ */
+ public static show_dialog (analysis: ModelImportAnalysis | null): void {
+ const content: string = analysis === null
+ ? '<p>No model has been imported yet.</p>'
+ : this.build_html(analysis)
+
+ new ModalDialog('Model Analysis', content, { customClass: 'model-analysis-dialog' }).show()
+ }
+
+ public static build_html (analysis: ModelImportAnalysis): string {
+ return `
+ <div class="model-analysis">
+ <p class="model-analysis-source">Source: <strong>${this.escape_html(analysis.source_name)}</strong></p>
+ ${this.build_warnings_html(analysis)}
+ ${this.build_summary_html(analysis)}
+ ${this.build_mesh_table_html(analysis.imported)}
+ ${this.build_contents_html(analysis.imported)}
+ </div>
+ `
+ }
+
+ private static build_warnings_html (analysis: ModelImportAnalysis): string {
+ const scene_warnings: string[] = this.collect_scene_warnings(analysis)
+ const grouped_warnings: GroupedWarning[] = this.group_object_warnings(analysis.imported)
+
+ if (scene_warnings.length === 0 && grouped_warnings.length === 0) {
+ return '<p class="model-analysis-clean">Nothing unusual found. The model imported cleanly.</p>'
+ }
+
+ const scene_items: string = scene_warnings
+ .map((message) => `<li>${this.escape_html(message)}</li>`)
+ .join('')
+
+ const object_items: string = grouped_warnings
+ .map((warning) => `
+ <li>
+ ${this.escape_html(warning.message)}
+ <span class="model-analysis-affected">${this.escape_html(warning.object_names.join(', '))}</span>
+ </li>
+ `)
+ .join('')
+
+ return `
+ <h3>Things to check</h3>
+ <ul class="model-analysis-warnings">${scene_items}${object_items}</ul>
+ `
+ }
+
+ /** Collapse identical per-object warnings into one row listing the objects. */
+ private static group_object_warnings (snapshot: SceneSnapshot): GroupedWarning[] {
+ const grouped = new Map<string, GroupedWarning>()
+
+ snapshot.objects.forEach((analyzed) => {
+ analyzed.warnings.forEach((message) => {
+ const existing: GroupedWarning | undefined = grouped.get(message)
+ if (existing === undefined) {
+ grouped.set(message, { message, object_names: [analyzed.name] })
+ } else {
+ existing.object_names.push(analyzed.name)
+ }
+ })
+ })
+
+ return Array.from(grouped.values())
+ }
+
+ private static build_summary_html (analysis: ModelImportAnalysis): string {
+ const imported: SceneSnapshot = analysis.imported
+ const processed: SceneSnapshot = analysis.processed
+
+ const rows: string = [
+ ['Meshes', String(imported.mesh_count), String(processed.mesh_count)],
+ ['Rigged meshes', String(imported.skinned_mesh_count), String(processed.skinned_mesh_count)],
+ ['Vertices', imported.vertex_count.toLocaleString(), processed.vertex_count.toLocaleString()],
+ ['Triangles', imported.triangle_count.toLocaleString(), processed.triangle_count.toLocaleString()],
+ ['Size (X x Y x Z)', this.format_vector(imported.world_size, ' x '), this.format_vector(processed.world_size, ' x ')],
+ ['Lowest point (Y)', this.format_number(imported.world_min.y), this.format_number(processed.world_min.y)]
+ ]
+ .map(([label, imported_value, processed_value]) => `
+ <tr>
+ <th scope="row">${this.escape_html(label)}</th>
+ <td>${this.escape_html(imported_value)}</td>
+ <td>${this.escape_html(processed_value)}</td>
+ </tr>
+ `)
+ .join('')
+
+ return `
+ <h3>Summary</h3>
+ <div class="model-analysis-table-scroll">
+ <table class="model-analysis-table">
+ <thead>
+ <tr>
+ <th scope="col"></th>
+ <th scope="col">In the file</th>
+ <th scope="col">After import</th>
+ </tr>
+ </thead>
+ <tbody>${rows}</tbody>
+ </table>
+ </div>
+ `
+ }
+
+ private static build_mesh_table_html (snapshot: SceneSnapshot): string {
+ if (snapshot.objects.length === 0) {
+ return ''
+ }
+
+ const rows: string = snapshot.objects
+ .map((analyzed) => `
+ <tr${analyzed.warnings.length > 0 ? ' class="model-analysis-row-flagged"' : ''}>
+ <td>
+ <span class="model-analysis-name" style="padding-left: ${analyzed.depth * 0.75}rem">${this.escape_html(analyzed.name)}</span>
+ <span class="model-analysis-parent">${this.escape_html(this.describe_parentage(analyzed))}</span>
+ </td>
+ <td>${this.escape_html(analyzed.type)}</td>
+ <td>${this.escape_html(this.format_vector(analyzed.position))}</td>
+ <td>${this.escape_html(this.format_vector(analyzed.rotation_degrees))}</td>
+ <td>${this.escape_html(this.format_vector(analyzed.scale))}</td>
+ <td>${this.escape_html(this.format_vector(analyzed.world_scale))}</td>
+ <td>${this.escape_html(this.format_vector(analyzed.world_size, ' x '))}</td>
+ <td>${analyzed.vertex_count.toLocaleString()}</td>
+ <td>${analyzed.triangle_count.toLocaleString()}</td>
+ <td>${this.escape_html(analyzed.material_summary)}</td>
+ </tr>
+ `)
+ .join('')
+
+ return `
+ <h3>Meshes in the file (${snapshot.objects.length})</h3>
+ <p class="model-analysis-note">Transforms below are as authored in the file, and are baked into the vertices on import so the model keeps this orientation, placement, and scale. Rotation is in degrees. World scale includes any scale inherited from parent objects.</p>
+ <div class="model-analysis-table-scroll">
+ <table class="model-analysis-table">
+ <thead>
+ <tr>
+ <th scope="col">Name</th>
+ <th scope="col">Type</th>
+ <th scope="col">Position</th>
+ <th scope="col">Rotation</th>
+ <th scope="col">Scale</th>
+ <th scope="col">World scale</th>
+ <th scope="col">Size</th>
+ <th scope="col">Verts</th>
+ <th scope="col">Tris</th>
+ <th scope="col">Material</th>
+ </tr>
+ </thead>
+ <tbody>${rows}</tbody>
+ </table>
+ </div>
+ `
+ }
+
+ private static build_contents_html (snapshot: SceneSnapshot): string {
+ const type_names: string[] = Object.keys(snapshot.type_counts).sort()
+
+ if (type_names.length === 0) {
+ return ''
+ }
+
+ const chips: string = type_names
+ .map((type_name) => `<span class="model-analysis-chip">${this.escape_html(type_name)} x ${snapshot.type_counts[type_name]}</span>`)
+ .join('')
+
+ return `
+ <h3>Everything in the file</h3>
+ <div class="model-analysis-chips">${chips}</div>
+ `
+ }
+
+ /**
+ * One line describing where a mesh sits and whether anything above it is
+ * contributing a transform, which is what makes the world scale column differ
+ * from the plain scale column.
+ */
+ private static describe_parentage (analyzed: AnalyzedObject): string {
+ if (analyzed.transformed_ancestors.length === 0) {
+ return `in ${analyzed.parent_name}`
+ }
+
+ // the parent line already names it, so avoid saying the same thing twice
+ if (analyzed.transformed_ancestors.length === 1 && analyzed.transformed_ancestors[0] === analyzed.parent_name) {
+ return `in ${analyzed.parent_name} (transformed)`
+ }
+
+ return `in ${analyzed.parent_name}, transformed by ${analyzed.transformed_ancestors.join(', ')}`
+ }
+
+ private static parent_label (object_3d: Object3D, scene_root: Object3D): string {
+ const parent: Object3D | null = object_3d.parent
+
+ if (parent === null || parent === scene_root) {
+ return 'scene root'
+ }
+
+ return parent.name === '' ? `(unnamed ${parent.type})` : parent.name
+ }
+
+ /**
+ * Names of the parent objects a mesh inherits a transform from. Import flattens
+ * the hierarchy, so a mesh can be positioned entirely by its parents and still
+ * look perfectly fine on its own row of the report.
+ */
+ private static find_transformed_ancestors (object_3d: Object3D, scene_root: Object3D): string[] {
+ const ancestors: string[] = []
+ let current: Object3D | null = object_3d.parent
+
+ while (current !== null && current !== scene_root) {
+ const has_transform: boolean = !this.is_zero_vector(current.position) ||
+ !this.is_unit_vector(current.scale) ||
+ !this.is_zero_rotation(new Vector3(
+ this.radians_to_degrees(current.rotation.x),
+ this.radians_to_degrees(current.rotation.y),
+ this.radians_to_degrees(current.rotation.z)
+ ))
+
+ if (has_transform) {
+ ancestors.push(current.name === '' ? `(unnamed ${current.type})` : current.name)
+ }
+
+ current = current.parent
+ }
+
+ return ancestors
+ }
+
+ private static depth_in_scene (object_3d: Object3D, scene_root: Object3D): number {
+ let depth = 0
+ let current: Object3D | null = object_3d.parent
+
+ while (current !== null && current !== scene_root) {
+ depth++
+ current = current.parent
+ }
+
+ return depth
+ }
+
+ private static is_zero_vector (vector: Vector3): boolean {
+ return Math.abs(vector.x) < this.TRANSFORM_EPSILON &&
+ Math.abs(vector.y) < this.TRANSFORM_EPSILON &&
+ Math.abs(vector.z) < this.TRANSFORM_EPSILON
+ }
+
+ private static is_unit_vector (vector: Vector3): boolean {
+ return Math.abs(vector.x - 1) < this.TRANSFORM_EPSILON &&
+ Math.abs(vector.y - 1) < this.TRANSFORM_EPSILON &&
+ Math.abs(vector.z - 1) < this.TRANSFORM_EPSILON
+ }
+
+ /**
+ * Compares magnitudes so a straight mirror (-1, 1, 1) counts as uniform and
+ * only gets reported once, by the negative scale check.
+ */
+ private static is_uniform_scale (vector: Vector3): boolean {
+ return Math.abs(Math.abs(vector.x) - Math.abs(vector.y)) < this.TRANSFORM_EPSILON &&
+ Math.abs(Math.abs(vector.y) - Math.abs(vector.z)) < this.TRANSFORM_EPSILON
+ }
+
+ private static is_zero_rotation (rotation_degrees: Vector3): boolean {
+ return Math.abs(rotation_degrees.x) < this.ROTATION_EPSILON_DEGREES &&
+ Math.abs(rotation_degrees.y) < this.ROTATION_EPSILON_DEGREES &&
+ Math.abs(rotation_degrees.z) < this.ROTATION_EPSILON_DEGREES
+ }
+
+ private static radians_to_degrees (radians: number): number {
+ return radians * 180 / Math.PI
+ }
+
+ private static format_vector (vector: Vector3, separator: string = ', '): string {
+ return [vector.x, vector.y, vector.z].map((value) => this.format_number(value)).join(separator)
+ }
+
+ /**
+ * Keep numbers short enough to scan while still showing tiny/huge values. A
+ * scale of 0.0001 is exactly the kind of thing we want visible, so anything
+ * that would round away to zero switches to exponent form instead. Only
+ * floating point noise is reported as a flat zero.
+ */
+ public static format_number (value: number, digits: number = 3): string {
+ if (!isFinite(value)) {
+ return '-'
+ }
+
+ const magnitude: number = Math.abs(value)
+
+ if (magnitude < 0.000001) {
+ return '0'
+ }
+
+ if (magnitude >= 100000 || magnitude < 0.001) {
+ return value.toExponential(2)
+ }
+
+ return String(Number(value.toFixed(digits)))
+ }
+
+ private static escape_html (value: string): string {
+ return value
+ .replace(/&/g, '&amp;')
+ .replace(/</g, '&lt;')
+ .replace(/>/g, '&gt;')
+ .replace(/"/g, '&quot;')
+ }
+}
diff --git a/src/lib/processes/load-model/ModelCleanupUtility.test.ts b/src/lib/processes/load-model/ModelCleanupUtility.test.ts
new file mode 100644
index 0000000..a25c73b
--- /dev/null
+++ b/src/lib/processes/load-model/ModelCleanupUtility.test.ts
@@ -0,0 +1,136 @@
+import { describe, it, expect } from 'vitest'
+import { Box3, type BufferGeometry, BoxGeometry, Group, Mesh, MeshStandardMaterial, PlaneGeometry, Scene, Vector3 } from 'three'
+import { ModelCleanupUtility } from './ModelCleanupUtility'
+
+function make_mesh (name: string, geometry: BufferGeometry = new BoxGeometry(1, 1, 1)): Mesh {
+ const mesh = new Mesh(geometry, new MeshStandardMaterial())
+ mesh.name = name
+ return mesh
+}
+
+/** World space bounds of a single mesh's own geometry. */
+function mesh_bounds (mesh: Mesh): Box3 {
+ mesh.updateMatrixWorld(true)
+ mesh.geometry.computeBoundingBox()
+ return new Box3().copy(mesh.geometry.boundingBox!).applyMatrix4(mesh.matrixWorld)
+}
+
+describe('ModelCleanupUtility.bake_transforms_into_geometry', () => {
+ it('keeps a mesh where it was, but with an identity transform', () => {
+ const scene = new Scene()
+ const mesh = make_mesh('head')
+ mesh.position.set(0, 5, 0)
+ mesh.scale.set(2, 2, 2)
+ scene.add(mesh)
+
+ const bounds_before: Box3 = mesh_bounds(mesh)
+ ModelCleanupUtility.bake_transforms_into_geometry(scene)
+ const bounds_after: Box3 = mesh_bounds(mesh)
+
+ expect(mesh.position.toArray()).toEqual([0, 0, 0])
+ expect(mesh.scale.toArray()).toEqual([1, 1, 1])
+ expect(bounds_after.min.toArray()).toEqual(bounds_before.min.toArray())
+ expect(bounds_after.max.toArray()).toEqual(bounds_before.max.toArray())
+ })
+
+ it('bakes a rotation so the mesh keeps facing the same way', () => {
+ const scene = new Scene()
+ // a plane is 2 wide on X and 4 tall on Y before rotating
+ const mesh = make_mesh('banner', new PlaneGeometry(2, 4))
+ mesh.rotation.set(Math.PI / 2, 0, 0)
+ scene.add(mesh)
+
+ ModelCleanupUtility.bake_transforms_into_geometry(scene)
+ const size: Vector3 = mesh_bounds(mesh).getSize(new Vector3())
+
+ expect(mesh.rotation.x).toBeCloseTo(0)
+ // rotating 90 degrees about X moves the 4 unit span onto Z
+ expect(size.x).toBeCloseTo(2)
+ expect(size.y).toBeCloseTo(0)
+ expect(size.z).toBeCloseTo(4)
+ })
+
+ it('bakes transforms inherited from parent objects', () => {
+ const scene = new Scene()
+ const group = new Group()
+ group.scale.set(10, 10, 10)
+ group.position.set(3, 0, 0)
+ const mesh = make_mesh('body')
+ group.add(mesh)
+ scene.add(group)
+
+ ModelCleanupUtility.bake_transforms_into_geometry(scene)
+ const bounds: Box3 = mesh_bounds(mesh)
+
+ // scaled to 10 units then offset by the parent, and the parent is cleared too
+ expect(group.scale.toArray()).toEqual([1, 1, 1])
+ expect(group.position.toArray()).toEqual([0, 0, 0])
+ expect(bounds.getSize(new Vector3()).x).toBeCloseTo(10)
+ expect(bounds.getCenter(new Vector3()).x).toBeCloseTo(3)
+ })
+
+ it('keeps the relative layout of separate parts', () => {
+ const scene = new Scene()
+ const left = make_mesh('left')
+ left.position.set(-4, 0, 0)
+ const right = make_mesh('right')
+ right.position.set(4, 0, 0)
+ scene.add(left, right)
+
+ ModelCleanupUtility.bake_transforms_into_geometry(scene)
+
+ expect(mesh_bounds(left).getCenter(new Vector3()).x).toBeCloseTo(-4)
+ expect(mesh_bounds(right).getCenter(new Vector3()).x).toBeCloseTo(4)
+ })
+
+ it('does not disturb geometry shared with another mesh', () => {
+ const scene = new Scene()
+ const shared_geometry = new BoxGeometry(1, 1, 1)
+ const first = make_mesh('first', shared_geometry)
+ first.position.set(0, 10, 0)
+ const second = make_mesh('second', shared_geometry)
+ scene.add(first, second)
+
+ ModelCleanupUtility.bake_transforms_into_geometry(scene)
+
+ expect(first.geometry).not.toBe(second.geometry)
+ expect(mesh_bounds(first).getCenter(new Vector3()).y).toBeCloseTo(10)
+ expect(mesh_bounds(second).getCenter(new Vector3()).y).toBeCloseTo(0)
+ })
+
+ it('reverses face winding for a mirrored transform', () => {
+ const scene = new Scene()
+ const mesh = make_mesh('sword')
+ mesh.scale.set(-1, 1, 1)
+ scene.add(mesh)
+
+ const original_index = Array.from(mesh.geometry.getIndex()!.array)
+ ModelCleanupUtility.bake_transforms_into_geometry(scene)
+ const baked_index = Array.from(mesh.geometry.getIndex()!.array)
+
+ // first and last vertex of each triangle swap, so the face points back outward
+ expect(baked_index[0]).toBe(original_index[2])
+ expect(baked_index[2]).toBe(original_index[0])
+ expect(baked_index[1]).toBe(original_index[1])
+ })
+})
+
+describe('ModelCleanupUtility.strip_out_all_unecessary_model_data', () => {
+ it('does not duplicate a mesh that is nested under another mesh', () => {
+ const scene = new Scene()
+ const parent_mesh = make_mesh('torso')
+ parent_mesh.add(make_mesh('arm'))
+ scene.add(parent_mesh)
+
+ const stripped = ModelCleanupUtility.strip_out_all_unecessary_model_data(scene, 'Imported Model', false)
+
+ const names: string[] = []
+ stripped.traverse((child) => {
+ if (child.type === 'Mesh') {
+ names.push(child.name)
+ }
+ })
+
+ expect(names.sort()).toEqual(['arm', 'torso'])
+ })
+})
diff --git a/src/lib/processes/load-model/ModelCleanupUtility.ts b/src/lib/processes/load-model/ModelCleanupUtility.ts
index 2e906e0..9ca9768 100644
--- a/src/lib/processes/load-model/ModelCleanupUtility.ts
+++ b/src/lib/processes/load-model/ModelCleanupUtility.ts
@@ -1,4 +1,4 @@
-import { Box3, Group, type Object3DEventMap, type Object3D, Scene, Mesh, MeshPhongMaterial, type SkinnedMesh } from 'three'
+import { Box3, type BufferGeometry, Group, Matrix4, type Object3DEventMap, type Object3D, Scene, Mesh, MeshPhongMaterial, type SkinnedMesh } from 'three'
import { FrontSide } from 'three/src/constants.js'
/**
@@ -93,6 +93,88 @@ export class ModelCleanupUtility {
})
}
+ /**
+ * Applies each mesh's world transform to its vertices, then clears every
+ * transform in the hierarchy.
+ *
+ * The skinning process works from raw geometry and ignores object transforms,
+ * so it needs those transforms to be identity. Baking gets us that without
+ * throwing away the orientation, placement, and scale the model was authored
+ * with, which is what happens if the transforms are simply reset to defaults.
+ * @param model_data root of the hierarchy to flatten transforms on
+ */
+ public static bake_transforms_into_geometry (model_data: Object3D): void {
+ model_data.updateMatrixWorld(true)
+
+ // capture the world matrices up front, since clearing transforms below invalidates them
+ const meshes_to_bake: Array<{ mesh: Mesh, world_matrix: Matrix4 }> = []
+ model_data.traverse((child: Object3D) => {
+ if (child.type === 'Mesh' || child.type === 'SkinnedMesh') {
+ meshes_to_bake.push({ mesh: child as Mesh, world_matrix: child.matrixWorld.clone() })
+ }
+ })
+
+ meshes_to_bake.forEach(({ mesh, world_matrix }) => {
+ if (mesh.geometry === undefined || mesh.geometry === null) {
+ return
+ }
+
+ // geometry can be shared between meshes that have different transforms,
+ // so each mesh needs its own copy before we bake anything into it
+ const baked_geometry: BufferGeometry = mesh.geometry.clone()
+ baked_geometry.name = mesh.geometry.name
+ baked_geometry.applyMatrix4(world_matrix)
+
+ // a mirrored transform reverses triangle winding, which renders the mesh
+ // inside out unless we put the winding back
+ if (world_matrix.determinant() < 0) {
+ this.flip_face_winding(baked_geometry)
+ }
+
+ baked_geometry.computeBoundingBox()
+ baked_geometry.computeBoundingSphere()
+ mesh.geometry = baked_geometry
+ })
+
+ // every transform is part of the geometry now, so none of them should apply twice
+ model_data.traverse((child: Object3D) => {
+ child.position.set(0, 0, 0)
+ child.quaternion.identity()
+ child.scale.set(1, 1, 1)
+ child.updateMatrix()
+ })
+
+ model_data.updateMatrixWorld(true)
+ }
+
+ /** Reverses the vertex order of every triangle so faces point the other way. */
+ private static flip_face_winding (geometry: BufferGeometry): void {
+ const index = geometry.getIndex()
+
+ if (index !== null) {
+ for (let triangle_start = 0; triangle_start + 2 < index.count; triangle_start += 3) {
+ const first_vertex: number = index.getX(triangle_start)
+ index.setX(triangle_start, index.getX(triangle_start + 2))
+ index.setX(triangle_start + 2, first_vertex)
+ }
+ index.needsUpdate = true
+ return
+ }
+
+ // non-indexed geometry stores each triangle inline, so the outer vertices of
+ // every triangle have to be swapped across every attribute to stay in sync
+ Object.values(geometry.attributes).forEach((attribute) => {
+ for (let triangle_start = 0; triangle_start + 2 < attribute.count; triangle_start += 3) {
+ for (let component = 0; component < attribute.itemSize; component++) {
+ const first_value: number = attribute.getComponent(triangle_start, component)
+ attribute.setComponent(triangle_start, component, attribute.getComponent(triangle_start + 2, component))
+ attribute.setComponent(triangle_start + 2, component, first_value)
+ }
+ }
+ attribute.needsUpdate = true
+ })
+ }
+
public static strip_out_all_unecessary_model_data (model_data: Scene, model_display_name: string, debug_model_loading: boolean): Scene {
const new_scene = new Scene()
new_scene.name = model_display_name
@@ -105,7 +187,9 @@ export class ModelCleanupUtility {
new_mesh.name = child.name
new_scene.add(new_mesh)
} else if (child.type === 'Mesh') {
- new_mesh = (child as Mesh).clone()
+ // clone without children, otherwise a mesh nested under another mesh gets
+ // added once as part of its parent's clone and again when traverse reaches it
+ new_mesh = (child as Mesh).clone(false)
new_mesh.name = child.name
new_scene.add(new_mesh)
}
diff --git a/src/lib/processes/load-model/StepLoadModel.ts b/src/lib/processes/load-model/StepLoadModel.ts
index 765df3f..a1c6898 100644
--- a/src/lib/processes/load-model/StepLoadModel.ts
+++ b/src/lib/processes/load-model/StepLoadModel.ts
@@ -10,6 +10,7 @@ import { MathUtils } from 'three/src/math/MathUtils.js'
import { BufferGeometry, Group, MeshPhongMaterial, Object3DEventMap, type Material, type Object3D } from 'three'
import { ModalDialog } from '../../ModalDialog.ts'
import { ModelCleanupUtility } from './ModelCleanupUtility.ts'
+import { ModelAnalysisReport, type ModelImportAnalysis, type SceneSnapshot } from './ModelAnalysisReport.ts'
import { PlatformUtils } from '../../PlatformUtils.ts'
// Note: EventTarget is a built-ininterface and do not need to import it
@@ -26,6 +27,12 @@ export class StepLoadModel extends EventTarget {
private model_display_name: string = 'Imported Model'
+ // file the user picked, only used for labeling the analysis report
+ private source_file_name: string = 'Unknown file'
+
+ // diagnostic snapshot of what the file contained vs. what import produced
+ private import_analysis: ModelImportAnalysis | null = null
+
// there can be multiple objects in a model, so store them in a list
private readonly geometry_list: BufferGeometry[] = []
private readonly material_list: Material[] = []
@@ -168,6 +175,7 @@ export class StepLoadModel extends EventTarget {
this.ui.dom_upload_model_button.addEventListener('change', (event: Event) => {
const file = event.target.files[0]
const file_extension: string = this.get_file_extension(file.name)
+ this.source_file_name = file.name
const reader = new FileReader()
reader.readAsDataURL(file)
@@ -199,6 +207,7 @@ export class StepLoadModel extends EventTarget {
if (model_selection !== null) {
const file_name = model_selection.options[model_selection.selectedIndex].value
const file_extension: string = this.get_file_extension(file_name)
+ this.source_file_name = file_name.split('/').pop() ?? file_name
this.load_model_file(file_name, file_extension)
}
})
@@ -234,6 +243,7 @@ export class StepLoadModel extends EventTarget {
this.objects_count = 0
this.mesh_has_broken_material = false
this.preserve_skinned_mesh = false
+ this.import_analysis = null
}
public reset_model_position (): void {
@@ -342,6 +352,11 @@ export class StepLoadModel extends EventTarget {
}
private process_loaded_scene (loaded_scene: Scene): void {
+ // capture the file contents before any cleanup/normalization runs. this has to
+ // happen first because the steps below mutate geometry that is shared with the
+ // scene the loader handed us
+ const imported_snapshot: SceneSnapshot = ModelAnalysisReport.snapshot_scene(loaded_scene)
+
if (this.preserve_skinned_mesh) {
this.original_model_data = loaded_scene
} else {
@@ -360,6 +375,11 @@ export class StepLoadModel extends EventTarget {
// and mess up the skinned mesh and exports. So for now, just keep everything
clean_scene_with_only_models = this.original_model_data
} else {
+ // bake object transforms into the vertices before flattening the hierarchy.
+ // stripping and rebuilding meshes below drops object transforms entirely, so
+ // this is what keeps the orientation, placement, and scale from the file.
+ // skipped for skinned meshes, where baking would break the skeleton binding
+ ModelCleanupUtility.bake_transforms_into_geometry(this.original_model_data)
clean_scene_with_only_models = ModelCleanupUtility.strip_out_all_unecessary_model_data(this.original_model_data, this.model_display_name, this.debug_model_loading)
}
@@ -378,19 +398,15 @@ export class StepLoadModel extends EventTarget {
// any scaling or further processing can be donw as part of the retargeting process
if (this.preserve_skinned_mesh) {
this.final_retargetable_model_data = clean_scene_with_only_models
+ this.import_analysis = this.build_import_analysis(imported_snapshot, this.final_retargetable_model_data)
this.dispatchEvent(new CustomEvent('modelLoadedForRetargeting'))
return
}
- // loop through each child in scene and reset rotation
- // if we don't the skinning process doesn't take rotation into account
- // and creates odd results
- clean_scene_with_only_models.traverse((child) => {
- child.rotation.set(0, 0, 0)
- child.scale.set(1, 1, 1)
- child.updateMatrix() // helps re-calculate bounding box for scaling later
- child.updateMatrixWorld() // helps re-calculate bounding box for scaling later
- })
+ // every transform is already baked into the geometry at this point, so the
+ // skinning process sees the identity transforms it needs. just make sure the
+ // matrices are current for the bounding box calculations below
+ clean_scene_with_only_models.updateMatrixWorld(true)
// Some objects come in very large, which makes it harder to work with
// scale everything down to a max height. mutate the clean scene object
@@ -416,9 +432,27 @@ export class StepLoadModel extends EventTarget {
console.log('final mesh data should be prepared at this point', this.final_mesh_data)
+ this.import_analysis = this.build_import_analysis(imported_snapshot, this.final_mesh_data)
+
this.dispatchEvent(new CustomEvent('modelLoaded'))
}
+ private build_import_analysis (imported_snapshot: SceneSnapshot, processed_scene: Scene): ModelImportAnalysis {
+ return {
+ source_name: this.source_file_name,
+ imported: imported_snapshot,
+ processed: ModelAnalysisReport.snapshot_scene(processed_scene)
+ }
+ }
+
+ /**
+ * Diagnostic breakdown of the last import, or null if nothing is loaded yet.
+ * Used by the "Analyze" option to help troubleshoot odd looking models.
+ */
+ public get_import_analysis (): ModelImportAnalysis | null {
+ return this.import_analysis
+ }
+
public model_meshes (): Scene {
// if the scene has some children in it, that means we already built it
// this function gets called when we enter the application
diff --git a/src/styles.css b/src/styles.css
index 04360f8..bb03d50 100644
--- a/src/styles.css
+++ b/src/styles.css
@@ -269,7 +269,29 @@ button.no-style-button {
border: none;
}
button.no-style-button:hover {
- background: var(--bg-primary);
+ background: var(--bg-primary);
+}
+
+/* text that acts like a link, but is really an action (e.g. opening a dialog) */
+button.link-button {
+ background: none;
+ box-shadow: none;
+ border: none;
+ padding: 0;
+ margin: 0;
+ text-decoration: underline;
+ opacity: 0.75;
+ cursor: pointer;
+}
+button.link-button:hover {
+ background: none;
+ opacity: 1;
+ transform: none;
+}
+
+.analyze-model-row {
+ display: flex;
+ justify-content: flex-end;
}
button, .button {