@wonder-partners/model-viewer-stats 1.0.1 → 1.0.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,19 +1,22 @@
1
1
  {
2
2
  "name": "@wonder-partners/model-viewer-stats",
3
3
  "private": false,
4
- "version": "1.0.1",
4
+ "version": "1.0.2",
5
5
  "repository": {
6
6
  "type": "git",
7
7
  "url": "git+https://github.com/wonder-partners/model-viewer-stats.git"
8
8
  },
9
9
  "type": "module",
10
10
  "files": [
11
- "dist"
11
+ "dist",
12
+ "src"
12
13
  ],
13
14
  "main": "./dist/model-viewer-stats.umd.cjs",
14
15
  "module": "./dist/model-viewer-stats.js",
16
+ "types": "./src/index.d.ts",
15
17
  "exports": {
16
18
  ".": {
19
+ "types": "./src/index.d.ts",
17
20
  "import": "./dist/model-viewer-stats.js",
18
21
  "require": "./dist/model-viewer-stats.umd.cjs"
19
22
  }
@@ -0,0 +1,19 @@
1
+ export class ModelStats extends HTMLElement {
2
+ constructor();
3
+ viewer: HTMLElement | null;
4
+ connectedCallback(): void;
5
+ toggle(): void;
6
+ render(): void;
7
+ calculateStats(): Promise<void>;
8
+ updateText(id: string, text: string): void;
9
+ formatBytes(bytes: number, decimals?: number): string;
10
+ /**
11
+ * Retrieves the internal Three.js Scene from a <model-viewer> instance.
12
+ * * This function bypasses the public API to access the underlying symbol
13
+ * that holds the scene context. It is robust against minification and
14
+ * internal naming changes (e.g., 'model-viewer-scene' vs 'model-viewer-artboard').
15
+ * * @param {HTMLElement} viewer - The <model-viewer> DOM element.
16
+ * @returns {Object|null} The THREE.Scene object, or null if not found.
17
+ */
18
+ getInternalScene(viewer: HTMLElement): any;
19
+ }
@@ -0,0 +1,212 @@
1
+ import { Box3, Vector3 } from "three";
2
+
3
+ const html = String.raw;
4
+
5
+ export class ModelStats extends HTMLElement {
6
+ constructor() {
7
+ super();
8
+ this.attachShadow({ mode: "open" });
9
+ this.viewer = null;
10
+ }
11
+
12
+ connectedCallback() {
13
+ this.render();
14
+ this.viewer = this.closest("model-viewer");
15
+
16
+ if (this.viewer) {
17
+ this.viewer.addEventListener("load", () => {
18
+ console.log("Model Viewer loaded");
19
+ this.calculateStats();
20
+ });
21
+ }
22
+ }
23
+
24
+ toggle() {
25
+ if (this.hasAttribute("visible")) {
26
+ this.removeAttribute("visible");
27
+ } else {
28
+ this.setAttribute("visible", "");
29
+ }
30
+ }
31
+
32
+ render() {
33
+ this.shadowRoot.innerHTML = html`
34
+ <style>
35
+ :host {
36
+ position: absolute;
37
+ top: 1rem;
38
+ left: 1rem;
39
+ z-index: 1000;
40
+ background-color: rgba(0, 0, 0, 0.33);
41
+ color: white;
42
+ padding: 1rem;
43
+ border-radius: 0.5rem;
44
+ pointer-events: none;
45
+ opacity: 0;
46
+ transition: opacity 0.3s;
47
+ font-family: sans-serif;
48
+ font-size: 0.9rem;
49
+ }
50
+
51
+ :host([visible]) {
52
+ opacity: 1;
53
+ }
54
+
55
+ .row {
56
+ display: flex;
57
+ justify-content: space-between;
58
+ gap: 20px;
59
+ margin-bottom: 4px;
60
+ }
61
+
62
+ .row:last-child {
63
+ margin-bottom: 0;
64
+ }
65
+
66
+ .label {
67
+ opacity: 0.8;
68
+ }
69
+
70
+ .val {
71
+ font-weight: bold;
72
+ font-family: monospace;
73
+ }
74
+ </style>
75
+
76
+ <div class="row"><span class="label">File size:</span><span class="val" id="file">-</span></div>
77
+ <div class="row"><span class="label">Dimensions (W x H x D):</span><span class="val" id="size">-</span></div>
78
+ <div class="row"><span class="label">Triangles:</span><span class="val" id="tri">-</span></div>
79
+ <div class="row"><span class="label">Meshes:</span><span class="val" id="mesh">-</span></div>
80
+ <div class="row"><span class="label">Materials:</span><span class="val" id="mat">-</span></div>
81
+ <div class="row"><span class="label">Textures:</span><span class="val" id="tex">-</span></div>
82
+ <div class="row"><span class="label">Animations:</span><span class="val" id="anim">-</span></div>
83
+ `;
84
+ }
85
+
86
+ async calculateStats() {
87
+ if (!this.viewer) return;
88
+
89
+ // --- File Size ---
90
+ const src = this.viewer.src;
91
+ if (src) {
92
+ fetch(src, { method: "HEAD" })
93
+ .then((res) => {
94
+ const size = res.headers.get("content-length");
95
+ if (size) {
96
+ this.updateText("file", this.formatBytes(Number(size)));
97
+ } else {
98
+ this.updateText("file", "N/A");
99
+ }
100
+ })
101
+ .catch(() => {
102
+ this.updateText("file", "Unknown");
103
+ });
104
+ }
105
+
106
+ // --- Scene traversal for geometry stats ---
107
+ const scene = this.getInternalScene(this.viewer);
108
+
109
+ if (!scene) {
110
+ console.warn("[ModelStats] Could not access internal Three.js scene.");
111
+ return;
112
+ }
113
+
114
+ let triCount = 0;
115
+ let meshCount = 0;
116
+ const materials = new Set();
117
+ const textures = new Set();
118
+ const box = new Box3();
119
+
120
+ scene.traverse((obj) => {
121
+ if (obj.isMesh && obj.geometry) {
122
+ meshCount++;
123
+ const geom = obj.geometry;
124
+ triCount += geom.index ? geom.index.count / 3 : geom.attributes.position.count / 3;
125
+
126
+ // Bounding Box
127
+ // We assume the object is part of the model.
128
+ // expandByObject computes the world-axis-aligned box
129
+ box.expandByObject(obj);
130
+
131
+ // Materials
132
+ const mats = Array.isArray(obj.material) ? obj.material : [obj.material];
133
+ mats.forEach((m) => {
134
+ materials.add(m);
135
+ // Textures
136
+ for (const key in m) {
137
+ const val = m[key];
138
+ if (val?.isTexture) {
139
+ textures.add(val.uuid);
140
+ }
141
+ }
142
+ });
143
+ }
144
+ });
145
+
146
+ // Size
147
+ if (!box.isEmpty()) {
148
+ const size = new Vector3();
149
+ box.getSize(size);
150
+ // Format as W x H x D
151
+ // box.getSize returns width, height, depth.
152
+ // Let's assume Y is up, but just printing dimensions is fine.
153
+ const fmt = (n) => `${n.toFixed(2)}`;
154
+ this.updateText("size", `${fmt(size.x)} x ${fmt(size.y)} x ${fmt(size.z)}`);
155
+ } else {
156
+ this.updateText("size", "0m");
157
+ }
158
+
159
+ const animationCount = this.viewer.availableAnimations
160
+ ? this.viewer.availableAnimations.length
161
+ : 0;
162
+
163
+ this.updateText("tri", Math.round(triCount).toLocaleString());
164
+ this.updateText("mesh", meshCount.toLocaleString());
165
+ this.updateText("mat", materials.size.toString());
166
+ this.updateText("tex", textures.size.toString());
167
+ this.updateText("anim", animationCount.toString());
168
+ }
169
+
170
+ updateText(id, text) {
171
+ const el = this.shadowRoot.getElementById(id);
172
+ if (el) el.innerText = text;
173
+ }
174
+
175
+ formatBytes(bytes, decimals = 2) {
176
+ if (!+bytes) return "0 Bytes";
177
+ const k = 1024;
178
+ const dm = decimals < 0 ? 0 : decimals;
179
+ const sizes = ["Bytes", "KB", "MB", "GB", "TB"];
180
+ const i = Math.floor(Math.log(bytes) / Math.log(k));
181
+ return `${parseFloat((bytes / k ** i).toFixed(dm))} ${sizes[i]}`;
182
+ }
183
+
184
+ /**
185
+ * Retrieves the internal Three.js Scene from a <model-viewer> instance.
186
+ * * This function bypasses the public API to access the underlying symbol
187
+ * that holds the scene context. It is robust against minification and
188
+ * internal naming changes (e.g., 'model-viewer-scene' vs 'model-viewer-artboard').
189
+ * * @param {HTMLElement} viewer - The <model-viewer> DOM element.
190
+ * @returns {Object|null} The THREE.Scene object, or null if not found.
191
+ */
192
+ getInternalScene(viewer) {
193
+ if (!viewer) return null;
194
+
195
+ // We cannot rely on the symbol name (e.g., 'model-viewer-scene') because
196
+ // it changes between versions (v3.0 vs v3.4) and is stripped in minified builds.
197
+ // Instead, we inspect the symbols to find the one holding a valid Three.js scene.
198
+
199
+ // 1. Get all symbols from the element
200
+ const symbols = Object.getOwnPropertySymbols(viewer);
201
+
202
+ // 2. Find the symbol that points to an object containing a valid THREE scene.
203
+ const sceneSymbol = symbols.find((sym) => {
204
+ const value = viewer[sym];
205
+ return value?.scene?.isScene;
206
+ });
207
+
208
+ if (!sceneSymbol) return null;
209
+
210
+ return viewer[sceneSymbol].scene;
211
+ }
212
+ }
package/src/index.d.ts ADDED
@@ -0,0 +1,2 @@
1
+ import { ModelStats } from "./ModelStats.js";
2
+ export { ModelStats };
package/src/index.js ADDED
@@ -0,0 +1,7 @@
1
+ import { ModelStats } from "./ModelStats.js";
2
+
3
+ export { ModelStats };
4
+
5
+ if (!customElements.get("model-stats")) {
6
+ customElements.define("model-stats", ModelStats);
7
+ }