npy / preprocess_manual.js
stpete2's picture
Upload 2 files
c16d166 verified
raw
history blame
170 kB
// 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 = `
<h2 style="margin-top: 0;">Manual Preprocessing</h2>
<div id="manual-status">Loading PLY file...</div>
<!-- Camera Controls Info -->
<div style="
margin: 15px 0;
padding: 10px;
background: #1a1a2e;
border-radius: 5px;
border-left: 3px solid #4CAF50;
font-size: 12px;
">
<strong>🎮 Camera Controls:</strong><br>
• Left Mouse: Rotate view<br>
• Right Mouse: Pan<br>
• Scroll: Zoom in/out
</div>
<!-- Step 0: Adjust PLY and Box -->
<div id="position-adjustment-section" style="display: none; margin-top: 20px;">
<h3>Step 0: Adjust Position and Bounding Box</h3>
<p style="font-size: 12px; color: #aaa;">
First adjust the bounding box to frame your object, then fine-tune position if needed
</p>
<!-- Bounding Box Info Display -->
<div id="bbox-info" style="
margin: 10px 0;
padding: 10px;
background: #1a1a2e;
border-radius: 5px;
font-size: 11px;
color: #aaa;
">
<strong>Scene Bounds:</strong><br>
Size: <span id="scene-size">-</span><br>
Center: <span id="scene-center">-</span>
</div>
<!-- Bounding Box Controls -->
<h4 style="margin: 15px 0 10px 0; color: #4CAF50;">📦 Bounding Box</h4>
<!-- Box Rotation Controls -->
<h4 style="margin: 15px 0 10px 0; color: #FF9800;">🔄 Box Rotation</h4>
<div style="margin: 10px 0;">
<label>Rotate Y (Yaw): <span id="box-rot-y-value-step0">0</span>°</label><br>
<input type="range" id="box-rot-y-step0" min="-180" max="180" step="1" value="0" style="width: 100%;">
</div>
<div style="margin: 10px 0;">
<label>Rotate X (Pitch): <span id="box-rot-x-value-step0">0</span>°</label><br>
<input type="range" id="box-rot-x-step0" min="-90" max="90" step="1" value="0" style="width: 100%;">
</div>
<div style="margin: 10px 0;">
<label>Rotate Z (Roll): <span id="box-rot-z-value-step0">0</span>°</label><br>
<input type="range" id="box-rot-z-step0" min="-180" max="180" step="1" value="0" style="width: 100%;">
</div>
<div style="margin: 10px 0;">
<label>Box X Size: <span id="box-x-value-step0">3.0</span>m</label><br>
<input type="range" id="box-x-step0" min="0.5" max="50.0" step="0.1" value="3.0" style="width: 100%;">
</div>
<div style="margin: 10px 0;">
<label>Box Y Size: <span id="box-y-value-step0">3.0</span>m</label><br>
<input type="range" id="box-y-step0" min="0.5" max="50.0" step="0.1" value="3.0" style="width: 100%;">
</div>
<div style="margin: 10px 0;">
<label>Box Z Size: <span id="box-z-value-step0">3.0</span>m</label><br>
<input type="range" id="box-z-step0" min="0.5" max="50.0" step="0.1" value="3.0" style="width: 100%;">
</div>
<div style="margin: 10px 0;">
<label>Box X Position: <span id="box-x-pos-value-step0">0.0</span>m</label><br>
<input type="range" id="box-x-pos-step0" min="-25.0" max="25.0" step="0.1" value="0.0" style="width: 100%;">
</div>
<div style="margin: 10px 0;">
<label>Box Y Position: <span id="box-y-pos-value-step0">0.0</span>m</label><br>
<input type="range" id="box-y-pos-step0" min="-25.0" max="25.0" step="0.1" value="0.0" style="width: 100%;">
</div>
<div style="margin: 10px 0;">
<label>Box Z Position: <span id="box-z-pos-value-step0">0.0</span>m</label><br>
<input type="range" id="box-z-pos-step0" min="-25.0" max="25.0" step="0.1" value="0.0" style="width: 100%;">
</div>
<!-- PLY Offset Controls (Optional Fine-Tuning) -->
<h4 style="margin: 15px 0 10px 0; color: #2196F3;">🎯 Fine-tune PLY Position (Optional)</h4>
<div style="margin: 10px 0;">
<label>PLY X Offset: <span id="ply-x-value">0.0</span>m</label><br>
<input type="range" id="ply-x" min="-50.0" max="50.0" step="0.1" value="0.0" style="width: 100%;">
</div>
<div style="margin: 10px 0;">
<label>PLY Y Offset: <span id="ply-y-value">0.0</span>m</label><br>
<input type="range" id="ply-y" min="-50.0" max="50.0" step="0.1" value="0.0" style="width: 100%;">
</div>
<div style="margin: 10px 0;">
<label>PLY Z Offset: <span id="ply-z-value">0.0</span>m</label><br>
<input type="range" id="ply-z" min="-50.0" max="50.0" step="0.1" value="0.0" style="width: 100%;">
</div>
<button id="reset-all-btn" style="
margin-top: 10px;
padding: 8px 15px;
background: #FF9800;
color: white;
border: none;
border-radius: 5px;
cursor: pointer;
width: 48%;
margin-right: 2%;
">Reset All</button>
<!-- 保存状態表示 -->
<div id="save-status" style="
margin: 10px 0;
padding: 8px;
background: #1a1a2e;
border-radius: 5px;
font-size: 11px;
color: #4CAF50;
display: none;
border-left: 3px solid #4CAF50;
">
💾 Filtered PLY will be saved on confirm
</div>
<button id="confirm-box-btn" style="
margin-top: 10px;
padding: 8px 15px;
background: #4CAF50;
color: white;
border: none;
border-radius: 5px;
cursor: pointer;
width: 48%;
">✓ Confirm & Filter</button>
</div>
<!-- ⭐ Step 2のセクションをここに移動(manual-controlsの外へ) -->
<div id="bone-assignment-section" style="display: none; margin-top: 30px;">
<h3>Step 2: Assign Splats to Bones</h3>
<!-- Paint Mode Toggle -->
<div style="
margin: 15px 0;
padding: 10px;
background: #1a1a2e;
border-radius: 5px;
border-left: 3px solid #2196F3;
">
<label style="display: flex; align-items: center; cursor: pointer;">
<input type="checkbox" id="paint-mode-toggle" style="margin-right: 10px;">
<span>🎨 <strong>Paint Mode</strong> - Click and drag to paint over selections</span>
</label>
<div id="paint-mode-hint" style="
font-size: 11px;
color: #aaa;
margin-top: 5px;
display: none;
">
Hold Shift to erase (unassign splats)
</div>
</div>
<!-- Preset Selection -->
<div style="margin: 15px 0;">
<label style="display: block; margin-bottom: 5px; font-weight: bold;">Assignment Mode:</label>
<select id="preset-selector" style="
width: 100%;
padding: 8px;
font-size: 14px;
border-radius: 5px;
background: #333;
color: white;
border: 1px solid #555;
margin-bottom: 10px;
">
<option value="required19">✓ Required (19 parts) - All Essential Bones</option>
</select>
<div id="preset-description" style="
font-size: 11px;
color: #aaa;
padding: 8px;
background: #222;
border-radius: 5px;
margin-bottom: 10px;
"></div>
</div>
<!-- Bone/Group Selector -->
<div id="bone-selector-container" style="margin: 15px 0;">
<label style="display: block; margin-bottom: 5px;">Select Target:</label>
<select id="bone-selector" style="
width: 100%;
padding: 8px;
font-size: 14px;
border-radius: 5px;
background: #333;
color: white;
border: 1px solid #555;
">
<option value="">-- Select target --</option>
</select>
</div>
<!-- Selection Tools -->
<div style="margin: 15px 0;">
<h4 style="margin-bottom: 10px;">Selection Method:</h4>
<div style="margin: 10px 0;">
<button id="select-sphere-btn" style="
padding: 8px 15px;
background: #FF9800;
color: white;
border: none;
border-radius: 5px;
cursor: pointer;
width: 100%;
">🎯 Select by Sphere (Click on GS)</button>
</div>
<div style="margin: 10px 0;">
<label>Selection Radius: <span id="selection-radius-value">0.5</span>m</label><br>
<input type="range" id="selection-radius" min="0.1" max="10.0" step="0.1" value="0.5" style="width: 100%;">
<div style="font-size: 10px; color: #888; margin-top: 3px;">
Range: 0.1m - 10m (適切なサイズに調整してください)
</div>
</div>
<!-- Camera Lock Button -->
<div style="margin: 15px 0; padding: 10px; background: #1a1a2e; border-radius: 5px;">
<button id="camera-lock-btn" style="
padding: 10px 15px;
background: #9C27B0;
color: white;
border: none;
border-radius: 5px;
cursor: pointer;
width: 100%;
font-weight: bold;
">🔓 Camera Unlocked (Can Rotate)</button>
<div style="font-size: 11px; color: #aaa; margin-top: 5px;">
Lock camera to prevent accidental movement while painting
</div>
</div>
<!-- Statistics -->
<div id="assignment-info" style="
margin: 15px 0;
padding: 10px;
background: #222;
border-radius: 5px;
font-size: 12px;
">
<div>Total Splats: <span id="total-splats">0</span></div>
<div>Assigned: <span id="assigned-splats">0</span></div>
<div>Unassigned: <span id="unassigned-splats">0</span></div>
<div style="margin-top: 5px; padding-top: 5px; border-top: 1px solid #444;">
Progress: <span id="assignment-progress">0%</span>
</div>
</div>
<!-- Assignment List -->
<div id="bone-assignment-list" style="
max-height: 150px;
overflow-y: auto;
margin: 15px 0;
padding: 10px;
background: #222;
border-radius: 5px;
font-size: 11px;
">
<div style="color: #888;">No assignments yet</div>
</div>
<!-- Control Buttons -->
<div style="margin: 15px 0;">
<button id="clear-selection-btn" style="
padding: 8px 15px;
background: #f44336;
color: white;
border: none;
border-radius: 5px;
cursor: pointer;
width: 48%;
margin-right: 2%;
">↶ Undo Last</button>
<button id="undo-all-btn" style="
padding: 8px 15px;
background: #FF5722;
color: white;
border: none;
border-radius: 5px;
cursor: pointer;
width: 48%;
">⟲ Reset All</button>
</div>
<button id="finalize-btn" style="
margin-top: 20px;
padding: 10px 20px;
background: #2196F3;
color: white;
border: none;
border-radius: 5px;
cursor: pointer;
font-size: 16px;
width: 100%;
">✓ Finalize and Save</button>
</div>
`;
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
// ========================================
// 修正版 filterSplatsByBox 関数
// Line 527-742 を置き換え
// ========================================
// ========================================
// 修正版 filterSplatsByBox 関数(epsilon調整)
// Line 527-742 を置き換え
// ========================================
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);
// Box半径
const halfX = boxSize.x / 2;
const halfY = boxSize.y / 2;
const halfZ = boxSize.z / 2;
// ⭐ epsilon を大幅に増やす(回転時の数値誤差を吸収)
const epsilon = 0.01; // 0.0001 → 0.01 (1cm)
console.log('[filterSplatsByBox] Box half-extents:', { halfX, halfY, halfZ });
console.log('[filterSplatsByBox] Using epsilon:', epsilon);
// 回転行列の作成と逆行列
const rotationMatrix = new THREE.Matrix4();
rotationMatrix.makeRotationFromEuler(new THREE.Euler(boxRotation.x, boxRotation.y, boxRotation.z));
const inverseRotationMatrix = new THREE.Matrix4().copy(rotationMatrix).invert();
console.log('[filterSplatsByBox] Rotation matrices created');
// デバッグ: 境界付近の頂点を記録
let insideCount = 0;
let outsideCount = 0;
const boundaryVertices = [];
// 最初のパス: 統計収集
plyData.vertices.forEach((vertex, index) => {
const localPos = new THREE.Vector3(
vertex.x - boxPosition.x,
vertex.y - boxPosition.y,
vertex.z - boxPosition.z
);
localPos.applyMatrix4(inverseRotationMatrix);
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)
);
if (inside) {
insideCount++;
} else {
outsideCount++;
}
// 境界から0.5m以内の頂点を記録
const distToEdgeX = Math.min(Math.abs(localPos.x + halfX), Math.abs(localPos.x - halfX));
const distToEdgeY = Math.min(Math.abs(localPos.y + halfY), Math.abs(localPos.y - halfY));
const distToEdgeZ = Math.min(Math.abs(localPos.z + halfZ), Math.abs(localPos.z - halfZ));
const minDistToEdge = Math.min(distToEdgeX, distToEdgeY, distToEdgeZ);
if (minDistToEdge < 0.5) {
boundaryVertices.push({
index,
world: { x: vertex.x, y: vertex.y, z: vertex.z },
local: { x: localPos.x, y: localPos.y, z: localPos.z },
inside,
distToEdge: minDistToEdge
});
}
});
console.log('[DEBUG] Pre-filter summary:');
console.log(' Inside:', insideCount);
console.log(' Outside:', outsideCount);
console.log(' Boundary vertices (within 0.5m):', boundaryVertices.length);
if (boundaryVertices.length > 0) {
console.log('[DEBUG] Sample boundary vertices:');
boundaryVertices.slice(0, 20).forEach(v => {
console.log(` V${v.index}: world(${v.world.x.toFixed(2)}, ${v.world.y.toFixed(2)}, ${v.world.z.toFixed(2)}) ` +
`→ local(${v.local.x.toFixed(2)}, ${v.local.y.toFixed(2)}, ${v.local.z.toFixed(2)}) ` +
`→ ${v.inside ? 'IN' : 'OUT'} (dist: ${v.distToEdge.toFixed(3)}m)`);
});
}
// サンプル頂点表示(最初の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);
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)
);
// ⭐ どの軸で除外されているかを表示
const checkX = localPos.x >= -(halfX + epsilon) && localPos.x <= (halfX + epsilon);
const checkY = localPos.y >= -(halfY + epsilon) && localPos.y <= (halfY + epsilon);
const checkZ = 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,
checks: `X:${checkX} Y:${checkY} Z:${checkZ}`,
limits: {
x: `[${-(halfX + epsilon).toFixed(2)}, ${(halfX + epsilon).toFixed(2)}]`,
y: `[${-(halfY + epsilon).toFixed(2)}, ${(halfY + epsilon).toFixed(2)}]`,
z: `[${-(halfZ + epsilon).toFixed(2)}, ${(halfZ + epsilon).toFixed(2)}]`
}
});
}
// ⭐⭐⭐ 実際のフィルタリング ⭐⭐⭐
const filteredVertices = plyData.vertices.filter((vertex) => {
const localPos = new THREE.Vector3(
vertex.x - boxPosition.x,
vertex.y - boxPosition.y,
vertex.z - boxPosition.z
);
localPos.applyMatrix4(inverseRotationMatrix);
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)
});
console.log('[filterSplatsByBox] ℹ️ Box is rotated - World-space bounds will differ from box size');
}
// 警告
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, size, and rotation');
}
// ⭐⭐⭐ 重要: 結果を返す ⭐⭐⭐
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
// ========================================
// 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/16 12:20
parser.parsePLY(gsPath, true).then((plyData) => {
console.log('[preprocessManual] PLY loaded:', plyData.vertices.length, 'vertices');
loadingSpinner.removeTask(task);
// ========================================
// ⭐ PLY座標系の分析と正規化
// ========================================
console.log('[preprocessManual] ===== ANALYZING PLY COORDINATE SYSTEM =====');
// 1. 主成分分析(PCA)を使って点群の主軸を求める
function computePCA(vertices) {
// 中心を計算
const center = { x: 0, y: 0, z: 0 };
vertices.forEach(v => {
center.x += v.x;
center.y += v.y;
center.z += v.z;
});
center.x /= vertices.length;
center.y /= vertices.length;
center.z /= vertices.length;
console.log('[PCA] Center:', center);
// 共分散行列を計算
let cxx = 0, cxy = 0, cxz = 0;
let cyy = 0, cyz = 0, czz = 0;
vertices.forEach(v => {
const dx = v.x - center.x;
const dy = v.y - center.y;
const dz = v.z - center.z;
cxx += dx * dx;
cxy += dx * dy;
cxz += dx * dz;
cyy += dy * dy;
cyz += dy * dz;
czz += dz * dz;
});
cxx /= vertices.length;
cxy /= vertices.length;
cxz /= vertices.length;
cyy /= vertices.length;
cyz /= vertices.length;
czz /= vertices.length;
console.log('[PCA] Covariance matrix:', {
cxx: cxx.toFixed(2),
cxy: cxy.toFixed(2),
cxz: cxz.toFixed(2),
cyy: cyy.toFixed(2),
cyz: cyz.toFixed(2),
czz: czz.toFixed(2)
});
// 分散の比率から座標系の傾きを判定
const totalVariance = cxx + cyy + czz;
const xRatio = cxx / totalVariance;
const yRatio = cyy / totalVariance;
const zRatio = czz / totalVariance;
console.log('[PCA] Variance ratios:', {
x: (xRatio * 100).toFixed(1) + '%',
y: (yRatio * 100).toFixed(1) + '%',
z: (zRatio * 100).toFixed(1) + '%'
});
// 座標系が偏っているか判定
const isAligned = (
Math.abs(cxy) < 0.1 * Math.sqrt(cxx * cyy) &&
Math.abs(cxz) < 0.1 * Math.sqrt(cxx * czz) &&
Math.abs(cyz) < 0.1 * Math.sqrt(cyy * czz)
);
console.log('[PCA] Is aligned with world axes:', isAligned);
return {
center,
isAligned,
needsRotation: !isAligned,
covarianceMatrix: { cxx, cxy, cxz, cyy, cyz, czz }
};
}
// 2. 点群を分析
const pcaResult = computePCA(plyData.vertices);
// 完全修正版: PLY中心化(Line 1102-1233を置き換え)
// ========================================
// 完全修正版: PLY中心化(Line 1102-1233を置き換え)
// PCAではなく単純な重心で中心化
// ========================================
//preprocess_manual.js の Line 1100-1290付近
// ========================================
// 完全修正版: PLY中心化(Line 1100-1290を置き換え)
// イミュータブルなオブジェクト生成で確実に中心化
// ========================================
// デバッグ版: PLY中心化(Line 1107-1330を置き換え)
// ========================================
// デバッグ版: PLY中心化(Line 1107-1330を置き換え)
// 各ステップで配列の参照を確認
// ========================================
///// Line 1113-1419 を以下に置き換え ///// Line 1113-1419 を以下に置き換え
// ========================================
// 1. PLYをカメラ座標系のままにする
// Line 1113-1419 を以下に置き換え
// ========================================
console.log('[preprocessManual] ===== PLY DATA LOADED =====');
console.log('[preprocessManual] PLY data is in CAMERA coordinate space');
console.log(' Total vertices:', plyData.vertices.length);
// ⭐ 重要: PLYは既にカメラ座標系なので、そのまま使用
// 中心化も移動も一切しない
// 統計情報のみ計算
let minX = Infinity, minY = Infinity, minZ = Infinity;
let maxX = -Infinity, maxY = -Infinity, maxZ = -Infinity;
for (let i = 0; i < plyData.vertices.length; i++) {
const v = plyData.vertices[i];
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('[preprocessManual] PLY bounds (CAMERA space):');
console.log(' Min:', { x: minX.toFixed(3), y: minY.toFixed(3), z: minZ.toFixed(3) });
console.log(' Max:', { x: maxX.toFixed(3), y: maxY.toFixed(3), z: maxZ.toFixed(3) });
console.log(' Center:', {
x: ((minX + maxX) / 2).toFixed(3),
y: ((minY + maxY) / 2).toFixed(3),
z: ((minZ + maxZ) / 2).toFixed(3)
});
console.log('[preprocessManual] ✓ PLY coordinates preserved (CAMERA space)');
// ⭐ ここに追加 12/17 22:00 ⭐
console.log('[preprocessManual] ===== COORDINATE SYSTEM CHECK =====');
const worldOriginInCameraSpace = new THREE.Vector3(0, 0, 0);
worldOriginInCameraSpace.applyMatrix4(camera.matrixWorldInverse);
console.log(' World origin (0,0,0) in camera space:', {
x: worldOriginInCameraSpace.x.toFixed(3),
y: worldOriginInCameraSpace.y.toFixed(3),
z: worldOriginInCameraSpace.z.toFixed(3)
});
console.log(' Camera position in world space:', {
x: camera.position.x.toFixed(3),
y: camera.position.y.toFixed(3),
z: camera.position.z.toFixed(3)
});
// ========================================
// 2. 世界座標→カメラ座標の変換関数
// ========================================
/**
* 世界座標をカメラ座標に変換
* @param {THREE.Vector3} worldPos - 世界座標の位置
* @param {THREE.Camera} camera - カメラオブジェクト
* @returns {THREE.Vector3} カメラ座標での位置
*/
function worldToCameraSpace(worldPos, camera) {
const cameraPos = worldPos.clone();
// カメラのビュー行列を更新
camera.updateMatrixWorld();
// 世界座標→カメラ座標の変換
// ビュー行列 = カメラのmatrixWorldInverse
cameraPos.applyMatrix4(camera.matrixWorldInverse);
return cameraPos;
}
/**
* 世界座標のBOXをカメラ座標のBOXに変換
* @param {Object} worldBox - { min: {x,y,z}, max: {x,y,z} }
* @param {THREE.Camera} camera - カメラオブジェクト
* @returns {Object} カメラ座標のBOX { min: {x,y,z}, max: {x,y,z} }
*/
function transformBoxToCameraSpace(worldBox, camera) {
const { min, max } = worldBox;
// 8頂点を世界座標で定義
const vertices = [
new THREE.Vector3(min.x, min.y, min.z),
new THREE.Vector3(max.x, min.y, min.z),
new THREE.Vector3(max.x, max.y, min.z),
new THREE.Vector3(min.x, max.y, min.z),
new THREE.Vector3(min.x, min.y, max.z),
new THREE.Vector3(max.x, min.y, max.z),
new THREE.Vector3(max.x, max.y, max.z),
new THREE.Vector3(min.x, max.y, max.z)
];
// 各頂点をカメラ座標に変換
const cameraVertices = vertices.map(v => worldToCameraSpace(v, camera));
// カメラ座標での新しいAABB(軸並行境界ボックス)を計算
let cMinX = Infinity, cMinY = Infinity, cMinZ = Infinity;
let cMaxX = -Infinity, cMaxY = -Infinity, cMaxZ = -Infinity;
cameraVertices.forEach(v => {
cMinX = Math.min(cMinX, v.x);
cMinY = Math.min(cMinY, v.y);
cMinZ = Math.min(cMinZ, v.z);
cMaxX = Math.max(cMaxX, v.x);
cMaxY = Math.max(cMaxY, v.y);
cMaxZ = Math.max(cMaxZ, v.z);
});
return {
min: { x: cMinX, y: cMinY, z: cMinZ },
max: { x: cMaxX, y: cMaxY, z: cMaxZ }
};
}
console.log('[preprocessManual] ✓ Coordinate transformation functions defined');
// ========================================
// 3. BOXをカメラ座標系で作成・表示
// ========================================
/**
* カメラ座標系でBOXを作成
* @param {Object} cameraBox - { min: {x,y,z}, max: {x,y,z} } カメラ座標
* @param {THREE.Scene} scene - Three.jsシーン
* @returns {THREE.LineSegments} BOXオブジェクト
*/
function createCameraSpaceBox(cameraBox, scene) {
const { min, max } = cameraBox;
const size = {
x: max.x - min.x,
y: max.y - min.y,
z: max.z - min.z
};
const center = {
x: (min.x + max.x) / 2,
y: (min.y + max.y) / 2,
z: (min.z + max.z) / 2
};
console.log('[createCameraSpaceBox] Creating box in CAMERA space:');
console.log(' Min:', min);
console.log(' Max:', max);
console.log(' Center:', center);
console.log(' Size:', size);
// BOXジオメトリを作成
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 });
const boxHelper = new THREE.LineSegments(edges, material);
// ⭐ 重要: カメラ座標系で配置
// カメラ座標系 = ローカル座標系なので、シーンに直接追加
boxHelper.position.set(center.x, center.y, center.z);
scene.add(boxHelper);
console.log('[createCameraSpaceBox] ✓ Box added in camera space');
return boxHelper;
}
// ========================================
// 4. フィルタリング関数(カメラ座標系)
// Line 527-742 を以下に置き換え
// ========================================
/**
* カメラ座標系のBOX内のスプラットをフィルタリング
* @param {Object} plyData - PLYデータ(camera coordinates)
* @param {Object} cameraBox - { min: {x,y,z}, max: {x,y,z} } カメラ座標
* @returns {Array} フィルタリングされた頂点配列
*/
function filterSplatsByCameraBox(plyData, cameraBox) {
console.log('[filterSplatsByCameraBox] ===== FILTERING START =====');
console.log('[filterSplatsByCameraBox] CAMERA-space box:');
console.log(' Min:', cameraBox.min);
console.log(' Max:', cameraBox.max);
console.log(' Total vertices:', plyData.vertices.length);
const { min, max } = cameraBox;
// ⭐ PLYもカメラ座標、BOXもカメラ座標なので、シンプルな範囲チェック
const filteredVertices = plyData.vertices.filter(vertex => {
return (
vertex.x >= min.x && vertex.x <= max.x &&
vertex.y >= min.y && vertex.y <= max.y &&
vertex.z >= min.z && vertex.z <= max.z
);
});
const retentionRate = (filteredVertices.length / plyData.vertices.length * 100).toFixed(1);
console.log('[filterSplatsByCameraBox] ===== FILTERING COMPLETE =====');
console.log(' Filtered:', filteredVertices.length, '/', plyData.vertices.length);
console.log(' Retention rate:', retentionRate, '%');
if (filteredVertices.length > 0) {
let fMinX = Infinity, fMinY = Infinity, fMinZ = Infinity;
let fMaxX = -Infinity, fMaxY = -Infinity, fMaxZ = -Infinity;
filteredVertices.forEach(v => {
fMinX = Math.min(fMinX, v.x);
fMinY = Math.min(fMinY, v.y);
fMinZ = Math.min(fMinZ, v.z);
fMaxX = Math.max(fMaxX, v.x);
fMaxY = Math.max(fMaxY, v.y);
fMaxZ = Math.max(fMaxZ, v.z);
});
console.log('[filterSplatsByCameraBox] Filtered bounds (camera space):');
console.log(' X:', fMinX.toFixed(3), 'to', fMaxX.toFixed(3));
console.log(' Y:', fMinY.toFixed(3), 'to', fMaxY.toFixed(3));
console.log(' Z:', fMinZ.toFixed(3), 'to', fMaxZ.toFixed(3));
}
return filteredVertices;
}
// ========================================
// 5. 統合処理:世界座標のBOX → フィルタリング
// ========================================
/**
* 世界座標のBOXでPLYをフィルタリング(完全な処理)
* @param {Object} plyData - PLYデータ(camera coordinates)
* @param {Object} worldBox - 世界座標のBOX { min: {x,y,z}, max: {x,y,z} }
* @param {THREE.Camera} camera - カメラオブジェクト
* @param {THREE.Scene} scene - Three.jsシーン
* @returns {Object} { filteredVertices: Array, cameraBox: Object, boxHelper: Object }
*/
function filterWithWorldBox(plyData, worldBox, camera, scene) {
console.log('[filterWithWorldBox] ===== COMPLETE FILTERING PROCESS =====');
// Step 1: 世界座標のBOXをカメラ座標に変換
console.log('[filterWithWorldBox] Step 1: Transform box to camera space');
console.log(' World box:', worldBox);
const cameraBox = transformBoxToCameraSpace(worldBox, camera);
console.log('[filterWithWorldBox] ✓ Transformed to camera space:', cameraBox);
// Step 2: カメラ座標でBOXを表示
console.log('[filterWithWorldBox] Step 2: Display box in camera space');
const boxHelper = createCameraSpaceBox(cameraBox, scene);
console.log('[filterWithWorldBox] ✓ Box displayed');
// Step 3: カメラ座標でフィルタリング
console.log('[filterWithWorldBox] Step 3: Filter splats in camera space');
const filteredVertices = filterSplatsByCameraBox(plyData, cameraBox);
console.log('[filterWithWorldBox] ✓ Filtering complete:', filteredVertices.length, 'vertices');
console.log('[filterWithWorldBox] ===== PROCESS COMPLETE =====');
return {
filteredVertices,
cameraBox,
boxHelper
};
}
// ========================================
// UI統合版: confirm-box-btn イベントリスナー
// Line 1608付近を以下に置き換え
// ========================================
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('═══════════════════════════════════════════════════════');
// ⭐ Step 1: UIから世界座標のBOX設定を取得
const worldBoxSize = {
x: parseFloat(document.getElementById('box-x-step0').value),
y: parseFloat(document.getElementById('box-y-step0').value),
z: parseFloat(document.getElementById('box-z-step0').value)
};
const worldBoxPosition = {
x: parseFloat(document.getElementById('box-x-pos-step0').value),
y: parseFloat(document.getElementById('box-y-pos-step0').value),
z: parseFloat(document.getElementById('box-z-pos-step0').value)
};
// ⭐ 世界座標でのBOX範囲を計算
const worldBox = {
min: {
x: worldBoxPosition.x - worldBoxSize.x / 2,
y: worldBoxPosition.y - worldBoxSize.y / 2,
z: worldBoxPosition.z - worldBoxSize.z / 2
},
max: {
x: worldBoxPosition.x + worldBoxSize.x / 2,
y: worldBoxPosition.y + worldBoxSize.y / 2,
z: worldBoxPosition.z + worldBoxSize.z / 2
}
};
console.log('[CONFIRM] World box (from UI):', worldBox);
// ⭐ Step 2: 世界座標BOXをカメラ座標に変換
console.log('[CONFIRM] Transforming box to camera space...');
const cameraBox = transformBoxToCameraSpace(worldBox, camera);
console.log('[CONFIRM] Camera box (transformed):', cameraBox);
// ⭐ Step 3: カメラ座標でBOXを表示
console.log('[CONFIRM] Displaying box in camera space...');
ui.removeBoundingBox(); // 古いBOXを削除
///// step2におけるbox出現の理由?
// const boxHelper = createCameraSpaceBox(cameraBox, scene);
// ⭐ Step 4: カメラ座標でフィルタリング
console.log('[CONFIRM] Filtering splats in camera space...');
const filteredVertices = filterSplatsByCameraBox(plyData, cameraBox);
//console.log('[CONFIRM] ✓ Filtered', filteredVertices.length, 'vertices');
console.log('═══════════════════════════════════════════════════════');
console.log(' BOX FILTERING COMPLETE');
console.log('═══════════════════════════════════════════════════════');
// ⭐ 以降は元のコード(STEP 5以降)と同様
// フィルタリング後のPLY保存、GS再読み込み、VRM読み込み等...
});
}
///// Line 1113-1419 を以下に置き換え ///// Line 1113-1419 を以下に置き換え
/////////////////////////////ここから
GVRM.initGS(gsPath, undefined, undefined, scene).then((gs) => {
console.log('[preprocessManual] GS initialized');
// ========================================
// ⭐ PLY補正が適用されている場合、GSにも同じ変換を適用
// ========================================
if (window.plyAlignmentApplied && window.plyAlignmentMatrix) {
console.log('[preprocessManual] Applying alignment transform to GS display...');
const gsScene = gs.viewer.splatMesh.scenes[0];
// 補正行列をGS Sceneに適用
gsScene.matrixAutoUpdate = false;
gsScene.matrix.copy(window.plyAlignmentMatrix);
gsScene.matrixWorldNeedsUpdate = true;
gsScene.updateMatrixWorld(true);
console.log('[preprocessManual] ✓ GS display aligned with PLY data');
console.log('[preprocessManual] GS Scene matrix:', gsScene.matrix.elements.slice(0, 4));
} else {
console.log('[preprocessManual] No alignment transform needed for GS');
}
// ========================================
// ⭐ 1. カメラコントロールを初期化(グローバルに保存)
// ========================================
if (!window.globalCameraControls) {
window.globalCameraControls = setupCameraControls(camera, renderer);
console.log('[preprocessManual] ✓ Camera controls created and saved globally');
} else {
console.log('[preprocessManual] Using existing global camera controls');
}
// ========================================
// ⭐ 2. キーボードコントロールを初期化
// ========================================
setupKeyboardControls();
console.log('[preprocessManual] Keyboard controls initialized');
// ========================================
// ⭐ 3. アニメーションループを開始
// ========================================
// グローバルなカメラロック状態
if (!window.cameraLockState) {
window.cameraLockState = {
locked: false,
frameCount: 0
};
}
let animationId = null;
function animateControls() {
animationId = requestAnimationFrame(animateControls);
window.cameraLockState.frameCount++;
// キーボードコントロールの更新(カメラロック時は無効化)
if (!window.cameraLockState.locked) {
updateCameraFromKeys(camera, window.globalCameraControls);
}
// ⭐⭐⭐ 重要:カメラがロックされている場合はOrbitControlsを強制的に無効化し続ける
if (window.cameraLockState.locked) {
if (window.globalCameraControls && window.globalCameraControls.controls) {
window.globalCameraControls.controls.enabled = false;
}
} else {
// カメラがアンロックされている場合のみ更新
if (window.globalCameraControls && window.globalCameraControls.controls) {
window.globalCameraControls.controls.update();
}
}
// 10秒ごとに状態をログ出力(デバッグ用)
if (window.cameraLockState.frameCount % 600 === 0) {
console.log('[animateControls] Status check:', {
locked: window.cameraLockState.locked,
controlsEnabled: window.globalCameraControls?.controls?.enabled,
frame: window.cameraLockState.frameCount
});
}
renderer.render(scene, camera);
}
animateControls();
console.log('[preprocessManual] ✓ Animation loop started with camera lock support');
////ここまで
// Cleanup function to stop animation
const cleanupAnimation = () => {
if (animationId) {
cancelAnimationFrame(animationId);
animationId = null;
}
};
// ========================================
// ⭐ 4. カメラをPLYに合わせて調整(cameraControls初期化後)
// ========================================
/// add 12/17 13:30
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
};
/////////////////////add 13:40
// Initialize box and PLY offset variables
let boxSize = {
x: sceneSize.x * 1.2,
y: sceneSize.y * 1.2,
z: sceneSize.z * 1.2
};
let boxPosition = { x: 0, y: 0, z: 0 };
let boxRotation = { x: 0, y: 0, z: 0 };
let plyOffset = { x: 0, y: 0, z: 0 };
// Calculate camera position
const maxDim = Math.max(sceneSize.x, sceneSize.y, sceneSize.z);
const distance = maxDim * 2.0;
camera.position.set(0, maxDim * 0.3, distance);
camera.lookAt(0, 0, 0);
camera.updateProjectionMatrix();
////
window.globalCameraControls.controls.target.set(0, 0, 0);
window.globalCameraControls.controls.update();
console.log('[preprocessManual] Camera positioned at:', {
x: camera.position.x.toFixed(2),
y: camera.position.y.toFixed(2),
z: camera.position.z.toFixed(2)
});
////
console.log('[preprocessManual] Initial box setup - size:', boxSize);
/////////////////////end of add 13:40
// 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)})`;
}
const gsScene = gs.viewer.splatMesh.scenes[0];
// Create initial bounding box
ui.createBoundingBox(boxSize, boxPosition, boxRotation);
// ========================================
// ⭐ 7. UIスライダーの初期値を更新
// ========================================
if (document.getElementById('box-x-step0')) {
document.getElementById('box-x-step0').value = boxSize.x.toFixed(1);
document.getElementById('box-x-value-step0').textContent = boxSize.x.toFixed(1);
document.getElementById('box-y-step0').value = boxSize.y.toFixed(1);
document.getElementById('box-y-value-step0').textContent = boxSize.y.toFixed(1);
document.getElementById('box-z-step0').value = boxSize.z.toFixed(1);
document.getElementById('box-z-value-step0').textContent = boxSize.z.toFixed(1);
document.getElementById('box-x-pos-step0').value = boxPosition.x.toFixed(1);
document.getElementById('box-x-pos-value-step0').textContent = boxPosition.x.toFixed(1);
document.getElementById('box-y-pos-step0').value = boxPosition.y.toFixed(1);
document.getElementById('box-y-pos-value-step0').textContent = boxPosition.y.toFixed(1);
document.getElementById('box-z-pos-step0').value = boxPosition.z.toFixed(1);
document.getElementById('box-z-pos-value-step0').textContent = boxPosition.z.toFixed(1);
console.log('[preprocessManual] UI sliders initialized to PLY-aligned values');
}
ui.setStatus('Step 0: Adjust bounding box to frame your object');
ui.showPositionAdjustment();
console.log('[preprocessManual] ✓ Camera and Box aligned to PLY');
// ========================================
// ⭐ 8. 以降は元のコード(スライダー設定など)
// ========================================
// 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);
});
}
};
// Box rotation sliders
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;
ui.updateBoundingBox(boxSize, boxPosition, boxRotation);
});
}
};
// 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');
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');
setupPlyOffsetSlider('ply-x', 'ply-x-value', 'x');
setupPlyOffsetSlider('ply-y', 'ply-y-value', 'y');
setupPlyOffsetSlider('ply-z', 'ply-z-value', 'z');
// Reset button
const resetAllBtn = document.getElementById('reset-all-btn');
if (resetAllBtn) {
resetAllBtn.addEventListener('click', () => {
// Reset rotation
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 to PLY-aligned defaults
boxSize = {
x: size.x * 0.5,
y: size.y * 0.5,
z: size.z * 0.5
};
boxPosition = {
x: center.x,
y: center.y,
z: center.z
};
// Update UI
document.getElementById('box-x-step0').value = boxSize.x.toFixed(1);
document.getElementById('box-y-step0').value = boxSize.y.toFixed(1);
document.getElementById('box-z-step0').value = boxSize.z.toFixed(1);
document.getElementById('box-x-value-step0').textContent = boxSize.x.toFixed(1);
document.getElementById('box-y-value-step0').textContent = boxSize.y.toFixed(1);
document.getElementById('box-z-value-step0').textContent = boxSize.z.toFixed(1);
document.getElementById('box-x-pos-step0').value = boxPosition.x.toFixed(1);
document.getElementById('box-y-pos-step0').value = boxPosition.y.toFixed(1);
document.getElementById('box-z-pos-step0').value = boxPosition.z.toFixed(1);
document.getElementById('box-x-pos-value-step0').textContent = boxPosition.x.toFixed(1);
document.getElementById('box-y-pos-value-step0').textContent = boxPosition.y.toFixed(1);
document.getElementById('box-z-pos-value-step0').textContent = boxPosition.z.toFixed(1);
// 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);
});
}
////////////////////////////////////////////////これの上が書き換えられる
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設定を明示的に取得 ⭐⭐⭐
const currentBoxSize = {
x: parseFloat(document.getElementById('box-x-step0').value),
y: parseFloat(document.getElementById('box-y-step0').value),
z: parseFloat(document.getElementById('box-z-step0').value)
};
const currentBoxPosition = {
x: parseFloat(document.getElementById('box-x-pos-step0').value),
y: parseFloat(document.getElementById('box-y-pos-step0').value),
z: parseFloat(document.getElementById('box-z-pos-step0').value)
};
const currentBoxRotation = {
x: parseFloat(document.getElementById('box-rot-x-step0').value) * Math.PI / 180,
y: parseFloat(document.getElementById('box-rot-y-step0').value) * Math.PI / 180,
z: parseFloat(document.getElementById('box-rot-z-step0').value) * Math.PI / 180
};
const currentPlyOffset = {
x: parseFloat(document.getElementById('ply-x').value),
y: parseFloat(document.getElementById('ply-y').value),
z: parseFloat(document.getElementById('ply-z').value)
};
// 現在のBOX設定をログ
console.log('[STEP 1] Current BOX Settings (from UI):');
console.log(' Box Size:', currentBoxSize);
console.log(' Box Position:', currentBoxPosition);
console.log(' Box Rotation (radians):', currentBoxRotation);
console.log(' Box Rotation (degrees):', {
x: (currentBoxRotation.x * 180 / Math.PI).toFixed(1) + '°',
y: (currentBoxRotation.y * 180 / Math.PI).toFixed(1) + '°',
z: (currentBoxRotation.z * 180 / Math.PI).toFixed(1) + '°'
});
console.log(' PLY Offset:', currentPlyOffset);
// ⭐ デバッグ: 外側の変数も確認
console.log('[STEP 1] Outer scope variables (for comparison):');
console.log(' boxSize:', boxSize);
console.log(' boxPosition:', boxPosition);
console.log(' boxRotation:', boxRotation);
console.log(' plyOffset:', plyOffset);
////////////////////////////////////////////////////0123 start
// ⭐ 修正: 中心化後のPLYデータの範囲を確認
console.log('[STEP 2] Centered PLY Data (should be ~0,0,0):');
console.log(' Total vertices:', plyData.vertices.length);
let centeredMinX = Infinity, centeredMinY = Infinity, centeredMinZ = Infinity;
let centeredMaxX = -Infinity, centeredMaxY = -Infinity, centeredMaxZ = -Infinity;
plyData.vertices.forEach(v => {
centeredMinX = Math.min(centeredMinX, v.x);
centeredMinY = Math.min(centeredMinY, v.y);
centeredMinZ = Math.min(centeredMinZ, v.z);
centeredMaxX = Math.max(centeredMaxX, v.x);
centeredMaxY = Math.max(centeredMaxY, v.y);
centeredMaxZ = Math.max(centeredMaxZ, v.z);
});
const centeredCenter = {
x: (centeredMinX + centeredMaxX) / 2,
y: (centeredMinY + centeredMaxY) / 2,
z: (centeredMinZ + centeredMaxZ) / 2
};
cleanupAnimation();
// PLY Offsetの適用
if (currentPlyOffset.x !== 0 || currentPlyOffset.y !== 0 || currentPlyOffset.z !== 0) {
console.log('[STEP 3] Applying PLY offset:', currentPlyOffset);
plyData.vertices.forEach(vertex => {
vertex.x += currentPlyOffset.x;
vertex.y += currentPlyOffset.y;
vertex.z += currentPlyOffset.z;
});
console.log('[STEP 3] ✓ PLY data updated with offset');
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);
await gs.viewer.dispose();
gs = await GVRM.initGS(adjustedPlyUrl, undefined, undefined, scene);
// ⭐ 外側の変数も更新(念のため)
plyOffset = { x: 0, y: 0, z: 0 };
// confirm-box-btn のイベントリスナー内に追加
// フィルタリング後、結果を視覚化
if (filteredVertices.length > 0) {
// 色を変えて表示
filteredIndices.forEach(idx => {
filteredGs.colors[idx * 4 + 0] = 0;
filteredGs.colors[idx * 4 + 1] = 255;
filteredGs.colors[idx * 4 + 2] = 0;
});
filteredGs.splatMesh.updateDataTexturesFromBaseData(0, filteredGs.splatCount - 1);
const confirmResult = confirm(
`Filtered ${filteredVertices.length} splats (shown in green).\n\n` +
`Does the green area match the box?\n\n` +
`OK = Continue | Cancel = Adjust box again`
);
if (!confirmResult) {
// Box設定に戻る
ui.showPositionAdjustment();
return;
}
}
} else {
console.log('[STEP 3] No PLY offset to apply');
}
ui.hidePositionAdjustment();
ui.setStatus('Filtering splats with bounding box...');
///////////////////////////////////////13:47 start
console.log('[STEP 4] ⭐ Transforming Box coordinates to GS local space');
// GS Scene の変換行列を取得
const gsScene = gs.viewer.splatMesh.scenes[0];
gsScene.updateMatrixWorld(true);
// Box Position を Three.js Vector3 に変換
const boxWorldPosition = new THREE.Vector3(
currentBoxPosition.x,
currentBoxPosition.y,
currentBoxPosition.z
);
// GS の逆行列を適用してローカル空間に変換
const gsInverseMatrix = new THREE.Matrix4().copy(gsScene.matrixWorld).invert();
const boxLocalPosition = boxWorldPosition.applyMatrix4(gsInverseMatrix);
console.log('[STEP 4] Box position transformation:');
console.log(' World space:', currentBoxPosition);
console.log(' GS local space:', {
x: boxLocalPosition.x.toFixed(3),
y: boxLocalPosition.y.toFixed(3),
z: boxLocalPosition.z.toFixed(3)
});
// Box Rotation も変換
const boxRotationEuler = new THREE.Euler(
currentBoxRotation.x,
currentBoxRotation.y,
currentBoxRotation.z
);
const boxRotationMatrix = new THREE.Matrix4().makeRotationFromEuler(boxRotationEuler);
// GS の回転を抽出
const gsRotationMatrix = new THREE.Matrix4().extractRotation(gsScene.matrixWorld);
// 合成: GS^-1 * Box
const combinedRotationMatrix = new THREE.Matrix4()
.copy(gsRotationMatrix)
.invert()
.multiply(boxRotationMatrix);
const combinedRotationEuler = new THREE.Euler().setFromRotationMatrix(combinedRotationMatrix);
console.log('[STEP 4] Box rotation transformation:');
console.log(' World space (deg):', {
x: (currentBoxRotation.x * 180 / Math.PI).toFixed(1) + '°',
y: (currentBoxRotation.y * 180 / Math.PI).toFixed(1) + '°',
z: (currentBoxRotation.z * 180 / Math.PI).toFixed(1) + '°'
});
console.log(' GS local space (deg):', {
x: (combinedRotationEuler.x * 180 / Math.PI).toFixed(1) + '°',
y: (combinedRotationEuler.y * 180 / Math.PI).toFixed(1) + '°',
z: (combinedRotationEuler.z * 180 / Math.PI).toFixed(1) + '°'
});
// ⭐⭐⭐ 変換後の座標で filterSplatsByBox を呼ぶ
const filteredVertices = filterSplatsByBox(
plyData,
currentBoxSize,
{
x: boxLocalPosition.x,
y: boxLocalPosition.y,
z: boxLocalPosition.z
},
{
x: combinedRotationEuler.x,
y: combinedRotationEuler.y,
z: combinedRotationEuler.z
}
);
/////////////////////////////////////13:47 end
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 4] ✓ Filtering complete:', filteredVertices.length, 'splats kept');
// ⭐ 外側の変数も更新(他のコードで使われる可能性があるため)
boxSize = currentBoxSize;
boxPosition = currentBoxPosition;
boxRotation = currentBoxRotation;
// ... 残りのコード(STEP 5以降)は変更なし ...
// スプラットを中心化
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
// ========================================
////////////////////////////////////////////////0111
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);
///////////////////
// ========================================
// Load default bone operations with error handling
// ========================================
let boneOperations = [];
try {
console.log('[setupBoneAssignment] Attempting to load default.json...');
const response = await fetch("./assets/default.json");
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
const params = await response.json();
boneOperations = params.boneOperations || [];
console.log('[setupBoneAssignment] ✓ default.json loaded successfully');
} catch (error) {
console.warn('[setupBoneAssignment] Could not load default.json:', error.message);
console.warn('[setupBoneAssignment] Using default T-pose instead');
// デフォルトのT-poseを使用(何も変更しない)
boneOperations = [];
}
// ボーン操作を適用(boneOperationsが空でも安全)
if (boneOperations.length > 0) {
console.log('[setupBoneAssignment] Applying bone operations...');
GVRMUtils.resetPose(character, boneOperations);
} else {
console.log('[setupBoneAssignment] No bone operations to apply, using current pose');
}
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 = '<option value="">-- Select target --</option>';
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);
});
}
// ========================================
// Select Sphere Button 挿入 12/18 15:40
// ========================================
const selectSphereBtn = document.getElementById('select-sphere-btn');
if (selectSphereBtn) {
selectSphereBtn.addEventListener('click', () => {
if (!selectedTarget) {
alert('Please select a target bone or group first');
return;
}
selectionMode = 'sphere';
selectSphereBtn.style.background = '#4CAF50';
selectSphereBtn.textContent = '✓ Sphere Mode Active (Click GS)';
console.log('[setupBoneAssignment] Sphere selection mode activated');
console.log(' Target:', selectedTarget);
console.log(' Radius:', selectionRadius, 'm');
});
}
// ========================================
// Selection Radius Slider
// ========================================
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(1);
});
}
// ========================================
// 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');
}
});
}
////helper関数挿入
// ========================================
// 🎯 挿入場所: setupBoneAssignment 関数内
// ====helper関数挿入 の直後
// ========================================
/**
* ターゲットの色を取得
*/
function getTargetColor(target) {
if (target.startsWith('group_')) {
const groupIndex = parseInt(target.replace('group_', ''));
const group = currentBoneGroups[groupIndex];
if (group && group.color) {
return group.color;
}
}
return [255, 255, 255];
}
/**
* ターゲットのボーンインデックスを取得
*/
function getTargetBoneIndices(target) {
const indices = [];
if (target.startsWith('group_')) {
const groupIndex = parseInt(target.replace('group_', ''));
const group = currentBoneGroups[groupIndex];
if (group && group.bones) {
group.bones.forEach(boneName => {
if (boneNameToIndex[boneName] !== undefined) {
indices.push(boneNameToIndex[boneName]);
}
});
}
}
return indices;
}
/**
* ボーンインデックスからボーン名を取得
*/
function getBoneNameFromIndex(index) {
for (const [name, idx] of Object.entries(boneNameToIndex)) {
if (idx === index) {
return name;
}
}
return `bone_${index}`;
}
/**
* Splatに割り当てを適用
*/
function applyAssignmentToIndices(indices, target, isEraser) {
if (isEraser) {
indices.forEach(idx => {
if (assignmentData.splatBoneIndices[idx] >= 0) {
const oldBoneName = getBoneNameFromIndex(assignmentData.splatBoneIndices[idx]);
if (assignmentData.boneAssignments[oldBoneName]) {
const arrayIdx = assignmentData.boneAssignments[oldBoneName].indexOf(idx);
if (arrayIdx >= 0) {
assignmentData.boneAssignments[oldBoneName].splice(arrayIdx, 1);
}
}
assignmentData.splatBoneIndices[idx] = -1;
filteredGs.colors[idx * 4 + 0] = 255;
filteredGs.colors[idx * 4 + 1] = 255;
filteredGs.colors[idx * 4 + 2] = 255;
}
});
console.log('[Paint] Erased', indices.length, 'splats');
} else {
const targetColor = getTargetColor(target);
const boneIndices = getTargetBoneIndices(target);
if (boneIndices.length === 0) {
console.warn('[applyAssignmentToIndices] No bone indices found for target:', target);
return;
}
indices.forEach(idx => {
assignmentData.splatBoneIndices[idx] = boneIndices[0];
filteredGs.colors[idx * 4 + 0] = targetColor[0];
filteredGs.colors[idx * 4 + 1] = targetColor[1];
filteredGs.colors[idx * 4 + 2] = targetColor[2];
boneIndices.forEach(boneIdx => {
const boneName = getBoneNameFromIndex(boneIdx);
if (!assignmentData.boneAssignments[boneName]) {
assignmentData.boneAssignments[boneName] = [];
}
if (!assignmentData.boneAssignments[boneName].includes(idx)) {
assignmentData.boneAssignments[boneName].push(idx);
}
});
});
console.log('[Paint] Painted', indices.length, 'splats with', target);
}
filteredGs.splatMesh.updateDataTexturesFromBaseData(0, filteredGs.splatCount - 1);
updateStats();
}
/**
* 2D画面座標から最も近い3D Splatを検索
*/
function findNearestSplat(mouseX, mouseY, camera, filteredGs, maxScreenDistance = 100) {
const canvas = renderer.domElement;
const mousePixelX = (mouseX + 1) * canvas.width / 2;
const mousePixelY = (-mouseY + 1) * canvas.height / 2;
let nearestSplatIndex = -1;
let nearestScreenDist = Infinity;
const cameraPos = camera.position;
const worldPos = new THREE.Vector3();
const screenPos = new THREE.Vector3();
for (let i = 0; i < filteredGs.splatCount; i++) {
worldPos.x = filteredGs.centers0[i * 3 + 0];
worldPos.y = filteredGs.centers0[i * 3 + 1];
worldPos.z = filteredGs.centers0[i * 3 + 2];
screenPos.copy(worldPos);
screenPos.project(camera);
if (screenPos.z > 1) continue;
const screenPixelX = (screenPos.x + 1) * canvas.width / 2;
const screenPixelY = (-screenPos.y + 1) * canvas.height / 2;
const dx = screenPixelX - mousePixelX;
const dy = screenPixelY - mousePixelY;
const screenDist = Math.sqrt(dx * dx + dy * dy);
if (screenDist < maxScreenDistance && screenDist < nearestScreenDist) {
nearestScreenDist = screenDist;
nearestSplatIndex = i;
}
}
if (nearestSplatIndex >= 0) {
return {
index: nearestSplatIndex,
screenDistance: nearestScreenDist
};
}
return null;
}
/**
* 球体範囲内の全Splatを検索
*/
function findSplatsInSphere(center, radius, filteredGs) {
const indicesInSphere = [];
const radiusSquared = radius * radius;
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];
const dx = x - center.x;
const dy = y - center.y;
const dz = z - center.z;
const distSquared = dx * dx + dy * dy + dz * dz;
if (distSquared <= radiusSquared) {
indicesInSphere.push(i);
}
}
console.log('[findSplatsInSphere] Found', indicesInSphere.length, 'splats within radius', radius.toFixed(2), 'm');
return indicesInSphere;
}
/**
* ブラシ半径内の全Splatを返す
*/
function findNearestSplatWithRadius(mouseX, mouseY, camera, filteredGs, brushRadius) {
const canvas = renderer.domElement;
const mousePixelX = (mouseX + 1) * canvas.width / 2;
const mousePixelY = (-mouseY + 1) * canvas.height / 2;
const affectedIndices = [];
const worldPos = new THREE.Vector3();
const screenPos = new THREE.Vector3();
for (let i = 0; i < filteredGs.splatCount; i++) {
worldPos.x = filteredGs.centers0[i * 3 + 0];
worldPos.y = filteredGs.centers0[i * 3 + 1];
worldPos.z = filteredGs.centers0[i * 3 + 2];
screenPos.copy(worldPos);
screenPos.project(camera);
if (screenPos.z > 1) continue;
const screenPixelX = (screenPos.x + 1) * canvas.width / 2;
const screenPixelY = (-screenPos.y + 1) * canvas.height / 2;
const dx = screenPixelX - mousePixelX;
const dy = screenPixelY - mousePixelY;
const screenDist = Math.sqrt(dx * dx + dy * dy);
if (screenDist < brushRadius) {
affectedIndices.push(i);
}
}
return affectedIndices.length > 0 ? { indices: affectedIndices } : null;
}
/**
* ペイントモード用: マウスパスに沿ってSplatを塗る
*/
function findSplatsAlongMousePath(mouseX, mouseY, lastMouseX, lastMouseY, camera, filteredGs, brushRadius = 30) {
const affectedSplats = new Set();
const steps = 5;
for (let step = 0; step <= steps; step++) {
const t = step / steps;
const interpX = lastMouseX + (mouseX - lastMouseX) * t;
const interpY = lastMouseY + (mouseY - lastMouseY) * t;
const result = findNearestSplatWithRadius(interpX, interpY, camera, filteredGs, brushRadius);
if (result && result.indices) {
result.indices.forEach(idx => affectedSplats.add(idx));
}
}
return Array.from(affectedSplats);
}
/**
* ペイント処理を実行
*/
function handlePaintAtPosition(mouseX, mouseY) {
const result = findNearestSplatWithRadius(mouseX, mouseY, camera, filteredGs, 30);
if (result && result.indices.length > 0) {
applyAssignmentToIndices(result.indices, selectedTarget, paintModeEraser);
} else {
console.log('[Paint] No splats found under cursor');
}
}
// ========================================
// マウスイベント処理
// ========================================
const raycaster = new THREE.Raycaster();
const mouse = new THREE.Vector2();
let lastPaintMouseX = null;
let lastPaintMouseY = null;
////helper関数挿入 終了
// ========================================
// 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 = '<div style="color: #888;">No assignments yet</div>';
} else {
listEl.innerHTML = entries.map(([name, indices]) =>
`<div style="margin: 5px 0;">
<strong style="color: #4CAF50;">${name}</strong>: ${indices.length} splats
</div>`
).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
// ========================================
//////挿入箇所start
// ========================================
// 改善されたスプラット選択機能
// setupBoneAssignment関数内のマウスクリック処理を置き換えてください
// ========================================
/**
* 2D画面座標から最も近い3D Splatを検索
* @param {number} mouseX - 正規化されたマウスX座標 (-1 to 1)
* @param {number} mouseY - 正規化されたマウスY座標 (-1 to 1)
* @param {THREE.Camera} camera - カメラオブジェクト
* @param {Object} filteredGs - Gaussian Splat データ
* @param {number} maxScreenDistance - 最大許容画面距離(ピクセル、デフォルト50px)
* @returns {Object|null} { index, screenDistance, worldDistance } or null
*/
/**
* 球体範囲内の全Splatを検索
* @param {THREE.Vector3} center - 球の中心座標
* @param {number} radius - 球の半径
* @param {Object} filteredGs - Gaussian Splat データ
* @returns {Array<number>} Splat インデックスの配列
*/
/**
* ペイントモード用: マウスパスに沿ってSplatを塗る
* @param {number} mouseX - 正規化マウスX
* @param {number} mouseY - 正規化マウスY
* @param {number} lastMouseX - 前のマウスX
* @param {number} lastMouseY - 前のマウスY
* @param {THREE.Camera} camera
* @param {Object} filteredGs
* @param {number} brushRadius - ブラシ半径(ピクセル、デフォルト30px)
* @returns {Array<number>} 影響を受けたSplatインデックス
*/
/**
* ブラシ半径内の全Splatを返す
* @param {number} mouseX - 正規化マウスX
* @param {number} mouseY - 正規化マウスY
* @param {THREE.Camera} camera
* @param {Object} filteredGs
* @param {number} brushRadius - ブラシ半径(ピクセル)
* @returns {Object|null} { indices: Array<number> } or null
*/
// ========================================
// マウスクリック/ドラッグイベント処理の改善例
// ========================================
// マウスダウンイベント
renderer.domElement.addEventListener('mousedown', (event) => {
if (!isPaintMode || !selectedTarget) return;
isPainting = true;
paintModeEraser = event.shiftKey;
// マウス座標を正規化
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;
lastPaintMouseX = mouse.x;
lastPaintMouseY = mouse.y;
// 最初のクリック位置でペイント
handlePaintAtPosition(mouse.x, mouse.y);
});
// マウスムーブイベント(ドラッグ中)
renderer.domElement.addEventListener('mousemove', (event) => {
if (!isPainting || !isPaintMode) 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;
// パスに沿ってペイント
const affectedIndices = findSplatsAlongMousePath(
mouse.x, mouse.y,
lastPaintMouseX, lastPaintMouseY,
camera, filteredGs,
30 // ブラシ半径30px
);
if (affectedIndices.length > 0) {
applyAssignmentToIndices(affectedIndices, selectedTarget, paintModeEraser);
}
lastPaintMouseX = mouse.x;
lastPaintMouseY = mouse.y;
});
// マウスアップイベント
renderer.domElement.addEventListener('mouseup', () => {
isPainting = false;
lastPaintMouseX = null;
lastPaintMouseY = null;
});
// ========================================
// 球体選択モード(元のコード互換)
// ========================================
if (selectSphereBtn) {
selectSphereBtn.addEventListener('click', () => {
if (!selectedTarget) {
alert('Please select a target bone or group first!');
return;
}
selectionMode = 'sphere';
console.log('[Sphere Selection] Mode activated, radius:', selectionRadius, 'm');
console.log('[Sphere Selection] Click on a splat to select all nearby splats');
// One-time click listener
const onSphereClick = (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;
// ⭐ 改善: 最も近いsplatを見つける
const nearestResult = findNearestSplat(mouse.x, mouse.y, camera, filteredGs, 100);
if (!nearestResult) {
alert('No splat found near click. Please click closer to the object.');
renderer.domElement.removeEventListener('click', onSphereClick);
selectionMode = null;
return;
}
const centerIdx = nearestResult.index;
// 中心点の座標
const centerX = filteredGs.centers0[centerIdx * 3 + 0];
const centerY = filteredGs.centers0[centerIdx * 3 + 1];
const centerZ = filteredGs.centers0[centerIdx * 3 + 2];
const center = new THREE.Vector3(centerX, centerY, centerZ);
console.log('[Sphere Selection] Center splat:', centerIdx, 'at', center);
// 球体範囲内のsplatを検索
const indicesInSphere = findSplatsInSphere(center, selectionRadius, filteredGs);
if (indicesInSphere.length === 0) {
alert('No splats found in sphere. Try increasing the radius.');
renderer.domElement.removeEventListener('click', onSphereClick);
selectionMode = null;
return;
}
// 割り当てを実行
applyAssignmentToIndices(indicesInSphere, selectedTarget, false);
// 履歴に記録
assignmentData.history.push({
action: 'sphere_select',
indices: [...indicesInSphere],
target: selectedTarget
});
console.log('[Sphere Selection] Completed:', indicesInSphere.length, 'splats assigned');
renderer.domElement.removeEventListener('click', onSphereClick);
selectionMode = null;
};
renderer.domElement.addEventListener('click', onSphereClick);
});
}
console.log('[setupBoneAssignment] ✓ Improved splat selection system initialized');
console.log('[setupBoneAssignment] Features:');
console.log(' - Finds nearest splat within 50px (adjustable)');
console.log(' - Paint mode with drag support');
console.log(' - Smooth brush strokes with interpolation');
console.log(' - Sphere selection with improved center detection');
///////挿入箇所end
// ========================================
// ⭐ Camera Controls Setup
// ========================================
const cameraControls = setupCameraControls(camera, renderer);
console.log('[setupBoneAssignment] Camera controls initialized');
// ========================================
// Camera Lock Setup (完全版)
// ========================================
/////ここから
// ========================================
// Camera Lock Setup の修正版
// Line 2479-2562 付近を以下に置き換えてください
// ========================================
console.log('[setupBoneAssignment] Setting up camera lock...');
const cameraLockBtn = document.getElementById('camera-lock-btn');
if (!cameraLockBtn) {
console.error('[setupBoneAssignment] ❌ Camera lock button NOT FOUND!');
} else {
console.log('[setupBoneAssignment] ✓ Camera lock button found');
// カメラロック切り替え関数
function toggleCameraLock() {
// グローバル状態を反転
window.cameraLockState.locked = !window.cameraLockState.locked;
const isLocked = window.cameraLockState.locked;
console.log('');
console.log('═══════════════════════════════════════════════');
console.log(' CAMERA LOCK TOGGLE');
console.log('═══════════════════════════════════════════════');
console.log('New state:', isLocked ? '🔒 LOCKED' : '🔓 UNLOCKED');
if (isLocked) {
console.log('Locking camera...');
// OrbitControlsを無効化
if (cameraControls && cameraControls.controls) {
cameraControls.controls.enabled = false;
console.log(' ✓ OrbitControls.enabled = false');
}
// ⭐⭐⭐ ボタンのテキストとスタイルを更新 ⭐⭐⭐
cameraLockBtn.textContent = '🔒 Camera Locked (Click to Unlock)';
cameraLockBtn.style.background = '#4CAF50'; // 緑色に変更
console.log('✅ Camera locked');
console.log('ℹ️ Try to rotate the camera with mouse - it should NOT move');
console.log('ℹ️ You can still click to paint');
} else {
console.log('Unlocking camera...');
// OrbitControlsを有効化
if (cameraControls && cameraControls.controls) {
cameraControls.controls.enabled = true;
console.log(' ✓ OrbitControls.enabled = true');
}
// ⭐⭐⭐ ボタンのテキストとスタイルを更新 ⭐⭐⭐
cameraLockBtn.textContent = '🔓 Camera Unlocked (Can Rotate)';
cameraLockBtn.style.background = '#9C27B0'; // 元の紫色に戻す
console.log('✅ Camera unlocked');
console.log('ℹ️ Camera can now be rotated with mouse');
}
// デバッグ情報を出力
console.log('─────────────────────────────────────────────');
console.log('Current state:');
console.log(' window.cameraLockState.locked:', window.cameraLockState.locked);
console.log(' cameraControls exists:', !!cameraControls);
if (cameraControls && cameraControls.controls) {
console.log(' cameraControls.controls.enabled:', cameraControls.controls.enabled);
}
console.log(' Button text:', cameraLockBtn.textContent);
console.log('═══════════════════════════════════════════════');
console.log('');
}
// ✅ ボタンのクリックイベントを設定
cameraLockBtn.addEventListener('click', toggleCameraLock);
console.log('[setupBoneAssignment] ✓ Camera lock button configured');
console.log('[setupBoneAssignment] Initial state: 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
// ========================================
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 関数の終了