# graphics3d/toon/glbmeshreader (vanilla.js 0.4.0)

> https://vanillapunch.com/docs/vanilla.js/0.4.0/api/graphics3d/toon/glbmeshreader/

점토 모형(GLB) 읽기와 뼈대 자세. (툰 3D 의 MeshBuilder 꼭짓점 배열로, 외계행성 광부 키우기에서 왔다)

재질 색으로 칠하는 모형을 읽는다. 텍스처 좌표와 재질 텍스처가 있으면 그것도 읽는다.
  - 부품 하나가 노드 하나이고, 노드의 메시는 색마다 프리미티브 하나이다. 꼭짓점은 위치와 노멀, 뼈대가 있으면 본 번호와 무게이다.
    노멀이 없는 프리미티브는 glTF 2.0 명세대로 평평한 노멀(삼각형마다 하나)로 읽는다. 꼭짓점을 삼각형마다 따로 풀어 면 노멀을 준다. (새로 짓는 바깥선 껍데기도 같다)
  - 재질의 baseColorFactor 는 선형 색이라 sRGB 로 바꿔 담고(감마 색 공간은 pow 1 / 2.2, 선형 색 공간은 sRGB 표준 곡선, 셰이더가 푸는 곡선의 역), emissiveFactor 가 있으면 빛남으로 담는다. (emissiveTexture 가 있으면 빛남은 재질 범위로만 넘긴다)
  - TEXCOORD_0 이 있으면 uvData 로, TEXCOORD_1 이 있으면 uv1Data(2 번 UV, 천사 고리)로 담는다. 프리미티브마다 재질 범위(materialRanges)를 담는다.
    { name 재질 이름, materialIndex, nodeName, indexStart, indexCount, extras 재질 extras, alphaMode, alphaCutoff, baseColorFactor 선형, emissiveFactor 선형, baseColorImage, emissiveImage (images 차례, 없으면 -1), hasUv }
    부품 안에서 칸을 갈라 칠할 때(강조색 칸, 표시판) 재질 이름이나 extras 로 고르고 ToonRenderer.drawMesh 의 indexStart, indexCount 로 그 칸만 그린다.
  - 그림은 readGlbImages 로 읽고 decodeGlbImage 로 풀어 ToonRenderer.createTexture 에 넘긴다.
  - 재질 extras 의 outline 은 바깥선 껍데기(뒷면만 그림), basic 은 빛을 받지 않는 부품이다.
    outlineOptions 를 주면 그 껍데기는 담지 않고, ".outline" 짝이 있는 노드의 몸으로 점마다 같은 굵기의 껍데기를 새로 짓는다. (MeshBuilder.addTriangleShell)
  - 뼈대(skin)가 있으면 본 노드와 그 거꾸로 묶는 행렬, 움직임(animations)과 그 extras(치기의 hitAt, 한 번만 트는 loop "once" 등)를 함께 읽는다. 자세는 writeSkinPose 가 셈한다.
  - 부품을 따로 숨기거나 칠하는 모형(무더기의 결정 여럿처럼)은 readGlbNodeArrays 로 노드마다 따로 읽는다.
    노드 extras(문과 다리가 도는 자리 pivot 등)는 그 부품의 extras 로 함께 담는다.
  - 한 덩이로 읽은 뼈대 모형(탈것 같은)의 노드 extras 와 부품의 자리, 따르는 본은 readGlbNodeInfos 로 따로 읽는다.
  - 꼭짓점 속성을 정수로 담은 GLB(KHR_mesh_quantization)도 읽는다. 정규화 정수는 glTF 명세의 공식으로 나누고, 텍스처 좌표는 재질 텍스처의 KHR_texture_transform 을 구워 넣는다.
    이름 없는 메시 노드는 이름 있는 부모 노드의 부품에 든다. (양자화 도구가 되풀이 변환을 맡기는 잎 노드) extensionsRequired 에 읽지 못하는 확장(meshopt 압축 등)이 있으면 오류를 던진다.
엔진의 GLB 읽기는 엔진의 PBR 모형(SkinnedModel) 안에 묶여 있어, 툰 그리기에 쓸 꼭짓점 배열만 여기서 뽑는다.

예제: GLB 모형을 읽어 움직임 자세로 그리기

```js
import { ToonRenderer, readGlbArrays, writeSkinPose, Camera3D, Matrix4, Vector3 } from "./vanilla.js";
const webGL2RenderingContext = document.createElement("canvas").getContext("webgl2");
const renderer = new ToonRenderer(webGL2RenderingContext);
const arrayBuffer = await (await fetch("examples/ancientmountain/assets/fox.glb")).arrayBuffer();
const arrays = readGlbArrays(arrayBuffer, { width: 1.5, addedParts: ["fox"] });
const mesh = renderer.createMesh(arrays);
const skeleton = arrays.skeleton;
const jointMatrices = skeleton !== null ? new Float32Array(skeleton.joints.length * 16) : null;
if (skeleton !== null) {
	writeSkinPose(skeleton, "Survey", 0.5, jointMatrices);
}
const camera = new Camera3D();
camera.setPerspective(0.8, 0.1, 100);
camera.lookAt(Vector3.create(0, 1, 3), Vector3.create(0, 0.4, 0), Vector3.create(0, 1, 0));
renderer.beginFrameWithCamera(camera);
renderer.drawMesh(mesh, Matrix4.createScale(0.01, 0.01, 0.01), { jointMatrices: jointMatrices });
renderer.endFrame();
```

## Functions and constants

- `readGlbArrays(arrayBuffer, outlineOptions = null, colorSpace = readEngineColorSpace())` (method, since 0.4.0): GLB 하나를 꼭짓점 배열로. (MeshBuilder.readArrays 의 꼴, 뼈대가 있으면 skeleton 도)
  - `arrayBuffer` ArrayBuffer: GLB 파일 전체.
  - `outlineOptions` object | null: { width, partWidths, addedParts, innerParts, innerOverParts, innerWidth } 주면 GLB 의 바깥선 껍데기 대신 ".outline" 짝이 있는 노드의 몸으로 껍데기를 새로 짓는다. (모형 좌표의 굵기, partWidths 는 노드 이름마다, addedParts 는 짝이 없어도 껍데기를 지을 노드 이름)
  width 가 0 이면 껍데기를 하나도 짓지 않는다. (GLB 의 껍데기도 담지 않음)
  innerParts(노드 이름들)는 innerWidth 가 0 보다 크면 그 굵기의 껍데기를 하나 더 지어 바깥선 껍데기 끝에 담고, 그 자리를 innerOutlineRanges({ start, count } 들)로 돌려준다. (몸을 그린 뒤 그 부위를 둘레의 가는 선과 함께 한 번 더 그림)
  innerParts 와 그 위에 얹힌 innerOverParts(노드 이름들, 유리 위의 빛 반사 등)의 몸이 든 자리는 GLB 의 노드 차례대로 innerBodyRanges 로 돌려준다. (innerParts 가 없으면 빔)
  - `colorSpace` string: 색 공간. (ColorSpace, 기본은 엔진의 색 공간, 그릴 ToonRenderer 의 getColorSpace 와 같은 값. 선형 baseColorFactor 를 꼭짓점 sRGB 색으로 바꾸는 곡선을 고른다)
  - returns object: MeshBuilder.readArrays 의 꼴과 skeleton (없으면 null), innerOutlineRanges, innerBodyRanges. (ToonRenderer.createMesh 에 넘긴다)

  예제: 재질 범위마다 따로 칠하기

  ```js
  import { ToonRenderer, readGlbArrays, Camera3D, Matrix4, Vector3 } from "./vanilla.js";
  const webGL2RenderingContext = document.createElement("canvas").getContext("webgl2");
  const renderer = new ToonRenderer(webGL2RenderingContext);
  const arrayBuffer = await (await fetch("examples/ancientmountain/assets/mannequin_female.glb")).arrayBuffer();
  const arrays = readGlbArrays(arrayBuffer, { width: 1.5, partWidths: { Mannequin_F: 0.8 }, addedParts: ["Mannequin_F"] });
  const mesh = renderer.createMesh(arrays);
  const modelMatrix = Matrix4.createIdentity();
  const camera = new Camera3D();
  camera.setPerspective(0.8, 0.1, 100);
  camera.lookAt(Vector3.create(0, 1.5, 4), Vector3.create(0, 1, 0), Vector3.create(0, 1, 0));
  renderer.beginFrameWithCamera(camera);
  for (const materialRange of arrays.materialRanges) {
  	const tintColor = materialRange.name === "M_Joints.001" ? [1, 0.4, 0.3, 1] : [1, 1, 1, 1];
  	renderer.drawMesh(mesh, modelMatrix, { indexStart: materialRange.indexStart, indexCount: materialRange.indexCount, tintColor: tintColor, hasOutline: false });
  }
  renderer.drawMeshOutline(mesh, modelMatrix);
  renderer.endFrame();
  ```

- `readGlbImages(arrayBuffer)` (method, since 0.4.0): GLB 에 든 그림들. ([{ name, mimeType, data: Uint8Array }], images 의 차례, 재질 범위의 baseColorImage, emissiveImage 가 가리킴)
    - 바이너리 덩어리의 bufferView 로 담긴 그림만 읽는다. (바깥 파일 uri 는 data 가 빈 배열)
    - 텍스처로 쓰려면 decodeGlbImage 로 풀어 ToonRenderer.createTexture 에 넘긴다.
  - `arrayBuffer` ArrayBuffer: GLB 파일 전체.
  - returns Array<object>: [{ name, mimeType, data: Uint8Array }] images 차례의 그림.

  예제: 재질의 바탕 그림을 텍스처로 올려 그리기

  ```js
  import { ToonRenderer, readGlbArrays, readGlbImages, decodeGlbImage, Matrix4 } from "./vanilla.js";
  const webGL2RenderingContext = document.createElement("canvas").getContext("webgl2");
  const renderer = new ToonRenderer(webGL2RenderingContext);
  const arrayBuffer = await (await fetch("examples/ancientmountain/assets/mannequin_female.glb")).arrayBuffer();
  const arrays = readGlbArrays(arrayBuffer);
  const mesh = renderer.createMesh(arrays);
  const images = readGlbImages(arrayBuffer);
  const textures = await Promise.all(images.map(async (image) => image.data.length > 0 ? renderer.createTexture(await decodeGlbImage(image)) : null));
  const texturedRange = arrays.materialRanges.find((materialRange) => materialRange.hasUv && materialRange.baseColorImage >= 0);
  if (texturedRange !== undefined) {
  	renderer.drawMesh(mesh, Matrix4.createIdentity(), { indexStart: texturedRange.indexStart, indexCount: texturedRange.indexCount, baseColorTexture: textures[texturedRange.baseColorImage] });
  }
  ```

- `decodeGlbImage(image)` (method, since 0.4.0): readGlbImages 의 그림 하나를 풀기. (ImageBitmap, 알파를 미리 곱하지 않고 색 공간을 바꾸지 않음)
  - `image` object: { mimeType, data }
  - returns Promise<ImageBitmap>: 풀어 낸 그림. (ToonRenderer.createTexture 에 넘긴다)

  예제: 첫 그림 하나를 풀어 텍스처로

  ```js
  import { ToonRenderer, readGlbImages, decodeGlbImage } from "./vanilla.js";
  const renderer = new ToonRenderer(document.createElement("canvas").getContext("webgl2"));
  const arrayBuffer = await (await fetch("examples/ancientmountain/assets/mannequin_female.glb")).arrayBuffer();
  const images = readGlbImages(arrayBuffer);
  if (images.length > 0 && images[0].data.length > 0) {
  	const imageBitmap = await decodeGlbImage(images[0]);
  	const texture = renderer.createTexture(imageBitmap, { isRepeated: false });
  }
  ```

- `readGlbNodeArrays(arrayBuffer, outlineOptions = null, colorSpace = readEngineColorSpace())` (method, since 0.4.0): GLB 하나를 노드 이름마다의 꼭짓점 배열로. ({ 이름: MeshBuilder.readArrays 의 꼴 }, 뼈대는 읽지 않음)
    - 이름 끝의 ".outline" 노드(바깥선 껍데기)는 그 앞 이름의 노드에 함께 담는다. (crystal1 과 crystal1.outline 은 crystal1 하나)
    - 부품마다 그 노드의 extras 를 extras 로 담는다. (없으면 빈 것)
    - 부품마다 비치는 재질(alphaMode BLEND)의 가장 작은 불투명도를 alpha 로 담는다. (없으면 1)
  - `arrayBuffer` ArrayBuffer: GLB 파일 전체.
  - `outlineOptions` object | null: readGlbArrays 와 같음.
  - `colorSpace` string: 색 공간. (readGlbArrays 와 같음, 기본은 엔진의 색 공간)
  - returns object: { 노드 이름: MeshBuilder.readArrays 의 꼴과 extras, alpha } 부품마다의 배열.

  예제: 부품마다 메시를 따로 올려 하나만 숨기기

  ```js
  import { ToonRenderer, readGlbNodeArrays, Camera3D, Matrix4, Vector3 } from "./vanilla.js";
  const renderer = new ToonRenderer(document.createElement("canvas").getContext("webgl2"));
  const arrayBuffer = await (await fetch("examples/ancientmountain/assets/mannequin_female.glb")).arrayBuffer();
  const partArrays = readGlbNodeArrays(arrayBuffer, { width: 1.5, addedParts: ["Mannequin_F"] });
  const parts = Object.entries(partArrays).map(([partName, arrays]) => {
  	return { name: partName, mesh: renderer.createMesh(arrays), pivot: arrays.extras.pivot, alpha: arrays.alpha };
  });
  const camera = new Camera3D();
  camera.setPerspective(0.8, 0.1, 100);
  camera.lookAt(Vector3.create(0, 1.5, 4), Vector3.create(0, 1, 0), Vector3.create(0, 1, 0));
  renderer.beginFrameWithCamera(camera);
  for (const part of parts) {
  	if (part.name === "Mannequin_F") {
  		continue;
  	}
  	const modelMatrix = Matrix4.createScale(0.01, 0.01, 0.01);
  	if (Array.isArray(part.pivot)) {
  		modelMatrix.multiply(Matrix4.createTranslation(part.pivot[0], part.pivot[1], part.pivot[2]));
  	}
  	renderer.drawMesh(part.mesh, modelMatrix);
  }
  renderer.endFrame();
  ```

- `readGlbNodeInfos(arrayBuffer)` (method, since 0.4.0): GLB 의 메시 노드마다의 extras, 가운데, 따르는 본. ({ 이름: { extras, center, jointIndex } }, 이름 끝이 ".outline" 인 노드와 바깥선 재질은 뺌, 이름 없는 메시 노드는 이름 있는 부모 부품에 모음)
    - readGlbArrays 로 한 덩이에 읽은 뼈대 모형에서 노드 extras(body 의 height 등)와 부품의 자리(헬멧 불 등)를 따로 읽을 때 쓴다.
    - center 는 꼭짓점이 놓인 범위의 가운데이다. (모형 좌표, 뼈대로 움직이는 노드는 쉬는 자세의 자리, 꼭짓점이 없으면 원점)
    - jointIndex 는 그 노드의 꼭짓점이 가장 무겁게 딸린 본의 skin 안 차례이다. (writeSkinPose 가 쓴 본 행렬의 차례, 뼈대가 없으면 -1)
      자세를 세운 뒤의 자리는 그 본 행렬로 center 를 옮긴 것이다.
  - `arrayBuffer` ArrayBuffer: GLB 파일 전체.
  - returns object: { 노드 이름: { extras, center [x, y, z], jointIndex } } 메시 노드마다의 정보.

  예제: 걷는 모형의 몸 부품 자리 읽기

  ```js
  import { readGlbArrays, readGlbNodeInfos, writeSkinPose, Matrix4 } from "./vanilla.js";
  const arrayBuffer = await (await fetch("examples/ancientmountain/assets/mannequin_female.glb")).arrayBuffer();
  const skeleton = readGlbArrays(arrayBuffer).skeleton;
  const bodyInfo = readGlbNodeInfos(arrayBuffer)["Mannequin_F"];
  if (skeleton !== null && bodyInfo !== undefined && bodyInfo.jointIndex >= 0) {
  	const jointMatrices = new Float32Array(skeleton.joints.length * 16);
  	writeSkinPose(skeleton, "Walk", 0.25, jointMatrices);
  	const jointMatrix = Matrix4.createIdentity();
  	jointMatrix.getElements().set(jointMatrices.subarray(bodyInfo.jointIndex * 16, bodyInfo.jointIndex * 16 + 16));
  	const bodyPosition = jointMatrix.transformPoint(bodyInfo.center[0], bodyInfo.center[1], bodyInfo.center[2]);
  }
  ```

- `readAnimationSwing(skeleton, animationName, nodeIndex)` (method, since 0.4.0): 움직임에서 한 노드의 돌림이 쉬는 자세에서 가장 벗어난 각. (라디안, 열쇠 프레임마다 보고, 그 노드의 돌림이 없으면 0)
  - `skeleton` object: readGlbArrays 의 skeleton.
  - `animationName` string: 움직임 이름.
  - `nodeIndex` number: skeleton.nodes 의 차례.
  - returns number: 쉬는 자세에서 가장 벗어난 각. (라디안, 없으면 0)

  예제: 꼬리가 크게 흔들리는 만큼만 줄여 자세 셈하기

  ```js
  import { readGlbArrays, readAnimationSwing, writeSkinPose } from "./vanilla.js";
  const arrayBuffer = await (await fetch("examples/ancientmountain/assets/fox.glb")).arrayBuffer();
  const skeleton = readGlbArrays(arrayBuffer).skeleton;
  if (skeleton !== null) {
  	const tailIndex = skeleton.nodes.findIndex((node) => node.name === "b_Tail01_012");
  	const swing = readAnimationSwing(skeleton, "Run", tailIndex);
  	const swingScale = swing > 0.5 ? 0.5 / swing : 1;
  	const jointMatrices = new Float32Array(skeleton.joints.length * 16);
  	writeSkinPose(skeleton, "Run", 0.3, jointMatrices, null, { Run: [{ nodeIndex: tailIndex, scale: swingScale }] });
  }
  ```

- `adjustBones(locals, skeleton, modifiers)` (method, since 0.4.0): 섞은 자세의 뼈마다 지역 변환 고치기. (writeSkinPose 가 움직임을 읽어 섞은 뒤, 스킨 행렬을 짓기 전에 부르는 꼴, 행렬로 둔 노드는 건너뜀)
    - modifiers 의 고침 하나: { nodeIndex 또는 name, translation, rotation, scale, mode, weight } 준 칸만 건다.
    - 고침은 차례대로 걸린다. (같은 뼈에 둘을 주면 앞 고침 위에 뒤 고침)
    - weight 는 고치기 앞과 뒤 사이의 몫이다. (0 이면 그대로, 1 이면 다 고침, 돌림은 가까운 쪽으로 섞어 정규화)
  - `locals` Array<object>: 노드마다의 { translation, rotation, scale, matrix }. (writeSkinPose 의 poseAdjust 고리가 받는 것, 고친 값을 여기에 씀)
  - `skeleton` object: readGlbArrays 의 skeleton.
  - `modifiers` Array<object>: [{ nodeIndex, name, translation, rotation, scale, mode, weight }] 뼈마다의 고침. (nodeIndex 가 없으면 name 으로 찾음, 못 찾으면 건너뜀, mode 는 BoneModifyMode 기본 add, weight 기본 1)

  예제: 고리 안에서 표 고침과 직접 고침을 같이 쓰기

  ```js
  import { readGlbArrays, writeSkinPose, adjustBones } from "./vanilla.js";
  const arrayBuffer = await (await fetch("examples/ancientmountain/assets/fox.glb")).arrayBuffer();
  const skeleton = readGlbArrays(arrayBuffer).skeleton;
  if (skeleton !== null) {
  	const jointMatrices = new Float32Array(skeleton.joints.length * 16);
  	const crouch = 0.6;
  	const half = crouch / 2;
  	writeSkinPose(skeleton, "Survey", 0, jointMatrices, null, null, (locals, poseSkeleton) => {
  		adjustBones(locals, poseSkeleton, [{ name: "b_Spine01_02", rotation: [Math.sin(half), 0, 0, Math.cos(half)] }]);
  		const tailIndex = poseSkeleton.nodes.findIndex((node) => node.name === "b_Tail01_012");
  		locals[tailIndex].scale[1] *= 1.2;
  	});
  }
  ```

- `writeSkinPose(skeleton, animationName, time, target, blend = null, swingScales = null, poseAdjust = null)` (method, since 0.4.0): 뼈대 자세 셈하기. (움직임을 그 시각에서 읽어 본마다 행렬을 target 에 16 씩 씀, 움직임이 없으면 쉬는 자세)
    - blend 를 주면 앞 움직임의 자세를 그 무게만큼 섞는다. (움직임이 바뀔 때 잠깐)
    - swingScales 를 주면 그 움직임의 그 노드는 돌림을 쉬는 자세 쪽으로 줄인다. (움직임을 다시 뽑지 않고 흔들림만 줄일 때, 섞는 앞 자세에도 같이)
    - poseAdjust 를 주면 섞은 뒤, 스킨 행렬을 짓기 전에 뼈마다의 지역 변환을 고친다. (움직임에 없는 자세, 머리 돌리기, 웅크림 같은 뼈 덮어쓰기)
      함수면 (locals, skeleton) 으로 불러 그 함수가 locals 를 고치고, 배열이면 adjustBones 의 뼈마다 고침 표로 건다. (없으면 움직임 그대로)
  - `skeleton` object: readGlbArrays 의 skeleton.
  - `animationName` string: 움직임 이름. (없으면 쉬는 자세)
  - `time` number: 초. (움직임 길이로 되풀이, 한 번만 트는 움직임은 끝 시각에 묶음)
  - `target` Float32Array: 본마다 16 씩 쓸 곳. (skeleton.joints.length x 16 이상, ToonRenderer.drawMesh 의 jointMatrices)
  - `blend` object | null: { animationName, time, weight } 섞을 앞 자세와 그 무게. (0 ~ 1)
  - `swingScales` object | null: { 움직임 이름: [{ nodeIndex, scale }] } 흔들림 배율. (1 이면 그대로, 0 이면 쉬는 자세)
  - `poseAdjust` function | Array<object> | null: (locals, skeleton) 로 노드마다의 { translation, rotation, scale } 을 고치는 고리, 또는 adjustBones 의 고침 표. (locals 의 배열은 이 부름만의 것이라 제자리에서 고쳐도 된다)

  예제: 움직임이 바뀔 때 앞 자세를 잠깐 섞기

  ```js
  import { readGlbArrays, writeSkinPose } from "./vanilla.js";
  const arrayBuffer = await (await fetch("examples/ancientmountain/assets/fox.glb")).arrayBuffer();
  const skeleton = readGlbArrays(arrayBuffer).skeleton;
  if (skeleton !== null) {
  	const jointMatrices = new Float32Array(skeleton.joints.length * 16);
  	const blendDuration = 0.2;
  	const timeSinceChange = 0.05;
  	const blend = { animationName: "Survey", time: 1.4, weight: 1 - timeSinceChange / blendDuration };
  	writeSkinPose(skeleton, "Run", timeSinceChange, jointMatrices, blend);
  }
  ```

## BoneModifyMode (enum)

뼈 고치기의 꼴. (adjustBones 와 writeSkinPose 의 poseAdjust 표에서 고침 하나가 움직임 값에 어떻게 걸리는지)
  - add: 움직임 위에 덧붙인다. 자리는 부모 공간에서 더하고, 돌림은 그 뼈의 공간에서 뒤에 곱하고(q x 준 돌림), 크기는 곱한다.
  - replace: 준 값으로 바꾼다. (자리, 돌림, 크기 모두 부모 공간의 지역 값)

예제: 엉덩이는 내리고 머리는 움직임 값을 버리고 정면으로 두기

```js
import { readGlbArrays, writeSkinPose, BoneModifyMode } from "./vanilla.js";
const arrayBuffer = await (await fetch("examples/ancientmountain/assets/fox.glb")).arrayBuffer();
const skeleton = readGlbArrays(arrayBuffer).skeleton;
if (skeleton !== null) {
	const jointMatrices = new Float32Array(skeleton.joints.length * 16);
	writeSkinPose(skeleton, "Survey", 0.5, jointMatrices, null, null, [
		{ name: "b_Hip_01", translation: [0, -2, 0], mode: BoneModifyMode.add },
		{ name: "b_Head_05", rotation: [0, 0, 0, 1], mode: BoneModifyMode.replace },
	]);
}
```

- `add` = `0`: 움직임 위에 덧붙임. (자리는 더함, 돌림은 그 뼈의 공간에서 뒤에 곱함, 크기는 곱함)
- `replace` = `1`: 준 값으로 바꿈. (부모 공간의 지역 값)
