webgl_shadowmap_pcss
对应 three.js 示例地址 。
仅需关注 init
函数的内容,其他部分都是示例小程序所使用的描述配置。
js
import * as THREE from "three";
import { OrbitControls } from "three/examples/jsm/controls/OrbitControls.js";
var webgl_shadowmap_pcss_default = "#define LIGHT_WORLD_SIZE 0.005\n#define LIGHT_FRUSTUM_WIDTH 3.75\n#define LIGHT_SIZE_UV (LIGHT_WORLD_SIZE / LIGHT_FRUSTUM_WIDTH)\n#define NEAR_PLANE 9.5\n\n#define NUM_SAMPLES 17\n#define NUM_RINGS 11\n#define BLOCKER_SEARCH_NUM_SAMPLES NUM_SAMPLES\n\nvec2 poissonDisk[NUM_SAMPLES];\n\nvoid initPoissonSamples(const in vec2 randomSeed) {\n float ANGLE_STEP = PI2 * float(NUM_RINGS) / float(NUM_SAMPLES);\n float INV_NUM_SAMPLES = 1.0 / float(NUM_SAMPLES);\n\n \n float angle = rand(randomSeed) * PI2;\n float radius = INV_NUM_SAMPLES;\n float radiusStep = radius;\n\n for (int i = 0; i < NUM_SAMPLES; i++) {\n poissonDisk[i] = vec2(cos(angle), sin(angle)) * pow(radius, 0.75);\n radius += radiusStep;\n angle += ANGLE_STEP;\n }\n}\n\nfloat penumbraSize(const in float zReceiver, const in float zBlocker) { \n return (zReceiver - zBlocker) / zBlocker;\n}\n\nfloat findBlocker(sampler2D shadowMap, const in vec2 uv, const in float zReceiver) {\n \n \n float searchRadius = LIGHT_SIZE_UV * (zReceiver - NEAR_PLANE) / zReceiver;\n float blockerDepthSum = 0.0;\n int numBlockers = 0;\n\n for (int i = 0; i < BLOCKER_SEARCH_NUM_SAMPLES; i++) {\n float shadowMapDepth = unpackRGBAToDepth(texture2D(shadowMap, uv + poissonDisk[i] * searchRadius));\n if (shadowMapDepth < zReceiver) {\n blockerDepthSum += shadowMapDepth;\n numBlockers++;\n }\n }\n\n if (numBlockers == 0) return -1.0;\n\n return blockerDepthSum / float(numBlockers);\n}\n\nfloat PCF_Filter(sampler2D shadowMap, vec2 uv, float zReceiver, float filterRadius) {\n float sum = 0.0;\n float depth;\n #pragma unroll_loop_start\n for (int i = 0; i < 17; i++) {\n depth = unpackRGBAToDepth(texture2D(shadowMap, uv + poissonDisk[i] * filterRadius));\n if (zReceiver <= depth) sum += 1.0;\n }\n #pragma unroll_loop_end\n #pragma unroll_loop_start\n for (int i = 0; i < 17; i++) {\n depth = unpackRGBAToDepth(texture2D(shadowMap, uv + -poissonDisk[i].yx * filterRadius));\n if (zReceiver <= depth) sum += 1.0;\n }\n #pragma unroll_loop_end\n return sum / (2.0 * float(17));\n}\n\nfloat PCSS(sampler2D shadowMap, vec4 coords) {\n vec2 uv = coords.xy;\n float zReceiver = coords.z; \n\n initPoissonSamples(uv);\n \n float avgBlockerDepth = findBlocker(shadowMap, uv, zReceiver);\n\n \n if (avgBlockerDepth == -1.0) return 1.0;\n\n \n float penumbraRatio = penumbraSize(zReceiver, avgBlockerDepth);\n float filterRadius = penumbraRatio * LIGHT_SIZE_UV * NEAR_PLANE / zReceiver;\n\n \n \n return PCF_Filter(shadowMap, uv, zReceiver, filterRadius);\n}";
/** @type {import("@minisheeep/mp-three-examples").OfficialExampleInfo} */
const exampleInfo = {
name: "webgl_shadowmap_pcss",
useLoaders: [],
info: [
[
{
tag: "text",
content: "Percent Closer Soft-Shadows (PCSS) by"
},
{
tag: "a",
link: "http://eduperiment.com",
content: "spidersharma03"
}
]
],
init: ({ window, canvas, GUI, Stats, needToDispose, useFrame }) => {
let stats;
let camera, scene, renderer;
let group;
init();
function init() {
scene = new THREE.Scene();
scene.fog = new THREE.Fog(13426943, 5, 100);
camera = new THREE.PerspectiveCamera(30, window.innerWidth / window.innerHeight, 1, 1e4);
camera.position.x = 7;
camera.position.y = 13;
camera.position.z = 7;
scene.add(camera);
scene.add(new THREE.AmbientLight(11184810, 3));
const light = new THREE.DirectionalLight(15791871, 4.5);
light.position.set(2, 8, 4);
light.castShadow = true;
light.shadow.mapSize.width = 1024;
light.shadow.mapSize.height = 1024;
light.shadow.camera.far = 20;
scene.add(light);
scene.add(new THREE.CameraHelper(light.shadow.camera));
group = new THREE.Group();
scene.add(group);
const geometry = new THREE.SphereGeometry(0.3, 20, 20);
for (let i = 0; i < 20; i++) {
const material = new THREE.MeshPhongMaterial({ color: Math.random() * 16777215 });
const sphere = new THREE.Mesh(geometry, material);
sphere.position.x = Math.random() - 0.5;
sphere.position.z = Math.random() - 0.5;
sphere.position.normalize();
sphere.position.multiplyScalar(Math.random() * 2 + 1);
sphere.castShadow = true;
sphere.receiveShadow = true;
sphere.userData.phase = Math.random() * Math.PI;
group.add(sphere);
}
const groundMaterial = new THREE.MeshPhongMaterial({ color: 9013641 });
const ground = new THREE.Mesh(new THREE.PlaneGeometry(2e4, 2e4, 8, 8), groundMaterial);
ground.rotation.x = -Math.PI / 2;
ground.receiveShadow = true;
scene.add(ground);
const column = new THREE.Mesh(new THREE.BoxGeometry(1, 4, 1), groundMaterial);
column.position.y = 2;
column.castShadow = true;
column.receiveShadow = true;
scene.add(column);
let shader = THREE.ShaderChunk.shadowmap_pars_fragment;
shader = shader.replace("#ifdef USE_SHADOWMAP", "#ifdef USE_SHADOWMAP\n" + webgl_shadowmap_pcss_default);
shader = shader.replace(
"#if defined( SHADOWMAP_TYPE_PCF )",
`return PCSS( shadowMap, shadowCoord );
#if defined( SHADOWMAP_TYPE_PCF )`
);
THREE.ShaderChunk.shadowmap_pars_fragment = shader;
renderer = new THREE.WebGLRenderer({ antialias: true, canvas });
renderer.setPixelRatio(window.devicePixelRatio);
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.setAnimationLoop(animate);
renderer.setClearColor(scene.fog.color);
renderer.shadowMap.enabled = true;
const controls = new OrbitControls(camera, renderer.domElement);
controls.maxPolarAngle = Math.PI * 0.5;
controls.minDistance = 10;
controls.maxDistance = 75;
controls.target.set(0, 2.5, 0);
controls.update();
stats = new Stats(renderer);
window.addEventListener("resize", onWindowResize);
needToDispose(renderer, scene, controls);
}
function onWindowResize() {
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
renderer.setSize(window.innerWidth, window.innerHeight);
}
const startTime = Date.now();
function animate() {
const time = (Date.now() - startTime) / 1e3;
group.traverse(function(child) {
if ("phase" in child.userData) {
child.position.y = Math.abs(Math.sin(time + child.userData.phase)) * 4 + 0.3;
}
});
renderer.render(scene, camera);
stats.update();
}
}
};
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;