Files
vibemake/js/robot-materials.js
T

53 lines
3.2 KiB
JavaScript

import * as THREE from 'three';
const DEFAULT_COLOR = new THREE.Color('#9a9ea6');
const PRESETS = {
// Common metallic finish for imported geometry that does not carry authored PBR material data.
showcase: { roughness: 0.26, metalness: 0.72, clearcoat: 0.16, clearcoatRoughness: 0.14, envMapIntensity: 1.35 },
plastic: { roughness: 0.46, metalness: 0, clearcoat: 0, clearcoatRoughness: 0.1 },
// 金属预设使用较低粗糙度和轻微 clearcoat,让环境反射形成连续的高光带。
metal: { roughness: 0.24, metalness: 0.88, clearcoat: 0.18, clearcoatRoughness: 0.14 },
rubber: { roughness: 0.86, metalness: 0, clearcoat: 0, clearcoatRoughness: 0.1 },
};
// PBR 模型保留贴图、物理参数和多材质分组;只有 URDF / STL 的简单材质需要补齐。
export function prepareRobotMaterial(original, paint = {}) {
if (Array.isArray(original)) return original.map((mat) => prepareRobotMaterial(mat, paint));
const src = original;
let mat;
if (src?.isMeshStandardMaterial) {
mat = src.clone();
const hasTexture = ['map', 'normalMap', 'roughnessMap', 'metalnessMap', 'aoMap', 'emissiveMap', 'bumpMap', 'alphaMap'].some((key) => src[key]);
const hasAuthoredPbr = src.isMeshPhysicalMaterial || hasTexture || src.roughness !== 1 || src.metalness !== 0;
// STL-to-GLB conversion creates a default white StandardMaterial; treat that placeholder like URDF/STL fallback.
if (!hasAuthoredPbr) Object.assign(mat, PRESETS.showcase);
} else {
const hasColor = src?.color && !(src.color.r === 1 && src.color.g === 1 && src.color.b === 1 && src.isMeshPhongMaterial && !src.name);
mat = new THREE.MeshPhysicalMaterial({
name: src?.name || '',
color: hasColor ? src.color : DEFAULT_COLOR,
...PRESETS.showcase,
});
// 贴图共享原资源,颜色 / 向量独立复制,避免悬停高亮影响别的零件。
for (const key of ['map', 'normalMap', 'normalMapType', 'bumpMap', 'bumpScale', 'alphaMap', 'aoMap', 'aoMapIntensity', 'lightMap', 'lightMapIntensity', 'emissiveMap', 'emissiveIntensity', 'displacementMap', 'displacementScale', 'displacementBias', 'transparent', 'opacity', 'alphaTest', 'side', 'depthWrite', 'depthTest', 'vertexColors', 'flatShading']) {
if (src?.[key] !== undefined) mat[key] = src[key];
}
if (src?.normalScale) mat.normalScale.copy(src.normalScale);
if (src?.emissive) mat.emissive.copy(src.emissive);
}
for (const [name, value] of Object.entries(paint)) {
if (!mat.name.includes(name)) continue;
const override = typeof value === 'string' ? { color: value } : value;
if (PRESETS[override.preset]) Object.assign(mat, PRESETS[override.preset]);
if (override.color !== undefined) mat.color.set(override.color);
if (override.emissive !== undefined) mat.emissive.set(override.emissive);
for (const key of ['roughness', 'metalness', 'envMapIntensity', 'emissiveIntensity', 'clearcoat', 'clearcoatRoughness']) {
if (override[key] !== undefined) mat[key] = override[key];
}
}
// 只保留模型或配置明确指定的自发光,不根据绿色外壳的颜色猜测。
mat.userData.baseEmissive = { color: mat.emissive.clone(), intensity: mat.emissiveIntensity };
return mat;
}