修改3d场景渲染效果,修改pcb、cad入口路由

This commit is contained in:
2026-10-30 16:51:48 +08:00
parent 75eb29ec67
commit 8212c41bed
12 changed files with 262 additions and 70 deletions
+1 -1
View File
@@ -97,7 +97,7 @@ robots/demo-*/ 早期用基础几何体生成的演示 URDF(已不在
| `view` | 相机:`yaw` / `pitch`(角度)、`distance`(倍率) |
| `upAxis` | URDF 一般是 `z`(默认),网格本身 Y 轴向上时填 `y` |
| `facing` | 模型正面朝向修正(度)。我们的「前进」是 +x,模型正面朝 -x 就填 `180` |
| `paint` | 按 URDF 材质名改颜色:`{"wj-wk00": "#16181b"}`(包含即匹配) |
| `paint` | 按材质名包含匹配:颜色字符串,或 `{ "preset": "plastic / metal / rubber", "color": "#16181b", "roughness": 0.45 }`。也支持 `metalness`、`envMapIntensity`、`clearcoat`、`clearcoatRoughness`、`emissive`、`emissiveIntensity`;没有 PBR 数据的 URDF / STL 材质默认使用统一的展示金属表面,GLTF PBR 材质保留原参数。 |
| `extras` | 给模型补几何体,如眼珠:`[{"link": "head_assembly", "shape": "cylinder", "radius": 0.0115, "xyz": [x, y, z], "axis": "z", "color": "#07080a"}]` |
| `gait.footComp` | 双足脚掌补偿系数,默认 `{"hip": 1, "knee": 1}`(踝 = -(髋·hip + 膝·knee)),髋膝转向相反的机器人填 `-1` |
| `gait.armAmp` | 展示动画里手臂摆动幅度倍率,装在移动底盘上的手臂建议 `0.3~0.5` |
+12 -2
View File
@@ -4,7 +4,7 @@
<meta charset="utf-8">
<base href="/">
<meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover">
<title>VibeMake PCB</title>
<title>VibeMake CAD</title>
<style>
html, body { width: 100%; height: 100%; margin: 0; overflow: hidden; }
#cad-frame { position: fixed; inset: 0; display: block; width: 100vw; height: 100vh; height: 100dvh; border: 0; }
@@ -14,9 +14,19 @@
<iframe
id="cad-frame"
src="https://cadworld-studio.robotquan.com/cad"
title="VibeMake PCB"
title="VibeMake CAD"
allow="clipboard-read; clipboard-write; fullscreen"
allowfullscreen
referrerpolicy="strict-origin-when-cross-origin"></iframe>
<script>
const cadFrame = document.getElementById('cad-frame');
const cadOrigin = new URL(cadFrame.src, document.baseURI).origin;
window.addEventListener('message', (event) => {
if (event.source !== cadFrame.contentWindow
|| event.origin !== cadOrigin
|| event.data?.type !== 'vibemake:navigate-home') return;
window.location.assign('/');
});
</script>
</body>
</html>
+2 -2
View File
@@ -449,8 +449,8 @@ code, .md code { font-family: var(--mono); font-size: .86em; color: var(--accent
position: relative; height: clamp(420px, 62vh, 640px);
border-radius: 28px; border: 1px solid var(--line); overflow: hidden;
background:
radial-gradient(50% 60% at 50% 70%, color-mix(in srgb, var(--hue) 12%, transparent), transparent 70%),
radial-gradient(120% 90% at 50% 80%, #13161a, #08090b 75%);
radial-gradient(50% 60% at 50% 70%, color-mix(in srgb, var(--hue) 5%, transparent), transparent 70%),
radial-gradient(120% 90% at 50% 80%, #101318, #08090b 75%);
}
.p-stage .vm-canvas { position: absolute; inset: 0; width: 100% !important; height: 100% !important; }
.stage-tools { position: absolute; top: 20px; right: 20px; display: flex; gap: 8px; z-index: 2; }
+3 -3
View File
@@ -70,8 +70,8 @@ const NAV = [
{ id: 'home', label: '首页', href: '/' },
{ id: 'explore', label: '社区', href: '/explore/' },
{ id: 'studio', label: '工作台', href: '/studio/' },
{ id: 'cad', label: 'CAD', href: '/cad/', newTab: true },
{ id: 'pcb', label: 'PCB', href: '/pcb/', newTab: true },
{ id: 'cad', label: 'CAD', href: '/cad/' },
{ id: 'pcb', label: 'PCB', href: '/pcb/' },
{ id: 'workspace', label: '我的', href: '/workspace/' },
];
@@ -145,7 +145,7 @@ function renderFooter() {
<img src="assets/logo.png" alt="vibemake">
<p>开源机器人社区。<br>把你的机器人带到浏览器里,让更多人一起造。</p>
</div>
<nav class="footer-links"><a href="/explore/">社区</a><a href="/studio/">工作台</a><a href="/cad/" target="_blank" rel="noopener noreferrer">CAD</a><a href="/pcb/" target="_blank" rel="noopener noreferrer">PCB</a><a href="/workspace/">我的</a><a data-publish>发布项目</a></nav>
<nav class="footer-links"><a href="/explore/">社区</a><a href="/studio/">工作台</a><a href="/cad/">CAD</a><a href="/pcb/">PCB</a><a href="/workspace/">我的</a><a data-publish>发布项目</a></nav>
</div>
<div class="container footer-bottom"><span>© 2026 vibemake</span><span>Build robots with good vibes.</span></div>`;
return f;
+1 -1
View File
@@ -127,7 +127,7 @@ function syncUrl() {
async function setupViewer() {
// 3D 引擎按需加载:标题、README 先显示
const { RobotViewer } = await import('./viewer.js');
viewer = new RobotViewer($('stage'), { framing: 2.3, autoRotate: false });
viewer = new RobotViewer($('stage'), { framing: 2.3, autoRotate: false, renderPreset: 'studio' });
const loader = $('loader');
viewer.addEventListener('loading', () => loader.classList.remove('hidden', 'error'));
viewer.addEventListener('progress', (e) => splashProgress(e.detail.loaded / e.detail.total));
+52
View File
@@ -0,0 +1,52 @@
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;
}
+2 -2
View File
@@ -6,8 +6,8 @@
{ id: 'home', label: '首页', href: '/' },
{ id: 'explore', label: '社区', href: '/explore/' },
{ id: 'studio', label: '工作台', href: '/studio/' },
{ id: 'cad', label: 'CAD', href: '/cad/', newTab: true },
{ id: 'pcb', label: 'PCB', href: '/pcb/', newTab: true },
{ id: 'cad', label: 'CAD', href: '/cad/' },
{ id: 'pcb', label: 'PCB', href: '/pcb/' },
{ id: 'workspace', label: '我的', href: '/workspace/' },
];
var p = location.pathname;
+22
View File
@@ -0,0 +1,22 @@
import * as THREE from 'three';
// 只用于 IBL:柔光板形成宽高光,暗区保留反射层次,不增加逐帧的灯光开销。
export function createStudioEnvironment() {
const scene = new THREE.Scene();
const room = new THREE.Mesh(
new THREE.BoxGeometry(20, 20, 20),
new THREE.MeshBasicMaterial({ color: '#17191d', side: THREE.BackSide }),
);
scene.add(room);
const softbox = (width, height, position, intensity) => {
const material = new THREE.MeshBasicMaterial({ color: new THREE.Color().setScalar(intensity), side: THREE.DoubleSide });
const panel = new THREE.Mesh(new THREE.PlaneGeometry(width, height), material);
panel.position.set(...position);
panel.lookAt(0, 0, 0);
scene.add(panel);
};
softbox(4, 3, [-3, 4, 4], 6);
softbox(1.5, 4, [4, 2, 0], 4);
softbox(3, 2, [0, 5, -2], 3);
return scene;
}
+53 -58
View File
@@ -10,6 +10,8 @@ import { ColladaLoader } from 'three/addons/loaders/ColladaLoader.js';
import URDFLoader from 'urdf-loader';
import { URDFDragControls } from 'urdf-loader/src/URDFDragControls.js';
import { MotionController } from './motion.js';
import { prepareRobotMaterial } from './robot-materials.js';
import { createStudioEnvironment } from './studio-environment.js';
export const ACCENT = '#c8ff3e';
const GRID_SPACING = 0.075;
@@ -40,6 +42,7 @@ export class RobotViewer extends EventTarget {
constructor(container, opts = {}) {
super();
this.opts = { autoRotate: false, zoom: false, intro: true, dragJoints: true, follow: false, width: 0, height: 0, preserveDrawingBuffer: false, ...opts };
this.studioLighting = this.opts.renderPreset === 'studio';
this.container = container;
this.mode = 'showcase';
this.robot = null;
@@ -54,9 +57,10 @@ export class RobotViewer extends EventTarget {
r.setPixelRatio(Math.min(window.devicePixelRatio || 1, 2));
r.outputColorSpace = THREE.SRGBColorSpace;
r.toneMapping = THREE.ACESFilmicToneMapping;
r.toneMappingExposure = 0.95;
r.toneMappingExposure = this.studioLighting ? 0.82 : 0.95;
r.shadowMap.enabled = true;
r.shadowMap.type = THREE.PCFSoftShadowMap;
// PCFShadowMap 的 radius 才能控制采样范围;PCFSoftShadowMap 会忽略它。
r.shadowMap.type = this.studioLighting ? THREE.PCFShadowMap : THREE.PCFSoftShadowMap;
r.domElement.classList.add('vm-canvas');
// 第一帧画出来之前隐藏,避免刷新时闪白。
// 用 visibility 而不是 opacity 渐变:Chrome 对 WebGL 画布做透明度动画时偶尔会合成出一块白
@@ -80,7 +84,11 @@ export class RobotViewer extends EventTarget {
this.scene = new THREE.Scene();
const pmrem = new THREE.PMREMGenerator(r);
this.scene.environment = pmrem.fromScene(new RoomEnvironment(r), 0.04).texture;
const environment = this.studioLighting ? createStudioEnvironment() : new RoomEnvironment(r);
this.environmentTarget = pmrem.fromScene(environment, this.studioLighting ? 0.015 : 0.04);
this.scene.environment = this.environmentTarget.texture;
disposeObject(environment);
pmrem.dispose();
this.camera = new THREE.PerspectiveCamera(32, 1, 0.01, 100);
this.camera.position.set(1.8, 0.9, 2.0);
@@ -125,21 +133,23 @@ export class RobotViewer extends EventTarget {
addLights() {
const s = this.scene;
s.add(new THREE.HemisphereLight(0xdfe4ea, 0x0b0c0e, 0.9));
const key = new THREE.DirectionalLight(0xffffff, 2.4);
key.position.set(1.6, 3.2, 1.4);
const studio = this.studioLighting;
s.add(new THREE.HemisphereLight(studio ? 0xffffff : 0xdfe4ea, 0x0b0c0e, studio ? 0.16 : 0.9));
const key = new THREE.DirectionalLight(0xffffff, studio ? 3 : 2.4);
this.keyOffset = new THREE.Vector3(...(studio ? [2.5, 3, 3.5] : [1.6, 3.2, 1.4]));
key.position.copy(this.keyOffset);
key.castShadow = true;
key.shadow.mapSize.set(2048, 2048);
Object.assign(key.shadow.camera, { left: -1.4, right: 1.4, top: 1.4, bottom: -1.4, near: 0.1, far: 8 });
key.shadow.bias = -0.0004;
key.shadow.normalBias = 0.02;
key.shadow.radius = 6;
key.shadow.bias = studio ? -0.00015 : -0.0004;
key.shadow.normalBias = studio ? 0.003 : 0.02;
key.shadow.radius = studio ? 4 : 6;
this.key = key;
s.add(key, key.target);
const rim = new THREE.DirectionalLight(new THREE.Color(ACCENT), 1.1);
const rim = new THREE.DirectionalLight(studio ? 0xffffff : new THREE.Color(ACCENT), studio ? 0.55 : 1.1);
rim.position.set(-2.2, 1.4, -2.4);
s.add(rim);
const fill = new THREE.DirectionalLight(0x9fb4ff, 0.35);
const fill = new THREE.DirectionalLight(studio ? 0xffffff : 0x9fb4ff, studio ? 0.18 : 0.35);
fill.position.set(-2, 0.6, 2);
s.add(fill);
}
@@ -159,6 +169,8 @@ export class RobotViewer extends EventTarget {
uScale: { value: this.renderer.getPixelRatio() },
uColor: { value: new THREE.Color('#8b9099') },
uAccent: { value: new THREE.Color(ACCENT) },
uOpacity: { value: this.studioLighting ? 0.22 : 0.5 },
uAccentMix: { value: this.studioLighting ? 0.12 : 0.55 },
};
this.ground = new THREE.Points(geo, new THREE.ShaderMaterial({
uniforms: this.groundUniforms,
@@ -178,24 +190,25 @@ export class RobotViewer extends EventTarget {
}`,
fragmentShader: /* glsl */`
uniform vec3 uColor; uniform vec3 uAccent;
uniform float uOpacity; uniform float uAccentMix;
varying float vFade; varying float vNear;
void main() {
float r = length(gl_PointCoord - 0.5);
if (r > 0.5) discard;
float a = smoothstep(0.5, 0.25, r) * vFade * 0.5;
gl_FragColor = vec4(mix(uColor, uAccent, vNear * 0.55), a);
float a = smoothstep(0.5, 0.25, r) * vFade * uOpacity;
gl_FragColor = vec4(mix(uColor, uAccent, vNear * uAccentMix), a);
}`,
}));
this.ground.renderOrder = -1;
this.scene.add(this.ground);
this.shadowPlane = new THREE.Mesh(new THREE.PlaneGeometry(6, 6), new THREE.ShadowMaterial({ opacity: 0.45 }));
this.shadowPlane = new THREE.Mesh(new THREE.PlaneGeometry(6, 6), new THREE.ShadowMaterial({ opacity: this.studioLighting ? 0.32 : 0.45, depthWrite: false }));
this.shadowPlane.rotation.x = -Math.PI / 2;
this.shadowPlane.receiveShadow = true;
this.scene.add(this.shadowPlane);
const halo = new THREE.Mesh(new THREE.RingGeometry(0.42, 0.424, 128), new THREE.MeshBasicMaterial({
color: ACCENT, transparent: true, opacity: 0.35, depthWrite: false,
color: ACCENT, transparent: true, opacity: this.studioLighting ? 0.16 : 0.35, depthWrite: false,
}));
halo.rotation.x = -Math.PI / 2;
halo.position.y = 0.002;
@@ -252,11 +265,13 @@ export class RobotViewer extends EventTarget {
highlight(joint, on) {
joint.traverse((o) => {
const mat = o.isMesh && o.material;
if (!mat?.emissive) return;
const base = mat.userData.baseEmissive;
mat.emissive.set(on ? ACCENT : base?.color ?? 0x000000);
mat.emissiveIntensity = on ? 0.22 : base?.intensity ?? 0;
if (!o.isMesh) return;
for (const mat of [].concat(o.material || [])) {
if (!mat.emissive) continue;
const base = mat.userData.baseEmissive;
mat.emissive.set(on ? ACCENT : base?.color ?? 0x000000);
mat.emissiveIntensity = on ? 0.22 : base?.intensity ?? 0;
}
});
}
@@ -336,15 +351,7 @@ export class RobotViewer extends EventTarget {
if (!o.isMesh) return;
o.castShadow = true;
o.receiveShadow = true;
o.material = upgradeMaterial(o.material);
// 配置里的 paint:按 URDF 材质名(包含即可)改颜色,比如把眼睛涂黑
for (const [key, paint] of Object.entries(config.paint || {})) {
if (!o.material.name.includes(key)) continue;
const p = typeof paint === 'string' ? { color: paint } : paint;
o.material.color.set(p.color);
if (p.roughness !== undefined) o.material.roughness = p.roughness;
if (p.metalness !== undefined) o.material.metalness = p.metalness;
}
o.material = prepareRobotMaterial(o.material, config.paint);
});
this.addExtras(robot, config.extras);
return robot;
@@ -421,6 +428,7 @@ export class RobotViewer extends EventTarget {
this.unit = 1 / maxDim;
this.stage.scale.setScalar(this.unit);
this.height = size.y * this.unit;
if (this.studioLighting) this.fitShadows(size.clone().multiplyScalar(this.unit));
const yaw = THREE.MathUtils.degToRad(view.yaw ?? 35);
const pitch = THREE.MathUtils.degToRad(view.pitch ?? 16);
@@ -440,6 +448,14 @@ export class RobotViewer extends EventTarget {
this.lastRobotPos.set(0, 0, 0);
}
fitShadows(size) {
// 模型已归一化;覆盖本体和地面投影,避免固定大视锥浪费阴影分辨率。
const reach = Math.max(size.x, size.z) * 0.5 + size.y * 0.8 + 0.15;
const camera = this.key.shadow.camera;
Object.assign(camera, { left: -reach, right: reach, top: reach, bottom: -reach, near: 0.1, far: 8 });
camera.updateProjectionMatrix();
}
// 步态会改变腿的高度:每帧把最低的可见部件贴到地面,脚始终着地
// 配置里的 extras:给模型补几何体(比如原模型只有眼窝没有眼珠)
// { link, shape: 'sphere' | 'cylinder', radius, length, xyz: [x, y, z], axis: 'x' | 'y' | 'z', color, roughness, metalness }
@@ -568,8 +584,9 @@ export class RobotViewer extends EventTarget {
this.groundUniforms.uCenter.value.set(pos.x, pos.z);
this.halo.position.set(pos.x, 0.002, pos.z);
this.shadowPlane.position.set(pos.x, 0, pos.z);
this.key.position.set(pos.x + 1.6, 3.2, pos.z + 1.4);
this.key.target.position.set(pos.x, 0, pos.z);
const lightHeight = this.studioLighting ? this.height * 0.45 : 0;
this.key.target.position.set(pos.x, lightHeight, pos.z);
this.key.position.copy(this.key.target.position).add(this.keyOffset);
}
this.controls.update();
@@ -598,7 +615,11 @@ export class RobotViewer extends EventTarget {
this.ro?.disconnect();
this.clearRobot();
this.controls.dispose();
this.scene.environment?.dispose();
this.environmentTarget.dispose();
disposeObject(this.ground);
disposeObject(this.shadowPlane);
disposeObject(this.halo);
this.key.shadow.dispose();
this.renderer.domElement.remove();
if (this.opts.renderer) return; // 共用的渲染器不销毁
this.renderer.dispose();
@@ -606,32 +627,6 @@ export class RobotViewer extends EventTarget {
}
}
const DEFAULT_COLOR = new THREE.Color('#9a9ea6');
function upgradeMaterial(original) {
const src = Array.isArray(original) ? original[0] : original;
const hasColor = src?.color && !(src.color.r === 1 && src.color.g === 1 && src.color.b === 1 && src.type === 'MeshPhongMaterial' && !src.name);
const color = hasColor ? src.color.clone() : DEFAULT_COLOR.clone();
// 品牌荧光绿部件加一点自发光,避免被色调映射洗白
const accentish = color.g > 0.85 && color.b < 0.4;
const mat = new THREE.MeshStandardMaterial({
name: src?.name || '',
color,
map: src?.map || null,
roughness: accentish ? 0.35 : 0.58,
metalness: 0.08,
envMapIntensity: 0.7,
transparent: src?.transparent || false,
opacity: src?.opacity ?? 1,
});
if (accentish) {
mat.emissive.copy(color);
mat.emissiveIntensity = 0.7;
mat.userData.baseEmissive = { color: color.clone(), intensity: 0.7 };
}
return mat;
}
function disposeObject(obj) {
obj.traverse((o) => {
o.geometry?.dispose();
+9
View File
@@ -18,5 +18,14 @@
allow="clipboard-read; clipboard-write; fullscreen"
allowfullscreen
referrerpolicy="strict-origin-when-cross-origin"></iframe>
<script>
const pcbFrame = document.getElementById('pcb-frame');
window.addEventListener('message', (event) => {
if (event.source !== pcbFrame.contentWindow
|| event.origin !== new URL(pcbFrame.src).origin
|| event.data?.type !== 'vibemake:navigate-home') return;
window.location.assign('/');
});
</script>
</body>
</html>
+1 -1
View File
@@ -241,4 +241,4 @@
"license": "Apache-2.0"
}
}
]
]
+104
View File
@@ -0,0 +1,104 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import { build } from 'esbuild';
import * as THREE from '../vendor/three/build/three.module.min.js';
// 浏览器 import map 的 three 别名在 Node 中指向同一份随站点发布的库。
const { outputFiles } = await build({
entryPoints: ['js/robot-materials.js'],
absWorkingDir: new URL('..', import.meta.url).pathname,
bundle: true, write: false, format: 'esm', platform: 'node',
alias: { three: './vendor/three/build/three.module.min.js' },
});
const { prepareRobotMaterial } = await import(`data:text/javascript;base64,${Buffer.from(outputFiles[0].contents).toString('base64')}`);
test('preserves physical materials, texture channels and authored values without mutating the source', () => {
const normalMap = new THREE.Texture();
const roughnessMap = new THREE.Texture();
const source = new THREE.MeshPhysicalMaterial({
name: 'painted-metal', color: '#315cb0', roughness: 0.23, metalness: 0.85,
clearcoat: 0.6, normalMap, roughnessMap, envMapIntensity: 1.3,
side: THREE.DoubleSide,
});
const material = prepareRobotMaterial(source);
assert.equal(material.isMeshPhysicalMaterial, true);
for (const key of ['roughness', 'metalness', 'clearcoat', 'envMapIntensity', 'side']) assert.equal(material[key], source[key]);
assert.equal(material.normalMap, normalMap);
assert.equal(material.roughnessMap, roughnessMap);
assert.equal(material.color.getHex(), source.color.getHex());
material.color.set('#ff0000');
assert.equal(source.color.getHexString(), '315cb0');
});
test('metal preset adds a controlled clearcoat highlight without changing the authored gold color', () => {
const material = prepareRobotMaterial(new THREE.MeshPhongMaterial({ name: '3d_printed', color: '#9b7600' }), {
'3d_printed': { preset: 'metal', clearcoat: 0.2, clearcoatRoughness: 0.12 },
});
assert.equal(material.isMeshPhysicalMaterial, true);
assert.equal(material.metalness, 0.88);
assert.equal(material.roughness, 0.24);
assert.equal(material.clearcoat, 0.2);
assert.equal(material.clearcoatRoughness, 0.12);
assert.equal(material.color.getHexString(), '9b7600');
});
test('preserves every material slot and applies named overrides independently', () => {
const body = new THREE.MeshPhongMaterial({ name: 'body', color: '#ffffff' });
const tyre = new THREE.MeshPhongMaterial({ name: 'wheel-tyre', color: '#17191c' });
const materials = prepareRobotMaterial([body, tyre], { tyre: { preset: 'rubber', roughness: 0.9 } });
assert.equal(materials.length, 2);
assert.equal(materials[0].name, 'body');
assert.equal(materials[0].metalness, 0.72);
assert.equal(materials[1].name, 'wheel-tyre');
assert.equal(materials[1].roughness, 0.9);
assert.equal(materials[1].metalness, 0);
assert.equal(tyre.roughness, undefined);
});
test('applies the common metallic showcase finish to unconfigured URDF materials while retaining their colors', () => {
const source = new THREE.MeshPhongMaterial({ name: '3d_printed', color: '#ffe000' });
const material = prepareRobotMaterial(source);
assert.equal(material.isMeshPhysicalMaterial, true);
assert.equal(material.color.getHexString(), 'ffe000');
assert.equal(material.metalness, 0.72);
assert.equal(material.roughness, 0.26);
assert.equal(material.envMapIntensity, 1.35);
assert.equal(material.clearcoat, 0.16);
});
test('applies the same finish to default STL-to-GLB materials but preserves authored standard PBR settings', () => {
const imported = prepareRobotMaterial(new THREE.MeshStandardMaterial({ name: 'converted-stl', color: '#9b7600' }));
assert.equal(imported.metalness, 0.72);
assert.equal(imported.roughness, 0.26);
assert.equal(imported.color.getHexString(), '9b7600');
const authored = new THREE.MeshStandardMaterial({ name: 'authored-pbr', color: '#315cb0', roughness: 0.62, metalness: 0.2 });
const preserved = prepareRobotMaterial(authored);
assert.equal(preserved.roughness, 0.62);
assert.equal(preserved.metalness, 0.2);
});
test('green body paint stays non-emissive while authored emission can be restored after hover', () => {
const body = prepareRobotMaterial(new THREE.MeshPhongMaterial({ name: 'body', color: '#c8ff3e' }));
assert.equal(body.emissive.getHex(), 0);
const led = prepareRobotMaterial(new THREE.MeshStandardMaterial({
name: 'led', emissive: '#00ff00', emissiveIntensity: 0.4,
}));
led.emissive.set('#ffffff');
assert.equal(led.userData.baseEmissive.color.getHexString(), '00ff00');
assert.equal(led.userData.baseEmissive.intensity, 0.4);
});
test('keeps transparent legacy material settings and accepts a material preset without repainting', () => {
const source = new THREE.MeshPhongMaterial({ name: 'cover', color: '#335577', transparent: true, opacity: 0.4, depthWrite: false });
source.normalMap = new THREE.Texture();
source.normalScale.set(0.5, 0.7);
const material = prepareRobotMaterial(source, { cover: { preset: 'plastic' } });
assert.equal(material.color.getHex(), source.color.getHex());
assert.equal(material.opacity, 0.4);
assert.equal(material.transparent, true);
assert.equal(material.depthWrite, false);
assert.equal(material.normalMap, source.normalMap);
assert.equal(material.normalScale.x, 0.5);
assert.equal(material.normalScale.y, 0.7);
});