graphics3d/toon/glbmeshreader
점토 모형(GLB) 읽기와 뼈대 자세. (vanilla.js graphics3d/toon/glbmeshreader.js)
- 재질 색으로 칠하는 모형을 툰 3D 의 MeshBuilder 꼭짓점 배열로 읽는다. 텍스처 좌표와 재질 텍스처가 있으면 그것도 읽는다. (외계행성 광부 키우기에서 왔다)
- 부품 하나가 노드 하나이고, 노드의 메시는 색마다 프리미티브 하나다. 꼭짓점은 위치와 노멀, 뼈대가 있으면 본 번호와 무게다. 노멀이 없는 프리미티브는 glTF 명세대로 평평한 노멀(삼각형마다 하나)을 짓는다. (꼭짓점을 삼각형마다 따로 푼다)
- 재질의 baseColorFactor 는 선형 색이라 sRGB 로 바꿔 담고(감마 색 공간은 pow 1 / 2.2, 선형 색 공간은 sRGB 표준 곡선, 셰이더가 푸는 곡선의 역), emissiveFactor 가 있으면 빛남으로 담는다. (emissiveTexture 가 있으면 빛남은 재질 범위로만 넘긴다)
- TEXCOORD_0 이 있으면 uv_data 로, TEXCOORD_1 이 있으면 uv1_data(2 번 UV, 천사 고리)로 담는다. 프리미티브마다 재질 범위(ToonMaterialRange)를 담는다. (재질 이름, extras, 텍스처 그림 차례) 부품 안에서 칸을 갈라 칠할 때(강조색 칸, 표시판) 재질 이름이나 extras 로 고르고 ToonDrawOptions 의 index_start, index_count 로 그 칸만 그린다.
- 그림은 read_glb_images 로 읽고 decode_glb_image 로 풀어 ToonRenderer::create_texture 에 넘긴다.
- 재질 extras 의 outline 은 바깥선 껍데기(뒷면만 그림), basic 은 빛을 받지 않는 부품이다. 바깥선 설정을 주면 그 껍데기는 담지 않고, ".outline" 짝이 있는 노드의 몸으로 점마다 같은 굵기의 껍데기를 새로 짓는다.
- 뼈대(skin)가 있으면 본 노드와 그 거꾸로 묶는 행렬, 움직임(animations)과 그 extras 를 함께 읽는다. 자세는 write_skin_pose 가 셈한다. 섞은 자세를 스킨 행렬로 짓기 전에 뼈마다 고치려면 pose_adjust 에 고리(ToonPoseAdjust::Hook)나 고침 표(ToonPoseAdjust::Bones, adjust_bones, BoneModifier)를 준다.
- 부품을 따로 숨기거나 칠하는 모형은 read_glb_node_arrays 로 노드마다 따로 읽는다. (노드 extras 와 비치는 정도를 함께)
- 한 덩이로 읽은 뼈대 모형의 노드 extras 와 부품의 자리, 따르는 본은 read_glb_node_infos 로 따로 읽는다.
- 꼭짓점 속성을 정수로 담은 GLB(KHR_mesh_quantization)도 읽는다. 정규화 정수는 glTF 명세의 공식으로 나누고, 텍스처 좌표는 재질 텍스처의 KHR_texture_transform 을 구워 넣는다. 이름 없는 메시 노드는 이름 있는 부모 노드의 부품에 든다. (양자화 도구가 되풀이 변환을 맡기는 잎 노드) extensionsRequired 에 읽지 못하는 확장(meshopt 압축 등)이 있거나 바이너리 덩어리 밖의 버퍼를 가리키면 Err.
- 엔진의 SkinnedModel(텍스처 PBR)과는 따로다. 툰 그리기에 쓸 꼭짓점 배열만 뽑는다.
Reading clay models (GLB) and skeleton poses. (vanilla.js graphics3d/toon/glbmeshreader.js)
- Reads models painted with material colors into toon 3D MeshBuilder vertex arrays. Texture coordinates and material textures are read too if present. (Came from webgame-rimminer)
- One part is one node, and a node's mesh is one primitive per color. Vertices are position and normal, plus joint indices and weights if there is a skeleton. A primitive without normals gets flat normals (one per triangle) as the glTF spec says. (Vertices are split per triangle)
- The material's baseColorFactor is a linear color, so it is converted to sRGB (pow 1 / 2.2 in the gamma color space, the standard sRGB curve in the linear color space, the inverse of the curve the shader decodes with), and emissiveFactor, if present, is stored as emission. (with emissiveTexture, the emission is passed only as a material range)
- TEXCOORD_0, if present, goes into uv_data and TEXCOORD_1 into uv1_data (second UV, angel ring). A material range (ToonMaterialRange) is stored per primitive. (Material name, extras, texture image order) When painting split areas inside a part (accent color areas, display panels), pick them by material name or extras and draw only that area with index_start and index_count of ToonDrawOptions.
- Images are read with read_glb_images, decoded with decode_glb_image and passed to ToonRenderer::create_texture.
- outline in material extras is an outline shell (only back faces drawn), and basic is a part that does not receive light. If outline options are given, that shell is not stored, and a shell of uniform thickness per point is newly built from the body of each node that has a ".outline" pair.
- If there is a skeleton (skin), the joint nodes and their inverse bind matrices, the animations (animations) and their extras are read together. Poses are computed by write_skin_pose. To modify bones before the blended pose is built into skin matrices, pass a hook (ToonPoseAdjust::Hook) or a modification table (ToonPoseAdjust::Bones, adjust_bones, BoneModifier) as pose_adjust.
- Models whose parts are hidden or painted separately are read per node with read_glb_node_arrays. (Together with node extras and transparency)
- For a skeletal model read as one lump, node extras, part positions and the joints they follow are read separately with read_glb_node_infos.
- GLB files whose vertex attributes are stored as integers (KHR_mesh_quantization) are read too. Normalized integers are divided with the glTF spec formulas, and texture coordinates get the material texture KHR_texture_transform baked in. An unnamed mesh node belongs to the part of its named parent node. (the leaf node a quantizer adds for the dequantization transform) Err if extensionsRequired lists an extension that cannot be read (meshopt compression and others) or an accessor points to a buffer outside the binary chunk.
- Separate from the engine's SkinnedModel (textured PBR). Only the vertex arrays used for toon drawing are extracted.
ToonOutlineOptionsstruct traits Clone, Debug, Default
바깥선을 새로 지을 때의 설정.
- width: 껍데기 굵기. (0 이면 껍데기를 하나도 짓지 않는다, GLB 의 껍데기도 담지 않는다)
- part_widths: 부품(노드 이름)마다 따로 준 굵기. added_parts: ".outline" 짝이 없어도 껍데기를 지을 부품.
- inner_parts: inner_width 가 0 보다 크면 그 굵기의 껍데기를 하나 더 지어 바깥선 껍데기 끝에 담고 그 자리를 inner_outline_ranges 로 돌려준다. inner_parts 와 그 위에 얹힌 inner_over_parts 의 몸이 든 자리는 inner_body_ranges 로 돌려준다. (유리 같은 부위를 둘레의 가는 선과 함께 한 번 더 그릴 때)
Settings for building a new outline.
- width: shell width. (at 0 no shells are built at all, and the GLB's shells are not stored either)
- part_widths: width given separately per part (node name). added_parts: parts that get a shell even without a ".outline" pair.
- inner_parts: when inner_width is greater than 0, one more shell of that width is built and stored at the end of the outline shells, and that span is returned as inner_outline_ranges. The spans holding the bodies of inner_parts and of the inner_over_parts on top of them are returned as inner_body_ranges. (for drawing parts like glass once more with a thin line around them)
use std::collections::HashMap;
use vanilla::{read_glb_arrays, ToonMeshArrays, ToonOutlineOptions};
fn read_mannequin(bytes: &[u8]) -> Result<ToonMeshArrays, String> {
let outline_options = ToonOutlineOptions {
width: 1.5,
part_widths: HashMap::from([(String::from("Mannequin_F"), 0.8)]),
added_parts: vec![String::from("Mannequin_F")],
..ToonOutlineOptions::default()
};
read_glb_arrays(bytes, Some(&outline_options), None)
}껍데기 굵기. (모형 좌표, 0 이면 껍데기를 하나도 짓지 않는다)
Shell thickness. (Model coordinates, 0 builds no shells at all)
반환Returnsf64
부품(노드 이름)마다 따로 준 굵기.
Thickness given separately per part (node name).
반환ReturnsHashMap<String, f64>
".outline" 짝이 없어도 껍데기를 지을 부품. (노드 이름)
Parts to build a shell for even without a ".outline" pair. (Node names)
반환ReturnsVec<String>
안쪽 껍데기를 하나 더 지을 부품. (노드 이름, inner_width 가 0 보다 클 때)
Parts to build one more inner shell for. (Node names, when inner_width is greater than 0)
반환ReturnsVec<String>
inner_parts 위에 얹힌 부품. (노드 이름, 몸이 든 자리만 inner_body_ranges 로)
Parts placed on top of inner_parts. (Node names, only the span holding their body goes into inner_body_ranges)
반환ReturnsVec<String>
안쪽 껍데기 굵기. (0 이면 짓지 않는다)
Inner shell thickness. (0 builds none)
반환Returnsf64
ToonSkeletonNodestruct traits Clone, Debug
뼈대의 노드 하나. (쉬는 자세)
One node of the skeleton. (rest pose)
use std::collections::HashMap;
use vanilla::{write_skin_pose, ToonSkeleton, ToonSkeletonNode};
let root = ToonSkeletonNode { name: String::from("root"), parent_index: None, translation: [0.0, 1.0, 0.0], rotation: [0.0, 0.0, 0.0, 1.0], scale: [1.0; 3], matrix: None };
let arm = ToonSkeletonNode { name: String::from("arm"), parent_index: Some(0), translation: [0.5, 0.0, 0.0], rotation: [0.0, 0.0, 0.0, 1.0], scale: [2.0; 3], matrix: None };
let skeleton = ToonSkeleton { joints: vec![0, 1], inverse_bind_matrices: Vec::new(), nodes: vec![root, arm], animations: HashMap::new() };
let mut joint_matrices = vec![0.0f32; skeleton.joints.len() * 16];
write_skin_pose(&skeleton, "Idle", 0.0, &mut joint_matrices, None, None, None);
assert!((joint_matrices[16] - 2.0).abs() < 0.0001);
assert!((joint_matrices[28] - 0.5).abs() < 0.0001 && (joint_matrices[29] - 1.0).abs() < 0.0001);부모 노드의 차례. (뿌리면 None)
Index of the parent node. (None for the root)
반환ReturnsOption<usize>
돌림 사원수. ([x, y, z, w])
Rotation quaternion. ([x, y, z, w])
반환Returns[f64; 4]
glTF 의 matrix. (있으면 자리, 돌림, 크기 대신 쓰고 움직임을 받지 않는다)
glTF matrix. (if present, used instead of position, rotation and scale, and not animated)
반환ReturnsOption<[f64; 16]>
ToonAnimationChannelstruct traits Clone, Debug
움직임의 한 갈래. (움직이는 노드, 바꾸는 것, 열쇠 시각과 값)
One animation channel. (the animated node, what it changes, key times and values)
use std::collections::HashMap;
use vanilla::{write_skin_pose, ToonAnimation, ToonAnimationChannel, ToonChannelPath, ToonSkeleton, ToonSkeletonNode};
let node = ToonSkeletonNode { name: String::from("body"), parent_index: None, translation: [0.0; 3], rotation: [0.0, 0.0, 0.0, 1.0], scale: [1.0; 3], matrix: None };
let hop = ToonAnimationChannel { node_index: 0, path: ToonChannelPath::Translation, times: vec![0.0, 0.5], values: vec![0.0, 0.0, 0.0, 0.0, 1.0, 0.0], is_step: true };
let animation = ToonAnimation { duration: 1.0, channels: vec![hop], extras: serde_json::Value::Null };
let skeleton = ToonSkeleton { joints: vec![0], inverse_bind_matrices: Vec::new(), nodes: vec![node], animations: HashMap::from([(String::from("Hop"), animation)]) };
let mut joint_matrices = [0.0; 16];
write_skin_pose(&skeleton, "Hop", 0.25, &mut joint_matrices, None, None, None);
assert_eq!(joint_matrices[13], 0.0);
write_skin_pose(&skeleton, "Hop", 0.75, &mut joint_matrices, None, None, None);
assert_eq!(joint_matrices[13], 1.0);바꾸는 것. (자리, 돌림, 크기 가운데 하나)
What it changes. (One of position, rotation and scale)
반환ReturnsToonChannelPath
열쇠마다의 값. (돌림은 넷, 자리와 크기는 셋씩)
Values per key. (four for rotation, three each for position and scale)
반환ReturnsVec<f64>
interpolation 이 STEP 인지. (사이를 섞지 않고 앞 키)
Whether interpolation is STEP. (the previous key, without blending in between)
반환Returnsbool
ToonAnimationstruct traits Clone, Debug
움직임 하나. (길이, 갈래들, extras)
One animation. (duration, channels, extras)
use std::collections::HashMap;
use vanilla::{write_skin_pose, ToonAnimation, ToonAnimationChannel, ToonChannelPath, ToonSkeleton, ToonSkeletonNode};
let node = ToonSkeletonNode { name: String::from("body"), parent_index: None, translation: [0.0; 3], rotation: [0.0, 0.0, 0.0, 1.0], scale: [1.0; 3], matrix: None };
let rise = ToonAnimationChannel { node_index: 0, path: ToonChannelPath::Translation, times: vec![0.0, 2.0], values: vec![0.0, 0.0, 0.0, 0.0, 4.0, 0.0], is_step: false };
let animation = ToonAnimation { duration: 2.0, channels: vec![rise], extras: serde_json::json!({ "loop": "once" }) };
let skeleton = ToonSkeleton { joints: vec![0], inverse_bind_matrices: Vec::new(), nodes: vec![node], animations: HashMap::from([(String::from("Rise"), animation)]) };
let mut joint_matrices = [0.0; 16];
write_skin_pose(&skeleton, "Rise", 3.0, &mut joint_matrices, None, None, None);
assert_eq!(joint_matrices[13], 4.0);길이. (갈래들의 가장 늦은 열쇠 시각, 초)
Duration. (the latest key time among the channels, seconds)
반환Returnsf64
움직임의 extras. (loop 가 "once" 면 한 번만 튼다, 없으면 빈 것)
Animation extras. (plays only once if loop is "once", empty if none)
반환ReturnsValue
ToonSkeletonstruct traits Clone, Debug
뼈대와 움직임. (첫 skin 만)
Skeleton and animations. (first skin only)
use std::collections::HashMap;
use vanilla::{write_skin_pose, ToonAnimation, ToonAnimationChannel, ToonChannelPath, ToonSkeleton, ToonSkeletonNode};
let root = ToonSkeletonNode { name: String::from("root"), parent_index: None, translation: [0.0; 3], rotation: [0.0, 0.0, 0.0, 1.0], scale: [1.0; 3], matrix: None };
let arm = ToonSkeletonNode { name: String::from("arm"), parent_index: Some(0), translation: [1.0, 0.0, 0.0], rotation: [0.0, 0.0, 0.0, 1.0], scale: [1.0; 3], matrix: None };
let lift = ToonAnimationChannel { node_index: 0, path: ToonChannelPath::Translation, times: vec![0.0, 1.0], values: vec![0.0, 0.0, 0.0, 0.0, 2.0, 0.0], is_step: false };
let animation = ToonAnimation { duration: 1.0, channels: vec![lift], extras: serde_json::Value::Null };
let skeleton = ToonSkeleton { joints: vec![0, 1], inverse_bind_matrices: Vec::new(), nodes: vec![root, arm], animations: HashMap::from([(String::from("Lift"), animation)]) };
let mut joint_matrices = vec![0.0f32; skeleton.joints.len() * 16];
write_skin_pose(&skeleton, "Lift", 0.5, &mut joint_matrices, None, None, None);
assert!((joint_matrices[16 + 12] - 1.0).abs() < 0.0001);
assert!((joint_matrices[16 + 13] - 1.0).abs() < 0.0001);use vanilla::{read_glb_arrays, write_skin_pose};
fn read_pose(bytes: &[u8], time: f64) -> Result<Vec<f32>, String> {
let arrays = read_glb_arrays(bytes, None, None)?;
let Some(skeleton) = arrays.skeleton.as_ref() else {
return Ok(Vec::new());
};
let mut joint_matrices = vec![0.0f32; skeleton.joints.len() * 16];
write_skin_pose(skeleton, "Survey", time, &mut joint_matrices, None, None, None);
Ok(joint_matrices)
}본 노드의 차례. (skin 의 joints, 꼭짓점의 본 번호가 이 목록의 차례다)
Indices of the joint nodes. (the skin's joints, a vertex's joint number is an index into this list)
반환ReturnsVec<usize>
본마다 거꾸로 묶는 행렬. (16 씩, 없으면 단위 행렬)
Inverse bind matrix per joint. (16 each, identity matrix if none)
반환ReturnsVec<f32>
모든 노드의 쉬는 자세. (노드 차례)
Rest pose of every node. (in node order)
반환ReturnsVec<ToonSkeletonNode>
이름마다 움직임.
Animations by name.
반환ReturnsHashMap<String, ToonAnimation>
ToonPartArraysstruct traits Clone, Debug
노드마다 따로 읽은 부품. (배열, 노드 extras, 비치는 재질의 가장 작은 불투명도)
A part read separately per node. (arrays, node extras, smallest opacity of the translucent materials)
use vanilla::{read_glb_node_arrays, ToonMesh, ToonOutlineOptions, ToonRenderer};
fn create_part_meshes(gl: &vanilla::GlContext, renderer: &ToonRenderer, bytes: &[u8]) -> Result<Vec<(String, ToonMesh, f64)>, String> {
let outline_options = ToonOutlineOptions { width: 1.5, added_parts: vec![String::from("vanguard_Mesh"), String::from("vanguard_visor")], ..ToonOutlineOptions::default() };
let part_arrays = read_glb_node_arrays(bytes, Some(&outline_options), None)?;
let mut meshes = Vec::new();
for (part_name, part) in part_arrays.iter() {
if part_name == "vanguard_visor" {
continue;
}
if let Some(mesh) = renderer.create_mesh(gl, &part.arrays) {
meshes.push((part_name.clone(), mesh, part.alpha));
}
}
Ok(meshes)
}부품의 꼭짓점 배열. (뼈대는 읽지 않아 skeleton 은 None)
Vertex arrays of the part. (The skeleton is not read, so skeleton is None)
반환ReturnsToonMeshArrays
비치는 재질(alphaMode BLEND)의 가장 작은 불투명도. (없으면 1)
Smallest opacity of transparent materials (alphaMode BLEND). (1 if none)
반환Returnsf64
ToonNodeInfostruct traits Clone, Debug
메시 노드 하나의 정보. (extras, 꼭짓점 범위의 가운데, 가장 무겁게 딸린 본의 skin 안 차례)
Info for one mesh node. (extras, center of the vertex bounds, index within the skin of the bone it is most heavily bound to)
use vanilla::{read_glb_arrays, read_glb_node_infos, write_skin_pose, Matrix4};
fn read_visor_position(bytes: &[u8]) -> Result<Option<[f64; 3]>, String> {
let arrays = read_glb_arrays(bytes, None, None)?;
let node_infos = read_glb_node_infos(bytes)?;
let (Some(skeleton), Some(visor_info)) = (arrays.skeleton.as_ref(), node_infos.get("vanguard_visor")) else {
return Ok(None);
};
let Some(joint_index) = visor_info.joint_index else {
return Ok(Some(visor_info.center));
};
let mut joint_matrices = vec![0.0f32; skeleton.joints.len() * 16];
write_skin_pose(skeleton, "Walk", 0.25, &mut joint_matrices, None, None, None);
let mut joint_matrix = Matrix4::create_identity();
joint_matrix.elements.copy_from_slice(&joint_matrices[joint_index * 16..joint_index * 16 + 16]);
let visor_position = joint_matrix.transform_point(visor_info.center[0], visor_info.center[1], visor_info.center[2]);
Ok(Some([visor_position.x, visor_position.y, visor_position.z]))
}꼭짓점 범위의 가운데. (모형 좌표, 꼭짓점이 없으면 원점)
Center of the vertex bounds. (model coordinates, the origin if there are no vertices)
반환Returns[f64; 3]
가장 무겁게 딸린 본의 skin 안 차례. (뼈대로 움직이지 않으면 None)
Index within the skin of the most heavily weighted joint. (None if not moved by a skeleton)
반환ReturnsOption<usize>
ToonPoseBlendstruct traits Clone, Copy, Debug
자세를 섞을 앞 움직임. (움직임이 바뀔 때 잠깐)
Previous animation to blend the pose with. (briefly, when the animation changes)
use vanilla::{write_skin_pose, ToonPoseBlend};
let blend_duration = 0.2;
let time_since_change = 0.05;
let blend = ToonPoseBlend { animation_name: "Survey", time: 1.4, weight: 1.0 - time_since_change / blend_duration };
let mut joint_matrices = vec![0.0f32; skeleton.joints.len() * 16];
write_skin_pose(&skeleton, "Run", time_since_change, &mut joint_matrices, Some(blend), None, None);
assert!((joint_matrices[13] - 0.5).abs() < 0.0001);앞 자세의 무게. (0 이면 섞지 않음, 1 이면 앞 자세 그대로)
Weight of the previous pose. (0 for no blending, 1 for the previous pose as is)
반환Returnsf64
ToonSwingScalestype
노드마다의 흔들림 배율. (움직임 이름 → (노드 차례, 배율) 목록, 1 이면 그대로, 0 이면 쉬는 자세)
Swing scale per node. (animation name → list of (node index, scale), 1 keeps it as is, 0 is the rest pose)
pub type ToonSwingScales = HashMap<String, Vec<(usize, f64)>>BoneModifierstruct traits Clone, Copy, PartialEq, Debug, Default
뼈 하나의 고침. (adjust_bones 와 ToonPoseAdjust::Bones 표의 한 줄, 원본 { nodeIndex, name, translation, rotation, scale, mode, weight })
- 준 칸(Some)만 건다. node_index 가 None 이면 name 으로 찾는다. (같은 이름이 여럿이면 앞 노드, 못 찾거나 행렬로 둔 노드면 건너뛴다)
- weight 는 고치기 앞과 뒤 사이의 몫이다. (0 이면 그대로, 1 이면 다 고침, 0 ~ 1 로 자름, 돌림은 가까운 쪽으로 섞어 정규화)
- 기본은 칸 모두 None, mode Add, weight 1 이다.
Modification of one bone. (one row of the adjust_bones and ToonPoseAdjust::Bones table, original { nodeIndex, name, translation, rotation, scale, mode, weight })
- Only the given fields (Some) are applied. When node_index is None the node is looked up by name. (the first node when several share the name, skipped when not found or when the node uses a matrix)
- weight is the ratio between before and after the modification. (0 keeps it, 1 applies it fully, clamped to 0 ~ 1, rotation is blended the short way and normalized)
- The default is all fields None, mode Add, weight 1.
use vanilla::{BoneModifier, BoneModifyMode};
let half_angle: f64 = 0.4;
let modifier = BoneModifier { name: Some("b_Tail02_013"), rotation: Some([half_angle.sin(), 0.0, 0.0, half_angle.cos()]), weight: 0.5, ..Default::default() };
assert_eq!(modifier.mode, BoneModifyMode::Add);
assert_eq!(modifier.node_index, None);고칠 노드의 skeleton.nodes 차례. (None 이면 name 으로 찾음)
Index in skeleton.nodes of the node to modify. (looked up by name when None)
반환ReturnsOption<usize>
고칠 노드의 이름. (node_index 가 None 일 때 쓴다)
Name of the node to modify. (used when node_index is None)
반환ReturnsOption<&'a str>
자리. ([x, y, z], Add 면 더함, Replace 면 그 값, None 이면 그대로)
Translation. ([x, y, z], added with Add, set with Replace, unchanged when None)
반환ReturnsOption<[f64; 3]>
돌림 사원수. ([x, y, z, w], Add 면 그 뼈의 공간에서 뒤에 곱함, Replace 면 그 값을 정규화, None 이면 그대로)
Rotation quaternion. ([x, y, z, w], multiplied after in the bone's own space with Add, the normalized value with Replace, unchanged when None)
반환ReturnsOption<[f64; 4]>
크기. ([x, y, z], Add 면 곱함, Replace 면 그 값, None 이면 그대로)
Scale. ([x, y, z], multiplied with Add, set with Replace, unchanged when None)
반환ReturnsOption<[f64; 3]>
거는 꼴. (기본 Add)
How it is applied. (default Add)
반환ReturnsBoneModifyMode
고치기 앞과 뒤 사이의 몫. (0 ~ 1, 기본 1)
Ratio between before and after the modification. (0 ~ 1, default 1)
반환Returnsf64
ToonGlbImagestruct traits Clone, Debug, Default
GLB 에 든 그림 하나. (images 의 차례, 재질 범위의 base_color_image, emissive_image 가 가리킨다)
One image in a GLB. (index in images, referenced by base_color_image and emissive_image of material ranges)
use vanilla::core::graphic::GlTexture;
use vanilla::{decode_glb_image, read_glb_images, ToonRenderer, ToonTextureOptions};
fn create_image_textures(gl: &vanilla::GlContext, renderer: &ToonRenderer, bytes: &[u8]) -> Result<Vec<Option<GlTexture>>, String> {
let mut textures = Vec::new();
for image in read_glb_images(bytes)?.iter() {
if image.data.is_empty() {
textures.push(None);
continue;
}
let (width, height, pixels) = decode_glb_image(image)?;
textures.push(Some(renderer.create_texture(gl, width, height, &pixels, ToonTextureOptions::default())?));
}
Ok(textures)
}그림 종류. ("image/png" 같은, 없으면 빈 글자)
Image type. (such as "image/png", empty string if none)
반환ReturnsString
그림 파일 바이트. (바깥 파일 uri 면 빈 것)
Image file bytes. (empty for an external file uri)
반환ReturnsVec<u8>
함수Functions
GLB 에 든 그림들. (바이너리 덩어리의 bufferView 로 담긴 그림만 읽는다, 바깥 파일 uri 는 data 가 빈 것)
Images in a GLB. (only images stored through a bufferView of the binary chunk are read, external file uri images have empty data)
- bytes&[u8]
- GLB 파일 전체.The whole GLB file.
반환ReturnsResult<Vec<ToonGlbImage>, String> images 차례의 그림. (바깥 파일 uri 인 그림은 data 가 빈 것) GLB 가 아니거나 덩어리가 잘렸거나 모자라거나 JSON 을 읽지 못하면 Err(까닭 글).Images in images order. (An image from an external file uri has empty data) Err(reason text) if it is not a GLB, a chunk is cut off or missing, or the JSON cannot be read.
짝Counterpart: vanilla.js readGlbImages
read_glb_images 의 그림 하나를 풀기. ((너비, 높이, RGBA 바이트), 알파를 미리 곱하지 않는다, image 크레이트의 png, jpeg, webp, gif, bmp, ico)
Decodes one image from read_glb_images. ((width, height, RGBA bytes), alpha is not premultiplied, png, jpeg, webp, gif, bmp, ico through the image crate)
- image&ToonGlbImage
- read_glb_images 의 그림 하나.One image from read_glb_images.
반환ReturnsResult<(u32, u32, Vec<u8>), String> (너비, 높이, RGBA 바이트) 풀어 낸 그림. (ToonRenderer::create_texture 에 넘긴다) 풀지 못하면 Err(까닭 글).(width, height, RGBA bytes) decoded image. (Passed to ToonRenderer::create_texture) Err(reason text) if it cannot be decoded.
짝Counterpart: vanilla.js decodeGlbImage
pub fn read_glb_arrays(bytes: &[u8], outline_options: Option<&ToonOutlineOptions>, color_space: Option<ColorSpace>) -> Result<ToonMeshArrays, String>#GLB 하나를 꼭짓점 배열로. (뼈대가 있으면 skeleton 도, 바깥선 설정을 주면 껍데기를 새로 짓는다)
One GLB into vertex arrays. (the skeleton too if there is one, a new shell is built when outline settings are given)
- bytes&[u8]
- GLB 파일 전체.The whole GLB file.
- outline_optionsOption<&ToonOutlineOptions>
- 주면 GLB 의 바깥선 껍데기 대신 ".outline" 짝이 있는 노드의 몸으로 껍데기를 새로 짓는다. (None 이면 GLB 의 껍데기 그대로)If given, shells are newly built from the body of nodes that have a ".outline" pair instead of the GLB's outline shells. (None keeps the GLB's shells as is)
- color_spaceOption<ColorSpace>
- 꼭짓점 색(baseColorFactor 를 sRGB 로 바꾸는 곡선)의 색 공간. (None 이면 엔진의 색 공간, 원본 기본값과 같음, 그릴 ToonRenderer 와 같은 값)The color space of the vertex color (the curve that converts baseColorFactor to sRGB). (None means the engine's color space, the same as the original default, use the same value as the ToonRenderer that draws it)
반환ReturnsResult<ToonMeshArrays, String> MeshBuilder::read_arrays 의 꼴과 skeleton (없으면 None), inner_outline_ranges, inner_body_ranges. (ToonRenderer::create_mesh 에 넘긴다) GLB 가 아니거나 덩어리가 잘렸거나 모자라거나 JSON 을 읽지 못하면 Err(까닭 글).The form of MeshBuilder::read_arrays plus skeleton (None if none), inner_outline_ranges, inner_body_ranges. (Passed to ToonRenderer::create_mesh) Err(reason text) if it is not a GLB, a chunk is cut off or missing, or the JSON cannot be read.
짝Counterpart: vanilla.js readGlbArrays
pub fn read_glb_node_arrays(bytes: &[u8], outline_options: Option<&ToonOutlineOptions>, color_space: Option<ColorSpace>) -> Result<HashMap<String, ToonPartArrays>, String>#GLB 하나를 노드 이름마다의 꼭짓점 배열로. (뼈대는 읽지 않는다)
- 이름 끝의 ".outline" 노드(바깥선 껍데기)는 그 앞 이름의 노드에 함께 담는다.
- 부품마다 노드 extras 와 비치는 재질(alphaMode BLEND)의 가장 작은 불투명도를 함께 담는다.
One GLB into vertex arrays per node name. (the skeleton is not read)
- Nodes whose name ends in ".outline" (outline shells) are stored together with the node of the preceding name.
- For each part, the node extras and the smallest opacity of its translucent materials (alphaMode BLEND) are stored too.
- bytes&[u8]
- GLB 파일 전체.The whole GLB file.
- outline_optionsOption<&ToonOutlineOptions>
- read_glb_arrays 와 같음.Same as read_glb_arrays.
- color_spaceOption<ColorSpace>
- read_glb_arrays 와 같음. (None 이면 엔진의 색 공간)Same as read_glb_arrays. (None means the engine's color space)
반환ReturnsResult<HashMap<String, ToonPartArrays>, String> 노드 이름마다 부품의 배열과 extras, alpha. GLB 가 아니거나 덩어리가 잘렸거나 모자라거나 JSON 을 읽지 못하면 Err(까닭 글).Per node name, the part's arrays with extras and alpha. Err(reason text) if it is not a GLB, a chunk is cut off or missing, or the JSON cannot be read.
짝Counterpart: vanilla.js readGlbNodeArrays
pub fn read_glb_node_infos(bytes: &[u8]) -> Result<HashMap<String, ToonNodeInfo>, String>#GLB 의 메시 노드마다의 extras, 가운데, 따르는 본. (이름 끝이 ".outline" 인 노드와 바깥선 재질은 뺀다, 이름 없는 메시 노드는 이름 있는 부모 부품에 모은다)
- center 는 꼭짓점이 놓인 범위의 가운데다. (모형 좌표, 뼈대로 움직이는 노드는 쉬는 자세의 자리, 꼭짓점이 없으면 원점)
- joint_index 는 그 노드의 꼭짓점이 가장 무겁게 딸린 본의 skin 안 차례다. (write_skin_pose 가 쓴 본 행렬의 차례)
Extras, center and following bone of each mesh node of the GLB. (nodes whose name ends in ".outline" and outline materials are excluded, an unnamed mesh node is gathered into its named parent part)
- center is the center of the range the vertices occupy. (model coordinates, the rest pose position for nodes moved by the skeleton, the origin if there are no vertices)
- joint_index is the index within the skin of the bone the node's vertices are most heavily bound to. (the order of the bone matrices written by write_skin_pose)
- bytes&[u8]
- GLB 파일 전체.The whole GLB file.
반환ReturnsResult<HashMap<String, ToonNodeInfo>, String> 노드 이름마다 메시 노드의 extras, center, joint_index. GLB 가 아니거나 덩어리가 잘렸거나 모자라거나 JSON 을 읽지 못하면 Err(까닭 글).Per node name, the mesh node's extras, center and joint_index. Err(reason text) if it is not a GLB, a chunk is cut off or missing, or the JSON cannot be read.
짝Counterpart: vanilla.js readGlbNodeInfos
pub fn read_animation_swing(skeleton: &ToonSkeleton, animation_name: &str, node_index: usize) -> f64#움직임에서 한 노드의 돌림이 쉬는 자세에서 가장 벗어난 각. (라디안, 열쇠 프레임마다 보고, 그 노드의 돌림이 없으면 0)
The largest angle by which one node's rotation deviates from the rest pose in an animation. (radians, checked per keyframe, 0 if that node has no rotation)
- skeleton&ToonSkeleton
- read_glb_arrays 의 skeleton.skeleton of read_glb_arrays.
- animation_name&str
- 움직임 이름.Animation name.
- node_indexusize
- skeleton.nodes 의 차례.Order in skeleton.nodes.
반환Returnsf64 쉬는 자세에서 가장 벗어난 각. (라디안, 없으면 0)The largest angle away from the rest pose. (Radians, 0 if none)
짝Counterpart: vanilla.js readAnimationSwing
pub fn adjust_bones(locals: &mut [ToonSkeletonNode], skeleton: &ToonSkeleton, modifiers: &[BoneModifier])#섞은 자세의 뼈마다 지역 변환 고치기. (write_skin_pose 가 움직임을 읽어 섞은 뒤, 스킨 행렬을 짓기 전에 거는 꼴, 행렬로 둔 노드는 건너뜀)
- 고침은 차례대로 걸린다. (같은 뼈에 둘을 주면 앞 고침 위에 뒤 고침)
- weight 가 0 이하인 고침과 못 찾은 뼈는 건너뛴다.
Modify the local transform of each bone in a blended pose. (the form write_skin_pose applies after sampling and blending the animation and before building skin matrices, nodes using a matrix are skipped)
- Modifications are applied in order. (two on the same bone apply the later one on top of the earlier one)
- Modifications with weight 0 or less and bones that are not found are skipped.
- locals&mut [ToonSkeletonNode]
- 노드마다의 지역 값. (ToonPoseAdjust::Hook 고리가 받는 것, 고친 값을 여기에 쓴다)Local values per node. (what the ToonPoseAdjust::Hook hook receives, modified values are written here)
- skeleton&ToonSkeleton
- read_glb_arrays 의 skeleton. (이름으로 뼈를 찾는다)skeleton of read_glb_arrays. (bones are looked up by name)
- modifiers&[BoneModifier]
- 뼈마다의 고침. (BoneModifier, 차례대로)Modifications per bone. (BoneModifier, in order)
짝Counterpart: vanilla.js adjustBones
use std::collections::HashMap;
use vanilla::{adjust_bones, BoneModifier, ToonSkeleton, ToonSkeletonNode};
let hip = ToonSkeletonNode { name: String::from("hip"), parent_index: None, translation: [0.0, 1.0, 0.0], rotation: [0.0, 0.0, 0.0, 1.0], scale: [1.0; 3], matrix: None };
let skeleton = ToonSkeleton { joints: vec![0], inverse_bind_matrices: Vec::new(), nodes: vec![hip], animations: HashMap::new() };
let mut locals = skeleton.nodes.clone();
adjust_bones(&mut locals, &skeleton, &[
BoneModifier { name: Some("hip"), translation: Some([0.0, 4.0, 0.0]), weight: 0.5, ..Default::default() },
BoneModifier { node_index: Some(0), scale: Some([2.0, 1.0, 1.0]), ..Default::default() },
]);
assert_eq!(locals[0].translation, [0.0, 3.0, 0.0]);
assert_eq!(locals[0].scale, [2.0, 1.0, 1.0]);pub fn write_skin_pose(skeleton: &ToonSkeleton, animation_name: &str, time: f64, target: &mut [f32], blend: Option<ToonPoseBlend>, swing_scales: Option<&ToonSwingScales>, pose_adjust: Option<ToonPoseAdjust>)#뼈대 자세 셈하기. (움직임을 그 시각에서 읽어 본마다 행렬을 target 에 16 씩 쓴다, 움직임이 없으면 쉬는 자세)
- blend 를 주면 앞 움직임의 자세를 그 무게만큼 섞는다. (움직임이 바뀔 때 잠깐)
- swing_scales 를 주면 그 움직임의 그 노드는 돌림을 쉬는 자세 쪽으로 줄인다. (섞는 앞 자세에도 같이)
- pose_adjust 를 주면 섞은 뒤, 스킨 행렬을 짓기 전에 뼈마다의 지역 변환을 고친다. (움직임에 없는 자세, 머리 돌리기, 웅크림 같은 뼈 덮어쓰기) Hook 이면 (locals, skeleton) 으로 불러 그 함수가 locals 를 고치고, Bones 면 adjust_bones 의 뼈마다 고침 표로 건다. (None 이면 움직임 그대로)
Computes the skeleton pose. (samples the animation at that time and writes a matrix per bone into target, 16 each, rest pose if no animation)
- If blend is given, blends in the previous animation's pose by that weight. (briefly, when the animation changes)
- If swing_scales is given, that node in that animation has its rotation reduced toward the rest pose. (also applied to the blended previous pose)
- With pose_adjust, each bone's local transform is modified after blending and before the skin matrices are built. (bone overrides such as poses not in the animation, head turning, crouching) Hook is called with (locals, skeleton) and that function modifies locals, Bones is applied as the per-bone modification table of adjust_bones. (None keeps the animation as is)
- skeleton&ToonSkeleton
- read_glb_arrays 의 skeleton.skeleton of read_glb_arrays.
- animation_name&str
- 움직임 이름. (없으면 쉬는 자세)Animation name. (Rest pose if none)
- timef64
- 초. (움직임 길이로 되풀이, 한 번만 트는 움직임은 끝 시각에 묶음)Seconds. (wraps by the animation length, play-once animations are clamped to the end time)
- target&mut [f32]
- 본마다 16 씩 쓸 곳. (skeleton.joints 수 x 16 이상, 모자라면 들어가는 본까지만 쓴다, ToonDrawOptions 의 joint_matrices)Where to write 16 per joint. (At least skeleton.joints count x 16, if short only the joints that fit are written, joint_matrices of ToonDrawOptions)
- blendOption<ToonPoseBlend>
- 섞을 앞 자세와 그 무게. (None 이면 섞지 않음)Previous pose to blend and its weight. (None means no blending)
- swing_scalesOption<&ToonSwingScales>
- 움직임 이름마다 (노드 차례, 배율) 목록의 흔들림 배율. (1 이면 그대로, 0 이면 쉬는 자세, None 이면 없음)Swing scale as a list of (node index, scale) per animation name. (1 keeps as is, 0 gives the rest pose, None means none)
- pose_adjustOption<ToonPoseAdjust>
- 섞은 뒤 뼈마다의 지역 변환을 고치는 고리나 고침 표. (None 이면 움직임 그대로, 고리가 받는 locals 는 이 부름만의 사본이라 제자리에서 고쳐도 된다)Hook or modification table that modifies each bone's local transform after blending. (None keeps the animation as is, the locals a hook receives are a copy for this call only, so they can be modified in place)
짝Counterpart: vanilla.js writeSkinPose
ToonChannelPathenum traits Clone, Copy, PartialEq, Eq, Debug
움직임의 한 갈래. (노드 하나의 자리, 돌림, 크기 가운데 하나)
One track of an animation. (one of a node's translation, rotation or scale)
| 이름Name | 설명Description |
|---|---|
Translation | 자리. (값 셋)Position. (Three values) |
Rotation | 돌림. (사원수 넷)Rotation. (Four quaternion values) |
Scale | 크기. (값 셋)Scale. (Three values) |
Other | 그 밖의 것. (weights 같은, 읽기만 하고 자세에 쓰지 않는다)Anything else. (such as weights, read only and not applied to the pose) |
BoneModifyModeenum traits Clone, Copy, PartialEq, Eq, Debug, Default
뼈 고치기의 꼴. (adjust_bones 와 write_skin_pose 의 ToonPoseAdjust::Bones 표에서 고침 하나가 움직임 값에 어떻게 걸리는지, 원본 BoneModifyMode)
- Add: 움직임 위에 덧붙인다. 자리는 부모 공간에서 더하고, 돌림은 그 뼈의 공간에서 뒤에 곱하고(q x 준 돌림), 크기는 곱한다.
- Replace: 준 값으로 바꾼다. (자리, 돌림, 크기 모두 부모 공간의 지역 값)
Bone modification mode. (how one modification in the adjust_bones and write_skin_pose ToonPoseAdjust::Bones table is applied to the animation values, original BoneModifyMode)
- Add: layers on top of the animation. Translation is added in parent space, rotation is multiplied after in the bone's own space (q x given rotation), and scale is multiplied.
- Replace: sets the given values. (translation, rotation and scale are all local values in parent space)
use std::collections::HashMap;
use vanilla::{write_skin_pose, BoneModifier, BoneModifyMode, ToonPoseAdjust, ToonSkeleton, ToonSkeletonNode};
let hip = ToonSkeletonNode { name: String::from("hip"), parent_index: None, translation: [0.0, 5.0, 0.0], rotation: [0.0, 0.0, 0.0, 1.0], scale: [1.0; 3], matrix: None };
let head = ToonSkeletonNode { name: String::from("head"), parent_index: Some(0), translation: [0.0, 1.0, 0.0], rotation: [0.0, 0.7071, 0.0, 0.7071], scale: [1.0; 3], matrix: None };
let skeleton = ToonSkeleton { joints: vec![0, 1], inverse_bind_matrices: Vec::new(), nodes: vec![hip, head], animations: HashMap::new() };
let modifiers = [
BoneModifier { name: Some("hip"), translation: Some([0.0, -2.0, 0.0]), mode: BoneModifyMode::Add, ..Default::default() },
BoneModifier { name: Some("head"), rotation: Some([0.0, 0.0, 0.0, 1.0]), mode: BoneModifyMode::Replace, ..Default::default() },
];
let mut joint_matrices = vec![0.0f32; skeleton.joints.len() * 16];
write_skin_pose(&skeleton, "Idle", 0.0, &mut joint_matrices, None, None, Some(ToonPoseAdjust::Bones(&modifiers)));
assert_eq!(joint_matrices[13], 3.0);
assert_eq!(joint_matrices[16], 1.0);| 이름Name | 값Value | 설명Description |
|---|---|---|
Add | 0 | 움직임 위에 덧붙임. (자리는 더함, 돌림은 그 뼈의 공간에서 뒤에 곱함, 크기는 곱함)Layer on top of the animation. (translation is added, rotation is multiplied after in the bone's own space, scale is multiplied) |
Replace | 1 | 준 값으로 바꿈. (부모 공간의 지역 값)Set to the given values. (local values in parent space) |
ToonPoseAdjustenum
섞은 자세의 뼈마다 지역 변환을 고치는 것. (write_skin_pose 의 pose_adjust, 원본 writeSkinPose 일곱째 인자의 함수나 표)
- Hook: (노드마다의 지역 값, 뼈대) 로 불러 그 함수가 지역 값을 제자리에서 고친다. (이 부름만의 사본이라 뼈대의 쉬는 자세는 바뀌지 않는다)
- Bones: adjust_bones 의 뼈마다 고침 표로 건다.
What modifies each bone's local transform in a blended pose. (pose_adjust of write_skin_pose, the function or table of the seventh argument of the original writeSkinPose)
- Hook: called with (local values per node, skeleton) and that function modifies the local values in place. (a copy for this call only, so the skeleton's rest pose does not change)
- Bones: applied as the per-bone modification table of adjust_bones.
use std::collections::HashMap;
use vanilla::{adjust_bones, write_skin_pose, BoneModifier, ToonPoseAdjust, ToonSkeleton, ToonSkeletonNode};
let spine = ToonSkeletonNode { name: String::from("spine"), parent_index: None, translation: [0.0; 3], rotation: [0.0, 0.0, 0.0, 1.0], scale: [1.0; 3], matrix: None };
let tail = ToonSkeletonNode { name: String::from("tail"), parent_index: Some(0), translation: [0.0, 0.0, -1.0], rotation: [0.0, 0.0, 0.0, 1.0], scale: [1.0; 3], matrix: None };
let skeleton = ToonSkeleton { joints: vec![0, 1], inverse_bind_matrices: Vec::new(), nodes: vec![spine, tail], animations: HashMap::new() };
let half_angle: f64 = 0.3;
let mut crouch = |locals: &mut [ToonSkeletonNode], pose_skeleton: &ToonSkeleton| {
adjust_bones(locals, pose_skeleton, &[BoneModifier { name: Some("spine"), rotation: Some([half_angle.sin(), 0.0, 0.0, half_angle.cos()]), ..Default::default() }]);
locals[1].scale[1] *= 1.2;
};
let mut joint_matrices = vec![0.0f32; skeleton.joints.len() * 16];
write_skin_pose(&skeleton, "Idle", 0.0, &mut joint_matrices, None, None, Some(ToonPoseAdjust::Hook(&mut crouch)));
assert!((joint_matrices[5] - 0.6f64.cos() as f32).abs() < 0.0001);
assert_eq!(skeleton.nodes[1].scale, [1.0; 3]);| 이름Name | 값Value | 설명Description |
|---|---|---|
Hook | Hook(&'a mut dyn FnMut(&mut [ToonSkeletonNode], &ToonSkeleton)) | 노드마다의 지역 값을 직접 고치는 고리. (locals, skeleton)Hook that modifies the local values per node directly. (locals, skeleton) |
Bones | Bones(&'a [BoneModifier<'a>]) | adjust_bones 의 뼈마다 고침 표.Per-bone modification table of adjust_bones. |