Skip to content

webgl_postprocessing_pixel

对应 three.js 示例地址

仅需关注 init 函数的内容,其他部分都是示例小程序所使用的描述配置。

js
import * as THREE from "three";
import { OrbitControls } from "three/examples/jsm/controls/OrbitControls.js";
import { EffectComposer } from "three/examples/jsm/postprocessing/EffectComposer.js";
import { RenderPixelatedPass } from "three/examples/jsm/postprocessing/RenderPixelatedPass.js";
import { OutputPass } from "three/examples/jsm/postprocessing/OutputPass.js";

/** @type {import("@minisheeep/mp-three-examples").OfficialExampleInfo} */
const exampleInfo = {
  name: "webgl_postprocessing_pixel",
  useLoaders: [],
  info: [
    [
      {
        tag: "a",
        link: "https://threejs.org",
        content: "three.js"
      },
      {
        tag: "text",
        content: "- Pixelation pass with optional single pixel outlines by"
      },
      {
        tag: "a",
        link: "https://github.com/KodyJKing",
        content: "Kody King"
      }
    ]
  ],
  init: ({ window, canvas, GUI, Stats, needToDispose, useFrame }) => {
    let camera, scene, renderer, composer, crystalMesh, clock;
    let gui, params;
    init();
    function init() {
      const aspectRatio = window.innerWidth / window.innerHeight;
      camera = new THREE.OrthographicCamera(-aspectRatio, aspectRatio, 1, -1, 0.1, 10);
      camera.position.y = 2 * Math.tan(Math.PI / 6);
      camera.position.z = 2;
      scene = new THREE.Scene();
      scene.background = new THREE.Color(1382185);
      clock = new THREE.Clock();
      renderer = new THREE.WebGLRenderer({ canvas });
      renderer.shadowMap.enabled = true;
      renderer.setSize(window.innerWidth, window.innerHeight);
      renderer.setAnimationLoop(animate);
      composer = new EffectComposer(renderer);
      const renderPixelatedPass = new RenderPixelatedPass(6, scene, camera);
      composer.addPass(renderPixelatedPass);
      const outputPass = new OutputPass();
      composer.addPass(outputPass);
      window.addEventListener("resize", onWindowResize);
      const controls = new OrbitControls(camera, renderer.domElement);
      controls.maxZoom = 2;
      gui = new GUI();
      params = {
        pixelSize: 6,
        normalEdgeStrength: 0.3,
        depthEdgeStrength: 0.4,
        pixelAlignedPanning: true
      };
      gui.add(params, "pixelSize").min(1).max(16).step(1).onChange(() => {
        renderPixelatedPass.setPixelSize(params.pixelSize);
      });
      gui.add(renderPixelatedPass, "normalEdgeStrength").min(0).max(2).step(0.05);
      gui.add(renderPixelatedPass, "depthEdgeStrength").min(0).max(1).step(0.05);
      gui.add(params, "pixelAlignedPanning");
      const loader = new THREE.TextureLoader();
      const texChecker = pixelTexture(loader.load("textures/checker.png"));
      const texChecker2 = pixelTexture(loader.load("textures/checker.png"));
      texChecker.repeat.set(3, 3);
      texChecker2.repeat.set(1.5, 1.5);
      const boxMaterial = new THREE.MeshPhongMaterial({ map: texChecker2 });
      function addBox(boxSideLength, x, z, rotation) {
        const mesh = new THREE.Mesh(
          new THREE.BoxGeometry(boxSideLength, boxSideLength, boxSideLength),
          boxMaterial
        );
        mesh.castShadow = true;
        mesh.receiveShadow = true;
        mesh.rotation.y = rotation;
        mesh.position.y = boxSideLength / 2;
        mesh.position.set(x, boxSideLength / 2 + 1e-4, z);
        scene.add(mesh);
        return mesh;
      }
      addBox(0.4, 0, 0, Math.PI / 4);
      addBox(0.5, -0.5, -0.5, Math.PI / 4);
      const planeSideLength = 2;
      const planeMesh = new THREE.Mesh(
        new THREE.PlaneGeometry(planeSideLength, planeSideLength),
        new THREE.MeshPhongMaterial({ map: texChecker })
      );
      planeMesh.receiveShadow = true;
      planeMesh.rotation.x = -Math.PI / 2;
      scene.add(planeMesh);
      const radius = 0.2;
      const geometry = new THREE.IcosahedronGeometry(radius);
      crystalMesh = new THREE.Mesh(
        geometry,
        new THREE.MeshPhongMaterial({
          color: 6862825,
          emissive: 5209739,
          shininess: 10,
          specular: 16777215
        })
      );
      crystalMesh.receiveShadow = true;
      crystalMesh.castShadow = true;
      scene.add(crystalMesh);
      scene.add(new THREE.AmbientLight(7700366, 3));
      const directionalLight = new THREE.DirectionalLight(16776909, 1.5);
      directionalLight.position.set(100, 100, 100);
      directionalLight.castShadow = true;
      directionalLight.shadow.mapSize.set(2048, 2048);
      scene.add(directionalLight);
      const spotLight = new THREE.SpotLight(16761088, 10, 10, Math.PI / 16, 0.02, 2);
      spotLight.position.set(2, 2, 0);
      const target = spotLight.target;
      scene.add(target);
      target.position.set(0, 0, 0);
      spotLight.castShadow = true;
      scene.add(spotLight);
      needToDispose(renderer, scene, controls, composer, loader);
    }
    function onWindowResize() {
      const aspectRatio = window.innerWidth / window.innerHeight;
      camera.left = -aspectRatio;
      camera.right = aspectRatio;
      camera.updateProjectionMatrix();
      renderer.setSize(window.innerWidth, window.innerHeight);
      composer.setSize(window.innerWidth, window.innerHeight);
    }
    function animate() {
      const t = clock.getElapsedTime();
      crystalMesh.material.emissiveIntensity = Math.sin(t * 3) * 0.5 + 0.5;
      crystalMesh.position.y = 0.7 + Math.sin(t * 2) * 0.05;
      crystalMesh.rotation.y = stopGoEased(t, 2, 4) * 2 * Math.PI;
      const rendererSize = renderer.getSize(new THREE.Vector2());
      const aspectRatio = rendererSize.x / rendererSize.y;
      if (params["pixelAlignedPanning"]) {
        pixelAlignFrustum(
          camera,
          aspectRatio,
          Math.floor(rendererSize.x / params["pixelSize"]),
          Math.floor(rendererSize.y / params["pixelSize"])
        );
      } else if (camera.left != -aspectRatio || camera.top != 1) {
        camera.left = -aspectRatio;
        camera.right = aspectRatio;
        camera.top = 1;
        camera.bottom = -1;
        camera.updateProjectionMatrix();
      }
      composer.render();
    }
    function pixelTexture(texture) {
      texture.minFilter = THREE.NearestFilter;
      texture.magFilter = THREE.NearestFilter;
      texture.generateMipmaps = false;
      texture.wrapS = THREE.RepeatWrapping;
      texture.wrapT = THREE.RepeatWrapping;
      texture.colorSpace = THREE.SRGBColorSpace;
      return texture;
    }
    function easeInOutCubic(x) {
      return x ** 2 * 3 - x ** 3 * 2;
    }
    function linearStep(x, edge0, edge1) {
      const w = edge1 - edge0;
      const m = 1 / w;
      const y0 = -0.5 * edge0;
      return THREE.MathUtils.clamp(y0 + m * x, 0, 1);
    }
    function stopGoEased(x, downtime, period) {
      const cycle = x / period | 0;
      const tween = x - cycle * period;
      const linStep = easeInOutCubic(linearStep(tween, downtime, period));
      return cycle + linStep;
    }
    function pixelAlignFrustum(camera2, aspectRatio, pixelsPerScreenWidth, pixelsPerScreenHeight) {
      const worldScreenWidth = (camera2.right - camera2.left) / camera2.zoom;
      const worldScreenHeight = (camera2.top - camera2.bottom) / camera2.zoom;
      const pixelWidth = worldScreenWidth / pixelsPerScreenWidth;
      const pixelHeight = worldScreenHeight / pixelsPerScreenHeight;
      const camPos = new THREE.Vector3();
      camera2.getWorldPosition(camPos);
      const camRot = new THREE.Quaternion();
      camera2.getWorldQuaternion(camRot);
      const camRight = new THREE.Vector3(1, 0, 0).applyQuaternion(camRot);
      const camUp = new THREE.Vector3(0, 1, 0).applyQuaternion(camRot);
      const camPosRight = camPos.dot(camRight);
      const camPosUp = camPos.dot(camUp);
      const camPosRightPx = camPosRight / pixelWidth;
      const camPosUpPx = camPosUp / pixelHeight;
      const fractX = camPosRightPx - Math.round(camPosRightPx);
      const fractY = camPosUpPx - Math.round(camPosUpPx);
      camera2.left = -aspectRatio - fractX * pixelWidth;
      camera2.right = aspectRatio - fractX * pixelWidth;
      camera2.top = 1 - fractY * pixelHeight;
      camera2.bottom = -1 - fractY * pixelHeight;
      camera2.updateProjectionMatrix();
    }
  }
};
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;