webgl_renderer_pathtracer
对应 three.js 示例地址 。
仅需关注 init
函数的内容,其他部分都是示例小程序所使用的描述配置。
js
import * as THREE from "three";
import { OrbitControls } from "three/examples/jsm/controls/OrbitControls.js";
import { RGBELoader } from "three/examples/jsm/loaders/RGBELoader.js";
import { LDrawLoader } from "three/examples/jsm/loaders/LDrawLoader.js";
import { LDrawUtils } from "three/examples/jsm/utils/LDrawUtils.js";
import { LDrawConditionalLineMaterial } from "three/examples/jsm/materials/LDrawConditionalLineMaterial.js";
import { GradientEquirectTexture, WebGLPathTracer, BlurredEnvMapGenerator } from "three-gpu-pathtracer";
/** @type {import("@minisheeep/mp-three-examples").OfficialExampleInfo} */
const exampleInfo = {
name: "webgl_renderer_pathtracer",
useLoaders: [RGBELoader, LDrawLoader],
info: [
[
{
tag: "a",
link: "https://threejs.org",
content: "three.js"
},
{
tag: "text",
content: "pathtracer -"
},
{
tag: "a",
link: "https://github.com/gkjohnson/three-gpu-pathtracer",
content: "three-gpu-pathtracer"
}
],
[
{
tag: "text",
content: "See"
},
{
tag: "a",
link: "https://github.com/gkjohnson/three-gpu-pathtracer",
content: "main project repository"
},
{
tag: "text",
content: "for more information and examples on high fidelity path tracing."
}
]
],
init: ({
window,
canvas,
GUI,
Stats,
needToDispose,
useFrame,
requestLoading,
cancelLoading
}) => {
let camera, scene, renderer, controls, gui;
let pathTracer, floor, gradientMap;
const params = {
enable: false,
toneMapping: true,
pause: false,
tiles: 3,
transparentBackground: false,
resolutionScale: 1,
roughness: 0.15,
metalness: 0.9
};
init();
function init() {
camera = new THREE.PerspectiveCamera(45, window.innerWidth / window.innerHeight, 1, 1e4);
camera.position.set(150, 200, 250);
renderer = new THREE.WebGLRenderer({
antialias: true,
alpha: true,
preserveDrawingBuffer: true,
premultipliedAlpha: false,
canvas
});
renderer.setPixelRatio(window.devicePixelRatio);
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.toneMapping = THREE.ACESFilmicToneMapping;
gradientMap = new GradientEquirectTexture();
gradientMap.topColor.set(15658734);
gradientMap.bottomColor.set(15395562);
gradientMap.update();
pathTracer = new WebGLPathTracer(renderer);
pathTracer.filterGlossyFactor = 1;
pathTracer.minSamples = 3;
pathTracer.renderScale = params.resolutionScale;
pathTracer.tiles.set(params.tiles, params.tiles);
scene = new THREE.Scene();
scene.background = gradientMap;
controls = new OrbitControls(camera, renderer.domElement);
controls.addEventListener("change", () => {
pathTracer.updateCamera();
});
window.addEventListener("resize", onWindowResize);
onWindowResize();
createGUI();
loadModel();
needToDispose(renderer, scene, controls);
}
async function loadModel() {
let model = null;
let environment = null;
showProgressBar();
const lDrawLoader = new LDrawLoader();
lDrawLoader.setConditionalLineMaterial(LDrawConditionalLineMaterial);
const ldrawPromise = lDrawLoader.setPath("models/ldraw/officialLibrary/").loadAsync("models/7140-1-X-wingFighter.mpd_Packed.mpd", onProgress).then(function(legoGroup) {
legoGroup = LDrawUtils.mergeObject(legoGroup);
legoGroup.rotation.x = Math.PI;
legoGroup.updateMatrixWorld();
model = legoGroup;
legoGroup.traverse((c) => {
if (c.isLineSegments) {
c.visible = false;
}
if (c.material) {
c.material.roughness *= 0.25;
if (c.material.opacity < 1) {
const oldMaterial = c.material;
const newMaterial = new THREE.MeshPhysicalMaterial();
newMaterial.opacity = 1;
newMaterial.transmission = 1;
newMaterial.thickness = 1;
newMaterial.ior = 1.4;
newMaterial.roughness = oldMaterial.roughness;
newMaterial.metalness = 0;
const hsl = {};
oldMaterial.color.getHSL(hsl);
hsl.l = Math.max(hsl.l, 0.35);
newMaterial.color.setHSL(hsl.h, hsl.s, hsl.l);
c.material = newMaterial;
}
}
});
}).catch(onError);
const envMapPromise = new RGBELoader().setPath("textures/equirectangular/").loadAsync("royal_esplanade_1k.hdr").then((tex) => {
const envMapGenerator = new BlurredEnvMapGenerator(renderer);
const blurredEnvMap = envMapGenerator.generate(tex, 0);
environment = blurredEnvMap;
}).catch(onError);
await Promise.all([envMapPromise, ldrawPromise]);
hideProgressBar();
scene.environment = environment;
const bbox = new THREE.Box3().setFromObject(model);
const size = bbox.getSize(new THREE.Vector3());
const radius = Math.max(size.x, Math.max(size.y, size.z)) * 0.4;
controls.target0.copy(bbox.getCenter(new THREE.Vector3()));
controls.position0.set(2.3, 1, 2).multiplyScalar(radius).add(controls.target0);
controls.reset();
scene.add(model);
floor = new THREE.Mesh(
new THREE.PlaneGeometry(),
new THREE.MeshStandardMaterial({
side: THREE.DoubleSide,
roughness: params.roughness,
metalness: params.metalness,
map: generateRadialFloorTexture(1024),
transparent: true
})
);
floor.scale.setScalar(2500);
floor.rotation.x = -Math.PI / 2;
floor.position.y = bbox.min.y;
scene.add(floor);
pathTracer.setScene(scene, camera);
renderer.setAnimationLoop(animate);
}
function onWindowResize() {
const w = window.innerWidth;
const h = window.innerHeight;
const dpr = window.devicePixelRatio;
renderer.setSize(w, h);
renderer.setPixelRatio(dpr);
const aspect = w / h;
camera.aspect = aspect;
camera.updateProjectionMatrix();
pathTracer.updateCamera();
}
function createGUI() {
if (gui) {
gui.destroy();
}
gui = new GUI();
gui.add(params, "enable");
gui.add(params, "pause");
gui.add(params, "toneMapping");
gui.add(params, "transparentBackground").onChange((v) => {
scene.background = v ? null : gradientMap;
pathTracer.updateEnvironment();
});
gui.add(params, "resolutionScale", 0.1, 1, 0.1).onChange((v) => {
pathTracer.renderScale = v;
pathTracer.reset();
});
gui.add(params, "tiles", 1, 6, 1).onChange((v) => {
pathTracer.tiles.set(v, v);
});
gui.add(params, "roughness", 0, 1).name("floor roughness").onChange((v) => {
floor.material.roughness = v;
pathTracer.updateMaterials();
});
gui.add(params, "metalness", 0, 1).name("floor metalness").onChange((v) => {
floor.material.metalness = v;
pathTracer.updateMaterials();
});
}
function animate() {
renderer.toneMapping = params.toneMapping ? THREE.ACESFilmicToneMapping : THREE.NoToneMapping;
Math.floor(pathTracer.samples);
pathTracer.enablePathTracing = params.enable;
pathTracer.pausePathTracing = params.pause;
pathTracer.renderSample();
`samples: ${Math.floor(pathTracer.samples)}`;
}
function onProgress(xhr) {
if (xhr.lengthComputable) {
updateProgressBar(xhr.loaded / xhr.total);
}
}
function onError(error) {
const message = "Error loading model";
console.log(message);
console.error(error);
}
function showProgressBar() {
return requestLoading("加载中");
}
function hideProgressBar() {
cancelLoading();
}
function updateProgressBar(fraction) {
}
function generateRadialFloorTexture(dim) {
const data = new Uint8Array(dim * dim * 4);
for (let x = 0; x < dim; x++) {
for (let y = 0; y < dim; y++) {
const xNorm = x / (dim - 1);
const yNorm = y / (dim - 1);
const xCent = 2 * (xNorm - 0.5);
const yCent = 2 * (yNorm - 0.5);
let a = Math.max(Math.min(1 - Math.sqrt(xCent ** 2 + yCent ** 2), 1), 0);
a = a ** 1.5;
a = a * 1.5;
a = Math.min(a, 1);
const i = y * dim + x;
data[i * 4 + 0] = 255;
data[i * 4 + 1] = 255;
data[i * 4 + 2] = 255;
data[i * 4 + 3] = a * 255;
}
}
const tex = new THREE.DataTexture(data, dim, dim);
tex.format = THREE.RGBAFormat;
tex.type = THREE.UnsignedByteType;
tex.minFilter = THREE.LinearFilter;
tex.magFilter = THREE.LinearFilter;
tex.wrapS = THREE.RepeatWrapping;
tex.wrapT = THREE.RepeatWrapping;
tex.needsUpdate = true;
return tex;
}
}
};
export {
exampleInfo as default
};
ts
import { Loader, TypedArray } from 'three';
/**
* 官网示例的多端使用封装把版本
* */
export interface OfficialExampleInfo extends MiniProgramMeta {
/*** 示例名称(保持和官网一致)*/
name: string;
/** main */
init: (context: LoadContext) => void;
}
export interface LoadContext {
//为了减少官方代码的改动,实际上等同于 canvas
window: EventTarget & { innerWidth: number; innerHeight: number; devicePixelRatio: number };
/** HTMLCanvasElement */
canvas: any;
/** https://www.npmjs.com/package/lil-gui */
GUI: any;
/**
* https://www.npmjs.com/package/stats.js
* 也可以使用其他受支持的版本
* */
Stats: any;
/** 收集需要 dispose 的对象(官方示例没有处理这部分)*/
needToDispose: (...objs: any[]) => void | ((fromFn: () => any[]) => void);
/**基于 raq 的通用封装 */
useFrame(animateFunc: (/** ms */ delta: number) => void): { cancel: () => void };
/** 显示加载模态框 */
requestLoading(text?: string): Promise<void>;
/** 隐藏加载模态框*/
cancelLoading(): void;
/** 保存文件的通用封装*/
saveFile(
fileName: string,
data: ArrayBuffer | TypedArray | DataView | string
): Promise<string | null>;
/** 示例使用 DracoDecoder 时的资源路径 */
DecoderPath: {
GLTF: string;
STANDARD: string;
};
/** 为资源路径拼上 CDN 前缀 */
withCDNPrefix(path: string): string;
/**
* 在小程序中应使用 import { VideoTexture } from '@minisheep/three-platform-adapter/override/jsm/textures/VideoTexture.js';
* 正常情况(web) 可直接使用 THREE.VideoTexture
* */
getVideoTexture(videoOptions: VideoOptions): Promise<[{ isVideoTexture: true }, video: any]>;
/**
* 在小程序中应使用 import { CameraTexture } from '@minisheep/three-platform-adapter/override/jsm/textures/CameraTexture.js';
* 正常情况(web) 可参考示例 webgl_materials_video_webcam
* */
getCameraTexture(): { isVideoTexture: true };
/** 用于动态修改 info 中的占位符*/
bindInfoText(template: `$${string}$`, initValue?: string): { value: string };
/** 分屏控件对应的事件回调 */
onSlideStart(handle: () => void): void;
/** 分屏控件对应的事件回调 */
onSlideEnd(handle: () => void): void;
/** 分屏控件对应的事件回调 */
onSlideChange(handle: (offset: number, boxSize: number) => void): void;
}
export type VideoOptions = {
src: string;
/** 相当于 HTMLVideoElement 的 naturalWidth (小程序中获取不到)*/
width: number;
/** 相当于 HTMLVideoElement 的 naturalHeight (小程序中获取不到)*/
height: number;
loop?: boolean;
autoplay?: boolean;
muted?: boolean;
};
/** 示例小程序中使用的一些配置 */
export interface MiniProgramMeta {
/** 用于统计加载相关信息 */
useLoaders: Loader[];
/** 通用 info */
info: TagItem[][];
/** 特殊 info */
infoPanel?: {
left?: [string, string][];
right?: [string, string][];
};
/** 分屏控件配置 */
needSlider?: {
/** 方向 */
direction?: 'horizontal' | 'vertical';
/** 初始偏移 0-100 */
initPosition?: number;
};
/** 操作摇杆控件 */
needArrowControls?: boolean;
/** 默认需要的画布类型 */
canvasType?: '2d' | 'webgl' | 'webgl2';
/** 为保持效果一致所需要的画布样式 */
canvasStyle?: {
bgColor?: string;
width?: number | string;
height?: number | string;
};
/** 部分示例需要在加载前进行一些提示 */
initAfterConfirm?: {
/**
* 提示类型
* @default 'default'
* */
type?: 'warning' | 'default';
text: string[];
};
}
export interface BaseTag<T extends string> {
tag: T;
content: string;
}
export interface ATag extends BaseTag<'a'> {
link: string;
}
export type TextTag = BaseTag<'text'>;
export type TagItem = TextTag | ATag;