2019年更新
从版本r89开始,three.js还会调整面和法线。要翻转/镜像一个对象,只需使用:
object3D.applyMatrix(new THREE.Matrix4().makeScale(-1, 1, 1));
不需要进行原解决方案中显示的其他调整。 链接至工单:支持反射矩阵。#12787
原问题
我正在尝试创建一个实用程序,可以翻转Three.js场景中的任何对象。 翻转本身很容易:
object3D.applyMatrix(new THREE.Matrix4().makeScale(-1, 1, 1));
目前遇到的困难是在翻转后修正面部和法向量。结果看起来相当混乱。源对象和翻转对象的图片:https://dl.dropboxusercontent.com/u/20925853/Flipped.png
我看过一些关于这个问题和类似问题的讨论,但没有找到任何有用的东西。有人知道我错过了什么吗? - 谢谢!
Js fiddle上的示例代码: https://jsfiddle.net/7dwh084w/
var renderer;
var scene;
var camera;
function render() {
renderer.render(scene, camera);
};
function load(callback) {
new THREE.ColladaLoader().load("https://dl.dropboxusercontent.com/u/20925853/Kitchen.dae", function (result) {
var mesh = result.scene.children[0].children[0].clone();
if (callback) callback(mesh);
});
}
function init() {
scene = new THREE.Scene();
camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 10000);
camera.position.z = 1000;
var light = new THREE.DirectionalLight(0xffffff);
light.position.set(2, 1, 1).normalize();
scene.add(light);
var ambient = new THREE.AmbientLight(0x777777);
scene.add(ambient);
var controls = new THREE.OrbitControls(camera);
controls.damping = 0.2;
controls.addEventListener('change', render);
renderer = new THREE.WebGLRenderer();
renderer.setSize(window.innerWidth, window.innerHeight);
document.body.appendChild(renderer.domElement);
load(function (mesh) {
flipMesh(mesh);
scene.add(mesh);
render();
});
render();
}
function flipMesh(object3D) {
object3D.applyMatrix(new THREE.Matrix4().makeScale(-1, 1, 1));
reverseWindingOrder(object3D);
}
function reverseWindingOrder(object3D) {
// TODO: Something is missing, the objects are flipped alright but the light reflection on them is somehow broken
if (object3D.type === "Mesh") {
var geometry = object3D.geometry;
for (var i = 0, l = geometry.faces.length; i < l; i++) {
var face = geometry.faces[i];
var temp = face.a;
face.a = face.c;
face.c = temp;
}
var faceVertexUvs = geometry.faceVertexUvs[0];
for (i = 0, l = faceVertexUvs.length; i < l; i++) {
var vector2 = faceVertexUvs[i][0];
faceVertexUvs[i][0] = faceVertexUvs[i][2];
faceVertexUvs[i][2] = vector2;
}
geometry.computeFaceNormals();
geometry.computeVertexNormals();
}
if (object3D.children) {
for (var j = 0, jl = object3D.children.length; j < jl; j++) {
reverseWindingOrder(object3D.children[j]);
}
}
}
init();