554 lines
23 KiB
JavaScript
554 lines
23 KiB
JavaScript
import * as THREE from 'three';
|
|
import { GLTFLoader } from 'three/examples/jsm/loaders/GLTFLoader.js';
|
|
import { VRMLoaderPlugin, VRMUtils } from '@pixiv/three-vrm';
|
|
import { VRMAnimationLoaderPlugin, createVRMAnimationClip } from '@pixiv/three-vrm-animation';
|
|
|
|
/* ============ HEL-702 独立3D角色验证页 ============
|
|
* 环境状态(time/weather) 与 角色状态(outfit/action/gaze) 完全分离。
|
|
* 天气/时间切换不触碰角色骨架 —— assertPosePreserved() 可程序化验证。
|
|
* ================================================== */
|
|
|
|
const params = new URLSearchParams(location.search);
|
|
const MODEL = params.get('model') || 'twist';
|
|
const modelFile = MODEL === 'seed' ? 'assets/Seed-san.vrm' : 'assets/VRM1_Constraint_Twist_Sample.vrm';
|
|
|
|
const app = {
|
|
ready: false,
|
|
state: { outfit: 'A', action: 'stand', time: 'day', weather: 'sunny', gaze: 'idle' },
|
|
stats: {},
|
|
notes: [],
|
|
};
|
|
|
|
/* ---------- renderer / scene ---------- */
|
|
const renderer = new THREE.WebGLRenderer({ antialias: true });
|
|
renderer.setSize(innerWidth, innerHeight);
|
|
renderer.setPixelRatio(Math.min(devicePixelRatio, 2));
|
|
renderer.shadowMap.enabled = true;
|
|
renderer.shadowMap.type = THREE.PCFSoftShadowMap;
|
|
document.getElementById('app').appendChild(renderer.domElement);
|
|
|
|
const scene = new THREE.Scene();
|
|
const camera = new THREE.PerspectiveCamera(30, innerWidth / innerHeight, 0.1, 50);
|
|
const CAMS = {
|
|
main: { pos: [1.35, 1.35, 2.6], look: [0, 0.9, 0] },
|
|
front: { pos: [0, 1.15, 2.3], look: [0, 0.95, 0] },
|
|
wide: { pos: [2.3, 1.7, 3.4], look: [0.1, 0.8, 0] },
|
|
closeup: { pos: [0.75, 1.15, 1.15], look: [0.05, 1.05, 0.1] },
|
|
};
|
|
function setCam(name) {
|
|
const c = CAMS[name] || CAMS.main;
|
|
camera.position.set(...c.pos);
|
|
camera.lookAt(...c.look);
|
|
}
|
|
setCam(params.get('cam') || 'main');
|
|
|
|
/* ---------- room ---------- */
|
|
const room = new THREE.Group();
|
|
scene.add(room);
|
|
const matWall = new THREE.MeshStandardMaterial({ color: 0xcfc8bd, roughness: 0.95 });
|
|
const matWall2 = new THREE.MeshStandardMaterial({ color: 0xb9b2a6, roughness: 0.95 });
|
|
const matFloor = new THREE.MeshStandardMaterial({ color: 0x8a6a4e, roughness: 0.8 });
|
|
const matWood = new THREE.MeshStandardMaterial({ color: 0xa07850, roughness: 0.7 });
|
|
|
|
const floor = new THREE.Mesh(new THREE.BoxGeometry(4.6, 0.08, 4.6), matFloor);
|
|
floor.position.y = -0.04;
|
|
floor.receiveShadow = true;
|
|
room.add(floor);
|
|
const wallBack = new THREE.Mesh(new THREE.BoxGeometry(4.6, 2.75, 0.08), matWall);
|
|
wallBack.position.set(0, 1.375, -2.3);
|
|
wallBack.receiveShadow = true;
|
|
room.add(wallBack);
|
|
const wallLeft = new THREE.Mesh(new THREE.BoxGeometry(0.08, 2.75, 4.6), matWall2);
|
|
wallLeft.position.set(-2.3, 1.375, 0);
|
|
room.add(wallLeft);
|
|
|
|
/* window opening in back wall: 4 boxes around a hole (x: cx±x/2) */
|
|
const WIN = { x: 0.62, y: 1.0, cx: 0.55, cy: 1.45 };
|
|
function wallPiece(w, h, cx, cy) {
|
|
const m = new THREE.Mesh(new THREE.BoxGeometry(w, h, 0.08), matWall);
|
|
m.position.set(cx, cy, -2.3);
|
|
m.receiveShadow = true;
|
|
room.add(m);
|
|
}
|
|
wallPiece(4.6, 2.75 - (WIN.cy + WIN.y / 2), 0, WIN.cy + WIN.y / 2 + (2.75 - (WIN.cy + WIN.y / 2)) / 2); // top
|
|
wallPiece(4.6, WIN.cy - WIN.y / 2, 0, (WIN.cy - WIN.y / 2) / 2); // bottom
|
|
wallPiece((WIN.cx - WIN.x / 2) - (-2.3), WIN.y, (-2.3 + (WIN.cx - WIN.x / 2)) / 2, WIN.cy); // left
|
|
wallPiece(2.3 - (WIN.cx + WIN.x / 2), WIN.y, (2.3 + (WIN.cx + WIN.x / 2)) / 2, WIN.cy); // right
|
|
/* window frame + glass */
|
|
const frameMat = new THREE.MeshStandardMaterial({ color: 0xf0ece4, roughness: 0.5 });
|
|
const fr1 = new THREE.Mesh(new THREE.BoxGeometry(WIN.x + 0.08, 0.05, 0.1), frameMat);
|
|
fr1.position.set(WIN.cx, WIN.cy + WIN.y / 2, -2.28);
|
|
const fr2 = fr1.clone(); fr2.position.y = WIN.cy - WIN.y / 2;
|
|
const fr3 = new THREE.Mesh(new THREE.BoxGeometry(0.05, WIN.y + 0.08, 0.1), frameMat);
|
|
fr3.position.set(WIN.cx - WIN.x / 2, WIN.cy, -2.28);
|
|
const fr4 = fr3.clone(); fr4.position.x = WIN.cx + WIN.x / 2;
|
|
const fr5 = new THREE.Mesh(new THREE.BoxGeometry(0.03, WIN.y, 0.09), frameMat);
|
|
fr5.position.set(WIN.cx, WIN.cy, -2.28);
|
|
room.add(fr1, fr2, fr3, fr4, fr5);
|
|
const skyMat = new THREE.MeshBasicMaterial({ color: 0xbcd7f0 });
|
|
const sky = new THREE.Mesh(new THREE.PlaneGeometry(7, 5), skyMat);
|
|
sky.position.set(WIN.cx, WIN.cy, -2.65);
|
|
room.add(sky);
|
|
/* distant city silhouette (dark boxes outside window) */
|
|
const cityMat = new THREE.MeshBasicMaterial({ color: 0x6f7f96 });
|
|
const city = new THREE.Group();
|
|
for (let i = 0; i < 9; i++) {
|
|
const h = 0.5 + Math.abs(Math.sin(i * 2.7)) * 1.1;
|
|
const b = new THREE.Mesh(new THREE.BoxGeometry(0.42, h, 0.2), cityMat);
|
|
b.position.set(WIN.cx - 1.6 + i * 0.42, h / 2 - 0.4, -2.5);
|
|
city.add(b);
|
|
}
|
|
room.add(city);
|
|
|
|
/* rug */
|
|
const rug = new THREE.Mesh(new THREE.CircleGeometry(0.85, 40), new THREE.MeshStandardMaterial({ color: 0x9c4f3f, roughness: 1 }));
|
|
rug.rotation.x = -Math.PI / 2;
|
|
rug.position.set(-0.55, 0.005, 0.35);
|
|
rug.receiveShadow = true;
|
|
room.add(rug);
|
|
|
|
/* desk + chair + lamp (椅面高 0.46m,坐姿按它计算) */
|
|
const chair = new THREE.Group();
|
|
const seatY = 0.46;
|
|
const seat = new THREE.Mesh(new THREE.BoxGeometry(0.44, 0.05, 0.44), matWood);
|
|
seat.position.y = seatY - 0.025;
|
|
seat.castShadow = true;
|
|
const backrest = new THREE.Mesh(new THREE.BoxGeometry(0.44, 0.5, 0.05), matWood);
|
|
backrest.position.set(0, seatY + 0.25, -0.2);
|
|
backrest.castShadow = true;
|
|
chair.add(seat, backrest);
|
|
for (const [x, z] of [[-0.18, -0.18], [0.18, -0.18], [-0.18, 0.18], [0.18, 0.18]]) {
|
|
const leg = new THREE.Mesh(new THREE.BoxGeometry(0.05, seatY - 0.05, 0.05), matWood);
|
|
leg.position.set(x, (seatY - 0.05) / 2, z);
|
|
chair.add(leg);
|
|
}
|
|
chair.position.set(0.62, 0, 0.1);
|
|
chair.rotation.y = -0.5;
|
|
room.add(chair);
|
|
|
|
const desk = new THREE.Group();
|
|
const top = new THREE.Mesh(new THREE.BoxGeometry(1.1, 0.05, 0.55), matWood);
|
|
top.position.y = 0.74;
|
|
top.castShadow = true;
|
|
desk.add(top);
|
|
for (const [x, z] of [[-0.5, -0.22], [0.5, -0.22], [-0.5, 0.22], [0.5, 0.22]]) {
|
|
const leg = new THREE.Mesh(new THREE.BoxGeometry(0.05, 0.74, 0.05), matWood);
|
|
leg.position.set(x, 0.37, z);
|
|
desk.add(leg);
|
|
}
|
|
const mug = new THREE.Mesh(new THREE.CylinderGeometry(0.045, 0.045, 0.1, 16), new THREE.MeshStandardMaterial({ color: 0xd8cfc4, roughness: 0.4 }));
|
|
mug.position.set(0.25, 0.815, 0.06);
|
|
desk.add(mug);
|
|
desk.position.set(-0.85, 0, -0.75);
|
|
desk.rotation.y = 0.35;
|
|
room.add(desk);
|
|
|
|
const lampG = new THREE.Group();
|
|
const lampStand = new THREE.Mesh(new THREE.CylinderGeometry(0.02, 0.03, 1.25, 10), new THREE.MeshStandardMaterial({ color: 0x333333, metalness: 0.7, roughness: 0.4 }));
|
|
lampStand.position.y = 0.625;
|
|
const lampShade = new THREE.Mesh(new THREE.ConeGeometry(0.14, 0.18, 16, 1, true), new THREE.MeshStandardMaterial({ color: 0xf5e6c8, roughness: 0.6, side: THREE.DoubleSide }));
|
|
lampShade.position.y = 1.3;
|
|
lampG.add(lampStand, lampShade);
|
|
lampG.position.set(1.55, 0, -1.9);
|
|
room.add(lampG);
|
|
|
|
/* book prop (read 动作时挂到右手) */
|
|
const bookG = new THREE.Group();
|
|
const bookCover = new THREE.Mesh(new THREE.BoxGeometry(0.16, 0.015, 0.22), new THREE.MeshStandardMaterial({ color: 0x8a3033, roughness: 0.6 }));
|
|
const bookPage = new THREE.Mesh(new THREE.BoxGeometry(0.145, 0.012, 0.205), new THREE.MeshStandardMaterial({ color: 0xf2ecd9, roughness: 0.9 }));
|
|
bookPage.position.y = 0.008;
|
|
bookG.add(bookCover, bookPage);
|
|
bookG.visible = false;
|
|
|
|
/* ---------- lights ---------- */
|
|
const hemi = new THREE.HemisphereLight(0xdfe8f5, 0x5a4a3a, 0.55);
|
|
scene.add(hemi);
|
|
const sun = new THREE.DirectionalLight(0xfff2dd, 2.0);
|
|
sun.position.set(3, 4, 1.5);
|
|
sun.castShadow = true;
|
|
sun.shadow.mapSize.set(1024, 1024);
|
|
sun.shadow.camera.left = -3; sun.shadow.camera.right = 3;
|
|
sun.shadow.camera.top = 3; sun.shadow.camera.bottom = -3;
|
|
scene.add(sun);
|
|
const lampLight = new THREE.PointLight(0xffc98a, 0, 4, 2);
|
|
lampLight.position.set(1.55, 1.22, -1.9);
|
|
scene.add(lampLight);
|
|
|
|
/* rain (outside window) */
|
|
const RAIN_N = 500;
|
|
const rainGeo = new THREE.BufferGeometry();
|
|
const rainPos = new Float32Array(RAIN_N * 3);
|
|
for (let i = 0; i < RAIN_N; i++) {
|
|
rainPos[i * 3] = WIN.cx - 1.8 + Math.random() * 3.6;
|
|
rainPos[i * 3 + 1] = Math.random() * 4;
|
|
rainPos[i * 3 + 2] = -2.5 - Math.random() * 0.6;
|
|
}
|
|
rainGeo.setAttribute('position', new THREE.BufferAttribute(rainPos, 3));
|
|
const rain = new THREE.Points(rainGeo, new THREE.PointsMaterial({ color: 0xaec6e8, size: 0.022, transparent: true, opacity: 0.85 }));
|
|
rain.visible = false;
|
|
scene.add(rain);
|
|
|
|
/* ---------- VRM character ---------- */
|
|
let vrm = null;
|
|
let mixer = null;
|
|
let vrmaAction = null;
|
|
let vrmaClipLen = 0;
|
|
const rawBone = (n) => vrm?.humanoid.getRawBoneNode(n) ?? null;
|
|
const normBone = (n) => vrm?.humanoid.getNormalizedBoneNode(n) ?? null;
|
|
|
|
/* outfit B: 自制占位服装(连帽衫+长裤,硬segment绑定原始骨骼) */
|
|
const outfitB = new THREE.Group();
|
|
const matPants = new THREE.MeshStandardMaterial({ color: 0x46618f, roughness: 0.85 });
|
|
const matHood = new THREE.MeshStandardMaterial({ color: 0x9aa3ad, roughness: 0.9 });
|
|
function seg(mesh, bone, pos) { mesh.position.copy(pos); mesh.castShadow = true; outfitB.add(mesh); mesh.userData.bone = bone; return mesh; }
|
|
const B = (g, m) => new THREE.Mesh(g, m);
|
|
seg(B(new THREE.BoxGeometry(0.34, 0.34, 0.2), matHood), 'chest', new THREE.Vector3(0, 0.02, 0)); // 衣身
|
|
seg(B(new THREE.BoxGeometry(0.14, 0.12, 0.14), matHood), 'neck', new THREE.Vector3(0, 0.08, -0.03)); // 领口
|
|
seg(B(new THREE.CylinderGeometry(0.055, 0.05, 0.26, 8), matHood), 'leftUpperArm', new THREE.Vector3(0, -0.1, 0)); // 袖L上
|
|
seg(B(new THREE.CylinderGeometry(0.05, 0.045, 0.24, 8), matHood), 'leftLowerArm', new THREE.Vector3(0, -0.1, 0)); // 袖L下
|
|
seg(B(new THREE.CylinderGeometry(0.055, 0.05, 0.26, 8), matHood), 'rightUpperArm', new THREE.Vector3(0, -0.1, 0)); // 袖R上
|
|
seg(B(new THREE.CylinderGeometry(0.05, 0.045, 0.24, 8), matHood), 'rightLowerArm', new THREE.Vector3(0, -0.1, 0)); // 袖R下
|
|
for (const side of ['left', 'right']) {
|
|
seg(B(new THREE.CylinderGeometry(0.085, 0.075, 0.3, 10), matPants), side + 'UpperLeg', new THREE.Vector3(0, -0.15, 0)); // 裤大腿
|
|
seg(B(new THREE.CylinderGeometry(0.07, 0.06, 0.3, 10), matPants), side + 'LowerLeg', new THREE.Vector3(0, -0.14, 0)); // 裤小腿
|
|
}
|
|
outfitB.visible = false;
|
|
scene.add(outfitB);
|
|
|
|
/* ---------- 姿势系统(normalized 骨架,目标角度平滑过渡) ---------- */
|
|
const POSES = {
|
|
stand: {
|
|
hips: { pos: null },
|
|
leftShoulder: { z: 0.04 }, rightShoulder: { z: -0.04 },
|
|
leftUpperArm: { z: -1.22, x: 0.1 }, rightUpperArm: { z: 1.22, x: 0.1 },
|
|
leftLowerArm: { z: -0.18 }, rightLowerArm: { z: 0.18 },
|
|
spine: { x: 0.02 }, neck: { x: 0.03 },
|
|
},
|
|
sit: {
|
|
leftUpperLeg: { x: -1.45 }, rightUpperLeg: { x: -1.45 },
|
|
leftLowerLeg: { x: 1.42 }, rightLowerLeg: { x: 1.42 },
|
|
leftFoot: { x: -0.02 }, rightFoot: { x: -0.02 },
|
|
spine: { x: 0.09 }, neck: { x: -0.04 },
|
|
},
|
|
read: {
|
|
leftUpperLeg: { x: -1.45 }, rightUpperLeg: { x: -1.45 },
|
|
leftLowerLeg: { x: 1.42 }, rightLowerLeg: { x: 1.42 },
|
|
leftFoot: { x: -0.02 }, rightFoot: { x: -0.02 },
|
|
spine: { x: 0.14 }, neck: { x: 0.22 },
|
|
leftShoulder: { x: -0.5 }, rightShoulder: { x: -0.5 },
|
|
leftUpperArm: { z: -0.25, y: -1.05 }, rightUpperArm: { z: 0.25, y: 1.05 },
|
|
leftLowerArm: { y: -1.1, z: -0.3 }, rightLowerArm: { y: 1.1, z: 0.3 },
|
|
},
|
|
};
|
|
const poseTargets = {}; // bone -> {quat, posOffset}
|
|
let sitOffsetY = 0;
|
|
let baseHipY = 0;
|
|
|
|
function computeTargets(name) {
|
|
const p = POSES[name] || POSES.stand;
|
|
for (const k of Object.keys(poseTargets)) delete poseTargets[k];
|
|
for (const [bone, rot] of Object.entries(p)) {
|
|
const n = normBone(bone);
|
|
if (!n) continue;
|
|
const q = new THREE.Quaternion();
|
|
if (rot.x) q.multiply(new THREE.Quaternion().setFromAxisAngle(new THREE.Vector3(1, 0, 0), rot.x));
|
|
if (rot.y) q.multiply(new THREE.Quaternion().setFromAxisAngle(new THREE.Vector3(0, 1, 0), rot.y));
|
|
if (rot.z) q.multiply(new THREE.Quaternion().setFromAxisAngle(new THREE.Vector3(0, 0, 1), rot.z));
|
|
poseTargets[bone] = { quat: q };
|
|
}
|
|
if (name === 'sit' || name === 'read') {
|
|
poseTargets.hips = { quat: new THREE.Quaternion(), posY: hipsRestY + (seatY + 0.055 - baseHipY) };
|
|
} else {
|
|
poseTargets.hips = { quat: new THREE.Quaternion(), posY: hipsRestY };
|
|
}
|
|
}
|
|
|
|
/* gaze */
|
|
const lookTarget = new THREE.Object3D();
|
|
scene.add(lookTarget);
|
|
let gazeMode = 'idle';
|
|
let gazeWanderT = 0;
|
|
|
|
/* ---------- HUD ---------- */
|
|
const hud = document.getElementById('hud');
|
|
function renderHUD() {
|
|
const s = app.state;
|
|
const i = renderer.info;
|
|
hud.innerHTML = `
|
|
<b>HEL-702 · 独立角色验证</b> · ${MODEL === 'seed' ? 'Seed-san' : 'VRM1_Constraint_Twist_Sample'}<br>
|
|
状态: 衣=${s.outfit} 动作=${s.action} 时间=${s.time} 天气=${s.weather} 视线=${s.gaze}<br>
|
|
draw=${i.render.calls} tri=${i.render.triangles.toLocaleString()} tex=${i.memory.textures} geo=${i.memory.geometries} fps=${app.stats.fps ?? '-'}<br>
|
|
<span style="color:#888">${app.notes.length ? app.notes[app.notes.length - 1] : ''}</span>`;
|
|
}
|
|
|
|
/* ---------- decoupling assertion ---------- */
|
|
let poseSnapshot = null;
|
|
function snapshotPose() {
|
|
const names = ['hips', 'head', 'leftHand', 'rightHand', 'leftUpperLeg'];
|
|
const out = {};
|
|
for (const n of names) {
|
|
const b = normBone(n);
|
|
if (b) out[n] = b.quaternion.clone();
|
|
}
|
|
return out;
|
|
}
|
|
app.assertPosePreserved = () => {
|
|
if (!poseSnapshot) return { pass: null, reason: 'no snapshot' };
|
|
let maxDelta = 0;
|
|
for (const [n, q] of Object.entries(poseSnapshot)) {
|
|
const b = normBone(n);
|
|
if (b) maxDelta = Math.max(maxDelta, b.quaternion.angleTo(q));
|
|
}
|
|
const pass = maxDelta < 1e-4;
|
|
app.notes.push(`环境切换后姿态偏移 = ${maxDelta.toExponential(2)} rad → ${pass ? 'PASS 未重置' : 'FAIL 被重置'}`);
|
|
return { pass, maxDelta };
|
|
};
|
|
|
|
/* ---------- state apply ---------- */
|
|
function applyState(next) {
|
|
Object.assign(app.state, next);
|
|
const s = app.state;
|
|
if (!vrm) return;
|
|
|
|
/* 环境: 完全不触碰 vrm 与姿势 */
|
|
if (s.time === 'night') {
|
|
sun.intensity = 0.04; hemi.intensity = 0.1;
|
|
lampLight.intensity = 14; skyMat.color.set(0x0a1428); cityMat.color.set(0x1a2230);
|
|
renderer.toneMappingExposure = 1.0;
|
|
} else {
|
|
sun.intensity = 2.0; hemi.intensity = 0.55;
|
|
lampLight.intensity = 0; skyMat.color.set(0xbcd7f0); cityMat.color.set(0x6f7f96);
|
|
renderer.toneMappingExposure = 1.0;
|
|
}
|
|
rain.visible = s.weather === 'rain';
|
|
if (s.weather === 'rain') {
|
|
if (s.time === 'night') { skyMat.color.set(0x0a1428); }
|
|
else skyMat.color.set(0x93a8bd);
|
|
}
|
|
|
|
/* 角色 */
|
|
const garments = { Tops: false, Bottoms: false, Shoes: false };
|
|
if (s.outfit === 'B') { garments.Tops = true; garments.Bottoms = true; }
|
|
vrm.scene.traverse((o) => {
|
|
if (o.isMesh) {
|
|
const mats = Array.isArray(o.material) ? o.material : [o.material];
|
|
for (const m of mats) {
|
|
if (/Tops/.test(m.name)) m.visible = !garments.Tops;
|
|
if (/Bottoms/.test(m.name)) m.visible = !garments.Bottoms;
|
|
}
|
|
}
|
|
});
|
|
outfitB.visible = s.outfit === 'B';
|
|
|
|
if (s.action === 'vrma') {
|
|
if (vrmaAction) { vrmaAction.play(); computeTargets('stand'); }
|
|
} else {
|
|
if (vrmaAction) vrmaAction.stop();
|
|
computeTargets(s.action);
|
|
}
|
|
rootTarget = ROOT_T[s.action] || ROOT_T.stand;
|
|
bookG.visible = s.action === 'read';
|
|
gazeMode = s.gaze;
|
|
if (vrm.lookAt) vrm.lookAt.target = s.gaze === 'camera' ? camera : lookTarget;
|
|
if (vrm.expressionManager) vrm.expressionManager.setValue('happy', s.gaze === 'camera' ? 0.9 : 0);
|
|
renderHUD();
|
|
}
|
|
app.setState = (next) => { if (poseSnapshotForNext(next)) poseSnapshot = snapshotPose(); applyState(next); };
|
|
function poseSnapshotForNext(next) {
|
|
return ('time' in next) || ('weather' in next);
|
|
}
|
|
app.snapshotPose = () => { poseSnapshot = snapshotPose(); app.notes.push('已记录当前姿态快照'); renderHUD(); };
|
|
|
|
/* ---------- load ---------- */
|
|
const t0 = performance.now();
|
|
const loader = new GLTFLoader();
|
|
loader.register((p) => new VRMLoaderPlugin(p));
|
|
loader.register((p) => new VRMAnimationLoaderPlugin(p));
|
|
const [gltf, gltfA, manifest] = await Promise.all([
|
|
loader.loadAsync(modelFile),
|
|
loader.loadAsync('assets/test.vrma'),
|
|
fetch('assets/manifest.json').then((r) => r.json()),
|
|
]);
|
|
const loadMs = Math.round(performance.now() - t0);
|
|
vrm = gltf.userData.vrm;
|
|
if (!vrm) {
|
|
console.error('[load] userData keys:', Object.keys(gltf.userData), 'extensions:', gltf.parser?.json?.extensionsUsed, gltf.parser?.json?.extensions);
|
|
throw new Error('VRM plugin did not produce vrm from ' + modelFile);
|
|
}
|
|
VRMUtils.removeUnnecessaryVertices(gltf.scene);
|
|
VRMUtils.combineSkeletons?.(gltf.scene);
|
|
vrm.scene.traverse((o) => { if (o.isMesh) { o.castShadow = true; o.frustumCulled = false; } });
|
|
/* VRM1 模型面朝 +Z;镜头在 +Z 侧,不旋转 */
|
|
scene.add(vrm.scene);
|
|
if (vrm.lookAt) vrm.lookAt.target = lookTarget;
|
|
|
|
/* meta (embedded license info, read at runtime) */
|
|
const m = vrm.meta;
|
|
app.stats.modelMeta = {
|
|
name: m.name, authors: m.authors, licenseUrl: m.licenseUrl,
|
|
commercialUssageName: m.commercialUssageName ?? '(未设置→按VRM PL 1.0默认)',
|
|
modificationName: m.modificationName ?? '(未设置→按VRM PL 1.0默认)',
|
|
allowedUserName: m.allowedUserName ?? '(未设置)',
|
|
};
|
|
const entry = manifest.assets.find((a) => (MODEL === 'seed' ? a.file.includes('Seed') : a.file.includes('Twist')));
|
|
app.stats.asset = entry;
|
|
app.stats.loadMs = loadMs;
|
|
|
|
/* VRMA animation */
|
|
const vrmA = gltfA.userData.vrmAnimation;
|
|
if (vrmA) {
|
|
const clip = createVRMAnimationClip(vrmA, vrm);
|
|
vrmaClipLen = clip.duration;
|
|
mixer = new THREE.AnimationMixer(vrm.scene);
|
|
vrmaAction = mixer.clipAction(clip);
|
|
app.stats.vrma = { duration: clip.duration, tracks: clip.tracks.length, name: entry ? 'test.vrma' : 'test.vrma' };
|
|
}
|
|
|
|
/* pose init */
|
|
const hips = normBone('hips');
|
|
const hipsRestY = hips ? hips.position.y : 0;
|
|
baseHipY = hips ? hips.getWorldPosition(new THREE.Vector3()).y : 0.86;
|
|
sitOffsetY = seatY + 0.055 - baseHipY;
|
|
computeTargets('stand');
|
|
|
|
/* 书本:每帧放在两手之间并对齐角色朝向(阅读姿态可证据化:bookToHand 距离) */
|
|
scene.add(bookG);
|
|
const _rH = new THREE.Vector3(); const _lH = new THREE.Vector3(); const _mid = new THREE.Vector3();
|
|
function placeBook() {
|
|
const r = rawBone('rightHand'); const l = rawBone('leftHand');
|
|
if (!r || !l) return;
|
|
r.getWorldPosition(_rH); l.getWorldPosition(_lH);
|
|
_mid.copy(_rH).add(_lH).multiplyScalar(0.5);
|
|
bookG.position.copy(_mid).y += 0.02;
|
|
bookG.rotation.set(-1.35, vrm.scene.rotation.y, 0.1, 'YXZ');
|
|
}
|
|
|
|
/* runtime bone-binding of outfitB segments (snapshot: add() reparents) */
|
|
for (const o of [...outfitB.children]) {
|
|
if (o.userData.bone) {
|
|
const b = rawBone(o.userData.bone);
|
|
if (b) b.add(o);
|
|
}
|
|
}
|
|
|
|
/* 根节点运动目标(站立在地毯;坐下/阅读在椅子上) */
|
|
const ROOT_T = {
|
|
stand: { pos: new THREE.Vector3(-0.3, 0, 0.35), yaw: 0.45 },
|
|
sit: { pos: new THREE.Vector3(0.62, 0, 0.1), yaw: -0.3 },
|
|
read: { pos: new THREE.Vector3(0.62, 0, 0.1), yaw: -0.3 },
|
|
vrma: { pos: new THREE.Vector3(0, 0, 0), yaw: 0 },
|
|
};
|
|
let rootTarget = ROOT_T.stand;
|
|
|
|
app.probe = () => {
|
|
const wp = (n) => { const b = normBone(n); return b ? b.getWorldPosition(new THREE.Vector3()) : null; };
|
|
const head = wp('head'); const hipsP = wp('hips');
|
|
const lFoot = wp('leftFoot'); const rFoot = wp('rightFoot');
|
|
const lKnee = wp('leftLowerLeg'); const rHandW = rawBone('rightHand') ? rawBone('rightHand').getWorldPosition(new THREE.Vector3()) : null;
|
|
const lHandW = rawBone('leftHand') ? rawBone('leftHand').getWorldPosition(new THREE.Vector3()) : null;
|
|
const bookW = bookG.visible ? bookG.getWorldPosition(new THREE.Vector3()) : null;
|
|
const faceDir = new THREE.Vector3();
|
|
const headN = normBone('head');
|
|
if (headN) headN.getWorldDirection(faceDir);
|
|
const toCam = head ? camera.position.clone().sub(head).normalize() : new THREE.Vector3();
|
|
return {
|
|
headY: +head?.y?.toFixed(3), hipsY: +hipsP?.y?.toFixed(3),
|
|
footMinY: +Math.min(lFoot?.y ?? 9, rFoot?.y ?? 9).toFixed(3),
|
|
kneeFwd: lKnee && hipsP ? +(lKnee.z - hipsP.z).toFixed(3) : null,
|
|
faceAngleToCamDeg: head ? +THREE.MathUtils.radToDeg(faceDir.angleTo(toCam)).toFixed(1) : null,
|
|
bookToRHand: bookW && rHandW ? +bookW.distanceTo(rHandW).toFixed(3) : null,
|
|
bookToLHand: bookW && lHandW ? +bookW.distanceTo(lHandW).toFixed(3) : null,
|
|
handDist: rHandW && lHandW ? +rHandW.distanceTo(lHandW).toFixed(3) : null,
|
|
rHandPos: rHandW ? rHandW.toArray().map((v) => +v.toFixed(2)) : null,
|
|
lHandPos: lHandW ? lHandW.toArray().map((v) => +v.toFixed(2)) : null,
|
|
headPos: head ? head.toArray().map((v) => +v.toFixed(2)) : null,
|
|
bbox: (() => { const b = new THREE.Box3().setFromObject(vrm.scene); const sz = b.getSize(new THREE.Vector3()); return sz.toArray().map((v) => +v.toFixed(3)); })(),
|
|
eyeYaw: (() => { const la = vrm.lookAt; return la ? +THREE.MathUtils.radToDeg(la.yaw).toFixed(1) : null; })(),
|
|
happyWeight: vrm.expressionManager ? +vrm.expressionManager.getValue('happy').toFixed(2) : null,
|
|
rootPos: vrm.scene.position.toArray().map((v) => +v.toFixed(2)),
|
|
rootYaw: +vrm.scene.rotation.y.toFixed(2),
|
|
seatY, outfitBBound: outfitB.children.length === 0,
|
|
};
|
|
};
|
|
|
|
app.ready = true;
|
|
app.notes.push(`模型加载 ${loadMs}ms · ${entry ? (entry.sizeMB + 'MB') : ''} · 授权: ${m.licenseUrl}`);
|
|
applyState({});
|
|
|
|
/* ---------- loop ---------- */
|
|
const clock = new THREE.Clock();
|
|
let fpsAcc = 0, fpsN = 0, fpsT = 0;
|
|
function loop() {
|
|
requestAnimationFrame(loop);
|
|
const dt = Math.min(clock.getDelta(), 0.05);
|
|
const t = clock.elapsedTime;
|
|
|
|
/* root motion: 站位↔椅子 平滑移动 */
|
|
if (vrm) {
|
|
const k = 1 - Math.exp(-dt * 3.2);
|
|
vrm.scene.position.lerp(rootTarget.pos, k);
|
|
let dy = rootTarget.yaw - vrm.scene.rotation.y;
|
|
dy = Math.atan2(Math.sin(dy), Math.cos(dy));
|
|
vrm.scene.rotation.y += dy * k;
|
|
}
|
|
|
|
/* pose easing toward targets (动作自然过渡) */
|
|
if (vrm && app.state.action !== 'vrma') {
|
|
const k = 1 - Math.exp(-dt * 5.5);
|
|
for (const [bone, tgt] of Object.entries(poseTargets)) {
|
|
const n = normBone(bone);
|
|
if (!n) continue;
|
|
n.quaternion.slerp(tgt.quat, k);
|
|
if (tgt.posY !== undefined && bone === 'hips') n.position.y = THREE.MathUtils.lerp(n.position.y, tgt.posY, k);
|
|
}
|
|
/* breathing + micro sway on stand */
|
|
const chest = normBone('chest');
|
|
if (chest && (app.state.action === 'stand')) {
|
|
chest.rotation.x = 0.02 * Math.sin(t * 1.7);
|
|
}
|
|
}
|
|
if (app.state.action === 'read') placeBook();
|
|
if (mixer && app.state.action === 'vrma') mixer.update(dt);
|
|
if (vrm) vrm.update(dt);
|
|
|
|
/* gaze wander */
|
|
if (gazeMode === 'idle') {
|
|
gazeWanderT += dt;
|
|
lookTarget.position.set(0.35 * Math.sin(t * 0.31), 1.15 + 0.12 * Math.sin(t * 0.21), 1.3);
|
|
} else {
|
|
lookTarget.position.copy(camera.position);
|
|
}
|
|
|
|
/* rain fall */
|
|
if (rain.visible) {
|
|
const pos = rain.geometry.attributes.position;
|
|
for (let i = 0; i < RAIN_N; i++) {
|
|
let y = pos.getY(i) - dt * (2.6 + (i % 7) * 0.2);
|
|
if (y < 0) y = 4;
|
|
pos.setY(i, y);
|
|
}
|
|
pos.needsUpdate = true;
|
|
}
|
|
|
|
renderer.render(scene, camera);
|
|
|
|
fpsAcc += dt; fpsN++; fpsT += dt;
|
|
if (fpsT > 0.5) {
|
|
app.stats.fps = Math.round(fpsN / fpsAcc);
|
|
fpsAcc = 0; fpsN = 0; fpsT = 0;
|
|
app.stats.info = {
|
|
calls: renderer.info.render.calls,
|
|
triangles: renderer.info.render.triangles,
|
|
textures: renderer.info.memory.textures,
|
|
geometries: renderer.info.memory.geometries,
|
|
};
|
|
if (performance) {
|
|
if (performance.memory) app.stats.heapMB = Math.round(performance.memory.usedJSHeapSize / 1e6);
|
|
}
|
|
renderHUD();
|
|
}
|
|
}
|
|
loop();
|
|
window.__app = app;
|
|
window.__stats = app.stats;
|