Three.js 镜面反射Reflector 为MeshStandardMaterial增加Reflector能力

效果效果官方案例
在这里插入图片描述在这里插入图片描述在这里插入图片描述

区别:官方的案例更像一个镜子 没有纹理等属性 也没有透明度修改

根据源码进行修改为 MeshStandardMaterial实现反射

使用案例

createReflector() {const plane = this.helper.create.plane(2, 2);this.helper.add(plane.mesh);plane.mesh.rotateX(Math.PI / -2);plane.mesh.position.y -= 0.5;const material = plane.mesh.material;console.log(material);plane.mesh.material = new THREE.MeshStandardMaterial({map: this.helper.loadTexture("/public/textures/wallhaven-kxj3l1_840x840.png",(t) => {t.colorSpace = THREE.SRGBColorSpace;}),transparent: true,opacity: 0.3,});addReflectorEffect(plane.mesh);{const plane = this.helper.create.plane(100, 100);this.helper.add(plane.mesh);plane.mesh.rotateY(Math.PI / 2);plane.mesh.position.x -= 1.5;plane.mesh.material = new THREE.MeshStandardMaterial({map: this.helper.loadTexture("/public/textures/building.png",(t) => {t.colorSpace = THREE.SRGBColorSpace;}),normalMap: this.helper.loadTexture("/public/textures/wallhaven-kxj3l1_840x840.png",(t) => {t.colorSpace = THREE.SRGBColorSpace;}),});addReflectorEffect(plane.mesh);}}

源码:

import {Color,Matrix4,Mesh,PerspectiveCamera,Plane,ShaderMaterial,UniformsUtils,Vector3,Vector4,WebGLRenderTarget,HalfFloatType,
} from "three";class Reflector extends Mesh {constructor(geometry, options = {}) {super(geometry);this.isReflector = true;this.type = "Reflector";this.camera = new PerspectiveCamera();const scope = this;const color =options.color !== undefined? new Color(options.color): new Color(0x7f7f7f);const textureWidth = options.textureWidth || 512;const textureHeight = options.textureHeight || 512;const clipBias = options.clipBias || 0;const shader = options.shader || Reflector.ReflectorShader;const multisample =options.multisample !== undefined ? options.multisample : 4;//const reflectorPlane = new Plane();const normal = new Vector3();const reflectorWorldPosition = new Vector3();const cameraWorldPosition = new Vector3();const rotationMatrix = new Matrix4();const lookAtPosition = new Vector3(0, 0, -1);const clipPlane = new Vector4();const view = new Vector3();const target = new Vector3();const q = new Vector4();const textureMatrix = new Matrix4();const virtualCamera = this.camera;const renderTarget = new WebGLRenderTarget(textureWidth,textureHeight,{ samples: multisample, type: HalfFloatType });const material = new ShaderMaterial({name: shader.name !== undefined ? shader.name : "unspecified",uniforms: UniformsUtils.clone(shader.uniforms),fragmentShader: shader.fragmentShader,vertexShader: shader.vertexShader,transparent: true,});material.uniforms["tDiffuse"].value = renderTarget.texture;material.uniforms["_opacity"].value = options.opacity || 1;material.uniforms["color"].value = color;material.uniforms["textureMatrix"].value = textureMatrix;this.material = material;this.count = 0;this.onBeforeRender = (renderer, scene, camera) => {this.count++;// if (this.count % 4 === 0) {//     return;// }reflectorWorldPosition.setFromMatrixPosition(scope.matrixWorld);cameraWorldPosition.setFromMatrixPosition(camera.matrixWorld);rotationMatrix.extractRotation(scope.matrixWorld);normal.set(0, 0, 1);normal.applyMatrix4(rotationMatrix);view.subVectors(reflectorWorldPosition, cameraWorldPosition);// Avoid rendering when reflector is facing awayif (view.dot(normal) > 0) return;view.reflect(normal).negate();view.add(reflectorWorldPosition);rotationMatrix.extractRotation(camera.matrixWorld);lookAtPosition.set(0, 0, -1);lookAtPosition.applyMatrix4(rotationMatrix);lookAtPosition.add(cameraWorldPosition);target.subVectors(reflectorWorldPosition, lookAtPosition);target.reflect(normal).negate();target.add(reflectorWorldPosition);virtualCamera.position.copy(view);virtualCamera.up.set(0, 1, 0);virtualCamera.up.applyMatrix4(rotationMatrix);virtualCamera.up.reflect(normal);virtualCamera.lookAt(target);virtualCamera.far = camera.far; // Used in WebGLBackgroundvirtualCamera.updateMatrixWorld();virtualCamera.projectionMatrix.copy(camera.projectionMatrix);// Update the texture matrixtextureMatrix.set(0.5,0.0,0.0,0.5,0.0,0.5,0.0,0.5,0.0,0.0,0.5,0.5,0.0,0.0,0.0,1.0);textureMatrix.multiply(virtualCamera.projectionMatrix);textureMatrix.multiply(virtualCamera.matrixWorldInverse);textureMatrix.multiply(scope.matrixWorld);// Now update projection matrix with new clip plane, implementing code from: http://www.terathon.com/code/oblique.html// Paper explaining this technique: http://www.terathon.com/lengyel/Lengyel-Oblique.pdfreflectorPlane.setFromNormalAndCoplanarPoint(normal,reflectorWorldPosition);reflectorPlane.applyMatrix4(virtualCamera.matrixWorldInverse);clipPlane.set(reflectorPlane.normal.x,reflectorPlane.normal.y,reflectorPlane.normal.z,reflectorPlane.constant);const projectionMatrix = virtualCamera.projectionMatrix;q.x =(Math.sign(clipPlane.x) + projectionMatrix.elements[8]) /projectionMatrix.elements[0];q.y =(Math.sign(clipPlane.y) + projectionMatrix.elements[9]) /projectionMatrix.elements[5];q.z = -1.0;q.w =(1.0 + projectionMatrix.elements[10]) /projectionMatrix.elements[14];// Calculate the scaled plane vectorclipPlane.multiplyScalar(2.0 / clipPlane.dot(q));// Replacing the third row of the projection matrixprojectionMatrix.elements[2] = clipPlane.x;projectionMatrix.elements[6] = clipPlane.y;projectionMatrix.elements[10] = clipPlane.z + 1.0 - clipBias;projectionMatrix.elements[14] = clipPlane.w;// Renderscope.visible = false;const currentRenderTarget = renderer.getRenderTarget();const currentXrEnabled = renderer.xr.enabled;const currentShadowAutoUpdate = renderer.shadowMap.autoUpdate;renderer.xr.enabled = false; // Avoid camera modificationrenderer.shadowMap.autoUpdate = false; // Avoid re-computing shadowsrenderer.setRenderTarget(renderTarget);renderer.state.buffers.depth.setMask(true); // make sure the depth buffer is writable so it can be properly cleared, see #18897if (renderer.autoClear === false) renderer.clear();// filteroptions.filter.forEach((name) => {const mesh = scene.getObjectByName(name);mesh.visible = false;});renderer.render(scene, virtualCamera);options.filter.forEach((name) => {const mesh = scene.getObjectByName(name);mesh.visible = true;});renderer.xr.enabled = currentXrEnabled;renderer.shadowMap.autoUpdate = currentShadowAutoUpdate;renderer.setRenderTarget(currentRenderTarget);// Restore viewportconst viewport = camera.viewport;if (viewport !== undefined) {renderer.state.viewport(viewport);}scope.visible = true;};this.getRenderTarget = function () {return renderTarget;};this.dispose = function () {renderTarget.dispose();scope.material.dispose();};}
}Reflector.ReflectorShader = {name: "ReflectorShader",uniforms: {color: {value: null,},tDiffuse: {value: null,},textureMatrix: {value: null,},_opacity: {value: null,},},vertexShader: /* glsl */ `uniform mat4 textureMatrix;varying vec4 vUv;#include <common>#include <logdepthbuf_pars_vertex>void main() {vUv = textureMatrix * vec4( position, 1.0 );gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );#include <logdepthbuf_vertex>}`,fragmentShader: /* glsl */ `uniform vec3 color;uniform float _opacity;uniform sampler2D tDiffuse;varying vec4 vUv;#include <logdepthbuf_pars_fragment>float blendOverlay( float base, float blend ) {return( base < 0.5 ? ( 2.0 * base * blend ) : ( 1.0 - 2.0 * ( 1.0 - base ) * ( 1.0 - blend ) ) );}vec3 blendOverlay( vec3 base, vec3 blend ) {return vec3( blendOverlay( base.r, blend.r ), blendOverlay( base.g, blend.g ), blendOverlay( base.b, blend.b ) );}void main() {#include <logdepthbuf_fragment>vec4 base = texture2DProj( tDiffuse, vUv );gl_FragColor = vec4( base.rgb , 0.1 );#include <tonemapping_fragment>#include <colorspace_fragment>}`,
};export { Reflector };/*** @description: 为mesh的材质增加反光效果* @param {*} mesh* @return {*}*/
export function addReflectorEffect(mesh, options = { filter: [] }) {const material = mesh.material;// material.isReflector = true;// material.type = "Reflector";const camera = new PerspectiveCamera();const textureWidth = options.textureWidth || 512;const textureHeight = options.textureHeight || 512;const clipBias = options.clipBias || 0;const shader = options.shader || Reflector.ReflectorShader;const multisample =options.multisample !== undefined ? options.multisample : 4;const reflectorPlane = new Plane();const normal = new Vector3();const reflectorWorldPosition = new Vector3();const cameraWorldPosition = new Vector3();const rotationMatrix = new Matrix4();const lookAtPosition = new Vector3(0, 0, -1);const clipPlane = new Vector4();const view = new Vector3();const target = new Vector3();const q = new Vector4();const textureMatrix = new Matrix4();const virtualCamera = camera;const renderTarget = new WebGLRenderTarget(textureWidth, textureHeight, {samples: multisample,type: HalfFloatType,});const appendUniforms = {refDiffuse: { value: renderTarget.texture },// refOpacity: { value: options.opacity || 1 },refTextureMatrix: { value: textureMatrix },};material.onBeforeCompile = (shader) => {console.log(shader);Object.assign(shader.uniforms, appendUniforms);shader.vertexShader = shader.vertexShader.replace("#include <common>",`#include <common>uniform mat4 refTextureMatrix;varying vec4 refUv;`);shader.fragmentShader = shader.fragmentShader.replace("#include <common>",`#include <common>uniform sampler2D refDiffuse;varying vec4 refUv;`);shader.vertexShader = shader.vertexShader.replace("#include <begin_vertex>",`#include <begin_vertex>refUv = refTextureMatrix * vec4( position, 1.0 );`);shader.fragmentShader = shader.fragmentShader.replace("#include <dithering_fragment>",`#include <dithering_fragment>gl_FragColor.rgb += texture2DProj( refDiffuse, refUv ).rgb;gl_FragColor.a =  ${options.opacity || "1.0"};`);// uniform sampler2D refDiffuse;// varying vec4 vUv;// console.log(shader.fragmentShader);};mesh.material.onBeforeRender = (renderer, scene, camera) => {reflectorWorldPosition.setFromMatrixPosition(mesh.matrixWorld);cameraWorldPosition.setFromMatrixPosition(camera.matrixWorld);rotationMatrix.extractRotation(mesh.matrixWorld);normal.set(0, 0, 1);normal.applyMatrix4(rotationMatrix);view.subVectors(reflectorWorldPosition, cameraWorldPosition);// Avoid rendering when reflector is facing awayif (view.dot(normal) > 0) return;view.reflect(normal).negate();view.add(reflectorWorldPosition);rotationMatrix.extractRotation(camera.matrixWorld);lookAtPosition.set(0, 0, -1);lookAtPosition.applyMatrix4(rotationMatrix);lookAtPosition.add(cameraWorldPosition);target.subVectors(reflectorWorldPosition, lookAtPosition);target.reflect(normal).negate();target.add(reflectorWorldPosition);virtualCamera.position.copy(view);virtualCamera.up.set(0, 1, 0);virtualCamera.up.applyMatrix4(rotationMatrix);virtualCamera.up.reflect(normal);virtualCamera.lookAt(target);virtualCamera.far = camera.far; // Used in WebGLBackgroundvirtualCamera.updateMatrixWorld();virtualCamera.projectionMatrix.copy(camera.projectionMatrix);// Update the texture matrixtextureMatrix.set(0.5,0.0,0.0,0.5,0.0,0.5,0.0,0.5,0.0,0.0,0.5,0.5,0.0,0.0,0.0,1.0);textureMatrix.multiply(virtualCamera.projectionMatrix);textureMatrix.multiply(virtualCamera.matrixWorldInverse);textureMatrix.multiply(mesh.matrixWorld);// Now update projection matrix with new clip plane, implementing code from: http://www.terathon.com/code/oblique.html// Paper explaining this technique: http://www.terathon.com/lengyel/Lengyel-Oblique.pdfreflectorPlane.setFromNormalAndCoplanarPoint(normal,reflectorWorldPosition);reflectorPlane.applyMatrix4(virtualCamera.matrixWorldInverse);clipPlane.set(reflectorPlane.normal.x,reflectorPlane.normal.y,reflectorPlane.normal.z,reflectorPlane.constant);const projectionMatrix = virtualCamera.projectionMatrix;q.x =(Math.sign(clipPlane.x) + projectionMatrix.elements[8]) /projectionMatrix.elements[0];q.y =(Math.sign(clipPlane.y) + projectionMatrix.elements[9]) /projectionMatrix.elements[5];q.z = -1.0;q.w =(1.0 + projectionMatrix.elements[10]) /projectionMatrix.elements[14];// Calculate the scaled plane vectorclipPlane.multiplyScalar(2.0 / clipPlane.dot(q));// Replacing the third row of the projection matrixprojectionMatrix.elements[2] = clipPlane.x;projectionMatrix.elements[6] = clipPlane.y;projectionMatrix.elements[10] = clipPlane.z + 1.0 - clipBias;projectionMatrix.elements[14] = clipPlane.w;// Render// TODO : 于一体的反光 不能将自己隐去 只是不显示反射纹理mesh.visible = false;const currentRenderTarget = renderer.getRenderTarget();const currentXrEnabled = renderer.xr.enabled;const currentShadowAutoUpdate = renderer.shadowMap.autoUpdate;renderer.xr.enabled = false; // Avoid camera modificationrenderer.shadowMap.autoUpdate = false; // Avoid re-computing shadowsrenderer.setRenderTarget(renderTarget);renderer.state.buffers.depth.setMask(true); // make sure the depth buffer is writable so it can be properly cleared, see #18897if (renderer.autoClear === false) renderer.clear();// filteroptions.filter.forEach((name) => {const mesh = scene.getObjectByName(name);mesh.visible = false;});renderer.render(scene, virtualCamera);options.filter.forEach((name) => {const mesh = scene.getObjectByName(name);mesh.visible = true;});renderer.xr.enabled = currentXrEnabled;renderer.shadowMap.autoUpdate = currentShadowAutoUpdate;renderer.setRenderTarget(currentRenderTarget);// Restore viewportconst viewport = camera.viewport;if (viewport !== undefined) {renderer.state.viewport(viewport);}mesh.visible = true;};
}

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/624050.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

juniper EX系列交换机POE配置

PoE&#xff08;Power over Ethernet&#xff0c;以太网供电&#xff0c;又称远程供电&#xff09;是指设备通过以太网接口&#xff0c;利用双绞线对外接PD&#xff08;Powered Device&#xff0c;受电设备&#xff09;设备&#xff08;如IP 电话、无线AP、网络摄像头等&#x…

什么是视频短信,能用在什么地方?

视频短信是指通过106短信将带有视频的短信内容发送到对应的手机中&#xff0c;也称之为点对点的信息传递方式&#xff0c;视频短信可以支持2兆以内的多媒体信息发送&#xff0c;是直接、直观的宣传、沟通方式。 一、怎么就偏偏要找视频短信 根据目前的行情状况&#xff0c;尽管…

为什么模方崩过后重新新建工程打开会提示“OSG读取Node失败”?

为什么模方崩过后重新新建工程打开会提示“OSG读取Node失败”&#xff1f; 答&#xff1a;瓦块数据中可能有空文件或者不符合osgb组织结构的文件&#xff0c;可以检查移除。 模方是一款针对实景三维模型的冗余碎片、水面残缺、道路不平、标牌破损、纹理拉伸模糊等共性问题研发的…

3d模型素材亮度和对比度如何调整呢?

1、修改材质参数&#xff1a;打开3ds Max后&#xff0c;选择要调整亮度和对比度的3D模型素材。然后&#xff0c;进入材质编辑器&#xff0c;选择相应的材质球。在材质编辑器中&#xff0c;你可以调整材质的漫反射、反射和高光等参数&#xff0c;这些参数将影响模型的亮度和对比…

C语言实现学生成绩管理系统(单链表)

本次我就用学到的相关链表知识总结回顾一下学生成绩管理系统的实现。 首先还是先创建一个项目&#xff0c;分别创建头文件和源文件&#xff0c;头文件用来声明函数&#xff0c;源文件用来定义函数以及实现学生成绩管理系统。 创建完成后如上图。 先创建一个结构体用来存放学生…

第9章-第3节-Java中的自定义注解

注解&#xff1a;有Override,我们把它称为重写的注解。那么注解到底什么呢&#xff1f;我们能不能自定义注解。 1、概念&#xff1a; 注解是一种能被添加到java代码中的元数据&#xff0c;类、方法、变量、参数和包都可以用注解来修饰。注解对于它所修饰的代码并没有直接的影…

低端单片机彩色屏幕的内存占用疑惑

前言 问题&#xff1a; 假设320*240的rgb565屏幕&#xff0c;320*240*2153600&#xff0c;内存已经150K了&#xff0c;而很多低端单片机接口速度虽然勉强能用&#xff0c;但内存只有20K/8K&#xff0c;整屏的显存是绝对放不下的&#xff0c;只刷一部分都占很多内存&#xff0…

重建大师程序卡死过一次以后,再打开就显示“工程被本地机器打开”,怎么解决?

答&#xff1a;可以检查下本机是不是开了多个重建大师软件&#xff0c;将多开的软件关闭。或者可以修改下电脑名称&#xff0c;重启电脑&#xff0c;然后再打开工程。

DaisyDisk for mac 中文激活版 可视化磁盘清理工具

DaisyDisk 是一款专为 Mac 设计的磁盘空间分析工具。它以直观、图形化的方式展示硬盘使用情况&#xff0c;帮助用户迅速找到占用空间大的文件和文件夹。通过扫描磁盘&#xff0c;DaisyDisk 生成彩色的扇形图表&#xff0c;每个扇区代表一个文件或文件夹&#xff0c;大小直观反映…

Java多线程并发篇----第十五篇

系列文章目录 文章目录 系列文章目录前言一、偏向锁二、分段锁三、锁优化四、线程基本方法前言 前些天发现了一个巨牛的人工智能学习网站,通俗易懂,风趣幽默,忍不住分享一下给大家。点击跳转到网站,这篇文章男女通用,看懂了就去分享给你的码吧。 一、偏向锁 Hotspot 的…

肯尼斯·里科《C和指针》第6章 指针(4)实例

肯尼斯里科《C和指针》第6章 指针&#xff08;1&#xff09;-CSDN博客 肯尼斯里科《C和指针》第6章 指针&#xff08;2&#xff09;-CSDN博客 肯尼斯里科《C和指针》第6章 指针&#xff08;3&#xff09;-CSDN博客 6.12 实例 /* ** 计算一个字符串的长度。 */ #include <…

leetcode 349 两个数组的集合

题目 给定两个数组 nums1 和 nums2 &#xff0c;返回 它们的交集 。输出结果中的每个元素一定是 唯一 的。我们可以 不考虑输出结果的顺序 。 示例 1&#xff1a; 输入&#xff1a;nums1 [1,2,2,1], nums2 [2,2] 输出&#xff1a;[2] 示例 2&#xff1a; 输入&#xff1a…

JNA调用C++动态库,返回二维数组

1.下载eclipse创建一个项目&#xff0c;jdk选择1.8的版本&#xff0c;更高的需要配置下 package mydemo; import com.sun.jna.Library; import com.sun.jna.Native; import com.sun.jna.ptr.IntByReference; import com.sun.jna.ptr.LongByReference; import com.sun.jna.ptr.…

js获取当前日期方法

//获取当前日期函数 gettDate() { let date new Date(), obj { year: date.getFullYear(), //获取完整的年份(4位) month: date.getMonth() 1, //获取当前月份(0-11,0代表1月) strDate: date.getDate(), // 获取当前日(1-31) hour: date.getHours(), //获取当前小时(0 ~ 23)…

【playwright】新一代自动化测试神器playwright+python系列课程00——playwright安装

playwright安装 本文主要分享由微软开发的实现Web UI自动化测试工具Playwright库&#xff0c;相比于之前学习过selenium库&#xff0c;playwright对于编写自动化代码绝对是更轻松了&#xff0c;因为它支持脚本录制&#xff0c;如果只求简单点可以不用写一行代码就能够实现自动…

Spring 启动过程

博文目录 文章目录 内容总结new AnnotationConfigApplicationContextApplicationContext.refresh底层流程 refresh - invokeBeanFactoryPostProcessorsBeanFactoryPostProcessor 内容总结 Spring启动流程详解 通常&#xff0c;我们说的 Spring 启动&#xff0c;就是构造 Appli…

Debezium发布历史68

原文地址&#xff1a; https://debezium.io/blog/2019/09/05/website-documentation-overhaul/ 欢迎关注留言&#xff0c;我是收集整理小能手&#xff0c;工具翻译&#xff0c;仅供参考&#xff0c;笔芯笔芯. 网站和文档大修 2019 年 9 月 5 日 作者&#xff1a; 克里斯克兰福…

网络安全|GitHub 已成为恶意软件传播的严重污染源

Recorded Future 凸显了全球合法平台威胁的上升。 根据 Recorded Future最近 的一份报告&#xff0c;开发者平台GitHub最近已成为黑客用来托管和传播恶意软件的流行工具。 该平台为攻击者提供了将其行为伪装成合法网络流量的能力&#xff0c;这使得跟踪和确定攻击者的身份变得…

ubuntu20.04 deepstream 6.3安装

1.基础环境gstreamer sudo apt install \ libssl-dev \ libgstreamer1.0-0 \ gstreamer1.0-tools \ gstreamer1.0-plugins-good \ gstreamer1.0-plugins-bad \ gstreamer1.0-plugins-ugly \ gstreamer1.0-libav \ libgstreamer-plugins-base1.0-dev \ libgstrtspserver-1.0-0 …

C练习——模拟投掷6000次骰子

题目&#xff1a; 模拟骰子投6000次&#xff0c;并计算每一面出现的概率 解析&#xff1a; 6000次&#xff0c;首先想到用数组记录六个面各出现次数 其次&#xff0c;使用随机数&#xff08;1~6的数&#xff09;模拟骰子 然后统计1~6每个数出现的几次&#xff0c;最后除以6…