graphics3d/material
머티리얼. (원본 graphics3d/material.js)
- 셰이더 템플릿 참조 + metallic-roughness PBR 파라미터/텍스처, 포맷 중립. 모델은 머티리얼 인스턴스를 적용만 한다.
- 임포터가 만든 중립 머티리얼 서술(팩터 + 이미지 바이트, MaterialDescription)로부터 GL 텍스처를 만든다.
- FBX 의 스펙큘러/글로스 맵은 glossiness 경로로 러프니스를 근사한다.
- 텍스처 유닛 배치는 원본과 같다: 0 = base_color, 1 = 섀도우 맵 전용(사용 금지), 2 ~ 8 = normal / metallicRoughness / glossiness / occlusion / emissive / specular / opacity, 추가 슬롯은 9 이상.
- 원본과 다른 것:
- 셰이더 프로그램은
Rc<ShaderProgram>으로 렌더러와 나눠 든다. 모델의 드로어블은Rc<Material>로 가리킨다. (원본 참조 의미) 원본이 인스턴스를 고치는 set_texture / set_use_alpha_cutout / set_subsurface_factor 는 &self 로 부를 수 있게 안에서 Cell 로 든다. - 이미지 해석은 원본 createImageBitmap(비동기) 대신 image 크레이트(png, jpeg, webp, gif, bmp, ico)로 그 자리에서 한다. 그래서 async 가 없다. 형은 원본 크롬처럼 해석에 쓰지 않고 내용으로 가린다. (크롬 createImageBitmap(Blob) 도 Blob 의 형이 아니라 내용으로 해독기를 고른다) 원본처럼 flip_y 면 위아래를 뒤집고, is_color_data 면 SRGB8_ALPHA8 로 올린다.
- 원본 loadImageDescription(url) 의 Promise 는 ImageAsset 처럼 받기 손잡이(ImageDescriptionLoadHandle)다. load_image_description(엔진, 애셋 경로, 옵션)이 엔진의 애셋 받기(데스크탑은 애셋 폴더 후보, 웹은 asset_base_url 에서 fetch)로 바이트를 부탁하고, 다 받으면 get_image_description 이 서술을 만든다. 손잡이는 그대로 await 할 수 있다. (엔진 작업 안에서 Material::load_image_description(engine, 경로, 옵션).await 가 원본 await 처럼 서술을 낸다) mime_type 은 원본처럼 응답의 content-type 이다. (웹 fetch 응답 머리, 머리가 없으면 None) 데스크탑에는 응답이 없어 내용으로 고른 형이다. (Image::sniff_image_mime_type, WHATWG MIME 스니핑의 그림 표와 AVIF, 모르면 None) 바이트를 받는 create_image_description(bytes) 는 원본과 같다.
- 원본 이미지 서술의 source(캔버스/비트맵)는 RGBA 픽셀(ImageSource)로 받는다.
Material. (the original graphics3d/material.js)
- Shader template reference + metallic-roughness PBR parameters/textures, format neutral. Models only apply material instances.
- Builds GL textures from the neutral material description made by importers (factors + image bytes, MaterialDescription).
- FBX specular/gloss maps approximate roughness through the glossiness path.
- The texture unit layout is the same as the original: 0 = base_color, 1 = shadow map only (do not use), 2 ~ 8 = normal / metallicRoughness / glossiness / occlusion / emissive / specular / opacity, extra slots are 9 and above.
- Differences from the original:
- The shader program is shared with the renderer as
Rc<ShaderProgram>. Model drawables point to materials withRc<Material>. (the original reference semantics) set_texture / set_use_alpha_cutout / set_subsurface_factor, which modify the instance in the original, hold their state in Cell internally so they can be called with &self. - Image decoding is done on the spot with the image crate (png, jpeg, webp, gif, bmp, ico) instead of the original createImageBitmap (async). So there is no async. As in the original on Chrome, the type is not used for decoding and the format is detected from the content. (Chrome createImageBitmap(Blob) also picks the decoder by content, not by the Blob type) Like the original, flip_y flips it vertically and is_color_data uploads it as SRGB8_ALPHA8.
- The Promise of the original loadImageDescription(url) is a load handle (ImageDescriptionLoadHandle), like ImageAsset. load_image_description(engine, asset path, options) requests the bytes through the engine's asset loading (asset folder candidates on desktop, fetch from asset_base_url on the web), and once loaded get_image_description builds the description. The handle can be awaited directly. (inside an engine task, Material::load_image_description(engine, path, options).await yields the description like the original await) mime_type is the content-type of the response, as in the original. (the web fetch response header, None without the header) Desktop has no response, so it is the type detected from the content. (Image::sniff_image_mime_type, the image table of WHATWG MIME sniffing plus AVIF, None when unknown) create_image_description(bytes), which takes bytes, is the same as the original.
- The source (canvas/bitmap) of the original image description is taken as RGBA pixels (ImageSource).
ImageSourcestruct traits Clone, Debug, Default
이미 푼 RGBA 픽셀. (원본 이미지 서술의 source, 캔버스/비트맵 자리, 스트레이트 알파, 위에서 아래로)
Already decoded RGBA pixels. (the source of the original image description, in place of a canvas/bitmap, straight alpha, top to bottom)
use std::rc::Rc;
use vanilla::{ImageDescription, ImageSource};
let image_source = ImageSource { width: 2, height: 1, pixels: vec![255, 0, 0, 255, 0, 0, 255, 255] };
let image_description = ImageDescription { source: Some(Rc::new(image_source)), is_color_data: true, ..ImageDescription::default() };
assert!(image_description.bytes.is_empty());
assert_eq!(image_description.source.as_ref().map(|source| source.width), Some(2));RGBA 바이트. (픽셀마다 4 바이트, 위 행부터, 길이는 width x height x 4 이상)
RGBA bytes. (4 bytes per pixel, from the top row, length at least width x height x 4)
반환ReturnsVec<u8>
ImageDescriptionstruct traits Clone, Debug, Default
이미지 서술. (원본 { bytes, mime_type, flip_y, is_color_data, anisotropy } 또는 { source, flip_y })
- bytes 는 png / jpeg / webp 파일 내용이다. 같은 이미지를 여러 텍스처가 쓰면 Rc 로 나눠 든다. (FBX 비디오 중복 참조)
Image description. (the original { bytes, mime_type, flip_y, is_color_data, anisotropy } or { source, flip_y })
- bytes is the png / jpeg / webp file content. When several textures use the same image, it is shared with Rc. (duplicate references to FBX videos)
use vanilla::{ImageDescriptionOptions, Material};
let bytes = std::fs::read("examples/assets/atlas/icons.png").unwrap();
let options = ImageDescriptionOptions { flip_y: false, is_color_data: true, anisotropy: 8.0 };
let image_description = Material::create_image_description(bytes, Some(String::from("image/png")), Some(options));
assert!(image_description.is_color_data);
assert_eq!(image_description.anisotropy, 8.0);
assert!(image_description.source.is_none());이미지 파일 내용. (png, jpeg, webp, gif, bmp, ico, 비고 source 도 없으면 create_texture 가 대체색을 쓴다)
Image file content. (png, jpeg, webp, gif, bmp, ico, when it is empty and there is no source either, create_texture uses the fallback color)
반환ReturnsRc<Vec<u8>>
형. (응답의 content-type 이나 내용으로 고른 형, 해석에는 쓰지 않는다, 모르면 None)
Type. (the response content-type or the type detected from the content, not used for decoding, None when unknown)
반환ReturnsOption<String>
이미 푼 RGBA 픽셀. (있으면 bytes 대신 쓴다)
Already decoded RGBA pixels. (used instead of bytes when present)
반환ReturnsOption<Rc<ImageSource>>
올릴 때 위아래를 뒤집을지. (원본 createImageBitmap 의 imageOrientation)
Whether to flip vertically on upload. (imageOrientation of the original createImageBitmap)
반환Returnsbool
색 데이터인지. (true 면 SRGB8_ALPHA8 로 올려 선형으로 샘플링, 노멀 같은 데이터 맵은 false)
Whether it is color data. (if true, uploaded as SRGB8_ALPHA8 and sampled linearly, false for data maps such as normals)
반환Returnsbool
이방성 필터 단계. (0 이하면 쓰지 않음, 기기 최대치로 자른다, 확장이 없으면 무시)
Anisotropic filter level. (not used at 0 or below, clamped to the device maximum, ignored without the extension)
반환Returnsf64
ImageDescriptionOptionsstruct traits Clone, Copy, Debug, Default, PartialEq
이미지 서술 옵션. (원본 loadImageDescription 의 options { flip_y, is_color_data, anisotropy })
Image description options. (options { flip_y, is_color_data, anisotropy } of the original loadImageDescription)
use vanilla::{ImageDescriptionOptions, Material};
assert_eq!(ImageDescriptionOptions::default(), ImageDescriptionOptions { flip_y: false, is_color_data: false, anisotropy: 0.0 });
let image_description = Material::create_image_description(vec![1, 2, 3], None, None);
assert!(!image_description.flip_y);
assert!(!image_description.is_color_data);
assert_eq!(image_description.anisotropy, 0.0);위아래를 뒤집을지. (기본 false)
Whether to flip vertically. (default false)
반환Returnsbool
색 데이터인지. (true 면 sRGB 로 올린다, 기본 false)
Whether it is color data. (if true, uploaded as sRGB, default false)
반환Returnsbool
이방성 필터 단계. (0 이면 쓰지 않음, 기본 0)
Anisotropic filter level. (not used at 0, default 0)
반환Returnsf64
ImageDescriptionLoadHandlestruct traits Clone, Debug, IntoFuture
이미지 서술 받기 손잡이. (Material::load_image_description 이 돌려준다. 원본 loadImageDescription 의 Promise 자리)
- 씬은 get_load_handle 을 SceneBase::track_load_handle 로 맡겨 다 받을 때까지 initialize 를 미룰 수 있다.
Image description load handle. (returned by Material::load_image_description, stands in for the Promise of the original loadImageDescription)
- A scene can hand get_load_handle to SceneBase::track_load_handle to defer initialize until loading finishes.
use vanilla::{Engine, EngineConfiguration, ImageDescriptionOptions, Material};
let engine = Engine::new(EngineConfiguration::new());
let options = ImageDescriptionOptions { is_color_data: true, ..ImageDescriptionOptions::default() };
let load_handle = Material::load_image_description(&engine, "examples/assets/atlas/icons.png", Some(options));
assert!(load_handle.is_finished());
let image_description = load_handle.get_image_description().unwrap().unwrap();
assert_eq!(image_description.mime_type.as_deref(), Some("image/png"));
assert!(image_description.is_color_data);
let missing_load_handle = Material::load_image_description(&engine, "missing_texture.png", None);
assert!(missing_load_handle.get_image_description().unwrap().is_err());바이트 읽기 손잡이. (씬에 맡길 때)
Byte read handle. (for handing to a scene)
반환Returns&AssetLoadHandle 바이트 읽기 손잡이. (SceneBase::track_load_handle 에 맡길 때)Byte read handle. (for handing to SceneBase::track_load_handle)
끝났는지. (받았거나 실패했거나)
Whether it has finished. (loaded or failed)
반환Returnsbool 받았거나 받기에 실패했으면 true.true if loaded or loading failed.
받은 바이트로 이미지 서술 만들기. (받는 중이면 None, 받기에 실패하면 Err. 원본 문구 "Material image load failed: url")
Builds an image description from the loaded bytes. (None while loading, Err when loading fails. The original message is "Material image load failed: url")
반환ReturnsOption<Result<ImageDescription, String>> 받는 중이면 None. 받았으면 Some(Ok(서술)), 받기에 실패하면 Some(Err("Material image load failed: 경로")).
(옵션은 load_image_description 에 준 것, mime_type 은 응답의 content-type 이고 데스크탑은 내용으로 고른 형)None while loading. Some(Ok(description)) when loaded, Some(Err("Material image load failed: path")) when loading fails.
(the options are the ones given to load_image_description, mime_type is the response content-type, and on desktop the type detected from the content)
ImageDescriptionLoadFuturestruct traits Clone, Debug, Future
이미지 서술 받기를 기다리는 퓨처. (ImageDescriptionLoadHandle 을 await 하면 된다. 원본 loadImageDescription 의 Promise 가 풀린 값)
Future that waits for the image description load. (just await ImageDescriptionLoadHandle. The resolved value of the original loadImageDescription Promise)
use vanilla::{Engine, ImageDescriptionOptions, Material};
fn load_texture_description(engine: &Engine) {
engine.spawn_task(|mut engine_context| async move {
let options = ImageDescriptionOptions { is_color_data: true, ..ImageDescriptionOptions::default() };
let load_handle = engine_context.with(|engine| Material::load_image_description(engine, "examples/assets/atlas/icons.png", Some(options)));
if let Ok(image_description) = load_handle.await {
assert!(!image_description.bytes.is_empty());
}
});
}MaterialDescriptionstruct traits Clone, Debug
중립 머티리얼 서술. (원본 createDefaultDescription 이 만드는 객체, 팩터 + 이미지, GL 무관)
Neutral material description. (the object made by the original createDefaultDescription, factors + images, GL independent)
use vanilla::{ImageDescriptionOptions, Material};
let mut description = Material::create_default_description();
assert_eq!(description.metallic_factor, 0.0);
description.base_color_factor = [0.8, 0.6, 0.5];
description.roughness_factor = 0.7;
let bytes = std::fs::read("examples/assets/atlas/icons.png").unwrap();
description.normal_image = Some(Material::create_image_description(bytes, None, Some(ImageDescriptionOptions::default())));
assert!(description.normal_image.is_some());
assert!(description.base_color_image.is_none());베이스 컬러 배율. (선형 rgb, 텍스처 색에 곱한다, 기본 흰색)
Base color factor. (linear rgb, multiplied by the texture color, default white)
반환Returns[f64; 3]
메탈릭 배율. (0 ~ 1, 기본 0)
Metallic factor. (0 ~ 1, default 0)
반환Returnsf64
러프니스 배율. (0 ~ 1, 기본 1)
Roughness factor. (0 ~ 1, default 1)
반환Returnsf64
이미시브 배율. (선형 rgb, 이미시브 텍스처에 곱한다, 기본 검정)
Emissive factor. (linear rgb, multiplied by the emissive texture, default black)
반환Returns[f64; 3]
베이스 컬러 이미지. (None 이면 1x1 흰색)
Base color image. (1x1 white when None)
반환ReturnsOption<ImageDescription>
노멀 맵 이미지. (None 이면 1x1 (128, 128, 255) 평평한 노멀)
Normal map image. (1x1 (128, 128, 255) flat normal when None)
반환ReturnsOption<ImageDescription>
메탈릭 러프니스 맵 이미지. (g 러프니스, b 메탈릭, None 이면 1x1 흰색)
Metallic roughness map image. (g roughness, b metallic, 1x1 white when None)
반환ReturnsOption<ImageDescription>
글로시니스 맵 이미지. (있으면 글로시니스 경로로 러프니스를 근사한다, None 이면 1x1 흰색)
Glossiness map image. (when present, roughness is approximated through the glossiness path, 1x1 white when None)
반환ReturnsOption<ImageDescription>
오클루전 맵 이미지. (None 이면 1x1 흰색)
Occlusion map image. (1x1 white when None)
반환ReturnsOption<ImageDescription>
이미시브 맵 이미지. (None 이면 1x1 흰색)
Emissive map image. (1x1 white when None)
반환ReturnsOption<ImageDescription>
스펙큘러 맵 이미지. (None 이면 1x1 흰색)
Specular map image. (1x1 white when None)
반환ReturnsOption<ImageDescription>
오파시티 맵 이미지. (있으면 알파 컷아웃을 켠다, None 이면 1x1 흰색)
Opacity map image. (when present, alpha cutout is turned on, 1x1 white when None)
반환ReturnsOption<ImageDescription>
Materialstruct
머티리얼.
- 셰이더 템플릿 하나를 여러 머티리얼이 나눠 들고, apply 가 그 셰이더에 팩터 유니폼과 텍스처 유닛을 건다.
Material.
- Several materials share one shader template, and apply sets the factor uniforms and texture units on that shader.
use vanilla::{ImageDescriptionOptions, Material, SkinnedModelRenderer};
fn create_material(gl: &vanilla::GlContext, skinned_model_renderer: &SkinnedModelRenderer) -> Result<Material, String> {
let mut description = Material::create_default_description();
description.base_color_factor = [0.8, 0.6, 0.5];
let bytes = std::fs::read("examples/assets/atlas/icons.png").map_err(|error| error.to_string())?;
let options = ImageDescriptionOptions { is_color_data: true, ..ImageDescriptionOptions::default() };
description.base_color_image = Some(Material::create_image_description(bytes, None, Some(options)));
let shader_program = skinned_model_renderer.get_shader_program();
let material = Material::create_from_description(gl, shader_program.clone(), &description)?;
shader_program.use_program(gl);
material.apply(gl);
Ok(material)
}생성. (텍스처 없음, 흰색 팩터, 메탈릭 1, 러프니스 1)
Constructor. (no textures, white factor, metallic 1, roughness 1)
- shader_programRc<ShaderProgram>
- 쓸 셰이더 템플릿. (렌더러의 get_shader_program 이 돌려주는 것)Shader template to use. (what the renderer's get_shader_program returns)
반환ReturnsMaterial 팩터가 흰색, 메탈릭 1, 러프니스 1 이고 기본 슬롯 텍스처가 모두 None 인 머티리얼. (서브서피스 팩터 1, 알파 컷아웃 꺼짐)A material with a white factor, metallic 1, roughness 1, and all default slot textures None. (subsurface factor 1, alpha cutout off)
짝Counterpart: vanilla.js Material.constructor
기본 머티리얼 서술 생성. (흰색 무광 비금속)
Creates a default material description. (white matte non-metal)
반환ReturnsMaterialDescription 베이스 흰색, 메탈릭 0, 러프니스 1, 이미시브 검정이고 이미지가 없는 서술.A description with a white base, metallic 0, roughness 1, black emissive and no images.
짝Counterpart: vanilla.js Material.createDefaultDescription
pub fn create_from_description(gl: &GlContext, shader_program: Rc<ShaderProgram>, description: &MaterialDescription) -> Result<Material, String>#중립 머티리얼 서술로부터 생성. (이미지 바이트 → GL 텍스처, 못 풀면 오류)
- 중간에 실패하면 그때까지 지은 텍스처를 지우고 오류를 돌려준다.
Creates from a neutral material description. (image bytes to GL textures, error if they cannot be decoded)
- If it fails midway, it deletes the textures made so far and returns the error.
- gl&GlContext
- GL 컨텍스트. (Graphic::get_gl 로 꺼낸다)GL context. (taken out with Graphic::get_gl)
- shader_programRc<ShaderProgram>
- 쓸 셰이더 템플릿. (렌더러의 get_shader_program 이 돌려주는 것)Shader template to use. (what the renderer's get_shader_program returns)
- description&MaterialDescription
- 팩터와 이미지를 담은 서술. (빈 이미지 슬롯은 1x1 대체색 텍스처)Description holding factors and images. (empty image slots become 1x1 fallback color textures)
반환ReturnsResult<Material, String> 기본 슬롯 8 개에 모두 텍스처를 지은 머티리얼. (glossiness_image 가 있으면 글로시니스 경로, opacity_image 가 있으면 알파 컷아웃)
이미지를 못 풀거나 텍스처를 못 만들면 Err(오류 글).A material with textures built for all 8 default slots. (glossiness path when glossiness_image is present, alpha cutout when opacity_image is present)
Err(error message) if an image cannot be decoded or a texture cannot be created.
짝Counterpart: vanilla.js Material.createFromDescription
pub fn create_texture(gl: &GlContext, image_description: Option<&ImageDescription>, fallback_color: [u8; 4]) -> Result<GlTexture, String>#텍스처 생성. (이미지 서술 → GL 텍스처, 없으면 1x1 단색 대체)
- is_color_data: sRGB 로 저장된 색 텍스처, 하드웨어 디코드(SRGB8_ALPHA8)로 선형 공간 샘플링.
- anisotropy: 이방성 필터 단계. (확장 미지원 시 무시)
Creates a texture. (image description → GL texture, 1x1 solid color fallback if none)
- is_color_data: a color texture stored in sRGB, sampled in linear space with hardware decode (SRGB8_ALPHA8).
- anisotropy: anisotropic filter level. (ignored if the extension is unsupported)
- gl&GlContext
- GL 컨텍스트.GL context.
- image_descriptionOption<&ImageDescription>
- 올릴 이미지. (None 이거나 bytes 가 비고 source 도 없으면 대체색)Image to upload. (fallback color when None, or when bytes is empty and there is no source)
- fallback_color[u8; 4]
- 대체색. (RGBA 바이트, 1x1 텍스처로 짓는다)Fallback color. (RGBA bytes, built as a 1x1 texture)
반환ReturnsResult<GlTexture, String> 새 GL 텍스처. (이미지면 밉맵, LINEAR_MIPMAP_LINEAR, 반복 감기) 이미지를 못 풀거나, 픽셀이 width x height x 4 바이트보다 적거나, 텍스처를 못 만들면 Err(오류 글).New GL texture. (for images: mipmaps, LINEAR_MIPMAP_LINEAR, repeat wrap) Err(error message) if the image cannot be decoded, the pixels are fewer than width x height x 4 bytes, or the texture cannot be created.
짝Counterpart: vanilla.js Material.createTexture
use vanilla::core::graphic::GlTexture;
use vanilla::{ImageDescriptionOptions, Material};
fn create_albedo_texture(gl: &vanilla::GlContext, bytes: Option<Vec<u8>>) -> Result<GlTexture, String> {
let options = ImageDescriptionOptions { is_color_data: true, anisotropy: 8.0, ..ImageDescriptionOptions::default() };
let image_description = bytes.map(|bytes| Material::create_image_description(bytes, None, Some(options)));
Material::create_texture(gl, image_description.as_ref(), [255, 255, 255, 255])
}pub fn create_image_description(bytes: Vec<u8>, mime_type: Option<String>, options: Option<ImageDescriptionOptions>) -> ImageDescription#바이트로 이미지 서술 생성. (원본 loadImageDescription 의 fetch 뒤 부분, 웹은 BlobAsset 바이트를 넘긴다)
Creates an image description from bytes. (the part after fetch of the original loadImageDescription, the web passes BlobAsset bytes)
- bytesVec<u8>
- 이미지 파일 내용. (png, jpeg, webp, gif, bmp, ico)Image file content. (png, jpeg, webp, gif, bmp, ico)
- mime_typeOption<String>
- 형. (응답의 content-type 같은 것, 해석에는 쓰지 않는다, 모르면 None)Type. (such as the response content-type, not used for decoding, None when unknown)
- optionsOption<ImageDescriptionOptions>
- 뒤집기, 색 데이터, 이방성 옵션. (None 이면 모두 끄고 0)Flip, color data and anisotropy options. (all off and 0 when None)
반환ReturnsImageDescription source 가 없는 이미지 서술. (여기서는 풀지 않고 create_texture 가 푼다)An image description without source. (not decoded here, create_texture decodes it)
짝Counterpart: vanilla.js Material.createImageDescription
pub fn load_image_description(engine: &Engine, url: &str, options: Option<ImageDescriptionOptions>) -> ImageDescriptionLoadHandle#애셋 경로(웹은 URL)로부터 이미지 서술 받기 부탁. (원본 정적 loadImageDescription, 다 받으면 손잡이의 get_image_description 이 만든다)
Requests an image description load from an asset path (URL on the web). (the original static loadImageDescription, once loaded the handle's get_image_description builds it)
- engine&Engine
- 애셋을 받을 엔진.Engine to load the asset with.
- url&str
- 애셋 경로. (데스크탑은 애셋 폴더 후보 기준, 웹은 asset_base_url 기준 주소, data: 주소도 된다)Asset path. (relative to the asset folder candidates on desktop, an address relative to asset_base_url on the web, data: addresses also work)
- optionsOption<ImageDescriptionOptions>
- 서술 옵션. (None 이면 모두 끄고 0)Description options. (all off and 0 when None)
반환ReturnsImageDescriptionLoadHandle 받기 손잡이. (데스크탑은 그 자리에서 읽어 이미 끝나 있고, 웹은 fetch 가 끝나야 끝난다, get_image_description 이나 await 로 서술을 받는다)Load handle. (on desktop it is read on the spot and already finished, on the web it finishes when fetch finishes, get the description with get_image_description or await)
짝Counterpart: vanilla.js Material.loadImageDescription
use vanilla::{Engine, ImageDescriptionLoadHandle, ImageDescriptionOptions, Material, Scene, SceneBase};
struct TextureScene {
scene_base: SceneBase,
load_handle: Option<ImageDescriptionLoadHandle>,
}
impl Scene for TextureScene {
fn get_scene_base(&self) -> &SceneBase {
&self.scene_base
}
fn get_scene_base_mut(&mut self) -> &mut SceneBase {
&mut self.scene_base
}
fn load(&mut self, engine: &Engine) {
let options = ImageDescriptionOptions { is_color_data: true, ..ImageDescriptionOptions::default() };
let load_handle = Material::load_image_description(engine, "examples/assets/atlas/icons.png", Some(options));
self.scene_base.track_load_handle(load_handle.get_load_handle());
self.load_handle = Some(load_handle);
}
fn initialize(&mut self, _engine: &Engine) {
if let Some(Some(Ok(image_description))) = self.load_handle.as_ref().map(|load_handle| load_handle.get_image_description()) {
assert!(!image_description.bytes.is_empty());
}
}
}pub fn set_texture(&self, uniform_name: &str, texture_unit: u32, texture: Option<GlTexture>)#추가 텍스처 설정. (셰이더 템플릿 고유 슬롯, 기본 슬롯 밖의 유니폼 이름 / 텍스처 유닛)
- 유닛 1 은 섀도우 맵 전용, 0 / 2~8 은 기본 슬롯이므로 9 이상을 사용한다. 같은 이름은 자리를 지키고 값만 바꾼다.
Sets an extra texture. (a slot specific to the shader template, uniform name / texture unit outside the default slots)
- Unit 1 is reserved for the shadow map and 0 / 2~8 are default slots, so use 9 or above. The same name keeps its position and only its value changes.
- uniform_name&str
- 셰이더의 샘플러 유니폼 이름.Name of the shader's sampler uniform.
- texture_unitu32
- 텍스처 유닛. (9 이상)Texture unit. (9 or above)
- textureOption<GlTexture>
- 묶을 텍스처. (None 이면 그 유닛을 비워 묶는다, 지우는 것은 건 쪽이 한다)Texture to bind. (when None, the unit is bound empty, deleting is up to the side that set it)
짝Counterpart: vanilla.js Material.setTexture
use vanilla::{Material, SKIN_TEXTURE_UNIT_DETAILHEIGHT};
fn attach_detail_height(gl: &vanilla::GlContext, material: &Material) -> Result<(), String> {
let detail_height_texture = Material::create_texture(gl, None, [128, 128, 128, 255])?;
material.set_texture("detailHeightTexture", SKIN_TEXTURE_UNIT_DETAILHEIGHT, Some(detail_height_texture));
Ok(())
}적용. (참조 셰이더에 유니폼 설정 + 텍스처 유닛 바인드)
- 유니폼은 지금 쓰는 프로그램에 걸리므로 참조 셰이더를 먼저 use_program 해 둔다. 끝나면 TEXTURE0 이 활성이다.
Apply. (sets uniforms on the referenced shader + binds texture units)
- Uniforms go to the program currently in use, so call use_program on the referenced shader first. TEXTURE0 is active afterward.
- gl&GlContext
- GL 컨텍스트.GL context.
짝Counterpart: vanilla.js Material.apply
참조 셰이더 프로그램 반환. (머티리얼 템플릿의 셰이더)
Returns the referenced shader program. (the material template's shader)
반환Returns&Rc<ShaderProgram> 참조 셰이더 프로그램. (렌더러와 나눠 든 것)Referenced shader program. (shared with the renderer)
짝Counterpart: vanilla.js Material.getShaderProgram
베이스 컬러 팩터 반환.
Returns the base color factor.
반환Returns[f64; 3] 베이스 컬러 배율. (선형 rgb)Base color factor. (linear rgb)
짝Counterpart: vanilla.js Material.getBaseColorFactor
베이스 컬러 팩터 설정. (선형 rgb 배율, 나눠 쓰는 머티리얼이면 그것을 쓰는 모든 모델이 바뀐다)
Set the base color factor. (linear rgb multiplier; on a shared material every model using it changes)
- base_color_factor[f64; 3]
- 베이스 컬러 배율. (선형 rgb)Base color factor. (linear rgb)
짝Counterpart: vanilla.js Material.setBaseColorFactor
use std::rc::Rc;
use vanilla::{Material, ShaderProgram};
fn tint_instance(shared_material: &Rc<Material>) -> Material {
let instance_material = shared_material.create_instance();
instance_material.set_base_color_factor([1.0, 0.4, 0.4]);
instance_material
}
fn check(shader_program: Rc<ShaderProgram>) {
let shared_material = Rc::new(Material::new(shader_program));
let instance_material = tint_instance(&shared_material);
assert_eq!(shared_material.get_base_color_factor(), [1.0, 1.0, 1.0]);
assert_eq!(instance_material.get_base_color_factor(), [1.0, 0.4, 0.4]);
}
let _ = check;머티리얼 사본 만들기. (유니티의 material 과 sharedMaterial 처럼 값만 갈라지고 텍스처는 원본 것을 빌려 쓴다)
- 팩터, 플래그, 기본 슬롯 텍스처, set_texture 로 넣은 추가 텍스처를 그대로 베낀다. GPU 텍스처는 새로 올리지 않는다.
- 사본의 destroy 는 빌린 텍스처를 지우지 않는다. 원본(텍스처를 지은 머티리얼)을 지우기 전에 사본을 다 쓴다.
Create a material copy. (like Unity's material and sharedMaterial, only the values fork and the textures are borrowed from the original)
- Copies the factors, flags, default slot textures and extra textures added with set_texture. No GPU texture is uploaded again.
- The copy's destroy does not delete the borrowed textures. Finish using the copies before destroying the original (the material that created the textures).
반환ReturnsMaterial 같은 셰이더와 텍스처를 쓰고 값은 따로 바꿀 수 있는 사본. (텍스처 바이트 수는 0)Copy that uses the same shader and textures with values that can change separately. (texture byte count 0)
짝Counterpart: vanilla.js Material.createInstance
텍스처 바이트 수 반환. (이 머티리얼이 지은 기본 슬롯 텍스처의 GPU 바이트, 밉맵 포함, 사본은 0)
Return the texture byte count. (GPU bytes of the default slot textures this material created, including mipmaps; 0 for a copy)
반환Returnsusize GPU 텍스처 바이트 수. (RGBA8 로 셈, 단색 1x1 은 4)GPU texture byte count. (counted as RGBA8, a solid 1x1 is 4)
짝Counterpart: vanilla.js Material.getTextureByteCount
메탈릭 팩터 반환.
Returns the metallic factor.
반환Returnsf64 메탈릭 배율.Metallic factor.
짝Counterpart: vanilla.js Material.getMetallicFactor
러프니스 팩터 반환.
Returns the roughness factor.
반환Returnsf64 러프니스 배율.Roughness factor.
짝Counterpart: vanilla.js Material.getRoughnessFactor
이미시브 팩터 반환.
Returns the emissive factor.
반환Returns[f64; 3] 이미시브 배율. (선형 rgb)Emissive factor. (linear rgb)
짝Counterpart: vanilla.js Material.getEmissiveFactor
글로시니스 경로 사용 여부 반환.
Returns whether the glossiness path is used.
반환Returnsbool 글로시니스 맵으로 러프니스를 근사하면 true. (서술에 glossiness_image 가 있었을 때)true if roughness is approximated with the glossiness map. (when the description had glossiness_image)
짝Counterpart: vanilla.js Material.getUseGlossiness
서브서피스 팩터 설정. (피부 셰이더의 화면 공간 산란 마스크 배율, 눈 / 치아처럼 산란하지 않는 부위는 0)
Sets the subsurface factor. (screen-space scattering mask multiplier of the skin shader, 0 for non-scattering parts like eyes / teeth)
- subsurface_factorf64
- 산란 마스크 배율. (기본 1, 0 이면 산란하지 않음)Scattering mask multiplier. (default 1, no scattering at 0)
짝Counterpart: vanilla.js Material.setSubsurfaceFactor
서브서피스 팩터 반환.
Returns the subsurface factor.
반환Returnsf64 서브서피스 팩터. (기본 1)Subsurface factor. (default 1)
짝Counterpart: vanilla.js Material.getSubsurfaceFactor
알파 컷아웃 사용 여부 설정. (오파시티 텍스처를 나중에 붙인 머티리얼용)
Sets whether alpha cutout is used. (for materials with an opacity texture attached later)
- use_alpha_cutoutbool
- true 면 오파시티 텍스처로 투명한 곳을 잘라 낸다.If true, transparent areas are cut out with the opacity texture.
짝Counterpart: vanilla.js Material.setUseAlphaCutout
알파 컷아웃 사용 여부 반환. (오파시티 맵 보유 시, 머리카락/속눈썹 등)
Returns whether alpha cutout is used. (when it has an opacity map, hair/eyelashes etc.)
반환Returnsbool 알파 컷아웃을 쓰면 true.true if alpha cutout is used.
짝Counterpart: vanilla.js Material.getUseAlphaCutout
텍스처 바인딩 목록 반환. (유니폼 이름 / 텍스처 유닛 / GL 텍스처, 기본 슬롯 8개 뒤에 추가 슬롯)
Returns the texture binding list. (uniform name / texture unit / GL texture, extra slots after the 8 default slots)
반환ReturnsVec<(String, u32, Option<GlTexture>)> (유니폼 이름, 텍스처 유닛, 텍스처) 목록. (기본 슬롯 8 개 다음에 set_texture 로 건 추가 슬롯을 건 차례로)(uniform name, texture unit, texture) list. (the 8 default slots, then the extra slots set with set_texture in the order they were set)
짝Counterpart: vanilla.js Material.getTextureBindings
파괴. (기본 슬롯 텍스처 해제, 추가 슬롯 텍스처는 건 쪽이 지운다)
Destroy. (frees the default slot textures, extra slot textures are deleted by the side that set them)
- gl&GlContext
- 만들 때 쓴 GL 컨텍스트.GL context used at creation.
짝Counterpart: vanilla.js Material.destroy
함수Functions
이미지 바이트 해석. (png / jpeg / webp → 너비, 높이, 스트레이트 알파 RGBA)
Decodes image bytes. (png / jpeg / webp → width, height, straight alpha RGBA)
- bytes&[u8]
- 이미지 파일 내용. (형은 내용으로 가린다)Image file content. (the format is detected from the content)
반환ReturnsResult<(u32, u32, Vec<u8>), String> (너비, 높이, 스트레이트 알파 RGBA 바이트). 못 풀면 Err("Material: image decode failed: 까닭").(width, height, straight alpha RGBA bytes). Err("Material: image decode failed: reason") if it cannot be decoded.
use vanilla::graphics3d::material::decode_image_bytes;
let bytes = std::fs::read("examples/assets/atlas/icons.png").unwrap();
let (width, height, pixels) = decode_image_bytes(&bytes).unwrap();
assert_eq!((width, height), (128, 128));
assert_eq!(pixels.len(), 128 * 128 * 4);
assert!(decode_image_bytes(&[1, 2, 3]).is_err());픽셀 행 위아래 뒤집기. (원본 createImageBitmap 의 imageOrientation: "flip_y")
Flips pixel rows vertically. (the original createImageBitmap imageOrientation: "flip_y")
- pixels&mut [u8]
- RGBA 바이트. (제자리에서 바꾼다, width x height x 4 바이트보다 짧으면 패닉)RGBA bytes. (changed in place, panics if shorter than width x height x 4 bytes)
- widthusize
- 가로 픽셀 수.Width in pixels.
- heightusize
- 세로 픽셀 수.Height in pixels.
use vanilla::graphics3d::material::flip_pixel_rows;
let mut pixels = vec![255, 0, 0, 255, 0, 0, 255, 255];
flip_pixel_rows(&mut pixels, 1, 2);
assert_eq!(pixels, vec![0, 0, 255, 255, 255, 0, 0, 255]);상수Constants
텍스처 유닛 배치. (1번은 SkinnedModel 의 섀도우 맵 전용, 사용 금지)
Texture unit layout. (unit 1 is reserved for the SkinnedModel shadow map, do not use)
반환Returnsu32
섀도우 맵 유닛. (SkinnedModel 렌더러 전용, 머티리얼은 쓰지 않는다)
Shadow map unit. (SkinnedModel renderer only, materials do not use it)
반환Returnsu32
노멀 맵 유닛. (유니폼 normalTexture)
Normal map unit. (uniform normalTexture)
반환Returnsu32
메탈릭 러프니스 맵 유닛. (유니폼 metallicRoughnessTexture)
Metallic roughness map unit. (uniform metallicRoughnessTexture)
반환Returnsu32
글로시니스 맵 유닛. (유니폼 glossinessTexture, FBX 스펙큘러/글로스 경로)
Glossiness map unit. (uniform glossinessTexture, FBX specular/gloss path)
반환Returnsu32
오클루전 맵 유닛. (유니폼 occlusionTexture)
Occlusion map unit. (uniform occlusionTexture)
반환Returnsu32
이미시브 맵 유닛. (유니폼 emissiveTexture)
Emissive map unit. (uniform emissiveTexture)
반환Returnsu32
스펙큘러 맵 유닛. (유니폼 specularTexture)
Specular map unit. (uniform specularTexture)
반환Returnsu32
오파시티 맵 유닛. (유니폼 opacityTexture, 알파 컷아웃)
Opacity map unit. (uniform opacityTexture, alpha cutout)
반환Returnsu32