diff --git "a/preprocess_manual.js" "b/preprocess_manual.js"
new file mode 100644--- /dev/null
+++ "b/preprocess_manual.js"
@@ -0,0 +1,3085 @@
+// apps/preprocess/preprocess_manual.js
+// 2025/12/12 18:08 manual mode for human completed
+// 2025/12/12 20:55 manual mode for statue completed
+
+import * as THREE from 'three';
+import { GVRM } from '../../gvrm-format/gvrm.js';
+import { PLYParser } from '../../gvrm-format/ply.js';
+import * as GVRMUtils from '../../gvrm-format/utils.js';
+import { DropInViewer } from 'gaussian-splats-3d';
+// ==========================================
+// ADD THESE IMPORTS AT THE TOP
+// ==========================================
+
+import { OrbitControls } from '../../lib/OrbitControls.js';
+
+console.log('[preprocess_manual.js] ===== MODULE LOADING =====');
+
+/**
+ * Manual UI作成関数
+ * 手動でのBOX設定と部位割り当て用のUIを提供
+ */
+
+// プリセット定義
+// プリセット定義 - 必須18ボーンをすべてカバー
+const PRESET_BONE_GROUPS = {
+ 'required19': [
+ { name: '1. Head', bones: ['head'], color: [255, 0, 0] },
+ { name: '2. Neck', bones: ['neck'], color: [255, 100, 100] },
+ { name: '3. Chest', bones: ['chest'], color: [0, 255, 0] },
+ { name: '4. Upper Chest', bones: ['upperChest'], color: [50, 255, 50] },
+ { name: '5. Spine', bones: ['spine'], color: [100, 255, 100] },
+ { name: '6. Hips', bones: ['hips'], color: [150, 255, 150] },
+ { name: '7. Left Shoulder', bones: ['leftShoulder'], color: [0, 0, 255] },
+ { name: '8. Left Upper Arm', bones: ['leftUpperArm'], color: [50, 50, 255] },
+ { name: '9. Left Lower Arm', bones: ['leftLowerArm'], color: [100, 100, 255] },
+ { name: '10. Left Hand', bones: ['leftHand'], color: [150, 150, 255] },
+ { name: '11. Right Shoulder', bones: ['rightShoulder'], color: [255, 255, 0] },
+ { name: '12. Right Upper Arm', bones: ['rightUpperArm'], color: [255, 200, 0] },
+ { name: '13. Right Lower Arm', bones: ['rightLowerArm'], color: [255, 150, 0] },
+ { name: '14. Right Hand', bones: ['rightHand'], color: [255, 100, 0] },
+ { name: '15. Left Upper Leg', bones: ['leftUpperLeg'], color: [255, 0, 255] },
+ { name: '16. Left Lower Leg', bones: ['leftLowerLeg'], color: [255, 100, 255] },
+ { name: '17. Left Foot', bones: ['leftFoot'], color: [255, 150, 255] },
+ { name: '18. Right Upper Leg', bones: ['rightUpperLeg'], color: [0, 255, 255] },
+ { name: '19. Right Lower Leg', bones: ['rightLowerLeg'], color: [100, 255, 255] },
+ { name: '20. Right Foot', bones: ['rightFoot'], color: [150, 255, 255] }
+ ]
+};
+
+
+
+// ==========================================
+// FIX 3: Add Camera Controls Setup
+// Add this function before createManualUI
+// ==========================================
+
+function setupCameraControls(camera, renderer) {
+ const controls = new OrbitControls(camera, renderer.domElement);
+ controls.enableDamping = true;
+ controls.dampingFactor = 0.05;
+ controls.screenSpacePanning = false;
+ controls.minDistance = 1;
+ controls.maxDistance = 20;
+ controls.maxPolarAngle = Math.PI;
+
+ return { controls };
+}
+
+
+
+// ==========================================
+// FIX 4: Enhanced UI with Paint Mode
+// Replace the createManualUI function 2025/12/07
+// ==========================================
+
+//////////////////////////////////////////12/13 17:30
+
+// ========================================
+// 完全に修正された createManualUI 関数
+// Line 75 から Line 537 までを、この全体で置き換えてください
+// ========================================
+
+function createManualUI(scene, camera, renderer) {
+ console.log('[createManualUI] Creating manual preprocessing UI...');
+
+ const uiContainer = document.createElement('div');
+ uiContainer.id = 'manual-ui-container';
+ uiContainer.style.cssText = `
+ position: fixed;
+ top: 20px;
+ right: 20px;
+ background: rgba(0, 0, 0, 0.85);
+ padding: 20px;
+ border-radius: 10px;
+ color: white;
+ z-index: 10000;
+ max-width: 350px;
+ max-height: 90vh;
+ overflow-y: auto;
+ display: none;
+ box-shadow: 0 4px 20px rgba(0,0,0,0.5);
+ `;
+
+ uiContainer.innerHTML = `
+
Loading PLY file...
+
+
+
+
Step 2: Assign Splats to Bones
+
+
+
+
+
+ Hold Shift to erase (unassign splats)
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
Selection Method:
+
+
+
+
+
+
+
+
+
+ Range: 0.1m - 10m (適切なサイズに調整してください)
+
+
+
+
+
+
+
+ Lock camera to prevent accidental movement while painting
+
+
+
+
+
+
Total Splats: 0
+
Assigned: 0
+
Unassigned: 0
+
+ Progress: 0%
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ `;
+
+ document.body.appendChild(uiContainer);
+
+ let boundingBoxHelper = null;
+
+ return {
+ container: uiContainer,
+
+ initialize: function() {
+ console.log('[ManualUI] initialize called');
+ return Promise.resolve({ success: true });
+ },
+
+ show: function() {
+ uiContainer.style.display = 'block';
+ },
+
+ hide: function() {
+ uiContainer.style.display = 'none';
+ },
+
+ setStatus: function(message) {
+ const statusEl = document.getElementById('manual-status');
+ if (statusEl) statusEl.textContent = message;
+ },
+
+ showPositionAdjustment: function() {
+ const section = document.getElementById('position-adjustment-section');
+ if (section) section.style.display = 'block';
+ },
+
+ hidePositionAdjustment: function() {
+ const section = document.getElementById('position-adjustment-section');
+ if (section) section.style.display = 'none';
+ },
+
+ showControls: function() {
+ const controlsEl = document.getElementById('manual-controls');
+ if (controlsEl) controlsEl.style.display = 'block';
+ },
+
+ createBoundingBox: function(size = { x: 2, y: 2, z: 2 }, position = { x: 0, y: 0, z: 0 }, rotation = { x: 0, y: 0, z: 0 }) {
+ if (boundingBoxHelper) {
+ scene.remove(boundingBoxHelper);
+ }
+
+ const geometry = new THREE.BoxGeometry(size.x, size.y, size.z);
+ const edges = new THREE.EdgesGeometry(geometry);
+ const material = new THREE.LineBasicMaterial({ color: 0x00ff00, linewidth: 2 });
+ boundingBoxHelper = new THREE.LineSegments(edges, material);
+ boundingBoxHelper.position.set(position.x, position.y, position.z);
+
+ // ⭐ 回転を追加 (Euler angles in radians)
+ boundingBoxHelper.rotation.set(rotation.x, rotation.y, rotation.z);
+
+ scene.add(boundingBoxHelper);
+
+ return boundingBoxHelper;
+ },
+
+ updateBoundingBox: function(size, position, rotation = { x: 0, y: 0, z: 0 }) {
+ if (boundingBoxHelper) {
+ scene.remove(boundingBoxHelper);
+ }
+ return this.createBoundingBox(size, position, rotation);
+ },
+
+ removeBoundingBox: function() {
+ if (boundingBoxHelper) {
+ scene.remove(boundingBoxHelper);
+ boundingBoxHelper.geometry.dispose();
+ boundingBoxHelper.material.dispose();
+ boundingBoxHelper = null;
+ }
+ },
+
+ showBoneAssignment: function() {
+ const section = document.getElementById('bone-assignment-section');
+ if (section) section.style.display = 'block';
+ },
+
+ cleanup: function() {
+ this.removeBoundingBox();
+ if (uiContainer && uiContainer.parentNode) {
+ document.body.removeChild(uiContainer);
+ }
+ }
+ };
+}
+/**
+ * Bounding Box内のスプラットのみをフィルタリング
+ */
+/////////////////////////////12/15 17:20 start
+
+
+// ========================================
+// 修正版 filterSplatsByBox 関数(詳細なデバッグ付き)
+// Line 594付近を置き換え
+// ======================================== 20251214 21:20 fix
+
+function filterSplatsByBox(plyData, boxSize, boxPosition, boxRotation = { x: 0, y: 0, z: 0 }) {
+ console.log('[filterSplatsByBox] ===== FILTERING START =====');
+ console.log('[filterSplatsByBox] Input parameters:');
+ console.log(' Box Size:', boxSize);
+ console.log(' Box Position:', boxPosition);
+ console.log(' Box Rotation (radians):', boxRotation);
+ console.log(' Box Rotation (degrees):', {
+ x: (boxRotation.x * 180 / Math.PI).toFixed(1),
+ y: (boxRotation.y * 180 / Math.PI).toFixed(1),
+ z: (boxRotation.z * 180 / Math.PI).toFixed(1)
+ });
+ console.log(' Total input vertices:', plyData.vertices.length);
+
+ const halfX = boxSize.x / 2;
+ const halfY = boxSize.y / 2;
+ const halfZ = boxSize.z / 2;
+
+ // ⭐ 浮動小数点誤差のための許容値
+ const epsilon = 0.0001;
+
+ console.log('[filterSplatsByBox] Box half-extents:', { halfX, halfY, halfZ });
+ console.log('[filterSplatsByBox] Using epsilon:', epsilon);
+
+ // Create rotation matrix
+ const rotationMatrix = new THREE.Matrix4();
+ rotationMatrix.makeRotationFromEuler(new THREE.Euler(boxRotation.x, boxRotation.y, boxRotation.z));
+
+ // Inverse matrix for transforming points into box space
+ const inverseRotationMatrix = new THREE.Matrix4().copy(rotationMatrix).invert();
+
+ console.log('[filterSplatsByBox] Rotation matrix created');
+
+ // デバッグ: 最初の10個の頂点を詳細にログ
+ console.log('[filterSplatsByBox] Sample vertices (first 10):');
+ for (let i = 0; i < Math.min(10, plyData.vertices.length); i++) {
+ const v = plyData.vertices[i];
+ const localPos = new THREE.Vector3(
+ v.x - boxPosition.x,
+ v.y - boxPosition.y,
+ v.z - boxPosition.z
+ );
+ localPos.applyMatrix4(inverseRotationMatrix);
+
+ // ⭐ 修正: epsilonを使った境界判定
+ const inside = (
+ localPos.x >= -(halfX + epsilon) && localPos.x <= (halfX + epsilon) &&
+ localPos.y >= -(halfY + epsilon) && localPos.y <= (halfY + epsilon) &&
+ localPos.z >= -(halfZ + epsilon) && localPos.z <= (halfZ + epsilon)
+ );
+
+ console.log(` Vertex ${i}:`, {
+ world: { x: v.x.toFixed(3), y: v.y.toFixed(3), z: v.z.toFixed(3) },
+ local: { x: localPos.x.toFixed(3), y: localPos.y.toFixed(3), z: localPos.z.toFixed(3) },
+ inside: inside,
+ distances: {
+ x: `${(localPos.x + halfX).toFixed(3)} / ${(halfX - localPos.x).toFixed(3)}`,
+ y: `${(localPos.y + halfY).toFixed(3)} / ${(halfY - localPos.y).toFixed(3)}`,
+ z: `${(localPos.z + halfZ).toFixed(3)} / ${(halfZ - localPos.z).toFixed(3)}`
+ }
+ });
+ }
+
+ // 実際のフィルタリング
+ const filteredVertices = plyData.vertices.filter((vertex, index) => {
+ const localPos = new THREE.Vector3(
+ vertex.x - boxPosition.x,
+ vertex.y - boxPosition.y,
+ vertex.z - boxPosition.z
+ );
+
+ localPos.applyMatrix4(inverseRotationMatrix);
+
+ // ⭐⭐⭐ CRITICAL FIX: epsilon付き境界判定 ⭐⭐⭐
+ const inside = (
+ localPos.x >= -(halfX + epsilon) && localPos.x <= (halfX + epsilon) &&
+ localPos.y >= -(halfY + epsilon) && localPos.y <= (halfY + epsilon) &&
+ localPos.z >= -(halfZ + epsilon) && localPos.z <= (halfZ + epsilon)
+ );
+
+ return inside;
+ });
+
+ // フィルタリング結果の統計
+ const retentionRate = (filteredVertices.length / plyData.vertices.length * 100).toFixed(1);
+
+ console.log('[filterSplatsByBox] ===== FILTERING COMPLETE =====');
+ console.log('[filterSplatsByBox] Results:');
+ console.log(' Filtered:', filteredVertices.length, '/', plyData.vertices.length);
+ console.log(' Retention rate:', retentionRate, '%');
+
+ // フィルタリング後の範囲を計算
+ if (filteredVertices.length > 0) {
+ let minX = Infinity, minY = Infinity, minZ = Infinity;
+ let maxX = -Infinity, maxY = -Infinity, maxZ = -Infinity;
+
+ filteredVertices.forEach(v => {
+ minX = Math.min(minX, v.x);
+ minY = Math.min(minY, v.y);
+ minZ = Math.min(minZ, v.z);
+ maxX = Math.max(maxX, v.x);
+ maxY = Math.max(maxY, v.y);
+ maxZ = Math.max(maxZ, v.z);
+ });
+
+ console.log('[filterSplatsByBox] Filtered bounds (world space):');
+ console.log(' X:', minX.toFixed(3), 'to', maxX.toFixed(3), '(size:', (maxX - minX).toFixed(3), ')');
+ console.log(' Y:', minY.toFixed(3), 'to', maxY.toFixed(3), '(size:', (maxY - minY).toFixed(3), ')');
+ console.log(' Z:', minZ.toFixed(3), 'to', maxZ.toFixed(3), '(size:', (maxZ - minZ).toFixed(3), ')');
+ console.log(' Center:', {
+ x: ((minX + maxX) / 2).toFixed(3),
+ y: ((minY + maxY) / 2).toFixed(3),
+ z: ((minZ + maxZ) / 2).toFixed(3)
+ });
+
+ // 期待されるBOXの範囲と比較
+ const expectedMinX = boxPosition.x - halfX;
+ const expectedMaxX = boxPosition.x + halfX;
+ const expectedMinY = boxPosition.y - halfY;
+ const expectedMaxY = boxPosition.y + halfY;
+ const expectedMinZ = boxPosition.z - halfZ;
+ const expectedMaxZ = boxPosition.z + halfZ;
+
+ console.log('[filterSplatsByBox] Expected bounds (if rotation = 0):');
+ console.log(' X:', expectedMinX.toFixed(3), 'to', expectedMaxX.toFixed(3));
+ console.log(' Y:', expectedMinY.toFixed(3), 'to', expectedMaxY.toFixed(3));
+ console.log(' Z:', expectedMinZ.toFixed(3), 'to', expectedMaxZ.toFixed(3));
+
+ // ⭐ 誤差チェック
+ const errorX = Math.max(Math.abs(minX - expectedMinX), Math.abs(maxX - expectedMaxX));
+ const errorY = Math.max(Math.abs(minY - expectedMinY), Math.abs(maxY - expectedMaxY));
+ const errorZ = Math.max(Math.abs(minZ - expectedMinZ), Math.abs(maxZ - expectedMaxZ));
+
+ console.log('[filterSplatsByBox] Boundary errors:');
+ console.log(' X error:', errorX.toFixed(3), 'm');
+ console.log(' Y error:', errorY.toFixed(3), 'm');
+ console.log(' Z error:', errorZ.toFixed(3), 'm');
+
+ if (errorX > 0.1 || errorY > 0.1 || errorZ > 0.1) {
+ console.warn('[filterSplatsByBox] ⚠️ Boundary error > 0.1m detected!');
+ }
+ }
+
+ // 警告
+ if (filteredVertices.length < plyData.vertices.length * 0.1) {
+ console.warn('[filterSplatsByBox] ⚠️ WARNING: Less than 10% of splats kept!');
+ console.warn('[filterSplatsByBox] Box may be too small or positioned incorrectly');
+ }
+
+ if (filteredVertices.length === 0) {
+ console.error('[filterSplatsByBox] ❌ ERROR: No vertices passed the filter!');
+ console.error('[filterSplatsByBox] Check box position and size');
+ }
+
+ return filteredVertices;
+}
+
+
+//////////////////////////////12/15 17:20 end
+
+
+/**
+ * フィルタリングされたスプラットから新しいPLYファイルを作成
+ */
+function createFilteredPLY(parser, originalHeader, filteredVertices, vertexSize) {
+ const newHeader = originalHeader.map(line => {
+ if (line.startsWith('element vertex')) {
+ return `element vertex ${filteredVertices.length}`;
+ }
+ return line;
+ });
+
+ const newPlyData = parser.createPLYFile(newHeader, filteredVertices, vertexSize);
+ const blob = new Blob([newPlyData], { type: 'application/octet-stream' });
+ return URL.createObjectURL(blob);
+}
+
+//////////////////////////////////////////////12/14 13:40 start
+
+/**
+ * PLYファイルをダウンロード
+ */
+function downloadPLY(plyData, filename) {
+ const blob = new Blob([plyData], { type: 'application/octet-stream' });
+ const url = URL.createObjectURL(blob);
+
+ const link = document.createElement('a');
+ link.href = url;
+ link.download = filename;
+ link.style.display = 'none';
+
+ document.body.appendChild(link);
+ link.click();
+
+ // クリーンアップ
+ setTimeout(() => {
+ document.body.removeChild(link);
+ URL.revokeObjectURL(url);
+ }, 100);
+
+ console.log('[downloadPLY] Downloaded:', filename);
+}
+
+
+//////////////////////////////////////////////12/14 13:40 end
+
+///////////////////////////////////////////////////12/13 14:00
+
+ // ========================================
+ // Keyboard Controls - Global Variables and Helper Functions
+ // ========================================
+ let activeKeys = [];
+
+ // Helper functions for matrix operations
+ function invert4(a) {
+ let b00 = a[0] * a[5] - a[1] * a[4];
+ let b01 = a[0] * a[6] - a[2] * a[4];
+ let b02 = a[0] * a[7] - a[3] * a[4];
+ let b03 = a[1] * a[6] - a[2] * a[5];
+ let b04 = a[1] * a[7] - a[3] * a[5];
+ let b05 = a[2] * a[7] - a[3] * a[6];
+ let b06 = a[8] * a[13] - a[9] * a[12];
+ let b07 = a[8] * a[14] - a[10] * a[12];
+ let b08 = a[8] * a[15] - a[11] * a[12];
+ let b09 = a[9] * a[14] - a[10] * a[13];
+ let b10 = a[9] * a[15] - a[11] * a[13];
+ let b11 = a[10] * a[15] - a[11] * a[14];
+ let det = b00 * b11 - b01 * b10 + b02 * b09 + b03 * b08 - b04 * b07 + b05 * b06;
+ if (!det) return null;
+ return [
+ (a[5] * b11 - a[6] * b10 + a[7] * b09) / det,
+ (a[2] * b10 - a[1] * b11 - a[3] * b09) / det,
+ (a[13] * b05 - a[14] * b04 + a[15] * b03) / det,
+ (a[10] * b04 - a[9] * b05 - a[11] * b03) / det,
+ (a[6] * b08 - a[4] * b11 - a[7] * b07) / det,
+ (a[0] * b11 - a[2] * b08 + a[3] * b07) / det,
+ (a[14] * b02 - a[12] * b05 - a[15] * b01) / det,
+ (a[8] * b05 - a[10] * b02 + a[11] * b01) / det,
+ (a[4] * b10 - a[5] * b08 + a[7] * b06) / det,
+ (a[1] * b08 - a[0] * b10 - a[3] * b06) / det,
+ (a[12] * b04 - a[13] * b02 + a[15] * b00) / det,
+ (a[9] * b02 - a[8] * b04 - a[11] * b00) / det,
+ (a[5] * b07 - a[4] * b09 - a[6] * b06) / det,
+ (a[0] * b09 - a[1] * b07 + a[2] * b06) / det,
+ (a[13] * b01 - a[12] * b03 - a[14] * b00) / det,
+ (a[8] * b03 - a[9] * b01 + a[10] * b00) / det,
+ ];
+ }
+
+ function rotate4(a, rad, x, y, z) {
+ let len = Math.hypot(x, y, z);
+ x /= len;
+ y /= len;
+ z /= len;
+ let s = Math.sin(rad);
+ let c = Math.cos(rad);
+ let t = 1 - c;
+ let b00 = x * x * t + c;
+ let b01 = y * x * t + z * s;
+ let b02 = z * x * t - y * s;
+ let b10 = x * y * t - z * s;
+ let b11 = y * y * t + c;
+ let b12 = z * y * t + x * s;
+ let b20 = x * z * t + y * s;
+ let b21 = y * z * t - x * s;
+ let b22 = z * z * t + c;
+ return [
+ a[0] * b00 + a[4] * b01 + a[8] * b02,
+ a[1] * b00 + a[5] * b01 + a[9] * b02,
+ a[2] * b00 + a[6] * b01 + a[10] * b02,
+ a[3] * b00 + a[7] * b01 + a[11] * b02,
+ a[0] * b10 + a[4] * b11 + a[8] * b12,
+ a[1] * b10 + a[5] * b11 + a[9] * b12,
+ a[2] * b10 + a[6] * b11 + a[10] * b12,
+ a[3] * b10 + a[7] * b11 + a[11] * b12,
+ a[0] * b20 + a[4] * b21 + a[8] * b22,
+ a[1] * b20 + a[5] * b21 + a[9] * b22,
+ a[2] * b20 + a[6] * b21 + a[10] * b22,
+ a[3] * b20 + a[7] * b21 + a[11] * b22,
+ ...a.slice(12, 16),
+ ];
+ }
+
+ function translate4(a, x, y, z) {
+ return [
+ ...a.slice(0, 12),
+ a[0] * x + a[4] * y + a[8] * z + a[12],
+ a[1] * x + a[5] * y + a[9] * z + a[13],
+ a[2] * x + a[6] * y + a[10] * z + a[14],
+ a[3] * x + a[7] * y + a[11] * z + a[15],
+ ];
+ }
+
+ // Camera manipulation function
+ function updateCameraFromKeys(camera, cameraControls) {
+ if (activeKeys.length === 0) return;
+
+ // Get current camera matrix
+ let inv = invert4(camera.matrixWorld.elements);
+ if (!inv) return;
+
+ const shiftKey = activeKeys.includes("ShiftLeft") || activeKeys.includes("ShiftRight");
+
+ // Movement (arrow keys)
+ if (activeKeys.includes("ArrowUp")) {
+ if (shiftKey) {
+ inv = translate4(inv, 0, -0.03, 0);
+ } else {
+ inv = translate4(inv, 0, 0, 0.1);
+ }
+ }
+ if (activeKeys.includes("ArrowDown")) {
+ if (shiftKey) {
+ inv = translate4(inv, 0, 0.03, 0);
+ } else {
+ inv = translate4(inv, 0, 0, -0.1);
+ }
+ }
+ if (activeKeys.includes("ArrowLeft")) {
+ inv = translate4(inv, -0.03, 0, 0);
+ }
+ if (activeKeys.includes("ArrowRight")) {
+ inv = translate4(inv, 0.03, 0, 0);
+ }
+
+ // Camera angle (WASD)
+ if (activeKeys.includes("KeyA")) {
+ inv = rotate4(inv, -0.01, 0, 1, 0);
+ }
+ if (activeKeys.includes("KeyD")) {
+ inv = rotate4(inv, 0.01, 0, 1, 0);
+ }
+ if (activeKeys.includes("KeyW")) {
+ inv = rotate4(inv, 0.005, 1, 0, 0);
+ }
+ if (activeKeys.includes("KeyS")) {
+ inv = rotate4(inv, -0.005, 1, 0, 0);
+ }
+ if (activeKeys.includes("KeyQ")) {
+ inv = rotate4(inv, 0.01, 0, 0, 1);
+ }
+ if (activeKeys.includes("KeyE")) {
+ inv = rotate4(inv, -0.01, 0, 0, 1);
+ }
+
+ // Orbit (IJKL)
+ if (activeKeys.includes("KeyI") || activeKeys.includes("KeyK") ||
+ activeKeys.includes("KeyJ") || activeKeys.includes("KeyL")) {
+ let d = 4;
+ inv = translate4(inv, 0, 0, d);
+ inv = rotate4(
+ inv,
+ activeKeys.includes("KeyJ") ? -0.05 : activeKeys.includes("KeyL") ? 0.05 : 0,
+ 0, 1, 0
+ );
+ inv = rotate4(
+ inv,
+ activeKeys.includes("KeyI") ? 0.05 : activeKeys.includes("KeyK") ? -0.05 : 0,
+ 1, 0, 0
+ );
+ inv = translate4(inv, 0, 0, -d);
+ }
+
+ // Apply transformation
+ const newMatrix = invert4(inv);
+ if (newMatrix) {
+ camera.matrix.fromArray(newMatrix);
+ camera.matrix.decompose(camera.position, camera.quaternion, camera.scale);
+ camera.updateMatrixWorld(true);
+
+ // Temporarily disable OrbitControls
+ if (cameraControls && cameraControls.controls) {
+ cameraControls.controls.enabled = false;
+ setTimeout(() => {
+ if (cameraControls && cameraControls.controls) {
+ cameraControls.controls.enabled = true;
+ }
+ }, 100);
+ }
+ }
+ }
+
+ // Set up keyboard event listeners (call once)
+ function setupKeyboardControls() {
+ window.addEventListener("keydown", (e) => {
+ if (!activeKeys.includes(e.code)) {
+ activeKeys.push(e.code);
+ }
+ });
+
+ window.addEventListener("keyup", (e) => {
+ activeKeys = activeKeys.filter((k) => k !== e.code);
+ });
+
+ window.addEventListener("blur", () => {
+ activeKeys = [];
+ });
+ }
+
+/////////////////////////////////////////////////
+
+/**
+ * Manual preprocessing - メイン関数
+ */
+
+
+export function preprocessManual(vrmPath, gsPath, scene, camera, renderer, stage, useGPU, noBG, noCheck, fileName, savePly) {
+
+ console.log('[preprocessManual] ===== FUNCTION CALLED =====');
+ console.log('[preprocessManual] Parameters:');
+ console.log(' vrmPath:', vrmPath);
+ console.log(' gsPath:', gsPath);
+ console.log(' fileName:', fileName);
+
+ return new Promise((resolve, reject) => {
+ console.log('[preprocessManual] Creating Promise...');
+
+ try {
+ const ui = createManualUI(scene, camera, renderer);
+ console.log('[preprocessManual] UI created');
+
+ ui.initialize().then(() => {
+ console.log('[preprocessManual] UI initialized, starting manual process...');
+
+ ui.show();
+ ui.setStatus('Loading PLY file...');
+
+ // PLYファイルの読み込み
+ const parser = new PLYParser();
+ let loadingSpinner = new DropInViewer().viewer.loadingSpinner;
+ const task = loadingSpinner.addTask('Loading PLY...');
+
+
+ ///////////////////////12/13 15:20
+
+ parser.parsePLY(gsPath, true).then((plyData) => {
+ console.log('[preprocessManual] PLY loaded:', plyData.vertices.length, 'vertices');
+ loadingSpinner.removeTask(task);
+
+ // ========================================
+ // Calculate Bounding Box from PLY data
+ // ========================================
+ let minX = Infinity, minY = Infinity, minZ = Infinity;
+ let maxX = -Infinity, maxY = -Infinity, maxZ = -Infinity;
+
+ plyData.vertices.forEach(vertex => {
+ minX = Math.min(minX, vertex.x);
+ minY = Math.min(minY, vertex.y);
+ minZ = Math.min(minZ, vertex.z);
+ maxX = Math.max(maxX, vertex.x);
+ maxY = Math.max(maxY, vertex.y);
+ maxZ = Math.max(maxZ, vertex.z);
+ });
+
+ // Calculate size and center
+ const sizeX = maxX - minX;
+ const sizeY = maxY - minY;
+ const sizeZ = maxZ - minZ;
+ const centerX = (maxX + minX) / 2;
+ const centerY = (maxY + minY) / 2;
+ const centerZ = (maxZ + minZ) / 2;
+
+ // Add 20% margin for safety
+ const margin = 1.2;
+ const defaultBoxSize = {
+ x: sizeX * margin,
+ y: sizeY * margin,
+ z: sizeZ * margin
+ };
+ const defaultBoxPosition = {
+ x: centerX,
+ y: centerY,
+ z: centerZ
+ };
+
+ console.log('[preprocessManual] Calculated bounding box:');
+ console.log(' Size:', defaultBoxSize);
+ console.log(' Center:', defaultBoxPosition);
+ console.log(' Raw size:', { x: sizeX, y: sizeY, z: sizeZ });
+
+ // GSの初期表示, replace all 20251207
+ GVRM.initGS(gsPath, undefined, undefined, scene).then((gs) => {
+ console.log('[preprocessManual] GS initialized');
+
+ // ★★★ ADD CAMERA CONTROLS HERE ★★★
+ const cameraControls = setupCameraControls(camera, renderer);
+
+ // ⭐ Initialize keyboard controls 12/13 14:00
+ setupKeyboardControls();
+
+ // Animation loop for smooth camera controls
+ let animationId = null;
+ function animateControls() {
+ animationId = requestAnimationFrame(animateControls);
+ updateCameraFromKeys(camera, cameraControls);
+ cameraControls.controls.update();
+ renderer.render(scene, camera);
+ }
+
+ animateControls();
+
+ // Cleanup function to stop animation
+ const cleanupAnimation = () => {
+ if (animationId) {
+ cancelAnimationFrame(animationId);
+ animationId = null;
+ }
+ };
+
+//////////////// handle key 12/13 13:30
+
+ // ========================================
+ // Keyboard Controls for Camera Movement: Deleted 12/13 13:50
+ // ========================================
+
+////////////////////////////12/13 16:20 START
+
+ // ========================================
+ // Step 0: PLY Position Adjustment
+ // ========================================
+
+ // ========================================
+ // Step 0: Box and PLY Position Adjustment
+ // ========================================
+
+ ui.setStatus('Step 0: Adjust bounding box to frame your object');
+ ui.showPositionAdjustment();
+
+ // Calculate and display scene bounds
+ let minX = Infinity, minY = Infinity, minZ = Infinity;
+ let maxX = -Infinity, maxY = -Infinity, maxZ = -Infinity;
+
+ plyData.vertices.forEach(vertex => {
+ minX = Math.min(minX, vertex.x);
+ minY = Math.min(minY, vertex.y);
+ minZ = Math.min(minZ, vertex.z);
+ maxX = Math.max(maxX, vertex.x);
+ maxY = Math.max(maxY, vertex.y);
+ maxZ = Math.max(maxZ, vertex.z);
+ });
+
+ const sceneSize = {
+ x: maxX - minX,
+ y: maxY - minY,
+ z: maxZ - minZ
+ };
+ const sceneCenter = {
+ x: (maxX + minX) / 2,
+ y: (maxY + minY) / 2,
+ z: (maxZ + minZ) / 2
+ };
+
+ console.log('[preprocessManual] Scene bounds:', {
+ size: sceneSize,
+ center: sceneCenter
+ });
+
+ // Display scene info in UI
+ const sceneSizeEl = document.getElementById('scene-size');
+ const sceneCenterEl = document.getElementById('scene-center');
+ if (sceneSizeEl) {
+ sceneSizeEl.textContent = `${sceneSize.x.toFixed(1)}m × ${sceneSize.y.toFixed(1)}m × ${sceneSize.z.toFixed(1)}m`;
+ }
+ if (sceneCenterEl) {
+ sceneCenterEl.textContent = `(${sceneCenter.x.toFixed(1)}, ${sceneCenter.y.toFixed(1)}, ${sceneCenter.z.toFixed(1)})`;
+ }
+
+ // Initial box settings (conservative defaults)
+ let boxSize = { x: 3, y: 3, z: 3 };
+ let boxPosition = { x: 0, y: 0, z: 0 };
+ let plyOffset = { x: 0, y: 0, z: 0 };
+
+ const gsScene = gs.viewer.splatMesh.scenes[0];
+
+ // Create initial bounding box
+ ui.createBoundingBox(boxSize, boxPosition);
+
+
+
+ // Box size sliders
+ // Box size sliders
+ const setupBoxSizeSlider = (id, valueId, axis) => {
+ const slider = document.getElementById(id);
+ const valueDisplay = document.getElementById(valueId);
+
+ if (slider && valueDisplay) {
+ slider.addEventListener('input', (e) => {
+ const value = parseFloat(e.target.value);
+ valueDisplay.textContent = value.toFixed(1);
+ boxSize[axis] = value;
+ ui.updateBoundingBox(boxSize, boxPosition, boxRotation); // ⭐ 回転を渡す
+ });
+ }
+ };
+
+ // Box position sliders
+ const setupBoxPosSlider = (id, valueId, axis) => {
+ const slider = document.getElementById(id);
+ const valueDisplay = document.getElementById(valueId);
+
+ if (slider && valueDisplay) {
+ slider.addEventListener('input', (e) => {
+ const value = parseFloat(e.target.value);
+ valueDisplay.textContent = value.toFixed(1);
+ boxPosition[axis] = value;
+ ui.updateBoundingBox(boxSize, boxPosition, boxRotation); // ⭐ 回転を渡す
+ });
+ }
+ };
+
+/////////////////////////12/13 17:15 start
+
+ // この変数を追加 (line 1002付近):
+ let boxRotation = { x: 0, y: 0, z: 0 };
+
+ // Box rotation sliders (setupPlyOffsetSlider の後に追加):
+ const setupBoxRotSlider = (id, valueId, axis) => {
+ const slider = document.getElementById(id);
+ const valueDisplay = document.getElementById(valueId);
+
+ if (slider && valueDisplay) {
+ slider.addEventListener('input', (e) => {
+ const degrees = parseFloat(e.target.value);
+ valueDisplay.textContent = degrees.toFixed(0);
+ boxRotation[axis] = degrees * Math.PI / 180; // Convert to radians
+ ui.updateBoundingBox(boxSize, boxPosition, boxRotation);
+ });
+ }
+ };
+
+ // Setup rotation sliders (setupPlyOffsetSlider の呼び出しの後に追加):
+ setupBoxRotSlider('box-rot-y-step0', 'box-rot-y-value-step0', 'y');
+ setupBoxRotSlider('box-rot-x-step0', 'box-rot-x-value-step0', 'x');
+ setupBoxRotSlider('box-rot-z-step0', 'box-rot-z-value-step0', 'z');
+
+
+/////////////////////////12/13 17:15 end
+
+ // PLY offset sliders
+ const setupPlyOffsetSlider = (id, valueId, axis) => {
+ const slider = document.getElementById(id);
+ const valueDisplay = document.getElementById(valueId);
+
+ if (slider && valueDisplay) {
+ slider.addEventListener('input', (e) => {
+ const value = parseFloat(e.target.value);
+ valueDisplay.textContent = value.toFixed(1);
+ plyOffset[axis] = value;
+ gsScene.position[axis] = value;
+ gsScene.updateMatrixWorld();
+ });
+ }
+ };
+
+ // Setup all sliders
+ setupBoxSizeSlider('box-x-step0', 'box-x-value-step0', 'x');
+ setupBoxSizeSlider('box-y-step0', 'box-y-value-step0', 'y');
+ setupBoxSizeSlider('box-z-step0', 'box-z-value-step0', 'z');
+
+ setupBoxPosSlider('box-x-pos-step0', 'box-x-pos-value-step0', 'x');
+ setupBoxPosSlider('box-y-pos-step0', 'box-y-pos-value-step0', 'y');
+ setupBoxPosSlider('box-z-pos-step0', 'box-z-pos-value-step0', 'z');
+
+ setupPlyOffsetSlider('ply-x', 'ply-x-value', 'x');
+ setupPlyOffsetSlider('ply-y', 'ply-y-value', 'y');
+ setupPlyOffsetSlider('ply-z', 'ply-z-value', 'z');
+
+
+ /////////////////////////12/13 17:15 start
+ // Reset button
+ const resetAllBtn = document.getElementById('reset-all-btn');
+ if (resetAllBtn) {
+ resetAllBtn.addEventListener('click', () => {
+
+
+ // Reset rotation addition ########
+ boxRotation = { x: 0, y: 0, z: 0 };
+ document.getElementById('box-rot-y-step0').value = 0;
+ document.getElementById('box-rot-x-step0').value = 0;
+ document.getElementById('box-rot-z-step0').value = 0;
+ document.getElementById('box-rot-y-value-step0').textContent = '0';
+ document.getElementById('box-rot-x-value-step0').textContent = '0';
+ document.getElementById('box-rot-z-value-step0').textContent = '0';
+
+
+ // Reset box
+ boxSize = { x: 3, y: 3, z: 3 };
+ boxPosition = { x: 0, y: 0, z: 0 }; // ← y: 1 から y: 0 に変更
+ document.getElementById('box-x-step0').value = 3;
+ document.getElementById('box-y-step0').value = 3;
+ document.getElementById('box-z-step0').value = 3;
+ document.getElementById('box-x-value-step0').textContent = '3.0';
+ document.getElementById('box-y-value-step0').textContent = '3.0';
+ document.getElementById('box-z-value-step0').textContent = '3.0';
+
+ document.getElementById('box-x-pos-step0').value = 0;
+ document.getElementById('box-y-pos-step0').value = 0; // ← 1 から 0 に変更
+ document.getElementById('box-z-pos-step0').value = 0;
+ document.getElementById('box-x-pos-value-step0').textContent = '0.0';
+ document.getElementById('box-y-pos-value-step0').textContent = '0.0'; // ← '1.0' から '0.0' に変更
+ document.getElementById('box-z-pos-value-step0').textContent = '0.0';
+
+ // Reset PLY offset
+ plyOffset = { x: 0, y: 0, z: 0 };
+ document.getElementById('ply-x').value = 0;
+ document.getElementById('ply-y').value = 0;
+ document.getElementById('ply-z').value = 0;
+ document.getElementById('ply-x-value').textContent = '0.0';
+ document.getElementById('ply-y-value').textContent = '0.0';
+ document.getElementById('ply-z-value').textContent = '0.0';
+
+ gsScene.position.set(0, 0, 0);
+ gsScene.updateMatrixWorld();
+ ui.updateBoundingBox(boxSize, boxPosition, boxRotation); // ⭐ 最後の引数を追加
+ });
+ }
+ /////////////////////////12/13 17:15 end
+
+ // Confirm button
+
+ // ----------------------------------------
+ // 完全版: confirmBoxBtn のイベントリスナー
+ // Line 1107から約100行を以下に置き換え
+ // ----------------------------------------
+/////////////////// 12/15 18:00 全面描き直し
+
+ // ========================================
+ // 修正版 confirmBoxBtn(完全なデバッグ版)
+ // Line 1090-1220付近を置き換え
+ // ========================================
+
+ const confirmBoxBtn = document.getElementById('confirm-box-btn');
+ if (confirmBoxBtn) {
+ confirmBoxBtn.addEventListener('click', async () => {
+ console.log('\n\n');
+ console.log('═══════════════════════════════════════════════════════');
+ console.log(' CONFIRM BOX BUTTON CLICKED');
+ console.log('═══════════════════════════════════════════════════════');
+
+ // 現在のBOX設定をログ
+ console.log('[STEP 1] Current BOX Settings:');
+ console.log(' Box Size:', boxSize);
+ console.log(' Box Position:', boxPosition);
+ console.log(' Box Rotation (radians):', boxRotation);
+ console.log(' Box Rotation (degrees):', {
+ x: (boxRotation.x * 180 / Math.PI).toFixed(1) + '°',
+ y: (boxRotation.y * 180 / Math.PI).toFixed(1) + '°',
+ z: (boxRotation.z * 180 / Math.PI).toFixed(1) + '°'
+ });
+ console.log(' PLY Offset:', plyOffset);
+
+ // 元のPLYデータの範囲を表示
+ console.log('[STEP 2] Original PLY Data:');
+ console.log(' Total vertices:', plyData.vertices.length);
+
+ let origMinX = Infinity, origMinY = Infinity, origMinZ = Infinity;
+ let origMaxX = -Infinity, origMaxY = -Infinity, origMaxZ = -Infinity;
+
+ plyData.vertices.forEach(v => {
+ origMinX = Math.min(origMinX, v.x);
+ origMinY = Math.min(origMinY, v.y);
+ origMinZ = Math.min(origMinZ, v.z);
+ origMaxX = Math.max(origMaxX, v.x);
+ origMaxY = Math.max(origMaxY, v.y);
+ origMaxZ = Math.max(origMaxZ, v.z);
+ });
+
+ console.log(' Original bounds:');
+ console.log(' X:', origMinX.toFixed(3), 'to', origMaxX.toFixed(3));
+ console.log(' Y:', origMinY.toFixed(3), 'to', origMaxY.toFixed(3));
+ console.log(' Z:', origMinZ.toFixed(3), 'to', origMaxZ.toFixed(3));
+ console.log(' Original center:', {
+ x: ((origMinX + origMaxX) / 2).toFixed(3),
+ y: ((origMinY + origMaxY) / 2).toFixed(3),
+ z: ((origMinZ + origMaxZ) / 2).toFixed(3)
+ });
+
+ cleanupAnimation();
+
+ // PLY Offsetの適用
+ if (plyOffset.x !== 0 || plyOffset.y !== 0 || plyOffset.z !== 0) {
+ console.log('[STEP 3] Applying PLY offset:', plyOffset);
+
+ plyData.vertices.forEach(vertex => {
+ vertex.x += plyOffset.x;
+ vertex.y += plyOffset.y;
+ vertex.z += plyOffset.z;
+ });
+
+ await gs.viewer.dispose();
+
+ const newHeader = plyData.header;
+ const newPlyData = parser.createPLYFile(newHeader, plyData.vertices, plyData.vertexSize);
+ const blob = new Blob([newPlyData], { type: 'application/octet-stream' });
+ const adjustedPlyUrl = URL.createObjectURL(blob);
+
+ gs = await GVRM.initGS(adjustedPlyUrl, undefined, undefined, scene);
+ console.log('[STEP 3] ✓ GS reloaded with adjusted position');
+
+ // PLY offsetをリセット
+ plyOffset = { x: 0, y: 0, z: 0 };
+ } else {
+ console.log('[STEP 3] No PLY offset to apply');
+ }
+
+ ui.hidePositionAdjustment();
+ ui.setStatus('Filtering splats with bounding box...');
+
+ // フィルタリング実行
+ console.log('[STEP 4] Starting filtering...');
+ const filteredVertices = filterSplatsByBox(plyData, boxSize, boxPosition, boxRotation);
+
+ if (filteredVertices.length === 0) {
+ console.error('[STEP 4] ❌ No splats found in the box!');
+ alert('⚠️ No splats found in the box!\n\nPlease adjust the box size/position and try again.\n\nCheck the browser console for detailed debug information.');
+ ui.showPositionAdjustment();
+ return;
+ }
+
+ if (filteredVertices.length < 10) {
+ console.warn('[STEP 4] ⚠️ Only', filteredVertices.length, 'splats found');
+ alert(`⚠️ Only ${filteredVertices.length} splats found!\n\nThis is too few. Please adjust the box.\n\nCheck the browser console for detailed debug information.`);
+ ui.showPositionAdjustment();
+ return;
+ }
+
+ // スプラットを中心化
+ console.log('[STEP 5] Centering splats...');
+
+ let newMinX = Infinity, newMinY = Infinity, newMinZ = Infinity;
+ let newMaxX = -Infinity, newMaxY = -Infinity, newMaxZ = -Infinity;
+
+ filteredVertices.forEach(vertex => {
+ newMinX = Math.min(newMinX, vertex.x);
+ newMinY = Math.min(newMinY, vertex.y);
+ newMinZ = Math.min(newMinZ, vertex.z);
+ newMaxX = Math.max(newMaxX, vertex.x);
+ newMaxY = Math.max(newMaxY, vertex.y);
+ newMaxZ = Math.max(newMaxZ, vertex.z);
+ });
+
+ const centerX = (newMaxX + newMinX) / 2;
+ const centerY = (newMaxY + newMinY) / 2;
+ const centerZ = (newMaxZ + newMinZ) / 2;
+
+ console.log('[STEP 5] Before centering:', {
+ center: { x: centerX.toFixed(3), y: centerY.toFixed(3), z: centerZ.toFixed(3) }
+ });
+
+ filteredVertices.forEach(vertex => {
+ vertex.x -= centerX;
+ vertex.y -= centerY;
+ vertex.z -= centerZ;
+ });
+
+ console.log('[STEP 5] ✓ Splats centered to origin');
+
+ // フィルタ済みPLYを保存
+ console.log('[STEP 6] Saving filtered PLY...');
+ try {
+ ui.setStatus('Saving filtered & centered PLY file...');
+
+ const newHeader = plyData.header.map(line => {
+ if (line.startsWith('element vertex')) {
+ return `element vertex ${filteredVertices.length}`;
+ }
+ return line;
+ });
+
+ const filteredPlyData = parser.createPLYFile(
+ newHeader,
+ filteredVertices,
+ plyData.vertexSize
+ );
+
+ const originalFilename = gsPath.split('/').pop().replace('.ply', '');
+ const timestamp = new Date().toISOString().replace(/[:.]/g, '-').slice(0, -5);
+ const filteredFilename = `${originalFilename}_filtered_${timestamp}.ply`;
+
+ downloadPLY(filteredPlyData, filteredFilename);
+
+ console.log('[STEP 6] ✓ PLY saved:', filteredFilename);
+ console.log('[STEP 6] Statistics:');
+ console.log(' Original:', plyData.vertices.length, 'vertices');
+ console.log(' Filtered:', filteredVertices.length, 'vertices');
+ console.log(' Reduction:', ((1 - filteredVertices.length / plyData.vertices.length) * 100).toFixed(1), '%');
+
+ ui.setStatus(`✓ Saved: ${filteredFilename}`);
+ await new Promise(resolve => setTimeout(resolve, 1000));
+
+ } catch (error) {
+ console.error('[STEP 6] ❌ Error saving PLY:', error);
+ alert('Failed to save filtered PLY file: ' + error.message);
+ }
+
+ // 残りの処理
+ console.log('[STEP 7] Loading filtered splats into viewer...');
+ ui.setStatus('Loading filtered splats...');
+
+ const filteredPlyUrl = createFilteredPLY(
+ parser,
+ plyData.header,
+ filteredVertices,
+ plyData.vertexSize
+ );
+
+ await gs.viewer.dispose();
+
+ const filteredGs = await GVRM.initGS(filteredPlyUrl, undefined, undefined, scene);
+ console.log('[STEP 7] ✓ Filtered GS loaded');
+
+ ui.removeBoundingBox();
+ ui.setStatus('Loading VRM...');
+
+ const character = await GVRM.initVRM(vrmPath, scene, camera, renderer, null);
+ console.log('[STEP 7] ✓ VRM loaded');
+
+ const gvrm = new GVRM(character, filteredGs);
+
+ ui.setStatus('Step 2: Assign splats to bones');
+ ui.showBoneAssignment();
+
+ console.log('═══════════════════════════════════════════════════════');
+ console.log(' BOX FILTERING COMPLETE');
+ console.log('═══════════════════════════════════════════════════════');
+ console.log('\n\n');
+
+ const promise2 = setupBoneAssignment(
+ ui, scene, camera, renderer,
+ gvrm, character, filteredGs, filteredPlyUrl,
+ vrmPath, useGPU, savePly, fileName,
+ { vertices: filteredVertices, header: plyData.header, vertexSize: plyData.vertexSize },
+ plyData
+ );
+
+ resolve({
+ gvrm: gvrm,
+ promise2: promise2,
+ error: null,
+ ui: ui
+ });
+ });
+ }
+
+////////////////// 12/15 18:00 全面描き直し
+
+ }); // GVRM.initGS().then()閉じる
+ }); // parser.parsePLY().then()閉じる
+ }); // ui.initialize().then()閉じる
+
+ } catch (error) {
+ console.error('[preprocessManual] Error:', error);
+ reject(error);
+ }
+ });
+}
+ // ========================================
+ // Step 1: Bounding Box Adjustment Deleted
+ // ========================================
+
+////////////////////////////12/13 16:20 END
+
+
+
+// ========================================
+// Bone Assignment Setup Function
+// ========================================
+
+// ========================================
+// Complete setupBoneAssignment Function
+// Replace your entire setupBoneAssignment function with this
+// ========================================
+
+function setupBoneAssignment(ui, scene, camera, renderer, gvrm, character, filteredGs, filteredPlyUrl, vrmPath, useGPU, savePly, fileName, plyData, originalPlyData) {
+ return new Promise(async (resolve2) => {
+ console.log('[setupBoneAssignment] Starting bone assignment...');
+
+ try {
+///////////////////
+ // ⭐ オブジェクトのサイズから適切な初期半径を計算
+ function calculateOptimalRadius(filteredGs) {
+ // スプラットの範囲を計算
+ let minX = Infinity, minY = Infinity, minZ = Infinity;
+ let maxX = -Infinity, maxY = -Infinity, maxZ = -Infinity;
+
+ for (let i = 0; i < filteredGs.splatCount; i++) {
+ const x = filteredGs.centers0[i * 3 + 0];
+ const y = filteredGs.centers0[i * 3 + 1];
+ const z = filteredGs.centers0[i * 3 + 2];
+
+ minX = Math.min(minX, x);
+ minY = Math.min(minY, y);
+ minZ = Math.min(minZ, z);
+ maxX = Math.max(maxX, x);
+ maxY = Math.max(maxY, y);
+ maxZ = Math.max(maxZ, z);
+ }
+
+ // オブジェクトの最大サイズを取得
+ const sizeX = maxX - minX;
+ const sizeY = maxY - minY;
+ const sizeZ = maxZ - minZ;
+ const maxSize = Math.max(sizeX, sizeY, sizeZ);
+
+ // 適切な初期半径 = オブジェクトサイズの5%(調整可能)
+ const optimalRadius = Math.max(0.1, Math.min(10.0, maxSize * 0.05));
+
+ console.log('[calculateOptimalRadius] Object size:', { sizeX, sizeY, sizeZ, maxSize });
+ console.log('[calculateOptimalRadius] Optimal radius:', optimalRadius.toFixed(2), 'm');
+
+ return optimalRadius;
+ }
+
+ // setupBoneAssignment関数内で使用:
+ // let selectionRadius = 0.5; の代わりに:
+ let selectionRadius = calculateOptimalRadius(filteredGs);
+
+ // UIの初期値も更新
+ const selectionRadiusSlider = document.getElementById('selection-radius');
+ const selectionRadiusValue = document.getElementById('selection-radius-value');
+
+ if (selectionRadiusSlider && selectionRadiusValue) {
+ selectionRadiusSlider.value = selectionRadius.toFixed(2);
+ selectionRadiusValue.textContent = selectionRadius.toFixed(2);
+
+ selectionRadiusSlider.addEventListener('input', (e) => {
+ selectionRadius = parseFloat(e.target.value);
+ selectionRadiusValue.textContent = selectionRadius.toFixed(2);
+ });
+ }
+
+///////////////////
+
+
+ // Load default bone operations
+ let response = await fetch("./assets/default.json");
+ const params = await response.json();
+ const boneOperations = params.boneOperations;
+
+ GVRMUtils.resetPose(character, boneOperations);
+ character.currentVrm.scene.updateMatrixWorld(true);
+
+ // Get VRM bone information
+ const humanBones = character.currentVrm.humanoid.humanBones;
+ const boneNames = Object.keys(humanBones);
+ const boneNameToIndex = {};
+ boneNames.forEach((name, index) => {
+ boneNameToIndex[name] = index;
+ });
+
+ console.log('[setupBoneAssignment] Available bones:', boneNames.length);
+ console.log('[setupBoneAssignment] Bone names:', boneNames);
+
+ // Assignment data management
+ const assignmentData = {
+ splatBoneIndices: new Array(filteredGs.splatCount).fill(-1),
+ boneAssignments: {},
+ history: [],
+ currentPreset: 'required19'
+ };
+
+ let selectedTarget = null;
+ let currentBoneGroups = PRESET_BONE_GROUPS.required19;
+ let selectionMode = null;
+ //let selectionRadius = 0.5;
+
+ // ========================================
+ // Paint Mode Variables
+ // ========================================
+ let isPaintMode = false;
+ let isPainting = false;
+ let paintModeEraser = false;
+
+ // ========================================
+ // Preset Selector
+ // ========================================
+ const presetSelector = document.getElementById('preset-selector');
+ const presetDescription = document.getElementById('preset-description');
+ const boneSelector = document.getElementById('bone-selector');
+
+ const presetDescriptions = {
+ 'required19': 'Required mode: Assign to 20 individual body parts (20-30 min). All bones assigned individually.'
+ };
+
+
+
+
+
+
+
+ function updateBoneSelector(mode) {
+ if (!boneSelector) {
+ console.error('[updateBoneSelector] boneSelector not found');
+ return;
+ }
+
+ console.log('[updateBoneSelector] Updating for mode:', mode);
+
+ boneSelector.innerHTML = '
';
+
+ if (mode === 'required19') {
+ const groups = PRESET_BONE_GROUPS.required19;
+ groups.forEach((group, index) => {
+ const option = document.createElement('option');
+ option.value = `group_${index}`;
+ option.textContent = group.name;
+ boneSelector.appendChild(option);
+ });
+ console.log('[updateBoneSelector] Added', groups.length, 'groups');
+ }
+ }
+
+ // Initialize preset selector
+ if (presetSelector) {
+ updateBoneSelector('required19');
+
+ if (presetDescription) {
+ presetDescription.textContent = presetDescriptions['required19'];
+ }
+
+ presetSelector.addEventListener('change', (e) => {
+ const mode = e.target.value;
+ assignmentData.currentPreset = mode;
+
+ if (mode === 'required19') {
+ currentBoneGroups = PRESET_BONE_GROUPS.required19;
+ }
+
+ if (presetDescription) {
+ presetDescription.textContent = presetDescriptions[mode] || '';
+ }
+
+ updateBoneSelector(mode);
+ console.log('[setupBoneAssignment] Preset mode changed to:', mode);
+ });
+ }
+
+ // ========================================
+ // Bone/Group Selector
+ // ========================================
+ if (boneSelector) {
+ boneSelector.addEventListener('change', (e) => {
+ selectedTarget = e.target.value;
+ console.log('[setupBoneAssignment] Selected target:', selectedTarget);
+ });
+ }
+
+ // ========================================
+ // Paint Mode Toggle
+ // ========================================
+ const paintModeToggle = document.getElementById('paint-mode-toggle');
+ const paintModeHint = document.getElementById('paint-mode-hint');
+
+ if (paintModeToggle && paintModeHint) {
+ paintModeToggle.addEventListener('change', (e) => {
+ isPaintMode = e.target.checked;
+ if (isPaintMode) {
+ paintModeHint.style.display = 'block';
+ console.log('[setupBoneAssignment] Paint mode enabled');
+ } else {
+ paintModeHint.style.display = 'none';
+ console.log('[setupBoneAssignment] Paint mode disabled');
+ }
+ });
+ }
+
+ // ========================================
+ // Statistics Update
+ // ========================================
+ function updateStats() {
+ const totalSplats = filteredGs.splatCount;
+ const assignedSplats = assignmentData.splatBoneIndices.filter(idx => idx >= 0).length;
+ const unassignedSplats = totalSplats - assignedSplats;
+ const progress = ((assignedSplats / totalSplats) * 100).toFixed(1);
+
+ const totalEl = document.getElementById('total-splats');
+ const assignedEl = document.getElementById('assigned-splats');
+ const unassignedEl = document.getElementById('unassigned-splats');
+ const progressEl = document.getElementById('assignment-progress');
+
+ if (totalEl) totalEl.textContent = totalSplats;
+ if (assignedEl) assignedEl.textContent = assignedSplats;
+ if (unassignedEl) unassignedEl.textContent = unassignedSplats;
+ if (progressEl) progressEl.textContent = progress + '%';
+
+ // Update assignment list
+ const listEl = document.getElementById('bone-assignment-list');
+ if (listEl) {
+ const entries = Object.entries(assignmentData.boneAssignments)
+ .filter(([_, indices]) => indices.length > 0)
+ .sort((a, b) => b[1].length - a[1].length);
+
+ if (entries.length === 0) {
+ listEl.innerHTML = '
No assignments yet
';
+ } else {
+ listEl.innerHTML = entries.map(([name, indices]) =>
+ `
+ ${name}: ${indices.length} splats
+
`
+ ).join('');
+ }
+ }
+ }
+
+ updateStats();
+
+ // ========================================
+ // Selection Radius
+ // ========================================
+ //const selectionRadiusSlider = document.getElementById('selection-radius');
+ //const selectionRadiusValue = document.getElementById('selection-radius-value');
+
+ if (selectionRadiusSlider && selectionRadiusValue) {
+ selectionRadiusSlider.addEventListener('input', (e) => {
+ selectionRadius = parseFloat(e.target.value);
+ selectionRadiusValue.textContent = selectionRadius.toFixed(2);
+ });
+ }
+
+ // ========================================
+ // Raycaster Setup
+ // ========================================
+ const raycaster = new THREE.Raycaster();
+ const mouse = new THREE.Vector2();
+
+ // Camera lock state
+ let cameraLocked = false;
+ const cameraLockBtn = document.getElementById('camera-lock-btn');
+
+ // Get camera controls from parent scope (assuming it's accessible)
+ // If not accessible, you'll need to pass it as parameter
+ const setupCameraLock = (controls) => {
+ if (cameraLockBtn && controls) {
+ cameraLockBtn.addEventListener('click', () => {
+ cameraLocked = !cameraLocked;
+ controls.enabled = !cameraLocked;
+
+ if (cameraLocked) {
+ cameraLockBtn.textContent = '🔒 Camera Locked (Fixed View)';
+ cameraLockBtn.style.background = '#E91E63';
+ console.log('[setupBoneAssignment] Camera locked');
+ } else {
+ cameraLockBtn.textContent = '🔓 Camera Unlocked (Can Rotate)';
+ cameraLockBtn.style.background = '#9C27B0';
+ console.log('[setupBoneAssignment] Camera unlocked');
+ }
+ });
+ }
+ };
+
+
+// Call this after OrbitControls is created
+// You'll need to pass the cameraControls.controls object
+// setupCameraLock(cameraControls.controls);
+
+
+ // ========================================
+ // Assign Splats in Sphere Function
+ // ========================================
+ ///////////////////////////12/13 19:14
+ // ========================================
+ // 完全な修正版 assignSplatsInSphere 関数
+ // Line 1477 から Line 1590 までを置き換え
+ // ========================================
+
+ function assignSplatsInSphere(center, radius, target, isPaintMode = false) {
+ console.log(`[setupBoneAssignment] Assigning splats around center to ${target}`);
+
+ const mode = assignmentData.currentPreset;
+ let targetBones = [];
+ let targetColor = [128, 128, 128];
+ let displayName = target;
+
+ if (mode === 'required19') {
+ const groupIndex = parseInt(target.replace('group_', ''));
+ const group = currentBoneGroups[groupIndex];
+
+ if (!group) {
+ console.error('[setupBoneAssignment] Group not found:', groupIndex);
+ return;
+ }
+
+ targetBones = group.bones;
+ targetColor = group.color;
+ displayName = group.name;
+
+ console.log('[setupBoneAssignment] Group:', displayName, 'Bones:', targetBones);
+ } else {
+ console.error('[setupBoneAssignment] Unknown mode:', mode);
+ return;
+ }
+
+ if (targetBones.length === 0) {
+ console.error('[setupBoneAssignment] No bones found for target:', target);
+ return;
+ }
+
+ // Get bone indices
+ const boneIndices = targetBones
+ .map(name => boneNameToIndex[name])
+ .filter(idx => idx !== undefined);
+
+ if (boneIndices.length === 0) {
+ console.error('[setupBoneAssignment] No valid bone indices for:', targetBones);
+ return;
+ }
+
+ // Use the first bone index
+ const primaryBoneIndex = boneIndices[0];
+
+ let assignedCount = 0;
+ const newlyAssigned = [];
+
+ for (let i = 0; i < filteredGs.splatCount; i++) {
+ const splatPos = new THREE.Vector3(
+ filteredGs.centers0[i * 3 + 0],
+ filteredGs.centers0[i * 3 + 1],
+ filteredGs.centers0[i * 3 + 2]
+ );
+
+ splatPos.applyMatrix4(filteredGs.viewer.splatMesh.scenes[0].matrixWorld);
+
+ const distance = splatPos.distanceTo(center);
+
+ if (distance <= radius) {
+ // In paint mode, allow overwriting existing assignments
+ if (isPaintMode || assignmentData.splatBoneIndices[i] < 0) {
+ // If overwriting, remove from old assignment
+ if (assignmentData.splatBoneIndices[i] >= 0 && isPaintMode) {
+ for (const [name, indices] of Object.entries(assignmentData.boneAssignments)) {
+ const idx = indices.indexOf(i);
+ if (idx > -1) {
+ indices.splice(idx, 1);
+ }
+ }
+ }
+
+ assignmentData.splatBoneIndices[i] = primaryBoneIndex;
+ newlyAssigned.push(i);
+ assignedCount++;
+
+ // Change color
+ filteredGs.colors[i * 4 + 0] = targetColor[0];
+ filteredGs.colors[i * 4 + 1] = targetColor[1];
+ filteredGs.colors[i * 4 + 2] = targetColor[2];
+ }
+ }
+ }
+
+ if (assignedCount > 0) {
+ if (!assignmentData.boneAssignments[displayName]) {
+ assignmentData.boneAssignments[displayName] = [];
+ }
+
+ // ⭐⭐⭐ CRITICAL FIX: concat を使用してスタックオーバーフローを回避 ⭐⭐⭐
+ assignmentData.boneAssignments[displayName] =
+ assignmentData.boneAssignments[displayName].concat(newlyAssigned);
+
+ // Only add to history in non-paint mode
+ if (!isPaintMode) {
+ assignmentData.history.push({
+ targetName: displayName,
+ indices: newlyAssigned,
+ boneIndex: primaryBoneIndex
+ });
+ }
+
+ filteredGs.splatMesh.updateDataTexturesFromBaseData(0, filteredGs.splatCount - 1);
+
+ updateStats();
+
+ if (!isPaintMode) {
+ console.log(`[setupBoneAssignment] Assigned ${assignedCount} splats to ${displayName}`);
+ }
+ } else if (!isPaintMode) {
+ console.log('[setupBoneAssignment] No splats found in selection');
+ }
+ }
+
+
+
+ // ========================================
+ // Erase Splats in Sphere Function
+ // ========================================
+ function eraseSplatsInSphere(center, radius) {
+ let erasedCount = 0;
+ const erased = [];
+
+ for (let i = 0; i < filteredGs.splatCount; i++) {
+ // Skip already unassigned
+ if (assignmentData.splatBoneIndices[i] < 0) continue;
+
+ const splatPos = new THREE.Vector3(
+ filteredGs.centers0[i * 3 + 0],
+ filteredGs.centers0[i * 3 + 1],
+ filteredGs.centers0[i * 3 + 2]
+ );
+
+ splatPos.applyMatrix4(filteredGs.viewer.splatMesh.scenes[0].matrixWorld);
+
+ const distance = splatPos.distanceTo(center);
+
+ if (distance <= radius) {
+ assignmentData.splatBoneIndices[i] = -1;
+ erased.push(i);
+ erasedCount++;
+
+ // Change color to gray (unassigned)
+ filteredGs.colors[i * 4 + 0] = 128;
+ filteredGs.colors[i * 4 + 1] = 128;
+ filteredGs.colors[i * 4 + 2] = 128;
+ }
+ }
+
+ if (erasedCount > 0) {
+ // Update bone assignments
+ for (const [name, indices] of Object.entries(assignmentData.boneAssignments)) {
+ assignmentData.boneAssignments[name] = indices.filter(idx => !erased.includes(idx));
+ }
+
+ filteredGs.splatMesh.updateDataTexturesFromBaseData(0, filteredGs.splatCount - 1);
+ //renderer.render(scene, camera);
+
+ updateStats();
+
+ console.log(`[setupBoneAssignment] Erased ${erasedCount} splats`);
+ }
+ }
+
+ // ========================================
+ // Paint Mode Mouse Handlers
+ // ========================================
+ function paintAtMousePosition(event) {
+ const rect = renderer.domElement.getBoundingClientRect();
+ mouse.x = ((event.clientX - rect.left) / rect.width) * 2 - 1;
+ mouse.y = -((event.clientY - rect.top) / rect.height) * 2 + 1;
+
+ raycaster.setFromCamera(mouse, camera);
+
+ const intersects = raycaster.intersectObject(filteredGs.splatMesh, true);
+
+ if (intersects.length > 0) {
+ const hitPoint = intersects[0].point;
+
+ if (paintModeEraser) {
+ // Erase mode: use full radius for larger objects
+ eraseSplatsInSphere(hitPoint, selectionRadius, true); // 0.5 → 1.0
+ } else {
+ // Paint mode: use full radius for larger objects
+ assignSplatsInSphere(hitPoint, selectionRadius, selectedTarget, true); // 0.5 → 1.0
+ }
+ }
+ }
+
+ function onMouseDown(event) {
+ if (!isPaintMode) return;
+ if (!selectedTarget) {
+ alert('Please select a target first!');
+ return;
+ }
+
+ // Check if Shift key is held for eraser mode
+ paintModeEraser = event.shiftKey;
+ isPainting = true;
+
+ // Immediately paint at click location
+ paintAtMousePosition(event);
+ }
+
+ function onMouseMove(event) {
+ if (!isPaintMode || !isPainting) return;
+
+ paintAtMousePosition(event);
+ }
+
+ function onMouseUp(event) {
+ if (!isPaintMode) return;
+ isPainting = false;
+ }
+
+ // ========================================
+ // Regular Click Handler (non-paint mode)
+ // ========================================
+ function onCanvasClick(event) {
+ // Paint mode handles clicks differently
+ if (isPaintMode) {
+ return; // Handled by mouse down/move/up
+ }
+
+ if (selectionMode !== 'sphere' || !selectedTarget) return;
+
+ const rect = renderer.domElement.getBoundingClientRect();
+ mouse.x = ((event.clientX - rect.left) / rect.width) * 2 - 1;
+ mouse.y = -((event.clientY - rect.top) / rect.height) * 2 + 1;
+
+ raycaster.setFromCamera(mouse, camera);
+
+ const intersects = raycaster.intersectObject(filteredGs.splatMesh, true);
+
+ if (intersects.length > 0) {
+ const hitPoint = intersects[0].point;
+ console.log('[setupBoneAssignment] Clicked at:', hitPoint.toArray());
+
+ assignSplatsInSphere(hitPoint, selectionRadius, selectedTarget);
+ }
+ }
+
+ // ========================================
+ // Attach Event Listeners
+ // ========================================
+ renderer.domElement.addEventListener('mousedown', onMouseDown);
+ renderer.domElement.addEventListener('mousemove', onMouseMove);
+ renderer.domElement.addEventListener('mouseup', onMouseUp);
+ renderer.domElement.addEventListener('click', onCanvasClick);
+
+ // ========================================
+ // Sphere Selection Mode Button
+ // ========================================
+ const selectSphereBtn = document.getElementById('select-sphere-btn');
+
+ if (selectSphereBtn) {
+ selectSphereBtn.addEventListener('click', () => {
+ if (!selectedTarget) {
+ alert('Please select a target first!');
+ return;
+ }
+
+ selectionMode = 'sphere';
+ selectSphereBtn.style.background = '#FF6F00';
+
+ console.log('[setupBoneAssignment] Sphere selection mode activated');
+ });
+ }
+
+ // ========================================
+ // Undo Last Assignment
+ // ========================================
+ const clearSelectionBtn = document.getElementById('clear-selection-btn');
+ if (clearSelectionBtn) {
+ clearSelectionBtn.addEventListener('click', () => {
+ if (assignmentData.history.length === 0) {
+ alert('No assignments to undo');
+ return;
+ }
+
+ const lastAssignment = assignmentData.history.pop();
+ const { targetName, indices } = lastAssignment;
+
+ indices.forEach(idx => {
+ assignmentData.splatBoneIndices[idx] = -1;
+
+ filteredGs.colors[idx * 4 + 0] = 128;
+ filteredGs.colors[idx * 4 + 1] = 128;
+ filteredGs.colors[idx * 4 + 2] = 128;
+ });
+
+ if (assignmentData.boneAssignments[targetName]) {
+ assignmentData.boneAssignments[targetName] =
+ assignmentData.boneAssignments[targetName].filter(idx => !indices.includes(idx));
+ }
+
+ filteredGs.splatMesh.updateDataTexturesFromBaseData(0, filteredGs.splatCount - 1);
+ //renderer.render(scene, camera);
+
+ updateStats();
+
+ console.log(`[setupBoneAssignment] Undone ${indices.length} splats from ${targetName}`);
+ });
+ }
+
+ // ========================================
+ // Reset All Assignments
+ // ========================================
+ const undoAllBtn = document.getElementById('undo-all-btn');
+ if (undoAllBtn) {
+ undoAllBtn.addEventListener('click', () => {
+ if (!confirm('Reset all assignments?')) return;
+
+ assignmentData.splatBoneIndices.fill(-1);
+ assignmentData.boneAssignments = {};
+ assignmentData.history = [];
+
+ for (let i = 0; i < filteredGs.splatCount; i++) {
+ filteredGs.colors[i * 4 + 0] = 128;
+ filteredGs.colors[i * 4 + 1] = 128;
+ filteredGs.colors[i * 4 + 2] = 128;
+ }
+
+ filteredGs.splatMesh.updateDataTexturesFromBaseData(0, filteredGs.splatCount - 1);
+ //renderer.render(scene, camera);
+
+ updateStats();
+
+ console.log('[setupBoneAssignment] Reset all assignments');
+ });
+ }
+
+
+ ///////////////////////////////////////////////////////////////////////////////////////////////1356////
+
+// ========================================
+// finalizeBtn 正しい構造(完全版)
+// 1356行目から1818行目までを、この全体で置き換え
+// ========================================
+
+
+/////////////// 12/13 16:40 修正必要箇所かも
+
+const finalizeBtn = document.getElementById('finalize-btn');
+if (finalizeBtn) {
+ finalizeBtn.addEventListener('click', async () => {
+ const assignedCount = assignmentData.splatBoneIndices.filter(idx => idx >= 0).length;
+
+ if (assignedCount === 0) {
+ alert('Please assign at least some splats before finalizing!');
+ return;
+ }
+
+ if (assignedCount < filteredGs.splatCount * 0.3) {
+ if (!confirm(`Only ${assignedCount}/${filteredGs.splatCount} splats assigned. Continue?`)) {
+ return;
+ }
+ }
+
+ console.log('[setupBoneAssignment] Finalizing...');
+ ui.setStatus('Validating bone assignments...');
+
+ try {
+ // ========================================
+ // STEP 1: Create PMC FIRST
+ // ========================================
+ console.log('[setupBoneAssignment] Creating PMC...');
+ const { pmc, capsuleBoneIndex } = GVRMUtils.getPointsMeshCapsules(character);
+ GVRMUtils.addPMC(scene, pmc);
+ GVRMUtils.visualizePMC(pmc, false);
+ //renderer.render(scene, camera);
+
+ gvrm.pmc = pmc;
+ // gvrm.modelScale = 1.0;
+ gvrm.boneOperations = boneOperations;
+ gvrm.customType = "1";
+
+ console.log('[setupBoneAssignment] PMC created');
+ console.log('[setupBoneAssignment] capsuleBoneIndex:', capsuleBoneIndex);
+ console.log('[setupBoneAssignment] Number of capsules:', Object.keys(capsuleBoneIndex).length);
+ console.log('[setupBoneAssignment] ✓ Set gvrm.customType:', gvrm.customType); // ← このログを追加
+
+///////////////
+
+
+ // ========================================
+ // STEP 2: Required Bones Check
+ // ========================================
+ const requiredBones = [
+ 'hips', 'spine', 'chest', 'neck', 'head',
+ 'leftShoulder', 'leftUpperArm', 'leftLowerArm', 'leftHand',
+ 'rightShoulder', 'rightUpperArm', 'rightLowerArm', 'rightHand',
+ 'leftUpperLeg', 'leftLowerLeg', 'leftFoot',
+ 'rightUpperLeg', 'rightLowerLeg', 'rightFoot'
+ ];
+
+ const assignedBoneIndices = new Set(assignmentData.splatBoneIndices.filter(idx => idx >= 0));
+ const missingBones = [];
+
+ requiredBones.forEach(boneName => {
+ const boneIndex = boneNameToIndex[boneName];
+ if (boneIndex !== undefined && !assignedBoneIndices.has(boneIndex)) {
+ missingBones.push(boneName);
+ }
+ });
+
+ // Auto-complete missing bones
+ if (missingBones.length > 0) {
+ console.warn('[setupBoneAssignment] Missing bone assignments:', missingBones);
+
+ const proceed = confirm(
+ `Warning: The following bones have no splats assigned:\n\n${missingBones.join(', ')}\n\n` +
+ `This may cause rendering issues. The system will assign a few splats to these bones automatically.\n\n` +
+ `Continue?`
+ );
+
+ if (!proceed) {
+ ui.setStatus('Cancelled by user');
+ return;
+ }
+
+ ui.setStatus('Auto-assigning missing bones...');
+
+ for (const boneName of missingBones) {
+ const boneIndex = boneNameToIndex[boneName];
+ if (boneIndex === undefined) continue;
+
+ const bone = humanBones[boneName];
+ if (!bone || !bone.node) continue;
+
+ const boneWorldPos = new THREE.Vector3();
+ bone.node.getWorldPosition(boneWorldPos);
+
+ let assignedToThisBone = 0;
+ const maxToAssign = 5;
+
+ for (let i = 0; i < filteredGs.splatCount && assignedToThisBone < maxToAssign; i++) {
+ if (assignmentData.splatBoneIndices[i] >= 0) continue;
+
+ const splatPos = new THREE.Vector3(
+ filteredGs.centers0[i * 3 + 0],
+ filteredGs.centers0[i * 3 + 1],
+ filteredGs.centers0[i * 3 + 2]
+ );
+ splatPos.applyMatrix4(filteredGs.viewer.splatMesh.scenes[0].matrixWorld);
+
+ const distance = splatPos.distanceTo(boneWorldPos);
+
+ if (distance < 1.0) {
+ assignmentData.splatBoneIndices[i] = boneIndex;
+ assignedToThisBone++;
+
+ const color = GVRMUtils.colors[boneIndex % GVRMUtils.colors.length];
+ filteredGs.colors[i * 4 + 0] = color[0];
+ filteredGs.colors[i * 4 + 1] = color[1];
+ filteredGs.colors[i * 4 + 2] = color[2];
+ }
+ }
+
+ if (assignedToThisBone > 0) {
+ console.log(`[setupBoneAssignment] Auto-assigned ${assignedToThisBone} splats to ${boneName}`);
+ } else {
+ console.warn(`[setupBoneAssignment] Could not auto-assign any splats to ${boneName}`);
+ }
+ }
+
+ filteredGs.splatMesh.updateDataTexturesFromBaseData(0, filteredGs.splatCount - 1);
+ //renderer.render(scene, camera);
+ updateStats();
+ }
+
+ // ========================================
+ // STEP 3: Set Bone Assignments
+ // ========================================
+ ui.setStatus('Setting bone assignments...');
+ filteredGs.splatBoneIndices = assignmentData.splatBoneIndices;
+
+ console.log('[setupBoneAssignment] Bone assignments set:', filteredGs.splatBoneIndices.length);
+
+///////////////////////////////////////////////////////////////////////////////////////////////////
+
+
+ // ========================================
+ // STEP 4: Map Vertices to Bones (修正版)
+ // preprocess_manual.js の STEP 4 部分を置き換え
+ // ========================================
+ ui.setStatus('Mapping vertices to bones...');
+ const skinnedMesh = character.currentVrm.scene.children[character.skinnedMeshIndex];
+ const position = skinnedMesh.geometry.getAttribute('position');
+
+ const boneVertexIndices = {};
+
+ // ⭐ 修正: capsuleBoneIndexだけでなく、実際に割り当てられた全ボーンを含める
+ const allUsedBoneIndices = new Set(Object.values(capsuleBoneIndex));
+
+ // 割り当てられたスプラットのボーンインデックスも追加
+ assignmentData.splatBoneIndices.forEach(boneIdx => {
+ if (boneIdx >= 0) {
+ allUsedBoneIndices.add(boneIdx);
+ }
+ });
+
+ console.log('[setupBoneAssignment] Unique bone indices used:', Array.from(allUsedBoneIndices).sort((a,b) => a-b));
+ console.log('[setupBoneAssignment] Bone names:', Array.from(allUsedBoneIndices).map(idx => boneNames[idx]));
+
+ // 全使用ボーンに対して頂点リストを初期化
+ allUsedBoneIndices.forEach(boneIdx => {
+ boneVertexIndices[boneIdx] = [];
+ });
+
+ console.log('[setupBoneAssignment] Initialized boneVertexIndices for',
+ Object.keys(boneVertexIndices).length, 'bones');
+ console.log('[setupBoneAssignment] Mapping', position.count, 'vertices to bones...');
+
+////////////
+ // ⭐ 修正: humanBonesを取得し直す(スコープの問題を解決)
+ const humanBones = character.currentVrm.humanoid.humanBones;
+////////////
+
+ // 各頂点を最も近いボーンに割り当て
+ for (let vi = 0; vi < position.count; vi++) {
+ const vertex = new THREE.Vector3().fromBufferAttribute(position, vi);
+ const skinnedVertex = skinnedMesh.applyBoneTransform(vi, vertex);
+ skinnedVertex.applyMatrix4(character.currentVrm.scene.matrixWorld);
+
+ let minDistance = Infinity;
+ let closestBoneIndex = 0;
+
+ // 使用されている全ボーンから最も近いボーンを探す ここは、L.1536
+ for (const boneIndex of allUsedBoneIndices) {
+ const boneName = boneNames[boneIndex];
+ const bone = humanBones[boneName];
+ if (bone && bone.node) {
+ const boneWorldPos = new THREE.Vector3();
+ bone.node.getWorldPosition(boneWorldPos);
+
+ const distance = skinnedVertex.distanceTo(boneWorldPos);
+ if (distance < minDistance) {
+ minDistance = distance;
+ closestBoneIndex = boneIndex;
+ }
+ }
+ }
+
+ boneVertexIndices[closestBoneIndex].push(vi);
+
+ if (vi % 500 === 0) {
+ const progress = ((vi / position.count) * 100).toFixed(1);
+ ui.setStatus(`Mapping vertices: ${progress}%`);
+ await new Promise(resolve => setTimeout(resolve, 0));
+ }
+ }
+
+ console.log('[setupBoneAssignment] Vertex mapping complete');
+
+ // ⭐ デバッグ: 各ボーンの頂点数を出力
+ console.log('[setupBoneAssignment] Vertices per bone:');
+ for (const [boneIdx, vertices] of Object.entries(boneVertexIndices)) {
+ const boneName = boneNames[parseInt(boneIdx)];
+ console.log(` ${boneName} (${boneIdx}): ${vertices.length} vertices`);
+ }
+
+
+
+///////////////////////////////////////////////////////////////////////////////////////////////////
+
+ // ========================================
+ // STEP 5: Assign Splats to Vertices (修正版)
+ // ========================================
+ ui.setStatus('Assigning splats to vertices...');
+ filteredGs.splatVertexIndices = [];
+ filteredGs.splatRelativePoses = [];
+
+ console.log('[setupBoneAssignment] Assigning', filteredGs.splatCount, 'splats to vertices...');
+
+ let remappedCount = 0;
+ let fallbackCount = 0;
+
+ // ⭐ グローバルフォールバック: 最も頂点数が多いボーンを特定
+ let fallbackBoneIndex = 0;
+ let maxVertexCount = 0;
+ for (const [boneIdx, vertices] of Object.entries(boneVertexIndices)) {
+ if (vertices.length > maxVertexCount) {
+ maxVertexCount = vertices.length;
+ fallbackBoneIndex = parseInt(boneIdx);
+ }
+ }
+
+ console.log(`[setupBoneAssignment] Fallback bone: ${boneNames[fallbackBoneIndex]} (${fallbackBoneIndex}) with ${maxVertexCount} vertices`);
+
+ const fallbackVertices = boneVertexIndices[fallbackBoneIndex] || [];
+
+ // 最終フォールバック用の頂点
+ let ultimateFallbackVertex = 0;
+ if (fallbackVertices.length > 0) {
+ ultimateFallbackVertex = fallbackVertices[Math.floor(fallbackVertices.length / 2)];
+ }
+
+ for (let i = 0; i < filteredGs.splatCount; i++) {
+ const targetPoint = new THREE.Vector3(
+ filteredGs.centers0[i * 3 + 0],
+ filteredGs.centers0[i * 3 + 1],
+ filteredGs.centers0[i * 3 + 2]
+ );
+ targetPoint.applyMatrix4(filteredGs.viewer.splatMesh.scenes[0].matrixWorld);
+
+ let assignedBoneIndex = filteredGs.splatBoneIndices[i];
+
+ // 未割り当てまたは無効なボーンの場合、フォールバックボーンに割り当て
+ if (assignedBoneIndex < 0 || !allUsedBoneIndices.has(assignedBoneIndex)) {
+ if (assignedBoneIndex >= 0) {
+ remappedCount++;
+ }
+ assignedBoneIndex = fallbackBoneIndex;
+ filteredGs.splatBoneIndices[i] = fallbackBoneIndex;
+ }
+
+ const vertexIndices = boneVertexIndices[assignedBoneIndex] || [];
+
+ // ⭐ 修正: vertexIndicesが空の場合の処理
+ if (vertexIndices.length === 0) {
+ if (fallbackCount === 0) {
+ console.warn(`[setupBoneAssignment] Bone ${assignedBoneIndex} (${boneNames[assignedBoneIndex]}) has no vertices, using fallback bone`);
+ }
+
+ // フォー���バックボーンの頂点群から最も近い頂点を探す
+ if (fallbackVertices.length > 0) {
+ let minDistance = Infinity;
+ let bestVertexIndex = fallbackVertices[0];
+
+ // 高速化: サンプリング
+ const step = Math.max(1, Math.floor(fallbackVertices.length / 100));
+
+ for (let vi = 0; vi < fallbackVertices.length; vi += step) {
+ const vertexIndex = fallbackVertices[vi];
+ const vertex = new THREE.Vector3().fromBufferAttribute(position, vertexIndex);
+ const skinnedVertex = skinnedMesh.applyBoneTransform(vertexIndex, vertex);
+ skinnedVertex.applyMatrix4(character.currentVrm.scene.matrixWorld);
+
+ const distance = skinnedVertex.distanceTo(targetPoint);
+
+ if (distance < minDistance) {
+ minDistance = distance;
+ bestVertexIndex = vertexIndex;
+ }
+ }
+
+ filteredGs.splatVertexIndices.push(bestVertexIndex);
+
+ // 相対位置を計算
+ const vertex = new THREE.Vector3().fromBufferAttribute(position, bestVertexIndex);
+ const transformedVertex = skinnedMesh.applyBoneTransform(bestVertexIndex, vertex);
+
+ let center0 = new THREE.Vector3(
+ filteredGs.centers0[i * 3 + 0],
+ filteredGs.centers0[i * 3 + 1],
+ filteredGs.centers0[i * 3 + 2]
+ );
+ center0.applyMatrix4(filteredGs.viewer.splatMesh.scenes[0].matrixWorld);
+ center0.applyMatrix4(new THREE.Matrix4().copy(character.currentVrm.scene.matrixWorld).invert());
+
+ const relativePos = new THREE.Vector3().subVectors(center0, transformedVertex);
+ filteredGs.splatRelativePoses.push(relativePos.x, relativePos.y, relativePos.z);
+
+ fallbackCount++;
+ } else {
+ // 最終フォールバック: ジオメトリの任意の頂点を使用
+ if (fallbackCount === 0) {
+ console.error('[setupBoneAssignment] No vertices available for any bone, using vertex', ultimateFallbackVertex);
+ }
+
+ filteredGs.splatVertexIndices.push(ultimateFallbackVertex);
+
+ const vertex = new THREE.Vector3().fromBufferAttribute(position, ultimateFallbackVertex);
+ const transformedVertex = skinnedMesh.applyBoneTransform(ultimateFallbackVertex, vertex);
+
+ let center0 = new THREE.Vector3(
+ filteredGs.centers0[i * 3 + 0],
+ filteredGs.centers0[i * 3 + 1],
+ filteredGs.centers0[i * 3 + 2]
+ );
+ center0.applyMatrix4(filteredGs.viewer.splatMesh.scenes[0].matrixWorld);
+ center0.applyMatrix4(new THREE.Matrix4().copy(character.currentVrm.scene.matrixWorld).invert());
+
+ const relativePos = new THREE.Vector3().subVectors(center0, transformedVertex);
+ filteredGs.splatRelativePoses.push(relativePos.x, relativePos.y, relativePos.z);
+
+ fallbackCount++;
+ }
+
+ if (i % 100 === 0) {
+ const progress = ((i / filteredGs.splatCount) * 100).toFixed(1);
+ ui.setStatus(`Assigning splats: ${progress}%`);
+ await new Promise(resolve => setTimeout(resolve, 0));
+ }
+
+ continue;
+ }
+
+ // ⭐ 通常処理: vertexIndicesが存在する場合
+ let minDistance = Infinity;
+ let bestVertexIndex = vertexIndices[0];
+
+ // 高速化: サンプリング
+ const step = Math.max(1, Math.floor(vertexIndices.length / 100));
+
+ for (let vi = 0; vi < vertexIndices.length; vi += step) {
+ const vertexIndex = vertexIndices[vi];
+ const vertex = new THREE.Vector3().fromBufferAttribute(position, vertexIndex);
+ const skinnedVertex = skinnedMesh.applyBoneTransform(vertexIndex, vertex);
+ skinnedVertex.applyMatrix4(character.currentVrm.scene.matrixWorld);
+
+ const distance = skinnedVertex.distanceTo(targetPoint);
+
+ if (distance < minDistance) {
+ minDistance = distance;
+ bestVertexIndex = vertexIndex;
+ }
+ }
+
+ filteredGs.splatVertexIndices.push(bestVertexIndex);
+
+ // 相対位置の計算
+ const vertex = new THREE.Vector3().fromBufferAttribute(position, bestVertexIndex);
+ const transformedVertex = skinnedMesh.applyBoneTransform(bestVertexIndex, vertex);
+
+ let center0 = new THREE.Vector3(
+ filteredGs.centers0[i * 3 + 0],
+ filteredGs.centers0[i * 3 + 1],
+ filteredGs.centers0[i * 3 + 2]
+ );
+ center0.applyMatrix4(filteredGs.viewer.splatMesh.scenes[0].matrixWorld);
+ center0.applyMatrix4(new THREE.Matrix4().copy(character.currentVrm.scene.matrixWorld).invert());
+
+ const relativePos = new THREE.Vector3().subVectors(center0, transformedVertex);
+ filteredGs.splatRelativePoses.push(relativePos.x, relativePos.y, relativePos.z);
+
+ if (i % 100 === 0) {
+ const progress = ((i / filteredGs.splatCount) * 100).toFixed(1);
+ ui.setStatus(`Assigning splats: ${progress}%`);
+ await new Promise(resolve => setTimeout(resolve, 0));
+ }
+ }
+
+ console.log('[setupBoneAssignment] Splat assignment complete');
+ console.log(' - splatVertexIndices:', filteredGs.splatVertexIndices.length);
+ console.log(' - splatRelativePoses:', filteredGs.splatRelativePoses.length);
+ console.log(' - Remapped splats:', remappedCount);
+ console.log(' - Fallback assignments:', fallbackCount);
+
+ // ⭐ データ検証
+ const uniqueVertices = new Set(filteredGs.splatVertexIndices);
+ console.log(' - Unique vertices used:', uniqueVertices.size);
+
+ const zeroRelativePoses = filteredGs.splatRelativePoses.filter(v => v === 0).length;
+ const zeroPercent = (zeroRelativePoses / filteredGs.splatRelativePoses.length * 100).toFixed(1);
+ console.log(` - Zero values in relativePoses: ${zeroRelativePoses} (${zeroPercent}%)`);
+
+ // サンプルデータの出力
+ console.log(' - Sample splatVertexIndices:', filteredGs.splatVertexIndices.slice(0, 10));
+ console.log(' - Sample splatRelativePoses:', filteredGs.splatRelativePoses.slice(0, 30));
+
+ if (zeroPercent > 30) {
+ console.warn('[setupBoneAssignment] WARNING: High percentage of zero relative poses detected!');
+ }
+
+ if (uniqueVertices.size < 10) {
+ console.warn('[setupBoneAssignment] WARNING: Very few unique vertices used! This may cause issues.');
+ }
+
+
+
+ // ========================================
+ // STEP 6: Update PMC
+ // ========================================
+ console.log('[setupBoneAssignment] Updating PMC...');
+ gvrm.updatePMC();
+ console.log('[setupBoneAssignment] PMC updated');
+
+ ////////////////////////20251210start2///////////////////////////////////////////////////////////////////////////
+
+ // ========================================
+ // DIAGNOSTIC CODE - Insert BEFORE Step 6.5
+ // ========================================
+
+ console.log('========== GVRM STATE DIAGNOSTIC ==========');
+ console.log('1. GVRM Object:', gvrm);
+ console.log('2. GVRM properties:');
+ console.log(' - modelScale:', gvrm.modelScale);
+ console.log(' - boneOperations:', gvrm.boneOperations);
+ console.log(' - pmc:', gvrm.pmc);
+ console.log(' - gs:', gvrm.gs);
+
+ console.log('3. filteredGs Object:', filteredGs);
+ console.log('4. filteredGs properties:');
+ console.log(' - splatCount:', filteredGs.splatCount);
+ console.log(' - splatVertexIndices length:', filteredGs.splatVertexIndices?.length);
+ console.log(' - splatBoneIndices length:', filteredGs.splatBoneIndices?.length);
+ console.log(' - splatRelativePoses length:', filteredGs.splatRelativePoses?.length);
+ console.log(' - gsQuaternion:', filteredGs.gsQuaternion);
+ console.log(' - gsPosition:', filteredGs.gsPosition);
+ console.log(' - viewer:', filteredGs.viewer);
+ console.log(' - viewer.splatMesh:', filteredGs.viewer?.splatMesh);
+ console.log(' - scenes:', filteredGs.viewer?.splatMesh?.scenes);
+
+ console.log('5. Character Object:', character);
+ console.log('6. Character VRM:');
+ console.log(' - currentVrm:', character.currentVrm);
+ console.log(' - humanoid:', character.currentVrm?.humanoid);
+ console.log(' - humanBones:', character.currentVrm?.humanoid?.humanBones);
+
+ // const humanBones = character.currentVrm?.humanoid?.humanBones;
+ if (humanBones) {
+ console.log('7. Available bones:', Object.keys(humanBones));
+ console.log('8. Hips bone:', humanBones.hips);
+ console.log('9. LeftUpperLeg bone:', humanBones.leftUpperLeg);
+ }
+
+ console.log('========== END DIAGNOSTIC ==========');
+
+
+////////////////////////////////////////////////////////
+
+ // ========================================
+ // STEP 6.5: Calculate modelScale, gsQuaternion, gsPosition
+ // CRITICAL: Insert AFTER "gvrm.updatePMC()" and BEFORE "gvrm.save()"
+ // ========================================
+
+ console.log('[setupBoneAssignment] ===== CALCULATING GVRM TRANSFORMS =====');
+ ui.setStatus('Calculating transforms...');
+
+ try {
+ // ========================================
+ // 1. Calculate gsQuaternion and gsPosition
+ // ========================================
+
+
+ console.log('[setupBoneAssignment] Step 1: Calculate GS transform');
+
+ // Get the GS scene transform
+ const gsScene = filteredGs.viewer.splatMesh.scenes[0];
+ gsScene.updateMatrixWorld(true);
+
+ // Clone the world matrix
+ const gsWorldMatrix = gsScene.matrixWorld.clone();
+
+ // Extract position
+ const gsWorldPosition = new THREE.Vector3();
+ gsWorldPosition.setFromMatrixPosition(gsWorldMatrix);
+
+ console.log('[setupBoneAssignment] GS World Position:', {
+ x: gsWorldPosition.x,
+ y: gsWorldPosition.y,
+ z: gsWorldPosition.z
+ });
+
+ // Extract scale
+ const gsWorldScale = new THREE.Vector3();
+ gsWorldScale.setFromMatrixScale(gsWorldMatrix);
+
+ console.log('[setupBoneAssignment] GS World Scale:', {
+ x: gsWorldScale.x,
+ y: gsWorldScale.y,
+ z: gsWorldScale.z
+ });
+
+ // ⭐ 重要: スケールを除去したmatrixからrotationを取得
+ const rotationMatrix = gsWorldMatrix.clone();
+ rotationMatrix.scale(new THREE.Vector3(
+ 1 / gsWorldScale.x,
+ 1 / gsWorldScale.y,
+ 1 / gsWorldScale.z
+ ));
+
+ // Extract rotation as quaternion
+ const gsWorldQuaternion = new THREE.Quaternion();
+ gsWorldQuaternion.setFromRotationMatrix(rotationMatrix);
+
+ console.log('[setupBoneAssignment] GS World Quaternion:', {
+ x: gsWorldQuaternion.x,
+ y: gsWorldQuaternion.y,
+ z: gsWorldQuaternion.z,
+ w: gsWorldQuaternion.w
+ });
+
+ // ⭐ 修正: Identityチェックを追加
+ const isIdentity = (
+ Math.abs(gsWorldQuaternion.x) < 0.0001 &&
+ Math.abs(gsWorldQuaternion.y) < 0.0001 &&
+ Math.abs(gsWorldQuaternion.z) < 0.0001 &&
+ Math.abs(gsWorldQuaternion.w - 1.0) < 0.0001
+ );
+
+ if (isIdentity) {
+ console.log('[setupBoneAssignment] ✓ GS has identity rotation (no rotation applied)');
+ } else {
+ console.log('[setupBoneAssignment] ✓ GS has non-identity rotation');
+}
+
+
+////////////////////////////////
+
+ // Assign to filteredGs
+ filteredGs.gsQuaternion = [
+ gsWorldQuaternion.x,
+ gsWorldQuaternion.y,
+ gsWorldQuaternion.z,
+ gsWorldQuaternion.w
+ ];
+
+ filteredGs.gsPosition = [
+ gsWorldPosition.x,
+ gsWorldPosition.y,
+ gsWorldPosition.z
+ ];
+
+
+ /////////////////////////////////////20251210
+
+ // ========================================
+ // 2. Calculate modelScale
+ // ========================================
+
+ // ========================================
+ // 修正4: modelScaleの計算を修正
+ // Line 1929付近
+ // ========================================
+
+ console.log('[setupBoneAssignment] Step 2: Calculate modelScale');
+
+ const humanBones = character.currentVrm.humanoid.humanBones;
+
+ if (!humanBones.hips || !humanBones.hips.node) {
+ throw new Error('hips bone not found');
+ }
+
+ if (!humanBones.leftUpperLeg || !humanBones.leftUpperLeg.node) {
+ throw new Error('leftUpperLeg bone not found');
+ }
+
+ const hipsNode = humanBones.hips.node;
+ const leftUpperLegNode = humanBones.leftUpperLeg.node;
+
+ // ⭐ 修正: matrixWorldを強制的に更新
+ character.currentVrm.scene.updateMatrixWorld(true);
+
+ // Get world positions
+ const hipsWorldPos = new THREE.Vector3();
+ hipsNode.getWorldPosition(hipsWorldPos);
+
+ const leftUpperLegWorldPos = new THREE.Vector3();
+ leftUpperLegNode.getWorldPosition(leftUpperLegWorldPos);
+
+ console.log('[setupBoneAssignment] Hips world position:', {
+ x: hipsWorldPos.x.toFixed(4),
+ y: hipsWorldPos.y.toFixed(4),
+ z: hipsWorldPos.z.toFixed(4)
+ });
+
+ console.log('[setupBoneAssignment] Left upper leg world position:', {
+ x: leftUpperLegWorldPos.x.toFixed(4),
+ y: leftUpperLegWorldPos.y.toFixed(4),
+ z: leftUpperLegWorldPos.z.toFixed(4)
+ });
+
+
+/////////////////
+
+
+ const legLength = hipsWorldPos.distanceTo(leftUpperLegWorldPos);
+ console.log('[setupBoneAssignment] Raw leg length:', legLength);
+
+ // ⭐ 判定: legLengthが0.2以下の場合、VRMスケールが正しいと判断
+ if (legLength < 0.2) {
+ console.warn('[setupBoneAssignment] ⚠️ VRM has very small leg length:', legLength);
+ console.warn('[setupBoneAssignment] Using modelScale = 1.0 (no scaling needed)');
+ gvrm.modelScale = 1.0;
+ } else {
+ // 通常の計算
+ const standardLegLength = 0.45;
+ const calculatedModelScale = standardLegLength / legLength;
+
+ console.log('[setupBoneAssignment] Calculated modelScale:', calculatedModelScale);
+
+ // 適度なクランプ
+ const clampedModelScale = Math.max(0.1, Math.min(10.0, calculatedModelScale));
+
+ if (clampedModelScale !== calculatedModelScale) {
+ console.warn('[setupBoneAssignment] ⚠️ Clamped modelScale from', calculatedModelScale, 'to', clampedModelScale);
+ }
+
+ gvrm.modelScale = clampedModelScale;
+ }
+
+ console.log('[setupBoneAssignment] ✓ Final gvrm.modelScale:', gvrm.modelScale);
+
+///////////////////////
+
+
+ // ========================================
+ // 3. Update boneOperations (optional but recommended)
+ // ========================================
+
+ console.log('[setupBoneAssignment] Step 3: Update boneOperations');
+
+ // The current boneOperations already has the correct structure
+ // We could update rotations based on the actual pose, but it's optional
+
+ // For now, just log the current boneOperations
+ console.log('[setupBoneAssignment] Current boneOperations:', gvrm.boneOperations);
+
+ // ========================================
+ // Verification
+ // ========================================
+
+ console.log('[setupBoneAssignment] ===== TRANSFORM CALCULATION COMPLETE =====');
+ console.log('[setupBoneAssignment] Final values:');
+ console.log(' modelScale:', gvrm.modelScale);
+ console.log(' gsQuaternion:', filteredGs.gsQuaternion);
+ console.log(' gsPosition:', filteredGs.gsPosition);
+ console.log(' boneOperations:', gvrm.boneOperations.length, 'operations');
+
+ // Sanity checks
+ if (gvrm.modelScale < 0.5 || gvrm.modelScale > 2.0) {
+ console.warn('[setupBoneAssignment] ⚠️ WARNING: modelScale is outside normal range (0.5-2.0)');
+ console.warn('[setupBoneAssignment] This may cause rendering issues');
+ }
+
+ if (filteredGs.gsQuaternion[0] === 0 &&
+ filteredGs.gsQuaternion[1] === 0 &&
+ filteredGs.gsQuaternion[2] === 1 &&
+ filteredGs.gsQuaternion[3] === 0) {
+ console.warn('[setupBoneAssignment] ⚠️ WARNING: gsQuaternion is still default value!');
+ }
+
+ if (filteredGs.gsPosition[0] === 0 &&
+ filteredGs.gsPosition[1] === 0 &&
+ filteredGs.gsPosition[2] === 0) {
+ console.warn('[setupBoneAssignment] ⚠️ WARNING: gsPosition is still (0,0,0)!');
+ console.warn('[setupBoneAssignment] This means the GS has no offset from origin');
+ }
+
+ ui.setStatus('Transform calculation complete');
+
+ } catch (error) {
+ console.error('[setupBoneAssignment] ERROR in transform calculation:', error);
+ console.error('[setupBoneAssignment] Error stack:', error.stack);
+ alert('Error calculating transforms: ' + error.message);
+ throw error;
+ }
+
+
+////////////////////////////////////////////////////////////////////// add 20251211 13:54
+
+
+ // Key changes in STEP 6.6 section (around line 1598):
+
+ // ========================================
+ // STEP 6.6: Save matrixWorld0 for all bones
+ // CRITICAL: Insert AFTER transform calculation and BEFORE gvrm.save()
+ // ========================================
+
+ console.log('[setupBoneAssignment] ===== SAVING MATRIXWORLD0 =====');
+ ui.setStatus('Saving bone matrices...');
+
+ try {
+ const allBoneNames = Object.keys(humanBones); // ← humanBonesは既に定義済み
+ console.log('[setupBoneAssignment] Saving matrixWorld0 for', allBoneNames.length, 'bones');
+
+ // Initialize matrixWorld0 storage if it doesn't exist
+ if (!gvrm.matrixWorld0) {
+ gvrm.matrixWorld0 = {};
+ }
+
+ // Save matrixWorld for each bone
+ let savedCount = 0;
+ for (const boneName of allBoneNames) {
+ const bone = humanBones[boneName];
+
+ // ⭐ 修正: より詳細なチェック
+ if (bone && bone.node && bone.node.matrixWorld) {
+ // Clone the matrix to preserve the initial state
+ gvrm.matrixWorld0[boneName] = bone.node.matrixWorld.clone();
+ savedCount++;
+
+ // Log first few bones for verification
+ if (savedCount <= 3) {
+ console.log(`[setupBoneAssignment] Saved matrixWorld0 for ${boneName}:`,
+ bone.node.matrixWorld.elements.slice(0, 4));
+ }
+ } else {
+ console.warn(`[setupBoneAssignment] ⚠️ Bone ${boneName} has no valid node/matrixWorld:`, {
+ bone: !!bone,
+ node: !!bone?.node,
+ matrixWorld: !!bone?.node?.matrixWorld
+ });
+ }
+ }
+
+ console.log(`[setupBoneAssignment] ✓ Saved matrixWorld0 for ${savedCount} bones`);
+ console.log('[setupBoneAssignment] Sample matrixWorld0 keys:',
+ Object.keys(gvrm.matrixWorld0).slice(0, 5));
+
+ // Verify critical bones
+ const criticalBones = ['hips', 'leftUpperArm', 'rightUpperArm'];
+ for (const boneName of criticalBones) {
+ if (!gvrm.matrixWorld0[boneName]) {
+ console.error(`[setupBoneAssignment] ❌ CRITICAL: ${boneName} matrixWorld0 not saved!`);
+ } else {
+ console.log(`[setupBoneAssignment] ✓ ${boneName} matrixWorld0 verified`);
+ }
+ }
+
+ ui.setStatus('Bone matrices saved');
+
+ } catch (error) {
+ console.error('[setupBoneAssignment] ERROR saving matrixWorld0:', error);
+ console.error('[setupBoneAssignment] Error stack:', error.stack);
+ alert('Error saving bone matrices: ' + error.message);
+ throw error;
+ }
+
+
+////////////////////////////////////////////////////////////////////////////////
+
+ // ========================================
+ // STEP 6.7: Transfer matrixWorld0 to filteredGs
+ // ========================================
+
+ console.log('[setupBoneAssignment] ===== TRANSFERRING MATRIXWORLD0 TO FILTEREDGS =====');
+
+ // ⭐ 追加: gvrm.matrixWorld0が存在するか確認
+ if (!gvrm.matrixWorld0 || Object.keys(gvrm.matrixWorld0).length === 0) {
+ console.error('[setupBoneAssignment] ❌ CRITICAL: gvrm.matrixWorld0 is empty or undefined!');
+ throw new Error('matrixWorld0 was not properly saved');
+ }
+
+ // Convert matrixWorld0 from Matrix4 objects to serializable arrays
+ const matrixWorld0Serializable = {};
+
+ for (const [boneName, matrix] of Object.entries(gvrm.matrixWorld0)) {
+ // ⭐ 修正: matrixがnullでないことを確認
+ if (matrix && matrix.elements) {
+ // Convert THREE.Matrix4 to array
+ matrixWorld0Serializable[boneName] = matrix.elements.slice(); // Copy array
+ } else {
+ console.warn(`[setupBoneAssignment] ⚠️ Invalid matrix for ${boneName}:`, matrix);
+ }
+ }
+
+ // Assign to filteredGs so it gets saved
+ filteredGs.matrixWorld0 = matrixWorld0Serializable;
+
+ console.log('[setupBoneAssignment] ✓ Transferred matrixWorld0 to filteredGs');
+ console.log('[setupBoneAssignment] ✓ matrixWorld0 bone count:',
+ Object.keys(filteredGs.matrixWorld0).length);
+
+ // ⭐ 修正: hipsが存在するか確認してからアクセス
+ if (filteredGs.matrixWorld0['hips']) {
+ console.log('[setupBoneAssignment] Sample matrixWorld0 data (hips):',
+ filteredGs.matrixWorld0['hips'].slice(0, 4));
+ } else {
+ console.warn('[setupBoneAssignment] ⚠️ hips matrixWorld0 not found in filteredGs');
+ }
+
+ /////////////////////////20251210end2//////////////////////////////////////////////////////////////////////////
+
+ // ========================================
+ // STEP 7: Save GVRM File
+ // ========================================
+ ui.setStatus('Saving GVRM file...');
+ console.log('[setupBoneAssignment] Saving GVRM...');
+
+ // 保存直前に再確認
+ console.log('[setupBoneAssignment] ===== FINAL CHECK BEFORE SAVE =====');
+ console.log(' gvrm.customType:', gvrm.customType);
+ console.log(' gvrm.modelScale:', gvrm.modelScale);
+
+ // customTypeが失われていたら再設定
+ if (!gvrm.customType) {
+ console.warn('[setupBoneAssignment] ⚠️ customType was lost, resetting to "1"');
+ gvrm.customType = "1";
+ }
+
+ // modelScaleが異常なら1.0に修正
+ if (gvrm.modelScale > 2.0) {
+ console.warn('[setupBoneAssignment] ⚠️ modelScale is too large:', gvrm.modelScale);
+ console.warn('[setupBoneAssignment] Forcing modelScale = 1.0');
+ gvrm.modelScale = 1.0;
+ }
+
+ await gvrm.save(vrmPath, filteredPlyUrl, boneOperations, gvrm.modelScale, fileName, savePly);
+
+ console.log('[setupBoneAssignment] GVRM saved successfully');
+
+ ///////////////
+
+// ========================================
+// 修正6: データ検証の修正
+// Line 2199付近
+// ========================================
+
+ console.log('[setupBoneAssignment] ===== DATA VALIDATION =====');
+
+ // 1. 点群数の確認
+ console.log('1. Splat counts:');
+ console.log(' - Original PLY:', originalPlyData.vertices.length); // ⭐ originalPlyData使用
+ console.log(' - After box filter:', plyData.vertices.length); // ⭐ filteredPlyData使用
+ console.log(' - In filteredGs:', filteredGs.splatCount);
+
+ // 2. ボーン割り当ての確認
+ const assignedBones = new Set(filteredGs.splatBoneIndices.filter(idx => idx >= 0));
+ console.log('2. Bone assignments:');
+ console.log(' - Unique bones used:', assignedBones.size);
+ console.log(' - Assigned splats:', filteredGs.splatBoneIndices.filter(idx => idx >= 0).length);
+ console.log(' - Unassigned splats:', filteredGs.splatBoneIndices.filter(idx => idx < 0).length);
+
+ // 3. 頂点インデックスの確認
+ //const uniqueVertices = new Set(filteredGs.splatVertexIndices);
+ //const skinnedMesh = character.currentVrm.scene.children[character.skinnedMeshIndex];
+ //const position = skinnedMesh.geometry.getAttribute('position');
+
+ console.log('3. Vertex assignments:');
+ console.log(' - Total vertices in mesh:', position.count);
+ console.log(' - Unique vertices used:', uniqueVertices.size);
+ console.log(' - Average splats per vertex:', (filteredGs.splatCount / uniqueVertices.size).toFixed(2));
+
+ // 4. 相対位置の確認
+ const nonZeroRelPoses = filteredGs.splatRelativePoses.filter(v => Math.abs(v) > 0.0001).length;
+ const totalRelPoseValues = filteredGs.splatRelativePoses.length;
+ console.log('4. Relative poses:');
+ console.log(' - Total values:', totalRelPoseValues);
+ console.log(' - Non-zero values:', nonZeroRelPoses, `(${(nonZeroRelPoses/totalRelPoseValues*100).toFixed(1)}%)`);
+
+ // 5. Transform values
+ console.log('5. Transform values:');
+ console.log(' - modelScale:', gvrm.modelScale);
+ console.log(' - gsQuaternion:', filteredGs.gsQuaternion);
+ console.log(' - gsPosition:', filteredGs.gsPosition);
+
+ console.log('[setupBoneAssignment] ===== END VALIDATION =====');
+
+ ////////////////
+
+
+
+
+
+ // ========================================
+ // STEP 8: Reload GVRM
+ // ========================================
+ ui.setStatus('Reloading GVRM...');
+ const newGvrmUrl = gvrm.url;
+
+ if (gvrm.gs) {
+ await gvrm.gs.viewer.dispose();
+ }
+
+ await new Promise(resolve => setTimeout(resolve, 100));
+
+ await gvrm.load(newGvrmUrl, scene, camera, renderer, fileName);
+
+ console.log('[setupBoneAssignment] GVRM reloaded successfully');
+ ui.setStatus('Complete! ✓');
+
+ // ========================================
+ // Cleanup
+ // ========================================
+ setTimeout(() => {
+ renderer.domElement.removeEventListener('mousedown', onMouseDown);
+ renderer.domElement.removeEventListener('mousemove', onMouseMove);
+ renderer.domElement.removeEventListener('mouseup', onMouseUp);
+ renderer.domElement.removeEventListener('click', onCanvasClick);
+
+ ui.cleanup();
+ resolve2();
+ }, 1500);
+
+ } catch (error) {
+ console.error('[setupBoneAssignment] Finalize error:', error);
+ console.error('[setupBoneAssignment] Error stack:', error.stack);
+ alert('Error during finalization: ' + error.message);
+ ui.setStatus('Error: ' + error.message);
+ }
+ }); // finalize-btn click listener の終了
+} // if (finalizeBtn) の終了
+
+// ========================================
+// setupBoneAssignment 関数全体の終了
+// ========================================
+ } catch (error) {
+ console.error('[setupBoneAssignment] Error:', error);
+ ui.setStatus('Error: ' + error.message);
+ }
+ }); // setupBoneAssignment の Promise の終了
+} // setupBoneAssignment 関数の終了
\ No newline at end of file