|
|
|
|
|
|
|
|
|
|
|
|
|
|
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'; |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
import { OrbitControls } from '../../lib/OrbitControls.js'; |
|
|
|
|
|
console.log('[preprocess_manual.js] ===== MODULE LOADING ====='); |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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] } |
|
|
] |
|
|
}; |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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 }; |
|
|
} |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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); |
|
|
|
|
|
|
|
|
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); |
|
|
} |
|
|
} |
|
|
}; |
|
|
} |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
function filterSplatsByBox(plyData, boxSize, boxPosition, boxRotation = { x: 0, y: 0, z: 0 }) { |
|
|
console.log('[filterSplatsByBox] ===== FILTERING START ====='); |
|
|
console.log('[filterSplatsByBox] Input parameters:'); |
|
|
console.log(' Box Size:', boxSize); |
|
|
console.log(' Box Position:', boxPosition); |
|
|
console.log(' Box Rotation (radians):', boxRotation); |
|
|
console.log(' Box Rotation (degrees):', { |
|
|
x: (boxRotation.x * 180 / Math.PI).toFixed(1) + '°', |
|
|
y: (boxRotation.y * 180 / Math.PI).toFixed(1) + '°', |
|
|
z: (boxRotation.z * 180 / Math.PI).toFixed(1) + '°' |
|
|
}); |
|
|
console.log(' Total input vertices:', plyData.vertices.length); |
|
|
|
|
|
|
|
|
const halfX = boxSize.x / 2; |
|
|
const halfY = boxSize.y / 2; |
|
|
const halfZ = boxSize.z / 2; |
|
|
|
|
|
|
|
|
const epsilon = 0.01; |
|
|
|
|
|
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++; |
|
|
} |
|
|
|
|
|
|
|
|
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)`); |
|
|
}); |
|
|
} |
|
|
|
|
|
|
|
|
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; |
|
|
} |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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); |
|
|
} |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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); |
|
|
} |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
let activeKeys = []; |
|
|
|
|
|
|
|
|
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], |
|
|
]; |
|
|
} |
|
|
|
|
|
|
|
|
function updateCameraFromKeys(camera, cameraControls) { |
|
|
if (activeKeys.length === 0) return; |
|
|
|
|
|
|
|
|
let inv = invert4(camera.matrixWorld.elements); |
|
|
if (!inv) return; |
|
|
|
|
|
const shiftKey = activeKeys.includes("ShiftLeft") || activeKeys.includes("ShiftRight"); |
|
|
|
|
|
|
|
|
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); |
|
|
} |
|
|
|
|
|
|
|
|
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); |
|
|
} |
|
|
|
|
|
|
|
|
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); |
|
|
} |
|
|
|
|
|
|
|
|
const newMatrix = invert4(inv); |
|
|
if (newMatrix) { |
|
|
camera.matrix.fromArray(newMatrix); |
|
|
camera.matrix.decompose(camera.position, camera.quaternion, camera.scale); |
|
|
camera.updateMatrixWorld(true); |
|
|
|
|
|
|
|
|
if (cameraControls && cameraControls.controls) { |
|
|
cameraControls.controls.enabled = false; |
|
|
setTimeout(() => { |
|
|
if (cameraControls && cameraControls.controls) { |
|
|
cameraControls.controls.enabled = true; |
|
|
} |
|
|
}, 100); |
|
|
} |
|
|
} |
|
|
} |
|
|
|
|
|
|
|
|
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 = []; |
|
|
}); |
|
|
} |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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...'); |
|
|
|
|
|
|
|
|
const parser = new PLYParser(); |
|
|
let loadingSpinner = new DropInViewer().viewer.loadingSpinner; |
|
|
const task = loadingSpinner.addTask('Loading PLY...'); |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
parser.parsePLY(gsPath, true).then((plyData) => { |
|
|
console.log('[preprocessManual] PLY loaded:', plyData.vertices.length, 'vertices'); |
|
|
loadingSpinner.removeTask(task); |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
console.log('[preprocessManual] ===== ANALYZING PLY COORDINATE SYSTEM ====='); |
|
|
|
|
|
|
|
|
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 } |
|
|
}; |
|
|
} |
|
|
|
|
|
|
|
|
const pcaResult = computePCA(plyData.vertices); |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
console.log('[preprocessManual] ===== PLY DATA LOADED ====='); |
|
|
console.log('[preprocessManual] PLY data is in CAMERA coordinate space'); |
|
|
console.log(' Total vertices:', plyData.vertices.length); |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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)'); |
|
|
|
|
|
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) |
|
|
}); |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
function worldToCameraSpace(worldPos, camera) { |
|
|
const cameraPos = worldPos.clone(); |
|
|
|
|
|
|
|
|
camera.updateMatrixWorld(); |
|
|
|
|
|
|
|
|
|
|
|
cameraPos.applyMatrix4(camera.matrixWorldInverse); |
|
|
|
|
|
return cameraPos; |
|
|
} |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
function transformBoxToCameraSpace(worldBox, camera) { |
|
|
const { min, max } = worldBox; |
|
|
|
|
|
|
|
|
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)); |
|
|
|
|
|
|
|
|
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'); |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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); |
|
|
|
|
|
|
|
|
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; |
|
|
} |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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; |
|
|
|
|
|
|
|
|
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; |
|
|
} |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
function filterWithWorldBox(plyData, worldBox, camera, scene) { |
|
|
console.log('[filterWithWorldBox] ===== COMPLETE FILTERING PROCESS ====='); |
|
|
|
|
|
|
|
|
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); |
|
|
|
|
|
|
|
|
console.log('[filterWithWorldBox] Step 2: Display box in camera space'); |
|
|
|
|
|
const boxHelper = createCameraSpaceBox(cameraBox, scene); |
|
|
|
|
|
console.log('[filterWithWorldBox] ✓ Box displayed'); |
|
|
|
|
|
|
|
|
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 |
|
|
}; |
|
|
} |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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('═══════════════════════════════════════════════════════'); |
|
|
|
|
|
|
|
|
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) |
|
|
}; |
|
|
|
|
|
|
|
|
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); |
|
|
|
|
|
|
|
|
console.log('[CONFIRM] Transforming box to camera space...'); |
|
|
|
|
|
const cameraBox = transformBoxToCameraSpace(worldBox, camera); |
|
|
|
|
|
console.log('[CONFIRM] Camera box (transformed):', cameraBox); |
|
|
|
|
|
|
|
|
console.log('[CONFIRM] Displaying box in camera space...'); |
|
|
|
|
|
ui.removeBoundingBox(); |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
console.log('[CONFIRM] Filtering splats in camera space...'); |
|
|
|
|
|
const filteredVertices = filterSplatsByCameraBox(plyData, cameraBox); |
|
|
|
|
|
|
|
|
console.log('═══════════════════════════════════════════════════════'); |
|
|
console.log(' BOX FILTERING COMPLETE'); |
|
|
console.log('═══════════════════════════════════════════════════════'); |
|
|
|
|
|
|
|
|
|
|
|
}); |
|
|
} |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
GVRM.initGS(gsPath, undefined, undefined, scene).then((gs) => { |
|
|
console.log('[preprocessManual] GS initialized'); |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
if (window.plyAlignmentApplied && window.plyAlignmentMatrix) { |
|
|
console.log('[preprocessManual] Applying alignment transform to GS display...'); |
|
|
|
|
|
const gsScene = gs.viewer.splatMesh.scenes[0]; |
|
|
|
|
|
|
|
|
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'); |
|
|
} |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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'); |
|
|
} |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
setupKeyboardControls(); |
|
|
console.log('[preprocessManual] Keyboard controls initialized'); |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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); |
|
|
} |
|
|
|
|
|
|
|
|
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(); |
|
|
} |
|
|
} |
|
|
|
|
|
|
|
|
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'); |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
const cleanupAnimation = () => { |
|
|
if (animationId) { |
|
|
cancelAnimationFrame(animationId); |
|
|
animationId = null; |
|
|
} |
|
|
}; |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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 |
|
|
}; |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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 }; |
|
|
|
|
|
|
|
|
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); |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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]; |
|
|
|
|
|
|
|
|
ui.createBoundingBox(boxSize, boxPosition, boxRotation); |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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'); |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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); |
|
|
}); |
|
|
} |
|
|
}; |
|
|
|
|
|
|
|
|
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); |
|
|
}); |
|
|
} |
|
|
}; |
|
|
|
|
|
|
|
|
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); |
|
|
}); |
|
|
} |
|
|
}; |
|
|
|
|
|
|
|
|
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(); |
|
|
}); |
|
|
} |
|
|
}; |
|
|
|
|
|
|
|
|
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'); |
|
|
|
|
|
|
|
|
const resetAllBtn = document.getElementById('reset-all-btn'); |
|
|
if (resetAllBtn) { |
|
|
resetAllBtn.addEventListener('click', () => { |
|
|
|
|
|
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'; |
|
|
|
|
|
|
|
|
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 |
|
|
}; |
|
|
|
|
|
|
|
|
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); |
|
|
|
|
|
|
|
|
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('═══════════════════════════════════════════════════════'); |
|
|
|
|
|
|
|
|
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) |
|
|
}; |
|
|
|
|
|
|
|
|
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); |
|
|
|
|
|
|
|
|
|
|
|
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(); |
|
|
|
|
|
|
|
|
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 }; |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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) { |
|
|
|
|
|
ui.showPositionAdjustment(); |
|
|
return; |
|
|
} |
|
|
} |
|
|
|
|
|
|
|
|
} else { |
|
|
console.log('[STEP 3] No PLY offset to apply'); |
|
|
} |
|
|
|
|
|
ui.hidePositionAdjustment(); |
|
|
ui.setStatus('Filtering splats with bounding box...'); |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
console.log('[STEP 4] ⭐ Transforming Box coordinates to GS local space'); |
|
|
|
|
|
|
|
|
const gsScene = gs.viewer.splatMesh.scenes[0]; |
|
|
gsScene.updateMatrixWorld(true); |
|
|
|
|
|
|
|
|
const boxWorldPosition = new THREE.Vector3( |
|
|
currentBoxPosition.x, |
|
|
currentBoxPosition.y, |
|
|
currentBoxPosition.z |
|
|
); |
|
|
|
|
|
|
|
|
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) |
|
|
}); |
|
|
|
|
|
|
|
|
const boxRotationEuler = new THREE.Euler( |
|
|
currentBoxRotation.x, |
|
|
currentBoxRotation.y, |
|
|
currentBoxRotation.z |
|
|
); |
|
|
const boxRotationMatrix = new THREE.Matrix4().makeRotationFromEuler(boxRotationEuler); |
|
|
|
|
|
|
|
|
const gsRotationMatrix = new THREE.Matrix4().extractRotation(gsScene.matrixWorld); |
|
|
|
|
|
|
|
|
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) + '°' |
|
|
}); |
|
|
|
|
|
|
|
|
const filteredVertices = filterSplatsByBox( |
|
|
plyData, |
|
|
currentBoxSize, |
|
|
{ |
|
|
x: boxLocalPosition.x, |
|
|
y: boxLocalPosition.y, |
|
|
z: boxLocalPosition.z |
|
|
}, |
|
|
{ |
|
|
x: combinedRotationEuler.x, |
|
|
y: combinedRotationEuler.y, |
|
|
z: combinedRotationEuler.z |
|
|
} |
|
|
); |
|
|
|
|
|
|
|
|
|
|
|
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; |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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'); |
|
|
|
|
|
|
|
|
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 |
|
|
}); |
|
|
}); |
|
|
} |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
}); |
|
|
}); |
|
|
}); |
|
|
|
|
|
} catch (error) { |
|
|
console.error('[preprocessManual] Error:', error); |
|
|
reject(error); |
|
|
} |
|
|
}); |
|
|
} |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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); |
|
|
|
|
|
|
|
|
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; |
|
|
} |
|
|
|
|
|
|
|
|
|
|
|
let selectionRadius = calculateOptimalRadius(filteredGs); |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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'); |
|
|
|
|
|
|
|
|
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); |
|
|
|
|
|
|
|
|
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); |
|
|
|
|
|
|
|
|
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 isPaintMode = false; |
|
|
let isPainting = false; |
|
|
let paintModeEraser = false; |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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'); |
|
|
} |
|
|
} |
|
|
|
|
|
|
|
|
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); |
|
|
}); |
|
|
} |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
if (boneSelector) { |
|
|
boneSelector.addEventListener('change', (e) => { |
|
|
selectedTarget = e.target.value; |
|
|
console.log('[setupBoneAssignment] Selected target:', selectedTarget); |
|
|
}); |
|
|
} |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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'); |
|
|
}); |
|
|
} |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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); |
|
|
}); |
|
|
} |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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'); |
|
|
} |
|
|
}); |
|
|
} |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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}`; |
|
|
} |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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(); |
|
|
} |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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; |
|
|
} |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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; |
|
|
} |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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; |
|
|
} |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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; |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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 + '%'; |
|
|
|
|
|
|
|
|
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(); |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
if (selectionRadiusSlider && selectionRadiusValue) { |
|
|
selectionRadiusSlider.addEventListener('input', (e) => { |
|
|
selectionRadius = parseFloat(e.target.value); |
|
|
selectionRadiusValue.textContent = selectionRadius.toFixed(2); |
|
|
}); |
|
|
} |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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 |
|
|
); |
|
|
|
|
|
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'); |
|
|
|
|
|
|
|
|
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; |
|
|
|
|
|
|
|
|
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); |
|
|
|
|
|
|
|
|
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'); |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
const cameraControls = setupCameraControls(camera, renderer); |
|
|
console.log('[setupBoneAssignment] Camera controls initialized'); |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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...'); |
|
|
|
|
|
|
|
|
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...'); |
|
|
|
|
|
|
|
|
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'); |
|
|
} |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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; |
|
|
} |
|
|
|
|
|
|
|
|
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; |
|
|
} |
|
|
|
|
|
|
|
|
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) { |
|
|
|
|
|
if (isPaintMode || assignmentData.splatBoneIndices[i] < 0) { |
|
|
|
|
|
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++; |
|
|
|
|
|
|
|
|
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] = []; |
|
|
} |
|
|
|
|
|
|
|
|
assignmentData.boneAssignments[displayName] = |
|
|
assignmentData.boneAssignments[displayName].concat(newlyAssigned); |
|
|
|
|
|
|
|
|
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'); |
|
|
} |
|
|
} |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
function eraseSplatsInSphere(center, radius) { |
|
|
let erasedCount = 0; |
|
|
const erased = []; |
|
|
|
|
|
for (let i = 0; i < filteredGs.splatCount; 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(center); |
|
|
|
|
|
if (distance <= radius) { |
|
|
assignmentData.splatBoneIndices[i] = -1; |
|
|
erased.push(i); |
|
|
erasedCount++; |
|
|
|
|
|
|
|
|
filteredGs.colors[i * 4 + 0] = 128; |
|
|
filteredGs.colors[i * 4 + 1] = 128; |
|
|
filteredGs.colors[i * 4 + 2] = 128; |
|
|
} |
|
|
} |
|
|
|
|
|
if (erasedCount > 0) { |
|
|
|
|
|
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); |
|
|
|
|
|
|
|
|
updateStats(); |
|
|
|
|
|
console.log(`[setupBoneAssignment] Erased ${erasedCount} splats`); |
|
|
} |
|
|
} |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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) { |
|
|
|
|
|
eraseSplatsInSphere(hitPoint, selectionRadius, true); |
|
|
} else { |
|
|
|
|
|
assignSplatsInSphere(hitPoint, selectionRadius, selectedTarget, true); |
|
|
} |
|
|
} |
|
|
} |
|
|
|
|
|
function onMouseDown(event) { |
|
|
if (!isPaintMode) return; |
|
|
if (!selectedTarget) { |
|
|
alert('Please select a target first!'); |
|
|
return; |
|
|
} |
|
|
|
|
|
|
|
|
paintModeEraser = event.shiftKey; |
|
|
isPainting = true; |
|
|
|
|
|
|
|
|
paintAtMousePosition(event); |
|
|
} |
|
|
|
|
|
function onMouseMove(event) { |
|
|
if (!isPaintMode || !isPainting) return; |
|
|
|
|
|
paintAtMousePosition(event); |
|
|
} |
|
|
|
|
|
function onMouseUp(event) { |
|
|
if (!isPaintMode) return; |
|
|
isPainting = false; |
|
|
} |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
function onCanvasClick(event) { |
|
|
|
|
|
if (isPaintMode) { |
|
|
return; |
|
|
} |
|
|
|
|
|
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); |
|
|
} |
|
|
} |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
renderer.domElement.addEventListener('mousedown', onMouseDown); |
|
|
renderer.domElement.addEventListener('mousemove', onMouseMove); |
|
|
renderer.domElement.addEventListener('mouseup', onMouseUp); |
|
|
renderer.domElement.addEventListener('click', onCanvasClick); |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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'); |
|
|
}); |
|
|
} |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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); |
|
|
|
|
|
|
|
|
updateStats(); |
|
|
|
|
|
console.log(`[setupBoneAssignment] Undone ${indices.length} splats from ${targetName}`); |
|
|
}); |
|
|
} |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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); |
|
|
|
|
|
|
|
|
updateStats(); |
|
|
|
|
|
console.log('[setupBoneAssignment] Reset all assignments'); |
|
|
}); |
|
|
} |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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 { |
|
|
|
|
|
|
|
|
|
|
|
console.log('[setupBoneAssignment] Creating PMC...'); |
|
|
const { pmc, capsuleBoneIndex } = GVRMUtils.getPointsMeshCapsules(character); |
|
|
GVRMUtils.addPMC(scene, pmc); |
|
|
GVRMUtils.visualizePMC(pmc, false); |
|
|
|
|
|
|
|
|
gvrm.pmc = pmc; |
|
|
|
|
|
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); |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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); |
|
|
} |
|
|
}); |
|
|
|
|
|
|
|
|
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); |
|
|
|
|
|
updateStats(); |
|
|
} |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
ui.setStatus('Setting bone assignments...'); |
|
|
filteredGs.splatBoneIndices = assignmentData.splatBoneIndices; |
|
|
|
|
|
console.log('[setupBoneAssignment] Bone assignments set:', filteredGs.splatBoneIndices.length); |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
ui.setStatus('Mapping vertices to bones...'); |
|
|
const skinnedMesh = character.currentVrm.scene.children[character.skinnedMeshIndex]; |
|
|
const position = skinnedMesh.geometry.getAttribute('position'); |
|
|
|
|
|
const boneVertexIndices = {}; |
|
|
|
|
|
|
|
|
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...'); |
|
|
|
|
|
|
|
|
|
|
|
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; |
|
|
|
|
|
|
|
|
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`); |
|
|
} |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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] || []; |
|
|
|
|
|
|
|
|
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; |
|
|
} |
|
|
|
|
|
|
|
|
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.'); |
|
|
} |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
console.log('[setupBoneAssignment] Updating PMC...'); |
|
|
gvrm.updatePMC(); |
|
|
console.log('[setupBoneAssignment] PMC updated'); |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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); |
|
|
|
|
|
|
|
|
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 =========='); |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
console.log('[setupBoneAssignment] ===== CALCULATING GVRM TRANSFORMS ====='); |
|
|
ui.setStatus('Calculating transforms...'); |
|
|
|
|
|
try { |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
console.log('[setupBoneAssignment] Step 1: Calculate GS transform'); |
|
|
|
|
|
|
|
|
const gsScene = filteredGs.viewer.splatMesh.scenes[0]; |
|
|
gsScene.updateMatrixWorld(true); |
|
|
|
|
|
|
|
|
const gsWorldMatrix = gsScene.matrixWorld.clone(); |
|
|
|
|
|
|
|
|
const gsWorldPosition = new THREE.Vector3(); |
|
|
gsWorldPosition.setFromMatrixPosition(gsWorldMatrix); |
|
|
|
|
|
console.log('[setupBoneAssignment] GS World Position:', { |
|
|
x: gsWorldPosition.x, |
|
|
y: gsWorldPosition.y, |
|
|
z: gsWorldPosition.z |
|
|
}); |
|
|
|
|
|
|
|
|
const gsWorldScale = new THREE.Vector3(); |
|
|
gsWorldScale.setFromMatrixScale(gsWorldMatrix); |
|
|
|
|
|
console.log('[setupBoneAssignment] GS World Scale:', { |
|
|
x: gsWorldScale.x, |
|
|
y: gsWorldScale.y, |
|
|
z: gsWorldScale.z |
|
|
}); |
|
|
|
|
|
|
|
|
const rotationMatrix = gsWorldMatrix.clone(); |
|
|
rotationMatrix.scale(new THREE.Vector3( |
|
|
1 / gsWorldScale.x, |
|
|
1 / gsWorldScale.y, |
|
|
1 / gsWorldScale.z |
|
|
)); |
|
|
|
|
|
|
|
|
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 |
|
|
}); |
|
|
|
|
|
|
|
|
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'); |
|
|
} |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
filteredGs.gsQuaternion = [ |
|
|
gsWorldQuaternion.x, |
|
|
gsWorldQuaternion.y, |
|
|
gsWorldQuaternion.z, |
|
|
gsWorldQuaternion.w |
|
|
]; |
|
|
|
|
|
filteredGs.gsPosition = [ |
|
|
gsWorldPosition.x, |
|
|
gsWorldPosition.y, |
|
|
gsWorldPosition.z |
|
|
]; |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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; |
|
|
|
|
|
|
|
|
character.currentVrm.scene.updateMatrixWorld(true); |
|
|
|
|
|
|
|
|
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); |
|
|
|
|
|
|
|
|
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); |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
console.log('[setupBoneAssignment] Step 3: Update boneOperations'); |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
console.log('[setupBoneAssignment] Current boneOperations:', gvrm.boneOperations); |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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'); |
|
|
|
|
|
|
|
|
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; |
|
|
} |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
console.log('[setupBoneAssignment] ===== SAVING MATRIXWORLD0 ====='); |
|
|
ui.setStatus('Saving bone matrices...'); |
|
|
|
|
|
try { |
|
|
const allBoneNames = Object.keys(humanBones); |
|
|
console.log('[setupBoneAssignment] Saving matrixWorld0 for', allBoneNames.length, 'bones'); |
|
|
|
|
|
|
|
|
if (!gvrm.matrixWorld0) { |
|
|
gvrm.matrixWorld0 = {}; |
|
|
} |
|
|
|
|
|
|
|
|
let savedCount = 0; |
|
|
for (const boneName of allBoneNames) { |
|
|
const bone = humanBones[boneName]; |
|
|
|
|
|
|
|
|
if (bone && bone.node && bone.node.matrixWorld) { |
|
|
|
|
|
gvrm.matrixWorld0[boneName] = bone.node.matrixWorld.clone(); |
|
|
savedCount++; |
|
|
|
|
|
|
|
|
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)); |
|
|
|
|
|
|
|
|
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; |
|
|
} |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
console.log('[setupBoneAssignment] ===== TRANSFERRING MATRIXWORLD0 TO FILTEREDGS ====='); |
|
|
|
|
|
|
|
|
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'); |
|
|
} |
|
|
|
|
|
|
|
|
const matrixWorld0Serializable = {}; |
|
|
|
|
|
for (const [boneName, matrix] of Object.entries(gvrm.matrixWorld0)) { |
|
|
|
|
|
if (matrix && matrix.elements) { |
|
|
|
|
|
matrixWorld0Serializable[boneName] = matrix.elements.slice(); |
|
|
} else { |
|
|
console.warn(`[setupBoneAssignment] ⚠️ Invalid matrix for ${boneName}:`, matrix); |
|
|
} |
|
|
} |
|
|
|
|
|
|
|
|
filteredGs.matrixWorld0 = matrixWorld0Serializable; |
|
|
|
|
|
console.log('[setupBoneAssignment] ✓ Transferred matrixWorld0 to filteredGs'); |
|
|
console.log('[setupBoneAssignment] ✓ matrixWorld0 bone count:', |
|
|
Object.keys(filteredGs.matrixWorld0).length); |
|
|
|
|
|
|
|
|
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'); |
|
|
} |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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); |
|
|
|
|
|
|
|
|
if (!gvrm.customType) { |
|
|
console.warn('[setupBoneAssignment] ⚠️ customType was lost, resetting to "1"'); |
|
|
gvrm.customType = "1"; |
|
|
} |
|
|
|
|
|
|
|
|
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'); |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
console.log('[setupBoneAssignment] ===== DATA VALIDATION ====='); |
|
|
|
|
|
|
|
|
console.log('1. Splat counts:'); |
|
|
console.log(' - Original PLY:', originalPlyData.vertices.length); |
|
|
console.log(' - After box filter:', plyData.vertices.length); |
|
|
console.log(' - In filteredGs:', filteredGs.splatCount); |
|
|
|
|
|
|
|
|
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); |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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)); |
|
|
|
|
|
|
|
|
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)}%)`); |
|
|
|
|
|
|
|
|
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 ====='); |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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! ✓'); |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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); |
|
|
} |
|
|
}); |
|
|
} |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
} catch (error) { |
|
|
console.error('[setupBoneAssignment] Error:', error); |
|
|
ui.setStatus('Error: ' + error.message); |
|
|
} |
|
|
|
|
|
}); |
|
|
} |