misc_exporter_gltf
对应 three.js 示例地址 。
仅需关注 init
函数的内容,其他部分都是示例小程序所使用的描述配置。
js
import * as THREE from "three";
import { GLTFExporter } from "three/examples/jsm/exporters/GLTFExporter.js";
import { GLTFLoader } from "three/examples/jsm/loaders/GLTFLoader.js";
import { KTX2Loader } from "three/examples/jsm/loaders/KTX2Loader.js";
import { MeshoptDecoder } from "three/examples/jsm/libs/meshopt_decoder.module.js";
/** @type {import("@minisheeep/mp-three-examples").OfficialExampleInfo} */
const exampleInfo = {
name: "misc_exporter_gltf",
useLoaders: [GLTFLoader, KTX2Loader],
info: [
[
{
tag: "a",
link: "https://threejs.org",
content: "three.js"
},
{
tag: "text",
content: "webgl - exporter - gltf"
}
]
],
init: ({
window,
canvas,
GUI,
Stats,
needToDispose,
useFrame,
saveFile,
requestLoading,
cancelLoading
}) => {
function exportGLTF(input) {
const gltfExporter = new GLTFExporter();
const options = {
trs: params.trs,
onlyVisible: params.onlyVisible,
binary: params.binary,
maxTextureSize: params.maxTextureSize
};
requestLoading({
title: "生成中",
mask: true
});
gltfExporter.parse(
input,
async function(result) {
cancelLoading();
const prefix = Math.floor(Date.now() / 1e3);
if (result instanceof ArrayBuffer) {
await saveFile(prefix + "scene.glb", result);
} else {
const output = JSON.stringify(result);
await saveFile(prefix + "scene.gltf", output);
}
},
function(error) {
console.log("An error happened during parsing", error);
},
options
);
}
let camera, object, object2, material, geometry, scene1, scene2, renderer;
let gridHelper, sphere, model, coffeemat;
const params = {
trs: false,
onlyVisible: true,
binary: false,
maxTextureSize: 4096,
exportScene1,
exportScenes,
exportSphere,
exportModel,
exportObjects,
exportSceneObject,
exportCompressedObject
};
init();
function init() {
const data = new Uint8ClampedArray(100 * 100 * 4);
for (let y = 0; y < 100; y++) {
for (let x = 0; x < 100; x++) {
const stride = 4 * (100 * y + x);
data[stride] = Math.round(255 * y / 99);
data[stride + 1] = Math.round(255 - 255 * y / 99);
data[stride + 2] = 0;
data[stride + 3] = 255;
}
}
const gradientTexture = new THREE.DataTexture(data, 100, 100, THREE.RGBAFormat);
gradientTexture.minFilter = THREE.LinearFilter;
gradientTexture.magFilter = THREE.LinearFilter;
gradientTexture.needsUpdate = true;
scene1 = new THREE.Scene();
scene1.name = "Scene1";
camera = new THREE.PerspectiveCamera(45, window.innerWidth / window.innerHeight, 1, 2e3);
camera.position.set(600, 400, 0);
camera.name = "PerspectiveCamera";
scene1.add(camera);
const ambientLight = new THREE.AmbientLight(13421772);
ambientLight.name = "AmbientLight";
scene1.add(ambientLight);
const dirLight = new THREE.DirectionalLight(16777215, 3);
dirLight.target.position.set(0, 0, -1);
dirLight.add(dirLight.target);
dirLight.lookAt(-1, -1, 0);
dirLight.name = "DirectionalLight";
scene1.add(dirLight);
gridHelper = new THREE.GridHelper(2e3, 20, 12698049, 9276813);
gridHelper.position.y = -50;
gridHelper.name = "Grid";
scene1.add(gridHelper);
const axes = new THREE.AxesHelper(500);
axes.name = "AxesHelper";
scene1.add(axes);
const mapGrid = new THREE.TextureLoader().load("textures/uv_grid_opengl.jpg");
mapGrid.wrapS = mapGrid.wrapT = THREE.RepeatWrapping;
mapGrid.colorSpace = THREE.SRGBColorSpace;
material = new THREE.MeshBasicMaterial({
color: 16777215,
map: mapGrid
});
object = new THREE.Mesh(new THREE.IcosahedronGeometry(75, 0), material);
object.position.set(-200, 0, 200);
object.name = "Icosahedron";
scene1.add(object);
material = new THREE.MeshBasicMaterial({
color: 255,
wireframe: true
});
object = new THREE.Mesh(new THREE.OctahedronGeometry(75, 1), material);
object.position.set(0, 0, 200);
object.name = "Octahedron";
scene1.add(object);
material = new THREE.MeshBasicMaterial({
color: 16711680,
transparent: true,
opacity: 0.5
});
object = new THREE.Mesh(new THREE.TetrahedronGeometry(75, 0), material);
object.position.set(200, 0, 200);
object.name = "Tetrahedron";
scene1.add(object);
material = new THREE.MeshStandardMaterial({
color: 16776960,
metalness: 0.5,
roughness: 1,
flatShading: true
});
material.map = gradientTexture;
material.bumpMap = mapGrid;
sphere = new THREE.Mesh(new THREE.SphereGeometry(70, 10, 10), material);
sphere.position.set(0, 0, 0);
sphere.name = "Sphere";
scene1.add(sphere);
material = new THREE.MeshStandardMaterial({
color: 16711935,
flatShading: true
});
object = new THREE.Mesh(new THREE.CylinderGeometry(10, 80, 100), material);
object.position.set(200, 0, 0);
object.name = "Cylinder";
scene1.add(object);
material = new THREE.MeshStandardMaterial({
color: 16711680,
roughness: 1
});
object = new THREE.Mesh(new THREE.TorusKnotGeometry(50, 15, 40, 10), material);
object.position.set(-200, 0, 0);
object.name = "Cylinder";
scene1.add(object);
const mapWood = new THREE.TextureLoader().load("textures/hardwood2_diffuse.jpg");
material = new THREE.MeshStandardMaterial({ map: mapWood, side: THREE.DoubleSide });
object = new THREE.Mesh(new THREE.BoxGeometry(40, 100, 100), material);
object.position.set(-200, 0, 400);
object.name = "Cube";
scene1.add(object);
object2 = new THREE.Mesh(new THREE.BoxGeometry(40, 40, 40, 2, 2, 2), material);
object2.position.set(0, 0, 50);
object2.rotation.set(0, 45, 0);
object2.name = "SubCube";
object.add(object2);
const group1 = new THREE.Group();
group1.name = "Group";
scene1.add(group1);
const group2 = new THREE.Group();
group2.name = "subGroup";
group2.position.set(0, 50, 0);
group1.add(group2);
object2 = new THREE.Mesh(new THREE.BoxGeometry(30, 30, 30), material);
object2.name = "Cube in group";
object2.position.set(0, 0, 400);
group2.add(object2);
geometry = new THREE.BufferGeometry();
let numPoints = 100;
let positions = new Float32Array(numPoints * 3);
for (let i = 0; i < numPoints; i++) {
positions[i * 3] = i;
positions[i * 3 + 1] = Math.sin(i / 2) * 20;
positions[i * 3 + 2] = 0;
}
geometry.setAttribute("position", new THREE.BufferAttribute(positions, 3));
object = new THREE.Line(geometry, new THREE.LineBasicMaterial({ color: 16776960 }));
object.position.set(-50, 0, -200);
scene1.add(object);
geometry = new THREE.BufferGeometry();
numPoints = 5;
const radius = 70;
positions = new Float32Array(numPoints * 3);
for (let i = 0; i < numPoints; i++) {
const s = i * Math.PI * 2 / numPoints;
positions[i * 3] = radius * Math.sin(s);
positions[i * 3 + 1] = radius * Math.cos(s);
positions[i * 3 + 2] = 0;
}
geometry.setAttribute("position", new THREE.BufferAttribute(positions, 3));
object = new THREE.LineLoop(geometry, new THREE.LineBasicMaterial({ color: 16776960 }));
object.position.set(0, 0, -200);
scene1.add(object);
numPoints = 100;
const pointsArray = new Float32Array(numPoints * 3);
for (let i = 0; i < numPoints; i++) {
pointsArray[3 * i] = -50 + Math.random() * 100;
pointsArray[3 * i + 1] = Math.random() * 100;
pointsArray[3 * i + 2] = -50 + Math.random() * 100;
}
const pointsGeo = new THREE.BufferGeometry();
pointsGeo.setAttribute("position", new THREE.BufferAttribute(pointsArray, 3));
const pointsMaterial = new THREE.PointsMaterial({ color: 16776960, size: 5 });
const pointCloud = new THREE.Points(pointsGeo, pointsMaterial);
pointCloud.name = "Points";
pointCloud.position.set(-200, 0, -200);
scene1.add(pointCloud);
const cameraOrtho = new THREE.OrthographicCamera(
window.innerWidth / -2,
window.innerWidth / 2,
window.innerHeight / 2,
window.innerHeight / -2,
0.1,
10
);
scene1.add(cameraOrtho);
cameraOrtho.name = "OrthographicCamera";
material = new THREE.MeshLambertMaterial({
color: 16776960,
side: THREE.DoubleSide
});
object = new THREE.Mesh(new THREE.CircleGeometry(50, 20, 0, Math.PI * 2), material);
object.position.set(200, 0, -400);
scene1.add(object);
object = new THREE.Mesh(new THREE.RingGeometry(10, 50, 20, 5, 0, Math.PI * 2), material);
object.position.set(0, 0, -400);
scene1.add(object);
object = new THREE.Mesh(new THREE.CylinderGeometry(25, 75, 100, 40, 5), material);
object.position.set(-200, 0, -400);
scene1.add(object);
const points = [];
for (let i = 0; i < 50; i++) {
points.push(
new THREE.Vector2(Math.sin(i * 0.2) * Math.sin(i * 0.1) * 15 + 50, (i - 5) * 2)
);
}
object = new THREE.Mesh(new THREE.LatheGeometry(points, 20), material);
object.position.set(200, 0, 400);
scene1.add(object);
material = new THREE.MeshBasicMaterial({
color: 16711680
});
object = new THREE.Mesh(new THREE.BoxGeometry(200, 200, 200), material);
object.position.set(0, 0, 0);
object.name = "CubeHidden";
object.visible = false;
scene1.add(object);
const loader = new GLTFLoader();
loader.load("models/gltf/ShaderBall.glb", function(gltf) {
model = gltf.scene;
model.scale.setScalar(50);
model.position.set(200, -40, -200);
scene1.add(model);
});
material = new THREE.MeshBasicMaterial({
color: 16777215
});
object = new THREE.InstancedMesh(new THREE.BoxGeometry(10, 10, 10, 2, 2, 2), material, 50);
const matrix = new THREE.Matrix4();
const color = new THREE.Color();
for (let i = 0; i < 50; i++) {
matrix.setPosition(
Math.random() * 100 - 50,
Math.random() * 100 - 50,
Math.random() * 100 - 50
);
object.setMatrixAt(i, matrix);
object.setColorAt(i, color.setHSL(i / 50, 1, 0.5));
}
object.position.set(400, 0, 200);
scene1.add(object);
scene2 = new THREE.Scene();
object = new THREE.Mesh(new THREE.BoxGeometry(100, 100, 100), material);
object.position.set(0, 0, 0);
object.name = "Cube2ndScene";
scene2.name = "Scene2";
scene2.add(object);
renderer = new THREE.WebGLRenderer({ antialias: true, canvas });
renderer.setPixelRatio(window.devicePixelRatio);
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.setAnimationLoop(animate);
renderer.toneMapping = THREE.ACESFilmicToneMapping;
renderer.toneMappingExposure = 1;
window.addEventListener("resize", onWindowResize);
const ktx2Loader = new KTX2Loader().setTranscoderPath("jsm/libs/basis/").detectSupport(renderer);
const gltfLoader = new GLTFLoader().setPath("models/gltf/");
gltfLoader.setKTX2Loader(ktx2Loader);
gltfLoader.setMeshoptDecoder(MeshoptDecoder);
gltfLoader.load("coffeemat.glb", function(gltf) {
gltf.scene.position.x = 400;
gltf.scene.position.z = -200;
scene1.add(gltf.scene);
coffeemat = gltf.scene;
});
const gui = new GUI();
let h = gui.addFolder("Settings");
h.add(params, "trs").name("Use TRS");
h.add(params, "onlyVisible").name("Only Visible Objects");
h.add(params, "binary").name("Binary (GLB)");
h.add(params, "maxTextureSize", 2, 8192).name("Max Texture Size").step(1);
h = gui.addFolder("Export");
h.add(params, "exportScene1").name("Export Scene 1");
h.add(params, "exportScenes").name("Export Scene 1 and 2");
h.add(params, "exportSphere").name("Export Sphere");
h.add(params, "exportModel").name("Export Model");
h.add(params, "exportObjects").name("Export Sphere With Grid");
h.add(params, "exportSceneObject").name("Export Scene 1 and Object");
h.add(params, "exportCompressedObject").name("Export Coffeemat (from compressed data)");
gui.open();
needToDispose(renderer, scene1, scene2);
}
function exportScene1() {
exportGLTF(scene1);
}
function exportScenes() {
exportGLTF([scene1, scene2]);
}
function exportSphere() {
exportGLTF(sphere);
}
function exportModel() {
exportGLTF(model);
}
function exportObjects() {
exportGLTF([sphere, gridHelper]);
}
function exportSceneObject() {
exportGLTF([scene1, gridHelper]);
}
function exportCompressedObject() {
exportGLTF([coffeemat]);
}
function onWindowResize() {
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
renderer.setSize(window.innerWidth, window.innerHeight);
}
function animate() {
const timer = Date.now() * 1e-4;
camera.position.x = Math.cos(timer) * 800;
camera.position.z = Math.sin(timer) * 800;
camera.lookAt(scene1.position);
renderer.render(scene1, camera);
}
}
};
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;