vanilladocs
vanillapunch.com
API / graphics3d/shadowmap

graphics3d/shadowmap

섀도우 맵. (원본 graphics3d/shadowmap.js)

  • 방향광 실시간 그림자, 깊이 텍스처(하드웨어 비교 샘플링, sampler2DShadow) + 직교 광원 행렬.
  • begin_render() 로 깊이 패스를 시작하고, 결과 텍스처를 본 패스에서 샘플링한다.
  • 광원 행렬은 텍셀 단위로 스냅해 이동 시 그림자 가장자리 떨림을 줄인다. 빛이 거의 바로 위나 아래로 나아가면 위쪽을 z 축으로 잡아 행렬이 깨지지 않게 한다.
  • 지을 때 앞의 텍스처와 프레임버퍼 묶음을 돌린다. (모형을 지은 뒤에 지어도 깊이 텍스처가 텍스처 유닛에 남아 그리기가 INVALID_OPERATION 이 되지 않게)
  • ShadowAtlas: 점광과 스포트라이트의 그림자를 깊이 텍스처 한 장에 칸으로 나눠 담는다. (원본 ShadowAtlas, 유니티 URP 의 추가 빛 그림자 아틀라스 꼴) 칸 크기는 URP 기본과 같이 정한다. 칸마다 tile_resolution 을 바라고, 아틀라스에 다 들어가지 않으면 다 들어갈 때까지 칸 한 변을 반씩 줄인다. (점광 하나면 512, 스포트라이트 하나면 1024) 툰 셰이더는 받는 자리를 노멀 쪽으로 그 거리의 칸 텍셀 (1 + 3 x (1 - dot(N, L))) 개만큼 밀어 견준다. (빛에 비스듬한 면일수록 크게, 그림자 여드름을 막는다)
  • 텍셀 스냅의 반올림은 원본 Math.round 와 같이 0.5 를 위로 올린다. (러스트 round 는 0 에서 먼 쪽이라 음수에서 다르다)
  • 원본 해상도 기본값 인자 2048 은 DEFAULT_SHADOWMAP_RESOLUTION 으로 둔다. (러스트에 기본값 인자가 없다)
  • 해 그림자 치우침은 set_bias(깊이, 노멀) 의 그림자 텍셀 단위 값이다. (기본 1, 1, 유니티 URP 의 Depth Bias, Normal Bias 와 같은 단위, 받는 쪽 ToonRenderer 가 텍셀 크기와 기울기를 곱해 건다)
  • 그림자 갱신 방식(원본 ShadowUpdateMode)은 ShadowMap 과 ShadowAtlas 가 하나씩 가진 그림자 깊이 캐시(원본 createShadowCache)에 둔다. ToonDrawQueue 가 견주고 begin_render 가 그 결정대로 묶는다. begin_render 가 &self 로 캐시를 고치므로 캐시는 RefCell 에 둔다. (원본은 객체 안 값을 바로 고친다)

Shadow map. (original graphics3d/shadowmap.js)

  • Real-time directional light shadows, a depth texture (hardware compare sampling, sampler2DShadow) and an orthographic light matrix.
  • begin_render() starts the depth pass, and the main pass samples the resulting texture.
  • The light matrix snaps to texel units to reduce shadow edge shimmer while moving. When the light points almost straight up or down, the up axis is taken as z so the matrix does not break.
  • Construction restores the previous texture and framebuffer bindings. (so building it after models does not leave the depth texture on a texture unit and make drawing INVALID_OPERATION)
  • ShadowAtlas: stores point light and spot light shadows as tiles in one depth texture. (original ShadowAtlas, the form of Unity URP's additional light shadow atlas) Tile size follows the URP default. Each tile asks for tile_resolution, and if they do not all fit in the atlas, the tile side is halved until they fit. (512 for one point light, 1024 for one spot light) The toon shader pushes the receiving position toward the normal by (1 + 3 x (1 - dot(N, L))) tile texels at that distance before comparing. (larger for surfaces at a grazing angle to the light, prevents shadow acne)
  • Texel snapping rounds 0.5 up, like the original Math.round. (Rust round goes away from zero, so it differs for negative numbers)
  • The original default resolution argument 2048 is DEFAULT_SHADOWMAP_RESOLUTION. (Rust has no default arguments)
  • The sun shadow bias is the shadow-texel value of set_bias(depth, normal). (default 1, 1, the same unit as Depth Bias and Normal Bias of Unity URP, the receiving ToonRenderer applies it multiplied by the texel size and slope)
  • The shadow update mode (the original ShadowUpdateMode) lives in the shadow depth cache that ShadowMap and ShadowAtlas each hold (the original createShadowCache). ToonDrawQueue compares, and begin_render binds by that decision. begin_render changes the cache through &self, so the cache sits in a RefCell. (The original changes the values in the object directly)

ShadowMapstruct

짝Counterpart: vanilla.js ShadowMap소스source

섀도우 맵.

  • 깊이 텍스처는 정사각형 DEPTH_COMPONENT24 이고 비교 모드(LEQUAL)라 셰이더에서 sampler2DShadow 로 읽는다.

Shadow map.

  • The depth texture is a square DEPTH_COMPONENT24 in comparison mode (LEQUAL), so shaders read it with sampler2DShadow.
예제Example한 프레임의 그림자 깊이 패스를 그리고 본 패스 렌더러에 섀도우 맵 넘기기Draw one frame's shadow depth pass and pass the shadow map to the main pass renderer
use vanilla::graphics3d::shadowmap::DEFAULT_SHADOWMAP_RESOLUTION;
use vanilla::{Matrix4, ShadowMap, SkinnedModel, SkinnedModelRenderer, Vector3};

fn create_shadow_map(gl: &vanilla::GlContext) -> Result<ShadowMap, String> {
	ShadowMap::new(gl, DEFAULT_SHADOWMAP_RESOLUTION)
}

fn render_shadow_pass(gl: &vanilla::GlContext, shadow_map: &mut ShadowMap, skinned_model_renderer: &mut SkinnedModelRenderer, skinned_model: &mut SkinnedModel) {
	let light_direction = Vector3::create(-0.5, -0.8, -0.35);
	shadow_map.update_light_matrix(Vector3::zero(), light_direction, 4.0, 0.5, 30.0);
	let light_view_projection_elements = *shadow_map.get_light_view_projection_matrix().get_elements();
	let model_matrix = Matrix4::create_identity();
	shadow_map.begin_render(gl);
	skinned_model_renderer.draw_depth(gl, skinned_model, &light_view_projection_elements, model_matrix.get_elements());
	let texel_size = 1.0 / shadow_map.get_resolution() as f64;
	skinned_model_renderer.set_shadow_map(Some(shadow_map.get_depth_texture()), Some(&light_view_projection_elements), texel_size);
}
생성자constructorpub fn new(gl: &crate::GlContext, resolution: i32) -> Result<ShadowMap, String>#0.3.2 부터since 0.3.2소스source

생성. (깊이 텍스처 + 컬러 없는 프레임버퍼, 앞의 텍스처와 프레임버퍼 묶음은 돌린다)

  • 광원 행렬은 단위 행렬로 시작한다. (update_light_matrix 로 채운다)

Constructor. (depth texture + framebuffer without color, restores the previous texture and framebuffer bindings)

  • The light matrix starts as the identity matrix. (filled by update_light_matrix)
gl&crate::GlContext
GL 컨텍스트. (Graphic::get_gl 로 꺼낸다)GL context. (taken out with Graphic::get_gl)
resolutioni32
깊이 텍스처 한 변의 텍셀 수. (정사각형, 원본 기본값은 DEFAULT_SHADOWMAP_RESOLUTION = 2048)Number of texels per side of the depth texture. (square, the original default is DEFAULT_SHADOWMAP_RESOLUTION = 2048)

반환ReturnsResult<ShadowMap, String> 새 섀도우 맵. 텍스처나 프레임버퍼를 못 만들면 Err(GL 의 오류 글).New shadow map. Err(GL error message) if the texture or framebuffer cannot be created.

짝Counterpart: vanilla.js ShadowMap.constructor

메서드methodpub fn update_light_matrix(&mut self, focus_position: Vector3, light_direction: Vector3, extent: f64, near_distance: f64, far_distance: f64)#0.3.2 부터since 0.3.2소스source

광원 행렬 갱신. (초점 주변을 덮는 직교 투영, 텍셀 스냅, 빛이 거의 바로 위나 아래로 나아가면 위쪽을 z 축으로)

  • light_direction 은 빛이 나아가는 방향, extent 는 초점 기준 절반 커버 범위다.
  • 광원 눈은 초점에서 빛 반대쪽으로 (near_distance + far_distance) / 2 만큼 떨어지고, 위쪽은 Vector3::up() 이다. 빛 방향의 y 성분 절댓값이 0.99 를 넘으면(거의 바로 위나 아래로) 위쪽을 z 축(0, 0, 1)으로 바꾼다.

Updates the light matrix. (orthographic projection covering the area around the focus, texel snapping, the up direction becomes the z axis when the light travels almost straight up or down)

  • light_direction is the direction the light travels, extent is the half coverage range around the focus.
  • The light eye is placed (near_distance + far_distance) / 2 away from the focus on the side opposite the light, and up is Vector3::up(). If the absolute value of the y component of the light direction exceeds 0.99 (almost straight up or down), up is switched to the z axis (0, 0, 1).
focus_positionVector3
그림자를 덮을 가운데. (월드)Center of the shadow coverage. (world)
light_directionVector3
빛이 나아가는 방향. (월드, 길이는 상관없다, 안에서 정규화)Direction the light travels. (world, any length, normalized internally)
extentf64
초점에서 가로와 세로로 덮는 절반 범위. (월드 단위, 직교 상자는 -extent ~ extent)Half range covered horizontally and vertically from the focus. (world units, the orthographic box is -extent ~ extent)
near_distancef64
광원 직교 투영의 가까운 거리. (월드 단위)Near distance of the light's orthographic projection. (world units)
far_distancef64
광원 직교 투영의 먼 거리. (월드 단위)Far distance of the light's orthographic projection. (world units)

짝Counterpart: vanilla.js ShadowMap.updateLightMatrix

예제Example해가 비스듬히 비출 때 원점 둘레 반지름 4 를 덮기Cover a radius of 4 around the origin when the sun shines at an angle
use vanilla::{ShadowMap, Vector3};

fn aim_sun(shadow_map: &mut ShadowMap) {
	let sun_direction = Vector3::create(0.5, 0.8, 0.35).normalize();
	let light_travel_direction = sun_direction.multiply_scalar(-1.0);
	shadow_map.update_light_matrix(Vector3::zero(), light_travel_direction, 4.0, 0.5, 30.0);
}
메서드methodpub fn begin_render(&self, gl: &crate::GlContext)#0.3.2 부터since 0.3.2소스source

깊이 패스 시작. (프레임버퍼 바인드 + 뷰포트 + 깊이 클리어, ToonDrawQueue 가 캐시를 쓸 때는 구운 판에 그리거나 구운 판을 옮겨 그 위에 덧그린다)

  • 가위 시험을 끄고 깊이 시험과 깊이 쓰기를 켠다. 끝나면 부르는 쪽이 다음 패스의 프레임버퍼와 뷰포트를 다시 잡는다.

Starts the depth pass. (framebuffer bind + viewport + depth clear; when ToonDrawQueue uses the cache, it draws into the baked target or copies the baked target and draws over it)

  • Turns off the scissor test and turns on the depth test and depth writing. When done, the caller sets the next pass's framebuffer and viewport again.
gl&crate::GlContext
GL 컨텍스트.GL context.

짝Counterpart: vanilla.js ShadowMap.beginRender

메서드methodpub fn set_update_mode(&mut self, update_mode: ShadowUpdateMode, update_interval: u32)#0.4.0 부터since 0.4.0소스source

그림자를 다시 그리는 방식 정하기. (원본 setUpdateMode, ToonDrawQueue 가 따른다, 기본 ShadowUpdateMode::OnChange, 정하면 다음 그리기에서 전부 다시 그린다)

  • 원본의 updateInterval 기본값 인자 1 은 러스트에 기본값 인자가 없어 늘 준다. (Interval 이 아니면 쓰지 않는다)

Sets how the shadow is redrawn. (the original setUpdateMode, ToonDrawQueue follows it, default ShadowUpdateMode::OnChange, setting it redraws everything on the next draw)

  • Rust has no default arguments, so the original's default updateInterval argument 1 is always passed. (Unused unless Interval)
update_modeShadowUpdateMode
ShadowUpdateMode.
update_intervalu32
Interval 일 때 몇 프레임마다 그릴지. (1 보다 작으면 1)How many frames apart to draw for Interval. (1 if smaller than 1)

짝Counterpart: vanilla.js ShadowMap.setUpdateMode

예제Example그림자를 세 프레임마다 그리기Drawing the shadow every third frame
use vanilla::{GlContext, ShadowMap, ShadowUpdateMode};

fn draw_shadow_every_third_frame(gl: &GlContext) {
	let mut shadow_target = ShadowMap::new(gl, 1024).unwrap();
	shadow_target.set_update_mode(ShadowUpdateMode::Interval, 3);
	println!("{:?} {}", shadow_target.get_update_mode(), shadow_target.get_update_interval());
	shadow_target.set_update_mode(ShadowUpdateMode::EveryFrame, 1);
	shadow_target.destroy(gl);
}
메서드methodpub fn get_update_mode(&self) -> ShadowUpdateMode#0.4.0 부터since 0.4.0소스source

그림자를 다시 그리는 방식 반환. (원본 getUpdateMode)

Returns how the shadow is redrawn. (the original getUpdateMode)

반환ReturnsShadowUpdateMode ShadowUpdateMode. (기본 OnChange)ShadowUpdateMode. (default OnChange)

짝Counterpart: vanilla.js ShadowMap.getUpdateMode

메서드methodpub fn get_update_interval(&self) -> u32#0.4.0 부터since 0.4.0소스source

Interval 의 프레임 수 반환. (원본 getUpdateInterval)

Returns the frame count for Interval. (the original getUpdateInterval)

반환Returnsu32 몇 프레임마다 그리는지. (1 이상, 기본 1)How many frames apart it draws. (1 or more, default 1)

짝Counterpart: vanilla.js ShadowMap.getUpdateInterval

메서드methodpub fn request_update(&mut self)#0.4.0 부터since 0.4.0소스source

다음 그리기에서 전부 다시 그리게 하기. (원본 requestUpdate, 드리우개 기록이 못 보는 바뀜, 예를 들어 모형의 꼭짓점을 고쳤을 때)

Makes the next draw redraw everything. (the original requestUpdate, for changes the caster records cannot see, for example when a mesh's vertices were edited)

짝Counterpart: vanilla.js ShadowMap.requestUpdate

메서드methodpub fn get_framebuffer(&self) -> GlFramebuffer#0.3.2 부터since 0.3.2소스source

프레임버퍼 반환.

Returns the framebuffer.

반환ReturnsGlFramebuffer 깊이 전용 프레임버퍼. (컬러 어태치먼트 없음)Depth-only framebuffer. (no color attachment)

짝Counterpart: vanilla.js ShadowMap.getFramebuffer

메서드methodpub fn get_depth_texture(&self) -> GlTexture#0.3.2 부터since 0.3.2소스source

깊이 텍스처 반환.

Returns the depth texture.

반환ReturnsGlTexture 비교 샘플링(sampler2DShadow)용 깊이 텍스처. (DEPTH_COMPONENT24)Depth texture for comparison sampling (sampler2DShadow). (DEPTH_COMPONENT24)

짝Counterpart: vanilla.js ShadowMap.getDepthTexture

메서드methodpub fn get_resolution(&self) -> i32#0.3.2 부터since 0.3.2소스source

해상도 반환.

Returns the resolution.

반환Returnsi32 깊이 텍스처 한 변의 텍셀 수.Number of texels per side of the depth texture.

짝Counterpart: vanilla.js ShadowMap.getResolution

메서드methodpub fn get_light_view_projection_matrix(&self) -> &Matrix4#0.3.2 부터since 0.3.2소스source

광원 뷰 투영 행렬 반환.

Returns the light view-projection matrix.

반환Returns&Matrix4 광원 뷰 투영 행렬. (월드 → 광원 클립, update_light_matrix 전에는 단위 행렬)Light view-projection matrix. (world → light clip, identity before update_light_matrix)

짝Counterpart: vanilla.js ShadowMap.getLightViewProjectionMatrix

메서드methodpub fn set_bias(&mut self, depth_bias: f64, normal_bias: f64)#0.4.0 부터since 0.4.0소스source

그림자 치우침 정하기. (그림자 텍셀 단위, 기본 깊이 1, 노멀 1, 받는 쪽이 읽을 때 쓴다)

  • 텍셀 하나의 월드 크기(빛 행렬의 가로 폭 / 해상도)를 곱해 월드 거리로 바꾸므로 extent 와 해상도가 바뀌어도 같은 몫으로 걸린다. (유니티 URP 의 Depth Bias, Normal Bias 와 같은 단위)
  • 깊이 치우침은 빛 쪽으로 견줄 깊이를 당긴다. 노멀 치우침은 받는 점을 면의 노멀 쪽으로 밀어 읽는다. 둘 다 3x3 PCF 의 반지름 1.5 텍셀을 곱한다.
  • ToonRenderer 는 여기에 기울기 비례 치우침(빛과 면이 스칠수록 커짐, 텍셀 2.5 x 기울기, 기울기는 10 까지)을 더한다.
  • 줄이면 그림자가 붙고 제 그림자 여드름이 생기기 쉽다. 늘리면 여드름은 없어지고 그림자가 떠 보인다(피터 패닝).

Sets the shadow bias. (in shadow texels, default depth 1, normal 1, applied by the receiver when it reads the shadow)

  • It is multiplied by the world size of one texel (light matrix width / resolution), so the same amount applies when the extent or resolution changes. (the same units as Depth Bias and Normal Bias in Unity URP)
  • Depth bias pulls the compared depth toward the light. Normal bias pushes the receiving point along the surface normal before reading. Both are multiplied by the 1.5 texel radius of the 3x3 PCF.
  • ToonRenderer adds a slope-scaled bias on top (grows as the light grazes the surface, 2.5 texels x slope, slope clamped at 10).
  • Lower values keep shadows attached but invite self-shadow acne. Higher values remove acne but make shadows look detached (peter panning).
depth_biasf64
깊이 치우침. (텍셀 단위, 0 이상)Depth bias. (in shadow texels, 0 or more)
normal_biasf64
노멀 치우침. (텍셀 단위, 0 이상)Normal bias. (in shadow texels, 0 or more)

짝Counterpart: vanilla.js ShadowMap.setBias

예제Example텍셀 단위로 그림자 치우침 정하기Setting the shadow bias in texels
use vanilla::{GlContext, ShadowMap, Vector3};

fn soften_shadow(gl: &GlContext) {
	let mut shadow_map = ShadowMap::new(gl, 1024).unwrap();
	shadow_map.update_light_matrix(Vector3::create(0.0, 0.0, 0.0), Vector3::create(-0.3, -1.0, -0.2), 20.0, 1.0, 100.0);
	shadow_map.set_bias(0.5, 1.5);
	println!("{} {}", shadow_map.get_depth_bias(), shadow_map.get_normal_bias());
	shadow_map.destroy(gl);
}
메서드methodpub fn get_depth_bias(&self) -> f64#0.4.0 부터since 0.4.0소스source

깊이 치우침 반환.

Returns the depth bias.

반환Returnsf64 깊이 치우침. (그림자 텍셀 단위, 기본 1)Depth bias. (in shadow texels, default 1)

짝Counterpart: vanilla.js ShadowMap.getDepthBias

메서드methodpub fn get_normal_bias(&self) -> f64#0.4.0 부터since 0.4.0소스source

노멀 치우침 반환.

Returns the normal bias.

반환Returnsf64 노멀 치우침. (그림자 텍셀 단위, 기본 1)Normal bias. (in shadow texels, default 1)

짝Counterpart: vanilla.js ShadowMap.getNormalBias

메서드methodpub fn set_focus_step(&mut self, world_step: f64)#0.4.0 부터since 0.4.0소스source

초점을 끊어 옮기는 월드 칸 정하기. (해 그림자 캐시용, 기본 0 은 끊지 않고 텍셀 맞춤만)

  • 카메라를 따라 초점이 움직이면 텍셀 하나만 넘어도 빛 행렬이 바뀌어 ShadowUpdateMode::OnChange 캐시가 프레임마다 다시 그린다.
  • 칸을 주면 초점을 월드 칸(x, y, z 각각)의 배수에 맞춰 옮겨, 한 칸 안에서는 행렬이 같아 구운 판을 다시 쓴다. 덮는 너비와 깊이에 칸만큼 여유를 더해 초점 둘레가 판 밖으로 나가지 않는다.
  • 유니티와 언리얼의 캐시드 섀도, 가상 섀도 맵의 고정 칸에 초점을 붙이는 꼴과 같은 생각이다. (원문은 읽지 못해 짐작)
  • 텍셀 맞춤은 그 위에 그대로 걸린다. 여유가 늘어 텍셀 하나의 월드 크기는 조금 커진다.

Set the world step the focus moves in. (for the sun shadow cache, the default 0 does not snap and only snaps to texels)

  • When the focus follows a camera, passing a single texel changes the light matrix, so the ShadowUpdateMode::OnChange cache redraws every frame.
  • With a step, the focus is moved to multiples of the world step on each of x, y and z, so the matrix stays the same inside one cell and the baked map is reused. The covered width and depth get the step as margin so the area around the focus never leaves the map.
  • The same idea as the fixed-cell focus snapping of the cached shadows and virtual shadow maps in Unity and Unreal. (guessed, the sources were not read)
  • Texel snapping still applies on top. With the margin, one texel covers a slightly larger world size.
world_stepf64
월드 칸. (월드 단위, 0 이하면 끔)World step. (in world units, 0 or less turns it off)

짝Counterpart: vanilla.js ShadowMap.setFocusStep

예제Example초점을 1 미터 칸으로 끊어 옮기기Moving the focus in one meter steps
use vanilla::{GlContext, ShadowMap, Vector3};

fn snap_focus(gl: &GlContext) {
	let mut shadow_map = ShadowMap::new(gl, 1024).unwrap();
	shadow_map.set_focus_step(1.0);
	shadow_map.update_light_matrix(Vector3::create(0.2, 0.0, 0.0), Vector3::create(-0.4, -1.0, -0.3), 20.0, 0.5, 100.0);
	println!("{}", shadow_map.get_focus_step());
	shadow_map.destroy(gl);
}
메서드methodpub fn get_focus_step(&self) -> f64#0.4.0 부터since 0.4.0소스source

초점을 끊어 옮기는 월드 칸 반환.

Return the world step the focus moves in.

반환Returnsf64 월드 칸. (0 이면 끔)World step. (0 means off)

짝Counterpart: vanilla.js ShadowMap.getFocusStep

메서드methodpub fn destroy(&self, gl: &crate::GlContext)#0.3.2 부터since 0.3.2소스source

파괴. (GL 리소스 해제, 프레임버퍼와 깊이 텍스처, 구운 판을 지운다)

Destroy. (Releases GL resources, deletes the framebuffer, the depth texture and the baked target)

gl&crate::GlContext
만들 때 쓴 GL 컨텍스트.GL context used at creation.

짝Counterpart: vanilla.js ShadowMap.destroy

ShadowAtlasLightstruct traits Clone, Copy, Debug, PartialEq

소스source

그림자 아틀라스의 빛 하나. (셰이더에 올릴 값)

One light of the shadow atlas. (Values to upload to the shader)

예제Example아틀라스가 고른 빛과 그 첫 칸 읽기Read the lights the atlas picked and their first tiles
use vanilla::ShadowAtlas;

fn print_shadow_lights(shadow_atlas: &ShadowAtlas) {
	for light in shadow_atlas.get_lights() {
		let tile_count = if light.tangent > 0.0 {
			1
		}
		else {
			6
		};
		println!("light {} uses tiles {}..{}", light.light_index, light.first_tile, light.first_tile + tile_count);
	}
}
필드fieldpub light_index: usize#0.4.0 부터since 0.4.0소스source

빛 목록에서의 차례. (ToonRenderer 가 그 점광에 이 그림자를 붙인다)

Order in the light list. (ToonRenderer attaches this shadow to that point light)

반환Returnsusize

필드fieldpub position: [f64; 3]#0.4.0 부터since 0.4.0소스source

빛의 자리.

Light position.

반환Returns[f64; 3]

필드fieldpub forward: [f64; 3]#0.4.0 부터since 0.4.0소스source

보는 쪽. (스포트라이트만)

Forward direction. (Spotlights only)

반환Returns[f64; 3]

필드fieldpub up: [f64; 3]#0.4.0 부터since 0.4.0소스source

위쪽. (스포트라이트만)

Up direction. (Spotlights only)

반환Returns[f64; 3]

필드fieldpub tangent: f64#0.4.0 부터since 0.4.0소스source

반각의 탄젠트. (0 이면 점광)

Tangent of the half angle. (0 for a point light)

반환Returnsf64

필드fieldpub near: f64#0.4.0 부터since 0.4.0소스source

가까운 거리.

Near distance.

반환Returnsf64

필드fieldpub far: f64#0.4.0 부터since 0.4.0소스source

먼 거리.

Far distance.

반환Returnsf64

필드fieldpub first_tile: usize#0.4.0 부터since 0.4.0소스source

첫 칸 번호.

First tile number.

반환Returnsusize

ShadowAtlasTilestruct traits Clone, Copy, Debug

소스source

그림자 아틀라스의 칸 하나.

One tile of the shadow atlas.

예제Example칸마다 뷰포트 자리 읽기Read the viewport position of each tile
use vanilla::ShadowAtlas;

fn print_tiles(shadow_atlas: &ShadowAtlas) {
	for tile_index in 0..shadow_atlas.get_tile_count() {
		let tile = shadow_atlas.get_tile(tile_index);
		println!("tile {} at ({}, {}) size {}", tile_index, tile.x, tile.y, tile.size);
	}
}
필드fieldpub view_projection_matrix: Matrix4#0.4.0 부터since 0.4.0소스source

칸의 보기와 투영.

View and projection of the tile.

반환ReturnsMatrix4

필드fieldpub x: i32#0.4.0 부터since 0.4.0소스source

칸의 왼쪽 아래 x. (픽셀)

Bottom-left x of the tile. (Pixels)

반환Returnsi32

필드fieldpub y: i32#0.4.0 부터since 0.4.0소스source

칸의 왼쪽 아래 y. (픽셀)

Bottom-left y of the tile. (Pixels)

반환Returnsi32

필드fieldpub size: i32#0.4.0 부터since 0.4.0소스source

칸 한 변. (픽셀)

Side of a tile. (Pixels)

반환Returnsi32

ShadowAtlasLightSourcestruct traits Clone, Copy, Debug, PartialEq

소스source

그림자 아틀라스가 받는 빛 꼴. (원본 updateLights 의 객체 하나, ToonPointLight 에서 짓는다)

Light description the shadow atlas takes. (One object of the original updateLights, built from ToonPointLight)

예제Example점광 하나와 스포트라이트 하나One point light and one spotlight
use vanilla::ShadowAtlasLightSource;

let point_light = ShadowAtlasLightSource {
	position: [0.0, 2.0, 0.0],
	direction: None,
	outer_cone_angle: 0.0,
	range: 10.0,
	shadow_near: 0.05,
	casts_shadow: true,
};
let spot_light = ShadowAtlasLightSource {
	position: [3.0, 4.0, 0.0],
	direction: Some([0.0, -1.0, 0.0]),
	outer_cone_angle: std::f64::consts::FRAC_PI_4,
	..point_light
};
assert!(point_light.direction.is_none());
assert!(spot_light.direction.is_some());
필드fieldpub position: [f64; 3]#0.4.0 부터since 0.4.0소스source

빛의 자리.

Light position.

반환Returns[f64; 3]

필드fieldpub direction: Option<[f64; 3]>#0.4.0 부터since 0.4.0소스source

빛이 나아가는 쪽. (Some 이면 스포트라이트)

Direction the light travels. (spotlight if Some)

반환ReturnsOption<[f64; 3]>

필드fieldpub outer_cone_angle: f64#0.4.0 부터since 0.4.0소스source

스포트라이트 바깥 원뿔 반각. (라디안)

Outer cone half angle of the spotlight. (Radians)

반환Returnsf64

필드fieldpub range: f64#0.4.0 부터since 0.4.0소스source

먼 거리. (0 이면 30)

Far distance. (30 if 0)

반환Returnsf64

필드fieldpub shadow_near: f64#0.4.0 부터since 0.4.0소스source

가까운 거리.

Near distance.

반환Returnsf64

필드fieldpub casts_shadow: bool#0.4.0 부터since 0.4.0소스source

그림자를 드리울지.

Whether it casts a shadow.

반환Returnsbool

ShadowAtlasstruct

짝Counterpart: vanilla.js ShadowAtlas소스source

그림자 아틀라스. (점광과 스포트라이트의 실시간 그림자를 깊이 텍스처 한 장에 칸으로 나눠 담는다, 원본 ShadowAtlas)

  • 스포트라이트는 원근 그림자 맵 한 칸, 점광은 큐브 여섯 면을 칸 여섯에 (면마다 90 도 원근) 그린다.
  • update_lights(빛 목록) 이 casts_shadow 가 true 인 빛을 SHADOW_ATLAS_MAXIMUM_LIGHTS 까지 골라 칸을 나누고 칸마다 보기와 투영을 셈한다.
  • 칸은 한 변 grid_size 의 격자다. (grid_size = 올림(칸 수의 제곱근), 칸 한 변 = 내림(해상도 / grid_size))
  • 그리기: begin_render 로 판을 비우고, 칸마다 begin_tile 로 뷰포트를 건 뒤 그 칸의 보기와 투영으로 깊이를 그린다. (ToonRenderer::begin_shadow_atlas_pass, set_shadow_atlas_tile)

Shadow atlas. (Stores real-time shadows of point lights and spotlights as tiles in one depth texture, the original ShadowAtlas)

  • A spotlight is drawn into one perspective shadow map tile, a point light draws the six cube faces into six tiles (90 degree perspective per face).
  • update_lights(light list) picks lights with casts_shadow true up to SHADOW_ATLAS_MAXIMUM_LIGHTS, divides the tiles and computes view and projection per tile.
  • Tiles form a grid of grid_size per side. (grid_size = ceil(square root of the tile count), tile side = floor(resolution / grid_size))
  • Drawing: begin_render clears the target, then per tile begin_tile sets the viewport and depth is drawn with that tile's view and projection. (ToonRenderer::begin_shadow_atlas_pass, set_shadow_atlas_tile)
예제Example빛 목록으로 칸을 나누고 칸마다 깊이 그리기Divide tiles from the light list and draw depth per tile
use vanilla::{ShadowAtlas, ShadowAtlasLightSource};

fn render_shadows(gl: &vanilla::GlContext, shadow_atlas: &mut ShadowAtlas, light_source_list: &[ShadowAtlasLightSource]) {
	shadow_atlas.update_lights(light_source_list);
	shadow_atlas.begin_render(gl);
	for tile_index in 0..shadow_atlas.get_tile_count() {
		shadow_atlas.begin_tile(gl, tile_index);
		let _view_projection_matrix = shadow_atlas.get_tile(tile_index).view_projection_matrix;
	}
}
생성자constructorpub fn new(gl: &crate::GlContext, resolution: i32, tile_resolution: i32) -> Result<ShadowAtlas, String>#0.4.0 부터since 0.4.0소스source

생성. (깊이 텍스처와 컬러 없는 프레임버퍼, 앞의 묶음은 돌린다)

  • 칸이 없는 상태로 시작한다. (격자 한 변 1, 칸 한 변은 해상도, update_lights 로 나눈다)
  • resolution 은 아틀라스 한 변, tile_resolution 은 칸마다 바라는 한 변이다. (원본 기본값은 DEFAULT_SHADOW_ATLAS_RESOLUTION, DEFAULT_SHADOW_ATLAS_TILE_RESOLUTION)

Constructor. (Depth texture and framebuffer without color, restores the previous bindings)

  • Starts with no tiles. (Grid side 1, tile side equal to the resolution, divided by update_lights)
  • resolution is the side of the atlas, and tile_resolution is the side each tile asks for. (the original defaults are DEFAULT_SHADOW_ATLAS_RESOLUTION, DEFAULT_SHADOW_ATLAS_TILE_RESOLUTION)
gl&crate::GlContext
GL 컨텍스트.GL context.
resolutioni32
깊이 텍스처 한 변의 텍셀 수. (정사각형)Number of texels per side of the depth texture. (Square)
tile_resolutioni32
칸마다 바라는 한 변. (픽셀, 1 ~ resolution 으로 자르고, 다 들어가지 않으면 반씩 줄인다)Side each tile asks for. (Pixels, clamped to 1 ~ resolution, halved until the tiles fit)

반환ReturnsResult<ShadowAtlas, String> 새 그림자 아틀라스. 텍스처나 프레임버퍼를 못 만들면 Err(GL 의 오류 글).New shadow atlas. Err(GL error message) if the texture or framebuffer cannot be created.

짝Counterpart: vanilla.js ShadowAtlas.constructor

메서드methodpub fn update_lights(&mut self, light_source_list: &[ShadowAtlasLightSource])#0.4.0 부터since 0.4.0소스source

빛 목록으로 칸 나누기. (casts_shadow 가 true 인 것을 SHADOW_ATLAS_MAXIMUM_LIGHTS 까지, 스포트라이트 한 칸, 점광 여섯 칸)

  • 가까운 거리는 0.001 아래로, 먼 거리는 가까운 거리 + 0.01 아래로 내려가지 않는다. (range 가 0 이하면 30)
  • 스포트라이트의 원근 반각은 바깥 원뿔 반각(0.01 이상)에 0.05 라디안을 더하고 1.45 라디안에서 자른다.

Divides tiles from the light list. (Ones with casts_shadow true up to SHADOW_ATLAS_MAXIMUM_LIGHTS, one tile per spotlight, six per point light)

  • The near distance does not go below 0.001, and the far distance does not go below the near distance + 0.01. (30 if range is 0 or less)
  • The perspective half angle of a spotlight is the outer cone half angle (at least 0.01) plus 0.05 radians, clamped at 1.45 radians.
light_source_list&[ShadowAtlasLightSource]
빛 목록. (차례가 ShadowAtlasLight::light_index 가 된다, ToonLightSet::read_shadow_light_sources 로 짓는다)Light list. (The order becomes ShadowAtlasLight::light_index, built with ToonLightSet::read_shadow_light_sources)

짝Counterpart: vanilla.js ShadowAtlas.updateLights

메서드methodpub fn begin_render(&self, gl: &crate::GlContext)#0.4.0 부터since 0.4.0소스source

깊이 패스 시작. (프레임버퍼를 묶고 판 전체를 비운다, 칸마다 begin_tile, ToonDrawQueue 가 캐시를 쓸 때는 구운 판에 그리거나 구운 판을 옮겨 그 위에 덧그린다)

  • 뷰포트를 판 전체로, 가위 시험을 끄고, 깊이 시험과 깊이 쓰기를 켠다.

Begins the depth pass. (Binds the framebuffer and clears the whole target, begin_tile per tile; when ToonDrawQueue uses the cache, it draws into the baked target or copies the baked target and draws over it)

  • Sets the viewport to the whole target, turns off the scissor test, and turns on the depth test and depth writes.
gl&crate::GlContext
GL 컨텍스트.GL context.

짝Counterpart: vanilla.js ShadowAtlas.beginRender

메서드methodpub fn set_update_mode(&mut self, update_mode: ShadowUpdateMode, update_interval: u32)#0.4.0 부터since 0.4.0소스source

그림자를 다시 그리는 방식 정하기. (원본 setUpdateMode, ToonDrawQueue 가 따른다, 기본 ShadowUpdateMode::OnChange, 정하면 다음 그리기에서 전부 다시 그린다)

  • 원본의 updateInterval 기본값 인자 1 은 러스트에 기본값 인자가 없어 늘 준다. (Interval 이 아니면 쓰지 않는다)

Sets how the shadow is redrawn. (the original setUpdateMode, ToonDrawQueue follows it, default ShadowUpdateMode::OnChange, setting it redraws everything on the next draw)

  • Rust has no default arguments, so the original's default updateInterval argument 1 is always passed. (Unused unless Interval)
update_modeShadowUpdateMode
ShadowUpdateMode.
update_intervalu32
Interval 일 때 몇 프레임마다 그릴지. (1 보다 작으면 1)How many frames apart to draw for Interval. (1 if smaller than 1)

짝Counterpart: vanilla.js ShadowAtlas.setUpdateMode

예제Example그림자를 세 프레임마다 그리기Drawing the shadow every third frame
use vanilla::{GlContext, ShadowAtlas, ShadowUpdateMode, DEFAULT_SHADOW_ATLAS_TILE_RESOLUTION};

fn draw_shadow_every_third_frame(gl: &GlContext) {
	let mut shadow_target = ShadowAtlas::new(gl, 1024, DEFAULT_SHADOW_ATLAS_TILE_RESOLUTION).unwrap();
	shadow_target.set_update_mode(ShadowUpdateMode::Interval, 3);
	println!("{:?} {}", shadow_target.get_update_mode(), shadow_target.get_update_interval());
	shadow_target.set_update_mode(ShadowUpdateMode::EveryFrame, 1);
	shadow_target.destroy(gl);
}
메서드methodpub fn get_update_mode(&self) -> ShadowUpdateMode#0.4.0 부터since 0.4.0소스source

그림자를 다시 그리는 방식 반환. (원본 getUpdateMode)

Returns how the shadow is redrawn. (the original getUpdateMode)

반환ReturnsShadowUpdateMode ShadowUpdateMode. (기본 OnChange)ShadowUpdateMode. (default OnChange)

짝Counterpart: vanilla.js ShadowAtlas.getUpdateMode

메서드methodpub fn get_update_interval(&self) -> u32#0.4.0 부터since 0.4.0소스source

Interval 의 프레임 수 반환. (원본 getUpdateInterval)

Returns the frame count for Interval. (the original getUpdateInterval)

반환Returnsu32 몇 프레임마다 그리는지. (1 이상, 기본 1)How many frames apart it draws. (1 or more, default 1)

짝Counterpart: vanilla.js ShadowAtlas.getUpdateInterval

메서드methodpub fn request_update(&mut self)#0.4.0 부터since 0.4.0소스source

다음 그리기에서 전부 다시 그리게 하기. (원본 requestUpdate, 드리우개 기록이 못 보는 바뀜, 예를 들어 모형의 꼭짓점을 고쳤을 때)

Makes the next draw redraw everything. (the original requestUpdate, for changes the caster records cannot see, for example when a mesh's vertices were edited)

짝Counterpart: vanilla.js ShadowAtlas.requestUpdate

메서드methodpub fn begin_tile(&self, gl: &crate::GlContext, tile_index: usize)#0.4.0 부터since 0.4.0소스source

칸 하나에 뷰포트 걸기.

Set the viewport to one tile.

gl&crate::GlContext
GL 컨텍스트.GL context.
tile_indexusize
칸 번호. (0 ~ get_tile_count() - 1, 밖이면 패닉)Tile number. (0 ~ get_tile_count() - 1, panics if out of range)

짝Counterpart: vanilla.js ShadowAtlas.beginTile

메서드methodpub fn get_lights(&self) -> &[ShadowAtlasLight]#0.4.0 부터since 0.4.0소스source

그림자를 받는 빛 반환.

Returns the lights whose shadows are received.

반환Returns&[ShadowAtlasLight] 마지막 update_lights 가 고른 빛 목록. (SHADOW_ATLAS_MAXIMUM_LIGHTS 개까지)List of lights picked by the last update_lights. (Up to SHADOW_ATLAS_MAXIMUM_LIGHTS)

짝Counterpart: vanilla.js ShadowAtlas.getLights

메서드methodpub fn get_light_count(&self) -> usize#0.4.0 부터since 0.4.0소스source

그림자를 받는 빛 개수 반환. (원본 getLightCount, get_lights 의 길이)

Returns the number of shadow-casting lights. (the original getLightCount, the length of get_lights)

반환Returnsusize 마지막 update_lights 가 고른 빛 개수. (0 ~ SHADOW_ATLAS_MAXIMUM_LIGHTS)Number of lights the last update_lights picked. (0 ~ SHADOW_ATLAS_MAXIMUM_LIGHTS)

짝Counterpart: vanilla.js ShadowAtlas.getLightCount

예제Example
use vanilla::ShadowAtlas;

fn has_shadow_lights(shadow_atlas: &ShadowAtlas) -> bool {
	shadow_atlas.get_light_count() > 0
}
메서드methodpub fn get_tile_resolution(&self) -> i32#0.4.0 부터since 0.4.0소스source

칸마다 바라는 한 변 반환. (픽셀, 생성 때 준 값)

Returns the side each tile asks for. (pixels, the value given at creation)

반환Returnsi32 칸마다 바라는 한 변. (픽셀)Side each tile asks for. (Pixels)

짝Counterpart: vanilla.js ShadowAtlas.getTileResolution

메서드methodpub fn get_tile_count(&self) -> usize#0.4.0 부터since 0.4.0소스source

칸 수 반환.

Return the tile count.

반환Returnsusize 칸 수. (스포트라이트 1, 점광 6 씩 더한 것)Tile count. (1 per spotlight plus 6 per point light)

짝Counterpart: vanilla.js ShadowAtlas.getTileCount

메서드methodpub fn get_tile(&self, tile_index: usize) -> &ShadowAtlasTile#0.4.0 부터since 0.4.0소스source

칸 반환.

Return a tile.

tile_indexusize
칸 번호. (0 ~ get_tile_count() - 1, 밖이면 패닉)Tile number. (0 ~ get_tile_count() - 1, panics if out of range)

반환Returns&ShadowAtlasTile 그 칸의 보기와 투영, 자리, 크기.The tile's view and projection, position and size.

짝Counterpart: vanilla.js ShadowAtlas.getTile

메서드methodpub fn get_grid_size(&self) -> i32#0.4.0 부터since 0.4.0소스source

격자 한 변의 칸 수 반환.

Return the number of tiles per side of the grid.

반환Returnsi32 격자 한 변의 칸 수.Number of tiles per side of the grid.

짝Counterpart: vanilla.js ShadowAtlas.getGridSize

메서드methodpub fn get_tile_size(&self) -> i32#0.4.0 부터since 0.4.0소스source

칸 한 변 반환. (픽셀)

Return the side of a tile. (Pixels)

반환Returnsi32 칸 한 변. (픽셀)Side of a tile. (Pixels)

짝Counterpart: vanilla.js ShadowAtlas.getTileSize

메서드methodpub fn get_resolution(&self) -> i32#0.4.0 부터since 0.4.0소스source

해상도 반환.

Returns the resolution.

반환Returnsi32 깊이 텍스처 한 변의 텍셀 수.Number of texels per side of the depth texture.

짝Counterpart: vanilla.js ShadowAtlas.getResolution

메서드methodpub fn get_depth_texture(&self) -> GlTexture#0.4.0 부터since 0.4.0소스source

깊이 텍스처 반환. (비교 샘플링 sampler2DShadow)

Return the depth texture. (Comparison sampling with sampler2DShadow)

반환ReturnsGlTexture 아틀라스 깊이 텍스처의 GL 손잡이.GL handle of the atlas depth texture.

짝Counterpart: vanilla.js ShadowAtlas.getDepthTexture

메서드methodpub fn get_framebuffer(&self) -> GlFramebuffer#0.4.0 부터since 0.4.0소스source

프레임버퍼 반환.

Returns the framebuffer.

반환ReturnsGlFramebuffer 깊이만 붙은 프레임버퍼의 GL 손잡이.GL handle of the depth-only framebuffer.

짝Counterpart: vanilla.js ShadowAtlas.getFramebuffer

메서드methodpub fn destroy(&self, gl: &crate::GlContext)#0.4.0 부터since 0.4.0소스source

파괴. (GL 리소스 해제, 프레임버퍼와 깊이 텍스처, 구운 판을 지운다)

Destroy. (Releases GL resources, deletes the framebuffer, the depth texture and the baked target)

gl&crate::GlContext
이 아틀라스를 지은 GL 컨텍스트.GL context this atlas was built in.

짝Counterpart: vanilla.js ShadowAtlas.destroy

상수Constants

상수constantpub const DEFAULT_SHADOWMAP_RESOLUTION: i32 = 2048#0.3.2 부터since 0.3.2소스source

해상도 기본값. (원본 생성자 기본 인자)

Default resolution. (the original constructor's default argument)

반환Returnsi32

상수constantpub const DEFAULT_SHADOW_ATLAS_RESOLUTION: i32 = 2048#0.4.0 부터since 0.4.0소스source

그림자 아틀라스 한 변의 기본값. (원본 ShadowAtlas 의 기본값 인자, 유니티 URP 의 추가 빛 그림자 아틀라스 기본 2048)

Default side of the shadow atlas. (the original ShadowAtlas default argument, Unity URP's additional light shadow atlas default 2048)

반환Returnsi32

상수constantpub const DEFAULT_SHADOW_ATLAS_TILE_RESOLUTION: i32 = 1024#0.4.0 부터since 0.4.0소스source

그림자 아틀라스 칸마다 바라는 한 변의 기본값. (원본 ShadowAtlas 의 기본값 인자, 유니티 URP 의 추가 빛 그림자 해상도 단계 High 기본 1024, 빛의 기본 단계가 High)

Default side each shadow atlas tile asks for. (the original ShadowAtlas default argument, Unity URP's additional light shadow resolution tier High default 1024, the light's default tier is High)

반환Returnsi32

상수constantpub const SHADOW_ATLAS_MAXIMUM_LIGHTS: usize = 4#0.4.0 부터since 0.4.0소스source

그림자 아틀라스가 받는 점광과 스포트라이트 수의 상한. (셰이더의 유니폼 배열 크기)

Upper limit of point lights and spotlights the shadow atlas receives. (Size of the uniform arrays in the shader)

반환Returnsusize

짝Counterpart: vanilla.js SHADOW_ATLAS_MAXIMUM_LIGHTS

ShadowUpdateModeenum traits Clone, Copy, Debug, Default, PartialEq, Eq, Hash

짝Counterpart: vanilla.js ShadowUpdateMode소스source

그림자 깊이를 다시 그리는 방식. (원본 ShadowUpdateMode, ShadowMap 과 ShadowAtlas 의 set_update_mode, ToonDrawQueue::draw_shadows 와 draw_local_shadows 가 따른다)

  • EveryFrame: 매 프레임 드리우개 전부를 다시 그린다.
  • OnChange: 빛과 드리우개가 그대로면 다시 그리지 않는다. 오래 그대로인 드리우개는 따로 구워 두고, 움직이는 것만 매 프레임 그 위에 덧그린다. (기본, 화면은 매 프레임 그린 것과 같다)
  • Interval: N 프레임마다 한 번 전부 다시 그린다. (사이의 프레임은 앞의 그림자를 그대로 써서, 움직이는 것의 그림자가 늦게 따라온다)

How shadow depth is redrawn. (the original ShadowUpdateMode, followed by set_update_mode of ShadowMap and ShadowAtlas and by ToonDrawQueue::draw_shadows and draw_local_shadows)

  • EveryFrame: redraws every caster every frame.
  • OnChange: does not redraw when the lights and casters are unchanged. Casters that stay unchanged for a long time are baked separately, and only the moving ones are drawn over them every frame. (default, the screen is the same as drawing every frame)
  • Interval: redraws everything once every N frames. (Frames in between reuse the previous shadow, so the shadow of moving things follows late)
예제Example해 그림자는 바뀔 때만, 점광 그림자는 네 프레임마다Sun shadow only on change, point light shadow every four frames
use vanilla::{GlContext, ShadowAtlas, ShadowMap, ShadowUpdateMode, DEFAULT_SHADOW_ATLAS_TILE_RESOLUTION};

fn choose_shadow_updates(gl: &GlContext) {
	let mut shadow_map = ShadowMap::new(gl, 1024).unwrap();
	shadow_map.set_update_mode(ShadowUpdateMode::OnChange, 1);
	let mut shadow_atlas = ShadowAtlas::new(gl, 1024, DEFAULT_SHADOW_ATLAS_TILE_RESOLUTION).unwrap();
	shadow_atlas.set_update_mode(ShadowUpdateMode::Interval, 4);
	println!("{:?} {:?} {}", shadow_map.get_update_mode(), shadow_atlas.get_update_mode(), shadow_atlas.get_update_interval());
	shadow_map.destroy(gl);
	shadow_atlas.destroy(gl);
}
이름Name설명Description
EveryFrame매 프레임 전부.Everything every frame.
OnChange바뀔 때만. (기본)Only on change. (default)
IntervalN 프레임마다.Every N frames.