vanilladocs
vanillapunch.com
API / graphics3d/material

graphics3d/material

머티리얼. (셰이더 템플릿 참조 + metallic-roughness PBR 파라미터/텍스처, 포맷 중립)

Material. (shader template reference + metallic-roughness PBR parameters/textures, format-neutral)

Materialextends Object

짝Counterpart: vanilla-engine Material

머티리얼. (셰이더 템플릿 참조 + metallic-roughness PBR 파라미터/텍스처, 포맷 중립)

  • 셰이더(템플릿)를 참조하는 인스턴스로, 모델은 머티리얼 인스턴스를 적용만 한다.
  • 임포터가 만든 중립 머티리얼 서술(팩터 + 이미지 바이트)로부터 GL 텍스처를 생성한다.
  • FBX 의 스펙큘러/글로스 맵은 glossiness 경로로 러프니스를 근사한다.

Material. (shader template reference + metallic-roughness PBR parameters/textures, format-neutral)

  • An instance that references a shader (template), and the model only applies the material instance.
  • Creates GL textures from the neutral material description (factors + image bytes) made by the importer.
  • FBX specular/gloss maps approximate roughness through the glossiness path.
예제Example외부 텍스처로 머티리얼을 지어 모델에 입히기Build a material from an external texture and apply it to a model
import { Material, SkinnedModel, SkinnedModelRenderer } from "./build/vanilla.js";

const canvas = document.createElement("canvas");
const webGL2RenderingContext = canvas.getContext("webgl2");
const skinnedModelRenderer = new SkinnedModelRenderer(webGL2RenderingContext);
const shaderProgram = skinnedModelRenderer.getShaderProgram();
const description = Material.createDefaultDescription();
description.baseColorFactor = [1.0, 0.8, 0.6];
description.roughnessFactor = 0.7;
description.baseColorImage = await Material.loadImageDescription("assets/icons/icon.png", { isColorData: true, anisotropy: 4 });
const material = await Material.createFromDescription(webGL2RenderingContext, shaderProgram, description);
const skinnedModel = await SkinnedModel.loadFromUrl(webGL2RenderingContext, "examples/ancientmountain/assets/fox.glb", skinnedModelRenderer);
skinnedModel.setMaterial(0, material);
const textureBindings = material.getTextureBindings();
console.log(textureBindings.length);
생성자constructorconstructor(webGL2RenderingContext, shaderProgram)#0.3.0 부터since 0.3.0소스source

생성.

Constructor.

webGL2RenderingContextWebGL2RenderingContext
WebGL2 렌더링 컨텍스트.WebGL2 rendering context.
shaderProgramShaderProgram
유니폼을 넣을 셰이더 프로그램. (머티리얼 템플릿)Shader program to set uniforms on. (the material template)

짝Counterpart: vanilla-engine Material.new

정적staticstatic createDefaultDescription()#0.3.0 부터since 0.3.0소스source

기본 머티리얼 서술 생성. (정적, 흰색 무광 비금속)

Creates a default material description. (static, white matte non-metal)

반환Returnsobject 기본 서술. ({ baseColorFactor, metallicFactor, roughnessFactor, emissiveFactor } 와 이미지 칸 8 개, 흰색, 메탈릭 0, 러프니스 1, 이미지는 모두 null)Default description. ({ baseColorFactor, metallicFactor, roughnessFactor, emissiveFactor } and 8 image slots, white, metallic 0, roughness 1, all images null)

짝Counterpart: vanilla-engine Material.create_default_description

정적staticstatic async createFromDescription(webGL2RenderingContext, shaderProgram, description)#0.3.0 부터since 0.3.0소스source

중립 머티리얼 서술로부터 생성. (정적, 이미지 바이트 → GL 텍스처)

  • 중간에 이미지를 풀지 못하면 그때까지 지은 텍스처를 지우고 오류를 던진다.

Creates from a neutral material description. (static, image bytes → GL textures)

  • If an image cannot be decoded midway, it deletes the textures created so far and throws an error.
webGL2RenderingContextWebGL2RenderingContext
WebGL2 렌더링 컨텍스트.WebGL2 rendering context.
shaderProgramShaderProgram
참조할 셰이더 프로그램.Shader program to reference.
descriptionobject
중립 머티리얼 서술. (createDefaultDescription 꼴, 이미지 칸이 null 이면 1x1 단색 텍스처)Neutral material description. (createDefaultDescription shape, a null image slot becomes a 1x1 solid color texture)

반환ReturnsPromise<Material> 텍스처까지 올린 머티리얼. (이미지를 풀지 못하면 거절된다)Material with its textures uploaded. (rejected if an image cannot be decoded)

짝Counterpart: vanilla-engine Material.create_from_description

정적staticstatic async loadImageDescription(url, options = null)#0.3.0 부터since 0.3.0소스source

URL 로부터 이미지 서술 로드. (정적, 외부 텍스처 파일을 중립 이미지 서술로)

  • options: { flipY, isColorData, anisotropy }

Loads an image description from a URL. (static, an external texture file into a neutral image description)

  • options: { flipY, isColorData, anisotropy }
urlstring
텍스처 파일 주소.Texture file URL.
optionsobject | null
{ flipY = false, isColorData = false, anisotropy = 0 } (null 이면 모두 기본값){ flipY = false, isColorData = false, anisotropy = 0 } (all defaults when null)

반환ReturnsPromise<object> 이미지 서술. (응답이 실패면 오류를 던진다)Image description. (throws when the response fails)

짝Counterpart: vanilla-engine Material.load_image_description

정적staticstatic createImageDescription(bytes, mimeType = null, options = null)#0.4.0 부터since 0.4.0소스source

바이트로부터 이미지 서술 만들기. (정적, loadImageDescription 의 fetch 뒤 부분, 번들이나 BlobAsset 으로 이미 받은 바이트)

  • options: { flipY, isColorData, anisotropy }

Makes an image description from bytes. (static, the part of loadImageDescription after fetch, for bytes already received via a bundle or BlobAsset)

  • options: { flipY, isColorData, anisotropy }
bytesUint8Array
이미지 파일 바이트.Image file bytes.
mimeTypestring | null
이미지 MIME 꼴. (null 이면 꼴 없이 Blob 을 짓는다)Image MIME type. (when null, the Blob is built without a type)
optionsobject | null
{ flipY = false, isColorData = false, anisotropy = 0 } (null 이면 모두 기본값){ flipY = false, isColorData = false, anisotropy = 0 } (all defaults when null)

반환Returnsobject 이미지 서술. ({ bytes, mimeType, flipY, isColorData, anisotropy })Image description. ({ bytes, mimeType, flipY, isColorData, anisotropy })

짝Counterpart: vanilla-engine Material.create_image_description

예제Example이미 받은 바이트로 이미지 서술 만들기Create an image description from bytes already received
import { Material } from "./build/vanilla.js";

const response = await fetch("assets/icons/icon.png");
const arrayBuffer = await response.arrayBuffer();
const bytes = new Uint8Array(arrayBuffer);
const imageDescription = Material.createImageDescription(bytes, "image/png", { flipY: true, isColorData: true });
console.log(imageDescription.mimeType, imageDescription.flipY, imageDescription.anisotropy);
메서드methodasync createTexture(imageDescription, fallbackColor)#0.3.0 부터since 0.3.0소스source

텍스처 생성. (이미지 서술 → GL 텍스처, 없으면 1x1 단색 대체)

  • 이미지 서술: { bytes, mimeType, flipY } 또는 { source(캔버스/비트맵), flipY }
  • isColorData: sRGB 로 저장된 색 텍스처, 하드웨어 디코드(SRGB8_ALPHA8)로 선형 공간 샘플링.
  • anisotropy: 이방성 필터 단계. (확장 미지원 시 무시)
  • 그림을 다 푼 뒤에 텍스처를 짓는다. (풀지 못하면 텍스처를 남기지 않고, 기다리는 동안 다른 텍스처가 묶여도 이 텍스처에 올린다)

Creates a texture. (image description → GL texture, 1x1 solid color fallback if none)

  • Image description: { bytes, mimeType, flipY } or { source (canvas/bitmap), flipY }
  • isColorData: 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)
  • The texture is created after the image is fully decoded. (no texture is left behind if decoding fails, and the upload goes to this texture even if another texture is bound while waiting)
imageDescriptionobject | null
이미지 서술. ({ bytes, mimeType, flipY, isColorData, anisotropy } 나 { source, flipY, isColorData, anisotropy }, null 이거나 비면 단색)Image description. ({ bytes, mimeType, flipY, isColorData, anisotropy } or { source, flipY, isColorData, anisotropy }, solid color when null or empty)
fallbackColornumber[]
이미지가 없을 때 쓸 1x1 색. ([r, g, b, a], 0 ~ 255)1x1 color used when there is no image. ([r, g, b, a], 0 ~ 255)

반환ReturnsPromise<WebGLTexture> 지은 GL 텍스처. (이미지면 밉맵과 반복 감싸기, 이미지를 풀지 못하면 거절된다)The created GL texture. (mipmapped with repeat wrapping for images, rejected if the image cannot be decoded)

짝Counterpart: vanilla-engine Material.create_texture

메서드methodsetTexture(uniformName, textureUnit, glTexture)#0.3.0 부터since 0.3.0소스source

추가 텍스처 설정. (셰이더 템플릿 고유 슬롯, 기본 슬롯 밖의 유니폼 이름 / 텍스처 유닛)

  • 유닛 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.
uniformNamestring
셰이더의 sampler2D 유니폼 이름.Name of the shader's sampler2D uniform.
textureUnitnumber
텍스처 유닛 번호. (9 이상)Texture unit number. (9 or above)
glTextureWebGLTexture
묶을 GL 텍스처. (destroy 가 지우지 않는다)GL texture to bind. (destroy does not delete it)

짝Counterpart: vanilla-engine Material.set_texture

예제Example셰이더 고유 슬롯에 텍스처 더하기Add a texture to a shader-specific slot
import { Material, HumanSkinRenderer, SKIN_TEXTURE_UNIT_DETAILHEIGHT } from "./build/vanilla.js";

const canvas = document.createElement("canvas");
const webGL2RenderingContext = canvas.getContext("webgl2");
const humanSkinRenderer = new HumanSkinRenderer(webGL2RenderingContext);
const shaderProgram = humanSkinRenderer.getShaderProgram();
const description = Material.createDefaultDescription();
const material = await Material.createFromDescription(webGL2RenderingContext, shaderProgram, description);
const heightImageDescription = await Material.loadImageDescription("assets/icons/icon.png");
const heightTexture = await material.createTexture(heightImageDescription, [128, 128, 128, 255]);
material.setTexture("detailHeightTexture", SKIN_TEXTURE_UNIT_DETAILHEIGHT, heightTexture);
const textureBindings = material.getTextureBindings();
console.log(textureBindings.length);
메서드methodapply()#0.3.0 부터since 0.3.0소스source

적용. (참조 셰이더에 유니폼 설정 + 텍스처 유닛 바인드)

Applies. (sets uniforms on the referenced shader + binds texture units)

짝Counterpart: vanilla-engine Material.apply

메서드methodgetShaderProgram()#0.3.0 부터since 0.3.0소스source

참조 셰이더 프로그램 반환. (머티리얼 템플릿의 셰이더)

Returns the referenced shader program. (the material template's shader)

반환ReturnsShaderProgram 참조 셰이더 프로그램.Referenced shader program.

짝Counterpart: vanilla-engine Material.get_shader_program

메서드methodgetBaseColorFactor()#0.3.0 부터since 0.3.0소스source

베이스 컬러 팩터 반환.

Returns the base color factor.

반환Returnsnumber[] 베이스 컬러 팩터. ([r, g, b])Base color factor. ([r, g, b])

짝Counterpart: vanilla-engine Material.get_base_color_factor

메서드methodgetMetallicFactor()#0.3.0 부터since 0.3.0소스source

메탈릭 팩터 반환.

Returns the metallic factor.

반환Returnsnumber 메탈릭 팩터.Metallic factor.

짝Counterpart: vanilla-engine Material.get_metallic_factor

메서드methodgetRoughnessFactor()#0.3.0 부터since 0.3.0소스source

러프니스 팩터 반환.

Returns the roughness factor.

반환Returnsnumber 러프니스 팩터.Roughness factor.

짝Counterpart: vanilla-engine Material.get_roughness_factor

메서드methodgetEmissiveFactor()#0.3.0 부터since 0.3.0소스source

이미시브 팩터 반환.

Returns the emissive factor.

반환Returnsnumber[] 이미시브 팩터. ([r, g, b])Emissive factor. ([r, g, b])

짝Counterpart: vanilla-engine Material.get_emissive_factor

메서드methodgetUseGlossiness()#0.3.0 부터since 0.3.0소스source

글로시니스 경로 사용 여부 반환.

Returns whether the glossiness path is used.

반환Returnsboolean 글로시니스 텍스처로 러프니스를 구하면 참.True when roughness is derived from the glossiness texture.

짝Counterpart: vanilla-engine Material.get_use_glossiness

메서드methodsetBaseColorFactor(baseColorFactor)#0.4.0 부터since 0.4.0소스source

베이스 컬러 팩터 설정. (선형 rgb 배율, 나눠 쓰는 머티리얼이면 그것을 쓰는 모든 모델이 바뀐다)

Set the base color factor. (linear rgb multiplier; on a shared material every model using it changes)

baseColorFactornumber[]
베이스 컬러 배율. ([r, g, b], 선형, 앞 세 값을 베껴 둔다)Base color factor. ([r, g, b], linear, the first three values are copied)

짝Counterpart: vanilla-engine Material.set_base_color_factor

예제Example머티리얼 사본만 붉게 물들이기Tint only the material copy red
import { Material, SkinnedModelRenderer } from "./build/vanilla.js";

const canvas = document.createElement("canvas");
const webGL2RenderingContext = canvas.getContext("webgl2");
const skinnedModelRenderer = new SkinnedModelRenderer(webGL2RenderingContext);
const shaderProgram = skinnedModelRenderer.getShaderProgram();
const description = Material.createDefaultDescription();
const sharedMaterial = await Material.createFromDescription(webGL2RenderingContext, shaderProgram, description);
const instanceMaterial = sharedMaterial.createInstance();
instanceMaterial.setBaseColorFactor([1, 0.4, 0.4]);
console.log(sharedMaterial.getBaseColorFactor().join(", "), instanceMaterial.getBaseColorFactor().join(", "));
instanceMaterial.destroy();
sharedMaterial.destroy();
메서드methodcreateInstance()#0.4.0 부터since 0.4.0소스source

머티리얼 사본 만들기. (유니티의 material 과 sharedMaterial 처럼 값만 갈라지고 텍스처는 원본 것을 빌려 쓴다)

  • 팩터, 플래그, 기본 슬롯 텍스처, setTexture 로 넣은 추가 텍스처를 그대로 베낀다. 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 setTexture. 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-engine Material.create_instance

메서드methodgetTextureByteCount()#0.4.0 부터since 0.4.0소스source

텍스처 바이트 수 반환. (이 머티리얼이 지은 기본 슬롯 텍스처의 GPU 바이트, 밉맵 포함, 사본은 0)

Return the texture byte count. (GPU bytes of the default slot textures this material created, including mipmaps; 0 for a copy)

반환Returnsnumber GPU 텍스처 바이트 수. (RGBA8 로 셈, 단색 1x1 은 4)GPU texture byte count. (counted as RGBA8, a solid 1x1 is 4)

짝Counterpart: vanilla-engine Material.get_texture_byte_count

메서드methodsetSubsurfaceFactor(subsurfaceFactor)#0.3.0 부터since 0.3.0소스source

서브서피스 팩터 설정. (피부 셰이더의 화면 공간 산란 마스크 배율, 눈 / 치아처럼 산란하지 않는 부위는 0)

Sets the subsurface factor. (screen-space scattering mask multiplier of the skin shader, 0 for non-scattering parts like eyes / teeth)

subsurfaceFactornumber
산란 마스크 배율. (기본 1, 산란하지 않는 부위는 0)Scattering mask multiplier. (default 1, 0 for parts that do not scatter)

짝Counterpart: vanilla-engine Material.set_subsurface_factor

메서드methodgetSubsurfaceFactor()#0.3.0 부터since 0.3.0소스source

서브서피스 팩터 반환.

Returns the subsurface factor.

반환Returnsnumber 산란 마스크 배율.Scattering mask multiplier.

짝Counterpart: vanilla-engine Material.get_subsurface_factor

메서드methodsetUseAlphaCutout(useAlphaCutout)#0.3.0 부터since 0.3.0소스source

알파 컷아웃 사용 여부 설정. (오파시티 텍스처를 나중에 붙인 머티리얼용)

Sets whether alpha cutout is used. (for materials with an opacity texture attached later)

useAlphaCutoutboolean
참이면 알파 컷아웃을 쓴다.Uses alpha cutout when true.

짝Counterpart: vanilla-engine Material.set_use_alpha_cutout

메서드methodgetUseAlphaCutout()#0.3.0 부터since 0.3.0소스source

알파 컷아웃 사용 여부 반환. (오파시티 맵 보유 시, 머리카락/속눈썹 등)

Returns whether alpha cutout is used. (when it has an opacity map, hair/eyelashes etc.)

반환Returnsboolean 알파 컷아웃을 쓰면 참.True when alpha cutout is used.

짝Counterpart: vanilla-engine Material.get_use_alpha_cutout

메서드methodgetTextureBindings()#0.3.0 부터since 0.3.0소스source

텍스처 바인딩 목록 반환. (유니폼 이름 / 텍스처 유닛 / GL 텍스처)

Returns the texture binding list. (uniform name / texture unit / GL texture)

반환ReturnsArray<[string, number, WebGLTexture]> [유니폼 이름, 텍스처 유닛, GL 텍스처] 목록. (기본 슬롯 8 개 뒤에 setTexture 로 넣은 것)List of [uniform name, texture unit, GL texture]. (the 8 default slots followed by those added with setTexture)

짝Counterpart: vanilla-engine Material.get_texture_bindings

메서드methodgetWebGL2RenderingContext()#0.3.0 부터since 0.3.0소스source

렌더링 컨텍스트 반환.

Returns the rendering context.

반환ReturnsWebGL2RenderingContext 렌더링 컨텍스트.Rendering context.

메서드methoddestroy()#0.4.0 부터since 0.4.0소스source

파괴. (기본 슬롯 텍스처를 지운다, setTexture 로 넣은 추가 텍스처는 넣은 쪽 것이라 남긴다)

  • createInstance 로 만든 사본은 빌린 텍스처를 지우지 않고 슬롯만 비운다.

Destroy. (deletes the default slot textures; extra textures added with setTexture belong to whoever added them and stay)

  • A copy made with createInstance does not delete the borrowed textures and only clears the slots.

짝Counterpart: vanilla-engine Material.destroy